diff --git a/Cargo.lock b/Cargo.lock index bb6eb1f8..c733e929 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6057,6 +6057,7 @@ dependencies = [ "nohash-hasher", "once_cell", "petgraph", + "recursive", "reqsign", "reqwest 0.12.28", "rquickjs", diff --git a/core/engine/Cargo.toml b/core/engine/Cargo.toml index 033e03d3..c40f13ad 100644 --- a/core/engine/Cargo.toml +++ b/core/engine/Cargo.toml @@ -50,6 +50,7 @@ toml = "0.8" mimalloc = "0.1.52" [target.'cfg(not(target_family = "wasm"))'.dependencies] +recursive = { workspace = true } async-trait = { version = "0.1" } http = { version = "1.3" } reqwest = { version = "0.12", features = ["json", "rustls-tls"], default-features = false } @@ -67,5 +68,22 @@ name = "engine" [features] default = [] +driver = [] bindgen = ["rquickjs/bindgen"] -arbitrary_precision = ["serde_json/arbitrary_precision", "zen-expression/arbitrary_precision", "zen-types/arbitrary_precision", "zen-tmpl/arbitrary_precision"] \ No newline at end of file +arbitrary_precision = ["serde_json/arbitrary_precision", "zen-expression/arbitrary_precision", "zen-types/arbitrary_precision", "zen-tmpl/arbitrary_precision"] + +[[test]] +name = "golden" +required-features = ["arbitrary_precision"] + +[[test]] +name = "ceiling_lists" +required-features = ["driver"] + +[[test]] +name = "ceiling_switch" +required-features = ["driver"] + +[[test]] +name = "ceiling_table" +required-features = ["driver"] diff --git a/core/engine/clippy.toml b/core/engine/clippy.toml new file mode 100644 index 00000000..3a17528e --- /dev/null +++ b/core/engine/clippy.toml @@ -0,0 +1,11 @@ +disallowed-types = [ + { path = "zen_expression::Isolate", reason = "default builds evaluate policies and graphs on the lane Session; the stack VM Isolate is driver-only" }, + { path = "zen_expression::OpcodeCache", reason = "lane Programs replace the stack VM opcode cache outside the driver feature" }, +] +disallowed-methods = [ + { path = "zen_expression::Isolate::run_standard", reason = "use lane::Session::run_standard" }, + { path = "zen_expression::Isolate::run_unary", reason = "use lane::Session::run_unary" }, + { path = "zen_expression::Isolate::set_reference", reason = "use lane::Session::set_reference" }, + { path = "zen_expression::Isolate::compile_standard", reason = "use lane::LaneProgram::compile_exact" }, + { path = "zen_expression::Isolate::compile_unary", reason = "use lane::LaneProgram::compile_exact" }, +] diff --git a/core/engine/src/analysis/table/constraints.rs b/core/engine/src/analysis/table/constraints.rs index 51c8bd74..810d0e16 100644 --- a/core/engine/src/analysis/table/constraints.rs +++ b/core/engine/src/analysis/table/constraints.rs @@ -4,6 +4,7 @@ use zen_expression::intellisense::IntelliSense; use super::cell::Condition; use super::value_set::ValueSet; +use zen_types::path::DotPath; #[derive(Debug, Clone, Default)] pub(crate) struct PathConstraints { @@ -59,13 +60,8 @@ impl PathConstraints { pub(crate) fn without<'s>(mut self, written: impl IntoIterator) -> Self { let written: Vec<&str> = written.into_iter().collect(); - let overlaps = |a: &str, b: &str| { - a == b - || a.strip_prefix(b).is_some_and(|rest| rest.starts_with('.')) - || b.strip_prefix(a).is_some_and(|rest| rest.starts_with('.')) - }; self.entries - .retain(|(path, _)| !written.iter().any(|w| overlaps(path, w))); + .retain(|(path, _)| !written.iter().any(|w| DotPath::overlaps(path, w))); self } } diff --git a/core/engine/src/compiled/bound.rs b/core/engine/src/compiled/bound.rs new file mode 100644 index 00000000..2cf279b3 --- /dev/null +++ b/core/engine/src/compiled/bound.rs @@ -0,0 +1,188 @@ +use crate::compiled::core::special::Specialized; +use std::cell::RefCell; +use std::rc::Rc; +use zen_expression::lane::{Binding, Columns, Fault, Kind, LaneProgram, LaneRunner, Output}; +use zen_expression::{IsolateError, Scope, Variable}; + +pub(crate) enum Scopes { + Owned(Vec), + Blank(Rc<[Scope]>, usize), +} + +impl Scopes { + pub fn slice(&self) -> &[Scope] { + match self { + Scopes::Owned(scopes) => scopes, + Scopes::Blank(scopes, rows) => &scopes[..*rows], + } + } +} + +pub(crate) struct Bound<'a> { + pub scopes: Scopes, + pub columns: Columns<'a>, + pub bind: Box Binding + 'a>, +} + +pub(crate) struct Outs(Vec); + +impl Outs { + const KEEP: usize = 32; + + thread_local! { + static POOL: RefCell>> = const { RefCell::new(Vec::new()) }; + } + + pub fn take() -> Outs { + Outs(Self::POOL.with_borrow_mut(Vec::pop).unwrap_or_default()) + } +} + +impl std::ops::Deref for Outs { + type Target = Vec; + + fn deref(&self) -> &Vec { + &self.0 + } +} + +impl std::ops::DerefMut for Outs { + fn deref_mut(&mut self) -> &mut Vec { + &mut self.0 + } +} + +impl Drop for Outs { + fn drop(&mut self) { + let outs = std::mem::take(&mut self.0); + Self::POOL.with_borrow_mut(|pool| { + if pool.len() < Self::KEEP { + pool.push(outs); + } + }); + } +} + +pub(crate) type Many = Result, (usize, IsolateError)>; + +type Programs = Specialized<(u64, Vec>), Option>>; + +impl<'a> Bound<'a> { + thread_local! { + static SPECIALIZED: RefCell = RefCell::new(Specialized::new(usize::MAX)); + static BLANK: RefCell> = RefCell::new(Rc::from([])); + } + + pub fn blank(rows: usize) -> Scopes { + Self::BLANK.with_borrow_mut(|blank| { + if blank.len() < rows { + *blank = (0..rows.next_power_of_two()) + .map(|_| Scope::default()) + .collect(); + } + Scopes::Blank(blank.clone(), rows) + }) + } + + pub fn scopes(&self) -> &[Scope] { + match &self.scopes { + Scopes::Owned(scopes) => scopes, + Scopes::Blank(scopes, rows) => &scopes[..*rows], + } + } + + pub fn plain(scopes: Vec) -> Self { + let rows = scopes.len(); + Self { + scopes: Scopes::Owned(scopes), + columns: Columns::new(rows), + bind: Box::new(|_| Binding::Row), + } + } + + pub fn rows(&self) -> usize { + self.scopes().len() + } + + fn specialized( + &self, + program: &LaneProgram, + bind: &dyn Fn(&str) -> Binding, + ) -> Option> { + let p = program.program(); + let signature: Vec> = p + .keys + .iter() + .map(|key| match bind(key) { + Binding::Column(index) => self.columns.columns.get(index).map(|(_, c)| c.kind()), + _ => None, + }) + .collect(); + if signature + .iter() + .all(|k| matches!(k, None | Some(Kind::Dyn))) + { + return None; + } + Self::SPECIALIZED.with_borrow_mut(|cache| { + cache.get_or_insert_with((p.id, signature), || { + program + .specialize_bound(&self.columns, bind) + .ok() + .map(Rc::new) + }) + }) + } + + pub fn many( + &self, + runner: &mut LaneRunner, + program: &LaneProgram, + subset: Option<&[usize]>, + mut sink: impl FnMut(usize, Many), + ) { + let specialized = self.specialized(program, &*self.bind); + let program = specialized.as_deref().unwrap_or(program); + runner.evaluate_bound( + program, + self.scopes(), + &self.columns, + &*self.bind, + subset, + &mut sink, + ); + } + + pub fn export( + &self, + runner: &mut LaneRunner, + program: &LaneProgram, + subset: Option<&[usize]>, + outs: &mut Vec, + failure: impl FnMut(usize, usize, Fault), + ) { + self.export_with(runner, program, subset, &*self.bind, outs, failure) + } + + pub fn export_with( + &self, + runner: &mut LaneRunner, + program: &LaneProgram, + subset: Option<&[usize]>, + bind: &dyn Fn(&str) -> Binding, + outs: &mut Vec, + failure: impl FnMut(usize, usize, Fault), + ) { + let specialized = self.specialized(program, bind); + let program = specialized.as_deref().unwrap_or(program); + runner.evaluate_bound_into( + program, + self.scopes(), + &self.columns, + bind, + subset, + outs, + failure, + ); + } +} diff --git a/core/engine/src/compiled/census.rs b/core/engine/src/compiled/census.rs new file mode 100644 index 00000000..9cef08e2 --- /dev/null +++ b/core/engine/src/compiled/census.rs @@ -0,0 +1,162 @@ +use std::cell::{Cell, RefCell}; +use std::collections::{BTreeMap, HashMap}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +pub(crate) struct Census; + +#[derive(Default, Clone, Copy)] +pub(crate) struct Tally { + pub calls: u64, + pub rows: u64, + pub ns: u128, +} + +impl Census { + thread_local! { + static PATH: Cell<&'static str> = const { Cell::new("") }; + static STARTS: RefCell> = const { RefCell::new(Vec::new()) }; + static REASON: RefCell = const { RefCell::new(String::new()) }; + static NOTE: RefCell = const { RefCell::new(String::new()) }; + } + + pub fn note(what: &str) { + if Self::on() { + Self::NOTE.with_borrow_mut(|note| { + if note.is_empty() { + *note = what.to_string(); + } + }); + } + } + + pub fn fresh() { + if Self::on() { + Self::NOTE.with_borrow_mut(String::clear); + } + } + + pub fn reason(why: impl FnOnce() -> String) { + if Self::on() { + let note = Self::NOTE.with_borrow_mut(std::mem::take); + Self::REASON.with_borrow_mut(|reason| *reason = format!("{note}{}", why())); + } + } + + fn rejected() -> &'static Mutex> { + static REJECTED: OnceLock>> = OnceLock::new(); + REJECTED.get_or_init(|| Mutex::new(HashMap::new())) + } + + pub fn reject(key: (usize, String)) { + if !Self::on() { + return; + } + let reason = Self::REASON.with_borrow_mut(std::mem::take); + if let Ok(mut rejected) = Self::rejected().lock() { + rejected.insert(key, Self::normal(&reason)); + } + } + + fn normal(reason: &str) -> String { + let mut out = String::with_capacity(reason.len()); + let mut quoted = false; + for c in reason.chars() { + match c { + '"' => { + quoted = !quoted; + if quoted { + out.push_str("\"…"); + } + } + _ if quoted => {} + c if c.is_ascii_digit() => { + if !out.ends_with('N') { + out.push('N'); + } + } + c => out.push(c), + } + } + out + } + + pub fn recall(key: &(usize, String)) { + if Self::on() { + let reason = Self::rejected() + .lock() + .ok() + .and_then(|rejected| rejected.get(key).cloned()) + .unwrap_or_else(|| "?".into()); + Self::REASON.with_borrow_mut(|r| *r = reason); + } + } + + pub fn taken() -> String { + Self::REASON.with_borrow_mut(std::mem::take) + } + + pub fn fallback(key: (usize, String), what: &str, rows: usize, ns: u128) { + let reason = Self::rejected() + .lock() + .ok() + .and_then(|rejected| rejected.get(&key).cloned()) + .unwrap_or_else(|| "?".into()); + Self::record(format!("lane | {what} | {reason}"), rows, ns); + } + + pub fn begin() { + if Self::on() { + Self::STARTS.with_borrow_mut(|starts| starts.push(Instant::now())); + } + } + + pub fn elapsed() -> u128 { + Self::STARTS + .with_borrow_mut(|starts| starts.pop().map_or(0, |start| start.elapsed().as_nanos())) + } + + pub fn id() -> usize { + static NEXT: AtomicUsize = AtomicUsize::new(0); + NEXT.fetch_add(1, Ordering::Relaxed) + } + + pub fn on() -> bool { + crate::compiled::switches::SWITCHES.census() + } + + fn table() -> &'static Mutex> { + static TABLE: OnceLock>> = OnceLock::new(); + TABLE.get_or_init(|| Mutex::new(BTreeMap::new())) + } + + pub fn mark(path: &'static str) { + if Self::on() { + Self::PATH.with(|p| p.set(path)); + } + } + + pub fn path() -> &'static str { + Self::PATH.with(|p| p.replace("")) + } + + pub fn record(key: String, rows: usize, ns: u128) { + if let Ok(mut table) = Self::table().lock() { + let tally = table.entry(key).or_default(); + tally.calls += 1; + tally.rows += rows as u64; + tally.ns += ns; + } + } + + pub fn take() -> Vec<(String, u64, u64, u128)> { + match Self::table().lock() { + Ok(mut table) => std::mem::take(&mut *table) + .into_iter() + .map(|(k, t)| (k, t.calls, t.rows, t.ns)) + .collect(), + Err(_) => Vec::new(), + } + } +} diff --git a/core/engine/src/compiled/core/exec.rs b/core/engine/src/compiled/core/exec.rs new file mode 100644 index 00000000..a6bf1a9a --- /dev/null +++ b/core/engine/src/compiled/core/exec.rs @@ -0,0 +1,606 @@ +use super::list::Frame; +use super::switch::{Cost, Route}; +use crate::compiled::leaf::{Bits, Leaf}; +use crate::compiled::shred::{Coder, Listing}; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; +use zen_expression::lane::{Column, Values}; +use zen_expression::typed::{Batch, Outputs, Program}; + +pub(crate) type Hint = Option<(Rc<[i32]>, usize)>; + +pub(crate) enum ListPart<'l, 'a> { + Frame(&'l Frame, Vec>), + Listing(&'l Listing<'a>, Option<&'l [u64]>, Option<&'l [u64]>), +} + +pub(crate) struct TypedCall<'l, 'a> { + pub rows: usize, + pub columns: &'l [Leaf<'a>], + pub lists: Vec>, + pub select: Option<&'l [u64]>, +} + +pub(crate) struct Select; + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +enum Rows { + #[default] + Plain, + Coded, + Warm, + Probe, +} + +#[derive(Clone, Copy, Default)] +pub(crate) struct Choice { + rows: Rows, + spent: Duration, +} + +pub(crate) struct Dedup { + sparse: AtomicU32, + calls: AtomicU32, + plain: AtomicU64, + part: AtomicU64, + coded: AtomicU64, + trial: AtomicBool, + pending: AtomicBool, + clock: fn() -> Duration, +} + +impl TypedCall<'_, '_> { + pub fn run(self, program: &Program) -> Option { + let mut batch = Batch::new(self.rows); + self.columns + .iter() + .for_each(|leaf| batch.push_column(leaf.column())); + for (part, def) in self.lists.into_iter().zip(&program.hir().schema.lists) { + batch.push_list(match part { + ListPart::Frame(frame, fields) => frame.list(None, fields), + ListPart::Listing(listing, validity, faults) => { + let list = listing.frame.list(validity, listing.columns(&def.fields)?); + match faults.or(listing.hosted.as_deref()) { + Some(bits) => list.faults(bits, 0), + None => list, + } + } + }); + } + let mut out = program.outputs(); + program.run(&batch, &mut out, self.select).ok()?; + Some(out) + } +} + +impl Select { + pub fn bits(rows: usize, positions: &[usize]) -> Vec { + let mut bits = vec![0u64; rows.div_ceil(64)]; + positions + .iter() + .for_each(|&row| Bits::set(&mut bits, row, true)); + bits + } +} + +impl Dedup { + const SPARSE: u32 = 16; + const LONG: usize = 24; + const PERIOD: u32 = 64; + const MIN: usize = 16; + const MARGIN: u64 = 4; + const FAILED: u64 = u64::MAX - 1; + + pub fn new() -> Self { + Self::with_clock(Self::monotonic) + } + + fn monotonic() -> Duration { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(Instant::now).elapsed() + } + + pub(crate) fn with_clock(clock: fn() -> Duration) -> Self { + Self { + clock, + sparse: AtomicU32::new(0), + calls: AtomicU32::new(0), + plain: AtomicU64::new(0), + part: AtomicU64::new(u64::MAX), + coded: AtomicU64::new(u64::MAX), + trial: AtomicBool::new(false), + pending: AtomicBool::new(false), + } + } + + fn rows(&self) -> Rows { + let call = self.calls.fetch_add(1, Ordering::Relaxed); + let coded = self.coded.load(Ordering::Relaxed); + match call % Self::PERIOD { + 0 if call == 0 => Rows::Warm, + 1 if call > 1 || coded != Self::FAILED => Rows::Probe, + _ if coded < self.plain.load(Ordering::Relaxed) => Rows::Coded, + _ => Rows::Plain, + } + } + + pub fn choose( + &self, + cx: &mut C, + local: usize, + plain: impl FnOnce(&mut C) -> Option, + coded: impl FnOnce(&mut C) -> Option, + ) -> (Option, Choice) { + let rows = match local >= Self::MIN { + true => self.rows(), + false => Rows::Plain, + }; + let choice = |rows: Rows, spent: Duration| Choice { rows, spent }; + match rows { + Rows::Plain => (plain(cx), Choice::default()), + Rows::Coded => match coded(cx) { + Some(out) => (Some(out), choice(Rows::Coded, Duration::ZERO)), + None => { + self.coded.store(u64::MAX, Ordering::Relaxed); + self.trial.store(false, Ordering::Relaxed); + (plain(cx), Choice::default()) + } + }, + Rows::Warm => { + let out = plain(cx); + let begin = (self.clock)(); + if out.is_some() && coded(cx).is_none() { + self.coded.store(Self::FAILED, Ordering::Relaxed); + } + ( + out, + choice(Rows::Warm, (self.clock)().saturating_sub(begin)), + ) + } + Rows::Probe => { + let begin = (self.clock)(); + let out = plain(cx); + if out.is_some() { + let spent = (self.clock)().saturating_sub(begin); + self.part.store(Self::per(spent, local), Ordering::Relaxed); + self.pending.store(true, Ordering::Relaxed); + } + (out, choice(Rows::Probe, Duration::ZERO)) + } + } + } + + pub fn settle( + &self, + cost: &Cost, + path: Route, + choice: Choice, + elapsed: Duration, + local: usize, + ) { + let elapsed = elapsed.saturating_sub(choice.spent); + let per = Self::per(elapsed, local); + match choice.rows { + Rows::Probe => self.plain.store(per, Ordering::Relaxed), + Rows::Coded if self.trial.swap(false, Ordering::Relaxed) => { + self.coded.store(per, Ordering::Relaxed); + cost.typed(per.min(self.plain.load(Ordering::Relaxed))); + return; + } + Rows::Coded => { + self.coded.fetch_min(per, Ordering::Relaxed); + } + Rows::Plain | Rows::Warm => {} + } + cost.record(path, elapsed, local); + } + + pub fn probe( + &self, + cost: &Cost, + cx: &mut C, + local: usize, + coded: impl FnOnce(&mut C) -> Option, + ) { + if !self.pending.swap(false, Ordering::Relaxed) { + return; + } + let begin = (self.clock)(); + let tried = coded(cx).is_some(); + let part = Self::per((self.clock)().saturating_sub(begin), local); + let saving = self.part.load(Ordering::Relaxed).saturating_sub(part); + match ( + tried, + saving > 0 && saving.saturating_mul(Self::MARGIN) >= self.plain.load(Ordering::Relaxed), + ) { + (true, true) => { + self.coded.store( + self.plain.load(Ordering::Relaxed).saturating_sub(saving), + Ordering::Relaxed, + ); + self.trial.store(true, Ordering::Relaxed); + cost.credit(saving); + } + (true, false) => self.coded.store(u64::MAX, Ordering::Relaxed), + (false, _) => self.coded.store(Self::FAILED, Ordering::Relaxed), + } + } + + fn per(elapsed: Duration, rows: usize) -> u64 { + u64::try_from(elapsed.as_nanos().saturating_mul(1024) / rows.max(1) as u128) + .unwrap_or(Self::FAILED) + } + + pub fn reps( + program: &Program, + leaves: &[Leaf], + codes: &[Hint], + positions: Option<&Rc<[usize]>>, + rows: usize, + ) -> Option<(Outputs, Vec)> { + let (reps, ids) = Self::distinct(leaves, codes, positions, rows)?; + let picks: Rc<[usize]> = reps.into(); + let picked: Vec = leaves.iter().map(|leaf| leaf.pick(&picks)).collect(); + let call = TypedCall { + rows: picks.len(), + columns: &picked, + lists: Vec::new(), + select: None, + }; + Some((call.run(program)?, ids)) + } + + pub fn coded( + program: &Program, + leaves: &[Leaf], + codes: &[Hint], + positions: Option<&Rc<[usize]>>, + rows: usize, + ) -> Option { + let (mut out, ids) = Self::reps(program, leaves, codes, positions, rows)?; + out.spread(rows, &ids, positions.map(|p| &p[..])) + .then_some(out) + } + + pub fn codes(column: &Column, rows: usize) -> Hint { + match column.values { + Values::Scaled { .. } | Values::I64(_) => Self::numbered(column, rows), + Values::Text { offsets, data } => Coder::keys(data.as_bytes(), offsets.get(..=rows)?), + Values::Utf8 { offsets, data } => Coder::keys(data, offsets.get(..=rows)?), + _ => None, + } + } + + pub fn ready(&self) -> bool { + self.sparse.load(Ordering::Relaxed) == 0 + } + + pub fn eligible(&self, program: &Program, leaves: &[Leaf], hints: &[Hint]) -> bool { + let long = program.instructions() >= Self::LONG * leaves.len(); + leaves.iter().zip(hints).all(|(leaf, hint)| { + hint.is_some() + || match leaf.column().values { + Values::Dict { .. } | Values::Bool { .. } => true, + Values::Scaled { .. } + | Values::I64(_) + | Values::Dec(_) + | Values::Text { .. } => long, + _ => false, + } + }) + } + + pub fn learn( + &self, + keyed: bool, + leaves: &[Leaf], + hints: &mut [Hint], + positions: Option<&Rc<[usize]>>, + rows: usize, + ) -> Option<(Vec, Vec)> { + if !keyed { + let _ = self + .sparse + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |left| { + left.checked_sub(1) + }); + return None; + } + for (leaf, hint) in leaves + .iter() + .zip(hints.iter_mut()) + .filter(|(_, hint)| hint.is_none()) + { + *hint = Self::numbered(&leaf.column(), rows); + } + let distinct = Self::distinct(leaves, hints, positions, rows); + if distinct.is_none() { + self.sparse.store(Self::SPARSE, Ordering::Relaxed); + } + distinct + } + + pub fn distinct( + leaves: &[Leaf], + hints: &[Hint], + positions: Option<&Rc<[usize]>>, + rows: usize, + ) -> Option<(Vec, Vec)> { + let local = positions.map_or(rows, |p| p.len()); + if leaves.is_empty() || local < 16 { + return None; + } + let listed: Vec = leaves.iter().map(|leaf| leaf.records().is_some()).collect(); + if listed + .iter() + .enumerate() + .any(|(at, &listed)| listed && hints.get(at).is_none_or(Option::is_none)) + { + return None; + } + let held: Vec>> = leaves + .iter() + .zip(&listed) + .map(|(leaf, &listed)| listed.then(|| leaf.validity(rows))) + .collect(); + let columns: Vec = leaves + .iter() + .zip(&held) + .map(|(leaf, held)| match held { + Some(bits) => Column { + values: Values::Any(&[]), + validity: Some((bits.as_slice(), 0)), + }, + None => leaf.column(), + }) + .collect(); + let mut strides = Vec::with_capacity(columns.len()); + let mut size = 1u64; + for (at, column) in columns.iter().enumerate() { + let width = match (column.values, hints.get(at).and_then(Option::as_ref)) { + (_, Some((_, size))) => *size as u64 + 1, + (Values::Dict { values, .. }, None) => values.len() as u64 + 1, + (Values::Bool { .. }, None) => 3, + _ => return None, + }; + strides.push(size); + size = size.checked_mul(width)?; + } + let mut keys = vec![0u64; local]; + for (index, (column, stride)) in columns.iter().zip(&strides).enumerate() { + let hint = hints.get(index).and_then(Option::as_ref); + let code = |row: usize, code: i32| match column.valid(row) { + true => u64::try_from(code).map_or(0, |k| k + 1), + false => 0, + }; + let codes: Option<&[i32]> = match (hint, column.values) { + (Some((codes, _)), _) => Some(codes), + (None, Values::Dict { keys, .. }) => Some(keys), + _ => None, + }; + match (codes, column.values) { + (Some(codes), _) + if positions.is_none() && column.validity.is_none() && codes.len() >= local => + { + for (key, &code) in keys.iter_mut().zip(codes) { + *key += (code.max(-1) + 1) as u64 * stride; + } + } + (Some(codes), _) if positions.is_none() && codes.len() >= local => { + let valid = column.validity.map_or_else( + || Bits::ones(local), + |(bits, offset)| Bits::window(bits, offset, local), + ); + for ((at, key), &code) in keys.iter_mut().enumerate().zip(codes) { + let live = (valid[at >> 6] >> (at & 63)) & 1; + *key += (code.max(-1) + 1) as u64 * live * stride; + } + } + (Some(codes), _) => { + for (at, key) in keys.iter_mut().enumerate() { + let row = positions.map_or(at, |p| p[at]); + *key += code(row, codes.get(row).copied().unwrap_or(-1)) * stride; + } + } + (None, Values::Bool { bits, offset }) => { + for (at, key) in keys.iter_mut().enumerate() { + let row = positions.map_or(at, |p| p[at]); + *key += code(row, i32::from(Bits::get(bits, offset + row))) * stride; + } + } + _ => return None, + } + } + let dense = size <= 4096; + let slots = match dense { + true => size as usize, + false => (local / 2).next_power_of_two().max(16) * 2, + }; + let mut table = vec![(u64::MAX, u32::MAX); slots]; + let mask = slots - 1; + let mut reps = Vec::new(); + let mut ids = vec![0u32; local]; + for ((at, &key), id) in keys.iter().enumerate().zip(ids.iter_mut()) { + let mut slot = match dense { + true => key as usize, + false => (key.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) as usize & mask, + }; + while !dense && table[slot].1 != u32::MAX && table[slot].0 != key { + slot = (slot + 1) & mask; + } + let entry = table.get_mut(slot)?; + if entry.1 == u32::MAX { + *entry = (key, reps.len() as u32); + reps.push(positions.map_or(at, |p| p[at])); + if reps.len() * 4 > local { + return None; + } + } + *id = entry.1; + } + Some((reps, ids)) + } + + fn numbered(column: &Column, rows: usize) -> Option<(Rc<[i32]>, usize)> { + const SLOTS: usize = 256; + const LIMIT: usize = 128; + let (mant, scale) = match column.values { + Values::Scaled { mant, scale } => (mant.get(..rows)?, Some(scale.get(..rows)?)), + Values::I64(values) => (values.get(..rows)?, None), + _ => return None, + }; + let mut table = [(0i64, 0u8, u8::MAX); SLOTS]; + let mut count = 0usize; + let mut codes: Vec = Vec::with_capacity(rows); + let mut last: Option<(i64, u8, i32)> = None; + for (at, &m) in mant.iter().enumerate() { + let s = scale.map_or(0, |scale| scale[at]); + if let Some((_, _, code)) = last.filter(|(lm, ls, _)| *lm == m && *ls == s) { + codes.push(code); + continue; + } + let mut slot = ((m as u64 ^ u64::from(s) << 56).wrapping_mul(0x9E37_79B9_7F4A_7C15) + >> 56) as usize; + let code = loop { + let entry = &mut table[slot]; + if entry.2 == u8::MAX { + if count >= LIMIT { + return None; + } + *entry = (m, s, count as u8); + count += 1; + break i32::from(entry.2); + } + if entry.0 == m && entry.1 == s { + break i32::from(entry.2); + } + slot = (slot + 1) % SLOTS; + }; + last = Some((m, s, code)); + codes.push(code); + } + Some((codes.into(), count)) + } +} + +#[cfg(test)] +mod tests { + use super::{Choice, Dedup}; + use crate::compiled::core::switch::{Cost, Path, Route}; + use std::cell::Cell; + use std::time::Duration; + + thread_local! { + static NOW: Cell = const { Cell::new(Duration::ZERO) }; + } + + fn dedup() -> Dedup { + Dedup::with_clock(|| NOW.get()) + } + + struct Spin; + + impl Spin { + fn run(micros: u64) -> Option { + NOW.set(NOW.get() + Duration::from_micros(micros)); + Some(micros) + } + + fn call(dedup: &Dedup, cost: &Cost, plain: u64, coded: u64, merged: u64) -> Option { + let start = NOW.get(); + let (out, choice): (Option, Choice) = + dedup.choose(&mut (), 1024, |_| Self::run(plain), |_| Self::run(coded)); + Self::run(merged); + dedup.settle( + cost, + Route { + path: Path::Typed, + fresh: false, + }, + choice, + NOW.get() - start, + 1024, + ); + dedup.probe(cost, &mut (), 1024, |_| Self::run(coded)); + out + } + } + + #[test] + fn a_clearly_cheaper_coded_run_is_tried_and_kept() { + let (dedup, cost) = (dedup(), Cost::new()); + let runs: Vec> = (0..6) + .map(|_| Spin::call(&dedup, &cost, 400, 50, 20)) + .collect(); + assert_eq!(&runs[..2], &[Some(400), Some(400)]); + assert!(runs[2..].iter().all(|run| *run == Some(50))); + } + + #[test] + fn a_coded_trial_that_loses_reverts_to_plain() { + let (dedup, cost) = (dedup(), Cost::new()); + let mut runs: Vec> = (0..2) + .map(|_| Spin::call(&dedup, &cost, 400, 50, 20)) + .collect(); + let start = NOW.get(); + let (out, choice) = dedup.choose(&mut (), 1024, |_| Spin::run(400), |_| Spin::run(50)); + Spin::run(900); + dedup.settle( + &cost, + Route { + path: Path::Typed, + fresh: false, + }, + choice, + NOW.get() - start, + 1024, + ); + runs.push(out); + runs.extend((0..3).map(|_| Spin::call(&dedup, &cost, 400, 50, 20))); + assert_eq!(runs[2], Some(50)); + assert!(runs[3..].iter().all(|run| *run == Some(400))); + } + + #[test] + fn a_marginal_saving_is_not_tried() { + let (dedup, cost) = (dedup(), Cost::new()); + let runs: Vec> = (0..6) + .map(|_| Spin::call(&dedup, &cost, 400, 360, 20)) + .collect(); + assert!(runs.iter().all(|run| *run == Some(400))); + } + + #[test] + fn a_failed_warm_up_skips_the_probe() { + let (dedup, cost) = (dedup(), Cost::new()); + let mut tried = 0; + for _ in 0..6 { + let (out, choice) = dedup.choose( + &mut tried, + 1024, + |_| Some(1), + |tried| { + *tried += 1; + None:: + }, + ); + assert_eq!(out, Some(1)); + dedup.settle( + &cost, + Route { + path: Path::Typed, + fresh: false, + }, + choice, + Duration::from_micros(10), + 1024, + ); + dedup.probe(&cost, &mut tried, 1024, |tried| { + *tried += 1; + None:: + }); + } + assert_eq!(tried, 1); + } +} diff --git a/core/engine/src/compiled/core/fuse.rs b/core/engine/src/compiled/core/fuse.rs new file mode 100644 index 00000000..83829d33 --- /dev/null +++ b/core/engine/src/compiled/core/fuse.rs @@ -0,0 +1,68 @@ +use std::hash::Hash; +use std::sync::RwLock; +use zen_expression::lane::{Fusion, LaneProgram}; + +pub(crate) struct Fused { + pub program: LaneProgram, + pub sinks: Vec, +} + +pub(crate) struct Runs { + runs: RwLock>, +} + +impl Fused { + pub fn build(entries: &[Fusion], sinks: Vec) -> Option { + let outputs = entries + .iter() + .filter(|entry| !matches!(entry, Fusion::Hidden { .. })) + .count(); + let program = LaneProgram::compile_fused(entries).ok()?; + let p = program.program(); + (!(p.writes_env || p.chain || p.opaque() || p.rows) && p.outputs.len() == outputs) + .then_some(Self { program, sinks }) + } +} + +impl Default for Runs { + fn default() -> Self { + Self { + runs: RwLock::new(ahash::HashMap::default()), + } + } +} + +impl Runs { + pub fn run(&self, key: &K) -> Option { + self.runs + .read() + .ok() + .and_then(|runs| runs.get(key).copied()) + } + + pub fn ran(&self, key: K, run: usize) { + if self.run(&key) == Some(run) { + return; + } + if let Ok(mut runs) = self.runs.write() { + runs.insert(key, run); + } + } +} + +#[cfg(test)] +mod tests { + use super::Runs; + + #[test] + fn runs_remember_the_latest_length() { + let runs: Runs<(Vec, bool)> = Runs::default(); + assert_eq!(runs.run(&(vec![1, 2], false)), None); + runs.ran((vec![1, 2], false), 2); + runs.ran((vec![1, 2], true), 5); + assert_eq!(runs.run(&(vec![1, 2], false)), Some(2)); + runs.ran((vec![1, 2], false), 1); + assert_eq!(runs.run(&(vec![1, 2], false)), Some(1)); + assert_eq!(runs.run(&(vec![1, 2], true)), Some(5)); + } +} diff --git a/core/engine/src/compiled/core/group.rs b/core/engine/src/compiled/core/group.rs new file mode 100644 index 00000000..e11a814e --- /dev/null +++ b/core/engine/src/compiled/core/group.rs @@ -0,0 +1,105 @@ +pub(crate) enum Attempt { + Typed(T, usize), + Deferred, + Failed, +} + +pub(crate) enum Step { + Lowered, + Stop, + Done(T), +} + +pub(crate) enum Built { + Done(T), + Shrink { consumed: usize, fallback: T }, +} + +pub(crate) struct Prefix; + +impl Prefix { + pub fn lower( + len: usize, + mut start: impl FnMut() -> S, + mut unit: impl FnMut(&mut S, usize) -> Step, + mut build: impl FnMut(S) -> Built, + ) -> T { + let mut limit = len; + loop { + let mut state = start(); + for at in 0..limit { + match unit(&mut state, at) { + Step::Lowered => {} + Step::Stop => break, + Step::Done(done) => return done, + } + } + match build(state) { + Built::Done(done) => return done, + Built::Shrink { consumed, fallback } if consumed <= 1 => return fallback, + Built::Shrink { consumed, .. } => limit = consumed - 1, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::{Built, Prefix, Step}; + + fn lower(len: usize, fits: usize, stop: Option) -> (Option, Vec) { + let mut limits = Vec::new(); + let found = Prefix::lower( + len, + Vec::new, + |taken: &mut Vec, at| match Some(at) == stop { + true => Step::Stop, + false => { + taken.push(at); + Step::Lowered + } + }, + |taken| { + limits.push(taken.len()); + match taken.len() { + 0 => Built::Done(None), + n if n <= fits => Built::Done(Some(n)), + n => Built::Shrink { + consumed: n, + fallback: None, + }, + } + }, + ); + (found, limits) + } + + #[test] + fn shrinks_by_one_below_what_was_consumed() { + assert_eq!(lower(5, 3, None), (Some(3), vec![5, 4, 3])); + assert_eq!(lower(5, 2, Some(4)), (Some(2), vec![4, 3, 2])); + } + + #[test] + fn a_single_failing_unit_falls_back() { + assert_eq!(lower(3, 0, None), (None, vec![3, 2, 1])); + assert_eq!(lower(3, 3, Some(0)), (None, vec![0])); + } + + #[test] + fn done_returns_immediately() { + let found = Prefix::lower( + 4, + || (), + |_, at| { + if at == 1 { + Step::Done(7) + } else { + Step::Lowered + } + }, + |_| Built::Done(0), + ); + assert_eq!(found, 7); + } +} diff --git a/core/engine/src/compiled/core/list.rs b/core/engine/src/compiled/core/list.rs new file mode 100644 index 00000000..1181875b --- /dev/null +++ b/core/engine/src/compiled/core/list.rs @@ -0,0 +1,189 @@ +use crate::compiled::leaf::Bits; +use std::cell::OnceCell; +use std::rc::Rc; +use zen_expression::lane::Column; +use zen_expression::typed::List; + +pub(crate) type Family = (Rc<[usize]>, Rc<[usize]>); + +#[derive(Clone)] +pub(crate) struct Frame { + pub offsets: Rc<[i32]>, + pub validity: Option>, + pub children: usize, +} + +pub(crate) struct Kin { + pub at: usize, + pub kids: Rc<[usize]>, + pub parents: Rc<[usize]>, + pub identity: bool, + codes: OnceCell>>, +} + +impl Frame { + pub fn range(&self, row: usize) -> Option<(usize, usize)> { + if self + .validity + .as_ref() + .is_some_and(|bits| !Bits::get(bits, row)) + { + return None; + } + let a = usize::try_from(*self.offsets.get(row)?).unwrap_or(0); + let b = usize::try_from(*self.offsets.get(row + 1)?) + .unwrap_or(0) + .max(a); + Some((a.min(self.children), b.min(self.children))) + } + + pub fn span(&self, rows: usize) -> Option<(usize, usize)> { + let offsets = self.offsets.get(..=rows)?; + let base = usize::try_from(*offsets.first()?).ok()?; + let end = usize::try_from(*offsets.last()?).ok()?; + let sorted = offsets.windows(2).all(|pair| pair[0] <= pair[1]); + (sorted && base <= end && end <= self.children).then_some((base, end)) + } + + pub fn identity(&self, kids: &[usize]) -> bool { + kids.len() == self.children && kids.iter().enumerate().all(|(i, &k)| i == k) + } + + pub fn list<'f>(&'f self, validity: Option<&'f [u64]>, fields: Vec>) -> List<'f> { + List::new( + &self.offsets, + validity.or(self.validity.as_deref()).map(|bits| (bits, 0)), + fields, + ) + } +} + +impl Kin { + pub fn new(at: usize, kids: Rc<[usize]>, parents: Rc<[usize]>, identity: bool) -> Self { + Self { + at, + kids, + parents, + identity, + codes: OnceCell::new(), + } + } + + pub fn spans(frame: &Frame, rows: usize) -> Option { + if frame.validity.is_some() { + return None; + } + let offsets = frame.offsets.get(..=rows)?; + let ordered = offsets.first() == Some(&0) + && offsets.last().and_then(|&end| usize::try_from(end).ok()) == Some(frame.children) + && offsets.windows(2).all(|pair| pair[0] <= pair[1]); + if !ordered { + return None; + } + let mut parents = Vec::with_capacity(frame.children); + for (row, pair) in offsets.windows(2).enumerate() { + parents.extend(std::iter::repeat_n(row, (pair[1] - pair[0]) as usize)); + } + Some(((0..frame.children).collect(), parents.into())) + } + + pub fn gather( + positions: &[usize], + capacity: usize, + range: impl Fn(usize) -> Option<(usize, usize)>, + mut visit: impl FnMut(usize, Option<(usize, usize)>), + ) -> (Vec, Vec) { + let mut kids = Vec::with_capacity(capacity); + let mut parents = Vec::with_capacity(capacity); + for &row in positions { + match range(row) { + Some((a, b)) => { + let start = kids.len(); + kids.extend(a..b); + parents.extend(std::iter::repeat_n(row, b.saturating_sub(a))); + visit(row, Some((start, kids.len()))); + } + None => visit(row, None), + } + } + (kids, parents) + } + + pub fn codes(&self) -> Option> { + self.codes + .get_or_init(|| { + self.parents + .iter() + .map(|&row| i32::try_from(row).ok()) + .collect() + }) + .clone() + } +} + +#[cfg(test)] +mod tests { + use super::{Frame, Kin}; + use std::rc::Rc; + + fn frame(offsets: &[i32], validity: Option<&[u64]>, children: usize) -> Frame { + Frame { + offsets: offsets.into(), + validity: validity.map(Rc::from), + children, + } + } + + #[test] + fn invalid_rows_have_no_range_and_empty_lists_do() { + let lists = frame(&[0, 2, 2, 5], Some(&[0b101]), 5); + assert_eq!(lists.range(0), Some((0, 2))); + assert_eq!(lists.range(1), None); + assert_eq!(lists.range(2), Some((2, 5))); + assert_eq!(lists.range(3), None); + let empty = frame(&[0, 3, 3], None, 3); + assert_eq!(empty.range(1), Some((3, 3))); + } + + #[test] + fn ranges_clamp_to_children() { + let lists = frame(&[0, 4, 2, 9], None, 6); + assert_eq!(lists.range(1), Some((4, 4))); + assert_eq!(lists.range(2), Some((2, 6))); + } + + #[test] + fn spans_need_sorted_offsets_within_children() { + assert_eq!(frame(&[1, 2, 4], None, 4).span(2), Some((1, 4))); + assert_eq!(frame(&[0, 3, 2], None, 4).span(2), None); + assert_eq!(frame(&[0, 2, 5], None, 4).span(2), None); + assert_eq!(frame(&[0, 2], None, 4).span(2), None); + } + + #[test] + fn kin_spans_and_gather_agree() { + let lists = frame(&[0, 2, 2, 5], None, 5); + let (kids, parents) = Kin::spans(&lists, 3).unwrap_or_else(|| (Rc::from([]), Rc::from([]))); + let mut seen = Vec::new(); + let (gathered, owners) = Kin::gather( + &[0, 1, 2], + 5, + |row| lists.range(row), + |row, span| seen.push((row, span)), + ); + assert_eq!(&*kids, gathered.as_slice()); + assert_eq!(&*parents, owners.as_slice()); + assert_eq!( + seen, + vec![(0, Some((0, 2))), (1, Some((2, 2))), (2, Some((2, 5)))] + ); + assert!(lists.identity(&gathered)); + assert!(Kin::spans(&frame(&[0, 2, 5], Some(&[0b11]), 5), 2).is_none()); + } + + #[test] + fn kin_codes_are_parent_rows() { + let kin = Kin::new(0, Rc::from([0, 1, 2]), Rc::from([0, 0, 1]), true); + assert_eq!(kin.codes().as_deref(), Some(&[0, 0, 1][..])); + } +} diff --git a/core/engine/src/compiled/core/mod.rs b/core/engine/src/compiled/core/mod.rs new file mode 100644 index 00000000..5727eda7 --- /dev/null +++ b/core/engine/src/compiled/core/mod.rs @@ -0,0 +1,9 @@ +pub(crate) mod exec; +pub(crate) mod fuse; +pub(crate) mod group; +pub(crate) mod list; +pub(crate) mod retry; +pub(crate) mod segments; +pub(crate) mod special; +pub(crate) mod switch; +pub(crate) mod variants; diff --git a/core/engine/src/compiled/core/retry.rs b/core/engine/src/compiled/core/retry.rs new file mode 100644 index 00000000..69742826 --- /dev/null +++ b/core/engine/src/compiled/core/retry.rs @@ -0,0 +1,111 @@ +use crate::compiled::leaf::Bits; +use std::rc::Rc; + +pub(crate) struct Take { + bits: Vec, + rows: usize, +} + +impl Take { + pub fn new(rows: usize) -> Self { + Self { + bits: vec![0u64; rows.div_ceil(64)], + rows, + } + } + + pub fn among(faults: &[u64], positions: &[usize]) -> (Vec, Vec) { + positions.iter().partition(|&&row| Bits::get(faults, row)) + } + + pub fn seed(&mut self, prefault: Option<&[u64]>, positions: Option<&[usize]>) { + let Some(prefault) = prefault else { + return; + }; + match positions { + Some(positions) => positions + .iter() + .filter(|&&row| Bits::get(prefault, row)) + .for_each(|&row| Bits::set(&mut self.bits, row, true)), + None => self + .bits + .iter_mut() + .zip(prefault) + .for_each(|(t, f)| *t |= f), + } + } + + pub fn absorb( + &mut self, + failed: &[u64], + ids: Option<&[u32]>, + positions: Option<&[usize]>, + local: usize, + ) { + match ids { + Some(ids) => (0..local) + .filter(|&at| Bits::get(failed, ids[at] as usize)) + .for_each(|at| Bits::set(&mut self.bits, positions.map_or(at, |p| p[at]), true)), + None => self.bits.iter_mut().zip(failed).for_each(|(t, f)| *t |= f), + } + Bits::trim(&mut self.bits, self.rows); + } + + pub fn any(&self) -> bool { + !Bits::none(&self.bits) + } + + pub fn bits(&self) -> &[u64] { + &self.bits + } + + pub fn drain(&mut self, keep: impl Fn(usize) -> bool) -> Vec { + let rows = Bits::rows(&self.bits).filter(|&row| keep(row)).collect(); + self.bits.iter_mut().for_each(|word| *word = 0); + rows + } + + pub fn set(&mut self, row: usize) { + Bits::set(&mut self.bits, row, true); + } + + pub fn located(&self) -> Rc<[(usize, usize)]> { + (0..self.rows) + .map(|row| (usize::from(Bits::get(&self.bits, row)), row)) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::Take; + + #[test] + fn seeds_absorbs_and_drains_in_row_order() { + let mut take = Take::new(70); + take.seed(Some(&[0b1010, 0]), Some(&[1, 2, 3])); + assert_eq!(take.bits(), &[0b1010, 0]); + take.absorb(&[0b11], Some(&[1, 0, 1]), Some(&[5, 66, 69]), 3); + assert_eq!(take.bits(), &[0b10_1010, 0b100100]); + let rows = take.drain(|row| row != 3); + assert_eq!(rows, vec![1, 5, 66, 69]); + assert!(!take.any()); + take.set(2); + assert_eq!(take.located()[2], (1, 2)); + assert_eq!(take.located()[1], (0, 1)); + } + + #[test] + fn absorb_without_ids_trims_past_rows() { + let mut take = Take::new(3); + take.absorb(&[u64::MAX], None, None, 3); + assert_eq!(take.bits(), &[0b111]); + } + + #[test] + fn among_keeps_position_order() { + let (faulted, kept) = Take::among(&[0b100100], &[5, 1, 2, 3]); + assert_eq!(faulted, vec![5, 2]); + assert_eq!(kept, vec![1, 3]); + } +} diff --git a/core/engine/src/compiled/core/segments.rs b/core/engine/src/compiled/core/segments.rs new file mode 100644 index 00000000..858084d3 --- /dev/null +++ b/core/engine/src/compiled/core/segments.rs @@ -0,0 +1,77 @@ +use std::borrow::Borrow; +use std::sync::RwLock; + +pub(crate) struct Children { + cache: RwLock>, +} + +impl Children { + pub(crate) fn new() -> Self { + Self { + cache: RwLock::new(Vec::new()), + } + } + + pub(crate) fn get(&self, key: &Q, build: impl FnOnce() -> S) -> S + where + K: Borrow, + Q: PartialEq + ToOwned + ?Sized, + { + let found = |cache: &[(K, S)]| { + cache + .iter() + .find(|(k, _)| k.borrow() == key) + .map(|(_, child)| child.clone()) + }; + if let Some(child) = self.cache.read().ok().and_then(|cache| found(&cache)) { + return child; + } + let built = build(); + let Ok(mut cache) = self.cache.write() else { + return built; + }; + if let Some(child) = found(&cache) { + return child; + } + cache.push((key.to_owned(), built.clone())); + built + } + + pub(crate) fn each(&self, mut visit: impl FnMut(&S) -> Result<(), E>) -> Result<(), E> { + match self.cache.read() { + Ok(cache) => cache.iter().try_for_each(|(_, child)| visit(child)), + Err(_) => Ok(()), + } + } +} + +#[cfg(test)] +mod tests { + use super::Children; + use std::cell::Cell; + + #[test] + fn builds_each_key_once_and_visits_in_insertion_order() { + let children: Children, u32> = Children::new(); + let built = Cell::new(0); + let build = |value: u32| { + built.set(built.get() + 1); + value + }; + assert_eq!(children.get(&[2][..], || build(20)), 20); + assert_eq!(children.get(&[1][..], || build(10)), 10); + assert_eq!(children.get(&[2][..], || build(99)), 20); + assert_eq!(built.get(), 2); + let mut seen = Vec::new(); + let visited: Result<(), ()> = children.each(|child| { + seen.push(*child); + Ok(()) + }); + assert_eq!(visited, Ok(())); + assert_eq!(seen, vec![20, 10]); + assert_eq!( + children.each(|child| if *child == 20 { Err(*child) } else { Ok(()) }), + Err(20) + ); + } +} diff --git a/core/engine/src/compiled/core/special.rs b/core/engine/src/compiled/core/special.rs new file mode 100644 index 00000000..facc9608 --- /dev/null +++ b/core/engine/src/compiled/core/special.rs @@ -0,0 +1,59 @@ +use std::hash::Hash; + +pub(crate) struct Specialized { + cap: usize, + cache: ahash::HashMap, +} + +impl Specialized { + pub fn new(cap: usize) -> Self { + Self { + cap, + cache: ahash::HashMap::default(), + } + } + + pub fn get(&self, key: &K) -> Option { + self.cache.get(key).cloned() + } + + pub fn insert(&mut self, key: K, value: V) { + if self.cache.len() > self.cap { + self.cache.clear(); + } + self.cache.insert(key, value); + } + + pub fn get_or_insert_with(&mut self, key: K, build: impl FnOnce() -> V) -> V { + if self.cache.len() > self.cap && !self.cache.contains_key(&key) { + self.cache.clear(); + } + self.cache.entry(key).or_insert_with(build).clone() + } +} + +#[cfg(test)] +mod tests { + use super::Specialized; + + #[test] + fn clears_once_past_the_cap() { + let mut cache: Specialized = Specialized::new(2); + (0..3).for_each(|key| cache.insert(key, key)); + assert_eq!(cache.get(&0), Some(0)); + cache.insert(3, 3); + assert_eq!(cache.get(&0), None); + assert_eq!(cache.get(&3), Some(3)); + } + + #[test] + fn get_or_insert_with_keeps_failures_and_existing_entries() { + let mut cache: Specialized> = Specialized::new(1); + assert_eq!(cache.get_or_insert_with(1, || None), None); + assert_eq!(cache.get_or_insert_with(1, || Some(5)), None); + assert_eq!(cache.get_or_insert_with(2, || Some(2)), Some(2)); + assert_eq!(cache.get_or_insert_with(1, || Some(7)), None); + assert_eq!(cache.get_or_insert_with(3, || Some(3)), Some(3)); + assert_eq!(cache.get(&1), None); + } +} diff --git a/core/engine/src/compiled/core/switch.rs b/core/engine/src/compiled/core/switch.rs new file mode 100644 index 00000000..628b68e2 --- /dev/null +++ b/core/engine/src/compiled/core/switch.rs @@ -0,0 +1,274 @@ +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::time::Duration; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Path { + Typed, + Lane, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct Route { + pub path: Path, + pub fresh: bool, +} + +pub(crate) struct Cost { + calls: AtomicU32, + typed: AtomicU64, + lane: AtomicU64, +} + +pub(crate) struct Density; + +impl Density { + pub(crate) fn sparse(local: usize, rows: usize) -> bool { + local * 4 < rows + } +} + +impl Cost { + const WARM: u32 = 2; + const PERIOD: u32 = 64; + + pub(crate) fn new() -> Self { + Self { + calls: AtomicU32::new(0), + typed: AtomicU64::new(u64::MAX), + lane: AtomicU64::new(u64::MAX), + } + } + + pub(crate) fn path(&self) -> Route { + let call = self.calls.fetch_add(1, Ordering::Relaxed); + if call < Self::WARM { + return Route { + path: Path::Typed, + fresh: false, + }; + } + if call < 2 * Self::WARM { + return Route { + path: Path::Lane, + fresh: false, + }; + } + let (faster, slower) = + match self.typed.load(Ordering::Relaxed) <= self.lane.load(Ordering::Relaxed) { + true => (Path::Typed, Path::Lane), + false => (Path::Lane, Path::Typed), + }; + match call % Self::PERIOD { + 0 => Route { + path: slower, + fresh: true, + }, + 1 => Route { + path: faster, + fresh: true, + }, + _ => Route { + path: faster, + fresh: false, + }, + } + } + + pub(crate) fn typed(&self, per: u64) { + self.typed.store(per, Ordering::Relaxed); + } + + pub(crate) fn credit(&self, saving: u64) { + if saving > 0 { + let _ = self + .typed + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |typed| { + Some(typed.saturating_sub(saving)) + }); + } + } + + pub(crate) fn record(&self, Route { path, fresh }: Route, elapsed: Duration, rows: usize) { + let per = u64::try_from(elapsed.as_nanos().saturating_mul(1024) / rows.max(1) as u128) + .unwrap_or(u64::MAX - 1); + let cell = match path { + Path::Typed => &self.typed, + Path::Lane => &self.lane, + }; + match fresh { + true => cell.store(per, Ordering::Relaxed), + false => { + cell.fetch_min(per, Ordering::Relaxed); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::{Cost, Density, Path, Route}; + use std::time::Duration; + + fn timed(cost: &Cost, typed: u64, lane: u64) -> Vec { + (0..130) + .map(|_| { + let path = cost.path(); + let nanos = match path.path { + Path::Typed => typed, + Path::Lane => lane, + }; + cost.record(path, Duration::from_nanos(nanos), 1024); + path + }) + .collect() + } + + #[test] + fn warm_calls_alternate_then_pick_the_faster_path() { + let cost = Cost::new(); + let calls = timed(&cost, 10, 20); + assert_eq!( + &calls[..4], + &[ + Route { + path: Path::Typed, + fresh: false + }, + Route { + path: Path::Typed, + fresh: false + }, + Route { + path: Path::Lane, + fresh: false + }, + Route { + path: Path::Lane, + fresh: false + } + ] + ); + assert!(calls[4..64].iter().all(|&call| call + == Route { + path: Path::Typed, + fresh: false + })); + assert_eq!( + calls[64], + Route { + path: Path::Lane, + fresh: true + } + ); + assert_eq!( + calls[65], + Route { + path: Path::Typed, + fresh: true + } + ); + assert!(calls[66..128].iter().all(|&call| call + == Route { + path: Path::Typed, + fresh: false + })); + assert_eq!( + calls[128], + Route { + path: Path::Lane, + fresh: true + } + ); + assert_eq!( + calls[129], + Route { + path: Path::Typed, + fresh: true + } + ); + } + + #[test] + fn lane_wins_when_it_is_faster() { + let cost = Cost::new(); + let calls = timed(&cost, 30, 20); + assert!(calls[4..64].iter().all(|&call| call + == Route { + path: Path::Lane, + fresh: false + })); + assert_eq!( + calls[64], + Route { + path: Path::Typed, + fresh: true + } + ); + assert_eq!( + calls[65], + Route { + path: Path::Lane, + fresh: true + } + ); + } + + #[test] + fn fresh_probe_replaces_the_minimum() { + let cost = Cost::new(); + for _ in 0..4 { + let path = cost.path(); + cost.record(path, Duration::from_nanos(10), 1024); + } + (4..64).for_each(|_| { + cost.path(); + }); + cost.record( + Route { + path: Path::Typed, + fresh: true, + }, + Duration::from_nanos(50), + 1024, + ); + assert_eq!( + cost.path(), + Route { + path: Path::Typed, + fresh: true + } + ); + cost.record( + Route { + path: Path::Typed, + fresh: false, + }, + Duration::from_nanos(5), + 1024, + ); + assert_eq!( + cost.path(), + Route { + path: Path::Typed, + fresh: true + } + ); + assert_eq!( + cost.path(), + Route { + path: Path::Typed, + fresh: false + } + ); + } + + #[test] + fn density_matches_both_gates() { + for rows in 0..70 { + for local in 0..=rows { + let full = local == rows; + assert_eq!(Density::sparse(local, rows), !full && local * 4 < rows); + } + } + } +} diff --git a/core/engine/src/compiled/core/variants.rs b/core/engine/src/compiled/core/variants.rs new file mode 100644 index 00000000..62a2fe93 --- /dev/null +++ b/core/engine/src/compiled/core/variants.rs @@ -0,0 +1,105 @@ +use std::sync::RwLock; + +pub(crate) struct Variants { + cap: usize, + list: RwLock>, +} + +impl Variants { + pub(crate) fn new(cap: usize) -> Self { + Self { + cap, + list: RwLock::new(Vec::new()), + } + } + + pub(crate) fn find_map(&self, find: impl FnMut(&V) -> Option) -> Option { + self.list + .read() + .ok() + .and_then(|list| list.iter().find_map(find)) + } + + pub(crate) fn keep(&self, variant: V) { + if let Ok(mut list) = self.list.write() { + if list.len() < self.cap { + list.push(variant); + } + } + } + + pub(crate) fn get_or_build( + &self, + find: impl Fn(&V) -> Option, + build: impl FnOnce() -> V, + overflow: impl FnOnce() -> V, + ) -> Option { + if let Some(found) = self.find_map(&find) { + return Some(found); + } + let Ok(mut list) = self.list.write() else { + return find(&overflow()); + }; + if let Some(found) = list.iter().find_map(&find) { + return Some(found); + } + let variant = match list.len() < self.cap { + true => build(), + false => overflow(), + }; + let found = find(&variant); + list.push(variant); + found + } +} + +#[cfg(test)] +mod tests { + use super::Variants; + use std::cell::Cell; + + #[test] + fn kept_variants_replay_in_insertion_order_up_to_the_cap() { + let variants: Variants<(u32, &str)> = Variants::new(2); + variants.keep((1, "a")); + variants.keep((1, "b")); + variants.keep((2, "c")); + assert_eq!( + variants.find_map(|&(key, name)| (key == 1).then_some(name)), + Some("a") + ); + assert_eq!( + variants.find_map(|&(key, name)| (key == 2).then_some(name)), + None + ); + } + + #[test] + fn built_variants_are_cached_and_overflow_is_cached_too() { + let variants: Variants<(u32, u32)> = Variants::new(1); + let built = Cell::new(0); + let find = |key: u32| move |&(k, v): &(u32, u32)| (k == key).then_some(v); + let build = |key: u32| { + built.set(built.get() + 1); + (key, key * 10) + }; + assert_eq!( + variants.get_or_build(find(1), || build(1), || (1, 0)), + Some(10) + ); + assert_eq!( + variants.get_or_build(find(1), || build(1), || (1, 0)), + Some(10) + ); + assert_eq!(built.get(), 1); + assert_eq!( + variants.get_or_build(find(2), || build(2), || (2, 0)), + Some(0) + ); + assert_eq!( + variants.get_or_build(find(2), || build(2), || (2, 99)), + Some(0) + ); + assert_eq!(built.get(), 1); + } +} diff --git a/core/engine/src/compiled/exact/graph/expression.rs b/core/engine/src/compiled/exact/graph/expression.rs new file mode 100644 index 00000000..c7189881 --- /dev/null +++ b/core/engine/src/compiled/exact/graph/expression.rs @@ -0,0 +1,48 @@ +use super::{Ctx, Row}; +use crate::decision_graph::tracer::ExpressionNodeTraceItem; +use crate::nodes::expression::ExpressionNodeTrace; +use crate::nodes::NodeResult; +use std::rc::Rc; +use zen_expression::variable::Variable; +use zen_types::decision::ExpressionNodeContent; + +impl Row<'_> { + pub(crate) fn expression(self, content: &ExpressionNodeContent) -> NodeResult { + let mut ctx = Ctx::::new(self); + let result = Variable::empty_object(); + let mut session = ctx.row.session(); + + for expression in content.expressions.iter() { + if expression.key.is_empty() || expression.value.is_empty() { + continue; + } + + let value = match session.run_standard(&expression.value) { + Ok(value) => value, + Err(_) => { + return Err(ctx.error(crate::compiled::exact::Failure::expression( + &expression.value, + ))) + } + }; + let value = match expression.value.contains('$') { + true => value.deep_clone(), + false => value, + }; + ctx.trace(|trace| { + trace.insert( + Rc::from(&*expression.key), + ExpressionNodeTraceItem { + result: value.clone(), + }, + ); + }); + + session.insert_dollar(&expression.key, value.clone()); + + result.dot_insert(&expression.key, value); + } + + ctx.success(result) + } +} diff --git a/core/engine/src/compiled/exact/graph/mod.rs b/core/engine/src/compiled/exact/graph/mod.rs new file mode 100644 index 00000000..159a35c2 --- /dev/null +++ b/core/engine/src/compiled/exact/graph/mod.rs @@ -0,0 +1,129 @@ +mod expression; +mod transform; + +use crate::compiled::exact::RowTable; +use crate::nodes::decision_table::index::TableIndex; +use crate::nodes::{NodeError, NodeResponse, NodeResult}; +use std::future::Future; +use std::sync::Arc; +use std::task::{Context, Poll, Waker}; +use zen_expression::lane::{Programs, Session}; +use zen_expression::variable::{ToVariable, Variable}; +use zen_types::decision::{DecisionNode, DecisionNodeKind, TransformAttributes}; + +#[derive(Clone)] +pub(crate) struct Row<'a> { + pub(crate) id: &'a Arc, + pub(crate) input: Variable, + pub(crate) nodes: Option, + pub(crate) programs: Option<&'a Arc>, + pub(crate) trace: bool, +} + +pub(crate) struct Ctx<'a, T> { + pub(crate) row: Row<'a>, + pub(crate) trace: Option, +} + +impl<'a> Row<'a> { + pub(crate) fn session(&self) -> Session { + let mut session = + Session::with_environment(self.input.clone()).with_programs(self.programs.cloned()); + if let Some(nodes) = &self.nodes { + session.set_local(Variable::nodes_key(), nodes.clone()); + } + + session + } + + pub(crate) fn with_input(&self, input: Variable) -> Self { + Self { + input, + ..self.clone() + } + } + + pub(crate) async fn node( + self, + node: &'a DecisionNode, + index: Option<&'a TableIndex>, + transforms: bool, + ) -> NodeResult { + let plain = TransformAttributes::default(); + match &node.kind { + DecisionNodeKind::ExpressionNode { content } => { + let attributes = match transforms { + true => &content.transform_attributes, + false => &plain, + }; + self.transform(attributes, |input, _| { + let row = self.with_input(input); + async move { row.expression(content) } + }) + .await + } + DecisionNodeKind::DecisionTableNode { content } => { + let attributes = match transforms { + true => &content.transform_attributes, + false => &plain, + }; + self.transform(attributes, |input, _| { + let row = self.with_input(input); + async move { RowTable::graph(row, content, index) } + }) + .await + } + _ => Ok(NodeResponse { + output: Variable::Null, + trace_data: None, + }), + } + } + + pub(crate) fn now( + self, + node: &'a DecisionNode, + index: Option<&'a TableIndex>, + transforms: bool, + ) -> NodeResult { + let id = self.id.clone(); + let mut future = std::pin::pin!(self.node(node, index, transforms)); + match future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + { + Poll::Ready(result) => result, + Poll::Pending => Err(NodeError::new(id, "node did not complete")), + } + } +} + +impl<'a, T: Default + ToVariable> Ctx<'a, T> { + pub(crate) fn new(row: Row<'a>) -> Self { + Self { + trace: row.trace.then(T::default), + row, + } + } + + pub(crate) fn trace(&mut self, mutator: impl FnOnce(&mut T)) { + if let Some(trace) = &mut self.trace { + mutator(trace); + } + } + + pub(crate) fn error(&self, source: impl Into>) -> NodeError { + NodeError::traced( + self.row.id.clone(), + self.trace.as_ref().map(ToVariable::to_variable), + source, + ) + } + + pub(crate) fn success(&self, output: Variable) -> NodeResult { + Ok(NodeResponse { + output, + trace_data: self.trace.as_ref().map(ToVariable::to_variable), + }) + } +} diff --git a/core/engine/src/compiled/exact/graph/transform.rs b/core/engine/src/compiled/exact/graph/transform.rs new file mode 100644 index 00000000..3c87ca8c --- /dev/null +++ b/core/engine/src/compiled/exact/graph/transform.rs @@ -0,0 +1,86 @@ +use super::Row; +use crate::nodes::{NodeError, NodeResponse, NodeResult}; +use std::future::Future; +use std::ops::Deref; +use zen_expression::Variable; +use zen_types::decision::{TransformAttributes, TransformExecutionMode}; + +impl Row<'_> { + pub(crate) async fn transform( + &self, + attributes: &TransformAttributes, + evaluate: F, + ) -> NodeResult + where + F: Fn(Variable, bool) -> Fut, + Fut: Future, + { + let mut trace = self.trace.then_some(Variable::Null); + let input = match &attributes.input_field { + None => self.input.clone(), + Some(input_field) => { + let mut session = self.session(); + session.run_standard(input_field.deref()).map_err(|err| { + self.fault(&trace, crate::compiled::exact::Failure::input(err)) + })? + } + }; + + let output = match attributes.execution_mode { + TransformExecutionMode::Single => { + let response = evaluate(input, false).await?; + if let Some(td) = response.trace_data { + if let Some(t) = &mut trace { + *t = td; + } + } + + response.output + } + TransformExecutionMode::Loop => { + let input_array_ref = input + .as_array() + .ok_or_else(|| self.fault(&trace, "Expected an array".to_string()))?; + let input_array = input_array_ref.borrow().clone(); + if let Some(t) = &mut trace { + *t = Variable::from_array(Vec::with_capacity(input_array.len())); + } + + let mut output_array = Vec::with_capacity(input_array.len()); + for (index, input) in input_array.iter().enumerate() { + let has_more = index < input_array.len() - 1; + let response = evaluate(input.clone(), has_more).await?; + if let Some(td) = response.trace_data { + if let Some(Variable::Array(arr)) = &trace { + arr.borrow_mut().push(td); + } + } + + output_array.push(crate::compiled::exact::Attributes::item( + attributes.pass_through, + input, + response.output, + )); + } + + Variable::from_array(output_array) + } + }; + + let output = crate::compiled::exact::Attributes::finish( + attributes.output_path.as_deref(), + attributes.pass_through, + &self.input, + output, + ); + + Ok(NodeResponse { + output, + trace_data: trace, + }) + } + + fn fault(&self, trace: &Option, message: String) -> NodeError { + NodeError::traced(self.id.clone(), trace.clone(), message) + } +} diff --git a/core/engine/src/compiled/exact/mod.rs b/core/engine/src/compiled/exact/mod.rs new file mode 100644 index 00000000..ed311722 --- /dev/null +++ b/core/engine/src/compiled/exact/mod.rs @@ -0,0 +1,51 @@ +pub(crate) mod graph; +pub(super) mod policy; +mod table; + +pub(crate) use table::RowTable; +use zen_expression::Variable; + +pub(crate) struct Failure; + +impl Failure { + pub const EXPRESSION: &'static str = "Failed to evaluate expression"; + + pub fn expression(source: &str) -> String { + format!(r#"{}: "{source}""#, Self::EXPRESSION) + } + + pub fn input(error: impl std::fmt::Display) -> String { + format!("{}: {error}", Self::EXPRESSION) + } +} + +pub(crate) struct Attributes; + +impl Attributes { + pub fn item(pass_through: bool, item: &Variable, output: Variable) -> Variable { + match pass_through { + true => item.clone().merge_clone(&output), + false => output, + } + } + + pub fn finish( + output_path: Option<&str>, + pass_through: bool, + input: &Variable, + output: Variable, + ) -> Variable { + let output = match output_path { + Some(path) => { + let wrapped = Variable::empty_object(); + wrapped.dot_insert(path, output); + wrapped + } + None => output, + }; + match pass_through { + true => input.clone().merge_clone(&output), + false => output, + } + } +} diff --git a/core/engine/src/compiled/exact/policy/assertion.rs b/core/engine/src/compiled/exact/policy/assertion.rs new file mode 100644 index 00000000..1372f870 --- /dev/null +++ b/core/engine/src/compiled/exact/policy/assertion.rs @@ -0,0 +1,46 @@ +use zen_expression::variable::Variable; + +use super::Exact; +use crate::policy::blocks::{AssertionIr, ExecutionError}; +use crate::workspace::types::{BlockTrace, ConditionTrace}; + +impl Exact<'_> { + pub(crate) fn execute_assertion( + &mut self, + ir: &AssertionIr, + ) -> Result { + let mut traces: Vec = Vec::new(); + let result = self.evaluate_conditions(ir, &mut traces)?; + + if !ir.output.is_empty() { + self.site.write(&ir.output, Variable::Bool(result)); + } + + Ok(BlockTrace::Assertion { + result, + conditions: traces, + }) + } + + fn evaluate_conditions( + &mut self, + ir: &AssertionIr, + traces: &mut Vec, + ) -> Result { + let mut results = Vec::with_capacity(ir.conditions.len()); + for condition in &ir.conditions { + let cond_result = self + .session + .run_standard(&condition.expression) + .map_err(|e| self.site.expression_error(&condition.expression, e))? + .as_bool() + .unwrap_or(false); + traces.push(ConditionTrace { + id: condition.id.clone(), + result: cond_result, + }); + results.push(cond_result); + } + Ok(ir.fold(&results)) + } +} diff --git a/core/engine/src/compiled/exact/policy/expression.rs b/core/engine/src/compiled/exact/policy/expression.rs new file mode 100644 index 00000000..6467a32c --- /dev/null +++ b/core/engine/src/compiled/exact/policy/expression.rs @@ -0,0 +1,31 @@ +use zen_expression::variable::Variable; + +use super::Exact; +use crate::policy::blocks::{ExecutionError, ExpressionIr}; +use crate::workspace::types::BlockTrace; + +impl Exact<'_> { + pub(crate) fn execute_expression( + &mut self, + ir: &ExpressionIr, + ) -> Result { + if ir.key.is_empty() || ir.value.is_empty() { + return Ok(BlockTrace::Expression { + property: ir.key.clone(), + value: Variable::Null, + }); + } + + let result = self + .session + .run_standard(&ir.value) + .map_err(|e| self.site.expression_error(&ir.value, e))?; + let traced = self.site.trace.then(|| result.deep_clone()); + self.site.write(&ir.key, result); + + Ok(BlockTrace::Expression { + property: ir.key.clone(), + value: traced.unwrap_or(Variable::Null), + }) + } +} diff --git a/core/engine/src/compiled/exact/policy/matching.rs b/core/engine/src/compiled/exact/policy/matching.rs new file mode 100644 index 00000000..33452984 --- /dev/null +++ b/core/engine/src/compiled/exact/policy/matching.rs @@ -0,0 +1,76 @@ +use std::sync::Arc; + +use zen_expression::variable::Variable; + +use super::Exact; +use crate::policy::blocks::{ExecutionError, MatchIr, MatchSelection}; +use crate::workspace::types::{BlockTrace, ConditionTrace}; + +impl Exact<'_> { + pub(crate) fn select_match(&mut self, ir: &MatchIr) -> Result { + let mut arms: Vec = Vec::new(); + let mut matched_arm: Option> = None; + + for arm in &ir.arms { + if matched_arm.is_some() && !self.site.extras { + break; + } + let matches = if arm.condition.is_empty() { + true + } else { + match self.session.run_standard(&arm.condition) { + Ok(value) => value.as_bool().unwrap_or(false), + Err(_) if self.site.extras && matched_arm.is_some() => false, + Err(e) => return Err(self.site.expression_error(&arm.condition, e)), + } + }; + arms.push(ConditionTrace { + id: arm.id.clone(), + result: matches, + }); + if matches && matched_arm.is_none() { + matched_arm = Some(arm.id.clone()); + } + } + + Ok(MatchSelection { matched_arm, arms }) + } + + pub(crate) fn commit_match( + &mut self, + ir: &MatchIr, + selection: &MatchSelection, + ) -> Result { + let matched = selection + .matched_arm + .as_ref() + .and_then(|id| ir.arms.iter().find(|a| &a.id == id)); + let value = match matched { + Some(arm) if !arm.value.is_empty() => self + .session + .run_standard(&arm.value) + .map_err(|e| self.site.expression_error(&arm.value, e))?, + _ => Variable::Null, + }; + + let traced = self.site.trace.then(|| value.deep_clone()); + if !ir.key.is_empty() { + self.site.write(&ir.key, value); + } + + Ok(BlockTrace::Match { + matched_arm: selection.matched_arm.clone(), + value: traced.unwrap_or(Variable::Null), + arms: if self.site.trace { + selection.arms.clone() + } else { + Vec::new() + }, + }) + } + + pub(crate) fn execute_match(&mut self, ir: &MatchIr) -> Result { + let selection = self.select_match(ir)?; + self.commit_match(ir, &selection) + } +} diff --git a/core/engine/src/compiled/exact/policy/mod.rs b/core/engine/src/compiled/exact/policy/mod.rs new file mode 100644 index 00000000..4896254a --- /dev/null +++ b/core/engine/src/compiled/exact/policy/mod.rs @@ -0,0 +1,50 @@ +mod assertion; +mod expression; +mod matching; + +use zen_expression::lane::Session; + +use crate::compiled::exact::RowTable; +use crate::policy::blocks::{Block, BlockKind, DecisionTableIr, ExecutionError, TableSelection}; +use crate::policy::host::Site; +use crate::workspace::types::BlockTrace; + +pub(crate) struct Exact<'e> { + pub(crate) session: &'e mut Session, + pub(crate) site: &'e Site<'e>, +} + +impl Exact<'_> { + pub(crate) fn execute(&mut self, rule: &Block) -> Result { + match &rule.kind { + BlockKind::Assertion(a) => self.execute_assertion(a), + BlockKind::DecisionTable(d) => self.execute_table(d), + BlockKind::Expression(e) => self.execute_expression(e), + BlockKind::Match(m) => self.execute_match(m), + } + } +} + +impl Exact<'_> { + pub(crate) fn select_table( + &mut self, + ir: &DecisionTableIr, + ) -> Result { + RowTable::new(self.session, &ir.inputs, ir.table_index(), Some(self.site)) + .select(ir, self.site.extras) + } + + pub(crate) fn commit_table( + &mut self, + ir: &DecisionTableIr, + selection: &TableSelection, + ) -> Result { + RowTable::new(self.session, &ir.inputs, None, Some(self.site)) + .commit(ir, selection, self.site) + } + + fn execute_table(&mut self, ir: &DecisionTableIr) -> Result { + let selection = self.select_table(ir)?; + self.commit_table(ir, &selection) + } +} diff --git a/core/engine/src/compiled/exact/table.rs b/core/engine/src/compiled/exact/table.rs new file mode 100644 index 00000000..be1ce887 --- /dev/null +++ b/core/engine/src/compiled/exact/table.rs @@ -0,0 +1,506 @@ +use crate::compiled::exact::graph::{Ctx, Row}; +use crate::decision_graph::tracer::{DecisionTableNodeTrace, DecisionTableRowTrace}; +use crate::nodes::decision_table::index::TableIndex; +use crate::nodes::{NodeResponse, NodeResult}; +use crate::policy::blocks::{DecisionTableIr, ExecutionError, TableSelection}; +use crate::policy::host::Site; +use crate::workspace::types::{BlockTrace, DecisionTableExtras}; +use ahash::{HashMap, HashSet}; +use base64::Engine as _; +use fixedbitset::FixedBitSet; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::Session; +use zen_expression::IsolateError; +use zen_types::decision::{ + DecisionTableContent, DecisionTableHitPolicy, DecisionTableInputField, DecisionTableOutputField, +}; +use zen_types::variable::Variable; + +pub(crate) type Rule = HashMap, Arc>; +type Cells = (Option, Vec<(usize, Variable)>); + +pub(crate) struct RowTable<'t, 's> { + pub session: &'t mut Session, + pub inputs: &'t [DecisionTableInputField], + index: Option<&'t TableIndex>, + site: Option<&'t Site<'s>>, + refs: Vec>, +} + +impl<'t, 's> RowTable<'t, 's> { + pub fn new( + session: &'t mut Session, + inputs: &'t [DecisionTableInputField], + index: Option<&'t TableIndex>, + site: Option<&'t Site<'s>>, + ) -> Self { + Self { + session, + inputs, + index, + site, + refs: vec![None; inputs.len()], + } + } + + fn fail( + &self, + source: &Arc, + error: IsolateError, + lenient: T, + ) -> Result { + match self.site { + Some(site) => Err(site.expression_error(source, error)), + None => Ok(lenient), + } + } + + fn field(&self, col: usize) -> Option<&'t Arc> { + self.inputs + .get(col)? + .field + .as_ref() + .filter(|f| !f.is_empty()) + } + + pub fn reference(&mut self, col: usize) -> Result, ExecutionError> { + if let Some(value) = &self.refs[col] { + return Ok(Some(value.shallow_clone())); + } + let Some(field) = self.field(col) else { + return Ok(None); + }; + match self.session.run_standard(field) { + Ok(value) => { + self.refs[col] = Some(value.shallow_clone()); + Ok(Some(value)) + } + Err(error) => self.fail(field, error, None), + } + } + + fn bind(&mut self, col: usize) -> Result { + let Some(value) = self.reference(col)? else { + return Ok(false); + }; + match self.session.set_reference_value(value) { + Ok(()) => Ok(true), + Err(error) => self.fail( + self.field(col).unwrap_or(&self.inputs[col].id), + error, + false, + ), + } + } + + pub fn candidates(&mut self) -> Result, ExecutionError> { + let Some(index) = self.index else { + return Ok(None); + }; + let mut acc: Option = None; + for (col, column) in index.columns.iter().enumerate() { + let Some(column) = column else { + continue; + }; + if self.field(col).is_none() { + continue; + } + let Some(value) = self.reference(col)? else { + return Ok(None); + }; + if self.site.is_none() { + let _ = self.session.set_reference_value(value.shallow_clone()); + } + if matches!(value, Variable::Dynamic(_)) { + return Ok(None); + } + let hit = column.rows_for(&value); + match &mut acc { + None => { + let mut first = column.fallback.clone(); + if let Some(hit) = hit { + first.union_with(hit); + } + acc = Some(first); + } + Some(acc) => { + let fallback = column.fallback.as_slice(); + let hit = hit.map(FixedBitSet::as_slice).unwrap_or_default(); + for (i, word) in acc.as_mut_slice().iter_mut().enumerate() { + *word &= fallback.get(i).copied().unwrap_or(0) + | hit.get(i).copied().unwrap_or(0); + } + } + } + } + Ok(acc) + } + + pub fn cell(&mut self, col: usize, rule: &Rule) -> Result { + let Some(cell) = rule.get(&self.inputs[col].id).filter(|c| !c.is_empty()) else { + return Ok(true); + }; + if self.field(col).is_none() { + return match self.session.run_standard(cell) { + Ok(result) => Ok(result.as_bool().unwrap_or(false)), + Err(error) => self.fail(cell, error, false), + }; + } + if !self.bind(col)? { + return Ok(false); + } + match self.session.run_unary(cell) { + Ok(pass) => Ok(pass), + Err(error) => self.fail(cell, error, false), + } + } + + pub fn matches( + &mut self, + row: usize, + rule: &Rule, + pruned: bool, + ) -> Result { + for col in 0..self.inputs.len() { + if pruned && self.index.is_some_and(|index| index.decides(col, row)) { + if self.site.is_none() + && rule + .get(&self.inputs[col].id) + .is_some_and(|c| !c.is_empty()) + { + self.bind(col)?; + } + continue; + } + if !self.cell(col, rule)? { + return Ok(false); + } + } + Ok(true) + } + + pub fn each(&mut self, rule: &Rule, unreached: bool) -> Result, ExecutionError> { + let mut failed = false; + (0..self.inputs.len()) + .map(|col| { + let passed = match self.cell(col, rule) { + Ok(passed) => passed, + Err(_) if unreached || failed => false, + Err(e) => return Err(e), + }; + failed |= !passed; + Ok(passed) + }) + .collect() + } + + pub fn output(&mut self, cell: &Arc) -> Result, ExecutionError> { + match self.session.run_standard(cell) { + Ok(value) => Ok(Some(value)), + Err(error) => self.fail(cell, error, None), + } + } +} + +impl RowTable<'_, '_> { + fn hits( + &mut self, + rules: &[Rule], + candidates: &Option, + from: usize, + ) -> Result, ExecutionError> { + for (row, rule) in rules.iter().enumerate().skip(from) { + if candidates.as_ref().is_some_and(|c| !c.contains(row)) { + continue; + } + if self.matches(row, rule, candidates.is_some())? { + return Ok(Some(row)); + } + } + Ok(None) + } + + fn row( + &mut self, + outputs: &[DecisionTableOutputField], + rule: &Rule, + scalars: bool, + split: bool, + ) -> Option { + let object = scalars.then(Variable::empty_object); + let mut lists = Vec::new(); + for (column, output) in outputs.iter().enumerate() { + let (path, collect) = output.write_path(); + let collect = collect && split; + if path.is_empty() || (!collect && !scalars) { + continue; + } + let Some(cell) = rule.get(&output.id).filter(|c| !c.is_empty()) else { + continue; + }; + let value = self.output(cell).ok()??.deep_clone(); + match (collect, &object) { + (true, _) => lists.push((column, value)), + (false, Some(object)) => { + object.dot_insert(path, value); + } + (false, None) => {} + } + } + Some((object, lists)) + } + + fn trace(&mut self, index: usize, rule: &Rule) -> DecisionTableRowTrace { + let mut expressions: HashMap, Rc> = HashMap::default(); + let mut reference_map: HashMap, Variable> = HashMap::default(); + expressions.insert( + Rc::from("_id"), + rule.get("_id") + .map_or_else(|| Rc::from(""), |id| Rc::from(id.as_ref())), + ); + if let Some(description) = rule.get("_description") { + expressions.insert(Rc::from("_description"), Rc::from(description.as_ref())); + } + for (col, input) in self.inputs.iter().enumerate() { + let (Some(cell), Some(field)) = (rule.get(&input.id), &input.field) else { + continue; + }; + if let Ok(Some(reference)) = self.reference(col) { + reference_map.insert(Rc::from(field.as_ref()), reference); + } + expressions.insert( + Rc::from(format!("{field}[{}]", input.id).as_str()), + Rc::from(cell.as_ref()), + ); + } + DecisionTableRowTrace { + index, + reference_map, + rule: expressions, + } + } + + pub(crate) fn graph( + row: Row, + content: &DecisionTableContent, + index: Option<&TableIndex>, + ) -> NodeResult { + let mut ctx = Ctx::::new(row); + let mut session = ctx.row.session(); + let traced = ctx.row.trace; + let mut table = RowTable::new( + &mut session, + &content.inputs, + index.filter(|_| !traced), + None, + ); + let candidates = table.candidates().ok().flatten(); + let first = matches!(content.hit_policy, DecisionTableHitPolicy::First); + let split = first && content.outputs.iter().any(|output| output.write_path().1); + let mut scalars: Option = None; + let mut items = Vec::new(); + let mut lists: Vec> = vec![Vec::new(); content.outputs.len()]; + let mut traces = Vec::new(); + let slot = |column: usize| { + let path = content.outputs[column].write_path().0; + content + .outputs + .iter() + .position(|o| o.write_path() == (path, true)) + .unwrap_or(column) + }; + let mut from = 0; + while let Ok(Some(at)) = table.hits(&content.rules, &candidates, from) { + from = at + 1; + let rule = &content.rules[at]; + let Some((object, values)) = + table.row(&content.outputs, rule, scalars.is_none() || !split, split) + else { + continue; + }; + if traced { + traces.push(table.trace(at, rule)); + } + match (first, split, object) { + (true, false, Some(object)) => { + ctx.trace(|t| { + *t = traces.pop().map_or_else( + DecisionTableNodeTrace::default, + DecisionTableNodeTrace::FirstHit, + ) + }); + return ctx.success(object); + } + (false, _, Some(object)) => items.push(object), + (_, _, object) => { + scalars = scalars + .or(object) + .or_else(|| Some(Variable::empty_object())); + values + .into_iter() + .for_each(|(column, value)| lists[slot(column)].push(value)); + } + } + } + if first && !split { + return Ok(NodeResponse { + output: Variable::Null, + trace_data: None, + }); + } + ctx.trace(|t| *t = DecisionTableNodeTrace::Collect(traces)); + let output = match split { + false => Variable::from_array(items), + true => { + let output = scalars.unwrap_or_else(Variable::empty_object); + for (column, output_field) in content.outputs.iter().enumerate() { + let (path, collect) = output_field.write_path(); + if collect && !path.is_empty() && slot(column) == column { + output.dot_insert( + path, + Variable::from_array(std::mem::take(&mut lists[column])), + ); + } + } + output + } + }; + ctx.success(output) + } + + pub(crate) fn select( + &mut self, + ir: &DecisionTableIr, + extras: bool, + ) -> Result { + let active: Vec<_> = ir.outputs.iter().filter(|c| !c.field.is_empty()).collect(); + let has_collect = active.iter().any(|c| c.collect); + let mut pending = active.iter().filter(|c| !c.collect).count(); + let mut taken: Vec = vec![false; active.len()]; + let mut matched_rows: Vec = Vec::new(); + let mut used_cells: Vec<(u32, Arc)> = Vec::new(); + let width = ir.inputs.len().div_ceil(8); + let mut input_bits: Option> = extras.then(|| vec![0u8; ir.rules.len() * width]); + let candidates = match input_bits { + None => self.candidates()?, + Some(_) => None, + }; + for (row, rule) in ir.rules.iter().enumerate() { + let satisfied = !has_collect && pending == 0 && !matched_rows.is_empty(); + if satisfied && !extras { + break; + } + let hit = match input_bits.as_mut() { + Some(bits) => { + let each = self.each(rule, satisfied)?; + each.iter() + .enumerate() + .filter(|(_, p)| **p) + .for_each(|(col, _)| bits[row * width + col / 8] |= 1 << (col % 8)); + each.iter().all(|p| *p) + } + None => { + !candidates.as_ref().is_some_and(|c| !c.contains(row)) + && self.matches(row, rule, candidates.is_some())? + } + }; + if !hit || satisfied { + continue; + } + matched_rows.push(row as u32); + for (at, col) in active.iter().enumerate() { + if rule.get(&col.id).filter(|c| !c.is_empty()).is_none() + || (!col.collect && taken[at]) + { + continue; + } + if !col.collect { + taken[at] = true; + pending -= 1; + } + used_cells.push((row as u32, col.id.clone())); + } + } + Ok(TableSelection { + matched_rows, + used_cells, + input_bits, + }) + } + + pub(crate) fn commit( + &mut self, + ir: &DecisionTableIr, + selection: &TableSelection, + site: &Site, + ) -> Result { + let used: HashSet<(u32, &str)> = selection + .used_cells + .iter() + .map(|(row, col)| (*row, col.as_ref())) + .collect(); + let mut collected: HashMap, Vec> = HashMap::default(); + let mut written: HashSet> = HashSet::default(); + for col in ir + .outputs + .iter() + .filter(|col| col.collect && !col.field.is_empty()) + { + collected.entry(col.field.clone()).or_default(); + } + let mut evaluations: Vec, Variable>> = Vec::new(); + for &row in &selection.matched_rows { + let Some(rule) = ir.rules.get(row as usize) else { + continue; + }; + let mut outputs: HashMap, Variable> = HashMap::default(); + for col in &ir.outputs { + let Some(cell) = rule + .get(&col.id) + .filter(|c| !c.is_empty() && used.contains(&(row, col.id.as_ref()))) + else { + continue; + }; + let value = self.output(cell)?.unwrap_or(Variable::Null); + if site.trace { + outputs.insert(col.field.clone(), value.deep_clone()); + } + match col.collect { + true => collected.entry(col.field.clone()).or_default().push(value), + false => { + site.write(&col.field, value); + written.insert(col.field.clone()); + } + } + } + if site.trace { + evaluations.push(outputs); + } + } + for col in ir + .outputs + .iter() + .filter(|col| !col.collect && !col.field.is_empty()) + { + if written.insert(col.field.clone()) { + site.write(&col.field, Variable::Null); + } + } + for col in &ir.outputs { + if let Some(values) = collected.remove(&col.field) { + site.write(&col.field, Variable::from_array(values)); + } + } + Ok(BlockTrace::DecisionTable { + matched_rows: selection.matched_rows.clone(), + evaluations, + extras: selection + .input_bits + .as_ref() + .map(|bits| DecisionTableExtras { + input_pass: base64::engine::general_purpose::STANDARD.encode(bits), + }), + }) + } +} diff --git a/core/engine/src/compiled/graph/batched.rs b/core/engine/src/compiled/graph/batched.rs new file mode 100644 index 00000000..c72b158f --- /dev/null +++ b/core/engine/src/compiled/graph/batched.rs @@ -0,0 +1,276 @@ +use super::call::{Call, Load}; +use super::{CompiledGraph, Host, Nesting, Step}; +use crate::loader::LoaderError; +use crate::model::GraphContent; +use crate::nodes::custom::{CustomDecisionNode, CustomNodeRequest}; +use crate::nodes::{NodeError, NodeHandlerExtensions}; +use crate::EvaluationError; +use std::error::Error; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::Variable; +use zen_types::decision::{ + CustomNodeContent, DecisionNodeContent, TransformAttributes, TransformExecutionMode, +}; + +pub(crate) enum Failure { + Loader(LoaderError), + Kind(&'static str), + Compiled(Arc), +} + +impl Failure { + fn copy(&self, key: &str) -> Option> { + match self { + Failure::Loader(LoaderError::NotFound(missing)) => { + Some(LoaderError::NotFound(missing.clone()).into()) + } + Failure::Loader(LoaderError::Internal { .. }) => None, + Failure::Kind(kind) => Some(Call::kind(key, kind)), + Failure::Compiled(graph) => Call::compiled(graph).err(), + } + } + + fn source(self, key: &str) -> Box { + match self { + Failure::Loader(error) => error.into(), + Failure::Kind(kind) => Call::kind(key, kind), + Failure::Compiled(graph) => match Call::compiled(&graph) { + Err(source) => source, + Ok(_) => Call::uncompiled(), + }, + } + } + + pub(super) fn shared(self, step: &Step, key: &str) -> Rc { + Rc::new(NodeError::new(step.node.id.clone(), self.source(key)).into()) + } + + fn errors( + &self, + step: &Step, + key: &str, + count: usize, + ) -> Option>> { + (0..count) + .map(|_| { + self.copy(key) + .map(|source| Err(NodeError::new(step.node.id.clone(), source))) + }) + .collect() + } +} + +impl CompiledGraph { + pub(super) fn batchable(attributes: &TransformAttributes, count: usize) -> bool { + count >= 2 + && attributes.input_field.is_none() + && matches!(attributes.execution_mode, TransformExecutionMode::Single) + } + + pub(super) async fn resolve( + content: &DecisionNodeContent, + extensions: &NodeHandlerExtensions, + ) -> Result, Failure> { + Self::resolve_key(&content.key, extensions).await + } + + pub(super) async fn resolve_key( + key: &str, + extensions: &NodeHandlerExtensions, + ) -> Result, Failure> { + let call = Call { + key, + extensions, + max_depth: 0, + iteration: 0, + }; + match call.load().await { + Err(error) => Err(Failure::Loader(error)), + Ok(Load::Kind(kind)) => Err(Failure::Kind(kind)), + Ok(Load::Graph(graph)) => match Call::compiled(&graph) { + Ok(_) => Ok(graph), + Err(_) => Err(Failure::Compiled(graph)), + }, + } + } + + #[allow(clippy::too_many_arguments)] + pub(super) async fn batch( + step: &Step, + content: &DecisionNodeContent, + graph: &Arc, + inputs: &[Variable], + nodes: &[Option], + extensions: &NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + ) -> Vec> { + let attributes = &content.transform_attributes; + Self::nested_results( + step, content, graph, inputs, nodes, extensions, max_depth, iteration, + ) + .await + .into_iter() + .zip(inputs) + .map(|(result, input)| { + result.map(|value| { + crate::compiled::exact::Attributes::finish( + attributes.output_path.as_deref(), + attributes.pass_through, + input, + value, + ) + }) + }) + .collect() + } + + #[allow(clippy::too_many_arguments)] + pub(super) async fn nested_results( + step: &Step, + content: &DecisionNodeContent, + graph: &Arc, + inputs: &[Variable], + nodes: &[Option], + extensions: &NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + ) -> Vec> { + let fault = |source: Box| NodeError::new(step.node.id.clone(), source); + let compiled = match Call::compiled(graph) { + Ok(compiled) => compiled, + Err(_) => { + return inputs + .iter() + .map(|_| { + Err(fault( + Call::compiled(graph).err().unwrap_or_else(Call::uncompiled), + )) + }) + .collect() + } + }; + if iteration.saturating_add(1) >= max_depth { + return inputs + .iter() + .map(|_| { + Err(fault( + EvaluationError::DepthLimitExceeded.to_string().into(), + )) + }) + .collect(); + } + let call = Call { + key: &content.key, + extensions, + max_depth, + iteration, + }; + let content = compiled.schemas(graph, extensions.loader()).await; + let extensions = NodeHandlerExtensions { + function_runtime: Default::default(), + ..call.sub_extensions(&content) + }; + let parents: Vec> = (0..inputs.len()) + .map(|row| nodes.get(row).cloned().flatten()) + .collect(); + let nesting = Nesting { + parents: Some(&parents), + iteration: iteration + 1, + completed: None, + }; + let state = Box::pin(compiled.run( + Host { + content: &content, + extensions: &extensions, + max_depth, + }, + inputs, + nesting, + )) + .await; + state + .errors + .into_vec() + .into_iter() + .zip(state.results) + .map(|(error, result)| match error { + Some(error) => Err(fault(error.to_string().into())), + None => Ok(result.unwrap_or_else(Variable::empty_object)), + }) + .collect() + } + + pub(super) async fn nested( + step: &Step, + content: &DecisionNodeContent, + inputs: &[Variable], + nodes: &[Option], + extensions: &NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + ) -> Option>> { + let attributes = &content.transform_attributes; + if !Self::batchable(attributes, inputs.len()) { + return None; + } + match Self::resolve(content, extensions).await { + Ok(graph) => Some( + Self::batch( + step, content, &graph, inputs, nodes, extensions, max_depth, iteration, + ) + .await, + ), + Err(failure) => failure.errors(step, &content.key, inputs.len()), + } + } + + pub(super) async fn custom( + step: &Step, + content: &CustomNodeContent, + inputs: Vec, + nodes: Vec>, + extensions: &NodeHandlerExtensions, + ) -> Vec> { + let adapter = extensions.custom_node(); + let node = CustomDecisionNode { + id: step.node.id.clone(), + name: step.node.name.clone(), + kind: content.kind.clone(), + config: content.config.clone(), + }; + let mut nodes = nodes.into_iter(); + let mut results = Vec::with_capacity(inputs.len()); + let mut previous = None; + for input in inputs { + let input = Self::with_nodes(input, nodes.next().flatten()); + let request = CustomNodeRequest { + input: input.clone(), + node: node.clone(), + }; + results.push( + adapter + .handle(request) + .await + .map(|response| response.output), + ); + previous = Some(input); + } + drop(previous); + results + } + + fn with_nodes(input: Variable, nodes: Option) -> Variable { + let (Some(nodes), Variable::Object(object)) = (nodes, &input) else { + return input; + }; + if Rc::strong_count(object) == 1 && Rc::weak_count(object) == 0 { + object.borrow_mut().insert(Variable::nodes_key(), nodes); + return input; + } + let mut map = object.borrow().clone(); + map.insert(Variable::nodes_key(), nodes); + Variable::from_object(map) + } +} diff --git a/core/engine/src/compiled/graph/call.rs b/core/engine/src/compiled/graph/call.rs new file mode 100644 index 00000000..b9b6dc62 --- /dev/null +++ b/core/engine/src/compiled/graph/call.rs @@ -0,0 +1,185 @@ +use super::traced::Traced; +use super::{CompiledGraph, Host, Nesting}; +use crate::compiled::exact::graph::Row; +use crate::decision_graph::graph::DecisionGraphResponse; +use crate::loader::LoaderError; +use crate::model::GraphContent; +use crate::nodes::{NodeError, NodeHandlerExtensions, NodeResponse, NodeResult}; +use crate::EvaluationError; +use std::cell::{OnceCell, RefCell}; +use std::error::Error; +use std::sync::Arc; +use zen_expression::variable::ToVariable; +use zen_expression::Variable; +use zen_types::decision::TransformAttributes; + +pub(crate) struct Call<'a> { + pub(crate) key: &'a str, + pub(crate) extensions: &'a NodeHandlerExtensions, + pub(crate) max_depth: u8, + pub(crate) iteration: u8, +} + +pub(crate) enum Load { + Graph(Arc), + Kind(&'static str), +} + +pub(crate) type TracedRun = Result>; + +impl Call<'_> { + pub(crate) async fn load(&self) -> Result { + let loader = self.extensions.loader(); + let content = loader.load(self.key).await?; + let kind = content.kind(); + match content.into_graph_arc() { + Some(graph) => Ok(Load::Graph( + self.extensions + .prepared + .graph(self.key, graph, loader) + .await, + )), + None => Ok(Load::Kind(kind)), + } + } + + pub(super) fn compiled(graph: &GraphContent) -> Result<&CompiledGraph, Box> { + let plan = graph + .compiled_plan + .as_deref() + .ok_or_else(Self::uncompiled)?; + plan.graph().map_err(|invalid| invalid.source()) + } + + pub(super) fn uncompiled() -> Box { + "sub-decision is not compiled".into() + } + + pub(super) fn kind(key: &str, kind: &str) -> Box { + format!("sub-decision '{key}' is a {kind}, expected graph").into() + } + + #[allow(clippy::arc_with_non_send_sync)] + pub(super) fn sub_extensions(&self, content: &GraphContent) -> NodeHandlerExtensions { + NodeHandlerExtensions { + #[cfg(feature = "driver")] + compiled_cache: content.compiled_cache.clone(), + dt_indexes: content.dt_indexes.clone(), + stripped_functions: content.stripped_functions.clone(), + validator_cache: Arc::new(OnceCell::from(content.validator_cache.clone())), + ..self.extensions.clone() + } + } + + pub(crate) async fn run( + &self, + graph: &Arc, + input: Variable, + parent: Option, + ) -> Result> { + let compiled = Self::compiled(graph)?; + let content = compiled.schemas(graph, self.extensions.loader()).await; + let extensions = self.sub_extensions(&content); + let parents = [parent]; + let inputs = [input]; + let nesting = Nesting { + parents: Some(&parents), + iteration: self.iteration + 1, + completed: None, + }; + let state = Box::pin(compiled.run( + Host { + content: &content, + extensions: &extensions, + max_depth: self.max_depth, + }, + &inputs, + nesting, + )) + .await; + let error = state.errors.into_vec().into_iter().next().flatten(); + let result = state.results.into_iter().next().flatten(); + match error { + Some(error) => Err(error.to_string().into()), + None => Ok(result.unwrap_or_else(Variable::empty_object)), + } + } + + pub(crate) async fn traced( + &self, + graph: &Arc, + input: Variable, + parent: Option, + ) -> Result> { + let compiled = Self::compiled(graph)?; + let content = compiled.schemas(graph, self.extensions.loader()).await; + let extensions = self.sub_extensions(&content); + let traced = Traced { + graph: compiled, + content: &content, + extensions: &extensions, + max_depth: self.max_depth, + iteration: self.iteration + 1, + parent, + }; + Ok(Box::pin(traced.evaluate(input)).await) + } + + pub(crate) async fn node(&self, row: Row<'_>, attributes: &TransformAttributes) -> NodeResult { + let loaded: RefCell>> = RefCell::new(None); + let loaded = &loaded; + let id = row.id; + let nodes = &row.nodes; + let traced = row.trace; + row.transform(attributes, |input, _| async move { + let fault = |source: Box, trace: Option| { + NodeError::traced(id.clone(), trace, source) + }; + let blank = traced.then_some(Variable::Null); + let cached = loaded.borrow().clone(); + let graph = match cached { + Some(graph) => graph, + None => match self.load().await { + Err(error) => return Err(fault(error.into(), blank)), + Ok(Load::Kind(kind)) => return Err(fault(Self::kind(self.key, kind), blank)), + Ok(Load::Graph(graph)) => { + *loaded.borrow_mut() = Some(graph.clone()); + graph + } + }, + }; + if !traced { + let output = self + .run(&graph, input, nodes.clone()) + .await + .map_err(|e| fault(e, None))?; + return Ok(NodeResponse { + output, + trace_data: None, + }); + } + match self.traced(&graph, input, nodes.clone()).await { + Err(source) => Err(fault(source, blank)), + Ok(Ok(response)) => Ok(NodeResponse { + output: response.result, + trace_data: Some( + response + .trace + .and_then(|trace| trace.into_graph()) + .as_ref() + .map(ToVariable::to_variable) + .unwrap_or(Variable::Null), + ), + }), + Ok(Err(error)) => { + let trace = match error.as_ref() { + EvaluationError::NodeError { trace, .. } => trace.to_variable(), + _ => Variable::Null, + }; + Err(fault(error.to_string().into(), Some(trace))) + } + } + }) + .await + } +} diff --git a/core/engine/src/compiled/graph/columnar.rs b/core/engine/src/compiled/graph/columnar.rs new file mode 100644 index 00000000..47b05a5f --- /dev/null +++ b/core/engine/src/compiled/graph/columnar.rs @@ -0,0 +1,264 @@ +use crate::compiled::graph::data::{Data, Layer}; +use crate::compiled::graph::plan::PlanOutcome; +use crate::compiled::graph::CompiledGraph; +use crate::compiled::leaf::Bits; +use crate::compiled::leaf::Leaf; +use crate::compiled::leaf::Mask; +use crate::compiled::output::OutputColumn; +use crate::compiled::shred::{Normalizer, Shredder}; +use crate::decision_graph::cleaner::{VariableCleaner, ZEN_RESERVED_PROPERTIES}; +use crate::diagnostics::Paths; +use crate::model::GraphContent; +use crate::nodes::input::dates::DeclaredDates; +use crate::nodes::{NodeError, NodeHandlerExtensions}; +use crate::EvaluationError; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Columns, Dictionary, Values}; +use zen_expression::Variable; + +#[derive(Default)] +pub(crate) struct Admitted<'a> { + pub failures: Vec<(usize, Rc)>, + pub dated: Vec<(usize, Leaf<'a>)>, +} + +pub struct ColumnarOutput<'a> { + pub rows: usize, + pub columns: Vec<(Arc, OutputColumn<'a>)>, + pub errors: Vec>>, + pub(crate) paths: Paths, +} + +impl ColumnarOutput<'_> { + pub(crate) fn from_results( + results: Vec>>, + ) -> Self { + let rows = results.len(); + let (columns, errors) = + Shredder::results(results, |response: &crate::DecisionGraphResponse| { + &response.result + }); + ColumnarOutput { + rows, + columns, + errors: errors + .into_iter() + .map(|error| error.map(Rc::from)) + .collect(), + paths: Paths { + hosted: rows, + ..Paths::default() + }, + } + } + + pub fn row(&self, row: usize) -> Variable { + OutputColumn::row(&self.columns, row) + } + + #[doc(hidden)] + pub fn paths(&self) -> Paths { + self.paths + } + + pub(crate) fn splice( + self, + rows: &[usize], + results: Vec>>, + ) -> Self { + let mut values: Vec>> = (0..self.rows) + .map(|row| match self.errors.get(row).cloned().flatten() { + Some(error) => Err(error), + None => Ok(self.row(row)), + }) + .collect(); + for (&row, result) in rows.iter().zip(results) { + if let Some(slot) = values.get_mut(row) { + *slot = result.map(|response| response.result).map_err(Rc::from); + } + } + let (columns, errors) = Shredder::results(values, |value: &Variable| value); + ColumnarOutput { + rows: self.rows, + columns, + errors, + paths: Paths { + hosted: self.paths.hosted + rows.len(), + ..self.paths + }, + } + } +} + +impl CompiledGraph { + fn input_data<'a>(columns: &Columns<'a>) -> Data<'a> { + let rows = columns.rows; + let mut paths: Vec> = Vec::with_capacity(columns.columns.len()); + let mut leaves: Vec> = Vec::with_capacity(columns.columns.len()); + for (path, column) in &columns.columns { + paths.push(Arc::from(*path)); + leaves.push(Normalizer::input(*column, rows)); + } + let masked = columns + .columns + .iter() + .any(|(_, column)| column.validity.is_some()); + let present = masked.then(|| { + columns + .columns + .iter() + .zip(&leaves) + .map(|((_, column), leaf)| match (leaf, column.validity) { + (Leaf::Input(..), _) => Mask::Valid(leaf.clone()), + (_, Some((bits, offset))) => { + Mask::Bits(Bits::window(bits, offset, rows).into()) + } + (_, None) => Mask::Bits(Bits::ones(rows).into()), + }) + .collect() + }); + let layer = Layer::new(paths.into(), leaves, present); + Data::record(&(0..rows).collect::>(), layer, None) + } + + async fn planned_input<'a>( + &self, + content: &Arc, + extensions: &NodeHandlerExtensions, + columns: &Columns<'_>, + ) -> Option> { + let step = self + .steps + .iter() + .flatten() + .find(|step| matches!(step.kind, crate::compiled::graph::Kind::Input))?; + if !Self::columnar_input(step, content, extensions) { + return None; + } + let validator = Self::validator(step, content, extensions); + if !step.schema && validator.is_none() { + return Some(Admitted::default()); + } + let data = Self::input_data(columns); + let failures = self + .validate_input(step, &data, &[], content, extensions) + .await; + Some(Admitted { + failures: failures + .into_iter() + .map(|(row, message)| { + ( + row, + Rc::new(NodeError::new(step.node.id.clone(), message).into()), + ) + }) + .collect(), + dated: validator + .map(|(_, schema)| Self::dated(&schema, columns)) + .unwrap_or_default(), + }) + } + + fn dated<'a>(schema: &serde_json::Value, columns: &Columns<'_>) -> Vec<(usize, Leaf<'a>)> { + if !DeclaredDates::mentions(schema) { + return Vec::new(); + } + columns + .columns + .iter() + .enumerate() + .filter_map(|(index, (path, column))| { + let schema = + DeclaredDates::at(schema, path).filter(|s| DeclaredDates::mentions(s))?; + let values: Rc<[Variable]> = (0..columns.rows) + .map(|row| { + let value = column.variable(row); + DeclaredDates::prepare(&value, Some(schema)).unwrap_or(value) + }) + .collect(); + Some((index, Leaf::Any(values))) + }) + .collect() + } + + fn reserved_inside(value: &Variable) -> bool { + match value { + Variable::Object(map) => { + let map = map.borrow(); + ZEN_RESERVED_PROPERTIES + .iter() + .any(|key| map.get_str(key).is_some()) + || map.iter().any(|(_, child)| Self::reserved_inside(child)) + } + Variable::Array(items) => items.borrow().iter().any(Self::reserved_inside), + _ => false, + } + } + + pub(crate) fn cleaned<'a>(leaf: &Leaf<'a>) -> Leaf<'a> { + if !leaf.objects() { + return leaf.clone(); + } + let reserved = match leaf { + Leaf::Any(values) => values.iter().any(Self::reserved_inside), + _ => match leaf.column().values { + Values::Any(values) => values.iter().any(Self::reserved_inside), + Values::Dict { + values: Dictionary::Any(values), + .. + } => values.iter().any(Self::reserved_inside), + _ => (0..leaf.len()).any(|row| Self::reserved_inside(&leaf.get(row))), + }, + }; + if !reserved { + return leaf.clone(); + } + let mut cleaner = VariableCleaner::new(); + let values: Vec = (0..leaf.len()) + .map(|row| { + let value = leaf.get(row).deep_clone(); + cleaner.clean(&value); + value + }) + .collect(); + Leaf::Any(values.into()) + } + + pub(crate) async fn evaluate_columns<'a>( + &self, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + columns: &'a Columns<'a>, + ) -> ColumnarOutput<'a> { + if max_depth > 0 { + if let Some(admitted) = self.planned_input(content, extensions, columns).await { + match self + .plan() + .evaluate(self, content, extensions, max_depth, columns, admitted) + .await + { + PlanOutcome::Skipped => {} + PlanOutcome::Done(output) => return output, + PlanOutcome::Partial { + output, + rows, + completed, + } => { + let inputs = Self::input_data(columns).materialized(); + let inputs: Vec = + rows.iter().map(|&row| inputs[row].clone()).collect(); + let completed = completed.subset(&rows); + let results = self + .resumed(content, extensions, max_depth, &inputs, Some(&completed)) + .await; + return output.splice(&rows, results); + } + } + } + } + let inputs = Self::input_data(columns).materialized(); + ColumnarOutput::from_results(self.evaluate(content, extensions, max_depth, &inputs).await) + } +} diff --git a/core/engine/src/compiled/graph/data.rs b/core/engine/src/compiled/graph/data.rs new file mode 100644 index 00000000..2ac5e769 --- /dev/null +++ b/core/engine/src/compiled/graph/data.rs @@ -0,0 +1,973 @@ +use crate::compiled::leaf::{Bits, ColumnBuilder, Leaf, Mask}; +use crate::decision_graph::walker::GraphWalker; +use std::cell::{OnceCell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::Binding; +use zen_expression::Variable; +use zen_types::path::DotPath; +use zen_types::symbol::Symbol; +use zen_types::variable::VariableMap; + +pub(crate) type Col = Rc<[Variable]>; +type Parts<'a> = (Option, Vec>, Vec<(Arc, Leaf<'a>)>); + +#[derive(Clone)] +pub(crate) struct Layer<'a> { + pub paths: Arc<[Arc]>, + keys: Rc<[Symbol]>, + segments: Rc<[Box<[Symbol]>]>, + pub columns: Rc<[Leaf<'a>]>, + pub present: Option]>>, + pub flat: bool, +} + +impl<'a> Layer<'a> { + pub fn new( + paths: Arc<[Arc]>, + columns: Vec>, + present: Option>>, + ) -> Layer<'a> { + let flat = paths.iter().all(|p| !p.contains('.')); + let keys = paths.iter().map(|p| Symbol::from(p.as_ref())).collect(); + let segments = paths + .iter() + .map(|p| p.split('.').map(Symbol::from).collect()) + .collect(); + Layer { + paths, + keys, + segments, + columns: columns.into(), + present: present.map(Rc::from), + flat, + } + } + + fn has(&self, index: usize, row: usize) -> bool { + self.present.as_ref().is_none_or(|p| p[index].get(row)) + } + + fn object(&self, row: usize) -> Variable { + match self.flat { + true => { + let mut map = VariableMap::with_capacity(self.keys.len()); + for (i, (key, column)) in self.keys.iter().zip(self.columns.iter()).enumerate() { + if self.has(i, row) { + map.insert(key.clone(), column.get(row)); + } + } + Variable::from_object(map) + } + false => { + let object = Variable::empty_object(); + for (i, (segments, column)) in + self.segments.iter().zip(self.columns.iter()).enumerate() + { + if self.has(i, row) { + Self::insert(&object, segments, column.get(row)); + } + } + object + } + } + } + + fn insert(target: &Variable, segments: &[Symbol], value: Variable) { + let Some((last, head)) = segments.split_last() else { + return; + }; + let mut current = target.shallow_clone(); + for part in head { + let Variable::Object(object) = ¤t else { + return; + }; + let existing = object.borrow().get(part).map(Variable::shallow_clone); + let next = match existing { + Some(existing) => existing, + None => { + let created = Variable::empty_object(); + object + .borrow_mut() + .insert(part.clone(), created.shallow_clone()); + created + } + }; + current = next; + } + if let Variable::Object(object) = current { + object.borrow_mut().insert(last.clone(), value); + } + } + + fn put(current: &mut VariableMap, key: &Symbol, value: &Variable) { + match value { + Variable::Null => { + current.remove(key); + } + Variable::Object(_) => { + let merged = match current.get(key) { + Some(existing @ Variable::Object(_)) => existing.clone().merge_clone(value), + _ => value.clone(), + }; + current.insert(key.clone(), merged); + } + _ => { + current.insert(key.clone(), value.clone()); + } + } + } + + fn under(&self, top: &str) -> Vec { + self.paths + .iter() + .enumerate() + .filter(|(_, path)| DotPath::within(path, top)) + .map(|(i, _)| i) + .collect() + } + + fn object_key(&self, row: usize, top: &str, under: &[usize]) -> Option { + if let [index] = under { + if self.paths[*index].as_ref() == top { + return self.has(*index, row).then(|| self.columns[*index].get(row)); + } + } + let object = Variable::empty_object(); + let mut any = false; + for &i in under { + if self.has(i, row) { + Self::insert(&object, &self.segments[i], self.columns[i].get(row)); + any = true; + } + } + match any { + true => object + .as_object() + .and_then(|m| m.borrow().get_str(top).cloned()), + false => None, + } + } + + fn apply(&self, row: usize, current: &mut VariableMap) { + match self.flat { + true => { + for (i, (key, column)) in self.keys.iter().zip(self.columns.iter()).enumerate() { + if self.has(i, row) { + Self::put(current, key, &column.get(row)); + } + } + } + false => { + if let Variable::Object(map) = self.object(row) { + for (key, value) in map.borrow().iter() { + Self::put(current, key, value); + } + } + } + } + } + + fn gather(&self, positions: &Rc<[usize]>) -> Layer<'a> { + Layer { + paths: self.paths.clone(), + keys: self.keys.clone(), + segments: self.segments.clone(), + columns: self.columns.iter().map(|c| c.pick(positions)).collect(), + present: self + .present + .as_ref() + .map(|masks| masks.iter().map(|m| m.pick(positions)).collect()), + flat: self.flat, + } + } +} + +#[derive(Clone, Debug)] +pub(crate) enum Presence<'a> { + Valued, + All, + Mask(Mask<'a>), +} + +impl<'a> Presence<'a> { + fn at(&self, leaf: &Leaf, row: usize) -> bool { + match self { + Presence::Valued => !leaf.null(row), + Presence::All => true, + Presence::Mask(mask) => mask.get(row), + } + } + + fn pick(&self, positions: &Rc<[usize]>) -> Presence<'a> { + match self { + Presence::Mask(mask) => Presence::Mask(mask.pick(positions)), + other => other.clone(), + } + } + + fn mask(&self, leaf: &Leaf, rows: usize) -> Rc<[u64]> { + match self { + Presence::Mask(mask) => mask.dense(rows), + Presence::All => Bits::ones(rows).into(), + Presence::Valued => leaf.valued(rows).into(), + } + } +} + +#[derive(Clone)] +pub(crate) enum Shape<'a> { + Plain(Col), + Patched { + base: Option, + layers: Rc<[Layer<'a>]>, + leaves: Rc<[(Arc, Leaf<'a>)]>, + nulls: Option>, + presence: Option]>>, + }, +} + +pub(crate) enum Read { + Leaf(usize), + Base, + Whole, +} + +pub(crate) struct Data<'a> { + pub rows: Rc<[usize]>, + pub shape: Shape<'a>, + whole: OnceCell, + tops: RefCell, Col)>>, +} + +impl<'a> Data<'a> { + pub fn plain(rows: Rc<[usize]>, values: Col) -> Data<'a> { + Data { + rows, + shape: Shape::Plain(values), + whole: OnceCell::new(), + tops: RefCell::new(Vec::new()), + } + } + + fn with_shape(rows: Rc<[usize]>, shape: Shape<'a>) -> Data<'a> { + Data { + rows, + shape, + whole: OnceCell::new(), + tops: RefCell::new(Vec::new()), + } + } + + pub fn pick(column: &Col, positions: &[usize]) -> Col { + positions.iter().map(|&i| column[i].clone()).collect() + } + + pub fn len(&self) -> usize { + self.rows.len() + } + + pub fn gather(pieces: &[Rc>], rows: &Rc<[usize]>) -> Data<'a> { + if let [single] = pieces { + if Rc::ptr_eq(&single.rows, rows) || single.rows == *rows { + return Data::with_shape(rows.clone(), single.shape.clone()); + } + } + let span = pieces + .iter() + .filter_map(|piece| piece.rows.last()) + .chain(rows.last()) + .max() + .map_or(0, |m| m + 1); + let mut table: Vec<(usize, usize)> = vec![(usize::MAX, 0); span]; + for (p, piece) in pieces.iter().enumerate() { + for (i, &row) in piece.rows.iter().enumerate() { + if table[row].0 == usize::MAX { + table[row] = (p, i); + } + } + } + let located: Vec<(usize, usize)> = rows.iter().map(|&row| table[row]).collect(); + let single = located + .iter() + .all(|(p, _)| *p == located.first().map_or(0, |l| l.0)); + match (single, located.first()) { + (true, Some(&(piece, _))) if piece != usize::MAX => { + let positions: Vec = located.iter().map(|(_, i)| *i).collect(); + Data::with_shape(rows.clone(), pieces[piece].shape_at(&positions)) + } + _ => Self::concat(pieces, &located, rows).unwrap_or_else(|| { + let values: Col = located + .iter() + .map(|&(p, i)| match pieces.get(p) { + Some(piece) => piece.materialize_row(i), + None => Variable::Null, + }) + .collect(); + Data::plain(rows.clone(), values) + }), + } + } + + fn concat( + pieces: &[Rc>], + located: &[(usize, usize)], + rows: &Rc<[usize]>, + ) -> Option> { + let shapes = pieces + .iter() + .map(|piece| match &piece.shape { + Shape::Patched { + base: None, + leaves, + presence: Some(presence), + nulls, + .. + } if piece.patchable() => Some((leaves, presence, nulls)), + _ => None, + }) + .collect::>>()?; + let (first, _, _) = shapes.first()?; + let same = shapes.iter().all(|(leaves, _, _)| { + leaves.len() == first.len() + && leaves + .iter() + .zip(first.iter()) + .all(|((a, _), (b, _))| a == b) + }); + if !same { + return None; + } + let count = located.len(); + let nulls = Bits::of(count, |row| { + let (p, i) = located[row]; + match shapes.get(p) { + Some((_, _, nulls)) => nulls.as_ref().is_some_and(|n| Bits::get(n, i)), + None => true, + } + }); + let mut columns = Vec::with_capacity(first.len()); + let mut present = Vec::with_capacity(first.len()); + let shared: Rc<[(usize, usize)]> = located.iter().copied().collect(); + for k in 0..first.len() { + let mask = Bits::of(count, |row| { + let (p, i) = located[row]; + shapes + .get(p) + .is_some_and(|(leaves, presence, _)| presence[k].at(&leaves[k].1, i)) + }); + let sources = shapes + .iter() + .map(|(leaves, _, _)| leaves[k].1.clone()) + .collect(); + columns.push(Leaf::stitched(sources, shared.clone())); + present.push(Mask::Bits(mask.into())); + } + let layer = Layer::new( + first.iter().map(|(path, _)| path.clone()).collect(), + columns, + Some(present), + ); + let nulls = (!Bits::none(&nulls)).then(|| Rc::from(nulls)); + Some(Data::record(rows, layer, nulls)) + } + + fn shape_at(&self, positions: &[usize]) -> Shape<'a> { + let positions: Rc<[usize]> = positions.into(); + let positions = &positions; + match &self.shape { + Shape::Plain(values) => Shape::Plain(Self::pick(values, positions)), + Shape::Patched { + base, + layers, + leaves, + nulls, + presence, + } => Shape::Patched { + base: base.as_ref().map(|b| Self::pick(b, positions)), + layers: layers.iter().map(|l| l.gather(positions)).collect(), + leaves: leaves + .iter() + .map(|(p, c)| (p.clone(), c.pick(positions))) + .collect(), + nulls: nulls.as_ref().map(|n| Bits::gather(n, positions).into()), + presence: presence + .as_ref() + .map(|p| p.iter().map(|x| x.pick(positions)).collect()), + }, + } + } + + fn nulled(&self, row: usize) -> bool { + matches!(&self.shape, Shape::Patched { nulls: Some(nulls), .. } if Bits::get(nulls, row)) + } + + pub fn materialize_row(&self, row: usize) -> Variable { + if let Some(whole) = self.whole.get() { + return whole[row].clone(); + } + if self.nulled(row) { + return Variable::Null; + } + match &self.shape { + Shape::Plain(values) => values[row].clone(), + Shape::Patched { base, layers, .. } => { + let mut layers = layers.iter(); + let mut current = match base.as_ref().map(|b| &b[row]) { + Some(Variable::Object(map)) => map.borrow().clone(), + _ => match layers.next() { + Some(first) => match first.object(row) { + Variable::Object(map) => map.borrow().clone(), + _ => VariableMap::default(), + }, + None => VariableMap::default(), + }, + }; + current.reserve(layers.as_slice().iter().map(|l| l.keys.len()).sum()); + for layer in layers { + layer.apply(row, &mut current); + } + Variable::from_object(current) + } + } + } + + pub fn partial(&self, path: &str) -> Leaf<'a> { + Leaf::Any(self.subtree(path)) + } + + pub fn subtree(&self, path: &str) -> Col { + let top = path.split('.').next().unwrap_or(path); + let rest = DotPath::tail(path, top); + let column = self.top(top); + match rest { + None => column, + Some(rest) => column + .iter() + .map(|value| Self::lookup(value, rest).unwrap_or(Variable::Null)) + .collect(), + } + } + + fn top(&self, top: &str) -> Col { + if let Some((_, column)) = self + .tops + .borrow() + .iter() + .find(|(key, _)| key.as_ref() == top) + { + return column.clone(); + } + let column: Col = match (self.whole.get(), &self.shape) { + (Some(whole), _) => whole + .iter() + .map(|v| Self::lookup(v, top).unwrap_or(Variable::Null)) + .collect(), + (None, Shape::Plain(values)) => values + .iter() + .map(|v| Self::lookup(v, top).unwrap_or(Variable::Null)) + .collect(), + (None, Shape::Patched { layers, .. }) => { + let under: Vec> = layers.iter().map(|layer| layer.under(top)).collect(); + (0..self.len()) + .map(|row| { + self.materialize_key(row, top, &under) + .unwrap_or(Variable::Null) + }) + .collect() + } + }; + self.tops + .borrow_mut() + .push((Arc::from(top), column.clone())); + column + } + + fn materialize_key(&self, row: usize, top: &str, under: &[Vec]) -> Option { + if self.nulled(row) { + return None; + } + match &self.shape { + Shape::Plain(values) => Self::lookup(&values[row], top), + Shape::Patched { base, layers, .. } => { + let mut layers = layers.iter().zip(under); + let mut current = match base.as_ref().map(|b| &b[row]) { + Some(value @ Variable::Object(_)) => Self::lookup(value, top), + _ => layers + .next() + .and_then(|(first, under)| first.object_key(row, top, under)), + }; + for (layer, under) in layers { + if under.is_empty() { + continue; + } + let Some(value) = layer.object_key(row, top, under) else { + continue; + }; + current = match value { + Variable::Null => None, + value @ Variable::Object(_) => match current { + Some(mut existing @ Variable::Object(_)) => { + Some(existing.merge_clone(&value)) + } + _ => Some(value), + }, + value => Some(value), + }; + } + current + } + } + } + + pub fn materialized(&self) -> Col { + self.whole + .get_or_init(|| (0..self.len()).map(|r| self.materialize_row(r)).collect()) + .clone() + } + + fn read(leaves: &[(Arc, Leaf)], path: &str) -> Read { + if leaves.iter().any(|(leaf, _)| DotPath::nested(leaf, path)) { + return Read::Whole; + } + match leaves.iter().rposition(|(leaf, _)| leaf.as_ref() == path) { + Some(index) => Read::Leaf(index), + None => Read::Base, + } + } + + pub fn lookup(value: &Variable, path: &str) -> Option { + path.split('.') + .try_fold(value.clone(), |current, key| match current { + Variable::Object(map) => map.borrow().get_str(key).cloned(), + _ => None, + }) + } + + fn resolve(&self, path: &str, row: usize) -> Variable { + match &self.shape { + Shape::Plain(values) => Self::lookup(&values[row], path).unwrap_or(Variable::Null), + Shape::Patched { base, leaves, .. } => match Self::read(leaves, path) { + Read::Leaf(index) => leaves[index].1.get(row), + Read::Base => base + .as_ref() + .and_then(|b| Self::lookup(&b[row], path)) + .unwrap_or(Variable::Null), + Read::Whole => { + Self::lookup(&self.materialize_row(row), path).unwrap_or(Variable::Null) + } + }, + } + } + + pub fn merged(rows: &Rc<[usize]>, parents: Vec>) -> Data<'a> { + match parents.len() { + 0 => Data::plain( + rows.clone(), + (0..rows.len()).map(|_| Variable::empty_object()).collect(), + ), + 1 => { + let Some(single) = parents.into_iter().next() else { + return Data::plain(rows.clone(), Rc::from(Vec::new())); + }; + match &single.shape { + Shape::Plain(values) => { + let containers = values + .iter() + .all(|v| matches!(v, Variable::Object(_) | Variable::Array(_))); + match containers { + true => single, + false => Data::plain( + rows.clone(), + values + .iter() + .map(|v| match v { + Variable::Object(_) | Variable::Array(_) => v.clone(), + _ => Variable::empty_object(), + }) + .collect(), + ), + } + } + Shape::Patched { nulls: None, .. } => single, + Shape::Patched { + base, + layers, + leaves, + presence, + .. + } => Data::with_shape( + rows.clone(), + Shape::Patched { + base: base.clone(), + layers: layers.clone(), + leaves: leaves.clone(), + nulls: None, + presence: presence.clone(), + }, + ), + } + } + _ if parents.iter().all(Data::patchable) => { + let mut parents = parents.into_iter(); + let mut head = match parents.next() { + Some(first) => Data::merged(rows, vec![first]), + None => Data::empty(rows), + }; + for parent in parents { + if let Some(layer) = parent.patch() { + head = head.layered(layer); + } + } + head + } + _ => { + let materialized: Vec = parents.iter().map(Data::materialized).collect(); + let values: Col = (0..rows.len()) + .map(|row| GraphWalker::merge_values(materialized.iter().map(|m| &m[row]))) + .collect(); + Data::plain(rows.clone(), values) + } + } + } + + pub fn empty(rows: &Rc<[usize]>) -> Data<'a> { + Data::with_shape( + rows.clone(), + Shape::Patched { + base: None, + layers: Rc::from(Vec::new()), + leaves: Rc::from(Vec::new()), + nulls: None, + presence: Some(Rc::from(Vec::new())), + }, + ) + } + + pub fn patchable(&self) -> bool { + match &self.shape { + Shape::Patched { + base: None, + leaves, + presence: Some(_), + .. + } => !leaves + .iter() + .any(|(a, _)| leaves.iter().any(|(b, _)| DotPath::under(b, a))), + _ => false, + } + } + + pub fn patch(&self) -> Option> { + let Shape::Patched { + base: None, + leaves, + presence: Some(presence), + nulls, + .. + } = &self.shape + else { + return None; + }; + let rows = self.len(); + let masks: Vec> = leaves + .iter() + .zip(presence.iter()) + .map(|((_, leaf), p)| { + let mask = p.mask(leaf, rows); + Mask::Bits(match nulls { + Some(nulls) => mask.iter().zip(nulls.iter()).map(|(m, n)| m & !n).collect(), + None => mask, + }) + }) + .collect(); + Some(Layer::new( + leaves.iter().map(|(path, _)| path.clone()).collect(), + leaves.iter().map(|(_, leaf)| leaf.clone()).collect(), + Some(masks), + )) + } + + pub fn record(rows: &Rc<[usize]>, layer: Layer<'a>, nulls: Option>) -> Data<'a> { + let leaves: Rc<[(Arc, Leaf)]> = layer + .paths + .iter() + .cloned() + .zip(layer.columns.iter().cloned()) + .collect(); + let count = rows.len(); + let presence: Rc<[Presence]> = (0..layer.paths.len()) + .map(|index| match (&layer.present, &nulls) { + (None, None) => Presence::All, + (Some(masks), None) => Presence::Mask(masks[index].clone()), + (present, Some(nulls)) => Presence::Mask(Mask::Bits(match present { + Some(masks) => masks[index] + .dense(count) + .iter() + .zip(nulls.iter()) + .map(|(p, n)| p & !n) + .collect(), + None => { + let mut bits: Vec = nulls.iter().map(|n| !n).collect(); + Bits::trim(&mut bits, count); + bits.into() + } + })), + }) + .collect(); + Data::with_shape( + rows.clone(), + Shape::Patched { + base: None, + layers: Rc::from(vec![layer]), + leaves, + nulls, + presence: Some(presence), + }, + ) + } + + pub fn layered(&self, layer: Layer<'a>) -> Data<'a> { + let rows = &self.rows; + let count = rows.len(); + let mut presence: Option>> = match &self.shape { + Shape::Patched { + base: None, + presence: Some(p), + .. + } => Some(p.to_vec()), + _ => None, + }; + let (base, layers, leaves): Parts<'a> = match &self.shape { + Shape::Plain(values) => { + let objects = values.iter().all(|v| matches!(v, Variable::Object(_))); + match objects { + true => (Some(values.clone()), Vec::new(), Vec::new()), + false => { + let merged: Col = (0..count) + .map(|row| values[row].clone().merge_clone(&layer.object(row))) + .collect(); + return Data::plain(rows.clone(), merged); + } + } + } + Shape::Patched { + base, + layers, + leaves, + .. + } => (base.clone(), layers.to_vec(), leaves.to_vec()), + }; + let mut next = leaves; + for (index, (path, column)) in layer.paths.iter().zip(layer.columns.iter()).enumerate() { + let valued = match layer.present.is_some() || base.is_none() { + true => column.valued(count), + false => Vec::new(), + }; + let removed = base.is_none() && layer.present.is_none() && Bits::none(&valued); + if removed { + let keep: Vec = next + .iter() + .map(|(leaf, _)| !DotPath::within(leaf, path)) + .collect(); + if let Some(tracked) = presence.as_mut() { + let mut flags = keep.iter(); + tracked.retain(|_| flags.next().copied().unwrap_or(true)); + } + let mut flags = keep.iter(); + next.retain(|_| flags.next().copied().unwrap_or(true)); + continue; + } + let fresh = + base.is_none() && !next.iter().any(|(leaf, _)| DotPath::overlaps(leaf, path)); + let objects = column.objects(); + let needs = !fresh && (layer.present.is_some() || objects); + let exact = match (needs, objects) { + (true, false) => match Self::read(self.leaves(), path) { + Read::Leaf(at) => self.leaves().get(at).map(|(_, leaf)| leaf), + _ => None, + }, + _ => None, + }; + let has = |row: usize| layer.has(index, row); + let (resolved, valued): (Leaf<'a>, Vec) = match (needs, exact) { + (false, _) => (column.clone(), valued), + (true, Some(old)) => { + let mut builder = ColumnBuilder::with_capacity(count); + let (fresh, before) = (column.column(), old.column()); + for row in 0..count { + match has(row) { + true => builder.push_cell(&fresh, row), + false => builder.push_cell(&before, row), + } + } + let leaf = Leaf::typed(builder.finish()); + let valued = match layer.present.is_some() { + true => leaf.valued(count), + false => Vec::new(), + }; + (leaf, valued) + } + (true, None) => { + let leaf = Leaf::Any( + (0..count) + .map(|row| match (has(row), column.get(row)) { + (false, _) => self.resolve(path, row), + (true, value @ Variable::Object(_)) => { + match self.resolve(path, row) { + mut existing @ Variable::Object(_) => { + existing.merge_clone(&value) + } + _ => value, + } + } + (true, value) => value, + }) + .collect(), + ); + let valued = match layer.present.is_some() { + true => leaf.valued(count), + false => Vec::new(), + }; + (leaf, valued) + } + }; + let existing = next.iter().position(|(leaf, _)| leaf == path); + if let Some(tracked) = presence.as_mut() { + let present = match &layer.present { + None => Presence::Valued, + Some(masks) => { + let has = masks[index].dense(count); + let before = existing.map(|i| tracked[i].mask(&next[i].1, count)); + Presence::Mask(Mask::Bits(match before { + Some(before) => has + .iter() + .zip(valued.iter()) + .zip(before.iter()) + .map(|((h, v), b)| (h & v) | (!h & b)) + .collect(), + None => has.iter().zip(valued.iter()).map(|(h, v)| h & v).collect(), + })) + } + }; + match existing { + Some(i) => tracked[i] = present, + None => tracked.push(present), + } + } + match existing { + Some(i) => next[i].1 = resolved, + None => next.push((path.clone(), resolved)), + } + } + let mut all = layers; + all.push(layer); + Data::with_shape( + rows.clone(), + Shape::Patched { + base, + layers: all.into(), + leaves: next.into(), + nulls: None, + presence: presence.map(Rc::from), + }, + ) + } + + pub fn presence_bits(&self, index: usize) -> Option> { + let Shape::Patched { + presence: Some(presence), + leaves, + nulls, + .. + } = &self.shape + else { + return None; + }; + let rows = self.len(); + let mut bits = presence + .get(index)? + .mask(&leaves.get(index)?.1, rows) + .to_vec(); + if let Some(nulls) = nulls { + bits.iter_mut() + .zip(nulls.iter()) + .for_each(|(b, n)| *b &= !n); + } + Some(bits) + } + + pub fn present(&self, path: &str) -> (Leaf<'a>, Vec) { + let rows = self.len(); + if let (Binding::Column(index), Shape::Patched { leaves, nulls, .. }) = + (self.binding(path).0, &self.shape) + { + let bits = self.presence_bits(index).unwrap_or_else(|| { + let mut bits = Bits::ones(rows).to_vec(); + if let Some(nulls) = nulls { + bits.iter_mut() + .zip(nulls.iter()) + .for_each(|(b, n)| *b &= !n); + } + bits + }); + return (leaves[index].1.clone(), bits); + } + let mut bits = vec![0u64; rows.div_ceil(64)]; + let values: Col = (0..rows) + .map(|row| match Self::lookup(&self.materialize_row(row), path) { + Some(value) => { + Bits::set(&mut bits, row, true); + value + } + None => Variable::Null, + }) + .collect(); + (Leaf::Any(values), bits) + } + + pub fn leaves(&self) -> &[(Arc, Leaf<'a>)] { + match &self.shape { + Shape::Plain(_) => &[], + Shape::Patched { leaves, .. } => leaves, + } + } + + pub fn column_at(&self, path: &str) -> Leaf<'a> { + match self.binding(path).0 { + Binding::Column(index) => self.leaves()[index].1.clone(), + Binding::Absent => Leaf::nulls(self.len()), + Binding::Row => Leaf::Any((0..self.len()).map(|row| self.resolve(path, row)).collect()), + } + } + + pub fn binding(&self, path: &str) -> (Binding, bool) { + if path == "$" || path.starts_with("$.") || path.starts_with("$nodes") { + return (Binding::Row, false); + } + match &self.shape { + Shape::Plain(_) => (Binding::Row, false), + Shape::Patched { base, leaves, .. } => match Self::read(leaves, path) { + Read::Leaf(index) => (Binding::Column(index), false), + Read::Base => match base { + None => (Binding::Absent, false), + Some(_) => (Binding::Row, false), + }, + Read::Whole => (Binding::Row, true), + }, + } + } + + pub fn base(&self) -> Col { + match &self.shape { + Shape::Plain(values) => values.clone(), + Shape::Patched { + base: Some(base), .. + } => base.clone(), + Shape::Patched { base: None, .. } => { + let shared = Variable::empty_object(); + (0..self.len()).map(|_| shared.clone()).collect() + } + } + } +} diff --git a/core/engine/src/compiled/graph/errors.rs b/core/engine/src/compiled/graph/errors.rs new file mode 100644 index 00000000..3d3a7347 --- /dev/null +++ b/core/engine/src/compiled/graph/errors.rs @@ -0,0 +1,230 @@ +use crate::nodes::NodeError; +use crate::EvaluationError; +use ahash::HashMap; +use std::rc::Rc; +use std::sync::Arc; +use zen_types::decision::DecisionNode; + +pub(crate) struct RowErrors { + errors: Vec>, + failed: usize, +} + +impl RowErrors { + const COMPACT: usize = 7; + + pub fn new(rows: usize) -> Self { + Self { + errors: (0..rows).map(|_| None).collect(), + failed: 0, + } + } + + pub fn len(&self) -> usize { + self.errors.len() + } + + pub fn ok(&self, row: usize) -> bool { + self.errors.get(row).is_some_and(Option::is_none) + } + + pub fn get(&self, row: usize) -> Option<&E> { + self.errors.get(row)?.as_ref() + } + + pub fn generation(&self) -> usize { + self.failed + } + + pub fn set(&mut self, row: usize, error: E) { + if let Some(slot) = self.errors.get_mut(row) { + if slot.is_none() { + self.failed += 1; + } + *slot = Some(error); + } + } + + pub fn fill(&mut self, error: impl Fn() -> E) { + for row in 0..self.errors.len() { + self.set(row, error()); + } + } + + pub fn into_vec(self) -> Vec> { + self.errors + } + + pub fn take(&mut self) -> Vec> { + self.failed = 0; + std::mem::take(&mut self.errors) + } + + pub fn live(&self, rows: &Rc<[usize]>) -> Rc<[usize]> { + match self.failed == 0 || rows.iter().all(|&row| self.ok(row)) { + true => rows.clone(), + false => rows.iter().copied().filter(|&row| self.ok(row)).collect(), + } + } + + pub fn alive(&self, positions: Option>, seen: &mut usize) -> Option> { + if self.failed == *seen { + return positions; + } + *seen = self.failed; + let rows = self.errors.len(); + let total = positions.as_ref().map_or(rows, |p| p.len()); + let live = match &positions { + Some(p) => p.iter().filter(|&&row| self.ok(row)).count(), + None => self.errors.iter().filter(|error| error.is_none()).count(), + }; + match (live + live / Self::COMPACT < total, live == rows) { + (true, _) => { + let mut kept = Vec::with_capacity(live); + match &positions { + Some(p) => kept.extend(p.iter().copied().filter(|&row| self.ok(row))), + None => kept.extend((0..rows).filter(|&row| self.ok(row))), + } + Some(kept.into()) + } + (false, true) => None, + (false, false) => positions, + } + } +} + +impl RowErrors> { + pub fn fault(&mut self, row: usize, error: NodeError) { + self.set( + row, + Box::new(NodeError::new(error.node_id, error.source).into()), + ); + } + + pub fn fail(&mut self, row: usize, node: &DecisionNode, message: String) { + self.set( + row, + Box::new(NodeError::new(node.id.clone(), message).into()), + ); + } +} + +struct Failure(Rc); + +impl std::fmt::Display for Failure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::fmt::Debug for Failure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&*self.0, f) + } +} + +impl std::error::Error for Failure {} + +struct Known { + node: Arc, + message: Rc, + error: Rc, +} + +pub(crate) struct SharedErrors { + rows: RowErrors>, + known: HashMap<(Arc, Rc), Rc>, + last: Option, + deferral: Rc, +} + +impl std::ops::Deref for SharedErrors { + type Target = RowErrors>; + + fn deref(&self) -> &Self::Target { + &self.rows + } +} + +impl std::ops::DerefMut for SharedErrors { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.rows + } +} + +impl SharedErrors { + pub fn new(rows: usize) -> Self { + Self { + rows: RowErrors::new(rows), + known: HashMap::default(), + last: None, + deferral: Rc::new(EvaluationError::from(NodeError::new( + Arc::from(""), + Failure(Rc::from("deferred")), + ))), + } + } + + pub fn fail(&mut self, row: usize, node: &DecisionNode, message: Rc) { + if !self.ok(row) { + return; + } + if let Some(last) = &self.last { + if Arc::ptr_eq(&last.node, &node.id) && Rc::ptr_eq(&last.message, &message) { + let error = last.error.clone(); + self.rows.set(row, error); + return; + } + } + let error = self + .known + .entry((node.id.clone(), message.clone())) + .or_insert_with(|| { + Rc::new(EvaluationError::from(NodeError::new( + node.id.clone(), + Failure(message.clone()), + ))) + }) + .clone(); + self.last = Some(Known { + node: node.id.clone(), + message, + error: error.clone(), + }); + self.rows.set(row, error); + } + + pub fn fault(&mut self, row: usize, error: NodeError) { + if self.ok(row) { + self.rows.set( + row, + Rc::new(NodeError::new(error.node_id, error.source).into()), + ); + } + } + + pub fn share(&mut self, row: usize, error: &Rc) { + if self.ok(row) { + self.rows.set(row, error.clone()); + } + } + + pub fn defer(&mut self, row: usize) { + let deferral = self.deferral.clone(); + self.share(row, &deferral); + } + + pub fn deferred(&self) -> Vec { + self.rows + .errors + .iter() + .enumerate() + .filter(|(_, error)| { + error + .as_ref() + .is_some_and(|e| Rc::ptr_eq(e, &self.deferral)) + }) + .map(|(row, _)| row) + .collect() + } +} diff --git a/core/engine/src/compiled/graph/mod.rs b/core/engine/src/compiled/graph/mod.rs new file mode 100644 index 00000000..40786ed6 --- /dev/null +++ b/core/engine/src/compiled/graph/mod.rs @@ -0,0 +1,223 @@ +mod batched; +pub(crate) mod call; +mod plan; +mod state; +mod step; +pub(crate) mod traced; +pub use columnar::ColumnarOutput; +pub(super) mod columnar; +mod data; +pub(crate) mod errors; +mod schedule; +mod schema; + +use crate::decision_graph::graph::DecisionGraphResponse; +use crate::decision_graph::walker::StableDiDecisionGraph; +use crate::model::GraphContent; +use crate::nodes::NodeHandlerExtensions; +use crate::{DecisionGraphValidationError, EvaluationError}; +use schedule::Segment; +use state::Completed; +use state::Host; +use state::NodeColumn; +pub(crate) use state::{Nesting, State}; +use std::cell::RefCell; +use std::fmt::{Debug, Formatter}; +use std::sync::{Arc, OnceLock}; +use std::time::Instant; +use step::{Body, Condition, Hit, Kind, Step, Transform}; +use zen_expression::lane::Columns; +use zen_expression::lane::LaneRunner; +use zen_expression::Variable; + +pub struct CompiledGraph { + graph: StableDiDecisionGraph, + steps: Vec>, + root: Arc, + dictionaries: bool, + plan: OnceLock, + census: usize, +} + +pub struct CompiledPlan(Result); + +#[derive(Clone)] +pub(crate) enum Invalid { + Build(DecisionGraphValidationError), + Validation(DecisionGraphValidationError), +} + +impl Invalid { + pub(crate) fn evaluation(&self) -> Box { + match self { + Invalid::Build(error) | Invalid::Validation(error) => { + Box::new(EvaluationError::InvalidGraph(error.clone())) + } + } + } + + fn reason(&self) -> String { + match self { + Invalid::Build(error) => error.to_string(), + Invalid::Validation(_) => "graph fails validation".into(), + } + } + + pub(crate) fn source(&self) -> Box { + match self { + Invalid::Build(error) => Box::new(error.clone()), + Invalid::Validation(_) => self.evaluation().to_string().into(), + } + } +} + +impl Debug for CompiledPlan { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match &self.0 { + Ok(_) => write!(f, "CompiledPlan(Ok)"), + Err(invalid) => write!(f, "CompiledPlan(Err({}))", invalid.reason()), + } + } +} + +impl CompiledPlan { + pub fn compile(content: &GraphContent) -> Self { + Self(CompiledGraph::compile(content, true)) + } + + pub(crate) fn hosted(content: &GraphContent) -> Self { + Self(CompiledGraph::compile(content, false)) + } + + pub fn verdict(&self) -> Result<(), String> { + self.0.as_ref().map(|_| ()).map_err(Invalid::reason) + } + + pub(crate) fn graph(&self) -> Result<&CompiledGraph, &Invalid> { + self.0.as_ref() + } +} + +impl CompiledGraph { + thread_local! { + static RUNNER: RefCell = RefCell::new(LaneRunner::new()); + } + + pub(crate) fn census() -> Vec<(String, u64, u64, u128)> { + crate::compiled::census::Census::take() + } + + pub(crate) fn degraded(&self) -> Vec<(Arc, Arc)> { + let mut out = Vec::new(); + for step in self.steps.iter().flatten() { + match &step.kind { + Kind::Host(Some(why)) => out.push((step.node.id.clone(), why.clone())), + Kind::Switch { conditions, .. } => out.extend(conditions.iter().filter_map( + |(_, condition)| match condition { + Condition::Invalid(why) => Some((step.node.id.clone(), why.clone())), + _ => None, + }, + )), + _ => {} + } + } + out + } + + fn plan(&self) -> &plan::Plan { + self.plan.get_or_init(|| plan::Plan::analyze(self)) + } + + pub(crate) fn plan_verdict(&self, columns: &Columns) -> Result<(), String> { + self.plan() + .verdict(self, columns) + .map_err(|refusal| refusal.to_string()) + } + + pub(crate) async fn evaluate( + &self, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + inputs: &[Variable], + ) -> Vec>> { + self.resumed(content, extensions, max_depth, inputs, None) + .await + } + + pub(in crate::compiled::graph) async fn resumed( + &self, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + inputs: &[Variable], + completed: Option<&Completed>, + ) -> Vec>> { + let start = Instant::now(); + let nesting = Nesting { + completed, + ..Nesting::default() + }; + let state = self + .run( + Host { + content, + extensions, + max_depth, + }, + inputs, + nesting, + ) + .await; + let performance = format!("{:.1?}", start.elapsed()); + state + .errors + .into_vec() + .into_iter() + .zip(state.results) + .map(|(error, result)| match error { + Some(error) => Err(error), + None => Ok(DecisionGraphResponse { + performance: performance.clone(), + result: result.unwrap_or_else(Variable::empty_object), + trace: None, + }), + }) + .collect() + } + + pub(crate) async fn evaluate_one( + &self, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + input: Variable, + ) -> Result> { + let start = Instant::now(); + let inputs = [input]; + let state = self + .run( + Host { + content, + extensions, + max_depth, + }, + &inputs, + Nesting::default(), + ) + .await; + if let Some(error) = state.errors.into_vec().into_iter().next().flatten() { + return Err(error); + } + Ok(DecisionGraphResponse { + performance: format!("{:.1?}", start.elapsed()), + result: state + .results + .into_iter() + .next() + .flatten() + .unwrap_or_else(Variable::empty_object), + trace: None, + }) + } +} diff --git a/core/engine/src/compiled/graph/plan/census.rs b/core/engine/src/compiled/graph/plan/census.rs new file mode 100644 index 00000000..3603325e --- /dev/null +++ b/core/engine/src/compiled/graph/plan/census.rs @@ -0,0 +1,37 @@ +use super::{Op, Program}; +use crate::compiled::census::Census; + +impl Op { + pub(crate) fn refuse(&self, graph: &crate::compiled::graph::CompiledGraph) { + if Census::on() { + if let Some(key) = self.census(graph) { + Census::reject(key); + } + } + } + + pub(crate) fn census( + &self, + graph: &crate::compiled::graph::CompiledGraph, + ) -> Option<(usize, String)> { + let base = graph.census; + match self { + Op::Lane(lane) => Some(( + base, + format!("{}:{}", lane.node.index(), lane.program.tag()), + )), + Op::Table(table) => Some((base, format!("{}:table", table.node.index()))), + _ => None, + } + } +} + +impl Program { + fn tag(&self) -> String { + match self { + Program::Expression => "expression".into(), + Program::Condition(at) => format!("condition{at}"), + Program::Field => "field".into(), + } + } +} diff --git a/core/engine/src/compiled/graph/plan/mod.rs b/core/engine/src/compiled/graph/plan/mod.rs new file mode 100644 index 00000000..10481dce --- /dev/null +++ b/core/engine/src/compiled/graph/plan/mod.rs @@ -0,0 +1,1767 @@ +pub(crate) mod census; +mod run; +pub(crate) use run::PlanOutcome; +pub(crate) mod refusal; +pub(crate) mod subgraphs; +mod typed; +mod view; + +use crate::compiled::core::segments::Children; +use crate::compiled::graph::call::Call; +use crate::compiled::graph::schedule::{End, Outcome, Segment}; +use crate::compiled::graph::{Body, CompiledGraph, Condition, Kind, Step}; +use crate::compiled::leaf::Literal; +use crate::compiled::table::Table; +use crate::model::{DecisionNodeKind, GraphContent}; +use petgraph::prelude::NodeIndex; +use refusal::{ChildRefusal, Hosted, Needs, Refusal}; +use std::sync::{Arc, OnceLock, RwLock}; +use subgraphs::{Closure, Subgraphs}; +use view::{Masks, Node, Ref, Resolved, Shape, SlotId, Slots, M}; +use zen_expression::lane::{ + Binding as Site, Columns, Dictionary, Kind as LaneKind, LaneProgram, Values, +}; +use zen_types::decision::TransformExecutionMode; + +type Bound = Arc, Refusal>>; +struct Kept { + entry: (Arc, Arc), + fragment: Arc, +} + +struct Keyed { + view: Node, + keys: Vec<(Arc, SlotId, M)>, +} + +pub(crate) struct Plan { + roots: RwLock>, +} + +struct Root { + layout: Arc, + bound: Bound, + closure: Closure, +} + +#[derive(PartialEq, Eq, Clone)] +pub(crate) struct Layout(Vec<(Arc, Shape)>); + +#[derive(Clone)] +pub(crate) enum Source { + Input(usize), + Op, +} + +#[derive(Clone)] +pub(crate) struct SlotInfo { + pub shape: Shape, + pub source: Source, +} + +#[derive(Clone, Copy)] +pub(crate) enum Program { + Expression, + Condition(usize), + Field, +} + +pub(crate) struct LaneOp { + pub node: NodeIndex, + pub program: Program, + pub reads: Vec<(Arc, Ref)>, + pub bound: Vec, + pub outs: Vec, + pub uniform: bool, + pub stable: bool, + pub specialized: OnceLock>, + pub own: Option>, + pub sources: Vec<(Arc, Arc)>, +} + +pub(crate) struct Reduced { + pub program: LaneProgram, + pub entries: Box<[(Arc, Arc)]>, +} + +pub(crate) struct TableOp { + pub node: NodeIndex, + pub reads: Vec<(Arc, Option)>, + pub outs: Vec, + pub present: Vec, + pub matched: M, + pub mode: TableMode, +} + +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum TableMode { + First, + Collected, + Rows, +} + +pub(crate) enum Op { + Lane(Box), + Table(TableOp), + Typed { + op: Box, + units: Vec, + }, + Deferred { + op: Box, + units: Vec, + }, + Select { + a: Ref, + b: Ref, + take: M, + out: SlotId, + }, + Materialize { + node: Node, + out: SlotId, + }, + Extract { + from: Ref, + path: Vec>, + out: SlotId, + }, + Null { + out: SlotId, + }, + Coalesce { + from: Ref, + value: Literal, + out: SlotId, + }, + MergeRows { + a: Node, + b: Node, + parts: [M; 3], + present: M, + out: SlotId, + }, + Rows(Box), + Join { + inputs: Vec, + out: SlotId, + mode: JoinMode, + }, + Loop { + node: NodeIndex, + list: Ref, + out: SlotId, + }, + Child(Box), +} + +pub(crate) struct ChildKey { + pub path: Arc, + pub child: Ref, + pub out: SlotId, + pub present: M, +} + +pub(crate) struct ChildOp { + pub node: NodeIndex, + pub view: Node, + pub input: Node, + pub nodes: Option, Ref)>>, + pub content: Arc, + pub root: Arc, + pub layout: Arc, + pub keys: Vec, + pub record: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum JoinMode { + Strict, + Lenient, + Ending, +} + +pub(crate) struct RowsOp { + pub node: NodeIndex, + pub view: Node, + pub nodes: Option, Ref)>>, + pub out: SlotId, + pub keys: Vec<(Arc, SlotId, M)>, + pub reason: Arc, +} + +pub(crate) struct RowsCond { + pub index: usize, + pub node: NodeIndex, + pub input: Ref, + pub nodes: Option, Ref)>>, + pub reason: Arc, +} + +pub(crate) enum Cond { + Always, + Never, + Lane(Box), + Rows(Box), +} + +pub(crate) enum SegEnd { + Finish(Vec<(Arc, Ref)>), + Switch { + first: bool, + ids: Vec>, + conditions: Vec, + children: Children, Bound>, + }, +} + +pub(crate) struct SegPlan { + pub segment: Arc, + pub slots: Vec, + pub masks: Masks, + pub ops: Vec, + pub end: SegEnd, + pub hosted: Vec, + views: Vec<(NodeIndex, Node)>, + nested: Nested, +} + +#[derive(Clone, Default)] +struct Nested { + subgraphs: Option>, + stack: Arc<[Arc]>, +} + +struct Builder<'g> { + graph: &'g CompiledGraph, + masks: Masks, + catalog: Catalog, + views: Vec<(NodeIndex, Node)>, + objects: Vec<(Node, Ref)>, + hosted: Vec, + null: Option, + nested: Nested, +} + +#[derive(Default)] +struct Catalog { + slots: Vec, + ops: Vec, +} + +impl Catalog { + fn slot(&mut self, shape: Shape) -> SlotId { + self.slots.push(SlotInfo { + shape, + source: Source::Op, + }); + (self.slots.len() - 1) as SlotId + } +} + +impl Slots for Catalog { + fn shape(&self, slot: SlotId) -> Shape { + self.slots[slot as usize].shape + } + + fn merge_rows(&mut self, a: Node, b: Node, parts: [M; 3], present: M) -> SlotId { + let out = self.slot(Shape::Dyn); + self.ops.push(Op::MergeRows { + a, + b, + parts, + present, + out, + }); + out + } + + fn select(&mut self, a: Ref, b: Ref, take: M, _present: M) -> SlotId { + let shape = match (self.shape(a.slot), self.shape(b.slot)) { + (x, y) if x == y => x, + (Shape::Null, x) | (x, Shape::Null) if x.scalar() => x, + _ => Shape::Unknown, + }; + let out = self.slot(shape); + self.ops.push(Op::Select { a, b, take, out }); + out + } +} + +impl<'g> Builder<'g> { + fn slot(&mut self, shape: Shape) -> SlotId { + self.catalog.slot(shape) + } + + fn input(&mut self, layout: &Layout) -> Result { + let mut root = Node::root(M::All); + for (index, (path, shape)) in layout.0.iter().enumerate() { + self.catalog.slots.push(SlotInfo { + shape: *shape, + source: Source::Input(index), + }); + let slot = (self.catalog.slots.len() - 1) as SlotId; + let present = self.masks.validity(slot); + root.insert(path, Ref { slot, present }, M::All)?; + } + let mut fields = std::mem::take(&mut root.fields); + for (_, child) in fields.iter_mut() { + child.objects_from_leaves(&mut self.masks); + } + root.fields = fields; + Ok(root) + } + + fn read(&mut self, view: &Node, key: &str, base: Option<&str>) -> Result, Refusal> { + let rebased = match base { + Some(base) => CompiledGraph::rebased(base, key).ok_or_else(|| Refusal::Rebase { + key: Arc::from(key), + base: Arc::from(base), + })?, + None => Arc::from(key), + }; + let key = rebased.as_ref(); + let (view, key) = match key.strip_prefix("$nodes.") { + Some(rest) => { + let (name, path) = rest.split_once('.').unwrap_or((rest, "")); + if !crate::ZEN_CONFIG + .nodes_in_context + .load(std::sync::atomic::Ordering::Relaxed) + { + return Ok(None); + } + let named = self + .graph + .steps + .iter() + .flatten() + .filter(|s| s.node.name.as_ref() == name) + .count(); + if named > 1 { + return Err(Refusal::DuplicateName(Arc::from(name))); + } + let found = self + .views + .iter() + .rev() + .find(|(n, _)| { + self.graph + .step_at(*n) + .is_some_and(|s| s.node.name.as_ref() == name) + }) + .map(|(_, v)| v.clone()); + let Some(found) = found else { + return Ok(None); + }; + if path.is_empty() { + return Err(Refusal::WholeNodes); + } + (found, path.to_string()) + } + None => (view.clone(), key.to_string()), + }; + let key = key.as_str(); + if key.starts_with('$') { + return Err(Refusal::RowRead(Arc::from(key))); + } + match view.resolve(key, &self.catalog)? { + Resolved::Leaf(leaf) => Ok(Some(leaf)), + Resolved::Absent => Ok(None), + Resolved::Object(node) => { + if let Some((_, found)) = self.objects.iter().find(|(n, _)| *n == node) { + return Ok(Some(*found)); + } + let present = node.obj.unwrap_or(M::None); + let out = self.slot(Shape::Dyn); + self.catalog.ops.push(Op::Materialize { + node: node.clone(), + out, + }); + let found = Ref { slot: out, present }; + self.objects.push((node, found)); + Ok(Some(found)) + } + Resolved::Extract(from, path) => { + let out = self.slot(Shape::Dyn); + self.catalog.ops.push(Op::Extract { from, path, out }); + let present = self.masks.valued(out); + Ok(Some(Ref { slot: out, present })) + } + } + } + + fn lane( + &mut self, + node: NodeIndex, + kind: Program, + program: &LaneProgram, + input: &Node, + base: Option<&str>, + outs: Vec, + ) -> Result { + let needs = Needs::of(program); + if needs.any() { + return Err(Refusal::Program(needs)); + } + let p = program.program(); + let mut reads: Vec<(Arc, Ref)> = Vec::new(); + let mut bound = Vec::with_capacity(p.site_keys.len()); + for key in &p.site_keys { + let Some(key) = key.as_deref() else { + bound.push(Site::Row); + continue; + }; + bound.push(match self.read(input, key, base)? { + None => Site::Absent, + Some(leaf) => match reads.iter().position(|(k, _)| k.as_ref() == key) { + Some(at) => Site::Column(at), + None => { + reads.push((Arc::from(key), leaf)); + Site::Column(reads.len() - 1) + } + }, + }); + } + let stable = p.stable() && !p.opaque(); + let uniform = reads.is_empty() && stable; + Ok(LaneOp { + node, + program: kind, + reads, + bound, + outs, + uniform, + stable, + specialized: OnceLock::new(), + own: None, + sources: Vec::new(), + }) + } + + fn literal(text: &str) -> Option { + let text = text.trim(); + match text { + "true" => return Some(Literal::Bool(true)), + "false" => return Some(Literal::Bool(false)), + _ => {} + } + let quoted = ['\'', '"'] + .iter() + .find_map(|q| text.strip_prefix(*q).and_then(|t| t.strip_suffix(*q))) + .filter(|inner| !inner.contains(['\\', '\'', '"', '$', '`'])); + match quoted { + Some(inner) => Some(Literal::Str(Arc::from(inner))), + None if text.chars().all(|c| c.is_ascii_digit() || c == '.') + && text.starts_with(|c: char| c.is_ascii_digit()) => + { + text.parse::().ok().map(Literal::Num) + } + None => None, + } + } + + fn coalesce(&mut self, input: &Node, source: &str) -> Result, Refusal> { + let Some((left, right)) = source.split_once("??") else { + return Ok(None); + }; + let (Some(value), true) = (Self::literal(right), Self::path(left.trim())) else { + return Ok(None); + }; + let Resolved::Leaf(leaf) = input.resolve(left.trim(), &self.catalog)? else { + return Ok(None); + }; + let shape = match (&value, self.catalog.shape(leaf.slot)) { + (Literal::Num(_), Shape::Num) => Shape::Num, + (Literal::Str(_), Shape::Text) => Shape::Text, + (Literal::Bool(_), Shape::Bool) => Shape::Bool, + _ => return Ok(None), + }; + if !self.masks.implied(leaf) { + return Ok(None); + } + let out = self.slot(shape); + self.catalog.ops.push(Op::Coalesce { + from: leaf, + value, + out, + }); + Ok(Some(Node { + leaf: Some(Ref { + slot: out, + present: M::All, + }), + obj: None, + fields: Vec::new(), + })) + } + + fn path(path: &str) -> bool { + !matches!(path, "" | "true" | "false" | "null") + && path.split('.').all(|segment| { + segment + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && segment + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + }) + } + + fn alias(&mut self, input: &Node, source: &str) -> Result, Refusal> { + let path = source.trim(); + if !Self::path(path) { + return self.coalesce(input, path); + } + Ok(match input.resolve(path, &self.catalog)? { + Resolved::Leaf(leaf) if self.masks.implied(leaf) => Some(Node { + leaf: Some(Ref { + slot: leaf.slot, + present: M::All, + }), + obj: None, + fields: Vec::new(), + }), + Resolved::Object(mut node) if node.leaf.is_none() => { + let obj = node.obj.unwrap_or(M::None); + if obj != M::All { + let null = match self + .null + .filter(|slot| (*slot as usize) < self.catalog.slots.len()) + { + Some(slot) => slot, + None => { + let slot = self.slot(Shape::Null); + self.catalog.ops.push(Op::Null { out: slot }); + self.null = Some(slot); + slot + } + }; + let missing = self.masks.not(obj); + node.leaf = Some(Ref { + slot: null, + present: missing, + }); + } + Some(node) + } + _ => None, + }) + } + + fn expression(&mut self, node: NodeIndex, step: &Step, input: &Node) -> Result { + let Kind::Node { + body: + Body::Expression { + program, + keys, + empty, + entries, + fragments, + .. + }, + transform, + } = &step.kind + else { + return Err(Refusal::NotExpression); + }; + if transform.input_field.is_some() && transform.base.is_none() { + return Err(Refusal::DynamicInputField); + } + if matches!( + &step.kind, + Kind::Node { + body: Body::Expression { walked: true, .. }, + .. + } + ) { + return Err(Refusal::OverlappingCopies); + } + if let Some(base) = &transform.base { + if matches!( + input.resolve(base, &self.catalog)?, + Resolved::Leaf(_) | Resolved::Extract(..) + ) { + return Err(Refusal::ScalarInputField); + } + } + let p = program.program(); + let regs: Vec<_> = match p.outputs.is_empty() { + true => vec![p.out], + false => p.outputs.clone(), + }; + if regs.len() != keys.len() { + return Err(Refusal::OutputArity); + } + let aliasable = transform.base.is_none() && !p.opaque() && !p.writes_env && !p.chain; + let mut aliases: Vec> = Vec::with_capacity(keys.len()); + for (key, fragment) in keys.iter().zip(fragments.iter()) { + let root = format!("$.{}", key.split('.').next().unwrap_or_default()); + let read = entries.iter().any(|(_, v)| v.contains(root.as_str())); + aliases.push(match aliasable && !read && fragments.len() == keys.len() { + true => self.alias(input, fragment)?, + false => None, + }); + } + let reduced = match aliases.iter().any(Option::is_some) { + true => { + let kept: Vec = entries + .iter() + .zip(fragments.iter()) + .zip(&aliases) + .filter(|(_, alias)| alias.is_none()) + .map(|((entry, fragment), _)| Kept { + entry: entry.clone(), + fragment: fragment.clone(), + }) + .collect(); + let refs: Vec<(&str, &str)> = kept + .iter() + .map(|kept| (kept.entry.0.as_ref(), kept.fragment.as_ref())) + .collect(); + match kept.is_empty() { + true => None, + false => Some(Reduced { + program: LaneProgram::compile_many(&refs, true) + .map_err(|e| Refusal::Uncompiled(Arc::from(e.to_string())))?, + entries: kept.into_iter().map(|kept| kept.entry).collect(), + }), + } + } + false => None, + }; + let lane_program = reduced.as_ref().map_or(program.as_ref(), |r| &r.program); + let lp = lane_program.program(); + let lane_regs: Vec<_> = match lp.outputs.is_empty() { + true => vec![lp.out], + false => lp.outputs.clone(), + }; + let mut lane_regs = lane_regs.into_iter(); + let mut out = Node::root(M::All); + let mut outs = Vec::new(); + let mut sources = Vec::new(); + for ((((key, empty), (_, source)), alias), fragment) in keys + .iter() + .zip(empty.iter()) + .zip(entries.iter()) + .zip(aliases.iter_mut()) + .zip(fragments.iter()) + { + if keys.iter().filter(|k| *k == key).count() > 1 { + return Err(Refusal::DuplicateExpressionKey); + } + if key.split('.').any(str::is_empty) { + return Err(Refusal::EmptyKeySegment); + } + let path = match &transform.output_path { + Some(prefix) => format!("{prefix}.{key}"), + None => key.to_string(), + }; + if let Some(alias) = alias.take() { + out.insert_node(&path, alias, M::All)?; + continue; + } + let reg = lane_regs.next().ok_or(Refusal::OutputArity)?; + let shape = match (lp.kinds[reg as usize], source.trim() == "null") { + (_, true) => Shape::Null, + (LaneKind::Num, _) => Shape::Num, + (LaneKind::Bool, _) => Shape::Bool, + (LaneKind::Str, _) => Shape::Text, + _ => Shape::Dyn, + }; + let slot = self.slot(shape); + outs.push(slot); + sources.push((key.clone(), fragment.clone())); + match empty { + true => out.insert_object(&path, M::All)?, + false => out.insert( + &path, + Ref { + slot, + present: M::All, + }, + M::All, + )?, + } + } + if !outs.is_empty() { + let mut op = self.lane( + node, + Program::Expression, + lane_program, + input, + transform.base.as_deref(), + outs, + )?; + op.own = reduced.map(Box::new); + op.sources = sources; + self.catalog.ops.push(Op::Lane(Box::new(op))); + } + match transform.pass_through { + true => Node::merge(input, &out, &mut self.masks, &mut self.catalog), + false => Ok(out), + } + } + + fn table( + &mut self, + node: NodeIndex, + step: &Step, + table: &Table, + input: &Node, + ) -> Result { + let Kind::Node { transform, .. } = &step.kind else { + return Err(Refusal::NotTable); + }; + if transform.input_field.is_some() { + return Err(Refusal::TableInputField); + } + let mode = match (table.first_hit(), table.collects(), &transform.output_path) { + (true, _, _) => TableMode::First, + (false, true, _) => TableMode::Collected, + (false, false, _) if transform.output_path.is_some() || !transform.pass_through => { + TableMode::Rows + } + _ => return Err(Refusal::CollectTable), + }; + let mut reads: Vec<(Arc, Option)> = Vec::new(); + for program in table.programs() { + let p = program.program(); + if p.opaque() || p.writes_env || p.chain { + return Err(Refusal::TableNeedsRows); + } + for key in p.site_keys.iter() { + let Some(key) = key.as_deref() else { + continue; + }; + if key.starts_with("$.") { + return Err(Refusal::TableCellRead(Arc::from(key))); + } + if key == "$" || reads.iter().any(|(k, _)| k.as_ref() == key) { + continue; + } + if key.starts_with('$') && !key.starts_with("$nodes.") { + return Err(Refusal::TableRead(Arc::from(key))); + } + let leaf = self.read(input, key, None)?; + reads.push((Arc::from(key), leaf)); + } + } + let out = match mode { + TableMode::Rows => { + let slot = self.slot(Shape::Dyn); + self.catalog.ops.push(Op::Table(TableOp { + node, + reads, + outs: vec![slot], + present: Vec::new(), + matched: M::All, + mode, + })); + match &transform.output_path { + Some(path) => { + let mut out = Node::root(M::All); + out.insert( + path, + Ref { + slot, + present: M::All, + }, + M::All, + )?; + out + } + None => Node { + leaf: Some(Ref { + slot, + present: M::All, + }), + obj: None, + fields: Vec::new(), + }, + } + } + _ => { + let paths = table.output_paths(); + let mut out = Node::root(M::None); + let mut outs = Vec::with_capacity(paths.len()); + let mut present = Vec::with_capacity(paths.len()); + for path in paths.iter() { + let shape = table.slot_kind(path).map_or(Shape::Unknown, Shape::from); + let slot = self.slot(shape); + let mask = self.masks.produced(); + outs.push(slot); + present.push(mask); + out.insert( + path, + Ref { + slot, + present: mask, + }, + M::None, + )?; + } + let matched = self.masks.produced(); + out.objects_from_leaves(&mut self.masks); + out.obj = Some(matched); + self.catalog.ops.push(Op::Table(TableOp { + node, + reads, + outs, + present, + matched, + mode, + })); + match &transform.output_path { + None => out, + Some(path) => { + let null = self.slot(Shape::Dyn); + self.catalog.ops.push(Op::Null { out: null }); + let missing = self.masks.not(matched); + out.leaf = Some(Ref { + slot: null, + present: missing, + }); + Node::wrap(out, path) + } + } + } + }; + match transform.pass_through { + true => Node::merge(input, &out, &mut self.masks, &mut self.catalog), + false => Ok(out), + } + } + + fn whole(&mut self, view: &Node) -> Ref { + if let Some(leaf) = view.leaf.filter(|leaf| leaf.present == M::All) { + return leaf; + } + if let Some((_, found)) = self.objects.iter().find(|(n, _)| n == view) { + return Ref { + slot: found.slot, + present: M::All, + }; + } + let out = self.slot(Shape::Dyn); + self.catalog.ops.push(Op::Materialize { + node: view.clone(), + out, + }); + self.objects.push(( + view.clone(), + Ref { + slot: out, + present: view.obj.unwrap_or(M::None), + }, + )); + Ref { + slot: out, + present: M::All, + } + } + + fn nodes(&mut self, step: &Step, visible: &[NodeIndex]) -> Option, Ref)>> { + if !step.nodes + || !crate::ZEN_CONFIG + .nodes_in_context + .load(std::sync::atomic::Ordering::Relaxed) + { + return None; + } + let views: Vec<(Arc, Node)> = visible + .iter() + .filter_map(|nid| { + Some(( + self.graph.step_at(*nid)?.node.name.clone(), + self.view(*nid)?, + )) + }) + .collect(); + Some( + views + .into_iter() + .map(|(name, view)| (name, self.whole(&view))) + .collect(), + ) + } + + fn child( + &mut self, + node: NodeIndex, + step: &Step, + input: &Node, + visible: &[NodeIndex], + ) -> Result { + let DecisionNodeKind::DecisionNode { content } = &step.node.kind else { + return Err(Refusal::Host(Hosted::Decision)); + }; + let subgraphs = self + .nested + .subgraphs + .clone() + .ok_or(Refusal::Child(ChildRefusal::Unresolved))?; + if self.nested.stack.contains(&content.key) { + return Err(Refusal::Child(ChildRefusal::Cycle)); + } + let child = subgraphs + .get(&content.key) + .cloned() + .ok_or(Refusal::Child(ChildRefusal::Unresolved))?; + let graph = Call::compiled(&child).map_err(|_| Refusal::Child(ChildRefusal::Unresolved))?; + if Self::validated(graph, &child) { + return Err(Refusal::Child(ChildRefusal::Schemas)); + } + let attributes = &content.transform_attributes; + if !matches!(attributes.execution_mode, TransformExecutionMode::Single) { + return Err(Refusal::Child(ChildRefusal::Loop)); + } + let view = match attributes.input_field.as_deref() { + None => input.clone(), + Some(field) if Self::plain(field) => match input.resolve(field, &self.catalog)? { + Resolved::Object(view) => view, + _ => return Err(Refusal::Child(ChildRefusal::InputField)), + }, + Some(_) => return Err(Refusal::Child(ChildRefusal::InputField)), + }; + if !Self::tree(&view, true) { + return Err(Refusal::Child(ChildRefusal::Whole)); + } + let mut leaves = Vec::new(); + view.leaves("", &mut leaves); + let layout = Layout( + leaves + .iter() + .map(|(path, r)| { + let shape = match self.catalog.shape(r.slot) { + shape @ (Shape::Num | Shape::Bool | Shape::Text) => shape, + _ => Shape::Dyn, + }; + (path.clone(), shape) + }) + .collect(), + ); + let stack: Arc<[Arc]> = self + .nested + .stack + .iter() + .cloned() + .chain([content.key.clone()]) + .collect(); + let (layout, bound) = graph.plan().nested(graph, layout, &subgraphs, stack); + let root = bound + .as_ref() + .as_ref() + .map_err(|refusal| Refusal::ChildPlan(Box::new(refusal.clone())))? + .clone(); + let SegEnd::Finish(refs) = &root.end else { + return Err(Refusal::Child(ChildRefusal::Branches)); + }; + if root.ops.iter().any(|op| { + matches!( + op, + Op::Join { + mode: JoinMode::Strict, + .. + } + ) + }) { + return Err(Refusal::Child(ChildRefusal::Strict)); + } + let mut keys = Vec::with_capacity(refs.len()); + let out = match refs.as_slice() { + [(path, r)] if path.is_empty() => { + if attributes.pass_through { + return Err(Refusal::Child(ChildRefusal::Whole)); + } + let slot = self.slot(root.slots[r.slot as usize].shape); + let present = self.masks.produced(); + keys.push(ChildKey { + path: path.clone(), + child: *r, + out: slot, + present, + }); + Node { + leaf: Some(Ref { slot, present }), + obj: None, + fields: Vec::new(), + } + } + refs => { + let mut out = Node::root(M::All); + for (path, r) in refs { + if path.is_empty() { + return Err(Refusal::Child(ChildRefusal::Whole)); + } + let slot = self.slot(root.slots[r.slot as usize].shape); + let present = self.masks.produced(); + out.insert(path, Ref { slot, present }, M::None)?; + keys.push(ChildKey { + path: path.clone(), + child: *r, + out: slot, + present, + }); + } + out.objects_from_leaves(&mut self.masks); + out.obj = Some(M::All); + out + } + }; + let record = Self::effects(graph, &subgraphs); + let nodes = self.nodes(step, visible); + self.catalog.ops.push(Op::Child(Box::new(ChildOp { + node, + view, + input: input.clone(), + nodes, + content: child, + root, + layout, + keys, + record, + }))); + let out = match attributes.output_path.as_deref() { + Some(path) => Node::wrap(out, path), + None => out, + }; + match attributes.pass_through { + true => Node::merge(input, &out, &mut self.masks, &mut self.catalog), + false => Ok(out), + } + } + + fn validated(graph: &CompiledGraph, content: &GraphContent) -> bool { + graph + .steps + .iter() + .flatten() + .any(|step| match &step.node.kind { + DecisionNodeKind::InputNode { content: input } => { + input.schema.is_some() + || content + .resolved_schemas + .as_ref() + .is_some_and(|resolved| resolved.contains_key(&step.node.id)) + } + DecisionNodeKind::OutputNode { .. } => false, + _ => content + .resolved_schemas + .as_ref() + .is_some_and(|resolved| resolved.contains_key(&step.node.id)), + }) + } + + fn effects(graph: &CompiledGraph, subgraphs: &Subgraphs) -> bool { + let impure = |graph: &CompiledGraph| { + graph.steps.iter().flatten().any(|step| { + matches!( + step.node.kind, + DecisionNodeKind::FunctionNode { .. } | DecisionNodeKind::CustomNode { .. } + ) + }) + }; + impure(graph) + || subgraphs + .closure(graph) + .iter() + .any(|(_, content)| Call::compiled(content).map_or(true, impure)) + } + + fn plain(field: &str) -> bool { + !field.is_empty() + && field.split('.').all(|segment| { + segment + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && segment + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') + }) + } + + fn tree(node: &Node, root: bool) -> bool { + match (node.leaf, root) { + (Some(_), true) => false, + (Some(_), false) => node.fields.is_empty(), + (None, _) => node + .fields + .iter() + .all(|(_, child)| Self::tree(child, false)), + } + } + + fn rows( + &mut self, + node: NodeIndex, + step: &Step, + input: &Node, + visible: &[NodeIndex], + reason: Arc, + ) -> Node { + let nodes = self.nodes(step, visible); + let out = self.slot(Shape::Dyn); + let keyed = self.attempt(|b| b.keyed(step)); + let Keyed { view, keys } = keyed.unwrap_or_else(|_| { + let leaf = Node { + leaf: Some(Ref { + slot: out, + present: M::All, + }), + obj: None, + fields: Vec::new(), + }; + Keyed { + view: leaf, + keys: Vec::new(), + } + }); + self.catalog.ops.push(Op::Rows(Box::new(RowsOp { + node, + view: input.clone(), + nodes, + out, + keys, + reason, + }))); + let merged = match &step.kind { + Kind::Node { transform, .. } if transform.pass_through && view.leaf.is_none() => self + .attempt(|b| Node::merge(input, &view, &mut b.masks, &mut b.catalog)) + .ok(), + _ => Some(view), + }; + merged.unwrap_or_else(|| { + if let Some(Op::Rows(op)) = self.catalog.ops.last_mut() { + op.keys.clear(); + } + Node { + leaf: Some(Ref { + slot: out, + present: M::All, + }), + obj: None, + fields: Vec::new(), + } + }) + } + + fn keyed(&mut self, step: &Step) -> Result { + let (keys, empty, transform) = match &step.kind { + Kind::Node { + body: Body::Expression { keys, empty, .. }, + transform, + } => (keys, empty, transform), + Kind::Node { + body: Body::Table(table), + transform, + } if table.first_hit() + && transform.output_path.is_none() + && transform.input_field.is_none() + && !transform.looped => + { + let mut out = Node::root(M::All); + let mut slots = Vec::new(); + for path in table.output_paths().iter() { + if path.is_empty() || path.contains('$') || path.split('.').any(str::is_empty) { + return Err(Refusal::Opaque); + } + let slot = self.slot(Shape::Dyn); + let present = self.masks.produced(); + out.insert(path, Ref { slot, present }, M::None)?; + slots.push((path.clone(), slot, present)); + } + out.objects_from_leaves(&mut self.masks); + out.obj = Some(M::All); + return Ok(Keyed { + view: out, + keys: slots, + }); + } + _ => return Err(Refusal::Opaque), + }; + if transform.looped + || keys.is_empty() + || keys + .iter() + .any(|k| k.is_empty() || k.contains('$') || k.split('.').any(str::is_empty)) + { + return Err(Refusal::Opaque); + } + let mut out = Node::root(M::All); + let mut slots = Vec::with_capacity(keys.len()); + for (key, empty) in keys.iter().zip(empty.iter()) { + if keys.iter().filter(|k| *k == key).count() > 1 { + return Err(Refusal::DuplicateKey); + } + let path: Arc = match &transform.output_path { + Some(prefix) => Arc::from(format!("{prefix}.{key}")), + None => key.clone(), + }; + match empty { + true => out.insert_object(&path, M::All)?, + false => { + let slot = self.slot(Shape::Dyn); + out.insert( + &path, + Ref { + slot, + present: M::All, + }, + M::All, + )?; + slots.push((path, slot, M::All)); + } + } + } + Ok(Keyed { + view: out, + keys: slots, + }) + } + + fn attempt( + &mut self, + f: impl FnOnce(&mut Self) -> Result, + ) -> Result { + let (slots, ops, objects, masks) = ( + self.catalog.slots.len(), + self.catalog.ops.len(), + self.objects.len(), + self.masks.clone(), + ); + f(self).inspect_err(|_| { + self.catalog.slots.truncate(slots); + self.catalog.ops.truncate(ops); + self.objects.truncate(objects); + self.masks = masks; + }) + } + + fn reason(step: &Step) -> Refusal { + if let Kind::Host(Some(why)) = &step.kind { + return Refusal::Uncompiled(why.clone()); + } + Refusal::Host(match &step.node.kind { + crate::model::DecisionNodeKind::FunctionNode { .. } => Hosted::Function, + crate::model::DecisionNodeKind::DecisionNode { .. } => Hosted::Decision, + crate::model::DecisionNodeKind::CustomNode { .. } => Hosted::Custom, + crate::model::DecisionNodeKind::OutputNode { .. } => Hosted::OutputSchema, + _ => Hosted::Node, + }) + } + + fn looped(&mut self, node: NodeIndex, step: &Step, input: &Node) -> Result { + let Kind::Node { transform, .. } = &step.kind else { + return Err(Refusal::NotLoop); + }; + let (Some(path), Some((program, _)), false) = + (&transform.output_path, &transform.input_field, step.nodes) + else { + return Err(Refusal::Loop); + }; + let list = match program.path() { + Some(source) => self + .read(input, source, None)? + .ok_or(Refusal::LoopSourceAbsent)?, + None => { + let slot = self.slot(Shape::Dyn); + let op = self.lane(node, Program::Field, program, input, None, vec![slot])?; + self.catalog.ops.push(Op::Lane(Box::new(op))); + Ref { + slot, + present: M::All, + } + } + }; + let out = self.slot(Shape::List); + self.catalog.ops.push(Op::Loop { node, list, out }); + let leaf = Node { + leaf: Some(Ref { + slot: out, + present: M::All, + }), + obj: None, + fields: Vec::new(), + }; + let output = Node::wrap(leaf, path); + match transform.pass_through { + true => Node::merge(input, &output, &mut self.masks, &mut self.catalog), + false => Ok(output), + } + } + + fn view(&self, node: NodeIndex) -> Option { + self.views + .iter() + .rev() + .find(|(n, _)| *n == node) + .map(|(_, v)| v.clone()) + } + + fn join(&mut self, views: &[Node], mode: JoinMode) -> Node { + let inputs = views.iter().map(|view| self.whole(view)).collect(); + let out = self.slot(Shape::Dyn); + self.catalog.ops.push(Op::Join { inputs, out, mode }); + Node { + leaf: Some(Ref { + slot: out, + present: M::All, + }), + obj: None, + fields: Vec::new(), + } + } + + fn relax(&mut self, data: &Node) { + let Some(leaf) = data.leaf else { + return; + }; + for op in self.catalog.ops.iter_mut().rev() { + if let Op::Join { out, mode, .. } = op { + if *out == leaf.slot { + if *mode == JoinMode::Strict { + *mode = JoinMode::Lenient; + } + return; + } + } + } + } + + fn data(&mut self, parents: &[NodeIndex]) -> Result { + let views: Vec = parents.iter().filter_map(|p| self.view(*p)).collect(); + if views.iter().any(|view| view.leaf.is_some()) { + return Ok(self.join(&views, JoinMode::Strict)); + } + let mut parents = views.into_iter(); + let mut acc = match parents.next() { + Some(head) => head.head(), + None => Node::root(M::All), + }; + for parent in parents { + acc = Node::merge(&acc, &parent, &mut self.masks, &mut self.catalog)?; + } + Ok(acc) + } + + fn segment(mut self, segment: Arc, layout: &Layout) -> Result { + for event in segment.events.iter() { + let step = self.graph.step_at(event.node).ok_or(Refusal::MissingStep)?; + let data = match step.kind { + Kind::Input => self.input(layout)?, + _ => self.data(&event.parents)?, + }; + let planned = match &step.kind { + Kind::Input | Kind::Switch { .. } => Ok(data.clone()), + Kind::Output if !step.schema => { + self.relax(&data); + Ok(data.clone()) + } + Kind::Host(_) + if self.nested.subgraphs.is_some() + && matches!(step.node.kind, DecisionNodeKind::DecisionNode { .. }) => + { + self.attempt(|b| b.child(event.node, step, &data, &event.visible)) + } + Kind::Output | Kind::Host(_) => Err(Self::reason(step)), + Kind::Node { .. } => match Plan::analyze_step(step) { + Err(reason) => Err(reason), + Ok(()) => match &step.kind { + Kind::Node { transform, .. } if transform.looped => { + self.attempt(|b| b.looped(event.node, step, &data)) + } + Kind::Node { + body: Body::Table(table), + .. + } => self.attempt(|b| b.table(event.node, step, table, &data)), + _ => self.attempt(|b| b.expression(event.node, step, &data)), + }, + }, + }; + let output = match planned { + Ok(output) => output, + Err(reason) => { + self.relax(&data); + let hosted = self.rows( + event.node, + step, + &data, + &event.visible, + Arc::from(reason.to_string()), + ); + self.hosted.push(reason); + match (&step.kind, data.leaf.is_none()) { + (Kind::Output, true) => data.clone(), + _ => hosted, + } + } + }; + self.views.push((event.node, output)); + } + let end = match &segment.end { + End::Finish(endings) => { + let views: Vec = endings + .iter() + .filter_map(|ending| self.view(*ending)) + .collect(); + let mut acc = Node::root(M::All); + match views.iter().any(|view| view.leaf.is_some()) { + true => acc = self.join(&views, JoinMode::Ending), + false => { + for view in &views { + acc = Node::merge(&acc, view, &mut self.masks, &mut self.catalog)?; + } + } + } + self.typed(); + let mut output = Vec::new(); + acc.leaves("", &mut output); + if output + .iter() + .any(|(path, _)| path.split('.').any(|s| s == "$nodes")) + { + return Err(Refusal::ReservedOutput); + } + SegEnd::Finish(output) + } + End::Switch { + node, + parents, + visible, + .. + } => { + self.typed(); + let step = self.graph.step_at(*node).ok_or(Refusal::MissingSwitch)?; + let Kind::Switch { first, conditions } = &step.kind else { + return Err(Refusal::NotSwitch); + }; + let input = self.data(parents)?; + let mut built = Vec::with_capacity(conditions.len()); + for (index, (_, condition)) in conditions.iter().enumerate() { + built.push(match condition { + Condition::Always => Cond::Always, + Condition::Invalid(_) => Cond::Never, + Condition::Program(program) => { + let lane = self.attempt(|b| { + let out = b.slot(Shape::Bool); + b.lane( + *node, + Program::Condition(index), + program, + &input, + None, + vec![out], + ) + }); + let op = match lane { + Ok(op) => op, + Err(refusal) => { + let refusal = Refusal::Condition(Box::new(refusal)); + let reason = Arc::from(refusal.to_string()); + self.hosted.push(refusal); + let whole = self.whole(&input); + let nodes = self.nodes(step, visible); + built.push(Cond::Rows(Box::new(RowsCond { + index, + node: *node, + input: whole, + nodes, + reason, + }))); + continue; + } + }; + match op.uniform && program.program().timeless() { + true => { + let scope = zen_expression::Scope::default(); + let truth = zen_expression::lane::LaneRunner::new() + .evaluate_one(program, &scope); + match truth { + Ok(zen_expression::Variable::Bool(true)) => Cond::Always, + _ => Cond::Never, + } + } + false => Cond::Lane(Box::new(op)), + } + } + }); + } + if built.iter().all(|cond| !matches!(cond, Cond::Lane(_))) { + self.relax(&input); + } + SegEnd::Switch { + first: *first, + ids: conditions.iter().map(|(id, _)| id.clone()).collect(), + conditions: built, + children: Children::new(), + } + } + }; + Ok(SegPlan { + segment, + slots: self.catalog.slots, + masks: self.masks, + ops: self.catalog.ops, + end, + hosted: self.hosted, + views: self.views, + nested: self.nested, + }) + } +} + +impl SegPlan { + fn collect(&self, hosted: &mut Vec) -> Result<(), Refusal> { + hosted.extend(self.hosted.iter().cloned()); + if let SegEnd::Switch { children, .. } = &self.end { + children.each(|child| { + child + .as_ref() + .as_ref() + .map_err(Refusal::clone)? + .collect(hosted) + })?; + } + Ok(()) + } + + pub fn child(&self, graph: &CompiledGraph, layout: &Layout, key: &[u64]) -> Bound { + let SegEnd::Switch { children, ids, .. } = &self.end else { + return Arc::new(Err(Refusal::NotSwitch)); + }; + children.get(key, || self.branch(graph, layout, ids, key)) + } + + fn branch( + &self, + graph: &CompiledGraph, + layout: &Layout, + ids: &[Arc], + key: &[u64], + ) -> Bound { + let outcome: Outcome = ids + .iter() + .enumerate() + .filter(|(index, _)| { + key.get(index / 64) + .is_some_and(|word| word >> (index % 64) & 1 == 1) + }) + .map(|(_, id)| id.clone()) + .collect(); + let segment = graph.child(&self.segment, outcome); + let builder = Builder { + graph, + masks: self.masks.clone(), + catalog: Catalog { + slots: self.slots.clone(), + ops: Vec::new(), + }, + views: self.views.clone(), + objects: Vec::new(), + hosted: Vec::new(), + null: None, + nested: self.nested.clone(), + }; + Arc::new(builder.segment(segment, layout).map(Arc::new)) + } +} + +impl Plan { + pub fn analyze(_graph: &CompiledGraph) -> Plan { + Plan { + roots: RwLock::new(Vec::new()), + } + } + + pub fn analyze_step(step: &Step) -> Result<(), Refusal> { + let schema = step.schema && !matches!(step.kind, Kind::Input); + let nodes = step.nodes && step.statics.is_none(); + if nodes || step.root || step.dynamic || schema { + return Err(match (nodes, step.root, step.dynamic) { + (true, _, _) => Refusal::Nodes, + (_, true, _) => Refusal::Root, + (_, _, true) => Self::dynamic(step), + _ => Refusal::Schema, + }); + } + match &step.kind { + Kind::Input | Kind::Output | Kind::Switch { .. } => Ok(()), + Kind::Node { .. } => Ok(()), + Kind::Host(_) => Err(Builder::reason(step)), + } + } + + fn dynamic(step: &Step) -> Refusal { + let mut programs: Vec<&LaneProgram> = Vec::new(); + match &step.kind { + Kind::Node { body, transform } => { + match body { + Body::Expression { program, .. } => programs.push(program), + Body::Table(table) => programs.extend(table.programs()), + } + programs.extend(transform.input_field.iter().map(|(p, _)| p)); + } + Kind::Switch { conditions, .. } => { + programs.extend(conditions.iter().filter_map(|(_, c)| match c { + Condition::Program(p) => Some(p.as_ref()), + _ => None, + })) + } + _ => {} + } + Refusal::Dynamic( + programs + .iter() + .map(|p| Needs::of(p)) + .filter(Needs::dynamic) + .collect(), + ) + } + + pub fn verdict(&self, graph: &CompiledGraph, columns: &Columns) -> Result<(), Refusal> { + let (_, root) = self + .root(graph, columns, None, &[]) + .ok_or(Refusal::Layout)?; + let plan = root.as_ref().as_ref().map_err(Refusal::clone)?; + let mut hosted = Vec::new(); + plan.collect(&mut hosted)?; + hosted.sort(); + hosted.dedup(); + match hosted.is_empty() { + true => Ok(()), + false => Err(Refusal::Mixed(hosted)), + } + } + + fn tag(column: &zen_expression::lane::Column) -> Shape { + match column.values { + Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_) => Shape::Num, + Values::Bool { .. } => Shape::Bool, + Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) => Shape::Text, + Values::Dict { values, .. } => match values { + Dictionary::Scaled { .. } => Shape::Num, + Dictionary::Bool { .. } => Shape::Bool, + Dictionary::Text { .. } => Shape::Text, + _ => Shape::Dyn, + }, + Values::List { .. } | Values::Struct { .. } | Values::Any(_) => Shape::Dyn, + } + } + + fn shape(index: usize, column: &zen_expression::lane::Column, dated: &[usize]) -> Shape { + match dated.contains(&index) { + true => Shape::Dyn, + false => Self::tag(column), + } + } + + fn layout(columns: &Columns, dated: &[usize]) -> Option { + columns + .columns + .iter() + .enumerate() + .map(|(index, (path, column))| { + (!path.is_empty()).then(|| (Arc::from(*path), Self::shape(index, column, dated))) + }) + .collect::>>() + .map(Layout) + } + + fn matches(layout: &Layout, columns: &Columns, dated: &[usize]) -> bool { + layout.0.len() == columns.columns.len() + && layout.0.iter().zip(&columns.columns).enumerate().all( + |(index, ((path, tag), (name, column)))| { + path.as_ref() == *name && *tag == Self::shape(index, column, dated) + }, + ) + } + + pub fn root( + &self, + graph: &CompiledGraph, + columns: &Columns, + subgraphs: Option<&Arc>, + dated: &[usize], + ) -> Option<(Arc, Bound)> { + let closure = subgraphs.map(|subgraphs| subgraphs.closure(graph)); + if let Ok(cache) = self.roots.read() { + if let Some(root) = cache.iter().find(|root| { + Self::matches(&root.layout, columns, dated) + && closure + .as_ref() + .is_none_or(|closure| Subgraphs::same(closure, &root.closure)) + }) { + return Some((root.layout.clone(), root.bound.clone())); + } + } + let layout = Arc::new(Self::layout(columns, dated)?); + let nested = Nested { + subgraphs: subgraphs.cloned(), + stack: Arc::from([]), + }; + let bound = self.build(graph, layout.clone(), closure.unwrap_or_default(), nested); + Some((layout, bound)) + } + + fn nested( + &self, + graph: &CompiledGraph, + layout: Layout, + subgraphs: &Arc, + stack: Arc<[Arc]>, + ) -> (Arc, Bound) { + let closure = subgraphs.closure(graph); + if let Ok(cache) = self.roots.read() { + if let Some(root) = cache + .iter() + .find(|root| *root.layout == layout && Subgraphs::same(&closure, &root.closure)) + { + return (root.layout.clone(), root.bound.clone()); + } + } + let layout = Arc::new(layout); + let nested = Nested { + subgraphs: Some(subgraphs.clone()), + stack, + }; + let bound = self.build(graph, layout.clone(), closure, nested); + (layout, bound) + } + + fn build( + &self, + graph: &CompiledGraph, + layout: Arc, + closure: Closure, + nested: Nested, + ) -> Bound { + let builder = Builder { + graph, + masks: Masks::default(), + catalog: Catalog::default(), + views: Vec::new(), + objects: Vec::new(), + hosted: Vec::new(), + null: None, + nested, + }; + let bound: Bound = Arc::new(builder.segment(graph.root.clone(), &layout).map(Arc::new)); + if let Ok(mut cache) = self.roots.write() { + cache.retain(|root| root.layout != layout); + if cache.len() >= 16 { + cache.remove(0); + } + cache.push(Root { + layout, + bound: bound.clone(), + closure, + }); + } + bound + } +} diff --git a/core/engine/src/compiled/graph/plan/refusal.rs b/core/engine/src/compiled/graph/plan/refusal.rs new file mode 100644 index 00000000..4eca4f63 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/refusal.rs @@ -0,0 +1,215 @@ +use std::fmt; +use std::sync::Arc; +use zen_expression::lane::LaneProgram; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) struct Needs { + pub env: bool, + pub chain: bool, + pub opaque: bool, + pub rows: bool, +} + +impl Needs { + pub fn of(program: &LaneProgram) -> Self { + let p = program.program(); + Self { + env: p.writes_env, + chain: p.chain, + opaque: p.opaque(), + rows: p.rows, + } + } + + pub fn dynamic(&self) -> bool { + self.env || self.chain || self.opaque + } + + pub fn any(&self) -> bool { + self.dynamic() || self.rows + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Hosted { + Function, + Decision, + Custom, + OutputSchema, + Node, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Overlap { + Leaf, + Object, + Value, + ObjectLeaf, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Refusal { + Nodes, + Root, + Schema, + Dynamic(Box<[Needs]>), + Host(Hosted), + Uncompiled(Arc), + Layout, + Program(Needs), + Rebase { key: Arc, base: Arc }, + DuplicateName(Arc), + WholeNodes, + RowRead(Arc), + Overlaps { path: Arc, with: Overlap }, + ThroughDynamic(Arc), + ValueOrObject(Arc), + NotExpression, + DynamicInputField, + OverlappingCopies, + ScalarInputField, + OutputArity, + DuplicateExpressionKey, + EmptyKeySegment, + NotTable, + TableInputField, + CollectTable, + TableNeedsRows, + TableCellRead(Arc), + TableRead(Arc), + Opaque, + DuplicateKey, + NotLoop, + Loop, + LoopSourceAbsent, + MissingStep, + ReservedOutput, + MissingSwitch, + NotSwitch, + Condition(Box), + Mixed(Vec), + Child(ChildRefusal), + ChildPlan(Box), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum ChildRefusal { + Unresolved, + Cycle, + Loop, + InputField, + Whole, + Branches, + Strict, + Schemas, +} + +impl fmt::Display for ChildRefusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + ChildRefusal::Unresolved => "unresolved", + ChildRefusal::Cycle => "cycle", + ChildRefusal::Loop => "loop", + ChildRefusal::InputField => "input field", + ChildRefusal::Whole => "whole input", + ChildRefusal::Branches => "branches", + ChildRefusal::Strict => "strict join", + ChildRefusal::Schemas => "schemas", + }) + } +} + +impl fmt::Display for Needs { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "env {} chain {} opaque {}", + self.env, self.chain, self.opaque + ) + } +} + +impl fmt::Display for Hosted { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Hosted::Function => "function", + Hosted::Decision => "decision", + Hosted::Custom => "custom", + Hosted::OutputSchema => "output schema", + Hosted::Node => "rows", + }) + } +} + +impl fmt::Display for Refusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Refusal::Nodes => f.write_str("nodes"), + Refusal::Root => f.write_str("root"), + Refusal::Schema => f.write_str("schema"), + Refusal::Dynamic(needs) => { + f.write_str("dynamic (")?; + for (at, need) in needs.iter().enumerate() { + if at > 0 { + f.write_str("; ")?; + } + write!(f, "{need}")?; + } + f.write_str(")") + } + Refusal::Host(hosted) => write!(f, "{hosted}"), + Refusal::Uncompiled(why) => write!(f, "uncompiled: {why}"), + Refusal::Layout => f.write_str("layout"), + Refusal::Program(needs) => { + write!(f, "program needs rows ({needs} rows {})", needs.rows) + } + Refusal::Rebase { key, base } => write!(f, "read {key} under {base}"), + Refusal::DuplicateName(name) => write!(f, "duplicate node name {name}"), + Refusal::WholeNodes => f.write_str("whole $nodes value"), + Refusal::RowRead(key) => write!(f, "read {key} needs the row"), + Refusal::Overlaps { path, with } => match with { + Overlap::Leaf => write!(f, "path {path} overlaps a leaf"), + Overlap::Object => write!(f, "path {path} overlaps an object"), + Overlap::Value => write!(f, "path {path} overlaps a value"), + Overlap::ObjectLeaf => write!(f, "object {path} overlaps a leaf"), + }, + Refusal::ThroughDynamic(path) => write!(f, "read {path} goes through a dynamic value"), + Refusal::ValueOrObject(path) => write!(f, "read {path} is a value or an object"), + Refusal::NotExpression => f.write_str("not an expression"), + Refusal::DynamicInputField => f.write_str("dynamic input field"), + Refusal::OverlappingCopies => f.write_str("dollar copies under overlapping keys"), + Refusal::ScalarInputField => f.write_str("input field may hold a scalar"), + Refusal::OutputArity => f.write_str("output arity"), + Refusal::DuplicateExpressionKey => f.write_str("duplicate expression key"), + Refusal::EmptyKeySegment => f.write_str("empty key segment"), + Refusal::NotTable => f.write_str("not a table"), + Refusal::TableInputField => f.write_str("table input field"), + Refusal::CollectTable => f.write_str("collect table"), + Refusal::TableNeedsRows => f.write_str("table program needs rows"), + Refusal::TableCellRead(key) => write!(f, "table cell reads {key} through its column"), + Refusal::TableRead(key) => write!(f, "table read {key}"), + Refusal::Opaque => f.write_str("opaque"), + Refusal::DuplicateKey => f.write_str("duplicate key"), + Refusal::NotLoop => f.write_str("not a loop"), + Refusal::Loop => f.write_str("loop"), + Refusal::LoopSourceAbsent => f.write_str("loop source absent"), + Refusal::MissingStep => f.write_str("missing step"), + Refusal::ReservedOutput => f.write_str("reserved output"), + Refusal::MissingSwitch => f.write_str("missing switch"), + Refusal::NotSwitch => f.write_str("not a switch"), + Refusal::Condition(inner) => write!(f, "condition: {inner}"), + Refusal::Child(why) => write!(f, "child: {why}"), + Refusal::ChildPlan(inner) => write!(f, "child plan: {inner}"), + Refusal::Mixed(all) => { + f.write_str("mixed: ")?; + for (at, refusal) in all.iter().enumerate() { + if at > 0 { + f.write_str(", ")?; + } + write!(f, "{refusal}")?; + } + Ok(()) + } + } + } +} diff --git a/core/engine/src/compiled/graph/plan/run/assemble.rs b/core/engine/src/compiled/graph/plan/run/assemble.rs new file mode 100644 index 00000000..2dfe4c5e --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/assemble.rs @@ -0,0 +1,271 @@ +use super::store::{Group, Origin, Store, View}; +use super::{Host, Run}; +use crate::compiled::graph::columnar::Admitted; +use crate::compiled::graph::plan::subgraphs::Subgraphs; +use crate::compiled::graph::plan::Plan; +use crate::compiled::graph::{ColumnarOutput, CompiledGraph, Completed, Kind}; +use crate::compiled::leaf::{Bits, ColumnBuilder, Leaf}; +use crate::compiled::output::OutputColumn; +use crate::model::GraphContent; +use crate::nodes::NodeHandlerExtensions; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Column, Columns, Dictionary, Values}; + +impl<'a> Run<'_, 'a> { + fn assemble(store: Store<'a>) -> ColumnarOutput<'a> { + let rows = store.rows; + let mut store = store; + let groups = std::mem::take(&mut store.groups); + let finish = |leaf: &Leaf<'a>, presence: &Option>| match presence { + None => leaf.clone(), + Some(mask) => Leaf::masked(leaf.clone(), mask), + }; + let columns: Vec<(Arc, Leaf<'a>)> = match groups.as_slice() { + [Group { + positions: None, + leaves, + }] => leaves + .iter() + .map(|(path, leaf, presence)| (path.clone(), finish(leaf, presence))) + .collect(), + _ => { + let mut owner: Vec> = vec![None; rows]; + let mut reach: Vec> = Vec::with_capacity(groups.len()); + for (g, Group { positions, .. }) in groups.iter().enumerate() { + let mut bits = vec![0u64; rows.div_ceil(64)]; + match positions { + Some(positions) => positions.iter().enumerate().for_each(|(i, &row)| { + owner[row] = Some((g, i)); + Bits::set(&mut bits, row, true); + }), + None => (0..rows).for_each(|row| { + owner[row] = Some((g, row)); + Bits::set(&mut bits, row, true); + }), + } + reach.push(bits); + } + let mut paths: Vec> = Vec::new(); + for Group { leaves, .. } in &groups { + for (path, _, _) in leaves { + if !paths.contains(path) { + paths.push(path.clone()); + } + } + } + paths + .into_iter() + .map(|path| { + let sources: Vec> = groups + .iter() + .map(|Group { leaves, .. }| { + leaves + .iter() + .find(|(p, _, _)| *p == path) + .map(|(_, l, m)| (l, m)) + }) + .collect(); + if let Some(Some((first, _))) = sources.iter().find(|s| s.is_some()) { + if sources.iter().flatten().all(|(s, _)| s.same(first)) { + if sources.iter().all(|s| s.is_some_and(|(_, m)| m.is_none())) { + return (path, (*first).clone()); + } + let mut combined = vec![0u64; rows.div_ceil(64)]; + for (source, bits) in sources.iter().zip(&reach) { + match source { + None => {} + Some((_, Some(mask))) => combined + .iter_mut() + .zip(bits.iter().zip(mask.iter())) + .for_each(|(c, (b, m))| *c |= b & m), + Some((_, None)) => { + combined.iter_mut().zip(bits).for_each(|(c, b)| *c |= b) + } + } + } + return (path, Leaf::masked((*first).clone(), &combined.into())); + } + } + let views: Vec> = sources + .iter() + .zip(&groups) + .map(|(source, Group { positions, .. })| { + source.map(|(leaf, presence)| { + match (leaf.scatter_parts(), positions) { + (Some((inner, at)), Some(positions)) + if Rc::ptr_eq(at, positions) => + { + View { + column: inner.column(), + local: true, + presence: presence.as_ref(), + dict: inner.coded_dict(), + } + } + _ => View { + column: leaf.column(), + local: false, + presence: presence.as_ref(), + dict: leaf.coded_dict(), + }, + } + }) + }) + .collect(); + let located = |row: usize| -> Option<(usize, &Column, usize)> { + let (g, i) = owner[row]?; + let view = views[g].as_ref()?; + if view.presence.is_some_and(|p| !Bits::get(p, row)) { + return None; + } + let at = if view.local { i } else { row }; + view.column.valid(at).then_some((g, &view.column, at)) + }; + let cell = |row: usize| located(row).map(|(_, view, at)| (view, at)); + if let Some(array) = Self::coded_gather(rows, &views, &located) { + return (path, Leaf::typed(array)); + } + let family = |column: &Column| match column.values { + Values::Scaled { .. } + | Values::I64(_) + | Values::Dict { + values: Dictionary::Scaled { .. }, + .. + } => 0u8, + Values::Bool { .. } + | Values::Dict { + values: Dictionary::Bool { .. }, + .. + } => 1, + Values::Text { .. } + | Values::Utf8 { .. } + | Values::Dict { + values: Dictionary::Text { .. }, + .. + } => 2, + _ => 3, + }; + let families: Vec = views + .iter() + .flatten() + .map(|view| family(&view.column)) + .collect(); + let common = families + .first() + .copied() + .filter(|f| families.iter().all(|x| x == f)); + if let Some(array) = Self::typed_gather(rows, common, &cell) { + return (path, Leaf::typed(array)); + } + let mut builder = ColumnBuilder::with_capacity(rows); + for row in 0..rows { + match cell(row) { + Some((view, at)) => builder.push_cell(view, at), + None => builder.push_null(), + } + } + (path, Leaf::typed(builder.finish())) + }) + .collect() + } + }; + ColumnarOutput { + rows, + columns: columns + .into_iter() + .map(|(path, leaf)| (path, OutputColumn(CompiledGraph::cleaned(&leaf)))) + .collect(), + errors: store.errors.take(), + paths: crate::diagnostics::Paths { + typed: store.counts.0, + laned: store.counts.1, + hosted: 0, + }, + } + } +} + +impl Plan { + #[allow(clippy::too_many_arguments)] + pub async fn evaluate<'a>( + &self, + graph: &CompiledGraph, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + columns: &'a Columns<'a>, + admitted: Admitted<'a>, + ) -> PlanOutcome<'a> { + if let Some(resolved) = &content.resolved_schemas { + let touched = graph.steps.iter().flatten().any(|step| { + !matches!(step.kind, Kind::Input | Kind::Output) + && resolved.contains_key(&step.node.id) + }); + if touched { + return PlanOutcome::Skipped; + } + } + let Admitted { failures, dated } = admitted; + let indexes: Vec = dated.iter().map(|(index, _)| *index).collect(); + let subgraphs = match Subgraphs::wanted(graph) { + true => Some(Arc::new(Subgraphs::resolve(graph, extensions).await)), + false => None, + }; + let Some((layout, root)) = self.root(graph, columns, subgraphs.as_ref(), &indexes) else { + return PlanOutcome::Skipped; + }; + let Ok(root) = root.as_ref().as_ref() else { + return PlanOutcome::Skipped; + }; + let mut store = Store::new(root, columns, dated); + for (row, error) in failures { + store.errors.set(row, error); + } + let mut run = Run { + graph, + layout: &layout, + runner: CompiledGraph::RUNNER.with_borrow_mut(std::mem::take), + host: Host { + content, + extensions, + max_depth, + }, + store, + settled: true, + failures: Vec::new(), + shreds: Vec::new(), + completed: Completed::default(), + iteration: 0, + parents: None, + }; + run.walk(root.clone()).await; + let Run { + runner, + store, + completed, + .. + } = run; + CompiledGraph::RUNNER.with_borrow_mut(|slot| *slot = runner); + let rows = store.errors.deferred(); + let output = Run::assemble(store); + match rows.is_empty() { + true => PlanOutcome::Done(output), + false => PlanOutcome::Partial { + output, + rows, + completed, + }, + } + } +} + +pub(crate) enum PlanOutcome<'a> { + Skipped, + Done(ColumnarOutput<'a>), + Partial { + output: ColumnarOutput<'a>, + rows: Vec, + completed: Completed, + }, +} diff --git a/core/engine/src/compiled/graph/plan/run/child.rs b/core/engine/src/compiled/graph/plan/run/child.rs new file mode 100644 index 00000000..c2e3867a --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/child.rs @@ -0,0 +1,391 @@ +use super::store::{Layered, Store}; +use super::Run; +use crate::compiled::census::Census; +use crate::compiled::graph::call::Call; +use crate::compiled::graph::data::Data; +use crate::compiled::graph::plan::view::Shape; +use crate::compiled::graph::plan::{ChildOp, Plan, SegPlan}; +use crate::compiled::graph::{CompiledGraph, Completed, Host, Kind}; +use crate::compiled::leaf::{Array, Bits, Leaf}; +use crate::model::DecisionNodeKind; +use crate::nodes::{NodeError, NodeHandlerExtensions}; +use crate::EvaluationError; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Column, Columns}; +use zen_expression::Variable; +use zen_types::symbol::Symbol; +use zen_types::variable::VariableMap; + +struct Produced<'a> { + leaves: Vec<(Leaf<'a>, Rc<[u64]>)>, + failed: Vec<(usize, NodeError)>, +} + +impl CompiledGraph { + pub(in crate::compiled::graph) fn input_name(&self) -> Option> { + self.steps + .iter() + .flatten() + .find(|step| matches!(step.kind, Kind::Input)) + .map(|step| step.node.name.clone()) + } +} + +impl<'a> Run<'_, 'a> { + pub(super) async fn child( + &mut self, + seg: &SegPlan, + op: &ChildOp, + positions: Option<&Rc<[usize]>>, + ) { + let graph = self.graph; + let Some(step) = graph.step_at(op.node) else { + return; + }; + let DecisionNodeKind::DecisionNode { content } = &step.node.kind else { + return; + }; + let at: Rc<[usize]> = positions + .cloned() + .unwrap_or_else(|| (0..self.store.rows).collect()); + let count = at.len(); + let produced = match self.iteration.saturating_add(1) >= self.host.max_depth { + true => Produced { + leaves: Vec::new(), + failed: (0..count) + .map(|i| { + ( + i, + NodeError::new( + step.node.id.clone(), + EvaluationError::DepthLimitExceeded.to_string(), + ), + ) + }) + .collect(), + }, + false => match self.columns(seg, op, &at) { + Some(leaves) => { + Census::mark("columnar"); + self.nested(op, &step.node.id, content, &at, leaves).await + } + None => { + Census::mark("batched"); + self.fallback(seg, op, content, positions, &at).await + } + }, + }; + let mut failed = vec![false; count]; + for (i, error) in produced.failed { + failed[i] = true; + self.store.errors.fault(at[i], error); + } + let mut placed: Vec<(Leaf<'a>, Rc<[u64]>)> = Vec::with_capacity(op.keys.len()); + for (index, key) in op.keys.iter().enumerate() { + let (leaf, bits) = match produced.leaves.get(index) { + Some((leaf, bits)) => { + let mut bits = bits.to_vec(); + for (i, &fail) in failed.iter().enumerate() { + if fail { + Bits::set(&mut bits, i, false); + } + } + (leaf.clone(), Rc::<[u64]>::from(bits)) + } + None => (Leaf::nulls(count), Rc::from(vec![0u64; count.div_ceil(64)])), + }; + let spread = self.store.spread(&bits, positions); + let leaf_at = self.store.place(leaf.clone(), positions); + self.store.slots[key.out as usize] = Some(leaf_at); + self.store.produce(key.present, spread); + placed.push((leaf, bits)); + } + if op.record { + self.record(seg, op, &step.node.id, content, &at, &placed, &failed); + } + } + + fn columns(&mut self, seg: &SegPlan, op: &ChildOp, at: &Rc<[usize]>) -> Option>> { + let mut layered: Vec> = Vec::new(); + self.layer(seg, &op.view, "", &mut layered)?; + if layered.len() != op.layout.0.len() { + return None; + } + let count = at.len(); + let full = count == self.store.rows; + let mut leaves = Vec::with_capacity(layered.len()); + for (path, shape) in &op.layout.0 { + let (_, leaf, bits) = layered.iter().find(|(p, _, _)| p == path)?; + let (leaf, bits): (Leaf<'a>, Rc<[u64]>) = match full { + true => (leaf.clone(), bits.clone()), + false => ( + leaf.pick(at), + Bits::of(count, |i| Bits::get(bits, at[i])).into(), + ), + }; + let leaf = match Bits::full(&bits, 0, count) { + true => leaf, + false => Leaf::masked(leaf, &bits), + }; + let tag = Plan::tag(&leaf.column()); + if matches!(shape, Shape::Num | Shape::Bool | Shape::Text) && tag != *shape { + return None; + } + leaves.push(leaf); + } + Some(leaves) + } + + async fn nested( + &mut self, + op: &ChildOp, + id: &Arc, + content: &zen_types::decision::DecisionNodeContent, + at: &Rc<[usize]>, + leaves: Vec>, + ) -> Produced<'a> { + let count = at.len(); + let Ok(graph) = Call::compiled(&op.content) else { + return Produced { + leaves: Vec::new(), + failed: Vec::new(), + }; + }; + let columns = Columns { + rows: count, + columns: op + .layout + .0 + .iter() + .zip(&leaves) + .map(|((path, _), leaf)| (path.as_ref(), leaf.column())) + .collect::>(), + }; + let call = Call { + key: &content.key, + extensions: self.host.extensions, + max_depth: self.host.max_depth, + iteration: self.iteration, + }; + let extensions = NodeHandlerExtensions { + function_runtime: Default::default(), + ..call.sub_extensions(&op.content) + }; + let named: Vec<(&Arc, Symbol, Leaf<'a>)> = op + .nodes + .iter() + .flatten() + .map(|(name, r)| (name, Symbol::from(name.as_ref()), self.store.leaf(r.slot))) + .collect(); + let outer = self.parents; + let entry = outer.and_then(|_| self.graph.input_name()); + let parents = |row: usize| -> Option { + op.nodes.as_ref()?; + let source = *at.get(row)?; + let mut map = VariableMap::with_capacity(named.len()); + for (original, name, leaf) in &named { + let value = leaf.get(source); + let value = match (&entry, outer) { + (Some(entry), Some(outer)) if *original == entry => match outer(source) { + Some(parent) => { + let view = value.depth_clone(1); + view.dot_insert(Variable::nodes_key().as_ref(), parent); + view + } + None => value, + }, + _ => value, + }; + map.insert(name.clone(), value); + } + Some(Variable::from_object(map)) + }; + let store = Store::new(&op.root, &columns, Vec::new()); + let mut run = Run { + graph, + layout: &op.layout, + runner: std::mem::take(&mut self.runner), + host: Host { + content: &op.content, + extensions: &extensions, + max_depth: self.host.max_depth, + }, + store, + settled: true, + failures: Vec::new(), + shreds: Vec::new(), + completed: Completed::default(), + iteration: self.iteration + 1, + parents: Some(&parents), + }; + Box::pin(run.walk(op.root.clone())).await; + let Run { + runner, mut store, .. + } = run; + self.runner = runner; + let deferred = store.errors.deferred(); + for &row in &deferred { + self.store.errors.defer(at[row]); + } + let failed: Vec<(usize, NodeError)> = (0..count) + .filter(|&row| !deferred.contains(&row)) + .filter_map(|row| { + let error = store.errors.get(row)?; + Some((row, NodeError::new(id.clone(), error.to_string()))) + }) + .collect(); + let mut produced = Vec::with_capacity(op.keys.len()); + for key in &op.keys { + let leaf = store.leaf(key.child.slot); + let bits = store.mask(&op.root, key.child.present); + produced.push((Self::detach(&leaf, count), bits)); + } + Produced { + leaves: produced, + failed, + } + } + + fn detach<'x>(leaf: &Leaf<'_>, rows: usize) -> Leaf<'x> { + match leaf { + Leaf::Typed(array) => Leaf::Typed(array.clone()), + Leaf::Any(values) => Leaf::Any(values.clone()), + Leaf::Templated(templated) => Leaf::Templated(templated.clone()), + other => { + let positions: Vec = (0..rows).collect(); + Leaf::typed(Array::gather(&other.column(), &positions)) + } + } + } + + async fn fallback( + &mut self, + seg: &SegPlan, + op: &ChildOp, + content: &zen_types::decision::DecisionNodeContent, + positions: Option<&Rc<[usize]>>, + at: &Rc<[usize]>, + ) -> Produced<'a> { + let count = at.len(); + let (_, inputs, nodes) = self.inputs(seg, Some(&op.view), &op.nodes, positions); + let step = self.graph.step_at(op.node); + let Some(step) = step else { + return Produced { + leaves: Vec::new(), + failed: Vec::new(), + }; + }; + let results = CompiledGraph::nested_results( + step, + content, + &op.content, + &inputs, + &nodes, + self.host.extensions, + self.host.max_depth, + self.iteration, + ) + .await; + let mut failed = Vec::new(); + let values: Vec> = results + .into_iter() + .enumerate() + .map(|(i, result)| match result { + Ok(value) => Some(value), + Err(error) => { + failed.push((i, error)); + None + } + }) + .collect(); + let leaves = op + .keys + .iter() + .map(|key| { + let mut bits = vec![0u64; count.div_ceil(64)]; + let column: Vec = values + .iter() + .enumerate() + .map(|(i, value)| { + let found = value.as_ref().and_then(|value| match key.path.is_empty() { + true => Some(value.clone()), + false => Data::lookup(value, &key.path), + }); + match found { + Some(found) => { + Bits::set(&mut bits, i, true); + found + } + None => Variable::Null, + } + }) + .collect(); + (Leaf::Any(column.into()), Rc::<[u64]>::from(bits)) + }) + .collect(); + Produced { leaves, failed } + } + + #[allow(clippy::too_many_arguments)] + fn record( + &mut self, + seg: &SegPlan, + op: &ChildOp, + id: &Arc, + content: &zen_types::decision::DecisionNodeContent, + at: &Rc<[usize]>, + placed: &[(Leaf<'a>, Rc<[u64]>)], + failed: &[bool], + ) { + let attributes = &content.transform_attributes; + let input = attributes + .pass_through + .then(|| self.materialize(seg, &op.input)); + let results: Vec> = (0..at.len()) + .map(|i| { + if failed[i] { + return Err(NodeError::new(id.clone(), String::new())); + } + let value = match op.keys.first() { + Some(key) if key.path.is_empty() => placed + .first() + .map_or(Variable::Null, |(leaf, _)| leaf.get(i)), + _ => { + let object = Variable::empty_object(); + for (key, (leaf, bits)) in op.keys.iter().zip(placed) { + if !Bits::get(bits, i) { + continue; + } + let value = leaf.get(i); + if !matches!(value, Variable::Null) { + object.dot_insert(&key.path, value); + } + } + object + } + }; + let source = input + .as_ref() + .map_or(Variable::Null, |leaf| leaf.get(at[i])); + Ok(crate::compiled::exact::Attributes::finish( + attributes.output_path.as_deref(), + attributes.pass_through, + &source, + value, + )) + }) + .collect(); + self.completed + .record(op.node, self.store.rows, at, &results); + } + + pub(super) fn measured(&self, positions: Option<&Rc<[usize]>>) { + let rows = positions.map_or(self.store.rows, |p| p.len()); + Census::record( + format!("decision | child | {}", Census::path()), + rows, + Census::elapsed(), + ); + } +} diff --git a/core/engine/src/compiled/graph/plan/run/fanout.rs b/core/engine/src/compiled/graph/plan/run/fanout.rs new file mode 100644 index 00000000..720e622c --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/fanout.rs @@ -0,0 +1,188 @@ +use super::store::Branch; +use super::Run; +use crate::compiled::graph::plan::{Cond, SegPlan}; +use crate::compiled::leaf::Bits; +use std::rc::Rc; + +impl<'a> Run<'_, 'a> { + pub(super) fn fan_out( + &mut self, + seg: &SegPlan, + positions: Option<&Rc<[usize]>>, + first: bool, + conditions: &[Cond], + children: &mut Vec, + ) { + let rows = self.store.rows; + let truths: Vec>> = conditions + .iter() + .map(|condition| match condition { + Cond::Always => Some(self.store.ones.clone()), + Cond::Never => None, + Cond::Rows(op) => Some(self.rows_condition(seg, op, positions).into()), + Cond::Lane(op) => { + let uniform = op.uniform; + let first: Rc<[usize]>; + let local = match uniform { + true => { + first = + Rc::from([positions.and_then(|p| p.first().copied()).unwrap_or(0)]); + Some(&first) + } + false => positions, + }; + self.lane(seg, op, local, false); + let slot = op.outs.first().copied().unwrap_or_default(); + let leaf = self.store.leaf(slot); + match (uniform, leaf.scatter_parts()) { + (true, Some((inner, _))) => { + inner.truthy(0).then(|| self.store.ones.clone()) + } + _ => Some(leaf.truths(rows).into()), + } + } + }) + .collect(); + let words = conditions.len().div_ceil(64).max(1); + let ones = self.store.ones.clone(); + let owned: Vec; + let reach_bits: &[u64] = match positions { + None => &ones, + Some(p) => { + let mut bits = vec![0u64; rows.div_ceil(64)]; + p.iter().for_each(|&row| Bits::set(&mut bits, row, true)); + owned = bits; + &owned + } + }; + let uniform = truths + .iter() + .all(|t| t.as_ref().is_none_or(|t| Rc::ptr_eq(t, &ones))); + let mut keys: Vec = Vec::with_capacity(words * (conditions.len() + 1)); + let mut sets: Vec> = Vec::with_capacity(conditions.len() + 1); + let members = |bits: &[u64]| -> Vec { + let mut found = + Vec::with_capacity(bits.iter().map(|word| word.count_ones() as usize).sum()); + found.extend(Bits::rows(bits)); + found + }; + if uniform || first { + let mut remaining = reach_bits.to_vec(); + let mut hits = vec![0u64; remaining.len()]; + for (index, truth) in truths.iter().enumerate() { + let Some(truth) = truth else { + continue; + }; + let hit = &mut hits[..remaining.len().min(truth.len())]; + hit.iter_mut() + .zip(remaining.iter().zip(truth.iter())) + .for_each(|(h, (r, t))| *h = r & t); + if Bits::none(hit) { + continue; + } + let at = keys.len(); + keys.resize(at + words, 0); + if uniform && !first { + for (i, t) in truths.iter().enumerate() { + if t.is_some() { + keys[at + i / 64] |= 1 << (i % 64); + } + } + sets.push(members(hit)); + remaining.fill(0); + break; + } + keys[at + index / 64] |= 1 << (index % 64); + remaining + .iter_mut() + .zip(hit.iter()) + .for_each(|(r, h)| *r &= !h); + sets.push(match *hit == *reach_bits { + true => Vec::new(), + false => members(hit), + }); + } + if !Bits::none(&remaining) { + keys.resize(keys.len() + words, 0); + sets.push(match remaining.as_slice() == reach_bits { + true => Vec::new(), + false => members(&remaining), + }); + } + } else if words == 1 { + let mut last = 0usize; + let mut visit = |row: usize| { + let key = truths + .iter() + .enumerate() + .filter(|(_, t)| t.as_ref().is_some_and(|t| Bits::get(t, row))) + .fold(0u64, |k, (index, _)| k | 1 << index); + let at = match keys.get(last).is_some_and(|k| *k == key) { + true => last, + false => match keys.iter().position(|k| *k == key) { + Some(g) => g, + None => { + keys.push(key); + sets.push(Vec::new()); + keys.len() - 1 + } + }, + }; + sets[at].push(row); + last = at; + }; + match positions { + Some(p) => p.iter().for_each(|&row| visit(row)), + None => (0..rows).for_each(&mut visit), + } + } else { + let mut key = vec![0u64; words]; + let mut last: Option = None; + let mut visit = |row: usize| { + key.fill(0); + for (index, truth) in truths.iter().enumerate() { + if truth.as_ref().is_some_and(|t| Bits::get(t, row)) { + key[index / 64] |= 1 << (index % 64); + } + } + let at = match last + .filter(|&g| keys.get(g * words..(g + 1) * words) == Some(key.as_slice())) + { + Some(g) => g, + None => match keys.chunks_exact(words).position(|k| k == key.as_slice()) { + Some(g) => g, + None => { + keys.extend_from_slice(&key); + sets.push(Vec::new()); + sets.len() - 1 + } + }, + }; + sets[at].push(row); + last = Some(at); + }; + match positions { + Some(p) => p.iter().for_each(|&row| visit(row)), + None => (0..rows).for_each(&mut visit), + } + } + for (key, members) in keys.chunks_exact(words).zip(sets) { + let child = seg.child(self.graph, self.layout, key); + let Ok(child) = child.as_ref().as_ref() else { + for &row in &members { + self.store.errors.defer(row); + } + continue; + }; + let members: Option> = match (members.is_empty(), members.len() == rows) { + (true, _) => positions.cloned(), + (false, true) => None, + (false, false) => Some(members.into()), + }; + children.push(Branch { + seg: child.clone(), + positions: members, + }); + } + } +} diff --git a/core/engine/src/compiled/graph/plan/run/gather.rs b/core/engine/src/compiled/graph/plan/run/gather.rs new file mode 100644 index 00000000..1bb823c7 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/gather.rs @@ -0,0 +1,216 @@ +use super::store::View; +use super::Run; +use crate::compiled::leaf::{Array, Bits, ColumnBuilder, Dict, Leaf, Literal, Store as Buffer}; +use std::rc::Rc; +use zen_expression::lane::{Column, Dictionary, Values}; + +impl<'a> Run<'_, 'a> { + pub(super) fn coded_gather<'v>( + rows: usize, + views: &'v [Option>], + located: &dyn Fn(usize) -> Option<(usize, &'v Column<'v>, usize)>, + ) -> Option { + let mut unique: Vec<&Rc> = Vec::new(); + let mut slot = Vec::with_capacity(views.len()); + for view in views { + match view { + None => slot.push(0), + Some(view) => { + let dict = view.dict?; + let index = match unique.iter().position(|d| Rc::ptr_eq(d, dict)) { + Some(index) => index, + None => { + unique.push(dict); + unique.len() - 1 + } + }; + slot.push(index); + } + } + } + let (dict, bases) = Dict::concat(&unique)?; + let mut valid = vec![0u64; rows.div_ceil(64)]; + let codes: Rc<[i32]> = (0..rows) + .map(|row| { + let Some((g, view, at)) = located(row) else { + return -1; + }; + match view.code(at) { + Some(code) => { + Bits::on(&mut valid, row); + code as i32 + bases[slot[g]] + } + None => -1, + } + }) + .collect(); + Some(Array::coded_with(codes, dict, valid)) + } + + pub(super) fn coalesced(column: &Column, value: &Literal, rows: usize) -> Array { + let typed = match value { + Literal::Num(n) => Literal::Num(*n).scaled().and_then(|fill| { + let (mut mant, mut scale) = (vec![0i64; rows], vec![0u8; rows]); + for row in 0..rows { + let (m, s) = match column.valid(row) { + false => fill, + true => column.parts(row)?, + }; + mant[row] = m; + scale[row] = s; + } + Some(Array::parts(Buffer::Scaled { mant, scale }, None, rows)) + }), + Literal::Str(fill) => { + let mut offsets = Vec::with_capacity(rows + 1); + let mut data = String::new(); + offsets.push(0i32); + let mut ok = true; + for row in 0..rows { + match column.valid(row) { + false => data.push_str(fill), + true => match column.text(row) { + Some(text) => data.push_str(text), + None => { + ok = false; + break; + } + }, + } + offsets.push(data.len() as i32); + } + ok.then(|| Array::parts(Buffer::Text { offsets, data }, None, rows)) + } + Literal::Bool(fill) => { + let mut ok = true; + let bits = Bits::of(rows, |row| match column.valid(row) { + false => *fill, + true => column.boolean(row).unwrap_or_else(|| { + ok = false; + false + }), + }); + ok.then(|| Array::parts(Buffer::Bool(bits), None, rows)) + } + _ => None, + }; + typed.unwrap_or_else(|| { + let mut builder = ColumnBuilder::with_capacity(rows); + for row in 0..rows { + match column.valid(row) { + true => builder.push_cell(column, row), + false => builder.push_literal(value), + } + } + builder.finish() + }) + } + + fn selected(a: &Column, b: &Column, take: &[u64], rows: usize) -> Option { + let numeric = |column: &Column| { + matches!( + column.values, + Values::Scaled { .. } + | Values::I64(_) + | Values::Dict { + values: Dictionary::Scaled { .. }, + .. + } + ) || (0..rows).all(|row| !column.valid(row)) + }; + if !numeric(a) || !numeric(b) { + return None; + } + let (mut mant, mut scale) = (vec![0i64; rows], vec![0u8; rows]); + let mut valid = vec![0u64; rows.div_ceil(64)]; + for row in 0..rows { + let source = match Bits::get(take, row) { + true => b, + false => a, + }; + if !source.valid(row) { + continue; + } + let (m, s) = source.parts(row)?; + mant[row] = m; + scale[row] = s; + Bits::on(&mut valid, row); + } + Some(Array::parts( + Buffer::Scaled { mant, scale }, + Some(valid), + rows, + )) + } + + pub(super) fn typed_gather<'c>( + rows: usize, + family: Option, + cell: &dyn Fn(usize) -> Option<(&'c Column<'c>, usize)>, + ) -> Option { + let mut valid = vec![0u64; rows.div_ceil(64)]; + match family? { + 0 => { + let (mut mant, mut scale) = (vec![0i64; rows], vec![0u8; rows]); + for row in 0..rows { + let Some((view, at)) = cell(row) else { + continue; + }; + if let Some((m, s)) = view.parts(at) { + mant[row] = m; + scale[row] = s; + Bits::on(&mut valid, row); + } + } + Some(Array::parts( + Buffer::Scaled { mant, scale }, + Some(valid), + rows, + )) + } + 1 => { + let mut bits = vec![0u64; rows.div_ceil(64)]; + for row in 0..rows { + if let Some(b) = cell(row).and_then(|(view, at)| view.boolean(at)) { + Bits::set(&mut bits, row, b); + Bits::on(&mut valid, row); + } + } + Some(Array::parts(Buffer::Bool(bits), Some(valid), rows)) + } + 2 => { + let mut offsets = Vec::with_capacity(rows + 1); + let mut data = String::new(); + offsets.push(0i32); + for row in 0..rows { + if let Some(text) = cell(row).and_then(|(view, at)| view.text(at)) { + data.push_str(text); + Bits::on(&mut valid, row); + } + offsets.push(data.len() as i32); + } + Some(Array::parts( + Buffer::Text { offsets, data }, + Some(valid), + rows, + )) + } + _ => None, + } + } + + pub(super) fn chosen(a: &Leaf<'a>, b: &Leaf<'a>, take: &[u64], rows: usize) -> Leaf<'a> { + let (a, b) = (a.column(), b.column()); + let array = Self::selected(&a, &b, take, rows).unwrap_or_else(|| { + let mut builder = ColumnBuilder::with_capacity(rows); + for row in 0..rows { + match Bits::get(take, row) { + true => builder.push_cell(&b, row), + false => builder.push_cell(&a, row), + } + } + builder.finish() + }); + Leaf::typed(array) + } +} diff --git a/core/engine/src/compiled/graph/plan/run/lane.rs b/core/engine/src/compiled/graph/plan/run/lane.rs new file mode 100644 index 00000000..3cee31e3 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/lane.rs @@ -0,0 +1,237 @@ +use super::store::Entries; +use super::Run; +use crate::compiled::bound::{Bound, Outs}; +use crate::compiled::core::exec::Dedup; +use crate::compiled::graph::plan::{LaneOp, Program, SegPlan}; +use crate::compiled::graph::{Body, CompiledGraph, Condition, Kind}; +use crate::compiled::leaf::{Array, Leaf, Records}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Column, Columns, LaneProgram}; + +impl<'a> Run<'_, 'a> { + fn program<'g>( + graph: &'g CompiledGraph, + op: &'g LaneOp, + ) -> Option<(&'g LaneProgram, Entries<'g>)> { + if let Some(own) = &op.own { + return Some((&own.program, Some(&own.entries))); + } + let step = graph.step_at(op.node)?; + match (&step.kind, op.program) { + ( + Kind::Node { + body: + Body::Expression { + program, entries, .. + }, + .. + }, + Program::Expression, + ) => Some((program, Some(entries))), + (Kind::Node { transform, .. }, Program::Field) => transform + .input_field + .as_ref() + .map(|(program, _)| (program, None)), + (Kind::Switch { conditions, .. }, Program::Condition(index)) => { + match conditions.get(index) { + Some((_, Condition::Program(program))) => Some((program, None)), + _ => None, + } + } + _ => None, + } + } + + pub(super) fn lane( + &mut self, + seg: &SegPlan, + op: &LaneOp, + positions: Option<&Rc<[usize]>>, + report: bool, + ) { + let Some((program, entries)) = Self::program(self.graph, op) else { + return; + }; + let rows = self.store.rows; + let leaves: Vec> = op + .reads + .iter() + .map(|(_, r)| self.store.value(seg, *r)) + .collect(); + let held: Vec>>> = match Records::LANE_VIEW { + true => leaves.iter().map(Leaf::records).collect(), + false => Vec::new(), + }; + let parts: Vec>> = match held.iter().any(Option::is_some) { + true => held.iter().map(|r| r.as_ref().map(|r| r.parts())).collect(), + false => Vec::new(), + }; + let items: Vec> = held + .iter() + .zip(&parts) + .map(|(r, p)| Some(r.as_ref()?.item(p.as_ref()?))) + .collect(); + let mut columns = Columns::new(rows); + columns.columns.reserve_exact(op.reads.len()); + for (at, ((key, _), leaf)) in op.reads.iter().zip(&leaves).enumerate() { + let view = match ( + held.get(at).and_then(Option::as_ref), + items.get(at).and_then(Option::as_ref), + ) { + (Some(record), Some(item)) => record.list(item), + _ => leaf.column(), + }; + columns = columns.column(key.as_ref(), view); + } + let program = match (op.specialized.get(), self.settled) { + (Some(special), _) => special.as_ref().unwrap_or(program), + (None, true) => op + .specialized + .get_or_init(|| program.specialize_columns(&columns).ok()) + .as_ref() + .unwrap_or(program), + (None, false) => program, + }; + let scopes = Bound::blank(rows); + let mut outs = Outs::take(); + let mut failures = std::mem::take(&mut self.failures); + failures.clear(); + let local = positions.map_or(rows, |p| p.len()); + let single = [positions.and_then(|p| p.first().copied()).unwrap_or(0)]; + let uniform = op.uniform && local > 1; + let keyed = match op.stable && !uniform { + true => { + let hints: Vec, usize)>> = op + .reads + .iter() + .map(|(_, r)| { + self.store + .hints + .iter() + .find(|(slot, _, _)| *slot == r.slot) + .map(|(_, codes, size)| (codes.clone(), *size)) + }) + .collect(); + Dedup::distinct(&leaves, &hints, positions, rows) + } + false => None, + }; + let subset = match (uniform, &keyed) { + (true, _) => Some(&single[..]), + (false, Some((reps, _))) => Some(&reps[..]), + (false, None) => positions.map(|p| p.as_ref()), + }; + self.runner.evaluate_sites( + program, + scopes.slice(), + &columns, + &op.bound, + subset, + &mut outs, + |row, stage, _| failures.push((row, stage)), + ); + if uniform { + let stages: Vec = failures.iter().map(|(_, stage)| *stage).collect(); + failures = stages + .into_iter() + .flat_map(|stage| (0..local).map(move |at| (at, stage))) + .collect(); + } + if let (Some((reps, ids)), false) = (&keyed, failures.is_empty()) { + let mut stages: Vec> = vec![Vec::new(); reps.len()]; + failures + .iter() + .for_each(|&(rep, stage)| stages[rep].push(stage)); + failures = ids + .iter() + .enumerate() + .flat_map(|(at, id)| stages[*id as usize].iter().map(move |&stage| (at, stage))) + .collect(); + } + for (slot, out) in op.outs.iter().zip(outs.iter_mut()) { + let array = Array::from_output(out); + let leaf = match (uniform, &keyed) { + (true, _) => match Self::templated(&array, local) { + Some(leaf) => leaf, + None => array + .broadcast(local) + .map_or_else(|| Leaf::nulls(local), Leaf::typed), + }, + (false, Some((_, ids))) => Leaf::typed(array.expand(ids)), + (false, None) => Leaf::typed(array), + }; + let leaf = self.store.place(leaf, positions); + self.store.slots[*slot as usize] = Some(leaf); + } + let graph = self.graph; + match (report, op.program, graph.step_at(op.node), entries) { + (true, Program::Field, Some(step), _) => { + if let Some((source, _)) = Self::program(graph, op) { + self.fielded(step, source, &columns, positions, &failures); + } + } + (true, _, Some(step), Some(entries)) => { + self.report(entries, step, positions, &failures) + } + _ => {} + } + self.failures = failures; + } + + fn fielded( + &mut self, + step: &crate::compiled::graph::Step, + source: &LaneProgram, + columns: &Columns, + positions: Option<&Rc<[usize]>>, + failures: &[(usize, usize)], + ) { + for &(at, _) in failures { + let row = positions.map_or(at, |p| p.get(at).copied().unwrap_or(at)); + if !self.store.errors.ok(row) { + continue; + } + let scope = zen_expression::Scope::new(columns.row(row)); + let message = match self + .runner + .evaluate(source, std::slice::from_ref(&scope)) + .into_iter() + .next() + { + Some(Err(e)) => crate::compiled::exact::Failure::input(e), + _ => crate::compiled::exact::Failure::EXPRESSION.to_string(), + }; + self.store.errors.fail(row, &step.node, Rc::from(message)); + } + } + + fn report( + &mut self, + entries: &[(Arc, Arc)], + step: &crate::compiled::graph::Step, + positions: Option<&Rc<[usize]>>, + failures: &[(usize, usize)], + ) { + let mut messages: Vec>> = vec![None; entries.len().max(1)]; + for &(at, stage) in failures { + let row = positions.map_or(at, |p| p.get(at).copied().unwrap_or(at)); + if !self.store.errors.ok(row) { + continue; + } + let message = messages.get_mut(stage).map(|m| { + m.get_or_insert_with(|| { + let source = entries + .get(stage) + .map(|(_, v)| v.as_ref()) + .unwrap_or_default(); + Rc::from(crate::compiled::exact::Failure::expression(source)) + }) + .clone() + }); + self.store + .errors + .fail(row, &step.node, message.unwrap_or_else(|| Rc::from(""))); + } + } +} diff --git a/core/engine/src/compiled/graph/plan/run/loops.rs b/core/engine/src/compiled/graph/plan/run/loops.rs new file mode 100644 index 00000000..29ca8af0 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/loops.rs @@ -0,0 +1,391 @@ +use super::store::Shredded; +use super::Run; +use crate::compiled::core::list::Kin; +use crate::compiled::graph::data::Shape as DataShape; +use crate::compiled::graph::data::{Data, Layer}; +use crate::compiled::graph::plan::view::{Ref, SlotId}; +use crate::compiled::graph::plan::SegPlan; +use crate::compiled::graph::{Body, CompiledGraph, Kind}; +use crate::compiled::leaf::Mask; +use crate::compiled::leaf::{Bits, ColumnBuilder, Field, Items, Leaf, Records}; +use crate::compiled::shred::Shred; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::Values; +use zen_expression::Variable; +use zen_types::path::DotPath; +use zen_types::symbol::Symbol; + +impl<'a> Run<'_, 'a> { + pub(super) fn looped( + &mut self, + seg: &SegPlan, + node: petgraph::prelude::NodeIndex, + list: Ref, + out: SlotId, + positions: Option<&Rc<[usize]>>, + ) { + let graph = self.graph; + let Some((step, Kind::Node { body, transform })) = + graph.step_at(node).map(|step| (step, &step.kind)) + else { + return; + }; + let leaf = self.store.value(seg, list); + let rows = self.store.rows; + let mut at: Vec = match positions { + Some(positions) => positions.to_vec(), + None => (0..rows).collect(), + }; + let mut native: Option<(Leaf<'a>, Vec)> = None; + match leaf.items() { + Some(items) => { + if self.native_loop(step, body, transform.pass_through, &items, out, &at) { + return; + } + } + None => { + if let Some((records, odd)) = self.shredded(&leaf, rows) { + let (rest, lifted): (Vec, Vec) = + at.iter().partition(|&&row| Bits::get(&odd, row)); + if self.native_loop( + step, + body, + transform.pass_through, + &Items::Records(records), + out, + &lifted, + ) { + if rest.is_empty() { + return; + } + if let Some(leaf) = self.store.slots[out as usize].take() { + native = Some((leaf, lifted)); + at = rest; + } + } + } + } + } + let mut items: Vec = Vec::new(); + let mut spans: Vec<(usize, usize, usize)> = Vec::with_capacity(at.len()); + for &row in &at { + match leaf.get(row).as_array() { + Some(array) => { + let start = items.len(); + items.extend(array.borrow().iter().cloned()); + spans.push((row, start, items.len())); + } + None => self + .store + .errors + .fail(row, &step.node, Rc::from("Expected an array")), + } + } + let produced = CompiledGraph::items(&mut self.runner, step, body, &items, &[]); + let mut values = vec![Variable::Null; rows]; + for (row, start, end) in spans { + let mut collected = Vec::with_capacity(end - start); + let mut failure = None; + for (item, output) in items[start..end].iter().zip(&produced[start..end]) { + match output { + Ok(out) => collected.push(crate::compiled::exact::Attributes::item( + transform.pass_through, + item, + out.clone(), + )), + Err(e) => { + failure = Some(e.clone()); + break; + } + } + } + match failure { + Some(e) => self.store.errors.fail(row, &step.node, Rc::from(e)), + None => values[row] = Variable::from_array(collected), + } + } + if let Some((leaf, lifted)) = native { + lifted + .into_iter() + .for_each(|row| values[row] = leaf.get(row)); + } + self.store.slots[out as usize] = Some(Leaf::Any(values.into())); + } + + fn shredded(&mut self, leaf: &Leaf<'a>, rows: usize) -> Shredded<'a> { + if let Some((_, cached)) = self.shreds.iter().find(|(seen, _)| seen.same(leaf)) { + return cached.clone(); + } + let shredded = Self::shred(leaf, rows); + self.shreds.push((leaf.clone(), shredded.clone())); + shredded + } + + fn shred(leaf: &Leaf<'a>, rows: usize) -> Shredded<'a> { + let column = leaf.column(); + let shred = Shred::of(&column, rows)?; + let mut odd = vec![0u64; rows.div_ceil(64)]; + shred + .hosted + .iter() + .filter(|&&row| leaf.get(row).as_array().is_some()) + .for_each(|&row| Bits::set(&mut odd, row, true)); + let valid = match shred.frame.validity { + Some(bits) => bits.to_vec(), + None => Bits::ones(rows), + }; + let count = shred.frame.children; + let fields = shred + .fields + .into_iter() + .map(|(name, array)| { + let present: Rc<[u64]> = match array.validity_bits() { + Some(bits) => Bits::window(bits, 0, count).into(), + None => Bits::ones(count).into(), + }; + (Symbol::from(name.as_ref()), Leaf::typed(array), present) + }) + .collect(); + Some(( + Rc::new(Records::new( + rows, + shred.frame.offsets.to_vec(), + valid, + fields, + None, + )), + odd.into(), + )) + } + + fn native_loop( + &mut self, + step: &crate::compiled::graph::Step, + body: &Body, + pass_through: bool, + source: &Items<'a>, + out: SlotId, + at: &[usize], + ) -> bool { + let Some(keys) = CompiledGraph::item_keys(step, body) else { + return false; + }; + let Some(fields) = source.fields() else { + return false; + }; + let scalar = |leaf: &Leaf| { + !matches!( + leaf.column().values, + Values::Any(_) | Values::List { .. } | Values::Struct { .. } + ) + }; + let flat = fields.iter().all(|(name, leaf, _)| { + !name.is_empty() + && !name.contains('.') + && (scalar(leaf) || !keys.iter().any(|k| DotPath::under(k, name))) + }); + if !flat { + return false; + } + let rows = self.store.rows; + let mut spans: Vec<(usize, usize, usize)> = Vec::with_capacity(at.len()); + let mut missing: Vec = Vec::new(); + let (picked, owner) = Kin::gather( + at, + 0, + |row| source.range(row), + |row, span| match span { + Some((start, end)) => spans.push((row, start, end)), + None => missing.push(row), + }, + ); + let count = picked.len(); + let identity = count == source.count() && picked.iter().enumerate().all(|(i, p)| i == *p); + let picks: Rc<[usize]> = picked.into(); + let local = |leaf: &Leaf<'a>, present: &Rc<[u64]>| -> (Leaf<'a>, Rc<[u64]>) { + match identity { + true => (leaf.clone(), present.clone()), + false => (leaf.pick(&picks), Bits::gather(present, &picks).into()), + } + }; + let fields: Vec> = fields + .iter() + .map(|(name, leaf, present)| { + let (leaf, present) = local(leaf, present); + (name.clone(), leaf, present) + }) + .collect(); + let mut leaves = Vec::with_capacity(keys.len()); + let mut present = Vec::with_capacity(keys.len()); + for key in &keys { + match fields + .iter() + .find(|(name, _, _)| name.as_str() == key.as_ref()) + { + Some((_, leaf, bits)) => { + leaves.push(leaf.clone()); + present.push(Mask::Bits(bits.clone())); + } + None => { + leaves.push(Leaf::nulls(count)); + present.push(Mask::Bits(vec![0u64; count.div_ceil(64)].into())); + } + } + } + let items: Rc<[usize]> = (0..count).collect(); + let data = Data::record(&items, Layer::new(keys.into(), leaves, Some(present)), None); + let (output, failures) = CompiledGraph::item_run(&mut self.runner, step, body, &data); + let paths: Vec<(Arc, Leaf<'a>)> = output.leaves().to_vec(); + let shaped = matches!(output.shape, DataShape::Patched { base: None, .. }) + && paths + .iter() + .all(|(path, _)| !path.is_empty() && !path.split('.').any(str::is_empty)) + && !paths + .iter() + .any(|(a, _)| paths.iter().any(|(b, _)| DotPath::under(b, a))); + let nulled: Option> = match (&output.shape, pass_through) { + ( + DataShape::Patched { + nulls: Some(nulls), .. + }, + false, + ) => Some(nulls.clone()), + _ => None, + }; + let mut failed = vec![false; rows]; + let mut failures = failures; + failures.sort_by_key(|(item, _)| *item); + for (item, message) in failures { + let Some(&row) = owner.get(item) else { + continue; + }; + if !failed[row] { + failed[row] = true; + self.store.errors.fail(row, &step.node, Rc::from(message)); + } + } + for row in missing { + self.store + .errors + .fail(row, &step.node, Rc::from("Expected an array")); + } + let merged: Option>> = match (shaped, pass_through) { + (false, _) => None, + (true, false) => Some( + paths + .iter() + .map(|(path, _)| { + let (leaf, bits) = output.present(path); + (Symbol::from(path.as_ref()), leaf, bits.into()) + }) + .collect(), + ), + (true, true) => Self::passed(&fields, &output, &paths, count, &scalar), + }; + let mut offsets = Vec::with_capacity(rows + 1); + let mut valid = vec![0u64; rows.div_ceil(64)]; + let mut next = spans.iter().peekable(); + let mut total = 0i32; + offsets.push(0); + for (row, &fault) in failed.iter().enumerate() { + if let Some(&&(span_row, start, end)) = next.peek() { + if span_row == row { + total += (end - start) as i32; + if !fault { + Bits::set(&mut valid, row, true); + } + next.next(); + } + } + offsets.push(total); + } + let leaf = match merged { + Some(fields) => { + Leaf::Records(Rc::new(Records::new(rows, offsets, valid, fields, nulled))) + } + None => { + let values = output.materialized(); + let mut arrays = vec![Variable::Null; rows]; + for &(row, start, end) in &spans { + if failed[row] { + continue; + } + let collected: Vec = (start..end) + .map(|item| { + let value = values.get(item).cloned().unwrap_or(Variable::Null); + match pass_through { + true => Records::object(&fields, item).merge_clone(&value), + false => value, + } + }) + .collect(); + arrays[row] = Variable::from_array(collected); + } + Leaf::Any(arrays.into()) + } + }; + self.store.slots[out as usize] = Some(leaf); + true + } + + fn passed( + fields: &[Field<'a>], + output: &Data<'a>, + paths: &[(Arc, Leaf<'a>)], + count: usize, + scalar: &dyn Fn(&Leaf) -> bool, + ) -> Option>> { + let mut merged: Vec> = fields.to_vec(); + for (path, _) in paths { + let (leaf, bits) = output.present(path); + if let Some((top, _)) = path.split_once('.') { + if fields.iter().any(|(name, _, _)| name.as_str() == top) { + return None; + } + merged.push((Symbol::from(path.as_ref()), leaf, bits.into())); + continue; + } + let valued: Vec = leaf + .valued(count) + .iter() + .zip(&bits) + .map(|(v, b)| v & b) + .collect(); + match merged + .iter() + .position(|(name, _, _)| name.as_str() == path.as_ref()) + { + None => merged.push((Symbol::from(path.as_ref()), leaf, valued.into())), + Some(at) => { + let (name, item, present) = merged[at].clone(); + if !scalar(&item) { + return None; + } + let (patch, base) = (leaf.column(), item.column()); + let mut builder = ColumnBuilder::with_capacity(count); + let mut kept = vec![0u64; count.div_ceil(64)]; + for i in 0..count { + match ( + Bits::get(&valued, i), + Bits::get(&bits, i), + Bits::get(&present, i), + ) { + (true, _, _) => { + builder.push_cell(&patch, i); + Bits::set(&mut kept, i, true); + } + (false, false, true) => { + builder.push_cell(&base, i); + Bits::set(&mut kept, i, true); + } + _ => builder.push_null(), + } + } + merged[at] = (name, Leaf::typed(builder.finish()), kept.into()); + } + } + } + Some(merged) + } +} diff --git a/core/engine/src/compiled/graph/plan/run/mod.rs b/core/engine/src/compiled/graph/plan/run/mod.rs new file mode 100644 index 00000000..7a41777e --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/mod.rs @@ -0,0 +1,305 @@ +use crate::compiled::census::Census; +use crate::compiled::graph::data::Data; +use crate::compiled::graph::plan::typed::TypedOp; +use crate::compiled::graph::plan::{JoinMode, Layout, Op, Program, SegEnd, SegPlan}; +use crate::compiled::graph::Host; +use crate::compiled::graph::{CompiledGraph, Completed}; +use crate::compiled::leaf::{Bits, Leaf}; +use crate::decision_graph::walker::GraphWalker; +use std::rc::Rc; +use std::sync::Arc; +use store::{Branch, Group, Mark, Pending, Shredded, Store}; +use zen_expression::lane::LaneRunner; +use zen_expression::Variable; + +mod assemble; +pub(crate) use assemble::PlanOutcome; +mod child; +mod fanout; +mod gather; +mod lane; +mod loops; +mod rows; +mod store; +mod table; +mod typed; + +type Parents<'r> = &'r dyn Fn(usize) -> Option; + +struct Run<'r, 'a> { + graph: &'r CompiledGraph, + layout: &'r Layout, + runner: LaneRunner, + host: Host<'r>, + store: Store<'a>, + settled: bool, + failures: Vec<(usize, usize)>, + shreds: Vec<(Leaf<'a>, Shredded<'a>)>, + completed: Completed, + iteration: u8, + parents: Option>, +} + +impl<'a> Run<'_, 'a> { + fn alive(&self, positions: Option>, seen: &mut usize) -> Option> { + self.store.errors.alive(positions, seen) + } + + async fn walk(&mut self, root: Arc) { + let mut stack: Vec = vec![Pending { + branch: Branch { + seg: root, + positions: None, + }, + parent: None, + }]; + let mut children = Vec::new(); + while let Some(Pending { branch, parent }) = stack.pop() { + if let Some(parent) = parent { + self.store.rewind(parent); + } + let Branch { seg, positions } = branch; + self.segment(&seg, positions, &mut children).await; + let parent = Some(Mark { + slots: seg.slots.len(), + masks: seg.masks.exprs.len(), + }); + stack.extend( + children + .drain(..) + .rev() + .map(|branch| Pending { branch, parent }), + ); + } + } + + async fn segment( + &mut self, + seg: &SegPlan, + positions: Option>, + children: &mut Vec, + ) { + self.store.enter(seg); + let mut seen = 0usize; + let mut live = self.alive(positions, &mut seen); + let mut positions = live.as_ref(); + for op in &seg.ops { + if self.store.errors.generation() != seen { + live = self.alive(live, &mut seen); + positions = live.as_ref(); + } + match op { + Op::Lane(lane) => { + if matches!(lane.program, Program::Expression) { + self.store.counts.1 += 1; + } + match Census::on() { + true => self.timed(seg, op, positions), + false => self.lane(seg, lane, positions, true), + } + } + Op::Table(table) => { + self.store.counts.1 += 1; + match Census::on() { + true => self.timed(seg, op, positions), + false => self.table(seg, table, positions), + } + } + Op::Typed { op, units } => match Census::on() { + true => self.grouped(seg, op, units, positions), + false => self.typed(seg, op, units, positions), + }, + Op::Deferred { op, units } => self.deferred(seg, op, units, positions), + Op::Rows(op) => { + Census::begin(); + self.rows(seg, op, positions).await; + if Census::on() { + self.counted(op, positions); + } + } + Op::Loop { node, list, out } => self.looped(seg, *node, *list, *out, positions), + Op::Child(op) => { + Census::begin(); + self.child(seg, op, positions).await; + if Census::on() { + self.measured(positions); + } + } + Op::Join { inputs, out, mode } => { + let leaves: Vec> = + inputs.iter().map(|r| self.store.leaf(r.slot)).collect(); + let mut values = vec![Variable::Null; self.store.rows]; + let mut parts = Vec::with_capacity(leaves.len()); + let mut arrays = Vec::new(); + let at: Box> = match positions { + Some(positions) => Box::new(positions.iter().copied()), + None => Box::new(0..self.store.rows), + }; + for row in at { + parts.clear(); + parts.extend(leaves.iter().map(|leaf| leaf.get(row))); + let value = match mode { + JoinMode::Ending => GraphWalker::merge_ending(parts.iter()), + JoinMode::Strict | JoinMode::Lenient => { + GraphWalker::merge_values(parts.iter()) + } + }; + if *mode == JoinMode::Strict && matches!(value, Variable::Array(_)) { + arrays.push(row); + } + values[row] = value; + } + for row in arrays { + self.store.errors.defer(row); + } + self.store.slots[*out as usize] = Some(Leaf::Any(values.into())); + } + Op::Select { a, b, take, out } => { + let (a, b) = (self.store.value(seg, *a), self.store.value(seg, *b)); + let take = self.store.mask(seg, *take); + if Bits::none(&take) + || Rc::ptr_eq(&take, &self.store.ones) + || *take == *self.store.ones + { + let chosen = match Bits::none(&take) { + true => a, + false => b, + }; + self.store.slots[*out as usize] = Some(chosen); + continue; + } + self.store.slots[*out as usize] = + Some(Self::chosen(&a, &b, &take, self.store.rows)); + } + Op::Materialize { node, out } => { + let shape = self.store.shape(seg, node); + let values = Store::objects(&shape, self.store.rows); + self.store.slots[*out as usize] = Some(Leaf::Any(values.into())); + } + Op::MergeRows { + a, + b, + parts, + present, + out, + } => { + let (sa, sb) = (self.store.shape(seg, a), self.store.shape(seg, b)); + let [rr, rb, ra] = parts.map(|m| self.store.mask(seg, m)); + let rows = self.store.rows; + let mut bits = vec![0u64; rows.div_ceil(64)]; + let values: Vec = (0..rows) + .map(|row| { + let value = Store::merged( + &sa, + &sb, + Bits::get(&rr, row), + Bits::get(&rb, row), + Bits::get(&ra, row), + row, + ); + if value.is_some() { + Bits::set(&mut bits, row, true); + } + value.unwrap_or(Variable::Null) + }) + .collect(); + self.store.slots[*out as usize] = Some(Leaf::Any(values.into())); + self.store.produce(*present, bits.into()); + } + Op::Null { out } => { + self.store.slots[*out as usize] = Some(Leaf::nulls(self.store.rows)); + } + Op::Coalesce { from, value, out } => { + let leaf = self.store.value(seg, *from); + let array = Self::coalesced(&leaf.column(), value, self.store.rows); + self.store.slots[*out as usize] = Some(Leaf::typed(array)); + } + Op::Extract { from, path, out } => { + let leaf = self.store.value(seg, *from); + let path = path + .iter() + .map(|s| s.as_ref()) + .collect::>() + .join("."); + let values: Vec = (0..self.store.rows) + .map(|row| Data::lookup(&leaf.get(row), &path).unwrap_or(Variable::Null)) + .collect(); + self.store.slots[*out as usize] = Some(Leaf::Any(values.into())); + } + } + } + if self.store.errors.generation() != seen { + live = self.alive(live, &mut seen); + positions = live.as_ref(); + } + match &seg.end { + SegEnd::Finish(_) if self.iteration > 0 => {} + SegEnd::Finish(refs) if matches!(refs.as_slice(), [(path, _)] if path.is_empty()) => { + let leaves = self.flattened(refs[0].1, positions); + self.store.groups.push(Group { + positions: positions.cloned(), + leaves, + }); + } + SegEnd::Finish(refs) => { + let leaves = refs + .iter() + .map(|(path, r)| { + let base = self.store.leaf(r.slot); + let presence = + (!Store::implied(seg, *r)).then(|| self.store.mask(seg, r.present)); + (path.clone(), base, presence) + }) + .collect(); + self.store.groups.push(Group { + positions: positions.cloned(), + leaves, + }); + } + SegEnd::Switch { + first, conditions, .. + } => self.fan_out(seg, positions, *first, conditions, children), + } + } + + #[cold] + #[inline(never)] + fn timed(&mut self, seg: &SegPlan, op: &Op, positions: Option<&Rc<[usize]>>) { + let start = std::time::Instant::now(); + self.unit(seg, op, positions); + let rows = positions.map_or(self.store.rows, |p| p.len()); + if let Some(key) = op.census(self.graph) { + let what = match op { + Op::Table(_) => "table", + _ => "lane", + }; + Census::fallback(key, what, rows, start.elapsed().as_nanos()); + } + } + + #[cold] + #[inline(never)] + fn grouped( + &mut self, + seg: &SegPlan, + op: &TypedOp, + units: &[Op], + positions: Option<&Rc<[usize]>>, + ) { + let start = std::time::Instant::now(); + self.typed(seg, op, units, positions); + Census::record( + "typed | group".into(), + positions.map_or(self.store.rows, |p| p.len()), + start.elapsed().as_nanos(), + ); + } + + fn unit(&mut self, seg: &SegPlan, op: &Op, positions: Option<&Rc<[usize]>>) { + match op { + Op::Lane(lane) => self.lane(seg, lane, positions, true), + Op::Table(table) => self.table(seg, table, positions), + _ => {} + } + } +} diff --git a/core/engine/src/compiled/graph/plan/run/rows.rs b/core/engine/src/compiled/graph/plan/run/rows.rs new file mode 100644 index 00000000..6f73b673 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/rows.rs @@ -0,0 +1,408 @@ +use super::store::{Flat, Layered, Store}; +use super::Run; +use crate::compiled::census::Census; +use crate::compiled::graph::data::{Data, Layer}; +use crate::compiled::graph::plan::view::{Node, Ref, M}; +use crate::compiled::graph::plan::{RowsCond, RowsOp, SegPlan}; +use crate::compiled::graph::{CompiledGraph, Condition, Kind}; +use crate::compiled::leaf::Mask; +use crate::compiled::leaf::{Bits, Leaf}; +use crate::compiled::shred::Shredder; +use crate::decision_graph::cleaner::VariableCleaner; +use crate::model::DecisionNodeKind; +use crate::nodes::NodeError; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Instant; +use zen_expression::Variable; +use zen_types::symbol::Symbol; +use zen_types::variable::VariableMap; + +impl<'a> Run<'_, 'a> { + pub(super) fn flattened(&mut self, r: Ref, positions: Option<&Rc<[usize]>>) -> Vec> { + let leaf = self.store.leaf(r.slot); + let rows = self.store.rows; + let mut shredder = Shredder::new(rows); + let at: Box> = match positions { + Some(positions) => Box::new(positions.iter().copied()), + None => Box::new(0..rows), + }; + for row in at { + if !self.store.errors.ok(row) { + continue; + } + let value = leaf.get(row); + VariableCleaner::new().clean(&value); + shredder.visit(&value, 0, row); + } + shredder.finish() + } + + pub(super) fn materialize(&mut self, seg: &SegPlan, view: &Node) -> Leaf<'a> { + if let Some(leaf) = view + .leaf + .filter(|leaf| leaf.present == M::All && view.fields.is_empty()) + { + return self.store.leaf(leaf.slot); + } + let shape = self.store.shape(seg, view); + Leaf::Any(Store::objects(&shape, self.store.rows).into()) + } + + pub(super) fn layer( + &mut self, + seg: &SegPlan, + node: &Node, + prefix: &str, + out: &mut Vec>, + ) -> Option> { + match (node.leaf, node.fields.is_empty()) { + (Some(_), false) => None, + (Some(r), true) => { + let bits = self.store.mask(seg, r.present); + out.push((Arc::from(prefix), self.store.leaf(r.slot), bits.clone())); + Some(bits.to_vec()) + } + (None, empty) => { + let mut any = vec![0u64; self.store.words]; + for (key, child) in &node.fields { + let path = match prefix.is_empty() { + true => key.to_string(), + false => format!("{prefix}.{key}"), + }; + let bits = self.layer(seg, child, &path, out)?; + any.iter_mut().zip(&bits).for_each(|(a, b)| *a |= b); + } + let obj = self.store.mask(seg, node.obj.unwrap_or(M::None)); + let agrees = match (empty, prefix.is_empty()) { + (_, true) => obj + .iter() + .zip(self.store.ones.iter()) + .all(|(o, one)| o == one), + (true, false) => Bits::none(&obj), + (false, false) => obj.as_ref() == any.as_slice(), + }; + agrees.then_some(any) + } + } + } + + fn columnar( + &mut self, + seg: &SegPlan, + view: &Node, + positions: Option<&Rc<[usize]>>, + ) -> Option> { + let mut leaves = Vec::new(); + self.layer(seg, view, "", &mut leaves)?; + if leaves.iter().any(|(path, _, _)| path.is_empty()) { + return None; + } + let rows = positions.map_or(self.store.rows, |p| p.len()); + let mut paths = Vec::with_capacity(leaves.len()); + let mut columns = Vec::with_capacity(leaves.len()); + let mut present = Vec::with_capacity(leaves.len()); + for (path, leaf, bits) in leaves { + paths.push(path); + let mask = Mask::Bits(bits); + match positions { + Some(positions) => { + columns.push(leaf.pick(positions)); + present.push(mask.pick(positions)); + } + None => { + columns.push(leaf); + present.push(mask); + } + } + } + let local: Rc<[usize]> = (0..rows).collect(); + Some(Data::record( + &local, + Layer::new(paths.into(), columns, Some(present)), + None, + )) + } + + fn settle(&mut self, results: Vec>, at: &[usize]) -> Vec { + results + .into_iter() + .zip(at) + .map(|(result, &row)| match result { + Ok(value) => value, + Err(error) => { + self.store.errors.fault(row, error); + Variable::Null + } + }) + .collect() + } + + pub(super) fn inputs( + &mut self, + seg: &SegPlan, + input: Option<&Node>, + nodes: &Option, Ref)>>, + positions: Option<&Rc<[usize]>>, + ) -> (Vec, Vec, Vec>) { + let at: Vec = match positions { + Some(positions) => positions.to_vec(), + None => (0..self.store.rows).collect(), + }; + let inputs = match input { + Some(view) => { + let leaf = self.materialize(seg, view); + at.iter().map(|&row| leaf.get(row)).collect() + } + None => Vec::new(), + }; + let objects = match nodes { + None => Vec::new(), + Some(nodes) => { + let leaves: Vec<(Symbol, Leaf<'a>)> = nodes + .iter() + .map(|(name, r)| (Symbol::from(name.as_ref()), self.store.leaf(r.slot))) + .collect(); + let entry = self.parents.and_then(|_| self.graph.input_name()); + at.iter() + .map(|&row| { + let mut map = VariableMap::with_capacity(leaves.len()); + for ((original, _), (name, leaf)) in nodes.iter().zip(&leaves) { + let value = leaf.get(row); + let value = match (&entry, self.parents) { + (Some(entry), Some(parents)) if original == entry => { + match parents(row) { + Some(parent) => { + let view = value.depth_clone(1); + view.dot_insert(Variable::nodes_key().as_ref(), parent); + view + } + None => value, + } + } + _ => value, + }; + map.insert(name.clone(), value); + } + Some(Variable::from_object(map)) + }) + .collect() + } + }; + (at, inputs, objects) + } + + pub(super) async fn rows( + &mut self, + seg: &SegPlan, + op: &RowsOp, + positions: Option<&Rc<[usize]>>, + ) { + let graph = self.graph; + let Some(step) = graph.step_at(op.node) else { + return; + }; + let data = match step.kind { + Kind::Node { .. } | Kind::Output => self.columnar(seg, &op.view, positions), + _ => None, + }; + if let (Kind::Output, Some(data)) = (&step.kind, &data) { + let nodes = self.inputs(seg, None, &op.nodes, positions).2; + Census::mark("validate"); + let failures = graph + .validate_input(step, data, &nodes, self.host.content, self.host.extensions) + .await; + for (i, message) in failures { + let row = positions.map_or(i, |p| p[i]); + self.store.errors.fail(row, &step.node, Rc::from(message)); + } + return; + } + if let (Kind::Host(_), DecisionNodeKind::DecisionNode { content }) = + (&step.kind, &step.node.kind) + { + let count = positions.map_or(self.store.rows, |p| p.len()); + if CompiledGraph::batchable(&content.transform_attributes, count) { + Census::mark("batched"); + let values = match CompiledGraph::resolve(content, self.host.extensions).await { + Err(failure) => { + let error = failure.shared(step, &content.key); + match positions { + Some(positions) => positions + .iter() + .for_each(|&row| self.store.errors.share(row, &error)), + None => (0..count).for_each(|row| self.store.errors.share(row, &error)), + } + vec![Variable::Null; count] + } + Ok(graph) => { + let (at, inputs, nodes) = + self.inputs(seg, Some(&op.view), &op.nodes, positions); + let results = CompiledGraph::batch( + step, + content, + &graph, + &inputs, + &nodes, + self.host.extensions, + self.host.max_depth, + self.iteration, + ) + .await; + { + self.completed + .record(op.node, self.store.rows, &at, &results); + self.settle(results, &at) + } + } + }; + let leaf = self.store.place(Leaf::Any(values.into()), positions); + self.store.slots[op.out as usize] = Some(leaf); + return; + } + } + let (at, inputs, nodes) = self.inputs( + seg, + data.is_none().then_some(&op.view), + &op.nodes, + positions, + ); + let values: Vec = match &step.kind { + Kind::Host(_) => { + Census::mark("hosted"); + let results = match &step.node.kind { + DecisionNodeKind::CustomNode { content } => { + CompiledGraph::custom(step, content, inputs, nodes, self.host.extensions) + .await + } + _ => { + CompiledGraph::hosted( + step, + &inputs, + &nodes, + self.host.extensions, + self.host.max_depth, + self.iteration, + self.store.rows > 1, + ) + .await + } + }; + { + self.completed + .record(op.node, self.store.rows, &at, &results); + self.settle(results, &at) + } + } + Kind::Input | Kind::Output => { + Census::mark("bounded"); + let (values, failures) = graph + .bounded( + step, + &inputs, + &nodes, + self.host.content, + self.host.extensions, + ) + .await; + for (i, message) in failures { + self.store.errors.fail(at[i], &step.node, Rc::from(message)); + } + values + } + _ => { + let data = + data.unwrap_or_else(|| Data::plain((0..inputs.len()).collect(), inputs.into())); + let (output, failures) = graph.rowwise(&mut self.runner, step, data, &nodes); + for (i, message) in failures { + self.store.errors.fail(at[i], &step.node, Rc::from(message)); + } + if !op.keys.is_empty() { + for (path, slot, present) in &op.keys { + let (leaf, bits) = match present { + M::All => (output.column_at(path), None), + _ => { + let (leaf, bits) = output.present(path); + (leaf, Some(bits)) + } + }; + let leaf = self.store.place(leaf, positions); + self.store.slots[*slot as usize] = Some(leaf); + if let Some(bits) = bits { + let bits = self.store.spread(&bits.into(), positions); + self.store.produce(*present, bits); + } + } + return; + } + output.materialized().to_vec() + } + }; + let leaf = self.store.place(Leaf::Any(values.into()), positions); + self.store.slots[op.out as usize] = Some(leaf); + } + + pub(super) fn counted(&self, op: &RowsOp, positions: Option<&Rc<[usize]>>) { + let kind = self.graph.step_at(op.node).map_or("?", |step| step.label()); + let rows = positions.map_or(self.store.rows, |p| p.len()); + Census::record( + format!("{kind} | {} | {}", op.reason, Census::path()), + rows, + Census::elapsed(), + ); + } + + pub(super) fn rows_condition( + &mut self, + seg: &SegPlan, + op: &RowsCond, + positions: Option<&Rc<[usize]>>, + ) -> Vec { + if !Census::on() { + return self.conditioned(seg, op, positions); + } + let start = Instant::now(); + let bits = self.conditioned(seg, op, positions); + let rows = positions.map_or(self.store.rows, |p| p.len()); + Census::record( + format!("switch | {} | rows", op.reason), + rows, + start.elapsed().as_nanos(), + ); + bits + } + + fn conditioned( + &mut self, + seg: &SegPlan, + op: &RowsCond, + positions: Option<&Rc<[usize]>>, + ) -> Vec { + let mut bits = vec![0u64; self.store.rows.div_ceil(64)]; + let Some(Kind::Switch { conditions, .. }) = + self.graph.step_at(op.node).map(|step| &step.kind) + else { + return bits; + }; + let Some((_, Condition::Program(program))) = conditions.get(op.index) else { + return bits; + }; + let view = Node { + leaf: Some(op.input), + obj: None, + fields: Vec::new(), + }; + let (at, inputs, nodes) = self.inputs(seg, Some(&view), &op.nodes, positions); + let scopes: Vec = inputs + .iter() + .enumerate() + .map(|(i, input)| CompiledGraph::scope(input, nodes.get(i).and_then(Option::as_ref))) + .collect(); + for (result, &row) in self.runner.evaluate(program, &scopes).into_iter().zip(&at) { + if matches!(result, Ok(Variable::Bool(true))) { + Bits::set(&mut bits, row, true); + } + } + bits + } +} diff --git a/core/engine/src/compiled/graph/plan/run/store.rs b/core/engine/src/compiled/graph/plan/run/store.rs new file mode 100644 index 00000000..402649c5 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/store.rs @@ -0,0 +1,566 @@ +use crate::compiled::core::exec::{Dedup, Hint}; +use crate::compiled::graph::errors::SharedErrors; +use crate::compiled::graph::plan::view::{Expr, MaskId, Node, Ref, SlotId, M}; +use crate::compiled::graph::plan::{SegPlan, Source}; +use crate::compiled::leaf::{Bits, Dict, Leaf, Records}; +use crate::compiled::shred::{Listing, Normalizer}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Column, Columns, Values}; +use zen_expression::typed::Outputs; +use zen_expression::Variable; +use zen_types::symbol::Symbol; +use zen_types::variable::VariableMap; + +pub(super) type Shredded<'a> = Option<(Rc>, Rc<[u64]>)>; + +pub(super) struct Shaped<'a> { + leaf: Option<(Leaf<'a>, Rc<[u64]>)>, + obj: Option>, + fields: Vec<(Symbol, Shaped<'a>)>, + same: Vec>, +} + +pub(super) type Entries<'g> = Option<&'g [(Arc, Arc)]>; +pub(super) type Spread = (Rc<[u64]>, Rc<[u64]>); +pub(super) struct View<'v> { + pub column: Column<'v>, + pub local: bool, + pub presence: Option<&'v Rc<[u64]>>, + pub dict: Option<&'v Rc>, +} +pub(super) type Origin<'s, 'a> = Option<(&'s Leaf<'a>, &'s Option>)>; + +pub(super) struct Group<'a> { + pub positions: Option>, + pub leaves: Vec>, +} +pub(super) struct Lowered { + pub out: Outputs, + pub keyed: Option>, + pub select: Option>, + pub prefault: Option>, +} +type Shown<'a> = (Leaf<'a>, Option>); +type Cached<'a> = (SlotId, Rc, Option>>); +pub(super) type Prepared<'a> = (Rc>, Option>, Option>); +pub(super) struct Branch { + pub seg: Arc, + pub positions: Option>, +} + +#[derive(Clone, Copy)] +pub(super) struct Mark { + pub slots: usize, + pub masks: usize, +} + +pub(super) struct Pending { + pub branch: Branch, + pub parent: Option, +} +pub(super) type Flat<'a> = (Arc, Leaf<'a>, Option>); +pub(super) type Layered<'a> = (Arc, Leaf<'a>, Rc<[u64]>); + +pub(crate) struct Store<'a> { + pub(super) rows: usize, + pub(super) words: usize, + input: &'a Columns<'a>, + pub(super) slots: Vec>>, + inputs: Vec, std::cell::OnceCell>)>>, + arena: Vec, + offsets: Vec, + masked: Vec<(SlotId, M, Leaf<'a>)>, + shared: Vec<(usize, Rc<[u64]>)>, + pub(super) ones: Rc<[u64]>, + pub(super) errors: SharedErrors, + pub(super) groups: Vec>, + pub(super) hints: Vec<(SlotId, Rc<[i32]>, usize)>, + views: Vec<(SlotId, bool, Option>)>, + codes: Vec<(SlotId, bool, Hint)>, + viewed: Vec<(SlotId, M, bool, Leaf<'a>)>, + listings: std::cell::RefCell>>, + pub(super) counts: (usize, usize), +} + +impl Drop for Store<'_> { + fn drop(&mut self) { + let (arena, offsets) = ( + std::mem::take(&mut self.arena), + std::mem::take(&mut self.offsets), + ); + Store::POOL.with_borrow_mut(|pool| *pool = (arena, offsets)); + } +} + +impl<'a> Store<'a> { + const NONE: u32 = u32::MAX; + const ONES: usize = 0; + + thread_local! { + static POOL: std::cell::RefCell<(Vec, Vec)> = const { std::cell::RefCell::new((Vec::new(), Vec::new())) }; + } + + pub(super) fn new( + seg: &SegPlan, + input: &'a Columns<'a>, + dated: Vec<(usize, Leaf<'a>)>, + ) -> Self { + let rows = input.rows; + let words = rows.div_ceil(64); + let slots = vec![None; seg.slots.len()]; + let inputs = seg + .slots + .iter() + .map(|info| match info.source { + Source::Input(index) => input.columns.get(index).map(|(_, column)| { + let leaf = std::cell::OnceCell::new(); + if let Some((_, dated)) = dated.iter().find(|(at, _)| *at == index) { + let _ = leaf.set(dated.clone()); + } + (*column, leaf) + }), + Source::Op => None, + }) + .collect(); + let (mut arena, mut offsets) = Self::POOL.with_borrow_mut(std::mem::take); + let ones: Rc<[u64]> = Bits::ones(rows).into(); + arena.clear(); + arena.extend_from_slice(&ones); + arena.resize(words * 2, 0); + offsets.clear(); + offsets.resize(seg.masks.exprs.len(), Self::NONE); + Self { + rows, + words, + input, + slots, + inputs, + arena, + offsets, + masked: Vec::new(), + shared: Vec::new(), + ones, + errors: SharedErrors::new(rows), + groups: Vec::new(), + hints: Vec::new(), + views: Vec::new(), + codes: Vec::new(), + viewed: Vec::new(), + listings: std::cell::RefCell::new(Vec::new()), + counts: (0, 0), + } + } + + pub(super) fn enter(&mut self, seg: &SegPlan) { + self.slots.resize(seg.slots.len(), None); + self.offsets.resize(seg.masks.exprs.len(), Self::NONE); + } + + pub(super) fn rewind(&mut self, Mark { slots, masks }: Mark) { + self.slots.truncate(slots); + self.offsets.truncate(masks); + let kept = |slot: SlotId, m: M| { + (slot as usize) < slots + && match m { + M::Id(id) => (id as usize) < masks, + _ => true, + } + }; + self.masked.retain(|(slot, m, _)| kept(*slot, *m)); + self.views.retain(|(slot, ..)| kept(*slot, M::All)); + self.codes.retain(|(slot, ..)| kept(*slot, M::All)); + self.viewed.retain(|(slot, m, ..)| kept(*slot, *m)); + self.listings + .get_mut() + .retain(|(slot, ..)| kept(*slot, M::All)); + } + + pub(super) fn listing(&self, slot: SlotId, chain: &[&str]) -> Option>> { + let key = chain.join("\n"); + if let Some((.., found)) = self + .listings + .borrow() + .iter() + .find(|(s, k, _)| *s == slot && k.as_ref() == key) + { + return found.clone(); + } + let built = match chain.split_last() { + None => Listing::leaf(&self.leaf(slot), self.rows), + Some((field, rest)) => self + .listing(slot, rest) + .and_then(|parent| parent.nested(field)), + } + .map(Rc::new); + self.listings + .borrow_mut() + .push((slot, Rc::from(key), built.clone())); + built + } + + pub(super) fn leaf(&self, slot: SlotId) -> Leaf<'a> { + if let Some(Some(leaf)) = self.slots.get(slot as usize) { + return leaf.clone(); + } + match self.inputs.get(slot as usize) { + Some(Some((column, leaf))) => leaf + .get_or_init(|| Normalizer::input(*column, self.rows)) + .clone(), + _ => Leaf::nulls(self.rows), + } + } + + fn bits(&self, at: usize) -> &[u64] { + &self.arena[at..at + self.words] + } + + pub(super) fn mask(&mut self, seg: &SegPlan, m: M) -> Rc<[u64]> { + match m { + M::All => self.ones.clone(), + m => { + let at = self.region(seg, m); + if let Some((_, shared)) = self.shared.iter().find(|(offset, _)| *offset == at) { + return shared.clone(); + } + let bits: Rc<[u64]> = self.bits(at).into(); + self.shared.push((at, bits.clone())); + bits + } + } + } + + fn region(&mut self, seg: &SegPlan, m: M) -> usize { + match m { + M::All => Self::ONES, + M::None => self.words, + M::Id(id) => self.expr(seg, id), + } + } + + fn push(&mut self, bits: &[u64]) -> usize { + let at = self.arena.len(); + self.arena + .extend_from_slice(&bits[..self.words.min(bits.len())]); + self.arena.resize(at + self.words, 0); + at + } + + fn expr(&mut self, seg: &SegPlan, id: MaskId) -> usize { + if let Some(&at) = self + .offsets + .get(id as usize) + .filter(|at| **at != Self::NONE) + { + return at as usize; + } + let words = self.words; + let at = match seg.masks.exprs[id as usize] { + Expr::Validity(slot) => match seg.slots[slot as usize].source { + Source::Input(index) => { + match self.input.columns.get(index).and_then(|(_, c)| c.validity) { + Some((bits, offset)) => self.push(&Bits::window(bits, offset, self.rows)), + None => Self::ONES, + } + } + Source::Op => { + let bits = self.leaf(slot).validity(self.rows); + self.push(&bits) + } + }, + Expr::Valued(slot) => { + let bits = self.leaf(slot).valued(self.rows); + self.push(&bits) + } + Expr::And(a, b) | Expr::Or(a, b) => { + let (a, b) = (self.region(seg, a), self.region(seg, b)); + let at = self.arena.len(); + self.arena.resize(at + words, 0); + let and = matches!(seg.masks.exprs[id as usize], Expr::And(..)); + for w in 0..words { + self.arena[at + w] = match and { + true => self.arena[a + w] & self.arena[b + w], + false => self.arena[a + w] | self.arena[b + w], + }; + } + at + } + Expr::Not(a) => { + let a = self.region(seg, a); + let at = self.arena.len(); + self.arena.resize(at + words, 0); + for w in 0..words { + self.arena[at + w] = !self.arena[a + w] & self.arena[Self::ONES + w]; + } + at + } + Expr::Produced(_) => self.words, + }; + if let Some(slot) = self.offsets.get_mut(id as usize) { + *slot = at as u32; + } + at + } + + pub(super) fn produce(&mut self, m: M, bits: Rc<[u64]>) { + if let M::Id(id) = m { + let at = self.push(&bits); + if let Some(slot) = self.offsets.get_mut(id as usize) { + *slot = at as u32; + } + } + } + + pub(super) fn implied(seg: &SegPlan, r: Ref) -> bool { + match r.present { + M::All => true, + M::None => false, + M::Id(id) => { + matches!(seg.masks.exprs[id as usize], Expr::Validity(s) | Expr::Valued(s) if s == r.slot) + } + } + } + + pub(super) fn value(&mut self, seg: &SegPlan, r: Ref) -> Leaf<'a> { + let leaf = self.leaf(r.slot); + if Self::implied(seg, r) { + return leaf; + } + if let Some((_, _, cached)) = self + .masked + .iter() + .find(|(s, m, _)| *s == r.slot && *m == r.present) + { + return cached.clone(); + } + let mask = self.mask(seg, r.present); + let masked = Leaf::masked(leaf, &mask); + self.masked.push((r.slot, r.present, masked.clone())); + masked + } + + pub(super) fn codes(&mut self, slot: SlotId, code: bool, leaf: &Leaf<'a>) -> Hint { + if let Some((.., hint)) = self.codes.iter().find(|(s, c, _)| *s == slot && *c == code) { + return hint.clone(); + } + let hint = Dedup::codes(&leaf.column(), self.rows); + self.codes.push((slot, code, hint.clone())); + hint + } + + pub(super) fn viewed( + &mut self, + seg: &SegPlan, + r: Ref, + code: bool, + ) -> (Leaf<'a>, Option>) { + let leaf = self.leaf(r.slot); + let code = code && matches!(leaf.column().values, Values::Text { .. }); + let base = match self + .views + .iter() + .find(|(slot, coded, _)| *slot == r.slot && *coded == code) + { + Some((.., view)) => view.clone(), + None => { + let view = Normalizer::typed(&leaf, self.rows, code) + .map(|(leaf, faults)| (leaf, faults.map(Rc::from))); + self.views.push((r.slot, code, view.clone())); + view + } + }; + let Some((base, faults)) = base else { + return (self.value(seg, r), None); + }; + if Self::implied(seg, r) { + return (base, faults); + } + if let Some((.., cached)) = self + .viewed + .iter() + .find(|(slot, m, coded, _)| *slot == r.slot && *m == r.present && *coded == code) + { + return (cached.clone(), faults); + } + let mask = self.mask(seg, r.present); + let masked = Leaf::masked(base, &mask); + self.viewed.push((r.slot, r.present, code, masked.clone())); + (masked, faults) + } + + pub(super) fn shape(&mut self, seg: &SegPlan, node: &Node) -> Shaped<'a> { + let leaf = node + .leaf + .map(|r| (self.value(seg, r), self.mask(seg, r.present))); + let obj = node.obj.map(|m| self.mask(seg, m)); + let fields = node + .fields + .iter() + .map(|(key, child)| (Symbol::from(key.as_ref()), self.shape(seg, child))) + .collect(); + let same = node + .fields + .iter() + .enumerate() + .map(|(at, (_, child))| match child.fields.is_empty() { + true => None, + false => node.fields[..at] + .iter() + .position(|(_, other)| other == child), + }) + .collect(); + Shaped { + leaf, + obj, + fields, + same, + } + } + + pub(super) fn objects(shape: &Shaped<'a>, rows: usize) -> Vec { + let mut columns: Vec> = Vec::with_capacity(shape.fields.len()); + for (at, (_, child)) in shape.fields.iter().enumerate() { + let column = match shape + .same + .get(at) + .copied() + .flatten() + .and_then(|earlier| columns.get(earlier)) + { + Some(earlier) => earlier.clone(), + None => Self::objects(child, rows), + }; + columns.push(column); + } + let full = { + let mut map = VariableMap::with_capacity(shape.fields.len()); + shape.fields.iter().for_each(|(key, _)| { + map.insert(key.clone(), Variable::Null); + }); + map.shape().cloned() + }; + let leaf = shape + .leaf + .as_ref() + .map(|(leaf, present)| (leaf.column(), present)); + (0..rows) + .map(|row| { + if let Some((column, present)) = &leaf { + if Bits::get(present, row) { + return column.variable(row); + } + } + if !shape.obj.as_ref().is_some_and(|obj| Bits::get(obj, row)) { + return Variable::Null; + } + let complete = shape + .fields + .iter() + .all(|(_, child)| Self::exists(child, row)); + match (complete, &full) { + (true, Some(full)) => Variable::from_object(VariableMap::from_shape( + full.clone(), + columns + .iter_mut() + .map(|column| std::mem::replace(&mut column[row], Variable::Null)), + )), + _ => { + let mut map = VariableMap::with_capacity(shape.fields.len()); + for ((key, child), column) in shape.fields.iter().zip(columns.iter_mut()) { + if Self::exists(child, row) { + map.insert( + key.clone(), + std::mem::replace(&mut column[row], Variable::Null), + ); + } + } + Variable::from_object(map) + } + } + }) + .collect() + } + + fn exists(shape: &Shaped<'a>, row: usize) -> bool { + shape.leaf.as_ref().is_some_and(|(_, p)| Bits::get(p, row)) + || shape.obj.as_ref().is_some_and(|o| Bits::get(o, row)) + } + + pub(super) fn merged( + a: &Shaped<'a>, + b: &Shaped<'a>, + rr: bool, + rb: bool, + ra: bool, + row: usize, + ) -> Option { + if ra { + return Self::exists(a, row).then(|| Self::object(a, row)); + } + if rb { + return Self::exists(b, row).then(|| Self::object(b, row)); + } + if !rr { + return None; + } + if !Self::exists(b, row) { + return Self::exists(a, row).then(|| Self::object(a, row)); + } + let patch = Self::object(b, row); + match (&patch, Self::exists(a, row)) { + (Variable::Null, _) => None, + (Variable::Object(_), true) => { + let mut doc = Self::object(a, row); + Some(match doc { + Variable::Object(_) => doc.merge_clone(&patch), + _ => patch, + }) + } + _ => Some(patch), + } + } + + fn object(shape: &Shaped<'a>, row: usize) -> Variable { + if let Some((leaf, present)) = &shape.leaf { + if Bits::get(present, row) { + return leaf.get(row); + } + } + if !shape.obj.as_ref().is_some_and(|obj| Bits::get(obj, row)) { + return Variable::Null; + } + let mut map = VariableMap::with_capacity(shape.fields.len()); + for (key, child) in &shape.fields { + let present = child.leaf.as_ref().is_some_and(|(_, p)| Bits::get(p, row)) + || child.obj.as_ref().is_some_and(|o| Bits::get(o, row)); + if present { + map.insert(key.clone(), Self::object(child, row)); + } + } + Variable::from_object(map) + } + + pub(super) fn spread(&self, local: &Rc<[u64]>, positions: Option<&Rc<[usize]>>) -> Rc<[u64]> { + match positions { + None => local.clone(), + Some(positions) => { + let mut bits = vec![0u64; self.rows.div_ceil(64)]; + for (w, &word) in local.iter().enumerate() { + Bits::each(word, w * 64, |i| { + if let Some(&row) = positions.get(i) { + Bits::set(&mut bits, row, true); + } + }); + } + bits.into() + } + } + } + + pub(super) fn place(&self, leaf: Leaf<'a>, positions: Option<&Rc<[usize]>>) -> Leaf<'a> { + match positions { + None => leaf, + Some(positions) => Leaf::scattered(leaf, positions.clone(), self.rows), + } + } +} diff --git a/core/engine/src/compiled/graph/plan/run/table.rs b/core/engine/src/compiled/graph/plan/run/table.rs new file mode 100644 index 00000000..acfddf15 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/table.rs @@ -0,0 +1,254 @@ +use super::store::{Spread, Store}; +use super::Run; +use crate::compiled::bound::Bound; +use crate::compiled::core::exec::Dedup; +use crate::compiled::graph::plan::{SegPlan, TableMode, TableOp}; +use crate::compiled::graph::{Body, Kind}; +use crate::compiled::leaf::Mask; +use crate::compiled::leaf::{Array, Bits, Leaf, Literal, Records, Store as Buffer, Templated}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Binding as Bind, Column, Columns}; +use zen_expression::Variable; + +impl<'a> Run<'_, 'a> { + pub(super) fn table(&mut self, seg: &SegPlan, op: &TableOp, positions: Option<&Rc<[usize]>>) { + let Some(step) = self.graph.step_at(op.node) else { + return; + }; + let Kind::Node { + body: Body::Table(table), + .. + } = &step.kind + else { + return; + }; + let local = positions.map_or(self.store.rows, |p| p.len()); + let mut leaves: Vec>> = op + .reads + .iter() + .map(|(_, r)| { + r.map(|r| { + let leaf = self.store.value(seg, r); + match positions { + Some(positions) => leaf.regroup(positions), + None => leaf, + } + }) + }) + .collect(); + let keyed = match (op.mode, table.stable) { + (TableMode::First, true) => { + let present: Vec> = leaves.iter().flatten().cloned().collect(); + match present.len() > 1 { + true => Dedup::distinct(&present, &[], None, local), + false => None, + } + } + _ => None, + }; + let evaluated = match &keyed { + Some((reps, _)) => { + let reps: Rc<[usize]> = reps.as_slice().into(); + leaves = leaves + .into_iter() + .map(|leaf| leaf.map(|leaf| leaf.regroup(&reps))) + .collect(); + reps.len() + } + None => local, + }; + let mut columns = Columns::new(evaluated); + columns.columns.reserve_exact(op.reads.len()); + let mut names: Vec<(Arc, Bind)> = Vec::with_capacity(op.reads.len()); + let held: Vec>>> = match Records::LANE_VIEW { + true => leaves + .iter() + .map(|leaf| leaf.as_ref().and_then(Leaf::records)) + .collect(), + false => Vec::new(), + }; + let parts: Vec>> = match held.iter().any(Option::is_some) { + true => held.iter().map(|r| r.as_ref().map(|r| r.parts())).collect(), + false => Vec::new(), + }; + let items: Vec> = held + .iter() + .zip(&parts) + .map(|(r, p)| Some(r.as_ref()?.item(p.as_ref()?))) + .collect(); + let views: Vec> = leaves + .iter() + .enumerate() + .map(|(at, leaf)| { + match ( + held.get(at).and_then(Option::as_ref), + items.get(at).and_then(Option::as_ref), + ) { + (Some(record), Some(item)) => Some(record.list(item)), + _ => leaf.as_ref().map(Leaf::column), + } + }) + .collect(); + for ((key, _), view) in op.reads.iter().zip(&views) { + match view { + Some(view) => { + names.push((key.clone(), Bind::Column(columns.columns.len()))); + columns = columns.column(key.as_ref(), *view); + } + None => names.push((key.clone(), Bind::Absent)), + } + } + let bound = Bound { + scopes: Bound::blank(evaluated), + columns, + bind: Box::new(move |key: &str| match key.starts_with('$') { + true => Bind::Row, + false => names + .iter() + .find(|(k, _)| k.as_ref() == key) + .map_or(Bind::Absent, |(_, b)| *b), + }), + }; + let (columns, present, unmatched) = match op.mode { + TableMode::First => table.columns(table.first(&mut self.runner, &bound)), + TableMode::Collected => { + let collected = table.first_collect(&mut self.runner, &bound); + (collected.columns, collected.present, collected.unmatched) + } + TableMode::Rows => { + if let Some((records, codes, size)) = + table.collect_records(&mut self.runner, &bound) + { + let codes: Rc<[i32]> = match positions { + None => codes.into(), + Some(positions) => { + let mut full = vec![-1i32; self.store.rows]; + positions + .iter() + .zip(&codes) + .for_each(|(&row, &code)| full[row] = code); + full.into() + } + }; + let leaf = match positions { + None => Leaf::Records(Rc::new(records)), + Some(positions) => match records.spread(positions, self.store.rows) { + Some(spread) => Leaf::Records(Rc::new(spread)), + None => self + .store + .place(Leaf::Records(Rc::new(records)), Some(positions)), + }, + }; + if let Some(slot) = op.outs.first() { + self.store.slots[*slot as usize] = Some(leaf); + self.store.hints.push((*slot, codes, size)); + } + return; + } + let (values, hint) = match table.collect_keyed(&mut self.runner, &bound) { + Some((values, codes, size)) => { + let codes: Rc<[i32]> = match positions { + None => codes.into(), + Some(positions) => { + let mut full = vec![-1i32; self.store.rows]; + positions + .iter() + .zip(&codes) + .for_each(|(&row, &code)| full[row] = code); + full.into() + } + }; + (values, Some((codes, size))) + } + None => ( + table + .evaluate(&mut self.runner, &bound) + .into_iter() + .map(|out| table.value(out)) + .collect::>(), + None, + ), + }; + let leaf = self.store.place(Leaf::Any(values.into()), positions); + if let Some(slot) = op.outs.first() { + self.store.slots[*slot as usize] = Some(leaf); + if let Some((codes, size)) = hint { + self.store.hints.push((*slot, codes, size)); + } + } + return; + } + }; + let (columns, present, unmatched) = match &keyed { + Some((_, ids)) => ( + columns.iter().map(|leaf| leaf.expand(ids)).collect(), + present + .iter() + .map(|mask| { + Mask::Bits(Bits::of(local, |row| mask.get(ids[row] as usize)).into()) + }) + .collect(), + Bits::of(local, |row| Bits::get(&unmatched, ids[row] as usize)), + ), + None => (columns, present, unmatched), + }; + let mut spread: Vec = Vec::new(); + let mut cached = |store: &Store<'a>, dense: Rc<[u64]>| match spread + .iter() + .find(|(d, _)| Rc::ptr_eq(d, &dense) || *d == dense) + { + Some((_, bits)) => bits.clone(), + None => { + let bits = store.spread(&dense, positions); + spread.push((dense, bits.clone())); + bits + } + }; + for ((slot, leaf), (m, mask)) in op + .outs + .iter() + .zip(columns) + .zip(op.present.iter().zip(present)) + { + let leaf = self.store.place(leaf, positions); + self.store.slots[*slot as usize] = Some(leaf); + let bits = cached(&self.store, mask.dense(local)); + self.store.produce(*m, bits); + } + let mut matched: Vec = unmatched.iter().map(|w| !w).collect(); + Bits::trim(&mut matched, local); + let matched = cached(&self.store, matched.into()); + self.store.produce(op.matched, matched); + } + + pub(super) fn templated(array: &Array, rows: usize) -> Option> { + if !array.valid(0) { + return None; + } + let Buffer::Any(values) = array.store() else { + return None; + }; + let literal = match values.first()? { + Variable::Array(items) + if items.borrow().iter().all(|item| { + matches!( + item, + Variable::Null + | Variable::Bool(_) + | Variable::Number(_) + | Variable::String(_) + ) + }) => + { + return None + } + value @ (Variable::Array(_) | Variable::Object(_)) => Literal::of(value)?, + _ => return None, + }; + Some(Templated::leaf( + vec![0i32; rows].into(), + Rc::from(vec![literal]), + )) + } +} diff --git a/core/engine/src/compiled/graph/plan/run/typed.rs b/core/engine/src/compiled/graph/plan/run/typed.rs new file mode 100644 index 00000000..4253044e --- /dev/null +++ b/core/engine/src/compiled/graph/plan/run/typed.rs @@ -0,0 +1,529 @@ +use super::store::{Lowered, Prepared, Store}; +use super::Run; +use crate::compiled::census::Census; +use crate::compiled::core::exec::{Choice, Dedup, Hint, ListPart, Select, TypedCall}; +use crate::compiled::core::retry::Take; +use crate::compiled::core::switch::{Density, Path}; +use crate::compiled::graph::plan::typed::{Deferred, Grouping, Piece, Target, TypedOp}; +use crate::compiled::graph::plan::view::{SlotId, M}; +use crate::compiled::graph::plan::{Op, SegPlan, TableOp}; +use crate::compiled::graph::{Body, Kind}; +use crate::compiled::leaf::{Bits, Leaf}; +use crate::compiled::shred::{Normalizer, Seen}; +use crate::compiled::table::{First, Table}; +use std::rc::Rc; +use std::time::Instant; +use zen_expression::lane::Values; +use zen_expression::typed::{Data as Slotted, Outputs, Slot}; + +#[derive(Default)] +struct Held<'a> { + choice: Choice, + leaves: Vec>, + hints: Vec, +} + +impl<'a> Run<'_, 'a> { + pub(super) fn deferred( + &mut self, + seg: &SegPlan, + op: &Deferred, + units: &[Op], + positions: Option<&Rc<[usize]>>, + ) { + let rows = self.store.rows; + let seen: Vec<(SlotId, Seen)> = op + .keys + .iter() + .map(|slot| (*slot, Normalizer::seen(&self.store.leaf(*slot), rows))) + .collect(); + let key: Vec = seen.iter().map(|(_, seen)| *seen).collect(); + let graph = self.graph; + let store = &self.store; + let lister = |slot: SlotId, chain: &[&str]| { + store.listing(slot, chain).map(|listing| listing.classes()) + }; + let pieces = op.variant(&key, units.len(), || { + Grouping { + graph, + masks: &seg.masks, + slots: &seg.slots, + seen: &seen, + listing: Some(&lister), + } + .pieces(units) + }); + let mut at = 0; + let mut seen = self.store.errors.generation(); + let mut live = positions.cloned(); + for piece in pieces.iter() { + if self.store.errors.generation() != seen { + live = self.alive(live, &mut seen); + } + match piece { + Piece::Unit => { + if let Some(unit) = units.get(at) { + self.store.counts.1 += 1; + match Census::on() { + true => self.timed(seg, unit, live.as_ref()), + false => self.unit(seg, unit, live.as_ref()), + } + } + at += 1; + } + Piece::Typed(op, n) => { + self.typed( + seg, + op, + units.get(at..at + n).unwrap_or_default(), + live.as_ref(), + ); + at += n; + } + Piece::Deferred(op, n) => { + self.deferred( + seg, + op, + units.get(at..at + n).unwrap_or_default(), + live.as_ref(), + ); + at += n; + } + } + } + } + + pub(super) fn typed( + &mut self, + seg: &SegPlan, + op: &TypedOp, + units: &[Op], + positions: Option<&Rc<[usize]>>, + ) { + let rows = self.store.rows; + let local = positions.map_or(rows, |p| p.len()); + if Density::sparse(local, rows) { + match Census::on() { + true => self.fell("sparse", seg, units, positions, local), + false => self.laned(seg, units, positions), + } + return; + } + let path = op.cost.path(); + let start = Instant::now(); + let mut held = Held::default(); + let typed = match path.path { + Path::Typed => self + .lowered(seg, op, positions, &mut held) + .map(|lowered| self.merged(seg, op, units, positions, lowered)) + .is_some(), + Path::Lane => false, + }; + if !typed { + match Census::on() { + true => self.fell(&format!("{:?}", path.path), seg, units, positions, local), + false => self.laned(seg, units, positions), + } + } + let Held { + choice, + leaves, + hints, + } = held; + op.dedup + .settle(&op.cost, path, choice, start.elapsed(), local); + op.dedup.probe(&op.cost, self, local, |run| { + run.coded(op, &leaves, &hints, positions) + }); + } + + #[cold] + #[inline(never)] + fn fell( + &mut self, + what: &str, + seg: &SegPlan, + units: &[Op], + positions: Option<&Rc<[usize]>>, + local: usize, + ) { + let start = Instant::now(); + self.laned(seg, units, positions); + Census::record( + format!("typed->lane | {what}"), + local, + start.elapsed().as_nanos(), + ); + } + + fn laned(&mut self, seg: &SegPlan, units: &[Op], positions: Option<&Rc<[usize]>>) { + self.store.counts.1 += units.len(); + let mut seen = self.store.errors.generation(); + let mut live = positions.cloned(); + for unit in units { + if self.store.errors.generation() != seen { + live = self.alive(live, &mut seen); + } + self.unit(seg, unit, live.as_ref()); + } + } + + fn merged( + &mut self, + seg: &SegPlan, + op: &TypedOp, + units: &[Op], + positions: Option<&Rc<[usize]>>, + Lowered { + mut out, + keyed, + select, + prefault, + }: Lowered, + ) { + let rows = self.store.rows; + let local = positions.map_or(rows, |p| p.len()); + self.store.counts.0 += units.len(); + let ids = keyed.as_deref(); + let spots = positions.map(|p| &p[..]); + let mut take = Take::new(rows); + take.seed(prefault.as_deref(), spots); + let mut faulted = take.any(); + let mut dicts = op.exports.dictionaries(); + let mut at = 0; + for (unit, targets) in units.iter().zip(&op.targets) { + let slots = out.slots().get(at..at + targets.len()).unwrap_or_default(); + if slots.iter().any(|slot| slot.fault.any()) { + let mut failed: Vec = Vec::new(); + for slot in slots.iter().filter(|slot| slot.fault.any()) { + let words = slot.fault.words(); + failed.resize(failed.len().max(words.len()), 0); + failed.iter_mut().zip(words).for_each(|(f, w)| *f |= w); + } + take.absorb(&failed, ids, spots, local); + faulted = true; + } + if faulted { + let errors = &self.store.errors; + let rerun: Vec = take.drain(|row| errors.ok(row)); + if !rerun.is_empty() { + let rerun: Rc<[usize]> = rerun.into(); + self.settled = false; + self.unit(seg, unit, Some(&rerun)); + self.settled = true; + rerun + .iter() + .filter(|&&row| self.store.errors.ok(row)) + .for_each(|&row| take.set(row)); + } + faulted = take.any(); + } + let mut leaves: Vec<(SlotId, Leaf<'a>)> = Vec::with_capacity(targets.len()); + let mut masks: Vec<(M, Rc<[u64]>)> = Vec::new(); + for target in targets { + let Some(slot) = out.slot_mut(at) else { + return; + }; + at += 1; + let listed = slot.offsets.is_some(); + if let (Some(select), false) = (&select, listed) { + slot.valid.resize(select.len(), 0); + slot.valid + .iter_mut() + .zip(select) + .for_each(|(valid, chosen)| *valid &= chosen); + } + match (target, unit) { + (Target::Slot(id), _) if listed => { + let leaf = op.exports.leaf(slot, &mut dicts); + let leaf = match &select { + Some(select) => Leaf::masked(leaf, &Rc::from(select.as_slice())), + None => leaf, + }; + leaves.push((*id, leaf)); + } + (Target::Slot(id), _) => leaves.push((*id, op.exports.leaf(slot, &mut dicts))), + (Target::Choice, Op::Table(table)) => { + self.choice(table, slot, &mut leaves, &mut masks) + } + (Target::Choice, _) => {} + } + } + for (id, leaf) in leaves { + let leaf = self.widen(leaf, ids, positions); + let leaf = match faulted { + false => leaf, + true => Leaf::stitched(vec![leaf, self.store.leaf(id)], take.located()), + }; + if let Some(entry) = self.store.slots.get_mut(id as usize) { + *entry = Some(leaf); + } + } + for (m, bits) in masks { + let mut bits: Vec = match ids { + Some(ids) => { + let local: Rc<[u64]> = + Bits::of(local, |at| Bits::get(&bits, ids[at] as usize)).into(); + self.store.spread(&local, positions).to_vec() + } + None => bits.to_vec(), + }; + bits.resize(rows.div_ceil(64), 0); + Bits::trim(&mut bits, rows); + if faulted { + let laned = self.store.mask(seg, m); + bits.iter_mut() + .zip(laned.iter().zip(take.bits())) + .for_each(|(bit, (lane, fault))| *bit = (*bit & !fault) | (lane & fault)); + } + self.store.produce(m, bits.into()); + } + } + } + + fn decision(&self, op: &TableOp) -> Option<&Table> { + match self.graph.step_at(op.node).map(|step| &step.kind) { + Some(Kind::Node { + body: Body::Table(table), + .. + }) => Some(table), + _ => None, + } + } + + fn choice( + &self, + op: &TableOp, + slot: &Slot, + leaves: &mut Vec<(SlotId, Leaf<'a>)>, + masks: &mut Vec<(M, Rc<[u64]>)>, + ) { + let Some(table) = self.decision(op) else { + return; + }; + let count = slot.len; + let rules = table.rules(); + let codes: Vec = match &slot.data { + Slotted::Num { mant, .. } => (0..count) + .map(|at| { + match ( + slot.is_valid(at), + mant.get(at).and_then(|m| usize::try_from(*m).ok()), + ) { + (true, Some(rule)) if rule < rules => rule as i32, + _ => -1, + } + }) + .collect(), + _ => vec![-1; count], + }; + let matched: Rc<[u64]> = Bits::of(count, |at| codes[at] >= 0).into(); + match table.literal() { + true => { + let (columns, present, _) = table.columns(First::coded(rules, codes)); + for ((id, leaf), (m, mask)) in op + .outs + .iter() + .zip(columns) + .zip(op.present.iter().zip(present)) + { + leaves.push((*id, leaf)); + masks.push((*m, mask.dense(count))); + } + } + false => { + for (index, m) in op.present.iter().enumerate() { + let bits: Rc<[u64]> = Bits::of(count, |at| { + usize::try_from(codes[at]).is_ok_and(|rule| table.writes(rule, index)) + }) + .into(); + masks.push((*m, bits)); + } + } + } + masks.push((op.matched, matched)); + } + + fn widen( + &self, + leaf: Leaf<'a>, + ids: Option<&[u32]>, + positions: Option<&Rc<[usize]>>, + ) -> Leaf<'a> { + match ids { + Some(ids) => self.store.place(leaf.expand(ids), positions), + None => leaf, + } + } + + fn lowered( + &mut self, + seg: &SegPlan, + op: &TypedOp, + positions: Option<&Rc<[usize]>>, + held: &mut Held<'a>, + ) -> Option { + let rows = self.store.rows; + let mut hints: Vec = op + .columns + .iter() + .map(|read| { + self.store + .hints + .iter() + .find(|(slot, _, _)| *slot == read.slot) + .map(|(_, codes, size)| (codes.clone(), *size)) + }) + .collect(); + let raw: Vec> = op + .columns + .iter() + .map(|read| self.store.leaf(read.slot)) + .collect(); + let eligible = op.lists.is_empty() && op.dedup.eligible(&op.program, &raw, &hints); + let keyed = op.dedup.ready() && eligible; + let mut prefault: Option> = None; + let mut leaves: Vec> = Vec::with_capacity(op.columns.len()); + for (at, read) in op.columns.iter().enumerate() { + let (leaf, faults) = self.store.viewed( + seg, + *read, + keyed || op.shared.get(at).copied().unwrap_or(false), + ); + if let Some(faults) = faults { + let bits = prefault.get_or_insert_with(|| vec![0u64; rows.div_ceil(64)]); + bits.iter_mut() + .zip(faults.iter()) + .for_each(|(bit, fault)| *bit |= fault); + } + leaves.push(leaf); + } + match op.dedup.learn(keyed, &leaves, &mut hints, positions, rows) { + Some((reps, ids)) => { + let picks: Rc<[usize]> = reps.into(); + let picked: Vec> = leaves.iter().map(|leaf| leaf.pick(&picks)).collect(); + let call = TypedCall { + rows: picks.len(), + columns: &picked, + lists: Vec::new(), + select: None, + }; + Some(Lowered { + out: call.run(&op.program)?, + keyed: Some(ids), + select: None, + prefault, + }) + } + None => { + let select: Option> = + positions.map(|positions| Select::bits(rows, positions)); + let local = positions.map_or(rows, |p| p.len()); + let (out, ids) = match op.lists.is_empty() && !eligible { + true => { + let (out, choice) = op.dedup.choose( + self, + local, + |run| { + run.plain(seg, op, &leaves, select.as_deref()) + .map(|out| (out, None)) + }, + |run| run.coded(op, &leaves, &hints, positions), + ); + *held = Held { + choice, + leaves, + hints, + }; + out? + } + false => (self.plain(seg, op, &leaves, select.as_deref())?, None), + }; + let select = match ids { + Some(_) => None, + None => select, + }; + Some(Lowered { + out, + keyed: ids, + select, + prefault, + }) + } + } + } + + fn plain( + &mut self, + seg: &SegPlan, + op: &TypedOp, + leaves: &[Leaf<'a>], + select: Option<&[u64]>, + ) -> Option { + let rows = self.store.rows; + let mut listed: Vec> = Vec::with_capacity(op.lists.len()); + for (read, chain) in &op.lists { + let chain: Vec<&str> = chain.iter().map(|field| field.as_ref()).collect(); + let listing = self.store.listing(read.slot, &chain)?; + let (validity, faults) = match (chain.is_empty(), Store::implied(seg, *read)) { + (true, false) => { + let mask = self.store.mask(seg, read.present); + let mut validity = listing + .frame + .validity + .as_deref() + .map_or_else(|| Bits::ones(rows), <[u64]>::to_vec); + let mut faults = listing + .hosted + .as_deref() + .map_or_else(|| vec![0u64; rows.div_ceil(64)], <[u64]>::to_vec); + for row in (0..rows).filter(|&row| !Bits::get(&mask, row)) { + match listing.frame.offsets[row] == listing.frame.offsets[row + 1] { + true => Bits::set(&mut validity, row, false), + false => Bits::set(&mut faults, row, true), + } + } + (Some(validity), Some(faults)) + } + _ => (None, None), + }; + listed.push((listing, validity, faults)); + } + let call = TypedCall { + rows, + columns: leaves, + lists: listed + .iter() + .map(|(listing, validity, faults)| { + ListPart::Listing(listing, validity.as_deref(), faults.as_deref()) + }) + .collect(), + select, + }; + call.run(&op.program) + } + + fn coded( + &mut self, + op: &TypedOp, + leaves: &[Leaf<'a>], + hints: &[Hint], + positions: Option<&Rc<[usize]>>, + ) -> Option<(Outputs, Option>)> { + let rows = self.store.rows; + let mut codes: Vec = Vec::with_capacity(leaves.len()); + for (at, ((read, leaf), hint)) in op.columns.iter().zip(leaves).zip(hints).enumerate() { + let code = match (hint, leaf.column().values) { + (Some(hint), _) => Some(hint.clone()), + (None, Values::Dict { .. } | Values::Bool { .. }) => None, + (None, _) => Some(self.store.codes( + read.slot, + op.shared.get(at).copied().unwrap_or(false), + leaf, + )?), + }; + codes.push(code); + } + Dedup::reps(&op.program, leaves, &codes, positions, rows).map(|(out, ids)| (out, Some(ids))) + } +} diff --git a/core/engine/src/compiled/graph/plan/subgraphs.rs b/core/engine/src/compiled/graph/plan/subgraphs.rs new file mode 100644 index 00000000..00bbdc3d --- /dev/null +++ b/core/engine/src/compiled/graph/plan/subgraphs.rs @@ -0,0 +1,87 @@ +use crate::compiled::graph::call::Call; +use crate::compiled::graph::CompiledGraph; +use crate::model::{DecisionNodeKind, GraphContent}; +use crate::nodes::NodeHandlerExtensions; +use std::sync::Arc; + +#[derive(Default)] +pub(crate) struct Subgraphs { + graphs: Vec<(Arc, Arc)>, +} + +pub(crate) type Closure = Vec<(Arc, Arc)>; + +impl Subgraphs { + pub async fn resolve(graph: &CompiledGraph, extensions: &NodeHandlerExtensions) -> Subgraphs { + let mut found = Subgraphs::default(); + let mut pending: Vec> = Self::keys(graph); + let mut seen: Vec> = Vec::new(); + while let Some(key) = pending.pop() { + if seen.contains(&key) { + continue; + } + seen.push(key.clone()); + let Ok(content) = CompiledGraph::resolve_key(&key, extensions).await else { + continue; + }; + if let Ok(child) = Call::compiled(&content) { + pending.extend(Self::keys(child)); + } + found.graphs.push((key, content)); + } + found + } + + pub fn wanted(graph: &CompiledGraph) -> bool { + graph + .steps + .iter() + .flatten() + .any(|step| matches!(step.node.kind, DecisionNodeKind::DecisionNode { .. })) + } + + fn keys(graph: &CompiledGraph) -> Vec> { + graph + .steps + .iter() + .flatten() + .filter_map(|step| match &step.node.kind { + DecisionNodeKind::DecisionNode { content } => Some(content.key.clone()), + _ => None, + }) + .collect() + } + + pub fn get(&self, key: &str) -> Option<&Arc> { + self.graphs + .iter() + .find(|(k, _)| k.as_ref() == key) + .map(|(_, content)| content) + } + + pub fn closure(&self, graph: &CompiledGraph) -> Closure { + let mut out: Closure = Vec::new(); + let mut pending = Self::keys(graph); + while let Some(key) = pending.pop() { + if out.iter().any(|(k, _)| *k == key) { + continue; + } + let Some(content) = self.get(&key) else { + continue; + }; + if let Ok(child) = Call::compiled(content) { + pending.extend(Self::keys(child)); + } + out.push((key, content.clone())); + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + out + } + + pub fn same(a: &Closure, b: &Closure) -> bool { + a.len() == b.len() + && a.iter() + .zip(b) + .all(|((ka, ca), (kb, cb))| ka == kb && Arc::ptr_eq(ca, cb)) + } +} diff --git a/core/engine/src/compiled/graph/plan/typed.rs b/core/engine/src/compiled/graph/plan/typed.rs new file mode 100644 index 00000000..7a351f56 --- /dev/null +++ b/core/engine/src/compiled/graph/plan/typed.rs @@ -0,0 +1,752 @@ +use super::view::{Expr, Masks, Ref, Shape, SlotId, M}; +use super::{Builder, LaneOp, Op, Program, SlotInfo, Source, TableMode, TableOp}; +use crate::compiled::census::Census; +use crate::compiled::core::exec::Dedup; +use crate::compiled::core::group::{Attempt, Built, Prefix, Step}; +use crate::compiled::core::switch::Cost; +use crate::compiled::core::variants::Variants; +use crate::compiled::graph::{Body, CompiledGraph, Kind}; +use crate::compiled::lowered::Exports; +use crate::compiled::shred::Seen; +use crate::compiled::table::Table; +use std::sync::Arc; +use zen_expression::lane::{Binding as Site, Fusion}; +use zen_expression::typed::{Class, Lowering, Program as Typed, Resolve, Resolved, TableSpec}; + +pub(crate) enum Target { + Slot(SlotId), + Choice, +} + +pub(crate) type Fields = Vec<(Arc, Class)>; + +pub(crate) type Lister<'g> = &'g dyn Fn(SlotId, &[&str]) -> Option; + +pub(crate) struct TypedOp { + pub program: Typed, + pub exports: Exports, + pub columns: Vec, + pub lists: Vec<(Ref, Vec>)>, + pub targets: Vec>, + pub cost: Cost, + pub dedup: Dedup, + pub shared: Vec, +} + +pub(crate) enum Piece { + Unit, + Typed(Box, usize), + Deferred(Box, usize), +} + +type Variant = (Vec, Arc<[Piece]>); + +pub(crate) struct Deferred { + pub keys: Vec, + variants: Variants, +} + +pub(crate) struct Grouping<'g> { + pub graph: &'g CompiledGraph, + pub masks: &'g Masks, + pub slots: &'g [SlotInfo], + pub seen: &'g [(SlotId, Seen)], + pub listing: Option>, +} + +struct Probe<'p> { + masks: &'p Masks, + slots: &'p [SlotInfo], + seen: &'p [(SlotId, Seen)], + listing: Option>, + lists: Vec<(String, Ref)>, + deferred: bool, + novel: bool, + reads: Vec<(Arc, Option)>, + outputs: Vec<(SlotId, Vec, usize)>, + produced: Vec, + columns: Vec<(String, Ref)>, +} + +impl TypedOp { + fn new( + program: Typed, + columns: Vec, + lists: Vec<(Ref, Vec>)>, + targets: Vec>, + ) -> Self { + Self { + exports: Exports::of(program.hir()), + program, + columns, + lists, + targets, + cost: Cost::new(), + dedup: Dedup::new(), + shared: Vec::new(), + } + } +} + +impl Deferred { + const VARIANTS: usize = 8; + + fn new(keys: Vec) -> Self { + Self { + keys, + variants: Variants::new(Self::VARIANTS), + } + } + + pub fn variant( + &self, + seen: &[Seen], + units: usize, + build: impl FnOnce() -> Vec, + ) -> Arc<[Piece]> { + let plain = || -> Arc<[Piece]> { (0..units).map(|_| Piece::Unit).collect() }; + self.variants + .get_or_build( + |(key, pieces)| (key == seen).then(|| pieces.clone()), + || (seen.to_vec(), build().into()), + || (seen.to_vec(), plain()), + ) + .unwrap_or_else(plain) + } +} + +impl Resolve for Probe<'_> { + fn path(&mut self, path: &str) -> Resolved { + let Some((_, read)) = self.reads.iter().find(|(key, _)| key.as_ref() == path) else { + Census::note("unbound: "); + return Resolved::Unsupported; + }; + let Some(read) = *read else { + return Resolved::Absent; + }; + if let Some((_, allowed, at)) = self.outputs.iter().find(|(slot, _, _)| *slot == read.slot) + { + return match allowed.contains(&read.present) + || self.covers(read.present, read.slot, allowed) + { + true => Resolved::Output(*at), + false => { + Census::note("output mask: "); + Resolved::Unsupported + } + }; + } + if self.depends(read.present) { + Census::note("depends: "); + return Resolved::Unsupported; + } + let slot = self.slots.get(read.slot as usize); + let class = match slot.map(|info| info.shape) { + Some(Shape::Num) => Class::Num, + Some(Shape::Bool) => Class::Bool, + Some(Shape::Text) => Class::Text, + Some(Shape::Null) => return Resolved::Absent, + Some(shape @ (Shape::Dyn | Shape::Unknown)) + if shape == Shape::Dyn + || slot.is_some_and(|info| matches!(info.source, Source::Input(_))) => + { + match self.observed(read.slot, shape) { + Some(Seen::Num) => Class::Num, + Some(Seen::Bool) => Class::Bool, + Some(Seen::Text) => Class::Text, + Some(Seen::Null) => return Resolved::Absent, + Some(Seen::List) => return self.listed(read), + Some(Seen::Mixed) => { + Census::note("mixed: "); + return Resolved::Unsupported; + } + None => { + self.deferred = true; + return Resolved::Unsupported; + } + } + } + Some(Shape::List) => { + return match self.listing { + Some(_) => match self.listed(read) { + Resolved::KeyedList(key, fields) + if fields.iter().all(|(name, _)| name.is_empty()) => + { + self.novel = true; + Resolved::KeyedList(key, fields) + } + _ => { + Census::note("object list: "); + Resolved::Unsupported + } + }, + None => { + self.deferred = true; + Census::note("list: "); + Resolved::Unsupported + } + }; + } + other => { + Census::note(&format!("shape {other:?}: ")); + return Resolved::Unsupported; + } + }; + let key = format!("#{}:{:?}", read.slot, read.present); + if !self.columns.iter().any(|(k, _)| *k == key) { + self.columns.push((key.clone(), read)); + } + Resolved::Keyed(class, Arc::from(key)) + } + + fn alias(&mut self, _field: &str) -> Resolved { + Resolved::Unsupported + } + + fn novel(&mut self) -> bool { + std::mem::take(&mut self.novel) + } + + fn nested(&mut self, chain: &[&str]) -> Resolved { + let (Some((key, rest)), Some(listing)) = (chain.split_first(), self.listing) else { + return Resolved::Unsupported; + }; + let Some((_, read)) = self.lists.iter().find(|(k, _)| k.as_str() == *key) else { + return Resolved::Unsupported; + }; + match listing(read.slot, rest) { + Some(fields) => Resolved::List { fields }, + None => Resolved::Unsupported, + } + } +} + +impl Probe<'_> { + const ATOMS: usize = 12; + + fn observed(&mut self, slot: SlotId, shape: Shape) -> Option { + let seen = self + .seen + .iter() + .find(|(at, _)| *at == slot) + .map(|(_, seen)| *seen); + self.novel |= shape == Shape::Unknown && seen.is_some(); + seen + } + + fn listed(&mut self, read: Ref) -> Resolved { + let Some(fields) = self.listing.and_then(|listing| listing(read.slot, &[])) else { + Census::note("unlisted: "); + return Resolved::Unsupported; + }; + let key = format!("#{}:{:?}", read.slot, read.present); + if !self.lists.iter().any(|(k, _)| *k == key) { + self.lists.push((key.clone(), read)); + } + Resolved::KeyedList(Arc::from(key), fields) + } + + fn covers(&self, m: M, slot: SlotId, implied: &[M]) -> bool { + let mut atoms: Vec = Vec::new(); + if !self.atoms(m, &mut atoms) { + return false; + } + let given = |atom: &M| { + implied.contains(atom) + || matches!(atom, M::Id(id) if matches!(self.masks.exprs.get(*id as usize), Some(Expr::Valued(s) | Expr::Validity(s)) if *s == slot)) + }; + let free: Vec = atoms.iter().copied().filter(|atom| !given(atom)).collect(); + if free.len() > Self::ATOMS { + return false; + } + (0..1u32 << free.len()).all(|bits| { + let value = |atom: M| match free.iter().position(|f| *f == atom) { + Some(at) => bits >> at & 1 == 1, + None => true, + }; + self.holds(m, &value) + }) + } + + fn atoms(&self, m: M, out: &mut Vec) -> bool { + let M::Id(id) = m else { + return true; + }; + match self.masks.exprs.get(id as usize) { + Some(Expr::And(a, b) | Expr::Or(a, b)) => self.atoms(*a, out) && self.atoms(*b, out), + Some(Expr::Not(a)) => self.atoms(*a, out), + Some(_) => { + if !out.contains(&m) { + out.push(m); + } + true + } + None => false, + } + } + + fn holds(&self, m: M, value: &dyn Fn(M) -> bool) -> bool { + let M::Id(id) = m else { + return m == M::All; + }; + match self.masks.exprs.get(id as usize) { + Some(Expr::And(a, b)) => self.holds(*a, value) && self.holds(*b, value), + Some(Expr::Or(a, b)) => self.holds(*a, value) || self.holds(*b, value), + Some(Expr::Not(a)) => !self.holds(*a, value), + _ => value(m), + } + } + + fn depends(&self, m: M) -> bool { + let M::Id(id) = m else { + return false; + }; + if self.produced.contains(&m) { + return true; + } + match self.masks.exprs.get(id as usize) { + Some(Expr::Validity(slot) | Expr::Valued(slot)) => { + self.outputs.iter().any(|(s, _, _)| s == slot) + } + Some(Expr::And(a, b) | Expr::Or(a, b)) => self.depends(*a) || self.depends(*b), + Some(Expr::Not(a)) => self.depends(*a), + Some(Expr::Produced(_)) => false, + None => true, + } + } +} + +impl Builder<'_> { + pub(super) fn typed(&mut self) { + if !Exports::enabled() { + return; + } + let ops = std::mem::take(&mut self.catalog.ops); + let mut grouped = Vec::with_capacity(ops.len()); + let mut run: Vec = Vec::new(); + for op in ops { + match self.grouping().eligible(&op) { + true => run.push(op), + false => { + self.flush(&mut run, &mut grouped); + Census::reason(|| Grouping::ineligible(&op)); + op.refuse(self.graph); + grouped.push(op); + } + } + } + self.flush(&mut run, &mut grouped); + let texts: Vec = grouped + .iter() + .filter_map(|op| match op { + Op::Typed { op, .. } => Some(op.columns.iter().map(|read| read.slot)), + _ => None, + }) + .flatten() + .filter(|slot| { + matches!( + self.catalog.slots.get(*slot as usize), + Some(SlotInfo { + shape: Shape::Text, + source: Source::Input(_) + }) + ) + }) + .collect(); + for op in &mut grouped { + if let Op::Typed { op, .. } = op { + op.shared = op + .columns + .iter() + .map(|read| texts.iter().filter(|slot| **slot == read.slot).count() > 1) + .collect(); + } + } + self.catalog.ops = grouped; + } + + fn grouping(&self) -> Grouping<'_> { + Grouping { + graph: self.graph, + masks: &self.masks, + slots: &self.catalog.slots, + seen: &[], + listing: None, + } + } + + fn flush(&self, run: &mut Vec, out: &mut Vec) { + if run.is_empty() { + return; + } + let pieces = self.grouping().pieces(run); + let mut units = std::mem::take(run).into_iter(); + for piece in pieces { + match piece { + Piece::Unit => out.extend(units.next()), + Piece::Typed(op, n) => out.push(Op::Typed { + op, + units: units.by_ref().take(n).collect(), + }), + Piece::Deferred(op, n) => out.push(Op::Deferred { + op, + units: units.by_ref().take(n).collect(), + }), + } + } + } +} + +impl Grouping<'_> { + pub fn pieces(&self, ops: &[Op]) -> Vec { + let mut pieces = Vec::new(); + let mut at = 0; + while let Some(rest) = ops.get(at..).filter(|rest| !rest.is_empty()) { + match self.lower(rest) { + Attempt::Typed(_, n) + if rest + .iter() + .take(n) + .all(|op| matches!(op, Op::Lane(lane) if lane.uniform)) => + { + for op in rest.iter().take(n) { + Census::reason(|| "uniform".into()); + op.refuse(self.graph); + } + pieces.extend((0..n).map(|_| Piece::Unit)); + at += n; + } + Attempt::Typed(op, n) => { + pieces.push(Piece::Typed(op, n)); + at += n; + } + Attempt::Deferred => { + pieces.push(Piece::Deferred( + Box::new(Deferred::new(self.keys(rest))), + rest.len(), + )); + at = ops.len(); + } + Attempt::Failed => { + rest[0].refuse(self.graph); + pieces.push(Piece::Unit); + at += 1; + } + } + } + pieces + } + + fn keys(&self, ops: &[Op]) -> Vec { + let mut produced: Vec = Vec::new(); + let mut keys: Vec = Vec::new(); + for op in ops { + let (reads, outs): (Vec, &[SlotId]) = match op { + Op::Lane(lane) => ( + lane.reads.iter().map(|(_, read)| read.slot).collect(), + &lane.outs, + ), + Op::Table(table) => ( + table + .reads + .iter() + .filter_map(|(_, read)| read.map(|read| read.slot)) + .collect(), + &table.outs, + ), + _ => (Vec::new(), &[]), + }; + for slot in reads { + let dynamic = matches!( + self.slots.get(slot as usize), + Some( + SlotInfo { + shape: Shape::Dyn, + .. + } | SlotInfo { + shape: Shape::Unknown, + source: Source::Input(_) + } + ) + ); + if dynamic && !produced.contains(&slot) && !keys.contains(&slot) { + keys.push(slot); + } + } + produced.extend_from_slice(outs); + } + keys + } + + fn eligible(&self, op: &Op) -> bool { + match op { + Op::Lane(lane) => { + matches!(lane.program, Program::Expression) + && !lane.sources.is_empty() + && lane.sources.len() == lane.outs.len() + } + Op::Table(table) => { + table.mode == TableMode::First + && self.tabled(table).is_some_and(|t| t.spec.is_some()) + } + _ => false, + } + } + + fn tabled(&self, op: &TableOp) -> Option<&Table> { + match &self.graph.step_at(op.node)?.kind { + Kind::Node { + body: Body::Table(table), + .. + } => Some(table), + _ => None, + } + } + + fn sites(&self, op: &LaneOp) -> Option, Option)>> { + let program = match &op.own { + Some(own) => &own.program, + None => match &self.graph.step_at(op.node)?.kind { + Kind::Node { + body: Body::Expression { program, .. }, + .. + } => program.as_ref(), + _ => return None, + }, + }; + let mut reads: Vec<(Arc, Option)> = op + .reads + .iter() + .map(|(key, read)| (key.clone(), Some(*read))) + .collect(); + for (key, site) in program.program().site_keys.iter().zip(&op.bound) { + if let (Some(key), Site::Absent) = (key, site) { + reads.push((Arc::from(key.as_str()), None)); + } + } + Some(reads) + } + + fn lower(&self, ops: &[Op]) -> Attempt> { + Prefix::lower( + ops.len(), + || { + let probe = Probe { + masks: self.masks, + slots: self.slots, + seen: self.seen, + listing: self.listing, + lists: Vec::new(), + deferred: false, + novel: false, + reads: Vec::new(), + outputs: Vec::new(), + produced: Vec::new(), + columns: Vec::new(), + }; + (Lowering::graph(), probe, Vec::new(), Vec::new()) + }, + |(lowering, probe, targets, kept), at| { + self.unit(&ops[at], lowering, probe, targets, kept) + }, + |(lowering, probe, targets, kept)| self.build(lowering, probe, targets, kept), + ) + } + + fn unit( + &self, + op: &Op, + lowering: &mut Lowering, + probe: &mut Probe, + targets: &mut Vec>, + kept: &mut Vec, + ) -> Step>> { + let base = lowering.outputs(); + probe.deferred = false; + probe.novel = false; + let mut blanked: Vec = Vec::new(); + Census::fresh(); + let lowered = match op { + Op::Lane(lane) if self.eligible(op) => { + let Some(reads) = self.sites(lane) else { + return Step::Stop; + }; + probe.reads = reads; + let entries: Vec = lane + .sources + .iter() + .map(|(key, source)| Fusion::Output { + key: key.to_string(), + source: source.to_string(), + }) + .collect(); + lowering.unit(&entries, probe) + } + Op::Table(table) if self.eligible(op) => { + let Some((found, spec)) = + self.tabled(table).and_then(|t| Some((t, t.spec.as_ref()?))) + else { + return Step::Stop; + }; + probe.reads = table.reads.clone(); + match Self::blank(found, spec) { + Some((blank, columns)) => { + probe.novel = true; + blanked = columns; + lowering.table(&blank, probe) + } + None => lowering.table(spec, probe), + } + } + _ => { + Census::reason(|| Self::ineligible(op)); + return Step::Stop; + } + }; + if let Err(e) = &lowered { + Census::reason(|| e.0.clone()); + return match lowering.units() == 0 && probe.deferred { + true => Step::Done(Attempt::Deferred), + false => Step::Stop, + }; + } + let unit: Vec> = match op { + Op::Lane(lane) => { + for (at, slot) in lane.outs.iter().enumerate() { + probe.outputs.push((*slot, vec![M::All], base + at)); + } + lane.outs + .iter() + .map(|slot| Some(Target::Slot(*slot))) + .collect() + } + Op::Table(table) => { + for (at, (slot, present)) in table.outs.iter().zip(&table.present).enumerate() { + if !blanked.get(at).copied().unwrap_or(false) { + probe.outputs.push(( + *slot, + vec![M::All, *present, table.matched], + base + at, + )); + } + } + probe.produced.extend(table.present.iter().copied()); + probe.produced.push(table.matched); + let literal = self.tabled(table).is_some_and(Table::literal); + table + .outs + .iter() + .map(|slot| (!literal).then_some(Target::Slot(*slot))) + .chain(std::iter::once(Some(Target::Choice))) + .collect() + } + _ => Vec::new(), + }; + if lowering.outputs() != base + unit.len() { + Census::reason(|| "output count".into()); + return Step::Done(Attempt::Failed); + } + kept.extend(unit.iter().map(Option::is_some)); + targets.push(unit.into_iter().flatten().collect()); + Step::Lowered + } + + fn build( + &self, + mut lowering: Lowering, + probe: Probe, + targets: Vec>, + mut kept: Vec, + ) -> Built>> { + let consumed = lowering.units(); + if consumed == 0 { + return Built::Done(Attempt::Failed); + } + kept.resize(lowering.outputs(), true); + lowering.retain(|at| kept.get(at).copied().unwrap_or(true)); + let program = match Typed::new(lowering.finish()) { + Ok(program) => program, + Err(e) => { + Census::reason(|| format!("build: {}", e.0)); + return Built::Shrink { + consumed, + fallback: Attempt::Failed, + }; + } + }; + let schema = &program.hir().schema; + let columns = schema + .columns + .iter() + .map(|column| { + probe + .columns + .iter() + .find(|(key, _)| *key == column.path) + .map(|(_, read)| *read) + }) + .collect::>>(); + let lists = (0..schema.lists.len()) + .map(|at| { + let chain = schema.chain(at as u16); + let (key, rest) = chain.split_first()?; + let (_, read) = probe.lists.iter().find(|(k, _)| k.as_str() == *key)?; + Some((*read, rest.iter().map(|field| Arc::from(*field)).collect())) + }) + .collect::>)>>>(); + Built::Done(match (columns, lists) { + (Some(columns), Some(lists)) => Attempt::Typed( + Box::new(TypedOp::new(program, columns, lists, targets)), + consumed, + ), + _ => { + Census::reason(|| "columns unresolved".into()); + Attempt::Failed + } + }) + } + + fn blank(table: &Table, spec: &TableSpec) -> Option<(TableSpec, Vec)> { + if !table.literal() { + return None; + } + let composite = |value: &Option| { + value + .as_deref() + .is_some_and(|v| v.trim_start().starts_with(['[', '{'])) + }; + let columns: Vec = (0..spec.outputs.len()) + .map(|at| { + spec.rules + .iter() + .any(|rule| rule.values.get(at).is_some_and(composite)) + }) + .collect(); + if !columns.contains(&true) { + return None; + } + let mut blank = spec.clone(); + for rule in &mut blank.rules { + for (value, blanked) in rule.values.iter_mut().zip(&columns) { + if *blanked { + *value = None; + } + } + } + Some((blank, columns)) + } + + fn ineligible(op: &Op) -> String { + match op { + Op::Lane(lane) if !matches!(lane.program, Program::Expression) => { + "ineligible: switch/field program".into() + } + Op::Lane(_) => "ineligible: sources".into(), + Op::Table(table) if table.mode != TableMode::First => { + "ineligible: collect/rows table".into() + } + Op::Table(_) => "ineligible: table spec".into(), + _ => "ineligible".into(), + } + } +} diff --git a/core/engine/src/compiled/graph/plan/view.rs b/core/engine/src/compiled/graph/plan/view.rs new file mode 100644 index 00000000..4a93ad0d --- /dev/null +++ b/core/engine/src/compiled/graph/plan/view.rs @@ -0,0 +1,508 @@ +use super::refusal::{Overlap, Refusal}; +use std::sync::Arc; + +pub(crate) type SlotId = u32; +pub(crate) type MaskId = u32; + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)] +pub(crate) enum M { + None, + All, + Id(MaskId), +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(crate) enum Expr { + Validity(SlotId), + Valued(SlotId), + And(M, M), + Or(M, M), + Not(M), + Produced(u32), +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Shape { + Num, + Bool, + Text, + Null, + Dyn, + List, + Unknown, +} + +impl From for Shape { + fn from(scalar: crate::compiled::table::Scalar) -> Self { + match scalar { + crate::compiled::table::Scalar::Num => Shape::Num, + crate::compiled::table::Scalar::Bool => Shape::Bool, + crate::compiled::table::Scalar::Text => Shape::Text, + } + } +} + +impl Shape { + pub fn scalar(self) -> bool { + matches!(self, Shape::Num | Shape::Bool | Shape::Text | Shape::Null) + } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) struct Ref { + pub slot: SlotId, + pub present: M, +} + +#[derive(Clone, Default, Debug, PartialEq)] +pub(crate) struct Node { + pub leaf: Option, + pub obj: Option, + pub fields: Vec<(Arc, Node)>, +} + +pub(crate) enum Resolved { + Leaf(Ref), + Absent, + Object(Node), + Extract(Ref, Vec>), +} + +#[derive(Default, Clone)] +pub(crate) struct Masks { + pub exprs: Vec, + produced: u32, +} + +impl Masks { + pub fn produced(&mut self) -> M { + self.produced += 1; + self.intern(Expr::Produced(self.produced - 1)) + } + + fn intern(&mut self, expr: Expr) -> M { + match self.exprs.iter().position(|e| *e == expr) { + Some(at) => M::Id(at as MaskId), + None => { + self.exprs.push(expr); + M::Id((self.exprs.len() - 1) as MaskId) + } + } + } + + pub fn validity(&mut self, slot: SlotId) -> M { + self.intern(Expr::Validity(slot)) + } + + pub fn valued(&mut self, slot: SlotId) -> M { + self.intern(Expr::Valued(slot)) + } + + fn negates(&self, a: M, b: M) -> bool { + match (a, b) { + (M::Id(x), y) if self.exprs[x as usize] == Expr::Not(y) => true, + (x, M::Id(y)) if self.exprs[y as usize] == Expr::Not(x) => true, + _ => false, + } + } + + pub fn and(&mut self, a: M, b: M) -> M { + match (a, b) { + (M::None, _) | (_, M::None) => M::None, + (M::All, x) | (x, M::All) => x, + (x, y) if x == y => x, + (x, y) if self.negates(x, y) => M::None, + (x, y) => self.intern(Expr::And(x.min(y), x.max(y))), + } + } + + pub fn or(&mut self, a: M, b: M) -> M { + match (a, b) { + (M::All, _) | (_, M::All) => M::All, + (M::None, x) | (x, M::None) => x, + (x, y) if x == y => x, + (x, y) if self.negates(x, y) => M::All, + (x, y) => self.intern(Expr::Or(x.min(y), x.max(y))), + } + } + + pub fn implied(&self, leaf: Ref) -> bool { + match leaf.present { + M::All => true, + M::None => false, + M::Id(id) => { + matches!(self.exprs[id as usize], Expr::Validity(s) | Expr::Valued(s) if s == leaf.slot) + } + } + } + + pub fn not(&mut self, a: M) -> M { + match a { + M::None => M::All, + M::All => M::None, + M::Id(id) => match self.exprs[id as usize] { + Expr::Not(inner) => inner, + _ => self.intern(Expr::Not(a)), + }, + } + } + + pub fn and_not(&mut self, a: M, b: M) -> M { + let b = self.not(b); + self.and(a, b) + } + + pub fn any(&mut self, items: impl IntoIterator) -> M { + items.into_iter().fold(M::None, |acc, m| self.or(acc, m)) + } +} + +pub(crate) trait Slots { + fn shape(&self, slot: SlotId) -> Shape; + fn select(&mut self, a: Ref, b: Ref, take: M, present: M) -> SlotId; + fn merge_rows(&mut self, a: Node, b: Node, parts: [M; 3], present: M) -> SlotId; +} + +impl Node { + pub fn root(obj: M) -> Node { + Node { + leaf: None, + obj: Some(obj), + fields: Vec::new(), + } + } + + pub fn empty(&self) -> bool { + self.leaf.is_none() && self.obj.is_none_or(|o| o == M::None) && self.fields.is_empty() + } + + fn obj(&self) -> M { + self.obj.unwrap_or(M::None) + } + + pub fn insert(&mut self, path: &str, leaf: Ref, obj: M) -> Result<(), Refusal> { + let mut node = self; + let mut segments = path.split('.').peekable(); + while let Some(segment) = segments.next() { + let at = match node.fields.iter().position(|(k, _)| k.as_ref() == segment) { + Some(at) => at, + None => { + node.fields.push((Arc::from(segment), Node::default())); + node.fields.len() - 1 + } + }; + node = &mut node.fields[at].1; + match segments.peek() { + Some(_) => { + if node.leaf.is_some() { + return Err(Refusal::Overlaps { + path: Arc::from(path), + with: Overlap::Leaf, + }); + } + node.obj = Some(obj); + } + None => { + if !node.fields.is_empty() { + return Err(Refusal::Overlaps { + path: Arc::from(path), + with: Overlap::Object, + }); + } + node.leaf = Some(leaf); + } + } + } + Ok(()) + } + + pub fn insert_node(&mut self, path: &str, value: Node, obj: M) -> Result<(), Refusal> { + let mut node = self; + let mut segments = path.split('.').peekable(); + while let Some(segment) = segments.next() { + let at = match node.fields.iter().position(|(k, _)| k.as_ref() == segment) { + Some(at) => at, + None => { + node.fields.push((Arc::from(segment), Node::default())); + node.fields.len() - 1 + } + }; + node = &mut node.fields[at].1; + match segments.peek() { + Some(_) => { + if node.leaf.is_some() { + return Err(Refusal::Overlaps { + path: Arc::from(path), + with: Overlap::Leaf, + }); + } + node.obj = Some(obj); + } + None => { + if !node.fields.is_empty() || node.leaf.is_some() { + return Err(Refusal::Overlaps { + path: Arc::from(path), + with: Overlap::Value, + }); + } + *node = value; + return Ok(()); + } + } + } + Ok(()) + } + + pub fn insert_object(&mut self, path: &str, obj: M) -> Result<(), Refusal> { + let mut node = self; + for segment in path.split('.') { + let at = match node.fields.iter().position(|(k, _)| k.as_ref() == segment) { + Some(at) => at, + None => { + node.fields.push((Arc::from(segment), Node::default())); + node.fields.len() - 1 + } + }; + node = &mut node.fields[at].1; + if node.leaf.is_some() { + return Err(Refusal::Overlaps { + path: Arc::from(path), + with: Overlap::ObjectLeaf, + }); + } + node.obj = Some(obj); + } + Ok(()) + } + + pub fn objects_from_leaves(&mut self, masks: &mut Masks) -> M { + let mut present = Vec::new(); + for (_, child) in self.fields.iter_mut() { + present.push(child.objects_from_leaves(masks)); + } + if let Some(leaf) = self.leaf { + present.push(leaf.present); + } + let any = masks.any(present); + if !self.fields.is_empty() { + self.obj = Some(any); + } + any + } + + pub fn resolve(&self, path: &str, slots: &impl Slots) -> Result { + let mut node = self; + let segments: Vec<&str> = path.split('.').collect(); + for (at, segment) in segments.iter().enumerate() { + if let Some(leaf) = node.leaf { + if !slots.shape(leaf.slot).scalar() { + return match node.fields.is_empty() { + true => Ok(Resolved::Extract( + leaf, + segments[at..].iter().map(|s| Arc::from(*s)).collect(), + )), + false => Err(Refusal::ThroughDynamic(Arc::from(path))), + }; + } + } + match node.fields.iter().find(|(k, _)| k.as_ref() == *segment) { + Some((_, child)) => node = child, + None => return Ok(Resolved::Absent), + } + } + match (node.leaf, node.fields.is_empty()) { + (Some(leaf), true) => Ok(Resolved::Leaf(leaf)), + (None, true) => Ok(Resolved::Absent), + (None, false) => Ok(Resolved::Object(node.clone())), + (Some(_), false) => Err(Refusal::ValueOrObject(Arc::from(path))), + } + } + + pub fn wrap(node: Node, path: &str) -> Node { + let mut segments: Vec<&str> = path.split('.').collect(); + let mut current = node; + while let Some(last) = segments.pop() { + current = Node { + leaf: None, + obj: Some(M::All), + fields: vec![(Arc::from(last), current)], + }; + } + current + } + + pub fn head(&self) -> Node { + let mut head = self.clone(); + head.obj = Some(M::All); + head + } + + pub fn merge( + a: &Node, + b: &Node, + masks: &mut Masks, + slots: &mut dyn Slots, + ) -> Result { + if a.leaf.is_some() || b.leaf.is_some() { + return Self::child(a, b, M::All, M::None, M::None, masks, slots); + } + let (oa, ob) = (a.obj(), b.obj()); + let rr = masks.and(oa, ob); + let rb = masks.and_not(ob, oa); + let ra = masks.not(ob); + let mut node = Node::root(M::None); + let left = masks.and(ra, oa); + let both = masks.or(ob, left); + node.obj = Some(both); + node.fields = Self::fields(a, b, rr, rb, ra, masks, slots)?; + Ok(node) + } + + fn fields( + a: &Node, + b: &Node, + rr: M, + rb: M, + ra: M, + masks: &mut Masks, + slots: &mut dyn Slots, + ) -> Result, Node)>, Refusal> { + let empty = Node::default(); + let mut keys: Vec<&Arc> = a.fields.iter().map(|(k, _)| k).collect(); + for (k, _) in &b.fields { + if !keys.contains(&k) { + keys.push(k); + } + } + let mut out = Vec::with_capacity(keys.len()); + for key in keys { + let ca = a + .fields + .iter() + .find(|(k, _)| k == key) + .map_or(&empty, |(_, n)| n); + let cb = b + .fields + .iter() + .find(|(k, _)| k == key) + .map_or(&empty, |(_, n)| n); + let merged = Self::child(ca, cb, rr, rb, ra, masks, slots)?; + if !merged.empty() { + out.push((key.clone(), merged)); + } + } + Ok(out) + } + + fn child( + a: &Node, + b: &Node, + rr: M, + rb: M, + ra: M, + masks: &mut Masks, + slots: &mut dyn Slots, + ) -> Result { + let pb = b.leaf.map_or(M::None, |l| l.present); + let pa = a.leaf.map_or(M::None, |l| l.present); + let (oa, ob) = (a.obj(), b.obj()); + let dynamic = |leaf: Option| { + leaf.is_some_and(|l| { + !slots.shape(l.slot).scalar() && slots.shape(l.slot) != Shape::List + }) + }; + let (a_dyn, b_dyn) = (dynamic(a.leaf), dynamic(b.leaf)); + let a_object = a_dyn || oa != M::None; + let b_object = b_dyn || ob != M::None; + if rr != M::None && a_object && b_object && (a_dyn || b_dyn) { + { + let present = masks.produced(); + let slot = slots.merge_rows(a.clone(), b.clone(), [rr, rb, ra], present); + return Ok(Node { + leaf: Some(Ref { slot, present }), + obj: None, + fields: Vec::new(), + }); + } + } + let vb = match b.leaf { + Some(leaf) => masks.valued(leaf.slot), + None => M::None, + }; + let keep_b = masks.and(rb, pb); + let set_b = { + let x = masks.and(rr, pb); + masks.and(x, vb) + }; + let lb = masks.or(keep_b, set_b); + let untouched = { + let x = masks.and_not(rr, pb); + masks.and_not(x, ob) + }; + let keep = masks.or(ra, untouched); + let la = masks.and(pa, keep); + let leaf = match (b.leaf, a.leaf, lb, la) { + (_, _, M::None, M::None) => None, + (Some(b), _, lb, M::None) => Some(Ref { + slot: b.slot, + present: lb, + }), + (_, Some(a), M::None, la) => Some(Ref { + slot: a.slot, + present: la, + }), + (Some(b), Some(a), lb, la) => { + let present = masks.or(lb, la); + Some(Ref { + slot: slots.select(a, b, lb, present), + present, + }) + } + _ => None, + }; + let obj = { + let b_side = { + let r = masks.or(rb, rr); + masks.and(ob, r) + }; + let a_side = { + let kept = masks.and_not(rr, pb); + let r = masks.or(ra, kept); + masks.and(oa, r) + }; + masks.or(b_side, a_side) + }; + let rr2 = { + let x = masks.and(rr, ob); + masks.and(x, oa) + }; + let rb2 = { + let r = masks.and_not(rr, oa); + let r = masks.or(rb, r); + masks.and(ob, r) + }; + let ra2 = masks.and(oa, keep); + let fields = match a.fields.is_empty() && b.fields.is_empty() { + true => Vec::new(), + false => Self::fields(a, b, rr2, rb2, ra2, masks, slots)?, + }; + Ok(Node { + leaf, + obj: (obj != M::None).then_some(obj), + fields, + }) + } + + pub fn leaves(&self, prefix: &str, out: &mut Vec<(Arc, Ref)>) { + if let Some(leaf) = self.leaf { + out.push((Arc::from(prefix), leaf)); + } + for (key, child) in &self.fields { + let path = match prefix.is_empty() { + true => key.to_string(), + false => format!("{prefix}.{key}"), + }; + child.leaves(&path, out); + } + } +} diff --git a/core/engine/src/compiled/graph/schedule.rs b/core/engine/src/compiled/graph/schedule.rs new file mode 100644 index 00000000..1f69c4cc --- /dev/null +++ b/core/engine/src/compiled/graph/schedule.rs @@ -0,0 +1,112 @@ +use crate::compiled::core::segments::Children; +use crate::decision_graph::walker::{GraphWalker, NodeData, StableDiDecisionGraph, WalkStep}; +use crate::model::DecisionNodeKind; +use petgraph::prelude::NodeIndex; +use petgraph::Incoming; +use std::sync::Arc; + +pub(crate) type Outcome = Arc<[Arc]>; + +type Pending = (NodeIndex, Box<[NodeIndex]>, Box<[NodeIndex]>); + +pub(crate) struct Execute { + pub node: NodeIndex, + pub parents: Box<[NodeIndex]>, + pub visible: Box<[NodeIndex]>, +} + +pub(crate) enum End { + Finish(Box<[NodeIndex]>), + Switch { + node: NodeIndex, + parents: Box<[NodeIndex]>, + visible: Box<[NodeIndex]>, + children: Children>, + }, +} + +pub(crate) struct Segment { + pub path: Box<[Outcome]>, + pub events: Box<[Execute]>, + pub end: End, +} + +pub(crate) struct Replay<'a> { + graph: &'a StableDiDecisionGraph, +} + +impl<'a> Replay<'a> { + pub fn new(graph: &'a StableDiDecisionGraph) -> Self { + Self { graph } + } + + pub fn segment(&self, path: &[Outcome]) -> Segment { + let mut graph = self.graph.clone(); + let mut walker = GraphWalker::new(&graph); + let mut executed: Vec = Vec::new(); + let mut events: Vec = Vec::new(); + let mut consumed = 0usize; + let mut pending: Option = None; + + loop { + let step = walker.next_with(&mut graph, |_, g, nid, _, _| { + let outcome = path.get(consumed).cloned(); + match outcome { + Some(outcome) => { + consumed += 1; + Some(outcome.iter().cloned().collect()) + } + None => { + pending = Some(( + nid, + g.neighbors_directed(nid, Incoming).collect(), + executed.clone().into_boxed_slice(), + )); + None + } + } + }); + let nid = match step { + WalkStep::Node(nid) => nid, + WalkStep::Pending => { + let (node, parents, visible) = pending.take().unwrap_or_default(); + return Segment { + path: path.into(), + events: events.into_boxed_slice(), + end: End::Switch { + node, + parents, + visible, + children: Children::new(), + }, + }; + } + WalkStep::Done => break, + }; + if walker.has_node_data(nid) { + continue; + } + let Some(node) = graph.node_weight(nid).cloned() else { + break; + }; + if consumed == path.len() { + events.push(Execute { + node: nid, + parents: graph.neighbors_directed(nid, Incoming).collect(), + visible: executed.clone().into_boxed_slice(), + }); + } + executed.push(nid); + walker.set_node_data(nid, NodeData::placeholder(node.name.as_ref())); + if matches!(node.kind, DecisionNodeKind::OutputNode { .. }) { + break; + } + } + + Segment { + path: path.into(), + events: events.into_boxed_slice(), + end: End::Finish(walker.ending_nodes(&graph).into_boxed_slice()), + } + } +} diff --git a/core/engine/src/compiled/graph/schema.rs b/core/engine/src/compiled/graph/schema.rs new file mode 100644 index 00000000..8515ba54 --- /dev/null +++ b/core/engine/src/compiled/graph/schema.rs @@ -0,0 +1,862 @@ +use crate::compiled::graph::data::{Data, Shape}; +use crate::compiled::leaf::{Bits, Leaf}; +use crate::nodes::validator_cache::ValidatorCache; +use crate::nodes::variable_json::{Guards, VariableJson, VariableNode}; +use jsonschema::Validator; +use rust_decimal::prelude::ToPrimitive; +use rust_decimal::Decimal; +use serde_json::Value; +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Column, Values}; +use zen_expression::Variable; +use zen_types::path::DotPath; +use zen_types::variable::VariableMap; + +#[derive(Debug, Clone, Copy, PartialEq)] +enum SchemaType { + Number, + Integer, + Boolean, + String, + Array, + Object, +} + +#[derive(Debug)] +struct Bound { + limit: Decimal, + float: f64, + strict: bool, + upper: bool, +} + +#[derive(Debug)] +enum Check { + Any, + Type(SchemaType), + Strings(Vec), + Object(ObjectSchema), + Array(Box), + Number { + integer: bool, + bounds: Vec, + }, + Text { + values: Option>, + min: Option, + max: Option, + dated: bool, + }, + Nullable(Box), + List { + items: Box, + min: Option, + max: Option, + }, + Exact(Exact), +} + +struct Exact(Validator); + +impl std::fmt::Debug for Exact { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Exact") + } +} + +impl Exact { + fn compile(schema: &Value) -> Option { + match ObjectSchema::scoped(schema) || Self::drafted(schema) { + true => None, + false => ValidatorCache::build(schema).ok().map(Exact), + } + } + + fn drafted(schema: &Value) -> bool { + match schema { + Value::Object(map) => map + .iter() + .any(|(key, value)| key == "$schema" || Self::drafted(value)), + Value::Array(values) => values.iter().any(Self::drafted), + _ => false, + } + } + + fn valid(&self, value: &Variable) -> bool { + self.0 + .is_valid(VariableNode::new(value, &Guards::default())) + } +} + +pub(crate) struct Verdicts { + pub sure: Vec, + pub missing: Vec>, +} + +#[derive(Debug)] +struct Property { + name: String, + required: bool, + check: Check, +} + +#[derive(Debug)] +pub(crate) struct ObjectSchema { + properties: Vec, + additional: bool, +} + +enum Target<'s> { + Free, + Check(&'s Check), + Forbidden, +} + +impl Check { + fn annotation(key: &str) -> bool { + matches!( + key, + "title" + | "description" + | "$comment" + | "default" + | "examples" + | "readOnly" + | "writeOnly" + ) + } + + fn compile(schema: &Value) -> Option { + Self::basic(schema) + .or_else(|| schema.as_object().and_then(Self::extended)) + .or_else(|| Exact::compile(schema).map(Self::Exact)) + } + + fn group(key: &str) -> Option<&'static str> { + match key { + "minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum" | "multipleOf" => { + Some("number") + } + "minLength" | "maxLength" | "pattern" | "format" | "contentMediaType" + | "contentEncoding" => Some("string"), + "items" | "additionalItems" | "minItems" | "maxItems" | "uniqueItems" | "contains" => { + Some("array") + } + "properties" + | "required" + | "additionalProperties" + | "minProperties" + | "maxProperties" + | "patternProperties" + | "propertyNames" + | "dependencies" => Some("object"), + _ => None, + } + } + + fn limit(value: &Value, strict: bool, upper: bool) -> Option { + let limit = value.as_i64().filter(|n| n.unsigned_abs() <= 1 << 53)?; + Some(Bound { + limit: Decimal::from(limit), + float: limit as f64, + strict, + upper, + }) + } + + fn size(value: &Value) -> Option { + value.as_u64().and_then(|n| usize::try_from(n).ok()) + } + + fn extended(object: &serde_json::Map) -> Option { + let ty = object.get("type")?.as_str()?; + let family = match ty { + "integer" => "number", + other => other, + }; + let mut bounds = Vec::new(); + let (mut min, mut max, mut values, mut items) = (None, None, None, None); + let mut dated = false; + for (key, value) in object { + if key == "type" || Self::annotation(key) { + continue; + } + let group = Self::group(key); + if group.is_some_and(|group| group != family) { + continue; + } + match (family, key.as_str()) { + ("number", "minimum") => bounds.push(Self::limit(value, false, false)?), + ("number", "exclusiveMinimum") => bounds.push(Self::limit(value, true, false)?), + ("number", "maximum") => bounds.push(Self::limit(value, false, true)?), + ("number", "exclusiveMaximum") => bounds.push(Self::limit(value, true, true)?), + ("string", "minLength") | ("array", "minItems") => min = Some(Self::size(value)?), + ("string", "maxLength") | ("array", "maxItems") => max = Some(Self::size(value)?), + ("string", "enum") => { + let mut strings = value + .as_array()? + .iter() + .map(|v| v.as_str().map(str::to_owned)) + .collect::>>()?; + strings.sort_unstable(); + strings.dedup(); + values = Some(strings); + } + ("array", "items") => items = Some(Self::compile(value)?), + ("string", "format") => match value.as_str()? { + "date" | "date-time" => dated = true, + _ => return None, + }, + _ => return None, + } + } + match family { + "number" => Some(Self::Number { + integer: ty == "integer", + bounds, + }), + "string" => Some(Self::Text { + values, + min, + max, + dated, + }), + "array" => Some(Self::List { + items: Box::new(items.unwrap_or(Self::Any)), + min, + max, + }), + _ => None, + } + } + + fn nullable(variants: &[Value]) -> Option { + let null = |variant: &Value| { + variant.as_object().is_some_and(|object| { + object + .iter() + .filter(|(key, _)| !Self::annotation(key)) + .map(|(key, value)| (key.as_str(), value.as_str())) + .eq([("type", Some("null"))]) + }) + }; + match variants { + [a, b] if null(a) && !null(b) => Some(Self::Nullable(Box::new(Self::compile(b)?))), + [a, b] if null(b) && !null(a) => Some(Self::Nullable(Box::new(Self::compile(a)?))), + _ => None, + } + } + + fn integral(n: Decimal) -> bool { + n.scale() == 0 && i64::try_from(n).is_ok() + } + + fn bounded(bounds: &[Bound], n: Decimal) -> bool { + if bounds.is_empty() { + return true; + } + let Some(float) = n.to_f64() else { + return false; + }; + bounds + .iter() + .all(|bound| match (bound.upper, bound.strict) { + (false, false) => n >= bound.limit && float >= bound.float, + (false, true) => n > bound.limit && float > bound.float, + (true, false) => n <= bound.limit && float <= bound.float, + (true, true) => n < bound.limit && float < bound.float, + }) + } + + fn numeric(integer: bool, bounds: &[Bound], n: Decimal) -> bool { + (!integer || Self::integral(n)) && Self::bounded(bounds, n) + } + + fn textual( + values: &Option>, + min: Option, + max: Option, + text: &str, + ) -> bool { + let within = match (min, max) { + (None, None) => true, + _ => { + let count = text.chars().count(); + min.is_none_or(|m| count >= m) && max.is_none_or(|m| count <= m) + } + }; + within + && values + .as_ref() + .is_none_or(|v| v.binary_search_by(|s| s.as_str().cmp(text)).is_ok()) + } + + fn dated(dated: bool, text: &str) -> bool { + !dated || zen_expression::DateValue::is_text(text) + } + + fn counted(min: Option, max: Option, count: usize) -> bool { + min.is_none_or(|m| count >= m) && max.is_none_or(|m| count <= m) + } + + fn basic(schema: &Value) -> Option { + if schema == &Value::Bool(true) { + return Some(Self::Any); + } + let object = schema.as_object()?; + let keys: Vec<&str> = object + .keys() + .filter(|key| !Self::annotation(key)) + .map(String::as_str) + .collect(); + if keys.is_empty() { + return Some(Self::Any); + } + if keys == ["type"] { + return match object["type"].as_str()? { + "number" => Some(Self::Type(SchemaType::Number)), + "integer" => Some(Self::Type(SchemaType::Integer)), + "boolean" => Some(Self::Type(SchemaType::Boolean)), + "string" => Some(Self::Type(SchemaType::String)), + "array" => Some(Self::Type(SchemaType::Array)), + "object" => Some(Self::Type(SchemaType::Object)), + _ => None, + }; + } + if keys + .iter() + .all(|key| matches!(*key, "type" | "enum" | "const")) + && object + .get("type") + .is_none_or(|ty| ty.as_str() == Some("string")) + { + let strings: Option> = match (object.get("enum"), object.get("const")) { + (Some(Value::Array(values)), None) => values + .iter() + .map(|v| v.as_str().map(str::to_owned)) + .collect(), + (None, Some(Value::String(value))) => Some(vec![value.clone()]), + _ => None, + }; + if let Some(mut strings) = strings { + strings.sort_unstable(); + strings.dedup(); + return Some(Self::Strings(strings)); + } + return None; + } + if let Some(nested) = ObjectSchema::compile(schema) { + return Some(Self::Object(nested)); + } + if keys == ["anyOf"] { + return Self::nullable(object.get("anyOf")?.as_array()?); + } + if keys.iter().all(|key| matches!(*key, "type" | "items")) + && object.get("type").and_then(Value::as_str) == Some("array") + { + return object + .get("items") + .and_then(Self::compile) + .map(|items| Self::Array(Box::new(items))); + } + None + } + + fn sure(&self, value: &Variable) -> bool { + match self { + Self::Any => true, + Self::Type(kind) => match (kind, value) { + (SchemaType::Number, Variable::Number(_)) => true, + (SchemaType::Integer, Variable::Number(n)) => { + n.scale() == 0 && i64::try_from(*n).is_ok() + } + (SchemaType::Boolean, Variable::Bool(_)) => true, + (SchemaType::String, Variable::String(_)) => true, + (SchemaType::Array, Variable::Array(_)) => true, + (SchemaType::Object, Variable::Object(_)) => true, + _ => false, + }, + Self::Strings(strings) => match value { + Variable::String(text) => strings + .binary_search_by(|s| s.as_str().cmp(text.as_ref())) + .is_ok(), + _ => false, + }, + Self::Object(schema) => match value { + Variable::Object(map) => schema.sure_map(&map.borrow()), + _ => false, + }, + Self::Array(items) => match value { + Variable::Array(values) => values.borrow().iter().all(|item| items.sure(item)), + _ => false, + }, + Self::Number { integer, bounds } => match value { + Variable::Number(n) => Self::numeric(*integer, bounds, *n), + _ => false, + }, + Self::Text { + values, + min, + max, + dated, + } => match value { + Variable::String(text) => { + Self::textual(values, *min, *max, text) && Self::dated(*dated, text) + } + _ => false, + }, + Self::Nullable(inner) => matches!(value, Variable::Null) || inner.sure(value), + Self::Exact(exact) => exact.valid(value), + Self::List { items, min, max } => match value { + Variable::Array(values) => { + let values = values.borrow(); + Self::counted(*min, *max, values.len()) + && values.iter().all(|item| items.sure(item)) + } + _ => false, + }, + } + } + + fn sure_bits(&self, leaf: &Leaf, rows: usize) -> Vec { + if let Self::Exact(exact) = self { + return Bits::of(rows, |row| exact.valid(&leaf.get(row))); + } + let column = leaf.column(); + match (self, column.values) { + (Self::Any, _) + | ( + Self::Type(SchemaType::Number), + Values::Scaled { .. } | Values::Dec(_) | Values::I64(_), + ) + | (Self::Type(SchemaType::Integer), Values::I64(_)) + | (Self::Type(SchemaType::Boolean), Values::Bool { .. }) => leaf.validity(rows), + _ => Bits::of(rows, |row| self.sure_column(&column, row)), + } + } + + fn sure_column(&self, column: &zen_expression::lane::Column, row: usize) -> bool { + if let Self::Nullable(inner) = self { + return !column.valid(row) || inner.sure_column(column, row); + } + if let Self::Exact(exact) = self { + return exact.valid(&column.variable(row)); + } + if !column.valid(row) { + return false; + } + match (self, column.values) { + (Self::Any, _) => true, + ( + Self::Type(SchemaType::Number), + Values::Scaled { .. } | Values::Dec(_) | Values::I64(_), + ) => true, + (Self::Type(SchemaType::Number), Values::F64(_)) => column.number(row).is_some(), + (Self::Type(SchemaType::Integer), Values::Scaled { scale, .. }) => { + scale.get(row) == Some(&0) + } + (Self::Type(SchemaType::Integer), Values::I64(_)) => true, + (Self::Type(SchemaType::Integer), Values::Dec(_) | Values::F64(_)) => column + .number(row) + .is_some_and(|n| n.scale() == 0 && i64::try_from(n).is_ok()), + (Self::Type(SchemaType::Boolean), Values::Bool { .. }) => true, + ( + Self::Type(SchemaType::String), + Values::Text { .. } | Values::Utf8 { .. } | Values::Dict { .. }, + ) => column.text(row).is_some(), + ( + Self::Strings(strings), + Values::Text { .. } + | Values::Utf8 { .. } + | Values::LargeUtf8 { .. } + | Values::Dict { .. }, + ) => column.bytes(row).is_some_and(|bytes| { + strings + .iter() + .any(|s| s.len() == bytes.len() && s.as_bytes() == bytes) + }), + (Self::Type(SchemaType::Array), Values::List { .. }) => true, + (Self::Array(items), Values::List { offsets, child }) => { + let child = child.column(); + match (offsets.get(row), offsets.get(row + 1)) { + (Some(a), Some(b)) => { + (*a as usize..*b as usize).all(|i| items.sure_column(&child, i)) + } + _ => false, + } + } + ( + Self::Number { integer, bounds }, + Values::Scaled { .. } | Values::Dec(_) | Values::I64(_) | Values::F64(_), + ) => column + .number(row) + .is_some_and(|n| Self::numeric(*integer, bounds, n)), + ( + Self::Text { + values, + min, + max, + dated, + }, + Values::Text { .. } | Values::Utf8 { .. } | Values::Dict { .. }, + ) => column.text(row).is_some_and(|text| { + Self::textual(values, *min, *max, text) && Self::dated(*dated, text) + }), + (Self::List { items, min, max }, Values::List { offsets, child }) => { + let child = child.column(); + match (offsets.get(row), offsets.get(row + 1)) { + (Some(a), Some(b)) => { + let (a, b) = (*a as usize, *b as usize); + b >= a + && Self::counted(*min, *max, b - a) + && (a..b).all(|i| items.sure_column(&child, i)) + } + _ => false, + } + } + (_, Values::Any(_)) => column.borrowed(row).is_some_and(|value| self.sure(value)), + (_, Values::List { .. } | Values::Struct { .. }) => false, + (Self::Type(SchemaType::Number), _) => column.number(row).is_some(), + (Self::Type(SchemaType::Integer), _) => column.number(row).is_some_and(Self::integral), + (Self::Type(SchemaType::Boolean), _) => column.boolean(row).is_some(), + (Self::Type(SchemaType::String), _) => column.text(row).is_some(), + (Self::Strings(strings), _) => column + .text(row) + .is_some_and(|text| strings.binary_search_by(|s| s.as_str().cmp(text)).is_ok()), + (Self::Number { integer, bounds }, _) => column + .number(row) + .is_some_and(|n| Self::numeric(*integer, bounds, n)), + ( + Self::Text { + values, + min, + max, + dated, + }, + _, + ) => column.text(row).is_some_and(|text| { + Self::textual(values, *min, *max, text) && Self::dated(*dated, text) + }), + _ => false, + } + } +} + +type Compiled = (Arc, Option>); + +impl ObjectSchema { + thread_local! { + static CACHE: RefCell> = const { RefCell::new(Vec::new()) }; + } + + pub fn cached(schema: &Arc) -> Option> { + Self::CACHE.with_borrow_mut(|cache| { + if let Some((_, compiled)) = cache.iter().find(|(s, _)| Arc::ptr_eq(s, schema)) { + return compiled.clone(); + } + let compiled = Self::compile(schema).map(Rc::new); + if cache.len() >= 64 { + cache.remove(0); + } + cache.push((schema.clone(), compiled.clone())); + compiled + }) + } + + fn compile(schema: &Value) -> Option { + let object = schema.as_object()?; + if object.get("type")?.as_str()? != "object" + || object.keys().any(|key| { + !Check::annotation(key) + && !matches!( + key.as_str(), + "type" | "properties" | "required" | "additionalProperties" | "$schema" + ) + }) + || Self::scoped(schema) + { + return None; + } + let additional = match object.get("additionalProperties") { + None | Some(Value::Bool(true)) => true, + Some(Value::Bool(false)) => false, + _ => return None, + }; + let mut properties = Vec::new(); + if let Some(fields) = object.get("properties") { + for (name, schema) in fields.as_object()? { + properties.push(Property { + name: name.clone(), + required: false, + check: Check::compile(schema)?, + }); + } + } + if let Some(required) = object.get("required") { + for name in required.as_array()? { + let name = name.as_str()?; + match properties.iter_mut().find(|field| field.name == name) { + Some(field) => field.required = true, + None if !additional => return None, + None => properties.push(Property { + name: name.to_owned(), + required: true, + check: Check::Any, + }), + } + } + } + if properties + .iter() + .any(|field| field.name.is_empty() || field.name.contains('.')) + { + return None; + } + properties.sort_unstable_by(|a, b| a.name.cmp(&b.name)); + Some(Self { + properties, + additional, + }) + } + + fn scoped(schema: &Value) -> bool { + match schema { + Value::Object(map) => map.iter().any(|(key, value)| { + matches!( + key.as_str(), + "$ref" | "$id" | "$anchor" | "$dynamicRef" | "$recursiveRef" + ) || Self::scoped(value) + }), + Value::Array(values) => values.iter().any(Self::scoped), + _ => false, + } + } + + fn property(&self, name: &str) -> Option<&Property> { + self.properties + .binary_search_by(|field| field.name.as_str().cmp(name)) + .ok() + .map(|at| &self.properties[at]) + } + + fn sure_map(&self, map: &VariableMap) -> bool { + self.properties + .iter() + .all(|field| match map.get_str(&field.name) { + Some(value) => field.check.sure(value), + None => !field.required, + }) + && (self.additional + || map + .iter() + .all(|(key, _)| self.property(key.as_ref()).is_some())) + } + + fn target<'s>(&'s self, path: &str) -> (Target<'s>, Vec<(String, &'s ObjectSchema)>) { + let mut levels = vec![(String::new(), self)]; + let mut current = self; + let mut prefix = String::new(); + let mut segments = path.split('.').peekable(); + while let Some(segment) = segments.next() { + let Some(property) = current.property(segment) else { + return match current.additional { + true => (Target::Free, levels), + false => (Target::Forbidden, levels), + }; + }; + if !prefix.is_empty() { + prefix.push('.'); + } + prefix.push_str(segment); + if segments.peek().is_none() { + return (Target::Check(&property.check), levels); + } + match &property.check { + Check::Object(nested) => { + levels.push((prefix.clone(), nested)); + current = nested; + } + Check::Any | Check::Type(SchemaType::Object) => return (Target::Free, levels), + _ => return (Target::Forbidden, levels), + } + } + (Target::Free, levels) + } + + fn holds_null(value: &Variable) -> bool { + match value { + Variable::Null => true, + Variable::Object(map) => map + .borrow() + .iter() + .any(|(_, field)| Self::holds_null(field)), + Variable::Array(items) => items.borrow().iter().any(Self::holds_null), + _ => false, + } + } + + fn spotless(column: &Column, row: usize) -> bool { + if !column.valid(row) { + return false; + } + match column.values { + Values::Dec(_) + | Values::Scaled { .. } + | Values::I64(_) + | Values::F64(_) + | Values::Bool { .. } + | Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) => true, + Values::Dict { .. } => column.text(row).is_some() || column.number(row).is_some(), + Values::List { offsets, child } => { + let child = child.column(); + match (offsets.get(row), offsets.get(row + 1)) { + (Some(a), Some(b)) => { + (*a as usize..*b as usize).all(|i| Self::spotless(&child, i)) + } + _ => false, + } + } + Values::Any(_) => column + .borrowed(row) + .is_some_and(|value| !Self::holds_null(value)), + Values::Struct { .. } => false, + } + } + + pub fn verdicts(&self, data: &Data) -> Option { + let leaves = data.leaves(); + let rows = data.len(); + if leaves.is_empty() + || leaves + .iter() + .any(|(path, _)| path.is_empty() || path.starts_with('$')) + { + return None; + } + let overlapping = leaves + .iter() + .any(|(a, _)| leaves.iter().any(|(b, _)| DotPath::under(b, a))); + if overlapping { + return None; + } + let mut sure = vec![true; rows]; + let mut missing: Vec = Vec::new(); + let mut slots = 0u32; + let mut objects: Vec<(String, &ObjectSchema)> = Vec::new(); + let presences: Vec> = (0..leaves.len()) + .map(|index| data.presence_bits(index)) + .collect::>()?; + for ((path, leaf), present) in leaves.iter().zip(&presences) { + let (target, levels) = self.target(path); + for level in levels { + if !objects.iter().any(|(p, _)| *p == level.0) { + objects.push(level); + } + } + let passing = match &target { + Target::Free => None, + Target::Forbidden => Some(vec![0u64; rows.div_ceil(64)]), + Target::Check(check) => Some(check.sure_bits(leaf, rows)), + }; + if let Some(passing) = passing { + for (row, sure) in sure.iter_mut().enumerate() { + *sure &= !Bits::get(present, row) || Bits::get(&passing, row); + } + } + } + for (prefix, schema) in objects { + let under = |path: &str, name: &str| -> bool { + let rest = match prefix.is_empty() { + true => Some(path), + false => DotPath::tail(path, &prefix), + }; + rest.is_some_and(|rest| DotPath::within(rest, name)) + }; + let within: Vec = leaves + .iter() + .enumerate() + .filter(|(_, (path, _))| prefix.is_empty() || DotPath::under(path, &prefix)) + .map(|(index, _)| index) + .collect(); + let words = rows.div_ceil(64); + let union = |indices: &mut dyn Iterator| { + let mut bits = vec![0u64; words]; + for i in indices { + bits.iter_mut() + .zip(&presences[i]) + .for_each(|(b, p)| *b |= p); + } + bits + }; + let exists = match prefix.is_empty() { + true => vec![u64::MAX; words], + false => union(&mut within.iter().copied()), + }; + for field in schema.properties.iter().filter(|field| field.required) { + let exact = |path: &str| match prefix.is_empty() { + true => path == field.name, + false => DotPath::tail(path, &prefix) == Some(field.name.as_str()), + }; + let slot = match slots < 64 && leaves.iter().any(|(path, _)| exact(path)) { + true => { + slots += 1; + Some(slots - 1) + } + false => None, + }; + let held = union( + &mut within + .iter() + .copied() + .filter(|&i| under(&leaves[i].0, &field.name)), + ); + if slot.is_some() && missing.is_empty() { + missing = vec![0u64; rows]; + } + for row in + (0..rows).filter(|&row| Bits::get(&exists, row) && !Bits::get(&held, row)) + { + match slot { + Some(slot) => missing[row] |= 1u64 << slot, + None => sure[row] = false, + } + } + } + } + if missing.iter().all(|key| *key == 0) { + return Some(Verdicts { + sure, + missing: Vec::new(), + }); + } + let nulls = match &data.shape { + Shape::Patched { + base: None, nulls, .. + } => Some(nulls), + _ => None, + }; + let columns: Vec = match nulls { + Some(_) => leaves.iter().map(|(_, leaf)| leaf.column()).collect(), + None => Vec::new(), + }; + let mut keys: Vec> = vec![None; rows]; + for (row, key) in missing.iter().enumerate().filter(|(_, key)| **key != 0) { + let memo = sure[row] + && nulls.is_some_and(|nulls| nulls.as_ref().is_none_or(|n| !Bits::get(n, row))) + && presences.iter().zip(&columns).all(|(present, column)| { + !Bits::get(present, row) || Self::spotless(column, row) + }); + keys[row] = memo.then_some(*key); + sure[row] = false; + } + Some(Verdicts { + sure, + missing: keys, + }) + } +} diff --git a/core/engine/src/compiled/graph/state/exec.rs b/core/engine/src/compiled/graph/state/exec.rs new file mode 100644 index 00000000..5a65011a --- /dev/null +++ b/core/engine/src/compiled/graph/state/exec.rs @@ -0,0 +1,508 @@ +use crate::compiled::graph::data::{Col, Data}; +use crate::compiled::graph::schedule::Execute; +use crate::compiled::graph::{data, Body, CompiledGraph, Kind, NodeColumn, State, Step}; +use crate::model::{DecisionNodeKind, GraphContent}; +use crate::nodes::function::v1::{Batch, FunctionV1NodeHandler}; +use crate::nodes::function::v2::FunctionV2NodeHandler; +use crate::nodes::input::dates::DeclaredDates; +use crate::nodes::variable_json::{Guards, VariableNode}; +use crate::nodes::NodeError; +use crate::nodes::{NodeContextConfig, NodeHandlerExtensions}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::LaneRunner; +use zen_expression::Variable; +use zen_types::decision::FunctionNodeContent; + +impl CompiledGraph { + #[allow(clippy::too_many_arguments)] + pub(in crate::compiled::graph) async fn execute<'a>( + &self, + event: &Execute, + rows: &Rc<[usize]>, + inputs: &[Variable], + state: &mut State<'a>, + content: &Arc, + extensions: &NodeHandlerExtensions, + max_depth: u8, + ) { + let Some(step) = self.step_at(event.node) else { + return; + }; + let data = match step.kind { + Kind::Input => Data::plain( + rows.clone(), + rows.iter().map(|&r| inputs[r].clone()).collect(), + ), + _ => Self::input_of(state, &event.parents, rows), + }; + let (nodes, extra) = self.node_inputs( + step, + state, + &event.visible, + rows, + step.column_path(rows.len()), + ); + + if matches!(step.kind, Kind::Host(_)) { + let materialized = data.materialized(); + let batched = state.errors.len() > 1; + let replayed = state + .nesting + .completed + .and_then(|completed| completed.replay(event.node, rows)); + let results = match replayed { + None => { + Self::hosted( + step, + &materialized, + &nodes, + extensions, + max_depth, + state.nesting.iteration, + batched, + ) + .await + } + Some(replayed) => { + let missing: Vec = + (0..rows.len()).filter(|&i| replayed[i].is_none()).collect(); + let inputs: Vec = + missing.iter().map(|&i| materialized[i].clone()).collect(); + let parents: Vec> = missing + .iter() + .map(|&i| nodes.get(i).cloned().flatten()) + .collect(); + let mut fresh = match missing.is_empty() { + true => Vec::new(), + false => { + Self::hosted( + step, + &inputs, + &parents, + extensions, + max_depth, + state.nesting.iteration, + batched, + ) + .await + } + } + .into_iter(); + replayed + .into_iter() + .map(|done| match done { + Some(value) => Ok(value), + None => fresh.next().unwrap_or(Ok(Variable::Null)), + }) + .collect() + } + }; + let mut values = Vec::with_capacity(rows.len()); + for (i, result) in results.into_iter().enumerate() { + match result { + Ok(v) => values.push(v), + Err(error) => { + state.errors.fault(rows[i], error); + values.push(Variable::Null); + } + } + } + state.nodes[event.node.index()].push(Rc::new(Data::plain(rows.clone(), values.into()))); + return; + } + + let (output, failures): (Data<'a>, Vec<(usize, String)>) = match &step.kind { + Kind::Switch { .. } | Kind::Host(_) => (data, Vec::new()), + Kind::Output if !step.schema => (data, Vec::new()), + Kind::Input if !step.schema && Self::unresolved(content, &step.node) => { + let values: Col = data + .materialized() + .iter() + .map(|value| { + DeclaredDates::prepare(value, None).unwrap_or_else(|| value.clone()) + }) + .collect(); + (Data::plain(rows.clone(), values), Vec::new()) + } + Kind::Input | Kind::Output => { + let (values, failures) = self + .bounded(step, &data.materialized(), &nodes, content, extensions) + .await; + (Data::plain(rows.clone(), values.into()), failures) + } + Kind::Node { .. } => self.node(step, rows, &data, &nodes, &extra), + }; + + for (i, message) in failures { + state.errors.fail(rows[i], &step.node, message); + } + state.nodes[event.node.index()].push(Rc::new(output)); + } + + pub(in crate::compiled::graph) async fn hosted( + step: &Step, + inputs: &[Variable], + nodes: &[Option], + extensions: &NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + batched: bool, + ) -> Vec> { + if let DecisionNodeKind::DecisionNode { content } = &step.node.kind { + if let Some(results) = Self::nested( + step, content, inputs, nodes, extensions, max_depth, iteration, + ) + .await + { + return results; + } + } + let single = iteration > 0 && inputs.len() == 1; + if let ( + DecisionNodeKind::FunctionNode { + content: FunctionNodeContent::Version2(content), + }, + false, + ) = (&step.node.kind, single) + { + let config = NodeContextConfig { + max_depth, + trace: false, + ..Default::default() + }; + let inputs = inputs + .iter() + .enumerate() + .map(|(i, value)| (value.clone(), nodes.get(i).cloned().flatten())) + .collect(); + return FunctionV2NodeHandler::batch( + &step.node.id, + content, + extensions, + &config, + iteration, + inputs, + ) + .await; + } + if let DecisionNodeKind::FunctionNode { + content: FunctionNodeContent::Version1(source), + } = &step.node.kind + { + if let Some(batch) = FunctionV1NodeHandler::batch(&step.node.id, source, inputs.len()) { + return Self::scripted( + step, batch, inputs, nodes, extensions, max_depth, iteration, batched, + ) + .await; + } + } + let mut results = Vec::with_capacity(inputs.len()); + for (i, value) in inputs.iter().enumerate() { + let nodes = nodes.get(i).cloned().flatten(); + results.push( + Self::host( + step, + value.clone(), + nodes, + extensions, + max_depth, + iteration, + batched, + ) + .await, + ); + } + results + } + + #[allow(clippy::too_many_arguments)] + async fn scripted( + step: &Step, + mut batch: Batch, + inputs: &[Variable], + nodes: &[Option], + extensions: &NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + batched: bool, + ) -> Vec> { + let mut results = Vec::with_capacity(inputs.len()); + for (i, value) in inputs.iter().enumerate() { + let nodes = nodes.get(i).cloned().flatten(); + match batch.call(value, nodes.as_ref()) { + Some(result) => results.push(result), + None => results.push( + Self::host( + step, + value.clone(), + nodes, + extensions, + max_depth, + iteration, + batched, + ) + .await, + ), + } + } + results + } + + pub(in crate::compiled::graph) async fn bounded( + &self, + step: &Step, + inputs: &[Variable], + nodes: &[Option], + content: &Arc, + extensions: &NodeHandlerExtensions, + ) -> (Vec, Vec<(usize, String)>) { + let validator = Self::validator(step, content, extensions); + let mut values = Vec::with_capacity(inputs.len()); + let mut failures = Vec::new(); + for (i, value) in inputs.iter().enumerate() { + let nodes = nodes.get(i).cloned().flatten(); + if let Some((validator, schema)) = &validator { + if validator.is_valid(VariableNode::new(value, &Guards::default())) { + values.push(match step.kind { + Kind::Input => DeclaredDates::prepare(value, Some(schema)) + .unwrap_or_else(|| value.clone()), + _ => value.clone(), + }); + continue; + } + } + match self + .boundary(step, value.clone(), nodes, content, extensions) + .await + { + Ok(v) => values.push(v), + Err(e) => { + failures.push((i, e)); + values.push(Variable::Null); + } + } + } + (values, failures) + } + + pub(in crate::compiled::graph) fn rowwise<'a>( + &self, + runner: &mut LaneRunner, + step: &Step, + data: Data<'a>, + nodes: &[Option], + ) -> (Data<'a>, Vec<(usize, String)>) { + let rows: Rc<[usize]> = (0..data.len()).collect(); + if Self::foreign_input(step, &data) { + crate::compiled::census::Census::mark("walked"); + let mut failures = Vec::new(); + let values: Col = data + .materialized() + .iter() + .enumerate() + .map(|(i, value)| { + match Self::walked(step, value.clone(), nodes.get(i).cloned().flatten(), true) { + Ok(output) => output, + Err(message) => { + failures.push((i, message)); + Variable::Null + } + } + }) + .collect(); + return (Data::plain(rows, values), failures); + } + self.node_with(runner, step, &rows, &data, nodes, &[]) + } + + fn node<'a>( + &self, + step: &Step, + rows: &Rc<[usize]>, + data: &Data<'a>, + nodes: &[Option], + extra: &[NodeColumn<'a>], + ) -> (Data<'a>, Vec<(usize, String)>) { + Self::RUNNER + .with_borrow_mut(|runner| self.node_with(runner, step, rows, data, nodes, extra)) + } + + fn node_with<'a>( + &self, + runner: &mut LaneRunner, + step: &Step, + rows: &Rc<[usize]>, + data: &Data<'a>, + nodes: &[Option], + extra: &[NodeColumn<'a>], + ) -> (Data<'a>, Vec<(usize, String)>) { + let Kind::Node { body, transform } = &step.kind else { + return (Data::plain(rows.clone(), Rc::from(Vec::new())), Vec::new()); + }; + { + let wide = rows.len() > 1; + let rebase = match (&transform.input_field, &transform.base, transform.looped) { + (None, _, false) => Some(None), + (Some(_), Some(base), false) => Some(Some(base.as_ref())), + _ => None, + }; + let keyed = !matches!(body, Body::Expression { keys, .. } if keys.is_empty()); + let expression = matches!(body, Body::Expression { .. }); + let overlapping = matches!( + body, + Body::Expression { + overlapping: true, + .. + } + ); + match (rebase, &transform.output_path, wide) { + (Some(rebase), None, true) if !overlapping => { + crate::compiled::census::Census::mark("layered"); + Self::bound(step, data, nodes, extra, rebase, |bound| { + Self::layered(runner, body, transform.pass_through, data, bound, None) + }) + } + (Some(rebase), Some(path), true) if keyed && expression && !overlapping => { + crate::compiled::census::Census::mark("layered-path"); + Self::bound(step, data, nodes, extra, rebase, |bound| { + Self::layered( + runner, + body, + transform.pass_through, + data, + bound, + Some(path), + ) + }) + } + (Some(None), Some(path), true) if keyed => { + crate::compiled::census::Census::mark("placed"); + Self::bound(step, data, nodes, extra, None, |bound| { + Self::placed(runner, body, path, transform.pass_through, data, bound) + }) + } + (None, Some(path), true) + if transform.looped + && !step.nodes + && transform + .input_field + .as_ref() + .is_some_and(|(program, _)| program.path().is_some()) => + { + crate::compiled::census::Census::mark("looped"); + Self::looped(runner, step, body, transform, path, data) + } + _ => { + crate::compiled::census::Census::mark("transformed"); + let materialized = data.materialized(); + let results = + Self::transformed(runner, step, body, transform, &materialized, nodes); + let mut failures = Vec::new(); + let values: Col = results + .into_iter() + .enumerate() + .map(|(i, r)| match r { + Ok(v) => v, + Err(e) => { + failures.push((i, e)); + Variable::Null + } + }) + .collect(); + (Data::plain(rows.clone(), values), failures) + } + } + } + } + + fn foreign_input(step: &Step, data: &Data) -> bool { + let based = match &step.kind { + Kind::Node { transform, .. } if !transform.looped => transform.base.as_deref(), + _ => None, + }; + matches!( + &step.kind, + Kind::Node { + body: Body::Expression { walked: true, .. }, + .. + } + ) || matches!(&data.shape, data::Shape::Plain(values) if values.iter().any(Self::foreign)) + || Self::foreign_base(data, based) + } + + fn foreign_base(data: &Data, rebase: Option<&str>) -> bool { + let Some(base) = rebase else { + return false; + }; + let column = data.column_at(base); + (0..data.len()).any(|row| Self::foreign(&column.get(row))) + } + + pub(in crate::compiled::graph) fn immediate(step: &Step) -> bool { + match &step.kind { + Kind::Switch { .. } | Kind::Node { .. } => true, + Kind::Output => !step.schema, + Kind::Input | Kind::Host(_) => false, + } + } + + pub(in crate::compiled::graph) fn execute_now<'a>( + &self, + step: &Step, + event: &Execute, + rows: &Rc<[usize]>, + state: &mut State<'a>, + ) { + let data = Self::input_of(state, &event.parents, rows); + let foreign = Self::foreign_input(step, &data); + let (output, failures) = match &step.kind { + Kind::Node { .. } if foreign => { + let values = data.materialized(); + let nodes: Vec> = match step.nodes && state.with_nodes { + true => self + .nodes_of(state, &event.visible, rows) + .into_iter() + .map(Some) + .collect(), + false => Vec::new(), + }; + let mut failures = Vec::new(); + let outputs: Vec = values + .iter() + .enumerate() + .map(|(i, value)| { + match Self::walked( + step, + value.clone(), + nodes.get(i).cloned().flatten(), + true, + ) { + Ok(output) => output, + Err(message) => { + failures.push((i, message)); + Variable::Null + } + } + }) + .collect(); + (Data::plain(rows.clone(), outputs.into()), failures) + } + Kind::Node { .. } => { + let (nodes, extra) = self.node_inputs( + step, + state, + &event.visible, + rows, + step.column_path(rows.len()), + ); + self.node(step, rows, &data, &nodes, &extra) + } + _ => (data, Vec::new()), + }; + for (i, message) in failures { + state.errors.fail(rows[i], &step.node, message); + } + state.nodes[event.node.index()].push(Rc::new(output)); + } +} diff --git a/core/engine/src/compiled/graph/state/host.rs b/core/engine/src/compiled/graph/state/host.rs new file mode 100644 index 00000000..9c6e425f --- /dev/null +++ b/core/engine/src/compiled/graph/state/host.rs @@ -0,0 +1,505 @@ +use crate::compiled::bound::Bound; +use crate::compiled::exact::graph::Row; +use crate::compiled::graph::data::{Col, Data, Layer}; +use crate::compiled::graph::{call, schema, Body, CompiledGraph, Step}; +use crate::compiled::leaf; +use crate::compiled::leaf::Mask; +use crate::compiled::leaf::{Array, Leaf}; +use crate::compiled::table::TableOut; +use crate::decision_graph::graph::DecisionGraph; +use crate::loader::DynamicLoader; +use crate::model::{DecisionNodeKind, GraphContent}; +use crate::nodes::custom::CustomNodeHandler; +use crate::nodes::function::FunctionNodeHandler; +use crate::nodes::input::InputNodeHandler; +use crate::nodes::output::OutputNodeHandler; +use crate::nodes::validator_cache::ValidatorCache; +use crate::nodes::variable_json::{Guards, VariableJson, VariableNode}; +use crate::nodes::{NodeContextBase, NodeContextConfig, NodeHandlerExtensions}; +use crate::nodes::{NodeError, NodeResponse, NodeResult}; +use jsonschema::Validator; +use std::sync::Arc; +use zen_expression::lane::{LaneRunner, Programs}; +use zen_expression::Variable; +use zen_types::decision::{DecisionNode, InputNodeContent, OutputNodeContent}; + +impl CompiledGraph { + pub(in crate::compiled::graph) async fn validate_input( + &self, + step: &Step, + data: &Data<'_>, + nodes: &[Option], + content: &Arc, + extensions: &NodeHandlerExtensions, + ) -> Vec<(usize, String)> { + if let Some(message) = Self::failure(content, &step.node) { + return (0..data.len()).map(|i| (i, message.to_string())).collect(); + } + let mut failures = Vec::new(); + let Some((validator, schema)) = Self::validator(step, content, extensions) else { + return failures; + }; + let verdicts = + schema::ObjectSchema::cached(&schema).and_then(|columns| columns.verdicts(data)); + let doubtful: Vec<(usize, Option, Option)> = match &verdicts { + Some(verdicts) => (0..data.len()) + .filter(|&i| !verdicts.sure[i]) + .map(|i| match verdicts.missing.get(i).copied().flatten() { + Some(key) => (i, None, Some(key)), + None => (i, Some(data.materialize_row(i)), None), + }) + .collect(), + None => data + .materialized() + .iter() + .cloned() + .enumerate() + .map(|(i, value)| (i, Some(value), None)) + .collect(), + }; + let mut memo: Vec<(u64, Option)> = Vec::new(); + for (i, value, key) in doubtful { + if let Some((_, known)) = key.and_then(|key| memo.iter().find(|(k, _)| *k == key)) { + if let Some(e) = known { + failures.push((i, e.clone())); + } + continue; + } + let value = match value { + Some(value) + if validator.is_valid(VariableNode::new(&value, &Guards::default())) => + { + continue + } + Some(value) => value, + None => data.materialize_row(i), + }; + let nodes = nodes.get(i).cloned().flatten(); + let failure = self + .boundary(step, value, nodes, content, extensions) + .await + .err(); + if let Some(key) = key.filter(|_| memo.len() < 64) { + memo.push((key, failure.clone())); + } + if let Some(e) = failure { + failures.push((i, e)); + } + } + failures + } + + pub(in crate::compiled::graph) fn placed<'a>( + runner: &mut LaneRunner, + body: &Body, + path: &Arc, + pass_through: bool, + input: &Data<'a>, + bound: &Bound, + ) -> (Data<'a>, Vec<(usize, String)>) { + let count = input.rows.len(); + let mut failures = Vec::new(); + let values: Vec = match body { + Body::Expression { + program, + entries, + keys, + .. + } => { + let mut values = vec![Variable::Null; count]; + bound.many(runner, program, None, |row, result| match result { + Ok(outputs) => { + let object = Variable::empty_object(); + for (key, value) in keys.iter().zip(outputs) { + object.dot_insert(key, value); + } + values[row] = object; + } + Err((stage, _)) => failures.push(( + row, + crate::compiled::exact::Failure::expression( + entries + .get(stage) + .map(|(_, v)| v.as_ref()) + .unwrap_or_default(), + ), + )), + }); + values + } + Body::Table(table) => table + .evaluate(runner, bound) + .into_iter() + .map(|out| table.value(out)) + .collect(), + }; + let layer = Layer::new( + Arc::from([path.clone()]), + vec![Leaf::Any(values.into())], + None, + ); + let data = match pass_through { + true => input.layered(layer), + false => Data::record(&input.rows, layer, None), + }; + (data, failures) + } + + pub(in crate::compiled::graph) fn layered<'a>( + runner: &mut LaneRunner, + body: &Body, + pass_through: bool, + input: &Data<'a>, + bound: &Bound, + prefix: Option<&Arc>, + ) -> (Data<'a>, Vec<(usize, String)>) { + let rows = input.rows.clone(); + let count = rows.len(); + let mut failures = Vec::new(); + match body { + Body::Expression { + program, + entries, + keys, + .. + } => { + let mut outs = Vec::new(); + bound.export(runner, program, None, &mut outs, |row, stage, _| { + failures.push(( + row, + crate::compiled::exact::Failure::expression( + entries + .get(stage) + .map(|(_, v)| v.as_ref()) + .unwrap_or_default(), + ), + )) + }); + let keys = match prefix { + None => keys.clone(), + Some(prefix) => keys + .iter() + .map(|key| Arc::from(format!("{prefix}.{key}"))) + .collect(), + }; + let layer = Layer::new( + keys, + outs.iter_mut() + .map(|out| Leaf::typed(Array::from_output(out))) + .collect(), + None, + ); + let data = match pass_through { + true => input.layered(layer), + false => Data::record(&rows, layer, None), + }; + (data, failures) + } + Body::Table(table) if table.first_hit() => { + let (columns, present, unmatched) = table.columns(table.first(runner, bound)); + let layer = Layer::new(table.paths().clone(), columns, Some(present)); + let data = match pass_through { + true => input.layered(layer), + false => Data::record(&rows, layer, Some(unmatched.into())), + }; + (data, failures) + } + Body::Table(table) if table.collects() => { + let collected = table.first_collect(runner, bound); + let layer = Layer::new(collected.paths, collected.columns, Some(collected.present)); + let data = match pass_through { + true => input.layered(layer), + false => Data::record(&rows, layer, Some(collected.unmatched.into())), + }; + (data, failures) + } + Body::Table(table) => { + let outs = table.evaluate(runner, bound); + let first = outs + .iter() + .all(|o| matches!(o, TableOut::Leaves(..) | TableOut::Value(Variable::Null))); + match (pass_through, first) { + (true, true) => { + let paths = table.paths(); + let mut columns: Vec> = (0..paths.len()) + .map(|_| vec![Variable::Null; count]) + .collect(); + let mut present: Vec> = + (0..paths.len()).map(|_| vec![false; count]).collect(); + for (row, out) in outs.into_iter().enumerate() { + if let TableOut::Leaves(slots, values) = out { + for (&slot, value) in slots.iter().zip(values) { + columns[slot][row] = value; + present[slot][row] = true; + } + } + } + let layer = Layer::new( + paths.clone(), + columns + .into_iter() + .map(|c| Leaf::Any(Col::from(c))) + .collect(), + Some( + present + .into_iter() + .map(|p| Mask::Bits(leaf::Bits::of(count, |row| p[row]).into())) + .collect(), + ), + ); + (input.layered(layer), failures) + } + (true, false) => { + let materialized = input.materialized(); + let values: Col = outs + .into_iter() + .enumerate() + .map(|(row, out)| match table.value(out) { + output @ Variable::Object(_) => { + materialized[row].clone().merge_clone(&output) + } + output @ Variable::Array(_) => output, + _ => materialized[row].clone(), + }) + .collect(); + (Data::plain(rows, values), failures) + } + (false, _) => ( + Data::plain(rows, outs.into_iter().map(|o| table.value(o)).collect()), + failures, + ), + } + } + } + } + + pub(in crate::compiled::graph) async fn host( + step: &Step, + input: Variable, + nodes: Option, + extensions: &NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + batched: bool, + ) -> Result { + let node = &step.node; + let extensions = match &node.kind { + DecisionNodeKind::DecisionNode { .. } if batched => NodeHandlerExtensions { + function_runtime: Default::default(), + ..extensions.clone() + }, + _ => extensions.clone(), + }; + let base = NodeContextBase { + id: node.id.clone(), + name: node.name.clone(), + input, + nodes, + extensions, + iteration, + trace: None, + config: NodeContextConfig { + max_depth, + trace: false, + ..Default::default() + }, + }; + match &node.kind { + DecisionNodeKind::FunctionNode { .. } + | DecisionNodeKind::DecisionNode { .. } + | DecisionNodeKind::CustomNode { .. } + | DecisionNodeKind::ExpressionNode { .. } + | DecisionNodeKind::DecisionTableNode { .. } => { + Self::dispatch(step, base, step.shared_programs()) + .await + .map(|r| r.output) + } + _ => Ok(base.input), + } + } + + pub(in crate::compiled::graph) async fn dispatch( + step: &Step, + base: NodeContextBase, + programs: Option<&Arc>, + ) -> NodeResult { + let node = &step.node; + let trace = base.config.trace; + match &node.kind { + DecisionNodeKind::FunctionNode { content } => { + DecisionGraph::handle(base, content.clone(), FunctionNodeHandler).await + } + DecisionNodeKind::CustomNode { content } => { + DecisionGraph::handle(base, content.clone(), CustomNodeHandler).await + } + DecisionNodeKind::DecisionNode { content } => { + let call = call::Call { + key: &content.key, + extensions: &base.extensions, + max_depth: base.config.max_depth, + iteration: base.iteration, + }; + let row = Row { + id: &node.id, + input: base.input.clone(), + nodes: base.nodes.clone(), + programs: None, + trace, + }; + call.node(row, &content.transform_attributes).await + } + DecisionNodeKind::ExpressionNode { .. } + | DecisionNodeKind::DecisionTableNode { .. } => { + let index = base + .extensions + .dt_indexes + .as_ref() + .and_then(|indexes| indexes.get(&node.id)); + let row = Row { + id: &node.id, + input: base.input.clone(), + nodes: base.nodes.clone(), + programs, + trace, + }; + row.node(node, index, true).await + } + _ => Ok(NodeResponse { + output: base.input, + trace_data: None, + }), + } + } + + pub(in crate::compiled::graph) fn validator( + step: &Step, + content: &GraphContent, + extensions: &NodeHandlerExtensions, + ) -> Option<(Arc>, Arc)> { + let node = &step.node; + if Self::failure(content, node).is_some() { + return None; + } + let (schema, salt) = match content + .resolved_schemas + .as_ref() + .and_then(|r| r.get(&node.id)) + { + Some((schema, salt)) => (schema.clone(), *salt), + None => match &node.kind { + DecisionNodeKind::InputNode { content } => (content.schema.clone()?, 0), + DecisionNodeKind::OutputNode { content } => (content.schema.clone()?, 0), + _ => return None, + }, + }; + let key = ValidatorCache::key(&node.id, &node.name, salt); + let validator = extensions + .validator_cache() + .get_or_insert(key, &schema) + .ok()?; + Some((validator, schema)) + } + + fn failure<'c>(content: &'c GraphContent, node: &DecisionNode) -> Option<&'c Arc> { + content.schema_failures.as_ref()?.get(&node.id) + } + + pub(crate) async fn schemas( + &self, + content: &Arc, + loader: &DynamicLoader, + ) -> Arc { + if !self.dictionaries || content.resolved_schemas.is_some() { + return content.clone(); + } + let mut owned = (**content).clone(); + let _ = owned.resolve_schemas(loader).await; + Arc::new(owned) + } + + pub(in crate::compiled::graph) fn columnar_input( + step: &Step, + content: &GraphContent, + extensions: &NodeHandlerExtensions, + ) -> bool { + match Self::validator(step, content, extensions) { + None => !step.schema && Self::unresolved(content, &step.node), + Some(_) => true, + } + } + + pub(in crate::compiled::graph) fn unresolved( + content: &GraphContent, + node: &DecisionNode, + ) -> bool { + content + .resolved_schemas + .as_ref() + .is_none_or(|resolved| !resolved.contains_key(&node.id)) + } + + pub(in crate::compiled::graph) async fn boundary( + &self, + step: &Step, + input: Variable, + nodes: Option, + content: &Arc, + extensions: &NodeHandlerExtensions, + ) -> Result { + let node = &step.node; + let base = NodeContextBase { + id: node.id.clone(), + name: node.name.clone(), + input, + nodes, + extensions: extensions.clone(), + iteration: 0, + trace: None, + config: NodeContextConfig::default(), + }; + self.edge(step, base, content) + .await + .map(|r| r.output) + .map_err(|e| e.source.to_string()) + } + + pub(in crate::compiled::graph) async fn edge( + &self, + step: &Step, + mut base: NodeContextBase, + content: &Arc, + ) -> NodeResult { + let node = &step.node; + if let Some(message) = Self::failure(content, node) { + return base.error(message.to_string()); + } + let resolved = content + .resolved_schemas + .as_ref() + .and_then(|r| r.get(&node.id).cloned()); + if let Some((_, salt)) = &resolved { + base.config.validation_salt = *salt; + } + match &node.kind { + DecisionNodeKind::InputNode { content } => { + let content = match resolved { + Some((schema, _)) => InputNodeContent { + schema: Some(schema), + }, + None => content.clone(), + }; + DecisionGraph::handle(base, content, InputNodeHandler).await + } + DecisionNodeKind::OutputNode { content } => { + let content = match resolved { + Some((schema, _)) => OutputNodeContent { + schema: Some(schema), + }, + None => content.clone(), + }; + DecisionGraph::handle(base, content, OutputNodeHandler).await + } + _ => base.success(base.input.clone()), + } + } +} diff --git a/core/engine/src/compiled/graph/state/loops.rs b/core/engine/src/compiled/graph/state/loops.rs new file mode 100644 index 00000000..ffc1594f --- /dev/null +++ b/core/engine/src/compiled/graph/state/loops.rs @@ -0,0 +1,384 @@ +use crate::compiled::bound::Bound; +use crate::compiled::exact::graph::Row; +use crate::compiled::graph::data::{Data, Layer}; +use crate::compiled::graph::{Body, CompiledGraph, Kind, Step, Transform}; +use crate::compiled::leaf; +use crate::compiled::leaf::Mask; +use crate::compiled::leaf::{ColumnBuilder, Leaf}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{LaneProgram, LaneRunner}; +use zen_expression::{Scope, Variable}; +use zen_types::path::DotPath; + +impl CompiledGraph { + pub(in crate::compiled::graph) fn transformed( + runner: &mut LaneRunner, + step: &Step, + body: &Body, + transform: &Transform, + inputs: &[Variable], + nodes: &[Option], + ) -> Vec> { + let effective: Vec> = match &transform.input_field { + None => inputs.iter().cloned().map(Ok).collect(), + Some((program, _)) => { + let scopes: Vec = inputs + .iter() + .enumerate() + .map(|(row, i)| Self::scope(i, nodes.get(row).and_then(Option::as_ref))) + .collect(); + runner + .evaluate(program, &scopes) + .into_iter() + .map(|r| r.map_err(crate::compiled::exact::Failure::input)) + .collect() + } + }; + + let mut outputs: Vec> = match transform.looped { + false => { + let rows: Vec = (0..inputs.len()) + .filter(|&r| effective[r].is_ok()) + .collect(); + let body_inputs: Vec = rows + .iter() + .filter_map(|&r| effective[r].as_ref().ok().cloned()) + .collect(); + let body_nodes: Vec> = rows + .iter() + .map(|&r| nodes.get(r).cloned().flatten()) + .collect(); + let mut produced = + Self::items(runner, step, body, &body_inputs, &body_nodes).into_iter(); + effective + .into_iter() + .map(|e| e.and_then(|_| produced.next().unwrap_or_else(|| Ok(Variable::Null)))) + .collect() + } + true => { + let mut owners: Vec = Vec::new(); + let mut items: Vec = Vec::new(); + let mut item_nodes: Vec> = Vec::new(); + let mut shaped: Vec> = Vec::with_capacity(inputs.len()); + for (row, value) in effective.iter().enumerate() { + match value { + Err(e) => shaped.push(Err(e.clone())), + Ok(value) => match value.as_array() { + None => shaped.push(Err("Expected an array".to_string())), + Some(array) => { + let array = array.borrow(); + shaped.push(Ok(array.len())); + for item in array.iter() { + owners.push(row); + items.push(item.clone()); + item_nodes.push(nodes.get(row).cloned().flatten()); + } + } + }, + } + } + let mut produced = Self::items(runner, step, body, &items, &item_nodes).into_iter(); + let mut item_inputs = items.into_iter(); + shaped + .into_iter() + .map(|shape| { + let count = shape?; + let mut collected = Vec::with_capacity(count); + let mut failure: Option = None; + for _ in 0..count { + let output = produced.next().unwrap_or_else(|| Ok(Variable::Null)); + let item = item_inputs.next().unwrap_or(Variable::Null); + match (output, failure.is_some()) { + (_, true) => {} + (Err(e), false) => failure = Some(e), + (Ok(out), false) => { + collected.push(crate::compiled::exact::Attributes::item( + transform.pass_through, + &item, + out, + )) + } + } + } + match failure { + Some(e) => Err(e), + None => Ok(Variable::from_array(collected)), + } + }) + .collect() + } + }; + + for (row, output) in outputs.iter_mut().enumerate() { + let Ok(value) = output else { + continue; + }; + *value = crate::compiled::exact::Attributes::finish( + transform.output_path.as_deref(), + transform.pass_through, + &inputs[row], + std::mem::take(value), + ); + } + outputs + } + + pub(in crate::compiled::graph) fn looped<'a>( + runner: &mut LaneRunner, + step: &Step, + body: &Body, + transform: &Transform, + path: &Arc, + data: &Data<'a>, + ) -> (Data<'a>, Vec<(usize, String)>) { + let source = transform + .input_field + .as_ref() + .and_then(|(program, _)| program.path()) + .unwrap_or_default(); + let lists = data.subtree(source); + let mut items: Vec = Vec::new(); + let mut spans: Vec> = Vec::with_capacity(lists.len()); + let mut failures = Vec::new(); + for (row, list) in lists.iter().enumerate() { + match list.as_array() { + Some(array) => { + let start = items.len(); + items.extend(array.borrow().iter().cloned()); + spans.push(Some((start, items.len()))); + } + None => { + failures.push((row, "Expected an array".to_string())); + spans.push(None); + } + } + } + let produced = Self::items(runner, step, body, &items, &[]); + let mut values = Vec::with_capacity(spans.len()); + for (row, span) in spans.into_iter().enumerate() { + let Some((start, end)) = span else { + values.push(Variable::Null); + continue; + }; + let mut collected = Vec::with_capacity(end - start); + let mut failure = None; + for (item, output) in items[start..end].iter().zip(&produced[start..end]) { + match output { + Ok(out) => collected.push(crate::compiled::exact::Attributes::item( + transform.pass_through, + item, + out.clone(), + )), + Err(e) => { + failure = Some(e.clone()); + break; + } + } + } + match failure { + Some(e) => { + failures.push((row, e)); + values.push(Variable::Null); + } + None => values.push(Variable::from_array(collected)), + } + } + let layer = Layer::new( + Arc::from([path.clone()]), + vec![Leaf::Any(values.into())], + None, + ); + let output = match transform.pass_through { + true => data.layered(layer), + false => Data::record(&data.rows, layer, None), + }; + (output, failures) + } + + pub(in crate::compiled::graph) fn items( + runner: &mut LaneRunner, + step: &Step, + body: &Body, + inputs: &[Variable], + nodes: &[Option], + ) -> Vec> { + if inputs.iter().any(Self::foreign) { + let kept: Vec = (0..inputs.len()) + .filter(|&i| !Self::foreign(&inputs[i])) + .collect(); + let kept_inputs: Vec = kept.iter().map(|&i| inputs[i].clone()).collect(); + let kept_nodes: Vec> = kept + .iter() + .map(|&i| nodes.get(i).cloned().flatten()) + .collect(); + let mut produced = + Self::items(runner, step, body, &kept_inputs, &kept_nodes).into_iter(); + return inputs + .iter() + .enumerate() + .map(|(i, input)| match Self::foreign(input) { + true => { + Self::walked(step, input.clone(), nodes.get(i).cloned().flatten(), false) + } + false => produced.next().unwrap_or(Ok(Variable::Null)), + }) + .collect(); + } + match Self::item_data(step, body, inputs, nodes) { + Some(data) => { + let (output, failures) = Self::item_run(runner, step, body, &data); + let values = output.materialized(); + let mut results: Vec> = + values.iter().cloned().map(Ok).collect(); + for (item, message) in failures.into_iter().rev() { + if let Some(result) = results.get_mut(item) { + *result = Err(message); + } + } + results + } + None => Self::body(runner, body, inputs, nodes), + } + } + + pub(in crate::compiled::graph) fn foreign(value: &Variable) -> bool { + !matches!(value, Variable::Null | Variable::Object(_)) + } + + pub(in crate::compiled::graph) fn walked( + step: &Step, + input: Variable, + nodes: Option, + transforms: bool, + ) -> Result { + let row = Row { + id: &step.node.id, + input, + nodes, + programs: step.shared_programs(), + trace: false, + }; + row.now(&step.node, None, transforms) + .map(|response| response.output) + .map_err(|error| error.source.to_string()) + } + + pub(in crate::compiled::graph) fn item_keys(step: &Step, body: &Body) -> Option>> { + if step.root + || step.dynamic + || matches!(&step.kind, Kind::Node { transform, .. } if transform.base.is_some()) + { + return None; + } + let programs: Vec<&LaneProgram> = match body { + Body::Expression { program, .. } => vec![program], + Body::Table(table) => table.programs(), + }; + let mut keys: Vec> = Vec::new(); + for program in &programs { + let unary = matches!(program.kind(), zen_expression::ExpressionKind::Unary); + for key in program.program().site_keys.iter() { + let key = key.as_deref()?; + match key.starts_with('$') { + true if unary && (key == "$" || key.starts_with("$.")) => {} + true => return None, + false if !keys.iter().any(|k| k.as_ref() == key) => keys.push(Arc::from(key)), + false => {} + } + } + } + let overlapping = keys + .iter() + .any(|a| keys.iter().any(|b| DotPath::under(b, a))); + (!overlapping).then_some(keys) + } + + pub(in crate::compiled::graph) fn item_run<'a>( + runner: &mut LaneRunner, + step: &Step, + body: &Body, + data: &Data<'a>, + ) -> (Data<'a>, Vec<(usize, String)>) { + Self::bound(step, data, &[], &[], None, |bound| { + Self::layered(runner, body, false, data, bound, None) + }) + } + + fn item_data<'a>( + step: &Step, + body: &Body, + inputs: &[Variable], + nodes: &[Option], + ) -> Option> { + if inputs.len() < 2 || nodes.iter().any(Option::is_some) { + return None; + } + let keys = Self::item_keys(step, body)?; + let mut leaves = Vec::with_capacity(keys.len()); + let mut present = Vec::with_capacity(keys.len()); + for key in &keys { + let mut builder = ColumnBuilder::with_capacity(inputs.len()); + let mut mask = Vec::with_capacity(inputs.len()); + for item in inputs { + let value = Data::lookup(item, key); + mask.push(value.is_some()); + builder.push_variable(value.unwrap_or(Variable::Null)); + } + leaves.push(Leaf::typed(builder.finish())); + present.push(Mask::Bits( + leaf::Bits::of(mask.len(), |row| mask[row]).into(), + )); + } + let rows: Rc<[usize]> = (0..inputs.len()).collect(); + Some(Data::record( + &rows, + Layer::new(keys.into(), leaves, Some(present)), + None, + )) + } + + fn body( + runner: &mut LaneRunner, + body: &Body, + inputs: &[Variable], + nodes: &[Option], + ) -> Vec> { + let scopes: Vec = inputs + .iter() + .enumerate() + .map(|(row, i)| Self::scope(i, nodes.get(row).and_then(Option::as_ref))) + .collect(); + match body { + Body::Expression { + program, entries, .. + } => { + let mut out: Vec> = vec![Ok(Variable::Null); scopes.len()]; + runner.evaluate_many(program, &scopes, None, |row, result| { + out[row] = match result { + Some(Ok(values)) => { + let object = Variable::empty_object(); + for ((key, _), value) in entries.iter().zip(values) { + object.dot_insert(key, value); + } + Ok(object) + } + Some(Err((stage, _))) => Err(crate::compiled::exact::Failure::expression( + entries + .get(stage) + .map(|(_, v)| v.as_ref()) + .unwrap_or_default(), + )), + None => Ok(Variable::Null), + }; + }); + out + } + Body::Table(table) => table + .evaluate(runner, &Bound::plain(scopes)) + .into_iter() + .map(|o| Ok(table.value(o))) + .collect(), + } + } +} diff --git a/core/engine/src/compiled/graph/state/mod.rs b/core/engine/src/compiled/graph/state/mod.rs new file mode 100644 index 00000000..c65f8b6f --- /dev/null +++ b/core/engine/src/compiled/graph/state/mod.rs @@ -0,0 +1,576 @@ +mod exec; +mod host; +mod loops; + +use crate::compiled::bound::{Bound, Scopes}; +use crate::compiled::graph::data::{Col, Data}; +use crate::compiled::graph::errors::RowErrors; +use crate::compiled::graph::schedule::{End, Outcome, Replay, Segment}; +use crate::compiled::graph::step::StaticRead; +use crate::compiled::graph::{data, CompiledGraph, Condition, Hit, Kind, Step}; +use crate::compiled::leaf::{Array, Leaf}; +use crate::decision_graph::cleaner::VariableCleaner; +use crate::decision_graph::walker::GraphWalker; +use crate::model::GraphContent; +use crate::nodes::NodeError; +use crate::nodes::NodeHandlerExtensions; +use crate::{EvaluationError, ZEN_CONFIG}; +use petgraph::prelude::NodeIndex; +use std::rc::Rc; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use zen_expression::lane::{Binding, Columns}; +use zen_expression::{Scope, Variable}; +use zen_types::symbol::Symbol; + +pub(super) type NodeColumn<'a> = (Arc, Leaf<'a>); + +pub(in crate::compiled::graph) struct Host<'r> { + pub(in crate::compiled::graph) content: &'r Arc, + pub(in crate::compiled::graph) extensions: &'r NodeHandlerExtensions, + pub(in crate::compiled::graph) max_depth: u8, +} + +pub(crate) struct State<'a> { + nodes: Vec>>>, + pub(crate) errors: RowErrors>, + pub(in crate::compiled::graph) results: Vec>, + nesting: Nesting<'a>, + with_nodes: bool, +} + +#[derive(Clone, Copy, Default)] +pub(crate) struct Nesting<'a> { + pub(in crate::compiled::graph) parents: Option<&'a [Option]>, + pub(in crate::compiled::graph) iteration: u8, + pub(in crate::compiled::graph) completed: Option<&'a Completed>, +} + +#[derive(Default)] +pub(in crate::compiled::graph) struct Completed { + nodes: Vec<(NodeIndex, Vec>)>, +} + +impl Completed { + pub(in crate::compiled::graph) fn record( + &mut self, + node: NodeIndex, + rows: usize, + at: &[usize], + results: &[Result], + ) { + let index = match self.nodes.iter().position(|(n, _)| *n == node) { + Some(index) => index, + None => { + self.nodes.push((node, vec![None; rows])); + self.nodes.len() - 1 + } + }; + let slots = &mut self.nodes[index].1; + for (result, &row) in results.iter().zip(at) { + if let (Ok(value), Some(slot)) = (result, slots.get_mut(row)) { + *slot = Some(value.clone()); + } + } + } + + pub(in crate::compiled::graph) fn subset(&self, rows: &[usize]) -> Completed { + Completed { + nodes: self + .nodes + .iter() + .map(|(node, slots)| { + let picked = rows + .iter() + .map(|&row| slots.get(row).cloned().flatten()) + .collect(); + (*node, picked) + }) + .collect(), + } + } + + pub(in crate::compiled::graph) fn replay( + &self, + node: NodeIndex, + rows: &[usize], + ) -> Option>> { + let (_, slots) = self.nodes.iter().find(|(n, _)| *n == node)?; + Some( + rows.iter() + .map(|&row| slots.get(row).cloned().flatten()) + .collect(), + ) + } +} + +impl CompiledGraph { + pub(in crate::compiled::graph) fn child( + &self, + segment: &Segment, + outcome: Outcome, + ) -> Arc { + let End::Switch { children, .. } = &segment.end else { + return self.root.clone(); + }; + children.get(&outcome, || { + let mut path = segment.path.to_vec(); + path.push(outcome.clone()); + Arc::new(Replay::new(&self.graph).segment(&path)) + }) + } + + fn node_columns<'a>( + &self, + step: &Step, + state: &State<'a>, + visible: &[NodeIndex], + rows: &Rc<[usize]>, + ) -> Vec> { + let Some(statics) = &step.statics else { + return Vec::new(); + }; + statics + .iter() + .map(|StaticRead { key, name, path }| { + let source = visible + .iter() + .rev() + .filter(|_| state.with_nodes) + .find(|nid| { + self.step_at(**nid) + .is_some_and(|s| s.node.name.as_ref() == name.as_ref()) + }) + .and_then(|nid| state.nodes.get(nid.index())) + .filter(|pieces| !pieces.is_empty()) + .map(|pieces| Data::gather(pieces, rows)); + let leaf = match source { + Some(data) if path.is_empty() => Leaf::Any(data.materialized()), + Some(data) => data.column_at(path), + None => Leaf::nulls(rows.len()), + }; + (key.clone(), leaf) + }) + .collect() + } + + pub(in crate::compiled::graph) fn step_at(&self, nid: NodeIndex) -> Option<&Step> { + self.steps.get(nid.index())?.as_ref() + } + + fn input_of<'a>(state: &State<'a>, parents: &[NodeIndex], rows: &Rc<[usize]>) -> Data<'a> { + let gathered: Vec> = parents + .iter() + .filter_map(|p| { + let pieces = state.nodes.get(p.index())?; + (!pieces.is_empty()).then(|| Data::gather(pieces, rows)) + }) + .collect(); + Data::merged(rows, gathered) + } + + fn nodes_of(&self, state: &State, visible: &[NodeIndex], rows: &Rc<[usize]>) -> Vec { + let columns: Vec<(Arc, Col)> = visible + .iter() + .filter_map(|nid| { + let step = self.step_at(*nid)?; + let pieces = state + .nodes + .get(nid.index()) + .filter(|pieces| !pieces.is_empty())?; + let column = Data::gather(pieces, rows).materialized(); + let column = match (&step.kind, state.nesting.parents) { + (Kind::Input, Some(parents)) => column + .iter() + .zip(rows.iter()) + .map(|(value, &row)| match parents.get(row).cloned().flatten() { + Some(parent) => { + let view = value.depth_clone(1); + view.dot_insert(Variable::nodes_key().as_ref(), parent); + view + } + None => value.clone(), + }) + .collect(), + _ => column, + }; + Some((step.node.name.clone(), column)) + }) + .collect(); + (0..rows.len()) + .map(|row| { + let object = Variable::empty_object(); + if let Variable::Object(map) = &object { + let mut map = map.borrow_mut(); + for (name, column) in &columns { + map.insert(name.as_ref().into(), column[row].clone()); + } + } + object + }) + .collect() + } + + pub(in crate::compiled::graph) fn scope(input: &Variable, nodes: Option<&Variable>) -> Scope { + let mut scope = Scope::new(input.clone()); + if let Some(nodes) = nodes { + scope.set_local(Variable::nodes_key(), nodes.clone()); + } + scope + } + + pub(in crate::compiled::graph) async fn run<'a>( + &self, + host: Host<'_>, + inputs: &[Variable], + nesting: Nesting<'a>, + ) -> State<'a> { + let Host { + content, + extensions, + max_depth, + } = host; + let count = inputs.len(); + let mut state = State { + nodes: vec![Vec::new(); self.steps.len()], + errors: RowErrors::new(count), + results: vec![None; count], + with_nodes: ZEN_CONFIG.nodes_in_context.load(Ordering::Relaxed), + nesting, + }; + if nesting.iteration >= max_depth { + state + .errors + .fill(|| Box::new(EvaluationError::DepthLimitExceeded)); + return state; + } + let mut stack: Vec<(Arc, Rc<[usize]>)> = + vec![(self.root.clone(), (0..count).collect())]; + while let Some((segment, mut rows)) = stack.pop() { + for event in segment.events.iter() { + rows = state.errors.live(&rows); + if rows.is_empty() { + break; + } + match self + .step_at(event.node) + .filter(|step| Self::immediate(step)) + { + Some(step) => self.execute_now(step, event, &rows, &mut state), + None => { + self.execute( + event, &rows, inputs, &mut state, content, extensions, max_depth, + ) + .await + } + } + } + rows = state.errors.live(&rows); + if rows.is_empty() { + continue; + } + match &segment.end { + End::Finish(ending) => { + let columns: Vec = ending + .iter() + .filter_map(|nid| { + let pieces = state.nodes.get(nid.index())?; + (!pieces.is_empty()).then(|| Data::gather(pieces, &rows).materialized()) + }) + .collect(); + for (i, &row) in rows.iter().enumerate() { + let result = match columns.as_slice() { + [single] => Self::ending(&single[i]), + _ => GraphWalker::merge_ending(columns.iter().map(|c| &c[i])), + }; + if state.nesting.parents.is_none() { + VariableCleaner::new().clean(&result); + } + state.results[row] = Some(result); + } + } + End::Switch { + node, + parents, + visible, + .. + } => { + let groups = self.switch(*node, parents, visible, &rows, &state); + for (outcome, members) in groups.into_iter().rev() { + let members: Rc<[usize]> = match members.len() == rows.len() { + true => rows.clone(), + false => members.into(), + }; + stack.push((self.child(&segment, outcome), members)); + } + } + } + } + state + } + + fn ending(value: &Variable) -> Variable { + if let Variable::Object(map) = value { + if Rc::strong_count(map) == 1 && map.borrow().shape().is_some() { + let nulls: Vec = map + .borrow() + .iter() + .filter(|(_, v)| matches!(v, Variable::Null)) + .map(|(k, _)| k.clone()) + .collect(); + let mut map = map.borrow_mut(); + for key in &nulls { + map.remove(key); + } + return value.clone(); + } + } + GraphWalker::merge_ending(std::iter::once(value)) + } + + fn node_inputs<'a>( + &self, + step: &Step, + state: &State<'a>, + visible: &[NodeIndex], + rows: &Rc<[usize]>, + columnar: bool, + ) -> (Vec>, Vec>) { + match ( + step.nodes, + columnar && step.statics.is_some() && state.nesting.parents.is_none(), + ) { + (false, _) => (Vec::new(), Vec::new()), + (true, true) => (Vec::new(), self.node_columns(step, state, visible, rows)), + (true, false) => match state.with_nodes { + true => ( + self.nodes_of(state, visible, rows) + .into_iter() + .map(Some) + .collect(), + Vec::new(), + ), + false => (Vec::new(), Vec::new()), + }, + } + } + + fn whole(step: &Step, data: &Data, rebase: Option<&str>) -> bool { + let leaves = data.leaves(); + if leaves.is_empty() { + return false; + } + (step.root && rebase.is_none()) + || step.dynamic + || leaves.iter().any(|(k, _)| { + k.as_ref() == "$" || k.as_ref() == "$nodes" || k.starts_with("$nodes.") + }) + } + + fn partials<'a>(step: &Step, data: &Data<'a>) -> Vec> { + let mut out: Vec = Vec::new(); + for path in step.sites.iter().flatten() { + if data.binding(path).1 && !out.iter().any(|(p, _)| p == path) { + out.push((path.clone(), data.partial(path))); + } + } + out + } + + fn bound<'a, R>( + step: &Step, + data: &Data<'a>, + nodes: &[Option], + extra: &[NodeColumn<'a>], + rebase: Option<&str>, + f: impl FnOnce(&Bound) -> R, + ) -> R { + let with_nodes = |scope: Scope, row: usize| match nodes.get(row).cloned().flatten() { + None => scope, + Some(n) => { + let mut scope = scope; + scope.set_local(Variable::nodes_key(), n.clone()); + scope + } + }; + let root = |values: Col| -> Col { + match rebase { + None => values, + Some(base) => values + .iter() + .map(|v| Data::lookup(v, base).unwrap_or(Variable::Null)) + .collect(), + } + }; + if Self::whole(step, data, rebase) { + crate::compiled::census::Census::mark("whole"); + let whole = match rebase { + None => data.materialized(), + Some(base) => data.subtree(base), + }; + let scopes = whole + .iter() + .enumerate() + .map(|(row, v)| with_nodes(Scope::new(v.clone()), row)) + .collect(); + return f(&Bound::plain(scopes)); + } + let blank = nodes.iter().all(Option::is_none) + && matches!(&data.shape, data::Shape::Patched { base: None, .. }); + let scopes = match blank { + true => Bound::blank(data.len()), + false => Scopes::Owned( + root(data.base()) + .iter() + .enumerate() + .map(|(row, v)| with_nodes(Scope::new(v.clone()), row)) + .collect(), + ), + }; + let leaves = data.leaves(); + let mut slots: Vec> = vec![None; leaves.len()]; + let mut columns = Columns::new(data.len()); + for path in step.sites.iter().flatten() { + if let Binding::Column(index) = data.binding(path).0 { + if let (Some(slot @ None), Some((leaf, column))) = + (slots.get_mut(index), leaves.get(index)) + { + *slot = Some(columns.columns.len()); + columns = columns.column(leaf.as_ref(), column.column()); + } + } + } + let partials = Self::partials(step, data); + let offset = columns.columns.len(); + for (path, leaf) in extra.iter().chain(partials.iter()) { + columns = columns.column(path.as_ref(), leaf.column()); + } + let names: Vec> = extra + .iter() + .chain(partials.iter()) + .map(|(p, _)| p.clone()) + .collect(); + let bound = Bound { + scopes, + columns, + bind: Box::new(move |key: &str| { + let rebased = rebase.and_then(|base| Self::rebased(base, key)); + let path = rebased.as_deref().unwrap_or(key); + if let Some(at) = names.iter().position(|p| p.as_ref() == path) { + return Binding::Column(offset + at); + } + match data.binding(path).0 { + Binding::Column(index) => match slots.get(index).copied().flatten() { + Some(slot) => Binding::Column(slot), + None => Binding::Row, + }, + other => other, + } + }), + }; + f(&bound) + } + + fn switch( + &self, + node: NodeIndex, + parents: &[NodeIndex], + visible: &[NodeIndex], + rows: &Rc<[usize]>, + state: &State<'_>, + ) -> Vec<(Outcome, Vec)> { + let Some( + step @ Step { + kind: Kind::Switch { first, conditions }, + .. + }, + ) = self.step_at(node) + else { + return vec![(Outcome::from(Vec::new()), rows.to_vec())]; + }; + let data = Self::input_of(state, parents, rows); + let (nodes, extra) = self.node_inputs(step, state, visible, rows, true); + let hits: Vec = Self::RUNNER.with_borrow_mut(|runner| { + Self::bound(step, &data, &nodes, &extra, None, |bound| { + conditions + .iter() + .map(|(_, condition)| match condition { + Condition::Program(program) => { + let p = program.program(); + let rows = bound.rows(); + let uniform = rows > 1 + && !p.opaque() + && p.stable() + && p.site_keys.iter().all(|key| { + key.as_deref() + .is_some_and(|key| (bound.bind)(key) == Binding::Absent) + }); + let mut outs = Vec::new(); + let subset = [0usize]; + bound.export( + runner, + program, + uniform.then_some(&subset[..]), + &mut outs, + |_, _, _| {}, + ); + match ( + outs.first_mut() + .map(|out| Leaf::typed(Array::from_output(out))), + uniform, + ) { + (Some(column), true) => Hit::Uniform(column.truthy(0)), + (Some(column), false) => Hit::Rows(column.truths(rows)), + (None, _) => Hit::Uniform(false), + } + } + Condition::Always => Hit::Uniform(true), + Condition::Invalid(_) => Hit::Uniform(false), + }) + .collect() + }) + }); + let words = conditions.len().div_ceil(64).max(1); + let mut groups: Vec<(Vec, Vec)> = Vec::new(); + let mut key = vec![0u64; words]; + let uniform = hits.iter().all(|hit| matches!(hit, Hit::Uniform(_))); + let lanes = match uniform { + true => rows.len().min(1), + false => rows.len(), + }; + for (lane, &row) in rows.iter().enumerate().take(lanes) { + key.iter_mut().for_each(|w| *w = 0); + for (index, hit) in hits.iter().enumerate() { + let on = match hit { + Hit::Uniform(on) => *on, + Hit::Rows(truths) => truths[lane >> 6] >> (lane & 63) & 1 == 1, + }; + if on { + key[index / 64] |= 1 << (index % 64); + if *first { + break; + } + } + } + match groups.iter_mut().find(|(k, _)| *k == key) { + Some((_, members)) => members.push(row), + None => groups.push((key.clone(), vec![row])), + } + } + if let ([(_, members)], true) = (groups.as_mut_slice(), uniform) { + *members = rows.to_vec(); + } + groups + .into_iter() + .map(|(key, members)| { + let valid: Vec> = conditions + .iter() + .enumerate() + .filter(|(index, _)| key[index / 64] >> (index % 64) & 1 == 1) + .map(|(_, (id, _))| id.clone()) + .collect(); + (Outcome::from(valid), members) + }) + .collect() + } +} diff --git a/core/engine/src/compiled/graph/step.rs b/core/engine/src/compiled/graph/step.rs new file mode 100644 index 00000000..e4b5accc --- /dev/null +++ b/core/engine/src/compiled/graph/step.rs @@ -0,0 +1,554 @@ +use crate::compiled::graph::schedule::Replay; +use crate::compiled::graph::{CompiledGraph, Invalid}; +use crate::compiled::table::{Table, TableIr}; +use crate::decision_graph::graph::DecisionGraph; +use crate::decision_graph::schema_dict; +use crate::model::{DecisionNodeKind, GraphContent}; +use std::sync::{Arc, OnceLock}; +use zen_expression::lane::{LaneProgram, Programs, SourceInfo}; +use zen_expression::ExpressionKind; +use zen_types::decision::{ + DecisionNode, DecisionTableContent, ExpressionNodeContent, SwitchStatementHitPolicy, + TransformAttributes, TransformExecutionMode, +}; +use zen_types::path::DotPath; + +pub(super) enum Body { + Expression { + program: Box, + empty: Box<[bool]>, + entries: Box<[(Arc, Arc)]>, + fragments: Box<[Arc]>, + overlapping: bool, + walked: bool, + keys: Arc<[Arc]>, + }, + Table(Box), +} + +pub(super) enum Hit { + Uniform(bool), + Rows(Vec), +} + +pub(super) struct Transform { + pub(super) input_field: Option<(LaneProgram, Arc)>, + pub(super) base: Option>, + pub(super) looped: bool, + pub(super) output_path: Option>, + pub(super) pass_through: bool, +} + +pub(super) enum Kind { + Input, + Output, + Switch { + first: bool, + conditions: Box<[(Arc, Condition)]>, + }, + Node { + body: Body, + transform: Box, + }, + Host(Option>), +} + +pub(super) enum Condition { + Always, + Invalid(Arc), + Program(Box), +} + +pub(super) struct Step { + pub(super) node: Arc, + pub(super) kind: Kind, + pub(super) nodes: bool, + pub(super) statics: Option>, + pub(super) root: bool, + pub(super) schema: bool, + pub(super) sites: Vec>>, + pub(super) dynamic: bool, + eager: bool, + programs: OnceLock>, +} + +pub(super) struct StaticRead { + pub(super) key: Arc, + pub(super) name: Arc, + pub(super) path: Arc, +} + +impl Step { + pub(super) fn column_path(&self, rows: usize) -> bool { + match &self.kind { + Kind::Node { body, transform } => { + (transform.input_field.is_none() || transform.base.is_some()) + && !transform.looped + && rows > 1 + && !(transform.output_path.is_some() + && matches!(body, Body::Expression { keys, .. } if keys.is_empty())) + } + _ => false, + } + } + + pub(super) fn shared_programs(&self) -> Option<&Arc> { + self.eager.then(|| self.programs()) + } + + pub(super) fn programs(&self) -> &Arc { + self.programs.get_or_init(|| { + let mut sources: Vec<(&str, ExpressionKind)> = Vec::new(); + match &self.node.kind { + DecisionNodeKind::ExpressionNode { content } => { + sources.extend( + content + .expressions + .iter() + .filter(|e| !e.key.is_empty() && !e.value.is_empty()) + .map(|e| (e.value.as_ref(), ExpressionKind::Standard)), + ); + sources.extend( + content + .transform_attributes + .input_field + .iter() + .map(|f| (f.as_ref(), ExpressionKind::Standard)), + ); + } + DecisionNodeKind::DecisionTableNode { content } => { + for rule in content.rules.iter() { + for input in content.inputs.iter() { + if let Some(cell) = rule.get(&input.id).filter(|c| !c.is_empty()) { + let kind = match input.field.is_some() { + true => ExpressionKind::Unary, + false => ExpressionKind::Standard, + }; + sources.push((cell.as_ref(), kind)); + } + } + for output in content.outputs.iter() { + if let Some(cell) = rule.get(&output.id).filter(|c| !c.is_empty()) { + sources.push((cell.as_ref(), ExpressionKind::Standard)); + } + } + } + sources.extend( + content + .inputs + .iter() + .filter_map(|i| i.field.as_deref()) + .map(|f| (f, ExpressionKind::Standard)), + ); + sources.extend( + content + .transform_attributes + .input_field + .iter() + .map(|f| (f.as_ref(), ExpressionKind::Standard)), + ); + } + DecisionNodeKind::SwitchNode { content } => { + sources.extend( + content + .statements + .iter() + .filter(|s| !s.condition.is_empty()) + .map(|s| (s.condition.as_ref(), ExpressionKind::Standard)), + ); + } + _ => {} + } + Arc::new(Programs::compile(sources)) + }) + } +} + +impl Step { + pub(super) fn label(&self) -> &'static str { + match &self.node.kind { + DecisionNodeKind::InputNode { .. } => "input", + DecisionNodeKind::OutputNode { .. } => "output", + DecisionNodeKind::SwitchNode { .. } => "switch", + DecisionNodeKind::ExpressionNode { .. } => "expression", + DecisionNodeKind::DecisionTableNode { .. } => "table", + DecisionNodeKind::FunctionNode { .. } => "function", + DecisionNodeKind::DecisionNode { .. } => "decision", + DecisionNodeKind::CustomNode { .. } => "custom", + } + } +} + +impl CompiledGraph { + pub(super) fn compile(content: &GraphContent, eager: bool) -> Result { + crate::compiled::switches::SWITCHES.compiled(); + let graph = DecisionGraph::build_graph(content).map_err(Invalid::Build)?; + DecisionGraph::validate_graph(&graph).map_err(Invalid::Validation)?; + + let mut dictionaries = false; + let mut steps: Vec> = Vec::new(); + for nid in graph.node_indices() { + let node = graph[nid].clone(); + let step = Self::step(&node, &mut dictionaries, eager); + let index = nid.index(); + if steps.len() <= index { + steps.resize_with(index + 1, || None); + } + steps[index] = Some(step); + } + + let root = Arc::new(Replay::new(&graph).segment(&[])); + Ok(Self { + graph, + steps, + root, + dictionaries, + plan: OnceLock::new(), + census: crate::compiled::census::Census::id(), + }) + } + + fn transform(attributes: &TransformAttributes) -> Result<(Transform, Vec>), String> { + let input_field = attributes + .input_field + .as_ref() + .map(|f| { + LaneProgram::standard(f) + .map(|p| (p, f.clone())) + .map_err(|e| e.to_string()) + }) + .transpose()?; + let looped = matches!(attributes.execution_mode, TransformExecutionMode::Loop); + let base = input_field + .as_ref() + .filter(|_| !looped) + .and_then(|(program, _)| program.path().map(Arc::from)); + Ok(( + Transform { + input_field, + base, + looped, + output_path: attributes.output_path.clone(), + pass_through: attributes.pass_through, + }, + attributes.input_field.iter().cloned().collect(), + )) + } + + fn expression_kind( + content: &ExpressionNodeContent, + sources: &mut Vec>, + ) -> Result { + let entries: Box<[(Arc, Arc)]> = content + .expressions + .iter() + .filter(|e| !e.key.is_empty() && !e.value.is_empty()) + .map(|e| (e.key.clone(), e.value.clone())) + .collect(); + sources.extend(entries.iter().map(|(_, v)| v.clone())); + let opaque = entries.iter().any(|(_, v)| { + v.match_indices('$').any(|(at, _)| { + let rest = &v[at + 1..]; + !rest.starts_with("nodes") && !rest.starts_with('.') && !rest.starts_with('{') + }) + }); + let overlapping = entries + .iter() + .any(|(key, _)| key.split('.').any(str::is_empty)) + || entries.iter().enumerate().any(|(i, (a, _))| { + entries + .iter() + .skip(i + 1) + .any(|(b, _)| DotPath::overlaps(a, b)) + }); + let walked = overlapping && entries.iter().any(|(_, source)| source.contains('$')); + let mut expanded: Vec<(Arc, Arc, Arc)> = Vec::with_capacity(entries.len()); + for (key, source) in entries.iter() { + let read = format!("$.{}", key.split('.').next().unwrap_or_default()); + let flat = + !opaque && !overlapping && !entries.iter().any(|(_, v)| v.contains(read.as_str())); + match flat { + true => Self::expand(key, source, source, &mut expanded), + false => expanded.push((key.clone(), source.clone(), source.clone())), + } + } + let refs: Vec<(&str, &str)> = expanded + .iter() + .map(|(k, _, v)| (k.as_ref(), v.as_ref())) + .collect(); + let program = LaneProgram::compile_many(&refs, true).map_err(|e| e.to_string())?; + let empty: Box<[bool]> = expanded + .iter() + .map(|(_, _, fragment)| fragment.trim() == "{}") + .collect(); + let fragments: Box<[Arc]> = expanded + .iter() + .map(|(_, _, fragment)| fragment.clone()) + .collect(); + let entries: Box<[(Arc, Arc)]> = expanded + .into_iter() + .map(|(key, source, _)| (key, source)) + .collect(); + let (transform, extra) = Self::transform(&content.transform_attributes)?; + sources.extend(extra); + Ok(Kind::Node { + transform: Box::new(transform), + body: Body::Expression { + program: Box::new(program), + keys: entries.iter().map(|(k, _)| k.clone()).collect(), + entries, + fragments, + empty, + overlapping, + walked, + }, + }) + } + + fn table_kind( + content: &DecisionTableContent, + sources: &mut Vec>, + cells: &mut Vec>, + ) -> Result { + for rule in content.rules.iter() { + for input in content.inputs.iter() { + if let Some(cell) = rule.get(&input.id) { + match input.field.is_some() { + true => cells.push(cell.clone()), + false => sources.push(cell.clone()), + } + } + } + for output in content.outputs.iter() { + sources.extend(rule.get(&output.id).cloned()); + } + } + sources.extend(content.inputs.iter().filter_map(|i| i.field.clone())); + let table = Table::compile(TableIr::graph(content))?; + let (transform, extra) = Self::transform(&content.transform_attributes)?; + sources.extend(extra); + Ok(Kind::Node { + body: Body::Table(Box::new(table)), + transform: Box::new(transform), + }) + } + + fn step(node: &Arc, dictionaries: &mut bool, eager: bool) -> Step { + let mut sources: Vec> = Vec::new(); + let mut cells: Vec> = Vec::new(); + let kind = match &node.kind { + DecisionNodeKind::InputNode { content } => { + *dictionaries |= content + .schema + .as_deref() + .is_some_and(schema_dict::schema_references_dictionary); + Kind::Input + } + DecisionNodeKind::OutputNode { content } => { + *dictionaries |= content + .schema + .as_deref() + .is_some_and(schema_dict::schema_references_dictionary); + Kind::Output + } + DecisionNodeKind::SwitchNode { content } => { + let conditions = content + .statements + .iter() + .map(|s| { + sources.push(s.condition.clone()); + let condition = match s.condition.is_empty() { + true => Condition::Always, + false => LaneProgram::standard(&s.condition) + .map(|p| Condition::Program(Box::new(p))) + .unwrap_or_else(|e| Condition::Invalid(Arc::from(e.to_string()))), + }; + (s.id.clone(), condition) + }) + .collect(); + Kind::Switch { + first: matches!(content.hit_policy, SwitchStatementHitPolicy::First), + conditions, + } + } + DecisionNodeKind::ExpressionNode { .. } + | DecisionNodeKind::DecisionTableNode { .. } + if !eager => + { + Kind::Host(None) + } + DecisionNodeKind::ExpressionNode { content } => { + Self::expression_kind(content, &mut sources) + .unwrap_or_else(|why| Kind::Host(Some(Arc::from(why)))) + } + DecisionNodeKind::DecisionTableNode { content } => { + Self::table_kind(content, &mut sources, &mut cells) + .unwrap_or_else(|why| Kind::Host(Some(Arc::from(why)))) + } + DecisionNodeKind::FunctionNode { .. } + | DecisionNodeKind::DecisionNode { .. } + | DecisionNodeKind::CustomNode { .. } => Kind::Host(None), + }; + let mut kind = kind; + if let Kind::Node { body, transform } = &mut kind { + if let Some(base) = transform.base.clone() { + let mappable = match &*body { + Body::Expression { program, .. } => program + .program() + .site_keys + .iter() + .flatten() + .all(|key| Self::rebased(&base, key).is_some()), + Body::Table(_) => false, + }; + if !mappable { + transform.base = None; + } + } + } + let mut programs: Vec<&LaneProgram> = Vec::new(); + match &kind { + Kind::Switch { conditions, .. } => { + programs.extend(conditions.iter().filter_map(|(_, c)| match c { + Condition::Program(p) => Some(p.as_ref()), + _ => None, + })) + } + Kind::Node { body, transform } => { + match body { + Body::Expression { program, .. } => programs.push(program), + Body::Table(table) => programs.extend(table.programs()), + } + programs.extend(transform.input_field.iter().map(|(p, _)| p)); + } + Kind::Input | Kind::Output | Kind::Host(_) => {} + } + let base = match &kind { + Kind::Node { transform, .. } => transform.base.clone(), + _ => None, + }; + let input_sites = match &kind { + Kind::Node { transform, .. } => transform.input_field.iter().count(), + _ => 0, + }; + let body_programs = programs.len() - input_sites; + let programs = match base { + Some(_) => &programs[..body_programs], + None => &programs[..], + }; + let sites: Vec>> = programs + .iter() + .enumerate() + .flat_map(|(index, p)| { + let base = base.as_deref().filter(|_| index < body_programs); + p.program().site_keys.iter().map(move |k| { + k.as_deref().map(|key| match base { + Some(base) => Self::rebased(base, key).unwrap_or_else(|| Arc::from(key)), + None => Arc::from(key), + }) + }) + }) + .collect(); + let dynamic = programs + .iter() + .any(|p| p.program().writes_env || p.program().chain || p.program().opaque()); + let schema = match &node.kind { + DecisionNodeKind::InputNode { content } => content.schema.is_some(), + DecisionNodeKind::OutputNode { content } => content.schema.is_some(), + _ => false, + }; + Step { + node: node.clone(), + eager, + programs: OnceLock::new(), + statics: match &kind { + Kind::Host(_) => None, + Kind::Node { + body: Body::Table(_), + .. + } => None, + _ if sources.iter().any(|s| SourceInfo::reads_root(s)) => None, + _ => Self::statics(&sites), + }, + nodes: matches!(kind, Kind::Host(_)) + || sources.iter().any(|s| SourceInfo::reads_nodes(s)) + || cells.iter().any(|s| SourceInfo::reads_nodes_unary(s)), + root: match &kind { + Kind::Node { + body: Body::Expression { program, .. }, + transform, + } => { + program + .program() + .keys + .iter() + .any(|k| k == "$" || k.starts_with("$.")) + || transform + .input_field + .as_ref() + .is_some_and(|(_, source)| SourceInfo::reads_root(source)) + } + _ => { + sources.iter().any(|s| SourceInfo::reads_root(s)) + || cells.iter().any(|s| SourceInfo::reads_root_unary(s)) + } + }, + schema, + sites, + dynamic, + kind, + } + } + + fn expand( + key: &Arc, + origin: &Arc, + source: &str, + out: &mut Vec<(Arc, Arc, Arc)>, + ) { + match LaneProgram::object_fields(source).filter(|fields| !fields.is_empty()) { + Some(fields) => { + for (field, fragment) in fields.into_iter().rev() { + Self::expand(&Arc::from(format!("{key}.{field}")), origin, &fragment, out); + } + } + None => out.push((key.clone(), origin.clone(), Arc::from(source))), + } + } + + pub(super) fn rebased(base: &str, key: &str) -> Option> { + if key.starts_with("$nodes") { + return Some(Arc::from(key)); + } + match key.strip_prefix('$') { + Some("") => Some(Arc::from(base)), + Some(rest) if rest.starts_with('.') => Some(Arc::from(format!("{base}{rest}"))), + Some(_) => None, + None => Some(Arc::from(format!("{base}.{key}"))), + } + } + + fn statics(sites: &[Option>]) -> Option> { + if sites.iter().any(Option::is_none) { + return None; + } + let mut out: Vec = Vec::new(); + for key in sites.iter().flatten() { + if key.as_ref() == "$nodes" { + return None; + } + let Some(rest) = key.strip_prefix("$nodes.") else { + continue; + }; + let (name, path) = rest.split_once('.').unwrap_or((rest, "")); + if !out.iter().any(|read| read.key == *key) { + out.push(StaticRead { + key: key.clone(), + name: Arc::from(name), + path: Arc::from(path), + }); + } + } + Some(out) + } +} diff --git a/core/engine/src/compiled/graph/traced.rs b/core/engine/src/compiled/graph/traced.rs new file mode 100644 index 00000000..f42ab746 --- /dev/null +++ b/core/engine/src/compiled/graph/traced.rs @@ -0,0 +1,277 @@ +use super::schedule::{End, Outcome}; +use super::{CompiledGraph, Step}; +use crate::decision_graph::cleaner::VariableCleaner; +use crate::decision_graph::graph::{DecisionGraphResponse, EvaluationTrace}; +use crate::decision_graph::tracer::{NodeTracer, SwitchStatementTrace, SwitchStatementTraceRow}; +use crate::decision_graph::walker::GraphWalker; +use crate::model::{DecisionNodeKind, GraphContent}; +use crate::nodes::{ + NodeContextBase, NodeContextConfig, NodeError, NodeHandlerExtensions, NodeResponse, NodeResult, +}; +use crate::{DecisionGraphTrace, EvaluationError, ZEN_CONFIG}; +use ahash::HashMap; +use petgraph::prelude::NodeIndex; +use std::cell::RefCell; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::time::Instant; +use zen_expression::lane::Session; +use zen_expression::variable::{ToVariable, Variable}; +use zen_types::decision::{SwitchNodeContent, SwitchStatementHitPolicy}; +use zen_types::symbol::Symbol; + +pub(crate) struct Traced<'g> { + pub(crate) graph: &'g CompiledGraph, + pub(crate) content: &'g Arc, + pub(crate) extensions: &'g NodeHandlerExtensions, + pub(crate) max_depth: u8, + pub(crate) iteration: u8, + pub(crate) parent: Option, +} + +struct Slot { + data: Variable, + view: Option, +} + +type Traces = HashMap, DecisionGraphTrace>; + +impl Traced<'_> { + pub(crate) async fn evaluate( + &self, + context: Variable, + ) -> Result> { + let root_start = Instant::now(); + if self.iteration >= self.max_depth { + return Err(Box::new(EvaluationError::DepthLimitExceeded)); + } + + let with_nodes = ZEN_CONFIG.nodes_in_context.load(Ordering::Relaxed); + let mut slots: Vec> = (0..self.graph.steps.len()).map(|_| None).collect(); + let mut tracer = NodeTracer::new(true); + let mut segment = self.graph.root.clone(); + let ending = loop { + for event in segment.events.iter() { + let Some(step) = self.graph.step_at(event.node) else { + continue; + }; + let start = Instant::now(); + let input = Self::merged(&slots, &event.parents); + let nodes = with_nodes.then(|| self.nodes(&slots, &event.visible)); + let result = self.node(step, &context, input.clone(), nodes).await; + tracer.record_execution(&step.node, input, &result, start.elapsed()); + let output = match result { + Ok(response) => response.output, + Err(error) => return Err(Self::failed(tracer.into_traces(), error)), + }; + let view = match (&step.node.kind, &self.parent) { + (DecisionNodeKind::InputNode { .. }, Some(parent)) => { + let view = output.depth_clone(1); + view.dot_insert(Variable::nodes_key().as_ref(), parent.clone()); + Some(view) + } + _ => None, + }; + if let Some(slot) = slots.get_mut(event.node.index()) { + *slot = Some(Slot { data: output, view }); + } + } + + match &segment.end { + End::Finish(ending) => break ending.clone(), + End::Switch { + node, + parents, + visible, + .. + } => { + let start = Instant::now(); + let input = Self::merged(&slots, parents); + let nodes = with_nodes.then(|| self.nodes(&slots, visible)); + let outcome = match self.graph.step_at(*node) { + Some(step) => self.switch(step, input, nodes, start, &mut tracer), + None => Outcome::from(Vec::new()), + }; + segment = self.graph.child(&segment, outcome); + } + } + }; + + let result = GraphWalker::merge_ending( + ending + .iter() + .filter_map(|nid| slots.get(nid.index())?.as_ref().map(|slot| &slot.data)), + ); + let traces = tracer.into_traces(); + if self.iteration == 0 { + let mut cleaner = VariableCleaner::new(); + cleaner.clean(&result); + if let Some(traces) = &traces { + Self::clean(&mut cleaner, traces); + } + } + + Ok(DecisionGraphResponse { + performance: format!("{:.1?}", root_start.elapsed()), + result, + trace: traces.map(EvaluationTrace::Graph), + }) + } + + fn merged(slots: &[Option], parents: &[NodeIndex]) -> Variable { + GraphWalker::merge_values( + parents + .iter() + .filter_map(|nid| slots.get(nid.index())?.as_ref().map(|slot| &slot.data)), + ) + } + + fn nodes(&self, slots: &[Option], visible: &[NodeIndex]) -> Variable { + Variable::from_object( + visible + .iter() + .filter_map(|nid| { + let slot = slots.get(nid.index())?.as_ref()?; + let step = self.graph.step_at(*nid)?; + let value = slot.view.clone().unwrap_or_else(|| slot.data.clone()); + Some((Symbol::from(step.node.name.as_ref()), value)) + }) + .collect(), + ) + } + + fn clean(cleaner: &mut VariableCleaner, traces: &Traces) { + traces.values().for_each(|trace| { + cleaner.clean(&trace.input); + cleaner.clean(&trace.output); + if let Some(data) = &trace.trace_data { + cleaner.clean(data); + } + }); + } + + fn failed(traces: Option, error: NodeError) -> Box { + if let Some(traces) = &traces { + Self::clean(&mut VariableCleaner::new(), traces); + } + + Box::new( + NodeError::traced( + error.node_id, + traces.map(|traces| traces.to_variable()), + error.source, + ) + .into(), + ) + } + + fn switch( + &self, + step: &Step, + input: Variable, + nodes: Option, + start: Instant, + tracer: &mut NodeTracer, + ) -> Outcome { + let DecisionNodeKind::SwitchNode { content } = &step.node.kind else { + return Outcome::from(Vec::new()); + }; + let statements = Self::statements(step, content, &input, nodes); + if let Some(mut record) = tracer.trace_callback() { + let output = input.depth_clone(1); + record(DecisionGraphTrace { + id: step.node.id.clone(), + name: step.node.name.clone(), + input, + output, + order: 0, + performance: Some(Arc::from(format!("{:.1?}", start.elapsed()))), + trace_data: Some( + SwitchStatementTrace { + statements: statements.clone(), + } + .to_variable(), + ), + }); + } + + statements + .into_iter() + .map(|statement| statement.id) + .collect() + } + + fn statements( + step: &Step, + content: &SwitchNodeContent, + input: &Variable, + nodes: Option, + ) -> Vec { + let mut session = + Session::with_environment(input.clone()).with_programs(Some(step.programs().clone())); + if let Some(nodes) = nodes { + session.set_local(Variable::nodes_key(), nodes); + } + + let mut passes = |condition: &str| { + condition.is_empty() + || session + .run_standard(condition) + .is_ok_and(|value| value.as_bool().unwrap_or(false)) + }; + let mut statements = content.statements.iter(); + match content.hit_policy { + SwitchStatementHitPolicy::First => statements + .find(|statement| passes(&statement.condition)) + .into_iter() + .cloned() + .map(SwitchStatementTraceRow::from) + .collect(), + SwitchStatementHitPolicy::Collect => statements + .filter(|statement| passes(&statement.condition)) + .cloned() + .map(SwitchStatementTraceRow::from) + .collect(), + } + } + + async fn node( + &self, + step: &Step, + context: &Variable, + input: Variable, + nodes: Option, + ) -> NodeResult { + let node = &step.node; + let base = NodeContextBase { + id: node.id.clone(), + name: node.name.clone(), + input, + nodes, + extensions: self.extensions.clone(), + iteration: self.iteration, + trace: Some(RefCell::new(Variable::Null)), + config: NodeContextConfig { + max_depth: self.max_depth, + trace: true, + ..Default::default() + }, + }; + + match &node.kind { + DecisionNodeKind::InputNode { .. } => { + let base = NodeContextBase { + input: context.clone(), + ..base + }; + self.graph.edge(step, base, self.content).await + } + DecisionNodeKind::OutputNode { .. } => self.graph.edge(step, base, self.content).await, + DecisionNodeKind::SwitchNode { .. } => Ok(NodeResponse { + output: base.input, + trace_data: None, + }), + _ => CompiledGraph::dispatch(step, base, Some(step.programs())).await, + } + } +} diff --git a/core/engine/src/compiled/leaf/array.rs b/core/engine/src/compiled/leaf/array.rs new file mode 100644 index 00000000..7c9f2269 --- /dev/null +++ b/core/engine/src/compiled/leaf/array.rs @@ -0,0 +1,554 @@ +use super::{Bits, Dict}; +use std::rc::Rc; +use zen_expression::lane::{Column, Dictionary, Kind, Output, Scaled, Shape, Values}; +use zen_expression::Variable; + +#[derive(Debug)] +pub(crate) enum Store { + Scaled { + mant: Vec, + scale: Vec, + }, + Bool(Vec), + Text { + offsets: Vec, + data: String, + }, + Coded { + codes: Rc<[i32]>, + dict: Rc, + }, + Any(Vec), + List { + offsets: Vec, + child: Box, + }, +} + +impl Store { + pub fn unpacked(values: &[rust_decimal::Decimal]) -> Option { + let mut mant = Vec::with_capacity(values.len()); + let mut scale = Vec::with_capacity(values.len()); + for value in values { + let (m, s) = Scaled::parts(value)?; + mant.push(m); + scale.push(s); + } + Some(Store::Scaled { mant, scale }) + } +} + +#[derive(Debug)] +pub(crate) struct Array { + pub(super) values: Store, + pub(super) valid: Option>, + pub(super) rows: usize, +} + +impl Array { + fn any(out: &Output) -> Array { + Array::from_values( + (0..out.len()) + .map(|row| { + out.variable(row) + .and_then(Result::ok) + .unwrap_or(Variable::Null) + }) + .collect(), + ) + } + + pub fn from_output(out: &mut Output) -> Array { + let rows = out.len(); + let mut valid: Option> = None; + if out.kind() != Kind::Dyn { + for (row, value) in out.boxed_values() { + match value { + Variable::Null => Bits::set( + valid.get_or_insert_with(|| Bits::ones(rows)), + *row as usize, + false, + ), + _ => return Self::any(out), + } + } + } + if out.failed().iter().any(|w| *w != 0) { + let bits = valid.get_or_insert_with(|| Bits::ones(rows)); + bits.iter_mut() + .zip(out.failed()) + .for_each(|(v, failed)| *v &= !failed); + } + let scalar = matches!(out.shape(), Shape::Scalar); + if let (true, Some((keys, offsets, data))) = (scalar, out.codes()) { + let mut valid = valid.unwrap_or_else(|| Bits::ones(rows)); + keys.iter() + .enumerate() + .filter(|(_, code)| **code < 0) + .for_each(|(row, _)| Bits::set(&mut valid, row, false)); + let dict = Dict::Text { + offsets: offsets.to_vec(), + data: data.to_string(), + }; + return Array::coded_with(keys.into(), Rc::new(dict), valid); + } + let values = match out.kind() { + Kind::Num if scalar => { + let (mant, scale) = out.take_numbers(); + Store::Scaled { mant, scale } + } + Kind::Bool if scalar => Store::Bool(out.take_bits()), + Kind::Str + if i32::try_from(out.data().len()).is_ok() + && std::str::from_utf8(out.data()).is_ok() => + { + let (offsets, data) = out.take_text(); + Store::Text { + offsets: offsets.into_iter().map(|o| o as i32).collect(), + data: String::from_utf8(data).unwrap_or_default(), + } + } + Kind::Dyn if scalar && out.boxed_values().is_empty() => { + let failed = out.failed().to_vec(); + let mut values = out.take_values(); + values.resize(rows, Variable::Null); + for (row, value) in values.iter_mut().enumerate() { + if Bits::get(&failed, row) { + *value = Variable::Null; + } + } + return Array::from_values(values); + } + _ => return Self::any(out), + }; + Array { + values, + valid, + rows, + } + } + + pub fn parts(values: Store, valid: Option>, rows: usize) -> Array { + Array { + values, + valid, + rows, + } + } + + pub fn from_values(values: Vec) -> Array { + Array { + rows: values.len(), + values: Store::Any(values), + valid: None, + } + } + + pub fn len(&self) -> usize { + self.rows + } + + pub fn store(&self) -> &Store { + &self.values + } + + pub fn valid(&self, row: usize) -> bool { + self.valid + .as_deref() + .is_none_or(|bits| Bits::get(bits, row)) + } + + pub fn validity_bits(&self) -> Option<&[u64]> { + self.valid.as_deref() + } + + pub fn column(&self) -> Column<'_> { + let values = match &self.values { + Store::Scaled { mant, scale } => Values::Scaled { mant, scale }, + Store::Bool(bits) => Values::Bool { bits, offset: 0 }, + Store::Text { offsets, data } => Values::Text { offsets, data }, + Store::Coded { codes, dict } => Values::Dict { + keys: codes, + values: dict.dictionary(), + }, + Store::Any(values) => Values::Any(values), + Store::List { offsets, child } => Values::List { + offsets, + child: match child.as_ref() { + Store::Text { offsets, data } => Dictionary::Text { offsets, data }, + Store::Scaled { mant, scale } => Dictionary::Scaled { mant, scale }, + Store::Bool(bits) => Dictionary::Bool { bits }, + _ => Dictionary::Any(&[]), + }, + }, + }; + match &self.valid { + Some(bits) => Column::with_validity(values, bits, 0), + None => Column::new(values), + } + } + + fn listed( + offsets: &[i32], + child: Dictionary, + valid: Option<(&[u64], usize)>, + positions: &[usize], + ) -> Option { + let range = |p: usize| -> (usize, usize) { + let live = valid.is_none_or(|(bits, at)| Bits::get(bits, at + p)); + match (live, offsets.get(p), offsets.get(p + 1)) { + (true, Some(a), Some(b)) => (*a as usize, (*b as usize).max(*a as usize)), + _ => (0, 0), + } + }; + let mut out = Vec::with_capacity(positions.len() + 1); + out.push(0i32); + let child = match child { + Dictionary::Text { offsets: co, data } => { + let (mut offsets, mut text) = (vec![0i32], String::new()); + for &p in positions { + let (a, b) = range(p); + for i in a..b { + text.push_str(data.get(*co.get(i)? as usize..*co.get(i + 1)? as usize)?); + offsets.push(i32::try_from(text.len()).ok()?); + } + out.push(i32::try_from(offsets.len() - 1).ok()?); + } + Store::Text { + offsets, + data: text, + } + } + Dictionary::Scaled { mant, scale } => { + let (mut m, mut sc) = (Vec::new(), Vec::new()); + for &p in positions { + let (a, b) = range(p); + m.extend_from_slice(mant.get(a..b)?); + sc.extend_from_slice(scale.get(a..b)?); + out.push(i32::try_from(m.len()).ok()?); + } + Store::Scaled { mant: m, scale: sc } + } + Dictionary::Bool { bits } => { + let mut flat: Vec = Vec::new(); + for &p in positions { + let (a, b) = range(p); + flat.extend((a..b).map(|i| Bits::get(bits, i))); + out.push(i32::try_from(flat.len()).ok()?); + } + Store::Bool(Bits::of(flat.len(), |i| flat[i])) + } + _ => return None, + }; + Some(Store::List { + offsets: out, + child: Box::new(child), + }) + } + + fn coded_gather( + keys: &[i32], + values: Dictionary, + valid: Option<(&[u64], usize)>, + positions: &[usize], + ) -> Option { + let size = values.column().len(); + if size > positions.len().max(64) { + return None; + } + let dict = match values { + Dictionary::Text { offsets, data } => Dict::Text { + offsets: offsets.get(..=size)?.to_vec(), + data: data.to_string(), + }, + Dictionary::Scaled { mant, scale } => Dict::Scaled { + mant: mant.get(..size)?.to_vec(), + scale: scale.get(..size)?.to_vec(), + }, + Dictionary::Bool { bits } => Dict::Bool(bits.to_vec()), + _ => return None, + }; + let codes: Rc<[i32]> = positions + .iter() + .map( + |&p| match valid.is_none_or(|(bits, at)| Bits::get(bits, at + p)) { + true => keys.get(p).copied().unwrap_or(-1), + false => -1, + }, + ) + .collect(); + Some(Array::coded(codes, Rc::new(dict))) + } + + pub fn gather(column: &Column, positions: &[usize]) -> Array { + let rows = positions.len(); + if let Values::Dict { keys, values } = column.values { + if let Some(array) = Self::coded_gather(keys, values, column.validity, positions) { + return array; + } + } + if let Values::List { offsets, child } = column.values { + if let Some(values) = Self::listed(offsets, child, column.validity, positions) { + let valid = column.validity.map(|(bits, offset)| { + Bits::of(rows, |i| Bits::get(bits, offset + positions[i])) + }); + return Array { + values, + valid, + rows, + }; + } + } + let valid = column + .validity + .filter(|(bits, offset)| { + !Bits::full(bits, *offset, positions.iter().max().map_or(0, |m| m + 1)) + }) + .map(|(bits, offset)| Bits::of(rows, |i| Bits::get(bits, offset + positions[i]))); + let values = match column.values { + Values::Scaled { mant, scale } => Store::Scaled { + mant: positions + .iter() + .map(|&p| mant.get(p).copied().unwrap_or(0)) + .collect(), + scale: positions + .iter() + .map(|&p| scale.get(p).copied().unwrap_or(0)) + .collect(), + }, + Values::I64(values) => Store::Scaled { + mant: positions + .iter() + .map(|&p| values.get(p).copied().unwrap_or(0)) + .collect(), + scale: vec![0; rows], + }, + Values::Dec(values) => { + let mut mant = Vec::with_capacity(rows); + let mut scale = Vec::with_capacity(rows); + let parts = positions.iter().try_for_each(|&p| { + let (m, s) = match values.get(p) { + Some(d) => Scaled::parts(d)?, + None => (0, 0), + }; + mant.push(m); + scale.push(s); + Some(()) + }); + match parts { + Some(()) => Store::Scaled { mant, scale }, + None => { + return Array { + values: Store::Any( + positions.iter().map(|&p| column.variable(p)).collect(), + ), + valid: None, + rows, + } + } + } + } + Values::Bool { bits, offset } => { + Store::Bool(Bits::of(rows, |i| Bits::get(bits, offset + positions[i]))) + } + Values::Text { .. } | Values::Utf8 { .. } => { + let mut offsets = Vec::with_capacity(rows + 1); + let mut data = String::new(); + offsets.push(0); + for &p in positions { + match column.text(p) { + Some(text) => data.push_str(text), + None if !column.valid(p) => {} + None => { + return Array { + values: Store::Any( + positions.iter().map(|&p| column.variable(p)).collect(), + ), + valid: None, + rows, + } + } + } + offsets.push(data.len() as i32); + } + Store::Text { offsets, data } + } + _ => { + return Array { + values: Store::Any(positions.iter().map(|&p| column.variable(p)).collect()), + valid: None, + rows, + } + } + }; + Array { + values, + valid, + rows, + } + } + + pub fn coded(codes: Rc<[i32]>, dict: Rc) -> Array { + Array { + rows: codes.len(), + values: Store::Coded { codes, dict }, + valid: None, + } + } + + pub fn broadcast(&self, rows: usize) -> Option { + let valid = self.valid.as_deref().is_none_or(|bits| Bits::get(bits, 0)); + let (dict, code) = match &self.values { + Store::List { .. } => return Some(Self::gather(&self.column(), &vec![0; rows])), + Store::Scaled { mant, scale } => ( + Rc::new(Dict::Scaled { + mant: vec![*mant.first()?], + scale: vec![*scale.first()?], + }), + 0, + ), + Store::Bool(bits) => (Rc::new(Dict::Bool(vec![bits.first()? & 1])), 0), + Store::Text { offsets, data } => { + let text = data.get(*offsets.first()? as usize..*offsets.get(1)? as usize)?; + ( + Rc::new(Dict::Text { + offsets: vec![0, i32::try_from(text.len()).ok()?], + data: text.to_string(), + }), + 0, + ) + } + Store::Coded { codes, dict } => (dict.clone(), *codes.first()?), + Store::Any(values) => match values.first()? { + Variable::Array(items) + if items.borrow().iter().all(|item| { + matches!( + item, + Variable::Null + | Variable::Bool(_) + | Variable::Number(_) + | Variable::String(_) + ) + }) => + { + (Rc::new(Dict::Any(vec![values.first()?.clone()])), 0) + } + value @ (Variable::Array(_) | Variable::Object(_) | Variable::Dynamic(_)) => { + return Some(Array { + rows, + values: Store::Any( + (0..rows) + .map(|_| { + if valid { + value.deep_clone() + } else { + Variable::Null + } + }) + .collect(), + ), + valid: None, + }) + } + value => (Rc::new(Dict::Any(vec![value.clone()])), 0), + }, + }; + let code = if valid { code } else { -1 }; + Some(Array { + rows, + values: Store::Coded { + codes: vec![code; rows].into(), + dict, + }, + valid: None, + }) + } + + pub fn coded_with(codes: Rc<[i32]>, dict: Rc, valid: Vec) -> Array { + Array { + rows: codes.len(), + values: Store::Coded { codes, dict }, + valid: Some(valid), + } + } + + pub fn expand(&self, ids: &[u32]) -> Array { + let code = |id: u32| match self.valid(id as usize) { + true => id as i32, + false => -1, + }; + let shared = |value: &Variable| match value { + Variable::Array(items) => items.borrow().iter().all(|item| { + matches!( + item, + Variable::Null | Variable::Bool(_) | Variable::Number(_) | Variable::String(_) + ) + }), + Variable::Object(_) | Variable::Dynamic(_) => false, + _ => true, + }; + let dict = match &self.values { + Store::Scaled { mant, scale } => Dict::Scaled { + mant: mant.clone(), + scale: scale.clone(), + }, + Store::Text { offsets, data } => Dict::Text { + offsets: offsets.clone(), + data: data.clone(), + }, + Store::Coded { codes, dict } => { + let codes = ids + .iter() + .map(|&id| match self.valid(id as usize) { + true => codes.get(id as usize).copied().unwrap_or(-1), + false => -1, + }) + .collect(); + return Array::coded(codes, dict.clone()); + } + Store::Any(values) if values.iter().all(shared) => Dict::Any(values.clone()), + Store::Any(values) => { + let values = ids + .iter() + .map( + |&id| match (self.valid(id as usize), values.get(id as usize)) { + (true, Some(value)) => value.deep_clone(), + _ => Variable::Null, + }, + ) + .collect(); + return Array::from_values(values); + } + Store::Bool(_) | Store::List { .. } => { + let positions: Vec = ids.iter().map(|&id| id as usize).collect(); + return self.pick(&positions); + } + }; + Array::coded(ids.iter().map(|&id| code(id)).collect(), Rc::new(dict)) + } + + pub fn pick(&self, positions: &[usize]) -> Array { + match &self.values { + Store::Coded { codes, dict } => Array { + values: Store::Coded { + codes: positions.iter().map(|&p| codes[p]).collect(), + dict: dict.clone(), + }, + valid: self + .valid + .as_deref() + .map(|bits| Bits::gather(bits, positions)), + rows: positions.len(), + }, + Store::Any(values) => Array { + values: Store::Any(positions.iter().map(|&p| values[p].clone()).collect()), + valid: self + .valid + .as_deref() + .map(|bits| Bits::gather(bits, positions)), + rows: positions.len(), + }, + _ => Self::gather(&self.column(), positions), + } + } +} diff --git a/core/engine/src/compiled/leaf/builder.rs b/core/engine/src/compiled/leaf/builder.rs new file mode 100644 index 00000000..99c90421 --- /dev/null +++ b/core/engine/src/compiled/leaf/builder.rs @@ -0,0 +1,295 @@ +use super::{Array, Bits, Literal, Store}; +use zen_expression::lane::{Column, Dictionary, Scaled, Values}; +use zen_expression::Variable; + +#[derive(Default)] +pub(crate) struct ColumnBuilder { + kind: Option, + mant: Vec, + scale: Vec, + bits: Vec, + offsets: Vec, + data: String, + any: Vec, + valid: Vec, + nulls: bool, + rows: usize, + capacity: usize, +} + +impl ColumnBuilder { + const NUM: u8 = 0; + const BOOL: u8 = 1; + const TEXT: u8 = 2; + const ANY: u8 = 3; + + pub fn with_capacity(rows: usize) -> Self { + Self { + valid: Vec::with_capacity(rows.div_ceil(64)), + capacity: rows, + ..Default::default() + } + } + + pub fn null_at(column: &Column, row: usize) -> bool { + if !column.valid(row) { + return true; + } + match column.values { + Values::Any(values) => values.get(row).is_none_or(|v| matches!(v, Variable::Null)), + Values::Dict { values, .. } => column.code(row).is_none_or(|code| { + !values.valid(code) + || matches!(values, Dictionary::Any(v) if v.get(code).is_none_or(|v| matches!(v, Variable::Null))) + }), + Values::Dec(_) | Values::Scaled { .. } | Values::I64(_) | Values::F64(_) => column.number(row).is_none(), + Values::Bool { .. } | Values::List { .. } => false, + _ => column.text(row).is_none(), + } + } + + fn open(&mut self) -> usize { + let row = self.rows; + self.rows += 1; + if row.is_multiple_of(64) { + self.valid.push(0); + if self.kind == Some(Self::BOOL) { + self.bits.push(0); + } + } + row + } + + fn fill(&mut self) { + match self.kind { + Some(Self::NUM) => { + self.mant.push(0); + self.scale.push(0); + } + Some(Self::TEXT) => self.offsets.push(self.data.len() as i32), + Some(Self::ANY) => self.any.push(Variable::Null), + _ => {} + } + } + + fn start(&mut self, kind: u8) { + let rows = self.rows; + let capacity = self.capacity.max(rows); + self.kind = Some(kind); + match kind { + Self::NUM => { + self.mant = Vec::with_capacity(capacity); + self.mant.resize(rows, 0); + self.scale = Vec::with_capacity(capacity); + self.scale.resize(rows, 0); + } + Self::BOOL => self.bits = vec![0; rows.div_ceil(64)], + Self::TEXT => self.offsets = vec![0; rows + 1], + _ => self.any = vec![Variable::Null; rows], + } + } + + fn degrade(&mut self) { + let typed = Array { + values: match self.kind { + Some(Self::NUM) => Store::Scaled { + mant: std::mem::take(&mut self.mant), + scale: std::mem::take(&mut self.scale), + }, + Some(Self::BOOL) => Store::Bool(std::mem::take(&mut self.bits)), + Some(Self::TEXT) => Store::Text { + offsets: std::mem::take(&mut self.offsets), + data: std::mem::take(&mut self.data), + }, + _ => Store::Any(Vec::new()), + }, + valid: Some(self.valid.clone()), + rows: self.rows, + }; + let column = typed.column(); + self.any = (0..self.rows).map(|row| column.variable(row)).collect(); + self.kind = Some(Self::ANY); + } + + pub fn push_cell(&mut self, column: &Column, row: usize) { + if !column.valid(row) { + return self.push_null(); + } + match column.values { + Values::Scaled { mant, scale } => match (mant.get(row), scale.get(row)) { + (Some(m), Some(s)) => self.push_scaled(*m, *s), + _ => self.push_null(), + }, + Values::I64(values) => match values.get(row) { + Some(v) => self.push_scaled(*v, 0), + None => self.push_null(), + }, + Values::Dec(values) => match values.get(row) { + Some(d) => match Scaled::parts(d) { + Some((m, s)) => self.push_scaled(m, s), + None => self.push_variable(Variable::Number(*d)), + }, + None => self.push_null(), + }, + Values::Bool { .. } => match column.boolean(row) { + Some(b) => self.push_bool(b), + None => self.push_null(), + }, + Values::Text { .. } | Values::Utf8 { .. } => match column.text(row) { + Some(text) => self.push_text(text), + None => self.push_null(), + }, + Values::Dict { keys, values } => match keys + .get(row) + .and_then(|k| usize::try_from(*k).ok()) + { + None => self.push_null(), + Some(code) => match values { + Dictionary::Scaled { mant, scale } => match (mant.get(code), scale.get(code)) { + (Some(m), Some(s)) => self.push_scaled(*m, *s), + _ => self.push_null(), + }, + Dictionary::Text { offsets, data } => { + let text = offsets + .get(code) + .zip(offsets.get(code + 1)) + .and_then(|(a, b)| data.get(*a as usize..*b as usize)); + match text { + Some(text) => self.push_text(text), + None => self.push_null(), + } + } + Dictionary::Bool { bits } => self.push_bool(Bits::get(bits, code)), + Dictionary::Any(values) => { + self.push_variable(values.get(code).cloned().unwrap_or(Variable::Null)) + } + Dictionary::Column(inner) => self.push_cell(inner, code), + }, + }, + Values::Any(values) => { + self.push_variable(values.get(row).cloned().unwrap_or(Variable::Null)) + } + _ => self.push_variable(column.variable(row)), + } + } + + pub fn push_scaled(&mut self, mant: i64, scale: u8) { + if self.kind.is_none() { + self.start(Self::NUM); + } + if self.kind != Some(Self::NUM) { + return self.push_variable(Variable::Number(rust_decimal::Decimal::new( + mant, + scale as u32, + ))); + } + let row = self.open(); + self.mark(row); + self.mant.push(mant); + self.scale.push(scale); + } + + pub fn push_text(&mut self, text: &str) { + if self.kind.is_none() { + self.start(Self::TEXT); + } + if self.kind != Some(Self::TEXT) { + return self.push_variable(Variable::String(text.into())); + } + let row = self.open(); + self.mark(row); + self.data.push_str(text); + self.offsets.push(self.data.len() as i32); + } + + pub fn push_null(&mut self) { + self.open(); + self.nulls = true; + self.fill(); + } + + fn mark(&mut self, row: usize) { + if let Some(word) = self.valid.get_mut(row / 64) { + *word |= 1 << (row % 64); + } + } + + pub fn push_literal(&mut self, literal: &Literal) { + match literal { + Literal::Null => self.push_null(), + Literal::Array(_) | Literal::Object(_) => self.push_any(literal.variable()), + Literal::Num(n) => match Scaled::parts(n) { + Some((m, s)) => self.push_scaled(m, s), + None => self.push_any(Variable::Number(*n)), + }, + Literal::Str(text) => self.push_text(text), + Literal::Bool(b) => self.push_bool(*b), + } + } + + pub fn push_any(&mut self, value: Variable) { + match self.kind { + None => self.start(Self::ANY), + Some(Self::ANY) => {} + Some(_) => self.degrade(), + } + let row = self.open(); + self.mark(row); + self.any.push(value); + } + + pub fn push_variable(&mut self, value: Variable) { + let typed = |kind: u8| self.kind.is_none_or(|k| k == kind); + match &value { + Variable::Null => return self.push_null(), + Variable::Number(n) if typed(Self::NUM) => { + if let Some((m, s)) = Scaled::parts(n) { + return self.push_scaled(m, s); + } + } + Variable::String(text) if typed(Self::TEXT) => return self.push_text(text), + Variable::Bool(b) if typed(Self::BOOL) => return self.push_bool(*b), + _ => {} + } + self.push_any(value) + } + + pub fn push_bool(&mut self, b: bool) { + if self.kind.is_none() { + self.start(Self::BOOL); + } + if self.kind != Some(Self::BOOL) { + return self.push_any(Variable::Bool(b)); + } + let row = self.open(); + self.mark(row); + if b { + if let Some(word) = self.bits.get_mut(row / 64) { + *word |= 1 << (row % 64); + } + } + } + + pub fn finish(mut self) -> Array { + let values = match self.kind { + Some(Self::NUM) => Store::Scaled { + mant: self.mant, + scale: self.scale, + }, + Some(Self::BOOL) => Store::Bool(self.bits), + Some(Self::TEXT) => Store::Text { + offsets: self.offsets, + data: self.data, + }, + Some(_) => Store::Any(self.any), + None => { + self.nulls = true; + Store::Any(vec![Variable::Null; self.rows]) + } + }; + Array { + values, + valid: self.nulls.then_some(self.valid), + rows: self.rows, + } + } +} diff --git a/core/engine/src/compiled/leaf/column.rs b/core/engine/src/compiled/leaf/column.rs new file mode 100644 index 00000000..d0af0b06 --- /dev/null +++ b/core/engine/src/compiled/leaf/column.rs @@ -0,0 +1,761 @@ +use super::{ + Array, Bits, ColumnBuilder, Dict, Input, Items, Literal, Masked, Picked, Records, Scattered, + Stitched, Store, Templated, +}; +use std::cell::OnceCell; +use std::rc::Rc; +use zen_expression::lane::{Column, Dictionary, Values}; +use zen_expression::Variable; + +#[derive(Clone, Debug)] +pub(crate) enum Leaf<'a> { + Scattered(Rc>), + Masked(Rc>), + Input(Rc>), + Any(Rc<[Variable]>), + Typed(Rc), + Picked(Rc>), + Stitched(Rc>), + Records(Rc>), + Templated(Rc), +} + +impl<'a> Leaf<'a> { + pub fn items(&self) -> Option> { + match self { + Leaf::Records(records) => Some(Items::Records(records.clone())), + Leaf::Input(input) => Self::struct_list(input.column).then(|| Items::Input { + column: input.column, + mask: None, + }), + Leaf::Masked(masked) => match &masked.inner { + Leaf::Input(input) if Self::struct_list(input.column) => Some(Items::Input { + column: input.column, + mask: Some(masked.bits().clone()), + }), + Leaf::Records(records) => { + let valid: Vec = records + .valid + .iter() + .zip(masked.bits().iter()) + .map(|(v, m)| v & m) + .collect(); + Some(Items::Records(Rc::new(Records::new( + records.rows, + records.offsets.clone(), + valid, + records.fields.clone(), + records.nulled.clone(), + )))) + } + _ => None, + }, + _ => None, + } + } + + pub fn records(&self) -> Option>> { + match self { + Leaf::Records(records) => Some(records.clone()), + Leaf::Picked(picked) => { + let records = picked.source.records()?; + match picked + .dense + .get_or_init(|| Leaf::Records(Rc::new(records.pick(&picked.positions)))) + { + Leaf::Records(records) => Some(records.clone()), + _ => None, + } + } + Leaf::Scattered(scattered) if scattered.inner.records().is_some() => { + match scattered.dense.get_or_init(|| Self::spread(scattered)) { + Leaf::Records(records) => Some(records.clone()), + _ => None, + } + } + Leaf::Masked(masked) if matches!(masked.inner, Leaf::Records(_)) => { + match self.items() { + Some(Items::Records(records)) => Some(records), + _ => None, + } + } + _ => None, + } + } + + fn struct_list(column: Column) -> bool { + matches!(column.values, Values::List { child: Dictionary::Column(child), .. } if matches!(child.values, Values::Struct { .. })) + } + + pub fn typed(array: Array) -> Leaf<'a> { + Leaf::Typed(Rc::new(array)) + } + + pub fn masked(inner: Leaf<'a>, mask: &Rc<[u64]>) -> Leaf<'a> { + let rows = inner.len(); + let trimmed = mask + .last() + .is_none_or(|w| rows.is_multiple_of(64) || w >> (rows % 64) == 0); + let bits = OnceCell::new(); + if inner.all_valid() && trimmed && mask.len() == rows.div_ceil(64) { + let _ = bits.set(mask.clone()); + } + Leaf::Masked(Rc::new(Masked { + inner, + mask: mask.clone(), + bits, + })) + } + + fn all_valid(&self) -> bool { + match self { + Leaf::Input(input) => input.column.validity.is_none(), + Leaf::Typed(typed) => typed.valid.is_none(), + Leaf::Any(_) => true, + _ => false, + } + } + + pub fn scattered(inner: Leaf<'a>, positions: Rc<[usize]>, rows: usize) -> Leaf<'a> { + Leaf::Scattered(Rc::new(Scattered { + inner, + positions, + rows, + dense: OnceCell::new(), + })) + } + + pub fn coded_dict(&self) -> Option<&Rc> { + match self { + Leaf::Typed(typed) => match &typed.values { + Store::Coded { dict, .. } => Some(dict), + _ => None, + }, + _ => None, + } + } + + pub fn scatter_parts(&self) -> Option<(&Leaf<'a>, &Rc<[usize]>)> { + match self { + Leaf::Scattered(scattered) if scattered.dense.get().is_none() => { + Some((&scattered.inner, &scattered.positions)) + } + _ => None, + } + } + + pub fn same(&self, other: &Leaf<'a>) -> bool { + match (self, other) { + (Leaf::Scattered(a), Leaf::Scattered(b)) => Rc::ptr_eq(a, b), + (Leaf::Masked(a), Leaf::Masked(b)) => Rc::ptr_eq(a, b), + (Leaf::Input(a), Leaf::Input(b)) => Rc::ptr_eq(a, b), + (Leaf::Any(a), Leaf::Any(b)) => Rc::ptr_eq(a, b), + (Leaf::Typed(a), Leaf::Typed(b)) => Rc::ptr_eq(a, b), + (Leaf::Picked(a), Leaf::Picked(b)) => Rc::ptr_eq(a, b), + (Leaf::Stitched(a), Leaf::Stitched(b)) => Rc::ptr_eq(a, b), + (Leaf::Records(a), Leaf::Records(b)) => Rc::ptr_eq(a, b), + (Leaf::Templated(a), Leaf::Templated(b)) => Rc::ptr_eq(a, b), + _ => false, + } + } + + fn spread(scattered: &Scattered<'a>) -> Leaf<'a> { + let (rows, positions) = (scattered.rows, &scattered.positions); + if let Some(spread) = scattered + .inner + .records() + .and_then(|records| records.spread(positions, rows)) + { + return Leaf::Records(Rc::new(spread)); + } + if let Leaf::Templated(templated) = &scattered.inner { + let mut codes = vec![-1i32; rows]; + for (at, &row) in positions.iter().enumerate() { + if let (Some(slot), Some(code)) = (codes.get_mut(row), templated.codes.get(at)) { + *slot = *code; + } + } + return Templated::leaf(codes.into(), templated.templates.clone()); + } + if let Leaf::Typed(typed) = &scattered.inner { + if let Store::Coded { codes, dict } = &typed.values { + let mut full = vec![-1i32; rows]; + for (i, &row) in positions.iter().enumerate() { + if let (Some(slot), Some(code)) = (full.get_mut(row), codes.get(i)) { + *slot = match typed.valid(i) { + true => *code, + false => -1, + }; + } + } + return Leaf::typed(Array::coded(full.into(), dict.clone())); + } + } + let column = scattered.inner.column(); + let mut valid = vec![0u64; rows.div_ceil(64)]; + for (i, &row) in positions.iter().enumerate() { + if column.valid(i) { + Bits::set(&mut valid, row, true); + } + } + let values = match column.values { + Values::Scaled { mant, scale } => { + let (mut m, mut s) = (vec![0i64; rows], vec![0u8; rows]); + for (i, &row) in positions.iter().enumerate() { + m[row] = mant.get(i).copied().unwrap_or(0); + s[row] = scale.get(i).copied().unwrap_or(0); + } + Store::Scaled { mant: m, scale: s } + } + Values::Bool { bits, offset } => { + let mut out = vec![0u64; rows.div_ceil(64)]; + for (i, &row) in positions.iter().enumerate() { + Bits::set(&mut out, row, Bits::get(bits, offset + i)); + } + Store::Bool(out) + } + Values::Any(values) => { + let mut out = vec![Variable::Null; rows]; + for (i, &row) in positions.iter().enumerate() { + out[row] = values.get(i).cloned().unwrap_or(Variable::Null); + } + Store::Any(out) + } + Values::Text { .. } | Values::Utf8 { .. } => { + return Self::spread_text(&column, positions, rows) + .map_or_else(|| Self::spread_cells(&column, positions, rows), Leaf::typed) + } + _ => return Self::spread_cells(&column, positions, rows), + }; + Leaf::typed(Array { + values, + valid: Some(valid), + rows, + }) + } + + fn spread_text(column: &Column, positions: &[usize], rows: usize) -> Option { + let mut offsets = Vec::with_capacity(rows + 1); + let mut data = String::new(); + let mut valid = vec![0u64; rows.div_ceil(64)]; + let (mut nulls, mut filled) = (false, false); + let mut next = positions.iter().enumerate().peekable(); + offsets.push(0i32); + for row in 0..rows { + let text = match next.peek() { + Some(&(i, &at)) if at == row => { + next.next(); + match column.valid(i) { + true => column.text(i), + false => None, + } + } + _ => None, + }; + match text { + Some(text) => { + data.push_str(text); + Bits::on(&mut valid, row); + filled = true; + } + None => nulls = true, + } + offsets.push(data.len() as i32); + } + filled.then_some(Array { + values: Store::Text { offsets, data }, + valid: nulls.then_some(valid), + rows, + }) + } + + fn spread_cells(column: &Column, positions: &[usize], rows: usize) -> Leaf<'a> { + let mut builder = ColumnBuilder::with_capacity(rows); + let mut next = positions.iter().enumerate().peekable(); + for row in 0..rows { + match next.peek() { + Some(&(i, &at)) if at == row => { + builder.push_cell(column, i); + next.next(); + } + _ => builder.push_null(), + } + } + Leaf::typed(builder.finish()) + } + + pub fn nulls(rows: usize) -> Leaf<'a> { + Leaf::Any((0..rows).map(|_| Variable::Null).collect()) + } + + pub fn input(column: Column<'a>, rows: usize) -> Leaf<'a> { + Leaf::Input(Rc::new(Input { + column, + rows, + valued: OnceCell::new(), + })) + } + + pub fn stitched(sources: Vec>, located: Rc<[(usize, usize)]>) -> Leaf<'a> { + Leaf::Stitched(Rc::new(Stitched { + sources, + located, + dense: OnceCell::new(), + })) + } + + fn source(&self, row: usize) -> Option<(&Leaf<'a>, usize)> { + match self { + Leaf::Stitched(stitched) => { + let &(piece, at) = stitched.located.get(row)?; + Some((stitched.sources.get(piece)?, at)) + } + Leaf::Picked(picked) => Some((&picked.source, *picked.positions.get(row)?)), + _ => Some((self, row)), + } + } + + pub fn get(&self, row: usize) -> Variable { + match self { + Leaf::Any(values) => values.get(row).cloned().unwrap_or(Variable::Null), + Leaf::Picked(_) | Leaf::Stitched(_) => self + .source(row) + .map_or(Variable::Null, |(leaf, at)| leaf.get(at)), + Leaf::Records(records) => records.get(row), + Leaf::Templated(templated) => templated.get(row), + _ => self.column().variable(row), + } + } + + pub fn objects(&self) -> bool { + if let Leaf::Masked(_) | Leaf::Scattered(_) = self { + if let Some(found) = self.plain_objects() { + return found; + } + } + match self { + Leaf::Any(values) => values.iter().any(|v| matches!(v, Variable::Object(_))), + Leaf::Picked(picked) => picked.source.objects(), + Leaf::Stitched(stitched) => stitched.sources.iter().any(Leaf::objects), + Leaf::Records(records) => records + .fields + .iter() + .any(|(key, leaf, _)| key.as_str().starts_with('$') || leaf.objects()), + Leaf::Templated(templated) => templated + .templates + .iter() + .any(|literal| matches!(literal, Literal::Object(_))), + Leaf::Masked(masked) if matches!(masked.inner, Leaf::Records(_)) => { + masked.inner.objects() + } + Leaf::Scattered(scattered) if matches!(scattered.inner, Leaf::Records(_)) => { + scattered.inner.objects() + } + _ => match self.column().values { + Values::Any(values) => values.iter().any(|v| matches!(v, Variable::Object(_))), + Values::Dict { + values: Dictionary::Any(values), + .. + } => values.iter().any(|v| matches!(v, Variable::Object(_))), + _ => false, + }, + } + } + + fn plain_objects(&self) -> Option { + match self { + _ if self.objectless() => Some(false), + Leaf::Typed(_) | Leaf::Input(_) | Leaf::Any(_) => Some(self.objects()), + Leaf::Masked(masked) => masked.inner.plain_objects(), + _ => None, + } + } + + fn objectless(&self) -> bool { + let plain = |values: &[Variable]| !values.iter().any(|v| matches!(v, Variable::Object(_))); + match self { + _ if self.scalar() => true, + Leaf::Any(values) => plain(values), + Leaf::Typed(typed) => match &typed.values { + Store::Any(values) => plain(values), + Store::Coded { dict, .. } => matches!(&**dict, Dict::Any(values) if plain(values)), + _ => false, + }, + Leaf::Input(input) => match input.column.values { + Values::Any(values) + | Values::Dict { + values: Dictionary::Any(values), + .. + } => plain(values), + _ => false, + }, + Leaf::Templated(templated) => !templated + .templates + .iter() + .any(|literal| matches!(literal, Literal::Object(_))), + Leaf::Masked(masked) => masked.inner.objectless(), + Leaf::Scattered(scattered) => scattered.inner.objectless(), + Leaf::Picked(picked) => picked.source.objectless(), + Leaf::Stitched(stitched) => stitched.sources.iter().all(Leaf::objectless), + Leaf::Records(_) => false, + } + } + + fn scalar(&self) -> bool { + match self { + Leaf::Typed(typed) => match &typed.values { + Store::Scaled { .. } | Store::Bool(_) | Store::Text { .. } => true, + Store::Coded { dict, .. } => !matches!(**dict, Dict::Any(_)), + Store::Any(_) | Store::List { .. } => false, + }, + Leaf::Masked(masked) => masked.inner.scalar(), + Leaf::Scattered(scattered) => scattered.inner.scalar(), + Leaf::Picked(picked) => picked.source.scalar(), + Leaf::Stitched(stitched) => stitched.sources.iter().all(Leaf::scalar), + Leaf::Input(input) => match input.column.values { + Values::Dict { values, .. } => { + !matches!(values, Dictionary::Any(_) | Dictionary::Column(_)) + } + Values::List { .. } | Values::Struct { .. } | Values::Any(_) => false, + _ => true, + }, + _ => false, + } + } + + fn dense(&self, positions: &[usize]) -> Leaf<'a> { + match self { + Leaf::Any(values) => Leaf::Any(positions.iter().map(|&i| values[i].clone()).collect()), + Leaf::Typed(typed) => Leaf::typed(typed.pick(positions)), + Leaf::Input(input) => Leaf::typed(Array::gather(&input.column, positions)), + Leaf::Masked(_) | Leaf::Scattered(_) => { + Leaf::typed(Array::gather(&self.column(), positions)) + } + Leaf::Records(records) => Leaf::Records(Rc::new(records.pick(positions))), + Leaf::Templated(templated) => templated.mapped(positions.iter().copied()), + Leaf::Picked(picked) => { + let composed: Vec = positions.iter().map(|&i| picked.positions[i]).collect(); + picked.source.dense(&composed) + } + Leaf::Stitched(stitched) => { + let views: Vec = stitched.sources.iter().map(Leaf::column).collect(); + let mut builder = ColumnBuilder::with_capacity(positions.len()); + for &row in positions { + match stitched + .located + .get(row) + .and_then(|&(piece, at)| Some((views.get(piece)?, at))) + { + Some((view, at)) => builder.push_cell(view, at), + None => builder.push_null(), + } + } + Leaf::typed(builder.finish()) + } + } + } + + pub fn expand(&self, ids: &[u32]) -> Leaf<'a> { + match self { + Leaf::Typed(typed) => Leaf::typed(typed.expand(ids)), + Leaf::Any(values) => Leaf::typed(Array::from_values(values.to_vec()).expand(ids)), + Leaf::Templated(templated) => templated.mapped(ids.iter().map(|&id| id as usize)), + other => { + let column = other.column(); + Leaf::typed( + Array::from_values((0..other.len()).map(|row| column.variable(row)).collect()) + .expand(ids), + ) + } + } + } + + pub fn regroup(&self, positions: &Rc<[usize]>) -> Leaf<'a> { + match self.records() { + Some(records) => Leaf::Records(Rc::new(records.pick(positions))), + None => self.pick(positions), + } + } + + pub fn pick(&self, positions: &Rc<[usize]>) -> Leaf<'a> { + match self { + Leaf::Picked(picked) => Leaf::Picked(Rc::new(Picked { + source: picked.source.clone(), + positions: positions.iter().map(|&i| picked.positions[i]).collect(), + dense: OnceCell::new(), + })), + other => Leaf::Picked(Rc::new(Picked { + source: other.clone(), + positions: positions.clone(), + dense: OnceCell::new(), + })), + } + } + + pub fn column(&self) -> Column<'_> { + match self { + Leaf::Input(input) => input.column, + Leaf::Scattered(scattered) => scattered + .dense + .get_or_init(|| Self::spread(scattered)) + .column(), + Leaf::Masked(masked) => Column { + values: masked.inner.column().values, + validity: Some((masked.bits(), 0)), + }, + Leaf::Any(values) => Column::new(Values::Any(values)), + Leaf::Typed(typed) => typed.column(), + Leaf::Picked(picked) => picked + .dense + .get_or_init(|| picked.source.dense(&picked.positions)) + .column(), + Leaf::Stitched(stitched) => stitched + .dense + .get_or_init(|| self.dense(&(0..stitched.located.len()).collect::>())) + .column(), + Leaf::Records(records) => Column::new(Values::Any(records.dense())), + Leaf::Templated(templated) => { + Column::with_validity(Values::Any(templated.dense()), &templated.valid, 0) + } + } + } + + pub fn null(&self, row: usize) -> bool { + match self { + Leaf::Any(values) => values.get(row).is_none_or(|v| matches!(v, Variable::Null)), + Leaf::Picked(_) | Leaf::Stitched(_) => { + self.source(row).is_none_or(|(leaf, at)| leaf.null(at)) + } + Leaf::Records(records) => !records.valid(row), + Leaf::Templated(templated) => templated.template(row).is_none(), + _ => ColumnBuilder::null_at(&self.column(), row), + } + } + + pub fn valid_at(&self, row: usize) -> bool { + match self { + Leaf::Input(input) => input.column.valid(row), + Leaf::Masked(masked) => Bits::get(masked.bits(), row), + Leaf::Scattered(_) => self.column().valid(row), + Leaf::Typed(typed) => typed.valid(row), + Leaf::Any(_) | Leaf::Records(_) => true, + Leaf::Templated(templated) => templated.template(row).is_some(), + Leaf::Picked(_) => self.source(row).is_some_and(|(leaf, at)| leaf.valid_at(at)), + Leaf::Stitched(_) => self.column().valid(row), + } + } + + pub fn validity(&self, rows: usize) -> Vec { + match self { + Leaf::Input(input) => Bits::present(input.column.validity, rows), + Leaf::Typed(typed) => match &typed.valid { + Some(bits) => Bits::window(bits, 0, rows), + None => Bits::ones(rows), + }, + Leaf::Any(_) | Leaf::Records(_) => Bits::ones(rows), + Leaf::Templated(templated) => Bits::window(&templated.valid, 0, rows), + Leaf::Masked(masked) => Bits::window(masked.bits(), 0, rows), + Leaf::Scattered(_) => Bits::present(self.column().validity, rows), + Leaf::Picked(picked) => match picked.dense.get() { + Some(dense) => dense.validity(rows), + None => Bits::gather( + &picked.source.validity(picked.source.len()), + &picked.positions, + ), + }, + Leaf::Stitched(_) => Bits::present(self.column().validity, rows), + } + } + + pub fn valued(&self, rows: usize) -> Vec { + match self { + Leaf::Input(input) if input.rows == rows => input + .valued + .get_or_init(|| Self::column_valued(input.column, rows)) + .clone(), + Leaf::Any(values) => Bits::of(rows, |row| { + values + .get(row) + .is_some_and(|v| !matches!(v, Variable::Null)) + }), + Leaf::Picked(picked) => match picked.dense.get() { + Some(dense) => dense.valued(rows), + None => Bits::gather( + &picked.source.valued(picked.source.len()), + &picked.positions, + ), + }, + Leaf::Stitched(stitched) => { + let parts: Vec> = stitched + .sources + .iter() + .map(|leaf| leaf.valued(leaf.len())) + .collect(); + Bits::of(rows, |row| { + stitched.located.get(row).is_some_and(|&(piece, at)| { + parts.get(piece).is_some_and(|bits| Bits::get(bits, at)) + }) + }) + } + Leaf::Records(_) | Leaf::Templated(_) => Bits::of(rows, |row| !self.null(row)), + Leaf::Typed(typed) if matches!(typed.values, Store::Coded { ref dict, .. } if !matches!(**dict, Dict::Any(_))) => + { + let Store::Coded { codes, .. } = &typed.values else { + return Bits::of(rows, |row| !self.null(row)); + }; + let mut bits: Vec = codes + .get(..rows) + .unwrap_or(codes) + .chunks(64) + .map(|chunk| { + chunk + .iter() + .enumerate() + .fold(0u64, |word, (at, c)| word | (u64::from(*c >= 0) << at)) + }) + .collect(); + bits.resize(rows.div_ceil(64), 0); + if let Some(valid) = &typed.valid { + bits.iter_mut().zip(valid).for_each(|(b, v)| *b &= v); + } + bits + } + _ => Self::column_valued(self.column(), rows), + } + } + + fn column_valued(column: Column, rows: usize) -> Vec { + match column.values { + Values::Dict { keys, values } => { + let size = values.column().len(); + if size > rows { + return Bits::of(rows, |row| !ColumnBuilder::null_at(&column, row)); + } + let present: Vec = (0..size) + .map(|code| { + values.valid(code) + && !matches!(values, Dictionary::Any(v) if v.get(code).is_none_or(|v| matches!(v, Variable::Null))) + }) + .collect(); + let mut bits = Bits::of(rows, |row| { + keys.get(row) + .and_then(|k| usize::try_from(*k).ok()) + .and_then(|code| present.get(code)) + .is_some_and(|p| *p) + }); + if let Some((valid, offset)) = column.validity { + bits.iter_mut() + .zip(Bits::window(valid, offset, rows)) + .for_each(|(b, v)| *b &= v); + } + bits + } + Values::Text { offsets, data } => { + let bytes = data.as_bytes(); + let boundary = |o: &i32| { + usize::try_from(*o).is_ok_and(|o| { + o == bytes.len() || bytes.get(o).is_some_and(|b| (*b as i8) >= -0x40) + }) + }; + let formed = offsets.get(..=rows).is_some_and(|window| { + window.windows(2).all(|w| w[0] <= w[1]) && window.iter().all(boundary) + }); + if formed { + return match column.validity { + None => Bits::ones(rows), + Some((bits, offset)) => Bits::window(bits, offset, rows), + }; + } + let mut bits = Bits::of(rows, |row| { + offsets + .get(row) + .zip(offsets.get(row + 1)) + .is_some_and(|(a, b)| data.get(*a as usize..*b as usize).is_some()) + }); + if let Some((valid, offset)) = column.validity { + bits.iter_mut() + .zip(Bits::window(valid, offset, rows)) + .for_each(|(b, v)| *b &= v); + } + bits + } + Values::Any(_) + | Values::List { .. } + | Values::Strs(_) + | Values::Utf8 { .. } + | Values::LargeUtf8 { .. } => { + Bits::of(rows, |row| !ColumnBuilder::null_at(&column, row)) + } + _ => match column.validity { + None => Bits::ones(rows), + Some((bits, offset)) => Bits::window(bits, offset, rows), + }, + } + } + + pub fn truthy(&self, row: usize) -> bool { + match self { + Leaf::Any(values) => matches!(values.get(row), Some(Variable::Bool(true))), + Leaf::Picked(_) | Leaf::Stitched(_) => { + self.source(row).is_some_and(|(leaf, at)| leaf.truthy(at)) + } + Leaf::Records(_) => false, + Leaf::Templated(templated) => { + matches!(templated.template(row), Some(Literal::Bool(true))) + } + _ => { + let column = self.column(); + match column.values { + Values::Any(values) => { + column.valid(row) && matches!(values.get(row), Some(Variable::Bool(true))) + } + _ => column.valid(row) && column.boolean(row) == Some(true), + } + } + } + } + + pub fn truths(&self, rows: usize) -> Vec { + if let Leaf::Scattered(scattered) = self { + if scattered.dense.get().is_none() { + let inner = scattered.inner.truths(scattered.positions.len()); + let mut truths = vec![0u64; rows.div_ceil(64)]; + scattered + .positions + .iter() + .enumerate() + .filter(|(i, _)| Bits::get(&inner, *i)) + .for_each(|(_, &row)| Bits::set(&mut truths, row, true)); + return truths; + } + } + if let Leaf::Typed(_) | Leaf::Input(..) | Leaf::Masked(_) | Leaf::Scattered(_) = self { + let column = self.column(); + if let Values::Bool { bits, offset } = column.values { + let mut truths = Bits::window(bits, offset, rows); + if let Some((valid, at)) = column.validity { + truths + .iter_mut() + .zip(Bits::window(valid, at, rows)) + .for_each(|(t, v)| *t &= v); + } + return truths; + } + } + Bits::of(rows, |row| self.truthy(row)) + } + + pub fn len(&self) -> usize { + match self { + Leaf::Input(input) => input.rows, + Leaf::Masked(masked) => masked.inner.len(), + Leaf::Scattered(scattered) => scattered.rows, + Leaf::Any(values) => values.len(), + Leaf::Typed(typed) => typed.len(), + Leaf::Picked(picked) => picked.positions.len(), + Leaf::Stitched(stitched) => stitched.located.len(), + Leaf::Records(records) => records.rows, + Leaf::Templated(templated) => templated.codes.len(), + } + } +} diff --git a/core/engine/src/compiled/leaf/dict.rs b/core/engine/src/compiled/leaf/dict.rs new file mode 100644 index 00000000..1d895a3b --- /dev/null +++ b/core/engine/src/compiled/leaf/dict.rs @@ -0,0 +1,87 @@ +use std::rc::Rc; +use zen_expression::lane::Dictionary; +use zen_expression::Variable; + +#[derive(Debug)] +pub(crate) enum Dict { + Text { offsets: Vec, data: String }, + Scaled { mant: Vec, scale: Vec }, + Bool(Vec), + Any(Vec), +} + +impl Dict { + fn len(&self) -> Option { + match self { + Dict::Text { offsets, .. } => Some(offsets.len().saturating_sub(1)), + Dict::Scaled { mant, .. } => Some(mant.len()), + Dict::Any(values) => Some(values.len()), + Dict::Bool(_) => None, + } + } + + pub fn concat(dicts: &[&Rc]) -> Option<(Rc, Vec)> { + if let [single] = dicts { + return Some(((*single).clone(), vec![0])); + } + let mut bases = Vec::with_capacity(dicts.len()); + let mut total = 0usize; + for dict in dicts { + bases.push(i32::try_from(total).ok()?); + total += dict.len()?; + } + i32::try_from(total).ok()?; + let merged = match dicts.first().map(|d| &***d)? { + Dict::Text { .. } => { + let mut offsets = vec![0i32]; + let mut data = String::new(); + for dict in dicts { + let Dict::Text { + offsets: o, + data: d, + } = &***dict + else { + return None; + }; + let base = i32::try_from(data.len()).ok()?; + offsets.extend(o.iter().skip(1).map(|x| x + base)); + data.push_str(d); + } + i32::try_from(data.len()).ok()?; + Dict::Text { offsets, data } + } + Dict::Scaled { .. } => { + let (mut mant, mut scale) = (Vec::with_capacity(total), Vec::with_capacity(total)); + for dict in dicts { + let Dict::Scaled { mant: m, scale: s } = &***dict else { + return None; + }; + mant.extend_from_slice(m); + scale.extend_from_slice(s); + } + Dict::Scaled { mant, scale } + } + Dict::Any(_) => { + let mut values = Vec::with_capacity(total); + for dict in dicts { + let Dict::Any(v) = &***dict else { + return None; + }; + values.extend(v.iter().cloned()); + } + Dict::Any(values) + } + Dict::Bool(_) => return None, + }; + Some((Rc::new(merged), bases)) + } + + pub(super) fn dictionary(&self) -> Dictionary<'_> { + match self { + Dict::Text { offsets, data } => Dictionary::Text { offsets, data }, + Dict::Scaled { mant, scale } => Dictionary::Scaled { mant, scale }, + Dict::Bool(bits) => Dictionary::Bool { bits }, + Dict::Any(values) => Dictionary::Any(values), + } + } +} diff --git a/core/engine/src/compiled/leaf/literal.rs b/core/engine/src/compiled/leaf/literal.rs new file mode 100644 index 00000000..9f583f04 --- /dev/null +++ b/core/engine/src/compiled/leaf/literal.rs @@ -0,0 +1,89 @@ +use zen_expression::lane::{LaneProgram, LaneRunner, Scaled}; +use zen_expression::{Scope, Variable}; + +#[derive(Debug, Clone)] +pub(crate) enum Literal { + Null, + Bool(bool), + Num(rust_decimal::Decimal), + Str(std::sync::Arc), + Array(Vec), + Object(Vec<(std::sync::Arc, Literal)>), +} + +impl Literal { + pub fn constant(runner: &mut LaneRunner, program: &LaneProgram) -> Option { + let p = program.program(); + if !p.site_keys.is_empty() || p.opaque() || p.writes_env || p.chain || !p.timeless() { + return None; + } + match runner.evaluate_one(program, &Scope::default()).ok()? { + Variable::Null => Some(Literal::Null), + Variable::Bool(b) => Some(Literal::Bool(b)), + Variable::Number(n) => Some(Literal::Num(n)), + Variable::String(s) => Some(Literal::Str(std::sync::Arc::from(&*s))), + _ => None, + } + } + + pub fn variable(&self) -> Variable { + match self { + Literal::Null => Variable::Null, + Literal::Bool(b) => Variable::Bool(*b), + Literal::Num(n) => Variable::Number(*n), + Literal::Str(s) => Variable::String(s.as_ref().into()), + Literal::Array(items) => { + Variable::from_array(items.iter().map(Literal::variable).collect()) + } + Literal::Object(fields) => { + let mut map = zen_types::variable::VariableMap::with_capacity(fields.len()); + for (key, value) in fields { + map.insert(key.as_ref().into(), value.variable()); + } + Variable::from_object(map) + } + } + } + + pub fn deep(&self) -> bool { + match self { + Literal::Object(_) => true, + Literal::Array(items) => items.iter().any(Literal::deep), + _ => false, + } + } + + pub fn scaled(&self) -> Option<(i64, u8)> { + match self { + Literal::Num(n) => Scaled::parts(n), + _ => None, + } + } + + pub fn of(value: &Variable) -> Option { + match value { + Variable::Null => Some(Literal::Null), + Variable::Bool(b) => Some(Literal::Bool(*b)), + Variable::Number(n) => Some(Literal::Num(*n)), + Variable::String(s) => Some(Literal::Str(std::sync::Arc::from(s.as_ref() as &str))), + Variable::Array(items) => items + .borrow() + .iter() + .map(Literal::of) + .collect::>>() + .map(Literal::Array), + Variable::Object(fields) => fields + .borrow() + .iter() + .map(|(key, value)| { + Some(( + std::sync::Arc::from(key.as_ref() as &str), + Literal::of(value)?, + )) + }) + .collect::>>() + .map(Literal::Object), + _ => None, + } + } +} diff --git a/core/engine/src/compiled/leaf/mask.rs b/core/engine/src/compiled/leaf/mask.rs new file mode 100644 index 00000000..9778cf28 --- /dev/null +++ b/core/engine/src/compiled/leaf/mask.rs @@ -0,0 +1,39 @@ +use super::{Bits, Leaf}; +use std::rc::Rc; + +#[derive(Clone, Debug)] +pub(crate) enum Mask<'a> { + Bits(Rc<[u64]>), + Valid(Leaf<'a>), + Picked(Rc<[u64]>, Rc<[usize]>), +} + +impl<'a> Mask<'a> { + pub fn get(&self, row: usize) -> bool { + match self { + Mask::Bits(bits) => Bits::get(bits, row), + Mask::Valid(leaf) => leaf.valid_at(row), + Mask::Picked(bits, positions) => { + positions.get(row).is_some_and(|&at| Bits::get(bits, at)) + } + } + } + + pub fn pick(&self, positions: &Rc<[usize]>) -> Mask<'a> { + match self { + Mask::Bits(bits) => Mask::Picked(bits.clone(), positions.clone()), + Mask::Valid(leaf) => Mask::Valid(leaf.pick(positions)), + Mask::Picked(bits, inner) => { + Mask::Picked(bits.clone(), positions.iter().map(|&i| inner[i]).collect()) + } + } + } + + pub fn dense(&self, rows: usize) -> Rc<[u64]> { + match self { + Mask::Bits(bits) => bits.clone(), + Mask::Valid(leaf) => leaf.validity(rows).into(), + Mask::Picked(..) => Bits::of(rows, |row| self.get(row)).into(), + } + } +} diff --git a/core/engine/src/compiled/leaf/mod.rs b/core/engine/src/compiled/leaf/mod.rs new file mode 100644 index 00000000..96181107 --- /dev/null +++ b/core/engine/src/compiled/leaf/mod.rs @@ -0,0 +1,18 @@ +mod array; +mod builder; +mod column; +mod dict; +mod literal; +mod mask; +mod records; +mod views; + +pub(crate) use array::{Array, Store}; +pub(crate) use builder::ColumnBuilder; +pub(crate) use column::Leaf; +pub(crate) use dict::Dict; +pub(crate) use literal::Literal; +pub(crate) use mask::Mask; +pub(crate) use records::{Field, Items, Records}; +pub(crate) use views::{Input, Masked, Picked, Scattered, Stitched, Templated}; +pub(crate) use zen_expression::lane::Bits; diff --git a/core/engine/src/compiled/leaf/records.rs b/core/engine/src/compiled/leaf/records.rs new file mode 100644 index 00000000..6cd68097 --- /dev/null +++ b/core/engine/src/compiled/leaf/records.rs @@ -0,0 +1,434 @@ +use super::{Bits, Dict, Leaf, Store}; +use std::cell::OnceCell; +use std::rc::Rc; +use zen_expression::lane::{Column, Dictionary, Values}; +use zen_expression::Variable; +use zen_types::symbol::Symbol; +use zen_types::variable::VariableMap; + +pub(crate) type Field<'a> = (Symbol, Leaf<'a>, Rc<[u64]>); +type Lanes = (Vec>, Option>); + +#[derive(Debug)] +pub(crate) struct Records<'a> { + pub(super) rows: usize, + pub(super) offsets: Vec, + pub(super) valid: Vec, + pub(super) fields: Vec>, + pub(super) nulled: Option>, + dense: OnceCell>, + lanes: OnceCell, + maker: OnceCell>, +} + +#[derive(Debug)] +pub(crate) struct Maker { + shapes: std::cell::RefCell>)>>, + cached: Vec>, +} + +type Decoded = (Rc<[i32]>, Vec); + +impl<'a> Records<'a> { + pub const LANE_VIEW: bool = true; + + pub fn spread(&self, positions: &[usize], rows: usize) -> Option> { + if positions.len() != self.rows + || positions.windows(2).any(|w| w[0] >= w[1]) + || positions.last().is_some_and(|&last| last >= rows) + { + return None; + } + let mut offsets = Vec::with_capacity(rows + 1); + let mut valid = vec![0u64; rows.div_ceil(64)]; + offsets.push(0i32); + for (at, &row) in positions.iter().enumerate() { + let start = *self.offsets.get(at)?; + offsets.resize(row + 1, start); + offsets.push(*self.offsets.get(at + 1)?); + Bits::set(&mut valid, row, Bits::get(&self.valid, at)); + } + let end = self.offsets.last().copied().unwrap_or(0); + offsets.resize(rows + 1, end); + Some(Records::new( + rows, + offsets, + valid, + self.fields.clone(), + self.nulled.clone(), + )) + } + + pub fn pick(&self, positions: &[usize]) -> Records<'a> { + let rows = positions.len(); + let mut offsets = Vec::with_capacity(rows + 1); + let mut valid = vec![0u64; rows.div_ceil(64)]; + let mut items: Vec = Vec::new(); + offsets.push(0i32); + for (at, &row) in positions.iter().enumerate() { + if let Some((start, end)) = self.range(row) { + Bits::set(&mut valid, at, true); + items.extend(start..end); + } + offsets.push(i32::try_from(items.len()).unwrap_or(i32::MAX)); + } + let items: Rc<[usize]> = items.into(); + let fields = self + .fields + .iter() + .map(|(key, leaf, present)| { + ( + key.clone(), + leaf.pick(&items), + Rc::from(Bits::gather(present, &items)), + ) + }) + .collect(); + let nulled = self + .nulled + .as_ref() + .map(|nulled| Rc::from(Bits::gather(nulled, &items))); + Records::new(rows, offsets, valid, fields, nulled) + } + + pub fn plain(&self) -> bool { + self.nulled.is_none() + } + + pub fn alive(&self, rows: usize) -> bool { + (0..rows.min(self.rows)).any(|row| self.valid(row)) + } + + pub fn new( + rows: usize, + offsets: Vec, + valid: Vec, + fields: Vec>, + nulled: Option>, + ) -> Records<'a> { + Records { + rows, + offsets, + valid, + fields, + nulled, + dense: OnceCell::new(), + lanes: OnceCell::new(), + maker: OnceCell::new(), + } + } + + fn maker(&self) -> Option<&Maker> { + self.maker + .get_or_init(|| { + if self.nulled.is_some() + || self.fields.len() > 64 + || self + .fields + .iter() + .any(|(key, _, _)| key.as_str().contains('.')) + { + return None; + } + let cached = self + .fields + .iter() + .map(|(_, leaf, _)| match leaf { + Leaf::Typed(array) => match (&array.values, &array.valid) { + (Store::Coded { codes, dict }, None) + if !matches!(**dict, Dict::Any(_)) => + { + let values = dict.dictionary(); + Some(( + codes.clone(), + (0..values.len()) + .map(|code| values.variable(code)) + .collect(), + )) + } + _ => None, + }, + _ => None, + }) + .collect(); + Some(Maker { + shapes: std::cell::RefCell::new(Vec::new()), + cached, + }) + }) + .as_ref() + } + + fn made(&self, maker: &Maker, item: usize) -> Variable { + let value = |(at, (_, leaf, _)): (usize, &Field<'a>)| match maker + .cached + .get(at) + .and_then(Option::as_ref) + { + Some((codes, values)) => codes + .get(item) + .and_then(|&code| usize::try_from(code).ok()) + .and_then(|code| values.get(code)) + .cloned() + .unwrap_or(Variable::Null), + None => leaf.get(item), + }; + let pattern = self + .fields + .iter() + .enumerate() + .fold(0u64, |bits, (at, (_, _, present))| { + bits | u64::from(Bits::get(present, item)) << at + }); + let found = maker + .shapes + .borrow() + .iter() + .find(|(p, _)| *p == pattern) + .map(|(_, shape)| shape.clone()); + let shape = match found { + Some(shape) => shape, + None => { + let mut map = VariableMap::with_capacity(self.fields.len()); + self.fields + .iter() + .enumerate() + .filter(|(at, _)| pattern >> at & 1 == 1) + .for_each(|(_, (key, _, _))| { + map.insert(key.clone(), Variable::Null); + }); + let shape = map + .shape() + .filter(|_| map.len() == pattern.count_ones() as usize) + .cloned(); + maker.shapes.borrow_mut().push((pattern, shape.clone())); + shape + } + }; + let present = self + .fields + .iter() + .enumerate() + .filter(|(at, _)| pattern >> at & 1 == 1); + match shape { + Some(shape) => { + Variable::from_object(VariableMap::from_shape(shape, present.map(value))) + } + None => { + let mut map = VariableMap::with_capacity(self.fields.len()); + for (at, field) in present { + map.insert(field.0.clone(), value((at, field))); + } + Variable::from_object(map) + } + } + } + + fn lanes(&self) -> &(Vec>, Option>) { + self.lanes.get_or_init(|| { + let count = self.count(); + let fields = self + .fields + .iter() + .map(|(_, leaf, present)| { + leaf.validity(count) + .iter() + .zip(present.iter()) + .map(|(v, p)| v & p) + .collect() + }) + .collect(); + let alive = self.nulled.as_ref().map(|nulled| { + let mut bits: Vec = nulled.iter().map(|w| !w).collect(); + bits.resize(count.div_ceil(64), u64::MAX); + Bits::trim(&mut bits, count); + bits + }); + (fields, alive) + }) + } + + pub fn parts(&self) -> Vec<(&str, Column<'_>)> { + let (valid, _) = self.lanes(); + self.fields + .iter() + .zip(valid) + .map(|((key, leaf, _), bits)| { + ( + key.as_str(), + Column { + values: leaf.column().values, + validity: Some((bits.as_slice(), 0)), + }, + ) + }) + .collect() + } + + pub fn item<'c>(&'c self, fields: &'c [(&'c str, Column<'c>)]) -> Column<'c> { + let (_, alive) = self.lanes(); + Column { + values: Values::Struct { + fields, + len: self.count(), + }, + validity: alive.as_ref().map(|bits| (bits.as_slice(), 0)), + } + } + + pub fn list<'c>(&'c self, item: &'c Column<'c>) -> Column<'c> { + Column { + values: Values::List { + offsets: &self.offsets, + child: Dictionary::Column(item), + }, + validity: Some((&self.valid, 0)), + } + } + + pub fn valid(&self, row: usize) -> bool { + Bits::get(&self.valid, row) + } + + pub fn range(&self, row: usize) -> Option<(usize, usize)> { + match self.valid(row) { + true => Some(( + usize::try_from(*self.offsets.get(row)?).ok()?, + usize::try_from(*self.offsets.get(row + 1)?).ok()?, + )), + false => None, + } + } + + pub fn count(&self) -> usize { + self.offsets + .last() + .and_then(|o| usize::try_from(*o).ok()) + .unwrap_or(0) + } + + pub fn fields(&self) -> &[Field<'a>] { + &self.fields + } + + pub fn offsets(&self) -> &[i32] { + &self.offsets + } + + pub fn validity(&self) -> &[u64] { + &self.valid + } + + pub fn object(fields: &[Field<'a>], item: usize) -> Variable { + if fields.iter().any(|(key, _, _)| key.as_str().contains('.')) { + let object = Variable::empty_object(); + for (key, leaf, present) in fields { + if Bits::get(present, item) { + object.dot_insert(key.as_str(), leaf.get(item)); + } + } + return object; + } + let mut map = VariableMap::with_capacity(fields.len()); + for (key, leaf, present) in fields { + if Bits::get(present, item) { + map.insert(key.clone(), leaf.get(item)); + } + } + Variable::from_object(map) + } + + pub fn get(&self, row: usize) -> Variable { + if let (Some(maker), Some((start, end))) = (self.maker(), self.range(row)) { + return Variable::from_array((start..end).map(|item| self.made(maker, item)).collect()); + } + match self.range(row) { + Some((start, end)) => Variable::from_array( + (start..end) + .map( + |item| match self.nulled.as_ref().is_some_and(|n| Bits::get(n, item)) { + true => Variable::Null, + false => Self::object(&self.fields, item), + }, + ) + .collect(), + ), + None => Variable::Null, + } + } + + pub(super) fn dense(&self) -> &Rc<[Variable]> { + self.dense + .get_or_init(|| (0..self.rows).map(|row| self.get(row)).collect()) + } +} + +pub(crate) enum Items<'a> { + Input { + column: Column<'a>, + mask: Option>, + }, + Records(Rc>), +} + +impl<'a> Items<'a> { + pub fn range(&self, row: usize) -> Option<(usize, usize)> { + match self { + Items::Input { column, mask } => { + match mask.as_ref().is_none_or(|m| Bits::get(m, row)) { + true => column.range(row), + false => None, + } + } + Items::Records(records) => records.range(row), + } + } + + pub fn count(&self) -> usize { + match self { + Items::Input { column, .. } => match column.values { + Values::List { child, .. } => child.column().len(), + _ => 0, + }, + Items::Records(records) => records.count(), + } + } + + pub fn fields(&self) -> Option>> { + match self { + Items::Records(records) if records.nulled.is_some() => None, + Items::Records(records) => Some(records.fields.clone()), + Items::Input { column, .. } => { + let Values::List { + child: Dictionary::Column(child), + .. + } = column.values + else { + return None; + }; + let Values::Struct { fields, len } = child.values else { + return None; + }; + let rows = child + .validity + .map(|(bits, offset)| Bits::window(bits, offset, len)); + Some( + fields + .iter() + .map(|(name, field)| { + let mut present = Bits::present(field.validity, len); + if let Some(rows) = &rows { + present.iter_mut().zip(rows).for_each(|(p, r)| *p &= r); + } + ( + Symbol::from(*name), + Leaf::input(*field, len), + Rc::from(present), + ) + }) + .collect(), + ) + } + } + } +} diff --git a/core/engine/src/compiled/leaf/views.rs b/core/engine/src/compiled/leaf/views.rs new file mode 100644 index 00000000..dab62b10 --- /dev/null +++ b/core/engine/src/compiled/leaf/views.rs @@ -0,0 +1,104 @@ +use super::{Bits, Leaf, Literal}; +use std::cell::OnceCell; +use std::rc::Rc; +use zen_expression::lane::Column; +use zen_expression::Variable; + +#[derive(Debug)] +pub(crate) struct Picked<'a> { + pub(super) source: Leaf<'a>, + pub(super) positions: Rc<[usize]>, + pub(super) dense: OnceCell>, +} + +#[derive(Debug)] +pub(crate) struct Stitched<'a> { + pub(super) sources: Vec>, + pub(super) located: Rc<[(usize, usize)]>, + pub(super) dense: OnceCell>, +} + +#[derive(Debug)] +pub(crate) struct Input<'a> { + pub column: Column<'a>, + pub rows: usize, + pub(super) valued: OnceCell>, +} + +#[derive(Debug)] +pub(crate) struct Masked<'a> { + pub(super) inner: Leaf<'a>, + pub(super) mask: Rc<[u64]>, + pub(super) bits: OnceCell>, +} + +impl Masked<'_> { + pub(super) fn bits(&self) -> &Rc<[u64]> { + self.bits.get_or_init(|| { + let rows = self.inner.len(); + let mut bits = self.inner.validity(rows); + bits.iter_mut() + .zip(self.mask.iter()) + .for_each(|(b, m)| *b &= m); + bits.iter_mut().skip(self.mask.len()).for_each(|b| *b = 0); + bits.into() + }) + } +} + +#[derive(Debug)] +pub(crate) struct Scattered<'a> { + pub(super) inner: Leaf<'a>, + pub(super) positions: Rc<[usize]>, + pub(super) rows: usize, + pub(super) dense: OnceCell>, +} + +#[derive(Debug)] +pub(crate) struct Templated { + pub(super) codes: Rc<[i32]>, + pub(super) templates: Rc<[Literal]>, + pub(super) valid: Vec, + dense: OnceCell>, +} + +impl Templated { + pub fn leaf<'a>(codes: Rc<[i32]>, templates: Rc<[Literal]>) -> Leaf<'a> { + let valid = Bits::of(codes.len(), |row| { + usize::try_from(codes[row]) + .ok() + .and_then(|code| templates.get(code)) + .is_some_and(|literal| !matches!(literal, Literal::Null)) + }); + Leaf::Templated(Rc::new(Templated { + codes, + templates, + valid, + dense: OnceCell::new(), + })) + } + + pub(super) fn template(&self, row: usize) -> Option<&Literal> { + let code = usize::try_from(*self.codes.get(row)?).ok()?; + self.templates + .get(code) + .filter(|literal| !matches!(literal, Literal::Null)) + } + + pub(super) fn get(&self, row: usize) -> Variable { + self.template(row).map_or(Variable::Null, Literal::variable) + } + + pub(super) fn mapped<'a>(&self, rows: impl Iterator) -> Leaf<'a> { + Templated::leaf( + rows.map(|row| self.codes.get(row).copied().unwrap_or(-1)) + .collect(), + self.templates.clone(), + ) + } + + pub(super) fn dense(&self) -> &Rc<[Variable]> { + self.dense + .get_or_init(|| (0..self.codes.len()).map(|row| self.get(row)).collect()) + } +} diff --git a/core/engine/src/compiled/lowered.rs b/core/engine/src/compiled/lowered.rs new file mode 100644 index 00000000..fa98161e --- /dev/null +++ b/core/engine/src/compiled/lowered.rs @@ -0,0 +1,167 @@ +use crate::compiled::leaf::{Array, Bits, Dict, Leaf, Store}; +use std::rc::Rc; +use zen_expression::typed::{Data, Hir, Outputs, Slot}; +use zen_expression::Variable; + +pub(crate) struct Exports { + dicts: Vec<(Vec, String)>, +} + +impl Exports { + pub fn enabled() -> bool { + crate::compiled::switches::SWITCHES.typed() + } + + pub fn of(hir: &Hir) -> Self { + let dicts = hir + .schema + .dicts + .iter() + .map(|dict| { + let mut offsets = vec![0i32]; + let mut data = String::new(); + for value in &dict.values { + data.push_str(value); + offsets.push(i32::try_from(data.len()).unwrap_or(i32::MAX)); + } + (offsets, data) + }) + .collect(); + Self { dicts } + } + + pub fn leaves<'a>(&self, out: &mut Outputs) -> Vec> { + let mut dicts = self.dictionaries(); + let mut leaves = Vec::with_capacity(out.slots().len()); + for at in 0..out.slots().len() { + if let Some(slot) = out.slot_mut(at) { + leaves.push(self.leaf(slot, &mut dicts)); + } + } + leaves + } + + pub fn leaf<'a>(&self, slot: &mut Slot, dicts: &mut [Option>]) -> Leaf<'a> { + if let Some(offsets) = slot.offsets.take() { + return self.items(slot, &offsets); + } + let len = slot.len; + let dict = slot.dict(); + let array = match &slot.data { + Data::Num { .. } if !slot.wide.is_empty() => { + return Leaf::Any( + (0..len) + .map(|at| slot.decimal(at).map_or(Variable::Null, Variable::Number)) + .collect(), + ); + } + Data::Num { .. } => match slot.take_num() { + Some((mut mant, mut scale, valid)) => { + let valid = Self::validity(valid, len); + if let Some(bits) = &valid { + for at in (0..len).filter(|&at| !Bits::get(bits, at)) { + mant[at] = 0; + scale[at] = 0; + } + } + Array::parts(Store::Scaled { mant, scale }, valid, len) + } + None => return Leaf::nulls(len), + }, + Data::Bool(_) => match slot.take_bool() { + Some((mut bits, valid)) => { + Bits::trim(&mut bits, len); + Array::parts(Store::Bool(bits), Self::validity(valid, len), len) + } + None => return Leaf::nulls(len), + }, + Data::Code(_) => { + let (Some((mut codes, valid)), Some(d)) = (slot.take_code(), dict) else { + return Leaf::nulls(len); + }; + let Some(dict) = self.dictionary(dicts, usize::from(d)) else { + return Leaf::nulls(len); + }; + match Self::validity(valid, len) { + None => Array::coded(codes.into(), dict), + Some(bits) => { + for at in (0..len).filter(|&at| !Bits::get(&bits, at)) { + codes[at] = -1; + } + Array::coded_with(codes.into(), dict, bits) + } + } + } + Data::Text { .. } => match slot.take_text() { + Some((offsets, data, valid)) => Array::parts( + Store::Text { offsets, data }, + Self::validity(valid, len), + len, + ), + None => return Leaf::nulls(len), + }, + Data::Date(_) => Array::from_values((0..len).map(|at| slot.variable(at)).collect()), + }; + Leaf::typed(array) + } + + fn items<'a>(&self, slot: &Slot, offsets: &[i32]) -> Leaf<'a> { + let text = |code: i32| -> Option<&str> { + let (offsets, data) = self.dicts.get(usize::from(slot.dict()?))?; + let at = usize::try_from(code).ok()?; + data.get( + usize::try_from(*offsets.get(at)?).ok()? + ..usize::try_from(*offsets.get(at + 1)?).ok()?, + ) + }; + let value = |at: usize| -> Variable { + match &slot.data { + Data::Num { .. } => slot.decimal(at).map_or(Variable::Null, Variable::Number), + Data::Bool(_) => slot.boolean(at).map_or(Variable::Null, Variable::Bool), + Data::Code(_) => slot + .code(at) + .and_then(text) + .map_or(Variable::Null, |t| Variable::String(t.into())), + Data::Text { .. } => slot + .text(at) + .map_or(Variable::Null, |t| Variable::String(t.into())), + Data::Date(_) => slot.variable(at), + } + }; + Leaf::Any( + offsets + .windows(2) + .map(|w| { + let (lo, hi) = ( + usize::try_from(w[0]).unwrap_or(0), + usize::try_from(w[1]).unwrap_or(0), + ); + Variable::from_array((lo..hi).map(value).collect()) + }) + .collect(), + ) + } + + pub fn dictionaries(&self) -> Vec>> { + vec![None; self.dicts.len()] + } + + fn dictionary(&self, dicts: &mut [Option>], at: usize) -> Option> { + let slot = dicts.get_mut(at)?; + if slot.is_none() { + let (offsets, data) = self.dicts.get(at)?; + *slot = Some(Rc::new(Dict::Text { + offsets: offsets.clone(), + data: data.clone(), + })); + } + slot.clone() + } + + fn validity(mut valid: Vec, len: usize) -> Option> { + valid.resize(len.div_ceil(64), 0); + Bits::trim(&mut valid, len); + let full = valid.iter().map(|w| w.count_ones() as usize).sum::() == len; + (!full).then_some(valid) + } +} diff --git a/core/engine/src/compiled/mod.rs b/core/engine/src/compiled/mod.rs new file mode 100644 index 00000000..a58346e7 --- /dev/null +++ b/core/engine/src/compiled/mod.rs @@ -0,0 +1,17 @@ +pub(crate) mod bound; +pub(crate) mod census; +mod core; +pub(crate) mod exact; +mod graph; +mod leaf; +mod lowered; +mod output; +pub(crate) mod policy; +mod shred; +pub(crate) mod switches; +pub(crate) mod table; + +pub use graph::ColumnarOutput; +pub(crate) use graph::{call, traced, CompiledGraph, CompiledPlan, Invalid}; +pub use output::{OutputColumn, RecordsView}; +pub(crate) use table::{Profile, Rows}; diff --git a/core/engine/src/compiled/output.rs b/core/engine/src/compiled/output.rs new file mode 100644 index 00000000..b0321ba9 --- /dev/null +++ b/core/engine/src/compiled/output.rs @@ -0,0 +1,52 @@ +use crate::compiled::leaf::Leaf; +use std::sync::Arc; +use zen_expression::lane::Column; +use zen_expression::Variable; + +pub struct OutputColumn<'a>(pub(crate) Leaf<'a>); + +pub struct RecordsView<'c> { + pub offsets: &'c [i32], + pub valid: Vec, + pub fields: Vec<(&'c str, Column<'c>, &'c [u64])>, +} + +impl OutputColumn<'_> { + pub fn column(&self) -> Column<'_> { + self.0.column() + } + + pub fn records(&self) -> Option> { + let records = match &self.0 { + Leaf::Records(records) => records, + _ => return None, + }; + Some(RecordsView { + offsets: records.offsets(), + valid: records.validity().to_vec(), + fields: records + .fields() + .iter() + .map(|(key, leaf, present)| (key.as_str(), leaf.column(), present.as_ref())) + .collect(), + }) + } + + pub fn get(&self, row: usize) -> Variable { + self.0.get(row) + } + + pub(crate) fn row(columns: &[(Arc, OutputColumn)], row: usize) -> Variable { + let object = Variable::empty_object(); + for (path, column) in columns { + match (path.is_empty(), column.get(row)) { + (_, Variable::Null) => {} + (true, value) => return value, + (false, value) => { + object.dot_insert(path, value); + } + } + } + object + } +} diff --git a/core/engine/src/compiled/policy/columnar/blocks.rs b/core/engine/src/compiled/policy/columnar/blocks.rs new file mode 100644 index 00000000..a553a790 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/blocks.rs @@ -0,0 +1,334 @@ +use super::{Chosen, Pass}; +use crate::compiled::leaf::{Array, Bits, ColumnBuilder, Leaf, Literal}; +use crate::compiled::policy::Native; +use crate::policy::blocks::{AssertionIr, MatchIr}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{LaneProgram, Scaled, Values}; +use zen_expression::Variable; + +impl<'s, 'a> Pass<'s, 'a> { + pub(super) fn expression( + &mut self, + key: &Arc, + program: &LaneProgram, + positions: &[usize], + ) { + let (leaf, failed) = self.run(program, positions); + self.fail(positions, &failed); + self.write(key, leaf, positions); + } + + pub(super) fn assertion( + &mut self, + ir: &AssertionIr, + conditions: &[LaneProgram], + positions: &[usize], + ) { + let mut truths: Vec> = Vec::with_capacity(conditions.len()); + for program in conditions { + let (leaf, failed) = self.run(program, positions); + self.fail(positions, &failed); + truths.push(leaf.truths(positions.len())); + } + let bits = Self::folded(ir, &truths, positions.len()); + let leaf = Leaf::typed(Array::parts( + crate::compiled::leaf::Store::Bool(bits), + None, + positions.len(), + )); + self.write(&ir.output, leaf, positions); + } + + pub(super) fn folded(ir: &AssertionIr, truths: &[Vec], count: usize) -> Vec { + let width = truths.len(); + if width > 6 { + let mut results = vec![false; width]; + return Bits::of(count, |at| { + results + .iter_mut() + .zip(truths) + .for_each(|(r, t)| *r = Bits::get(t, at)); + ir.fold(&results) + }); + } + let mut results = vec![false; width]; + let table = (0..1usize << width).fold(0u64, |table, combo| { + results + .iter_mut() + .enumerate() + .for_each(|(c, r)| *r = combo >> c & 1 == 1); + table | u64::from(ir.fold(&results)) << combo + }); + match table { + 0 => vec![0; count.div_ceil(64)], + _ => Bits::of(count, |at| { + let combo = truths.iter().enumerate().fold(0usize, |combo, (c, t)| { + combo | usize::from(Bits::get(t, at)) << c + }); + table >> combo & 1 == 1 + }), + } + } + + fn dict(values: &[Variable]) -> crate::compiled::leaf::Dict { + use crate::compiled::leaf::Dict; + if values.iter().all(|v| matches!(v, Variable::String(_))) { + let mut offsets = vec![0i32]; + let mut data = String::new(); + for value in values { + data.push_str(value.as_str().unwrap_or_default()); + offsets.push(data.len() as i32); + } + return Dict::Text { offsets, data }; + } + let scaled: Option> = values + .iter() + .map(|v| match v { + Variable::Number(n) => Scaled::parts(n), + _ => None, + }) + .collect(); + if let Some(parts) = scaled { + return Dict::Scaled { + mant: parts.iter().map(|p| p.0).collect(), + scale: parts.iter().map(|p| p.1).collect(), + }; + } + if values.iter().all(|v| matches!(v, Variable::Bool(_))) { + return Dict::Bool(Bits::of(values.len(), |i| { + matches!(values[i], Variable::Bool(true)) + })); + } + Dict::Any(values.to_vec()) + } + + pub(super) fn coded(values: &[Variable], codes: Vec) -> Leaf<'a> { + let mut valid: Vec = codes + .chunks(64) + .map(|chunk| { + chunk + .iter() + .enumerate() + .fold(0u64, |word, (at, code)| word | u64::from(*code >= 0) << at) + }) + .collect(); + Bits::trim(&mut valid, codes.len()); + Leaf::typed(Array::coded_with( + codes.into(), + Rc::new(Self::dict(values)), + valid, + )) + } + + pub(super) fn arms_of(leaf: &Leaf, count: usize) -> Vec> { + let column = leaf.column(); + if let Values::Scaled { mant, scale } = column.values { + if mant.len() >= count && scale.len() >= count && scale[..count].iter().all(|s| *s == 0) + { + return mant[..count] + .iter() + .map(|m| usize::try_from(*m).ok()) + .collect(); + } + } + (0..count) + .map(|at| { + column + .number(at) + .and_then(|n| i64::try_from(n).ok()) + .and_then(|n| usize::try_from(n).ok()) + }) + .collect() + } + + pub(super) fn select( + &mut self, + block: usize, + conditions: &[Option], + pick: Option<&LaneProgram>, + positions: &[usize], + ) { + let mut chosen: Vec> = vec![None; self.sheet.rows]; + if let Some(pick) = pick { + let (leaf, failed) = self.run(pick, positions); + self.fail(positions, &failed); + for (&row, arm) in positions.iter().zip(Self::arms_of(&leaf, positions.len())) { + chosen[row] = arm; + } + match self.arms.get_mut(block) { + Some(arms) => positions.iter().for_each(|&row| arms[row] = chosen[row]), + None => self.arms.insert(block, chosen), + } + return; + } + let mut open: Vec = positions.to_vec(); + for (arm, condition) in conditions.iter().enumerate() { + if open.is_empty() { + break; + } + let Some(program) = condition else { + open.drain(..).for_each(|row| chosen[row] = Some(arm)); + break; + }; + let (leaf, failed) = self.run(program, &open); + self.fail(&open, &failed); + let mut next = Vec::with_capacity(open.len()); + for (at, &row) in open.iter().enumerate() { + match leaf.truthy(at) { + true => chosen[row] = Some(arm), + false => next.push(row), + } + } + open = next; + } + match self.arms.get_mut(block) { + Some(arms) => positions.iter().for_each(|&row| arms[row] = chosen[row]), + None => self.arms.insert(block, chosen), + } + } + + pub(super) fn arm(&self, block: usize, row: usize) -> Option { + self.arms.get(block).and_then(|arms| arms[row]) + } + + pub(super) fn constant(values: &[Option], constants: &[Option]) -> bool { + values + .iter() + .enumerate() + .all(|(arm, value)| value.is_none() || constants.get(arm).is_some_and(Option::is_some)) + } + + pub(super) fn fixed(constants: &[Option]) -> Vec { + constants + .iter() + .map(|c| c.as_ref().map_or(Variable::Null, Literal::variable)) + .collect() + } + + pub(super) fn code(arm: Option, values: &[Option]) -> i32 { + arm.filter(|&arm| values.get(arm).is_some_and(Option::is_some)) + .map_or(-1, |arm| arm as i32) + } + + pub(super) fn commit( + &mut self, + block: usize, + ir: &MatchIr, + values: &[Option], + constants: &[Option], + positions: &[usize], + ) { + if Self::constant(values, constants) { + let codes: Vec = match self.arms.get(block) { + Some(arms) => positions + .iter() + .map(|&row| Self::code(arms[row], values)) + .collect(), + None => vec![-1; positions.len()], + }; + self.write( + &ir.key, + Self::coded(&Self::fixed(constants), codes), + positions, + ); + return; + } + let mut groups: Vec> = vec![Vec::new(); ir.arms.len()]; + for (local, &row) in positions.iter().enumerate() { + if let Some(arm) = self.arm(block, row).filter(|&arm| values[arm].is_some()) { + groups[arm].push(local); + } + } + if groups.iter().enumerate().all(|(arm, locals)| { + locals.is_empty() || constants.get(arm).is_some_and(Option::is_some) + }) { + let values: Vec = constants + .iter() + .map(|c| c.as_ref().map_or(Variable::Null, Literal::variable)) + .collect(); + let mut codes = vec![-1i32; positions.len()]; + for (arm, locals) in groups.iter().enumerate() { + locals.iter().for_each(|&local| codes[local] = arm as i32); + } + self.write(&ir.key, Self::coded(&values, codes), positions); + return; + } + let mut out: Vec = vec![Variable::Null; positions.len()]; + for (arm, locals) in groups.iter_mut().enumerate() { + if let Some(Some(value)) = constants.get(arm) { + let value = value.variable(); + locals + .drain(..) + .for_each(|local| out[local] = value.clone()); + } + } + for (arm, locals) in groups.into_iter().enumerate() { + let Some(program) = values[arm].as_ref().filter(|_| !locals.is_empty()) else { + continue; + }; + let members: Vec = locals.iter().map(|&local| positions[local]).collect(); + let (leaf, failed) = self.run(program, &members); + self.fail(&members, &failed); + for (i, &local) in locals.iter().enumerate() { + out[local] = leaf.get(i); + } + } + let mut builder = ColumnBuilder::with_capacity(out.len()); + out.into_iter() + .for_each(|value| builder.push_variable(value)); + self.write(&ir.key, Leaf::typed(builder.finish()), positions); + } + + pub(super) fn selection(&self, block: usize, row: usize) -> Option> { + let code = |arm: Option| arm.map_or(0, |arm| arm as u32 + 1); + if let Some(at) = self.entity_of(block) { + if let (Some(arms), Some(Native::Match { .. })) = + (self.members.get(block), Self::native(self.plan, block)) + { + let (a, b) = self.sheet.entities[at].frame.range(row).unwrap_or((0, 0)); + let mut key: Vec = (a..b) + .map(|child| code(arms.get(child).copied().flatten())) + .collect(); + key.sort_unstable(); + key.dedup(); + key.insert(0, 1); + return Some(key); + } + } + if let (Some(table), false) = (&self.plan.plans[block].table, self.hosted(block, row)) { + if let Some(Chosen { firsts, matched }) = self.chosen.get(block) { + let outputs = table.picked().len().max(1); + let words = table.words(); + let unit = |unit: usize| -> Vec { + let rules = matched + .get(unit * words..(unit + 1) * words) + .unwrap_or_default(); + (0..outputs) + .map(|c| firsts.get(unit * outputs + c).copied().unwrap_or(u32::MAX)) + .chain(rules.iter().flat_map(|w| [*w as u32, (*w >> 32) as u32])) + .collect() + }; + let mut units: Vec> = match self.entity_of(block) { + None => vec![unit(row)], + Some(at) => { + let (a, b) = self.sheet.entities[at].frame.range(row).unwrap_or((0, 0)); + (a..b).map(unit).collect() + } + }; + units.sort_unstable(); + units.dedup(); + let mut key = vec![2]; + key.extend(units.into_iter().flatten()); + return Some(key); + } + } + if self.state.picked(row, block).is_some() { + return None; + } + match self.plan.plans[block].native() { + Some(Native::Match { .. }) => Some(vec![3, code(self.arm(block, row))]), + _ => None, + } + } +} diff --git a/core/engine/src/compiled/policy/columnar/by_block.rs b/core/engine/src/compiled/policy/columnar/by_block.rs new file mode 100644 index 00000000..fa340648 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/by_block.rs @@ -0,0 +1,77 @@ +pub(super) struct ByBlock(Vec<(usize, T)>); + +impl Default for ByBlock { + fn default() -> Self { + Self(Vec::new()) + } +} + +impl ByBlock { + pub fn get(&self, block: usize) -> Option<&T> { + self.0 + .iter() + .find(|(b, _)| *b == block) + .map(|(_, value)| value) + } + + pub fn get_mut(&mut self, block: usize) -> Option<&mut T> { + self.0 + .iter_mut() + .find(|(b, _)| *b == block) + .map(|(_, value)| value) + } + + pub fn has(&self, block: usize) -> bool { + self.0.iter().any(|(b, _)| *b == block) + } + + pub fn insert(&mut self, block: usize, value: T) { + self.0.push((block, value)); + } + + pub fn entry(&mut self, block: usize, make: impl FnOnce() -> T) -> &mut T { + let at = match self.0.iter().position(|(b, _)| *b == block) { + Some(at) => at, + None => { + self.0.push((block, make())); + self.0.len() - 1 + } + }; + &mut self.0[at].1 + } +} + +pub(super) struct Chosen { + pub firsts: Vec, + pub matched: Vec, +} + +pub(super) struct Fallback { + rows: Vec, + fell: usize, +} + +impl Fallback { + pub fn new(rows: Vec) -> Self { + Self { rows, fell: 0 } + } + + pub fn fall(&mut self, row: usize) { + if !self.rows[row] { + self.rows[row] = true; + self.fell += 1; + } + } + + pub fn fallen(&self, row: usize) -> bool { + self.rows[row] + } + + pub fn fell(&self) -> usize { + self.fell + } + + pub fn rows(self) -> Vec { + self.rows + } +} diff --git a/core/engine/src/compiled/policy/columnar/evaluate.rs b/core/engine/src/compiled/policy/columnar/evaluate.rs new file mode 100644 index 00000000..c149a33c --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/evaluate.rs @@ -0,0 +1,386 @@ +use super::output::{from_results, output}; +use super::{ByBlock, Fallback, Pass, Sheet}; +use crate::compiled::policy::entity::Entity; +use crate::compiled::policy::{PolicyPlan, Rows}; +use crate::compiled::shred::{Shred, Shredder}; +use crate::compiled::ColumnarOutput; +use crate::diagnostics::Paths; +use crate::policy::evaluator::{EvalArtifact, Iteration}; +use crate::workspace::types::{EvaluateRequest, EvaluationError}; +use std::cell::{OnceCell, RefCell}; +use std::sync::Arc; +use zen_expression::lane::{Columns, Kind as LaneKind, LaneProgram}; +use zen_expression::Variable; +use zen_types::path::DotPath; + +impl PolicyPlan { + pub(super) fn scalar(program: &LaneProgram) -> bool { + let p = program.program(); + let regs = match p.outputs.is_empty() { + true => std::slice::from_ref(&p.out), + false => p.outputs.as_slice(), + }; + regs.iter().all(|r| { + matches!( + p.kinds.get(*r as usize), + Some(LaneKind::Num | LaneKind::Bool | LaneKind::Str) + ) + }) + } + + fn safe(&self, artifact: &EvalArtifact) -> &[Iteration] { + self.safe.get_or_init(|| { + let mut found: Vec = Vec::new(); + for (name, path, owner) in self.plans.iter().filter_map(|plan| plan.iteration.as_ref()) + { + if !found.iter().any(|(_, p, _)| p == path) { + found.push((name.clone(), path.clone(), owner.clone())); + } + } + found.retain(|(name, path, _)| { + self.members_safe(name, path) && self.readers_safe(artifact, path) + }); + found + }) + } + + fn entities<'a>(&self, artifact: &EvalArtifact, sheet: &Sheet<'a>) -> Vec> { + if !artifact.reference_fields.is_empty() { + return Vec::new(); + } + self.safe(artifact) + .iter() + .filter_map(|(name, path, owner)| { + let (name, path, owner) = (name.clone(), path.clone(), owner.clone()); + let entry = sheet + .entries + .iter() + .position(|e| e.input && e.path == path)?; + if sheet + .entries + .iter() + .any(|e| Sheet::related(&e.path, &path) == Some(std::cmp::Ordering::Greater)) + { + return None; + } + Entity::new( + name.clone(), + path.clone(), + owner.clone(), + entry, + sheet.inputs[entry], + ) + .or_else(|| { + Shred::of(&sheet.inputs[entry], sheet.rows) + .map(|shred| Entity::shredded(name, path, owner, entry, shred)) + }) + }) + .collect() + } + + fn dated_tables(&self, artifact: &EvalArtifact) -> bool { + *self.dated_tables.get_or_init(|| { + let schema = &artifact.input_schema; + schema.has_dates() + && self.plans.iter().any(|plan| { + let Some(table) = &plan.table else { + return false; + }; + let alias = plan.iteration.as_ref().map(|(name, path, _)| (name, path)); + table.fields().any(|field| { + field.program().site_keys.iter().flatten().any(|key| { + let key = match alias.and_then(|(name, path)| { + DotPath::tail(key, name).map(|rest| format!("{path}.{rest}")) + }) { + Some(mapped) => mapped, + None => key.clone(), + }; + schema.dates_at(&key).is_some() + }) + }) + }) + }) + } + + fn members_safe(&self, name: &str, path: &str) -> bool { + let prefix = format!("{name}."); + self.plans.iter().enumerate().all(|(block, plan)| { + let Some((_, own, _)) = &plan.iteration else { + return true; + }; + if Sheet::related(own, path) == Some(std::cmp::Ordering::Greater) { + return false; + } + if own.as_ref() != path { + return true; + } + if plan.member.is_none() && plan.table.is_none() { + return false; + } + let Some((programs, keys)) = Pass::block(self, block) else { + return false; + }; + let keyed = keys.iter().all(|key| { + key.is_empty() + || key + .strip_prefix(prefix.as_str()) + .is_some_and(|f| !f.is_empty()) + }); + keyed + && programs.iter().all(|program| { + program + .program() + .site_keys + .iter() + .all(|k| match k.as_deref() { + None => true, + Some(k) if k == name || k.starts_with('$') => false, + Some(k) if k == path => Pass::siblings(program, path, name, &keys), + Some(k) => match k.strip_prefix(prefix.as_str()) { + Some(field) => !field.is_empty(), + None => Sheet::related(k, path).is_none(), + }, + }) + }) + }) + } + + fn readers_safe(&self, artifact: &EvalArtifact, path: &str) -> bool { + self.blocks.rules.iter().enumerate().all(|(block, rule)| { + if self.plans[block] + .iteration + .as_ref() + .is_some_and(|(_, own, _)| own.as_ref() == path) + { + return true; + } + let writes = rule + .kind + .write_sites() + .iter() + .any(|site| Sheet::related(&site.path, path).is_some()); + let reads = artifact + .reads + .get(&self.blocks.refs[block]) + .map_or(Vec::new(), |reads| { + reads + .iter() + .filter_map(|read| Sheet::related(&read.path, path)) + .collect::>() + }); + if writes || reads.contains(&std::cmp::Ordering::Less) { + return false; + } + reads.is_empty() + || matches!( + ( + self.plans[block].native(), + self.plans[block].iterated, + &self.plans[block].table, + &self.plans[block].iteration + ), + (Some(_), false, _, None) | (None, _, Some(_), None) + ) + }) + } + + pub(crate) fn evaluate_columns<'a>( + &self, + artifact: &EvalArtifact, + policy_path: &Arc, + goals: &[Arc], + columns: &'a Columns<'a>, + ) -> ColumnarOutput<'a> { + let rows = columns.rows; + let request = |row: usize| EvaluateRequest { + policy_path: policy_path.clone(), + input: columns.row(row), + goals: goals.to_vec(), + trace: false, + }; + let sheet = Sheet::new(columns); + let Some(mut sheet) = sheet else { + let requests: Vec = (0..rows).map(request).collect(); + return from_results(rows, self.evaluate(artifact, &requests)); + }; + let mut errors: Vec> = (0..rows).map(|_| None).collect(); + let stores: Vec> = (0..rows).map(|_| OnceCell::new()).collect(); + sheet.entities = self.entities(artifact, &sheet); + sheet.refs = artifact + .reference_fields + .iter() + .map(|field| field.path.clone()) + .collect(); + let shared = !artifact.reference_fields.is_empty() + || self.plans.iter().any(|plan| match &plan.iteration { + Some((_, path, _)) => !sheet.entities.iter().any(|e| e.path == *path), + None => plan.native().is_none() && plan.table.is_none(), + }); + if shared { + sheet.entities.clear(); + } + let dated = match shared || self.dated_tables(artifact) { + true => vec![false; rows], + false => sheet.dates(&artifact.input_schema), + }; + let mut fallback = vec![false; rows]; + let mut erred = false; + let sure = match shared { + true => None, + false => Entity::sure(artifact, columns, &sheet.entities, goals), + }; + sheet + .entities + .iter() + .filter_map(|entity| entity.hosted.as_deref()) + .flatten() + .for_each(|&row| fallback[row] = true); + for row in 0..rows { + if !dated[row] && sure.as_ref().is_some_and(|sure| sure[row]) { + continue; + } + let req = request(row); + if !dated[row] && artifact.input_schema.convert_dates(&req.input).is_some() { + fallback[row] = true; + continue; + } + match artifact.prepare(&req) { + Err(error) => { + errors[row] = Some(error); + erred = true; + } + Ok((store, _)) if shared => { + let _ = stores[row].set(store); + } + Ok(_) => {} + } + } + let base = sheet.entries.len(); + let settled = !fallback.contains(&true); + let live: Vec = match (erred, settled) { + (true, _) => (0..rows) + .filter(|&row| errors[row].is_none() && !fallback[row]) + .collect(), + (false, true) => (0..rows).collect(), + (false, false) => (0..rows).filter(|&row| !fallback[row]).collect(), + }; + let mut runner = Self::RUNNER.with_borrow_mut(std::mem::take); + let (sheet, fallback, errors, owned, fell, counts) = { + let runner = &mut runner; + let mut pass = Pass { + plan: self, + artifact, + entry: policy_path, + sheet, + runner, + fallback: Fallback::new(fallback), + arms: ByBlock::default(), + stores: &stores, + state: Rows { + hosts: Vec::new(), + picks: Vec::new(), + failures: errors, + }, + synced: vec![0; rows], + shared, + base, + chosen: ByBlock::default(), + members: ByBlock::default(), + hosting: ByBlock::default(), + kin: Vec::new(), + delegated: false, + counts: Paths::default(), + listed: RefCell::new(Vec::new()), + owners: self + .plans + .iter() + .map(|plan| plan.iteration.as_ref().map(|(_, path, _)| path.clone())) + .collect(), + }; + pass.walk(self.root.clone(), live); + let owning = |row: usize| { + pass.state.hosts.get(row).is_some_and(Option::is_some) + || pass.stores[row].get().is_some() + }; + let owns = (0..rows).any(owning); + if owns { + (0..pass.sheet.entities.len()).for_each(|at| pass.sheet.retire(at)); + } + let owned: Vec> = match owns { + false => Vec::new(), + true => (0..rows) + .map(|row| { + match pass.state.hosts.get(row).is_some_and(Option::is_some) + || pass.stores[row].get().is_some() + { + true => pass + .host(row) + .map(|host| host.state.env().shallow_clone()) + .and(pass.stores[row].get().cloned()), + false => None, + } + }) + .collect(), + }; + erred |= pass.delegated; + let fell = pass.fallback.fell(); + ( + pass.sheet, + pass.fallback.rows(), + pass.state.failures, + owned, + fell, + pass.counts, + ) + }; + Self::RUNNER.with_borrow_mut(|slot| *slot = runner); + let mut errors = errors; + let clean = |row: usize| !erred || errors[row].is_none(); + let (hosted, finished): (Vec, Vec) = match settled && fell == 0 && !erred { + true => (Vec::new(), (0..rows).collect()), + false => ( + (0..rows) + .filter(|&row| fallback[row] && clean(row)) + .collect(), + (0..rows) + .filter(|&row| !fallback[row] && clean(row)) + .collect(), + ), + }; + if hosted.is_empty() && owned.iter().all(Option::is_none) { + let columns = sheet.output(&finished); + return output( + rows, + columns, + errors, + Paths { + hosted: 0, + ..counts + }, + ); + } + let requests: Vec = hosted.iter().map(|&row| request(row)).collect(); + let mut shredder = Shredder::new(rows); + for &row in &finished { + match owned.get(row) { + Some(Some(store)) => shredder.visit(store, 0, row), + _ => shredder.visit(&sheet.object(row), 0, row), + } + } + for (&row, result) in hosted.iter().zip(self.evaluate(artifact, &requests)) { + match result { + Ok(result) => shredder.visit(&result.output, 0, row), + Err(error) => errors[row] = Some(error), + } + } + output( + rows, + shredder.output(), + errors, + Paths { + hosted: hosted.len(), + ..counts + }, + ) + } +} diff --git a/core/engine/src/compiled/policy/columnar/fuse.rs b/core/engine/src/compiled/policy/columnar/fuse.rs new file mode 100644 index 00000000..72add038 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/fuse.rs @@ -0,0 +1,796 @@ +use super::typed::{Typed, TypedGroup}; +use super::{Pass, Sheet}; +use crate::compiled::census::Census; +use crate::compiled::core::fuse::{Fused, Runs}; +use crate::compiled::core::variants::Variants; +use crate::compiled::leaf::{Array, Bits, Leaf, Store}; +use crate::compiled::lowered::Exports; +use crate::compiled::policy::schedule::{End, Event, Segment}; +use crate::compiled::policy::{Native, PolicyPlan}; +use crate::compiled::table::TableIr; +use crate::policy::blocks::{AssertionIr, BlockKind, ConditionOperator, DecisionTableIr, MatchIr}; +use std::cmp::Ordering; +use std::rc::Rc; +use std::sync::{Arc, RwLock}; +use std::time::Instant; +use zen_expression::lane::{Fusion, LaneProgram}; +use zen_expression::typed::TableSpec; +use zen_types::path::DotPath; + +type Groups = ahash::HashMap>>; +type Lanes = ahash::HashMap, Option>>>; + +#[derive(Default)] +pub(crate) struct Fusions { + groups: RwLock, + effects: RwLock>>>, + tables: RwLock>, + runs: Runs, + pub(super) typed: RwLock, +} + +pub(crate) struct Effects { + reads: Vec>, + writes: Vec>, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +pub(super) struct Chain { + pub blocks: Vec, + pub member: bool, +} + +impl Chain { + pub fn of(blocks: &[usize], member: bool) -> Self { + Self { + blocks: blocks.to_vec(), + member, + } + } +} + +#[derive(Clone, Copy)] +pub(super) struct Span { + pub block: usize, + pub start: usize, + pub len: usize, +} + +struct Item { + units: Vec, + domain: Option>, + written: Vec<(Arc, bool)>, +} + +pub(super) enum Sink { + Write(Arc), + Assert(Arc), +} + +struct Unit<'p> { + entity: Option, + programs: Vec<&'p LaneProgram>, + writes: Vec<(Arc, bool)>, +} + +impl Fusions { + fn table(&self, block: usize, ir: &DecisionTableIr) -> bool { + if let Some(found) = self + .tables + .read() + .ok() + .and_then(|cache| cache.get(&block).copied()) + { + return found; + } + let fusable = Fused::::fusable(ir); + if let Ok(mut cache) = self.tables.write() { + cache.insert(block, fusable); + } + fusable + } + + fn effects(&self, plan: &PolicyPlan, block: usize) -> Option> { + if let Some(found) = self + .effects + .read() + .ok() + .and_then(|cache| cache.get(&block).cloned()) + { + return found; + } + let built = Effects::of(plan, block).map(Arc::new); + if let Ok(mut cache) = self.effects.write() { + cache.insert(block, built.clone()); + } + built + } + + fn get(&self, plan: &PolicyPlan, blocks: &[usize], member: bool) -> Option>> { + if let Some(found) = self + .groups + .read() + .ok() + .and_then(|cache| cache.get(blocks).cloned()) + { + return found; + } + let built = Fused::::compile(plan, blocks, member).map(Arc::new); + match self.groups.write() { + Ok(mut cache) => cache.entry(blocks.to_vec()).or_insert(built).clone(), + Err(_) => built, + } + } +} + +impl Effects { + fn of(plan: &PolicyPlan, block: usize) -> Option { + let (programs, _) = Pass::block(plan, block)?; + let rule = &plan.blocks.rules[block]; + let iteration = plan.plans[block].iteration.clone(); + if let Some((_, path, Some(owner))) = &iteration { + if path.split('.').next() != Some(owner.as_ref()) { + return None; + } + } + let alias = iteration.map(|(name, path, _)| (name, path)); + let map = |key: &str| -> Arc { + match &alias { + Some((name, path)) if key == name.as_ref() => path.clone(), + Some((name, path)) => match DotPath::tail(key, name) { + Some(rest) => Arc::from(format!("{path}.{rest}")), + None => Arc::from(key), + }, + None => Arc::from(key), + } + }; + let mut reads: Vec> = Vec::new(); + for program in programs { + let p = program.program(); + if p.writes_env || p.chain || p.opaque() || p.rows { + return None; + } + let mut keys: Vec<&str> = p.site_keys.iter().flatten().map(String::as_str).collect(); + keys.sort_unstable(); + keys.dedup(); + for key in keys { + if key.starts_with('$') || key.contains('[') { + return None; + } + match alias.is_none().then(|| p.source_fields(key)).flatten() { + Some(fields) => reads.extend( + fields + .iter() + .map(|field| Arc::from(format!("{key}.{field}"))), + ), + None => reads.push(map(key)), + } + } + } + let writes = rule + .kind + .write_sites() + .into_iter() + .map(|site| map(&site.path)) + .collect(); + Some(Self { reads, writes }) + } + + fn commute(&self, other: &Effects) -> bool { + let clash = |xs: &[Arc], ys: &[Arc]| { + xs.iter() + .any(|x| ys.iter().any(|y| Sheet::related(x, y).is_some())) + }; + !clash(&self.writes, &other.reads) + && !clash(&self.writes, &other.writes) + && !clash(&other.writes, &self.reads) + } +} + +impl Fused { + fn compile(plan: &PolicyPlan, blocks: &[usize], member: bool) -> Option { + let mut entries: Vec = Vec::new(); + let mut sinks = Vec::with_capacity(blocks.len()); + for &block in blocks { + if member && plan.plans[block].table.is_some() { + return None; + } + if member && Self::siblings(plan, block) { + return None; + } + let (unit, sunk) = Self::entries(plan, block, member)?; + entries.extend(unit); + sinks.extend(sunk); + } + Self::build(&entries, sinks) + } + + fn siblings(plan: &PolicyPlan, block: usize) -> bool { + let Some((_, path, _)) = &plan.plans[block].iteration else { + return false; + }; + Pass::block(plan, block).is_some_and(|(programs, _)| { + programs.iter().any(|program| { + program + .program() + .site_keys + .iter() + .flatten() + .any(|key| *key == **path) + }) + }) + } + + pub(super) fn entries( + plan: &PolicyPlan, + block: usize, + member: bool, + ) -> Option<(Vec, Vec)> { + let mut entries: Vec = Vec::new(); + let mut sinks = Vec::new(); + if let BlockKind::DecisionTable(ir) = &plan.blocks.rules[block].kind { + let (hidden, tables) = Self::table(ir, block)?; + entries.extend(hidden); + for entry in tables { + if let Fusion::Rules { key, .. } = &entry { + sinks.push(Sink::Write(Arc::from(key.as_str()))); + } + entries.push(entry); + } + return Some((entries, sinks)); + } + let native = match member { + true => Pass::native(plan, block)?, + false => plan.plans[block].native()?, + }; + match native { + Native::Expression { key, program } => { + entries.push(Fusion::Output { + key: key.to_string(), + source: program.source()?.to_string(), + }); + sinks.push(Sink::Write(key.clone())); + } + Native::Match { ir, .. } => { + entries.push(Fusion::Output { + key: ir.key.to_string(), + source: Self::ternary(ir), + }); + sinks.push(Sink::Write(ir.key.clone())); + } + Native::Assertion { ir, .. } => { + entries.extend(ir.conditions.iter().map(|c| Fusion::Output { + key: String::new(), + source: c.expression.to_string(), + })); + sinks.push(Sink::Assert(ir.clone())); + } + } + Some((entries, sinks)) + } + + fn fusable(ir: &DecisionTableIr) -> bool { + TableIr::policy(ir).filled() + } + + pub(super) fn spec(ir: &DecisionTableIr) -> Option { + TableIr::policy(ir).spec() + } + + fn table(ir: &DecisionTableIr, block: usize) -> Option<(Vec, Vec)> { + if !Self::fusable(ir) { + return None; + } + let mut hidden = Vec::new(); + let mut fields: Vec<(String, &Arc)> = Vec::new(); + for (index, input) in ir.inputs.iter().enumerate() { + if ir + .rules + .iter() + .all(|rule| rule.get(&input.id).is_none_or(|c| c.is_empty())) + { + continue; + } + let source = input.field.as_deref()?; + let plain = source.split('.').all(|segment| { + let mut chars = segment.chars(); + chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') + }); + let key = match plain { + true => source.to_string(), + false => { + let key = format!("__fuse{block}_{index}"); + hidden.push(Fusion::Hidden { + key: key.clone(), + source: source.to_string(), + }); + key + } + }; + fields.push((key, &input.id)); + } + let outputs = ir + .outputs + .iter() + .filter(|o| !o.field.is_empty()) + .map(|output| { + let rules = ir + .rules + .iter() + .map(|rule| { + let cells = fields + .iter() + .filter_map(|(key, id)| { + rule.get(*id) + .filter(|c| !c.is_empty()) + .map(|c| (key.clone(), c.to_string())) + }) + .collect(); + ( + cells, + rule.get(&output.id) + .map(|c| c.to_string()) + .unwrap_or_default(), + ) + }) + .collect(); + Fusion::Rules { + key: output.field.to_string(), + rules, + } + }) + .collect(); + Some((hidden, outputs)) + } + + fn ternary(ir: &MatchIr) -> String { + let mut source = String::new(); + let mut open = 0usize; + let mut tail = String::from("null"); + for arm in &ir.arms { + let value = match arm.value.is_empty() { + true => String::from("null"), + false => format!("({})", arm.value), + }; + if arm.condition.is_empty() { + tail = value; + break; + } + source.push_str(&format!("(({}) == true) ? {value} : (", arm.condition)); + open += 1; + } + source.push_str(&tail); + source.push_str(&")".repeat(open)); + source + } +} + +impl<'s, 'a> Pass<'s, 'a> { + pub(super) fn events(&mut self, segment: Arc, rows: &mut Vec) -> Arc { + let mut last = segment; + let mut events: Vec = last.events.clone(); + while let End::Branch { block, .. } = &last.end { + if !self.quiet(*block) { + break; + } + let next = self.plan.child(self.artifact, &last, Arc::from([])); + events.extend_from_slice(&next.events); + last = next; + } + let mut seen = Some(0); + let mut fresh = |pass: &mut Self, rows: &mut Vec| { + if seen != Some(pass.fallback.fell()) { + rows.retain(|&row| !pass.fallback.fallen(row)); + seen = Some(pass.fallback.fell()); + } + }; + fresh(self, rows); + let typed = Exports::enabled(); + for item in self.schedule(&events, rows) { + fresh(self, rows); + if rows.is_empty() { + break; + } + let blocks: Vec = item.units.iter().map(|span| span.block).collect(); + if let (Some(_), true) = (item.domain, typed) { + if let Some(entity) = self.regroup(&item, rows) { + let member = entity.is_some(); + let plan = self.plan; + let fusions = &plan.fusions; + let mut at = 0; + let mut laning: Option = None; + while at < item.units.len() { + fresh(self, rows); + if rows.is_empty() { + break; + } + let began = Census::on().then(|| (Instant::now(), rows.len())); + match self.typed(&item.units[at..], entity, rows) { + Typed::Ran(consumed, faulted) => { + if let Some((start, count)) = began { + Census::record( + "policy typed | group".into(), + count, + start.elapsed().as_nanos(), + ); + } + if let Some(from) = laning.take() { + fusions + .runs + .ran(Chain::of(&blocks[from..], member), at - from); + } + self.counts.typed += consumed; + if !faulted.is_empty() { + self.retry(&events, &item.units[at..at + consumed], faulted); + } + at += consumed; + continue; + } + Typed::Lane(group, path) => { + if let Some(from) = laning.take() { + fusions + .runs + .ran(Chain::of(&blocks[from..], member), at - from); + } + let (start, count) = (Instant::now(), rows.len()); + for span in &item.units[at..at + group.units] { + for event in &events[span.start..span.start + span.len] { + fresh(self, rows); + if rows.is_empty() { + break; + } + self.event(*event, rows); + } + } + group.cost.record(path, start.elapsed(), count); + self.counts.laned += group.units; + at += group.units; + continue; + } + Typed::Skipped => {} + } + let census = + Census::on().then(|| (Census::taken(), Instant::now(), rows.len())); + if laning.is_none() { + let run = fusions + .runs + .run(&Chain::of(&blocks[at..], member)) + .map_or(0, |run| run.min(blocks.len() - at)); + if let Some(fused) = (run > 1) + .then(|| fusions.get(plan, &blocks[at..at + run], member)) + .flatten() + { + self.fused(&fused, entity, rows); + self.counts.laned += run; + at += run; + if let Some((why, start, count)) = census { + Census::record( + format!("policy lane | fused | {why}"), + count, + start.elapsed().as_nanos(), + ); + } + continue; + } + laning = Some(at); + } + let span = item.units[at]; + for event in &events[span.start..span.start + span.len] { + fresh(self, rows); + if rows.is_empty() { + break; + } + self.event(*event, rows); + } + if let Some((why, start, count)) = census { + Census::record( + format!("policy lane | unit | {why}"), + count, + start.elapsed().as_nanos(), + ); + } + self.counts.laned += 1; + at += 1; + } + if let (Some(from), true) = (laning, at == item.units.len()) { + fusions + .runs + .ran(Chain::of(&blocks[from..], member), at - from); + } + continue; + } + } + self.counts.laned += item.units.len(); + let census = Census::on().then(|| (Instant::now(), rows.len(), item.domain.is_some())); + let group = match (item.domain, blocks.len() > 1) { + (Some(domain), true) => self.regroup(&item, rows).and_then(|entity| { + let fused = self + .plan + .fusions + .get(self.plan, &blocks, domain.is_some())?; + Some((fused, entity)) + }), + _ => None, + }; + match group { + Some((fused, entity)) => self.fused(&fused, entity, rows), + None => { + for span in &item.units { + for event in &events[span.start..span.start + span.len] { + fresh(self, rows); + if rows.is_empty() { + break; + } + self.event(*event, rows); + } + } + } + } + if let Some((start, count, domain)) = census { + Census::record( + format!("policy lane | whole item | domain {domain} typed {typed}"), + count, + start.elapsed().as_nanos(), + ); + } + } + fresh(self, rows); + last + } + + fn retry(&mut self, events: &[Event], units: &[Span], mut rows: Vec) { + for span in units { + for event in &events[span.start..span.start + span.len] { + rows.retain(|&row| !self.fallback.fallen(row)); + if rows.is_empty() { + return; + } + self.event(*event, &rows); + } + } + } + + fn regroup(&self, item: &Item, rows: &[usize]) -> Option> { + let mut entity = None; + for span in &item.units { + let unit = self.unit(span.block, span.len, rows)?; + if entity.is_some_and(|e| e != unit.entity) { + return None; + } + entity = Some(unit.entity); + } + entity + } + + fn schedule(&self, events: &[Event], rows: &[usize]) -> Vec { + let mut items: Vec = Vec::new(); + let mut at = 0; + while at < events.len() { + let (block, len) = match events[at..] { + [Event::Select(a), Event::Commit(b), ..] if a == b => (a, 2), + [Event::Select(b), ..] | [Event::Commit(b), ..] => (b, 1), + [] => break, + }; + let unit = match rows.is_empty() { + true => None, + false => self.unit(block, len, rows), + }; + let merged = unit.as_ref().is_some_and(|unit| { + self.merge( + &mut items, + Span { + block, + start: at, + len, + }, + unit, + ) + }); + if !merged { + items.push(Item { + units: vec![Span { + block, + start: at, + len, + }], + domain: unit.as_ref().map(|unit| unit.entity), + written: unit.map(|unit| unit.writes).unwrap_or_default(), + }); + } + at += len; + } + items + } + + fn merge(&self, items: &mut [Item], entry: Span, unit: &Unit) -> bool { + let Some(target) = items + .iter() + .rposition(|item| item.domain == Some(unit.entity)) + else { + return false; + }; + let effects = |block: usize| self.plan.fusions.effects(self.plan, block); + if target + 1 < items.len() { + let Some(own) = effects(entry.block) else { + return false; + }; + let free = items[target + 1..] + .iter() + .flat_map(|item| item.units.iter()) + .all(|other| effects(other.block).is_some_and(|theirs| own.commute(&theirs))); + if !free { + return false; + } + } + let item = &mut items[target]; + let reads = unit + .programs + .iter() + .flat_map(|p| p.program().site_keys.iter().flatten()); + let blocked = reads.clone().any(|key| { + item.written + .iter() + .any(|(w, readable)| match Sheet::related(key, w) { + None => false, + Some(Ordering::Equal | Ordering::Greater) => !readable, + Some(Ordering::Less) => true, + }) + }); + let nested = unit.writes.iter().any(|(key, _)| { + item.written.iter().any(|(w, _)| { + matches!( + Sheet::related(key, w), + Some(Ordering::Less | Ordering::Greater) + ) + }) + }); + if blocked || nested { + return false; + } + item.units.push(entry); + item.written.extend(unit.writes.iter().cloned()); + true + } + + fn unit(&self, block: usize, len: usize, rows: &[usize]) -> Option> { + let plan = self.plan; + if self.shared { + return None; + } + let (entity, programs, writes) = + match (&plan.plans[block].table, &plan.blocks.rules[block].kind) { + (Some(table), BlockKind::DecisionTable(ir)) => { + let entity = match self.owners[block] { + Some(_) if Exports::enabled() => { + let at = self.entity_of(block)?; + self.supported(at, block, rows).then_some(Some(at))? + } + Some(_) => return None, + None => None, + }; + let ready = len == 2 && self.quiet(block) && plan.fusions.table(block, ir); + let writes: Vec<(Arc, bool)> = table + .picked() + .iter() + .map(|o| (o.field.clone(), true)) + .collect(); + ready.then_some((entity, table.programs(), writes))? + } + (Some(_), _) => return None, + (None, _) => { + let entity = match self.owners[block] { + Some(_) => { + let at = self.entity_of(block)?; + self.supported(at, block, rows).then_some(Some(at))? + } + None => None, + }; + let native = match entity { + Some(_) => Pass::native(plan, block)?, + None if plan.plans[block].iterated => return None, + None => plan.plans[block].native()?, + }; + match (native, len) { + (Native::Expression { key, program }, 1) => { + (entity, vec![program.as_ref()], vec![(key.clone(), true)]) + } + (Native::Match { ir, .. }, 2) if self.quiet(block) => { + (entity, Pass::programs(native), vec![(ir.key.clone(), true)]) + } + (Native::Assertion { ir, conditions }, 1) => ( + entity, + conditions.iter().collect(), + vec![(ir.output.clone(), false)], + ), + _ => return None, + } + } + }; + let plain = programs.iter().all(|program| { + let p = program.program(); + !(p.writes_env || p.chain || p.opaque() || p.rows) + }); + let clear = entity.is_some() + || writes.iter().all(|(key, _)| { + !self + .sheet + .entities + .iter() + .any(|e| e.active && Sheet::related(key, &e.path).is_some()) + }); + (plain && clear).then_some(Unit { + entity, + programs, + writes, + }) + } + + fn conjunction(ir: &AssertionIr) -> bool { + let last = ir.conditions.len().saturating_sub(1); + !ir.conditions.is_empty() + && ir.conditions.iter().enumerate().all(|(at, c)| { + c.depth == 0 && (at == last || matches!(c.operator, ConditionOperator::And)) + }) + } + + fn fused(&mut self, fused: &Fused, entity: Option, rows: &[usize]) { + match entity { + None => { + let (leaves, failed) = self.run_outs(&fused.program, rows); + self.fail(rows, &failed); + self.sink(&fused.sinks, leaves, None, rows); + } + Some(at) => { + let (kids, parents) = self.kids(at, rows); + let (leaves, failed) = self.member_outs(at, &fused.program, &kids, &parents); + self.member_fail(&parents, &failed); + self.sink(&fused.sinks, leaves, Some((at, &kids)), rows); + } + } + } + + pub(super) fn sink( + &mut self, + sinks: &[Sink], + leaves: Vec>, + member: Option<(usize, &Rc<[usize]>)>, + rows: &[usize], + ) { + let count = member.map_or(rows.len(), |(_, kids)| kids.len()); + let mut leaves = leaves.into_iter(); + for sink in sinks { + let leaf = match sink { + Sink::Write(_) => leaves.next().unwrap_or_else(|| Leaf::nulls(count)), + Sink::Assert(ir) if member.is_none() && Self::conjunction(ir) => { + let mut bits = Bits::ones(count); + for leaf in leaves.by_ref().take(ir.conditions.len()) { + bits.iter_mut() + .zip(leaf.truths(count)) + .for_each(|(b, t)| *b &= t); + } + Leaf::typed(Array::parts(Store::Bool(bits), None, count)) + } + Sink::Assert(ir) => { + let truths: Vec> = leaves + .by_ref() + .take(ir.conditions.len()) + .map(|leaf| leaf.truths(count)) + .collect(); + let bits = Self::folded(ir, &truths, count); + Leaf::typed(Array::parts(Store::Bool(bits), None, count)) + } + }; + let key = match sink { + Sink::Write(key) => key, + Sink::Assert(ir) => &ir.output, + }; + match member { + None => self.write(key, leaf, rows), + Some((at, kids)) => self.member_write(at, key, leaf, kids), + } + } + } +} diff --git a/core/engine/src/compiled/policy/columnar/host.rs b/core/engine/src/compiled/policy/columnar/host.rs new file mode 100644 index 00000000..39da54a3 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/host.rs @@ -0,0 +1,143 @@ +use super::{Pass, Sheet}; +use crate::compiled::census::Census; +use crate::compiled::leaf::Bits; +use crate::compiled::policy::schedule::Event; +use crate::compiled::policy::{Host, Refused}; +use std::sync::Arc; +use std::time::Instant; +use zen_expression::Variable; + +impl<'s, 'a> Pass<'s, 'a> { + pub(super) fn host(&mut self, row: usize) -> Option<&mut Host<'s>> { + self.state.ensure(); + if self.state.hosts[row].is_none() { + let prepared = self.stores[row].get().is_some(); + let store = self.stores[row].get_or_init(|| self.sheet.object(row)); + self.state.hosts[row] = Some(Host::new( + self.artifact, + store, + self.entry, + false, + false, + &self.plan.programs, + )); + self.synced[row] = match prepared { + true => self.base, + false => self.sheet.entries.len(), + }; + } + let from = self.synced[row]; + self.synced[row] = self.sheet.entries.len(); + let host = self.state.hosts[row].as_mut()?; + for entry in &self.sheet.entries[from..] { + if Sheet::present(entry, row) { + host.state.write(&entry.path, entry.leaf.get(row)); + } + } + Some(host) + } + + fn readback(&self, block: usize) -> Vec> { + let rule = &self.plan.blocks.rules[block]; + let top = + |path: &str| -> Arc { Arc::from(path.split(['.', '[']).next().unwrap_or(path)) }; + let mut paths: Vec> = match &self.plan.plans[block].iteration { + Some((_, path, _)) => vec![top(path)], + None => rule + .kind + .write_sites() + .into_iter() + .map(|site| match site.path.contains('[') { + true => top(&site.path), + false => site.path, + }) + .collect(), + }; + paths.sort(); + paths.dedup(); + let nested: Vec> = paths + .iter() + .filter(|p| { + paths + .iter() + .any(|q| Sheet::related(p, q) == Some(std::cmp::Ordering::Greater)) + }) + .cloned() + .collect(); + paths.retain(|p| !nested.contains(p)); + paths + } + + pub(super) fn delegate(&mut self, event: Event, positions: &[usize]) { + let (block, commit) = match event { + Event::Select(block) => (block, false), + Event::Commit(block) => (block, true), + }; + self.state.ensure(); + self.delegated = true; + let began = Census::on().then(Instant::now); + for &row in positions { + self.host(row); + } + match commit { + false => self.plan.select(block, positions, &mut self.state), + true => self.plan.commit(block, positions, &mut self.state), + } + if let Some(began) = began { + let why = self.plan.plans[block] + .refused() + .map_or_else(|| "native".to_string(), Refused::to_string); + Census::record( + format!("policy delegate | {why}"), + positions.len(), + began.elapsed().as_nanos(), + ); + } + let mut done: Vec = Vec::with_capacity(positions.len()); + for &row in positions { + match self.state.failures[row].is_some() { + true => self.fall(row), + false => done.push(row), + } + } + if !commit || done.is_empty() { + return; + } + for path in self.readback(block) { + let mut values = vec![Variable::Null; self.sheet.rows]; + let mut present = vec![0u64; self.sheet.rows.div_ceil(64)]; + for &row in &done { + if let Some(value) = self.stores[row].get().and_then(|store| store.dot(&path)) { + values[row] = value; + Bits::set(&mut present, row, true); + } + } + self.sheet.hosted(path, values, present); + } + for &row in &done { + self.synced[row] = self.sheet.entries.len(); + } + } + + pub(super) fn quiet(&self, block: usize) -> bool { + use crate::policy::blocks::ConditionalReads; + match self + .artifact + .read_plans + .get(&self.plan.blocks.refs[block]) + .map(|plan| &plan.conditional) + { + None | Some(ConditionalReads::None) => true, + Some(ConditionalReads::Match(arms)) => { + arms.iter().all(|arm| arm.value_reads.is_empty()) + } + Some(ConditionalReads::DecisionTable(cells)) => { + cells.iter().all(|cell| cell.cell_reads.is_empty()) + } + } + } + + pub(super) fn hosted(&self, block: usize, row: usize) -> bool { + self.hosting.get(block).is_some_and(|rows| rows[row]) + } +} diff --git a/core/engine/src/compiled/policy/columnar/lane.rs b/core/engine/src/compiled/policy/columnar/lane.rs new file mode 100644 index 00000000..d62734c8 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/lane.rs @@ -0,0 +1,240 @@ +use super::{Bind, Extent, Fields, Pass, Sheet, Slot}; +use crate::compiled::bound::Outs; +use crate::compiled::leaf::{Array, Leaf}; +use crate::compiled::policy::PolicyPlan; +use std::sync::Arc; +use zen_expression::lane::{Binding, Column, Columns, Dictionary, LaneProgram, Values}; +use zen_expression::{Scope, Variable}; + +impl<'s, 'a> Pass<'s, 'a> { + pub(super) fn run( + &mut self, + program: &LaneProgram, + positions: &[usize], + ) -> (Leaf<'a>, Vec) { + let (mut leaves, failed) = self.run_outs(program, positions); + let leaf = match leaves.is_empty() { + true => Leaf::nulls(positions.len()), + false => leaves.swap_remove(0), + }; + (leaf, failed) + } + + pub(super) fn run_outs( + &mut self, + program: &LaneProgram, + positions: &[usize], + ) -> (Vec>, Vec) { + let p = program.program(); + let nested = p.site_keys.iter().flatten().any(|key| { + self.sheet + .entities + .iter() + .any(|e| e.active && e.path.as_ref() == key.as_str() && !e.flat()) + }); + let cached = nested || !PolicyPlan::scalar(program); + if cached { + for key in p.site_keys.iter().flatten() { + if let Some(entity) = self + .sheet + .entities + .iter_mut() + .find(|e| e.active && e.path.as_ref() == key.as_str()) + { + entity.materialize(); + } + } + } + let mut failed = vec![false; positions.len()]; + if p.writes_env || p.chain || p.opaque() || p.rows { + let scopes: Vec = positions.iter().map(|&row| self.scope(row)).collect(); + let mut values = vec![Variable::Null; positions.len()]; + self.runner + .evaluate_with(program, &scopes, |at, result| match result { + Ok(value) => values[at] = value, + Err(_) => failed[at] = true, + }); + return (vec![Leaf::Any(values.into())], failed); + } + for key in p.site_keys.iter().flatten() { + let stale: Vec = self + .sheet + .entities + .iter() + .enumerate() + .filter(|(_, entity)| { + entity.active + && Sheet::related(key, &entity.path) + .is_some_and(|o| o != std::cmp::Ordering::Equal) + }) + .map(|(at, _)| at) + .collect(); + stale.into_iter().for_each(|at| self.sheet.retire(at)); + } + let mut columns = Columns::new(self.sheet.rows); + let mut used: Vec = Vec::new(); + let mut rows = false; + let bound: Vec = p + .site_keys + .iter() + .map(|key| { + let slot = match key.as_deref() { + None => return Binding::Row, + Some(key) => match self + .sheet + .entities + .iter() + .position(|e| e.active && e.path.as_ref() == key) + { + Some(entity) => Slot::Composed(entity), + None => match self.sheet.bind(key, positions, self.shared) { + Bind::Absent => return Binding::Absent, + Bind::Row => { + rows = true; + return Binding::Row; + } + Bind::Column(entry) => Slot::Entry(entry), + }, + }, + }; + match used.iter().position(|e| *e == slot) { + Some(at) => Binding::Column(at), + None => { + used.push(slot); + Binding::Column(used.len() - 1) + } + } + }) + .collect(); + let scopes = match rows { + true => crate::compiled::bound::Scopes::Owned(self.scopes(positions)), + false => crate::compiled::bound::Bound::blank(self.sheet.rows), + }; + let views: Vec<(Arc, Leaf<'a>)> = used + .iter() + .filter_map(|slot| match slot { + Slot::Entry(entry) => Some(( + self.sheet.entries[*entry].path.clone(), + self.sheet.entries[*entry].leaf.clone(), + )), + Slot::Composed(at) if cached => { + let entity = &self.sheet.entities[*at]; + let values: Vec = (0..self.sheet.rows) + .map(|row| entity.compose(row).unwrap_or(Variable::Null)) + .collect(); + Some((entity.path.clone(), Leaf::Any(values.into()))) + } + Slot::Composed(_) => None, + }) + .collect(); + let parts: Vec> = used + .iter() + .filter_map(|slot| match slot { + Slot::Composed(at) if !cached => { + let entity = &self.sheet.entities[*at]; + Some(Fields { + entity: *at, + leaves: (0..entity.fields.len()) + .map(|f| (entity.fields[f].name.clone(), entity.view(f))) + .collect(), + }) + } + _ => None, + }) + .collect(); + let shapes: Vec> = parts + .iter() + .map(|part| { + let entity = &self.sheet.entities[part.entity]; + Extent { + len: entity.frame.children, + offsets: entity.frame.offsets.as_ref(), + validity: entity.frame.validity.as_deref().map(|bits| (bits, 0)), + } + }) + .collect(); + let fields: Vec> = parts + .iter() + .map(|part| { + part.leaves + .iter() + .map(|(n, l)| (n.as_ref(), l.column())) + .collect() + }) + .collect(); + let structs: Vec = fields + .iter() + .zip(&shapes) + .map(|(f, shape)| { + Column::new(Values::Struct { + fields: f, + len: shape.len, + }) + }) + .collect(); + let lists: Vec<(&str, Column)> = structs + .iter() + .zip(&shapes) + .zip(&parts) + .map(|((child, shape), part)| { + ( + self.sheet.entities[part.entity].path.as_ref(), + Column { + values: Values::List { + offsets: shape.offsets, + child: Dictionary::Column(child), + }, + validity: shape.validity, + }, + ) + }) + .collect(); + let (mut next_view, mut next_list) = (views.iter(), lists.iter()); + for slot in &used { + match (slot, cached) { + (Slot::Entry(_), _) | (Slot::Composed(_), true) => { + if let Some((path, view)) = next_view.next() { + columns = columns.column(path.as_ref(), view.column()); + } + } + (Slot::Composed(_), false) => { + if let Some((path, list)) = next_list.next() { + columns = columns.column(path, *list); + } + } + } + } + let mut outs = Outs::take(); + let subset = (positions.len() != self.sheet.rows).then_some(positions); + let special = self.plan.special(program, &columns); + let program = special.as_deref().unwrap_or(program); + Self::prefer_codes(program, &mut outs); + self.runner.evaluate_sites( + program, + scopes.slice(), + &columns, + &bound, + subset, + &mut outs, + |at, _, _| { + if let Some(f) = failed.get_mut(at) { + *f = true; + } + }, + ); + let leaves = outs + .iter_mut() + .map(|out| Leaf::typed(Array::from_output(out))) + .collect(); + outs.iter_mut() + .for_each(zen_expression::lane::Output::prefer_text); + (leaves, failed) + } + + pub(super) fn prefer_codes(program: &LaneProgram, outs: &mut Outs) { + let p = program.program(); + outs.resize_with(p.outputs.len().max(1), zen_expression::lane::Output::new); + outs.iter_mut() + .for_each(zen_expression::lane::Output::prefer_codes); + } +} diff --git a/core/engine/src/compiled/policy/columnar/member.rs b/core/engine/src/compiled/policy/columnar/member.rs new file mode 100644 index 00000000..2d763642 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/member.rs @@ -0,0 +1,635 @@ +use super::{Bind, Pass, Sheet, Units}; +use crate::compiled::bound::Outs; +use crate::compiled::core::list::Kin; +use crate::compiled::leaf::{Array, ColumnBuilder, Dict, Leaf, Literal}; +use crate::compiled::policy::schedule::{Demand, Event}; +use crate::compiled::policy::{Native, PolicyPlan}; +use crate::policy::blocks::MatchSelection; +use crate::policy::host::Pick; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Binding, Column, Columns, Dictionary, LaneProgram, Values}; +use zen_expression::Variable; +use zen_types::path::DotPath; + +pub(super) enum Member { + Field(usize), + Root(usize), + List, + Closure, + Absent, + Unsupported, +} + +impl<'s, 'a> Pass<'s, 'a> { + pub(super) fn entity_of(&self, block: usize) -> Option { + let path = self.owners.get(block)?.as_ref()?; + self.sheet + .entities + .iter() + .position(|e| e.active && e.path == *path) + } + + pub(super) fn kids(&mut self, at: usize, positions: &[usize]) -> (Rc<[usize]>, Rc<[usize]>) { + let full = positions.len() == self.sheet.rows; + if let Some(kin) = self.kin.iter().find(|kin| full && kin.at == at) { + return (kin.kids.clone(), kin.parents.clone()); + } + if let Some((kids, parents)) = full + .then(|| Kin::spans(&self.sheet.entities[at].frame, self.sheet.rows)) + .flatten() + { + self.kin + .push(Kin::new(at, kids.clone(), parents.clone(), true)); + return (kids, parents); + } + let (kids, parents) = self.gather(at, positions); + if full { + let identity = self.sheet.entities[at].frame.identity(&kids); + self.kin + .push(Kin::new(at, kids.clone(), parents.clone(), identity)); + } + (kids, parents) + } + + fn identity(&self, at: usize, kids: &Rc<[usize]>) -> bool { + match self + .kin + .iter() + .find(|kin| kin.at == at && Rc::ptr_eq(&kin.kids, kids)) + { + Some(kin) => kin.identity, + None => self.sheet.entities[at].frame.identity(kids), + } + } + + fn broadcast(&self, entry: usize, parents: &Rc<[usize]>) -> Option> { + let column = self.sheet.entries[entry].leaf.column(); + let (Values::Scaled { mant, scale }, None) = (column.values, column.validity) else { + return None; + }; + let codes = self + .kin + .iter() + .find(|kin| Rc::ptr_eq(&kin.parents, parents))? + .codes()?; + let dict = Dict::Scaled { + mant: mant.to_vec(), + scale: scale.to_vec(), + }; + Some(Leaf::typed(Array::coded(codes, Rc::new(dict)))) + } + + pub(super) fn gather(&self, at: usize, positions: &[usize]) -> (Rc<[usize]>, Rc<[usize]>) { + let frame = &self.sheet.entities[at].frame; + let (kids, parents) = + Kin::gather(positions, frame.children, |row| frame.range(row), |_, _| {}); + (kids.into(), parents.into()) + } + + pub(super) fn site(&self, at: usize, key: Option<&str>, rows: &[usize]) -> Member { + let Some(key) = key else { + return Member::Closure; + }; + let entity = &self.sheet.entities[at]; + let owned = |field: &str| { + entity + .owner + .as_deref() + .is_some_and(|owner| DotPath::within(field, owner)) + }; + match DotPath::tail(key, &entity.name) { + Some(field) if owned(field) || entity.overlaps(field) => Member::Unsupported, + Some(field) => entity.field(field).map_or(Member::Absent, Member::Field), + None if key == entity.name.as_ref() || key.starts_with('$') => Member::Unsupported, + None if key == entity.path.as_ref() => Member::List, + None if self + .sheet + .entities + .iter() + .any(|e| e.active && Sheet::related(key, &e.path).is_some()) => + { + Member::Unsupported + } + None => match self.sheet.bind(key, rows, self.shared) { + Bind::Column(entry) => Member::Root(entry), + Bind::Absent => Member::Absent, + Bind::Row => Member::Unsupported, + }, + } + } + + fn field_of(&self, at: usize, key: &Arc) -> Option>> { + if key.is_empty() { + return Some(None); + } + let entity = &self.sheet.entities[at]; + let field = DotPath::tail(key, &entity.name)?; + (!field.is_empty() && !entity.overlaps(field)).then(|| Some(Arc::from(field))) + } + + pub(super) fn native(plan: &PolicyPlan, block: usize) -> Option<&Native> { + let plan = &plan.plans[block]; + plan.native().or(plan.member.as_ref()) + } + + pub(super) fn block( + plan: &PolicyPlan, + block: usize, + ) -> Option<(Vec<&LaneProgram>, Vec<&Arc>)> { + match (Self::native(plan, block), &plan.plans[block].table) { + (Some(native), _) => { + let key = match native { + Native::Expression { key, .. } => key, + Native::Assertion { ir, .. } => &ir.output, + Native::Match { ir, .. } => &ir.key, + }; + Some((Self::programs(native), vec![key])) + } + (None, Some(table)) => Some(( + table.programs(), + table.picked().iter().map(|o| &o.field).collect(), + )), + (None, None) => None, + } + } + + pub(super) fn programs(native: &Native) -> Vec<&LaneProgram> { + match native { + Native::Expression { program, .. } => vec![program.as_ref()], + Native::Assertion { conditions, .. } => conditions.iter().collect(), + Native::Match { + conditions, values, .. + } => conditions.iter().chain(values.iter()).flatten().collect(), + } + } + + pub(super) fn supported(&self, at: usize, block: usize, rows: &[usize]) -> bool { + let Some((programs, keys)) = Self::block(self.plan, block) else { + return false; + }; + let iterated = + self.plan.plans[block].member.is_some() || self.plan.plans[block].table.is_some(); + let entity = &self.sheet.entities[at]; + iterated + && keys.iter().all(|key| self.field_of(at, key).is_some()) + && programs.into_iter().all(|program| { + let p = program.program(); + !(p.writes_env || p.chain || p.opaque() || p.rows) + && p.site_keys + .iter() + .all(|k| match self.site(at, k.as_deref(), rows) { + Member::Unsupported => false, + Member::List => { + Self::siblings(program, &entity.path, &entity.name, &keys) + } + _ => true, + }) + }) + } + + pub(super) fn siblings( + program: &LaneProgram, + path: &str, + name: &str, + keys: &[&Arc], + ) -> bool { + let prefix = format!("{name}."); + let written: Vec<&str> = keys + .iter() + .filter_map(|key| key.strip_prefix(prefix.as_str())) + .collect(); + program.program().source_fields(path).is_some_and(|fields| { + fields + .iter() + .all(|field| written.iter().all(|w| Sheet::related(field, w).is_none())) + }) + } + + fn siblings_of(&self, at: usize, parents: &[usize]) -> Leaf<'a> { + let entity = &self.sheet.entities[at]; + let mut last: Option<(usize, Variable)> = None; + let values: Vec = parents + .iter() + .map(|&row| match &last { + Some((seen, value)) if *seen == row => value.clone(), + _ => { + let value = entity.compose(row).unwrap_or(Variable::Null); + last = Some((row, value.clone())); + value + } + }) + .collect(); + Leaf::Any(values.into()) + } + + fn member_run( + &mut self, + at: usize, + program: &LaneProgram, + kids: &Rc<[usize]>, + parents: &Rc<[usize]>, + ) -> (Leaf<'a>, Vec) { + let (mut leaves, failed) = self.member_outs(at, program, kids, parents); + let leaf = match leaves.is_empty() { + true => Leaf::nulls(kids.len()), + false => leaves.swap_remove(0), + }; + (leaf, failed) + } + + pub(super) fn member_outs( + &mut self, + at: usize, + program: &LaneProgram, + kids: &Rc<[usize]>, + parents: &Rc<[usize]>, + ) -> (Vec>, Vec) { + let p = program.program(); + let count = kids.len(); + let mut failed = vec![false; count]; + if count == 0 { + return (Vec::new(), failed); + } + let mut views: Vec<(Arc, Leaf<'a>)> = Vec::new(); + let identity = self.identity(at, kids); + let bound: Vec = p + .site_keys + .iter() + .map(|key| { + let name: Arc = key.as_deref().map_or_else(|| Arc::from(""), Arc::from); + if let Some(position) = views.iter().position(|(k, _)| *k == name) { + return Binding::Column(position); + } + let leaf = match self.site(at, key.as_deref(), parents) { + Member::Field(field) if identity => self.sheet.entities[at].view(field), + Member::Field(field) => self.sheet.entities[at].view(field).pick(kids), + Member::Root(entry) => self + .broadcast(entry, parents) + .unwrap_or_else(|| self.sheet.entries[entry].leaf.pick(parents)), + Member::List => self.siblings_of(at, parents), + Member::Closure => return Binding::Row, + Member::Absent | Member::Unsupported => return Binding::Absent, + }; + views.push((name, leaf)); + Binding::Column(views.len() - 1) + }) + .collect(); + let mut columns = Columns::new(count); + for (name, view) in &views { + columns = columns.column(name.as_ref(), view.column()); + } + let scopes = crate::compiled::bound::Bound::blank(count); + let mut outs = Outs::take(); + let special = self.plan.special(program, &columns); + let program = special.as_deref().unwrap_or(program); + Self::prefer_codes(program, &mut outs); + self.runner.evaluate_sites( + program, + scopes.slice(), + &columns, + &bound, + None, + &mut outs, + |child, _, _| { + if let Some(f) = failed.get_mut(child) { + *f = true; + } + }, + ); + let leaves = outs + .iter_mut() + .map(|out| Leaf::typed(Array::from_output(out))) + .collect(); + outs.iter_mut() + .for_each(zen_expression::lane::Output::prefer_text); + (leaves, failed) + } + + pub(super) fn member_fail(&mut self, parents: &[usize], failed: &[bool]) { + if !failed.contains(&true) { + return; + } + for (&row, &f) in parents.iter().zip(failed) { + if f { + self.fall(row); + } + } + } + + pub(super) fn member_write( + &mut self, + at: usize, + key: &Arc, + leaf: Leaf<'a>, + kids: &Rc<[usize]>, + ) { + if let Some(Some(field)) = self.field_of(at, key) { + self.sheet.entities[at].write(field, leaf, kids); + } + } + + pub(super) fn member(&mut self, at: usize, block: usize, event: Event, positions: &[usize]) { + let plan = self.plan; + let (kids, parents) = self.kids(at, positions); + if let (None, Some(table)) = (Self::native(plan, block), &plan.plans[block].table) { + let units = Units { + member: Some(at), + units: kids, + owners: parents, + }; + return match event { + Event::Select(block) => self.table_select(block, table, &units), + Event::Commit(block) => self.table_commit(block, table, &units), + }; + } + match (event, Self::native(plan, block)) { + (Event::Commit(_), Some(Native::Expression { key, program })) => { + let (leaf, failed) = self.member_run(at, program, &kids, &parents); + self.member_fail(&parents, &failed); + self.member_write(at, key, leaf, &kids); + } + (Event::Commit(_), Some(Native::Assertion { ir, conditions })) => { + let mut truths: Vec> = Vec::with_capacity(conditions.len()); + for program in conditions { + let (leaf, failed) = self.member_run(at, program, &kids, &parents); + self.member_fail(&parents, &failed); + truths.push(leaf.truths(kids.len())); + } + let bits = Self::folded(ir, &truths, kids.len()); + let leaf = Leaf::typed(Array::parts( + crate::compiled::leaf::Store::Bool(bits), + None, + kids.len(), + )); + self.member_write(at, &ir.output, leaf, &kids); + } + ( + Event::Select(_), + Some(Native::Match { + pick: Some(pick), .. + }), + ) => { + let total = self.sheet.entities[at].frame.children; + let (leaf, failed) = self.member_run(at, pick, &kids, &parents); + self.member_fail(&parents, &failed); + let picked = Self::arms_of(&leaf, kids.len()); + match self.members.get_mut(block) { + Some(arms) => { + kids.iter() + .zip(picked) + .for_each(|(&child, arm)| arms[child] = arm); + } + None => { + let chosen = match self.identity(at, &kids) { + true => picked, + false => { + let mut chosen: Vec> = vec![None; total]; + kids.iter() + .zip(picked) + .for_each(|(&child, arm)| chosen[child] = arm); + chosen + } + }; + self.members.insert(block, chosen); + } + } + } + (Event::Select(_), Some(Native::Match { conditions, .. })) => { + let total = self.sheet.entities[at].frame.children; + let mut chosen: Vec> = vec![None; total]; + let mut open: Vec = (0..kids.len()).collect(); + for (arm, condition) in conditions.iter().enumerate() { + if open.is_empty() { + break; + } + let Some(program) = condition else { + open.drain(..) + .for_each(|local| chosen[kids[local]] = Some(arm)); + break; + }; + let subset: Rc<[usize]> = open.iter().map(|&local| kids[local]).collect(); + let owners: Rc<[usize]> = open.iter().map(|&local| parents[local]).collect(); + let (leaf, failed) = self.member_run(at, program, &subset, &owners); + self.member_fail(&owners, &failed); + let mut next = Vec::with_capacity(open.len()); + for (i, &local) in open.iter().enumerate() { + match leaf.truthy(i) { + true => chosen[kids[local]] = Some(arm), + false => next.push(local), + } + } + open = next; + } + match self.members.get_mut(block) { + Some(arms) => kids.iter().for_each(|&child| arms[child] = chosen[child]), + None => self.members.insert(block, chosen), + } + } + ( + Event::Commit(_), + Some(Native::Match { + ir, + values, + constants, + .. + }), + ) if Self::constant(values, constants) => { + let codes: Vec = match self.members.get(block) { + Some(arms) => kids + .iter() + .map(|&child| Self::code(arms.get(child).copied().flatten(), values)) + .collect(), + None => vec![-1; kids.len()], + }; + self.member_write( + at, + &ir.key, + Self::coded(&Self::fixed(constants), codes), + &kids, + ); + } + ( + Event::Commit(_), + Some(Native::Match { + ir, + values, + constants, + .. + }), + ) => { + let arms = self.members.get(block).cloned().unwrap_or_default(); + let mut out: Vec> = vec![None; kids.len()]; + let mut leaves: Vec> = Vec::new(); + let mut groups: Vec> = vec![Vec::new(); ir.arms.len()]; + for (local, &child) in kids.iter().enumerate() { + if let Some(arm) = arms + .get(child) + .copied() + .flatten() + .filter(|&arm| values[arm].is_some()) + { + groups[arm].push(local); + } + } + if groups.iter().enumerate().all(|(arm, locals)| { + locals.is_empty() || constants.get(arm).is_some_and(Option::is_some) + }) { + let values: Vec = constants + .iter() + .map(|c| c.as_ref().map_or(Variable::Null, Literal::variable)) + .collect(); + let mut codes = vec![-1i32; kids.len()]; + for (arm, locals) in groups.iter().enumerate() { + locals.iter().for_each(|&local| codes[local] = arm as i32); + } + self.member_write(at, &ir.key, Self::coded(&values, codes), &kids); + return; + } + let fixed: Vec<(usize, Variable)> = constants + .iter() + .enumerate() + .filter_map(|(arm, c)| Some((arm, c.as_ref()?.variable()))) + .collect(); + if !fixed.is_empty() { + let mut builder = ColumnBuilder::with_capacity(fixed.len()); + fixed + .iter() + .for_each(|(_, value)| builder.push_variable(value.clone())); + let table = Leaf::typed(builder.finish()); + for (slot, (arm, _)) in fixed.iter().enumerate() { + groups[*arm] + .drain(..) + .for_each(|local| out[local] = Some((leaves.len(), slot))); + } + leaves.push(table); + } + for (arm, locals) in groups.into_iter().enumerate() { + let Some(program) = values[arm].as_ref().filter(|_| !locals.is_empty()) else { + continue; + }; + let subset: Rc<[usize]> = locals.iter().map(|&local| kids[local]).collect(); + let owners: Rc<[usize]> = locals.iter().map(|&local| parents[local]).collect(); + let (leaf, failed) = self.member_run(at, program, &subset, &owners); + self.member_fail(&owners, &failed); + for (i, &local) in locals.iter().enumerate() { + out[local] = Some((leaves.len(), i)); + } + leaves.push(leaf); + } + let columns: Vec = leaves.iter().map(Leaf::column).collect(); + let mut builder = ColumnBuilder::with_capacity(out.len()); + for cell in &out { + match cell { + Some((leaf, i)) => builder.push_cell(&columns[*leaf], *i), + None => builder.push_null(), + } + } + self.member_write(at, &ir.key, Leaf::typed(builder.finish()), &kids); + } + _ => {} + } + } + + pub(super) fn member_demand(&self, block: usize, row: usize) -> Option { + let at = self.entity_of(block)?; + let arms = self.members.get(block)?; + let Some(Native::Match { ir, .. }) = Self::native(self.plan, block) else { + return None; + }; + let plan = self + .artifact + .read_plans + .get(&self.plan.blocks.refs[block])?; + let (a, b) = self.sheet.entities[at].frame.range(row).unwrap_or((0, 0)); + let mut demanded: Vec> = Vec::new(); + for child in a..b { + let pick = Pick::Match(MatchSelection { + matched_arm: arms + .get(child) + .copied() + .flatten() + .and_then(|arm| ir.arms.get(arm)) + .map(|arm| arm.id.clone()), + arms: Vec::new(), + }); + pick.collect_reads(plan, &mut demanded); + } + demanded.sort(); + demanded.dedup(); + Some(demanded.into()) + } + + fn plain(leaf: &Leaf) -> bool { + matches!( + leaf, + Leaf::Input(_) + | Leaf::Typed(_) + | Leaf::Masked(_) + | Leaf::Scattered(_) + | Leaf::Picked(_) + ) && matches!( + leaf.column().values, + Values::Scaled { .. } + | Values::Dec(_) + | Values::I64(_) + | Values::Bool { .. } + | Values::Utf8 { .. } + | Values::Text { .. } + | Values::Dict { + values: Dictionary::Scaled { .. } + | Dictionary::Text { .. } + | Dictionary::Bool { .. }, + .. + } + ) + } + + pub(super) fn direct(&self, units: &Units, program: &LaneProgram) -> Option> { + let key = program.path()?; + let leaf = match units.member { + None => { + if self + .sheet + .entities + .iter() + .any(|e| e.active && Sheet::related(key, &e.path).is_some()) + { + return None; + } + let Bind::Column(entry) = self.sheet.bind(key, &units.units, self.shared) else { + return None; + }; + let leaf = &self.sheet.entries[entry].leaf; + match units.units.len() == self.sheet.rows { + true => leaf.clone(), + false => leaf.pick(&units.units), + } + } + Some(at) => match self.site(at, Some(key), &units.owners) { + Member::Field(field) if self.identity(at, &units.units) => { + self.sheet.entities[at].view(field) + } + Member::Field(field) => self.sheet.entities[at].view(field).pick(&units.units), + Member::Root(entry) => self.sheet.entries[entry].leaf.pick(&units.owners), + _ => return None, + }, + }; + Self::plain(&leaf).then_some(leaf) + } + + pub(super) fn evaluate(&mut self, units: &Units, program: &LaneProgram) -> Leaf<'a> { + match units.member { + None => { + let (leaf, failed) = self.run(program, &units.units); + self.fail(&units.units, &failed); + leaf + } + Some(at) => { + let (leaf, failed) = self.member_run(at, program, &units.units, &units.owners); + self.member_fail(&units.owners, &failed); + leaf + } + } + } +} diff --git a/core/engine/src/compiled/policy/columnar/mod.rs b/core/engine/src/compiled/policy/columnar/mod.rs new file mode 100644 index 00000000..bd84068f --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/mod.rs @@ -0,0 +1,264 @@ +mod blocks; +mod by_block; +mod evaluate; +mod fuse; +mod host; +mod lane; +mod member; +mod output; +mod sheet; +mod table; +mod typed; + +use super::schedule::{Demand, End, Event, Segment}; +use super::{Native, PolicyPlan, Rows}; +use crate::compiled::core::list::Kin; +use crate::compiled::leaf::Leaf; +use crate::compiled::shred::Listing; +use crate::diagnostics::Paths; +use crate::policy::blocks::MatchSelection; +use crate::policy::evaluator::EvalArtifact; +use crate::policy::host::Pick; +use by_block::{ByBlock, Chosen, Fallback}; +pub(super) use fuse::Fusions; +use member::Member; +use sheet::{Bind, Sheet, Slot, Units}; +use std::cell::{OnceCell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::LaneRunner; +use zen_expression::{Scope, Variable}; + +struct Listed<'a> { + key: Rc, + stable: bool, + listing: Option>>, +} + +struct Fields<'a> { + entity: usize, + leaves: Vec<(Arc, Leaf<'a>)>, +} + +struct Extent<'p> { + len: usize, + offsets: &'p [i32], + validity: Option<(&'p [u64], usize)>, +} + +struct Pass<'s, 'a> { + plan: &'s PolicyPlan, + artifact: &'s EvalArtifact, + entry: &'s Arc, + sheet: Sheet<'a>, + runner: &'s mut LaneRunner, + fallback: Fallback, + arms: ByBlock>>, + stores: &'s [OnceCell], + state: Rows<'s>, + synced: Vec, + shared: bool, + base: usize, + chosen: ByBlock, + members: ByBlock>>, + hosting: ByBlock>, + owners: Vec>>, + kin: Vec, + delegated: bool, + counts: Paths, + listed: RefCell>>, +} + +impl<'s, 'a> Pass<'s, 'a> { + fn scope(&mut self, row: usize) -> Scope { + if !self.shared { + return Scope::new(self.sheet.object(row)); + } + match self.host(row) { + Some(host) => { + host.state.clear_dollar(); + Scope::new(host.state.env().shallow_clone()) + } + None => Scope::default(), + } + } + + fn scopes(&mut self, positions: &[usize]) -> Vec { + let mut scopes: Vec = (0..self.sheet.rows).map(|_| Scope::default()).collect(); + for &row in positions { + scopes[row] = self.scope(row); + } + scopes + } + + fn fall(&mut self, row: usize) { + self.fallback.fall(row); + } + + fn fail(&mut self, positions: &[usize], failed: &[bool]) { + if !failed.contains(&true) { + return; + } + for (&row, &f) in positions.iter().zip(failed) { + if f { + self.fall(row); + } + } + } + + fn write(&mut self, key: &Arc, leaf: Leaf<'a>, positions: &[usize]) { + if !key.is_empty() { + self.sheet.write(key.clone(), leaf, positions); + } + } + + fn demand(&self, block: usize, row: usize) -> Demand { + if let Some(demand) = self + .member_demand(block, row) + .or_else(|| self.table_demand(block, row)) + { + return demand; + } + let owner = &self.plan.blocks.refs[block]; + if let (Some(picked), Some(host)) = ( + self.state.picked(row, block), + self.state.hosts.get(row).and_then(Option::as_ref), + ) { + return host.state.demanded(owner, picked).into(); + } + let Some(plan) = self.artifact.read_plans.get(owner) else { + return Arc::from([]); + }; + let Some(Native::Match { ir, .. }) = self.plan.plans[block].native() else { + return Arc::from([]); + }; + let pick = Pick::Match(MatchSelection { + matched_arm: self + .arm(block, row) + .and_then(|arm| ir.arms.get(arm)) + .map(|arm| arm.id.clone()), + arms: Vec::new(), + }); + let mut demanded = Vec::new(); + pick.collect_reads(plan, &mut demanded); + demanded.into() + } + + fn event(&mut self, event: Event, positions: &[usize]) { + let plan = self.plan; + let block = match event { + Event::Select(block) | Event::Commit(block) => block, + }; + if self.owners[block].is_some() { + let selected = self.members.has(block) || self.chosen.has(block); + if let Some(at) = self.entity_of(block) { + if self.supported(at, block, positions) { + return self.member(at, block, event, positions); + } + if selected || self.sheet.entities[at].cached() { + positions.iter().for_each(|&row| self.fall(row)); + return; + } + self.sheet.retire(at); + } + if selected { + positions.iter().for_each(|&row| self.fall(row)); + return; + } + return self.delegate(event, positions); + } + if let Some(table) = &plan.plans[block].table { + let units = |rows: &[usize]| Units { + member: None, + units: rows.into(), + owners: rows.into(), + }; + return match event { + Event::Select(block) => self.table_select(block, table, &units(positions)), + Event::Commit(block) if !self.hosting.has(block) => { + self.table_commit(block, table, &units(positions)) + } + Event::Commit(block) => { + let (hosted, native): (Vec, Vec) = + positions.iter().partition(|&&row| self.hosted(block, row)); + if !native.is_empty() { + self.table_commit(block, table, &units(&native)); + } + if !hosted.is_empty() { + self.delegate(event, &hosted); + } + } + }; + } + match (event, plan.plans[block].native()) { + ( + Event::Select(block), + Some(Native::Match { + conditions, pick, .. + }), + ) => self.select(block, conditions, pick.as_deref(), positions), + ( + Event::Commit(block), + Some(Native::Match { + ir, + values, + constants, + .. + }), + ) => self.commit(block, ir, values, constants, positions), + (Event::Commit(_), Some(Native::Expression { key, program })) => { + self.expression(key, program, positions) + } + (Event::Commit(_), Some(Native::Assertion { ir, conditions })) => { + self.assertion(ir, conditions, positions) + } + _ => self.delegate(event, positions), + } + } + + fn walk(&mut self, root: Arc, live: Vec) { + let mut stack: Vec<(Arc, Vec)> = vec![(root, live)]; + while let Some((segment, mut rows)) = stack.pop() { + let segment = self.events(segment, &mut rows); + let End::Branch { block, .. } = &segment.end else { + continue; + }; + if rows.is_empty() { + continue; + } + if self.quiet(*block) { + stack.push(( + self.plan.child(self.artifact, &segment, Arc::from([])), + rows, + )); + continue; + } + let mut groups: Vec<(Demand, Vec)> = Vec::new(); + let mut memo: ahash::HashMap, usize> = ahash::HashMap::default(); + for &row in &rows { + let key = self.selection(*block, row); + if let Some(&at) = key.as_ref().and_then(|key| memo.get(key)) { + groups[at].1.push(row); + continue; + } + let demand = self.demand(*block, row); + let at = match groups.iter().position(|(d, _)| *d == demand) { + Some(at) => { + groups[at].1.push(row); + at + } + None => { + groups.push((demand, vec![row])); + groups.len() - 1 + } + }; + if let Some(key) = key { + memo.insert(key, at); + } + } + for (demand, members) in groups.into_iter().rev() { + stack.push((self.plan.child(self.artifact, &segment, demand), members)); + } + } + } +} diff --git a/core/engine/src/compiled/policy/columnar/output.rs b/core/engine/src/compiled/policy/columnar/output.rs new file mode 100644 index 00000000..18bc28e3 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/output.rs @@ -0,0 +1,40 @@ +use crate::compiled::output::OutputColumn; +use crate::compiled::shred::Shredder; +use crate::compiled::ColumnarOutput; +use crate::diagnostics::Paths; +use crate::workspace::types::{EvaluationError, EvaluationResult}; +use std::rc::Rc; +use std::sync::Arc; + +pub(super) fn output<'a>( + rows: usize, + columns: Vec<(Arc, OutputColumn<'a>)>, + errors: Vec>, + paths: Paths, +) -> ColumnarOutput<'a> { + ColumnarOutput { + rows, + columns, + errors: errors + .into_iter() + .map(|error| error.map(|error| Rc::new(crate::EvaluationError::Policy(error)))) + .collect(), + paths, + } +} + +pub(super) fn from_results<'a>( + rows: usize, + results: Vec>, +) -> ColumnarOutput<'a> { + let (columns, errors) = Shredder::results(results, |result: &EvaluationResult| &result.output); + output( + rows, + columns, + errors, + Paths { + hosted: rows, + ..Paths::default() + }, + ) +} diff --git a/core/engine/src/compiled/policy/columnar/sheet.rs b/core/engine/src/compiled/policy/columnar/sheet.rs new file mode 100644 index 00000000..a3086d98 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/sheet.rs @@ -0,0 +1,423 @@ +use crate::compiled::leaf::{Bits, ColumnBuilder, Leaf}; +use crate::compiled::output::OutputColumn; +use crate::compiled::policy::entity::Entity; +use crate::compiled::shred::{Normalizer, Shredder}; +use crate::policy::validator::{DatesAt, InputSchema}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Column, Columns, Dictionary, Values}; +use zen_expression::Variable; +use zen_types::path::DotPath; + +pub(super) struct Entry<'a> { + pub(super) path: Arc, + pub(super) leaf: Leaf<'a>, + present: Option>, + pub(super) input: bool, + dead: bool, +} + +pub(super) enum Bind { + Column(usize), + Absent, + Row, +} + +#[derive(Clone, Copy, PartialEq)] +pub(super) enum Slot { + Entry(usize), + Composed(usize), +} + +pub(super) struct Units { + pub(super) member: Option, + pub(super) units: Rc<[usize]>, + pub(super) owners: Rc<[usize]>, +} + +impl Units { + pub(super) fn subset(&self, locals: &[usize]) -> Units { + Units { + member: self.member, + units: locals.iter().map(|&local| self.units[local]).collect(), + owners: locals.iter().map(|&local| self.owners[local]).collect(), + } + } +} + +pub(super) struct Sheet<'a> { + pub(super) rows: usize, + pub(super) entries: Vec>, + pub(super) inputs: Vec>, + pub(super) entities: Vec>, + pub(super) refs: Vec>, + order: Vec, +} + +impl<'a> Sheet<'a> { + pub(super) fn new(columns: &Columns<'a>) -> Option { + let rows = columns.rows; + let mut entries = Vec::with_capacity(columns.columns.len()); + let mut inputs = Vec::with_capacity(columns.columns.len()); + for (path, column) in &columns.columns { + inputs.push(*column); + if path.is_empty() || path.contains('[') { + return None; + } + let present = Bits::validity(column.validity, rows).map(Rc::from); + entries.push(Entry { + path: Arc::from(*path), + leaf: Normalizer::lean(*column, rows), + present, + input: true, + dead: false, + }); + } + Some(Self { + rows, + order: (0..entries.len()).collect(), + entries, + inputs, + entities: Vec::new(), + refs: Vec::new(), + }) + } + + pub(super) fn dates(&mut self, schema: &InputSchema) -> Vec { + let rows = self.rows; + let mut dated = vec![false; rows]; + if !schema.has_dates() { + return dated; + } + for entry in self.entries.iter_mut().filter(|entry| entry.input) { + let Some(at) = schema.dates_at(&entry.path) else { + continue; + }; + if let Some(leaf) = + Self::converted(schema, &at, &entry.leaf, rows, |row| dated[row] = true) + { + entry.leaf = leaf; + } + } + for entity in self.entities.iter_mut() { + let offsets = entity.frame.offsets.clone(); + let children = entity.frame.children; + let mut owner = vec![0usize; children]; + for row in 0..offsets.len().saturating_sub(1) { + let (start, end) = ( + offsets[row].max(0) as usize, + offsets[row + 1].max(0) as usize, + ); + for child in start..end.min(children) { + owner[child] = row; + } + } + for field in entity.fields.iter_mut().filter(|field| field.input) { + let Some(at) = schema.dates_at(&format!("{}.{}", entity.path, field.name)) else { + continue; + }; + if let Some(leaf) = Self::converted(schema, &at, &field.leaf, children, |child| { + dated[owner[child]] = true + }) { + field.leaf = leaf; + } + } + } + dated + } + + fn converted( + schema: &InputSchema, + at: &DatesAt, + leaf: &Leaf<'a>, + len: usize, + mut mark: impl FnMut(usize), + ) -> Option> { + let mut changed = false; + let values: Vec = (0..len) + .map(|at_row| { + let value = leaf.get(at_row); + match schema.convert_at(at, &value) { + Some(next) => { + changed = true; + mark(at_row); + next + } + None => value, + } + }) + .collect(); + if !changed { + return None; + } + let any = Leaf::Any(values.into()); + let mut validity = leaf.validity(len); + Bits::trim(&mut validity, len); + let valid = validity + .iter() + .map(|w| w.count_ones() as usize) + .sum::(); + match valid == len { + true => Some(any), + false => Some(Leaf::masked(any, &validity.into())), + } + } + + pub(super) fn related(a: &str, b: &str) -> Option { + match (a == b, DotPath::under(a, b), DotPath::under(b, a)) { + (true, _, _) => Some(std::cmp::Ordering::Equal), + (_, true, _) => Some(std::cmp::Ordering::Greater), + (_, _, true) => Some(std::cmp::Ordering::Less), + _ => None, + } + } + + pub(super) fn bind(&self, key: &str, positions: &[usize], shared: bool) -> Bind { + if self + .refs + .iter() + .any(|path| Self::related(path, key).is_some()) + { + return Bind::Row; + } + let Some((index, entry)) = self + .entries + .iter() + .enumerate() + .rev() + .find(|(_, entry)| !entry.dead && Self::related(&entry.path, key).is_some()) + else { + return Bind::Absent; + }; + let covered = entry.input + || entry + .present + .as_ref() + .is_none_or(|present| positions.iter().all(|&row| Bits::get(present, row))); + match ( + Self::related(&entry.path, key), + covered, + shared && Self::composite(&entry.leaf), + ) { + (Some(std::cmp::Ordering::Equal), true, false) => Bind::Column(index), + _ => Bind::Row, + } + } + + fn composite(leaf: &Leaf) -> bool { + match leaf { + Leaf::Any(values) => values + .iter() + .any(|v| matches!(v, Variable::Object(_) | Variable::Array(_))), + _ => !matches!( + leaf.column().values, + Values::Scaled { .. } + | Values::I64(_) + | Values::Dec(_) + | Values::F64(_) + | Values::Bool { .. } + | Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) + | Values::Dict { + values: Dictionary::Scaled { .. } + | Dictionary::Text { .. } + | Dictionary::Bool { .. }, + .. + } + ), + } + } + + pub(super) fn present(entry: &Entry, row: usize) -> bool { + entry + .present + .as_ref() + .is_none_or(|present| Bits::get(present, row)) + } + + fn active(&self, index: usize) -> Option<&Entity<'a>> { + self.entities + .iter() + .find(|entity| entity.active && entity.entry == index) + } + + pub(super) fn retire(&mut self, at: usize) { + let Some(entity) = self.entities.get(at).filter(|entity| entity.active) else { + return; + }; + let mut values = vec![Variable::Null; self.rows]; + let mut present = vec![0u64; self.rows.div_ceil(64)]; + for (row, value) in values.iter_mut().enumerate() { + if let Some(composed) = entity.compose(row) { + *value = composed; + Bits::set(&mut present, row, true); + } + } + let path = entity.path.clone(); + self.entities[at].active = false; + self.hosted(path, values, present); + } + + pub(super) fn object(&self, row: usize) -> Variable { + let object = Variable::empty_object(); + for &index in &self.order { + let entry = &self.entries[index]; + if entry.dead { + continue; + } + if let Some(entity) = self.active(index) { + if let Some(composed) = entity.compose(row) { + object.dot_insert(&entry.path, composed); + } + continue; + } + let value = entry.leaf.get(row); + let keep = match entry.input { + true => !matches!(value, Variable::Null) || Self::present(entry, row), + false => Self::present(entry, row), + }; + if keep { + object.dot_insert(&entry.path, value.depth_clone(usize::MAX)); + } + } + object + } + + pub(super) fn write(&mut self, path: Arc, leaf: Leaf<'a>, positions: &[usize]) { + let present: Option> = match positions.len() == self.rows { + true => None, + false => { + let mut bits = vec![0u64; self.rows.div_ceil(64)]; + positions + .iter() + .for_each(|&row| Bits::set(&mut bits, row, true)); + Some(bits.into()) + } + }; + let leaf = match present { + None => leaf, + Some(_) => Leaf::scattered(leaf, positions.iter().copied().collect(), self.rows), + }; + let previous = self + .entries + .iter() + .rposition(|entry| !entry.dead && Self::related(&entry.path, &path).is_some()) + .filter(|&at| { + !self.entries[at].input + && self.entries[at].path == path + && self.entries[at].present.is_some() + }); + let (leaf, present) = match (previous, &present) { + (Some(at), Some(bits)) => { + self.entries[at].dead = true; + let old = &self.entries[at]; + let (fresh, stale) = (leaf.column(), old.leaf.column()); + let mut builder = ColumnBuilder::with_capacity(self.rows); + let mut union = vec![0u64; self.rows.div_ceil(64)]; + for row in 0..self.rows { + match (Bits::get(bits, row), Self::present(old, row)) { + (true, _) => { + builder.push_cell(&fresh, row); + Bits::set(&mut union, row, true); + } + (false, true) => { + builder.push_cell(&stale, row); + Bits::set(&mut union, row, true); + } + (false, false) => builder.push_null(), + } + } + let full = + union.iter().map(|w| w.count_ones() as usize).sum::() == self.rows; + let union: Rc<[u64]> = union.into(); + (Leaf::typed(builder.finish()), (!full).then_some(union)) + } + _ => (leaf, present), + }; + self.push( + Entry { + path, + leaf, + present, + input: false, + dead: false, + }, + previous.filter(|&at| self.entries[at].dead), + ); + } + + fn push(&mut self, entry: Entry<'a>, replaces: Option) { + let index = self.entries.len(); + self.entries.push(entry); + match replaces.and_then(|at| self.order.iter().position(|&slot| slot == at)) { + Some(slot) => self.order[slot] = index, + None => self.order.push(index), + } + } + + pub(super) fn hosted(&mut self, path: Arc, values: Vec, present: Vec) { + let full = present + .iter() + .map(|w| w.count_ones() as usize) + .sum::() + == self.rows; + self.push( + Entry { + path, + leaf: Leaf::Any(values.into()), + present: (!full).then(|| present.into()), + input: false, + dead: false, + }, + None, + ); + } + + pub(super) fn output(&self, finished: &[usize]) -> Vec<(Arc, OutputColumn<'a>)> { + let nested = self + .entries + .iter() + .enumerate() + .filter(|(_, a)| !a.dead) + .any(|(i, a)| { + self.entries + .iter() + .enumerate() + .filter(|(_, b)| !b.dead) + .any(|(j, b)| { + i != j + && matches!( + Self::related(&a.path, &b.path), + Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal) + ) + }) + }); + match nested { + false => self + .order + .iter() + .map(|&index| (index, &self.entries[index])) + .filter(|(_, entry)| !entry.dead) + .map(|(index, entry)| { + if let Some(entity) = self.active(index) { + return (entry.path.clone(), OutputColumn(entity.records(self.rows))); + } + let leaf = match &entry.present { + Some(present) => Leaf::masked(entry.leaf.clone(), present), + None => entry.leaf.clone(), + }; + (entry.path.clone(), OutputColumn(leaf)) + }) + .collect(), + true => { + let mut shredder = Shredder::new(self.rows); + for &row in finished { + shredder.visit(&self.object(row), 0, row); + } + shredder.output() + } + } + } +} diff --git a/core/engine/src/compiled/policy/columnar/table.rs b/core/engine/src/compiled/policy/columnar/table.rs new file mode 100644 index 00000000..9a39927e --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/table.rs @@ -0,0 +1,267 @@ +use super::{Chosen, Pass, Units}; +use crate::compiled::leaf::{Bits, ColumnBuilder, Leaf, Literal}; +use crate::compiled::policy::schedule::{Demand, Event}; +use crate::compiled::table::{Matching, Picked, Table}; +use crate::policy::blocks::TableSelection; +use crate::policy::host::Pick; +use std::sync::Arc; +use zen_expression::Variable; + +impl<'s, 'a> Pass<'s, 'a> { + pub(super) fn table_select(&mut self, block: usize, table: &Table, units: &Units) { + let count = units.units.len(); + let words = table.words(); + let mut matching = table.matching(count); + for (input, field) in table.fields().enumerate() { + let leaf = match self.direct(units, field) { + Some(leaf) => leaf, + None => self.evaluate(units, field), + }; + table.matched(self.runner, input, &leaf, &mut matching); + } + let Matching { all, host, .. } = matching; + let outputs = table.picked().len(); + let total = match units.member { + Some(at) => self.sheet.entities[at].frame.children, + None => self.sheet.rows, + }; + let collects = table.gathers(); + let chosen = self.chosen.entry(block, || Chosen { + firsts: vec![u32::MAX; total * outputs], + matched: match collects { + true => vec![0u64; total * words], + false => Vec::new(), + }, + }); + for (local, &unit) in units.units.iter().enumerate() { + let rules = &all[local * words..(local + 1) * words]; + for (c, first) in table.firsts(rules).enumerate() { + chosen.firsts[unit * outputs + c] = first; + } + if collects { + chosen.matched[unit * words..(unit + 1) * words].copy_from_slice(rules); + } + } + let hosted: Vec = (0..count) + .filter(|&local| host[local]) + .map(|local| units.owners[local]) + .collect(); + if hosted.is_empty() { + return; + } + if units.member.is_some() { + hosted.into_iter().for_each(|row| self.fall(row)); + return; + } + let rows = self.sheet.rows; + let hosting = self.hosting.entry(block, || vec![false; rows]); + hosted.iter().for_each(|&row| hosting[row] = true); + self.delegate(Event::Select(block), &hosted); + } + + fn put(&mut self, units: &Units, field: &Arc, leaf: Leaf<'a>) { + match units.member { + Some(at) => self.member_write(at, field, leaf, &units.units), + None => self.write(field, leaf, &units.units), + } + } + + fn cell_values( + &mut self, + units: &Units, + output: &Picked, + rule: usize, + locals: &[usize], + ) -> Vec { + if let Some(Some(value)) = output.constants.get(rule) { + let value = value.variable(); + return locals.iter().map(|_| value.clone()).collect(); + } + let Some(Some(program)) = output.cells.get(rule) else { + return locals.iter().map(|_| Variable::Null).collect(); + }; + let leaf = self.evaluate(&units.subset(locals), program); + (0..locals.len()).map(|i| leaf.get(i)).collect() + } + + pub(super) fn table_commit(&mut self, block: usize, table: &Table, units: &Units) { + let outputs = table.picked().len(); + let words = table.words(); + let (chosen, matched) = self + .chosen + .get_mut(block) + .map(|chosen| { + ( + std::mem::take(&mut chosen.firsts), + std::mem::take(&mut chosen.matched), + ) + }) + .unwrap_or_default(); + let rule_of = + |unit: usize, c: usize| chosen.get(unit * outputs + c).copied().unwrap_or(u32::MAX); + let resolved: Units; + let units = match table.fills() { + true => units, + false => { + let locals: Vec = (0..units.units.len()) + .filter(|&local| { + (0..outputs).any(|c| rule_of(units.units[local], c) != u32::MAX) + }) + .collect(); + resolved = units.subset(&locals); + &resolved + } + }; + for (c, output) in table + .picked() + .iter() + .enumerate() + .filter(|(_, o)| !o.collect) + { + if let Some((values, remap)) = output.constants() { + let codes = units + .units + .iter() + .map(|&unit| remap.get(rule_of(unit, c) as usize).copied().unwrap_or(-1)) + .collect(); + self.put(units, &output.field, Self::coded(&values, codes)); + continue; + } + let mut groups: Vec<(u32, Vec)> = Vec::new(); + for (local, &unit) in units.units.iter().enumerate() { + let rule = rule_of(unit, c); + if rule == u32::MAX { + continue; + } + match groups.iter_mut().find(|(r, _)| *r == rule) { + Some((_, locals)) => locals.push(local), + None => groups.push((rule, vec![local])), + } + } + let coded = groups + .iter() + .all(|(rule, _)| { + output + .constants + .get(*rule as usize) + .is_some_and(Option::is_some) + }) + .then(|| { + let mut codes = vec![-1i32; units.units.len()]; + let values = groups + .iter() + .enumerate() + .map(|(code, (rule, locals))| { + locals.iter().for_each(|&local| codes[local] = code as i32); + output.constants[*rule as usize] + .as_ref() + .map_or(Variable::Null, Literal::variable) + }) + .collect::>(); + (values, codes) + }); + if let Some((values, codes)) = coded { + self.put(units, &output.field, Self::coded(&values, codes)); + continue; + } + let mut values: Vec = vec![Variable::Null; units.units.len()]; + for (rule, locals) in groups { + for (local, value) in + locals + .iter() + .zip(self.cell_values(units, output, rule as usize, &locals)) + { + values[*local] = value; + } + } + let mut builder = ColumnBuilder::with_capacity(values.len()); + values + .into_iter() + .for_each(|value| builder.push_variable(value)); + self.put(units, &output.field, Leaf::typed(builder.finish())); + } + let mut fields: Vec<&Arc> = Vec::new(); + for output in table.picked().iter().filter(|o| o.collect) { + if !fields.contains(&&output.field) { + fields.push(&output.field); + } + } + for field in fields { + let columns: Vec<&Picked> = table + .picked() + .iter() + .filter(|o| o.collect && o.field == *field) + .collect(); + let rows = |unit: usize| { + matched + .get(unit * words..(unit + 1) * words) + .unwrap_or_default() + }; + let mut any = vec![0u64; words]; + units + .units + .iter() + .for_each(|&unit| Bits::or(&mut any, rows(unit))); + let mut lists: Vec> = vec![Vec::new(); units.units.len()]; + for rule in Bits::rows(&any) { + for output in &columns { + if !output.fills(rule) { + continue; + } + let locals: Vec = (0..units.units.len()) + .filter(|&local| Bits::get(rows(units.units[local]), rule)) + .collect(); + if locals.is_empty() { + continue; + } + for (local, value) in locals + .iter() + .zip(self.cell_values(units, output, rule, &locals)) + { + lists[*local].push(value); + } + } + } + let mut builder = ColumnBuilder::with_capacity(lists.len()); + lists + .into_iter() + .for_each(|items| builder.push_variable(Variable::from_array(items))); + self.put(units, field, Leaf::typed(builder.finish())); + } + if let Some(slot) = self.chosen.get_mut(block) { + slot.firsts = chosen; + slot.matched = matched; + } + } + + pub(super) fn table_demand(&self, block: usize, row: usize) -> Option { + if self.hosted(block, row) { + return None; + } + let table = self.plan.plans[block].table.as_ref()?; + let Chosen { + firsts: chosen, + matched, + } = self.chosen.get(block)?; + let plan = self + .artifact + .read_plans + .get(&self.plan.blocks.refs[block])?; + let matched = (!matched.is_empty()).then_some(matched.as_slice()); + let mut demanded = Vec::new(); + match self.entity_of(block) { + None => Pick::Table(TableSelection::used(table.used(chosen, matched, row))) + .collect_reads(plan, &mut demanded), + Some(at) => { + let (a, b) = self.sheet.entities[at].frame.range(row).unwrap_or((0, 0)); + for child in a..b { + Pick::Table(TableSelection::used(table.used(chosen, matched, child))) + .collect_reads(plan, &mut demanded); + } + demanded.sort(); + demanded.dedup(); + } + } + Some(demanded.into()) + } +} diff --git a/core/engine/src/compiled/policy/columnar/typed.rs b/core/engine/src/compiled/policy/columnar/typed.rs new file mode 100644 index 00000000..443f2ae9 --- /dev/null +++ b/core/engine/src/compiled/policy/columnar/typed.rs @@ -0,0 +1,700 @@ +use super::fuse::{Chain, Fusions, Sink, Span}; +use super::{Bind, Listed, Member, Pass, Sheet}; +use crate::compiled::census::Census; +use crate::compiled::core::exec::{Choice, Dedup, Hint, ListPart, Select, TypedCall}; +use crate::compiled::core::fuse::Fused; +use crate::compiled::core::group::{Built, Prefix, Step}; +use crate::compiled::core::list::Frame; +use crate::compiled::core::retry::Take; +use crate::compiled::core::switch::{Cost, Density, Path, Route}; +use crate::compiled::core::variants::Variants; +use crate::compiled::leaf::Leaf; +use crate::compiled::lowered::Exports; +use crate::compiled::shred::{Listing, Normalizer}; +use crate::policy::blocks::BlockKind; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Instant; +use zen_expression::lane::Values; +use zen_expression::typed::{Lowering, Outputs, Program, Resolve, Resolved}; + +pub(crate) struct TypedGroup { + program: Option, + sinks: Vec, + pub(super) units: usize, + pub(super) cost: Cost, + dedup: Dedup, + probe: Box<[Probed]>, + columns: Vec, + lists: Vec>, + fields: Vec, + exports: Exports, + census: usize, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Ask { + Path, + Alias, + Nested, +} + +struct Probed { + ask: Ask, + path: Arc, + answer: Resolved, +} + +enum Source { + Entry(usize), + Field(usize), + List(usize, Vec), + Listed(usize), + Absent, +} + +enum Part<'a> { + Entity(Frame, Vec>), + Listed(Rc>), +} + +struct Probe<'p, 's, 'a> { + pass: &'p Pass<'s, 'a>, + entity: Option, + rows: &'p [usize], + record: Vec, +} + +impl Resolve for Probe<'_, '_, '_> { + fn path(&mut self, path: &str) -> Resolved { + self.ask(Ask::Path, path) + } + + fn alias(&mut self, field: &str) -> Resolved { + self.ask(Ask::Alias, field) + } + + fn nested(&mut self, chain: &[&str]) -> Resolved { + self.ask(Ask::Nested, &chain.join("\n")) + } +} + +impl Probe<'_, '_, '_> { + fn ask(&mut self, ask: Ask, path: &str) -> Resolved { + let (answer, _) = self.pass.locate(self.entity, self.rows, path, ask); + if !self + .record + .iter() + .any(|p| p.ask == ask && p.path.as_ref() == path) + { + self.record.push(Probed { + ask, + path: Arc::from(path), + answer: answer.clone(), + }); + } + answer + } +} + +impl TypedGroup { + fn lower(pass: &Pass, units: &[Span], entity: Option, rows: &[usize]) -> Self { + let member = entity + .map(|at| &pass.sheet.entities[at]) + .map(|e| (e.name.as_ref(), e.path.as_ref())); + Prefix::lower( + units.len(), + || { + let probe = Probe { + pass, + entity, + rows, + record: Vec::new(), + }; + (Lowering::new(member), probe, Vec::new()) + }, + |(lowering, probe, sinks), at| { + let block = units[at].block; + let lowered = match &pass.plan.blocks.rules[block].kind { + BlockKind::DecisionTable(ir) => Fused::::spec(ir).map(|spec| { + let sunk: Vec = spec + .outputs + .iter() + .map(|key| Sink::Write(Arc::from(key.as_str()))) + .collect(); + (lowering.table(&spec, probe), sunk) + }), + _ => Fused::::entries(pass.plan, block, entity.is_some()) + .map(|(entries, sunk)| (lowering.unit(&entries, probe), sunk)), + }; + match lowered { + Some((Ok(()), sunk)) => { + sinks.extend(sunk); + Step::Lowered + } + Some((Err(e), _)) => { + Census::reason(|| e.0); + Step::Stop + } + None => { + Census::reason(|| "no entries".into()); + Step::Stop + } + } + }, + |(lowering, probe, sinks)| { + let consumed = lowering.units(); + let record = probe.record; + if consumed == 0 { + return Built::Done(Self::empty(record)); + } + let built = match Program::new(lowering.finish()) { + Ok(program) => Self::new(program, sinks, consumed, record, entity.is_some()), + Err(e) => { + Census::reason(|| format!("build: {}", e.0)); + Err(record) + } + }; + match built { + Ok(group) => Built::Done(group), + Err(record) => Built::Shrink { + consumed, + fallback: Self::empty(record), + }, + } + }, + ) + } + + fn empty(record: Vec) -> Self { + Self { + program: None, + sinks: Vec::new(), + units: 0, + cost: Cost::new(), + dedup: Dedup::new(), + probe: record.into(), + columns: Vec::new(), + lists: Vec::new(), + fields: Vec::new(), + exports: Exports::of(&Default::default()), + census: Census::id(), + } + } + + fn new( + program: Program, + sinks: Vec, + units: usize, + record: Vec, + member: bool, + ) -> Result> { + let hir = program.hir(); + let schema = &hir.schema; + let find = |ask: Ask, path: &str| { + record + .iter() + .position(|p| p.ask == ask && p.path.as_ref() == path) + }; + let columns: Option> = schema + .columns + .iter() + .map(|c| find(Ask::Path, &c.path)) + .collect(); + let lists: Option>> = schema + .lists + .iter() + .enumerate() + .map(|(at, list)| match (member && at == 0, list.parent) { + (true, _) => Some(None), + (false, None) => find(Ask::Path, &list.path).map(Some), + (false, Some(_)) => { + find(Ask::Nested, &schema.chain(at as u16).join("\n")).map(Some) + } + }) + .collect(); + let fields: Option> = match (member, schema.lists.first()) { + (true, Some(list)) => list + .fields + .iter() + .map(|f| find(Ask::Alias, &f.path)) + .collect(), + (true, None) => None, + (false, _) => Some(Vec::new()), + }; + let (Some(columns), Some(lists), Some(fields)) = (columns, lists, fields) else { + Census::reason(|| "columns unresolved".into()); + return Err(record); + }; + let exports = Exports::of(hir); + Ok(Self { + program: Some(program), + sinks, + units, + cost: Cost::new(), + dedup: Dedup::new(), + probe: record.into(), + columns, + lists, + fields, + exports, + census: Census::id(), + }) + } + + fn replay(&self, pass: &Pass, entity: Option, rows: &[usize]) -> Option> { + self.probe + .iter() + .map(|probed| { + let (answer, source) = pass.locate(entity, rows, &probed.path, probed.ask); + (answer == probed.answer).then_some(source) + }) + .collect() + } +} + +impl Fusions { + const VARIANTS: usize = 8; + + fn group( + &self, + pass: &Pass, + units: &[Span], + entity: Option, + rows: &[usize], + ) -> Option<(Arc, Vec)> { + let key = Chain { + blocks: units.iter().map(|span| span.block).collect(), + member: entity.is_some(), + }; + let found = self.typed.read().ok().and_then(|cache| { + cache + .get(&key)? + .find_map(|group| Some((group.clone(), group.replay(pass, entity, rows)?))) + }); + if found.is_some() { + return found; + } + let group = Arc::new(TypedGroup::lower(pass, units, entity, rows)); + if group.program.is_none() { + Census::reject((group.census, "policy".into())); + } + let sources = group.replay(pass, entity, rows)?; + if let Ok(mut cache) = self.typed.write() { + cache + .entry(key) + .or_insert_with(|| Variants::new(Self::VARIANTS)) + .keep(group.clone()); + } + Some((group, sources)) + } +} + +pub(super) enum Typed { + Ran(usize, Vec), + Lane(Arc, Route), + Skipped, +} + +impl<'s, 'a> Pass<'s, 'a> { + pub(super) fn typed(&mut self, units: &[Span], entity: Option, rows: &[usize]) -> Typed { + let total = self.sheet.rows; + let full = rows.len() == total; + if Density::sparse(rows.len(), total) { + Census::reason(|| "sparse".into()); + return Typed::Skipped; + } + if let Some(at) = entity { + let path = self.sheet.entities[at].path.clone(); + let siblings = units.iter().any(|span| { + Pass::block(self.plan, span.block).is_some_and(|(programs, _)| { + programs.iter().any(|program| { + program + .program() + .site_keys + .iter() + .flatten() + .any(|key| *key == *path) + }) + }) + }); + if siblings { + Census::reason(|| "member reads its own list".into()); + return Typed::Skipped; + } + } + let plan = self.plan; + self.listed.borrow_mut().retain(|listed| listed.stable); + let Some((group, sources)) = plan.fusions.group(self, units, entity, rows) else { + Census::reason(|| "replay".into()); + return Typed::Skipped; + }; + let Some(program) = group.program.as_ref() else { + Census::recall(&(group.census, "policy".into())); + return Typed::Skipped; + }; + let span = match entity { + Some(at) => match self.sheet.entities[at].frame.span(self.sheet.rows) { + Some(span) => Some((at, span)), + None => { + Census::reason(|| "span".into()); + return Typed::Skipped; + } + }, + None => None, + }; + let path = group.cost.path(); + if path.path == Path::Lane { + return Typed::Lane(group, path); + } + let (start, count, asked, whole) = (Instant::now(), rows.len(), rows, full); + let select = (!full).then(|| Select::bits(total, rows)); + let (out, choice) = match group.lists.is_empty() { + true => group.dedup.choose( + self, + count, + |pass| pass.execute(&group, program, &sources, entity, select.as_deref()), + |pass| pass.deduped(&group, program, &sources, asked, whole), + ), + false => ( + self.execute(&group, program, &sources, entity, select.as_deref()), + Choice::default(), + ), + }; + let Some(mut out) = out else { + Census::reason(|| "execute".into()); + return Typed::Skipped; + }; + let (faulted, kept) = match out.faults().any() { + true => Take::among(out.faults().words(), rows), + false => (Vec::new(), Vec::new()), + }; + let rows = match faulted.is_empty() { + true => rows, + false => kept.as_slice(), + }; + if rows.is_empty() { + group + .dedup + .settle(&group.cost, path, choice, start.elapsed(), count); + group.dedup.probe(&group.cost, self, count, |pass| { + pass.deduped(&group, program, &sources, asked, whole) + }); + return Typed::Ran(group.units, faulted); + } + let full = rows.len() == total; + let leaves: Vec> = group.exports.leaves(&mut out); + match span { + None => { + let leaves = match full { + true => leaves, + false => { + let picks: Rc<[usize]> = rows.into(); + leaves.iter().map(|leaf| leaf.pick(&picks)).collect() + } + }; + self.sink(&group.sinks, leaves, None, rows); + } + Some((at, (base, end))) => { + let (kids, leaves) = match full { + true => ((base..end).collect::>(), leaves), + false => { + let (kids, _) = self.gather(at, rows); + let picks: Rc<[usize]> = kids.iter().map(|&kid| kid - base).collect(); + (kids, leaves.iter().map(|leaf| leaf.pick(&picks)).collect()) + } + }; + self.sink(&group.sinks, leaves, Some((at, &kids)), rows); + } + } + group + .dedup + .settle(&group.cost, path, choice, start.elapsed(), count); + group.dedup.probe(&group.cost, self, count, |pass| { + pass.deduped(&group, program, &sources, asked, whole) + }); + Typed::Ran(group.units, faulted) + } + + fn deduped( + &self, + group: &TypedGroup, + program: &Program, + sources: &[Source], + rows: &[usize], + full: bool, + ) -> Option { + let leaves: Vec> = group + .columns + .iter() + .map(|&at| match sources.get(at)? { + Source::Entry(entry) => Some(self.sheet.entries[*entry].leaf.clone()), + _ => None, + }) + .collect::>()?; + let total = self.sheet.rows; + let codes: Vec = leaves + .iter() + .map(|leaf| { + let column = leaf.column(); + match column.values { + Values::Dict { .. } | Values::Bool { .. } => Some(None), + _ => Dedup::codes(&column, total).map(Some), + } + }) + .collect::>()?; + let positions: Option> = (!full).then(|| rows.into()); + Dedup::coded(program, &leaves, &codes, positions.as_ref(), total) + } + + fn execute( + &self, + group: &TypedGroup, + program: &Program, + sources: &[Source], + entity: Option, + select: Option<&[u64]>, + ) -> Option { + let leaf = |at: usize| -> Option> { + match sources.get(at)? { + Source::Entry(entry) => Some(self.sheet.entries[*entry].leaf.clone()), + Source::Field(field) => Some(self.sheet.entities[entity?].view(*field)), + Source::List(..) | Source::Listed(_) | Source::Absent => None, + } + }; + let columns: Vec> = group + .columns + .iter() + .map(|&at| leaf(at)) + .collect::>()?; + let mut parts: Vec> = Vec::with_capacity(group.lists.len()); + for list in &group.lists { + parts.push(match list { + None => { + let owner = &self.sheet.entities[entity?]; + let fields = group + .fields + .iter() + .map(|&at| leaf(at)) + .collect::>()?; + Part::Entity(owner.frame.clone(), fields) + } + Some(at) => match sources.get(*at)? { + Source::List(owner, fields) => { + let owner = &self.sheet.entities[*owner]; + Part::Entity( + owner.frame.clone(), + fields.iter().map(|&f| owner.view(f)).collect(), + ) + } + Source::Listed(index) => { + Part::Listed(self.listed.borrow().get(*index)?.listing.clone()?) + } + _ => return None, + }, + }); + } + let call = TypedCall { + rows: self.sheet.rows, + columns: &columns, + lists: parts + .iter() + .map(|part| match part { + Part::Entity(frame, fields) => { + ListPart::Frame(frame, fields.iter().map(Leaf::column).collect()) + } + Part::Listed(listing) => ListPart::Listing(listing, None, None), + }) + .collect(), + select, + }; + call.run(program) + } + + fn listing( + &self, + key: String, + stable: bool, + build: impl FnOnce() -> Option>, + ) -> Option<(usize, Rc>)> { + if let Some(at) = self + .listed + .borrow() + .iter() + .position(|listed| listed.key.as_ref() == key) + { + return self.listed.borrow()[at] + .listing + .clone() + .map(|listing| (at, listing)); + } + let built = build().map(Rc::new); + let mut listed = self.listed.borrow_mut(); + listed.push(Listed { + key: Rc::from(key), + stable, + listing: built.clone(), + }); + built.map(|listing| (listed.len() - 1, listing)) + } + + fn listed_entry(&self, entry: usize) -> (Resolved, Source) { + let leaf = &self.sheet.entries[entry].leaf; + match self.listing(format!("#{entry}"), true, || { + Listing::leaf(leaf, self.sheet.rows) + }) { + Some((at, listing)) => ( + Resolved::List { + fields: listing.classes(), + }, + Source::Listed(at), + ), + None => (Resolved::Unsupported, Source::Absent), + } + } + + fn bound(&self, entry: usize) -> (Resolved, Source) { + match Normalizer::class(&self.sheet.entries[entry].leaf.column().values) { + Some(class) => (Resolved::Column(class), Source::Entry(entry)), + None => self.listed_entry(entry), + } + } + + fn nested_list( + &self, + entity: Option, + rows: &[usize], + chain: &[&str], + ) -> Option<(usize, Rc>)> { + let (root, rest) = chain.split_first()?; + let (first, rest) = rest.split_first()?; + let entities = &self.sheet.entities; + let owner = match entity { + Some(at) => (entities[at].path.as_ref() == *root).then_some(at), + None => entities + .iter() + .position(|e| e.active && e.path.as_ref() == *root), + }; + let (mut key, stable, mut current) = match owner { + Some(at) => { + let owner = &entities[at]; + if owner.cached() || !owner.flat() { + return None; + } + let f = owner.field(first)?; + let key = format!("@{at}:{f}"); + let (_, current) = self.listing(key.clone(), false, || { + Listing::leaf(&owner.view(f), owner.frame.children) + })?; + (key, false, current) + } + None => { + let entry = match entity { + None => match self.sheet.bind(root, rows, false) { + Bind::Column(entry) => entry, + _ => return None, + }, + Some(at) => match self.site(at, Some(root), rows) { + Member::Root(entry) => entry, + _ => return None, + }, + }; + let (_, base) = self.listing(format!("#{entry}"), true, || { + Listing::leaf(&self.sheet.entries[entry].leaf, self.sheet.rows) + })?; + let key = format!("#{entry}\n{first}"); + let (_, current) = self.listing(key.clone(), true, || base.nested(first))?; + (key, true, current) + } + }; + let mut at = self + .listed + .borrow() + .iter() + .position(|listed| listed.key.as_ref() == key)?; + for field in rest { + key.push('\n'); + key.push_str(field); + let parent = current.clone(); + let (next, listing) = self.listing(key.clone(), stable, || parent.nested(field))?; + at = next; + current = listing; + } + Some((at, current)) + } + + fn locate( + &self, + entity: Option, + rows: &[usize], + key: &str, + ask: Ask, + ) -> (Resolved, Source) { + let unsupported = (Resolved::Unsupported, Source::Absent); + let column = |leaf: &Leaf, source: Source| match Normalizer::class(&leaf.column().values) { + Some(class) => (Resolved::Column(class), source), + None => (Resolved::Unsupported, Source::Absent), + }; + match (entity, ask) { + (_, Ask::Nested) => { + let chain: Vec<&str> = key.split('\n').collect(); + match self.nested_list(entity, rows, &chain) { + Some((at, listing)) => ( + Resolved::List { + fields: listing.classes(), + }, + Source::Listed(at), + ), + None => unsupported, + } + } + (Some(at), Ask::Alias) => { + let owner = &self.sheet.entities[at]; + match self.site(at, Some(&format!("{}.{key}", owner.name)), rows) { + Member::Field(field) => column(&owner.view(field), Source::Field(field)), + Member::Absent => (Resolved::Absent, Source::Absent), + _ => unsupported, + } + } + (Some(at), Ask::Path) => match self.site(at, Some(key), rows) { + Member::Root(entry) => self.bound(entry), + Member::Absent => (Resolved::Absent, Source::Absent), + _ => unsupported, + }, + (None, Ask::Alias) => unsupported, + (None, Ask::Path) => { + let entities = &self.sheet.entities; + if let Some(at) = entities + .iter() + .position(|e| e.active && e.path.as_ref() == key) + { + let owner = &entities[at]; + if owner.cached() || !owner.flat() { + return unsupported; + } + let mut fields = Vec::new(); + let mut index = Vec::new(); + for (f, field) in owner.fields.iter().enumerate() { + let class = Normalizer::class(&owner.view(f).column().values); + if let (Some(class), true) = (class, owner.field(&field.name) == Some(f)) { + fields.push((field.name.clone(), class)); + index.push(f); + } + } + return (Resolved::List { fields }, Source::List(at, index)); + } + if entities + .iter() + .any(|e| e.active && Sheet::related(key, &e.path).is_some()) + { + return unsupported; + } + match self.sheet.bind(key, rows, false) { + Bind::Column(entry) => self.bound(entry), + Bind::Absent => (Resolved::Absent, Source::Absent), + Bind::Row => unsupported, + } + } + } + } +} diff --git a/core/engine/src/compiled/policy/entity.rs b/core/engine/src/compiled/policy/entity.rs new file mode 100644 index 00000000..bfa4108e --- /dev/null +++ b/core/engine/src/compiled/policy/entity.rs @@ -0,0 +1,362 @@ +use crate::compiled::core::list::Frame; +use crate::compiled::leaf::{Bits, ColumnBuilder, Leaf}; +use crate::compiled::shred::{Normalizer, Shred}; +use crate::policy::evaluator::EvalArtifact; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Column, Columns, Dictionary, Values}; +use zen_expression::Variable; +use zen_types::path::DotPath; +use zen_types::symbol::Symbol; +use zen_types::variable::VariableMap; + +pub(super) struct Field<'a> { + pub name: Arc, + pub leaf: Leaf<'a>, + pub present: Option>, + pub input: bool, +} + +pub(super) struct Entity<'a> { + pub name: Arc, + pub path: Arc, + pub owner: Option>, + pub entry: usize, + pub frame: Frame, + pub fields: Vec>, + pub active: bool, + pub hosted: Option>, + cache: Option>, +} + +impl<'a> Entity<'a> { + pub fn sure( + artifact: &EvalArtifact, + columns: &Columns, + entities: &[Entity], + goals: &[Arc], + ) -> Option> { + let shredded: Vec<&Entity> = entities + .iter() + .filter(|entity| entity.hosted.is_some()) + .collect(); + if shredded.is_empty() { + return artifact.sure(columns, goals); + } + let parts: Vec> = shredded + .iter() + .map(|entity| { + entity + .fields + .iter() + .map(|field| (field.name.as_ref(), field.leaf.column())) + .collect() + }) + .collect(); + let items: Vec = parts + .iter() + .zip(&shredded) + .map(|(fields, entity)| { + Column::new(Values::Struct { + fields, + len: entity.frame.children, + }) + }) + .collect(); + let lists: Vec<(usize, Column)> = items + .iter() + .zip(&shredded) + .map(|(item, entity)| { + ( + entity.entry, + Column { + values: Values::List { + offsets: &entity.frame.offsets, + child: Dictionary::Column(item), + }, + validity: entity.frame.validity.as_deref().map(|bits| (bits, 0)), + }, + ) + }) + .collect(); + let mut replaced = Columns::new(columns.rows); + for (index, (path, column)) in columns.columns.iter().enumerate() { + let column = lists + .iter() + .find(|(entry, _)| *entry == index) + .map_or(*column, |(_, list)| *list); + replaced = replaced.column(path, column); + } + artifact.sure(&replaced, goals) + } + + pub fn new( + name: Arc, + path: Arc, + owner: Option>, + entry: usize, + list: Column<'a>, + ) -> Option { + let Values::List { + offsets, + child: Dictionary::Column(child), + } = list.values + else { + return None; + }; + let Values::Struct { fields, len } = child.values else { + return None; + }; + if Bits::partial(child.validity, len).is_some() { + return None; + } + let fields = fields + .iter() + .map(|(name, column)| Field { + name: Arc::from(*name), + leaf: Normalizer::lean(*column, len), + present: None, + input: true, + }) + .collect(); + let rows = offsets.len().saturating_sub(1); + let validity = Bits::partial(list.validity, rows); + Some(Self { + name, + path, + owner, + entry, + frame: Frame { + offsets: Rc::from(offsets), + validity: validity.map(|(bits, offset)| Rc::from(Bits::window(bits, offset, rows))), + children: len, + }, + fields, + active: true, + hosted: None, + cache: None, + }) + } + + pub fn shredded( + name: Arc, + path: Arc, + owner: Option>, + entry: usize, + shred: Shred, + ) -> Self { + let fields = shred + .fields + .into_iter() + .map(|(name, array)| Field { + name, + leaf: Leaf::typed(array), + present: None, + input: true, + }) + .collect(); + Self { + name, + path, + owner, + entry, + frame: shred.frame, + fields, + active: true, + hosted: Some(shred.hosted), + cache: None, + } + } + + pub fn field(&self, name: &str) -> Option { + self.fields.iter().rposition(|f| f.name.as_ref() == name) + } + + pub fn flat(&self) -> bool { + self.fields.iter().all(|f| !f.name.contains('.')) + } + + pub fn overlaps(&self, name: &str) -> bool { + self.fields.iter().any(|f| DotPath::nested(&f.name, name)) + } + + fn present(field: &Field, child: usize) -> bool { + match field.input { + true => field.leaf.valid_at(child) || !matches!(field.leaf.get(child), Variable::Null), + false => field + .present + .as_ref() + .is_none_or(|bits| Bits::get(bits, child)), + } + } + + fn held(field: &Field, children: usize) -> Vec { + let mut bits = field.leaf.validity(children); + Bits::trim(&mut bits, children); + let full = bits.iter().map(|w| w.count_ones() as usize).sum::() == children; + if !full { + for child in 0..children { + if !Bits::get(&bits, child) && !matches!(field.leaf.get(child), Variable::Null) { + Bits::set(&mut bits, child, true); + } + } + } + bits + } + + pub fn view(&self, field: usize) -> Leaf<'a> { + let field = &self.fields[field]; + match &field.present { + Some(bits) => Leaf::masked(field.leaf.clone(), bits), + None => field.leaf.clone(), + } + } + + fn object(&self, child: usize) -> Variable { + let present = self + .fields + .iter() + .filter(|field| Self::present(field, child)) + .map(|field| { + let value = match field.leaf.get(child) { + value @ (Variable::Object(_) | Variable::Array(_)) => { + value.depth_clone(usize::MAX) + } + other => other, + }; + (field, value) + }); + if self.fields.iter().any(|field| field.name.contains('.')) { + let object = Variable::empty_object(); + for (field, value) in present { + object.dot_insert(&field.name, value); + } + return object; + } + let mut map = VariableMap::with_capacity(self.fields.len()); + for (field, value) in present { + map.insert(Symbol::from(field.name.as_ref()), value); + } + Variable::from_object(map) + } + + pub fn materialize(&mut self) { + if self.cache.is_none() { + self.cache = Some( + (0..self.frame.children) + .map(|child| self.object(child)) + .collect(), + ); + } + } + + pub fn cached(&self) -> bool { + self.cache.is_some() + } + + pub fn records(&self, rows: usize) -> Leaf<'a> { + let offsets: Vec = self + .frame + .offsets + .get(..=rows) + .map_or_else(Vec::new, <[i32]>::to_vec); + let valid = match &self.frame.validity { + Some(bits) => Bits::window(bits, 0, rows), + None => Bits::ones(rows), + }; + let fields = self + .fields + .iter() + .map(|field| { + let present: Rc<[u64]> = match (&field.present, field.input) { + (Some(bits), _) => bits.clone(), + (None, false) => Bits::ones(self.frame.children).into(), + (None, true) => Self::held(field, self.frame.children).into(), + }; + ( + Symbol::from(field.name.as_ref()), + field.leaf.clone(), + present, + ) + }) + .collect(); + Leaf::Records(Rc::new(crate::compiled::leaf::Records::new( + rows, offsets, valid, fields, None, + ))) + } + + pub fn compose(&self, row: usize) -> Option { + let (a, b) = self.frame.range(row)?; + Some(Variable::from_array(match &self.cache { + Some(cache) => cache[a..b].iter().map(Variable::shallow_clone).collect(), + None => (a..b).map(|child| self.object(child)).collect(), + })) + } + + pub fn write(&mut self, name: Arc, leaf: Leaf<'a>, kids: &Rc<[usize]>) { + if let Some(cache) = &self.cache { + let key = Symbol::from(name.as_ref()); + for (local, &child) in kids.iter().enumerate() { + match (cache.get(child), name.contains('.')) { + (Some(object), true) => { + object.dot_insert(&name, leaf.get(local)); + } + (Some(Variable::Object(map)), false) => { + map.borrow_mut().insert(key.clone(), leaf.get(local)); + } + _ => {} + } + } + } + let total = self.frame.children; + let full = kids.len() == total; + let (leaf, present) = match full { + true => (leaf, None), + false => { + let mut bits = vec![0u64; total.div_ceil(64)]; + kids.iter() + .for_each(|&child| Bits::set(&mut bits, child, true)); + ( + Leaf::scattered(leaf, kids.clone(), total), + Some(Rc::from(bits)), + ) + } + }; + let fresh = Field { + name, + leaf, + present, + input: false, + }; + match (self.field(&fresh.name), full) { + (None, _) => self.fields.push(fresh), + (Some(at), true) => self.fields[at] = fresh, + (Some(at), false) => { + let old = &self.fields[at]; + let (new_column, old_column) = (fresh.leaf.column(), old.leaf.column()); + let mut builder = ColumnBuilder::with_capacity(total); + let mut bits = vec![0u64; total.div_ceil(64)]; + for child in 0..total { + match (Self::present(&fresh, child), Self::present(old, child)) { + (true, _) => { + builder.push_cell(&new_column, child); + Bits::set(&mut bits, child, true); + } + (false, true) => { + builder.push_cell(&old_column, child); + Bits::set(&mut bits, child, true); + } + (false, false) => builder.push_null(), + } + } + let merged = Field { + name: fresh.name.clone(), + leaf: Leaf::typed(builder.finish()), + present: Some(bits.into()), + input: false, + }; + self.fields[at] = merged; + } + } + } +} diff --git a/core/engine/src/compiled/policy/host.rs b/core/engine/src/compiled/policy/host.rs new file mode 100644 index 00000000..48bef620 --- /dev/null +++ b/core/engine/src/compiled/policy/host.rs @@ -0,0 +1,144 @@ +use std::sync::Arc; + +use zen_expression::lane::{Programs, Session}; +use zen_expression::variable::Variable; +use zen_expression::ExpressionKind; + +use crate::compiled::exact::policy::Exact; +use crate::policy::blocks::{Block, BlockKind, ExecutionError}; +use crate::policy::evaluator::EvalArtifact; +use crate::policy::host::{Evaluate, HostState, Pick, Picked, Site}; +use crate::workspace::types::{BlockExecution, BlockRef, BlockTrace, EvaluationError}; + +pub(crate) struct Host<'a> { + pub(crate) state: HostState<'a>, + session: Session, +} + +impl<'a> Host<'a> { + pub(crate) fn new( + artifact: &'a EvalArtifact, + store: &'a Variable, + entry: &'a Arc, + trace: bool, + extras: bool, + programs: &Arc, + ) -> Self { + Self { + state: HostState::new(artifact, store, entry, trace, extras), + session: Session::new().with_programs(Some(programs.clone())), + } + } + + pub(crate) fn select( + &mut self, + owner: &BlockRef, + rule: &Block, + ) -> Result { + self.state.select(owner, rule, &mut self.session) + } + + pub(crate) fn commit( + &mut self, + owner: &BlockRef, + rule: &Block, + picked: Picked, + ) -> Result<(), EvaluationError> { + self.state.commit(owner, rule, picked, &mut self.session) + } + + pub(crate) fn executions(self) -> Vec { + self.state.executions() + } + + pub(crate) fn programs<'r>(rules: impl IntoIterator) -> Programs { + let mut sources: Vec<(&'r str, ExpressionKind)> = Vec::new(); + for rule in rules { + rule.kind.sources(&mut sources); + } + Programs::compile(sources) + } +} + +impl BlockKind { + fn sources<'r>(&'r self, out: &mut Vec<(&'r str, ExpressionKind)>) { + let standard = |source: &'r Arc| { + (!source.is_empty()).then(|| (source.as_ref(), ExpressionKind::Standard)) + }; + match self { + BlockKind::Expression(ir) => out.extend(standard(&ir.value)), + BlockKind::Assertion(ir) => { + out.extend(ir.conditions.iter().filter_map(|c| standard(&c.expression))) + } + BlockKind::Match(ir) => out.extend( + ir.arms + .iter() + .flat_map(|arm| [standard(&arm.condition), standard(&arm.value)]) + .flatten(), + ), + BlockKind::DecisionTable(ir) => { + for col in &ir.outputs { + out.extend( + ir.rules + .iter() + .filter_map(|rule| rule.get(&col.id)) + .filter_map(standard), + ); + } + for col in &ir.inputs { + let kind = match col.field.as_ref().and_then(standard) { + Some(field) => { + out.push(field); + ExpressionKind::Unary + } + None => ExpressionKind::Standard, + }; + out.extend( + ir.rules + .iter() + .filter_map(|rule| rule.get(&col.id)) + .filter(|cell| !cell.is_empty()) + .map(|cell| (cell.as_ref(), kind.clone())), + ); + } + } + } + } +} + +impl Evaluate for Session { + fn environment(&mut self, env: Variable) { + self.set_environment(env); + } + + fn select(&mut self, rule: &Block, site: &Site) -> Result { + let mut exact = Exact { + session: self, + site, + }; + match &rule.kind { + BlockKind::Match(m) => exact.select_match(m).map(Pick::Match), + BlockKind::DecisionTable(d) => exact.select_table(d).map(Pick::Table), + BlockKind::Expression(_) | BlockKind::Assertion(_) => Ok(Pick::Unconditional), + } + } + + fn commit( + &mut self, + rule: &Block, + site: &Site, + pick: &Pick, + ) -> Result { + let mut exact = Exact { + session: self, + site, + }; + match (&rule.kind, pick) { + (BlockKind::Match(m), Pick::Match(selection)) => exact.commit_match(m, selection), + (BlockKind::DecisionTable(d), Pick::Table(selection)) => { + exact.commit_table(d, selection) + } + _ => exact.execute(rule), + } + } +} diff --git a/core/engine/src/compiled/policy/mod.rs b/core/engine/src/compiled/policy/mod.rs new file mode 100644 index 00000000..378eb82b --- /dev/null +++ b/core/engine/src/compiled/policy/mod.rs @@ -0,0 +1,930 @@ +mod columnar; +mod entity; +mod host; +mod schedule; +mod traced; + +pub(crate) use host::Host; + +use crate::compiled::core::special::Specialized; +use crate::compiled::leaf::Literal; +use crate::compiled::table::{Table, TableIr}; +use crate::policy::blocks::Block; +use crate::policy::blocks::{AssertionIr, BlockKind, MatchIr, MatchSelection}; +use crate::policy::evaluator::{EvalArtifact, Iteration}; +use crate::policy::host::{HostState, InstanceSlot, Iterated, Pick, Picked}; +use crate::workspace::types::BlockRef; +use crate::workspace::types::{EvaluateRequest, EvaluationError, EvaluationResult}; +use schedule::{Blocks, Demand, End, Event, Replay, Segment}; +use std::cell::RefCell; +use std::sync::Arc; +use std::time::Instant; +use zen_expression::lane::SourceInfo; +use zen_expression::lane::{LaneProgram, LaneRunner, Programs}; +use zen_expression::{Scope, Variable}; +use zen_types::path::DotPath; + +enum Native { + Expression { + key: Arc, + program: Box, + }, + Assertion { + ir: Arc, + conditions: Vec, + }, + Match { + ir: Arc, + conditions: Vec>, + values: Vec>, + pick: Option>, + constants: Vec>, + }, +} + +#[derive(Debug, Clone)] +enum Refused { + Kind, + Iterated, + Compile(Arc), +} + +impl std::fmt::Display for Refused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Refused::Kind => f.write_str("block kind"), + Refused::Iterated => f.write_str("iteration not lane safe"), + Refused::Compile(why) => write!(f, "compile: {why}"), + } + } +} + +impl Native { + fn program(source: &str) -> Result { + LaneProgram::standard(source).map_err(|e| Refused::Compile(Arc::from(e.to_string()))) + } + + fn optional(source: &str) -> Result, Refused> { + match source.is_empty() { + true => Ok(None), + false => Self::program(source).map(Some), + } + } + + fn pick(ir: &MatchIr) -> Option> { + let mut source = String::new(); + let mut open = 0usize; + let mut tail = String::from("null"); + for (index, arm) in ir.arms.iter().enumerate() { + if arm.condition.is_empty() { + tail = index.to_string(); + break; + } + source.push_str(&format!("(({}) == true) ? {index} : (", arm.condition)); + open += 1; + } + source.push_str(&tail); + source.push_str(&")".repeat(open)); + LaneProgram::standard(&source).ok().map(Box::new) + } + + fn compile(kind: &BlockKind) -> Result { + match kind { + BlockKind::Expression(ir) if !ir.key.is_empty() && !ir.value.is_empty() => { + Self::program(&ir.value).map(|program| Native::Expression { + key: ir.key.clone(), + program: Box::new(program), + }) + } + BlockKind::Assertion(ir) => Ok(Native::Assertion { + ir: ir.clone(), + conditions: ir + .conditions + .iter() + .map(|c| Self::program(&c.expression)) + .collect::, _>>()?, + }), + BlockKind::Match(ir) => { + let values = ir + .arms + .iter() + .map(|arm| Self::optional(&arm.value)) + .collect::, _>>()?; + let mut runner = LaneRunner::new(); + let constants = values + .iter() + .map(|value| Literal::constant(&mut runner, value.as_ref()?)) + .collect(); + Ok(Native::Match { + ir: ir.clone(), + conditions: ir + .arms + .iter() + .map(|arm| Self::optional(&arm.condition)) + .collect::, _>>()?, + values, + pick: Self::pick(ir), + constants, + }) + } + _ => Err(Refused::Kind), + } + } +} + +struct BlockPlan { + native: Result, + iterated: bool, + table: Option
, + member: Option, + iteration: Option, +} + +impl BlockPlan { + fn native(&self) -> Option<&Native> { + self.native.as_ref().ok() + } + + fn refused(&self) -> Option<&Refused> { + self.native.as_ref().err() + } +} + +struct Write { + path: Arc, + value: Variable, +} + +struct Capture { + row: usize, + iterated: Iterated, + span: std::ops::Range, +} + +struct Lane { + owner: usize, + index: usize, + root: Variable, + slot: InstanceSlot, +} + +enum Arm { + Failed, + Matched(Option>), +} + +pub(crate) struct PolicyPlan { + blocks: Blocks, + plans: Vec, + roots: Vec>, + root: Arc, + special: std::sync::RwLock>>, + safe: std::sync::OnceLock>, + dated_tables: std::sync::OnceLock, + fusions: columnar::Fusions, + programs: Arc, +} + +struct Rows<'a> { + hosts: Vec>>, + picks: Vec>, + failures: Vec>, +} + +impl Rows<'_> { + fn ensure(&mut self) { + let rows = self.failures.len(); + if self.hosts.len() < rows { + self.hosts.resize_with(rows, || None); + } + if self.picks.len() < rows { + self.picks.resize_with(rows, Vec::new); + } + } + + fn alive(&self, rows: &mut Vec) { + rows.retain(|&row| self.failures[row].is_none()); + } + + fn take(&mut self, row: usize, block: usize) -> Option { + let picks = &mut self.picks[row]; + let at = picks.iter().position(|(b, _)| *b == block)?; + Some(picks.swap_remove(at).1) + } + + fn picked(&self, row: usize, block: usize) -> Option<&Picked> { + self.picks + .get(row)? + .iter() + .find(|(b, _)| *b == block) + .map(|(_, p)| p) + } +} + +impl PolicyPlan { + const SPECIAL: usize = 4096; + + thread_local! { + static RUNNER: RefCell = RefCell::new(LaneRunner::new()); + } + + pub(crate) fn compile(artifact: &EvalArtifact, roots: Vec>) -> Self { + let blocks = Blocks::new(artifact); + let root = Arc::new( + Replay { + artifact, + blocks: &blocks, + roots: &roots, + } + .segment(&[]), + ); + let plans = blocks + .rules + .iter() + .zip(&blocks.refs) + .map(|(rule, owner)| { + let iteration = artifact.iteration(rule); + let (native, iterated) = match &iteration { + None => (Native::compile(&rule.kind), false), + Some((_, path, _)) if Self::lane_safe(artifact, owner, rule, path) => { + (Native::compile(&rule.kind), true) + } + Some(_) => (Err(Refused::Iterated), false), + }; + BlockPlan { + native, + iterated, + table: match &rule.kind { + BlockKind::DecisionTable(ir) => Table::compile(TableIr::policy(ir)).ok(), + _ => None, + }, + member: iteration + .as_ref() + .and_then(|_| Native::compile(&rule.kind).ok()), + iteration, + } + }) + .collect(); + Self { + blocks, + plans, + roots, + root, + special: std::sync::RwLock::new(Specialized::new(Self::SPECIAL)), + safe: std::sync::OnceLock::new(), + dated_tables: std::sync::OnceLock::new(), + fusions: columnar::Fusions::default(), + programs: artifact.programs(), + } + } + + fn signature(columns: &zen_expression::lane::Columns) -> u64 { + use std::hash::{Hash, Hasher}; + use zen_expression::lane::{Column, Dictionary, Values}; + let mut hasher = ahash::AHasher::default(); + let shape = |column: &Column, hasher: &mut ahash::AHasher| { + std::mem::discriminant(&column.values).hash(hasher); + column.validity.is_some().hash(hasher); + }; + for (name, column) in &columns.columns { + name.hash(&mut hasher); + shape(column, &mut hasher); + if let Values::List { child, .. } = column.values { + let child = match child { + Dictionary::Column(child) => *child, + other => other.column(), + }; + shape(&child, &mut hasher); + if let Values::Struct { fields, .. } = child.values { + for (field, column) in fields { + field.hash(&mut hasher); + shape(column, &mut hasher); + } + } + } + } + hasher.finish() + } + + fn special( + &self, + program: &LaneProgram, + columns: &zen_expression::lane::Columns, + ) -> Option> { + let key = (program.program().id as usize, Self::signature(columns)); + if let Some(found) = self.special.read().ok().and_then(|cache| cache.get(&key)) { + return Some(found); + } + let built = Arc::new(program.specialize_columns(columns).ok()?); + if let Ok(mut cache) = self.special.write() { + cache.insert(key, built.clone()); + } + Some(built) + } + + fn lane_safe(artifact: &EvalArtifact, owner: &BlockRef, rule: &Block, iter_path: &str) -> bool { + let Some(reads) = artifact.reads.get(owner) else { + return false; + }; + let overlaps = + |a: &str, b: &str| a == b || DotPath::indexed(a, b) || DotPath::indexed(b, a); + let writes: Vec> = rule + .kind + .write_sites() + .into_iter() + .map(|w| w.path) + .collect(); + let reads_safe = reads.iter().all(|read| { + !read.unresolved + && !overlaps(&read.path, iter_path) + && writes.iter().all(|w| !overlaps(&read.path, w)) + }); + reads_safe + && rule + .kind + .expressions(&rule.id) + .iter() + .all(|e| !SourceInfo::reads_root(&e.source) && !SourceInfo::reads_dollar(&e.source)) + } + + fn child(&self, artifact: &EvalArtifact, segment: &Segment, demand: Demand) -> Arc { + let End::Branch { children, .. } = &segment.end else { + return Arc::new(Segment::finished()); + }; + children.get(&demand, || { + let mut path = segment.path.to_vec(); + path.push(demand.clone()); + Arc::new( + Replay { + artifact, + blocks: &self.blocks, + roots: &self.roots, + } + .segment(&path), + ) + }) + } + + pub(crate) fn evaluate( + &self, + artifact: &EvalArtifact, + requests: &[EvaluateRequest], + ) -> Vec> { + let start = Instant::now(); + let count = requests.len(); + let mut failures: Vec> = (0..count).map(|_| None).collect(); + let stores: Vec> = requests + .iter() + .enumerate() + .map(|(row, request)| match artifact.prepare(request) { + Ok((store, _)) => Some(store), + Err(error) => { + failures[row] = Some(error); + None + } + }) + .collect(); + let mut state = Rows { + hosts: stores + .iter() + .zip(requests) + .map(|(store, request)| { + store.as_ref().map(|store| { + Host::new( + artifact, + store, + &request.policy_path, + false, + false, + &self.programs, + ) + }) + }) + .collect(), + picks: (0..count).map(|_| Vec::new()).collect(), + failures, + }; + + let rows: Vec = (0..count) + .filter(|&row| state.hosts[row].is_some()) + .collect(); + let mut stack: Vec<(Arc, Vec)> = vec![(self.root.clone(), rows)]; + while let Some((segment, mut rows)) = stack.pop() { + for event in &segment.events { + state.alive(&mut rows); + if rows.is_empty() { + break; + } + match *event { + Event::Select(block) => self.select(block, &rows, &mut state), + Event::Commit(block) => self.commit(block, &rows, &mut state), + } + } + state.alive(&mut rows); + if rows.is_empty() { + continue; + } + let End::Branch { block, .. } = &segment.end else { + continue; + }; + let owner = &self.blocks.refs[*block]; + let mut groups: Vec<(Demand, Vec)> = Vec::new(); + for &row in &rows { + let demand: Demand = match (state.hosts[row].as_ref(), state.picked(row, *block)) { + (Some(host), Some(picked)) => host.state.demanded(owner, picked).into(), + _ => Arc::from([]), + }; + match groups.iter_mut().find(|(d, _)| *d == demand) { + Some((_, members)) => members.push(row), + None => groups.push((demand, vec![row])), + } + } + for (demand, members) in groups.into_iter().rev() { + stack.push((self.child(artifact, &segment, demand), members)); + } + } + + let duration = start.elapsed(); + let Rows { failures, .. } = state; + failures + .into_iter() + .zip(stores) + .map(|(failure, store)| match (failure, store) { + (Some(error), _) => Err(error), + (None, Some(store)) => Ok(EvaluationResult { + output: store, + duration, + trace: None, + }), + (None, None) => Ok(EvaluationResult { + output: Variable::Null, + duration, + trace: None, + }), + }) + .collect() + } + + fn select(&self, block: usize, rows: &[usize], state: &mut Rows) { + let plan = &self.plans[block]; + match (plan.native(), plan.iterated) { + (Some(Native::Match { ir, conditions, .. }), false) => { + let delegated = Self::select_match(block, ir, conditions, rows, state); + self.select_delegated(block, &delegated, state); + } + (Some(Native::Match { ir, conditions, .. }), true) => { + let delegated = self.select_match_iterated(block, ir, conditions, rows, state); + self.select_delegated(block, &delegated, state); + } + _ => self.select_delegated(block, rows, state), + } + } + + fn select_delegated(&self, block: usize, rows: &[usize], state: &mut Rows) { + let (owner, rule) = (&self.blocks.refs[block], &self.blocks.rules[block]); + for &row in rows { + let Some(host) = state.hosts[row].as_mut() else { + continue; + }; + match host.select(owner, rule) { + Ok(picked) => state.picks[row].push((block, picked)), + Err(error) => state.failures[row] = Some(error), + } + } + } + + fn commit(&self, block: usize, rows: &[usize], state: &mut Rows) { + let plan = &self.plans[block]; + if let (Some(native), true) = (plan.native(), plan.iterated) { + let delegated = self.commit_iterated(block, native, rows, state); + self.delegate(block, &delegated, state); + return; + } + match plan.native() { + Some(Native::Expression { key, program }) => { + let delegated = self.expression(key, program, rows, state); + self.delegate(block, &delegated, state); + } + Some(Native::Assertion { ir, conditions }) => { + let delegated = Self::assertion(ir, conditions, rows, state); + self.delegate(block, &delegated, state); + } + Some(Native::Match { ir, values, .. }) => { + let delegated = Self::commit_match(block, ir, values, rows, state); + self.delegate(block, &delegated, state); + } + None => self.delegate(block, rows, state), + } + } + + fn delegate(&self, block: usize, rows: &[usize], state: &mut Rows) { + let (owner, rule) = (&self.blocks.refs[block], &self.blocks.rules[block]); + for &row in rows { + let picked = state.take(row, block); + let Some(host) = state.hosts[row].as_mut() else { + continue; + }; + let result = match picked { + Some(picked) => host.commit(owner, rule, picked), + None => host + .select(owner, rule) + .and_then(|picked| host.commit(owner, rule, picked)), + }; + if let Err(error) = result { + state.failures[row] = Some(error); + } + } + } + + fn scopes(rows: &[usize], state: &Rows) -> (Vec, Vec) { + rows.iter() + .filter_map(|&row| { + let host = state.hosts[row].as_ref()?; + host.state.clear_dollar(); + Some((row, Scope::new(host.state.env().shallow_clone()))) + }) + .unzip() + } + + fn run( + program: &LaneProgram, + scopes: &[Scope], + sink: impl FnMut(usize, Result), + ) { + Self::RUNNER.with_borrow_mut(|runner| runner.evaluate_with(program, scopes, sink)); + } + + fn arms(ir: &MatchIr, conditions: &[Option], scopes: Vec) -> Vec { + let mut outcome: Vec> = (0..scopes.len()).map(|_| None).collect(); + let mut open: Vec = (0..scopes.len()).collect(); + let mut scopes = scopes; + for (arm, condition) in ir.arms.iter().zip(conditions) { + if open.is_empty() { + break; + } + let Some(program) = condition else { + for lane in open.drain(..) { + outcome[lane] = Some(Arm::Matched(Some(arm.id.clone()))); + } + break; + }; + let mut hit = vec![None; open.len()]; + Self::run(program, &scopes, |i, result| { + hit[i] = Some(result.map(|v| v.as_bool().unwrap_or(false)).ok()) + }); + let mut next_open = Vec::with_capacity(open.len()); + let mut next_scopes = Vec::with_capacity(open.len()); + for ((lane, scope), hit) in open.drain(..).zip(scopes.drain(..)).zip(hit) { + match hit.flatten() { + None => outcome[lane] = Some(Arm::Failed), + Some(true) => outcome[lane] = Some(Arm::Matched(Some(arm.id.clone()))), + Some(false) => { + next_open.push(lane); + next_scopes.push(scope); + } + } + } + open = next_open; + scopes = next_scopes; + } + outcome + .into_iter() + .map(|o| o.unwrap_or(Arm::Matched(None))) + .collect() + } + + fn selection(matched_arm: Option>) -> Pick { + Pick::Match(MatchSelection { + matched_arm, + arms: Vec::new(), + }) + } + + fn select_match( + block: usize, + ir: &MatchIr, + conditions: &[Option], + rows: &[usize], + state: &mut Rows, + ) -> Vec { + let (live, scopes) = Self::scopes(rows, state); + let mut delegated = Vec::new(); + for (row, arm) in live.into_iter().zip(Self::arms(ir, conditions, scopes)) { + match arm { + Arm::Failed => delegated.push(row), + Arm::Matched(matched_arm) => { + state.picks[row].push((block, Picked::Singleton(Self::selection(matched_arm)))) + } + } + } + delegated + } + + fn lanes(&self, block: usize, rows: &[usize], state: &mut Rows) -> (Vec, Vec) { + let rule = &self.blocks.rules[block]; + let mut lanes = Vec::new(); + let mut captured = Vec::new(); + for &row in rows { + let picked = state.take(row, block); + let Some(host) = state.hosts[row].as_ref() else { + continue; + }; + let iterated = match picked { + Some(Picked::Iterated(iterated)) => iterated, + Some(Picked::Skipped) => continue, + Some(other) => { + state.picks[row].push((block, other)); + continue; + } + None => match host.state.capture(rule) { + Some(iterated) => iterated, + None => continue, + }, + }; + let (start, owner) = (lanes.len(), captured.len()); + for (index, bound) in host + .state + .instance_scopes(&iterated) + .into_iter() + .enumerate() + { + if let Some((root, slot)) = bound { + lanes.push(Lane { + owner, + index, + root, + slot, + }); + } + } + captured.push(Capture { + row, + iterated, + span: start..lanes.len(), + }); + } + (lanes, captured) + } + + fn select_match_iterated( + &self, + block: usize, + ir: &MatchIr, + conditions: &[Option], + rows: &[usize], + state: &mut Rows, + ) -> Vec { + let (lanes, captured) = self.lanes(block, rows, state); + let scopes: Vec = lanes + .iter() + .map(|l| Scope::new(l.root.shallow_clone())) + .collect(); + let arms = Self::arms(ir, conditions, scopes); + let mut delegated = Vec::new(); + for Capture { + row, + iterated, + span, + } in captured + { + let mut picks: Vec = iterated + .instances() + .iter() + .map(|_| Pick::Unconditional) + .collect(); + let mut failed = false; + for (lane, arm) in lanes[span.clone()].iter().zip(&arms[span]) { + match arm { + Arm::Failed => failed = true, + Arm::Matched(matched_arm) => { + picks[lane.index] = Self::selection(matched_arm.clone()) + } + } + } + match failed { + true => delegated.push(row), + false => state.picks[row].push((block, iterated.picked(picks))), + } + } + delegated + } + + fn commit_iterated( + &self, + block: usize, + native: &Native, + rows: &[usize], + state: &mut Rows, + ) -> Vec { + let (owner, rule) = (&self.blocks.refs[block], &self.blocks.rules[block]); + let (lanes, captured) = self.lanes(block, rows, state); + let scopes: Vec = lanes + .iter() + .map(|l| Scope::new(l.root.shallow_clone())) + .collect(); + let mut writes: Vec>> = (0..lanes.len()).map(|_| None).collect(); + match native { + Native::Expression { key, program } => Self::run(program, &scopes, |i, result| { + writes[i] = result.ok().map(|value| { + Some(Write { + path: key.clone(), + value, + }) + }) + }), + Native::Assertion { ir, conditions } => { + let mut results: Vec>> = + (0..lanes.len()).map(|_| Some(Vec::new())).collect(); + for program in conditions { + Self::run(program, &scopes, |i, result| { + match (result, &mut results[i]) { + (Ok(value), Some(r)) => r.push(value.as_bool().unwrap_or(false)), + _ => results[i] = None, + } + }); + } + for (i, result) in results.into_iter().enumerate() { + writes[i] = result.map(|r| { + (!ir.output.is_empty()).then(|| Write { + path: ir.output.clone(), + value: Variable::Bool(ir.fold(&r)), + }) + }); + } + } + Native::Match { ir, values, .. } => { + let key = (!ir.key.is_empty()).then(|| ir.key.clone()); + let arm_of = |lane: &Lane| match captured + .get(lane.owner)? + .iterated + .picks() + .get(lane.index)? + { + Pick::Match(selection) => { + let id = selection.matched_arm.as_ref()?; + ir.arms.iter().position(|a| &a.id == id) + } + _ => None, + }; + let mut groups: Vec> = vec![Vec::new(); ir.arms.len()]; + for (i, lane) in lanes.iter().enumerate() { + match arm_of(lane).filter(|&arm| values[arm].is_some()) { + Some(arm) => groups[arm].push(i), + None => { + writes[i] = Some(key.clone().map(|path| Write { + path, + value: Variable::Null, + })) + } + } + } + for (arm, members) in groups.into_iter().enumerate() { + let Some(program) = values[arm].as_ref().filter(|_| !members.is_empty()) else { + continue; + }; + let subset: Vec = members.iter().map(|&i| scopes[i].clone()).collect(); + Self::run(program, &subset, |j, result| { + writes[members[j]] = result + .ok() + .map(|value| key.clone().map(|path| Write { path, value })) + }); + } + } + } + let mut delegated = Vec::new(); + for Capture { + row, + iterated, + span, + } in captured + { + let failed = writes[span.clone()].iter().any(Option::is_none); + if failed { + match iterated.picks().is_empty() { + true => delegated.push(row), + false => { + if let Some(host) = state.hosts[row].as_mut() { + if let Err(error) = host.commit(owner, rule, Picked::Iterated(iterated)) + { + state.failures[row] = Some(error); + } + } + } + } + continue; + } + for (lane, write) in lanes[span.clone()].iter().zip(&writes[span]) { + if let Some(Some(Write { path, value })) = write { + HostState::write_into(&lane.root, None, path, value.clone()); + } + lane.slot.write_back(&iterated.instances()[lane.index]); + } + } + delegated + } + + fn commit_match( + block: usize, + ir: &MatchIr, + values: &[Option], + rows: &[usize], + state: &mut Rows, + ) -> Vec { + let mut delegated = Vec::new(); + let mut by_arm: Vec> = vec![Vec::new(); ir.arms.len()]; + let mut nulls: Vec = Vec::new(); + for &row in rows { + let arm = match state.picked(row, block) { + Some(Picked::Singleton(Pick::Match(selection))) => selection + .matched_arm + .as_ref() + .and_then(|id| ir.arms.iter().position(|a| &a.id == id)), + _ => { + delegated.push(row); + continue; + } + }; + match arm { + Some(arm) if values[arm].is_some() => by_arm[arm].push(row), + _ => nulls.push(row), + } + } + for row in nulls { + state.take(row, block); + if let (false, Some(host)) = (ir.key.is_empty(), state.hosts[row].as_ref()) { + host.state.write(&ir.key, Variable::Null); + } + } + for (arm, members) in by_arm.into_iter().enumerate() { + let Some(program) = values[arm].as_ref().filter(|_| !members.is_empty()) else { + continue; + }; + let (live, scopes) = Self::scopes(&members, state); + let mut results: Vec> = vec![None; live.len()]; + Self::run(program, &scopes, |i, result| results[i] = result.ok()); + for (row, result) in live.into_iter().zip(results) { + match result { + Some(value) => { + state.take(row, block); + if let (false, Some(host)) = (ir.key.is_empty(), state.hosts[row].as_ref()) + { + host.state.write(&ir.key, value); + } + } + None => delegated.push(row), + } + } + } + delegated + } + + fn assertion( + ir: &AssertionIr, + conditions: &[LaneProgram], + rows: &[usize], + state: &mut Rows, + ) -> Vec { + let (live, scopes) = Self::scopes(rows, state); + let mut results: Vec> = vec![Vec::with_capacity(conditions.len()); live.len()]; + let mut failed = vec![false; live.len()]; + for program in conditions { + Self::run(program, &scopes, |i, result| match result { + Ok(value) => results[i].push(value.as_bool().unwrap_or(false)), + Err(_) => failed[i] = true, + }); + } + let mut delegated = Vec::new(); + for (i, row) in live.into_iter().enumerate() { + if failed[i] { + delegated.push(row); + continue; + } + let outcome = ir.fold(&results[i]); + if let (false, Some(host)) = (ir.output.is_empty(), state.hosts[row].as_ref()) { + host.state.write(&ir.output, Variable::Bool(outcome)); + } + } + delegated + } + + fn expression( + &self, + key: &Arc, + program: &LaneProgram, + rows: &[usize], + state: &mut Rows, + ) -> Vec { + let (live, scopes) = Self::scopes(rows, state); + let mut delegated = Vec::new(); + Self::RUNNER.with_borrow_mut(|runner| { + runner.evaluate_with(program, &scopes, |i, result| { + let row = live[i]; + match (result, state.hosts[row].as_ref()) { + (Ok(value), Some(host)) => host.state.write(key, value), + _ => delegated.push(row), + } + }) + }); + delegated + } +} diff --git a/core/engine/src/compiled/policy/schedule.rs b/core/engine/src/compiled/policy/schedule.rs new file mode 100644 index 00000000..9d89b2b9 --- /dev/null +++ b/core/engine/src/compiled/policy/schedule.rs @@ -0,0 +1,174 @@ +use crate::compiled::core::segments::Children; +use crate::policy::blocks::{Block, BlockKind, ConditionalReads}; +use crate::policy::evaluator::EvalArtifact; +use crate::workspace::types::BlockRef; +use ahash::{HashMap, HashSet}; +use std::sync::Arc; + +pub(crate) type Demand = Arc<[Arc]>; + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Event { + Select(usize), + Commit(usize), +} + +pub(crate) enum End { + Finish, + Branch { + block: usize, + children: Children>, + }, +} + +pub(crate) struct Segment { + pub(crate) path: Arc<[Demand]>, + pub(crate) events: Vec, + pub(crate) end: End, +} + +impl Segment { + pub(crate) fn finished() -> Self { + Self { + path: Arc::from([]), + events: Vec::new(), + end: End::Finish, + } + } +} + +pub(crate) struct Blocks { + pub(crate) refs: Vec, + pub(crate) rules: Vec>, + index: HashMap, +} + +impl Blocks { + pub(crate) fn new(artifact: &EvalArtifact) -> Self { + let mut entries: Vec<(&BlockRef, &Arc)> = artifact.rule_by_ref.iter().collect(); + entries.sort_by(|(a, _), (b, _)| { + (a.policy_path.as_ref(), a.block_id.as_ref()) + .cmp(&(b.policy_path.as_ref(), b.block_id.as_ref())) + }); + let refs: Vec = entries.iter().map(|(r, _)| (*r).clone()).collect(); + let rules = entries.iter().map(|(_, b)| (*b).clone()).collect(); + let index = refs + .iter() + .enumerate() + .map(|(i, r)| (r.clone(), i)) + .collect(); + Self { refs, rules, index } + } + + pub(crate) fn selects(rule: &Block) -> bool { + matches!(rule.kind, BlockKind::Match(_) | BlockKind::DecisionTable(_)) + } +} + +struct Stop; + +struct Sim<'a> { + artifact: &'a EvalArtifact, + blocks: &'a Blocks, + script: &'a [Demand], + used: usize, + start: usize, + ran: HashSet, + in_progress: HashSet, + events: Vec, + stopped: Option, +} + +impl Sim<'_> { + fn demand(&mut self, prop: &str) -> Result<(), Stop> { + for owner in self.artifact.writers_of_longest_prefix(prop) { + self.run_block(owner)?; + } + Ok(()) + } + + fn run_block(&mut self, owner: &BlockRef) -> Result<(), Stop> { + let Some(&block) = self.blocks.index.get(owner) else { + return Ok(()); + }; + if self.ran.contains(&block) || !self.in_progress.insert(block) { + return Ok(()); + } + let result = self.inner(owner, block); + self.in_progress.remove(&block); + if result.is_ok() { + self.ran.insert(block); + } + result + } + + fn inner(&mut self, owner: &BlockRef, block: usize) -> Result<(), Stop> { + let plan = self.artifact.read_plans.get(owner); + if let Some(plan) = plan { + for path in plan.unconditional.iter() { + self.demand(path)?; + } + } + let rule = &self.blocks.rules[block]; + if Blocks::selects(rule) { + self.events.push(Event::Select(block)); + let conditional = + plan.is_some_and(|p| !matches!(p.conditional, ConditionalReads::None)); + if conditional { + let Some(demand) = self.script.get(self.used) else { + self.stopped = Some(block); + return Err(Stop); + }; + self.used += 1; + if self.used == self.script.len() { + self.start = self.events.len(); + } + for path in demand.iter() { + self.demand(path)?; + } + } + } + self.events.push(Event::Commit(block)); + Ok(()) + } +} + +pub(crate) struct Replay<'a> { + pub(crate) artifact: &'a EvalArtifact, + pub(crate) blocks: &'a Blocks, + pub(crate) roots: &'a [Arc], +} + +impl Replay<'_> { + pub(crate) fn segment(&self, script: &[Demand]) -> Segment { + let mut sim = Sim { + artifact: self.artifact, + blocks: self.blocks, + script, + used: 0, + start: 0, + ran: HashSet::default(), + in_progress: HashSet::default(), + events: Vec::new(), + stopped: None, + }; + let finished = self + .roots + .iter() + .try_for_each(|root| sim.demand(root)) + .is_ok(); + let events = sim.events.split_off(sim.start.min(sim.events.len())); + let end = match (finished, sim.stopped) { + (false, Some(block)) => End::Branch { + block, + children: Children::new(), + }, + _ => End::Finish, + }; + Segment { + path: script.into(), + events, + end, + } + } +} diff --git a/core/engine/src/compiled/policy/traced.rs b/core/engine/src/compiled/policy/traced.rs new file mode 100644 index 00000000..6e99a350 --- /dev/null +++ b/core/engine/src/compiled/policy/traced.rs @@ -0,0 +1,78 @@ +use std::sync::Arc; +use std::time::Instant; + +use super::schedule::{Demand, End, Event}; +use super::{Host, PolicyPlan}; +use crate::policy::evaluator::{EvalArtifact, StoreOps}; +use crate::policy::host::Picked; +use crate::workspace::types::{EvaluateRequest, EvaluationError, EvaluationResult, Trace}; + +impl PolicyPlan { + pub(crate) fn traced( + &self, + artifact: &EvalArtifact, + req: &EvaluateRequest, + extras: bool, + ) -> Result { + let start = Instant::now(); + let (store, order_to_run) = artifact.prepare(req)?; + let mut host = Host::new( + artifact, + &store, + &req.policy_path, + req.trace, + extras, + &self.programs, + ); + let outcome = self.replay(artifact, &mut host); + + let trace = req.trace.then(|| Trace { + engine_version: Arc::from(crate::ENGINE_VERSION), + properties: store.snapshot(&order_to_run), + executions: host.executions(), + }); + + if let Err(error) = outcome { + return Err(error.with_partial_trace(trace)); + } + + Ok(EvaluationResult { + output: store, + duration: start.elapsed(), + trace, + }) + } + + fn replay(&self, artifact: &EvalArtifact, host: &mut Host) -> Result<(), EvaluationError> { + let mut segment = self.root.clone(); + let mut picks: Vec<(usize, Picked)> = Vec::new(); + loop { + for event in &segment.events { + match *event { + Event::Select(block) => { + let picked = + host.select(&self.blocks.refs[block], &self.blocks.rules[block])?; + picks.push((block, picked)); + } + Event::Commit(block) => { + let (owner, rule) = (&self.blocks.refs[block], &self.blocks.rules[block]); + let picked = match picks.iter().position(|(b, _)| *b == block) { + Some(at) => picks.swap_remove(at).1, + None => host.select(owner, rule)?, + }; + host.commit(owner, rule, picked)?; + } + } + } + let End::Branch { block, .. } = &segment.end else { + return Ok(()); + }; + let owner = &self.blocks.refs[*block]; + let demand: Demand = match picks.iter().find(|(b, _)| b == block) { + Some((_, picked)) => host.state.demanded(owner, picked).into(), + None => Arc::from([]), + }; + segment = self.child(artifact, &segment, demand); + } + } +} diff --git a/core/engine/src/compiled/shred.rs b/core/engine/src/compiled/shred.rs new file mode 100644 index 00000000..3823fce3 --- /dev/null +++ b/core/engine/src/compiled/shred.rs @@ -0,0 +1,1823 @@ +use crate::compiled::core::list::Frame; +use crate::compiled::leaf::{Array, Bits, Dict, Leaf, Records, Store}; +use crate::compiled::output::OutputColumn; +use crate::nodes::input::dates::DeclaredDates; +use std::cell::Ref; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Column, Dictionary, Scaled, ShortKey, Values}; +use zen_expression::typed::{Class, ColumnDef}; +use zen_expression::Variable; +use zen_types::variable::Shape; + +pub(crate) struct Normalizer; + +pub(crate) type Shredded<'a> = (Arc, Leaf<'a>, Option>); +type Outputs<'a> = Vec<(Arc, OutputColumn<'a>)>; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Seen { + Num, + Bool, + Text, + Null, + List, + Mixed, +} + +pub(crate) struct Coder<'d> { + data: &'d [u8], + slots: [u8; Coder::SLOTS], + entries: Vec<((u64, u64, usize), usize)>, +} + +struct Interner { + slots: [u8; Coder::SLOTS], + keys: Vec<(u64, u64, usize)>, + offsets: Vec, + data: String, +} + +struct Trie { + path: Arc, + children: Vec<(Arc, usize)>, + column: Option, +} + +pub(crate) struct Shredder { + rows: usize, + nodes: Vec, + columns: Vec<(Arc, Vec, Vec)>, +} + +pub(crate) struct Listing<'a> { + pub frame: Frame, + pub hosted: Option>, + pub fields: Vec<(Arc, Leaf<'a>)>, +} + +pub(crate) struct Shred { + pub frame: Frame, + pub fields: Vec<(Arc, Array)>, + pub hosted: Rc<[usize]>, +} + +impl Shredder { + pub(crate) fn new(rows: usize) -> Self { + Self { + rows, + nodes: vec![Trie { + path: Arc::from(""), + children: Vec::new(), + column: None, + }], + columns: Vec::new(), + } + } + + fn child(&mut self, node: usize, key: &str) -> usize { + if let Some((_, at)) = self.nodes[node] + .children + .iter() + .find(|(k, _)| k.as_ref() == key) + { + return *at; + } + let path: Arc = match self.nodes[node].path.is_empty() { + true => Arc::from(key), + false => Arc::from(format!("{}.{key}", self.nodes[node].path)), + }; + self.nodes.push(Trie { + path, + children: Vec::new(), + column: None, + }); + let at = self.nodes.len() - 1; + self.nodes[node].children.push((Arc::from(key), at)); + at + } + + fn put(&mut self, node: usize, row: usize, value: Variable) { + let column = match self.nodes[node].column { + Some(column) => column, + None => { + self.columns.push(( + self.nodes[node].path.clone(), + vec![Variable::Null; self.rows], + vec![0u64; self.rows.div_ceil(64)], + )); + self.nodes[node].column = Some(self.columns.len() - 1); + self.columns.len() - 1 + } + }; + let (_, values, present) = &mut self.columns[column]; + values[row] = value; + Bits::set(present, row, true); + } + + pub(crate) fn visit(&mut self, value: &Variable, node: usize, row: usize) { + match value { + Variable::Object(map) => { + let map = map.borrow(); + if map + .iter() + .any(|(key, _)| key.is_empty() || key.contains('.')) + { + self.put(node, row, value.clone()); + return; + } + for (key, child) in map.iter() { + let at = self.child(node, key); + self.visit(child, at, row); + } + } + Variable::Null => {} + other => self.put(node, row, other.clone()), + } + } + + pub(crate) fn finish<'a>(self) -> Vec> { + let rows = self.rows; + self.columns + .into_iter() + .map(|(path, values, present)| { + let mut field = FieldBuilder::new(path.clone(), 0, false); + for (row, value) in values.iter().enumerate() { + match Bits::get(&present, row) { + true => field.push(value, rows), + false => field.missing(), + } + } + let (_, array) = field.array(); + (path, Leaf::typed(array), Some(present.into())) + }) + .collect() + } + + pub(crate) fn output<'a>(self) -> Outputs<'a> { + self.finish() + .into_iter() + .map(|(path, leaf, present)| match present { + Some(present) => (path, OutputColumn(Leaf::masked(leaf, &present))), + None => (path, OutputColumn(leaf)), + }) + .collect() + } + + pub(crate) fn results<'a, T, E>( + results: Vec>, + output: impl Fn(&T) -> &Variable, + ) -> (Outputs<'a>, Vec>) { + let mut shredder = Self::new(results.len()); + let errors = results + .into_iter() + .enumerate() + .map(|(row, result)| match result { + Ok(value) => { + shredder.visit(output(&value), 0, row); + None + } + Err(error) => Some(error), + }) + .collect(); + (shredder.output(), errors) + } +} + +impl Normalizer { + const SAMPLE: usize = 64; + + pub(crate) fn input<'a>(column: Column<'a>, rows: usize) -> Leaf<'a> { + let dated = DeclaredDates::dated; + let nested = match column.values { + Values::Any(values) => values.iter().take(rows).any(dated), + Values::Dict { + values: Dictionary::Any(values), + .. + } + | Values::List { + child: Dictionary::Any(values), + .. + } => values.iter().any(dated), + Values::List { + child: Dictionary::Text { .. } | Dictionary::Scaled { .. } | Dictionary::Bool { .. }, + .. + } => false, + Values::List { + child: Dictionary::Column(child), + .. + } if Self::scalar_struct(child) => false, + Values::Struct { .. } if Self::scalar_struct(&column) => false, + Values::List { .. } + | Values::Dict { + values: Dictionary::Column(_), + .. + } => (0..rows).any(|row| dated(&column.variable(row))), + _ => false, + }; + match nested { + true => Leaf::Any( + (0..rows) + .map(|row| { + let value = column.variable(row); + DeclaredDates::prepare(&value, None).unwrap_or(value) + }) + .collect(), + ), + false => Leaf::input(Self::validated(column, rows), rows), + } + } + + fn scalar_struct(column: &Column) -> bool { + match column.values { + Values::Struct { fields, .. } => fields.iter().all(|(_, field)| { + !matches!( + field.values, + Values::Any(_) + | Values::List { .. } + | Values::Struct { .. } + | Values::Dict { + values: Dictionary::Any(_) | Dictionary::Column(_), + .. + } + ) + }), + _ => false, + } + } + + fn validated<'a>(column: Column<'a>, rows: usize) -> Column<'a> { + let Values::Utf8 { offsets, data } = column.values else { + return column; + }; + let text = offsets + .get(rows) + .and_then(|&end| usize::try_from(end).ok()) + .and_then(|end| data.get(..end)) + .and_then(|bytes| std::str::from_utf8(bytes).ok()); + match text { + Some(data) => Column { + values: Values::Text { offsets, data }, + validity: column.validity, + }, + None => column, + } + } + + pub(crate) fn lean<'a>(column: Column<'a>, rows: usize) -> Leaf<'a> { + let column = Self::validated(column, rows); + let validity = Bits::partial(column.validity, rows); + let column = Column { validity, ..column }; + let unpacked = match column.values { + Values::Dec(values) => values.get(..rows).and_then(Store::unpacked), + _ => None, + }; + match unpacked { + Some(store) => Leaf::typed(Array::parts( + store, + validity.map(|(bits, offset)| Bits::window(bits, offset, rows)), + rows, + )), + None => Leaf::input(column, rows), + } + } + + pub(crate) fn seen(leaf: &Leaf, rows: usize) -> Seen { + if let Some(records) = leaf.records() { + return match records.alive(rows) { + true => Seen::List, + false => Seen::Null, + }; + } + let column = leaf.column(); + let dict; + let values = match column.values { + Values::Dict { values, .. } => { + dict = values.column(); + dict.values + } + values => values, + }; + match values { + Values::Scaled { .. } | Values::I64(_) | Values::Dec(_) => Seen::Num, + Values::Bool { .. } => Seen::Bool, + Values::Text { .. } | Values::Utf8 { .. } => Seen::Text, + Values::Any(values) if !matches!(column.values, Values::Dict { .. }) => { + let mut counts = [0usize; 5]; + let live = + values.iter().take(rows).enumerate().filter(|(row, value)| { + column.valid(*row) && !matches!(value, Variable::Null) + }); + for (_, value) in live.take(Self::SAMPLE) { + let kind = match value { + Variable::Number(_) => 0, + Variable::Bool(_) => 1, + Variable::String(_) => 2, + Variable::Array(_) => 3, + _ => 4, + }; + counts[kind] += 1; + } + let total: usize = counts.iter().sum(); + let (kind, most) = counts[..3] + .iter() + .enumerate() + .max_by_key(|(_, count)| **count) + .map_or((3, 0), |(kind, count)| (kind, *count)); + match (total, most * 2 >= total, kind) { + (0, ..) => Seen::Null, + (_, false, _) if counts[3] * 2 > total => Seen::List, + (_, true, 0) => Seen::Num, + (_, true, 1) => Seen::Bool, + (_, true, 2) => Seen::Text, + _ => Seen::Mixed, + } + } + Values::List { .. } => Seen::List, + _ => Seen::Mixed, + } + } + + pub(crate) fn typed<'a>( + leaf: &Leaf<'a>, + rows: usize, + code: bool, + ) -> Option<(Leaf<'a>, Option>)> { + if leaf.records().is_some() { + return None; + } + let column = leaf.column(); + if let Values::Any(values) = column.values { + return Self::shredded(values.get(..rows)?, &column, Self::seen(leaf, rows), rows); + } + let Leaf::Input(input) = leaf else { + return None; + }; + let column = input.column; + let valid = || Bits::validity(column.validity, rows); + match column.values { + Values::Dec(values) => Some(( + Leaf::typed(Array::parts( + Store::unpacked(values.get(..rows)?)?, + valid(), + rows, + )), + None, + )), + Values::Text { offsets, data } if code => { + let (codes, dict) = Coder::new(data.as_bytes()).codes(offsets.get(..=rows)?)?; + let array = match valid() { + Some(bits) => Array::coded_with(codes.into(), Rc::new(dict), bits), + None => Array::coded(codes.into(), Rc::new(dict)), + }; + Some((Leaf::typed(array), None)) + } + _ => None, + } + } + + fn shredded<'a>( + values: &[Variable], + column: &zen_expression::lane::Column, + seen: Seen, + rows: usize, + ) -> Option<(Leaf<'a>, Option>)> { + let mut valid = vec![0u64; rows.div_ceil(64)]; + let mut faults: Option> = None; + let mut fault = |row: usize| { + Bits::set( + faults.get_or_insert_with(|| vec![0u64; rows.div_ceil(64)]), + row, + true, + ) + }; + let live = values + .iter() + .enumerate() + .filter(|(row, value)| column.valid(*row) && !matches!(value, Variable::Null)); + let store = match seen { + Seen::Num => { + let (mut mant, mut scale) = (vec![0i64; rows], vec![0u8; rows]); + for (row, value) in live { + match value { + Variable::Number(n) => match Scaled::parts(n) { + Some((m, s)) => { + mant[row] = m; + scale[row] = s; + Bits::set(&mut valid, row, true); + } + None => fault(row), + }, + _ => fault(row), + } + } + Store::Scaled { mant, scale } + } + Seen::Bool => { + let mut bits = vec![0u64; rows.div_ceil(64)]; + for (row, value) in live { + match value { + Variable::Bool(b) => { + Bits::set(&mut bits, row, *b); + Bits::set(&mut valid, row, true); + } + _ => fault(row), + } + } + Store::Bool(bits) + } + Seen::Text => { + let mut offsets = vec![0i32; rows + 1]; + let mut data = String::new(); + let mut next = 0; + for (row, value) in live { + offsets[next..=row].fill(i32::try_from(data.len()).ok()?); + match value { + Variable::String(text) => { + data.push_str(text); + Bits::set(&mut valid, row, true); + } + _ => fault(row), + } + next = row + 1; + } + offsets[next..].fill(i32::try_from(data.len()).ok()?); + Store::Text { offsets, data } + } + Seen::Null | Seen::List | Seen::Mixed => return None, + }; + let full = Bits::full(&valid, 0, rows); + Some(( + Leaf::typed(Array::parts(store, (!full).then_some(valid), rows)), + faults, + )) + } +} + +impl<'d> Coder<'d> { + const SLOTS: usize = 128; + const LIMIT: usize = 64; + const SAMPLE: usize = 64; + const SAMPLED: usize = 16; + + fn new(data: &'d [u8]) -> Self { + Self { + data, + slots: [u8::MAX; Self::SLOTS], + entries: Vec::new(), + } + } + + #[inline] + fn code(&mut self, lo: usize, hi: usize) -> Option { + let len = hi.checked_sub(lo)?; + let key = ( + ShortKey::at(self.data, lo, len), + ShortKey::at(self.data, lo + 8, len.saturating_sub(8)), + len, + ); + let mut slot = Self::slot(key); + loop { + match self.slots[slot] { + u8::MAX => { + if self.entries.len() >= Self::LIMIT || hi > self.data.len() { + return None; + } + self.slots[slot] = self.entries.len() as u8; + self.entries.push((key, lo)); + return i32::try_from(self.entries.len() - 1).ok(); + } + at => { + let (k, a) = self.entries[at as usize]; + if k == key && (len <= 16 || self.data.get(a..a + len) == self.data.get(lo..hi)) + { + return Some(i32::from(at)); + } + slot = (slot + 1) % Self::SLOTS; + } + } + } + } + + #[inline] + fn slot((low, high, len): (u64, u64, usize)) -> usize { + let hash = (low ^ high.rotate_left(29) ^ (len as u64).rotate_right(8)) + .wrapping_mul(0x9E37_79B9_7F4A_7C15); + (hash >> 57) as usize + } + + fn scan(&mut self, offsets: &[i32]) -> Option> { + let mut codes = Vec::with_capacity(offsets.len().saturating_sub(1)); + for (at, w) in offsets.windows(2).enumerate() { + if at == Self::SAMPLE && self.entries.len() > Self::SAMPLED { + return None; + } + codes.push(self.code(usize::try_from(w[0]).ok()?, usize::try_from(w[1]).ok()?)?); + } + Some(codes) + } + + pub(crate) fn keys(data: &'d [u8], offsets: &[i32]) -> Option<(Rc<[i32]>, usize)> { + let mut coder = Self::new(data); + let codes = coder.scan(offsets)?; + Some((codes.into(), coder.entries.len())) + } + + fn codes(mut self, offsets: &[i32]) -> Option<(Vec, Dict)> { + let codes = self.scan(offsets)?; + let mut dict_offsets = Vec::with_capacity(self.entries.len() + 1); + let mut text = String::new(); + dict_offsets.push(0); + for &((_, _, len), lo) in &self.entries { + text.push_str(std::str::from_utf8(self.data.get(lo..lo + len)?).ok()?); + dict_offsets.push(i32::try_from(text.len()).ok()?); + } + Some(( + codes, + Dict::Text { + offsets: dict_offsets, + data: text, + }, + )) + } +} + +impl Interner { + fn new() -> Self { + Self { + slots: [u8::MAX; Coder::SLOTS], + keys: Vec::new(), + offsets: vec![0], + data: String::new(), + } + } + + #[inline(always)] + fn key(bytes: &[u8]) -> (u64, u64, usize) { + let len = bytes.len(); + let at = |lo: usize| { + bytes + .get(lo..) + .and_then(<[u8]>::first_chunk::<8>) + .map_or(0, |word| u64::from_le_bytes(*word)) + }; + let half = |lo: usize| { + bytes + .get(lo..) + .and_then(<[u8]>::first_chunk::<4>) + .map_or(0, |word| u64::from(u32::from_le_bytes(*word))) + }; + let byte = |lo: usize| bytes.get(lo).map_or(0, |&byte| u64::from(byte)); + let words = match len { + 0 => (0, 0), + 1..=3 => (byte(0) | byte(len / 2) << 8 | byte(len - 1) << 16, 0), + 4..=8 => (half(0) | half(len - 4) << 32, 0), + 9..=16 => (at(0), at(len - 8)), + _ => (at(0), at(8)), + }; + (words.0, words.1, len) + } + + fn text(&self, code: i32) -> &str { + let at = usize::try_from(code).unwrap_or(usize::MAX); + let range = self + .offsets + .get(at) + .zip(self.offsets.get(at.wrapping_add(1))); + range + .and_then(|(&lo, &hi)| { + self.data + .get(usize::try_from(lo).ok()?..usize::try_from(hi).ok()?) + }) + .unwrap_or_default() + } + + #[inline(always)] + fn found(&self, text: &str) -> Option { + let key = Self::key(text.as_bytes()); + let mut slot = Coder::slot(key); + loop { + let at = self.slots[slot]; + let code = i32::from(at); + match self.keys.get(usize::from(at)) { + None => return None, + Some(known) if *known == key && (key.2 <= 16 || self.text(code) == text) => { + return Some(code) + } + Some(_) => slot = (slot + 1) % Coder::SLOTS, + } + } + } + + fn code(&mut self, text: &str) -> Option { + let bytes = text.as_bytes(); + let len = bytes.len(); + let key = Self::key(bytes); + let mut slot = Coder::slot(key); + loop { + match self.slots[slot] { + u8::MAX => { + if self.keys.len() >= Coder::LIMIT { + return None; + } + let code = i32::try_from(self.keys.len()).ok()?; + let end = i32::try_from(self.data.len() + len).ok()?; + self.slots[slot] = self.keys.len() as u8; + self.keys.push(key); + self.data.push_str(text); + self.offsets.push(end); + return Some(code); + } + at => { + let code = i32::from(at); + if self.keys[usize::from(at)] == key && (len <= 16 || self.text(code) == text) { + return Some(code); + } + slot = (slot + 1) % Coder::SLOTS; + } + } + } + } + + fn dict(self) -> Dict { + Dict::Text { + offsets: self.offsets, + data: self.data, + } + } +} + +enum Cells { + Empty, + Scaled { + mant: Vec, + scale: Vec, + }, + Text { + offsets: Vec, + data: String, + }, + Coded { + codes: Vec, + words: Interner, + bytes: usize, + }, + Bool(Vec), + Any(Vec), +} + +struct FieldBuilder { + name: Arc, + coded: bool, + cells: Cells, + gaps: Option>, + len: usize, +} + +impl FieldBuilder { + fn new(name: Arc, len: usize, coded: bool) -> Self { + let mut field = Self { + name, + coded, + cells: Cells::Empty, + gaps: None, + len: 0, + }; + (0..len).for_each(|_| field.missing()); + field + } + + #[inline] + fn bit(&mut self, on: bool) { + let len = self.len; + let gaps = match (&mut self.gaps, on) { + (None, true) => return, + (Some(gaps), _) => gaps, + (gaps @ None, false) => gaps.insert(Bits::ones(len)), + }; + if len & 63 == 0 { + gaps.push(0); + } + if on { + Bits::set(gaps, len, true); + } + } + + fn present(&self, at: usize) -> bool { + self.gaps.as_ref().is_none_or(|gaps| Bits::get(gaps, at)) + } + + fn missing(&mut self) { + self.bit(false); + match &mut self.cells { + Cells::Empty | Cells::Bool(_) => {} + Cells::Scaled { mant, scale } => { + mant.push(0); + scale.push(0); + } + Cells::Text { offsets, data } => offsets.push(data.len() as i32), + Cells::Coded { .. } => { + self.text(""); + } + Cells::Any(values) => values.push(Variable::Null), + } + self.len += 1; + } + + #[inline] + fn text(&mut self, text: &str) -> bool { + match &mut self.cells { + Cells::Coded { + codes, + words, + bytes, + } => { + let end = bytes + .checked_add(text.len()) + .filter(|&end| i32::try_from(end).is_ok()); + if let Some((end, code)) = end + .zip(words.found(text)) + .filter(|_| codes.len() != Coder::SAMPLE) + { + codes.push(code); + *bytes = end; + return true; + } + self.spell(text) + } + Cells::Text { offsets, data } => Self::spelt(offsets, data, text), + _ => false, + } + } + + #[inline] + fn spelt(offsets: &mut Vec, data: &mut String, text: &str) -> bool { + match i32::try_from(data.len() + text.len()) { + Ok(end) => { + data.push_str(text); + offsets.push(end); + true + } + Err(_) => false, + } + } + + #[cold] + #[inline(never)] + fn spell(&mut self, text: &str) -> bool { + if let Cells::Coded { + codes, + words, + bytes, + } = &mut self.cells + { + let Some(end) = bytes + .checked_add(text.len()) + .filter(|&end| i32::try_from(end).is_ok()) + else { + return false; + }; + let sampled = codes.len() != Coder::SAMPLE || words.keys.len() <= Coder::SAMPLED; + if let Some(code) = sampled.then(|| words.code(text)).flatten() { + codes.push(code); + *bytes = end; + return true; + } + self.cells = self.spelled(); + } + match &mut self.cells { + Cells::Text { offsets, data } => Self::spelt(offsets, data, text), + _ => false, + } + } + + fn spelled(&self) -> Cells { + let Cells::Coded { + codes, + words, + bytes, + } = &self.cells + else { + return Cells::Empty; + }; + let mut offsets = Vec::with_capacity(codes.capacity() + 1); + let mut data = String::with_capacity(*bytes); + offsets.push(0); + for &code in codes { + data.push_str(words.text(code)); + offsets.push(data.len() as i32); + } + Cells::Text { offsets, data } + } + + fn variables(&self) -> Vec { + let mut values = Vec::with_capacity(self.len + 1); + for at in 0..self.len { + let value = match (&self.cells, self.present(at)) { + (_, false) | (Cells::Empty, _) => Variable::Null, + (Cells::Scaled { mant, scale }, true) => { + Variable::Number(rust_decimal::Decimal::new(mant[at], u32::from(scale[at]))) + } + (Cells::Text { offsets, data }, true) => { + Variable::String(data[offsets[at] as usize..offsets[at + 1] as usize].into()) + } + (Cells::Coded { codes, words, .. }, true) => { + Variable::String(words.text(codes[at]).into()) + } + (Cells::Bool(bits), true) => Variable::Bool(Bits::get(bits, at)), + (Cells::Any(values), true) => values[at].clone(), + }; + values.push(value); + } + values + } + + fn start(&mut self, value: &Variable, capacity: usize) { + let len = self.len; + self.cells = match value { + Variable::Number(n) if Scaled::parts(n).is_some() => { + let (mut mant, mut scale) = + (Vec::with_capacity(capacity), Vec::with_capacity(capacity)); + mant.resize(len, 0); + scale.resize(len, 0); + Cells::Scaled { mant, scale } + } + Variable::String(_) if self.coded => Cells::Coded { + codes: Vec::with_capacity(capacity), + words: Interner::new(), + bytes: 0, + }, + Variable::String(_) => { + let mut offsets = Vec::with_capacity(capacity + 1); + offsets.resize(len + 1, 0); + Cells::Text { + offsets, + data: String::new(), + } + } + Variable::Bool(_) => Cells::Bool(Vec::with_capacity(capacity.div_ceil(64))), + _ => { + let mut values = Vec::with_capacity(capacity); + values.resize(len, Variable::Null); + Cells::Any(values) + } + }; + if matches!(self.cells, Cells::Coded { .. }) { + (0..len).for_each(|_| { + self.text(""); + }); + } + } + + #[inline(always)] + fn push(&mut self, value: &Variable, capacity: usize) { + if matches!(self.cells, Cells::Empty) { + self.start(value, capacity); + } + let len = self.len; + let fits = match (&mut self.cells, value) { + (Cells::Scaled { mant, scale }, Variable::Number(n)) => match Scaled::parts(n) { + Some((m, s)) => { + mant.push(m); + scale.push(s); + true + } + None => false, + }, + (Cells::Text { .. } | Cells::Coded { .. }, Variable::String(text)) => self.text(text), + (Cells::Bool(bits), Variable::Bool(on)) => { + let words = (len + 1).div_ceil(64); + if bits.len() < words { + bits.resize(words, 0); + } + Bits::set(bits, len, *on); + true + } + (Cells::Any(values), value) => { + values.push(value.clone()); + true + } + _ => false, + }; + if !fits { + let mut values = self.variables(); + values.push(value.clone()); + self.cells = Cells::Any(values); + } + self.bit(true); + self.len += 1; + } + + fn run<'v>(&mut self, mut values: impl Iterator, capacity: usize) { + while let Some(value) = self.quick(&mut values) { + self.push(value, capacity); + } + } + + #[inline] + fn quick<'v>( + &mut self, + values: &mut impl Iterator, + ) -> Option<&'v Variable> { + if self.gaps.is_some() { + return values.next(); + } + let len = self.len; + let mut taken = 0; + let stray = match &mut self.cells { + Cells::Scaled { mant, scale } => values.find(|value| { + let part = match value { + Variable::Number(n) => Scaled::parts(n), + _ => None, + }; + part.inspect(|&(m, s)| { + mant.push(m); + scale.push(s); + taken += 1; + }) + .is_none() + }), + Cells::Bool(bits) => values.find(|value| { + let Variable::Bool(on) = value else { + return true; + }; + let at = len + taken; + let words = (at + 1).div_ceil(64); + if bits.len() < words { + bits.resize(words, 0); + } + Bits::set(bits, at, *on); + taken += 1; + false + }), + Cells::Coded { + codes, + words, + bytes, + } => values.find(|value| { + let Variable::String(text) = value else { + return true; + }; + let end = bytes + .checked_add(text.len()) + .filter(|&end| i32::try_from(end).is_ok()); + match end + .zip(words.found(text)) + .filter(|_| codes.len() != Coder::SAMPLE) + { + Some((end, code)) => { + codes.push(code); + *bytes = end; + taken += 1; + false + } + None => true, + } + }), + _ => values.next(), + }; + self.len += taken; + stray + } + + fn truncate(&mut self, len: usize) { + if len >= self.len { + return; + } + let mut values = self.variables(); + values.truncate(len); + self.cells = Cells::Any(values); + if let Some(gaps) = &mut self.gaps { + gaps.truncate(len.div_ceil(64)); + Bits::trim(gaps, len); + } + self.len = len; + } + + fn array(self) -> (Arc, Array) { + let len = self.len; + let valid = self.gaps.filter(|gaps| !Bits::full(gaps, 0, len)); + let store = match self.cells { + Cells::Empty => Store::Any(vec![Variable::Null; len]), + Cells::Scaled { mant, scale } => Store::Scaled { mant, scale }, + Cells::Text { offsets, data } => Store::Text { offsets, data }, + Cells::Coded { codes, words, .. } => Store::Coded { + codes: codes.into(), + dict: Rc::new(words.dict()), + }, + Cells::Bool(mut bits) => { + bits.resize(len.div_ceil(64), 0); + Store::Bool(bits) + } + Cells::Any(values) => Store::Any(values), + }; + (self.name, Array::parts(store, valid, len)) + } +} + +struct ListBuilder { + nulls: bool, + primitive: bool, + rows: usize, + offsets: Vec, + validity: Vec, + children: usize, + capacity: usize, + fields: Vec, + shapes: Vec<(Rc, Vec)>, + hosted: Vec, +} + +impl ListBuilder { + const CHUNK: usize = 64; + + fn new(rows: usize, capacity: usize) -> Self { + let mut offsets = Vec::with_capacity(rows + 1); + offsets.push(0); + Self { + nulls: false, + primitive: false, + rows, + offsets, + validity: Bits::ones(rows), + children: 0, + capacity, + fields: Vec::new(), + shapes: Vec::new(), + hosted: Vec::new(), + } + } + + fn field(&mut self, hint: usize, key: &str) -> Option { + if self + .fields + .get(hint) + .is_some_and(|field| field.name.as_ref() == key) + { + return Some(hint); + } + if let Some(at) = self + .fields + .iter() + .position(|field| field.name.as_ref() == key) + { + return Some(at); + } + if key.is_empty() || key.contains('.') { + return None; + } + self.fields + .push(FieldBuilder::new(Arc::from(key), self.children, true)); + Some(self.fields.len() - 1) + } + + fn layout(&mut self, shape: &Rc) -> Option { + if let Some(at) = self + .shapes + .iter() + .position(|(known, _)| Rc::ptr_eq(known, shape)) + { + return Some(at); + } + let slots = shape + .keys() + .iter() + .enumerate() + .map(|(hint, key)| self.field(hint, key)) + .collect::>>()?; + self.shapes.push((shape.clone(), slots)); + Some(self.shapes.len() - 1) + } + + #[inline(always)] + fn item(&mut self, item: &Variable) -> Option<()> { + if self.primitive { + let field = self.fields.first_mut()?; + match item { + Variable::Object(_) | Variable::Array(_) => return None, + Variable::Null => field.missing(), + value => field.push(value, self.capacity), + } + self.children += 1; + return Some(()); + } + let Variable::Object(map) = item else { + return None; + }; + let child = self.children; + let map = map.borrow(); + let touched = match map.slots() { + Some((_, values)) => { + let layout = self.layout(map.shape()?)?; + let (fields, capacity, nulls) = (&mut self.fields, self.capacity, self.nulls); + for (&at, value) in self.shapes[layout].1.iter().zip(values) { + match (nulls, value) { + (true, Variable::Null) => fields[at].missing(), + _ => fields[at].push(value, capacity), + } + } + values.len() + } + None => { + for (hint, (key, value)) in map.iter().enumerate() { + let at = self.field(hint, key)?; + match (self.nulls, value) { + (true, Variable::Null) => self.fields[at].missing(), + _ => self.fields[at].push(value, self.capacity), + } + } + map.len() + } + }; + if touched != self.fields.len() { + self.fields + .iter_mut() + .filter(|field| field.len == child) + .for_each(FieldBuilder::missing); + } + self.children += 1; + Some(()) + } + + fn host(&mut self, row: usize) { + self.hosted.push(row); + Bits::set(&mut self.validity, row, false); + } + + fn row(&mut self, row: usize, items: &[Variable]) { + let start = self.children; + if items.iter().try_for_each(|item| self.item(item)).is_none() { + self.fields + .iter_mut() + .for_each(|field| field.truncate(start)); + self.children = start; + self.host(row); + } + } + + fn close(&mut self) -> Option<()> { + self.offsets.push(i32::try_from(self.children).ok()?); + Some(()) + } + + fn each(mut self, column: &Column) -> Option { + for row in 0..self.rows { + if !column.valid(row) { + Bits::set(&mut self.validity, row, false); + self.close()?; + continue; + } + match column.values { + Values::Any(values) => match values.get(row) { + Some(Variable::Array(items)) => self.row(row, &items.borrow()), + _ => self.host(row), + }, + Values::List { + child: Dictionary::Any(items), + .. + } => match column.range(row).and_then(|(a, b)| items.get(a..b)) { + Some(slice) => self.row(row, slice), + None => self.host(row), + }, + _ => return None, + } + self.close()?; + } + Some(self.finish()) + } + + fn uniform(mut self, column: &Column, values: &[Variable]) -> Option> { + let mut lists = Vec::with_capacity(self.rows); + for row in 0..self.rows { + match values.get(row) { + _ if !column.valid(row) => Bits::set(&mut self.validity, row, false), + Some(Variable::Array(items)) => { + let list = items.borrow(); + self.children += list.len(); + lists.push(list); + } + _ => self.host(row), + } + if self.close().is_none() { + return Some(None); + } + } + self.capacity = self.children; + self.children = 0; + let mut items = Vec::with_capacity(self.capacity.min(Self::CHUNK)); + let mut last = (0, 0, 0); + let mut all = lists.iter().flat_map(|list| list.iter()).peekable(); + while all.peek().is_some() { + for item in all.by_ref().take(Self::CHUNK) { + let Variable::Object(map) = item else { + return None; + }; + let map = map.borrow(); + let (shape, values) = map.slots()?; + if shape.id() != last.0 || self.children == 0 { + let known = self.shapes.len(); + let layout = self.layout(map.shape()?)?; + let slots = &self.shapes[layout].1; + if layout >= known + && slots + .iter() + .enumerate() + .any(|(at, slot)| slots[..at].contains(slot)) + { + return None; + } + last = (shape.id(), layout, slots.len()); + } + if last.2 != values.len() { + return None; + } + items.push(( + last.1, + Ref::map(map, |map| map.slots().map_or(&[][..], |(_, values)| values)), + )); + self.children += 1; + } + self.spread(&items); + items.clear(); + } + Some(Some(self.finish())) + } + + fn spread(&mut self, items: &[(usize, Ref<'_, [Variable]>)]) { + let (capacity, start) = (self.capacity, self.children - items.len()); + let shapes = &self.shapes; + for (index, field) in self.fields.iter_mut().enumerate() { + let slot = |layout: usize| { + shapes + .get(layout) + .and_then(|(_, slots)| slots.iter().position(|&at| at == index)) + }; + let fixed = (0..shapes.len()) + .map(slot) + .reduce(|a, b| a.filter(|&a| Some(a) == b)) + .flatten(); + let items = items + .get(field.len.saturating_sub(start)..) + .unwrap_or_default(); + match fixed { + Some(at) => field.run( + items.iter().filter_map(|(_, values)| values.get(at)), + capacity, + ), + None => items.iter().for_each(|(layout, values)| { + match slot(*layout).and_then(|at| values.get(at)) { + Some(value) => field.push(value, capacity), + None => field.missing(), + } + }), + } + } + } + + fn finish(self) -> Shred { + let validity = match Bits::ones(self.rows) == self.validity { + true => None, + false => Some(Rc::from(self.validity)), + }; + Shred { + frame: Frame { + offsets: self.offsets.into(), + validity, + children: self.children, + }, + fields: self.fields.into_iter().map(FieldBuilder::array).collect(), + hosted: self.hosted.into(), + } + } +} + +impl Shred { + pub fn of(column: &Column, rows: usize) -> Option { + let capacity = match column.values { + Values::Any(values) => { + if let Some(shred) = ListBuilder::new(rows, 0).uniform(column, values) { + return shred; + } + values + .iter() + .take(rows) + .map(|value| match value { + Variable::Array(items) => items.borrow().len(), + _ => 0, + }) + .sum() + } + Values::List { child, .. } => child.len(), + _ => return None, + }; + ListBuilder::new(rows, capacity).each(column) + } +} + +impl<'a> Listing<'a> { + pub fn of(column: Column<'a>, owners: usize) -> Option> { + let validity = Bits::validity(column.validity, owners).map(Rc::from); + match column.values { + Values::List { offsets, child } => { + let offsets: Rc<[i32]> = offsets.get(..=owners)?.into(); + match child { + Dictionary::Any(_) => Self::shredded(&column, owners), + Dictionary::Column(item) => match item.values { + Values::Struct { fields, len } => { + if Bits::partial(item.validity, len).is_some() { + return None; + } + let fields = fields + .iter() + .map(|(name, field)| { + (Arc::from(*name), Normalizer::lean(*field, len)) + }) + .collect(); + Some(Listing { + frame: Frame { + offsets, + validity, + children: len, + }, + hosted: None, + fields, + }) + } + Values::Any(_) | Values::List { .. } | Values::Dict { .. } => None, + _ => { + let len = item.len(); + Some(Listing { + frame: Frame { + offsets, + validity, + children: len, + }, + hosted: None, + fields: vec![(Arc::from(""), Normalizer::lean(*item, len))], + }) + } + }, + scalar => { + let len = scalar.len(); + Some(Listing { + frame: Frame { + offsets, + validity, + children: len, + }, + hosted: None, + fields: vec![(Arc::from(""), Normalizer::lean(scalar.column(), len))], + }) + } + } + } + Values::Any(_) => Self::shredded(&column, owners), + _ => None, + } + } + + pub fn leaf(leaf: &Leaf<'a>, owners: usize) -> Option> { + match leaf { + Leaf::Input(input) => Listing::of(input.column, owners), + other => match other + .records() + .and_then(|records| Self::recorded(&records, owners)) + { + Some(listing) => Some(listing), + None => Self::copied(&other.column(), owners), + }, + } + } + + fn recorded(records: &Records<'a>, owners: usize) -> Option> { + if !records.plain() { + return None; + } + let count = records.count(); + let mut fields = Vec::with_capacity(records.fields().len()); + for (key, leaf, present) in records.fields() { + Normalizer::class(&leaf.column().values)?; + let leaf = match Bits::full(present, 0, count) { + true => leaf.clone(), + false => Leaf::masked(leaf.clone(), present), + }; + fields.push((Arc::from(key.as_str()), leaf)); + } + let validity = records.validity(); + Some(Listing { + frame: Frame { + offsets: records.offsets().get(..=owners)?.into(), + validity: (!Bits::full(validity, 0, owners)) + .then(|| Rc::from(Bits::window(validity, 0, owners))), + children: count, + }, + hosted: None, + fields, + }) + } + + fn copied(column: &Column<'_>, owners: usize) -> Option> { + let validity = Bits::validity(column.validity, owners).map(Rc::from); + let Values::List { offsets, child } = column.values else { + return match column.values { + Values::Any(_) => Self::shredded(column, owners), + _ => None, + }; + }; + let store = match child { + Dictionary::Any(_) => return Self::shredded(column, owners), + Dictionary::Scaled { mant, scale } => Store::Scaled { + mant: mant.to_vec(), + scale: scale.to_vec(), + }, + Dictionary::Text { offsets, data } => Store::Text { + offsets: offsets.to_vec(), + data: data.to_string(), + }, + Dictionary::Bool { bits } => Store::Bool(bits.to_vec()), + Dictionary::Column(_) => return None, + }; + let len = child.len(); + Some(Listing { + frame: Frame { + offsets: offsets.get(..=owners)?.into(), + validity, + children: len, + }, + hosted: None, + fields: vec![(Arc::from(""), Leaf::typed(Array::parts(store, None, len)))], + }) + } + + pub fn nested(&self, name: &str) -> Option> { + let (_, leaf) = self + .fields + .iter() + .rev() + .find(|(key, _)| key.as_ref() == name)?; + Listing::leaf(leaf, self.frame.children) + } + + pub fn columns<'s>(&'s self, names: &[ColumnDef]) -> Option>> { + names + .iter() + .map(|def| { + self.fields + .iter() + .rev() + .find(|(name, _)| name.as_ref() == def.path) + .map(|(_, leaf)| leaf.column()) + }) + .collect() + } + + pub fn classes(&self) -> Vec<(Arc, Class)> { + self.fields + .iter() + .filter_map(|(name, leaf)| { + Some((name.clone(), Normalizer::class(&leaf.column().values)?)) + }) + .collect() + } + + fn items<'v>( + column: &Column<'v>, + row: usize, + ) -> Option>> { + if !column.valid(row) { + return Some(None); + } + match column.values { + Values::Any(values) => match values.get(row)? { + Variable::Null => Some(None), + Variable::Array(items) => { + Some(Some(std::borrow::Cow::Owned(items.borrow().clone()))) + } + _ => None, + }, + Values::List { + child: Dictionary::Any(items), + .. + } => column + .range(row) + .and_then(|(a, b)| items.get(a..b)) + .map(|slice| Some(std::borrow::Cow::Borrowed(slice))), + _ => None, + } + } + + fn sort(value: &Variable) -> Option { + match value { + Variable::Null => None, + Variable::Number(n) if Scaled::parts(n).is_some() => Some(0), + Variable::String(_) => Some(1), + Variable::Bool(_) => Some(2), + _ => Some(3), + } + } + + fn odd(items: &[Variable], objects: bool, sorts: &[(Arc, usize)]) -> bool { + let wanted = |key: &str| { + sorts + .iter() + .find(|(k, _)| k.as_ref() == key) + .map(|(_, sort)| *sort) + }; + items.iter().any(|item| match (objects, item) { + (false, item) => Self::sort(item).is_some_and(|sort| Some(sort) != wanted("")), + (true, Variable::Object(map)) => map.borrow().iter().any(|(key, value)| { + Self::sort(value).is_some_and(|sort| Some(sort) != wanted(key)) + }), + (true, _) => false, + }) + } + + fn shredded(column: &Column<'_>, owners: usize) -> Option> { + let mut capacity = 0; + let mut arrays = 0; + let mut objects = false; + let mut counts: Vec<(Arc, [usize; 4])> = Vec::new(); + let mut count = |key: &str, value: &Variable| { + let Some(sort) = Self::sort(value) else { + return; + }; + match counts.iter_mut().find(|(k, _)| k.as_ref() == key) { + Some((_, c)) => c[sort] += 1, + None => { + let mut c = [0usize; 4]; + c[sort] = 1; + counts.push((Arc::from(key), c)); + } + } + }; + for row in 0..owners { + if let Some(Some(items)) = Self::items(column, row) { + arrays += 1; + capacity += items.len(); + objects |= items.iter().any(|item| matches!(item, Variable::Object(_))); + } + } + if arrays == 0 { + return None; + } + for row in 0..owners { + if let Some(Some(items)) = Self::items(column, row) { + for item in items.iter() { + match (objects, item) { + (true, Variable::Object(map)) => map + .borrow() + .iter() + .for_each(|(key, value)| count(key, value)), + (true, _) => {} + (false, item) => count("", item), + } + } + } + } + let sorts: Vec<(Arc, usize)> = counts + .into_iter() + .map(|(key, c)| { + ( + key, + (0..4) + .max_by_key(|&sort| (c[sort], std::cmp::Reverse(sort))) + .unwrap_or(3), + ) + }) + .collect(); + let mut builder = ListBuilder::new(owners, capacity); + builder.nulls = true; + builder.primitive = !objects; + if builder.primitive { + builder + .fields + .push(FieldBuilder::new(Arc::from(""), 0, true)); + } + for row in 0..owners { + match Self::items(column, row) { + Some(Some(items)) if Self::odd(&items, objects, &sorts) => builder.host(row), + Some(Some(items)) => builder.row(row, &items), + Some(None) => Bits::set(&mut builder.validity, row, false), + None => builder.host(row), + } + builder.close()?; + } + let hosted = (!builder.hosted.is_empty()).then(|| { + let mut bits = vec![0u64; owners.div_ceil(64)]; + builder + .hosted + .iter() + .for_each(|&row| Bits::set(&mut bits, row, true)); + Rc::from(bits) + }); + let shred = builder.finish(); + Some(Listing { + frame: shred.frame, + hosted, + fields: shred + .fields + .into_iter() + .map(|(name, array)| (name, Leaf::typed(array))) + .collect(), + }) + } +} + +impl Normalizer { + pub(crate) fn class(values: &Values) -> Option { + match values { + Values::Scaled { .. } | Values::I64(_) | Values::Dec(_) => Some(Class::Num), + Values::Bool { .. } => Some(Class::Bool), + Values::Text { .. } | Values::Utf8 { .. } => Some(Class::Text), + Values::Dict { values, .. } => match values { + Dictionary::Scaled { .. } => Some(Class::Num), + Dictionary::Bool { .. } => Some(Class::Bool), + Dictionary::Text { .. } => Some(Class::Text), + Dictionary::Column(column) => match column.values { + Values::Scaled { .. } => Some(Class::Num), + Values::Bool { .. } => Some(Class::Bool), + Values::Text { .. } | Values::Utf8 { .. } => Some(Class::Text), + _ => None, + }, + Dictionary::Any(_) => None, + }, + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + + struct Random(u64); + + impl Random { + fn next(&mut self, n: u64) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 % n.max(1) + } + + fn text(&mut self, wide: u64) -> Value { + let pool = [ + "", + "a", + "ab", + "abc", + "loan", + "saving", + "savings", + "checking", + "currency", + "a much longer text value", + "a much longer text valuf", + "ü€x", + ]; + match wide { + 0 => json!(pool[self.next(pool.len() as u64) as usize]), + spread => json!(format!("w{}", self.next(spread))), + } + } + + fn value(&mut self, kind: u64, wide: u64) -> Value { + match kind { + 0 => json!(self.next(5000)), + 1 => json!(self.next(5000) as f64 / 8.0), + 2 => self.text(wide), + 3 => json!(self.next(2) == 0), + 4 => Value::Null, + 5 => json!([self.next(3)]), + 6 => json!({"x": 1}), + _ => serde_json::from_str("123456789012345678901234567890").unwrap_or(Value::Null), + } + } + + fn rows(&mut self, mixed: u64) -> Vec { + let keys = ["balance", "kind", "active", "rate", "note"]; + let kinds: Vec = (0..keys.len()).map(|_| self.next(4)).collect(); + let wide = [0, 0, 0, 8, 16, 17, 18, 40, 64, 65, 90][self.next(11) as usize]; + let many = self.next(4) == 0; + (0..self.next(70) + 1) + .map(|_| { + if self.next(12) == 0 { + let kind = self.next(3); + return Variable::from(self.value(kind, wide)); + } + let items: Vec = (0..self.next(if many { 40 } else { 6 })) + .map(|_| { + if mixed > 0 && self.next(200 / mixed) == 0 { + let kind = self.next(8); + return self.value(kind, wide); + } + let mut map = serde_json::Map::new(); + for (at, key) in keys.iter().enumerate() { + if mixed > 0 && self.next(12) == 0 { + continue; + } + let kind = match mixed > 0 && self.next(40) == 0 { + true => self.next(8), + false => kinds[at], + }; + map.insert(key.to_string(), self.value(kind, wide)); + } + let odd = if mixed == 2 { self.next(300) } else { 9 }; + match odd { + 0 => { + map.insert("a.b".to_string(), json!(1)); + } + 1 => { + (0..40).for_each(|at| { + map.insert(format!("k{at}"), json!(at)); + }); + } + _ => {} + } + Value::Object(map) + }) + .collect(); + Variable::from(Value::Array(items)) + }) + .collect() + } + } + + fn render(shred: Option) -> String { + let Some(shred) = shred else { + return "none".to_string(); + }; + let fields: Vec = shred + .fields + .iter() + .map(|(name, array)| format!("{name}={array:?}")) + .collect(); + format!( + "{:?} {:?} {} {:?} {fields:?}", + shred.frame.offsets, shred.frame.validity, shred.frame.children, shred.hosted + ) + } + + fn recoded(shred: &Option) -> usize { + let fields = shred.iter().flat_map(|shred| shred.fields.iter()); + fields + .map(|(_, array)| match array.store() { + Store::Coded { codes, dict } => { + let Dict::Text { offsets, data } = dict.as_ref() else { + panic!("coded text dictionary"); + }; + let mut spelled = vec![0i32]; + let mut text = String::new(); + for &code in codes.iter() { + let at = usize::try_from(code).unwrap_or(usize::MAX); + text.push_str(&data[offsets[at] as usize..offsets[at + 1] as usize]); + spelled.push(text.len() as i32); + } + let (again, dict_again) = Coder::new(text.as_bytes()) + .codes(&spelled) + .expect("old coder codes"); + assert_eq!(again.as_slice(), codes.as_ref()); + assert_eq!(format!("{dict_again:?}"), format!("{dict:?}")); + 1 + } + Store::Text { offsets, data } => { + assert!(Coder::new(data.as_bytes()).codes(offsets).is_none()); + 0 + } + _ => 0, + }) + .sum() + } + + #[test] + fn uniform_lists_shred_like_row_by_row() { + let mut random = Random(0x9E37_79B9_7F4A_7C15); + let (mut uniform, mut coded) = (0, 0); + for round in 0..3000u64 { + let rows = random.rows(round % 3); + let count = rows.len(); + let valid = Bits::of(count, |_| random.next(9) != 0); + let column = match round % 2 { + 0 => Column::new(Values::Any(&rows)), + _ => Column::with_validity(Values::Any(&rows), &valid, 0), + }; + let capacity = rows + .iter() + .map(|value| match value { + Variable::Array(items) => items.borrow().len(), + _ => 0, + }) + .sum(); + let generic = ListBuilder::new(count, capacity).each(&column); + coded += recoded(&generic); + let expected = render(generic); + if let Some(shred) = ListBuilder::new(count, capacity).uniform(&column, &rows) { + uniform += 1; + assert_eq!(render(shred), expected, "round {round}"); + } + assert_eq!(render(Shred::of(&column, count)), expected, "round {round}"); + } + assert!(uniform > 1000 && coded > 1000, "{uniform} {coded}"); + } +} diff --git a/core/engine/src/compiled/switches.rs b/core/engine/src/compiled/switches.rs new file mode 100644 index 00000000..d1811985 --- /dev/null +++ b/core/engine/src/compiled/switches.rs @@ -0,0 +1,39 @@ +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +pub(crate) struct Switches { + typed: AtomicBool, + census: AtomicBool, + compilations: AtomicUsize, +} + +impl Switches { + pub fn typed(&self) -> bool { + self.typed.load(Ordering::Relaxed) + } + + pub fn census(&self) -> bool { + self.census.load(Ordering::Relaxed) + } + + pub fn compiled(&self) { + self.compilations.fetch_add(1, Ordering::Relaxed); + } + + pub fn compilations(&self) -> usize { + self.compilations.load(Ordering::Relaxed) + } + + pub fn set_typed(&self, on: bool) { + self.typed.store(on, Ordering::Relaxed); + } + + pub fn set_census(&self, on: bool) { + self.census.store(on, Ordering::Relaxed); + } +} + +pub(crate) static SWITCHES: Switches = Switches { + typed: AtomicBool::new(true), + census: AtomicBool::new(false), + compilations: AtomicUsize::new(0), +}; diff --git a/core/engine/src/compiled/table/cells.rs b/core/engine/src/compiled/table/cells.rs new file mode 100644 index 00000000..e34d5bc9 --- /dev/null +++ b/core/engine/src/compiled/table/cells.rs @@ -0,0 +1,651 @@ +use super::{First, Found, Keyed, Kind, OutSource, Part, RuleOutputs, Table}; +use crate::compiled::bound::{Bound, Outs}; +use crate::compiled::leaf::Mask; +use crate::compiled::leaf::{Array, Bits, ColumnBuilder, Dict, Leaf, Literal, Store, Templated}; +use std::borrow::Cow; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::{Binding, CellSet, LaneProgram, LaneRunner, Values}; +use zen_expression::Variable; + +pub(super) type OutputCell = (Option, Option); +type BuiltCache = ahash::HashMap<(u64, usize, u8), Option>>; + +#[derive(Default)] +pub(super) struct OutputCells<'c> { + cells: ahash::HashMap<&'c str, OutputCell>, + many: ahash::HashMap, Option>, +} + +impl<'c> OutputCells<'c> { + pub(super) fn cell(&mut self, cell: &'c str) -> &OutputCell { + self.cells + .entry(cell) + .or_insert_with(|| Self::summary(cell)) + } + + fn summary(cell: &str) -> OutputCell { + let Ok(program) = LaneProgram::standard(cell) else { + return (None, None); + }; + let literal = program.literal(); + let constant = literal + .clone() + .or_else(|| { + let p = program.program(); + match p.site_keys.is_empty() && p.timeless() && !p.opaque() { + true => LaneRunner::new() + .evaluate_one(&program, &zen_expression::Scope::default()) + .ok(), + false => None, + } + }) + .as_ref() + .and_then(Literal::of); + let source = match literal.as_ref().and_then(Literal::of) { + Some(literal) => Some(OutSource::Literal(literal)), + None => program + .path() + .filter(|path| !path.starts_with('$')) + .map(|path| OutSource::Path(Arc::from(path))), + }; + (constant, source) + } + + pub(super) fn many(&mut self, entries: &[(String, &'c str)]) -> Option { + self.many + .entry(entries.to_vec()) + .or_insert_with(|| { + let refs: Vec<(&str, &str)> = + entries.iter().map(|(k, v)| (k.as_str(), *v)).collect(); + LaneProgram::compile_many(&refs, false).ok() + }) + .clone() + } +} + +pub(super) struct Built { + shape: Rc, + parts: Vec, +} + +impl Built { + fn of(paths: &[(Vec<&str>, usize)]) -> Option { + let mut keys: Vec<&str> = Vec::new(); + for (segments, _) in paths { + let head = *segments.first()?; + if !keys.contains(&head) { + keys.push(head); + } + } + let mut map = zen_types::variable::VariableMap::with_capacity(keys.len()); + let mut parts = Vec::with_capacity(keys.len()); + for key in &keys { + let group: Vec<&(Vec<&str>, usize)> = paths + .iter() + .filter(|(segments, _)| segments.first() == Some(key)) + .collect(); + let part = match group.as_slice() { + [(segments, index)] if segments.len() == 1 => Part::Value(*index), + _ if group.iter().all(|(segments, _)| segments.len() > 1) => { + let rest: Vec<(Vec<&str>, usize)> = group + .iter() + .map(|(segments, index)| (segments[1..].to_vec(), *index)) + .collect(); + Part::Child(Built::of(&rest)?) + } + _ => return None, + }; + map.insert(zen_types::symbol::Symbol::from(*key), Variable::Null); + parts.push(part); + } + let shape = map.shape().filter(|_| map.len() == keys.len())?.clone(); + Some(Built { shape, parts }) + } + + fn make(&self, values: &[Variable]) -> Variable { + let values = self.parts.iter().map(|part| match part { + Part::Value(index) => values + .get(*index) + .map_or(Variable::Null, Variable::deep_clone), + Part::Child(child) => child.make(values), + }); + Variable::from_object(zen_types::variable::VariableMap::from_shape( + self.shape.clone(), + values, + )) + } +} + +impl Table { + pub(super) fn referenced_truths( + runner: &mut LaneRunner, + bound: &Bound, + cells: &CellSet, + other: usize, + reference: &str, + rows: &[usize], + mut sink: impl FnMut(usize, bool), + ) { + let Some((program, _)) = cells.other(other).filter(|_| !rows.is_empty()) else { + return; + }; + let bind = |key: &str| Self::rebound(bound, reference, key).unwrap_or(Binding::Row); + let mut outs = Outs::take(); + bound.export_with(runner, program, Some(rows), &bind, &mut outs, |_, _, _| {}); + let truths = outs + .first_mut() + .map(|out| Leaf::typed(Array::from_output(out)).truths(rows.len())); + for (i, &row) in rows.iter().enumerate() { + sink(row, truths.as_ref().is_some_and(|t| Bits::get(t, i))); + } + } + + fn rebound(bound: &Bound, reference: &str, key: &str) -> Option { + let rest = match key.strip_prefix('$') { + Some(rest) if rest.is_empty() || rest.starts_with('.') => rest, + Some(_) if !key.starts_with("$nodes") => return None, + _ => return Some((bound.bind)(key)), + }; + match (bound.bind)(&format!("{reference}{rest}")) { + Binding::Row => None, + binding => Some(binding), + } + } + + pub(super) fn referenced(bound: &Bound, cells: &CellSet, reference: &str) -> bool { + (0..cells.others()).all(|other| { + cells.other(other).is_some_and(|(program, _)| { + let p = program.program(); + !p.opaque() + && p.site_keys.iter().all(|key| { + key.as_deref() + .is_some_and(|key| Self::rebound(bound, reference, key).is_some()) + }) + }) + }) + } + + pub(super) fn truths( + runner: &mut LaneRunner, + bound: &Bound, + program: &LaneProgram, + within: Option<&[usize]>, + mut sink: impl FnMut(usize, bool), + ) { + let mut outs = Outs::take(); + bound.export(runner, program, within, &mut outs, |_, _, _| {}); + let count = within.map_or(bound.rows(), <[usize]>::len); + let Some(truths) = outs + .first_mut() + .map(|out| Leaf::typed(Array::from_output(out)).truths(count)) + else { + return; + }; + match within { + Some(rows) => rows + .iter() + .enumerate() + .for_each(|(i, &row)| sink(row, Bits::get(&truths, i))), + None => (0..count).for_each(|row| sink(row, Bits::get(&truths, row))), + } + } + + pub(super) fn run_rule( + runner: &mut LaneRunner, + program: Option<&LaneProgram>, + bound: &Bound, + lanes: &[usize], + sink: &mut dyn FnMut(usize, Option>), + ) { + let Some(program) = program else { + lanes.iter().for_each(|&lane| sink(lane, None)); + return; + }; + bound.many(runner, program, Some(lanes), |row, r| sink(row, r.ok())); + } + + thread_local! { + static BUILT: std::cell::RefCell = std::cell::RefCell::new(ahash::HashMap::default()); + } + + pub(super) fn builder(&self, rule: usize, collect: Option) -> Option> { + let outputs = &self.outputs[rule]; + let variant = match collect { + None => 0u8, + Some(false) => 1, + Some(true) => 2, + }; + Self::BUILT.with_borrow_mut(|cache| { + if cache.len() >= Self::THAWS { + cache.clear(); + } + cache + .entry((self.id, rule, variant)) + .or_insert_with(|| { + let paths: Vec<(Vec<&str>, usize)> = outputs + .paths + .iter() + .enumerate() + .filter(|(_, (_, is_collect, _))| collect.is_none_or(|c| c == *is_collect)) + .map(|(index, (path, _, _))| (path.split('.').collect(), index)) + .collect(); + Built::of(&paths).map(Rc::new) + }) + .clone() + }) + } + + pub(super) fn built( + &self, + builder: Option<&Rc>, + rule: usize, + collect: Option, + values: &[Variable], + ) -> Variable { + let outputs = &self.outputs[rule]; + match builder { + Some(built) if values.len() >= outputs.paths.len() => built.make(values), + _ => Self::assemble(&outputs.paths, values, collect), + } + } + + fn assemble( + paths: &[(Arc, bool, usize)], + values: &[Variable], + collect: Option, + ) -> Variable { + let object = Variable::empty_object(); + for ((path, is_collect, _), value) in paths.iter().zip(values) { + if collect.is_none_or(|c| c == *is_collect) { + object.dot_insert(path, value.deep_clone()); + } + } + object + } + + pub(super) fn spread_rules( + target: &mut [u64], + words: usize, + truth: &[u64], + rules: &[u64], + rows: usize, + ) { + for (w, &word) in truth.iter().enumerate() { + let mut set = word; + while set != 0 { + let row = w * 64 + set.trailing_zeros() as usize; + set &= set - 1; + if row >= rows { + return; + } + match words { + 1 => target[row] |= rules[0], + _ => Bits::or(&mut target[row * words..(row + 1) * words], rules), + } + } + } + } + + pub(super) fn direct( + outputs: &RuleOutputs, + bound: &Bound, + lanes: &[usize], + ) -> Option> { + outputs + .sources + .as_ref()? + .iter() + .map(|source| match source { + OutSource::Literal(literal) => { + let mut builder = ColumnBuilder::with_capacity(lanes.len()); + lanes.iter().for_each(|_| builder.push_literal(literal)); + Some(builder.finish()) + } + OutSource::Path(path) => match (bound.bind)(path) { + Binding::Column(index) => { + let (_, column) = bound.columns.columns.get(index)?; + match column.values { + Values::Any(_) | Values::List { .. } | Values::Dict { .. } => None, + _ => Some(Array::gather(column, lanes)), + } + } + Binding::Absent => { + let mut builder = ColumnBuilder::with_capacity(lanes.len()); + lanes.iter().for_each(|_| builder.push_null()); + Some(builder.finish()) + } + Binding::Row => None, + }, + }) + .collect() + } + + fn literal_at( + &self, + rule: usize, + slot: usize, + slots: usize, + positions: &[Option], + ) -> Option> { + let index = positions[rule * slots + slot]? as usize; + Some( + self.outputs[rule] + .literals + .as_ref() + .and_then(|literals| literals.get(index)), + ) + } + + pub(super) fn slot( + &self, + first: &First, + slot: usize, + slots: usize, + positions: &[Option], + used: &[u64], + ) -> Option<(Dict, Vec, Vec)> { + let rules = self.outputs.len(); + let entries = first.entries(); + let arrays: Vec> = first + .batches + .iter() + .map(|batch| { + let index = positions[batch.rule * slots + slot]? as usize; + batch.outputs.get(index) + }) + .collect(); + let mut kind = None; + for rule in (0..rules).filter(|&rule| Bits::get(used, rule)) { + if let Some(Some(literal)) = self.literal_at(rule, slot, slots, positions) { + if literal.deep() { + return None; + } + kind = Kind::join(kind, Kind::of_literal(literal)); + } + } + for array in arrays.iter().flatten() { + kind = Kind::join(kind, Kind::of_array(array)); + } + let mut valid = vec![0u64; entries.div_ceil(64)]; + let mut written = vec![0u64; entries.div_ceil(64)]; + for rule in 0..rules { + let literal = self.literal_at(rule, slot, slots, positions); + Bits::set(&mut written, rule, literal.is_some_and(|l| l.is_some())); + Bits::set( + &mut valid, + rule, + literal.flatten().is_some_and(|l| { + Kind::of_literal(l).is_some_and(|k| kind == Some(Kind::Any) || Some(k) == kind) + }), + ); + } + for (batch, array) in arrays.iter().enumerate() { + let start = rules + first.starts[batch]; + let len = first.starts[batch + 1] - first.starts[batch]; + let Some(array) = array else { + continue; + }; + let same = kind == Some(Kind::Any) || Kind::of_array(array) == kind; + Bits::fill(&mut written, start, len); + match (same, array.store(), array.validity_bits()) { + (false, _, _) => {} + (true, Store::Any(values), _) => { + for pos in 0..len { + if array.valid(pos) + && !matches!(values.get(pos), None | Some(Variable::Null)) + { + Bits::set(&mut valid, start + pos, true); + } + } + } + (true, _, None) => Bits::fill(&mut valid, start, len), + (true, _, Some(bits)) => Bits::splice(&mut valid, start, bits, len), + } + } + let literal = |rule: usize| self.literal_at(rule, slot, slots, positions).flatten(); + let dict = match kind.unwrap_or(Kind::Num) { + Kind::Num => { + let mut mant = Vec::with_capacity(entries); + let mut scale = Vec::with_capacity(entries); + for rule in 0..rules { + let (m, s) = literal(rule).and_then(Literal::scaled).unwrap_or((0, 0)); + mant.push(m); + scale.push(s); + } + for (batch, array) in arrays.iter().enumerate() { + let len = first.starts[batch + 1] - first.starts[batch]; + match array.map(|a| a.store()) { + Some(Store::Scaled { mant: m, scale: s }) + if m.len() >= len && s.len() >= len => + { + mant.extend_from_slice(&m[..len]); + scale.extend_from_slice(&s[..len]); + } + _ => { + mant.resize(mant.len() + len, 0); + scale.resize(scale.len() + len, 0); + } + } + } + Dict::Scaled { mant, scale } + } + Kind::Text => { + let mut offsets = Vec::with_capacity(entries + 1); + let mut data = String::new(); + offsets.push(0); + for rule in 0..rules { + if let Some(Literal::Str(text)) = literal(rule) { + data.push_str(text); + } + offsets.push(data.len() as i32); + } + for (batch, array) in arrays.iter().enumerate() { + let len = first.starts[batch + 1] - first.starts[batch]; + match array.map(|a| a.store()) { + Some(Store::Text { + offsets: o, + data: d, + }) if o.len() > len => { + let (from, to) = (o[0] as usize, o[len] as usize); + let base = data.len() as i32 - o[0]; + data.push_str(d.get(from..to).unwrap_or_default()); + offsets.extend(o[1..=len].iter().map(|x| x + base)); + } + _ => offsets.extend(std::iter::repeat_n(data.len() as i32, len)), + } + } + Dict::Text { offsets, data } + } + Kind::Bool => { + let mut bits = vec![0u64; entries.div_ceil(64).max(1)]; + for rule in 0..rules { + if let Some(Literal::Bool(true)) = literal(rule) { + Bits::set(&mut bits, rule, true); + } + } + for (batch, array) in arrays.iter().enumerate() { + let start = rules + first.starts[batch]; + let len = first.starts[batch + 1] - first.starts[batch]; + if let Some(Store::Bool(source)) = array.map(|a| a.store()) { + Bits::splice(&mut bits, start, source, len); + } + } + Dict::Bool(bits) + } + Kind::Any => { + let mut values = Vec::with_capacity(entries); + values.extend( + (0..rules).map(|rule| literal(rule).map_or(Variable::Null, Literal::variable)), + ); + for (batch, array) in arrays.iter().enumerate() { + let len = first.starts[batch + 1] - first.starts[batch]; + match array { + Some(array) => { + let column = array.column(); + values.extend((0..len).map(|pos| column.variable(pos))); + } + None => values.extend((0..len).map(|_| Variable::Null)), + } + } + Dict::Any(values) + } + }; + Some((dict, valid, written)) + } + + fn templated<'a>( + &self, + first: &First, + slot: usize, + slots: usize, + positions: &[Option], + ) -> Option> { + if !first.batches.is_empty() { + return None; + } + let templates: Rc<[Literal]> = (0..self.outputs.len()) + .map(|rule| { + self.literal_at(rule, slot, slots, positions) + .flatten() + .cloned() + .unwrap_or(Literal::Null) + }) + .collect(); + let codes: Rc<[i32]> = first + .codes + .iter() + .map(|&code| first.rule(code).map_or(-1, |rule| rule as i32)) + .collect(); + Some(Templated::leaf(codes, templates)) + } + + fn materialized<'a>( + &self, + first: &First, + slot: usize, + slots: usize, + positions: &[Option], + ) -> Leaf<'a> { + let templates: Vec> = (0..self.outputs.len()) + .map( + |rule| match self.literal_at(rule, slot, slots, positions).flatten() { + Some(literal @ (Literal::Array(_) | Literal::Object(_))) => { + Some(literal.variable()) + } + _ => None, + }, + ) + .collect(); + let mut builder = ColumnBuilder::with_capacity(first.codes.len()); + for (row, &code) in first.codes.iter().enumerate() { + match (first.rule(code), first.computed(code)) { + (Some(rule), Some(_)) => match positions[rule * slots + slot] { + Some(index) => builder.push_variable(first.value(row, index as usize)), + None => builder.push_null(), + }, + (Some(rule), None) => match ( + &templates[rule], + self.literal_at(rule, slot, slots, positions).flatten(), + ) { + (Some(template), _) => builder.push_any(template.deep_clone()), + (None, Some(literal)) => builder.push_literal(literal), + (None, None) => builder.push_null(), + }, + _ => builder.push_null(), + } + } + Leaf::typed(builder.finish()) + } + + pub fn columns<'a>(&self, first: First) -> (Vec>, Vec>, Vec) { + let rows = first.codes.len(); + let slots = self.all_paths.len(); + let positions = &self.positions; + let entries = first.entries(); + let mut flags = vec![0u8; entries + 1]; + let mut unmatched = vec![0u64; rows.div_ceil(64)]; + for (chunk, word) in first.codes.chunks(64).zip(unmatched.iter_mut()) { + let mut bits = 0u64; + for (at, &code) in chunk.iter().enumerate() { + bits |= u64::from(code < 0) << at; + if let Some(flag) = flags.get_mut((code.max(-1) + 1) as usize) { + *flag = 1; + } + } + *word = bits; + } + let used = Bits::of(entries, |code| flags[code + 1] != 0); + let matched: Rc<[u64]> = { + let mut bits: Vec = unmatched.iter().map(|w| !w).collect(); + Bits::trim(&mut bits, rows); + bits.into() + }; + let covered = |flags: &[u64]| used.iter().zip(flags).all(|(u, f)| u & !f == 0); + let shared: Rc<[i32]> = first.codes.as_slice().into(); + let mut columns = Vec::with_capacity(slots); + let mut present = Vec::with_capacity(slots); + let mut masks: Vec> = Vec::new(); + let mut filtered: Vec> = Vec::new(); + for slot in 0..slots { + let found: Option> = + self.slot(&first, slot, slots, positions, &used) + .map(|(dict, valid, written)| { + (Rc::new(dict), Cow::Owned(valid), Cow::Owned(written)) + }); + let Some((dict, valid, written)) = found else { + let leaf = match self.templated(&first, slot, slots, positions) { + Some(leaf) => leaf, + None => self.materialized(&first, slot, slots, positions), + }; + let written: Rc<[u64]> = Bits::of(rows, |row| { + first + .rule(first.codes[row]) + .is_some_and(|rule| positions[rule * slots + slot].is_some()) + }) + .into(); + columns.push(leaf); + present.push(Mask::Bits(written)); + continue; + }; + let mask = match covered(&written) { + true => matched.clone(), + false => match masks.iter().find(|(key, _)| *key == written) { + Some((_, mask)) => mask.clone(), + None => { + let mask: Rc<[u64]> = Bits::of(rows, |row| { + usize::try_from(first.codes[row]) + .is_ok_and(|code| Bits::get(&written, code)) + }) + .into(); + masks.push((written, mask.clone())); + mask + } + }, + }; + present.push(Mask::Bits(mask)); + let codes = match covered(&valid) { + true => shared.clone(), + false => match filtered.iter().find(|(key, _)| *key == valid) { + Some((_, codes)) => codes.clone(), + None => { + let codes: Rc<[i32]> = first + .codes + .iter() + .map(|&code| { + match usize::try_from(code).is_ok_and(|c| Bits::get(&valid, c)) { + true => code, + false => -1, + } + }) + .collect(); + filtered.push((valid, codes.clone())); + codes + } + }, + }; + columns.push(Leaf::typed(Array::coded(codes, dict))); + } + (columns, present, unmatched) + } +} diff --git a/core/engine/src/compiled/table/collect.rs b/core/engine/src/compiled/table/collect.rs new file mode 100644 index 00000000..ee5c7461 --- /dev/null +++ b/core/engine/src/compiled/table/collect.rs @@ -0,0 +1,473 @@ +use super::{First, Hit, Kind, Table}; +use crate::compiled::bound::Bound; +use crate::compiled::leaf::Mask; +use crate::compiled::leaf::{Array, Bits, ColumnBuilder, Dict, Leaf, Literal, Records}; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::lane::LaneRunner; +use zen_expression::Variable; + +type Targets = (Vec>>, Vec>>); + +pub(crate) struct Collected<'a> { + pub paths: Arc<[Arc]>, + pub columns: Vec>, + pub present: Vec>, + pub unmatched: Vec, +} + +impl Table { + pub fn collects(&self) -> bool { + self.split.is_some() + } + + fn literal_lists<'a>( + first: &First, + candidates: &[u64], + words: usize, + lists: usize, + targets: &[Vec>], + templates: &[Vec>], + ) -> Vec> { + let mut keys: std::collections::HashMap, i32> = std::collections::HashMap::new(); + let mut entries: Vec> = Vec::new(); + let codes: Rc<[i32]> = (0..first.codes.len()) + .map(|row| { + let Some(chosen) = first.chosen(row) else { + return *keys.entry(vec![0u64; words]).or_insert_with_key(|key| { + entries.push(key.clone()); + entries.len() as i32 - 1 + }); + }; + let mut key: Vec = candidates[row * words..(row + 1) * words].to_vec(); + for (word, bits) in key.iter_mut().enumerate() { + let base = word * 64; + *bits &= match chosen.checked_sub(base) { + Some(skip) if skip >= 64 => 0, + Some(skip) => u64::MAX << skip, + None => u64::MAX, + }; + } + key[chosen / 64] |= 1 << (chosen % 64); + *keys.entry(key).or_insert_with_key(|key| { + entries.push(key.clone()); + entries.len() as i32 - 1 + }) + }) + .collect(); + (0..lists) + .map(|list| { + let values: Vec = entries + .iter() + .map(|key| { + let items: Vec = Bits::rows(key) + .flat_map(|rule| targets[rule].iter().zip(&templates[rule])) + .filter(|(target, _)| **target == Some(list)) + .filter_map(|(_, template)| template.clone()) + .collect(); + Variable::from_array(items) + }) + .collect(); + Leaf::typed(Array::coded(codes.clone(), Rc::new(Dict::Any(values)))) + }) + .collect() + } + + pub(super) fn targets(&self) -> Targets { + let targets: Vec>> = self + .outputs + .iter() + .map(|outputs| { + outputs + .paths + .iter() + .map(|(path, c, _)| match c { + true => self.collect_columns.iter().position(|(_, p)| p == path), + false => None, + }) + .collect() + }) + .collect(); + let templates = self + .outputs + .iter() + .zip(&targets) + .map(|(outputs, targets)| match &outputs.literals { + Some(literals) => literals + .iter() + .zip(targets) + .map(|(literal, target)| target.map(|_| literal.variable())) + .collect(), + None => Vec::new(), + }) + .collect(); + (targets, templates) + } + + pub(super) fn gather( + &self, + runner: &mut LaneRunner, + bound: &Bound, + first: &First, + candidates: &[u64], + (targets, templates): &Targets, + ) -> Vec>> { + let rows = bound.rows(); + let words = self.words; + let mut collected: Vec>> = + vec![vec![Vec::new(); rows]; self.collect_columns.len()]; + let push = |collected: &mut Vec>>, row: usize, rule: usize| { + for (target, template) in targets[rule].iter().zip(&templates[rule]) { + if let (Some(list), Some(template)) = (target, template) { + collected[*list][row].push(template.deep_clone()); + } + } + }; + for (row, &code) in first.codes.iter().enumerate() { + let Some(rule) = first.rule(code) else { + continue; + }; + match first.computed(code).is_some() { + true => { + for (index, target) in targets[rule].iter().enumerate() { + if let Some(list) = target { + collected[*list][row].push(first.value(row, index)); + } + } + } + false => push(&mut collected, row, rule), + } + } + let mut any = vec![0u64; words]; + candidates + .chunks_exact(words) + .for_each(|row| Bits::or(&mut any, row)); + for rule in Bits::rows(&any) { + let outputs = &self.outputs[rule]; + if !targets[rule].iter().any(Option::is_some) { + continue; + } + let lanes: Vec = (0..rows) + .filter(|&row| { + Bits::get(&candidates[row * words..(row + 1) * words], rule) + && first.chosen(row).is_some_and(|c| c < rule) + }) + .collect(); + if lanes.is_empty() { + continue; + } + match outputs.literals { + Some(_) => lanes + .iter() + .for_each(|&row| push(&mut collected, row, rule)), + None => { + let order: Vec = targets[rule].iter().filter_map(|t| *t).collect(); + Self::run_rule( + runner, + outputs.collect.as_ref(), + bound, + &lanes, + &mut |row, values| { + for (list, value) in order.iter().zip(values.iter().flatten()) { + collected[*list][row].push(value.deep_clone()); + } + }, + ); + } + } + } + collected + } + + pub fn first_collect<'a>(&self, runner: &mut LaneRunner, bound: &Bound) -> Collected<'a> { + let paths = self.split.clone().unwrap_or_default(); + let rows = bound.rows(); + let words = self.words; + let (candidates, deferred) = self.candidates(runner, bound, false); + let first = self.choose(runner, bound, &candidates, deferred); + let lists = self.collect_columns.len(); + let targeted = self.targets(); + let (targets, templates) = &targeted; + let literal = + first.batches.is_empty() + && self.outputs.iter().zip(targets).all(|(outputs, targets)| { + match &outputs.literals { + Some(literals) => !literals.iter().any(Literal::deep), + None => !targets.iter().any(Option::is_some), + } + }); + let lists_leaves: Vec> = match literal { + true => Self::literal_lists(&first, &candidates, words, lists, targets, templates), + false => self + .gather(runner, bound, &first, &candidates, &targeted) + .into_iter() + .map(|lists| { + Leaf::Any( + lists + .into_iter() + .map(Variable::from_array) + .collect::>(), + ) + }) + .collect(), + }; + let collect_slots: Vec = self + .all_paths + .iter() + .map(|p| self.collect_columns.iter().any(|(_, c)| c == p)) + .collect(); + let (scalars, masks, unmatched) = self.columns(first); + let mut columns = Vec::with_capacity(paths.len()); + let mut present = Vec::with_capacity(paths.len()); + for ((column, mask), skip) in scalars.into_iter().zip(masks).zip(&collect_slots) { + if !skip { + columns.push(column); + present.push(mask); + } + } + let all: Rc<[u64]> = Bits::ones(rows).into(); + for leaf in lists_leaves { + columns.push(leaf); + present.push(Mask::Bits(all.clone())); + } + Collected { + paths, + columns, + present, + unmatched: vec![0u64; unmatched.len()], + } + } + + pub fn collect_keyed( + &self, + runner: &mut LaneRunner, + bound: &Bound, + ) -> Option<(Vec, Vec, usize)> { + let literal = self + .outputs + .iter() + .all(|o| o.paths.is_empty() || o.literals.is_some()); + if self.hit != Hit::Collect || !literal || !self.stable { + return None; + } + let (candidates, _) = self.candidates(runner, bound, false); + let (codes, sets) = self.sets(&candidates, bound.rows()); + let templates: Vec> = sets + .iter() + .map(|set| { + Bits::rows(set) + .map(|rule| { + let outputs = &self.outputs[rule]; + match &outputs.literals { + Some(literals) if !outputs.paths.is_empty() => { + let values: Vec = + literals.iter().map(Literal::variable).collect(); + self.built(self.builder(rule, None).as_ref(), rule, None, &values) + } + _ => Variable::empty_object(), + } + }) + .collect() + }) + .collect(); + let values = codes + .iter() + .map(|&code| { + Variable::from_array( + templates[code as usize] + .iter() + .map(Variable::deep_clone) + .collect(), + ) + }) + .collect(); + Some((values, codes, sets.len())) + } + + fn record_names(&self) -> Option>> { + let mut names: Vec> = Vec::new(); + for outputs in &self.outputs { + let mut last: Option = None; + for (path, _, _) in &outputs.paths { + if path.is_empty() || path.contains('.') || path.starts_with('$') { + return None; + } + let at = match names.iter().position(|name| name == path) { + Some(at) => at, + None => { + names.push(path.clone()); + names.len() - 1 + } + }; + if last.is_some_and(|last| at <= last) { + return None; + } + last = Some(at); + } + } + Some(names) + } + + fn record_dict(cells: &[Vec>], field: usize) -> Option { + let column: Vec> = cells + .iter() + .map(|rule| { + rule.get(field) + .copied() + .flatten() + .filter(|l| !matches!(l, Literal::Null)) + }) + .collect(); + let kinds: Vec = column + .iter() + .flatten() + .map(|literal| Kind::of_literal(literal)) + .collect::>>()?; + let kind = *kinds.first()?; + if kinds.iter().any(|k| *k != kind) { + return None; + } + Some(match kind { + Kind::Text => { + let mut offsets = Vec::with_capacity(column.len() + 1); + let mut data = String::new(); + offsets.push(0i32); + for literal in &column { + if let Some(Literal::Str(text)) = literal { + data.push_str(text); + } + offsets.push(i32::try_from(data.len()).ok()?); + } + Dict::Text { offsets, data } + } + Kind::Num => { + let parts: Vec<(i64, u8)> = column + .iter() + .map(|literal| literal.and_then(Literal::scaled).unwrap_or((0, 0))) + .collect(); + Dict::Scaled { + mant: parts.iter().map(|p| p.0).collect(), + scale: parts.iter().map(|p| p.1).collect(), + } + } + Kind::Bool => { + let mut bits = vec![0u64; column.len().div_ceil(64).max(1)]; + column + .iter() + .enumerate() + .filter(|(_, l)| matches!(l, Some(Literal::Bool(true)))) + .for_each(|(at, _)| Bits::set(&mut bits, at, true)); + Dict::Bool(bits) + } + Kind::Any => return None, + }) + } + + pub fn collect_records<'a>( + &self, + runner: &mut LaneRunner, + bound: &Bound, + ) -> Option<(Records<'a>, Vec, usize)> { + let literal = self + .outputs + .iter() + .all(|o| o.paths.is_empty() || o.literals.is_some()); + if self.hit != Hit::Collect || !literal || !self.stable { + return None; + } + let names = self.record_names()?; + let rows = bound.rows(); + let (candidates, _) = self.candidates(runner, bound, false); + let (codes, sets) = self.sets(&candidates, rows); + let sets: Vec> = sets + .into_iter() + .map(|key| Bits::rows(key).collect()) + .collect(); + let cells: Vec>> = (0..self.outputs.len()) + .map(|rule| { + let outputs = &self.outputs[rule]; + names + .iter() + .map(|name| { + let index = outputs.paths.iter().position(|(path, _, _)| path == name)?; + outputs.literals.as_ref()?.get(index) + }) + .collect() + }) + .collect(); + let mut offsets = Vec::with_capacity(rows + 1); + offsets.push(0i32); + let mut total = 0usize; + for &code in &codes { + total += sets[code as usize].len(); + offsets.push(i32::try_from(total).ok()?); + } + let dicts: Vec>> = (0..names.len()) + .map(|field| Self::record_dict(&cells, field).map(Rc::new)) + .collect(); + let mut builders: Vec> = dicts + .iter() + .map(|dict| dict.is_none().then(|| ColumnBuilder::with_capacity(total))) + .collect(); + let mut keys: Vec> = dicts + .iter() + .map(|dict| match dict { + Some(_) => Vec::with_capacity(total), + None => Vec::new(), + }) + .collect(); + let mut present: Vec> = names + .iter() + .map(|_| vec![0u64; total.div_ceil(64)]) + .collect(); + let mut item = 0usize; + for &code in &codes { + for &rule in &sets[code as usize] { + for (((builder, keys), bits), cell) in builders + .iter_mut() + .zip(keys.iter_mut()) + .zip(present.iter_mut()) + .zip(&cells[rule]) + { + if cell.is_some() { + Bits::set(bits, item, true); + } + match builder { + Some(builder) => match cell { + Some(literal) => builder.push_literal(literal), + None => builder.push_null(), + }, + None => keys.push(match cell { + Some(Literal::Null) | None => -1, + Some(_) => rule as i32, + }), + } + } + item += 1; + } + } + let fields = names + .iter() + .zip(builders.into_iter().zip(keys).zip(dicts)) + .zip(present) + .map(|((name, ((builder, keys), dict)), bits)| { + let leaf = match (builder, dict) { + (Some(builder), _) => Leaf::typed(builder.finish()), + (None, Some(dict)) => Leaf::typed(Array::coded(keys.into(), dict)), + (None, None) => Leaf::nulls(total), + }; + ( + zen_types::symbol::Symbol::from(name.as_ref()), + leaf, + Rc::from(bits), + ) + }) + .collect(); + let size = sets.len(); + Some(( + Records::new(rows, offsets, Bits::ones(rows), fields, None), + codes, + size, + )) + } +} diff --git a/core/engine/src/compiled/table/dispatch.rs b/core/engine/src/compiled/table/dispatch.rs new file mode 100644 index 00000000..05aacfe6 --- /dev/null +++ b/core/engine/src/compiled/table/dispatch.rs @@ -0,0 +1,206 @@ +use super::{Column, Table}; +use crate::compiled::bound::Bound; +use crate::compiled::leaf::{Array, Bits}; +use zen_expression::lane::{LaneRunner, Pieces}; + +pub(crate) struct Dispatch { + pieces: Vec, + strides: Vec, + lut: Option>, + candidates: Vec>, + pub(super) chosen: Option>, +} + +impl Dispatch { + const LUT: usize = 1 << 16; + + pub(super) fn build(columns: &[Column], rules: usize, words: usize) -> Option { + let pieces = columns + .iter() + .map(|column| match column { + Column::Field { cells, empty, .. } => cells.pieces(empty), + Column::Plain { .. } => None, + }) + .collect::>>()?; + let mut strides = Vec::with_capacity(pieces.len()); + let mut size = 1usize; + for p in &pieces { + strides.push(size); + size = size.saturating_mul(p.len().max(1)); + } + let mut candidates: Vec> = Vec::new(); + let lut = (size <= Self::LUT).then(|| { + (0..size) + .map(|index| { + let mut bits = Table::opened(rules, words, 1); + for (p, stride) in pieces.iter().zip(&strides) { + let piece = (index / stride) % p.len().max(1); + if let Some(b) = p.bits.get(piece) { + Bits::and(&mut bits, b); + } + } + match candidates.iter().position(|c| *c == bits) { + Some(at) => at as u32, + None => { + candidates.push(bits); + (candidates.len() - 1) as u32 + } + } + }) + .collect() + }); + let firsts: Vec = candidates + .iter() + .map(|bits| { + bits.iter() + .enumerate() + .find(|(_, w)| **w != 0) + .map_or(-1, |(i, w)| (i * 64 + w.trailing_zeros() as usize) as i32) + }) + .collect(); + let chosen = lut.as_ref().map(|lut: &Vec| { + lut.iter() + .map(|&at| firsts.get(at as usize).copied().unwrap_or(-1)) + .collect() + }); + Some(Dispatch { + pieces, + strides, + lut, + candidates, + chosen, + }) + } +} + +impl Table { + pub(super) fn keyed( + &self, + dispatch: &Dispatch, + runner: &mut LaneRunner, + bound: &Bound, + ) -> Option> { + dispatch.lut.as_ref()?; + let rows = bound.rows(); + let mut keys = vec![0u32; rows]; + let mut pieces = vec![0u32; rows]; + let mut failed = vec![false; rows]; + for ((column, p), stride) in self + .columns + .iter() + .zip(&dispatch.pieces) + .zip(&dispatch.strides) + { + let Column::Field { field, cells, .. } = column else { + continue; + }; + failed.iter_mut().for_each(|f| *f = false); + let (direct, typed) = Self::field_column(runner, bound, field, &mut failed); + let view = direct.or_else(|| typed.as_ref().map(Array::column)); + match view { + Some(view) => cells.classify(p, &view, rows, &mut pieces), + None => pieces.iter_mut().for_each(|x| *x = p.failed), + } + let stride = *stride as u32; + match failed.iter().any(|f| *f) { + false => keys + .iter_mut() + .zip(&pieces) + .for_each(|(key, piece)| *key += *piece as u32 * stride), + true => { + for ((key, piece), failed) in keys.iter_mut().zip(&pieces).zip(&failed) { + *key += match failed { + true => p.failed as u32, + false => *piece as u32, + } * stride; + } + } + } + } + Some(keys) + } + + pub(super) fn dispatched( + &self, + dispatch: &Dispatch, + runner: &mut LaneRunner, + bound: &Bound, + ) -> Vec { + if let (Some(keys), Some(lut), 1) = ( + self.keyed(dispatch, runner, bound), + &dispatch.lut, + self.words, + ) { + return keys + .iter() + .map(|key| { + lut.get(*key as usize) + .and_then(|i| dispatch.candidates.get(*i as usize)) + .and_then(|bits| bits.first().copied()) + .unwrap_or(0) + }) + .collect(); + } + let (rows, words) = (bound.rows(), self.words); + let mut keys = vec![0u32; rows]; + let mut pieces = vec![0u32; rows]; + let mut failed = vec![false; rows]; + let tail = Self::tail(self.rules); + let mut all: Vec = match dispatch.lut { + Some(_) => Vec::new(), + None => self.open(rows), + }; + for ((column, p), stride) in self + .columns + .iter() + .zip(&dispatch.pieces) + .zip(&dispatch.strides) + { + let Column::Field { field, cells, .. } = column else { + continue; + }; + failed.iter_mut().for_each(|f| *f = false); + let (direct, typed) = Self::field_column(runner, bound, field, &mut failed); + let view = direct.or_else(|| typed.as_ref().map(Array::column)); + match view { + Some(view) => cells.classify(p, &view, rows, &mut pieces), + None => pieces.iter_mut().for_each(|x| *x = p.failed), + } + for (piece, failed) in pieces.iter_mut().zip(&failed) { + if *failed { + *piece = p.failed; + } + } + match dispatch.lut { + Some(_) => keys + .iter_mut() + .zip(&pieces) + .for_each(|(k, piece)| *k += *piece as u32 * *stride as u32), + None => { + for (row, piece) in pieces.iter().enumerate() { + if let Some(bits) = p.bits.get(*piece as usize) { + Bits::and(&mut all[row * words..(row + 1) * words], bits); + } + } + } + } + } + if let Some(lut) = &dispatch.lut { + all = Vec::with_capacity(rows * words); + for key in &keys { + let index = lut.get(*key as usize).copied().unwrap_or(0) as usize; + match dispatch.candidates.get(index) { + Some(bits) => all.extend(bits.iter().enumerate().map(|(w, b)| { + if w + 1 == words { + b & tail + } else { + *b + } + })), + None => all.extend(std::iter::repeat_n(0, words)), + } + } + } + all + } +} diff --git a/core/engine/src/compiled/table/first.rs b/core/engine/src/compiled/table/first.rs new file mode 100644 index 00000000..84eadd2f --- /dev/null +++ b/core/engine/src/compiled/table/first.rs @@ -0,0 +1,239 @@ +use super::{Batch, Deferred, Hit, Table}; +use crate::compiled::bound::{Bound, Outs}; +use crate::compiled::leaf::Array; +use zen_expression::lane::LaneRunner; +use zen_expression::Variable; + +pub(crate) struct First { + pub(super) rules: usize, + pub(super) codes: Vec, + pub(super) batches: Vec, + pub(super) starts: Vec, +} + +impl First { + pub fn coded(rules: usize, codes: Vec) -> First { + First { + rules, + codes, + batches: Vec::new(), + starts: vec![0], + } + } + + pub(super) fn entries(&self) -> usize { + self.rules + self.starts.last().copied().unwrap_or(0) + } + + pub(super) fn computed(&self, code: i32) -> Option<(usize, usize)> { + let entry = usize::try_from(code).ok()?.checked_sub(self.rules)?; + let batch = self + .starts + .partition_point(|&start| start <= entry) + .checked_sub(1)?; + Some((batch, entry - self.starts[batch])) + } + + pub(super) fn rule(&self, code: i32) -> Option { + let code = usize::try_from(code).ok()?; + match code < self.rules { + true => Some(code), + false => self + .computed(code as i32) + .and_then(|(batch, _)| self.batches.get(batch)) + .map(|b| b.rule), + } + } + + pub(super) fn chosen(&self, row: usize) -> Option { + self.codes.get(row).and_then(|&code| self.rule(code)) + } + + pub(super) fn value(&self, row: usize, index: usize) -> Variable { + self.codes + .get(row) + .and_then(|&code| self.computed(code)) + .and_then(|(batch, pos)| { + Some( + self.batches + .get(batch)? + .outputs + .get(index)? + .column() + .variable(pos) + .deep_clone(), + ) + }) + .unwrap_or(Variable::Null) + } +} + +impl Table { + pub fn first_hit(&self) -> bool { + self.hit == Hit::First + } + + #[inline] + pub(super) fn next(candidates: &[u64], mask: Option<&[u64]>, from: usize) -> Option { + let at = |word: usize| -> Option { + let bits = *candidates.get(word)?; + match mask { + None => Some(bits), + Some(mask) => Some(bits & mask.get(word)?), + } + }; + let (mut word, bit) = (from / 64, from % 64); + let mut current = at(word)? & (u64::MAX << bit); + loop { + if current != 0 { + return Some(word * 64 + current.trailing_zeros() as usize); + } + word += 1; + current = at(word)?; + } + } + + pub fn first(&self, runner: &mut LaneRunner, bound: &Bound) -> First { + if let (Some(dispatch), true) = (&self.dispatch, self.literal) { + if let (Some(keys), Some(chosen)) = + (self.keyed(dispatch, runner, bound), &dispatch.chosen) + { + return First { + rules: self.outputs.len(), + codes: keys + .iter() + .map(|key| chosen.get(*key as usize).copied().unwrap_or(-1)) + .collect(), + batches: Vec::new(), + starts: vec![0], + }; + } + } + let (candidates, deferred) = self.candidates(runner, bound, true); + self.choose(runner, bound, &candidates, deferred) + } + + pub(super) fn choose( + &self, + runner: &mut LaneRunner, + bound: &Bound, + candidates: &[u64], + mut deferred: Vec, + ) -> First { + let rows = bound.rows(); + let words = self.words; + let rules = self.outputs.len(); + if deferred.is_empty() && self.literal { + return First { + rules, + codes: candidates + .chunks_exact(words) + .map(|row| Self::next(row, None, 0).map_or(-1, |rule| rule as i32)) + .collect(), + batches: Vec::new(), + starts: vec![0], + }; + } + let mut cursor = vec![0usize; rows]; + let mut codes: Vec = vec![-1; rows]; + let mut batches: Vec = Vec::new(); + let mut starts: Vec = vec![0]; + let mut open: Vec = (0..rows).collect(); + let mut buckets: Vec> = vec![Vec::new(); self.rules]; + let mut touched: Vec = Vec::new(); + let mut kept = vec![false; rows]; + let mut before: Vec = Vec::new(); + let mut outs = Outs::take(); + while !open.is_empty() { + for &row in &open { + if let Some(rule) = Self::next( + &candidates[row * words..(row + 1) * words], + None, + cursor[row], + ) { + if buckets[rule].is_empty() { + touched.push(rule); + } + buckets[rule].push(row); + } + } + open.clear(); + for rule in std::mem::take(&mut touched) { + let mut lanes = std::mem::take(&mut buckets[rule]); + if !deferred.is_empty() { + before.clear(); + before.extend_from_slice(&lanes); + self.verify(runner, bound, &mut deferred, rule, &mut lanes); + lanes.iter().for_each(|&row| kept[row] = true); + for &row in before.iter().filter(|&&r| !kept[r]) { + cursor[row] = rule + 1; + open.push(row); + } + lanes.iter().for_each(|&row| kept[row] = false); + } + if lanes.is_empty() { + buckets[rule] = lanes; + continue; + } + let outputs = &self.outputs[rule]; + let direct = match (outputs.paths.is_empty(), &outputs.literals) { + (false, None) => Self::direct(outputs, bound, &lanes), + _ => None, + }; + match (outputs.paths.is_empty(), &outputs.literals, &outputs.full) { + (true, _, _) | (false, Some(_), _) => { + lanes.iter().for_each(|&row| codes[row] = rule as i32) + } + (false, None, _) if direct.is_some() => { + let start = starts.last().copied().unwrap_or(0); + for (pos, &row) in lanes.iter().enumerate() { + codes[row] = (rules + start + pos) as i32; + } + starts.push(start + lanes.len()); + batches.push(Batch { + rule, + outputs: direct.unwrap_or_default(), + }); + } + (false, None, Some(program)) => { + let mut failed = vec![false; lanes.len()]; + bound.export(runner, program, Some(&lanes), &mut outs, |pos, _, _| { + if let Some(f) = failed.get_mut(pos) { + *f = true; + } + }); + let start = starts.last().copied().unwrap_or(0); + for (pos, &row) in lanes.iter().enumerate() { + match failed[pos] { + true => { + cursor[row] = rule + 1; + open.push(row); + } + false => codes[row] = (rules + start + pos) as i32, + } + } + starts.push(start + lanes.len()); + batches.push(Batch { + rule, + outputs: outs.iter_mut().map(Array::from_output).collect(), + }); + } + (false, None, None) => { + for &row in &lanes { + cursor[row] = rule + 1; + open.push(row); + } + } + } + lanes.clear(); + buckets[rule] = lanes; + } + } + First { + rules, + codes, + batches, + starts, + } + } +} diff --git a/core/engine/src/compiled/table/fused.rs b/core/engine/src/compiled/table/fused.rs new file mode 100644 index 00000000..12c4d8bf --- /dev/null +++ b/core/engine/src/compiled/table/fused.rs @@ -0,0 +1,125 @@ +use super::{Column, Table}; +use crate::compiled::bound::{Bound, Outs}; +use crate::compiled::leaf::{Array, Bits, Leaf}; +use std::sync::Arc; +use zen_expression::lane::{Binding, LaneProgram, LaneRunner, Op}; + +pub(super) struct FusedCells { + program: LaneProgram, + cells: Vec<(usize, usize)>, +} + +impl Table { + pub(super) fn fused( + columns: &[Column], + plain: &[(usize, usize, Arc)], + lazy: bool, + ) -> Option { + let mut entries: Vec<(Arc, Option>)> = Vec::new(); + let mut cells: Vec<(usize, usize)> = Vec::new(); + for (index, column) in columns.iter().enumerate() { + match column { + Column::Field { + field, cells: set, .. + } if !lazy && set.others() > 0 && !set.peelable() && field.path().is_some() => { + let Some(target) = field.source() else { + continue; + }; + let sources: Option>> = (0..set.others()) + .map(|other| { + set.other(other) + .and_then(|(program, _)| program.source()) + .map(Arc::from) + }) + .collect(); + let Some(sources) = sources else { + continue; + }; + for (other, source) in sources.into_iter().enumerate() { + entries.push((source, Some(Arc::from(target)))); + cells.push((index, other)); + } + } + Column::Plain { + cells: programs, .. + } if !lazy + || plain.len() <= 8 + || !programs.iter().flat_map(|(p, _)| p).any(Self::heavy) => + { + for (_, cell, source) in plain.iter().filter(|(column, _, _)| *column == index) + { + entries.push((source.clone(), None)); + cells.push((index, *cell)); + } + } + Column::Field { .. } | Column::Plain { .. } => {} + } + } + if entries.is_empty() || entries.len() > Self::FUSED { + return None; + } + let refs: Vec<(&str, Option<&str>)> = entries + .iter() + .map(|(s, f)| (s.as_ref(), f.as_deref())) + .collect(); + LaneProgram::compile_cells(&refs) + .ok() + .map(|program| FusedCells { program, cells }) + } + + fn heavy(program: &LaneProgram) -> bool { + program.program().steps.iter().any(|step| { + matches!( + step.op, + Op::Call { .. } | Op::Method { .. } | Op::Closure(_) | Op::LoadCall(_) + ) + }) + } + + pub(super) fn fused_truths( + &self, + runner: &mut LaneRunner, + bound: &Bound, + ) -> Option>> { + let fused = self.fused.as_ref()?; + let p = fused.program.program(); + let bound_only = p.site_keys.iter().all(|key| { + key.as_deref() + .is_some_and(|key| !matches!((bound.bind)(key), Binding::Row)) + }); + if p.opaque() || !bound_only { + return None; + } + let rows = bound.rows(); + let mut outs = Outs::take(); + let mut failed: Vec<(usize, usize)> = Vec::new(); + bound.export(runner, &fused.program, None, &mut outs, |row, stage, _| { + failed.push((row, stage)) + }); + let mut truths: Vec> = outs + .iter_mut() + .map(|out| Leaf::typed(Array::from_output(out)).truths(rows)) + .collect(); + truths.resize(fused.cells.len(), vec![0u64; rows.div_ceil(64)]); + for (row, stage) in failed { + if let Some(truth) = truths.get_mut(stage) { + Bits::set(truth, row, false); + } + } + Some(truths) + } + + pub(super) fn fused_at(&self, column: usize, cell: usize) -> Option { + self.fused + .as_ref()? + .cells + .iter() + .position(|c| *c == (column, cell)) + } + + pub(super) fn fuses(&self, column: usize) -> bool { + self.fused + .as_ref() + .is_some_and(|fused| fused.cells.iter().any(|(c, _)| *c == column)) + } +} diff --git a/core/engine/src/compiled/table/mod.rs b/core/engine/src/compiled/table/mod.rs new file mode 100644 index 00000000..5c213d7c --- /dev/null +++ b/core/engine/src/compiled/table/mod.rs @@ -0,0 +1,1137 @@ +mod cells; +mod collect; +mod dispatch; +mod first; +mod fused; +mod profile; +mod strict; + +use crate::compiled::bound::{Bound, Outs}; +use crate::compiled::leaf::{Array, Bits, Dict, Literal, Store}; +use cells::{Built, OutputCells}; +pub(crate) use dispatch::Dispatch; +pub(crate) use first::First; +use fused::FusedCells; +use profile::{Empty, Resolve}; +pub(crate) use profile::{Profile, Rows, TableIr}; +use std::borrow::Cow; +use std::rc::Rc; +use std::sync::Arc; +use strict::Strict; +pub(crate) use strict::{Matching, Picked}; +use zen_expression::lane::{ + Binding, CellEnv, CellSet, Column as LaneColumn, LaneProgram, LaneRunner, SourceInfo, Values, +}; +use zen_expression::typed::TableSpec; +use zen_expression::Variable; + +pub(crate) enum Column { + Field { + field: Box, + cells: Box, + empty: Vec, + }, + Plain { + cells: Vec<(Option, Vec)>, + empty: Vec, + owners: Vec>, + optimistic: Vec, + }, +} + +enum Deferred { + Field { + column: usize, + reference: Option, + values: Vec, + scopes: Option>, + memo: Vec>, + }, + Plain { + column: usize, + memo: Vec>, + }, +} + +#[derive(Clone)] +pub(crate) enum OutSource { + Literal(Literal), + Path(Arc), +} + +pub(crate) struct RuleOutputs { + full: Option, + literals: Option>, + sources: Option>, + collect: Option, + paths: Vec<(Arc, bool, usize)>, + slots: Arc<[usize]>, +} + +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Num, + Text, + Bool, + Any, +} + +impl Kind { + fn of_literal(literal: &Literal) -> Option { + match literal { + Literal::Null => None, + Literal::Num(_) if literal.scaled().is_some() => Some(Kind::Num), + Literal::Str(_) => Some(Kind::Text), + Literal::Bool(_) => Some(Kind::Bool), + _ => Some(Kind::Any), + } + } + + fn of_array(array: &Array) -> Option { + match array.store() { + Store::Scaled { .. } => Some(Kind::Num), + Store::Text { .. } => Some(Kind::Text), + Store::Bool(_) => Some(Kind::Bool), + Store::Coded { .. } | Store::List { .. } => Some(Kind::Any), + Store::Any(values) => values + .iter() + .any(|v| !matches!(v, Variable::Null)) + .then_some(Kind::Any), + } + } + + fn join(a: Option, b: Option) -> Option { + match (a, b) { + (None, k) | (k, None) => k, + (Some(a), Some(b)) if a == b => Some(a), + _ => Some(Kind::Any), + } + } +} + +pub(crate) struct Batch { + rule: usize, + outputs: Vec, +} + +pub(crate) enum TableOut { + Leaves(Arc<[usize]>, Vec), + Value(Variable), +} + +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum Hit { + First, + Collect, + FirstCollect, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Scalar { + Num, + Bool, + Text, +} + +type Keyed<'k, T> = (Cow<'k, [u64]>, Rc<[T]>); +type Found<'k> = (Rc, Cow<'k, [u64]>, Cow<'k, [u64]>); + +pub(crate) struct Table { + id: u64, + profile: Profile, + fused: Option, + positions: Vec>, + dispatch: Option, + all_paths: Arc<[Arc]>, + hit: Hit, + rules: usize, + words: usize, + columns: Vec, + outputs: Vec, + collect_columns: Vec<(usize, Arc)>, + split: Option]>>, + literal: bool, + pub stable: bool, + pub spec: Option, + strict: Option>, +} + +enum Part { + Value(usize), + Child(Built), +} + +impl Table { + fn reachable(mut ir: TableIr) -> TableIr { + if ir.collect || ir.profile.resolve != Resolve::Row || ir.outputs.iter().any(|o| o.collect) + { + return ir; + } + let ids: Vec<&Arc> = ir + .inputs + .iter() + .map(|i| i.id) + .chain(ir.outputs.iter().map(|o| o.id)) + .collect(); + let mut seen: std::collections::HashSet> = + std::collections::HashSet::with_capacity(ir.rules.len()); + let keep: Vec = ir + .rules + .iter() + .map(|rule| { + seen.insert( + ids.iter() + .map(|id| ir.cell(rule, id).unwrap_or("")) + .collect(), + ) + }) + .collect(); + let mut keep = keep.into_iter(); + ir.rules.retain(|_| keep.next().unwrap_or(true)); + ir + } + + pub fn compile(ir: TableIr) -> Result { + let ir = Self::reachable(ir); + let rules = ir.rules.len(); + let words = rules.div_ceil(64).max(1); + let strict = ir.profile.strict(); + let bit = |bits: &mut Vec, rule: usize| bits[rule / 64] |= 1 << (rule % 64); + let mut columns = Vec::with_capacity(ir.inputs.len()); + let mut ordered = Vec::new(); + let mut plain_sources: Vec<(usize, usize, Arc)> = Vec::new(); + for input in ir.inputs.iter() { + let cells = ir.cells(input.id); + if strict && cells.iter().all(Option::is_none) { + continue; + } + let empty = Self::empty(&cells, words); + let field = match strict { + true => Some( + input + .field + .filter(|f| !f.trim().is_empty()) + .ok_or("table cell without a field")?, + ), + false => input.field, + }; + match field { + Some(field) => { + if strict + && cells + .iter() + .flatten() + .any(|cell| LaneProgram::unary(cell).is_err()) + { + return Err("table cell does not parse".into()); + } + let program = LaneProgram::standard(field).map_err(|e| e.to_string())?; + let set = CellSet::compile(&cells).map_err(|e| e.to_string())?; + if strict { + let dollar = (0..set.others()).all(|other| { + set.other(other).is_some_and(|(program, _)| { + program + .program() + .site_keys + .iter() + .flatten() + .all(|key| key.starts_with('$')) + }) + }); + if !dollar { + return Err("table cell reads beyond `$`".into()); + } + ordered.push( + cells + .iter() + .flatten() + .any(|cell| cell.contains(['<', '>']) || cell.contains("..")), + ); + } + columns.push(Column::Field { + field: Box::new(program), + cells: Box::new(set), + empty, + }); + } + None => { + let mut distinct: Vec<(Arc, Option, Vec)> = Vec::new(); + for (rule, cell) in cells.iter().enumerate() { + let Some(cell) = cell else { + continue; + }; + if SourceInfo::reads_dollar(cell) { + return Err("table cell without a field reads `$`".into()); + } + match distinct.iter_mut().find(|(s, _, _)| s.as_ref() == *cell) { + Some((_, _, bits)) => bit(bits, rule), + None => { + let mut bits = vec![0u64; words]; + bit(&mut bits, rule); + distinct.push(( + Arc::from(*cell), + LaneProgram::standard(cell).ok(), + bits, + )); + } + } + } + let mut owners = vec![None; rules]; + let mut optimistic = vec![0u64; words]; + for (index, (_, program, bits)) in distinct.iter().enumerate() { + if program.is_none() { + continue; + } + Bits::or(&mut optimistic, bits); + for (rule, owner) in owners.iter_mut().enumerate() { + if bits[rule / 64] >> (rule % 64) & 1 == 1 { + *owner = Some(index); + } + } + } + for (cell, (source, program, _)) in distinct.iter().enumerate() { + if program.is_some() { + plain_sources.push((columns.len(), cell, source.clone())); + } + } + columns.push(Column::Plain { + cells: distinct.into_iter().map(|(_, p, b)| (p, b)).collect(), + empty, + owners, + optimistic, + }); + } + } + } + let mut table = Self { + id: Self::next_id(), + profile: ir.profile, + fused: None, + positions: Vec::new(), + dispatch: None, + all_paths: Arc::from([]), + hit: Hit::First, + rules, + words, + columns, + outputs: Vec::new(), + collect_columns: Vec::new(), + split: None, + literal: false, + stable: false, + spec: None, + strict: None, + }; + match ir.profile.resolve { + Resolve::Column => table.strict = Some(Box::new(Strict::compile(&ir, ordered)?)), + Resolve::Row => table.rows(&ir, &plain_sources)?, + } + Ok(table) + } + + fn rows( + &mut self, + ir: &TableIr, + plain_sources: &[(usize, usize, Arc)], + ) -> Result<(), String> { + let rules = self.rules; + let mut all_paths: Vec> = Vec::new(); + for output in ir.written() { + if !all_paths.iter().any(|p| p.as_ref() == output.path) { + all_paths.push(Arc::from(output.path)); + } + } + let mut outputs = Vec::with_capacity(rules); + let mut memo = OutputCells::default(); + for rule in ir.rules.iter() { + let mut paths = Vec::new(); + let mut full: Vec<(String, &str)> = Vec::new(); + let mut collect: Vec<(String, &str)> = Vec::new(); + for (column, output) in ir.outputs.iter().enumerate() { + if output.path.is_empty() { + continue; + } + let Some(cell) = ir.cell(rule, output.id) else { + continue; + }; + if SourceInfo::reads_dollar(cell) { + return Err("table output cell reads `$`".into()); + } + let key = format!("o{}", full.len()); + full.push((key, cell)); + if output.collect { + collect.push((format!("o{}", collect.len()), cell)); + } + paths.push((Arc::from(output.path), output.collect, column)); + } + let literals = full + .iter() + .map(|(_, cell)| memo.cell(cell).0.clone()) + .collect::>>(); + let sources = match literals { + Some(_) => None, + None => full + .iter() + .map(|(_, cell)| memo.cell(cell).1.clone()) + .collect::>>(), + }; + outputs.push(RuleOutputs { + literals, + sources, + full: memo.many(&full), + collect: memo.many(&collect), + slots: paths + .iter() + .map(|(p, _, _): &(Arc, bool, usize)| { + all_paths.iter().position(|a| a == p).unwrap_or_default() + }) + .collect(), + paths, + }); + } + + let has_collect = ir.outputs.iter().any(|o| o.collect); + let hit = match (ir.collect, has_collect) { + (false, true) => Hit::FirstCollect, + (false, false) => Hit::First, + (true, _) => Hit::Collect, + }; + let collect_columns = ir + .outputs + .iter() + .enumerate() + .filter(|(_, o)| o.collect && !o.path.is_empty()) + .map(|(i, o)| (i, Arc::from(o.path))) + .collect::)>>(); + let collected: Vec<&Arc> = collect_columns.iter().map(|(_, p)| p).collect(); + let distinct = collected + .iter() + .enumerate() + .all(|(i, p)| !collected[..i].contains(p)); + let scalars: Vec> = all_paths + .iter() + .filter(|p| !collected.contains(p)) + .cloned() + .collect(); + let disjoint = ir.outputs.iter().all(|o| { + o.collect || o.path.is_empty() || !collected.iter().any(|c| c.as_ref() == o.path) + }); + let split = (hit == Hit::FirstCollect && distinct && disjoint).then(|| { + scalars + .into_iter() + .chain(collected.into_iter().cloned()) + .collect() + }); + + let literal = outputs + .iter() + .all(|o| o.paths.is_empty() || o.literals.is_some()); + let slots = all_paths.len(); + let mut positions: Vec> = vec![None; outputs.len() * slots]; + for (rule, rule_outputs) in outputs.iter().enumerate() { + for (index, &slot) in rule_outputs.slots.iter().enumerate() { + if slot < slots { + positions[rule * slots + slot] = Some(index as u32); + } + } + } + let clocked = |text: &str| { + text.split(|c: char| !(c.is_alphanumeric() || c == '_')) + .any(|token| { + matches!( + token, + "rand" | "date" | "time" | "d" | "now" | "dateString" | "isToday" + ) + }) + }; + self.fused = Self::fused(&self.columns, plain_sources, hit == Hit::First); + self.stable = ir + .rules + .iter() + .all(|rule| rule.values().all(|cell| !clocked(cell.as_ref()))); + self.spec = ir.spec(); + self.positions = positions; + self.dispatch = Dispatch::build(&self.columns, rules, self.words); + self.literal = literal; + self.split = split; + self.all_paths = all_paths.into(); + self.hit = hit; + self.outputs = outputs; + self.collect_columns = collect_columns; + Ok(()) + } + + fn empty(cells: &[Option<&str>], words: usize) -> Vec { + let mut empty = vec![0u64; words]; + for (rule, cell) in cells.iter().enumerate() { + if cell.is_none() { + empty[rule / 64] |= 1 << (rule % 64); + } + } + empty + } + + fn tail(rules: usize) -> u64 { + match (rules, rules % 64) { + (0, _) => 0, + (_, 0) => u64::MAX, + (_, t) => (1u64 << t) - 1, + } + } + + fn opened(rules: usize, words: usize, rows: usize) -> Vec { + let mut all = vec![u64::MAX; rows * words]; + all.chunks_exact_mut(words) + .for_each(|row| row[words - 1] &= Self::tail(rules)); + all + } + + pub fn open(&self, rows: usize) -> Vec { + Self::opened(self.rules, self.words, rows) + } + + fn sets<'c>(&self, candidates: &'c [u64], rows: usize) -> (Vec, Vec<&'c [u64]>) { + let words = self.words; + let mut seen: ahash::HashMap<&[u64], i32> = ahash::HashMap::default(); + let mut sets: Vec<&[u64]> = Vec::new(); + let codes = (0..rows) + .map(|row| { + let key = &candidates[row * words..(row + 1) * words]; + *seen.entry(key).or_insert_with(|| { + sets.push(key); + (sets.len() - 1) as i32 + }) + }) + .collect(); + (codes, sets) + } + + pub fn programs(&self) -> Vec<&LaneProgram> { + if let Some(strict) = &self.strict { + return self.fields().chain(strict.cells()).collect(); + } + let mut programs: Vec<&LaneProgram> = Vec::new(); + for column in &self.columns { + match column { + Column::Field { field, cells, .. } => { + programs.push(field); + programs.extend(cells.programs()); + } + Column::Plain { cells, .. } => { + programs.extend(cells.iter().filter_map(|(p, _)| p.as_ref())) + } + } + } + for outputs in &self.outputs { + programs.extend(outputs.full.iter()); + programs.extend(outputs.collect.iter()); + } + programs + } + + pub fn fills(&self) -> bool { + self.profile.empty == Empty::Fill + } + + pub fn literal(&self) -> bool { + self.literal + } + + pub fn rules(&self) -> usize { + self.outputs.len() + } + + pub fn writes(&self, rule: usize, slot: usize) -> bool { + self.positions + .get(rule * self.all_paths.len() + slot) + .is_some_and(Option::is_some) + } + + pub fn paths(&self) -> &Arc<[Arc]> { + &self.all_paths + } + + pub fn slot_kind(&self, path: &str) -> Option { + let slots = self.all_paths.len(); + let slot = self.all_paths.iter().position(|p| p.as_ref() == path)?; + let rules = self.outputs.len(); + if (0..rules).any(|rule| { + self.positions[rule * slots + slot].is_some() && self.outputs[rule].literals.is_none() + }) { + return None; + } + let empty = First { + rules, + codes: Vec::new(), + batches: Vec::new(), + starts: vec![0], + }; + match self + .slot(&empty, slot, slots, &self.positions, &Bits::ones(rules))? + .0 + { + Dict::Scaled { .. } => Some(Scalar::Num), + Dict::Bool(_) => Some(Scalar::Bool), + Dict::Text { .. } => Some(Scalar::Text), + Dict::Any(_) => None, + } + } + + pub fn output_paths(&self) -> Arc<[Arc]> { + match &self.split { + Some(split) if !self.first_hit() => split.clone(), + _ => self.all_paths.clone(), + } + } + + pub fn value(&self, out: TableOut) -> Variable { + match out { + TableOut::Value(v) => v, + TableOut::Leaves(slots, values) => { + let object = Variable::empty_object(); + for (&slot, value) in slots.iter().zip(values) { + if let Some(path) = self.all_paths.get(slot) { + object.dot_insert(path, value); + } + } + object + } + } + } + + fn field_column<'b>( + runner: &mut LaneRunner, + bound: &'b Bound, + field: &LaneProgram, + failed: &mut [bool], + ) -> (Option>, Option) { + let direct = field.path().and_then(|path| match (bound.bind)(path) { + Binding::Column(index) => bound.columns.columns.get(index).map(|(_, c)| *c), + Binding::Absent => Some(LaneColumn::new(Values::Any(&[]))), + Binding::Row => None, + }); + match direct { + Some(column) => (Some(column), None), + None => { + let mut outs = Outs::take(); + bound.export(runner, field, None, &mut outs, |row, _, _| { + if let Some(f) = failed.get_mut(row) { + *f = true; + } + }); + (None, outs.first_mut().map(Array::from_output)) + } + } + } + + fn candidates( + &self, + runner: &mut LaneRunner, + bound: &Bound, + lazy: bool, + ) -> (Vec, Vec) { + if let Some(dispatch) = &self.dispatch { + return (self.dispatched(dispatch, runner, bound), Vec::new()); + } + let (rows, words) = (bound.rows(), self.words); + let scopes = bound.scopes(); + let mut all = self.open(rows); + let mut bits = Vec::new(); + let mut deferred = Vec::new(); + let fused = self.fused_truths(runner, bound); + for (index, column) in self.columns.iter().enumerate() { + match column { + Column::Field { + field, + cells, + empty, + } => { + let mut failed = vec![false; rows]; + let (direct, typed) = Self::field_column(runner, bound, field, &mut failed); + let column = direct.or_else(|| typed.as_ref().map(Array::column)); + if let (Some(truths), Some(view), true) = (&fused, direct, self.fuses(index)) { + cells.indexed_column(&view, rows, &mut bits); + for other in 0..cells.others() { + let (Some((_, rules)), Some(truth)) = ( + cells.other(other), + self.fused_at(index, other).and_then(|at| truths.get(at)), + ) else { + continue; + }; + Self::spread_rules(&mut bits, words, truth, rules, rows); + } + Bits::and(&mut all, &bits); + continue; + } + let values = |_: &Option| -> Vec { + (0..rows) + .map(|row| column.map_or(Variable::Null, |c| c.variable(row))) + .collect() + }; + let referenced = direct + .and(field.path()) + .filter(|reference| Self::referenced(bound, cells, reference)); + let peeled = cells.others() > 0 + && cells.peelable() + && column.is_some_and(|column| { + Self::peeled(runner, cells, &column, rows, &mut bits) + }); + match ( + lazy && !peeled, + cells.others() > 0 && !peeled, + column, + referenced, + ) { + _ if peeled => {} + (_, false, Some(column), _) => { + cells.indexed_column(&column, rows, &mut bits) + } + (true, true, Some(column), _) => { + cells.evaluate_indexed_column(&column, rows, &mut bits) + } + (false, true, Some(column), Some(reference)) => { + cells.indexed_column(&column, rows, &mut bits); + for other in 0..cells.others() { + let Some((_, rules)) = cells.other(other) else { + continue; + }; + let subset: Vec = (0..rows) + .filter(|&row| { + all[row * words..(row + 1) * words] + .iter() + .zip(rules) + .any(|(a, r)| a & r != 0) + }) + .collect(); + Self::referenced_truths( + runner, + bound, + cells, + other, + reference, + &subset, + |row, pass| { + if pass { + Bits::or( + &mut bits[row * words..(row + 1) * words], + rules, + ); + } + }, + ); + } + } + _ => { + let env = CellEnv { + scopes, + columns: &bound.columns, + bind: &*bound.bind, + }; + cells.evaluate_within( + runner, + &values(&typed), + &env, + Some(&all), + &mut bits, + ) + } + } + Bits::and(&mut all, &bits); + for row in (0..rows).filter(|&row| failed[row]) { + Bits::and(&mut all[row * words..(row + 1) * words], empty); + } + if lazy && cells.others() > 0 && !peeled { + deferred.push(Deferred::Field { + column: index, + reference: referenced.map(str::to_string), + values: match referenced { + Some(_) => Vec::new(), + None => values(&typed), + }, + scopes: None, + memo: vec![None; rows * cells.others()], + }); + } + } + Column::Plain { cells, empty, .. } if fused.is_some() && self.fuses(index) => { + let truths = fused.as_ref(); + let mut passing = match words { + 1 => vec![empty[0]; rows], + _ => { + let mut passing = vec![0u64; rows * words]; + passing + .chunks_exact_mut(words) + .for_each(|row| row.copy_from_slice(empty)); + passing + } + }; + for (cell, (_, rules)) in cells.iter().enumerate() { + let found = self + .fused_at(index, cell) + .and_then(|at| truths.and_then(|t| t.get(at))); + let Some(truth) = found else { + continue; + }; + Self::spread_rules(&mut passing, words, truth, rules, rows); + } + Bits::and(&mut all, &passing); + } + Column::Plain { + cells, + empty, + optimistic, + .. + } if lazy => { + for row in 0..rows { + all[row * words..(row + 1) * words] + .iter_mut() + .zip(empty.iter().zip(optimistic)) + .for_each(|(a, (e, o))| *a &= e | o); + } + deferred.push(Deferred::Plain { + column: index, + memo: vec![None; rows * cells.len()], + }); + } + Column::Plain { cells, empty, .. } => { + let mut passing = vec![0u64; rows * words]; + for row in 0..rows { + passing[row * words..(row + 1) * words].copy_from_slice(empty); + } + for (program, rules) in cells { + let Some(program) = program else { + continue; + }; + let subset: Vec = (0..rows) + .filter(|&row| { + all[row * words..(row + 1) * words] + .iter() + .zip(rules) + .any(|(a, r)| a & r != 0) + }) + .collect(); + if subset.is_empty() { + continue; + } + let within = (subset.len() < rows).then_some(subset.as_slice()); + Self::truths(runner, bound, program, within, |row, pass| { + if pass { + Bits::or(&mut passing[row * words..(row + 1) * words], rules); + } + }); + } + Bits::and(&mut all, &passing); + } + } + } + (all, deferred) + } + + const FUSED: usize = 64; + const THAWS: usize = 4096; + + fn next_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + } + + fn peeled( + runner: &mut LaneRunner, + cells: &CellSet, + column: &LaneColumn, + rows: usize, + out: &mut Vec, + ) -> bool { + let mut index: Vec = Vec::with_capacity(rows); + let mut values: Vec = Vec::new(); + let limit = rows / 2; + let text = matches!( + column.values, + Values::Text { .. } | Values::Utf8 { .. } | Values::Strs(_) + ); + match text { + true => { + let mut seen: ahash::HashMap<&[u8], u32> = ahash::HashMap::default(); + let mut null: Option = None; + for row in 0..rows { + let at = match column.valid(row).then(|| column.bytes(row)).flatten() { + Some(bytes) => match seen.get(bytes) { + Some(at) => *at, + None => { + let at = values.len() as u32; + values.push( + std::str::from_utf8(bytes) + .map_or(Variable::Null, |t| Variable::String(t.into())), + ); + seen.insert(bytes, at); + at + } + }, + None => *null.get_or_insert_with(|| { + values.push(Variable::Null); + (values.len() - 1) as u32 + }), + }; + if values.len() > limit { + return false; + } + index.push(at); + } + } + false => { + let mut seen: Vec = Vec::new(); + for row in 0..rows { + let value = column.variable(row); + if !matches!( + value, + Variable::Null + | Variable::Bool(_) + | Variable::Number(_) + | Variable::String(_) + ) { + return false; + } + let same = |a: &Variable, b: &Variable| match (a, b) { + (Variable::Number(x), Variable::Number(y)) => { + x.serialize() == y.serialize() + } + (x, y) => std::mem::discriminant(x) == std::mem::discriminant(y) && x == y, + }; + let at = match seen.iter().position(|v| same(v, &value)) { + Some(at) => at, + None => { + seen.push(value); + seen.len() - 1 + } + }; + if seen.len() > limit.min(64) { + return false; + } + index.push(at as u32); + } + values = seen; + } + } + let words = cells.words(); + let scopes = Bound::blank(values.len()); + let columns = zen_expression::lane::Columns::new(values.len()); + let env = CellEnv { + scopes: scopes.slice(), + columns: &columns, + bind: &|_| Binding::Row, + }; + let mut distinct = Vec::new(); + cells.evaluate_within(runner, &values, &env, None, &mut distinct); + out.clear(); + out.reserve(rows * words); + for at in &index { + let at = *at as usize * words; + out.extend_from_slice(&distinct[at..at + words]); + } + true + } + + fn verify( + &self, + runner: &mut LaneRunner, + bound: &Bound, + deferred: &mut [Deferred], + rule: usize, + lanes: &mut Vec, + ) { + for entry in deferred.iter_mut() { + if lanes.is_empty() { + return; + } + match entry { + Deferred::Field { + column, + reference, + values, + scopes, + memo, + } => { + let Some(Column::Field { cells, .. }) = self.columns.get(*column) else { + continue; + }; + let Some(other) = cells.owner(rule) else { + continue; + }; + let stride = cells.others(); + let unknown: Vec = lanes + .iter() + .copied() + .filter(|&row| memo[row * stride + other].is_none()) + .collect(); + match (unknown.is_empty(), reference) { + (true, _) => {} + (false, Some(reference)) => Self::referenced_truths( + runner, + bound, + cells, + other, + reference, + &unknown, + |row, pass| memo[row * stride + other] = Some(pass), + ), + (false, None) => { + let env = CellEnv { + scopes: bound.scopes(), + columns: &bound.columns, + bind: &*bound.bind, + }; + let scopes = + scopes.get_or_insert_with(|| CellSet::scopes(values, &env)); + cells.test(runner, other, scopes, &env, &unknown, |row, pass| { + memo[row * stride + other] = Some(pass == Some(true)) + }); + } + } + lanes.retain(|&row| memo[row * stride + other] == Some(true)); + } + Deferred::Plain { column, memo } => { + let Some(Column::Plain { cells, owners, .. }) = self.columns.get(*column) + else { + continue; + }; + let Some(cell) = owners.get(rule).copied().flatten() else { + continue; + }; + let Some((Some(program), _)) = cells.get(cell) else { + continue; + }; + let stride = cells.len(); + let unknown: Vec = lanes + .iter() + .copied() + .filter(|&row| memo[row * stride + cell].is_none()) + .collect(); + if !unknown.is_empty() { + let within = (unknown.len() < bound.rows()).then_some(unknown.as_slice()); + Self::truths(runner, bound, program, within, |row, pass| { + memo[row * stride + cell] = Some(pass) + }); + } + lanes.retain(|&row| memo[row * stride + cell] == Some(true)); + } + } + } + } + + fn chosen_values(&self, first: &First, row: usize, rule: usize) -> Vec { + let outputs = &self.outputs[rule]; + match ( + first.codes.get(row).and_then(|&code| first.computed(code)), + &outputs.literals, + ) { + (Some(_), _) => (0..outputs.paths.len()) + .map(|index| first.value(row, index)) + .collect(), + (None, Some(literals)) => literals.iter().map(Literal::variable).collect(), + (None, None) => Vec::new(), + } + } + + pub fn evaluate(&self, runner: &mut LaneRunner, bound: &Bound) -> Vec { + let rows = bound.rows(); + match self.hit { + Hit::First => { + let first = self.first(runner, bound); + (0..rows) + .map(|row| match first.chosen(row) { + None => TableOut::Value(Variable::Null), + Some(rule) => TableOut::Leaves( + self.outputs[rule].slots.clone(), + self.chosen_values(&first, row, rule), + ), + }) + .collect() + } + Hit::Collect => { + let words = self.words; + let (candidates, _) = self.candidates(runner, bound, false); + let mut result: Vec> = vec![Vec::new(); rows]; + let mut any = vec![0u64; words]; + candidates + .chunks_exact(words) + .for_each(|row| Bits::or(&mut any, row)); + for rule in Bits::rows(&any) { + let lanes: Vec = (0..rows) + .filter(|&r| Bits::get(&candidates[r * words..(r + 1) * words], rule)) + .collect(); + if lanes.is_empty() { + continue; + } + let outputs = &self.outputs[rule]; + match (outputs.paths.is_empty(), &outputs.literals) { + (true, _) => lanes + .iter() + .for_each(|&l| result[l].push(Variable::empty_object())), + (false, Some(literals)) => { + let values: Vec = + literals.iter().map(Literal::variable).collect(); + let template = + self.built(self.builder(rule, None).as_ref(), rule, None, &values); + lanes + .iter() + .for_each(|&l| result[l].push(template.deep_clone())); + } + (false, None) => { + let builder = self.builder(rule, None); + Self::run_rule( + runner, + outputs.full.as_ref(), + bound, + &lanes, + &mut |lane, values| { + if let Some(values) = values { + result[lane].push(self.built( + builder.as_ref(), + rule, + None, + &values, + )); + } + }, + ) + } + } + } + result + .into_iter() + .map(|items| TableOut::Value(Variable::from_array(items))) + .collect() + } + Hit::FirstCollect => { + let (candidates, deferred) = self.candidates(runner, bound, false); + let first = self.choose(runner, bound, &candidates, deferred); + let mut collected = + self.gather(runner, bound, &first, &candidates, &self.targets()); + (0..rows) + .map(|row| { + let output = match first.chosen(row) { + Some(rule) => self.built( + self.builder(rule, Some(false)).as_ref(), + rule, + Some(false), + &self.chosen_values(&first, row, rule), + ), + None => Variable::empty_object(), + }; + for (at, (lists, (_, path))) in + collected.iter_mut().zip(&self.collect_columns).enumerate() + { + if !self.collect_columns[..at].iter().any(|(_, p)| p == path) { + output.dot_insert( + path, + Variable::from_array(std::mem::take(&mut lists[row])), + ); + } + } + TableOut::Value(output) + }) + .collect() + } + } + } +} diff --git a/core/engine/src/compiled/table/profile.rs b/core/engine/src/compiled/table/profile.rs new file mode 100644 index 00000000..4770d515 --- /dev/null +++ b/core/engine/src/compiled/table/profile.rs @@ -0,0 +1,258 @@ +use crate::policy::blocks::DecisionTableIr; +use ahash::HashMap; +use std::sync::Arc; +use zen_expression::typed::{Hit as Typed, TableRule, TableSpec}; +use zen_types::decision::{DecisionTableContent, DecisionTableHitPolicy}; +use zen_types::path::DotPath; + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) enum Resolve { + Row, + Column, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) enum Rows { + Objects, + Fields, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) enum Empty { + Absent, + Fill, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) enum Errors { + Lenient, + Strict, +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) struct Profile { + pub resolve: Resolve, + pub rows: Rows, + pub empty: Empty, + pub errors: Errors, + pub trim: bool, +} + +impl Profile { + pub const GRAPH: Profile = Profile { + resolve: Resolve::Row, + rows: Rows::Objects, + empty: Empty::Absent, + errors: Errors::Lenient, + trim: true, + }; + + pub const POLICY: Profile = Profile { + resolve: Resolve::Column, + rows: Rows::Fields, + empty: Empty::Fill, + errors: Errors::Strict, + trim: true, + }; + + pub fn strict(&self) -> bool { + self.errors == Errors::Strict + } +} + +type Rule = HashMap, Arc>; + +pub(crate) struct InputIr<'t> { + pub id: &'t Arc, + pub field: Option<&'t str>, +} + +pub(crate) struct OutputIr<'t> { + pub id: &'t Arc, + pub path: &'t str, + pub collect: bool, +} + +pub(crate) struct TableIr<'t> { + pub profile: Profile, + pub collect: bool, + pub inputs: Vec>, + pub outputs: Vec>, + pub rules: Vec<&'t Rule>, +} + +impl<'t> TableIr<'t> { + const FILLED: usize = 64; + + pub fn graph(content: &'t DecisionTableContent) -> Self { + Self { + profile: Profile::GRAPH, + collect: matches!(content.hit_policy, DecisionTableHitPolicy::Collect), + inputs: content + .inputs + .iter() + .map(|input| InputIr { + id: &input.id, + field: input.field.as_deref(), + }) + .collect(), + outputs: content + .outputs + .iter() + .map(|output| { + let (path, collect) = output.write_path(); + OutputIr { + id: &output.id, + path, + collect, + } + }) + .collect(), + rules: content.rules.iter().collect(), + } + } + + pub fn policy(ir: &'t DecisionTableIr) -> Self { + Self { + profile: Profile::POLICY, + collect: ir.outputs.iter().any(|o| !o.field.is_empty()) + && ir + .outputs + .iter() + .filter(|o| !o.field.is_empty()) + .all(|o| o.collect), + inputs: ir + .inputs + .iter() + .map(|input| InputIr { + id: &input.id, + field: input.field.as_deref(), + }) + .collect(), + outputs: ir + .outputs + .iter() + .map(|o| OutputIr { + id: &o.id, + path: &o.field, + collect: o.collect, + }) + .collect(), + rules: ir.rules.iter().collect(), + } + } + + pub fn cell(&self, rule: &'t Rule, id: &str) -> Option<&'t str> { + rule.get(id) + .map(Arc::as_ref) + .filter(|cell| !cell.is_empty()) + } + + pub fn cells(&self, id: &str) -> Vec> { + self.rules.iter().map(|rule| self.cell(rule, id)).collect() + } + + pub fn used(&self, id: &str) -> bool { + self.rules.iter().any(|rule| self.cell(rule, id).is_some()) + } + + pub fn written(&self) -> impl Iterator> { + self.outputs.iter().filter(|o| !o.path.is_empty()) + } + + pub fn filled(&self) -> bool { + self.rules.len() <= Self::FILLED + && self.written().next().is_some() + && self.written().all(|o| { + !o.collect + && self + .rules + .iter() + .all(|rule| self.cell(rule, o.id).is_some()) + }) + && self.inputs.iter().all(|input| { + input.field.is_some_and(|f| !f.trim().is_empty()) || !self.used(input.id) + }) + } + + pub fn spec(&self) -> Option { + if self.collect || self.written().any(|o| o.collect) { + return None; + } + let strict = self.profile.strict(); + let mut paths: Vec<&str> = Vec::new(); + for output in self.written() { + if strict || !paths.contains(&output.path) { + paths.push(output.path); + } + } + let inputs: Vec<&InputIr> = self + .inputs + .iter() + .filter(|input| !strict || self.used(input.id)) + .collect(); + match strict { + true if !self.filled() => return None, + true => {} + false => { + let nested = paths + .iter() + .any(|a| paths.iter().any(|b| DotPath::under(b, a))); + let plain = paths.iter().all(|path| { + path.split('.') + .all(|segment| !segment.is_empty() && !segment.contains(['$', '[', ']'])) + }); + let blank = self + .inputs + .iter() + .any(|input| input.field.is_some_and(|field| field.trim().is_empty())) + || self.rules.iter().any(|rule| { + rule.values() + .any(|cell| !cell.is_empty() && cell.trim().is_empty()) + }); + if nested || !plain || blank { + return None; + } + } + } + let rules = self + .rules + .iter() + .map(|rule| TableRule { + cells: inputs + .iter() + .map(|input| self.cell(rule, input.id).map(str::to_string)) + .collect(), + values: match strict { + true => self + .written() + .map(|o| self.cell(rule, o.id).map(str::to_string)) + .collect(), + false => paths + .iter() + .map(|path| { + self.written() + .filter(|o| o.path == *path) + .filter_map(|o| self.cell(rule, o.id)) + .last() + .map(str::to_string) + }) + .collect(), + }, + }) + .collect(); + Some(TableSpec { + inputs: inputs + .iter() + .map(|input| input.field.map(str::to_string)) + .collect(), + outputs: paths.iter().map(|path| path.to_string()).collect(), + rules, + hit: match strict { + true => Typed::Strict, + false => Typed::Lenient, + }, + selector: !strict, + }) + } +} diff --git a/core/engine/src/compiled/table/strict.rs b/core/engine/src/compiled/table/strict.rs new file mode 100644 index 00000000..dd246cb2 --- /dev/null +++ b/core/engine/src/compiled/table/strict.rs @@ -0,0 +1,244 @@ +use super::{Column, Table, TableIr}; +use crate::compiled::leaf::{Bits, Leaf, Literal}; +use std::sync::Arc; +use zen_expression::lane::{Binding, CellEnv, CellSet, Columns, LaneProgram, LaneRunner}; +use zen_expression::Variable; + +pub(crate) struct Picked { + pub id: Arc, + pub field: Arc, + pub collect: bool, + pub cells: Vec>, + pub constants: Vec>, + filled: Vec, +} + +pub(crate) struct Matching { + pub all: Vec, + pub host: Vec, + bits: Vec, + count: usize, +} + +pub(super) struct Strict { + ordered: Vec, + outputs: Vec, +} + +impl Strict { + pub(super) fn cells(&self) -> impl Iterator { + self.outputs + .iter() + .flat_map(|output| output.cells.iter().flatten()) + } +} + +impl Picked { + pub fn fills(&self, rule: usize) -> bool { + Bits::get(&self.filled, rule) + } + + pub fn constants(&self) -> Option<(Vec, Vec)> { + let mut values = Vec::new(); + let mut remap = vec![-1i32; self.constants.len()]; + for (rule, constant) in self.constants.iter().enumerate() { + if !Bits::get(&self.filled, rule) { + continue; + } + remap[rule] = values.len() as i32; + values.push(constant.as_ref()?.variable()); + } + Some((values, remap)) + } +} + +impl Strict { + pub(super) fn compile(ir: &TableIr, ordered: Vec) -> Result { + let words = ir.rules.len().div_ceil(64).max(1); + let mut runner = LaneRunner::new(); + let mut outputs = Vec::new(); + let fields: Vec<&str> = ir.written().map(|column| column.path).collect(); + if fields.iter().enumerate().any(|(at, field)| { + fields[..at].contains(field) + && ir.written().nth(at).is_some_and(|column| !column.collect) + }) { + return Err("output field written by two scalar columns".into()); + } + for column in ir.written() { + let mut filled = vec![0u64; words]; + let mut cells = Vec::with_capacity(ir.rules.len()); + for (index, rule) in ir.rules.iter().enumerate() { + match ir.cell(rule, column.id) { + Some(source) => { + Bits::set(&mut filled, index, true); + cells.push(Some( + LaneProgram::standard(source).map_err(|e| e.to_string())?, + )); + } + None => cells.push(None), + } + } + let constants = cells + .iter() + .map(|cell| Literal::constant(&mut runner, cell.as_ref()?)) + .collect(); + outputs.push(Picked { + id: column.id.clone(), + field: Arc::from(column.path), + collect: column.collect, + cells, + constants, + filled, + }); + } + Ok(Strict { ordered, outputs }) + } +} + +impl Table { + pub fn words(&self) -> usize { + self.words + } + + pub fn fields(&self) -> impl Iterator { + self.columns.iter().filter_map(|column| match column { + Column::Field { field, .. } => Some(field.as_ref()), + Column::Plain { .. } => None, + }) + } + + pub fn picked(&self) -> &[Picked] { + self.strict.as_ref().map_or(&[], |strict| &strict.outputs) + } + + pub fn matching(&self, count: usize) -> Matching { + Matching { + all: self.open(count), + host: vec![false; count], + bits: Vec::new(), + count, + } + } + + pub fn matched( + &self, + runner: &mut LaneRunner, + input: usize, + leaf: &Leaf, + matching: &mut Matching, + ) { + let Matching { + all, + host, + bits, + count, + } = matching; + let count = *count; + let (Some(Column::Field { cells, .. }), Some(strict)) = + (self.columns.get(input), &self.strict) + else { + return; + }; + let words = self.words; + let column = leaf.column(); + if strict.ordered.get(input).copied().unwrap_or(false) { + for (local, hosted) in host.iter_mut().enumerate() { + if !column.valid(local) || column.number(local).is_none() { + *hosted = true; + } + } + } + cells.indexed_column(&column, count, bits); + let columns = Columns::new(count); + let env = CellEnv { + scopes: &[], + columns: &columns, + bind: &|_| Binding::Row, + }; + let mut scopes = None; + for other in 0..cells.others() { + let Some((_, rules)) = cells.other(other) else { + continue; + }; + let locals: Vec = (0..count) + .filter(|&local| { + all[local * words..(local + 1) * words] + .iter() + .zip(rules) + .any(|(a, r)| a & r != 0) + }) + .collect(); + if locals.is_empty() { + continue; + } + let scopes = scopes.get_or_insert_with(|| { + CellSet::scopes( + &(0..count).map(|local| leaf.get(local)).collect::>(), + &env, + ) + }); + cells.test( + runner, + other, + scopes, + &env, + &locals, + |local, pass| match pass { + None => host[local] = true, + Some(true) => Bits::or(&mut bits[local * words..(local + 1) * words], rules), + Some(false) => {} + }, + ); + } + Bits::and(all, bits); + } + + pub fn firsts<'t>(&'t self, matched: &'t [u64]) -> impl Iterator + 't { + self.picked() + .iter() + .map(move |output| match output.collect { + true => u32::MAX, + false => Self::next(matched, Some(&output.filled), 0) + .map_or(u32::MAX, |rule| rule as u32), + }) + } + + pub fn gathers(&self) -> bool { + self.picked().iter().any(|output| output.collect) + } + + pub fn used( + &self, + chosen: &[u32], + matched: Option<&[u64]>, + unit: usize, + ) -> Vec<(u32, Arc)> { + let outputs = self.picked(); + let words = self.words; + let mut used: Vec<(u32, usize)> = Vec::new(); + for (c, output) in outputs.iter().enumerate() { + match ( + output.collect, + matched.and_then(|m| m.get(unit * words..(unit + 1) * words)), + ) { + (true, Some(rules)) => used.extend( + Bits::rows(rules) + .filter(|&rule| Bits::get(&output.filled, rule)) + .map(|rule| (rule as u32, c)), + ), + (true, None) => {} + (false, _) => used.extend( + chosen + .get(unit * outputs.len() + c) + .copied() + .filter(|&rule| rule != u32::MAX) + .map(|rule| (rule, c)), + ), + } + } + used.sort(); + used.into_iter() + .map(|(rule, c)| (rule, outputs[c].id.clone())) + .collect() + } +} diff --git a/core/engine/src/decision.rs b/core/engine/src/decision.rs index ed0a4af6..6cff9d37 100644 --- a/core/engine/src/decision.rs +++ b/core/engine/src/decision.rs @@ -1,32 +1,49 @@ -use crate::decision_graph::graph::{DecisionGraph, DecisionGraphConfig, DecisionGraphResponse}; +use crate::compiled::traced::Traced; +use crate::compiled::{CompiledGraph, CompiledPlan, Invalid}; +use crate::decision_graph::graph::{DecisionGraph, DecisionGraphResponse}; +#[cfg(feature = "driver")] +use crate::decision_graph::walk::DecisionGraphConfig; use crate::engine::{EvaluationOptions, EvaluationSerializedOptions, EvaluationTraceKind}; use crate::loader::{DynamicLoader, NoopLoader}; use crate::model::GraphContent; use crate::nodes::custom::{DynamicCustomNode, NoopCustomNode}; use crate::nodes::function::http_handler::DynamicHttpHandler; use crate::nodes::NodeHandlerExtensions; +use crate::prepared::Prepared; use crate::{DecisionGraphValidationError, EvaluationError}; use serde_json::Value; use std::cell::OnceCell; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use zen_expression::variable::Variable; +type Planned = (Arc, Arc); + /// Represents a JDM decision which can be evaluated #[derive(Debug, Clone)] pub struct Decision { content: Arc, + prepared: OnceLock, + hosted: OnceLock, + #[cfg(feature = "driver")] + interpreted: bool, loader: DynamicLoader, adapter: DynamicCustomNode, http_handler: DynamicHttpHandler, + children: Arc, } impl From for Decision { fn from(value: GraphContent) -> Self { Self { content: value.into(), - loader: Arc::new(NoopLoader::default()), - adapter: Arc::new(NoopCustomNode::default()), + prepared: OnceLock::new(), + hosted: OnceLock::new(), + #[cfg(feature = "driver")] + interpreted: false, + loader: Arc::new(NoopLoader), + adapter: Arc::new(NoopCustomNode), http_handler: None, + children: Default::default(), } } } @@ -35,9 +52,14 @@ impl From> for Decision { fn from(value: Arc) -> Self { Self { content: value, - loader: Arc::new(NoopLoader::default()), - adapter: Arc::new(NoopCustomNode::default()), + prepared: OnceLock::new(), + hosted: OnceLock::new(), + #[cfg(feature = "driver")] + interpreted: false, + loader: Arc::new(NoopLoader), + adapter: Arc::new(NoopCustomNode), http_handler: None, + children: Default::default(), } } } @@ -58,6 +80,15 @@ impl Decision { self } + pub(crate) fn with_children(mut self, children: Arc) -> Self { + self.children = children; + self + } + + pub(crate) fn holds(&self, content: &Arc) -> bool { + Arc::ptr_eq(&self.content, content) + } + /// Evaluates a decision using an in-memory reference stored in struct pub async fn evaluate( &self, @@ -71,22 +102,175 @@ impl Decision { &self, context: Variable, options: EvaluationOptions, + ) -> Result> { + #[cfg(feature = "driver")] + if self.interpreted { + return self.evaluate_walker(context, options).await; + } + if options.trace { + return self.traced(context, options).await; + } + + let (compiled, content) = Self::compiled(self.single()).map_err(Invalid::evaluation)?; + let content = compiled.schemas(content, &self.loader).await; + compiled + .evaluate_one( + &content, + &self.extensions(&content), + options.max_depth, + context, + ) + .await + } + + /// Evaluates a decision for many contexts at once + pub async fn evaluate_batch( + &self, + contexts: &[Variable], + options: EvaluationOptions, + ) -> Vec>> { + let owned: Vec = contexts.iter().map(Variable::deep_clone).collect(); + if self.walked() || options.trace { + let mut responses = Vec::with_capacity(owned.len()); + for context in owned { + responses.push(self.evaluate_with_opts(context, options).await); + } + return responses; + } + + match Self::compiled(self.prepared()) { + Ok((compiled, content)) => { + let content = compiled.schemas(content, &self.loader).await; + compiled + .evaluate( + &content, + &self.extensions(&content), + options.max_depth, + &owned, + ) + .await + } + Err(invalid) => owned.iter().map(|_| Err(invalid.evaluation())).collect(), + } + } + + pub async fn evaluate_columns<'a>( + &self, + columns: &'a zen_expression::lane::Columns<'a>, + options: EvaluationOptions, + ) -> crate::compiled::ColumnarOutput<'a> { + match (self.walked(), Self::compiled(self.prepared())) { + (false, Ok((compiled, content))) => { + let content = compiled.schemas(content, &self.loader).await; + compiled + .evaluate_columns( + &content, + &self.extensions(&content), + options.max_depth, + columns, + ) + .await + } + _ => { + let contexts: Vec = + (0..columns.rows).map(|row| columns.row(row)).collect(); + let options = EvaluationOptions { + trace: false, + ..options + }; + let results = self.evaluate_batch(&contexts, options).await; + crate::compiled::ColumnarOutput::from_results(results) + } + } + } + + async fn traced( + &self, + context: Variable, + options: EvaluationOptions, + ) -> Result> { + let (compiled, content) = Self::compiled(self.tracing()).map_err(Invalid::evaluation)?; + let content = compiled.schemas(content, &self.loader).await; + let extensions = self.extensions(&content); + let traced = Traced { + graph: compiled, + content: &content, + extensions: &extensions, + max_depth: options.max_depth, + iteration: 0, + parent: None, + }; + traced.evaluate(context).await + } + + fn prepared(&self) -> (&Arc, &CompiledPlan) { + if let Some(plan) = self.content.compiled_plan.as_deref() { + return (&self.content, plan); + } + let (content, plan) = self.prepared.get_or_init(|| { + let mut owned = (*self.content).clone(); + let plan = owned.prepare(); + (Arc::new(owned), plan) + }); + (content, plan) + } + + fn hosted(&self) -> (&Arc, &CompiledPlan) { + let (content, plan) = self.hosted.get_or_init(|| { + let (content, plan) = self.content.hosted(); + (Arc::new(content), plan) + }); + (content, plan) + } + + fn single(&self) -> (&Arc, &CompiledPlan) { + match (self.prepared.get(), self.hosted.get()) { + (None, None) if self.content.compiled_plan.is_none() => self.hosted(), + _ => self.prepared(), + } + } + + fn tracing(&self) -> (&Arc, &CompiledPlan) { + match self.prepared.get() { + None if self.content.compiled_plan.is_none() => self.hosted(), + _ => self.prepared(), + } + } + + fn compiled<'c>( + (content, plan): (&'c Arc, &'c CompiledPlan), + ) -> Result<(&'c CompiledGraph, &'c Arc), &'c Invalid> { + plan.graph().map(|compiled| (compiled, content)) + } + + #[allow(clippy::arc_with_non_send_sync)] + fn extensions(&self, content: &GraphContent) -> NodeHandlerExtensions { + NodeHandlerExtensions { + function_runtime: Default::default(), + loader: self.loader.clone(), + custom_node: self.adapter.clone(), + http_handler: self.http_handler.clone(), + #[cfg(feature = "driver")] + compiled_cache: content.compiled_cache.clone(), + dt_indexes: content.dt_indexes.clone(), + stripped_functions: content.stripped_functions.clone(), + validator_cache: Arc::new(OnceCell::from(content.validator_cache.clone())), + prepared: self.children.clone(), + } + } + + #[cfg(feature = "driver")] + async fn evaluate_walker( + &self, + context: Variable, + options: EvaluationOptions, ) -> Result> { let mut decision_graph = DecisionGraph::try_new(DecisionGraphConfig { content: self.content.clone(), max_depth: options.max_depth, trace: options.trace, iteration: 0, - extensions: NodeHandlerExtensions { - loader: self.loader.clone(), - custom_node: self.adapter.clone(), - http_handler: self.http_handler.clone(), - compiled_cache: self.content.compiled_cache.clone(), - dt_indexes: self.content.dt_indexes.clone(), - stripped_functions: self.content.stripped_functions.clone(), - validator_cache: Arc::new(OnceCell::from(self.content.validator_cache.clone())), - ..Default::default() - }, + extensions: self.extensions(&self.content), })?; let response = decision_graph.evaluate(context).await?; @@ -109,30 +293,53 @@ impl Decision { ) .await; - match response { - Ok(ok) => Ok(ok - .serialize_with_mode(serde_json::value::Serializer, options.trace) - .unwrap_or_default()), - Err(err) => Err(err - .serialize_with_mode(serde_json::value::Serializer, options.trace) - .unwrap_or_default()), - } + DecisionGraphResponse::serialized(response, options.trace) } pub fn validate(&self) -> Result<(), DecisionGraphValidationError> { - let decision_graph = DecisionGraph::try_new(DecisionGraphConfig { - content: self.content.clone(), - max_depth: 1, - trace: false, - iteration: 0, - extensions: Default::default(), - })?; - - decision_graph.validate() + DecisionGraph::validate_graph(&DecisionGraph::build_graph(&self.content)?) } - pub fn compile(&mut self) -> () { + fn walked(&self) -> bool { + #[cfg(feature = "driver")] + if self.interpreted { + return true; + } + false + } + + #[cfg(feature = "driver")] + #[doc(hidden)] + pub fn interpreted(&self) -> Self { + Self { + interpreted: true, + ..self.clone() + } + } + + #[doc(hidden)] + pub fn plan_verdict( + &self, + columns: &zen_expression::lane::Columns, + ) -> Option> { + let (compiled, _) = Self::compiled(self.prepared()).ok()?; + Some(compiled.plan_verdict(columns)) + } + + pub(crate) fn degraded(&self) -> Option, Arc)>> { + let (compiled, _) = Self::compiled(self.prepared()).ok()?; + Some(compiled.degraded()) + } + + #[doc(hidden)] + pub fn compiled_verdict(&self) -> Option> { + self.content.compiled_verdict() + } + + pub fn compile(&mut self) { let cm = Arc::make_mut(&mut self.content); cm.compile(); + self.prepared = OnceLock::new(); + self.hosted = OnceLock::new(); } } diff --git a/core/engine/src/decision_graph/error.rs b/core/engine/src/decision_graph/error.rs index 7981117e..365881b4 100644 --- a/core/engine/src/decision_graph/error.rs +++ b/core/engine/src/decision_graph/error.rs @@ -2,7 +2,7 @@ use serde::ser::SerializeMap; use serde::{Serialize, Serializer}; use thiserror::Error; -#[derive(Debug, Error)] +#[derive(Debug, Clone, Error)] pub enum DecisionGraphValidationError { #[error("Invalid input node count: {0}")] InvalidInputCount(u32), diff --git a/core/engine/src/decision_graph/graph.rs b/core/engine/src/decision_graph/graph.rs index 69c5ef36..08ba6487 100644 --- a/core/engine/src/decision_graph/graph.rs +++ b/core/engine/src/decision_graph/graph.rs @@ -1,67 +1,32 @@ -use crate::decision_graph::cleaner::VariableCleaner; -use crate::decision_graph::schema_dict; -use crate::decision_graph::tracer::NodeTracer; -use crate::decision_graph::walker::{GraphWalker, NodeData, StableDiDecisionGraph}; +use crate::decision_graph::walker::StableDiDecisionGraph; use crate::engine::EvaluationTraceKind; use crate::model::{DecisionNodeKind, GraphContent}; -use crate::nodes::custom::CustomNodeHandler; -use crate::nodes::decision::DecisionNodeHandler; -use crate::nodes::decision_table::DecisionTableNodeHandler; -use crate::nodes::expression::ExpressionNodeHandler; -use crate::nodes::function::FunctionNodeHandler; -use crate::nodes::input::InputNodeHandler; -use crate::nodes::output::OutputNodeHandler; -use crate::nodes::transform_attributes::TransformAttributesExecution; use crate::nodes::{ - NodeContext, NodeContextBase, NodeContextConfig, NodeDataType, NodeHandler, - NodeHandlerExtensions, NodeResponse, NodeResult, TraceDataType, + NodeContext, NodeContextBase, NodeDataType, NodeHandler, NodeResult, TraceDataType, }; +use crate::workspace::types::EvaluationResult; use crate::{DecisionGraphTrace, DecisionGraphValidationError, EvaluationError}; use ahash::{HashMap, HashMapExt}; use petgraph::algo::is_cyclic_directed; -use petgraph::matrix_graph::Zero; use serde::ser::SerializeMap; use serde::{Serialize, Serializer}; -use std::cell::RefCell; -use std::ops::Deref; use std::sync::Arc; -use std::time::Instant; use zen_expression::variable::{ToVariable, Variable}; -use zen_types::decision::{DecisionNode, InputNodeContent, OutputNodeContent}; #[derive(Debug)] pub struct DecisionGraph { - initial_graph: StableDiDecisionGraph, - graph: StableDiDecisionGraph, - config: DecisionGraphConfig, - parent_nodes: Option, -} - -#[derive(Debug)] -pub struct DecisionGraphConfig { - pub content: Arc, - pub trace: bool, - pub iteration: u8, - pub max_depth: u8, - pub extensions: NodeHandlerExtensions, + #[cfg(feature = "driver")] + pub(super) initial_graph: StableDiDecisionGraph, + #[cfg(feature = "driver")] + pub(super) graph: StableDiDecisionGraph, + #[cfg(feature = "driver")] + pub(super) config: crate::decision_graph::walk::DecisionGraphConfig, + #[cfg(feature = "driver")] + pub(super) parent_nodes: Option, } impl DecisionGraph { - pub fn try_new(config: DecisionGraphConfig) -> Result { - let graph = Self::build_graph(config.content.deref())?; - Ok(Self { - initial_graph: graph.clone(), - graph, - config, - parent_nodes: None, - }) - } - - pub(crate) fn set_parent_nodes(&mut self, nodes: Option) { - self.parent_nodes = nodes; - } - - fn build_graph( + pub(crate) fn build_graph( content: &GraphContent, ) -> Result { let mut graph = StableDiDecisionGraph::new(); @@ -89,13 +54,10 @@ impl DecisionGraph { Ok(graph) } - pub(crate) fn reset_graph(&mut self) { - self.graph = self.initial_graph.clone(); - } - - pub fn validate(&self) -> Result<(), DecisionGraphValidationError> { - let input_count = self - .graph + pub(crate) fn validate_graph( + graph: &StableDiDecisionGraph, + ) -> Result<(), DecisionGraphValidationError> { + let input_count = graph .node_weights() .filter(|w| matches!(w.kind, DecisionNodeKind::InputNode { .. })) .count(); @@ -105,218 +67,12 @@ impl DecisionGraph { )); } - if is_cyclic_directed(&self.graph) { + if is_cyclic_directed(graph) { return Err(DecisionGraphValidationError::CyclicGraph); } Ok(()) } - - async fn validation_schema( - &self, - node_id: &str, - schema: Option<&serde_json::Value>, - ) -> Result, u64)>, String> { - let Some(schema) = schema else { - return Ok(None); - }; - if let Some(resolved) = &self.config.content.resolved_schemas { - return Ok(resolved.get(node_id).cloned()); - } - if !schema_dict::schema_references_dictionary(schema) { - return Ok(None); - } - - let dictionaries = schema_dict::load_import_dictionaries( - self.config.extensions.loader(), - &self.config.content.imports, - ) - .await?; - schema_dict::resolve_schema(schema, &dictionaries) - .map(|resolved| Some((Arc::new(resolved.0), resolved.1))) - } - - fn build_node_context( - &self, - node: &DecisionNode, - input: Variable, - nodes: Option, - ) -> NodeContextBase { - NodeContextBase { - id: node.id.clone(), - name: node.name.clone(), - input, - nodes, - extensions: self.config.extensions.clone(), - iteration: self.config.iteration, - trace: match self.config.trace { - true => Some(RefCell::new(Variable::Null)), - false => None, - }, - config: NodeContextConfig { - max_depth: self.config.max_depth, - trace: self.config.trace, - ..Default::default() - }, - } - } - - pub async fn evaluate( - &mut self, - context: Variable, - ) -> Result> { - let root_start = Instant::now(); - - self.validate()?; - if self.config.iteration >= self.config.max_depth { - return Err(Box::new(EvaluationError::DepthLimitExceeded)); - } - - let mut walker = GraphWalker::new(&self.graph); - let mut tracer = NodeTracer::new(self.config.trace); - - while let Some(nid) = walker.next(&mut self.graph, tracer.trace_callback()) { - if let Some(_) = walker.get_node_data(nid) { - continue; - } - - let node = &self.graph[nid]; - let start = self.config.trace.then(Instant::now); - let (input, input_trace) = walker.incoming_node_data(&self.graph, nid); - let mut base_ctx = self.build_node_context(node.deref(), input, walker.nodes_context()); - - let node_execution = match &node.kind { - DecisionNodeKind::InputNode { content } => { - base_ctx.input = context.clone(); - match self - .validation_schema(&node.id, content.schema.as_deref()) - .await - { - Err(message) => base_ctx.error(message), - Ok(None) => handle_node(base_ctx, content.clone(), InputNodeHandler).await, - Ok(Some((schema, salt))) => { - base_ctx.config.validation_salt = salt; - let resolved = InputNodeContent { - schema: Some(schema), - }; - handle_node(base_ctx, resolved, InputNodeHandler).await - } - } - } - DecisionNodeKind::OutputNode { content } => { - match self - .validation_schema(&node.id, content.schema.as_deref()) - .await - { - Err(message) => base_ctx.error(message), - Ok(None) => handle_node(base_ctx, content.clone(), OutputNodeHandler).await, - Ok(Some((schema, salt))) => { - base_ctx.config.validation_salt = salt; - let resolved = OutputNodeContent { - schema: Some(schema), - }; - handle_node(base_ctx, resolved, OutputNodeHandler).await - } - } - } - DecisionNodeKind::SwitchNode { .. } => Ok(NodeResponse { - output: input_trace.clone(), - trace_data: None, - }), - DecisionNodeKind::FunctionNode { content } => { - handle_node(base_ctx, content.clone(), FunctionNodeHandler).await - } - DecisionNodeKind::DecisionNode { content } => { - handle_node(base_ctx, content.clone(), DecisionNodeHandler::default()).await - } - DecisionNodeKind::DecisionTableNode { content } => { - handle_node(base_ctx, content.clone(), DecisionTableNodeHandler).await - } - DecisionNodeKind::ExpressionNode { content } => { - handle_node(base_ctx, content.clone(), ExpressionNodeHandler).await - } - DecisionNodeKind::CustomNode { content } => { - handle_node(base_ctx, content.clone(), CustomNodeHandler).await - } - }; - - tracer.record_execution( - node.deref(), - input_trace, - &node_execution, - start.map(|s| s.elapsed()).unwrap_or_default(), - ); - - let output = match node_execution { - Ok(ok) => ok.output, - Err(err) => { - let trace = tracer.into_traces(); - if let Some(t) = &trace { - let mut cleaner = VariableCleaner::new(); - t.values().for_each(|v| { - cleaner.clean(&v.input); - cleaner.clean(&v.output); - if let Some(td) = &v.trace_data { - cleaner.clean(td); - } - }) - } - - return Err(Box::new(EvaluationError::NodeError { - node_id: err.node_id, - source: err.source, - trace: trace.map(|t| t.to_variable()), - })); - } - }; - - let nodes_view = match (&node.kind, &self.parent_nodes) { - (DecisionNodeKind::InputNode { .. }, Some(parent_nodes)) => { - let view = output.depth_clone(1); - view.dot_insert(Variable::nodes_key().as_ref(), parent_nodes.clone()); - Some(view) - } - _ => None, - }; - - walker.set_node_data( - nid, - NodeData { - name: zen_types::symbol::Symbol::from(node.name.deref()), - data: output, - nodes_view, - }, - ); - - // Terminate once Output node is reached - if matches!(node.kind, DecisionNodeKind::OutputNode { .. }) { - break; - } - } - - let result = walker.ending_variables(&self.graph); - let trace = tracer.into_traces(); - - if self.config.iteration.is_zero() { - let mut cleaner = VariableCleaner::new(); - cleaner.clean(&result); - if let Some(t) = &trace { - t.values().for_each(|v| { - cleaner.clean(&v.input); - cleaner.clean(&v.output); - if let Some(td) = &v.trace_data { - cleaner.clean(td); - } - }) - } - } - - Ok(DecisionGraphResponse { - performance: format!("{:.1?}", root_start.elapsed()), - result, - trace: trace.map(EvaluationTrace::Graph), - }) - } } #[derive(Debug, Clone, Serialize)] @@ -351,7 +107,31 @@ pub struct DecisionGraphResponse { pub trace: Option, } +impl From for DecisionGraphResponse { + fn from(result: EvaluationResult) -> Self { + Self { + performance: format!("{:.1?}", result.duration), + result: result.output, + trace: result.trace.map(EvaluationTrace::Policy), + } + } +} + impl DecisionGraphResponse { + pub(crate) fn serialized( + response: Result>, + mode: EvaluationTraceKind, + ) -> Result { + match response { + Ok(ok) => Ok(ok + .serialize_with_mode(serde_json::value::Serializer, mode) + .unwrap_or_default()), + Err(err) => Err(err + .serialize_with_mode(serde_json::value::Serializer, mode) + .unwrap_or_default()), + } + } + pub fn serialize_with_mode( &self, serializer: S, @@ -389,37 +169,21 @@ impl DecisionGraphResponse { } } -async fn handle_node( - base_ctx: NodeContextBase, - content: NodeData, - handler: NodeHandlerType, -) -> NodeResult -where - TraceData: TraceDataType, - NodeData: NodeDataType, - NodeHandlerType: NodeHandler, -{ - let ctx = NodeContext::::from_base(base_ctx.clone(), content); - if let Some(transform_attributes) = handler.transform_attributes(&ctx) { - return transform_attributes - .run_with(base_ctx, move |input, has_more| { - let handler = handler.clone(); - let mut new_ctx = ctx.clone(); - new_ctx.input = input; - - async move { - match has_more { - false => handler.handle(new_ctx).await, - true => { - let result = handler.handle(new_ctx.clone()).await; - handler.after_transform_attributes(&new_ctx).await?; - result - } - } - } - }) - .await; +impl DecisionGraph { + pub(crate) async fn handle( + base_ctx: NodeContextBase, + content: NodeData, + handler: NodeHandlerType, + ) -> NodeResult + where + TraceData: TraceDataType, + NodeData: NodeDataType, + NodeHandlerType: NodeHandler, + { + handler + .handle(NodeContext::::from_base( + base_ctx, content, + )) + .await } - - handler.handle(ctx).await } diff --git a/core/engine/src/decision_graph/mod.rs b/core/engine/src/decision_graph/mod.rs index 47183fdb..ffdb5763 100644 --- a/core/engine/src/decision_graph/mod.rs +++ b/core/engine/src/decision_graph/mod.rs @@ -2,8 +2,10 @@ pub(crate) mod cleaner; mod error; pub(crate) mod graph; pub(crate) mod schema_dict; -mod tracer; -mod walker; +pub(crate) mod tracer; +#[cfg(feature = "driver")] +pub(crate) mod walk; +pub(crate) mod walker; pub use error::DecisionGraphValidationError; pub use graph::{DecisionGraphResponse, EvaluationTrace}; diff --git a/core/engine/src/decision_graph/tracer.rs b/core/engine/src/decision_graph/tracer.rs index 2f7c2f99..6aeae61c 100644 --- a/core/engine/src/decision_graph/tracer.rs +++ b/core/engine/src/decision_graph/tracer.rs @@ -1,8 +1,10 @@ use crate::nodes::NodeResult; use ahash::HashMap; use serde::{Deserialize, Serialize}; +use std::rc::Rc; use std::sync::Arc; use zen_expression::variable::ToVariable; +use zen_types::decision::SwitchStatement; use zen_types::decision::{DecisionNode, DecisionNodeKind}; use zen_types::variable::Variable; @@ -94,3 +96,45 @@ pub struct DecisionGraphTrace { fn null_variable() -> Variable { Variable::Null } + +#[derive(Debug, Clone, ToVariable)] +pub struct ExpressionNodeTraceItem { + pub(crate) result: Variable, +} + +#[derive(Debug, Clone, Serialize, ToVariable)] +pub struct DecisionTableRowTrace { + pub(crate) index: usize, + pub(crate) reference_map: HashMap, Variable>, + pub(crate) rule: HashMap, Rc>, +} + +#[derive(Debug, Clone, Serialize, ToVariable)] +#[serde(untagged)] +pub enum DecisionTableNodeTrace { + FirstHit(DecisionTableRowTrace), + Collect(Vec), +} + +impl Default for DecisionTableNodeTrace { + fn default() -> Self { + DecisionTableNodeTrace::Collect(Default::default()) + } +} + +#[derive(ToVariable)] +pub(crate) struct SwitchStatementTrace { + pub(crate) statements: Vec, +} + +#[derive(ToVariable, Clone)] +#[serde(rename_all = "camelCase")] +pub(crate) struct SwitchStatementTraceRow { + pub id: Arc, +} + +impl From for SwitchStatementTraceRow { + fn from(value: SwitchStatement) -> Self { + Self { id: value.id } + } +} diff --git a/core/engine/src/decision_graph/walk.rs b/core/engine/src/decision_graph/walk.rs new file mode 100644 index 00000000..e5d04564 --- /dev/null +++ b/core/engine/src/decision_graph/walk.rs @@ -0,0 +1,414 @@ +use crate::decision_graph::cleaner::VariableCleaner; +use crate::decision_graph::graph::{DecisionGraph, DecisionGraphResponse, EvaluationTrace}; +use crate::decision_graph::tracer::{NodeTracer, SwitchStatementTrace, SwitchStatementTraceRow}; +use crate::decision_graph::walker::{GraphWalker, NodeData, StableDiDecisionGraph, WalkStep}; +use crate::model::GraphContent; +use crate::model::{DecisionNodeKind, SwitchStatement, SwitchStatementHitPolicy}; +use crate::nodes::custom::CustomNodeHandler; +use crate::nodes::decision::DecisionNodeHandler; +use crate::nodes::decision_table::DecisionTableNodeHandler; +use crate::nodes::expression::ExpressionNodeHandler; +use crate::nodes::function::FunctionNodeHandler; +use crate::nodes::input::InputNodeHandler; +use crate::nodes::output::OutputNodeHandler; +use crate::nodes::transform_attributes::TransformAttributesExecution; +use crate::nodes::NodeHandlerExtensions; +use crate::nodes::{ + NodeContext, NodeContextBase, NodeContextConfig, NodeDataType, NodeHandler, NodeResponse, + NodeResult, TraceDataType, +}; +use crate::DecisionGraphValidationError; +use crate::{DecisionGraphTrace, EvaluationError}; +use petgraph::matrix_graph::Zero; +use petgraph::prelude::NodeIndex; +use petgraph::Incoming; +use std::cell::RefCell; +use std::ops::Deref; +use std::sync::Arc; +use std::time::Instant; +use zen_expression::variable::{ToVariable, Variable}; +use zen_expression::Isolate; +use zen_types::decision::{DecisionNode, InputNodeContent, OutputNodeContent}; + +impl GraphWalker { + pub fn get_node_data(&self, node_id: NodeIndex) -> Option { + Some(self.node_data.get(&node_id)?.data.clone()) + } + + pub fn ending_variables(&self, g: &StableDiDecisionGraph) -> Variable { + Self::merge_ending( + self.ending_nodes(g) + .into_iter() + .filter_map(|nid| self.node_data.get(&nid).map(|nd| &nd.data)), + ) + } + + pub fn get_all_node_data(&self) -> Variable { + let node_values = self + .node_data + .iter() + .filter_map(|(_, nd)| { + let value = nd.nodes_view.clone().unwrap_or_else(|| nd.data.clone()); + Some((nd.name.clone(), value)) + }) + .collect(); + + Variable::from_object(node_values) + } + + pub fn nodes_context(&self) -> Option { + self.nodes_in_context.then(|| self.get_all_node_data()) + } + + pub fn incoming_node_data( + &self, + g: &StableDiDecisionGraph, + node_id: NodeIndex, + ) -> (Variable, Variable) { + let value = self.merge_node_data(g.neighbors_directed(node_id, Incoming)); + + (value.clone(), value) + } + + pub fn merge_node_data(&self, iter: I) -> Variable + where + I: Iterator, + { + Self::merge_values(iter.filter_map(|nid| self.node_data.get(&nid).map(|nd| &nd.data))) + } + + pub fn next( + &mut self, + g: &mut StableDiDecisionGraph, + mut on_trace: Option, + ) -> Option { + let start = Instant::now(); + let step = self.next_with(g, |walker, g, nid, node, content| { + let (input, input_trace) = walker.incoming_node_data(g, nid); + let mut isolate = Isolate::with_environment(input); + if let Some(nodes) = walker.nodes_context() { + isolate.set_local(Variable::nodes_key(), nodes); + } + + let mut statement_iter = content.statements.iter(); + let valid_statements: Vec = match content.hit_policy { + SwitchStatementHitPolicy::First => statement_iter + .find(|&s| Self::switch_statement_evaluate(&mut isolate, &s)) + .into_iter() + .cloned() + .map(SwitchStatementTraceRow::from) + .collect(), + SwitchStatementHitPolicy::Collect => statement_iter + .filter(|&s| Self::switch_statement_evaluate(&mut isolate, &s)) + .cloned() + .map(SwitchStatementTraceRow::from) + .collect(), + }; + + if let Some(on_trace) = &mut on_trace { + let output = input_trace.depth_clone(1); + + on_trace(DecisionGraphTrace { + id: node.id.clone(), + name: node.name.clone(), + input: input_trace, + output, + order: 0, + performance: Some(Arc::from(format!("{:.1?}", start.elapsed()))), + trace_data: Some( + SwitchStatementTrace { + statements: valid_statements.clone(), + } + .to_variable(), + ), + }); + } + + Some(valid_statements.into_iter().map(|s| s.id).collect()) + }); + + match step { + WalkStep::Node(nid) => Some(nid), + WalkStep::Done | WalkStep::Pending => None, + } + } + + fn switch_statement_evaluate( + isolate: &mut Isolate, + switch_statement: &SwitchStatement, + ) -> bool { + if switch_statement.condition.is_empty() { + return true; + } + + isolate + .run_standard(switch_statement.condition.deref()) + .map_or(false, |v| v.as_bool().unwrap_or(false)) + } +} + +#[derive(Debug)] +pub struct DecisionGraphConfig { + pub content: Arc, + pub trace: bool, + pub iteration: u8, + pub max_depth: u8, + pub extensions: NodeHandlerExtensions, +} + +impl DecisionGraph { + pub fn try_new(config: DecisionGraphConfig) -> Result { + let graph = Self::build_graph(config.content.deref())?; + Ok(Self { + initial_graph: graph.clone(), + graph, + config, + parent_nodes: None, + }) + } + + pub fn validate(&self) -> Result<(), DecisionGraphValidationError> { + Self::validate_graph(&self.graph) + } + + pub(crate) fn set_parent_nodes(&mut self, nodes: Option) { + self.parent_nodes = nodes; + } + + pub(crate) fn reset_graph(&mut self) { + self.graph = self.initial_graph.clone(); + } + + fn build_node_context( + &self, + node: &DecisionNode, + input: Variable, + nodes: Option, + ) -> NodeContextBase { + NodeContextBase { + id: node.id.clone(), + name: node.name.clone(), + input, + nodes, + extensions: self.config.extensions.clone(), + iteration: self.config.iteration, + trace: match self.config.trace { + true => Some(RefCell::new(Variable::Null)), + false => None, + }, + config: NodeContextConfig { + max_depth: self.config.max_depth, + trace: self.config.trace, + ..Default::default() + }, + } + } + + pub async fn evaluate( + &mut self, + context: Variable, + ) -> Result> { + let root_start = Instant::now(); + + self.validate()?; + if self.config.iteration >= self.config.max_depth { + return Err(Box::new(EvaluationError::DepthLimitExceeded)); + } + + let mut walker = GraphWalker::new(&self.graph); + let mut tracer = NodeTracer::new(self.config.trace); + + while let Some(nid) = walker.next(&mut self.graph, tracer.trace_callback()) { + if let Some(_) = walker.get_node_data(nid) { + continue; + } + + let node = &self.graph[nid]; + let start = self.config.trace.then(Instant::now); + let (input, input_trace) = walker.incoming_node_data(&self.graph, nid); + let mut base_ctx = self.build_node_context(node.deref(), input, walker.nodes_context()); + + let node_execution = match &node.kind { + DecisionNodeKind::InputNode { content } => { + base_ctx.input = context.clone(); + match self + .config + .content + .validation_schema( + self.config.extensions.loader(), + &node.id, + content.schema.as_deref(), + ) + .await + { + Err(message) => base_ctx.error(message), + Ok(None) => { + Self::handle_node(base_ctx, content.clone(), InputNodeHandler).await + } + Ok(Some((schema, salt))) => { + base_ctx.config.validation_salt = salt; + let resolved = InputNodeContent { + schema: Some(schema), + }; + Self::handle_node(base_ctx, resolved, InputNodeHandler).await + } + } + } + DecisionNodeKind::OutputNode { content } => { + match self + .config + .content + .validation_schema( + self.config.extensions.loader(), + &node.id, + content.schema.as_deref(), + ) + .await + { + Err(message) => base_ctx.error(message), + Ok(None) => { + Self::handle_node(base_ctx, content.clone(), OutputNodeHandler).await + } + Ok(Some((schema, salt))) => { + base_ctx.config.validation_salt = salt; + let resolved = OutputNodeContent { + schema: Some(schema), + }; + Self::handle_node(base_ctx, resolved, OutputNodeHandler).await + } + } + } + DecisionNodeKind::SwitchNode { .. } => Ok(NodeResponse { + output: input_trace.clone(), + trace_data: None, + }), + DecisionNodeKind::FunctionNode { content } => { + Self::handle_node(base_ctx, content.clone(), FunctionNodeHandler).await + } + DecisionNodeKind::DecisionNode { content } => { + Self::handle_node(base_ctx, content.clone(), DecisionNodeHandler::default()) + .await + } + DecisionNodeKind::DecisionTableNode { content } => { + Self::handle_node(base_ctx, content.clone(), DecisionTableNodeHandler).await + } + DecisionNodeKind::ExpressionNode { content } => { + Self::handle_node(base_ctx, content.clone(), ExpressionNodeHandler).await + } + DecisionNodeKind::CustomNode { content } => { + Self::handle_node(base_ctx, content.clone(), CustomNodeHandler).await + } + }; + + tracer.record_execution( + node.deref(), + input_trace, + &node_execution, + start.map(|s| s.elapsed()).unwrap_or_default(), + ); + + let output = match node_execution { + Ok(ok) => ok.output, + Err(err) => { + let trace = tracer.into_traces(); + if let Some(t) = &trace { + let mut cleaner = VariableCleaner::new(); + t.values().for_each(|v| { + cleaner.clean(&v.input); + cleaner.clean(&v.output); + if let Some(td) = &v.trace_data { + cleaner.clean(td); + } + }) + } + + return Err(Box::new(EvaluationError::NodeError { + node_id: err.node_id, + source: err.source, + trace: trace.map(|t| t.to_variable()), + })); + } + }; + + let nodes_view = match (&node.kind, &self.parent_nodes) { + (DecisionNodeKind::InputNode { .. }, Some(parent_nodes)) => { + let view = output.depth_clone(1); + view.dot_insert(Variable::nodes_key().as_ref(), parent_nodes.clone()); + Some(view) + } + _ => None, + }; + + walker.set_node_data( + nid, + NodeData { + name: zen_types::symbol::Symbol::from(node.name.deref()), + data: output, + nodes_view, + }, + ); + + if matches!(node.kind, DecisionNodeKind::OutputNode { .. }) { + break; + } + } + + let result = walker.ending_variables(&self.graph); + let trace = tracer.into_traces(); + + if self.config.iteration.is_zero() { + let mut cleaner = VariableCleaner::new(); + cleaner.clean(&result); + if let Some(t) = &trace { + t.values().for_each(|v| { + cleaner.clean(&v.input); + cleaner.clean(&v.output); + if let Some(td) = &v.trace_data { + cleaner.clean(td); + } + }) + } + } + + Ok(DecisionGraphResponse { + performance: format!("{:.1?}", root_start.elapsed()), + result, + trace: trace.map(EvaluationTrace::Graph), + }) + } + + pub(crate) async fn handle_node( + base_ctx: NodeContextBase, + content: NodeData, + handler: NodeHandlerType, + ) -> NodeResult + where + TraceData: TraceDataType, + NodeData: NodeDataType, + NodeHandlerType: NodeHandler, + { + let ctx = NodeContext::::from_base(base_ctx.clone(), content); + if let Some(transform_attributes) = handler.transform_attributes(&ctx) { + return transform_attributes + .run_with(base_ctx, move |input, has_more| { + let handler = handler.clone(); + let mut new_ctx = ctx.clone(); + new_ctx.input = input; + + async move { + match has_more { + false => handler.handle(new_ctx).await, + true => { + let result = handler.handle(new_ctx.clone()).await; + handler.after_transform_attributes(&new_ctx).await?; + result + } + } + } + }) + .await; + } + + handler.handle(ctx).await + } +} diff --git a/core/engine/src/decision_graph/walker.rs b/core/engine/src/decision_graph/walker.rs index b9ff9f89..1f99dd64 100644 --- a/core/engine/src/decision_graph/walker.rs +++ b/core/engine/src/decision_graph/walker.rs @@ -6,34 +6,55 @@ use petgraph::prelude::{EdgeIndex, NodeIndex, StableDiGraph}; use petgraph::visit::{EdgeRef, IntoNodeIdentifiers, VisitMap, Visitable}; use petgraph::{Incoming, Outgoing}; use std::ops::Deref; +#[cfg(feature = "driver")] use std::sync::atomic::Ordering; use std::sync::Arc; -use std::time::Instant; +#[cfg(feature = "driver")] use crate::config::ZEN_CONFIG; -use crate::model::{ - DecisionEdge, DecisionNode, DecisionNodeKind, SwitchStatement, SwitchStatementHitPolicy, -}; -use crate::DecisionGraphTrace; -use zen_expression::variable::{ToVariable, Variable}; -use zen_expression::Isolate; +use crate::model::{DecisionEdge, DecisionNode, DecisionNodeKind, SwitchNodeContent}; +use zen_expression::variable::Variable; pub(crate) type StableDiDecisionGraph = StableDiGraph, Arc>; pub(crate) struct NodeData { + #[cfg(feature = "driver")] pub name: zen_types::symbol::Symbol, + #[cfg(feature = "driver")] pub data: Variable, + #[cfg(feature = "driver")] pub nodes_view: Option, } +impl NodeData { + #[cfg_attr(not(feature = "driver"), allow(unused_variables))] + pub(crate) fn placeholder(name: &str) -> Self { + Self { + #[cfg(feature = "driver")] + name: zen_types::symbol::Symbol::from(name), + #[cfg(feature = "driver")] + data: Variable::Null, + #[cfg(feature = "driver")] + nodes_view: None, + } + } +} + +pub(crate) enum WalkStep { + Node(NodeIndex), + Pending, + Done, +} + pub(crate) struct GraphWalker { iter: usize, - node_data: HashMap, + pub(super) node_data: HashMap, ordered: FixedBitSet, to_visit: Vec, visited_switch_nodes: Vec, - nodes_in_context: bool, + #[cfg(feature = "driver")] + pub(super) nodes_in_context: bool, } const ITER_MAX: usize = 1_000; @@ -62,6 +83,7 @@ impl GraphWalker { visited_switch_nodes: Default::default(), iter: 0, + #[cfg(feature = "driver")] nodes_in_context: ZEN_CONFIG.nodes_in_context.load(Ordering::Relaxed), } } @@ -74,80 +96,39 @@ impl GraphWalker { self.iter += 1; } - pub fn get_node_data(&self, node_id: NodeIndex) -> Option { - Some(self.node_data.get(&node_id)?.data.clone()) - } - - pub fn ending_variables(&self, g: &StableDiDecisionGraph) -> Variable { - g.node_indices() - .filter(|nid| { - self.ordered.is_visited(nid) - && g.neighbors_directed(*nid, Outgoing).count().is_zero() - }) - .fold(Variable::empty_object(), |mut acc, curr| { - match self.node_data.get(&curr) { - None => acc, - Some(nd) => acc.merge(&nd.data), - } - }) - } - - pub fn get_all_node_data(&self) -> Variable { - let node_values = self - .node_data - .iter() - .filter_map(|(_, nd)| { - let value = nd.nodes_view.clone().unwrap_or_else(|| nd.data.clone()); - Some((nd.name.clone(), value)) - }) - .collect(); - - Variable::from_object(node_values) + pub(crate) fn merge_ending<'a>(values: impl Iterator) -> Variable { + values.fold(Variable::empty_object(), |mut acc, data| acc.merge(data)) } pub fn set_node_data(&mut self, node_id: NodeIndex, value: NodeData) { self.node_data.insert(node_id, value); } - pub fn nodes_context(&self) -> Option { - self.nodes_in_context.then(|| self.get_all_node_data()) - } - - pub fn incoming_node_data( - &self, - g: &StableDiDecisionGraph, - node_id: NodeIndex, - ) -> (Variable, Variable) { - let value = self.merge_node_data(g.neighbors_directed(node_id, Incoming)); - - (value.clone(), value) - } - - pub fn merge_node_data(&self, iter: I) -> Variable - where - I: Iterator, - { - let mut incoming = iter.filter_map(|nid| self.node_data.get(&nid)); + pub(crate) fn merge_values<'a>(mut incoming: impl Iterator) -> Variable { let Some(first) = incoming.next() else { return Variable::empty_object(); }; - let head = match &first.data { - Variable::Object(_) | Variable::Array(_) => first.data.clone(), + let head = match first { + Variable::Object(_) | Variable::Array(_) => first.clone(), _ => Variable::empty_object(), }; - incoming.fold(head, |mut prev, nd| prev.merge_clone(&nd.data)) + incoming.fold(head, |mut prev, data| prev.merge_clone(data)) } - pub fn next( - &mut self, - g: &mut StableDiDecisionGraph, - mut on_trace: Option, - ) -> Option { - let start = Instant::now(); + pub(crate) fn next_with(&mut self, g: &mut StableDiDecisionGraph, mut switch: S) -> WalkStep + where + S: FnMut( + &Self, + &StableDiDecisionGraph, + NodeIndex, + &DecisionNode, + &SwitchNodeContent, + ) -> Option>>, + { if self.iter >= ITER_MAX { - return None; + return WalkStep::Done; } // Take an unvisited element and find which of its neighbors are next while let Some(nid) = self.to_visit.pop() { @@ -164,64 +145,29 @@ impl GraphWalker { self.ordered.visit(nid); - let decision_node = g.node_weight(nid)?.clone(); + let Some(decision_node) = g.node_weight(nid).cloned() else { + return WalkStep::Done; + }; if let DecisionNodeKind::SwitchNode { content } = &decision_node.kind { if !self.visited_switch_nodes.contains(&nid) { - let (input, input_trace) = self.incoming_node_data(g, nid); - let mut isolate = Isolate::with_environment(input); - if let Some(nodes) = self.nodes_context() { - isolate.set_local(Variable::nodes_key(), nodes); - } - - let mut statement_iter = content.statements.iter(); - let valid_statements: Vec = match content.hit_policy { - SwitchStatementHitPolicy::First => statement_iter - .find(|&s| switch_statement_evaluate(&mut isolate, &s)) - .into_iter() - .cloned() - .map(SwitchStatementTraceRow::from) - .collect(), - SwitchStatementHitPolicy::Collect => statement_iter - .filter(|&s| switch_statement_evaluate(&mut isolate, &s)) - .cloned() - .map(SwitchStatementTraceRow::from) - .collect(), + let Some(valid_statements) = switch(self, g, nid, &decision_node, content) + else { + return WalkStep::Pending; }; - if let Some(on_trace) = &mut on_trace { - let output = input_trace.depth_clone(1); - - on_trace(DecisionGraphTrace { - id: decision_node.id.clone(), - name: decision_node.name.clone(), - input: input_trace, - output, - order: 0, - performance: Some(Arc::from(format!("{:.1?}", start.elapsed()))), - trace_data: Some( - SwitchStatementTrace { - statements: valid_statements.clone(), - } - .to_variable(), - ), - }); - } - // Remove all non-valid edges let edges_to_remove: Vec = g .edges_directed(nid, Outgoing) .filter(|edge| { edge.weight().source_handle.as_ref().map_or(true, |handle| { - !valid_statements - .iter() - .any(|s| s.id.deref() == handle.deref()) + !valid_statements.iter().any(|s| s.deref() == handle.deref()) }) }) .map(|edge| edge.id()) .collect(); let edges_remove_count = edges_to_remove.len(); for edge in edges_to_remove { - remove_edge_recursive(g, edge); + Self::remove_edge_recursive(g, edge); } self.visited_switch_nodes.push(nid); @@ -236,10 +182,24 @@ impl GraphWalker { let successors = g.neighbors_directed(nid, Outgoing); self.to_visit.extend(successors); - return Some(nid); + return WalkStep::Node(nid); } - None + WalkStep::Done + } + + pub(crate) fn has_node_data(&self, node_id: NodeIndex) -> bool { + self.node_data.contains_key(&node_id) + } + + pub(crate) fn ending_nodes(&self, g: &StableDiDecisionGraph) -> Vec { + g.node_indices() + .filter(|nid| { + self.ordered.is_visited(nid) + && g.neighbors_directed(*nid, Outgoing).count().is_zero() + && self.node_data.contains_key(nid) + }) + .collect() } fn all_dependencies_resolved(&self, g: &StableDiDecisionGraph, nid: NodeIndex) -> bool { @@ -256,57 +216,30 @@ impl GraphWalker { .filter(|dep| !self.ordered.is_visited(dep)) .collect() } -} -fn switch_statement_evaluate(isolate: &mut Isolate, switch_statement: &SwitchStatement) -> bool { - if switch_statement.condition.is_empty() { - return true; - } + fn remove_edge_recursive(g: &mut StableDiDecisionGraph, edge_id: EdgeIndex) { + let Some((source_nid, target_nid)) = g.edge_endpoints(edge_id) else { + return; + }; - isolate - .run_standard(switch_statement.condition.deref()) - .map_or(false, |v| v.as_bool().unwrap_or(false)) -} + g.remove_edge(edge_id); -fn remove_edge_recursive(g: &mut StableDiDecisionGraph, edge_id: EdgeIndex) { - let Some((source_nid, target_nid)) = g.edge_endpoints(edge_id) else { - return; - }; + for (nid, direction) in [(target_nid, Incoming), (source_nid, Outgoing)] { + let count = g.edges_directed(nid, direction).count(); + if count.is_zero() { + let edge_ids: Vec = g + .edges_directed(nid, direction.opposite()) + .map(|edge| edge.id()) + .collect(); - g.remove_edge(edge_id); + edge_ids.iter().for_each(|&edge_id| { + Self::remove_edge_recursive(g, edge_id); + }); - for (nid, direction) in [(target_nid, Incoming), (source_nid, Outgoing)] { - let count = g.edges_directed(nid, direction).count(); - if count.is_zero() { - let edge_ids: Vec = g - .edges_directed(nid, direction.opposite()) - .map(|edge| edge.id()) - .collect(); - - edge_ids.iter().for_each(|&edge_id| { - remove_edge_recursive(g, edge_id); - }); - - if g.edges(nid).count().is_zero() { - g.remove_node(nid); + if g.edges(nid).count().is_zero() { + g.remove_node(nid); + } } } } } - -#[derive(ToVariable)] -struct SwitchStatementTrace { - statements: Vec, -} - -#[derive(ToVariable, Clone)] -#[serde(rename_all = "camelCase")] -struct SwitchStatementTraceRow { - pub id: Arc, -} - -impl From for SwitchStatementTraceRow { - fn from(value: SwitchStatement) -> Self { - Self { id: value.id } - } -} diff --git a/core/engine/src/diagnostics.rs b/core/engine/src/diagnostics.rs new file mode 100644 index 00000000..c30ce45d --- /dev/null +++ b/core/engine/src/diagnostics.rs @@ -0,0 +1,47 @@ +use crate::compiled::ColumnarOutput; +use crate::Decision; +use zen_expression::lane::Columns; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Paths { + pub typed: usize, + pub laned: usize, + pub hosted: usize, +} + +pub fn paths(output: &ColumnarOutput) -> Paths { + output.paths +} + +pub fn census() -> Vec<(String, u64, u64, u128)> { + crate::compiled::CompiledGraph::census() +} + +pub fn plan_verdict(decision: &Decision, columns: &Columns) -> Option> { + decision.plan_verdict(columns) +} + +pub fn compiled_verdict(decision: &Decision) -> Option> { + decision.compiled_verdict() +} + +pub fn degraded(decision: &Decision) -> Option> { + decision.degraded().map(|nodes| { + nodes + .into_iter() + .map(|(node, why)| (node.to_string(), why.to_string())) + .collect() + }) +} + +pub fn set_census(on: bool) { + crate::compiled::switches::SWITCHES.set_census(on); +} + +pub fn set_typed(on: bool) { + crate::compiled::switches::SWITCHES.set_typed(on); +} + +pub fn compilations() -> usize { + crate::compiled::switches::SWITCHES.compilations() +} diff --git a/core/engine/src/engine.rs b/core/engine/src/engine.rs index bfc19405..003db084 100644 --- a/core/engine/src/engine.rs +++ b/core/engine/src/engine.rs @@ -1,11 +1,13 @@ use crate::decision::Decision; -use crate::decision_graph::graph::{DecisionGraphResponse, EvaluationTrace}; +use crate::decision_graph::graph::DecisionGraphResponse; use crate::error::ContentKindError; use crate::loader::{ClosureLoader, DynamicLoader, LoaderResponse, LoaderResult, NoopLoader}; use crate::model::{DecisionContent, GraphContent}; use crate::nodes::custom::{DynamicCustomNode, NoopCustomNode}; use crate::nodes::function::http_handler::DynamicHttpHandler; use crate::policy::runtime::{CompiledEntry, CompiledSet}; +use crate::prepared::{Decisions, Policies, Prepared}; +use crate::workspace::types::EvaluateRequest; use crate::{CompileFailure, EvaluationError}; use arc_swap::ArcSwapOption; use serde_json::Value; @@ -22,6 +24,9 @@ pub struct DecisionEngine { adapter: DynamicCustomNode, http_handler: DynamicHttpHandler, compiled: Arc>, + prepared: Arc, + decisions: Arc, + policies: Arc, } impl Debug for DecisionEngine { @@ -79,12 +84,12 @@ impl EvaluationTraceKind { pub fn serialize_trace(&self, trace: &Variable) -> Value { match self { EvaluationTraceKind::None => Value::Null, - EvaluationTraceKind::Default => serde_json::to_value(&trace).unwrap_or_default(), + EvaluationTraceKind::Default => serde_json::to_value(trace).unwrap_or_default(), EvaluationTraceKind::String => { Value::String(serde_json::to_string(&trace).unwrap_or_default()) } EvaluationTraceKind::Reference => { - serde_json::to_value(&trace.serialize_ref()).unwrap_or_default() + serde_json::to_value(trace.serialize_ref()).unwrap_or_default() } EvaluationTraceKind::ReferenceString => { Value::String(serde_json::to_string(&trace.serialize_ref()).unwrap_or_default()) @@ -96,10 +101,13 @@ impl EvaluationTraceKind { impl Default for DecisionEngine { fn default() -> Self { Self { - loader: Arc::new(NoopLoader::default()), - adapter: Arc::new(NoopCustomNode::default()), + loader: Arc::new(NoopLoader), + adapter: Arc::new(NoopCustomNode), http_handler: None, compiled: Arc::new(ArcSwapOption::empty()), + prepared: Default::default(), + decisions: Default::default(), + policies: Default::default(), } } } @@ -111,24 +119,36 @@ impl DecisionEngine { adapter, http_handler: None, compiled: Arc::new(ArcSwapOption::empty()), + prepared: Default::default(), + decisions: Default::default(), + policies: Default::default(), } } pub fn with_adapter(mut self, adapter: DynamicCustomNode) -> Self { self.adapter = adapter; self.compiled = Arc::new(ArcSwapOption::empty()); + self.prepared = Default::default(); + self.decisions = Default::default(); + self.policies = Default::default(); self } pub fn with_loader(mut self, loader: DynamicLoader) -> Self { self.loader = loader; self.compiled = Arc::new(ArcSwapOption::empty()); + self.prepared = Default::default(); + self.decisions = Default::default(); + self.policies = Default::default(); self } pub fn with_http_handler(mut self, http_handler: DynamicHttpHandler) -> Self { self.http_handler = http_handler; self.compiled = Arc::new(ArcSwapOption::empty()); + self.prepared = Default::default(); + self.decisions = Default::default(); + self.policies = Default::default(); self } @@ -139,6 +159,9 @@ impl DecisionEngine { { self.loader = Arc::new(ClosureLoader::new(loader)); self.compiled = Arc::new(ArcSwapOption::empty()); + self.prepared = Default::default(); + self.decisions = Default::default(); + self.policies = Default::default(); self } @@ -184,43 +207,108 @@ impl DecisionEngine { where K: AsRef, { - let key_str = key.as_ref(); + self.evaluated(key.as_ref(), context, options).await? + } + + async fn evaluated( + &self, + key: &str, + context: Variable, + options: EvaluationOptions, + ) -> LoaderResult>> { if let Some(set) = self.compiled.load_full() { - if let Some(entry) = set.get(key_str) { - return match entry { + if let Some(entry) = set.get(key) { + return Ok(match entry { CompiledEntry::Policy(artifact) => artifact - .evaluate_entry(key_str, context, options.trace) - .map(|r| DecisionGraphResponse { - performance: format!("{:.1?}", r.duration), - result: r.output, - trace: r.trace.map(EvaluationTrace::Policy), - }) + .evaluate_entry(key, context, options.trace) + .map(DecisionGraphResponse::from) .map_err(|e| Box::new(EvaluationError::Policy(e))), CompiledEntry::Graph(graph) => { - self.decision_from_graph(graph) + self.decision(key, &graph) .evaluate_with_opts(context, options) .await } - }; + }); } } - let content = self.loader.load(key_str).await?; - match content.as_ref() { - DecisionContent::Graph(_) => { - let decision = self.decision_from_graph_arc(content); - decision.evaluate_with_opts(context, options).await + let content = self.loader.load(key).await?; + Ok(match content.as_ref() { + DecisionContent::Graph(graph) => { + self.decision(key, graph) + .evaluate_with_opts(context, options) + .await } DecisionContent::Policy(_) => { crate::policy::runtime::evaluate_policy( + &self.policies, &self.loader, - key_str, + key, content, context, options, ) .await } + }) + } + + pub async fn evaluate_batch( + &self, + key: K, + contexts: &[Variable], + options: EvaluationOptions, + ) -> Vec>> + where + K: AsRef, + { + let key_str = key.as_ref(); + if let Some(set) = self.compiled.load_full() { + if let Some(entry) = set.get(key_str) { + return match entry { + CompiledEntry::Policy(artifact) => { + let requests: Vec = contexts + .iter() + .map(|context| EvaluateRequest { + policy_path: Arc::from(key_str), + input: context.clone(), + goals: Vec::new(), + trace: options.trace, + }) + .collect(); + artifact + .evaluate_batch(&requests) + .into_iter() + .map(|result| { + result + .map(DecisionGraphResponse::from) + .map_err(|e| Box::new(EvaluationError::Policy(e))) + }) + .collect() + } + CompiledEntry::Graph(graph) => { + self.decision(key_str, &graph) + .evaluate_batch(contexts, options) + .await + } + }; + } } + if let Ok(content) = self.loader.load(key_str).await { + if let DecisionContent::Graph(graph) = content.as_ref() { + return self + .decision(key_str, graph) + .evaluate_batch(contexts, options) + .await; + } + } + let mut results = Vec::with_capacity(contexts.len()); + for context in contexts { + results.push( + self.evaluate_with_opts(key_str, context.clone(), options) + .await, + ); + } + results } pub async fn evaluate_serialized( @@ -232,92 +320,14 @@ impl DecisionEngine { where K: AsRef, { - let key_str = key.as_ref(); - if let Some(set) = self.compiled.load_full() { - if let Some(entry) = set.get(key_str) { - match entry { - CompiledEntry::Policy(artifact) => { - let trace_mode = options.trace; - let trace = options.trace != EvaluationTraceKind::None; - return match artifact.evaluate_entry(key_str, context, trace) { - Ok(r) => { - let response = DecisionGraphResponse { - performance: format!("{:.1?}", r.duration), - result: r.output, - trace: r.trace.map(EvaluationTrace::Policy), - }; - Ok(response - .serialize_with_mode(serde_json::value::Serializer, trace_mode) - .unwrap_or_default()) - } - Err(e) => { - let err = EvaluationError::Policy(e); - Err(err - .serialize_with_mode(serde_json::value::Serializer, trace_mode) - .unwrap_or_default()) - } - }; - } - CompiledEntry::Graph(graph) => { - return self - .decision_from_graph(graph) - .evaluate_serialized(context, options) - .await; - } - } - } - } - let content = self - .loader - .load(key_str) - .await - .map_err(|err| Value::String(err.to_string()))?; - - match content.as_ref() { - DecisionContent::Graph(_) => { - let decision = self.decision_from_graph_arc(content); - decision.evaluate_serialized(context, options).await - } - DecisionContent::Policy(_) => { - let inner_opts = EvaluationOptions { - trace: options.trace != EvaluationTraceKind::None, - max_depth: options.max_depth, - }; - let trace_mode = options.trace; - let response = crate::policy::runtime::evaluate_policy( - &self.loader, - key_str, - content, - context, - inner_opts, - ) - .await; - match response { - Ok(ok) => Ok(ok - .serialize_with_mode(serde_json::value::Serializer, trace_mode) - .unwrap_or_default()), - Err(err) => Err(err - .serialize_with_mode(serde_json::value::Serializer, trace_mode) - .unwrap_or_default()), - } - } - } - } - - fn decision_from_graph_arc(&self, content: Arc) -> Decision { - let graph: Arc = match Arc::try_unwrap(content) { - Ok(DecisionContent::Graph(g)) => g, - Err(arc) => match arc.as_ref() { - DecisionContent::Graph(g) => g.clone(), - DecisionContent::Policy(_) => { - panic!("decision_from_graph_arc called with Policy variant") - } - }, - Ok(DecisionContent::Policy(_)) => { - panic!("decision_from_graph_arc called with Policy variant") - } + let opts = EvaluationOptions { + trace: options.trace != EvaluationTraceKind::None, + max_depth: options.max_depth, }; - self.decision_from_graph(graph) + match self.evaluated(key.as_ref(), context, opts).await { + Ok(response) => DecisionGraphResponse::serialized(response, options.trace), + Err(err) => Err(Value::String(err.to_string())), + } } fn decision_from_graph(&self, graph: Arc) -> Decision { @@ -325,6 +335,12 @@ impl DecisionEngine { .with_loader(self.loader.clone()) .with_adapter(self.adapter.clone()) .with_http_handler(self.http_handler.clone()) + .with_children(self.prepared.clone()) + } + + fn decision(&self, key: &str, graph: &Arc) -> Arc { + self.decisions + .get(key, graph, || self.decision_from_graph(graph.clone())) } /// Creates a decision from DecisionContent, exists for easier binding creation @@ -333,7 +349,7 @@ impl DecisionEngine { content: Arc, ) -> Result { match content.as_ref() { - DecisionContent::Graph(_) => Ok(self.decision_from_graph_arc(content)), + DecisionContent::Graph(graph) => Ok(self.decision_from_graph(graph.clone())), DecisionContent::Policy(_) => Err(ContentKindError { expected: "graph", got: "policy", diff --git a/core/engine/src/error.rs b/core/engine/src/error.rs index cc4ae2f7..438d05ef 100644 --- a/core/engine/src/error.rs +++ b/core/engine/src/error.rs @@ -78,6 +78,13 @@ pub enum EvaluationError { } impl EvaluationError { + pub fn policy(&self) -> Option<&crate::policy::EvaluationError> { + match self { + EvaluationError::Policy(error) => Some(error), + _ => None, + } + } + pub fn serialize_with_mode( &self, serializer: S, diff --git a/core/engine/src/lib.rs b/core/engine/src/lib.rs index c66d9d3b..0911b510 100644 --- a/core/engine/src/lib.rs +++ b/core/engine/src/lib.rs @@ -121,8 +121,17 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used)] #![allow(clippy::module_inception)] +#![cfg_attr( + not(feature = "driver"), + deny(clippy::disallowed_types, clippy::disallowed_methods) +)] +#![cfg_attr( + feature = "driver", + allow(clippy::disallowed_types, clippy::disallowed_methods) +)] mod analysis; +mod compiled; mod config; mod decision; mod decision_graph; @@ -132,10 +141,19 @@ pub mod loader; pub mod model; pub mod nodes; pub mod policy; +mod prepared; pub mod workspace; +#[doc(hidden)] +pub mod diagnostics; + +pub mod columns { + pub use zen_expression::lane::{Column, Columns, Dictionary, Values}; +} + pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION"); +pub use compiled::{ColumnarOutput, OutputColumn, RecordsView}; pub use config::ZEN_CONFIG; pub use decision::Decision; pub use decision_graph::{ diff --git a/core/engine/src/loader/cached.rs b/core/engine/src/loader/cached.rs index 1542ad6f..aea7afa3 100644 --- a/core/engine/src/loader/cached.rs +++ b/core/engine/src/loader/cached.rs @@ -25,7 +25,7 @@ fn compiled(content: Arc) -> Arc { let DecisionContent::Graph(graph) = content.as_ref() else { return content; }; - if graph.compiled_cache.is_some() { + if graph.is_compiled() { return content; } @@ -34,18 +34,29 @@ fn compiled(content: Arc) -> Arc { Arc::new(DecisionContent::Graph(Arc::new(owned))) } -async fn prepared(loader: &DynamicLoader, content: Arc) -> Arc { +async fn prepared( + loader: &DynamicLoader, + content: Arc, +) -> (Arc, Arc) { let DecisionContent::Graph(graph) = content.as_ref() else { - return content; + return (content.clone(), content); }; - if graph.compiled_cache.is_some() && graph.resolved_schemas.is_some() { - return content; + if graph.is_compiled() && graph.resolved_schemas.is_some() && !graph.schemas_failed() { + return (content.clone(), content); } let mut owned = (**graph).clone(); owned.compile(); - let _ = owned.resolve_schemas(loader).await; - Arc::new(DecisionContent::Graph(Arc::new(owned))) + let resolved = owned.resolve_schemas(loader).await; + let kept = match resolved { + Ok(()) => None, + Err(_) => Some(Arc::new(DecisionContent::Graph(Arc::new( + owned.without_failed_schemas(), + )))), + }; + let current = Arc::new(DecisionContent::Graph(Arc::new(owned))); + let kept = kept.unwrap_or_else(|| current.clone()); + (current, kept) } impl DecisionLoader for CachedLoader { @@ -65,13 +76,13 @@ impl DecisionLoader for CachedLoader { None => self.loader.load(key).await?, }; - let decision_content = prepared(&self.loader, loaded).await; + let (decision_content, kept) = prepared(&self.loader, loaded).await; let unchanged = cached .as_ref() - .is_some_and(|content| Arc::ptr_eq(content, &decision_content)); + .is_some_and(|content| Arc::ptr_eq(content, &kept)); if !unchanged { if let Ok(mut cache) = self.cache.write() { - cache.insert(key.to_string(), decision_content.clone()); + cache.insert(key.to_string(), kept); } } Ok(decision_content) diff --git a/core/engine/src/model/decision_content.rs b/core/engine/src/model/decision_content.rs index b920ca2f..49c6b698 100644 --- a/core/engine/src/model/decision_content.rs +++ b/core/engine/src/model/decision_content.rs @@ -1,3 +1,4 @@ +use crate::compiled::CompiledPlan; use crate::decision_graph::schema_dict; use crate::loader::DynamicLoader; use crate::nodes::decision_table::index::TableIndex; @@ -7,7 +8,8 @@ use crate::policy::PolicyDocument; use ahash::{HashMap, HashMapExt}; use serde::{Deserialize, Deserializer, Serialize}; use std::sync::Arc; -use zen_expression::{ExpressionKind, Isolate, OpcodeCache}; + +type ResolvedSchemas = HashMap, (Arc, u64)>; use zen_types::decision::{DecisionEdge, DecisionNode, DecisionNodeKind, FunctionNodeContent}; #[derive(Clone, Debug, Serialize)] @@ -98,7 +100,7 @@ impl From> for PolicyContent { } } -#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, Default)] +#[derive(Clone, Debug, Deserialize, Serialize, Default)] #[serde(rename_all = "camelCase")] pub struct GraphContent { pub nodes: Vec>, @@ -108,19 +110,32 @@ pub struct GraphContent { pub imports: Vec>, #[serde(skip)] - pub compiled_cache: Option>, + #[cfg(feature = "driver")] + pub compiled_cache: Option>, #[serde(skip)] pub stripped_functions: Option, Arc>>>, #[serde(skip)] - pub resolved_schemas: Option, (Arc, u64)>>>, + pub resolved_schemas: Option>, #[serde(skip)] pub(crate) validator_cache: ValidatorCache, #[serde(skip)] pub(crate) dt_indexes: Option, TableIndex>>>, + + #[serde(skip)] + pub(crate) compiled_plan: Option>, + + #[serde(skip)] + pub(crate) schema_failures: Option, Arc>>>, +} + +impl PartialEq for GraphContent { + fn eq(&self, other: &Self) -> bool { + self.nodes == other.nodes && self.edges == other.edges && self.imports == other.imports + } } #[derive(Clone, Debug, Deserialize, Serialize)] @@ -128,78 +143,60 @@ pub struct GraphContent { pub struct PolicyContent(pub Arc); impl GraphContent { - pub fn compile(&mut self) { + pub fn compiled_verdict(&self) -> Option> { + self.compiled_plan.as_deref().map(CompiledPlan::verdict) + } +} + +impl GraphContent { + pub(crate) fn prepare(&mut self) -> Arc { self.compile_functions(); self.build_dt_indexes(); - if self.compiled_cache.is_some() { - return; - } - - let mut sources: Vec<(Arc, ExpressionKind)> = Vec::new(); - for node in &self.nodes { - match &node.kind { - DecisionNodeKind::ExpressionNode { content } => { - for expr in content.expressions.iter() { - if !expr.key.is_empty() && !expr.value.is_empty() { - sources.push((expr.value.clone(), ExpressionKind::Standard)); - } - } - } - DecisionNodeKind::DecisionTableNode { content } => { - for rule in content.rules.iter() { - for input in content.inputs.iter() { - let Some(rule_value) = rule.get(&input.id) else { - continue; - }; - - let kind = if input.field.is_some() { - ExpressionKind::Unary - } else { - ExpressionKind::Standard - }; - - sources.push((rule_value.clone(), kind)); - } - - for output in content.outputs.iter() { - let Some(rule_value) = rule.get(&output.id) else { - continue; - }; - - sources.push((rule_value.clone(), ExpressionKind::Standard)); - } - } - } - _ => {} + match &self.compiled_plan { + Some(plan) => plan.clone(), + None => { + let plan = Arc::new(CompiledPlan::compile(self)); + self.compiled_plan = Some(plan.clone()); + plan } } + } - let mut cache: OpcodeCache = OpcodeCache::new(); - let mut isolate = Isolate::new(); + pub(crate) fn hosted(&self) -> (GraphContent, Arc) { + let mut owned = self.clone(); + let plan = Arc::new(CompiledPlan::hosted(&owned)); + owned.compiled_plan = Some(plan.clone()); + (owned, plan) + } - for (source, kind) in &sources { - let map = match kind { - ExpressionKind::Standard => &mut cache.standard, - ExpressionKind::Unary => &mut cache.unary, - }; - if map.contains_key(source) { - continue; - } - - let result = match kind { - ExpressionKind::Standard => isolate - .compile_standard(source) - .map(|e| e.bytecode().to_vec()), - ExpressionKind::Unary => { - isolate.compile_unary(source).map(|e| e.bytecode().to_vec()) - } - }; - if let Ok(bytecode) = result { - map.insert(source.clone(), Arc::from(bytecode)); - } + pub(crate) async fn loaded( + graph: Arc, + loader: &DynamicLoader, + ) -> Arc { + if graph.compiled_plan.is_some() + && graph.resolved_schemas.is_some() + && !graph.schemas_failed() + { + return graph; } + let mut owned = (*graph).clone(); + owned.prepare(); + let _ = owned.resolve_schemas(loader).await; + Arc::new(owned) + } - self.compiled_cache.replace(Arc::new(cache)); + pub fn compile(&mut self) { + self.prepare(); + #[cfg(feature = "driver")] + self.build_opcode_cache(); + } + + pub(crate) fn is_compiled(&self) -> bool { + #[cfg(feature = "driver")] + if self.compiled_cache.is_none() { + return false; + } + self.compiled_plan.is_some() } fn build_dt_indexes(&mut self) { @@ -223,7 +220,7 @@ impl GraphContent { } pub async fn resolve_schemas(&mut self, loader: &DynamicLoader) -> Result<(), String> { - if self.resolved_schemas.is_some() { + if self.resolved_schemas.is_some() && !self.schemas_failed() { return Ok(()); } @@ -241,20 +238,75 @@ impl GraphContent { } } - if referencing.is_empty() { - self.resolved_schemas = Some(Arc::new(HashMap::new())); - return Ok(()); - } - - let dictionaries = schema_dict::load_import_dictionaries(loader, &self.imports).await?; let mut resolved = HashMap::with_capacity(referencing.len()); - for (id, schema) in referencing { - let (value, salt) = schema_dict::resolve_schema(&schema, &dictionaries)?; - resolved.insert(id, (Arc::new(value), salt)); + let mut failures = HashMap::new(); + let mut first = None; + if !referencing.is_empty() { + let dictionaries = schema_dict::load_import_dictionaries(loader, &self.imports).await; + for (id, schema) in referencing { + match dictionaries + .as_ref() + .map_err(Clone::clone) + .and_then(|dictionaries| schema_dict::resolve_schema(&schema, dictionaries)) + { + Ok((value, salt)) => { + resolved.insert(id, (Arc::new(value), salt)); + } + Err(message) => { + failures.insert(id, Arc::from(message.as_str())); + first.get_or_insert(message); + } + } + } } self.resolved_schemas = Some(Arc::new(resolved)); - Ok(()) + self.schema_failures = Some(Arc::new(failures)); + first.map_or(Ok(()), Err) + } + + pub(crate) fn schemas_failed(&self) -> bool { + self.schema_failures + .as_ref() + .is_some_and(|failures| !failures.is_empty()) + } + + pub(crate) fn without_failed_schemas(&self) -> Self { + let mut kept = self.clone(); + if kept.schemas_failed() { + kept.resolved_schemas = None; + kept.schema_failures = None; + } + kept + } + + #[cfg(feature = "driver")] + pub(crate) async fn validation_schema( + &self, + loader: &DynamicLoader, + node_id: &str, + schema: Option<&serde_json::Value>, + ) -> Result, u64)>, String> { + let Some(schema) = schema else { + return Ok(None); + }; + if let Some(message) = self + .schema_failures + .as_ref() + .and_then(|failures| failures.get(node_id)) + { + return Err(message.to_string()); + } + if let Some(resolved) = &self.resolved_schemas { + return Ok(resolved.get(node_id).cloned()); + } + if !schema_dict::schema_references_dictionary(schema) { + return Ok(None); + } + + let dictionaries = schema_dict::load_import_dictionaries(loader, &self.imports).await?; + schema_dict::resolve_schema(schema, &dictionaries) + .map(|resolved| Some((Arc::new(resolved.0), resolved.1))) } fn compile_functions(&mut self) { diff --git a/core/engine/src/model/mod.rs b/core/engine/src/model/mod.rs index 006cd418..5605625c 100644 --- a/core/engine/src/model/mod.rs +++ b/core/engine/src/model/mod.rs @@ -1,3 +1,5 @@ pub use zen_types::decision::*; mod decision_content; +#[cfg(feature = "driver")] +mod opcode_cache; pub use decision_content::{DecisionContent, GraphContent, PolicyContent}; diff --git a/core/engine/src/model/opcode_cache.rs b/core/engine/src/model/opcode_cache.rs new file mode 100644 index 00000000..7d3b84b1 --- /dev/null +++ b/core/engine/src/model/opcode_cache.rs @@ -0,0 +1,78 @@ +use super::GraphContent; +use std::sync::Arc; +use zen_expression::{ExpressionKind, Isolate, OpcodeCache}; +use zen_types::decision::DecisionNodeKind; + +impl GraphContent { + pub(crate) fn build_opcode_cache(&mut self) { + if self.compiled_cache.is_some() { + return; + } + + let mut sources: Vec<(Arc, ExpressionKind)> = Vec::new(); + for node in &self.nodes { + match &node.kind { + DecisionNodeKind::ExpressionNode { content } => { + for expr in content.expressions.iter() { + if !expr.key.is_empty() && !expr.value.is_empty() { + sources.push((expr.value.clone(), ExpressionKind::Standard)); + } + } + } + DecisionNodeKind::DecisionTableNode { content } => { + for rule in content.rules.iter() { + for input in content.inputs.iter() { + let Some(rule_value) = rule.get(&input.id) else { + continue; + }; + + let kind = if input.field.is_some() { + ExpressionKind::Unary + } else { + ExpressionKind::Standard + }; + + sources.push((rule_value.clone(), kind)); + } + + for output in content.outputs.iter() { + let Some(rule_value) = rule.get(&output.id) else { + continue; + }; + + sources.push((rule_value.clone(), ExpressionKind::Standard)); + } + } + } + _ => {} + } + } + + let mut cache: OpcodeCache = OpcodeCache::new(); + let mut isolate = Isolate::new(); + + for (source, kind) in &sources { + let map = match kind { + ExpressionKind::Standard => &mut cache.standard, + ExpressionKind::Unary => &mut cache.unary, + }; + if map.contains_key(source) { + continue; + } + + let result = match kind { + ExpressionKind::Standard => isolate + .compile_standard(source) + .map(|e| e.bytecode().to_vec()), + ExpressionKind::Unary => { + isolate.compile_unary(source).map(|e| e.bytecode().to_vec()) + } + }; + if let Ok(bytecode) = result { + map.insert(source.clone(), Arc::from(bytecode)); + } + } + + self.compiled_cache.replace(Arc::new(cache)); + } +} diff --git a/core/engine/src/nodes/context.rs b/core/engine/src/nodes/context.rs index 3c8041d9..93b4dbd0 100644 --- a/core/engine/src/nodes/context.rs +++ b/core/engine/src/nodes/context.rs @@ -2,20 +2,19 @@ use crate::nodes::definition::{NodeDataType, TraceDataType}; use crate::nodes::extensions::NodeHandlerExtensions; use crate::nodes::function::v2::function::Function; use crate::nodes::result::{NodeResponse, NodeResult}; +use crate::nodes::validator_cache::ValidatorCache; use crate::nodes::variable_json::{Guards, VariableNode}; use crate::nodes::NodeError; use crate::ZEN_CONFIG; -use ahash::{AHasher, HashSet}; +use ahash::HashSet; use jsonschema::ValidationError; use serde::Serialize; use serde_json::Value; use std::cell::RefCell; use std::fmt::{Display, Formatter}; -use std::hash::Hasher; use std::sync::atomic::Ordering; use std::sync::Arc; use thiserror::Error; -use zen_expression::Isolate; use zen_types::symbol::Symbol; use zen_types::variable::{ToVariable, Variable}; @@ -42,16 +41,7 @@ where TraceData: TraceDataType, { pub fn input_with_nodes(&self) -> Variable { - let Some(nodes) = &self.nodes else { - return self.input.shallow_clone(); - }; - let Variable::Object(object) = &self.input else { - return self.input.shallow_clone(); - }; - - let mut map = object.borrow().clone(); - map.insert(Variable::nodes_key(), nodes.clone()); - Variable::from_object(map) + NodeContextBase::joined(&self.input, self.nodes.as_ref()) } pub fn from_base(base: NodeContextBase, data: NodeData) -> Self { @@ -62,16 +52,12 @@ where nodes: base.nodes, extensions: base.extensions, iteration: base.iteration, - trace: base.config.trace.then(|| Default::default()), + trace: base.config.trace.then(Default::default), node: data, config: base.config, } } - pub fn isolate(&self) -> Isolate { - make_isolate(&self.input, self.nodes.as_ref(), &self.extensions) - } - pub fn trace(&self, mutator: Function) where Function: FnOnce(&mut TraceData), @@ -99,11 +85,11 @@ where where Error: Into>, { - NodeError { - node_id: self.id.clone(), - trace: self.trace.as_ref().map(|v| (*v.borrow()).to_variable()), - source: error.into(), - } + NodeError::traced( + self.id.clone(), + self.trace.as_ref().map(|v| (*v.borrow()).to_variable()), + error, + ) } pub(crate) async fn function_runtime(&self) -> Result<&Function, NodeError> { @@ -120,6 +106,25 @@ where return Ok(()); } + { + let guards = Guards::default(); + let mut first = None; + let mut nullable = false; + for error in validator.iter_errors(VariableNode::new(value, &guards)) { + if Self::nullable(value, &error.instance_path().to_string()) { + nullable = true; + break; + } + first.get_or_insert(error); + } + if !nullable { + return match first { + Some(error) => Err(ValidationErrorJson::from(error)).node_context(self), + None => Ok(()), + }; + } + } + let current = value.deep_clone(); let mut removed: HashSet = HashSet::default(); loop { @@ -156,6 +161,32 @@ where } } + fn nullable(value: &Variable, pointer: &str) -> bool { + let segments: Vec = pointer + .split('/') + .skip(1) + .map(|s| s.replace("~1", "/").replace("~0", "~")) + .collect(); + match (Self::node_at(value, &segments), segments.split_last()) { + (None, _) => false, + (Some(Variable::Null), Some((_, parents))) => { + matches!(Self::node_at(value, parents), Some(Variable::Object(_))) + } + (Some(target), _) => Self::holds_null(&target), + } + } + + fn holds_null(value: &Variable) -> bool { + match value { + Variable::Object(object) => object + .borrow() + .iter() + .any(|(_, field)| matches!(field, Variable::Null) || Self::holds_null(field)), + Variable::Array(array) => array.borrow().iter().any(Self::holds_null), + _ => false, + } + } + fn remove_nulls_at(value: &Variable, pointer: &str, removed: &mut HashSet) { let segments: Vec = pointer .split('/') @@ -235,11 +266,7 @@ where } fn hash_node(&self) -> u64 { - let mut hasher = AHasher::default(); - hasher.write(self.id.as_bytes()); - hasher.write(self.name.as_bytes()); - hasher.write_u64(self.config.validation_salt); - hasher.finish() + ValidatorCache::key(&self.id, &self.name, self.config.validation_salt) } } @@ -325,23 +352,18 @@ pub struct NodeContextBase { pub trace: Option>, } -pub(crate) fn make_isolate( - input: &Variable, - nodes: Option<&Variable>, - extensions: &NodeHandlerExtensions, -) -> Isolate { - let mut isolate = - Isolate::with_environment(input.clone()).with_cache(extensions.compiled_cache.clone()); - if let Some(nodes) = nodes { - isolate.set_local(Variable::nodes_key(), nodes.clone()); - } - - isolate -} - impl NodeContextBase { - pub fn isolate(&self) -> Isolate { - make_isolate(&self.input, self.nodes.as_ref(), &self.extensions) + pub(crate) fn joined(input: &Variable, nodes: Option<&Variable>) -> Variable { + let Some(nodes) = nodes else { + return input.shallow_clone(); + }; + let Variable::Object(object) = input else { + return input.shallow_clone(); + }; + + let mut map = object.borrow().clone(); + map.insert(Variable::nodes_key(), nodes.clone()); + Variable::from_object(map) } pub fn error(&self, error: Error) -> NodeResult @@ -362,47 +384,25 @@ impl NodeContextBase { where Error: Into>, { - NodeError { - node_id: self.id.clone(), - trace: self.trace.as_ref().map(|t| t.borrow().to_variable()), - source: error.into(), - } + NodeError::traced( + self.id.clone(), + self.trace.as_ref().map(|t| t.borrow().to_variable()), + error, + ) } + #[cfg(feature = "driver")] pub fn trace(&self, mutator: Function) where Function: FnOnce(&mut Variable), { if let Some(trace) = &self.trace { - mutator(&mut *trace.borrow_mut()); - } - } -} - -impl From> for NodeContextBase -where - NodeData: NodeDataType, - TraceData: TraceDataType, -{ - fn from(value: NodeContext) -> Self { - let trace = match value.config.trace { - true => Some(RefCell::new(Variable::Null)), - false => None, - }; - - Self { - id: value.id, - name: value.name, - input: value.input, - nodes: value.nodes, - extensions: value.extensions, - iteration: value.iteration, - config: value.config, - trace, + mutator(&mut trace.borrow_mut()); } } } +#[cfg(feature = "driver")] impl NodeContextExt for Result where E: Into>, @@ -422,6 +422,7 @@ where } } +#[cfg(feature = "driver")] impl NodeContextExt for Option { type Error = &'static str; diff --git a/core/engine/src/nodes/custom/adapter.rs b/core/engine/src/nodes/custom/adapter.rs index 16e3c4a8..c9ad5b6a 100644 --- a/core/engine/src/nodes/custom/adapter.rs +++ b/core/engine/src/nodes/custom/adapter.rs @@ -19,11 +19,10 @@ pub struct NoopCustomNode; impl CustomNodeAdapter for NoopCustomNode { fn handle(&self, request: CustomNodeRequest) -> Pin>> { Box::pin(async move { - Err(NodeError { - trace: None, - node_id: request.node.id.clone(), - source: "Custom node handler not provided".to_string().into(), - }) + Err(NodeError::new( + request.node.id.clone(), + "Custom node handler not provided".to_string(), + )) }) } } diff --git a/core/engine/src/nodes/decision/handler.rs b/core/engine/src/nodes/decision/handler.rs new file mode 100644 index 00000000..455cf067 --- /dev/null +++ b/core/engine/src/nodes/decision/handler.rs @@ -0,0 +1,110 @@ +use super::{DecisionNodeData, DecisionNodeTrace}; +use crate::decision_graph::graph::DecisionGraph; +use crate::decision_graph::walk::DecisionGraphConfig; +use crate::nodes::{NodeContext, NodeContextExt, NodeError, NodeHandler, NodeResult}; +use crate::EvaluationError; +use std::cell::RefCell; +use std::ops::Deref; +use std::rc::Rc; +use zen_types::decision::TransformAttributes; +use zen_types::variable::{ToVariable, Variable}; + +#[derive(Debug, Clone, Default)] +pub struct DecisionNodeHandler { + decision_graph: Rc>>, +} + +impl NodeHandler for DecisionNodeHandler { + type NodeData = DecisionNodeData; + type TraceData = DecisionNodeTrace; + + fn transform_attributes( + &self, + ctx: &NodeContext, + ) -> Option { + Some(ctx.node.transform_attributes.clone()) + } + + async fn after_transform_attributes( + &self, + _ctx: &NodeContext, + ) -> Result<(), NodeError> { + if let Some(graph) = self.decision_graph.borrow_mut().as_mut() { + graph.reset_graph(); + }; + + Ok(()) + } + + async fn handle(&self, ctx: NodeContext) -> NodeResult { + let mut decision_graph_ref = self.decision_graph.borrow_mut(); + + if decision_graph_ref.is_none() { + let loader = ctx.extensions.loader(); + let sub_decision = loader.load(ctx.node.key.deref()).await.node_context(&ctx)?; + let sub_kind = sub_decision.kind(); + let Some(sub_graph) = sub_decision.into_graph_arc() else { + return ctx.error(format!( + "sub-decision '{}' is a {sub_kind}, expected graph", + ctx.node.key + )); + }; + + let sub_graph = + if sub_graph.compiled_cache.is_some() && sub_graph.resolved_schemas.is_some() { + sub_graph + } else { + let mut owned = (*sub_graph).clone(); + owned.compile(); + let _ = owned.resolve_schemas(loader).await; + std::sync::Arc::new(owned) + }; + + let mut extensions = ctx.extensions.clone(); + extensions.compiled_cache = sub_graph.compiled_cache.clone(); + extensions.dt_indexes = sub_graph.dt_indexes.clone(); + extensions.validator_cache = + std::sync::Arc::new(std::cell::OnceCell::from(sub_graph.validator_cache.clone())); + + let dg = DecisionGraph::try_new(DecisionGraphConfig { + content: sub_graph, + extensions, + trace: ctx.config.trace, + iteration: ctx.iteration + 1, + max_depth: ctx.config.max_depth, + }) + .node_context(&ctx)?; + + *decision_graph_ref = Some(dg); + } + + let Some(decision_graph) = decision_graph_ref.as_mut() else { + return ctx.error("Failed to initialize decision graph".to_string()); + }; + + decision_graph.set_parent_nodes(ctx.nodes.clone()); + + let evaluate_result = Box::pin(decision_graph.evaluate(ctx.input.clone())).await; + match evaluate_result { + Ok(result) => { + ctx.trace(|trace| { + *trace = result + .trace + .and_then(|t| t.into_graph()) + .as_ref() + .map(|m| m.to_variable()) + .unwrap_or(Variable::Null); + }); + + ctx.success(result.result) + } + Err(err) => { + if let EvaluationError::NodeError { trace, .. } = err.deref() { + ctx.trace(|t| *t = trace.to_variable()); + } + + ctx.error(err.to_string()) + } + } + } +} diff --git a/core/engine/src/nodes/decision/mod.rs b/core/engine/src/nodes/decision/mod.rs index 026a7c10..ce3c2470 100644 --- a/core/engine/src/nodes/decision/mod.rs +++ b/core/engine/src/nodes/decision/mod.rs @@ -1,111 +1,10 @@ -use crate::decision_graph::graph::{DecisionGraph, DecisionGraphConfig}; -use crate::nodes::{NodeContext, NodeContextExt, NodeError, NodeHandler, NodeResult}; -use crate::EvaluationError; -use std::cell::RefCell; -use std::ops::Deref; -use std::rc::Rc; -use zen_types::decision::{DecisionNodeContent, TransformAttributes}; -use zen_types::variable::{ToVariable, Variable}; +#[cfg(feature = "driver")] +pub use handler::DecisionNodeHandler; +use zen_types::decision::DecisionNodeContent; +use zen_types::variable::Variable; -#[derive(Debug, Clone, Default)] -pub struct DecisionNodeHandler { - decision_graph: Rc>>, -} +#[cfg(feature = "driver")] +mod handler; pub type DecisionNodeData = DecisionNodeContent; pub type DecisionNodeTrace = Variable; - -impl NodeHandler for DecisionNodeHandler { - type NodeData = DecisionNodeData; - type TraceData = DecisionNodeTrace; - - fn transform_attributes( - &self, - ctx: &NodeContext, - ) -> Option { - Some(ctx.node.transform_attributes.clone()) - } - - async fn after_transform_attributes( - &self, - _ctx: &NodeContext, - ) -> Result<(), NodeError> { - if let Some(graph) = self.decision_graph.borrow_mut().as_mut() { - graph.reset_graph(); - }; - - Ok(()) - } - - async fn handle(&self, ctx: NodeContext) -> NodeResult { - let mut decision_graph_ref = self.decision_graph.borrow_mut(); - - if decision_graph_ref.is_none() { - let loader = ctx.extensions.loader(); - let sub_decision = loader.load(ctx.node.key.deref()).await.node_context(&ctx)?; - let sub_kind = sub_decision.kind(); - let Some(sub_graph) = sub_decision.into_graph_arc() else { - return ctx.error(format!( - "sub-decision '{}' is a {sub_kind}, expected graph", - ctx.node.key - )); - }; - - let sub_graph = - if sub_graph.compiled_cache.is_some() && sub_graph.resolved_schemas.is_some() { - sub_graph - } else { - let mut owned = (*sub_graph).clone(); - owned.compile(); - let _ = owned.resolve_schemas(loader).await; - std::sync::Arc::new(owned) - }; - - let mut extensions = ctx.extensions.clone(); - extensions.compiled_cache = sub_graph.compiled_cache.clone(); - extensions.dt_indexes = sub_graph.dt_indexes.clone(); - extensions.validator_cache = - std::sync::Arc::new(std::cell::OnceCell::from(sub_graph.validator_cache.clone())); - - let dg = DecisionGraph::try_new(DecisionGraphConfig { - content: sub_graph, - extensions, - trace: ctx.config.trace, - iteration: ctx.iteration + 1, - max_depth: ctx.config.max_depth, - }) - .node_context(&ctx)?; - - *decision_graph_ref = Some(dg); - } - - let Some(decision_graph) = decision_graph_ref.as_mut() else { - return ctx.error("Failed to initialize decision graph".to_string()); - }; - - decision_graph.set_parent_nodes(ctx.nodes.clone()); - - let evaluate_result = Box::pin(decision_graph.evaluate(ctx.input.clone())).await; - match evaluate_result { - Ok(result) => { - ctx.trace(|trace| { - *trace = result - .trace - .and_then(|t| t.into_graph()) - .as_ref() - .map(|m| m.to_variable()) - .unwrap_or(Variable::Null); - }); - - ctx.success(result.result) - } - Err(err) => { - if let EvaluationError::NodeError { trace, .. } = err.deref() { - ctx.trace(|t| *t = trace.to_variable()); - } - - ctx.error(err.to_string()) - } - } - } -} diff --git a/core/engine/src/nodes/decision_table/handler.rs b/core/engine/src/nodes/decision_table/handler.rs new file mode 100644 index 00000000..6ab8355e --- /dev/null +++ b/core/engine/src/nodes/decision_table/handler.rs @@ -0,0 +1,422 @@ +use super::index::TableIndex; +use super::DecisionTableNodeData; +use crate::decision_graph::tracer::{DecisionTableNodeTrace, DecisionTableRowTrace}; +use crate::nodes::definition::NodeHandler; +use crate::nodes::result::NodeResult; +use crate::nodes::{NodeContext, NodeResponse}; +use ahash::HashMap; +use fixedbitset::FixedBitSet; +use std::ops::Deref; +use std::rc::Rc; +use std::sync::Arc; +use zen_expression::variable::ToVariable; +use zen_expression::Isolate; +use zen_types::decision::{DecisionTableHitPolicy, DecisionTableInputField, TransformAttributes}; +use zen_types::variable::Variable; + +#[derive(Debug, Clone)] +pub struct DecisionTableNodeHandler; + +type DecisionTableContext = NodeContext; + +impl NodeHandler for DecisionTableNodeHandler { + type NodeData = DecisionTableNodeData; + type TraceData = DecisionTableNodeTrace; + + fn transform_attributes( + &self, + ctx: &NodeContext, + ) -> Option { + Some(ctx.node.transform_attributes.clone()) + } + + async fn handle(&self, ctx: NodeContext) -> NodeResult { + let has_collect_columns = ctx.node.outputs.iter().any(|output| output.write_path().1); + match ctx.node.hit_policy { + DecisionTableHitPolicy::First if has_collect_columns => { + self.handle_first_hit_collect(ctx) + } + DecisionTableHitPolicy::First => self.handle_first_hit(ctx), + DecisionTableHitPolicy::Collect => self.handle_collect(ctx), + } + } +} + +impl DecisionTableNodeHandler { + fn handle_first_hit(&self, ctx: DecisionTableContext) -> NodeResult { + let mut isolate = ctx.isolate(); + + if !ctx.config.trace { + let index = Self::table_index(&ctx); + let candidates = + index.and_then(|ix| Self::candidate_rows(ix, &ctx.node.inputs, &mut isolate)); + let pruner = candidates.as_ref().and(index); + for (row_idx, rule) in ctx.node.rules.iter().enumerate() { + if candidates.as_ref().is_some_and(|c| !c.contains(row_idx)) { + continue; + } + let pruned = pruner.map(|ix| (ix, row_idx)); + if let Some(RowResult::Output(output)) = + self.evaluate_row(&ctx, rule, &mut isolate, pruned) + { + return ctx.success(output); + } + } + return Ok(NodeResponse { + output: Variable::Null, + trace_data: None, + }); + } + + let hit = ctx.node.rules.iter().enumerate().find_map(|(index, rule)| { + match self.evaluate_row(&ctx, rule, &mut isolate, None)? { + RowResult::WithTrace { + output, + reference_map, + rule, + } => Some((index, output, reference_map, rule)), + RowResult::Output(output) => { + Some((index, output, Default::default(), Default::default())) + } + } + }); + + match hit { + Some((index, output, reference_map, rule)) => { + ctx.trace(|t| { + *t = DecisionTableNodeTrace::FirstHit(DecisionTableRowTrace { + reference_map, + index, + rule, + }) + }); + ctx.success(output) + } + None => Ok(NodeResponse { + output: Variable::Null, + trace_data: None, + }), + } + } + + fn handle_collect(&self, ctx: DecisionTableContext) -> NodeResult { + let mut outputs = Vec::new(); + let mut traces = Vec::new(); + let mut isolate = ctx.isolate(); + + let table_index = (!ctx.config.trace) + .then(|| Self::table_index(&ctx)) + .flatten(); + let candidates = + table_index.and_then(|ix| Self::candidate_rows(ix, &ctx.node.inputs, &mut isolate)); + let pruner = candidates.as_ref().and(table_index); + + for (index, rule) in ctx.node.rules.iter().enumerate() { + if candidates.as_ref().is_some_and(|c| !c.contains(index)) { + continue; + } + let pruned = pruner.map(|ix| (ix, index)); + if let Some(result) = self.evaluate_row(&ctx, rule, &mut isolate, pruned) { + match result { + RowResult::Output(output) => { + outputs.push(output); + } + RowResult::WithTrace { + output, + reference_map, + rule, + } => { + outputs.push(output); + traces.push(DecisionTableRowTrace { + index, + rule, + reference_map, + }); + } + } + } + } + + ctx.trace(|t| { + *t = DecisionTableNodeTrace::Collect(traces); + }); + + ctx.success(Variable::from_array(outputs)) + } + + fn table_index(ctx: &DecisionTableContext) -> Option<&TableIndex> { + ctx.extensions.dt_indexes.as_ref()?.get(&ctx.id) + } + + fn candidate_rows( + index: &TableIndex, + inputs: &[DecisionTableInputField], + isolate: &mut Isolate, + ) -> Option { + let mut acc: Option = None; + for (col_idx, column) in index.columns.iter().enumerate() { + let Some(column) = column else { + continue; + }; + let Some(field) = inputs[col_idx].field.as_ref().filter(|f| !f.is_empty()) else { + continue; + }; + isolate.set_reference(field).ok()?; + let value = isolate.get_reference(field)?; + if matches!(value, Variable::Dynamic(_)) { + return None; + } + let hit = column.rows_for(&value); + match &mut acc { + None => { + let mut first = column.fallback.clone(); + if let Some(hit) = hit { + first.union_with(hit); + } + acc = Some(first); + } + Some(acc) => { + let fallback = column.fallback.as_slice(); + let hit = hit.map(FixedBitSet::as_slice).unwrap_or_default(); + for (i, word) in acc.as_mut_slice().iter_mut().enumerate() { + let f = fallback.get(i).copied().unwrap_or(0); + let h = hit.get(i).copied().unwrap_or(0); + *word &= f | h; + } + } + } + } + acc + } + + fn handle_first_hit_collect(&self, ctx: DecisionTableContext) -> NodeResult { + let mut isolate = ctx.isolate(); + + let table_index = (!ctx.config.trace) + .then(|| Self::table_index(&ctx)) + .flatten(); + let candidates = + table_index.and_then(|ix| Self::candidate_rows(ix, &ctx.node.inputs, &mut isolate)); + let pruner = candidates.as_ref().and(table_index); + + let mut scalars: Option = None; + let mut collected: Vec> = vec![Vec::new(); ctx.node.outputs.len()]; + let mut traces = Vec::new(); + let slot = |column: usize| { + let path = ctx.node.outputs[column].write_path().0; + ctx.node + .outputs + .iter() + .position(|o| o.write_path() == (path, true)) + .unwrap_or(column) + }; + + for (row_idx, rule) in ctx.node.rules.iter().enumerate() { + if candidates.as_ref().is_some_and(|c| !c.contains(row_idx)) { + continue; + } + let pruned = pruner.map(|ix| (ix, row_idx)); + if !Self::row_matches(&ctx, rule, &mut isolate, pruned) { + continue; + } + + let Some((row_scalars, row_collects)) = + Self::evaluate_row_cells(&ctx, rule, &mut isolate, scalars.is_none()) + else { + continue; + }; + if let Some(row_scalars) = row_scalars { + scalars = Some(row_scalars); + } + for (column_idx, value) in row_collects { + collected[slot(column_idx)].push(value); + } + + if ctx.config.trace { + let (reference_map, rule_trace) = Self::row_trace_parts(&ctx, rule, &mut isolate); + traces.push(DecisionTableRowTrace { + index: row_idx, + reference_map, + rule: rule_trace, + }); + } + } + + let output = scalars.unwrap_or_else(Variable::empty_object); + for (column_idx, column) in ctx.node.outputs.iter().enumerate() { + let (path, collect) = column.write_path(); + if !collect || path.is_empty() || slot(column_idx) != column_idx { + continue; + } + let values = std::mem::take(&mut collected[column_idx]); + output.dot_insert(path, Variable::from_array(values)); + } + + ctx.trace(|t| { + *t = DecisionTableNodeTrace::Collect(traces); + }); + ctx.success(output) + } + + fn row_matches( + ctx: &DecisionTableContext, + rule: &HashMap, Arc>, + isolate: &mut Isolate, + pruned: Option<(&TableIndex, usize)>, + ) -> bool { + for (col_idx, input) in ctx.node.inputs.iter().enumerate() { + let Some(rule_value) = rule.get(&input.id) else { + continue; + }; + if rule_value.is_empty() { + continue; + } + if pruned.is_some_and(|(ix, row_idx)| ix.decides(col_idx, row_idx)) { + if let Some(field) = &input.field { + let _ = isolate.set_reference(field); + } + continue; + } + + let passed = match &input.field { + None => isolate + .run_standard(rule_value) + .ok() + .and_then(|result| result.as_bool()) + .unwrap_or(false), + Some(field) => { + isolate.set_reference(field).is_ok() + && isolate.run_unary(rule_value).unwrap_or(false) + } + }; + if !passed { + return false; + } + } + true + } + + fn evaluate_row_cells( + ctx: &DecisionTableContext, + rule: &HashMap, Arc>, + isolate: &mut Isolate, + include_scalars: bool, + ) -> Option<(Option, Vec<(usize, Variable)>)> { + let scalars = include_scalars.then(Variable::empty_object); + let mut collects = Vec::new(); + for (column_idx, output) in ctx.node.outputs.iter().enumerate() { + let (path, collect) = output.write_path(); + if path.is_empty() || (!collect && !include_scalars) { + continue; + } + let Some(rule_value) = rule.get(&output.id) else { + continue; + }; + if rule_value.is_empty() { + continue; + } + + let value = isolate.run_standard(rule_value).ok()?.deep_clone(); + if collect { + collects.push((column_idx, value)); + } else if let Some(scalars) = &scalars { + scalars.dot_insert(path, value); + } + } + Some((scalars, collects)) + } + + fn row_trace_parts( + ctx: &DecisionTableContext, + rule: &HashMap, Arc>, + isolate: &mut Isolate, + ) -> (HashMap, Variable>, HashMap, Rc>) { + let id_str = Rc::::from("_id"); + let description_str = Rc::::from("_description"); + + let rule_id = match rule.get(id_str.as_ref()) { + Some(rid) => Rc::::from(rid.deref()), + None => Rc::from(""), + }; + + let mut expressions: HashMap, Rc> = Default::default(); + let mut reference_map: HashMap, Variable> = Default::default(); + + expressions.insert(id_str.clone(), rule_id.clone()); + if let Some(description) = rule.get(description_str.as_ref()) { + expressions.insert(description_str.clone(), Rc::from(description.deref())); + } + + for input in ctx.node.inputs.iter() { + let Some(rule_value) = rule.get(input.id.deref()) else { + continue; + }; + let Some(input_field) = &input.field else { + continue; + }; + + if let Some(reference) = isolate.get_reference(input_field.deref()) { + reference_map.insert(Rc::from(input_field.deref()), reference); + } else if let Some(reference) = isolate.run_standard(input_field.deref()).ok() { + reference_map.insert(Rc::from(input_field.deref()), reference); + } + + let input_identifier = format!("{input_field}[{}]", &input.id); + expressions.insert( + Rc::from(input_identifier.as_str()), + Rc::from(rule_value.deref()), + ); + } + + (reference_map, expressions) + } + + fn evaluate_row<'a>( + &self, + ctx: &'a DecisionTableContext, + rule: &'a HashMap, Arc>, + isolate: &mut Isolate, + pruned: Option<(&TableIndex, usize)>, + ) -> Option { + if !Self::row_matches(ctx, rule, isolate, pruned) { + return None; + } + + let outputs = Variable::empty_object(); + for output in ctx.node.outputs.iter() { + let (path, _) = output.write_path(); + if path.is_empty() { + continue; + } + let Some(rule_value) = rule.get(&output.id) else { + continue; + }; + if rule_value.is_empty() { + continue; + } + + let res = isolate.run_standard(rule_value).ok()?; + outputs.dot_insert(path, res.deep_clone()); + } + + if !ctx.config.trace { + return Some(RowResult::Output(outputs)); + } + + let (reference_map, expressions) = Self::row_trace_parts(ctx, rule, isolate); + Some(RowResult::WithTrace { + output: outputs.to_variable(), + reference_map, + rule: expressions, + }) + } +} + +enum RowResult { + Output(Variable), + WithTrace { + output: Variable, + reference_map: HashMap, Variable>, + rule: HashMap, Rc>, + }, +} diff --git a/core/engine/src/nodes/decision_table/mod.rs b/core/engine/src/nodes/decision_table/mod.rs index 151ebfcc..f424170c 100644 --- a/core/engine/src/nodes/decision_table/mod.rs +++ b/core/engine/src/nodes/decision_table/mod.rs @@ -1,470 +1,10 @@ -use crate::nodes::definition::NodeHandler; -use crate::nodes::result::NodeResult; -use crate::nodes::{NodeContext, NodeResponse}; -use ahash::HashMap; -use fixedbitset::FixedBitSet; -use index::TableIndex; -use serde::Serialize; -use std::ops::Deref; -use std::rc::Rc; -use std::sync::Arc; -use zen_expression::variable::ToVariable; -use zen_expression::Isolate; -use zen_types::decision::{ - DecisionTableContent, DecisionTableHitPolicy, DecisionTableInputField, TransformAttributes, -}; -use zen_types::variable::Variable; +pub use crate::decision_graph::tracer::{DecisionTableNodeTrace, DecisionTableRowTrace}; +#[cfg(feature = "driver")] +pub use handler::DecisionTableNodeHandler; +use zen_types::decision::DecisionTableContent; + +#[cfg(feature = "driver")] +mod handler; pub(crate) mod index; -#[derive(Debug, Clone)] -pub struct DecisionTableNodeHandler; - pub type DecisionTableNodeData = DecisionTableContent; - -type DecisionTableContext = NodeContext; - -impl NodeHandler for DecisionTableNodeHandler { - type NodeData = DecisionTableNodeData; - type TraceData = DecisionTableNodeTrace; - - fn transform_attributes( - &self, - ctx: &NodeContext, - ) -> Option { - Some(ctx.node.transform_attributes.clone()) - } - - async fn handle(&self, ctx: NodeContext) -> NodeResult { - let has_collect_columns = ctx.node.outputs.iter().any(|output| output.write_path().1); - match ctx.node.hit_policy { - DecisionTableHitPolicy::First if has_collect_columns => { - self.handle_first_hit_collect(ctx) - } - DecisionTableHitPolicy::First => self.handle_first_hit(ctx), - DecisionTableHitPolicy::Collect => self.handle_collect(ctx), - } - } -} - -impl DecisionTableNodeHandler { - fn handle_first_hit(&self, ctx: DecisionTableContext) -> NodeResult { - let mut isolate = ctx.isolate(); - - if !ctx.config.trace { - let index = Self::table_index(&ctx); - let candidates = - index.and_then(|ix| Self::candidate_rows(ix, &ctx.node.inputs, &mut isolate)); - let pruner = candidates.as_ref().and(index); - for (row_idx, rule) in ctx.node.rules.iter().enumerate() { - if candidates.as_ref().is_some_and(|c| !c.contains(row_idx)) { - continue; - } - let pruned = pruner.map(|ix| (ix, row_idx)); - if let Some(RowResult::Output(output)) = - self.evaluate_row(&ctx, rule, &mut isolate, pruned) - { - return ctx.success(output); - } - } - return Ok(NodeResponse { - output: Variable::Null, - trace_data: None, - }); - } - - let hit = ctx.node.rules.iter().enumerate().find_map(|(index, rule)| { - match self.evaluate_row(&ctx, rule, &mut isolate, None)? { - RowResult::WithTrace { - output, - reference_map, - rule, - } => Some((index, output, reference_map, rule)), - RowResult::Output(output) => { - Some((index, output, Default::default(), Default::default())) - } - } - }); - - match hit { - Some((index, output, reference_map, rule)) => { - ctx.trace(|t| { - *t = DecisionTableNodeTrace::FirstHit(DecisionTableRowTrace { - reference_map, - index, - rule, - }) - }); - ctx.success(output) - } - None => Ok(NodeResponse { - output: Variable::Null, - trace_data: None, - }), - } - } - - fn handle_collect(&self, ctx: DecisionTableContext) -> NodeResult { - let mut outputs = Vec::new(); - let mut traces = Vec::new(); - let mut isolate = ctx.isolate(); - - let table_index = (!ctx.config.trace) - .then(|| Self::table_index(&ctx)) - .flatten(); - let candidates = - table_index.and_then(|ix| Self::candidate_rows(ix, &ctx.node.inputs, &mut isolate)); - let pruner = candidates.as_ref().and(table_index); - - for (index, rule) in ctx.node.rules.iter().enumerate() { - if candidates.as_ref().is_some_and(|c| !c.contains(index)) { - continue; - } - let pruned = pruner.map(|ix| (ix, index)); - if let Some(result) = self.evaluate_row(&ctx, rule, &mut isolate, pruned) { - match result { - RowResult::Output(output) => { - outputs.push(output); - } - RowResult::WithTrace { - output, - reference_map, - rule, - } => { - outputs.push(output); - traces.push(DecisionTableRowTrace { - index, - rule, - reference_map, - }); - } - } - } - } - - ctx.trace(|t| { - *t = DecisionTableNodeTrace::Collect(traces); - }); - - ctx.success(Variable::from_array(outputs)) - } - - pub(crate) fn cell_passes( - rule: &HashMap, Arc>, - input: &zen_types::decision::DecisionTableInputField, - isolate: &mut Isolate, - ) -> bool { - let Some(rule_value) = rule.get(&input.id) else { - return true; - }; - if rule_value.is_empty() { - return true; - } - match &input.field { - None => isolate - .run_standard(rule_value) - .ok() - .and_then(|result| result.as_bool()) - .unwrap_or(false), - Some(field) => { - if isolate.set_reference(field).is_err() { - return false; - } - isolate.run_unary(rule_value).unwrap_or(false) - } - } - } - - fn table_index(ctx: &DecisionTableContext) -> Option<&TableIndex> { - ctx.extensions.dt_indexes.as_ref()?.get(&ctx.id) - } - - fn candidate_rows( - index: &TableIndex, - inputs: &[DecisionTableInputField], - isolate: &mut Isolate, - ) -> Option { - let mut acc: Option = None; - for (col_idx, column) in index.columns.iter().enumerate() { - let Some(column) = column else { - continue; - }; - let Some(field) = inputs[col_idx].field.as_ref().filter(|f| !f.is_empty()) else { - continue; - }; - isolate.set_reference(field).ok()?; - let value = isolate.get_reference(field)?; - if matches!(value, Variable::Dynamic(_)) { - return None; - } - let hit = column.rows_for(&value); - match &mut acc { - None => { - let mut first = column.fallback.clone(); - if let Some(hit) = hit { - first.union_with(hit); - } - acc = Some(first); - } - Some(acc) => { - let fallback = column.fallback.as_slice(); - let hit = hit.map(FixedBitSet::as_slice).unwrap_or_default(); - for (i, word) in acc.as_mut_slice().iter_mut().enumerate() { - let f = fallback.get(i).copied().unwrap_or(0); - let h = hit.get(i).copied().unwrap_or(0); - *word &= f | h; - } - } - } - } - acc - } - - fn handle_first_hit_collect(&self, ctx: DecisionTableContext) -> NodeResult { - let mut isolate = ctx.isolate(); - - let table_index = (!ctx.config.trace) - .then(|| Self::table_index(&ctx)) - .flatten(); - let candidates = - table_index.and_then(|ix| Self::candidate_rows(ix, &ctx.node.inputs, &mut isolate)); - let pruner = candidates.as_ref().and(table_index); - - let mut scalars: Option = None; - let mut collected: Vec> = vec![Vec::new(); ctx.node.outputs.len()]; - let mut matched = false; - let mut traces = Vec::new(); - - for (row_idx, rule) in ctx.node.rules.iter().enumerate() { - if candidates.as_ref().is_some_and(|c| !c.contains(row_idx)) { - continue; - } - let pruned = pruner.map(|ix| (ix, row_idx)); - if !Self::row_matches(&ctx, rule, &mut isolate, pruned) { - continue; - } - - let Some((row_scalars, row_collects)) = - Self::evaluate_row_cells(&ctx, rule, &mut isolate, scalars.is_none()) - else { - continue; - }; - matched = true; - if let Some(row_scalars) = row_scalars { - scalars = Some(row_scalars); - } - for (column_idx, value) in row_collects { - collected[column_idx].push(value); - } - - if ctx.config.trace { - let (reference_map, rule_trace) = Self::row_trace_parts(&ctx, rule, &mut isolate); - traces.push(DecisionTableRowTrace { - index: row_idx, - reference_map, - rule: rule_trace, - }); - } - } - - if !matched { - return Ok(NodeResponse { - output: Variable::Null, - trace_data: None, - }); - } - - let output = scalars.unwrap_or_else(Variable::empty_object); - for (column_idx, column) in ctx.node.outputs.iter().enumerate() { - let (path, collect) = column.write_path(); - if !collect || path.is_empty() { - continue; - } - let values = std::mem::take(&mut collected[column_idx]); - output.dot_insert(path, Variable::from_array(values)); - } - - ctx.trace(|t| { - *t = DecisionTableNodeTrace::Collect(traces); - }); - ctx.success(output) - } - - fn row_matches( - ctx: &DecisionTableContext, - rule: &HashMap, Arc>, - isolate: &mut Isolate, - pruned: Option<(&TableIndex, usize)>, - ) -> bool { - for (col_idx, input) in ctx.node.inputs.iter().enumerate() { - if pruned.is_some_and(|(ix, row_idx)| ix.decides(col_idx, row_idx)) { - continue; - } - let Some(rule_value) = rule.get(&input.id) else { - continue; - }; - if rule_value.is_empty() { - continue; - } - - let passed = match &input.field { - None => isolate - .run_standard(rule_value) - .ok() - .and_then(|result| result.as_bool()) - .unwrap_or(false), - Some(field) => { - isolate.set_reference(field).is_ok() - && isolate.run_unary(rule_value).unwrap_or(false) - } - }; - if !passed { - return false; - } - } - true - } - - fn evaluate_row_cells( - ctx: &DecisionTableContext, - rule: &HashMap, Arc>, - isolate: &mut Isolate, - include_scalars: bool, - ) -> Option<(Option, Vec<(usize, Variable)>)> { - let scalars = include_scalars.then(Variable::empty_object); - let mut collects = Vec::new(); - for (column_idx, output) in ctx.node.outputs.iter().enumerate() { - let (path, collect) = output.write_path(); - if path.is_empty() || (!collect && !include_scalars) { - continue; - } - let Some(rule_value) = rule.get(&output.id) else { - continue; - }; - if rule_value.is_empty() { - continue; - } - - let value = isolate.run_standard(rule_value).ok()?.deep_clone(); - if collect { - collects.push((column_idx, value)); - } else if let Some(scalars) = &scalars { - scalars.dot_insert(path, value); - } - } - Some((scalars, collects)) - } - - fn row_trace_parts( - ctx: &DecisionTableContext, - rule: &HashMap, Arc>, - isolate: &mut Isolate, - ) -> (HashMap, Variable>, HashMap, Rc>) { - let id_str = Rc::::from("_id"); - let description_str = Rc::::from("_description"); - - let rule_id = match rule.get(id_str.as_ref()) { - Some(rid) => Rc::::from(rid.deref()), - None => Rc::from(""), - }; - - let mut expressions: HashMap, Rc> = Default::default(); - let mut reference_map: HashMap, Variable> = Default::default(); - - expressions.insert(id_str.clone(), rule_id.clone()); - if let Some(description) = rule.get(description_str.as_ref()) { - expressions.insert(description_str.clone(), Rc::from(description.deref())); - } - - for input in ctx.node.inputs.iter() { - let Some(rule_value) = rule.get(input.id.deref()) else { - continue; - }; - let Some(input_field) = &input.field else { - continue; - }; - - if let Some(reference) = isolate.get_reference(input_field.deref()) { - reference_map.insert(Rc::from(input_field.deref()), reference); - } else if let Some(reference) = isolate.run_standard(input_field.deref()).ok() { - reference_map.insert(Rc::from(input_field.deref()), reference); - } - - let input_identifier = format!("{input_field}[{}]", &input.id); - expressions.insert( - Rc::from(input_identifier.as_str()), - Rc::from(rule_value.deref()), - ); - } - - (reference_map, expressions) - } - - fn evaluate_row<'a>( - &self, - ctx: &'a DecisionTableContext, - rule: &'a HashMap, Arc>, - isolate: &mut Isolate, - pruned: Option<(&TableIndex, usize)>, - ) -> Option { - if !Self::row_matches(ctx, rule, isolate, pruned) { - return None; - } - - let outputs = Variable::empty_object(); - for output in ctx.node.outputs.iter() { - let (path, _) = output.write_path(); - if path.is_empty() { - continue; - } - let Some(rule_value) = rule.get(&output.id) else { - continue; - }; - if rule_value.is_empty() { - continue; - } - - let res = isolate.run_standard(rule_value).ok()?; - outputs.dot_insert(path, res.deep_clone()); - } - - if !ctx.config.trace { - return Some(RowResult::Output(outputs)); - } - - let (reference_map, expressions) = Self::row_trace_parts(ctx, rule, isolate); - Some(RowResult::WithTrace { - output: outputs.to_variable(), - reference_map, - rule: expressions, - }) - } -} - -enum RowResult { - Output(Variable), - WithTrace { - output: Variable, - reference_map: HashMap, Variable>, - rule: HashMap, Rc>, - }, -} - -#[derive(Debug, Clone, Serialize, ToVariable)] -pub struct DecisionTableRowTrace { - index: usize, - reference_map: HashMap, Variable>, - rule: HashMap, Rc>, -} - -#[derive(Debug, Clone, Serialize, ToVariable)] -#[serde(untagged)] -pub enum DecisionTableNodeTrace { - FirstHit(DecisionTableRowTrace), - Collect(Vec), -} - -impl Default for DecisionTableNodeTrace { - fn default() -> Self { - DecisionTableNodeTrace::Collect(Default::default()) - } -} diff --git a/core/engine/src/nodes/definition.rs b/core/engine/src/nodes/definition.rs index ee660fa6..0d738cd1 100644 --- a/core/engine/src/nodes/definition.rs +++ b/core/engine/src/nodes/definition.rs @@ -1,8 +1,10 @@ use crate::nodes::context::NodeContext; use crate::nodes::result::NodeResult; +#[cfg(feature = "driver")] use crate::nodes::NodeError; use serde::{Deserialize, Serialize}; use std::fmt::Debug; +#[cfg(feature = "driver")] use zen_types::decision::TransformAttributes; use zen_types::variable::ToVariable; @@ -16,6 +18,7 @@ pub trait NodeHandler: Clone { type NodeData: NodeDataType; type TraceData: TraceDataType; + #[cfg(feature = "driver")] #[allow(unused_variables)] fn transform_attributes( &self, @@ -24,6 +27,7 @@ pub trait NodeHandler: Clone { None } + #[cfg(feature = "driver")] #[allow(unused_variables)] fn after_transform_attributes( &self, diff --git a/core/engine/src/nodes/expression/handler.rs b/core/engine/src/nodes/expression/handler.rs new file mode 100644 index 00000000..49184453 --- /dev/null +++ b/core/engine/src/nodes/expression/handler.rs @@ -0,0 +1,59 @@ +use super::{ExpressionNodeData, ExpressionNodeTrace}; +use crate::nodes::result::NodeResult; +use std::rc::Rc; + +use crate::decision_graph::tracer::ExpressionNodeTraceItem; +use crate::nodes::context::{NodeContext, NodeContextExt}; +use crate::nodes::definition::NodeHandler; +use zen_expression::variable::Variable; +use zen_types::decision::TransformAttributes; + +#[derive(Debug, Clone)] +pub struct ExpressionNodeHandler; + +impl NodeHandler for ExpressionNodeHandler { + type NodeData = ExpressionNodeData; + type TraceData = ExpressionNodeTrace; + + fn transform_attributes( + &self, + ctx: &NodeContext, + ) -> Option { + Some(ctx.node.transform_attributes.clone()) + } + + async fn handle(&self, ctx: NodeContext) -> NodeResult { + let result = Variable::empty_object(); + let mut isolate = ctx.isolate(); + + for expression in ctx.node.expressions.iter() { + if expression.key.is_empty() || expression.value.is_empty() { + continue; + } + + let value = isolate + .run_standard(&expression.value) + .with_node_context(&ctx, |_| { + crate::compiled::exact::Failure::expression(&expression.value) + })?; + let value = match expression.value.contains('$') { + true => value.deep_clone(), + false => value, + }; + ctx.trace(|trace| { + trace.insert( + Rc::from(&*expression.key), + ExpressionNodeTraceItem { + result: value.clone(), + }, + ); + }); + + isolate.insert_dollar(&expression.key, value.clone()); + + result.dot_insert(&expression.key, value); + } + + ctx.success(result) + } +} diff --git a/core/engine/src/nodes/expression/mod.rs b/core/engine/src/nodes/expression/mod.rs index 40fd46ed..8abc94e4 100644 --- a/core/engine/src/nodes/expression/mod.rs +++ b/core/engine/src/nodes/expression/mod.rs @@ -1,67 +1,12 @@ +pub use crate::decision_graph::tracer::ExpressionNodeTraceItem; use crate::model::ExpressionNodeContent; -use crate::nodes::result::NodeResult; use ahash::HashMap; +#[cfg(feature = "driver")] +pub use handler::ExpressionNodeHandler; use std::rc::Rc; -use crate::nodes::context::{NodeContext, NodeContextExt}; -use crate::nodes::definition::NodeHandler; -use zen_expression::variable::{ToVariable, Variable}; -use zen_types::decision::TransformAttributes; - -#[derive(Debug, Clone)] -pub struct ExpressionNodeHandler; +#[cfg(feature = "driver")] +mod handler; pub type ExpressionNodeData = ExpressionNodeContent; pub type ExpressionNodeTrace = HashMap, ExpressionNodeTraceItem>; - -impl NodeHandler for ExpressionNodeHandler { - type NodeData = ExpressionNodeData; - type TraceData = ExpressionNodeTrace; - - fn transform_attributes( - &self, - ctx: &NodeContext, - ) -> Option { - Some(ctx.node.transform_attributes.clone()) - } - - async fn handle(&self, ctx: NodeContext) -> NodeResult { - let result = Variable::empty_object(); - let mut isolate = ctx.isolate(); - - for expression in ctx.node.expressions.iter() { - if expression.key.is_empty() || expression.value.is_empty() { - continue; - } - - let value = isolate - .run_standard(&expression.value) - .with_node_context(&ctx, |_| { - format!(r#"Failed to evaluate expression: "{}""#, &expression.value) - })?; - let value = match expression.value.contains('$') { - true => value.deep_clone(), - false => value, - }; - ctx.trace(|trace| { - trace.insert( - Rc::from(&*expression.key), - ExpressionNodeTraceItem { - result: value.clone(), - }, - ); - }); - - isolate.insert_dollar(&expression.key, value.clone()); - - result.dot_insert(&expression.key, value); - } - - ctx.success(result) - } -} - -#[derive(Debug, Clone, ToVariable)] -pub struct ExpressionNodeTraceItem { - result: Variable, -} diff --git a/core/engine/src/nodes/extensions.rs b/core/engine/src/nodes/extensions.rs index 4ee46328..a3fa0dfc 100644 --- a/core/engine/src/nodes/extensions.rs +++ b/core/engine/src/nodes/extensions.rs @@ -10,7 +10,6 @@ use crate::nodes::validator_cache::ValidatorCache; use anyhow::Context; use std::cell::OnceCell; use std::sync::Arc; -use zen_expression::OpcodeCache; /// This is created on every graph evaluation #[derive(Debug, Clone)] @@ -20,9 +19,11 @@ pub struct NodeHandlerExtensions { pub(crate) loader: DynamicLoader, pub(crate) custom_node: DynamicCustomNode, pub(crate) http_handler: DynamicHttpHandler, - pub(crate) compiled_cache: Option>, + #[cfg(feature = "driver")] + pub(crate) compiled_cache: Option>, pub(crate) stripped_functions: Option, Arc>>>, pub(crate) dt_indexes: Option, TableIndex>>>, + pub(crate) prepared: Arc, } impl Default for NodeHandlerExtensions { @@ -33,10 +34,12 @@ impl Default for NodeHandlerExtensions { loader: Arc::new(NoopLoader::default()), custom_node: Arc::new(NoopCustomNode::default()), + #[cfg(feature = "driver")] compiled_cache: None, stripped_functions: None, dt_indexes: None, http_handler: None, + prepared: Default::default(), } } } @@ -52,6 +55,7 @@ impl NodeHandlerExtensions { http_handler: self.http_handler.clone(), }), Box::new(ZenListener { + prepared: self.prepared.clone(), loader: self.loader.clone(), custom_node: self.custom_node.clone(), http_handler: self.http_handler.clone(), diff --git a/core/engine/src/nodes/function/mod.rs b/core/engine/src/nodes/function/mod.rs index e253e3a6..786fb6a2 100644 --- a/core/engine/src/nodes/function/mod.rs +++ b/core/engine/src/nodes/function/mod.rs @@ -1,4 +1,5 @@ pub mod http_handler; +pub(crate) mod purity; pub mod sleep; pub(crate) mod v1; pub(crate) mod v2; diff --git a/core/engine/src/nodes/function/purity.rs b/core/engine/src/nodes/function/purity.rs new file mode 100644 index 00000000..522acc42 --- /dev/null +++ b/core/engine/src/nodes/function/purity.rs @@ -0,0 +1,1771 @@ +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use swc_common::input::StringInput; +use swc_common::source_map::SmallPos; +use swc_common::{BytePos, GLOBALS}; +use swc_ecma_ast::{ + ArrowExpr, AssignTarget, AssignTargetPat, BinaryOp, BlockStmt, BlockStmtOrExpr, Callee, Decl, + Expr, ExprOrSpread, ForHead, Function, ImportDecl, ImportSpecifier, Lit, MemberExpr, + MemberProp, ModuleDecl, ModuleExportName, ModuleItem, ObjectPatProp, OptChainBase, Pat, Prop, + PropName, PropOrSpread, SimpleAssignTarget, Stmt, UnaryOp, VarDecl, VarDeclKind, VarDeclOrExpr, +}; +use swc_ecma_parser::{lexer::Lexer, EsSyntax, Parser, Syntax}; + +use super::v1::script::Session; + +pub(crate) struct Purity; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Dialect { + Script, + Module, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Lib { + Dayjs, + Big, + Zen, + Opaque, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Site { + TopFn, + TopConst, + Local, + Lib(Lib), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Class { + TopFn, + TopConst, + Local, + Lib(Lib), + Global, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Use { + Value, + Consumed, +} + +struct Walk { + dialect: Dialect, + collect: bool, + sites: HashMap>, + classes: HashMap, + pure: bool, +} + +impl Purity { + const LIMIT: usize = 256; + const RESERVED: &'static [&'static str] = + &["main", "now", "log", "console", "dayjs", "Big", "handler"]; + const BANNED: &'static [&'static str] = &[ + "__proto__", + "prototype", + "constructor", + "caller", + "callee", + "arguments", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__", + ]; + const VALUES: &'static [&'static str] = &["undefined", "NaN", "Infinity"]; + const CALLABLE: &'static [&'static str] = &[ + "Number", + "String", + "Boolean", + "parseFloat", + "parseInt", + "isNaN", + "isFinite", + "Array", + "Date", + "Error", + "TypeError", + "RangeError", + "encodeURIComponent", + "decodeURIComponent", + "encodeURI", + "decodeURI", + "BigInt", + "Symbol", + ]; + const CONSTRUCTORS: &'static [&'static str] = &[ + "Date", + "Map", + "Set", + "Array", + "Object", + "Error", + "TypeError", + "RangeError", + "RegExp", + "Number", + "String", + "Boolean", + "Promise", + ]; + const STATICS: &'static [(&'static str, &'static [&'static str])] = &[ + ( + "Object", + &["keys", "values", "entries", "fromEntries", "hasOwn", "is"], + ), + ( + "Math", + &[ + "abs", "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh", "cbrt", "ceil", + "clz32", "cos", "cosh", "exp", "expm1", "floor", "fround", "hypot", "imul", "log", + "log10", "log1p", "log2", "max", "min", "pow", "random", "round", "sign", "sin", + "sinh", "sqrt", "tan", "tanh", "trunc", + ], + ), + ("JSON", &["stringify", "parse"]), + ( + "Number", + &[ + "isInteger", + "isFinite", + "isNaN", + "isSafeInteger", + "parseFloat", + "parseInt", + ], + ), + ("Array", &["isArray", "from", "of"]), + ("String", &["fromCharCode", "fromCodePoint"]), + ("Date", &["now", "parse", "UTC"]), + ( + "Promise", + &["all", "allSettled", "any", "race", "reject", "resolve"], + ), + ]; + const MODULE_STATICS: &'static [(&'static str, &'static [&'static str])] = + &[("console", &["log"])]; + const CONSTANTS: &'static [(&'static str, &'static [&'static str])] = &[ + ( + "Math", + &[ + "PI", "E", "LN2", "LN10", "LOG2E", "LOG10E", "SQRT1_2", "SQRT2", + ], + ), + ( + "Number", + &[ + "MAX_SAFE_INTEGER", + "MIN_SAFE_INTEGER", + "EPSILON", + "MAX_VALUE", + "MIN_VALUE", + "POSITIVE_INFINITY", + "NEGATIVE_INFINITY", + "NaN", + ], + ), + ]; + const MODULE_CONSTANTS: &'static [(&'static str, &'static [&'static str])] = + &[("config", &["iteration", "maxDepth", "trace"])]; + const METHODS: &'static [&'static str] = &[ + "at", + "concat", + "entries", + "every", + "filter", + "find", + "findIndex", + "findLast", + "findLastIndex", + "flat", + "flatMap", + "forEach", + "includes", + "indexOf", + "join", + "keys", + "lastIndexOf", + "map", + "reduce", + "reduceRight", + "slice", + "some", + "values", + "toReversed", + "toSorted", + "toSpliced", + "with", + "push", + "pop", + "shift", + "unshift", + "splice", + "sort", + "reverse", + "fill", + "charAt", + "charCodeAt", + "codePointAt", + "endsWith", + "localeCompare", + "match", + "matchAll", + "normalize", + "padEnd", + "padStart", + "repeat", + "replace", + "replaceAll", + "search", + "split", + "startsWith", + "substring", + "substr", + "toLowerCase", + "toUpperCase", + "trim", + "trimStart", + "trimEnd", + "toFixed", + "toPrecision", + "toExponential", + "toString", + "valueOf", + "hasOwnProperty", + "has", + "set", + "add", + "delete", + "clear", + "getTime", + "getFullYear", + "getMonth", + "getDate", + "getDay", + "getHours", + "getMinutes", + "getSeconds", + "getMilliseconds", + "getUTCFullYear", + "getUTCMonth", + "getUTCDate", + "getUTCDay", + "getUTCHours", + "getUTCMinutes", + "getUTCSeconds", + "getUTCMilliseconds", + "getTimezoneOffset", + "toISOString", + "toJSON", + "toDateString", + "toTimeString", + "toUTCString", + "test", + "exec", + "abs", + "cmp", + "div", + "eq", + "gt", + "gte", + "lt", + "lte", + "minus", + "mul", + "neg", + "plus", + "pow", + "prec", + "round", + "sqrt", + "sub", + "times", + "toNumber", + "subtract", + "format", + "diff", + "isBefore", + "isAfter", + "isSame", + "isValid", + "startOf", + "endOf", + "year", + "month", + "date", + "day", + "hour", + "minute", + "second", + "millisecond", + "unix", + "toDate", + "daysInMonth", + "clone", + "utcOffset", + ]; + const MEMBERS: &'static [&'static str] = &[ + "$g", + "$locale", + "$set", + "$utils", + "abs", + "add", + "anchor", + "apply", + "at", + "big", + "bind", + "blink", + "bold", + "call", + "charAt", + "charCodeAt", + "clear", + "clone", + "cmp", + "codePointAt", + "compile", + "concat", + "copyWithin", + "date", + "day", + "daysInMonth", + "delete", + "diff", + "div", + "endOf", + "endsWith", + "entries", + "eq", + "every", + "exec", + "fill", + "filter", + "finally", + "find", + "findIndex", + "findLast", + "findLastIndex", + "fixed", + "flat", + "flatMap", + "fontcolor", + "fontsize", + "forEach", + "format", + "get", + "getDate", + "getDay", + "getFullYear", + "getHours", + "getMilliseconds", + "getMinutes", + "getMonth", + "getSeconds", + "getTime", + "getTimezoneOffset", + "getUTCDate", + "getUTCDay", + "getUTCFullYear", + "getUTCHours", + "getUTCMilliseconds", + "getUTCMinutes", + "getUTCMonth", + "getUTCSeconds", + "getYear", + "gt", + "gte", + "has", + "hasOwnProperty", + "hour", + "includes", + "indexOf", + "init", + "isAfter", + "isBefore", + "isPrototypeOf", + "isSame", + "isValid", + "isWellFormed", + "italics", + "join", + "keys", + "lastIndexOf", + "link", + "locale", + "localeCompare", + "lt", + "lte", + "map", + "match", + "matchAll", + "millisecond", + "minus", + "minute", + "mod", + "month", + "mul", + "neg", + "next", + "normalize", + "padEnd", + "padStart", + "parse", + "plus", + "pop", + "pow", + "prec", + "propertyIsEnumerable", + "push", + "reduce", + "reduceRight", + "repeat", + "replace", + "replaceAll", + "reverse", + "round", + "search", + "second", + "set", + "setDate", + "setFullYear", + "setHours", + "setMilliseconds", + "setMinutes", + "setMonth", + "setSeconds", + "setTime", + "setUTCDate", + "setUTCFullYear", + "setUTCHours", + "setUTCMilliseconds", + "setUTCMinutes", + "setUTCMonth", + "setUTCSeconds", + "setYear", + "shift", + "slice", + "small", + "some", + "sort", + "splice", + "split", + "sqrt", + "startOf", + "startsWith", + "strike", + "sub", + "subtract", + "substr", + "substring", + "sup", + "test", + "then", + "times", + "toDate", + "toDateString", + "toExponential", + "toFixed", + "toGMTString", + "toISOString", + "toJSON", + "toLocaleDateString", + "toLocaleLowerCase", + "toLocaleString", + "toLocaleTimeString", + "toLocaleUpperCase", + "toLowerCase", + "toNumber", + "toPrecision", + "toReversed", + "toSorted", + "toSpliced", + "toString", + "toTimeString", + "toUTCString", + "toUpperCase", + "toWellFormed", + "trim", + "trimEnd", + "trimLeft", + "trimRight", + "trimStart", + "unix", + "unshift", + "utcOffset", + "valueOf", + "values", + "with", + "year", + "catch", + "drop", + "take", + "toArray", + "throw", + "return", + "union", + "intersection", + "difference", + "symmetricDifference", + "isSubsetOf", + "isSupersetOf", + "isDisjointFrom", + "getOrInsert", + "getOrInsertComputed", + ]; + + const ZEN: &'static [&'static str] = + &["evaluate", "evaluateExpression", "evaluateUnaryExpression"]; + const BIG_CONSTANTS: &'static [&'static str] = + &["roundDown", "roundHalfUp", "roundHalfEven", "roundUp"]; + + thread_local! { + static LAYOUTS: RefCell, Option>>> = RefCell::new(HashMap::new()); + } + + pub(crate) fn layout(source: &str) -> Option> { + if let Some(cached) = Self::LAYOUTS.with_borrow(|layouts| layouts.get(source).cloned()) { + return cached; + } + let layout = Self::analyze(source).then(|| Self::blank(source)); + Self::LAYOUTS.with_borrow_mut(|layouts| { + if layouts.len() >= Self::LIMIT { + layouts.clear(); + } + layouts.insert(Rc::from(source), layout.clone()); + }); + layout + } + + fn blank(source: &str) -> Rc { + let blank: String = source + .bytes() + .map(|byte| if byte == b'\n' { '\n' } else { ' ' }) + .collect(); + Rc::from(blank) + } + + fn analyze(source: &str) -> bool { + if source.contains(['\r', '\u{2028}', '\u{2029}']) + || source.contains("\\\n") + || source.contains(Session::ROW) + { + return false; + } + GLOBALS.set(&Default::default(), || { + let lexer = Lexer::new( + Syntax::Es(EsSyntax::default()), + Default::default(), + StringInput::new( + source, + BytePos::from_usize(0), + BytePos::from_usize(source.len()), + ), + None, + ); + let mut parser = Parser::new_from(lexer); + match parser.parse_script() { + Ok(script) if parser.take_errors().is_empty() => Walk::script(&script.body), + _ => false, + } + }) + } + + pub(crate) fn module(source: &str) -> bool { + GLOBALS.set(&Default::default(), || { + let lexer = Lexer::new( + Syntax::Es(EsSyntax::default()), + Default::default(), + StringInput::new( + source, + BytePos::from_usize(0), + BytePos::from_usize(source.len()), + ), + None, + ); + let mut parser = Parser::new_from(lexer); + match parser.parse_module() { + Ok(module) if parser.take_errors().is_empty() => Walk::module(&module.body), + _ => false, + } + }) + } + + fn listed(table: &[(&str, &[&str])], owner: &str, name: &str) -> bool { + table + .iter() + .any(|(listed, names)| *listed == owner && names.contains(&name)) + } + + fn library(source: &str, specifier: &ImportSpecifier) -> Lib { + let imported = match specifier { + ImportSpecifier::Default(_) => Some("default"), + ImportSpecifier::Namespace(_) => None, + ImportSpecifier::Named(named) => match &named.imported { + None => Some(named.local.sym.as_ref()), + Some(ModuleExportName::Ident(ident)) => Some(ident.sym.as_ref()), + Some(ModuleExportName::Str(_)) => None, + }, + }; + match (source, imported) { + ("dayjs", Some("default")) => Lib::Dayjs, + ("big.js", Some("default" | "Big")) => Lib::Big, + ("zen", Some("default") | None) => Lib::Zen, + _ => Lib::Opaque, + } + } +} + +impl Walk { + fn new(dialect: Dialect) -> Self { + Walk { + dialect, + collect: true, + sites: HashMap::new(), + classes: HashMap::new(), + pure: true, + } + } + + fn script(body: &[Stmt]) -> bool { + let mut decls = Vec::new(); + for stmt in body { + match stmt { + Stmt::Decl(decl) => decls.push(decl), + Stmt::Empty(_) => {} + _ => return false, + } + } + Walk::new(Dialect::Script).walk(&decls) + } + + fn module(items: &[ModuleItem]) -> bool { + let mut walk = Walk::new(Dialect::Module); + let mut decls = Vec::new(); + for item in items { + match item { + ModuleItem::ModuleDecl(ModuleDecl::Import(import)) => walk.import(import), + ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export)) => decls.push(&export.decl), + ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(named)) if named.src.is_none() => {} + ModuleItem::Stmt(Stmt::Decl(decl)) => decls.push(decl), + ModuleItem::Stmt(Stmt::Empty(_)) => {} + _ => return false, + } + } + walk.walk(&decls) + } + + fn walk(mut self, decls: &[&Decl]) -> bool { + if !self.top(decls) { + return false; + } + self.top_level(decls); + if !self.classify() { + return false; + } + self.collect = false; + self.top_level(decls); + self.pure + } + + fn import(&mut self, import: &ImportDecl) { + let source = import.src.value.to_string_lossy(); + for specifier in &import.specifiers { + let local = match specifier { + ImportSpecifier::Named(named) => &named.local, + ImportSpecifier::Default(default) => &default.local, + ImportSpecifier::Namespace(namespace) => &namespace.local, + }; + self.site( + local.sym.as_ref(), + Site::Lib(Purity::library(&source, specifier)), + ); + } + } + + fn top(&self, decls: &[&Decl]) -> bool { + let mut handlers = 0; + for decl in decls { + match decl { + Decl::Fn(declared) => { + let name = declared.ident.sym.as_ref(); + handlers += usize::from(name == "handler"); + if !self.declarable(name) { + return false; + } + } + Decl::Var(var) if var.kind == VarDeclKind::Const => { + for declarator in &var.decls { + let (Pat::Ident(binding), Some(init)) = + (&declarator.name, &declarator.init) + else { + return false; + }; + let name = binding.id.sym.as_ref(); + if name == "handler" { + if !matches!(&**init, Expr::Arrow(_) | Expr::Fn(_)) { + return false; + } + handlers += 1; + } else if !self.declarable(name) || !Self::inert(init) { + return false; + } + } + } + _ => return false, + } + } + self.dialect == Dialect::Module || handlers == 1 + } + + fn declarable(&self, name: &str) -> bool { + self.dialect == Dialect::Module || name == "handler" || !Purity::RESERVED.contains(&name) + } + + fn inert(expr: &Expr) -> bool { + match expr { + Expr::Lit(Lit::Regex(_)) => false, + Expr::Lit(_) => true, + Expr::Tpl(template) => template.exprs.is_empty(), + Expr::Arrow(_) | Expr::Fn(_) => true, + Expr::Paren(inner) => Self::inert(&inner.expr), + Expr::Unary(unary) if matches!(unary.op, UnaryOp::Minus | UnaryOp::Plus) => { + Self::inert(&unary.arg) + } + _ => false, + } + } + + fn classify(&mut self) -> bool { + for (name, sites) in &self.sites { + let Some(&first) = sites.first() else { + return false; + }; + if sites.iter().any(|site| *site != first) { + return false; + } + let class = match first { + Site::TopFn => Class::TopFn, + Site::TopConst => Class::TopConst, + Site::Local => Class::Local, + Site::Lib(lib) => Class::Lib(lib), + }; + self.classes.insert(name.clone(), class); + } + true + } + + fn class(&self, name: &str) -> Class { + match (self.classes.get(name), self.dialect, name) { + (Some(class), _, _) => *class, + (None, Dialect::Script, "dayjs") => Class::Lib(Lib::Dayjs), + (None, Dialect::Script, "Big") => Class::Lib(Lib::Big), + (None, _, _) => Class::Global, + } + } + + fn site(&mut self, name: &str, site: Site) { + if self.collect { + self.sites.entry(name.to_string()).or_default().push(site); + } + } + + fn reject(&mut self) { + self.check(false); + } + + fn check(&mut self, ok: bool) { + if !self.collect { + self.pure &= ok; + } + } + + fn top_level(&mut self, decls: &[&Decl]) { + for decl in decls { + match decl { + Decl::Fn(declared) => { + let handler = declared.ident.sym.as_ref() == "handler"; + self.site(declared.ident.sym.as_ref(), Site::TopFn); + self.function(&declared.function, handler); + } + Decl::Var(var) => { + for declarator in &var.decls { + let (Pat::Ident(binding), Some(init)) = + (&declarator.name, &declarator.init) + else { + continue; + }; + let name = binding.id.sym.as_ref(); + let handler = name == "handler"; + match &**init { + Expr::Arrow(arrow) => { + self.site(name, Site::TopFn); + self.arrow(arrow, handler); + } + Expr::Fn(function) => { + self.site(name, Site::TopFn); + if let Some(ident) = &function.ident { + self.site(ident.sym.as_ref(), Site::Local); + } + self.function(&function.function, handler); + } + _ => self.site(name, Site::TopConst), + } + } + } + _ => {} + } + } + } + + fn function(&mut self, function: &Function, handler: bool) { + if function.is_generator + || !function.decorators.is_empty() + || !self.awaits(function.is_async) + { + return self.reject(); + } + let params: Vec<&Pat> = function.params.iter().map(|param| ¶m.pat).collect(); + self.check( + function + .params + .iter() + .all(|param| param.decorators.is_empty()), + ); + self.params(¶ms, handler); + match &function.body { + Some(body) => self.block(body), + None => self.reject(), + } + } + + fn arrow(&mut self, arrow: &ArrowExpr, handler: bool) { + if arrow.is_generator || !self.awaits(arrow.is_async) { + return self.reject(); + } + let params: Vec<&Pat> = arrow.params.iter().collect(); + self.params(¶ms, handler); + match &*arrow.body { + BlockStmtOrExpr::BlockStmt(body) => self.block(body), + BlockStmtOrExpr::Expr(expr) => self.expr(expr, Use::Value), + } + } + + fn awaits(&self, asynchronous: bool) -> bool { + !asynchronous || self.dialect == Dialect::Module + } + + fn params(&mut self, params: &[&Pat], handler: bool) { + for (index, param) in params.iter().enumerate() { + if handler && index == 1 && self.dialect == Dialect::Script { + self.helpers(param); + } else { + self.pat(param); + } + } + } + + fn helpers(&mut self, pat: &Pat) { + let Pat::Object(object) = pat else { + return self.reject(); + }; + for prop in &object.props { + let (key, binding) = match prop { + ObjectPatProp::Assign(assign) if assign.value.is_none() => { + (assign.key.id.sym.as_ref(), assign.key.id.sym.as_ref()) + } + ObjectPatProp::KeyValue(pair) => match (&pair.key, &*pair.value) { + (PropName::Ident(key), Pat::Ident(binding)) => { + (key.sym.as_ref(), binding.id.sym.as_ref()) + } + _ => return self.reject(), + }, + _ => return self.reject(), + }; + let site = match key { + "moment" | "dayjs" => Site::Lib(Lib::Dayjs), + "Big" => Site::Lib(Lib::Big), + "env" => Site::Local, + _ => return self.reject(), + }; + self.site(binding, site); + } + } + + fn pat(&mut self, pat: &Pat) { + match pat { + Pat::Ident(binding) => self.site(binding.id.sym.as_ref(), Site::Local), + Pat::Array(array) => { + for element in array.elems.iter().flatten() { + self.pat(element); + } + } + Pat::Rest(rest) => self.pat(&rest.arg), + Pat::Object(object) => { + for prop in &object.props { + match prop { + ObjectPatProp::KeyValue(pair) => { + self.key(&pair.key, true); + self.pat(&pair.value); + } + ObjectPatProp::Assign(assign) => { + let name = assign.key.id.sym.as_ref(); + self.check( + !Purity::BANNED.contains(&name) && !Purity::MEMBERS.contains(&name), + ); + self.site(name, Site::Local); + if let Some(value) = &assign.value { + self.expr(value, Use::Value); + } + } + ObjectPatProp::Rest(rest) => self.pat(&rest.arg), + } + } + } + Pat::Assign(assign) => { + self.pat(&assign.left); + self.expr(&assign.right, Use::Value); + } + Pat::Expr(_) | Pat::Invalid(_) => self.reject(), + } + } + + fn key(&mut self, key: &PropName, read: bool) { + match key { + PropName::Ident(ident) => { + let name = ident.sym.as_ref(); + self.check( + name != "__proto__" + && !(read + && (Purity::BANNED.contains(&name) || Purity::MEMBERS.contains(&name))), + ); + } + PropName::Str(text) => { + let name = text.value.to_string_lossy(); + self.check( + name != "__proto__" + && !(read + && (Purity::BANNED.contains(&name.as_ref()) + || Purity::MEMBERS.contains(&name.as_ref()))), + ); + } + PropName::Num(_) | PropName::BigInt(_) => {} + PropName::Computed(computed) => match read { + true => self.reject(), + false => self.expr(&computed.expr, Use::Value), + }, + } + } + + fn block(&mut self, block: &BlockStmt) { + for stmt in &block.stmts { + self.stmt(stmt); + } + } + + fn var(&mut self, var: &VarDecl) { + if var.declare { + return self.reject(); + } + for declarator in &var.decls { + self.pat(&declarator.name); + if let Some(init) = &declarator.init { + self.expr(init, Use::Value); + } + } + } + + fn stmt(&mut self, stmt: &Stmt) { + match stmt { + Stmt::Block(block) => self.block(block), + Stmt::Empty(_) | Stmt::Debugger(_) | Stmt::Break(_) | Stmt::Continue(_) => {} + Stmt::Return(ret) => { + if let Some(arg) = &ret.arg { + self.expr(arg, Use::Value); + } + } + Stmt::Labeled(labeled) => self.stmt(&labeled.body), + Stmt::If(branch) => { + self.expr(&branch.test, Use::Consumed); + self.stmt(&branch.cons); + if let Some(alt) = &branch.alt { + self.stmt(alt); + } + } + Stmt::Switch(switch) => { + self.expr(&switch.discriminant, Use::Consumed); + for case in &switch.cases { + if let Some(test) = &case.test { + self.expr(test, Use::Consumed); + } + for stmt in &case.cons { + self.stmt(stmt); + } + } + } + Stmt::Throw(throw) => self.expr(&throw.arg, Use::Value), + Stmt::Try(attempt) => { + self.block(&attempt.block); + if let Some(handler) = &attempt.handler { + if let Some(param) = &handler.param { + self.pat(param); + } + self.block(&handler.body); + } + if let Some(finalizer) = &attempt.finalizer { + self.block(finalizer); + } + } + Stmt::While(looped) => { + self.expr(&looped.test, Use::Consumed); + self.stmt(&looped.body); + } + Stmt::DoWhile(looped) => { + self.stmt(&looped.body); + self.expr(&looped.test, Use::Consumed); + } + Stmt::For(looped) => { + match &looped.init { + Some(VarDeclOrExpr::VarDecl(var)) => self.var(var), + Some(VarDeclOrExpr::Expr(expr)) => self.expr(expr, Use::Value), + None => {} + } + if let Some(test) = &looped.test { + self.expr(test, Use::Consumed); + } + if let Some(update) = &looped.update { + self.expr(update, Use::Value); + } + self.stmt(&looped.body); + } + Stmt::ForIn(looped) => { + self.head(&looped.left); + self.expr(&looped.right, Use::Value); + self.stmt(&looped.body); + } + Stmt::ForOf(looped) => { + if looped.is_await { + return self.reject(); + } + self.head(&looped.left); + self.expr(&looped.right, Use::Value); + self.stmt(&looped.body); + } + Stmt::Decl(Decl::Var(var)) => self.var(var), + Stmt::Decl(Decl::Fn(decl)) => { + if decl.declare { + return self.reject(); + } + self.site(decl.ident.sym.as_ref(), Site::Local); + self.function(&decl.function, false); + } + Stmt::Expr(expr) => self.expr(&expr.expr, Use::Value), + Stmt::With(_) | Stmt::Decl(_) => self.reject(), + } + } + + fn head(&mut self, head: &ForHead) { + match head { + ForHead::VarDecl(var) => self.var(var), + ForHead::Pat(pat) => self.target_pat(pat), + ForHead::UsingDecl(_) => self.reject(), + } + } + + fn name(prop: &MemberProp) -> Option { + match prop { + MemberProp::Ident(ident) => Some(ident.sym.to_string()), + MemberProp::Computed(computed) => match &*computed.expr { + Expr::Lit(Lit::Str(text)) => Some(text.value.to_string_lossy().into_owned()), + Expr::Lit(Lit::Num(number)) => Some(number.value.to_string()), + _ => None, + }, + MemberProp::PrivateName(_) => None, + } + } + + fn global(&self, expr: &Expr) -> Option<(Class, String)> { + match expr { + Expr::Ident(ident) => Some((self.class(ident.sym.as_ref()), ident.sym.to_string())), + Expr::Paren(inner) => self.global(&inner.expr), + _ => None, + } + } + + fn member(&mut self, member: &MemberExpr, usage: Use) { + let Some(name) = Self::name(&member.prop) else { + return self.reject(); + }; + if Purity::BANNED.contains(&name.as_str()) { + return self.reject(); + } + if let Some((class, object)) = self.global(&member.obj) { + match class { + Class::Global | Class::Lib(_) | Class::TopFn => { + let constant = match class { + Class::Global => { + Purity::listed(Purity::CONSTANTS, &object, &name) + || (self.dialect == Dialect::Module + && Purity::listed(Purity::MODULE_CONSTANTS, &object, &name)) + } + Class::Lib(Lib::Big) => Purity::BIG_CONSTANTS.contains(&name.as_str()), + _ => false, + }; + return self.check(constant); + } + Class::TopConst | Class::Local => {} + } + } + if usage == Use::Value && Purity::MEMBERS.contains(&name.as_str()) { + return self.reject(); + } + self.expr(&member.obj, Use::Value); + } + + fn args(&mut self, args: &[ExprOrSpread]) { + for arg in args { + self.expr(&arg.expr, Use::Value); + } + } + + fn call(&mut self, callee: &Expr, args: &[ExprOrSpread]) { + match callee { + Expr::Paren(inner) => return self.call(&inner.expr, args), + Expr::Arrow(arrow) => self.arrow(arrow, false), + Expr::Fn(function) => { + if let Some(ident) = &function.ident { + self.site(ident.sym.as_ref(), Site::Local); + } + self.function(&function.function, false); + } + Expr::Ident(ident) => { + let name = ident.sym.as_ref(); + let allowed = match self.class(name) { + Class::Local | Class::TopFn | Class::TopConst => true, + Class::Lib(Lib::Big) => { + args.len() <= 1 && args.iter().all(|arg| arg.spread.is_none()) + } + Class::Lib(Lib::Dayjs) => Self::dated(args), + Class::Lib(Lib::Zen | Lib::Opaque) => false, + Class::Global => Purity::CALLABLE.contains(&name), + }; + self.check(allowed); + } + Expr::Member(member) => self.method(member), + Expr::OptChain(chain) => match &*chain.base { + OptChainBase::Member(member) => self.method(member), + OptChainBase::Call(_) => self.reject(), + }, + _ => self.reject(), + } + self.args(args); + } + + fn dated(args: &[ExprOrSpread]) -> bool { + if args.iter().any(|arg| arg.spread.is_some()) { + return false; + } + match args { + [] | [_] => true, + [_, format] => matches!(&*format.expr, Expr::Lit(Lit::Str(_))), + _ => false, + } + } + + fn method(&mut self, member: &MemberExpr) { + let Some(name) = Self::name(&member.prop) else { + return self.reject(); + }; + if let Some((class, object)) = self.global(&member.obj) { + match class { + Class::Global => { + let allowed = Purity::listed(Purity::STATICS, &object, &name) + || (self.dialect == Dialect::Module + && Purity::listed(Purity::MODULE_STATICS, &object, &name)); + return self.check(allowed); + } + Class::Lib(Lib::Dayjs) => { + return self.check(matches!(name.as_str(), "unix" | "isDayjs")) + } + Class::Lib(Lib::Zen) => return self.check(Purity::ZEN.contains(&name.as_str())), + Class::Lib(Lib::Big | Lib::Opaque) | Class::TopFn => return self.reject(), + Class::TopConst | Class::Local => {} + } + } + if !Purity::METHODS.contains(&name.as_str()) { + return self.reject(); + } + self.expr(&member.obj, Use::Value); + } + + fn target(&mut self, target: &SimpleAssignTarget) { + match target { + SimpleAssignTarget::Ident(binding) => { + let local = self.class(binding.id.sym.as_ref()) == Class::Local; + self.check(local); + } + SimpleAssignTarget::Member(member) => self.written(member), + SimpleAssignTarget::Paren(inner) => match &*inner.expr { + Expr::Ident(ident) => { + let local = self.class(ident.sym.as_ref()) == Class::Local; + self.check(local); + } + Expr::Member(member) => self.written(member), + _ => self.reject(), + }, + _ => self.reject(), + } + } + + fn written(&mut self, member: &MemberExpr) { + let Some(name) = Self::name(&member.prop) else { + return self.reject(); + }; + if Purity::BANNED.contains(&name.as_str()) || name.starts_with('$') { + return self.reject(); + } + self.expr(&member.obj, Use::Value); + } + + fn target_pat(&mut self, pat: &Pat) { + match pat { + Pat::Ident(binding) => { + let local = self.class(binding.id.sym.as_ref()) == Class::Local; + self.check(local); + } + Pat::Expr(expr) => match &**expr { + Expr::Member(member) => self.written(member), + Expr::Ident(ident) => { + let local = self.class(ident.sym.as_ref()) == Class::Local; + self.check(local); + } + _ => self.reject(), + }, + Pat::Array(array) => { + for element in array.elems.iter().flatten() { + self.target_pat(element); + } + } + Pat::Rest(rest) => self.target_pat(&rest.arg), + Pat::Object(object) => { + for prop in &object.props { + match prop { + ObjectPatProp::KeyValue(pair) => { + self.key(&pair.key, true); + self.target_pat(&pair.value); + } + ObjectPatProp::Assign(assign) => { + let name = assign.key.id.sym.as_ref(); + let local = self.class(name) == Class::Local; + self.check(local); + self.check( + !Purity::BANNED.contains(&name) && !Purity::MEMBERS.contains(&name), + ); + if let Some(value) = &assign.value { + self.expr(value, Use::Value); + } + } + ObjectPatProp::Rest(rest) => self.target_pat(&rest.arg), + } + } + } + Pat::Assign(assign) => { + self.target_pat(&assign.left); + self.expr(&assign.right, Use::Value); + } + Pat::Invalid(_) => self.reject(), + } + } + + fn ident(&mut self, name: &str, usage: Use) { + if self.collect { + return; + } + let allowed = match self.class(name) { + Class::Local | Class::TopConst => true, + Class::TopFn | Class::Lib(_) => usage == Use::Consumed, + Class::Global => { + let reserved = self.dialect == Dialect::Script && Purity::RESERVED.contains(&name); + Purity::VALUES.contains(&name) + || (usage == Use::Consumed && name != "arguments" && !reserved) + } + }; + self.check(allowed); + } + + fn expr(&mut self, expr: &Expr, usage: Use) { + match expr { + Expr::Lit(_) => {} + Expr::Ident(ident) => self.ident(ident.sym.as_ref(), usage), + Expr::Paren(inner) => self.expr(&inner.expr, usage), + Expr::Array(array) => { + for element in array.elems.iter().flatten() { + self.expr(&element.expr, Use::Value); + } + } + Expr::Object(object) => { + for prop in &object.props { + match prop { + PropOrSpread::Spread(spread) => self.expr(&spread.expr, Use::Value), + PropOrSpread::Prop(prop) => match &**prop { + Prop::Shorthand(ident) => { + self.check(ident.sym.as_ref() != "__proto__"); + self.ident(ident.sym.as_ref(), Use::Value); + } + Prop::KeyValue(pair) => { + self.key(&pair.key, false); + self.expr(&pair.value, Use::Value); + } + Prop::Getter(getter) => { + self.key(&getter.key, false); + match &getter.body { + Some(body) => self.block(body), + None => self.reject(), + } + } + Prop::Setter(setter) => { + self.key(&setter.key, false); + if setter.this_param.is_some() { + return self.reject(); + } + self.pat(&setter.param); + match &setter.body { + Some(body) => self.block(body), + None => self.reject(), + } + } + Prop::Method(method) => { + self.key(&method.key, false); + self.function(&method.function, false); + } + Prop::Assign(_) => self.reject(), + }, + } + } + } + Expr::Fn(function) => { + if let Some(ident) = &function.ident { + self.site(ident.sym.as_ref(), Site::Local); + } + self.function(&function.function, false); + } + Expr::Arrow(arrow) => self.arrow(arrow, false), + Expr::Unary(unary) => match unary.op { + UnaryOp::Delete => match &*unary.arg { + Expr::Member(member) => self.written(member), + _ => self.reject(), + }, + _ => self.expr(&unary.arg, Use::Consumed), + }, + Expr::Update(update) => match &*update.arg { + Expr::Ident(ident) => { + let local = self.class(ident.sym.as_ref()) == Class::Local; + self.check(local); + } + Expr::Member(member) => self.written(member), + _ => self.reject(), + }, + Expr::Bin(bin) => match bin.op { + BinaryOp::LogicalOr | BinaryOp::LogicalAnd | BinaryOp::NullishCoalescing => { + self.expr(&bin.left, usage); + self.expr(&bin.right, usage); + } + BinaryOp::In => { + self.expr(&bin.left, Use::Consumed); + self.expr(&bin.right, Use::Value); + } + BinaryOp::InstanceOf => { + self.expr(&bin.left, Use::Consumed); + let constructor = match self.global(&bin.right) { + Some((Class::Global, name)) => { + Purity::CONSTRUCTORS.contains(&name.as_str()) + } + Some((Class::Lib(Lib::Big), _)) => true, + _ => false, + }; + if !constructor { + self.expr(&bin.right, Use::Value); + } + } + _ => { + self.expr(&bin.left, Use::Consumed); + self.expr(&bin.right, Use::Consumed); + } + }, + Expr::Assign(assign) => { + match &assign.left { + AssignTarget::Simple(target) => self.target(target), + AssignTarget::Pat(AssignTargetPat::Array(array)) => { + for element in array.elems.iter().flatten() { + self.target_pat(element); + } + } + AssignTarget::Pat(AssignTargetPat::Object(object)) => { + self.target_pat(&Pat::Object(object.clone())); + } + AssignTarget::Pat(AssignTargetPat::Invalid(_)) => self.reject(), + } + self.expr(&assign.right, Use::Value); + } + Expr::Member(member) => self.member(member, usage), + Expr::Cond(cond) => { + self.expr(&cond.test, Use::Consumed); + self.expr(&cond.cons, usage); + self.expr(&cond.alt, usage); + } + Expr::Call(call) => match &call.callee { + Callee::Expr(callee) => self.call(callee, &call.args), + Callee::Super(_) | Callee::Import(_) => self.reject(), + }, + Expr::New(new) => { + let constructor = match self.global(&new.callee) { + Some((Class::Global, name)) => Purity::CONSTRUCTORS.contains(&name.as_str()), + Some((Class::Lib(Lib::Big), _)) => true, + _ => false, + }; + self.check(constructor); + if let Some(args) = &new.args { + self.args(args); + } + } + Expr::Seq(seq) => { + let last = seq.exprs.len().saturating_sub(1); + for (index, expr) in seq.exprs.iter().enumerate() { + self.expr(expr, if index == last { usage } else { Use::Consumed }); + } + } + Expr::Tpl(template) => { + for expr in &template.exprs { + self.expr(expr, Use::Consumed); + } + } + Expr::Await(awaited) if self.dialect == Dialect::Module => { + self.expr(&awaited.arg, Use::Value) + } + Expr::OptChain(chain) => match &*chain.base { + OptChainBase::Member(member) => self.member(member, usage), + OptChainBase::Call(call) => self.call(&call.callee, &call.args), + }, + _ => self.reject(), + } + } +} + +#[cfg(test)] +mod tests { + use super::Purity; + use crate::nodes::function::v2::serde::{JsValue, JsValueWithNodes}; + use crate::nodes::NodeHandlerExtensions; + use zen_expression::Variable; + + #[test] + fn plain_modules_share_a_runtime() { + let sources = [ + "export const handler = async (input) => { let x = 1; x++; return { x, y: `a${input.a}b` }; };", + "const RATE = 0.2\nexport async function handler(input) { return { v: input.v * RATE } }", + "function helper(a) { return a + 1 }\nexport const handler = (input) => ({ v: helper(input.v) })", + "import dayjs from 'dayjs';\nexport const handler = async (input) => { const out = {}; out.at = dayjs(input.when).format(); const list = []; list.push(1); input.seen = true; return { out, list }; };", + "export const handler = async (input) => { const items = input.items.map((i) => ({ ...i, total: i.qty * i.price })); items.sort((a, b) => a.total - b.total); return { items }; };", + "export const handler = async (input) => ({ hello: 'world', multiplied: input.input * 2 })", + "import zen from 'zen';\n\n/** @type {Handler} **/\nexport const handler = async (input) => {\n return {\n functionParentNodes: input['$nodes'].request['$nodes']\n, functionRequest: input['$nodes'].request\n };\n};\n", + "import Big from 'big.js';\nexport const handler = async (input) => {\n const total = input.items.reduce((sum, item) => sum.plus(Big(item.price).times(item.qty)), Big(0));\n console.log('total', total.toString());\n return { total: total.toNumber(), depth: config.maxDepth };\n};", + "import zen from 'zen';\nexport const handler = async (input) => {\n const helper = async (value) => value * 2;\n const doubled = await helper(input.n);\n return { doubled, sum: await zen.evaluateExpression('a + b', { a: 1, b: input.n }) };\n};", + "import zen from 'zen';\nexport const handler = async (input) => zen.evaluate('child', input)", + "export const handler = async (input) => ({ v: await Promise.resolve(input.n) })", + "export const handler = async (input) => { let i = 0; while (input.spin) { i++; } return { ok: true, i }; };", + "export const handler = async (input) => { const all = await Promise.allSettled([Promise.reject(new Error('x')), Promise.resolve(1)]); return { first: await Promise.race([Promise.resolve(input.n)]), n: all.length } }", + "export const handler = async (input) => ({ v: await new Promise((resolve) => resolve(input.n)) })", + "export const handler = async (input) => ({ big: BigInt(input.n) * 2n, id: Symbol('x').toString() })", + "import Big from 'big.js';\nexport const handler = async (input) => ({ v: Big(input.n).round(2, Big.roundHalfEven).toNumber() })", + ]; + for source in sources { + assert!(Purity::module(source), "{source}"); + } + } + + #[test] + fn shared_state_needs_a_fresh_runtime() { + let sources = [ + "let count = 0;\nexport const handler = async () => ({ n: ++count });", + "const cache = new Map();\nexport const handler = async (input) => { cache.set(1, 2); return {}; };", + "const seen = {};\nexport const handler = async (input) => ({ first: !seen.x });", + "export const handler = async () => { globalThis.flag = 1; return {}; };", + "var hits = 0\nexport const handler = () => ({ hits: hits++ })", + "Array.prototype.last = function () { return this[this.length - 1]; };\nexport const handler = () => ({})", + "console.log('loaded');\nexport const handler = () => ({})", + "const LIMIT = 5, queue = [];\nexport const handler = () => { queue.push(1); return { n: queue.length } }", + "const counter = (() => { let n = 0; return () => ++n; })();\nexport const handler = () => ({ n: counter() })", + "function helper() { helper.calls = (helper.calls || 0) + 1; return helper.calls }\nexport const handler = () => ({ n: helper() })", + "export const handler = () => { Math.seen = (Math.seen || 0) + 1; return { n: Math.seen } }", + "import Big from 'big.js';\nexport const handler = () => { Big.DP = 2; return {} }", + "import dayjs from 'dayjs';\nexport const handler = () => { dayjs.locale('de'); return {} }", + "export const handler = () => { const m = Math; m.x = 1; return {} }", + "export const handler = () => { const p = Object.getPrototypeOf([]); p.x = 1; return {} }", + "export const handler = () => { config.x = 1; return {} }", + "const pattern = /a/g;\nexport const handler = (input) => ({ ok: pattern.test(input.s) })", + "import zod from 'zod';\nconst schema = zod.object({ a: zod.number() });\nexport const handler = (input) => ({ a: schema.parse(input).a })", + "export const handler = async (input) => { const f = () => Math; f().seen = (f().seen || 0) + 1; return { n: f().seen } }", + "export const handler = async (input) => { const o = { m: Math }; o.m.seen = (o.m.seen || 0) + 1; return { n: o.m.seen } }", + "export const handler = async (input) => { const bump = (t) => { t.seen = (t.seen || 0) + 1; return t.seen }; return { n: bump(JSON) } }", + "export const handler = async (input) => { const c = config; c.seen = 1; return {} }", + "export const handler = async (input) => ({ c: [config][0] })", + "import { z } from 'zod';\nexport const handler = async (input) => ({ ok: z.string().safeParse(input.s).success })", + "import http from 'http';\nexport const handler = async (input) => (await http.get('https://example.com')).data", + "export const handler = async (input) => { await console.sleep(5); return {} }", + "export const handler = async (input) => { const log = console.log; log(1); return {} }", + "export const handler = async (input) => { Object.assign(Math, { seen: 1 }); return {} }", + "export const handler = async (input) => { Promise.seen = 1; return {} }", + "export const handler = async (input) => ({ v: Promise.resolve(1).constructor })", + "import zen from 'zen';\nexport const handler = async (input) => { zen.seen = 1; return {} }", + "import Big from 'big.js';\nexport const handler = async (input) => { Big.roundUp = 0; return {} }", + "export const handler = async (input) => { const s = Symbol; s.seen = 1; return {} }", + "export const handler = async (input) => { input.then((x) => x); return {} }", + "export function* handler(input) { yield 1 }", + "export default async (input) => ({})", + "export { handler } from './other';", + "import other from 'other';\nexport const handler = async (input) => other(input)", + "export const handler = async (input) => ({ v: input[input.key] })", + "export const handler = async (input) => ({ v: this })", + "export const handler = async (input) => ({ v: import.meta })", + "export class Handler {}\nexport const handler = async (input) => ({})", + ]; + for source in sources { + assert!(!Purity::module(source), "{source}"); + } + } + + #[tokio::test] + async fn denied_members_cover_the_module_realm() { + let extensions = NodeHandlerExtensions::default(); + let function = extensions.function_runtime().await.expect("runtime"); + let probe = r#" + import dayjs from 'dayjs'; + import Big from 'big.js'; + const iterators = [[].values(), ''[Symbol.iterator](), new Map().values(), new Set().values(), 'a'.matchAll(/a/g)]; + const protos = [Object.prototype, Function.prototype, Array.prototype, String.prototype, Number.prototype, + Boolean.prototype, Symbol.prototype, BigInt.prototype, Date.prototype, RegExp.prototype, Error.prototype, + Map.prototype, Set.prototype, WeakMap.prototype, WeakSet.prototype, Promise.prototype, + Object.getPrototypeOf(Big(1)), Object.getPrototypeOf(dayjs())]; + for (const iterator of iterators) { + for (let proto = Object.getPrototypeOf(iterator); proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) { + protos.push(proto); + } + } + const names = new Set(); + for (const proto of protos) { + for (const key of Object.getOwnPropertyNames(proto)) { + const value = Object.getOwnPropertyDescriptor(proto, key).value; + if (typeof value === 'function' || (typeof value === 'object' && value !== null)) { + names.add(key); + } + } + } + for (const instance of [Big(1), dayjs(), new Date(), /a/, [], {}, new Map(), new Set(), new Error('x')]) { + for (const key of Object.getOwnPropertyNames(instance)) { + if (typeof instance[key] === 'function') { + names.add(key); + } + } + } + export const handler = async () => [...names].join(','); + "#; + let name = function + .shared_module("probe", probe) + .await + .expect("module"); + let response = function + .call_handler(&name, JsValueWithNodes(JsValue(Variable::Null))) + .await + .expect("names"); + let names = response + .data + .as_str() + .map(str::to_string) + .unwrap_or_default(); + assert!(!names.is_empty()); + let missing: Vec<&str> = names + .split(',') + .filter(|name| !Purity::MEMBERS.contains(name) && !Purity::BANNED.contains(name)) + .collect(); + assert!(missing.is_empty(), "{missing:?}"); + } + + #[test] + fn plain_handlers_share_a_context() { + let sources = [ + "const handler = (input, { moment, env }) => {\n return { output: input.input * 2 };\n}", + "const handler = (input, { moment, env }) => {\n const count = (flag) => Object.values(input?.flag || {}).reduce((acc, curr) => {\n if (curr === flag) return acc + 1;\n return acc;\n }, 0);\n return { critical: count('critical'), red: count('red') };\n}", + "const handler = (input, { dayjs, Big }) => {\n const flags = input.flags || {};\n let overall = 'green';\n if (Object.values(flags).some((f) => f === 'red')) {\n overall = 'red';\n }\n return { ...input, overall };\n}", + "const handler = (input, { dayjs, Big }) => {\n const round = (val) => val?.toFixed !== undefined ? val.round(2).toNumber() : val;\n const base = Big(input.base.pi).times(Big(input.tax.gst).div(100));\n return { breakdown: [{ key: 'premium', value: round(base) }] };\n}", + "const RATE = 0.2;\nfunction helper(a) { return a * RATE }\nconst handler = (input) => {\n const out = [];\n for (const item of input.items) { out.push({ ...item, v: helper(item.v) }); }\n out.sort((a, b) => a.v - b.v);\n const total = { sum: 0 };\n out.forEach((item) => { total.sum += item.v; });\n return { out, total, at: dayjs(input.when).add(1, 'day').format('YYYY-MM-DD') };\n}", + "function handler(input, { dayjs: d }) {\n const map = new Map();\n map.set('a', 1);\n try { return { v: map.has('a'), when: d(input.when).isValid(), n: Math.max(1, Number(input.n)) } } catch (e) { return { e: e.message } }\n}", + ]; + for source in sources { + assert!(Purity::layout(source).is_some(), "{source}"); + } + } + + #[test] + fn shared_state_keeps_a_fresh_context() { + let sources = [ + "let count = 0;\nconst handler = () => ({ n: ++count });", + "const cache = {};\nconst handler = (input) => { cache.x = 1; return {}; };", + "const handler = () => { globalThis.flag = 1; return {}; };", + "var hits = 0\nconst handler = () => ({ hits: hits++ })", + "const handler = (input, { Big }) => { Big.DP = 2; return {} }", + "const handler = (input, { dayjs }) => { dayjs.locale('de'); return {} }", + "const handler = (input, { dayjs }) => { const d = dayjs; d.x = 1; return {} }", + "const handler = (input, { dayjs }) => ({ d: dayjs(input.at, { locale: { name: 'x' } }) })", + "const handler = (input, { dayjs }) => { const d = dayjs(); d.$L = { name: 'x' }; return { v: d.add(1, 'day') } }", + "const handler = (input, { dayjs }) => ({ u: dayjs().get(input.unit) })", + "const handler = (input) => { const o = { map: dayjs().add }; return o.map(1) }", + "const handler = (input) => { const f = [].push; return {} }", + "const handler = (input) => ({ v: input[input.key] })", + "const handler = (input) => { input[input.key] = 1; return input }", + "const handler = (input) => { const p = input.constructor; return {} }", + "const handler = (input) => { console.log(input); return {} }", + "const handler = (input) => { log.push(1); return {} }", + "function helper() { helper.calls = (helper.calls || 0) + 1; return helper.calls }\nconst handler = () => ({ n: helper() })", + "const handler = () => { Math.seen = 1; return {} }", + "const handler = () => { const m = Math; return {} }", + "const handler = (input, { Big }) => ({ v: Big(input.a).mod(3) })", + "const handler = async (input) => ({ v: await input })", + "const handler = (input) => ({ v: this })", + "const handler = (input) => ({ v: eval('1') })", + "const handler = (input) => ({ v: Function('return 1')() })", + "const handler = (input) => ({ v: [1].map.call(input, (x) => x) })", + "const handler = (input) => ({ v: input.list.map((x) => x)() })", + "const handler = (input) => ({ __proto__: input })", + "const handler = (input) => { const { constructor } = input; return {} }", + "const handler = (input) => ({ v: `a\\\nb` })", + "const handler = (input) => ({ v: 1 })\r\n", + "const handler = (input) => ({ v: typeof __zenRow })", + "const handler = (input) => ({ v: input.at > now })", + "const handler = (input) => ({ v: typeof main })", + "console.log('loaded');\nconst handler = () => ({})", + "const pattern = /a/g;\nconst handler = (input) => ({ ok: pattern.test(input.s) })", + "const handler = (input, helpers) => ({ v: helpers.dayjs() })", + "const handler = (input) => ({})\nconst handler2 = handler;", + "const main = 1;\nconst handler = (input) => ({})", + "const handler = (input) => { handler.x = 1; return {} }", + "const handler = (input) => ({ f: handler })", + "class A {}\nconst handler = (input) => ({})", + "const handler = (input) => { x = 1; return {} }", + "const handler = (input) => { const count = 1; return {} }\nconst count = () => 1;", + "const handler = (input) => ({ v: Object.assign(input, {}) })", + "const handler = (input) => { Reflect.set(input, 'a', 1); return {} }", + "const handler = (input) => { const f = () => Math; f().seen = (f().seen || 0) + 1; return { n: f().seen } }", + "const handler = (input) => { const o = { m: Math }; o.m.seen = (o.m.seen || 0) + 1; return { n: o.m.seen } }", + "const handler = (input) => { const bump = (t) => { t.seen = (t.seen || 0) + 1; return t.seen }; return { n: bump(JSON) } }", + ]; + for source in sources { + assert!(Purity::layout(source).is_none(), "{source}"); + } + } + + #[test] + fn fixture_handlers_share_a_context() { + let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../../test-data/"); + let files = [ + "function.json", + "credit-analysis.json", + "graphs/aml.json", + "graphs/company-analysis.json", + "graphs/insurance-breakdown.json", + ]; + for file in files { + let text = std::fs::read_to_string(format!("{root}{file}")).unwrap(); + let graph: serde_json::Value = serde_json::from_str(&text).unwrap(); + let sources: Vec<&str> = graph["nodes"] + .as_array() + .unwrap() + .iter() + .filter(|node| node["type"] == "functionNode") + .filter_map(|node| node["content"].as_str()) + .collect(); + assert!(!sources.is_empty(), "{file}"); + for source in sources { + assert!(Purity::layout(source).is_some(), "{file}"); + } + } + } + + #[test] + fn throwing_handlers_share_a_context() { + let sources = [ + "/**\n * é ünïcödé — 日本\n */\nconst handler = (input, { moment, env }) => {\n const label = `row\n${input.n} é`;\n if (input.n % 3 === 0) {\n throw new Error('boom ' + input.n + label);\n }\n return { label };\n}", + "const handler = (input, { Big }) => ({ v: Big(input.n % 4 === 0 ? 'x' : input.n).plus(1).toString() })", + "const handler = (input) => ({ v: input.n % 5 === 0 ? 10n : 1 })", + "const handler = (input) => {\n const o = input.n > 5 ? input.items : null;\n return { v: o.length };\n}", + "const handler = (input) => input.n % 2 ? undefined : { a: 1 }", + "const deep = (n) => deep(n + 1);\nconst handler = (input) => {\n if (input.n === 7) {\n deep(0);\n }\n return { ok: true };\n}", + "const handler = (input) => {\n if (input.n === 4) throw { code: input.n, items: input.items };\n if (input.n === 8) throw 'plain ' + input.n;\n return { list: input.items.map((x) => x * 1.5), s: input.s.toUpperCase() };\n}", + "const handler = (input, { moment, env }) => {\n while (true) {}\n return input;\n}", + ]; + for source in sources { + assert!(Purity::layout(source).is_some(), "{source}"); + } + } + + #[test] + fn denied_members_cover_the_script_realm() { + let runtime = crate::nodes::function::v1::runtime::create_runtime().unwrap(); + let context = rquickjs::Context::full(&runtime).unwrap(); + let names: String = context.with(|ctx| { + rquickjs::Module::evaluate(ctx.clone(), "main", "import 'internals';").unwrap().finish::<()>().unwrap(); + ctx.eval( + r#" + const iterators = [[].values(), ''[Symbol.iterator](), new Map().values(), new Set().values(), 'a'.matchAll(/a/g)]; + const protos = [Object.prototype, Function.prototype, Array.prototype, String.prototype, Number.prototype, + Boolean.prototype, Symbol.prototype, BigInt.prototype, Date.prototype, RegExp.prototype, Error.prototype, + Map.prototype, Set.prototype, WeakMap.prototype, WeakSet.prototype, Promise.prototype, + Object.getPrototypeOf(Big(1)), Object.getPrototypeOf(dayjs())]; + for (const iterator of iterators) { + for (let proto = Object.getPrototypeOf(iterator); proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) { + protos.push(proto); + } + } + const names = new Set(); + for (const proto of protos) { + for (const key of Object.getOwnPropertyNames(proto)) { + const value = Object.getOwnPropertyDescriptor(proto, key).value; + if (typeof value === 'function' || (typeof value === 'object' && value !== null)) { + names.add(key); + } + } + } + for (const instance of [Big(1), dayjs(), new Date(), /a/, [], {}, new Map(), new Set(), new Error('x')]) { + for (const key of Object.getOwnPropertyNames(instance)) { + if (typeof instance[key] === 'function') { + names.add(key); + } + } + } + [...names].join(',') + "#, + ) + .unwrap() + }); + let missing: Vec<&str> = names + .split(',') + .filter(|name| !Purity::MEMBERS.contains(name) && !Purity::BANNED.contains(name)) + .collect(); + assert!(missing.is_empty(), "{missing:?}"); + } + + #[test] + fn layout_keeps_lines_and_columns() { + let source = "const handler = (input) => {\n // é ünïcödé\n return { v: `a\nb` };\n}"; + let layout = Purity::layout(source).unwrap(); + assert_eq!(layout.len(), source.len()); + assert_eq!(layout.matches('\n').count(), source.matches('\n').count()); + assert!(layout.chars().all(|c| c == ' ' || c == '\n')); + } +} diff --git a/core/engine/src/nodes/function/v1/mod.rs b/core/engine/src/nodes/function/v1/mod.rs index 7ad46df7..61080ebe 100644 --- a/core/engine/src/nodes/function/v1/mod.rs +++ b/core/engine/src/nodes/function/v1/mod.rs @@ -1,17 +1,20 @@ use std::ops::Deref; +use std::rc::Rc; use std::sync::Arc; use std::time::{Duration, Instant}; use crate::nodes::definition::NodeHandler; +use crate::nodes::function::purity::Purity; use crate::nodes::function::v1::runtime::create_runtime; -use crate::nodes::function::v1::script::Script; +use crate::nodes::function::v1::script::{Script, Session}; use crate::nodes::result::NodeResult; -use crate::nodes::{NodeContext, NodeContextExt}; +use crate::nodes::{NodeContext, NodeContextBase, NodeContextExt, NodeError}; use serde_json::Value; use zen_expression::variable::ToVariable; +use zen_expression::Variable; pub(crate) mod runtime; -mod script; +pub(super) mod script; #[derive(Debug, Clone)] pub struct FunctionV1NodeHandler; @@ -43,6 +46,53 @@ impl NodeHandler for FunctionV1NodeHandler { } } +impl FunctionV1NodeHandler { + pub(crate) fn batch(id: &Arc, source: &Arc, rows: usize) -> Option { + if rows < 2 { + return None; + } + let layout = Purity::layout(source)?; + Some(Batch { + id: id.clone(), + source: source.clone(), + layout, + session: None, + failed: false, + }) + } +} + +pub(crate) struct Batch { + id: Arc, + source: Arc, + layout: Rc, + session: Option, + failed: bool, +} + +impl Batch { + pub(crate) fn call( + &mut self, + input: &Variable, + nodes: Option<&Variable>, + ) -> Option> { + if self.session.is_none() && !self.failed { + self.session = Session::open(&self.source, MAX_DURATION); + self.failed = self.session.is_none(); + } + let session = self.session.as_ref()?; + let result = session.call(&self.layout, &NodeContextBase::joined(input, nodes)); + if result.is_err() || !session.settled() { + self.session = None; + } + Some( + result + .map(|response| response.output) + .map_err(|error| NodeError::new(self.id.clone(), error)), + ) + } +} + #[derive(Debug, Clone, Default, ToVariable)] pub struct FunctionV1Trace { log: Vec, diff --git a/core/engine/src/nodes/function/v1/script.rs b/core/engine/src/nodes/function/v1/script.rs index 6157cd14..ef6c8c77 100644 --- a/core/engine/src/nodes/function/v1/script.rs +++ b/core/engine/src/nodes/function/v1/script.rs @@ -4,6 +4,9 @@ use rquickjs::{Context, Ctx, Error as QError, FromJs, Module, Runtime}; use serde::{Deserialize, Serialize}; use serde_json::Value; use std::fmt::Debug; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; use zen_expression::variable::Variable; #[derive(Debug, Deserialize)] @@ -27,36 +30,126 @@ impl Script { P: Serialize, { let runtime = &self.runtime; - let context = Context::full(&runtime).context("Failed to create context")?; + let context = Context::full(runtime).context("Failed to create context")?; let args_str = serde_json::to_string(args).context("Failed to serialize function arguments")?; let json_response = context.with(|ctx| -> anyhow::Result { - Module::evaluate( - ctx.clone(), - "main", - "import 'internals'; globalThis.now = Date.now();", - ) - .map_err(|e| map_js_error(&ctx, e))? - .finish::<()>() - .map_err(|e| map_js_error(&ctx, e))?; - - let _ = ctx - .globals() - .set("log", Vec::::new()) - .map_err(|e| map_js_error(&ctx, e))?; - + Self::prepare(&ctx)?; ctx.eval::(format!("{source};main({args_str})")) .map_err(|e| map_js_error(&ctx, e)) })?; - serde_json::from_str(json_response.as_str()).context("Failed to parse function result") + Self::response(&json_response) + } + + fn prepare(ctx: &Ctx) -> anyhow::Result<()> { + Module::evaluate( + ctx.clone(), + "main", + "import 'internals'; globalThis.now = Date.now();", + ) + .map_err(|e| map_js_error(ctx, e))? + .finish::<()>() + .map_err(|e| map_js_error(ctx, e))?; + + ctx.globals() + .set("log", Vec::::new()) + .map_err(|e| map_js_error(ctx, e))?; + Ok(()) + } + + fn response(json: &str) -> anyhow::Result { + serde_json::from_str(json).context("Failed to parse function result") + } +} + +pub(crate) struct Session { + runtime: Runtime, + context: Context, + base: Instant, + started: Arc, +} + +impl Session { + pub(crate) const ROW: &'static str = "__zenRow"; + const NESTING: usize = 32; + + pub(crate) fn open(source: &str, limit: Duration) -> Option { + let runtime = super::runtime::create_runtime().ok()?; + let base = Instant::now(); + let started = Arc::new(AtomicU64::new(0)); + let watched = started.clone(); + runtime.set_interrupt_handler(Some(Box::new(move || { + base.elapsed() + .saturating_sub(Duration::from_nanos(watched.load(Ordering::Relaxed))) + > limit + }))); + let context = Context::full(&runtime).ok()?; + let ready = + context.with(|ctx| Script::prepare(&ctx).is_ok() && ctx.eval::<(), _>(source).is_ok()); + (ready && !runtime.is_job_pending()).then_some(Self { + runtime, + context, + base, + started, + }) + } + + pub(crate) fn call

(&self, layout: &str, args: &P) -> anyhow::Result + where + P: Serialize, + { + let args_str = + serde_json::to_string(args).context("Failed to serialize function arguments")?; + self.started + .store(self.base.elapsed().as_nanos() as u64, Ordering::Relaxed); + let json_response = self.context.with(|ctx| -> anyhow::Result { + let parsed = Self::plain(&args_str) + .then(|| ctx.json_parse(args_str.as_str()).ok()) + .flatten() + .is_some_and(|value| ctx.globals().set(Self::ROW, value).is_ok()); + let script = match parsed { + true => format!("{layout};main(({}))", Self::ROW), + false => format!("{layout};main({args_str})"), + }; + ctx.eval::(script) + .map_err(|e| map_js_error(&ctx, e)) + })?; + Script::response(&json_response) + } + + fn plain(json: &str) -> bool { + if json.contains("\"__proto__\"") { + return false; + } + let (mut depth, mut deepest, mut quoted, mut escaped) = (0usize, 0usize, false, false); + for byte in json.bytes() { + match (quoted, escaped, byte) { + (true, true, _) => escaped = false, + (true, false, b'\\') => escaped = true, + (true, false, b'"') => quoted = false, + (true, false, _) => {} + (false, _, b'"') => quoted = true, + (false, _, b'{' | b'[') => { + depth += 1; + deepest = deepest.max(depth); + } + (false, _, b'}' | b']') => depth = depth.saturating_sub(1), + (false, _, _) => {} + } + } + deepest <= Self::NESTING + } + + pub(crate) fn settled(&self) -> bool { + !self.runtime.is_job_pending() } } fn map_js_error(ctx: &Ctx, e: QError) -> anyhow::Error { - let error = JsValue::from_js(&ctx, ctx.catch()) + let error = JsValue::from_js(ctx, ctx.catch()) .map(|v| v.0) .unwrap_or(Variable::String((e.to_string().as_str()).into())); diff --git a/core/engine/src/nodes/function/v2/error.rs b/core/engine/src/nodes/function/v2/error.rs index ece061fa..48e51c00 100644 --- a/core/engine/src/nodes/function/v2/error.rs +++ b/core/engine/src/nodes/function/v2/error.rs @@ -13,7 +13,19 @@ pub enum FunctionError { impl<'js> From> for FunctionError { fn from(value: CaughtError<'js>) -> Self { - Self::Caught(value.to_string()) + match value { + CaughtError::Value(thrown) if thrown.is_object() => { + let text = thrown + .ctx() + .json_stringify(thrown.clone()) + .ok() + .flatten() + .and_then(|json| json.to_string().ok()) + .unwrap_or_else(|| thrown.type_name().to_string()); + Self::Caught(format!("Exception generated by quickjs: {text}")) + } + other => Self::Caught(other.to_string()), + } } } diff --git a/core/engine/src/nodes/function/v2/function.rs b/core/engine/src/nodes/function/v2/function.rs index 5e41a139..8224e85e 100644 --- a/core/engine/src/nodes/function/v2/function.rs +++ b/core/engine/src/nodes/function/v2/function.rs @@ -1,3 +1,5 @@ +use std::cell::RefCell; +use std::collections::HashMap; use std::fmt::{Debug, Formatter}; use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::Arc; @@ -7,9 +9,11 @@ use crate::nodes::function::v2::listener::{RuntimeEvent, RuntimeListener}; use crate::nodes::function::v2::module::console::{Console, Log}; use crate::nodes::function::v2::module::ModuleLoader; use crate::nodes::function::v2::serde::{JsValue, JsValueWithNodes}; +use rquickjs::prelude::Func; use rquickjs::promise::MaybePromise; -use rquickjs::{async_with, AsyncContext, AsyncRuntime, CatchResultExt, Ctx, Module}; +use rquickjs::{async_with, AsyncContext, AsyncRuntime, CatchResultExt, Ctx, Module, Object}; use serde::{Deserialize, Serialize}; +use std::rc::Rc; use zen_expression::variable::{ToVariable, Variable}; pub struct FunctionConfig { @@ -21,6 +25,7 @@ pub struct Function { ctx: AsyncContext, listeners: Vec>, module_loader: ModuleLoader, + declared: RefCell>, } impl Debug for Function { @@ -43,6 +48,7 @@ impl Function { ctx, module_loader, listeners: config.listeners.unwrap_or_default(), + declared: RefCell::new(HashMap::new()), }; this.dispatch_event(RuntimeEvent::Startup).await?; @@ -101,6 +107,27 @@ impl Function { Ok(()) } + pub(crate) async fn shared_module(&self, name: &str, source: &str) -> FunctionResult { + let content_hash = create_content_hash(source); + let declarative_name = format!("node:{name}"); + let module_name = match self.declared.borrow().get(&declarative_name) { + Some(hash) if *hash == content_hash => return Ok(declarative_name), + Some(_) => format!("node:{name}.{content_hash:x}"), + None if self.module_loader.has_module(&declarative_name) => { + format!("node:{name}.{content_hash:x}") + } + None => declarative_name.clone(), + }; + if self.declared.borrow().get(&module_name) == Some(&content_hash) { + return Ok(module_name); + } + self.register_module(&module_name, source).await?; + self.declared + .borrow_mut() + .insert(module_name.clone(), content_hash); + Ok(module_name) + } + pub(crate) async fn call_handler( &self, name: &str, @@ -125,6 +152,57 @@ impl Function { Ok(k?) } + pub(crate) async fn call_rows( + &self, + name: &str, + config: (u8, u8, bool), + rows: Vec<(Variable, Option)>, + tick: &dyn Fn(), + ) -> Vec> { + let count = rows.len(); + let current: Rc> = Rc::new(RefCell::new(Variable::Null)); + let shared = current.clone(); + let results: FunctionResult>> = async_with!(&self.ctx => |ctx| { + let settings = Object::new(ctx.clone()).catch(&ctx)?; + settings.prop("iteration", config.0).catch(&ctx)?; + settings.prop("maxDepth", config.1).catch(&ctx)?; + settings.prop("trace", config.2).catch(&ctx)?; + ctx.globals().set("config", settings).catch(&ctx)?; + ctx.globals() + .set("__getNodesData", Func::from(move || JsValue(shared.borrow().clone()))) + .catch(&ctx)?; + let m: rquickjs::Object = Module::import(&ctx, name).catch(&ctx)?.into_future().await.catch(&ctx)?; + let handler: rquickjs::Function = m.get("handler").catch(&ctx)?; + let mut results = Vec::with_capacity(count); + self.dispatch_event_inner(&ctx, RuntimeEvent::SoftReset).await?; + for (input, nodes) in rows { + tick(); + *current.borrow_mut() = nodes.unwrap_or_default(); + let result: FunctionResult = async { + if config.2 { + self.dispatch_event_inner(&ctx, RuntimeEvent::SoftReset).await?; + } + let promise: MaybePromise = handler.call((JsValueWithNodes(JsValue(input)), 5)).catch(&ctx)?; + let value = promise.into_future::().await.catch(&ctx)?; + Ok(value.0) + } + .await; + results.push(result); + } + Ok(results) + }) + .await; + match results { + Ok(results) => results, + Err(error) => { + let message = error.to_string(); + (0..count) + .map(|_| Err(FunctionError::Caught(message.clone()))) + .collect() + } + } + } + pub(crate) async fn extract_logs(&self) -> Vec { let logs: Option> = async_with!(&self.ctx => |ctx| { let console = Console::from_context(&ctx).ok()?; diff --git a/core/engine/src/nodes/function/v2/mod.rs b/core/engine/src/nodes/function/v2/mod.rs index 9a30cb74..b4a77c9f 100644 --- a/core/engine/src/nodes/function/v2/mod.rs +++ b/core/engine/src/nodes/function/v2/mod.rs @@ -1,18 +1,22 @@ use std::ops::Deref; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; use std::time::{Duration, Instant}; use crate::nodes::definition::NodeHandler; +use crate::nodes::function::purity::Purity; use crate::nodes::function::v2::error::{FunctionError, FunctionResult}; use crate::nodes::function::v2::function::Function; use crate::nodes::function::v2::module::console::Log; use crate::nodes::function::v2::serde::{JsValue, JsValueWithNodes}; use crate::nodes::result::NodeResult; -use crate::nodes::{NodeContext, NodeError}; +use crate::nodes::{NodeContext, NodeContextConfig, NodeError, NodeHandlerExtensions}; use rquickjs::prelude::Func; use rquickjs::{async_with, CatchResultExt, Object}; use serde_json::json; use zen_expression::variable::ToVariable; use zen_types::decision::FunctionContent; +use zen_types::variable::Variable; pub(crate) mod error; pub(crate) mod function; @@ -51,7 +55,7 @@ impl NodeHandler for FunctionV2NodeHandler { let function_context = FunctionContext { start, context: &ctx, - function: &function, + function, }; self.attach_globals(function, &ctx) @@ -110,6 +114,91 @@ impl FunctionV2NodeHandler { } } +impl FunctionV2NodeHandler { + pub(crate) async fn batch( + id: &Arc, + content: &FunctionContent, + extensions: &NodeHandlerExtensions, + config: &NodeContextConfig, + iteration: u8, + rows: Vec<(Variable, Option)>, + ) -> Vec> { + let source = extensions + .stripped_functions + .as_ref() + .and_then(|stripped| stripped.get(content.source.as_ref()).cloned()) + .unwrap_or_else(|| strip::TypeStripper::strip(content.source.deref())); + if rows.len() < 2 || Purity::module(source.as_ref()) { + return Self::run(id, &source, extensions, config, iteration, rows).await; + } + let mut results = Vec::with_capacity(rows.len()); + for row in rows { + let fresh = NodeHandlerExtensions { + function_runtime: Default::default(), + ..extensions.clone() + }; + results.extend(Self::run(id, &source, &fresh, config, iteration, vec![row]).await); + } + results + } + + async fn run( + id: &Arc, + source: &Arc, + extensions: &NodeHandlerExtensions, + config: &NodeContextConfig, + iteration: u8, + rows: Vec<(Variable, Option)>, + ) -> Vec> { + let failed = |source: Box| NodeError::new(id.clone(), source); + let count = rows.len(); + let function = match extensions.function_runtime().await { + Ok(function) => function, + Err(error) => { + let message = error.to_string(); + return (0..count) + .map(|_| Err(failed(message.clone().into()))) + .collect(); + } + }; + let module_name = match function.shared_module(id.deref(), source.as_ref()).await { + Ok(name) => name, + Err(error) => { + let message = error.to_string(); + return (0..count) + .map(|_| Err(failed(FunctionError::Caught(message.clone()).into()))) + .collect(); + } + }; + let base = Instant::now(); + let started = Arc::new(AtomicU64::new(0)); + let limit = Duration::from_millis(config.function_timeout_millis); + let watched = started.clone(); + function + .runtime() + .set_interrupt_handler(Some(Box::new(move || { + base.elapsed() + .saturating_sub(Duration::from_nanos(watched.load(Ordering::Relaxed))) + > limit + }))) + .await; + let tick = || started.store(base.elapsed().as_nanos() as u64, Ordering::Relaxed); + let results = function + .call_rows( + &module_name, + (iteration, config.max_depth, config.trace), + rows, + &tick, + ) + .await; + function.runtime().set_interrupt_handler(None).await; + results + .into_iter() + .map(|result| result.map_err(|error| failed(error.into()))) + .collect() + } +} + #[derive(Debug, Clone, Default, ToVariable)] #[serde(rename_all = "camelCase")] pub struct FunctionV2Trace { diff --git a/core/engine/src/nodes/function/v2/module/zen.rs b/core/engine/src/nodes/function/v2/module/zen.rs index 764dc0f4..dc89af0b 100644 --- a/core/engine/src/nodes/function/v2/module/zen.rs +++ b/core/engine/src/nodes/function/v2/module/zen.rs @@ -1,4 +1,5 @@ -use crate::decision_graph::graph::{DecisionGraph, DecisionGraphConfig}; +use crate::compiled::call::{Call, Load}; +use crate::decision_graph::graph::DecisionGraphResponse; use crate::loader::DynamicLoader; use crate::nodes::custom::DynamicCustomNode; use crate::nodes::function::v2::error::{FunctionResult, ResultExt}; @@ -11,21 +12,90 @@ use rquickjs::prelude::{Async, Func, Opt}; use rquickjs::{CatchResultExt, Ctx, Function, Object}; use std::future::Future; use std::pin::Pin; +use std::time::Instant; use crate::nodes::function::http_handler::DynamicHttpHandler; pub(crate) struct ZenListener { + pub prepared: std::sync::Arc, pub loader: DynamicLoader, pub custom_node: DynamicCustomNode, pub http_handler: DynamicHttpHandler, } +impl ZenListener { + async fn call<'js>( + ctx: &Ctx<'js>, + key: &str, + context: JsValue, + extensions: NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + ) -> rquickjs::Result { + let start = Instant::now(); + let call = Call { + key, + extensions: &extensions, + max_depth, + iteration, + }; + let graph = match call.load().await.or_throw(ctx)? { + Load::Graph(graph) => graph, + Load::Kind(kind) => { + return Err(rquickjs::Exception::throw_message( + ctx, + &format!("decision '{key}' is a {kind}, expected graph"), + )) + } + }; + let result = call + .run(&graph, context.0, None) + .await + .map_err(|error| rquickjs::Exception::throw_message(ctx, &error.to_string()))?; + Ok(DecisionGraphResponse { + performance: format!("{:.1?}", start.elapsed()), + result, + trace: None, + }) + } + + async fn walk<'js>( + ctx: &Ctx<'js>, + key: &str, + context: JsValue, + extensions: NodeHandlerExtensions, + max_depth: u8, + iteration: u8, + ) -> rquickjs::Result { + let call = Call { + key, + extensions: &extensions, + max_depth, + iteration, + }; + let graph = match call.load().await.or_throw(ctx)? { + Load::Graph(graph) => graph, + Load::Kind(kind) => { + return Err(rquickjs::Exception::throw_message( + ctx, + &format!("decision '{key}' is a {kind}, expected graph"), + )) + } + }; + call.traced(&graph, context.0, None) + .await + .map_err(|error| rquickjs::Exception::throw_message(ctx, &error.to_string()))? + .or_throw(ctx) + } +} + impl RuntimeListener for ZenListener { fn on_event<'js>( &self, ctx: Ctx<'js>, event: RuntimeEvent, ) -> Pin + 'js>> { + let prepared = self.prepared.clone(); let loader = self.loader.clone(); let custom_node = self.custom_node.clone(); let http_handler = self.http_handler.clone(); @@ -43,6 +113,7 @@ impl RuntimeListener for ZenListener { key: String, context: JsValue, opts: Opt>| { + let prepared = prepared.clone(); let loader = loader.clone(); let custom_node = custom_node.clone(); let http_handler = http_handler.clone(); @@ -57,30 +128,27 @@ impl RuntimeListener for ZenListener { .map(|opt| opt.get::<_, bool>("trace").unwrap_or_default()) .unwrap_or_default(); - let load_result = loader.load(key.as_str()).await; - let decision_content = load_result.or_throw(&ctx)?; - let kind = decision_content.kind(); - let Some(graph_content) = decision_content.into_graph_arc() else { - return Err(rquickjs::Exception::throw_message( - &ctx, - &format!("decision '{key}' is a {kind}, expected graph"), - )); + let extensions = NodeHandlerExtensions { + loader: loader.clone(), + custom_node: custom_node.clone(), + http_handler: http_handler.clone(), + prepared: prepared.clone(), + ..Default::default() + }; + let response = match trace { + true => { + Self::walk( + &ctx, &key, context, extensions, max_depth, iteration, + ) + .await? + } + false => { + Self::call( + &ctx, &key, context, extensions, max_depth, iteration, + ) + .await? + } }; - let mut sub_tree = DecisionGraph::try_new(DecisionGraphConfig { - content: graph_content, - max_depth, - iteration: iteration + 1, - trace, - extensions: NodeHandlerExtensions { - loader: loader.clone(), - custom_node: custom_node.clone(), - http_handler: http_handler.clone(), - ..Default::default() - }, - }) - .or_throw(&ctx)?; - - let response = sub_tree.evaluate(context.0).await.or_throw(&ctx)?; let k = serde_json::to_value(response).or_throw(&ctx)?.into(); return rquickjs::Result::Ok(JsValue(k)); diff --git a/core/engine/src/nodes/function/v2/serde.rs b/core/engine/src/nodes/function/v2/serde.rs index f11a75f5..ed7f54b8 100644 --- a/core/engine/src/nodes/function/v2/serde.rs +++ b/core/engine/src/nodes/function/v2/serde.rs @@ -13,6 +13,7 @@ use zen_types::rccell::RcCell; pub(crate) struct JsValue(pub(crate) Variable); impl<'js> FromJs<'js> for JsValue { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] fn from_js(ctx: &Ctx<'js>, v: QValue<'js>) -> rquickjs::Result { let computed_value = match v.type_of() { Type::Uninitialized | Type::Undefined | Type::Null => Variable::Null, @@ -117,9 +118,26 @@ impl<'js> IntoJs<'js> for JsValueWithNodes { } let obj = base_js.into_object().or_throw(ctx)?; - let nodes_proxy: QValue<'js> = ctx.eval( - r#" - (() => { + let globals = ctx.globals(); + let factory: rquickjs::Function<'js> = + match globals.get::<_, Option>>("__zenNodesProxy")? { + Some(factory) => factory, + None => { + let factory: rquickjs::Function<'js> = ctx.eval(Self::FACTORY)?; + globals.set("__zenNodesProxy", factory.clone())?; + factory + } + }; + let nodes_proxy: QValue<'js> = factory.call(())?; + + obj.set("$nodes", nodes_proxy)?; + Ok(obj.into_value()) + } +} + +impl JsValueWithNodes { + const FACTORY: &'static str = r#" + () => { const _data = { loaded: false, inner: null }; const data = () => { if (!_data.loaded) { @@ -136,13 +154,8 @@ impl<'js> IntoJs<'js> for JsValueWithNodes { ownKeys: () => Object.keys(data()), getOwnPropertyDescriptor: (target, prop) => Object.getOwnPropertyDescriptor(data(), prop), }); - })(); - "#, - )?; - - obj.set("$nodes", nodes_proxy)?; - Ok(obj.into_value()) - } + } + "#; } pub(crate) struct JsConverter<'r, 'js> { @@ -162,6 +175,7 @@ impl<'r, 'js> JsConverter<'r, 'js> { self.convert_with_cache(var) } + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] fn convert_with_cache(&mut self, var: &Variable) -> rquickjs::Result> { match var { Variable::Null => Ok(QValue::new_null(self.ctx.clone())), @@ -214,6 +228,7 @@ pub(crate) mod rquickjs_conv { struct JsonValue(serde_json::Value); impl<'js> FromJs<'js> for JsonValue { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] fn from_js(ctx: &Ctx<'js>, value: QValue<'js>) -> rquickjs::Result { let json_value = match value.type_of() { Type::Uninitialized | Type::Undefined | Type::Null => serde_json::Value::Null, @@ -287,6 +302,7 @@ pub(crate) mod rquickjs_conv { } impl<'js> IntoJs<'js> for JsonValue { + #[cfg_attr(not(target_family = "wasm"), recursive::recursive)] fn into_js(self, ctx: &Ctx<'js>) -> rquickjs::Result> { match self.0 { serde_json::Value::Null => Ok(QValue::new_null(ctx.clone())), diff --git a/core/engine/src/nodes/input/dates.rs b/core/engine/src/nodes/input/dates.rs index 1f35323d..b3100b31 100644 --- a/core/engine/src/nodes/input/dates.rs +++ b/core/engine/src/nodes/input/dates.rs @@ -18,6 +18,19 @@ impl DeclaredDates { "deprecated", ]; + pub(crate) fn mentions(schema: &Value) -> bool { + match schema { + Value::Object(map) => { + matches!( + map.get("format").and_then(Value::as_str), + Some("date" | "date-time") + ) || map.values().any(Self::mentions) + } + Value::Array(items) => items.iter().any(Self::mentions), + _ => false, + } + } + pub(crate) fn declared(schema: &Value) -> bool { schema.as_object().is_some_and(Self::declared_map) } @@ -69,6 +82,29 @@ impl DeclaredDates { } } + pub(crate) fn at<'s>(schema: &'s Value, path: &str) -> Option<&'s Value> { + let mut current = schema; + for segment in path.split('.') { + if Self::declared(current) { + return None; + } + let object = current.as_object()?; + current = Self::structure(object, "properties")? + .as_object()? + .get(segment)?; + } + Some(current) + } + + pub(crate) fn dated(value: &Variable) -> bool { + match value { + Variable::Dynamic(_) => DateValue::source_text(value).is_some(), + Variable::Array(items) => items.borrow().iter().any(Self::dated), + Variable::Object(object) => object.borrow().values().any(Self::dated), + _ => false, + } + } + fn structure<'s>(schema: &'s Map, key: &str) -> Option<&'s Value> { schema.get(key).or_else(|| { ["anyOf", "oneOf", "allOf"] @@ -108,15 +144,20 @@ impl DeclaredDates { ) -> Option { let array = value.as_array()?; let array = array.borrow(); - let rewritten: Vec> = array.iter().map(&rewrite).collect(); - if rewritten.iter().all(Option::is_none) { - return None; - } + let (first, next) = array + .iter() + .enumerate() + .find_map(|(index, item)| rewrite(item).map(|next| (index, next)))?; Some(Variable::from_array( - array + array[..first] .iter() - .zip(rewritten) - .map(|(item, next)| next.unwrap_or_else(|| item.clone())) + .cloned() + .chain(std::iter::once(next)) + .chain( + array[first + 1..] + .iter() + .map(|item| rewrite(item).unwrap_or_else(|| item.clone())), + ) .collect(), )) } diff --git a/core/engine/src/nodes/isolate.rs b/core/engine/src/nodes/isolate.rs new file mode 100644 index 00000000..8d52fd39 --- /dev/null +++ b/core/engine/src/nodes/isolate.rs @@ -0,0 +1,32 @@ +use crate::nodes::{ + NodeContext, NodeContextBase, NodeDataType, NodeHandlerExtensions, TraceDataType, +}; +use zen_expression::{Isolate, Variable}; + +impl NodeHandlerExtensions { + pub(crate) fn isolate(&self, input: &Variable, nodes: Option<&Variable>) -> Isolate { + let mut isolate = + Isolate::with_environment(input.clone()).with_cache(self.compiled_cache.clone()); + if let Some(nodes) = nodes { + isolate.set_local(Variable::nodes_key(), nodes.clone()); + } + + isolate + } +} + +impl NodeContext +where + NodeData: NodeDataType, + TraceData: TraceDataType, +{ + pub fn isolate(&self) -> Isolate { + self.extensions.isolate(&self.input, self.nodes.as_ref()) + } +} + +impl NodeContextBase { + pub fn isolate(&self) -> Isolate { + self.extensions.isolate(&self.input, self.nodes.as_ref()) + } +} diff --git a/core/engine/src/nodes/mod.rs b/core/engine/src/nodes/mod.rs index fd6a0950..adf3ceb5 100644 --- a/core/engine/src/nodes/mod.rs +++ b/core/engine/src/nodes/mod.rs @@ -7,8 +7,11 @@ pub mod expression; mod extensions; pub mod function; pub mod input; +#[cfg(feature = "driver")] +mod isolate; pub mod output; mod result; +#[cfg(feature = "driver")] pub(crate) mod transform_attributes; pub(crate) mod validator_cache; pub mod variable_json; @@ -18,4 +21,4 @@ pub use definition::NodeHandler; pub(crate) use definition::{NodeDataType, TraceDataType}; pub use extensions::NodeHandlerExtensions; pub use function::http_handler; -pub use result::{NodeError, NodeRequest, NodeResponse, NodeResult}; +pub use result::{NodeError, NodeResponse, NodeResult}; diff --git a/core/engine/src/nodes/result.rs b/core/engine/src/nodes/result.rs index e84f56ce..6fc6b012 100644 --- a/core/engine/src/nodes/result.rs +++ b/core/engine/src/nodes/result.rs @@ -1,4 +1,4 @@ -use crate::model::DecisionNode; +use crate::EvaluationError; use serde::{Deserialize, Serialize}; use std::fmt::{Display, Formatter}; use std::sync::Arc; @@ -12,13 +12,6 @@ pub struct NodeResponse { pub trace_data: Option, } -#[derive(Debug, Serialize, Clone)] -pub struct NodeRequest { - pub input: Variable, - pub iteration: u8, - pub node: Arc, -} - pub type NodeResult = Result; #[derive(Debug, Error)] @@ -28,6 +21,34 @@ pub struct NodeError { pub source: Box, } +impl NodeError { + pub fn new(node_id: Arc, source: impl Into>) -> Self { + Self::traced(node_id, None, source) + } + + pub fn traced( + node_id: Arc, + trace: Option, + source: impl Into>, + ) -> Self { + Self { + node_id, + trace, + source: source.into(), + } + } +} + +impl From for EvaluationError { + fn from(error: NodeError) -> Self { + EvaluationError::NodeError { + node_id: error.node_id, + trace: error.trace, + source: error.source, + } + } +} + impl Display for NodeError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.source) diff --git a/core/engine/src/nodes/transform_attributes.rs b/core/engine/src/nodes/transform_attributes.rs index 1f948ead..2b80d02a 100644 --- a/core/engine/src/nodes/transform_attributes.rs +++ b/core/engine/src/nodes/transform_attributes.rs @@ -28,7 +28,6 @@ impl TransformAttributesExecution for TransformAttributes { } }; - // let mut trace_data: Option = None; let mut output = match self.execution_mode { TransformExecutionMode::Single => { let response = evaluate(input, false).await?; diff --git a/core/engine/src/nodes/validator_cache.rs b/core/engine/src/nodes/validator_cache.rs index 4ed14fbc..243d936b 100644 --- a/core/engine/src/nodes/validator_cache.rs +++ b/core/engine/src/nodes/validator_cache.rs @@ -1,8 +1,9 @@ use crate::nodes::variable_json::VariableJson; -use ahash::HashMap; +use ahash::{AHasher, HashMap}; use anyhow::Context; use jsonschema::Validator; use serde_json::Value; +use std::hash::Hasher; use std::sync::{Arc, RwLock}; #[derive(Clone, Default, Debug)] @@ -10,13 +11,15 @@ pub struct ValidatorCache { inner: Arc>>>>, } -impl PartialEq for ValidatorCache { - fn eq(&self, _: &Self) -> bool { - true - } -} - impl ValidatorCache { + pub(crate) fn key(id: &str, name: &str, salt: u64) -> u64 { + let mut hasher = AHasher::default(); + hasher.write(id.as_bytes()); + hasher.write(name.as_bytes()); + hasher.write_u64(salt); + hasher.finish() + } + pub fn get(&self, key: u64) -> Option>> { let read = self.inner.read().ok()?; read.get(&key).cloned() @@ -36,15 +39,17 @@ impl ValidatorCache { .write() .ok() .context("Failed to acquire lock on validator cache")?; - let validator = Arc::new( - jsonschema::options_for::() - .with_draft(jsonschema::Draft::Draft7) - .with_format("date", zen_expression::DateValue::is_text) - .with_format("date-time", zen_expression::DateValue::is_text) - .build(schema)?, - ); + let validator = Arc::new(Self::build(schema)?); w_shared.insert(key, validator.clone()); Ok(validator) } + + pub(crate) fn build(schema: &Value) -> anyhow::Result> { + Ok(jsonschema::options_for::() + .with_draft(jsonschema::Draft::Draft7) + .with_format("date", zen_expression::DateValue::is_text) + .with_format("date-time", zen_expression::DateValue::is_text) + .build(schema)?) + } } diff --git a/core/engine/src/policy/blocks/assertion.rs b/core/engine/src/policy/blocks/assertion.rs index a5f68360..cfb6591c 100644 --- a/core/engine/src/policy/blocks/assertion.rs +++ b/core/engine/src/policy/blocks/assertion.rs @@ -2,16 +2,13 @@ use std::sync::Arc; use ahash::HashSet; use serde::{Deserialize, Serialize}; -use zen_expression::variable::{Variable, VariableType}; -use zen_expression::Isolate; +use zen_expression::variable::VariableType; -use crate::workspace::types::{ - BlockTrace, ConditionTrace, Cursor, CursorTarget, Diagnostic, DiagnosticCode, ExpressionKind, -}; +use crate::workspace::types::{Cursor, CursorTarget, Diagnostic, DiagnosticCode, ExpressionKind}; use crate::policy::ArcStrTrim; -use super::context::{AnalysisContext, ExecutionContext, ExecutionError}; +use super::context::AnalysisContext; use super::{ Block, BlockKind, BlockReadPlan, ConditionalReads, ExpressionLocation, ParseContext, ReadFlattenFn, WriteSite, WriteTarget, @@ -203,21 +200,6 @@ impl AssertionIr { } } - pub(super) fn execute(&self, cx: &ExecutionContext) -> Result { - let mut isolate = cx.isolate.borrow_mut(); - let mut traces: Vec = Vec::new(); - let result = self.evaluate_conditions(&mut isolate, cx, &mut traces)?; - - if !self.output.is_empty() { - cx.write(&self.output, Variable::Bool(result)); - } - - Ok(BlockTrace::Assertion { - result, - conditions: traces, - }) - } - pub(super) fn resolve_cursor( &self, cursor: &Cursor, @@ -235,14 +217,9 @@ impl AssertionIr { } } - fn evaluate_conditions( - &self, - isolate: &mut Isolate, - cx: &ExecutionContext, - traces: &mut Vec, - ) -> Result { + pub(crate) fn fold(&self, results: &[bool]) -> bool { if self.conditions.is_empty() { - return Ok(false); + return false; } let mut stack: Vec = Vec::new(); @@ -251,7 +228,7 @@ impl AssertionIr { let mut depth = 0u32; let mut combine_next = ConditionOperator::And; - for condition in &self.conditions { + for (condition, &cond_result) in self.conditions.iter().zip(results) { while condition.depth > depth { stack.push(Frame { acc, @@ -271,17 +248,6 @@ impl AssertionIr { depth -= 1; } - let cond_result = isolate - .run_standard(&condition.expression) - .map_err(|e| cx.expression_error(&condition.expression, e))? - .as_bool() - .unwrap_or(false); - - traces.push(ConditionTrace { - id: condition.id.clone(), - result: cond_result, - }); - acc = if started { combine_next.apply(acc, cond_result) } else { @@ -295,7 +261,7 @@ impl AssertionIr { acc = frame.close(acc); } - Ok(acc) + acc } } diff --git a/core/engine/src/policy/blocks/context.rs b/core/engine/src/policy/blocks/context.rs index 8cd75498..6a350d74 100644 --- a/core/engine/src/policy/blocks/context.rs +++ b/core/engine/src/policy/blocks/context.rs @@ -3,8 +3,8 @@ use std::rc::Rc; use std::sync::Arc; use zen_expression::intellisense::{ArmTest, ExpressionAnalysis, IntelliSense, ReadDependency}; -use zen_expression::variable::{Variable, VariableType}; -use zen_expression::{Isolate, IsolateError}; +use zen_expression::variable::VariableType; +use zen_expression::IsolateError; use super::property_read::ReadFlattener; use super::type_check::TypeCheck; @@ -16,11 +16,13 @@ use crate::policy::queries::scope::VariableTypeScope; use crate::workspace::db::AnalysisPass; use crate::workspace::types::{ CursorTarget, Diagnostic, DiagnosticArgs, DiagnosticCode, DiagnosticLocation, ExpressionKind, - Severity, WriteTrace, + Severity, }; pub type SharedIntelliSense = Rc>; +type Problem = (Option>, Option<(u32, u32)>, String); + #[derive(Debug, Clone)] pub struct ExpressionLocation { pub block_id: Arc, @@ -418,7 +420,7 @@ impl AnalysisContext { } fn validate_reads(&mut self) { - let mut problems: Vec<(Option>, Option<(u32, u32)>, String)> = Vec::new(); + let mut problems: Vec = Vec::new(); for read in &self.reads { if matches!(read.path.as_ref(), "$" | "$root") || read.via_alias || read.unresolved { continue; @@ -515,59 +517,6 @@ pub struct AnalysisSummary { pub table_checks: Vec, } -pub struct ExecutionContext<'a> { - pub store: &'a Variable, - pub policy_path: &'a Arc, - pub block_id: &'a Arc, - pub trace: bool, - pub extras: bool, - pub write_log: Option<&'a RefCell>>, - pub env_mirror: Option<&'a Variable>, - pub isolate: &'a RefCell, -} - -impl ExecutionContext<'_> { - pub fn expression_error(&self, expression: &Arc, source: IsolateError) -> ExecutionError { - ExecutionError { - block_id: self.block_id.clone(), - policy_path: self.policy_path.clone(), - expression: expression.clone(), - source, - } - } - - pub fn write(&self, path: &Arc, value: Variable) { - if let Some(log) = self.write_log { - log.borrow_mut().push(WriteTrace { - path: path.clone(), - value: value.deep_clone(), - }); - } - self.store.dot_insert(path, value); - self.mirror_top_level(path); - } - - fn mirror_top_level(&self, path: &str) { - let Some(env) = self.env_mirror else { - return; - }; - let (Some(store_fields), Some(env_fields)) = (self.store.as_object(), env.as_object()) - else { - return; - }; - let segment = &path[..path.find('.').unwrap_or(path.len())]; - let store_fields = store_fields.borrow(); - let Some((key, value)) = - store_fields.get_key_value(&zen_types::symbol::Symbol::from(segment)) - else { - return; - }; - env_fields - .borrow_mut() - .insert(key.clone(), value.shallow_clone()); - } -} - pub(crate) struct IntelliSenseSource; impl IntelliSenseSource { diff --git a/core/engine/src/policy/blocks/decision_table.rs b/core/engine/src/policy/blocks/decision_table.rs index 88a48a25..d7fedb2c 100644 --- a/core/engine/src/policy/blocks/decision_table.rs +++ b/core/engine/src/policy/blocks/decision_table.rs @@ -1,37 +1,44 @@ use std::sync::{Arc, OnceLock}; use ahash::{HashMap, HashSet}; -use fixedbitset::FixedBitSet; use serde::{Deserialize, Serialize}; use zen_expression::intellisense::{ArmTest, IntelliSense, NumberCover}; -use zen_expression::variable::{Variable, VariableType}; -use zen_expression::Isolate; +use zen_expression::variable::VariableType; use zen_types::decision::{ DecisionTableHitPolicy, DecisionTableInputField, DecisionTableOutputField, }; -use base64::Engine as _; - use crate::analysis::table::{HitMode, TableColumn, VerifyTable}; use crate::policy::queries::scope::VariableTypeScope; use crate::workspace::types::{ - BlockTrace, Cursor, CursorTarget, DecisionTableExtras, Diagnostic, DiagnosticArgs, - DiagnosticCode, DiagnosticLocation, ExpressionKind, + Cursor, CursorTarget, Diagnostic, DiagnosticArgs, DiagnosticCode, DiagnosticLocation, + ExpressionKind, }; use crate::policy::ArcStrTrim; -use super::context::{AnalysisContext, ExecutionContext, ExecutionError, TableCheck}; +use super::context::{AnalysisContext, TableCheck}; use super::{ Block, BlockKind, BlockReadPlan, CellReads, ConditionalReads, ExpressionLocation, ParseContext, ReadFlattenFn, WriteSite, WriteTarget, }; +use crate::compiled::{Profile, Rows}; use crate::nodes::decision_table::index::TableIndex; pub(crate) struct TableSelection { pub(crate) matched_rows: Vec, pub(crate) used_cells: Vec<(u32, Arc)>, - input_bits: Option>, + pub(crate) input_bits: Option>, +} + +impl TableSelection { + pub(crate) fn used(used_cells: Vec<(u32, Arc)>) -> Self { + Self { + matched_rows: Vec::new(), + used_cells, + input_bits: None, + } + } } pub(crate) const ROW_ID_KEY: &str = "_id"; @@ -208,7 +215,8 @@ impl DecisionTableIr { col.name = col.name.trimmed(); } - let collect_all = doc.hit_policy == DecisionTableHitPolicy::Collect; + let collect_all = doc.hit_policy == DecisionTableHitPolicy::Collect + && Profile::POLICY.rows == Rows::Fields; let outputs = doc .outputs .iter() @@ -220,7 +228,14 @@ impl DecisionTableIr { kind: BlockKind::DecisionTable(Arc::new(DecisionTableIr { inputs, outputs, - rules: doc.rules.clone(), + rules: match Profile::POLICY.trim { + true => doc + .rules + .iter() + .map(|rule| rule.iter().map(|(k, v)| (k.clone(), v.trimmed())).collect()) + .collect(), + false => doc.rules.clone(), + }, index: OnceLock::new(), })), } @@ -784,176 +799,6 @@ impl DecisionTableIr { } } - pub(crate) fn select(&self, cx: &ExecutionContext) -> Result { - let mut isolate = cx.isolate.borrow_mut(); - let mut col_refs: Vec> = vec![None; self.inputs.len()]; - - let active: Vec<&OutputColumn> = self - .outputs - .iter() - .filter(|c| !c.field.is_empty()) - .collect(); - let has_collect = active.iter().any(|c| c.collect); - let mut pending_scalars = active.iter().filter(|c| !c.collect).count(); - let mut taken: Vec = vec![false; active.len()]; - - let mut matched_rows: Vec = Vec::new(); - let mut used_cells: Vec<(u32, Arc)> = Vec::new(); - let cols = self.inputs.len(); - let bytes_per_row = cols.div_ceil(8); - let mut input_bits: Option> = cx - .extras - .then(|| vec![0u8; self.rules.len() * bytes_per_row]); - let candidates = match input_bits { - None => self.candidate_rows(&mut isolate, &mut col_refs, cx)?, - Some(_) => None, - }; - - for (row_idx, rule) in self.rules.iter().enumerate() { - let satisfied = !has_collect && pending_scalars == 0 && !matched_rows.is_empty(); - if satisfied && !cx.extras { - break; - } - - let row_matches = match input_bits.as_mut() { - Some(bits) => { - let per_col = self.evaluate_row_inputs_full( - rule, - &mut isolate, - &mut col_refs, - cx, - satisfied, - )?; - for (col_idx, &passed) in per_col.iter().enumerate() { - if passed { - let byte = row_idx * bytes_per_row + col_idx / 8; - bits[byte] |= 1 << (col_idx % 8); - } - } - per_col.iter().all(|p| *p) - } - None => match &candidates { - Some(rows) if !rows.contains(row_idx) => false, - Some(_) => self.evaluate_row_inputs_pruned( - row_idx, - rule, - &mut isolate, - &mut col_refs, - cx, - )?, - None => self.evaluate_row_inputs(rule, &mut isolate, &mut col_refs, cx)?, - }, - }; - if !row_matches || satisfied { - continue; - } - - matched_rows.push(row_idx as u32); - for (col_pos, col) in active.iter().enumerate() { - if rule.get(&col.id).filter(|c| !c.is_empty()).is_none() { - continue; - } - if col.collect { - used_cells.push((row_idx as u32, col.id.clone())); - } else if !taken[col_pos] { - taken[col_pos] = true; - used_cells.push((row_idx as u32, col.id.clone())); - pending_scalars -= 1; - } - } - } - - Ok(TableSelection { - matched_rows, - used_cells, - input_bits, - }) - } - - pub(crate) fn commit( - &self, - cx: &ExecutionContext, - selection: &TableSelection, - ) -> Result { - let mut isolate = cx.isolate.borrow_mut(); - - let used: HashSet<(u32, &str)> = selection - .used_cells - .iter() - .map(|(row, col)| (*row, col.as_ref())) - .collect(); - let mut collected: HashMap, Vec> = HashMap::default(); - let mut scalar_written: HashSet> = HashSet::default(); - for col in &self.outputs { - if col.collect && !col.field.is_empty() { - collected.entry(col.field.clone()).or_default(); - } - } - - let mut evaluations: Vec, Variable>> = Vec::new(); - for &row_idx in &selection.matched_rows { - let Some(rule) = self.rules.get(row_idx as usize) else { - continue; - }; - let mut row_outputs: HashMap, Variable> = HashMap::default(); - - for col in &self.outputs { - if !used.contains(&(row_idx, col.id.as_ref())) { - continue; - } - let Some(cell) = rule.get(&col.id).filter(|c| !c.is_empty()) else { - continue; - }; - - let value = isolate - .run_standard(cell) - .map_err(|e| cx.expression_error(cell, e))?; - - if cx.trace { - row_outputs.insert(col.field.clone(), value.deep_clone()); - } - - if col.collect { - collected.entry(col.field.clone()).or_default().push(value); - } else { - cx.write(&col.field, value); - scalar_written.insert(col.field.clone()); - } - } - if cx.trace { - evaluations.push(row_outputs); - } - } - - for col in &self.outputs { - if !col.collect && !col.field.is_empty() && !scalar_written.contains(&col.field) { - cx.write(&col.field, Variable::Null); - scalar_written.insert(col.field.clone()); - } - } - for (field, values) in collected { - cx.write(&field, Variable::from_array(values)); - } - - let extras = selection - .input_bits - .as_ref() - .map(|bits| DecisionTableExtras { - input_pass: base64::engine::general_purpose::STANDARD.encode(bits), - }); - - Ok(BlockTrace::DecisionTable { - matched_rows: selection.matched_rows.clone(), - evaluations, - extras, - }) - } - - pub(super) fn execute(&self, cx: &ExecutionContext) -> Result { - let selection = self.select(cx)?; - self.commit(cx, &selection) - } - pub(super) fn resolve_cursor( &self, cursor: &Cursor, @@ -1029,156 +874,11 @@ impl DecisionTableIr { .map(ColumnRef::Output) } - fn table_index(&self) -> Option<&TableIndex> { + pub(crate) fn table_index(&self) -> Option<&TableIndex> { self.index .get_or_init(|| TableIndex::build(&self.inputs, &self.rules)) .as_ref() } - - fn candidate_rows( - &self, - isolate: &mut Isolate, - col_refs: &mut [Option], - cx: &ExecutionContext, - ) -> Result, ExecutionError> { - let Some(index) = self.table_index() else { - return Ok(None); - }; - let mut acc: Option = None; - for (col_idx, column) in index.columns.iter().enumerate() { - let Some(column) = column else { - continue; - }; - let Some(field) = self.inputs[col_idx] - .field - .as_ref() - .filter(|f| !f.is_empty()) - else { - continue; - }; - let value = match &col_refs[col_idx] { - Some(value) => value.shallow_clone(), - None => { - let value = isolate - .run_standard(field) - .map_err(|e| cx.expression_error(field, e))?; - col_refs[col_idx] = Some(value.shallow_clone()); - value - } - }; - if matches!(value, Variable::Dynamic(_)) { - return Ok(None); - } - let mut col_rows = column.fallback.clone(); - if let Some(hit) = column.rows_for(&value) { - col_rows.union_with(hit); - } - match &mut acc { - None => acc = Some(col_rows), - Some(set) => set.intersect_with(&col_rows), - } - } - Ok(acc) - } - - fn evaluate_row_inputs_pruned( - &self, - row_idx: usize, - rule: &HashMap, Arc>, - isolate: &mut Isolate, - col_refs: &mut [Option], - cx: &ExecutionContext, - ) -> Result { - let index = self.table_index(); - for (col_idx, col) in self.inputs.iter().enumerate() { - if index.is_some_and(|ix| ix.decides(col_idx, row_idx)) { - continue; - } - if !self.evaluate_cell(col_idx, col, rule, isolate, col_refs, cx)? { - return Ok(false); - } - } - Ok(true) - } - - fn evaluate_row_inputs( - &self, - rule: &HashMap, Arc>, - isolate: &mut Isolate, - col_refs: &mut [Option], - cx: &ExecutionContext, - ) -> Result { - for (col_idx, col) in self.inputs.iter().enumerate() { - if !self.evaluate_cell(col_idx, col, rule, isolate, col_refs, cx)? { - return Ok(false); - } - } - Ok(true) - } - - fn evaluate_row_inputs_full( - &self, - rule: &HashMap, Arc>, - isolate: &mut Isolate, - col_refs: &mut [Option], - cx: &ExecutionContext, - row_unreached: bool, - ) -> Result, ExecutionError> { - let mut row_failed = false; - self.inputs - .iter() - .enumerate() - .map(|(col_idx, col)| { - let passed = match self.evaluate_cell(col_idx, col, rule, isolate, col_refs, cx) { - Ok(passed) => passed, - Err(_) if row_unreached || row_failed => false, - Err(e) => return Err(e), - }; - row_failed |= !passed; - Ok(passed) - }) - .collect() - } - - fn evaluate_cell( - &self, - col_idx: usize, - col: &DecisionTableInputField, - rule: &HashMap, Arc>, - isolate: &mut Isolate, - col_refs: &mut [Option], - cx: &ExecutionContext, - ) -> Result { - let Some(cell) = rule.get(&col.id).filter(|c| !c.is_empty()) else { - return Ok(true); - }; - match col.field.as_ref() { - Some(field) if !field.is_empty() => { - let value = match &col_refs[col_idx] { - Some(value) => value.shallow_clone(), - None => { - let value = isolate - .run_standard(field) - .map_err(|e| cx.expression_error(field, e))?; - col_refs[col_idx] = Some(value.shallow_clone()); - value - } - }; - isolate - .set_reference_value(value) - .map_err(|e| cx.expression_error(field, e))?; - isolate - .run_unary(cell) - .map_err(|e| cx.expression_error(cell, e)) - } - _ => { - let result = isolate - .run_standard(cell) - .map_err(|e| cx.expression_error(cell, e))?; - Ok(result.as_bool().unwrap_or(false)) - } - } - } } pub(crate) struct DictionaryCandidate; diff --git a/core/engine/src/policy/blocks/expression.rs b/core/engine/src/policy/blocks/expression.rs index 18b68e20..d9ae7f4e 100644 --- a/core/engine/src/policy/blocks/expression.rs +++ b/core/engine/src/policy/blocks/expression.rs @@ -2,15 +2,13 @@ use std::sync::Arc; use ahash::HashSet; use serde::{Deserialize, Serialize}; -use zen_expression::variable::{Variable, VariableType}; +use zen_expression::variable::VariableType; -use crate::workspace::types::{ - BlockTrace, Cursor, CursorTarget, Diagnostic, DiagnosticCode, ExpressionKind, -}; +use crate::workspace::types::{Cursor, CursorTarget, Diagnostic, DiagnosticCode, ExpressionKind}; use crate::policy::ArcStrTrim; -use super::context::{AnalysisContext, ExecutionContext, ExecutionError}; +use super::context::AnalysisContext; use super::{ Block, BlockKind, BlockReadPlan, ConditionalReads, ExpressionLocation, ParseContext, ReadFlattenFn, WriteSite, WriteTarget, @@ -139,27 +137,6 @@ impl ExpressionIr { ); } - pub(super) fn execute(&self, cx: &ExecutionContext) -> Result { - if self.key.is_empty() || self.value.is_empty() { - return Ok(BlockTrace::Expression { - property: self.key.clone(), - value: Variable::Null, - }); - } - - let mut isolate = cx.isolate.borrow_mut(); - let result = isolate - .run_standard(&self.value) - .map_err(|e| cx.expression_error(&self.value, e))?; - let traced = cx.trace.then(|| result.deep_clone()); - cx.write(&self.key, result); - - Ok(BlockTrace::Expression { - property: self.key.clone(), - value: traced.unwrap_or(Variable::Null), - }) - } - pub(super) fn resolve_cursor( &self, cursor: &Cursor, diff --git a/core/engine/src/policy/blocks/match_block.rs b/core/engine/src/policy/blocks/match_block.rs index d96a5f7b..fe9e2d1c 100644 --- a/core/engine/src/policy/blocks/match_block.rs +++ b/core/engine/src/policy/blocks/match_block.rs @@ -3,18 +3,18 @@ use std::sync::Arc; use ahash::HashSet; use serde::{Deserialize, Serialize}; use zen_expression::intellisense::{ArmTest, NumberCover}; -use zen_expression::variable::{Variable, VariableType}; +use zen_expression::variable::VariableType; use crate::policy::queries::scope::VariableTypeScope; use crate::workspace::types::{ - BlockTrace, ConditionTrace, Cursor, CursorTarget, Diagnostic, DiagnosticArgs, DiagnosticCode, + ConditionTrace, Cursor, CursorTarget, Diagnostic, DiagnosticArgs, DiagnosticCode, ExpressionKind, }; use crate::policy::ArcStrTrim; -use super::context::{AnalysisContext, ExecutionContext, ExecutionError, InstanceSource}; +use super::context::{AnalysisContext, InstanceSource}; use super::{ ArmReads, Block, BlockKind, BlockReadPlan, ConditionalReads, ExpressionLocation, ParseContext, ReadFlattenFn, WriteSite, WriteTarget, @@ -22,7 +22,7 @@ use super::{ pub(crate) struct MatchSelection { pub(crate) matched_arm: Option>, - arms: Vec, + pub(crate) arms: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -345,77 +345,6 @@ impl MatchIr { } } - pub(crate) fn select(&self, cx: &ExecutionContext) -> Result { - let mut isolate = cx.isolate.borrow_mut(); - - let mut arms: Vec = Vec::new(); - let mut matched_arm: Option> = None; - - for arm in &self.arms { - if matched_arm.is_some() && !cx.extras { - break; - } - let matches = if arm.condition.is_empty() { - true - } else { - match isolate.run_standard(&arm.condition) { - Ok(value) => value.as_bool().unwrap_or(false), - Err(_) if cx.extras && matched_arm.is_some() => false, - Err(e) => return Err(cx.expression_error(&arm.condition, e)), - } - }; - arms.push(ConditionTrace { - id: arm.id.clone(), - result: matches, - }); - if matches && matched_arm.is_none() { - matched_arm = Some(arm.id.clone()); - } - } - - Ok(MatchSelection { matched_arm, arms }) - } - - pub(crate) fn commit( - &self, - cx: &ExecutionContext, - selection: &MatchSelection, - ) -> Result { - let matched = selection - .matched_arm - .as_ref() - .and_then(|id| self.arms.iter().find(|a| &a.id == id)); - let value = match matched { - Some(arm) if !arm.value.is_empty() => { - let mut isolate = cx.isolate.borrow_mut(); - isolate - .run_standard(&arm.value) - .map_err(|e| cx.expression_error(&arm.value, e))? - } - _ => Variable::Null, - }; - - let traced = cx.trace.then(|| value.deep_clone()); - if !self.key.is_empty() { - cx.write(&self.key, value); - } - - Ok(BlockTrace::Match { - matched_arm: selection.matched_arm.clone(), - value: traced.unwrap_or(Variable::Null), - arms: if cx.trace { - selection.arms.clone() - } else { - Vec::new() - }, - }) - } - - pub(super) fn execute(&self, cx: &ExecutionContext) -> Result { - let selection = self.select(cx)?; - self.commit(cx, &selection) - } - pub(super) fn resolve_cursor( &self, cursor: &Cursor, diff --git a/core/engine/src/policy/blocks/mod.rs b/core/engine/src/policy/blocks/mod.rs index e9d2fd99..db549c5a 100644 --- a/core/engine/src/policy/blocks/mod.rs +++ b/core/engine/src/policy/blocks/mod.rs @@ -12,8 +12,7 @@ use ahash::{HashMap, HashMapExt, HashSet}; use zen_expression::variable::VariableType; use crate::workspace::types::{ - BlockTrace, Cursor, CursorTarget, Diagnostic, DiagnosticCode, DiagnosticLocation, - ExpressionKind, Span, + Cursor, CursorTarget, Diagnostic, DiagnosticCode, DiagnosticLocation, ExpressionKind, Span, }; #[derive(Debug, Clone)] @@ -24,11 +23,12 @@ pub struct WriteSite { pub contributing_expr_ids: HashSet>, } +pub(crate) use assertion::ConditionOperator; pub use assertion::{AssertionDoc, AssertionIr}; pub(crate) use context::IntelliSenseSource; pub use context::{ - AnalysisContext, AnalysisSummary, ExecutionContext, ExecutionError, ExpressionLocation, - InstanceSource, PropertyRead, SharedDeclaredPaths, SharedDictionaryTypes, SharedIntelliSense, + AnalysisContext, AnalysisSummary, ExecutionError, ExpressionLocation, InstanceSource, + PropertyRead, SharedDeclaredPaths, SharedDictionaryTypes, SharedIntelliSense, SharedPoisonedPaths, TableCheck, WriteTarget, }; pub use decision_table::{DecisionTableDoc, DecisionTableIr, DeclaredType}; @@ -220,10 +220,6 @@ pub enum BlockKind { } impl Block { - pub fn execute(&self, cx: &ExecutionContext) -> Result { - self.kind.execute(cx) - } - pub fn resolve_cursor( &self, cursor: &Cursor, @@ -289,15 +285,6 @@ impl BlockKind { } } - pub fn execute(&self, cx: &ExecutionContext) -> Result { - match self { - BlockKind::Assertion(a) => a.execute(cx), - BlockKind::DecisionTable(d) => d.execute(cx), - BlockKind::Expression(e) => e.execute(cx), - BlockKind::Match(m) => m.execute(cx), - } - } - pub(crate) fn read_plan(&self, flatten: &mut ReadFlattenFn) -> BlockReadPlan { match self { BlockKind::Assertion(a) => a.read_plan(flatten), diff --git a/core/engine/src/policy/driver.rs b/core/engine/src/policy/driver.rs new file mode 100644 index 00000000..92a01f61 --- /dev/null +++ b/core/engine/src/policy/driver.rs @@ -0,0 +1,714 @@ +use std::cell::RefCell; +use std::sync::Arc; +use std::time::Instant; + +use ahash::{HashMap, HashSet, HashSetExt}; +use base64::Engine as _; +use fixedbitset::FixedBitSet; +use zen_expression::variable::Variable; +use zen_expression::{Isolate, IsolateError}; +use zen_types::decision::DecisionTableInputField; + +use crate::policy::blocks::{ + AssertionIr, Block, BlockKind, DecisionTableIr, ExecutionError, ExpressionIr, MatchIr, + MatchSelection, TableSelection, +}; +use crate::policy::evaluator::{EvalArtifact, StoreOps}; +use crate::policy::host::{Evaluate, HostState, Pick, Picked, Site}; +use crate::workspace::db::Db; +use crate::workspace::types::{ + BlockExecution, BlockRef, BlockTrace, ConditionTrace, DecisionTableExtras, EvaluateRequest, + EvaluationError, EvaluationResult, Trace, WriteTrace, +}; + +impl Db { + pub fn evaluate_with_driver( + &self, + req: &EvaluateRequest, + ) -> Result { + self.check_evaluable(req)?; + self.eval_artifact(&req.policy_path) + .evaluate_with_driver(req, false) + } + + pub fn enhance_trace_with_driver( + &self, + req: &EvaluateRequest, + ) -> Result { + self.check_evaluable(req)?; + let mut req = req.clone(); + req.trace = true; + self.eval_artifact(&req.policy_path) + .evaluate_with_driver(&req, true) + } +} + +impl EvalArtifact { + pub(crate) fn evaluate_with_driver( + &self, + req: &EvaluateRequest, + extras: bool, + ) -> Result { + let start = Instant::now(); + let (store, order_to_run) = self.prepare(req)?; + let roots = self.roots(req); + let mut driver = Driver::new(self, &store, &req.policy_path, req.trace, extras); + let outcome = roots.iter().try_for_each(|root| driver.demand(root)); + + let trace = req.trace.then(|| Trace { + engine_version: Arc::from(crate::ENGINE_VERSION), + properties: store.snapshot(&order_to_run), + executions: driver.executions(), + }); + + if let Err(error) = outcome { + return Err(error.with_partial_trace(trace)); + } + + Ok(EvaluationResult { + output: store, + duration: start.elapsed(), + trace, + }) + } + + pub(crate) fn roots(&self, req: &EvaluateRequest) -> Vec> { + match req.goals.is_empty() { + true => self.eval_graph.terminal_sinks(&self.members), + false => req.goals.clone(), + } + } +} + +pub(crate) struct Driver<'a> { + state: HostState<'a>, + isolate: RefCell, + ran: HashSet, + in_progress: HashSet, +} + +impl Evaluate for RefCell { + fn environment(&mut self, env: Variable) { + self.borrow_mut().set_environment(env); + } + + fn select(&mut self, rule: &Block, site: &Site) -> Result { + let ctx = ExecutionContext::of(site, self); + match &rule.kind { + BlockKind::Match(m) => m.select(&ctx).map(Pick::Match), + BlockKind::DecisionTable(d) => d.select(&ctx).map(Pick::Table), + BlockKind::Expression(_) | BlockKind::Assertion(_) => Ok(Pick::Unconditional), + } + } + + fn commit( + &mut self, + rule: &Block, + site: &Site, + pick: &Pick, + ) -> Result { + let ctx = ExecutionContext::of(site, self); + match (&rule.kind, pick) { + (BlockKind::Match(m), Pick::Match(selection)) => m.commit(&ctx, selection), + (BlockKind::DecisionTable(d), Pick::Table(selection)) => d.commit(&ctx, selection), + _ => rule.execute(&ctx), + } + } +} + +impl<'a> Driver<'a> { + pub(crate) fn new( + artifact: &'a EvalArtifact, + store: &'a Variable, + entry: &'a Arc, + trace: bool, + extras: bool, + ) -> Self { + Self { + isolate: RefCell::new(Isolate::new().with_cache(Some(artifact.opcode_cache.clone()))), + state: HostState::new(artifact, store, entry, trace, extras), + ran: HashSet::new(), + in_progress: HashSet::new(), + } + } + + pub(crate) fn executions(self) -> Vec { + self.state.executions() + } + + pub(crate) fn demand(&mut self, prop: &str) -> Result<(), EvaluationError> { + self.state + .writers_of_longest_prefix(prop) + .iter() + .try_for_each(|owner| self.run_block(owner)) + } + + fn run_block(&mut self, owner: &BlockRef) -> Result<(), EvaluationError> { + if self.ran.contains(owner) || !self.in_progress.insert(owner.clone()) { + return Ok(()); + } + let result = self.run_block_inner(owner); + self.in_progress.remove(owner); + if result.is_ok() { + self.ran.insert(owner.clone()); + } + result + } + + fn run_block_inner(&mut self, owner: &BlockRef) -> Result<(), EvaluationError> { + let artifact = self.state.artifact(); + let Some(rule) = artifact.rule_by_ref.get(owner) else { + return Ok(()); + }; + let rule = rule.clone(); + + if let Some(plan) = artifact.read_plans.get(owner) { + for path in plan.unconditional.iter() { + self.demand(path)?; + } + } + + let picked = self.select(owner, &rule)?; + for path in &self.state.demanded(owner, &picked) { + self.demand(path)?; + } + self.commit(owner, &rule, picked) + } + + pub(crate) fn select( + &mut self, + owner: &BlockRef, + rule: &Block, + ) -> Result { + self.state.select(owner, rule, &mut self.isolate) + } + + pub(crate) fn commit( + &mut self, + owner: &BlockRef, + rule: &Block, + picked: Picked, + ) -> Result<(), EvaluationError> { + self.state.commit(owner, rule, picked, &mut self.isolate) + } +} + +pub(crate) struct ExecutionContext<'a> { + pub(crate) store: &'a Variable, + pub(crate) policy_path: &'a Arc, + pub(crate) block_id: &'a Arc, + pub(crate) trace: bool, + pub(crate) extras: bool, + pub(crate) write_log: Option<&'a RefCell>>, + pub(crate) env_mirror: Option<&'a Variable>, + pub(crate) isolate: &'a RefCell, +} + +impl<'a> ExecutionContext<'a> { + pub(crate) fn of(site: &Site<'a>, isolate: &'a RefCell) -> Self { + Self { + store: site.store, + policy_path: site.policy_path, + block_id: site.block_id, + trace: site.trace, + extras: site.extras, + write_log: site.write_log, + env_mirror: site.env_mirror, + isolate, + } + } + + pub(crate) fn expression_error( + &self, + expression: &Arc, + source: IsolateError, + ) -> ExecutionError { + ExecutionError { + block_id: self.block_id.clone(), + policy_path: self.policy_path.clone(), + expression: expression.clone(), + source, + } + } + + pub(crate) fn write(&self, path: &Arc, value: Variable) { + if let Some(log) = self.write_log { + log.borrow_mut().push(WriteTrace { + path: path.clone(), + value: value.deep_clone(), + }); + } + HostState::write_into(self.store, self.env_mirror, path, value); + } +} + +impl Block { + pub(crate) fn execute(&self, cx: &ExecutionContext) -> Result { + self.kind.execute(cx) + } +} + +impl BlockKind { + pub(crate) fn execute(&self, cx: &ExecutionContext) -> Result { + match self { + BlockKind::Assertion(a) => a.execute(cx), + BlockKind::DecisionTable(d) => d.execute(cx), + BlockKind::Expression(e) => e.execute(cx), + BlockKind::Match(m) => m.execute(cx), + } + } +} + +impl ExpressionIr { + pub(crate) fn execute(&self, cx: &ExecutionContext) -> Result { + if self.key.is_empty() || self.value.is_empty() { + return Ok(BlockTrace::Expression { + property: self.key.clone(), + value: Variable::Null, + }); + } + + let mut isolate = cx.isolate.borrow_mut(); + let result = isolate + .run_standard(&self.value) + .map_err(|e| cx.expression_error(&self.value, e))?; + let traced = cx.trace.then(|| result.deep_clone()); + cx.write(&self.key, result); + + Ok(BlockTrace::Expression { + property: self.key.clone(), + value: traced.unwrap_or(Variable::Null), + }) + } +} + +impl AssertionIr { + pub(crate) fn execute(&self, cx: &ExecutionContext) -> Result { + let mut isolate = cx.isolate.borrow_mut(); + let mut traces: Vec = Vec::new(); + let result = self.evaluate_conditions(&mut isolate, cx, &mut traces)?; + + if !self.output.is_empty() { + cx.write(&self.output, Variable::Bool(result)); + } + + Ok(BlockTrace::Assertion { + result, + conditions: traces, + }) + } + + fn evaluate_conditions( + &self, + isolate: &mut Isolate, + cx: &ExecutionContext, + traces: &mut Vec, + ) -> Result { + let mut results = Vec::with_capacity(self.conditions.len()); + for condition in &self.conditions { + let cond_result = isolate + .run_standard(&condition.expression) + .map_err(|e| cx.expression_error(&condition.expression, e))? + .as_bool() + .unwrap_or(false); + traces.push(ConditionTrace { + id: condition.id.clone(), + result: cond_result, + }); + results.push(cond_result); + } + Ok(self.fold(&results)) + } +} + +impl MatchIr { + pub(crate) fn select(&self, cx: &ExecutionContext) -> Result { + let mut isolate = cx.isolate.borrow_mut(); + + let mut arms: Vec = Vec::new(); + let mut matched_arm: Option> = None; + + for arm in &self.arms { + if matched_arm.is_some() && !cx.extras { + break; + } + let matches = if arm.condition.is_empty() { + true + } else { + match isolate.run_standard(&arm.condition) { + Ok(value) => value.as_bool().unwrap_or(false), + Err(_) if cx.extras && matched_arm.is_some() => false, + Err(e) => return Err(cx.expression_error(&arm.condition, e)), + } + }; + arms.push(ConditionTrace { + id: arm.id.clone(), + result: matches, + }); + if matches && matched_arm.is_none() { + matched_arm = Some(arm.id.clone()); + } + } + + Ok(MatchSelection { matched_arm, arms }) + } + + pub(crate) fn commit( + &self, + cx: &ExecutionContext, + selection: &MatchSelection, + ) -> Result { + let matched = selection + .matched_arm + .as_ref() + .and_then(|id| self.arms.iter().find(|a| &a.id == id)); + let value = match matched { + Some(arm) if !arm.value.is_empty() => { + let mut isolate = cx.isolate.borrow_mut(); + isolate + .run_standard(&arm.value) + .map_err(|e| cx.expression_error(&arm.value, e))? + } + _ => Variable::Null, + }; + + let traced = cx.trace.then(|| value.deep_clone()); + if !self.key.is_empty() { + cx.write(&self.key, value); + } + + Ok(BlockTrace::Match { + matched_arm: selection.matched_arm.clone(), + value: traced.unwrap_or(Variable::Null), + arms: if cx.trace { + selection.arms.clone() + } else { + Vec::new() + }, + }) + } + + pub(crate) fn execute(&self, cx: &ExecutionContext) -> Result { + let selection = self.select(cx)?; + self.commit(cx, &selection) + } +} + +impl DecisionTableIr { + pub(crate) fn select(&self, cx: &ExecutionContext) -> Result { + let mut isolate = cx.isolate.borrow_mut(); + let mut col_refs: Vec> = vec![None; self.inputs.len()]; + + let active: Vec<_> = self + .outputs + .iter() + .filter(|c| !c.field.is_empty()) + .collect(); + let has_collect = active.iter().any(|c| c.collect); + let mut pending_scalars = active.iter().filter(|c| !c.collect).count(); + let mut taken: Vec = vec![false; active.len()]; + + let mut matched_rows: Vec = Vec::new(); + let mut used_cells: Vec<(u32, Arc)> = Vec::new(); + let cols = self.inputs.len(); + let bytes_per_row = cols.div_ceil(8); + let mut input_bits: Option> = cx + .extras + .then(|| vec![0u8; self.rules.len() * bytes_per_row]); + let candidates = match input_bits { + None => self.candidate_rows(&mut isolate, &mut col_refs, cx)?, + Some(_) => None, + }; + + for (row_idx, rule) in self.rules.iter().enumerate() { + let satisfied = !has_collect && pending_scalars == 0 && !matched_rows.is_empty(); + if satisfied && !cx.extras { + break; + } + + let row_matches = match input_bits.as_mut() { + Some(bits) => { + let per_col = self.evaluate_row_inputs_full( + rule, + &mut isolate, + &mut col_refs, + cx, + satisfied, + )?; + for (col_idx, &passed) in per_col.iter().enumerate() { + if passed { + let byte = row_idx * bytes_per_row + col_idx / 8; + bits[byte] |= 1 << (col_idx % 8); + } + } + per_col.iter().all(|p| *p) + } + None => match &candidates { + Some(rows) if !rows.contains(row_idx) => false, + Some(_) => self.evaluate_row_inputs_pruned( + row_idx, + rule, + &mut isolate, + &mut col_refs, + cx, + )?, + None => self.evaluate_row_inputs(rule, &mut isolate, &mut col_refs, cx)?, + }, + }; + if !row_matches || satisfied { + continue; + } + + matched_rows.push(row_idx as u32); + for (col_pos, col) in active.iter().enumerate() { + if rule.get(&col.id).filter(|c| !c.is_empty()).is_none() { + continue; + } + if col.collect { + used_cells.push((row_idx as u32, col.id.clone())); + } else if !taken[col_pos] { + taken[col_pos] = true; + used_cells.push((row_idx as u32, col.id.clone())); + pending_scalars -= 1; + } + } + } + + Ok(TableSelection { + matched_rows, + used_cells, + input_bits, + }) + } + + pub(crate) fn commit( + &self, + cx: &ExecutionContext, + selection: &TableSelection, + ) -> Result { + let mut isolate = cx.isolate.borrow_mut(); + + let used: HashSet<(u32, &str)> = selection + .used_cells + .iter() + .map(|(row, col)| (*row, col.as_ref())) + .collect(); + let mut collected: HashMap, Vec> = HashMap::default(); + let mut scalar_written: HashSet> = HashSet::default(); + for col in &self.outputs { + if col.collect && !col.field.is_empty() { + collected.entry(col.field.clone()).or_default(); + } + } + + let mut evaluations: Vec, Variable>> = Vec::new(); + for &row_idx in &selection.matched_rows { + let Some(rule) = self.rules.get(row_idx as usize) else { + continue; + }; + let mut row_outputs: HashMap, Variable> = HashMap::default(); + + for col in &self.outputs { + if !used.contains(&(row_idx, col.id.as_ref())) { + continue; + } + let Some(cell) = rule.get(&col.id).filter(|c| !c.is_empty()) else { + continue; + }; + + let value = isolate + .run_standard(cell) + .map_err(|e| cx.expression_error(cell, e))?; + + if cx.trace { + row_outputs.insert(col.field.clone(), value.deep_clone()); + } + + if col.collect { + collected.entry(col.field.clone()).or_default().push(value); + } else { + cx.write(&col.field, value); + scalar_written.insert(col.field.clone()); + } + } + if cx.trace { + evaluations.push(row_outputs); + } + } + + for col in &self.outputs { + if !col.collect && !col.field.is_empty() && !scalar_written.contains(&col.field) { + cx.write(&col.field, Variable::Null); + scalar_written.insert(col.field.clone()); + } + } + for col in &self.outputs { + if let Some(values) = collected.remove(&col.field) { + cx.write(&col.field, Variable::from_array(values)); + } + } + + let extras = selection + .input_bits + .as_ref() + .map(|bits| DecisionTableExtras { + input_pass: base64::engine::general_purpose::STANDARD.encode(bits), + }); + + Ok(BlockTrace::DecisionTable { + matched_rows: selection.matched_rows.clone(), + evaluations, + extras, + }) + } + + pub(crate) fn execute(&self, cx: &ExecutionContext) -> Result { + let selection = self.select(cx)?; + self.commit(cx, &selection) + } + + fn candidate_rows( + &self, + isolate: &mut Isolate, + col_refs: &mut [Option], + cx: &ExecutionContext, + ) -> Result, ExecutionError> { + let Some(index) = self.table_index() else { + return Ok(None); + }; + let mut acc: Option = None; + for (col_idx, column) in index.columns.iter().enumerate() { + let Some(column) = column else { + continue; + }; + let Some(field) = self.inputs[col_idx] + .field + .as_ref() + .filter(|f| !f.is_empty()) + else { + continue; + }; + let value = match &col_refs[col_idx] { + Some(value) => value.shallow_clone(), + None => { + let value = isolate + .run_standard(field) + .map_err(|e| cx.expression_error(field, e))?; + col_refs[col_idx] = Some(value.shallow_clone()); + value + } + }; + if matches!(value, Variable::Dynamic(_)) { + return Ok(None); + } + let mut col_rows = column.fallback.clone(); + if let Some(hit) = column.rows_for(&value) { + col_rows.union_with(hit); + } + match &mut acc { + None => acc = Some(col_rows), + Some(set) => set.intersect_with(&col_rows), + } + } + Ok(acc) + } + + fn evaluate_row_inputs_pruned( + &self, + row_idx: usize, + rule: &HashMap, Arc>, + isolate: &mut Isolate, + col_refs: &mut [Option], + cx: &ExecutionContext, + ) -> Result { + let index = self.table_index(); + for (col_idx, col) in self.inputs.iter().enumerate() { + if index.is_some_and(|ix| ix.decides(col_idx, row_idx)) { + continue; + } + if !self.evaluate_cell(col_idx, col, rule, isolate, col_refs, cx)? { + return Ok(false); + } + } + Ok(true) + } + + fn evaluate_row_inputs( + &self, + rule: &HashMap, Arc>, + isolate: &mut Isolate, + col_refs: &mut [Option], + cx: &ExecutionContext, + ) -> Result { + for (col_idx, col) in self.inputs.iter().enumerate() { + if !self.evaluate_cell(col_idx, col, rule, isolate, col_refs, cx)? { + return Ok(false); + } + } + Ok(true) + } + + fn evaluate_row_inputs_full( + &self, + rule: &HashMap, Arc>, + isolate: &mut Isolate, + col_refs: &mut [Option], + cx: &ExecutionContext, + row_unreached: bool, + ) -> Result, ExecutionError> { + let mut row_failed = false; + self.inputs + .iter() + .enumerate() + .map(|(col_idx, col)| { + let passed = match self.evaluate_cell(col_idx, col, rule, isolate, col_refs, cx) { + Ok(passed) => passed, + Err(_) if row_unreached || row_failed => false, + Err(e) => return Err(e), + }; + row_failed |= !passed; + Ok(passed) + }) + .collect() + } + + fn evaluate_cell( + &self, + col_idx: usize, + col: &DecisionTableInputField, + rule: &HashMap, Arc>, + isolate: &mut Isolate, + col_refs: &mut [Option], + cx: &ExecutionContext, + ) -> Result { + let Some(cell) = rule.get(&col.id).filter(|c| !c.is_empty()) else { + return Ok(true); + }; + match col.field.as_ref() { + Some(field) if !field.is_empty() => { + let value = match &col_refs[col_idx] { + Some(value) => value.shallow_clone(), + None => { + let value = isolate + .run_standard(field) + .map_err(|e| cx.expression_error(field, e))?; + col_refs[col_idx] = Some(value.shallow_clone()); + value + } + }; + isolate + .set_reference_value(value) + .map_err(|e| cx.expression_error(field, e))?; + isolate + .run_unary(cell) + .map_err(|e| cx.expression_error(cell, e)) + } + _ => { + let result = isolate + .run_standard(cell) + .map_err(|e| cx.expression_error(cell, e))?; + Ok(result.as_bool().unwrap_or(false)) + } + } + } +} diff --git a/core/engine/src/policy/evaluator.rs b/core/engine/src/policy/evaluator.rs index 5acb78c9..cd587e8f 100644 --- a/core/engine/src/policy/evaluator.rs +++ b/core/engine/src/policy/evaluator.rs @@ -1,19 +1,12 @@ -use std::cell::RefCell; -use std::rc::Rc; -use std::sync::Arc; -use std::time::Instant; -use zen_types::symbol::Symbol; +use crate::compiled::policy::{Host, PolicyPlan}; +use std::sync::{Arc, Mutex, OnceLock}; use ahash::{HashMap, HashMapExt, HashSet, HashSetExt}; use zen_expression::variable::Variable; -use zen_types::rccell::RcCell; -use zen_expression::{Isolate, OpcodeCache}; +use zen_expression::lane::{Bits, Programs}; -use crate::policy::blocks::{ - Block, BlockKind, BlockReadPlan, ExecutionContext, ExecutionError, MatchSelection, - PropertyRead, TableSelection, -}; +use crate::policy::blocks::{Block, BlockReadPlan, ExecutionError, PropertyRead}; use crate::policy::ir::PropertyPath; use crate::policy::queries::dependency::{DataModelPaths, EvalGraph, WriteScope}; use crate::policy::queries::path::PathClassifier; @@ -22,8 +15,9 @@ use crate::policy::refs::RefPoolIndex; use crate::policy::validator::InputSchema; use crate::workspace::db::Db; use crate::workspace::types::{ - BlockExecution, BlockRef, BlockTrace, EvaluateRequest, EvaluationError, EvaluationResult, Trace, + BlockRef, EvaluateRequest, EvaluationError, EvaluationResult, Trace, }; +use zen_types::path::DotPath; pub(crate) struct EvalArtifact { pub(crate) members: HashSet>, @@ -33,11 +27,227 @@ pub(crate) struct EvalArtifact { pub(crate) reference_fields: Vec, pub(crate) data_model_paths: DataModelPaths, pub(crate) classifier: PathClassifier, - pub(crate) opcode_cache: Arc, + #[cfg(feature = "driver")] + pub(crate) opcode_cache: Arc, pub(crate) rule_by_ref: Arc>>, pub(crate) input_schema: InputSchema, pub(crate) reads: HashMap>, pub(crate) read_plans: HashMap, + pub(crate) compiled: OnceLock>, + pub(crate) goal_plans: Mutex>, Arc>>, + pub(crate) requirements: OnceLock, + pub(crate) programs: OnceLock>, +} + +pub(crate) type Iteration = (Arc, Arc, Option>); + +pub(crate) struct Requirements { + order: Vec, + goals: Vec>, + checks: Vec, +} + +struct Requirement { + path: PropertyPath, + primary: Probe, + alternate: Option, +} + +struct Probe { + segments: Vec>, + optional: Vec, + prefixes: Vec, +} + +impl Probe { + fn new(paths: &DataModelPaths, path: &str) -> Self { + let segments: Vec> = path.split('.').map(Arc::from).collect(); + let prefixes = (0..segments.len()) + .map(|i| { + segments[..=i] + .iter() + .map(|s| s.as_ref()) + .collect::>() + .join(".") + }) + .collect(); + Self { + segments, + optional: paths.optional_steps(path), + prefixes, + } + } + + fn missing(&self, input: &Variable) -> bool { + let mut current = input.shallow_clone(); + for (i, segment) in self.segments.iter().enumerate() { + if current.as_object().is_none() { + return false; + } + let next = current + .as_object() + .and_then(|o| o.borrow().get_str(segment).map(Variable::shallow_clone)); + match next { + Some(Variable::Null) | None => return !self.optional[i..].iter().any(|o| *o), + Some(v) => current = v, + } + } + false + } +} + +struct Steps<'p> { + probe: &'p Probe, + steps: Vec<(Option, Vec)>, +} + +impl<'p> Steps<'p> { + fn new(probe: &'p Probe, columns: &zen_expression::lane::Columns) -> Self { + let steps = probe + .prefixes + .iter() + .map(|path| { + let exact = columns + .columns + .iter() + .position(|(p, _)| *p == path.as_str()); + let under = columns + .columns + .iter() + .enumerate() + .filter(|(_, (p, _))| DotPath::under(p, path)) + .map(|(at, _)| at) + .collect(); + (exact, under) + }) + .collect(); + Self { probe, steps } + } + + fn coded(column: &zen_expression::lane::Column) -> Option { + use zen_expression::lane::{Dictionary, Values}; + match column.values { + Values::Dict { + values: + values @ (Dictionary::Text { .. } + | Dictionary::Scaled { .. } + | Dictionary::Bool { .. }), + .. + } => Some(values.len()), + _ => None, + } + } + + fn held(column: &zen_expression::lane::Column, row: usize) -> bool { + use zen_expression::lane::Values; + match (column.values, Self::coded(column)) { + (Values::Dict { .. }, Some(len)) => { + column.valid(row) && column.code(row).is_some_and(|key| key < len) + } + (Values::Any(_) | Values::Dict { .. }, _) => { + column.valid(row) && !matches!(column.variable(row), Variable::Null) + } + _ => column.valid(row), + } + } + + fn solid(column: &zen_expression::lane::Column, rows: usize) -> bool { + use zen_expression::lane::Values; + let full = column + .validity + .is_none_or(|(bits, offset)| Self::ones(bits, offset, rows)); + match (column.values, Self::coded(column)) { + (Values::Dict { keys, .. }, Some(len)) => { + full && keys.get(..rows).is_some_and(|keys| { + keys.iter() + .all(|&key| usize::try_from(key).is_ok_and(|key| key < len)) + }) + } + (values, _) => full && !matches!(values, Values::Any(_) | Values::Dict { .. }), + } + } + + fn ones(bits: &[u64], offset: usize, rows: usize) -> bool { + (0..rows.div_ceil(64)).all(|w| { + let take = (rows - (w << 6)).min(64); + let mask = match take { + 64 => u64::MAX, + _ => (1u64 << take) - 1, + }; + Bits::word(bits, offset + (w << 6), take) & mask == mask + }) + } + + fn always(&self, columns: &zen_expression::lane::Columns) -> bool { + let rows = columns.rows; + for (i, (exact, under)) in self.steps.iter().enumerate() { + if let Some(at) = exact { + let column = &columns.columns[*at].1; + return Self::solid(column, rows) + && (i + 1 == self.steps.len() + || !matches!(column.values, zen_expression::lane::Values::Struct { .. })); + } + if !under + .iter() + .any(|at| Self::solid(&columns.columns[*at].1, rows)) + { + return false; + } + } + true + } + + fn missing(&self, columns: &zen_expression::lane::Columns, row: usize) -> bool { + let absent = |i: usize| !self.probe.optional[i..].iter().any(|o| *o); + for (i, (exact, under)) in self.steps.iter().enumerate() { + if let Some(at) = exact { + let column = &columns.columns[*at].1; + if !Self::held(column, row) { + return absent(i); + } + if i + 1 == self.steps.len() { + return false; + } + let nested = matches!( + column.values, + zen_expression::lane::Values::Any(_) + | zen_expression::lane::Values::Struct { .. } + ); + let value = if nested { + column.variable(row) + } else { + Variable::Null + }; + return match value { + Variable::Object(_) => Probe { + segments: self.probe.segments[i + 1..].to_vec(), + optional: self.probe.optional[i + 1..].to_vec(), + prefixes: Vec::new(), + } + .missing(&column.variable(row)), + _ => false, + }; + } + if !under + .iter() + .any(|at| Self::held(&columns.columns[*at].1, row)) + { + return absent(i); + } + } + false + } +} + +impl Requirement { + fn missing(&self, input: &Variable) -> bool { + if !self.primary.missing(input) { + return false; + } + self.alternate + .as_ref() + .is_none_or(|alternate| alternate.missing(input)) + } } impl Db { @@ -68,6 +278,65 @@ impl Db { self.eval_artifact(&req.policy_path).evaluate(&req, true) } + pub fn evaluate_columns<'a>( + &self, + policy_path: &Arc, + goals: &[Arc], + columns: &'a zen_expression::lane::Columns<'a>, + ) -> Result, EvaluationError> { + let probe = EvaluateRequest { + policy_path: policy_path.clone(), + input: Variable::Null, + goals: goals.to_vec(), + trace: false, + }; + self.check_evaluable(&probe)?; + let artifact = self.eval_artifact(policy_path); + Ok(artifact + .plan(goals) + .evaluate_columns(&artifact, policy_path, goals, columns)) + } + + pub fn evaluate_batch( + &self, + requests: &[EvaluateRequest], + ) -> Vec> { + let mut results: Vec>> = + (0..requests.len()).map(|_| None).collect(); + let mut groups: Vec<(Arc, Vec)> = Vec::new(); + for (index, request) in requests.iter().enumerate() { + match self.check_evaluable(request) { + Err(error) => results[index] = Some(Err(error)), + Ok(()) => match groups.iter_mut().find(|(p, _)| *p == request.policy_path) { + Some((_, members)) => members.push(index), + None => groups.push((request.policy_path.clone(), vec![index])), + }, + } + } + for (path, members) in groups { + let artifact = self.eval_artifact(&path); + let batch: Vec = + members.iter().map(|&i| requests[i].clone()).collect(); + for (index, result) in members.into_iter().zip(artifact.evaluate_batch(&batch)) { + results[index] = Some(result); + } + } + results + .into_iter() + .map(|r| r.unwrap_or_else(|| Err(EvaluationError::PolicyNotFound(Arc::from(""))))) + .collect() + } + + pub(crate) fn check_evaluable(&self, req: &EvaluateRequest) -> Result<(), EvaluationError> { + if self.is_graph(&req.policy_path) { + return Err(EvaluationError::GraphNotEvaluable(req.policy_path.clone())); + } + if self.raw_policy(&req.policy_path).is_none() { + return Err(EvaluationError::PolicyNotFound(req.policy_path.clone())); + } + self.check_imports_resolved(&req.policy_path) + } + fn check_imports_resolved(&self, entry: &Arc) -> Result<(), EvaluationError> { let mut visited: HashSet> = HashSet::new(); let mut queue: Vec> = vec![entry.clone()]; @@ -114,8 +383,85 @@ impl EvalArtifact { req: &EvaluateRequest, extras: bool, ) -> Result { - let start = Instant::now(); + let plan = self.plan(&req.goals); + if !req.trace && !extras { + if let Some(result) = plan.evaluate(self, std::slice::from_ref(req)).pop() { + return result; + } + } + plan.traced(self, req, extras) + } + const GOAL_PLANS: usize = 32; + + fn plan(&self, goals: &[Arc]) -> Arc { + if goals.is_empty() { + return self + .compiled + .get_or_init(|| { + Arc::new(PolicyPlan::compile( + self, + self.eval_graph.terminal_sinks(&self.members), + )) + }) + .clone(); + } + if let Some(plan) = self + .goal_plans + .lock() + .ok() + .and_then(|p| p.get(goals).cloned()) + { + return plan; + } + let plan = Arc::new(PolicyPlan::compile(self, goals.to_vec())); + if let Ok(mut plans) = self.goal_plans.lock() { + if plans.len() >= Self::GOAL_PLANS { + plans.clear(); + } + plans.insert(goals.to_vec(), plan.clone()); + } + plan + } + + pub(crate) fn evaluate_batch( + &self, + requests: &[EvaluateRequest], + ) -> Vec> { + let mut results: Vec>> = + (0..requests.len()).map(|_| None).collect(); + let mut groups: Vec<(&[Arc], Vec)> = Vec::new(); + for (index, request) in requests.iter().enumerate() { + match request.trace { + true => { + results[index] = Some(self.plan(&request.goals).traced(self, request, false)) + } + false => match groups + .iter_mut() + .find(|(g, _)| *g == request.goals.as_slice()) + { + Some((_, members)) => members.push(index), + None => groups.push((&request.goals, vec![index])), + }, + } + } + for (goals, members) in groups { + let batch: Vec = + members.iter().map(|&i| requests[i].clone()).collect(); + for (index, result) in members + .into_iter() + .zip(self.plan(goals).evaluate(self, &batch)) + { + results[index] = Some(result); + } + } + results.into_iter().flatten().collect() + } + + pub(crate) fn prepare( + &self, + req: &EvaluateRequest, + ) -> Result<(Variable, Vec), EvaluationError> { let input = self .input_schema .convert_dates(&req.input) @@ -132,30 +478,7 @@ impl EvalArtifact { store.hydrate_references(&self.reference_fields, &pool_index); let order_to_run = self.compute_order_to_run(req, &store)?; - - let roots: Vec> = if req.goals.is_empty() { - self.eval_graph.terminal_sinks(&self.members) - } else { - req.goals.clone() - }; - let mut driver = Driver::new(self, &store, &req.policy_path, req.trace, extras); - let outcome = roots.iter().try_for_each(|root| driver.demand(root)); - - let trace = req.trace.then(|| Trace { - engine_version: Arc::from(crate::ENGINE_VERSION), - properties: store.snapshot(&order_to_run), - executions: driver.executions, - }); - - if let Err(error) = outcome { - return Err(error.with_partial_trace(trace)); - } - - Ok(EvaluationResult { - output: store, - duration: start.elapsed(), - trace, - }) + Ok((store, order_to_run)) } fn validate_request( @@ -177,11 +500,106 @@ impl EvalArtifact { Ok(()) } + pub(crate) fn sure( + &self, + columns: &zen_expression::lane::Columns, + goals: &[Arc], + ) -> Option> { + if !goals.is_empty() || !self.reference_fields.is_empty() { + return None; + } + let mut sure = self.input_schema.sure(columns)?; + for check in &self.requirements().checks { + let primary = Steps::new(&check.primary, columns); + if primary.always(columns) { + continue; + } + let alternate = check.alternate.as_ref().map(|a| Steps::new(a, columns)); + if alternate.as_ref().is_some_and(|a| a.always(columns)) { + continue; + } + for (row, sure) in sure.iter_mut().enumerate() { + if *sure + && primary.missing(columns, row) + && alternate.as_ref().is_none_or(|a| a.missing(columns, row)) + { + *sure = false; + } + } + } + Some(sure) + } + + fn requirements(&self) -> &Requirements { + self.requirements.get_or_init(|| { + let visible = &self.members; + let order: Vec = self + .execution_order + .iter() + .filter(|path| { + self.eval_graph + .writer_for(path) + .is_some_and(|o| visible.contains(&o.policy_path)) + }) + .cloned() + .collect(); + let goals = self.eval_graph.terminal_sinks(visible); + let entity_form = EntityForm::new(&self.entity_sources); + let checks = self + .eval_graph + .reachable_input_paths(&goals, visible) + .into_iter() + .filter(|p| { + !entity_form + .rewrite(p) + .is_some_and(|entity| self.eval_graph.written_at(&entity, visible)) + }) + .map(|path| { + let alternate = path.split_once('.').and_then(|(entity, rest)| { + let src = self.entity_sources.get(entity)?; + Some(Probe::new( + &self.data_model_paths, + &format!("{}.{}", src.path, rest), + )) + }); + Requirement { + primary: Probe::new(&self.data_model_paths, &path), + alternate, + path, + } + }) + .collect(); + Requirements { + order, + goals, + checks, + } + }) + } + fn compute_order_to_run( &self, req: &EvaluateRequest, input: &Variable, ) -> Result, EvaluationError> { + if req.goals.is_empty() { + let requirements = self.requirements(); + let mut missing: Vec = requirements + .checks + .iter() + .filter(|check| check.missing(input)) + .map(|check| check.path.clone()) + .collect(); + if !missing.is_empty() { + missing.sort(); + return Err(EvaluationError::MissingRequiredInputs { + goals: requirements.goals.clone(), + missing, + }); + } + return Ok(requirements.order.clone()); + } + let visible = &self.members; let visible_order: Vec = self .execution_order @@ -257,200 +675,32 @@ impl EvalArtifact { } } -struct Driver<'a> { - artifact: &'a EvalArtifact, - store: &'a Variable, - env: Variable, - entry: &'a Arc, - trace: bool, - extras: bool, - isolate: Rc>, - ran: HashSet, - in_progress: HashSet, - executions: Vec, -} - -enum Pick { - Unconditional, - Match(MatchSelection), - Table(TableSelection), -} - -impl Pick { - fn collect_reads(&self, plan: &BlockReadPlan, out: &mut Vec>) { - match self { - Pick::Match(selection) => { - if let Some(arm_id) = &selection.matched_arm { - if let Some(reads) = plan.match_arm_reads(arm_id) { - out.extend(reads.iter().cloned()); - } - } - } - Pick::Table(selection) => { - for (row_idx, col_id) in &selection.used_cells { - out.extend(plan.cell_reads(*row_idx, col_id)); - } - } - Pick::Unconditional => {} - } - } -} - -struct PhaseScope { - scoped: Variable, - entity_key: Rc, -} - -impl PhaseScope { - fn new(store: &Variable, entity_key: Rc) -> Self { - Self { - scoped: store.depth_clone(1), - entity_key, +impl EvalArtifact { + pub(crate) fn iteration(&self, rule: &Block) -> Option { + match rule.write_scope(&self.classifier) { + WriteScope::Entity(entity) => self + .entity_sources + .get(entity.as_ref()) + .map(|src| (entity, src.path.clone(), src.owner.clone())), + _ => None, } } - fn bind( - &self, - instance: &Variable, - owner_binding: &Option<(String, Variable)>, - ) -> Option { - let scoped_fields = self.scoped.as_object()?; - - let needs_owner = match (owner_binding, instance.as_object()) { - (Some((name, _)), Some(fields)) => { - !fields.borrow().contains_key(&Symbol::from(name.as_str())) - } - _ => false, - }; - - let (bound, slot) = if needs_owner { - let wrapper = instance.depth_clone(1); - let synthetic_owner = match (owner_binding, wrapper.as_object()) { - (Some((name, owner_var)), Some(wrapper_fields)) => { - let key = Symbol::from(name.as_str()); - let injected = owner_var.shallow_clone(); - wrapper_fields - .borrow_mut() - .insert(key.clone(), injected.shallow_clone()); - Some((key, injected)) - } - _ => None, - }; - let bound = wrapper.shallow_clone(); - ( - bound, - InstanceSlot::Wrapped { - wrapper, - synthetic_owner, - }, - ) - } else { - (instance.shallow_clone(), InstanceSlot::Direct) - }; - - { - let mut fields = scoped_fields.borrow_mut(); - fields.remove(&Variable::dollar_key()); - fields.insert(Symbol::from(self.entity_key.as_ref()), bound); - } - Some(slot) - } -} - -enum InstanceSlot { - Direct, - Wrapped { - wrapper: Variable, - synthetic_owner: Option<(Symbol, Variable)>, - }, -} - -impl InstanceSlot { - fn write_back(&self, instance: &Variable) { - let Self::Wrapped { - wrapper, - synthetic_owner, - } = self - else { - return; - }; - let (Some(written), Some(target)) = (wrapper.as_object(), instance.as_object()) else { - return; - }; - let written = written.borrow(); - let mut target = target.borrow_mut(); - for (key, value) in written.iter() { - if Self::is_injected_owner(synthetic_owner, key.clone(), value) { - continue; - } - target.insert(key.clone(), value.shallow_clone()); - } + pub(crate) fn programs(&self) -> Arc { + self.programs + .get_or_init(|| { + Arc::new(Host::programs( + self.rule_by_ref + .iter() + .filter(|(owner, _)| self.members.contains(&owner.policy_path)) + .map(|(_, rule)| rule.as_ref()), + )) + }) + .clone() } - fn is_injected_owner( - synthetic_owner: &Option<(Symbol, Variable)>, - key: Symbol, - value: &Variable, - ) -> bool { - match synthetic_owner { - Some((owner_key, injected)) if owner_key.as_str() == key.as_str() => { - Self::same_ref(value, injected) - } - _ => false, - } - } - - fn same_ref(a: &Variable, b: &Variable) -> bool { - match (a, b) { - (Variable::Object(x), Variable::Object(y)) => RcCell::ptr_eq(x, y), - (Variable::Array(x), Variable::Array(y)) => RcCell::ptr_eq(x, y), - (Variable::String(x), Variable::String(y)) => x == y, - _ => a == b, - } - } -} - -impl<'a> Driver<'a> { - fn new( - artifact: &'a EvalArtifact, - store: &'a Variable, - entry: &'a Arc, - trace: bool, - extras: bool, - ) -> Self { - Self { - isolate: Rc::new(RefCell::new( - Isolate::new().with_cache(Some(artifact.opcode_cache.clone())), - )), - artifact, - store, - env: store.depth_clone(1), - entry, - trace, - extras, - ran: HashSet::new(), - in_progress: HashSet::new(), - executions: Vec::new(), - } - } - - fn bind_env(&self, isolate: &RefCell) { - if let Some(fields) = self.env.as_object() { - fields.borrow_mut().remove(&Variable::dollar_key()); - } - isolate - .borrow_mut() - .set_environment(self.env.shallow_clone()); - } - - fn demand(&mut self, prop: &str) -> Result<(), EvaluationError> { - self.writers_of_longest_prefix(prop) - .iter() - .try_for_each(|owner| self.run_block(owner)) - } - - fn writers_of_longest_prefix(&self, prop: &str) -> &'a [BlockRef] { - let graph = &self.artifact.eval_graph; + pub(crate) fn writers_of_longest_prefix(&self, prop: &str) -> &[BlockRef] { + let graph = &self.eval_graph; let direct = graph.demand_writers_for(prop); if !direct.is_empty() { return direct; @@ -465,284 +715,9 @@ impl<'a> Driver<'a> { } &[] } - - fn run_block(&mut self, owner: &BlockRef) -> Result<(), EvaluationError> { - if self.ran.contains(owner) || !self.in_progress.insert(owner.clone()) { - return Ok(()); - } - let result = self.run_block_inner(owner); - self.in_progress.remove(owner); - if result.is_ok() { - self.ran.insert(owner.clone()); - } - result - } - - fn run_block_inner(&mut self, owner: &BlockRef) -> Result<(), EvaluationError> { - let artifact = self.artifact; - let Some(rule) = artifact.rule_by_ref.get(owner) else { - return Ok(()); - }; - let rule = rule.clone(); - - if let Some(plan) = artifact.read_plans.get(owner) { - for path in plan.unconditional.iter() { - self.demand(path)?; - } - } - - let iterated = match rule.write_scope(&artifact.classifier) { - WriteScope::Entity(entity) => artifact - .entity_sources - .get(entity.as_ref()) - .map(|src| (entity, src.path.clone(), src.owner.clone())), - _ => None, - }; - - match iterated { - Some((entity, path, src_owner)) => { - self.run_iterated(owner, &rule, entity.as_ref(), &path, src_owner.as_deref()) - } - None => self.run_singleton(owner, &rule), - } - } - - fn select_pick(rule: &Block, ctx: &ExecutionContext) -> Result { - match &rule.kind { - BlockKind::Match(m) => m.select(ctx).map(Pick::Match), - BlockKind::DecisionTable(d) => d.select(ctx).map(Pick::Table), - BlockKind::Expression(_) | BlockKind::Assertion(_) => Ok(Pick::Unconditional), - } - } - - fn commit_pick( - rule: &Block, - ctx: &ExecutionContext, - pick: &Pick, - ) -> Result { - match (&rule.kind, pick) { - (BlockKind::Match(m), Pick::Match(selection)) => m.commit(ctx, selection), - (BlockKind::DecisionTable(d), Pick::Table(selection)) => d.commit(ctx, selection), - _ => rule.execute(ctx), - } - } - - fn run_singleton(&mut self, owner: &BlockRef, rule: &Block) -> Result<(), EvaluationError> { - let artifact = self.artifact; - let write_log = (self.trace && self.extras).then(|| RefCell::new(Vec::new())); - let isolate = Rc::clone(&self.isolate); - let env = self.env.shallow_clone(); - let ctx = ExecutionContext { - store: self.store, - policy_path: &owner.policy_path, - block_id: &rule.id, - trace: self.trace, - extras: self.extras, - write_log: write_log.as_ref(), - env_mirror: Some(&env), - isolate: &isolate, - }; - - if matches!(rule.kind, BlockKind::Match(_) | BlockKind::DecisionTable(_)) { - self.bind_env(&isolate); - } - let pick = Self::select_pick(rule, &ctx)?; - let mut demanded: Vec> = Vec::new(); - if let Some(plan) = artifact.read_plans.get(owner) { - pick.collect_reads(plan, &mut demanded); - } - for path in &demanded { - self.demand(path)?; - } - self.bind_env(&isolate); - let bt = Self::commit_pick(rule, &ctx, &pick)?; - - if self.trace { - let trace_policy_path = - (&owner.policy_path != self.entry).then(|| owner.policy_path.clone()); - let operand_values = - Block::operand_values(self.extras, self.reads_for(owner), self.store); - self.executions.push(BlockExecution { - block_id: rule.id.clone(), - policy_path: trace_policy_path, - instance_path: None, - trace: bt, - operand_values, - writes: write_log.map(RefCell::into_inner).unwrap_or_default(), - reads: self.execution_reads(owner, &pick), - }); - } - Ok(()) - } - - fn run_iterated( - &mut self, - owner: &BlockRef, - rule: &Block, - entity: &str, - iter_path: &Arc, - owner_name: Option<&str>, - ) -> Result<(), EvaluationError> { - let Some(target) = self.store.dot(iter_path.as_ref()) else { - return Ok(()); - }; - let single = target.as_object().is_some(); - let instances: Vec = match target.as_array() { - Some(arr) => arr.borrow().iter().map(|v| v.shallow_clone()).collect(), - None if single => vec![target.shallow_clone()], - None => return Ok(()), - }; - let owner_binding = owner_name.and_then(|name| { - let owner_path = iter_path.rsplit_once('.').map(|(o, _)| o)?; - self.store - .dot(owner_path) - .map(|var| (name.to_string(), var)) - }); - let entity_key: Rc = Rc::from(entity); - let artifact = self.artifact; - - let picks: Vec = - if matches!(rule.kind, BlockKind::Match(_) | BlockKind::DecisionTable(_)) { - let phase = PhaseScope::new(self.store, entity_key.clone()); - let isolate = Rc::clone(&self.isolate); - isolate - .borrow_mut() - .set_environment(phase.scoped.shallow_clone()); - let mut picks = Vec::with_capacity(instances.len()); - for instance in &instances { - let Some(_slot) = phase.bind(instance, &owner_binding) else { - picks.push(Pick::Unconditional); - continue; - }; - let ctx = ExecutionContext { - store: &phase.scoped, - policy_path: &owner.policy_path, - block_id: &rule.id, - trace: self.trace, - extras: self.extras, - write_log: None, - env_mirror: None, - isolate: &isolate, - }; - picks.push(Self::select_pick(rule, &ctx)?); - } - picks - } else { - instances.iter().map(|_| Pick::Unconditional).collect() - }; - - let mut demanded: Vec> = Vec::new(); - if let Some(plan) = artifact.read_plans.get(owner) { - for pick in &picks { - pick.collect_reads(plan, &mut demanded); - } - } - demanded.sort(); - demanded.dedup(); - for path in &demanded { - self.demand(path)?; - } - - let trace_policy_path = - (&owner.policy_path != self.entry).then(|| owner.policy_path.clone()); - let phase = PhaseScope::new(self.store, entity_key); - let isolate = Rc::clone(&self.isolate); - isolate - .borrow_mut() - .set_environment(phase.scoped.shallow_clone()); - for (idx, instance) in instances.iter().enumerate() { - let Some(slot) = phase.bind(instance, &owner_binding) else { - continue; - }; - let write_log = (self.trace && self.extras).then(|| RefCell::new(Vec::new())); - let ctx = ExecutionContext { - store: &phase.scoped, - policy_path: &owner.policy_path, - block_id: &rule.id, - trace: self.trace, - extras: self.extras, - write_log: write_log.as_ref(), - env_mirror: None, - isolate: &isolate, - }; - let result = Self::commit_pick(rule, &ctx, &picks[idx]); - let operand_values = match (&result, self.trace) { - (Ok(_), true) => { - Block::operand_values(self.extras, self.reads_for(owner), &phase.scoped) - } - _ => HashMap::default(), - }; - slot.write_back(instance); - let bt = result?; - if self.trace { - self.executions.push(BlockExecution { - block_id: rule.id.clone(), - policy_path: trace_policy_path.clone(), - instance_path: Some(match single { - true => iter_path.clone(), - false => format!("{iter_path}.{idx}").into(), - }), - trace: bt, - operand_values, - writes: write_log.map(RefCell::into_inner).unwrap_or_default(), - reads: self.execution_reads(owner, &picks[idx]), - }); - } - } - Ok(()) - } - - fn reads_for(&self, owner: &BlockRef) -> &[PropertyRead] { - if self.extras { - self.artifact - .reads - .get(owner) - .map(|r| r.as_ref()) - .unwrap_or(&[]) - } else { - &[] - } - } - - fn execution_reads(&self, owner: &BlockRef, pick: &Pick) -> Vec> { - if !self.extras { - return Vec::new(); - } - let Some(plan) = self.artifact.read_plans.get(owner) else { - return Vec::new(); - }; - let mut reads: Vec> = plan.unconditional.to_vec(); - pick.collect_reads(plan, &mut reads); - reads.sort(); - reads.dedup(); - reads - } } -impl Block { - fn operand_values( - extras: bool, - reads: &[PropertyRead], - store: &Variable, - ) -> HashMap, Variable> { - let mut out: HashMap, Variable> = HashMap::new(); - if !extras { - return out; - } - for read in reads { - if read.via_alias || read.unresolved { - continue; - } - if let Some(value) = store.dot(&read.path) { - out.entry(read.path.clone()) - .or_insert_with(|| value.deep_clone()); - } - } - out - } -} - -trait StoreOps { +pub(crate) trait StoreOps { fn hydrate_references(&self, reference_fields: &[ReferenceField], pool_index: &RefPoolIndex); fn snapshot(&self, order: &[PropertyPath]) -> HashMap, Variable>; } @@ -801,7 +776,7 @@ impl From for EvaluationError { } impl EvaluationError { - fn with_partial_trace(self, trace: Option) -> Self { + pub(crate) fn with_partial_trace(self, trace: Option) -> Self { match (self, trace) { ( EvaluationError::ExpressionFailed { diff --git a/core/engine/src/policy/host.rs b/core/engine/src/policy/host.rs new file mode 100644 index 00000000..864630d6 --- /dev/null +++ b/core/engine/src/policy/host.rs @@ -0,0 +1,647 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use ahash::{HashMap, HashMapExt}; +use zen_expression::variable::Variable; +use zen_expression::IsolateError; +use zen_types::rccell::RcCell; +use zen_types::symbol::Symbol; + +use crate::policy::blocks::{ + Block, BlockKind, BlockReadPlan, ExecutionError, MatchSelection, PropertyRead, TableSelection, +}; +use crate::policy::evaluator::{EvalArtifact, Iteration}; +use crate::workspace::types::{BlockExecution, BlockRef, BlockTrace, EvaluationError, WriteTrace}; + +pub(crate) struct Site<'a> { + pub(crate) store: &'a Variable, + pub(crate) policy_path: &'a Arc, + pub(crate) block_id: &'a Arc, + pub(crate) trace: bool, + pub(crate) extras: bool, + pub(crate) write_log: Option<&'a RefCell>>, + pub(crate) env_mirror: Option<&'a Variable>, +} + +impl Site<'_> { + pub(crate) fn expression_error( + &self, + expression: &Arc, + source: IsolateError, + ) -> ExecutionError { + ExecutionError { + block_id: self.block_id.clone(), + policy_path: self.policy_path.clone(), + expression: expression.clone(), + source, + } + } + + pub(crate) fn write(&self, path: &Arc, value: Variable) { + if let Some(log) = self.write_log { + log.borrow_mut().push(WriteTrace { + path: path.clone(), + value: value.deep_clone(), + }); + } + HostState::write_into(self.store, self.env_mirror, path, value); + } +} + +pub(crate) trait Evaluate { + fn environment(&mut self, env: Variable); + fn select(&mut self, rule: &Block, site: &Site) -> Result; + fn commit( + &mut self, + rule: &Block, + site: &Site, + pick: &Pick, + ) -> Result; +} + +pub(crate) enum Pick { + Unconditional, + Match(MatchSelection), + Table(TableSelection), +} + +impl Pick { + pub(crate) fn collect_reads(&self, plan: &BlockReadPlan, out: &mut Vec>) { + match self { + Pick::Match(selection) => { + if let Some(arm_id) = &selection.matched_arm { + if let Some(reads) = plan.match_arm_reads(arm_id) { + out.extend(reads.iter().cloned()); + } + } + } + Pick::Table(selection) => { + for (row_idx, col_id) in &selection.used_cells { + out.extend(plan.cell_reads(*row_idx, col_id)); + } + } + Pick::Unconditional => {} + } + } +} + +struct PhaseScope { + scoped: Variable, + entity_key: Rc, +} + +impl PhaseScope { + fn new(store: &Variable, entity_key: Rc) -> Self { + Self { + scoped: store.depth_clone(1), + entity_key, + } + } + + fn bind( + &self, + instance: &Variable, + owner_binding: &Option<(String, Variable)>, + ) -> Option { + let scoped_fields = self.scoped.as_object()?; + + let needs_owner = match (owner_binding, instance.as_object()) { + (Some((name, _)), Some(fields)) => { + !fields.borrow().contains_key(&Symbol::from(name.as_str())) + } + _ => false, + }; + + let (bound, slot) = if needs_owner { + let wrapper = instance.depth_clone(1); + let synthetic_owner = match (owner_binding, wrapper.as_object()) { + (Some((name, owner_var)), Some(wrapper_fields)) => { + let key = Symbol::from(name.as_str()); + let injected = owner_var.shallow_clone(); + wrapper_fields + .borrow_mut() + .insert(key.clone(), injected.shallow_clone()); + Some((key, injected)) + } + _ => None, + }; + let bound = wrapper.shallow_clone(); + ( + bound, + InstanceSlot::Wrapped { + wrapper, + synthetic_owner, + }, + ) + } else { + (instance.shallow_clone(), InstanceSlot::Direct) + }; + + { + let mut fields = scoped_fields.borrow_mut(); + fields.remove(&Variable::dollar_key()); + fields.insert(Symbol::from(self.entity_key.as_ref()), bound); + } + Some(slot) + } +} + +pub(crate) enum InstanceSlot { + Direct, + Wrapped { + wrapper: Variable, + synthetic_owner: Option<(Symbol, Variable)>, + }, +} + +impl InstanceSlot { + pub(crate) fn write_back(&self, instance: &Variable) { + let Self::Wrapped { + wrapper, + synthetic_owner, + } = self + else { + return; + }; + let (Some(written), Some(target)) = (wrapper.as_object(), instance.as_object()) else { + return; + }; + let written = written.borrow(); + let mut target = target.borrow_mut(); + for (key, value) in written.iter() { + if Self::is_injected_owner(synthetic_owner, key.clone(), value) { + continue; + } + target.insert(key.clone(), value.shallow_clone()); + } + } + + fn is_injected_owner( + synthetic_owner: &Option<(Symbol, Variable)>, + key: Symbol, + value: &Variable, + ) -> bool { + match synthetic_owner { + Some((owner_key, injected)) if owner_key.as_str() == key.as_str() => { + Self::same_ref(value, injected) + } + _ => false, + } + } + + fn same_ref(a: &Variable, b: &Variable) -> bool { + match (a, b) { + (Variable::Object(x), Variable::Object(y)) => RcCell::ptr_eq(x, y), + (Variable::Array(x), Variable::Array(y)) => RcCell::ptr_eq(x, y), + (Variable::String(x), Variable::String(y)) => x == y, + _ => a == b, + } + } +} + +pub(crate) enum Picked { + Skipped, + Singleton(Pick), + Iterated(Iterated), +} + +pub(crate) struct Iterated { + entity: Rc, + iter_path: Arc, + instances: Vec, + single: bool, + owner_binding: Option<(String, Variable)>, + picks: Vec, +} + +impl Iterated { + pub(crate) fn picks(&self) -> &[Pick] { + &self.picks + } + + pub(crate) fn instances(&self) -> &[Variable] { + &self.instances + } + + pub(crate) fn picked(mut self, picks: Vec) -> Picked { + self.picks = picks; + Picked::Iterated(self) + } +} + +pub(crate) struct HostState<'a> { + artifact: &'a EvalArtifact, + store: &'a Variable, + env: Variable, + entry: &'a Arc, + trace: bool, + extras: bool, + executions: Vec, +} + +impl<'a> HostState<'a> { + pub(crate) fn new( + artifact: &'a EvalArtifact, + store: &'a Variable, + entry: &'a Arc, + trace: bool, + extras: bool, + ) -> Self { + Self { + artifact, + store, + env: store.depth_clone(1), + entry, + trace, + extras, + executions: Vec::new(), + } + } + + #[cfg(feature = "driver")] + pub(crate) fn artifact(&self) -> &'a EvalArtifact { + self.artifact + } + + pub(crate) fn executions(self) -> Vec { + self.executions + } + + #[cfg(feature = "driver")] + pub(crate) fn writers_of_longest_prefix(&self, prop: &str) -> &'a [BlockRef] { + self.artifact.writers_of_longest_prefix(prop) + } + + pub(crate) fn env(&self) -> &Variable { + &self.env + } + + pub(crate) fn clear_dollar(&self) { + if let Some(fields) = self.env.as_object() { + fields.borrow_mut().remove(&Variable::dollar_key()); + } + } + + pub(crate) fn write(&self, path: &str, value: Variable) { + Self::write_into(self.store, Some(&self.env), path, value); + } + + pub(crate) fn write_into( + store: &Variable, + env_mirror: Option<&Variable>, + path: &str, + value: Variable, + ) { + store.dot_insert(path, value); + Self::mirror_top_level(store, env_mirror, path); + } + + fn mirror_top_level(store: &Variable, env_mirror: Option<&Variable>, path: &str) { + let Some(env) = env_mirror else { + return; + }; + let (Some(store_fields), Some(env_fields)) = (store.as_object(), env.as_object()) else { + return; + }; + let segment = &path[..path.find('.').unwrap_or(path.len())]; + let store_fields = store_fields.borrow(); + let Some((key, value)) = store_fields.get_key_value(&Symbol::from(segment)) else { + return; + }; + env_fields + .borrow_mut() + .insert(key.clone(), value.shallow_clone()); + } + + fn bind_env(&self, eval: &mut impl Evaluate) { + self.clear_dollar(); + eval.environment(self.env.shallow_clone()); + } + + pub(crate) fn iterated(&self, rule: &Block) -> Option { + self.artifact.iteration(rule) + } + + pub(crate) fn select( + &mut self, + owner: &BlockRef, + rule: &Block, + eval: &mut impl Evaluate, + ) -> Result { + match self.iterated(rule) { + Some((entity, path, src_owner)) => self.select_iterated( + owner, + rule, + entity.as_ref(), + &path, + src_owner.as_deref(), + eval, + ), + None => self + .select_singleton(owner, rule, eval) + .map(Picked::Singleton), + } + } + + pub(crate) fn demanded(&self, owner: &BlockRef, picked: &Picked) -> Vec> { + let mut demanded: Vec> = Vec::new(); + let Some(plan) = self.artifact.read_plans.get(owner) else { + return demanded; + }; + match picked { + Picked::Skipped => {} + Picked::Singleton(pick) => pick.collect_reads(plan, &mut demanded), + Picked::Iterated(iterated) => { + for pick in &iterated.picks { + pick.collect_reads(plan, &mut demanded); + } + demanded.sort(); + demanded.dedup(); + } + } + demanded + } + + pub(crate) fn commit( + &mut self, + owner: &BlockRef, + rule: &Block, + picked: Picked, + eval: &mut impl Evaluate, + ) -> Result<(), EvaluationError> { + match picked { + Picked::Skipped => Ok(()), + Picked::Singleton(pick) => self.commit_singleton(owner, rule, pick, eval), + Picked::Iterated(iterated) => self.commit_iterated(owner, rule, iterated, eval), + } + } + + fn site<'s>( + &self, + store: &'s Variable, + owner: &'s BlockRef, + rule: &'s Block, + write_log: Option<&'s RefCell>>, + env_mirror: Option<&'s Variable>, + ) -> Site<'s> { + Site { + store, + policy_path: &owner.policy_path, + block_id: &rule.id, + trace: self.trace, + extras: self.extras, + write_log, + env_mirror, + } + } + + fn select_singleton( + &mut self, + owner: &BlockRef, + rule: &Block, + eval: &mut impl Evaluate, + ) -> Result { + let env = self.env.shallow_clone(); + let site = self.site(self.store, owner, rule, None, Some(&env)); + if matches!(rule.kind, BlockKind::Match(_) | BlockKind::DecisionTable(_)) { + self.bind_env(eval); + } + Ok(eval.select(rule, &site)?) + } + + fn commit_singleton( + &mut self, + owner: &BlockRef, + rule: &Block, + pick: Pick, + eval: &mut impl Evaluate, + ) -> Result<(), EvaluationError> { + let write_log = (self.trace && self.extras).then(|| RefCell::new(Vec::new())); + let env = self.env.shallow_clone(); + let bt = { + let site = self.site(self.store, owner, rule, write_log.as_ref(), Some(&env)); + self.bind_env(eval); + eval.commit(rule, &site, &pick)? + }; + + if self.trace { + let trace_policy_path = + (&owner.policy_path != self.entry).then(|| owner.policy_path.clone()); + let operand_values = + Block::operand_values(self.extras, self.reads_for(owner), self.store); + let reads = self.execution_reads(owner, &pick); + self.executions.push(BlockExecution { + block_id: rule.id.clone(), + policy_path: trace_policy_path, + instance_path: None, + trace: bt, + operand_values, + writes: write_log.map(RefCell::into_inner).unwrap_or_default(), + reads, + }); + } + Ok(()) + } + + fn captured( + &self, + entity: &str, + iter_path: &Arc, + owner_name: Option<&str>, + ) -> Option { + let target = self.store.dot(iter_path.as_ref())?; + let single = target.as_object().is_some(); + let instances: Vec = match target.as_array() { + Some(arr) => arr.borrow().iter().map(|v| v.shallow_clone()).collect(), + None if single => vec![target.shallow_clone()], + None => return None, + }; + let owner_binding = owner_name.and_then(|name| { + let owner_path = iter_path.rsplit_once('.').map(|(o, _)| o)?; + self.store + .dot(owner_path) + .map(|var| (name.to_string(), var)) + }); + Some(Iterated { + entity: Rc::from(entity), + iter_path: iter_path.clone(), + instances, + single, + owner_binding, + picks: Vec::new(), + }) + } + + pub(crate) fn capture(&self, rule: &Block) -> Option { + let (entity, path, owner) = self.iterated(rule)?; + self.captured(entity.as_ref(), &path, owner.as_deref()) + } + + pub(crate) fn instance_scopes( + &self, + iterated: &Iterated, + ) -> Vec> { + iterated + .instances + .iter() + .map(|instance| { + let phase = PhaseScope::new(self.store, iterated.entity.clone()); + let slot = phase.bind(instance, &iterated.owner_binding)?; + Some((phase.scoped, slot)) + }) + .collect() + } + + fn select_iterated( + &mut self, + owner: &BlockRef, + rule: &Block, + entity: &str, + iter_path: &Arc, + owner_name: Option<&str>, + eval: &mut impl Evaluate, + ) -> Result { + let Some(captured) = self.captured(entity, iter_path, owner_name) else { + return Ok(Picked::Skipped); + }; + let Iterated { + entity: entity_key, + instances, + single, + owner_binding, + .. + } = captured; + + let picks: Vec = + if matches!(rule.kind, BlockKind::Match(_) | BlockKind::DecisionTable(_)) { + let phase = PhaseScope::new(self.store, entity_key.clone()); + eval.environment(phase.scoped.shallow_clone()); + let mut picks = Vec::with_capacity(instances.len()); + for instance in &instances { + let Some(_slot) = phase.bind(instance, &owner_binding) else { + picks.push(Pick::Unconditional); + continue; + }; + let site = self.site(&phase.scoped, owner, rule, None, None); + picks.push(eval.select(rule, &site)?); + } + picks + } else { + instances.iter().map(|_| Pick::Unconditional).collect() + }; + + Ok(Picked::Iterated(Iterated { + entity: entity_key, + iter_path: iter_path.clone(), + instances, + single, + owner_binding, + picks, + })) + } + + fn commit_iterated( + &mut self, + owner: &BlockRef, + rule: &Block, + iterated: Iterated, + eval: &mut impl Evaluate, + ) -> Result<(), EvaluationError> { + let Iterated { + entity: entity_key, + iter_path, + instances, + single, + owner_binding, + picks, + } = iterated; + let trace_policy_path = + (&owner.policy_path != self.entry).then(|| owner.policy_path.clone()); + let phase = PhaseScope::new(self.store, entity_key); + eval.environment(phase.scoped.shallow_clone()); + for (idx, instance) in instances.iter().enumerate() { + let Some(slot) = phase.bind(instance, &owner_binding) else { + continue; + }; + let write_log = (self.trace && self.extras).then(|| RefCell::new(Vec::new())); + let result = { + let site = self.site(&phase.scoped, owner, rule, write_log.as_ref(), None); + eval.commit(rule, &site, &picks[idx]) + }; + let operand_values = match (&result, self.trace) { + (Ok(_), true) => { + Block::operand_values(self.extras, self.reads_for(owner), &phase.scoped) + } + _ => HashMap::default(), + }; + slot.write_back(instance); + let bt = result?; + if self.trace { + let reads = self.execution_reads(owner, &picks[idx]); + self.executions.push(BlockExecution { + block_id: rule.id.clone(), + policy_path: trace_policy_path.clone(), + instance_path: Some(match single { + true => iter_path.clone(), + false => format!("{iter_path}.{idx}").into(), + }), + trace: bt, + operand_values, + writes: write_log.map(RefCell::into_inner).unwrap_or_default(), + reads, + }); + } + } + Ok(()) + } + + fn reads_for(&self, owner: &BlockRef) -> &'a [PropertyRead] { + if self.extras { + self.artifact + .reads + .get(owner) + .map(|r| r.as_ref()) + .unwrap_or(&[]) + } else { + &[] + } + } + + fn execution_reads(&self, owner: &BlockRef, pick: &Pick) -> Vec> { + if !self.extras { + return Vec::new(); + } + let Some(plan) = self.artifact.read_plans.get(owner) else { + return Vec::new(); + }; + let mut reads: Vec> = plan.unconditional.to_vec(); + pick.collect_reads(plan, &mut reads); + reads.sort(); + reads.dedup(); + reads + } +} + +impl Block { + fn operand_values( + extras: bool, + reads: &[PropertyRead], + store: &Variable, + ) -> HashMap, Variable> { + let mut out: HashMap, Variable> = HashMap::new(); + if !extras { + return out; + } + for read in reads { + if read.via_alias || read.unresolved { + continue; + } + if let Some(value) = store.dot(&read.path) { + out.entry(read.path.clone()) + .or_insert_with(|| value.deep_clone()); + } + } + out + } +} diff --git a/core/engine/src/policy/mod.rs b/core/engine/src/policy/mod.rs index 2ec250b0..57a2d6f5 100644 --- a/core/engine/src/policy/mod.rs +++ b/core/engine/src/policy/mod.rs @@ -3,7 +3,10 @@ use std::sync::Arc; pub(crate) const MAX_RECURSION_DEPTH: usize = 32; pub(crate) mod blocks; +#[cfg(feature = "driver")] +pub(crate) mod driver; pub(crate) mod evaluator; +pub(crate) mod host; pub(crate) mod ir; pub(crate) mod linter; pub(crate) mod queries; diff --git a/core/engine/src/policy/queries/diagnostics.rs b/core/engine/src/policy/queries/diagnostics.rs index cd032057..abd3c813 100644 --- a/core/engine/src/policy/queries/diagnostics.rs +++ b/core/engine/src/policy/queries/diagnostics.rs @@ -9,6 +9,9 @@ use crate::policy::queries::dependency::{RuleEnrichedAnalysis, WriteScope}; use crate::policy::queries::path::PathRoot; use crate::workspace::db::{Db, Unit}; use crate::workspace::types::{BlockRef, Diagnostic, DiagnosticCode, DiagnosticLocation}; +use zen_types::path::DotPath; + +type Seen = (Arc, Arc, PropertyTypeIr, bool, bool); impl Db { pub fn compute_policy_diagnostics(&self, path: &Arc) -> Vec { @@ -108,12 +111,7 @@ impl Db { let unit = self.unit(path); let mut members: Vec<&Arc> = unit.members.iter().collect(); members.sort_by_key(|member| (*member != path, member.to_string())); - let covers = |written: &str, field: &str| { - field == written - || field - .strip_prefix(written) - .is_some_and(|rest| rest.starts_with('.')) - }; + let covers = |written: &str, field: &str| DotPath::within(field, written); for diagnostic in out.iter_mut() { if !diagnostic.is_in(path) { continue; @@ -376,7 +374,7 @@ impl Db { let Some(rule) = rule_index.get(&block_ref) else { continue; }; - let write_scope = rule.write_scope(&classifier); + let write_scope = rule.write_scope(classifier); for read in &rule_analysis.reads { if read.via_alias { @@ -596,10 +594,7 @@ impl Db { fn data_model_diagnostics(&self, target: &Arc) -> Vec { let mut out = Vec::new(); - let mut seen: HashMap< - (Option>, Arc), - (Arc, Arc, PropertyTypeIr, bool, bool), - > = HashMap::default(); + let mut seen: HashMap<(Option>, Arc), Seen> = HashMap::default(); let unit = self.unit(target); let all_dms = &unit.data_models; let known_entities: HashSet> = all_dms diff --git a/core/engine/src/policy/runtime.rs b/core/engine/src/policy/runtime.rs index 6007d3ec..17e578dd 100644 --- a/core/engine/src/policy/runtime.rs +++ b/core/engine/src/policy/runtime.rs @@ -5,19 +5,18 @@ use ahash::{HashMap, HashSet, HashSetExt}; use zen_expression::variable::Variable; use crate::decision::Decision; -use crate::decision_graph::graph::{DecisionGraphResponse, EvaluationTrace}; +use crate::decision_graph::graph::DecisionGraphResponse; use crate::engine::EvaluationOptions; use crate::loader::DynamicLoader; use crate::model::{DecisionContent, GraphContent}; use crate::policy::evaluator::EvalArtifact; use crate::policy::raw::PolicyDocument; -use crate::workspace::types::{ - Diagnostic, EvaluateRequest, EvaluationError as PolicyEvaluationError, Severity, -}; +use crate::workspace::types::{Diagnostic, EvaluationError as PolicyEvaluationError, Severity}; use crate::workspace::Workspace; use crate::{CompileFailure, EvaluationError}; pub(crate) async fn evaluate_policy( + policies: &crate::prepared::Policies, loader: &DynamicLoader, entry_key: &str, entry_content: Arc, @@ -28,40 +27,30 @@ pub(crate) async fn evaluate_policy( let documents = collect_transitive_policies(loader, entry_path.clone(), entry_content).await?; - let mut workspace = Workspace::new(); - for (path, doc) in documents { - workspace.set_policy_arc(path, doc); - } - - let blocking_errors = workspace - .evaluation_diagnostics(&entry_path) - .into_iter() - .filter(|d| d.severity == Severity::Error) - .count(); - if blocking_errors > 0 { + let artifact = policies.artifact(&entry_path, documents, |documents| { + let mut workspace = Workspace::new(); + for (path, doc) in documents { + workspace.set_policy_arc(path.clone(), doc.clone()); + } + let blocked = workspace + .evaluation_diagnostics(&entry_path) + .into_iter() + .any(|d| d.severity == Severity::Error); + (!blocked).then(|| workspace.eval_artifact(&entry_path)) + }); + let Some(artifact) = artifact else { return Err(Box::new(EvaluationError::Policy( PolicyEvaluationError::CompilationErrors { policy_path: entry_path.clone(), }, ))); - } - - let request = EvaluateRequest { - policy_path: entry_path, - input, - goals: vec![], - trace: options.trace, }; - let result = workspace - .evaluate(&request) + let result = artifact + .evaluate_entry(&entry_path, input, options.trace) .map_err(|e| Box::new(EvaluationError::Policy(e)))?; - Ok(DecisionGraphResponse { - performance: format!("{:.1?}", result.duration), - result: result.output, - trace: result.trace.map(EvaluationTrace::Policy), - }) + Ok(DecisionGraphResponse::from(result)) } async fn collect_transitive_policies( @@ -95,7 +84,7 @@ async fn collect_transitive_policies( let next = loader .load(import_path.as_ref()) .await - .map_err(|e| Box::::from(e))?; + .map_err(Box::::from)?; queue.push_back((import_path.clone(), next)); } diff --git a/core/engine/src/policy/validator.rs b/core/engine/src/policy/validator.rs index 985693e7..f628910c 100644 --- a/core/engine/src/policy/validator.rs +++ b/core/engine/src/policy/validator.rs @@ -9,6 +9,7 @@ use crate::policy::refs::RefPoolIndex; use crate::policy::MAX_RECURSION_DEPTH; use crate::workspace::db::Db; use crate::workspace::types::InputValidationError; +use zen_types::symbol::Symbol; impl Db { pub(crate) fn input_schema(&self, policy_path: &str) -> InputSchema { @@ -17,11 +18,13 @@ impl Db { let visible_dms = self.visible_data_models(policy_path); let (roots, ref_targets) = DataModelIr::classify_roots(visible_dms.iter().map(|dm| dm.as_ref())); + let dated = InputSchema::dated(&entities); InputSchema { entities, globals, roots, ref_targets, + dated, dictionaries: self.unit(policy_path).dictionaries.clone(), } } @@ -72,6 +75,7 @@ pub(crate) struct InputSchema { globals: HashMap, Property>, roots: HashSet>, ref_targets: HashSet>, + dated: HashSet>, dictionaries: HashMap, Arc>, } @@ -84,6 +88,7 @@ impl InputSchema { ref_pools: &ref_pools, errors: Vec::new(), depth: 0, + path: Vec::new(), }; let Some(input_obj) = input.as_object() else { @@ -102,13 +107,15 @@ impl InputSchema { continue; } let key_str: &str = key.as_ref(); + validator.path.push(Segment::Key(key.clone())); if self.ref_targets.contains(key_str) { - validator.validate_array_of_entity(val, key_str, key_str.to_string()); + validator.validate_array_of_entity(val, key_str); } else if self.roots.contains(key_str) { - validator.validate_entity(val, key_str, key_str.to_string()); + validator.validate_entity(val, key_str); } else if let Some(prop) = self.globals.get(key_str) { - validator.validate_global(val, prop, key_str.to_string()); + validator.validate_global(val, prop); } + validator.path.pop(); } validator.errors @@ -116,6 +123,29 @@ impl InputSchema { } impl InputSchema { + fn dated(entities: &HashMap, Arc>) -> HashSet> { + let mut dated: HashSet> = HashSet::default(); + loop { + let before = dated.len(); + for (name, model) in entities.iter() { + if dated.contains(name) { + continue; + } + let any = model.properties.iter().any(|p| match &p.kind { + PropertyTypeIr::Date => true, + PropertyTypeIr::Relationship { target } => dated.contains(target), + _ => false, + }); + if any { + dated.insert(name.clone()); + } + } + if dated.len() == before { + return dated; + } + } + } + pub(crate) fn convert_dates(&self, input: &Variable) -> Option { DeclaredDates::rewrite_fields(input, |key, value| { if self.ref_targets.contains(key) { @@ -129,7 +159,7 @@ impl InputSchema { } fn convert_entity(&self, value: &Variable, entity: &str, depth: usize) -> Option { - if depth >= MAX_RECURSION_DEPTH { + if depth >= MAX_RECURSION_DEPTH || !self.dated.contains(entity) { return None; } let model = self.entities.get(entity)?; @@ -160,6 +190,78 @@ impl InputSchema { false => convert_one(value), } } + + pub(crate) fn has_dates(&self) -> bool { + !self.dated.is_empty() + || self + .globals + .values() + .any(|property| matches!(property.kind, PropertyTypeIr::Date)) + } + + pub(crate) fn dates_at(&self, path: &str) -> Option { + let mut segments = path.split('.'); + let first = segments.next()?; + let mut at = if self.ref_targets.contains(first) { + DatesAt::Items(Arc::from(first), 0) + } else if self.roots.contains(first) { + DatesAt::Entity(Arc::from(first), 0) + } else { + DatesAt::Property(self.globals.get(first)?.clone(), 0) + }; + for segment in segments { + let (entity, depth) = match &at { + DatesAt::Entity(name, depth) | DatesAt::Items(name, depth) => { + (name.clone(), *depth) + } + DatesAt::Property(property, depth) => match &property.kind { + PropertyTypeIr::Relationship { target } => (target.clone(), *depth), + _ => return None, + }, + }; + if depth >= MAX_RECURSION_DEPTH || !self.dated.contains(&entity) { + return None; + } + let model = self.entities.get(&entity)?; + let property = model.properties.iter().find(|p| *p.name == *segment)?; + at = DatesAt::Property(property.clone(), depth + 1); + } + let dated = match &at { + DatesAt::Entity(name, depth) | DatesAt::Items(name, depth) => { + *depth < MAX_RECURSION_DEPTH && self.dated.contains(name) + } + DatesAt::Property(property, _) => match &property.kind { + PropertyTypeIr::Date => true, + PropertyTypeIr::Relationship { target } => { + self.entities.contains_key(target) && self.dated.contains(target) + } + _ => false, + }, + }; + dated.then_some(at) + } + + pub(crate) fn convert_at(&self, at: &DatesAt, value: &Variable) -> Option { + match at { + DatesAt::Entity(name, depth) => self.convert_entity(value, name, *depth), + DatesAt::Items(name, depth) => { + DeclaredDates::rewrite_items(value, |item| self.convert_entity(item, name, *depth)) + } + DatesAt::Property(property, depth) => self.convert_property(value, property, *depth), + } + } +} + +pub(crate) enum DatesAt { + Entity(Arc, usize), + Items(Arc, usize), + Property(Property, usize), +} + +enum Segment { + Key(Symbol), + Name(Arc), + Index(usize), } struct InputValidator<'a> { @@ -168,24 +270,53 @@ struct InputValidator<'a> { ref_pools: &'a RefPoolIndex, errors: Vec, depth: usize, + path: Vec, } impl InputValidator<'_> { - fn validate_entity(&mut self, value: &Variable, entity_name: &str, path: String) { + fn rendered(&self) -> String { + let mut out = String::new(); + for (i, segment) in self.path.iter().enumerate() { + match segment { + Segment::Key(key) => { + if i > 0 { + out.push('.'); + } + out.push_str(key.as_ref()); + } + Segment::Name(name) => { + out.push('.'); + out.push_str(name); + } + Segment::Index(index) => { + out.push('['); + out.push_str(&index.to_string()); + out.push(']'); + } + } + } + out + } + + fn fail(&mut self, expected: String, got: String) { + let path = self.rendered(); + self.errors.push(InputValidationError { + path, + expected, + got, + }); + } + + fn validate_entity(&mut self, value: &Variable, entity_name: &str) { if self.depth >= MAX_RECURSION_DEPTH { - self.errors.push(InputValidationError { - path, - expected: format!("entity nesting within {MAX_RECURSION_DEPTH} levels"), - got: "deeper".into(), - }); + self.fail( + format!("entity nesting within {MAX_RECURSION_DEPTH} levels"), + "deeper".into(), + ); return; } let Some(obj) = value.as_object() else { - self.errors.push(InputValidationError { - path, - expected: format!("object ({entity_name})"), - got: value.type_name().into(), - }); + self.fail(format!("object ({entity_name})"), value.type_name().into()); return; }; let Some(dm) = self.entities.get(entity_name) else { @@ -205,63 +336,60 @@ impl InputValidator<'_> { else { continue; }; - let child_path = format!("{path}.{}", prop.name); + self.path.push(Segment::Name(prop.name.clone())); if prop.array { - self.validate_array_of_property(val, prop, child_path); + self.validate_array_of_property(val, prop); } else { - self.validate_kind(val, &prop.kind, child_path); + self.validate_kind(val, &prop.kind); } + self.path.pop(); } self.depth -= 1; } - fn validate_global(&mut self, value: &Variable, prop: &Property, path: String) { + fn validate_global(&mut self, value: &Variable, prop: &Property) { if prop.array { - self.validate_array_of_property(value, prop, path); + self.validate_array_of_property(value, prop); } else { - self.validate_kind(value, &prop.kind, path); + self.validate_kind(value, &prop.kind); } } - fn validate_array_of_property(&mut self, value: &Variable, prop: &Property, path: String) { + fn validate_array_of_property(&mut self, value: &Variable, prop: &Property) { let Some(arr) = value.as_array() else { - self.errors.push(InputValidationError { - path, - expected: format!("array of {}", prop.kind), - got: value.type_name().into(), - }); + self.fail(format!("array of {}", prop.kind), value.type_name().into()); return; }; for (i, item) in arr.borrow().iter().enumerate() { if matches!(item, Variable::Null) { continue; } - self.validate_kind(item, &prop.kind, format!("{path}[{i}]")); + self.path.push(Segment::Index(i)); + self.validate_kind(item, &prop.kind); + self.path.pop(); } } - fn validate_array_of_entity(&mut self, value: &Variable, entity_name: &str, path: String) { + fn validate_array_of_entity(&mut self, value: &Variable, entity_name: &str) { let Some(arr) = value.as_array() else { - self.errors.push(InputValidationError { - path, - expected: format!("array of {entity_name}"), - got: value.type_name().into(), - }); + self.fail(format!("array of {entity_name}"), value.type_name().into()); return; }; for (i, item) in arr.borrow().iter().enumerate() { if matches!(item, Variable::Null) { continue; } - self.validate_entity(item, entity_name, format!("{path}[{i}]")); + self.path.push(Segment::Index(i)); + self.validate_entity(item, entity_name); + self.path.pop(); } } - fn validate_kind(&mut self, value: &Variable, kind: &PropertyTypeIr, path: String) { + fn validate_kind(&mut self, value: &Variable, kind: &PropertyTypeIr) { let ok = match kind { PropertyTypeIr::String => matches!(value, Variable::String(_)), PropertyTypeIr::Enum(values) => { - self.validate_enum(value, values, path); + self.validate_enum(value, values); return; } PropertyTypeIr::Number => matches!(value, Variable::Number(_)), @@ -273,35 +401,30 @@ impl InputValidator<'_> { other => zen_expression::DateValue::is(other), }, PropertyTypeIr::Reference { target } => { - self.validate_reference(value, target, path); + self.validate_reference(value, target); return; } PropertyTypeIr::Relationship { target } => { if !self.entities.contains_key(target) { if let Some(dict) = self.dictionaries.get(target) { let values: Vec> = dict.values().cloned().collect(); - self.validate_enum(value, &values, path); + self.validate_enum(value, &values); return; } } - self.validate_entity(value, target, path); + self.validate_entity(value, target); return; } }; if !ok { - self.errors.push(InputValidationError { - path, - expected: kind.to_string(), - got: value.type_name().into(), - }); + self.fail(kind.to_string(), value.type_name().into()); } } - fn validate_enum(&mut self, value: &Variable, values: &[Arc], path: String) { + fn validate_enum(&mut self, value: &Variable, values: &[Arc]) { let Some(s) = value.as_rc_str() else { - self.errors.push(InputValidationError { - path, - expected: format!( + self.fail( + format!( "one of {}", values .iter() @@ -309,14 +432,13 @@ impl InputValidator<'_> { .collect::>() .join(", ") ), - got: value.type_name().into(), - }); + value.type_name().into(), + ); return; }; if !values.iter().any(|v| v.as_ref() == s.as_ref()) { - self.errors.push(InputValidationError { - path, - expected: format!( + self.fail( + format!( "one of {}", values .iter() @@ -324,26 +446,276 @@ impl InputValidator<'_> { .collect::>() .join(", ") ), - got: format!("'{s}'"), - }); + format!("'{s}'"), + ); } } - fn validate_reference(&mut self, value: &Variable, target: &Arc, path: String) { + fn validate_reference(&mut self, value: &Variable, target: &Arc) { let Some(id) = value.as_rc_str() else { - self.errors.push(InputValidationError { - path, - expected: format!("reference id (string → {target})"), - got: value.type_name().into(), - }); + self.fail( + format!("reference id (string → {target})"), + value.type_name().into(), + ); return; }; if !self.ref_pools.contains(target, &id) { - self.errors.push(InputValidationError { - path, - expected: format!("reference id present in '{target}' pool"), - got: format!("'{id}' (not found)"), - }); + self.fail( + format!("reference id present in '{target}' pool"), + format!("'{id}' (not found)"), + ); } } } + +struct Sureness<'s> { + schema: &'s InputSchema, + rows: usize, + sure: Vec, +} + +impl Sureness<'_> { + fn number(column: &zen_expression::lane::Column) -> bool { + use zen_expression::lane::{Dictionary, Values}; + matches!( + column.values, + Values::Dec(_) + | Values::Scaled { .. } + | Values::I64(_) + | Values::F64(_) + | Values::Dict { + values: Dictionary::Scaled { .. }, + .. + } + ) + } + + fn string(column: &zen_expression::lane::Column) -> bool { + use zen_expression::lane::{Dictionary, Values}; + matches!( + column.values, + Values::Utf8 { .. } + | Values::Text { .. } + | Values::LargeUtf8 { .. } + | Values::Strs(_) + | Values::Dict { + values: Dictionary::Text { .. }, + .. + } + ) + } + + fn boolean(column: &zen_expression::lane::Column) -> bool { + use zen_expression::lane::{Dictionary, Values}; + matches!( + column.values, + Values::Bool { .. } + | Values::Dict { + values: Dictionary::Bool { .. }, + .. + } + ) + } + + fn scalar( + &self, + kind: &PropertyTypeIr, + column: &zen_expression::lane::Column, + at: usize, + ) -> bool { + if !column.valid(at) { + return true; + } + match kind { + PropertyTypeIr::Number => { + Self::number(column) + || matches!(column.variable(at), Variable::Number(_) | Variable::Null) + } + PropertyTypeIr::String => { + Self::string(column) + || matches!(column.variable(at), Variable::String(_) | Variable::Null) + } + PropertyTypeIr::Boolean => { + Self::boolean(column) + || matches!(column.variable(at), Variable::Bool(_) | Variable::Null) + } + PropertyTypeIr::Enum(values) => match column.variable(at) { + Variable::Null => true, + Variable::String(s) => values.iter().any(|v| v.as_ref() == s.as_str()), + _ => false, + }, + PropertyTypeIr::Relationship { target } => self.objects(target, column, at), + PropertyTypeIr::Date | PropertyTypeIr::Reference { .. } => false, + } + } + + fn objects(&self, target: &str, column: &zen_expression::lane::Column, at: usize) -> bool { + use zen_expression::lane::Values; + if !self.schema.entities.contains_key(target) { + return false; + } + match column.values { + Values::Struct { fields, .. } => self.structs(target, fields, at), + _ => false, + } + } + + fn structs( + &self, + target: &str, + fields: &[(&str, zen_expression::lane::Column)], + at: usize, + ) -> bool { + let Some(model) = self.schema.entities.get(target) else { + return false; + }; + fields.iter().all(|(name, column)| { + match model.properties.iter().find(|p| p.name.as_ref() == *name) { + None => true, + Some(prop) => self.property(prop, column, at), + } + }) + } + + fn property(&self, prop: &Property, column: &zen_expression::lane::Column, at: usize) -> bool { + use zen_expression::lane::{Dictionary, Values}; + if !column.valid(at) { + return true; + } + match prop.array { + false => self.scalar(&prop.kind, column, at), + true => { + let Values::List { child, .. } = column.values else { + return false; + }; + let Some((a, b)) = column.range(at) else { + return true; + }; + let child = match child { + Dictionary::Column(child) => *child, + other => other.column(), + }; + (a..b).all(|item| self.scalar(&prop.kind, &child, item)) + } + } + } + + fn typed(&self, prop: &Property, column: &zen_expression::lane::Column) -> bool { + use zen_expression::lane::{Dictionary, Values}; + match prop.array { + false => self.kinded(&prop.kind, column), + true => match column.values { + Values::List { child, .. } => { + let child = match child { + Dictionary::Column(child) => *child, + other => other.column(), + }; + self.kinded(&prop.kind, &child) + } + _ => false, + }, + } + } + + fn kinded(&self, kind: &PropertyTypeIr, column: &zen_expression::lane::Column) -> bool { + use zen_expression::lane::Values; + match kind { + PropertyTypeIr::Number => Self::number(column), + PropertyTypeIr::String => Self::string(column), + PropertyTypeIr::Boolean => Self::boolean(column), + PropertyTypeIr::Relationship { target } => { + match (column.values, self.schema.entities.get(target)) { + (Values::Struct { fields, .. }, Some(model)) => { + fields.iter().all(|(name, field)| { + match model.properties.iter().find(|p| p.name.as_ref() == *name) { + None => true, + Some(prop) => self.typed(prop, field), + } + }) + } + _ => false, + } + } + _ => false, + } + } + + fn mark(&mut self, column: &zen_expression::lane::Column, test: impl Fn(&Self, usize) -> bool) { + for row in 0..self.rows { + if self.sure[row] && column.valid(row) && !test(self, row) { + self.sure[row] = false; + } + } + } + + fn path(&mut self, path: &str, column: &zen_expression::lane::Column) -> Option<()> { + let segments: Vec<&str> = path.split('.').collect(); + let (first, rest) = segments.split_first()?; + if self.schema.ref_targets.contains(*first) { + return None; + } + if self.schema.roots.contains(*first) { + let mut entity: Arc = Arc::from(*first); + for (depth, segment) in rest.iter().enumerate() { + let model = self.schema.entities.get(&entity)?.clone(); + let Some(prop) = model + .properties + .iter() + .find(|p| p.name.as_ref() == *segment) + else { + return Some(()); + }; + if depth + 1 == rest.len() { + if !self.typed(prop, column) { + self.mark(column, |s, row| s.property(prop, column, row)); + } + return Some(()); + } + match (&prop.kind, prop.array) { + (PropertyTypeIr::Relationship { target }, false) + if self.schema.entities.contains_key(target) => + { + entity = target.clone() + } + _ => { + self.mark(column, |_, _| false); + return Some(()); + } + } + } + let target = entity.clone(); + self.mark(column, |s, row| s.objects(&target, column, row)); + return Some(()); + } + if let Some(prop) = self.schema.globals.get(*first) { + match rest.is_empty() { + true if self.typed(prop, column) => {} + true => self.mark(column, |s, row| s.property(prop, column, row)), + false => self.mark(column, |_, _| false), + } + } + Some(()) + } +} + +impl InputSchema { + pub(crate) fn sure(&self, columns: &zen_expression::lane::Columns) -> Option> { + let dated_global = self.globals.values().any(|p| match &p.kind { + PropertyTypeIr::Date => true, + PropertyTypeIr::Relationship { target } => self.dated.contains(target), + _ => false, + }); + if !self.dated.is_empty() || !self.ref_targets.is_empty() || dated_global { + return None; + } + let mut sureness = Sureness { + schema: self, + rows: columns.rows, + sure: vec![true; columns.rows], + }; + for (path, column) in &columns.columns { + sureness.path(path, column)?; + } + Some(sureness.sure) + } +} diff --git a/core/engine/src/prepared.rs b/core/engine/src/prepared.rs new file mode 100644 index 00000000..8a0c40d0 --- /dev/null +++ b/core/engine/src/prepared.rs @@ -0,0 +1,131 @@ +use crate::decision::Decision; +use crate::loader::DynamicLoader; +use crate::model::GraphContent; +use crate::policy::evaluator::EvalArtifact; +use crate::policy::raw::PolicyDocument; +use ahash::HashMap; +use std::sync::{Arc, Mutex}; + +#[derive(Debug, Default)] +pub(crate) struct Prepared { + graphs: Mutex, Kept>>, +} + +#[derive(Debug)] +struct Kept { + source: Arc, + ready: Arc, +} + +impl Prepared { + pub async fn graph( + &self, + key: &str, + source: Arc, + loader: &DynamicLoader, + ) -> Arc { + if let Some(ready) = self.kept(key, &source) { + return ready; + } + let ready = GraphContent::loaded(source.clone(), loader).await; + if !ready.schemas_failed() { + if let Ok(mut graphs) = self.graphs.lock() { + graphs.insert( + Arc::from(key), + Kept { + source, + ready: ready.clone(), + }, + ); + } + } + ready + } + + fn kept(&self, key: &str, source: &Arc) -> Option> { + let graphs = self.graphs.lock().ok()?; + let kept = graphs.get(key)?; + Arc::ptr_eq(&kept.source, source).then(|| kept.ready.clone()) + } +} + +#[derive(Debug, Default)] +pub(crate) struct Decisions { + decisions: Mutex, Arc>>, +} + +impl Decisions { + pub fn get( + &self, + key: &str, + source: &Arc, + build: impl FnOnce() -> Decision, + ) -> Arc { + if let Ok(decisions) = self.decisions.lock() { + if let Some(decision) = decisions.get(key) { + if decision.holds(source) { + return decision.clone(); + } + } + } + let decision = Arc::new(build()); + if let Ok(mut decisions) = self.decisions.lock() { + decisions.insert(Arc::from(key), decision.clone()); + } + decision + } +} + +type Documents = Vec<(Arc, Arc)>; + +#[derive(Default)] +pub(crate) struct Policies { + artifacts: Mutex, KeptPolicy>>, +} + +struct KeptPolicy { + documents: Documents, + artifact: Option>, +} + +impl std::fmt::Debug for Policies { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Policies").finish_non_exhaustive() + } +} + +impl Policies { + pub fn artifact( + &self, + key: &str, + documents: Documents, + build: impl FnOnce(&Documents) -> Option>, + ) -> Option> { + if let Ok(artifacts) = self.artifacts.lock() { + if let Some(kept) = artifacts.get(key) { + if Self::same(&kept.documents, &documents) { + return kept.artifact.clone(); + } + } + } + let artifact = build(&documents); + if let Ok(mut artifacts) = self.artifacts.lock() { + artifacts.insert( + Arc::from(key), + KeptPolicy { + documents, + artifact: artifact.clone(), + }, + ); + } + artifact + } + + fn same(kept: &Documents, loaded: &Documents) -> bool { + kept.len() == loaded.len() + && kept + .iter() + .zip(loaded) + .all(|((a, x), (b, y))| a == b && Arc::ptr_eq(x, y)) + } +} diff --git a/core/engine/src/workspace/db.rs b/core/engine/src/workspace/db.rs index d6baf353..efa65797 100644 --- a/core/engine/src/workspace/db.rs +++ b/core/engine/src/workspace/db.rs @@ -5,12 +5,10 @@ use std::sync::Arc; use ahash::{HashMap, HashMapExt, HashSet}; use zen_expression::intellisense::IntelliSense; use zen_expression::variable::VariableType; -use zen_expression::{Isolate, OpcodeCache}; use crate::model::{DecisionContent, PolicyContent}; use crate::policy::blocks::{ - Block, BlockKind, BlockReadPlan, IntelliSenseSource, PropertyRead, ReadFlattener, - SharedIntelliSense, + Block, BlockReadPlan, IntelliSenseSource, PropertyRead, ReadFlattener, SharedIntelliSense, }; use crate::policy::evaluator::EvalArtifact; use crate::policy::ir::{ @@ -59,12 +57,18 @@ pub(crate) struct DepFrame { views: Vec<(Arc, ReadView)>, } +type ParsedEntry = (Arc, Arc); +type ShallowEntry = (Arc, Arc>); +type UnitEntry = (Vec>, Arc); +type GraphEntry = (GraphDeps, Arc); +type Components = (Vec>>, HashMap, usize>); + #[derive(Default)] pub(crate) struct PolicyDerivedCache { - parsed: RefCell, (Arc, Arc)>>, - shallow: RefCell, (Arc, Arc>)>>, - units: RefCell>, (Vec>, Arc)>>, - graphs: RefCell, (GraphDeps, Arc)>>, + parsed: RefCell, ParsedEntry>>, + shallow: RefCell, ShallowEntry>>, + units: RefCell>, UnitEntry>>, + graphs: RefCell, GraphEntry>>, } impl PolicyDerivedCache { @@ -174,7 +178,8 @@ pub struct Unit { pub execution_order: Vec, pub computed_instances: HashMap, InstanceTarget>, enriched_once: OnceCell>, - opcode_cache: OnceCell>, + #[cfg(feature = "driver")] + opcode_cache: OnceCell>, pub data_models: Vec, pub entities: HashMap, Arc>, pub dictionaries: HashMap, Arc>, @@ -649,7 +654,8 @@ impl Db { ) } - pub(crate) fn opcode_cache_of_unit(&self, unit: &Unit) -> Arc { + #[cfg(feature = "driver")] + pub(crate) fn opcode_cache_of_unit(&self, unit: &Unit) -> Arc { unit.opcode_cache .get_or_init(|| { let snap = self.snapshot(); @@ -662,7 +668,7 @@ impl Db { for loc in rule.kind.expressions(&rule.id) { sources.push((loc.source, loc.kind)); } - if let BlockKind::DecisionTable(dt) = &rule.kind { + if let crate::policy::blocks::BlockKind::DecisionTable(dt) = &rule.kind { for col in &dt.inputs { if let Some(field) = col.field.as_ref().filter(|f| !f.as_ref().is_empty()) @@ -674,8 +680,8 @@ impl Db { } } - let mut cache = OpcodeCache::new(); - let mut isolate = Isolate::new(); + let mut cache = zen_expression::OpcodeCache::new(); + let mut isolate = zen_expression::Isolate::new(); for (source, kind) in &sources { let map = match kind { ExpressionKind::Standard => &mut cache.standard, @@ -708,6 +714,7 @@ impl Db { } let unit = self.unit(policy); + #[cfg(feature = "driver")] let opcode_cache = self.opcode_cache_of_unit(&unit); let input_schema = self.input_schema(policy); let eval_graph = EvalGraph::from_graph(&unit.dep_graph); @@ -784,11 +791,16 @@ impl Db { reference_fields: unit.reference_fields.clone(), data_model_paths: unit.data_model_paths.clone(), classifier: unit.classifier.clone(), + #[cfg(feature = "driver")] opcode_cache, rule_by_ref: snap.rule_by_ref.clone(), input_schema, reads, read_plans, + compiled: Default::default(), + goal_plans: Default::default(), + requirements: Default::default(), + programs: Default::default(), }); snap.eval_artifacts .borrow_mut() @@ -909,7 +921,7 @@ impl Snapshot { fn compute_components( import_graph: &ImportGraph, all_parsed: &HashMap, Arc>, - ) -> (Vec>>, HashMap, usize>) { + ) -> Components { let mut seen: HashSet> = HashSet::default(); let mut components: Vec>> = Vec::new(); let mut sorted: Vec<&Arc> = all_parsed.keys().collect(); @@ -1031,6 +1043,7 @@ impl Snapshot { execution_order, computed_instances, enriched_once: OnceCell::new(), + #[cfg(feature = "driver")] opcode_cache: OnceCell::new(), data_models, entities, diff --git a/core/engine/src/workspace/graph/analysis.rs b/core/engine/src/workspace/graph/analysis.rs index a5782bb5..7c958479 100644 --- a/core/engine/src/workspace/graph/analysis.rs +++ b/core/engine/src/workspace/graph/analysis.rs @@ -29,6 +29,7 @@ use crate::workspace::types::{ CursorTarget, Diagnostic, DiagnosticArgs, DiagnosticCode, DiagnosticLocation, ExpressionKind, Severity, }; +use zen_types::path::DotPath; const NODES_KEY: &str = "$nodes"; @@ -1221,6 +1222,14 @@ impl<'a> GraphAnalyzer<'a> { )); continue; } + if collect && matches!(content.hit_policy, DecisionTableHitPolicy::Collect) { + self.diagnostics.push(Diagnostic::warning( + DiagnosticCode::InvalidWritePath, + DiagnosticLocation::expression(self.path.clone(), node.id.clone(), col.id.clone(), None) + .with_target(CursorTarget::DecisionTableHead { col: col.id.clone() }), + format!("the collect marker on '{}' has no effect under the collect hit policy: each matched rule writes '{path}' as a single value", col.field), + )); + } let declared = self.declared_output_type(node, col); let mut cell_types: Vec = Vec::new(); let mut has_null_cell = false; @@ -1417,15 +1426,7 @@ impl<'a> GraphAnalyzer<'a> { return false; } let field = field.trim(); - !written.iter().any(|w| { - let w = w.as_ref(); - field == w - || field - .strip_prefix(w) - .is_some_and(|rest| rest.starts_with('.')) - || w.strip_prefix(field) - .is_some_and(|rest| rest.starts_with('.')) - }) + !written.iter().any(|w| DotPath::overlaps(field, w)) } fn constraints_after(node: &DecisionNode, incoming: PathConstraints) -> PathConstraints { @@ -2643,12 +2644,7 @@ impl<'a> GraphAnalyzer<'a> { } fn locate_nullable_sources(&mut self, topology: &GraphTopology) { - let covers = |written: &str, field: &str| { - field == written - || field - .strip_prefix(written) - .is_some_and(|rest| rest.starts_with('.')) - }; + let covers = |written: &str, field: &str| DotPath::within(field, written); let writes = |node: &DecisionNode, field: &str| -> bool { let prefixed = |attrs: &TransformAttributes, key: &str| match &attrs.output_path { Some(prefix) => format!("{prefix}.{key}"), diff --git a/core/engine/src/workspace/graph/enhance.rs b/core/engine/src/workspace/graph/enhance.rs index 18d874f0..7b7cdca8 100644 --- a/core/engine/src/workspace/graph/enhance.rs +++ b/core/engine/src/workspace/graph/enhance.rs @@ -3,15 +3,15 @@ use std::sync::Arc; use ahash::{HashMap, HashMapExt, HashSet, HashSetExt}; use base64::Engine as _; use rust_decimal::prelude::ToPrimitive; +use zen_expression::lane::Session; use zen_expression::variable::Variable; -use zen_expression::Isolate; use zen_types::decision::{ DecisionNode, DecisionNodeKind, DecisionTableContent, DecisionTableHitPolicy, TransformExecutionMode, }; +use crate::compiled::exact::RowTable; use crate::model::GraphContent; -use crate::nodes::decision_table::DecisionTableNodeHandler; use crate::workspace::db::{Db, Snapshot}; use crate::workspace::graph::editor::{NodePaths, ReadBase}; use crate::workspace::graph::function_source; @@ -54,8 +54,8 @@ impl EnhanceState<'_> { let Some(input_field) = &content.transform_attributes.input_field else { return Some(base); }; - let mut isolate = Isolate::with_environment(base); - let calculated = isolate.run_standard(input_field.as_ref()).ok()?; + let mut session = Session::with_environment(base); + let calculated = session.run_standard(input_field.as_ref()).ok()?; match &calculated { Variable::Array(items) => { let items = items @@ -82,12 +82,13 @@ impl EnhanceState<'_> { content: &DecisionTableContent, environment: Variable, ) -> DecisionTableExtras { - let mut isolate = Isolate::with_environment(environment.depth_clone(1)); + let mut session = Session::with_environment(environment.depth_clone(1)); + let mut table = RowTable::new(&mut session, &content.inputs, None, None); let bytes_per_row = content.inputs.len().div_ceil(8); let mut bits = vec![0u8; bytes_per_row * content.rules.len()]; for (row, rule) in content.rules.iter().enumerate() { - for (col, input) in content.inputs.iter().enumerate() { - if DecisionTableNodeHandler::cell_passes(rule, input, &mut isolate) { + for col in 0..content.inputs.len() { + if table.cell(col, rule).unwrap_or(false) { bits[row * bytes_per_row + (col >> 3)] |= 1 << (col & 7); } } diff --git a/core/engine/src/workspace/mod.rs b/core/engine/src/workspace/mod.rs index cc59adf5..6cf6996a 100644 --- a/core/engine/src/workspace/mod.rs +++ b/core/engine/src/workspace/mod.rs @@ -91,6 +91,40 @@ impl Workspace { self.db.enhance_trace(req) } + pub fn evaluate_batch( + &self, + requests: &[EvaluateRequest], + ) -> Vec> { + self.db.evaluate_batch(requests) + } + + pub fn evaluate_columns<'a>( + &self, + policy_path: &Arc, + goals: &[Arc], + columns: &'a zen_expression::lane::Columns<'a>, + ) -> Result, EvaluationError> { + self.db.evaluate_columns(policy_path, goals, columns) + } + + #[cfg(feature = "driver")] + #[doc(hidden)] + pub fn evaluate_with_driver( + &self, + req: &EvaluateRequest, + ) -> Result { + self.db.evaluate_with_driver(req) + } + + #[cfg(feature = "driver")] + #[doc(hidden)] + pub fn enhance_trace_with_driver( + &self, + req: &EvaluateRequest, + ) -> Result { + self.db.enhance_trace_with_driver(req) + } + pub fn enhance_graph_trace( &self, document: &Arc, @@ -166,7 +200,7 @@ impl Workspace { self.db.unit(importer).members.contains(policy) } - pub(crate) fn evaluation_diagnostics(&self, entry: &str) -> Vec { + pub fn evaluation_diagnostics(&self, entry: &str) -> Vec { self.db.evaluation_diagnostics(&Arc::from(entry)) } diff --git a/core/engine/tests/bench_matrix.rs b/core/engine/tests/bench_matrix.rs new file mode 100644 index 00000000..48eec504 --- /dev/null +++ b/core/engine/tests/bench_matrix.rs @@ -0,0 +1,633 @@ +#![cfg(feature = "driver")] +#![allow(dead_code)] + +mod conformance; +#[path = "support/fixture.rs"] +mod fixture; +#[path = "support/policies.rs"] +mod policies; +#[path = "support/policy_gen.rs"] +mod policy_gen; +mod support; + +use conformance::run::{GraphRun, PolicyRun}; +use conformance::{Dialect, Spec}; +use fixture::{Fixture, NETWORK_BOUND, TIME_BOUND}; +use policies::Anchor; +use policy_gen::{Gen, Rng}; +use serde_json::{json, Value}; +use std::io::Write; +use std::sync::Arc; +use std::time::Instant; +use support::columns::Built; +use zen_engine::policy::{EvaluateRequest, PolicyWorkspace}; +use zen_engine::{Decision, DecisionEngine, EvaluationOptions}; +use zen_expression::Variable; + +struct Matrix { + out: std::fs::File, + rows: usize, + reps: usize, + runtime: tokio::runtime::Runtime, +} + +struct GraphJob<'j> { + corpus: &'static str, + case: String, + walker: Decision, + compiled: Decision, + cold: Decision, + engine: Option<(&'j DecisionEngine, &'static str)>, + rows: Vec, +} + +struct PolicyJob<'j> { + corpus: &'static str, + case: String, + workspace: &'j PolicyWorkspace, + path: Arc, + goals: Vec>, + engine: Option<(&'j DecisionEngine, &'static str)>, + cold: Option<&'j dyn Fn() -> PolicyWorkspace>, + rows: Vec, +} + +impl Matrix { + fn new() -> Matrix { + let path = std::env::var("BENCH_OUT").unwrap_or_else(|_| "/tmp/bench-matrix.jsonl".into()); + Matrix { + out: std::fs::File::create(path).expect("bench output"), + rows: std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(256), + reps: std::env::var("BENCH_REPS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(5), + runtime: tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"), + } + } + + fn cycled(&self, rows: &[Value]) -> Vec { + (0..self.rows) + .map(|i| rows[i % rows.len()].clone()) + .collect() + } + + fn record(&mut self, kind: &str, corpus: &str, case: &str, mode: &str, rows: usize, ns: f64) { + if ns.is_finite() { + let line = json!({ "kind": kind, "corpus": corpus, "case": case, "mode": mode, "rows": rows, "ns": ns }); + writeln!(self.out, "{line}").expect("bench write"); + } + } + + fn best( + &self, + rows: usize, + mut prepare: impl FnMut() -> Vec, + mut run: impl FnMut(Vec), + ) -> f64 { + let mut best = f64::INFINITY; + for _ in 0..self.reps { + let inputs = prepare(); + let start = Instant::now(); + run(inputs); + best = best.min(start.elapsed().as_nanos() as f64 / rows.max(1) as f64); + } + best + } + + fn columns(rows: &[Value], run: impl FnOnce(&zen_expression::lane::Columns)) -> bool { + let nested = std::env::var("BENCH_NESTED").is_ok(); + if nested { + if let Some(built) = Built::nested(rows) { + let fields = built.fields(); + let structs = built.structs(&fields); + run(&built.columns_with(&structs)); + return true; + } + } + if let Some(built) = Built::new(rows) { + run(&built.columns()); + return true; + } + match Built::nested(rows) { + Some(built) => { + let fields = built.fields(); + let structs = built.structs(&fields); + run(&built.columns_with(&structs)); + true + } + None => false, + } + } + + fn graph(&mut self, job: GraphJob) { + let rows = self.cycled(&job.rows); + let count = rows.len(); + let fresh = || { + rows.iter() + .map(|r| Variable::from(r.clone())) + .collect::>() + }; + let rt = &self.runtime; + rt.block_on(async { + for decision in [&job.walker, &job.compiled] { + for input in fresh().into_iter().take(2) { + let _ = decision.evaluate(input).await; + } + } + let _ = job + .compiled + .evaluate_batch(&fresh(), EvaluationOptions::default()) + .await; + }); + let old = self.best(count, fresh, |inputs| { + rt.block_on(async { + for input in inputs { + let _ = job.walker.evaluate(input).await; + } + }) + }); + let single = self.best(count, fresh, |inputs| { + rt.block_on(async { + for input in inputs { + let _ = job.compiled.evaluate(input).await; + } + }) + }); + let engine = match job.engine { + Some((engine, key)) => self.best(count, fresh, |inputs| { + rt.block_on(async { + for input in inputs { + let _ = engine.evaluate(key, input).await; + } + }) + }), + None => f64::NAN, + }; + let batch = self.best(count, fresh, |inputs| { + rt.block_on(async { + drop( + job.compiled + .evaluate_batch(&inputs, EvaluationOptions::default()) + .await, + ); + }) + }); + let mut columnar = f64::INFINITY; + let reps = self.reps; + Self::columns(&rows, |columns| { + rt.block_on(async { + drop( + job.compiled + .evaluate_columns(columns, EvaluationOptions::default()) + .await, + ); + for _ in 0..reps { + let start = Instant::now(); + drop( + job.compiled + .evaluate_columns(columns, EvaluationOptions::default()) + .await, + ); + columnar = columnar.min(start.elapsed().as_nanos() as f64 / count as f64); + } + }) + }); + let first = || Variable::from(rows[0].clone()); + let cold_old = self.best( + 1, + || vec![first()], + |inputs| { + let walker = job.cold.clone().interpreted(); + rt.block_on(async { + for input in inputs { + let _ = walker.evaluate(input).await; + } + }) + }, + ); + let cold_new = self.best( + 1, + || vec![first()], + |inputs| { + let decision = job.cold.clone(); + rt.block_on(async { + for input in inputs { + let _ = decision.evaluate(input).await; + } + }) + }, + ); + for (mode, ns) in [ + ("old.single", old), + ("new.single", single), + ("new.engine", engine), + ("new.batch", batch), + ("new.columnar", columnar), + ("old.cold", cold_old), + ("new.cold", cold_new), + ] { + self.record("graph", job.corpus, &job.case, mode, count, ns); + } + } + + fn policy(&mut self, job: PolicyJob) { + let rows = self.cycled(&job.rows); + let count = rows.len(); + let requests = || -> Vec { + rows.iter() + .map(|r| EvaluateRequest { + policy_path: job.path.clone(), + input: Variable::from(r.clone()), + goals: job.goals.clone(), + trace: false, + }) + .collect() + }; + let ws = job.workspace; + for request in requests().iter().take(2) { + let _ = ws.evaluate_with_driver(request); + let _ = ws.evaluate(request); + } + drop(ws.evaluate_batch(&requests())); + let time = |run: &dyn Fn(Vec)| { + let mut best = f64::INFINITY; + for _ in 0..self.reps { + let batch = requests(); + let start = Instant::now(); + run(batch); + best = best.min(start.elapsed().as_nanos() as f64 / count as f64); + } + best + }; + let old = time(&|batch| batch.iter().for_each(|r| drop(ws.evaluate_with_driver(r)))); + let single = time(&|batch| batch.iter().for_each(|r| drop(ws.evaluate(r)))); + let batch = time(&|batch| drop(ws.evaluate_batch(&batch))); + let engine = match job.engine { + Some((engine, key)) => { + let rt = &self.runtime; + let fresh = || { + rows.iter() + .map(|r| Variable::from(r.clone())) + .collect::>() + }; + self.best(count, fresh, |inputs| { + rt.block_on(async { + for input in inputs { + let _ = engine.evaluate(key, input).await; + } + }) + }) + } + None => f64::NAN, + }; + let mut columnar = f64::INFINITY; + let reps = self.reps; + Self::columns(&rows, |columns| { + drop(ws.evaluate_columns(&job.path, &job.goals, columns)); + for _ in 0..reps { + let start = Instant::now(); + drop(ws.evaluate_columns(&job.path, &job.goals, columns)); + columnar = columnar.min(start.elapsed().as_nanos() as f64 / count as f64); + } + }); + let (mut cold_old, mut cold_new) = (f64::NAN, f64::NAN); + if let Some(build) = job.cold { + let first = requests().into_iter().next(); + if let Some(first) = first { + let measure = |driver: bool| { + let mut best = f64::INFINITY; + for _ in 0..self.reps { + let request = first.clone(); + let start = Instant::now(); + let ws = build(); + match driver { + true => drop(ws.evaluate_with_driver(&request)), + false => drop(ws.evaluate(&request)), + } + best = best.min(start.elapsed().as_nanos() as f64); + } + best + }; + cold_old = measure(true); + cold_new = measure(false); + } + } + for (mode, ns) in [ + ("old.single", old), + ("new.single", single), + ("new.engine", engine), + ("new.batch", batch), + ("new.columnar", columnar), + ("old.cold", cold_old), + ("new.cold", cold_new), + ] { + self.record("policy", job.corpus, &job.case, mode, count, ns); + } + } +} + +#[test] +#[ignore] +fn bench_matrix() { + support::switches(); + let only = std::env::var("BENCH_ONLY").unwrap_or_default(); + let wants = |corpus: &str| only.is_empty() || only.split(',').any(|o| o == corpus); + let mut matrix = Matrix::new(); + let started = Instant::now(); + + if wants("spec-graph") { + Spec::prepare(); + let (suites, _) = Spec::suites(Dialect::Graph); + for suite in &suites { + if suite.cases.is_empty() { + continue; + } + let Ok(run) = GraphRun::new(suite) else { + continue; + }; + let rows: Vec = suite.cases.iter().map(|c| c.input.to_value()).collect(); + let job = GraphJob { + corpus: "spec-graph", + case: suite.id(), + walker: run.walker.clone(), + compiled: run.uncompiled.clone(), + cold: run.uncompiled.clone(), + engine: Some((&run.engine, GraphRun::MAIN)), + rows, + }; + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| matrix.graph(job))); + } + eprintln!( + "spec-graph: {} suites in {:?}", + suites.len(), + started.elapsed() + ); + } + + if wants("fixtures") { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let loader = Arc::new(support::create_fs_loader()); + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + { + continue; + } + let decision = + Decision::from(Arc::new(fixture.content.clone())).with_loader(loader.clone()); + let job = GraphJob { + corpus: "fixtures", + case: fixture.name.clone(), + walker: decision.interpreted(), + compiled: decision.clone(), + cold: decision, + engine: None, + rows: fixture.variants(), + }; + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| matrix.graph(job))); + } + eprintln!("fixtures done at {:?}", started.elapsed()); + } + + if wants("spec-policy") { + Spec::prepare(); + let (suites, _) = Spec::suites(Dialect::Policy); + for suite in &suites { + let Ok(run) = PolicyRun::new(suite) else { + continue; + }; + if !run.blocking.is_empty() || suite.cases.is_empty() { + continue; + } + let goals = &suite.cases[0].goals; + let cases: Vec<_> = suite.cases.iter().filter(|c| &c.goals == goals).collect(); + let rows: Vec = cases.iter().map(|c| c.input.to_value()).collect(); + let cold = || { + PolicyRun::new(suite) + .map(|run| run.workspace) + .unwrap_or_default() + }; + let job = PolicyJob { + corpus: "spec-policy", + case: suite.id(), + workspace: &run.workspace, + path: Arc::from(PolicyRun::MAIN), + goals: goals.iter().map(|g| Arc::from(g.as_str())).collect(), + engine: goals.is_empty().then_some((&run.engine, PolicyRun::MAIN)), + cold: Some(&cold), + rows, + }; + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| matrix.policy(job))); + } + eprintln!( + "spec-policy: {} suites done at {:?}", + suites.len(), + started.elapsed() + ); + } + + if wants("generated") { + for seed in 0..40u64 { + let Ok(parsed) = serde_json::from_value(Gen::document(seed)) else { + continue; + }; + let build = || { + let mut ws = PolicyWorkspace::new(); + if let Ok(parsed) = serde_json::from_value(Gen::document(seed)) { + ws.set_policy("generated.json", parsed); + } + ws + }; + let mut ws = PolicyWorkspace::new(); + ws.set_policy("generated.json", parsed); + let mut rng = Rng(seed.wrapping_mul(7919) | 1); + let rows: Vec = (0..64).map(|_| Gen::valid_input(&mut rng)).collect(); + let job = PolicyJob { + corpus: "generated-policy", + case: format!("seed-{seed:02}"), + workspace: &ws, + path: Arc::from("generated.json"), + goals: Vec::new(), + engine: None, + cold: Some(&build), + rows, + }; + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| matrix.policy(job))); + } + let ws = Anchor::workspace(); + let build = Anchor::workspace; + let job = PolicyJob { + corpus: "anchor-policy", + case: "anchor".into(), + workspace: &ws, + path: Arc::from(Anchor::PATH), + goals: Vec::new(), + engine: None, + cold: Some(&build), + rows: Anchor::rows(matrix.rows, 7), + }; + matrix.policy(job); + eprintln!("generated done at {:?}", started.elapsed()); + } + if support::switches().census { + for (key, calls, rows, ns) in zen_engine::diagnostics::census() { + println!("CENSUS\t{key}\t{calls}\t{rows}\t{ns}"); + } + } +} + +#[test] +#[ignore] +fn columnar_reasons() { + support::switches(); + let path = std::env::var("BENCH_OUT").unwrap_or_else(|_| "/tmp/columnar-reasons.jsonl".into()); + let mut out = std::fs::File::create(path).expect("reasons output"); + let rows: usize = 256; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime"); + let cycled = |rows_in: &[Value]| -> Vec { + (0..rows) + .map(|i| rows_in[i % rows_in.len()].clone()) + .collect() + }; + let graph = |out: &mut std::fs::File, + corpus: &str, + case: String, + decision: &Decision, + rows: Vec| { + Matrix::columns(&rows, |columns| { + let output = + runtime.block_on(decision.evaluate_columns(columns, EvaluationOptions::default())); + let verdict = match zen_engine::diagnostics::plan_verdict(decision, columns) { + Some(Ok(())) => "planned".to_string(), + Some(Err(reason)) => reason, + None => "invalid".to_string(), + }; + let errors = output.errors.iter().filter(|e| e.is_some()).count(); + let paths = output.paths(); + let line = json!({ "kind": "graph", "corpus": corpus, "case": case, "verdict": verdict, "typed": paths.typed, "laned": paths.laned, "hosted": paths.hosted, "errors": errors, "rows": columns.rows }); + writeln!(out, "{line}").expect("write"); + }); + }; + Spec::prepare(); + let (suites, _) = Spec::suites(Dialect::Graph); + for suite in &suites { + if suite.cases.is_empty() { + continue; + } + let Ok(run) = GraphRun::new(suite) else { + continue; + }; + let rows = cycled( + &suite + .cases + .iter() + .map(|c| c.input.to_value()) + .collect::>(), + ); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + graph(&mut out, "spec-graph", suite.id(), &run.compiled, rows) + })); + } + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let loader = Arc::new(support::create_fs_loader()); + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + { + continue; + } + let decision = + Decision::from(Arc::new(fixture.content.clone())).with_loader(loader.clone()); + let rows = cycled(&fixture.variants()); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + graph(&mut out, "fixtures", fixture.name.clone(), &decision, rows) + })); + } + let policy = |out: &mut std::fs::File, + corpus: &str, + case: String, + ws: &PolicyWorkspace, + path: &Arc, + goals: &[Arc], + rows: Vec| { + Matrix::columns(&rows, |columns| { + let line = match ws.evaluate_columns(path, goals, columns) { + Ok(output) => { + let paths = output.paths(); + let errors = output.errors.iter().filter(|e| e.is_some()).count(); + let census: Vec = zen_engine::diagnostics::census() + .into_iter() + .map(|(key, _, rows, _)| format!("{key} [{rows}]")) + .collect(); + json!({ "kind": "policy", "corpus": corpus, "case": case, "typed": paths.typed, "laned": paths.laned, "hosted": paths.hosted, "errors": errors, "rows": columns.rows, "census": census }) + } + Err(e) => { + json!({ "kind": "policy", "corpus": corpus, "case": case, "failed": format!("{e:?}") }) + } + }; + writeln!(out, "{line}").expect("write"); + }); + }; + let (suites, _) = Spec::suites(Dialect::Policy); + for suite in &suites { + let Ok(run) = PolicyRun::new(suite) else { + continue; + }; + if !run.blocking.is_empty() || suite.cases.is_empty() { + continue; + } + let goals = &suite.cases[0].goals; + let rows = cycled( + &suite + .cases + .iter() + .filter(|c| &c.goals == goals) + .map(|c| c.input.to_value()) + .collect::>(), + ); + let targets: Vec> = goals.iter().map(|g| Arc::from(g.as_str())).collect(); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + policy( + &mut out, + "spec-policy", + suite.id(), + &run.workspace, + &Arc::from(PolicyRun::MAIN), + &targets, + rows, + ) + })); + } + for seed in 0..40u64 { + let Ok(parsed) = serde_json::from_value(Gen::document(seed)) else { + continue; + }; + let mut ws = PolicyWorkspace::new(); + ws.set_policy("generated.json", parsed); + let mut rng = Rng(seed.wrapping_mul(7919) | 1); + let rows = cycled( + &(0..64) + .map(|_| Gen::valid_input(&mut rng)) + .collect::>(), + ); + policy( + &mut out, + "generated-policy", + format!("seed-{seed:02}"), + &ws, + &Arc::from("generated.json"), + &[], + rows, + ); + } +} diff --git a/core/engine/tests/ceiling_lists.rs b/core/engine/tests/ceiling_lists.rs new file mode 100644 index 00000000..7573be10 --- /dev/null +++ b/core/engine/tests/ceiling_lists.rs @@ -0,0 +1,791 @@ +mod support; + +use rust_decimal::Decimal; +use serde_json::{json, Value}; +use std::fs; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Instant; +use support::test_data_root; +use zen_engine::model::DecisionContent; +use zen_engine::{Decision, EvaluationOptions}; +use zen_expression::Variable; + +enum Buf { + Dec(Vec), + Text(Vec, Vec), + Bool(Vec), + Any(Vec), +} + +struct Built { + rows: usize, + paths: Vec, + bufs: Vec<(Buf, Vec)>, +} + +impl Built { + fn flatten(value: &Value, prefix: &str, out: &mut Vec<(String, Value)>) -> bool { + match value { + Value::Object(map) => map.iter().all(|(key, child)| { + !key.contains('.') + && Self::flatten( + child, + &match prefix.is_empty() { + true => key.clone(), + false => format!("{prefix}.{key}"), + }, + out, + ) + }), + Value::Null => true, + other if !prefix.is_empty() => { + out.push((prefix.to_string(), other.clone())); + true + } + _ => false, + } + } + + fn new(rows: &[Value]) -> Option { + let mut kept: Vec> = Vec::new(); + for value in rows { + let mut entries = Vec::new(); + if !Self::flatten(value, "", &mut entries) { + continue; + } + kept.push(entries); + } + let count = kept.len(); + let mut paths: Vec = Vec::new(); + let mut cells: Vec>> = Vec::new(); + for (row, entries) in kept.into_iter().enumerate() { + for (path, leaf) in entries { + let at = match paths.iter().position(|p| *p == path) { + Some(at) => at, + None => { + paths.push(path); + cells.push(vec![None; count]); + cells.len() - 1 + } + }; + cells[at][row] = Some(leaf); + } + } + let words = count.div_ceil(64); + let bufs = cells + .into_iter() + .map(|column| { + let mut valid = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if cell.is_some() { + valid[row / 64] |= 1 << (row % 64); + } + } + let present: Vec<&Value> = column.iter().flatten().collect(); + let buf = if !present.is_empty() && present.iter().all(|v| v.is_number()) { + Buf::Dec( + column + .iter() + .map(|c| match c { + Some(Value::Number(n)) => n.to_string().parse().unwrap_or_default(), + _ => Decimal::ZERO, + }) + .collect(), + ) + } else if !present.is_empty() && present.iter().all(|v| v.is_string()) { + let mut offsets = vec![0i32]; + let mut data = Vec::new(); + for cell in &column { + if let Some(Value::String(s)) = cell { + data.extend_from_slice(s.as_bytes()); + } + offsets.push(data.len() as i32); + } + Buf::Text(offsets, data) + } else if !present.is_empty() && present.iter().all(|v| v.is_boolean()) { + let mut bits = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if let Some(Value::Bool(true)) = cell { + bits[row / 64] |= 1 << (row % 64); + } + } + Buf::Bool(bits) + } else { + Buf::Any( + column + .iter() + .map(|c| { + c.as_ref() + .map_or(Variable::Null, |v| Variable::from(v.clone())) + }) + .collect(), + ) + }; + (buf, valid) + }) + .collect(); + Some(Built { + rows: count, + paths, + bufs, + }) + } + + fn columns(&self) -> zen_expression::lane::Columns<'_> { + use zen_expression::lane::{Column, Columns, Values}; + let mut columns = Columns::new(self.rows); + for (path, (buf, valid)) in self.paths.iter().zip(&self.bufs) { + let values = match buf { + Buf::Dec(v) => Values::Dec(v), + Buf::Text(offsets, data) => Values::Utf8 { offsets, data }, + Buf::Bool(bits) => Values::Bool { bits, offset: 0 }, + Buf::Any(v) => Values::Any(v), + }; + columns = columns.column(path, Column::with_validity(values, valid, 0)); + } + columns + } + + fn normalized(value: Value) -> Value { + match value { + Value::Object(map) => { + let cleaned: serde_json::Map = map + .into_iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k, Self::normalized(v))) + .filter(|(_, v)| !matches!(v, Value::Object(m) if m.is_empty())) + .collect(); + Value::Object(cleaned) + } + other => other, + } + } + + fn dec(&self, path: &str) -> Num<'_> { + let at = self.paths.iter().position(|p| p == path).unwrap(); + match &self.bufs[at] { + (Buf::Dec(v), valid) => Num { values: v, valid }, + _ => panic!("{path} not decimal"), + } + } + + fn bool(&self, path: &str) -> Flag<'_> { + let at = self.paths.iter().position(|p| p == path).unwrap(); + match &self.bufs[at] { + (Buf::Bool(bits), valid) => Flag { bits, valid }, + _ => panic!("{path} not bool"), + } + } +} + +struct Num<'a> { + values: &'a [Decimal], + valid: &'a [u64], +} + +struct Flag<'a> { + bits: &'a [u64], + valid: &'a [u64], +} + +const POW10: [i128; 29] = { + let mut p = [1i128; 29]; + let mut i = 1; + while i < 29 { + p[i] = p[i - 1] * 10; + i += 1; + } + p +}; + +impl Num<'_> { + #[inline(always)] + fn scaled(d: &Decimal, c: i64) -> (i128, i128) { + (d.mantissa(), c as i128 * POW10[d.scale() as usize]) + } + + #[inline(always)] + fn integral(d: &Decimal) -> bool { + d.scale() == 0 || d.mantissa() % POW10[d.scale() as usize] == 0 + } + + #[inline(always)] + fn small(d: &Decimal) -> Option { + match d.scale() == 0 { + true => i64::try_from(d.mantissa()).ok(), + false => None, + } + } + + fn above(&self, thresholds: [i64; N], strict: bool, out: &mut [Vec; N]) { + for (w, word) in self.values.chunks(64).enumerate() { + let mut acc = [0u64; N]; + for (i, d) in word.iter().enumerate() { + match Self::small(d) { + Some(v) => { + for k in 0..N { + let hit = if strict { + v > thresholds[k] + } else { + v >= thresholds[k] + }; + acc[k] |= (hit as u64) << i; + } + } + None => { + for k in 0..N { + let (m, c) = Self::scaled(d, thresholds[k]); + let hit = if strict { m > c } else { m >= c }; + acc[k] |= (hit as u64) << i; + } + } + } + } + for k in 0..N { + out[k][w] = acc[k] & self.valid[w]; + } + } + } + + fn below(&self, thresholds: [i64; N], out: &mut [Vec; N]) { + for (w, word) in self.values.chunks(64).enumerate() { + let mut acc = [0u64; N]; + for (i, d) in word.iter().enumerate() { + for k in 0..N { + let (m, c) = Self::scaled(d, thresholds[k]); + acc[k] |= ((m < c) as u64) << i; + } + } + for k in 0..N { + out[k][w] = acc[k] & self.valid[w]; + } + } + } + + fn fractional(&self, err: &mut [u64]) { + for (w, word) in self.values.chunks(64).enumerate() { + let mut acc = 0u64; + for (i, d) in word.iter().enumerate() { + acc |= (!Self::integral(d) as u64) << i; + } + err[w] |= acc & self.valid[w]; + } + } +} + +impl Flag<'_> { + fn truthy(&self, w: usize) -> u64 { + self.bits[w] & self.valid[w] + } +} + +struct Inputs<'a> { + rows: usize, + count: Num<'a>, + high: Flag<'a>, + variant: Flag<'a>, + words: Num<'a>, + bullets: Flag<'a>, + specs: Flag<'a>, + density: Num<'a>, + rank: Num<'a>, + stock: Num<'a>, + ship: Num<'a>, +} + +struct Preds { + c: [Vec; 4], + wc: [Vec; 4], + kd_gt: [Vec; 3], + kd_lt: [Vec; 2], + sl: [Vec; 4], + cr: [Vec; 3], +} + +struct Out { + image: Vec, + desc: Vec, + total: Vec, + category: Vec, + errors: Vec, +} + +const IMG_SCORE: [i64; 5] = [30, 25, 20, 10, 0]; +const IMG_CAT: [&str; 5] = ["excellent", "good", "average", "poor", "missing"]; +const DESC: [[i64; 4]; 5] = [ + [30, 20, 10, 10], + [25, 15, 8, 8], + [15, 10, 5, 5], + [10, 5, 3, 3], + [0, 0, 0, 0], +]; +const DESC_CAT: [&str; 5] = ["excellent", "good", "average", "poor", "missing"]; +const OVERALL: [&str; 5] = ["excellent", "good", "average", "poor", "unacceptable"]; + +impl<'a> Inputs<'a> { + fn new(built: &'a Built) -> Self { + Inputs { + rows: built.rows, + count: built.dec("listing.images.count"), + high: built.bool("listing.images.highResolution"), + variant: built.bool("listing.images.hasVariantImages"), + words: built.dec("listing.description.wordCount"), + bullets: built.bool("listing.description.hasBulletPoints"), + specs: built.bool("listing.description.hasSpecifications"), + density: built.dec("listing.description.keywordDensity"), + rank: built.dec("listing.pricing.competitiveRank"), + stock: built.dec("listing.inventory.stockLevel"), + ship: built.dec("listing.inventory.daysToShip"), + } + } + + #[inline(always)] + fn fixed(d: &Decimal) -> i128 { + let scale = d.scale() as usize; + match scale <= 8 { + true => d.mantissa() * POW10[8 - scale], + false => (d.round_dp(8)).mantissa(), + } + } + + #[inline(always)] + fn bit(words: &[u64], r: usize) -> bool { + (words[r >> 6] >> (r & 63)) & 1 == 1 + } + + fn rows(&self) -> Out { + let n = self.rows; + let errors = self.validate(); + let k = POW10[8]; + let mut image = Vec::with_capacity(n); + let mut desc = Vec::with_capacity(n); + let mut total = Vec::with_capacity(n); + let mut category = Vec::with_capacity(n); + for r in 0..n { + let has = |v: &[u64]| Self::bit(v, r); + let flag = |f: &Flag| Self::bit(f.bits, r) & Self::bit(f.valid, r); + let num = |x: &Num| has(x.valid).then(|| Self::fixed(&x.values[r])); + let count = num(&self.count); + let ge = |v: Option, c: i128| v.is_some_and(|v| v >= c * k); + let gt = |v: Option, c: i128| v.is_some_and(|v| v > c * k); + let lt = |v: Option, c: i128| v.is_some_and(|v| v < c * k); + let (hr, hv) = (flag(&self.high), flag(&self.variant)); + let a: u8 = if ge(count, 5) && hr && hv { + 0 + } else if ge(count, 3) && hr { + 1 + } else if ge(count, 2) && hr { + 2 + } else if ge(count, 1) { + 3 + } else { + 4 + }; + let (wc, kd, sl, cr) = ( + num(&self.words), + num(&self.density), + num(&self.stock), + num(&self.rank), + ); + let (bp, sp) = (flag(&self.bullets), flag(&self.specs)); + let b: u8 = + if gt(wc, 300) && bp && sp && gt(kd, 2) && lt(kd, 5) && gt(sl, 20) && lt(cr, 3) { + 0 + } else if gt(wc, 200) && bp && gt(kd, 1) && lt(kd, 6) && gt(sl, 10) && lt(cr, 5) { + 1 + } else if gt(wc, 100) && gt(kd, 0) && gt(sl, 5) && lt(cr, 10) { + 2 + } else if gt(wc, 50) && gt(sl, 0) { + 3 + } else { + 4 + }; + let d = DESC[b as usize]; + let s = IMG_SCORE[a as usize] + d[0] + d[1] + d[2] + d[3]; + image.push(a); + desc.push(b); + category.push(Self::overall(s)); + total.push(Decimal::from(s)); + } + Out { + image, + desc, + total, + category, + errors, + } + } + + #[inline(always)] + fn first(masks: &[u64], i: usize) -> u8 { + let mut code = masks.len() as u8; + for k in (0..masks.len()).rev() { + if (masks[k] >> i) & 1 == 1 { + code = k as u8; + } + } + code + } + + #[inline(always)] + fn overall(total: i64) -> u8 { + match total { + t if t >= 80 => 0, + t if t >= 60 => 1, + t if t >= 40 => 2, + t if t >= 20 => 3, + _ => 4, + } + } + + fn run(&self, decimal_total: bool) -> Out { + let errors = self.validate(); + let preds = self.predicates(); + self.select(errors, &preds, decimal_total) + } + + fn validate(&self) -> Vec { + let mut errors = vec![0u64; self.rows.div_ceil(64)]; + for column in [ + &self.count, + &self.words, + &self.rank, + &self.stock, + &self.ship, + ] { + column.fractional(&mut errors); + } + errors + } + + fn predicates(&self) -> Preds { + let words = self.rows.div_ceil(64); + let z = || vec![0u64; words]; + let mut c = [z(), z(), z(), z()]; + self.count.above([5, 3, 2, 1], false, &mut c); + let mut wc = [z(), z(), z(), z()]; + self.words.above([300, 200, 100, 50], true, &mut wc); + let mut kd_gt = [z(), z(), z()]; + self.density.above([2, 1, 0], true, &mut kd_gt); + let mut kd_lt = [z(), z()]; + self.density.below([5, 6], &mut kd_lt); + let mut sl = [z(), z(), z(), z()]; + self.stock.above([20, 10, 5, 0], true, &mut sl); + let mut cr = [z(), z(), z()]; + self.rank.below([3, 5, 10], &mut cr); + Preds { + c, + wc, + kd_gt, + kd_lt, + sl, + cr, + } + } + + fn select(&self, errors: Vec, p: &Preds, decimal_total: bool) -> Out { + let n = self.rows; + let words = n.div_ceil(64); + let Preds { + c, + wc, + kd_gt, + kd_lt, + sl, + cr, + } = p; + let mut image = vec![0u8; n]; + let mut desc = vec![0u8; n]; + let mut total = Vec::with_capacity(n); + let mut category = vec![0u8; n]; + for w in 0..words { + let (hr, hv) = (self.high.truthy(w), self.variant.truthy(w)); + let (bp, sp) = (self.bullets.truthy(w), self.specs.truthy(w)); + let img = [c[0][w] & hr & hv, c[1][w] & hr, c[2][w] & hr, c[3][w]]; + let des = [ + wc[0][w] & bp & sp & kd_gt[0][w] & kd_lt[0][w] & sl[0][w] & cr[0][w], + wc[1][w] & bp & kd_gt[1][w] & kd_lt[1][w] & sl[1][w] & cr[1][w], + wc[2][w] & kd_gt[2][w] & sl[2][w] & cr[2][w], + wc[3][w] & sl[3][w], + ]; + let base = w * 64; + let end = (base + 64).min(n); + for i in 0..end - base { + let (a, b) = (Self::first(&img, i), Self::first(&des, i)); + image[base + i] = a; + desc[base + i] = b; + let d = DESC[b as usize]; + let sum = match decimal_total { + true => { + let s = Decimal::from(IMG_SCORE[a as usize]) + + Decimal::from(d[0]) + + Decimal::from(d[1]) + + Decimal::from(d[2]) + + Decimal::from(d[3]); + category[base + i] = match s { + s if s >= Decimal::from(80) => 0, + s if s >= Decimal::from(60) => 1, + s if s >= Decimal::from(40) => 2, + s if s >= Decimal::from(20) => 3, + _ => 4, + }; + s + } + false => { + let s = IMG_SCORE[a as usize] + d[0] + d[1] + d[2] + d[3]; + category[base + i] = Self::overall(s); + Decimal::from(s) + } + }; + total.push(sum); + } + } + Out { + image, + desc, + total, + category, + errors, + } + } +} + +impl Out { + fn num(d: Decimal) -> Value { + serde_json::from_str(&d.normalize().to_string()).unwrap() + } + + fn row(&self, r: usize) -> Option { + if (self.errors[r / 64] >> (r % 64)) & 1 == 1 { + return None; + } + let (a, b) = (self.image[r] as usize, self.desc[r] as usize); + let d = DESC[b]; + Some(json!({ + "totalScore": Self::num(self.total[r]), + "overallScoreCategory": OVERALL[self.category[r] as usize], + "maximumPossibleScore": Self::num(Decimal::from(100)), + "breakdown": { + "imageQuality": { "score": Self::num(Decimal::from(IMG_SCORE[a])), "category": IMG_CAT[a] }, + "descriptionCompleteness": { "score": Self::num(Decimal::from(d[0])), "category": DESC_CAT[b] }, + "keywordOptimization": { "score": Self::num(Decimal::from(d[1])) }, + "inventoryAvailability": { "score": Self::num(Decimal::from(d[2])) }, + "pricingCompetitiveness": { "score": Self::num(Decimal::from(d[3])) }, + } + })) + } +} + +struct Fixture; + +impl Fixture { + fn load() -> (zen_engine::model::GraphContent, Vec) { + let path = PathBuf::from(test_data_root()).join("graphs/product-listing-scoring.json"); + let raw: Value = serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap(); + let DecisionContent::Graph(graph) = serde_json::from_value(raw.clone()).unwrap() else { + panic!("not a graph"); + }; + let inputs: Vec = raw["tests"] + .as_array() + .unwrap() + .iter() + .map(|t| t["input"].clone()) + .collect(); + let mut out = Vec::new(); + for base in &inputs { + out.push(base.clone()); + for (key, value) in base.as_object().unwrap() { + let mut copy = base.as_object().unwrap().clone(); + copy.remove(key); + out.push(Value::Object(copy)); + if let Value::Bool(b) = value { + let mut copy = base.as_object().unwrap().clone(); + copy.insert(key.clone(), json!(!b)); + out.push(Value::Object(copy)); + } + } + } + ((*graph).clone(), out) + } + + fn rich() -> Vec { + let mut out = Vec::new(); + let mut seed = 0x9e3779b97f4a7c15u64; + let mut next = |m: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed % m + }; + for _ in 0..400 { + let mut num = |m: u64, frac: bool| -> Value { + match next(9) { + 0 => Value::Null, + 1 if frac => json!(next(m) as f64 / 10.0), + _ => json!(next(m)), + } + }; + let count = num(8, false); + let wc = num(400, false); + let kd = num(80, true); + let cr = num(12, false); + let sl = num(30, false); + let mut b = || match next(3) { + 0 => Value::Null, + 1 => json!(true), + _ => json!(false), + }; + out.push(json!({"listing": { + "images": {"count": count, "highResolution": b(), "hasVariantImages": b()}, + "description": {"wordCount": wc, "hasBulletPoints": b(), "hasSpecifications": b(), "keywordDensity": kd}, + "pricing": {"competitiveRank": cr, "hasDiscount": b()}, + "inventory": {"stockLevel": sl, "daysToShip": 2} + }})); + } + out + } +} + +#[tokio::test] +#[ignore] +async fn ceiling_product_listing_scoring() { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let rows: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1024); + let (content, variants) = Fixture::load(); + let mut compiled = Decision::from(Arc::new(content)); + compiled.compile(); + assert!(matches!(compiled.compiled_verdict(), Some(Ok(())))); + let walker = compiled.interpreted(); + let options = EvaluationOptions::default(); + let sets: Vec<(&str, Vec)> = vec![ + ( + "harness", + (0..rows).map(|i| variants[i % 2].clone()).collect(), + ), + ("rich", { + let rich = Fixture::rich(); + (0..rows).map(|i| rich[i % rich.len()].clone()).collect() + }), + ]; + for (label, inputs) in &sets { + let built = Built::new(inputs).unwrap(); + assert_eq!(built.rows, rows); + let columns = built.columns(); + let ins = Inputs::new(&built); + let hand = ins.run(true); + let alt = ins.rows(); + let engine = compiled.evaluate_columns(&columns, options).await; + let mut mismatches = 0; + for r in 0..rows { + let want = match walker.evaluate(columns.row(r)).await { + Ok(v) => Some(Built::normalized(v.result.to_value())), + Err(_) => None, + }; + let eng = match &engine.errors[r] { + Some(_) => None, + None => Some(Built::normalized(engine.row(r).to_value())), + }; + let got = hand.row(r); + if alt.row(r) != want { + mismatches += 1; + } + if got != want || eng != want { + mismatches += 1; + if mismatches < 5 { + println!( + "row {r} {}\n walker {want:?}\n hand {got:?}\n engine {eng:?}", + columns.row(r).to_value() + ); + } + } + } + println!("{label}: parity mismatches {mismatches}/{rows}"); + assert_eq!(mismatches, 0); + + if *label == "harness" { + use zen_expression::lane::Values; + for (path, column) in &engine.columns { + let kind = match column.column().values { + Values::Dec(_) => "Dec", + Values::Scaled { .. } => "Scaled", + Values::I64(_) => "I64", + Values::Text { .. } + | Values::Utf8 { .. } + | Values::Strs(_) + | Values::LargeUtf8 { .. } => "Text", + Values::Dict { .. } => "Dict", + Values::Any(_) => "Any", + _ => "other", + }; + println!("engine output column {path}: {kind}"); + } + } + let mut phases = [f64::MAX; 3]; + for _ in 0..9 { + let ins = Inputs::new(&built); + let t = Instant::now(); + let errors = std::hint::black_box(ins.validate()); + phases[0] = phases[0].min(t.elapsed().as_nanos() as f64 / rows as f64); + let t = Instant::now(); + let preds = std::hint::black_box(ins.predicates()); + phases[1] = phases[1].min(t.elapsed().as_nanos() as f64 / rows as f64); + let t = Instant::now(); + let out = std::hint::black_box(ins.select(errors, &preds, false)); + phases[2] = phases[2].min(t.elapsed().as_nanos() as f64 / rows as f64); + drop(out); + } + println!( + "{label}: hand phases validate {:.2} predicates {:.2} select+outputs {:.2} ns/row", + phases[0], phases[1], phases[2] + ); + let mut best = [f64::MAX; 5]; + for _ in 0..9 { + let t = Instant::now(); + for c in (0..rows.min(256)).map(|r| columns.row(r)) { + let _ = walker.evaluate(c).await; + } + best[0] = best[0].min(t.elapsed().as_nanos() as f64 / rows.min(256) as f64); + let t = Instant::now(); + let out = compiled.evaluate_columns(&columns, options).await; + std::hint::black_box(&out); + drop(out); + best[1] = best[1].min(t.elapsed().as_nanos() as f64 / rows as f64); + let t = Instant::now(); + let out = Inputs::new(&built).run(true); + std::hint::black_box(&out); + drop(out); + best[2] = best[2].min(t.elapsed().as_nanos() as f64 / rows as f64); + let t = Instant::now(); + let out = Inputs::new(&built).run(false); + std::hint::black_box(&out); + drop(out); + best[3] = best[3].min(t.elapsed().as_nanos() as f64 / rows as f64); + let t = Instant::now(); + let out = Inputs::new(&built).rows(); + std::hint::black_box(&out); + drop(out); + best[4] = best[4].min(t.elapsed().as_nanos() as f64 / rows as f64); + } + println!( + "{label}: hand row-wise {:.2} ns/row ({:.0}x)", + best[4], + best[0] / best[4] + ); + println!( + "{label}: walker {:.0} ns/row | engine {:.1} ns/row ({:.1}x) | hand decimal {:.2} ns/row ({:.0}x) | hand int {:.2} ns/row ({:.0}x)", + best[0], best[1], best[0] / best[1], best[2], best[0] / best[2], best[3], best[0] / best[3] + ); + } + if let Ok(seconds) = std::env::var("BENCH_PROFILE") { + let built = Built::new(&sets[0].1).unwrap(); + let columns = built.columns(); + let until = Instant::now() + std::time::Duration::from_secs(seconds.parse().unwrap_or(5)); + while Instant::now() < until { + let _ = compiled.evaluate_columns(&columns, options).await; + } + } +} diff --git a/core/engine/tests/ceiling_switch.rs b/core/engine/tests/ceiling_switch.rs new file mode 100644 index 00000000..826878b3 --- /dev/null +++ b/core/engine/tests/ceiling_switch.rs @@ -0,0 +1,686 @@ +mod support; + +use rust_decimal::Decimal; +use serde_json::{json, Value}; +use std::hint::black_box; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Instant; +use support::test_data_root; +use zen_engine::model::{DecisionContent, GraphContent}; +use zen_engine::{Decision, EvaluationOptions}; +use zen_expression::lane::{Column, Columns, Dictionary, Values}; +use zen_expression::Variable; + +struct Fixture { + content: GraphContent, + inputs: Vec, +} + +impl Fixture { + fn load(name: &str) -> Fixture { + let path = PathBuf::from(test_data_root()).join("graphs").join(name); + let raw: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let DecisionContent::Graph(graph) = serde_json::from_value(raw.clone()).unwrap() else { + panic!("not a graph"); + }; + let inputs = raw["tests"] + .as_array() + .unwrap() + .iter() + .map(|t| t["input"].clone()) + .collect(); + Fixture { + content: (*graph).clone(), + inputs, + } + } + + fn typed_variants(&self) -> Vec { + let mut out: Vec = Vec::new(); + for base in &self.inputs { + out.push(base.clone()); + let Some(object) = base.as_object() else { + continue; + }; + for (key, value) in object { + let mut with = |replacement: Option| { + let mut copy = object.clone(); + match replacement { + Some(v) => copy.insert(key.clone(), v), + None => copy.remove(key), + }; + out.push(Value::Object(copy)); + }; + with(None); + match value { + Value::Number(n) => { + for delta in ["1", "-1", "0", "1000000", "0.5"] { + let shifted: Option = n + .to_string() + .parse::() + .ok() + .zip(delta.parse::().ok()) + .and_then(|(a, b)| a.checked_add(b)); + if let Some(v) = + shifted.and_then(|d| serde_json::from_str(&d.to_string()).ok()) + { + with(Some(v)); + } + } + } + Value::String(s) => { + with(Some(json!(""))); + with(Some(json!(format!("{s}x")))); + } + Value::Bool(b) => with(Some(json!(!b))), + _ => {} + } + } + } + out.truncate(400); + out + } +} + +enum Buf { + Dec(Vec), + Text(Vec, Vec), + Bool(Vec), + Any(Vec), +} + +struct Built { + rows: usize, + paths: Vec, + bufs: Vec<(Buf, Vec)>, +} + +impl Built { + fn flatten(value: &Value, prefix: &str, out: &mut Vec<(String, Value)>) -> bool { + match value { + Value::Object(map) => map.iter().all(|(key, child)| { + !key.contains('.') + && Self::flatten( + child, + &match prefix.is_empty() { + true => key.clone(), + false => format!("{prefix}.{key}"), + }, + out, + ) + }), + Value::Null => true, + other if !prefix.is_empty() => { + out.push((prefix.to_string(), other.clone())); + true + } + _ => false, + } + } + + fn new(rows: &[Value]) -> Option { + let conflicts = |a: &str, b: &str| { + a.strip_prefix(b).is_some_and(|r| r.starts_with('.')) + || b.strip_prefix(a).is_some_and(|r| r.starts_with('.')) + }; + let mut kept: Vec> = Vec::new(); + let mut seen: Vec = Vec::new(); + for value in rows { + let mut entries = Vec::new(); + if !Self::flatten(value, "", &mut entries) { + continue; + } + if entries + .iter() + .any(|(p, _)| seen.iter().any(|s| conflicts(p, s))) + { + continue; + } + for (p, _) in &entries { + if !seen.contains(p) { + seen.push(p.clone()); + } + } + kept.push(entries); + } + if kept.is_empty() { + return None; + } + let rows: Vec<()> = vec![(); kept.len()]; + let mut paths: Vec = Vec::new(); + let mut cells: Vec>> = Vec::new(); + for (row, entries) in kept.into_iter().enumerate() { + for (path, leaf) in entries { + let at = match paths.iter().position(|p| *p == path) { + Some(at) => at, + None => { + paths.push(path); + cells.push(vec![None; rows.len()]); + cells.len() - 1 + } + }; + cells[at][row] = Some(leaf); + } + } + let words = rows.len().div_ceil(64); + let bufs = cells + .into_iter() + .map(|column| { + let mut valid = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if cell.is_some() { + valid[row / 64] |= 1 << (row % 64); + } + } + let present: Vec<&Value> = column.iter().flatten().collect(); + let buf = if !present.is_empty() && present.iter().all(|v| v.is_number()) { + Buf::Dec( + column + .iter() + .map(|c| match c { + Some(Value::Number(n)) => n.to_string().parse().unwrap_or_default(), + _ => Decimal::ZERO, + }) + .collect(), + ) + } else if !present.is_empty() && present.iter().all(|v| v.is_string()) { + let mut offsets = vec![0i32]; + let mut data = Vec::new(); + for cell in &column { + if let Some(Value::String(s)) = cell { + data.extend_from_slice(s.as_bytes()); + } + offsets.push(data.len() as i32); + } + Buf::Text(offsets, data) + } else if !present.is_empty() && present.iter().all(|v| v.is_boolean()) { + let mut bits = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if let Some(Value::Bool(true)) = cell { + bits[row / 64] |= 1 << (row % 64); + } + } + Buf::Bool(bits) + } else { + Buf::Any( + column + .iter() + .map(|c| { + c.as_ref() + .map_or(Variable::Null, |v| Variable::from(v.clone())) + }) + .collect(), + ) + }; + (buf, valid) + }) + .collect(); + Some(Built { + rows: rows.len(), + paths, + bufs, + }) + } + + fn columns(&self) -> Columns<'_> { + let mut columns = Columns::new(self.rows); + for (path, (buf, valid)) in self.paths.iter().zip(&self.bufs) { + let values = match buf { + Buf::Dec(v) => Values::Dec(v), + Buf::Text(offsets, data) => Values::Utf8 { offsets, data }, + Buf::Bool(bits) => Values::Bool { bits, offset: 0 }, + Buf::Any(v) => Values::Any(v), + }; + columns = columns.column(path, Column::with_validity(values, valid, 0)); + } + columns + } + + fn normalized(value: Value) -> Value { + match value { + Value::Object(map) => { + let cleaned: serde_json::Map = map + .into_iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k, Self::normalized(v))) + .filter(|(_, v)| !matches!(v, Value::Object(m) if m.is_empty())) + .collect(); + Value::Object(cleaned) + } + other => other, + } + } +} + +const GREEN: i32 = 0; +const AMBER: i32 = 1; +const RED: i32 = 2; +const FLAG_OFFSETS: [i32; 4] = [0, 5, 10, 13]; +const FLAG_DATA: &str = "greenamberred"; + +struct Thresholds { + llc_green: Decimal, + llc_amber: Decimal, + corp_green: Decimal, + corp_amber: Decimal, +} + +enum Arrays<'a> { + Any(&'a [Variable]), + Lens(&'a [u32]), +} + +struct Inputs<'a> { + rows: usize, + kind: (&'a [i32], &'a [u8], &'a [u64]), + turnover: (&'a [Decimal], &'a [u64]), + secretaries: (Arrays<'a>, &'a [u64]), + directors: (Arrays<'a>, &'a [u64]), +} + +#[derive(Default)] +struct HandOutput { + secretaries: Vec, + secretaries_valid: Vec, + directors: Vec, + directors_valid: Vec, + turnover: Vec, + turnover_valid: Vec, + pass: Vec, + errors: Vec, +} + +struct Hand; + +impl Hand { + fn thresholds() -> Thresholds { + Thresholds { + llc_green: Decimal::from(1_000_000), + llc_amber: Decimal::from(200_000), + corp_green: Decimal::from(10_000_000), + corp_amber: Decimal::from(1_000_000), + } + } + + #[inline(always)] + fn bit(bits: &[u64], row: usize) -> bool { + bits[row >> 6] >> (row & 63) & 1 == 1 + } + + #[inline(always)] + fn len(arrays: &Arrays, row: usize) -> Option { + match arrays { + Arrays::Lens(lens) => Some(lens[row] as i64), + Arrays::Any(values) => match &values[row] { + Variable::Array(a) => Some(a.borrow().len() as i64), + Variable::String(s) => Some(s.chars().count() as i64), + _ => None, + }, + } + } + + #[inline(always)] + fn not_null(arrays: &Arrays, valid: &[u64], row: usize) -> bool { + Self::bit(valid, row) + && match arrays { + Arrays::Lens(_) => true, + Arrays::Any(values) => !matches!(values[row], Variable::Null), + } + } + + fn run(input: &Inputs, t: &Thresholds, out: &mut HandOutput) { + let rows = input.rows; + let words = rows.div_ceil(64); + out.secretaries.resize(rows, -1); + out.directors.resize(rows, -1); + out.turnover.resize(rows, -1); + for v in [ + &mut out.secretaries_valid, + &mut out.directors_valid, + &mut out.turnover_valid, + &mut out.pass, + &mut out.errors, + ] { + v.clear(); + v.resize(words, 0); + } + let (offsets, data, kind_valid) = input.kind; + let (turnover, turnover_valid) = input.turnover; + let (secretaries, sec_valid) = (&input.secretaries.0, input.secretaries.1); + let (directors, dir_valid) = (&input.directors.0, input.directors.1); + for w in 0..words { + let base = w * 64; + let width = (rows - base).min(64); + let mut llc = 0u64; + let mut corp = 0u64; + let kv = kind_valid[w]; + for i in 0..width { + let row = base + i; + let (a, b) = (offsets[row] as usize, offsets[row + 1] as usize); + let s = &data[a..b]; + llc |= (((kv >> i & 1 == 1) & (s == b"LLC")) as u64) << i; + corp |= (((kv >> i & 1 == 1) & (s == b"Corporation")) as u64) << i; + } + out.pass[w] = !(llc | corp) + & if width == 64 { + u64::MAX + } else { + (1u64 << width) - 1 + }; + let routed = llc | corp; + out.turnover_valid[w] = routed; + if P & 1 == 0 { + continue; + } + let tv = turnover_valid[w]; + let mut m = routed; + while m != 0 { + let i = m.trailing_zeros() as usize; + m &= m - 1; + let row = base + i; + let (green, amber) = match llc >> i & 1 == 1 { + true => (&t.llc_green, &t.llc_amber), + false => (&t.corp_green, &t.corp_amber), + }; + out.turnover[row] = match tv >> i & 1 == 1 { + false => RED, + true => { + let v = &turnover[row]; + match (v > green, v >= amber && v <= green) { + (true, _) => GREEN, + (_, true) => AMBER, + _ => RED, + } + } + }; + } + if P & 2 == 0 { + continue; + } + let mut sec = 0u64; + let mut m = routed; + while m != 0 { + let i = m.trailing_zeros() as usize; + m &= m - 1; + let row = base + i; + if !Self::not_null(secretaries, sec_valid, row) { + continue; + } + sec |= 1 << i; + let Some(n) = Self::len(secretaries, row) else { + out.errors[w] |= 1 << i; + continue; + }; + out.secretaries[row] = match (llc >> i & 1 == 1, n > 2, n > 1) { + (_, true, _) => GREEN, + (true, _, true) => AMBER, + _ => RED, + }; + } + out.secretaries_valid[w] = sec; + let mut dir = 0u64; + let mut m = llc; + while m != 0 { + let i = m.trailing_zeros() as usize; + m &= m - 1; + let row = base + i; + if !Self::not_null(directors, dir_valid, row) { + continue; + } + dir |= 1 << i; + let Some(n) = Self::len(directors, row) else { + out.errors[w] |= 1 << i; + continue; + }; + out.directors[row] = if n > 2 { GREEN } else { RED }; + } + out.directors_valid[w] = dir; + } + } +} + +struct Inputs2 { + sec_lens: Vec, + dir_lens: Vec, +} + +#[tokio::test] +#[ignore] +async fn ceiling_multi_switch() { + let fixture = Fixture::load("multi-switch.json"); + let rows: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1024); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + assert!(matches!(compiled.compiled_verdict(), Some(Ok(())))); + let walker = compiled.interpreted(); + let variants = fixture.typed_variants(); + let inputs: Vec = (0..rows) + .map(|i| variants[i % variants.len()].clone()) + .collect(); + let built = Built::new(&inputs).unwrap(); + let columns = built.columns(); + println!("paths {:?}", built.paths); + let find = |name: &str| built.paths.iter().position(|p| p == name).unwrap(); + let (kind_offsets, kind_data, kind_valid) = match &built.bufs[find("company.type")] { + (Buf::Text(o, d), v) => (o.as_slice(), d.as_slice(), v.as_slice()), + _ => panic!("type"), + }; + let (turnover, turnover_valid) = match &built.bufs[find("company.turnover")] { + (Buf::Dec(d), v) => (d.as_slice(), v.as_slice()), + _ => panic!("turnover"), + }; + let any = |name: &str| match &built.bufs[find(name)] { + (Buf::Any(a), v) => (a.as_slice(), v.as_slice()), + _ => panic!("{name}"), + }; + let (sec_any, sec_valid) = any("company.secretaries"); + let (dir_any, dir_valid) = any("company.directors"); + let lens = |values: &[Variable]| -> Vec { + values + .iter() + .map(|v| match v { + Variable::Array(a) => a.borrow().len() as u32, + _ => 0, + }) + .collect() + }; + let typed_lists = Inputs2 { + sec_lens: lens(sec_any), + dir_lens: lens(dir_any), + }; + let input_any = Inputs { + rows: built.rows, + kind: (kind_offsets, kind_data, kind_valid), + turnover: (turnover, turnover_valid), + secretaries: (Arrays::Any(sec_any), sec_valid), + directors: (Arrays::Any(dir_any), dir_valid), + }; + let input_list = Inputs { + rows: built.rows, + kind: (kind_offsets, kind_data, kind_valid), + turnover: (turnover, turnover_valid), + secretaries: (Arrays::Lens(&typed_lists.sec_lens), sec_valid), + directors: (Arrays::Lens(&typed_lists.dir_lens), dir_valid), + }; + let thresholds = Hand::thresholds(); + let mut out = HandOutput::default(); + Hand::run::<3>(&input_any, &thresholds, &mut out); + + let flag_dict = Dictionary::Text { + offsets: &FLAG_OFFSETS, + data: FLAG_DATA, + }; + let out_columns: Vec<(&str, Column)> = { + let mut cols: Vec<(&str, Column)> = Vec::new(); + cols.push(( + "flag.turnover", + Column::with_validity( + Values::Dict { + keys: &out.turnover, + values: flag_dict, + }, + &out.turnover_valid, + 0, + ), + )); + cols.push(( + "flag.secretaries", + Column::with_validity( + Values::Dict { + keys: &out.secretaries, + values: flag_dict, + }, + &out.secretaries_valid, + 0, + ), + )); + cols.push(( + "flag.directors", + Column::with_validity( + Values::Dict { + keys: &out.directors, + values: flag_dict, + }, + &out.directors_valid, + 0, + ), + )); + cols + }; + let pass_valid: Vec> = built + .bufs + .iter() + .map(|(_, valid)| valid.iter().zip(&out.pass).map(|(a, b)| a & b).collect()) + .collect(); + let pass_columns: Vec<(&str, Column)> = columns + .columns + .iter() + .zip(&pass_valid) + .map(|((path, column), valid)| (*path, Column::with_validity(column.values, valid, 0))) + .collect(); + let hand_row = |row: usize| -> Variable { + let object = Variable::empty_object(); + for (path, column) in pass_columns.iter().chain(&out_columns) { + if column.valid(row) { + object.dot_insert(path, column.variable(row)); + } + } + object + }; + + let engine_out = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + let mut mismatches = 0usize; + let mut order_mismatches = 0usize; + for row in 0..built.rows { + let want = walker.evaluate(columns.row(row)).await.unwrap().result; + assert!(out.errors[row / 64] >> (row % 64) & 1 == 0); + let got = hand_row(row); + let engine = engine_out.row(row); + if got.to_value() != want.to_value() { + mismatches += 1; + if mismatches < 5 { + println!( + "row {row}: walker {} hand {}", + want.to_value(), + got.to_value() + ); + } + } + if serde_json::to_string(&got).unwrap() != serde_json::to_string(&want).unwrap() { + order_mismatches += 1; + if order_mismatches < 3 { + println!( + "order row {row}: walker {} hand {}", + serde_json::to_string(&want).unwrap(), + serde_json::to_string(&got).unwrap() + ); + } + } + assert!(engine_out.errors[row].is_none()); + assert_eq!( + Built::normalized(engine.to_value()), + Built::normalized(want.to_value()), + "engine row {row}" + ); + } + println!( + "parity: {} rows, {mismatches} value mismatches, {order_mismatches} key-order mismatches", + built.rows + ); + assert_eq!(mismatches, 0); + + let n = built.rows as f64; + let reps = 2000; + let mut best = [f64::MAX; 4]; + let options = EvaluationOptions::default(); + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..reps { + Hand::run::<3>(black_box(&input_any), &thresholds, &mut out); + black_box(&out); + } + best[0] = best[0].min(start.elapsed().as_nanos() as f64 / (n * reps as f64)); + let start = Instant::now(); + for _ in 0..reps { + Hand::run::<3>(black_box(&input_list), &thresholds, &mut out); + black_box(&out); + } + best[1] = best[1].min(start.elapsed().as_nanos() as f64 / (n * reps as f64)); + let start = Instant::now(); + for _ in 0..reps { + let mut fresh = HandOutput::default(); + Hand::run::<3>(black_box(&input_any), &thresholds, &mut fresh); + let pass: Vec> = built + .bufs + .iter() + .map(|(_, valid)| valid.iter().zip(&fresh.pass).map(|(a, b)| a & b).collect()) + .collect(); + black_box((&fresh, &pass)); + } + best[2] = best[2].min(start.elapsed().as_nanos() as f64 / (n * reps as f64)); + let start = Instant::now(); + for _ in 0..50 { + black_box( + compiled + .evaluate_columns(black_box(&columns), options) + .await, + ); + } + best[3] = best[3].min(start.elapsed().as_nanos() as f64 / (n * 50.0)); + } + let mut phases = [f64::MAX; 2]; + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..reps { + Hand::run::<0>(black_box(&input_any), &thresholds, &mut out); + black_box(&out); + } + phases[0] = phases[0].min(start.elapsed().as_nanos() as f64 / (n * reps as f64)); + let start = Instant::now(); + for _ in 0..reps { + Hand::run::<1>(black_box(&input_any), &thresholds, &mut out); + black_box(&out); + } + phases[1] = phases[1].min(start.elapsed().as_nanos() as f64 / (n * reps as f64)); + } + println!( + "phases: classify+init {:.2} | +turnover tables {:.2} | +len tables (full) {:.2} ns/row", + phases[0], phases[1], best[0] + ); + println!( + "hand (Any arrays, reused buffers) {:.2} ns/row | hand (typed list lens) {:.2} ns/row | hand (fresh alloc + pass validity) {:.2} ns/row | evaluate_columns {:.1} ns/row", + best[0], best[1], best[2], best[3] + ); + if let Ok(seconds) = std::env::var("BENCH_PROFILE") { + let until = Instant::now() + std::time::Duration::from_secs(seconds.parse().unwrap_or(5)); + while Instant::now() < until { + black_box(compiled.evaluate_columns(&columns, options).await); + } + } +} diff --git a/core/engine/tests/ceiling_table.rs b/core/engine/tests/ceiling_table.rs new file mode 100644 index 00000000..c4991564 --- /dev/null +++ b/core/engine/tests/ceiling_table.rs @@ -0,0 +1,1000 @@ +use rust_decimal::{Decimal, RoundingStrategy}; +use serde_json::{json, Value}; +use std::str::FromStr; +use std::sync::Arc; +use zen_engine::model::{DecisionContent, GraphContent}; +use zen_engine::{Decision, EvaluationOptions}; +use zen_expression::Variable; + +enum Buf { + Dec(Vec), + Text(Vec, Vec), + Bool(Vec), + Any(Vec), +} + +struct Built { + rows: usize, + paths: Vec, + bufs: Vec<(Buf, Vec)>, +} + +impl Built { + fn flatten(value: &Value, prefix: &str, out: &mut Vec<(String, Value)>) -> bool { + match value { + Value::Object(map) => map.iter().all(|(key, child)| { + !key.contains('.') + && Self::flatten( + child, + &match prefix.is_empty() { + true => key.clone(), + false => format!("{prefix}.{key}"), + }, + out, + ) + }), + Value::Null => true, + other if !prefix.is_empty() => { + out.push((prefix.to_string(), other.clone())); + true + } + _ => false, + } + } + + fn new(rows: &[Value]) -> Option { + let conflicts = |a: &str, b: &str| { + a.strip_prefix(b).is_some_and(|r| r.starts_with('.')) + || b.strip_prefix(a).is_some_and(|r| r.starts_with('.')) + }; + let mut kept: Vec> = Vec::new(); + let mut seen: Vec = Vec::new(); + for value in rows { + let mut entries = Vec::new(); + if !Self::flatten(value, "", &mut entries) { + continue; + } + if entries + .iter() + .any(|(p, _)| seen.iter().any(|s| conflicts(p, s))) + { + continue; + } + for (p, _) in &entries { + if !seen.contains(p) { + seen.push(p.clone()); + } + } + kept.push(entries); + } + if kept.is_empty() { + return None; + } + let rows: Vec<()> = vec![(); kept.len()]; + let mut paths: Vec = Vec::new(); + let mut cells: Vec>> = Vec::new(); + for (row, entries) in kept.into_iter().enumerate() { + for (path, leaf) in entries { + let at = match paths.iter().position(|p| *p == path) { + Some(at) => at, + None => { + paths.push(path); + cells.push(vec![None; rows.len()]); + cells.len() - 1 + } + }; + cells[at][row] = Some(leaf); + } + } + let words = rows.len().div_ceil(64); + let bufs = cells + .into_iter() + .map(|column| { + let mut valid = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if cell.is_some() { + valid[row / 64] |= 1 << (row % 64); + } + } + let present: Vec<&Value> = column.iter().flatten().collect(); + let buf = if !present.is_empty() && present.iter().all(|v| v.is_number()) { + Buf::Dec( + column + .iter() + .map(|c| match c { + Some(Value::Number(n)) => n.to_string().parse().unwrap_or_default(), + _ => Decimal::ZERO, + }) + .collect(), + ) + } else if !present.is_empty() && present.iter().all(|v| v.is_string()) { + let mut offsets = vec![0i32]; + let mut data = Vec::new(); + for cell in &column { + if let Some(Value::String(s)) = cell { + data.extend_from_slice(s.as_bytes()); + } + offsets.push(data.len() as i32); + } + Buf::Text(offsets, data) + } else if !present.is_empty() && present.iter().all(|v| v.is_boolean()) { + let mut bits = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if let Some(Value::Bool(true)) = cell { + bits[row / 64] |= 1 << (row % 64); + } + } + Buf::Bool(bits) + } else { + Buf::Any( + column + .iter() + .map(|c| { + c.as_ref() + .map_or(Variable::Null, |v| Variable::from(v.clone())) + }) + .collect(), + ) + }; + (buf, valid) + }) + .collect(); + Some(Built { + rows: rows.len(), + paths, + bufs, + }) + } + + fn columns(&self) -> zen_expression::lane::Columns<'_> { + use zen_expression::lane::{Column, Columns, Values}; + let mut columns = Columns::new(self.rows); + for (path, (buf, valid)) in self.paths.iter().zip(&self.bufs) { + let values = match buf { + Buf::Dec(v) => Values::Dec(v), + Buf::Text(offsets, data) => Values::Utf8 { offsets, data }, + Buf::Bool(bits) => Values::Bool { bits, offset: 0 }, + Buf::Any(v) => Values::Any(v), + }; + columns = columns.column(path, Column::with_validity(values, valid, 0)); + } + columns + } + + fn normalized(value: Value) -> Value { + match value { + Value::Object(map) => { + let cleaned: serde_json::Map = map + .into_iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k, Self::normalized(v))) + .filter(|(_, v)| !matches!(v, Value::Object(m) if m.is_empty())) + .collect(); + Value::Object(cleaned) + } + other => other, + } + } + + fn at(&self, path: &str) -> Option<&(Buf, Vec)> { + self.paths + .iter() + .position(|p| p == path) + .map(|i| &self.bufs[i]) + } +} + +struct Fixture { + content: GraphContent, + inputs: Vec, +} + +impl Fixture { + fn load() -> Fixture { + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../test-data/graphs/traffic-violation-penalty-calculator.json" + ); + let raw: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let DecisionContent::Graph(graph) = serde_json::from_value(raw.clone()).unwrap() else { + panic!("graph expected"); + }; + let inputs = raw["tests"] + .as_array() + .unwrap() + .iter() + .map(|t| t["input"].clone()) + .collect(); + Fixture { + content: (*graph).clone(), + inputs, + } + } + + fn typed_variants(&self) -> Vec { + let mut out: Vec = Vec::new(); + for base in &self.inputs { + out.push(base.clone()); + let Some(object) = base.as_object() else { + continue; + }; + for (key, value) in object { + let mut with = |replacement: Option| { + let mut copy = object.clone(); + match replacement { + Some(v) => copy.insert(key.clone(), v), + None => copy.remove(key), + }; + out.push(Value::Object(copy)); + }; + with(None); + match value { + Value::Number(n) => { + for delta in ["1", "-1", "0", "1000000", "0.5"] { + let shifted: Option = n + .to_string() + .parse::() + .ok() + .zip(delta.parse::().ok()) + .and_then(|(a, b)| a.checked_add(b)); + if let Some(v) = + shifted.and_then(|d| serde_json::from_str(&d.to_string()).ok()) + { + with(Some(v)); + } + } + } + Value::String(s) => { + with(Some(json!(""))); + with(Some(json!(format!("{s}x")))); + } + Value::Bool(b) => with(Some(json!(!b))), + _ => {} + } + } + } + out.truncate(400); + out + } + + fn random(rows: usize) -> Vec { + let types = [ + "speeding", + "running_red_light", + "illegal_turn", + "dui", + "driving_without_license", + "reckless_driving", + "parking", + "", + "speedingx", + "Speeding", + ]; + let speeds = [ + "10", "15", "15.5", "16", "30", "30.01", "31", "0", "-1", "45.25", + ]; + let prevs = ["0", "1", "2", "2.5", "3", "3.5", "4", "10"]; + let mut state: u64 = 0x9E3779B97F4A7C15; + let mut next = move |n: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % n as u64) as usize + }; + (0..rows) + .map(|_| { + let mut violation = serde_json::Map::new(); + if next(12) > 0 { + violation.insert("type".into(), json!(types[next(types.len())])); + } + if next(8) > 0 { + violation.insert( + "speed_over_limit".into(), + serde_json::from_str(speeds[next(speeds.len())]).unwrap(), + ); + } + if next(5) > 0 { + violation.insert("in_school_zone".into(), json!(next(2) == 1)); + } + if next(3) > 0 { + violation.insert("location".into(), json!("Main St & 5th Ave")); + } + let mut driver = serde_json::Map::new(); + if next(6) > 0 { + driver.insert( + "previous_violations".into(), + serde_json::from_str(prevs[next(prevs.len())]).unwrap(), + ); + } + if next(2) > 0 { + driver.insert("license_number".into(), json!(format!("DL{}", next(1000)))); + } + let mut root = serde_json::Map::new(); + if next(15) > 0 { + root.insert("violation".into(), Value::Object(violation)); + } + if next(15) > 0 { + root.insert("driver".into(), Value::Object(driver)); + } + Value::Object(root) + }) + .collect() + } +} + +const SEVERITY: [&str; 3] = ["severe", "moderate", "minor"]; +const RULE_SEVERITY: [u8; 9] = [0, 1, 2, 1, 2, 0, 1, 0, 2]; +const RULE_POINTS: [i64; 9] = [4, 3, 2, 3, 2, 6, 3, 5, 1]; +const RULE_FINE: [i64; 9] = [300, 150, 75, 200, 100, 500, 250, 350, 50]; +const FINE_FACTOR: [&str; 6] = ["2", "1.5", "1.25", "1.2", "1.1", ""]; +const POINTS_FACTOR: [&str; 6] = ["1.5", "", "1.25", "", "", ""]; +const RISK: [&str; 3] = ["high", "medium", "low"]; +const RISK_RULE: [(u8, i64); 8] = [ + (0, 15), + (1, 15), + (1, 30), + (1, 45), + (2, 15), + (2, 30), + (2, 45), + (2, 45), +]; +const COMBOS: usize = 9 * 3 * 2; + +struct Inputs<'a> { + kind: (&'a [i32], &'a [u8], &'a [u64]), + speed: (&'a [Decimal], &'a [u64]), + school: (&'a [u64], &'a [u64]), + prev: (&'a [Decimal], &'a [u64]), +} + +impl<'a> Inputs<'a> { + const EMPTY_WORDS: &'static [u64] = &[]; + + fn of(built: &'a Built) -> Inputs<'a> { + let text = |path| match built.at(path) { + Some((Buf::Text(o, d), v)) => (o.as_slice(), d.as_slice(), v.as_slice()), + None => (&[][..], &[][..], Self::EMPTY_WORDS), + _ => panic!("{path} not text"), + }; + let dec = |path| match built.at(path) { + Some((Buf::Dec(d), v)) => (d.as_slice(), v.as_slice()), + None => (&[][..], Self::EMPTY_WORDS), + _ => panic!("{path} not decimal"), + }; + let boolean = |path| match built.at(path) { + Some((Buf::Bool(b), v)) => (b.as_slice(), v.as_slice()), + None => (Self::EMPTY_WORDS, Self::EMPTY_WORDS), + _ => panic!("{path} not bool"), + }; + Inputs { + kind: text("violation.type"), + speed: dec("violation.speed_over_limit"), + school: boolean("violation.in_school_zone"), + prev: dec("driver.previous_violations"), + } + } + + #[inline(always)] + fn bit(words: &[u64], row: usize) -> bool { + words + .get(row >> 6) + .is_some_and(|w| w >> (row & 63) & 1 == 1) + } + + #[inline(always)] + fn rule1(&self, row: usize, d15: Decimal, d30: Decimal) -> u8 { + let (offsets, data, valid) = self.kind; + if !Self::bit(valid, row) { + return 8; + } + let bytes = &data[offsets[row] as usize..offsets[row + 1] as usize]; + match bytes { + b"speeding" => { + let (speed, valid) = self.speed; + match Self::bit(valid, row) { + true if speed[row] > d30 => 0, + true if speed[row] > d15 => 1, + _ => 2, + } + } + b"running_red_light" => 3, + b"illegal_turn" => 4, + b"dui" => 5, + b"driving_without_license" => 6, + b"reckless_driving" => 7, + _ => 8, + } + } + + #[inline(always)] + fn above(value: &Decimal, limits: &[i128; 29]) -> bool { + value.mantissa() > limits[value.scale() as usize] + } + + fn limits(c: i64) -> [i128; 29] { + let mut out = [0i128; 29]; + let mut pow = 1i128; + for slot in out.iter_mut() { + *slot = c as i128 * pow; + pow = pow.saturating_mul(10); + } + out + } + + #[inline(always)] + fn word(bytes: &[u8], at: usize) -> u64 { + bytes + .get(at..at + 8) + .and_then(|b| b.try_into().ok()) + .map_or(0, u64::from_le_bytes) + } + + #[inline(always)] + fn kind_fast(&self, row: usize) -> u8 { + let (offsets, data, valid) = self.kind; + if !Self::bit(valid, row) { + return 8; + } + let (from, to) = (offsets[row] as usize, offsets[row + 1] as usize); + let bytes = &data[from..to]; + let lit = |b: &[u8], at: usize| Self::word(b, at); + match bytes.len() { + 8 => match Self::word(bytes, 0) == lit(b"speeding", 0) { + true => 0, + false => 8, + }, + 17 if Self::word(bytes, 0) == lit(b"running_red_light", 0) + && Self::word(bytes, 8) == lit(b"running_red_light", 8) + && bytes[16] == b't' => + { + 3 + } + 12 if Self::word(bytes, 0) == lit(b"illegal_turn", 0) + && Self::word(bytes, 4) == lit(b"illegal_turn", 4) => + { + 4 + } + 3 if bytes == b"dui" => 5, + 23 if Self::word(bytes, 0) == lit(b"driving_without_license", 0) + && Self::word(bytes, 8) == lit(b"driving_without_license", 8) + && Self::word(bytes, 15) == lit(b"driving_without_license", 15) => + { + 6 + } + 16 if Self::word(bytes, 0) == lit(b"reckless_driving", 0) + && Self::word(bytes, 8) == lit(b"reckless_driving", 8) => + { + 7 + } + _ => 8, + } + } + + #[inline(always)] + fn rule1_fast(&self, row: usize, l15: &[i128; 29], l30: &[i128; 29]) -> u8 { + match self.kind_fast(row) { + 0 => { + let (speed, valid) = self.speed; + match Self::bit(valid, row) { + true if Self::above(&speed[row], l30) => 0, + true if Self::above(&speed[row], l15) => 1, + _ => 2, + } + } + other => other, + } + } + + #[inline(always)] + fn prev_fast(&self, row: usize, l2: &[i128; 29], l3: &[i128; 29]) -> u8 { + let (prev, valid) = self.prev; + match Self::bit(valid, row) { + true if Self::above(&prev[row], l3) => 2, + true if Self::above(&prev[row], l2) => 1, + _ => 0, + } + } + + #[inline(always)] + fn prev_class(&self, row: usize, d2: Decimal, d3: Decimal) -> u8 { + let (prev, valid) = self.prev; + match Self::bit(valid, row) { + true if prev[row] > d3 => 2, + true if prev[row] > d2 => 1, + _ => 0, + } + } + + #[inline(always)] + fn school(&self, row: usize) -> u8 { + (Self::bit(self.school.1, row) & Self::bit(self.school.0, row)) as u8 + } +} + +struct Rules; + +impl Rules { + fn rule2(severity: u8, prev: u8, school: u8) -> u8 { + match (severity, prev, school) { + (0, 1 | 2, 1) => 0, + (0, _, _) => 1, + (1, 1 | 2, _) => 2, + (1, _, 1) => 3, + (2, 2, _) => 4, + _ => 5, + } + } + + fn factor(text: &str) -> Option { + (!text.is_empty()).then(|| Decimal::from_str(text).unwrap()) + } + + fn finals(r1: usize, r2: usize) -> (Decimal, Decimal) { + let round = + |d: Decimal| d.round_dp_with_strategy(0, RoundingStrategy::MidpointAwayFromZero); + let fine = Decimal::from(RULE_FINE[r1]); + let points = Decimal::from(RULE_POINTS[r1]); + let fine = Self::factor(FINE_FACTOR[r2]).map_or(fine, |f| fine * f); + let points = Self::factor(POINTS_FACTOR[r2]).map_or(points, |f| points * f); + (round(fine), round(points)) + } + + fn rule3(points: Decimal, severity: u8) -> u8 { + let (d3, d5) = (Decimal::from(3), Decimal::from(5)); + match severity { + 0 if points >= d5 => 0, + 0 if points >= d3 => 1, + 1 if points >= d3 => 2, + 2 if points >= d3 => 3, + 0 => 4, + 1 => 5, + 2 => 6, + _ => 7, + } + } +} + +struct Entry { + r1: u8, + r2: u8, + r3: u8, + fine: Decimal, + points: Decimal, +} + +struct Folded { + entries: Vec, + d2: Decimal, + d3: Decimal, + d15: Decimal, + d30: Decimal, +} + +impl Folded { + fn new() -> Folded { + let entries = (0..COMBOS) + .map(|combo| { + let (r1, prev, school) = (combo / 6, (combo / 2) % 3, combo % 2); + let r2 = Rules::rule2(RULE_SEVERITY[r1], prev as u8, school as u8); + let (fine, points) = Rules::finals(r1, r2 as usize); + Entry { + r1: r1 as u8, + r2, + r3: Rules::rule3(points, RULE_SEVERITY[r1]), + fine, + points, + } + }) + .collect(); + Folded { + entries, + d2: Decimal::from(2), + d3: Decimal::from(3), + d15: Decimal::from(15), + d30: Decimal::from(30), + } + } + + fn run(&self, inputs: &Inputs, rows: usize, codes: &mut Vec) { + codes.clear(); + codes.extend((0..rows).map(|row| { + let r1 = inputs.rule1(row, self.d15, self.d30); + let prev = inputs.prev_class(row, self.d2, self.d3); + r1 * 6 + prev * 2 + inputs.school(row) + })); + } + + fn run_fast( + &self, + inputs: &Inputs, + rows: usize, + codes: &mut Vec, + limits: &[[i128; 29]; 4], + ) { + codes.clear(); + codes.extend((0..rows).map(|row| { + let r1 = inputs.rule1_fast(row, &limits[1], &limits[2]); + let prev = inputs.prev_fast(row, &limits[0], &limits[3]); + r1 * 6 + prev * 2 + inputs.school(row) + })); + } + + fn assessment(entry: &Entry) -> Vec<(&'static str, Variable)> { + let r1 = entry.r1 as usize; + let (risk, days) = RISK_RULE[entry.r3 as usize]; + vec![ + ( + "assessment.severity", + Variable::String(SEVERITY[RULE_SEVERITY[r1] as usize].into()), + ), + ( + "assessment.base_points", + Variable::Number(Decimal::from(RULE_POINTS[r1])), + ), + ( + "assessment.base_fine", + Variable::Number(Decimal::from(RULE_FINE[r1])), + ), + ("assessment.final_fine", Variable::Number(entry.fine)), + ("assessment.final_points", Variable::Number(entry.points)), + ( + "assessment.license_suspension_recommended", + Variable::Bool(entry.r2 == 0), + ), + ( + "assessment.risk_level", + Variable::String(RISK[risk as usize].into()), + ), + ( + "assessment.payment_deadline_days", + Variable::Number(Decimal::from(days)), + ), + ] + } + + fn row(&self, input: Variable, code: u8) -> Variable { + for (path, value) in Self::assessment(&self.entries[code as usize]) { + input.dot_insert(path, value); + } + input + } +} + +#[derive(Default)] +struct Staged { + r1: Vec, + r2: Vec, + r3: Vec, + fine: Vec, + points: Vec, +} + +impl Staged { + fn run(&mut self, folded: &Folded, inputs: &Inputs, rows: usize) { + let round = + |d: Decimal| d.round_dp_with_strategy(0, RoundingStrategy::MidpointAwayFromZero); + let fine_factor: Vec> = + FINE_FACTOR.iter().map(|f| Rules::factor(f)).collect(); + let points_factor: Vec> = + POINTS_FACTOR.iter().map(|f| Rules::factor(f)).collect(); + let (d3, d5) = (folded.d3, Decimal::from(5)); + self.r1.clear(); + self.r1 + .extend((0..rows).map(|row| inputs.rule1(row, folded.d15, folded.d30))); + self.r2.clear(); + self.r2.extend(self.r1.iter().enumerate().map(|(row, &r1)| { + Rules::rule2( + RULE_SEVERITY[r1 as usize], + inputs.prev_class(row, folded.d2, folded.d3), + inputs.school(row), + ) + })); + self.fine.clear(); + self.points.clear(); + for (&r1, &r2) in self.r1.iter().zip(&self.r2) { + let fine = Decimal::from(RULE_FINE[r1 as usize]); + let points = Decimal::from(RULE_POINTS[r1 as usize]); + self.fine + .push(round(fine_factor[r2 as usize].map_or(fine, |f| fine * f))); + self.points.push(round( + points_factor[r2 as usize].map_or(points, |f| points * f), + )); + } + self.r3.clear(); + self.r3.extend( + self.r1.iter().zip(&self.points).map(|(&r1, &points)| { + match RULE_SEVERITY[r1 as usize] { + 0 if points >= d5 => 0, + 0 if points >= d3 => 1, + 1 if points >= d3 => 2, + 2 if points >= d3 => 3, + 0 => 4, + 1 => 5, + _ => 6, + } + }), + ); + } + + fn row(&self, input: Variable, row: usize) -> Variable { + let entry = Entry { + r1: self.r1[row], + r2: self.r2[row], + r3: self.r3[row], + fine: self.fine[row], + points: self.points[row], + }; + for (path, value) in Folded::assessment(&entry) { + input.dot_insert(path, value); + } + input + } +} + +#[derive(Default)] +struct Scaled { + r1: Vec, + r2: Vec, + r3: Vec, + fine: Vec, + points: Vec, +} + +impl Scaled { + const FINE: [(i64, u32); 6] = [(2, 0), (15, 1), (125, 2), (12, 1), (11, 1), (1, 0)]; + const POINTS: [(i64, u32); 6] = [(15, 1), (1, 0), (125, 2), (1, 0), (1, 0), (1, 0)]; + + #[inline(always)] + fn rounded(value: i64, (factor, scale): (i64, u32)) -> i64 { + let m = value * factor; + let pow = 10i64.pow(scale); + let (q, r) = (m / pow, m % pow); + match 2 * r.abs() >= pow && pow > 1 { + true => q + m.signum(), + false => q, + } + } + + fn run(&mut self, inputs: &Inputs, rows: usize, limits: &[[i128; 29]; 4]) { + self.r1.clear(); + self.r1 + .extend((0..rows).map(|row| inputs.rule1_fast(row, &limits[1], &limits[2]))); + self.r2.clear(); + self.r2.extend(self.r1.iter().enumerate().map(|(row, &r1)| { + Rules::rule2( + RULE_SEVERITY[r1 as usize], + inputs.prev_fast(row, &limits[0], &limits[3]), + inputs.school(row), + ) + })); + self.fine.clear(); + self.points.clear(); + for (&r1, &r2) in self.r1.iter().zip(&self.r2) { + self.fine.push(Self::rounded( + RULE_FINE[r1 as usize], + Self::FINE[r2 as usize], + )); + self.points.push(Self::rounded( + RULE_POINTS[r1 as usize], + Self::POINTS[r2 as usize], + )); + } + self.r3.clear(); + self.r3.extend( + self.r1.iter().zip(&self.points).map(|(&r1, &points)| { + match RULE_SEVERITY[r1 as usize] { + 0 if points >= 5 => 0, + 0 if points >= 3 => 1, + 1 if points >= 3 => 2, + 2 if points >= 3 => 3, + 0 => 4, + 1 => 5, + _ => 6, + } + }), + ); + } + + fn row(&self, input: Variable, row: usize) -> Variable { + let entry = Entry { + r1: self.r1[row], + r2: self.r2[row], + r3: self.r3[row], + fine: Decimal::new(self.fine[row], 0), + points: Decimal::new(self.points[row], 0), + }; + for (path, value) in Folded::assessment(&entry) { + input.dot_insert(path, value); + } + input + } +} + +struct Ceiling; + +impl Ceiling { + async fn measure(label: &str, inputs_json: &[Value], runs: usize) { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let fixture = Fixture::load(); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + assert!(matches!(compiled.compiled_verdict(), Some(Ok(())))); + let walker = compiled.interpreted(); + let built = Built::new(inputs_json).unwrap(); + let rows = built.rows; + let columns = built.columns(); + let options = EvaluationOptions::default(); + let inputs = Inputs::of(&built); + let folded = Folded::new(); + let mut codes = Vec::with_capacity(rows); + let limits = [ + Inputs::limits(2), + Inputs::limits(15), + Inputs::limits(30), + Inputs::limits(3), + ]; + let mut fast = Vec::with_capacity(rows); + folded.run_fast(&inputs, rows, &mut fast, &limits); + let mut scaled = Scaled::default(); + scaled.run(&inputs, rows, &limits); + let mut staged = Staged::default(); + folded.run(&inputs, rows, &mut codes); + staged.run(&folded, &inputs, rows); + let output = compiled.evaluate_columns(&columns, options).await; + let mut mismatches = Vec::new(); + for row in 0..rows { + let input = columns.row(row); + let walked = walker + .evaluate(input.clone()) + .await + .map(|r| Built::normalized(r.result.to_value())) + .map_err(|e| e.to_string()); + let engine = match &output.errors[row] { + Some(e) => Err(e.to_string()), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + let hand = Ok(Built::normalized( + folded.row(input.deep_clone(), codes[row]).to_value(), + )); + let stage = Ok(Built::normalized( + staged.row(input.deep_clone(), row).to_value(), + )); + let scale = Ok(Built::normalized( + scaled.row(input.deep_clone(), row).to_value(), + )); + if walked != hand || walked != engine || walked != stage || walked != scale { + mismatches.push(format!( + "row {row} {}\n walker {walked:?}\n engine {engine:?}\n folded {hand:?}\n staged {stage:?}", + input.to_value() + )); + } + } + assert_eq!(fast, codes); + assert!( + mismatches.is_empty(), + "{} mismatches:\n{}", + mismatches.len(), + mismatches + .iter() + .take(5) + .cloned() + .collect::>() + .join("\n") + ); + let distinct: std::collections::BTreeSet = codes.iter().copied().collect(); + let mut best = [f64::MAX; 6]; + let per = + |start: std::time::Instant, n: usize| start.elapsed().as_nanos() as f64 / n as f64; + for _ in 0..runs { + let start = std::time::Instant::now(); + for c in (0..rows.min(256)).map(|r| columns.row(r)) { + let _ = walker.evaluate(c).await; + } + best[0] = best[0].min(per(start, rows.min(256))); + let start = std::time::Instant::now(); + let out = compiled.evaluate_columns(&columns, options).await; + best[1] = best[1].min(per(start, rows)); + drop(std::hint::black_box(out)); + let start = std::time::Instant::now(); + for _ in 0..100 { + let inputs = Inputs::of(&built); + folded.run(std::hint::black_box(&inputs), rows, &mut codes); + std::hint::black_box(&codes); + } + best[2] = best[2].min(per(start, rows * 100)); + let start = std::time::Instant::now(); + for _ in 0..100 { + let inputs = Inputs::of(&built); + staged.run(&folded, std::hint::black_box(&inputs), rows); + std::hint::black_box(&staged.fine); + } + best[3] = best[3].min(per(start, rows * 100)); + let start = std::time::Instant::now(); + for _ in 0..100 { + let inputs = Inputs::of(&built); + folded.run_fast(std::hint::black_box(&inputs), rows, &mut fast, &limits); + std::hint::black_box(&fast); + } + best[4] = best[4].min(per(start, rows * 100)); + let start = std::time::Instant::now(); + for _ in 0..100 { + let inputs = Inputs::of(&built); + scaled.run(std::hint::black_box(&inputs), rows, &limits); + std::hint::black_box(&scaled.fine); + } + best[5] = best[5].min(per(start, rows * 100)); + } + println!( + "{label}: rows {rows} distinct combos {} | walker {:.0} ns/row | engine {:.1} ns/row | hand folded {:.2} ns/row | hand folded-fast {:.2} ns/row | hand staged-decimal {:.2} ns/row | hand staged-scaled {:.2} ns/row | engine/folded {:.1}x engine/staged {:.1}x | walker/engine {:.1}x walker/folded {:.0}x walker/staged {:.0}x", + distinct.len(), + best[0], + best[1], + best[2], + best[4], + best[3], + best[5], + best[1] / best[2], + best[1] / best[3], + best[0] / best[1], + best[0] / best[2], + best[0] / best[3], + ); + } +} + +#[tokio::test] +#[ignore] +async fn traffic_ceiling() { + let rows: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1024); + let runs: usize = std::env::var("BENCH_RUNS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(7); + let fixture = Fixture::load(); + let variants = fixture.typed_variants(); + let bench: Vec = (0..rows) + .map(|i| variants[i % variants.len()].clone()) + .collect(); + Ceiling::measure("bench-input", &bench, runs).await; + Ceiling::measure("random-input", &Fixture::random(rows), runs).await; +} + +#[tokio::test] +#[ignore] +async fn traffic_profile_engine() { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let fixture = Fixture::load(); + let variants = fixture.typed_variants(); + let random = std::env::var("BENCH_RANDOM").is_ok(); + let rows: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1024); + let inputs: Vec = match random { + true => Fixture::random(rows), + false => (0..rows) + .map(|i| variants[i % variants.len()].clone()) + .collect(), + }; + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + let built = Built::new(&inputs).unwrap(); + let columns = built.columns(); + let seconds: u64 = std::env::var("BENCH_PROFILE") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(10); + let until = std::time::Instant::now() + std::time::Duration::from_secs(seconds); + let mut calls = 0usize; + while std::time::Instant::now() < until { + let _ = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + calls += 1; + } + println!("calls {calls}"); +} diff --git a/core/engine/tests/columnar_schemas.rs b/core/engine/tests/columnar_schemas.rs new file mode 100644 index 00000000..ccc44019 --- /dev/null +++ b/core/engine/tests/columnar_schemas.rs @@ -0,0 +1,292 @@ +mod support; + +use serde_json::{json, Value}; +use std::sync::Arc; +use support::columns::Built; +use zen_engine::loader::MemoryLoader; +use zen_engine::model::{DecisionContent, GraphContent}; +use zen_engine::{Decision, EvaluationOptions}; +use zen_expression::Variable; + +struct Case; + +impl Case { + fn graph(nodes: Vec, imports: Vec<&str>) -> GraphContent { + let edges: Vec = nodes + .windows(2) + .enumerate() + .map(|(i, pair)| json!({ "id": format!("e{i}"), "sourceId": pair[0]["id"], "targetId": pair[1]["id"] })) + .collect(); + serde_json::from_value(json!({ "nodes": nodes, "edges": edges, "imports": imports })) + .expect("graph") + } + + fn input(schema: Value) -> Value { + json!({ "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }) + } + + fn expression(fields: &[(&str, &str)]) -> Value { + let expressions: Vec = fields + .iter() + .enumerate() + .map(|(i, (key, value))| json!({ "id": format!("x{i}"), "key": key, "value": value })) + .collect(); + json!({ "id": "calc", "name": "calc", "type": "expressionNode", "content": { "expressions": expressions, "passThrough": true, "inputField": null, "outputPath": null, "executionMode": "single" } }) + } + + fn output(schema: Option) -> Value { + let content = match schema { + Some(schema) => json!({ "schema": schema.to_string() }), + None => json!({}), + }; + json!({ "id": "out", "name": "response", "type": "outputNode", "content": content }) + } + + fn render(result: Result) -> Value { + match result { + Ok(value) => json!({ "ok": Built::normalized(value.to_value()) }), + Err(error) => json!({ "error": error }), + } + } + + async fn compare(decision: &Decision, rows: Vec) { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); + let mut expected = Vec::new(); + for row in &rows { + let result = decision + .evaluate(Variable::from(row.clone())) + .await + .map(|r| r.result) + .map_err(|e| serde_json::to_string(&e).unwrap_or_default()); + expected.push(Self::render(result)); + } + let mut representations = 0; + for built in [Built::new(&rows), Built::nested(&rows)] + .into_iter() + .flatten() + { + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let output = decision + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + representations += 1; + assert_eq!(output.paths().hosted, 0, "rows left the columnar plan"); + for (row, want) in expected.iter().enumerate() { + let got = Self::render(match &output.errors[row] { + Some(error) => Err(serde_json::to_string(error.as_ref()).unwrap_or_default()), + None => Ok(output.row(row)), + }); + assert_eq!(&got, want, "row {row}: {}", rows[row]); + } + } + assert!(representations > 0, "no columnar representation built"); + } +} + +#[tokio::test] +async fn date_schemas_match_row_evaluation_in_one_columnar_batch() { + let schema = json!({ + "type": "object", + "required": ["at"], + "properties": { + "at": { "type": "string", "format": "date-time" }, + "day": { "anyOf": [{ "type": "string", "format": "date" }, { "type": "null" }] }, + "customer": { "type": "object", "properties": { "born": { "type": "string", "format": "date" }, "name": { "type": "string" } } }, + "count": { "type": "integer" } + } + }); + let decision = Decision::from(Case::graph( + vec![ + Case::input(schema), + Case::expression(&[ + ("kind", "type(at)"), + ("hour", "at.hour()"), + ("dayKind", "type(day)"), + ("born", "customer.born == null ? null : year(customer.born)"), + ("bornKind", "type(customer.born)"), + ]), + Case::output(None), + ], + vec![], + )); + let rows = vec![ + json!({ "at": "2024-01-31T10:00:00Z", "day": "2024-02-29", "customer": { "born": "1990-05-01", "name": "a" }, "count": 1 }), + json!({ "at": "2024-01-31T10:00:00+02:00", "day": null, "customer": { "name": "b" }, "count": 2 }), + json!({ "at": "not a date", "day": "2024-02-29", "customer": { "born": "1990-05-01", "name": "c" }, "count": 3 }), + json!({ "at": "2024-01-31T23:30:00-05:00", "day": "2023-02-29", "customer": { "born": "1990-05-01", "name": "d" }, "count": 4 }), + json!({ "day": "2024-01-01", "customer": { "born": "1990-05-01", "name": "e" }, "count": 5 }), + json!({ "at": "2024-01-31T10:00", "customer": { "born": "31/01/1990", "name": "f" }, "count": 6 }), + json!({ "at": "2024-01-31T10:00:00Z", "day": "2024", "customer": { "born": "2000", "name": "g" }, "count": 7.5 }), + json!({ "at": "2024-01-31", "day": "20240131", "customer": { "born": "1990-05-01", "name": "h" }, "count": 8 }), + ]; + Case::compare(&decision, rows).await; +} + +#[tokio::test] +async fn dates_inside_lists_and_untouched_dates_match_row_evaluation() { + let schema = json!({ + "type": "object", + "properties": { + "visits": { "type": "array", "items": { "type": "string", "format": "date" } }, + "plain": { "type": "string" } + } + }); + let decision = Decision::from(Case::graph( + vec![ + Case::input(schema), + Case::expression(&[("first", "type(visits[0])"), ("count", "len(visits)")]), + Case::output(None), + ], + vec![], + )); + let rows = vec![ + json!({ "visits": ["2024-01-01", "2024-02-01"], "plain": "2024-01-01" }), + json!({ "visits": ["2024-03-01"], "plain": "x" }), + json!({ "visits": ["bad"], "plain": "y" }), + json!({ "visits": [], "plain": "z" }), + ]; + Case::compare(&decision, rows).await; +} + +#[tokio::test] +async fn dictionary_schemas_match_row_evaluation_in_one_columnar_batch() { + let loader = Arc::new(MemoryLoader::default()); + loader.add( + "dicts", + serde_json::from_value::(json!({ + "imports": [], + "blocks": [{ "id": "dict1", "type": "dictionary", "props": { "data": { "name": "customerTier", + "entries": [{ "id": "e0", "value": "VIP", "label": "v" }, { "id": "e1", "value": "STD", "label": "s" }] } } }] + })) + .expect("dictionary"), + ); + let schema = json!({ "type": "object", "properties": { "tier": { "$dictionary": "customerTier" }, "since": { "type": "string", "format": "date" } } }); + let decision = Decision::from(Case::graph( + vec![ + Case::input(schema), + Case::expression(&[("vip", "tier == 'VIP'"), ("sinceKind", "type(since)")]), + Case::output(None), + ], + vec!["dicts"], + )) + .with_loader(loader); + let rows = vec![ + json!({ "tier": "VIP", "since": "2024-01-01" }), + json!({ "tier": "STD", "since": "2024-02-30" }), + json!({ "tier": "GOLD", "since": "2024-01-01" }), + json!({ "tier": "VIP" }), + json!({ "since": "2024-05-05" }), + ]; + Case::compare(&decision, rows).await; +} + +#[tokio::test] +async fn output_schemas_over_mixed_columns_match_row_evaluation() { + let schema = json!({ + "type": "object", + "required": ["count", "status"], + "properties": { + "count": { "type": "integer", "minimum": 0 }, + "ratio": { "type": "number" }, + "status": { "enum": ["approved", "review"] }, + "flag": { "type": "boolean" }, + "label": { "type": "string", "maxLength": 3 } + } + }); + let decision = Decision::from(Case::graph( + vec![ + json!({ "id": "in", "name": "request", "type": "inputNode", "content": {} }), + json!({ "id": "calc", "name": "calc", "type": "expressionNode", "content": { + "expressions": [ + { "id": "a", "key": "count", "value": "kind == 'a' ? 1 : (kind == 'b' ? 'x' : (kind == 'c' ? 2.5 : (kind == 'd' ? -1 : 7)))" }, + { "id": "b", "key": "ratio", "value": "kind == 'e' ? 'no' : 0.5" }, + { "id": "c", "key": "status", "value": "kind == 'f' ? 'other' : 'approved'" }, + { "id": "d", "key": "flag", "value": "kind == 'g' ? 1 : true" }, + { "id": "e", "key": "label", "value": "kind == 'h' ? 'long text' : 'ok'" } + ], + "passThrough": false, "inputField": null, "outputPath": null, "executionMode": "single" + } }), + Case::output(Some(schema)), + ], + vec![], + )); + let rows: Vec = ["a", "b", "c", "d", "e", "f", "g", "h", "z", "a", "z"] + .iter() + .map(|kind| json!({ "kind": kind })) + .collect(); + Case::compare(&decision, rows).await; +} + +#[tokio::test] +async fn unmodelled_property_keywords_match_row_evaluation() { + let schema = json!({ + "type": "object", + "required": ["email", "code"], + "properties": { + "email": { "type": "string", "format": "email" }, + "code": { "type": "string", "pattern": "^[A-Z]{2}[0-9]+$" }, + "step": { "type": "number", "multipleOf": 0.5 }, + "contact": { "oneOf": [{ "type": "string" }, { "type": "integer", "minimum": 1 }] }, + "customer": { "type": "object", "properties": { "vat": { "type": "string", "pattern": "^DE" } } } + } + }); + let decision = Decision::from(Case::graph( + vec![ + Case::input(schema), + Case::expression(&[("ok", "true")]), + Case::output(None), + ], + vec![], + )); + let rows = vec![ + json!({ "email": "a@b.co", "code": "DE12", "step": 1.5, "contact": "x", "customer": { "vat": "DE1" } }), + json!({ "email": "not-an-email", "code": "DE12", "step": 1.5, "contact": 2, "customer": { "vat": "DE1" } }), + json!({ "email": "a@b.co", "code": "de12", "step": 1.5, "contact": 2 }), + json!({ "email": "a@b.co", "code": "DE12", "step": 1.25, "contact": 3 }), + json!({ "email": "a@b.co", "code": "DE12", "step": 2, "contact": 0 }), + json!({ "email": "a@b.co", "code": "DE12", "contact": 1.5, "customer": { "vat": "FR1" } }), + json!({ "email": "c@d.org", "code": "AT9", "step": 0.5, "contact": "y", "customer": { "vat": "DE9" } }), + json!({ "code": "DE12" }), + ]; + Case::compare(&decision, rows).await; +} + +#[tokio::test] +async fn output_schemas_over_constant_columns_match_row_evaluation() { + for (field, value) in [ + ("count", "-1"), + ("count", "1.5"), + ("count", "3"), + ("ratio", "'0.5'"), + ("status", "'other'"), + ("status", "'review'"), + ("flag", "1"), + ("label", "'long text'"), + ] { + let schema = json!({ + "type": "object", + "properties": { + "count": { "type": "integer", "minimum": 0 }, + "ratio": { "type": "number" }, + "status": { "enum": ["approved", "review"] }, + "flag": { "type": "boolean" }, + "label": { "type": "string", "maxLength": 3 } + } + }); + let decision = Decision::from(Case::graph( + vec![ + json!({ "id": "in", "name": "request", "type": "inputNode", "content": {} }), + json!({ "id": "calc", "name": "calc", "type": "expressionNode", "content": { + "expressions": [{ "id": "a", "key": field, "value": value }, { "id": "b", "key": "seen", "value": "kind" }], + "passThrough": false, "inputField": null, "outputPath": null, "executionMode": "single" + } }), + Case::output(Some(schema)), + ], + vec![], + )); + let rows: Vec = (0..8).map(|i| json!({ "kind": format!("k{i}") })).collect(); + Case::compare(&decision, rows).await; + } +} diff --git a/core/engine/tests/columnar_side_effects.rs b/core/engine/tests/columnar_side_effects.rs new file mode 100644 index 00000000..88ab997e --- /dev/null +++ b/core/engine/tests/columnar_side_effects.rs @@ -0,0 +1,321 @@ +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use zen_engine::loader::{DecisionLoader, LoaderResponse, MemoryLoader}; +use zen_engine::model::{DecisionContent, GraphContent}; +use zen_engine::nodes::custom::{CustomNodeAdapter, CustomNodeRequest}; +use zen_engine::nodes::http_handler::{HttpHandler, HttpHandlerRequest, HttpHandlerResponse}; +use zen_engine::nodes::{NodeError, NodeResponse, NodeResult}; +use zen_engine::{Decision, EvaluationOptions}; +use zen_expression::lane::{Column, Columns, Values}; +use zen_expression::Variable; + +#[derive(Debug, Default, Clone)] +struct Counts(Arc>>); + +impl Counts { + fn bump(&self, key: &str) { + if let Ok(mut map) = self.0.lock() { + *map.entry(key.to_string()).or_default() += 1; + } + } + + fn take(&self) -> BTreeMap { + self.0 + .lock() + .map(|mut map| std::mem::take(&mut *map)) + .unwrap_or_default() + } +} + +#[derive(Debug)] +struct Counting(Counts); + +impl CustomNodeAdapter for Counting { + fn handle(&self, request: CustomNodeRequest) -> Pin + '_>> { + Box::pin(async move { + self.0.bump(&format!("custom:{}", request.node.name)); + let odd = request + .input + .dot("x") + .is_some_and(|x| x.to_value().as_i64().is_some_and(|x| x % 2 == 1)); + let output = match request.node.kind.as_ref() { + "array" => Variable::from(json!([1, 2])), + "flaky" if odd => return Err(NodeError::new(request.node.id.clone(), "odd row")), + "flaky" => Variable::from(json!([1, 2])), + _ => Variable::from(json!({ "seen": true })), + }; + Ok(NodeResponse { + output, + trace_data: None, + }) + }) + } +} + +#[derive(Debug)] +struct Http(Counts); + +impl HttpHandler for Http { + fn handle( + &self, + _request: HttpHandlerRequest, + ) -> Pin> + Send + '_>> { + Box::pin(async move { + self.0.bump("http"); + Ok(HttpHandlerResponse { + status: 200, + headers: json!({}), + data: json!({ "ok": true }), + }) + }) + } +} + +#[derive(Debug)] +struct Loads(Counts, MemoryLoader); + +impl DecisionLoader for Loads { + fn load<'a>( + &'a self, + key: &'a str, + ) -> Pin + 'a + Send>> { + self.0.bump(&format!("load:{key}")); + self.1.load(key) + } +} + +struct Scenario { + name: &'static str, + graph: Value, +} + +impl Scenario { + const ROWS: usize = 4; + + fn node(id: &str, kind: &str, content: Value) -> Value { + json!({ "id": id, "name": id, "type": kind, "content": content }) + } + + fn edge(from: &str, to: &str) -> Value { + json!({ "id": format!("{from}-{to}"), "sourceId": from, "targetId": to }) + } + + fn switched(from: &str, to: &str, handle: &str) -> Value { + json!({ "id": format!("{from}-{to}"), "sourceId": from, "targetId": to, "sourceHandle": handle }) + } + + fn expression(id: &str, key: &str, value: &str) -> Value { + Self::node( + id, + "expressionNode", + json!({ "expressions": [{ "id": format!("{id}-1"), "key": key, "value": value }] }), + ) + } + + fn custom(id: &str, kind: &str) -> Value { + Self::node(id, "customNode", json!({ "kind": kind, "config": {} })) + } + + fn io() -> [Value; 2] { + [ + json!({ "id": "in", "name": "in", "type": "inputNode" }), + json!({ "id": "out", "name": "out", "type": "outputNode" }), + ] + } + + fn all() -> Vec { + let [input, output] = Self::io(); + let http = Self::node( + "fetch", + "functionNode", + json!({ "source": "import http from 'http';\nexport const handler = async (input) => {\n const r = await http.get('https://example.invalid/x');\n return { status: r.status };\n};\n" }), + ); + let switch = Self::node( + "sw", + "switchNode", + json!({ "hitPolicy": "first", "statements": [{ "id": "hi", "condition": "x > 2" }, { "id": "lo", "condition": "" }] }), + ); + vec![ + Scenario { + name: "control: custom returns object", + graph: json!({ + "nodes": [input, Self::custom("side", "object"), Self::expression("e", "y", "1"), output], + "edges": [Self::edge("in", "side"), Self::edge("side", "e"), Self::edge("e", "out")] + }), + }, + Scenario { + name: "strict join sees array", + graph: json!({ + "nodes": [input, Self::custom("side", "array"), Self::expression("e", "y", "1"), output], + "edges": [Self::edge("in", "side"), Self::edge("side", "e"), Self::edge("e", "out")] + }), + }, + Scenario { + name: "lazy child plan fails", + graph: json!({ + "nodes": [input, Self::custom("side", "object"), Self::expression("e", "z", "1"), switch, output], + "edges": [ + Self::edge("in", "side"), Self::edge("side", "e"), Self::edge("in", "sw"), + Self::switched("sw", "out", "hi"), Self::switched("sw", "out", "lo") + ] + }), + }, + Scenario { + name: "custom fails on odd rows, array on even rows", + graph: json!({ + "nodes": [input, Self::custom("side", "flaky"), Self::expression("e", "y", "1"), output], + "edges": [Self::edge("in", "side"), Self::edge("side", "e"), Self::edge("e", "out")] + }), + }, + Scenario { + name: "sub-decision then array", + graph: json!({ + "nodes": [input, Self::node("sub", "decisionNode", json!({ "key": "sub" })), Self::custom("side", "array"), Self::expression("e", "y", "1"), output], + "edges": [Self::edge("in", "sub"), Self::edge("sub", "side"), Self::edge("side", "e"), Self::edge("e", "out")] + }), + }, + Scenario { + name: "v2 function http then array", + graph: json!({ + "nodes": [input, http, Self::custom("side", "array"), Self::expression("e", "y", "1"), output], + "edges": [Self::edge("in", "fetch"), Self::edge("fetch", "side"), Self::edge("side", "e"), Self::edge("e", "out")] + }), + }, + ] + } + + fn compiled(value: Value) -> Arc { + let mut graph: GraphContent = serde_json::from_value(value).expect("graph"); + graph.compile(); + Arc::new(graph) + } + + fn decision(&self, counts: &Counts) -> Decision { + let [input, output] = Self::io(); + let sub = json!({ + "nodes": [input, Self::custom("inner", "object"), output], + "edges": [Self::edge("in", "inner"), Self::edge("inner", "out")] + }); + let memory = MemoryLoader::default(); + memory.add("sub", DecisionContent::Graph(Self::compiled(sub))); + let mut decision = Decision::from(Arc::new( + serde_json::from_value::(self.graph.clone()).expect("graph"), + )) + .with_adapter(Arc::new(Counting(counts.clone()))) + .with_http_handler(Some(Arc::new(Http(counts.clone())))) + .with_loader(Arc::new(Loads(counts.clone(), memory))); + decision.compile(); + decision + } + + fn outcome( + result: &Result>, + ) -> Result { + match result { + Ok(response) => Ok(response.result.to_value()), + Err(error) => Err(serde_json::to_value(&**error) + .map(|v| v.to_string()) + .unwrap_or_else(|_| error.to_string())), + } + } + + async fn measure(&self) -> (BTreeMap<&'static str, BTreeMap>, Vec) { + let counts = Counts::default(); + let decision = self.decision(&counts); + let xs: Vec = (1..=Self::ROWS as i64).collect(); + let columns = Columns::new(Self::ROWS) + .column("x", Column::new(Values::I64(&xs))) + .column("$nodes.k", Column::new(Values::I64(&xs))); + let contexts: Vec = xs + .iter() + .map(|x| Variable::from(json!({ "x": x, "$nodes": { "k": x } }))) + .collect(); + let mut out = BTreeMap::new(); + let columnar = decision + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + out.insert("columns", counts.take()); + let batch = decision + .evaluate_batch(&contexts, EvaluationOptions::default()) + .await; + out.insert("batch", counts.take()); + let mut mismatches = Vec::new(); + for (row, result) in batch.iter().enumerate() { + let want = Self::outcome(result); + let got = match &columnar.errors[row] { + Some(error) => Err(serde_json::to_value(&**error) + .map(|v| v.to_string()) + .unwrap_or_else(|_| error.to_string())), + None => Ok(columnar.row(row).to_value()), + }; + if got != want { + mismatches.push(format!( + "{} row {row}: columns {got:?} vs batch {want:?}", + self.name + )); + } + } + for context in &contexts { + let _ = decision.evaluate(context.clone()).await; + } + out.insert("single", counts.take()); + #[cfg(feature = "driver")] + { + let walker = decision.interpreted(); + for context in &contexts { + let _ = walker.evaluate(context.clone()).await; + } + out.insert("walker", counts.take()); + } + (out, mismatches) + } +} + +#[tokio::test] +async fn columnar_host_nodes_run_once_per_row() { + let mut failures = Vec::new(); + for scenario in Scenario::all() { + let (measured, mismatches) = scenario.measure().await; + println!("{}: {measured:?}", scenario.name); + failures.extend(mismatches); + let Some(single) = measured.get("single") else { + continue; + }; + let hosted = |counts: &BTreeMap| { + counts + .iter() + .filter(|(k, _)| !k.starts_with("load:")) + .map(|(k, v)| (k.clone(), *v)) + .collect::>() + }; + let loads = |counts: &BTreeMap| { + counts + .iter() + .filter(|(k, _)| k.starts_with("load:")) + .map(|(k, v)| (k.clone(), *v)) + .collect::>() + }; + if let (Some(columns), Some(batch)) = (measured.get("columns"), measured.get("batch")) { + if loads(columns) != loads(batch) { + failures.push(format!( + "{} columns loads {:?} vs batch {:?}", + scenario.name, + loads(columns), + loads(batch) + )); + } + } + for (mode, counts) in &measured { + if hosted(counts) != hosted(single) { + failures.push(format!( + "{} {mode} {counts:?} vs single {single:?}", + scenario.name + )); + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/core/engine/tests/columnar_subdecisions.rs b/core/engine/tests/columnar_subdecisions.rs new file mode 100644 index 00000000..7de091ec --- /dev/null +++ b/core/engine/tests/columnar_subdecisions.rs @@ -0,0 +1,363 @@ +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use zen_engine::loader::MemoryLoader; +use zen_engine::model::{DecisionContent, GraphContent}; +use zen_engine::nodes::custom::{CustomNodeAdapter, CustomNodeRequest}; +use zen_engine::nodes::{NodeError, NodeResponse, NodeResult}; +use zen_engine::{Decision, EvaluationOptions}; +use zen_expression::lane::{Column, Columns, Values}; +use zen_expression::Variable; + +#[derive(Debug, Default, Clone)] +struct Counts(Arc>>); + +impl Counts { + fn bump(&self, key: &str) { + if let Ok(mut map) = self.0.lock() { + *map.entry(key.to_string()).or_default() += 1; + } + } + + fn take(&self) -> BTreeMap { + self.0 + .lock() + .map(|mut map| std::mem::take(&mut *map)) + .unwrap_or_default() + } +} + +#[derive(Debug)] +struct Adapter(Counts); + +impl CustomNodeAdapter for Adapter { + fn handle(&self, request: CustomNodeRequest) -> Pin + '_>> { + Box::pin(async move { + self.0.bump(&request.node.name); + let odd = request + .input + .dot("x") + .is_some_and(|x| x.to_value().as_i64().is_some_and(|x| x % 2 == 1)); + let output = match request.node.kind.as_ref() { + "array" => Variable::from(json!([1, 2])), + "flaky" if odd => return Err(NodeError::new(request.node.id.clone(), "odd row")), + "echo" | "flaky" => request.input.clone(), + _ => Variable::from(json!({ "seen": true })), + }; + Ok(NodeResponse { + output, + trace_data: None, + }) + }) + } +} + +fn node(id: &str, kind: &str, content: Value) -> Value { + json!({ "id": id, "name": id, "type": kind, "content": content }) +} + +fn input(name: &str) -> Value { + json!({ "id": name, "name": name, "type": "inputNode" }) +} + +fn output() -> Value { + json!({ "id": "out", "name": "out", "type": "outputNode" }) +} + +fn expression(id: &str, fields: &[(&str, &str)]) -> Value { + let expressions: Vec = fields + .iter() + .enumerate() + .map(|(i, (key, value))| json!({ "id": format!("{id}-{i}"), "key": key, "value": value })) + .collect(); + node(id, "expressionNode", json!({ "expressions": expressions })) +} + +fn decision(id: &str, key: &str, attributes: Value) -> Value { + let mut content = json!({ "key": key }); + if let (Some(map), Some(extra)) = (content.as_object_mut(), attributes.as_object()) { + map.extend(extra.clone()); + } + node(id, "decisionNode", content) +} + +fn custom(id: &str, kind: &str) -> Value { + node(id, "customNode", json!({ "kind": kind, "config": {} })) +} + +fn chain(nodes: Vec) -> Value { + let ids: Vec = nodes + .iter() + .map(|n| n["id"].as_str().unwrap_or_default().to_string()) + .collect(); + let edges: Vec = ids + .windows(2) + .map(|w| json!({ "id": format!("{}-{}", w[0], w[1]), "sourceId": w[0], "targetId": w[1] })) + .collect(); + json!({ "nodes": nodes, "edges": edges }) +} + +struct Scenario { + name: &'static str, + graph: Value, + children: Vec<(&'static str, Value)>, + planned: bool, + max_depth: u8, +} + +impl Scenario { + const ROWS: i64 = 6; + + fn all() -> Vec { + let child = chain(vec![ + input("childIn"), + expression("c", &[("double", "x * 2"), ("label", "'n' + string(x)")]), + output(), + ]); + vec![ + Scenario { + name: "plain child", + graph: chain(vec![ + input("in"), + decision("call", "child", json!({})), + output(), + ]), + children: vec![("child", child.clone())], + planned: true, + max_depth: 10, + }, + Scenario { + name: "output path and pass through", + graph: chain(vec![ + input("in"), + decision( + "call", + "child", + json!({ "transformAttributes": { "outputPath": "res.inner", "passThrough": true } }), + ), + expression("after", &[("total", "res.inner.double + x")]), + output(), + ]), + children: vec![("child", child.clone())], + planned: true, + max_depth: 10, + }, + Scenario { + name: "input field", + graph: chain(vec![ + input("in"), + expression("wrap", &[("inner.x", "x + 1")]), + decision( + "call", + "child", + json!({ "transformAttributes": { "inputField": "inner" } }), + ), + output(), + ]), + children: vec![("child", child.clone())], + planned: true, + max_depth: 10, + }, + Scenario { + name: "grandchild reads parents through input views", + graph: chain(vec![ + input("root"), + expression("pre", &[("r", "x * 10"), ("x", "x")]), + decision("call", "mid", json!({})), + output(), + ]), + children: vec![ + ( + "mid", + chain(vec![ + input("midIn"), + expression("m", &[("x", "x"), ("mid", "x + 1")]), + decision("call", "leaf", json!({})), + output(), + ]), + ), + ( + "leaf", + chain(vec![ + input("leafIn"), + custom("probe", "echo"), + expression( + "l", + &[ + ("fromMid", "$nodes.leafIn.$nodes.m.mid"), + ("fromRoot", "$nodes.leafIn.$nodes.midIn.$nodes.pre.r"), + ], + ), + output(), + ]), + ), + ], + planned: false, + max_depth: 10, + }, + Scenario { + name: "child errors on odd rows", + graph: chain(vec![ + input("in"), + decision( + "call", + "flaky", + json!({ "transformAttributes": { "outputPath": "res" } }), + ), + output(), + ]), + children: vec![( + "flaky", + chain(vec![input("flakyIn"), custom("side", "flaky"), output()]), + )], + planned: true, + max_depth: 10, + }, + Scenario { + name: "child side effect then parent array", + graph: chain(vec![ + input("in"), + decision("call", "effect", json!({})), + custom("arr", "array"), + expression("e", &[("y", "1")]), + output(), + ]), + children: vec![( + "effect", + chain(vec![input("effectIn"), custom("inner", "object"), output()]), + )], + planned: false, + max_depth: 10, + }, + Scenario { + name: "depth limit", + graph: chain(vec![ + input("in"), + decision("call", "a", json!({})), + output(), + ]), + children: vec![ + ( + "a", + chain(vec![ + input("aIn"), + decision("next", "b", json!({})), + output(), + ]), + ), + ( + "b", + chain(vec![ + input("bIn"), + decision("next", "c", json!({})), + output(), + ]), + ), + ( + "c", + chain(vec![ + input("cIn"), + expression("e", &[("deep", "x")]), + output(), + ]), + ), + ], + planned: false, + max_depth: 3, + }, + ] + } + + fn decision(&self, counts: &Counts) -> Decision { + let memory = MemoryLoader::default(); + for (key, graph) in &self.children { + let content: GraphContent = serde_json::from_value(graph.clone()).expect("child"); + memory.add(*key, DecisionContent::Graph(Arc::new(content))); + } + Decision::from(Arc::new( + serde_json::from_value::(self.graph.clone()).expect("graph"), + )) + .with_adapter(Arc::new(Adapter(counts.clone()))) + .with_loader(Arc::new(memory)) + } + + fn error(error: &zen_engine::EvaluationError) -> String { + serde_json::to_value(error) + .map(|v| v.to_string()) + .unwrap_or_else(|_| error.to_string()) + } + + async fn check(&self) -> Vec { + let counts = Counts::default(); + let decision = self.decision(&counts); + let options = EvaluationOptions { + trace: false, + max_depth: self.max_depth, + }; + let xs: Vec = (1..=Self::ROWS).collect(); + let columns = Columns::new(xs.len()).column("x", Column::new(Values::I64(&xs))); + let contexts: Vec = xs + .iter() + .map(|x| Variable::from(json!({ "x": x }))) + .collect(); + let mut failures = Vec::new(); + let columnar = decision.evaluate_columns(&columns, options).await; + let columnar_counts = counts.take(); + if self.planned { + match zen_engine::diagnostics::plan_verdict(&decision, &columns) { + Some(Ok(())) => {} + other => failures.push(format!("{}: not planned: {other:?}", self.name)), + } + } + let mut singles = Vec::new(); + for context in &contexts { + singles.push(decision.evaluate_with_opts(context.clone(), options).await); + } + let single_counts = counts.take(); + let batch = decision.evaluate_batch(&contexts, options).await; + for (row, (single, batched)) in singles.iter().zip(&batch).enumerate() { + let want = single + .as_ref() + .map(|r| r.result.to_value()) + .map_err(|e| Self::error(e)); + let other = batched + .as_ref() + .map(|r| r.result.to_value()) + .map_err(|e| Self::error(e)); + let got = match &columnar.errors[row] { + Some(error) => Err(Self::error(error)), + None => Ok(columnar.row(row).to_value()), + }; + if got != want { + failures.push(format!( + "{} row {row}: columnar {got:?} vs single {want:?}", + self.name + )); + } + if other != want { + failures.push(format!( + "{} row {row}: batch {other:?} vs single {want:?}", + self.name + )); + } + } + if columnar_counts != single_counts { + failures.push(format!( + "{}: custom calls columnar {columnar_counts:?} vs single {single_counts:?}", + self.name + )); + } + failures + } +} + +#[tokio::test] +async fn columnar_sub_decisions_match_row_evaluation() { + let mut failures = Vec::new(); + for scenario in Scenario::all() { + failures.extend(scenario.check().await); + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/core/engine/tests/compiled.rs b/core/engine/tests/compiled.rs new file mode 100644 index 00000000..f83e2156 --- /dev/null +++ b/core/engine/tests/compiled.rs @@ -0,0 +1,1967 @@ +#[path = "support/fixture.rs"] +mod fixture; +mod support; + +use fixture::{Fixture, NETWORK_BOUND, TIME_BOUND}; +#[cfg(feature = "driver")] +use serde_json::json; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fs; +use std::sync::Arc; +use support::columns::Built; +use support::golden::{Canon, Live, Reference}; +#[cfg(feature = "driver")] +use zen_engine::model::GraphContent; +use zen_engine::{Decision, EvaluationOptions}; +use zen_expression::Variable; + +struct Outcome; + +impl Outcome { + const CLOCK: &'static str = "2025-08-19T16:55:02.078Z"; + + fn of( + result: Result>, + ) -> Result { + result + .map(|r| serde_json::to_string(&r.result).unwrap_or_default()) + .map_err(|e| { + serde_json::to_value(&*e) + .map(|v| v.to_string()) + .unwrap_or_else(|_| e.to_string()) + }) + } + + fn recorded(outcome: &support::golden::Outcome) -> Result { + match outcome { + support::golden::Outcome::Ok(value) => { + Ok(Canon::value(Canon::restore(value).to_value()).to_string()) + } + support::golden::Outcome::Err { value, .. } => Err(value.to_string()), + } + } + + fn canonical(result: Result) -> Result { + let canon = |text: String| { + serde_json::from_str::(&text) + .map(|v| Canon::value(v).to_string()) + .unwrap_or(text) + }; + result.map(canon).map_err(canon) + } + + fn columnar(outcome: &support::golden::Outcome) -> Result { + match outcome { + support::golden::Outcome::Ok(value) => { + Ok(Built::normalized(Canon::restore(value).to_value())) + } + support::golden::Outcome::Err { value, .. } => Err(value.to_string()), + } + } +} + +#[tokio::test] +async fn compiled_graphs_match_the_walker() { + if Reference::unavailable("graph-fixtures") { + return; + } + Reference::prepare(Outcome::CLOCK); + let reference = Reference::open("graph-fixtures"); + let mut census: BTreeMap> = BTreeMap::new(); + let mut failures: Vec = Vec::new(); + let mut compared = 0usize; + for fixture in Fixture::load_all() { + let walker = Live::walker(&Decision::from(Arc::new(fixture.content.clone()))); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + let verdict = compiled.compiled_verdict(); + let key = match &verdict { + Some(Ok(())) => "compiled".to_string(), + Some(Err(reason)) => format!("walker: {reason}"), + None => "not compiled".to_string(), + }; + census.entry(key).or_default().push(fixture.name.clone()); + if !matches!(verdict, Some(Ok(()))) || NETWORK_BOUND.contains(&fixture.name.as_str()) { + continue; + } + let variants = fixture.variants(); + let contexts: Vec = variants.iter().map(|v| Variable::from(v.clone())).collect(); + let options = EvaluationOptions::default(); + let batch = compiled.evaluate_batch(&contexts, options).await; + for (i, input) in variants.iter().enumerate() { + let context = Variable::from(input.clone()); + let want = reference + .graph( + || Canon::key(&fixture.name, &[], &context), + || async { + Live::require_walker(); + Outcome::of(walker.evaluate(Variable::from(input.clone())).await) + }, + Outcome::recorded, + ) + .await; + let single = Outcome::of(compiled.evaluate(Variable::from(input.clone())).await); + let batched = batch.get(i).map(|r| match r { + Ok(r) => Ok(serde_json::to_string(&r.result).unwrap_or_default()), + Err(e) => Err(serde_json::to_value(&**e) + .map(|v| v.to_string()) + .unwrap_or_else(|_| e.to_string())), + }); + let (single, batched) = match reference.is_live() { + true => (single, batched), + false => (Outcome::canonical(single), batched.map(Outcome::canonical)), + }; + compared += 1; + if single != want { + failures.push(format!( + "{} single {input}\n walker {want:?}\n compiled {single:?}", + fixture.name + )); + } + if batched.as_ref() != Some(&want) { + failures.push(format!( + "{} batch {input}\n walker {want:?}\n compiled {batched:?}", + fixture.name + )); + } + } + } + for (verdict, files) in &census { + println!("{verdict}: {} {:?}", files.len(), files); + } + println!("compared {compared} inputs"); + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(20) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[cfg(feature = "driver")] +#[tokio::test] +#[ignore] +async fn compiled_graph_throughput() { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let rows: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(256); + let filter = std::env::var("BENCH_FILE").ok(); + let mut ratios: Vec<(f64, f64, String)> = Vec::new(); + println!( + "{:44} {:>10} {:>10} {:>10} {:>7} {:>7}", + "fixture", "walker", "single", "batch", "x1", "xN" + ); + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + || filter + .as_ref() + .is_some_and(|f| !fixture.name.contains(f.as_str())) + { + continue; + } + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + if !matches!(compiled.compiled_verdict(), Some(Ok(()))) { + continue; + } + let walker = compiled.interpreted(); + let variants = fixture.variants(); + let contexts: Vec = (0..rows) + .map(|i| Variable::from(variants[i % variants.len()].clone())) + .collect(); + let options = EvaluationOptions::default(); + if let Ok(seconds) = std::env::var("BENCH_PROFILE") { + let until = std::time::Instant::now() + + std::time::Duration::from_secs(seconds.parse().unwrap_or(5)); + let single = std::env::var("BENCH_MODE").is_ok_and(|m| m == "single"); + while std::time::Instant::now() < until { + match single { + true => { + for c in &contexts { + let _ = compiled.evaluate(c.clone()).await; + } + } + false => { + let _ = compiled.evaluate_batch(&contexts, options).await; + } + } + } + continue; + } + let time = |elapsed: std::time::Duration, n: usize| elapsed.as_nanos() as f64 / n as f64; + let mut best = [f64::MAX; 3]; + for _ in 0..5 { + let start = std::time::Instant::now(); + for c in &contexts { + let _ = walker.evaluate(c.clone()).await; + } + best[0] = best[0].min(time(start.elapsed(), rows)); + let start = std::time::Instant::now(); + for c in &contexts { + let _ = compiled.evaluate(c.clone()).await; + } + best[1] = best[1].min(time(start.elapsed(), rows)); + let start = std::time::Instant::now(); + let _ = compiled.evaluate_batch(&contexts, options).await; + best[2] = best[2].min(time(start.elapsed(), rows)); + } + println!( + "{:44} {:>10.0} {:>10.0} {:>10.0} {:>6.2}x {:>6.2}x", + fixture.name, + best[0], + best[1], + best[2], + best[0] / best[1], + best[0] / best[2] + ); + ratios.push((best[0] / best[1], best[0] / best[2], fixture.name.clone())); + } + let gm = |f: fn(&(f64, f64, String)) -> f64| { + (ratios.iter().map(|r| f(r).ln()).sum::() / ratios.len() as f64).exp() + }; + let median = |f: fn(&(f64, f64, String)) -> f64| { + let mut v: Vec = ratios.iter().map(f).collect(); + v.sort_by(|a, b| a.total_cmp(b)); + v[v.len() / 2] + }; + println!( + "single: geomean {:.2}x median {:.2}x | batch: geomean {:.2}x median {:.2}x", + gm(|r| r.0), + median(|r| r.0), + gm(|r| r.1), + median(|r| r.1) + ); +} + +#[tokio::test] +async fn columnar_graphs_match_the_walker() { + if Reference::unavailable("graph-fixtures") { + return; + } + Reference::prepare(Outcome::CLOCK); + let reference = Reference::open("graph-fixtures"); + let mut failures: Vec = Vec::new(); + let (mut compared, mut skipped) = (0usize, 0usize); + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + || std::env::var("BENCH_FILE").is_ok_and(|f| !fixture.name.contains(f.as_str())) + { + continue; + } + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + if !matches!(compiled.compiled_verdict(), Some(Ok(()))) { + continue; + } + let walker = Live::walker(&compiled); + let variants = fixture.variants(); + let Some(built) = Built::new(&variants) else { + skipped += 1; + continue; + }; + let cycled: Vec = (0..variants.len() * 4) + .map(|i| variants[i % variants.len()].clone()) + .collect(); + for built in std::iter::once(built) + .chain(Built::lists(&variants)) + .chain(Built::new(&cycled)) + .chain(Built::nested(&variants)) + .chain(Built::nested(&cycled)) + { + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let output = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + for row in 0..built.rows { + let input = columns.row(row); + let want = reference + .graph( + || Canon::key(&fixture.name, &[], &input), + || async { + Live::require_walker(); + match walker.evaluate(input.clone()).await { + Ok(r) => Ok(Built::normalized(r.result.to_value())), + Err(e) => Err(serde_json::to_value(&*e) + .map(|v| v.to_string()) + .unwrap_or_default()), + } + }, + Outcome::columnar, + ) + .await; + let got = match &output.errors[row] { + Some(e) => Err(serde_json::to_value(&**e) + .map(|v| v.to_string()) + .unwrap_or_default()), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + compared += 1; + if got != want { + failures.push(format!( + "{} {}\n walker {want:?}\n columnar {got:?}", + fixture.name, + input.to_value() + )); + } + } + } + } + println!("compared {compared} rows, {skipped} fixtures skipped"); + failures.extend(reference.missing()); + let mut kinds: Vec<&str> = failures + .iter() + .filter_map(|f| f.split_whitespace().next()) + .collect(); + kinds.dedup(); + assert!( + failures.is_empty(), + "{} mismatches in {kinds:?}:\n{}", + failures.len(), + failures + .iter() + .take(15) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[cfg(feature = "driver")] +#[tokio::test] +async fn struct_inputs_match_the_walker() { + use zen_expression::lane::{Column, Columns, Values}; + Reference::prepare(Outcome::CLOCK); + let mut failures: Vec = Vec::new(); + let mut compared = 0usize; + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + || std::env::var("BENCH_FILE").is_ok_and(|f| !fixture.name.contains(f.as_str())) + { + continue; + } + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + if !matches!(compiled.compiled_verdict(), Some(Ok(()))) { + continue; + } + let walker = compiled.interpreted(); + let variants = fixture.variants(); + let rows: Vec = (0..variants.len() * 3) + .map(|i| variants[i % variants.len()].clone()) + .collect(); + let scalar = |v: &Value| !matches!(v, Value::Object(_) | Value::Array(_)); + let Some(key) = rows + .iter() + .filter_map(|r| r.as_object()) + .flat_map(|m| m.iter()) + .find(|(_, v)| { + v.as_object() + .is_some_and(|o| !o.is_empty() && o.values().all(scalar)) + }) + .map(|(k, _)| k.clone()) + else { + continue; + }; + let usable = rows.iter().all(|r| { + r.get(&key).is_none_or(|v| { + v.is_null() || v.as_object().is_some_and(|o| o.values().all(scalar)) + }) + }); + if !usable { + continue; + } + let inner: Vec = rows + .iter() + .map(|r| { + r.get(&key) + .filter(|v| v.is_object()) + .cloned() + .unwrap_or(json!({})) + }) + .collect(); + let rest: Vec = rows + .iter() + .map(|r| { + let mut r = r.clone(); + if let Some(m) = r.as_object_mut() { + m.remove(&key); + if m.is_empty() { + m.insert("__pad".into(), json!(1)); + } + } + r + }) + .collect(); + let (Some(inner_built), Some(rest_built)) = (Built::new(&inner), Built::new(&rest)) else { + continue; + }; + if inner_built.rows != rows.len() + || rest_built.rows != rows.len() + || inner_built.paths.iter().any(|p| p.contains('.')) + { + continue; + } + let inner_columns = inner_built.columns(); + let fields: Vec<(&str, Column)> = inner_columns.columns.clone(); + let mut valid = vec![0u64; rows.len().div_ceil(64)]; + rows.iter() + .enumerate() + .filter(|(_, r)| r.get(&key).is_some_and(Value::is_object)) + .for_each(|(i, _)| valid[i / 64] |= 1 << (i % 64)); + let rest_columns = rest_built.columns(); + let mut columns = Columns::new(rows.len()); + for (path, column) in rest_columns.columns.iter().filter(|(p, _)| *p != "__pad") { + columns = columns.column(path, *column); + } + columns = columns.column( + &key, + Column::with_validity( + Values::Struct { + fields: &fields, + len: rows.len(), + }, + &valid, + 0, + ), + ); + let output = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + for row in 0..rows.len() { + let input = columns.row(row); + let want = match walker.evaluate(input.clone()).await { + Ok(r) => Ok(Built::normalized(r.result.to_value())), + Err(e) => Err(serde_json::to_value(&*e) + .map(|v| v.to_string()) + .unwrap_or_default()), + }; + let got = match &output.errors[row] { + Some(e) => Err(serde_json::to_value(&**e) + .map(|v| v.to_string()) + .unwrap_or_default()), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + compared += 1; + if got != want { + failures.push(format!( + "{} {}\n walker {want:?}\n columnar {got:?}", + fixture.name, + input.to_value() + )); + } + } + } + println!("struct inputs: compared {compared} rows"); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[tokio::test] +async fn columnar_tables_match_coded_nulls_against_null_cells() { + use zen_expression::lane::{Column, Columns, Dictionary, Values}; + let table = |inputs: Value, first: Value| -> Decision { + let content: zen_engine::model::GraphContent = serde_json::from_value(serde_json::json!({ + "nodes": [ + { "id": "in", "name": "in", "type": "inputNode", "content": {} }, + { + "id": "cls", "name": "cls", "type": "decisionTableNode", + "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [{ "id": "o1", "name": "cls", "field": "cls" }], + "rules": [first, { "_id": "r2", "o1": "'other'" }] + } + }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "cls" }, + { "id": "e2", "sourceId": "cls", "targetId": "out" } + ] + })) + .expect("graph"); + let mut decision = Decision::from(Arc::new(content)); + decision.compile(); + decision + }; + let dispatched = table( + serde_json::json!([{ "id": "i1", "name": "k", "field": "k" }]), + serde_json::json!({ "_id": "r1", "i1": "null", "o1": "'null'" }), + ); + let generic = table( + serde_json::json!([{ "id": "i1", "name": "k", "field": "k" }, { "id": "i2", "name": "always" }]), + serde_json::json!({ "_id": "r1", "i1": "null", "i2": "true", "o1": "'null'" }), + ); + let keys = [0i32, -1, 0, -1, 1]; + let column = Column::new(Values::Dict { + keys: &keys, + values: Dictionary::Text { + offsets: &[0, 1, 1], + data: "x", + }, + }); + let columns = Columns::new(keys.len()).column("k", column); + let want = ["other", "null", "other", "null", "other"]; + for (label, decision) in [("dispatched", &dispatched), ("generic", &generic)] { + let output = decision + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + for (row, want) in want.iter().enumerate() { + assert!( + output.errors[row].is_none(), + "{label} row {row}: {:?}", + output.errors[row] + ); + assert_eq!( + output.row(row).to_value(), + serde_json::json!({ "cls": want }), + "{label} row {row}" + ); + } + } +} + +#[tokio::test] +async fn columnar_function_rows_time_out_independently() { + let fixture = Fixture::load_all() + .into_iter() + .find(|f| f.name == "infinite-function.json") + .expect("fixture"); + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + let rows: Vec = (0..3).map(|i| serde_json::json!({ "row": i })).collect(); + let built = Built::new(&rows).expect("columns"); + let columns = built.columns(); + let started = std::time::Instant::now(); + let output = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + let elapsed = started.elapsed(); + let messages: Vec = output + .errors + .iter() + .map(|e| e.as_ref().map(|e| e.to_string()).unwrap_or_default()) + .collect(); + assert!( + messages.iter().all(|m| m.contains("interrupted")), + "{messages:?}" + ); + assert!(elapsed < std::time::Duration::from_secs(30), "{elapsed:?}"); +} + +struct FunctionNode; + +impl FunctionNode { + const LEAKS: &'static [&'static str] = &[ + "export const handler = async (input) => { const f = () => Math; f().seen = (f().seen || 0) + 1; return { n: f().seen, row: input.n } }", + "export const handler = async (input) => { const o = { m: Math }; o.m.seen = (o.m.seen || 0) + 1; return { n: o.m.seen, row: input.n } }", + "export const handler = async (input) => { const bump = (t) => { t.seen = (t.seen || 0) + 1; return t.seen }; return { n: bump(JSON), row: input.n } }", + ]; + + const V1: &'static [&'static str] = &[ + "const handler = (input, { dayjs, Big }) => {\n const flags = input.flags || {};\n const countFlags = (flag) => Object.values(flags).reduce((acc, curr) => {\n return curr == flag ? acc + 1 : acc;\n }, 0);\n let overallFlag = 'green';\n if (countFlags('red') > 0) {\n overallFlag = 'red';\n }\n return { ...input, overallFlag };\n}", + "const handler = (input, { dayjs, Big }) => {\n const round = (val) => val?.toFixed !== undefined ? val.round(2).toNumber() : val;\n return { a: round(Big(input.a).times(3)), b: Big(input.a).div(7).toFixed(5), c: input.n / 3, d: 0.1 + 0.2, e: 1e21 * input.n, f: -0, g: 2 ** 60 + input.n };\n}", + "/**\n * é ünïcödé — 日本\n */\nconst handler = (input, { moment, env }) => {\n const label = `row\n${input.n} é`;\n if (input.n % 3 === 0) {\n throw new Error('boom ' + input.n + label);\n }\n return { label };\n}", + "const handler = (input, { Big }) => ({ v: Big(input.n % 4 === 0 ? 'x' : input.n).plus(1).toString() })", + "const handler = (input) => ({ v: input.n % 5 === 0 ? 10n : 1 })", + "const handler = (input, { dayjs }) => ({ d: dayjs('2024-01-0' + (input.n % 9 + 1)).add(input.n, 'day').format('YYYY-MM-DD'), valid: dayjs(input.s).isValid() })", + "let c = 0;\nconst handler = (input) => ({ c: ++c, n: input.n })", + "const handler = (input) => {\n const o = input.n > 5 ? input.items : null;\n return { v: o.length };\n}", + "const handler = (input) => input.n % 2 ? undefined : { a: 1 }", + "const deep = (n) => deep(n + 1);\nconst handler = (input) => {\n if (input.n === 7) {\n deep(0);\n }\n return { ok: true };\n}", + "const handler = (input) => {\n if (input.n === 4) throw { code: input.n, items: input.items };\n if (input.n === 8) throw 'plain ' + input.n;\n return { list: input.items.map((x) => x * 1.5), s: input.s.toUpperCase() };\n}", + "const handler = (input) => {\n const out = [];\n for (const item of input.items) { out.push({ v: item }); }\n out.sort((a, b) => b.v - a.v);\n try { if (input.n % 2) { throw new Error('caught'); } } catch (e) { out.push({ e: e.message }); }\n return { out };\n}", + ]; + + fn graph(content: Value) -> Arc { + let graph = serde_json::json!({ + "nodes": [ + { "id": "in", "type": "inputNode", "name": "Request", "position": { "x": 0, "y": 0 } }, + { "id": "fn", "type": "functionNode", "name": "Function", "position": { "x": 0, "y": 0 }, "content": content }, + { "id": "out", "type": "outputNode", "name": "Response", "position": { "x": 0, "y": 0 } } + ], + "edges": [ + { "id": "e1", "type": "edge", "sourceId": "in", "targetId": "fn" }, + { "id": "e2", "type": "edge", "sourceId": "fn", "targetId": "out" } + ] + }); + match serde_json::from_value(graph) { + Ok(zen_engine::model::DecisionContent::Graph(graph)) => graph, + _ => panic!("graph"), + } + } + + fn rows(count: i64) -> Vec { + (0..count) + .map(|n| { + serde_json::json!({ + "n": n, + "a": format!("{n}.{n}5"), + "s": format!("2024-0{}-1{} é", n % 9 + 1, n % 9), + "items": [n, n * 2, 3], + "flags": { "x": if n % 2 == 0 { "red" } else { "green" }, "y": "amber" } + }) + }) + .collect() + } + + async fn compare(contents: &[Value], rows: &[Value]) -> Vec { + let built = Built::new(rows).expect("columns"); + let columns = built.columns(); + let mut failures = Vec::new(); + for content in contents { + let mut compiled = Decision::from(FunctionNode::graph(content.clone())); + compiled.compile(); + let output = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + for row in 0..rows.len() { + let want = match compiled.evaluate(columns.row(row)).await { + Ok(r) => Ok(Built::normalized(r.result.to_value())), + Err(e) => Err(serde_json::to_value(&*e) + .map(|v| v.to_string()) + .unwrap_or_default()), + }; + let got = match &output.errors[row] { + Some(e) => Err(serde_json::to_value(&**e) + .map(|v| v.to_string()) + .unwrap_or_default()), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + if got != want { + failures.push(format!( + "{content}\n row {row}\n single {want:?}\n columnar {got:?}" + )); + } + } + } + failures + } +} + +#[tokio::test] +async fn columnar_function_v2_shared_state_matches_rows() { + let rows: Vec = (0..6).map(|n| serde_json::json!({ "n": n })).collect(); + let contents: Vec = FunctionNode::LEAKS + .iter() + .map(|source| serde_json::json!({ "source": source })) + .collect(); + let failures = FunctionNode::compare(&contents, &rows).await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[tokio::test] +async fn columnar_function_v1_inputs_match_literals() { + let rows: Vec = (0..6) + .map(|n| { + let mut deep = serde_json::json!(n); + for _ in 0..(n * 10) { + deep = serde_json::json!([deep]); + } + match n % 2 { + 0 => serde_json::json!({ "n": n, "deep": deep, "meta": { "__proto__": { "x": n }, "y": 1 } }), + _ => serde_json::json!({ "n": n, "deep": deep, "meta": { "y": 1.25e-7, "z": 12345678901234567890u64 } }), + } + }) + .collect(); + let contents = [serde_json::json!("const handler = (input) => ({ x: input.meta.x, keys: Object.keys(input.meta), d: JSON.stringify(input.deep).length, y: input.meta.y, z: input.meta.z })")]; + let failures = FunctionNode::compare(&contents, &rows).await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[tokio::test] +async fn columnar_function_v1_batches_match_rows() { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let rows = FunctionNode::rows(12); + let contents: Vec = FunctionNode::V1 + .iter() + .map(|source| serde_json::json!(source)) + .collect(); + let failures = FunctionNode::compare(&contents, &rows).await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[cfg(feature = "driver")] +#[tokio::test] +#[ignore] +async fn columnar_graph_throughput() { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let rows: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1024); + let filter = std::env::var("BENCH_FILE").ok(); + let read = std::env::var("BENCH_READ").is_ok_and(|v| v == "1"); + let loader = std::env::var("BENCH_LOADER").is_ok_and(|v| v == "1"); + let mut ratios: Vec<(f64, String)> = Vec::new(); + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + || filter + .as_ref() + .is_some_and(|f| !fixture.name.contains(f.as_str())) + { + continue; + } + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + if loader { + compiled = compiled.with_loader(Arc::new(support::create_fs_loader())); + } + compiled.compile(); + if !matches!(compiled.compiled_verdict(), Some(Ok(()))) { + continue; + } + let walker = compiled.interpreted(); + let variants = match std::env::var("BENCH_VALID").is_ok() && !fixture.inputs.is_empty() { + true => fixture.inputs.clone(), + false => fixture.typed_variants(), + }; + let inputs: Vec = (0..rows) + .map(|i| variants[i % variants.len()].clone()) + .collect(); + let built = match ( + std::env::var("BENCH_NESTED").is_ok(), + std::env::var("BENCH_LISTS").is_ok(), + ) { + (true, _) => Built::nested(&inputs) + .or_else(|| Built::lists(&inputs)) + .or_else(|| Built::new(&inputs)), + (false, true) => Built::lists(&inputs).or_else(|| Built::new(&inputs)), + (false, false) => Built::new(&inputs), + }; + let Some(built) = built else { + continue; + }; + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let contexts: Vec = (0..rows).map(|r| columns.row(r)).collect(); + let options = EvaluationOptions::default(); + if let Ok(seconds) = std::env::var("BENCH_PROFILE") { + let until = std::time::Instant::now() + + std::time::Duration::from_secs(seconds.parse().unwrap_or(5)); + while std::time::Instant::now() < until { + let _ = compiled.evaluate_columns(&columns, options).await; + } + continue; + } + let mut best = [f64::MAX; 2]; + let calls: usize = std::env::var("BENCH_CALLS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(5); + for call in 0..calls { + if call < 5 { + let start = std::time::Instant::now(); + for c in contexts.iter().take(256) { + let _ = walker.evaluate(c.clone()).await; + } + best[0] = best[0].min(start.elapsed().as_nanos() as f64 / rows.min(256) as f64); + } + let start = std::time::Instant::now(); + let output = compiled.evaluate_columns(&columns, options).await; + if read { + output.columns.iter().for_each(|(_, column)| { + std::hint::black_box(column.column()); + }); + } + drop(output); + best[1] = best[1].min(start.elapsed().as_nanos() as f64 / rows as f64); + } + println!( + "{:44} {:>10.0} {:>10.1} {:>7.1}x", + fixture.name, + best[0], + best[1], + best[0] / best[1] + ); + ratios.push((best[0] / best[1], fixture.name.clone())); + } + let mut sorted: Vec = ratios.iter().map(|r| r.0).collect(); + sorted.sort_by(|a, b| a.total_cmp(b)); + let gm = (sorted.iter().map(|r| r.ln()).sum::() / sorted.len() as f64).exp(); + println!( + "columnar: geomean {gm:.1}x median {:.1}x p10 {:.1}x p90 {:.1}x", + sorted[sorted.len() / 2], + sorted[sorted.len() / 10], + sorted[sorted.len() * 9 / 10] + ); +} + +#[cfg(feature = "driver")] +struct Latency; + +#[cfg(feature = "driver")] +impl Latency { + async fn measure(contexts: &[Variable], reps: usize, mut f: F) -> f64 + where + F: FnMut(Variable) -> Fut, + Fut: std::future::Future, + { + let mut best = f64::MAX; + for _ in 0..reps { + let fresh: Vec = contexts.iter().map(|c| c.depth_clone(usize::MAX)).collect(); + let start = std::time::Instant::now(); + for context in fresh { + f(context).await; + } + best = best.min(start.elapsed().as_nanos() as f64 / contexts.len() as f64); + } + best + } + + fn geomean(values: &[f64]) -> f64 { + (values.iter().map(|v| v.ln()).sum::() / values.len().max(1) as f64).exp() + } +} + +#[cfg(feature = "driver")] +#[tokio::test] +#[ignore] +async fn single_row_latency() { + std::env::set_var("__ZEN_MOCK_UTC_TIME", Outcome::CLOCK); + let reps: usize = std::env::var("BENCH_REPS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(5); + let filter = std::env::var("BENCH_FILE").ok(); + let traced = EvaluationOptions { + trace: true, + max_depth: 10, + }; + let mut columns: [Vec; 5] = Default::default(); + println!( + "{:44} {:>10} {:>10} {:>10} {:>10} {:>10}", + "fixture", "compiled", "cold", "traced", "walker", "w-traced" + ); + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + || filter + .as_ref() + .is_some_and(|f| !fixture.name.contains(f.as_str())) + { + continue; + } + let content = Arc::new(fixture.content.clone()); + let mut compiled = Decision::from(content.clone()); + compiled.compile(); + if !matches!(compiled.compiled_verdict(), Some(Ok(()))) { + continue; + } + let walker = compiled.interpreted(); + let contexts: Vec = fixture + .variants() + .into_iter() + .take(64) + .map(Variable::from) + .collect(); + let times = [ + Latency::measure(&contexts, reps, |c| { + let compiled = &compiled; + async move { drop(compiled.evaluate(c).await) } + }) + .await, + Latency::measure(&contexts, reps, |c| { + let content = content.clone(); + async move { drop(Decision::from(content).evaluate(c).await) } + }) + .await, + Latency::measure(&contexts, reps, |c| { + let compiled = &compiled; + async move { drop(compiled.evaluate_with_opts(c, traced).await) } + }) + .await, + Latency::measure(&contexts, reps, |c| { + let walker = &walker; + async move { drop(walker.evaluate(c).await) } + }) + .await, + Latency::measure(&contexts, reps, |c| { + let walker = &walker; + async move { drop(walker.evaluate_with_opts(c, traced).await) } + }) + .await, + ]; + println!( + "{:44} {:>10.0} {:>10.0} {:>10.0} {:>10.0} {:>10.0}", + fixture.name, times[0], times[1], times[2], times[3], times[4] + ); + columns + .iter_mut() + .zip(times) + .for_each(|(column, t)| column.push(t)); + } + let gm: Vec = columns.iter().map(|c| Latency::geomean(c)).collect(); + println!("geomean ns/eval ({} fixtures): compiled {:.0} cold {:.0} traced {:.0} walker {:.0} walker-traced {:.0}", columns[0].len(), gm[0], gm[1], gm[2], gm[3], gm[4]); +} + +#[cfg(feature = "driver")] +struct Noise(u64); + +#[cfg(feature = "driver")] +impl Noise { + fn new(seed: u64) -> Self { + Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1) + } + + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + + fn chance(&mut self, percent: u64) -> bool { + self.next() % 100 < percent + } +} + +#[cfg(feature = "driver")] +struct Wide { + numbers: Vec, + strings: Vec, +} + +#[cfg(feature = "driver")] +impl Wide { + fn of(fixture: &Fixture) -> Wide { + let text = serde_json::to_string(&fixture.content).unwrap_or_default(); + let mut numbers: Vec = Vec::new(); + let mut strings: Vec = Vec::new(); + let bytes = text.as_bytes(); + let mut i = 0; + while i < bytes.len() { + let c = bytes[i]; + if c == b'\'' { + let end = text[i + 1..].find('\'').map(|e| i + 1 + e); + if let Some(end) = end { + let s = &text[i + 1..end]; + if s.len() <= 40 && !strings.iter().any(|x| x == s) { + strings.push(s.to_string()); + } + i = end + 1; + continue; + } + } + if c.is_ascii_digit() + && (i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_')) + { + let start = i; + while i < bytes.len() && (bytes[i].is_ascii_digit() || bytes[i] == b'.') { + i += 1; + } + if let Ok(n) = text[start..i] + .trim_end_matches('.') + .parse::() + { + if !numbers.contains(&n) && numbers.len() < 64 { + numbers.push(n); + } + } + continue; + } + i += 1; + } + for input in &fixture.inputs { + let mut leaves = Vec::new(); + Self::leaves(input, &mut leaves); + for leaf in leaves { + match leaf { + Value::String(s) if !strings.contains(&s) => strings.push(s), + Value::Number(n) => { + if let Ok(d) = n.to_string().parse::() { + if !numbers.contains(&d) { + numbers.push(d); + } + } + } + _ => {} + } + } + } + Wide { numbers, strings } + } + + fn leaves(value: &Value, out: &mut Vec) { + match value { + Value::Object(map) => map.values().for_each(|v| Self::leaves(v, out)), + Value::Array(items) => items.iter().for_each(|v| Self::leaves(v, out)), + other => out.push(other.clone()), + } + } + + fn number(&self, noise: &mut Noise, current: &serde_json::Number) -> Value { + let base = match (noise.chance(70), self.numbers.is_empty()) { + (true, false) => self.numbers[noise.below(self.numbers.len())], + _ => current.to_string().parse().unwrap_or_default(), + }; + let deltas = ["0", "0", "1", "-1", "0.5", "-0.01", "0.001"]; + let delta: rust_decimal::Decimal = deltas[noise.below(deltas.len())] + .parse() + .unwrap_or_default(); + let mut value = base.checked_add(delta).unwrap_or(base); + match noise.below(6) { + 0 => { + value = value + .checked_mul(rust_decimal::Decimal::from(10)) + .unwrap_or(value) + } + 1 => value = -value, + 2 => value.rescale(value.scale() + 2), + _ => {} + } + if value.is_integer() && noise.chance(50) { + value = value.trunc(); + value.rescale(0); + } + serde_json::from_str(&value.to_string()).unwrap_or(Value::Null) + } + + fn string(&self, noise: &mut Noise, current: &str) -> Value { + match noise.below(10) { + 0..=5 if !self.strings.is_empty() => { + json!(self.strings[noise.below(self.strings.len())]) + } + 6 => json!(current), + 7 => json!(""), + 8 => json!(format!("unseen{}", noise.below(1000))), + _ => json!(current.to_uppercase()), + } + } + + fn mutate(&self, value: &Value, noise: &mut Noise, depth: usize) -> Option { + if depth > 0 && noise.chance(6) { + return None; + } + if depth > 0 && noise.chance(4) { + return Some(Value::Null); + } + Some(match value { + Value::Object(map) => { + if depth > 0 && noise.chance(3) { + return Some(json!({})); + } + Value::Object( + map.iter() + .filter_map(|(k, v)| { + self.mutate(v, noise, depth + 1).map(|v| (k.clone(), v)) + }) + .collect(), + ) + } + Value::Array(items) => match noise.below(8) { + 0 => json!([]), + 1 => Value::Array(items.iter().chain(items.iter()).cloned().collect()), + _ => Value::Array( + items + .iter() + .filter_map(|v| self.mutate(v, noise, depth + 1)) + .collect(), + ), + }, + Value::Number(n) => match noise.chance(3) { + true => self.string(noise, "7"), + false => self.number(noise, n), + }, + Value::String(s) => match noise.chance(3) { + true => json!(noise.below(100)), + false => self.string(noise, s), + }, + Value::Bool(b) => match noise.chance(3) { + true => json!("true"), + false => json!(noise.chance(50) ^ b), + }, + Value::Null => match noise.below(3) { + 0 => json!(1), + 1 => self.string(noise, "x"), + _ => Value::Null, + }, + }) + } + + fn rows(fixture: &Fixture, count: usize, seed: u64) -> Vec { + let wide = Wide::of(fixture); + let mut noise = Noise::new(seed); + (0..count) + .map(|_| { + let base = &fixture.inputs[noise.below(fixture.inputs.len())]; + wide.mutate(base, &mut noise, 0).unwrap_or(json!({})) + }) + .collect() + } + + fn seed(name: &str) -> u64 { + name.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| { + (h ^ b as u64).wrapping_mul(0x100_0000_01b3) + }) + } +} + +#[cfg(feature = "driver")] +#[tokio::test] +#[ignore] +async fn wide_inputs_match_the_walker() { + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); + let rows: usize = std::env::var("WIDE_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(256); + let filter = std::env::var("WIDE_FILE").ok(); + let mut report: Vec<(String, usize, usize, usize)> = Vec::new(); + let mut samples: Vec = Vec::new(); + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + || filter + .as_ref() + .is_some_and(|f| !fixture.name.contains(f.as_str())) + { + continue; + } + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + if !matches!(compiled.compiled_verdict(), Some(Ok(()))) { + continue; + } + let walker = compiled.interpreted(); + let inputs = Wide::rows(&fixture, rows, Wide::seed(&fixture.name)); + let contexts: Vec = inputs.iter().map(|v| Variable::from(v.clone())).collect(); + let batch = compiled + .evaluate_batch(&contexts, EvaluationOptions::default()) + .await; + let mut wants = Vec::with_capacity(inputs.len()); + let mut batched = 0usize; + for (i, input) in inputs.iter().enumerate() { + let want = Outcome::of(walker.evaluate(Variable::from(input.clone())).await); + let got = batch.get(i).map(|r| match r { + Ok(r) => Ok(serde_json::to_string(&r.result).unwrap_or_default()), + Err(e) => Err(serde_json::to_value(&**e) + .map(|v| v.to_string()) + .unwrap_or_else(|_| e.to_string())), + }); + if got.as_ref() != Some(&want) { + batched += 1; + if samples.len() < 12 { + samples.push(format!( + "{} batch {input}\n walker {want:?}\n compiled {got:?}", + fixture.name + )); + } + } + wants.push(want); + } + let mut columnar = 0usize; + let mut compared = 0usize; + for built in Built::new(&inputs) + .into_iter() + .chain(Built::lists(&inputs)) + .chain(Built::nested(&inputs)) + { + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let output = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + for row in 0..built.rows { + let input = columns.row(row); + let want = match walker.evaluate(input.clone()).await { + Ok(r) => Ok(Built::normalized(r.result.to_value())), + Err(e) => Err(serde_json::to_value(&*e) + .map(|v| v.to_string()) + .unwrap_or_default()), + }; + let got = match &output.errors[row] { + Some(e) => Err(serde_json::to_value(&**e) + .map(|v| v.to_string()) + .unwrap_or_default()), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + compared += 1; + if got != want { + columnar += 1; + if samples.len() < 24 { + samples.push(format!( + "{} columnar {}\n walker {want:?}\n columnar {got:?}", + fixture.name, + input.to_value() + )); + } + } + } + } + if std::env::var("WIDE_SHOW").is_ok() { + let distinct: std::collections::BTreeSet = + inputs.iter().map(|v| v.to_string()).collect(); + let errors = wants.iter().filter(|w| w.is_err()).count(); + println!( + "{:44} distinct {:>4} errors {:>4} columnar-compared {:>4} first {}", + fixture.name, + distinct.len(), + errors, + compared, + inputs[0] + ); + } + report.push((fixture.name.clone(), batched, columnar, compared)); + } + let failing: Vec<&(String, usize, usize, usize)> = + report.iter().filter(|r| r.1 > 0 || r.2 > 0).collect(); + for (name, batched, columnar, compared) in &failing { + println!("{name:44} row {batched:>4}/{rows} columnar {columnar:>4}/{compared}"); + } + println!( + "wide inputs: {} fixtures, {} with mismatches", + report.len(), + failing.len() + ); + for sample in &samples { + println!("{sample}"); + } + assert!( + failing.is_empty() || std::env::var("WIDE_REPORT").is_ok(), + "{} fixtures mismatch on wide inputs", + failing.len() + ); +} + +#[tokio::test] +#[ignore] +async fn plan_census() { + let settled: Vec = std::env::var("CENSUS_SETTLED") + .ok() + .and_then(|path| fs::read_to_string(path).ok()) + .map(|text| { + text.lines() + .filter_map(|l| l.split_whitespace().next().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + let mut reasons: BTreeMap> = BTreeMap::new(); + for fixture in Fixture::load_all() { + if NETWORK_BOUND.contains(&fixture.name.as_str()) + || TIME_BOUND.contains(&fixture.name.as_str()) + || std::env::var("BENCH_FILE").is_ok_and(|f| !fixture.name.contains(f.as_str())) + { + continue; + } + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + let variants = match std::env::var("BENCH_VALID").is_ok() && !fixture.inputs.is_empty() { + true => fixture.inputs.clone(), + false => fixture.typed_variants(), + }; + let variants: Vec = match std::env::var("CENSUS_ROWS") + .ok() + .and_then(|v| v.parse::().ok()) + { + Some(rows) if !variants.is_empty() => (0..rows) + .map(|i| variants[i % variants.len()].clone()) + .collect(), + _ => variants, + }; + let Some(built) = Built::new(&variants) else { + reasons + .entry("no columns".into()) + .or_default() + .push(fixture.name.clone()); + continue; + }; + let columns = built.columns(); + let _ = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + let _ = zen_engine::diagnostics::census(); + let start = std::time::Instant::now(); + let _ = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + println!( + "CENSUS\t{}\ttotal\t1\t{}\t{}", + fixture.name, + built.rows, + start.elapsed().as_nanos() + ); + for (key, calls, rows, ns) in zen_engine::diagnostics::census() { + println!("CENSUS\t{}\t{key}\t{calls}\t{rows}\t{ns}", fixture.name); + } + let key = match compiled.plan_verdict(&columns) { + None => "not compiled".to_string(), + Some(Ok(())) => "planned".to_string(), + Some(Err(reason)) => reason, + }; + let mark = if settled.contains(&fixture.name) { + "*" + } else { + "" + }; + reasons + .entry(key) + .or_default() + .push(format!("{}{mark}", fixture.name)); + } + for (reason, names) in &reasons { + println!("{:>3} {reason}: {}", names.len(), names.join(" ")); + } +} + +#[cfg(feature = "driver")] +struct Chain; + +#[cfg(feature = "driver")] +impl Chain { + const FULLY_TYPED: &[&str] = &[ + "affiliate-commission-calculator.json", + "airline-upgrade-eligibility.json", + "auto-insurance-premium-calculator.json", + "delivery-route-optimizer.json", + "dynamic-fx-rate-pricing-system.json", + "environment-compliance-assessment.json", + ]; + + fn typed() -> bool { + support::switches().typed + } + + fn graph(nodes: Vec) -> GraphContent { + support::switches(); + let mut all = + vec![json!({"id": "input", "name": "request", "type": "inputNode", "content": {}})]; + all.extend(nodes); + all.push(json!({"id": "output", "name": "response", "type": "outputNode", "content": {}})); + let edges: Vec = all + .windows(2) + .enumerate() + .map(|(at, pair)| json!({"id": format!("e{at}"), "sourceId": pair[0]["id"], "targetId": pair[1]["id"], "type": "edge"})) + .collect(); + serde_json::from_value(json!({"nodes": all, "edges": edges})).expect("graph") + } + + fn expression(id: &str, pairs: &[(&str, &str)]) -> Value { + let expressions: Vec = pairs.iter().enumerate().map(|(at, (key, value))| json!({"id": format!("{id}-{at}"), "key": key, "value": value})).collect(); + json!({"id": id, "name": id, "type": "expressionNode", "content": {"expressions": expressions, "passThrough": true, "inputField": null, "outputPath": null, "executionMode": "single"}}) + } + + fn table(id: &str, inputs: &[&str], outputs: &[&str], rules: &[&[&str]]) -> Value { + let inputs_json: Vec = inputs + .iter() + .enumerate() + .map(|(at, field)| json!({"id": format!("i{at}"), "name": field, "field": field})) + .collect(); + let outputs_json: Vec = outputs + .iter() + .enumerate() + .map(|(at, field)| json!({"id": format!("o{at}"), "name": field, "field": field})) + .collect(); + let rules_json: Vec = rules + .iter() + .enumerate() + .map(|(at, cells)| { + let mut rule = serde_json::Map::new(); + rule.insert("_id".into(), json!(format!("r{at}"))); + for (column, cell) in cells.iter().enumerate() { + let key = match column < inputs.len() { + true => format!("i{column}"), + false => format!("o{}", column - inputs.len()), + }; + rule.insert(key, json!(cell)); + } + Value::Object(rule) + }) + .collect(); + json!({"id": id, "name": id, "type": "decisionTableNode", "content": {"hitPolicy": "first", "inputs": inputs_json, "outputs": outputs_json, "rules": rules_json, "passThrough": true, "inputField": null, "outputPath": null, "executionMode": "single"}}) + } + + async fn checked( + content: GraphContent, + rows: &[Value], + failures: &mut Vec, + ) -> (usize, usize) { + let mut compiled = Decision::from(Arc::new(content)); + compiled.compile(); + assert!( + matches!(compiled.compiled_verdict(), Some(Ok(()))), + "verdict {:?}", + compiled.compiled_verdict() + ); + let walker = compiled.interpreted(); + let built = Built::new(rows).expect("columns"); + let columns = built.columns(); + let output = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + for row in 0..built.rows { + let input = columns.row(row); + let want = match walker.evaluate(input.clone()).await { + Ok(r) => Ok(Built::normalized(r.result.to_value()).to_string()), + Err(e) => Err(serde_json::to_value(&*e) + .map(|v| v.to_string()) + .unwrap_or_default()), + }; + let got = match &output.errors[row] { + Some(e) => Err(serde_json::to_value(&**e) + .map(|v| v.to_string()) + .unwrap_or_default()), + None => Ok(Built::normalized(output.row(row).to_value()).to_string()), + }; + if got != want { + failures.push(format!( + "row {row} input {}\n walker {want:?}\n columnar {got:?}", + input.to_value() + )); + } + } + (output.paths().typed, output.paths().laned) + } + + fn rows(count: usize, seed: u64) -> Vec { + let mut noise = Noise::new(seed); + let tiers = ["gold", "silver", "bronze", "platinum"]; + (0..count) + .map(|_| { + let income = noise.below(9000) as i64 - 500; + let cents = noise.below(100); + json!({"tier": tiers[noise.below(tiers.len())], "income": income, "rate": format!("{}.{cents:02}", noise.below(5)).parse::().map(Value::Number).unwrap_or(Value::Null), "age": noise.below(90)}) + }) + .collect() + } + + fn nodes(middle: Option) -> Vec { + let mut nodes = vec![ + Self::table( + "band", + &["tier", "income"], + &["band", "factor"], + &[ + &["'gold'", "> 5000", "'high'", "1.25"], + &["'gold', 'platinum'", "", "'mid'", "1.10"], + &["", "[0..1000]", "'low'", "0.5"], + &["", "", "'none'", "1"], + ], + ), + Self::expression( + "score", + &[ + ("net", "income - 100"), + ("scaled", "$.net * factor"), + ("adult", "age >= 18"), + ("third", "$.net / 3"), + ], + ), + ]; + nodes.extend(middle); + nodes.push(Self::expression( + "final", + &[ + ("total", "scaled + rate"), + ("share", "total / 4"), + ("rich", "band == 'high' and adult"), + ("large", "third > 100 or scaled < 0"), + ], + )); + nodes + } +} + +#[cfg(feature = "driver")] +#[tokio::test] +async fn graph_typed_falls_back_per_unit() { + let mut failures = Vec::new(); + let unsupported = Chain::expression("label", &[("label", "split(tier, 'l')")]); + let (typed, laned) = Chain::checked( + Chain::graph(Chain::nodes(Some(unsupported))), + &Chain::rows(300, 3), + &mut failures, + ) + .await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); + if Chain::typed() { + assert!(typed > 0 && laned > 0, "units typed {typed}, laned {laned}"); + assert_eq!(typed + laned, 4, "units typed {typed}, laned {laned}"); + } +} + +#[cfg(feature = "driver")] +#[tokio::test] +async fn graph_typed_reads_dynamic_slots() { + let mut rows = Chain::rows(240, 5); + let odd = [ + json!({"tier": "gold", "income": "lots", "rate": 1, "age": 30}), + json!({"tier": "gold", "income": {"value": 5}, "rate": 0.5, "age": 70}), + json!({"tier": "silver", "income": 79228162514264337593543950335u128, "rate": 0, "age": 40}), + json!({"tier": "gold", "income": true, "rate": 0.25, "age": 60}), + json!({"tier": "bronze", "income": -0.0, "rate": 1.50, "age": 18}), + json!({"tier": null, "income": null, "rate": null, "age": null}), + json!({"tier": "gold", "income": 6000.50, "rate": 2, "age": 55}), + ]; + for (at, row) in odd.into_iter().enumerate() { + rows.insert(at * 31 + 3, row); + } + let nodes = vec![ + Chain::expression("pick", &[("pick", "age > 20 ? income : tier")]), + Chain::expression("half", &[("half", "income / 2")]), + Chain::table( + "level", + &["pick", "half"], + &["level"], + &[ + &["> 3000", "", "'top'"], + &["", "> 100", "'some'"], + &["", "", "'none'"], + ], + ), + Chain::expression( + "final", + &[ + ("bonus", "half * rate"), + ("big", "level == 'top' or $.bonus > 50"), + ], + ), + ]; + let mut failures = Vec::new(); + let (typed, laned) = Chain::checked(Chain::graph(nodes), &rows, &mut failures).await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); + if Chain::typed() { + assert!(typed > 0, "units typed {typed}, laned {laned}"); + } +} + +#[cfg(feature = "driver")] +#[tokio::test] +async fn graph_typed_lists_and_closures() { + let mut noise = Noise::new(17); + let tags = ["a", "vip", "b"]; + let mut rows: Vec = (0..300) + .map(|_| { + let xs: Vec = (0..noise.below(6)).map(|_| json!(format!("{}.{}", noise.below(40) as i64 - 10, noise.below(10)).parse::().map(Value::Number).unwrap_or(Value::Null))).collect(); + let tg: Vec = (0..noise.below(3)).map(|_| json!(tags[noise.below(3)])).collect(); + let items: Vec = (0..noise.below(5)) + .map(|_| { + let cells: Vec = (0..noise.below(3)).map(|_| json!({"p": noise.below(50)})).collect(); + json!({"qty": noise.below(8), "price": noise.below(500), "ok": noise.below(3) != 0, "cells": cells}) + }) + .collect(); + json!({"xs": xs, "tags": tg, "items": items, "limit": noise.below(20), "n": noise.below(12) as i64 - 3}) + }) + .collect(); + let odd = [ + json!({"xs": null, "tags": ["vip"], "items": null, "limit": 3, "n": 1}), + json!({"xs": [1, null, 3], "tags": [], "items": [], "limit": 2, "n": 3}), + json!({"xs": ["a", 2], "tags": ["b", 7], "items": [{"qty": 1, "price": 2, "ok": null, "cells": []}], "limit": 1, "n": 2}), + json!({"xs": [9223372036854775807i64, 9223372036854775807i64], "tags": ["a"], "items": [{"qty": 9223372036854775807i64, "price": 3, "ok": true, "cells": [{"p": 9223372036854775807i64}, {"p": 1}]}], "limit": 0, "n": 0}), + json!({"xs": [0.00, -0.0, 1.50], "tags": ["vip", "vip"], "items": [{"qty": 2, "price": 1.25, "ok": true, "cells": null}], "limit": null, "n": null}), + json!({"limit": 5, "n": 5}), + json!({"xs": [], "tags": null, "items": [{"qty": 3}, {"price": 4, "ok": false, "cells": [{"q": 1}]}], "limit": 1, "n": -1}), + json!({"xs": [79228162514264337593543950335u128], "tags": ["a"], "items": [{"qty": 1, "price": 0.000000001, "ok": true, "cells": [{"p": 0.5}]}], "limit": 1, "n": 1}), + ]; + for (at, row) in odd.into_iter().enumerate() { + rows.insert(at * 29 + 5, row); + } + let nodes = vec![ + Chain::expression( + "lists", + &[ + ("total", "sum(xs)"), + ("pos", "filter(xs, # > limit)"), + ("doubled", "map(xs, # * 2)"), + ("has", "n in xs"), + ("vip", "'vip' in tags"), + ("qtys", "map(filter(items, #.ok), #.qty)"), + ("ct", "count(filter(items, #.ok), #.price > limit)"), + ("cells", "sum(map(items, sum(map(#.cells, #.p))))"), + ("safe", "sum(map(items ?? [], #.qty))"), + ("copy", "xs ?? []"), + ("hit", "contains(xs, 2)"), + ], + ), + Chain::expression( + "later", + &[ + ("big", "len(filter(doubled, # > 10))"), + ("sumd", "sum(doubled)"), + ("anyq", "some(qtys, # > 3)"), + ("lo", "min(map(items, #.price))"), + ], + ), + ]; + let mut failures = Vec::new(); + let (typed, laned) = Chain::checked(Chain::graph(nodes), &rows, &mut failures).await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); + if Chain::typed() { + assert!(typed > 0, "units typed {typed}, laned {laned}"); + } +} + +#[cfg(feature = "driver")] +#[tokio::test] +async fn graph_typed_strings() { + let mut noise = Noise::new(29); + let names = [ + "Anna", + "bob", + " Cara ", + "Émile", + "straße", + "", + "İstanbul", + "日本", + "Bart", + ]; + let cities = ["Berlin", "bonn", "Anna", " x ", ""]; + let tiers = ["gold", "silver", "Gold"]; + let mut rows: Vec = (0..300) + .map(|_| { + let items: Vec = (0..noise.below(4)).map(|_| json!({"name": names[noise.below(names.len())], "qty": noise.below(9), "tag": tiers[noise.below(3)]})).collect(); + let tags: Vec = (0..noise.below(3)).map(|_| json!(cities[noise.below(cities.len())])).collect(); + let amount = format!("{}.{}", noise.below(4000) as i64 - 2000, noise.below(100)).parse::().map(Value::Number).unwrap_or(Value::Null); + json!({"name": names[noise.below(names.len())], "city": cities[noise.below(cities.len())], "tier": tiers[noise.below(3)], "amount": amount, "qty": noise.below(10), "flag": noise.below(2) == 0, "items": items, "tags": tags}) + }) + .collect(); + let long = "ab".repeat(600); + let odd = [ + json!({"name": null, "city": "Berlin", "tier": null, "amount": null, "qty": 3, "flag": null, "items": null, "tags": null}), + json!({"name": long, "city": long, "tier": "gold", "amount": 79228162514264337593543950335u128, "qty": 9223372036854775807i64, "flag": false, "items": [], "tags": []}), + json!({"name": "ß", "city": "Dž", "tier": "", "amount": -0.0, "qty": 0, "flag": true, "items": [{"name": "ß", "qty": 1, "tag": null}], "tags": ["Dž"]}), + json!({"name": "\u{1F600} x", "city": "\u{2003}a\u{2003}", "tier": "silver", "amount": 0.000000001, "qty": 6, "flag": false, "items": [{"qty": 2}], "tags": ["\u{2003}a\u{2003}"]}), + json!({"qty": 5}), + json!({"name": "Anna", "city": "Anna", "tier": "gold", "amount": 1.50, "qty": 8, "flag": true, "items": [{"name": "gold", "qty": 9223372036854775807i64, "tag": "gold"}], "tags": ["Anna", "x"]}), + json!({"name": "", "city": "", "tier": "silver", "amount": 0.00, "qty": 2, "flag": true, "items": [{"name": "", "qty": 0}], "tags": [""]}), + ]; + for (at, row) in odd.into_iter().enumerate() { + rows.insert(at * 31 + 2, row); + } + let nodes = vec![ + Chain::expression( + "texts", + &[ + ("s", "string(amount)"), + ("tpl", "`${name}-${qty}:${amount} ${flag}`"), + ("cat", "name + '/' + city"), + ("up", "upper(name)"), + ("lo", "lower(city)"), + ("tr", "trim(name)"), + ("has", "contains(lower(name), 'an')"), + ("tierz", "tier ?? 'none'"), + ("pick", "qty > 4 ? name : 'nobody'"), + ("same", "name == city"), + ("pass", "city"), + ("rx", "matches(name, '^[A-Z]')"), + ("names", "map(items, #.name)"), + ("upn", "map(items, upper(#.name) + string(#.qty))"), + ("cnt", "count(items, #.name == tier)"), + ("intag", "city in tags"), + ("big", "string(amount * 1000000000000)"), + ("mixeq", "name == qty"), + ], + ), + Chain::table( + "level", + &["qty", "tierz"], + &["level", "who"], + &[ + &["> 7", "'gold'", "'top'", "name"], + &["> 3", "", "'mid'", "city"], + &["", "", "'low'", "'nobody'"], + ], + ), + Chain::expression( + "later", + &[ + ("again", "upper(tierz) + '!'"), + ("g", "tierz in ['gold', 'none']"), + ("l", "len(cat)"), + ("w", "level + ':' + (who ?? '-')"), + ], + ), + ]; + let mut failures = Vec::new(); + let (typed, laned) = Chain::checked(Chain::graph(nodes.clone()), &rows, &mut failures).await; + eprintln!("strings typed {typed} laned {laned}"); + if Chain::typed() { + assert!(typed > laned, "units typed {typed}, laned {laned}"); + } + rows.insert(12, json!({"name": "q", "city": "q", "tier": "gold", "amount": 1, "qty": 2, "flag": true, "items": [{"name": null, "qty": 2}], "tags": [null]})); + rows.insert(9, json!({"name": 7, "city": true, "tier": 1.5, "amount": "x", "qty": 1, "flag": true, "items": [{"name": 3, "qty": "a"}], "tags": [1]})); + Chain::checked(Chain::graph(nodes), &rows, &mut failures).await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[cfg(feature = "driver")] +#[tokio::test] +async fn graph_typed_dates() { + Reference::prepare(Outcome::CLOCK); + let mut noise = Noise::new(31); + let days = [ + "2024-01-15", + "2024-02-29", + "2023-12-31 23:59:59", + "2024-03-31T01:30:00Z", + "2025-03-30 02:30:00", + "2024-10-27 02:30:00", + "1900-01-01", + "9999-12-31", + "2024-06-15T12:00:00+05:30", + "2024-06-15T12:00:00.123456789Z", + "20240115", + "2024/01/15", + "2024", + "2024-07", + "2025-01-31", + "2025-08-19", + ]; + let bad = ["nope", "", "2024-02-30", "2024-13-01"]; + let day = |noise: &mut Noise| match noise.below(12) { + 0 => json!(bad[noise.below(bad.len())]), + 1 => Value::Null, + _ => json!(days[noise.below(days.len())]), + }; + let mut rows: Vec = (0..300) + .map(|_| { + let items: Vec = (0..noise.below(4)).map(|_| json!({"on": day(&mut noise), "gb": noise.below(9)})).collect(); + json!({"at": day(&mut noise), "other": day(&mut noise), "ms": noise.below(2_000_000_000) as i64 * 1000 - 1_000_000_000_000, "n": noise.below(7), "items": items}) + }) + .collect(); + let odd = [ + json!({"at": "0001-01-01", "other": "9999-12-31 23:59:59", "ms": 9223372036854775807i64, "n": 0, "items": []}), + json!({"at": null, "other": null, "ms": null, "n": 3, "items": [{"on": null, "gb": 1}]}), + json!({"at": "2024-02-29", "other": "2024-02-29T00:00:00Z", "ms": -0.0, "n": 6, "items": [{"on": "2024-02-29", "gb": 2}]}), + json!({"at": "Europe/Berlin", "other": "UTC", "ms": 1.5, "n": 1, "items": null}), + ]; + for (at, row) in odd.into_iter().enumerate() { + rows.insert(at * 41 + 3, row); + } + let nodes = vec![ + Chain::expression( + "dates", + &[ + ("p", "d(at)"), + ("ps", "string(d(at))"), + ("m", "d(ms)"), + ("y", "d(at).year()"), + ("add", "d(at).add(1, 'month')"), + ("addn", "d(at).add(n, 'day')"), + ("som", "d(at).startOf('month')"), + ("fmt", "d(at).format('%Y-%m-%d %H:%M')"), + ("diff", "d(at).diff(other, 'day')"), + ("bef", "d(at).isBefore(d('2024-03-01'))"), + ("same", "d(at).isSame(d(other), 'month')"), + ("lt", "d(at) < d(other)"), + ("eqs", "d(at) == other"), + ("inl", "d(at) in [d('2024-01-15'), '2024-02-29']"), + ("rng", "d(at) in [d('2024-01-01')..d('2024-12-31')]"), + ("tpl", "`at ${d(at)}`"), + ("now", "d().diff(d(at), 'year')"), + ("cnt", "count(items, d(#.on).isAfter(d(at)))"), + ("dts", "map(items, d(#.on).add(1, 'd'))"), + ("mm", "max([d(at), d(other)])"), + ("leg", "date('2024-01-01') + year('2024-06-30')"), + ], + ), + Chain::table( + "band", + &["at"], + &["band", "since"], + &[ + &["< d('2000-01-01')", "'old'", "d('1999-12-31')"], + &["d($).isValid() == false", "'bad'", "null"], + &["", "'mid'", "d(at)"], + ], + ), + Chain::expression( + "later", + &[ + ("again", "p.add(1, 'd')"), + ("s", "string(add)"), + ("old", "since == null or since < d()"), + ], + ), + ]; + let mut failures = Vec::new(); + let (typed, laned) = Chain::checked(Chain::graph(nodes.clone()), &rows, &mut failures).await; + eprintln!("dates typed {typed} laned {laned}"); + if Chain::typed() { + assert!(typed > laned, "units typed {typed}, laned {laned}"); + } + let faulty = vec![Chain::expression( + "faulty", + &[ + ("lts", "d(at) < other"), + ("cat", "'D:' + d(at)"), + ("mx", "max(map(items, d(#.on)))"), + ("legd", "dateString(at)"), + ], + )]; + Chain::checked(Chain::graph(faulty), &rows, &mut failures).await; + rows.insert( + 12, + json!({"at": 5, "other": true, "ms": "x", "n": 1, "items": [{"on": 3}]}), + ); + Chain::checked(Chain::graph(nodes), &rows, &mut failures).await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[cfg(feature = "driver")] +#[tokio::test] +async fn graph_typed_extremes() { + let mut rows = Chain::rows(200, 9); + let odd = [ + json!({"tier": "gold", "income": 9223372036854775807i64, "rate": 1, "age": 30}), + json!({"tier": "gold", "income": -9223372036854775807i64, "rate": 0.5, "age": 30}), + json!({"tier": "silver", "income": 79228162514264337593543950335u128, "rate": 0, "age": 40}), + json!({"tier": "gold", "income": 12.5, "rate": 0.000000001, "age": 18}), + json!({"tier": "gold", "income": 0.00, "rate": 0.00, "age": 17}), + json!({"tier": "bronze", "income": -0.0, "rate": 1.50, "age": 18}), + json!({"tier": null, "income": null, "rate": null, "age": null}), + json!({"tier": "platinum", "income": 1000, "rate": 3.333, "age": 0}), + json!({"tier": "", "income": 1000.000, "rate": 2.10, "age": 65}), + json!({"income": 7, "age": 5}), + json!({"tier": "gold", "income": 5000.01, "rate": 0.1, "age": 90}), + json!({"tier": "gold", "income": 100, "rate": 0.3333333333333333333333333333, "age": 20}), + ]; + for (at, row) in odd.into_iter().enumerate() { + rows.insert(at * 13 + 4, row); + } + let mut failures = Vec::new(); + let (typed, laned) = + Chain::checked(Chain::graph(Chain::nodes(None)), &rows, &mut failures).await; + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); + if Chain::typed() { + assert!(typed > 0, "units typed {typed}, laned {laned}"); + assert_eq!(typed + laned, 3, "units typed {typed}, laned {laned}"); + } +} + +#[cfg(feature = "driver")] +#[tokio::test] +async fn graph_fixtures_are_fully_typed() { + Reference::prepare(Outcome::CLOCK); + let mut failures = Vec::new(); + let fixtures: Vec = Fixture::load_all() + .into_iter() + .filter(|f| Chain::FULLY_TYPED.contains(&f.name.as_str())) + .collect(); + assert_eq!(fixtures.len(), Chain::FULLY_TYPED.len(), "fixtures found"); + for fixture in fixtures { + let variants = fixture.typed_variants(); + let rows: Vec = (0..256) + .map(|at| variants[at % variants.len()].clone()) + .collect(); + let (typed, laned) = Chain::checked(fixture.content.clone(), &rows, &mut failures).await; + if Chain::typed() { + assert!( + typed > 0 && laned == 0, + "{}: units typed {typed}, laned {laned}", + fixture.name + ); + } + } + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} diff --git a/core/engine/tests/compiled_policy.rs b/core/engine/tests/compiled_policy.rs new file mode 100644 index 00000000..3b540219 --- /dev/null +++ b/core/engine/tests/compiled_policy.rs @@ -0,0 +1,1713 @@ +#[allow(dead_code)] +mod conformance; +#[allow(dead_code)] +#[path = "support/policies.rs"] +mod policies; +#[path = "support/policy_gen.rs"] +mod policy_gen; +mod support; + +use policies::{Anchor, Batch, Generated, PolicyCase}; +use policy_gen::{Gen, Rng}; +#[cfg(feature = "driver")] +use serde_json::json; +use serde_json::Value; +use std::sync::Arc; +use support::columns::Built; +use support::golden::{Canon, Live, Outcome, Reference}; +use zen_engine::policy::{EvaluateRequest, EvaluationError, EvaluationResult, PolicyWorkspace}; +use zen_expression::Variable; + +struct Differential { + reference: Reference, + compared: usize, + succeeded: usize, + failures: Vec, + kinds: std::collections::BTreeMap, +} + +impl Differential { + fn new(reference: Reference) -> Differential { + Differential { + reference, + compared: 0, + succeeded: 0, + failures: Vec::new(), + kinds: Default::default(), + } + } + + fn shape(result: &Result) -> Result { + match result { + Ok(result) => Ok(result.output.clone().into()), + Err(error) => Err(Reference::debug(error)), + } + } + + fn recorded(outcome: &Outcome) -> Result { + match outcome { + Outcome::Ok(value) => Ok(Canon::restore(value).into()), + Outcome::Err { debug, .. } => Err(debug.clone()), + } + } + + #[cfg(feature = "driver")] + fn request(path: &str, input: &Value) -> EvaluateRequest { + Self::with_goals(path, input, &[]) + } + + fn with_goals(path: &str, input: &Value, goals: &[String]) -> EvaluateRequest { + EvaluateRequest { + policy_path: Arc::from(path), + input: Variable::from(input.clone()), + goals: goals.iter().map(|g| Arc::from(g.as_str())).collect(), + trace: false, + } + } + + fn driver( + &self, + suite: &str, + ws: &PolicyWorkspace, + path: &str, + input: &Value, + goals: &[String], + ) -> Result { + self.reference.policy( + || Canon::key(suite, goals, &Variable::from(input.clone())), + || Self::shape(&Live::policy(ws, &Self::with_goals(path, input, goals))), + Self::recorded, + ) + } + + fn computed( + &self, + suite: &str, + ws: &PolicyWorkspace, + path: &str, + inputs: &[Value], + ) -> Vec { + inputs + .iter() + .find_map(|input| { + self.driver(suite, ws, path, input, &[]) + .ok() + .map(|output| PolicyCase::computed(&output, input)) + }) + .unwrap_or_default() + } + + fn run(&mut self, label: &str, ws: &PolicyWorkspace, path: &str, inputs: &[Value]) { + let computed = self.computed(label, ws, path, inputs); + let requests: Vec = inputs + .iter() + .enumerate() + .map(|(i, input)| Self::with_goals(path, input, &PolicyCase::goals(&computed, i))) + .collect(); + let batch = ws.evaluate_batch(&requests); + for (i, (input, batched)) in inputs.iter().zip(&batch).enumerate() { + let goals = PolicyCase::goals(&computed, i); + let want = self.driver(label, ws, path, input, &goals); + let single = Self::shape(&ws.evaluate(&Self::with_goals(path, input, &goals))); + let batched = Self::shape(batched); + self.compared += 1; + self.succeeded += usize::from(want.is_ok()); + if let Err(error) = &want { + let kind: String = error.chars().take_while(|c| c.is_alphanumeric()).collect(); + *self.kinds.entry(kind).or_default() += 1; + } + if self + .reference + .ordered(|| Canon::key(label, &goals, &Variable::from(input.clone()))) + { + continue; + } + if single != want { + self.failures.push(format!( + "{label} single {input}\n driver {want:?}\n compiled {single:?}" + )); + } + if batched != want { + self.failures.push(format!( + "{label} batch {input}\n driver {want:?}\n compiled {batched:?}" + )); + } + } + } + + fn finish(mut self) { + self.failures.extend(self.reference.missing()); + println!( + "compared {} inputs, {} evaluated without error, errors {:?}", + self.compared, self.succeeded, self.kinds + ); + assert!( + self.failures.is_empty(), + "{} mismatches:\n{}", + self.failures.len(), + self.failures + .iter() + .take(15) + .cloned() + .collect::>() + .join("\n") + ); + } +} + +#[test] +fn compiled_policies_match_the_driver_on_fixtures() { + if Reference::unavailable("policy-fixtures") { + return; + } + let mut differential = Differential::new(Reference::open("policy-fixtures")); + for case in PolicyCase::load_all() { + differential.run(&case.name, &case.workspace, &case.path, &case.inputs); + } + differential.finish(); +} + +#[test] +fn compiled_policies_match_the_driver_on_generated_documents() { + if Reference::unavailable("generated/policy") { + return; + } + let mut differential = Differential::new(Reference::open("generated/policy")); + for seed in 0..Generated::seeds() { + let Some(ws) = Generated::workspace(seed) else { + continue; + }; + let inputs = Generated::inputs(seed); + let label = Generated::label(seed); + if differential.reference.stale( + || Canon::key(&label, &[], &Variable::from(inputs[0].clone())), + &Generated::fingerprint(seed), + ) { + differential.failures.push(format!( + "{label}: generated document changed since the goldens were recorded" + )); + } + differential.run(&label, &ws, Generated::PATH, &inputs); + Columnar::check( + &differential.reference, + &label, + &ws, + &inputs, + &mut differential.failures, + ); + } + differential.finish(); +} + +struct Columnar; + +impl Columnar { + fn check( + reference: &Reference, + label: &str, + ws: &PolicyWorkspace, + inputs: &[Value], + failures: &mut Vec, + ) { + for built in Built::new(inputs).into_iter().chain(Built::lists(inputs)) { + Self::compare(reference, label, ws, &built.columns(), failures); + } + if let Some(built) = Built::nested(inputs) { + let fields = built.fields(); + let structs = built.structs(&fields); + Self::compare( + reference, + label, + ws, + &built.columns_with(&structs), + failures, + ); + } + } + + fn compare( + reference: &Reference, + label: &str, + ws: &PolicyWorkspace, + columns: &zen_expression::lane::Columns, + failures: &mut Vec, + ) { + let Ok(output) = ws.evaluate_columns(&Arc::from(Generated::PATH), &[], columns) else { + return; + }; + for row in 0..columns.rows { + let input = columns.row(row); + let request = EvaluateRequest { + policy_path: Arc::from(Generated::PATH), + input: input.depth_clone(64), + goals: Vec::new(), + trace: false, + }; + let want = reference.policy( + || Canon::key(label, &[], &input), + || { + Live::policy(&ws, &request) + .map(|r| Built::normalized(r.output.to_value())) + .map_err(|e| format!("{e:?}")) + }, + |outcome| Differential::recorded(outcome).map(Built::normalized), + ); + let got = match output.errors[row] + .as_deref() + .and_then(zen_engine::EvaluationError::policy) + { + Some(error) => Err(Reference::debug(error)), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + if got != want && !reference.ordered(|| Canon::key(label, &[], &input)) { + failures.push(format!( + "{label} columnar row {row} input {}\n driver {want:?}\n columnar {got:?}", + input.to_value() + )); + } + } + } +} + +#[cfg(feature = "driver")] +#[test] +#[ignore] +fn compiled_policy_throughput() { + let rows: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(256); + let seeds: u64 = std::env::var("POLICY_SEEDS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(40); + let time = |elapsed: std::time::Duration| elapsed.as_nanos() as f64 / rows as f64; + let mut ratios: Vec<(f64, f64, f64)> = Vec::new(); + for seed in 0..seeds { + let mut ws = PolicyWorkspace::new(); + let Ok(parsed) = serde_json::from_value(Gen::document(seed)) else { + continue; + }; + ws.set_policy("generated.json", parsed); + let mut rng = Rng(seed.wrapping_mul(7919) | 1); + let requests: Vec = (0..rows) + .map(|_| Differential::request("generated.json", &Gen::valid_input(&mut rng))) + .collect(); + if let Ok(profile) = std::env::var("BENCH_PROFILE") { + let until = std::time::Instant::now() + + std::time::Duration::from_secs(profile.parse().unwrap_or(1)); + while std::time::Instant::now() < until { + match std::env::var("BENCH_MODE").as_deref() { + Ok("single") => requests.iter().for_each(|r| drop(ws.evaluate(r))), + Ok("columns") => { + if let Some(columns) = Built::new( + &requests + .iter() + .map(|r| r.input.to_value()) + .collect::>(), + ) + .as_ref() + .map(Built::columns) + { + drop(ws.evaluate_columns(&Arc::from("generated.json"), &[], &columns)); + } + } + _ => drop(ws.evaluate_batch(&requests)), + } + } + continue; + } + let values: Vec = requests.iter().map(|r| r.input.to_value()).collect(); + let built = Built::new(&values); + let mut best = [f64::MAX; 4]; + let fresh = || -> Vec { + requests + .iter() + .map(|r| EvaluateRequest { + input: r.input.depth_clone(usize::MAX), + ..r.clone() + }) + .collect() + }; + for _ in 0..5 { + let batch = fresh(); + let start = std::time::Instant::now(); + batch.iter().for_each(|r| drop(ws.evaluate_with_driver(r))); + best[0] = best[0].min(time(start.elapsed())); + let batch = fresh(); + let start = std::time::Instant::now(); + batch.iter().for_each(|r| drop(ws.evaluate(r))); + best[1] = best[1].min(time(start.elapsed())); + let batch = fresh(); + let start = std::time::Instant::now(); + drop(ws.evaluate_batch(&batch)); + best[2] = best[2].min(time(start.elapsed())); + if let Some(columns) = built.as_ref().map(Built::columns) { + let start = std::time::Instant::now(); + drop(ws.evaluate_columns(&Arc::from("generated.json"), &[], &columns)); + best[3] = best[3].min(time(start.elapsed())); + } + } + println!("seed {seed:3} driver {:>8.0} single {:>8.0} batch {:>8.0} columns {:>8.0} {:.2}x {:.2}x {:.2}x", best[0], best[1], best[2], best[3], best[0] / best[1], best[0] / best[2], best[0] / best[3]); + ratios.push((best[0] / best[1], best[0] / best[2], best[0] / best[3])); + } + let gm = |f: fn(&(f64, f64, f64)) -> f64| { + (ratios.iter().map(|r| f(r).ln()).sum::() / ratios.len() as f64).exp() + }; + let mut columnar: Vec = ratios.iter().map(|r| r.2).collect(); + columnar.sort_by(f64::total_cmp); + println!( + "single: geomean {:.2}x | batch: geomean {:.2}x | columns: geomean {:.2}x median {:.2}x", + gm(|r| r.0), + gm(|r| r.1), + gm(|r| r.2), + columnar + .get(columnar.len() / 2) + .copied() + .unwrap_or_default() + ); +} + +#[tokio::test] +async fn engine_batch_matches_single_evaluations() { + use zen_engine::loader::MemoryLoader; + use zen_engine::model::{DecisionContent, PolicyContent}; + use zen_engine::{DecisionEngine, EvaluationOptions}; + + let loader = Arc::new(MemoryLoader::default()); + let mut rng = Rng(11); + let document = serde_json::from_value(Gen::document(3)).expect("policy document"); + loader.add( + "policy", + DecisionContent::Policy(PolicyContent(Arc::new(document))), + ); + let graph: DecisionContent = serde_json::from_str( + &std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../test-data/graphs/loan-approval.json" + )) + .or_else(|_| { + std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../test-data/loan-approval.json" + )) + }) + .expect("graph fixture"), + ) + .expect("graph content"); + loader.add("graph", graph); + let contexts: Vec = (0..40) + .map(|i| match i % 2 { + 0 => Variable::from(Gen::valid_input(&mut rng)), + _ => Variable::from(Gen::input(&mut rng)), + }) + .collect(); + let engine = DecisionEngine::default().with_loader(loader); + for compiled in [false, true] { + if compiled { + engine.compile(); + } + for key in ["policy", "graph"] { + let fresh: Vec = contexts.iter().map(Variable::deep_clone).collect(); + let batch = engine + .evaluate_batch(key, &fresh, EvaluationOptions::default()) + .await; + assert_eq!(batch.len(), contexts.len()); + for (context, batched) in contexts.iter().zip(batch) { + let single = engine + .evaluate_with_opts(key, context.deep_clone(), EvaluationOptions::default()) + .await; + let shape = |r: Result< + zen_engine::DecisionGraphResponse, + Box, + >| { + r.map(|r| r.result.to_value()).map_err(|e| e.to_string()) + }; + assert_eq!( + shape(batched), + shape(single), + "{key} compiled={compiled} {context:?}" + ); + } + } + } +} + +impl Anchor { + #[cfg(feature = "driver")] + const PROGRAMS: [(&'static str, &'static str); 8] = [ + ("fee", "account.balance * customer.rate / 100 * (account.kind == 'loan' ? 2 : 1)"), + ("label", "account.kind == 'savings' ? 'S' : (account.kind == 'checking' ? 'C' : 'L')"), + ("total", "sum(map(filter(customer.accounts, #.active), #.balance))"), + ("fees", "sum(map(customer.accounts, #.fee))"), + ("risk", "customer.total > customer.income * 2 ? 'high' : (customer.total > customer.income ? 'mid' : 'low')"), + ("discount", "customer.tier == 'gold' and customer.risk == 'low' ? 0.15 : (customer.tier == 'gold' and customer.risk == 'mid' ? 0.1 : (customer.tier == 'silver' and customer.risk == 'low' ? 0.1 : (customer.tier == 'silver' and customer.risk == 'mid' ? 0.05 : (customer.risk == 'low' ? 0.02 : 0))))"), + ("net", "customer.total - customer.fees - customer.discount"), + ("eligible", "customer.age >= 18 and customer.risk != 'high'"), + ]; + + #[cfg(feature = "driver")] + const KEYS: [&'static str; 8] = [ + "account.fee", + "account.label", + "customer.total", + "customer.fees", + "customer.risk", + "customer.discount", + "customer.net", + "customer.eligible", + ]; + + #[cfg(feature = "driver")] + fn fused( + columns: &zen_expression::lane::Columns, + programs: &mut Vec>, + runner: &mut zen_expression::lane::LaneRunner, + stages: &mut [f64; 2], + ) -> Option> { + use zen_expression::lane::{Column, Columns, Dictionary, LaneProgram, Output, Values}; + let rows = columns.rows; + let find = |path: &str| columns.find(path).map(|i| columns.columns[i].1); + let (accounts, rate) = (find("customer.accounts")?, find("customer.rate")?); + let Values::List { + offsets, + child: Dictionary::Column(record), + } = accounts.values + else { + return None; + }; + let parent: Vec = (0..rows) + .flat_map(|row| { + let (a, b) = (offsets[row] as usize, offsets[row + 1] as usize); + std::iter::repeat_n(row, b - a) + }) + .collect(); + let gathered: Vec = parent + .iter() + .map(|p| rate.number(*p).unwrap_or_default()) + .collect(); + let field = |name: &str| record.field(name).copied(); + let (balance, kind, active) = (field("balance")?, field("kind")?, field("active")?); + let child = Columns::new(parent.len()) + .column("account.balance", balance) + .column("account.kind", kind) + .column("account.active", active) + .column("customer.rate", Column::new(Values::Dec(&gathered))); + let mut run = |index: usize, + range: std::ops::Range, + columns: &Columns, + outs: &mut Vec, + stages: &mut [f64; 2]| { + let start = std::time::Instant::now(); + let program = programs[index].get_or_insert_with(|| { + let entries: Vec = range + .clone() + .map(|i| zen_expression::lane::Fusion::Output { + key: Self::KEYS[i].to_string(), + source: std::env::var(format!("ANCHOR_SOURCE_{i}")) + .unwrap_or_else(|_| Self::PROGRAMS[i].1.to_string()), + }) + .collect(); + let generic = LaneProgram::compile_fused(&entries).expect("fused program"); + let program = generic.specialize_columns(columns).unwrap_or(generic); + if std::env::var("ANCHOR_DUMP").is_ok() { + eprintln!("== fused {index}\n{:#?}", program.program().steps); + } + program + }); + runner.evaluate_columns_many(program, columns, outs, |_, _, _| {}); + stages[index] += start.elapsed().as_nanos() as f64 / rows as f64; + }; + let mut member: Vec = (0..2).map(|_| Output::new()).collect(); + member[1].prefer_codes(); + run(0, 0..2, &child, &mut member, stages); + let [fee, label] = &member[..] else { + return None; + }; + let label_offsets: Vec = label.offsets().iter().map(|o| *o as i32).collect(); + let label_column = match label.codes() { + Some((keys, offsets, data)) => Column::new(Values::Dict { + keys, + values: Dictionary::Text { offsets, data }, + }), + None => Column::new(Values::Utf8 { + offsets: &label_offsets, + data: label.data(), + }), + }; + let fields = [ + ("balance", balance), + ("kind", kind), + ("active", active), + ( + "fee", + Column::new(Values::Scaled { + mant: fee.mantissas(), + scale: fee.scales(), + }), + ), + ("label", label_column), + ]; + let composed = Column::new(Values::Struct { + fields: &fields, + len: parent.len(), + }); + let list = Column::new(Values::List { + offsets, + child: Dictionary::Column(&composed), + }); + let mut root = Columns::new(rows).column("customer.accounts", list); + for path in ["customer.age", "customer.income", "customer.tier"] { + if let Some(column) = find(path) { + root = root.column(path, column); + } + } + let mut outs: Vec = (0..6).map(|_| Output::new()).collect(); + outs[2].prefer_codes(); + run(1, 2..8, &root, &mut outs, stages); + let check = std::env::var("ANCHOR_CHECK").is_ok(); + check.then(|| { + (0..rows) + .map(|row| { + let values: Vec = outs + .iter() + .map(|o| { + o.variable(row) + .and_then(Result::ok) + .map_or(Value::Null, |v| Built::normalized(v.to_value())) + }) + .collect(); + json!(values) + }) + .collect() + }) + } + + fn check( + reference: &Reference, + suite: &str, + ws: &PolicyWorkspace, + columns: &zen_expression::lane::Columns, + failures: &mut Vec, + ) -> (usize, usize, usize) { + let output = ws + .evaluate_columns(&Arc::from(Anchor::PATH), &[], columns) + .expect("columnar"); + for row in 0..columns.rows { + let input = columns.row(row); + let request = EvaluateRequest { + policy_path: Arc::from(Anchor::PATH), + input: input.depth_clone(64), + goals: Vec::new(), + trace: false, + }; + let want = reference.policy( + || Canon::key(suite, &[], &input), + || { + Live::policy(&ws, &request) + .map(|r| Built::normalized(r.output.to_value())) + .map_err(|e| format!("{e:?}")) + }, + |outcome| Differential::recorded(outcome).map(Built::normalized), + ); + let got = match output.errors[row] + .as_deref() + .and_then(zen_engine::EvaluationError::policy) + { + Some(error) => Err(Reference::debug(error)), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + if got != want && !reference.ordered(|| Canon::key(suite, &[], &input)) { + failures.push(format!( + "row {row} input {}\n driver {want:?}\n columnar {got:?}", + input.to_value() + )); + } + } + ( + output.paths().typed, + output.paths().laned, + output.paths().hosted, + ) + } + + fn time(rows: usize, mut f: impl FnMut() -> f64) -> f64 { + (0..7).map(|_| f()).fold(f64::MAX, f64::min) / rows as f64 + } + + fn clock(f: impl FnOnce()) -> f64 { + let start = std::time::Instant::now(); + f(); + start.elapsed().as_nanos() as f64 + } + + fn fresh(rows: &[Variable]) -> Vec { + rows.iter() + .map(|r| EvaluateRequest { + policy_path: Arc::from("anchor"), + input: r.depth_clone(usize::MAX), + goals: Vec::new(), + trace: false, + }) + .collect() + } + + #[cfg(feature = "driver")] + fn floor( + columns: &zen_expression::lane::Columns, + programs: &mut Vec>, + runner: &mut zen_expression::lane::LaneRunner, + stages: &mut [f64; 8], + ) { + use zen_expression::lane::{Column, Columns, Dictionary, LaneProgram, Output, Values}; + let rows = columns.rows; + let find = |path: &str| columns.find(path).map(|i| columns.columns[i].1); + let (Some(accounts), Some(rate)) = (find("customer.accounts"), find("customer.rate")) + else { + return; + }; + let Values::List { + offsets, + child: Dictionary::Column(record), + } = accounts.values + else { + return; + }; + let parent: Vec = (0..rows) + .flat_map(|row| { + let (a, b) = (offsets[row] as usize, offsets[row + 1] as usize); + std::iter::repeat_n(row, b - a) + }) + .collect(); + let gathered: Vec = parent + .iter() + .map(|p| rate.number(*p).unwrap_or_default()) + .collect(); + let field = |name: &str| record.field(name).copied(); + let (Some(balance), Some(kind), Some(active)) = + (field("balance"), field("kind"), field("active")) + else { + return; + }; + + let child = Columns::new(parent.len()) + .column("account.balance", balance) + .column("account.kind", kind) + .column("account.active", active) + .column("customer.rate", Column::new(Values::Dec(&gathered))); + let mut run = |index: usize, columns: &Columns, out: &mut Output, stages: &mut [f64; 8]| { + let start = std::time::Instant::now(); + let program = programs[index].get_or_insert_with(|| { + let source = std::env::var(format!("ANCHOR_SOURCE_{index}")) + .unwrap_or_else(|_| Self::PROGRAMS[index].1.to_string()); + let generic = LaneProgram::standard(&source).expect("program"); + let program = generic.specialize_columns(columns).unwrap_or(generic); + if std::env::var("ANCHOR_DUMP").is_ok() { + eprintln!( + "== {}\n{:#?}", + Self::PROGRAMS[index].0, + program.program().steps + ); + } + program + }); + let repeat = match std::env::var("ANCHOR_REPEAT") + .ok() + .and_then(|v| v.parse::().ok()) + { + Some(only) if only == index => 50, + _ => 1, + }; + for _ in 0..repeat { + runner.evaluate_columns_into(program, columns, out); + } + stages[index] += start.elapsed().as_nanos() as f64 / rows as f64 / repeat as f64; + }; + let mut outs: Vec = (0..8).map(|_| Output::new()).collect(); + outs[1].prefer_codes(); + outs[4].prefer_codes(); + let [fee, label, total, fees, risk, discount, net, eligible] = &mut outs[..] else { + return; + }; + run(0, &child, fee, stages); + run(1, &child, label, stages); + let label_offsets: Vec = label.offsets().iter().map(|o| *o as i32).collect(); + let label_column = match label.codes() { + Some((keys, offsets, data)) => Column::new(Values::Dict { + keys, + values: Dictionary::Text { offsets, data }, + }), + None => Column::new(Values::Utf8 { + offsets: &label_offsets, + data: label.data(), + }), + }; + let fields = [ + ("balance", balance), + ("kind", kind), + ("active", active), + ( + "fee", + Column::new(Values::Scaled { + mant: fee.mantissas(), + scale: fee.scales(), + }), + ), + ("label", label_column), + ]; + let composed = Column::new(Values::Struct { + fields: &fields, + len: parent.len(), + }); + let list = Column::new(Values::List { + offsets, + child: Dictionary::Column(&composed), + }); + let mut root = Columns::new(rows).column("customer.accounts", list); + for path in ["customer.age", "customer.income", "customer.tier"] { + if let Some(column) = find(path) { + root = root.column(path, column); + } + } + run(2, &root, total, stages); + run(3, &root, fees, stages); + let root = root + .column( + "customer.total", + Column::new(Values::Scaled { + mant: total.mantissas(), + scale: total.scales(), + }), + ) + .column( + "customer.fees", + Column::new(Values::Scaled { + mant: fees.mantissas(), + scale: fees.scales(), + }), + ); + run(4, &root, risk, stages); + let risk_offsets: Vec = risk.offsets().iter().map(|o| *o as i32).collect(); + let risk_column = match risk.codes() { + Some((keys, offsets, data)) => Column::new(Values::Dict { + keys, + values: Dictionary::Text { offsets, data }, + }), + None => Column::new(Values::Utf8 { + offsets: &risk_offsets, + data: risk.data(), + }), + }; + let root = root.column("customer.risk", risk_column); + run(5, &root, discount, stages); + let root = root.column( + "customer.discount", + Column::new(Values::Scaled { + mant: discount.mantissas(), + scale: discount.scales(), + }), + ); + run(6, &root, net, stages); + run(7, &root, eligible, stages); + } +} + +impl Batch { + fn checked( + &self, + reference: &Reference, + ws: &PolicyWorkspace, + failures: &mut Vec, + ) -> Vec<(usize, usize, usize)> { + let mut counts = Vec::new(); + let built = Built::new(&self.values).expect("flat columns"); + counts.push(Anchor::check( + reference, + self.suite, + ws, + &built.columns(), + failures, + )); + if let Some(built) = Built::nested(&self.values) { + let fields = built.fields(); + let structs = built.structs(&fields); + counts.push(Anchor::check( + reference, + self.suite, + ws, + &built.columns_with(&structs), + failures, + )); + } + counts + } +} + +#[cfg(feature = "driver")] +#[test] +fn policy_columnar_shredded_irregular_lists() { + let mut values = Anchor::rows(96, 11); + let odd = [ + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": -0.0, "accounts": [{"balance": 3, "kind": "loan", "active": true}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": []}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"balance": 10, "kind": "loan"}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"balance": 10, "kind": "loan", "active": null}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"balance": "100", "kind": "savings", "active": true}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"balance": 5, "kind": "savings", "active": true, "note": "x"}, {"balance": 7, "kind": "loan", "active": false}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": "oops"}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [1, 2]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"a.b": 1, "balance": 3, "kind": "loan", "active": true}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"balance": 1e30, "kind": "loan", "active": true}, {"balance": -0.0, "kind": "loan", "active": true}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [null]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"balance": 2, "kind": "checking", "active": true, "meta": {"x": 1}, "tags": [1, "a"]}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"balance": 12.5, "kind": "checking", "active": true}, {"kind": "savings", "balance": 0.000000001, "active": true}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{"balance": 4, "kind": 3, "active": "yes"}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": [{}]}}), + ]; + for (at, row) in odd.into_iter().enumerate() { + values.insert(at * 6 + 1, row); + } + let ws = Anchor::workspace(); + let built = Built::new(&values).expect("flat columns"); + let columns = built.columns(); + let at = columns.find("customer.accounts").expect("accounts column"); + let mut cells: Vec = (0..columns.rows) + .map(|row| columns.columns[at].1.variable(row)) + .collect(); + let mut valid = vec![0u64; columns.rows.div_ceil(64)]; + (0..columns.rows) + .filter(|&row| columns.columns[at].1.valid(row)) + .for_each(|row| valid[row / 64] |= 1 << (row % 64)); + for row in [3usize, 40] { + cells[row] = Variable::Null; + valid[row / 64] |= 1 << (row % 64); + } + let mut nulled = zen_expression::lane::Columns::new(columns.rows); + for (index, (path, column)) in columns.columns.iter().enumerate() { + nulled = match index == at { + true => nulled.column( + path, + zen_expression::lane::Column::with_validity( + zen_expression::lane::Values::Any(&cells), + &valid, + 0, + ), + ), + false => nulled.column(path, *column), + }; + } + let mut failures = Vec::new(); + for columns in [&columns, &nulled] { + let output = ws + .evaluate_columns(&Arc::from("anchor"), &[], columns) + .expect("columnar"); + for row in 0..columns.rows { + let request = EvaluateRequest { + policy_path: Arc::from("anchor"), + input: columns.row(row), + goals: Vec::new(), + trace: false, + }; + let want = ws + .evaluate_with_driver(&request) + .map(|r| Built::normalized(r.output.to_value())) + .map_err(|e| format!("{e:?}")); + let got = match output.errors[row].as_deref() { + Some(error) => Err(match error.policy() { + Some(error) => format!("{error:?}"), + None => format!("{error:?}"), + }), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + if got != want { + failures.push(format!( + "row {row} input {}\n driver {want:?}\n columnar {got:?}", + columns.row(row).to_value() + )); + } + } + assert!( + output.paths().hosted < columns.rows / 2, + "shredded flat input mostly hosted: {}", + output.paths().hosted + ); + } + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); +} + +#[cfg(feature = "driver")] +#[test] +fn policy_columnar_converts_declared_dates_without_hosting() { + let policy = r#"{ + models: { + customer: {since: "date", birth: "date?", tier: "string", accounts: "account[]"}, + account: {opened: "date", balance: "number"}, + }, + blocks: [ + {expression: "customer.loyal", value: "customer.since < d('2020-01-01')"}, + {expression: "customer.adult", value: "customer.birth != null and customer.birth < d('2005-06-01')"}, + {match: "account.fresh", arms: [["account.opened > d('2023-01-01')", "true"], ["", "false"]]}, + {expression: "account.weight", value: "account.balance * (account.opened.year() > 2020 ? 2 : 1)"}, + {expression: "customer.recent", value: "count(customer.accounts, #.fresh)"}, + ], +}"#; + let ws = Anchor::workspace_with(policy); + let values: Vec = (0..48) + .map(|i| { + let accounts: Vec = (0..i % 4) + .map(|j| json!({"opened": format!("20{:02}-0{}-1{}", 18 + (i + j) % 8, 1 + j % 9, j % 9), "balance": i * 10 + j})) + .collect(); + match i % 3 { + 0 => json!({"customer": {"since": format!("201{}-03-04", i % 10), "birth": "1990-05-06", "tier": "gold", "accounts": accounts}}), + 1 => json!({"customer": {"since": "2021-11-30", "birth": null, "tier": "silver", "accounts": accounts}}), + _ => json!({"customer": {"since": "2019-12-31", "tier": "bronze", "accounts": accounts}}), + } + }) + .collect(); + let mut failures = Vec::new(); + for built in [Built::new(&values), Built::nested(&values)] + .into_iter() + .flatten() + { + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let output = ws + .evaluate_columns(&Arc::from("anchor"), &[], &columns) + .expect("columnar"); + assert_eq!(output.paths().hosted, 0, "dated rows were hosted"); + for row in 0..columns.rows { + let request = EvaluateRequest { + policy_path: Arc::from("anchor"), + input: columns.row(row), + goals: Vec::new(), + trace: false, + }; + let want = ws + .evaluate_with_driver(&request) + .map(|r| Built::normalized(r.output.to_value())) + .map_err(|e| format!("{e:?}")); + let got = match output.errors[row].as_deref() { + Some(error) => Err(match error.policy() { + Some(error) => format!("{error:?}"), + None => format!("{error:?}"), + }), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + if got != want { + failures.push(format!( + "row {row} input {}\n driver {want:?}\n columnar {got:?}", + columns.row(row).to_value() + )); + } + } + } + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); +} + +#[cfg(feature = "driver")] +#[test] +fn policy_member_blocks_reading_their_own_list_match_the_driver() { + let policies = [ + ( + true, + r#"{ + models: { + customer: {tier: "string", accounts: "account[]"}, + account: {balance: "number", kind: "string"}, + }, + blocks: [ + {expression: "account.big", value: "account.balance > 100"}, + {expression: "account.share", value: "account.balance / (sum(map(customer.accounts, #.balance)) + 1)"}, + {expression: "account.allBig", value: "all(customer.accounts, #.big)"}, + {expression: "customer.bigs", value: "count(customer.accounts, #.big)"}, + ], +}"#, + ), + ( + true, + r#"{ + models: { + customer: {tier: "string", accounts: "account[]"}, + account: {balance: "number", kind: "string"}, + }, + blocks: [ + {match: "account.rank", arms: [["count(customer.accounts, #.balance > account.balance) == 0", "'top'"], ["", "'rest'"]]}, + {expression: "customer.tops", value: "count(customer.accounts, #.rank == 'top')"}, + ], +}"#, + ), + ( + true, + r#"{ + models: { + customer: {tier: "string", limit: "number", accounts: "account[]"}, + account: {balance: "number", kind: "string"}, + }, + blocks: [ + {expression: "customer.over", value: "count(customer.accounts, #.balance > customer.limit)"}, + {expression: "account.over", value: "count(customer.accounts, #.balance > 50)"}, + ], +}"#, + ), + ( + false, + r#"{ + models: { + customer: {tier: "string", accounts: "account[]"}, + account: {balance: "number", kind: "string"}, + }, + blocks: [ + {expression: "account.seen", value: "count(customer.accounts, #.seen != null)"}, + {expression: "customer.seen", value: "sum(map(customer.accounts, #.seen))"}, + ], +}"#, + ), + ]; + let values: Vec = (0..40) + .map(|i| { + let accounts: Vec = (0..(i % 5)) + .map(|j| { + let kind = ["loan", "savings"][j % 2]; + json!({"balance": (i * 37 + j * 53) % 250, "kind": kind}) + }) + .collect(); + let tier = ["gold", "silver"][i % 2]; + json!({"customer": {"tier": tier, "limit": 60 + i, "accounts": accounts}}) + }) + .collect(); + let mut failures = Vec::new(); + for (columnar, policy) in policies { + let ws = Anchor::workspace_with(policy); + for built in [Built::new(&values), Built::nested(&values)] + .into_iter() + .flatten() + { + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let output = ws + .evaluate_columns(&Arc::from("anchor"), &[], &columns) + .expect("columnar"); + if columnar { + assert_eq!(output.paths().hosted, 0, "sibling reads were hosted"); + } + for row in 0..columns.rows { + let request = EvaluateRequest { + policy_path: Arc::from("anchor"), + input: columns.row(row), + goals: Vec::new(), + trace: false, + }; + let want = ws + .evaluate_with_driver(&request) + .map(|r| Built::normalized(r.output.to_value())) + .map_err(|e| format!("{e:?}")); + let got = match output.errors[row].as_deref() { + Some(error) => Err(match error.policy() { + Some(error) => format!("{error:?}"), + None => format!("{error:?}"), + }), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + if got != want { + failures.push(format!( + "row {row} input {}\n driver {want:?}\n columnar {got:?}", + columns.row(row).to_value() + )); + } + } + } + } + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); +} + +#[test] +fn policy_column_order_is_path_independent() { + let cases = [ + ( + r#"{models: {a: {x: "number"}}, blocks: [{expression: "a.ok", value: "a.x - 1"}, {expression: "a.big", value: "a.x * a.x"}]}"#, + r#"[{"a": {"x": 5}}, {"a": {"x": 1000000000000000}}]"#, + ["a.x", "a.big", "a.ok"].as_slice(), + ), + ( + r#"{models: {a: {x: "number", y: "number"}}, blocks: [{expression: "a.q", value: "a.x / a.y"}, {table: "dt", inputs: ["a.q"], outputs: ["a.band"], rules: [["> 1", "'big'"], ["", "'small'"]]}]}"#, + r#"[{"a": {"x": 4, "y": 2}}, {"a": {"x": 4, "y": 0}}]"#, + ["a.x", "a.y", "a.q", "a.band"].as_slice(), + ), + ( + r#"{models: {a: {x: "number", y: "number"}}, blocks: [{expression: "a.q", value: "a.x / a.y"}, {match: "a.band", arms: [["a.q > 1", "'big'"], ["", "'small'"]]}]}"#, + r#"[{"a": {"x": 4, "y": 2}}, {"a": {"x": 4, "y": 0}}]"#, + ["a.x", "a.y", "a.q", "a.band"].as_slice(), + ), + ]; + for (policy, rows, order) in cases { + let ws = Anchor::workspace_with(policy); + let pair: Vec = serde_json::from_str(rows).expect("rows"); + let values: Vec = (0..64).map(|row| pair[row % 2].clone()).collect(); + let built = Built::new(&values).expect("flat columns"); + let columns = built.columns(); + for call in 0..8 { + let output = ws + .evaluate_columns(&Arc::from("anchor"), &[], &columns) + .expect("columnar"); + let got: Vec<&str> = output + .columns + .iter() + .map(|(path, _)| path.as_ref()) + .collect(); + assert_eq!( + got, + order, + "call {call}: typed {}, laned {}", + output.paths().typed, + output.paths().laned + ); + assert!( + (0..output.rows).all(|row| output.errors[row].is_some() == (row % 2 == 1)), + "call {call}: errors" + ); + } + } +} + +#[test] +fn policy_tables_match_coded_nulls_against_null_cells() { + use zen_expression::lane::{Column, Columns, Dictionary, Values}; + let ws = Anchor::workspace_with( + r#"{models: {a: {k: "string?"}}, blocks: [{table: "cls", inputs: ["a.k"], outputs: ["a.cls"], rules: [["null", "'null'"], ["", "'other'"]]}]}"#, + ); + let keys = [0i32, -1, 0, -1, 1]; + let column = Column::new(Values::Dict { + keys: &keys, + values: Dictionary::Text { + offsets: &[0, 1, 1], + data: "x", + }, + }); + let columns = Columns::new(keys.len()).column("a.k", column); + let want = ["other", "null", "other", "null", "other"]; + for call in 0..4 { + let output = ws + .evaluate_columns(&Arc::from("anchor"), &[], &columns) + .expect("columnar"); + for (row, want) in want.iter().enumerate() { + assert!( + output.errors[row].is_none(), + "call {call} row {row}: {:?}", + output.errors[row] + ); + let cls = output.row(row).dot("a.cls").map(|v| v.to_value()); + assert_eq!(cls, Some(Value::from(*want)), "call {call} row {row}"); + } + } +} + +#[test] +fn policy_anchor_is_fully_typed() { + if Reference::unavailable("anchor") { + return; + } + let reference = Reference::open("anchor"); + let batch = Anchor::base(); + let mut failures = Vec::new(); + let counts = batch.checked(&reference, &batch.workspace(), &mut failures); + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); + for (typed, laned, hosted) in counts { + assert_eq!(hosted, 0, "anchor rows hosted"); + if Anchor::typed() { + assert_eq!((typed, laned), (8, 0), "anchor units typed / laned"); + } + } +} + +#[test] +fn policy_typed_falls_back_per_unit() { + if Reference::unavailable("anchor") { + return; + } + let reference = Reference::open("anchor"); + let batch = Anchor::fallback(); + assert_ne!(batch.policy, Anchor::POLICY); + let mut failures = Vec::new(); + let counts = batch.checked(&reference, &batch.workspace(), &mut failures); + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); + for (typed, laned, hosted) in counts { + assert_eq!(hosted, 0, "rows hosted"); + if Anchor::typed() { + assert!(typed > 0 && laned > 0, "units typed {typed}, laned {laned}"); + assert_eq!(typed + laned, 9, "units typed {typed}, laned {laned}"); + } + } +} + +#[test] +fn policy_typed_fuses_lane_runs() { + if Reference::unavailable("anchor") { + return; + } + let reference = Reference::open("anchor"); + assert_ne!(Anchor::fused_policy(), Anchor::POLICY); + let ws = Anchor::workspace_with(&Anchor::fused_policy()); + let mut failures = Vec::new(); + let counts: Vec<(usize, usize, usize)> = [5, 6, 7] + .into_iter() + .flat_map(|seed| Anchor::fusion(seed).checked(&reference, &ws, &mut failures)) + .collect(); + for (call, (typed, laned, hosted)) in counts.into_iter().enumerate() { + assert_eq!(hosted, 0, "rows hosted"); + if Anchor::typed() { + assert_eq!( + typed + laned, + 10, + "call {call}: units typed {typed}, laned {laned}" + ); + if call < 2 { + assert!( + typed > 0 && laned >= 2, + "call {call}: units typed {typed}, laned {laned}" + ); + } + } + } + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); +} + +#[test] +fn policy_typed_member_tables_and_math() { + if Reference::unavailable("anchor") { + return; + } + let reference = Reference::open("anchor"); + let policy = Anchor::members_policy(); + assert!(policy.contains("account.band") && policy.contains("customer.square")); + let ws = Anchor::workspace_with(&policy); + let mut failures = Vec::new(); + let counts: Vec<(usize, usize, usize)> = [5, 9] + .into_iter() + .flat_map(|seed| Anchor::members(seed).checked(&reference, &ws, &mut failures)) + .collect(); + for (call, (typed, laned, hosted)) in counts.into_iter().enumerate() { + assert_eq!(hosted, 0, "rows hosted"); + if Anchor::typed() { + assert_eq!( + typed + laned, + 15, + "call {call}: units typed {typed}, laned {laned}" + ); + if call < 2 { + assert_eq!( + (typed, laned), + (15, 0), + "call {call}: units typed {typed}, laned {laned}" + ); + } + } + } + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); +} + +#[test] +fn policy_typed_lists_and_closures() { + if Reference::unavailable("anchor") { + return; + } + let reference = Reference::open("anchor"); + let batch = Anchor::lists(); + let mut failures = Vec::new(); + for (typed, laned, hosted) in batch.checked(&reference, &batch.workspace(), &mut failures) { + eprintln!("lists typed {typed} laned {laned} hosted {hosted}"); + if Anchor::typed() { + assert!(typed > 0, "units typed {typed}, laned {laned}"); + } + } + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); +} + +#[test] +fn policy_typed_strings() { + if Reference::unavailable("anchor") { + return; + } + let reference = Reference::open("anchor"); + let [first, second] = Anchor::strings(); + let ws = first.workspace(); + let mut failures = Vec::new(); + for (typed, laned, hosted) in first.checked(&reference, &ws, &mut failures) { + eprintln!("strings typed {typed} laned {laned} hosted {hosted}"); + if Anchor::typed() { + assert!(typed > laned, "units typed {typed}, laned {laned}"); + } + } + second.checked(&reference, &ws, &mut failures); + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[test] +fn policy_typed_dates() { + if Reference::unavailable("anchor") { + return; + } + let reference = Reference::open("anchor"); + let [first, second] = Anchor::dates(); + let ws = first.workspace(); + let mut failures = Vec::new(); + for (typed, laned, hosted) in first.checked(&reference, &ws, &mut failures) { + eprintln!("dates typed {typed} laned {laned} hosted {hosted}"); + if Anchor::typed() { + assert!(typed > laned, "units typed {typed}, laned {laned}"); + } + } + second.checked(&reference, &ws, &mut failures); + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures + .iter() + .take(10) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[test] +fn policy_typed_extremes() { + if Reference::unavailable("anchor") { + return; + } + let reference = Reference::open("anchor"); + let [first, second] = Anchor::extremes(); + let ws = Anchor::workspace(); + let mut failures = Vec::new(); + let counts = first.checked(&reference, &ws, &mut failures); + assert_eq!(counts.len(), 2, "flat and struct-list columns"); + for (typed, laned, hosted) in counts { + eprintln!("extremes typed {typed} laned {laned} hosted {hosted}"); + assert_eq!(hosted, 0, "hosted rows"); + if Anchor::typed() { + assert!(typed > 0, "anchor units typed {typed}"); + assert_eq!( + typed + laned, + 8, + "anchor units typed {typed} / laned {laned}" + ); + } + } + second.checked(&reference, &ws, &mut failures); + failures.extend(reference.missing()); + assert!( + failures.is_empty(), + "{} mismatches:\n{}", + failures.len(), + failures.join("\n") + ); +} + +#[test] +#[ignore] +fn single_row_latency() { + let count: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(256); + let rows: Vec = Anchor::rows(count, 7) + .into_iter() + .map(Variable::from) + .collect(); + let ws = Anchor::workspace(); + let traced = |rows: &[Variable]| -> Vec { + Anchor::fresh(rows) + .into_iter() + .map(|r| EvaluateRequest { trace: true, ..r }) + .collect() + }; + let mut results: Vec<(&str, f64)> = vec![ + ( + "evaluate", + Anchor::time(count, || { + let fresh = Anchor::fresh(&rows); + Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate(r)))) + }), + ), + ( + "evaluate traced", + Anchor::time(count, || { + let fresh = traced(&rows); + Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate(r)))) + }), + ), + ( + "enhance_trace", + Anchor::time(count, || { + let fresh = Anchor::fresh(&rows); + Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.enhance_trace(r)))) + }), + ), + ]; + if cfg!(feature = "driver") { + results.push(( + "driver", + Anchor::time(count, || { + let fresh = Anchor::fresh(&rows); + Anchor::clock(|| fresh.iter().for_each(|r| drop(Live::policy(&ws, r)))) + }), + )); + results.push(( + "driver traced", + Anchor::time(count, || { + let fresh = traced(&rows); + Anchor::clock(|| fresh.iter().for_each(|r| drop(Live::policy(&ws, r)))) + }), + )); + } + for (name, t) in results { + println!("{name:24} {t:>10.0} ns/eval"); + } +} + +#[cfg(feature = "driver")] +#[test] +#[ignore] +fn policy_anchor_throughput() { + support::switches(); + let count: usize = std::env::var("BENCH_ROWS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1024); + let values = Anchor::rows(count, 7); + let rows: Vec = values.iter().map(|v| Variable::from(v.clone())).collect(); + let ws = Anchor::workspace(); + let path: Arc = Arc::from("anchor"); + let reference: Vec = Anchor::fresh(&rows) + .iter() + .map(|r| { + Built::normalized( + ws.evaluate_with_driver(r) + .expect("driver") + .output + .to_value(), + ) + }) + .collect(); + if let Ok(seconds) = std::env::var("ANCHOR_PROFILE_PLAN") { + let built = Built::nested(&values).expect("nested columns"); + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let until = std::time::Instant::now() + + std::time::Duration::from_secs(seconds.parse().unwrap_or(4)); + while std::time::Instant::now() < until { + drop(ws.evaluate_columns(&path, &[], &columns)); + } + return; + } + let mut results: Vec<(&str, f64)> = Vec::new(); + results.push(( + "driver", + Anchor::time(count, || { + let fresh = Anchor::fresh(&rows); + Anchor::clock(|| fresh.iter().for_each(|r| drop(ws.evaluate_with_driver(r)))) + }), + )); + results.push(( + "compiled batch", + Anchor::time(count, || { + let fresh = Anchor::fresh(&rows); + Anchor::clock(|| drop(ws.evaluate_batch(&fresh))) + }), + )); + let built = Built::new(&values).expect("flat columns"); + let columns = built.columns(); + let flat = ws + .evaluate_columns(&path, &[], &columns) + .expect("columnar flat"); + let flat_wrong = (0..count) + .filter(|&r| { + flat.errors[r].is_some() || Built::normalized(flat.row(r).to_value()) != reference[r] + }) + .count(); + let flat_hosted = flat.paths().hosted; + drop(flat); + results.push(( + "columnar flat", + Anchor::time(count, || { + Anchor::clock(|| drop(ws.evaluate_columns(&path, &[], &columns))) + }), + )); + let built = Built::nested(&values).expect("nested columns"); + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let output = ws.evaluate_columns(&path, &[], &columns).expect("columnar"); + let wrong = (0..count) + .filter(|&r| { + output.errors[r].is_some() + || Built::normalized(output.row(r).to_value()) != reference[r] + }) + .count(); + if let Ok(seconds) = std::env::var("ANCHOR_PROFILE_COLUMNAR") { + let until = std::time::Instant::now() + + std::time::Duration::from_secs(seconds.parse().unwrap_or(4)); + while std::time::Instant::now() < until { + drop(ws.evaluate_columns(&path, &[], &columns)); + } + return; + } + results.push(( + "columnar struct lists", + Anchor::time(count, || { + Anchor::clock(|| drop(ws.evaluate_columns(&path, &[], &columns))) + }), + )); + if support::switches().census { + for (key, calls, rows, ns) in zen_engine::diagnostics::census() { + println!("CENSUS\tanchor\t{key}\t{calls}\t{rows}\t{ns}"); + } + } + let mut programs = vec![None; 8]; + let mut runner = zen_expression::lane::LaneRunner::new(); + let mut stages = [0f64; 8]; + Anchor::floor(&columns, &mut programs, &mut runner, &mut stages); + if let Ok(seconds) = std::env::var("ANCHOR_PROFILE") { + let until = std::time::Instant::now() + + std::time::Duration::from_secs(seconds.parse().unwrap_or(4)); + let mut each = [0f64; 8]; + while std::time::Instant::now() < until { + Anchor::floor(&columns, &mut programs, &mut runner, &mut each); + } + return; + } + let mut best = [f64::MAX; 8]; + let floor = Anchor::time(count, || { + let mut each = [0f64; 8]; + let t = Anchor::clock(|| Anchor::floor(&columns, &mut programs, &mut runner, &mut each)); + best.iter_mut().zip(each).for_each(|(b, e)| *b = b.min(e)); + t + }); + results.push(("lane floor (specialized programs)", floor)); + let mut fused_programs = vec![None; 2]; + let mut fused_best = [f64::MAX; 2]; + std::env::set_var("ANCHOR_CHECK", "1"); + let checked = Anchor::fused(&columns, &mut fused_programs, &mut runner, &mut [0f64; 2]) + .unwrap_or_default(); + std::env::remove_var("ANCHOR_CHECK"); + let fused_wrong = (0..count) + .filter(|&r| { + let expected: Vec = Anchor::KEYS[2..] + .iter() + .map(|key| key.split('.').fold(&reference[r], |v, k| &v[k]).clone()) + .collect(); + checked.get(r) != Some(&json!(expected)) + }) + .count(); + if let Ok(seconds) = std::env::var("ANCHOR_PROFILE_FUSED") { + let until = std::time::Instant::now() + + std::time::Duration::from_secs(seconds.parse().unwrap_or(4)); + while std::time::Instant::now() < until { + Anchor::fused(&columns, &mut fused_programs, &mut runner, &mut [0f64; 2]); + } + return; + } + let fused = Anchor::time(count, || { + let mut each = [0f64; 2]; + let t = Anchor::clock(|| { + drop(Anchor::fused( + &columns, + &mut fused_programs, + &mut runner, + &mut each, + )) + }); + fused_best + .iter_mut() + .zip(each) + .for_each(|(b, e)| *b = b.min(e)); + t + }); + results.push(("lane floor (fused programs)", fused)); + let driver = results[0].1; + println!("flat columnar: {flat_wrong} mismatching rows of {count}, {flat_hosted} hosted"); + println!("struct-list columnar: {wrong} mismatching rows of {count}, {} hosted; fused floor: {fused_wrong} mismatching rows", output.paths().hosted); + for (name, t) in &results { + println!("{name:36} {t:>10.1} ns/row {:>8.1}x vs driver", driver / t); + } + let stages: Vec = Anchor::PROGRAMS + .iter() + .zip(best) + .map(|((name, _), t)| format!("{name} {t:.0}")) + .collect(); + println!("lane floor per program (ns/row): {}", stages.join(", ")); + println!( + "fused floor per program (ns/row): member {:.0}, root {:.0}", + fused_best[0], fused_best[1] + ); + assert_eq!(fused_wrong, 0, "fused floor differs from the driver"); + assert_eq!( + flat_wrong, 0, + "flat columnar output differs from the driver" + ); + assert_eq!( + wrong, 0, + "struct-list columnar output differs from the driver" + ); +} diff --git a/core/engine/tests/conformance/graph.rs b/core/engine/tests/conformance/graph.rs new file mode 100644 index 00000000..4909caf8 --- /dev/null +++ b/core/engine/tests/conformance/graph.rs @@ -0,0 +1,348 @@ +use super::literal::{Kind, Lit}; +use serde_json::{json, Map, Value}; + +const KINDS: &[(&str, &str)] = &[ + ("input", "inputNode"), + ("output", "outputNode"), + ("expression", "expressionNode"), + ("table", "decisionTableNode"), + ("switch", "switchNode"), + ("function", "functionNode"), + ("functionV1", "functionNode"), + ("decision", "decisionNode"), + ("custom", "customNode"), +]; + +pub struct Graph; + +impl Graph { + pub fn expand(lit: &Lit) -> Result { + if let Some(raw) = lit.get("raw") { + return Ok(raw.json()); + } + let specs = match lit.get("nodes") { + Some(nodes) => nodes.list().ok_or("`nodes` must be a list")?, + None => &[], + }; + let mut nodes: Vec<(String, &str, Value)> = Vec::new(); + for spec in specs { + let (name, kind, node) = Self::node(spec)?; + if nodes.iter().any(|(n, _, _)| *n == name) { + return Err(format!("duplicate node name {name:?}")); + } + nodes.push((name, kind, node)); + } + if !nodes.iter().any(|(_, k, _)| *k == "input") { + nodes.insert( + 0, + ( + "input".into(), + "input", + json!({"id": "input", "name": "input", "type": "inputNode", "content": {}}), + ), + ); + } + if !nodes.iter().any(|(_, k, _)| *k == "output") { + nodes.push(( + "output".into(), + "output", + json!({"id": "output", "name": "output", "type": "outputNode", "content": {}}), + )); + } + let id = |name: &str| -> Result { + nodes + .iter() + .find(|(n, _, _)| n == name) + .and_then(|(_, _, node)| node.get("id").and_then(Value::as_str).map(str::to_string)) + .ok_or_else(|| format!("edge names unknown node {name:?}")) + }; + let mut edges: Vec = Vec::new(); + let mut push = |from: &str, to: &str| -> Result<(), String> { + let (source, handle) = match from.rsplit_once(':') { + Some((source, handle)) if handle.chars().all(|c| c.is_ascii_digit()) => { + (source, Some(format!("{}:{handle}", id(source)?))) + } + _ => (from, None), + }; + edges.push(json!({ + "id": format!("e{}", edges.len()), + "sourceId": id(source)?, + "targetId": id(to)?, + "sourceHandle": handle, + })); + Ok(()) + }; + match lit.get("edges") { + Some(list) => { + for chain in list.list().ok_or("`edges` must be a list")? { + let text = chain + .text() + .ok_or("edge must be a string like \"a -> b\"")?; + let hops: Vec<&str> = text.split("->").map(str::trim).collect(); + for pair in hops.windows(2) { + push(pair[0], pair[1])?; + } + } + } + None => { + let order: Vec<&str> = nodes + .iter() + .filter(|(_, k, _)| *k == "input") + .chain( + nodes + .iter() + .filter(|(_, k, _)| *k != "input" && *k != "output"), + ) + .chain(nodes.iter().filter(|(_, k, _)| *k == "output")) + .map(|(n, _, _)| n.as_str()) + .collect(); + if nodes.iter().any(|(_, k, _)| *k == "switch") { + return Err("a graph with a switch needs explicit `edges`".into()); + } + for pair in order.windows(2) { + push(pair[0], pair[1])?; + } + } + } + Ok(json!({ + "nodes": nodes.into_iter().map(|(_, _, node)| node).collect::>(), + "edges": edges, + })) + } + + fn node(spec: &Lit) -> Result<(String, &'static str, Value), String> { + let entries = spec.map().ok_or("node must be an object")?; + let found: Vec<(&str, &str, &Lit)> = KINDS + .iter() + .filter_map(|(short, wire)| spec.get(short).map(|v| (*short, *wire, v))) + .collect(); + let [(short, wire, name)] = found.as_slice() else { + return Err(format!( + "node needs exactly one of {:?}, got {:?}", + KINDS.iter().map(|k| k.0).collect::>(), + entries.iter().map(|e| e.0.as_str()).collect::>() + )); + }; + let name = name.text().ok_or("node name must be a string")?.to_string(); + let id = spec + .get("id") + .and_then(Lit::text) + .unwrap_or(&name) + .to_string(); + let mut content = Map::new(); + match *short { + "input" | "output" => { + if let Some(schema) = spec.get("schema") { + let text = match schema.text() { + Some(text) => text.to_string(), + None => schema.json().to_string(), + }; + content.insert("schema".into(), Value::String(text)); + } + } + "expression" => { + let fields = spec.get("fields").ok_or("expression node needs `fields`")?; + let pairs: Vec<(String, String)> = match &fields.kind { + Kind::Map(entries) => entries + .iter() + .map(|(k, v)| v.text().map(|v| (k.clone(), v.to_string()))) + .collect::>() + .ok_or("expression values must be strings")?, + Kind::List(items) => items + .iter() + .map(|pair| match pair.list() { + Some([k, v]) => k + .text() + .zip(v.text()) + .map(|(k, v)| (k.to_string(), v.to_string())), + _ => None, + }) + .collect::>() + .ok_or("expression `fields` list items must be [key, value] strings")?, + _ => { + return Err( + "expression `fields` must be an object or a list of pairs".into() + ) + } + }; + let expressions: Vec = pairs + .into_iter() + .enumerate() + .map(|(i, (key, value))| json!({"id": format!("x{i}"), "key": key, "value": value})) + .collect(); + content.insert("expressions".into(), Value::Array(expressions)); + } + "table" => Self::table(spec, &mut content)?, + "switch" => { + let when = spec + .get("when") + .and_then(Lit::list) + .ok_or("switch node needs `when`")?; + let statements: Vec = when + .iter() + .enumerate() + .map(|(i, c)| { + c.text() + .map(|c| json!({"id": format!("{id}:{i}"), "condition": c})) + }) + .collect::>() + .ok_or("switch conditions must be strings")?; + content.insert("statements".into(), Value::Array(statements)); + content.insert( + "hitPolicy".into(), + Value::String( + spec.get("hit") + .and_then(Lit::text) + .unwrap_or("first") + .into(), + ), + ); + } + "function" => { + let source = spec + .get("source") + .and_then(Lit::text) + .ok_or("function node needs `source`")?; + content.insert("source".into(), Value::String(source.into())); + } + "functionV1" => { + let source = spec + .get("source") + .and_then(Lit::text) + .ok_or("functionV1 node needs `source`")?; + return Ok(( + name.clone(), + "function", + json!({"id": id, "name": name, "type": wire, "content": source}), + )); + } + "decision" => { + let key = spec + .get("key") + .and_then(Lit::text) + .ok_or("decision node needs `key`")?; + content.insert("key".into(), Value::String(key.into())); + } + "custom" => { + content.insert( + "kind".into(), + Value::String( + spec.get("kind") + .and_then(Lit::text) + .unwrap_or_default() + .into(), + ), + ); + content.insert( + "config".into(), + spec.get("config").map_or(json!({}), Lit::json), + ); + } + _ => {} + } + if matches!(*short, "expression" | "table" | "decision") { + for key in ["inputField", "outputPath", "executionMode"] { + if let Some(value) = spec.get(key) { + content.insert(key.into(), value.json()); + } + } + content.insert("passThrough".into(), Value::Bool(spec.flag("passThrough"))); + } + Ok(( + name.clone(), + short, + json!({"id": id, "name": name, "type": wire, "content": content}), + )) + } + + fn table(spec: &Lit, content: &mut Map) -> Result<(), String> { + let column = |lit: &Lit, prefix: &str, i: usize, output: bool| -> Result { + let mut out = json!({"id": format!("{prefix}{i}"), "name": format!("{prefix}{i}")}); + match &lit.kind { + Kind::Null => {} + Kind::Text(field) => { + out["field"] = Value::String(field.clone()); + } + Kind::Map(_) => { + for key in ["field", "name", "type"] { + if let Some(v) = lit.get(key) { + out[key] = v.json(); + } + } + } + _ => return Err("table column must be a string, null or object".into()), + } + if output && out.get("field").is_none() { + return Err("output column needs a field".into()); + } + Ok(out) + }; + let inputs: Vec = spec + .get("inputs") + .and_then(Lit::list) + .unwrap_or_default() + .iter() + .enumerate() + .map(|(i, c)| column(c, "i", i, false)) + .collect::>()?; + let outputs: Vec = spec + .get("outputs") + .and_then(Lit::list) + .unwrap_or_default() + .iter() + .enumerate() + .map(|(i, c)| column(c, "o", i, true)) + .collect::>()?; + let ids: Vec = inputs + .iter() + .chain(&outputs) + .filter_map(|c| c.get("id").and_then(Value::as_str).map(str::to_string)) + .collect(); + let rules: Vec = spec + .get("rules") + .and_then(Lit::list) + .unwrap_or_default() + .iter() + .enumerate() + .map(|(r, row)| { + let cells = row.list().ok_or("rule must be a list of cells")?; + if cells.len() != ids.len() { + return Err(format!( + "rule {r} has {} cells, table has {} columns", + cells.len(), + ids.len() + )); + } + let mut rule = Map::new(); + rule.insert("_id".into(), Value::String(format!("r{r}"))); + for (id, cell) in ids.iter().zip(cells) { + let text = match &cell.kind { + Kind::Null => String::new(), + Kind::Text(t) => t.clone(), + _ => { + return Err(format!( + "rule {r}: cells are expression strings, got {}", + cell.source() + )) + } + }; + rule.insert(id.clone(), Value::String(text)); + } + Ok(Value::Object(rule)) + }) + .collect::>()?; + content.insert("inputs".into(), Value::Array(inputs)); + content.insert("outputs".into(), Value::Array(outputs)); + content.insert("rules".into(), Value::Array(rules)); + content.insert( + "hitPolicy".into(), + Value::String( + spec.get("hit") + .and_then(Lit::text) + .unwrap_or("first") + .into(), + ), + ); + Ok(()) + } +} diff --git a/core/engine/tests/conformance/literal.rs b/core/engine/tests/conformance/literal.rs new file mode 100644 index 00000000..0a9889fd --- /dev/null +++ b/core/engine/tests/conformance/literal.rs @@ -0,0 +1,331 @@ +use rust_decimal::Decimal; +use serde_json::Value; +use std::str::FromStr; +use zen_expression::Variable; + +#[derive(Debug, Clone)] +pub enum Kind { + Null, + Bool(bool), + Number(Decimal, String), + Text(String), + Date(String), + List(Vec), + Map(Vec<(String, Lit)>), +} + +#[derive(Debug, Clone)] +pub struct Lit { + pub line: usize, + pub kind: Kind, +} + +impl Lit { + pub fn get(&self, key: &str) -> Option<&Lit> { + match &self.kind { + Kind::Map(entries) => entries.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + pub fn text(&self) -> Option<&str> { + match &self.kind { + Kind::Text(s) => Some(s), + _ => None, + } + } + + pub fn list(&self) -> Option<&[Lit]> { + match &self.kind { + Kind::List(items) => Some(items), + _ => None, + } + } + + pub fn map(&self) -> Option<&[(String, Lit)]> { + match &self.kind { + Kind::Map(entries) => Some(entries), + _ => None, + } + } + + pub fn flag(&self, key: &str) -> bool { + matches!(self.get(key).map(|l| &l.kind), Some(Kind::Bool(true))) + } + + pub fn variable(&self) -> Variable { + match &self.kind { + Kind::Null => Variable::Null, + Kind::Bool(b) => Variable::Bool(*b), + Kind::Number(n, _) => Variable::Number(*n), + Kind::Text(s) => Variable::String(s.as_str().into()), + Kind::Date(s) => zen_expression::DateValue::from_text(s).unwrap_or(Variable::Null), + Kind::List(items) => Variable::from_array(items.iter().map(Lit::variable).collect()), + Kind::Map(entries) => { + let object = Variable::empty_object(); + if let Variable::Object(map) = &object { + let mut map = map.borrow_mut(); + for (key, value) in entries { + map.insert(key.as_str().into(), value.variable()); + } + } + object + } + } + } + + pub fn json(&self) -> Value { + match &self.kind { + Kind::Null => Value::Null, + Kind::Bool(b) => Value::Bool(*b), + Kind::Number(n, raw) => serde_json::from_str(raw) + .or_else(|_| serde_json::from_str(&n.to_string())) + .unwrap_or(Value::Null), + Kind::Text(s) | Kind::Date(s) => Value::String(s.clone()), + Kind::List(items) => Value::Array(items.iter().map(Lit::json).collect()), + Kind::Map(entries) => { + Value::Object(entries.iter().map(|(k, v)| (k.clone(), v.json())).collect()) + } + } + } + + pub fn source(&self) -> String { + match &self.kind { + Kind::Null => "null".to_string(), + Kind::Bool(b) => b.to_string(), + Kind::Number(_, raw) => raw.clone(), + Kind::Text(s) => format!("{s:?}"), + Kind::Date(s) => format!("date({s:?})"), + Kind::List(items) => format!( + "[{}]", + items.iter().map(Lit::source).collect::>().join(", ") + ), + Kind::Map(entries) => format!( + "{{{}}}", + entries + .iter() + .map(|(k, v)| format!("{k}: {}", v.source())) + .collect::>() + .join(", ") + ), + } + } +} + +pub struct Parser<'a> { + text: &'a str, + at: usize, +} + +impl<'a> Parser<'a> { + pub fn document(text: &'a str) -> Result, String> { + let mut p = Parser { text, at: 0 }; + let mut out = Vec::new(); + loop { + p.space(); + if p.at >= p.text.len() { + return Ok(out); + } + out.push(p.value().map_err(|e| format!("line {}: {e}", p.line()))?); + p.space(); + if p.peek() == Some(',') { + p.at += 1; + } + } + } + + fn line(&self) -> usize { + self.text + .get(..self.at) + .unwrap_or_default() + .matches('\n') + .count() + + 1 + } + + fn rest(&self) -> &'a str { + self.text.get(self.at..).unwrap_or_default() + } + + fn peek(&self) -> Option { + self.rest().chars().next() + } + + fn space(&mut self) { + loop { + let rest = self.rest(); + let trimmed = rest.trim_start(); + self.at += rest.len() - trimmed.len(); + if trimmed.starts_with("//") { + self.at += trimmed.find('\n').unwrap_or(trimmed.len()); + } else if trimmed.starts_with("/*") { + self.at += trimmed.find("*/").map_or(trimmed.len(), |end| end + 2); + } else { + return; + } + } + } + + fn eat(&mut self, c: char) -> Result<(), String> { + self.space(); + match self.peek() { + Some(x) if x == c => { + self.at += c.len_utf8(); + Ok(()) + } + other => Err(format!("expected {c:?}, found {other:?}")), + } + } + + fn value(&mut self) -> Result { + self.space(); + let line = self.line(); + let kind = match self.peek() { + Some('[') => { + self.at += 1; + let mut items = Vec::new(); + loop { + self.space(); + if self.peek() == Some(']') { + self.at += 1; + break; + } + items.push(self.value()?); + self.space(); + match self.peek() { + Some(',') => self.at += 1, + Some(']') => {} + other => return Err(format!("expected , or ], found {other:?}")), + } + } + Kind::List(items) + } + Some('{') => { + self.at += 1; + let mut entries: Vec<(String, Lit)> = Vec::new(); + loop { + self.space(); + if self.peek() == Some('}') { + self.at += 1; + break; + } + let key = match self.peek() { + Some('"' | '\'') => self.string()?, + _ => match self.word() { + w if w.is_empty() => return Err("expected key".to_string()), + w => w, + }, + }; + if entries.iter().any(|(k, _)| *k == key) { + return Err(format!("duplicate key {key:?}")); + } + self.eat(':')?; + let value = self.value()?; + entries.push((key, value)); + self.space(); + match self.peek() { + Some(',') => self.at += 1, + Some('}') => {} + other => return Err(format!("expected , or }}, found {other:?}")), + } + } + Kind::Map(entries) + } + Some('"') if self.rest().starts_with("\"\"\"") => Kind::Text(self.block()?), + Some('"' | '\'') => Kind::Text(self.string()?), + Some(c) if c == '-' || c == '+' || c.is_ascii_digit() || c == '.' => self.number()?, + _ => match self.word().as_str() { + "date" => { + self.eat('(')?; + self.space(); + let text = self.string()?; + self.eat(')')?; + Kind::Date(text) + } + "true" => Kind::Bool(true), + "false" => Kind::Bool(false), + "null" => Kind::Null, + other => return Err(format!("unexpected {other:?}")), + }, + }; + Ok(Lit { line, kind }) + } + + fn word(&mut self) -> String { + let start = self.at; + while self + .peek() + .is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$') + { + self.at += self.peek().map_or(1, char::len_utf8); + } + self.text + .get(start..self.at) + .unwrap_or_default() + .to_string() + } + + fn number(&mut self) -> Result { + let start = self.at; + while self + .peek() + .is_some_and(|c| c.is_ascii_digit() || matches!(c, '-' | '+' | '.' | 'e' | 'E' | '_')) + { + self.at += 1; + } + let raw: String = self + .text + .get(start..self.at) + .unwrap_or_default() + .chars() + .filter(|c| *c != '_' && *c != '+') + .collect(); + let parsed = match raw.contains(['e', 'E']) { + true => Decimal::from_scientific(&raw), + false => Decimal::from_str(&raw), + }; + parsed + .map(|n| Kind::Number(n, raw.clone())) + .map_err(|e| format!("number {raw:?}: {e}")) + } + + fn block(&mut self) -> Result { + self.at += 3; + let rest = self.rest(); + let end = rest.find("\"\"\"").ok_or("unterminated \"\"\" string")?; + let body = rest.get(..end).unwrap_or_default().to_string(); + self.at += end + 3; + Ok(body) + } + + fn string(&mut self) -> Result { + let quote = self.peek().ok_or("expected string")?; + self.at += 1; + let mut out = String::new(); + loop { + let c = self.peek().ok_or("unterminated string")?; + self.at += c.len_utf8(); + match c { + c if c == quote => return Ok(out), + '\\' => { + let e = self.peek().ok_or("unterminated escape")?; + self.at += e.len_utf8(); + match e { + 'n' => out.push('\n'), + 't' => out.push('\t'), + 'r' => out.push('\r'), + '0' => out.push('\0'), + 'u' => { + let hex = self.text.get(self.at..self.at + 4).ok_or("short \\u")?; + let code = u32::from_str_radix(hex, 16).map_err(|e| e.to_string())?; + out.push(char::from_u32(code).ok_or("bad \\u")?); + self.at += 4; + } + other => out.push(other), + } + } + c => out.push(c), + } + } + } +} diff --git a/core/engine/tests/conformance/mod.rs b/core/engine/tests/conformance/mod.rs new file mode 100644 index 00000000..3e710d1f --- /dev/null +++ b/core/engine/tests/conformance/mod.rs @@ -0,0 +1,359 @@ +#![allow(dead_code)] + +pub mod graph; +pub mod literal; +pub mod policy; +pub mod run; + +use literal::{Kind, Lit, Parser}; +use serde_json::Value; +use std::path::{Path, PathBuf}; +use zen_expression::Variable; + +#[derive(Debug, Clone)] +pub enum Expected { + Value(Variable), + Error(Option), +} + +#[derive(Debug, Clone, PartialEq)] +pub enum Note { + None, + Bug(String), + Question(String), +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Dialect { + Graph, + Policy, +} + +#[derive(Debug, Clone)] +pub struct Case { + pub line: usize, + pub input: Variable, + pub input_text: String, + pub expected: Expected, + pub expected_text: String, + pub goals: Vec, + pub note: Note, + pub engines: Option, +} + +#[derive(Debug, Clone)] +pub struct Suite { + pub file: String, + pub line: usize, + pub name: String, + pub dialect: Dialect, + pub content: Value, + pub documents: Vec<(String, Value)>, + pub diagnostics: Option>, + pub cases: Vec, +} + +impl Suite { + pub fn id(&self) -> String { + format!("{}#{}", self.file, self.name) + } + + pub fn location(&self, case: &Case) -> String { + format!("{}:{} [{}]", self.file, case.line, self.name) + } + + pub fn verdict(&self, case: &Case, got: &Result) -> Option { + let pass = match (&case.expected, got) { + (Expected::Error(None), Err(_)) => true, + (Expected::Error(Some(text)), Err(e)) => e.contains(text.as_str()), + (Expected::Value(want), Ok(v)) => Spec::same(want, v), + _ => false, + }; + (!pass).then(|| { + format!( + "{} | input {} | expected {} | got {}", + self.location(case), + case.input_text, + case.expected_text, + match got { + Ok(v) => Spec::render(v), + Err(e) => format!("!error ({e})"), + } + ) + }) + } +} + +pub struct Spec; + +impl Spec { + pub fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("spec") + } + + pub fn prepare() { + std::env::set_var( + "TZ", + std::env::var("SPEC_TZ").unwrap_or_else(|_| "UTC".to_string()), + ); + std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-03-20T10:15:30Z"); + } + + pub fn files(dialect: Dialect) -> Vec { + let filter = std::env::var("SPEC_FILE").ok(); + let dir = match dialect { + Dialect::Graph => "graph", + Dialect::Policy => "policy", + }; + let Ok(entries) = std::fs::read_dir(Self::root().join(dir)) else { + return Vec::new(); + }; + let mut paths: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json5")) + .filter(|p| { + filter + .as_ref() + .is_none_or(|f| p.to_string_lossy().contains(f.as_str())) + }) + .collect(); + paths.sort(); + paths + } + + pub fn suites(dialect: Dialect) -> (Vec, Vec) { + let mut suites = Vec::new(); + let mut problems = Vec::new(); + let only = std::env::var("SPEC_SUITE").ok(); + for path in Self::files(dialect) { + let file = path + .strip_prefix(Self::root()) + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default(); + let text = match std::fs::read_to_string(&path) { + Ok(t) => t, + Err(e) => { + problems.push(format!("{file}: {e}")); + continue; + } + }; + let document = match Parser::document(&text) { + Ok(d) => d, + Err(e) => { + problems.push(format!("{file}: {e}")); + continue; + } + }; + let mut names: Vec = Vec::new(); + for lit in &document { + match Self::suite(&file, dialect, lit) { + Ok(suite) => { + if names.contains(&suite.name) { + problems.push(format!( + "{file}:{}: duplicate suite name {:?}", + lit.line, suite.name + )); + } + names.push(suite.name.clone()); + if only + .as_ref() + .is_none_or(|o| suite.name.contains(o.as_str())) + { + suites.push(suite); + } + } + Err(e) => problems.push(format!("{file}:{}: {e}", lit.line)), + } + } + } + (suites, problems) + } + + fn suite(file: &str, dialect: Dialect, lit: &Lit) -> Result { + let name = lit + .get("name") + .and_then(Lit::text) + .ok_or("suite needs a `name`")? + .to_string(); + let (main, extra, expand): (&str, &str, fn(&Lit) -> Result) = match dialect { + Dialect::Graph => ("graph", "decisions", graph::Graph::expand), + Dialect::Policy => ("policy", "policies", policy::Policy::expand), + }; + let content = expand( + lit.get(main) + .ok_or_else(|| format!("{name}: suite needs `{main}`"))?, + ) + .map_err(|e| format!("{name}: {e}"))?; + let documents = lit + .get(extra) + .and_then(Lit::map) + .unwrap_or_default() + .iter() + .map(|(key, doc)| { + let expanded = match (dialect, doc.get("policy")) { + (_, Some(policy)) => policy::Policy::expand(policy), + (Dialect::Policy, None) if doc.get("graph").is_some() => doc + .get("graph") + .map_or(Ok(Value::Null), graph::Graph::expand), + _ => expand(doc), + }; + expanded + .map(|v| (key.clone(), v)) + .map_err(|e| format!("{name}: {extra}.{key}: {e}")) + }) + .collect::>()?; + let cases = lit + .get("cases") + .and_then(Lit::list) + .ok_or_else(|| format!("{name}: suite needs `cases`"))? + .iter() + .map(Self::case) + .collect::>() + .map_err(|e| format!("{name}: {e}"))?; + let diagnostics = lit.get("diagnostics").and_then(Lit::list).map(|codes| { + let mut codes: Vec = codes + .iter() + .filter_map(|c| c.text().map(str::to_string)) + .collect(); + codes.sort(); + codes + }); + Ok(Suite { + file: file.to_string(), + line: lit.line, + name, + dialect, + content, + documents, + diagnostics, + cases, + }) + } + + fn case(lit: &Lit) -> Result { + let (input, output, note, goals) = match &lit.kind { + Kind::List(parts) => match parts.as_slice() { + [input, output] => (input, output, None, None), + [input, output, note] => (input, output, Some(note), None), + _ => { + return Err(format!( + "line {}: case must be [input, output, note?]", + lit.line + )) + } + }, + Kind::Map(_) => ( + lit.get("input") + .ok_or_else(|| format!("line {}: case needs `input`", lit.line))?, + lit.get("output") + .ok_or_else(|| format!("line {}: case needs `output`", lit.line))?, + lit.get("note"), + lit.get("goals"), + ), + _ => return Err(format!("line {}: case must be a list or object", lit.line)), + }; + let expected = match output.text() { + Some(text) if text.starts_with("!error") => { + let detail = text + .trim_start_matches("!error") + .trim_start_matches(':') + .trim(); + Expected::Error((!detail.is_empty()).then(|| detail.to_string())) + } + _ => Expected::Value(output.variable()), + }; + let note_text = note.and_then(Lit::text).unwrap_or_default(); + let note = match note_text.split_once(':') { + None if note_text.is_empty() => Note::None, + Some(("bug", text)) => Note::Bug(text.trim().to_string()), + Some(("question", text)) => Note::Question(text.trim().to_string()), + _ => { + return Err(format!( + "line {}: note must be `bug: ...` or `question: ...`", + lit.line + )) + } + }; + let engines = match &lit.kind { + Kind::Map(_) => lit.get("engines").and_then(Lit::text).map(str::to_string), + _ => None, + }; + let goals = goals + .and_then(Lit::list) + .unwrap_or_default() + .iter() + .filter_map(|g| g.text().map(str::to_string)) + .collect(); + Ok(Case { + line: lit.line, + input: input.variable(), + input_text: input.source(), + expected, + expected_text: output.source(), + goals, + engines, + note, + }) + } + + pub fn same(want: &Variable, got: &Variable) -> bool { + match (want, got) { + (Variable::Null, Variable::Null) => true, + (Variable::Bool(a), Variable::Bool(b)) => a == b, + (Variable::Number(a), Variable::Number(b)) => a == b, + (Variable::String(a), Variable::String(b)) => a == b, + (Variable::String(a), Variable::Dynamic(d)) => a.as_str() == d.to_string(), + (Variable::Dynamic(a), Variable::Dynamic(b)) => { + a.type_name() == b.type_name() && a.to_string() == b.to_string() + } + (Variable::Array(a), Variable::Array(b)) => { + let (a, b) = (a.borrow(), b.borrow()); + a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| Self::same(x, y)) + } + (Variable::Object(a), Variable::Object(b)) => { + let (a, b) = (a.borrow(), b.borrow()); + a.len() == b.len() + && a.iter() + .all(|(k, x)| b.get(k).is_some_and(|y| Self::same(x, y))) + } + _ => false, + } + } + + pub fn render(v: &Variable) -> String { + match v { + Variable::Null => "null".to_string(), + Variable::Bool(b) => b.to_string(), + Variable::Number(n) => n.to_string(), + Variable::String(s) => format!("{:?}", s.as_str()), + Variable::Dynamic(d) => format!("{:?}", d.to_string()), + Variable::Array(a) => format!( + "[{}]", + a.borrow() + .iter() + .map(Self::render) + .collect::>() + .join(", ") + ), + Variable::Object(o) => { + let o = o.borrow(); + let mut entries: Vec<(String, String)> = o + .iter() + .map(|(k, v)| (k.to_string(), Self::render(v))) + .collect(); + entries.sort(); + format!( + "{{{}}}", + entries + .iter() + .map(|(k, v)| format!("{k}: {v}")) + .collect::>() + .join(", ") + ) + } + } + } +} diff --git a/core/engine/tests/conformance/policy.rs b/core/engine/tests/conformance/policy.rs new file mode 100644 index 00000000..6cd3b1fe --- /dev/null +++ b/core/engine/tests/conformance/policy.rs @@ -0,0 +1,236 @@ +use super::literal::{Kind, Lit}; +use serde_json::{json, Map, Value}; + +const PRIMITIVES: &[&str] = &["string", "number", "boolean", "date"]; + +pub struct Policy; + +impl Policy { + pub fn expand(lit: &Lit) -> Result { + if let Some(raw) = lit.get("raw") { + return Ok(raw.json()); + } + let mut blocks: Vec = Vec::new(); + for (key, scope) in [("models", "entity"), ("globals", "global")] { + for (name, props) in lit.get(key).and_then(Lit::map).unwrap_or_default() { + let properties: Vec = props + .map() + .ok_or_else(|| format!("model {name} must be an object of property types"))? + .iter() + .map(|(prop, ty)| Self::property(name, prop, ty)) + .collect::>()?; + blocks.push(json!({ + "id": format!("model:{name}"), + "type": "dataModel", + "props": {"data": {"name": name, "scope": scope, "properties": properties}}, + })); + } + } + for (name, entries) in lit + .get("dictionaries") + .and_then(Lit::map) + .unwrap_or_default() + { + let entries: Vec = entries + .list() + .ok_or_else(|| format!("dictionary {name} must be a list"))? + .iter() + .enumerate() + .map(|(i, entry)| match &entry.kind { + Kind::Text(value) => Ok(json!({"id": format!("{name}:{i}"), "value": value, "label": value})), + Kind::List(pair) => match pair.as_slice() { + [value, label] => Ok(json!({"id": format!("{name}:{i}"), "value": value.json(), "label": label.json()})), + _ => Err(format!("dictionary {name} entry {i} must be \"value\" or [value, label]")), + }, + _ => Err(format!("dictionary {name} entry {i} must be \"value\" or [value, label]")), + }) + .collect::>()?; + blocks.push(json!({ + "id": format!("dictionary:{name}"), + "type": "dictionary", + "props": {"data": {"name": name, "entries": entries}}, + })); + } + for (i, block) in lit + .get("blocks") + .and_then(Lit::list) + .unwrap_or_default() + .iter() + .enumerate() + { + blocks.push(Self::block(i, block)?); + } + let imports: Vec = lit + .get("imports") + .map(|l| l.json()) + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default(); + Ok(json!({"imports": imports, "blocks": blocks})) + } + + fn property(model: &str, name: &str, ty: &Lit) -> Result { + let text = ty + .text() + .ok_or_else(|| format!("{model}.{name}: type must be a string like \"number[]?\""))?; + let (text, optional) = match text.strip_suffix('?') { + Some(rest) => (rest, true), + None => (text, false), + }; + let (text, array) = match text.strip_suffix("[]") { + Some(rest) => (rest, true), + None => (text, false), + }; + let mut out = json!({"id": format!("{model}.{name}"), "name": name, "array": array, "optional": optional}); + if let Some(values) = text + .strip_prefix("string(") + .and_then(|r| r.strip_suffix(')')) + { + out["type"] = json!("string"); + out["enum"] = json!(values.split('|').map(str::trim).collect::>()); + } else if PRIMITIVES.contains(&text) { + out["type"] = json!(text); + } else if let Some(target) = text.strip_prefix('&') { + out["type"] = json!("reference"); + out["target"] = json!(target); + } else { + out["type"] = json!("relationship"); + out["target"] = json!(text); + } + Ok(out) + } + + fn block(i: usize, spec: &Lit) -> Result { + let text = |key: &str| spec.get(key).and_then(Lit::text).map(str::to_string); + let id = text("id") + .or_else(|| text("table")) + .unwrap_or_else(|| format!("b{i}")); + let (kind, data) = if let Some(key) = text("expression") { + let value = text("value").ok_or("expression block needs `value`")?; + ("expression", json!({"key": key, "value": value})) + } else if let Some(key) = text("match") { + let arms: Vec = spec + .get("arms") + .and_then(Lit::list) + .ok_or("match block needs `arms`")? + .iter() + .enumerate() + .map(|(a, arm)| match arm.list() { + Some([condition, value]) => condition + .text() + .zip(value.text()) + .map( + |(c, v)| json!({"id": format!("{id}:{a}"), "condition": c, "value": v}), + ) + .ok_or_else(|| "match arm cells must be strings".to_string()), + _ => Err("match arm must be [condition, value]".to_string()), + }) + .collect::>()?; + ("match", json!({"key": key, "arms": arms})) + } else if let Some(output) = text("assertion") { + let conditions: Vec = spec + .get("conditions") + .and_then(Lit::list) + .ok_or("assertion block needs `conditions`")? + .iter() + .enumerate() + .map(|(c, cond)| { + let (operator, expression, depth) = match &cond.kind { + Kind::Text(e) => ("and".to_string(), e.clone(), 0u64), + Kind::List(parts) => match parts.as_slice() { + [op, e] => (op.text().unwrap_or("and").to_string(), e.text().unwrap_or_default().to_string(), 0), + [op, e, depth] => ( + op.text().unwrap_or("and").to_string(), + e.text().unwrap_or_default().to_string(), + depth.json().as_u64().unwrap_or(0), + ), + _ => return Err("assertion condition must be \"expr\" or [operator, expr, depth?]".to_string()), + }, + _ => return Err("assertion condition must be \"expr\" or [operator, expr, depth?]".to_string()), + }; + Ok(json!({"id": format!("{id}:{c}"), "expression": expression, "operator": operator, "depth": depth})) + }) + .collect::>()?; + ( + "assertion", + json!({"output": output, "conditions": conditions}), + ) + } else if spec.get("table").is_some() { + ("decisionTable", Self::table(spec)?) + } else { + return Err(format!( + "block needs one of expression/match/assertion/table, got {:?}", + spec.map() + .unwrap_or_default() + .iter() + .map(|e| e.0.as_str()) + .collect::>() + )); + }; + Ok(json!({"id": id, "type": kind, "props": {"data": data}})) + } + + fn table(spec: &Lit) -> Result { + let columns = |key: &str, prefix: &str| -> Result, String> { + spec.get(key) + .and_then(Lit::list) + .unwrap_or_default() + .iter() + .enumerate() + .map(|(i, c)| match &c.kind { + Kind::Null => Ok(json!({"id": format!("{prefix}{i}"), "name": ""})), + Kind::Text(field) => { + Ok(json!({"id": format!("{prefix}{i}"), "name": "", "field": field})) + } + Kind::Map(_) => { + let mut out = c.json(); + out["id"] = json!(format!("{prefix}{i}")); + Ok(out) + } + _ => Err("table column must be a string, null or object".to_string()), + }) + .collect() + }; + let inputs = columns("inputs", "i")?; + let outputs = columns("outputs", "o")?; + let ids: Vec = inputs + .iter() + .chain(&outputs) + .filter_map(|c| c.get("id").and_then(Value::as_str).map(str::to_string)) + .collect(); + let rules: Vec = spec + .get("rules") + .and_then(Lit::list) + .unwrap_or_default() + .iter() + .enumerate() + .map(|(r, row)| { + let cells = row.list().ok_or("rule must be a list of cells")?; + if cells.len() != ids.len() { + return Err(format!( + "rule {r} has {} cells, table has {} columns", + cells.len(), + ids.len() + )); + } + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{r}"))); + for (id, cell) in ids.iter().zip(cells) { + let text = match &cell.kind { + Kind::Null => String::new(), + Kind::Text(t) => t.clone(), + _ => { + return Err(format!( + "rule {r}: cells are expression strings, got {}", + cell.source() + )) + } + }; + rule.insert(id.clone(), json!(text)); + } + Ok(Value::Object(rule)) + }) + .collect::>()?; + let hit = spec.get("hit").and_then(Lit::text).unwrap_or("first"); + Ok(json!({"hitPolicy": hit, "inputs": inputs, "outputs": outputs, "rules": rules})) + } +} diff --git a/core/engine/tests/conformance/run.rs b/core/engine/tests/conformance/run.rs new file mode 100644 index 00000000..351fde68 --- /dev/null +++ b/core/engine/tests/conformance/run.rs @@ -0,0 +1,302 @@ +use crate::conformance::{Case, Suite}; +use crate::support::golden::{Canon, Live, Outcome, Reference}; +use serde_json::Value; +use std::sync::Arc; +use zen_engine::loader::MemoryLoader; +use zen_engine::model::DecisionContent; +use zen_engine::nodes::custom::{CustomNodeAdapter, CustomNodeRequest}; +use zen_engine::nodes::{NodeError, NodeResponse, NodeResult}; +use zen_engine::policy::{EvaluateRequest, EvaluationResult, PolicyWorkspace, Severity}; +use zen_engine::{Decision, DecisionEngine, DecisionGraphResponse, EvaluationError}; +use zen_expression::Variable; + +#[derive(Debug)] +pub struct SpecNodes; + +impl SpecNodes { + pub fn respond(request: &CustomNodeRequest) -> Result { + let config = &request.node.config; + match request.node.kind.as_ref() { + "echo" => Ok(request.input.clone()), + "config" => Ok(Variable::from(config.as_ref().clone())), + "render" => { + let out = Variable::empty_object(); + for key in config + .as_object() + .map(|o| o.keys().cloned().collect::>()) + .unwrap_or_default() + { + let value = request + .get_field(&key) + .map_err(|e| e.to_string())? + .unwrap_or(Variable::Null); + out.dot_insert(&key, value); + } + Ok(out) + } + "fail" => Err(config + .get("message") + .and_then(|m| m.as_str()) + .unwrap_or("custom node failed") + .to_string()), + other => Err(format!("unknown spec custom node kind {other:?}")), + } + } +} + +impl CustomNodeAdapter for SpecNodes { + fn handle( + &self, + request: CustomNodeRequest, + ) -> std::pin::Pin + '_>> { + Box::pin(async move { + Self::respond(&request) + .map(|output| NodeResponse { + output, + trace_data: None, + }) + .map_err(|message| NodeError { + trace: None, + node_id: request.node.id.clone(), + source: message.into(), + }) + }) + } +} + +pub struct GraphRun { + pub walker: Decision, + pub uncompiled: Decision, + pub compiled: Decision, + pub engine: DecisionEngine, +} + +impl GraphRun { + pub fn new(suite: &Suite) -> Result { + let content = |value: &Value| -> Result { + serde_json::from_value::(value.clone()) + .map_err(|e| format!("{}: invalid content: {e}", suite.name)) + }; + let (plain, built) = ( + Arc::new(MemoryLoader::default()), + Arc::new(MemoryLoader::default()), + ); + for (key, doc) in &suite.documents { + plain.add(key.as_str(), content(doc)?); + built.add(key.as_str(), Self::compiled(content(doc)?)); + } + let DecisionContent::Graph(graph) = content(&suite.content)? else { + return Err(format!( + "{}: graph suite content is not a graph", + suite.name + )); + }; + let shared = Arc::new(MemoryLoader::default()); + for (key, doc) in &suite.documents { + shared.add(key.as_str(), content(doc)?); + } + shared.add(Self::MAIN, content(&suite.content)?); + let engine = DecisionEngine::default() + .with_loader(shared) + .with_adapter(Arc::new(SpecNodes)); + engine.compile(); + let uncompiled = Decision::from(graph.clone()) + .with_loader(plain) + .with_adapter(Arc::new(SpecNodes)); + let walker = Live::walker(&uncompiled); + let mut compiled = Decision::from(graph) + .with_loader(built) + .with_adapter(Arc::new(SpecNodes)); + compiled.compile(); + Ok(GraphRun { + walker, + uncompiled, + compiled, + engine, + }) + } + + pub const MAIN: &'static str = "spec-main"; + + pub fn compiled(content: DecisionContent) -> DecisionContent { + match content { + DecisionContent::Graph(mut graph) => { + Arc::make_mut(&mut graph).compile(); + DecisionContent::Graph(graph) + } + other => other, + } + } + + pub fn outcome( + result: Result>, + ) -> Result { + result.map(|r| r.result).map_err(|e| Self::error(&e)) + } + + pub fn error(error: &EvaluationError) -> String { + serde_json::to_value(error) + .map(|v| v.to_string()) + .unwrap_or_else(|_| error.to_string()) + } + + pub async fn walker(&self, case: &Case) -> Result { + Live::require_walker(); + Self::outcome(self.walker.evaluate(case.input.depth_clone(64)).await) + } +} + +pub struct PolicyRun { + pub workspace: PolicyWorkspace, + pub blocking: Vec, + pub gate: bool, + pub engine: DecisionEngine, +} + +impl PolicyRun { + pub const MAIN: &'static str = "main"; + + pub fn new(suite: &Suite) -> Result { + let mut workspace = PolicyWorkspace::new(); + let loader = Arc::new(MemoryLoader::default()); + let policy = |value: &Value| { + serde_json::from_value(value.clone()) + .map_err(|e| format!("{}: invalid policy: {e}", suite.name)) + }; + let document = |value: &Value| { + serde_json::from_value::(value.clone()) + .map_err(|e| format!("{}: invalid document: {e}", suite.name)) + }; + workspace.set_policy(Self::MAIN, policy(&suite.content)?); + loader.add(Self::MAIN, document(&suite.content)?); + for (key, doc) in &suite.documents { + match doc.get("nodes") { + Some(_) => workspace.set_document(key.as_str(), document(doc)?), + None => workspace.set_policy(key.as_str(), policy(doc)?), + } + loader.add(key.as_str(), document(doc)?); + } + let mut blocking: Vec = workspace + .evaluation_diagnostics(Self::MAIN) + .into_iter() + .filter(|d| d.severity == Severity::Error) + .map(|d| { + serde_json::to_value(d.code) + .ok() + .and_then(|v| v.as_str().map(str::to_string)) + .unwrap_or_default() + }) + .collect(); + blocking.sort(); + blocking.dedup(); + let engine = DecisionEngine::default().with_loader(loader); + let gate = suite.diagnostics.is_none(); + Ok(PolicyRun { + workspace, + blocking, + gate, + engine, + }) + } + + pub fn gated( + &self, + result: &Result, + ) -> Result { + match self.blocking.is_empty() || !self.gate { + true => Self::outcome(result), + false => Err(format!("CompilationErrors {:?}", self.blocking)), + } + } + + pub fn driver(&self, case: &Case) -> Result { + self.gated(&crate::support::golden::Live::policy( + &self.workspace, + &Self::request(case), + )) + } + + pub fn compiled(&self, case: &Case) -> Result { + self.gated(&self.workspace.evaluate(&Self::request(case))) + } + + pub fn engine(&self, case: &Case) -> Result { + let result = Guard::block(self.engine.evaluate(Self::MAIN, case.input.depth_clone(64))); + match (&result, self.blocking.is_empty()) { + (Err(_), false) => Err(format!("CompilationErrors {:?}", self.blocking)), + (Err(error), true) => match &**error { + EvaluationError::Policy(error) => Err(Reference::debug(error)), + other => Err(GraphRun::error(other)), + }, + (Ok(response), _) => Ok(response.result.clone()), + } + } + + pub fn request(case: &Case) -> EvaluateRequest { + EvaluateRequest { + policy_path: Arc::from(Self::MAIN), + input: case.input.depth_clone(64), + goals: case.goals.iter().map(|g| Arc::from(g.as_str())).collect(), + trace: false, + } + } + + pub fn outcome( + result: &Result, + ) -> Result { + result + .as_ref() + .map(|r| r.output.clone()) + .map_err(Reference::debug) + } +} + +pub struct Guard; + +impl Guard { + pub fn run( + label: String, + failures: &mut Vec, + work: impl FnOnce() -> T, + ) -> Option { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)) { + Ok(value) => Some(value), + Err(payload) => { + let message = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string())) + .unwrap_or_default(); + failures.push(format!("{label} | PANIC: {message}")); + None + } + } + } + + pub fn block(future: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime") + .block_on(future) + } +} + +impl GraphRun { + pub fn recorded(outcome: &Outcome) -> Result { + match outcome { + Outcome::Ok(value) => Ok(Canon::restore(value)), + Outcome::Err { value, .. } => Err(value.to_string()), + } + } +} + +impl PolicyRun { + pub fn recorded(&self, outcome: &Outcome) -> Result { + match (self.blocking.is_empty() || !self.gate, outcome) { + (false, _) => Err(format!("CompilationErrors {:?}", self.blocking)), + (true, Outcome::Ok(value)) => Ok(Canon::restore(value)), + (true, Outcome::Err { debug, .. }) => Err(debug.clone()), + } + } +} diff --git a/core/engine/tests/data/compiled/collect-tables.json b/core/engine/tests/data/compiled/collect-tables.json new file mode 100644 index 00000000..7f3f5835 --- /dev/null +++ b/core/engine/tests/data/compiled/collect-tables.json @@ -0,0 +1,476 @@ +{ + "nodes": [ + { + "id": "in", + "type": "inputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Request" + }, + { + "id": "t1", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Tags", + "content": { + "hitPolicy": "first", + "passThrough": true, + "inputs": [ + { + "id": "t1i0", + "name": "customer.age", + "field": "customer.age" + }, + { + "id": "t1i1", + "name": "customer.country", + "field": "customer.country" + } + ], + "outputs": [ + { + "id": "t1o0", + "name": "customer.tier", + "field": "customer.tier" + }, + { + "id": "t1o1", + "name": "customer.tags[]", + "field": "customer.tags[]" + }, + { + "id": "t1o2", + "name": "flags[]", + "field": "flags[]" + }, + { + "id": "t1o3", + "name": "customer.bonus", + "field": "customer.bonus" + } + ], + "rules": [ + { + "_id": "t1r0", + "t1i0": ">= 65", + "t1i1": "'US'", + "t1o0": "'senior'", + "t1o1": "'senior-discount'", + "t1o2": "['a', 'b']", + "t1o3": "customer.age * 2" + }, + { + "_id": "t1r1", + "t1i0": ">= 18", + "t1i1": "", + "t1o0": "'standard'", + "t1o1": "customer.country + '-adult'", + "t1o2": "", + "t1o3": "" + }, + { + "_id": "t1r2", + "t1i0": ">= 21", + "t1i1": "", + "t1o0": "'unused'", + "t1o1": "'age-verified'", + "t1o2": "[customer.age]", + "t1o3": "customer.age / customer.divisor" + }, + { + "_id": "t1r3", + "t1i0": "", + "t1i1": "'DE', 'FR'", + "t1o0": "'eu'", + "t1o1": "customer.age > 30 ? 'old' : 'young'", + "t1o2": "", + "t1o3": "" + }, + { + "_id": "t1r4", + "t1i0": "", + "t1i1": "", + "t1o0": "", + "t1o1": "'customer'", + "t1o2": "['z']", + "t1o3": "" + } + ] + } + }, + { + "id": "t2", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Summary", + "content": { + "hitPolicy": "first", + "passThrough": false, + "inputs": [ + { + "id": "t2i0", + "name": "customer.country", + "field": "customer.country" + } + ], + "outputs": [ + { + "id": "t2o0", + "name": "summary.level", + "field": "summary.level" + }, + { + "id": "t2o1", + "name": "summary.tags[]", + "field": "summary.tags[]" + }, + { + "id": "t2o2", + "name": "summary.codes[]", + "field": "summary.codes[]" + } + ], + "rules": [ + { + "_id": "t2r0", + "t2i0": "'US'", + "t2o0": "'domestic'", + "t2o1": "customer.country", + "t2o2": "1" + }, + { + "_id": "t2r1", + "t2i0": "'DE'", + "t2o0": "", + "t2o1": "'any'", + "t2o2": "customer.age" + }, + { + "_id": "t2r2", + "t2i0": "'DE', 'US'", + "t2o0": "'late'", + "t2o1": "'second'", + "t2o2": "" + } + ] + } + }, + { + "id": "t3", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Lists", + "content": { + "hitPolicy": "first", + "passThrough": true, + "inputs": [ + { + "id": "t3i0", + "name": "customer.age", + "field": "customer.age" + } + ], + "outputs": [ + { + "id": "t3o0", + "name": "lists.items[]", + "field": "lists.items[]" + }, + { + "id": "t3o1", + "name": "lists.count", + "field": "lists.count" + } + ], + "rules": [ + { + "_id": "t3r0", + "t3i0": "< 30", + "t3o0": "'young'", + "t3o1": "1" + }, + { + "_id": "t3r1", + "t3i0": "< 50", + "t3o0": "'mid'", + "t3o1": "2" + }, + { + "_id": "t3r2", + "t3i0": "", + "t3o0": "['x', customer.country]", + "t3o1": "" + } + ] + } + }, + { + "id": "e1", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Reads", + "content": { + "passThrough": true, + "expressions": [ + { + "id": "x1", + "key": "tagCount", + "value": "len(customer.tags ?? [])" + }, + { + "id": "x2", + "key": "firstFlag", + "value": "flags[0]" + }, + { + "id": "x3", + "key": "joined", + "value": "map(customer.tags ?? [], # + '!')" + } + ] + } + }, + { + "id": "out", + "type": "outputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Response" + }, + { + "id": "t4", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Refs", + "content": { + "hitPolicy": "first", + "passThrough": true, + "inputs": [ + { + "id": "t4i0", + "name": "customer.age", + "field": "customer.age" + }, + { + "id": "t4i1", + "name": "customer.country", + "field": "customer.country" + }, + { + "id": "t4i2", + "name": "customer", + "field": "customer" + } + ], + "outputs": [ + { + "id": "t4o0", + "name": "refs.rule", + "field": "refs.rule" + }, + { + "id": "t4o1", + "name": "refs.value", + "field": "refs.value" + } + ], + "rules": [ + { + "_id": "t4r0", + "t4i0": "$ > customer.divisor * 10", + "t4i1": "some(['DE', 'FR'], # == $)", + "t4i2": "", + "t4o0": "'scaled'", + "t4o1": "customer.age - customer.divisor" + }, + { + "_id": "t4r1", + "t4i0": "$ + 1 > 20 and $ < 60", + "t4i1": "len($) == 2", + "t4i2": "", + "t4o0": "'mid'", + "t4o1": "len(customer.country)" + }, + { + "_id": "t4r2", + "t4i0": "", + "t4i1": "$ != 'US' and $ != customer.country", + "t4i2": "", + "t4o0": "'never'", + "t4o1": "1" + }, + { + "_id": "t4r3", + "t4i0": "", + "t4i1": "", + "t4i2": "$.age > 60", + "t4o0": "'object'", + "t4o1": "customer.age" + }, + { + "_id": "t4r4", + "t4i0": "> 5 and < 15", + "t4i1": "", + "t4i2": "", + "t4o0": "'band'", + "t4o1": "customer.age * 2" + }, + { + "_id": "t4r5", + "t4i0": "", + "t4i1": "", + "t4i2": "", + "t4o0": "'fallback'", + "t4o1": "customer.missing" + } + ] + } + } + ], + "edges": [ + { + "id": "x0", + "sourceId": "in", + "targetId": "t1", + "type": "edge" + }, + { + "id": "x1", + "sourceId": "t1", + "targetId": "e1", + "type": "edge" + }, + { + "id": "x2", + "sourceId": "e1", + "targetId": "out", + "type": "edge" + }, + { + "id": "x3", + "sourceId": "in", + "targetId": "t2", + "type": "edge" + }, + { + "id": "x4", + "sourceId": "t2", + "targetId": "out", + "type": "edge" + }, + { + "id": "x5", + "sourceId": "in", + "targetId": "t3", + "type": "edge" + }, + { + "id": "x6", + "sourceId": "t3", + "targetId": "out", + "type": "edge" + }, + { + "id": "x10", + "sourceId": "in", + "targetId": "t4", + "type": "edge" + }, + { + "id": "x11", + "sourceId": "t4", + "targetId": "out", + "type": "edge" + } + ], + "tests": [ + { + "input": { + "customer": { + "age": 70, + "country": "US", + "divisor": 2 + } + } + }, + { + "input": { + "customer": { + "age": 19, + "country": "DE", + "divisor": 0 + } + } + }, + { + "input": { + "customer": { + "age": 25 + } + } + }, + { + "input": { + "customer": { + "age": 10, + "country": "FR" + } + } + }, + { + "input": { + "customer": { + "age": 45, + "country": "US", + "divisor": 3 + } + } + }, + { + "input": { + "customer": { + "age": "old", + "country": "DE" + } + } + }, + { + "input": { + "customer": { + "country": "PL" + } + } + }, + { + "input": { + "customer": { + "age": 66, + "country": "FR", + "divisor": 1 + } + } + }, + { + "input": {} + } + ] +} \ No newline at end of file diff --git a/core/engine/tests/data/compiled/fused-chain.json b/core/engine/tests/data/compiled/fused-chain.json new file mode 100644 index 00000000..04073bc1 --- /dev/null +++ b/core/engine/tests/data/compiled/fused-chain.json @@ -0,0 +1,204 @@ +{ + "nodes": [ + { + "id": "in", + "type": "inputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Request" + }, + { + "id": "t1", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Age", + "content": { + "hitPolicy": "first", + "passThrough": true, + "inputs": [ + { + "id": "t1i0", + "name": "customer.age", + "field": "customer.age" + } + ], + "outputs": [ + { + "id": "t1o0", + "name": "elig.age.ok", + "field": "elig.age.ok" + }, + { + "id": "t1o1", + "name": "elig.age.reason", + "field": "elig.age.reason" + } + ], + "rules": [ + { + "_id": "t1r0", + "t1i0": "< 18", + "t1o0": "false", + "t1o1": "'young'" + }, + { + "_id": "t1r1", + "t1i0": "> 75", + "t1o0": "false", + "t1o1": "'old'" + }, + { + "_id": "t1r2", + "t1i0": "", + "t1o0": "true", + "t1o1": "'fine'" + } + ] + } + }, + { + "id": "t2", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Loc", + "content": { + "hitPolicy": "first", + "passThrough": true, + "inputs": [ + { + "id": "t2i0", + "name": "customer.location.state", + "field": "customer.location.state" + } + ], + "outputs": [ + { + "id": "t2o0", + "name": "elig.loc.ok", + "field": "elig.loc.ok" + }, + { + "id": "t2o1", + "name": "elig.loc.reason", + "field": "elig.loc.reason" + } + ], + "rules": [ + { + "_id": "t2r0", + "t2i0": "contains(['FL', 'LA', 'TX'], $)", + "t2o0": "false", + "t2o1": "'risk'" + }, + { + "_id": "t2r1", + "t2i0": "!contains(['US', 'CA', 'UK'], $)", + "t2o0": "false", + "t2o1": "'unsupported'" + }, + { + "_id": "t2r2", + "t2i0": "", + "t2o0": "true", + "t2o1": "'fine'" + } + ] + } + }, + { + "id": "e1", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Final", + "content": { + "passThrough": true, + "expressions": [ + { + "id": "x", + "key": "ok", + "value": "elig.age.ok and elig.loc.ok" + } + ] + } + }, + { + "id": "out", + "type": "outputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Response" + } + ], + "edges": [ + { + "id": "x0", + "sourceId": "in", + "targetId": "t1", + "type": "edge" + }, + { + "id": "x1", + "sourceId": "t1", + "targetId": "t2", + "type": "edge" + }, + { + "id": "x2", + "sourceId": "t2", + "targetId": "e1", + "type": "edge" + }, + { + "id": "x3", + "sourceId": "e1", + "targetId": "out", + "type": "edge" + } + ], + "tests": [ + { + "input": { + "customer": { + "age": 45, + "location": { + "state": "CA", + "city": "SF" + } + } + } + }, + { + "input": { + "customer": { + "age": 10, + "location": { + "state": "TX" + } + } + } + }, + { + "input": { + "customer": { + "age": 80, + "location": { + "state": "DE" + } + } + } + } + ] +} \ No newline at end of file diff --git a/core/engine/tests/data/compiled/fused-chain2.json b/core/engine/tests/data/compiled/fused-chain2.json new file mode 100644 index 00000000..dcae1cdc --- /dev/null +++ b/core/engine/tests/data/compiled/fused-chain2.json @@ -0,0 +1,146 @@ +{ + "nodes": [ + { + "id": "in", + "type": "inputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Request" + }, + { + "id": "t2", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Loc", + "content": { + "hitPolicy": "first", + "passThrough": true, + "inputs": [ + { + "id": "t2i0", + "name": "customer.location.state", + "field": "customer.location.state" + } + ], + "outputs": [ + { + "id": "t2o0", + "name": "elig.loc.ok", + "field": "elig.loc.ok" + }, + { + "id": "t2o1", + "name": "elig.loc.reason", + "field": "elig.loc.reason" + } + ], + "rules": [ + { + "_id": "t2r0", + "t2i0": "contains(['FL', 'LA', 'TX'], $)", + "t2o0": "false", + "t2o1": "'risk'" + }, + { + "_id": "t2r1", + "t2i0": "!contains(['US', 'CA', 'UK'], $)", + "t2o0": "false", + "t2o1": "'unsupported'" + }, + { + "_id": "t2r2", + "t2i0": "", + "t2o0": "true", + "t2o1": "'fine'" + } + ] + } + }, + { + "id": "e1", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Final", + "content": { + "passThrough": true, + "expressions": [ + { + "id": "x", + "key": "ok", + "value": "elig.loc.ok" + } + ] + } + }, + { + "id": "out", + "type": "outputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Response" + } + ], + "edges": [ + { + "id": "x0", + "sourceId": "in", + "targetId": "t2", + "type": "edge" + }, + { + "id": "x1", + "sourceId": "t2", + "targetId": "e1", + "type": "edge" + }, + { + "id": "x2", + "sourceId": "e1", + "targetId": "out", + "type": "edge" + } + ], + "tests": [ + { + "input": { + "customer": { + "age": 45, + "location": { + "state": "CA", + "city": "SF" + } + } + } + }, + { + "input": { + "customer": { + "age": 10, + "location": { + "state": "TX" + } + } + } + }, + { + "input": { + "customer": { + "age": 80, + "location": { + "state": "DE" + } + } + } + } + ] +} \ No newline at end of file diff --git a/core/engine/tests/data/compiled/input-fields.json b/core/engine/tests/data/compiled/input-fields.json new file mode 100644 index 00000000..76c8d934 --- /dev/null +++ b/core/engine/tests/data/compiled/input-fields.json @@ -0,0 +1,283 @@ +{ + "nodes": [ + { + "id": "in", + "type": "inputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Request" + }, + { + "id": "e1", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Customer", + "content": { + "expressions": [ + { + "id": "e1x0", + "key": "fullName", + "value": "firstName + ' ' + lastName" + }, + { + "id": "e1x1", + "key": "older", + "value": "age > 40" + }, + { + "id": "e1x2", + "key": "rootAge", + "value": "$.age" + }, + { + "id": "e1x3", + "key": "orderTotal", + "value": "$nodes.Request.order.total" + } + ], + "inputField": "customer", + "outputPath": "customer", + "passThrough": true + } + }, + { + "id": "e2", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Address", + "content": { + "expressions": [ + { + "id": "e2x0", + "key": "cityUpper", + "value": "upper(city ?? '')" + }, + { + "id": "e2x1", + "key": "zip", + "value": "zip" + } + ], + "inputField": "customer.address", + "passThrough": false + } + }, + { + "id": "e3", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Stats", + "content": { + "expressions": [ + { + "id": "e3x0", + "key": "count", + "value": "1" + }, + { + "id": "e3x1", + "key": "total", + "value": "order.total * 2" + } + ], + "outputPath": "summary.stats", + "passThrough": true + } + }, + { + "id": "e4", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Chain", + "content": { + "expressions": [ + { + "id": "e4x0", + "key": "a", + "value": "total + 1" + }, + { + "id": "e4x1", + "key": "b", + "value": "$.a * 2" + } + ], + "inputField": "order", + "outputPath": "orderCopy", + "passThrough": false + } + }, + { + "id": "e5", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Downstream", + "content": { + "expressions": [ + { + "id": "e5x0", + "key": "seen", + "value": "customer.fullName" + }, + { + "id": "e5x1", + "key": "cityCopy", + "value": "cityUpper" + } + ], + "passThrough": true + } + }, + { + "id": "out", + "type": "outputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Response" + } + ], + "edges": [ + { + "id": "x0", + "sourceId": "in", + "targetId": "e1", + "type": "edge" + }, + { + "id": "x1", + "sourceId": "e1", + "targetId": "e5", + "type": "edge" + }, + { + "id": "x2", + "sourceId": "in", + "targetId": "e2", + "type": "edge" + }, + { + "id": "x3", + "sourceId": "e2", + "targetId": "e5", + "type": "edge" + }, + { + "id": "x4", + "sourceId": "in", + "targetId": "e3", + "type": "edge" + }, + { + "id": "x5", + "sourceId": "e3", + "targetId": "out", + "type": "edge" + }, + { + "id": "x6", + "sourceId": "in", + "targetId": "e4", + "type": "edge" + }, + { + "id": "x7", + "sourceId": "e4", + "targetId": "out", + "type": "edge" + }, + { + "id": "x8", + "sourceId": "e5", + "targetId": "out", + "type": "edge" + } + ], + "tests": [ + { + "input": { + "customer": { + "firstName": "John", + "lastName": "Doe", + "age": 30, + "address": { + "city": "Paris", + "zip": "75001" + } + }, + "order": { + "id": "A", + "total": 100 + } + } + }, + { + "input": { + "customer": { + "firstName": "Ann", + "lastName": "Lee", + "age": 55 + }, + "order": { + "total": 7.5 + } + } + }, + { + "input": { + "customer": { + "firstName": "Bob" + }, + "order": {} + } + }, + { + "input": { + "customer": "text", + "order": { + "total": "x" + } + } + }, + { + "input": { + "customer": null, + "order": null + } + }, + { + "input": { + "customer": { + "age": 41, + "address": { + "city": null + } + }, + "order": { + "total": -3 + } + } + }, + { + "input": {} + } + ] +} \ No newline at end of file diff --git a/core/engine/tests/data/compiled/loops.json b/core/engine/tests/data/compiled/loops.json new file mode 100644 index 00000000..b9ec5611 --- /dev/null +++ b/core/engine/tests/data/compiled/loops.json @@ -0,0 +1,312 @@ +{ + "nodes": [ + { + "id": "in", + "type": "inputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Request" + }, + { + "id": "e1", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Lines", + "content": { + "expressions": [ + { + "id": "e1x0", + "key": "total", + "value": "price * qty" + }, + { + "id": "e1x1", + "key": "label", + "value": "name + '!'" + }, + { + "id": "e1x2", + "key": "nested.flag", + "value": "price > 10" + } + ], + "executionMode": "loop", + "inputField": "lines", + "outputPath": "priced", + "passThrough": true + } + }, + { + "id": "e2", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Strict", + "content": { + "expressions": [ + { + "id": "e2x0", + "key": "ratio", + "value": "price / qty" + } + ], + "executionMode": "loop", + "inputField": "lines", + "outputPath": "ratios", + "passThrough": false + } + }, + { + "id": "t1", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Tiers", + "content": { + "hitPolicy": "first", + "executionMode": "loop", + "inputs": [ + { + "id": "t1i0", + "name": "price", + "field": "price" + }, + { + "id": "t1i1", + "name": "meta.kind", + "field": "meta.kind" + } + ], + "outputs": [ + { + "id": "t1o0", + "name": "tier", + "field": "tier" + }, + { + "id": "t1o1", + "name": "tags[]", + "field": "tags[]" + } + ], + "rules": [ + { + "_id": "t1r0", + "t1i0": "> 50", + "t1i1": "'gold'", + "t1o0": "'premium'", + "t1o1": "'big'" + }, + { + "_id": "t1r1", + "t1i0": "> 10", + "t1i1": "", + "t1o0": "'standard'", + "t1o1": "'mid'" + }, + { + "_id": "t1r2", + "t1i0": "", + "t1i1": "", + "t1o0": "", + "t1o1": "'any'" + } + ], + "inputField": "lines", + "outputPath": "tiers", + "passThrough": true + } + }, + { + "id": "t2", + "type": "decisionTableNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Collect", + "content": { + "hitPolicy": "collect", + "executionMode": "loop", + "inputs": [ + { + "id": "t2i0", + "name": "qty", + "field": "qty" + } + ], + "outputs": [ + { + "id": "t2o0", + "name": "code", + "field": "code" + } + ], + "rules": [ + { + "_id": "t2r0", + "t2i0": "> 1", + "t2o0": "qty * 10" + }, + { + "_id": "t2r1", + "t2i0": "", + "t2o0": "'one'" + } + ], + "inputField": "lines", + "outputPath": "codes", + "passThrough": false + } + }, + { + "id": "out", + "type": "outputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Response" + } + ], + "edges": [ + { + "id": "x0", + "sourceId": "in", + "targetId": "e1", + "type": "edge" + }, + { + "id": "x1", + "sourceId": "e1", + "targetId": "out", + "type": "edge" + }, + { + "id": "x2", + "sourceId": "in", + "targetId": "e2", + "type": "edge" + }, + { + "id": "x3", + "sourceId": "e2", + "targetId": "out", + "type": "edge" + }, + { + "id": "x4", + "sourceId": "in", + "targetId": "t1", + "type": "edge" + }, + { + "id": "x5", + "sourceId": "t1", + "targetId": "out", + "type": "edge" + }, + { + "id": "x6", + "sourceId": "in", + "targetId": "t2", + "type": "edge" + }, + { + "id": "x7", + "sourceId": "t2", + "targetId": "out", + "type": "edge" + } + ], + "tests": [ + { + "input": { + "lines": [ + { + "name": "a", + "price": 20, + "qty": 2, + "meta": { + "kind": "gold" + } + }, + { + "name": "b", + "price": 5, + "qty": 1 + }, + { + "name": "c", + "price": 60, + "qty": 0 + } + ] + } + }, + { + "input": { + "lines": [] + } + }, + { + "input": { + "lines": [ + { + "price": "x", + "qty": 2 + } + ] + } + }, + { + "input": { + "lines": [ + 1, + 2 + ] + } + }, + { + "input": { + "lines": "no" + } + }, + { + "input": {} + }, + { + "input": { + "lines": [ + { + "name": "z", + "price": 70, + "qty": 3, + "meta": { + "kind": "silver" + } + } + ] + } + }, + { + "input": { + "lines": [ + { + "name": null, + "price": null + } + ] + } + } + ] +} \ No newline at end of file diff --git a/core/engine/tests/data/compiled/objects.json b/core/engine/tests/data/compiled/objects.json new file mode 100644 index 00000000..1a5c8e51 --- /dev/null +++ b/core/engine/tests/data/compiled/objects.json @@ -0,0 +1,226 @@ +{ + "nodes": [ + { + "id": "in", + "type": "inputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Request" + }, + { + "id": "e1", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Pass", + "content": { + "expressions": [ + { + "id": "e1x0", + "key": "profile", + "value": "{ 'name': user.name, 'age': user.age, 'missing': user.none, 'tags': [user.name, 'x'] }" + }, + { + "id": "e1x1", + "key": "meta", + "value": "{}" + }, + { + "id": "e1x2", + "key": "nested", + "value": "{ 'a': { 'b': user.age * 2, 'c': null }, 'd': 'lit' }" + }, + { + "id": "e1x3", + "key": "user", + "value": "{ 'extra': 1, 'age': user.age + 1 }" + } + ], + "passThrough": true + } + }, + { + "id": "e2", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Strict", + "content": { + "expressions": [ + { + "id": "e2x0", + "key": "out", + "value": "{ 'n': user.age / user.div, 'flag': user.age > 30 }" + }, + { + "id": "e2x1", + "key": "computed", + "value": "{ [user.name]: 1 }" + } + ], + "passThrough": false + } + }, + { + "id": "e3", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Dollar", + "content": { + "expressions": [ + { + "id": "e3x0", + "key": "x", + "value": "{ 'a': user.age }" + }, + { + "id": "e3x1", + "key": "y", + "value": "$.x.a + 1" + } + ], + "passThrough": false + } + }, + { + "id": "e4", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Down", + "content": { + "expressions": [ + { + "id": "e4x0", + "key": "seen", + "value": "profile.name" + }, + { + "id": "e4x1", + "key": "deep", + "value": "nested.a.b" + } + ], + "passThrough": true + } + }, + { + "id": "out", + "type": "outputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Response" + } + ], + "edges": [ + { + "id": "x0", + "sourceId": "in", + "targetId": "e1", + "type": "edge" + }, + { + "id": "x1", + "sourceId": "e1", + "targetId": "e4", + "type": "edge" + }, + { + "id": "x2", + "sourceId": "e4", + "targetId": "out", + "type": "edge" + }, + { + "id": "x3", + "sourceId": "in", + "targetId": "e2", + "type": "edge" + }, + { + "id": "x4", + "sourceId": "e2", + "targetId": "out", + "type": "edge" + }, + { + "id": "x5", + "sourceId": "in", + "targetId": "e3", + "type": "edge" + }, + { + "id": "x6", + "sourceId": "e3", + "targetId": "out", + "type": "edge" + } + ], + "tests": [ + { + "input": { + "user": { + "name": "ann", + "age": 40, + "div": 2 + }, + "profile": { + "keep": 1, + "name": "old" + }, + "nested": "text" + } + }, + { + "input": { + "user": { + "name": "bob", + "age": 20, + "div": 0 + } + } + }, + { + "input": { + "user": { + "name": null, + "age": null + } + } + }, + { + "input": { + "user": "str" + } + }, + { + "input": {} + }, + { + "input": { + "user": { + "name": "cy", + "age": 31, + "div": 3, + "none": 5 + }, + "meta": { + "k": 1 + } + } + } + ] +} \ No newline at end of file diff --git a/core/engine/tests/data/compiled/schema-input.json b/core/engine/tests/data/compiled/schema-input.json new file mode 100644 index 00000000..1e05e7a9 --- /dev/null +++ b/core/engine/tests/data/compiled/schema-input.json @@ -0,0 +1,229 @@ +{ + "nodes": [ + { + "id": "in", + "type": "inputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Request", + "content": { + "schema": "{\"type\": \"object\", \"required\": [\"customer\"], \"properties\": {\"customer\": {\"type\": \"object\", \"required\": [\"age\", \"tier\"], \"additionalProperties\": false, \"properties\": {\"age\": {\"type\": \"integer\"}, \"tier\": {\"type\": \"string\", \"enum\": [\"gold\", \"silver\"]}, \"name\": {\"type\": \"string\"}, \"active\": {\"type\": \"boolean\"}, \"tags\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"address\": {\"type\": \"object\", \"properties\": {\"zip\": {\"type\": \"string\"}, \"floor\": {\"type\": \"number\"}}}}}, \"order\": {\"type\": \"object\", \"properties\": {\"total\": {\"type\": \"number\"}}}, \"note\": {\"title\": \"free\"}}}" + } + }, + { + "id": "e1", + "type": "expressionNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Calc", + "content": { + "passThrough": true, + "expressions": [ + { + "id": "a", + "key": "doubled", + "value": "customer.age * 2" + }, + { + "id": "b", + "key": "vip", + "value": "customer.tier == 'gold'" + } + ] + } + }, + { + "id": "out", + "type": "outputNode", + "position": { + "x": 0, + "y": 0 + }, + "name": "Response" + } + ], + "edges": [ + { + "id": "x0", + "sourceId": "in", + "targetId": "e1", + "type": "edge" + }, + { + "id": "x1", + "sourceId": "e1", + "targetId": "out", + "type": "edge" + } + ], + "tests": [ + { + "input": { + "customer": { + "age": 30, + "tier": "gold", + "name": "A", + "active": true, + "tags": [ + "x", + "y" + ], + "address": { + "zip": "1", + "floor": 2.5 + } + }, + "order": { + "total": 10 + } + } + }, + { + "input": { + "customer": { + "age": 30, + "tier": "silver" + } + } + }, + { + "input": { + "customer": { + "age": 30.5, + "tier": "gold" + } + } + }, + { + "input": { + "customer": { + "age": 30, + "tier": "bronze" + } + } + }, + { + "input": { + "customer": { + "age": 30 + } + } + }, + { + "input": { + "customer": { + "tier": "gold" + } + } + }, + { + "input": { + "customer": { + "age": 30, + "tier": "gold", + "extra": 1 + } + } + }, + { + "input": { + "customer": { + "age": "30", + "tier": "gold" + } + } + }, + { + "input": { + "customer": { + "age": 30, + "tier": "gold", + "active": "yes" + } + } + }, + { + "input": { + "customer": { + "age": 30, + "tier": "gold", + "tags": [ + "x", + 1 + ] + } + } + }, + { + "input": { + "customer": { + "age": 30, + "tier": "gold", + "address": { + "zip": 5 + } + } + } + }, + { + "input": { + "customer": { + "age": 30, + "tier": "gold" + }, + "order": { + "total": "x" + } + } + }, + { + "input": { + "customer": { + "age": 30, + "tier": "gold" + }, + "note": { + "anything": [ + 1, + 2 + ] + } + } + }, + { + "input": { + "order": { + "total": 1 + } + } + }, + { + "input": {} + }, + { + "input": { + "customer": null + } + }, + { + "input": { + "customer": { + "age": null, + "tier": "gold" + } + } + }, + { + "input": { + "customer": { + "age": 4.0, + "tier": "gold" + } + } + } + ] +} \ No newline at end of file diff --git a/core/engine/tests/decision.rs b/core/engine/tests/decision.rs index 6273e4ea..8fa2958c 100644 --- a/core/engine/tests/decision.rs +++ b/core/engine/tests/decision.rs @@ -554,3 +554,47 @@ async fn merged_inputs_do_not_mutate_parent_node_outputs() { assert_eq!(output_of("pa"), json!({ "a": 1, "pa": 10 }).into()); assert_eq!(output_of("pb"), json!({ "a": 1, "pb": 20 }).into()); } + +#[tokio::test] +#[cfg_attr(miri, ignore)] +async fn evaluate_batch_leaves_the_callers_contexts_unchanged() { + let content = json!({ + "nodes": [ + { "id": "in", "name": "input", "type": "inputNode", "content": {} }, + { "id": "calc", "name": "calc", "type": "expressionNode", "content": { + "passThrough": true, "inputField": null, "outputPath": null, "executionMode": "single", + "expressions": [ + { "id": "e1", "key": "copy", "value": "inp" }, + { "id": "e2", "key": "copy.extra", "value": "1" } + ] + } }, + { "id": "out", "name": "output", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "a", "sourceId": "in", "targetId": "calc", "type": "edge" }, + { "id": "b", "sourceId": "calc", "targetId": "out", "type": "edge" } + ] + }); + let content: zen_engine::model::DecisionContent = serde_json::from_value(content).unwrap(); + let zen_engine::model::DecisionContent::Graph(graph) = content else { + panic!("graph"); + }; + let mut compiled = Decision::from(graph.clone()); + compiled.compile(); + #[allow(unused_mut)] + let mut decisions = vec![Decision::from(graph.clone()), compiled.clone()]; + #[cfg(feature = "driver")] + decisions.push(compiled.interpreted()); + for decision in decisions { + let contexts: Vec = (0..3) + .map(|v| json!({ "inp": { "v": v } }).into()) + .collect(); + let before: Vec = contexts.iter().map(Variable::to_value).collect(); + let results = decision + .evaluate_batch(&contexts, EvaluationOptions::default()) + .await; + let after: Vec = contexts.iter().map(Variable::to_value).collect(); + assert_eq!(before, after); + assert!(results.iter().all(Result::is_ok)); + } +} diff --git a/core/engine/tests/degraded.rs b/core/engine/tests/degraded.rs new file mode 100644 index 00000000..86ee0873 --- /dev/null +++ b/core/engine/tests/degraded.rs @@ -0,0 +1,63 @@ +use serde_json::json; +use zen_engine::model::GraphContent; +use zen_engine::Decision; + +fn decision() -> Decision { + let graph: GraphContent = serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "in", "type": "inputNode", "content": {} }, + { "id": "broken", "name": "broken", "type": "expressionNode", "content": { + "expressions": [{ "id": "e", "key": "y", "value": "1 +" }] + } }, + { "id": "fine", "name": "fine", "type": "expressionNode", "content": { + "expressions": [{ "id": "e", "key": "z", "value": "2" }] + } }, + { "id": "switch", "name": "switch", "type": "switchNode", "content": { + "hitPolicy": "first", + "statements": [ + { "id": "bad", "condition": "x >" }, + { "id": "rest", "condition": "" } + ] + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "a", "sourceId": "in", "targetId": "fine" }, + { "id": "b", "sourceId": "fine", "targetId": "switch" }, + { "id": "c", "sourceId": "switch", "targetId": "broken", "sourceHandle": "bad" }, + { "id": "d", "sourceId": "switch", "targetId": "out", "sourceHandle": "rest" }, + { "id": "e", "sourceId": "broken", "targetId": "out" } + ] + })) + .expect("graph"); + let mut decision = Decision::from(graph); + decision.compile(); + decision +} + +#[test] +fn nodes_that_fail_to_compile_report_why() { + let decision = decision(); + let mut degraded = zen_engine::diagnostics::degraded(&decision).expect("compiled"); + degraded.sort(); + let nodes: Vec<&str> = degraded.iter().map(|(node, _)| node.as_str()).collect(); + assert_eq!(nodes, ["broken", "switch"]); + assert!(degraded.iter().all(|(_, why)| !why.is_empty())); +} + +#[tokio::test] +async fn an_invalid_switch_condition_never_matches() { + let decision = decision(); + let response = decision + .evaluate(json!({ "x": 1 }).into()) + .await + .expect("evaluates"); + assert_eq!(response.result.to_value(), json!({ "z": 2 })); +} + +#[test] +fn engine_and_decision_stay_send_and_sync() { + fn check() {} + check::(); + check::(); +} diff --git a/core/engine/tests/dictionary_retry.rs b/core/engine/tests/dictionary_retry.rs new file mode 100644 index 00000000..b7c71cc7 --- /dev/null +++ b/core/engine/tests/dictionary_retry.rs @@ -0,0 +1,101 @@ +use serde_json::{json, Value}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use zen_engine::loader::{ + CachedLoader, DecisionLoader, DynamicLoader, LoaderError, LoaderResponse, MemoryLoader, +}; +use zen_engine::model::DecisionContent; +use zen_engine::{DecisionEngine, DecisionGraphResponse, EvaluationError}; + +#[derive(Debug)] +struct Flaky { + inner: MemoryLoader, + fails: AtomicUsize, +} + +impl DecisionLoader for Flaky { + fn load<'a>( + &'a self, + key: &'a str, + ) -> Pin + 'a + Send>> { + Box::pin(async move { + if key == "dicts" && self.fails.load(Ordering::SeqCst) > 0 { + self.fails.fetch_sub(1, Ordering::SeqCst); + return Err(LoaderError::NotFound(key.to_string())); + } + self.inner.load(key).await + }) + } +} + +fn document(value: Value) -> DecisionContent { + serde_json::from_value(value).expect("valid decision content") +} + +fn flaky(fails: usize) -> Arc { + let inner = MemoryLoader::default(); + inner.add( + "dicts", + document(json!({ + "imports": [], + "blocks": [{ "id": "dict1", "type": "dictionary", "props": { "data": { "name": "customerTier", + "entries": [{ "id": "e0", "value": "VIP", "label": "v" }, { "id": "e1", "value": "STD", "label": "s" }] } } }] + })), + ); + let schema = + json!({ "type": "object", "properties": { "tier": { "$dictionary": "customerTier" } } }); + inner.add( + "g", + document(json!({ + "imports": ["dicts"], + "nodes": [ + { "id": "in", "name": "in", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [{ "id": "e", "sourceId": "in", "targetId": "out", "sourceHandle": null }] + })), + ); + Arc::new(Flaky { + inner, + fails: AtomicUsize::new(fails), + }) +} + +fn message(result: &Result>) -> String { + match result { + Ok(response) => format!("ok {}", serde_json::to_string(&response.result).unwrap()), + Err(error) => format!("error {error}"), + } +} + +#[tokio::test] +async fn a_failed_dictionary_load_is_retried_by_the_cached_loader() { + let loader: Arc = flaky(1); + let engine = DecisionEngine::default().with_loader(Arc::new(CachedLoader::from(loader))); + let first = message(&engine.evaluate("g", json!({ "tier": "GOLD" }).into()).await); + let second = message(&engine.evaluate("g", json!({ "tier": "GOLD" }).into()).await); + let third = message(&engine.evaluate("g", json!({ "tier": "VIP" }).into()).await); + assert!(first.contains("dicts"), "{first}"); + assert!( + second.starts_with("error") && !second.contains("dicts"), + "{second}" + ); + assert!(third.starts_with("ok"), "{third}"); +} + +#[tokio::test] +async fn resolve_schemas_keeps_failing_until_it_succeeds() { + let loader = flaky(2); + let DecisionContent::Graph(graph) = loader.inner.load("g").await.unwrap().as_ref().clone() + else { + panic!("graph"); + }; + let dynamic: DynamicLoader = loader; + let mut graph = (*graph).clone(); + assert!(graph.resolve_schemas(&dynamic).await.is_err()); + assert!(graph.resolve_schemas(&dynamic).await.is_err()); + assert!(graph.resolve_schemas(&dynamic).await.is_ok()); + assert!(graph.resolve_schemas(&dynamic).await.is_ok()); +} diff --git a/core/engine/tests/engine.rs b/core/engine/tests/engine.rs index bceae4c5..4075ad33 100644 --- a/core/engine/tests/engine.rs +++ b/core/engine/tests/engine.rs @@ -300,25 +300,62 @@ async fn engine_graph_tests() { .unwrap() .result; - assert_eq!( - test_case.output, result, - "Decision file: {file_name}.\nInput:\n {input:#?}" + assert!( + Precision::same(&test_case.output, &result), + "Decision file: {file_name}.\nInput:\n {input:#?}\n{:?} != {result:?}", + test_case.output ); - assert_eq!( - test_case.output, result_compiled, - "Compiled decision file: {file_name}.\nInput:\n {input:#?}" + assert!( + Precision::same(&test_case.output, &result_compiled), + "Compiled decision file: {file_name}.\nInput:\n {input:#?}\n{:?} != {result_compiled:?}", + test_case.output ); } } } +struct Precision; + +impl Precision { + fn same(expected: &Variable, actual: &Variable) -> bool { + if cfg!(feature = "arbitrary_precision") { + return expected == actual; + } + match (expected, actual) { + (Variable::Number(a), Variable::Number(b)) => { + let (a, b) = ( + rust_decimal::prelude::ToPrimitive::to_f64(a).unwrap_or(f64::NAN), + rust_decimal::prelude::ToPrimitive::to_f64(b).unwrap_or(f64::NAN), + ); + (a - b).abs() <= a.abs().max(b.abs()) * f64::EPSILON * 4.0 + } + (Variable::Array(a), Variable::Array(b)) => { + let (a, b) = (a.borrow(), b.borrow()); + a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| Self::same(a, b)) + } + (Variable::Object(a), Variable::Object(b)) => { + let (a, b) = (a.borrow(), b.borrow()); + a.len() == b.len() + && a.iter().all(|(key, value)| { + b.get(key).is_some_and(|other| Self::same(value, other)) + }) + } + _ => expected == actual, + } + } +} + fn mock_datetime() { std::env::set_var("__ZEN_MOCK_UTC_TIME", "2025-08-19T16:55:02.078Z"); } #[tokio::test] #[cfg_attr(miri, ignore)] +#[cfg_attr( + not(feature = "arbitrary_precision"), + ignore = "snapshots record arbitrary-precision decimals" +)] async fn engine_snapshot_tests() { mock_datetime(); diff --git a/core/engine/tests/function_batch_isolation.rs b/core/engine/tests/function_batch_isolation.rs new file mode 100644 index 00000000..8113d07a --- /dev/null +++ b/core/engine/tests/function_batch_isolation.rs @@ -0,0 +1,122 @@ +use serde_json::{json, Value}; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use zen_engine::loader::MemoryLoader; +use zen_engine::model::{DecisionContent, GraphContent}; +use zen_engine::{Decision, EvaluationOptions, ZEN_CONFIG}; +use zen_expression::Variable; + +fn function(id: &str, source: &str) -> Value { + json!({ "id": id, "name": id, "type": "functionNode", "content": { "version": "v2", "source": source } }) +} + +fn chain(nodes: Vec) -> GraphContent { + let mut all = + vec![json!({ "id": "input", "name": "input", "type": "inputNode", "content": {} })]; + all.extend(nodes); + all.push(json!({ "id": "output", "name": "output", "type": "outputNode", "content": {} })); + let edges: Vec = all + .windows(2) + .enumerate() + .map(|(i, w)| json!({ "id": format!("e{i}"), "sourceId": w[0]["id"], "targetId": w[1]["id"] })) + .collect(); + serde_json::from_value(json!({ "nodes": all, "edges": edges })).expect("graph") +} + +fn outcome(result: Result) -> Value { + match result { + Ok(value) => value.to_value(), + Err(error) => json!({ "error": error }), + } +} + +async fn compare(decision: &Decision, inputs: &[Value]) -> Vec { + let rows: Vec = (0..inputs.len() * 3) + .map(|i| Variable::from(inputs[i % inputs.len()].clone())) + .collect(); + let mut single = Vec::new(); + for row in &rows { + let result = decision.evaluate(row.depth_clone(64)).await; + single.push(outcome(result.map(|r| r.result).map_err(|e| e.to_string()))); + } + let batch: Vec = decision + .evaluate_batch(&rows, EvaluationOptions::default()) + .await + .into_iter() + .map(|r| outcome(r.map(|r| r.result).map_err(|e| e.to_string()))) + .collect(); + assert_eq!(batch, single); + batch +} + +#[tokio::test] +async fn promise_and_bigint_handlers_match_single_rows_in_a_batch() { + let source = "export const handler = async (input) => { const all = await Promise.allSettled([Promise.reject(new Error('no')), Promise.resolve(input.n)]); const first = await Promise.race([new Promise((resolve) => resolve(input.n * 2))]); return { first, settled: all.map((s) => s.status), big: Number(BigInt(input.n) * 3n) }; };"; + let decision = Decision::from(chain(vec![function("f", source)])); + let out = compare(&decision, &[json!({ "n": 1 }), json!({ "n": 2 })]).await; + assert_eq!( + out[1], + json!({ "first": 4, "settled": ["rejected", "fulfilled"], "big": 6 }) + ); +} + +#[tokio::test] +async fn a_stateful_child_called_through_zen_evaluate_is_fresh_on_every_row() { + let loader = Arc::new(MemoryLoader::default()); + let child: DecisionContent = serde_json::from_value( + serde_json::to_value(chain(vec![function( + "c", + "let n = 0;\nexport const handler = async (input) => ({ n: ++n });", + )])) + .expect("child"), + ) + .expect("child content"); + loader.add("counter", child); + let source = "import zen from 'zen';\nexport const handler = async (input) => { const a = await zen.evaluate('counter', {}); const b = await zen.evaluate('counter', {}); return { a: a.result.n, b: b.result.n, v: input.v }; };"; + let decision = Decision::from(chain(vec![function("f", source)])).with_loader(loader); + let out = compare(&decision, &[json!({ "v": 1 }), json!({ "v": 2 })]).await; + assert!( + out.iter() + .all(|row| row["a"] == json!(1) && row["b"] == json!(1)), + "{out:?}" + ); +} + +#[tokio::test] +async fn globals_written_by_one_row_are_not_seen_by_the_next() { + let source = "export const handler = async (input) => { const before = globalThis.specRows ?? 0; globalThis.specRows = before + 1; return { before }; };"; + let decision = Decision::from(chain(vec![function("f", source)])); + let out = compare(&decision, &[json!({}), json!({ "x": 1 })]).await; + assert!(out.iter().all(|row| row["before"] == json!(0)), "{out:?}"); +} + +#[tokio::test] +async fn a_row_that_times_out_does_not_fail_its_neighbours_in_a_batch() { + ZEN_CONFIG + .function_timeout_millis + .store(100, Ordering::Relaxed); + let source = "export const handler = async (input) => { let i = 0; while (input.spin) { i++; } return { ok: true, i }; };"; + let decision = Decision::from(chain(vec![function("f", source)])); + let rows: Vec = [ + json!({ "spin": false }), + json!({ "spin": true }), + json!({ "spin": false }), + ] + .into_iter() + .map(Variable::from) + .collect(); + let out = decision + .evaluate_batch(&rows, EvaluationOptions::default()) + .await; + assert!( + out[0].is_ok(), + "{:?}", + out[0].as_ref().err().map(|e| e.to_string()) + ); + assert!(out[1].is_err()); + assert!( + out[2].is_ok(), + "{:?}", + out[2].as_ref().err().map(|e| e.to_string()) + ); +} diff --git a/core/engine/tests/golden.rs b/core/engine/tests/golden.rs new file mode 100644 index 00000000..73b6769a --- /dev/null +++ b/core/engine/tests/golden.rs @@ -0,0 +1,1501 @@ +#[allow(dead_code)] +mod conformance; +#[path = "support/fixture.rs"] +mod fixture; +#[allow(dead_code)] +#[path = "support/policies.rs"] +mod policies; +#[path = "support/policy_gen.rs"] +mod policy_gen; +mod support; + +use conformance::run::{GraphRun, Guard, PolicyRun}; +use conformance::{Dialect, Spec, Suite}; +use fixture::{Fixture, NETWORK_BOUND, TIME_BOUND}; +use policies::{Anchor, Generated, PolicyCase}; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex, MutexGuard}; +use support::columns::Built; +#[cfg(feature = "driver")] +use support::golden::Live; +use support::golden::{Canon, Entry, Golden, Outcome}; +use zen_engine::policy::{EvaluateRequest, PolicyWorkspace}; +use zen_engine::{ + Decision, EvaluationError, EvaluationOptions, EvaluationSerializedOptions, EvaluationTraceKind, + ZEN_CONFIG, +}; +use zen_expression::lane::Columns; +use zen_expression::Variable; + +static GRAPH: Mutex<()> = Mutex::new(()); + +struct Nodes; + +impl Nodes { + const CHAPTER: &'static str = "15-nodes-references"; + + fn modes(suite: &Suite) -> Vec { + match suite.file.contains(Self::CHAPTER) { + true => vec![true, false], + false => vec![true], + } + } + + fn id(suite: &Suite, nodes: bool) -> String { + match nodes { + true => suite.id(), + false => format!("{}#nodes-off", suite.id()), + } + } + + fn set(nodes: bool) { + ZEN_CONFIG.nodes_in_context.store(nodes, Ordering::Relaxed); + } + + fn lock() -> MutexGuard<'static, ()> { + GRAPH + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } +} + +struct Rows; + +impl Rows { + fn cycled(rows: &[Value], times: usize) -> Vec { + (0..rows.len() * times) + .map(|i| rows[i % rows.len()].clone()) + .collect() + } + + fn spec_graph(rows: &[Value]) -> Vec<(Built, bool)> { + let cycled = Self::cycled(rows, 3); + Built::new(rows) + .into_iter() + .chain(Built::lists(rows)) + .chain(Built::new(&cycled)) + .chain(Built::nested(rows)) + .chain(Built::nested(&cycled)) + .map(|b| (b, true)) + .collect() + } + + fn spec_policy(rows: &[Value]) -> Vec<(Built, bool)> { + let cycled = Self::cycled(rows, 3); + let flat = Built::new(rows) + .into_iter() + .chain(Built::lists(rows)) + .chain(Built::new(&cycled)) + .map(|b| (b, false)); + let nested = Built::nested(rows) + .into_iter() + .chain(Built::nested(&cycled)) + .map(|b| (b, true)); + flat.chain(nested).collect() + } + + fn generated(inputs: &[Value]) -> Vec<(Built, bool)> { + let flat = Built::new(inputs) + .into_iter() + .chain(Built::lists(inputs)) + .map(|b| (b, false)); + flat.chain(Built::nested(inputs).map(|b| (b, true))) + .collect() + } + + fn fixture(variants: &[Value]) -> Vec<(Built, bool)> { + let Some(first) = Built::new(variants) else { + return Vec::new(); + }; + let cycled = Self::cycled(variants, 4); + std::iter::once(first) + .chain(Built::lists(variants)) + .chain(Built::new(&cycled)) + .chain(Built::nested(variants)) + .chain(Built::nested(&cycled)) + .map(|b| (b, true)) + .collect() + } + + fn with(built: &Built, structs: bool, f: impl FnOnce(&Columns) -> T) -> T { + match structs { + true => { + let fields = built.fields(); + let parts = built.structs(&fields); + f(&built.columns_with(&parts)) + } + false => f(&built.columns()), + } + } + + fn of(builds: &[(Built, bool)]) -> Vec { + builds + .iter() + .flat_map(|(built, structs)| { + Self::with(built, *structs, |c| { + (0..c.rows).map(|r| c.row(r)).collect::>() + }) + }) + .collect() + } +} + +struct Graphs; + +impl Graphs { + fn traced() -> EvaluationOptions { + EvaluationOptions { + trace: true, + max_depth: 10, + } + } + + fn serialized() -> EvaluationSerializedOptions { + EvaluationSerializedOptions { + trace: EvaluationTraceKind::Reference, + max_depth: 10, + } + } + + #[cfg(feature = "driver")] + async fn record( + golden: &mut Golden, + id: &str, + walker: &Decision, + input: &Variable, + traced: bool, + ) { + let plain = Outcome::graph(&walker.evaluate(input.depth_clone(64)).await); + let entry = Entry::new(id, &[], input, plain); + let entry = match traced { + true => { + let traced = Outcome::graph_traced( + &walker + .evaluate_with_opts(input.depth_clone(64), Self::traced()) + .await, + EvaluationTraceKind::Default, + ); + let reference = Canon::reference( + &traced, + walker + .evaluate_serialized(input.depth_clone(64), Self::serialized()) + .await, + ); + entry.traced(traced, Some(reference)) + } + false => entry, + }; + golden.insert(entry); + } + + async fn verify( + check: &mut Check, + golden: &Golden, + id: &str, + decision: &Decision, + input: &Variable, + label: &str, + ) { + let key = Canon::key(id, &[], input); + let Some(entry) = check.entry(golden, &key) else { + return; + }; + let plain = Outcome::graph(&decision.evaluate(input.depth_clone(64)).await); + check.same(&key, &format!("{label} single"), &entry.plain, &plain); + if let Some(traced) = &entry.traced { + let got = Outcome::graph_traced( + &decision + .evaluate_with_opts(input.depth_clone(64), Self::traced()) + .await, + EvaluationTraceKind::Default, + ); + check.same(&key, &format!("{label} traced"), traced, &got); + let reference = Canon::reference( + traced, + decision + .evaluate_serialized(input.depth_clone(64), Self::serialized()) + .await, + ); + check.values( + &key, + &format!("{label} reference"), + entry.reference.as_ref(), + Some(&reference), + ); + } + } + + async fn columns( + check: &mut Check, + golden: &Golden, + id: &str, + decision: &Decision, + builds: &[(Built, bool)], + ) { + for (built, _) in builds { + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let output = decision + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + for row in 0..columns.rows { + let input = columns.row(row); + let key = Canon::key(id, &[], &input); + let Some(entry) = check.entry(golden, &key) else { + continue; + }; + let got = match &output.errors[row] { + Some(error) => Outcome::Err { + debug: error.to_string(), + value: Canon::value(serde_json::to_value(&**error).unwrap_or(Value::Null)), + }, + None => Outcome::Ok(Canon::variable(&output.row(row))), + }; + check.same( + &key, + "columns", + &entry.plain.normalized(Built::normalized), + &got.normalized(Built::normalized), + ); + } + } + } + + async fn batch( + check: &mut Check, + golden: &Golden, + id: &str, + decision: &Decision, + inputs: &[Variable], + label: &str, + ) { + let keys: Vec = inputs + .iter() + .map(|input| Canon::key(id, &[], input)) + .collect(); + let results = decision + .evaluate_batch(inputs, EvaluationOptions::default()) + .await; + for (key, result) in keys.into_iter().zip(&results) { + if let Some(entry) = check.entry(golden, &key) { + check.same(&key, label, &entry.plain, &Outcome::graph(result)); + } + } + } +} + +#[cfg(feature = "driver")] +struct Modes; + +#[cfg(feature = "driver")] +impl Modes { + const ALL: [EvaluationTraceKind; 4] = [ + EvaluationTraceKind::Default, + EvaluationTraceKind::String, + EvaluationTraceKind::Reference, + EvaluationTraceKind::ReferenceString, + ]; + + async fn compare( + check: &mut Check, + live: &Golden, + id: &str, + walker: &Decision, + decision: &Decision, + input: &Variable, + label: &str, + ) { + let key = Canon::key(id, &[], input); + if check + .entry(live, &key) + .and_then(|entry| entry.traced.as_ref()) + .is_none() + { + return; + } + for mode in Self::ALL { + let options = EvaluationSerializedOptions { + trace: mode, + max_depth: 10, + }; + let reference = matches!( + mode, + EvaluationTraceKind::Reference | EvaluationTraceKind::ReferenceString + ); + let want = Canon::mode( + walker + .evaluate_serialized(input.depth_clone(64), options) + .await, + reference, + ); + let got = Canon::mode( + decision + .evaluate_serialized(input.depth_clone(64), options) + .await, + reference, + ); + check.same(&key, &format!("{label} {mode:?}"), &want, &got); + } + } +} + +struct Policies; + +impl Policies { + fn request(path: &str, input: &Variable, goals: &[String], trace: bool) -> EvaluateRequest { + EvaluateRequest { + policy_path: Arc::from(path), + input: input.depth_clone(64), + goals: goals.iter().map(|g| Arc::from(g.as_str())).collect(), + trace, + } + } + + #[cfg(feature = "driver")] + fn record( + golden: &mut Golden, + ws: &PolicyWorkspace, + id: &str, + path: &str, + input: &Variable, + goals: &[String], + traced: bool, + fingerprint: Option, + ) { + let plain = Outcome::policy(Live::policy(ws, &Self::request(path, input, goals, false))); + let entry = Entry::new(id, goals, input, plain).fingerprint(fingerprint); + let entry = match traced { + true => entry + .traced( + Outcome::policy_traced(Live::policy( + ws, + &Self::request(path, input, goals, true), + )), + None, + ) + .enhanced(Outcome::policy_traced(Live::enhanced( + ws, + &Self::request(path, input, goals, false), + ))), + false => entry, + }; + golden.insert(entry); + } + + fn verify( + check: &mut Check, + golden: &Golden, + ws: &PolicyWorkspace, + id: &str, + path: &str, + input: &Variable, + goals: &[String], + fingerprint: Option<&str>, + ) { + let key = Canon::key(id, goals, input); + let Some(entry) = check.entry(golden, &key) else { + return; + }; + if fingerprint.is_some() && entry.fingerprint.as_deref() != fingerprint { + check + .failures + .push(format!("{key}: fingerprint changed, goldens are stale")); + } + check.same( + &key, + "single", + &entry.plain, + &Outcome::policy(ws.evaluate(&Self::request(path, input, goals, false))), + ); + if let Some(traced) = &entry.traced { + check.same( + &key, + "traced", + traced, + &Outcome::policy_traced(ws.evaluate(&Self::request(path, input, goals, true))), + ); + } + if let Some(enhanced) = &entry.enhanced { + check.same( + &key, + "enhanced", + enhanced, + &Outcome::policy_traced( + ws.enhance_trace(&Self::request(path, input, goals, false)), + ), + ); + } + } + + fn batch( + check: &mut Check, + golden: &Golden, + ws: &PolicyWorkspace, + id: &str, + path: &str, + requests: &[(Variable, Vec)], + ) { + let batch: Vec = requests + .iter() + .map(|(input, goals)| Self::request(path, input, goals, false)) + .collect(); + for ((input, goals), result) in requests.iter().zip(ws.evaluate_batch(&batch)) { + let key = Canon::key(id, goals, input); + if let Some(entry) = check.entry(golden, &key) { + check.same(&key, "batch", &entry.plain, &Outcome::policy(result)); + } + } + } + + fn columns( + check: &mut Check, + golden: &Golden, + ws: &PolicyWorkspace, + id: &str, + path: &str, + goals: &[String], + builds: &[(Built, bool)], + ) { + let targets: Vec> = goals.iter().map(|g| Arc::from(g.as_str())).collect(); + for (built, structs) in builds { + Rows::with(built, *structs, |columns| { + let output = ws.evaluate_columns(&Arc::from(path), &targets, columns); + for row in 0..columns.rows { + let input = columns.row(row); + let key = Canon::key(id, goals, &input); + let Some(entry) = check.entry(golden, &key) else { + continue; + }; + let error = match &output { + Ok(output) => output.errors[row] + .as_deref() + .and_then(zen_engine::EvaluationError::policy), + Err(refused) => Some(refused), + }; + let got = match (error, &output) { + (Some(error), _) => Outcome::Err { + debug: Outcome::debug(error), + value: Value::Null, + }, + (None, Ok(output)) => Outcome::Ok(Canon::variable(&output.row(row))), + (None, Err(_)) => Outcome::missing(&key), + }; + let want = match &entry.plain { + Outcome::Err { debug, .. } => Outcome::Err { + debug: debug.clone(), + value: Value::Null, + }, + ok => ok.normalized(Built::normalized), + }; + check.same(&key, "columns", &want, &got.normalized(Built::normalized)); + } + }); + } + } +} + +#[derive(Default)] +struct Check { + failures: Vec, + compared: usize, + ordered: usize, + divergent: BTreeSet, + skipped: usize, +} + +impl Check { + fn entry<'g>(&mut self, golden: &'g Golden, key: &str) -> Option<&'g Entry> { + match golden.get(key) { + None => { + self.failures.push(format!("{key}: missing golden entry")); + None + } + Some(entry) if entry.ordered => { + self.ordered += 1; + None + } + entry => entry, + } + } + + fn diverges(&mut self, suite: &Suite, id: &str, inputs: impl IntoIterator) { + for input in inputs { + let value = Built::normalized(input.to_value()); + let case = suite + .cases + .iter() + .find(|c| Built::normalized(c.input.to_value()) == value) + .unwrap_or(&suite.cases[0]); + if case.engines.is_some() { + self.divergent.insert(Canon::key(id, &[], &input)); + } + } + } + + fn same(&mut self, key: &str, path: &str, want: &Outcome, got: &Outcome) { + if self.divergent.contains(key) { + self.skipped += 1; + return; + } + self.compared += 1; + if want != got { + self.failures.push(format!( + "{key} {path}\n golden {}\n got {}", + want.show(), + got.show() + )); + } + } + + fn values(&mut self, key: &str, path: &str, want: Option<&Value>, got: Option<&Value>) { + self.compared += 1; + if want != got { + self.failures + .push(format!("{key} {path}\n golden {want:?}\n got {got:?}")); + } + } + + fn finish(mut self, golden: &Golden, label: &str) { + let unvisited = golden.unvisited(); + if !unvisited.is_empty() { + self.failures.push(format!( + "{} golden entries never checked, e.g. {:?}", + unvisited.len(), + unvisited.iter().take(5).collect::>() + )); + } + eprintln!("{label}: {} entries, {} comparisons, {} key-order dependent lookups and {} documented engine divergences skipped, {} failures", golden.len(), self.compared, self.ordered, self.skipped, self.failures.len()); + let limit = std::env::var("SPEC_SHOW") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(40); + assert!( + self.failures.is_empty(), + "{} failures:\n{}", + self.failures.len(), + self.failures + .iter() + .take(limit) + .cloned() + .collect::>() + .join("\n") + ); + } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +enum Corpus { + SpecGraph, + SpecPolicy, + Generated, + PolicyFixtures, + Anchor, + GraphFixtures, +} + +impl Corpus { + #[cfg(feature = "driver")] + const ALL: [Corpus; 6] = [ + Corpus::SpecGraph, + Corpus::SpecPolicy, + Corpus::Generated, + Corpus::PolicyFixtures, + Corpus::Anchor, + Corpus::GraphFixtures, + ]; + + fn name(&self) -> &'static str { + match self { + Corpus::SpecGraph => "spec-graph", + Corpus::SpecPolicy => "spec-policy", + Corpus::Generated => "generated/policy", + Corpus::PolicyFixtures => "policy-fixtures", + Corpus::Anchor => "anchor", + Corpus::GraphFixtures => "graph-fixtures", + } + } + + #[cfg(feature = "driver")] + fn shard(&self, entry: &Entry) -> Option { + match self { + Corpus::SpecGraph | Corpus::SpecPolicy => { + let file = entry.suite.split('#').next().unwrap_or_default(); + let name = file.rsplit('/').next().unwrap_or(file); + Some(name.trim_end_matches(".json5").to_string()) + } + _ => None, + } + } + + #[cfg(feature = "driver")] + fn selected() -> Vec { + let only = std::env::var("GOLDEN_CORPUS").ok(); + Self::ALL + .into_iter() + .filter(|c| only.as_ref().is_none_or(|o| c.name().contains(o.as_str()))) + .collect() + } + + #[cfg(feature = "driver")] + fn record(&self) -> Golden { + Golden::prepare(); + let mut golden = Golden::new(self.name()); + let mut failures = Vec::new(); + match self { + Corpus::SpecGraph => Self::spec_graph(&mut golden, &mut failures), + Corpus::SpecPolicy => Self::spec_policy(&mut golden, &mut failures), + Corpus::Generated => Self::generated(&mut golden), + Corpus::PolicyFixtures => Self::policy_fixtures(&mut golden), + Corpus::Anchor => Self::anchor(&mut golden), + Corpus::GraphFixtures => Guard::block(Self::graph_fixtures(&mut golden)), + } + failures.extend(golden.conflicts.iter().cloned()); + assert!( + failures.is_empty(), + "{}: recording failed:\n{}", + self.name(), + failures.join("\n") + ); + golden + } + + #[cfg(feature = "driver")] + fn spec_graph(golden: &mut Golden, failures: &mut Vec) { + let (suites, problems) = Spec::suites(Dialect::Graph); + failures.extend(problems); + let _guard = Nodes::lock(); + for suite in &suites { + for nodes in Nodes::modes(suite) { + Nodes::set(nodes); + let Ok(run) = GraphRun::new(suite) else { + continue; + }; + let id = Nodes::id(suite, nodes); + let rows: Vec = suite.cases.iter().map(|c| c.input.to_value()).collect(); + let label = format!("{id} record"); + Guard::run(label, failures, || { + Guard::block(async { + for case in &suite.cases { + Graphs::record(golden, &id, &run.walker, &case.input, true).await; + } + for row in Rows::of(&Rows::spec_graph(&rows)) { + Graphs::record(golden, &id, &run.walker, &row, false).await; + } + }) + }); + } + } + Nodes::set(true); + } + + #[cfg(feature = "driver")] + fn spec_policy(golden: &mut Golden, failures: &mut Vec) { + let (suites, problems) = Spec::suites(Dialect::Policy); + failures.extend(problems); + for suite in &suites { + let Ok(run) = PolicyRun::new(suite) else { + continue; + }; + let id = suite.id(); + let label = format!("{id} record"); + Guard::run(label, failures, || { + golden.insert(Entry::new( + &format!("{id}#diagnostics"), + &[], + &Variable::Null, + Outcome::Ok(json!(run.blocking)), + )); + for case in &suite.cases { + Policies::record( + golden, + &run.workspace, + &id, + PolicyRun::MAIN, + &case.input, + &case.goals, + true, + None, + ); + } + if !run.blocking.is_empty() && run.gate { + return; + } + for (goals, rows) in Self::goal_rows(suite) { + for row in Rows::of(&Rows::spec_policy(&rows)) { + Policies::record( + golden, + &run.workspace, + &id, + PolicyRun::MAIN, + &row, + &goals, + false, + None, + ); + } + } + }); + } + } + + fn goal_rows(suite: &Suite) -> Vec<(Vec, Vec)> { + let mut goal_sets: Vec<&Vec> = suite.cases.iter().map(|c| &c.goals).collect(); + goal_sets.dedup(); + goal_sets + .into_iter() + .map(|goals| { + ( + goals.clone(), + suite + .cases + .iter() + .filter(|c| &c.goals == goals) + .map(|c| c.input.to_value()) + .collect(), + ) + }) + .collect() + } + + #[cfg(feature = "driver")] + fn computed(ws: &PolicyWorkspace, path: &str, inputs: &[Value]) -> Vec { + inputs + .iter() + .find_map(|input| { + Live::policy( + ws, + &Policies::request(path, &Variable::from(input.clone()), &[], false), + ) + .ok() + .map(|r| PolicyCase::computed(&r.output.to_value(), input)) + }) + .unwrap_or_default() + } + + fn goal_sets(computed: &[String], i: usize) -> Vec> { + let goals = PolicyCase::goals(computed, i); + match goals.is_empty() { + true => vec![goals], + false => vec![Vec::new(), goals], + } + } + + #[cfg(feature = "driver")] + fn generated(golden: &mut Golden) { + for seed in 0..Generated::seeds() { + let Some(ws) = Generated::workspace(seed) else { + continue; + }; + let (inputs, label, fingerprint) = ( + Generated::inputs(seed), + Generated::label(seed), + Generated::fingerprint(seed), + ); + let computed = Self::computed(&ws, Generated::PATH, &inputs); + for (i, input) in inputs.iter().enumerate() { + for goals in Self::goal_sets(&computed, i) { + Policies::record( + golden, + &ws, + &label, + Generated::PATH, + &Variable::from(input.clone()), + &goals, + i < 8, + Some(fingerprint.clone()), + ); + } + } + for row in Rows::of(&Rows::generated(&inputs)) { + Policies::record( + golden, + &ws, + &label, + Generated::PATH, + &row, + &[], + false, + Some(fingerprint.clone()), + ); + } + } + } + + #[cfg(feature = "driver")] + fn policy_fixtures(golden: &mut Golden) { + for case in PolicyCase::load_all() { + let computed = Self::computed(&case.workspace, &case.path, &case.inputs); + for (i, input) in case.inputs.iter().enumerate() { + for goals in Self::goal_sets(&computed, i) { + Policies::record( + golden, + &case.workspace, + &case.name, + &case.path, + &Variable::from(input.clone()), + &goals, + false, + None, + ); + } + } + } + } + + #[cfg(feature = "driver")] + fn anchor(golden: &mut Golden) { + for batch in Anchor::batches() { + let ws = batch.workspace(); + for row in batch.column_rows() { + Policies::record( + golden, + &ws, + batch.suite, + Anchor::PATH, + &row, + &[], + false, + None, + ); + } + } + let base = Anchor::base(); + let ws = base.workspace(); + for (at, value) in base.values.iter().enumerate() { + Policies::record( + golden, + &ws, + base.suite, + Anchor::PATH, + &Variable::from(value.clone()), + &[], + at < 32, + None, + ); + } + } + + fn fixtures() -> Vec { + Fixture::load_all() + .into_iter() + .filter(|f| !NETWORK_BOUND.contains(&f.name.as_str())) + .collect() + } + + fn slow(fixture: &Fixture) -> bool { + TIME_BOUND.contains(&fixture.name.as_str()) + } + + fn fixture_inputs(fixture: &Fixture) -> Vec { + fixture + .variants() + .into_iter() + .chain(fixture.typed_variants()) + .map(Variable::from) + .collect() + } + + fn compiled(fixture: &Fixture) -> Decision { + let mut compiled = Decision::from(Arc::new(fixture.content.clone())); + compiled.compile(); + compiled + } + + #[cfg(feature = "driver")] + async fn graph_fixtures(golden: &mut Golden) { + let _guard = Nodes::lock(); + for fixture in Self::fixtures() { + let walker = Decision::from(Arc::new(fixture.content.clone())).interpreted(); + for input in Self::fixture_inputs(&fixture) { + Graphs::record( + golden, + &fixture.name, + &walker, + &input, + !Self::slow(&fixture), + ) + .await; + } + if !Self::slow(&fixture) + && matches!(Self::compiled(&fixture).compiled_verdict(), Some(Ok(()))) + { + for row in Rows::of(&Rows::fixture(&fixture.variants())) { + Graphs::record(golden, &fixture.name, &walker, &row, false).await; + } + } + } + } + + #[cfg(feature = "driver")] + fn modes(&self, live: &Golden) { + let mut check = Check::default(); + match self { + Corpus::SpecGraph => Self::modes_spec_graph(live, &mut check), + Corpus::GraphFixtures => Guard::block(Self::modes_graph_fixtures(live, &mut check)), + _ => {} + } + check.finish(live, &format!("{} trace modes", self.name())); + } + + #[cfg(feature = "driver")] + fn modes_spec_graph(live: &Golden, check: &mut Check) { + let (suites, _) = Spec::suites(Dialect::Graph); + let _guard = Nodes::lock(); + for suite in &suites { + for nodes in Nodes::modes(suite) { + Nodes::set(nodes); + let Ok(run) = GraphRun::new(suite) else { + continue; + }; + let id = Nodes::id(suite, nodes); + check.diverges(suite, &id, suite.cases.iter().map(|c| c.input.clone())); + let mut failures = Vec::new(); + Guard::run(format!("{id} trace modes"), &mut failures, || { + Guard::block(async { + for case in &suite.cases { + Modes::compare( + check, + live, + &id, + &run.walker, + &run.compiled, + &case.input, + "compiled", + ) + .await; + Modes::compare( + check, + live, + &id, + &run.walker, + &run.uncompiled, + &case.input, + "uncompiled", + ) + .await; + } + }) + }); + check.failures.extend(failures); + } + } + Nodes::set(true); + } + + #[cfg(feature = "driver")] + async fn modes_graph_fixtures(live: &Golden, check: &mut Check) { + let _guard = Nodes::lock(); + for fixture in Self::fixtures().into_iter().filter(|f| !Self::slow(f)) { + let walker = Decision::from(Arc::new(fixture.content.clone())).interpreted(); + let compiled = Self::compiled(&fixture); + let uncompiled = Decision::from(Arc::new(fixture.content.clone())); + for input in Self::fixture_inputs(&fixture) { + Modes::compare( + check, + live, + &fixture.name, + &walker, + &compiled, + &input, + "compiled", + ) + .await; + Modes::compare( + check, + live, + &fixture.name, + &walker, + &uncompiled, + &input, + "uncompiled", + ) + .await; + } + } + } + + fn verify(&self) { + Golden::prepare(); + self.verify_against(&Golden::open(self.name())); + } + + fn verify_against(&self, golden: &Golden) { + let mut check = Check::default(); + match self { + Corpus::SpecGraph => Self::verify_spec_graph(golden, &mut check), + Corpus::SpecPolicy => Self::verify_spec_policy(golden, &mut check), + Corpus::Generated => Self::verify_generated(golden, &mut check), + Corpus::PolicyFixtures => Self::verify_policy_fixtures(golden, &mut check), + Corpus::Anchor => Self::verify_anchor(golden, &mut check), + Corpus::GraphFixtures => Guard::block(Self::verify_graph_fixtures(golden, &mut check)), + } + check.finish(golden, self.name()); + } + + fn verify_spec_graph(golden: &Golden, check: &mut Check) { + let (suites, _) = Spec::suites(Dialect::Graph); + let _guard = Nodes::lock(); + for suite in &suites { + for nodes in Nodes::modes(suite) { + Nodes::set(nodes); + let Ok(run) = GraphRun::new(suite) else { + continue; + }; + let id = Nodes::id(suite, nodes); + let rows: Vec = suite.cases.iter().map(|c| c.input.to_value()).collect(); + let builds = Rows::spec_graph(&rows); + check.diverges( + suite, + &id, + suite + .cases + .iter() + .map(|c| c.input.clone()) + .chain(Rows::of(&builds)), + ); + let mut failures = Vec::new(); + Guard::run(format!("{id} verify"), &mut failures, || { + Guard::block(async { + for case in &suite.cases { + Graphs::verify( + check, + golden, + &id, + &run.compiled, + &case.input, + "compiled", + ) + .await; + Graphs::verify( + check, + golden, + &id, + &run.uncompiled, + &case.input, + "uncompiled", + ) + .await; + let key = Canon::key(&id, &[], &case.input); + if let Some(entry) = case + .engines + .is_none() + .then(|| check.entry(golden, &key)) + .flatten() + { + let engine = Outcome::graph( + &run.engine + .evaluate(GraphRun::MAIN, case.input.depth_clone(64)) + .await, + ); + check.same(&key, "engine", &entry.plain, &engine); + if let Some(traced) = &entry.traced { + let got = Outcome::graph_traced( + &run.engine + .evaluate_with_opts( + GraphRun::MAIN, + case.input.depth_clone(64), + Graphs::traced(), + ) + .await, + EvaluationTraceKind::Default, + ); + check.same(&key, "engine traced", traced, &got); + } + } + } + let contexts: Vec = suite + .cases + .iter() + .cycle() + .take(suite.cases.len() * 3) + .map(|c| c.input.depth_clone(64)) + .collect(); + Graphs::batch(check, golden, &id, &run.compiled, &contexts, "batch").await; + Graphs::columns(check, golden, &id, &run.compiled, &builds).await; + }) + }); + check.failures.extend(failures); + } + } + Nodes::set(true); + } + + fn verify_spec_policy(golden: &Golden, check: &mut Check) { + let (suites, _) = Spec::suites(Dialect::Policy); + for suite in &suites { + let Ok(run) = PolicyRun::new(suite) else { + continue; + }; + let id = suite.id(); + let mut failures = Vec::new(); + Guard::run(format!("{id} verify"), &mut failures, || { + let key = Canon::key(&format!("{id}#diagnostics"), &[], &Variable::Null); + if let Some(entry) = check.entry(golden, &key) { + check.same( + &key, + "diagnostics", + &entry.plain, + &Outcome::Ok(json!(run.blocking)), + ); + } + for case in &suite.cases { + Policies::verify( + check, + golden, + &run.workspace, + &id, + PolicyRun::MAIN, + &case.input, + &case.goals, + None, + ); + let key = Canon::key(&id, &case.goals, &case.input); + if case.goals.is_empty() + && run.gate + && run.blocking.is_empty() + && case.engines.is_none() + { + if let Some(entry) = check.entry(golden, &key) { + let engine = match Guard::block( + run.engine + .evaluate(PolicyRun::MAIN, case.input.depth_clone(64)), + ) { + Ok(response) => Outcome::Ok(Canon::variable(&response.result)), + Err(error) => match *error { + EvaluationError::Policy(error) => Outcome::policy(Err(error)), + other => Outcome::Err { + debug: other.to_string(), + value: Value::Null, + }, + }, + }; + check.same(&key, "engine", &entry.plain, &engine); + } + } + } + let requests: Vec<(Variable, Vec)> = suite + .cases + .iter() + .cycle() + .take(suite.cases.len() * 3) + .map(|c| (c.input.clone(), c.goals.clone())) + .collect(); + Policies::batch( + check, + golden, + &run.workspace, + &id, + PolicyRun::MAIN, + &requests, + ); + if !run.blocking.is_empty() && run.gate { + return; + } + for (goals, rows) in Self::goal_rows(suite) { + Policies::columns( + check, + golden, + &run.workspace, + &id, + PolicyRun::MAIN, + &goals, + &Rows::spec_policy(&rows), + ); + } + }); + check.failures.extend(failures); + } + } + + fn goals_from(golden: &Golden, id: &str, inputs: &[Value]) -> Vec { + inputs + .iter() + .find_map(|input| { + match golden + .get(&Canon::key(id, &[], &Variable::from(input.clone()))) + .map(|e| &e.plain) + { + Some(Outcome::Ok(output)) => Some(PolicyCase::computed(output, input)), + _ => None, + } + }) + .unwrap_or_default() + } + + fn verify_generated(golden: &Golden, check: &mut Check) { + for seed in 0..Generated::seeds() { + let Some(ws) = Generated::workspace(seed) else { + continue; + }; + let (inputs, label, fingerprint) = ( + Generated::inputs(seed), + Generated::label(seed), + Generated::fingerprint(seed), + ); + let computed = Self::goals_from(golden, &label, &inputs); + let mut requests = Vec::new(); + for (i, input) in inputs.iter().enumerate() { + for goals in Self::goal_sets(&computed, i) { + let variable = Variable::from(input.clone()); + Policies::verify( + check, + golden, + &ws, + &label, + Generated::PATH, + &variable, + &goals, + Some(&fingerprint), + ); + requests.push((variable, goals)); + } + } + Policies::batch(check, golden, &ws, &label, Generated::PATH, &requests); + Policies::columns( + check, + golden, + &ws, + &label, + Generated::PATH, + &[], + &Rows::generated(&inputs), + ); + } + } + + fn verify_policy_fixtures(golden: &Golden, check: &mut Check) { + for case in PolicyCase::load_all() { + let computed = Self::goals_from(golden, &case.name, &case.inputs); + let mut requests = Vec::new(); + for (i, input) in case.inputs.iter().enumerate() { + for goals in Self::goal_sets(&computed, i) { + let variable = Variable::from(input.clone()); + Policies::verify( + check, + golden, + &case.workspace, + &case.name, + &case.path, + &variable, + &goals, + None, + ); + requests.push((variable, goals)); + } + } + Policies::batch( + check, + golden, + &case.workspace, + &case.name, + &case.path, + &requests, + ); + } + } + + fn verify_anchor(golden: &Golden, check: &mut Check) { + for batch in Anchor::batches() { + let ws = batch.workspace(); + let rows = batch.column_rows(); + let builds: Vec<(Built, bool)> = Built::new(&batch.values) + .map(|b| (b, false)) + .into_iter() + .chain(Built::nested(&batch.values).map(|b| (b, true))) + .collect(); + Policies::columns(check, golden, &ws, batch.suite, Anchor::PATH, &[], &builds); + for row in &rows { + Policies::verify( + check, + golden, + &ws, + batch.suite, + Anchor::PATH, + row, + &[], + None, + ); + } + let requests: Vec<(Variable, Vec)> = + rows.into_iter().map(|r| (r, Vec::new())).collect(); + Policies::batch(check, golden, &ws, batch.suite, Anchor::PATH, &requests); + } + let base = Anchor::base(); + let ws = base.workspace(); + for value in &base.values { + Policies::verify( + check, + golden, + &ws, + base.suite, + Anchor::PATH, + &Variable::from(value.clone()), + &[], + None, + ); + } + } + + async fn verify_graph_fixtures(golden: &Golden, check: &mut Check) { + let _guard = Nodes::lock(); + for fixture in Self::fixtures() { + let compiled = Self::compiled(&fixture); + let uncompiled = Decision::from(Arc::new(fixture.content.clone())); + let inputs = Self::fixture_inputs(&fixture); + for input in &inputs { + Graphs::verify(check, golden, &fixture.name, &compiled, input, "compiled").await; + if !Self::slow(&fixture) { + Graphs::verify( + check, + golden, + &fixture.name, + &uncompiled, + input, + "uncompiled", + ) + .await; + } + } + if Self::slow(&fixture) { + continue; + } + Graphs::batch(check, golden, &fixture.name, &compiled, &inputs, "batch").await; + if matches!(compiled.compiled_verdict(), Some(Ok(()))) { + Graphs::columns( + check, + golden, + &fixture.name, + &compiled, + &Rows::fixture(&fixture.variants()), + ) + .await; + } + } + } +} + +#[cfg(feature = "driver")] +#[test] +#[ignore] +fn capture() { + assert!( + std::env::var("GOLDEN_WRITE").is_ok_and(|v| v == "1"), + "set GOLDEN_WRITE=1 to rewrite the goldens" + ); + for corpus in Corpus::selected() { + let started = std::time::Instant::now(); + let golden = corpus.record(); + let written = golden.write(|entry| corpus.shard(entry)); + let (raw, stored) = written + .iter() + .fold((0u64, 0u64), |(r, s), w| (r + w.raw, s + w.stored)); + let traced = golden.entries().filter(|e| e.traced.is_some()).count(); + let ordered: Vec<&str> = golden + .entries() + .filter(|e| e.ordered) + .map(|e| e.suite.as_str()) + .collect(); + if !ordered.is_empty() { + eprintln!( + "{}: {} entries depend on input key order: {:?}", + corpus.name(), + ordered.len(), + ordered + ); + } + let enhanced = golden.entries().filter(|e| e.enhanced.is_some()).count(); + eprintln!( + "{:18} {:>7} entries ({traced} traced, {enhanced} enhanced) {:>3} files raw {:>11} stored {:>11} in {:.1}s", + corpus.name(), + golden.len(), + written.len(), + raw, + stored, + started.elapsed().as_secs_f64() + ); + } +} + +#[cfg(feature = "driver")] +#[test] +fn goldens_are_current() { + let mut failures = Vec::new(); + for corpus in Corpus::selected() { + let live = corpus.record(); + let recorded = Golden::open(corpus.name()); + failures.extend(live.compare(&recorded)); + } + let limit = std::env::var("SPEC_SHOW") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(20); + assert!( + failures.is_empty(), + "{} stale golden entries:\n{}", + failures.len(), + failures + .iter() + .take(limit) + .cloned() + .collect::>() + .join("\n") + ); +} + +#[cfg(feature = "driver")] +#[test] +fn hosts_match_the_live_driver() { + for corpus in Corpus::selected() + .into_iter() + .filter(|c| !matches!(c, Corpus::SpecGraph | Corpus::GraphFixtures)) + { + let live = corpus.record(); + corpus.verify_against(&live); + } +} + +#[cfg(feature = "driver")] +#[test] +fn traced_graphs_match_the_live_walker() { + for corpus in Corpus::selected() + .into_iter() + .filter(|c| matches!(c, Corpus::SpecGraph | Corpus::GraphFixtures)) + { + let live = corpus.record(); + corpus.verify_against(&live); + corpus.modes(&live); + } +} + +#[test] +fn goldens_spec_graph() { + Corpus::SpecGraph.verify(); +} + +#[test] +fn goldens_spec_policy() { + Corpus::SpecPolicy.verify(); +} + +#[test] +fn goldens_generated_policy() { + Corpus::Generated.verify(); +} + +#[test] +fn goldens_policy_fixtures() { + Corpus::PolicyFixtures.verify(); +} + +#[test] +fn goldens_anchor() { + Corpus::Anchor.verify(); +} + +#[test] +fn goldens_graph_fixtures() { + Corpus::GraphFixtures.verify(); +} diff --git a/core/engine/tests/golden/anchor.jsonl.gz b/core/engine/tests/golden/anchor.jsonl.gz new file mode 100644 index 00000000..bcb68f12 Binary files /dev/null and b/core/engine/tests/golden/anchor.jsonl.gz differ diff --git a/core/engine/tests/golden/generated/policy.jsonl.gz b/core/engine/tests/golden/generated/policy.jsonl.gz new file mode 100644 index 00000000..36964ecf Binary files /dev/null and b/core/engine/tests/golden/generated/policy.jsonl.gz differ diff --git a/core/engine/tests/golden/graph-fixtures.jsonl.gz b/core/engine/tests/golden/graph-fixtures.jsonl.gz new file mode 100644 index 00000000..21711875 Binary files /dev/null and b/core/engine/tests/golden/graph-fixtures.jsonl.gz differ diff --git a/core/engine/tests/golden/policy-fixtures.jsonl.gz b/core/engine/tests/golden/policy-fixtures.jsonl.gz new file mode 100644 index 00000000..662c694a Binary files /dev/null and b/core/engine/tests/golden/policy-fixtures.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/00-harness.jsonl.gz b/core/engine/tests/golden/spec-graph/00-harness.jsonl.gz new file mode 100644 index 00000000..bd5b6d5c Binary files /dev/null and b/core/engine/tests/golden/spec-graph/00-harness.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/01-input-output.jsonl.gz b/core/engine/tests/golden/spec-graph/01-input-output.jsonl.gz new file mode 100644 index 00000000..ca9bbb55 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/01-input-output.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/02-expression-node.jsonl.gz b/core/engine/tests/golden/spec-graph/02-expression-node.jsonl.gz new file mode 100644 index 00000000..d9367ec1 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/02-expression-node.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/03-expression-paths.jsonl.gz b/core/engine/tests/golden/spec-graph/03-expression-paths.jsonl.gz new file mode 100644 index 00000000..37af8b18 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/03-expression-paths.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/04-table-first-hit.jsonl.gz b/core/engine/tests/golden/spec-graph/04-table-first-hit.jsonl.gz new file mode 100644 index 00000000..a799a857 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/04-table-first-hit.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/05-table-collect.jsonl.gz b/core/engine/tests/golden/spec-graph/05-table-collect.jsonl.gz new file mode 100644 index 00000000..7e0af753 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/05-table-collect.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/06-table-cells.jsonl.gz b/core/engine/tests/golden/spec-graph/06-table-cells.jsonl.gz new file mode 100644 index 00000000..6a6f7ae9 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/06-table-cells.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/07-table-outputs.jsonl.gz b/core/engine/tests/golden/spec-graph/07-table-outputs.jsonl.gz new file mode 100644 index 00000000..7d88fc63 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/07-table-outputs.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/08-switch-first.jsonl.gz b/core/engine/tests/golden/spec-graph/08-switch-first.jsonl.gz new file mode 100644 index 00000000..2f869b71 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/08-switch-first.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/09-switch-collect.jsonl.gz b/core/engine/tests/golden/spec-graph/09-switch-collect.jsonl.gz new file mode 100644 index 00000000..173ec867 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/09-switch-collect.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/10-merges-and-joins.jsonl.gz b/core/engine/tests/golden/spec-graph/10-merges-and-joins.jsonl.gz new file mode 100644 index 00000000..44bb2ff7 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/10-merges-and-joins.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/11-pass-through.jsonl.gz b/core/engine/tests/golden/spec-graph/11-pass-through.jsonl.gz new file mode 100644 index 00000000..766941cc Binary files /dev/null and b/core/engine/tests/golden/spec-graph/11-pass-through.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/12-input-field-output-path.jsonl.gz b/core/engine/tests/golden/spec-graph/12-input-field-output-path.jsonl.gz new file mode 100644 index 00000000..5feebbb5 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/12-input-field-output-path.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/13-loops.jsonl.gz b/core/engine/tests/golden/spec-graph/13-loops.jsonl.gz new file mode 100644 index 00000000..9359dcc1 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/13-loops.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/14-sub-decisions.jsonl.gz b/core/engine/tests/golden/spec-graph/14-sub-decisions.jsonl.gz new file mode 100644 index 00000000..644d580d Binary files /dev/null and b/core/engine/tests/golden/spec-graph/14-sub-decisions.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/15-nodes-references.jsonl.gz b/core/engine/tests/golden/spec-graph/15-nodes-references.jsonl.gz new file mode 100644 index 00000000..3314b2c4 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/15-nodes-references.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/16-functions-v2.jsonl.gz b/core/engine/tests/golden/spec-graph/16-functions-v2.jsonl.gz new file mode 100644 index 00000000..c1f703b9 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/16-functions-v2.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/17-functions-v1.jsonl.gz b/core/engine/tests/golden/spec-graph/17-functions-v1.jsonl.gz new file mode 100644 index 00000000..40c12244 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/17-functions-v1.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/18-custom-nodes.jsonl.gz b/core/engine/tests/golden/spec-graph/18-custom-nodes.jsonl.gz new file mode 100644 index 00000000..867bdbd7 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/18-custom-nodes.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/19-schemas.jsonl.gz b/core/engine/tests/golden/spec-graph/19-schemas.jsonl.gz new file mode 100644 index 00000000..963a198c Binary files /dev/null and b/core/engine/tests/golden/spec-graph/19-schemas.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/20-graph-errors.jsonl.gz b/core/engine/tests/golden/spec-graph/20-graph-errors.jsonl.gz new file mode 100644 index 00000000..17d0e54c Binary files /dev/null and b/core/engine/tests/golden/spec-graph/20-graph-errors.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/21-values.jsonl.gz b/core/engine/tests/golden/spec-graph/21-values.jsonl.gz new file mode 100644 index 00000000..8e0a6bc2 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/21-values.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/22-composite.jsonl.gz b/core/engine/tests/golden/spec-graph/22-composite.jsonl.gz new file mode 100644 index 00000000..744003f5 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/22-composite.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/23-switch-nesting.jsonl.gz b/core/engine/tests/golden/spec-graph/23-switch-nesting.jsonl.gz new file mode 100644 index 00000000..9e5c2d65 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/23-switch-nesting.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/24-switch-and-transforms.jsonl.gz b/core/engine/tests/golden/spec-graph/24-switch-and-transforms.jsonl.gz new file mode 100644 index 00000000..e3c2b602 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/24-switch-and-transforms.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/25-graph-topologies.jsonl.gz b/core/engine/tests/golden/spec-graph/25-graph-topologies.jsonl.gz new file mode 100644 index 00000000..6308e433 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/25-graph-topologies.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/26-table-numeric-ranges.jsonl.gz b/core/engine/tests/golden/spec-graph/26-table-numeric-ranges.jsonl.gz new file mode 100644 index 00000000..7344e54f Binary files /dev/null and b/core/engine/tests/golden/spec-graph/26-table-numeric-ranges.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/27-table-strings-and-lists.jsonl.gz b/core/engine/tests/golden/spec-graph/27-table-strings-and-lists.jsonl.gz new file mode 100644 index 00000000..ebeda396 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/27-table-strings-and-lists.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/28-table-dates-and-bools.jsonl.gz b/core/engine/tests/golden/spec-graph/28-table-dates-and-bools.jsonl.gz new file mode 100644 index 00000000..1eae3a4e Binary files /dev/null and b/core/engine/tests/golden/spec-graph/28-table-dates-and-bools.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/29-table-large.jsonl.gz b/core/engine/tests/golden/spec-graph/29-table-large.jsonl.gz new file mode 100644 index 00000000..45ccb653 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/29-table-large.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/30-table-combinatorics.jsonl.gz b/core/engine/tests/golden/spec-graph/30-table-combinatorics.jsonl.gz new file mode 100644 index 00000000..e9f3cd16 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/30-table-combinatorics.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/31-table-null-and-missing.jsonl.gz b/core/engine/tests/golden/spec-graph/31-table-null-and-missing.jsonl.gz new file mode 100644 index 00000000..5e163d2c Binary files /dev/null and b/core/engine/tests/golden/spec-graph/31-table-null-and-missing.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/32-expression-closures.jsonl.gz b/core/engine/tests/golden/spec-graph/32-expression-closures.jsonl.gz new file mode 100644 index 00000000..98fa7b24 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/32-expression-closures.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/33-expression-objects.jsonl.gz b/core/engine/tests/golden/spec-graph/33-expression-objects.jsonl.gz new file mode 100644 index 00000000..68acbaac Binary files /dev/null and b/core/engine/tests/golden/spec-graph/33-expression-objects.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/34-expression-templates-and-strings.jsonl.gz b/core/engine/tests/golden/spec-graph/34-expression-templates-and-strings.jsonl.gz new file mode 100644 index 00000000..5ac21c4f Binary files /dev/null and b/core/engine/tests/golden/spec-graph/34-expression-templates-and-strings.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/35-loops-nested.jsonl.gz b/core/engine/tests/golden/spec-graph/35-loops-nested.jsonl.gz new file mode 100644 index 00000000..fc65fb78 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/35-loops-nested.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/36-loops-tables.jsonl.gz b/core/engine/tests/golden/spec-graph/36-loops-tables.jsonl.gz new file mode 100644 index 00000000..dde950db Binary files /dev/null and b/core/engine/tests/golden/spec-graph/36-loops-tables.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/37-loops-merging.jsonl.gz b/core/engine/tests/golden/spec-graph/37-loops-merging.jsonl.gz new file mode 100644 index 00000000..46e4fb55 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/37-loops-merging.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/38-subdecision-transforms.jsonl.gz b/core/engine/tests/golden/spec-graph/38-subdecision-transforms.jsonl.gz new file mode 100644 index 00000000..cbf4ca03 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/38-subdecision-transforms.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/39-subdecision-chains.jsonl.gz b/core/engine/tests/golden/spec-graph/39-subdecision-chains.jsonl.gz new file mode 100644 index 00000000..d9a2a7dd Binary files /dev/null and b/core/engine/tests/golden/spec-graph/39-subdecision-chains.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/40-subdecision-data-flow.jsonl.gz b/core/engine/tests/golden/spec-graph/40-subdecision-data-flow.jsonl.gz new file mode 100644 index 00000000..1fa9668c Binary files /dev/null and b/core/engine/tests/golden/spec-graph/40-subdecision-data-flow.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/41-functions-isolation.jsonl.gz b/core/engine/tests/golden/spec-graph/41-functions-isolation.jsonl.gz new file mode 100644 index 00000000..3c1a7753 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/41-functions-isolation.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/42-functions-data.jsonl.gz b/core/engine/tests/golden/spec-graph/42-functions-data.jsonl.gz new file mode 100644 index 00000000..5c0836bc Binary files /dev/null and b/core/engine/tests/golden/spec-graph/42-functions-data.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/43-functions-in-graphs.jsonl.gz b/core/engine/tests/golden/spec-graph/43-functions-in-graphs.jsonl.gz new file mode 100644 index 00000000..ba7eec18 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/43-functions-in-graphs.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/44-realistic-insurance.jsonl.gz b/core/engine/tests/golden/spec-graph/44-realistic-insurance.jsonl.gz new file mode 100644 index 00000000..7042dd7a Binary files /dev/null and b/core/engine/tests/golden/spec-graph/44-realistic-insurance.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/45-realistic-lending.jsonl.gz b/core/engine/tests/golden/spec-graph/45-realistic-lending.jsonl.gz new file mode 100644 index 00000000..38139d17 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/45-realistic-lending.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/46-realistic-commerce.jsonl.gz b/core/engine/tests/golden/spec-graph/46-realistic-commerce.jsonl.gz new file mode 100644 index 00000000..a26e48c0 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/46-realistic-commerce.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/47-realistic-operations.jsonl.gz b/core/engine/tests/golden/spec-graph/47-realistic-operations.jsonl.gz new file mode 100644 index 00000000..67f3a478 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/47-realistic-operations.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/48-rows-heterogeneous-types.jsonl.gz b/core/engine/tests/golden/spec-graph/48-rows-heterogeneous-types.jsonl.gz new file mode 100644 index 00000000..1abae5e1 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/48-rows-heterogeneous-types.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/49-rows-nested-shapes.jsonl.gz b/core/engine/tests/golden/spec-graph/49-rows-nested-shapes.jsonl.gz new file mode 100644 index 00000000..f85ade0d Binary files /dev/null and b/core/engine/tests/golden/spec-graph/49-rows-nested-shapes.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/50-rows-errors-and-branches.jsonl.gz b/core/engine/tests/golden/spec-graph/50-rows-errors-and-branches.jsonl.gz new file mode 100644 index 00000000..2def95ac Binary files /dev/null and b/core/engine/tests/golden/spec-graph/50-rows-errors-and-branches.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/51-input-schema-types.jsonl.gz b/core/engine/tests/golden/spec-graph/51-input-schema-types.jsonl.gz new file mode 100644 index 00000000..886e0ba6 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/51-input-schema-types.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/52-input-schema-dates.jsonl.gz b/core/engine/tests/golden/spec-graph/52-input-schema-dates.jsonl.gz new file mode 100644 index 00000000..02a774d3 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/52-input-schema-dates.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/53-output-schemas.jsonl.gz b/core/engine/tests/golden/spec-graph/53-output-schemas.jsonl.gz new file mode 100644 index 00000000..a68e389b Binary files /dev/null and b/core/engine/tests/golden/spec-graph/53-output-schemas.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/54-null-semantics.jsonl.gz b/core/engine/tests/golden/spec-graph/54-null-semantics.jsonl.gz new file mode 100644 index 00000000..0efb4b29 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/54-null-semantics.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/55-merge-matrix.jsonl.gz b/core/engine/tests/golden/spec-graph/55-merge-matrix.jsonl.gz new file mode 100644 index 00000000..b3d0b9eb Binary files /dev/null and b/core/engine/tests/golden/spec-graph/55-merge-matrix.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/56-output-assembly.jsonl.gz b/core/engine/tests/golden/spec-graph/56-output-assembly.jsonl.gz new file mode 100644 index 00000000..f769ceba Binary files /dev/null and b/core/engine/tests/golden/spec-graph/56-output-assembly.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/57-table-output-shapes.jsonl.gz b/core/engine/tests/golden/spec-graph/57-table-output-shapes.jsonl.gz new file mode 100644 index 00000000..eecff73d Binary files /dev/null and b/core/engine/tests/golden/spec-graph/57-table-output-shapes.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/58-table-hit-policies.jsonl.gz b/core/engine/tests/golden/spec-graph/58-table-hit-policies.jsonl.gz new file mode 100644 index 00000000..5bed47d0 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/58-table-hit-policies.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/59-table-cell-expressions.jsonl.gz b/core/engine/tests/golden/spec-graph/59-table-cell-expressions.jsonl.gz new file mode 100644 index 00000000..d758e149 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/59-table-cell-expressions.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/60-realistic-healthcare.jsonl.gz b/core/engine/tests/golden/spec-graph/60-realistic-healthcare.jsonl.gz new file mode 100644 index 00000000..4cec4dc0 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/60-realistic-healthcare.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/61-realistic-telco-energy.jsonl.gz b/core/engine/tests/golden/spec-graph/61-realistic-telco-energy.jsonl.gz new file mode 100644 index 00000000..221b6bf2 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/61-realistic-telco-energy.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/62-realistic-hr-public.jsonl.gz b/core/engine/tests/golden/spec-graph/62-realistic-hr-public.jsonl.gz new file mode 100644 index 00000000..2c9e7844 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/62-realistic-hr-public.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/63-realistic-large-graphs.jsonl.gz b/core/engine/tests/golden/spec-graph/63-realistic-large-graphs.jsonl.gz new file mode 100644 index 00000000..848d81f1 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/63-realistic-large-graphs.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/64-expression-optimizations.jsonl.gz b/core/engine/tests/golden/spec-graph/64-expression-optimizations.jsonl.gz new file mode 100644 index 00000000..b92e833f Binary files /dev/null and b/core/engine/tests/golden/spec-graph/64-expression-optimizations.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/65-numbers-in-graphs.jsonl.gz b/core/engine/tests/golden/spec-graph/65-numbers-in-graphs.jsonl.gz new file mode 100644 index 00000000..e27c3d7a Binary files /dev/null and b/core/engine/tests/golden/spec-graph/65-numbers-in-graphs.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/66-dates-in-graphs.jsonl.gz b/core/engine/tests/golden/spec-graph/66-dates-in-graphs.jsonl.gz new file mode 100644 index 00000000..f21a99a6 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/66-dates-in-graphs.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/67-switch-row-splits.jsonl.gz b/core/engine/tests/golden/spec-graph/67-switch-row-splits.jsonl.gz new file mode 100644 index 00000000..4631eaa5 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/67-switch-row-splits.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/68-nodes-across-branches.jsonl.gz b/core/engine/tests/golden/spec-graph/68-nodes-across-branches.jsonl.gz new file mode 100644 index 00000000..69c8397f Binary files /dev/null and b/core/engine/tests/golden/spec-graph/68-nodes-across-branches.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/69-loops-advanced.jsonl.gz b/core/engine/tests/golden/spec-graph/69-loops-advanced.jsonl.gz new file mode 100644 index 00000000..17d23011 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/69-loops-advanced.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/70-generated-a.jsonl.gz b/core/engine/tests/golden/spec-graph/70-generated-a.jsonl.gz new file mode 100644 index 00000000..0b9ef8a3 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/70-generated-a.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/71-generated-b.jsonl.gz b/core/engine/tests/golden/spec-graph/71-generated-b.jsonl.gz new file mode 100644 index 00000000..2b83a592 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/71-generated-b.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-graph/72-generated-minimal.jsonl.gz b/core/engine/tests/golden/spec-graph/72-generated-minimal.jsonl.gz new file mode 100644 index 00000000..cfc88f19 Binary files /dev/null and b/core/engine/tests/golden/spec-graph/72-generated-minimal.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/00-harness.jsonl.gz b/core/engine/tests/golden/spec-policy/00-harness.jsonl.gz new file mode 100644 index 00000000..f06db43b Binary files /dev/null and b/core/engine/tests/golden/spec-policy/00-harness.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/01-models-and-input.jsonl.gz b/core/engine/tests/golden/spec-policy/01-models-and-input.jsonl.gz new file mode 100644 index 00000000..a4a282a9 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/01-models-and-input.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/02-expression-blocks.jsonl.gz b/core/engine/tests/golden/spec-policy/02-expression-blocks.jsonl.gz new file mode 100644 index 00000000..2400f07b Binary files /dev/null and b/core/engine/tests/golden/spec-policy/02-expression-blocks.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/03-dependencies.jsonl.gz b/core/engine/tests/golden/spec-policy/03-dependencies.jsonl.gz new file mode 100644 index 00000000..3bc0d969 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/03-dependencies.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/04-nested-paths.jsonl.gz b/core/engine/tests/golden/spec-policy/04-nested-paths.jsonl.gz new file mode 100644 index 00000000..db957bf2 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/04-nested-paths.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/05-match-blocks.jsonl.gz b/core/engine/tests/golden/spec-policy/05-match-blocks.jsonl.gz new file mode 100644 index 00000000..57456d66 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/05-match-blocks.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/06-assertion-blocks.jsonl.gz b/core/engine/tests/golden/spec-policy/06-assertion-blocks.jsonl.gz new file mode 100644 index 00000000..7e36b9d6 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/06-assertion-blocks.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/07-tables-first.jsonl.gz b/core/engine/tests/golden/spec-policy/07-tables-first.jsonl.gz new file mode 100644 index 00000000..6cd478e1 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/07-tables-first.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/08-tables-collect.jsonl.gz b/core/engine/tests/golden/spec-policy/08-tables-collect.jsonl.gz new file mode 100644 index 00000000..22d332a2 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/08-tables-collect.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/09-relationships.jsonl.gz b/core/engine/tests/golden/spec-policy/09-relationships.jsonl.gz new file mode 100644 index 00000000..ba4bb6b9 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/09-relationships.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/10-references.jsonl.gz b/core/engine/tests/golden/spec-policy/10-references.jsonl.gz new file mode 100644 index 00000000..00473b04 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/10-references.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/11-globals.jsonl.gz b/core/engine/tests/golden/spec-policy/11-globals.jsonl.gz new file mode 100644 index 00000000..d914c309 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/11-globals.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/12-dictionaries.jsonl.gz b/core/engine/tests/golden/spec-policy/12-dictionaries.jsonl.gz new file mode 100644 index 00000000..82d143de Binary files /dev/null and b/core/engine/tests/golden/spec-policy/12-dictionaries.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/13-imports.jsonl.gz b/core/engine/tests/golden/spec-policy/13-imports.jsonl.gz new file mode 100644 index 00000000..6532cdd5 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/13-imports.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/14-goals.jsonl.gz b/core/engine/tests/golden/spec-policy/14-goals.jsonl.gz new file mode 100644 index 00000000..c9e3b413 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/14-goals.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/15-nullability.jsonl.gz b/core/engine/tests/golden/spec-policy/15-nullability.jsonl.gz new file mode 100644 index 00000000..dcd43462 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/15-nullability.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/16-policy-errors.jsonl.gz b/core/engine/tests/golden/spec-policy/16-policy-errors.jsonl.gz new file mode 100644 index 00000000..2bd87330 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/16-policy-errors.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/17-policy-values.jsonl.gz b/core/engine/tests/golden/spec-policy/17-policy-values.jsonl.gz new file mode 100644 index 00000000..8a671c16 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/17-policy-values.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/18-match-advanced.jsonl.gz b/core/engine/tests/golden/spec-policy/18-match-advanced.jsonl.gz new file mode 100644 index 00000000..f9a4261e Binary files /dev/null and b/core/engine/tests/golden/spec-policy/18-match-advanced.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/19-assertions-advanced.jsonl.gz b/core/engine/tests/golden/spec-policy/19-assertions-advanced.jsonl.gz new file mode 100644 index 00000000..d0d07a90 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/19-assertions-advanced.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/20-tables-advanced.jsonl.gz b/core/engine/tests/golden/spec-policy/20-tables-advanced.jsonl.gz new file mode 100644 index 00000000..739f3b27 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/20-tables-advanced.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/21-relationships-deep.jsonl.gz b/core/engine/tests/golden/spec-policy/21-relationships-deep.jsonl.gz new file mode 100644 index 00000000..e6389440 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/21-relationships-deep.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/22-aggregates.jsonl.gz b/core/engine/tests/golden/spec-policy/22-aggregates.jsonl.gz new file mode 100644 index 00000000..d3b9d933 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/22-aggregates.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/23-member-blocks.jsonl.gz b/core/engine/tests/golden/spec-policy/23-member-blocks.jsonl.gz new file mode 100644 index 00000000..bb4ab4d7 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/23-member-blocks.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/24-realistic-kyc.jsonl.gz b/core/engine/tests/golden/spec-policy/24-realistic-kyc.jsonl.gz new file mode 100644 index 00000000..960536c5 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/24-realistic-kyc.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/25-realistic-underwriting.jsonl.gz b/core/engine/tests/golden/spec-policy/25-realistic-underwriting.jsonl.gz new file mode 100644 index 00000000..599c2203 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/25-realistic-underwriting.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/26-realistic-billing.jsonl.gz b/core/engine/tests/golden/spec-policy/26-realistic-billing.jsonl.gz new file mode 100644 index 00000000..eb3592a3 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/26-realistic-billing.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/27-policy-dates.jsonl.gz b/core/engine/tests/golden/spec-policy/27-policy-dates.jsonl.gz new file mode 100644 index 00000000..2cc9ddf0 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/27-policy-dates.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/28-policy-strings-enums.jsonl.gz b/core/engine/tests/golden/spec-policy/28-policy-strings-enums.jsonl.gz new file mode 100644 index 00000000..5b77e997 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/28-policy-strings-enums.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/29-policy-optionals.jsonl.gz b/core/engine/tests/golden/spec-policy/29-policy-optionals.jsonl.gz new file mode 100644 index 00000000..d6268437 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/29-policy-optionals.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/30-imports-composition.jsonl.gz b/core/engine/tests/golden/spec-policy/30-imports-composition.jsonl.gz new file mode 100644 index 00000000..9f35550a Binary files /dev/null and b/core/engine/tests/golden/spec-policy/30-imports-composition.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/31-goals-advanced.jsonl.gz b/core/engine/tests/golden/spec-policy/31-goals-advanced.jsonl.gz new file mode 100644 index 00000000..d251c1f5 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/31-goals-advanced.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/32-policy-diagnostics.jsonl.gz b/core/engine/tests/golden/spec-policy/32-policy-diagnostics.jsonl.gz new file mode 100644 index 00000000..09c06181 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/32-policy-diagnostics.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/33-generated-a.jsonl.gz b/core/engine/tests/golden/spec-policy/33-generated-a.jsonl.gz new file mode 100644 index 00000000..89793899 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/33-generated-a.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/34-generated-b.jsonl.gz b/core/engine/tests/golden/spec-policy/34-generated-b.jsonl.gz new file mode 100644 index 00000000..3323165e Binary files /dev/null and b/core/engine/tests/golden/spec-policy/34-generated-b.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/35-generated-goals.jsonl.gz b/core/engine/tests/golden/spec-policy/35-generated-goals.jsonl.gz new file mode 100644 index 00000000..7230c9b8 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/35-generated-goals.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/36-generated-minimal.jsonl.gz b/core/engine/tests/golden/spec-policy/36-generated-minimal.jsonl.gz new file mode 100644 index 00000000..e2ca4b3c Binary files /dev/null and b/core/engine/tests/golden/spec-policy/36-generated-minimal.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/37-input-validation.jsonl.gz b/core/engine/tests/golden/spec-policy/37-input-validation.jsonl.gz new file mode 100644 index 00000000..a8535030 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/37-input-validation.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/38-laziness-and-terminals.jsonl.gz b/core/engine/tests/golden/spec-policy/38-laziness-and-terminals.jsonl.gz new file mode 100644 index 00000000..41123969 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/38-laziness-and-terminals.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/39-numbers-in-policies.jsonl.gz b/core/engine/tests/golden/spec-policy/39-numbers-in-policies.jsonl.gz new file mode 100644 index 00000000..adeff9d5 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/39-numbers-in-policies.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/40-references-and-globals-advanced.jsonl.gz b/core/engine/tests/golden/spec-policy/40-references-and-globals-advanced.jsonl.gz new file mode 100644 index 00000000..a33d05df Binary files /dev/null and b/core/engine/tests/golden/spec-policy/40-references-and-globals-advanced.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/41-realistic-insurance.jsonl.gz b/core/engine/tests/golden/spec-policy/41-realistic-insurance.jsonl.gz new file mode 100644 index 00000000..cb966698 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/41-realistic-insurance.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/42-realistic-payroll-hr.jsonl.gz b/core/engine/tests/golden/spec-policy/42-realistic-payroll-hr.jsonl.gz new file mode 100644 index 00000000..781d8a49 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/42-realistic-payroll-hr.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/43-realistic-eligibility.jsonl.gz b/core/engine/tests/golden/spec-policy/43-realistic-eligibility.jsonl.gz new file mode 100644 index 00000000..89ef5c9d Binary files /dev/null and b/core/engine/tests/golden/spec-policy/43-realistic-eligibility.jsonl.gz differ diff --git a/core/engine/tests/golden/spec-policy/44-realistic-commerce.jsonl.gz b/core/engine/tests/golden/spec-policy/44-realistic-commerce.jsonl.gz new file mode 100644 index 00000000..68c7d738 Binary files /dev/null and b/core/engine/tests/golden/spec-policy/44-realistic-commerce.jsonl.gz differ diff --git a/core/engine/tests/lane_census.rs b/core/engine/tests/lane_census.rs new file mode 100644 index 00000000..fb36a45d --- /dev/null +++ b/core/engine/tests/lane_census.rs @@ -0,0 +1,481 @@ +mod conformance; +#[allow(dead_code)] +#[path = "support/fixture.rs"] +mod fixture; +#[allow(dead_code)] +#[path = "support/policies.rs"] +mod policies; +#[path = "support/policy_gen.rs"] +mod policy_gen; +mod support; + +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(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/engine/tests/policy_cache.rs b/core/engine/tests/policy_cache.rs index 9cf289d6..274339bd 100644 --- a/core/engine/tests/policy_cache.rs +++ b/core/engine/tests/policy_cache.rs @@ -295,3 +295,76 @@ async fn reload_recompiles_from_loader() { let allowed = engine.evaluate("policy", input(150)).await.unwrap(); assert_eq!(approved(&allowed.result), json!(true)); } + +#[tokio::test] +async fn lazy_policies_follow_changed_content() { + let loader = Arc::new(MemoryLoader::default()); + loader.add("policy", policy_content_with_threshold(100)); + let engine = DecisionEngine::default().with_loader(loader.clone()); + + for _ in 0..3 { + let result = engine.evaluate("policy", input(150)).await.unwrap(); + assert_eq!(approved(&result.result), json!(true)); + } + + loader.add("policy", policy_content_with_threshold(200)); + for _ in 0..3 { + let result = engine.evaluate("policy", input(150)).await.unwrap(); + assert_eq!(approved(&result.result), json!(false)); + } + + loader.add("policy", parse_error_policy()); + assert!(engine.evaluate("policy", input(150)).await.is_err()); + + loader.add("policy", policy_content_with_threshold(100)); + let result = engine.evaluate("policy", input(150)).await.unwrap(); + assert_eq!(approved(&result.result), json!(true)); +} + +#[tokio::test] +async fn lazy_policies_follow_changed_imports() { + let base = |threshold: i64| -> DecisionContent { + serde_json::from_value(json!({ + "imports": [], + "blocks": [ + { "id": "dm", "type": "dataModel", "props": { "data": { + "name": "platform", "scope": "global", + "properties": [ + { "id": "g1", "name": "amount", "type": "number", "array": false, "optional": false } + ] + }}}, + { "id": "qual", "type": "assertion", "props": { "data": { + "output": "qualified", + "conditions": [ + { "id": "c1", "expression": format!("amount >= {threshold}"), "operator": "and", "depth": 0 } + ] + }}} + ] + })) + .unwrap() + }; + let loader = Arc::new(MemoryLoader::default()); + loader.add("base.json", base(100)); + loader.add( + "main.json", + serde_json::from_value::(json!({ + "imports": ["base.json"], + "blocks": [ + { "id": "appr", "type": "assertion", "props": { "data": { + "output": "approved", + "conditions": [ + { "id": "c1", "expression": "qualified", "operator": "and", "depth": 0 } + ] + }}} + ] + })) + .unwrap(), + ); + let engine = DecisionEngine::default().with_loader(loader.clone()); + let result = engine.evaluate("main.json", input(150)).await.unwrap(); + assert_eq!(approved(&result.result), json!(true)); + + loader.add("base.json", base(200)); + let result = engine.evaluate("main.json", input(150)).await.unwrap(); + assert_eq!(approved(&result.result), json!(false)); +} diff --git a/core/engine/tests/prepared_reuse.rs b/core/engine/tests/prepared_reuse.rs new file mode 100644 index 00000000..056729aa --- /dev/null +++ b/core/engine/tests/prepared_reuse.rs @@ -0,0 +1,72 @@ +use serde_json::{json, Value}; +use std::sync::Arc; +use zen_engine::loader::MemoryLoader; +use zen_engine::model::DecisionContent; +use zen_engine::DecisionEngine; + +fn document(value: Value) -> DecisionContent { + serde_json::from_value(value).expect("valid decision content") +} + +fn child(value: i64) -> DecisionContent { + document(json!({ + "nodes": [ + { "id": "in", "name": "in", "type": "inputNode", "content": {} }, + { "id": "e", "name": "e", "type": "expressionNode", "content": { + "expressions": [{ "id": "x", "key": "y", "value": format!("x + {value}") }] + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "a", "sourceId": "in", "targetId": "e" }, + { "id": "b", "sourceId": "e", "targetId": "out" } + ] + })) +} + +fn parent() -> DecisionContent { + document(json!({ + "nodes": [ + { "id": "in", "name": "in", "type": "inputNode", "content": {} }, + { "id": "d", "name": "d", "type": "decisionNode", "content": { "key": "child" } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "a", "sourceId": "in", "targetId": "d" }, + { "id": "b", "sourceId": "d", "targetId": "out" } + ] + })) +} + +#[tokio::test] +async fn graphs_and_sub_decisions_compile_once_while_the_loader_returns_the_same_content() { + let loader = Arc::new(MemoryLoader::default()); + loader.add("parent", parent()); + loader.add("child", child(1)); + let engine = DecisionEngine::default().with_loader(loader.clone()); + let run = || async { + engine + .evaluate("parent", json!({ "x": 1 }).into()) + .await + .expect("evaluates") + .result + .to_value() + }; + + assert_eq!(run().await, json!({ "y": 2 })); + assert_eq!(run().await, json!({ "y": 2 })); + let warm = zen_engine::diagnostics::compilations(); + for _ in 0..3 { + assert_eq!(run().await, json!({ "y": 2 })); + } + assert_eq!(zen_engine::diagnostics::compilations(), warm); + + loader.add("child", child(10)); + assert_eq!(run().await, json!({ "y": 11 })); + let changed = zen_engine::diagnostics::compilations(); + assert!(changed > warm); + for _ in 0..3 { + assert_eq!(run().await, json!({ "y": 11 })); + } + assert_eq!(zen_engine::diagnostics::compilations(), changed); +} diff --git a/core/engine/tests/spec.rs b/core/engine/tests/spec.rs new file mode 100644 index 00000000..18fcb3b7 --- /dev/null +++ b/core/engine/tests/spec.rs @@ -0,0 +1,751 @@ +mod conformance; +mod support; + +use conformance::run::{GraphRun, Guard, PolicyRun}; +use conformance::{Case, Dialect, Note, Spec, Suite}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::sync::Arc; +use support::columns::Built; +use support::golden::{Canon, Live, Outcome, Reference}; +use zen_engine::policy::EvaluateRequest; +use zen_engine::EvaluationOptions; +use zen_expression::Variable; + +#[derive(Default)] +struct Tally { + total: usize, + failed: usize, + bugs: usize, + questions: usize, +} + +#[derive(Default)] +struct Report { + files: BTreeMap, + failures: Vec, + bugs: Vec, + cases: usize, +} + +impl Report { + fn record(&mut self, suite: &Suite, case: &Case, got: &Result) { + let tally = self.files.entry(suite.file.clone()).or_default(); + tally.total += 1; + self.cases += 1; + tally.questions += matches!(case.note, Note::Question(_)) as usize; + match (&case.note, suite.verdict(case, got)) { + (Note::Bug(note), Some(failure)) => { + tally.bugs += 1; + self.bugs.push(format!("{failure} | bug: {note}")); + } + (Note::Bug(note), None) => { + tally.failed += 1; + self.failures.push(format!( + "{} | passes now, drop the bug note ({note})", + suite.location(case) + )); + } + (_, Some(failure)) => { + tally.failed += 1; + self.failures.push(failure); + } + (_, None) => {} + } + } + + fn finish(self, label: &str, problems: Vec) { + for (file, t) in &self.files { + eprintln!( + "{file}: {} cases, {} failed, {} known bugs, {} questions", + t.total, t.failed, t.bugs, t.questions + ); + } + eprintln!( + "{label}: {} cases, {} failed, {} known bugs, {} malformed", + self.cases, + self.failures.len(), + self.bugs.len(), + problems.len() + ); + if std::env::var("SPEC_BUGS").is_ok() { + eprintln!("known bugs:\n{}", self.bugs.join("\n")); + } + Differential::assert(problems, self.failures); + } +} + +struct Differential; + +impl Differential { + fn limit() -> usize { + std::env::var("SPEC_SHOW") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(60) + } + + fn assert(problems: Vec, failures: Vec) { + assert!( + problems.is_empty() && failures.is_empty(), + "malformed:\n{}\nfailures ({}):\n{}", + problems.join("\n"), + failures.len(), + failures + .iter() + .take(Self::limit()) + .cloned() + .collect::>() + .join("\n") + ); + } + + fn compare( + suite: &Suite, + case: &Case, + mode: &str, + want: &Result, + got: &Result, + out: &mut Vec, + ) { + let same = match (want, got) { + (Ok(a), Ok(b)) => Spec::same(a, b), + (Err(a), Err(b)) => a == b, + _ => false, + }; + if case.engines.is_some() { + return; + } + if !same { + out.push(format!( + "{} {mode} | input {}\n reference {}\n {mode:9} {}", + suite.location(case), + case.input_text, + Self::show(want), + Self::show(got) + )); + } + } + + fn show(r: &Result) -> String { + match r { + Ok(v) => Spec::render(v), + Err(e) => format!("!error ({e})"), + } + } +} + +struct Engines { + reference: Reference, + failures: Vec, + census: BTreeMap, + compared: usize, + columnar: usize, + hosted: usize, + nested: usize, + typed: usize, + laned: usize, +} + +impl Engines { + fn new(reference: Reference) -> Engines { + Engines { + reference, + failures: Vec::new(), + census: BTreeMap::new(), + compared: 0, + columnar: 0, + hosted: 0, + nested: 0, + typed: 0, + laned: 0, + } + } + + async fn walker( + reference: &Reference, + run: &GraphRun, + suite: &Suite, + case: &Case, + ) -> Result { + reference + .graph( + || Canon::key(&suite.id(), &[], &case.input), + || run.walker(case), + GraphRun::recorded, + ) + .await + } + + async fn graph(&mut self, suite: &Suite) { + let Ok(run) = GraphRun::new(suite) else { + return; + }; + let verdict = match run.compiled.compiled_verdict() { + Some(Ok(())) => "compiled".to_string(), + Some(Err(reason)) => format!("walker: {reason}"), + None => "not compiled".to_string(), + }; + *self.census.entry(verdict).or_default() += 1; + let mut wants = Vec::new(); + for case in &suite.cases { + wants.push(Self::walker(&self.reference, &run, suite, case).await); + } + let contexts: Vec = suite + .cases + .iter() + .map(|c| c.input.depth_clone(64)) + .collect(); + let cycled: Vec = (0..contexts.len() * 3) + .map(|i| contexts[i % contexts.len()].depth_clone(64)) + .collect(); + let batch = run + .compiled + .evaluate_batch(&cycled, EvaluationOptions::default()) + .await; + for (i, case) in suite.cases.iter().enumerate() { + let single = GraphRun::outcome(run.compiled.evaluate(case.input.depth_clone(64)).await); + Differential::compare( + suite, + case, + "single", + &wants[i], + &single, + &mut self.failures, + ); + let engine = GraphRun::outcome( + run.engine + .evaluate(GraphRun::MAIN, case.input.depth_clone(64)) + .await, + ); + Differential::compare( + suite, + case, + "engine", + &wants[i], + &engine, + &mut self.failures, + ); + for result in batch.iter().skip(i).step_by(suite.cases.len().max(1)) { + let got = result + .as_ref() + .map(|r| r.result.clone()) + .map_err(|e| GraphRun::error(e)); + Differential::compare(suite, case, "batch", &wants[i], &got, &mut self.failures); + } + self.compared += 1; + } + let _ = zen_engine::diagnostics::census(); + let rows: Vec = suite.cases.iter().map(|c| c.input.to_value()).collect(); + let cycled_rows: Vec = (0..rows.len() * 3) + .map(|i| rows[i % rows.len()].clone()) + .collect(); + for built in Built::new(&rows) + .into_iter() + .chain(Built::lists(&rows)) + .chain(Built::new(&cycled_rows)) + .chain(Built::nested(&rows)) + .chain(Built::nested(&cycled_rows)) + { + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + let output = run + .compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + self.typed += output.paths().typed; + self.laned += output.paths().laned; + for row in 0..built.rows { + let input = columns.row(row); + let want = self + .reference + .graph( + || Canon::key(&suite.id(), &[], &input), + || async { + match run.walker.evaluate(input.depth_clone(64)).await { + Ok(r) => Ok(Built::normalized(r.result.to_value())), + Err(e) => Err(GraphRun::error(&e)), + } + }, + |outcome| { + GraphRun::recorded(outcome).map(|v| Built::normalized(v.to_value())) + }, + ) + .await; + let got = match &output.errors[row] { + Some(e) => Err(GraphRun::error(e)), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + self.columnar += 1; + let case = suite + .cases + .iter() + .find(|c| { + Built::normalized(c.input.to_value()) == Built::normalized(input.to_value()) + }) + .unwrap_or(&suite.cases[0]); + if got != want + && case.engines.is_none() + && !self + .reference + .ordered(|| Canon::key(&suite.id(), &[], &input)) + { + self.failures.push(format!( + "{} columnar | input {}\n reference {want:?}\n columnar {got:?}", + suite.location(case), + input.to_value() + )); + } + } + } + if support::switches().census { + for (key, calls, rows, ns) in zen_engine::diagnostics::census() { + println!("CENSUS\tspec:{}\t{key}\t{calls}\t{rows}\t{ns}", suite.id()); + } + } + } + + fn driver( + reference: &Reference, + run: &PolicyRun, + suite: &Suite, + case: &Case, + ) -> Result { + reference.policy( + || Canon::key(&suite.id(), &case.goals, &case.input), + || run.driver(case), + |outcome| run.recorded(outcome), + ) + } + + fn policy(&mut self, suite: &Suite) { + let Ok(run) = PolicyRun::new(suite) else { + return; + }; + let requests: Vec = (0..suite.cases.len() * 3) + .map(|i| PolicyRun::request(&suite.cases[i % suite.cases.len()])) + .collect(); + let batch = run.workspace.evaluate_batch(&requests); + for (i, case) in suite.cases.iter().enumerate() { + let want = Self::driver(&self.reference, &run, suite, case); + let single = run.compiled(case); + Differential::compare(suite, case, "single", &want, &single, &mut self.failures); + for result in batch.iter().skip(i).step_by(suite.cases.len().max(1)) { + let got = run.gated(result); + Differential::compare(suite, case, "batch", &want, &got, &mut self.failures); + } + if case.goals.is_empty() && run.gate { + let engine = run.engine(case); + Differential::compare(suite, case, "engine", &want, &engine, &mut self.failures); + } + self.compared += 1; + } + if !run.blocking.is_empty() && run.gate { + return; + } + let mut goal_sets: Vec<&Vec> = suite.cases.iter().map(|c| &c.goals).collect(); + goal_sets.dedup(); + for goals in goal_sets { + let cases: Vec<&Case> = suite.cases.iter().filter(|c| &c.goals == goals).collect(); + let rows: Vec = cases.iter().map(|c| c.input.to_value()).collect(); + let cycled: Vec = (0..rows.len() * 3) + .map(|i| rows[i % rows.len()].clone()) + .collect(); + let targets: Vec> = goals.iter().map(|g| Arc::from(g.as_str())).collect(); + for built in Built::new(&rows) + .into_iter() + .chain(Built::lists(&rows)) + .chain(Built::new(&cycled)) + { + self.policy_columns(suite, &run, &cases, goals, &targets, &built.columns()); + } + for built in Built::nested(&rows) + .into_iter() + .chain(Built::nested(&cycled)) + { + let fields = built.fields(); + let structs = built.structs(&fields); + self.nested += built.rows; + self.policy_columns( + suite, + &run, + &cases, + goals, + &targets, + &built.columns_with(&structs), + ); + } + } + } + + fn policy_columns( + &mut self, + suite: &Suite, + run: &PolicyRun, + cases: &[&Case], + goals: &[String], + targets: &[Arc], + columns: &zen_expression::lane::Columns, + ) { + let Ok(output) = + run.workspace + .evaluate_columns(&Arc::from(PolicyRun::MAIN), targets, columns) + else { + return; + }; + self.hosted += output.paths().hosted; + self.typed += output.paths().typed; + self.laned += output.paths().laned; + for row in 0..columns.rows { + let input = columns.row(row); + let request = EvaluateRequest { + policy_path: Arc::from(PolicyRun::MAIN), + input: input.depth_clone(64), + goals: targets.to_vec(), + trace: false, + }; + let want = self.reference.policy( + || Canon::key(&suite.id(), goals, &input), + || { + Live::policy(&run.workspace, &request) + .map(|r| Built::normalized(r.output.to_value())) + .map_err(|e| format!("{e:?}")) + }, + |outcome| match outcome { + Outcome::Ok(value) => Ok(Built::normalized(Canon::restore(value).to_value())), + Outcome::Err { debug, .. } => Err(debug.clone()), + }, + ); + let got = match output.errors[row] + .as_deref() + .and_then(zen_engine::EvaluationError::policy) + { + Some(error) => Err(Reference::debug(error)), + None => Ok(Built::normalized(output.row(row).to_value())), + }; + self.columnar += 1; + if got != want + && !self + .reference + .ordered(|| Canon::key(&suite.id(), goals, &input)) + { + let case = cases + .iter() + .find(|c| { + Built::normalized(c.input.to_value()) == Built::normalized(input.to_value()) + }) + .copied() + .unwrap_or(cases[0]); + self.failures.push(format!( + "{} columnar | input {}\n reference {want:?}\n columnar {got:?}", + suite.location(case), + input.to_value() + )); + } + } + } +} + +#[test] +fn graph_spec_matches_walker() { + support::switches(); + if Reference::unavailable("spec-graph") { + return; + } + Spec::prepare(); + let (suites, mut problems) = Spec::suites(Dialect::Graph); + let reference = Reference::open("spec-graph"); + let mut report = Report::default(); + for suite in &suites { + let run = match GraphRun::new(suite) { + Ok(run) => run, + Err(e) => { + problems.push(e); + continue; + } + }; + let label = format!("{}:{} [{}]", suite.file, suite.line, suite.name); + let outcomes = Guard::run(label, &mut report.failures, || { + Guard::block(async { + let mut out = Vec::new(); + for case in &suite.cases { + out.push(Engines::walker(&reference, &run, suite, case).await); + } + out + }) + }); + for (case, got) in suite.cases.iter().zip(outcomes.unwrap_or_default()) { + report.record(suite, case, &got); + } + } + report.failures.extend(reference.missing()); + report.finish("graph spec", problems); +} + +#[test] +fn graph_engines_match_walker() { + support::switches(); + if Reference::unavailable("spec-graph") { + return; + } + Spec::prepare(); + let (suites, problems) = Spec::suites(Dialect::Graph); + let mut engines = Engines::new(Reference::open("spec-graph")); + for suite in &suites { + let label = format!("{}:{} [{}]", suite.file, suite.line, suite.name); + let mut failures = Vec::new(); + Guard::run(label, &mut failures, || Guard::block(engines.graph(suite))); + engines.failures.extend(failures); + } + engines.failures.extend(engines.reference.missing()); + for (verdict, count) in &engines.census { + eprintln!("{verdict}: {count} suites"); + } + eprintln!( + "graph engines: {} cases, {} columnar rows, {} mismatches", + engines.compared, + engines.columnar, + engines.failures.len() + ); + eprintln!( + "graph engines: {} typed units, {} laned units", + engines.typed, engines.laned + ); + assert!( + !support::switches().typed || engines.typed > 0, + "no graph unit ran typed" + ); + Differential::assert(problems, engines.failures); +} + +#[test] +fn policy_spec_matches_driver() { + support::switches(); + if Reference::unavailable("spec-policy") { + return; + } + Spec::prepare(); + let (suites, mut problems) = Spec::suites(Dialect::Policy); + let reference = Reference::open("spec-policy"); + let mut report = Report::default(); + for suite in &suites { + let run = match PolicyRun::new(suite) { + Ok(run) => run, + Err(e) => { + problems.push(e); + continue; + } + }; + let label = format!("{}:{} [{}]", suite.file, suite.line, suite.name); + let outcomes = Guard::run(label, &mut report.failures, || { + suite + .cases + .iter() + .map(|case| Engines::driver(&reference, &run, suite, case)) + .collect::>() + }); + for (case, got) in suite.cases.iter().zip(outcomes.unwrap_or_default()) { + report.record(suite, case, &got); + } + if let Some(expected) = &suite.diagnostics { + if *expected != run.blocking { + report.failures.push(format!( + "{}:{} [{}] | diagnostics expected {expected:?} got {:?}", + suite.file, suite.line, suite.name, run.blocking + )); + } + } + } + report.failures.extend(reference.missing()); + report.finish("policy spec", problems); +} + +#[test] +fn policy_engines_match_driver() { + support::switches(); + if Reference::unavailable("spec-policy") { + return; + } + Spec::prepare(); + let (suites, problems) = Spec::suites(Dialect::Policy); + let mut engines = Engines::new(Reference::open("spec-policy")); + for suite in &suites { + let label = format!("{}:{} [{}]", suite.file, suite.line, suite.name); + let mut failures = Vec::new(); + Guard::run(label, &mut failures, || engines.policy(suite)); + engines.failures.extend(failures); + } + engines.failures.extend(engines.reference.missing()); + eprintln!("policy engines: {} cases, {} columnar rows ({} with struct lists, {} hosted per row), {} mismatches", engines.compared, engines.columnar, engines.nested, engines.hosted, engines.failures.len()); + eprintln!( + "policy engines: {} typed units, {} laned units", + engines.typed, engines.laned + ); + if support::switches().census { + for (key, calls, rows, ns) in zen_engine::diagnostics::census() { + println!("CENSUS\tspec-policy\t{key}\t{calls}\t{rows}\t{ns}"); + } + } + assert!( + !support::switches().typed || engines.typed > 0, + "no policy unit ran typed" + ); + Differential::assert(problems, engines.failures); +} + +struct Snapshot { + lines: Vec, +} + +impl Snapshot { + const CALLS: usize = 4; + + fn paths<'p>(paths: impl Iterator>) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for path in paths { + path.hash(&mut hasher); + } + hasher.finish() + } + + fn kinds(errors: impl Iterator) -> String { + let mut kinds: BTreeMap = BTreeMap::new(); + for error in errors { + let kind: String = error + .chars() + .take_while(|c| c.is_alphanumeric() || *c == '_') + .collect(); + *kinds.entry(kind).or_default() += 1; + } + kinds + .iter() + .map(|(kind, count)| format!("{kind}={count}")) + .collect::>() + .join(",") + } + + fn graph_rows(rows: &[Value]) -> Vec<(&'static str, Built)> { + let cycled: Vec = (0..rows.len() * 3) + .map(|i| rows[i % rows.len()].clone()) + .collect(); + let mut builds = Vec::new(); + builds.extend(Built::new(rows).map(|b| ("flat", b))); + builds.extend(Built::lists(rows).map(|b| ("lists", b))); + builds.extend(Built::new(&cycled).map(|b| ("cycled", b))); + builds.extend(Built::nested(rows).map(|b| ("nested", b))); + builds.extend(Built::nested(&cycled).map(|b| ("nested-cycled", b))); + builds + } + + async fn graph(&mut self, suite: &Suite) { + let rows: Vec = suite.cases.iter().map(|c| c.input.to_value()).collect(); + for (label, built) in Self::graph_rows(&rows) { + let Ok(run) = GraphRun::new(suite) else { + return; + }; + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + for call in 1..=Self::CALLS { + let output = run + .compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + let errors = output.errors.iter().flatten().map(|e| format!("{e:?}")); + self.lines.push(format!( + "graph\t{}\t{label}\tcall{call}\trows={}\ttyped={}\tlaned={}\terrors=[{}]\tpaths={:016x}", + suite.id(), + output.rows, + output.paths().typed, + output.paths().laned, + Self::kinds(errors), + Self::paths(output.columns.iter().map(|(path, _)| path)) + )); + } + } + } + + fn policy(&mut self, suite: &Suite) { + let Ok(probe) = PolicyRun::new(suite) else { + return; + }; + if !probe.blocking.is_empty() && probe.gate { + return; + } + let mut goal_sets: Vec<&Vec> = suite.cases.iter().map(|c| &c.goals).collect(); + goal_sets.dedup(); + for goals in goal_sets { + let rows: Vec = suite + .cases + .iter() + .filter(|c| &c.goals == goals) + .map(|c| c.input.to_value()) + .collect(); + let targets: Vec> = goals.iter().map(|g| Arc::from(g.as_str())).collect(); + for (label, built) in Self::graph_rows(&rows) { + let Ok(run) = PolicyRun::new(suite) else { + return; + }; + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = match label.starts_with("nested") { + true => built.columns_with(&structs), + false => built.columns(), + }; + for call in 1..=Self::CALLS { + let line = match run.workspace.evaluate_columns(&Arc::from(PolicyRun::MAIN), &targets, &columns) { + Ok(output) => format!( + "rows={}\ttyped={}\tlaned={}\thosted={}\terrors=[{}]\tpaths={:016x}\torder={:016x}", + output.rows, + output.paths().typed, + output.paths().laned, + output.paths().hosted, + Self::kinds(output.errors.iter().flatten().map(|e| format!("{e:?}"))), + Self::paths(output.columns.iter().map(|(path, _)| path).collect::>().into_iter()), + Self::paths(output.columns.iter().map(|(path, _)| path)) + ), + Err(error) => format!("refused {}", Self::kinds(std::iter::once(format!("{error:?}")))), + }; + self.lines.push(format!( + "policy\t{}\t{goals:?}\t{label}\tcall{call}\t{line}", + suite.id() + )); + } + } + } + } +} + +#[test] +#[ignore] +fn consolidation_snapshot() { + Spec::prepare(); + let mut snapshot = Snapshot { lines: Vec::new() }; + let (suites, _) = Spec::suites(Dialect::Graph); + for suite in &suites { + let label = format!("{}:{} [{}]", suite.file, suite.line, suite.name); + let mut failures = Vec::new(); + Guard::run(label, &mut failures, || Guard::block(snapshot.graph(suite))); + snapshot.lines.extend( + failures + .iter() + .map(|f| format!("graph\tpanic\t{}", f.lines().next().unwrap_or_default())), + ); + } + let (suites, _) = Spec::suites(Dialect::Policy); + for suite in &suites { + let label = format!("{}:{} [{}]", suite.file, suite.line, suite.name); + let mut failures = Vec::new(); + Guard::run(label, &mut failures, || snapshot.policy(suite)); + snapshot.lines.extend( + failures + .iter() + .map(|f| format!("policy\tpanic\t{}", f.lines().next().unwrap_or_default())), + ); + } + for line in &snapshot.lines { + println!("SNAPSHOT\t{line}"); + } +} diff --git a/core/engine/tests/spec/README.md b/core/engine/tests/spec/README.md new file mode 100644 index 00000000..9854599c --- /dev/null +++ b/core/engine/tests/spec/README.md @@ -0,0 +1,150 @@ +# ZEN engine conformance suite + +Executable specification of decision graphs and policies, the engine-level sibling of +`core/expression/tests/spec`. Each case states what a decision is meant to produce, not +only what the current engine does. Known deviations are recorded in place. + +## Layout + +- `graph/NN-chapter.json5`: decision graphs (JDM), evaluated by the graph walker. +- `policy/NN-chapter.json5`: policies, evaluated by the policy driver. + +A chapter is a sequence of suites. A suite is one decision plus the cases run against it. +Files use a JSON5-like syntax: `//` and `/* */` comments, unquoted keys, single or double +quoted strings, trailing commas, and `"""raw"""` strings for multi-line source (function +nodes). Numbers are read as exact decimals. `date('...')` is a date input that keeps its +source text, as the engine produces for schema date fields. Graph requests are normalized at +the input node, so in graph suites a `date()` input arrives as text; build date values with an +upstream `d(...)` expression or an input schema field with `format: date`. + +## Cases + +```json5 +cases: [ + [input, output], + [input, output, "bug: why the engine differs"], + {input: {...}, output: {...}, goals: ["customer.tier"], note: "question: ..."}, +] +``` + +- **output**: the expected result, compared by value. Numbers compare by exact decimal + value (`1.10 == 1.1`); objects compare unordered. `"!error"` expects any error; + `"!error: text"` expects an error whose serialized form contains `text` (use it only for + stable, user-facing error kinds). +- **note** (optional): + - `bug: `: the output holds the intended result and the engine differs. A bug case + that starts passing fails the run, so the note gets removed. + - `question: `: the output holds current behaviour whose intent is unclear. +- **goals** (policy only): the request goals. +- **engines** (object form only): a documented difference between the reference (walker or + driver) and the other engine modes, with the reason. The case is still checked against the + spec, but not compared across engines. Use it only when the reference itself is wrong or + reports a different but equivalent error, and say which side gives the intended result. + +Evaluation time is fixed at `2025-03-20T10:15:30Z`, time zone UTC (`SPEC_TZ` overrides). + +## Graph suites + +```json5 +{ + name: "first hit returns the first matching rule", + graph: { + nodes: [ + {table: "rules", hit: "first", inputs: ["age"], outputs: ["tier"], rules: [ + ["> 18", "'adult'"], + ["", "'minor'"], + ]}, + ], + }, + cases: [ + [{age: 20}, {tier: "adult"}], + ], +} +``` + +`graph` is either `{raw: }` or the shorthand below. Shorthand nodes name +their kind with one key whose value is the node name (also its id unless `id` is given): + +| node | fields | +|---|---| +| `{input: "request", schema?}` | `schema` is a JSON schema object or string | +| `{output: "response", schema?}` | | +| `{expression: "calc", fields}` | `fields` is `{key: "expr"}` in order, or `[["key", "expr"], ...]` for duplicate keys | +| `{table: "t", hit?, inputs, outputs, rules}` | `hit` is `first` (default) or `collect`; `inputs` are field strings (`null`/`""` = no field) or `{field, name}`; `outputs` are field paths (a `[]` suffix collects per column) or `{field, type}`; `rules` are rows of cell strings, inputs then outputs (`""` = any) | +| `{switch: "s", hit?, when: ["cond", ...]}` | `""` is the default branch; edges leave branch `i` as `"s:i"` | +| `{function: "f", source}` | v2 function node (`export const handler = async (input) => ...`) | +| `{functionV1: "f", source}` | v1 function node | +| `{decision: "d", key}` | sub-decision loaded from the suite's `decisions` | +| `{custom: "c", kind, config}` | spec adapter kinds: `echo` (returns input), `config` (returns config), `render` (each config key rendered as a template field), `fail` (errors with `config.message`) | + +Expression, table and decision nodes also take `passThrough`, `inputField`, `outputPath` and +`executionMode` (`"single"` or `"loop"`). + +When the graph has no input or output node, nodes named `input` and `output` are added. +`edges` is a list of chains: `"input -> a -> b -> output"`, `"route:0 -> adult"`. Without +`edges`, the nodes are chained in order from input to output. + +`decisions: {key: | {raw: ...} | {policy: }}` registers +sub-decisions for decision nodes. + +## Policy suites + +```json5 +{ + name: "an expression block writes a computed property", + policy: { + models: {customer: {age: "number", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + ], + }, + cases: [ + [{customer: {age: 20, companies: []}}, {customer: {age: 20, companies: [], adult: true}}], + ], +} +``` + +`policy` is either `{raw: }` or: + +- `models: {entity: {property: "type"}}` and `globals: {name: {...}}` (global scope). Types: + `string`, `number`, `boolean`, `date`, `string(a|b|c)` (enum), `entity` (relationship), + `&entity` (reference); suffix `[]` for arrays and `?` for optional (`"company[]?"`). +- `dictionaries: {name: ["value", ["value", "label"], ...]}` +- `imports: ["path", ...]` naming documents in the suite's `policies`. +- `blocks`, in document order: + - `{expression: "path", value: "expr"}` + - `{match: "path", arms: [["condition", "value"], ["", "default"]]}` + - `{assertion: "path", conditions: ["expr", ["or", "expr", depth], ...]}` + - `{table: "id", hit?, inputs: ["field", ...], outputs: ["path", ...], rules: [[...]]}` + - any block takes an explicit `id`. + +`policies: {path: | {graph: }}` registers other +workspace documents. The suite's own policy is evaluated at path `main`. + +Policies with error diagnostics are refused by `DecisionEngine`, so the runners gate them the +same way: every case of such a suite yields `CompilationErrors [codes]`. A suite that sets +`diagnostics: ["TYPE_MISMATCH", ...]` pins the exact set of error codes and evaluates its cases +through the workspace API, which runs policies despite errors; use it to specify runtime +behaviour of policies that only the workspace (editor) path can execute. + +## Runners + +All runners live in `core/engine/tests/spec.rs`. Run with `--all-features` (exact decimals +need `arbitrary_precision`): + +- `graph_spec_matches_walker`: the graph walker against the spec. +- `graph_engines_match_walker`: the compiled engine (single, batch, columnar with plain, + list and cycled column layouts, and `DecisionEngine` with a loader) against the walker's + actual result, bugs included. +- `policy_spec_matches_driver`: the policy driver against the spec. +- `policy_engines_match_driver`: the compiled policy engine (single, batch, and + `DecisionEngine` for cases without goals) against the driver's actual result. + +A panic in any engine is reported as a failure of its suite and does not stop the run. + +``` +cargo test -p zen-engine --all-features --release --test spec +``` + +Environment knobs: `SPEC_FILE=` (files), `SPEC_SUITE=` (suite +names), `SPEC_SHOW=` (failures printed), `SPEC_BUGS=1` (list known bugs). diff --git a/core/engine/tests/spec/graph/00-harness.json5 b/core/engine/tests/spec/graph/00-harness.json5 new file mode 100644 index 00000000..6e60e2ee --- /dev/null +++ b/core/engine/tests/spec/graph/00-harness.json5 @@ -0,0 +1,81 @@ +// The harness itself: implicit input/output nodes, chains, raw content. +{ + name: "an empty graph passes the input through", + graph: {}, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + ], +} + +{ + name: "implicit chain through one expression node", + graph: { + nodes: [{expression: "calc", fields: {total: "a + b"}}], + }, + cases: [ + [{a: 1, b: 2}, {total: 3}], + [{a: 0.1, b: 0.2}, {total: 0.3}], + [{a: "x", b: 1}, "!error"], + ], +} + +{ + name: "explicit edges and pass-through", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: {total: "a * 2"}}], + edges: ["input -> calc -> output"], + }, + cases: [ + [{a: 2}, {a: 2, total: 4}], + ], +} + +{ + name: "raw JDM content", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [{id: "e", sourceId: "i", targetId: "o"}], + }, + }, + cases: [[{x: true}, {x: true}]], +} + +{ + name: "custom spec adapter kinds", + graph: { + nodes: [{custom: "c", kind: "render", config: {greeting: "hello {{ name }}", n: 2}}], + }, + cases: [[{name: "ann"}, {greeting: "hello ann", n: 2}]], +} + +{ + name: "switch branches by handle", + graph: { + nodes: [ + {switch: "route", when: ["age >= 18", ""]}, + {expression: "adult", fields: {kind: "'adult'"}}, + {expression: "minor", fields: {kind: "'minor'"}}, + ], + edges: ["input -> route", "route:0 -> adult -> output", "route:1 -> minor -> output"], + }, + cases: [ + [{age: 20}, {kind: "adult"}], + [{age: 3}, {kind: "minor"}], + ], +} + +{ + name: "sub-decision by key", + decisions: { + child: {nodes: [{expression: "double", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [[{x: 4}, {y: 8}]], +} diff --git a/core/engine/tests/spec/graph/01-input-output.json5 b/core/engine/tests/spec/graph/01-input-output.json5 new file mode 100644 index 00000000..499688c9 --- /dev/null +++ b/core/engine/tests/spec/graph/01-input-output.json5 @@ -0,0 +1,507 @@ +// Input and output nodes: what enters a graph, what leaves it, and which nodes contribute to the result. + +// --------------------------------------------------------------------------- +// input -> output passes the request through unchanged. +{ + name: "input -> output passes scalars through", + graph: {nodes: [{input: "request"}, {output: "response"}]}, + cases: [ + [{a: 1}, {a: 1}], + [{a: "text"}, {a: "text"}], + [{a: true, b: false}, {a: true, b: false}], + [{a: 0}, {a: 0}], + [{a: -1.5}, {a: -1.5}], + [{a: 0.1000000000000000000000000001}, {a: 0.1000000000000000000000000001}], + [{a: ""}, {a: ""}], + ], +} + +{ + name: "input -> output passes nested structures through", + graph: {nodes: [{input: "request"}, {output: "response"}]}, + cases: [ + [{a: {b: {c: 1}}}, {a: {b: {c: 1}}}], + [{list: [1, 2, 3]}, {list: [1, 2, 3]}], + [{list: [{x: 1}, {x: 2}]}, {list: [{x: 1}, {x: 2}]}], + [{list: []}, {list: []}], + [{obj: {}}, {obj: {}}], + [{m: [[1, 2], [3]]}, {m: [[1, 2], [3]]}], + [{a: 1, b: "x", c: [true], d: {e: null}}, {a: 1, b: "x", c: [true], d: {e: null}}], + ], +} + +{ + name: "input -> output with an empty request", + graph: {nodes: [{input: "request"}, {output: "response"}]}, + cases: [ + [{}, {}], + ], +} + +// Keys whose value is null sit at the top level of the request. The final result is assembled by +// merging the ending nodes into an empty object with merge-patch semantics, which deletes top-level +// null keys. Nested nulls survive because a nested object replaces a missing key wholesale. +{ + name: "null keys in the request", + graph: {nodes: [{input: "request"}, {output: "response"}]}, + cases: [ + [{a: null}, {}, "question: top-level null keys are dropped from the result while nested nulls survive"], + [{a: null, b: 1}, {b: 1}, "question: top-level null keys are dropped from the result while nested nulls survive"], + [{a: {b: null}}, {a: {b: null}}], + [{a: [null, 1]}, {a: [null, 1]}], + [{a: {b: {c: null}}, d: 2}, {a: {b: {c: null}}, d: 2}], + ], +} + +{ + name: "keys with special characters pass through", + graph: {nodes: [{input: "request"}, {output: "response"}]}, + cases: [ + [{"a.b": 1}, {"a.b": 1}], + [{"my key": "v"}, {"my key": "v"}], + [{"": 1}, {"": 1}], + [{"ключ": "значение"}, {"ключ": "значение"}], + [{"$x": 1}, {"$x": 1}], + ], +} + +// --------------------------------------------------------------------------- +// Non-object requests. Nodes receive the merge of their incoming data; a scalar incoming value is +// not an object, so the next node sees an empty object. Arrays are kept as they are. +{ + name: "non-object requests through input -> output", + graph: {nodes: [{input: "request"}, {output: "response"}]}, + cases: [ + [5, {}, "question: a scalar request is replaced by an empty object instead of being returned or rejected"], + ["text", {}, "question: a scalar request is replaced by an empty object instead of being returned or rejected"], + [true, {}, "question: a scalar request is replaced by an empty object instead of being returned or rejected"], + [null, {}], + [[1, 2, 3], [1, 2, 3]], + [[], []], + [[{a: 1}], [{a: 1}]], + ], +} + +{ + name: "an expression node after a non-object request sees an empty object", + graph: {nodes: [{expression: "calc", fields: {kind: "type(a)", isNull: "a == null"}}]}, + cases: [ + [5, {kind: "null", isNull: true}], + ["x", {kind: "null", isNull: true}], + [null, {kind: "null", isNull: true}], + [{a: 1}, {kind: "number", isNull: false}], + [{a: "s"}, {kind: "string", isNull: false}], + [{}, {kind: "null", isNull: true}], + ], +} + +{ + name: "an expression node sees an array request through $nodes", + graph: {nodes: [{input: "request"}, {expression: "calc", fields: {n: "len($nodes.request)"}}, {output: "response"}]}, + cases: [ + [[1, 2, 3], {n: 3}], + [[], {n: 0}], + [["a"], {n: 1}], + ], +} + +// --------------------------------------------------------------------------- +// Input node names: the input node publishes the request under its name in $nodes. +{ + name: "the input node is visible in $nodes under its name", + graph: {nodes: [{input: "request"}, {expression: "calc", fields: {x: "$nodes.request.a", same: "$nodes.request.a == a"}}, {output: "response"}]}, + cases: [ + [{a: 1}, {x: 1, same: true}], + [{a: "s"}, {x: "s", same: true}], + [{a: true}, {x: true, same: true}], + [{}, {same: true}], + ], +} + +{ + name: "an input node name with spaces is reachable with bracket access", + graph: {nodes: [{input: "my request"}, {expression: "calc", fields: {x: "$nodes['my request'].a"}}, {output: "response"}]}, + cases: [ + [{a: 1}, {x: 1}], + [{a: {b: 2}}, {x: {b: 2}}], + [{}, {}], + ], +} + +{ + name: "the input node id differs from its name", + graph: {nodes: [{input: "request", id: "in-1"}, {expression: "calc", fields: {byName: "$nodes.request.a", byId: "$nodes['in-1'].a"}}, {output: "response", id: "out-1"}]}, + cases: [ + [{a: 1}, {byName: 1}], + [{a: "x"}, {byName: "x"}], + ], +} + +{ + name: "output node name has no effect on the result", + graph: {nodes: [{input: "request"}, {output: "anything at all"}]}, + cases: [ + [{a: 1}, {a: 1}], + [{response: 1}, {response: 1}], + ], +} + +{ + name: "$nodes is removed from the final result", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {x: "1"}}]}, + cases: [ + [{a: 1}, {a: 1, x: 1}], + [{"$nodes": {y: 1}, a: 1}, {a: 1, x: 1}, "question: a request key named $nodes is silently stripped from the result"], + ], +} + +// --------------------------------------------------------------------------- +// Graph shape: input count, cycles, edges to unknown nodes. +{ + name: "a graph with two input nodes is rejected", + graph: { + nodes: [{input: "a"}, {input: "b"}, {output: "response"}], + edges: ["a -> response", "b -> response"], + }, + cases: [ + [{x: 1}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "a graph with no input node is rejected", + graph: { + raw: { + nodes: [{id: "o", name: "response", type: "outputNode", content: {}}], + edges: [], + }, + }, + cases: [ + [{x: 1}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "a cyclic graph is rejected", + graph: { + nodes: [ + {expression: "a", fields: {x: "1"}}, + {expression: "b", fields: {y: "2"}}, + ], + edges: ["input -> a -> b -> a", "b -> output"], + }, + cases: [ + [{x: 1}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "an edge to an unknown node is rejected", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [ + {id: "e1", sourceId: "i", targetId: "o"}, + {id: "e2", sourceId: "i", targetId: "missing"}, + ], + }, + }, + cases: [ + [{x: 1}, "!error"], + ], +} + +{ + name: "a graph with only an input node returns the request", + graph: {raw: {nodes: [{id: "i", name: "request", type: "inputNode", content: {}}], edges: []}}, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{a: {b: [1]}}, {a: {b: [1]}}], + ], +} + +// --------------------------------------------------------------------------- +// Unconnected and dead-end nodes. Only nodes reachable from the input run. The result is the merge +// of executed nodes without outgoing edges. +{ + name: "an unconnected output node: the input node is the ending node", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [], + }, + }, + cases: [ + [{a: 1}, {a: 1}], + [{a: "x", b: [1]}, {a: "x", b: [1]}], + [{}, {}], + ], +} + +{ + name: "an unconnected expression node never runs", + graph: { + nodes: [{expression: "orphan", fields: {boom: "1 + 'x'", y: "1"}}], + edges: ["input -> output"], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{a: "x"}, {a: "x"}], + ], +} + +{ + name: "an expression node that feeds into nothing is not part of a graph without output edges", + graph: { + nodes: [{expression: "calc", fields: {y: "a * 2"}}], + edges: ["input -> calc"], + }, + cases: [ + [{a: 1}, {y: 2}], + [{a: 0}, {y: 0}], + [{a: -3}, {y: -6}], + ], +} + +{ + name: "a node chain that never reaches an output node still produces the result", + graph: { + nodes: [ + {expression: "first", fields: {y: "a + 1"}}, + {expression: "second", fields: {z: "y * 10"}}, + ], + edges: ["input -> first -> second"], + }, + cases: [ + [{a: 1}, {z: 20}], + [{a: 0}, {z: 10}], + ], +} + +{ + name: "an unconnected expression node with input upstream of the chain", + graph: { + nodes: [ + {expression: "used", fields: {y: "a"}}, + {expression: "unused", fields: {z: "a"}}, + ], + edges: ["input -> used -> output", "unused -> output"], + }, + cases: [ + [{a: 1}, {y: 1}, "question: a node with no incoming edges is executed as an unresolved dependency of the output node and contributes with an empty input; null keys get dropped"], + ], +} + +// A dead-end branch (input -> side, side has no outgoing edge) next to input -> output. The walker +// stops once the output node runs, so whether the dead end contributes depends on visiting order. +{ + name: "a dead-end branch listed before the output edge", + graph: { + nodes: [{expression: "side", fields: {side: "1"}}], + edges: ["input -> side", "input -> output"], + }, + cases: [ + [{a: 1}, {a: 1, side: 1}, "question: whether a dead-end node contributes to the result depends on edge order (listed after output it is skipped)"], + [{}, {side: 1}, "question: whether a dead-end node contributes to the result depends on edge order (listed after output it is skipped)"], + [{a: 2, side: 0}, {a: 2, side: 0}, "question: whether a dead-end node contributes depends on edge order, and on conflicts the output node wins over the dead end"], + ], +} + +{ + name: "a dead-end branch listed after the output edge", + graph: { + nodes: [{expression: "side", fields: {side: "1"}}], + edges: ["input -> output", "input -> side"], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + ], +} + +{ + name: "a dead end that errors does not fail the graph when it is not visited", + graph: { + nodes: [{expression: "side", fields: {boom: "a + 'x' + true"}}], + edges: ["input -> output", "input -> side"], + }, + cases: [ + [{a: 1}, {a: 1}], + [{a: "s"}, {a: "s"}], + ], +} + +// --------------------------------------------------------------------------- +// Multiple output nodes. The first output node reached ends the walk. +{ + name: "two outputs on two branches", + graph: { + nodes: [ + {expression: "left", fields: {side: "'left'"}}, + {expression: "right", fields: {side: "'right'"}}, + {output: "out1"}, + {output: "out2"}, + ], + edges: ["input -> left -> out1", "input -> right -> out2"], + }, + cases: [ + [{a: 1}, {side: "left"}], + [{}, {side: "left"}], + ], +} + +{ + name: "two outputs fed by the same node", + graph: { + nodes: [ + {expression: "calc", fields: {y: "a + 1"}}, + {output: "out1"}, + {output: "out2"}, + ], + edges: ["input -> calc -> out1", "calc -> out2"], + }, + cases: [ + [{a: 1}, {y: 2}], + [{a: 10}, {y: 11}], + ], +} + +{ + name: "an output node directly after input and another after an expression", + graph: { + nodes: [ + {expression: "calc", fields: {y: "a + 1"}}, + {output: "early"}, + {output: "late"}, + ], + edges: ["input -> early", "input -> calc -> late"], + }, + cases: [ + [{a: 1}, {a: 1}], + [{a: 5}, {a: 5}], + ], +} + +// --------------------------------------------------------------------------- +// Output node with several incoming edges merges them. +{ + name: "the output node merges disjoint branches", + graph: { + nodes: [ + {expression: "left", fields: {l: "a + 1"}}, + {expression: "right", fields: {r: "a * 2"}}, + ], + edges: ["input -> left -> output", "input -> right -> output"], + }, + cases: [ + [{a: 1}, {l: 2, r: 2}], + [{a: 3}, {l: 4, r: 6}], + [{a: 0}, {l: 1, r: 0}], + ], +} + +{ + name: "the output node merges nested objects from branches", + graph: { + nodes: [ + {expression: "left", fields: {"res.l": "a"}}, + {expression: "right", fields: {"res.r": "b"}}, + ], + edges: ["input -> left -> output", "input -> right -> output"], + }, + cases: [ + [{a: 1, b: 2}, {res: {l: 1, r: 2}}], + [{a: "x", b: [1]}, {res: {l: "x", r: [1]}}], + [{a: 1}, {res: {l: 1, r: null}}], + ], +} + +{ + name: "the output node receives input and an expression branch", + graph: { + nodes: [{expression: "calc", fields: {y: "a + 1"}}], + edges: ["input -> output", "input -> calc -> output"], + }, + cases: [ + [{a: 1}, {a: 1, y: 2}], + [{a: 1, y: 100}, {a: 1, y: 100}, "question: on conflicting keys the output node keeps the branch whose edge is listed first (the request here), not the computed value"], + [{a: 0, z: "keep"}, {a: 0, y: 1, z: "keep"}], + ], +} + +// --------------------------------------------------------------------------- +// Schemas on input and output nodes validate the data at that point. +{ + name: "input schema accepts a valid request", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {age: {type: "number"}}, required: ["age"]}}, + {output: "response"}, + ], + }, + cases: [ + [{age: 20}, {age: 20}], + [{age: 0, other: "x"}, {age: 0, other: "x"}], + [{age: "20"}, "!error"], + [{}, "!error"], + [{age: true}, "!error"], + ], +} + +{ + name: "output schema validates the result", + graph: { + nodes: [ + {expression: "calc", fields: {total: "a * 2"}}, + {output: "response", schema: {type: "object", properties: {total: {type: "number", maximum: 100}}, required: ["total"]}}, + ], + }, + cases: [ + [{a: 1}, {total: 2}], + [{a: 50}, {total: 100}], + [{a: 51}, "!error"], + ], +} + +{ + name: "output schema rejects a missing required key", + graph: { + nodes: [ + {expression: "calc", fields: {total: "a"}}, + {output: "response", schema: {type: "object", required: ["total"]}}, + ], + }, + cases: [ + [{a: 1}, {total: 1}], + [{a: "x"}, {total: "x"}], + [{}, {}, "question: the schema sees {total: null} and passes, then the null key is dropped from the result"], + ], +} + +// --------------------------------------------------------------------------- +// Input data is not mutated across the graph: a downstream node sees the original request. +{ + name: "two consumers of the input see the same request", + graph: { + nodes: [ + {expression: "a", fields: {"req.extra": "1", fromA: "req.v"}}, + {expression: "b", fields: {fromB: "req", hasExtra: "req.extra != null"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{req: {v: 1}}, {req: {extra: 1}, fromA: 1, fromB: {v: 1}, hasExtra: false}], + [{req: {v: "x"}}, {req: {extra: 1}, fromA: "x", fromB: {v: "x"}, hasExtra: false}], + ], +} diff --git a/core/engine/tests/spec/graph/02-expression-node.json5 b/core/engine/tests/spec/graph/02-expression-node.json5 new file mode 100644 index 00000000..6a77df11 --- /dev/null +++ b/core/engine/tests/spec/graph/02-expression-node.json5 @@ -0,0 +1,631 @@ +// Expression nodes: each field is an expression evaluated against the node's input, in order. The +// node's output is an object of the field results; `$` holds the fields computed so far. + +// --------------------------------------------------------------------------- +// One field, every result type. +{ + name: "a single field copies an input value of any type", + graph: {nodes: [{expression: "calc", fields: {out: "v"}}]}, + cases: [ + [{v: 1}, {out: 1}], + [{v: -0.5}, {out: -0.5}], + [{v: "s"}, {out: "s"}], + [{v: ""}, {out: ""}], + [{v: true}, {out: true}], + [{v: false}, {out: false}], + [{v: [1, "a", null]}, {out: [1, "a", null]}], + [{v: {k: {n: 1}}}, {out: {k: {n: 1}}}], + [{v: {}}, {out: {}}], + [{v: []}, {out: []}], + ], +} + +{ + name: "literal results of every type", + graph: {nodes: [{expression: "calc", fields: { + n: "42", + f: "0.1 + 0.2", + s: "'text'", + t: "true", + l: "[1, 2, 3]", + o: "{a: 1, b: 'x'}", + e: "[]", + eo: "{}", + }}]}, + cases: [ + [{}, {n: 42, f: 0.3, s: "text", t: true, l: [1, 2, 3], o: {a: 1, b: "x"}, e: [], eo: {}}], + [{n: 1, s: "ignored"}, {n: 42, f: 0.3, s: "text", t: true, l: [1, 2, 3], o: {a: 1, b: "x"}, e: [], eo: {}}], + ], +} + +{ + name: "date results", + graph: {nodes: [{expression: "calc", fields: {day: "d(v)", year: "d(v).year()", text: "d(v).format('%Y-%m-%d')"}}]}, + cases: [ + [{v: "2024-01-01"}, {day: "2024-01-01T00:00:00Z", year: 2024, text: "2024-01-01"}], + [{v: "2023-12-31T23:59:59Z"}, {day: "2023-12-31T23:59:59Z", year: 2023, text: "2023-12-31"}], + [{v: date('2020-02-29')}, {day: "2020-02-29T00:00:00Z", year: 2020, text: "2020-02-29"}], + ], +} + +{ + name: "arithmetic on input fields", + graph: {nodes: [{expression: "calc", fields: {sum: "a + b", product: "a * b", ratio: "a / b"}}]}, + cases: [ + [{a: 6, b: 3}, {sum: 9, product: 18, ratio: 2}], + [{a: 1, b: 4}, {sum: 5, product: 4, ratio: 0.25}], + [{a: -2, b: 0.5}, {sum: -1.5, product: -1, ratio: -4}], + [{a: 0.1, b: 0.2}, {sum: 0.3, product: 0.02, ratio: 0.5}], + ], +} + +// --------------------------------------------------------------------------- +// Null and missing: a field reading a missing input is null; a null field is part of the node output +// but the final result drops top-level null keys (merge-patch). +{ + name: "a missing input reads as null and the null field is dropped", + graph: {nodes: [{expression: "calc", fields: {out: "missing", other: "1"}}]}, + cases: [ + [{}, {other: 1}], + [{x: 1}, {other: 1}], + [{missing: null}, {other: 1}], + [{missing: 0}, {out: 0, other: 1}], + [{missing: false}, {out: false, other: 1}], + ], +} + +{ + name: "a null field result is observable downstream", + graph: { + nodes: [ + {expression: "first", fields: {out: "missing", seen: "1"}}, + {expression: "second", fields: {isNull: "out == null", kind: "type(out)", seen: "seen"}}, + ], + }, + cases: [ + [{}, {isNull: true, kind: "null", seen: 1}], + [{missing: 2}, {isNull: false, kind: "number", seen: 1}], + [{missing: "x"}, {isNull: false, kind: "string", seen: 1}], + ], +} + +{ + name: "null-coalescing defaults for missing inputs", + graph: {nodes: [{expression: "calc", fields: {name: "name ?? 'anonymous'", age: "age ?? 0"}}]}, + cases: [ + [{}, {name: "anonymous", age: 0}], + [{name: "ann"}, {name: "ann", age: 0}], + [{name: null, age: 30}, {name: "anonymous", age: 30}], + [{name: "", age: 0}, {name: "", age: 0}], + ], +} + +{ + name: "a nested null field keeps its key", + graph: {nodes: [{expression: "calc", fields: {"o.v": "missing", "o.w": "1"}}]}, + cases: [ + [{}, {o: {v: null, w: 1}}], + [{missing: 3}, {o: {v: 3, w: 1}}], + ], +} + +{ + name: "an object result holding null keeps it", + graph: {nodes: [{expression: "calc", fields: {o: "{v: missing, w: 1}"}}]}, + cases: [ + [{}, {o: {v: null, w: 1}}], + [{missing: "x"}, {o: {v: "x", w: 1}}], + ], +} + +{ + name: "every field null produces an empty result", + graph: {nodes: [{expression: "calc", fields: {a: "x", b: "null", c: "y.z"}}]}, + cases: [ + [{}, {}], + [{x: null, y: null}, {}], + [{x: 1}, {a: 1}], + [{y: {z: false}}, {c: false}], + ], +} + +// --------------------------------------------------------------------------- +// Evaluation order: fields run top to bottom. `$` holds earlier fields; plain names read the input. +{ + name: "a later field reads an earlier one through $", + graph: {nodes: [{expression: "calc", fields: {a: "x + 1", b: "$.a * 2", c: "$.b - $.a"}}]}, + cases: [ + [{x: 1}, {a: 2, b: 4, c: 2}], + [{x: 0}, {a: 1, b: 2, c: 1}], + [{x: -1}, {a: 0, b: 0, c: 0}], + [{x: 0.5}, {a: 1.5, b: 3, c: 1.5}], + ], +} + +{ + name: "a plain name reads the input, not an earlier field", + graph: {nodes: [{expression: "calc", fields: {a: "100", fromInput: "a", fromDollar: "$.a"}}]}, + cases: [ + [{a: 5}, {a: 100, fromInput: 5, fromDollar: 100}], + [{a: "s"}, {a: 100, fromInput: "s", fromDollar: 100}], + [{}, {a: 100, fromDollar: 100}], + ], +} + +{ + name: "$ of a field not yet computed is null", + graph: {nodes: [{expression: "calc", fields: {early: "$.late ?? 'unset'", late: "1"}}]}, + cases: [ + [{}, {early: "unset", late: 1}], + [{late: 9}, {early: "unset", late: 1}], + ], +} + +{ + name: "$ before any field is computed", + graph: {nodes: [{expression: "calc", fields: {first: "$ == null", second: "type($)"}}]}, + cases: [ + [{}, {first: true, second: "object"}], + [{a: 1}, {first: true, second: "object"}], + ], +} + +{ + name: "$ is an object of the fields computed so far", + graph: {nodes: [{expression: "calc", fields: {a: "1", b: "'two'", names: "keys($)", c: "values($)"}}]}, + cases: [ + [{}, {a: 1, b: "two", names: ["a", "b"], c: [1, "two", ["a", "b"]]}], + [{a: 5}, {a: 1, b: "two", names: ["a", "b"], c: [1, "two", ["a", "b"]]}], + ], +} + +{ + name: "conditions over earlier fields", + graph: {nodes: [{expression: "calc", fields: { + total: "sum(map(items, #.price * #.qty))", + discount: "$.total > 100 ? 0.1 : 0", + due: "$.total * (1 - $.discount)", + }}]}, + cases: [ + [{items: [{price: 10, qty: 2}]}, {total: 20, discount: 0, due: 20}], + [{items: [{price: 50, qty: 3}]}, {total: 150, discount: 0.1, due: 135}], + [{items: []}, {total: 0, discount: 0, due: 0}], + [{items: [{price: 100, qty: 1}, {price: 1, qty: 1}]}, {total: 101, discount: 0.1, due: 90.9}], + ], +} + +{ + name: "array and closure results feed later fields", + graph: {nodes: [{expression: "calc", fields: {doubled: "map(xs, # * 2)", total: "sum($.doubled)", big: "filter($.doubled, # > 4)"}}]}, + cases: [ + [{xs: [1, 2, 3]}, {doubled: [2, 4, 6], total: 12, big: [6]}], + [{xs: []}, {doubled: [], total: 0, big: []}], + [{xs: [10]}, {doubled: [20], total: 20, big: [20]}], + ], +} + +{ + name: "a request key named $ is read when no field has been computed yet", + graph: {nodes: [{expression: "calc", fields: {a: "$.x", b: "$.a"}}]}, + cases: [ + [{x: 3}, {}], + [{"$": {x: 9}}, {a: 9, b: 9}, "question: before the first field, $ falls back to the request key \"$\""], + [{x: 3, "$": {x: 9}}, {a: 9, b: 9}, "question: before the first field, $ falls back to the request key \"$\""], + ], +} + +// --------------------------------------------------------------------------- +// Duplicate keys: the later field overwrites the earlier one, also in $. +{ + name: "a duplicate key overwrites the earlier value", + graph: {nodes: [{expression: "calc", fields: [["v", "1"], ["v", "2"]]}]}, + cases: [ + [{}, {v: 2}], + [{v: 0}, {v: 2}], + ], +} + +{ + name: "a duplicate key reads its own earlier value through $", + graph: {nodes: [{expression: "calc", fields: [["v", "x"], ["v", "$.v + 1"], ["v", "$.v * 10"]]}]}, + cases: [ + [{x: 1}, {v: 20}], + [{x: 0}, {v: 10}], + [{x: -1}, {v: 0}], + ], +} + +{ + name: "a duplicate key that turns null removes the value", + graph: {nodes: [{expression: "calc", fields: [["v", "1"], ["v", "missing"]]}]}, + cases: [ + [{}, {}], + [{missing: 3}, {v: 3}], + ], +} + +{ + name: "a duplicate key changes the type", + graph: {nodes: [{expression: "calc", fields: [["v", "[1]"], ["v", "'s'"], ["w", "type($.v)"]]}]}, + cases: [ + [{}, {v: "s", w: "string"}], + ], +} + +{ + name: "a duplicate key replacing an object with a scalar", + graph: {nodes: [{expression: "calc", fields: [["o", "{a: 1}"], ["o", "2"]]}]}, + cases: [ + [{}, {o: 2}], + ], +} + +{ + name: "a duplicate key replacing a scalar with an object", + graph: {nodes: [{expression: "calc", fields: [["o", "2"], ["o", "{a: 1}"]]}]}, + cases: [ + [{}, {o: {a: 1}}], + ], +} + +// --------------------------------------------------------------------------- +// Empty keys and empty expressions are skipped. +{ + name: "a field with an empty key is skipped", + graph: {nodes: [{expression: "calc", fields: [["", "1"], ["b", "2"]]}]}, + cases: [ + [{}, {b: 2}], + [{a: 1}, {b: 2}], + ], +} + +{ + name: "a field with an empty expression is skipped", + graph: {nodes: [{expression: "calc", fields: {a: "", b: "2"}}]}, + cases: [ + [{}, {b: 2}], + [{a: 1}, {b: 2}], + ], +} + +{ + name: "a node with no fields outputs an empty object", + graph: {nodes: [{expression: "calc", fields: {}}]}, + cases: [ + [{}, {}], + [{a: 1}, {}], + [{a: {b: 1}}, {}], + ], +} + +{ + name: "a node with no fields and pass-through returns the input", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {}}]}, + cases: [ + [{}, {}], + [{a: 1}, {a: 1}], + [{a: {b: 1}}, {a: {b: 1}}], + ], +} + +// --------------------------------------------------------------------------- +// Errors: one failing field fails the node and the graph; earlier successful fields do not survive. +{ + name: "a syntax error fails the graph", + graph: {nodes: [{expression: "calc", fields: {ok: "1", bad: "1 +"}}]}, + cases: [ + [{}, "!error: Failed to evaluate expression"], + [{a: 1}, "!error"], + ], +} + +{ + name: "a runtime type error fails the graph only for inputs that trigger it", + graph: {nodes: [{expression: "calc", fields: {ok: "1", total: "a + b"}}]}, + cases: [ + [{a: 1, b: 2}, {ok: 1, total: 3}], + [{a: "x", b: "y"}, {ok: 1, total: "xy"}], + [{a: "x", b: 1}, "!error"], + [{a: true, b: 1}, "!error"], + ], +} + +{ + name: "an error in the first field", + graph: {nodes: [{expression: "calc", fields: {bad: "a.b.", ok: "1"}}]}, + cases: [ + [{}, "!error"], + [{a: {b: 1}}, "!error"], + ], +} + +{ + name: "the error names the node", + graph: {nodes: [{expression: "pricing step", id: "pricing", fields: {bad: "unknownFunction(1)"}}]}, + cases: [ + [{}, "!error: pricing"], + ], +} + +{ + name: "an error in a downstream node fails the graph", + graph: { + nodes: [ + {expression: "first", fields: {v: "a"}}, + {expression: "second", fields: {w: "v * 2"}}, + ], + }, + cases: [ + [{a: 2}, {w: 4}], + [{a: 0}, {w: 0}], + [{a: "s"}, "!error"], + [{a: [1]}, "!error"], + ], +} + +{ + name: "an error in a later field after an earlier field with $", + graph: {nodes: [{expression: "calc", fields: {a: "x", b: "$.a + 1"}}]}, + cases: [ + [{x: 1}, {a: 1, b: 2}], + [{x: 0.5}, {a: 0.5, b: 1.5}], + [{x: "s"}, "!error"], + [{x: true}, "!error"], + [{x: [1]}, "!error"], + ], +} + +// --------------------------------------------------------------------------- +// Many fields. +{ + name: "thirty fields chained through $", + graph: {nodes: [{expression: "calc", fields: [ + ["f01", "x"], ["f02", "$.f01 + 1"], ["f03", "$.f02 + 1"], ["f04", "$.f03 + 1"], ["f05", "$.f04 + 1"], + ["f06", "$.f05 + 1"], ["f07", "$.f06 + 1"], ["f08", "$.f07 + 1"], ["f09", "$.f08 + 1"], ["f10", "$.f09 + 1"], + ["f11", "$.f10 + 1"], ["f12", "$.f11 + 1"], ["f13", "$.f12 + 1"], ["f14", "$.f13 + 1"], ["f15", "$.f14 + 1"], + ["f16", "$.f15 + 1"], ["f17", "$.f16 + 1"], ["f18", "$.f17 + 1"], ["f19", "$.f18 + 1"], ["f20", "$.f19 + 1"], + ["f21", "$.f20 + 1"], ["f22", "$.f21 + 1"], ["f23", "$.f22 + 1"], ["f24", "$.f23 + 1"], ["f25", "$.f24 + 1"], + ["f26", "$.f25 + 1"], ["f27", "$.f26 + 1"], ["f28", "$.f27 + 1"], ["f29", "$.f28 + 1"], ["f30", "$.f29 + 1"], + ]}]}, + cases: [ + [{x: 0}, {f01: 0, f02: 1, f03: 2, f04: 3, f05: 4, f06: 5, f07: 6, f08: 7, f09: 8, f10: 9, f11: 10, f12: 11, f13: 12, f14: 13, f15: 14, f16: 15, f17: 16, f18: 17, f19: 18, f20: 19, f21: 20, f22: 21, f23: 22, f24: 23, f25: 24, f26: 25, f27: 26, f28: 27, f29: 28, f30: 29}], + [{x: 100}, {f01: 100, f02: 101, f03: 102, f04: 103, f05: 104, f06: 105, f07: 106, f08: 107, f09: 108, f10: 109, f11: 110, f12: 111, f13: 112, f14: 113, f15: 114, f16: 115, f17: 116, f18: 117, f19: 118, f20: 119, f21: 120, f22: 121, f23: 122, f24: 123, f25: 124, f26: 125, f27: 126, f28: 127, f29: 128, f30: 129}], + [{x: 0.5}, {f01: 0.5, f02: 1.5, f03: 2.5, f04: 3.5, f05: 4.5, f06: 5.5, f07: 6.5, f08: 7.5, f09: 8.5, f10: 9.5, f11: 10.5, f12: 11.5, f13: 12.5, f14: 13.5, f15: 14.5, f16: 15.5, f17: 16.5, f18: 17.5, f19: 18.5, f20: 19.5, f21: 20.5, f22: 21.5, f23: 22.5, f24: 23.5, f25: 24.5, f26: 25.5, f27: 26.5, f28: 27.5, f29: 28.5, f30: 29.5}], + [{x: "s"}, "!error"], + ], +} + +{ + name: "twenty independent fields", + graph: {nodes: [{expression: "calc", fields: { + a: "x + 1", b: "x + 2", c: "x + 3", d: "x + 4", e: "x + 5", + f: "x * 1", g: "x * 2", h: "x * 3", i: "x * 4", j: "x * 5", + k: "x > 0", l: "x < 0", m: "x == 0", n: "string(x)", o: "x - 1", + p: "-x", q: "abs(x)", r: "x ^ 2", s: "[x]", t: "{v: x}", + }}]}, + cases: [ + [{x: 2}, {a: 3, b: 4, c: 5, d: 6, e: 7, f: 2, g: 4, h: 6, i: 8, j: 10, k: true, l: false, m: false, n: "2", o: 1, p: -2, q: 2, r: 4, s: [2], t: {v: 2}}], + [{x: 0}, {a: 1, b: 2, c: 3, d: 4, e: 5, f: 0, g: 0, h: 0, i: 0, j: 0, k: false, l: false, m: true, n: "0", o: -1, p: 0, q: 0, r: 0, s: [0], t: {v: 0}}], + [{x: -3}, {a: -2, b: -1, c: 0, d: 1, e: 2, f: -3, g: -6, h: -9, i: -12, j: -15, k: false, l: true, m: false, n: "-3", o: -4, p: 3, q: 3, r: 9, s: [-3], t: {v: -3}}], + ], +} + +// --------------------------------------------------------------------------- +// Pass-through off: the output holds only the fields. Pass-through on: the input merged with the fields. +{ + name: "without pass-through the input is not part of the output", + graph: {nodes: [{expression: "calc", fields: {y: "x * 2"}}]}, + cases: [ + [{x: 1}, {y: 2}], + [{x: 1, other: "keep?"}, {y: 2}], + [{x: 1, y: 100}, {y: 2}], + [{x: 1, nested: {a: 1}}, {y: 2}], + ], +} + +{ + name: "with pass-through the input is merged under the fields", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {y: "x * 2"}}]}, + cases: [ + [{x: 1}, {x: 1, y: 2}], + [{x: 1, other: "keep"}, {x: 1, other: "keep", y: 2}], + [{x: 1, y: 100}, {x: 1, y: 2}], + [{x: 1, nested: {a: 1}}, {x: 1, nested: {a: 1}, y: 2}], + [{x: 0, list: [1, 2]}, {x: 0, list: [1, 2], y: 0}], + ], +} + +{ + name: "pass-through with a field overwriting an input key", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {x: "x + 1"}}]}, + cases: [ + [{x: 1}, {x: 2}], + [{x: -1, y: "keep"}, {x: 0, y: "keep"}], + [{x: 0.5}, {x: 1.5}], + ], +} + +{ + name: "pass-through with an object field merges into the input object", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {o: "{b: 2}"}}]}, + cases: [ + [{o: {a: 1}}, {o: {a: 1, b: 2}}], + [{o: {b: 1, c: 3}}, {o: {b: 2, c: 3}}], + [{o: 5}, {o: {b: 2}}], + [{o: [1]}, {o: {b: 2}}], + [{}, {o: {b: 2}}], + ], +} + +{ + name: "pass-through with an array field replaces the input array", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {l: "[9]"}}]}, + cases: [ + [{l: [1, 2, 3]}, {l: [9]}], + [{l: {a: 1}}, {l: [9]}], + [{}, {l: [9]}], + ], +} + +{ + name: "pass-through with a null field deletes the input key", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {a: "null", b: "missing"}}]}, + cases: [ + [{a: 1, b: 2, c: 3}, {c: 3}, "question: a null field under pass-through removes the input key instead of keeping or nulling it"], + [{a: {x: 1}}, {}, "question: a null field under pass-through removes the input key instead of keeping or nulling it"], + [{c: 3}, {c: 3}], + [{b: 5, missing: 7}, {b: 7, missing: 7}], + ], +} + +{ + name: "pass-through with a nested null field deletes the nested input key", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {"n.x": "null"}}]}, + cases: [ + [{n: {x: 1, y: 2}}, {n: {y: 2}}, "question: a nested null field under pass-through removes the nested input key"], + [{n: {y: 2}}, {n: {y: 2}}], + [{}, {n: {x: null}}], + [{n: 5}, {n: {x: null}}], + ], +} + +{ + name: "pass-through keeps input keys of every type", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {seen: "true"}}]}, + cases: [ + [{s: "x", n: 1, b: false, l: [1], o: {k: 1}}, {s: "x", n: 1, b: false, l: [1], o: {k: 1}, seen: true}], + [{}, {seen: true}], + [{seen: false}, {seen: true}], + ], +} + +{ + name: "pass-through with a non-object request", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {y: "1"}}]}, + cases: [ + [5, {y: 1}], + [null, {y: 1}], + ["s", {y: 1}], + ], +} + +// --------------------------------------------------------------------------- +// Chains: the next node sees only the previous node's output; `$` does not carry over. +{ + name: "a second node sees only the first node's fields", + graph: { + nodes: [ + {expression: "first", fields: {y: "x + 1"}}, + {expression: "second", fields: {z: "y * 2", xSeen: "x"}}, + ], + }, + cases: [ + [{x: 1}, {z: 4}], + [{x: 0}, {z: 2}], + ], +} + +{ + name: "a second node sees the input when the first passes it through", + graph: { + nodes: [ + {expression: "first", passThrough: true, fields: {y: "x + 1"}}, + {expression: "second", fields: {z: "y * 2", xSeen: "x"}}, + ], + }, + cases: [ + [{x: 1}, {z: 4, xSeen: 1}], + [{x: 5}, {z: 12, xSeen: 5}], + ], +} + +{ + name: "$ does not carry over to the next node", + graph: { + nodes: [ + {expression: "first", fields: {y: "1"}}, + {expression: "second", fields: {fromDollar: "$.y", fromInput: "y"}}, + ], + }, + cases: [ + [{}, {fromInput: 1}], + [{y: 9}, {fromInput: 1}], + ], +} + +{ + name: "a downstream node reads an upstream node through $nodes", + graph: { + nodes: [ + {expression: "first", fields: {y: "x + 1"}}, + {expression: "second", fields: {z: "$nodes.first.y", x: "$nodes.input.x"}}, + ], + }, + cases: [ + [{x: 1}, {z: 2, x: 1}], + [{x: 10}, {z: 11, x: 10}], + [{x: -1}, {z: 0, x: -1}], + [{}, "!error"], + ], +} + +{ + name: "three chained nodes with pass-through accumulate", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {s1: "x + 1"}}, + {expression: "b", passThrough: true, fields: {s2: "s1 + 1"}}, + {expression: "c", passThrough: true, fields: {s3: "s2 + 1"}}, + ], + }, + cases: [ + [{x: 0}, {x: 0, s1: 1, s2: 2, s3: 3}], + [{x: 10, keep: "k"}, {x: 10, keep: "k", s1: 11, s2: 12, s3: 13}], + ], +} + +{ + name: "mixed pass-through in a chain", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {s1: "x + 1"}}, + {expression: "b", fields: {s2: "s1 + x"}}, + {expression: "c", passThrough: true, fields: {s3: "s2 * 2"}}, + ], + }, + cases: [ + [{x: 1}, {s2: 3, s3: 6}], + [{x: 2, keep: true}, {s2: 5, s3: 10}], + ], +} + +// --------------------------------------------------------------------------- +// String and boolean logic in fields. +{ + name: "string building over input fields", + graph: {nodes: [{expression: "calc", fields: {full: "first + ' ' + last", size: "len($.full)", upper: "upper($.full)"}}]}, + cases: [ + [{first: "ann", last: "lee"}, {full: "ann lee", size: 7, upper: "ANN LEE"}], + [{first: "", last: "x"}, {full: " x", size: 2, upper: " X"}], + ], +} + +{ + name: "boolean fields", + graph: {nodes: [{expression: "calc", fields: {adult: "age >= 18", senior: "age >= 65", both: "$.adult and not $.senior"}}]}, + cases: [ + [{age: 17}, {adult: false, senior: false, both: false}], + [{age: 18}, {adult: true, senior: false, both: true}], + [{age: 65}, {adult: true, senior: true, both: false}], + [{age: 40.5}, {adult: true, senior: false, both: true}], + ], +} + +{ + name: "template strings in fields", + graph: {nodes: [{expression: "calc", fields: {msg: "`hello ${name}`", n: "`${len(name)}`"}}]}, + cases: [ + [{name: "ann"}, {msg: "hello ann", n: "3"}], + [{name: ""}, {msg: "hello ", n: "0"}], + ], +} diff --git a/core/engine/tests/spec/graph/03-expression-paths.json5 b/core/engine/tests/spec/graph/03-expression-paths.json5 new file mode 100644 index 00000000..4a4cd3fc --- /dev/null +++ b/core/engine/tests/spec/graph/03-expression-paths.json5 @@ -0,0 +1,405 @@ +// Expression field keys are dotted paths: `a.b.c` writes into nested objects of the node output, +// creating them as needed. `$` mirrors the same nested shape for later fields. + +// --------------------------------------------------------------------------- +// Building nested objects. +{ + name: "a dotted key builds nested objects", + graph: {nodes: [{expression: "calc", fields: {"a.b.c": "v"}}]}, + cases: [ + [{v: 1}, {a: {b: {c: 1}}}], + [{v: "s"}, {a: {b: {c: "s"}}}], + [{v: [1, 2]}, {a: {b: {c: [1, 2]}}}], + [{v: {d: 1}}, {a: {b: {c: {d: 1}}}}], + [{v: false}, {a: {b: {c: false}}}], + [{}, {a: {b: {c: null}}}], + ], +} + +{ + name: "sibling dotted keys share their parent", + graph: {nodes: [{expression: "calc", fields: {"a.x": "1", "a.y": "2", "a.z.w": "3"}}]}, + cases: [ + [{}, {a: {x: 1, y: 2, z: {w: 3}}}], + [{a: {old: 1}}, {a: {x: 1, y: 2, z: {w: 3}}}], + ], +} + +{ + name: "dotted keys at different depths", + graph: {nodes: [{expression: "calc", fields: {"r": "1", "s.t": "2", "u.v.w": "3", "x.y.z.q": "4"}}]}, + cases: [ + [{}, {r: 1, s: {t: 2}, u: {v: {w: 3}}, x: {y: {z: {q: 4}}}}], + ], +} + +{ + name: "a ten level deep key", + graph: {nodes: [{expression: "calc", fields: {"a.b.c.d.e.f.g.h.i.j": "v", back: "$.a.b.c.d.e.f.g.h.i.j"}}]}, + cases: [ + [{v: 1}, {a: {b: {c: {d: {e: {f: {g: {h: {i: {j: 1}}}}}}}}}, back: 1}], + [{v: "deep"}, {a: {b: {c: {d: {e: {f: {g: {h: {i: {j: "deep"}}}}}}}}}, back: "deep"}], + ], +} + +{ + name: "$ mirrors the nested shape", + graph: {nodes: [{expression: "calc", fields: {"a.b": "v", leaf: "$.a.b", node: "$.a", flat: "$['a.b']"}}]}, + cases: [ + [{v: 1}, {a: {b: 1}, leaf: 1, node: {b: 1}}], + [{v: "x"}, {a: {b: "x"}, leaf: "x", node: {b: "x"}}], + [{v: [1]}, {a: {b: [1]}, leaf: [1], node: {b: [1]}}], + ], +} + +{ + name: "fields reading a nested branch built so far", + graph: {nodes: [{expression: "calc", fields: {"p.a": "1", "p.b": "2", total: "sum(values($.p))", "p.c": "3", count: "len(keys($.p))"}}]}, + cases: [ + [{}, {p: {a: 1, b: 2, c: 3}, total: 3, count: 3}], + [{p: {z: 9}}, {p: {a: 1, b: 2, c: 3}, total: 3, count: 3}], + ], +} + +// --------------------------------------------------------------------------- +// Writing into an object produced by an earlier field. +{ + name: "a dotted key extends an object literal written earlier", + graph: {nodes: [{expression: "calc", fields: {o: "{a: 1}", "o.b": "2"}}]}, + cases: [ + [{}, {o: {a: 1, b: 2}}], + [{o: {z: 1}}, {o: {a: 1, b: 2}}], + ], +} + +{ + name: "a dotted key overwrites a leaf of an object written earlier", + graph: {nodes: [{expression: "calc", fields: {o: "{a: 1, b: 1}", "o.a": "2"}}]}, + cases: [ + [{}, {o: {a: 2, b: 1}}], + ], +} + +{ + name: "a plain key after a dotted key replaces the whole branch", + graph: {nodes: [{expression: "calc", fields: {"o.a": "1", "o.b": "2", o: "{c: 3}"}}]}, + cases: [ + [{}, {o: {c: 3}}], + [{o: {a: 9}}, {o: {c: 3}}], + ], +} + +{ + name: "a plain scalar key after a dotted key replaces the branch", + graph: {nodes: [{expression: "calc", fields: {"o.a": "1", o: "5", read: "$.o"}}]}, + cases: [ + [{}, {o: 5, read: 5}], + ], +} + +// Writing a field into an object copied from the request must not change the request. +{ + name: "extending a copied request object does not change the request", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {copy: "inp", "copy.extra": "1"}}]}, + cases: [ + {input: {inp: {v: 1}}, output: {inp: {v: 1}, copy: {v: 1, extra: 1}}, note: "bug: the copy aliases the request object, so writing copy.extra also adds extra to the passed-through inp", engines: "walker and compiled row path alias the request; columnar gives the intended result"}, + [{inp: {}}, {inp: {}, copy: {extra: 1}}, "bug: the copy aliases the request object, so writing copy.extra also adds extra to the passed-through inp"], + {input: {inp: {extra: 0}}, output: {inp: {extra: 0}, copy: {extra: 1}}, note: "bug: the copy aliases the request object, so writing copy.extra also overwrites the passed-through inp.extra", engines: "walker and compiled row path alias the request; columnar gives the intended result"}, + ], +} + +{ + name: "extending a copied request object does not leak into sibling branches", + graph: { + nodes: [ + {expression: "writer", fields: {copy: "inp", "copy.extra": "1"}}, + {expression: "reader", fields: {seen: "$nodes.input.inp"}}, + ], + edges: ["input -> writer -> output", "input -> reader -> output"], + }, + cases: [ + {input: {inp: {v: 1}}, output: {copy: {v: 1, extra: 1}, seen: {v: 1}}, note: "bug: the copy aliases the request object, so the sibling branch sees inp.extra through $nodes", engines: "walker and compiled row path alias the request; columnar gives the intended result"}, + {input: {inp: {v: "x"}}, output: {copy: {v: "x", extra: 1}, seen: {v: "x"}}, note: "bug: the copy aliases the request object, so the sibling branch sees inp.extra through $nodes", engines: "walker and compiled row path alias the request; columnar gives the intended result"}, + ], +} + +{ + name: "extending a copied request object without pass-through", + graph: {nodes: [{expression: "calc", fields: {copy: "inp", "copy.extra": "1", original: "inp"}}]}, + cases: [ + [{inp: {v: 1}}, {copy: {v: 1, extra: 1}, original: {v: 1}}, "bug: the copy aliases the request object, so a later read of inp sees extra"], + [{inp: {}}, {copy: {extra: 1}, original: {}}, "bug: the copy aliases the request object, so a later read of inp sees extra"], + ], +} + +{ + name: "extending an object copied from an earlier field", + graph: {nodes: [{expression: "calc", fields: {first: "{a: 1}", second: "$.first", "second.b": "2"}}]}, + cases: [ + [{}, {first: {a: 1}, second: {a: 1, b: 2}}], + ], +} + +// --------------------------------------------------------------------------- +// Merging dotted output into input objects under pass-through. +{ + name: "pass-through merges a dotted key into an input object", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {"customer.tier": "customer.score > 50 ? 'gold' : 'silver'"}}]}, + cases: [ + [{customer: {score: 80, name: "ann"}}, {customer: {score: 80, name: "ann", tier: "gold"}}], + [{customer: {score: 10}}, {customer: {score: 10, tier: "silver"}}], + [{customer: {score: 10, tier: "old"}}, {customer: {score: 10, tier: "silver"}}], + [{customer: {score: 51}, other: [1]}, {customer: {score: 51, tier: "gold"}, other: [1]}], + ], +} + +{ + name: "pass-through merges deep dotted keys into nested input objects", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {"a.b.c": "1", "a.b.d": "2"}}]}, + cases: [ + [{a: {b: {x: 0}, y: 0}}, {a: {b: {x: 0, c: 1, d: 2}, y: 0}}], + [{a: {b: {c: 9}}}, {a: {b: {c: 1, d: 2}}}], + [{a: {}}, {a: {b: {c: 1, d: 2}}}], + [{}, {a: {b: {c: 1, d: 2}}}], + ], +} + +{ + name: "pass-through replaces a scalar input with the dotted object", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {"a.b": "1"}}]}, + cases: [ + [{a: 5}, {a: {b: 1}}], + [{a: "s"}, {a: {b: 1}}], + [{a: true}, {a: {b: 1}}], + [{a: [1, 2]}, {a: {b: 1}}], + [{a: null}, {a: {b: 1}}], + ], +} + +{ + name: "without pass-through a dotted key does not merge with the input", + graph: {nodes: [{expression: "calc", fields: {"customer.tier": "'gold'"}}]}, + cases: [ + [{customer: {score: 80, name: "ann"}}, {customer: {tier: "gold"}}], + [{}, {customer: {tier: "gold"}}], + [{customer: 1}, {customer: {tier: "gold"}}], + ], +} + +{ + name: "pass-through with a dotted key under an input array", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {"items.count": "len(items)"}}]}, + cases: [ + [{items: [1, 2, 3]}, {items: {count: 3}}, "question: a dotted key whose parent is an input array replaces the array with an object under pass-through"], + [{items: []}, {items: {count: 0}}, "question: a dotted key whose parent is an input array replaces the array with an object under pass-through"], + ], +} + +// --------------------------------------------------------------------------- +// Conflicting paths inside one node. +{ + name: "a dotted key under an earlier scalar field is dropped", + graph: {nodes: [{expression: "calc", fields: {a: "1", "a.b": "2", read: "$.a"}}]}, + cases: [ + [{}, {a: {b: 2}, read: {b: 2}}, "bug: writing a.b under a scalar a is silently ignored; it should replace a (as a later plain key does) or fail"], + [{a: {b: 0}}, {a: {b: 2}, read: {b: 2}}, "bug: writing a.b under a scalar a is silently ignored; it should replace a (as a later plain key does) or fail"], + ], +} + +{ + name: "a dotted key under an earlier string field is dropped", + graph: {nodes: [{expression: "calc", fields: {a: "'s'", "a.b.c": "2"}}]}, + cases: [ + [{}, {a: {b: {c: 2}}}, "bug: writing a.b.c under a string a is silently ignored"], + ], +} + +{ + name: "a dotted key under an earlier null field", + graph: {nodes: [{expression: "calc", fields: {a: "missing", "a.b": "2"}}]}, + cases: [ + [{}, {a: {b: 2}}, "bug: writing a.b under a null a is silently ignored"], + [{missing: {x: 1}}, {a: {x: 1, b: 2}}], + ], +} + +{ + name: "a dotted key under an earlier array field is dropped", + graph: {nodes: [{expression: "calc", fields: {items: "[1, 2]", "items.0": "9", "items.x": "8"}}]}, + cases: [ + [{}, {items: [1, 2]}, "question: a dotted key whose parent is an array is silently ignored, including numeric segments"], + ], +} + +{ + name: "a nested scalar blocks a deeper write", + graph: {nodes: [{expression: "calc", fields: {"a.b": "1", "a.b.c": "2", "a.d": "3"}}]}, + cases: [ + [{}, {a: {b: {c: 2}, d: 3}}, "bug: writing a.b.c under a scalar a.b is silently ignored"], + ], +} + +{ + name: "duplicate dotted keys overwrite", + graph: {nodes: [{expression: "calc", fields: [["a.b", "1"], ["a.b", "2"], ["a.c", "$.a.b + 1"]]}]}, + cases: [ + [{}, {a: {b: 2, c: 3}}], + ], +} + +{ + name: "a duplicate dotted key turned null", + graph: {nodes: [{expression: "calc", fields: [["a.b", "1"], ["a.b", "missing"], ["a.c", "2"]]}]}, + cases: [ + [{}, {a: {b: null, c: 2}}], + [{missing: 5}, {a: {b: 5, c: 2}}], + ], +} + +// --------------------------------------------------------------------------- +// Numeric segments create objects, never arrays. +{ + name: "numeric path segments create object keys", + graph: {nodes: [{expression: "calc", fields: {"items.0": "'a'", "items.1.name": "'b'"}}]}, + cases: [ + [{}, {items: {"0": "a", "1": {name: "b"}}}], + [{items: ["x", "y"]}, {items: {"0": "a", "1": {name: "b"}}}], + ], +} + +{ + name: "numeric keys under pass-through over an input array", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {"items.0": "'a'"}}]}, + cases: [ + [{items: ["x", "y"]}, {items: {"0": "a"}}, "question: a numeric segment does not index into an input array; the array is replaced by an object"], + [{}, {items: {"0": "a"}}], + ], +} + +{ + name: "reading numeric keys back", + graph: {nodes: [{expression: "calc", fields: {"m.0": "'zero'", back: "$.m['0']", missing: "$.m[0]"}}]}, + cases: [ + [{}, {m: {"0": "zero"}, back: "zero"}], + ], +} + +// --------------------------------------------------------------------------- +// The `$` root and keys with special characters. +{ + name: "a key named $ is an ordinary output key", + graph: {nodes: [{expression: "calc", fields: {"$": "v"}}]}, + cases: [ + [{v: 1}, {"$": 1}], + [{v: "s"}, {"$": "s"}], + [{v: {a: 1}}, {"$": {a: 1}}], + ], +} + +{ + name: "a key starting with $. nests under a $ key", + graph: {nodes: [{expression: "calc", fields: {"$.x": "v", read: "$['$'].x"}}]}, + cases: [ + [{v: 1}, {"$": {x: 1}, read: 1}], + [{v: "s"}, {"$": {x: "s"}, read: "s"}], + ], +} + +{ + name: "a key with spaces", + graph: {nodes: [{expression: "calc", fields: {"my key": "v", read: "$['my key']", "outer.inner key": "v"}}]}, + cases: [ + [{v: 1}, {"my key": 1, read: 1, outer: {"inner key": 1}}], + [{v: "x"}, {"my key": "x", read: "x", outer: {"inner key": "x"}}], + ], +} + +{ + name: "keys with dashes, unicode and symbols", + graph: {nodes: [{expression: "calc", fields: {"a-b": "1", "ключ": "2", "x@y": "3", "c[0]": "4", "q?": "5"}}]}, + cases: [ + [{}, {"a-b": 1, "ключ": 2, "x@y": 3, "c[0]": 4, "q?": 5}], + ], +} + +{ + name: "empty path segments", + graph: {nodes: [{expression: "calc", fields: {"a..b": "1", ".lead": "2", "trail.": "3"}}]}, + cases: [ + [{}, {a: {"": {b: 1}}, "": {lead: 2}, trail: {"": 3}}, "question: empty segments in a dotted key become empty-string keys rather than being rejected"], + ], +} + +{ + name: "a key that is a single dot", + graph: {nodes: [{expression: "calc", fields: {".": "1", ok: "2"}}]}, + cases: [ + [{}, {"": {"": 1}, ok: 2}, "question: a key \".\" becomes nested empty-string keys"], + ], +} + +{ + name: "a request key containing a dot is not a path", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {"a.b": "2", flat: "$['a.b']"}}]}, + cases: [ + [{"a.b": 1}, {"a.b": 1, a: {b: 2}}], + [{"a.b": 1, a: {c: 3}}, {"a.b": 1, a: {b: 2, c: 3}}], + ], +} + +{ + name: "a request with a dotted key read through member access", + graph: {nodes: [{expression: "calc", fields: {member: "a.b", bracket: "$nodes.input['a.b']"}}]}, + cases: [ + [{"a.b": 1}, {bracket: 1}], + [{"a.b": 1, a: {b: 2}}, {member: 2, bracket: 1}], + [{a: {b: 3}}, {member: 3}], + ], +} + +// --------------------------------------------------------------------------- +// Dotted keys across nodes. +{ + name: "a downstream node reads nested output of an upstream node", + graph: { + nodes: [ + {expression: "first", fields: {"res.a": "x", "res.b": "x * 2"}}, + {expression: "second", fields: {"out.sum": "res.a + res.b", "out.keys": "keys(res)"}}, + ], + }, + cases: [ + [{x: 1}, {out: {sum: 3, keys: ["a", "b"]}}], + [{x: 0}, {out: {sum: 0, keys: ["a", "b"]}}], + [{x: -2}, {out: {sum: -6, keys: ["a", "b"]}}], + ], +} + +{ + name: "chained pass-through nodes each add to the same nested object", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {"res.a": "1"}}, + {expression: "b", passThrough: true, fields: {"res.b": "res.a + 1"}}, + {expression: "c", passThrough: true, fields: {"res.c": "res.b + 1"}}, + ], + }, + cases: [ + [{}, {res: {a: 1, b: 2, c: 3}}], + [{res: {z: 0}, k: 1}, {res: {z: 0, a: 1, b: 2, c: 3}, k: 1}], + ], +} + +{ + name: "parallel branches write disjoint leaves of the same object", + graph: { + nodes: [ + {expression: "left", fields: {"res.left": "x"}}, + {expression: "right", fields: {"res.right": "x * 10"}}, + ], + edges: ["input -> left -> output", "input -> right -> output"], + }, + cases: [ + [{x: 1}, {res: {left: 1, right: 10}}], + [{x: 0}, {res: {left: 0, right: 0}}], + ], +} diff --git a/core/engine/tests/spec/graph/04-table-first-hit.json5 b/core/engine/tests/spec/graph/04-table-first-hit.json5 new file mode 100644 index 00000000..c673c335 --- /dev/null +++ b/core/engine/tests/spec/graph/04-table-first-hit.json5 @@ -0,0 +1,855 @@ +// Decision tables, first hit policy. +// +// A first-hit table evaluates rules top to bottom and returns the outputs of the first rule +// whose input cells all pass. An empty input cell matches anything. Output cells are standard +// expressions; an empty output cell leaves its field out. When no rule matches, the node +// produces null, which the output node turns into an empty object. + +// --- Rule order --------------------------------------------------------------------------- + +{ + name: "first hit: the first matching rule wins even when later rules also match", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 80", "'B'"], + [">= 70", "'C'"], + ["", "'F'"], + ]}, + ], + }, + cases: [ + [{score: 95}, {grade: "A"}], + [{score: 90}, {grade: "A"}], + [{score: 89.99}, {grade: "B"}], + [{score: 80}, {grade: "B"}], + [{score: 70}, {grade: "C"}], + [{score: 69}, {grade: "F"}], + [{score: -5}, {grade: "F"}], + [{}, {grade: "F"}], + ], +} + +{ + name: "first hit: a catch-all placed first shadows every later rule", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["grade"], rules: [ + ["", "'any'"], + [">= 90", "'A'"], + ]}, + ], + }, + cases: [ + [{score: 95}, {grade: "any"}], + [{score: 1}, {grade: "any"}], + [{score: null}, {grade: "any"}], + [{}, {grade: "any"}], + ], +} + +{ + name: "first hit: overlapping ranges resolve by order, not by specificity", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["band"], rules: [ + ["[0..100]", "'wide'"], + ["[40..60]", "'narrow'"], + ]}, + ], + }, + cases: [ + [{n: 50}, {band: "wide"}], + [{n: 0}, {band: "wide"}], + [{n: 100}, {band: "wide"}], + [{n: 101}, {}], + ], +} + +// --- No match ------------------------------------------------------------------------------- + +{ + name: "first hit: no matching rule yields an empty result", + graph: { + nodes: [ + {table: "t", inputs: ["age"], outputs: ["tier"], rules: [ + ["> 18", "'adult'"], + ["< 5", "'toddler'"], + ]}, + ], + }, + cases: [ + [{age: 20}, {tier: "adult"}], + [{age: 3}, {tier: "toddler"}], + [{age: 10}, {}], + [{age: 18}, {}], + [{age: 5}, {}], + ], +} + +{ + name: "first hit: a table with no rules yields an empty result", + graph: { + nodes: [{table: "t", inputs: ["a"], outputs: ["b"], rules: []}], + }, + cases: [ + [{a: 1}, {}], + [{}, {}], + [{a: "x", b: 2}, {}], + ], +} + +{ + name: "first hit: no match with passThrough keeps the input unchanged", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["age"], outputs: ["tier"], rules: [ + ["> 18", "'adult'"], + ]}, + ], + }, + cases: [ + [{age: 20}, {age: 20, tier: "adult"}], + [{age: 10}, {age: 10}], + [{age: 10, tier: "old"}, {age: 10, tier: "old"}], + [{age: 30, tier: "old"}, {age: 30, tier: "adult"}], + [{}, {}], + ], +} + +{ + name: "first hit: no match with outputPath writes null under the path, which the merge drops", + graph: { + nodes: [ + {table: "t", outputPath: "result", inputs: ["age"], outputs: ["tier"], rules: [ + ["> 18", "'adult'"], + ]}, + ], + }, + cases: [ + [{age: 20}, {result: {tier: "adult"}}], + [{age: 10}, {}], + ], +} + +{ + name: "first hit: no match feeding a downstream expression gives it an empty input", + graph: { + nodes: [ + {table: "t", inputs: ["age"], outputs: ["tier"], rules: [["> 18", "'adult'"]]}, + {expression: "e", fields: {hasTier: "tier != null", tierOr: "tier ?? 'none'", ageSeen: "age ?? 'gone'"}}, + ], + }, + cases: [ + [{age: 20}, {hasTier: true, tierOr: "adult", ageSeen: "gone"}], + [{age: 10}, {hasTier: false, tierOr: "none", ageSeen: "gone"}], + ], +} + +// --- Wildcards ------------------------------------------------------------------------------ + +{ + name: "first hit: empty input cells are wildcards per column", + graph: { + nodes: [ + {table: "t", inputs: ["country", "age"], outputs: ["rate"], rules: [ + ["'US'", "> 65", "1"], + ["'US'", "", "2"], + ["", "> 65", "3"], + ["", "", "4"], + ]}, + ], + }, + cases: [ + [{country: "US", age: 70}, {rate: 1}], + [{country: "US", age: 30}, {rate: 2}], + [{country: "DE", age: 70}, {rate: 3}], + [{country: "DE", age: 30}, {rate: 4}], + [{country: "US"}, {rate: 2}], + [{age: 70}, {rate: 3}], + [{}, {rate: 4}], + ], +} + +{ + name: "first hit: a wildcard matches null, missing and values of every type", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["hit"], rules: [["", "true"]]}, + ], + }, + cases: [ + [{v: 1}, {hit: true}], + [{v: "s"}, {hit: true}], + [{v: false}, {hit: true}], + [{v: null}, {hit: true}], + [{v: [1, 2]}, {hit: true}], + [{v: {a: 1}}, {hit: true}], + [{}, {hit: true}], + ], +} + +{ + name: "first hit: a rule whose input cells are all empty always matches", + graph: { + nodes: [ + {table: "t", inputs: ["a", "b", "c"], outputs: ["r"], rules: [ + ["", "", "", "'all-empty'"], + ["1", "2", "3", "'specific'"], + ]}, + ], + }, + cases: [ + [{a: 1, b: 2, c: 3}, {r: "all-empty"}], + [{}, {r: "all-empty"}], + [{a: "x"}, {r: "all-empty"}], + ], +} + +{ + name: "first hit: a table with no input columns matches its first rule", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "b"], rules: [ + ["1", "'one'"], + ["2", "'two'"], + ]}, + ], + }, + cases: [ + [{}, {a: 1, b: "one"}], + [{a: 99}, {a: 1, b: "one"}], + ], +} + +// --- Multiple input columns ----------------------------------------------------------------- + +{ + name: "first hit: all input cells of a rule must pass (conjunction)", + graph: { + nodes: [ + {table: "t", inputs: ["tier", "amount", "active"], outputs: ["discount"], rules: [ + ["'gold'", "> 1000", "true", "0.2"], + ["'gold'", "", "true", "0.1"], + ["'silver'", "> 1000", "true", "0.05"], + ["", "", "false", "0"], + ]}, + ], + }, + cases: [ + [{tier: "gold", amount: 2000, active: true}, {discount: 0.2}], + [{tier: "gold", amount: 500, active: true}, {discount: 0.1}], + [{tier: "silver", amount: 2000, active: true}, {discount: 0.05}], + [{tier: "silver", amount: 500, active: true}, {}], + [{tier: "gold", amount: 2000, active: false}, {discount: 0}], + [{tier: "bronze", amount: 1, active: false}, {discount: 0}], + [{tier: "gold", amount: 2000}, {}], + ], +} + +{ + name: "first hit: the same field may appear in two input columns", + graph: { + nodes: [ + {table: "t", inputs: ["n", "n"], outputs: ["band"], rules: [ + [">= 10", "< 20", "'teens'"], + [">= 20", "< 30", "'twenties'"], + ["", "", "'other'"], + ]}, + ], + }, + cases: [ + [{n: 15}, {band: "teens"}], + [{n: 10}, {band: "teens"}], + [{n: 20}, {band: "twenties"}], + [{n: 30}, {band: "other"}], + [{n: 5}, {band: "other"}], + ], +} + +{ + name: "first hit: nested dotted input fields", + graph: { + nodes: [ + {table: "t", inputs: ["customer.address.country", "order.total"], outputs: ["shipping"], rules: [ + ["'US'", "> 100", "0"], + ["'US'", "", "10"], + ["", "", "25"], + ]}, + ], + }, + cases: [ + [{customer: {address: {country: "US"}}, order: {total: 150}}, {shipping: 0}], + [{customer: {address: {country: "US"}}, order: {total: 50}}, {shipping: 10}], + [{customer: {address: {country: "FR"}}, order: {total: 150}}, {shipping: 25}], + [{customer: {address: {}}, order: {total: 150}}, {shipping: 25}], + [{customer: {}}, {shipping: 25}], + [{customer: null}, {shipping: 25}], + [{}, {shipping: 25}], + ], +} + +{ + name: "first hit: indexed input field into an array", + graph: { + nodes: [ + {table: "t", inputs: ["items[0].sku"], outputs: ["first"], rules: [ + ["'A'", "'alpha'"], + ["'B'", "'beta'"], + ["", "'unknown'"], + ]}, + ], + }, + cases: [ + [{items: [{sku: "A"}, {sku: "B"}]}, {first: "alpha"}], + [{items: [{sku: "B"}]}, {first: "beta"}], + [{items: []}, {first: "unknown"}], + [{}, {first: "unknown"}], + ], +} + +// --- Outputs ---------------------------------------------------------------------------------- + +{ + name: "first hit: several output columns, empty output cells are omitted", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["a", "b", "c"], rules: [ + ["'full'", "1", "2", "3"], + ["'partial'", "1", "", "3"], + ["'none'", "", "", ""], + ]}, + ], + }, + cases: [ + [{kind: "full"}, {a: 1, b: 2, c: 3}], + [{kind: "partial"}, {a: 1, c: 3}], + [{kind: "none"}, {}], + [{kind: "other"}, {}], + ], +} + +{ + name: "first hit: a matched rule with only empty outputs is still a hit (stops the search)", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["x"], outputs: ["y"], rules: [ + ["> 0", ""], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{x: 1}, {x: 1}], + [{x: -1}, {x: -1, y: "fallback"}], + ], +} + +{ + name: "first hit: dotted output fields build nested objects", + graph: { + nodes: [ + {table: "t", inputs: ["plan"], outputs: ["limits.users", "limits.storage.gb", "meta.plan"], rules: [ + ["'pro'", "50", "100", "plan"], + ["", "5", "1", "'free'"], + ]}, + ], + }, + cases: [ + [{plan: "pro"}, {limits: {users: 50, storage: {gb: 100}}, meta: {plan: "pro"}}], + [{plan: "basic"}, {limits: {users: 5, storage: {gb: 1}}, meta: {plan: "free"}}], + [{}, {limits: {users: 5, storage: {gb: 1}}, meta: {plan: "free"}}], + ], +} + +{ + name: "first hit: two output columns writing into the same parent object merge", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["r.a", "r.b", "r.c.d"], rules: [ + ["1", "'x'", "true"], + ]}, + ], + }, + cases: [ + [{}, {r: {a: 1, b: "x", c: {d: true}}}], + [{r: {z: 1}}, {r: {a: 1, b: "x", c: {d: true}}}], + ], +} + +{ + name: "first hit: output values of every type", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["v"], rules: [ + ["'num'", "1.50"], + ["'neg'", "-3"], + ["'str'", "'text'"], + ["'dq'", "\"double\""], + ["'bool'", "false"], + ["'null'", "null"], + ["'arr'", "[1, 'a', true]"], + ["'obj'", "{x: 1, y: {z: 'deep'}}"], + ["'empty'", "''"], + ]}, + ], + }, + cases: [ + [{k: "num"}, {v: 1.5}], + [{k: "neg"}, {v: -3}], + [{k: "str"}, {v: "text"}], + [{k: "dq"}, {v: "double"}], + [{k: "bool"}, {v: false}], + [{k: "null"}, {}], + [{k: "arr"}, {v: [1, "a", true]}], + [{k: "obj"}, {v: {x: 1, y: {z: "deep"}}}], + [{k: "empty"}, {v: ""}], + ], +} + +{ + name: "first hit: a null output cell is a merge-patch delete, it removes the key from the pass-through input", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["v"], rules: [["null"]]}, + ], + }, + cases: [ + [{}, {}], + [{v: 5}, {}], + [{v: 5, w: 1}, {w: 1}], + ], +} + +{ + name: "first hit: decimals in outputs keep exact precision", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["", "n * 0.1 + 0.2"], + ]}, + ], + }, + cases: [ + [{n: 1}, {r: 0.3}], + [{n: 3}, {r: 0.5}], + [{n: 0.1}, {r: 0.21}], + [{n: 12345678901234567890}, {r: 1234567890123456789.2}], + ], +} + +// --- Cell value kinds ------------------------------------------------------------------------ + +{ + name: "first hit: numeric equality cells, integer and decimal forms are equal", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["1", "'one'"], + ["2.5", "'two and a half'"], + ["-1", "'minus one'"], + ["0", "'zero'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {r: "one"}], + [{n: 1.0}, {r: "one"}], + [{n: 2.50}, {r: "two and a half"}], + [{n: -1}, {r: "minus one"}], + [{n: 0}, {r: "zero"}], + [{n: -0}, {r: "zero"}], + [{n: 3}, {}], + [{n: "1"}, {}], + [{n: true}, {}], + ], +} + +{ + name: "first hit: string cells are case sensitive and exact", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["'Gold'", "1"], + ["\"silver\"", "2"], + ["''", "3"], + ["' padded '", "4"], + ]}, + ], + }, + cases: [ + [{s: "Gold"}, {r: 1}], + [{s: "gold"}, {}], + [{s: "silver"}, {r: 2}], + [{s: ""}, {r: 3}], + [{s: " padded "}, {r: 4}], + [{s: "padded"}, {}], + [{s: 1}, {}], + [{}, {}], + ], +} + +{ + name: "first hit: boolean cells", + graph: { + nodes: [ + {table: "t", inputs: ["flag"], outputs: ["r"], rules: [ + ["true", "'yes'"], + ["false", "'no'"], + ["", "'unknown'"], + ]}, + ], + }, + cases: [ + [{flag: true}, {r: "yes"}], + [{flag: false}, {r: "no"}], + [{flag: null}, {r: "unknown"}], + [{flag: "true"}, {r: "unknown"}], + [{flag: 1}, {r: "unknown"}], + [{flag: 0}, {r: "unknown"}], + [{}, {r: "unknown"}], + ], +} + +{ + name: "first hit: date cells compare date-string inputs through d()", + graph: { + nodes: [ + {table: "t", inputs: ["d"], outputs: ["era"], rules: [ + ["d($) < d('2000-01-01')", "'old'"], + ["d($) >= d('2000-01-01') and d($) <= d('2020-12-31')", "'mid'"], + ["> d('2020-12-31')", "'new'"], + ]}, + ], + }, + cases: [ + [{d: "1999-12-31"}, {era: "old"}], + [{d: "2000-01-01"}, {era: "mid"}], + [{d: "2010-06-15"}, {era: "mid"}], + [{d: "2020-12-31"}, {era: "mid"}], + [{d: "2021-01-01"}, {era: "new"}], + [{d: "2021-01-01T08:00:00Z"}, {era: "new"}], + [{d: date('2010-06-15')}, {era: "mid"}], + [{d: null}, {era: "old"}, "question: d(null) is an invalid date that orders before every valid date, so a null input lands in the first `<` band instead of matching nothing"], + ], +} + +{ + name: "first hit: date cells using d() and a reference to $", + graph: { + nodes: [ + {table: "t", inputs: ["since"], outputs: ["recent"], rules: [ + ["d($).isAfter(d('2025-01-01'))", "true"], + ["", "false"], + ]}, + ], + }, + cases: [ + [{since: "2025-03-01"}, {recent: true}], + [{since: "2024-12-31"}, {recent: false}], + [{since: "2025-01-01"}, {recent: false}], + ], +} + +{ + name: "first hit: number cell against a numeric string input does not coerce", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["> 5", "'big'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{n: 6}, {r: "big"}], + [{n: "6"}, {r: "other"}], + [{n: null}, {r: "other"}], + [{n: [6]}, {r: "other"}], + ], +} + +// --- Large tables (eight or more rules use an equality index for some columns) -------------- + +{ + name: "first hit: large enum table matches the right row", + graph: { + nodes: [ + {table: "t", inputs: ["state"], outputs: ["region"], rules: [ + ["'CA'", "'west'"], + ["'OR'", "'west'"], + ["'WA'", "'west'"], + ["'NY'", "'east'"], + ["'NJ'", "'east'"], + ["'MA'", "'east'"], + ["'TX'", "'south'"], + ["'FL'", "'south'"], + ["'IL', 'OH'", "'midwest'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{state: "CA"}, {region: "west"}], + [{state: "WA"}, {region: "west"}], + [{state: "MA"}, {region: "east"}], + [{state: "FL"}, {region: "south"}], + [{state: "IL"}, {region: "midwest"}], + [{state: "OH"}, {region: "midwest"}], + [{state: "ZZ"}, {region: "other"}], + [{state: "ca"}, {region: "other"}], + [{state: null}, {region: "other"}], + [{state: 5}, {region: "other"}], + [{}, {region: "other"}], + ], +} + +{ + name: "first hit: large table keeps first-hit order when an earlier non-equality rule also matches", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["r"], rules: [ + ["1", "'r0'"], + ["2", "'r1'"], + ["> 100", "'r2-range'"], + ["3", "'r3'"], + ["150", "'r4-shadowed'"], + ["4", "'r5'"], + ["5", "'r6'"], + ["6", "'r7'"], + ["200", "'r8-shadowed'"], + ["", "'default'"], + ]}, + ], + }, + cases: [ + [{code: 1}, {r: "r0"}], + [{code: 3}, {r: "r3"}], + [{code: 150}, {r: "r2-range"}], + [{code: 200}, {r: "r2-range"}], + [{code: 6}, {r: "r7"}], + [{code: 6.0}, {r: "r7"}], + [{code: 7}, {r: "default"}], + [{code: "3"}, {r: "default"}], + [{}, {r: "default"}], + ], +} + +{ + name: "first hit: large table with two indexed columns intersects them", + graph: { + nodes: [ + {table: "t", inputs: ["country", "vip"], outputs: ["fee"], rules: [ + ["'US'", "true", "0"], + ["'US'", "false", "5"], + ["'DE'", "true", "1"], + ["'DE'", "false", "6"], + ["'FR'", "true", "2"], + ["'FR'", "false", "7"], + ["'JP'", "", "8"], + ["", "true", "9"], + ["", "", "10"], + ]}, + ], + }, + cases: [ + [{country: "US", vip: true}, {fee: 0}], + [{country: "US", vip: false}, {fee: 5}], + [{country: "DE", vip: false}, {fee: 6}], + [{country: "FR", vip: true}, {fee: 2}], + [{country: "JP", vip: true}, {fee: 8}], + [{country: "JP"}, {fee: 8}], + [{country: "IT", vip: true}, {fee: 9}], + [{country: "IT", vip: false}, {fee: 10}], + [{country: "US"}, {fee: 10}], + [{vip: true}, {fee: 9}], + [{}, {fee: 10}], + ], +} + +{ + name: "first hit: large boolean and numeric table with mixed cell shapes", + graph: { + nodes: [ + {table: "t", inputs: ["n", "b"], outputs: ["r"], rules: [ + ["1, 2", "true", "'a'"], + ["3", "true", "'b'"], + ["[4..6]", "", "'c'"], + ["7", "false", "'d'"], + ["8", "", "'e'"], + ["!= 9", "false", "'f'"], + ["9", "", "'g'"], + ["10", "true", "'h'"], + ]}, + ], + }, + cases: [ + [{n: 1, b: true}, {r: "a"}], + [{n: 2, b: true}, {r: "a"}], + [{n: 2, b: false}, {r: "f"}], + [{n: 3, b: true}, {r: "b"}], + [{n: 5, b: false}, {r: "c"}], + [{n: 4.5}, {r: "c"}], + [{n: 7, b: false}, {r: "d"}], + [{n: 8, b: true}, {r: "e"}], + [{n: 9, b: false}, {r: "g"}], + [{n: 10, b: true}, {r: "h"}], + [{n: 10, b: false}, {r: "f"}], + [{n: 11, b: true}, {}], + [{n: null, b: false}, {r: "f"}], + ], +} + +{ + name: "first hit: a large table with no matching rule yields an empty result", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["v"], rules: [ + ["'a'", "1"], ["'b'", "2"], ["'c'", "3"], ["'d'", "4"], + ["'e'", "5"], ["'f'", "6"], ["'g'", "7"], ["'h'", "8"], + ["'i'", "9"], ["'j'", "10"], ["'k'", "11"], ["'l'", "12"], + ]}, + ], + }, + cases: [ + [{k: "a"}, {v: 1}], + [{k: "h"}, {v: 8}], + [{k: "l"}, {v: 12}], + [{k: "m"}, {}], + [{k: ""}, {}], + [{}, {}], + ], +} + +// --- Interaction with other nodes ---------------------------------------------------------- + +{ + name: "first hit: reads values computed by an upstream expression node", + graph: { + nodes: [ + {expression: "calc", passThrough: true, fields: {bmi: "weight / (height * height)"}}, + {table: "t", inputs: ["bmi"], outputs: ["category"], rules: [ + ["< 18.5", "'under'"], + ["[18.5..25)", "'normal'"], + ["[25..30)", "'over'"], + ["", "'obese'"], + ]}, + ], + }, + cases: [ + [{weight: 50, height: 1.8}, {category: "under"}], + [{weight: 70, height: 1.75}, {category: "normal"}], + [{weight: 85, height: 1.75}, {category: "over"}], + [{weight: 120, height: 1.7}, {category: "obese"}], + ], +} + +{ + name: "first hit: two tables in sequence, the second reads the first's output", + graph: { + nodes: [ + {table: "risk", passThrough: true, inputs: ["score"], outputs: ["risk"], rules: [ + ["< 500", "'high'"], + ["< 700", "'medium'"], + ["", "'low'"], + ]}, + {table: "rate", inputs: ["risk", "amount"], outputs: ["rate"], rules: [ + ["'high'", "", "0.15"], + ["'medium'", "> 10000", "0.09"], + ["'medium'", "", "0.1"], + ["'low'", "", "0.05"], + ]}, + ], + }, + cases: [ + [{score: 400, amount: 1}, {rate: 0.15}], + [{score: 600, amount: 20000}, {rate: 0.09}], + [{score: 600, amount: 100}, {rate: 0.1}], + [{score: 800}, {rate: 0.05}], + ], +} + +{ + name: "first hit: inputField scopes the table to a nested object", + graph: { + nodes: [ + {table: "t", inputField: "applicant", inputs: ["age", "income"], outputs: ["eligible"], rules: [ + [">= 18", ">= 30000", "true"], + ["", "", "false"], + ]}, + ], + }, + cases: [ + [{applicant: {age: 30, income: 50000}}, {eligible: true}], + [{applicant: {age: 17, income: 50000}}, {eligible: false}], + [{applicant: {age: 30}}, {eligible: false}], + [{age: 30, income: 50000, applicant: {}}, {eligible: false}], + ], +} + +{ + name: "first hit: loop execution mode runs the table per array element", + graph: { + nodes: [ + {table: "t", inputField: "items", executionMode: "loop", outputPath: "results", inputs: ["qty"], outputs: ["size"], rules: [ + ["> 10", "'bulk'"], + ["", "'single'"], + ]}, + ], + }, + cases: [ + [{items: [{qty: 20}, {qty: 1}]}, {results: [{size: "bulk"}, {size: "single"}]}], + [{items: []}, {results: []}], + [{items: [{qty: 11}]}, {results: [{size: "bulk"}]}], + [{items: "nope"}, "!error"], + ], +} + +{ + name: "first hit: loop mode where some elements match no rule", + graph: { + nodes: [ + {table: "t", inputField: "items", executionMode: "loop", outputPath: "results", inputs: ["qty"], outputs: ["size"], rules: [ + ["> 10", "'bulk'"], + ]}, + ], + }, + cases: [ + [{items: [{qty: 20}, {qty: 1}]}, {results: [{size: "bulk"}, null]}, "question: unmatched elements in loop mode become null entries rather than {} or being dropped"], + [{items: [{qty: 1}]}, {results: [null]}, "question: unmatched elements in loop mode become null entries rather than {} or being dropped"], + ], +} + +{ + name: "first hit: two tables in parallel merge their outputs at the output node", + graph: { + nodes: [ + {table: "a", inputs: ["x"], outputs: ["fromA"], rules: [["> 0", "'pos'"], ["", "'nonpos'"]]}, + {table: "b", inputs: ["x"], outputs: ["fromB"], rules: [["< 0", "'neg'"]]}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{x: 1}, {fromA: "pos"}], + [{x: -1}, {fromA: "nonpos", fromB: "neg"}], + [{x: 0}, {fromA: "nonpos"}], + ], +} + +{ + name: "first hit: table output overrides the same key when merged with passThrough", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["status"], outputs: ["status", "changed"], rules: [ + ["'new'", "'open'", "true"], + ["", "status", "false"], + ]}, + ], + }, + cases: [ + [{status: "new"}, {status: "open", changed: true}], + [{status: "done"}, {status: "done", changed: false}], + [{status: "new", other: 1}, {status: "open", changed: true, other: 1}], + ], +} diff --git a/core/engine/tests/spec/graph/05-table-collect.json5 b/core/engine/tests/spec/graph/05-table-collect.json5 new file mode 100644 index 00000000..58018384 --- /dev/null +++ b/core/engine/tests/spec/graph/05-table-collect.json5 @@ -0,0 +1,642 @@ +// Decision tables, collect hit policy, and per-column `[]` collect outputs. +// +// A collect table evaluates every rule and returns an array with one object per matching rule, +// in rule order. No match gives an empty array. A first-hit table whose output field ends in +// `[]` keeps first-hit semantics for its plain columns and gathers that column's value from +// every matching rule into an array; with no matching rule the `[]` columns are empty arrays. + +// --- Collect basics ------------------------------------------------------------------------- + +{ + name: "collect: every matching rule contributes one object, in rule order", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["amount"], outputs: ["flag"], rules: [ + ["> 1000", "'large'"], + ["> 100", "'medium'"], + ["> 0", "'positive'"], + ["< 0", "'negative'"], + ]}, + ], + }, + cases: [ + [{amount: 5000}, [{flag: "large"}, {flag: "medium"}, {flag: "positive"}]], + [{amount: 500}, [{flag: "medium"}, {flag: "positive"}]], + [{amount: 1}, [{flag: "positive"}]], + [{amount: -1}, [{flag: "negative"}]], + [{amount: 0}, []], + ], +} + +{ + name: "collect: no matching rule yields an empty array", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["y"], rules: [ + ["1", "'one'"], + ["2", "'two'"], + ]}, + ], + }, + cases: [ + [{x: 3}, []], + [{x: "1"}, []], + [{x: null}, []], + [{}, []], + [{x: 2}, [{y: "two"}]], + ], +} + +{ + name: "collect: a table with no rules yields an empty array", + graph: { + nodes: [{table: "t", hit: "collect", inputs: ["x"], outputs: ["y"], rules: []}], + }, + cases: [ + [{x: 1}, []], + [{}, []], + ], +} + +{ + name: "collect: a table with no input columns returns every rule", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: [], outputs: ["n"], rules: [["1"], ["2"], ["3"]]}, + ], + }, + cases: [ + [{}, [{n: 1}, {n: 2}, {n: 3}]], + [{n: 9}, [{n: 1}, {n: 2}, {n: 3}]], + ], +} + +{ + name: "collect: wildcard rules match everything and keep their position", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["tier"], outputs: ["perk"], rules: [ + ["", "'newsletter'"], + ["'gold'", "'lounge'"], + ["", "'support'"], + ["'gold', 'silver'", "'discount'"], + ]}, + ], + }, + cases: [ + [{tier: "gold"}, [{perk: "newsletter"}, {perk: "lounge"}, {perk: "support"}, {perk: "discount"}]], + [{tier: "silver"}, [{perk: "newsletter"}, {perk: "support"}, {perk: "discount"}]], + [{tier: "bronze"}, [{perk: "newsletter"}, {perk: "support"}]], + [{}, [{perk: "newsletter"}, {perk: "support"}]], + [{tier: null}, [{perk: "newsletter"}, {perk: "support"}]], + ], +} + +{ + name: "collect: identical matching rules produce duplicate entries", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["y"], rules: [ + ["> 0", "'p'"], + ["> 0", "'p'"], + ["> 5", "'big'"], + ]}, + ], + }, + cases: [ + [{x: 1}, [{y: "p"}, {y: "p"}]], + [{x: 6}, [{y: "p"}, {y: "p"}, {y: "big"}]], + [{x: 0}, []], + ], +} + +{ + name: "collect: multiple input columns, each rule is a conjunction", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["country", "age"], outputs: ["rule"], rules: [ + ["'US'", ">= 21", "'can-drink'"], + ["'DE'", ">= 16", "'can-drink'"], + ["", ">= 18", "'can-vote'"], + ["'US'", "", "'pays-us-tax'"], + ]}, + ], + }, + cases: [ + [{country: "US", age: 30}, [{rule: "can-drink"}, {rule: "can-vote"}, {rule: "pays-us-tax"}]], + [{country: "US", age: 19}, [{rule: "can-vote"}, {rule: "pays-us-tax"}]], + [{country: "DE", age: 17}, [{rule: "can-drink"}]], + [{country: "DE", age: 15}, []], + [{country: "FR", age: 18}, [{rule: "can-vote"}]], + [{country: "US"}, [{rule: "pays-us-tax"}]], + ], +} + +// --- Output shape of each entry ------------------------------------------------------------ + +{ + name: "collect: several output columns, empty output cells are omitted per entry", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["code", "message", "severity"], rules: [ + ["> 10", "'E1'", "'too big'", "'error'"], + ["> 5", "'W1'", "", "'warn'"], + ["> 0", "", "", ""], + ]}, + ], + }, + cases: [ + [{x: 11}, [{code: "E1", message: "too big", severity: "error"}, {code: "W1", severity: "warn"}, {}]], + [{x: 6}, [{code: "W1", severity: "warn"}, {}]], + [{x: 1}, [{}]], + [{x: 0}, []], + ], +} + +{ + name: "collect: nested dotted output fields build one nested object per entry", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["kind"], outputs: ["fee.name", "fee.amount", "meta.source"], rules: [ + ["'card', 'wire'", "'processing'", "2.5", "'tbl'"], + ["'wire'", "'wire'", "15", "kind"], + ["", "'base'", "1", ""], + ]}, + ], + }, + cases: [ + [{kind: "wire"}, [ + {fee: {name: "processing", amount: 2.5}, meta: {source: "tbl"}}, + {fee: {name: "wire", amount: 15}, meta: {source: "wire"}}, + {fee: {name: "base", amount: 1}}, + ]], + [{kind: "card"}, [ + {fee: {name: "processing", amount: 2.5}, meta: {source: "tbl"}}, + {fee: {name: "base", amount: 1}}, + ]], + [{kind: "cash"}, [{fee: {name: "base", amount: 1}}]], + ], +} + +{ + name: "collect: output cells are expressions over the input", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["price"], outputs: ["label", "value"], rules: [ + ["> 0", "'tax'", "price * 0.2"], + ["> 100", "'discount'", "-(price * 0.1)"], + ["", "'echo'", "price"], + ]}, + ], + }, + cases: [ + [{price: 200}, [{label: "tax", value: 40}, {label: "discount", value: -20}, {label: "echo", value: 200}]], + [{price: 50}, [{label: "tax", value: 10}, {label: "echo", value: 50}]], + [{price: -1}, [{label: "echo", value: -1}]], + [{}, [{label: "echo", value: null}]], + ], +} + +{ + name: "collect: null output values stay inside the collected entries", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: [], outputs: ["a", "b"], rules: [ + ["null", "1"], + ["2", "null"], + ]}, + ], + }, + cases: [ + [{}, [{a: null, b: 1}, {a: 2, b: null}]], + ], +} + +{ + name: "collect: entries holding arrays and objects", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: [], outputs: ["v"], rules: [ + ["[1, 2]"], + ["{k: 'v'}"], + ["[]"], + ["{}"], + ]}, + ], + }, + cases: [ + [{}, [{v: [1, 2]}, {v: {k: "v"}}, {v: []}, {v: {}}]], + ], +} + +// --- Collect with transform attributes and downstream nodes ----------------------------- + +{ + name: "collect: outputPath wraps the array under a key", + graph: { + nodes: [ + {table: "t", hit: "collect", outputPath: "hits", inputs: ["x"], outputs: ["y"], rules: [ + ["> 0", "'a'"], + ["> 1", "'b'"], + ]}, + ], + }, + cases: [ + [{x: 2}, {hits: [{y: "a"}, {y: "b"}]}], + [{x: 1}, {hits: [{y: "a"}]}], + [{x: 0}, {hits: []}], + ], +} + +{ + name: "collect: outputPath with passThrough keeps the input next to the array", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, outputPath: "hits", inputs: ["x"], outputs: ["y"], rules: [ + ["> 0", "'a'"], + ]}, + ], + }, + cases: [ + [{x: 1}, {x: 1, hits: [{y: "a"}]}], + [{x: 0}, {x: 0, hits: []}], + [{x: 1, hits: "old"}, {x: 1, hits: [{y: "a"}]}], + ], +} + +{ + name: "collect: passThrough without outputPath replaces the input with the array", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, inputs: ["x"], outputs: ["y"], rules: [ + ["> 0", "'a'"], + ]}, + ], + }, + cases: [ + [{x: 1}, [{y: "a"}], "question: merging an array result into the pass-through input object replaces the whole input; the input fields are lost"], + [{x: 0}, [], "question: merging an array result into the pass-through input object replaces the whole input; the input fields are lost"], + ], +} + +{ + name: "collect: a downstream expression reads the array through $", + graph: { + nodes: [ + {table: "t", hit: "collect", outputPath: "fees", inputs: ["kind"], outputs: ["amount"], rules: [ + ["'a', 'b'", "10"], + ["'b'", "5"], + ["", "1"], + ]}, + {expression: "sum", fields: {total: "sum(map(fees, #.amount))", count: "len(fees)"}}, + ], + }, + cases: [ + [{kind: "a"}, {total: 11, count: 2}], + [{kind: "b"}, {total: 16, count: 3}], + [{kind: "c"}, {total: 1, count: 1}], + ], +} + +{ + name: "collect: a downstream expression on an unwrapped array result sees $root as the array", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["v"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ]}, + {expression: "e", fields: {n: "len($root)", s: "sum(map($root, #.v))"}}, + ], + }, + cases: [ + [{x: 2}, {n: 2, s: 3}], + [{x: 1}, {n: 1, s: 1}], + [{x: 0}, {n: 0, s: 0}], + ], +} + +{ + name: "collect: loop mode yields one array per element", + graph: { + nodes: [ + {table: "t", hit: "collect", inputField: "lines", executionMode: "loop", outputPath: "flags", inputs: ["qty", "price"], outputs: ["flag"], rules: [ + ["> 10", "", "'bulk'"], + ["", "> 100", "'pricey'"], + ]}, + ], + }, + cases: [ + [{lines: [{qty: 20, price: 200}, {qty: 1, price: 1}, {qty: 1, price: 500}]}, {flags: [[{flag: "bulk"}, {flag: "pricey"}], [], [{flag: "pricey"}]]}], + [{lines: []}, {flags: []}], + ], +} + +{ + name: "collect: two collect tables meeting at the output node, one array wins", + graph: { + nodes: [ + {table: "a", hit: "collect", inputs: [], outputs: ["from"], rules: [["'a'"]]}, + {table: "b", hit: "collect", inputs: [], outputs: ["from"], rules: [["'b'"], ["'b2'"]]}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, [{from: "a"}], "question: arrays are not concatenated at a join; the merge keeps only the array of the first-declared edge (a), not the later one"], + ], +} + +{ + name: "collect: two collect tables under distinct outputPaths merge into one object", + graph: { + nodes: [ + {table: "a", hit: "collect", outputPath: "left", inputs: ["x"], outputs: ["v"], rules: [["> 0", "1"], ["> 1", "2"]]}, + {table: "b", hit: "collect", outputPath: "right", inputs: ["x"], outputs: ["v"], rules: [["< 5", "3"]]}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{x: 2}, {left: [{v: 1}, {v: 2}], right: [{v: 3}]}], + [{x: 9}, {left: [{v: 1}, {v: 2}], right: []}], + [{x: 0}, {left: [], right: [{v: 3}]}], + ], +} + +// --- Large collect tables (eight or more rules use the equality index) ------------------- + +{ + name: "collect: large table returns every matching row in order across indexed and fallback rows", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["code"], outputs: ["r"], rules: [ + ["'A'", "0"], + ["", "1"], + ["'B'", "2"], + ["'A', 'B'", "3"], + ["startsWith($, 'A')", "4"], + ["'C'", "5"], + ["'A'", "6"], + ["'D'", "7"], + ["'E'", "8"], + ]}, + ], + }, + cases: [ + [{code: "A"}, [{r: 0}, {r: 1}, {r: 3}, {r: 4}, {r: 6}]], + [{code: "B"}, [{r: 1}, {r: 2}, {r: 3}]], + [{code: "AX"}, [{r: 1}, {r: 4}]], + [{code: "E"}, [{r: 1}, {r: 8}]], + [{code: "Z"}, [{r: 1}]], + [{}, [{r: 1}]], + ], +} + +{ + name: "collect: large numeric table with points and ranges", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [ + ["1", "'eq1'"], + ["1, 2, 3", "'small'"], + ["[1..5]", "'range'"], + ["2", "'eq2'"], + ["> 2", "'gt2'"], + ["4", "'eq4'"], + ["5.0", "'eq5'"], + ["6", "'eq6'"], + ]}, + ], + }, + cases: [ + [{n: 1}, [{r: "eq1"}, {r: "small"}, {r: "range"}]], + [{n: 2}, [{r: "small"}, {r: "range"}, {r: "eq2"}]], + [{n: 4}, [{r: "range"}, {r: "gt2"}, {r: "eq4"}]], + [{n: 5}, [{r: "range"}, {r: "gt2"}, {r: "eq5"}]], + [{n: 6}, [{r: "gt2"}, {r: "eq6"}]], + [{n: 0}, []], + [{n: "1"}, []], + ], +} + +// --- Per-column collect `[]` in a first-hit table ---------------------------------------- + +{ + name: "column collect: a `[]` output gathers the column from every matching rule", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["tags[]"], rules: [ + ["> 90", "'excellent'"], + ["> 50", "'pass'"], + ["> 0", "'attempted'"], + ]}, + ], + }, + cases: [ + [{score: 95}, {tags: ["excellent", "pass", "attempted"]}], + [{score: 60}, {tags: ["pass", "attempted"]}], + [{score: 1}, {tags: ["attempted"]}], + [{score: 0}, {tags: []}], + ], +} + +{ + name: "column collect: plain columns take the first matching rule, `[]` columns take all", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["grade", "tags[]"], rules: [ + ["> 90", "'A'", "'excellent'"], + ["> 50", "'C'", "'pass'"], + ["> 0", "'F'", "'attempted'"], + ]}, + ], + }, + cases: [ + [{score: 95}, {grade: "A", tags: ["excellent", "pass", "attempted"]}], + [{score: 60}, {grade: "C", tags: ["pass", "attempted"]}], + [{score: 5}, {grade: "F", tags: ["attempted"]}], + [{score: -5}, {tags: []}], + ], +} + +{ + name: "column collect: an empty `[]` cell contributes nothing but the rule still matches", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["first", "notes[]"], rules: [ + ["> 10", "'big'", ""], + ["> 5", "'mid'", "'over five'"], + ["> 0", "", "'positive'"], + ]}, + ], + }, + cases: [ + [{x: 11}, {first: "big", notes: ["over five", "positive"]}], + [{x: 6}, {first: "mid", notes: ["over five", "positive"]}], + [{x: 1}, {notes: ["positive"]}], + [{x: 0}, {notes: []}], + ], +} + +{ + name: "column collect: rules that match but contribute no values still produce an empty array", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["notes[]"], rules: [ + ["> 0", ""], + ["> 5", "'big'"], + ]}, + ], + }, + cases: [ + [{x: 6}, {notes: ["big"]}], + [{x: 1}, {notes: []}], + [{x: 0}, {notes: []}], + ], +} + +{ + name: "column collect: the first matching rule's empty plain cell is not filled by later rules", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["a", "b", "list[]"], rules: [ + ["> 5", "'a-first'", "", "1"], + ["> 0", "'a-second'", "'b-second'", "2"], + ]}, + ], + }, + cases: [ + [{x: 6}, {a: "a-first", list: [1, 2]}], + [{x: 1}, {a: "a-second", b: "b-second", list: [2]}], + ], +} + +{ + name: "column collect: several `[]` columns collect independently", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["codes[]", "levels[]"], rules: [ + ["> 10", "'C1'", "3"], + ["> 5", "'C2'", ""], + ["> 0", "", "1"], + ]}, + ], + }, + cases: [ + [{x: 20}, {codes: ["C1", "C2"], levels: [3, 1]}], + [{x: 6}, {codes: ["C2"], levels: [1]}], + [{x: 1}, {codes: [], levels: [1]}], + [{x: -1}, {codes: [], levels: []}], + ], +} + +{ + name: "column collect: dotted `[]` paths nest the collected array", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["result.status", "result.reasons[]"], rules: [ + ["> 100", "'rejected'", "'over limit'"], + ["> 50", "'review'", "'over half'"], + ["", "'ok'", ""], + ]}, + ], + }, + cases: [ + [{x: 150}, {result: {status: "rejected", reasons: ["over limit", "over half"]}}], + [{x: 60}, {result: {status: "review", reasons: ["over half"]}}], + [{x: 1}, {result: {status: "ok", reasons: []}}], + ], +} + +{ + name: "column collect: whitespace before `[]` is trimmed from the path", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["tags []"], rules: [ + ["> 0", "'p'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{x: 1}, {tags: ["p", "any"]}], + [{x: 0}, {tags: ["any"]}], + ], +} + +{ + name: "column collect: collected values of mixed types, including null and objects", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["vals[]"], rules: [ + ["1"], + ["'two'"], + ["null"], + ["{k: true}"], + ["[3]"], + ]}, + ], + }, + cases: [ + [{}, {vals: [1, "two", null, {k: true}, [3]]}], + ], +} + +{ + name: "column collect: passThrough merges the collected array into the input", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["x"], outputs: ["tags[]"], rules: [ + ["> 0", "'p'"], + ["> 5", "'big'"], + ]}, + ], + }, + cases: [ + [{x: 6}, {x: 6, tags: ["p", "big"]}], + [{x: 6, tags: ["old"]}, {x: 6, tags: ["p", "big"]}], + [{x: 0, tags: ["old"]}, {tags: [], x: 0}], + ], +} + +{ + name: "column collect: large first-hit table with a `[]` column", + graph: { + nodes: [ + {table: "t", inputs: ["country"], outputs: ["zone", "docs[]"], rules: [ + ["'US'", "'na'", "'passport'"], + ["'CA'", "'na'", "'passport'"], + ["'US', 'CA'", "", "'esta'"], + ["'DE'", "'eu'", "'id'"], + ["'FR'", "'eu'", "'id'"], + ["'DE', 'FR'", "", "'schengen'"], + ["'JP'", "'apac'", "'visa'"], + ["", "'other'", "'visa'"], + ["", "", "'photo'"], + ]}, + ], + }, + cases: [ + [{country: "US"}, {zone: "na", docs: ["passport", "esta", "visa", "photo"]}], + [{country: "FR"}, {zone: "eu", docs: ["id", "schengen", "visa", "photo"]}], + [{country: "JP"}, {zone: "apac", docs: ["visa", "visa", "photo"]}], + [{country: "BR"}, {zone: "other", docs: ["visa", "photo"]}], + [{}, {zone: "other", docs: ["visa", "photo"]}], + ], +} + +{ + name: "column collect: a `[]` column in a collect-policy table is written per entry, not gathered", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["name", "tags[]"], rules: [ + ["> 0", "'a'", "'t1'"], + ["> 5", "'b'", "'t2'"], + ]}, + ], + }, + cases: [ + [{x: 6}, [{name: "a", tags: "t1"}, {name: "b", tags: "t2"}], "question: under the collect hit policy the `[]` suffix is stripped and each entry gets a scalar value; whether it should wrap each value in a one-element array (or be rejected) is unspecified"], + [{x: 1}, [{name: "a", tags: "t1"}], "question: under the collect hit policy the `[]` suffix is stripped and each entry gets a scalar value; whether it should wrap each value in a one-element array (or be rejected) is unspecified"], + [{x: 0}, []], + ], +} diff --git a/core/engine/tests/spec/graph/06-table-cells.json5 b/core/engine/tests/spec/graph/06-table-cells.json5 new file mode 100644 index 00000000..12111bf9 --- /dev/null +++ b/core/engine/tests/spec/graph/06-table-cells.json5 @@ -0,0 +1,859 @@ +// Decision table cells. +// +// An input column with a field evaluates that field against the node input and binds it as `$`; +// each cell is then a unary test (`> 5`, `[1..10]`, `'a', 'b'`, or a full boolean expression +// using `$`). A cell that errors does not match. An input column without a field runs its +// cells as standard expressions over the node input; only a boolean `true` matches. Output +// cells are standard expressions over the node input. The unary language itself is pinned +// down in core/expression/tests/spec/unary; this chapter covers how tables wire it up. + +// --- Unary shorthands --------------------------------------------------------------------- + +{ + name: "cells: comparison shorthands", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["op"], rules: [ + ["> 5", "'gt'"], + [">= 5", "'gte'"], + ["< 5", "'lt'"], + ["<= 5", "'lte'"], + ["== 5", "'eq'"], + ["!= 5", "'ne'"], + ["5", "'bare'"], + ]}, + ], + }, + cases: [ + [{n: 6}, [{op: "gt"}, {op: "gte"}, {op: "ne"}]], + [{n: 5}, [{op: "gte"}, {op: "lte"}, {op: "eq"}, {op: "bare"}]], + [{n: 4.999}, [{op: "lt"}, {op: "lte"}, {op: "ne"}]], + [{n: 5.000}, [{op: "gte"}, {op: "lte"}, {op: "eq"}, {op: "bare"}]], + [{n: -100}, [{op: "lt"}, {op: "lte"}, {op: "ne"}]], + ], +} + +{ + name: "cells: closed, open and half-open intervals", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["iv"], rules: [ + ["[1..10]", "'closed'"], + ["(1..10)", "'open'"], + ["[1..10)", "'right-open'"], + ["(1..10]", "'left-open'"], + ]}, + ], + }, + cases: [ + [{n: 1}, [{iv: "closed"}, {iv: "right-open"}]], + [{n: 10}, [{iv: "closed"}, {iv: "left-open"}]], + [{n: 5.5}, [{iv: "closed"}, {iv: "open"}, {iv: "right-open"}, {iv: "left-open"}]], + [{n: 0.99}, []], + [{n: 10.01}, []], + [{n: "5"}, []], + [{n: null}, []], + ], +} + +{ + name: "cells: comma lists match any entry", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["'a', 'b'", "'letter'"], + ["1, 2, 3", "'digit'"], + ["> 100, < -100", "'extreme'"], + ["'x', 7", "'mixed'"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [{v: "a"}, {r: "letter"}], + [{v: "b"}, {r: "letter"}], + [{v: "c"}, {r: "none"}], + [{v: 2}, {r: "digit"}], + [{v: 2.0}, {r: "digit"}], + [{v: 101}, {r: "extreme"}], + [{v: -101}, {r: "extreme"}], + [{v: 50}, {r: "none"}], + [{v: "x"}, {r: "mixed"}], + [{v: 7}, {r: "mixed"}], + [{v: "7"}, {r: "none"}], + ], +} + +{ + name: "cells: array literal and `in` / `not in` shorthands", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["['a', 'b']", "'arr'"], + ["in ['a', 'c']", "'in'"], + ["not in ['a', 'b']", "'not-in'"], + ["in [1..5]", "'in-range'"], + ]}, + ], + }, + cases: [ + [{v: "a"}, [{r: "arr"}, {r: "in"}]], + [{v: "b"}, [{r: "arr"}]], + [{v: "c"}, [{r: "in"}, {r: "not-in"}]], + [{v: 3}, [{r: "not-in"}, {r: "in-range"}]], + [{v: null}, [{r: "not-in"}]], + ], +} + +{ + name: "cells: FEEL-style not(...) list negation is not supported", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["not('a', 'b')", "'not a or b'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{v: "c"}, {r: "other"}, "question: `not('a', 'b')` is not a list negation (it never matches); a FEEL-style reading would match any value other than 'a' and 'b'"], + [{v: "a"}, {r: "other"}], + [{v: "b"}, {r: "other"}], + ], +} + +{ + name: "cells: `not` applied to a full expression over $", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["not ($ in ['a', 'b'])", "'not a or b'"], + ["not startsWith($, 'x')", "'no x prefix'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{v: "c"}, {r: "not a or b"}], + [{v: "a"}, {r: "no x prefix"}], + [{v: "xa"}, {r: "not a or b"}], + ], +} + +{ + name: "cells: boolean and null literal cells", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["true", "'true'"], + ["false", "'false'"], + ["null", "'null'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{v: true}, {r: "true"}], + [{v: false}, {r: "false"}], + [{v: null}, {r: "null"}], + [{}, {r: "null"}], + [{v: 0}, {r: "other"}], + [{v: ""}, {r: "other"}], + ], +} + +{ + name: "cells: surrounding whitespace in cells is ignored", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + [" > 5 ", " 'big' "], + [" ", "'blank cell is a wildcard'"], + ]}, + ], + }, + cases: [ + [{v: 6}, {r: "big"}], + [{v: 1}, {r: "blank cell is a wildcard"}], + [{}, {r: "blank cell is a wildcard"}], + ], +} + +// --- `$` references in input cells --------------------------------------------------------- + +{ + name: "cells: `$` is the column's field value", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["user.name"], outputs: ["r"], rules: [ + ["startsWith($, 'A')", "'starts-a'"], + ["len($) > 3", "'long'"], + ["$ == upper($)", "'upper'"], + ["contains(lower($), 'bob')", "'bob'"], + ]}, + ], + }, + cases: [ + [{user: {name: "Alice"}}, [{r: "starts-a"}, {r: "long"}]], + [{user: {name: "BOB"}}, [{r: "upper"}, {r: "bob"}]], + [{user: {name: "Al"}}, [{r: "starts-a"}]], + [{user: {name: "ABOBA"}}, [{r: "starts-a"}, {r: "long"}, {r: "upper"}, {r: "bob"}]], + ], +} + +{ + name: "cells: `$` on an array field", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["tags"], outputs: ["r"], rules: [ + ["contains($, 'vip')", "'vip'"], + ["len($) == 0", "'empty'"], + ["some($, # == 'new')", "'has-new'"], + ["len($) >= 2", "'many'"], + ]}, + ], + }, + cases: [ + [{tags: ["vip", "new"]}, [{r: "vip"}, {r: "has-new"}, {r: "many"}]], + [{tags: []}, [{r: "empty"}]], + [{tags: ["old"]}, []], + [{tags: null}, [], "question: every cell errors on a null array (len/contains/some of null), so no rule matches; `len($) == 0` does not treat null as empty"], + ], +} + +{ + name: "cells: `$` on an object field", + graph: { + nodes: [ + {table: "t", inputs: ["address"], outputs: ["r"], rules: [ + ["$.country == 'US' and $.zip != null", "'us-complete'"], + ["$.country == 'US'", "'us'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{address: {country: "US", zip: "10001"}}, {r: "us-complete"}], + [{address: {country: "US"}}, {r: "us"}], + [{address: {country: "DE"}}, {r: "other"}], + [{address: {}}, {r: "other"}], + [{}, {r: "other"}], + ], +} + +{ + name: "cells: `$` compared with another input field", + graph: { + nodes: [ + {table: "t", inputs: ["spent"], outputs: ["status"], rules: [ + ["> budget", "'over'"], + ["$ == budget", "'exact'"], + ["< budget * 0.5", "'well under'"], + ["", "'under'"], + ]}, + ], + }, + cases: [ + [{spent: 120, budget: 100}, {status: "over"}], + [{spent: 100, budget: 100}, {status: "exact"}], + [{spent: 40, budget: 100}, {status: "well under"}], + [{spent: 80, budget: 100}, {status: "under"}], + [{spent: 80}, {status: "under"}], + [{spent: 80, budget: "100"}, {status: "under"}], + ], +} + +{ + name: "cells: a cell may reference fields of nested objects and other columns' fields", + graph: { + nodes: [ + {table: "t", inputs: ["order.total", "customer.tier"], outputs: ["r"], rules: [ + ["> customer.limit", "'gold'", "'over gold limit'"], + ["> customer.limit", "", "'over limit'"], + ["", "$ == customer.preferred", "'preferred tier'"], + ["", "", "'ok'"], + ]}, + ], + }, + cases: [ + [{order: {total: 500}, customer: {tier: "gold", limit: 100}}, {r: "over gold limit"}], + [{order: {total: 500}, customer: {tier: "silver", limit: 100}}, {r: "over limit"}], + [{order: {total: 50}, customer: {tier: "silver", limit: 100, preferred: "silver"}}, {r: "preferred tier"}], + [{order: {total: 50}, customer: {tier: "silver", limit: 100}}, {r: "ok"}], + [{order: {total: 500}, customer: {tier: "gold"}}, {r: "ok"}], + ], +} + +{ + name: "cells: `$` is rebound per column within one rule", + graph: { + nodes: [ + {table: "t", inputs: ["a", "b"], outputs: ["r"], rules: [ + ["$ > 1", "$ > 10", "'both'"], + ["$ > 1", "", "'a only'"], + ["", "$ > 10", "'b only'"], + ]}, + ], + }, + cases: [ + [{a: 2, b: 20}, {r: "both"}], + [{a: 2, b: 2}, {r: "a only"}], + [{a: 0, b: 20}, {r: "b only"}], + [{a: 20, b: 0}, {r: "a only"}], + [{a: 0, b: 0}, {}], + ], +} + +// --- Input fields that are expressions ------------------------------------------------------ + +{ + name: "cells: an input field may be an arbitrary expression", + graph: { + nodes: [ + {table: "t", inputs: ["price * qty", "len(items)"], outputs: ["r"], rules: [ + ["> 100", "> 2", "'big order, many items'"], + ["> 100", "", "'big order'"], + ["", "0", "'empty'"], + ["", "", "'small'"], + ]}, + ], + }, + cases: [ + [{price: 50, qty: 3, items: [1, 2, 3]}, {r: "big order, many items"}], + [{price: 50, qty: 3, items: [1]}, {r: "big order"}], + [{price: 1, qty: 1, items: []}, {r: "empty"}], + [{price: 1, qty: 1, items: [1]}, {r: "small"}], + ], +} + +{ + name: "cells: a field expression that errors makes every non-empty cell in that column fail", + graph: { + nodes: [ + {table: "t", inputs: ["price * qty"], outputs: ["r"], rules: [ + ["> 100", "'big'"], + ["<= 100", "'small'"], + ["", "'wildcard still matches'"], + ]}, + ], + }, + cases: [ + [{price: 50, qty: 3}, {r: "big"}], + [{price: 50, qty: 1}, {r: "small"}], + [{price: "x", qty: 1}, {r: "wildcard still matches"}], + [{price: 50}, {r: "wildcard still matches"}], + [{}, {r: "wildcard still matches"}], + ], +} + +{ + name: "cells: a field expression with a function call and a default", + graph: { + nodes: [ + {table: "t", inputs: ["upper(country ?? 'unknown')"], outputs: ["r"], rules: [ + ["'US', 'CA'", "'na'"], + ["'UNKNOWN'", "'missing'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{country: "us"}, {r: "na"}], + [{country: "Ca"}, {r: "na"}], + [{}, {r: "missing"}], + [{country: null}, {r: "missing"}], + [{country: "de"}, {r: "other"}], + ], +} + +{ + name: "cells: a field reading an upstream node through $nodes", + graph: { + nodes: [ + {expression: "score", fields: {value: "a + b"}}, + {table: "t", inputs: ["$nodes.score.value"], outputs: ["r"], rules: [ + ["> 10", "'high'"], + ["", "'low'"], + ]}, + ], + edges: ["input -> score -> t -> output"], + }, + cases: [ + [{a: 6, b: 6}, {r: "high"}], + [{a: 1, b: 2}, {r: "low"}], + ], +} + +// --- Input columns without a field -------------------------------------------------------- + +{ + name: "cells: a field-less column runs each cell as a full boolean expression", + graph: { + nodes: [ + {table: "t", inputs: [null], outputs: ["r"], rules: [ + ["age >= 18 and country == 'US'", "'adult us'"], + ["age >= 18", "'adult'"], + ["", "'minor'"], + ]}, + ], + }, + cases: [ + [{age: 30, country: "US"}, {r: "adult us"}], + [{age: 30, country: "DE"}, {r: "adult"}], + [{age: 10, country: "US"}, {r: "minor"}], + ], +} + +{ + name: "cells: an empty-string field is the same as no field", + graph: { + nodes: [ + {table: "t", inputs: [""], outputs: ["r"], rules: [ + ["x > 1", "'yes'"], + ["", "'no'"], + ]}, + ], + }, + cases: [ + [{x: 2}, {r: "yes"}], + [{x: 1}, {r: "no"}], + ], +} + +{ + name: "cells: a field-less cell that is not a boolean does not match", + graph: { + nodes: [ + {table: "t", inputs: [null], outputs: ["r"], rules: [ + ["x", "'truthy x'"], + ["1", "'number'"], + ["'true'", "'string'"], + ["null", "'null'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{x: true}, {r: "truthy x"}], + [{x: false}, {r: "fallback"}], + [{x: 1}, {r: "fallback"}], + [{x: "yes"}, {r: "fallback"}], + [{}, {r: "fallback"}], + ], +} + +{ + name: "cells: a field-less cell that errors does not match", + graph: { + nodes: [ + {table: "t", inputs: [null], outputs: ["r"], rules: [ + ["amount > 100", "'big'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{amount: 200}, {r: "big"}], + [{amount: 50}, {r: "fallback"}], + [{amount: null}, {r: "fallback"}], + [{amount: "200"}, {r: "fallback"}], + [{}, {r: "fallback"}], + ], +} + +{ + name: "cells: field-less shorthand cells have no `$` to compare", + graph: { + nodes: [ + {table: "t", inputs: [null], outputs: ["r"], rules: [ + ["> 5", "'gt'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{x: 10}, {r: "fallback"}], + [{}, {r: "fallback"}], + ], +} + +{ + name: "cells: field and field-less columns combine in one rule", + graph: { + nodes: [ + {table: "t", inputs: ["tier", null], outputs: ["discount"], rules: [ + ["'gold'", "total > 1000 and !blocked", "0.2"], + ["'gold'", "", "0.1"], + ["", "total > 5000", "0.05"], + ["", "", "0"], + ]}, + ], + }, + cases: [ + [{tier: "gold", total: 2000, blocked: false}, {discount: 0.2}], + [{tier: "gold", total: 2000, blocked: true}, {discount: 0.1}], + [{tier: "gold", total: 2000}, {discount: 0.1}, "question: `!blocked` with a missing `blocked` errors (not of null), so the cell fails and the rule falls through"], + [{tier: "silver", total: 6000}, {discount: 0.05}], + [{tier: "silver", total: 10}, {discount: 0}], + ], +} + +{ + name: "cells: field-less cells using closures over input arrays", + graph: { + nodes: [ + {table: "t", inputs: [null], outputs: ["r"], rules: [ + ["all(items, #.qty > 0)", "'all positive'"], + ["some(items, #.qty < 0)", "'some negative'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{items: [{qty: 1}, {qty: 2}]}, {r: "all positive"}], + [{items: [{qty: 1}, {qty: -2}]}, {r: "some negative"}], + [{items: [{qty: 0}]}, {r: "other"}], + [{items: []}, {r: "all positive"}], + ], +} + +// --- Null and missing inputs against cells ------------------------------------------------- + +{ + name: "cells: comparison cells never match a null or missing value", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [ + ["> 0", "'gt'"], + ["< 0", "'lt'"], + ["[0..10]", "'range'"], + ["0", "'zero'"], + ["!= 0", "'ne'"], + ["null", "'null'"], + ["== null", "'eq-null'"], + ["$ == null", "'dollar-null'"], + ["$ != null", "'not-null'"], + ]}, + ], + }, + cases: [ + [{n: null}, [{r: "ne"}, {r: "null"}, {r: "eq-null"}, {r: "dollar-null"}]], + [{}, [{r: "ne"}, {r: "null"}, {r: "eq-null"}, {r: "dollar-null"}]], + [{n: 0}, [{r: "range"}, {r: "zero"}, {r: "not-null"}]], + [{n: 5}, [{r: "gt"}, {r: "range"}, {r: "ne"}, {r: "not-null"}]], + ], +} + +{ + name: "cells: string cells against null, missing and wrongly typed values", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["s"], outputs: ["r"], rules: [ + ["'a'", "'eq'"], + ["'a', 'b'", "'list'"], + ["startsWith($, 'a')", "'prefix'"], + ["!= 'a'", "'ne'"], + ]}, + ], + }, + cases: [ + [{s: "a"}, [{r: "eq"}, {r: "list"}, {r: "prefix"}]], + [{s: "ab"}, [{r: "prefix"}, {r: "ne"}]], + [{s: null}, [{r: "ne"}]], + [{}, [{r: "ne"}]], + [{s: 1}, [{r: "ne"}]], + [{s: ["a"]}, [{r: "ne"}]], + ], +} + +{ + name: "cells: a missing intermediate object in a dotted field behaves like null", + graph: { + nodes: [ + {table: "t", inputs: ["a.b.c"], outputs: ["r"], rules: [ + ["null", "'null'"], + ["> 0", "'positive'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{a: {b: {c: 5}}}, {r: "positive"}], + [{a: {b: {c: null}}}, {r: "null"}], + [{a: {b: {}}}, {r: "null"}], + [{a: {}}, {r: "null"}], + [{a: null}, {r: "null"}], + [{a: 5}, {r: "null"}], + [{}, {r: "null"}], + [{a: {b: {c: "x"}}}, {r: "other"}], + ], +} + +{ + name: "cells: an error in one cell fails only that rule, later rules still run", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["> 5", "'big'"], + ["len($) > 2", "'long'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{v: 6}, {r: "big"}], + [{v: "abc"}, {r: "long"}], + [{v: "ab"}, {r: "fallback"}], + [{v: 1}, {r: "fallback"}], + [{v: null}, {r: "fallback"}], + ], +} + +{ + name: "cells: a malformed input cell never matches", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["> > 5", "'broken'"], + ["[1..", "'broken range'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{v: 6}, {r: "fallback"}, "question: a cell that does not parse is silently treated as a non-match instead of failing the evaluation"], + [{v: 1}, {r: "fallback"}, "question: a cell that does not parse is silently treated as a non-match instead of failing the evaluation"], + ], +} + +// --- Output cells ------------------------------------------------------------------------- + +{ + name: "cells: output cells are expressions over the node input", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["total", "label", "items"], rules: [ + ["'sum'", "price * qty", "'Total: ' + string(price * qty)", "map(lines, #.id)"], + ["", "price", "upper(kind ?? 'none')", "[]"], + ]}, + ], + }, + cases: [ + [{kind: "sum", price: 2, qty: 5, lines: [{id: 1}, {id: 2}]}, {total: 10, label: "Total: 10", items: [1, 2]}], + [{kind: "x", price: 3}, {total: 3, label: "X", items: []}], + [{price: 3}, {total: 3, label: "NONE", items: []}], + ], +} + +{ + name: "cells: output cells can reference fields that are not input columns", + graph: { + nodes: [ + {table: "t", inputs: ["tier"], outputs: ["greeting"], rules: [ + ["'gold'", "'Dear ' + customer.name"], + ["", "'Hi ' + (customer.nickname ?? customer.name)"], + ]}, + ], + }, + cases: [ + [{tier: "gold", customer: {name: "Ann"}}, {greeting: "Dear Ann"}], + [{tier: "basic", customer: {name: "Bob", nickname: "B"}}, {greeting: "Hi B"}], + [{tier: "basic", customer: {name: "Cy"}}, {greeting: "Hi Cy"}], + ], +} + +{ + name: "cells: output cells use template strings and conditionals", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["msg", "parity"], rules: [ + ["> 0", "`n is ${n}`", "n % 2 == 0 ? 'even' : 'odd'"], + ["", "'non-positive'", "null"], + ]}, + ], + }, + cases: [ + [{n: 4}, {msg: "n is 4", parity: "even"}], + [{n: 3}, {msg: "n is 3", parity: "odd"}], + [{n: 0}, {msg: "non-positive"}], + ], +} + +{ + name: "cells: `$` inside an output cell is the last bound input column value", + graph: { + nodes: [ + {table: "t", inputs: ["v", "w"], outputs: ["out"], rules: [ + ["> 0", "> 0", "$"], + ["> 0", "", "$"], + ["", "", "$"], + ]}, + ], + }, + cases: [ + [{v: 5, w: 7}, {out: 7}, "question: `$` in an output cell leaks the value bound by the last non-empty input cell evaluated for the row; outputs have no defined `$`"], + [{v: 5, w: -7}, {out: 5}, "question: `$` in an output cell leaks the value bound by the last non-empty input cell evaluated for the row; outputs have no defined `$`"], + [{v: -5, w: 7}, {out: -5}, "question: `$` in an output cell leaks the value bound while testing an earlier, failed rule (the all-wildcard rule binds nothing); outputs have no defined `$`"], + ], +} + +{ + name: "cells: an output cell reading a missing field gives null, which drops the key", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["copy"], rules: [ + ["source"], + ]}, + ], + }, + cases: [ + [{source: 1}, {source: 1, copy: 1}], + [{source: "s"}, {source: "s", copy: "s"}], + [{}, {}], + [{copy: "old"}, {}], + ], +} + +{ + name: "cells: an output cell that errors makes a first-hit table skip to the next rule", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["> 0", "v + 'x' * 2"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{v: 1}, "!error", "bug: an output cell that fails to evaluate silently discards the matched rule and falls through to the next one; it should fail the node"], + [{v: -1}, {r: "fallback"}], + ], +} + +{ + name: "cells: an output cell that errors only for some inputs", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["r"], rules: [ + ["'div'", "a / b"], + ["'len'", "len(s)"], + ["", "'default'"], + ]}, + ], + }, + cases: [ + [{kind: "div", a: 10, b: 4}, {r: 2.5}], + [{kind: "len", s: "abc"}, {r: 3}], + [{kind: "len", s: 5}, "!error", "bug: an output cell that fails to evaluate silently discards the matched rule and falls through to the next one; it should fail the node"], + [{kind: "other"}, {r: "default"}], + ], +} + +{ + name: "cells: an output cell that errors drops the entry from a collect table", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: [], outputs: ["r"], rules: [ + ["1"], + ["len(missing)"], + ["3"], + ]}, + ], + }, + cases: [ + [{}, "!error", "bug: an output cell that fails to evaluate silently drops that rule's entry from the collected list; it should fail the node"], + [{missing: "ab"}, [{r: 1}, {r: 2}, {r: 3}]], + ], +} + +{ + name: "cells: an output cell that errors in a `[]` column skips the whole rule", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["first", "all[]"], rules: [ + ["> 5", "'big'", "len(v)"], + ["> 0", "'positive'", "v"], + ]}, + ], + }, + cases: [ + [{v: 6}, "!error", "bug: an output cell that fails to evaluate silently discards the matched rule (scalars and collected values); it should fail the node"], + [{v: 1}, {first: "positive", all: [1]}], + ], +} + +{ + name: "cells: a malformed output cell", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["> 0", "1 +"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{v: 1}, "!error", "bug: an output cell that does not parse silently discards the matched rule and falls through; it should fail the node"], + [{v: 0}, {r: "fallback"}], + ], +} + +{ + name: "cells: an output cell may copy a whole object or array from the input", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["copy"], rules: [ + ["obj"], + ]}, + {expression: "e", passThrough: true, fields: {objX: "obj.x", copyX: "copy.x"}}, + ], + }, + cases: [ + [{obj: {x: 1}}, {obj: {x: 1}, copy: {x: 1}, objX: 1, copyX: 1}], + [{obj: [1, 2]}, {obj: [1, 2], copy: [1, 2]}], + [{obj: "s"}, {obj: "s", copy: "s"}], + ], +} + +// --- Realistic combinations -------------------------------------------------------------- + +{ + name: "cells: loan pricing with ranges, lists, references and computed outputs", + graph: { + nodes: [ + {table: "t", inputs: ["applicant.creditScore", "loan.purpose", "loan.amount / applicant.income"], outputs: ["rate", "reason"], rules: [ + [">= 750", "'home', 'auto'", "< 0.3", "base - 0.5", "'prime'"], + [">= 750", "", "< 0.5", "base", "'good credit'"], + ["[650..750)", "'home'", "< 0.4", "base + 1", "'near prime home'"], + ["[650..750)", "", "", "base + 2", "'near prime'"], + ["< 650", "", "", "null", "'declined: score ' + string(applicant.creditScore)"], + ["", "", "", "base + 5", "'other'"], + ]}, + ], + }, + cases: [ + [{applicant: {creditScore: 800, income: 100000}, loan: {purpose: "home", amount: 20000}, base: 4.5}, {rate: 4, reason: "prime"}], + [{applicant: {creditScore: 800, income: 100000}, loan: {purpose: "boat", amount: 20000}, base: 4.5}, {rate: 4.5, reason: "good credit"}], + [{applicant: {creditScore: 800, income: 100000}, loan: {purpose: "home", amount: 40000}, base: 4.5}, {rate: 4.5, reason: "good credit"}], + [{applicant: {creditScore: 700, income: 100000}, loan: {purpose: "home", amount: 20000}, base: 4.5}, {rate: 5.5, reason: "near prime home"}], + [{applicant: {creditScore: 650, income: 100000}, loan: {purpose: "auto", amount: 20000}, base: 4.5}, {rate: 6.5, reason: "near prime"}], + [{applicant: {creditScore: 600, income: 100000}, loan: {purpose: "home", amount: 20000}, base: 4.5}, {reason: "declined: score 600"}], + [{applicant: {creditScore: 800, income: 10000}, loan: {purpose: "home", amount: 20000}, base: 4.5}, {rate: 9.5, reason: "other"}], + [{applicant: {creditScore: 800, income: 0}, loan: {purpose: "home", amount: 20000}, base: 4.5}, {rate: 9.5, reason: "other"}], + ], +} + +{ + name: "cells: a table reading its own earlier column results is not possible, cells see only the input", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["a", "b"], rules: [ + ["", "x * 2", "a ?? 'no a'"], + ]}, + ], + }, + cases: [ + [{x: 2}, {a: 4, b: "no a"}], + [{x: 2, a: 100}, {a: 4, b: 100}], + ], +} diff --git a/core/engine/tests/spec/graph/07-table-outputs.json5 b/core/engine/tests/spec/graph/07-table-outputs.json5 new file mode 100644 index 00000000..ca247b5b --- /dev/null +++ b/core/engine/tests/spec/graph/07-table-outputs.json5 @@ -0,0 +1,1284 @@ +// Decision table outputs: how a matched row becomes an object. Output fields are dot paths, +// cells are standard expressions, empty cells write nothing, `[]` suffixed columns collect +// across matched rows, and transform attributes (passThrough, outputPath) merge the result +// with the node input. + +// --------------------------------------------------------------------------------------- +// Flat output fields: every non-empty cell of the matched row writes its field. +// --------------------------------------------------------------------------------------- + +{ + name: "flat outputs of the first matching row", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["kind", "score"], rules: [ + ["> 10", "'big'", "3"], + ["> 0", "'small'", "2"], + ["", "'none'", "1"], + ]}, + ], + }, + cases: [ + [{n: 20}, {kind: "big", score: 3}], + [{n: 5}, {kind: "small", score: 2}], + [{n: 0}, {kind: "none", score: 1}], + [{n: -1.5}, {kind: "none", score: 1}], + [{}, {kind: "none", score: 1}], + [{n: null}, {kind: "none", score: 1}], + [{n: "20"}, {kind: "none", score: 1}], + ], +} + +{ + name: "a table with no input columns always matches its first row", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "b"], rules: [ + ["1", "'x'"], + ["2", "'y'"], + ]}, + ], + }, + cases: [ + [{}, {a: 1, b: "x"}], + [{a: 99}, {a: 1, b: "x"}], + ], +} + +{ + name: "a table with no rules produces nothing", + graph: { + nodes: [{table: "t", inputs: ["n"], outputs: ["a"], rules: []}], + }, + cases: [ + [{n: 1}, {}], + [{}, {}], + ], +} + +{ + name: "no matching row produces an empty result, not an error", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["a"], rules: [ + ["> 100", "1"], + ]}, + ], + }, + cases: [ + [{n: 1}, {}], + [{n: 101}, {a: 1}], + [{}, {}], + ], +} + +// --------------------------------------------------------------------------------------- +// Nested output paths: `a.b` builds intermediate objects; sibling paths share them. +// --------------------------------------------------------------------------------------- + +{ + name: "a dotted output field builds nested objects", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["result.tier", "result.limits.max"], rules: [ + ["> 10", "'gold'", "n * 10"], + ["", "'basic'", "100"], + ]}, + ], + }, + cases: [ + [{n: 11}, {result: {tier: "gold", limits: {max: 110}}}], + [{n: 1}, {result: {tier: "basic", limits: {max: 100}}}], + [{}, {result: {tier: "basic", limits: {max: 100}}}], + ], +} + +{ + name: "sibling dotted fields share their parent object", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a.x", "b", "a.y", "a.z.w"], rules: [ + ["1", "2", "3", "4"], + ]}, + ], + }, + cases: [ + [{}, {a: {x: 1, y: 3, z: {w: 4}}, b: 2}], + ], +} + +{ + name: "deeply nested output path", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["a.b.c.d.e"], rules: [ + ["'x'", "k"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{k: "x"}, {a: {b: {c: {d: {e: "x"}}}}}], + [{k: "y"}, {a: {b: {c: {d: {e: "other"}}}}}], + ], +} + +{ + name: "a numeric path segment creates an object key, not an array", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["items.0", "items.1.name"], rules: [ + ["'first'", "'second'"], + ]}, + ], + }, + cases: [ + [{}, {items: {"0": "first", "1": {name: "second"}}}], + ], +} + +{ + name: "a nested path whose parent was written as a scalar is dropped", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "a.b"], rules: [ + ["1", "2"], + ["", ""], + ]}, + ], + }, + cases: [ + [{}, {a: 1}, "question: `a.b` is silently dropped because `a` already holds a scalar; no error is raised"], + ], +} + +{ + name: "a scalar field written after a nested one replaces the parent object", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a.b", "a"], rules: [ + ["2", "1"], + ]}, + ], + }, + cases: [ + [{}, {a: 1}], + ], +} + +{ + name: "an object cell and a nested field merge in column order", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "a.c"], rules: [ + ["{b: 1}", "2"], + ]}, + ], + }, + cases: [ + [{}, {a: {b: 1, c: 2}}], + ], +} + +{ + name: "output field names keep spaces and special characters", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["my field", "a-b", "$x", " padded "], rules: [ + ["1", "2", "3", "4"], + ]}, + ], + }, + cases: [ + [{}, {"my field": 1, "a-b": 2, "$x": 3, padded: 4}], + ], +} + +// --------------------------------------------------------------------------------------- +// Output cell values: cells are standard expressions evaluated against the node input. +// The column `type` is metadata for analysis and does not coerce runtime values. +// --------------------------------------------------------------------------------------- + +{ + name: "output cells produce every value type", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["s", "n", "b", "arr", "obj", "neg", "dec"], rules: [ + ["'text'", "42", "true", "[1, 'two', false]", "{k: 'v', nested: {x: 1}}", "-7", "0.1 + 0.2"], + ]}, + ], + }, + cases: [ + [{}, {s: "text", n: 42, b: true, arr: [1, "two", false], obj: {k: "v", nested: {x: 1}}, neg: -7, dec: 0.3}], + ], +} + +{ + name: "output cells read the node input", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["total", "label", "first", "count"], rules: [ + ["'a'", "price * qty", "`${kind}-${qty}`", "items[0]", "len(items)"], + ["", "0", "'other'", "null", "0"], + ]}, + ], + }, + cases: [ + [{kind: "a", price: 2.5, qty: 4, items: [9, 8]}, {total: 10, label: "a-4", first: 9, count: 2}], + [{kind: "a", price: 1, qty: 1, items: ["z"]}, {total: 1, label: "a-1", first: "z", count: 1}], + [{kind: "b", items: []}, {total: 0, label: "other", count: 0}], + ], +} + +{ + name: "output cells read nested input paths", + graph: { + nodes: [ + {table: "t", inputs: ["customer.tier"], outputs: ["discount", "name"], rules: [ + ["'gold'", "customer.base * 0.2", "customer.profile.name"], + ["", "0", "'anonymous'"], + ]}, + ], + }, + cases: [ + [{customer: {tier: "gold", base: 50, profile: {name: "Ann"}}}, {discount: 10, name: "Ann"}], + [{customer: {tier: "gold", base: 50}}, {discount: 10}], + [{customer: {tier: "silver"}}, {discount: 0, name: "anonymous"}], + [{}, {discount: 0, name: "anonymous"}], + ], +} + +{ + name: "the declared column type does not coerce output values", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: [{field: "n", type: "number"}, {field: "s", type: "string"}, {field: "b", type: "boolean"}], rules: [ + ["", "v", "v", "v"], + ]}, + ], + }, + cases: [ + [{v: 1}, {n: 1, s: 1, b: 1}], + [{v: "1"}, {n: "1", s: "1", b: "1"}], + [{v: true}, {n: true, s: true, b: true}], + [{v: [1]}, {n: [1], s: [1], b: [1]}], + ], +} + +{ + name: "an output column with an empty type behaves as untyped", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: [{field: "a", type: ""}, {field: "b", name: "Bee"}], rules: [ + ["'x'", "2"], + ]}, + ], + }, + cases: [ + [{}, {a: "x", b: 2}], + ], +} + +{ + name: "output values are copies of the input, not shared references", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["copy"], rules: [ + ["src"], + ]}, + ], + }, + cases: [ + [{src: {a: 1}}, {src: {a: 1}, copy: {a: 1}}], + [{src: [1, 2]}, {src: [1, 2], copy: [1, 2]}], + [{src: "s"}, {src: "s", copy: "s"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Null and errors in output cells. +// A top-level null output is dropped from the final graph result, a nested null is kept. +// An output cell that fails to evaluate makes its row count as not matched. +// --------------------------------------------------------------------------------------- + +{ + name: "a top-level null output is absent from the graph result", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "b"], rules: [ + ["null", "1"], + ]}, + ], + }, + cases: [ + [{}, {b: 1}], + [{a: 5}, {b: 1}], + ], +} + +{ + name: "a nested null output is kept", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["r.a", "r.b"], rules: [ + ["null", "1"], + ]}, + ], + }, + cases: [ + [{}, {r: {a: null, b: 1}}], + ], +} + +{ + name: "a missing reference in an output cell yields null", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "r.b"], rules: [ + ["missing", "missing.deep"], + ]}, + ], + }, + cases: [ + [{}, {r: {b: null}}], + [{missing: 1}, {a: 1, r: {b: null}}], + [{missing: {deep: 2}}, {a: {deep: 2}, r: {b: 2}}], + ], +} + +{ + name: "a type error in an output cell skips the row and the next matching row wins", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["a", "b"], rules: [ + ["> 0", "1", "n + 'x'"], + ["", "2", "'fallback'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {a: 2, b: "fallback"}, "question: a type error in an output cell (number + string) silently turns the row into a non-match"], + [{n: 0}, {a: 2, b: "fallback"}], + ], +} + +{ + name: "a failing output cell falls through to later rules", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["a", "b"], rules: [ + ["> 0", "1", "date('nope')"], + ["", "2", "'fallback'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {a: 2, b: "fallback"}, "question: an output evaluation error silently turns the row into a non-match instead of failing the node"], + [{n: 0}, {a: 2, b: "fallback"}], + ], +} + +{ + name: "a failing output cell in the only matching row produces nothing", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a"], rules: [ + ["date('nope')"], + ]}, + ], + }, + cases: [ + [{}, {}, "question: the error is swallowed; the table behaves as if no row matched"], + ], +} + +// --------------------------------------------------------------------------------------- +// Empty output cells write nothing: the key is absent, not null. +// --------------------------------------------------------------------------------------- + +{ + name: "empty output cells leave their field out", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["a", "b", "c.d"], rules: [ + ["1", "'one'", "", ""], + ["2", "", "'two'", ""], + ["3", "", "", "3"], + ["", "", "", ""], + ]}, + ], + }, + cases: [ + [{n: 1}, {a: "one"}], + [{n: 2}, {b: "two"}], + [{n: 3}, {c: {d: 3}}], + [{n: 4}, {}], + ], +} + +{ + name: "a row with all output cells empty still stops first hit", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["a"], rules: [ + ["> 0", ""], + ["", "'later'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {}], + [{n: 0}, {a: "later"}], + ], +} + +{ + name: "an all-empty matching row and no match differ under outputPath", + graph: { + nodes: [ + {table: "t", outputPath: "res", inputs: ["n"], outputs: ["a"], rules: [ + ["> 0", ""], + ["0", "'zero'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {res: {}}], + [{n: 0}, {res: {a: "zero"}}], + [{n: -1}, {}], + ], +} + +{ + name: "empty output cells under passThrough keep the input value", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["n"], outputs: ["a", "b"], rules: [ + ["> 0", "'new'", ""], + ["", "", "'new'"], + ]}, + ], + }, + cases: [ + [{n: 1, a: "old", b: "old"}, {n: 1, a: "new", b: "old"}], + [{n: 0, a: "old", b: "old"}, {n: 0, a: "old", b: "new"}], + [{n: 0}, {n: 0, b: "new"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Duplicate output fields: columns write in order, so the last non-empty cell wins. +// --------------------------------------------------------------------------------------- + +{ + name: "duplicate output fields: the later column wins", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["x", "x"], rules: [ + ["1", "'first'", "'second'"], + ["2", "'first'", ""], + ["3", "", "'second'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {x: "second"}], + [{n: 2}, {x: "first"}], + [{n: 3}, {x: "second"}], + [{n: 4}, {}], + ], +} + +{ + name: "a later null in a duplicate column overwrites an earlier value", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["r.x", "r.x"], rules: [ + ["1", "null"], + ]}, + ], + }, + cases: [ + [{}, {r: {x: null}}], + ], +} + +{ + name: "duplicate nested fields under a shared parent", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a.b", "a.c", "a.b"], rules: [ + ["1", "2", "3"], + ]}, + ], + }, + cases: [ + [{}, {a: {b: 3, c: 2}}], + ], +} + +{ + name: "duplicate fields in a collect table, per row", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["x", "x"], rules: [ + ["> 0", "'a'", "'b'"], + ["> 1", "'c'", ""], + ]}, + ], + }, + cases: [ + [{n: 2}, [{x: "b"}, {x: "c"}]], + [{n: 1}, [{x: "b"}]], + [{n: 0}, []], + ], +} + +// --------------------------------------------------------------------------------------- +// Collect hit policy: an array of the matched rows' outputs, in rule order. +// --------------------------------------------------------------------------------------- + +{ + name: "collect returns every matching row in rule order", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "'pos'"], + ["> 10", "'big'"], + ["", "'any'"], + ["< 0", "'neg'"], + ]}, + ], + }, + cases: [ + [{n: 20}, [{v: "pos"}, {v: "big"}, {v: "any"}]], + [{n: 5}, [{v: "pos"}, {v: "any"}]], + [{n: -1}, [{v: "any"}, {v: "neg"}]], + [{}, [{v: "any"}]], + ], +} + +{ + name: "collect with no match returns an empty array", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ]}, + ], + }, + cases: [ + [{n: 0}, []], + [{n: 1}, [{v: 1}]], + [{}, []], + ], +} + +{ + name: "collect rows keep nested output paths", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["r.code", "r.meta.n"], rules: [ + ["> 0", "'A'", "n"], + ["> 1", "'B'", ""], + ]}, + ], + }, + cases: [ + [{n: 2}, [{r: {code: "A", meta: {n: 2}}}, {r: {code: "B"}}]], + [{n: 1}, [{r: {code: "A", meta: {n: 1}}}]], + ], +} + +{ + name: "collect rows with all outputs empty become empty objects", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", ""], + ["> 1", "2"], + ]}, + ], + }, + cases: [ + [{n: 2}, [{}, {v: 2}]], + [{n: 1}, [{}]], + ], +} + +{ + name: "collect skips a row whose output cell fails", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: [], outputs: ["v"], rules: [ + ["1"], + ["date('nope')"], + ["3"], + ]}, + ], + }, + cases: [ + [{}, [{v: 1}, {v: 3}], "question: a failing output cell drops the row silently instead of failing the node"], + ], +} + +{ + name: "collect skips a failing row when the table has an input column", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ["> 0", "date('nope')"], + ["", "3"], + ]}, + ], + }, + cases: [ + [{n: 1}, [{v: 1}, {v: 3}], "question: a failing output cell drops the row silently instead of failing the node"], + [{n: 0}, [{v: 3}]], + [{}, [{v: 3}]], + ], +} + +{ + name: "collect rows keep null outputs when the table has an input column", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v", "w"], rules: [ + ["> 0", "null", "n"], + ["", "n", "null"], + ]}, + ], + }, + cases: [ + [{n: 1}, [{v: null, w: 1}, {v: 1, w: null}]], + [{n: 0}, [{v: 0, w: null}]], + [{}, [{v: null, w: null}]], + ], +} + +{ + name: "collect rows keep null outputs inside each row", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: [], outputs: ["v", "w"], rules: [ + ["null", "1"], + ["2", "null"], + ]}, + ], + }, + cases: [ + [{}, [{v: null, w: 1}, {v: 2, w: null}]], + ], +} + +{ + name: "collect under outputPath nests the array", + graph: { + nodes: [ + {table: "t", hit: "collect", outputPath: "hits", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ]}, + ], + }, + cases: [ + [{n: 2}, {hits: [{v: 1}, {v: 2}]}], + [{n: 0}, {hits: []}], + [{}, {hits: []}], + ], +} + +{ + name: "collect under passThrough and outputPath keeps the input", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, outputPath: "hits", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ]}, + ], + }, + cases: [ + [{n: 2}, {n: 2, hits: [{v: 1}, {v: 2}]}], + [{n: 0, hits: "old"}, {n: 0, hits: []}], + [{n: 1, hits: [{v: 9}, {v: 8}]}, {n: 1, hits: [{v: 1}]}], + ], +} + +{ + name: "collect under passThrough without outputPath", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ]}, + ], + }, + cases: [ + [{n: 1}, [{v: 1}], "question: the row array replaces the whole input, passThrough has no visible effect for collect tables without outputPath"], + [{n: 0}, [], "question: the empty row array replaces the whole input"], + ], +} + +// --------------------------------------------------------------------------------------- +// `[]` suffix collect columns in a first-hit table: scalar columns come from the first +// matched row, `[]` columns gather their cell from every matched row (empty cells skip). +// --------------------------------------------------------------------------------------- + +{ + name: "first hit with a collect column gathers from all matching rows", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["tier", "tags[]"], rules: [ + ["> 10", "'gold'", "'big'"], + ["> 0", "'silver'", "'positive'"], + ["", "'basic'", "'any'"], + ]}, + ], + }, + cases: [ + [{n: 20}, {tier: "gold", tags: ["big", "positive", "any"]}], + [{n: 5}, {tier: "silver", tags: ["positive", "any"]}], + [{n: 0}, {tier: "basic", tags: ["any"]}], + [{}, {tier: "basic", tags: ["any"]}], + ], +} + +{ + name: "collect column with empty cells skips those rows", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["tier", "tags[]"], rules: [ + ["> 10", "'gold'", ""], + ["> 0", "", "'positive'"], + ["", "", ""], + ]}, + ], + }, + cases: [ + [{n: 20}, {tier: "gold", tags: ["positive"]}], + [{n: 5}, {tags: ["positive"]}], + [{n: 0}, {tags: []}], + ], +} + +{ + name: "collect column alone with no match produces an empty list", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["tags[]"], rules: [ + ["> 0", "'a'"], + ["> 1", "'b'"], + ]}, + ], + }, + cases: [ + [{n: 2}, {tags: ["a", "b"]}], + [{n: 1}, {tags: ["a"]}], + [{n: 0}, {tags: []}], + ], +} + +{ + name: "a matched collect column with no non-empty cells is an empty array", + graph: { + nodes: [ + {table: "t", outputPath: "r", inputs: ["n"], outputs: ["tags[]"], rules: [ + ["> 0", ""], + ["> 1", "'b'"], + ]}, + ], + }, + cases: [ + [{n: 2}, {r: {tags: ["b"]}}], + [{n: 1}, {r: {tags: []}}], + [{n: 0}, {r: {tags: []}}], + ], +} + +{ + name: "several collect columns gather independently", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["a[]", "b[]", "first"], rules: [ + ["> 0", "1", "", "'r0'"], + ["> 1", "", "'x'", "'r1'"], + ["> 2", "3", "'y'", "'r2'"], + ]}, + ], + }, + cases: [ + [{n: 3}, {a: [1, 3], b: ["x", "y"], first: "r0"}], + [{n: 2}, {a: [1], b: ["x"], first: "r0"}], + [{n: 1}, {a: [1], b: [], first: "r0"}], + ], +} + +{ + name: "collect columns on nested paths", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r.tier", "r.flags[]", "audit.reasons[]"], rules: [ + ["> 0", "'p'", "'positive'", "'n>0'"], + ["> 5", "'q'", "'large'", ""], + ]}, + ], + }, + cases: [ + [{n: 6}, {r: {tier: "p", flags: ["positive", "large"]}, audit: {reasons: ["n>0"]}}], + [{n: 1}, {r: {tier: "p", flags: ["positive"]}, audit: {reasons: ["n>0"]}}], + ], +} + +{ + name: "collect column values keep every type, including null and objects", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["v[]"], rules: [ + ["1"], + ["'s'"], + ["null"], + ["{k: 1}"], + ["[1, 2]"], + ["missing"], + ]}, + ], + }, + cases: [ + [{}, {v: [1, "s", null, {k: 1}, [1, 2], null]}], + [{missing: true}, {v: [1, "s", null, {k: 1}, [1, 2], true]}], + ], +} + +{ + name: "collect column values keep every type when the table has an input column", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["v[]"], rules: [ + ["", "1"], + ["", "null"], + ["'x'", "{k: k}"], + ["", "missing"], + ]}, + ], + }, + cases: [ + [{k: "x"}, {v: [1, null, {k: "x"}, null]}], + [{k: "y", missing: [1]}, {v: [1, null, [1]]}], + [{}, {v: [1, null, null]}], + ], +} + +{ + name: "collect column cells read the input of each row", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["reasons[]"], rules: [ + ["< 500", "`low score ${score}`"], + ["< 300", "'very low'"], + ["", "name"], + ]}, + ], + }, + cases: [ + [{score: 200, name: "a"}, {reasons: ["low score 200", "very low", "a"]}], + [{score: 400, name: "b"}, {reasons: ["low score 400", "b"]}], + [{score: 900}, {reasons: [null]}], + ], +} + +{ + name: "a collect column with spaces before the suffix", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["tags []", " other[] "], rules: [ + ["1", "2"], + ["3", ""], + ]}, + ], + }, + cases: [ + [{}, {tags: [1, 3], other: [2]}], + ], +} + +{ + name: "scalar columns come from the first matched row only", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["a", "b", "all[]"], rules: [ + ["> 0", "'r0'", "", "0"], + ["> 1", "'r1'", "'r1'", "1"], + ]}, + ], + }, + cases: [ + [{n: 2}, {a: "r0", all: [0, 1]}], + [{n: 1}, {a: "r0", all: [0]}], + ], +} + +{ + name: "a failing collect cell drops that row from all collect columns", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["a[]", "b[]"], rules: [ + ["> 0", "1", "'x'"], + ["> 1", "2", "date('nope')"], + ["> 2", "3", "'z'"], + ]}, + ], + }, + cases: [ + [{n: 3}, {a: [1, 3], b: ["x", "z"]}, "question: an erroring collect cell silently drops the whole row, including its other collect cells"], + [{n: 1}, {a: [1], b: ["x"]}], + ], +} + +{ + name: "a failing scalar cell in a later row does not drop its collect cells", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["s", "c[]"], rules: [ + ["> 0", "'ok'", "1"], + ["> 1", "date('nope')", "2"], + ]}, + ], + }, + cases: [ + [{n: 2}, {s: "ok", c: [1, 2]}], + [{n: 1}, {s: "ok", c: [1]}], + ], +} + +{ + name: "a failing scalar cell in the first matched row", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["s", "c[]"], rules: [ + ["> 0", "date('nope')", "1"], + ["> 1", "'second'", "2"], + ]}, + ], + }, + cases: [ + [{n: 2}, {s: "second", c: [2]}, "question: the first matched row is dropped entirely and the second row provides the scalars"], + [{n: 1}, {c: []}, "question: the only matched row is dropped, so the table produces only the empty collect list"], + ], +} + +{ + name: "a duplicate collect column: both columns gather into one array, row by row", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["x[]", "x[]"], rules: [ + ["1", "'a'"], + ["2", ""], + ]}, + ], + }, + cases: [ + [{}, {x: [1, "a", 2]}], + ], +} + +{ + name: "a scalar column and a collect column on the same field", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["x", "x[]"], rules: [ + ["'scalar'", "1"], + ["'ignored'", "2"], + ]}, + ], + }, + cases: [ + [{}, {x: [1, 2]}, "question: the collected array overwrites the scalar column; no conflict is reported"], + ], +} + +{ + name: "a collect column in a collect table is written per row, not gathered", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v", "tags[]"], rules: [ + ["> 0", "1", "'a'"], + ["> 1", "2", "'b'"], + ]}, + ], + }, + cases: [ + [{n: 2}, [{v: 1, tags: "a"}, {v: 2, tags: "b"}], "question: under hit policy collect the `[]` suffix is stripped and each row holds the scalar; it is not wrapped in an array"], + [{n: 0}, []], + ], +} + +{ + name: "a collect column under passThrough replaces an input array", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["n"], outputs: ["tags[]"], rules: [ + ["> 0", "'a'"], + ["> 1", "'b'"], + ]}, + ], + }, + cases: [ + [{n: 2, tags: ["old"]}, {n: 2, tags: ["a", "b"]}], + [{n: 0, tags: ["old"]}, {n: 0, tags: []}], + [{n: 1}, {n: 1, tags: ["a"]}], + ], +} + +// --------------------------------------------------------------------------------------- +// passThrough: the table output is merged over the node input. Objects merge deeply, +// arrays and scalars replace, a top-level null output removes the input key. +// --------------------------------------------------------------------------------------- + +{ + name: "passThrough keeps input fields next to the outputs", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["n"], outputs: ["tier"], rules: [ + ["> 10", "'gold'"], + ["", "'basic'"], + ]}, + ], + }, + cases: [ + [{n: 11, other: "x"}, {n: 11, other: "x", tier: "gold"}], + [{n: 1}, {n: 1, tier: "basic"}], + [{}, {tier: "basic"}], + ], +} + +{ + name: "passThrough: an output overrides an input field of the same name", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["n", "s"], rules: [ + ["n + 1", "'new'"], + ]}, + ], + }, + cases: [ + [{n: 1, s: "old"}, {n: 2, s: "new"}], + [{n: 1, s: {deep: 1}}, {n: 2, s: "new"}], + [{n: 1, s: [1]}, {n: 2, s: "new"}], + ], +} + +{ + name: "passThrough merges nested outputs into nested input objects", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["customer.tier", "customer.flags.vip"], rules: [ + ["'gold'", "true"], + ]}, + ], + }, + cases: [ + [{customer: {name: "Ann", tier: "basic"}}, {customer: {name: "Ann", tier: "gold", flags: {vip: true}}}], + [{customer: {flags: {new: true}}}, {customer: {tier: "gold", flags: {new: true, vip: true}}}], + [{customer: "scalar"}, {customer: {tier: "gold", flags: {vip: true}}}], + [{}, {customer: {tier: "gold", flags: {vip: true}}}], + ], +} + +{ + name: "passThrough: an output object merges with, not replaces, the input object", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["cfg"], rules: [ + ["{b: 2, c: {d: 4}}"], + ]}, + ], + }, + cases: [ + [{cfg: {a: 1, c: {e: 5}}}, {cfg: {a: 1, b: 2, c: {d: 4, e: 5}}}], + [{cfg: [1]}, {cfg: {b: 2, c: {d: 4}}}], + ], +} + +{ + name: "passThrough: an output array replaces the input array", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["list"], rules: [ + ["[3]"], + ]}, + ], + }, + cases: [ + [{list: [1, 2]}, {list: [3]}], + [{list: {a: 1}}, {list: [3]}], + ], +} + +{ + name: "passThrough: a top-level null output removes the input field", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["a", "keep"], rules: [ + ["null", "1"], + ]}, + ], + }, + cases: [ + [{a: 1, b: 2}, {b: 2, keep: 1}], + [{b: 2}, {b: 2, keep: 1}], + ], +} + +{ + name: "passThrough: a nested null output removes the nested input field", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["r.a"], rules: [ + ["null"], + ]}, + ], + }, + cases: [ + [{r: {a: 1, b: 2}}, {r: {b: 2}}], + [{}, {r: {a: null}}, "question: with no input object to merge into, the nested null is kept"], + ], +} + +{ + name: "passThrough with no matching row returns the input unchanged", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["n"], outputs: ["a"], rules: [ + ["> 0", "1"], + ]}, + ], + }, + cases: [ + [{n: 0, a: "kept"}, {n: 0, a: "kept"}], + [{n: 1, a: "kept"}, {n: 1, a: 1}], + [{}, {}], + ], +} + +{ + name: "passThrough with outputPath nests the outputs next to the input", + graph: { + nodes: [ + {table: "t", passThrough: true, outputPath: "result", inputs: ["n"], outputs: ["tier", "x.y"], rules: [ + ["> 0", "'p'", "1"], + ]}, + ], + }, + cases: [ + [{n: 1}, {n: 1, result: {tier: "p", x: {y: 1}}}], + [{n: 1, result: {old: true}}, {n: 1, result: {old: true, tier: "p", x: {y: 1}}}], + [{n: 0, result: {old: true}}, {n: 0}, "question: no match writes result: null, which removes the input's result under passThrough"], + ], +} + +{ + name: "outputPath with a dotted path", + graph: { + nodes: [ + {table: "t", outputPath: "a.b", inputs: [], outputs: ["c"], rules: [ + ["1"], + ]}, + ], + }, + cases: [ + [{}, {a: {b: {c: 1}}}], + [{a: 1}, {a: {b: {c: 1}}}], + ], +} + +{ + name: "passThrough keeps the input when the table runs on a sub-object via inputField", + graph: { + nodes: [ + {table: "t", passThrough: true, inputField: "customer", inputs: ["age"], outputs: ["adult"], rules: [ + [">= 18", "true"], + ["", "false"], + ]}, + ], + }, + cases: [ + [{customer: {age: 20}, other: 1}, {customer: {age: 20}, other: 1, adult: true}], + [{customer: {age: 3}}, {customer: {age: 3}, adult: false}], + [{}, {adult: false}], + ], +} + +{ + name: "loop mode with passThrough merges each row's output into its item", + graph: { + nodes: [ + {table: "t", passThrough: true, executionMode: "loop", inputField: "items", outputPath: "items", inputs: ["price"], outputs: ["band", "tags[]"], rules: [ + ["> 100", "'high'", "'expensive'"], + ["", "'normal'", "'item'"], + ]}, + ], + }, + cases: [ + [{items: [{price: 150}, {price: 10}]}, {items: [{price: 150, band: "high", tags: ["expensive", "item"]}, {price: 10, band: "normal", tags: ["item"]}]}], + [{items: []}, {items: []}], + [{items: [{}]}, {items: [{band: "normal", tags: ["item"]}]}], + ], +} + +// --------------------------------------------------------------------------------------- +// Table outputs flowing into later nodes. +// --------------------------------------------------------------------------------------- + +{ + name: "a downstream expression sees nested table outputs", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r.v", "tags[]"], rules: [ + ["> 0", "n * 2", "'a'"], + ["", "0", "'b'"], + ]}, + {expression: "e", fields: {v: "r.v", count: "len(tags)"}}, + ], + }, + cases: [ + [{n: 3}, {v: 6, count: 2}], + [{n: 0}, {v: 0, count: 1}], + ], +} + +{ + name: "a downstream node does not see the table input, and sees an empty object after no match", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ]}, + {expression: "e", fields: {hasV: "v != null", n: "n"}}, + ], + }, + cases: [ + [{n: 1}, {hasV: true}], + [{n: 0}, {hasV: false}], + ], +} + +{ + name: "a downstream expression iterates collect table rows via outputPath", + graph: { + nodes: [ + {table: "t", hit: "collect", outputPath: "rows", inputs: ["n"], outputs: ["w"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ["> 2", "4"], + ]}, + {expression: "e", fields: {total: "sum(map(rows, #.w))"}}, + ], + }, + cases: [ + [{n: 3}, {total: 7}], + [{n: 1}, {total: 1}], + [{n: 0}, {total: 0}], + ], +} diff --git a/core/engine/tests/spec/graph/08-switch-first.json5 b/core/engine/tests/spec/graph/08-switch-first.json5 new file mode 100644 index 00000000..dcfef88e --- /dev/null +++ b/core/engine/tests/spec/graph/08-switch-first.json5 @@ -0,0 +1,950 @@ +// Switch node, hit policy first: conditions are evaluated in order and only the first one +// that is true routes; `""` is the default branch and is always true. The switch passes its +// input unchanged to the chosen branch. Edges of branches not taken are pruned, along with +// the nodes that become unreachable through them. + +// --------------------------------------------------------------------------------------- +// Condition order: the first true condition wins even when later ones also hold. +// --------------------------------------------------------------------------------------- + +{ + name: "the first true condition wins", + graph: { + nodes: [ + {switch: "s", when: ["n > 10", "n > 5", "n > 0"]}, + {expression: "a", fields: {branch: "'gt10'"}}, + {expression: "b", fields: {branch: "'gt5'"}}, + {expression: "c", fields: {branch: "'gt0'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output"], + }, + cases: [ + [{n: 11}, {branch: "gt10"}], + [{n: 10}, {branch: "gt5"}], + [{n: 6}, {branch: "gt5"}], + [{n: 5}, {branch: "gt0"}], + [{n: 0.5}, {branch: "gt0"}], + [{n: 1000000000000000000000}, {branch: "gt10"}], + ], +} + +{ + name: "reordering conditions changes the winner", + graph: { + nodes: [ + {switch: "s", when: ["n > 0", "n > 5", "n > 10"]}, + {expression: "a", fields: {branch: "'gt0'"}}, + {expression: "b", fields: {branch: "'gt5'"}}, + {expression: "c", fields: {branch: "'gt10'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output"], + }, + cases: [ + [{n: 11}, {branch: "gt0"}], + [{n: 6}, {branch: "gt0"}], + [{n: 1}, {branch: "gt0"}], + ], +} + +{ + name: "conditions over several fields", + graph: { + nodes: [ + {switch: "s", when: ["country == 'US' and age >= 21", "country != 'US' and age >= 18", ""]}, + {expression: "us", fields: {allowed: "true", rule: "'us'"}}, + {expression: "intl", fields: {allowed: "true", rule: "'intl'"}}, + {expression: "deny", fields: {allowed: "false", rule: "'deny'"}}, + ], + edges: ["input -> s", "s:0 -> us -> output", "s:1 -> intl -> output", "s:2 -> deny -> output"], + }, + cases: [ + [{country: "US", age: 21}, {allowed: true, rule: "us"}], + [{country: "US", age: 20}, {allowed: false, rule: "deny"}], + [{country: "DE", age: 18}, {allowed: true, rule: "intl"}], + [{country: "DE", age: 17}, {allowed: false, rule: "deny"}], + [{age: 30}, {allowed: true, rule: "intl"}], + [{}, {allowed: false, rule: "deny"}], + ], +} + +{ + name: "conditions over nested and array input", + graph: { + nodes: [ + {switch: "s", when: ["customer.tier == 'gold'", "len(orders) > 2", "some(orders, #.total > 100)", ""]}, + {expression: "a", fields: {r: "'gold'"}}, + {expression: "b", fields: {r: "'frequent'"}}, + {expression: "c", fields: {r: "'big'"}}, + {expression: "d", fields: {r: "'other'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output", "s:3 -> d -> output"], + }, + cases: [ + [{customer: {tier: "gold"}, orders: []}, {r: "gold"}], + [{customer: {tier: "basic"}, orders: [{total: 1}, {total: 2}, {total: 3}]}, {r: "frequent"}], + [{customer: {tier: "basic"}, orders: [{total: 101}]}, {r: "big"}], + [{customer: {tier: "basic"}, orders: [{total: 100}]}, {r: "other"}], + [{customer: {}, orders: []}, {r: "other"}], + ], +} + +// --------------------------------------------------------------------------------------- +// The default branch `""` is always true. Under first hit its position matters: placed +// before other conditions it shadows them. +// --------------------------------------------------------------------------------------- + +{ + name: "the default branch catches everything not matched before it", + graph: { + nodes: [ + {switch: "s", when: ["n > 0", ""]}, + {expression: "pos", fields: {r: "'pos'"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> pos -> output", "s:1 -> def -> output"], + }, + cases: [ + [{n: 1}, {r: "pos"}], + [{n: 0}, {r: "default"}], + [{n: -1}, {r: "default"}], + [{}, {r: "default"}], + [{n: "x"}, {r: "default"}], + ], +} + +{ + name: "a default branch first shadows every later condition", + graph: { + nodes: [ + {switch: "s", when: ["", "n > 0"]}, + {expression: "def", fields: {r: "'default'"}}, + {expression: "pos", fields: {r: "'pos'"}}, + ], + edges: ["input -> s", "s:0 -> def -> output", "s:1 -> pos -> output"], + }, + cases: [ + [{n: 1}, {r: "default"}], + [{n: 0}, {r: "default"}], + [{}, {r: "default"}], + ], +} + +{ + name: "a default branch in the middle shadows the conditions after it", + graph: { + nodes: [ + {switch: "s", when: ["n > 10", "", "n > 0"]}, + {expression: "big", fields: {r: "'big'"}}, + {expression: "def", fields: {r: "'default'"}}, + {expression: "pos", fields: {r: "'pos'"}}, + ], + edges: ["input -> s", "s:0 -> big -> output", "s:1 -> def -> output", "s:2 -> pos -> output"], + }, + cases: [ + [{n: 11}, {r: "big"}], + [{n: 5}, {r: "default"}], + [{n: -5}, {r: "default"}], + ], +} + +{ + name: "a whitespace-only condition is not a default branch", + graph: { + nodes: [ + {switch: "s", when: [" ", ""]}, + {expression: "blank", fields: {r: "'blank'"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> blank -> output", "s:1 -> def -> output"], + }, + cases: [ + [{}, {r: "default"}, "question: a condition of only whitespace is evaluated (and fails) rather than treated as the default branch"], + [{n: 1}, {r: "default"}, "question: a condition of only whitespace is evaluated (and fails) rather than treated as the default branch"], + ], +} + +{ + name: "a switch with only a default branch always routes", + graph: { + nodes: [ + {switch: "s", when: [""]}, + {expression: "e", fields: {r: "'taken'", n: "n"}}, + ], + edges: ["input -> s -> output", "s:0 -> e -> output"], + }, + cases: [ + [{n: 1}, {r: "taken", n: 1}], + [{}, {r: "taken"}], + ], +} + +// --------------------------------------------------------------------------------------- +// The switch output is its input: the chosen branch sees exactly what reached the switch. +// --------------------------------------------------------------------------------------- + +{ + name: "a branch straight to the output passes the input through", + graph: { + nodes: [ + {switch: "s", when: ["flag", ""]}, + {expression: "other", fields: {r: "'other'"}}, + ], + edges: ["input -> s", "s:0 -> output", "s:1 -> other -> output"], + }, + cases: [ + [{flag: true, x: 1}, {flag: true, x: 1}], + [{flag: true, nested: {a: [1, 2]}}, {flag: true, nested: {a: [1, 2]}}], + [{flag: false, x: 1}, {r: "other"}], + [{x: 1}, {r: "other"}], + ], +} + +{ + name: "the switch routes on the output of an upstream node", + graph: { + nodes: [ + {expression: "calc", fields: {score: "a + b"}}, + {switch: "s", when: ["score >= 10", ""]}, + {expression: "high", fields: {band: "'high'", score: "score", a: "a"}}, + {expression: "low", fields: {band: "'low'", score: "score"}}, + ], + edges: ["input -> calc -> s", "s:0 -> high -> output", "s:1 -> low -> output"], + }, + cases: [ + [{a: 5, b: 5}, {band: "high", score: 10}], + [{a: 5, b: 4}, {band: "low", score: 9}], + [{a: 0, b: 0, score: 100}, {band: "low", score: 0}], + ], +} + +{ + name: "the switch routes on a passThrough upstream node", + graph: { + nodes: [ + {expression: "calc", passThrough: true, fields: {score: "a + b"}}, + {switch: "s", when: ["score >= 10", ""]}, + {expression: "high", passThrough: true, fields: {band: "'high'"}}, + {expression: "low", passThrough: true, fields: {band: "'low'"}}, + ], + edges: ["input -> calc -> s", "s:0 -> high -> output", "s:1 -> low -> output"], + }, + cases: [ + [{a: 5, b: 5}, {a: 5, b: 5, score: 10, band: "high"}], + [{a: 1, b: 1}, {a: 1, b: 1, score: 2, band: "low"}], + ], +} + +{ + name: "conditions see $nodes of earlier nodes", + graph: { + nodes: [ + {expression: "calc", fields: {score: "a * 2"}}, + {switch: "s", when: ["$nodes.calc.score > 10", "$nodes.input.a > 0", ""]}, + {expression: "x", fields: {r: "'score'"}}, + {expression: "y", fields: {r: "'a'"}}, + {expression: "z", fields: {r: "'none'"}}, + ], + edges: ["input -> calc -> s", "s:0 -> x -> output", "s:1 -> y -> output", "s:2 -> z -> output"], + }, + cases: [ + [{a: 6}, {r: "score"}], + [{a: 5}, {r: "a"}], + [{a: 0}, {r: "none"}], + [{a: -1}, {r: "none"}], + ], +} + +// --------------------------------------------------------------------------------------- +// No branch matches: every outgoing edge is pruned and the output is never reached. +// --------------------------------------------------------------------------------------- + +{ + name: "no branch matching and no default", + graph: { + nodes: [ + {switch: "s", when: ["n > 10", "n < -10"]}, + {expression: "a", fields: {r: "'big'"}}, + {expression: "b", fields: {r: "'small'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{n: 11}, {r: "big"}], + [{n: -11}, {r: "small"}], + [{n: 0}, {}], + [{}, {}], + ], +} + +{ + name: "no branch matching with a branch straight to the output", + graph: { + nodes: [ + {switch: "s", when: ["ok"]}, + ], + edges: ["input -> s", "s:0 -> output"], + }, + cases: [ + [{ok: true, v: 1}, {ok: true, v: 1}], + [{ok: false, v: 1}, {}], + [{v: 1}, {}], + ], +} + +{ + name: "no branch matching while a parallel path still reaches the output", + graph: { + nodes: [ + {switch: "s", when: ["n > 0"]}, + {expression: "pos", fields: {pos: "true"}}, + {expression: "side", fields: {side: "n"}}, + ], + edges: ["input -> s", "s:0 -> pos -> output", "input -> side -> output"], + }, + cases: [ + [{n: 1}, {pos: true, side: 1}], + [{n: 0}, {side: 0}], + [{}, {}], + ], +} + +{ + name: "a switch with no conditions routes nowhere", + graph: { + nodes: [ + {switch: "s", when: []}, + {expression: "side", fields: {side: "true"}}, + ], + edges: ["input -> s", "input -> side -> output"], + }, + cases: [ + [{}, {side: true}], + [{n: 1}, {n: 1, side: true}, "question: a switch with no outgoing edges is a leaf, so its pass-through input is merged into the graph result"], + ], +} + +// --------------------------------------------------------------------------------------- +// Unconnected branches: a matched branch without an edge ends the switch path there. +// Edges leaving a switch without a branch handle are never followed. +// --------------------------------------------------------------------------------------- + +{ + name: "a matched branch with no edge stops the flow", + graph: { + nodes: [ + {switch: "s", when: ["n > 10", "n > 0", ""]}, + {expression: "pos", fields: {r: "'pos'"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:1 -> pos -> output", "s:2 -> def -> output"], + }, + cases: [ + [{n: 11}, {}, "question: the first branch matched but has no edge; the graph returns an empty object rather than an error or the default branch"], + [{n: 5}, {r: "pos"}], + [{n: 0}, {r: "default"}], + ], +} + +{ + name: "an unconnected matched branch next to a parallel path", + graph: { + nodes: [ + {switch: "s", when: ["n > 0", ""]}, + {expression: "def", fields: {r: "'default'"}}, + {expression: "side", fields: {side: "n"}}, + ], + edges: ["input -> s", "s:1 -> def -> output", "input -> side -> output"], + }, + cases: [ + [{n: 1}, {side: 1}], + [{n: 0}, {r: "default", side: 0}], + ], +} + +{ + name: "an edge from a switch without a branch handle is never followed", + graph: { + nodes: [ + {switch: "s", when: [""]}, + {expression: "e", fields: {r: "'via handle'"}}, + {expression: "plain", fields: {plain: "true"}}, + ], + edges: ["input -> s", "s:0 -> e -> output", "s -> plain -> output"], + }, + cases: [ + [{}, {r: "via handle"}], + [{n: 1}, {r: "via handle"}], + ], +} + +{ + name: "a switch connected only by a handle-less edge", + graph: { + nodes: [ + {switch: "s", when: [""]}, + ], + edges: ["input -> s -> output"], + }, + cases: [ + [{a: 1}, {}, "question: the plain edge is pruned like an unmatched branch, so the flow ends at the switch"], + ], +} + +{ + name: "an edge with an unknown branch handle is never followed", + graph: { + raw: { + nodes: [ + {id: "in", name: "input", type: "inputNode", content: {}}, + {id: "s", name: "s", type: "switchNode", content: {hitPolicy: "first", statements: [{id: "yes", condition: ""}]}}, + {id: "a", name: "a", type: "expressionNode", content: {expressions: [{id: "x", key: "r", value: "'a'"}]}}, + {id: "b", name: "b", type: "expressionNode", content: {expressions: [{id: "x", key: "r", value: "'b'"}]}}, + {id: "out", name: "output", type: "outputNode", content: {}}, + ], + edges: [ + {id: "e0", sourceId: "in", targetId: "s"}, + {id: "e1", sourceId: "s", targetId: "a", sourceHandle: "yes"}, + {id: "e2", sourceId: "s", targetId: "b", sourceHandle: "nope"}, + {id: "e3", sourceId: "a", targetId: "out"}, + {id: "e4", sourceId: "b", targetId: "out"}, + ], + }, + }, + cases: [ + [{}, {r: "a"}], + [{r: "x"}, {r: "a"}], + ], +} + +{ + name: "statement ids are matched as handles, whatever their shape", + graph: { + raw: { + nodes: [ + {id: "in", name: "input", type: "inputNode", content: {}}, + {id: "s", name: "s", type: "switchNode", content: {statements: [ + {id: "b-1", condition: "v == 1"}, + {id: "b 2", condition: "v == 2"}, + {id: "", condition: ""}, + ]}}, + {id: "a", name: "a", type: "expressionNode", content: {expressions: [{id: "x", key: "r", value: "'one'"}]}}, + {id: "b", name: "b", type: "expressionNode", content: {expressions: [{id: "x", key: "r", value: "'two'"}]}}, + {id: "c", name: "c", type: "expressionNode", content: {expressions: [{id: "x", key: "r", value: "'other'"}]}}, + {id: "out", name: "output", type: "outputNode", content: {}}, + ], + edges: [ + {id: "e0", sourceId: "in", targetId: "s"}, + {id: "e1", sourceId: "s", targetId: "a", sourceHandle: "b-1"}, + {id: "e2", sourceId: "s", targetId: "b", sourceHandle: "b 2"}, + {id: "e3", sourceId: "s", targetId: "c", sourceHandle: ""}, + {id: "e4", sourceId: "a", targetId: "out"}, + {id: "e5", sourceId: "b", targetId: "out"}, + {id: "e6", sourceId: "c", targetId: "out"}, + ], + }, + }, + cases: [ + [{v: 1}, {r: "one"}], + [{v: 2}, {r: "two"}], + [{v: 3}, {r: "other"}], + ], +} + +{ + name: "a switch without hitPolicy defaults to first", + graph: { + raw: { + nodes: [ + {id: "in", name: "input", type: "inputNode", content: {}}, + {id: "s", name: "s", type: "switchNode", content: {statements: [ + {id: "a", condition: "v > 0"}, + {id: "b", condition: "v > 1"}, + ]}}, + {id: "na", name: "na", type: "expressionNode", content: {expressions: [{id: "x", key: "a", value: "true"}]}}, + {id: "nb", name: "nb", type: "expressionNode", content: {expressions: [{id: "x", key: "b", value: "true"}]}}, + {id: "out", name: "output", type: "outputNode", content: {}}, + ], + edges: [ + {id: "e0", sourceId: "in", targetId: "s"}, + {id: "e1", sourceId: "s", targetId: "na", sourceHandle: "a"}, + {id: "e2", sourceId: "s", targetId: "nb", sourceHandle: "b"}, + {id: "e3", sourceId: "na", targetId: "out"}, + {id: "e4", sourceId: "nb", targetId: "out"}, + ], + }, + }, + cases: [ + [{v: 2}, {a: true}], + [{v: 1}, {a: true}], + [{v: 0}, {}], + ], +} + +// --------------------------------------------------------------------------------------- +// Branches leading to different kinds of nodes, and one branch fanning out. +// --------------------------------------------------------------------------------------- + +{ + name: "branches into a table and an expression", + graph: { + nodes: [ + {switch: "s", when: ["kind == 'table'", ""]}, + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["> 0", "'positive'"], + ["", "'non-positive'"], + ]}, + {expression: "e", fields: {r: "'expr'", v: "v"}}, + ], + edges: ["input -> s", "s:0 -> t -> output", "s:1 -> e -> output"], + }, + cases: [ + [{kind: "table", v: 1}, {r: "positive"}], + [{kind: "table", v: 0}, {r: "non-positive"}], + [{kind: "expr", v: 2}, {r: "expr", v: 2}], + [{v: 2}, {r: "expr", v: 2}], + ], +} + +{ + name: "a branch into a sub-decision", + decisions: { + child: {nodes: [{expression: "inner", fields: {doubled: "v * 2"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["v != null", ""]}, + {decision: "call", key: "child"}, + {expression: "none", fields: {doubled: "0"}}, + ], + edges: ["input -> s", "s:0 -> call -> output", "s:1 -> none -> output"], + }, + cases: [ + [{v: 4}, {doubled: 8}], + [{v: 0}, {doubled: 0}], + [{}, {doubled: 0}], + ], +} + +{ + name: "a branch into a function node", + graph: { + nodes: [ + {switch: "s", when: ["useFn", ""]}, + {function: "f", source: """export const handler = async (input) => ({ fn: true, v: input.v });"""}, + {expression: "e", fields: {fn: "false"}}, + ], + edges: ["input -> s", "s:0 -> f -> output", "s:1 -> e -> output"], + }, + cases: [ + [{useFn: true, v: 3}, {fn: true, v: 3}], + [{useFn: false, v: 3}, {fn: false}], + ], +} + +{ + name: "one branch fanning out to two nodes merges both", + graph: { + nodes: [ + {switch: "s", when: ["n > 0", ""]}, + {expression: "a", fields: {a: "n"}}, + {expression: "b", fields: {b: "n * 2"}}, + {expression: "c", fields: {c: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:0 -> b -> output", "s:1 -> c -> output"], + }, + cases: [ + [{n: 2}, {a: 2, b: 4}], + [{n: 0}, {c: "default"}], + ], +} + +{ + name: "two branches leading to the same node", + graph: { + nodes: [ + {switch: "s", when: ["n > 10", "n > 0", ""]}, + {expression: "shared", fields: {r: "'shared'", n: "n"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> shared -> output", "s:1 -> shared", "s:2 -> def -> output"], + }, + cases: [ + [{n: 11}, {r: "shared", n: 11}], + [{n: 5}, {r: "shared", n: 5}], + [{n: 0}, {r: "default"}], + ], +} + +{ + name: "branches that rejoin a common downstream node", + graph: { + nodes: [ + {switch: "s", when: ["vip", ""]}, + {expression: "v", passThrough: true, fields: {discount: "0.2"}}, + {expression: "r", passThrough: true, fields: {discount: "0.05"}}, + {expression: "price", fields: {price: "base * (1 - discount)"}}, + ], + edges: ["input -> s", "s:0 -> v -> price", "s:1 -> r -> price", "price -> output"], + }, + cases: [ + [{vip: true, base: 100}, {price: 80}], + [{vip: false, base: 100}, {price: 95}], + [{base: 10}, {price: 9.5}], + ], +} + +{ + name: "a node fed by both the switch input and a branch", + graph: { + nodes: [ + {expression: "pre", fields: {pre: "n + 1"}}, + {switch: "s", when: ["n > 0", ""]}, + {expression: "pos", fields: {kind: "'pos'"}}, + {expression: "neg", fields: {kind: "'neg'"}}, + {expression: "join", fields: {both: "kind + ':' + string(pre)"}}, + ], + edges: ["input -> pre -> join", "input -> s", "s:0 -> pos -> join", "s:1 -> neg -> join", "join -> output"], + }, + cases: [ + [{n: 1}, {both: "pos:2"}], + [{n: 0}, {both: "neg:1"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Nested switches: an inner switch only runs when its branch was taken. +// --------------------------------------------------------------------------------------- + +{ + name: "a switch inside a branch of another switch", + graph: { + nodes: [ + {switch: "outer", when: ["age >= 18", ""]}, + {switch: "inner", when: ["income > 50000", ""]}, + {expression: "rich", fields: {r: "'adult-high'"}}, + {expression: "poor", fields: {r: "'adult-low'"}}, + {expression: "minor", fields: {r: "'minor'"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "inner:0 -> rich -> output", "inner:1 -> poor -> output", "outer:1 -> minor -> output"], + }, + cases: [ + [{age: 30, income: 60000}, {r: "adult-high"}], + [{age: 30, income: 50000}, {r: "adult-low"}], + [{age: 30}, {r: "adult-low"}], + [{age: 10, income: 99999}, {r: "minor"}], + [{}, {r: "minor"}], + ], +} + +{ + name: "three levels of switches", + graph: { + nodes: [ + {switch: "a", when: ["x > 0", ""]}, + {switch: "b", when: ["y > 0", ""]}, + {switch: "c", when: ["z > 0", ""]}, + {expression: "ppp", fields: {r: "'+++'"}}, + {expression: "ppn", fields: {r: "'++-'"}}, + {expression: "pn", fields: {r: "'+-'"}}, + {expression: "n", fields: {r: "'-'"}}, + ], + edges: [ + "input -> a", + "a:0 -> b", "a:1 -> n -> output", + "b:0 -> c", "b:1 -> pn -> output", + "c:0 -> ppp -> output", "c:1 -> ppn -> output", + ], + }, + cases: [ + [{x: 1, y: 1, z: 1}, {r: "+++"}], + [{x: 1, y: 1, z: 0}, {r: "++-"}], + [{x: 1, y: 0, z: 1}, {r: "+-"}], + [{x: 0, y: 1, z: 1}, {r: "-"}], + [{}, {r: "-"}], + ], +} + +{ + name: "an inner switch with no match inside a taken branch", + graph: { + nodes: [ + {switch: "outer", when: ["go", ""]}, + {switch: "inner", when: ["n > 0"]}, + {expression: "pos", fields: {r: "'pos'"}}, + {expression: "skip", fields: {r: "'skipped'"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "inner:0 -> pos -> output", "outer:1 -> skip -> output"], + }, + cases: [ + [{go: true, n: 1}, {r: "pos"}], + [{go: true, n: 0}, {}], + [{go: false, n: 1}, {r: "skipped"}], + ], +} + +{ + name: "consecutive switches on a single path", + graph: { + nodes: [ + {switch: "s1", when: ["a", ""]}, + {expression: "x1", passThrough: true, fields: {first: "'a'"}}, + {expression: "y1", passThrough: true, fields: {first: "'not a'"}}, + {switch: "s2", when: ["b", ""]}, + {expression: "x2", passThrough: true, fields: {second: "'b'"}}, + {expression: "y2", passThrough: true, fields: {second: "'not b'"}}, + ], + edges: [ + "input -> s1", "s1:0 -> x1 -> s2", "s1:1 -> y1 -> s2", + "s2:0 -> x2 -> output", "s2:1 -> y2 -> output", + ], + }, + cases: [ + [{a: true, b: true}, {a: true, b: true, first: "a", second: "b"}], + [{a: true, b: false}, {a: true, b: false, first: "a", second: "not b"}], + [{a: false, b: true}, {a: false, b: true, first: "not a", second: "b"}], + [{}, {first: "not a", second: "not b"}], + ], +} + +{ + name: "the second switch routes on what the first branch wrote", + graph: { + nodes: [ + {switch: "s1", when: ["n > 0", ""]}, + {expression: "pos", fields: {sign: "'+'", n: "n"}}, + {expression: "neg", fields: {sign: "'-'", n: "n"}}, + {switch: "s2", when: ["sign == '+' and n > 100", "sign == '+'", ""]}, + {expression: "huge", fields: {r: "'huge'"}}, + {expression: "plus", fields: {r: "'plus'"}}, + {expression: "rest", fields: {r: "sign"}}, + ], + edges: [ + "input -> s1", "s1:0 -> pos -> s2", "s1:1 -> neg -> s2", + "s2:0 -> huge -> output", "s2:1 -> plus -> output", "s2:2 -> rest -> output", + ], + }, + cases: [ + [{n: 101}, {r: "huge"}], + [{n: 1}, {r: "plus"}], + [{n: 0}, {r: "-"}], + [{n: -500}, {r: "-"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Null and missing input in conditions: a condition is taken only when it yields true. +// --------------------------------------------------------------------------------------- + +{ + name: "comparisons against missing or null fields are not taken", + graph: { + nodes: [ + {switch: "s", when: ["age >= 18", "age < 18", ""]}, + {expression: "adult", fields: {r: "'adult'"}}, + {expression: "minor", fields: {r: "'minor'"}}, + {expression: "unknown", fields: {r: "'unknown'"}}, + ], + edges: ["input -> s", "s:0 -> adult -> output", "s:1 -> minor -> output", "s:2 -> unknown -> output"], + }, + cases: [ + [{age: 18}, {r: "adult"}], + [{age: 17}, {r: "minor"}], + [{}, {r: "unknown"}], + [{age: null}, {r: "unknown"}], + [{age: "18"}, {r: "unknown"}], + ], +} + +{ + name: "null checks route missing values", + graph: { + nodes: [ + {switch: "s", when: ["v == null", "v != null"]}, + {expression: "missing", fields: {r: "'missing'"}}, + {expression: "present", fields: {r: "'present'"}}, + ], + edges: ["input -> s", "s:0 -> missing -> output", "s:1 -> present -> output"], + }, + cases: [ + [{}, {r: "missing"}], + [{v: null}, {r: "missing"}], + [{v: 0}, {r: "present"}], + [{v: false}, {r: "present"}], + [{v: ""}, {r: "present"}], + [{v: []}, {r: "present"}], + ], +} + +{ + name: "conditions on missing nested paths", + graph: { + nodes: [ + {switch: "s", when: ["a.b.c == 1", "a.b == null", ""]}, + {expression: "deep", fields: {r: "'deep'"}}, + {expression: "nob", fields: {r: "'no b'"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> deep -> output", "s:1 -> nob -> output", "s:2 -> def -> output"], + }, + cases: [ + [{a: {b: {c: 1}}}, {r: "deep"}], + [{a: {b: {c: 2}}}, {r: "default"}], + [{a: {}}, {r: "no b"}], + [{}, {r: "no b"}], + [{a: 5}, {r: "no b"}], + ], +} + +{ + name: "a bare field as condition is taken only when it is true", + graph: { + nodes: [ + {switch: "s", when: ["flag", ""]}, + {expression: "yes", fields: {r: "'yes'"}}, + {expression: "no", fields: {r: "'no'"}}, + ], + edges: ["input -> s", "s:0 -> yes -> output", "s:1 -> no -> output"], + }, + cases: [ + [{flag: true}, {r: "yes"}], + [{flag: false}, {r: "no"}], + [{}, {r: "no"}], + [{flag: null}, {r: "no"}], + [{flag: 1}, {r: "no"}], + [{flag: "true"}, {r: "no"}], + [{flag: [true]}, {r: "no"}], + [{flag: {}}, {r: "no"}], + ], +} + +{ + name: "a condition yielding a non-boolean is not taken", + graph: { + nodes: [ + {switch: "s", when: ["n", "'text'", "[1]", "n + 1", ""]}, + {expression: "a", fields: {r: "0"}}, + {expression: "b", fields: {r: "1"}}, + {expression: "c", fields: {r: "2"}}, + {expression: "d", fields: {r: "3"}}, + {expression: "e", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output", "s:3 -> d -> output", "s:4 -> e -> output"], + }, + cases: [ + [{n: 1}, {r: "default"}], + [{n: 0}, {r: "default"}], + [{}, {r: "default"}], + ], +} + +{ + name: "conditions over empty or missing lists", + graph: { + nodes: [ + {switch: "s", when: ["items == null", "len(items) == 0", ""]}, + {expression: "missing", fields: {r: "'missing'"}}, + {expression: "empty", fields: {r: "'empty'"}}, + {expression: "full", fields: {r: "'full'"}}, + ], + edges: ["input -> s", "s:0 -> missing -> output", "s:1 -> empty -> output", "s:2 -> full -> output"], + }, + cases: [ + [{}, {r: "missing"}], + [{items: null}, {r: "missing"}], + [{items: []}, {r: "empty"}], + [{items: [1]}, {r: "full"}], + [{items: ""}, {r: "empty"}], + [{items: 5}, {r: "full"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Condition errors: an erroring condition counts as false and evaluation continues with +// the next condition; it does not fail the graph. +// --------------------------------------------------------------------------------------- + +{ + name: "an erroring condition is skipped", + graph: { + nodes: [ + {switch: "s", when: ["date('nope') > 1", "n > 0", ""]}, + {expression: "err", fields: {r: "'err'"}}, + {expression: "pos", fields: {r: "'pos'"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> err -> output", "s:1 -> pos -> output", "s:2 -> def -> output"], + }, + cases: [ + [{n: 1}, {r: "pos"}], + [{n: 0}, {r: "default"}], + ], +} + +{ + name: "a syntax error in a condition is skipped", + graph: { + nodes: [ + {switch: "s", when: ["n >", "n > 0", ""]}, + {expression: "err", fields: {r: "'err'"}}, + {expression: "pos", fields: {r: "'pos'"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> err -> output", "s:1 -> pos -> output", "s:2 -> def -> output"], + }, + cases: [ + [{n: 1}, {r: "pos"}, "question: a condition that does not parse is silently false; no validation error is raised"], + [{n: 0}, {r: "default"}, "question: a condition that does not parse is silently false; no validation error is raised"], + ], +} + +{ + name: "a type error depending on the input is skipped", + graph: { + nodes: [ + {switch: "s", when: ["n + 1 > 5", ""]}, + {expression: "big", fields: {r: "'big'"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> big -> output", "s:1 -> def -> output"], + }, + cases: [ + [{n: 5}, {r: "big"}], + [{n: 4}, {r: "default"}], + [{n: "x"}, {r: "default"}], + [{n: [1]}, {r: "default"}], + [{n: {}}, {r: "default"}], + ], +} + +{ + name: "an error in a chosen branch still fails the graph", + graph: { + nodes: [ + {switch: "s", when: ["fail", ""]}, + {expression: "bad", fields: {r: "date('nope')"}}, + {expression: "ok", fields: {r: "'ok'"}}, + ], + edges: ["input -> s", "s:0 -> bad -> output", "s:1 -> ok -> output"], + }, + cases: [ + [{fail: true}, "!error"], + [{fail: false}, {r: "ok"}], + ], +} + +{ + name: "an error in a branch not taken does not fail the graph", + graph: { + nodes: [ + {switch: "s", when: ["n > 0", ""]}, + {expression: "bad", fields: {r: "n + 'x' + date('nope')"}}, + {custom: "boom", kind: "fail", config: {message: "should not run"}}, + {expression: "ok", fields: {r: "'ok'"}}, + ], + edges: ["input -> s", "s:0 -> ok -> output", "s:1 -> bad -> output", "s:1 -> boom -> output"], + }, + cases: [ + [{n: 1}, {r: "ok"}], + [{n: 0}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/09-switch-collect.json5 b/core/engine/tests/spec/graph/09-switch-collect.json5 new file mode 100644 index 00000000..67a6c881 --- /dev/null +++ b/core/engine/tests/spec/graph/09-switch-collect.json5 @@ -0,0 +1,781 @@ +// Switch node, hit policy collect: every condition that is true routes, so several branches +// run in parallel and their results meet at the output (or at a shared node), where they +// are merged. `""` is always true and is therefore always taken under collect. + +// --------------------------------------------------------------------------------------- +// Multiple branches taken: each true condition routes; results merge at the output. +// --------------------------------------------------------------------------------------- + +{ + name: "every true condition routes", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", "n > 10", "n % 2 == 0"]}, + {expression: "pos", fields: {pos: "true"}}, + {expression: "big", fields: {big: "true"}}, + {expression: "even", fields: {even: "true"}}, + ], + edges: ["input -> s", "s:0 -> pos -> output", "s:1 -> big -> output", "s:2 -> even -> output"], + }, + cases: [ + [{n: 12}, {pos: true, big: true, even: true}], + [{n: 11}, {pos: true, big: true}], + [{n: 2}, {pos: true, even: true}], + [{n: 1}, {pos: true}], + [{n: 0}, {even: true}], + [{n: -3}, {}], + ], +} + +{ + name: "collect with one branch taken behaves like first", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["kind == 'a'", "kind == 'b'"]}, + {expression: "a", fields: {r: "'a'", v: "v"}}, + {expression: "b", fields: {r: "'b'", v: "v * 10"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{kind: "a", v: 1}, {r: "a", v: 1}], + [{kind: "b", v: 1}, {r: "b", v: 10}], + [{kind: "c", v: 1}, {}], + [{v: 1}, {}], + ], +} + +{ + name: "each branch sees the same switch input", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["true", "true"]}, + {expression: "a", fields: {fromA: "x"}}, + {expression: "b", fields: {fromB: "x * 2"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{x: 1}, {fromA: 1, fromB: 2}], + [{x: 0.5}, {fromA: 0.5, fromB: 1}], + [{}, "!error"], + ], +} + +{ + name: "branches into different node kinds", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["score > 0", "score > 50"]}, + {table: "t", inputs: ["score"], outputs: ["band"], rules: [ + ["> 80", "'A'"], + ["> 50", "'B'"], + ["", "'C'"], + ]}, + {expression: "e", fields: {bonus: "score - 50"}}, + ], + edges: ["input -> s", "s:0 -> t -> output", "s:1 -> e -> output"], + }, + cases: [ + [{score: 90}, {band: "A", bonus: 40}], + [{score: 60}, {band: "B", bonus: 10}], + [{score: 10}, {band: "C"}], + [{score: 0}, {}], + ], +} + +{ + name: "a branch with passThrough and one without", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["true", "flag"]}, + {expression: "keep", passThrough: true, fields: {kept: "true"}}, + {expression: "add", fields: {added: "true"}}, + ], + edges: ["input -> s", "s:0 -> keep -> output", "s:1 -> add -> output"], + }, + cases: [ + [{flag: true, x: 1}, {flag: true, x: 1, kept: true, added: true}], + [{flag: false, x: 1}, {flag: false, x: 1, kept: true}], + ], +} + +// --------------------------------------------------------------------------------------- +// Merging parallel results at the output. Objects merge deeply. For a key written by more +// than one branch the branch whose edge into the merge point was declared first wins. +// --------------------------------------------------------------------------------------- + +{ + name: "disjoint keys from parallel branches all reach the output", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {expression: "a", fields: {"r.a": "1", "list": "[1]"}}, + {expression: "b", fields: {"r.b": "2", "other": "'x'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{}, {r: {a: 1, b: 2}, list: [1], other: "x"}], + [{z: 1}, {r: {a: 1, b: 2}, list: [1], other: "x"}], + ], +} + +{ + name: "a key written by two branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "x", fields: {who: "'x'", x: "true"}}, + {expression: "y", fields: {who: "'y'", y: "true"}}, + ], + edges: ["input -> s", "s:0 -> x -> output", "s:1 -> y -> output"], + }, + cases: [ + [{a: true, b: true}, {who: "x", x: true, y: true}, "question: on a key conflict the branch whose edge into the output was added first wins; the walker merges incoming nodes in reverse edge order, so the result depends on edge order, not branch order"], + [{a: true, b: false}, {who: "x", x: true}], + [{a: false, b: true}, {who: "y", y: true}], + ], +} + +{ + name: "the conflict winner follows the edge order into the output", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "x", fields: {who: "'x'"}}, + {expression: "y", fields: {who: "'y'"}}, + ], + edges: ["input -> s", "s:0 -> x", "s:1 -> y", "y -> output", "x -> output"], + }, + cases: [ + [{a: true, b: true}, {who: "y"}, "question: with the edge from y declared first, y wins the conflict"], + [{a: true, b: false}, {who: "x"}], + [{a: false, b: true}, {who: "y"}], + ], +} + +{ + name: "nested objects from parallel branches merge deeply", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {expression: "a", fields: {"res.price.base": "10", "res.tags": "['a']"}}, + {expression: "b", fields: {"res.price.tax": "2", "res.tags": "['b']"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{}, {res: {price: {base: 10, tax: 2}, tags: ["a"]}}, "question: arrays under the same key do not concatenate; one branch's array replaces the other"], + ], +} + +{ + name: "a scalar and an object for the same key from parallel branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {expression: "a", fields: {v: "1"}}, + {expression: "b", fields: {"v.k": "2"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{}, {v: 1}], + ], +} + +{ + name: "a null from the winning branch removes the key written by another", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {expression: "a", fields: {v: "null", keep: "1"}}, + {expression: "b", fields: {v: "2"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{}, {keep: 1}, "question: a null written by one branch deletes the value another branch computed, because merging treats null as removal"], + ], +} + +{ + name: "a null from the losing branch leaves the other branch's value", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {expression: "a", fields: {v: "1"}}, + {expression: "b", fields: {v: "null", keep: "1"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{}, {v: 1, keep: 1}, "question: whether a branch's null deletes the other value or is ignored depends on edge order"], + ], +} + +{ + name: "a branch that produces nothing does not disturb the others", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {table: "t", inputs: ["n"], outputs: ["fromTable"], rules: [ + ["> 0", "true"], + ]}, + {expression: "e", fields: {fromExpr: "true"}}, + ], + edges: ["input -> s", "s:0 -> t -> output", "s:1 -> e -> output"], + }, + cases: [ + [{n: 1}, {fromTable: true, fromExpr: true}], + [{n: 0}, {fromExpr: true}], + [{}, {fromExpr: true}], + ], +} + +{ + name: "a branch producing an array meets an object branch", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {table: "rows", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ]}, + {expression: "e", fields: {fromExpr: "true"}}, + ], + edges: ["input -> s", "s:0 -> rows -> output", "s:1 -> e -> output"], + }, + cases: [ + [{n: 2}, [{v: 1}, {v: 2}], "question: a collect table's array output replaces the merged object of the other branch at the output"], + [{n: 0}, [], "question: even an empty array replaces the other branch's object"], + ], +} + +{ + name: "parallel branches each nesting under their own outputPath", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", "n > 0"]}, + {table: "rows", hit: "collect", outputPath: "rows", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ]}, + {expression: "e", outputPath: "summary", fields: {pos: "true", n: "n"}}, + ], + edges: ["input -> s", "s:0 -> rows -> output", "s:1 -> e -> output"], + }, + cases: [ + [{n: 2}, {rows: [{v: 1}, {v: 2}], summary: {pos: true, n: 2}}], + [{n: 1}, {rows: [{v: 1}], summary: {pos: true, n: 1}}], + [{n: 0}, {rows: []}], + ], +} + +{ + name: "three parallel branches, two of them passThrough", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", "", ""]}, + {expression: "a", passThrough: true, fields: {a: "x + 1"}}, + {expression: "b", passThrough: true, fields: {b: "x + 2", x: "0"}}, + {expression: "c", fields: {c: "x + 3"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output"], + }, + cases: [ + [{x: 1}, {x: 1, a: 2, b: 3, c: 4}, "question: b overwrites x with 0 but a's pass-through copy of x wins, because a's edge into the output comes first"], + ], +} + +// --------------------------------------------------------------------------------------- +// Default branch under collect: `""` is always true, so it is taken together with every +// other true condition, wherever it is placed. +// --------------------------------------------------------------------------------------- + +{ + name: "the default branch is always taken alongside matching branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", ""]}, + {expression: "pos", fields: {pos: "true"}}, + {expression: "def", fields: {def: "true"}}, + ], + edges: ["input -> s", "s:0 -> pos -> output", "s:1 -> def -> output"], + }, + cases: [ + [{n: 1}, {pos: true, def: true}], + [{n: 0}, {def: true}], + [{}, {def: true}], + ], +} + +{ + name: "a default branch placed first is still not exclusive under collect", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", "n > 0", "n > 10"]}, + {expression: "def", fields: {def: "true"}}, + {expression: "pos", fields: {pos: "true"}}, + {expression: "big", fields: {big: "true"}}, + ], + edges: ["input -> s", "s:0 -> def -> output", "s:1 -> pos -> output", "s:2 -> big -> output"], + }, + cases: [ + [{n: 11}, {def: true, pos: true, big: true}], + [{n: 1}, {def: true, pos: true}], + [{n: -1}, {def: true}], + ], +} + +{ + name: "two default branches are both taken", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {expression: "a", fields: {a: "1"}}, + {expression: "b", fields: {b: "2"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{}, {a: 1, b: 2}], + [{a: 5}, {a: 1, b: 2}], + ], +} + +{ + name: "a default branch straight to the output carries the input", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", ""]}, + {expression: "pos", fields: {pos: "true"}}, + ], + edges: ["input -> s", "s:0 -> pos -> output", "s:1 -> output"], + }, + cases: [ + [{n: 1}, {n: 1, pos: true}], + [{n: 0}, {n: 0}], + [{n: 1, pos: false}, {n: 1, pos: true}, "question: the computed branch beats the raw input copy only because its edge into the output was declared first"], + ], +} + +// --------------------------------------------------------------------------------------- +// No branch taken under collect. +// --------------------------------------------------------------------------------------- + +{ + name: "no condition true under collect", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", "n < 0"]}, + {expression: "pos", fields: {r: "'pos'"}}, + {expression: "neg", fields: {r: "'neg'"}}, + ], + edges: ["input -> s", "s:0 -> pos -> output", "s:1 -> neg -> output"], + }, + cases: [ + [{n: 0}, {}], + [{}, {}], + [{n: null}, {}], + [{n: 1}, {r: "pos"}], + ], +} + +{ + name: "no condition true while a parallel path reaches the output", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", "n > 1"]}, + {expression: "a", fields: {a: "true"}}, + {expression: "b", fields: {b: "true"}}, + {expression: "side", fields: {side: "n"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "input -> side -> output"], + }, + cases: [ + [{n: 2}, {a: true, b: true, side: 2}], + [{n: 1}, {a: true, side: 1}], + [{n: 0}, {side: 0}], + ], +} + +// --------------------------------------------------------------------------------------- +// Null, missing and erroring conditions under collect: only `true` routes; an error makes +// that condition false without affecting the others. +// --------------------------------------------------------------------------------------- + +{ + name: "conditions on missing fields are false, the rest still route", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a > 0", "b > 0", "a == null", "b == null"]}, + {expression: "ea", fields: {a: "true"}}, + {expression: "eb", fields: {b: "true"}}, + {expression: "na", fields: {noA: "true"}}, + {expression: "nb", fields: {noB: "true"}}, + ], + edges: ["input -> s", "s:0 -> ea -> output", "s:1 -> eb -> output", "s:2 -> na -> output", "s:3 -> nb -> output"], + }, + cases: [ + [{a: 1, b: 1}, {a: true, b: true}], + [{a: 1}, {a: true, noB: true}], + [{b: 1}, {b: true, noA: true}], + [{}, {noA: true, noB: true}], + [{a: null, b: 0}, {noA: true}], + [{a: "x", b: true}, {}], + ], +} + +{ + name: "an erroring condition does not stop the other branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["date('nope') > 1", "n > 0", "n + 'x' == 1", ""]}, + {expression: "err", fields: {err: "true"}}, + {expression: "pos", fields: {pos: "true"}}, + {expression: "typ", fields: {typ: "true"}}, + {expression: "def", fields: {def: "true"}}, + ], + edges: ["input -> s", "s:0 -> err -> output", "s:1 -> pos -> output", "s:2 -> typ -> output", "s:3 -> def -> output"], + }, + cases: [ + [{n: 1}, {pos: true, def: true}], + [{n: 0}, {def: true}], + [{}, {def: true}], + ], +} + +{ + name: "an error inside one taken branch fails the whole graph", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", "boom"]}, + {expression: "ok", fields: {ok: "true"}}, + {custom: "bad", kind: "fail", config: {message: "branch failed"}}, + ], + edges: ["input -> s", "s:0 -> ok -> output", "s:1 -> bad -> output"], + }, + cases: [ + [{boom: false}, {ok: true}], + [{boom: true}, "!error: branch failed"], + ], +} + +// --------------------------------------------------------------------------------------- +// Branches converging on a shared node: the node runs once, after all of its taken +// predecessors, on their merged outputs. Predecessors on branches not taken are pruned. +// --------------------------------------------------------------------------------------- + +{ + name: "two taken branches converge on a shared node", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["hasA", "hasB"]}, + {expression: "a", fields: {a: "10"}}, + {expression: "b", fields: {b: "5"}}, + {expression: "join", fields: {sum: "(a ?? 0) + (b ?? 0)", seenA: "a != null", seenB: "b != null"}}, + ], + edges: ["input -> s", "s:0 -> a -> join", "s:1 -> b -> join", "join -> output"], + }, + cases: [ + [{hasA: true, hasB: true}, {sum: 15, seenA: true, seenB: true}], + [{hasA: true, hasB: false}, {sum: 10, seenA: true, seenB: false}], + [{hasA: false, hasB: true}, {sum: 5, seenA: false, seenB: true}], + [{hasA: false, hasB: false}, {}], + ], +} + +{ + name: "the shared node runs once even when both branches feed it", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {expression: "a", passThrough: true, fields: {count: "count + 1"}}, + {expression: "b", passThrough: true, fields: {count: "count + 10"}}, + {expression: "join", passThrough: true, fields: {joined: "count"}}, + ], + edges: ["input -> s", "s:0 -> a -> join", "s:1 -> b -> join", "join -> output"], + }, + cases: [ + [{count: 0}, {count: 1, joined: 1}, "question: both branches wrote `count`; the shared node sees a's value because a's edge into it was declared first"], + ], +} + +{ + name: "the shared node also reached through the switch input directly", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", ""]}, + {expression: "pos", fields: {sign: "'+'"}}, + {expression: "join", fields: {sign: "sign ?? 'none'", n: "n"}}, + ], + edges: ["input -> s", "s:0 -> pos -> join", "s:1 -> join", "join -> output"], + }, + cases: [ + [{n: 1}, {sign: "+", n: 1}], + [{n: 0}, {sign: "none", n: 0}], + ], +} + +{ + name: "branches converging at different depths", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", "deep"]}, + {expression: "short", fields: {short: "true"}}, + {expression: "d1", passThrough: true, fields: {d1: "true"}}, + {expression: "d2", passThrough: true, fields: {d2: "d1"}}, + {expression: "join", passThrough: true, fields: {all: "short == true and d2 == true"}}, + ], + edges: ["input -> s", "s:0 -> short -> join", "s:1 -> d1 -> d2 -> join", "join -> output"], + }, + cases: [ + [{deep: true}, {deep: true, short: true, d1: true, d2: true, all: true}], + [{deep: false}, {short: true, all: false}], + ], +} + +{ + name: "a table on a shared node sees fields from both branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["risk != null", "income != null"]}, + {expression: "r", fields: {riskScore: "risk * 10"}}, + {expression: "i", fields: {incomeBand: "income > 1000 ? 'high' : 'low'"}}, + {table: "decide", inputs: ["riskScore", "incomeBand"], outputs: ["approve"], rules: [ + ["< 50", "'high'", "true"], + ["< 50", "", "'review'"], + ["", "", "false"], + ]}, + ], + edges: ["input -> s", "s:0 -> r -> decide", "s:1 -> i -> decide", "decide -> output"], + }, + cases: [ + [{risk: 1, income: 2000}, {approve: true}], + [{risk: 1, income: 10}, {approve: "review"}], + [{risk: 9, income: 2000}, {approve: false}], + [{risk: 1}, {approve: "review"}], + [{income: 2000}, {approve: false}], + [{}, {}], + ], +} + +{ + name: "a converging node fed by a taken and a pruned branch", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "x", fields: {x: "true"}}, + {expression: "y", fields: {y: "true"}}, + {expression: "join", passThrough: true, fields: {joined: "true"}}, + ], + edges: ["input -> s", "s:0 -> x -> join", "s:1 -> y -> join", "join -> output"], + }, + cases: [ + [{a: true, b: false}, {x: true, joined: true}], + [{a: false, b: true}, {y: true, joined: true}], + [{a: true, b: true}, {x: true, y: true, joined: true}], + ], +} + +{ + name: "a node fed by the input and by a pruned branch still runs", + graph: { + nodes: [ + {expression: "pre", fields: {pre: "true"}}, + {switch: "s", hit: "collect", when: ["a"]}, + {expression: "x", fields: {x: "true"}}, + {expression: "join", passThrough: true, fields: {joined: "true"}}, + ], + edges: ["input -> pre -> join", "input -> s", "s:0 -> x -> join", "join -> output"], + }, + cases: [ + [{a: true}, {pre: true, x: true, joined: true}], + [{a: false}, {pre: true, joined: true}], + ], +} + +// --------------------------------------------------------------------------------------- +// Collect switches in combination: nested, sequential, and fan-out. +// --------------------------------------------------------------------------------------- + +{ + name: "a collect switch inside a branch of a first switch", + graph: { + nodes: [ + {switch: "outer", when: ["enabled", ""]}, + {switch: "inner", hit: "collect", when: ["x > 0", "y > 0"]}, + {expression: "fx", fields: {fx: "true"}}, + {expression: "fy", fields: {fy: "true"}}, + {expression: "off", fields: {off: "true"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "inner:0 -> fx -> output", "inner:1 -> fy -> output", "outer:1 -> off -> output"], + }, + cases: [ + [{enabled: true, x: 1, y: 1}, {fx: true, fy: true}], + [{enabled: true, x: 1, y: 0}, {fx: true}], + [{enabled: true, x: 0, y: 0}, {}], + [{enabled: false, x: 1, y: 1}, {off: true}], + ], +} + +{ + name: "a first switch inside each branch of a collect switch", + graph: { + nodes: [ + {switch: "c", hit: "collect", when: ["", ""]}, + {switch: "f1", when: ["a > 0", ""]}, + {switch: "f2", when: ["b > 0", ""]}, + {expression: "a1", fields: {a: "'pos'"}}, + {expression: "a2", fields: {a: "'non-pos'"}}, + {expression: "b1", fields: {b: "'pos'"}}, + {expression: "b2", fields: {b: "'non-pos'"}}, + ], + edges: [ + "input -> c", "c:0 -> f1", "c:1 -> f2", + "f1:0 -> a1 -> output", "f1:1 -> a2 -> output", + "f2:0 -> b1 -> output", "f2:1 -> b2 -> output", + ], + }, + cases: [ + [{a: 1, b: 1}, {a: "pos", b: "pos"}], + [{a: 1, b: 0}, {a: "pos", b: "non-pos"}], + [{a: 0, b: 1}, {a: "non-pos", b: "pos"}], + [{}, {a: "non-pos", b: "non-pos"}], + ], +} + +{ + name: "two collect switches in sequence", + graph: { + nodes: [ + {switch: "c1", hit: "collect", when: ["", "x"]}, + {expression: "base", passThrough: true, fields: {base: "true"}}, + {expression: "extra", passThrough: true, fields: {extra: "true"}}, + {switch: "c2", hit: "collect", when: ["base", "extra == true"]}, + {expression: "rb", fields: {sawBase: "true"}}, + {expression: "re", fields: {sawExtra: "true"}}, + ], + edges: [ + "input -> c1", "c1:0 -> base -> c2", "c1:1 -> extra -> c2", + "c2:0 -> rb -> output", "c2:1 -> re -> output", + ], + }, + cases: [ + [{x: true}, {sawBase: true, sawExtra: true}], + [{x: false}, {sawBase: true}], + ], +} + +{ + name: "one collect branch fanning out to several nodes", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", "n > 5"]}, + {expression: "a", fields: {a: "true"}}, + {expression: "b", fields: {b: "true"}}, + {expression: "c", fields: {c: "true"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:0 -> b -> output", "s:1 -> c -> output"], + }, + cases: [ + [{n: 6}, {a: true, b: true, c: true}], + [{n: 1}, {a: true, b: true}], + [{n: 0}, {}], + ], +} + +{ + name: "two branches of one collect switch into the same node", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", "n > 5"]}, + {expression: "shared", fields: {ran: "true", n: "n"}}, + ], + edges: ["input -> s", "s:0 -> shared -> output", "s:1 -> shared"], + }, + cases: [ + [{n: 6}, {ran: true, n: 6}], + [{n: 1}, {ran: true, n: 1}], + [{n: 0}, {}], + ], +} + +{ + name: "collect branches into sub-decisions", + decisions: { + left: {nodes: [{expression: "l", fields: {left: "v + 1"}}]}, + right: {nodes: [{expression: "r", fields: {right: "v * 2"}}]}, + }, + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["v > 0", "v > 10"]}, + {decision: "dl", key: "left"}, + {decision: "dr", key: "right"}, + ], + edges: ["input -> s", "s:0 -> dl -> output", "s:1 -> dr -> output"], + }, + cases: [ + [{v: 11}, {left: 12, right: 22}], + [{v: 1}, {left: 2}], + [{v: 0}, {}], + ], +} + +{ + name: "collect branches into function nodes", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", "twice"]}, + {function: "f1", source: """export const handler = async (input) => ({ one: input.v });"""}, + {function: "f2", source: """export const handler = async (input) => ({ two: input.v * 2 });"""}, + ], + edges: ["input -> s", "s:0 -> f1 -> output", "s:1 -> f2 -> output"], + }, + cases: [ + [{v: 3, twice: true}, {one: 3, two: 6}], + [{v: 3, twice: false}, {one: 3}], + ], +} + +// --------------------------------------------------------------------------------------- +// Several output nodes: the walk ends at the first output node reached. +// --------------------------------------------------------------------------------------- + +{ + name: "parallel branches into separate output nodes", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["", ""]}, + {expression: "a", fields: {a: "true"}}, + {expression: "b", fields: {b: "true"}}, + {output: "out1"}, + {output: "out2"}, + ], + edges: ["input -> s", "s:0 -> a -> out1", "s:1 -> b -> out2"], + }, + cases: [ + [{}, {a: true, b: true}, "bug: both branches were taken but the walk stops at the first output node it reaches, dropping the other branch"], + ], +} + +{ + name: "branches into separate output nodes, only one taken", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "ea", fields: {a: "true"}}, + {expression: "eb", fields: {b: "true"}}, + {output: "out1"}, + {output: "out2"}, + ], + edges: ["input -> s", "s:0 -> ea -> out1", "s:1 -> eb -> out2"], + }, + cases: [ + [{a: true, b: false}, {a: true}], + [{a: false, b: true}, {b: true}], + [{a: false, b: false}, {}], + ], +} diff --git a/core/engine/tests/spec/graph/10-merges-and-joins.json5 b/core/engine/tests/spec/graph/10-merges-and-joins.json5 new file mode 100644 index 00000000..00d9952e --- /dev/null +++ b/core/engine/tests/spec/graph/10-merges-and-joins.json5 @@ -0,0 +1,1055 @@ +// Merges and joins: nodes with several incoming edges (fan-in). +// +// A node's input is the merge of its parents' outputs. The merge is deep for objects, +// replaces arrays and primitives, and a null value in a later parent deletes the key. +// Parents are merged in reverse edge-insertion order, so on a key conflict the parent +// whose edge into the join was declared first wins. The graph result is the merge of the +// visited leaf nodes (normally only the output node), and that final merge drops +// top-level null values. + +// --------------------------------------------------------------------------------------- +// Parallel branches from the input with disjoint keys: the join sees the union. + +{ + name: "two branches with disjoint keys meet at the output", + graph: { + nodes: [ + {expression: "a", fields: {fromA: "x + 1"}}, + {expression: "b", fields: {fromB: "x * 2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{x: 1}, {fromA: 2, fromB: 2}], + [{x: 0}, {fromA: 1, fromB: 0}], + [{x: -2.5}, {fromA: -1.5, fromB: -5}], + [{x: 10, other: true}, {fromA: 11, fromB: 20}], + ], +} + +{ + name: "three branches with disjoint keys meet at the output", + graph: { + nodes: [ + {expression: "a", fields: {a: "'A' + s"}}, + {expression: "b", fields: {b: "len(s)"}}, + {expression: "c", fields: {c: "s == ''"}}, + ], + edges: ["input -> a -> output", "input -> b -> output", "input -> c -> output"], + }, + cases: [ + [{s: "xy"}, {a: "Axy", b: 2, c: false}], + [{s: ""}, {a: "A", b: 0, c: true}], + [{s: "hello"}, {a: "Ahello", b: 5, c: false}], + ], +} + +{ + name: "branches of different node kinds meet at the output", + graph: { + nodes: [ + {expression: "calc", fields: {doubled: "n * 2"}}, + {table: "grade", inputs: ["n"], outputs: ["grade"], rules: [ + [">= 10", "'high'"], + ["", "'low'"], + ]}, + {custom: "cfg", kind: "config", config: {source: "custom"}}, + ], + edges: ["input -> calc -> output", "input -> grade -> output", "input -> cfg -> output"], + }, + cases: [ + [{n: 12}, {doubled: 24, grade: "high", source: "custom"}], + [{n: 1}, {doubled: 2, grade: "low", source: "custom"}], + [{n: 10}, {doubled: 20, grade: "high", source: "custom"}], + ], +} + +{ + name: "branches without pass-through drop the original input at the join", + graph: { + nodes: [ + {expression: "a", fields: {p: "1"}}, + {expression: "b", fields: {q: "2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{keep: "no"}, {p: 1, q: 2}], + [{}, {p: 1, q: 2}], + [{p: 9, q: 9}, {p: 1, q: 2}], + ], +} + +// --------------------------------------------------------------------------------------- +// Key conflicts: the parent whose edge into the join was declared first wins. + +{ + name: "conflicting key: first declared edge into the join wins (a first)", + graph: { + nodes: [ + {expression: "a", fields: {k: "'a'", onlyA: "1"}}, + {expression: "b", fields: {k: "'b'", onlyB: "2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {k: "a", onlyA: 1, onlyB: 2}, "question: conflicts are resolved by edge declaration order (first edge wins), an artifact of petgraph's reverse incoming iteration rather than a documented rule"], + [{k: "input"}, {k: "a", onlyA: 1, onlyB: 2}, "question: conflicts are resolved by edge declaration order (first edge wins), an artifact of petgraph's reverse incoming iteration rather than a documented rule"], + ], +} + +{ + name: "conflicting key: first declared edge into the join wins (b first)", + graph: { + nodes: [ + {expression: "a", fields: {k: "'a'", onlyA: "1"}}, + {expression: "b", fields: {k: "'b'", onlyB: "2"}}, + ], + edges: ["input -> b -> output", "input -> a -> output"], + }, + cases: [ + [{}, {k: "b", onlyA: 1, onlyB: 2}, "question: same graph as above with edges declared in the other order; the result flips"], + [{k: "input"}, {k: "b", onlyA: 1, onlyB: 2}, "question: same graph as above with edges declared in the other order; the result flips"], + ], +} + +{ + name: "conflict order follows edges into the join, not the order of nodes", + graph: { + nodes: [ + {expression: "a", fields: {k: "'a'"}}, + {expression: "b", fields: {k: "'b'"}}, + ], + edges: ["input -> a", "input -> b", "b -> output", "a -> output"], + }, + cases: [ + [{}, {k: "b"}, "question: b -> output is declared before a -> output, so b wins"], + [{n: 1}, {k: "b"}, "question: b -> output is declared before a -> output, so b wins"], + ], +} + +{ + name: "three-way conflict: first declared edge wins over both others", + graph: { + nodes: [ + {expression: "a", fields: {k: "1", ab: "'a'"}}, + {expression: "b", fields: {k: "2", ab: "'b'", bc: "'b'"}}, + {expression: "c", fields: {k: "3", bc: "'c'"}}, + ], + edges: ["input -> a -> output", "input -> b -> output", "input -> c -> output"], + }, + cases: [ + [{}, {k: 1, ab: "a", bc: "b"}, "question: precedence is a > b > c by edge declaration order"], + [{k: 0}, {k: 1, ab: "a", bc: "b"}, "question: precedence is a > b > c by edge declaration order"], + ], +} + +{ + name: "conflicting values of different types: the winner replaces the loser", + graph: { + nodes: [ + {expression: "obj", fields: {k: "{x: 1}"}}, + {expression: "num", fields: {k: "5"}}, + ], + edges: ["input -> num -> output", "input -> obj -> output"], + }, + cases: [ + [{}, {k: 5}], + [{k: "ignored"}, {k: 5}], + ], +} + +{ + name: "conflicting values of different types: an object winner replaces a primitive", + graph: { + nodes: [ + {expression: "obj", fields: {k: "{x: 1}"}}, + {expression: "num", fields: {k: "5"}}, + ], + edges: ["input -> obj -> output", "input -> num -> output"], + }, + cases: [ + [{}, {k: {x: 1}}], + [{z: 1}, {k: {x: 1}}], + ], +} + +{ + name: "conflicting strings, booleans and numbers", + graph: { + nodes: [ + {expression: "a", fields: {s: "'a'", b: "true", n: "1.50"}}, + {expression: "b", fields: {s: "'b'", b: "false", n: "2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {s: "a", b: true, n: 1.5}], + [{s: "x"}, {s: "a", b: true, n: 1.5}], + ], +} + +// --------------------------------------------------------------------------------------- +// Deep merge of nested objects. + +{ + name: "nested objects from two parents merge key by key", + graph: { + nodes: [ + {expression: "a", fields: {"o.x": "1", "o.deep.p": "'a'"}}, + {expression: "b", fields: {"o.y": "2", "o.deep.q": "'b'"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {o: {x: 1, y: 2, deep: {p: "a", q: "b"}}}], + [{o: {z: 3}}, {o: {x: 1, y: 2, deep: {p: "a", q: "b"}}}], + ], +} + +{ + name: "nested conflict: the winner's leaf replaces, siblings survive", + graph: { + nodes: [ + {expression: "a", fields: {"o.k": "'a'", "o.onlyA": "true"}}, + {expression: "b", fields: {"o.k": "'b'", "o.onlyB": "true"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {o: {k: "a", onlyA: true, onlyB: true}}], + [{o: 1}, {o: {k: "a", onlyA: true, onlyB: true}}], + ], +} + +{ + name: "object literals as values merge deeply too", + graph: { + nodes: [ + {expression: "a", fields: {cfg: "{limits: {min: 1}, name: 'a'}"}}, + {expression: "b", fields: {cfg: "{limits: {max: 9}, tags: ['b']}"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {cfg: {limits: {min: 1, max: 9}, name: "a", tags: ["b"]}}], + [{cfg: {limits: {min: 0}}}, {cfg: {limits: {min: 1, max: 9}, name: "a", tags: ["b"]}}], + ], +} + +{ + name: "nested object replaced by a primitive from the winner", + graph: { + nodes: [ + {expression: "a", fields: {"o.inner": "'flat'"}}, + {expression: "b", fields: {"o.inner.deep": "1"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {o: {inner: "flat"}}], + [{x: 1}, {o: {inner: "flat"}}], + ], +} + +{ + name: "deep merge three levels down", + graph: { + nodes: [ + {expression: "a", fields: {"l1.l2.l3.a": "1"}}, + {expression: "b", fields: {"l1.l2.l3.b": "2", "l1.l2.b": "3"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {l1: {l2: {l3: {a: 1, b: 2}, b: 3}}}], + [{l1: null}, {l1: {l2: {l3: {a: 1, b: 2}, b: 3}}}], + ], +} + +// --------------------------------------------------------------------------------------- +// Arrays are values: they are replaced, never concatenated or merged by index. + +{ + name: "arrays at the same key are replaced by the winner", + graph: { + nodes: [ + {expression: "a", fields: {arr: "[1, 2, 3]"}}, + {expression: "b", fields: {arr: "[9]"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {arr: [1, 2, 3]}], + [{arr: [0, 0, 0, 0]}, {arr: [1, 2, 3]}], + ], +} + +{ + name: "a shorter winner array does not keep the loser's tail", + graph: { + nodes: [ + {expression: "a", fields: {arr: "[1, 2, 3]"}}, + {expression: "b", fields: {arr: "[9]"}}, + ], + edges: ["input -> b -> output", "input -> a -> output"], + }, + cases: [ + [{}, {arr: [9]}], + [{z: 1}, {arr: [9]}], + ], +} + +{ + name: "arrays of objects are not merged element by element", + graph: { + nodes: [ + {expression: "a", fields: {items: "[{id: 1, a: true}]"}}, + {expression: "b", fields: {items: "[{id: 1, b: true}, {id: 2}]"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {items: [{id: 1, a: true}]}], + [{items: []}, {items: [{id: 1, a: true}]}], + ], +} + +{ + name: "empty array from the winner replaces a populated one", + graph: { + nodes: [ + {expression: "a", fields: {arr: "[]", "o.list": "[]"}}, + {expression: "b", fields: {arr: "[1]", "o.list": "['x']", "o.keep": "1"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {arr: [], o: {list: [], keep: 1}}], + [{arr: [5]}, {arr: [], o: {list: [], keep: 1}}], + ], +} + +{ + name: "array versus object at the same key", + graph: { + nodes: [ + {expression: "a", fields: {v: "[1]"}}, + {expression: "b", fields: {v: "{x: 1}"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {v: [1]}], + [{v: "s"}, {v: [1]}], + ], +} + +// --------------------------------------------------------------------------------------- +// Null values: a null from the winning parent deletes the key; a null from the losing +// parent survives the join but top-level nulls are dropped from the final result. + +{ + name: "a null from the winning parent deletes the loser's key", + graph: { + nodes: [ + {expression: "a", fields: {k: "null", keepA: "1"}}, + {expression: "b", fields: {k: "'b'", keepB: "2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {keepA: 1, keepB: 2}], + [{k: "input"}, {keepA: 1, keepB: 2}], + ], +} + +{ + name: "a null from the losing parent does not override the winner", + graph: { + nodes: [ + {expression: "a", fields: {k: "'a'"}}, + {expression: "b", fields: {k: "null", z: "null"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {k: "a"}], + [{z: 1}, {k: "a"}], + ], +} + +{ + name: "a nested null from the winner deletes the nested key", + graph: { + nodes: [ + {expression: "a", fields: {o: "{x: null, y: 1}"}}, + {expression: "b", fields: {o: "{x: 'b', z: 2}"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {o: {y: 1, z: 2}}], + [{o: {x: 1}}, {o: {y: 1, z: 2}}], + ], +} + +{ + name: "a nested null from the loser survives into the result", + graph: { + nodes: [ + {expression: "a", fields: {o: "{y: 1}"}}, + {expression: "b", fields: {o: "{x: null, z: 2}"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {o: {x: null, y: 1, z: 2}}, "question: nested nulls survive while top-level nulls are dropped by the final merge"], + [{x: 1}, {o: {x: null, y: 1, z: 2}}, "question: nested nulls survive while top-level nulls are dropped by the final merge"], + ], +} + +{ + name: "a node downstream of the join sees the loser's null as null", + graph: { + nodes: [ + {expression: "a", fields: {k: "1"}}, + {expression: "b", fields: {x: "null", k: "null"}}, + {expression: "after", fields: {xIsNull: "x == null", k: "k", hasX: "'x' in keys($root)"}}, + ], + edges: ["input -> a -> after", "input -> b -> after", "after -> output"], + }, + cases: [ + [{}, {xIsNull: true, k: 1, hasX: true}], + [{x: 5}, {xIsNull: true, k: 1, hasX: true}], + ], +} + +{ + name: "a node downstream of the join does not see a deleted key", + graph: { + nodes: [ + {expression: "a", fields: {k: "null"}}, + {expression: "b", fields: {k: "1"}}, + {expression: "after", fields: {hasK: "'k' in keys($root)", k: "k ?? 'none'"}}, + ], + edges: ["input -> a -> after", "input -> b -> after", "after -> output"], + }, + cases: [ + [{}, {hasK: false, k: "none"}], + [{k: 3}, {hasK: false, k: "none"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Non-object parent outputs: an unmatched first-hit table produces null, a collect table +// produces an array. + +{ + name: "an unmatched table at a join is ignored (table edge declared first)", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["v"], rules: [["> 100", "'big'"]]}, + {expression: "a", fields: {k: "1"}}, + ], + edges: ["input -> t -> output", "input -> a -> output"], + }, + cases: [ + [{n: 1}, {k: 1}], + [{n: 500}, {v: "big", k: 1}], + [{}, {k: 1}], + ], +} + +{ + name: "an unmatched table at a join is ignored (table edge declared last)", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["v"], rules: [["> 100", "'big'"]]}, + {expression: "a", fields: {k: "1"}}, + ], + edges: ["input -> a -> output", "input -> t -> output"], + }, + cases: [ + [{n: 1}, {k: 1}], + [{n: 500}, {v: "big", k: 1}], + [{n: null}, {k: 1}], + ], +} + +{ + name: "two unmatched tables meeting at the output give an empty object", + graph: { + nodes: [ + {table: "t1", inputs: ["n"], outputs: ["a"], rules: [["> 100", "1"]]}, + {table: "t2", inputs: ["n"], outputs: ["b"], rules: [["< 0", "2"]]}, + ], + edges: ["input -> t1 -> output", "input -> t2 -> output"], + }, + cases: [ + [{n: 5}, {}], + [{n: 500}, {a: 1}], + [{n: -1}, {b: 2}], + ], +} + +{ + name: "a collect table losing at a join is replaced by the object parent", + graph: { + nodes: [ + {expression: "a", fields: {k: "1"}}, + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [["> 0", "'pos'"], ["", "'any'"]]}, + ], + edges: ["input -> a -> output", "input -> t -> output"], + }, + cases: [ + [{n: 1}, {k: 1}, "question: the collect table's rows are silently discarded because the object parent replaces the array head"], + [{n: -1}, {k: 1}, "question: the collect table's rows are silently discarded because the object parent replaces the array head"], + ], +} + +{ + name: "a collect table winning at a join replaces everything with its rows", + graph: { + nodes: [ + {expression: "a", fields: {k: "1"}}, + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [["> 0", "'pos'"], ["", "'any'"]]}, + ], + edges: ["input -> t -> output", "input -> a -> output"], + }, + cases: [ + [{n: 1}, [{v: "pos"}, {v: "any"}], "question: a top-level array from the winning parent replaces the merged object, dropping the sibling's keys"], + [{n: -1}, [{v: "any"}], "question: a top-level array from the winning parent replaces the merged object, dropping the sibling's keys"], + ], +} + +{ + name: "a collect table with no matching rows at a join", + graph: { + nodes: [ + {expression: "a", fields: {k: "1"}}, + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [["> 100", "'big'"]]}, + ], + edges: ["input -> t -> output", "input -> a -> output"], + }, + cases: [ + [{n: 1}, [], "question: an empty collect result wins the join and replaces the sibling's object"], + [{n: 101}, [{v: "big"}], "question: a top-level array from the winning parent replaces the merged object"], + ], +} + +{ + name: "a collect table under an output path merges like any object", + graph: { + nodes: [ + {expression: "a", fields: {k: "1"}}, + {table: "t", hit: "collect", outputPath: "rows", inputs: ["n"], outputs: ["v"], rules: [["> 0", "'pos'"], ["", "'any'"]]}, + ], + edges: ["input -> t -> output", "input -> a -> output"], + }, + cases: [ + [{n: 1}, {k: 1, rows: [{v: "pos"}, {v: "any"}]}], + [{n: 0}, {k: 1, rows: [{v: "any"}]}], + ], +} + +// --------------------------------------------------------------------------------------- +// Diamonds: one node fans out and the branches join again. + +{ + name: "diamond: both branches see the shared parent's output", + graph: { + nodes: [ + {expression: "base", fields: {v: "x * 10"}}, + {expression: "left", fields: {l: "v + 1"}}, + {expression: "right", fields: {r: "v + 2"}}, + {expression: "join", fields: {sum: "l + r"}}, + ], + edges: ["input -> base", "base -> left -> join", "base -> right -> join", "join -> output"], + }, + cases: [ + [{x: 1}, {sum: 23}], + [{x: 0}, {sum: 3}], + [{x: -1}, {sum: -17}], + [{x: 0.5}, {sum: 13}], + ], +} + +{ + name: "diamond with pass-through branches carries the shared parent's keys", + graph: { + nodes: [ + {expression: "base", passThrough: true, fields: {v: "x * 10"}}, + {expression: "left", passThrough: true, fields: {l: "v + 1"}}, + {expression: "right", passThrough: true, fields: {r: "v + 2"}}, + ], + edges: ["input -> base", "base -> left -> output", "base -> right -> output"], + }, + cases: [ + [{x: 1}, {x: 1, v: 10, l: 11, r: 12}], + [{x: 2, y: "keep"}, {x: 2, y: "keep", v: 20, l: 21, r: 22}], + ], +} + +{ + name: "diamond where both branches rewrite the same key", + graph: { + nodes: [ + {expression: "base", passThrough: true, fields: {v: "1"}}, + {expression: "left", passThrough: true, fields: {v: "v + 10"}}, + {expression: "right", passThrough: true, fields: {v: "v + 100"}}, + ], + edges: ["input -> base", "base -> left -> output", "base -> right -> output"], + }, + cases: [ + [{}, {v: 11}], + [{v: 0, w: 1}, {v: 11, w: 1}], + ], +} + +{ + name: "diamond where only one branch passes the parent through", + graph: { + nodes: [ + {expression: "base", fields: {v: "x + 1", tag: "'base'"}}, + {expression: "left", passThrough: true, fields: {l: "v * 2"}}, + {expression: "right", fields: {r: "v * 3"}}, + ], + edges: ["input -> base", "base -> left -> output", "base -> right -> output"], + }, + cases: [ + [{x: 1}, {v: 2, tag: "base", l: 4, r: 6}], + [{x: 9}, {v: 10, tag: "base", l: 20, r: 30}], + ], +} + +{ + name: "nested diamonds", + graph: { + nodes: [ + {expression: "a", fields: {n: "x"}}, + {expression: "b1", passThrough: true, fields: {b1: "n + 1"}}, + {expression: "b2", passThrough: true, fields: {b2: "n + 2"}}, + {expression: "c", fields: {c: "b1 + b2"}}, + {expression: "d1", passThrough: true, fields: {d1: "c * 2"}}, + {expression: "d2", passThrough: true, fields: {d2: "c * 3"}}, + ], + edges: [ + "input -> a", + "a -> b1 -> c", "a -> b2 -> c", + "c -> d1 -> output", "c -> d2 -> output", + ], + }, + cases: [ + [{x: 0}, {c: 3, d1: 6, d2: 9}], + [{x: 5}, {c: 13, d1: 26, d2: 39}], + ], +} + +{ + name: "diamond whose shared parent is a table", + graph: { + nodes: [ + {table: "rate", inputs: ["tier"], outputs: ["rate"], rules: [ + ["'gold'", "0.2"], + ["", "0.05"], + ]}, + {expression: "fee", fields: {fee: "amount * rate"}}, + {expression: "label", fields: {label: "'rate ' + string(rate)"}}, + ], + edges: ["input -> rate", "input -> fee", "input -> label", "rate -> fee -> output", "rate -> label -> output"], + }, + cases: [ + [{tier: "gold", amount: 100}, {fee: 20, label: "rate 0.2"}], + [{tier: "basic", amount: 100}, {fee: 5, label: "rate 0.05"}], + [{amount: 10}, {fee: 0.5, label: "rate 0.05"}], + ], +} + +// --------------------------------------------------------------------------------------- +// The input as one parent of a join. + +{ + name: "a join of the input and a branch sees both", + graph: { + nodes: [ + {expression: "calc", fields: {total: "price * qty"}}, + {expression: "join", fields: {line: "string(qty) + ' x ' + string(price) + ' = ' + string(total)"}}, + ], + edges: ["input -> calc -> join", "input -> join", "join -> output"], + }, + cases: [ + [{price: 2, qty: 3}, {line: "3 x 2 = 6"}], + [{price: 1.5, qty: 1}, {line: "1 x 1.5 = 1.5"}], + [{price: 0, qty: 0}, {line: "0 x 0 = 0"}], + ], +} + +{ + name: "input joined with a branch at the output keeps the input's keys", + graph: { + nodes: [{expression: "calc", fields: {total: "a + b"}}], + edges: ["input -> calc -> output", "input -> output"], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, total: 3}], + [{a: 1, b: 2, total: 99}, {a: 1, b: 2, total: 3}], + [{a: 0, b: 0, nested: {x: [1]}}, {a: 0, b: 0, total: 0, nested: {x: [1]}}], + ], +} + +{ + name: "input edge declared first: the input wins key conflicts", + graph: { + nodes: [{expression: "calc", fields: {total: "a + b"}}], + edges: ["input -> output", "input -> calc -> output"], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, total: 3}], + [{a: 1, b: 2, total: 99}, {a: 1, b: 2, total: 99}, "question: the stale input value beats the computed one only because its edge was declared first"], + ], +} + +{ + name: "a branch null deletes an input key at the join", + graph: { + nodes: [{expression: "scrub", fields: {secret: "null"}}], + edges: ["input -> scrub -> output", "input -> output"], + }, + cases: [ + [{secret: "pw", user: "ann"}, {user: "ann"}], + [{user: "bob"}, {user: "bob"}], + [{secret: {nested: true}}, {}], + ], +} + +{ + name: "input nested object deep-merges with a branch object", + graph: { + nodes: [{expression: "enrich", fields: {"customer.segment": "customer.age >= 65 ? 'senior' : 'adult'"}}], + edges: ["input -> enrich -> output", "input -> output"], + }, + cases: [ + [{customer: {age: 70, name: "a"}}, {customer: {age: 70, name: "a", segment: "senior"}}], + [{customer: {age: 30}}, {customer: {age: 30, segment: "adult"}}], + ], +} + +// --------------------------------------------------------------------------------------- +// Nodes downstream of a join. + +{ + name: "an expression after the join reads keys from both parents", + graph: { + nodes: [ + {expression: "tax", fields: {tax: "amount * 0.2"}}, + {expression: "ship", fields: {shipping: "amount > 100 ? 0 : 5"}}, + {expression: "total", fields: {total: "tax + shipping"}}, + ], + edges: ["input -> tax -> total", "input -> ship -> total", "total -> output"], + }, + cases: [ + [{amount: 50}, {total: 15}], + [{amount: 200}, {total: 40}], + [{amount: 100}, {total: 25}], + ], +} + +{ + name: "a table after the join matches on keys from both parents", + graph: { + nodes: [ + {expression: "age", fields: {adult: "(age ?? 0) >= 18"}}, + {expression: "score", fields: {good: "(score ?? 0) > 600"}}, + {table: "decide", inputs: ["adult", "good"], outputs: ["approved"], rules: [ + ["true", "true", "true"], + ["", "", "false"], + ]}, + ], + edges: ["input -> age -> decide", "input -> score -> decide", "decide -> output"], + }, + cases: [ + [{age: 20, score: 700}, {approved: true}], + [{age: 20, score: 500}, {approved: false}], + [{age: 10, score: 700}, {approved: false}], + [{}, {approved: false}], + ], +} + +{ + name: "a chain after the join keeps working on the merged input", + graph: { + nodes: [ + {expression: "a", fields: {x: "1"}}, + {expression: "b", fields: {y: "2"}}, + {expression: "c", passThrough: true, fields: {z: "x + y"}}, + {expression: "d", passThrough: true, fields: {w: "z * 10"}}, + ], + edges: ["input -> a -> c", "input -> b -> c", "c -> d -> output"], + }, + cases: [ + [{}, {x: 1, y: 2, z: 3, w: 30}], + [{x: 100}, {x: 1, y: 2, z: 3, w: 30}], + ], +} + +{ + name: "a join that is itself a fan-out source", + graph: { + nodes: [ + {expression: "a", fields: {x: "n + 1"}}, + {expression: "b", fields: {y: "n + 2"}}, + {expression: "j", fields: {s: "x + y"}}, + {expression: "p", fields: {p: "s * 2"}}, + {expression: "q", fields: {q: "s * 3"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> p -> output", "j -> q -> output"], + }, + cases: [ + [{n: 0}, {p: 6, q: 9}], + [{n: 1}, {p: 10, q: 15}], + ], +} + +{ + name: "a sub-decision after the join receives the merged input", + decisions: { + child: {nodes: [{expression: "sum", fields: {sum: "x + y"}}]}, + }, + graph: { + nodes: [ + {expression: "a", fields: {x: "n"}}, + {expression: "b", fields: {y: "n * 2"}}, + {decision: "call", key: "child"}, + ], + edges: ["input -> a -> call", "input -> b -> call", "call -> output"], + }, + cases: [ + [{n: 1}, {sum: 3}], + [{n: 5}, {sum: 15}], + ], +} + +{ + name: "a function node after the join receives the merged input", + graph: { + nodes: [ + {expression: "a", fields: {x: "n"}}, + {expression: "b", fields: {y: "n * 2"}}, + {function: "f", source: """export const handler = async (input) => ({keys: Object.keys(input).filter((k) => !k.startsWith('$')).sort(), sum: input.x + input.y});"""}, + ], + edges: ["input -> a -> f", "input -> b -> f", "f -> output"], + }, + cases: [ + [{n: 1}, {keys: ["x", "y"], sum: 3}], + [{n: 4}, {keys: ["x", "y"], sum: 12}], + ], +} + +// --------------------------------------------------------------------------------------- +// $nodes at a join: every parent's own output stays addressable regardless of conflicts. + +{ + name: "$nodes exposes each parent of a join", + graph: { + nodes: [ + {expression: "a", fields: {k: "'a'"}}, + {expression: "b", fields: {k: "'b'"}}, + {expression: "c", fields: {fromA: "$nodes.a.k", fromB: "$nodes.b.k", merged: "k", inp: "$nodes.input.q"}}, + ], + edges: ["input -> a -> c", "input -> b -> c", "c -> output"], + }, + cases: [ + [{q: 5}, {fromA: "a", fromB: "b", merged: "a", inp: 5}], + [{q: "x"}, {fromA: "a", fromB: "b", merged: "a", inp: "x"}], + ], +} + +{ + name: "$nodes keeps a parent's key that the merge deleted", + graph: { + nodes: [ + {expression: "a", fields: {k: "null"}}, + {expression: "b", fields: {k: "'b'"}}, + {expression: "c", fields: {merged: "k ?? 'gone'", fromB: "$nodes.b.k"}}, + ], + edges: ["input -> a -> c", "input -> b -> c", "c -> output"], + }, + cases: [ + [{}, {merged: "gone", fromB: "b"}], + [{k: 1}, {merged: "gone", fromB: "b"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Repeated and redundant edges. + +{ + name: "a duplicated edge merges the same parent twice without effect", + graph: { + nodes: [{expression: "a", fields: {k: "x + 1", "o.p": "1"}}], + edges: ["input -> a -> output", "a -> output"], + }, + cases: [ + [{x: 1}, {k: 2, o: {p: 1}}], + [{x: 0}, {k: 1, o: {p: 1}}], + ], +} + +{ + name: "a transitive shortcut edge: the join sees both the ancestor and the child", + graph: { + nodes: [ + {expression: "a", fields: {v: "1", fromA: "true"}}, + {expression: "b", fields: {v: "2", fromB: "true"}}, + ], + edges: ["input -> a -> b -> output", "a -> output"], + }, + cases: [ + [{}, {v: 2, fromA: true, fromB: true}], + [{v: 0}, {v: 2, fromA: true, fromB: true}], + ], +} + +{ + name: "a transitive shortcut edge declared first wins over the child", + graph: { + nodes: [ + {expression: "a", fields: {v: "1", fromA: "true"}}, + {expression: "b", fields: {v: "2", fromB: "true"}}, + ], + edges: ["a -> output", "input -> a -> b -> output"], + }, + cases: [ + [{}, {v: 1, fromA: true, fromB: true}, "question: the ancestor's stale value beats its descendant's only because its edge into the join was declared first"], + ], +} + +// --------------------------------------------------------------------------------------- +// Joins behind a switch: a pruned branch does not contribute to the join. + +{ + name: "a join behind a switch only merges the taken branch", + graph: { + nodes: [ + {switch: "route", when: ["kind == 'a'", ""]}, + {expression: "a", fields: {picked: "'a'", fromA: "true"}}, + {expression: "b", fields: {picked: "'b'", fromB: "true"}}, + {expression: "join", passThrough: true, fields: {done: "true"}}, + ], + edges: ["input -> route", "route:0 -> a -> join", "route:1 -> b -> join", "join -> output"], + }, + cases: [ + [{kind: "a"}, {picked: "a", fromA: true, done: true}], + [{kind: "b"}, {picked: "b", fromB: true, done: true}], + [{}, {picked: "b", fromB: true, done: true}], + ], +} + +{ + name: "a collect switch taking both branches merges both at the join", + graph: { + nodes: [ + {switch: "route", hit: "collect", when: ["x > 0", "x > 10"]}, + {expression: "a", fields: {big: "false", pos: "true"}}, + {expression: "b", fields: {big: "true"}}, + ], + edges: ["input -> route", "route:0 -> a -> output", "route:1 -> b -> output"], + }, + cases: [ + [{x: 5}, {big: false, pos: true}], + [{x: 50}, {big: false, pos: true}, "question: both branches are taken and the first declared branch wins the conflict"], + [{x: -1}, {}], + ], +} + +{ + name: "a join fed by the input and by a switch branch", + graph: { + nodes: [ + {switch: "route", when: ["flag", ""]}, + {expression: "on", fields: {state: "'on'"}}, + {expression: "join", fields: {state: "state ?? 'unset'", v: "v"}}, + ], + edges: ["input -> route", "route:0 -> on -> join", "input -> join", "join -> output"], + }, + cases: [ + [{flag: true, v: 1}, {state: "on", v: 1}], + [{flag: false, v: 2}, {state: "unset", v: 2}], + [{v: 3, state: "input"}, {state: "input", v: 3}], + ], +} + +// --------------------------------------------------------------------------------------- +// Leaves: the result is the merge of visited leaf nodes. + +{ + name: "a graph without an output node merges all leaves", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "a", name: "a", type: "expressionNode", content: {expressions: [{id: "x1", key: "y", value: "n + 1"}]}}, + {id: "b", name: "b", type: "expressionNode", content: {expressions: [{id: "x2", key: "z", value: "n + 2"}]}}, + ], + edges: [{id: "e1", sourceId: "i", targetId: "a"}, {id: "e2", sourceId: "i", targetId: "b"}], + }, + }, + cases: [ + [{n: 0}, {y: 1, z: 2}], + [{n: 10}, {y: 11, z: 12}], + ], +} + +{ + name: "a dangling branch visited after the output does not contribute", + graph: { + nodes: [ + {expression: "a", fields: {k: "1"}}, + {expression: "d", fields: {dangling: "1"}}, + ], + edges: ["input -> a -> output", "input -> d"], + }, + cases: [ + [{}, {k: 1}], + [{k: 5}, {k: 1}], + ], +} + +{ + name: "a dangling branch visited before the output contributes to the result", + graph: { + nodes: [ + {expression: "a", fields: {k: "1"}}, + {expression: "d", fields: {dangling: "1"}}, + ], + edges: ["input -> d", "input -> a -> output"], + }, + cases: [ + [{}, {k: 1, dangling: 1}, "question: whether a leaf that never reaches the output node contributes depends on edge declaration order"], + [{k: 5}, {k: 1, dangling: 1}, "question: whether a leaf that never reaches the output node contributes depends on edge declaration order"], + ], +} + +// --------------------------------------------------------------------------------------- +// Top-level nulls and the final merge. + +{ + name: "top-level null values are dropped from the result, nested ones kept", + graph: { + nodes: [{expression: "a", fields: {x: "null", y: "1", "n.z": "null"}}], + }, + cases: [ + [{}, {y: 1, n: {z: null}}, "question: the final merge drops top-level nulls but keeps nested ones"], + [{x: 1}, {y: 1, n: {z: null}}, "question: the final merge drops top-level nulls but keeps nested ones"], + ], +} + +{ + name: "input nulls are dropped when the input reaches the output", + graph: {}, + cases: [ + [{a: null, b: 1}, {b: 1}, "question: the final merge drops top-level nulls of the input"], + [{o: {p: null}}, {o: {p: null}}], + ], +} diff --git a/core/engine/tests/spec/graph/11-pass-through.json5 b/core/engine/tests/spec/graph/11-pass-through.json5 new file mode 100644 index 00000000..ef635b22 --- /dev/null +++ b/core/engine/tests/spec/graph/11-pass-through.json5 @@ -0,0 +1,683 @@ +// Pass-through: `passThrough: true` on expression, table and decision nodes. +// +// With pass-through the node's result is its input with the node's own output merged on +// top (the same deep merge as at joins): new keys are added, existing keys are replaced, +// nested objects merge key by key, arrays are replaced, and a null in the output deletes +// the input key. Without pass-through the node's result is only its own output. + +// --------------------------------------------------------------------------------------- +// Expression nodes: off versus on. + +{ + name: "expression without pass-through returns only its fields", + graph: { + nodes: [{expression: "calc", fields: {total: "a + b"}}], + }, + cases: [ + [{a: 1, b: 2}, {total: 3}], + [{a: 1, b: 2, extra: "x"}, {total: 3}], + [{a: 0, b: 0, total: 99}, {total: 0}], + ], +} + +{ + name: "expression with pass-through adds its fields to the input", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: {total: "a + b"}}], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, total: 3}], + [{a: 1, b: 2, extra: "x"}, {a: 1, b: 2, extra: "x", total: 3}], + [{a: -1, b: 1, list: [1, 2], o: {p: true}}, {a: -1, b: 1, total: 0, list: [1, 2], o: {p: true}}], + ], +} + +{ + name: "pass-through replaces an existing input key", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: {total: "a + b"}}], + }, + cases: [ + [{a: 1, b: 2, total: 99}, {a: 1, b: 2, total: 3}], + [{a: 1, b: 2, total: "text"}, {a: 1, b: 2, total: 3}], + [{a: 1, b: 2, total: {nested: 1}}, {a: 1, b: 2, total: 3}], + [{a: 1, b: 2, total: [1]}, {a: 1, b: 2, total: 3}], + ], +} + +{ + name: "pass-through can rewrite a key from its own previous value", + graph: { + nodes: [{expression: "inc", passThrough: true, fields: {count: "count + 1"}}], + }, + cases: [ + [{count: 0}, {count: 1}], + [{count: 41, other: "x"}, {count: 42, other: "x"}], + [{count: -0.5}, {count: 0.5}], + ], +} + +{ + name: "pass-through with an empty input object", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: {const: "'c'", n: "1 + 1"}}], + }, + cases: [ + [{}, {const: "c", n: 2}], + [{x: null}, {const: "c", n: 2}], + ], +} + +{ + name: "pass-through with fields that have empty keys or values keeps only the input", + graph: { + nodes: [{expression: "noop", passThrough: true, fields: [["", "1"], ["k", ""]]}], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{k: "kept"}, {k: "kept"}], + ], +} + +{ + name: "pass-through: later fields see earlier ones through $ and the input as root", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: [ + ["net", "price * qty"], + ["tax", "$.net * 0.2"], + ["gross", "$.net + $.tax"], + ["original", "net ?? 'none'"], + ]}], + }, + cases: [ + [{price: 10, qty: 2}, {price: 10, qty: 2, net: 20, tax: 4, gross: 24, original: "none"}], + [{price: 10, qty: 2, net: 1}, {price: 10, qty: 2, net: 20, tax: 4, gross: 24, original: 1}], + ], +} + +{ + name: "duplicate keys in a pass-through node: the last one wins", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: [["k", "1"], ["k", "$.k + 1"]]}], + }, + cases: [ + [{}, {k: 2}], + [{k: 10}, {k: 2}], + ], +} + +// --------------------------------------------------------------------------------------- +// Null in the node's output deletes the input key. + +{ + name: "a field evaluating to null deletes the input key", + graph: { + nodes: [{expression: "scrub", passThrough: true, fields: {password: "null", user: "user"}}], + }, + cases: [ + [{user: "ann", password: "pw"}, {user: "ann"}], + [{user: "ann"}, {user: "ann"}], + [{password: {nested: 1}}, {}], + ], +} + +{ + name: "a field reading a missing key deletes the same key from the input", + graph: { + nodes: [{expression: "copy", passThrough: true, fields: {mirror: "source"}}], + }, + cases: [ + [{source: 1, mirror: "old"}, {source: 1, mirror: 1}], + [{mirror: "old"}, {}, "question: a field that evaluates to null erases the input key instead of setting it to null"], + [{source: null, mirror: 0}, {}, "question: a field that evaluates to null erases the input key instead of setting it to null"], + ], +} + +{ + name: "a nested null deletes only the nested key", + graph: { + nodes: [{expression: "scrub", passThrough: true, fields: {"o.secret": "null"}}], + }, + cases: [ + [{o: {secret: 1, keep: 2}}, {o: {keep: 2}}], + [{o: {keep: 2}}, {o: {keep: 2}}], + [{o: {secret: 1}}, {o: {}}], + [{}, {o: {secret: null}}, "question: when the parent object is missing the nested null is materialized instead of omitted"], + ], +} + +{ + name: "null values already in the input pass through to nodes downstream", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {seen: "true"}}, + {expression: "b", passThrough: true, fields: {wasNull: "x == null", hadKey: "'x' in keys($root)"}}, + ], + }, + cases: [ + [{x: null}, {seen: true, wasNull: true, hadKey: true}], + [{}, {seen: true, wasNull: true, hadKey: false}], + [{x: 1}, {x: 1, seen: true, wasNull: false, hadKey: true}], + ], +} + +// --------------------------------------------------------------------------------------- +// Nested objects under pass-through. + +{ + name: "dotted keys merge into an existing input object", + graph: { + nodes: [{expression: "enrich", passThrough: true, fields: {"customer.segment": "customer.age >= 65 ? 'senior' : 'adult'"}}], + }, + cases: [ + [{customer: {age: 70, name: "a"}}, {customer: {age: 70, name: "a", segment: "senior"}}], + [{customer: {age: 30, segment: "old"}}, {customer: {age: 30, segment: "adult"}}], + [{customer: {age: 18, address: {city: "x"}}}, {customer: {age: 18, address: {city: "x"}, segment: "adult"}}], + ], +} + +{ + name: "dotted keys create the object when the input lacks it", + graph: { + nodes: [{expression: "make", passThrough: true, fields: {"meta.version": "2", "meta.flags.on": "true"}}], + }, + cases: [ + [{}, {meta: {version: 2, flags: {on: true}}}], + [{other: 1}, {other: 1, meta: {version: 2, flags: {on: true}}}], + [{meta: {author: "x"}}, {meta: {author: "x", version: 2, flags: {on: true}}}], + ], +} + +{ + name: "dotted keys replace a primitive or array in the input", + graph: { + nodes: [{expression: "make", passThrough: true, fields: {"meta.version": "2"}}], + }, + cases: [ + [{meta: 5}, {meta: {version: 2}}], + [{meta: "s"}, {meta: {version: 2}}], + [{meta: [1, 2]}, {meta: {version: 2}}], + [{meta: null}, {meta: {version: 2}}], + ], +} + +{ + name: "an object-valued field deep-merges with the input object", + graph: { + nodes: [{expression: "cfg", passThrough: true, fields: {settings: "{theme: 'dark', limits: {max: 10}}"}}], + }, + cases: [ + [{settings: {lang: "en", limits: {min: 1}}}, {settings: {lang: "en", theme: "dark", limits: {min: 1, max: 10}}}], + [{settings: {theme: "light"}}, {settings: {theme: "dark", limits: {max: 10}}}], + [{}, {settings: {theme: "dark", limits: {max: 10}}}], + ], +} + +{ + name: "a primitive field replaces an input object", + graph: { + nodes: [{expression: "flatten", passThrough: true, fields: {settings: "'default'"}}], + }, + cases: [ + [{settings: {lang: "en"}}, {settings: "default"}], + [{settings: [1]}, {settings: "default"}], + ], +} + +{ + name: "array fields replace input arrays instead of merging", + graph: { + nodes: [{expression: "tags", passThrough: true, fields: {tags: "['new']", "o.list": "[]"}}], + }, + cases: [ + [{tags: ["a", "b", "c"]}, {tags: ["new"], o: {list: []}}], + [{tags: [], o: {list: [1, 2], keep: true}}, {tags: ["new"], o: {list: [], keep: true}}], + [{tags: {x: 1}}, {tags: ["new"], o: {list: []}}], + ], +} + +{ + name: "arrays of objects in the input stay untouched when not written", + graph: { + nodes: [{expression: "count", passThrough: true, fields: {n: "len(items)"}}], + }, + cases: [ + [{items: [{id: 1, o: {x: 1}}, {id: 2}]}, {items: [{id: 1, o: {x: 1}}, {id: 2}], n: 2}], + [{items: []}, {items: [], n: 0}], + ], +} + +// --------------------------------------------------------------------------------------- +// Decision tables with pass-through. + +{ + name: "first-hit table with pass-through adds its outputs to the input", + graph: { + nodes: [{table: "grade", passThrough: true, inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 50", "'B'"], + ["", "'F'"], + ]}], + }, + cases: [ + [{score: 95}, {score: 95, grade: "A"}], + [{score: 60, name: "x"}, {score: 60, name: "x", grade: "B"}], + [{score: 10, grade: "old"}, {score: 10, grade: "F"}], + ], +} + +{ + name: "first-hit table with pass-through and no matching rule returns the input", + graph: { + nodes: [{table: "grade", passThrough: true, inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + ]}], + }, + cases: [ + [{score: 95}, {score: 95, grade: "A"}], + [{score: 10}, {score: 10}], + [{score: 10, grade: "kept"}, {score: 10, grade: "kept"}], + [{}, {}], + ], +} + +{ + name: "first-hit table without pass-through and no matching rule returns nothing", + graph: { + nodes: [{table: "grade", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + ]}], + }, + cases: [ + [{score: 95}, {grade: "A"}], + [{score: 10}, {}], + [{score: 10, grade: "kept"}, {}], + ], +} + +{ + name: "table outputs with dotted fields merge into nested input objects", + graph: { + nodes: [{table: "risk", passThrough: true, inputs: ["applicant.score"], outputs: ["applicant.risk", "decision.code"], rules: [ + ["> 700", "'low'", "1"], + ["", "'high'", "2"], + ]}], + }, + cases: [ + [{applicant: {score: 750, name: "a"}}, {applicant: {score: 750, name: "a", risk: "low"}, decision: {code: 1}}], + [{applicant: {score: 100}, decision: {note: "x"}}, {applicant: {score: 100, risk: "high"}, decision: {note: "x", code: 2}}], + ], +} + +{ + name: "a table output cell evaluating to null deletes the input key", + graph: { + nodes: [{table: "clear", passThrough: true, inputs: ["mode"], outputs: ["token", "status"], rules: [ + ["'logout'", "null", "'out'"], + ["", "token", "'in'"], + ]}], + }, + cases: [ + [{mode: "logout", token: "abc"}, {mode: "logout", status: "out"}], + [{mode: "login", token: "abc"}, {mode: "login", token: "abc", status: "in"}], + ], +} + +{ + name: "collect table with pass-through replaces the input with its rows", + graph: { + nodes: [{table: "flags", hit: "collect", passThrough: true, inputs: ["n"], outputs: ["flag"], rules: [ + ["> 0", "'positive'"], + ["> 10", "'large'"], + ]}], + }, + cases: [ + [{n: 20}, [{flag: "positive"}, {flag: "large"}], "question: pass-through cannot overlay an array result on the input object, so the input is dropped"], + [{n: 5}, [{flag: "positive"}], "question: pass-through cannot overlay an array result on the input object, so the input is dropped"], + [{n: -1}, [], "question: pass-through cannot overlay an array result on the input object, so the input is dropped"], + ], +} + +{ + name: "collect table with pass-through and an output path keeps the input", + graph: { + nodes: [{table: "flags", hit: "collect", passThrough: true, outputPath: "flags", inputs: ["n"], outputs: ["flag"], rules: [ + ["> 0", "'positive'"], + ["> 10", "'large'"], + ]}], + }, + cases: [ + [{n: 20}, {n: 20, flags: [{flag: "positive"}, {flag: "large"}]}], + [{n: -1}, {n: -1, flags: []}], + [{n: 5, flags: [{flag: "old"}, {flag: "older"}]}, {n: 5, flags: [{flag: "positive"}]}], + ], +} + +{ + name: "first-hit table with per-column collect and pass-through", + graph: { + nodes: [{table: "tags", passThrough: true, inputs: ["n"], outputs: ["tags[]", "first"], rules: [ + ["> 0", "'pos'", "'p'"], + ["> 10", "'big'", "'b'"], + ]}], + }, + cases: [ + [{n: 20}, {n: 20, tags: ["pos", "big"], first: "p"}], + [{n: 5, tags: ["old"]}, {n: 5, tags: ["pos"], first: "p"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Decision nodes with pass-through. + +{ + name: "decision node with pass-through overlays the sub-decision result", + decisions: { + child: {nodes: [{expression: "double", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{x: 4}, {x: 4, y: 8}], + [{x: 0, z: "keep"}, {x: 0, z: "keep", y: 0}], + [{x: 1, y: "old"}, {x: 1, y: 2}], + ], +} + +{ + name: "decision node without pass-through returns only the sub-decision result", + decisions: { + child: {nodes: [{expression: "double", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 4}, {y: 8}], + [{x: 1, z: "drop"}, {y: 2}], + ], +} + +{ + name: "decision node whose sub-decision itself passes the input through", + decisions: { + child: {nodes: [{expression: "double", passThrough: true, fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 4, z: 1}, {x: 4, z: 1, y: 8}], + [{x: 0}, {x: 0, y: 0}], + ], +} + +{ + name: "decision node with pass-through and a sub-decision deleting a key", + decisions: { + child: {nodes: [{expression: "scrub", fields: {secret: "null", "o.inner": "null", done: "true"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{secret: "x", o: {inner: 1, keep: 2}}, {secret: "x", o: {keep: 2}, done: true}, "question: the sub-decision's final merge already dropped its top-level null, so the parent's secret survives while the nested null still deletes o.inner"], + [{o: {keep: 2}}, {o: {keep: 2}, done: true}], + ], +} + +{ + name: "decision node with pass-through and a sub-decision returning nested objects", + decisions: { + child: {nodes: [{expression: "nest", fields: {"result.score": "base * 10", "result.ok": "base > 0"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{base: 1, result: {prev: true}}, {base: 1, result: {prev: true, score: 10, ok: true}}], + [{base: 0}, {base: 0, result: {score: 0, ok: false}}], + ], +} + +{ + name: "decision node with pass-through and an empty sub-decision", + decisions: { + child: {}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{o: {p: [1]}}, {o: {p: [1]}}], + ], +} + +// --------------------------------------------------------------------------------------- +// Chains of pass-through and non-pass-through nodes. + +{ + name: "a chain of pass-through nodes accumulates every field", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {a: "x + 1"}}, + {expression: "b", passThrough: true, fields: {b: "a + 1"}}, + {expression: "c", passThrough: true, fields: {c: "b + 1"}}, + ], + }, + cases: [ + [{x: 0}, {x: 0, a: 1, b: 2, c: 3}], + [{x: 10, y: "y"}, {x: 10, y: "y", a: 11, b: 12, c: 13}], + ], +} + +{ + name: "a non-pass-through node in the middle drops everything before it", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {a: "x + 1"}}, + {expression: "b", fields: {b: "a + 1"}}, + {expression: "c", passThrough: true, fields: {c: "b + 1", sawX: "x != null"}}, + ], + }, + cases: [ + [{x: 0}, {b: 2, c: 3, sawX: false}], + [{x: 5, y: 1}, {b: 7, c: 8, sawX: false}], + ], +} + +{ + name: "a non-pass-through first node feeds only its output into a pass-through node", + graph: { + nodes: [ + {expression: "a", fields: {a: "x * 2"}}, + {expression: "b", passThrough: true, fields: {b: "a + 1"}}, + ], + }, + cases: [ + [{x: 1}, {a: 2, b: 3}], + [{x: 1, keep: "no"}, {a: 2, b: 3}], + ], +} + +{ + name: "a non-pass-through last node returns only its fields", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {a: "x * 2"}}, + {expression: "b", passThrough: true, fields: {b: "a + 1"}}, + {expression: "final", fields: {result: "b"}}, + ], + }, + cases: [ + [{x: 1}, {result: 3}], + [{x: 4, noise: true}, {result: 9}], + ], +} + +{ + name: "a pass-through chain where each node rewrites the same key", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {v: "v + 1"}}, + {expression: "b", passThrough: true, fields: {v: "v * 10"}}, + {expression: "c", passThrough: true, fields: {v: "v - 1"}}, + ], + }, + cases: [ + [{v: 0}, {v: 9}], + [{v: 2}, {v: 29}], + [{v: -1}, {v: -1}], + ], +} + +{ + name: "a pass-through chain where a later node deletes an earlier field", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {temp: "x * 2"}}, + {expression: "b", passThrough: true, fields: {result: "temp + 1"}}, + {expression: "c", passThrough: true, fields: {temp: "null"}}, + ], + }, + cases: [ + [{x: 1}, {x: 1, result: 3}], + [{x: 5, temp: "in"}, {x: 5, result: 11}], + ], +} + +{ + name: "mixed node kinds in a pass-through chain", + decisions: { + child: {nodes: [{expression: "fee", fields: {fee: "amount * rate"}}]}, + }, + graph: { + nodes: [ + {table: "rate", passThrough: true, inputs: ["tier"], outputs: ["rate"], rules: [ + ["'gold'", "0.1"], + ["", "0.2"], + ]}, + {decision: "fee", key: "child", passThrough: true}, + {expression: "total", passThrough: true, fields: {total: "amount + fee"}}, + ], + }, + cases: [ + [{tier: "gold", amount: 100}, {tier: "gold", amount: 100, rate: 0.1, fee: 10, total: 110}], + [{tier: "basic", amount: 50}, {tier: "basic", amount: 50, rate: 0.2, fee: 10, total: 60}], + [{amount: 0}, {amount: 0, rate: 0.2, fee: 0, total: 0}], + ], +} + +{ + name: "an unmatched pass-through table in a chain changes nothing", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {a: "1"}}, + {table: "t", passThrough: true, inputs: ["n"], outputs: ["hit"], rules: [["> 100", "true"]]}, + {expression: "c", passThrough: true, fields: {hit: "hit ?? false"}}, + ], + }, + cases: [ + [{n: 1}, {n: 1, a: 1, hit: false}], + [{n: 101}, {n: 101, a: 1, hit: true}], + ], +} + +{ + name: "an unmatched non-pass-through table in a chain leaves the next node with nothing", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {a: "1"}}, + {table: "t", inputs: ["n"], outputs: ["hit"], rules: [["> 100", "true"]]}, + {expression: "c", passThrough: true, fields: {hit: "hit ?? false", sawA: "a != null"}}, + ], + }, + cases: [ + [{n: 1}, {hit: false, sawA: false}], + [{n: 101}, {hit: true, sawA: false}], + ], +} + +// --------------------------------------------------------------------------------------- +// Pass-through at a join: the node's input is the merged parents. + +{ + name: "pass-through at a join carries every parent's keys", + graph: { + nodes: [ + {expression: "a", fields: {fromA: "x + 1"}}, + {expression: "b", fields: {fromB: "x + 2"}}, + {expression: "j", passThrough: true, fields: {sum: "fromA + fromB"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{x: 0}, {fromA: 1, fromB: 2, sum: 3}], + [{x: 1}, {fromA: 2, fromB: 3, sum: 5}], + ], +} + +{ + name: "pass-through at a join that includes the input", + graph: { + nodes: [ + {expression: "a", fields: {computed: "x * 2"}}, + {expression: "j", passThrough: true, fields: {check: "computed == x * 2"}}, + ], + edges: ["input -> a -> j", "input -> j", "j -> output"], + }, + cases: [ + [{x: 3}, {x: 3, computed: 6, check: true}], + [{x: 3, extra: [1]}, {x: 3, extra: [1], computed: 6, check: true}], + ], +} + +// --------------------------------------------------------------------------------------- +// Pass-through and function nodes, custom nodes (which have no pass-through option). + +{ + name: "a pass-through expression after a function node", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({fromF: input.x * 3});"""}, + {expression: "e", passThrough: true, fields: {fromE: "fromF + 1"}}, + ], + }, + cases: [ + [{x: 1}, {fromF: 3, fromE: 4}], + [{x: 2, drop: true}, {fromF: 6, fromE: 7}], + ], +} + +{ + name: "a pass-through expression after a custom echo node", + graph: { + nodes: [ + {custom: "c", kind: "echo", config: {}}, + {expression: "e", passThrough: true, fields: {tagged: "true"}}, + ], + }, + cases: [ + [{a: 1}, {a: 1, tagged: true}], + [{o: {p: 1}}, {o: {p: 1}, tagged: true}], + ], +} + +// --------------------------------------------------------------------------------------- +// Errors are not masked by pass-through. + +{ + name: "a failing field in a pass-through node fails the graph", + graph: { + nodes: [{expression: "bad", passThrough: true, fields: {r: "a + b"}}], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, r: 3}], + [{a: "x", b: 1}, "!error"], + [{a: 1, b: [1]}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/12-input-field-output-path.json5 b/core/engine/tests/spec/graph/12-input-field-output-path.json5 new file mode 100644 index 00000000..07d84bf2 --- /dev/null +++ b/core/engine/tests/spec/graph/12-input-field-output-path.json5 @@ -0,0 +1,666 @@ +// Transform attributes in single execution mode: `inputField` and `outputPath`. +// +// `inputField` is an expression evaluated against the node's input; its value becomes the +// node's environment instead of the whole input. `outputPath` is a dotted path the node's +// result is written under. `passThrough` always overlays onto the node's full input, not +// onto the inputField selection. The three attributes apply to expression, table and +// decision nodes. Empty strings mean "not set". + +// --------------------------------------------------------------------------------------- +// inputField selects a nested object as the node's environment. + +{ + name: "inputField scopes an expression node to a nested object", + graph: { + nodes: [{expression: "a", inputField: "customer", fields: {name: "name", upper: "upper(name)"}}], + }, + cases: [ + [{customer: {name: "ann"}}, {name: "ann", upper: "ANN"}], + [{customer: {name: "bob", age: 3}, name: "outer"}, {name: "bob", upper: "BOB"}], + [{customer: {name: ""}}, {name: "", upper: ""}], + ], +} + +{ + name: "fields outside the inputField selection are not visible", + graph: { + nodes: [{expression: "a", inputField: "customer", fields: {flag: "flag ?? 'unseen'", viaRoot: "$root.flag ?? 'unseen'"}}], + }, + cases: [ + [{customer: {}, flag: true}, {flag: "unseen", viaRoot: "unseen"}], + [{customer: {flag: false}, flag: true}, {flag: false, viaRoot: false}], + ], +} + +{ + name: "dotted inputField selects a deeply nested object", + graph: { + nodes: [{expression: "a", inputField: "a.b.c", fields: {n: "v * 2"}}], + }, + cases: [ + [{a: {b: {c: {v: 3}}}}, {n: 6}], + [{a: {b: {c: {v: 0}, d: 1}}}, {n: 0}], + [{a: {b: {c: {v: -1.5}}}}, {n: -3}], + ], +} + +{ + name: "inputField is an expression: indexing", + graph: { + nodes: [{expression: "a", inputField: "items[0]", fields: {first: "v"}}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {first: 1}], + [{items: [{v: "x"}]}, {first: "x"}], + [{items: []}, {}], + ], +} + +{ + name: "inputField is an expression: an object literal builds the environment", + graph: { + nodes: [{expression: "a", inputField: "{x: price * 2, y: qty}", fields: {total: "x * y"}}], + }, + cases: [ + [{price: 5, qty: 3}, {total: 30}], + [{price: 0.5, qty: 4}, {total: 4}], + ], +} + +{ + name: "inputField is an expression: a conditional picks one of two objects", + graph: { + nodes: [{expression: "a", inputField: "useB == true ? b : a", fields: {v: "v"}}], + }, + cases: [ + [{useB: true, a: {v: "a"}, b: {v: "b"}}, {v: "b"}], + [{useB: false, a: {v: "a"}, b: {v: "b"}}, {v: "a"}], + [{a: {v: "a"}, b: {v: "b"}}, {v: "a"}], + ], +} + +{ + name: "inputField can read $nodes", + graph: { + nodes: [ + {expression: "prep", fields: {x: "1"}}, + {expression: "a", inputField: "$nodes.input.payload", fields: {v: "v"}}, + ], + }, + cases: [ + [{payload: {v: 7}}, {v: 7}], + [{payload: {v: "s"}}, {v: "s"}], + ], +} + +{ + name: "$ inside an inputField-scoped expression node refers to the node's own fields", + graph: { + nodes: [{expression: "a", inputField: "c", fields: [["x", "v + 1"], ["y", "$.x * 2"], ["z", "$.v ?? 'none'"]]}], + }, + cases: [ + [{c: {v: 1}}, {x: 2, y: 4, z: "none"}], + [{c: {v: 10}}, {x: 11, y: 22, z: "none"}], + ], +} + +// --------------------------------------------------------------------------------------- +// inputField resolving to null, a missing key, or a non-object. + +{ + name: "inputField resolving to null or a missing key gives a null environment", + graph: { + nodes: [{expression: "a", inputField: "customer", fields: {name: "name ?? 'anon'", isNull: "name == null"}}], + }, + cases: [ + [{customer: null}, {name: "anon", isNull: true}], + [{}, {name: "anon", isNull: true}], + [{customer: {}}, {name: "anon", isNull: true}], + [{customer: {name: "x"}}, {name: "x", isNull: false}], + ], +} + +{ + name: "inputField resolving to a primitive: reading a field fails", + graph: { + nodes: [{expression: "a", inputField: "customer", fields: {name: "name"}}], + }, + cases: [ + [{customer: 5}, "!error", "question: a field read on a number environment errors while the same read on a null environment yields null"], + [{customer: "s"}, "!error", "question: a field read on a string environment errors while the same read on a null environment yields null"], + [{customer: true}, "!error", "question: a field read on a boolean environment errors while the same read on a null environment yields null"], + [{customer: [1, 2]}, "!error", "question: a field read on an array environment errors while the same read on a null environment yields null"], + ], +} + +{ + name: "inputField resolving to a primitive: fields not reading the environment succeed", + graph: { + nodes: [{expression: "a", inputField: "customer", fields: {c: "'const'", n: "1 + 1"}}], + }, + cases: [ + [{customer: 5}, {c: "const", n: 2}], + [{customer: "s"}, {c: "const", n: 2}], + [{customer: [1]}, {c: "const", n: 2}], + [{customer: null}, {c: "const", n: 2}], + ], +} + +{ + name: "inputField resolving to an array of objects is not iterated in single mode", + graph: { + nodes: [{expression: "a", inputField: "items", fields: {count: "len($root)"}}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {count: 2}], + [{items: []}, {count: 0}], + ], +} + +{ + name: "an inputField with a syntax error fails the node", + graph: { + nodes: [{expression: "a", inputField: "a +", fields: {n: "1"}}], + }, + cases: [ + [{a: 1}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "an inputField that fails at runtime fails the node", + graph: { + nodes: [{expression: "a", inputField: "x + y", fields: {n: "1"}}], + }, + cases: [ + [{x: 1, y: "s"}, "!error"], + [{x: 1, y: 2}, {n: 1}], + ], +} + +// --------------------------------------------------------------------------------------- +// outputPath writes the node's result under a dotted path. + +{ + name: "outputPath with a single segment", + graph: { + nodes: [{expression: "a", outputPath: "result", fields: {n: "v + 1", s: "'x'"}}], + }, + cases: [ + [{v: 1}, {result: {n: 2, s: "x"}}], + [{v: 0, result: "old"}, {result: {n: 1, s: "x"}}], + ], +} + +{ + name: "outputPath with nested segments and dotted field keys", + graph: { + nodes: [{expression: "a", outputPath: "res.deep", fields: {n: "v", "m.k": "v * 2"}}], + }, + cases: [ + [{v: 1}, {res: {deep: {n: 1, m: {k: 2}}}}], + [{v: -3}, {res: {deep: {n: -3, m: {k: -6}}}}], + ], +} + +{ + name: "outputPath on a node producing an empty object", + graph: { + nodes: [{expression: "a", outputPath: "res", fields: [["", "1"]]}], + }, + cases: [ + [{v: 1}, {res: {}}], + [{}, {res: {}}], + ], +} + +{ + name: "outputPath with a null result field keeps the null nested", + graph: { + nodes: [{expression: "a", outputPath: "res", fields: {n: "missing", m: "1"}}], + }, + cases: [ + [{}, {res: {n: null, m: 1}}], + [{missing: 2}, {res: {n: 2, m: 1}}], + ], +} + +{ + name: "outputPath segments that look like indexes are object keys", + graph: { + nodes: [{expression: "a", outputPath: "items.0", fields: {v: "1"}}], + }, + cases: [ + [{}, {items: {"0": {v: 1}}}], + [{items: [{v: 0}]}, {items: {"0": {v: 1}}}], + ], +} + +{ + name: "a node downstream reads through the outputPath", + graph: { + nodes: [ + {expression: "a", outputPath: "calc", fields: {total: "price * qty"}}, + {expression: "b", fields: {label: "'total ' + string(calc.total)"}}, + ], + }, + cases: [ + [{price: 2, qty: 3}, {label: "total 6"}], + [{price: 0, qty: 9}, {label: "total 0"}], + ], +} + +{ + name: "two branches with different output paths merge side by side", + graph: { + nodes: [ + {expression: "a", outputPath: "left", fields: {v: "x + 1"}}, + {expression: "b", outputPath: "right", fields: {v: "x + 2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{x: 0}, {left: {v: 1}, right: {v: 2}}], + [{x: 10}, {left: {v: 11}, right: {v: 12}}], + ], +} + +{ + name: "two branches sharing an output path prefix deep-merge", + graph: { + nodes: [ + {expression: "a", outputPath: "res.a", fields: {v: "1"}}, + {expression: "b", outputPath: "res.b", fields: {v: "2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {res: {a: {v: 1}, b: {v: 2}}}], + [{res: 1}, {res: {a: {v: 1}, b: {v: 2}}}], + ], +} + +// --------------------------------------------------------------------------------------- +// outputPath combined with passThrough. + +{ + name: "outputPath with pass-through adds the result next to the input", + graph: { + nodes: [{expression: "a", outputPath: "res", passThrough: true, fields: {n: "v * 10"}}], + }, + cases: [ + [{v: 1}, {v: 1, res: {n: 10}}], + [{v: 2, other: [1]}, {v: 2, other: [1], res: {n: 20}}], + ], +} + +{ + name: "outputPath with pass-through deep-merges into an existing input object", + graph: { + nodes: [{expression: "a", outputPath: "res", passThrough: true, fields: {n: "v"}}], + }, + cases: [ + [{v: 1, res: {old: 1, n: 0}}, {v: 1, res: {old: 1, n: 1}}], + [{v: 1, res: {deep: {x: 1}}}, {v: 1, res: {deep: {x: 1}, n: 1}}], + ], +} + +{ + name: "outputPath with pass-through replaces a non-object at the path", + graph: { + nodes: [{expression: "a", outputPath: "res", passThrough: true, fields: {n: "v"}}], + }, + cases: [ + [{v: 1, res: 5}, {v: 1, res: {n: 1}}], + [{v: 1, res: "s"}, {v: 1, res: {n: 1}}], + [{v: 1, res: [1, 2]}, {v: 1, res: {n: 1}}], + [{v: 1, res: null}, {v: 1, res: {n: 1}}], + ], +} + +{ + name: "nested outputPath with pass-through keeps sibling keys at every level", + graph: { + nodes: [{expression: "a", outputPath: "a.b", passThrough: true, fields: {c: "1"}}], + }, + cases: [ + [{a: {x: 1, b: {y: 2}}}, {a: {x: 1, b: {y: 2, c: 1}}}], + [{a: {x: 1}}, {a: {x: 1, b: {c: 1}}}], + [{}, {a: {b: {c: 1}}}], + ], +} + +{ + name: "outputPath with pass-through and a null field deletes the key under the path", + graph: { + nodes: [{expression: "a", outputPath: "res", passThrough: true, fields: {gone: "null", kept: "1"}}], + }, + cases: [ + [{res: {gone: "x", other: 2}}, {res: {other: 2, kept: 1}}], + [{}, {res: {gone: null, kept: 1}}, "question: when the path is new, the nested null is materialized instead of omitted"], + ], +} + +{ + name: "outputPath with pass-through where the path equals an input key read by the node", + graph: { + nodes: [{expression: "a", outputPath: "counter", passThrough: true, fields: {value: "counter.value + 1"}}], + }, + cases: [ + [{counter: {value: 1, step: 1}}, {counter: {value: 2, step: 1}}], + [{counter: {value: 0}}, {counter: {value: 1}}], + ], +} + +// --------------------------------------------------------------------------------------- +// inputField combined with passThrough and outputPath. + +{ + name: "inputField with pass-through overlays onto the full input, not the selection", + graph: { + nodes: [{expression: "a", inputField: "customer", passThrough: true, fields: {greeting: "'hi ' + name"}}], + }, + cases: [ + [{customer: {name: "x"}, flag: true}, {customer: {name: "x"}, flag: true, greeting: "hi x"}], + [{customer: {name: "y"}}, {customer: {name: "y"}, greeting: "hi y"}], + ], +} + +{ + name: "inputField with pass-through and a null-environment field", + graph: { + nodes: [{expression: "a", inputField: "customer", passThrough: true, fields: {name: "name"}}], + }, + cases: [ + [{customer: null, name: "outer"}, {}, "question: the scoped field reads null and that null deletes the outer input key with the same name"], + [{customer: {name: "inner"}, name: "outer"}, {customer: {name: "inner"}, name: "inner"}], + ], +} + +{ + name: "inputField and outputPath write a result back next to its source", + graph: { + nodes: [{expression: "a", inputField: "customer", outputPath: "customerResult", fields: {adult: "age >= 18"}}], + }, + cases: [ + [{customer: {age: 20}}, {customerResult: {adult: true}}], + [{customer: {age: 10}, x: 1}, {customerResult: {adult: false}}], + ], +} + +{ + name: "inputField, outputPath and pass-through enrich the selected object in place", + graph: { + nodes: [{expression: "a", inputField: "customer", outputPath: "customer", passThrough: true, fields: {adult: "age >= 18"}}], + }, + cases: [ + [{customer: {age: 20, name: "a"}}, {customer: {age: 20, name: "a", adult: true}}], + [{customer: {age: 10}, other: 1}, {customer: {age: 10, adult: false}, other: 1}], + ], +} + +{ + name: "inputField and outputPath on different nested paths", + graph: { + nodes: [{expression: "a", inputField: "req.body", outputPath: "res.body", passThrough: true, fields: {echo: "msg"}}], + }, + cases: [ + [{req: {body: {msg: "hi"}}}, {req: {body: {msg: "hi"}}, res: {body: {echo: "hi"}}}], + [{req: {body: {msg: "a"}}, res: {status: 200}}, {req: {body: {msg: "a"}}, res: {status: 200, body: {echo: "a"}}}], + ], +} + +// --------------------------------------------------------------------------------------- +// Decision tables with inputField and outputPath. + +{ + name: "table with inputField matches against the selected object", + graph: { + nodes: [{table: "t", inputField: "applicant", inputs: ["age"], outputs: ["tier"], rules: [ + ["> 18", "'adult'"], + ["", "'minor'"], + ]}], + }, + cases: [ + [{applicant: {age: 20}}, {tier: "adult"}], + [{applicant: {age: 5}, age: 99}, {tier: "minor"}], + [{applicant: null}, {tier: "minor"}], + [{age: 40}, {tier: "minor"}], + ], +} + +{ + name: "table with inputField and outputPath", + graph: { + nodes: [{table: "t", inputField: "c", outputPath: "out", inputs: ["age"], outputs: ["tier"], rules: [ + ["> 18", "'a'"], + ["", "'m'"], + ]}], + }, + cases: [ + [{c: {age: 20}}, {out: {tier: "a"}}], + [{c: null}, {out: {tier: "m"}}], + [{}, {out: {tier: "m"}}], + ], +} + +{ + name: "unmatched table with an outputPath writes a null that is dropped at the top level", + graph: { + nodes: [{table: "t", outputPath: "out", inputs: ["age"], outputs: ["tier"], rules: [["> 18", "'a'"]]}], + }, + cases: [ + [{age: 20}, {out: {tier: "a"}}], + [{age: 2}, {}], + ], +} + +{ + name: "unmatched table with a nested outputPath leaves a nested null", + graph: { + nodes: [{table: "t", outputPath: "res.out", inputs: ["age"], outputs: ["tier"], rules: [["> 18", "'a'"]]}], + }, + cases: [ + [{age: 20}, {res: {out: {tier: "a"}}}], + [{age: 2}, {res: {out: null}}, "question: an unmatched table under a nested path yields an explicit null, under a top-level path nothing"], + ], +} + +{ + name: "unmatched table with outputPath and pass-through keeps the input", + graph: { + nodes: [{table: "t", outputPath: "out", passThrough: true, inputs: ["age"], outputs: ["tier"], rules: [["> 18", "'a'"]]}], + }, + cases: [ + [{age: 20}, {age: 20, out: {tier: "a"}}], + [{age: 2}, {age: 2}], + [{age: 2, out: {tier: "old"}}, {age: 2}, "question: no matching rule deletes the existing value at the output path (null overlay)"], + ], +} + +{ + name: "collect table with outputPath nests the rows array", + graph: { + nodes: [{table: "t", hit: "collect", outputPath: "rows", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ["", "2"], + ]}], + }, + cases: [ + [{n: 1}, {rows: [{v: 1}, {v: 2}]}], + [{n: 0}, {rows: [{v: 2}]}], + ], +} + +{ + name: "collect table with inputField and outputPath", + graph: { + nodes: [{table: "t", hit: "collect", inputField: "order", outputPath: "order.discounts", passThrough: true, inputs: ["total", "vip"], outputs: ["pct"], rules: [ + ["> 100", "", "5"], + ["", "true", "10"], + ]}], + }, + cases: [ + [{order: {total: 200, vip: true}}, {order: {total: 200, vip: true, discounts: [{pct: 5}, {pct: 10}]}}], + [{order: {total: 50, vip: false}}, {order: {total: 50, vip: false, discounts: []}}], + [{order: {total: 150}}, {order: {total: 150, discounts: [{pct: 5}]}}], + ], +} + +{ + name: "table input columns with dotted fields relative to the inputField", + graph: { + nodes: [{table: "t", inputField: "data", outputPath: "result", inputs: ["person.age", "person.country"], outputs: ["eligible"], rules: [ + [">= 18", "'US'", "true"], + ["", "", "false"], + ]}], + }, + cases: [ + [{data: {person: {age: 20, country: "US"}}}, {result: {eligible: true}}], + [{data: {person: {age: 20, country: "DE"}}}, {result: {eligible: false}}], + [{data: {}}, {result: {eligible: false}}], + ], +} + +// --------------------------------------------------------------------------------------- +// Decision nodes with inputField and outputPath. + +{ + name: "decision node with inputField passes the selection as the sub-decision input", + decisions: { + child: {nodes: [{expression: "double", fields: {y: "x * 2", sawZ: "z != null"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub"}], + }, + cases: [ + [{sub: {x: 4}, z: 1}, {y: 8, sawZ: false}], + [{sub: {x: 0, z: 1}}, {y: 0, sawZ: true}], + ], +} + +{ + name: "decision node with inputField, outputPath and pass-through", + decisions: { + child: {nodes: [{expression: "double", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub", outputPath: "r", passThrough: true}], + }, + cases: [ + [{sub: {x: 4}, z: 1}, {r: {y: 8}, sub: {x: 4}, z: 1}], + [{sub: {x: 1}, r: {old: true}}, {r: {old: true, y: 2}, sub: {x: 1}}], + ], +} + +{ + name: "decision node with inputField resolving to a non-object", + decisions: { + child: {nodes: [{expression: "double", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub"}], + }, + cases: [ + [{sub: 3}, "!error", "question: a field read on a number environment errors while the same read on a null environment yields null"], + ], +} + +{ + name: "decision node with inputField resolving to null", + decisions: { + child: {nodes: [{expression: "e", fields: {y: "x ?? 'none'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub"}], + }, + cases: [ + [{sub: null}, {y: "none"}], + [{}, {y: "none"}], + [{sub: {x: 1}}, {y: 1}], + ], +} + +{ + name: "decision node with outputPath only", + decisions: { + child: {nodes: [{expression: "e", passThrough: true, fields: {seen: "true"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "child.result"}], + }, + cases: [ + [{a: 1}, {child: {result: {a: 1, seen: true}}}], + [{}, {child: {result: {seen: true}}}], + ], +} + +{ + name: "decision node with inputField whose sub-decision passes the selection through", + decisions: { + child: {nodes: [{expression: "e", passThrough: true, fields: {checked: "true"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "item", outputPath: "item", passThrough: true}], + }, + cases: [ + [{item: {id: 1}, other: "x"}, {item: {id: 1, checked: true}, other: "x"}], + [{item: {}}, {item: {checked: true}}], + ], +} + +// --------------------------------------------------------------------------------------- +// Empty attribute strings mean "not set". + +{ + name: "empty inputField and outputPath strings are ignored", + graph: { + nodes: [{expression: "a", inputField: "", outputPath: "", fields: {n: "v"}}], + }, + cases: [ + [{v: 1}, {n: 1}], + [{v: "s", w: 2}, {n: "s"}], + ], +} + +{ + name: "empty attribute strings with pass-through", + graph: { + nodes: [{expression: "a", inputField: "", outputPath: "", passThrough: true, fields: {n: "v"}}], + }, + cases: [ + [{v: 1}, {v: 1, n: 1}], + [{v: "s", w: 2}, {v: "s", w: 2, n: "s"}], + ], +} + +{ + name: "explicit single execution mode behaves like the default", + graph: { + nodes: [{expression: "a", executionMode: "single", inputField: "items", outputPath: "out", fields: {n: "len($root)"}}], + }, + cases: [ + [{items: [1, 2, 3]}, {out: {n: 3}}], + [{items: []}, {out: {n: 0}}], + ], +} + +// --------------------------------------------------------------------------------------- +// Transform attributes at a join. + +{ + name: "inputField at a join selects from the merged parents", + graph: { + nodes: [ + {expression: "a", outputPath: "pick", fields: {from: "'a'"}}, + {expression: "b", fields: {other: "1"}}, + {expression: "j", inputField: "pick", outputPath: "picked", fields: {from: "from"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{}, {picked: {from: "a"}}], + [{pick: {from: "input"}}, {picked: {from: "a"}}], + ], +} diff --git a/core/engine/tests/spec/graph/13-loops.json5 b/core/engine/tests/spec/graph/13-loops.json5 new file mode 100644 index 00000000..4069c5a2 --- /dev/null +++ b/core/engine/tests/spec/graph/13-loops.json5 @@ -0,0 +1,811 @@ +// Loop execution mode: expression, table and decision nodes with executionMode "loop" run once +// per element of the array selected by inputField (or of the node input itself), and produce +// an array of per-item results, in item order. + +// --- Expression nodes over arrays of objects -------------------------------------------------- +// Each item becomes the expression environment; the node output is the array of item results. +{ + name: "expression loop over items maps each object", + graph: { + nodes: [{expression: "each", inputField: "items", executionMode: "loop", fields: {total: "price * qty"}}], + }, + cases: [ + [{items: [{price: 2, qty: 3}, {price: 1.5, qty: 2}]}, [{total: 6}, {total: 3}]], + [{items: [{price: 10, qty: 0}]}, [{total: 0}]], + [{items: [{price: 0.1, qty: 3}, {price: 4, qty: 0.25}, {price: 7, qty: 1}]}, [{total: 0.3}, {total: 1}, {total: 7}]], + ], +} + +{ + name: "expression loop with outputPath collects results under a key", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "results", executionMode: "loop", fields: {total: "price * qty"}}], + }, + cases: [ + [{items: [{price: 2, qty: 3}, {price: 1, qty: 1}]}, {results: [{total: 6}, {total: 1}]}], + [{items: [{price: 5, qty: 2}]}, {results: [{total: 10}]}], + [{items: []}, {results: []}], + ], +} + +{ + name: "expression loop with dotted outputPath nests the result array", + graph: { + nodes: [{expression: "each", inputField: "order.lines", outputPath: "summary.lines", executionMode: "loop", fields: {sku: "upper(sku)"}}], + }, + cases: [ + [{order: {lines: [{sku: "a1"}, {sku: "b2"}]}}, {summary: {lines: [{sku: "A1"}, {sku: "B2"}]}}], + [{order: {lines: [{sku: "x"}]}}, {summary: {lines: [{sku: "X"}]}}], + [{order: {lines: []}}, {summary: {lines: []}}], + ], +} + +{ + name: "expression loop with several fields and nested keys per item", + graph: { + nodes: [{expression: "each", inputField: "people", outputPath: "out", executionMode: "loop", fields: { + "name.full": "first + ' ' + last", + "flags.adult": "age >= 18", + "age": "age", + }}], + }, + cases: [ + [ + {people: [{first: "Ann", last: "Lee", age: 30}, {first: "Bo", last: "Ng", age: 9}]}, + {out: [{name: {full: "Ann Lee"}, flags: {adult: true}, age: 30}, {name: {full: "Bo Ng"}, flags: {adult: false}, age: 9}]}, + ], + [{people: [{first: "C", last: "D", age: 18}]}, {out: [{name: {full: "C D"}, flags: {adult: true}, age: 18}]}], + ], +} + +// --- Empty arrays ------------------------------------------------------------------------------- +// An empty array runs the body zero times and yields an empty array, with or without outputPath. +{ + name: "expression loop over an empty array yields an empty array", + graph: { + nodes: [{expression: "each", inputField: "items", executionMode: "loop", fields: {v: "x + 1"}}], + }, + cases: [ + [{items: []}, []], + [{items: [{x: 1}]}, [{v: 2}]], + [{items: [], other: 5}, []], + ], +} + +{ + name: "empty loop output reaches the output node next to other branches", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "mapped", executionMode: "loop", fields: {v: "x * 10"}}, + {expression: "count", fields: {n: "len(items)"}}, + ], + edges: ["input -> each -> output", "input -> count -> output"], + }, + cases: [ + [{items: []}, {mapped: [], n: 0}], + [{items: [{x: 1}, {x: 2}]}, {mapped: [{v: 10}, {v: 20}], n: 2}], + [{items: [{x: -1}]}, {mapped: [{v: -10}], n: 1}], + ], +} + +// --- Non-array loop inputs -------------------------------------------------------------------- +// A loop needs an array: a missing field, null, an object, a string or a number is an error. +{ + name: "expression loop over a non-array is an error", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {v: "1"}}], + }, + cases: [ + [{items: [{}]}, {out: [{v: 1}]}], + [{}, "!error"], + [{items: null}, "!error"], + [{items: {a: 1}}, "!error"], + [{items: "abc"}, "!error"], + [{items: 3}, "!error"], + [{items: true}, "!error"], + ], +} + +{ + name: "loop without inputField iterates the node input, which is an object", + graph: { + nodes: [{expression: "each", executionMode: "loop", fields: {v: "1"}}], + }, + cases: [ + [{items: [1, 2]}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "inputField that fails to evaluate is an error", + graph: { + nodes: [{expression: "each", inputField: "items[", outputPath: "out", executionMode: "loop", fields: {v: "1"}}], + }, + cases: [ + [{items: [1]}, "!error"], + [{}, "!error"], + ], +} + +// --- inputField as an expression ---------------------------------------------------------------- +// inputField is an expression evaluated against the node input, not only a path. +{ + name: "inputField may be a filter expression", + graph: { + nodes: [{expression: "each", inputField: "filter(items, #.active)", outputPath: "out", executionMode: "loop", fields: {id: "id"}}], + }, + cases: [ + [{items: [{id: 1, active: true}, {id: 2, active: false}, {id: 3, active: true}]}, {out: [{id: 1}, {id: 3}]}], + [{items: [{id: 1, active: false}]}, {out: []}], + [{items: []}, {out: []}], + ], +} + +{ + name: "inputField may build the array from a range", + graph: { + nodes: [{expression: "each", inputField: "map([1..n], {k: #})", outputPath: "out", executionMode: "loop", fields: {sq: "k * k"}}], + }, + cases: [ + [{n: 3}, {out: [{sq: 1}, {sq: 4}, {sq: 9}]}], + [{n: 1}, {out: [{sq: 1}]}], + ], +} + +{ + name: "inputField may concatenate arrays", + graph: { + nodes: [{expression: "each", inputField: "flatten([a, b])", outputPath: "out", executionMode: "loop", fields: {v: "v"}}], + }, + cases: [ + [{a: [{v: 1}], b: [{v: 2}, {v: 3}]}, {out: [{v: 1}, {v: 2}, {v: 3}]}], + [{a: [], b: []}, {out: []}], + ], +} + +// --- Scalar and null items -------------------------------------------------------------------- +// A scalar item becomes the whole environment; it is reachable through `$root`. Reading a field +// off a scalar environment is an expression error (see the expression spec), which fails the node. +{ + name: "loop over scalar items reads them through $root", + graph: { + nodes: [{expression: "each", inputField: "nums", outputPath: "out", executionMode: "loop", fields: {doubled: "$root * 2"}}], + }, + cases: [ + [{nums: [1, 2, 3]}, {out: [{doubled: 2}, {doubled: 4}, {doubled: 6}]}], + [{nums: [0.5]}, {out: [{doubled: 1}]}], + [{nums: []}, {out: []}], + ], +} + +{ + name: "loop over strings", + graph: { + nodes: [{expression: "each", inputField: "tags", outputPath: "out", executionMode: "loop", fields: {tag: "upper($root)", n: "len($root)"}}], + }, + cases: [ + [{tags: ["a", "bc"]}, {out: [{tag: "A", n: 1}, {tag: "BC", n: 2}]}], + [{tags: [""]}, {out: [{tag: "", n: 0}]}], + ], +} + +{ + name: "field reads on scalar items fail the node", + graph: { + nodes: [{expression: "each", inputField: "nums", outputPath: "out", executionMode: "loop", fields: {x: "x", has: "x != null"}}], + }, + cases: [ + [{nums: [1, "a"]}, "!error", "question: an identifier on a non-object root errors while $root.x is null (expression spec 17-04 / standard row 177)"], + [{nums: [{x: 2}, 3]}, "!error", "question: an identifier on a non-object root errors while $root.x is null (expression spec 17-04 / standard row 177)"], + [{nums: [{x: 2}, {}]}, {out: [{x: 2, has: true}, {x: null, has: false}]}], + ], +} + +{ + name: "null items run the body with a null environment", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {v: "x ?? 'none'", isNull: "$root == null"}}], + }, + cases: [ + [{items: [null]}, {out: [{v: "none", isNull: true}]}], + [{items: [{x: 1}, null, {x: 3}]}, {out: [{v: 1, isNull: false}, {v: "none", isNull: true}, {v: 3, isNull: false}]}], + [{items: [{}, {x: null}]}, {out: [{v: "none", isNull: false}, {v: "none", isNull: false}]}], + ], +} + +{ + name: "loop over nested arrays", + graph: { + nodes: [{expression: "each", inputField: "rows", outputPath: "out", executionMode: "loop", fields: {sum: "sum($root)", n: "len($root)"}}], + }, + cases: [ + [{rows: [[1, 2], [3], []]}, {out: [{sum: 3, n: 2}, {sum: 3, n: 1}, {sum: 0, n: 0}]}], + [{rows: [[10]]}, {out: [{sum: 10, n: 1}]}], + ], +} + +{ + name: "an item error fails the whole node", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {v: "a + b"}}], + }, + cases: [ + [{items: [{a: 1, b: 2}, {a: 3, b: 4}]}, {out: [{v: 3}, {v: 7}]}], + [{items: [{a: 1, b: 2}, {a: "x", b: 4}]}, "!error"], + [{items: [{a: "x", b: 1}]}, "!error"], + ], +} + +// --- `$` inside loops -------------------------------------------------------------------------- +// `$` is the object built so far for the current item; it starts empty for every item. +{ + name: "$ refers to earlier fields of the same item", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: { + base: "price * qty", + tax: "$.base * 0.1", + total: "$.base + $.tax", + }}], + }, + cases: [ + [{items: [{price: 10, qty: 2}, {price: 5, qty: 1}]}, {out: [{base: 20, tax: 2, total: 22}, {base: 5, tax: 0.5, total: 5.5}]}], + [{items: [{price: 0, qty: 9}]}, {out: [{base: 0, tax: 0, total: 0}]}], + ], +} + +{ + name: "$ does not leak between items", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: { + seen: "$.marker ?? 'fresh'", + marker: "'set'", + }}], + }, + cases: [ + [{items: [{}, {}, {}]}, {out: [{seen: "fresh", marker: "set"}, {seen: "fresh", marker: "set"}, {seen: "fresh", marker: "set"}]}], + [{items: [{marker: "x"}]}, {out: [{seen: "fresh", marker: "set"}]}], + ], +} + +{ + name: "$ with nested keys in a loop", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: { + "a.b": "v + 1", + "c": "$.a.b * 2", + }}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {out: [{a: {b: 2}, c: 4}, {a: {b: 3}, c: 6}]}], + ], +} + +// --- Outer context inside loops --------------------------------------------------------------- +// The item replaces the environment: fields of the node input outside the item are not visible +// unless reached through $nodes. +{ + name: "outer input fields are not in scope inside the loop", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {rate: "rate ?? 'missing'"}}], + }, + cases: [ + [{rate: 2, items: [{}]}, {out: [{rate: "missing"}]}], + [{rate: 2, items: [{rate: 5}]}, {out: [{rate: 5}]}], + ], +} + +{ + name: "outer input fields through $nodes inside the loop", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {scaled: "v * $nodes.input.rate"}}], + }, + cases: [ + [{rate: 2, items: [{v: 1}, {v: 3}]}, {out: [{scaled: 2}, {scaled: 6}]}], + [{rate: 0.5, items: [{v: 4}]}, {out: [{scaled: 2}]}], + [{rate: 10, items: []}, {out: []}], + ], +} + +{ + name: "loop body reads a previous node through $nodes", + graph: { + nodes: [ + {expression: "config", fields: {factor: "factor ?? 1"}}, + {expression: "each", inputField: "$nodes.input.items", outputPath: "out", executionMode: "loop", fields: {v: "v * $nodes.config.factor"}}, + ], + }, + cases: [ + [{factor: 3, items: [{v: 1}, {v: 2}]}, {out: [{v: 3}, {v: 6}]}], + [{items: [{v: 5}]}, {out: [{v: 5}]}], + ], +} + +// --- passThrough with loops ------------------------------------------------------------------- +// passThrough in a loop merges each item into its result, and then the node input into the +// final output. +{ + name: "loop with passThrough and outputPath keeps the input and merges items", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {total: "price * qty"}}], + }, + cases: [ + [ + {customer: "c1", items: [{price: 2, qty: 3}, {price: 1, qty: 4}]}, + {customer: "c1", items: [{price: 2, qty: 3, total: 6}, {price: 1, qty: 4, total: 4}]}, + ], + [{customer: "c2", items: []}, {customer: "c2", items: []}], + ], +} + +{ + name: "loop with passThrough writing to a different path", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "priced", executionMode: "loop", passThrough: true, fields: {total: "price"}}], + }, + cases: [ + [{items: [{price: 2}]}, {items: [{price: 2}], priced: [{price: 2, total: 2}]}], + [{items: [{price: 2, total: 9}]}, {items: [{price: 2, total: 9}], priced: [{price: 2, total: 2}]}], + [{items: [], x: 1}, {items: [], x: 1, priced: []}], + ], +} + +{ + name: "loop result overrides item fields of the same name", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", passThrough: true, fields: {v: "v * 10", "meta.seen": "true"}}], + }, + cases: [ + [{items: [{v: 1, meta: {id: 7}}]}, {items: [{v: 1, meta: {id: 7}}], out: [{v: 10, meta: {id: 7, seen: true}}]}], + [{items: [{v: 2}]}, {items: [{v: 2}], out: [{v: 20, meta: {seen: true}}]}], + ], +} + +{ + name: "loop with passThrough and no outputPath", + graph: { + nodes: [{expression: "each", inputField: "items", executionMode: "loop", passThrough: true, fields: {v: "1"}}], + }, + cases: [ + [{items: [{a: 1}]}, [{a: 1, v: 1}], "question: the node input merged with the result array yields the array itself (items merged with their results), the outer input is dropped"], + [{x: 1, items: [{a: 2}, {}]}, [{a: 2, v: 1}, {v: 1}], "question: the node input merged with the result array yields the array itself (items merged with their results), the outer input is dropped"], + ], +} + +{ + name: "loop passThrough over scalar items", + graph: { + nodes: [{expression: "each", inputField: "nums", outputPath: "out", executionMode: "loop", passThrough: true, fields: {d: "$root * 2"}}], + }, + cases: [ + [{nums: [1, 2]}, {nums: [1, 2], out: [{d: 2}, {d: 4}]}], + ], +} + +// --- Downstream of loops ----------------------------------------------------------------------- +{ + name: "a node after a loop aggregates its results", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "lines", executionMode: "loop", fields: {total: "price * qty"}}, + {expression: "sum", fields: {grand: "sum(map(lines, #.total))", count: "len(lines)"}}, + ], + }, + cases: [ + [{items: [{price: 2, qty: 3}, {price: 1, qty: 4}]}, {grand: 10, count: 2}], + [{items: []}, {grand: 0, count: 0}], + [{items: [{price: 0.1, qty: 1}, {price: 0.2, qty: 1}]}, {grand: 0.3, count: 2}], + ], +} + +{ + name: "loop output without outputPath feeds a non-object to the next node", + graph: { + nodes: [ + {expression: "each", inputField: "items", executionMode: "loop", fields: {v: "x"}}, + {expression: "after", fields: {n: "len($root)", first: "$root[0].v"}}, + ], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {n: 2, first: 1}], + [{items: [{x: 9}]}, {n: 1, first: 9}], + ], +} + +{ + name: "two loops in parallel merge at the output", + graph: { + nodes: [ + {expression: "a", inputField: "xs", outputPath: "as", executionMode: "loop", fields: {v: "$root + 1"}}, + {expression: "b", inputField: "ys", outputPath: "bs", executionMode: "loop", fields: {v: "$root * 2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{xs: [1, 2], ys: [3]}, {as: [{v: 2}, {v: 3}], bs: [{v: 6}]}], + [{xs: [], ys: []}, {as: [], bs: []}], + ], +} + +{ + name: "two loops writing the same outputPath merge index-wise", + graph: { + nodes: [ + {expression: "a", inputField: "xs", outputPath: "out", executionMode: "loop", fields: {a: "$root"}}, + {expression: "b", inputField: "xs", outputPath: "out", executionMode: "loop", fields: {b: "$root * 2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{xs: [1, 2]}, {out: [{a: 1}, {a: 2}]}, "question: two branches writing the same array path: the first branch's array is kept whole, the second is dropped (not merged per index, not replaced)"], + [{xs: [3]}, {out: [{a: 3}]}, "question: two branches writing the same array path: the first branch's array is kept whole, the second is dropped (not merged per index, not replaced)"], + ], +} + +{ + name: "a loop feeding a second loop", + graph: { + nodes: [ + {expression: "first", inputField: "items", outputPath: "stage1", executionMode: "loop", fields: {v: "x + 1"}}, + {expression: "second", inputField: "stage1", outputPath: "stage2", executionMode: "loop", fields: {w: "v * 10"}}, + ], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {stage2: [{w: 20}, {w: 30}]}], + [{items: []}, {stage2: []}], + ], +} + +{ + name: "switch routes before a loop", + graph: { + nodes: [ + {switch: "route", when: ["len(items) > 0", ""]}, + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {v: "x"}}, + {expression: "none", fields: {out: "'empty'"}}, + ], + edges: ["input -> route", "route:0 -> each -> output", "route:1 -> none -> output"], + }, + cases: [ + [{items: [{x: 1}]}, {out: [{v: 1}]}], + [{items: []}, {out: "empty"}], + [{items: [{x: "a"}, {x: null}]}, {out: [{v: "a"}, {v: null}]}], + ], +} + +// --- Decision tables in loop mode ------------------------------------------------------------- +// The table is evaluated against each item; a first-hit table yields the matched outputs (or +// an empty object), a collect table yields an array per item. +{ + name: "first-hit table per item", + graph: { + nodes: [{table: "grade", inputField: "students", outputPath: "grades", executionMode: "loop", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 50", "'B'"], + ["", "'F'"], + ]}], + }, + cases: [ + [{students: [{score: 95}, {score: 60}, {score: 10}]}, {grades: [{grade: "A"}, {grade: "B"}, {grade: "F"}]}], + [{students: []}, {grades: []}], + [{students: [{score: 90}]}, {grades: [{grade: "A"}]}], + ], +} + +{ + name: "first-hit table per item with no match yields null", + graph: { + nodes: [{table: "grade", inputField: "students", outputPath: "grades", executionMode: "loop", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + ]}], + }, + cases: [ + [{students: [{score: 95}, {score: 10}]}, {grades: [{grade: "A"}, null]}, "question: a non-matching first-hit table outputs null; in single mode the graph merge hides it as {}, in a loop the null lands in the result array"], + [{students: [{score: 1}]}, {grades: [null]}, "question: a non-matching first-hit table outputs null; in single mode the graph merge hides it as {}, in a loop the null lands in the result array"], + [{students: [{}]}, {grades: [null]}, "question: a non-matching first-hit table outputs null; in single mode the graph merge hides it as {}, in a loop the null lands in the result array"], + [{students: [{score: 99}]}, {grades: [{grade: "A"}]}], + ], +} + +{ + name: "collect table per item yields an array per item", + graph: { + nodes: [{table: "tags", hit: "collect", inputField: "items", outputPath: "tags", executionMode: "loop", inputs: ["v"], outputs: ["tag"], rules: [ + ["> 0", "'positive'"], + ["> 10", "'big'"], + ["< 0", "'negative'"], + ]}], + }, + cases: [ + [{items: [{v: 20}, {v: -1}, {v: 0}]}, {tags: [[{tag: "positive"}, {tag: "big"}], [{tag: "negative"}], []]}], + [{items: [{v: 5}]}, {tags: [[{tag: "positive"}]]}], + [{items: []}, {tags: []}], + ], +} + +{ + name: "table loop with passThrough merges each item with its row", + graph: { + nodes: [{table: "rate", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, inputs: ["kind"], outputs: ["rate"], rules: [ + ["'a'", "0.1"], + ["", "0"], + ]}], + }, + cases: [ + [{id: 1, items: [{kind: "a"}, {kind: "b"}]}, {id: 1, items: [{kind: "a", rate: 0.1}, {kind: "b", rate: 0}]}], + [{id: 2, items: []}, {id: 2, items: []}], + ], +} + +{ + name: "table loop over scalars uses $root as the input field", + graph: { + nodes: [{table: "sign", inputField: "nums", outputPath: "out", executionMode: "loop", inputs: ["$root"], outputs: ["sign"], rules: [ + ["> 0", "'+'"], + ["< 0", "'-'"], + ["", "'0'"], + ]}], + }, + cases: [ + [{nums: [3, -2, 0]}, {out: [{sign: "+"}, {sign: "-"}, {sign: "0"}]}], + [{nums: []}, {out: []}], + ], +} + +{ + name: "table loop over a non-array is an error", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["v"], outputs: ["r"], rules: [["", "1"]]}], + }, + cases: [ + [{items: [{}]}, {out: [{r: 1}]}], + [{items: {v: 1}}, "!error"], + [{}, "!error"], + [{items: null}, "!error"], + ], +} + +{ + name: "table loop output cells read the item", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["kind"], outputs: ["label", "doubled"], rules: [ + ["'x'", "'X:' + name", "n * 2"], + ["", "name", "n"], + ]}], + }, + cases: [ + [{items: [{kind: "x", name: "a", n: 2}, {kind: "y", name: "b", n: 3}]}, {out: [{label: "X:a", doubled: 4}, {label: "b", doubled: 3}]}], + ], +} + +{ + name: "table loop on a nested input field", + graph: { + nodes: [{table: "t", inputField: "order.lines", outputPath: "order.rated", executionMode: "loop", inputs: ["product.type"], outputs: ["vat"], rules: [ + ["'food'", "0.05"], + ["", "0.2"], + ]}], + }, + cases: [ + [{order: {lines: [{product: {type: "food"}}, {product: {type: "tv"}}, {product: null}]}}, {order: {rated: [{vat: 0.05}, {vat: 0.2}, {vat: 0.2}]}}], + [{order: {lines: []}}, {order: {rated: []}}], + ], +} + +// --- Decision nodes in loop mode -------------------------------------------------------------- +// Each item is evaluated by the sub-decision; results are collected in order. +{ + name: "sub-decision per item", + decisions: { + price: {nodes: [{expression: "calc", fields: {total: "price * qty"}}]}, + }, + graph: { + nodes: [{decision: "each", key: "price", inputField: "items", outputPath: "lines", executionMode: "loop"}], + }, + cases: [ + [{items: [{price: 2, qty: 3}, {price: 4, qty: 1}]}, {lines: [{total: 6}, {total: 4}]}], + [{items: []}, {lines: []}], + [{items: [{price: 0.5, qty: 2}]}, {lines: [{total: 1}]}], + ], +} + +{ + name: "sub-decision per item with a table and switch inside", + decisions: { + classify: { + nodes: [ + {switch: "s", when: ["amount > 1000", ""]}, + {expression: "big", fields: {kind: "'big'", review: "true"}}, + {table: "small", inputs: ["amount"], outputs: ["kind"], rules: [["< 10", "'tiny'"], ["", "'small'"]]}, + ], + edges: ["input -> s", "s:0 -> big -> output", "s:1 -> small -> output"], + }, + }, + graph: { + nodes: [{decision: "each", key: "classify", inputField: "txs", outputPath: "kinds", executionMode: "loop"}], + }, + cases: [ + [{txs: [{amount: 5000}, {amount: 5}, {amount: 50}]}, {kinds: [{kind: "big", review: true}, {kind: "tiny"}, {kind: "small"}]}], + [{txs: [{amount: 50}, {amount: 5000}]}, {kinds: [{kind: "small"}, {kind: "big", review: true}]}], + [{txs: []}, {kinds: []}], + ], +} + +{ + name: "sub-decision loop with passThrough", + decisions: { + flag: {nodes: [{expression: "f", fields: {flagged: "score < 0.5"}}]}, + }, + graph: { + nodes: [{decision: "each", key: "flag", inputField: "users", outputPath: "users", executionMode: "loop", passThrough: true}], + }, + cases: [ + [{batch: 1, users: [{id: "a", score: 0.2}, {id: "b", score: 0.9}]}, {batch: 1, users: [{id: "a", score: 0.2, flagged: true}, {id: "b", score: 0.9, flagged: false}]}], + [{batch: 2, users: []}, {batch: 2, users: []}], + ], +} + +{ + name: "sub-decision loop over a non-array is an error", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "1"}}]}, + }, + graph: { + nodes: [{decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{}, {}]}, {out: [{v: 1}, {v: 1}]}], + [{items: {}}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "sub-decision loop: an item failing in the child fails the parent", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "a + 1"}}]}, + }, + graph: { + nodes: [{decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{a: 1}, {a: 2}]}, {out: [{v: 2}, {v: 3}]}], + [{items: [{a: 1}, {a: "x"}]}, "!error"], + ], +} + +{ + name: "sub-decision loop over scalar items", + decisions: { + child: {nodes: [{expression: "e", fields: {sq: "$root * $root"}}]}, + }, + graph: { + nodes: [{decision: "each", key: "child", inputField: "nums", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{nums: [2, 3]}, "!error", "question: the child's first node sees {} because graph-edge merging drops non-object values, so a scalar item never reaches the child's nodes"], + [{nums: []}, {out: []}], + ], +} + +{ + name: "sub-decision state does not leak between items", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["kind == 'a'", ""]}, + {expression: "a", fields: {fromA: "true"}}, + {expression: "b", fields: {fromB: "true"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + }, + graph: { + nodes: [{decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{kind: "a"}, {kind: "b"}, {kind: "a"}]}, {out: [{fromA: true}, {fromB: true}, {fromA: true}]}], + [{items: [{kind: "b"}, {kind: "a"}]}, {out: [{fromB: true}, {fromA: true}]}], + ], +} + +// --- Nested loops ------------------------------------------------------------------------------ +// A loop over outer items calls a sub-decision that itself loops over the inner items. +{ + name: "nested loops through a sub-decision", + decisions: { + order: {nodes: [ + {expression: "lines", inputField: "lines", outputPath: "lines", executionMode: "loop", fields: {total: "price * qty"}}, + {expression: "sum", fields: {total: "sum(map(lines, #.total))", lines: "lines"}}, + ]}, + }, + graph: { + nodes: [{decision: "orders", key: "order", inputField: "orders", outputPath: "orders", executionMode: "loop"}], + }, + cases: [ + [ + {orders: [{lines: [{price: 2, qty: 1}, {price: 3, qty: 2}]}, {lines: []}]}, + {orders: [{total: 8, lines: [{total: 2}, {total: 6}]}, {total: 0, lines: []}]}, + ], + [{orders: []}, {orders: []}], + [{orders: [{lines: [{price: 1, qty: 1}]}]}, {orders: [{total: 1, lines: [{total: 1}]}]}], + ], +} + +{ + name: "nested sub-decision loops two levels deep", + decisions: { + cell: {nodes: [{expression: "c", fields: {v: "n * 10"}}]}, + row: {nodes: [{decision: "cells", key: "cell", inputField: "cells", outputPath: "cells", executionMode: "loop"}]}, + }, + graph: { + nodes: [{decision: "rows", key: "row", inputField: "rows", outputPath: "rows", executionMode: "loop"}], + }, + cases: [ + [{rows: [{cells: [{n: 1}, {n: 2}]}, {cells: [{n: 3}]}]}, {rows: [{cells: [{v: 10}, {v: 20}]}, {cells: [{v: 30}]}]}], + [{rows: [{cells: []}]}, {rows: [{cells: []}]}], + [{rows: []}, {rows: []}], + ], +} + +{ + name: "inner loop error bubbles through the outer loop", + decisions: { + inner: {nodes: [{expression: "e", inputField: "xs", outputPath: "xs", executionMode: "loop", fields: {v: "$root + 1"}}]}, + }, + graph: { + nodes: [{decision: "outer", key: "inner", inputField: "groups", outputPath: "groups", executionMode: "loop"}], + }, + cases: [ + [{groups: [{xs: [1]}, {xs: [2, 3]}]}, {groups: [{xs: [{v: 2}]}, {xs: [{v: 3}, {v: 4}]}]}], + [{groups: [{xs: [1]}, {xs: "nope"}]}, "!error"], + [{groups: [{xs: [1, "a"]}]}, "!error"], + ], +} + +// --- Single mode and explicit modes ------------------------------------------------------------- +// executionMode "single" (the default) treats the selected value as one input, even an array. +{ + name: "single mode with inputField evaluates once against the selected value", + graph: { + nodes: [{expression: "e", inputField: "customer", outputPath: "out", executionMode: "single", fields: {n: "name"}}], + }, + cases: [ + [{customer: {name: "ann"}}, {out: {n: "ann"}}], + [{customer: {}}, {out: {n: null}}], + [{}, {out: {n: null}}], + ], +} + +{ + name: "single mode over an array input does not iterate", + graph: { + nodes: [{expression: "e", inputField: "items", outputPath: "out", executionMode: "single", fields: {n: "len($root)"}}], + }, + cases: [ + [{items: [1, 2, 3]}, {out: {n: 3}}], + [{items: []}, {out: {n: 0}}], + ], +} + +// --- Larger loops -------------------------------------------------------------------------------- +{ + name: "loop preserves order over many items", + graph: { + nodes: [{expression: "each", inputField: "map([1..20], {i: #})", outputPath: "out", executionMode: "loop", fields: {i: "i"}}], + edges: ["input -> each -> output"], + }, + cases: [ + [{}, {out: [{i: 1}, {i: 2}, {i: 3}, {i: 4}, {i: 5}, {i: 6}, {i: 7}, {i: 8}, {i: 9}, {i: 10}, {i: 11}, {i: 12}, {i: 13}, {i: 14}, {i: 15}, {i: 16}, {i: 17}, {i: 18}, {i: 19}, {i: 20}]}], + ], +} + +{ + name: "loop items with mixed shapes", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {t: "type($root)"}}], + }, + cases: [ + [{items: [1, "a", true, null, [1], {x: 1}]}, {out: [{t: "number"}, {t: "string"}, {t: "bool"}, {t: "null"}, {t: "array"}, {t: "object"}]}], + ], +} diff --git a/core/engine/tests/spec/graph/14-sub-decisions.json5 b/core/engine/tests/spec/graph/14-sub-decisions.json5 new file mode 100644 index 00000000..81478f05 --- /dev/null +++ b/core/engine/tests/spec/graph/14-sub-decisions.json5 @@ -0,0 +1,813 @@ +// Decision nodes: a node that evaluates another decision (loaded by key) with its own input and +// returns that decision's result as its output. + +// --- Basic calls --------------------------------------------------------------------------------- +// The child receives the decision node's input and its result becomes the node output. +{ + name: "child result replaces the node input", + decisions: { + child: {nodes: [{expression: "e", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 4}, {y: 8}], + [{x: 0.5}, {y: 1}], + [{x: -3, other: true}, {y: -6}], + [{x: "a"}, "!error"], + ], +} + +{ + name: "an empty child graph echoes its input", + decisions: { + child: {}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{a: 1, b: {c: [1, 2]}}, {a: 1, b: {c: [1, 2]}}], + [{}, {}], + [{s: "x", n: null}, {s: "x"}, "question: the child's final merge drops its top-level null values (as for a root graph, see 10-merges), so they are missing in the parent even under an outputPath"], + ], +} + +{ + name: "child with a pass-through expression keeps the parent's fields", + decisions: { + child: {nodes: [{expression: "e", passThrough: true, fields: {sum: "a + b"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, sum: 3}], + [{a: 1, b: 2, sum: 99}, {a: 1, b: 2, sum: 3}], + ], +} + +{ + name: "child result is merged with parallel parent branches", + decisions: { + child: {nodes: [{expression: "e", fields: {fromChild: "x + 1"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {expression: "local", fields: {fromParent: "x - 1"}}, + ], + edges: ["input -> call -> output", "input -> local -> output"], + }, + cases: [ + [{x: 10}, {fromChild: 11, fromParent: 9}], + [{x: 0}, {fromChild: 1, fromParent: -1}], + ], +} + +{ + name: "parent nodes after the call see the child result", + decisions: { + child: {nodes: [{expression: "e", fields: {score: "a * 10"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {expression: "after", fields: {grade: "score >= 50 ? 'pass' : 'fail'", hasA: "a != null"}}, + ], + }, + cases: [ + [{a: 7}, {grade: "pass", hasA: false}], + [{a: 2}, {grade: "fail", hasA: false}], + ], +} + +{ + name: "the same child called from two nodes", + decisions: { + child: {nodes: [{expression: "e", fields: {"out.double": "v * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "first", key: "child", inputField: "a", outputPath: "a"}, + {decision: "second", key: "child", inputField: "b", outputPath: "b"}, + ], + edges: ["input -> first -> output", "input -> second -> output"], + }, + cases: [ + [{a: {v: 1}, b: {v: 2}}, {a: {out: {double: 2}}, b: {out: {double: 4}}}], + [{a: {v: 0}, b: {v: -5}}, {a: {out: {double: 0}}, b: {out: {double: -10}}}], + ], +} + +{ + name: "two different children in sequence", + decisions: { + enrich: {nodes: [{expression: "e", passThrough: true, fields: {tier: "spend > 100 ? 'gold' : 'basic'"}}]}, + price: {nodes: [{table: "t", inputs: ["tier"], outputs: ["discount"], rules: [["'gold'", "0.2"], ["", "0"]]}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "enrich"}, + {decision: "b", key: "price"}, + ], + }, + cases: [ + [{spend: 500}, {discount: 0.2}], + [{spend: 10}, {discount: 0}], + [{}, "!error"], + ], +} + +// --- Nesting ------------------------------------------------------------------------------------- +// A child can itself call further children, several levels deep. +{ + name: "three levels of nesting", + decisions: { + level1: {nodes: [{expression: "e1", passThrough: true, fields: {l1: "v + 1"}}, {decision: "d2", key: "level2"}]}, + level2: {nodes: [{expression: "e2", passThrough: true, fields: {l2: "l1 + 1"}}, {decision: "d3", key: "level3"}]}, + level3: {nodes: [{expression: "e3", passThrough: true, fields: {l3: "l2 + 1"}}]}, + }, + graph: { + nodes: [{decision: "d1", key: "level1"}], + }, + cases: [ + [{v: 0}, {v: 0, l1: 1, l2: 2, l3: 3}], + [{v: 10}, {v: 10, l1: 11, l2: 12, l3: 13}], + [{v: "x"}, "!error"], + ], +} + +{ + name: "nested children with outputPath at each level", + decisions: { + outer: {nodes: [{decision: "inner", key: "inner", outputPath: "inner"}]}, + inner: {nodes: [{expression: "e", fields: {v: "x"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "outer", outputPath: "outer"}], + }, + cases: [ + [{x: 1}, {outer: {inner: {v: 1}}}], + [{x: null}, {outer: {inner: {}}}, "question: the child's final merge drops its top-level null values (as for a root graph, see 10-merges), so they are missing in the parent even under an outputPath"], + [{}, {outer: {inner: {}}}, "question: the child's final merge drops its top-level null values (as for a root graph, see 10-merges), so they are missing in the parent even under an outputPath"], + ], +} + +{ + name: "eight levels of nesting stays within the depth limit", + decisions: { + d1: {nodes: [{decision: "n", key: "d2"}]}, + d2: {nodes: [{decision: "n", key: "d3"}]}, + d3: {nodes: [{decision: "n", key: "d4"}]}, + d4: {nodes: [{decision: "n", key: "d5"}]}, + d5: {nodes: [{decision: "n", key: "d6"}]}, + d6: {nodes: [{decision: "n", key: "d7"}]}, + d7: {nodes: [{decision: "n", key: "d8"}]}, + d8: {nodes: [{expression: "e", fields: {deep: "v * 2"}}]}, + }, + graph: { + nodes: [{decision: "n", key: "d1"}], + }, + cases: [ + [{v: 1}, {deep: 2}], + [{v: 21}, {deep: 42}], + ], +} + +// --- Recursion and the depth limit ----------------------------------------------------------- +// A decision may call itself; recursion is bounded by the evaluation depth limit (default 10: +// the root runs at depth 0 and a graph at depth 10 is refused). +{ + name: "recursive countdown terminates through a switch", + decisions: { + countdown: { + nodes: [ + {switch: "s", when: ["n > 0", ""]}, + {expression: "step", fields: {n: "n - 1", acc: "(acc ?? 0) + n"}}, + {decision: "again", key: "countdown"}, + {expression: "done", fields: {acc: "acc ?? 0"}}, + ], + edges: ["input -> s", "s:0 -> step -> again -> output", "s:1 -> done -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "countdown"}], + }, + cases: [ + [{n: 0}, {acc: 0}], + [{n: 1}, {acc: 1}], + [{n: 3}, {acc: 6}], + [{n: 8}, {acc: 36}], + [{n: 9}, "!error"], + [{n: 50}, "!error"], + ], +} + +{ + name: "unbounded self-recursion hits the depth limit", + decisions: { + forever: {nodes: [{decision: "again", key: "forever"}]}, + }, + graph: { + nodes: [{decision: "call", key: "forever"}], + }, + cases: [ + [{}, "!error"], + [{a: 1}, "!error"], + ], +} + +{ + name: "mutual recursion hits the depth limit", + decisions: { + ping: {nodes: [{expression: "e", passThrough: true, fields: {n: "(n ?? 0) + 1"}}, {decision: "d", key: "pong"}]}, + pong: {nodes: [{decision: "d", key: "ping"}]}, + }, + graph: { + nodes: [{decision: "call", key: "ping"}], + }, + cases: [ + [{}, "!error"], + [{n: 100}, "!error"], + ], +} + +{ + name: "graph calling itself under its own key", + decisions: { + self: { + nodes: [ + {switch: "s", when: ["len(xs) > 0", ""]}, + {expression: "pop", fields: {xs: "xs[1:]", total: "(total ?? 0) + xs[0]"}}, + {decision: "again", key: "self"}, + {expression: "end", fields: {total: "total ?? 0"}}, + ], + edges: ["input -> s", "s:0 -> pop -> again -> output", "s:1 -> end -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "self"}], + }, + cases: [ + [{xs: []}, {total: 0}], + [{xs: [5]}, {total: 5}], + [{xs: [1, 2, 3, 4]}, {total: 10}], + [{xs: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}, "!error"], + ], +} + +// --- Missing and unusable children --------------------------------------------------------- +{ + name: "missing key is an error", + graph: { + nodes: [{decision: "call", key: "nowhere"}], + }, + cases: [ + [{}, "!error"], + [{x: 1}, "!error"], + ], +} + +{ + name: "missing key on a switch branch not taken is not an error", + graph: { + nodes: [ + {switch: "s", when: ["go", ""]}, + {decision: "call", key: "nowhere"}, + {expression: "skip", fields: {skipped: "true"}}, + ], + edges: ["input -> s", "s:0 -> call -> output", "s:1 -> skip -> output"], + }, + cases: [ + [{go: false}, {skipped: true}], + [{go: true}, "!error"], + ], +} + +{ + name: "missing key in a nested child", + decisions: { + child: {nodes: [{decision: "inner", key: "nowhere"}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, "!error"], + [{a: 1}, "!error"], + ], +} + +{ + name: "child with a cycle is an error", + decisions: { + child: { + nodes: [{expression: "a", fields: {x: "1"}}, {expression: "b", fields: {y: "2"}}], + edges: ["input -> a -> b -> a", "b -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, "!error"], + [{z: 1}, "!error"], + ], +} + +{ + name: "child with two input nodes is an error", + decisions: { + child: {raw: { + nodes: [ + {id: "i1", name: "in1", type: "inputNode", content: {}}, + {id: "i2", name: "in2", type: "inputNode", content: {}}, + {id: "o", name: "out", type: "outputNode", content: {}}, + ], + edges: [{id: "e1", sourceId: "i1", targetId: "o"}, {id: "e2", sourceId: "i2", targetId: "o"}], + }}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, "!error"], + [{a: 1}, "!error"], + ], +} + +// --- Child errors propagate ------------------------------------------------------------------ +{ + name: "an expression error in the child fails the parent", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "a / b"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{a: 6, b: 3}, {v: 2}], + [{a: "x", b: 3}, "!error"], + [{a: 1, b: 0}, {}, "question: division by zero yields null rather than an error; the null is then dropped by the child's final merge"], + ], +} + +{ + name: "a failing custom node in the child fails the parent", + decisions: { + child: {nodes: [{custom: "c", kind: "fail", config: {message: "boom"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, "!error: boom"], + [{x: 1}, "!error: boom"], + ], +} + +{ + name: "a child error only on the taken branch", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["safe", ""]}, + {expression: "ok", fields: {r: "'ok'"}}, + {custom: "bad", kind: "fail", config: {message: "unsafe branch"}}, + ], + edges: ["input -> s", "s:0 -> ok -> output", "s:1 -> bad -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{safe: true}, {r: "ok"}], + [{safe: false}, "!error: unsafe branch"], + [{}, "!error: unsafe branch"], + ], +} + +{ + name: "child input schema rejects the call", + decisions: { + child: {nodes: [ + {input: "in", schema: {type: "object", properties: {age: {type: "number"}}, required: ["age"]}}, + {expression: "e", fields: {adult: "age >= 18"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{age: 20}, {adult: true}], + [{age: 3}, {adult: false}], + [{}, "!error"], + [{age: "old"}, "!error"], + ], +} + +{ + name: "child output schema rejects the result", + decisions: { + child: {nodes: [ + {expression: "e", fields: {total: "a + b"}}, + {output: "out", schema: {type: "object", properties: {total: {type: "number", maximum: 100}}}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{a: 1, b: 2}, {total: 3}], + [{a: 99, b: 2}, "!error"], + ], +} + +{ + name: "a deep error surfaces from the innermost child", + decisions: { + a: {nodes: [{decision: "n", key: "b"}]}, + b: {nodes: [{decision: "n", key: "c"}]}, + c: {nodes: [{custom: "f", kind: "fail", config: {message: "deep failure"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "a"}], + }, + cases: [ + [{}, "!error: deep failure"], + [{v: 1}, "!error: deep failure"], + ], +} + +// --- Children with switches and tables ---------------------------------------------------- +{ + name: "child with a first-hit switch", + decisions: { + route: { + nodes: [ + {switch: "s", when: ["amount > 1000", "amount > 100", ""]}, + {expression: "high", fields: {band: "'high'"}}, + {expression: "mid", fields: {band: "'mid'"}}, + {expression: "low", fields: {band: "'low'"}}, + ], + edges: ["input -> s", "s:0 -> high -> output", "s:1 -> mid -> output", "s:2 -> low -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "route"}], + }, + cases: [ + [{amount: 5000}, {band: "high"}], + [{amount: 500}, {band: "mid"}], + [{amount: 5}, {band: "low"}], + [{amount: null}, {band: "low"}], + ], +} + +{ + name: "child with a collect switch merges taken branches", + decisions: { + flags: { + nodes: [ + {switch: "s", hit: "collect", when: ["age < 18", "country != 'US'", "vip"]}, + {expression: "minor", fields: {minor: "true"}}, + {expression: "foreign", fields: {foreign: "true"}}, + {expression: "vip", fields: {vip: "true"}}, + ], + edges: ["input -> s", "s:0 -> minor -> output", "s:1 -> foreign -> output", "s:2 -> vip -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "flags", outputPath: "flags"}], + }, + cases: [ + [{age: 10, country: "DE", vip: true}, {flags: {minor: true, foreign: true, vip: true}}], + [{age: 30, country: "US", vip: false}, {flags: {}}], + [{age: 30, country: "FR", vip: false}, {flags: {foreign: true}}], + ], +} + +{ + name: "child with a first-hit table", + decisions: { + rates: {nodes: [{table: "t", inputs: ["tier", "years"], outputs: ["rate"], rules: [ + ["'gold'", ">= 5", "0.03"], + ["'gold'", "", "0.02"], + ["", "", "0.01"], + ]}]}, + }, + graph: { + nodes: [{decision: "call", key: "rates", outputPath: "pricing"}], + }, + cases: [ + [{tier: "gold", years: 7}, {pricing: {rate: 0.03}}], + [{tier: "gold", years: 1}, {pricing: {rate: 0.02}}], + [{tier: "silver", years: 9}, {pricing: {rate: 0.01}}], + [{}, {pricing: {rate: 0.01}}], + ], +} + +{ + name: "child with a collect table returns an array", + decisions: { + tags: {nodes: [{table: "t", hit: "collect", inputs: ["score"], outputs: ["tag"], rules: [ + ["> 50", "'high'"], + ["> 90", "'top'"], + ["< 10", "'low'"], + ]}]}, + }, + graph: { + nodes: [{decision: "call", key: "tags", outputPath: "tags"}], + }, + cases: [ + [{score: 95}, {tags: [{tag: "high"}, {tag: "top"}]}], + [{score: 60}, {tags: [{tag: "high"}]}], + [{score: 30}, {tags: []}], + [{score: 1}, {tags: [{tag: "low"}]}], + ], +} + +{ + name: "child table with no match", + decisions: { + t: {nodes: [{table: "t", inputs: ["v"], outputs: ["r"], rules: [["1", "'one'"]]}]}, + }, + graph: { + nodes: [{decision: "call", key: "t", outputPath: "res"}], + }, + cases: [ + [{v: 1}, {res: {r: "one"}}], + [{v: 2}, {res: {}}], + ], +} + +// --- Children returning non-objects ------------------------------------------------------------ +// A child's result is the merge of its ending nodes: arrays survive, scalars collapse to {}. +{ + name: "child returning an array", + decisions: { + child: {nodes: [{expression: "e", inputField: "xs", executionMode: "loop", fields: {v: "$root + 1"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{xs: [1, 2]}, {out: [{v: 2}, {v: 3}]}], + [{xs: []}, {out: []}], + ], +} + +{ + name: "child returning an array without outputPath", + decisions: { + child: {nodes: [{expression: "e", inputField: "xs", executionMode: "loop", fields: {v: "$root"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{xs: [7]}, [{v: 7}]], + [{xs: [1, 2, 3]}, [{v: 1}, {v: 2}, {v: 3}]], + ], +} + +{ + name: "child returning a scalar from a function node", + decisions: { + child: {nodes: [{function: "f", source: """export const handler = async (input) => input.n * 2;"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{n: 2}, {out: {}}, "question: a scalar function result is dropped at the child's output (ending merge starts from {}), so the parent sees {}"], + [{n: 0}, {out: {}}, "question: a scalar function result is dropped at the child's output (ending merge starts from {}), so the parent sees {}"], + ], +} + +{ + name: "child output from two ending branches is merged", + decisions: { + child: { + nodes: [{expression: "a", fields: {a: "1", shared: "'a'"}}, {expression: "b", fields: {b: "2", shared: "'b'"}}], + edges: ["input -> a -> output", "input -> b -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, {a: 1, b: 2, shared: "a"}, "question: at the child's output fan-in the first branch keeps a shared key; which branch wins is not obvious from the graph"], + ], +} + +{ + name: "child with no output node reachable returns its ending nodes", + decisions: { + child: {raw: { + nodes: [ + {id: "i", name: "in", type: "inputNode", content: {}}, + {id: "e", name: "calc", type: "expressionNode", content: {expressions: [{id: "x", key: "v", value: "a + 1"}], passThrough: false}}, + {id: "o", name: "out", type: "outputNode", content: {}}, + ], + edges: [{id: "e1", sourceId: "i", targetId: "e"}], + }}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{a: 1}, {v: 2}, "question: a child without an edge into its output node returns the dangling ending node's result"], + ], +} + +// --- Transform attributes on decision nodes ------------------------------------------------------ +{ + name: "inputField selects the child's input", + decisions: { + child: {nodes: [{expression: "e", fields: {greeting: "'hi ' + name"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "customer"}], + }, + cases: [ + [{customer: {name: "ann"}}, {greeting: "hi ann"}], + [{customer: {name: "bo"}, name: "outer"}, {greeting: "hi bo"}], + ], +} + +{ + name: "inputField to a missing or non-object field", + decisions: { + child: {nodes: [{expression: "e", fields: {n: "name ?? 'none'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "customer", outputPath: "out"}], + }, + cases: [ + [{customer: {name: "ann"}}, {out: {n: "ann"}}], + [{}, {out: {n: "none"}}], + [{customer: null}, {out: {n: "none"}}], + [{customer: 5}, {out: {n: "none"}}], + ], +} + +{ + name: "inputField as an expression", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "a + b"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "{a: x * 2, b: y}", outputPath: "res"}], + }, + cases: [ + [{x: 1, y: 1}, {res: {total: 3}}], + [{x: 5, y: 0}, {res: {total: 10}}], + ], +} + +{ + name: "outputPath nests the child result", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "x"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "result.inner"}], + }, + cases: [ + [{x: 1}, {result: {inner: {v: 1}}}], + [{x: [1]}, {result: {inner: {v: [1]}}}], + ], +} + +{ + name: "passThrough keeps the parent input next to the child result", + decisions: { + child: {nodes: [{expression: "e", fields: {score: "a + b"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, score: 3}], + [{a: 1, b: 2, score: 0}, {a: 1, b: 2, score: 3}], + ], +} + +{ + name: "passThrough with outputPath", + decisions: { + child: {nodes: [{expression: "e", fields: {score: "a + b"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true, outputPath: "child"}], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, child: {score: 3}}], + [{a: 1, b: 2, child: {old: true}}, {a: 1, b: 2, child: {old: true, score: 3}}], + ], +} + +{ + name: "passThrough, inputField and outputPath together", + decisions: { + child: {nodes: [{expression: "e", fields: {upper: "upper(name)"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true, inputField: "customer", outputPath: "customer"}], + }, + cases: [ + [{id: 1, customer: {name: "ann", age: 3}}, {id: 1, customer: {name: "ann", age: 3, upper: "ANN"}}], + [{id: 2, customer: {name: ""}}, {id: 2, customer: {name: "", upper: ""}}], + ], +} + +// --- Policies as children ------------------------------------------------------------------------ +// A decision node expects a graph; a key naming a policy is reported as an error. +{ + name: "a policy child is rejected", + decisions: { + pol: {policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }}, + }, + graph: { + nodes: [{decision: "call", key: "pol"}], + }, + cases: [ + [{customer: {age: 20}}, "!error: expected graph"], + [{customer: {age: 1}}, "!error: expected graph"], + ], +} + +// --- Children seen from the parent graph ------------------------------------------------ +{ + name: "child nodes are not visible through the parent's $nodes", + decisions: { + child: {nodes: [{expression: "inner", fields: {v: "1"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {expression: "after", fields: {callOut: "$nodes.call.v", inner: "$nodes.inner"}}, + ], + }, + cases: [ + [{}, {callOut: 1}], + [{v: 9}, {callOut: 1}], + ], +} + +{ + name: "child with a function node", + decisions: { + child: {nodes: [{function: "f", source: """export const handler = async (input) => ({len: input.items.length, first: input.items[0] ?? null});"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "info"}], + }, + cases: [ + [{items: [3, 4]}, {info: {len: 2, first: 3}}], + [{items: []}, {info: {len: 0}}, "question: the child's final merge drops its top-level null values (as for a root graph, see 10-merges), so they are missing in the parent even under an outputPath"], + [{}, "!error"], + ], +} + +{ + name: "child with a custom node", + decisions: { + child: {nodes: [{custom: "c", kind: "render", config: {msg: "{{ who }} ok"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{who: "ann"}, {who: "ann", msg: "ann ok"}], + [{who: "bo"}, {who: "bo", msg: "bo ok"}], + ], +} + +{ + name: "sub-decision on one switch branch only", + decisions: { + scoring: {nodes: [{expression: "e", fields: {score: "income / 1000"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["income != null", ""]}, + {decision: "score", key: "scoring"}, + {expression: "none", fields: {score: "0"}}, + ], + edges: ["input -> s", "s:0 -> score -> output", "s:1 -> none -> output"], + }, + cases: [ + [{income: 50000}, {score: 50}], + [{}, {score: 0}], + [{income: null}, {score: 0}], + [{income: 1500}, {score: 1.5}], + ], +} diff --git a/core/engine/tests/spec/graph/15-nodes-references.json5 b/core/engine/tests/spec/graph/15-nodes-references.json5 new file mode 100644 index 00000000..4db50c92 --- /dev/null +++ b/core/engine/tests/spec/graph/15-nodes-references.json5 @@ -0,0 +1,1017 @@ +// `$nodes`: every node can read the outputs of nodes that already ran, by node name, next to its +// regular input. `$nodes.` is the node's output as produced (before merging at joins). + +// --- Reading the input node ------------------------------------------------------------------- +// The input node's output is the request itself. +{ + name: "$nodes.input reads the request", + graph: { + nodes: [{expression: "e", fields: {a: "$nodes.input.a", same: "$nodes.input.a == a"}}], + }, + cases: [ + [{a: 1}, {a: 1, same: true}], + [{a: "x"}, {a: "x", same: true}], + [{a: null}, {same: true}], + [{}, {same: true}], + ], +} + +{ + name: "$nodes. follows the input node's name", + graph: { + nodes: [ + {input: "request"}, + {expression: "e", fields: {v: "$nodes.request.v", viaDefault: "$nodes.input"}}, + ], + }, + cases: [ + [{v: 5}, {v: 5}], + [{v: true}, {v: true}], + ], +} + +{ + name: "$nodes.input keeps the original request after transforms", + graph: { + nodes: [ + {expression: "a", fields: {x: "x * 10"}}, + {expression: "b", fields: {now: "x", original: "$nodes.input.x"}}, + ], + }, + cases: [ + [{x: 1}, {now: 10, original: 1}], + [{x: 0.5}, {now: 5, original: 0.5}], + ], +} + +{ + name: "$nodes.input nested paths", + graph: { + nodes: [{expression: "e", fields: {city: "$nodes.input.customer.address.city", first: "$nodes.input.items[0]", n: "len($nodes.input.items)"}}], + }, + cases: [ + [{customer: {address: {city: "Oslo"}}, items: [7, 8]}, {city: "Oslo", first: 7, n: 2}], + [{customer: {address: {}}, items: []}, {n: 0}], + [{customer: null, items: ["a"]}, {first: "a", n: 1}], + ], +} + +// --- Reading earlier nodes --------------------------------------------------------------------- +{ + name: "reading an earlier node's output", + graph: { + nodes: [ + {expression: "calc", fields: {total: "price * qty"}}, + {expression: "fee", fields: {fee: "$nodes.calc.total * 0.1"}}, + {expression: "sum", fields: {grand: "$nodes.calc.total + $nodes.fee.fee"}}, + ], + }, + cases: [ + [{price: 10, qty: 2}, {grand: 22}], + [{price: 5, qty: 0}, {grand: 0}], + [{price: 0.1, qty: 3}, {grand: 0.33}], + ], +} + +{ + name: "a node two steps back is still readable", + graph: { + nodes: [ + {expression: "a", fields: {fromA: "x + 1"}}, + {expression: "b", fields: {fromB: "fromA + 1"}}, + {expression: "c", fields: {fromC: "fromB + 1", stillA: "$nodes.a.fromA", inputX: "$nodes.input.x"}}, + ], + }, + cases: [ + [{x: 0}, {fromC: 3, stillA: 1, inputX: 0}], + [{x: 10}, {fromC: 13, stillA: 11, inputX: 10}], + ], +} + +{ + name: "reading a node on a parallel branch that already ran", + graph: { + nodes: [ + {expression: "left", fields: {l: "x * 2"}}, + {expression: "right", fields: {r: "x * 3"}}, + {expression: "join", fields: {both: "$nodes.left.l + $nodes.right.r"}}, + ], + edges: ["input -> left -> join", "input -> right -> join", "join -> output"], + }, + cases: [ + [{x: 1}, {both: 5}], + [{x: 2}, {both: 10}], + ], +} + +{ + name: "$nodes shows the node's own output, not the merged join input", + graph: { + nodes: [ + {expression: "left", fields: {k: "'left'", l: "1"}}, + {expression: "right", fields: {k: "'right'", r: "2"}}, + {expression: "join", fields: {leftK: "$nodes.left.k", rightK: "$nodes.right.k", leftHasR: "$nodes.left.r == null"}}, + ], + edges: ["input -> left -> join", "input -> right -> join", "join -> output"], + }, + cases: [ + [{}, {leftK: "left", rightK: "right", leftHasR: true}], + [{k: "input"}, {leftK: "left", rightK: "right", leftHasR: true}], + ], +} + +{ + name: "a whole node output as a value", + graph: { + nodes: [ + {expression: "a", fields: {x: "1", "y.z": "2"}}, + {expression: "b", fields: {copy: "$nodes.a", keys: "keys($nodes.a)"}}, + ], + }, + cases: [ + [{}, {copy: {x: 1, y: {z: 2}}, keys: ["x", "y"]}], + [{x: 9}, {copy: {x: 1, y: {z: 2}}, keys: ["x", "y"]}], + ], +} + +{ + name: "$nodes of a pass-through node includes its input", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {added: "1"}}, + {expression: "b", fields: {seen: "$nodes.a"}}, + ], + }, + cases: [ + [{v: 1}, {seen: {v: 1, added: 1}}], + [{}, {seen: {added: 1}}], + ], +} + +{ + name: "$nodes of a node with outputPath", + graph: { + nodes: [ + {expression: "a", outputPath: "nested.out", fields: {v: "x"}}, + {expression: "b", fields: {seen: "$nodes.a.nested.out.v", direct: "$nodes.a.v"}}, + ], + }, + cases: [ + [{x: 3}, {seen: 3}], + [{x: "s"}, {seen: "s"}], + ], +} + +{ + name: "$nodes of a loop node is the result array", + graph: { + nodes: [ + {expression: "each", inputField: "xs", executionMode: "loop", fields: {v: "$root * 2"}}, + {expression: "after", fields: {n: "len($nodes.each)", second: "$nodes.each[1].v"}}, + ], + }, + cases: [ + [{xs: [1, 2, 3]}, {n: 3, second: 4}], + [{xs: [5]}, {n: 1}], + [{xs: []}, {n: 0}], + ], +} + +{ + name: "$nodes of a table node", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["grade"], rules: [[">= 50", "'pass'"], ["", "'fail'"]]}, + {expression: "after", fields: {grade: "$nodes.t.grade", score: "$nodes.input.score"}}, + ], + }, + cases: [ + [{score: 70}, {grade: "pass", score: 70}], + [{score: 10}, {grade: "fail", score: 10}], + ], +} + +{ + name: "$nodes of a table that matched nothing is null", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["grade"], rules: [[">= 50", "'pass'"]]}, + {expression: "after", fields: {isNull: "$nodes.t == null", grade: "$nodes.t.grade ?? 'none'"}}, + ], + }, + cases: [ + [{score: 70}, {isNull: false, grade: "pass"}], + [{score: 10}, {isNull: true, grade: "none"}], + ], +} + +{ + name: "$nodes of a collect table is the row array", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["tag"], rules: [["> 0", "'pos'"], ["> 10", "'big'"]]}, + {expression: "after", fields: {tags: "map($nodes.t, #.tag)"}}, + ], + }, + cases: [ + [{v: 20}, {tags: ["pos", "big"]}], + [{v: 5}, {tags: ["pos"]}], + [{v: -1}, {tags: []}], + ], +} + +// --- Nodes that did not run --------------------------------------------------------------------- +// A node on a switch branch that was not taken has no entry; reading it gives null. +{ + name: "$nodes of a node on a branch not taken is null", + graph: { + nodes: [ + {switch: "s", when: ["big", ""]}, + {expression: "yes", fields: {y: "'yes'"}}, + {expression: "no", fields: {n: "'no'"}}, + {expression: "after", fields: { + yesRan: "$nodes.yes != null", + noRan: "$nodes.no != null", + y: "$nodes.yes.y ?? '-'", + n: "$nodes.no.n ?? '-'", + }}, + ], + edges: ["input -> s", "s:0 -> yes -> after", "s:1 -> no -> after", "after -> output"], + }, + cases: [ + [{big: true}, {yesRan: true, noRan: false, y: "yes", n: "-"}], + [{big: false}, {yesRan: false, noRan: true, y: "-", n: "no"}], + [{}, {yesRan: false, noRan: true, y: "-", n: "no"}], + ], +} + +{ + name: "a member read on a node that did not run is null, not an error", + graph: { + nodes: [ + {switch: "s", when: ["go", ""]}, + {expression: "deep", fields: {"a.b.c": "1"}}, + {expression: "skip", fields: {}}, + {expression: "after", fields: {v: "$nodes.deep.a.b.c", isNull: "$nodes.deep.a.b.c == null"}}, + ], + edges: ["input -> s", "s:0 -> deep -> after", "s:1 -> skip -> after", "after -> output"], + }, + cases: [ + [{go: true}, {v: 1, isNull: false}], + [{go: false}, {isNull: true}], + ], +} + +{ + name: "an unknown node name is null", + graph: { + nodes: [{expression: "e", fields: {v: "$nodes.nothing", w: "$nodes.nothing.x ?? 'fallback'", isNull: "$nodes.nothing == null"}}], + }, + cases: [ + [{}, {w: "fallback", isNull: true}], + [{nothing: 1}, {w: "fallback", isNull: true}], + ], +} + +{ + name: "node names are case sensitive", + graph: { + nodes: [ + {expression: "Calc", fields: {v: "1"}}, + {expression: "after", fields: {upper: "$nodes.Calc.v", lower: "$nodes.calc.v ?? 'none'"}}, + ], + }, + cases: [ + [{}, {upper: 1, lower: "none"}], + ], +} + +{ + name: "a downstream node that has not run yet is not visible", + graph: { + nodes: [ + {expression: "first", fields: {sawSecond: "$nodes.second == null"}}, + {expression: "second", fields: {s: "1"}}, + ], + }, + cases: [ + [{}, {s: 1}], + [{x: 1}, {s: 1}], + ], +} + +{ + name: "a downstream node's view of an upstream node that has not run", + graph: { + nodes: [ + {expression: "first", fields: {sawSecond: "$nodes.second == null"}}, + {expression: "second", fields: {s: "1"}}, + {expression: "third", fields: {firstSaw: "$nodes.first.sawSecond", second: "$nodes.second.s"}}, + ], + }, + cases: [ + [{}, {firstSaw: true, second: 1}], + ], +} + +{ + name: "a node cannot see itself", + graph: { + nodes: [{expression: "me", fields: {selfIsNull: "$nodes.me == null"}}], + }, + cases: [ + [{}, {selfIsNull: true}], + [{me: 1}, {selfIsNull: true}], + ], +} + +// --- Names with spaces and symbols -------------------------------------------------------------- +// Names that are not identifiers are read with bracket access. +{ + name: "node names with spaces via bracket access", + graph: { + nodes: [ + {expression: "Risk Score", fields: {score: "income / 1000"}}, + {expression: "after", fields: {score: "$nodes['Risk Score'].score", dq: "$nodes[\"Risk Score\"].score"}}, + ], + }, + cases: [ + [{income: 5000}, {score: 5, dq: 5}], + [{income: 0}, {score: 0, dq: 0}], + ], +} + +{ + name: "node names with dashes, dots and unicode", + graph: { + nodes: [ + {expression: "step-1", fields: {a: "1"}}, + {expression: "v1.2", fields: {b: "2"}}, + {expression: "Größe", fields: {c: "3"}}, + {expression: "after", fields: {a: "$nodes['step-1'].a", b: "$nodes['v1.2'].b", c: "$nodes['Größe'].c"}}, + ], + }, + cases: [ + [{}, {a: 1, b: 2, c: 3}], + ], +} + +{ + name: "a dotted node name is not a path", + graph: { + nodes: [ + {expression: "v1.2", fields: {b: "2"}}, + {expression: "after", fields: {dotted: "$nodes.v1 ?? 'none'"}}, + ], + }, + cases: [ + [{}, {dotted: "none"}], + ], +} + +{ + name: "node name with a leading digit via bracket access", + graph: { + nodes: [ + {expression: "1st", fields: {x: "'first'"}}, + {expression: "after", fields: {x: "$nodes['1st'].x"}}, + ], + }, + cases: [ + [{}, {x: "first"}], + ], +} + +{ + name: "node name given by an expression", + graph: { + nodes: [ + {expression: "alpha", fields: {v: "'A'"}}, + {expression: "beta", fields: {v: "'B'"}}, + {expression: "pick", fields: {chosen: "$nodes[$nodes.input.which].v"}}, + ], + edges: ["input -> alpha -> pick", "input -> beta -> pick", "pick -> output"], + }, + cases: [ + [{which: "alpha"}, {chosen: "A"}], + [{which: "beta"}, {chosen: "B"}], + [{which: "gamma"}, {}], + ], +} + +{ + name: "keys of $nodes lists the nodes that ran", + graph: { + nodes: [ + {switch: "s", when: ["a", ""]}, + {expression: "x", fields: {x: "1"}}, + {expression: "y", fields: {y: "1"}}, + {expression: "after", fields: {n: "len(keys($nodes))", x: "'x' in keys($nodes)", y: "'y' in keys($nodes)", s: "'s' in keys($nodes)"}}, + ], + edges: ["input -> s", "s:0 -> x -> after", "s:1 -> y -> after", "after -> output"], + }, + cases: [ + [{a: true}, {n: 3, x: true, y: false, s: true}], + [{a: false}, {n: 3, x: false, y: true, s: true}], + ], +} + +// --- $nodes in tables ------------------------------------------------------------------------ +{ + name: "table input column reading $nodes", + graph: { + nodes: [ + {expression: "calc", fields: {ratio: "debt / income"}}, + {table: "t", inputs: ["$nodes.calc.ratio"], outputs: ["risk"], rules: [["> 0.5", "'high'"], ["", "'low'"]]}, + ], + edges: ["input -> calc", "input -> t -> output", "calc -> t"], + }, + cases: [ + [{debt: 60, income: 100}, {risk: "high"}], + [{debt: 10, income: 100}, {risk: "low"}], + ], +} + +{ + name: "table input cell comparing against $nodes", + graph: { + nodes: [ + {expression: "limits", fields: {max: "100"}}, + {table: "t", inputs: ["amount"], outputs: ["ok"], rules: [["<= $nodes.limits.max", "true"], ["", "false"]]}, + ], + edges: ["input -> limits -> t", "input -> t -> output"], + }, + cases: [ + [{amount: 50}, {ok: true}], + [{amount: 100}, {ok: true}], + [{amount: 101}, {ok: false}], + ], +} + +{ + name: "table output cell reading $nodes", + graph: { + nodes: [ + {expression: "base", fields: {rate: "0.05"}}, + {table: "t", inputs: ["tier"], outputs: ["rate"], rules: [ + ["'gold'", "$nodes.base.rate * 2"], + ["", "$nodes.base.rate"], + ]}, + ], + edges: ["input -> base -> t", "input -> t -> output"], + }, + cases: [ + [{tier: "gold"}, {rate: 0.1}], + [{tier: "silver"}, {rate: 0.05}], + [{}, {rate: 0.05}], + ], +} + +{ + name: "table reading $nodes.input while its input comes from another node", + graph: { + nodes: [ + {expression: "derived", fields: {age: "2025 - birthYear"}}, + {table: "t", inputs: ["age", "$nodes.input.country"], outputs: ["eligible"], rules: [ + [">= 18", "'US'", "true"], + [">= 16", "'DE'", "true"], + ["", "", "false"], + ]}, + ], + }, + cases: [ + [{birthYear: 2000, country: "US"}, {eligible: true}], + [{birthYear: 2008, country: "DE"}, {eligible: true}], + [{birthYear: 2008, country: "US"}, {eligible: false}], + ], +} + +{ + name: "table in a loop reads $nodes for shared settings", + graph: { + nodes: [ + {expression: "cfg", passThrough: true, fields: {threshold: "threshold ?? 10"}}, + {table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["v"], outputs: ["over"], rules: [ + ["> $nodes.cfg.threshold", "true"], + ["", "false"], + ]}, + ], + }, + cases: [ + [{items: [{v: 5}, {v: 15}]}, {out: [{over: false}, {over: true}]}], + [{threshold: 1, items: [{v: 5}]}, {out: [{over: true}]}], + ], +} + +// --- $nodes in switches -------------------------------------------------------------------------- +{ + name: "switch condition reading $nodes", + graph: { + nodes: [ + {expression: "score", fields: {s: "a + b"}}, + {switch: "route", when: ["$nodes.score.s >= 10", ""]}, + {expression: "high", fields: {band: "'high'"}}, + {expression: "low", fields: {band: "'low'"}}, + ], + edges: ["input -> score -> route", "route:0 -> high -> output", "route:1 -> low -> output"], + }, + cases: [ + [{a: 5, b: 5}, {band: "high"}], + [{a: 1, b: 2}, {band: "low"}], + ], +} + +{ + name: "switch condition reading $nodes.input after a transform", + graph: { + nodes: [ + {expression: "strip", fields: {only: "1"}}, + {switch: "route", when: ["$nodes.input.vip == true", "vip == null"]}, + {expression: "vip", fields: {kind: "'vip'"}}, + {expression: "plain", fields: {kind: "'plain'"}}, + ], + edges: ["input -> strip -> route", "route:0 -> vip -> output", "route:1 -> plain -> output"], + }, + cases: [ + [{vip: true}, {kind: "vip"}], + [{vip: false}, {kind: "plain"}], + [{}, {kind: "plain"}], + ], +} + +{ + name: "collect switch over $nodes", + graph: { + nodes: [ + {expression: "flags", fields: {a: "x > 0", b: "x > 10"}}, + {switch: "route", hit: "collect", when: ["$nodes.flags.a", "$nodes.flags.b"]}, + {expression: "pa", fields: {pa: "true"}}, + {expression: "pb", fields: {pb: "true"}}, + ], + edges: ["input -> flags -> route", "route:0 -> pa -> output", "route:1 -> pb -> output"], + }, + cases: [ + [{x: 20}, {pa: true, pb: true}], + [{x: 5}, {pa: true}], + [{x: -1}, {}], + ], +} + +{ + name: "a switch has a $nodes entry holding its input", + graph: { + nodes: [ + {switch: "route", when: ["true"]}, + {expression: "after", fields: {fromSwitch: "$nodes.route.v"}}, + ], + edges: ["input -> route", "route:0 -> after -> output"], + }, + cases: [ + [{v: 1}, {fromSwitch: 1}], + [{v: "s"}, {fromSwitch: "s"}], + ], +} + +// --- $nodes in expression features ------------------------------------------------------------ +{ + name: "$nodes inside closures", + graph: { + nodes: [ + {expression: "cfg", passThrough: true, fields: {min: "min"}}, + {expression: "after", fields: {kept: "filter(items, # >= $nodes.cfg.min)", scaled: "map(items, # * $nodes.input.factor)"}}, + ], + }, + cases: [ + [{min: 2, factor: 10, items: [1, 2, 3]}, {kept: [2, 3], scaled: [10, 20, 30]}], + [{min: 0, factor: 1, items: []}, {kept: [], scaled: []}], + ], +} + +{ + name: "$nodes in an inputField expression", + graph: { + nodes: [ + {expression: "pick", fields: {target: "customer"}}, + {expression: "use", inputField: "$nodes.pick.target", outputPath: "out", fields: {name: "name"}}, + ], + }, + cases: [ + [{customer: {name: "ann"}}, {out: {name: "ann"}}], + [{customer: {}}, {out: {name: null}}], + ], +} + +{ + name: "$ and $nodes together", + graph: { + nodes: [ + {expression: "a", fields: {base: "10"}}, + {expression: "b", fields: {x: "$nodes.a.base + 1", y: "$.x * 2", z: "$.y + $nodes.input.k"}}, + ], + }, + cases: [ + [{k: 1}, {x: 11, y: 22, z: 23}], + [{k: -22}, {x: 11, y: 22, z: 0}], + ], +} + +{ + name: "an expression field named $nodes does not shadow the node map", + graph: { + nodes: [ + {expression: "a", fields: {v: "1"}}, + {expression: "b", fields: {"$nodes": "'shadow'", after: "$nodes.a.v"}}, + ], + }, + cases: [ + [{}, {after: 1}, "question: a field key `$nodes` is stripped from the result by the reserved-property cleaner"], + ], +} + +{ + name: "an input field named $nodes is replaced by the node map", + graph: { + nodes: [ + {expression: "a", fields: {v: "1"}}, + {expression: "b", fields: {after: "$nodes.a.v", raw: "$root['$nodes'] ?? 'none'"}}, + ], + }, + cases: [ + [{"$nodes": {a: {v: 99}}}, {after: 1, raw: {a: {v: 1}, input: {}}}, "question: `$root['$nodes']` reads the injected node map, while an input key `$nodes` is replaced by it"], + [{}, {after: 1, raw: {a: {v: 1}, input: {}}}, "question: `$root['$nodes']` reads the injected node map, while an input key `$nodes` is replaced by it"], + ], +} + +{ + name: "keys($root) inside an expression node lists $nodes and $", + graph: { + nodes: [{expression: "e", fields: {first: "keys($root)", second: "keys($root)"}}], + }, + cases: [ + {input: {q: 1}, output: {first: ["q", "$nodes"], second: ["q", "$nodes", "$"]}, note: "question: the `$nodes` local and the `$` accumulator are visible as keys of `$root` (compare expression spec: locals leak into $root)", engines: "walker and compiled single list $nodes in $root; batch and columnar do not"}, + {input: {}, output: {first: ["$nodes"], second: ["$nodes", "$"]}, note: "question: the `$nodes` local and the `$` accumulator are visible as keys of `$root` (compare expression spec: locals leak into $root)", engines: "walker and compiled single list $nodes in $root; batch and columnar do not"}, + ], +} + +{ + name: "$nodes does not appear in the result", + graph: { + nodes: [{expression: "e", passThrough: true, fields: {n: "len(keys($nodes))"}}], + }, + cases: [ + [{a: 1}, {a: 1, n: 1}], + [{}, {n: 1}], + ], +} + +{ + name: "copying $nodes into the output strips nothing below the top level", + graph: { + nodes: [ + {expression: "a", fields: {v: "1"}}, + {expression: "b", fields: {snapshot: "$nodes"}}, + ], + }, + cases: [ + [{x: 1}, {snapshot: {input: {x: 1}, a: {v: 1}}}], + ], +} + +// --- $nodes in function nodes ---------------------------------------------------------------- +// Functions see `$nodes` as a property of their input. +{ + name: "v2 function reads $nodes", + graph: { + nodes: [ + {expression: "calc", fields: {total: "a + b"}}, + {function: "f", source: """export const handler = async (input) => ({ + doubled: input.$nodes.calc.total * 2, + original: input.$nodes.input.a, + fromInput: input.total, +});"""}, + ], + }, + cases: [ + [{a: 1, b: 2}, {doubled: 6, original: 1, fromInput: 3}], + [{a: 10, b: 0}, {doubled: 20, original: 10, fromInput: 10}], + ], +} + +{ + name: "v2 function reads a node with a spaced name", + graph: { + nodes: [ + {expression: "My Calc", fields: {v: "x * 3"}}, + {function: "f", source: """export const handler = async (input) => ({v: input.$nodes['My Calc'].v});"""}, + ], + }, + cases: [ + [{x: 2}, {v: 6}], + [{x: 0}, {v: 0}], + ], +} + +{ + name: "v2 function sees a node that did not run as undefined", + graph: { + nodes: [ + {switch: "s", when: ["go", ""]}, + {expression: "maybe", fields: {m: "1"}}, + {expression: "other", fields: {o: "1"}}, + {function: "f", source: """export const handler = async (input) => ({ran: input.$nodes.maybe !== undefined, keys: Object.keys(input.$nodes).sort()});"""}, + ], + edges: ["input -> s", "s:0 -> maybe -> f", "s:1 -> other -> f", "f -> output"], + }, + cases: [ + [{go: true}, {ran: true, keys: ["input", "maybe", "s"]}], + [{go: false}, {ran: false, keys: ["input", "other", "s"]}], + ], +} + +{ + name: "v2 function returning its input does not leak $nodes", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {v: "1"}}, + {function: "f", source: """export const handler = async (input) => input;"""}, + ], + }, + cases: [ + [{x: 1}, {x: 1, v: 1}], + [{}, {v: 1}], + ], +} + +{ + name: "node after a v2 function returning its input", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {v: "1"}}, + {function: "f", source: """export const handler = async (input) => input;"""}, + {expression: "after", fields: {hasNodesKey: "'$nodes' in keys($nodes.f)", v: "v"}}, + ], + }, + cases: [ + [{x: 1}, {hasNodesKey: false, v: 1}], + [{}, {hasNodesKey: false, v: 1}], + ], +} + +{ + name: "v1 function reads $nodes", + graph: { + nodes: [ + {expression: "calc", fields: {total: "a * b"}}, + {functionV1: "f", source: """const handler = (input) => { + return {total: input.$nodes.calc.total, a: input.$nodes.input.a}; +}"""}, + ], + }, + cases: [ + [{a: 2, b: 3}, {total: 6, a: 2}], + [{a: 0, b: 3}, {total: 0, a: 0}], + ], +} + +{ + name: "expression reads a function node's output via $nodes", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({list: [input.x, input.x + 1]});"""}, + {expression: "after", fields: {last: "$nodes.f.list[1]", n: "len($nodes.f.list)"}}, + ], + }, + cases: [ + [{x: 1}, {last: 2, n: 2}], + [{x: 10}, {last: 11, n: 2}], + ], +} + +// --- $nodes in custom nodes -------------------------------------------------------------------- +{ + name: "custom node templates read $nodes", + graph: { + nodes: [ + {expression: "calc", fields: {v: "x * 2"}}, + {custom: "c", kind: "render", config: {msg: "value {{ $nodes.calc.v }} from {{ $nodes.input.x }}"}}, + ], + }, + cases: [ + [{x: 2}, {msg: "value 4 from 2"}], + [{x: 5}, {msg: "value 10 from 5"}], + ], +} + +{ + name: "custom echo output carries $nodes downstream", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {v: "1"}}, + {custom: "c", kind: "echo"}, + {expression: "after", fields: {hasNodes: "'$nodes' in keys($nodes.c)", inputSeen: "$nodes.c['$nodes'].input.x"}}, + ], + }, + cases: [ + [{x: 1}, {hasNodes: true, inputSeen: 1}, "question: a custom node's input includes `$nodes`; an echo forwards it as a regular key the next node can see"], + ], +} + +// --- $nodes inside sub-decisions ------------------------------------------------------------- +// A child graph has its own $nodes. The parent's nodes are reached through the child's input +// node entry: `$nodes..$nodes.`. +{ + name: "child $nodes holds the child's own nodes", + decisions: { + child: {nodes: [ + {expression: "inner", fields: {v: "x + 1"}}, + {expression: "after", fields: {fromInner: "$nodes.inner.v", childInput: "$nodes.input.x"}}, + ]}, + }, + graph: { + nodes: [ + {expression: "pre", passThrough: true, fields: {x: "x * 10"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{x: 1}, {fromInner: 11, childInput: 10}], + [{x: 0}, {fromInner: 1, childInput: 0}], + ], +} + +{ + name: "child reads parent nodes through its input node", + decisions: { + child: {nodes: [ + {input: "request"}, + {expression: "e", fields: {parentPre: "$nodes.request.$nodes.pre.y", parentInput: "$nodes.request.$nodes.input.x"}}, + ]}, + }, + graph: { + nodes: [ + {expression: "pre", fields: {y: "x + 100"}}, + {decision: "call", key: "child"}, + ], + edges: ["input -> pre", "input -> call -> output", "pre -> call"], + }, + cases: [ + [{x: 1}, {parentPre: 101, parentInput: 1}], + [{x: -1}, {parentPre: 99, parentInput: -1}], + ], +} + +{ + name: "child input node view without the parent map", + decisions: { + child: {nodes: [ + {input: "request"}, + {expression: "e", fields: {req: "$nodes.request"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{hello: "world"}, {req: {hello: "world"}}], + ], +} + +{ + name: "child does not see parent nodes directly", + decisions: { + child: {nodes: [{expression: "e", fields: {direct: "$nodes.pre ?? 'none'"}}]}, + }, + graph: { + nodes: [ + {expression: "pre", passThrough: true, fields: {p: "1"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{}, {direct: "none"}], + ], +} + +{ + name: "grandchild reaches the root through two input views", + decisions: { + mid: {nodes: [ + {input: "midIn"}, + {expression: "m", passThrough: true, fields: {mid: "1"}}, + {decision: "call", key: "leaf"}, + ]}, + leaf: {nodes: [ + {input: "leafIn"}, + {expression: "l", fields: { + fromMid: "$nodes.leafIn.$nodes.m.mid", + fromRoot: "$nodes.leafIn.$nodes.midIn.$nodes.root.r", + }}, + ]}, + }, + graph: { + nodes: [ + {expression: "root", passThrough: true, fields: {r: "'root'"}}, + {decision: "call", key: "mid"}, + ], + }, + cases: [ + [{}, {fromMid: 1, fromRoot: "root"}], + ], +} + +{ + name: "function in a child reads parent nodes", + decisions: { + child: {nodes: [ + {input: "request"}, + {function: "f", source: """export const handler = async (input) => ({parent: input.$nodes.request.$nodes.pre.v});"""}, + ]}, + }, + graph: { + nodes: [ + {expression: "pre", passThrough: true, fields: {v: "x * 2"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{x: 4}, {parent: 8}], + [{x: 0}, {parent: 0}], + ], +} + +{ + name: "loop child items see the parent nodes", + decisions: { + child: {nodes: [ + {input: "item"}, + {expression: "e", fields: {v: "n * $nodes.item.$nodes.cfg.factor"}}, + ]}, + }, + graph: { + nodes: [ + {expression: "cfg", passThrough: true, fields: {factor: "factor ?? 2"}}, + {decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{n: 1}, {n: 2}]}, {out: [{v: 2}, {v: 4}]}], + [{factor: 10, items: [{n: 3}]}, {out: [{v: 30}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "parent $nodes of a decision node is the child result", + decisions: { + child: {nodes: [{expression: "e", fields: {r: "x * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {expression: "after", fields: {r: "$nodes.call.r", x: "$nodes.input.x"}}, + ], + }, + cases: [ + [{x: 3}, {r: 6, x: 3}], + [{x: 0}, {r: 0, x: 0}], + ], +} + +// --- $nodes in realistic combinations ------------------------------------------------------- +{ + name: "pricing pipeline reading several earlier nodes", + graph: { + nodes: [ + {table: "tier", inputs: ["spend"], outputs: ["tier"], rules: [[">= 1000", "'gold'"], [">= 100", "'silver'"], ["", "'basic'"]]}, + {table: "discount", inputs: ["tier"], outputs: ["pct"], rules: [["'gold'", "20"], ["'silver'", "10"], ["", "0"]]}, + {expression: "final", fields: { + tier: "$nodes.tier.tier", + pct: "$nodes.discount.pct", + price: "$nodes.input.price * (100 - $nodes.discount.pct) / 100", + }}, + ], + }, + cases: [ + [{spend: 5000, price: 200}, {tier: "gold", pct: 20, price: 160}], + [{spend: 500, price: 200}, {tier: "silver", pct: 10, price: 180}], + [{spend: 5, price: 200}, {tier: "basic", pct: 0, price: 200}], + ], +} + +{ + name: "fan-in node choosing between branch results by $nodes", + graph: { + nodes: [ + {switch: "s", when: ["kind == 'a'", ""]}, + {expression: "fa", fields: {val: "'from a'"}}, + {expression: "fb", fields: {val: "'from b'"}}, + {expression: "pick", fields: {chosen: "$nodes.fa.val ?? $nodes.fb.val"}}, + ], + edges: ["input -> s", "s:0 -> fa -> pick", "s:1 -> fb -> pick", "pick -> output"], + }, + cases: [ + [{kind: "a"}, {chosen: "from a"}], + [{kind: "b"}, {chosen: "from b"}], + [{}, {chosen: "from b"}], + ], +} diff --git a/core/engine/tests/spec/graph/16-functions-v2.json5 b/core/engine/tests/spec/graph/16-functions-v2.json5 new file mode 100644 index 00000000..6eb7f2e8 --- /dev/null +++ b/core/engine/tests/spec/graph/16-functions-v2.json5 @@ -0,0 +1,1284 @@ +// Function nodes, version 2: `export const handler = async (input) => ...` modules run in +// QuickJS. The node's output is whatever the handler resolves to, converted back to a +// Variable. Helpers come from module imports (`dayjs`, `big.js`, `zod`, `zen`); the +// previously executed nodes are reachable through `input.$nodes`. + +// --- Return shapes: objects -------------------------------------------------------------- + +{ + name: "v2 returns an object literal computed from the input", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ total: input.a + input.b, label: 'sum' });"""}], + }, + cases: [ + [{a: 1, b: 2}, {total: 3, label: "sum"}], + [{a: -5, b: 5}, {total: 0, label: "sum"}], + [{a: "x", b: "y"}, {total: "xy", label: "sum"}], + [{a: 1, b: "2"}, {total: "12", label: "sum"}], + [{a: true, b: true}, {total: 2, label: "sum"}], + ], +} + +{ + name: "v2 returning the input unchanged passes it through", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => input;"""}], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{nested: {deep: [1, {x: "y"}]}}, {nested: {deep: [1, {x: "y"}]}}], + [{s: "text", b: false, n: null}, {s: "text", b: false}], + ], +} + +{ + name: "v2 spreading the input does not leak the $nodes proxy", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ ...input, seen: true });"""}], + }, + cases: [ + [{a: 1}, {a: 1, seen: true}], + [{}, {seen: true}], + [{seen: false}, {seen: true}], + ], +} + +{ + name: "v2 a returned $nodes key is stripped", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ $nodes: { fake: 1 }, kept: input.k ?? 'none' });"""}], + }, + cases: [ + [{k: 1}, {kept: 1}], + [{}, {kept: "none"}], + ], +} + +{ + name: "v2 deeply nested objects and arrays survive the round trip", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + a: { b: { c: { d: [input.v, [input.v, { e: input.v }]] } } }, + empty: {}, + list: [], +});"""}], + }, + cases: [ + [{v: 1}, {a: {b: {c: {d: [1, [1, {e: 1}]]}}}, empty: {}, list: []}], + [{v: "s"}, {a: {b: {c: {d: ["s", ["s", {e: "s"}]]}}}, empty: {}, list: []}], + [{v: null}, {a: {b: {c: {d: [null, [null, {e: null}]]}}}, empty: {}, list: []}], + ], +} + +{ + name: "v2 a synchronous handler is accepted", + graph: { + nodes: [{function: "f", source: """export const handler = (input) => ({ doubled: input.x * 2 });"""}], + }, + cases: [ + [{x: 2}, {doubled: 4}], + [{x: 0}, {doubled: 0}], + [{x: -1.5}, {doubled: -3}], + ], +} + +{ + name: "v2 a handler declared as a function declaration", + graph: { + nodes: [{function: "f", source: """export async function handler(input) { + const out = {}; + for (const [k, v] of Object.entries(input)) { + if (k === '$nodes') continue; + out[k.toUpperCase()] = v; + } + return out; +}"""}], + }, + cases: [ + [{a: 1, b: 2}, {A: 1, B: 2}], + [{}, {}], + [{mixed: "x"}, {MIXED: "x"}], + ], +} + +{ + name: "v2 Object.keys of the input lists $nodes as an own key", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ keys: Object.keys(input).sort() });"""}], + }, + cases: [ + [{a: 1}, {keys: ["$nodes", "a"]}], + [{}, {keys: ["$nodes"]}], + [{b: 1, a: 2}, {keys: ["$nodes", "a", "b"]}], + ], +} + +// --- Return shapes: non-objects ------------------------------------------------------------ +// The node output is the raw value, but the output node merges its incoming data and only +// objects and arrays become the head of that merge, so primitive results reach the response +// as an empty object. + +{ + name: "v2 primitive results are not objects", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => input.value;"""}], + }, + cases: [ + [{value: 5}, {}], + [{value: "text"}, {}], + [{value: true}, {}], + [{value: null}, {}], + [{}, {}], + [{value: {x: 1}}, {x: 1}], + ], +} + +{ + name: "v2 an array result reaches the response", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => input.items.map((i) => i * 10);"""}], + }, + cases: [ + [{items: [1, 2, 3]}, [10, 20, 30], "question: an array result is merged into the response object; the response is not an object"], + [{items: []}, [], "question: an array result is merged into the response object; the response is not an object"], + ], +} + +{ + name: "v2 a handler without a return value", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { const x = input.a; };"""}], + }, + cases: [ + [{a: 1}, {}], + [{}, {}], + ], +} + +{ + name: "v2 a primitive result read by a following expression node", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => input.n * 2;"""}, + {expression: "e", fields: {n: "n ?? 'missing'", isNull: "n == null"}}, + ], + }, + cases: [ + [{n: 2}, {n: "missing", isNull: true}], + [{n: 0}, {n: "missing", isNull: true}], + [{n: -1}, {n: "missing", isNull: true}], + ], +} + +// --- Special JS values --------------------------------------------------------------------- +// Top-level null properties are dropped when node outputs are merged into the response, so +// nulls are observed nested one level down. + +{ + name: "v2 undefined properties become null", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ o: { missing: input.nope, explicit: undefined, kept: 1 } });"""}], + }, + cases: [ + [{}, {o: {missing: null, explicit: null, kept: 1}}, "question: v2 keeps undefined properties as null while v1 (JSON) drops them"], + [{nope: 3}, {o: {missing: 3, explicit: null, kept: 1}}, "question: v2 keeps undefined properties as null while v1 (JSON) drops them"], + ], +} + +{ + name: "v2 array holes and undefined elements become null", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { const a = [1, undefined, 3]; a[5] = 6; return { a }; };"""}], + }, + cases: [ + [{}, {a: [1, null, 3, null, null, 6]}], + ], +} + +{ + name: "v2 functions and symbols are rendered as placeholders", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ fn: () => 1, sym: Symbol('s'), n: input.n });"""}], + }, + cases: [ + [{n: 1}, {fn: "[Function]", sym: "[Symbol]", n: 1}, "question: non-data JS values become placeholder strings instead of being dropped or rejected"], + ], +} + +{ + name: "v2 NaN and Infinity cannot be represented", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ value: input.a / input.b });"""}], + }, + cases: [ + [{a: 1, b: 2}, {value: 0.5}], + [{a: 1, b: 0}, "!error", "question: Infinity is a conversion error rather than null"], + [{a: 0, b: 0}, "!error", "question: NaN is a conversion error rather than null"], + [{a: -1, b: 0}, "!error", "question: -Infinity is a conversion error rather than null"], + ], +} + +{ + name: "v2 BigInt results become numbers", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ big: BigInt(input.n) * 3n });"""}], + }, + cases: [ + [{n: 2}, {big: 6}], + [{n: 0}, {big: 0}], + [{n: 1000000000000}, {big: 3000000000000}], + ], +} + +{ + name: "v2 class instances keep their own enumerable fields", + graph: { + nodes: [{function: "f", source: """class Point { + constructor(x, y) { this.x = x; this.y = y; } + get len() { return Math.abs(this.x) + Math.abs(this.y); } +} +export const handler = async (input) => ({ p: new Point(input.x, input.y) });"""}], + }, + cases: [ + [{x: 1, y: 2}, {p: {x: 1, y: 2}}], + [{x: -1, y: 0}, {p: {x: -1, y: 0}}], + ], +} + +{ + name: "v2 Map and Set have no own properties", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + map: new Map([['a', 1]]), + set: new Set([1, 2]), + fromMap: Object.fromEntries(new Map([['a', input.v]])), + fromSet: [...new Set([input.v, input.v])], +});"""}], + }, + cases: [ + [{v: 1}, {map: {}, set: {}, fromMap: {a: 1}, fromSet: [1]}], + [{v: "x"}, {map: {}, set: {}, fromMap: {a: "x"}, fromSet: ["x"]}], + ], +} + +// --- Numbers crossing the JS boundary ------------------------------------------------------- +// Numbers enter JS as doubles, so exact decimals beyond double precision are rounded. On the +// way back the double is converted to a decimal with about 15 significant digits, which +// hides binary artifacts such as 0.1 + 0.2. + +{ + name: "v2 decimals become doubles in JS", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: input.v, t: typeof input.v });"""}], + }, + cases: [ + [{v: 0.1}, {v: 0.1, t: "number"}], + [{v: 1}, {v: 1, t: "number"}], + [{v: -0.5}, {v: -0.5, t: "number"}], + [{v: 0.1000000000000000000000000001}, {v: 0.1, t: "number"}], + [{v: 9007199254740993}, {v: 9007199254740992, t: "number"}], + [{v: 123456789.123456789}, {v: 123456789.1234568, t: "number"}], + ], +} + +{ + name: "v2 float results are rounded on the way back", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ sum: input.a + input.b });"""}], + }, + cases: [ + [{a: 0.1, b: 0.2}, {sum: 0.3}], + [{a: 1, b: 2}, {sum: 3}], + [{a: 1.5, b: 1.5}, {sum: 3}], + [{a: 0.7, b: 0.1}, {sum: 0.8}], + ], +} + +{ + name: "v2 integer and float results", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + int: 42, + neg: -7, + frac: 2.5, + tiny: 1e-7, + huge: 1e21, + maxSafe: Number.MAX_SAFE_INTEGER, + negZero: -0, +});"""}], + }, + cases: [ + [{}, {int: 42, neg: -7, frac: 2.5, tiny: 0.0000001, huge: 1000000000000000000000, maxSafe: 9007199254740991, negZero: 0}], + ], +} + +{ + name: "v2 big.js gives exact decimal arithmetic", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => { + const sum = new Big(input.a).plus(input.b); + return { str: sum.toString(), num: sum.toNumber(), fixed: sum.toFixed(2), gt: sum.gt(1) }; +};"""}], + }, + cases: [ + [{a: 0.1, b: 0.2}, {str: "0.3", num: 0.3, fixed: "0.30", gt: false}], + [{a: 1, b: 2}, {str: "3", num: 3, fixed: "3.00", gt: true}], + [{a: "1.005", b: 0}, {str: "1.005", num: 1.005, fixed: "1.01", gt: true}], + [{a: -2, b: 1}, {str: "-1", num: -1, fixed: "-1.00", gt: false}], + ], +} + +{ + name: "v2 numeric strings stay strings", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ t: typeof input.v, n: Number(input.v), v: input.v });"""}], + }, + cases: [ + [{v: "12.50"}, {t: "string", n: 12.5, v: "12.50"}], + [{v: "0"}, {t: "string", n: 0, v: "0"}], + [{v: " 7 "}, {t: "string", n: 7, v: " 7 "}], + ], +} + +{ + name: "v2 Math helpers", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + round: Math.round(input.v), + floor: Math.floor(input.v), + ceil: Math.ceil(input.v), + max: Math.max(...input.list), + fixed: Number(input.v.toFixed(1)), +});"""}], + }, + cases: [ + [{v: 2.45, list: [1, 9, 3]}, {round: 2, floor: 2, ceil: 3, max: 9, fixed: 2.5}], + [{v: -2.5, list: [-1]}, {round: -2, floor: -3, ceil: -2, max: -1, fixed: -2.5}], + [{v: 0, list: [0, 0]}, {round: 0, floor: 0, ceil: 0, max: 0, fixed: 0}], + ], +} + +// --- Dates ----------------------------------------------------------------------------------- + +{ + name: "v2 dayjs parses, shifts and formats dates", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => { + const d = dayjs(input.date); + return { + next: d.add(1, 'day').format('YYYY-MM-DD'), + month: d.month() + 1, + weekday: d.day(), + valid: d.isValid(), + }; +};"""}], + }, + cases: [ + [{date: "2024-01-15"}, {next: "2024-01-16", month: 1, weekday: 1, valid: true}], + [{date: "2024-02-28"}, {next: "2024-02-29", month: 2, weekday: 3, valid: true}], + [{date: "2023-12-31"}, {next: "2024-01-01", month: 12, weekday: 0, valid: true}], + ], +} + +{ + name: "v2 dayjs differences between two dates", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => ({ + days: dayjs(input.to).diff(dayjs(input.from), 'day'), + before: dayjs(input.from).isBefore(dayjs(input.to)), +});"""}], + }, + cases: [ + [{from: "2024-01-01", to: "2024-03-01"}, {days: 60, before: true}], + [{from: "2024-03-01", to: "2024-01-01"}, {days: -60, before: false}], + [{from: "2024-01-01", to: "2024-01-01"}, {days: 0, before: false}], + ], +} + +{ + name: "v2 an invalid dayjs date", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => ({ valid: dayjs(input.date).isValid() });"""}], + }, + cases: [ + [{date: "not a date"}, {valid: false}], + [{date: "2024-06-01"}, {valid: true}], + [{}, {valid: true}], + [{date: null}, {valid: false}], + ], +} + +{ + name: "v2 native Date in UTC", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const d = new Date(input.ts); + return { iso: d.toISOString(), year: d.getUTCFullYear(), ms: d.getTime() }; +};"""}], + }, + cases: [ + [{ts: "2024-01-01T00:00:00Z"}, {iso: "2024-01-01T00:00:00.000Z", year: 2024, ms: 1704067200000}], + [{ts: "2000-02-29T12:30:00Z"}, {iso: "2000-02-29T12:30:00.000Z", year: 2000, ms: 951827400000}], + [{ts: 0}, {iso: "1970-01-01T00:00:00.000Z", year: 1970, ms: 0}], + ], +} + +{ + name: "v2 a returned Date object has no own properties", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ d: new Date(input.ts), s: new Date(input.ts).toISOString() });"""}], + }, + cases: [ + [{ts: "2024-01-01T00:00:00Z"}, {d: {}, s: "2024-01-01T00:00:00.000Z"}, "question: a Date becomes an empty object; JSON semantics would give its ISO string"], + ], +} + +{ + name: "v2 schema date inputs arrive as strings", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ t: typeof input.d, d: input.d });"""}], + }, + cases: [ + [{d: date('2024-05-01')}, {t: "string", d: "2024-05-01"}], + [{d: "2024-05-01"}, {t: "string", d: "2024-05-01"}], + ], +} + +// --- Null and missing inputs ----------------------------------------------------------------- + +{ + name: "v2 null and missing fields with nullish defaults", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + value: input.v ?? 'default', + isNull: input.v === null, + isUndefined: input.v === undefined, + has: 'v' in input, +});"""}], + }, + cases: [ + [{v: 1}, {value: 1, isNull: false, isUndefined: false, has: true}], + [{v: null}, {value: "default", isNull: true, isUndefined: false, has: true}], + [{}, {value: "default", isNull: false, isUndefined: true, has: false}], + [{v: 0}, {value: 0, isNull: false, isUndefined: false, has: true}], + [{v: ""}, {value: "", isNull: false, isUndefined: false, has: true}], + [{v: false}, {value: false, isNull: false, isUndefined: false, has: true}], + ], +} + +{ + name: "v2 optional chaining over nested and missing paths", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ r: { city: input.customer?.address?.city ?? null, first: input.items?.[0] ?? null } });"""}], + }, + cases: [ + [{customer: {address: {city: "Berlin"}}, items: [5]}, {r: {city: "Berlin", first: 5}}], + [{customer: {}}, {r: {city: null, first: null}}], + [{customer: null, items: []}, {r: {city: null, first: null}}], + [{}, {r: {city: null, first: null}}], + ], +} + +// --- Errors ---------------------------------------------------------------------------------- + +{ + name: "v2 a thrown Error fails the evaluation", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + if (input.fail) throw new Error('boom ' + input.fail); + return { ok: true }; +};"""}], + }, + cases: [ + [{fail: "now"}, "!error: boom now"], + [{}, {ok: true}], + [{fail: 0}, {ok: true}], + [{fail: 1}, "!error: boom 1"], + ], +} + +{ + name: "v2 throwing non-Error values", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + if (input.kind === 'string') throw 'plain message'; + if (input.kind === 'object') throw { code: 42 }; + if (input.kind === 'null') throw null; + return { ok: input.kind ?? null }; +};"""}], + }, + cases: [ + [{kind: "string"}, "!error: plain message"], + [{kind: "object"}, "!error"], + [{kind: "null"}, "!error"], + [{kind: "none"}, {ok: "none"}], + ], +} + +{ + name: "v2 runtime type errors", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: input.a.b.c });"""}], + }, + cases: [ + [{a: {b: {c: 1}}}, {v: 1}], + [{a: {b: null}}, "!error"], + [{a: {}}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "v2 a reference to an undefined identifier", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: input.ok ? 1 : notDefinedAnywhere });"""}], + }, + cases: [ + [{ok: true}, {v: 1}], + [{ok: false}, "!error: notDefinedAnywhere"], + ], +} + +{ + name: "v2 a rejected promise fails the evaluation", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + if (input.reject) return Promise.reject(new Error('rejected')); + return Promise.resolve({ ok: true }); +};"""}], + }, + cases: [ + [{reject: true}, "!error: rejected"], + [{reject: false}, {ok: true}], + ], +} + +{ + name: "v2 a syntax error fails every evaluation", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ a: 1 ;"""}], + }, + cases: [ + [{}, "!error"], + [{a: 1}, "!error"], + ], +} + +{ + name: "v2 a module without a handler export", + graph: { + nodes: [{function: "f", source: """export const notHandler = async (input) => input;"""}], + }, + cases: [ + [{}, "!error"], + [{a: 1}, "!error"], + ], +} + +{ + name: "v2 a handler export that is not a function", + graph: { + nodes: [{function: "f", source: """export const handler = 5;"""}], + }, + cases: [ + [{}, "!error"], + ], +} + +{ + name: "v2 a v1-style source in a v2 node", + graph: { + nodes: [{function: "f", source: """const handler = (input) => ({ a: 1 });"""}], + }, + cases: [ + [{}, "!error"], + ], +} + +{ + name: "v2 an error in one node stops the graph", + graph: { + nodes: [ + {expression: "before", fields: {x: "a * 2"}}, + {function: "f", source: """export const handler = async (input) => { if (input.x > 10) throw new Error('too big'); return { y: input.x + 1 }; };"""}, + {expression: "after", fields: {z: "y * 10"}}, + ], + }, + cases: [ + [{a: 1}, {z: 30}], + [{a: 6}, "!error: too big"], + [{a: 5}, {z: 110}], + ], +} + +{ + name: "v2 an error caught inside the handler is not an error", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + try { + return { parsed: JSON.parse(input.text) }; + } catch (e) { + return { error: e.name }; + } +};"""}], + }, + cases: [ + [{text: "{\"a\": 1}"}, {parsed: {a: 1}}], + [{text: "[1, 2]"}, {parsed: [1, 2]}], + [{text: "nope"}, {error: "SyntaxError"}], + [{text: "3"}, {parsed: 3}], + ], +} + +// --- Mutation of the input --------------------------------------------------------------------- +// The handler receives a converted copy: mutating it changes only what the handler returns. + +{ + name: "v2 mutating and returning the input", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + input.count = (input.count ?? 0) + 1; + delete input.secret; + input.list?.push('added'); + return input; +};"""}], + }, + cases: [ + [{count: 1, secret: "s", list: []}, {count: 2, list: ["added"]}], + [{}, {count: 1}], + [{secret: null, list: ["a"]}, {count: 1, list: ["a", "added"]}], + ], +} + +{ + name: "v2 mutation inside a function does not leak into other nodes", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => { input.a = 'changed'; input.nested.b = 'changed'; return { done: true }; };"""}, + {expression: "e", fields: {a: "$nodes.input.a", b: "$nodes.input.nested.b"}}, + ], + edges: ["input -> f -> output", "input -> e -> output"], + }, + cases: [ + [{a: "orig", nested: {b: "orig"}}, {done: true, a: "orig", b: "orig"}], + [{a: 1, nested: {b: 2}}, {done: true, a: 1, b: 2}], + ], +} + +{ + name: "v2 mutation of $nodes data does not leak into later nodes", + graph: { + nodes: [ + {expression: "first", fields: {v: "a"}}, + {function: "f", source: """export const handler = async (input) => { input.$nodes.first.v = 'mutated'; input.$nodes.input.a = 'mutated'; return { done: true }; };"""}, + {expression: "last", fields: {v: "$nodes.first.v", a: "$nodes.input.a", done: "done"}}, + ], + }, + cases: [ + [{a: 1}, {v: 1, a: 1, done: true}], + [{a: "x"}, {v: "x", a: "x", done: true}], + ], +} + +{ + name: "v2 shared references in the input are converted once", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + input.left.tag = 'L'; + return { left: input.left, right: input.right }; +};"""}], + }, + cases: [ + [{left: {v: 1}, right: {v: 1}}, {left: {v: 1, tag: "L"}, right: {v: 1}}], + ], +} + +// --- Async ------------------------------------------------------------------------------------- + +{ + name: "v2 awaiting promises and helpers", + graph: { + nodes: [{function: "f", source: """const double = async (x) => x * 2; +const later = (x) => new Promise((resolve) => resolve(x + 1)); +export const handler = async (input) => { + const a = await double(input.n); + const b = await later(a); + const all = await Promise.all(input.list.map(double)); + return { a, b, all }; +};"""}], + }, + cases: [ + [{n: 2, list: [1, 2]}, {a: 4, b: 5, all: [2, 4]}], + [{n: 0, list: []}, {a: 0, b: 1, all: []}], + ], +} + +{ + name: "v2 Promise.allSettled and race", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const settled = await Promise.allSettled([Promise.resolve(input.v), Promise.reject(new Error('no'))]); + const first = await Promise.race([Promise.resolve('a'), new Promise(() => {})]); + return { statuses: settled.map((s) => s.status), value: settled[0].value, first }; +};"""}], + }, + cases: [ + [{v: 1}, {statuses: ["fulfilled", "rejected"], value: 1, first: "a"}], + [{v: "x"}, {statuses: ["fulfilled", "rejected"], value: "x", first: "a"}], + ], +} + +{ + name: "v2 a handler returning a nested promise", + graph: { + nodes: [{function: "f", source: """export const handler = (input) => Promise.resolve(Promise.resolve({ v: input.v }));"""}], + }, + cases: [ + [{v: 1}, {v: 1}], + [{v: "s"}, {v: "s"}], + ], +} + +{ + name: "v2 a promise as a property value is awaited", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: Promise.resolve(input.v) });"""}], + }, + cases: [ + [{v: 1}, {v: 1}, "question: promises nested inside the result are resolved during conversion"], + ], +} + +// --- Console ----------------------------------------------------------------------------------- + +{ + name: "v2 console.log has no effect on the output", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + console.log('input', input, 1, null); + console.log(); + const circular = {}; + circular.self = circular; + console.log(circular); + return { logged: true, v: input.v }; +};"""}], + }, + cases: [ + [{v: 1}, {logged: true, v: 1}], + [{}, {logged: true}], + ], +} + +// --- Large data ---------------------------------------------------------------------------------- + +{ + name: "v2 building and reducing large arrays", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const xs = Array.from({ length: input.n }, (_, i) => i); + const objects = xs.map((i) => ({ id: i, even: i % 2 === 0 })); + return { + count: objects.length, + sum: xs.reduce((a, b) => a + b, 0), + evens: objects.filter((o) => o.even).length, + last: objects[objects.length - 1] ?? null, + }; +};"""}], + }, + cases: [ + [{n: 10000}, {count: 10000, sum: 49995000, evens: 5000, last: {id: 9999, even: false}}], + [{n: 1}, {count: 1, sum: 0, evens: 1, last: {id: 0, even: true}}], + [{n: 0}, {count: 0, sum: 0, evens: 0}], + ], +} + +{ + name: "v2 returning a large generated object", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => { + const rows = []; + for (let i = 0; i < input.n; i++) rows.push({ id: i, name: 'row' + i, tags: ['a', 'b'] }); + return { rows }; +};"""}, + {expression: "e", fields: {count: "len(rows)", lastName: "rows[len(rows) - 1].name", tags: "sum(map(rows, len(#.tags)))"}}, + ], + }, + cases: [ + [{n: 2000}, {count: 2000, lastName: "row1999", tags: 4000}], + [{n: 3}, {count: 3, lastName: "row2", tags: 6}], + ], +} + +{ + name: "v2 a large input array", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + total: input.items.reduce((acc, item) => acc + item.price * item.qty, 0), + skus: input.items.map((i) => i.sku).join(','), +});"""}], + }, + cases: [ + [{items: [{sku: "a", price: 2, qty: 3}, {sku: "b", price: 5, qty: 1}, {sku: "c", price: 0.5, qty: 4}, {sku: "d", price: 10, qty: 0}, {sku: "e", price: 1, qty: 1}]}, {total: 14, skus: "a,b,c,d,e"}], + [{items: []}, {total: 0, skus: ""}], + ], +} + +// --- Strings ----------------------------------------------------------------------------------- + +{ + name: "v2 unicode strings and string helpers", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + upper: input.s.toUpperCase(), + length: input.s.length, + codePoints: [...input.s].length, + padded: input.s.padStart(6, '*'), +});"""}], + }, + cases: [ + [{s: "abc"}, {upper: "ABC", length: 3, codePoints: 3, padded: "***abc"}], + [{s: "über"}, {upper: "ÜBER", length: 4, codePoints: 4, padded: "**über"}], + [{s: "😀"}, {upper: "😀", length: 2, codePoints: 1, padded: "****😀"}], + [{s: ""}, {upper: "", length: 0, codePoints: 0, padded: "******"}], + ], +} + +{ + name: "v2 template literals and regular expressions", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + greeting: `Hello, ${input.name}!`, + isEmail: /^[^@\s]+@[^@\s]+\.[a-z]+$/.test(input.email ?? ''), + digits: (input.email ?? '').replace(/\D/g, ''), +});"""}], + }, + cases: [ + [{name: "Ann", email: "ann42@example.com"}, {greeting: "Hello, Ann!", isEmail: true, digits: "42"}], + [{name: "Bo", email: "not-an-email"}, {greeting: "Hello, Bo!", isEmail: false, digits: ""}], + [{}, {greeting: "Hello, undefined!", isEmail: false, digits: ""}], + ], +} + +// --- TypeScript sources ------------------------------------------------------------------------ + +{ + name: "v2 TypeScript type annotations are stripped", + graph: { + nodes: [{function: "f", source: """type Input = { a: number; b?: number }; +interface Output { total: number } +export const handler = async (input: Input): Promise => { + const b: number = input.b ?? 0; + return { total: input.a + b } as Output; +};"""}], + }, + cases: [ + [{a: 1, b: 2}, {total: 3}], + [{a: 5}, {total: 5}], + ], +} + +// --- Modules ----------------------------------------------------------------------------------- + +{ + name: "v2 zen.evaluateExpression and evaluateUnaryExpression", + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => ({ + sum: zen.evaluateExpression('a + b', { a: input.a, b: input.b }), + matches: zen.evaluateUnaryExpression('> 10', { $: input.a }), +});"""}], + }, + cases: [ + [{a: 20, b: 1}, {sum: 21, matches: true}], + [{a: 1, b: 2}, {sum: 3, matches: false}], + [{a: 0.1, b: 0.2}, {sum: 0.3, matches: false}], + ], +} + +{ + name: "v2 zen.evaluateExpression errors are throwable", + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => { + try { + return { v: zen.evaluateExpression(input.expr, {}) }; + } catch (e) { + return { failed: true }; + } +};"""}], + }, + cases: [ + [{expr: "1 + 1"}, {v: 2}], + [{expr: "1 +"}, {failed: true}], + [{expr: "'a' + 1"}, {failed: true}], + ], +} + +{ + name: "v2 zen.evaluate runs a sub-decision", + decisions: { + child: {nodes: [{expression: "e", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => { + const response = await zen.evaluate('child', { x: input.x }); + return { y: response.result.y }; +};"""}], + }, + cases: [ + [{x: 2}, {y: 4}], + [{x: 0.5}, {y: 1}], + ], +} + +{ + name: "v2 zen.evaluate of an unknown key throws", + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => { + try { + await zen.evaluate('missing-key', input); + return { loaded: true }; + } catch (e) { + return { loaded: false }; + } +};"""}], + }, + cases: [ + [{}, {loaded: false}], + ], +} + +{ + name: "v2 named imports from big.js and dayjs", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +import dayjs from 'dayjs'; +export const handler = async (input) => ({ + times: Big(input.a).times(input.b).toNumber(), + year: dayjs('2024-07-04').year(), +});"""}], + }, + cases: [ + [{a: 1.1, b: 3}, {times: 3.3, year: 2024}], + [{a: 0, b: 3}, {times: 0, year: 2024}], + ], +} + +{ + name: "v2 a named import of Big from big.js", + graph: { + nodes: [{function: "f", source: """import { Big } from 'big.js'; +export const handler = async (input) => ({ v: Big(input.a).toNumber() });"""}], + }, + cases: [ + [{a: 1}, "!error: Could not find export 'Big'", "question: the published big.js module also has a named Big export; the embedded bundle only exports the default"], + [{a: 2.5}, "!error: Could not find export 'Big'", "question: the published big.js module also has a named Big export; the embedded bundle only exports the default"], + ], +} + +{ + name: "v2 importing an unknown module", + graph: { + nodes: [{function: "f", source: """import fs from 'fs'; +export const handler = async (input) => ({ ok: true });"""}], + }, + cases: [ + [{}, "!error"], + ], +} + +{ + name: "v2 the config global", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ iteration: config.iteration, depthPositive: config.maxDepth > 0, trace: config.trace });"""}], + }, + cases: [ + [{}, {iteration: 0, depthPositive: true, trace: false}], + ], +} + +{ + name: "v2 config.iteration inside a sub-decision", + decisions: { + child: {nodes: [{function: "inner", source: """export const handler = async (input) => ({ iteration: config.iteration });"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, {iteration: 1}], + [{a: 1}, {iteration: 1}], + ], +} + +// --- $nodes: reading earlier node outputs ---------------------------------------------------- + +{ + name: "v2 reads the input node and an earlier expression node", + graph: { + nodes: [ + {expression: "calc", fields: {doubled: "a * 2"}}, + {function: "f", source: """export const handler = async (input) => ({ + fromInput: input.$nodes.input.a, + fromCalc: input.$nodes.calc.doubled, + direct: input.doubled, +});"""}, + ], + }, + cases: [ + [{a: 2}, {fromInput: 2, fromCalc: 4, direct: 4}], + [{a: 0}, {fromInput: 0, fromCalc: 0, direct: 0}], + [{a: -1.5}, {fromInput: -1.5, fromCalc: -3, direct: -3}], + ], +} + +{ + name: "v2 $nodes lists only nodes that have run", + graph: { + nodes: [ + {expression: "first", fields: {v: "1"}}, + {function: "f", source: """export const handler = async (input) => ({ + names: Object.keys(input.$nodes).sort(), + hasLast: 'last' in input.$nodes, + lastType: typeof input.$nodes.last, +});"""}, + {expression: "last", fields: {names: "names", hasLast: "hasLast", lastType: "lastType"}}, + ], + }, + cases: [ + [{}, {names: ["first", "input"], hasLast: false, lastType: "undefined"}], + [{x: 1}, {names: ["first", "input"], hasLast: false, lastType: "undefined"}], + ], +} + +{ + name: "v2 $nodes of a branch that did not run", + graph: { + nodes: [ + {switch: "route", when: ["kind == 'a'", ""]}, + {expression: "a", fields: {picked: "'a'"}}, + {expression: "b", fields: {picked: "'b'"}}, + {function: "f", source: """export const handler = async (input) => ({ + picked: input.picked, + ranA: input.$nodes.a !== undefined, + ranB: input.$nodes.b !== undefined, +});"""}, + ], + edges: ["input -> route", "route:0 -> a -> f", "route:1 -> b -> f", "f -> output"], + }, + cases: [ + [{kind: "a"}, {picked: "a", ranA: true, ranB: false}], + [{kind: "b"}, {picked: "b", ranA: false, ranB: true}], + [{}, {picked: "b", ranA: false, ranB: true}], + ], +} + +{ + name: "v2 reads the output of an earlier function node", + graph: { + nodes: [ + {function: "one", source: """export const handler = async (input) => ({ step: 1, value: input.v * 10 });"""}, + {function: "two", source: """export const handler = async (input) => ({ step: input.$nodes.one.step + 1, value: input.$nodes.one.value + input.$nodes.input.v });"""}, + ], + }, + cases: [ + [{v: 1}, {step: 2, value: 11}], + [{v: 3}, {step: 2, value: 33}], + ], +} + +{ + name: "v2 reads a decision table output by node name", + graph: { + nodes: [ + {table: "tier", inputs: ["score"], outputs: ["tier"], rules: [ + [">= 80", "'gold'"], + [">= 50", "'silver'"], + ["", "'bronze'"], + ]}, + {function: "f", source: """export const handler = async (input) => ({ tier: input.$nodes.tier.tier, score: input.$nodes.input.score ?? null });"""}, + ], + }, + cases: [ + [{score: 90}, {tier: "gold", score: 90}], + [{score: 60}, {tier: "silver", score: 60}], + [{score: 1}, {tier: "bronze", score: 1}], + [{}, {tier: "bronze"}], + ], +} + +{ + name: "v2 $nodes inside a sub-decision reaches the parent through its input node", + decisions: { + child: {nodes: [ + {input: "request"}, + {function: "inner", source: """export const handler = async (input) => ({ + parentCalc: input.$nodes.request.$nodes?.calc?.v ?? null, + own: Object.keys(input.$nodes).sort(), +});"""}, + ], edges: ["request -> inner -> output"]}, + }, + graph: { + nodes: [ + {expression: "calc", fields: {v: "a + 1"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{a: 1}, {parentCalc: 2, own: ["request"]}], + [{a: 9}, {parentCalc: 10, own: ["request"]}], + ], +} + +// --- Function nodes in larger graphs ------------------------------------------------------- + +{ + name: "v2 two functions merge at the output", + graph: { + nodes: [ + {function: "left", source: """export const handler = async (input) => ({ left: input.v, shared: 'left' });"""}, + {function: "right", source: """export const handler = async (input) => ({ right: input.v, shared: 'right' });"""}, + ], + edges: ["input -> left -> output", "input -> right -> output"], + }, + cases: [ + [{v: 1}, {left: 1, right: 1, shared: "left"}, "question: incoming outputs merge in reverse edge order, so the first-listed edge wins a shared key"], + [{v: "x"}, {left: "x", right: "x", shared: "left"}, "question: incoming outputs merge in reverse edge order, so the first-listed edge wins a shared key"], + [{v: null}, {shared: "left"}, "question: incoming outputs merge in reverse edge order, so the first-listed edge wins a shared key"], + ], +} + +{ + name: "v2 function feeding a decision table", + graph: { + nodes: [ + {function: "prep", source: """export const handler = async (input) => ({ age: new Date('2025-01-01').getUTCFullYear() - input.birthYear });"""}, + {table: "t", inputs: ["age"], outputs: ["group"], rules: [ + ["< 18", "'minor'"], + ["[18..64]", "'adult'"], + ["", "'senior'"], + ]}, + ], + }, + cases: [ + [{birthYear: 2010}, {group: "minor"}], + [{birthYear: 1990}, {group: "adult"}], + [{birthYear: 1950}, {group: "senior"}], + [{birthYear: 2007}, {group: "adult"}], + ], +} + +{ + name: "v2 function after a pass-through expression", + graph: { + nodes: [ + {expression: "e", passThrough: true, fields: {total: "price * qty"}}, + {function: "f", source: """export const handler = async (input) => ({ summary: `${input.qty} x ${input.price} = ${input.total}` });"""}, + ], + }, + cases: [ + [{price: 2, qty: 3}, {summary: "3 x 2 = 6"}], + [{price: 1.5, qty: 2}, {summary: "2 x 1.5 = 3"}], + ], +} + +{ + name: "v2 function on one switch branch", + graph: { + nodes: [ + {switch: "route", when: ["useJs", ""]}, + {function: "js", source: """export const handler = async (input) => ({ via: 'js', v: input.v * 2 });"""}, + {expression: "expr", fields: {via: "'expr'", v: "v * 3"}}, + ], + edges: ["input -> route", "route:0 -> js -> output", "route:1 -> expr -> output"], + }, + cases: [ + [{useJs: true, v: 2}, {via: "js", v: 4}], + [{useJs: false, v: 2}, {via: "expr", v: 6}], + [{v: 1}, {via: "expr", v: 3}], + ], +} + +{ + name: "v2 a failing function on a branch that is not taken", + graph: { + nodes: [ + {switch: "route", when: ["safe", ""]}, + {expression: "ok", fields: {ok: "true"}}, + {function: "bad", source: """export const handler = async (input) => { throw new Error('should not run'); };"""}, + ], + edges: ["input -> route", "route:0 -> ok -> output", "route:1 -> bad -> output"], + }, + cases: [ + [{safe: true}, {ok: true}], + [{safe: false}, "!error: should not run"], + ], +} + +{ + name: "v2 the same source in two nodes", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ({ n: (input.n ?? 0) + 1 });"""}, + {function: "b", source: """export const handler = async (input) => ({ n: (input.n ?? 0) + 1 });"""}, + ], + }, + cases: [ + [{n: 1}, {n: 3}], + [{}, {n: 2}], + ], +} + +{ + name: "v2 module state starts fresh for every evaluation", + graph: { + nodes: [{function: "f", source: """let calls = 0; +export const handler = async (input) => { calls += 1; return { first: calls === 1 || input.ignore === true }; };"""}], + }, + cases: [ + [{}, {first: true}], + [{ignore: true}, {first: true}], + ], +} + +{ + name: "v2 globals defined by one evaluation are not seen by the next", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const before = typeof globalThis.__specLeak; + globalThis.__specLeak = input.v; + return { before }; +};"""}], + }, + cases: [ + [{v: 1}, {before: "undefined"}], + [{v: 2}, {before: "undefined"}], + ], +} + +{ + name: "v2 zod is importable", + graph: { + nodes: [{function: "f", source: """import { z } from 'zod'; +const Schema = z.object({ age: z.number().int().min(0) }); +export const handler = async (input) => { + const parsed = Schema.safeParse({ age: input.age }); + return { valid: parsed.success }; +};"""}], + }, + cases: [ + [{age: 3}, {valid: true}], + [{age: -1}, {valid: false}], + [{age: 1.5}, {valid: false}], + [{age: "3"}, {valid: false}], + [{}, {valid: false}], + ], +} diff --git a/core/engine/tests/spec/graph/17-functions-v1.json5 b/core/engine/tests/spec/graph/17-functions-v1.json5 new file mode 100644 index 00000000..a1aa0a6e --- /dev/null +++ b/core/engine/tests/spec/graph/17-functions-v1.json5 @@ -0,0 +1,470 @@ +// Function nodes, version 1: a script defining `const handler = (input, helpers) => ...`. +// The input (with `$nodes`) is passed through JSON, the handler runs synchronously, and its +// result comes back through JSON.stringify. Helpers are `dayjs`, `moment` (an alias of +// dayjs), `Big` and `env`; `dayjs` and `Big` are also globals. + +// --- Return shapes --------------------------------------------------------------------------- + +{ + name: "v1 returns an object computed from the input", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ total: input.a + input.b, label: 'sum' });"""}], + }, + cases: [ + [{a: 1, b: 2}, {total: 3, label: "sum"}], + [{a: -5, b: 5}, {total: 0, label: "sum"}], + [{a: "x", b: "y"}, {total: "xy", label: "sum"}], + [{a: 1, b: "2"}, {total: "12", label: "sum"}], + [{a: true, b: true}, {total: 2, label: "sum"}], + ], +} + +{ + name: "v1 a function declaration handler", + graph: { + nodes: [{functionV1: "f", source: """function handler(input) { + return { n: input.n * 3 }; +}"""}], + }, + cases: [ + [{n: 1}, {n: 3}], + [{n: 0.5}, {n: 1.5}], + [{n: -2}, {n: -6}], + ], +} + +{ + name: "v1 returning the input passes it through", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => input;"""}], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{nested: {deep: [1, {x: "y"}]}}, {nested: {deep: [1, {x: "y"}]}}], + [{s: "text", b: false, n: null}, {s: "text", b: false}], + ], +} + +{ + name: "v1 the input carries $nodes as a plain key", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ keys: Object.keys(input).sort() });"""}], + }, + cases: [ + [{a: 1}, {keys: ["$nodes", "a"]}], + [{}, {keys: ["$nodes"]}], + ], +} + +{ + name: "v1 primitive and array results", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => input.value;"""}], + }, + cases: [ + [{value: 5}, {}], + [{value: "text"}, {}], + [{value: true}, {}], + [{value: {x: 1}}, {x: 1}], + [{value: [1, 2]}, [1, 2], "question: an array result is merged into the response object; the response is not an object"], + ], +} + +{ + name: "v1 a handler returning undefined", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => input.missing;"""}], + }, + cases: [ + [{}, "!error", "question: an undefined result drops the output key from the JSON envelope and fails, while v2 treats it as null"], + [{missing: {a: 1}}, {a: 1}], + [{missing: null}, {}], + ], +} + +{ + name: "v1 undefined properties are dropped by JSON", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ o: { missing: input.nope, explicit: undefined, kept: 1, list: [undefined, 1] } });"""}], + }, + cases: [ + [{}, {o: {kept: 1, list: [null, 1]}}], + [{nope: 3}, {o: {missing: 3, kept: 1, list: [null, 1]}}], + ], +} + +{ + name: "v1 non-data JS values follow JSON.stringify", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ o: { + fn: () => 1, + nan: NaN, + inf: Infinity, + date: new Date(input.ts), + map: new Map([['a', 1]]), + n: input.n, +} });"""}], + }, + cases: [ + [{ts: "2024-01-01T00:00:00Z", n: 1}, {o: {nan: null, inf: null, date: "2024-01-01T00:00:00.000Z", map: {}, n: 1}}], + [{ts: 0, n: "s"}, {o: {nan: null, inf: null, date: "1970-01-01T00:00:00.000Z", map: {}, n: "s"}}], + ], +} + +{ + name: "v1 an async handler resolves to an empty object", + graph: { + nodes: [{functionV1: "f", source: """const handler = async (input) => ({ v: input.v });"""}], + }, + cases: [ + [{v: 1}, {}, "question: v1 does not await the handler, the Promise is serialized as an empty object"], + [{}, {}, "question: v1 does not await the handler, the Promise is serialized as an empty object"], + ], +} + +// --- Numbers ------------------------------------------------------------------------------- +// v1 numbers go through JSON text both ways: exact decimals are parsed into doubles, but the +// double's shortest representation comes back unchanged, binary artifacts included. + +{ + name: "v1 decimals become doubles", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ v: input.v, t: typeof input.v });"""}], + }, + cases: [ + [{v: 0.1}, {v: 0.1, t: "number"}], + [{v: 1}, {v: 1, t: "number"}], + [{v: 0.1000000000000000000000000001}, {v: 0.1, t: "number"}], + [{v: 9007199254740993}, {v: 9007199254740992, t: "number"}], + [{v: 123456789.123456789}, {v: 123456789.12345679, t: "number"}], + ], +} + +{ + name: "v1 float arithmetic keeps binary artifacts", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ sum: input.a + input.b });"""}], + }, + cases: [ + [{a: 0.1, b: 0.2}, {sum: 0.30000000000000004}], + [{a: 1, b: 2}, {sum: 3}], + [{a: 0.7, b: 0.1}, {sum: 0.7999999999999999}], + ], +} + +{ + name: "v1 Big helper for exact decimals", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input, { Big }) => { + const sum = Big(input.a).plus(input.b); + return { str: sum.toString(), num: sum.toNumber(), fixed: sum.toFixed(2) }; +};"""}], + }, + cases: [ + [{a: 0.1, b: 0.2}, {str: "0.3", num: 0.3, fixed: "0.30"}], + [{a: 1, b: 2}, {str: "3", num: 3, fixed: "3.00"}], + [{a: "1.005", b: 0}, {str: "1.005", num: 1.005, fixed: "1.01"}], + ], +} + +{ + name: "v1 Big and dayjs are globals as well", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ + big: typeof Big, + dayjs: typeof dayjs, + value: Big(input.a).times(2).toNumber(), +});"""}], + }, + cases: [ + [{a: 1.5}, {big: "function", dayjs: "function", value: 3}], + [{a: 0}, {big: "function", dayjs: "function", value: 0}], + ], +} + +// --- Dates --------------------------------------------------------------------------------- + +{ + name: "v1 dayjs and moment helpers", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input, { dayjs, moment }) => ({ + next: dayjs(input.date).add(1, 'day').format('YYYY-MM-DD'), + sameAsMoment: moment(input.date).valueOf() === dayjs(input.date).valueOf(), + days: dayjs(input.to).diff(dayjs(input.date), 'day'), +});"""}], + }, + cases: [ + [{date: "2024-01-15", to: "2024-02-15"}, {next: "2024-01-16", sameAsMoment: true, days: 31}], + [{date: "2024-02-28", to: "2024-02-28"}, {next: "2024-02-29", sameAsMoment: true, days: 0}], + [{date: "2023-12-31", to: "2023-12-01"}, {next: "2024-01-01", sameAsMoment: true, days: -30}], + ], +} + +{ + name: "v1 schema date inputs arrive as strings", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ t: typeof input.d, d: input.d });"""}], + }, + cases: [ + [{d: date('2024-05-01')}, {t: "string", d: "2024-05-01"}], + [{d: "2024-05-01"}, {t: "string", d: "2024-05-01"}], + ], +} + +{ + name: "v1 the env helper is empty", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input, { env }) => ({ keys: Object.keys(env) });"""}], + }, + cases: [ + [{}, {keys: []}], + ], +} + +// --- Null and missing ------------------------------------------------------------------------ + +{ + name: "v1 null and missing fields", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ + value: input.v ?? 'default', + isNull: input.v === null, + has: 'v' in input, +});"""}], + }, + cases: [ + [{v: 1}, {value: 1, isNull: false, has: true}], + [{v: null}, {value: "default", isNull: true, has: true}], + [{}, {value: "default", isNull: false, has: false}], + [{v: 0}, {value: 0, isNull: false, has: true}], + [{v: false}, {value: false, isNull: false, has: true}], + ], +} + +// --- Errors ---------------------------------------------------------------------------------- + +{ + name: "v1 a thrown Error fails the evaluation", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => { + if (input.fail) throw new Error('v1 boom ' + input.fail); + return { ok: true }; +};"""}], + }, + cases: [ + [{fail: "now"}, "!error: v1 boom now"], + [{}, {ok: true}], + [{fail: 1}, "!error: v1 boom 1"], + ], +} + +{ + name: "v1 a thrown string", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => { if (input.fail) throw 'plain v1'; return { ok: true }; };"""}], + }, + cases: [ + [{fail: true}, "!error: plain v1"], + [{fail: false}, {ok: true}], + ], +} + +{ + name: "v1 runtime type errors", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ v: input.a.b });"""}], + }, + cases: [ + [{a: {b: 1}}, {v: 1}], + [{a: null}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "v1 a syntax error", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => ({ a: 1 ;"""}], + }, + cases: [ + [{}, "!error"], + [{a: 1}, "!error"], + ], +} + +{ + name: "v1 a script without a handler", + graph: { + nodes: [{functionV1: "f", source: """const other = (input) => input;"""}], + }, + cases: [ + [{}, "!error"], + ], +} + +{ + name: "v1 a v2 module source in a v1 node", + graph: { + nodes: [{functionV1: "f", source: """export const handler = async (input) => ({ a: 1 });"""}], + }, + cases: [ + [{}, "!error"], + ], +} + +{ + name: "v1 circular results cannot be serialized", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => { const o = { v: input.v }; if (input.loop) o.self = o; return o; };"""}], + }, + cases: [ + [{v: 1, loop: true}, "!error"], + [{v: 1}, {v: 1}], + ], +} + +{ + name: "v1 an error caught inside the handler", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => { + try { + return { parsed: JSON.parse(input.text) }; + } catch (e) { + return { error: e.name }; + } +};"""}], + }, + cases: [ + [{text: "{\"a\": 1}"}, {parsed: {a: 1}}], + [{text: "nope"}, {error: "SyntaxError"}], + ], +} + +// --- Mutation, console, state ---------------------------------------------------------------- + +{ + name: "v1 mutating the input changes only the result", + graph: { + nodes: [ + {functionV1: "f", source: """const handler = (input) => { input.a = 'changed'; return { a: input.a }; };"""}, + {expression: "e", passThrough: true, fields: {original: "$nodes.input.a"}}, + ], + }, + cases: [ + [{a: "orig"}, {a: "changed", original: "orig"}], + [{a: 1}, {a: "changed", original: 1}], + ], +} + +{ + name: "v1 console.log does not change the output", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => { console.log('in', input.v); const c = {}; c.c = c; console.log(c); return { v: input.v ?? 'none' }; };"""}], + }, + cases: [ + [{v: 1}, {v: 1}], + [{}, {v: "none"}], + ], +} + +{ + name: "v1 script state starts fresh for every evaluation", + graph: { + nodes: [{functionV1: "f", source: """globalThis.calls = (globalThis.calls ?? 0) + 1; +const handler = (input) => ({ calls: globalThis.calls });"""}], + }, + cases: [ + [{}, {calls: 1}], + [{a: 1}, {calls: 1}], + ], +} + +// --- Large data ---------------------------------------------------------------------------- + +{ + name: "v1 building large arrays", + graph: { + nodes: [{functionV1: "f", source: """const handler = (input) => { + const xs = Array.from({ length: input.n }, (_, i) => i); + return { count: xs.length, sum: xs.reduce((a, b) => a + b, 0), rows: xs.slice(-2).map((i) => ({ id: i })) }; +};"""}], + }, + cases: [ + [{n: 10000}, {count: 10000, sum: 49995000, rows: [{id: 9998}, {id: 9999}]}], + [{n: 1}, {count: 1, sum: 0, rows: [{id: 0}]}], + [{n: 0}, {count: 0, sum: 0, rows: []}], + ], +} + +// --- $nodes and graph position --------------------------------------------------------------- + +{ + name: "v1 reads earlier node outputs through $nodes", + graph: { + nodes: [ + {expression: "calc", fields: {doubled: "a * 2"}}, + {functionV1: "f", source: """const handler = (input) => ({ + fromInput: input.$nodes.input.a, + fromCalc: input.$nodes.calc.doubled, + direct: input.doubled, + names: Object.keys(input.$nodes).sort(), +});"""}, + ], + }, + cases: [ + [{a: 2}, {fromInput: 2, fromCalc: 4, direct: 4, names: ["calc", "input"]}], + [{a: 0.5}, {fromInput: 0.5, fromCalc: 1, direct: 1, names: ["calc", "input"]}], + ], +} + +{ + name: "v1 and v2 nodes in one graph", + graph: { + nodes: [ + {functionV1: "one", source: """const handler = (input) => ({ v: input.v + 1, from: 'v1' });"""}, + {function: "two", source: """export const handler = async (input) => ({ v: input.v * 10, prev: input.from, first: input.$nodes.one.v });"""}, + ], + }, + cases: [ + [{v: 1}, {v: 20, prev: "v1", first: 2}], + [{v: 0}, {v: 10, prev: "v1", first: 1}], + ], +} + +{ + name: "v1 function on a switch branch", + graph: { + nodes: [ + {switch: "route", when: ["v > 0", ""]}, + {functionV1: "pos", source: """const handler = (input) => ({ sign: 'positive', v: input.v });"""}, + {functionV1: "neg", source: """const handler = (input) => { if (input.v === undefined) throw new Error('no v'); return { sign: 'non-positive', v: input.v }; };"""}, + ], + edges: ["input -> route", "route:0 -> pos -> output", "route:1 -> neg -> output"], + }, + cases: [ + [{v: 3}, {sign: "positive", v: 3}], + [{v: 0}, {sign: "non-positive", v: 0}], + [{v: -1}, {sign: "non-positive", v: -1}], + [{}, "!error: no v"], + ], +} + +{ + name: "v1 output feeding a decision table", + graph: { + nodes: [ + {functionV1: "prep", source: """const handler = (input) => ({ score: input.answers.filter(Boolean).length * 25 });"""}, + {table: "t", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 75", "'A'"], + [">= 50", "'B'"], + ["", "'C'"], + ]}, + ], + }, + cases: [ + [{answers: [true, true, true, false]}, {grade: "A"}], + [{answers: [true, false, true, false]}, {grade: "B"}], + [{answers: []}, {grade: "C"}], + ], +} diff --git a/core/engine/tests/spec/graph/18-custom-nodes.json5 b/core/engine/tests/spec/graph/18-custom-nodes.json5 new file mode 100644 index 00000000..e3ea2745 --- /dev/null +++ b/core/engine/tests/spec/graph/18-custom-nodes.json5 @@ -0,0 +1,591 @@ +// Custom nodes, using the spec adapter kinds: `echo` returns its input (with `$nodes`), +// `config` returns its config, `render` renders each top-level config key through +// `CustomNodeRequest::get_field` (string values are templates over the node input), and +// `fail` errors with `config.message`. The engine owns how the node is placed in the graph, +// what input it receives and how its output and errors propagate. + +// --- echo ---------------------------------------------------------------------------------- + +{ + name: "custom echo returns its input", + graph: { + nodes: [{custom: "c", kind: "echo"}], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{nested: {list: [1, "x", true]}}, {nested: {list: [1, "x", true]}}], + [{a: 0.1000000000000000000000000001}, {a: 0.1000000000000000000000000001}], + [{n: null, s: ""}, {s: ""}], + ], +} + +{ + name: "custom echo receives $nodes, which a following node can see", + graph: { + nodes: [ + {custom: "c", kind: "echo"}, + {expression: "e", fields: {hasNodes: "$nodes != null", inputA: "$nodes.input.a", echoedA: "$nodes.c.a"}}, + ], + }, + cases: [ + [{a: 1}, {hasNodes: true, inputA: 1, echoedA: 1}], + [{a: "x"}, {hasNodes: true, inputA: "x", echoedA: "x"}], + ], +} + +{ + name: "custom echo after an expression node", + graph: { + nodes: [ + {expression: "calc", fields: {total: "price * qty"}}, + {custom: "c", kind: "echo"}, + ], + }, + cases: [ + [{price: 2, qty: 3}, {total: 6}], + [{price: 0.1, qty: 3}, {total: 0.3}], + [{price: 1, qty: 0}, {total: 0}], + ], +} + +{ + name: "custom echo of a pass-through expression", + graph: { + nodes: [ + {expression: "calc", passThrough: true, fields: {total: "price * qty"}}, + {custom: "c", kind: "echo"}, + ], + }, + cases: [ + [{price: 2, qty: 3}, {price: 2, qty: 3, total: 6}], + [{price: 5, qty: 1, extra: "kept"}, {price: 5, qty: 1, extra: "kept", total: 5}], + ], +} + +{ + name: "custom echo nodes chained", + graph: { + nodes: [ + {custom: "c1", kind: "echo"}, + {custom: "c2", kind: "echo"}, + {custom: "c3", kind: "echo"}, + ], + }, + cases: [ + [{a: 1}, {a: 1}], + [{a: {b: [1]}}, {a: {b: [1]}}], + ], +} + +// --- config ---------------------------------------------------------------------------------- + +{ + name: "custom config returns its config and ignores the input", + graph: { + nodes: [{custom: "c", kind: "config", config: {rate: 0.15, enabled: true, tiers: ["a", "b"], nested: {x: 1}}}], + }, + cases: [ + [{}, {rate: 0.15, enabled: true, tiers: ["a", "b"], nested: {x: 1}}], + [{rate: 99}, {rate: 0.15, enabled: true, tiers: ["a", "b"], nested: {x: 1}}], + ], +} + +{ + name: "custom config strings are not templates", + graph: { + nodes: [{custom: "c", kind: "config", config: {text: "{{ a }}"}}], + }, + cases: [ + [{a: 1}, {text: "{{ a }}"}], + [{}, {text: "{{ a }}"}], + ], +} + +{ + name: "custom config with an empty config", + graph: { + nodes: [{custom: "c", kind: "config", config: {}}], + }, + cases: [ + [{}, {}], + [{a: 1}, {}], + ], +} + +{ + name: "custom config output read by an expression", + graph: { + nodes: [ + {custom: "settings", kind: "config", config: {rate: 0.2, base: 10}}, + {expression: "e", fields: {fee: "base + $nodes.input.amount * rate", sawAmount: "amount != null"}}, + ], + edges: ["input -> settings -> e -> output"], + }, + cases: [ + [{amount: 100}, {fee: 30, sawAmount: false}], + [{amount: 0}, {fee: 10, sawAmount: false}], + [{amount: 2.5}, {fee: 10.5, sawAmount: false}], + ], +} + +// --- render ---------------------------------------------------------------------------------- + +{ + name: "custom render with a single interpolation keeps the value type", + graph: { + nodes: [{custom: "c", kind: "render", config: {value: "{{ a }}"}}], + }, + cases: [ + [{a: 1}, {value: 1}], + [{a: "x"}, {value: "x"}], + [{a: true}, {value: true}], + [{a: [1, 2]}, {value: [1, 2]}], + [{a: {b: 1}}, {value: {b: 1}}], + [{a: 1.50}, {value: 1.5}], + [{}, {}], + ], +} + +{ + name: "custom render with text around an interpolation produces a string", + graph: { + nodes: [{custom: "c", kind: "render", config: {greeting: "Hello, {{ name }}!"}}], + }, + cases: [ + [{name: "Ann"}, {greeting: "Hello, Ann!"}], + [{name: 42}, {greeting: "Hello, 42!"}], + [{name: true}, {greeting: "Hello, true!"}], + [{name: ""}, {greeting: "Hello, !"}], + [{}, {greeting: "Hello, null!"}, "question: a missing value renders as the text null inside a template"], + ], +} + +{ + name: "custom render with expressions in templates", + graph: { + nodes: [{custom: "c", kind: "render", config: { + total: "{{ price * qty }}", + label: "{{ qty }} x {{ price }}", + upper: "{{ upper(name) }}", + adult: "{{ age >= 18 }}", + }}], + }, + cases: [ + [{price: 2, qty: 3, name: "ann", age: 20}, {total: 6, label: "3 x 2", upper: "ANN", adult: true}], + [{price: 0.1, qty: 3, name: "bo", age: 3}, {total: 0.3, label: "3 x 0.1", upper: "BO", adult: false}], + ], +} + +{ + name: "custom render surrounding whitespace is trimmed", + graph: { + nodes: [{custom: "c", kind: "render", config: {padded: " {{ a }} ", inner: " x {{ a }} y "}}], + }, + cases: [ + [{a: 1}, {padded: 1, inner: "x 1 y"}], + [{a: "s"}, {padded: "s", inner: "x s y"}], + ], +} + +{ + name: "custom render of adjacent interpolations", + graph: { + nodes: [{custom: "c", kind: "render", config: {joined: "{{ a }}{{ b }}"}}], + }, + cases: [ + [{a: 1, b: 2}, {joined: "12"}], + [{a: "x", b: "y"}, {joined: "xy"}], + [{a: 1.50, b: 0}, {joined: "1.500"}], + ], +} + +{ + name: "custom render passes non-string config values through", + graph: { + nodes: [{custom: "c", kind: "render", config: {n: 2, b: false, list: ["{{ a }}"], obj: {t: "{{ a }}"}}}], + }, + cases: [ + [{a: 1}, {n: 2, b: false, list: ["{{ a }}"], obj: {t: "{{ a }}"}}], + ], +} + +{ + name: "custom render of plain text and empty strings", + graph: { + nodes: [{custom: "c", kind: "render", config: {plain: "just text", empty: ""}}], + }, + cases: [ + [{}, {plain: "just text"}], + [{a: 1}, {plain: "just text"}], + ], +} + +{ + name: "custom render with an invalid template expression", + graph: { + nodes: [{custom: "c", kind: "render", config: {broken: "{{ 1 + }}"}}], + }, + cases: [ + [{}, "!error"], + [{a: 1}, "!error"], + ], +} + +{ + name: "custom render with a template that fails at runtime", + graph: { + nodes: [{custom: "c", kind: "render", config: {v: "{{ a + 1 }}"}}], + }, + cases: [ + [{a: 1}, {v: 2}], + [{a: "x"}, "!error"], + ], +} + +{ + name: "custom render reading nested and dotted paths", + graph: { + nodes: [{custom: "c", kind: "render", config: {city: "{{ customer.address.city }}", first: "{{ items[0].sku }}"}}], + }, + cases: [ + [{customer: {address: {city: "Berlin"}}, items: [{sku: "a"}]}, {city: "Berlin", first: "a"}], + [{customer: {}, items: []}, {}], + [{}, {}], + ], +} + +{ + name: "custom render with a dotted config key", + graph: { + nodes: [{custom: "c", kind: "render", config: {"a.b": "{{ v }}"}}], + }, + cases: [ + [{v: 1}, {a: {b: null}}, "question: the key is looked up as a nested path in the config, so the literal dotted key is never found"], + ], +} + +{ + name: "custom render reading $nodes", + graph: { + nodes: [ + {expression: "calc", fields: {doubled: "a * 2"}}, + {custom: "c", kind: "render", config: {fromInput: "{{ $nodes.input.a }}", fromCalc: "{{ $nodes.calc.doubled }}", direct: "{{ doubled }}"}}, + ], + }, + cases: [ + [{a: 2}, {fromInput: 2, fromCalc: 4, direct: 4}], + [{a: 0.5}, {fromInput: 0.5, fromCalc: 1, direct: 1}], + ], +} + +{ + name: "custom render of a schema date input", + graph: { + nodes: [{custom: "c", kind: "render", config: {raw: "{{ d }}", text: "on {{ d }}"}}], + }, + cases: [ + [{d: date('2024-05-01')}, {raw: "2024-05-01", text: "on 2024-05-01"}], + [{d: "2024-05-01"}, {raw: "2024-05-01", text: "on 2024-05-01"}], + ], +} + +// --- fail and unknown kinds ------------------------------------------------------------------ + +{ + name: "custom fail errors with its message", + graph: { + nodes: [{custom: "c", kind: "fail", config: {message: "custom refused"}}], + }, + cases: [ + [{}, "!error: custom refused"], + [{a: 1}, "!error: custom refused"], + ], +} + +{ + name: "custom fail without a message", + graph: { + nodes: [{custom: "c", kind: "fail"}], + }, + cases: [ + [{}, "!error: custom node failed"], + ], +} + +{ + name: "custom error names the failing node", + graph: { + nodes: [ + {expression: "e", fields: {x: "1"}}, + {custom: "gate", id: "gate-id", kind: "fail", config: {message: "gate closed"}}, + ], + }, + cases: [ + [{}, "!error: gate-id"], + [{a: 1}, "!error: gate closed"], + ], +} + +{ + name: "custom node with an unknown kind", + graph: { + nodes: [{custom: "c", kind: "nope"}], + }, + cases: [ + [{}, "!error: unknown spec custom node kind"], + ], +} + +{ + name: "custom node without a kind", + graph: { + nodes: [{custom: "c"}], + }, + cases: [ + [{}, "!error"], + ], +} + +{ + name: "custom fail stops the nodes after it", + graph: { + nodes: [ + {custom: "check", kind: "fail", config: {message: "stop here"}}, + {expression: "after", fields: {reached: "true"}}, + ], + }, + cases: [ + [{}, "!error: stop here"], + [{reached: false}, "!error: stop here"], + ], +} + +{ + name: "custom fail on a parallel path fails the graph", + graph: { + nodes: [ + {expression: "ok", fields: {ok: "true"}}, + {custom: "bad", kind: "fail", config: {message: "parallel failure"}}, + ], + edges: ["input -> ok -> output", "input -> bad -> output"], + }, + cases: [ + [{}, "!error: parallel failure"], + [{a: 1}, "!error: parallel failure"], + ], +} + +// --- switches -------------------------------------------------------------------------------- + +{ + name: "custom nodes on switch branches", + graph: { + nodes: [ + {switch: "route", when: ["tier == 'gold'", "tier == 'silver'", ""]}, + {custom: "gold", kind: "config", config: {discount: 0.2}}, + {custom: "silver", kind: "render", config: {discount: "{{ 0.1 }}", tier: "{{ tier }}"}}, + {custom: "other", kind: "echo"}, + ], + edges: ["input -> route", "route:0 -> gold -> output", "route:1 -> silver -> output", "route:2 -> other -> output"], + }, + cases: [ + [{tier: "gold"}, {discount: 0.2}], + [{tier: "silver"}, {discount: 0.1, tier: "silver"}], + [{tier: "bronze"}, {tier: "bronze"}], + [{}, {}], + ], +} + +{ + name: "custom fail on a branch that is not taken", + graph: { + nodes: [ + {switch: "route", when: ["allowed", ""]}, + {custom: "ok", kind: "render", config: {status: "'allowed'", who: "{{ user }}"}}, + {custom: "deny", kind: "fail", config: {message: "denied"}}, + ], + edges: ["input -> route", "route:0 -> ok -> output", "route:1 -> deny -> output"], + }, + cases: [ + [{allowed: true, user: "ann"}, {status: "'allowed'", who: "ann"}], + [{allowed: false, user: "ann"}, "!error: denied"], + [{user: "bo"}, "!error: denied"], + ], +} + +{ + name: "custom nodes on collect switch branches merge (the default branch always fires under collect)", + graph: { + nodes: [ + {switch: "route", hit: "collect", when: ["a > 0", "b > 0", ""]}, + {custom: "ca", kind: "render", config: {fromA: "{{ a }}"}}, + {custom: "cb", kind: "render", config: {fromB: "{{ b }}"}}, + {custom: "cd", kind: "config", config: {fallback: true}}, + ], + edges: ["input -> route", "route:0 -> ca -> output", "route:1 -> cb -> output", "route:2 -> cd -> output"], + }, + cases: [ + [{a: 1, b: 1}, {fromA: 1, fromB: 1, fallback: true}], + [{a: 1, b: 0}, {fromA: 1, fallback: true}], + [{a: 0, b: 2}, {fromB: 2, fallback: true}], + [{a: 0, b: 0}, {fallback: true}], + ], +} + +{ + name: "custom echo before a switch", + graph: { + nodes: [ + {custom: "prep", kind: "render", config: {score: "{{ points * 10 }}"}}, + {switch: "route", when: ["score >= 50", ""]}, + {expression: "pass", fields: {result: "'pass'", score: "score"}}, + {expression: "fail", fields: {result: "'fail'", score: "score"}}, + ], + edges: ["input -> prep -> route", "route:0 -> pass -> output", "route:1 -> fail -> output"], + }, + cases: [ + [{points: 5}, {result: "pass", score: 50}], + [{points: 4.9}, {result: "fail", score: 49}], + [{points: 0}, {result: "fail", score: 0}], + ], +} + +// --- merges ---------------------------------------------------------------------------------- + +{ + name: "custom nodes merging with an expression at the output", + graph: { + nodes: [ + {expression: "calc", fields: {total: "a + b"}}, + {custom: "meta", kind: "config", config: {version: 2, source: "custom"}}, + {custom: "echo", kind: "echo"}, + ], + edges: ["input -> calc -> output", "input -> meta -> output", "input -> echo -> output"], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, total: 3, version: 2, source: "custom"}], + [{a: 0, b: 0}, {a: 0, b: 0, total: 0, version: 2, source: "custom"}], + ], +} + +{ + name: "custom nodes as join inputs for a downstream node", + graph: { + nodes: [ + {custom: "left", kind: "render", config: {l: "{{ v * 2 }}"}}, + {custom: "right", kind: "render", config: {r: "{{ v * 3 }}"}}, + {expression: "join", fields: {sum: "l + r"}}, + ], + edges: ["input -> left -> join", "input -> right -> join", "join -> output"], + }, + cases: [ + [{v: 1}, {sum: 5}], + [{v: 0.5}, {sum: 2.5}], + [{v: 0}, {sum: 0}], + ], +} + +{ + name: "custom render reads a join of two earlier nodes", + graph: { + nodes: [ + {expression: "a", fields: {x: "1", shared: "'a'"}}, + {expression: "b", fields: {y: "2", shared: "'b'"}}, + {custom: "c", kind: "render", config: {x: "{{ x }}", y: "{{ y }}", shared: "{{ shared }}"}}, + ], + edges: ["input -> a -> c", "input -> b -> c", "c -> output"], + }, + cases: [ + [{}, {x: 1, y: 2, shared: "a"}], + ], +} + +{ + name: "custom echo of a join keeps keys from both sides", + graph: { + nodes: [ + {expression: "a", fields: {x: "v"}}, + {expression: "b", fields: {y: "v * 2"}}, + {custom: "c", kind: "echo"}, + ], + edges: ["input -> a -> c", "input -> b -> c", "c -> output"], + }, + cases: [ + [{v: 1}, {x: 1, y: 2}], + [{v: 2.5}, {x: 2.5, y: 5}], + ], +} + +// --- sub-decisions and loops ------------------------------------------------------------- + +{ + name: "custom node inside a sub-decision", + decisions: { + child: {nodes: [{custom: "inner", kind: "render", config: {msg: "child got {{ x }}", x: "{{ x }}"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 1}, {msg: "child got 1", x: 1}], + [{x: "s"}, {msg: "child got s", x: "s"}], + ], +} + +{ + name: "custom fail inside a sub-decision", + decisions: { + child: {nodes: [{custom: "inner", kind: "fail", config: {message: "child failed"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, "!error: child failed"], + ], +} + +{ + name: "custom node inside a looped sub-decision", + decisions: { + child: {nodes: [{custom: "inner", kind: "render", config: {label: "#{{ id }}"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "labels", executionMode: "loop"}], + }, + cases: [ + [{items: [{id: 1}, {id: 2}]}, {labels: [{label: "#1"}, {label: "#2"}]}], + [{items: []}, {labels: []}], + ], +} + +// --- interactions with functions ---------------------------------------------------------- + +{ + name: "custom node output read by a function", + graph: { + nodes: [ + {custom: "settings", kind: "config", config: {multiplier: 3}}, + {function: "f", source: """export const handler = async (input) => ({ v: input.$nodes.input.v * input.multiplier });"""}, + ], + }, + cases: [ + [{v: 2}, {v: 6}], + [{v: 0}, {v: 0}], + ], +} + +{ + name: "custom render of a function result", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({ items: input.names.map((n) => n.toUpperCase()) });"""}, + {custom: "c", kind: "render", config: {first: "{{ items[0] }}", count: "{{ len(items) }}", line: "{{ len(items) }} items, first {{ items[0] }}"}}, + ], + }, + cases: [ + [{names: ["a", "b"]}, {first: "A", count: 2, line: "2 items, first A"}], + [{names: ["x"]}, {first: "X", count: 1, line: "1 items, first X"}], + ], +} diff --git a/core/engine/tests/spec/graph/19-schemas.json5 b/core/engine/tests/spec/graph/19-schemas.json5 new file mode 100644 index 00000000..02648307 --- /dev/null +++ b/core/engine/tests/spec/graph/19-schemas.json5 @@ -0,0 +1,756 @@ +// Input and output node JSON schemas. A schema on the input node validates the request before any +// node runs; a schema on the output node validates the merged result after the last node. Validation +// failures are node errors (`NodeError`) carrying `path: message`. A field declared with +// `format: date` or `format: date-time` becomes a date value on the input node, so downstream nodes +// see a date and the result renders it back as its source text. + +// --------------------------------------------------------------------------------------------- +// Required fields on the input node. +{ + name: "input schema: required fields must be present", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["age", "name"], properties: {age: {type: "number"}, name: {type: "string"}}}}, + {expression: "calc", fields: {older: "age + 1", greeting: "'hi ' + name"}}, + ], + }, + cases: [ + [{age: 30, name: "ann"}, {older: 31, greeting: "hi ann"}], + [{age: 0, name: ""}, {older: 1, greeting: "hi "}], + [{age: 30}, "!error: NodeError"], + [{name: "ann"}, "!error: NodeError"], + [{}, "!error: NodeError"], + [{age: 30, name: "ann", extra: true}, {older: 31, greeting: "hi ann"}], + ], +} + +{ + name: "input schema: the error names the missing property", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["customerId"], properties: {customerId: {type: "string"}}}}, + ], + }, + cases: [ + [{customerId: "c-1"}, {customerId: "c-1"}], + [{}, "!error: customerId"], + [{customerid: "c-1"}, "!error: customerId"], + ], +} + +{ + name: "input schema: a required field that is null fails a non-nullable type", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["score"], properties: {score: {type: "number"}}}}, + ], + }, + cases: [ + [{score: 1}, {score: 1}], + [{score: null}, "!error: NodeError"], + [{score: "1"}, "!error: NodeError"], + ], +} + +{ + name: "input schema: an optional null field validates, and the result drops null-valued keys", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {nickname: {type: "string"}, age: {type: "number"}}}}, + ], + }, + cases: [ + [{nickname: "al", age: 3}, {nickname: "al", age: 3}], + [{nickname: null, age: 3}, {age: 3}], + [{age: null}, {}], + [{}, {}], + [{nickname: 5}, "!error: NodeError"], + ], +} + +{ + name: "input schema: nullable via a type list", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["limit"], properties: {limit: {type: ["number", "null"]}}}}, + {expression: "calc", fields: {limit: "limit ?? 100"}}, + ], + }, + cases: [ + [{limit: 5}, {limit: 5}], + [{limit: null}, {limit: 100}], + [{}, "!error: NodeError"], + [{limit: "5"}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Primitive types. +{ + name: "input schema: primitive types are checked", + graph: { + nodes: [ + {input: "request", schema: { + type: "object", + properties: {s: {type: "string"}, n: {type: "number"}, i: {type: "integer"}, b: {type: "boolean"}, o: {type: "object"}, a: {type: "array"}}, + }}, + ], + }, + cases: [ + [{s: "x", n: 1.5, i: 2, b: false, o: {}, a: []}, {s: "x", n: 1.5, i: 2, b: false, o: {}, a: []}], + [{s: 1}, "!error: NodeError"], + [{n: "1"}, "!error: NodeError"], + [{n: true}, "!error: NodeError"], + [{i: 2.5}, "!error: NodeError"], + [{i: 2.0}, {i: 2}], + [{b: "true"}, "!error: NodeError"], + [{b: 0}, "!error: NodeError"], + [{o: []}, "!error: NodeError"], + [{a: {}}, "!error: NodeError"], + [{n: -0.000001}, {n: -0.000001}], + [{n: 12345678901234567890123456}, {n: 12345678901234567890123456}], + ], +} + +{ + name: "input schema: numeric bounds", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + pct: {type: "number", minimum: 0, maximum: 100}, + qty: {type: "integer", exclusiveMinimum: 0}, + step: {type: "number", multipleOf: 0.5}, + }}}, + ], + }, + cases: [ + [{pct: 0}, {pct: 0}], + [{pct: 100}, {pct: 100}], + [{pct: 100.01}, "!error: NodeError"], + [{pct: -1}, "!error: NodeError"], + [{qty: 1}, {qty: 1}], + [{qty: 0}, "!error: NodeError"], + [{step: 2.5}, {step: 2.5}], + [{step: 2.25}, "!error: NodeError"], + ], +} + +{ + name: "input schema: string length and pattern", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + code: {type: "string", minLength: 2, maxLength: 4}, + sku: {type: "string", pattern: "^[A-Z]{3}-[0-9]+$"}, + }}}, + ], + }, + cases: [ + [{code: "ab"}, {code: "ab"}], + [{code: "abcd"}, {code: "abcd"}], + [{code: "a"}, "!error: NodeError"], + [{code: "abcde"}, "!error: NodeError"], + [{code: "ßü"}, {code: "ßü"}], + [{sku: "ABC-12"}, {sku: "ABC-12"}], + [{sku: "abc-12"}, "!error: NodeError"], + [{sku: "ABC-"}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Enums and const. +{ + name: "input schema: enum restricts values", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["tier"], properties: {tier: {type: "string", enum: ["gold", "silver", "bronze"]}}}}, + {table: "discount", inputs: ["tier"], outputs: ["rate"], rules: [ + ["'gold'", "0.2"], + ["'silver'", "0.1"], + ["", "0"], + ]}, + ], + }, + cases: [ + [{tier: "gold"}, {rate: 0.2}], + [{tier: "silver"}, {rate: 0.1}], + [{tier: "bronze"}, {rate: 0}], + [{tier: "platinum"}, "!error: NodeError"], + [{tier: "Gold"}, "!error: NodeError"], + [{tier: null}, "!error: NodeError"], + ], +} + +{ + name: "input schema: mixed-type enum and const", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {level: {enum: [1, 2, "max", null]}, version: {const: "v2"}}}}, + ], + }, + cases: [ + [{level: 1}, {level: 1}], + [{level: "max"}, {level: "max"}], + [{level: null}, {}], + [{level: 3}, "!error: NodeError"], + [{level: "1"}, "!error: NodeError"], + [{version: "v2"}, {version: "v2"}], + [{version: "v1"}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Nested objects. +{ + name: "input schema: nested object properties", + graph: { + nodes: [ + {input: "request", schema: { + type: "object", + required: ["customer"], + properties: {customer: {type: "object", required: ["address"], properties: { + address: {type: "object", required: ["country"], properties: {country: {type: "string", minLength: 2}}}, + }}}, + }}, + {expression: "calc", fields: {country: "customer.address.country"}}, + ], + }, + cases: [ + [{customer: {address: {country: "DE"}}}, {country: "DE"}], + [{customer: {address: {country: "D"}}}, "!error: /customer/address/country"], + [{customer: {address: {}}}, "!error: NodeError"], + [{customer: {}}, "!error: NodeError"], + [{customer: null}, "!error: NodeError"], + [{customer: "DE"}, "!error: NodeError"], + ], +} + +{ + name: "input schema: dotted keys are literal property names, not paths", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["a.b"]}}, + ], + }, + cases: [ + [{"a.b": 1}, {"a.b": 1}], + [{a: {b: 1}}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Arrays. +{ + name: "input schema: array items are validated", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + scores: {type: "array", items: {type: "number"}, minItems: 1, maxItems: 3}, + }}}, + {expression: "calc", fields: {total: "sum(scores ?? [])"}}, + ], + }, + cases: [ + [{scores: [1, 2, 3]}, {total: 6}], + [{scores: [1]}, {total: 1}], + [{scores: []}, "!error: NodeError"], + [{scores: [1, 2, 3, 4]}, "!error: NodeError"], + [{scores: [1, "2"]}, "!error: /scores/1"], + [{scores: [1, null]}, "!error: NodeError"], + [{}, {total: 0}], + ], +} + +{ + name: "input schema: arrays of objects with required members", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["lines"], properties: { + lines: {type: "array", items: {type: "object", required: ["qty", "price"], properties: {qty: {type: "integer", minimum: 1}, price: {type: "number"}}}}, + }}}, + {expression: "calc", fields: {total: "sum(map(lines, #.qty * #.price))"}}, + ], + }, + cases: [ + [{lines: [{qty: 2, price: 1.5}, {qty: 1, price: 10}]}, {total: 13}], + [{lines: []}, {total: 0}], + [{lines: [{qty: 0, price: 1}]}, "!error: /lines/0/qty"], + [{lines: [{qty: 1, price: 1}, {qty: 1}]}, "!error: /lines/1"], + [{lines: {qty: 1, price: 1}}, "!error: NodeError"], + ], +} + +{ + name: "input schema: uniqueItems and contains", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + tags: {type: "array", uniqueItems: true, items: {type: "string"}}, + flags: {type: "array", contains: {const: "primary"}}, + }}}, + ], + }, + cases: [ + [{tags: ["a", "b"]}, {tags: ["a", "b"]}], + [{tags: ["a", "a"]}, "!error: NodeError"], + [{flags: ["x", "primary"]}, {flags: ["x", "primary"]}], + [{flags: ["x"]}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// additionalProperties. +// A null-valued unknown key is accepted: validation retries with null-valued keys removed, so null +// counts as absent for every keyword (required excepted, see above). +{ + name: "input schema: additionalProperties false rejects unknown keys", + graph: { + nodes: [ + {input: "request", schema: {type: "object", additionalProperties: false, properties: {a: {type: "number"}, b: {type: "string"}}}}, + ], + }, + cases: [ + [{a: 1, b: "x"}, {a: 1, b: "x"}], + [{a: 1}, {a: 1}], + [{}, {}], + [{a: 1, c: 2}, "!error: NodeError"], + [{c: null}, {}], + [{c: null, d: 1}, "!error: NodeError"], + ], +} + +{ + name: "input schema: additionalProperties with a schema types the extra keys", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {id: {type: "string"}}, additionalProperties: {type: "number"}}}, + {expression: "calc", fields: {sum: "(p ?? 0) + (q ?? 0)"}}, + ], + }, + cases: [ + [{id: "x", p: 1, q: 2}, {sum: 3}], + [{id: "x", p: 1.5}, {sum: 1.5}], + [{id: "x"}, {sum: 0}], + [{id: "x", p: "1"}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Combinators. +{ + name: "input schema: oneOf / anyOf branches", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["payment"], properties: {payment: {oneOf: [ + {type: "object", required: ["card"], properties: {card: {type: "string"}}}, + {type: "object", required: ["iban"], properties: {iban: {type: "string"}}}, + ]}}}}, + {expression: "calc", fields: {method: "payment.card != null ? 'card' : 'iban'"}}, + ], + }, + cases: [ + [{payment: {card: "4111"}}, {method: "card"}], + [{payment: {iban: "DE00"}}, {method: "iban"}], + [{payment: {card: "4111", iban: "DE00"}}, "!error: NodeError"], + [{payment: {}}, "!error: NodeError"], + ], +} + +{ + name: "input schema: if/then conditional requirement", + graph: { + nodes: [ + {input: "request", schema: { + type: "object", + properties: {kind: {type: "string"}, vat: {type: "string"}}, + if: {properties: {kind: {const: "business"}}, required: ["kind"]}, + then: {required: ["vat"]}, + }}, + ], + }, + cases: [ + [{kind: "private"}, {kind: "private"}], + [{kind: "business", vat: "DE1"}, {kind: "business", vat: "DE1"}], + [{kind: "business"}, "!error: NodeError"], + [{}, {}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Schema root shapes and degenerate schemas. +{ + name: "input schema: an empty schema accepts anything", + graph: { + nodes: [{input: "request", schema: {}}], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{a: [null, {b: "x"}]}, {a: [null, {b: "x"}]}], + ], +} + +{ + name: "input schema: a schema given as a string is parsed", + graph: { + nodes: [{input: "request", schema: '{"type":"object","required":["x"]}'}], + }, + cases: [ + [{x: 1}, {x: 1}], + [{}, "!error: NodeError"], + ], +} + +{ + name: "input schema: an empty string schema means no schema", + graph: { + nodes: [{input: "request", schema: ""}], + }, + cases: [ + [{x: 1}, {x: 1}], + [{}, {}], + ], +} + +{ + name: "input schema: a root type other than object rejects every request", + graph: { + nodes: [{input: "request", schema: {type: "array"}}], + }, + cases: [ + [{}, "!error: NodeError"], + [{a: []}, "!error: NodeError"], + ], +} + +{ + name: "input schema: the walk stops on failure, no node after the input runs", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["x"]}}, + {custom: "boom", kind: "fail", config: {message: "should not run"}}, + ], + }, + cases: [ + [{}, "!error: required"], + [{x: 1}, "!error: should not run"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dates declared in the input schema become date values. +{ + name: "input schema: format date-time produces a date value", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {at: {type: "string", format: "date-time"}}}}, + {expression: "calc", fields: {year: "year(at)", plusDay: "at.add(1, 'd')", same: "at", kind: "type(at)"}}, + ], + }, + cases: [ + [{at: "2024-02-28T12:00:00Z"}, {year: 2024, plusDay: "2024-02-29T12:00:00Z", same: "2024-02-28T12:00:00Z", kind: "date"}], + [{at: "2025-03-20T10:15:30Z"}, {year: 2025, plusDay: "2025-03-21T10:15:30Z", same: "2025-03-20T10:15:30Z", kind: "date"}], + ], +} + +{ + name: "input schema: a declared date passes through unchanged as its source text", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}, at: {type: "string", format: "date-time"}}}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {day: "2024-01-31"}], + [{at: "2024-01-31T08:00:00+02:00"}, {at: "2024-01-31T08:00:00+02:00"}], + [{day: "2024-01-31", other: "2024-01-31"}, {day: "2024-01-31", other: "2024-01-31"}], + [{}, {}], + ], +} + +{ + name: "input schema: a declared date compares as a date", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["start", "end"], properties: {start: {type: "string", format: "date"}, end: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {ordered: "start < end", days: "end.diff(start, 'day')"}}, + ], + }, + cases: [ + [{start: "2024-01-01", end: "2024-03-01"}, {ordered: true, days: 60}], + [{start: "2024-03-01", end: "2024-01-01"}, {ordered: false, days: -60}], + [{start: "2025-03-20", end: "2025-03-20"}, {ordered: false, days: 0}], + ], +} + +{ + name: "input schema: a nullable date field stays null", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {due: {anyOf: [{type: "string", format: "date"}, {type: "null"}]}}}}, + {expression: "calc", fields: {kind: "type(due)", has: "due != null"}}, + ], + }, + cases: [ + [{due: "2024-05-01"}, {kind: "date", has: true}], + [{due: null}, {kind: "null", has: false}], + [{}, {kind: "null", has: false}], + ], +} + +{ + name: "input schema: dates inside nested objects and arrays", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + order: {type: "object", properties: {placed: {type: "string", format: "date"}}}, + payments: {type: "array", items: {type: "object", properties: {on: {type: "string", format: "date"}}}}, + }}}, + {expression: "calc", fields: {placedYear: "year(order.placed)", payYears: "map(payments, year(#.on))"}}, + ], + }, + cases: [ + [{order: {placed: "2023-06-01"}, payments: [{on: "2023-07-01"}, {on: "2024-01-15"}]}, {placedYear: 2023, payYears: [2023, 2024]}], + [{order: {placed: "2020-02-29"}, payments: []}, {placedYear: 2020, payYears: []}], + ], +} + +{ + name: "input schema: an undeclared date-looking string stays a string", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string"}}}}, + {expression: "calc", fields: {kind: "type(day)"}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {kind: "string"}], + ], +} + +{ + name: "input schema: an invalid date string fails the format", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {day: "2024-01-31"}], + [{day: "2024-02-30"}, "!error: NodeError"], + [{day: "31.01.2024"}, "!error: NodeError"], + [{day: "not a date"}, "!error: NodeError"], + [{day: 20240131}, "!error: NodeError"], + ], +} + +{ + name: "input schema: a date value given as input is accepted by a date-time field", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {at: {type: "string", format: "date-time"}}}}, + {expression: "calc", fields: {month: "at.month()"}}, + ], + }, + cases: [ + [{at: date("2024-07-04T00:00:00Z")}, {month: 7}], + ], +} + +{ + name: "input schema: dates feed a decision table", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["signup"], properties: {signup: {type: "string", format: "date"}}}}, + {table: "cohort", inputs: ["signup"], outputs: ["cohort"], rules: [ + ["< d('2024-01-01')", "'legacy'"], + ["[d('2024-01-01')..d('2024-12-31')]", "'2024'"], + ["", "'new'"], + ]}, + ], + }, + cases: [ + [{signup: "2023-12-31"}, {cohort: "legacy"}], + [{signup: "2024-01-01"}, {cohort: "2024"}], + [{signup: "2024-12-31"}, {cohort: "2024"}], + [{signup: "2025-01-01"}, {cohort: "new"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Output schemas validate the merged result. +{ + name: "output schema: success when the result conforms", + graph: { + nodes: [ + {expression: "calc", fields: {total: "a + b", label: "a > b ? 'a' : 'b'"}}, + {output: "response", schema: {type: "object", required: ["total", "label"], properties: {total: {type: "number", minimum: 0}, label: {enum: ["a", "b"]}}}}, + ], + }, + cases: [ + [{a: 1, b: 2}, {total: 3, label: "b"}], + [{a: 5, b: 2}, {total: 7, label: "a"}], + [{a: -5, b: 2}, "!error: /total"], + [{a: 0, b: 0}, {total: 0, label: "b"}], + ], +} + +{ + name: "output schema: a missing computed field fails required", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["price"], rules: [ + ["'a'", "10"], + ["'b'", "20"], + ]}, + {output: "response", schema: {type: "object", required: ["price"]}}, + ], + }, + cases: [ + [{kind: "a"}, {price: 10}], + [{kind: "b"}, {price: 20}], + [{kind: "c"}, "!error: price"], + [{}, "!error: NodeError"], + ], +} + +{ + name: "output schema: type mismatch in the produced value", + graph: { + nodes: [ + {expression: "calc", fields: {count: "len(items)"}}, + {output: "response", schema: {type: "object", properties: {count: {type: "string"}}}}, + ], + }, + cases: [ + [{items: [1]}, "!error: NodeError"], + [{items: "ab"}, "!error: NodeError"], + ], +} + +{ + name: "output schema: additionalProperties false catches pass-through leaks", + graph: { + nodes: [ + {expression: "calc", passThrough: true, fields: {score: "x * 10"}}, + {output: "response", schema: {type: "object", additionalProperties: false, properties: {score: {type: "number"}, x: {type: "number"}}}}, + ], + }, + cases: [ + [{x: 1}, {x: 1, score: 10}], + [{x: 1, secret: "s"}, "!error: NodeError"], + ], +} + +{ + name: "output schema: optional null fields are tolerated", + graph: { + nodes: [ + {expression: "calc", fields: {note: "comment", n: "1"}}, + {output: "response", schema: {type: "object", properties: {note: {type: "string"}, n: {type: "number"}}}}, + ], + }, + cases: [ + [{comment: "hi"}, {note: "hi", n: 1}], + [{}, {n: 1}], + [{comment: 7}, "!error: NodeError"], + ], +} + +{ + name: "output schema: format date-time does not turn output strings into dates", + graph: { + nodes: [ + {expression: "calc", fields: {at: "'2024-01-01T00:00:00Z'"}}, + {output: "response", schema: {type: "object", properties: {at: {type: "string", format: "date-time"}}}}, + ], + }, + cases: [ + [{}, {at: "2024-01-01T00:00:00Z"}], + ], +} + +{ + name: "output schema: a date value produced by an expression satisfies format date-time", + graph: { + nodes: [ + {expression: "calc", fields: {at: "d('2024-01-01T00:00:00Z')"}}, + {output: "response", schema: {type: "object", required: ["at"], properties: {at: {type: "string", format: "date-time"}}}}, + ], + }, + cases: [ + [{}, {at: "2024-01-01T00:00:00Z"}], + ], +} + +{ + name: "both schemas: input and output validate independently", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["qty"], properties: {qty: {type: "integer"}}}}, + {expression: "calc", fields: {total: "qty * 2.5"}}, + {output: "response", schema: {type: "object", properties: {total: {type: "integer"}}}}, + ], + }, + cases: [ + [{qty: 2}, {total: 5}], + [{qty: 4}, {total: 10}], + [{qty: 1}, "!error: /total"], + [{qty: 1.5}, "!error: /qty"], + [{}, "!error: NodeError"], + ], +} + +{ + name: "output schema on a sub-decision fails the parent", + decisions: { + child: {nodes: [ + {expression: "calc", fields: {y: "x * 2"}}, + {output: "response", schema: {type: "object", properties: {y: {type: "number", maximum: 10}}}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 1}, {y: 2}], + [{x: 5}, {y: 10}], + [{x: 6}, "!error: NodeError"], + ], +} + +{ + name: "input schema of a sub-decision validates what the parent sends", + decisions: { + child: {nodes: [ + {input: "request", schema: {type: "object", required: ["x"], properties: {x: {type: "number"}, d: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {kind: "type(d)", x: "x"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 1, d: "2024-01-01"}, {kind: "date", x: 1}], + [{x: 1}, {kind: "null", x: 1}], + [{y: 1}, "!error: NodeError"], + ], +} + +{ + name: "input schema with loop mode: each item is validated by the sub-decision", + decisions: { + child: {nodes: [ + {input: "request", schema: {type: "object", required: ["v"], properties: {v: {type: "number"}}}}, + {expression: "calc", fields: {w: "v + 1"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", executionMode: "loop", outputPath: "out"}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {out: [{w: 2}, {w: 3}]}], + [{items: []}, {out: []}], + [{items: [{v: 1}, {}]}, "!error: NodeError"], + ], +} diff --git a/core/engine/tests/spec/graph/20-graph-errors.json5 b/core/engine/tests/spec/graph/20-graph-errors.json5 new file mode 100644 index 00000000..bce5f1b7 --- /dev/null +++ b/core/engine/tests/spec/graph/20-graph-errors.json5 @@ -0,0 +1,872 @@ +// Structural and runtime errors. Structural problems (input node count, cycles, edges naming +// unknown nodes) are reported as `InvalidGraph` before any node runs; runtime failures inside a +// node are `NodeError` with the failing node's id. Only the stable kinds are matched in text. + +// --------------------------------------------------------------------------------------------- +// Input node count. +{ + name: "structure: a graph without an input node is invalid", + graph: { + raw: { + nodes: [ + {id: "c", name: "calc", type: "expressionNode", content: {expressions: [{id: "x", key: "y", value: "1"}]}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [{id: "e", sourceId: "c", targetId: "o"}], + }, + }, + cases: [ + [{}, "!error: invalidInputCount"], + [{a: 1}, "!error: InvalidGraph"], + ], +} + +{ + name: "structure: two input nodes are invalid", + graph: { + raw: { + nodes: [ + {id: "i1", name: "request", type: "inputNode", content: {}}, + {id: "i2", name: "request2", type: "inputNode", content: {}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [{id: "e1", sourceId: "i1", targetId: "o"}, {id: "e2", sourceId: "i2", targetId: "o"}], + }, + }, + cases: [ + [{}, "!error: invalidInputCount"], + [{a: 1}, "!error: \"nodeCount\":2"], + ], +} + +{ + name: "structure: an empty node list is invalid", + graph: {raw: {nodes: [], edges: []}}, + cases: [ + [{}, "!error: invalidInputCount"], + [{a: 1}, "!error: \"nodeCount\":0"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Output node count. The output node is optional: without one, the result is the merge of every +// visited node that has no outgoing edges. +{ + name: "structure: without an output node the dead-end node's output is the result", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "c", name: "calc", type: "expressionNode", content: {expressions: [{id: "x", key: "y", value: "a * 2"}]}}, + ], + edges: [{id: "e", sourceId: "i", targetId: "c"}], + }, + }, + cases: [ + [{a: 1}, {y: 2}], + [{a: 2.5}, {y: 5}], + [{}, "!error: NodeError"], + ], +} + +{ + name: "structure: without an output node every dead end is merged", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "a", name: "a", type: "expressionNode", content: {expressions: [{id: "x", key: "fromA", value: "v + 1"}]}}, + {id: "b", name: "b", type: "expressionNode", content: {expressions: [{id: "x", key: "fromB", value: "v + 2"}]}}, + ], + edges: [{id: "e1", sourceId: "i", targetId: "a"}, {id: "e2", sourceId: "i", targetId: "b"}], + }, + }, + cases: [ + [{v: 1}, {fromA: 2, fromB: 3}], + [{v: 0}, {fromA: 1, fromB: 2}], + ], +} + +{ + name: "structure: an input node alone returns the request", + graph: { + raw: { + nodes: [{id: "i", name: "request", type: "inputNode", content: {}}], + edges: [], + }, + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + [{a: {b: [1, 2]}}, {a: {b: [1, 2]}}], + ], +} + +{ + name: "structure: two output nodes are both reachable, the first reached ends the walk", + graph: { + nodes: [ + {expression: "calc", fields: {y: "x + 1"}}, + {output: "out1"}, + {output: "out2", id: "out2"}, + ], + edges: ["input -> calc -> out1", "calc -> out2"], + }, + cases: [ + [{x: 1}, {y: 2}], + [{x: 5}, {y: 6}], + ], +} + +{ + name: "structure: an output node that is not connected does not make the graph invalid", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "c", name: "calc", type: "expressionNode", content: {expressions: [{id: "x", key: "y", value: "1"}]}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [{id: "e", sourceId: "i", targetId: "c"}], + }, + }, + cases: [ + [{}, {y: 1}], + [{a: 1}, {y: 1}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Cycles. +{ + name: "structure: a cycle between two nodes is invalid", + graph: { + nodes: [ + {expression: "a", fields: {x: "1"}}, + {expression: "b", fields: {y: "2"}}, + ], + edges: ["input -> a -> b -> output", "b -> a"], + }, + cases: [ + [{}, "!error: cyclicGraph"], + [{x: 1}, "!error: InvalidGraph"], + ], +} + +{ + name: "structure: a self loop is a cycle", + graph: { + nodes: [{expression: "a", fields: {x: "1"}}], + edges: ["input -> a -> output", "a -> a"], + }, + cases: [ + [{}, "!error: cyclicGraph"], + ], +} + +{ + name: "structure: a cycle in an unreachable part of the graph is still invalid", + graph: { + nodes: [ + {expression: "a", fields: {x: "1"}}, + {expression: "b", fields: {y: "2"}}, + {expression: "c", fields: {z: "3"}}, + ], + edges: ["input -> a -> output", "b -> c -> b"], + }, + cases: [ + [{}, "!error: cyclicGraph"], + ], +} + +{ + name: "structure: a cycle through the output node back to the input is invalid", + graph: { + nodes: [{expression: "a", fields: {x: "1"}}], + edges: ["input -> a -> output -> input"], + }, + cases: [ + [{}, "!error: cyclicGraph"], + ], +} + +{ + name: "structure: a cycle behind a switch branch is invalid even when the branch is not taken", + graph: { + nodes: [ + {switch: "s", when: ["flag", ""]}, + {expression: "a", fields: {x: "1"}}, + {expression: "b", fields: {y: "2"}}, + {expression: "c", fields: {z: "3"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> c -> b", "c -> output"], + }, + cases: [ + [{flag: true}, "!error: cyclicGraph"], + [{flag: false}, "!error: cyclicGraph"], + ], +} + +{ + name: "structure: a diamond is not a cycle", + graph: { + nodes: [ + {expression: "a", fields: {x: "v + 1"}}, + {expression: "b", fields: {y: "v + 2"}}, + {expression: "c", passThrough: true, fields: {z: "x + y"}}, + ], + edges: ["input -> a -> c -> output", "input -> b -> c"], + }, + cases: [ + [{v: 1}, {x: 2, y: 3, z: 5}], + [{v: 10}, {x: 11, y: 12, z: 23}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Edges naming unknown nodes. +{ + name: "structure: an edge to an unknown target is a missing node", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [{id: "e1", sourceId: "i", targetId: "o"}, {id: "e2", sourceId: "i", targetId: "ghost"}], + }, + }, + cases: [ + [{}, "!error: missingNode"], + [{a: 1}, "!error: ghost"], + ], +} + +{ + name: "structure: an edge from an unknown source is a missing node", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [{id: "e1", sourceId: "i", targetId: "o"}, {id: "e2", sourceId: "phantom", targetId: "o"}], + }, + }, + cases: [ + [{}, "!error: missingNode"], + [{}, "!error: phantom"], + ], +} + +{ + name: "structure: edges match node ids, not node names", + graph: { + raw: { + nodes: [ + {id: "n1", name: "request", type: "inputNode", content: {}}, + {id: "n2", name: "response", type: "outputNode", content: {}}, + ], + edges: [{id: "e1", sourceId: "request", targetId: "response"}], + }, + }, + cases: [ + [{}, "!error: missingNode"], + ], +} + +{ + name: "structure: a switch handle naming an unknown statement just never fires", + graph: { + raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {}}, + {id: "s", name: "s", type: "switchNode", content: {hitPolicy: "first", statements: [{id: "yes", condition: "flag"}, {id: "no", condition: ""}]}}, + {id: "a", name: "a", type: "expressionNode", content: {expressions: [{id: "x", key: "path", value: "'a'"}]}}, + {id: "b", name: "b", type: "expressionNode", content: {expressions: [{id: "x", key: "path", value: "'b'"}]}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [ + {id: "e1", sourceId: "i", targetId: "s"}, + {id: "e2", sourceId: "s", targetId: "a", sourceHandle: "yes"}, + {id: "e3", sourceId: "s", targetId: "b", sourceHandle: "stale"}, + {id: "e4", sourceId: "a", targetId: "o"}, + {id: "e5", sourceId: "b", targetId: "o"}, + ], + }, + }, + cases: [ + [{flag: true}, {path: "a"}], + [{flag: false}, {}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Unreachable and disconnected nodes. +{ + name: "unreachable: a node with no incoming edge never runs", + graph: { + nodes: [ + {expression: "calc", fields: {y: "1"}}, + {custom: "boom", kind: "fail", config: {message: "unreachable ran"}}, + ], + edges: ["input -> calc -> output"], + }, + cases: [ + [{}, {y: 1}], + [{a: 1}, {y: 1}], + ], +} + +{ + name: "unreachable: a node feeding a reachable node runs with an empty input", + graph: { + nodes: [ + {expression: "calc", fields: {y: "v"}}, + {expression: "orphan", fields: {o: "v ?? 'none'"}}, + {expression: "join", passThrough: true, fields: {}}, + ], + edges: ["input -> calc -> join -> output", "orphan -> join"], + }, + cases: [ + [{v: 1}, {y: 1, o: "none"}], + [{v: "x"}, {y: "x", o: "none"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Expression node errors. +{ + name: "expression errors: a syntax error fails the node", + graph: { + nodes: [{expression: "calc", fields: {ok: "1", bad: "1 +"}}], + }, + cases: [ + [{}, "!error: NodeError"], + [{a: 1}, "!error: \"nodeId\":\"calc\""], + ], +} + +{ + name: "expression errors: a runtime type error fails the node", + graph: { + nodes: [{expression: "calc", fields: {total: "price * qty"}}], + }, + cases: [ + [{price: 2, qty: 3}, {total: 6}], + [{price: "2", qty: 3}, "!error: NodeError"], + [{price: 2}, "!error: NodeError"], + [{}, "!error: Failed to evaluate expression"], + ], +} + +{ + name: "expression errors: the error names the failing expression", + graph: { + nodes: [{expression: "calc", fields: {a: "x + 1", b: "upper(x)"}}], + }, + cases: [ + [{x: 1}, "!error: upper(x)"], + [{x: "s"}, "!error: x + 1"], + ], +} + +{ + name: "expression errors: an unknown function fails the node", + graph: { + nodes: [{expression: "calc", fields: {a: "frobnicate(1)"}}], + }, + cases: [ + [{}, "!error: NodeError"], + ], +} + +{ + name: "expression errors: an empty key or empty value is skipped", + graph: { + nodes: [{expression: "calc", fields: [["", "1 +"], ["a", ""], ["b", "2"]]}], + }, + cases: [ + [{}, {b: 2}], + [{a: 1}, {b: 2}], + ], +} + +{ + name: "expression errors: a failure after earlier fields still fails the whole node", + graph: { + nodes: [ + {expression: "first", passThrough: true, fields: {a: "1"}}, + {expression: "second", fields: {b: "missing.deep + 1"}}, + ], + edges: ["input -> first -> second -> output"], + }, + cases: [ + [{}, "!error: \"nodeId\":\"second\""], + [{missing: {deep: 1}}, {b: 2}], + ], +} + +{ + name: "expression errors: a failure in a parallel branch fails the graph", + graph: { + nodes: [ + {expression: "good", fields: {a: "1"}}, + {expression: "bad", fields: {b: "x.y.z * 2"}}, + ], + edges: ["input -> good -> output", "input -> bad -> output"], + }, + cases: [ + [{}, "!error: \"nodeId\":\"bad\""], + [{x: {y: {z: 2}}}, {a: 1, b: 4}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Decision table errors. A cell that fails to evaluate makes its row not match; the table +// itself never errors on a cell. +{ + name: "table errors: an input cell with a syntax error never matches", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["r"], rules: [ + ["> > 1", "'broken'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{x: 5}, {r: "fallback"}], + [{x: 0}, {r: "fallback"}], + [{}, {r: "fallback"}], + ], +} + +{ + name: "table errors: an output cell that fails to evaluate skips the row", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["r"], rules: [ + ["> 1", "x.y.z + 1"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{x: 5}, {r: "fallback"}], + [{x: 0}, {r: "fallback"}], + ], +} + +{ + name: "table errors: a failing output cell in collect mode drops only that row", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["r"], rules: [ + ["> 0", "'positive'"], + ["> 1", "unknownFn(x)"], + ["> 2", "'big'"], + ]}, + ], + }, + cases: [ + [{x: 5}, [{r: "positive"}, {r: "big"}]], + [{x: 1}, [{r: "positive"}]], + [{x: 0}, []], + ], +} + +{ + name: "table errors: an input expression that errors on the value makes the cell false", + graph: { + nodes: [ + {table: "t", inputs: ["amount"], outputs: ["r"], rules: [ + ["> 100", "'large'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{amount: 500}, {r: "large"}], + [{amount: "500"}, {r: "other"}], + [{amount: null}, {r: "other"}], + [{amount: [1]}, {r: "other"}], + ], +} + +{ + name: "table errors: an input field with a syntax error never matches a non-empty cell", + graph: { + nodes: [ + {table: "t", inputs: ["a +"], outputs: ["r"], rules: [ + ["1", "'one'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{a: 1}, {r: "any"}], + [{}, {r: "any"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Switch errors. +{ + name: "switch errors: a failing condition is false, not an error", + graph: { + nodes: [ + {switch: "s", when: ["x.y.z > 1", ""]}, + {expression: "a", fields: {path: "'a'"}}, + {expression: "b", fields: {path: "'b'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{x: {y: {z: 5}}}, {path: "a"}], + [{}, {path: "b"}], + [{x: "str"}, {path: "b"}], + ], +} + +{ + name: "switch errors: a condition with a syntax error is false", + graph: { + nodes: [ + {switch: "s", when: ["(((", ""]}, + {expression: "a", fields: {path: "'a'"}}, + {expression: "b", fields: {path: "'b'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{}, {path: "b"}], + [{x: 1}, {path: "b"}], + ], +} + +{ + name: "switch errors: a non-boolean condition is false", + graph: { + nodes: [ + {switch: "s", when: ["x", ""]}, + {expression: "a", fields: {path: "'a'"}}, + {expression: "b", fields: {path: "'b'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{x: true}, {path: "a"}], + [{x: 1}, {path: "b"}], + [{x: "true"}, {path: "b"}], + [{x: null}, {path: "b"}], + [{x: false}, {path: "b"}], + ], +} + +{ + name: "switch errors: an error inside the untaken branch never surfaces", + graph: { + nodes: [ + {switch: "s", when: ["safe", ""]}, + {expression: "ok", fields: {path: "'ok'"}}, + {expression: "bad", fields: {path: "1 + 'x' * 2"}}, + ], + edges: ["input -> s", "s:0 -> ok -> output", "s:1 -> bad -> output"], + }, + cases: [ + [{safe: true}, {path: "ok"}], + [{safe: false}, "!error: \"nodeId\":\"bad\""], + [{}, "!error: NodeError"], + ], +} + +{ + name: "switch errors: a failing custom node in the untaken branch never runs", + graph: { + nodes: [ + {switch: "s", when: ["mode == 'safe'", "mode == 'fail'"]}, + {expression: "ok", fields: {path: "'ok'"}}, + {custom: "boom", kind: "fail", config: {message: "branch failed"}}, + ], + edges: ["input -> s", "s:0 -> ok -> output", "s:1 -> boom -> output"], + }, + cases: [ + [{mode: "safe"}, {path: "ok"}], + [{mode: "fail"}, "!error: branch failed"], + [{mode: "other"}, {}], + ], +} + +{ + name: "switch errors: collect mode runs every matching branch, so any failure surfaces", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["x > 0", "x > 10", ""]}, + {expression: "small", fields: {small: "true"}}, + {expression: "big", fields: {big: "x / zero"}}, + {expression: "always", fields: {always: "true"}}, + ], + edges: ["input -> s", "s:0 -> small -> output", "s:1 -> big -> output", "s:2 -> always -> output"], + }, + cases: [ + [{x: 5}, {small: true, always: true}], + [{x: 50, zero: 1}, {small: true, big: 50, always: true}], + [{x: 50, zero: 0}, {small: true, always: true}], + [{x: 50, zero: "0"}, "!error: \"nodeId\":\"big\""], + [{x: 50}, "!error: NodeError"], + [{x: -1}, {always: true}], + ], +} + +{ + name: "switch errors: no matching statement and no default produces an empty result", + graph: { + nodes: [ + {switch: "s", when: ["x == 1", "x == 2"]}, + {expression: "a", fields: {path: "'a'"}}, + {expression: "b", fields: {path: "'b'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{x: 1}, {path: "a"}], + [{x: 2}, {path: "b"}], + [{x: 3}, {}], + [{}, {}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Transform attribute errors. +{ + name: "transform errors: loop mode on a non-array input field fails", + graph: { + nodes: [{expression: "each", inputField: "items", executionMode: "loop", fields: {d: "v * 2"}}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, [{d: 2}, {d: 4}]], + [{items: []}, []], + [{items: {v: 1}}, "!error: Expected an array"], + [{items: "x"}, "!error: NodeError"], + [{}, "!error: NodeError"], + ], +} + +{ + name: "transform errors: an input field with a syntax error fails", + graph: { + nodes: [{expression: "each", inputField: "items[", fields: {d: "1"}}], + }, + cases: [ + [{items: []}, "!error: NodeError"], + [{}, "!error: Failed to evaluate expression"], + ], +} + +{ + name: "transform errors: one failing item fails the whole loop", + graph: { + nodes: [{expression: "each", inputField: "items", executionMode: "loop", outputPath: "out", fields: {d: "v * 2"}}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {out: [{d: 2}, {d: 4}]}], + [{items: [{v: 1}, {v: "x"}]}, "!error: NodeError"], + [{items: [{v: 1}, {}]}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Custom and function node errors. +{ + name: "custom errors: a failing custom node fails the graph with its message", + graph: { + nodes: [{custom: "c", kind: "fail", config: {message: "service unavailable"}}], + }, + cases: [ + [{}, "!error: service unavailable"], + [{a: 1}, "!error: \"nodeId\":\"c\""], + ], +} + +{ + name: "custom errors: an unknown custom kind fails", + graph: { + nodes: [{custom: "c", kind: "nope", config: {}}], + }, + cases: [ + [{}, "!error: NodeError"], + ], +} + +{ + name: "function errors: a thrown error fails the graph", + graph: { + nodes: [{function: "f", source: """ +export const handler = async (input) => { + if (input.fail) { + throw new Error('rejected by function'); + } + return { ok: true }; +}; +"""}], + }, + cases: [ + [{fail: false}, {ok: true}], + [{fail: true}, "!error: rejected by function"], + [{}, {ok: true}], + ], +} + +{ + name: "function errors: a syntax error in the source fails the graph", + graph: { + nodes: [{function: "f", source: "export const handler = async (input) => { return {"}], + }, + cases: [ + [{}, "!error: NodeError"], + ], +} + +{ + name: "function errors: a source without a handler export fails", + graph: { + nodes: [{function: "f", source: "export const other = () => 1;"}], + }, + cases: [ + [{}, "!error: NodeError"], + ], +} + +{ + name: "function errors: a reference error at runtime fails", + graph: { + nodes: [{function: "f", source: """ +export const handler = async (input) => { + return { v: input.a.b.c }; +}; +"""}], + }, + cases: [ + [{a: {b: {c: 1}}}, {v: 1}], + [{a: {}}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Sub-decision errors. +{ + name: "decision errors: an unknown key is a loader error", + graph: { + nodes: [{decision: "call", key: "does-not-exist"}], + }, + cases: [ + [{}, "!error: NodeError"], + [{a: 1}, "!error: \"nodeId\":\"call\""], + ], +} + +{ + name: "decision errors: a failing node inside the child fails the parent", + decisions: { + child: {nodes: [{expression: "calc", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 2}, {y: 4}], + [{x: "two"}, "!error: \"nodeId\":\"call\""], + [{}, "!error: NodeError"], + ], +} + +{ + name: "decision errors: an invalid child graph fails the parent", + decisions: { + child: {raw: {nodes: [], edges: []}}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, "!error: NodeError"], + ], +} + +{ + name: "decision errors: a cyclic child graph fails the parent", + decisions: { + child: { + nodes: [{expression: "a", fields: {x: "1"}}], + edges: ["input -> a -> output", "a -> a"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, "!error: NodeError"], + ], +} + +{ + name: "decision errors: a self-referencing decision hits the depth limit", + decisions: { + loop: {nodes: [{decision: "again", key: "loop"}]}, + }, + graph: { + nodes: [{decision: "call", key: "loop"}], + }, + cases: [ + [{}, "!error: Depth limit exceeded"], + [{a: 1}, "!error: NodeError"], + ], +} + +{ + name: "decision errors: nesting within the depth limit is fine", + decisions: { + d1: {nodes: [{decision: "next", key: "d2"}]}, + d2: {nodes: [{decision: "next", key: "d3"}]}, + d3: {nodes: [{expression: "leaf", fields: {deep: "v + 3"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "d1"}], + }, + cases: [ + [{v: 0}, {deep: 3}], + [{v: 1}, {deep: 4}], + ], +} + +{ + name: "decision errors: a child failing only for some loop items fails the loop", + decisions: { + child: {nodes: [{expression: "calc", fields: {r: "10 / d"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "rows", executionMode: "loop", outputPath: "out"}], + }, + cases: [ + [{rows: [{d: 2}, {d: 5}]}, {out: [{r: 5}, {r: 2}]}], + [{rows: [{d: 2}, {d: "x"}]}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Errors versus early termination: the walk ends at the output node. +{ + name: "termination: a node reached only after the output node never runs", + graph: { + nodes: [ + {expression: "calc", fields: {y: "1"}}, + {custom: "boom", kind: "fail", config: {message: "after output"}}, + ], + edges: ["input -> calc -> output -> boom"], + }, + cases: [ + [{}, {}, "question: the walk stops at the output node, but the result merges only nodes without outgoing edges, so an output node with an outgoing edge yields an empty result"], + [{a: 1}, {}, "question: same as above, the output node's data is discarded"], + ], +} diff --git a/core/engine/tests/spec/graph/21-values.json5 b/core/engine/tests/spec/graph/21-values.json5 new file mode 100644 index 00000000..0fb18e46 --- /dev/null +++ b/core/engine/tests/spec/graph/21-values.json5 @@ -0,0 +1,679 @@ +// Value semantics across nodes. Numbers are exact decimals end to end: a value read from the +// request, computed by an expression, emitted by a table cell or passed into a sub-decision keeps +// its precision. Results are assembled by merging node outputs, so a null-valued top-level key never +// appears in a graph result (nested nulls and nulls inside arrays are kept). Evaluation time is +// fixed at 2025-03-20T10:15:30Z. + +// --------------------------------------------------------------------------------------------- +// Decimal precision through expressions. +{ + name: "decimals: classic binary-float traps are exact", + graph: { + nodes: [{expression: "calc", fields: {sum: "a + b", diff: "c - a", prod: "a * 3", third: "1 / 3 * 3"}}], + }, + cases: [ + [{a: 0.1, b: 0.2, c: 0.3}, {sum: 0.3, diff: 0.2, prod: 0.3, third: 0.9999999999999999999999999999}], + [{a: 1.1, b: 2.2, c: 3.3}, {sum: 3.3, diff: 2.2, prod: 3.3, third: 0.9999999999999999999999999999}], + [{a: 0.7, b: 0.1, c: 0.8}, {sum: 0.8, diff: 0.1, prod: 2.1, third: 0.9999999999999999999999999999}], + ], +} + +{ + name: "decimals: many fractional digits survive the request and the result", + graph: {}, + cases: [ + [{x: 0.1000000000000000000000000001}, {x: 0.1000000000000000000000000001}], + [{x: 3.1415926535897932384626433832}, {x: 3.1415926535897932384626433832}], + [{x: -0.0000000000000000000000000001}, {x: -0.0000000000000000000000000001}], + ], +} + +{ + name: "decimals: precision carries through chained expression nodes", + graph: { + nodes: [ + {expression: "net", passThrough: true, fields: {net: "price * qty"}}, + {expression: "tax", passThrough: true, fields: {tax: "net * rate"}}, + {expression: "total", fields: {total: "net + tax", rounded: "round(net + tax, 2)"}}, + ], + }, + cases: [ + [{price: 19.99, qty: 3, rate: 0.19}, {total: 71.3643, rounded: 71.36}], + [{price: 0.01, qty: 7, rate: 0.075}, {total: 0.07525, rounded: 0.08}], + [{price: 1000000.005, qty: 1, rate: 0}, {total: 1000000.005, rounded: 1000000.01}], + ], +} + +{ + name: "decimals: rounding helpers", + graph: { + nodes: [{expression: "calc", fields: {r: "round(x)", r2: "round(x, 2)", f: "floor(x)", c: "ceil(x)", t: "trunc(x)"}}], + }, + cases: [ + [{x: 2.5}, {r: 3, r2: 2.5, f: 2, c: 3, t: 2}], + [{x: -2.5}, {r: -3, r2: -2.5, f: -3, c: -2, t: -2}], + [{x: 1.005}, {r: 1, r2: 1.01, f: 1, c: 2, t: 1}], + [{x: 0}, {r: 0, r2: 0, f: 0, c: 0, t: 0}], + ], +} + +{ + name: "decimals: scale is kept when a value is passed through", + graph: { + nodes: [{expression: "calc", fields: {s: "string(x)", y: "x"}}], + }, + cases: [ + [{x: 1.10}, {s: "1.10", y: 1.1}], + [{x: 2.000}, {s: "2.000", y: 2}], + [{x: 100}, {s: "100", y: 100}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Decimal precision through decision tables. +{ + name: "decimals: table output cells are exact", + graph: { + nodes: [ + {table: "rates", inputs: ["band"], outputs: ["rate", "fee"], rules: [ + ["'a'", "0.015", "0.1 + 0.2"], + ["'b'", "0.0275", "1.23456789012345678901234567"], + ["", "0", "0"], + ]}, + ], + }, + cases: [ + [{band: "a"}, {rate: 0.015, fee: 0.3}], + [{band: "b"}, {rate: 0.0275, fee: 1.23456789012345678901234567}], + [{band: "z"}, {rate: 0, fee: 0}], + ], +} + +{ + name: "decimals: table input intervals compare exactly at boundaries", + graph: { + nodes: [ + {table: "bands", inputs: ["score"], outputs: ["band"], rules: [ + ["< 0.3", "'low'"], + ["[0.3..0.7)", "'mid'"], + [">= 0.7", "'high'"], + ]}, + ], + }, + cases: [ + [{score: 0.29999999999999999999}, {band: "low"}], + [{score: 0.3}, {band: "mid"}], + [{score: 0.30}, {band: "mid"}], + [{score: 0.69999999999999999999}, {band: "mid"}], + [{score: 0.7}, {band: "high"}], + [{score: 1}, {band: "high"}], + ], +} + +{ + name: "decimals: a table equality cell matches regardless of scale", + graph: { + nodes: [ + {table: "t", inputs: ["amount"], outputs: ["hit"], rules: [ + ["1.5", "true"], + ["", "false"], + ]}, + ], + }, + cases: [ + [{amount: 1.5}, {hit: true}], + [{amount: 1.50}, {hit: true}], + [{amount: 1.500000}, {hit: true}], + [{amount: 1.5000001}, {hit: false}], + [{amount: "1.5"}, {hit: false}], + ], +} + +{ + name: "decimals: table output computed from input keeps precision", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["fee"], rules: [ + ["'pct'", "amount * 0.035"], + ["'flat'", "2.50"], + ]}, + ], + }, + cases: [ + [{kind: "pct", amount: 99.99}, {fee: 3.49965}], + [{kind: "pct", amount: 0.01}, {fee: 0.00035}], + [{kind: "flat", amount: 10}, {fee: 2.5}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Large and small magnitudes. +{ + name: "magnitudes: large integers stay exact", + graph: { + nodes: [{expression: "calc", fields: {plus: "x + 1", times: "x * 10", same: "x"}}], + }, + cases: [ + [{x: 9007199254740993}, {plus: 9007199254740994, times: 90071992547409930, same: 9007199254740993}], + [{x: 1000000000000000000000}, {plus: 1000000000000000000001, times: 10000000000000000000000, same: 1000000000000000000000}], + [{x: -9223372036854775808}, {plus: -9223372036854775807, times: -92233720368547758080, same: -9223372036854775808}], + ], +} + +{ + name: "magnitudes: tiny values stay exact", + graph: { + nodes: [{expression: "calc", fields: {double: "x * 2", isPos: "x > 0"}}], + }, + cases: [ + [{x: 0.000000000000000000000000001}, {double: 0.000000000000000000000000002, isPos: true}], + [{x: 0.0000001}, {double: 0.0000002, isPos: true}], + [{x: -0.0000001}, {double: -0.0000002, isPos: false}], + ], +} + +{ + name: "magnitudes: overflow in arithmetic is an error", + graph: { + nodes: [{expression: "calc", fields: {big: "x * x"}}], + }, + cases: [ + [{x: 1000000}, {big: 1000000000000}], + [{x: 10000000000000000000000000000}, "!error: NodeError"], + ], +} + +{ + name: "magnitudes: negative zero and zero", + graph: { + nodes: [{expression: "calc", fields: {eq: "x == 0", neg: "x < 0", v: "x"}}], + }, + cases: [ + [{x: 0}, {eq: true, neg: false, v: 0}], + [{x: -0}, {eq: true, neg: false, v: 0}], + [{x: 0.000}, {eq: true, neg: false, v: 0}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Strings. +{ + name: "strings: unicode passes through unchanged", + graph: {}, + cases: [ + [{s: "Zürich"}, {s: "Zürich"}], + [{s: "東京"}, {s: "東京"}], + [{s: "emoji 🎉 ok"}, {s: "emoji 🎉 ok"}], + [{s: "مرحبا"}, {s: "مرحبا"}], + [{"ключ": "значение"}, {"ключ": "значение"}], + ], +} + +{ + name: "strings: unicode through expressions", + graph: { + nodes: [{expression: "calc", fields: {up: "upper(s)", n: "len(s)", greet: "'hi ' + s", has: "contains(s, 'ü')"}}], + }, + cases: [ + [{s: "zürich"}, {up: "ZÜRICH", n: 6, greet: "hi zürich", has: true}, "bug: len counts UTF-8 bytes instead of characters"], + [{s: "東京"}, {up: "東京", n: 2, greet: "hi 東京", has: false}, "bug: len counts UTF-8 bytes instead of characters"], + [{s: ""}, {up: "", n: 0, greet: "hi ", has: false}], + ], +} + +{ + name: "strings: unicode in table cells", + graph: { + nodes: [ + {table: "t", inputs: ["city"], outputs: ["country"], rules: [ + ["'Zürich'", "'Schweiz'"], + ["'東京'", "'日本'"], + ["'São Paulo', 'Rio'", "'Brasil'"], + ["", "'?'"], + ]}, + ], + }, + cases: [ + [{city: "Zürich"}, {country: "Schweiz"}], + [{city: "東京"}, {country: "日本"}], + [{city: "São Paulo"}, {country: "Brasil"}], + [{city: "Rio"}, {country: "Brasil"}], + [{city: "Zurich"}, {country: "?"}], + ], +} + +{ + name: "strings: escapes and whitespace are preserved", + graph: { + nodes: [{expression: "calc", fields: {copy: "s", trimmed: "trim(s)", n: "len(s)"}}], + }, + cases: [ + [{s: " padded "}, {copy: " padded ", trimmed: "padded", n: 10}], + [{s: "line1\nline2"}, {copy: "line1\nline2", trimmed: "line1\nline2", n: 11}], + [{s: "tab\there"}, {copy: "tab\there", trimmed: "tab\there", n: 8}], + [{s: "quote \" and \\ back"}, {copy: "quote \" and \\ back", trimmed: "quote \" and \\ back", n: 18}], + ], +} + +{ + name: "strings: a numeric-looking string is not a number", + graph: { + nodes: [{expression: "calc", fields: {isNum: "type(x) == 'number'", parsed: "number(x) + 1"}}], + }, + cases: [ + [{x: "41"}, {isNum: false, parsed: 42}], + [{x: "0.10"}, {isNum: false, parsed: 1.1}], + [{x: 41}, {isNum: true, parsed: 42}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Booleans. +{ + name: "booleans: pass through and compute", + graph: { + nodes: [{expression: "calc", fields: {notA: "not a", both: "a and b", either: "a or b", copy: "a"}}], + }, + cases: [ + [{a: true, b: true}, {notA: false, both: true, either: true, copy: true}], + [{a: true, b: false}, {notA: false, both: false, either: true, copy: true}], + [{a: false, b: false}, {notA: true, both: false, either: false, copy: false}], + ], +} + +{ + name: "booleans: false is kept in the result, unlike null", + graph: { + nodes: [{expression: "calc", fields: {f: "false", t: "true", n: "null", z: "0", e: "''"}}], + }, + cases: [ + [{}, {f: false, t: true, z: 0, e: ""}], + [{f: true}, {f: false, t: true, z: 0, e: ""}], + ], +} + +{ + name: "booleans: table cells match booleans strictly", + graph: { + nodes: [ + {table: "t", inputs: ["flag"], outputs: ["r"], rules: [ + ["true", "'yes'"], + ["false", "'no'"], + ["", "'unknown'"], + ]}, + ], + }, + cases: [ + [{flag: true}, {r: "yes"}], + [{flag: false}, {r: "no"}], + [{flag: "true"}, {r: "unknown"}], + [{flag: 1}, {r: "unknown"}], + [{flag: null}, {r: "unknown"}], + [{}, {r: "unknown"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dates. +{ + name: "dates: d() values render as ISO text in the result", + graph: { + nodes: [{expression: "calc", fields: {a: "d('2024-01-01')", b: "d('2024-06-15T08:30:00Z')", c: "d('2024-06-15T08:30:00+02:00')"}}], + }, + cases: [ + [{}, {a: "2024-01-01T00:00:00Z", b: "2024-06-15T08:30:00Z", c: "2024-06-15T06:30:00Z"}], + ], +} + +{ + name: "dates: now is fixed in the suite", + graph: { + nodes: [{expression: "calc", fields: {now: "d()", nowLegacy: "date('now')", year: "d().year()", today: "d().isToday()"}}], + }, + cases: [ + [{}, {now: "2025-03-20T10:15:30Z", nowLegacy: 1742465730, year: 2025, today: true}], + ], +} + +{ + name: "dates: computed from request strings", + graph: { + nodes: [{expression: "calc", fields: { + age: "d().diff(d(dob), 'year')", + next: "d(start).add(1, 'month')", + weekday: "d(start).weekday()", + eom: "d(start).endOf('month')", + }}], + }, + cases: [ + [{dob: "1990-03-21", start: "2024-01-31"}, {age: 34, next: "2024-02-29T00:00:00Z", weekday: 3, eom: "2024-01-31T23:59:59Z"}], + [{dob: "1990-03-20", start: "2025-02-15"}, {age: 35, next: "2025-03-15T00:00:00Z", weekday: 6, eom: "2025-02-28T23:59:59Z"}], + ], +} + +{ + name: "dates: comparisons in table cells", + graph: { + nodes: [ + {table: "t", inputs: ["d(expires)"], outputs: ["status"], rules: [ + ["< d()", "'expired'"], + ["< d().add(30, 'd')", "'expiring'"], + ["", "'valid'"], + ]}, + ], + }, + cases: [ + [{expires: "2025-03-19"}, {status: "expired"}], + [{expires: "2025-03-20T10:15:29Z"}, {status: "expired"}], + [{expires: "2025-03-25"}, {status: "expiring"}], + [{expires: "2025-04-30"}, {status: "valid"}], + ], +} + +{ + name: "dates: a date flows between nodes as a date", + graph: { + nodes: [ + {expression: "make", fields: {due: "d(start).add(14, 'd')"}}, + {expression: "use", fields: {due: "due", late: "due < d()", month: "due.month()"}}, + ], + }, + cases: [ + [{start: "2025-03-01"}, {due: "2025-03-15T00:00:00Z", late: true, month: 3}], + [{start: "2025-03-10"}, {due: "2025-03-24T00:00:00Z", late: false, month: 3}], + [{start: "2024-12-25"}, {due: "2025-01-08T00:00:00Z", late: true, month: 1}], + ], +} + +{ + name: "dates: an invalid date string is an Invalid date value, not null", + graph: { + nodes: [{expression: "calc", fields: {when: "d(s)", ok: "d(s) != null"}}], + }, + cases: [ + [{s: "2024-01-01"}, {when: "2024-01-01T00:00:00Z", ok: true}], + [{s: "garbage"}, {when: "Invalid date", ok: true}], + ], +} + +{ + name: "dates: date input values keep their source text", + graph: {}, + cases: [ + [{at: date("2024-03-15")}, {at: "2024-03-15"}], + [{at: date("2024-03-15T10:30:00+02:00")}, {at: "2024-03-15T10:30:00+02:00"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Null versus missing keys in results. +{ + name: "null: a null-valued request key is dropped from a pass-through result", + graph: {}, + cases: [ + [{a: null, b: 1}, {b: 1}], + [{a: null}, {}], + [{a: {b: null, c: 2}}, {a: {b: null, c: 2}}, "question: only top-level null-valued keys are dropped, nested ones survive the merge"], + [{a: {b: {c: null}}}, {a: {b: {c: null}}}, "question: only top-level null-valued keys are dropped, nested ones survive the merge"], + ], +} + +{ + name: "null: an expression producing null leaves the key out", + graph: { + nodes: [{expression: "calc", fields: {x: "missing", y: "1", z: "null"}}], + }, + cases: [ + [{}, {y: 1}], + [{missing: 5}, {x: 5, y: 1}], + [{missing: null}, {y: 1}], + ], +} + +{ + name: "null: null inside arrays is kept", + graph: { + nodes: [{expression: "calc", fields: {list: "[1, null, 3]", objs: "[{a: null}, {a: 1}]"}}], + }, + cases: [ + [{}, {list: [1, null, 3], objs: [{a: null}, {a: 1}]}], + ], +} + +{ + name: "null: a null output removes a pass-through key of the same name", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: {secret: "null", extra: "1"}}], + }, + cases: [ + [{secret: "s", keep: 1}, {keep: 1, extra: 1}], + [{keep: 1}, {keep: 1, extra: 1}], + ], +} + +{ + name: "null: a later node can see a null written by an earlier field via $", + graph: { + nodes: [{expression: "calc", fields: {a: "null", b: "$.a == null", c: "a ?? 'default'"}}], + }, + cases: [ + [{}, {b: true, c: "default"}], + [{a: 5}, {b: true, c: 5}], + ], +} + +{ + name: "null: a table that matches no rule contributes nothing", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["r"], rules: [ + ["1", "'one'"], + ]}, + ], + }, + cases: [ + [{x: 1}, {r: "one"}], + [{x: 2}, {}], + [{}, {}], + ], +} + +{ + name: "null: a table output cell that is empty leaves the key out", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["a", "b"], rules: [ + ["1", "'a1'", ""], + ["2", "", "'b2'"], + ["", "null", "null"], + ]}, + ], + }, + cases: [ + [{x: 1}, {a: "a1"}], + [{x: 2}, {b: "b2"}], + [{x: 3}, {}], + ], +} + +{ + name: "null: null versus missing as seen by expressions", + graph: { + nodes: [{expression: "calc", fields: {isNull: "x == null", t: "type(x)", coalesce: "x ?? 'fallback'"}}], + }, + cases: [ + [{x: null}, {isNull: true, t: "null", coalesce: "fallback"}], + [{}, {isNull: true, t: "null", coalesce: "fallback"}], + [{x: 0}, {isNull: false, t: "number", coalesce: 0}], + [{x: ""}, {isNull: false, t: "string", coalesce: ""}], + [{x: false}, {isNull: false, t: "bool", coalesce: false}], + ], +} + +{ + name: "null: a null sub-decision output field is dropped", + decisions: { + child: {nodes: [{expression: "calc", fields: {a: "x", b: "2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 1}, {a: 1, b: 2}], + [{x: null}, {b: 2}], + [{}, {b: 2}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Empty objects and arrays in results. +{ + name: "empty: empty objects and arrays are kept", + graph: { + nodes: [{expression: "calc", fields: {o: "{}", a: "[]", nested: "{inner: {}}", list: "[[]]"}}], + }, + cases: [ + [{}, {o: {}, a: [], nested: {inner: {}}, list: [[]]}], + ], +} + +{ + name: "empty: empty request values pass through", + graph: {}, + cases: [ + [{o: {}, a: [], s: ""}, {o: {}, a: [], s: ""}], + [{deep: {x: {y: {}}}}, {deep: {x: {y: {}}}}], + ], +} + +{ + name: "empty: an expression node with no fields outputs an empty object", + graph: { + nodes: [{expression: "calc", fields: {}}], + }, + cases: [ + [{a: 1}, {}], + [{}, {}], + ], +} + +{ + name: "empty: a collect table with no hits yields an empty list", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["r"], rules: [ + ["> 10", "'big'"], + ]}, + ], + }, + cases: [ + [{x: 50}, [{r: "big"}]], + [{x: 1}, []], + ], +} + +{ + name: "empty: a collect table under an output path yields an empty list key", + graph: { + nodes: [ + {table: "t", hit: "collect", outputPath: "hits", inputs: ["x"], outputs: ["r"], rules: [ + ["> 10", "'big'"], + ]}, + ], + }, + cases: [ + [{x: 50}, {hits: [{r: "big"}]}], + [{x: 1}, {hits: []}], + ], +} + +{ + name: "empty: merging an empty object over a key does not clear it", + graph: { + nodes: [ + {expression: "a", fields: {cfg: "{x: 1}"}}, + {expression: "b", fields: {cfg: "{}"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {cfg: {x: 1}}], + ], +} + +{ + name: "empty: merging an empty array over a key replaces it", + graph: { + nodes: [ + {expression: "a", fields: {list: "[1, 2]"}}, + {expression: "b", fields: {list: "[]"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {list: [1, 2]}, "question: which of two parallel branches wins a conflicting key depends on the walk order; here the value of the first-listed branch survives"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Merging nested values. +{ + name: "merge: nested objects from parallel branches are deep-merged", + graph: { + nodes: [ + {expression: "a", fields: {"customer.name": "name"}}, + {expression: "b", fields: {"customer.tier": "'gold'", "customer.flags.vip": "true"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{name: "ann"}, {customer: {name: "ann", tier: "gold", flags: {vip: true}}}], + [{name: ""}, {customer: {name: "", tier: "gold", flags: {vip: true}}}], + [{}, {customer: {tier: "gold", flags: {vip: true}}}], + ], +} + +{ + name: "merge: dotted expression keys build nested objects", + graph: { + nodes: [{expression: "calc", fields: {"a.b.c": "1", "a.b.d": "2", "a.e": "'x'"}}], + }, + cases: [ + [{}, {a: {b: {c: 1, d: 2}, e: "x"}}], + ], +} + +{ + name: "merge: pass-through keeps request values the node does not overwrite", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: {"order.total": "order.qty * order.price"}}], + }, + cases: [ + [{order: {qty: 2, price: 1.25, id: "o1"}}, {order: {qty: 2, price: 1.25, id: "o1", total: 2.5}}], + [{order: {qty: 0, price: 9}, other: [1]}, {order: {qty: 0, price: 9, total: 0}, other: [1]}], + ], +} + +{ + name: "merge: arrays are replaced, never concatenated", + graph: { + nodes: [{expression: "calc", passThrough: true, fields: {tags: "['new']"}}], + }, + cases: [ + [{tags: ["a", "b"]}, {tags: ["new"]}], + [{}, {tags: ["new"]}], + ], +} + +// --------------------------------------------------------------------------------------------- +// The $root environment. +{ + name: "environment: $root holds the node input", + graph: { + nodes: [{expression: "calc", fields: {n: "len(keys($root))", hasA: "'a' in keys($root)"}}], + }, + cases: [ + {input: {a: 1, b: 2}, output: {n: 2, hasA: true}, note: "bug: $root also contains the internal $nodes key", engines: "walker and compiled single list $nodes in $root; batch and columnar do not"}, + {input: {}, output: {n: 0, hasA: false}, note: "bug: $root also contains the internal $nodes key", engines: "walker and compiled single list $nodes in $root; batch and columnar do not"}, + ], +} diff --git a/core/engine/tests/spec/graph/22-composite.json5 b/core/engine/tests/spec/graph/22-composite.json5 new file mode 100644 index 00000000..ee62c15b --- /dev/null +++ b/core/engine/tests/spec/graph/22-composite.json5 @@ -0,0 +1,611 @@ +// Realistic multi-node decisions mixing tables, switches, expressions, sub-decisions, loops and +// `$nodes`. Each suite is one business decision exercised across its main paths, boundaries and +// missing inputs. + +// --------------------------------------------------------------------------------------------- +// Pricing: base price by product, tiered discount, coupon, tax by country. +{ + name: "pricing: base, tier discount, coupon and tax", + graph: { + nodes: [ + {table: "base", passThrough: true, inputs: ["product"], outputs: ["unitPrice"], rules: [ + ["'basic'", "9.99"], + ["'pro'", "29.99"], + ["'enterprise'", "199"], + ]}, + {table: "tier", passThrough: true, inputs: ["qty"], outputs: ["discount"], rules: [ + ["< 10", "0"], + ["[10..49]", "0.05"], + ["[50..99]", "0.1"], + [">= 100", "0.15"], + ]}, + {expression: "subtotal", passThrough: true, fields: { + gross: "unitPrice * qty", + net: "round(unitPrice * qty * (1 - discount), 2)", + }}, + {table: "coupon", passThrough: true, inputs: ["coupon", "net"], outputs: ["couponOff"], rules: [ + ["'SAVE10'", ">= 50", "10"], + ["'HALF'", "", "round(net / 2, 2)"], + ["", "", "0"], + ]}, + {table: "tax", passThrough: true, inputs: ["country"], outputs: ["taxRate"], rules: [ + ["'DE'", "0.19"], + ["'FR'", "0.2"], + ["'US'", "0"], + ["", "0.1"], + ]}, + {expression: "total", fields: { + net: "net - couponOff", + tax: "round((net - couponOff) * taxRate, 2)", + total: "round((net - couponOff) * (1 + taxRate), 2)", + }}, + ], + }, + cases: [ + [{product: "basic", qty: 1, country: "US"}, {net: 9.99, tax: 0, total: 9.99}], + [{product: "basic", qty: 10, country: "DE"}, {net: 94.91, tax: 18.03, total: 112.94}], + [{product: "pro", qty: 50, country: "FR", coupon: "SAVE10"}, {net: 1339.55, tax: 267.91, total: 1607.46}], + [{product: "pro", qty: 2, country: "FR", coupon: "SAVE10"}, {net: 49.98, tax: 10, total: 59.98}], + [{product: "enterprise", qty: 100, country: "JP"}, {net: 16915, tax: 1691.5, total: 18606.5}], + [{product: "enterprise", qty: 1, country: "DE", coupon: "HALF"}, {net: 99.5, tax: 18.91, total: 118.41}], + [{product: "pro", qty: 49, country: "US", coupon: "NOPE"}, {net: 1396.03, tax: 0, total: 1396.03}], + [{product: "unknown", qty: 1, country: "US"}, "!error: \"nodeId\":\"subtotal\""], + [{product: "basic", qty: 0, country: "US"}, {net: 0, tax: 0, total: 0}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Loan eligibility: hard rejections first through a switch, then a scoring table. +{ + name: "eligibility: loan application with hard rules and a score band", + graph: { + nodes: [ + {switch: "gate", when: ["age < 18 or age > 75", "income <= 0", "bankrupt == true", ""]}, + {expression: "tooYoungOrOld", fields: {decision: "'reject'", reason: "'age'"}}, + {expression: "noIncome", fields: {decision: "'reject'", reason: "'income'"}}, + {expression: "bankrupt", fields: {decision: "'reject'", reason: "'bankruptcy'"}}, + {expression: "ratio", passThrough: true, fields: {dti: "round(debt / income, 4)"}}, + {table: "band", inputs: ["creditScore", "dti"], outputs: ["decision", "rate", "reason"], rules: [ + [">= 750", "< 0.35", "'approve'", "0.045", "'prime'"], + [">= 680", "< 0.4", "'approve'", "0.065", "'near prime'"], + [">= 620", "< 0.3", "'review'", "0.09", "'subprime'"], + ["", "", "'reject'", "", "'score'"], + ]}, + ], + edges: [ + "input -> gate", + "gate:0 -> tooYoungOrOld -> output", + "gate:1 -> noIncome -> output", + "gate:2 -> bankrupt -> output", + "gate:3 -> ratio -> band -> output", + ], + }, + cases: [ + [{age: 30, income: 5000, debt: 1000, creditScore: 780}, {decision: "approve", rate: 0.045, reason: "prime"}], + [{age: 30, income: 5000, debt: 1900, creditScore: 780}, {decision: "approve", rate: 0.065, reason: "near prime"}], + [{age: 30, income: 5000, debt: 2000, creditScore: 780}, {decision: "reject", reason: "score"}], + [{age: 45, income: 4000, debt: 1000, creditScore: 650}, {decision: "review", rate: 0.09, reason: "subprime"}], + [{age: 45, income: 4000, debt: 1200, creditScore: 650}, {decision: "reject", reason: "score"}], + [{age: 17, income: 5000, debt: 0, creditScore: 800}, {decision: "reject", reason: "age"}], + [{age: 76, income: 5000, debt: 0, creditScore: 800}, {decision: "reject", reason: "age"}], + [{age: 18, income: 0, debt: 0, creditScore: 800}, {decision: "reject", reason: "income"}], + [{age: 40, income: 3000, debt: 0, creditScore: 800, bankrupt: true}, {decision: "reject", reason: "bankruptcy"}], + [{age: 75, income: 3000, debt: 0, creditScore: 800, bankrupt: false}, {decision: "approve", rate: 0.045, reason: "prime"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Routing: support tickets routed by a collect switch to several queues at once. +{ + name: "routing: a ticket can land in several queues", + graph: { + nodes: [ + {switch: "route", hit: "collect", when: [ + "priority == 'urgent'", + "contains(lower(subject), 'invoice') or category == 'billing'", + "customer.tier == 'enterprise'", + "", + ]}, + {expression: "pager", fields: {"queues.pager": "true", "sla.hours": "1"}}, + {expression: "billing", fields: {"queues.billing": "true"}}, + {expression: "tam", fields: {"queues.tam": "customer.owner"}}, + {expression: "triage", fields: {"queues.triage": "true", "sla.default": "24"}}, + ], + edges: [ + "input -> route", + "route:0 -> pager -> output", + "route:1 -> billing -> output", + "route:2 -> tam -> output", + "route:3 -> triage -> output", + ], + }, + cases: [ + [{priority: "low", subject: "hello", customer: {tier: "free"}}, {queues: {triage: true}, sla: {default: 24}}], + [{priority: "urgent", subject: "down", customer: {tier: "free"}}, {queues: {pager: true, triage: true}, sla: {hours: 1, default: 24}}], + [{priority: "low", subject: "Invoice #42 wrong", customer: {tier: "free"}}, {queues: {billing: true, triage: true}, sla: {default: 24}}], + [{priority: "low", subject: "x", category: "billing", customer: {tier: "enterprise", owner: "kim"}}, {queues: {billing: true, tam: "kim", triage: true}, sla: {default: 24}}], + [{priority: "urgent", subject: "INVOICE", customer: {tier: "enterprise", owner: "lee"}}, {queues: {pager: true, billing: true, tam: "lee", triage: true}, sla: {hours: 1, default: 24}}], + [{priority: "urgent", subject: "x", customer: {tier: "enterprise"}}, {queues: {pager: true, triage: true}, sla: {hours: 1, default: 24}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Risk scoring: a collect table of signals summed into a score, then banded. +{ + name: "scoring: fraud signals summed and banded", + graph: { + nodes: [ + {table: "signals", hit: "collect", outputPath: "signals", passThrough: true, inputs: ["amount", "country", "accountAgeDays", "attempts"], outputs: ["code", "points"], rules: [ + ["> 1000", "", "", "", "'high_amount'", "30"], + ["> 5000", "", "", "", "'very_high_amount'", "20"], + ["", "$ not in ['US', 'CA', 'GB']", "", "", "'foreign'", "15"], + ["", "", "< 7", "", "'new_account'", "25"], + ["", "", "", ">= 3", "'retries'", "10 * (attempts - 2)"], + ]}, + {expression: "score", passThrough: true, fields: {score: "sum(map(signals, #.points))", codes: "map(signals, #.code)"}}, + {table: "band", passThrough: true, inputs: ["score"], outputs: ["action"], rules: [ + ["< 30", "'allow'"], + ["[30..59]", "'review'"], + [">= 60", "'block'"], + ]}, + {expression: "out", fields: {action: "action", score: "score", codes: "codes"}}, + ], + }, + cases: [ + [{amount: 50, country: "US", accountAgeDays: 400, attempts: 1}, {action: "allow", score: 0, codes: []}], + [{amount: 1500, country: "US", accountAgeDays: 400, attempts: 1}, {action: "review", score: 30, codes: ["high_amount"]}], + [{amount: 6000, country: "US", accountAgeDays: 400, attempts: 1}, {action: "review", score: 50, codes: ["high_amount", "very_high_amount"]}], + [{amount: 6000, country: "BR", accountAgeDays: 2, attempts: 5}, {action: "block", score: 120, codes: ["high_amount", "very_high_amount", "foreign", "new_account", "retries"]}], + [{amount: 10, country: "DE", accountAgeDays: 3, attempts: 1}, {action: "review", score: 40, codes: ["foreign", "new_account"]}], + [{amount: 10, country: "GB", accountAgeDays: 30, attempts: 3}, {action: "allow", score: 10, codes: ["retries"]}], + [{amount: 1000, country: "CA", accountAgeDays: 7, attempts: 2}, {action: "allow", score: 0, codes: []}], + [{amount: 1000.01, country: "FR", accountAgeDays: 6, attempts: 4}, {action: "block", score: 90, codes: ["high_amount", "foreign", "new_account", "retries"]}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Insurance premium: a sub-decision computes a risk factor per driver in a loop. +{ + name: "insurance: per-driver factors from a sub-decision loop", + decisions: { + driver: {nodes: [ + {table: "ageFactor", passThrough: true, inputs: ["age"], outputs: ["ageFactor"], rules: [ + ["< 25", "1.8"], + ["[25..64]", "1"], + [">= 65", "1.3"], + ]}, + {table: "claimsFactor", passThrough: true, inputs: ["claims"], outputs: ["claimsFactor"], rules: [ + ["0", "0.9"], + ["1", "1.2"], + ["", "1.6"], + ]}, + {expression: "factor", fields: {name: "name", factor: "ageFactor * claimsFactor"}}, + ]}, + }, + graph: { + nodes: [ + {decision: "drivers", key: "driver", inputField: "drivers", executionMode: "loop", outputPath: "factors", passThrough: true}, + {expression: "premium", fields: { + worst: "max(map(factors, #.factor))", + premium: "round(base * max(map(factors, #.factor)), 2)", + names: "map(factors, #.name)", + }}, + ], + }, + cases: [ + [{base: 500, drivers: [{name: "a", age: 40, claims: 0}]}, {worst: 0.9, premium: 450, names: ["a"]}], + [{base: 500, drivers: [{name: "a", age: 40, claims: 0}, {name: "b", age: 19, claims: 0}]}, {worst: 1.62, premium: 810, names: ["a", "b"]}], + [{base: 500, drivers: [{name: "a", age: 70, claims: 1}]}, {worst: 1.56, premium: 780, names: ["a"]}], + [{base: 499.99, drivers: [{name: "a", age: 22, claims: 3}, {name: "b", age: 30, claims: 1}]}, {worst: 2.88, premium: 1439.97, names: ["a", "b"]}], + [{base: 500, drivers: [{name: "a", age: 25, claims: 0}, {name: "b", age: 64, claims: 0}, {name: "c", age: 65, claims: 0}]}, {worst: 1.17, premium: 585, names: ["a", "b", "c"]}], + [{base: 500, drivers: []}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Shipping: carrier selection by weight and destination with a surcharge expression and $nodes. +{ + name: "shipping: carrier, cost and delivery date", + graph: { + nodes: [ + {expression: "parcel", passThrough: true, fields: { + volumetric: "round(l * w * h / 5000, 2)", + billable: "max([weight, round(l * w * h / 5000, 2)])", + }}, + {table: "carrier", passThrough: true, inputs: ["dest", "billable"], outputs: ["carrier", "cost", "days"], rules: [ + ["'domestic'", "<= 2", "'post'", "4.5", "3"], + ["'domestic'", "(2..30]", "'ground'", "8 + billable * 0.5", "2"], + ["'eu'", "<= 30", "'euroexpress'", "15 + billable * 1.2", "4"], + ["'world'", "<= 30", "'air'", "40 + billable * 3", "7"], + ["", "> 30", "'freight'", "120", "10"], + ]}, + {expression: "quote", fields: { + carrier: "carrier", + cost: "round(cost * (express ? 1.5 : 1), 2)", + eta: "d(shipDate).add(express ? days - 1 : days, 'd')", + billable: "$nodes.parcel.billable", + }}, + ], + }, + cases: [ + [{dest: "domestic", weight: 1, l: 10, w: 10, h: 10, shipDate: "2025-03-20", express: false}, {carrier: "post", cost: 4.5, eta: "2025-03-23T00:00:00Z", billable: 1}], + [{dest: "domestic", weight: 1, l: 50, w: 40, h: 30, shipDate: "2025-03-20", express: false}, {carrier: "ground", cost: 14, eta: "2025-03-22T00:00:00Z", billable: 12}], + [{dest: "eu", weight: 5.5, l: 20, w: 20, h: 20, shipDate: "2025-03-20", express: true}, {carrier: "euroexpress", cost: 32.4, eta: "2025-03-23T00:00:00Z", billable: 5.5}], + [{dest: "world", weight: 30, l: 10, w: 10, h: 10, shipDate: "2025-12-30", express: false}, {carrier: "air", cost: 130, eta: "2026-01-06T00:00:00Z", billable: 30}], + [{dest: "world", weight: 30.01, l: 10, w: 10, h: 10, shipDate: "2025-03-20", express: false}, {carrier: "freight", cost: 120, eta: "2025-03-30T00:00:00Z", billable: 30.01}], + [{dest: "domestic", weight: 2, l: 1, w: 1, h: 1, shipDate: "2024-02-27", express: true}, {carrier: "post", cost: 6.75, eta: "2024-02-29T00:00:00Z", billable: 2}], + [{dest: "moon", weight: 1, l: 1, w: 1, h: 1, shipDate: "2025-03-20", express: false}, "!error: \"nodeId\":\"quote\""], + ], +} + +// --------------------------------------------------------------------------------------------- +// Payroll: overtime, allowances and a progressive tax computed with a collect table. +{ + name: "payroll: overtime and progressive tax brackets", + graph: { + nodes: [ + {expression: "gross", passThrough: true, fields: { + regular: "min([hours, 40]) * rate", + overtime: "max([hours - 40, 0]) * rate * 1.5", + gross: "min([hours, 40]) * rate + max([hours - 40, 0]) * rate * 1.5 + (allowance ?? 0)", + }}, + {table: "brackets", hit: "collect", outputPath: "brackets", passThrough: true, inputs: ["gross"], outputs: ["from", "to", "pct"], rules: [ + ["> 0", "0", "500", "0"], + ["> 500", "500", "2000", "0.2"], + ["> 2000", "2000", "1000000", "0.4"], + ]}, + {expression: "net", fields: { + gross: "gross", + tax: "sum(map(brackets, (min([gross, #.to]) - #.from) * #.pct))", + net: "gross - sum(map(brackets, (min([gross, #.to]) - #.from) * #.pct))", + }}, + ], + }, + cases: [ + [{hours: 40, rate: 10}, {gross: 400, tax: 0, net: 400}], + [{hours: 40, rate: 12.5}, {gross: 500, tax: 0, net: 500}], + [{hours: 45, rate: 20}, {gross: 950, tax: 90, net: 860}], + [{hours: 50, rate: 40, allowance: 100}, {gross: 2300, tax: 420, net: 1880}], + [{hours: 0, rate: 30}, {gross: 0, tax: 0, net: 0}], + [{hours: 38.5, rate: 15.25, allowance: 12.75}, {gross: 599.875, tax: 19.975, net: 579.9}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Commission: plan chosen by a switch, each plan its own sub-decision. +{ + name: "commission: plans as sub-decisions behind a switch", + decisions: { + flat: {nodes: [{expression: "c", fields: {commission: "sales * 0.05", plan: "'flat'"}}]}, + tiered: {nodes: [ + {table: "t", inputs: ["sales"], outputs: ["commission", "plan"], rules: [ + ["< 10000", "sales * 0.03", "'tiered'"], + ["[10000..50000)", "300 + (sales - 10000) * 0.06", "'tiered'"], + [">= 50000", "2700 + (sales - 50000) * 0.1", "'tiered'"], + ]}, + ]}, + }, + graph: { + nodes: [ + {switch: "plan", when: ["plan == 'flat'", "plan == 'tiered'", ""]}, + {decision: "flatPlan", key: "flat"}, + {decision: "tieredPlan", key: "tiered"}, + {expression: "none", fields: {commission: "0", plan: "'none'"}}, + {expression: "cap", fields: {commission: "min([commission, 10000])", plan: "plan", capped: "commission > 10000"}}, + ], + edges: [ + "input -> plan", + "plan:0 -> flatPlan -> cap", + "plan:1 -> tieredPlan -> cap", + "plan:2 -> none -> cap", + "cap -> output", + ], + }, + cases: [ + [{plan: "flat", sales: 1000}, {commission: 50, plan: "flat", capped: false}], + [{plan: "flat", sales: 300000}, {commission: 10000, plan: "flat", capped: true}], + [{plan: "tiered", sales: 9999.99}, {commission: 299.9997, plan: "tiered", capped: false}], + [{plan: "tiered", sales: 10000}, {commission: 300, plan: "tiered", capped: false}], + [{plan: "tiered", sales: 50000}, {commission: 2700, plan: "tiered", capped: false}], + [{plan: "tiered", sales: 123456}, {commission: 10000, plan: "tiered", capped: true}], + [{plan: "other", sales: 5000}, {commission: 0, plan: "none", capped: false}], + [{sales: 5000}, {commission: 0, plan: "none", capped: false}], + ], +} + +// --------------------------------------------------------------------------------------------- +// KYC: document checks, age from a schema date, and a final verdict collecting reasons. +{ + name: "kyc: verdict with collected reasons", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["dob", "country"], properties: { + dob: {type: "string", format: "date"}, + country: {type: "string", minLength: 2, maxLength: 2}, + docs: {type: "array", items: {type: "string"}}, + }}}, + {expression: "facts", passThrough: true, fields: {age: "d().diff(dob, 'year')", docCount: "len(docs ?? [])"}}, + {table: "checks", hit: "collect", outputPath: "failures", passThrough: true, inputs: ["age", "country", "docCount", "pep"], outputs: ["reason"], rules: [ + ["< 18", "", "", "", "'underage'"], + ["", "'KP', 'IR', 'SY'", "", "", "'sanctioned_country'"], + ["", "", "< 2", "", "'insufficient_documents'"], + ["", "", "", "true", "'politically_exposed'"], + ]}, + {expression: "verdict", fields: { + age: "age", + status: "len(failures) == 0 ? 'pass' : (some(failures, #.reason == 'politically_exposed') and len(failures) == 1 ? 'manual' : 'fail')", + reasons: "map(failures, #.reason)", + }}, + ], + }, + cases: [ + [{dob: "1990-01-01", country: "DE", docs: ["passport", "utility"]}, {age: 35, status: "pass", reasons: []}], + [{dob: "2007-03-21", country: "DE", docs: ["passport", "utility"]}, {age: 17, status: "fail", reasons: ["underage"]}], + [{dob: "2007-03-20", country: "DE", docs: ["passport", "utility"]}, {age: 18, status: "pass", reasons: []}], + [{dob: "1980-05-05", country: "IR", docs: ["passport"]}, {age: 44, status: "fail", reasons: ["sanctioned_country", "insufficient_documents"]}], + [{dob: "1970-01-01", country: "GB", docs: ["passport", "id"], pep: true}, {age: 55, status: "manual", reasons: ["politically_exposed"]}], + [{dob: "1970-01-01", country: "GB", pep: true}, {age: 55, status: "fail", reasons: ["insufficient_documents", "politically_exposed"]}], + [{dob: "1970-01-01", country: "GBR"}, "!error: NodeError"], + [{country: "GB"}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Healthcare triage: vitals scored in parallel branches, joined by a final table. +{ + name: "triage: parallel vital scores joined into a level", + graph: { + nodes: [ + {table: "hr", inputs: ["heartRate"], outputs: ["hrScore"], rules: [ + ["< 40", "3"], ["[40..50]", "1"], ["(50..90]", "0"], ["(90..110]", "1"], ["(110..130]", "2"], ["> 130", "3"], + ]}, + {table: "temp", inputs: ["temperature"], outputs: ["tempScore"], rules: [ + ["< 35", "3"], ["[35..36]", "1"], ["(36..38]", "0"], ["(38..39]", "1"], ["> 39", "2"], + ]}, + {table: "spo2", inputs: ["spo2"], outputs: ["spo2Score"], rules: [ + ["<= 91", "3"], ["[92..93]", "2"], ["[94..95]", "1"], ["", "0"], + ]}, + {expression: "total", passThrough: true, fields: {score: "hrScore + tempScore + spo2Score", maxSingle: "max([hrScore, tempScore, spo2Score])"}}, + {table: "level", inputs: ["score", "maxSingle"], outputs: ["level", "respondWithinMin"], rules: [ + [">= 7", "", "'emergency'", "0"], + ["", "3", "'urgent'", "15"], + ["[5..6]", "", "'urgent'", "15"], + ["[1..4]", "", "'standard'", "60"], + ["", "", "'routine'", "240"], + ]}, + ], + edges: [ + "input -> hr -> total", + "input -> temp -> total", + "input -> spo2 -> total", + "total -> level -> output", + ], + }, + cases: [ + [{heartRate: 70, temperature: 37, spo2: 98}, {level: "routine", respondWithinMin: 240}], + [{heartRate: 95, temperature: 37, spo2: 98}, {level: "standard", respondWithinMin: 60}], + [{heartRate: 95, temperature: 38.5, spo2: 95}, {level: "standard", respondWithinMin: 60}], + [{heartRate: 120, temperature: 39.5, spo2: 95}, {level: "urgent", respondWithinMin: 15}], + [{heartRate: 35, temperature: 37, spo2: 99}, {level: "urgent", respondWithinMin: 15}], + [{heartRate: 140, temperature: 34, spo2: 90}, {level: "emergency", respondWithinMin: 0}], + [{heartRate: 50, temperature: 36, spo2: 93}, {level: "standard", respondWithinMin: 60}], + [{heartRate: 90, temperature: 38, spo2: 96}, {level: "routine", respondWithinMin: 240}], + ], +} + +// --------------------------------------------------------------------------------------------- +// E-commerce cart: line items in a loop, free-shipping threshold, loyalty points. +{ + name: "cart: line totals in a loop then cart-level rules", + graph: { + nodes: [ + {expression: "lines", inputField: "items", executionMode: "loop", outputPath: "lines", passThrough: true, fields: { + sku: "sku", + lineTotal: "round(price * qty * (1 - (lineDiscount ?? 0)), 2)", + }}, + {expression: "cart", passThrough: true, fields: { + subtotal: "sum(map(lines, #.lineTotal))", + itemCount: "sum(map(items, #.qty))", + }}, + {table: "shipping", passThrough: true, inputs: ["subtotal", "member"], outputs: ["shipping"], rules: [ + ["", "true", "0"], + [">= 50", "", "0"], + ["", "", "4.99"], + ]}, + {expression: "summary", fields: { + subtotal: "subtotal", + shipping: "shipping", + total: "subtotal + shipping", + points: "floor(subtotal) * (member ? 2 : 1)", + skus: "map(lines, #.sku)", + }}, + ], + }, + cases: [ + [{items: [{sku: "a", price: 10, qty: 2}], member: false}, {subtotal: 20, shipping: 4.99, total: 24.99, points: 20, skus: ["a"]}], + [{items: [{sku: "a", price: 10, qty: 2}, {sku: "b", price: 15.5, qty: 2}], member: false}, {subtotal: 51, shipping: 0, total: 51, points: 51, skus: ["a", "b"]}], + [{items: [{sku: "a", price: 49.99, qty: 1}], member: true}, {subtotal: 49.99, shipping: 0, total: 49.99, points: 98, skus: ["a"]}], + [{items: [{sku: "a", price: 100, qty: 1, lineDiscount: 0.5}], member: false}, {subtotal: 50, shipping: 0, total: 50, points: 50, skus: ["a"]}], + [{items: [{sku: "a", price: 33.33, qty: 3, lineDiscount: 0.1}], member: false}, {subtotal: 89.99, shipping: 0, total: 89.99, points: 89, skus: ["a"]}], + [{items: [], member: false}, {subtotal: 0, shipping: 4.99, total: 4.99, points: 0, skus: []}], + [{items: [{sku: "a", price: 10, qty: 1}]}, "!error: \"nodeId\":\"summary\""], + ], +} + +// --------------------------------------------------------------------------------------------- +// Subscription renewal: dates, grace periods and a switch on status. +{ + name: "subscription: renewal status from dates", + graph: { + nodes: [ + {expression: "dates", passThrough: true, fields: { + daysLeft: "d(renewsOn).diff(d(), 'day')", + graceEnds: "d(renewsOn).add(graceDays ?? 7, 'd')", + }}, + {switch: "status", when: ["cancelled == true", "daysLeft > 30", "daysLeft >= 0", "d() <= graceEnds", ""]}, + {expression: "cancelled", fields: {status: "'cancelled'", notify: "false"}}, + {expression: "active", fields: {status: "'active'", notify: "false"}}, + {expression: "renewing", fields: {status: "'renewing'", notify: "true", daysLeft: "daysLeft"}}, + {expression: "grace", fields: {status: "'grace'", notify: "true", graceEnds: "graceEnds"}}, + {expression: "lapsed", fields: {status: "'lapsed'", notify: "false"}}, + ], + edges: [ + "input -> dates -> status", + "status:0 -> cancelled -> output", + "status:1 -> active -> output", + "status:2 -> renewing -> output", + "status:3 -> grace -> output", + "status:4 -> lapsed -> output", + ], + }, + cases: [ + [{renewsOn: "2025-06-01"}, {status: "active", notify: false}], + [{renewsOn: "2025-04-01"}, {status: "renewing", notify: true, daysLeft: 11}], + [{renewsOn: "2025-03-21"}, {status: "renewing", notify: true, daysLeft: 0}], + [{renewsOn: "2025-03-15"}, {status: "grace", notify: true, graceEnds: "2025-03-22T00:00:00Z"}], + [{renewsOn: "2025-03-01", graceDays: 30}, {status: "grace", notify: true, graceEnds: "2025-03-31T00:00:00Z"}], + [{renewsOn: "2025-03-01"}, {status: "lapsed", notify: false}], + [{renewsOn: "2025-06-01", cancelled: true}, {status: "cancelled", notify: false}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Currency conversion: rates from a table, fees from a nested sub-decision. +{ + name: "fx: conversion with a fee sub-decision", + decisions: { + fee: {nodes: [ + {table: "fee", inputs: ["amount", "channel"], outputs: ["fee"], rules: [ + ["", "'app'", "0"], + ["< 100", "", "2"], + ["", "", "round(amount * 0.015, 2)"], + ]}, + ]}, + }, + graph: { + nodes: [ + {table: "rate", passThrough: true, inputs: ["from", "to"], outputs: ["rate"], rules: [ + ["'EUR'", "'USD'", "1.0825"], + ["'USD'", "'EUR'", "0.9238"], + ["'GBP'", "'EUR'", "1.1691"], + ["", "", "null"], + ]}, + {decision: "fees", key: "fee", passThrough: true}, + {expression: "convert", fields: { + supported: "rate != null", + fee: "fee", + received: "rate != null ? round((amount - fee) * rate, 2) : null", + }}, + ], + }, + cases: [ + [{from: "EUR", to: "USD", amount: 1000, channel: "web"}, {supported: true, fee: 15, received: 1066.26}], + [{from: "EUR", to: "USD", amount: 1000, channel: "app"}, {supported: true, fee: 0, received: 1082.5}], + [{from: "USD", to: "EUR", amount: 50, channel: "web"}, {supported: true, fee: 2, received: 44.34}], + [{from: "GBP", to: "EUR", amount: 99.99, channel: "web"}, {supported: true, fee: 2, received: 114.56}], + [{from: "GBP", to: "EUR", amount: 100, channel: "web"}, {supported: true, fee: 1.5, received: 115.16}], + [{from: "JPY", to: "EUR", amount: 100, channel: "web"}, {supported: false, fee: 1.5}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Lending affordability: a function node computes an amortised payment. +{ + name: "lending: function node computes the monthly payment", + graph: { + nodes: [ + {table: "apr", passThrough: true, inputs: ["termMonths", "creditScore"], outputs: ["apr"], rules: [ + ["<= 36", ">= 700", "0.06"], + ["<= 36", "", "0.09"], + ["", ">= 700", "0.075"], + ["", "", "0.11"], + ]}, + {function: "amortise", source: """ +export const handler = async (input) => { + const r = input.apr / 12; + const n = input.termMonths; + const payment = r === 0 ? input.principal / n : input.principal * r / (1 - Math.pow(1 + r, -n)); + return { ...input, payment: Math.round(payment * 100) / 100 }; +}; +"""}, + {expression: "afford", fields: { + apr: "apr", + payment: "payment", + affordable: "payment <= income * 0.35", + }}, + ], + }, + cases: [ + [{principal: 10000, termMonths: 36, creditScore: 720, income: 3000}, {apr: 0.06, payment: 304.22, affordable: true}], + [{principal: 10000, termMonths: 36, creditScore: 650, income: 1000}, {apr: 0.09, payment: 318, affordable: true}], + [{principal: 30000, termMonths: 60, creditScore: 760, income: 1500}, {apr: 0.075, payment: 601.14, affordable: false}], + [{principal: 30000, termMonths: 72, creditScore: 600, income: 2000}, {apr: 0.11, payment: 571.02, affordable: true}], + [{principal: 1200, termMonths: 12, creditScore: 800, income: 300}, {apr: 0.06, payment: 103.28, affordable: true}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Inventory reorder: per-warehouse decisions in a loop with first-hit tables, then aggregation. +// In loop mode, passThrough merges each item into its own output, and the request into the node's. +{ + name: "inventory: reorder plan across warehouses", + graph: { + nodes: [ + {table: "plan", inputField: "warehouses", executionMode: "loop", outputPath: "plan", passThrough: true, inputs: ["stock", "dailyDemand"], outputs: ["id", "action", "orderQty"], rules: [ + ["", "0", "id", "'hold'", "0"], + ["< dailyDemand * 3", "", "id", "'expedite'", "dailyDemand * 14 - stock"], + ["< dailyDemand * 7", "", "id", "'reorder'", "dailyDemand * 14 - stock"], + ["", "", "id", "'hold'", "0"], + ]}, + {expression: "totals", fields: { + plan: "plan", + totalOrder: "sum(map(plan, #.orderQty))", + urgent: "some(plan, #.action == 'expedite')", + }}, + ], + }, + cases: [ + [{warehouses: [{id: "w1", stock: 100, dailyDemand: 10}]}, {plan: [{id: "w1", stock: 100, dailyDemand: 10, action: "hold", orderQty: 0}], totalOrder: 0, urgent: false}], + [{warehouses: [{id: "w1", stock: 50, dailyDemand: 10}]}, {plan: [{id: "w1", stock: 50, dailyDemand: 10, action: "reorder", orderQty: 90}], totalOrder: 90, urgent: false}], + [{warehouses: [{id: "w1", stock: 20, dailyDemand: 10}, {id: "w2", stock: 5, dailyDemand: 0}]}, {plan: [{id: "w1", stock: 20, dailyDemand: 10, action: "expedite", orderQty: 120}, {id: "w2", stock: 5, dailyDemand: 0, action: "hold", orderQty: 0}], totalOrder: 120, urgent: true}], + [{warehouses: [{id: "a", stock: 30, dailyDemand: 10}, {id: "b", stock: 69, dailyDemand: 10}, {id: "c", stock: 70, dailyDemand: 10}]}, {plan: [{id: "a", stock: 30, dailyDemand: 10, action: "reorder", orderQty: 110}, {id: "b", stock: 69, dailyDemand: 10, action: "reorder", orderQty: 71}, {id: "c", stock: 70, dailyDemand: 10, action: "hold", orderQty: 0}], totalOrder: 181, urgent: false}], + [{warehouses: []}, {plan: [], totalOrder: 0, urgent: false}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Access control: role table, ownership expression and a deny-overrides switch. +{ + name: "access: deny overrides, then role and ownership", + graph: { + nodes: [ + {switch: "deny", when: ["user.suspended == true or resource.locked == true", ""]}, + {expression: "denied", fields: {allow: "false", why: "'blocked'"}}, + {table: "role", passThrough: true, inputs: ["user.role", "action"], outputs: ["roleAllows"], rules: [ + ["'admin'", "", "true"], + ["'editor'", "'read', 'write'", "true"], + ["'viewer'", "'read'", "true"], + ["", "", "false"], + ]}, + {expression: "decide", fields: { + allow: "roleAllows or (resource.owner == user.id and action != 'delete')", + why: "roleAllows ? 'role' : (resource.owner == user.id and action != 'delete' ? 'owner' : 'none')", + }}, + ], + edges: [ + "input -> deny", + "deny:0 -> denied -> output", + "deny:1 -> role -> decide -> output", + ], + }, + cases: [ + [{user: {id: "u1", role: "admin"}, resource: {owner: "u2"}, action: "delete"}, {allow: true, why: "role"}], + [{user: {id: "u1", role: "editor"}, resource: {owner: "u2"}, action: "write"}, {allow: true, why: "role"}], + [{user: {id: "u1", role: "editor"}, resource: {owner: "u2"}, action: "delete"}, {allow: false, why: "none"}], + [{user: {id: "u1", role: "viewer"}, resource: {owner: "u1"}, action: "write"}, {allow: true, why: "owner"}], + [{user: {id: "u1", role: "viewer"}, resource: {owner: "u1"}, action: "delete"}, {allow: false, why: "none"}], + [{user: {id: "u1", role: "admin", suspended: true}, resource: {owner: "u1"}, action: "read"}, {allow: false, why: "blocked"}], + [{user: {id: "u1", role: "admin"}, resource: {owner: "u1", locked: true}, action: "read"}, {allow: false, why: "blocked"}], + [{user: {id: "u1"}, resource: {}, action: "read"}, {allow: false, why: "none"}], + ], +} diff --git a/core/engine/tests/spec/graph/23-switch-nesting.json5 b/core/engine/tests/spec/graph/23-switch-nesting.json5 new file mode 100644 index 00000000..16657adc --- /dev/null +++ b/core/engine/tests/spec/graph/23-switch-nesting.json5 @@ -0,0 +1,991 @@ +// Switch nesting: switches inside the branches of other switches, switches separated by +// tables, switches routing on what earlier nodes produced, switches with many branches and +// graphs where every branch converges on one node. Each switch prunes the edges of its +// untaken branches; an inner switch only runs when its branch survives. + +// --------------------------------------------------------------------------------------- +// An inner switch in every branch of the outer switch: a decision tree. Each leaf is +// reached by exactly one path of conditions. +// --------------------------------------------------------------------------------------- + +{ + name: "an inner switch in each branch of the outer switch", + graph: { + nodes: [ + {switch: "region", when: ["country == 'US'", ""]}, + {switch: "us", when: ["state == 'CA'", "state == 'NY'", ""]}, + {switch: "intl", when: ["eu", ""]}, + {expression: "ca", fields: {tax: "0.0725"}}, + {expression: "ny", fields: {tax: "0.04"}}, + {expression: "usOther", fields: {tax: "0.05"}}, + {expression: "eu", fields: {tax: "0.2"}}, + {expression: "row", fields: {tax: "0"}}, + ], + edges: [ + "input -> region", "region:0 -> us", "region:1 -> intl", + "us:0 -> ca -> output", "us:1 -> ny -> output", "us:2 -> usOther -> output", + "intl:0 -> eu -> output", "intl:1 -> row -> output", + ], + }, + cases: [ + [{country: "US", state: "CA"}, {tax: 0.0725}], + [{country: "US", state: "NY"}, {tax: 0.04}], + [{country: "US", state: "TX"}, {tax: 0.05}], + [{country: "US"}, {tax: 0.05}], + [{country: "DE", eu: true}, {tax: 0.2}], + [{country: "DE", eu: false, state: "CA"}, {tax: 0}], + [{}, {tax: 0}], + [{country: null, eu: true}, {tax: 0.2}], + ], +} + +{ + name: "a binary decision tree four switches deep over one number", + graph: { + nodes: [ + {switch: "s50", when: ["n < 50", ""]}, + {switch: "s25", when: ["n < 25", ""]}, + {switch: "s75", when: ["n < 75", ""]}, + {switch: "s12", when: ["n < 12.5", ""]}, + {expression: "q0", fields: {bucket: "0"}}, + {expression: "q1", fields: {bucket: "1"}}, + {expression: "q2", fields: {bucket: "2"}}, + {expression: "q3", fields: {bucket: "3"}}, + {expression: "q4", fields: {bucket: "4"}}, + ], + edges: [ + "input -> s50", "s50:0 -> s25", "s50:1 -> s75", + "s25:0 -> s12", "s25:1 -> q2 -> output", + "s12:0 -> q0 -> output", "s12:1 -> q1 -> output", + "s75:0 -> q3 -> output", "s75:1 -> q4 -> output", + ], + }, + cases: [ + [{n: 0}, {bucket: 0}], + [{n: 12.4999}, {bucket: 0}], + [{n: 12.5}, {bucket: 1}], + [{n: 24.99}, {bucket: 1}], + [{n: 25}, {bucket: 2}], + [{n: 49}, {bucket: 2}], + [{n: 50}, {bucket: 3}], + [{n: 74.5}, {bucket: 3}], + [{n: 75}, {bucket: 4}], + [{n: -1000}, {bucket: 0}], + [{}, {bucket: 4}], + [{n: "10"}, {bucket: 4}], + ], +} + +{ + name: "an inner switch whose default branch rejoins the outer default", + graph: { + nodes: [ + {switch: "outer", when: ["member", ""]}, + {switch: "inner", when: ["points >= 1000", ""]}, + {expression: "gold", fields: {perk: "'gold'"}}, + {expression: "standard", fields: {perk: "'standard'"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "inner:0 -> gold -> output", "inner:1 -> standard", "outer:1 -> standard -> output"], + }, + cases: [ + [{member: true, points: 1000}, {perk: "gold"}], + [{member: true, points: 999}, {perk: "standard"}], + [{member: false, points: 5000}, {perk: "standard"}], + [{points: 5000}, {perk: "standard"}], + [{member: true}, {perk: "standard"}], + ], +} + +{ + name: "inner and outer switch passing the input straight through to the output", + graph: { + nodes: [ + {switch: "outer", when: ["a", ""]}, + {switch: "inner", when: ["b", ""]}, + {expression: "notB", fields: {r: "'a, not b'"}}, + {expression: "notA", fields: {r: "'not a'"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "inner:0 -> output", "inner:1 -> notB -> output", "outer:1 -> notA -> output"], + }, + cases: [ + [{a: true, b: true, x: 1}, {a: true, b: true, x: 1}], + [{a: true, b: false, x: 1}, {r: "a, not b"}], + [{a: false, b: true}, {r: "not a"}], + [{a: true, b: true, nested: {k: [1, null]}}, {a: true, b: true, nested: {k: [1, null]}}], + ], +} + +{ + name: "the inner switch sees what a node between the switches wrote", + graph: { + nodes: [ + {switch: "outer", when: ["kind == 'loan'", ""]}, + {expression: "ratio", passThrough: true, fields: {dti: "debt / income"}}, + {switch: "inner", when: ["dti <= 0.3", "dti <= 0.45", ""]}, + {expression: "approve", fields: {decision: "'approve'", dti: "dti"}}, + {expression: "review", fields: {decision: "'review'", dti: "dti"}}, + {expression: "decline", fields: {decision: "'decline'", dti: "dti"}}, + {expression: "other", fields: {decision: "'n/a'"}}, + ], + edges: [ + "input -> outer", "outer:0 -> ratio -> inner", "outer:1 -> other -> output", + "inner:0 -> approve -> output", "inner:1 -> review -> output", "inner:2 -> decline -> output", + ], + }, + cases: [ + [{kind: "loan", debt: 300, income: 1000}, {decision: "approve", dti: 0.3}], + [{kind: "loan", debt: 450, income: 1000}, {decision: "review", dti: 0.45}], + [{kind: "loan", debt: 451, income: 1000}, {decision: "decline", dti: 0.451}], + [{kind: "card", debt: 1, income: 0}, {decision: "n/a"}], + [{kind: "loan", debt: 1, income: 0}, {decision: "decline"}], + ], +} + +{ + name: "an inner collect switch inside a first switch branch", + graph: { + nodes: [ + {switch: "outer", when: ["active", ""]}, + {switch: "flags", hit: "collect", when: ["overdue", "vip", "len(tags) > 0"]}, + {expression: "fOverdue", fields: {overdue: "true"}}, + {expression: "fVip", fields: {vip: "true"}}, + {expression: "fTags", fields: {tagCount: "len(tags)"}}, + {expression: "inactive", fields: {inactive: "true"}}, + ], + edges: [ + "input -> outer", "outer:0 -> flags", "outer:1 -> inactive -> output", + "flags:0 -> fOverdue -> output", "flags:1 -> fVip -> output", "flags:2 -> fTags -> output", + ], + }, + cases: [ + [{active: true, overdue: true, vip: true, tags: ["a"]}, {overdue: true, vip: true, tagCount: 1}], + [{active: true, overdue: false, vip: true, tags: []}, {vip: true}], + [{active: true, tags: ["a", "b"]}, {tagCount: 2}], + [{active: true, overdue: false, vip: false, tags: []}, {}], + [{active: false, overdue: true, vip: true, tags: ["a"]}, {inactive: true}], + ], +} + +{ + name: "an inner switch that matches nothing leaves the outer graph empty", + graph: { + nodes: [ + {switch: "outer", when: ["n > 0", ""]}, + {switch: "inner", when: ["n > 100", "n > 10"]}, + {expression: "huge", fields: {r: "'huge'"}}, + {expression: "big", fields: {r: "'big'"}}, + {expression: "neg", fields: {r: "'non-positive'"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "outer:1 -> neg -> output", "inner:0 -> huge -> output", "inner:1 -> big -> output"], + }, + cases: [ + [{n: 101}, {r: "huge"}], + [{n: 11}, {r: "big"}], + [{n: 10}, {}], + [{n: 1}, {}], + [{n: 0}, {r: "non-positive"}], + ], +} + +{ + name: "an inner switch with no match next to a sibling branch of the outer collect switch", + graph: { + nodes: [ + {switch: "outer", hit: "collect", when: ["true", "true"]}, + {switch: "inner", when: ["n > 10"]}, + {expression: "big", fields: {big: "true"}}, + {expression: "side", fields: {side: "n"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "inner:0 -> big -> output", "outer:1 -> side -> output"], + }, + cases: [ + [{n: 11}, {big: true, side: 11}], + [{n: 10}, {side: 10}], + [{n: -1}, {side: -1}], + ], +} + +// --------------------------------------------------------------------------------------- +// Switch, table, switch: a table between two switches computes the value the second +// switch routes on. An unmatched first-hit table yields nothing for the next switch. +// --------------------------------------------------------------------------------------- + +{ + name: "switch, table, switch on the table's band", + graph: { + nodes: [ + {switch: "product", when: ["product == 'loan'", ""]}, + {table: "score", inputs: ["income", "debt"], outputs: ["band"], rules: [ + [">= 5000", "< 1000", "'A'"], + [">= 3000", "", "'B'"], + ["", "", "'C'"], + ]}, + {switch: "band", when: ["band == 'A'", "band == 'B'", ""]}, + {expression: "a", fields: {offer: "'prime'"}}, + {expression: "b", fields: {offer: "'standard'"}}, + {expression: "c", fields: {offer: "'decline'"}}, + {expression: "noloan", fields: {offer: "'none'"}}, + ], + edges: [ + "input -> product", "product:0 -> score -> band", "product:1 -> noloan -> output", + "band:0 -> a -> output", "band:1 -> b -> output", "band:2 -> c -> output", + ], + }, + cases: [ + [{product: "loan", income: 6000, debt: 500}, {offer: "prime"}], + [{product: "loan", income: 6000, debt: 1000}, {offer: "standard"}], + [{product: "loan", income: 3000, debt: 0}, {offer: "standard"}], + [{product: "loan", income: 2999, debt: 0}, {offer: "decline"}], + [{product: "loan"}, {offer: "decline"}], + [{product: "card", income: 6000, debt: 0}, {offer: "none"}], + ], +} + +{ + name: "an unmatched table before a switch sends the switch an empty object", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["band"], rules: [ + ["> 10", "'high'"], + ["> 0", "'low'"], + ]}, + {switch: "s", when: ["band == 'high'", "band == 'low'", "band == null", ""]}, + {expression: "h", fields: {r: "'high'"}}, + {expression: "l", fields: {r: "'low'"}}, + {expression: "none", fields: {r: "'none'"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> t -> s", "s:0 -> h -> output", "s:1 -> l -> output", "s:2 -> none -> output", "s:3 -> def -> output"], + }, + cases: [ + [{n: 11}, {r: "high"}], + [{n: 1}, {r: "low"}], + [{n: 0}, {r: "none"}], + [{}, {r: "none"}], + ], +} + +{ + name: "a passThrough table before a switch: conditions see input and table output", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["age"], outputs: ["group"], rules: [ + ["< 18", "'minor'"], + ["< 65", "'adult'"], + ["", "'senior'"], + ]}, + {switch: "s", when: ["group == 'adult' and employed", "group == 'senior' or disabled", ""]}, + {expression: "work", fields: {plan: "'employer'", age: "age"}}, + {expression: "gov", fields: {plan: "'public'", age: "age"}}, + {expression: "self", fields: {plan: "'private'", group: "group"}}, + ], + edges: ["input -> t -> s", "s:0 -> work -> output", "s:1 -> gov -> output", "s:2 -> self -> output"], + }, + cases: [ + [{age: 30, employed: true}, {plan: "employer", age: 30}], + [{age: 30, employed: false}, {plan: "private", group: "adult"}], + [{age: 70, employed: true}, {plan: "public", age: 70}], + [{age: 10, disabled: true}, {plan: "public", age: 10}], + [{age: 10}, {plan: "private", group: "minor"}], + ], +} + +{ + name: "a table on a branch between two switches, with outputPath", + graph: { + nodes: [ + {switch: "s1", when: ["type == 'parcel'", ""]}, + {table: "rate", passThrough: true, outputPath: "rate", inputs: ["weight"], outputs: ["per", "zone"], rules: [ + ["<= 1", "5", "'light'"], + ["<= 10", "3", "'medium'"], + ["", "2", "'heavy'"], + ]}, + {switch: "s2", when: ["rate.zone == 'heavy'", ""]}, + {expression: "freight", fields: {cost: "weight * rate.per + 50", via: "'freight'"}}, + {expression: "post", fields: {cost: "weight * rate.per", via: "'post'"}}, + {expression: "letter", fields: {cost: "1", via: "'letter'"}}, + ], + edges: [ + "input -> s1", "s1:0 -> rate -> s2", "s1:1 -> letter -> output", + "s2:0 -> freight -> output", "s2:1 -> post -> output", + ], + }, + cases: [ + [{type: "parcel", weight: 1}, {cost: 5, via: "post"}], + [{type: "parcel", weight: 10}, {cost: 30, via: "post"}], + [{type: "parcel", weight: 11}, {cost: 72, via: "freight"}], + [{type: "letter", weight: 100}, {cost: 1, via: "letter"}], + ], +} + +{ + name: "a collect table before a switch hands the switch an array", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["tag"], rules: [ + ["> 0", "'pos'"], + ["> 10", "'big'"], + ]}, + {switch: "s", when: ["len($root) == 2", "len($root) == 1", ""]}, + {expression: "two", fields: {r: "'two'"}}, + {expression: "one", fields: {r: "'one'"}}, + {expression: "zero", fields: {r: "'zero'"}}, + ], + edges: ["input -> t -> s", "s:0 -> two -> output", "s:1 -> one -> output", "s:2 -> zero -> output"], + }, + cases: [ + [{n: 11}, {r: "two"}], + [{n: 5}, {r: "one"}], + [{n: 0}, {r: "zero"}], + ], +} + +{ + name: "switch, table on one branch, switch on both branches' outcome", + graph: { + nodes: [ + {switch: "s1", when: ["manual", ""]}, + {expression: "fixed", fields: {level: "manualLevel"}}, + {table: "auto", inputs: ["risk"], outputs: ["level"], rules: [ + ["> 0.8", "3"], + ["> 0.5", "2"], + ["", "1"], + ]}, + {switch: "s2", when: ["level >= 3", "level == 2", ""]}, + {expression: "high", fields: {action: "'block'", level: "level"}}, + {expression: "mid", fields: {action: "'review'", level: "level"}}, + {expression: "low", fields: {action: "'allow'", level: "level"}}, + ], + edges: [ + "input -> s1", "s1:0 -> fixed -> s2", "s1:1 -> auto -> s2", + "s2:0 -> high -> output", "s2:1 -> mid -> output", "s2:2 -> low -> output", + ], + }, + cases: [ + [{manual: true, manualLevel: 3, risk: 0}, {action: "block", level: 3}], + [{manual: true, manualLevel: 2, risk: 0.9}, {action: "review", level: 2}], + [{manual: true, risk: 0.9}, {action: "allow"}], + [{manual: false, risk: 0.9}, {action: "block", level: 3}], + [{risk: 0.6}, {action: "review", level: 2}], + [{risk: 0.5}, {action: "allow", level: 1}], + ], +} + +{ + name: "a table inside a nested switch branch with an unmatched row", + graph: { + nodes: [ + {switch: "outer", when: ["a", ""]}, + {switch: "inner", when: ["b", ""]}, + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["> 0", "'pos'"], + ]}, + {expression: "nb", fields: {r: "'not b'"}}, + {expression: "na", fields: {r: "'not a'"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "outer:1 -> na -> output", "inner:0 -> t -> output", "inner:1 -> nb -> output"], + }, + cases: [ + [{a: true, b: true, n: 1}, {r: "pos"}], + [{a: true, b: true, n: 0}, {}], + [{a: true, b: false, n: 1}, {r: "not b"}], + [{a: false, b: true, n: 1}, {r: "not a"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Switches routing on outputs of earlier nodes that are not their direct parents, through +// $nodes, and on nodes that pruned branches never ran. +// --------------------------------------------------------------------------------------- + +{ + name: "a switch reads a sibling node's output through $nodes", + graph: { + nodes: [ + {expression: "limit", fields: {max: "cap * 2"}}, + {expression: "usage", fields: {used: "sum(map(items, #.qty))"}}, + {switch: "s", when: ["$nodes.usage.used > $nodes.limit.max", ""]}, + {expression: "over", fields: {over: "true"}}, + {expression: "ok", fields: {over: "false"}}, + ], + edges: ["input -> limit -> s", "input -> usage", "usage -> s", "s:0 -> over -> output", "s:1 -> ok -> output"], + }, + cases: [ + [{cap: 2, items: [{qty: 3}, {qty: 2}]}, {over: true}], + [{cap: 2, items: [{qty: 3}, {qty: 1}]}, {over: false}], + [{cap: 0, items: []}, {over: false}], + ], +} + +{ + name: "a switch reads a field a non-passThrough parent dropped through $nodes.input", + graph: { + nodes: [ + {expression: "calc", fields: {score: "a + b"}}, + {switch: "s", when: ["score > 10 and $nodes.input.vip", "score > 10", "score == null", ""]}, + {expression: "vipHigh", fields: {r: "'vip-high'"}}, + {expression: "high", fields: {r: "'high'"}}, + {expression: "nil", fields: {r: "'nil'"}}, + {expression: "low", fields: {r: "'low'", vipVisible: "vip"}}, + ], + edges: ["input -> calc -> s", "s:0 -> vipHigh -> output", "s:1 -> high -> output", "s:2 -> nil -> output", "s:3 -> low -> output"], + }, + cases: [ + [{a: 10, b: 1, vip: true}, {r: "vip-high"}], + [{a: 10, b: 1, vip: false}, {r: "high"}], + [{a: 10, b: 1}, {r: "high"}], + [{a: 1, b: 1, vip: true}, {r: "low"}], + ], +} + +{ + name: "a second switch reads $nodes of the first switch's taken branch", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["x > 0", "y > 0"]}, + {expression: "px", fields: {v: "x"}}, + {expression: "py", fields: {v: "y"}}, + {switch: "s2", when: ["$nodes.px.v > 5", "$nodes.py.v > 5", "$nodes.px == null and $nodes.py == null", ""]}, + {expression: "rx", fields: {r: "'x'"}}, + {expression: "ry", fields: {r: "'y'"}}, + {expression: "none", fields: {r: "'none'"}}, + {expression: "small", fields: {r: "'small'"}}, + ], + edges: [ + "input -> s1", "s1:0 -> px -> s2", "s1:1 -> py -> s2", "input -> s2", + "s2:0 -> rx -> output", "s2:1 -> ry -> output", "s2:2 -> none -> output", "s2:3 -> small -> output", + ], + }, + cases: [ + [{x: 6, y: 6}, {r: "x"}], + [{x: 1, y: 6}, {r: "y"}], + [{x: 0, y: 6}, {r: "y"}], + [{x: 0, y: 0}, {r: "none"}], + [{x: 1, y: 1}, {r: "small"}], + ], +} + +{ + name: "a switch reads the output of a function node", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({ kind: typeof input.v, len: Array.isArray(input.v) ? input.v.length : null });"""}, + {switch: "s", when: ["kind == 'number'", "kind == 'string'", "len != null", ""]}, + {expression: "num", fields: {r: "'number'"}}, + {expression: "str", fields: {r: "'string'"}}, + {expression: "arr", fields: {r: "'array'", len: "len"}}, + {expression: "other", fields: {r: "kind"}}, + ], + edges: ["input -> f -> s", "s:0 -> num -> output", "s:1 -> str -> output", "s:2 -> arr -> output", "s:3 -> other -> output"], + }, + cases: [ + [{v: 1}, {r: "number"}], + [{v: "a"}, {r: "string"}], + [{v: [1, 2]}, {r: "array", len: 2}], + [{v: true}, {r: "boolean"}], + [{}, {r: "undefined"}], + ], +} + +{ + name: "a switch reads a sub-decision's result", + decisions: { + score: {nodes: [ + {table: "t", inputs: ["income"], outputs: ["score"], rules: [ + [">= 100", "700"], + [">= 50", "600"], + ["", "400"], + ]}, + ]}, + }, + graph: { + nodes: [ + {decision: "call", key: "score", outputPath: "credit", passThrough: true}, + {switch: "s", when: ["credit.score >= 650", "credit.score >= 500", ""]}, + {expression: "good", fields: {r: "'good'", income: "income"}}, + {expression: "fair", fields: {r: "'fair'", income: "income"}}, + {expression: "poor", fields: {r: "'poor'", score: "credit.score"}}, + ], + edges: ["input -> call -> s", "s:0 -> good -> output", "s:1 -> fair -> output", "s:2 -> poor -> output"], + }, + cases: [ + [{income: 100}, {r: "good", income: 100}], + [{income: 50}, {r: "fair", income: 50}], + [{income: 49}, {r: "poor", score: 400}], + [{}, {r: "poor", score: 400}], + ], +} + +{ + name: "a switch after a join routes on keys from both parents", + graph: { + nodes: [ + {expression: "a", fields: {left: "x * 2"}}, + {expression: "b", fields: {right: "y * 3"}}, + {switch: "s", when: ["left > right", "left < right", ""]}, + {expression: "l", fields: {r: "'left'"}}, + {expression: "rr", fields: {r: "'right'"}}, + {expression: "eq", fields: {r: "'tie'", v: "left"}}, + ], + edges: ["input -> a -> s", "input -> b -> s", "s:0 -> l -> output", "s:1 -> rr -> output", "s:2 -> eq -> output"], + }, + cases: [ + [{x: 4, y: 2}, {r: "left"}], + [{x: 1, y: 1}, {r: "right"}], + [{x: 3, y: 2}, {r: "tie", v: 6}], + [{x: 0, y: 0}, {r: "tie", v: 0}], + ], +} + +{ + name: "a switch reads $nodes of a node on a pruned branch as null", + graph: { + nodes: [ + {switch: "s1", when: ["a", ""]}, + {expression: "onA", fields: {v: "1"}}, + {expression: "notA", fields: {v: "2"}}, + {switch: "s2", when: ["$nodes.onA != null", "$nodes.notA != null", ""]}, + {expression: "sawA", fields: {r: "'a ran'"}}, + {expression: "sawNotA", fields: {r: "'not-a ran'"}}, + {expression: "none", fields: {r: "'neither'"}}, + ], + edges: [ + "input -> s1", "s1:0 -> onA -> s2", "s1:1 -> notA -> s2", + "s2:0 -> sawA -> output", "s2:1 -> sawNotA -> output", "s2:2 -> none -> output", + ], + }, + cases: [ + [{a: true}, {r: "a ran"}], + [{a: false}, {r: "not-a ran"}], + [{}, {r: "not-a ran"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Many-branch switches: eight or more branches, first and collect. +// --------------------------------------------------------------------------------------- + +{ + name: "eight branches over score ranges, first hit", + graph: { + nodes: [ + {switch: "s", when: ["score >= 97", "score >= 93", "score >= 90", "score >= 87", "score >= 83", "score >= 80", "score >= 70", ""]}, + {expression: "b0", fields: {grade: "'A+'"}}, + {expression: "b1", fields: {grade: "'A'"}}, + {expression: "b2", fields: {grade: "'A-'"}}, + {expression: "b3", fields: {grade: "'B+'"}}, + {expression: "b4", fields: {grade: "'B'"}}, + {expression: "b5", fields: {grade: "'B-'"}}, + {expression: "b6", fields: {grade: "'C'"}}, + {expression: "b7", fields: {grade: "'F'"}}, + ], + edges: [ + "input -> s", + "s:0 -> b0 -> output", "s:1 -> b1 -> output", "s:2 -> b2 -> output", "s:3 -> b3 -> output", + "s:4 -> b4 -> output", "s:5 -> b5 -> output", "s:6 -> b6 -> output", "s:7 -> b7 -> output", + ], + }, + cases: [ + [{score: 100}, {grade: "A+"}], + [{score: 97}, {grade: "A+"}], + [{score: 96.9}, {grade: "A"}], + [{score: 90}, {grade: "A-"}], + [{score: 89}, {grade: "B+"}], + [{score: 85}, {grade: "B"}], + [{score: 80}, {grade: "B-"}], + [{score: 79.99}, {grade: "C"}], + [{score: 70}, {grade: "C"}], + [{score: 0}, {grade: "F"}], + [{}, {grade: "F"}], + [{score: "100"}, {grade: "F"}], + ], +} + +{ + name: "ten branches over an enum string", + graph: { + nodes: [ + {switch: "s", when: [ + "day == 'mon'", "day == 'tue'", "day == 'wed'", "day == 'thu'", "day == 'fri'", + "day == 'sat'", "day == 'sun'", "day == null", "len(day) > 3", "", + ]}, + {expression: "d0", fields: {n: "1"}}, + {expression: "d1", fields: {n: "2"}}, + {expression: "d2", fields: {n: "3"}}, + {expression: "d3", fields: {n: "4"}}, + {expression: "d4", fields: {n: "5"}}, + {expression: "d5", fields: {n: "6", weekend: "true"}}, + {expression: "d6", fields: {n: "7", weekend: "true"}}, + {expression: "d7", fields: {n: "0", missing: "true"}}, + {expression: "d8", fields: {n: "-1", long: "true"}}, + {expression: "d9", fields: {n: "-2"}}, + ], + edges: [ + "input -> s", + "s:0 -> d0 -> output", "s:1 -> d1 -> output", "s:2 -> d2 -> output", "s:3 -> d3 -> output", "s:4 -> d4 -> output", + "s:5 -> d5 -> output", "s:6 -> d6 -> output", "s:7 -> d7 -> output", "s:8 -> d8 -> output", "s:9 -> d9 -> output", + ], + }, + cases: [ + [{day: "mon"}, {n: 1}], + [{day: "wed"}, {n: 3}], + [{day: "fri"}, {n: 5}], + [{day: "sat"}, {n: 6, weekend: true}], + [{day: "sun"}, {n: 7, weekend: true}], + [{}, {n: 0, missing: true}], + [{day: null}, {n: 0, missing: true}], + [{day: "monday"}, {n: -1, long: true}], + [{day: "Mon"}, {n: -2}], + [{day: ""}, {n: -2}], + ], +} + +{ + name: "eight collect branches, each writing its own key", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n % 2 == 0", "n % 3 == 0", "n % 5 == 0", "n % 7 == 0", "n > 50", "n < 10", "n == 0", ""]}, + {expression: "b0", fields: {div2: "true"}}, + {expression: "b1", fields: {div3: "true"}}, + {expression: "b2", fields: {div5: "true"}}, + {expression: "b3", fields: {div7: "true"}}, + {expression: "b4", fields: {large: "true"}}, + {expression: "b5", fields: {small: "true"}}, + {expression: "b6", fields: {zero: "true"}}, + {expression: "b7", fields: {seen: "n"}}, + ], + edges: [ + "input -> s", + "s:0 -> b0 -> output", "s:1 -> b1 -> output", "s:2 -> b2 -> output", "s:3 -> b3 -> output", + "s:4 -> b4 -> output", "s:5 -> b5 -> output", "s:6 -> b6 -> output", "s:7 -> b7 -> output", + ], + }, + cases: [ + [{n: 0}, {div2: true, div3: true, div5: true, div7: true, small: true, zero: true, seen: 0}], + [{n: 210}, {div2: true, div3: true, div5: true, div7: true, large: true, seen: 210}], + [{n: 1}, {small: true, seen: 1}], + [{n: 11}, {seen: 11}], + [{n: 49}, {div7: true, seen: 49}], + [{n: 60}, {div2: true, div3: true, div5: true, large: true, seen: 60}], + ], +} + +{ + name: "eight collect branches writing the same key: the first declared edge into the output wins", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n >= 1", "n >= 2", "n >= 3", "n >= 4", "n >= 5", "n >= 6", "n >= 7", "n >= 8"]}, + {expression: "b0", fields: {v: "1"}}, + {expression: "b1", fields: {v: "2"}}, + {expression: "b2", fields: {v: "3"}}, + {expression: "b3", fields: {v: "4"}}, + {expression: "b4", fields: {v: "5"}}, + {expression: "b5", fields: {v: "6"}}, + {expression: "b6", fields: {v: "7"}}, + {expression: "b7", fields: {v: "8"}}, + ], + edges: [ + "input -> s", + "s:0 -> b0", "s:1 -> b1", "s:2 -> b2", "s:3 -> b3", "s:4 -> b4", "s:5 -> b5", "s:6 -> b6", "s:7 -> b7", + "b7 -> output", "b6 -> output", "b5 -> output", "b4 -> output", "b3 -> output", "b2 -> output", "b1 -> output", "b0 -> output", + ], + }, + cases: [ + [{n: 8}, {v: 8}], + [{n: 5}, {v: 5}], + [{n: 1}, {v: 1}], + [{n: 0}, {}], + ], +} + +{ + name: "eight branches with gaps: some matched branches have no edge", + graph: { + nodes: [ + {switch: "s", when: ["n == 0", "n == 1", "n == 2", "n == 3", "n == 4", "n == 5", "n == 6", ""]}, + {expression: "even", fields: {r: "'even'", n: "n"}}, + {expression: "def", fields: {r: "'default'"}}, + ], + edges: ["input -> s", "s:0 -> even", "s:2 -> even", "s:4 -> even", "s:6 -> even -> output", "s:7 -> def -> output"], + }, + cases: [ + [{n: 0}, {r: "even", n: 0}], + [{n: 4}, {r: "even", n: 4}], + [{n: 6}, {r: "even", n: 6}], + [{n: 1}, {}], + [{n: 5}, {}], + [{n: 7}, {r: "default"}], + ], +} + +{ + name: "nine branches with duplicate conditions: only the first duplicate routes", + graph: { + nodes: [ + {switch: "s", when: ["t == 'a'", "t == 'a'", "t == 'b'", "t == 'b'", "t == 'c'", "t == 'c'", "t == 'd'", "t == 'd'", ""]}, + {expression: "a1", fields: {r: "'a1'"}}, + {expression: "a2", fields: {r: "'a2'"}}, + {expression: "b1", fields: {r: "'b1'"}}, + {expression: "b2", fields: {r: "'b2'"}}, + {expression: "c1", fields: {r: "'c1'"}}, + {expression: "c2", fields: {r: "'c2'"}}, + {expression: "d1", fields: {r: "'d1'"}}, + {expression: "d2", fields: {r: "'d2'"}}, + {expression: "z", fields: {r: "'z'"}}, + ], + edges: [ + "input -> s", + "s:0 -> a1 -> output", "s:1 -> a2 -> output", "s:2 -> b1 -> output", "s:3 -> b2 -> output", + "s:4 -> c1 -> output", "s:5 -> c2 -> output", "s:6 -> d1 -> output", "s:7 -> d2 -> output", "s:8 -> z -> output", + ], + }, + cases: [ + [{t: "a"}, {r: "a1"}], + [{t: "b"}, {r: "b1"}], + [{t: "c"}, {r: "c1"}], + [{t: "d"}, {r: "d1"}], + [{t: "e"}, {r: "z"}], + ], +} + +{ + name: "eight branches into eight different node kinds and shapes", + decisions: { + child: {nodes: [{expression: "e", fields: {r: "'child'"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["k == 0", "k == 1", "k == 2", "k == 3", "k == 4", "k == 5", "k == 6", ""]}, + {expression: "e0", fields: {r: "'expr'"}}, + {table: "t1", inputs: ["k"], outputs: ["r"], rules: [["1", "'table'"]]}, + {table: "t2", hit: "collect", inputs: ["k"], outputs: ["r"], rules: [["2", "'a'"], ["", "'b'"]]}, + {decision: "d3", key: "child"}, + {function: "f4", source: """export const handler = async (input) => ({ r: 'fn' });"""}, + {custom: "c5", kind: "config", config: {r: "custom"}}, + {expression: "e6", outputPath: "nested.deep", fields: {r: "'path'"}}, + {expression: "e7", passThrough: true, fields: {r: "'pass'"}}, + ], + edges: [ + "input -> s", + "s:0 -> e0 -> output", "s:1 -> t1 -> output", "s:2 -> t2 -> output", "s:3 -> d3 -> output", + "s:4 -> f4 -> output", "s:5 -> c5 -> output", "s:6 -> e6 -> output", "s:7 -> e7 -> output", + ], + }, + cases: [ + [{k: 0}, {r: "expr"}], + [{k: 1}, {r: "table"}], + [{k: 2}, [{r: "a"}, {r: "b"}]], + [{k: 3}, {r: "child"}], + [{k: 4}, {r: "fn"}], + [{k: 5}, {r: "custom"}], + [{k: 6}, {nested: {deep: {r: "path"}}}], + [{k: 7}, {k: 7, r: "pass"}], + ], +} + +// --------------------------------------------------------------------------------------- +// All branches converging on one node: the converging node runs once with whatever the +// taken branches produced. Under first hit it sees one branch; under collect it sees the +// merge of the taken branches, first declared edge into it winning conflicts. +// --------------------------------------------------------------------------------------- + +{ + name: "eight first-hit branches converge on one summary node", + graph: { + nodes: [ + {switch: "s", when: ["n == 1", "n == 2", "n == 3", "n == 4", "n == 5", "n == 6", "n == 7", ""]}, + {expression: "b0", fields: {w: "10"}}, + {expression: "b1", fields: {w: "20"}}, + {expression: "b2", fields: {w: "30"}}, + {expression: "b3", fields: {w: "40"}}, + {expression: "b4", fields: {w: "50"}}, + {expression: "b5", fields: {w: "60"}}, + {expression: "b6", fields: {w: "70"}}, + {expression: "b7", fields: {w: "0"}}, + {expression: "sum", fields: {weight: "w", double: "w * 2"}}, + ], + edges: [ + "input -> s", + "s:0 -> b0 -> sum", "s:1 -> b1 -> sum", "s:2 -> b2 -> sum", "s:3 -> b3 -> sum", + "s:4 -> b4 -> sum", "s:5 -> b5 -> sum", "s:6 -> b6 -> sum", "s:7 -> b7 -> sum", + "sum -> output", + ], + }, + cases: [ + [{n: 1}, {weight: 10, double: 20}], + [{n: 4}, {weight: 40, double: 80}], + [{n: 7}, {weight: 70, double: 140}], + [{n: 8}, {weight: 0, double: 0}], + [{}, {weight: 0, double: 0}], + ], +} + +{ + name: "collect branches converge on one node that sums their keys", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c", "d"]}, + {expression: "fa", fields: {pa: "1"}}, + {expression: "fb", fields: {pb: "2"}}, + {expression: "fc", fields: {pc: "4"}}, + {expression: "fd", fields: {pd: "8"}}, + {expression: "total", fields: {mask: "(pa ?? 0) + (pb ?? 0) + (pc ?? 0) + (pd ?? 0)"}}, + ], + edges: [ + "input -> s", "s:0 -> fa -> total", "s:1 -> fb -> total", "s:2 -> fc -> total", "s:3 -> fd -> total", + "total -> output", + ], + }, + cases: [ + [{a: true, b: true, c: true, d: true}, {mask: 15}], + [{a: true, c: true}, {mask: 5}], + [{d: true}, {mask: 8}], + [{b: true, c: true, d: true}, {mask: 14}], + ], +} + +{ + name: "collect branches converge with no condition true", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "fa", fields: {pa: "1"}}, + {expression: "fb", fields: {pb: "2"}}, + {expression: "total", fields: {sum: "(pa ?? 0) + (pb ?? 0)"}}, + ], + edges: ["input -> s", "s:0 -> fa -> total", "s:1 -> fb -> total", "total -> output"], + }, + cases: [ + [{a: true, b: true}, {sum: 3}], + [{a: true}, {sum: 1}], + [{}, {}], + ], +} + +{ + name: "collect branches converge writing the same key: the first edge into the join wins", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "fa", fields: {who: "'a'", a: "true"}}, + {expression: "fb", fields: {who: "'b'", b: "true"}}, + {expression: "fc", fields: {who: "'c'", c: "true"}}, + {expression: "join", passThrough: true, fields: {joined: "who"}}, + ], + edges: ["input -> s", "s:0 -> fa", "s:1 -> fb", "s:2 -> fc", "fc -> join", "fa -> join", "fb -> join", "join -> output"], + }, + cases: [ + [{a: true, b: true, c: true}, {who: "c", a: true, b: true, c: true, joined: "c"}], + [{a: true, b: true}, {who: "a", a: true, b: true, joined: "a"}], + [{b: true}, {who: "b", b: true, joined: "b"}], + ], +} + +{ + name: "branches of nested switches all converge on one node", + graph: { + nodes: [ + {switch: "outer", when: ["x > 0", ""]}, + {switch: "innerPos", when: ["y > 0", ""]}, + {switch: "innerNeg", when: ["y > 0", ""]}, + {expression: "q1", fields: {q: "1"}}, + {expression: "q2", fields: {q: "4"}}, + {expression: "q3", fields: {q: "2"}}, + {expression: "q4", fields: {q: "3"}}, + {expression: "label", fields: {quadrant: "'Q' + string(q)"}}, + ], + edges: [ + "input -> outer", "outer:0 -> innerPos", "outer:1 -> innerNeg", + "innerPos:0 -> q1 -> label", "innerPos:1 -> q2 -> label", + "innerNeg:0 -> q3 -> label", "innerNeg:1 -> q4 -> label", + "label -> output", + ], + }, + cases: [ + [{x: 1, y: 1}, {quadrant: "Q1"}], + [{x: -1, y: 1}, {quadrant: "Q2"}], + [{x: -1, y: -1}, {quadrant: "Q3"}], + [{x: 1, y: -1}, {quadrant: "Q4"}], + [{x: 0, y: 0}, {quadrant: "Q3"}], + ], +} + +{ + name: "branches converge straight into the node: the switch input passes through", + graph: { + nodes: [ + {switch: "s", when: ["mode == 'a'", "mode == 'b'", ""]}, + {expression: "sink", fields: {mode: "mode", v: "v"}}, + ], + edges: ["input -> s", "s:0 -> sink", "s:1 -> sink", "s:2 -> sink", "sink -> output"], + }, + cases: [ + [{mode: "a", v: 1}, {mode: "a", v: 1}], + [{mode: "b", v: [1]}, {mode: "b", v: [1]}], + [{mode: "c", v: {k: 1}}, {mode: "c", v: {k: 1}}], + [{}, {}], + ], +} + +{ + name: "collect branches straight into one node see the input once", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["true", "true", "true"]}, + {expression: "sink", fields: {n: "n", m: "m"}}, + ], + edges: ["input -> s", "s:0 -> sink", "s:1 -> sink", "s:2 -> sink", "sink -> output"], + }, + cases: [ + [{n: 1}, {n: 1}], + [{n: 2, m: 3}, {n: 2, m: 3}], + [{m: [1, 2]}, {m: [1, 2]}], + ], +} + +{ + name: "a converging node also fed by the input: the input edge is declared first and wins", + graph: { + nodes: [ + {switch: "s", when: ["vip", "member", ""]}, + {expression: "v", fields: {rate: "0.2"}}, + {expression: "m", fields: {rate: "0.1"}}, + {expression: "g", fields: {rate: "0"}}, + {expression: "price", fields: {final: "base * (1 - rate)"}}, + ], + edges: ["input -> price", "input -> s", "s:0 -> v -> price", "s:1 -> m -> price", "s:2 -> g -> price", "price -> output"], + }, + cases: [ + [{vip: true, base: 100}, {final: 80}], + [{member: true, base: 100}, {final: 90}], + [{base: 100}, {final: 100}], + [{vip: true, base: 100, rate: 0.5}, {final: 50}], + [{base: 100, rate: 0.25}, {final: 75}], + ], +} + +{ + name: "a converging node fed by branches of two different switches", + graph: { + nodes: [ + {switch: "s1", when: ["a", ""]}, + {switch: "s2", when: ["b", ""]}, + {expression: "a1", fields: {fromA: "'yes'"}}, + {expression: "a2", fields: {fromA: "'no'"}}, + {expression: "b1", fields: {fromB: "'yes'"}}, + {expression: "b2", fields: {fromB: "'no'"}}, + {expression: "join", fields: {r: "fromA + '/' + fromB"}}, + ], + edges: [ + "input -> s1", "input -> s2", + "s1:0 -> a1 -> join", "s1:1 -> a2 -> join", "s2:0 -> b1 -> join", "s2:1 -> b2 -> join", + "join -> output", + ], + }, + cases: [ + [{a: true, b: true}, {r: "yes/yes"}], + [{a: true, b: false}, {r: "yes/no"}], + [{a: false, b: true}, {r: "no/yes"}], + [{}, {r: "no/no"}], + ], +} diff --git a/core/engine/tests/spec/graph/24-switch-and-transforms.json5 b/core/engine/tests/spec/graph/24-switch-and-transforms.json5 new file mode 100644 index 00000000..853efb14 --- /dev/null +++ b/core/engine/tests/spec/graph/24-switch-and-transforms.json5 @@ -0,0 +1,813 @@ +// Switches combined with the node transforms: loop execution mode, sub-decisions, +// passThrough, inputField and outputPath on the nodes of a branch, and switches living +// inside sub-decisions (called once or per item). A switch itself has no transforms: it +// hands its merged input unchanged to the chosen branches. + +// --------------------------------------------------------------------------------------- +// A switch choosing between loop nodes: each branch iterates a different array, or the +// same array with a different body. +// --------------------------------------------------------------------------------------- + +{ + name: "branches choose between two loop bodies over the same array", + graph: { + nodes: [ + {switch: "s", when: ["mode == 'net'", ""]}, + {expression: "net", inputField: "lines", outputPath: "out", executionMode: "loop", fields: {v: "price * qty"}}, + {expression: "gross", inputField: "lines", outputPath: "out", executionMode: "loop", fields: {v: "price * qty * 1.2"}}, + ], + edges: ["input -> s", "s:0 -> net -> output", "s:1 -> gross -> output"], + }, + cases: [ + [{mode: "net", lines: [{price: 10, qty: 2}, {price: 5, qty: 1}]}, {out: [{v: 20}, {v: 5}]}], + [{mode: "gross", lines: [{price: 10, qty: 2}, {price: 5, qty: 1}]}, {out: [{v: 24}, {v: 6}]}], + [{mode: "net", lines: []}, {out: []}], + [{lines: [{price: 1, qty: 1}]}, {out: [{v: 1.2}]}], + ], +} + +{ + name: "branches iterate different arrays", + graph: { + nodes: [ + {switch: "s", when: ["useA", ""]}, + {expression: "la", inputField: "a", outputPath: "picked", executionMode: "loop", fields: {x: "$root * 10"}}, + {expression: "lb", inputField: "b", outputPath: "picked", executionMode: "loop", fields: {x: "$root"}}, + ], + edges: ["input -> s", "s:0 -> la -> output", "s:1 -> lb -> output"], + }, + cases: [ + [{useA: true, a: [1, 2], b: [3]}, {picked: [{x: 10}, {x: 20}]}], + [{useA: false, a: [1, 2], b: [3]}, {picked: [{x: 3}]}], + [{useA: true, a: [], b: [3]}, {picked: []}], + ], +} + +{ + name: "a loop on the taken branch over a non-array fails, on the pruned branch it does not", + graph: { + nodes: [ + {switch: "s", when: ["isArray", ""]}, + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {v: "$root"}}, + {expression: "one", fields: {out: "items"}}, + ], + edges: ["input -> s", "s:0 -> each -> output", "s:1 -> one -> output"], + }, + cases: [ + [{isArray: true, items: [1, 2]}, {out: [{v: 1}, {v: 2}]}], + [{isArray: false, items: 5}, {out: 5}], + [{isArray: false, items: "x"}, {out: "x"}], + [{isArray: true, items: 5}, "!error"], + [{isArray: true}, "!error"], + ], +} + +{ + name: "a switch on the array length picks a loop or a scalar fallback", + graph: { + nodes: [ + {switch: "s", when: ["len(items) > 3", "len(items) > 0", ""]}, + {table: "many", inputField: "items", outputPath: "tiers", executionMode: "loop", inputs: ["v"], outputs: ["t"], rules: [ + ["> 10", "'hi'"], + ["", "'lo'"], + ]}, + {expression: "few", inputField: "items", outputPath: "tiers", executionMode: "loop", fields: {t: "'few'"}}, + {expression: "none", fields: {tiers: "[]", empty: "true"}}, + ], + edges: ["input -> s", "s:0 -> many -> output", "s:1 -> few -> output", "s:2 -> none -> output"], + }, + cases: [ + [{items: [{v: 11}, {v: 1}, {v: 20}, {v: 0}]}, {tiers: [{t: "hi"}, {t: "lo"}, {t: "hi"}, {t: "lo"}]}], + [{items: [{v: 11}, {v: 1}]}, {tiers: [{t: "few"}, {t: "few"}]}], + [{items: []}, {tiers: [], empty: true}], + [{}, {tiers: [], empty: true}], + ], +} + +{ + name: "collect branches each running a loop under their own outputPath", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["wantNames", "wantTotals"]}, + {expression: "names", inputField: "rows", outputPath: "names", executionMode: "loop", fields: {n: "upper(name)"}}, + {expression: "totals", inputField: "rows", outputPath: "totals", executionMode: "loop", fields: {t: "amount * 2"}}, + ], + edges: ["input -> s", "s:0 -> names -> output", "s:1 -> totals -> output"], + }, + cases: [ + [{wantNames: true, wantTotals: true, rows: [{name: "a", amount: 1}]}, {names: [{n: "A"}], totals: [{t: 2}]}], + [{wantNames: true, rows: [{name: "a", amount: 1}, {name: "b", amount: 2}]}, {names: [{n: "A"}, {n: "B"}]}], + [{wantTotals: true, rows: [{name: "a", amount: 1}]}, {totals: [{t: 2}]}], + [{rows: [{name: "a", amount: 1}]}, {}], + ], +} + +{ + name: "a loop branch and a scalar branch converge on one node", + graph: { + nodes: [ + {switch: "s", when: ["perItem", ""]}, + {expression: "each", inputField: "items", outputPath: "vals", executionMode: "loop", fields: {v: "$root * 2"}}, + {expression: "flat", fields: {vals: "map(items, {v: #})"}}, + {expression: "sum", fields: {total: "sum(map(vals, #.v))", count: "len(vals)"}}, + ], + edges: ["input -> s", "s:0 -> each -> sum", "s:1 -> flat -> sum", "sum -> output"], + }, + cases: [ + [{perItem: true, items: [1, 2, 3]}, {total: 12, count: 3}], + [{perItem: false, items: [1, 2, 3]}, {total: 6, count: 3}], + [{perItem: true, items: []}, {total: 0, count: 0}], + ], +} + +{ + name: "a loop with passThrough on a branch keeps the input next to the loop result", + graph: { + nodes: [ + {switch: "s", when: ["enrich", ""]}, + {expression: "each", inputField: "users", outputPath: "users", passThrough: true, executionMode: "loop", fields: {adult: "age >= 18"}}, + {expression: "skip", passThrough: true, fields: {skipped: "true"}}, + ], + edges: ["input -> s", "s:0 -> each -> output", "s:1 -> skip -> output"], + }, + cases: [ + [{enrich: true, users: [{age: 20}, {age: 3}]}, {enrich: true, users: [{age: 20, adult: true}, {age: 3, adult: false}]}], + [{enrich: false, users: [{age: 20}]}, {enrich: false, users: [{age: 20}], skipped: true}], + [{enrich: true, users: []}, {enrich: true, users: []}], + ], +} + +// --------------------------------------------------------------------------------------- +// A switch after a loop routes on the collected results. +// --------------------------------------------------------------------------------------- + +{ + name: "a switch routes on the array a loop produced under an outputPath", + graph: { + nodes: [ + {expression: "each", inputField: "txs", outputPath: "checks", executionMode: "loop", fields: {suspicious: "amount > 1000"}}, + {switch: "s", when: ["some(checks, #.suspicious)", "len(checks) == 0", ""]}, + {expression: "flag", fields: {status: "'review'", hits: "len(filter(checks, #.suspicious))"}}, + {expression: "empty", fields: {status: "'empty'"}}, + {expression: "ok", fields: {status: "'ok'"}}, + ], + edges: ["input -> each -> s", "s:0 -> flag -> output", "s:1 -> empty -> output", "s:2 -> ok -> output"], + }, + cases: [ + [{txs: [{amount: 5}, {amount: 5000}, {amount: 2000}]}, {status: "review", hits: 2}], + [{txs: [{amount: 5}, {amount: 1000}]}, {status: "ok"}], + [{txs: []}, {status: "empty"}], + ], +} + +{ + name: "a switch after a passThrough loop sees the input and the results", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "scored", passThrough: true, executionMode: "loop", fields: {s: "x * $nodes.input.weight"}}, + {switch: "s", when: ["sum(map(scored, #.s)) > limit", ""]}, + {expression: "over", fields: {over: "true", limit: "limit"}}, + {expression: "under", fields: {over: "false", n: "len(items)"}}, + ], + edges: ["input -> each -> s", "s:0 -> over -> output", "s:1 -> under -> output"], + }, + cases: [ + [{items: [{x: 1}, {x: 2}, {x: 3}], weight: 2, limit: 10}, {over: true, limit: 10}], + [{items: [{x: 1}, {x: 2}, {x: 3}], weight: 1, limit: 10}, {over: false, n: 3}], + [{items: [], weight: 1, limit: 0}, {over: false, n: 0}], + ], +} + +{ + name: "a switch after a loop without outputPath sees an array", + graph: { + nodes: [ + {expression: "each", inputField: "items", executionMode: "loop", fields: {v: "$root"}}, + {switch: "s", when: ["len($root) > 1", ""]}, + {expression: "many", fields: {r: "'many'"}}, + {expression: "few", fields: {r: "'few'"}}, + ], + edges: ["input -> each -> s", "s:0 -> many -> output", "s:1 -> few -> output"], + }, + cases: [ + [{items: [1, 2]}, {r: "many"}], + [{items: [1]}, {r: "few"}], + [{items: []}, {r: "few"}], + ], +} + +{ + name: "a switch on a table-loop result picks per-batch handling", + graph: { + nodes: [ + {table: "grade", inputField: "students", outputPath: "grades", passThrough: true, executionMode: "loop", inputs: ["score"], outputs: ["g"], rules: [ + [">= 50", "'pass'"], + ["", "'fail'"], + ]}, + {switch: "s", when: ["all(grades, #.g == 'pass')", "none(grades, #.g == 'pass')", ""]}, + {expression: "allPass", fields: {batch: "'all'", class: "class"}}, + {expression: "allFail", fields: {batch: "'none'", class: "class"}}, + {expression: "mixed", fields: {batch: "'mixed'", failed: "len(filter(grades, #.g == 'fail'))"}}, + ], + edges: ["input -> grade -> s", "s:0 -> allPass -> output", "s:1 -> allFail -> output", "s:2 -> mixed -> output"], + }, + cases: [ + [{class: "x", students: [{score: 50}, {score: 99}]}, {batch: "all", class: "x"}], + [{class: "y", students: [{score: 1}, {score: 49}]}, {batch: "none", class: "y"}], + [{class: "z", students: [{score: 1}, {score: 60}, {score: 2}]}, {batch: "mixed", failed: 2}], + [{class: "e", students: []}, {batch: "all", class: "e"}], + ], +} + +// --------------------------------------------------------------------------------------- +// Sub-decisions on switch branches: each branch calls a different child, or the same child +// with different transforms. +// --------------------------------------------------------------------------------------- + +{ + name: "each branch calls a different sub-decision", + decisions: { + retail: {nodes: [{expression: "e", fields: {fee: "amount * 0.03", plan: "'retail'"}}]}, + business: {nodes: [{table: "t", inputs: ["amount"], outputs: ["fee"], rules: [ + ["> 10000", "50"], + ["", "amount * 0.01"], + ]}, {expression: "tag", passThrough: true, fields: {plan: "'business'"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["segment == 'business'", ""]}, + {decision: "biz", key: "business"}, + {decision: "ret", key: "retail"}, + ], + edges: ["input -> s", "s:0 -> biz -> output", "s:1 -> ret -> output"], + }, + cases: [ + [{segment: "business", amount: 20000}, {fee: 50, plan: "business"}], + [{segment: "business", amount: 1000}, {fee: 10, plan: "business"}], + [{segment: "retail", amount: 1000}, {fee: 30, plan: "retail"}], + [{amount: 100}, {fee: 3, plan: "retail"}], + ], +} + +{ + name: "the same sub-decision on two branches with different inputFields", + decisions: { + addr: {nodes: [{expression: "fmt", fields: {line: "street + ', ' + city"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["shipTo == 'billing'", ""]}, + {decision: "bill", key: "addr", inputField: "billing", outputPath: "label"}, + {decision: "ship", key: "addr", inputField: "shipping", outputPath: "label"}, + ], + edges: ["input -> s", "s:0 -> bill -> output", "s:1 -> ship -> output"], + }, + cases: [ + [{shipTo: "billing", billing: {street: "1 Main", city: "A"}, shipping: {street: "2 Side", city: "B"}}, {label: {line: "1 Main, A"}}], + [{shipTo: "shipping", billing: {street: "1 Main", city: "A"}, shipping: {street: "2 Side", city: "B"}}, {label: {line: "2 Side, B"}}], + [{billing: {street: "1 Main", city: "A"}, shipping: {street: "9 Far", city: "C"}}, {label: {line: "9 Far, C"}}], + ], +} + +{ + name: "a sub-decision on a pruned branch with a missing key is never loaded", + decisions: { + present: {nodes: [{expression: "e", fields: {r: "'present'"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["usePresent", ""]}, + {decision: "a", key: "present"}, + {decision: "b", key: "absent"}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{usePresent: true}, {r: "present"}], + [{usePresent: false}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "a sub-decision with passThrough on a branch, then a second switch", + decisions: { + risk: {nodes: [{expression: "e", fields: {risk: "min([1, claims * 0.25])"}}]}, + }, + graph: { + nodes: [ + {switch: "s1", when: ["insured", ""]}, + {decision: "assess", key: "risk", passThrough: true}, + {expression: "uninsured", passThrough: true, fields: {risk: "1"}}, + {switch: "s2", when: ["risk >= 1", "risk >= 0.5", ""]}, + {expression: "deny", fields: {r: "'deny'", risk: "risk"}}, + {expression: "refer", fields: {r: "'refer'", risk: "risk"}}, + {expression: "accept", fields: {r: "'accept'", risk: "risk"}}, + ], + edges: [ + "input -> s1", "s1:0 -> assess -> s2", "s1:1 -> uninsured -> s2", + "s2:0 -> deny -> output", "s2:1 -> refer -> output", "s2:2 -> accept -> output", + ], + }, + cases: [ + [{insured: true, claims: 0}, {r: "accept", risk: 0}], + [{insured: true, claims: 2}, {r: "refer", risk: 0.5}], + [{insured: true, claims: 9}, {r: "deny", risk: 1}], + [{insured: false, claims: 0}, {r: "deny", risk: 1}], + ], +} + +{ + name: "a sub-decision loop on one branch, a single call on the other", + decisions: { + price: {nodes: [{expression: "e", fields: {p: "base * 1.1"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["batch", ""]}, + {decision: "many", key: "price", inputField: "items", outputPath: "prices", executionMode: "loop"}, + {decision: "one", key: "price", inputField: "item", outputPath: "prices"}, + ], + edges: ["input -> s", "s:0 -> many -> output", "s:1 -> one -> output"], + }, + cases: [ + [{batch: true, items: [{base: 10}, {base: 20}]}, {prices: [{p: 11}, {p: 22}]}], + [{batch: false, item: {base: 100}}, {prices: {p: 110}}], + [{batch: true, items: []}, {prices: []}], + ], +} + +{ + name: "collect branches call two sub-decisions that write disjoint keys", + decisions: { + left: {nodes: [{expression: "e", fields: {l: "v + 1"}}]}, + right: {nodes: [{expression: "e", fields: {r: "v - 1"}}]}, + }, + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["v > 0", "v < 10"]}, + {decision: "a", key: "left"}, + {decision: "b", key: "right"}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output"], + }, + cases: [ + [{v: 5}, {l: 6, r: 4}], + [{v: 20}, {l: 21}], + [{v: -5}, {r: -6}], + ], +} + +// --------------------------------------------------------------------------------------- +// Switches inside sub-decisions: the child routes on its own input; the parent sees only +// the child's result. +// --------------------------------------------------------------------------------------- + +{ + name: "a child with a switch called once through an inputField", + decisions: { + classify: { + nodes: [ + {switch: "s", when: ["age >= 65", "age >= 18", ""]}, + {expression: "senior", fields: {group: "'senior'"}}, + {expression: "adult", fields: {group: "'adult'"}}, + {expression: "minor", fields: {group: "'minor'"}}, + ], + edges: ["input -> s", "s:0 -> senior -> output", "s:1 -> adult -> output", "s:2 -> minor -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "classify", inputField: "person", outputPath: "person", passThrough: true}], + }, + cases: [ + [{person: {age: 70, name: "a"}, id: 1}, {person: {age: 70, name: "a", group: "senior"}, id: 1}], + [{person: {age: 18}}, {person: {age: 18, group: "adult"}}], + [{person: {}}, {person: {group: "minor"}}], + ], +} + +{ + name: "a child whose switch matches nothing returns an empty result", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["n > 0"]}, + {expression: "pos", fields: {pos: "true"}}, + ], + edges: ["input -> s", "s:0 -> pos -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "res", passThrough: true}], + }, + cases: [ + [{n: 1}, {n: 1, res: {pos: true}}], + [{n: 0}, {n: 0, res: {}}], + [{}, {res: {}}], + ], +} + +{ + name: "a child switch routing per item in loop mode", + decisions: { + route: { + nodes: [ + {switch: "s", when: ["type == 'refund'", "type == 'sale' and amount > 100", ""]}, + {expression: "refund", fields: {sign: "-1", amount: "amount"}}, + {expression: "big", fields: {sign: "1", amount: "amount", review: "true"}}, + {expression: "sale", fields: {sign: "1", amount: "amount"}}, + ], + edges: ["input -> s", "s:0 -> refund -> output", "s:1 -> big -> output", "s:2 -> sale -> output"], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "route", inputField: "txs", outputPath: "routed", executionMode: "loop"}, + {expression: "net", fields: {net: "sum(map(routed, #.sign * #.amount))", reviews: "len(filter(routed, #.review == true))"}}, + ], + }, + cases: [ + [{txs: [{type: "sale", amount: 50}, {type: "refund", amount: 20}, {type: "sale", amount: 200}]}, {net: 230, reviews: 1}], + [{txs: [{type: "refund", amount: 500}]}, {net: -500, reviews: 0}], + [{txs: [{type: "other", amount: 1000}]}, {net: 1000, reviews: 0}], + [{txs: []}, {net: 0, reviews: 0}], + ], +} + +{ + name: "a child collect switch per item", + decisions: { + tags: { + nodes: [ + {switch: "s", hit: "collect", when: ["price > 100", "stock == 0", "onSale"]}, + {expression: "a", fields: {premium: "true"}}, + {expression: "b", fields: {soldOut: "true"}}, + {expression: "c", fields: {sale: "true"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output"], + }, + }, + graph: { + nodes: [{decision: "each", key: "tags", inputField: "products", outputPath: "tags", executionMode: "loop"}], + }, + cases: [ + [{products: [{price: 200, stock: 0, onSale: true}, {price: 5, stock: 1}]}, {tags: [{premium: true, soldOut: true, sale: true}, {}]}], + [{products: [{price: 101, stock: 3}]}, {tags: [{premium: true}]}], + ], +} + +{ + name: "a child switch with no match per item yields empty objects", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["v > 0"]}, + {expression: "pos", fields: {pos: "v"}}, + ], + edges: ["input -> s", "s:0 -> pos -> output"], + }, + }, + graph: { + nodes: [{decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{v: 1}, {v: 0}, {v: 2}]}, {out: [{pos: 1}, {}, {pos: 2}]}], + [{items: [{v: -1}]}, {out: [{}]}], + ], +} + +{ + name: "a parent switch routes on what a child switch decided", + decisions: { + tier: { + nodes: [ + {switch: "s", when: ["spend >= 1000", "spend >= 100", ""]}, + {expression: "gold", fields: {tier: "'gold'"}}, + {expression: "silver", fields: {tier: "'silver'"}}, + {expression: "bronze", fields: {tier: "'bronze'"}}, + ], + edges: ["input -> s", "s:0 -> gold -> output", "s:1 -> silver -> output", "s:2 -> bronze -> output"], + }, + }, + graph: { + nodes: [ + {decision: "call", key: "tier", passThrough: true}, + {switch: "s", when: ["tier == 'gold'", ""]}, + {expression: "vip", fields: {lounge: "true", tier: "tier"}}, + {expression: "reg", fields: {lounge: "false", tier: "tier"}}, + ], + edges: ["input -> call -> s", "s:0 -> vip -> output", "s:1 -> reg -> output"], + }, + cases: [ + [{spend: 1000}, {lounge: true, tier: "gold"}], + [{spend: 999}, {lounge: false, tier: "silver"}], + [{spend: 0}, {lounge: false, tier: "bronze"}], + [{}, {lounge: false, tier: "bronze"}], + ], +} + +{ + name: "switches nested across two sub-decision levels", + decisions: { + outer: { + nodes: [ + {switch: "s", when: ["domestic", ""]}, + {decision: "dom", key: "inner"}, + {expression: "intl", fields: {rate: "25"}}, + ], + edges: ["input -> s", "s:0 -> dom -> output", "s:1 -> intl -> output"], + }, + inner: { + nodes: [ + {switch: "s", when: ["express", ""]}, + {expression: "fast", fields: {rate: "15"}}, + {expression: "slow", fields: {rate: "5"}}, + ], + edges: ["input -> s", "s:0 -> fast -> output", "s:1 -> slow -> output"], + }, + }, + graph: { + nodes: [ + {switch: "s", when: ["free", ""]}, + {expression: "zero", fields: {rate: "0"}}, + {decision: "call", key: "outer"}, + ], + edges: ["input -> s", "s:0 -> zero -> output", "s:1 -> call -> output"], + }, + cases: [ + [{free: true, domestic: true, express: true}, {rate: 0}], + [{domestic: true, express: true}, {rate: 15}], + [{domestic: true}, {rate: 5}], + [{domestic: false, express: true}, {rate: 25}], + ], +} + +{ + name: "a child switch reading $nodes sees only the child's nodes", + decisions: { + child: { + nodes: [ + {expression: "own", fields: {k: "1"}}, + {switch: "s", when: ["$nodes.own.k == 1 and $nodes.parentNode == null", ""]}, + {expression: "isolated", fields: {r: "'isolated'"}}, + {expression: "leaked", fields: {r: "'leaked'"}}, + ], + edges: ["input -> own -> s", "s:0 -> isolated -> output", "s:1 -> leaked -> output"], + }, + }, + graph: { + nodes: [ + {expression: "parentNode", passThrough: true, fields: {p: "1"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{}, {r: "isolated"}], + [{x: 1}, {r: "isolated"}], + ], +} + +{ + name: "a child switch reading $nodes.input sees the child's input", + decisions: { + child: { + nodes: [ + {expression: "drop", fields: {only: "1"}}, + {switch: "s", when: ["$nodes.input.flag", ""]}, + {expression: "y", fields: {r: "'flag'"}}, + {expression: "n", fields: {r: "'no flag'"}}, + ], + edges: ["input -> drop -> s", "s:0 -> y -> output", "s:1 -> n -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub"}], + }, + cases: [ + [{sub: {flag: true}, flag: false}, {r: "flag"}], + [{sub: {flag: false}, flag: true}, {r: "no flag"}], + [{sub: {}, flag: true}, {r: "no flag"}], + ], +} + +// --------------------------------------------------------------------------------------- +// passThrough, inputField and outputPath on the nodes of switch branches. +// --------------------------------------------------------------------------------------- + +{ + name: "branches writing under different outputPaths", + graph: { + nodes: [ + {switch: "s", when: ["ok", ""]}, + {expression: "good", outputPath: "result.success", fields: {code: "200"}}, + {expression: "bad", outputPath: "result.failure", fields: {code: "500"}}, + ], + edges: ["input -> s", "s:0 -> good -> output", "s:1 -> bad -> output"], + }, + cases: [ + [{ok: true}, {result: {success: {code: 200}}}], + [{ok: false}, {result: {failure: {code: 500}}}], + [{}, {result: {failure: {code: 500}}}], + ], +} + +{ + name: "collect branches writing under a shared outputPath prefix deep-merge", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", ""]}, + {expression: "fa", outputPath: "flags.a", fields: {on: "true"}}, + {expression: "fb", outputPath: "flags.b", fields: {on: "true"}}, + {expression: "fz", outputPath: "flags", fields: {count: "(a ? 1 : 0) + (b ? 1 : 0)"}}, + ], + edges: ["input -> s", "s:0 -> fa -> output", "s:1 -> fb -> output", "s:2 -> fz -> output"], + }, + cases: [ + [{a: true, b: true}, {flags: {a: {on: true}, b: {on: true}, count: 2}}], + [{a: true, b: false}, {flags: {a: {on: true}, count: 1}}], + [{a: false, b: false}, {flags: {count: 0}}], + ], +} + +{ + name: "passThrough branches with outputPath keep the input", + graph: { + nodes: [ + {switch: "s", when: ["kind == 'p'", ""]}, + {expression: "person", passThrough: true, outputPath: "meta", fields: {label: "first + ' ' + last"}}, + {expression: "company", passThrough: true, outputPath: "meta", fields: {label: "upper(name)"}}, + ], + edges: ["input -> s", "s:0 -> person -> output", "s:1 -> company -> output"], + }, + cases: [ + [{kind: "p", first: "a", last: "b"}, {kind: "p", first: "a", last: "b", meta: {label: "a b"}}], + [{kind: "c", name: "acme"}, {kind: "c", name: "acme", meta: {label: "ACME"}}], + [{kind: "c", name: "acme", meta: {id: 7}}, {kind: "c", name: "acme", meta: {id: 7, label: "ACME"}}], + ], +} + +{ + name: "branches with inputField select different parts of the switch input", + graph: { + nodes: [ + {switch: "s", when: ["side == 'buy'", ""]}, + {expression: "buy", inputField: "bid", fields: {px: "price", qty: "size"}}, + {expression: "sell", inputField: "ask", fields: {px: "price", qty: "size"}}, + ], + edges: ["input -> s", "s:0 -> buy -> output", "s:1 -> sell -> output"], + }, + cases: [ + [{side: "buy", bid: {price: 99, size: 1}, ask: {price: 101, size: 2}}, {px: 99, qty: 1}], + [{side: "sell", bid: {price: 99, size: 1}, ask: {price: 101, size: 2}}, {px: 101, qty: 2}], + [{side: "sell", bid: {price: 99, size: 1}}, {}], + ], +} + +{ + name: "a branch with inputField, outputPath and passThrough writes back in place", + graph: { + nodes: [ + {switch: "s", when: ["normalize", ""]}, + {expression: "norm", inputField: "addr", outputPath: "addr", passThrough: true, fields: {city: "upper(city)", zip: "trim(zip)"}}, + ], + edges: ["input -> s", "s:0 -> norm -> output", "s:1 -> output"], + }, + cases: [ + [{normalize: true, addr: {city: "paris", zip: " 75 ", line: "x"}}, {normalize: true, addr: {city: "PARIS", zip: "75", line: "x"}}], + [{normalize: false, addr: {city: "paris", zip: " 75 "}}, {normalize: false, addr: {city: "paris", zip: " 75 "}}], + ], +} + +{ + name: "a node with outputPath before the switch: conditions read through the path", + graph: { + nodes: [ + {expression: "calc", outputPath: "calc", passThrough: true, fields: {total: "a + b"}}, + {switch: "s", when: ["calc.total > 10", "total != null", ""]}, + {expression: "big", fields: {r: "'big'", t: "calc.total"}}, + {expression: "flat", fields: {r: "'flat'"}}, + {expression: "small", fields: {r: "'small'", t: "calc.total"}}, + ], + edges: ["input -> calc -> s", "s:0 -> big -> output", "s:1 -> flat -> output", "s:2 -> small -> output"], + }, + cases: [ + [{a: 10, b: 1}, {r: "big", t: 11}], + [{a: 1, b: 1}, {r: "small", t: 2}], + [{a: 1, b: 1, total: 99}, {r: "flat"}], + ], +} + +{ + name: "a table with outputPath on each of two branches converging on one node", + graph: { + nodes: [ + {switch: "s", when: ["country == 'US'", ""]}, + {table: "us", outputPath: "tax", inputs: ["state"], outputs: ["rate"], rules: [ + ["'CA'", "0.07"], + ["", "0.05"], + ]}, + {table: "eu", outputPath: "tax", inputs: ["country"], outputs: ["rate"], rules: [ + ["'DE'", "0.19"], + ["'FR'", "0.2"], + ]}, + {expression: "final", fields: {rate: "tax.rate ?? 0", hasRate: "tax != null"}}, + ], + edges: ["input -> s", "s:0 -> us -> final", "s:1 -> eu -> final", "final -> output"], + }, + cases: [ + [{country: "US", state: "CA"}, {rate: 0.07, hasRate: true}], + [{country: "US", state: "NV"}, {rate: 0.05, hasRate: true}], + [{country: "DE"}, {rate: 0.19, hasRate: true}], + [{country: "JP"}, {rate: 0, hasRate: false}], + ], +} + +{ + name: "a switch passes a non-object input from a loop straight to a branch", + graph: { + nodes: [ + {expression: "each", inputField: "items", executionMode: "loop", fields: {v: "$root"}}, + {switch: "s", when: ["len($root) > 0", ""]}, + {expression: "count", fields: {n: "len($root)"}}, + ], + edges: ["input -> each -> s", "s:0 -> count -> output", "s:1 -> output"], + }, + cases: [ + [{items: [1, 2]}, {n: 2}], + [{items: []}, []], + ], +} + +// --------------------------------------------------------------------------------------- +// Loops whose bodies route through a switch in a child, combined with transforms on the +// parent: passThrough over items, and a second loop after the routed one. +// --------------------------------------------------------------------------------------- + +{ + name: "a child switch per item with passThrough enriches each item", + decisions: { + band: { + nodes: [ + {switch: "s", when: ["score >= 80", "score >= 50", ""]}, + {expression: "a", fields: {band: "'A'"}}, + {expression: "b", fields: {band: "'B'"}}, + {expression: "c", fields: {band: "'C'"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output"], + }, + }, + graph: { + nodes: [{decision: "each", key: "band", inputField: "rows", outputPath: "rows", passThrough: true, executionMode: "loop"}], + }, + cases: [ + [{rows: [{id: 1, score: 90}, {id: 2, score: 50}, {id: 3, score: 0}]}, {rows: [{id: 1, score: 90, band: "A"}, {id: 2, score: 50, band: "B"}, {id: 3, score: 0, band: "C"}]}], + [{rows: [{id: 1}]}, {rows: [{id: 1, band: "C"}]}], + [{rows: [], keep: true}, {rows: [], keep: true}], + ], +} + +{ + name: "a routed loop followed by a second loop over its results", + decisions: { + route: { + nodes: [ + {switch: "s", when: ["qty > 10", ""]}, + {expression: "bulk", fields: {unit: "price * 0.9", qty: "qty"}}, + {expression: "retail", fields: {unit: "price", qty: "qty"}}, + ], + edges: ["input -> s", "s:0 -> bulk -> output", "s:1 -> retail -> output"], + }, + }, + graph: { + nodes: [ + {decision: "priced", key: "route", inputField: "lines", outputPath: "priced", executionMode: "loop"}, + {expression: "totals", inputField: "priced", outputPath: "totals", executionMode: "loop", fields: {t: "unit * qty"}}, + ], + }, + cases: [ + [{lines: [{price: 10, qty: 20}, {price: 10, qty: 1}]}, {totals: [{t: 180}, {t: 10}]}], + [{lines: []}, {totals: []}], + ], +} + +{ + name: "a switch inside a loop child fails for one item and fails the parent", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["ok", ""]}, + {expression: "good", fields: {r: "'ok'"}}, + {custom: "bad", kind: "fail", config: {message: "item rejected"}}, + ], + edges: ["input -> s", "s:0 -> good -> output", "s:1 -> bad -> output"], + }, + }, + graph: { + nodes: [{decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{ok: true}, {ok: true}]}, {out: [{r: "ok"}, {r: "ok"}]}], + [{items: [{ok: true}, {ok: false}]}, "!error"], + [{items: []}, {out: []}], + ], +} diff --git a/core/engine/tests/spec/graph/25-graph-topologies.json5 b/core/engine/tests/spec/graph/25-graph-topologies.json5 new file mode 100644 index 00000000..10508c24 --- /dev/null +++ b/core/engine/tests/spec/graph/25-graph-topologies.json5 @@ -0,0 +1,892 @@ +// Graph topologies: diamonds, wide fan-outs, long chains, dead ends and nodes reachable by +// several paths through switches. A node runs once, after all its parents have run, with +// the merge of its parents' outputs (the first declared edge into it wins conflicts). +// The walk stops at the first output node it reaches; the result merges every visited +// leaf. Switches prune the edges of untaken branches and every node left without parents. + +// --------------------------------------------------------------------------------------- +// Diamonds with different apexes, middles and depths. +// --------------------------------------------------------------------------------------- + +{ + name: "a diamond with a table and an expression in the middle", + graph: { + nodes: [ + {expression: "top", fields: {amount: "qty * price", tier: "tier"}}, + {table: "rate", inputs: ["tier"], outputs: ["rate"], rules: [ + ["'gold'", "0.1"], + ["'silver'", "0.05"], + ["", "0"], + ]}, + {expression: "ship", fields: {shipping: "amount >= 100 ? 0 : 9"}}, + {expression: "bottom", fields: {shipping: "shipping", rate: "rate"}}, + ], + edges: ["input -> top", "top -> rate -> bottom", "top -> ship -> bottom", "bottom -> output"], + }, + cases: [ + [{qty: 2, price: 50, tier: "gold"}, {shipping: 0, rate: 0.1}], + [{qty: 1, price: 50, tier: "silver"}, {shipping: 9, rate: 0.05}], + [{qty: 1, price: 50}, {shipping: 9, rate: 0}], + [{qty: 0, price: 0, tier: "gold"}, {shipping: 9, rate: 0.1}], + ], +} + +{ + name: "a diamond with arms of different lengths", + graph: { + nodes: [ + {expression: "a", fields: {v: "x"}}, + {expression: "short", fields: {s: "v + 1"}}, + {expression: "l1", fields: {l: "v * 2"}}, + {expression: "l2", fields: {l: "l * 2"}}, + {expression: "l3", fields: {l: "l * 2"}}, + {expression: "join", fields: {s: "s", l: "l"}}, + ], + edges: ["input -> a", "a -> short -> join", "a -> l1 -> l2 -> l3 -> join", "join -> output"], + }, + cases: [ + [{x: 1}, {s: 2, l: 8}], + [{x: 0}, {s: 1, l: 0}], + [{x: -2.5}, {s: -1.5, l: -20}], + ], +} + +{ + name: "a three-armed diamond whose arms rewrite the same key", + graph: { + nodes: [ + {expression: "top", passThrough: true, fields: {v: "1"}}, + {expression: "a", passThrough: true, fields: {v: "v + 10", a: "true"}}, + {expression: "b", passThrough: true, fields: {v: "v + 20", b: "true"}}, + {expression: "c", passThrough: true, fields: {v: "v + 30", c: "true"}}, + {expression: "join", passThrough: true, fields: {seen: "v"}}, + ], + edges: ["input -> top", "top -> a", "top -> b", "top -> c", "b -> join", "c -> join", "a -> join", "join -> output"], + }, + cases: [ + [{}, {v: 21, a: true, b: true, c: true, seen: 21}], + [{v: 100, x: 1}, {v: 21, x: 1, a: true, b: true, c: true, seen: 21}], + ], +} + +{ + name: "a diamond whose apex is a switch taking both arms (collect)", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", "n < 100"]}, + {expression: "lo", fields: {lo: "n"}}, + {expression: "hi", fields: {hi: "100 - n"}}, + {expression: "join", fields: {span: "(lo ?? 0) + (hi ?? 0)", both: "lo != null and hi != null"}}, + ], + edges: ["input -> s", "s:0 -> lo -> join", "s:1 -> hi -> join", "join -> output"], + }, + cases: [ + [{n: 30}, {span: 100, both: true}], + [{n: 200}, {span: 200, both: false}], + [{n: -5}, {span: 105, both: false}], + [{n: 0}, {span: 100, both: false}], + ], +} + +{ + name: "a diamond whose apex is the input and whose bottom is the output", + graph: { + nodes: [ + {expression: "a", fields: {a: "x + 1"}}, + {expression: "b", fields: {b: "x + 2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{x: 1}, {a: 2, b: 3}], + [{x: 1.5}, {a: 2.5, b: 3.5}], + ], +} + +{ + name: "stacked diamonds: the bottom of one is the apex of the next", + graph: { + nodes: [ + {expression: "a1", fields: {p: "x + 1"}}, + {expression: "b1", fields: {q: "x * 2"}}, + {expression: "m1", fields: {v: "p + q"}}, + {expression: "a2", fields: {p: "v + 1"}}, + {expression: "b2", fields: {q: "v * 2"}}, + {expression: "m2", fields: {v: "p + q"}}, + {expression: "a3", fields: {p: "v + 1"}}, + {expression: "b3", fields: {q: "v * 2"}}, + {expression: "m3", fields: {v: "p + q"}}, + ], + edges: [ + "input -> a1 -> m1", "input -> b1 -> m1", + "m1 -> a2 -> m2", "m1 -> b2 -> m2", + "m2 -> a3 -> m3", "m2 -> b3 -> m3", + "m3 -> output", + ], + }, + cases: [ + [{x: 0}, {v: 13}], + [{x: 1}, {v: 40}], + [{x: -1}, {v: -14}], + ], +} + +{ + name: "a diamond whose arms are sub-decisions", + decisions: { + left: {nodes: [{expression: "e", fields: {l: "x * 2"}}]}, + right: {nodes: [{expression: "e", fields: {r: "x * 3"}}]}, + }, + graph: { + nodes: [ + {expression: "top", fields: {x: "x + 1"}}, + {decision: "dl", key: "left"}, + {decision: "dr", key: "right"}, + {expression: "join", fields: {sum: "l + r"}}, + ], + edges: ["input -> top", "top -> dl -> join", "top -> dr -> join", "join -> output"], + }, + cases: [ + [{x: 0}, {sum: 5}], + [{x: 1}, {sum: 10}], + ], +} + +{ + name: "a diamond with one arm erroring fails the graph", + graph: { + nodes: [ + {expression: "top", passThrough: true, fields: {}}, + {expression: "ok", fields: {ok: "true"}}, + {expression: "bad", fields: {bad: "date(d) > date('2020-01-01')"}}, + {expression: "join", fields: {ok: "ok", bad: "bad"}}, + ], + edges: ["input -> top", "top -> ok -> join", "top -> bad -> join", "join -> output"], + }, + cases: [ + [{d: "2021-01-01"}, {ok: true, bad: true}], + [{d: "2019-01-01"}, {ok: true, bad: false}], + [{d: "not a date"}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------- +// Wide fan-outs: six or more nodes in parallel from one parent, meeting at the output or +// at a join node. +// --------------------------------------------------------------------------------------- + +{ + name: "six parallel nodes with disjoint keys meet at the output", + graph: { + nodes: [ + {expression: "n1", fields: {sum: "a + b"}}, + {expression: "n2", fields: {diff: "a - b"}}, + {expression: "n3", fields: {prod: "a * b"}}, + {expression: "n4", fields: {max: "max([a, b])"}}, + {expression: "n5", fields: {min: "min([a, b])"}}, + {expression: "n6", fields: {eq: "a == b"}}, + ], + edges: [ + "input -> n1 -> output", "input -> n2 -> output", "input -> n3 -> output", + "input -> n4 -> output", "input -> n5 -> output", "input -> n6 -> output", + ], + }, + cases: [ + [{a: 3, b: 2}, {sum: 5, diff: 1, prod: 6, max: 3, min: 2, eq: false}], + [{a: 2, b: 2}, {sum: 4, diff: 0, prod: 4, max: 2, min: 2, eq: true}], + [{a: -1, b: 0.5}, {sum: -0.5, diff: -1.5, prod: -0.5, max: 0.5, min: -1, eq: false}], + ], +} + +{ + name: "eight parallel nodes of mixed kinds meet at a join", + graph: { + nodes: [ + {expression: "e1", fields: {e1: "v + 1"}}, + {expression: "e2", fields: {e2: "v + 2"}}, + {table: "t1", inputs: ["v"], outputs: ["t1"], rules: [["> 0", "'pos'"], ["", "'non'"]]}, + {table: "t2", inputs: ["v"], outputs: ["t2"], rules: [["0", "'zero'"]]}, + {function: "f1", source: """export const handler = async (input) => ({ f1: typeof input.v });"""}, + {custom: "c1", kind: "config", config: {c1: "static"}}, + {custom: "c2", kind: "render", config: {c2: "v={{ v }}"}}, + {expression: "e3", outputPath: "nested", fields: {e3: "v * 3"}}, + {expression: "join", passThrough: true, fields: {hasT2: "t2 != null"}}, + ], + edges: [ + "input -> e1 -> join", "input -> e2 -> join", "input -> t1 -> join", "input -> t2 -> join", + "input -> f1 -> join", "input -> c1 -> join", "input -> c2 -> join", "input -> e3 -> join", + "join -> output", + ], + }, + cases: [ + [{v: 1}, {e1: 2, e2: 3, t1: "pos", f1: "number", c1: "static", c2: "v=1", nested: {e3: 3}, hasT2: false}], + [{v: 0}, {e1: 1, e2: 2, t1: "non", t2: "zero", f1: "number", c1: "static", c2: "v=0", nested: {e3: 0}, hasT2: true}], + ], +} + +{ + name: "twelve parallel nodes writing the same key: the first declared edge into the output wins", + graph: { + nodes: [ + {expression: "p01", fields: {w: "1", p01: "true"}}, + {expression: "p02", fields: {w: "2", p02: "true"}}, + {expression: "p03", fields: {w: "3", p03: "true"}}, + {expression: "p04", fields: {w: "4", p04: "true"}}, + {expression: "p05", fields: {w: "5", p05: "true"}}, + {expression: "p06", fields: {w: "6", p06: "true"}}, + {expression: "p07", fields: {w: "7", p07: "true"}}, + {expression: "p08", fields: {w: "8", p08: "true"}}, + {expression: "p09", fields: {w: "9", p09: "true"}}, + {expression: "p10", fields: {w: "10", p10: "true"}}, + {expression: "p11", fields: {w: "11", p11: "true"}}, + {expression: "p12", fields: {w: "12", p12: "true"}}, + ], + edges: [ + "input -> p01", "input -> p02", "input -> p03", "input -> p04", "input -> p05", "input -> p06", + "input -> p07", "input -> p08", "input -> p09", "input -> p10", "input -> p11", "input -> p12", + "p07 -> output", "p01 -> output", "p02 -> output", "p03 -> output", "p04 -> output", "p05 -> output", + "p06 -> output", "p08 -> output", "p09 -> output", "p10 -> output", "p11 -> output", "p12 -> output", + ], + }, + cases: [ + [{}, {w: 7, p01: true, p02: true, p03: true, p04: true, p05: true, p06: true, p07: true, p08: true, p09: true, p10: true, p11: true, p12: true}], + ], +} + +{ + name: "a wide fan-out where some parallel nodes produce nothing", + graph: { + nodes: [ + {table: "t1", inputs: ["a"], outputs: ["a1"], rules: [["> 0", "true"]]}, + {table: "t2", inputs: ["b"], outputs: ["b1"], rules: [["> 0", "true"]]}, + {table: "t3", inputs: ["c"], outputs: ["c1"], rules: [["> 0", "true"]]}, + {table: "t4", inputs: ["d"], outputs: ["d1"], rules: [["> 0", "true"]]}, + {table: "t5", inputs: ["e"], outputs: ["e1"], rules: [["> 0", "true"]]}, + {table: "t6", inputs: ["f"], outputs: ["f1"], rules: [["> 0", "true"]]}, + {expression: "count", fields: {hits: "len(filter([a1, b1, c1, d1, e1, f1], # == true))"}}, + ], + edges: [ + "input -> t1 -> count", "input -> t2 -> count", "input -> t3 -> count", + "input -> t4 -> count", "input -> t5 -> count", "input -> t6 -> count", + "count -> output", + ], + }, + cases: [ + [{a: 1, b: 1, c: 1, d: 1, e: 1, f: 1}, {hits: 6}], + [{a: 1, c: 1, e: 1}, {hits: 3}], + [{}, {hits: 0}], + ], +} + +{ + name: "a fan-out from a mid-graph node, each child read through $nodes by the join", + graph: { + nodes: [ + {expression: "base", fields: {v: "x * 10"}}, + {expression: "c1", fields: {r: "v + 1"}}, + {expression: "c2", fields: {r: "v + 2"}}, + {expression: "c3", fields: {r: "v + 3"}}, + {expression: "c4", fields: {r: "v + 4"}}, + {expression: "c5", fields: {r: "v + 5"}}, + {expression: "c6", fields: {r: "v + 6"}}, + {expression: "join", fields: { + all: "[$nodes.c1.r, $nodes.c2.r, $nodes.c3.r, $nodes.c4.r, $nodes.c5.r, $nodes.c6.r]", + merged: "r", + }}, + ], + edges: [ + "input -> base", + "base -> c1 -> join", "base -> c2 -> join", "base -> c3 -> join", + "base -> c4 -> join", "base -> c5 -> join", "base -> c6 -> join", + "join -> output", + ], + }, + cases: [ + [{x: 1}, {all: [11, 12, 13, 14, 15, 16], merged: 11}], + [{x: 0}, {all: [1, 2, 3, 4, 5, 6], merged: 1}], + ], +} + +{ + name: "a wide fan-out where one parallel node fails fails the graph", + graph: { + nodes: [ + {expression: "a", fields: {a: "1"}}, + {expression: "b", fields: {b: "2"}}, + {expression: "c", fields: {c: "3"}}, + {custom: "boom", kind: "fail", config: {message: "parallel failure"}}, + {expression: "d", fields: {d: "4"}}, + {expression: "e", fields: {e: "5"}}, + ], + edges: [ + "input -> a -> output", "input -> b -> output", "input -> c -> output", + "input -> boom -> output", "input -> d -> output", "input -> e -> output", + ], + }, + cases: [ + [{}, "!error"], + [{x: 1}, "!error"], + ], +} + +{ + name: "a fan-out into six chains of two meeting at the output", + graph: { + nodes: [ + {expression: "a1", fields: {v: "x + 1"}}, {expression: "a2", fields: {a: "v * 2"}}, + {expression: "b1", fields: {v: "x + 2"}}, {expression: "b2", fields: {b: "v * 2"}}, + {expression: "c1", fields: {v: "x + 3"}}, {expression: "c2", fields: {c: "v * 2"}}, + {expression: "d1", fields: {v: "x + 4"}}, {expression: "d2", fields: {d: "v * 2"}}, + {expression: "e1", fields: {v: "x + 5"}}, {expression: "e2", fields: {e: "v * 2"}}, + {expression: "f1", fields: {v: "x + 6"}}, {expression: "f2", fields: {f: "v * 2"}}, + ], + edges: [ + "input -> a1 -> a2 -> output", "input -> b1 -> b2 -> output", "input -> c1 -> c2 -> output", + "input -> d1 -> d2 -> output", "input -> e1 -> e2 -> output", "input -> f1 -> f2 -> output", + ], + }, + cases: [ + [{x: 0}, {a: 2, b: 4, c: 6, d: 8, e: 10, f: 12}], + [{x: 1}, {a: 4, b: 6, c: 8, d: 10, e: 12, f: 14}], + ], +} + +// --------------------------------------------------------------------------------------- +// Long chains: ten or more nodes in a row. Each node only sees its parent's output. +// --------------------------------------------------------------------------------------- + +{ + name: "a chain of ten pass-through nodes accumulates every key", + graph: { + nodes: [ + {expression: "k01", passThrough: true, fields: {n: "n + 1", k01: "n"}}, + {expression: "k02", passThrough: true, fields: {n: "n + 1", k02: "n"}}, + {expression: "k03", passThrough: true, fields: {n: "n + 1", k03: "n"}}, + {expression: "k04", passThrough: true, fields: {n: "n + 1", k04: "n"}}, + {expression: "k05", passThrough: true, fields: {n: "n + 1", k05: "n"}}, + {expression: "k06", passThrough: true, fields: {n: "n + 1", k06: "n"}}, + {expression: "k07", passThrough: true, fields: {n: "n + 1", k07: "n"}}, + {expression: "k08", passThrough: true, fields: {n: "n + 1", k08: "n"}}, + {expression: "k09", passThrough: true, fields: {n: "n + 1", k09: "n"}}, + {expression: "k10", passThrough: true, fields: {n: "n + 1", k10: "n"}}, + ], + }, + cases: [ + [{n: 0}, {n: 10, k01: 0, k02: 1, k03: 2, k04: 3, k05: 4, k06: 5, k07: 6, k08: 7, k09: 8, k10: 9}], + [{n: 100}, {n: 110, k01: 100, k02: 101, k03: 102, k04: 103, k05: 104, k06: 105, k07: 106, k08: 107, k09: 108, k10: 109}], + [{}, "!error"], + ], +} + +{ + name: "a chain of twelve non-pass-through nodes keeps only the last output", + graph: { + nodes: [ + {expression: "s01", fields: {v: "v * 2"}}, + {expression: "s02", fields: {v: "v + 1"}}, + {expression: "s03", fields: {v: "v * 2"}}, + {expression: "s04", fields: {v: "v + 1"}}, + {expression: "s05", fields: {v: "v * 2"}}, + {expression: "s06", fields: {v: "v + 1"}}, + {expression: "s07", fields: {v: "v * 2"}}, + {expression: "s08", fields: {v: "v + 1"}}, + {expression: "s09", fields: {v: "v * 2"}}, + {expression: "s10", fields: {v: "v + 1"}}, + {expression: "s11", fields: {v: "v * 2"}}, + {expression: "s12", fields: {v: "v + 1", origin: "$nodes.input.v"}}, + ], + }, + cases: [ + [{v: 0, other: 1}, {v: 63, origin: 0}], + [{v: 1, other: 1}, {v: 127, origin: 1}], + [{v: -1}, {v: -1, origin: -1}], + ], +} + +{ + name: "a chain alternating tables and expressions", + graph: { + nodes: [ + {table: "t1", inputs: ["income"], outputs: ["bracket"], rules: [[">= 100000", "3"], [">= 40000", "2"], ["", "1"]]}, + {expression: "e1", passThrough: true, fields: {rate: "bracket * 0.1"}}, + {table: "t2", passThrough: true, inputs: ["bracket"], outputs: ["label"], rules: [["3", "'high'"], ["2", "'mid'"], ["", "'low'"]]}, + {expression: "e2", passThrough: true, fields: {pct: "string(bracket * 10) + '%'"}}, + {table: "t3", passThrough: true, inputs: ["label"], outputs: ["review"], rules: [["'high'", "true"], ["", "false"]]}, + {expression: "e3", passThrough: true, fields: {summary: "label + ' ' + pct"}}, + {table: "t4", passThrough: true, inputs: ["review"], outputs: ["queue"], rules: [["true", "'manual'"], ["", "'auto'"]]}, + {expression: "e4", passThrough: true, fields: {done: "true"}}, + {table: "t5", passThrough: true, inputs: ["queue"], outputs: ["sla"], rules: [["'manual'", "48"], ["", "1"]]}, + {expression: "e5", fields: {summary: "summary", queue: "queue", sla: "sla", done: "done"}}, + ], + }, + cases: [ + [{income: 150000}, {summary: "high 30%", queue: "manual", sla: 48, done: true}], + [{income: 50000}, {summary: "mid 20%", queue: "auto", sla: 1, done: true}], + [{income: 0}, {summary: "low 10%", queue: "auto", sla: 1, done: true}], + [{}, {summary: "low 10%", queue: "auto", sla: 1, done: true}], + ], +} + +{ + name: "a long chain where a mid node drops the original input", + graph: { + nodes: [ + {expression: "c01", passThrough: true, fields: {a: "1"}}, + {expression: "c02", passThrough: true, fields: {b: "2"}}, + {expression: "c03", passThrough: true, fields: {c: "3"}}, + {expression: "c04", passThrough: true, fields: {d: "4"}}, + {expression: "c05", fields: {sum: "a + b + c + d"}}, + {expression: "c06", passThrough: true, fields: {e: "5"}}, + {expression: "c07", passThrough: true, fields: {f: "6"}}, + {expression: "c08", passThrough: true, fields: {g: "7"}}, + {expression: "c09", passThrough: true, fields: {h: "8"}}, + {expression: "c10", passThrough: true, fields: {lost: "a == null and x == null"}}, + ], + }, + cases: [ + [{x: 1}, {sum: 10, e: 5, f: 6, g: 7, h: 8, lost: true}], + [{}, {sum: 10, e: 5, f: 6, g: 7, h: 8, lost: true}], + ], +} + +{ + name: "a fifteen-node chain where each node reads the previous one through $nodes", + graph: { + nodes: [ + {expression: "n01", fields: {v: "$nodes.input.v + 1"}}, + {expression: "n02", fields: {v: "$nodes.n01.v + 1"}}, + {expression: "n03", fields: {v: "$nodes.n02.v + 1"}}, + {expression: "n04", fields: {v: "$nodes.n03.v + 1"}}, + {expression: "n05", fields: {v: "$nodes.n04.v + 1"}}, + {expression: "n06", fields: {v: "$nodes.n05.v + 1"}}, + {expression: "n07", fields: {v: "$nodes.n06.v + 1"}}, + {expression: "n08", fields: {v: "$nodes.n07.v + 1"}}, + {expression: "n09", fields: {v: "$nodes.n08.v + 1"}}, + {expression: "n10", fields: {v: "$nodes.n09.v + 1"}}, + {expression: "n11", fields: {v: "$nodes.n10.v + 1"}}, + {expression: "n12", fields: {v: "$nodes.n11.v + 1"}}, + {expression: "n13", fields: {v: "$nodes.n12.v + 1"}}, + {expression: "n14", fields: {v: "$nodes.n13.v + 1"}}, + {expression: "n15", fields: {v: "$nodes.n14.v + 1", first: "$nodes.n01.v", mid: "$nodes.n08.v"}}, + ], + }, + cases: [ + [{v: 0}, {v: 15, first: 1, mid: 8}], + [{v: -15}, {v: 0, first: -14, mid: -7}], + ], +} + +{ + name: "a chain of ten switches, each gate passing the input on", + graph: { + nodes: [ + {switch: "g1", when: ["n >= 1", ""]}, + {switch: "g2", when: ["n >= 2", ""]}, + {switch: "g3", when: ["n >= 3", ""]}, + {switch: "g4", when: ["n >= 4", ""]}, + {switch: "g5", when: ["n >= 5", ""]}, + {switch: "g6", when: ["n >= 6", ""]}, + {switch: "g7", when: ["n >= 7", ""]}, + {switch: "g8", when: ["n >= 8", ""]}, + {switch: "g9", when: ["n >= 9", ""]}, + {switch: "g10", when: ["n >= 10", ""]}, + {expression: "stop", fields: {passed: "min([max([n ?? 0, 0]), 10])"}}, + {expression: "all", fields: {passed: "10", all: "true"}}, + ], + edges: [ + "input -> g1", + "g1:0 -> g2", "g2:0 -> g3", "g3:0 -> g4", "g4:0 -> g5", "g5:0 -> g6", + "g6:0 -> g7", "g7:0 -> g8", "g8:0 -> g9", "g9:0 -> g10", "g10:0 -> all -> output", + "g1:1 -> stop", "g2:1 -> stop", "g3:1 -> stop", "g4:1 -> stop", "g5:1 -> stop", + "g6:1 -> stop", "g7:1 -> stop", "g8:1 -> stop", "g9:1 -> stop", "g10:1 -> stop", + "stop -> output", + ], + }, + cases: [ + [{n: 0}, {passed: 0}], + [{n: 1}, {passed: 1}], + [{n: 5}, {passed: 5}], + [{n: 9.5}, {passed: 9.5}], + [{n: 10}, {passed: 10, all: true}], + [{n: 1000}, {passed: 10, all: true}], + [{}, {passed: 0}], + ], +} + +{ + name: "a long chain with an error at the end", + graph: { + nodes: [ + {expression: "x1", passThrough: true, fields: {a: "1"}}, + {expression: "x2", passThrough: true, fields: {b: "2"}}, + {expression: "x3", passThrough: true, fields: {c: "3"}}, + {expression: "x4", passThrough: true, fields: {d: "4"}}, + {expression: "x5", passThrough: true, fields: {e: "5"}}, + {expression: "x6", passThrough: true, fields: {f: "6"}}, + {expression: "x7", passThrough: true, fields: {g: "7"}}, + {expression: "x8", passThrough: true, fields: {h: "8"}}, + {expression: "x9", passThrough: true, fields: {i: "9"}}, + {expression: "x10", passThrough: true, fields: {j: "upper(name)"}}, + ], + }, + cases: [ + [{name: "ok"}, {name: "ok", a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: "OK"}], + [{name: 5}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------- +// Dead ends: leaves other than the output node. A graph without an output node merges all +// its leaves; with an output node, a leaf contributes only if it ran before the output. +// --------------------------------------------------------------------------------------- + +{ + name: "a graph without an output node merges several dead ends", + graph: { + raw: { + nodes: [ + {id: "in", name: "input", type: "inputNode", content: {}}, + {id: "a", name: "a", type: "expressionNode", content: {expressions: [{id: "1", key: "a", value: "x + 1"}]}}, + {id: "b", name: "b", type: "expressionNode", content: {expressions: [{id: "1", key: "b", value: "x + 2"}]}}, + {id: "c", name: "c", type: "expressionNode", content: {expressions: [{id: "1", key: "c", value: "x + 3"}]}}, + {id: "c2", name: "c2", type: "expressionNode", content: {expressions: [{id: "1", key: "c2", value: "c * 10"}]}}, + ], + edges: [ + {id: "e1", sourceId: "in", targetId: "a"}, + {id: "e2", sourceId: "in", targetId: "b"}, + {id: "e3", sourceId: "in", targetId: "c"}, + {id: "e4", sourceId: "c", targetId: "c2"}, + ], + }, + }, + cases: [ + [{x: 0}, {a: 1, b: 2, c2: 30}], + [{x: 1}, {a: 2, b: 3, c2: 40}], + ], +} + +{ + name: "a graph without an output node: dead ends writing the same key", + graph: { + raw: { + nodes: [ + {id: "in", name: "input", type: "inputNode", content: {}}, + {id: "a", name: "a", type: "expressionNode", content: {expressions: [{id: "1", key: "k", value: "'a'"}]}}, + {id: "b", name: "b", type: "expressionNode", content: {expressions: [{id: "1", key: "k", value: "'b'"}]}}, + {id: "c", name: "c", type: "expressionNode", content: {expressions: [{id: "1", key: "k", value: "'c'"}]}}, + ], + edges: [ + {id: "e1", sourceId: "in", targetId: "a"}, + {id: "e2", sourceId: "in", targetId: "b"}, + {id: "e3", sourceId: "in", targetId: "c"}, + ], + }, + }, + cases: [ + [{}, {k: "c"}, "question: with no output node the leaves merge in node order, so the last declared node wins, unlike a join where the first declared edge wins"], + ], +} + +{ + name: "a graph whose only node is the input returns the input", + graph: { + raw: { + nodes: [{id: "in", name: "input", type: "inputNode", content: {}}], + edges: [], + }, + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + ], +} + +{ + name: "dead ends declared after the output path do not contribute", + graph: { + nodes: [ + {expression: "d1", fields: {d1: "1"}}, + {expression: "d2", fields: {d2: "2"}}, + {expression: "main", fields: {main: "true"}}, + ], + edges: ["input -> main -> output", "input -> d1", "input -> d2"], + }, + cases: [ + [{}, {main: true}], + ], +} + +{ + name: "dead ends declared before the output path contribute", + graph: { + nodes: [ + {expression: "d1", fields: {d1: "1"}}, + {expression: "d2", fields: {d2: "2"}}, + {expression: "main", fields: {main: "true"}}, + ], + edges: ["input -> d1", "input -> d2", "input -> main -> output"], + }, + cases: [ + [{}, {main: true, d1: 1, d2: 2}, "question: whether a leaf that never reaches the output node contributes depends on edge declaration order"], + ], +} + +{ + name: "a failing dead end visited before the output fails the graph", + graph: { + nodes: [ + {custom: "boom", kind: "fail", config: {message: "dead end failed"}}, + {expression: "main", fields: {main: "true"}}, + ], + edges: ["input -> boom", "input -> main -> output"], + }, + cases: [ + [{}, "!error"], + ], +} + +{ + name: "a failing dead end visited after the output never runs", + graph: { + nodes: [ + {custom: "boom", kind: "fail", config: {message: "dead end failed"}}, + {expression: "main", fields: {main: "true"}}, + ], + edges: ["input -> main -> output", "input -> boom"], + }, + cases: [ + [{}, {main: true}], + ], +} + +{ + name: "dead ends at the end of switch branches", + graph: { + nodes: [ + {switch: "s", when: ["a", "b", ""]}, + {expression: "da", fields: {da: "true"}}, + {expression: "db", fields: {db: "true"}}, + {expression: "def", fields: {def: "true"}}, + ], + edges: ["input -> s", "s:0 -> da", "s:1 -> db", "s:2 -> def -> output"], + }, + cases: [ + [{a: true}, {da: true}], + [{b: true}, {db: true}], + [{}, {def: true}], + ], +} + +{ + name: "dead ends at the end of collect switch branches all merge", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "da", fields: {da: "true"}}, + {expression: "db", fields: {db: "true"}}, + {expression: "dc", fields: {dc: "true"}}, + ], + edges: ["input -> s", "s:0 -> da", "s:1 -> db", "s:2 -> dc"], + }, + cases: [ + [{a: true, b: true, c: true}, {da: true, db: true, dc: true}], + [{b: true}, {db: true}], + [{}, {}], + ], +} + +{ + name: "a dead end hanging off a mid-chain node", + graph: { + nodes: [ + {expression: "a", fields: {v: "x + 1"}}, + {expression: "dead", fields: {dead: "v"}}, + {expression: "b", fields: {w: "v * 2"}}, + ], + edges: ["input -> a -> b -> output", "a -> dead"], + }, + cases: [ + [{x: 1}, {w: 4}], + ], +} + +{ + name: "a dead end hanging off a mid-chain node, declared first", + graph: { + nodes: [ + {expression: "a", fields: {v: "x + 1"}}, + {expression: "dead", fields: {dead: "v"}}, + {expression: "b", fields: {w: "v * 2"}}, + ], + edges: ["a -> dead", "input -> a -> b -> output"], + }, + cases: [ + [{x: 1}, {w: 4, dead: 2}, "question: whether a leaf that never reaches the output node contributes depends on edge declaration order"], + ], +} + +// --------------------------------------------------------------------------------------- +// Nodes reachable by two paths whose switch outcomes differ: the node runs when at least +// one path survives, and sees only what the surviving paths produced. +// --------------------------------------------------------------------------------------- + +{ + name: "a node reachable directly from one branch and through a node from another", + graph: { + nodes: [ + {switch: "s", when: ["direct", ""]}, + {expression: "prep", fields: {prepared: "true", v: "v * 2"}}, + {expression: "target", fields: {v: "v", prepared: "prepared ?? false"}}, + ], + edges: ["input -> s", "s:0 -> target", "s:1 -> prep -> target", "target -> output"], + }, + cases: [ + [{direct: true, v: 5}, {v: 5, prepared: false}], + [{direct: false, v: 5}, {v: 10, prepared: true}], + [{v: 1}, {v: 2, prepared: true}], + ], +} + +{ + name: "a node reachable from two switches in sequence", + graph: { + nodes: [ + {switch: "s1", when: ["a", ""]}, + {expression: "mid", passThrough: true, fields: {mid: "true"}}, + {switch: "s2", when: ["b", ""]}, + {expression: "target", fields: {hit: "true", mid: "mid ?? false"}}, + {expression: "miss", fields: {hit: "false"}}, + ], + edges: [ + "input -> s1", "s1:0 -> target", "s1:1 -> mid -> s2", + "s2:0 -> target", "s2:1 -> miss -> output", + "target -> output", + ], + }, + cases: [ + [{a: true}, {hit: true, mid: false}], + [{a: false, b: true}, {hit: true, mid: true}], + [{a: false, b: false}, {hit: false}], + [{}, {hit: false}], + ], +} + +{ + name: "a node fed by two independent switches: runs when either routes to it", + graph: { + nodes: [ + {switch: "s1", when: ["a", ""]}, + {switch: "s2", when: ["b", ""]}, + {expression: "fromA", fields: {fromA: "true"}}, + {expression: "fromB", fields: {fromB: "true"}}, + {expression: "target", fields: {a: "fromA ?? false", b: "fromB ?? false"}}, + {expression: "noA", fields: {noA: "true"}}, + {expression: "noB", fields: {noB: "true"}}, + ], + edges: [ + "input -> s1", "input -> s2", + "s1:0 -> fromA -> target", "s1:1 -> noA -> output", + "s2:0 -> fromB -> target", "s2:1 -> noB -> output", + "target -> output", + ], + }, + cases: [ + [{a: true, b: true}, {a: true, b: true}], + [{a: true, b: false}, {a: true, b: false, noB: true}], + [{a: false, b: true}, {a: false, b: true, noA: true}], + [{a: false, b: false}, {noA: true, noB: true}], + ], +} + +{ + name: "a node reachable by both branches of a collect switch at different depths", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["near", "far"]}, + {expression: "f1", fields: {far1: "true"}}, + {expression: "f2", passThrough: true, fields: {far2: "true"}}, + {expression: "target", passThrough: true, fields: {done: "true"}}, + ], + edges: ["input -> s", "s:0 -> target", "s:1 -> f1 -> f2 -> target", "target -> output"], + }, + cases: [ + [{near: true, far: true}, {near: true, far: true, far1: true, far2: true, done: true}], + [{near: true}, {near: true, done: true}], + [{far: true}, {far1: true, far2: true, done: true}], + [{}, {}], + ], +} + +{ + name: "a node behind a pruned branch and a live branch of nested switches", + graph: { + nodes: [ + {switch: "outer", when: ["x > 0", ""]}, + {switch: "inner", when: ["y > 0", ""]}, + {expression: "pp", fields: {tag: "'pp'"}}, + {expression: "pn", fields: {tag: "'pn'"}}, + {expression: "neg", fields: {tag: "'neg'"}}, + {expression: "shared", fields: {tag: "tag", shared: "true"}}, + ], + edges: [ + "input -> outer", "outer:0 -> inner", "outer:1 -> neg -> shared", + "inner:0 -> pp -> shared", "inner:1 -> pn -> output", + "shared -> output", + ], + }, + cases: [ + [{x: 1, y: 1}, {tag: "pp", shared: true}], + [{x: 1, y: 0}, {tag: "pn"}], + [{x: 0, y: 1}, {tag: "neg", shared: true}], + ], +} + +{ + name: "the output reachable only through pruned branches yields the visited leaves", + graph: { + nodes: [ + {switch: "s", when: ["go"]}, + {expression: "on", fields: {on: "true"}}, + {expression: "side", fields: {side: "true"}}, + ], + edges: ["input -> s", "s:0 -> on -> output", "input -> side"], + }, + cases: [ + [{go: true}, {on: true}], + [{go: false}, {side: true}], + ], +} + +{ + name: "a node upstream of a switch that routes nowhere is pruned from the result", + graph: { + nodes: [ + {expression: "pre", fields: {pre: "true", n: "n"}}, + {switch: "s", when: ["n > 0"]}, + {expression: "pos", fields: {pos: "true"}}, + {expression: "side", fields: {side: "true"}}, + ], + edges: ["input -> pre -> s", "s:0 -> pos -> output", "input -> side -> output"], + }, + cases: [ + [{n: 1}, {pos: true, side: true}], + [{n: 0}, {side: true}], + ], +} + +{ + name: "a shared parent of a pruned branch and a live path still feeds the live path", + graph: { + nodes: [ + {expression: "shared", fields: {v: "x * 2"}}, + {switch: "s", when: ["v > 200"]}, + {expression: "big", fields: {big: "true"}}, + {expression: "live", fields: {v: "v"}}, + ], + edges: ["input -> shared", "shared -> s", "s:0 -> big -> output", "shared -> live -> output"], + }, + cases: [ + [{x: 101}, {big: true, v: 202}], + [{x: 1}, {v: 2}], + ], +} diff --git a/core/engine/tests/spec/graph/26-table-numeric-ranges.json5 b/core/engine/tests/spec/graph/26-table-numeric-ranges.json5 new file mode 100644 index 00000000..3b53cea3 --- /dev/null +++ b/core/engine/tests/spec/graph/26-table-numeric-ranges.json5 @@ -0,0 +1,864 @@ +// Decision tables over numbers: intervals, comparison cells and banded rule sets. +// +// Chapter 06 pins the unary shorthands one by one; this chapter covers how numeric cells behave +// inside whole tables: exact boundaries between adjacent bands, gaps and overlaps resolved by +// hit policy, negative and decimal bounds, numbers that arrive as strings, and tables large +// enough (8 rules or more) to take the indexed path, where point cells are looked up and +// ranges fall back to evaluation. The unary language itself is pinned in +// core/expression/tests/spec/unary/04-intervals.csv. + +// --- Bracket forms at their exact boundaries ----------------------------------------------- + +{ + name: "ranges: closed bands that share a boundary resolve by rule order", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["band"], rules: [ + ["[0..10]", "'low'"], + ["[10..20]", "'mid'"], + ["[20..30]", "'high'"], + ]}, + ], + }, + cases: [ + [{n: 0}, {band: "low"}], + [{n: 10}, {band: "low"}], + [{n: 10.0001}, {band: "mid"}], + [{n: 20}, {band: "mid"}], + [{n: 30}, {band: "high"}], + [{n: 30.0001}, {}], + [{n: -0.0001}, {}], + ], +} + +{ + name: "ranges: shared closed boundaries collect both bands", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["band"], rules: [ + ["[0..10]", "'low'"], + ["[10..20]", "'mid'"], + ["[20..30]", "'high'"], + ]}, + ], + }, + cases: [ + [{n: 10}, [{band: "low"}, {band: "mid"}]], + [{n: 20}, [{band: "mid"}, {band: "high"}]], + [{n: 15}, [{band: "mid"}]], + [{n: 31}, []], + ], +} + +{ + name: "ranges: half-open bands tile the line without overlap", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["band"], rules: [ + ["[0..10)", "'a'"], + ["[10..20)", "'b'"], + ["[20..30)", "'c'"], + ]}, + ], + }, + cases: [ + [{n: 0}, [{band: "a"}]], + [{n: 9.9999}, [{band: "a"}]], + [{n: 10}, [{band: "b"}]], + [{n: 20}, [{band: "c"}]], + [{n: 29.999999}, [{band: "c"}]], + [{n: 30}, []], + ], +} + +{ + name: "ranges: left-open bands tile the line from the other side", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["band"], rules: [ + ["(0..10]", "'a'"], + ["(10..20]", "'b'"], + ["", "'outside'"], + ]}, + ], + }, + cases: [ + [{n: 0}, {band: "outside"}], + [{n: 0.0000001}, {band: "a"}], + [{n: 10}, {band: "a"}], + [{n: 10.5}, {band: "b"}], + [{n: 20}, {band: "b"}], + [{n: 20.0000001}, {band: "outside"}], + ], +} + +{ + name: "ranges: open bands leave the shared boundary unmatched", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["band"], rules: [ + ["(0..10)", "'a'"], + ["(10..20)", "'b'"], + ["", "'gap'"], + ]}, + ], + }, + cases: [ + [{n: 5}, {band: "a"}], + [{n: 10}, {band: "gap"}], + [{n: 10.0}, {band: "gap"}], + [{n: 15}, {band: "b"}], + [{n: 0}, {band: "gap"}], + [{n: 20}, {band: "gap"}], + ], +} + +{ + name: "ranges: reversed brackets `]a..b[` act as the complement of (a..b)", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["]1..5[", "'outside'"], + ["", "'inside'"], + ]}, + ], + }, + cases: [ + [{n: 0}, {r: "outside"}], + [{n: 1}, {r: "outside"}, "question: `]1..5[` is undocumented; it acts as the complement of (1..5) and includes the bounds, while the ISO reading would be the open interval (1..5)"], + [{n: 3}, {r: "inside"}, "question: `]1..5[` is undocumented; under the ISO reading 3 lies inside the open interval and would match the first rule"], + [{n: 5}, {r: "outside"}, "question: `]1..5[` is undocumented; it acts as the complement of (1..5) and includes the bounds, while the ISO reading would be the open interval (1..5)"], + [{n: 6}, {r: "outside"}], + [{n: null}, {r: "inside"}], + ], +} + +{ + name: "ranges: degenerate and reversed intervals in a table", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [ + ["[5..5]", "'point'"], + ["(5..5)", "'empty open'"], + ["[9..1]", "'reversed'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{n: 5}, [{r: "point"}, {r: "any"}]], + [{n: 5.00}, [{r: "point"}, {r: "any"}]], + [{n: 3}, [{r: "any"}]], + [{n: 9}, [{r: "any"}]], + ], +} + +// --- Negative and decimal bounds ------------------------------------------------------------ + +{ + name: "ranges: negative bounds", + graph: { + nodes: [ + {table: "t", inputs: ["temp"], outputs: ["state"], rules: [ + ["< -40", "'extreme cold'"], + ["[-40..-10)", "'freezing'"], + ["[-10..0]", "'cold'"], + ["(0..25]", "'mild'"], + ["> 25", "'hot'"], + ]}, + ], + }, + cases: [ + [{temp: -41}, {state: "extreme cold"}], + [{temp: -40}, {state: "freezing"}], + [{temp: -10.01}, {state: "freezing"}], + [{temp: -10}, {state: "cold"}], + [{temp: 0}, {state: "cold"}], + [{temp: -0}, {state: "cold"}], + [{temp: 0.01}, {state: "mild"}], + [{temp: 25}, {state: "mild"}], + [{temp: 25.000001}, {state: "hot"}], + ], +} + +{ + name: "ranges: decimal bounds compare exactly", + graph: { + nodes: [ + {table: "t", inputs: ["ratio"], outputs: ["grade"], rules: [ + ["[0.1..0.3)", "'A'"], + ["[0.3..0.45]", "'B'"], + ["(0.45..0.7]", "'C'"], + ["", "'D'"], + ]}, + ], + }, + cases: [ + [{ratio: 0.1}, {grade: "A"}], + [{ratio: 0.29999999999999999999}, {grade: "A"}], + [{ratio: 0.3}, {grade: "B"}], + [{ratio: 0.30}, {grade: "B"}], + [{ratio: 0.45}, {grade: "B"}], + [{ratio: 0.4500000001}, {grade: "C"}], + [{ratio: 0.7}, {grade: "C"}], + [{ratio: 0.09999}, {grade: "D"}], + [{ratio: 1}, {grade: "D"}], + ], +} + +{ + name: "ranges: computed input against decimal bands (0.1 + 0.2 is exactly 0.3)", + graph: { + nodes: [ + {table: "t", inputs: ["a + b"], outputs: ["r"], rules: [ + ["(0.3..1]", "'above'"], + ["[0.3..0.3]", "'exactly 0.3'"], + ["< 0.3", "'below'"], + ]}, + ], + }, + cases: [ + [{a: 0.1, b: 0.2}, {r: "exactly 0.3"}], + [{a: 0.1, b: 0.20001}, {r: "above"}], + [{a: 0.1, b: 0.19999}, {r: "below"}], + [{a: -0.1, b: 0.4}, {r: "exactly 0.3"}], + ], +} + +{ + name: "ranges: large and tiny magnitudes at the bounds", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["[1000000000000..9999999999999]", "'trillions'"], + ["(0..0.000001]", "'tiny'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{n: 1000000000000}, {r: "trillions"}], + [{n: 9999999999999}, {r: "trillions"}], + [{n: 10000000000000}, {r: "other"}], + [{n: 0.000001}, {r: "tiny"}], + [{n: 0.0000001}, {r: "tiny"}], + [{n: 0.0000010001}, {r: "other"}], + ], +} + +// --- Comparison cells ---------------------------------------------------------------------- + +{ + name: "comparisons: descending `>=` thresholds under first hit", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 80", "'B'"], + [">= 70", "'C'"], + [">= 60", "'D'"], + ["", "'F'"], + ]}, + ], + }, + cases: [ + [{score: 100}, {grade: "A"}], + [{score: 90}, {grade: "A"}], + [{score: 89.99}, {grade: "B"}], + [{score: 80}, {grade: "B"}], + [{score: 70}, {grade: "C"}], + [{score: 60}, {grade: "D"}], + [{score: 59.9}, {grade: "F"}], + [{score: -5}, {grade: "F"}], + [{score: null}, {grade: "F"}], + [{}, {grade: "F"}], + ], +} + +{ + name: "comparisons: ascending `<` thresholds under first hit", + graph: { + nodes: [ + {table: "t", inputs: ["weight"], outputs: ["cost"], rules: [ + ["< 1", "5"], + ["< 5", "9.5"], + ["< 20", "15"], + ["", "weight * 1.25"], + ]}, + ], + }, + cases: [ + [{weight: 0}, {cost: 5}], + [{weight: 0.999}, {cost: 5}], + [{weight: 1}, {cost: 9.5}], + [{weight: 4.99}, {cost: 9.5}], + [{weight: 5}, {cost: 15}], + [{weight: 20}, {cost: 25}], + [{weight: 100}, {cost: 125}], + ], +} + +{ + name: "comparisons: `>` vs `>=` and `<` vs `<=` differ only at the boundary", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["op"], rules: [ + ["> 0", "'gt0'"], + [">= 0", "'gte0'"], + ["< 0", "'lt0'"], + ["<= 0", "'lte0'"], + ]}, + ], + }, + cases: [ + [{n: 0}, [{op: "gte0"}, {op: "lte0"}]], + [{n: 0.0}, [{op: "gte0"}, {op: "lte0"}]], + [{n: -0}, [{op: "gte0"}, {op: "lte0"}]], + [{n: 0.0000000001}, [{op: "gt0"}, {op: "gte0"}]], + [{n: -0.0000000001}, [{op: "lt0"}, {op: "lte0"}]], + ], +} + +{ + name: "comparisons: `!=` excludes one value and matches null and other types", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["!= 0", "'nonzero'"], + ["", "'zero'"], + ]}, + ], + }, + cases: [ + [{n: 0}, {r: "zero"}], + [{n: 0.00}, {r: "zero"}], + [{n: 1}, {r: "nonzero"}], + [{n: -1}, {r: "nonzero"}], + [{n: null}, {r: "nonzero"}], + [{}, {r: "nonzero"}], + [{n: "0"}, {r: "nonzero"}], + [{n: false}, {r: "nonzero"}], + ], +} + +{ + name: "comparisons: two comparisons combined into one cell", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["> 0 and < 10", "'single digit'"], + ["< 0 or > 100", "'out of range'"], + [">= 10 and != 50", "'tens'"], + ["", "'fifty or edge'"], + ]}, + ], + }, + cases: [ + [{n: 5}, {r: "single digit"}], + [{n: 0}, {r: "fifty or edge"}], + [{n: 10}, {r: "tens"}], + [{n: 50}, {r: "fifty or edge"}], + [{n: 101}, {r: "out of range"}], + [{n: -1}, {r: "out of range"}], + [{n: 100}, {r: "tens"}], + ], +} + +{ + name: "comparisons: comma list of comparisons and intervals", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["< 0, [10..20], > 100", "'flagged'"], + ["", "'ok'"], + ]}, + ], + }, + cases: [ + [{n: -5}, {r: "flagged"}], + [{n: 0}, {r: "ok"}], + [{n: 10}, {r: "flagged"}], + [{n: 20}, {r: "flagged"}], + [{n: 20.5}, {r: "ok"}], + [{n: 100}, {r: "ok"}], + [{n: 100.01}, {r: "flagged"}], + ], +} + +{ + name: "comparisons: bounds read from other input fields", + graph: { + nodes: [ + {table: "t", inputs: ["value"], outputs: ["r"], rules: [ + ["< limits.min", "'below'"], + ["[limits.min..limits.max]", "'within'"], + ["> limits.max", "'above'"], + ["", "'unknown'"], + ]}, + ], + }, + cases: [ + [{value: 5, limits: {min: 1, max: 10}}, {r: "within"}], + [{value: 1, limits: {min: 1, max: 10}}, {r: "within"}], + [{value: 0, limits: {min: 1, max: 10}}, {r: "below"}], + [{value: 11, limits: {min: 1, max: 10}}, {r: "above"}], + [{value: 5, limits: {min: 1}}, {r: "unknown"}], + [{value: 5}, {r: "unknown"}], + [{value: 5, limits: {min: 10, max: 1}}, {r: "below"}], + ], +} + +// --- Overlapping rules --------------------------------------------------------------------- + +{ + name: "overlap: nested ranges, most specific last loses under first hit", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["[0..100]", "'wide'"], + ["[40..60]", "'narrow'"], + ["50", "'exact'"], + ]}, + ], + }, + cases: [ + [{n: 50}, {r: "wide"}], + [{n: 45}, {r: "wide"}], + [{n: 101}, {}], + ], +} + +{ + name: "overlap: nested ranges, collect returns every containing band", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [ + ["[0..100]", "'wide'"], + ["[40..60]", "'narrow'"], + ["50", "'exact'"], + ["> 55", "'upper'"], + ]}, + ], + }, + cases: [ + [{n: 50}, [{r: "wide"}, {r: "narrow"}, {r: "exact"}]], + [{n: 58}, [{r: "wide"}, {r: "narrow"}, {r: "upper"}]], + [{n: 70}, [{r: "wide"}, {r: "upper"}]], + [{n: 200}, [{r: "upper"}]], + [{n: -1}, []], + ], +} + +{ + name: "overlap: two numeric columns, each rule a rectangle", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x", "y"], outputs: ["zone"], rules: [ + ["[0..10]", "[0..10]", "'A'"], + ["[5..15]", "[5..15]", "'B'"], + ["[0..15]", "> 10", "'C'"], + ]}, + ], + }, + cases: [ + [{x: 2, y: 2}, [{zone: "A"}]], + [{x: 7, y: 7}, [{zone: "A"}, {zone: "B"}]], + [{x: 7, y: 12}, [{zone: "B"}, {zone: "C"}]], + [{x: 12, y: 2}, []], + [{x: 10, y: 10}, [{zone: "A"}, {zone: "B"}]], + [{x: 15, y: 15}, [{zone: "B"}, {zone: "C"}]], + [{x: 7}, []], + ], +} + +{ + name: "overlap: a per-column `[]` output collects every containing band", + graph: { + nodes: [ + {table: "t", inputs: ["age"], outputs: ["primary", "tags[]"], rules: [ + ["< 13", "'child'", "'minor'"], + ["[13..17]", "'teen'", "'minor'"], + ["[16..25]", "'young'", "'student-eligible'"], + [">= 18", "'adult'", "'can-vote'"], + [">= 65", "'senior'", "'discount'"], + ]}, + ], + }, + cases: [ + [{age: 10}, {primary: "child", tags: ["minor"]}], + [{age: 16}, {primary: "teen", tags: ["minor", "student-eligible"]}], + [{age: 18}, {primary: "young", tags: ["student-eligible", "can-vote"]}], + [{age: 40}, {primary: "adult", tags: ["can-vote"]}], + [{age: 70}, {primary: "adult", tags: ["can-vote", "discount"]}], + ], +} + +// --- Indexed tables (8+ rules) ------------------------------------------------------------ + +{ + name: "indexed: point cells mixed with ranges keep first-hit order", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["r"], rules: [ + ["[100..199]", "'1xx'"], + ["200", "'ok'"], + ["201, 202", "'created or accepted'"], + ["[200..299]", "'2xx'"], + ["301, 302, 307, 308", "'redirect'"], + ["404", "'not found'"], + ["[400..499]", "'client error'"], + ["[500..599]", "'server error'"], + ["", "'unknown'"], + ]}, + ], + }, + cases: [ + [{code: 100}, {r: "1xx"}], + [{code: 200}, {r: "ok"}], + [{code: 200.0}, {r: "ok"}], + [{code: 202}, {r: "created or accepted"}], + [{code: 204}, {r: "2xx"}], + [{code: 307}, {r: "redirect"}], + [{code: 303}, {r: "unknown"}], + [{code: 404}, {r: "not found"}], + [{code: 418}, {r: "client error"}], + [{code: 503}, {r: "server error"}], + [{code: 600}, {r: "unknown"}], + [{code: "200"}, {r: "unknown"}], + [{code: null}, {r: "unknown"}], + ], +} + +{ + name: "indexed: a range rule placed before a point rule still wins", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["1", "'one'"], + ["2", "'two'"], + ["3", "'three'"], + ["[4..6]", "'four to six'"], + ["5", "'five'"], + ["6", "'six'"], + ["7", "'seven'"], + ["> 7", "'big'"], + ["8", "'eight'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {r: "one"}], + [{n: 3}, {r: "three"}], + [{n: 5}, {r: "four to six"}], + [{n: 6}, {r: "four to six"}], + [{n: 7}, {r: "seven"}], + [{n: 8}, {r: "big"}], + [{n: 0}, {}], + [{n: 4.5}, {r: "four to six"}], + ], +} + +{ + name: "indexed: collect over points, ranges and comparisons", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [ + ["0", "'zero'"], + ["!= 0", "'nonzero'"], + ["< 0", "'negative'"], + ["1, 3, 5, 7, 9", "'odd digit'"], + ["0, 2, 4, 6, 8", "'even digit'"], + ["[0..9]", "'digit'"], + ["(9..99]", "'two digits'"], + ["-1", "'minus one'"], + ["10.5", "'ten and a half'"], + ]}, + ], + }, + cases: [ + [{n: 0}, [{r: "zero"}, {r: "even digit"}, {r: "digit"}]], + [{n: 3}, [{r: "nonzero"}, {r: "odd digit"}, {r: "digit"}]], + [{n: 3.0}, [{r: "nonzero"}, {r: "odd digit"}, {r: "digit"}]], + [{n: -1}, [{r: "nonzero"}, {r: "negative"}, {r: "minus one"}]], + [{n: 10.5}, [{r: "nonzero"}, {r: "two digits"}, {r: "ten and a half"}]], + [{n: 10.50}, [{r: "nonzero"}, {r: "two digits"}, {r: "ten and a half"}]], + [{n: 100}, [{r: "nonzero"}]], + [{n: null}, [{r: "nonzero"}]], + [{n: "3"}, [{r: "nonzero"}]], + ], +} + +{ + name: "indexed: two numeric columns, one point-indexed and one ranged", + graph: { + nodes: [ + {table: "t", inputs: ["zone", "weight"], outputs: ["price"], rules: [ + ["1", "< 1", "5"], + ["1", "[1..10)", "8"], + ["1", ">= 10", "12"], + ["2", "< 1", "6"], + ["2", "[1..10)", "10"], + ["2", ">= 10", "15"], + ["3, 4", "< 5", "9"], + ["3, 4", ">= 5", "20"], + ["", "", "99"], + ]}, + ], + }, + cases: [ + [{zone: 1, weight: 0.5}, {price: 5}], + [{zone: 1, weight: 1}, {price: 8}], + [{zone: 1, weight: 10}, {price: 12}], + [{zone: 2, weight: 9.99}, {price: 10}], + [{zone: 2, weight: 10}, {price: 15}], + [{zone: 3, weight: 4.999}, {price: 9}], + [{zone: 4, weight: 5}, {price: 20}], + [{zone: 5, weight: 1}, {price: 99}], + [{zone: 1}, {price: 99}], + [{zone: "1", weight: 1}, {price: 99}], + ], +} + +{ + name: "indexed: decimal point cells normalise their scale", + graph: { + nodes: [ + {table: "t", inputs: ["rate"], outputs: ["r"], rules: [ + ["0.5", "'half'"], + ["0.25", "'quarter'"], + ["0.125", "'eighth'"], + ["1.0", "'one'"], + ["1.50", "'one and a half'"], + ["2", "'two'"], + ["2.5, 3.5", "'odd halves'"], + ["100.00", "'hundred'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{rate: 0.5}, {r: "half"}], + [{rate: 0.50}, {r: "half"}], + [{rate: 0.125}, {r: "eighth"}], + [{rate: 1}, {r: "one"}], + [{rate: 1.5}, {r: "one and a half"}], + [{rate: 2.000}, {r: "two"}], + [{rate: 3.5}, {r: "odd halves"}], + [{rate: 100}, {r: "hundred"}], + [{rate: 0.1250001}, {r: "other"}], + ], +} + +{ + name: "indexed: negative point cells", + graph: { + nodes: [ + {table: "t", inputs: ["delta"], outputs: ["r"], rules: [ + ["-3", "'m3'"], + ["-2", "'m2'"], + ["-1", "'m1'"], + ["0", "'zero'"], + ["1", "'p1'"], + ["2", "'p2'"], + ["3", "'p3'"], + ["< -3", "'very negative'"], + ["", "'very positive'"], + ]}, + ], + }, + cases: [ + [{delta: -3}, {r: "m3"}], + [{delta: -1.0}, {r: "m1"}], + [{delta: 0}, {r: "zero"}], + [{delta: -0}, {r: "zero"}], + [{delta: 2}, {r: "p2"}], + [{delta: -10}, {r: "very negative"}], + [{delta: 10}, {r: "very positive"}], + [{delta: -2.5}, {r: "very positive"}], + ], +} + +// --- Numbers that arrive as strings ---------------------------------------------------------- + +{ + name: "strings as numbers: numeric cells do not coerce string inputs", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [ + ["5", "'eq'"], + ["> 1", "'gt'"], + ["[1..10]", "'range'"], + ["!= 5", "'ne'"], + ["'5'", "'string five'"], + ]}, + ], + }, + cases: [ + [{n: 5}, [{r: "eq"}, {r: "gt"}, {r: "range"}]], + [{n: "5"}, [{r: "ne"}, {r: "string five"}]], + [{n: "5.0"}, [{r: "ne"}]], + [{n: " 5"}, [{r: "ne"}]], + [{n: "abc"}, [{r: "ne"}]], + ], +} + +{ + name: "strings as numbers: number() in the input field converts before matching", + graph: { + nodes: [ + {table: "t", inputs: ["number(n)"], outputs: ["r"], rules: [ + ["< 0", "'negative'"], + ["[0..100]", "'percent'"], + ["> 100", "'over'"], + ["", "'not a number'"], + ]}, + ], + }, + cases: [ + [{n: "50"}, {r: "percent"}], + [{n: "-1.5"}, {r: "negative"}], + [{n: "100.0"}, {r: "percent"}], + [{n: "100.01"}, {r: "over"}], + [{n: 7}, {r: "percent"}], + [{n: "x"}, {r: "not a number"}], + [{n: null}, {r: "not a number"}], + ], +} + +{ + name: "strings as numbers: indexed point cells do not match numeric strings", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["1", "'n1'"], + ["2", "'n2'"], + ["3", "'n3'"], + ["4", "'n4'"], + ["'1'", "'s1'"], + ["'2'", "'s2'"], + ["'3'", "'s3'"], + ["'4'", "'s4'"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {r: "n1"}], + [{n: "1"}, {r: "s1"}], + [{n: 4}, {r: "n4"}], + [{n: "4"}, {r: "s4"}], + [{n: "4.0"}, {r: "none"}], + [{n: 4.0}, {r: "n4"}], + [{n: true}, {r: "none"}], + ], +} + +// --- Wrong types, null and missing against numeric cells ---------------------------------- + +{ + name: "types: non-numeric values fall through numeric bands to the catch-all", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["< 0", "'negative'"], + ["[0..10]", "'small'"], + ["> 10", "'large'"], + ["", "'not a number'"], + ]}, + ], + }, + cases: [ + [{n: 3}, {r: "small"}], + [{n: null}, {r: "not a number"}], + [{}, {r: "not a number"}], + [{n: true}, {r: "not a number"}], + [{n: [3]}, {r: "not a number"}], + [{n: {v: 3}}, {r: "not a number"}], + [{n: "3"}, {r: "not a number"}], + ], +} + +{ + name: "types: a numeric band on a nested dotted field with missing parents", + graph: { + nodes: [ + {table: "t", inputs: ["order.totals.net"], outputs: ["tier"], rules: [ + ["[0..100)", "'small'"], + ["[100..1000)", "'medium'"], + [">= 1000", "'large'"], + ]}, + ], + }, + cases: [ + [{order: {totals: {net: 99.99}}}, {tier: "small"}], + [{order: {totals: {net: 100}}}, {tier: "medium"}], + [{order: {totals: {net: 1000}}}, {tier: "large"}], + [{order: {totals: {}}}, {}], + [{order: {}}, {}], + [{}, {}], + ], +} + +// --- Interactions with other nodes ---------------------------------------------------------- + +{ + name: "with nodes: bands applied to a value computed upstream", + graph: { + nodes: [ + {expression: "bmi", passThrough: true, fields: {bmi: "round(weight / (height * height) * 10) / 10"}}, + {table: "class", passThrough: true, inputs: ["bmi"], outputs: ["category"], rules: [ + ["< 18.5", "'underweight'"], + ["[18.5..25)", "'normal'"], + ["[25..30)", "'overweight'"], + [">= 30", "'obese'"], + ]}, + ], + }, + cases: [ + [{weight: 70, height: 1.75}, {weight: 70, height: 1.75, bmi: 22.9, category: "normal"}], + [{weight: 50, height: 1.75}, {weight: 50, height: 1.75, bmi: 16.3, category: "underweight"}], + [{weight: 92, height: 1.75}, {weight: 92, height: 1.75, bmi: 30, category: "obese"}], + [{weight: 76.5625, height: 1.75}, {weight: 76.5625, height: 1.75, bmi: 25, category: "overweight"}], + ], +} + +{ + name: "with nodes: bands per element in loop mode", + graph: { + nodes: [ + {table: "t", executionMode: "loop", inputField: "items", outputPath: "grades", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + ["[75..90)", "'B'"], + ["", "'C'"], + ]}, + ], + }, + cases: [ + [{items: [{score: 95}, {score: 75}, {score: 74.99}]}, {grades: [{grade: "A"}, {grade: "B"}, {grade: "C"}]}], + [{items: [{score: 90}, {}]}, {grades: [{grade: "A"}, {grade: "C"}]}], + [{items: []}, {grades: []}], + ], +} + +{ + name: "with nodes: tiered tax brackets feed an expression", + graph: { + nodes: [ + {table: "bracket", passThrough: true, inputs: ["income"], outputs: ["rate", "base", "floor"], rules: [ + ["[0..10000]", "0", "0", "0"], + ["(10000..40000]", "0.1", "0", "10000"], + ["(40000..90000]", "0.2", "3000", "40000"], + ["> 90000", "0.35", "13000", "90000"], + ]}, + {expression: "tax", fields: {tax: "base + (income - floor) * rate"}}, + ], + }, + cases: [ + [{income: 5000}, {tax: 0}], + [{income: 10000}, {tax: 0}], + [{income: 10001}, {tax: 0.1}], + [{income: 40000}, {tax: 3000}], + [{income: 90000}, {tax: 13000}], + [{income: 100000}, {tax: 16500}], + ], +} diff --git a/core/engine/tests/spec/graph/27-table-strings-and-lists.json5 b/core/engine/tests/spec/graph/27-table-strings-and-lists.json5 new file mode 100644 index 00000000..d9f02165 --- /dev/null +++ b/core/engine/tests/spec/graph/27-table-strings-and-lists.json5 @@ -0,0 +1,809 @@ +// Decision tables over strings and lists. +// +// String cells compare exactly: case, whitespace and unicode form all matter. Comma lists match +// any entry, function cells (`startsWith($, ...)`, `contains`, `upper`, `len`) run as full +// expressions over `$`, and list-typed inputs are matched with `in`, `contains`, `some` and +// friends rather than with equality. Tables of 8 rules or more take the indexed path, where +// string literal cells are looked up by value and everything else falls back to evaluation; +// several suites repeat a small-table shape at that size. Chapter 06 covers the basic +// shorthands; the string functions themselves are pinned in the expression spec. + +// --- String equality ----------------------------------------------------------------------- + +{ + name: "strings: equality is exact in case and whitespace", + graph: { + nodes: [ + {table: "t", inputs: ["tier"], outputs: ["r"], rules: [ + ["'gold'", "'gold'"], + ["'Gold'", "'Gold'"], + ["'gold '", "'gold with space'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{tier: "gold"}, {r: "gold"}], + [{tier: "Gold"}, {r: "Gold"}], + [{tier: "GOLD"}, {r: "other"}], + [{tier: "gold "}, {r: "gold with space"}], + [{tier: " gold"}, {r: "other"}], + [{tier: ""}, {r: "other"}], + [{tier: null}, {r: "other"}], + ], +} + +{ + name: "strings: single, double and backtick quoted cells are the same literal", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["s"], outputs: ["r"], rules: [ + ["'abc'", "'single'"], + ["\"abc\"", "'double'"], + ["`abc`", "'backtick'"], + ["== 'abc'", "'explicit'"], + ]}, + ], + }, + cases: [ + [{s: "abc"}, [{r: "single"}, {r: "double"}, {r: "backtick"}, {r: "explicit"}]], + [{s: "ABC"}, []], + [{s: "ab"}, []], + ], +} + +{ + name: "strings: the empty string is a value, distinct from null and the wildcard", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["''", "'empty'"], + ["null", "'null'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{s: ""}, {r: "empty"}], + [{s: null}, {r: "null"}], + [{}, {r: "null"}], + [{s: " "}, {r: "other"}], + [{s: 0}, {r: "other"}], + [{s: false}, {r: "other"}], + ], +} + +{ + name: "strings: a literal containing a comma is one value, not a list", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["'a, b'", "'one literal'"], + ["'a', 'b'", "'list'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{s: "a, b"}, {r: "one literal"}], + [{s: "a"}, {r: "list"}], + [{s: "b"}, {r: "list"}], + [{s: "a,b"}, {r: "other"}], + ], +} + +{ + name: "strings: quotes and escapes inside literals", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["\"it's\"", "'apostrophe'"], + ["'say \"hi\"'", "'quoted'"], + ["'a\\b'", "'backslash'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{s: "it's"}, {r: "apostrophe"}], + [{s: "say \"hi\""}, {r: "quoted"}], + [{s: "a\\b"}, {r: "backslash"}], + [{s: "its"}, {r: "other"}], + ], +} + +{ + name: "strings: string cells do not coerce numbers or booleans", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["'1'", "'string one'"], + ["'true'", "'string true'"], + ["'null'", "'string null'"], + ["!= '1'", "'not string one'"], + ]}, + ], + }, + cases: [ + [{v: "1"}, [{r: "string one"}]], + [{v: 1}, [{r: "not string one"}]], + [{v: "true"}, [{r: "string true"}, {r: "not string one"}]], + [{v: true}, [{r: "not string one"}]], + [{v: "null"}, [{r: "string null"}, {r: "not string one"}]], + [{v: null}, [{r: "not string one"}]], + ], +} + +// --- Comma lists and negation ---------------------------------------------------------------- + +{ + name: "lists: comma lists in several rules, first hit", + graph: { + nodes: [ + {table: "t", inputs: ["country"], outputs: ["region"], rules: [ + ["'US', 'CA', 'MX'", "'NA'"], + ["'DE', 'FR', 'IT', 'ES'", "'EU'"], + ["'GB', 'IE'", "'UKI'"], + ["'JP'", "'APAC'"], + ["", "'ROW'"], + ]}, + ], + }, + cases: [ + [{country: "US"}, {region: "NA"}], + [{country: "MX"}, {region: "NA"}], + [{country: "ES"}, {region: "EU"}], + [{country: "IE"}, {region: "UKI"}], + [{country: "JP"}, {region: "APAC"}], + [{country: "us"}, {region: "ROW"}], + [{country: "BR"}, {region: "ROW"}], + [{}, {region: "ROW"}], + ], +} + +{ + name: "lists: a value appearing in two lists is collected twice", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["code"], outputs: ["group"], rules: [ + ["'a', 'b', 'c'", "'abc'"], + ["'c', 'd'", "'cd'"], + ["'c'", "'c'"], + ["'e'", "'e'"], + ]}, + ], + }, + cases: [ + [{code: "c"}, [{group: "abc"}, {group: "cd"}, {group: "c"}]], + [{code: "a"}, [{group: "abc"}]], + [{code: "d"}, [{group: "cd"}]], + [{code: "z"}, []], + ], +} + +{ + name: "lists: a comma list mixing a literal and a function test", + graph: { + nodes: [ + {table: "t", inputs: ["sku"], outputs: ["r"], rules: [ + ["'GIFT', startsWith($, 'PROMO-')", "'free'"], + ["", "'paid'"], + ]}, + ], + }, + cases: [ + [{sku: "GIFT"}, {r: "free"}], + [{sku: "PROMO-10"}, {r: "free"}], + [{sku: "promo-10"}, {r: "paid"}], + [{sku: "BOOK"}, {r: "paid"}], + [{sku: null}, {r: "paid"}], + ], +} + +{ + name: "lists: `not in [...]` excludes listed strings and keeps null and other types", + graph: { + nodes: [ + {table: "t", inputs: ["status"], outputs: ["r"], rules: [ + ["not in ['closed', 'cancelled']", "'open-ish'"], + ["", "'final'"], + ]}, + ], + }, + cases: [ + [{status: "open"}, {r: "open-ish"}], + [{status: "closed"}, {r: "final"}], + [{status: "cancelled"}, {r: "final"}], + [{status: "Closed"}, {r: "open-ish"}], + [{status: null}, {r: "open-ish"}], + [{}, {r: "open-ish"}], + [{status: 1}, {r: "open-ish"}], + ], +} + +{ + name: "lists: `not (...)` around a membership test", + graph: { + nodes: [ + {table: "t", inputs: ["role"], outputs: ["access"], rules: [ + ["not ($ in ['guest', 'banned'])", "'granted'"], + ["", "'denied'"], + ]}, + ], + }, + cases: [ + [{role: "admin"}, {access: "granted"}], + [{role: "guest"}, {access: "denied"}], + [{role: "banned"}, {access: "denied"}], + [{role: ""}, {access: "granted"}], + [{role: null}, {access: "granted"}], + ], +} + +{ + name: "lists: `!=` against a string and against a list entry", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["s"], outputs: ["r"], rules: [ + ["!= 'x'", "'not x'"], + ["!= 'x', 'x'", "'not x or x'"], + ["!= 'x' and != 'y'", "'neither'"], + ]}, + ], + }, + cases: [ + [{s: "x"}, [{r: "not x or x"}]], + [{s: "y"}, [{r: "not x"}, {r: "not x or x"}]], + [{s: "z"}, [{r: "not x"}, {r: "not x or x"}, {r: "neither"}]], + [{s: null}, [{r: "not x"}, {r: "not x or x"}, {r: "neither"}]], + ], +} + +// --- String functions in cells ------------------------------------------------------------ + +{ + name: "functions: prefix, suffix and substring tests", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["email"], outputs: ["r"], rules: [ + ["endsWith($, '@gorules.io')", "'internal'"], + ["startsWith($, 'admin')", "'admin'"], + ["contains($, '+')", "'alias'"], + ["matches($, '^[a-z]+@')", "'simple local part'"], + ]}, + ], + }, + cases: [ + [{email: "ann@gorules.io"}, [{r: "internal"}, {r: "simple local part"}]], + [{email: "admin+ops@example.com"}, [{r: "admin"}, {r: "alias"}]], + [{email: "Admin@example.com"}, []], + [{email: "bob@example.com"}, [{r: "simple local part"}]], + [{email: ""}, []], + [{email: null}, []], + ], +} + +{ + name: "functions: case-insensitive matching through upper and lower", + graph: { + nodes: [ + {table: "t", inputs: ["status"], outputs: ["r"], rules: [ + ["lower($) == 'active'", "'active'"], + ["upper($) in ['PENDING', 'NEW']", "'waiting'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{status: "ACTIVE"}, {r: "active"}], + [{status: "Active"}, {r: "active"}], + [{status: "pending"}, {r: "waiting"}], + [{status: "New"}, {r: "waiting"}], + [{status: "closed"}, {r: "other"}], + [{status: 1}, {r: "other"}], + [{status: null}, {r: "other"}], + ], +} + +{ + name: "functions: normalising the input field instead of every cell", + graph: { + nodes: [ + {table: "t", inputs: ["lower(trim(code ?? ''))"], outputs: ["r"], rules: [ + ["'abc'", "'abc'"], + ["''", "'blank'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{code: "ABC"}, {r: "abc"}], + [{code: " aBc "}, {r: "abc"}], + [{code: " "}, {r: "blank"}], + [{}, {r: "blank"}], + [{code: "abcd"}, {r: "other"}], + ], +} + +{ + name: "functions: length bands over strings", + graph: { + nodes: [ + {table: "t", inputs: ["len(name)"], outputs: ["r"], rules: [ + ["0", "'empty'"], + ["[1..3]", "'short'"], + ["[4..10]", "'medium'"], + ["> 10", "'long'"], + ["", "'not a string'"], + ]}, + ], + }, + cases: [ + [{name: ""}, {r: "empty"}], + [{name: "Al"}, {r: "short"}], + [{name: "Ann"}, {r: "short"}], + [{name: "Anna"}, {r: "medium"}], + [{name: "Bartholomew"}, {r: "long"}], + [{name: null}, {r: "not a string"}], + [{name: 12345}, {r: "not a string"}], + [{name: ["a", "b"]}, {r: "short"}], + ], +} + +{ + name: "functions: regular expressions in cells", + graph: { + nodes: [ + {table: "t", inputs: ["postcode"], outputs: ["country"], rules: [ + ["matches($, '^[0-9]{5}$')", "'US or DE'"], + ["matches($, '^[A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2}$')", "'GB'"], + ["matches($, '^[0-9]{4}$')", "'four digits'"], + ["", "'unknown'"], + ]}, + ], + }, + cases: [ + [{postcode: "10115"}, {country: "US or DE"}], + [{postcode: "SW1A 1AA"}, {country: "GB"}], + [{postcode: "M1 1AE"}, {country: "GB"}], + [{postcode: "1010"}, {country: "four digits"}], + [{postcode: "101155"}, {country: "unknown"}], + [{postcode: 10115}, {country: "unknown"}], + ], +} + +{ + name: "functions: splitting a string input and testing its parts", + graph: { + nodes: [ + {table: "t", inputs: ["split(path, '/')"], outputs: ["r"], rules: [ + ["$[0] == 'api' and $[1] == 'v2'", "'api v2'"], + ["$[0] == 'api'", "'api'"], + ["len($) == 1", "'root segment'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{path: "api/v2/users"}, {r: "api v2"}], + [{path: "api/v1/users"}, {r: "api"}], + [{path: "home"}, {r: "root segment"}], + [{path: "static/app.js"}, {r: "other"}], + [{path: ""}, {r: "root segment"}], + ], +} + +// --- Unicode ------------------------------------------------------------------------------- + +{ + name: "unicode: literal cells match non-ASCII strings exactly", + graph: { + nodes: [ + {table: "t", inputs: ["city"], outputs: ["r"], rules: [ + ["'München'", "'munich'"], + ["'東京'", "'tokyo'"], + ["'São Paulo', 'Zürich'", "'accented'"], + ["'🚀'", "'rocket'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{city: "München"}, {r: "munich"}], + [{city: "Munchen"}, {r: "other"}], + [{city: "MÜNCHEN"}, {r: "other"}], + [{city: "東京"}, {r: "tokyo"}], + [{city: "Zürich"}, {r: "accented"}], + [{city: "🚀"}, {r: "rocket"}], + ], +} + +{ + name: "unicode: composed and decomposed forms are different strings", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["'é'", "'composed'"], + ["'é'", "'decomposed'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{s: "é"}, {r: "composed"}], + [{s: "é"}, {r: "decomposed"}], + [{s: "e"}, {r: "other"}], + ], +} + +{ + name: "unicode: upper and lower fold non-ASCII letters", + graph: { + nodes: [ + {table: "t", inputs: ["upper(word)"], outputs: ["r"], rules: [ + ["'STRASSE'", "'street'"], + ["'ÉCOLE'", "'school'"], + ["'ΑΘΗΝΑ'", "'athens'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{word: "straße"}, {r: "street"}], + [{word: "Strasse"}, {r: "street"}], + [{word: "école"}, {r: "school"}], + [{word: "Αθηνα"}, {r: "athens"}], + [{word: "school"}, {r: "other"}], + ], +} + +{ + name: "unicode: len counts characters", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["r"], rules: [ + ["len($) == 3", "'three'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{code: "abc"}, {r: "three"}], + [{code: "äöü"}, {r: "three"}, "bug: len counts UTF-8 bytes (6), so a three-character non-ASCII code is not three long"], + [{code: "日本語"}, {r: "three"}, "bug: len counts UTF-8 bytes (9), so a three-character non-ASCII code is not three long"], + [{code: "ab"}, {r: "other"}], + [{code: "é"}, {r: "other"}], + ], +} + +{ + name: "unicode: prefix tests on multi-byte strings", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["startsWith($, 'Ö')", "'umlaut O'"], + ["contains($, '€')", "'euro'"], + ["endsWith($, '✓')", "'checked'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{s: "Österreich"}, {r: "umlaut O"}], + [{s: "price 5€"}, {r: "euro"}], + [{s: "done ✓"}, {r: "checked"}], + [{s: "Oesterreich"}, {r: "other"}], + ], +} + +// --- Indexed string tables (8+ rules) ------------------------------------------------------ + +{ + name: "indexed: string point cells, lists and function cells keep first-hit order", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["r"], rules: [ + ["'A'", "'a'"], + ["'B', 'C'", "'b or c'"], + ["startsWith($, 'D')", "'d-prefix'"], + ["'D1'", "'d1 literal'"], + ["'E'", "'e'"], + ["'F', 'G', 'H'", "'fgh'"], + ["!= 'Z'", "'anything but z'"], + ["'Z'", "'z'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{code: "A"}, {r: "a"}], + [{code: "C"}, {r: "b or c"}], + [{code: "D1"}, {r: "d-prefix"}], + [{code: "E"}, {r: "e"}], + [{code: "H"}, {r: "fgh"}], + [{code: "Q"}, {r: "anything but z"}], + [{code: "Z"}, {r: "z"}], + [{code: "a"}, {r: "anything but z"}], + [{code: null}, {r: "anything but z"}], + [{code: 1}, {r: "anything but z"}], + ], +} + +{ + name: "indexed: string enum collect with duplicates across rules", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["plan"], outputs: ["feature"], rules: [ + ["'free', 'pro', 'team', 'enterprise'", "'basic'"], + ["'pro', 'team', 'enterprise'", "'export'"], + ["'team', 'enterprise'", "'sharing'"], + ["'enterprise'", "'sso'"], + ["'enterprise'", "'audit'"], + ["'pro'", "'priority email'"], + ["'team'", "'admin console'"], + ["'legacy'", "'basic'"], + ]}, + ], + }, + cases: [ + [{plan: "free"}, [{feature: "basic"}]], + [{plan: "pro"}, [{feature: "basic"}, {feature: "export"}, {feature: "priority email"}]], + [{plan: "team"}, [{feature: "basic"}, {feature: "export"}, {feature: "sharing"}, {feature: "admin console"}]], + [{plan: "enterprise"}, [{feature: "basic"}, {feature: "export"}, {feature: "sharing"}, {feature: "sso"}, {feature: "audit"}]], + [{plan: "legacy"}, [{feature: "basic"}]], + [{plan: "Pro"}, []], + [{plan: null}, []], + ], +} + +{ + name: "indexed: two string columns intersect", + graph: { + nodes: [ + {table: "t", inputs: ["country", "channel"], outputs: ["fee"], rules: [ + ["'US'", "'web'", "1"], + ["'US'", "'store'", "0"], + ["'US'", "", "2"], + ["'DE', 'FR'", "'web'", "1.5"], + ["'DE', 'FR'", "'store'", "0.5"], + ["'GB'", "'web', 'app'", "1.2"], + ["", "'app'", "3"], + ["", "", "5"], + ]}, + ], + }, + cases: [ + [{country: "US", channel: "web"}, {fee: 1}], + [{country: "US", channel: "app"}, {fee: 2}], + [{country: "FR", channel: "store"}, {fee: 0.5}], + [{country: "DE", channel: "app"}, {fee: 3}], + [{country: "GB", channel: "app"}, {fee: 1.2}], + [{country: "GB", channel: "store"}, {fee: 5}], + [{country: "JP", channel: "app"}, {fee: 3}], + [{country: "JP"}, {fee: 5}], + [{}, {fee: 5}], + ], +} + +{ + name: "indexed: unicode and case in indexed string cells", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["'ä'", "'a umlaut'"], + ["'Ä'", "'A umlaut'"], + ["'é'", "'decomposed'"], + ["'é'", "'composed'"], + ["'ß'", "'eszett'"], + ["'日'", "'sun'"], + ["'😀'", "'smile'"], + ["'a'", "'plain a'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{s: "ä"}, {r: "a umlaut"}], + [{s: "Ä"}, {r: "A umlaut"}], + [{s: "é"}, {r: "composed"}], + [{s: "é"}, {r: "decomposed"}], + [{s: "ß"}, {r: "eszett"}], + [{s: "SS"}, {r: "other"}], + [{s: "😀"}, {r: "smile"}], + [{s: "A"}, {r: "other"}], + ], +} + +{ + name: "indexed: a list-typed input never matches string point cells", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["'a'", "'a'"], + ["'b'", "'b'"], + ["'c'", "'c'"], + ["'d'", "'d'"], + ["'e'", "'e'"], + ["'f'", "'f'"], + ["'g'", "'g'"], + ["contains($, 'a')", "'contains a'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{v: "a"}, {r: "a"}], + [{v: ["a"]}, {r: "contains a"}], + [{v: ["b"]}, {r: "other"}], + [{v: "banana"}, {r: "contains a"}], + [{v: []}, {r: "other"}], + ], +} + +// --- List-typed inputs ----------------------------------------------------------------------- + +{ + name: "list inputs: membership of a literal in the input array", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["tags"], outputs: ["r"], rules: [ + ["'vip' in $", "'vip'"], + ["contains($, 'beta')", "'beta'"], + ["not ('blocked' in $)", "'not blocked'"], + ["'vip'", "'equals vip'"], + ]}, + ], + }, + cases: [ + [{tags: ["vip", "beta"]}, [{r: "vip"}, {r: "beta"}, {r: "not blocked"}]], + [{tags: ["blocked", "vip"]}, [{r: "vip"}]], + [{tags: []}, [{r: "not blocked"}]], + [{tags: ["VIP"]}, [{r: "not blocked"}]], + [{tags: "vip"}, [{r: "equals vip"}], "question: a string where a list is expected is not rejected: `contains($, 'beta')` becomes a substring test and the `in` cells error into non-matches, so only the equality cell decides"], + [{tags: null}, []], + ], +} + +{ + name: "list inputs: any, all and none over input arrays", + graph: { + nodes: [ + {table: "t", inputs: ["roles"], outputs: ["r"], rules: [ + ["some($, # in ['admin', 'owner'])", "'privileged'"], + ["len($) > 0 and all($, startsWith(#, 'read'))", "'read only'"], + ["none($, # == 'guest')", "'member'"], + ["", "'guest'"], + ]}, + ], + }, + cases: [ + [{roles: ["viewer", "owner"]}, {r: "privileged"}], + [{roles: ["read:docs", "read:wiki"]}, {r: "read only"}], + [{roles: ["writer"]}, {r: "member"}], + [{roles: ["guest"]}, {r: "guest"}], + [{roles: []}, {r: "member"}], + [{roles: null}, {r: "guest"}], + ], +} + +{ + name: "list inputs: overlap between the input array and a fixed list", + graph: { + nodes: [ + {table: "t", inputs: ["skills"], outputs: ["r"], rules: [ + ["len(filter($, # in ['rust', 'go', 'c++'])) >= 2", "'systems'"], + ["some($, # in ['rust', 'go', 'c++'])", "'some systems'"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [{skills: ["rust", "go", "js"]}, {r: "systems"}], + [{skills: ["js", "go"]}, {r: "some systems"}], + [{skills: ["js", "python"]}, {r: "none"}], + [{skills: []}, {r: "none"}], + [{skills: ["Rust"]}, {r: "none"}], + ], +} + +{ + name: "list inputs: a scalar input tested against a list from the input", + graph: { + nodes: [ + {table: "t", inputs: ["country"], outputs: ["r"], rules: [ + ["in blocked", "'blocked'"], + ["in allowed", "'allowed'"], + ["", "'review'"], + ]}, + ], + }, + cases: [ + [{country: "XX", blocked: ["XX", "YY"], allowed: ["US"]}, {r: "blocked"}], + [{country: "US", blocked: ["XX"], allowed: ["US", "CA"]}, {r: "allowed"}], + [{country: "BR", blocked: ["XX"], allowed: ["US"]}, {r: "review"}], + [{country: "US", allowed: ["US"]}, {r: "allowed"}], + [{country: "US", blocked: [], allowed: []}, {r: "review"}], + [{country: "US"}, {r: "review"}], + ], +} + +{ + name: "list inputs: arrays of objects with closures", + graph: { + nodes: [ + {table: "t", inputs: ["cart.items"], outputs: ["r"], rules: [ + ["some($, #.category == 'alcohol')", "'age check'"], + ["sum(map($, #.qty)) > 10", "'bulk'"], + ["", "'standard'"], + ]}, + ], + }, + cases: [ + [{cart: {items: [{category: "food", qty: 1}, {category: "alcohol", qty: 1}]}}, {r: "age check"}], + [{cart: {items: [{category: "food", qty: 6}, {category: "toys", qty: 5}]}}, {r: "bulk"}], + [{cart: {items: [{category: "food", qty: 2}]}}, {r: "standard"}], + [{cart: {items: []}}, {r: "standard"}], + [{cart: {}}, {r: "standard"}], + ], +} + +{ + name: "list inputs: string lists with a `[]` output column collecting reasons", + graph: { + nodes: [ + {table: "t", inputs: ["flags"], outputs: ["reasons[]"], rules: [ + ["contains($, 'chargeback')", "'prior chargeback'"], + ["contains($, 'new_device')", "'new device'"], + ["contains($, 'vpn')", "'vpn'"], + ["len($) == 0", "'clean'"], + ]}, + ], + }, + cases: [ + [{flags: ["vpn", "chargeback"]}, {reasons: ["prior chargeback", "vpn"]}], + [{flags: ["new_device"]}, {reasons: ["new device"]}], + [{flags: []}, {reasons: ["clean"]}], + [{flags: ["other"]}, {reasons: []}], + ], +} + +// --- Strings across nodes and loops -------------------------------------------------------- + +{ + name: "with nodes: a string built upstream feeds an equality table", + graph: { + nodes: [ + {expression: "key", fields: {key: "upper(country) + '-' + lower(channel)"}}, + {table: "t", inputs: ["key"], outputs: ["r"], rules: [ + ["'US-web'", "'us web'"], + ["'US-store', 'CA-store'", "'na store'"], + ["endsWith($, '-app')", "'app'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{country: "us", channel: "WEB"}, {r: "us web"}], + [{country: "ca", channel: "Store"}, {r: "na store"}], + [{country: "de", channel: "app"}, {r: "app"}], + [{country: "de", channel: "web"}, {r: "other"}], + ], +} + +{ + name: "with nodes: string matching per element of an array in loop mode", + graph: { + nodes: [ + {table: "t", executionMode: "loop", inputField: "files", outputPath: "kinds", inputs: ["name"], outputs: ["kind"], rules: [ + ["endsWith($, '.png'), endsWith($, '.jpg')", "'image'"], + ["endsWith($, '.pdf')", "'document'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{files: [{name: "a.png"}, {name: "b.pdf"}, {name: "c.txt"}]}, {kinds: [{kind: "image"}, {kind: "document"}, {kind: "other"}]}], + [{files: [{name: "A.PNG"}, {}]}, {kinds: [{kind: "other"}, {kind: "other"}]}], + [{files: []}, {kinds: []}], + ], +} diff --git a/core/engine/tests/spec/graph/28-table-dates-and-bools.json5 b/core/engine/tests/spec/graph/28-table-dates-and-bools.json5 new file mode 100644 index 00000000..ae200fc8 --- /dev/null +++ b/core/engine/tests/spec/graph/28-table-dates-and-bools.json5 @@ -0,0 +1,716 @@ +// Decision tables over dates and booleans. +// +// Date inputs reach a table in three shapes: plain strings that cells convert with `d($)`, +// date values produced by an upstream expression (`d(...)`), and strings declared as +// `format: date` / `date-time` in the input schema, which the input node turns into date +// values. Comparison and interval cells work on date values; equality cells may compare a +// date value with a date string. Boolean columns match `true` and `false` strictly: null, +// missing, 0, '' and 'true' are not booleans. Tables of 8 rules or more take the indexed path +// (literal cells looked up by value), so several suites are repeated at that size. Evaluation +// time is fixed at 2025-03-20T10:15:30Z. + +// --- Date strings converted in the cell ------------------------------------------------------ + +{ + name: "dates: string inputs compared with d($) in every cell", + graph: { + nodes: [ + {table: "t", inputs: ["since"], outputs: ["r"], rules: [ + ["d($) < d('2024-01-01')", "'before 2024'"], + ["d($) <= d('2024-06-30')", "'first half'"], + ["d($) <= d('2024-12-31T23:59:59Z')", "'second half'"], + ["", "'2025 or later'"], + ]}, + ], + }, + cases: [ + [{since: "2023-12-31"}, {r: "before 2024"}], + [{since: "2024-01-01"}, {r: "first half"}], + [{since: "2024-06-30"}, {r: "first half"}], + [{since: "2024-06-30T00:00:01Z"}, {r: "second half"}], + [{since: "2024-12-31T23:59:59Z"}, {r: "second half"}], + [{since: "2025-01-01"}, {r: "2025 or later"}], + ], +} + +{ + name: "dates: d() in the input field makes plain comparison cells work", + graph: { + nodes: [ + {table: "t", inputs: ["d(due)"], outputs: ["r"], rules: [ + ["< d('2025-03-20')", "'overdue'"], + ["[d('2025-03-20')..d('2025-03-21'))", "'due today'"], + ["<= d('2025-03-27')", "'this week'"], + ["", "'later'"], + ]}, + ], + }, + cases: [ + [{due: "2025-03-19"}, {r: "overdue"}], + [{due: "2025-03-20"}, {r: "due today"}], + [{due: "2025-03-20T23:59:59Z"}, {r: "due today"}], + [{due: "2025-03-21"}, {r: "this week"}], + [{due: "2025-03-27"}, {r: "this week"}], + [{due: "2025-03-28"}, {r: "later"}], + ], +} + +{ + name: "dates: date-string inputs against d(...) cells, comparisons coerce but intervals do not", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["at"], outputs: ["r"], rules: [ + ["> d('2024-01-01')", "'after'"], + ["<= d('2024-01-01')", "'on or before'"], + ["[d('2024-01-01')..d('2024-12-31')]", "'in 2024'"], + ["d('2024-06-01')", "'june 1st'"], + ]}, + ], + }, + cases: [ + [{at: "2025-01-01"}, [{r: "after"}]], + [{at: "2023-01-01"}, [{r: "on or before"}]], + [{at: "2024-01-01"}, [{r: "on or before"}], "question: `>`/`<=` against a date convert a date-string input, but an interval with date bounds does not (it errors), so the same string is before 2024-01-01 yet never inside [2024-01-01..2024-12-31]"], + [{at: "2024-06-01"}, [{r: "after"}, {r: "june 1st"}], "question: `>`/`<=` against a date convert a date-string input, but an interval with date bounds does not (it errors), so the same string is before 2024-01-01 yet never inside [2024-01-01..2024-12-31]"], + [{at: "2024-06-01T00:00:00Z"}, [{r: "after"}, {r: "june 1st"}], "question: `>`/`<=` against a date convert a date-string input, but an interval with date bounds does not (it errors), so the same string is before 2024-01-01 yet never inside [2024-01-01..2024-12-31]"], + [{at: null}, []], + [{}, []], + ], +} + +{ + name: "dates: invalid, null and missing values under d($)", + graph: { + nodes: [ + {table: "t", inputs: ["at"], outputs: ["r"], rules: [ + ["d($).isValid() == false", "'invalid'"], + ["d($) >= d('2025-01-01')", "'recent'"], + ["", "'old'"], + ]}, + ], + }, + cases: [ + [{at: "2025-02-01"}, {r: "recent"}], + [{at: "2020-02-01"}, {r: "old"}], + [{at: "not a date"}, {r: "invalid"}], + [{at: "2025-02-30"}, {r: "invalid"}], + [{at: null}, {r: "invalid"}, "question: d(null) is an invalid date rather than an error, so a null input is reported as invalid instead of falling through"], + [{}, {r: "invalid"}, "question: d(null) is an invalid date rather than an error, so a missing input is reported as invalid instead of falling through"], + ], +} + +// --- Date values from upstream nodes ----------------------------------------------------------- + +{ + name: "dates: a date computed upstream compared with date cells", + graph: { + nodes: [ + {expression: "calc", fields: {expires: "d(start).add(term, 'M')"}}, + {table: "t", inputs: ["expires"], outputs: ["status"], rules: [ + ["< d()", "'expired'"], + ["< d().add(30, 'd')", "'expiring soon'"], + ["", "'active'"], + ]}, + ], + }, + cases: [ + [{start: "2024-01-01", term: 12}, {status: "expired"}], + [{start: "2024-04-01", term: 12}, {status: "expiring soon"}], + [{start: "2024-03-20T10:15:31Z", term: 12}, {status: "expiring soon"}], + [{start: "2024-03-20T10:15:29Z", term: 12}, {status: "expired"}], + [{start: "2025-01-01", term: 12}, {status: "active"}], + ], +} + +{ + name: "dates: date intervals on date values, every bracket form", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["d(at)"], outputs: ["r"], rules: [ + ["[d('2024-03-01')..d('2024-03-31')]", "'closed'"], + ["(d('2024-03-01')..d('2024-03-31'))", "'open'"], + ["[d('2024-03-01')..d('2024-03-31'))", "'right-open'"], + ["(d('2024-03-01')..d('2024-03-31')]", "'left-open'"], + ]}, + ], + }, + cases: [ + [{at: "2024-03-01"}, [{r: "closed"}, {r: "right-open"}]], + [{at: "2024-03-31"}, [{r: "closed"}, {r: "left-open"}]], + [{at: "2024-03-15"}, [{r: "closed"}, {r: "open"}, {r: "right-open"}, {r: "left-open"}]], + [{at: "2024-03-31T00:00:01Z"}, []], + [{at: "2024-02-29"}, []], + ], +} + +{ + name: "dates: interval bounds from other input fields", + graph: { + nodes: [ + {table: "t", inputs: ["d(at)"], outputs: ["r"], rules: [ + ["[d(window.from)..d(window.to)]", "'in window'"], + ["< d(window.from)", "'early'"], + ["", "'late or unknown'"], + ]}, + ], + }, + cases: [ + [{at: "2024-05-10", window: {from: "2024-05-01", to: "2024-05-31"}}, {r: "in window"}], + [{at: "2024-05-01", window: {from: "2024-05-01", to: "2024-05-31"}}, {r: "in window"}], + [{at: "2024-04-30", window: {from: "2024-05-01", to: "2024-05-31"}}, {r: "early"}], + [{at: "2024-06-01", window: {from: "2024-05-01", to: "2024-05-31"}}, {r: "late or unknown"}], + ], +} + +{ + name: "dates: date parts in cells", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["d(at)"], outputs: ["r"], rules: [ + ["$.weekday() in [6, 7]", "'weekend'"], + ["$.month() == 12", "'december'"], + ["$.year() == 2024", "'2024'"], + ["$.day() == 1", "'first of month'"], + ]}, + ], + }, + cases: [ + [{at: "2024-12-01"}, [{r: "weekend"}, {r: "december"}, {r: "2024"}, {r: "first of month"}]], + [{at: "2024-12-02"}, [{r: "december"}, {r: "2024"}]], + [{at: "2025-03-01"}, [{r: "weekend"}, {r: "first of month"}]], + [{at: "2025-03-20"}, []], + ], +} + +{ + name: "dates: an age band computed from a birth date", + graph: { + nodes: [ + {table: "t", inputs: ["d().diff(d(birth), 'year')"], outputs: ["band"], rules: [ + ["< 18", "'minor'"], + ["[18..65)", "'adult'"], + [">= 65", "'senior'"], + ]}, + ], + }, + cases: [ + [{birth: "2007-03-21"}, {band: "minor"}], + [{birth: "2007-03-20"}, {band: "adult"}], + [{birth: "1960-03-20"}, {band: "senior"}], + [{birth: "1960-03-21"}, {band: "adult"}], + [{birth: "2000-01-01"}, {band: "adult"}], + ], +} + +// --- Date values produced upstream --------------------------------------------------------- +// +// The harness `date('...')` literal reaches a graph's input node as plain text, so date values +// are made by an upstream expression node here. + +{ + name: "dates: date values against comparison, interval and equality cells", + graph: { + nodes: [ + {expression: "conv", fields: {at: "raw == null ? null : d(raw)"}}, + {table: "t", hit: "collect", inputs: ["at"], outputs: ["r"], rules: [ + ["'2024-03-15'", "'string equality'"], + ["d('2024-03-15')", "'date equality'"], + ["> d('2024-03-01')", "'after march 1'"], + ["[d('2024-03-01')..d('2024-03-31')]", "'in march'"], + ["!= '2024-03-15'", "'not the 15th'"], + ]}, + ], + }, + cases: [ + [{raw: "2024-03-15"}, [{r: "string equality"}, {r: "date equality"}, {r: "after march 1"}, {r: "in march"}]], + [{raw: "2024-03-16"}, [{r: "after march 1"}, {r: "in march"}, {r: "not the 15th"}]], + [{raw: "2024-03-15T10:30:00+02:00"}, [{r: "after march 1"}, {r: "in march"}, {r: "not the 15th"}]], + [{raw: "2024-02-15"}, [{r: "not the 15th"}]], + [{raw: null}, [{r: "not the 15th"}]], + ], +} + +{ + name: "dates: indexed equality cells against date values", + graph: { + nodes: [ + {expression: "conv", fields: {at: "d(raw)"}}, + {table: "t", inputs: ["at"], outputs: ["holiday"], rules: [ + ["'2024-01-01'", "'new year'"], + ["'2024-05-01'", "'labour day'"], + ["'2024-07-04'", "'independence day'"], + ["'2024-10-03'", "'unity day'"], + ["'2024-12-24', '2024-12-25', '2024-12-26'", "'christmas'"], + ["'2024-12-31'", "'new year eve'"], + ["'2025-01-01'", "'new year'"], + ["'2025-05-01'", "'labour day'"], + ["", "'workday'"], + ]}, + ], + }, + cases: [ + [{raw: "2024-05-01"}, {holiday: "labour day"}], + [{raw: "2024-12-25"}, {holiday: "christmas"}], + [{raw: "2024-05-02"}, {holiday: "workday"}], + ], +} + +{ + name: "dates: indexed equality cells against date strings", + graph: { + nodes: [ + {table: "t", inputs: ["at"], outputs: ["holiday"], rules: [ + ["'2024-01-01'", "'new year'"], + ["'2024-05-01'", "'labour day'"], + ["'2024-07-04'", "'independence day'"], + ["'2024-10-03'", "'unity day'"], + ["'2024-12-24', '2024-12-25', '2024-12-26'", "'christmas'"], + ["'2024-12-31'", "'new year eve'"], + ["'2025-01-01'", "'new year'"], + ["'2025-05-01'", "'labour day'"], + ["", "'workday'"], + ]}, + ], + }, + cases: [ + [{at: "2024-05-01"}, {holiday: "labour day"}], + [{at: "2024-12-25"}, {holiday: "christmas"}], + [{at: "2024-05-02"}, {holiday: "workday"}], + [{at: "2024-05-01T00:00:00Z"}, {holiday: "workday"}], + ], +} + +{ + name: "dates: the same equality cells in a small table match date values", + graph: { + nodes: [ + {expression: "conv", fields: {at: "d(raw)"}}, + {table: "t", inputs: ["at"], outputs: ["holiday"], rules: [ + ["'2024-01-01'", "'new year'"], + ["'2024-05-01'", "'labour day'"], + ["'2024-12-24', '2024-12-25', '2024-12-26'", "'christmas'"], + ["", "'workday'"], + ]}, + ], + }, + cases: [ + [{raw: "2024-05-01"}, {holiday: "labour day"}], + [{raw: "2024-12-26"}, {holiday: "christmas"}], + [{raw: "2024-05-02"}, {holiday: "workday"}], + [{raw: "2024-05-01T08:00:00Z"}, {holiday: "workday"}], + ], +} + +// --- Schema-declared dates --------------------------------------------------------------------- + +{ + name: "schema dates: plain comparison cells work on declared date fields", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {due: {type: "string", format: "date"}}}}, + {table: "t", inputs: ["due"], outputs: ["r"], rules: [ + ["< d()", "'overdue'"], + ["<= d().add(7, 'd')", "'due soon'"], + ["", "'later'"], + ]}, + ], + }, + cases: [ + [{due: "2025-03-19"}, {r: "overdue"}], + [{due: "2025-03-20"}, {r: "overdue"}], + [{due: "2025-03-21"}, {r: "due soon"}], + [{due: "2025-03-27"}, {r: "due soon"}], + [{due: "2025-03-28"}, {r: "later"}], + [{}, {r: "later"}], + ], +} + +{ + name: "schema dates: date-time fields with offsets", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["at"], properties: {at: {type: "string", format: "date-time"}}}}, + {table: "t", inputs: ["at"], outputs: ["r"], rules: [ + ["< d('2025-01-01T00:00:00Z')", "'2024'"], + ["", "'2025'"], + ]}, + ], + }, + cases: [ + [{at: "2024-12-31T23:59:59Z"}, {r: "2024"}], + [{at: "2025-01-01T00:00:00Z"}, {r: "2025"}], + [{at: "2025-01-01T00:30:00+01:00"}, {r: "2024"}], + [{at: "2024-12-31T23:30:00-01:00"}, {r: "2025"}], + ], +} + +{ + name: "schema dates: a declared date passes through a pass-through table as its source text", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {table: "t", passThrough: true, inputs: ["day"], outputs: ["weekend"], rules: [ + ["$.weekday() >= 6", "true"], + ["", "false"], + ]}, + ], + }, + cases: [ + [{day: "2025-03-22"}, {day: "2025-03-22", weekend: true}], + [{day: "2025-03-20"}, {day: "2025-03-20", weekend: false}], + [{}, {weekend: false}], + ], +} + +{ + name: "schema dates: equality cells in a small table", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {table: "t", inputs: ["day"], outputs: ["r"], rules: [ + ["'2025-03-20'", "'today'"], + ["d('2025-03-21')", "'tomorrow'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{day: "2025-03-20"}, {r: "today"}], + [{day: "2025-03-21"}, {r: "tomorrow"}], + [{day: "2025-03-22"}, {r: "other"}], + ], +} + +{ + name: "schema dates: equality cells in an indexed table", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {table: "t", inputs: ["day"], outputs: ["r"], rules: [ + ["'2025-03-17'", "'mon'"], + ["'2025-03-18'", "'tue'"], + ["'2025-03-19'", "'wed'"], + ["'2025-03-20'", "'thu'"], + ["'2025-03-21'", "'fri'"], + ["'2025-03-22'", "'sat'"], + ["'2025-03-23'", "'sun'"], + ["", "'other week'"], + ]}, + ], + }, + cases: [ + [{day: "2025-03-20"}, {r: "thu"}], + [{day: "2025-03-23"}, {r: "sun"}], + [{day: "2025-03-24"}, {r: "other week"}], + ], +} + +{ + name: "schema dates: a nullable date column", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {closed: {anyOf: [{type: "string", format: "date"}, {type: "null"}]}}}}, + {table: "t", inputs: ["closed"], outputs: ["r"], rules: [ + ["null", "'open'"], + ["< d('2025-01-01')", "'closed last year'"], + ["", "'closed this year'"], + ]}, + ], + }, + cases: [ + [{closed: null}, {r: "open"}], + [{}, {r: "open"}], + [{closed: "2024-11-11"}, {r: "closed last year"}], + [{closed: "2025-02-02"}, {r: "closed this year"}], + ], +} + +{ + name: "schema dates: dates inside array items, loop mode", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {payments: {type: "array", items: {type: "object", properties: {on: {type: "string", format: "date"}}}}}}}, + {table: "t", executionMode: "loop", inputField: "payments", outputPath: "status", inputs: ["on"], outputs: ["late"], rules: [ + ["> d('2025-03-15')", "true"], + ["", "false"], + ]}, + ], + }, + cases: [ + [{payments: [{on: "2025-03-10"}, {on: "2025-03-16"}]}, {status: [{late: false}, {late: true}]}], + [{payments: [{on: "2025-03-15"}]}, {status: [{late: false}]}], + [{payments: []}, {status: []}], + ], +} + +// --- Boolean columns -------------------------------------------------------------------------- + +{ + name: "bools: true, false and wildcard cells over two columns", + graph: { + nodes: [ + {table: "t", inputs: ["verified", "blocked"], outputs: ["r"], rules: [ + ["", "true", "'blocked'"], + ["true", "false", "'ok'"], + ["false", "false", "'unverified'"], + ["", "", "'unknown'"], + ]}, + ], + }, + cases: [ + [{verified: true, blocked: true}, {r: "blocked"}], + [{verified: false, blocked: true}, {r: "blocked"}], + [{verified: true, blocked: false}, {r: "ok"}], + [{verified: false, blocked: false}, {r: "unverified"}], + [{verified: true}, {r: "unknown"}], + [{verified: null, blocked: false}, {r: "unknown"}], + [{}, {r: "unknown"}], + ], +} + +{ + name: "bools: boolean cells do not match truthy or falsy non-booleans", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["true", "'true'"], + ["false", "'false'"], + ["!= true", "'not true'"], + ["$ == false or $ == null", "'false or null'"], + ]}, + ], + }, + cases: [ + [{v: true}, [{r: "true"}]], + [{v: false}, [{r: "false"}, {r: "not true"}, {r: "false or null"}]], + [{v: null}, [{r: "not true"}, {r: "false or null"}]], + [{}, [{r: "not true"}, {r: "false or null"}]], + [{v: 1}, [{r: "not true"}]], + [{v: 0}, [{r: "not true"}]], + [{v: "true"}, [{r: "not true"}]], + [{v: "false"}, [{r: "not true"}]], + [{v: ""}, [{r: "not true"}]], + [{v: []}, [{r: "not true"}]], + ], +} + +{ + name: "bools: `true, false` matches any boolean and nothing else", + graph: { + nodes: [ + {table: "t", inputs: ["flag"], outputs: ["r"], rules: [ + ["true, false", "'boolean'"], + ["", "'not boolean'"], + ]}, + ], + }, + cases: [ + [{flag: true}, {r: "boolean"}], + [{flag: false}, {r: "boolean"}], + [{flag: null}, {r: "not boolean"}], + [{flag: "true"}, {r: "not boolean"}], + [{}, {r: "not boolean"}], + ], +} + +{ + name: "bools: treating null as false needs an explicit default in the field", + graph: { + nodes: [ + {table: "t", inputs: ["optIn ?? false"], outputs: ["r"], rules: [ + ["true", "'subscribed'"], + ["false", "'not subscribed'"], + ["", "'invalid'"], + ]}, + ], + }, + cases: [ + [{optIn: true}, {r: "subscribed"}], + [{optIn: false}, {r: "not subscribed"}], + [{optIn: null}, {r: "not subscribed"}], + [{}, {r: "not subscribed"}], + [{optIn: "yes"}, {r: "invalid"}], + ], +} + +{ + name: "bools: a field-less column with boolean expressions over inputs", + graph: { + nodes: [ + {table: "t", inputs: [null, "premium"], outputs: ["shipping"], rules: [ + ["total >= 50", "", "0"], + ["", "true", "0"], + ["express == true", "false", "15"], + ["", "", "5"], + ]}, + ], + }, + cases: [ + [{total: 60, premium: false}, {shipping: 0}], + [{total: 10, premium: true}, {shipping: 0}], + [{total: 10, premium: false, express: true}, {shipping: 15}], + [{total: 10, premium: false}, {shipping: 5}], + [{total: 10}, {shipping: 5}], + [{total: 10, express: true}, {shipping: 5}], + ], +} + +{ + name: "bools: boolean outputs from comparisons and literals", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["age"], outputs: ["adult", "senior", "eligible"], rules: [ + [">= 18", "true", "age >= 65", "member == true"], + ["", "false", "false", "false"], + ]}, + ], + }, + cases: [ + [{age: 30, member: true}, {age: 30, member: true, adult: true, senior: false, eligible: true}], + [{age: 70}, {age: 70, adult: true, senior: true, eligible: false}], + [{age: 10, member: true}, {age: 10, member: true, adult: false, senior: false, eligible: false}], + [{age: null}, {adult: false, senior: false, eligible: false}], + ], +} + +{ + name: "bools: indexed boolean columns combined with strings", + graph: { + nodes: [ + {table: "t", inputs: ["tier", "active", "trial"], outputs: ["r"], rules: [ + ["'gold'", "true", "false", "'gold active'"], + ["'gold'", "true", "true", "'gold trial'"], + ["'gold'", "false", "", "'gold inactive'"], + ["'silver'", "true", "false", "'silver active'"], + ["'silver'", "true", "true", "'silver trial'"], + ["'silver'", "false", "", "'silver inactive'"], + ["", "true", "", "'other active'"], + ["", "false", "", "'other inactive'"], + ["", "", "", "'unknown'"], + ]}, + ], + }, + cases: [ + [{tier: "gold", active: true, trial: false}, {r: "gold active"}], + [{tier: "gold", active: true, trial: true}, {r: "gold trial"}], + [{tier: "gold", active: false}, {r: "gold inactive"}], + [{tier: "silver", active: true, trial: true}, {r: "silver trial"}], + [{tier: "silver", active: true}, {r: "other active"}], + [{tier: "bronze", active: false}, {r: "other inactive"}], + [{tier: "gold", active: "true", trial: false}, {r: "unknown"}], + [{tier: "gold", active: 1}, {r: "unknown"}], + [{tier: "gold"}, {r: "unknown"}], + ], +} + +{ + name: "bools: indexed collect over a boolean column", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["ok"], outputs: ["r"], rules: [ + ["true", "'t1'"], + ["false", "'f1'"], + ["true", "'t2'"], + ["false", "'f2'"], + ["true, false", "'any bool'"], + ["", "'any'"], + ["!= true", "'not true'"], + ["null", "'null'"], + ]}, + ], + }, + cases: [ + [{ok: true}, [{r: "t1"}, {r: "t2"}, {r: "any bool"}, {r: "any"}]], + [{ok: false}, [{r: "f1"}, {r: "f2"}, {r: "any bool"}, {r: "any"}, {r: "not true"}]], + [{ok: null}, [{r: "any"}, {r: "not true"}, {r: "null"}]], + [{}, [{r: "any"}, {r: "not true"}, {r: "null"}]], + [{ok: "true"}, [{r: "any"}, {r: "not true"}]], + [{ok: 0}, [{r: "any"}, {r: "not true"}]], + ], +} + +{ + name: "bools: schema-declared booleans and a missing optional boolean", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {consent: {type: "boolean"}, adult: {type: "boolean"}}}}, + {table: "t", inputs: ["consent", "adult"], outputs: ["r"], rules: [ + ["true", "true", "'allowed'"], + ["true", "false", "'guardian needed'"], + ["false", "", "'refused'"], + ["", "", "'ask'"], + ]}, + ], + }, + cases: [ + [{consent: true, adult: true}, {r: "allowed"}], + [{consent: true, adult: false}, {r: "guardian needed"}], + [{consent: false}, {r: "refused"}], + [{}, {r: "ask"}], + [{consent: true}, {r: "ask"}], + [{consent: "true"}, "!error: NodeError"], + ], +} + +// --- Dates and booleans together --------------------------------------------------------------- + +{ + name: "mixed: subscription status from a date and two flags", + graph: { + nodes: [ + {table: "t", inputs: ["cancelled", "d(renewsOn)", "autoRenew"], outputs: ["status"], rules: [ + ["true", "", "", "'cancelled'"], + ["", "< d()", "false", "'lapsed'"], + ["", "< d()", "true", "'renewing'"], + ["", "<= d().add(14, 'd')", "false", "'expiring'"], + ["", "", "", "'active'"], + ]}, + ], + }, + cases: [ + [{cancelled: true, renewsOn: "2026-01-01", autoRenew: true}, {status: "cancelled"}], + [{cancelled: false, renewsOn: "2025-03-01", autoRenew: false}, {status: "lapsed"}], + [{renewsOn: "2025-03-01", autoRenew: true}, {status: "renewing"}], + [{renewsOn: "2025-03-30", autoRenew: false}, {status: "expiring"}], + [{renewsOn: "2025-03-30", autoRenew: true}, {status: "active"}], + [{renewsOn: "2025-03-01"}, {status: "active"}], + ], +} + +{ + name: "mixed: a date check in a field-less column next to a boolean column", + graph: { + nodes: [ + {table: "t", inputs: ["kyc", null], outputs: ["r"], rules: [ + ["true", "d(kycDate) >= d().sub(1, 'y')", "'verified'"], + ["true", "", "'reverify'"], + ["", "", "'unverified'"], + ]}, + ], + }, + cases: [ + [{kyc: true, kycDate: "2024-06-01"}, {r: "verified"}], + [{kyc: true, kycDate: "2024-03-20T10:15:30Z"}, {r: "verified"}], + [{kyc: true, kycDate: "2024-03-19"}, {r: "reverify"}], + [{kyc: true}, {r: "reverify"}], + [{kyc: false, kycDate: "2025-01-01"}, {r: "unverified"}], + ], +} + +{ + name: "mixed: date and boolean outputs flow into a downstream expression", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["plan"], outputs: ["trialEnds", "billable"], rules: [ + ["'trial'", "d(start).add(14, 'd')", "false"], + ["", "null", "true"], + ]}, + {expression: "e", fields: {inTrial: "trialEnds != null and trialEnds > d()", billable: "billable"}}, + ], + }, + cases: [ + [{plan: "trial", start: "2025-03-10"}, {inTrial: true, billable: false}], + [{plan: "trial", start: "2025-03-01"}, {inTrial: false, billable: false}], + [{plan: "pro", start: "2025-03-10"}, {inTrial: false, billable: true}], + ], +} diff --git a/core/engine/tests/spec/graph/29-table-large.json5 b/core/engine/tests/spec/graph/29-table-large.json5 new file mode 100644 index 00000000..ae257f67 --- /dev/null +++ b/core/engine/tests/spec/graph/29-table-large.json5 @@ -0,0 +1,1844 @@ +// Large decision tables. +// +// Tables with eight or more rules build an equality index per input column: cells that are +// literal string, number or boolean equalities (`'a'`, `5`, `true`, `'a', 'b'`, `in [1, 2]`, +// `[5..5]`, `$ == 'a'`) are looked up by value, every other cell (ranges, expressions, +// wildcards) is evaluated row by row. The index is an optimisation only: a large table must +// produce exactly what evaluating its rules top to bottom produces, in both hit policies, for +// every input type, with indexed and non-indexed rules interleaved, across many columns. + +// --- Equality index at scale --------------------------------------------------------------- +// One indexed column with 100-200 literal rules: every row is reachable, misses fall through. + +{ + name: "large: 200 string equality rules, each row reachable by its key", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["n"], rules: [ + ["'C000'", "0"], + ["'C001'", "1"], + ["'C002'", "2"], + ["'C003'", "3"], + ["'C004'", "4"], + ["'C005'", "5"], + ["'C006'", "6"], + ["'C007'", "7"], + ["'C008'", "8"], + ["'C009'", "9"], + ["'C010'", "10"], + ["'C011'", "11"], + ["'C012'", "12"], + ["'C013'", "13"], + ["'C014'", "14"], + ["'C015'", "15"], + ["'C016'", "16"], + ["'C017'", "17"], + ["'C018'", "18"], + ["'C019'", "19"], + ["'C020'", "20"], + ["'C021'", "21"], + ["'C022'", "22"], + ["'C023'", "23"], + ["'C024'", "24"], + ["'C025'", "25"], + ["'C026'", "26"], + ["'C027'", "27"], + ["'C028'", "28"], + ["'C029'", "29"], + ["'C030'", "30"], + ["'C031'", "31"], + ["'C032'", "32"], + ["'C033'", "33"], + ["'C034'", "34"], + ["'C035'", "35"], + ["'C036'", "36"], + ["'C037'", "37"], + ["'C038'", "38"], + ["'C039'", "39"], + ["'C040'", "40"], + ["'C041'", "41"], + ["'C042'", "42"], + ["'C043'", "43"], + ["'C044'", "44"], + ["'C045'", "45"], + ["'C046'", "46"], + ["'C047'", "47"], + ["'C048'", "48"], + ["'C049'", "49"], + ["'C050'", "50"], + ["'C051'", "51"], + ["'C052'", "52"], + ["'C053'", "53"], + ["'C054'", "54"], + ["'C055'", "55"], + ["'C056'", "56"], + ["'C057'", "57"], + ["'C058'", "58"], + ["'C059'", "59"], + ["'C060'", "60"], + ["'C061'", "61"], + ["'C062'", "62"], + ["'C063'", "63"], + ["'C064'", "64"], + ["'C065'", "65"], + ["'C066'", "66"], + ["'C067'", "67"], + ["'C068'", "68"], + ["'C069'", "69"], + ["'C070'", "70"], + ["'C071'", "71"], + ["'C072'", "72"], + ["'C073'", "73"], + ["'C074'", "74"], + ["'C075'", "75"], + ["'C076'", "76"], + ["'C077'", "77"], + ["'C078'", "78"], + ["'C079'", "79"], + ["'C080'", "80"], + ["'C081'", "81"], + ["'C082'", "82"], + ["'C083'", "83"], + ["'C084'", "84"], + ["'C085'", "85"], + ["'C086'", "86"], + ["'C087'", "87"], + ["'C088'", "88"], + ["'C089'", "89"], + ["'C090'", "90"], + ["'C091'", "91"], + ["'C092'", "92"], + ["'C093'", "93"], + ["'C094'", "94"], + ["'C095'", "95"], + ["'C096'", "96"], + ["'C097'", "97"], + ["'C098'", "98"], + ["'C099'", "99"], + ["'C100'", "100"], + ["'C101'", "101"], + ["'C102'", "102"], + ["'C103'", "103"], + ["'C104'", "104"], + ["'C105'", "105"], + ["'C106'", "106"], + ["'C107'", "107"], + ["'C108'", "108"], + ["'C109'", "109"], + ["'C110'", "110"], + ["'C111'", "111"], + ["'C112'", "112"], + ["'C113'", "113"], + ["'C114'", "114"], + ["'C115'", "115"], + ["'C116'", "116"], + ["'C117'", "117"], + ["'C118'", "118"], + ["'C119'", "119"], + ["'C120'", "120"], + ["'C121'", "121"], + ["'C122'", "122"], + ["'C123'", "123"], + ["'C124'", "124"], + ["'C125'", "125"], + ["'C126'", "126"], + ["'C127'", "127"], + ["'C128'", "128"], + ["'C129'", "129"], + ["'C130'", "130"], + ["'C131'", "131"], + ["'C132'", "132"], + ["'C133'", "133"], + ["'C134'", "134"], + ["'C135'", "135"], + ["'C136'", "136"], + ["'C137'", "137"], + ["'C138'", "138"], + ["'C139'", "139"], + ["'C140'", "140"], + ["'C141'", "141"], + ["'C142'", "142"], + ["'C143'", "143"], + ["'C144'", "144"], + ["'C145'", "145"], + ["'C146'", "146"], + ["'C147'", "147"], + ["'C148'", "148"], + ["'C149'", "149"], + ["'C150'", "150"], + ["'C151'", "151"], + ["'C152'", "152"], + ["'C153'", "153"], + ["'C154'", "154"], + ["'C155'", "155"], + ["'C156'", "156"], + ["'C157'", "157"], + ["'C158'", "158"], + ["'C159'", "159"], + ["'C160'", "160"], + ["'C161'", "161"], + ["'C162'", "162"], + ["'C163'", "163"], + ["'C164'", "164"], + ["'C165'", "165"], + ["'C166'", "166"], + ["'C167'", "167"], + ["'C168'", "168"], + ["'C169'", "169"], + ["'C170'", "170"], + ["'C171'", "171"], + ["'C172'", "172"], + ["'C173'", "173"], + ["'C174'", "174"], + ["'C175'", "175"], + ["'C176'", "176"], + ["'C177'", "177"], + ["'C178'", "178"], + ["'C179'", "179"], + ["'C180'", "180"], + ["'C181'", "181"], + ["'C182'", "182"], + ["'C183'", "183"], + ["'C184'", "184"], + ["'C185'", "185"], + ["'C186'", "186"], + ["'C187'", "187"], + ["'C188'", "188"], + ["'C189'", "189"], + ["'C190'", "190"], + ["'C191'", "191"], + ["'C192'", "192"], + ["'C193'", "193"], + ["'C194'", "194"], + ["'C195'", "195"], + ["'C196'", "196"], + ["'C197'", "197"], + ["'C198'", "198"], + ["'C199'", "199"], + ]}, + ], + }, + cases: [ + [{code: "C000"}, {n: 0}], + [{code: "C001"}, {n: 1}], + [{code: "C057"}, {n: 57}], + [{code: "C128"}, {n: 128}], + [{code: "C198"}, {n: 198}], + [{code: "C199"}, {n: 199}], + [{code: "C200"}, {}], + [{code: "c000"}, {}], + [{code: " C001"}, {}], + [{code: ""}, {}], + [{code: null}, {}], + [{code: 1}, {}], + [{code: ["C001"]}, {}], + [{}, {}], + ], +} + +{ + name: "large: 120 numeric equality rules including negatives, decimal forms of the key match", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["sq"], rules: [ + ["-20", "400"], + ["-19", "361"], + ["-18", "324"], + ["-17", "289"], + ["-16", "256"], + ["-15", "225"], + ["-14", "196"], + ["-13", "169"], + ["-12", "144"], + ["-11", "121"], + ["-10", "100"], + ["-9", "81"], + ["-8", "64"], + ["-7", "49"], + ["-6", "36"], + ["-5", "25"], + ["-4", "16"], + ["-3", "9"], + ["-2", "4"], + ["-1", "1"], + ["0", "0"], + ["1", "1"], + ["2", "4"], + ["3", "9"], + ["4", "16"], + ["5", "25"], + ["6", "36"], + ["7", "49"], + ["8", "64"], + ["9", "81"], + ["10", "100"], + ["11", "121"], + ["12", "144"], + ["13", "169"], + ["14", "196"], + ["15", "225"], + ["16", "256"], + ["17", "289"], + ["18", "324"], + ["19", "361"], + ["20", "400"], + ["21", "441"], + ["22", "484"], + ["23", "529"], + ["24", "576"], + ["25", "625"], + ["26", "676"], + ["27", "729"], + ["28", "784"], + ["29", "841"], + ["30", "900"], + ["31", "961"], + ["32", "1024"], + ["33", "1089"], + ["34", "1156"], + ["35", "1225"], + ["36", "1296"], + ["37", "1369"], + ["38", "1444"], + ["39", "1521"], + ["40", "1600"], + ["41", "1681"], + ["42", "1764"], + ["43", "1849"], + ["44", "1936"], + ["45", "2025"], + ["46", "2116"], + ["47", "2209"], + ["48", "2304"], + ["49", "2401"], + ["50", "2500"], + ["51", "2601"], + ["52", "2704"], + ["53", "2809"], + ["54", "2916"], + ["55", "3025"], + ["56", "3136"], + ["57", "3249"], + ["58", "3364"], + ["59", "3481"], + ["60", "3600"], + ["61", "3721"], + ["62", "3844"], + ["63", "3969"], + ["64", "4096"], + ["65", "4225"], + ["66", "4356"], + ["67", "4489"], + ["68", "4624"], + ["69", "4761"], + ["70", "4900"], + ["71", "5041"], + ["72", "5184"], + ["73", "5329"], + ["74", "5476"], + ["75", "5625"], + ["76", "5776"], + ["77", "5929"], + ["78", "6084"], + ["79", "6241"], + ["80", "6400"], + ["81", "6561"], + ["82", "6724"], + ["83", "6889"], + ["84", "7056"], + ["85", "7225"], + ["86", "7396"], + ["87", "7569"], + ["88", "7744"], + ["89", "7921"], + ["90", "8100"], + ["91", "8281"], + ["92", "8464"], + ["93", "8649"], + ["94", "8836"], + ["95", "9025"], + ["96", "9216"], + ["97", "9409"], + ["98", "9604"], + ["99", "9801"], + ]}, + ], + }, + cases: [ + [{k: -20}, {sq: 400}], + [{k: -1}, {sq: 1}], + [{k: 0}, {sq: 0}], + [{k: 7}, {sq: 49}], + [{k: 99}, {sq: 9801}], + [{k: 7.0}, {sq: 49}], + [{k: 7.000}, {sq: 49}], + [{k: -0}, {sq: 0}], + [{k: 1e1}, {sq: 100}], + [{k: 7.5}, {}], + [{k: 100}, {}], + [{k: -21}, {}], + [{k: "7"}, {}], + [{k: true}, {}], + [{k: null}, {}], + ], +} + +{ + name: "large: one column with number, string and boolean literals never coerces between them", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["0", "'n'"], + ["1", "'n'"], + ["2", "'n'"], + ["3", "'n'"], + ["4", "'n'"], + ["5", "'n'"], + ["6", "'n'"], + ["7", "'n'"], + ["8", "'n'"], + ["9", "'n'"], + ["'0'", "'s'"], + ["'1'", "'s'"], + ["'2'", "'s'"], + ["'3'", "'s'"], + ["'4'", "'s'"], + ["'5'", "'s'"], + ["'6'", "'s'"], + ["'7'", "'s'"], + ["'8'", "'s'"], + ["'9'", "'s'"], + ["true", "'t'"], + ["false", "'f'"], + ]}, + ], + }, + cases: [ + [{v: 3}, {r: "n"}], + [{v: "3"}, {r: "s"}], + [{v: 0}, {r: "n"}], + [{v: "0"}, {r: "s"}], + [{v: true}, {r: "t"}], + [{v: false}, {r: "f"}], + [{v: "true"}, {}], + [{v: 1.0}, {r: "n"}], + [{v: ""}, {}], + [{v: null}, {}], + [{}, {}], + ], +} + +// --- Cell forms the index recognises ------------------------------------------------------- +// Every recognised equality form must behave exactly like the same cell evaluated directly, and +// forms the index does not recognise must still be evaluated in their position. + +{ + name: "index forms: string equality written every supported way", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["'a'", "'plain'"], + ["== 'b'", "'eq-op'"], + ["$ == 'c'", "'dollar-left'"], + ["'d' == $", "'dollar-right'"], + ["'e', 'f'", "'list'"], + ["in ['g', 'h']", "'in-array'"], + ["$ in ['i']", "'dollar-in'"], + ["\"j\"", "'double-quoted'"], + ["('k')", "'parenthesized'"], + ["$ == 'l' or $ == 'm'", "'or'"], + ["not in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'z']", "'not-in'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{s: "a"}, {r: "plain"}], + [{s: "b"}, {r: "eq-op"}], + [{s: "c"}, {r: "dollar-left"}], + [{s: "d"}, {r: "dollar-right"}], + [{s: "e"}, {r: "list"}], + [{s: "f"}, {r: "list"}], + [{s: "g"}, {r: "in-array"}], + [{s: "h"}, {r: "in-array"}], + [{s: "i"}, {r: "dollar-in"}], + [{s: "j"}, {r: "double-quoted"}], + [{s: "k"}, {r: "parenthesized"}], + [{s: "l"}, {r: "or"}], + [{s: "m"}, {r: "or"}], + [{s: "n"}, {r: "not-in"}], + [{s: "z"}, {r: "fallback"}], + [{s: null}, {r: "not-in"}], + [{}, {r: "not-in"}], + [{s: 1}, {r: "not-in"}], + ], +} + +{ + name: "index forms: numeric equality, lists, point intervals and ranges", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["1", "'plain'"], + ["== 2", "'eq-op'"], + ["$ == 3", "'dollar'"], + ["4 == $", "'dollar-right'"], + ["5, 6", "'list'"], + ["in [7, 8]", "'in-array'"], + ["[9..9]", "'closed-point'"], + ["-10", "'negative'"], + ["(11)", "'parenthesized'"], + [">= 12 and <= 12", "'and-point'"], + ["(13..13)", "'empty-open'"], + ["[14..16]", "'range'"], + ["1.50", "'decimal'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {r: "plain"}], + [{n: 2}, {r: "eq-op"}], + [{n: 3}, {r: "dollar"}], + [{n: 4}, {r: "dollar-right"}], + [{n: 5}, {r: "list"}], + [{n: 6}, {r: "list"}], + [{n: 7}, {r: "in-array"}], + [{n: 8}, {r: "in-array"}], + [{n: 9}, {r: "closed-point"}], + [{n: -10}, {r: "negative"}], + [{n: 10}, {r: "fallback"}], + [{n: 11}, {r: "parenthesized"}], + [{n: 12}, {r: "and-point"}], + [{n: 13}, {r: "fallback"}], + [{n: 14}, {r: "range"}], + [{n: 15}, {r: "range"}], + [{n: 15.5}, {r: "range"}], + [{n: 16}, {r: "range"}], + [{n: 1.5}, {r: "decimal"}], + [{n: 17}, {r: "fallback"}], + [{n: "1"}, {r: "fallback"}], + [{n: null}, {r: "fallback"}], + ], +} + +{ + name: "index forms: boolean cells in a collect table", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["b"], outputs: ["r"], rules: [ + ["true", "'t1'"], + ["false", "'f1'"], + ["true, false", "'either'"], + ["in [true]", "'t-in'"], + ["$ == false", "'f-dollar'"], + ["", "'x1'"], + ["", "'x2'"], + ["", "'x3'"], + ]}, + ], + }, + cases: [ + [{b: true}, [{r: "t1"}, {r: "either"}, {r: "t-in"}, {r: "x1"}, {r: "x2"}, {r: "x3"}]], + [{b: false}, [{r: "f1"}, {r: "either"}, {r: "f-dollar"}, {r: "x1"}, {r: "x2"}, {r: "x3"}]], + [{b: "true"}, [{r: "x1"}, {r: "x2"}, {r: "x3"}]], + [{b: 1}, [{r: "x1"}, {r: "x2"}, {r: "x3"}]], + [{b: null}, [{r: "x1"}, {r: "x2"}, {r: "x3"}]], + [{}, [{r: "x1"}, {r: "x2"}, {r: "x3"}]], + ], +} + +{ + name: "index forms: string keys with spaces, unicode, quotes and the empty string", + graph: { + nodes: [ + {table: "t", inputs: ["s"], outputs: ["r"], rules: [ + ["'it''s'", "'never'"], + ["\"it's\"", "'apostrophe'"], + ["'a b'", "'space'"], + ["'Ünï'", "'unicode'"], + ["''", "'empty'"], + ["'1'", "'digit'"], + ["'null'", "'null-text'"], + ["'A'", "'upper'"], + ["'a'", "'lower'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{s: "it's"}, {r: "apostrophe"}], + [{s: "a b"}, {r: "space"}], + [{s: "Ünï"}, {r: "unicode"}], + [{s: ""}, {r: "empty"}], + [{s: "1"}, {r: "digit"}], + [{s: "null"}, {r: "null-text"}], + [{s: null}, {r: "fallback"}], + [{s: "A"}, {r: "upper"}], + [{s: "a"}, {r: "lower"}], + [{s: "ab"}, {r: "fallback"}], + ], +} + +{ + name: "index forms: numeric keys compare by exact decimal value", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["r"], rules: [ + ["0.1", "'tenth'"], + ["0.10", "'tenth-again'"], + ["100", "'hundred'"], + ["1e2", "'hundred-exp'"], + ["12345678901234567890", "'big'"], + ["0.000001", "'tiny'"], + ["-0.5", "'neg-half'"], + ["0", "'zero'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{x: 0.1}, {r: "tenth"}], + [{x: 0.10}, {r: "tenth"}], + [{x: 100}, {r: "hundred"}], + [{x: 100.00}, {r: "hundred"}], + [{x: 12345678901234567890}, {r: "big"}], + [{x: 12345678901234567891}, {r: "fallback"}], + [{x: 0.000001}, {r: "tiny"}], + [{x: 0.0000010}, {r: "tiny"}], + [{x: -0.50}, {r: "neg-half"}], + [{x: -0}, {r: "zero"}], + [{x: 0.0}, {r: "zero"}], + [{x: 0.2}, {r: "fallback"}], + ], +} + +// --- Indexed and evaluated rules interleaved ----------------------------------------------- +// Rules the index cannot decide keep their place in the rule order: a range or expression rule +// before an equality rule must win under first hit and appear first under collect. + +{ + name: "interleaved: first hit over 40 equality and range rules keeps rule order", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["0", "'eq-0'"], + ["10", "'eq-1'"], + ["20", "'eq-2'"], + ["30", "'eq-3'"], + ["[40..90]", "'range-4'"], + ["50", "'eq-5'"], + ["60", "'eq-6'"], + ["70", "'eq-7'"], + ["80", "'eq-8'"], + ["[90..140]", "'range-9'"], + ["100", "'eq-10'"], + ["110", "'eq-11'"], + ["120", "'eq-12'"], + ["130", "'eq-13'"], + ["[140..190]", "'range-14'"], + ["150", "'eq-15'"], + ["160", "'eq-16'"], + ["170", "'eq-17'"], + ["180", "'eq-18'"], + ["[190..240]", "'range-19'"], + ["200", "'eq-20'"], + ["210", "'eq-21'"], + ["220", "'eq-22'"], + ["230", "'eq-23'"], + ["[240..290]", "'range-24'"], + ["250", "'eq-25'"], + ["260", "'eq-26'"], + ["270", "'eq-27'"], + ["280", "'eq-28'"], + ["[290..340]", "'range-29'"], + ["300", "'eq-30'"], + ["310", "'eq-31'"], + ["320", "'eq-32'"], + ["330", "'eq-33'"], + ["[340..390]", "'range-34'"], + ["350", "'eq-35'"], + ["360", "'eq-36'"], + ["370", "'eq-37'"], + ["380", "'eq-38'"], + ["[390..440]", "'range-39'"], + ["", "'default'"], + ]}, + ], + }, + cases: [ + [{v: 0}, {r: "eq-0"}], + [{v: 30}, {r: "eq-3"}], + [{v: 40}, {r: "range-4"}], + [{v: 45}, {r: "range-4"}], + [{v: 50}, {r: "range-4"}], + [{v: 60}, {r: "range-4"}], + [{v: 90}, {r: "range-4"}], + [{v: 100}, {r: "range-9"}], + [{v: 140}, {r: "range-9"}], + [{v: 190}, {r: "range-14"}], + [{v: 230}, {r: "range-19"}], + [{v: 390}, {r: "range-34"}], + [{v: 395}, {r: "range-39"}], + [{v: 440}, {r: "range-39"}], + [{v: 1000}, {r: "default"}], + [{v: -10}, {r: "default"}], + [{v: null}, {r: "default"}], + [{}, {r: "default"}], + ], +} + +{ + name: "interleaved: collect over the same 40 rules returns indexed and range rows in order", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["0", "'eq-0'"], + ["10", "'eq-1'"], + ["20", "'eq-2'"], + ["30", "'eq-3'"], + ["[40..90]", "'range-4'"], + ["50", "'eq-5'"], + ["60", "'eq-6'"], + ["70", "'eq-7'"], + ["80", "'eq-8'"], + ["[90..140]", "'range-9'"], + ["100", "'eq-10'"], + ["110", "'eq-11'"], + ["120", "'eq-12'"], + ["130", "'eq-13'"], + ["[140..190]", "'range-14'"], + ["150", "'eq-15'"], + ["160", "'eq-16'"], + ["170", "'eq-17'"], + ["180", "'eq-18'"], + ["[190..240]", "'range-19'"], + ["200", "'eq-20'"], + ["210", "'eq-21'"], + ["220", "'eq-22'"], + ["230", "'eq-23'"], + ["[240..290]", "'range-24'"], + ["250", "'eq-25'"], + ["260", "'eq-26'"], + ["270", "'eq-27'"], + ["280", "'eq-28'"], + ["[290..340]", "'range-29'"], + ["300", "'eq-30'"], + ["310", "'eq-31'"], + ["320", "'eq-32'"], + ["330", "'eq-33'"], + ["[340..390]", "'range-34'"], + ["350", "'eq-35'"], + ["360", "'eq-36'"], + ["370", "'eq-37'"], + ["380", "'eq-38'"], + ["[390..440]", "'range-39'"], + ["", "'default'"], + ]}, + ], + }, + cases: [ + [{v: 0}, [{r: "eq-0"}, {r: "default"}]], + [{v: 30}, [{r: "eq-3"}, {r: "default"}]], + [{v: 40}, [{r: "range-4"}, {r: "default"}]], + [{v: 45}, [{r: "range-4"}, {r: "default"}]], + [{v: 50}, [{r: "range-4"}, {r: "eq-5"}, {r: "default"}]], + [{v: 60}, [{r: "range-4"}, {r: "eq-6"}, {r: "default"}]], + [{v: 90}, [{r: "range-4"}, {r: "range-9"}, {r: "default"}]], + [{v: 100}, [{r: "range-9"}, {r: "eq-10"}, {r: "default"}]], + [{v: 140}, [{r: "range-9"}, {r: "range-14"}, {r: "default"}]], + [{v: 190}, [{r: "range-14"}, {r: "range-19"}, {r: "default"}]], + [{v: 230}, [{r: "range-19"}, {r: "eq-23"}, {r: "default"}]], + [{v: 390}, [{r: "range-34"}, {r: "range-39"}, {r: "default"}]], + [{v: "40"}, [{r: "default"}]], + [{}, [{r: "default"}]], + ], +} + +{ + name: "interleaved: literal and expression cells mixed in one collect column", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["tier"], outputs: ["r"], rules: [ + ["'gold'", "'g1'"], + ["startsWith($, 'go')", "'prefix'"], + ["'gold'", "'g2'"], + ["len($) == 6", "'six'"], + ["'silver'", "'s1'"], + ["$ == other", "'same-as-other'"], + ["'bronze'", "'b1'"], + ["contains(allowed, $)", "'allowed'"], + ["'iron'", "'i1'"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [{tier: "gold"}, [{r: "g1"}, {r: "prefix"}, {r: "g2"}, {r: "none"}]], + [{tier: "goal"}, [{r: "prefix"}, {r: "none"}]], + [{tier: "silver"}, [{r: "six"}, {r: "s1"}, {r: "none"}]], + [{tier: "bronze", other: "bronze"}, [{r: "six"}, {r: "same-as-other"}, {r: "b1"}, {r: "none"}]], + [{tier: "iron", allowed: ["iron", "tin"]}, [{r: "allowed"}, {r: "i1"}, {r: "none"}]], + [{tier: "tin", allowed: ["iron", "tin"]}, [{r: "allowed"}, {r: "none"}]], + [{tier: null, other: null}, [{r: "same-as-other"}, {r: "none"}]], + ], +} + +{ + name: "interleaved: a wildcard in the second row shadows all later indexed rows", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["r"], rules: [ + ["'a'", "'r0'"], + ["", "'r1-wild'"], + ["'b'", "'r2'"], + ["'c'", "'r3'"], + ["'d'", "'r4'"], + ["'e'", "'r5'"], + ["'f'", "'r6'"], + ["'g'", "'r7'"], + ]}, + ], + }, + cases: [ + [{k: "a"}, {r: "r0"}], + [{k: "b"}, {r: "r1-wild"}], + [{k: "g"}, {r: "r1-wild"}], + [{}, {r: "r1-wild"}], + ], +} + +{ + name: "interleaved: repeated keys, collect returns every duplicate in order", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["k"], outputs: ["i"], rules: [ + ["'k0'", "0"], + ["'k1'", "1"], + ["'k2'", "2"], + ["'k3'", "3"], + ["'k4'", "4"], + ["'k0'", "5"], + ["'k1'", "6"], + ["'k2'", "7"], + ["'k3'", "8"], + ["'k4'", "9"], + ["'k0'", "10"], + ["'k1'", "11"], + ["'k2'", "12"], + ["'k3'", "13"], + ["'k4'", "14"], + ["'k0'", "15"], + ["'k1'", "16"], + ["'k2'", "17"], + ["'k3'", "18"], + ["'k4'", "19"], + ["'k0'", "20"], + ["'k1'", "21"], + ["'k2'", "22"], + ["'k3'", "23"], + ["'k4'", "24"], + ]}, + ], + }, + cases: [ + [{k: "k0"}, [{i: 0}, {i: 5}, {i: 10}, {i: 15}, {i: 20}]], + [{k: "k3"}, [{i: 3}, {i: 8}, {i: 13}, {i: 18}, {i: 23}]], + [{k: "k5"}, []], + ], +} + +{ + name: "interleaved: repeated keys, first hit takes the earliest duplicate", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["i"], rules: [ + ["'k0'", "0"], + ["'k1'", "1"], + ["'k2'", "2"], + ["'k3'", "3"], + ["'k4'", "4"], + ["'k0'", "5"], + ["'k1'", "6"], + ["'k2'", "7"], + ["'k3'", "8"], + ["'k4'", "9"], + ["'k0'", "10"], + ["'k1'", "11"], + ["'k2'", "12"], + ["'k3'", "13"], + ["'k4'", "14"], + ["'k0'", "15"], + ["'k1'", "16"], + ["'k2'", "17"], + ["'k3'", "18"], + ["'k4'", "19"], + ["'k0'", "20"], + ["'k1'", "21"], + ["'k2'", "22"], + ["'k3'", "23"], + ["'k4'", "24"], + ]}, + ], + }, + cases: [ + [{k: "k0"}, {i: 0}], + [{k: "k4"}, {i: 4}], + [{k: "k5"}, {}], + [{k: null}, {}], + ], +} + +{ + name: "interleaved: an output cell error in the indexed row falls through to a later row", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["r", "x"], rules: [ + ["'a'", "'r0'", "1 + 'x'"], + ["'a', 'b'", "'r1'", "2"], + ["'c'", "'r-c'", "0"], + ["'d'", "'r-d'", "0"], + ["'e'", "'r-e'", "0"], + ["'f'", "'r-f'", "0"], + ["'g'", "'r-g'", "0"], + ["'h'", "'r-h'", "0"], + ["", "'tail'", "upper(k)"], + ]}, + ], + }, + cases: [ + [{k: "a"}, {r: "r1", x: 2}], + [{k: "b"}, {r: "r1", x: 2}], + [{k: "h"}, {r: "r-h", x: 0}], + [{k: "z"}, {r: "tail", x: "Z"}], + [{k: 1}, {}], + ], +} + +// --- Indexed columns on derived fields ----------------------------------------------------- +// The index looks the column value up however the field is written: dotted, indexed or computed. + +{ + name: "derived fields: a dotted path field", + graph: { + nodes: [ + {table: "t", inputs: ["customer.address.state"], outputs: ["n"], rules: [ + ["'CA'", "0"], + ["'NY'", "1"], + ["'TX'", "2"], + ["'FL'", "3"], + ["'WA'", "4"], + ["'OR'", "5"], + ["'NV'", "6"], + ["'AZ'", "7"], + ["'CO'", "8"], + ["'UT'", "9"], + ["'IL'", "10"], + ["'OH'", "11"], + ]}, + ], + }, + cases: [ + [{customer: {address: {state: "TX"}}}, {n: 2}], + [{customer: {address: {state: "OH"}}}, {n: 11}], + [{customer: {address: {state: "ZZ"}}}, {}], + [{customer: {address: {}}}, {}], + [{customer: {address: null}}, {}], + [{customer: {}}, {}], + [{}, {}], + ], +} + +{ + name: "derived fields: a computed field expression", + graph: { + nodes: [ + {table: "t", inputs: ["upper(trim(state ?? ''))"], outputs: ["n"], rules: [ + ["'CA'", "0"], + ["'NY'", "1"], + ["'TX'", "2"], + ["'FL'", "3"], + ["'WA'", "4"], + ["'OR'", "5"], + ["'NV'", "6"], + ["'AZ'", "7"], + ["'CO'", "8"], + ["'UT'", "9"], + ["'IL'", "10"], + ["'OH'", "11"], + ]}, + ], + }, + cases: [ + [{state: "ca"}, {n: 0}], + [{state: " wa "}, {n: 4}], + [{state: "Oh"}, {n: 11}], + [{state: "xx"}, {}], + [{state: null}, {}], + [{}, {}], + [{state: 5}, {}], + ], +} + +{ + name: "derived fields: an array index and a $nodes-free arithmetic field", + graph: { + nodes: [ + {table: "t", inputs: ["items[1]", "a + b"], outputs: ["n"], rules: [ + ["'CA'", "0", "0"], + ["'NY'", "1", "1"], + ["'TX'", "2", "2"], + ["'FL'", "3", "3"], + ["'WA'", "4", "4"], + ["'OR'", "5", "5"], + ["'NV'", "6", "6"], + ["'AZ'", "7", "7"], + ["'CO'", "8", "8"], + ["'UT'", "9", "9"], + ["'IL'", "10", "10"], + ["'OH'", "11", "11"], + ]}, + ], + }, + cases: [ + [{items: ["x", "NY"], a: 0, b: 1}, {n: 1}], + [{items: ["x", "NY"], a: 1, b: 1}, {}], + [{items: ["x", "OH"], a: 5, b: 6}, {n: 11}], + [{items: ["OH"], a: 5, b: 6}, {}], + [{items: [], a: 5, b: 6}, {}], + [{items: ["x", "CA"], a: 0.5, b: -0.5}, {n: 0}], + [{items: ["x", "CA"], a: "0", b: 0}, {}], + ], +} + +{ + name: "derived fields: an indexed column next to a field-less expression column", + graph: { + nodes: [ + {table: "t", inputs: ["state", null], outputs: ["n"], rules: [ + ["'CA'", "amount > 100", "0"], + ["'NY'", "", "1"], + ["'TX'", "amount > 100", "2"], + ["'FL'", "", "3"], + ["'WA'", "amount > 100", "4"], + ["'OR'", "", "5"], + ["'NV'", "amount > 100", "6"], + ["'AZ'", "", "7"], + ["'CO'", "amount > 100", "8"], + ["'UT'", "", "9"], + ["'IL'", "amount > 100", "10"], + ["'OH'", "", "11"], + ["", "amount > 1000", "99"], + ]}, + ], + }, + cases: [ + [{state: "CA", amount: 200}, {n: 0}], + [{state: "CA", amount: 50}, {}], + [{state: "NY", amount: 50}, {n: 1}], + [{state: "NY"}, {n: 1}], + [{state: "TX", amount: 5000}, {n: 2}], + [{state: "ZZ", amount: 5000}, {n: 99}], + [{state: "CA", amount: "500"}, {}], + ], +} + +// --- First hit versus collect over big tables ---------------------------------------------- +// The same 60-rule table under both hit policies; first hit equals the head of collect. + +{ + name: "hit policy: a 61-rule pricing table, first hit", + graph: { + nodes: [ + {table: "t", inputs: ["tier", "region", "amount"], outputs: ["d"], rules: [ + ["'bronze'", "'eu'", "[0..100)", "0"], + ["'bronze'", "'eu'", "[100..1000)", "1"], + ["'bronze'", "'eu'", ">= 1000", "2"], + ["'bronze'", "'us'", "[0..100)", "1"], + ["'bronze'", "'us'", "[100..1000)", "2"], + ["'bronze'", "'us'", ">= 1000", "3"], + ["'bronze'", "'apac'", "[0..100)", "2"], + ["'bronze'", "'apac'", "[100..1000)", "3"], + ["'bronze'", "'apac'", ">= 1000", "4"], + ["'silver'", "'eu'", "[0..100)", "5"], + ["'silver'", "'eu'", "[100..1000)", "6"], + ["'silver'", "'eu'", ">= 1000", "7"], + ["'silver'", "'us'", "[0..100)", "6"], + ["'silver'", "'us'", "[100..1000)", "7"], + ["'silver'", "'us'", ">= 1000", "8"], + ["'silver'", "'apac'", "[0..100)", "7"], + ["'silver'", "'apac'", "[100..1000)", "8"], + ["'silver'", "'apac'", ">= 1000", "9"], + ["'gold'", "'eu'", "[0..100)", "10"], + ["'gold'", "'eu'", "[100..1000)", "11"], + ["'gold'", "'eu'", ">= 1000", "12"], + ["'gold'", "'us'", "[0..100)", "11"], + ["'gold'", "'us'", "[100..1000)", "12"], + ["'gold'", "'us'", ">= 1000", "13"], + ["'gold'", "'apac'", "[0..100)", "12"], + ["'gold'", "'apac'", "[100..1000)", "13"], + ["'gold'", "'apac'", ">= 1000", "14"], + ["'platinum'", "'eu'", "[0..100)", "15"], + ["'platinum'", "'eu'", "[100..1000)", "16"], + ["'platinum'", "'eu'", ">= 1000", "17"], + ["'platinum'", "'us'", "[0..100)", "16"], + ["'platinum'", "'us'", "[100..1000)", "17"], + ["'platinum'", "'us'", ">= 1000", "18"], + ["'platinum'", "'apac'", "[0..100)", "17"], + ["'platinum'", "'apac'", "[100..1000)", "18"], + ["'platinum'", "'apac'", ">= 1000", "19"], + ["'bronze'", "", "", "-1"], + ["'silver'", "", "", "-1"], + ["'gold'", "", "", "-1"], + ["'platinum'", "", "", "-1"], + ["", "", "", "-2"], + ]}, + ], + }, + cases: [ + [{tier: "gold", region: "us", amount: 50}, {d: 11}], + [{tier: "gold", region: "us", amount: 100}, {d: 12}], + [{tier: "gold", region: "us", amount: 5000}, {d: 13}], + [{tier: "platinum", region: "apac", amount: 999}, {d: 18}], + [{tier: "bronze", region: "eu", amount: 0}, {d: 0}], + [{tier: "bronze", region: "mars", amount: 10}, {d: -1}], + [{tier: "silver", region: "eu"}, {d: -1}], + [{tier: "diamond", region: "eu", amount: 10}, {d: -2}], + [{tier: "gold", region: "us", amount: -1}, {d: -1}], + [{}, {d: -2}], + ], +} + +{ + name: "hit policy: the same 61-rule pricing table, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["tier", "region", "amount"], outputs: ["d"], rules: [ + ["'bronze'", "'eu'", "[0..100)", "0"], + ["'bronze'", "'eu'", "[100..1000)", "1"], + ["'bronze'", "'eu'", ">= 1000", "2"], + ["'bronze'", "'us'", "[0..100)", "1"], + ["'bronze'", "'us'", "[100..1000)", "2"], + ["'bronze'", "'us'", ">= 1000", "3"], + ["'bronze'", "'apac'", "[0..100)", "2"], + ["'bronze'", "'apac'", "[100..1000)", "3"], + ["'bronze'", "'apac'", ">= 1000", "4"], + ["'silver'", "'eu'", "[0..100)", "5"], + ["'silver'", "'eu'", "[100..1000)", "6"], + ["'silver'", "'eu'", ">= 1000", "7"], + ["'silver'", "'us'", "[0..100)", "6"], + ["'silver'", "'us'", "[100..1000)", "7"], + ["'silver'", "'us'", ">= 1000", "8"], + ["'silver'", "'apac'", "[0..100)", "7"], + ["'silver'", "'apac'", "[100..1000)", "8"], + ["'silver'", "'apac'", ">= 1000", "9"], + ["'gold'", "'eu'", "[0..100)", "10"], + ["'gold'", "'eu'", "[100..1000)", "11"], + ["'gold'", "'eu'", ">= 1000", "12"], + ["'gold'", "'us'", "[0..100)", "11"], + ["'gold'", "'us'", "[100..1000)", "12"], + ["'gold'", "'us'", ">= 1000", "13"], + ["'gold'", "'apac'", "[0..100)", "12"], + ["'gold'", "'apac'", "[100..1000)", "13"], + ["'gold'", "'apac'", ">= 1000", "14"], + ["'platinum'", "'eu'", "[0..100)", "15"], + ["'platinum'", "'eu'", "[100..1000)", "16"], + ["'platinum'", "'eu'", ">= 1000", "17"], + ["'platinum'", "'us'", "[0..100)", "16"], + ["'platinum'", "'us'", "[100..1000)", "17"], + ["'platinum'", "'us'", ">= 1000", "18"], + ["'platinum'", "'apac'", "[0..100)", "17"], + ["'platinum'", "'apac'", "[100..1000)", "18"], + ["'platinum'", "'apac'", ">= 1000", "19"], + ["'bronze'", "", "", "-1"], + ["'silver'", "", "", "-1"], + ["'gold'", "", "", "-1"], + ["'platinum'", "", "", "-1"], + ["", "", "", "-2"], + ]}, + ], + }, + cases: [ + [{tier: "gold", region: "us", amount: 50}, [{d: 11}, {d: -1}, {d: -2}]], + [{tier: "gold", region: "us", amount: 100}, [{d: 12}, {d: -1}, {d: -2}]], + [{tier: "gold", region: "us", amount: 5000}, [{d: 13}, {d: -1}, {d: -2}]], + [{tier: "platinum", region: "apac", amount: 999}, [{d: 18}, {d: -1}, {d: -2}]], + [{tier: "bronze", region: "eu", amount: 0}, [{d: 0}, {d: -1}, {d: -2}]], + [{tier: "bronze", region: "mars", amount: 10}, [{d: -1}, {d: -2}]], + [{tier: "silver", region: "eu"}, [{d: -1}, {d: -2}]], + [{tier: "diamond", region: "eu", amount: 10}, [{d: -2}]], + [{tier: "gold", region: "us", amount: -1}, [{d: -1}, {d: -2}]], + [{}, [{d: -2}]], + ], +} + +{ + name: "hit policy: the same table with a `[]` column gathers every match, scalars from the first", + graph: { + nodes: [ + {table: "t", inputs: ["tier", "region", "amount"], outputs: ["d", "all[]"], rules: [ + ["'bronze'", "'eu'", "[0..100)", "0", "0"], + ["'bronze'", "'eu'", "[100..1000)", "1", "1"], + ["'bronze'", "'eu'", ">= 1000", "2", "2"], + ["'bronze'", "'us'", "[0..100)", "1", "1"], + ["'bronze'", "'us'", "[100..1000)", "2", "2"], + ["'bronze'", "'us'", ">= 1000", "3", "3"], + ["'bronze'", "'apac'", "[0..100)", "2", "2"], + ["'bronze'", "'apac'", "[100..1000)", "3", "3"], + ["'bronze'", "'apac'", ">= 1000", "4", "4"], + ["'silver'", "'eu'", "[0..100)", "5", "5"], + ["'silver'", "'eu'", "[100..1000)", "6", "6"], + ["'silver'", "'eu'", ">= 1000", "7", "7"], + ["'silver'", "'us'", "[0..100)", "6", "6"], + ["'silver'", "'us'", "[100..1000)", "7", "7"], + ["'silver'", "'us'", ">= 1000", "8", "8"], + ["'silver'", "'apac'", "[0..100)", "7", "7"], + ["'silver'", "'apac'", "[100..1000)", "8", "8"], + ["'silver'", "'apac'", ">= 1000", "9", "9"], + ["'gold'", "'eu'", "[0..100)", "10", "10"], + ["'gold'", "'eu'", "[100..1000)", "11", "11"], + ["'gold'", "'eu'", ">= 1000", "12", "12"], + ["'gold'", "'us'", "[0..100)", "11", "11"], + ["'gold'", "'us'", "[100..1000)", "12", "12"], + ["'gold'", "'us'", ">= 1000", "13", "13"], + ["'gold'", "'apac'", "[0..100)", "12", "12"], + ["'gold'", "'apac'", "[100..1000)", "13", "13"], + ["'gold'", "'apac'", ">= 1000", "14", "14"], + ["'platinum'", "'eu'", "[0..100)", "15", "15"], + ["'platinum'", "'eu'", "[100..1000)", "16", "16"], + ["'platinum'", "'eu'", ">= 1000", "17", "17"], + ["'platinum'", "'us'", "[0..100)", "16", "16"], + ["'platinum'", "'us'", "[100..1000)", "17", "17"], + ["'platinum'", "'us'", ">= 1000", "18", "18"], + ["'platinum'", "'apac'", "[0..100)", "17", "17"], + ["'platinum'", "'apac'", "[100..1000)", "18", "18"], + ["'platinum'", "'apac'", ">= 1000", "19", "19"], + ["'bronze'", "", "", "-1", "-1"], + ["'silver'", "", "", "-1", "-1"], + ["'gold'", "", "", "-1", "-1"], + ["'platinum'", "", "", "-1", "-1"], + ["", "", "", "-2", "-2"], + ]}, + ], + }, + cases: [ + [{tier: "gold", region: "us", amount: 50}, {d: 11, all: [11, -1, -2]}], + [{tier: "gold", region: "us", amount: 100}, {d: 12, all: [12, -1, -2]}], + [{tier: "gold", region: "us", amount: 5000}, {d: 13, all: [13, -1, -2]}], + [{tier: "platinum", region: "apac", amount: 999}, {d: 18, all: [18, -1, -2]}], + [{tier: "bronze", region: "eu", amount: 0}, {d: 0, all: [0, -1, -2]}], + [{tier: "bronze", region: "mars", amount: 10}, {d: -1, all: [-1, -2]}], + [{tier: "silver", region: "eu"}, {d: -1, all: [-1, -2]}], + [{tier: "diamond", region: "eu", amount: 10}, {d: -2, all: [-2]}], + [{tier: "gold", region: "us", amount: -1}, {d: -1, all: [-1, -2]}], + [{}, {d: -2, all: [-2]}], + ], +} + +{ + name: "hit policy: 20 wildcard rules, collect returns all of them", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["i"], rules: [ + ["", "0"], + ["", "1"], + ["", "2"], + ["", "3"], + ["", "4"], + ["", "5"], + ["", "6"], + ["", "7"], + ["", "8"], + ["", "9"], + ["", "10"], + ["", "11"], + ["", "12"], + ["", "13"], + ["", "14"], + ["", "15"], + ["", "16"], + ["", "17"], + ["", "18"], + ["", "19"], + ]}, + ], + }, + cases: [ + [{x: 1}, [{i: 0}, {i: 1}, {i: 2}, {i: 3}, {i: 4}, {i: 5}, {i: 6}, {i: 7}, {i: 8}, {i: 9}, {i: 10}, {i: 11}, {i: 12}, {i: 13}, {i: 14}, {i: 15}, {i: 16}, {i: 17}, {i: 18}, {i: 19}]], + [{}, [{i: 0}, {i: 1}, {i: 2}, {i: 3}, {i: 4}, {i: 5}, {i: 6}, {i: 7}, {i: 8}, {i: 9}, {i: 10}, {i: 11}, {i: 12}, {i: 13}, {i: 14}, {i: 15}, {i: 16}, {i: 17}, {i: 18}, {i: 19}]], + ], +} + +{ + name: "hit policy: a 30-rule collect table with no match is an empty array", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["i"], rules: [ + ["'v0'", "0"], + ["'v1'", "1"], + ["'v2'", "2"], + ["'v3'", "3"], + ["'v4'", "4"], + ["'v5'", "5"], + ["'v6'", "6"], + ["'v7'", "7"], + ["'v8'", "8"], + ["'v9'", "9"], + ["'v10'", "10"], + ["'v11'", "11"], + ["'v12'", "12"], + ["'v13'", "13"], + ["'v14'", "14"], + ["'v15'", "15"], + ["'v16'", "16"], + ["'v17'", "17"], + ["'v18'", "18"], + ["'v19'", "19"], + ["'v20'", "20"], + ["'v21'", "21"], + ["'v22'", "22"], + ["'v23'", "23"], + ["'v24'", "24"], + ["'v25'", "25"], + ["'v26'", "26"], + ["'v27'", "27"], + ["'v28'", "28"], + ["'v29'", "29"], + ]}, + ], + }, + cases: [ + [{x: "v30"}, []], + [{x: null}, []], + [{}, []], + [{x: "v29"}, [{i: 29}]], + ], +} + +{ + name: "hit policy: a 30-rule collect table under passThrough and outputPath", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, outputPath: "hits", inputs: ["x"], outputs: ["i"], rules: [ + ["'v0'", "0"], + ["'v1'", "1"], + ["'v2'", "2"], + ["'v3'", "3"], + ["'v4'", "4"], + ["'v5'", "5"], + ["'v6'", "6"], + ["'v7'", "7"], + ["'v8'", "8"], + ["'v9'", "9"], + ["'v10'", "10"], + ["'v11'", "11"], + ["'v12'", "12"], + ["'v13'", "13"], + ["'v14'", "14"], + ["'v15'", "15"], + ["'v16'", "16"], + ["'v17'", "17"], + ["'v18'", "18"], + ["'v19'", "19"], + ["'v20'", "20"], + ["'v21'", "21"], + ["'v22'", "22"], + ["'v23'", "23"], + ["'v24'", "24"], + ["'v25'", "25"], + ["'v26'", "26"], + ["'v27'", "27"], + ["'v28'", "28"], + ["'v29'", "29"], + ]}, + ], + }, + cases: [ + [{x: "v7"}, {x: "v7", hits: [{i: 7}]}], + [{x: "none"}, {x: "none", hits: []}], + [{}, {hits: []}], + ], +} + +// --- Many input columns -------------------------------------------------------------------- +// Six to ten columns: every column must pass, the index intersects the indexed ones. + +{ + name: "many columns: 64 rules over six boolean columns, one per combination", + graph: { + nodes: [ + {table: "t", inputs: ["f0", "f1", "f2", "f3", "f4", "f5"], outputs: ["i"], rules: [ + ["false", "false", "false", "false", "false", "false", "0"], + ["true", "false", "false", "false", "false", "false", "1"], + ["false", "true", "false", "false", "false", "false", "2"], + ["true", "true", "false", "false", "false", "false", "3"], + ["false", "false", "true", "false", "false", "false", "4"], + ["true", "false", "true", "false", "false", "false", "5"], + ["false", "true", "true", "false", "false", "false", "6"], + ["true", "true", "true", "false", "false", "false", "7"], + ["false", "false", "false", "true", "false", "false", "8"], + ["true", "false", "false", "true", "false", "false", "9"], + ["false", "true", "false", "true", "false", "false", "10"], + ["true", "true", "false", "true", "false", "false", "11"], + ["false", "false", "true", "true", "false", "false", "12"], + ["true", "false", "true", "true", "false", "false", "13"], + ["false", "true", "true", "true", "false", "false", "14"], + ["true", "true", "true", "true", "false", "false", "15"], + ["false", "false", "false", "false", "true", "false", "16"], + ["true", "false", "false", "false", "true", "false", "17"], + ["false", "true", "false", "false", "true", "false", "18"], + ["true", "true", "false", "false", "true", "false", "19"], + ["false", "false", "true", "false", "true", "false", "20"], + ["true", "false", "true", "false", "true", "false", "21"], + ["false", "true", "true", "false", "true", "false", "22"], + ["true", "true", "true", "false", "true", "false", "23"], + ["false", "false", "false", "true", "true", "false", "24"], + ["true", "false", "false", "true", "true", "false", "25"], + ["false", "true", "false", "true", "true", "false", "26"], + ["true", "true", "false", "true", "true", "false", "27"], + ["false", "false", "true", "true", "true", "false", "28"], + ["true", "false", "true", "true", "true", "false", "29"], + ["false", "true", "true", "true", "true", "false", "30"], + ["true", "true", "true", "true", "true", "false", "31"], + ["false", "false", "false", "false", "false", "true", "32"], + ["true", "false", "false", "false", "false", "true", "33"], + ["false", "true", "false", "false", "false", "true", "34"], + ["true", "true", "false", "false", "false", "true", "35"], + ["false", "false", "true", "false", "false", "true", "36"], + ["true", "false", "true", "false", "false", "true", "37"], + ["false", "true", "true", "false", "false", "true", "38"], + ["true", "true", "true", "false", "false", "true", "39"], + ["false", "false", "false", "true", "false", "true", "40"], + ["true", "false", "false", "true", "false", "true", "41"], + ["false", "true", "false", "true", "false", "true", "42"], + ["true", "true", "false", "true", "false", "true", "43"], + ["false", "false", "true", "true", "false", "true", "44"], + ["true", "false", "true", "true", "false", "true", "45"], + ["false", "true", "true", "true", "false", "true", "46"], + ["true", "true", "true", "true", "false", "true", "47"], + ["false", "false", "false", "false", "true", "true", "48"], + ["true", "false", "false", "false", "true", "true", "49"], + ["false", "true", "false", "false", "true", "true", "50"], + ["true", "true", "false", "false", "true", "true", "51"], + ["false", "false", "true", "false", "true", "true", "52"], + ["true", "false", "true", "false", "true", "true", "53"], + ["false", "true", "true", "false", "true", "true", "54"], + ["true", "true", "true", "false", "true", "true", "55"], + ["false", "false", "false", "true", "true", "true", "56"], + ["true", "false", "false", "true", "true", "true", "57"], + ["false", "true", "false", "true", "true", "true", "58"], + ["true", "true", "false", "true", "true", "true", "59"], + ["false", "false", "true", "true", "true", "true", "60"], + ["true", "false", "true", "true", "true", "true", "61"], + ["false", "true", "true", "true", "true", "true", "62"], + ["true", "true", "true", "true", "true", "true", "63"], + ]}, + ], + }, + cases: [ + [{f0: false, f1: false, f2: false, f3: false, f4: false, f5: false}, {i: 0}], + [{f0: true, f1: false, f2: false, f3: false, f4: false, f5: false}, {i: 1}], + [{f0: true, f1: false, f2: true, f3: false, f4: true, f5: false}, {i: 21}], + [{f0: false, f1: true, f2: false, f3: true, f4: false, f5: true}, {i: 42}], + [{f0: false, f1: true, f2: true, f3: true, f4: true, f5: true}, {i: 62}], + [{f0: true, f1: true, f2: true, f3: true, f4: true, f5: true}, {i: 63}], + [{f0: true, f1: false, f2: true, f3: false, f4: false, f5: null}, {}], + [{f0: true}, {}], + [{f0: true, f1: false, f2: 1, f3: false, f4: false, f5: false}, {}], + ], +} + +{ + name: "many columns: eight mixed columns, each column can veto the rule", + graph: { + nodes: [ + {table: "t", inputs: ["country", "channel", "vip", "items", "age", "score", "coupon", "segment"], outputs: ["r"], rules: [ + ["'US'", "'web'", "true", "> 10", "[18..65]", ">= 700", "", "'a', 'b'", "'r0'"], + ["'US'", "'web'", "true", "> 10", "", "", "'SAVE'", "", "'r1'"], + ["'US'", "'store'", "", "", "> 65", "", "", "'c'", "'r2'"], + ["'DE'", "", "false", "[1..5]", "", "< 500", "", "", "'r3'"], + ["'DE'", "'web'", "", "", "", "", "'SAVE', 'BIG'", "'a'", "'r4'"], + ["", "'app'", "true", "", "< 18", "", "", "", "'r5'"], + ["'FR'", "'app'", "", "0", "", "", "", "", "'r6'"], + ["", "", "", "", "", "> 900", "", "", "'r7'"], + ["'US'", "", "", "", "", "", "", "'z'", "'r8'"], + ["", "", "", "", "", "", "", "", "'r9'"], + ]}, + ], + }, + cases: [ + [{country: "US", channel: "web", vip: true, items: 11, age: 30, score: 750, coupon: null, segment: "a"}, {r: "r0"}], + [{country: "US", channel: "web", vip: true, items: 11, age: 30, score: 750, coupon: null, segment: "c"}, {r: "r9"}], + [{country: "US", channel: "web", vip: true, items: 11, age: 30, score: 750, coupon: "SAVE", segment: "c"}, {r: "r1"}], + [{country: "US", channel: "web", vip: true, items: 11, age: 70, score: 750, coupon: null, segment: "a"}, {r: "r9"}], + [{country: "US", channel: "store", vip: true, items: 11, age: 70, score: 750, coupon: null, segment: "c"}, {r: "r2"}], + [{country: "US", channel: "web", vip: true, items: 11, age: 30, score: 699, coupon: null, segment: "a"}, {r: "r9"}], + [{country: "US", channel: "web", vip: true, items: 1, age: 30, score: 950, coupon: null, segment: "a"}, {r: "r7"}], + [{country: "DE", vip: false, items: 3, score: 400}, {r: "r3"}], + [{country: "DE", channel: "web", coupon: "BIG", segment: "a"}, {r: "r4"}], + [{country: "IT", channel: "app", vip: true, age: 12}, {r: "r5"}], + [{country: "FR", channel: "app", items: 0}, {r: "r6"}], + [{country: "US", segment: "z"}, {r: "r8"}], + [{}, {r: "r9"}], + ], +} + +{ + name: "many columns: the same eight columns, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["country", "channel", "vip", "items", "age", "score", "coupon", "segment"], outputs: ["r"], rules: [ + ["'US'", "'web'", "true", "> 10", "[18..65]", ">= 700", "", "'a', 'b'", "'r0'"], + ["'US'", "'web'", "true", "> 10", "", "", "'SAVE'", "", "'r1'"], + ["'US'", "'store'", "", "", "> 65", "", "", "'c'", "'r2'"], + ["'DE'", "", "false", "[1..5]", "", "< 500", "", "", "'r3'"], + ["'DE'", "'web'", "", "", "", "", "'SAVE', 'BIG'", "'a'", "'r4'"], + ["", "'app'", "true", "", "< 18", "", "", "", "'r5'"], + ["'FR'", "'app'", "", "0", "", "", "", "", "'r6'"], + ["", "", "", "", "", "> 900", "", "", "'r7'"], + ["'US'", "", "", "", "", "", "", "'z'", "'r8'"], + ["", "", "", "", "", "", "", "", "'r9'"], + ]}, + ], + }, + cases: [ + [{country: "US", channel: "web", vip: true, items: 11, age: 30, score: 750, coupon: null, segment: "a"}, [{r: "r0"}, {r: "r9"}]], + [{country: "US", channel: "web", vip: true, items: 11, age: 30, score: 950, coupon: "SAVE", segment: "a"}, [{r: "r0"}, {r: "r1"}, {r: "r7"}, {r: "r9"}]], + [{country: "US", segment: "z", score: 901}, [{r: "r7"}, {r: "r8"}, {r: "r9"}]], + [{country: "DE", channel: "web", vip: false, items: 5, score: 100, coupon: "SAVE", segment: "a"}, [{r: "r3"}, {r: "r4"}, {r: "r9"}]], + [{}, [{r: "r9"}]], + ], +} + +{ + name: "many columns: ten columns with dotted, field-less and indexed columns", + graph: { + nodes: [ + {table: "t", inputs: ["p", "m.n", "flag", "deep.v", null, "q", "unused", "tail"], outputs: ["r", "i"], rules: [ + ["'p0'", "0", "false", "> 0", "", "'q0'", "", "'end'", "'r0'", "0"], + ["'p1'", "1", "true", "> 1", "", "'q1'", "", "'end'", "'r1'", "1"], + ["'p2'", "2", "false", "> 2", "", "'q2'", "", "'end'", "'r2'", "2"], + ["'p0'", "3", "true", "> 3", "", "'q3'", "", "'end'", "'r3'", "3"], + ["'p1'", "0", "false", "> 4", "", "'q4'", "", "'end'", "'r4'", "4"], + ["'p2'", "1", "true", "> 5", "", "'q5'", "", "'end'", "'r5'", "5"], + ["'p0'", "2", "false", "> 6", "", "'q6'", "", "'end'", "'r6'", "6"], + ["'p1'", "3", "true", "> 7", "a.b == 'x'", "'q7'", "", "'end'", "'r7'", "7"], + ["'p2'", "0", "false", "> 8", "", "'q8'", "", "'end'", "'r8'", "8"], + ["'p0'", "1", "true", "> 9", "", "'q9'", "", "'end'", "'r9'", "9"], + ["'p1'", "2", "false", "> 10", "", "'q10'", "", "'end'", "'r10'", "10"], + ["'p2'", "3", "true", "> 11", "", "'q11'", "", "'end'", "'r11'", "11"], + ]}, + ], + }, + cases: [ + [{p: "p0", m: {n: 0}, flag: false, deep: {v: 1}, q: "q0", tail: "end"}, {r: "r0", i: 0}], + [{p: "p1", m: {n: 3}, flag: true, deep: {v: 8}, a: {b: "x"}, q: "q7", tail: "end"}, {r: "r7", i: 7}], + [{p: "p1", m: {n: 3}, flag: true, deep: {v: 8}, a: {b: "y"}, q: "q7", tail: "end"}, {}], + [{p: "p2", m: {n: 3}, flag: true, deep: {v: 12}, q: "q11", tail: "end"}, {r: "r11", i: 11}], + [{p: "p2", m: {n: 3}, flag: true, deep: {v: 11}, q: "q11", tail: "end"}, {}], + [{p: "p2", m: {n: 3}, flag: true, deep: {v: 12}, q: "q11"}, {}], + [{p: "p0", m: {n: 0}, flag: false, deep: {v: 1}, q: "q0", tail: "end", unused: 5}, {r: "r0", i: 0}], + ], +} + +// --- Realistic large tables ---------------------------------------------------------------- + +{ + name: "realistic: a 101-rule sales tax table by state and category", + graph: { + nodes: [ + {table: "t", inputs: ["state", "category"], outputs: ["rate"], rules: [ + ["'AL'", "'food'", "0"], + ["'AL'", "", "0"], + ["'AK'", "'food'", "0.00625"], + ["'AK'", "", "0.0125"], + ["'AZ'", "'food'", "0.0125"], + ["'AZ'", "", "0.025"], + ["'AR'", "'food'", "0"], + ["'AR'", "", "0.0375"], + ["'CA'", "'food'", "0.02"], + ["'CA'", "", "0.04"], + ["'CO'", "'food'", "0.02625"], + ["'CO'", "", "0.0525"], + ["'CT'", "'food'", "0"], + ["'CT'", "", "0.065"], + ["'DE'", "'food'", "0.03875"], + ["'DE'", "", "0.0775"], + ["'FL'", "'food'", "0.04"], + ["'FL'", "", "0.08"], + ["'GA'", "'food'", "0"], + ["'GA'", "", "0.0025"], + ["'HI'", "'food'", "0.0075"], + ["'HI'", "", "0.015"], + ["'ID'", "'food'", "0.01375"], + ["'ID'", "", "0.0275"], + ["'IL'", "'food'", "0"], + ["'IL'", "", "0.03"], + ["'IN'", "'food'", "0.02125"], + ["'IN'", "", "0.0425"], + ["'IA'", "'food'", "0.0275"], + ["'IA'", "", "0.055"], + ["'KS'", "'food'", "0"], + ["'KS'", "", "0.0675"], + ["'KY'", "'food'", "0.035"], + ["'KY'", "", "0.07"], + ["'LA'", "'food'", "0.04125"], + ["'LA'", "", "0.0825"], + ["'ME'", "'food'", "0"], + ["'ME'", "", "0.005"], + ["'MD'", "'food'", "0.00875"], + ["'MD'", "", "0.0175"], + ["'MA'", "'food'", "0.01"], + ["'MA'", "", "0.02"], + ["'MI'", "'food'", "0"], + ["'MI'", "", "0.0325"], + ["'MN'", "'food'", "0.0225"], + ["'MN'", "", "0.045"], + ["'MS'", "'food'", "0.02875"], + ["'MS'", "", "0.0575"], + ["'MO'", "'food'", "0"], + ["'MO'", "", "0.06"], + ["'MT'", "'food'", "0.03625"], + ["'MT'", "", "0.0725"], + ["'NE'", "'food'", "0.0425"], + ["'NE'", "", "0.085"], + ["'NV'", "'food'", "0"], + ["'NV'", "", "0.0075"], + ["'NH'", "'food'", "0.005"], + ["'NH'", "", "0.01"], + ["'NJ'", "'food'", "0.01125"], + ["'NJ'", "", "0.0225"], + ["'NM'", "'food'", "0"], + ["'NM'", "", "0.035"], + ["'NY'", "'food'", "0.02375"], + ["'NY'", "", "0.0475"], + ["'NC'", "'food'", "0.025"], + ["'NC'", "", "0.05"], + ["'ND'", "'food'", "0"], + ["'ND'", "", "0.0625"], + ["'OH'", "'food'", "0.0375"], + ["'OH'", "", "0.075"], + ["'OK'", "'food'", "0.04375"], + ["'OK'", "", "0.0875"], + ["'OR'", "'food'", "0"], + ["'OR'", "", "0"], + ["'PA'", "'food'", "0.00625"], + ["'PA'", "", "0.0125"], + ["'RI'", "'food'", "0.0125"], + ["'RI'", "", "0.025"], + ["'SC'", "'food'", "0"], + ["'SC'", "", "0.0375"], + ["'SD'", "'food'", "0.02"], + ["'SD'", "", "0.04"], + ["'TN'", "'food'", "0.02625"], + ["'TN'", "", "0.0525"], + ["'TX'", "'food'", "0"], + ["'TX'", "", "0.065"], + ["'UT'", "'food'", "0.03875"], + ["'UT'", "", "0.0775"], + ["'VT'", "'food'", "0.04"], + ["'VT'", "", "0.08"], + ["'VA'", "'food'", "0"], + ["'VA'", "", "0.0025"], + ["'WA'", "'food'", "0.0075"], + ["'WA'", "", "0.015"], + ["'WV'", "'food'", "0.01375"], + ["'WV'", "", "0.0275"], + ["'WI'", "'food'", "0"], + ["'WI'", "", "0.03"], + ["'WY'", "'food'", "0.02125"], + ["'WY'", "", "0.0425"], + ["", "", "null"], + ]}, + {expression: "calc", passThrough: true, fields: {tax: "rate * $nodes.input.amount"}}, + ], + }, + cases: [ + [{state: "CA", category: "food", amount: 100}, {rate: 0.0200, tax: 2.0000}], + [{state: "CA", category: "general", amount: 100}, {rate: 0.0400, tax: 4.0000}], + [{state: "NY", category: "food", amount: 80}, {rate: 0.02375, tax: 1.90000}], + [{state: "TX", amount: 250}, {rate: 0.0650, tax: 16.2500}], + [{state: "WY", category: "food", amount: 10}, {rate: 0.02125, tax: 0.21250}], + [{state: "WY", category: "general", amount: 10}, {rate: 0.0425, tax: 0.4250}], + [{state: "AL", category: "food", amount: 1}, {rate: 0, tax: 0}], + [{state: "ZZ", category: "food", amount: 100}, "!error"], + ], +} + +{ + name: "realistic: a 101-rule shipping zone table keyed by a zip prefix field expression", + graph: { + nodes: [ + {table: "t", inputs: ["zip[0:1]"], outputs: ["zone"], rules: [ + ["'00'", "1"], + ["'01'", "1"], + ["'02'", "1"], + ["'03'", "1"], + ["'04'", "1"], + ["'05'", "1"], + ["'06'", "1"], + ["'07'", "1"], + ["'08'", "1"], + ["'09'", "1"], + ["'10'", "1"], + ["'11'", "1"], + ["'12'", "1"], + ["'13'", "1"], + ["'14'", "1"], + ["'15'", "1"], + ["'16'", "1"], + ["'17'", "1"], + ["'18'", "1"], + ["'19'", "1"], + ["'20'", "2"], + ["'21'", "2"], + ["'22'", "2"], + ["'23'", "2"], + ["'24'", "2"], + ["'25'", "2"], + ["'26'", "2"], + ["'27'", "2"], + ["'28'", "2"], + ["'29'", "2"], + ["'30'", "2"], + ["'31'", "2"], + ["'32'", "2"], + ["'33'", "2"], + ["'34'", "2"], + ["'35'", "2"], + ["'36'", "2"], + ["'37'", "2"], + ["'38'", "2"], + ["'39'", "2"], + ["'40'", "3"], + ["'41'", "3"], + ["'42'", "3"], + ["'43'", "3"], + ["'44'", "3"], + ["'45'", "3"], + ["'46'", "3"], + ["'47'", "3"], + ["'48'", "3"], + ["'49'", "3"], + ["'50'", "3"], + ["'51'", "3"], + ["'52'", "3"], + ["'53'", "3"], + ["'54'", "3"], + ["'55'", "3"], + ["'56'", "3"], + ["'57'", "3"], + ["'58'", "3"], + ["'59'", "3"], + ["'60'", "4"], + ["'61'", "4"], + ["'62'", "4"], + ["'63'", "4"], + ["'64'", "4"], + ["'65'", "4"], + ["'66'", "4"], + ["'67'", "4"], + ["'68'", "4"], + ["'69'", "4"], + ["'70'", "4"], + ["'71'", "4"], + ["'72'", "4"], + ["'73'", "4"], + ["'74'", "4"], + ["'75'", "4"], + ["'76'", "4"], + ["'77'", "4"], + ["'78'", "4"], + ["'79'", "4"], + ["'80'", "5"], + ["'81'", "5"], + ["'82'", "5"], + ["'83'", "5"], + ["'84'", "5"], + ["'85'", "5"], + ["'86'", "5"], + ["'87'", "5"], + ["'88'", "5"], + ["'89'", "5"], + ["'90'", "5"], + ["'91'", "5"], + ["'92'", "5"], + ["'93'", "5"], + ["'94'", "5"], + ["'95'", "5"], + ["'96'", "5"], + ["'97'", "5"], + ["'98'", "5"], + ["'99'", "5"], + ["", "9"], + ]}, + ], + }, + cases: [ + [{zip: "00501"}, {zone: 1}], + [{zip: "19103"}, {zone: 1}], + [{zip: "20001"}, {zone: 2}], + [{zip: "60601"}, {zone: 4}], + [{zip: "99501"}, {zone: 5}], + [{zip: "9"}, {zone: 9}], + [{zip: 12345}, {zone: 9}], + [{}, {zone: 9}], + ], +} + +{ + name: "realistic: a 41-rule catalogue table in loop mode over line items", + graph: { + nodes: [ + {table: "t", inputField: "items", executionMode: "loop", outputPath: "priced", inputs: ["sku"], outputs: ["price", "cat"], rules: [ + ["'SKU-000'", "10", "'cat-a'"], + ["'SKU-001'", "11", "'cat-b'"], + ["'SKU-002'", "12", "'cat-c'"], + ["'SKU-003'", "13", "'cat-d'"], + ["'SKU-004'", "14", "'cat-a'"], + ["'SKU-005'", "15", "'cat-b'"], + ["'SKU-006'", "16", "'cat-c'"], + ["'SKU-007'", "17", "'cat-d'"], + ["'SKU-008'", "18", "'cat-a'"], + ["'SKU-009'", "19", "'cat-b'"], + ["'SKU-010'", "20", "'cat-c'"], + ["'SKU-011'", "21", "'cat-d'"], + ["'SKU-012'", "22", "'cat-a'"], + ["'SKU-013'", "23", "'cat-b'"], + ["'SKU-014'", "24", "'cat-c'"], + ["'SKU-015'", "25", "'cat-d'"], + ["'SKU-016'", "26", "'cat-a'"], + ["'SKU-017'", "27", "'cat-b'"], + ["'SKU-018'", "28", "'cat-c'"], + ["'SKU-019'", "29", "'cat-d'"], + ["'SKU-020'", "30", "'cat-a'"], + ["'SKU-021'", "31", "'cat-b'"], + ["'SKU-022'", "32", "'cat-c'"], + ["'SKU-023'", "33", "'cat-d'"], + ["'SKU-024'", "34", "'cat-a'"], + ["'SKU-025'", "35", "'cat-b'"], + ["'SKU-026'", "36", "'cat-c'"], + ["'SKU-027'", "37", "'cat-d'"], + ["'SKU-028'", "38", "'cat-a'"], + ["'SKU-029'", "39", "'cat-b'"], + ["'SKU-030'", "40", "'cat-c'"], + ["'SKU-031'", "41", "'cat-d'"], + ["'SKU-032'", "42", "'cat-a'"], + ["'SKU-033'", "43", "'cat-b'"], + ["'SKU-034'", "44", "'cat-c'"], + ["'SKU-035'", "45", "'cat-d'"], + ["'SKU-036'", "46", "'cat-a'"], + ["'SKU-037'", "47", "'cat-b'"], + ["'SKU-038'", "48", "'cat-c'"], + ["'SKU-039'", "49", "'cat-d'"], + ["", "0", "'unknown'"], + ]}, + {expression: "sum", fields: {total: "sum(map(priced, #.price))", cats: "map(priced, #.cat)"}}, + ], + }, + cases: [ + [{items: [{sku: "SKU-000"}, {sku: "SKU-013"}, {sku: "SKU-039"}, {sku: "SKU-999"}, {}]}, {total: 82, cats: ["cat-a", "cat-b", "cat-d", "unknown", "unknown"]}], + [{items: [{sku: "SKU-000"}, {sku: "SKU-013"}]}, {total: 33, cats: ["cat-a", "cat-b"]}], + [{items: []}, {total: 0, cats: []}], + ], +} diff --git a/core/engine/tests/spec/graph/30-table-combinatorics.json5 b/core/engine/tests/spec/graph/30-table-combinatorics.json5 new file mode 100644 index 00000000..91686645 --- /dev/null +++ b/core/engine/tests/spec/graph/30-table-combinatorics.json5 @@ -0,0 +1,647 @@ +// Decision tables, multi-column combinatorics. +// +// A rule matches only when every one of its input cells passes for the same input. These +// suites pin down conjunction across columns (values that each appear in some rule but never +// together), where wildcards sit and how that interacts with rule order, cells that read +// several input fields at once, and output cells computed from several inputs. Small tables +// (under eight rules) are evaluated row by row; the larger variants also exercise the +// per-column equality index intersecting its columns. + +// --- Columns that match individually but not together -------------------------------------- +// Every value of the input appears in some rule, but no single rule accepts the combination. + +{ + name: "combinations: two columns, a cross pairing matches no rule", + graph: { + nodes: [ + {table: "t", inputs: ["p", "q"], outputs: ["r"], rules: [ + ["'A'", "'x'", "'Ax'"], + ["'B'", "'y'", "'By'"], + ["'C'", "'z'", "'Cz'"], + ]}, + ], + }, + cases: [ + [{p: "A", q: "x"}, {r: "Ax"}], + [{p: "B", q: "y"}, {r: "By"}], + [{p: "A", q: "y"}, {}], + [{p: "B", q: "x"}, {}], + [{p: "C", q: "x"}, {}], + [{p: "A"}, {}], + [{q: "x"}, {}], + ], +} + +{ + name: "combinations: the same cross pairing in a collect table", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["p", "q"], outputs: ["r"], rules: [ + ["'A'", "'x'", "'Ax'"], + ["'B'", "'y'", "'By'"], + ["'C'", "'z'", "'Cz'"], + ]}, + ], + }, + cases: [ + [{p: "A", q: "x"}, [{r: "Ax"}]], + [{p: "A", q: "y"}, []], + [{p: "C", q: "z"}, [{r: "Cz"}]], + [{p: "C", q: null}, []], + ], +} + +{ + name: "combinations: a 3x3 grid with three holes, large enough to be indexed", + graph: { + nodes: [ + {table: "t", inputs: ["p", "q"], outputs: ["r"], rules: [ + ["'A'", "'x'", "'Ax'"], + ["'A'", "'z'", "'Az'"], + ["'B'", "'x'", "'Bx'"], + ["'B'", "'y'", "'By'"], + ["'C'", "'y'", "'Cy'"], + ["'C'", "'z'", "'Cz'"], + ]}, + ], + }, + cases: [ + [{p: "A", q: "x"}, {r: "Ax"}], + [{p: "A", q: "y"}, {}], + [{p: "A", q: "z"}, {r: "Az"}], + [{p: "B", q: "x"}, {r: "Bx"}], + [{p: "B", q: "y"}, {r: "By"}], + [{p: "B", q: "z"}, {}], + [{p: "C", q: "x"}, {}], + [{p: "C", q: "y"}, {r: "Cy"}], + [{p: "C", q: "z"}, {r: "Cz"}], + [{p: "A", q: "w"}, {}], + [{p: "D", q: "x"}, {}], + ], +} + +{ + name: "combinations: three boolean columns, each rule needs one false", + graph: { + nodes: [ + {table: "t", inputs: ["a", "b", "c"], outputs: ["r"], rules: [ + ["true", "true", "false", "'ab'"], + ["false", "true", "true", "'bc'"], + ["true", "false", "true", "'ac'"], + ]}, + ], + }, + cases: [ + [{a: true, b: true, c: false}, {r: "ab"}], + [{a: false, b: true, c: true}, {r: "bc"}], + [{a: true, b: false, c: true}, {r: "ac"}], + [{a: true, b: true, c: true}, {}], + [{a: false, b: false, c: false}, {}], + [{a: true, b: true}, {}], + ], +} + +{ + name: "combinations: an indexed column matches but a range column vetoes", + graph: { + nodes: [ + {table: "t", inputs: ["code", "amount"], outputs: ["r"], rules: [ + ["'c0'", "[0..9]", "'c0'"], + ["'c1'", "[10..19]", "'c1'"], + ["'c2'", "[20..29]", "'c2'"], + ["'c3'", "[30..39]", "'c3'"], + ["'c4'", "[40..49]", "'c4'"], + ["'c5'", "[50..59]", "'c5'"], + ["'c6'", "[60..69]", "'c6'"], + ["'c7'", "[70..79]", "'c7'"], + ["'c8'", "[80..89]", "'c8'"], + ["'c9'", "[90..99]", "'c9'"], + ["", "> 1000", "'big'"], + ]}, + ], + }, + cases: [ + [{code: "c3", amount: 35}, {r: "c3"}], + [{code: "c3", amount: 45}, {}], + [{code: "c4", amount: 45}, {r: "c4"}], + [{code: "c0", amount: 0}, {r: "c0"}], + [{code: "c9", amount: 99}, {r: "c9"}], + [{code: "c9", amount: 2000}, {r: "big"}], + [{code: "c9"}, {}], + [{amount: 35}, {}], + ], +} + +{ + name: "combinations: two indexed columns of different types intersect", + graph: { + nodes: [ + {table: "t", inputs: ["n", "s"], outputs: ["r"], rules: [ + ["0", "'a'", "'0a'"], + ["0", "'b'", "'0b'"], + ["1", "'a'", "'1a'"], + ["1", "'b'", "'1b'"], + ["2", "'a'", "'2a'"], + ["2", "'b'", "'2b'"], + ["0", "", "'0*'"], + ["", "'a'", "'*a'"], + ["", "", "'**'"], + ]}, + ], + }, + cases: [ + [{n: 0, s: "a"}, {r: "0a"}], + [{n: 2, s: "b"}, {r: "2b"}], + [{n: 0, s: "c"}, {r: "0*"}], + [{n: 3, s: "a"}, {r: "*a"}], + [{n: 3, s: "b"}, {r: "**"}], + [{n: "0", s: "a"}, {r: "*a"}], + [{n: 1, s: 1}, {r: "**"}], + ], +} + +// --- Wildcard placement -------------------------------------------------------------------- +// Wildcards in different positions combined with rule order: first hit picks the first rule in +// order, not the most specific one, so tables list specific rules first by convention. + +{ + name: "wildcards: all eight wildcard patterns over three columns, most specific first", + graph: { + nodes: [ + {table: "t", inputs: ["a", "b", "c"], outputs: ["r"], rules: [ + ["'a'", "'b'", "'c'", "'abc'"], + ["'a'", "'b'", "", "'ab*'"], + ["'a'", "", "'c'", "'a*c'"], + ["", "'b'", "'c'", "'*bc'"], + ["'a'", "", "", "'a**'"], + ["", "'b'", "", "'*b*'"], + ["", "", "'c'", "'**c'"], + ["", "", "", "'***'"], + ]}, + ], + }, + cases: [ + [{a: "a", b: "b", c: "c"}, {r: "abc"}], + [{a: "a", b: "b", c: "x"}, {r: "ab*"}], + [{a: "a", b: "x", c: "c"}, {r: "a*c"}], + [{a: "x", b: "b", c: "c"}, {r: "*bc"}], + [{a: "a"}, {r: "a**"}], + [{c: "c"}, {r: "**c"}], + [{a: "x", b: "x", c: "x"}, {r: "***"}], + [{}, {r: "***"}], + ], +} + +{ + name: "wildcards: the same patterns, most general first, always hit the all-wildcard rule", + graph: { + nodes: [ + {table: "t", inputs: ["a", "b", "c"], outputs: ["r"], rules: [ + ["", "", "", "'***'"], + ["", "", "'c'", "'**c'"], + ["", "'b'", "", "'*b*'"], + ["'a'", "", "", "'a**'"], + ["", "'b'", "'c'", "'*bc'"], + ["'a'", "", "'c'", "'a*c'"], + ["'a'", "'b'", "", "'ab*'"], + ["'a'", "'b'", "'c'", "'abc'"], + ]}, + ], + }, + cases: [ + [{a: "a", b: "b", c: "c"}, {r: "***"}], + [{a: "a", b: "b", c: "x"}, {r: "***"}], + [{a: "a", b: "x", c: "c"}, {r: "***"}], + [{a: "x", b: "b", c: "c"}, {r: "***"}], + ], +} + +{ + name: "wildcards: the eight patterns in a collect table list every applicable pattern in order", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["a", "b", "c"], outputs: ["r"], rules: [ + ["'a'", "'b'", "'c'", "'abc'"], + ["'a'", "'b'", "", "'ab*'"], + ["'a'", "", "'c'", "'a*c'"], + ["", "'b'", "'c'", "'*bc'"], + ["'a'", "", "", "'a**'"], + ["", "'b'", "", "'*b*'"], + ["", "", "'c'", "'**c'"], + ["", "", "", "'***'"], + ]}, + ], + }, + cases: [ + [{a: "a", b: "b", c: "c"}, [{r: "abc"}, {r: "ab*"}, {r: "a*c"}, {r: "*bc"}, {r: "a**"}, {r: "*b*"}, {r: "**c"}, {r: "***"}]], + [{a: "a", b: "b", c: "x"}, [{r: "ab*"}, {r: "a**"}, {r: "*b*"}, {r: "***"}]], + [{a: "a", b: "x", c: "c"}, [{r: "a*c"}, {r: "a**"}, {r: "**c"}, {r: "***"}]], + [{a: "x", b: "b", c: "c"}, [{r: "*bc"}, {r: "*b*"}, {r: "**c"}, {r: "***"}]], + [{a: "a"}, [{r: "a**"}, {r: "***"}]], + [{c: "c"}, [{r: "**c"}, {r: "***"}]], + [{a: "x", b: "x", c: "x"}, [{r: "***"}]], + [{}, [{r: "***"}]], + ], +} + +{ + name: "wildcards: single-column rules placed before the full match shadow it", + graph: { + nodes: [ + {table: "t", inputs: ["a", "b", "c"], outputs: ["r"], rules: [ + ["", "'b'", "", "'*b*'"], + ["'a'", "", "", "'a**'"], + ["", "", "'c'", "'**c'"], + ["'a'", "'b'", "'c'", "'abc'"], + ]}, + ], + }, + cases: [ + [{a: "a", b: "b", c: "c"}, {r: "*b*"}], + [{a: "a", b: "x", c: "c"}, {r: "a**"}], + [{a: "x", b: "x", c: "c"}, {r: "**c"}], + [{a: "x", b: "x", c: "x"}, {}], + ], +} + +{ + name: "wildcards: a wildcard column between two constrained ones", + graph: { + nodes: [ + {table: "t", inputs: ["country", "plan", "seats"], outputs: ["price"], rules: [ + ["'US'", "", "> 100", "8"], + ["'US'", "'pro'", "", "12"], + ["", "'pro'", "> 100", "10"], + ["'US'", "", "", "15"], + ["", "", "> 100", "11"], + ["", "", "", "20"], + ]}, + ], + }, + cases: [ + [{country: "US", plan: "pro", seats: 500}, {price: 8}], + [{country: "US", plan: "pro", seats: 5}, {price: 12}], + [{country: "DE", plan: "pro", seats: 500}, {price: 10}], + [{country: "US", plan: "basic", seats: 5}, {price: 15}], + [{country: "DE", plan: "basic", seats: 500}, {price: 11}], + [{country: "DE", plan: "basic", seats: 5}, {price: 20}], + [{country: "US"}, {price: 15}], + [{seats: 101}, {price: 11}], + ], +} + +{ + name: "wildcards: per-column `[]` collects from rules matched through different wildcard patterns", + graph: { + nodes: [ + {table: "t", inputs: ["a", "b"], outputs: ["first", "via[]"], rules: [ + ["'a'", "'b'", "'ab'", "'ab'"], + ["'a'", "", "'a*'", "'a*'"], + ["", "'b'", "'*b'", "'*b'"], + ["", "", "'**'", "'**'"], + ]}, + ], + }, + cases: [ + [{a: "a", b: "b"}, {first: "ab", via: ["ab", "a*", "*b", "**"]}], + [{a: "a", b: "x"}, {first: "a*", via: ["a*", "**"]}], + [{a: "x", b: "b"}, {first: "*b", via: ["*b", "**"]}], + [{}, {first: "**", via: ["**"]}], + ], +} + +// --- Order sensitivity --------------------------------------------------------------------- +// Reordering rules changes first-hit results and collect order, never the collected set. + +{ + name: "order: overlapping rectangles over two range columns, rules A, B, C, first hit", + graph: { + nodes: [ + {table: "t", inputs: ["x", "y"], outputs: ["r"], rules: [ + ["[0..10]", "[0..10]", "'A'"], + ["[5..15]", "[5..15]", "'B'"], + ["[0..15]", "[8..9]", "'C'"], + ]}, + ], + }, + cases: [ + [{x: 1, y: 1}, {r: "A"}], + [{x: 7, y: 7}, {r: "A"}], + [{x: 12, y: 12}, {r: "B"}], + [{x: 12, y: 8}, {r: "B"}], + [{x: 7, y: 8}, {r: "A"}], + [{x: 16, y: 1}, {}], + [{x: 10, y: 5}, {r: "A"}], + ], +} + +{ + name: "order: overlapping rectangles, rules A, B, C, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x", "y"], outputs: ["r"], rules: [ + ["[0..10]", "[0..10]", "'A'"], + ["[5..15]", "[5..15]", "'B'"], + ["[0..15]", "[8..9]", "'C'"], + ]}, + ], + }, + cases: [ + [{x: 1, y: 1}, [{r: "A"}]], + [{x: 7, y: 7}, [{r: "A"}, {r: "B"}]], + [{x: 12, y: 12}, [{r: "B"}]], + [{x: 12, y: 8}, [{r: "B"}, {r: "C"}]], + [{x: 7, y: 8}, [{r: "A"}, {r: "B"}, {r: "C"}]], + [{x: 16, y: 1}, []], + [{x: 10, y: 5}, [{r: "A"}, {r: "B"}]], + ], +} + +{ + name: "order: overlapping rectangles over two range columns, rules C, B, A, first hit", + graph: { + nodes: [ + {table: "t", inputs: ["x", "y"], outputs: ["r"], rules: [ + ["[0..15]", "[8..9]", "'C'"], + ["[5..15]", "[5..15]", "'B'"], + ["[0..10]", "[0..10]", "'A'"], + ]}, + ], + }, + cases: [ + [{x: 1, y: 1}, {r: "A"}], + [{x: 7, y: 7}, {r: "B"}], + [{x: 12, y: 12}, {r: "B"}], + [{x: 12, y: 8}, {r: "C"}], + [{x: 7, y: 8}, {r: "C"}], + [{x: 16, y: 1}, {}], + [{x: 10, y: 5}, {r: "B"}], + ], +} + +{ + name: "order: overlapping rectangles, rules C, B, A, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x", "y"], outputs: ["r"], rules: [ + ["[0..15]", "[8..9]", "'C'"], + ["[5..15]", "[5..15]", "'B'"], + ["[0..10]", "[0..10]", "'A'"], + ]}, + ], + }, + cases: [ + [{x: 1, y: 1}, [{r: "A"}]], + [{x: 7, y: 7}, [{r: "B"}, {r: "A"}]], + [{x: 12, y: 12}, [{r: "B"}]], + [{x: 12, y: 8}, [{r: "C"}, {r: "B"}]], + [{x: 7, y: 8}, [{r: "C"}, {r: "B"}, {r: "A"}]], + [{x: 16, y: 1}, []], + [{x: 10, y: 5}, [{r: "B"}, {r: "A"}]], + ], +} + +{ + name: "order: an earlier rule whose cell errors for this input type is skipped, not fatal", + graph: { + nodes: [ + {table: "t", inputs: ["v", "w"], outputs: ["r"], rules: [ + ["len($) > 2", "> 0", "'long-positive'"], + ["> 2", "len($) > 2", "'big-long'"], + ["", "", "'default'"], + ]}, + ], + }, + cases: [ + [{v: "abc", w: 1}, {r: "long-positive"}], + [{v: 5, w: "xyz"}, {r: "big-long"}], + [{v: 5, w: 1}, {r: "default"}], + [{v: "abc", w: "xyz"}, {r: "default"}], + [{}, {r: "default"}], + ], +} + +// --- Cells reading several input fields ---------------------------------------------------- +// Cells may reference any input field next to `$`, so one cell can relate several fields. + +{ + name: "multi-field cells: `$` compared with sibling fields", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["age", "income"], outputs: ["r"], rules: [ + [">= minAge", "", "'old-enough'"], + ["[minAge..maxAge]", "", "'in-band'"], + ["", "> expenses * 2", "'solvent'"], + ["$ >= minAge and $ <= maxAge", "$ > expenses", "'both'"], + ["", "$ == base + bonus", "'exact'"], + ]}, + ], + }, + cases: [ + [{age: 30, minAge: 18, maxAge: 65, income: 5000, expenses: 2000, base: 4000, bonus: 1000}, [{r: "old-enough"}, {r: "in-band"}, {r: "solvent"}, {r: "both"}, {r: "exact"}]], + [{age: 70, minAge: 18, maxAge: 65, income: 3000, expenses: 2000}, [{r: "old-enough"}]], + [{age: 18, minAge: 18, maxAge: 18, income: 100, expenses: 100, base: 50, bonus: 50}, [{r: "old-enough"}, {r: "in-band"}, {r: "exact"}]], + [{age: 30, income: 5000}, []], + ], +} + +{ + name: "multi-field cells: a field-less column relating several fields", + graph: { + nodes: [ + {table: "t", inputs: [null, "kind"], outputs: ["r"], rules: [ + ["a > b and b > c", "'x'", "'desc-x'"], + ["a > b and b > c", "", "'desc'"], + ["a == b and b == c", "", "'flat'"], + ["a < b and b < c", "", "'asc'"], + ["", "", "'mixed'"], + ]}, + ], + }, + cases: [ + [{a: 3, b: 2, c: 1, kind: "x"}, {r: "desc-x"}], + [{a: 3, b: 2, c: 1, kind: "y"}, {r: "desc"}], + [{a: 1, b: 1, c: 1}, {r: "flat"}], + [{a: 1, b: 2, c: 3}, {r: "asc"}], + [{a: 1, b: 3, c: 2}, {r: "mixed"}], + [{a: 1, b: 2}, {r: "mixed"}], + [{a: "a", b: "b", c: "c"}, {r: "mixed"}], + ], +} + +{ + name: "multi-field cells: a cell compares its column with another column's field", + graph: { + nodes: [ + {table: "t", inputs: ["from", "to"], outputs: ["r"], rules: [ + ["", "== from", "'same'"], + ["< to", "", "'forward'"], + ["> to", "", "'backward'"], + ["", "", "'unknown'"], + ]}, + ], + }, + cases: [ + [{from: 1, to: 1}, {r: "same"}], + [{from: 1, to: 2}, {r: "forward"}], + [{from: 3, to: 2}, {r: "backward"}], + [{from: "a", to: "a"}, {r: "same"}], + [{from: 1}, {r: "unknown"}], + [{from: null, to: null}, {r: "same"}], + [{}, {r: "same"}], + ], +} + +{ + name: "multi-field cells: cells reading nested objects and arrays of the input", + graph: { + nodes: [ + {table: "t", inputs: ["role", "amount"], outputs: ["r"], rules: [ + ["in policy.admins", "", "'admin'"], + ["", "<= max(policy.limits)", "'within'"], + ["", "", "'denied'"], + ]}, + ], + }, + cases: [ + [{role: "root", amount: 1000000.0, policy: {admins: ["root", "ops"], limits: [10, 50]}}, {r: "admin"}], + [{role: "user", amount: 50, policy: {admins: ["root"], limits: [10, 50]}}, {r: "within"}], + [{role: "user", amount: 51, policy: {admins: ["root"], limits: [10, 50]}}, {r: "denied"}], + [{role: "user", amount: 5, policy: {admins: [], limits: []}}, {r: "denied"}], + [{role: "user", amount: 5}, {r: "denied"}], + ], +} + +{ + name: "multi-field cells: input fields that combine several inputs", + graph: { + nodes: [ + {table: "t", inputs: ["qty * price", "country + '-' + plan", "[a, b]"], outputs: ["r"], rules: [ + ["> 1000", "'US-pro'", "", "'big-us-pro'"], + ["> 1000", "", "", "'big'"], + ["", "'DE-basic', 'DE-pro'", "", "'de'"], + ["", "", "contains($, 7)", "'has-seven'"], + ["", "", "len($) == 2", "'other'"], + ]}, + ], + }, + cases: [ + [{qty: 10, price: 200, country: "US", plan: "pro"}, {r: "big-us-pro"}], + [{qty: 10, price: 200, country: "US", plan: "basic"}, {r: "big"}], + [{qty: 1, price: 2, country: "DE", plan: "pro"}, {r: "de"}], + [{qty: 1, price: 2, country: "FR", plan: "pro", a: 7}, {r: "has-seven"}], + [{qty: 1, price: 2, country: "FR", plan: "pro", b: 7}, {r: "has-seven"}], + [{qty: 1, price: 2, country: "FR", plan: "pro"}, {r: "other"}], + ], +} + +// --- Outputs computed from several inputs -------------------------------------------------- +// Output cells are full expressions over the node input, so one output can combine many fields. + +{ + name: "multi-input outputs: arithmetic, templates, objects and arrays", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["total", "label", "pair", "box", "biggest"], rules: [ + ["'sum'", "a + b + c", "`${first} ${last}`", "[a, b]", "{x: a, y: b}", "max([a, b, c])"], + ["'mul'", "a * b * c", "first + '/' + last", "[b, a]", "{x: b}", "a > b ? a : b"], + ]}, + ], + }, + cases: [ + [{kind: "sum", a: 1, b: 2, c: 3, first: "Ann", last: "Lee"}, {total: 6, label: "Ann Lee", pair: [1, 2], box: {x: 1, y: 2}, biggest: 3}], + [{kind: "mul", a: 2, b: 5, c: 0.5, first: "x", last: "y"}, {total: 5, label: "x/y", pair: [5, 2], box: {x: 5}, biggest: 5}], + [{kind: "sum", a: 0.1, b: 0.2, c: 0, first: "A", last: "B"}, {total: 0.3, label: "A B", pair: [0.1, 0.2], box: {x: 0.1, y: 0.2}, biggest: 0.2}], + [{kind: "other", a: 1}, {}], + ], +} + +{ + name: "multi-input outputs: an output that fails for one combination skips that rule", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["ratio"], rules: [ + ["'div'", "round(a / b, 2)"], + ["", "'n/a'"], + ]}, + ], + }, + cases: [ + [{kind: "div", a: 1, b: 4}, {ratio: 0.25}], + [{kind: "div", a: 2, b: 3}, {ratio: 0.67}], + [{kind: "div", a: "x", b: 3}, {ratio: "n/a"}], + [{kind: "other", a: 1, b: 4}, {ratio: "n/a"}], + ], +} + +{ + name: "multi-input outputs: collect rows each compute from several inputs", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["amount"], outputs: ["fee", "note"], rules: [ + ["> 0", "amount * rate", "'percent'"], + ["> threshold", "flat", "`over ${threshold}`"], + ["", "amount * rate + flat", "'combined'"], + ]}, + ], + }, + cases: [ + [{amount: 200, rate: 0.01, flat: 5, threshold: 100}, [{fee: 2, note: "percent"}, {fee: 5, note: "over 100"}, {fee: 7, note: "combined"}]], + [{amount: 50, rate: 0.02, flat: 1, threshold: 100}, [{fee: 1, note: "percent"}, {fee: 2, note: "combined"}]], + [{amount: 0, rate: 0.02, flat: 1, threshold: 100}, [{fee: 1, note: "combined"}]], + ], +} + +{ + name: "multi-input outputs: outputs mixing the input with an upstream node through $nodes", + graph: { + nodes: [ + {expression: "prep", passThrough: true, fields: {base: "price * qty"}}, + {table: "t", inputs: ["tier"], outputs: ["due", "saved"], rules: [ + ["'gold'", "base * 0.8", "base - base * 0.8"], + ["", "base", "$nodes.prep.base - base"], + ]}, + ], + }, + cases: [ + [{tier: "gold", price: 10, qty: 3}, {due: 24, saved: 6}], + [{tier: "basic", price: 10, qty: 3}, {due: 30, saved: 0}], + [{tier: "gold", price: 2.5, qty: 4}, {due: 8, saved: 2}], + ], +} + +// --- Realistic combinations ---------------------------------------------------------------- + +{ + name: "realistic: a 13-rule premium table over age band, region and smoker status", + graph: { + nodes: [ + {table: "t", inputs: ["age", "region", "smoker"], outputs: ["premium", "rated"], rules: [ + ["< 25", "'urban'", "true", "base * 1.6 * 1.2 * 1.5", "'young/urban/true'"], + ["< 25", "'urban'", "false", "base * 1.6 * 1.2 * 1", "'young/urban/false'"], + ["< 25", "'rural'", "true", "base * 1.6 * 0.9 * 1.5", "'young/rural/true'"], + ["< 25", "'rural'", "false", "base * 1.6 * 0.9 * 1", "'young/rural/false'"], + ["[25..60)", "'urban'", "true", "base * 1 * 1.2 * 1.5", "'adult/urban/true'"], + ["[25..60)", "'urban'", "false", "base * 1 * 1.2 * 1", "'adult/urban/false'"], + ["[25..60)", "'rural'", "true", "base * 1 * 0.9 * 1.5", "'adult/rural/true'"], + ["[25..60)", "'rural'", "false", "base * 1 * 0.9 * 1", "'adult/rural/false'"], + [">= 60", "'urban'", "true", "base * 1.3 * 1.2 * 1.5", "'senior/urban/true'"], + [">= 60", "'urban'", "false", "base * 1.3 * 1.2 * 1", "'senior/urban/false'"], + [">= 60", "'rural'", "true", "base * 1.3 * 0.9 * 1.5", "'senior/rural/true'"], + [">= 60", "'rural'", "false", "base * 1.3 * 0.9 * 1", "'senior/rural/false'"], + ["", "", "", "null", "'unrated'"], + ]}, + ], + }, + cases: [ + [{age: 20, region: "urban", smoker: true, base: 100}, {premium: 288.000, rated: "young/urban/true"}], + [{age: 30, region: "rural", smoker: false, base: 100}, {premium: 90.0, rated: "adult/rural/false"}], + [{age: 60, region: "urban", smoker: false, base: 100}, {premium: 156.00, rated: "senior/urban/false"}], + [{age: 59, region: "rural", smoker: true, base: 100}, {premium: 135.00, rated: "adult/rural/true"}], + [{age: 24, region: "rural", smoker: false, base: 100}, {premium: 144.00, rated: "young/rural/false"}], + [{age: 30, region: "suburb", smoker: false, base: 100}, {rated: "unrated"}], + [{age: 30, region: "urban", smoker: "no", base: 100}, {rated: "unrated"}], + [{region: "urban", smoker: true, base: 100}, {rated: "unrated"}], + [{age: 30, region: "urban", smoker: true}, {rated: "unrated"}], + ], +} diff --git a/core/engine/tests/spec/graph/31-table-null-and-missing.json5 b/core/engine/tests/spec/graph/31-table-null-and-missing.json5 new file mode 100644 index 00000000..96e7ae3e --- /dev/null +++ b/core/engine/tests/spec/graph/31-table-null-and-missing.json5 @@ -0,0 +1,574 @@ +// Decision tables, null, missing and falsy inputs. +// +// Each suite runs the same cells against a missing field, null, the empty string, 0 and false +// (plus "a", 1 and true as controls). Intended semantics: a missing field reads as null; +// equality never coerces between types, so 0, false, "" and null are four different values; +// comparisons and ranges only match numbers; `!=` and `not in` match every value that is not +// equal, including null; an empty cell matches everything. The matrix is repeated for first +// hit and collect, with and without passThrough, small (row by row) and large (indexed). + +// --- Equality cells ------------------------------------------------------------------------ +// Literal equality: each falsy value matches only its own literal; `null` matches null and missing. + +{ + name: "falsy: literal equality cells, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["'a'", "'str-a'"], + ["''", "'str-empty'"], + ["0", "'num-zero'"], + ["false", "'bool-false'"], + ["null", "'null'"], + ["'0'", "'str-zero'"], + ["'false'", "'str-false'"], + ]}, + ], + }, + cases: [ + [{}, [{r: "null"}]], + [{v: null}, [{r: "null"}]], + [{v: ""}, [{r: "str-empty"}]], + [{v: 0}, [{r: "num-zero"}]], + [{v: false}, [{r: "bool-false"}]], + [{v: "a"}, [{r: "str-a"}]], + [{v: 1}, []], + [{v: true}, []], + ], +} + +{ + name: "falsy: literal equality cells, first hit with a trailing wildcard", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["'a'", "'str-a'"], + ["''", "'str-empty'"], + ["0", "'num-zero'"], + ["false", "'bool-false'"], + ["null", "'null'"], + ["'0'", "'str-zero'"], + ["'false'", "'str-false'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{}, {r: "null"}], + [{v: null}, {r: "null"}], + [{v: ""}, {r: "str-empty"}], + [{v: 0}, {r: "num-zero"}], + [{v: false}, {r: "bool-false"}], + [{v: "a"}, {r: "str-a"}], + [{v: 1}, {r: "any"}], + [{v: true}, {r: "any"}], + ], +} + +// --- Negated cells ------------------------------------------------------------------------- +// `!=` and `not in` are plain negations: they match null and missing too. + +{ + name: "falsy: negated equality and `not in` cells, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["!= 'a'", "'ne-a'"], + ["!= ''", "'ne-empty'"], + ["!= 0", "'ne-zero'"], + ["!= false", "'ne-false'"], + ["!= null", "'ne-null'"], + ["not in ['a', '']", "'not-in-strings'"], + ["not in [0, false]", "'not-in-falsy'"], + ]}, + ], + }, + cases: [ + [{}, [{r: "ne-a"}, {r: "ne-empty"}, {r: "ne-zero"}, {r: "ne-false"}, {r: "not-in-strings"}, {r: "not-in-falsy"}]], + [{v: null}, [{r: "ne-a"}, {r: "ne-empty"}, {r: "ne-zero"}, {r: "ne-false"}, {r: "not-in-strings"}, {r: "not-in-falsy"}]], + [{v: ""}, [{r: "ne-a"}, {r: "ne-zero"}, {r: "ne-false"}, {r: "ne-null"}, {r: "not-in-falsy"}]], + [{v: 0}, [{r: "ne-a"}, {r: "ne-empty"}, {r: "ne-false"}, {r: "ne-null"}, {r: "not-in-strings"}]], + [{v: false}, [{r: "ne-a"}, {r: "ne-empty"}, {r: "ne-zero"}, {r: "ne-null"}, {r: "not-in-strings"}]], + [{v: "a"}, [{r: "ne-empty"}, {r: "ne-zero"}, {r: "ne-false"}, {r: "ne-null"}, {r: "not-in-falsy"}]], + [{v: 1}, [{r: "ne-a"}, {r: "ne-empty"}, {r: "ne-zero"}, {r: "ne-false"}, {r: "ne-null"}, {r: "not-in-strings"}, {r: "not-in-falsy"}]], + [{v: true}, [{r: "ne-a"}, {r: "ne-empty"}, {r: "ne-zero"}, {r: "ne-false"}, {r: "ne-null"}, {r: "not-in-strings"}, {r: "not-in-falsy"}]], + ], +} + +// --- Comparison and range cells ------------------------------------------------------------ +// Only numbers order: null, missing, strings and booleans never satisfy a comparison or range. + +{ + name: "falsy: comparison and interval cells, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["> 0", "'gt0'"], + [">= 0", "'ge0'"], + ["< 1", "'lt1'"], + ["<= 0", "'le0'"], + ["[0..10]", "'closed'"], + ["(0..10]", "'open-left'"], + ["[-1..0]", "'ends-at-zero'"], + ]}, + ], + }, + cases: [ + [{}, []], + [{v: null}, []], + [{v: ""}, []], + [{v: 0}, [{r: "ge0"}, {r: "lt1"}, {r: "le0"}, {r: "closed"}, {r: "ends-at-zero"}]], + [{v: false}, []], + [{v: "a"}, []], + [{v: 1}, [{r: "gt0"}, {r: "ge0"}, {r: "closed"}, {r: "open-left"}]], + [{v: true}, []], + ], +} + +{ + name: "falsy: a comparison cell before a wildcard, first hit", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["< 1", "'below-one'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{}, {r: "other"}], + [{v: null}, {r: "other"}], + [{v: ""}, {r: "other"}], + [{v: 0}, {r: "below-one"}], + [{v: false}, {r: "other"}], + [{v: "a"}, {r: "other"}], + [{v: 1}, {r: "other"}], + [{v: true}, {r: "other"}], + ], +} + +// --- List cells ---------------------------------------------------------------------------- +// Comma lists and `in` arrays are disjunctions of equalities, so they can name falsy values and null. + +{ + name: "falsy: comma lists and `in` arrays naming falsy values, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["'a', ''", "'strs'"], + ["0, 1", "'nums'"], + ["true, false", "'bools'"], + ["'', null", "'empty-or-null'"], + ["in [0, false, '', null]", "'any-falsy'"], + ["in []", "'empty-array'"], + ["in ['', 0]", "'empty-or-zero'"], + ]}, + ], + }, + cases: [ + [{}, [{r: "empty-or-null"}, {r: "any-falsy"}]], + [{v: null}, [{r: "empty-or-null"}, {r: "any-falsy"}]], + [{v: ""}, [{r: "strs"}, {r: "empty-or-null"}, {r: "any-falsy"}, {r: "empty-or-zero"}]], + [{v: 0}, [{r: "nums"}, {r: "any-falsy"}, {r: "empty-or-zero"}]], + [{v: false}, [{r: "bools"}, {r: "any-falsy"}]], + [{v: "a"}, [{r: "strs"}]], + [{v: 1}, [{r: "nums"}]], + [{v: true}, [{r: "bools"}]], + ], +} + +// --- Expression cells ---------------------------------------------------------------------- +// Cells written as expressions over `$`; a cell that errors for a type does not match. + +{ + name: "falsy: expression cells over `$`, collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["$ == null", "'is-null'"], + ["($ ?? 'd') == 'd'", "'coalesced'"], + ["len($ ?? '') == 0", "'len-zero'"], + ["$ == false or $ == null", "'false-or-null'"], + ["type($) == 'null'", "'type-null'"], + ["isNumeric($)", "'numeric'"], + ["$ ? true : false", "'truthy'"], + ]}, + ], + }, + cases: [ + [{}, [{r: "is-null"}, {r: "coalesced"}, {r: "len-zero"}, {r: "false-or-null"}, {r: "type-null"}]], + [{v: null}, [{r: "is-null"}, {r: "coalesced"}, {r: "len-zero"}, {r: "false-or-null"}, {r: "type-null"}]], + [{v: ""}, [{r: "len-zero"}]], + [{v: 0}, [{r: "numeric"}]], + [{v: false}, [{r: "false-or-null"}, {r: "truthy"}], "question: `$ ? true : false` is not a boolean test in a cell; unary mode compares `$` with the ternary's value, so false matches because `false == (false ? true : false)`, while a reader expects a truthiness test"], + [{v: "a"}, []], + [{v: 1}, [{r: "numeric"}]], + [{v: true}, [{r: "truthy"}]], + ], +} + +{ + name: "falsy: field-less cells reading the field by name", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: [null], outputs: ["r"], rules: [ + ["v == null", "'is-null'"], + ["v == ''", "'is-empty'"], + ["v == 0", "'is-zero'"], + ["v == false", "'is-false'"], + ["v", "'bare'"], + ["not v", "'negated'"], + ]}, + ], + }, + cases: [ + [{}, [{r: "is-null"}]], + [{v: null}, [{r: "is-null"}]], + [{v: ""}, [{r: "is-empty"}]], + [{v: 0}, [{r: "is-zero"}]], + [{v: false}, [{r: "is-false"}, {r: "negated"}]], + [{v: "a"}, []], + [{v: 1}, []], + [{v: true}, [{r: "bare"}]], + ], +} + +// --- Empty cells --------------------------------------------------------------------------- +// An empty cell is a wildcard: it matches every value, including missing. + +{ + name: "falsy: empty cells in every column match any combination of falsy values", + graph: { + nodes: [ + {table: "t", inputs: ["v", "w", "x"], outputs: ["r"], rules: [ + ["", "", "", "'wild'"], + ]}, + ], + }, + cases: [ + [{}, {r: "wild"}], + [{v: null, w: "", x: 0}, {r: "wild"}], + [{v: false, w: null}, {r: "wild"}], + [{v: "a", w: 1, x: true}, {r: "wild"}], + ], +} + +{ + name: "falsy: a constrained column next to empty ones decides alone", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v", "w"], outputs: ["r"], rules: [ + ["null", "", "'v-null'"], + ["", "null", "'w-null'"], + ["''", "0", "'empty-zero'"], + ["false", "", "'v-false'"], + ]}, + ], + }, + cases: [ + [{}, [{r: "v-null"}, {r: "w-null"}]], + [{v: null, w: 0}, [{r: "v-null"}]], + [{v: "", w: 0}, [{r: "empty-zero"}]], + [{v: "", w: false}, []], + [{v: false}, [{r: "w-null"}, {r: "v-false"}]], + [{v: 0, w: ""}, []], + ], +} + +// --- Large (indexed) tables with falsy keys ------------------------------------------------ +// The same distinctions with eight or more rules, where literal cells go through the equality +// index: 0, false, "", "0", "false", null and "null" must stay apart. + +{ + name: "falsy: an indexed collect table keyed by every falsy literal", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["''", "'str-empty'"], + ["0", "'num-zero'"], + ["false", "'bool-false'"], + ["'0'", "'str-zero'"], + ["'false'", "'str-false'"], + ["null", "'null'"], + ["'null'", "'str-null'"], + ["0.0", "'num-zero-decimal'"], + ["'a'", "'str-a'"], + ["1", "'num-one'"], + ["true", "'bool-true'"], + ]}, + ], + }, + cases: [ + [{}, [{r: "null"}]], + [{v: null}, [{r: "null"}]], + [{v: ""}, [{r: "str-empty"}]], + [{v: 0}, [{r: "num-zero"}, {r: "num-zero-decimal"}]], + [{v: false}, [{r: "bool-false"}]], + [{v: "a"}, [{r: "str-a"}]], + [{v: 1}, [{r: "num-one"}]], + [{v: true}, [{r: "bool-true"}]], + ], +} + +{ + name: "falsy: the indexed table under first hit with a trailing wildcard", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["''", "'str-empty'"], + ["0", "'num-zero'"], + ["false", "'bool-false'"], + ["'0'", "'str-zero'"], + ["'false'", "'str-false'"], + ["null", "'null'"], + ["'null'", "'str-null'"], + ["0.0", "'num-zero-decimal'"], + ["'a'", "'str-a'"], + ["1", "'num-one'"], + ["true", "'bool-true'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{}, {r: "null"}], + [{v: null}, {r: "null"}], + [{v: ""}, {r: "str-empty"}], + [{v: 0}, {r: "num-zero"}], + [{v: false}, {r: "bool-false"}], + [{v: "a"}, {r: "str-a"}], + [{v: 1}, {r: "num-one"}], + [{v: true}, {r: "bool-true"}], + [{v: "0"}, {r: "str-zero"}], + [{v: "false"}, {r: "str-false"}], + [{v: "null"}, {r: "str-null"}], + [{v: 0.00}, {r: "num-zero"}], + [{v: []}, {r: "any"}], + [{v: {}}, {r: "any"}], + ], +} + +{ + name: "falsy: an indexed table with two falsy-keyed columns intersects them", + graph: { + nodes: [ + {table: "t", inputs: ["v", "w"], outputs: ["r"], rules: [ + ["''", "0", "'e0'"], + ["''", "false", "'ef'"], + ["0", "''", "'0e'"], + ["0", "false", "'0f'"], + ["false", "''", "'fe'"], + ["false", "0", "'f0'"], + ["null", "null", "'nn'"], + ["''", "", "'e*'"], + ["", "0", "'*0'"], + ["", "", "'**'"], + ]}, + ], + }, + cases: [ + [{v: "", w: 0}, {r: "e0"}], + [{v: "", w: false}, {r: "ef"}], + [{v: 0, w: ""}, {r: "0e"}], + [{v: false, w: 0}, {r: "f0"}], + [{}, {r: "nn"}], + [{v: null}, {r: "nn"}], + [{v: "", w: null}, {r: "e*"}], + [{v: null, w: 0}, {r: "*0"}], + [{v: 0, w: 0}, {r: "*0"}], + [{v: false, w: false}, {r: "**"}], + ], +} + +// --- passThrough with falsy inputs --------------------------------------------------------- +// passThrough merges the outputs into the input: a falsy input field survives no match, an output +// overrides it, and a null output removes it. Top-level null input fields are dropped from the +// graph result like any top-level null (see 11-pass-through). + +{ + name: "falsy: first hit with passThrough, matched and unmatched falsy inputs", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["v"], outputs: ["r"], rules: [ + ["null", "'was-null'"], + ["''", "'was-empty'"], + ["0", "'was-zero'"], + ]}, + ], + }, + cases: [ + [{}, {r: "was-null"}], + [{v: null}, {r: "was-null"}], + [{v: ""}, {v: "", r: "was-empty"}], + [{v: 0}, {v: 0, r: "was-zero"}], + [{v: false}, {v: false}], + [{v: false, r: ""}, {v: false, r: ""}], + [{v: 0, r: null}, {v: 0, r: "was-zero"}], + ], +} + +{ + name: "falsy: passThrough where the output rewrites the falsy field itself", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["v"], outputs: ["v"], rules: [ + ["null", "'filled'"], + ["''", "null"], + ["0", "false"], + ["false", "0"], + ]}, + ], + }, + cases: [ + [{}, {v: "filled"}], + [{v: null}, {v: "filled"}], + [{v: "", k: 1}, {k: 1}], + [{v: 0}, {v: false}], + [{v: false}, {v: 0}], + [{v: "a"}, {v: "a"}], + ], +} + +{ + name: "falsy: collect with passThrough and outputPath over falsy inputs", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, outputPath: "hits", inputs: ["v"], outputs: ["r"], rules: [ + ["null", "'null'"], + ["!= null", "'set'"], + ["", "v"], + ]}, + ], + }, + cases: [ + [{}, {hits: [{r: "null"}, {r: null}]}], + [{v: null}, {hits: [{r: "null"}, {r: null}]}], + [{v: ""}, {v: "", hits: [{r: "set"}, {r: ""}]}], + [{v: 0}, {v: 0, hits: [{r: "set"}, {r: 0}]}], + [{v: false}, {v: false, hits: [{r: "set"}, {r: false}]}], + ], +} + +// --- Falsy output values ------------------------------------------------------------------- +// Outputs that evaluate to "", 0 or false are written; only a top-level null is dropped. + +{ + name: "falsy: output cells echoing falsy inputs, first hit", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["out", "nested.out", "kind"], rules: [ + ["", "v", "v", "type(v)"], + ]}, + ], + }, + cases: [ + [{}, {nested: {out: null}, kind: "null"}], + [{v: null}, {nested: {out: null}, kind: "null"}], + [{v: ""}, {out: "", nested: {out: ""}, kind: "string"}], + [{v: 0}, {out: 0, nested: {out: 0}, kind: "number"}], + [{v: false}, {out: false, nested: {out: false}, kind: "bool"}], + ], +} + +{ + name: "falsy: output cells defaulting falsy inputs with `??` and `or`", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["coalesced", "ternary"], rules: [ + ["v ?? 'default'", "v == null ? 'none' : v"], + ]}, + ], + }, + cases: [ + [{}, {coalesced: "default", ternary: "none"}], + [{v: null}, {coalesced: "default", ternary: "none"}], + [{v: ""}, {coalesced: "", ternary: ""}], + [{v: 0}, {coalesced: 0, ternary: 0}], + [{v: false}, {coalesced: false, ternary: false}], + ], +} + +{ + name: "falsy: a `[]` column gathers falsy values but not skipped empty cells", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["vals[]"], rules: [ + ["", "''"], + ["", "0"], + ["", "false"], + ["", "null"], + ["", ""], + ["'x'", "'only-x'"], + ]}, + ], + }, + cases: [ + [{}, {vals: ["", 0, false, null]}], + [{k: "x"}, {vals: ["", 0, false, null, "only-x"]}], + [{k: null}, {vals: ["", 0, false, null]}], + ], +} + +// --- Nested and scoped access with falsy parents ------------------------------------------- +// A dotted field through a falsy or missing parent reads as null. + +{ + name: "falsy: dotted fields through falsy, empty and missing parents", + graph: { + nodes: [ + {table: "t", inputs: ["a.b"], outputs: ["r"], rules: [ + ["null", "'null'"], + ["", "'value'"], + ]}, + ], + }, + cases: [ + [{}, {r: "null"}], + [{a: null}, {r: "null"}], + [{a: ""}, {r: "null"}], + [{a: 0}, {r: "null"}], + [{a: false}, {r: "null"}], + [{a: []}, {r: "null"}], + [{a: {}}, {r: "null"}], + [{a: {b: 0}}, {r: "value"}], + [{a: {b: false}}, {r: "value"}], + ], +} + +{ + name: "falsy: inputField pointing at a missing, null or empty object", + graph: { + nodes: [ + {table: "t", inputField: "obj", inputs: ["v"], outputs: ["r"], rules: [ + ["null", "'v-null'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{obj: {v: 1}}, {r: "other"}], + [{obj: {v: null}}, {r: "v-null"}], + [{obj: {}}, {r: "v-null"}], + [{obj: null}, {r: "v-null"}], + [{}, {r: "v-null"}], + ], +} + +{ + name: "falsy: loop mode over items holding null, missing and falsy fields", + graph: { + nodes: [ + {table: "t", inputField: "items", executionMode: "loop", outputPath: "out", inputs: ["v"], outputs: ["r"], rules: [ + ["null", "'null'"], + ["''", "'empty'"], + ["0", "'zero'"], + ["false", "'false'"], + ]}, + ], + }, + cases: [ + [{items: [{v: null}, {}, {v: ""}, {v: 0}, {v: false}, {v: 1}]}, {out: [{r: "null"}, {r: "null"}, {r: "empty"}, {r: "zero"}, {r: "false"}, null]}], + [{items: [{v: 0}]}, {out: [{r: "zero"}]}], + [{items: []}, {out: []}], + ], +} diff --git a/core/engine/tests/spec/graph/32-expression-closures.json5 b/core/engine/tests/spec/graph/32-expression-closures.json5 new file mode 100644 index 00000000..dbb6b6dd --- /dev/null +++ b/core/engine/tests/spec/graph/32-expression-closures.json5 @@ -0,0 +1,633 @@ +// Closures inside expression nodes: map, filter, some, all, none, one, count, flatMap and the +// aggregates sum/avg/min/max over request arrays, over arrays computed by earlier fields (`$`), and +// over arrays produced by earlier nodes. Closure semantics themselves live in the expression spec; +// these suites pin how closure results move through nodes, merges, pass-through and tables. + +// --------------------------------------------------------------------------- +// map over request arrays of every element type. +{ + name: "map over request numbers", + graph: {nodes: [{expression: "calc", fields: {doubled: "map(xs, # * 2)", labels: "map(xs, `n${#}`)"}}]}, + cases: [ + [{xs: [1, 2, 3]}, {doubled: [2, 4, 6], labels: ["n1", "n2", "n3"]}], + [{xs: [0.1, -0.5]}, {doubled: [0.2, -1], labels: ["n0.1", "n-0.5"]}], + [{xs: [7]}, {doubled: [14], labels: ["n7"]}], + [{xs: []}, {doubled: [], labels: []}], + [{xs: [1.10]}, {doubled: [2.2], labels: ["n1.10"]}], + ], +} + +{ + name: "map over request strings", + graph: {nodes: [{expression: "calc", fields: {up: "map(names, upper(#))", sizes: "map(names, len(#))"}}]}, + cases: [ + [{names: ["ann", "bob"]}, {up: ["ANN", "BOB"], sizes: [3, 3]}], + [{names: [""]}, {up: [""], sizes: [0]}], + [{names: ["é"]}, {up: ["É"], sizes: [1]}, "bug: len counts UTF-8 bytes instead of characters (same as the expression spec)"], + [{names: []}, {up: [], sizes: []}], + ], +} + +{ + name: "map over request objects reading members", + graph: {nodes: [{expression: "calc", fields: {totals: "map(items, #.price * #.qty)", names: "map(items, #.name)"}}]}, + cases: [ + [{items: [{name: "a", price: 10, qty: 2}, {name: "b", price: 0.5, qty: 3}]}, {totals: [20, 1.5], names: ["a", "b"]}], + [{items: [{name: "a", price: 1, qty: 0}]}, {totals: [0], names: ["a"]}], + [{items: []}, {totals: [], names: []}], + ], +} + +{ + name: "map over objects with missing members yields nulls inside the array", + graph: {nodes: [{expression: "calc", fields: {names: "map(items, #.name)", safe: "map(items, #.name ?? '?')"}}]}, + cases: [ + [{items: [{name: "a"}, {}]}, {names: ["a", null], safe: ["a", "?"]}], + [{items: [{name: null}]}, {names: [null], safe: ["?"]}], + [{items: [{}, {}]}, {names: [null, null], safe: ["?", "?"]}], + [{items: [{name: "x"}]}, {names: ["x"], safe: ["x"]}], + ], +} + +{ + name: "map over an array holding nulls", + graph: {nodes: [{expression: "calc", fields: {kept: "map(xs, #)", filled: "map(xs, # ?? 0)", kinds: "map(xs, type(#))"}}]}, + cases: [ + [{xs: [1, null, 3]}, {kept: [1, null, 3], filled: [1, 0, 3], kinds: ["number", "null", "number"]}], + [{xs: [null]}, {kept: [null], filled: [0], kinds: ["null"]}], + [{xs: ["a", null]}, {kept: ["a", null], filled: ["a", 0], kinds: ["string", "null"]}], + ], +} + +{ + name: "map arithmetic over a null element is an error", + graph: {nodes: [{expression: "calc", fields: {out: "map(xs, # * 2)"}}]}, + cases: [ + [{xs: [1, 2]}, {out: [2, 4]}], + [{xs: [1, null]}, "!error"], + [{xs: [null]}, "!error"], + [{xs: ["a"]}, "!error"], + ], +} + +{ + name: "map over a missing or non-array input", + graph: {nodes: [{expression: "calc", fields: {out: "map(xs, #)"}}]}, + cases: [ + [{xs: [1]}, {out: [1]}], + [{}, "!error"], + [{xs: null}, "!error"], + [{xs: "abc"}, "!error"], + [{xs: {a: 1}}, "!error"], + [{xs: 5}, "!error"], + ], +} + +{ + name: "map guarded with ?? [] tolerates missing arrays", + graph: {nodes: [{expression: "calc", fields: {out: "map(xs ?? [], # + 1)", n: "len(xs ?? [])"}}]}, + cases: [ + [{xs: [1, 2]}, {out: [2, 3], n: 2}], + [{}, {out: [], n: 0}], + [{xs: null}, {out: [], n: 0}], + [{xs: []}, {out: [], n: 0}], + ], +} + +// --------------------------------------------------------------------------- +// filter: result keeps original elements, order preserved. +{ + name: "filter numbers by a request threshold", + graph: {nodes: [{expression: "calc", fields: {big: "filter(xs, # > limit)", n: "len($.big)"}}]}, + cases: [ + [{xs: [1, 5, 10], limit: 4}, {big: [5, 10], n: 2}], + [{xs: [1, 5, 10], limit: 10}, {big: [], n: 0}], + [{xs: [1, 5, 10], limit: -1}, {big: [1, 5, 10], n: 3}], + [{xs: [], limit: 0}, {big: [], n: 0}], + [{xs: [0.5, 0.25], limit: 0.3}, {big: [0.5], n: 1}], + ], +} + +{ + name: "filter objects keeps whole elements", + graph: {nodes: [{expression: "calc", fields: {active: "filter(users, #.active)"}}]}, + cases: [ + [{users: [{id: 1, active: true}, {id: 2, active: false}]}, {active: [{id: 1, active: true}]}], + [{users: [{id: 1, active: false}]}, {active: []}], + [{users: [{id: 1, active: true, tags: ["a"]}]}, {active: [{id: 1, active: true, tags: ["a"]}]}], + [{users: []}, {active: []}], + ], +} + +{ + name: "filter with a null-tolerant predicate", + graph: {nodes: [{expression: "calc", fields: {present: "filter(xs, # != null)", nulls: "count(xs, # == null)"}}]}, + cases: [ + [{xs: [1, null, 2, null]}, {present: [1, 2], nulls: 2}], + [{xs: [null]}, {present: [], nulls: 1}], + [{xs: []}, {present: [], nulls: 0}], + [{xs: ["a", false, 0]}, {present: ["a", false, 0], nulls: 0}], + ], +} + +{ + name: "filter on a missing member compares as null", + graph: {nodes: [{expression: "calc", fields: {gold: "filter(xs, #.tier == 'gold')", untiered: "filter(xs, #.tier == null)"}}]}, + cases: [ + [{xs: [{tier: "gold"}, {}, {tier: "silver"}]}, {gold: [{tier: "gold"}], untiered: [{}]}], + [{xs: [{tier: null}]}, {gold: [], untiered: [{tier: null}]}], + [{xs: [{n: 1}]}, {gold: [], untiered: [{n: 1}]}], + ], +} + +{ + name: "filter strings with string functions", + graph: {nodes: [{expression: "calc", fields: {a: "filter(words, startsWith(#, 'a'))", long: "filter(words, len(#) > 3)"}}]}, + cases: [ + [{words: ["apple", "bee", "avocado", "kiwi"]}, {a: ["apple", "avocado"], long: ["apple", "avocado", "kiwi"]}], + [{words: ["", "a"]}, {a: ["a"], long: []}], + [{words: []}, {a: [], long: []}], + ], +} + +// --------------------------------------------------------------------------- +// Quantifiers: some, all, none, one. On an empty array all and none are true, some and one false. +{ + name: "quantifiers over request numbers", + graph: {nodes: [{expression: "calc", fields: { + some: "some(xs, # > 10)", + all: "all(xs, # > 10)", + none: "none(xs, # > 10)", + one: "one(xs, # > 10)", + }}]}, + cases: [ + [{xs: [1, 20]}, {some: true, all: false, none: false, one: true}], + [{xs: [11, 20]}, {some: true, all: true, none: false, one: false}], + [{xs: [1, 2]}, {some: false, all: false, none: true, one: false}], + [{xs: [11]}, {some: true, all: true, none: false, one: true}], + [{xs: []}, {some: false, all: true, none: true, one: false}], + [{xs: [10]}, {some: false, all: false, none: true, one: false}], + ], +} + +{ + name: "quantifiers over objects", + graph: {nodes: [{expression: "calc", fields: { + anyBlocked: "some(accounts, #.status == 'blocked')", + allVerified: "all(accounts, #.verified)", + noneOverdue: "none(accounts, #.overdue > 0)", + onePrimary: "one(accounts, #.primary == true)", + }}]}, + cases: [ + [ + {accounts: [{status: "ok", verified: true, overdue: 0, primary: true}, {status: "ok", verified: true, overdue: 0, primary: false}]}, + {anyBlocked: false, allVerified: true, noneOverdue: true, onePrimary: true}, + ], + [ + {accounts: [{status: "blocked", verified: false, overdue: 5, primary: true}, {status: "ok", verified: true, overdue: 0, primary: true}]}, + {anyBlocked: true, allVerified: false, noneOverdue: false, onePrimary: false}, + ], + [{accounts: []}, {anyBlocked: false, allVerified: true, noneOverdue: true, onePrimary: false}], + [ + {accounts: [{status: "ok", verified: true, overdue: 0}]}, + {anyBlocked: false, allVerified: true, noneOverdue: true, onePrimary: false}, + ], + ], +} + +{ + name: "quantifiers over strings with membership", + graph: {nodes: [{expression: "calc", fields: { + risky: "some(countries, # in ['XX', 'YY'])", + eu: "all(countries, # in eu)", + single: "one(countries, # == home)", + }}]}, + cases: [ + [{countries: ["DE", "FR"], eu: ["DE", "FR", "IT"], home: "DE"}, {risky: false, eu: true, single: true}], + [{countries: ["DE", "XX"], eu: ["DE"], home: "DE"}, {risky: true, eu: false, single: true}], + [{countries: ["DE", "DE"], eu: ["DE"], home: "DE"}, {risky: false, eu: true, single: false}], + [{countries: [], eu: [], home: "DE"}, {risky: false, eu: true, single: false}], + ], +} + +{ + name: "a quantifier result drives a switch", + graph: { + nodes: [ + {expression: "flags", fields: {blocked: "some(items, #.blocked)"}}, + {switch: "route", when: ["blocked", ""]}, + {expression: "deny", fields: {decision: "'deny'"}}, + {expression: "allow", fields: {decision: "'allow'"}}, + ], + edges: ["input -> flags -> route", "route:0 -> deny -> output", "route:1 -> allow -> output"], + }, + cases: [ + [{items: [{blocked: false}, {blocked: true}]}, {decision: "deny"}], + [{items: [{blocked: false}]}, {decision: "allow"}], + [{items: []}, {decision: "allow"}], + ], +} + +// --------------------------------------------------------------------------- +// count and aggregates. +{ + name: "count with predicates over numbers and objects", + graph: {nodes: [{expression: "calc", fields: {neg: "count(xs, # < 0)", all: "count(xs, true)", none: "count(xs, false)"}}]}, + cases: [ + [{xs: [-1, 2, -3]}, {neg: 2, all: 3, none: 0}], + [{xs: []}, {neg: 0, all: 0, none: 0}], + [{xs: [0]}, {neg: 0, all: 1, none: 0}], + [{xs: [-0.01]}, {neg: 1, all: 1, none: 0}], + ], +} + +{ + name: "sum, avg, min and max over mapped members", + graph: {nodes: [{expression: "calc", fields: { + prices: "map(items, #.price)", + total: "sum($.prices)", + mean: "avg($.prices)", + low: "min($.prices)", + high: "max($.prices)", + }}]}, + cases: [ + [{items: [{price: 10}, {price: 20}, {price: 30}]}, {prices: [10, 20, 30], total: 60, mean: 20, low: 10, high: 30}], + [{items: [{price: 0.1}, {price: 0.2}]}, {prices: [0.1, 0.2], total: 0.3, mean: 0.15, low: 0.1, high: 0.2}], + [{items: [{price: -5}]}, {prices: [-5], total: -5, mean: -5, low: -5, high: -5}], + ], +} + +{ + name: "aggregates over an empty array", + graph: {nodes: [{expression: "calc", fields: {total: "sum(xs)", mean: "avg(xs)", low: "min(xs)", high: "max(xs)", n: "count(xs, true)"}}]}, + cases: [ + [{xs: []}, "!error", "question: avg/min/max of an empty array fail the whole node (expression spec asks the same); sum and count give 0"], + [{xs: [4]}, {total: 4, mean: 4, low: 4, high: 4, n: 1}], + [{xs: [1, 2]}, {total: 3, mean: 1.5, low: 1, high: 2, n: 2}], + ], +} + +{ + name: "sum over an array holding null is an error, coalescing first is not", + graph: {nodes: [{expression: "calc", fields: {safe: "sum(map(xs, # ?? 0))", raw: "sum(xs)"}}]}, + cases: [ + [{xs: [1, 2]}, {safe: 3, raw: 3}], + [{xs: [1, null]}, "!error"], + [{xs: []}, {safe: 0, raw: 0}], + ], +} + +{ + name: "sum of a filtered map", + graph: {nodes: [{expression: "calc", fields: {due: "sum(map(filter(lines, not #.paid), #.amount))"}}]}, + cases: [ + [{lines: [{amount: 10, paid: true}, {amount: 5, paid: false}, {amount: 2.5, paid: false}]}, {due: 7.5}], + [{lines: [{amount: 10, paid: true}]}, {due: 0}], + [{lines: []}, {due: 0}], + [{lines: [{amount: 0.1, paid: false}, {amount: 0.2, paid: false}]}, {due: 0.3}], + ], +} + +// --------------------------------------------------------------------------- +// flatMap and nested closures. +{ + name: "flatMap flattens one level of per-element arrays", + graph: {nodes: [{expression: "calc", fields: {tags: "flatMap(posts, #.tags)", n: "len($.tags)"}}]}, + cases: [ + [{posts: [{tags: ["a", "b"]}, {tags: ["c"]}]}, {tags: ["a", "b", "c"], n: 3}], + [{posts: [{tags: []}, {tags: ["x"]}]}, {tags: ["x"], n: 1}], + [{posts: []}, {tags: [], n: 0}], + [{posts: [{tags: [["deep"]]}]}, {tags: [["deep"]], n: 1}], + ], +} + +{ + name: "nested map over a matrix", + graph: {nodes: [{expression: "calc", fields: {scaled: "map(rows, map(#, # * 10))", sizes: "map(rows, len(#))"}}]}, + cases: [ + [{rows: [[1, 2], [3]]}, {scaled: [[10, 20], [30]], sizes: [2, 1]}], + [{rows: [[], [1]]}, {scaled: [[], [10]], sizes: [0, 1]}], + [{rows: []}, {scaled: [], sizes: []}], + ], +} + +{ + name: "nested closures with aliases read the outer element", + graph: {nodes: [{expression: "calc", fields: { + pairs: "map(orders as o, map(o.lines as l, o.id + ':' + l.sku))", + big: "filter(orders as o, some(o.lines as l, l.qty > o.limit))", + }}]}, + cases: [ + [ + {orders: [{id: "a", limit: 1, lines: [{sku: "x", qty: 1}, {sku: "y", qty: 2}]}, {id: "b", limit: 5, lines: [{sku: "z", qty: 3}]}]}, + {pairs: [["a:x", "a:y"], ["b:z"]], big: [{id: "a", limit: 1, lines: [{sku: "x", qty: 1}, {sku: "y", qty: 2}]}]}, + ], + [{orders: [{id: "c", limit: 0, lines: []}]}, {pairs: [[]], big: []}], + [{orders: []}, {pairs: [], big: []}], + ], +} + +{ + name: "nested closures read request fields from outside the closure", + graph: {nodes: [{expression: "calc", fields: { + adjusted: "map(groups, map(#, # * rate))", + over: "count(groups, some(#, # > cap))", + }}]}, + cases: [ + [{groups: [[1, 2], [10]], rate: 2, cap: 5}, {adjusted: [[2, 4], [20]], over: 1}], + [{groups: [[1], [2]], rate: 0.5, cap: 0}, {adjusted: [[0.5], [1]], over: 2}], + [{groups: [], rate: 1, cap: 1}, {adjusted: [], over: 0}], + ], +} + +{ + name: "a closure reading an earlier field through $", + graph: {nodes: [{expression: "calc", fields: { + threshold: "avg(xs)", + above: "filter(xs, # > $.threshold)", + shifted: "map(xs, # - $.threshold)", + }}]}, + cases: [ + [{xs: [1, 2, 3]}, {threshold: 2, above: [3], shifted: [-1, 0, 1]}], + [{xs: [4, 4]}, {threshold: 4, above: [], shifted: [0, 0]}], + [{xs: [0, 10]}, {threshold: 5, above: [10], shifted: [-5, 5]}], + ], +} + +{ + name: "a closure building objects from elements and request fields", + graph: {nodes: [{expression: "calc", fields: {lines: "map(items, {sku: #.sku, total: #.qty * price, currency: currency})"}}]}, + cases: [ + [{items: [{sku: "a", qty: 2}], price: 3, currency: "EUR"}, {lines: [{sku: "a", total: 6, currency: "EUR"}]}], + [{items: [{sku: "a", qty: 1}, {sku: "b", qty: 0}], price: 1.5, currency: "USD"}, {lines: [{sku: "a", total: 1.5, currency: "USD"}, {sku: "b", total: 0, currency: "USD"}]}], + [{items: [], price: 1, currency: "EUR"}, {lines: []}], + [{items: [{sku: "a", qty: 1}], price: 1}, {lines: [{sku: "a", total: 1, currency: null}]}], + ], +} + +// --------------------------------------------------------------------------- +// Closures over arrays produced by earlier nodes. +{ + name: "a downstream node maps over an upstream node's array", + graph: { + nodes: [ + {expression: "prices", fields: {list: "map(items, #.price)"}}, + {expression: "taxed", fields: {gross: "map(list, # * 1.2)", total: "sum(map(list, # * 1.2))"}}, + ], + }, + cases: [ + [{items: [{price: 10}, {price: 5}]}, {gross: [12, 6], total: 18}], + [{items: []}, {gross: [], total: 0}], + [{items: [{price: 0.1}]}, {gross: [0.12], total: 0.12}], + ], +} + +{ + name: "a downstream node filters an upstream array through $nodes", + graph: { + nodes: [ + {expression: "base", fields: {scores: "map(people, #.score)"}}, + {expression: "next", fields: {passing: "filter($nodes.base.scores, # >= 50)", allIn: "all($nodes.base.scores, # >= 0)"}}, + ], + }, + cases: [ + [{people: [{score: 10}, {score: 60}, {score: 50}]}, {passing: [60, 50], allIn: true}], + [{people: [{score: -1}]}, {passing: [], allIn: false}], + [{people: []}, {passing: [], allIn: true}], + ], +} + +{ + name: "a downstream node closes over an upstream pass-through array", + graph: { + nodes: [ + {expression: "enrich", passThrough: true, fields: {rate: "0.5"}}, + {expression: "apply", fields: {out: "map(xs, # * rate)"}}, + ], + }, + cases: [ + [{xs: [2, 4]}, {out: [1, 2]}], + [{xs: []}, {out: []}], + [{xs: [0.1]}, {out: [0.05]}], + ], +} + +{ + name: "arrays from two parallel branches combined after a join", + graph: { + nodes: [ + {expression: "evens", fields: {e: "filter(xs, # % 2 == 0)"}}, + {expression: "odds", fields: {o: "filter(xs, # % 2 == 1)"}}, + {expression: "join", fields: {counts: "[len(e), len(o)]", all: "merge([e, o])"}}, + ], + edges: ["input -> evens -> join", "input -> odds -> join", "join -> output"], + }, + cases: [ + [{xs: [1, 2, 3, 4]}, {counts: [2, 2], all: [2, 4, 1, 3]}], + [{xs: [1]}, {counts: [0, 1], all: [1]}], + [{xs: []}, {counts: [0, 0], all: []}], + ], +} + +{ + name: "a loop node output array aggregated by the next node", + graph: { + nodes: [ + {expression: "line", executionMode: "loop", inputField: "items", outputPath: "lines", fields: {total: "price * qty"}}, + {expression: "sum", fields: {grand: "sum(map(lines, #.total))", n: "len(lines)"}}, + ], + }, + cases: [ + [{items: [{price: 2, qty: 3}, {price: 1.5, qty: 2}]}, {grand: 9, n: 2}], + [{items: [{price: 1, qty: 1}]}, {grand: 1, n: 1}], + [{items: []}, {grand: 0, n: 0}], + ], +} + +{ + name: "a collect table's rows reduced by a closure", + graph: { + nodes: [ + {table: "fees", hit: "collect", inputs: ["amount"], outputs: ["name", "fee"], rules: [ + ["> 0", "'base'", "1"], + ["> 100", "'large'", "amount * 0.01"], + ["> 1000", "'huge'", "5"], + ], outputPath: "fees"}, + {expression: "total", fields: {fee: "sum(map(fees, #.fee))", names: "map(fees, #.name)"}}, + ], + }, + cases: [ + [{amount: 50}, {fee: 1, names: ["base"]}], + [{amount: 200}, {fee: 3, names: ["base", "large"]}], + [{amount: 2000}, {fee: 26, names: ["base", "large", "huge"]}], + [{amount: 0}, {fee: 0, names: []}], + ], +} + +// --------------------------------------------------------------------------- +// Closure results flowing into decision tables. +{ + name: "a count feeds a first-hit table", + graph: { + nodes: [ + {expression: "stats", fields: {late: "count(payments, #.daysLate > 30)"}}, + {table: "band", inputs: ["late"], outputs: ["risk"], rules: [ + ["0", "'low'"], + ["[1..2]", "'medium'"], + ["", "'high'"], + ]}, + ], + }, + cases: [ + [{payments: []}, {risk: "low"}], + [{payments: [{daysLate: 10}, {daysLate: 31}]}, {risk: "medium"}], + [{payments: [{daysLate: 40}, {daysLate: 31}]}, {risk: "medium"}], + [{payments: [{daysLate: 40}, {daysLate: 31}, {daysLate: 99}]}, {risk: "high"}], + [{payments: [{daysLate: 30}]}, {risk: "low"}], + ], +} + +{ + name: "a boolean quantifier feeds a table column", + graph: { + nodes: [ + {expression: "flags", fields: {anyMinor: "some(drivers, #.age < 18)", allLicensed: "all(drivers, #.licensed)"}}, + {table: "eligible", inputs: ["anyMinor", "allLicensed"], outputs: ["ok", "reason"], rules: [ + ["true", "", "false", "'minor driver'"], + ["", "false", "false", "'unlicensed'"], + ["", "", "true", "'ok'"], + ]}, + ], + }, + cases: [ + [{drivers: [{age: 30, licensed: true}]}, {ok: true, reason: "ok"}], + [{drivers: [{age: 16, licensed: true}]}, {ok: false, reason: "minor driver"}], + [{drivers: [{age: 30, licensed: false}]}, {ok: false, reason: "unlicensed"}], + [{drivers: []}, {ok: true, reason: "ok"}], + ], +} + +{ + name: "a mapped array checked by table cells with membership", + graph: { + nodes: [ + {expression: "codes", fields: {codes: "map(items, #.code)"}}, + {table: "t", inputs: ["codes"], outputs: ["hasA"], rules: [ + ["'A' in $", "true"], + ["", "false"], + ]}, + ], + }, + cases: [ + [{items: [{code: "A"}, {code: "B"}]}, {hasA: true}], + [{items: [{code: "B"}]}, {hasA: false}], + [{items: []}, {hasA: false}], + ], +} + +{ + name: "a table input column is a closure over the node input", + graph: { + nodes: [ + {table: "t", inputs: ["sum(map(items, #.qty))", "len(items)"], outputs: ["size"], rules: [ + ["> 10", "", "'bulk'"], + ["", "> 3", "'many'"], + ["", "", "'small'"], + ]}, + ], + }, + cases: [ + [{items: [{qty: 11}]}, {size: "bulk"}], + [{items: [{qty: 1}, {qty: 1}, {qty: 1}, {qty: 1}]}, {size: "many"}], + [{items: [{qty: 2}]}, {size: "small"}], + [{items: []}, {size: "small"}], + ], +} + +{ + name: "table output cells computed with closures", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["picked", "count"], rules: [ + ["'cheap'", "filter(prices, # < 10)", "count(prices, # < 10)"], + ["'dear'", "filter(prices, # >= 10)", "count(prices, # >= 10)"], + ]}, + ], + }, + cases: [ + [{kind: "cheap", prices: [5, 15, 9.99]}, {picked: [5, 9.99], count: 2}], + [{kind: "dear", prices: [5, 15, 10]}, {picked: [15, 10], count: 2}], + [{kind: "dear", prices: []}, {picked: [], count: 0}], + [{kind: "other", prices: [1]}, {}], + ], +} + +{ + name: "a table in a loop over a mapped array, summed afterwards", + graph: { + nodes: [ + {expression: "prep", fields: {lines: "map(items, {amount: #.price * #.qty})"}}, + {table: "disc", executionMode: "loop", inputField: "lines", outputPath: "discounts", inputs: ["amount"], outputs: ["d"], rules: [ + [">= 100", "amount * 0.1"], + ["", "0"], + ]}, + {expression: "total", fields: {discount: "sum(map(discounts, #.d))"}}, + ], + }, + cases: [ + [{items: [{price: 50, qty: 2}, {price: 10, qty: 1}]}, {discount: 10}], + [{items: [{price: 5, qty: 1}]}, {discount: 0}], + [{items: []}, {discount: 0}], + [{items: [{price: 200, qty: 1}, {price: 300, qty: 1}]}, {discount: 50}], + ], +} + +// --------------------------------------------------------------------------- +// Closures and pass-through / null results. +{ + name: "a closure field replacing an input array under pass-through", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {xs: "filter(xs, # > 0)"}}]}, + cases: [ + [{xs: [-1, 2, 3], keep: "k"}, {xs: [2, 3], keep: "k"}], + [{xs: [-1]}, {xs: []}], + [{xs: []}, {xs: []}], + ], +} + +{ + name: "a closure producing an array of nulls keeps the nulls", + graph: {nodes: [{expression: "calc", fields: {out: "map(xs, null)"}}]}, + cases: [ + [{xs: [1, 2]}, {out: [null, null]}], + [{xs: []}, {out: []}], + ], +} + +{ + name: "a closure result read with an index", + graph: {nodes: [{expression: "calc", fields: {first: "filter(xs, # > 1)[0]", last: "map(xs, # * 2)[len(xs) - 1]"}}]}, + cases: [ + [{xs: [1, 2, 3]}, {first: 2, last: 6}], + [{xs: [5]}, {first: 5, last: 10}], + [{xs: [1]}, {last: 2}], + ], +} + +{ + name: "a closure over a range literal", + graph: {nodes: [{expression: "calc", fields: {squares: "map([1..n], # * #)"}}]}, + cases: [ + [{n: 3}, {squares: [1, 4, 9]}], + [{n: 1}, {squares: [1]}], + ], +} + +{ + name: "closures over a mixed-type array with type guards", + graph: {nodes: [{expression: "calc", fields: {nums: "filter(xs, type(#) == 'number')", strs: "count(xs, type(#) == 'string')"}}]}, + cases: [ + [{xs: [1, "a", true, null, 2.5, {}]}, {nums: [1, 2.5], strs: 1}], + [{xs: ["a", "b"]}, {nums: [], strs: 2}], + [{xs: []}, {nums: [], strs: 0}], + ], +} diff --git a/core/engine/tests/spec/graph/33-expression-objects.json5 b/core/engine/tests/spec/graph/33-expression-objects.json5 new file mode 100644 index 00000000..8e5e50c5 --- /dev/null +++ b/core/engine/tests/spec/graph/33-expression-objects.json5 @@ -0,0 +1,523 @@ +// Object and array values built in expression nodes: object literals as field values, nested +// literals mixing request paths and computed values, computed keys, merge/mergeDeep as the +// language's spread, arrays of objects, and object outputs consumed by later nodes (expression +// nodes, tables, switches, loops) through dotted reads. Literal syntax itself is in the expression +// spec; these suites pin how built values flow through the graph and the result merge. + +// --------------------------------------------------------------------------- +// Object literals as field values. +{ + name: "an object literal of request values", + graph: {nodes: [{expression: "calc", fields: {customer: "{name: name, age: age, adult: age >= 18}"}}]}, + cases: [ + [{name: "ann", age: 30}, {customer: {name: "ann", age: 30, adult: true}}], + [{name: "bob", age: 17}, {customer: {name: "bob", age: 17, adult: false}}], + [{name: "", age: 18.5}, {customer: {name: "", age: 18.5, adult: true}}], + ], +} + +{ + name: "an object literal keeps null members for missing inputs", + graph: {nodes: [{expression: "calc", fields: {customer: "{name: name, email: email}"}}]}, + cases: [ + [{name: "ann", email: "a@x"}, {customer: {name: "ann", email: "a@x"}}], + [{name: "ann"}, {customer: {name: "ann", email: null}}], + [{}, {customer: {name: null, email: null}}], + [{email: null, name: 1}, {customer: {name: 1, email: null}}], + ], +} + +{ + name: "a nested object literal mixing paths and computed values", + graph: {nodes: [{expression: "calc", fields: {quote: "{customer: {id: customer.id, tier: customer.tier ?? 'basic'}, pricing: {net: price * qty, gross: price * qty * (1 + tax), currency: 'EUR'}}"}}]}, + cases: [ + [ + {customer: {id: 7, tier: "gold"}, price: 10, qty: 2, tax: 0.2}, + {quote: {customer: {id: 7, tier: "gold"}, pricing: {net: 20, gross: 24, currency: "EUR"}}}, + ], + [ + {customer: {id: 8}, price: 0.1, qty: 3, tax: 0}, + {quote: {customer: {id: 8, tier: "basic"}, pricing: {net: 0.3, gross: 0.3, currency: "EUR"}}}, + ], + [ + {customer: {}, price: 1, qty: 1, tax: 0.5}, + {quote: {customer: {id: null, tier: "basic"}, pricing: {net: 1, gross: 1.5, currency: "EUR"}}}, + ], + ], +} + +{ + name: "an object literal with a member read on a missing parent", + graph: {nodes: [{expression: "calc", fields: {o: "{city: address.city, zip: address.zip}"}}]}, + cases: [ + [{address: {city: "Berlin", zip: "10115"}}, {o: {city: "Berlin", zip: "10115"}}], + [{address: {}}, {o: {city: null, zip: null}}], + [{}, {o: {city: null, zip: null}}], + [{address: null}, {o: {city: null, zip: null}}], + ], +} + +{ + name: "an object literal holding arrays, dates and booleans", + graph: {nodes: [{expression: "calc", fields: {o: "{tags: tags, first: tags[0], since: d(since), active: active == true}"}}]}, + cases: [ + [{tags: ["a", "b"], since: "2024-01-01", active: true}, {o: {tags: ["a", "b"], first: "a", since: "2024-01-01T00:00:00Z", active: true}}], + [{tags: [], since: "2020-02-29", active: false}, {o: {tags: [], first: null, since: "2020-02-29T00:00:00Z", active: false}}], + [{tags: ["x"], since: "2023-12-31T10:00:00Z"}, {o: {tags: ["x"], first: "x", since: "2023-12-31T10:00:00Z", active: false}}], + ], +} + +{ + name: "an empty object literal and an object of empties", + graph: {nodes: [{expression: "calc", fields: {e: "{}", o: "{a: {}, b: [], c: ''}"}}]}, + cases: [ + [{}, {e: {}, o: {a: {}, b: [], c: ""}}], + [{e: 1, o: 2}, {e: {}, o: {a: {}, b: [], c: ""}}], + ], +} + +{ + name: "a duplicate key inside one object literal", + graph: {nodes: [{expression: "calc", fields: {o: "{a: 1, a: x}"}}]}, + cases: [ + [{x: 2}, {o: {a: 1}}, "question: the expression spec records that duplicate literal keys keep the first value; JS/JSON5 keep the last"], + [{}, {o: {a: 1}}, "question: the expression spec records that duplicate literal keys keep the first value; JS/JSON5 keep the last"], + ], +} + +{ + name: "quoted keys with spaces and symbols", + graph: {nodes: [{expression: "calc", fields: {o: "{'full name': name, 'a.b': 1, 'x-y': 2}"}}]}, + cases: [ + [{name: "ann"}, {o: {"full name": "ann", "a.b": 1, "x-y": 2}}], + [{}, {o: {"full name": null, "a.b": 1, "x-y": 2}}], + ], +} + +// --------------------------------------------------------------------------- +// Computed keys. +{ + name: "a computed key from a request string", + graph: {nodes: [{expression: "calc", fields: {o: "{[key]: value}"}}]}, + cases: [ + [{key: "a", value: 1}, {o: {a: 1}}], + [{key: "b c", value: "x"}, {o: {"b c": "x"}}], + [{key: "", value: true}, {o: {"": true}}], + [{key: "n", value: null}, {o: {n: null}}], + ], +} + +{ + name: "a computed key built from a template", + graph: {nodes: [{expression: "calc", fields: {o: "{[`${prefix}_${id}`]: score}"}}]}, + cases: [ + [{prefix: "user", id: 1, score: 9}, {o: {user_1: 9}}], + [{prefix: "acct", id: "x", score: 0}, {o: {acct_x: 0}}], + ], +} + +{ + name: "a computed key that is not a string is stringified", + graph: {nodes: [{expression: "calc", fields: {o: "{[key]: 1}"}}]}, + cases: [ + [{key: "ok"}, {o: {ok: 1}}], + [{key: 5}, {o: {"5": 1}}], + [{key: 1.50}, {o: {"1.50": 1}}], + [{key: true}, {o: {"true": 1}}], + [{key: null}, {o: {"null": 1}}, "question: a null computed key becomes the string 'null' (as in the expression spec)"], + [{}, {o: {"null": 1}}, "question: a missing computed key reads null and becomes the string 'null'"], + [{key: [1]}, "!error"], + ], +} + +{ + name: "an object built from pairs with merge over map", + graph: {nodes: [{expression: "calc", fields: {byId: "merge(map(items, {[#.id]: #.value}))"}}]}, + cases: [ + [{items: [{id: "a", value: 1}, {id: "b", value: 2}]}, {byId: {a: 1, b: 2}}], + [{items: [{id: "a", value: 1}, {id: "a", value: 3}]}, {byId: {a: 3}}], + [{items: []}, {byId: {}}], + [{items: [{id: "x", value: {deep: true}}]}, {byId: {x: {deep: true}}}], + ], +} + +// --------------------------------------------------------------------------- +// merge and mergeDeep as spread: combining request objects with computed members. +{ + name: "merge spreads a request object and overrides members", + graph: {nodes: [{expression: "calc", fields: {customer: "merge([customer, {tier: 'gold', score: customer.score + 1}])"}}]}, + cases: [ + [{customer: {name: "ann", score: 1}}, {customer: {name: "ann", score: 2, tier: "gold"}}], + [{customer: {name: "bob", score: 0, tier: "basic"}}, {customer: {name: "bob", score: 1, tier: "gold"}}], + [{customer: {score: -1, extra: [1]}}, {customer: {score: 0, tier: "gold", extra: [1]}}], + ], +} + +{ + name: "merge with a missing request object", + graph: {nodes: [{expression: "calc", fields: {o: "merge([base, {added: true}])"}}]}, + cases: [ + [{base: {a: 1}}, {o: {a: 1, added: true}}], + [{base: {}}, {o: {added: true}}], + [{}, {o: {added: true}}], + [{base: null}, {o: {added: true}}], + [{base: 5}, "!error"], + ], +} + +{ + name: "merge is shallow, mergeDeep is recursive", + graph: {nodes: [{expression: "calc", fields: {shallow: "merge([a, b])", deep: "mergeDeep([a, b])"}}]}, + cases: [ + [{a: {x: {p: 1}}, b: {x: {q: 2}}}, {shallow: {x: {q: 2}}, deep: {x: {p: 1, q: 2}}}], + [{a: {x: 1}, b: {y: 2}}, {shallow: {x: 1, y: 2}, deep: {x: 1, y: 2}}], + [{a: {l: [1]}, b: {l: [2]}}, {shallow: {l: [2]}, deep: {l: [1, 2]}}], + [{a: {}, b: {}}, {shallow: {}, deep: {}}], + ], +} + +{ + name: "a null member in a merge keeps the key", + graph: {nodes: [{expression: "calc", fields: {o: "merge([a, {gone: null}])"}}]}, + cases: [ + [{a: {gone: 1, kept: 2}}, {o: {gone: null, kept: 2}}], + [{a: {}}, {o: {gone: null}}], + ], +} + +{ + name: "merge of the request root", + graph: {nodes: [{expression: "calc", fields: {all: "merge([$root, {extra: 1}])"}}]}, + cases: [ + [{a: 1}, {all: {a: 1, extra: 1}}], + [{}, {all: {extra: 1}}], + ], +} + +// --------------------------------------------------------------------------- +// Arrays of objects. +{ + name: "an array literal of object literals", + graph: {nodes: [{expression: "calc", fields: {rows: "[{k: 'a', v: a}, {k: 'b', v: b}]"}}]}, + cases: [ + [{a: 1, b: 2}, {rows: [{k: "a", v: 1}, {k: "b", v: 2}]}], + [{a: "x"}, {rows: [{k: "a", v: "x"}, {k: "b", v: null}]}], + [{}, {rows: [{k: "a", v: null}, {k: "b", v: null}]}], + ], +} + +{ + name: "an array of objects mapped from request objects", + graph: {nodes: [{expression: "calc", fields: {summary: "map(people, {name: upper(#.name), adult: #.age >= 18})"}}]}, + cases: [ + [{people: [{name: "ann", age: 30}, {name: "bob", age: 12}]}, {summary: [{name: "ANN", adult: true}, {name: "BOB", adult: false}]}], + [{people: []}, {summary: []}], + [{people: [{name: "c", age: 18}]}, {summary: [{name: "C", adult: true}]}], + ], +} + +{ + name: "an array of objects carrying their index", + graph: {nodes: [{expression: "calc", fields: {rows: "map([0..len(xs) - 1], {i: #, v: xs[#]})"}}]}, + cases: [ + [{xs: ["a", "b"]}, {rows: [{i: 0, v: "a"}, {i: 1, v: "b"}]}], + [{xs: [true]}, {rows: [{i: 0, v: true}]}], + ], +} + +{ + name: "nested arrays of objects inside an object", + graph: {nodes: [{expression: "calc", fields: {report: "{groups: map(groups, {name: #.name, members: map(#.members, {id: #})}), count: len(groups)}"}}]}, + cases: [ + [ + {groups: [{name: "a", members: [1, 2]}, {name: "b", members: []}]}, + {report: {groups: [{name: "a", members: [{id: 1}, {id: 2}]}, {name: "b", members: []}], count: 2}}, + ], + [{groups: []}, {report: {groups: [], count: 0}}], + ], +} + +{ + name: "an array literal mixing scalars, objects, arrays and nulls", + graph: {nodes: [{expression: "calc", fields: {l: "[n, {n: n}, [n], null, 'x']"}}]}, + cases: [ + [{n: 1}, {l: [1, {n: 1}, [1], null, "x"]}], + [{}, {l: [null, {n: null}, [null], null, "x"]}], + ], +} + +// --------------------------------------------------------------------------- +// Reading built objects back within the node via `$`. +{ + name: "a later field reads a member of an earlier object field", + graph: {nodes: [{expression: "calc", fields: { + totals: "{net: price * qty, tax: price * qty * rate}", + gross: "$.totals.net + $.totals.tax", + label: "`${$.totals.net} + ${$.totals.tax}`", + }}]}, + cases: [ + [{price: 10, qty: 2, rate: 0.1}, {totals: {net: 20, tax: 2}, gross: 22, label: "20 + 2.0"}], + [{price: 1, qty: 0, rate: 0.2}, {totals: {net: 0, tax: 0}, gross: 0, label: "0 + 0"}], + ], +} + +{ + name: "a later field indexes an earlier array of objects", + graph: {nodes: [{expression: "calc", fields: { + rows: "map(xs, {v: #})", + first: "$.rows[0].v", + last: "$.rows[len($.rows) - 1].v", + }}]}, + cases: [ + [{xs: [3, 4, 5]}, {rows: [{v: 3}, {v: 4}, {v: 5}], first: 3, last: 5}], + [{xs: ["a"]}, {rows: [{v: "a"}], first: "a", last: "a"}], + ], +} + +{ + name: "keys and values of an object built earlier", + graph: {nodes: [{expression: "calc", fields: {o: "{x: a, y: b}", n: "len(keys($.o))", sum: "sum(values($.o))"}}]}, + cases: [ + [{a: 1, b: 2}, {o: {x: 1, y: 2}, n: 2, sum: 3}], + [{a: 0.1, b: 0.2}, {o: {x: 0.1, y: 0.2}, n: 2, sum: 0.3}], + ], +} + +{ + name: "a dotted key extends an object literal field and a later field reads both", + graph: {nodes: [{expression: "calc", fields: [ + ["o", "{a: a}"], + ["o.b", "b"], + ["both", "$.o.a + $.o.b"], + ]}]}, + cases: [ + [{a: 1, b: 2}, {o: {a: 1, b: 2}, both: 3}], + [{a: 0.5, b: 0.5}, {o: {a: 0.5, b: 0.5}, both: 1}], + ], +} + +// --------------------------------------------------------------------------- +// Object outputs consumed downstream through dotted reads. +{ + name: "a downstream expression reads members of an upstream object", + graph: { + nodes: [ + {expression: "build", fields: {customer: "{name: name, score: score * 10}"}}, + {expression: "use", fields: {greeting: "'hi ' + customer.name", high: "customer.score > 50"}}, + ], + }, + cases: [ + [{name: "ann", score: 6}, {greeting: "hi ann", high: true}], + [{name: "bob", score: 5}, {greeting: "hi bob", high: false}], + [{name: "", score: 0}, {greeting: "hi ", high: false}], + ], +} + +{ + name: "a downstream read of a null member of an upstream object", + graph: { + nodes: [ + {expression: "build", fields: {o: "{a: a, b: b}"}}, + {expression: "use", fields: {aNull: "o.a == null", hasA: "'a' in keys(o)", b: "o.b"}}, + ], + }, + cases: [ + [{a: 1, b: 2}, {aNull: false, hasA: true, b: 2}], + [{b: 2}, {aNull: true, hasA: true, b: 2}], + [{}, {aNull: true, hasA: true}], + ], +} + +{ + name: "deep dotted reads three levels into an upstream object", + graph: { + nodes: [ + {expression: "build", fields: {a: "{b: {c: {d: v, e: [v, v]}}}"}}, + {expression: "use", fields: {d: "a.b.c.d", e1: "a.b.c.e[1]", missing: "a.b.x.y"}}, + ], + }, + cases: [ + [{v: 1}, {d: 1, e1: 1}], + [{v: "s"}, {d: "s", e1: "s"}], + [{}, {}], + ], +} + +{ + name: "a downstream node reads an upstream object through $nodes", + graph: { + nodes: [ + {expression: "build", fields: {o: "{total: price * qty}"}}, + {expression: "mid", fields: {unrelated: "1"}}, + {expression: "use", fields: {total: "$nodes.build.o.total", whole: "$nodes.build"}}, + ], + }, + cases: [ + [{price: 2, qty: 3}, {total: 6, whole: {o: {total: 6}}}], + [{price: 0.5, qty: 2}, {total: 1, whole: {o: {total: 1}}}], + ], +} + +{ + name: "a table reads dotted members of an upstream object", + graph: { + nodes: [ + {expression: "build", fields: {applicant: "{age: age, income: income, ratio: debt / income}"}}, + {table: "score", inputs: ["applicant.age", "applicant.ratio"], outputs: ["band"], rules: [ + ["< 18", "", "'reject'"], + ["", "> 0.5", "'high'"], + ["", "", "'ok'"], + ]}, + ], + }, + cases: [ + [{age: 17, income: 100, debt: 0}, {band: "reject"}], + [{age: 30, income: 100, debt: 60}, {band: "high"}], + [{age: 30, income: 100, debt: 50}, {band: "ok"}], + [{age: 40, income: 1, debt: 0}, {band: "ok"}], + ], +} + +{ + name: "a table outputs into dotted keys and a later node reads the object", + graph: { + nodes: [ + {table: "t", inputs: ["tier"], outputs: ["offer.rate", "offer.label"], rules: [ + ["'gold'", "0.2", "'Gold'"], + ["", "0", "'Standard'"], + ]}, + {expression: "use", fields: {text: "offer.label + ': ' + string(offer.rate * 100) + '%'", offer: "offer"}}, + ], + }, + cases: [ + [{tier: "gold"}, {text: "Gold: 20.0%", offer: {rate: 0.2, label: "Gold"}}], + [{tier: "silver"}, {text: "Standard: 0%", offer: {rate: 0, label: "Standard"}}], + ], +} + +{ + name: "a switch condition reads a member of an upstream object", + graph: { + nodes: [ + {expression: "build", fields: {risk: "{score: a + b, flagged: a > 5}"}}, + {switch: "route", when: ["risk.flagged", "risk.score > 3", ""]}, + {expression: "flag", fields: {route: "'flag'"}}, + {expression: "review", fields: {route: "'review'"}}, + {expression: "pass", fields: {route: "'pass'"}}, + ], + edges: ["input -> build -> route", "route:0 -> flag -> output", "route:1 -> review -> output", "route:2 -> pass -> output"], + }, + cases: [ + [{a: 6, b: 0}, {route: "flag"}], + [{a: 2, b: 2}, {route: "review"}], + [{a: 1, b: 1}, {route: "pass"}], + ], +} + +{ + name: "an inputField points at an object built upstream", + graph: { + nodes: [ + {expression: "build", fields: {ctx: "{x: a * 2, y: a * 3}"}}, + {expression: "use", inputField: "ctx", fields: {sum: "x + y"}}, + ], + }, + cases: [ + [{a: 1}, {sum: 5}], + [{a: 0.1}, {sum: 0.5}], + [{a: 0}, {sum: 0}], + ], +} + +{ + name: "a loop over an array of objects built upstream", + graph: { + nodes: [ + {expression: "build", fields: {lines: "map(items, {net: #.price * #.qty, rate: rate})"}}, + {expression: "line", executionMode: "loop", inputField: "lines", outputPath: "taxed", fields: {gross: "net * (1 + rate)"}}, + ], + }, + cases: [ + [{items: [{price: 10, qty: 1}, {price: 5, qty: 2}], rate: 0.2}, {taxed: [{gross: 12}, {gross: 12}]}], + [{items: [], rate: 0.2}, {taxed: []}], + [{items: [{price: 1, qty: 1}], rate: 0}, {taxed: [{gross: 1}]}], + ], +} + +{ + name: "a sub-decision receives an object built upstream", + decisions: { + child: {nodes: [{expression: "calc", fields: {area: "shape.w * shape.h", kind: "shape.w == shape.h ? 'square' : 'rect'"}}]}, + }, + graph: { + nodes: [ + {expression: "build", fields: {shape: "{w: w, h: h}"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{w: 2, h: 2}, {area: 4, kind: "square"}], + [{w: 2, h: 3}, {area: 6, kind: "rect"}], + [{w: 0.5, h: 4}, {area: 2, kind: "rect"}], + ], +} + +// --------------------------------------------------------------------------- +// Objects in the result merge and under pass-through. +{ + name: "object fields from parallel branches deep-merge in the result", + graph: { + nodes: [ + {expression: "a", fields: {profile: "{name: name}"}}, + {expression: "b", fields: {profile: "{score: score, flags: {vip: score > 90}}"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{name: "ann", score: 95}, {profile: {name: "ann", score: 95, flags: {vip: true}}}], + [{name: "bob", score: 10}, {profile: {name: "bob", score: 10, flags: {vip: false}}}], + ], +} + +{ + name: "an object field merges into an input object under pass-through", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {customer: "{tier: customer.score > 50 ? 'gold' : 'basic', meta: {checked: true}}"}}]}, + cases: [ + [{customer: {name: "ann", score: 80}}, {customer: {name: "ann", score: 80, tier: "gold", meta: {checked: true}}}], + [{customer: {name: "bob", score: 10, meta: {src: "x"}}}, {customer: {name: "bob", score: 10, tier: "basic", meta: {src: "x", checked: true}}}], + ], +} + +{ + name: "a null member of an object literal deletes the input key under pass-through (merge-patch)", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {customer: "{email: null, seen: true}"}}]}, + cases: [ + [{customer: {email: "a@x", name: "ann"}}, {customer: {name: "ann", seen: true}}], + [{customer: {name: "ann"}}, {customer: {name: "ann", seen: true}}], + [{}, {customer: {email: null, seen: true}}], + ], +} + +{ + name: "an array of objects replaces an input array under pass-through", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {items: "map(items, {id: #.id})"}}]}, + cases: [ + [{items: [{id: 1, junk: true}, {id: 2, junk: false}]}, {items: [{id: 1}, {id: 2}]}], + [{items: []}, {items: []}], + ], +} + +{ + name: "an object output of a node chain accumulated by dotted keys and literals", + graph: { + nodes: [ + {expression: "one", passThrough: true, fields: {acc: "{a: 1}"}}, + {expression: "two", passThrough: true, fields: {"acc.b": "acc.a + 1"}}, + {expression: "three", passThrough: true, fields: {acc: "merge([acc, {c: acc.b + 1}])"}}, + ], + }, + cases: [ + [{}, {acc: {a: 1, b: 2, c: 3}}], + [{acc: {z: 0}}, {acc: {z: 0, a: 1, b: 2, c: 3}}], + ], +} diff --git a/core/engine/tests/spec/graph/34-expression-templates-and-strings.json5 b/core/engine/tests/spec/graph/34-expression-templates-and-strings.json5 new file mode 100644 index 00000000..012e1b49 --- /dev/null +++ b/core/engine/tests/spec/graph/34-expression-templates-and-strings.json5 @@ -0,0 +1,683 @@ +// Strings across expression nodes: template strings over request values, `$` fields and upstream +// node outputs, strings assembled from several nodes and branches, string functions applied to node +// outputs, the conversions string(), number() and bool() between nodes, and numbers and dates +// formatted into text. Function-level string semantics live in the expression spec; these suites +// pin how text is built and carried through graphs. + +// --------------------------------------------------------------------------- +// Template strings over request values of every type. +{ + name: "a template interpolating request scalars", + graph: {nodes: [{expression: "calc", fields: {msg: "`${name} is ${age} (${active})`"}}]}, + cases: [ + [{name: "ann", age: 30, active: true}, {msg: "ann is 30 (true)"}], + [{name: "", age: 0, active: false}, {msg: " is 0 (false)"}], + [{name: "bob", age: 1.50, active: true}, {msg: "bob is 1.50 (true)"}], + [{name: "é😀", age: -0.25, active: false}, {msg: "é😀 is -0.25 (false)"}], + ], +} + +{ + name: "a template interpolating a missing value renders null", + graph: {nodes: [{expression: "calc", fields: {msg: "`hello ${name}`", safe: "`hello ${name ?? 'guest'}`"}}]}, + cases: [ + [{name: "ann"}, {msg: "hello ann", safe: "hello ann"}], + [{}, {msg: "hello null", safe: "hello guest"}], + [{name: null}, {msg: "hello null", safe: "hello guest"}], + ], +} + +{ + name: "a template interpolating an array or object fails the node", + graph: {nodes: [{expression: "calc", fields: {msg: "`v=${v}`"}}]}, + cases: [ + [{v: 1}, {msg: "v=1"}], + [{v: "s"}, {msg: "v=s"}], + [{v: [1]}, "!error"], + [{v: {a: 1}}, "!error"], + [{v: []}, "!error"], + ], +} + +{ + name: "a template over nested request members", + graph: {nodes: [{expression: "calc", fields: {addr: "`${address.street} ${address.no}, ${address.city}`"}}]}, + cases: [ + [{address: {street: "Main", no: 5, city: "Berlin"}}, {addr: "Main 5, Berlin"}], + [{address: {street: "Elm", city: "Paris"}}, {addr: "Elm null, Paris"}], + [{address: {}}, {addr: "null null, null"}], + ], +} + +{ + name: "a template with expressions inside the placeholders", + graph: {nodes: [{expression: "calc", fields: {msg: "`${qty} x ${price} = ${qty * price}${qty > 1 ? ' (bulk)' : ''}`"}}]}, + cases: [ + [{qty: 2, price: 1.5}, {msg: "2 x 1.5 = 3.0 (bulk)"}], + [{qty: 1, price: 10}, {msg: "1 x 10 = 10"}], + [{qty: 0, price: 0.1}, {msg: "0 x 0.1 = 0"}], + ], +} + +{ + name: "a template with an arithmetic error fails the graph", + graph: {nodes: [{expression: "calc", fields: {msg: "`total ${a + b}`"}}]}, + cases: [ + [{a: 1, b: 2}, {msg: "total 3"}], + [{a: 1}, "!error"], + [{a: "x", b: 1}, "!error"], + [{a: "x", b: "y"}, {msg: "total xy"}], + ], +} + +{ + name: "a template over a closure result", + graph: {nodes: [{expression: "calc", fields: {msg: "`${len(items)} items, total ${sum(map(items, #.price))}`"}}]}, + cases: [ + [{items: [{price: 1}, {price: 2}]}, {msg: "2 items, total 3"}], + [{items: []}, {msg: "0 items, total 0"}], + [{items: [{price: 0.10}]}, {msg: "1 items, total 0.10"}], + ], +} + +{ + name: "templates inside a map build a list of strings", + graph: {nodes: [{expression: "calc", fields: {lines: "map(items, `${#.name}: ${#.qty}`)"}}]}, + cases: [ + [{items: [{name: "a", qty: 1}, {name: "b", qty: 2}]}, {lines: ["a: 1", "b: 2"]}], + [{items: [{name: "c"}]}, {lines: ["c: null"]}], + [{items: []}, {lines: []}], + ], +} + +{ + name: "nested template strings", + graph: {nodes: [{expression: "calc", fields: {msg: "`outer ${`inner ${x}`} end`"}}]}, + cases: [ + [{x: 1}, {msg: "outer inner 1 end"}, "bug: a template nested in an interpolation fails to parse (same as the expression spec)"], + [{x: "y"}, {msg: "outer inner y end"}, "bug: a template nested in an interpolation fails to parse (same as the expression spec)"], + ], +} + +// --------------------------------------------------------------------------- +// Templates over `$` fields and over upstream node outputs. +{ + name: "a template reads earlier fields through $", + graph: {nodes: [{expression: "calc", fields: { + net: "price * qty", + tax: "$.net * 0.2", + line: "`net ${$.net}, tax ${$.tax}, gross ${$.net + $.tax}`", + }}]}, + cases: [ + [{price: 10, qty: 2}, {net: 20, tax: 4, line: "net 20, tax 4.0, gross 24.0"}], + [{price: 1, qty: 1}, {net: 1, tax: 0.2, line: "net 1, tax 0.2, gross 1.2"}], + ], +} + +{ + name: "a template reads an upstream node's output", + graph: { + nodes: [ + {expression: "calc", fields: {total: "price * qty", currency: "currency ?? 'EUR'"}}, + {expression: "text", fields: {summary: "`Total: ${total} ${currency}`"}}, + ], + }, + cases: [ + [{price: 5, qty: 2, currency: "USD"}, {summary: "Total: 10 USD"}], + [{price: 0.5, qty: 3}, {summary: "Total: 1.5 EUR"}], + ], +} + +{ + name: "a template reads several nodes through $nodes", + graph: { + nodes: [ + {expression: "who", fields: {name: "upper(name)"}}, + {expression: "what", fields: {action: "$nodes.input.verb + 'ed'"}}, + {expression: "say", fields: {line: "`${$nodes.who.name} ${$nodes.what.action} at ${$nodes.input.place}`"}}, + ], + }, + cases: [ + [{name: "ann", verb: "jump", place: "home"}, {line: "ANN jumped at home"}], + [{name: "", verb: "", place: ""}, {line: " ed at "}], + ], +} + +{ + name: "a template reads a table output", + graph: { + nodes: [ + {table: "tier", inputs: ["points"], outputs: ["tier", "discount"], rules: [ + [">= 1000", "'gold'", "0.15"], + [">= 100", "'silver'", "0.05"], + ["", "'none'", "0"], + ]}, + {expression: "text", fields: {msg: "`${upper(tier)} tier, ${discount * 100}% off`"}}, + ], + }, + cases: [ + [{points: 1500}, {msg: "GOLD tier, 15.00% off"}], + [{points: 100}, {msg: "SILVER tier, 5.00% off"}], + [{points: 0}, {msg: "NONE tier, 0% off"}], + ], +} + +{ + name: "a template over a table that matched nothing", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["label"], rules: [["'a'", "'Alpha'"]]}, + {expression: "text", fields: {msg: "`label=${label}`"}}, + ], + }, + cases: [ + [{code: "a"}, {msg: "label=Alpha"}], + [{code: "b"}, {msg: "label=null"}], + ], +} + +{ + name: "table output cells written as templates", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["msg"], rules: [ + ["'greet'", "`hello ${name}`"], + ["'bye'", "`bye ${name}, see you ${when ?? 'soon'}`"], + ["", "`unknown ${kind}`"], + ]}, + ], + }, + cases: [ + [{kind: "greet", name: "ann"}, {msg: "hello ann"}], + [{kind: "bye", name: "bob", when: "monday"}, {msg: "bye bob, see you monday"}], + [{kind: "bye", name: "bob"}, {msg: "bye bob, see you soon"}], + [{kind: "x"}, {msg: "unknown x"}], + ], +} + +{ + name: "a template inside a loop node", + graph: { + nodes: [ + {expression: "line", executionMode: "loop", inputField: "items", outputPath: "labels", fields: {label: "`#${id} ${name}`"}}, + ], + }, + cases: [ + [{items: [{id: 1, name: "a"}, {id: 2, name: "b"}]}, {labels: [{label: "#1 a"}, {label: "#2 b"}]}], + [{items: []}, {labels: []}], + ], +} + +// --------------------------------------------------------------------------- +// Strings assembled from several nodes and branches. +{ + name: "concatenation across a chain of nodes", + graph: { + nodes: [ + {expression: "a", fields: {s: "first"}}, + {expression: "b", fields: {s: "s + ' ' + $nodes.input.middle"}}, + {expression: "c", fields: {full: "s + ' ' + $nodes.input.last", first: "$nodes.a.s"}}, + ], + }, + cases: [ + [{first: "a", middle: "b", last: "c"}, {full: "a b c", first: "a"}], + [{first: "", middle: "", last: ""}, {full: " ", first: ""}], + [{first: "x", middle: "y"}, "!error"], + ], +} + +{ + name: "concatenation of strings from parallel branches after a join", + graph: { + nodes: [ + {expression: "left", fields: {l: "upper(a)"}}, + {expression: "right", fields: {r: "lower(b)"}}, + {expression: "join", fields: {s: "l + '-' + r", n: "len(l + r)"}}, + ], + edges: ["input -> left -> join", "input -> right -> join", "join -> output"], + }, + cases: [ + [{a: "x", b: "Y"}, {s: "X-y", n: 2}], + [{a: "", b: ""}, {s: "-", n: 0}], + [{a: "Ab", b: "CD"}, {s: "AB-cd", n: 4}], + ], +} + +{ + name: "a string built incrementally by pass-through nodes", + graph: { + nodes: [ + {expression: "one", passThrough: true, fields: {acc: "'a'"}}, + {expression: "two", passThrough: true, fields: {acc: "acc + 'b'"}}, + {expression: "three", passThrough: true, fields: {acc: "acc + 'c'", size: "len(acc + 'c')"}}, + ], + }, + cases: [ + [{}, {acc: "abc", size: 3}], + [{acc: "zzz", x: 1}, {acc: "abc", size: 3, x: 1}], + ], +} + +{ + name: "a list of words built upstream read downstream", + graph: { + nodes: [ + {expression: "words", fields: {ws: "map(filter(parts, len(#) > 0), upper(#))"}}, + {expression: "use", fields: {first: "ws[0] ?? ''", hasA: "contains(ws, 'A')", lens: "map(ws, len(#))"}}, + ], + }, + cases: [ + [{parts: ["a", "", "bc"]}, {first: "A", hasA: true, lens: [1, 2]}], + [{parts: ["x"]}, {first: "X", hasA: false, lens: [1]}], + [{parts: []}, {first: "", hasA: false, lens: []}], + ], +} + +{ + name: "a string concatenated with a number needs string()", + graph: {nodes: [{expression: "calc", fields: {a: "'n=' + string(n)", b: "string(n) + '!'"}}]}, + cases: [ + [{n: 1}, {a: "n=1", b: "1!"}], + [{n: 1.50}, {a: "n=1.50", b: "1.50!"}], + [{n: -2}, {a: "n=-2", b: "-2!"}], + ], +} + +{ + name: "a string concatenated with a raw number fails", + graph: {nodes: [{expression: "calc", fields: {a: "'n=' + n"}}]}, + cases: [ + [{n: "1"}, {a: "n=1"}], + [{n: 1}, "!error"], + [{n: 1.50}, "!error"], + ], +} + +{ + name: "a string concatenated with null or a boolean", + graph: {nodes: [{expression: "calc", fields: {out: "'v=' + v"}}]}, + cases: [ + [{v: "s"}, {out: "v=s"}], + [{v: true}, "!error"], + [{v: null}, "!error"], + [{}, "!error"], + ], +} + +// --------------------------------------------------------------------------- +// String functions over node outputs. +{ + name: "case and trim functions over an upstream string", + graph: { + nodes: [ + {expression: "src", fields: {raw: "' ' + name + ' '"}}, + {expression: "fn", fields: {trimmed: "trim(raw)", up: "upper(trim(raw))", low: "lower(raw)", size: "len(trim(raw))"}}, + ], + }, + cases: [ + [{name: "Ann"}, {trimmed: "Ann", up: "ANN", low: " ann ", size: 3}], + [{name: ""}, {trimmed: "", up: "", low: " ", size: 0}], + [{name: "a B"}, {trimmed: "a B", up: "A B", low: " a b ", size: 3}], + ], +} + +{ + name: "prefix, suffix and contains over an upstream string", + graph: { + nodes: [ + {expression: "src", fields: {email: "lower(email)"}}, + {expression: "fn", fields: { + corp: "endsWith(email, '@corp.com')", + admin: "startsWith(email, 'admin')", + plus: "contains(email, '+')", + }}, + ], + }, + cases: [ + [{email: "Admin@Corp.com"}, {corp: true, admin: true, plus: false}], + [{email: "ann+x@mail.com"}, {corp: false, admin: false, plus: true}], + [{email: ""}, {corp: false, admin: false, plus: false}], + ], +} + +{ + name: "split an upstream string and read the parts", + graph: { + nodes: [ + {expression: "src", fields: {code: "trim(code)"}}, + {expression: "fn", fields: {parts: "split(code, '-')", country: "split(code, '-')[0]", n: "len(split(code, '-'))"}}, + ], + }, + cases: [ + [{code: " DE-BY-123 "}, {parts: ["DE", "BY", "123"], country: "DE", n: 3}], + [{code: "FR"}, {parts: ["FR"], country: "FR", n: 1}], + [{code: ""}, {parts: [""], country: "", n: 1}], + [{code: "-"}, {parts: ["", ""], country: "", n: 2}], + ], +} + +{ + name: "matches and extract over an upstream value", + graph: { + nodes: [ + {expression: "src", fields: {ref: "upper(ref)"}}, + {expression: "fn", fields: {valid: "matches(ref, '^[A-Z]{3}-[0-9]+$')", digits: "extract(ref, '([0-9]+)')"}}, + ], + }, + cases: [ + [{ref: "abc-123"}, {valid: true, digits: ["123", "123"]}], + [{ref: "ab-1"}, {valid: false, digits: ["1", "1"]}], + [{ref: "xyz"}, {valid: false, digits: []}], + ], +} + +{ + name: "string functions over a missing upstream value fail", + graph: { + nodes: [ + {expression: "src", fields: {s: "v"}}, + {expression: "fn", fields: {up: "upper(s)"}}, + ], + }, + cases: [ + [{v: "a"}, {up: "A"}], + [{}, "!error"], + [{v: 1}, "!error"], + ], +} + +{ + name: "string comparisons drive a table", + graph: { + nodes: [ + {expression: "norm", fields: {country: "upper(trim(country))"}}, + {table: "t", inputs: ["country"], outputs: ["region"], rules: [ + ["'DE', 'FR', 'IT'", "'EU'"], + ["'US'", "'NA'"], + ["", "'OTHER'"], + ]}, + ], + }, + cases: [ + [{country: " de "}, {region: "EU"}], + [{country: "us"}, {region: "NA"}], + [{country: "Fr"}, {region: "EU"}], + [{country: "jp"}, {region: "OTHER"}], + ], +} + +// --------------------------------------------------------------------------- +// Conversions between nodes. +{ + name: "number() parses request strings for arithmetic downstream", + graph: { + nodes: [ + {expression: "parse", fields: {amount: "number(amount)", qty: "number(qty)"}}, + {expression: "calc", fields: {total: "amount * qty"}}, + ], + }, + cases: [ + [{amount: "12.50", qty: "2"}, {total: 25}], + [{amount: " 1 ", qty: "0.5"}, {total: 0.5}], + [{amount: 3, qty: "1e1"}, {total: 30}], + [{amount: "abc", qty: "1"}, "!error"], + [{amount: "", qty: "1"}, "!error"], + [{qty: "1"}, "!error"], + ], +} + +{ + name: "number() over a boolean and over numbers", + graph: {nodes: [{expression: "calc", fields: {n: "number(v)"}}]}, + cases: [ + [{v: true}, {n: 1}], + [{v: false}, {n: 0}], + [{v: 2.50}, {n: 2.5}], + [{v: "-0.1"}, {n: -0.1}], + ], +} + +{ + name: "string() renders numbers with their scale", + graph: { + nodes: [ + {expression: "calc", fields: {a: "x * 2", b: "x + 0.10"}}, + {expression: "text", fields: {a: "string(a)", b: "string(b)"}}, + ], + }, + cases: [ + [{x: 1}, {a: "2", b: "1.10"}], + [{x: 1.5}, {a: "3.0", b: "1.60"}], + [{x: 0}, {a: "0", b: "0.10"}], + [{x: -0.25}, {a: "-0.50", b: "-0.15"}], + ], +} + +{ + name: "string() of booleans, null and dates", + graph: {nodes: [{expression: "calc", fields: {b: "string(flag)", n: "string(missing)", d: "string(d(day))"}}]}, + cases: [ + [{flag: true, day: "2024-01-01"}, {b: "true", n: "null", d: "2024-01-01T00:00:00Z"}], + [{flag: false, day: "2023-06-15T12:30:00Z"}, {b: "false", n: "null", d: "2023-06-15T12:30:00Z"}], + ], +} + +{ + name: "string() of an array or object fails", + graph: {nodes: [{expression: "calc", fields: {s: "string(v)"}}]}, + cases: [ + [{v: 1}, {s: "1"}], + [{v: [1]}, "!error"], + [{v: {a: 1}}, "!error"], + ], +} + +{ + name: "a string round trip through number() and string()", + graph: { + nodes: [ + {expression: "toNum", fields: {n: "number(s)"}}, + {expression: "toStr", fields: {s: "string(n)", same: "string(n) == $nodes.input.s"}}, + ], + }, + cases: [ + [{s: "42"}, {s: "42", same: true}], + [{s: "1.50"}, {s: "1.50", same: true}], + [{s: " 7 "}, {s: "7", same: false}], + [{s: "1e3"}, {s: "1000", same: false}], + ], +} + +{ + name: "bool() over numbers and booleans from upstream", + graph: { + nodes: [ + {expression: "src", fields: {n: "count(xs, # > 0)"}}, + {expression: "conv", fields: {any: "bool(n)", neg: "bool(n - n)"}}, + ], + }, + cases: [ + [{xs: [1, 2]}, {any: true, neg: false}], + [{xs: [-1]}, {any: false, neg: false}], + [{xs: []}, {any: false, neg: false}], + ], +} + +{ + name: "bool() over request strings", + graph: {nodes: [{expression: "calc", fields: {b: "bool(s)"}}]}, + cases: [ + [{s: "true"}, {b: true}], + [{s: "false"}, {b: false}], + [{s: " true "}, {b: true}], + [{}, {b: false}], + [{s: "yes"}, {b: true}, "bug: non-empty strings other than true/false convert to false (inverted is_empty, see expression spec)"], + [{s: ""}, {b: false}, "bug: the empty string converts to true (inverted is_empty, see expression spec)"], + ], +} + +{ + name: "a converted value feeds a table input", + graph: { + nodes: [ + {expression: "parse", fields: {age: "number(age)"}}, + {table: "t", inputs: ["age"], outputs: ["group"], rules: [ + ["< 18", "'minor'"], + ["[18..64]", "'adult'"], + ["", "'senior'"], + ]}, + ], + }, + cases: [ + [{age: "17"}, {group: "minor"}], + [{age: "18"}, {group: "adult"}], + [{age: "64.5"}, {group: "senior"}], + [{age: 30}, {group: "adult"}], + ], +} + +{ + name: "a string-typed number does not match a numeric table cell", + graph: { + nodes: [ + {table: "t", inputs: ["age"], outputs: ["group"], rules: [ + ["< 18", "'minor'"], + ["'30'", "'string thirty'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{age: 10}, {group: "minor"}], + [{age: "30"}, {group: "string thirty"}], + [{age: 30}, {group: "other"}], + ], +} + +{ + name: "isNumeric guards a conversion", + graph: {nodes: [{expression: "calc", fields: {n: "isNumeric(v) ? number(v) : 0"}}]}, + cases: [ + [{v: "12"}, {n: 12}], + [{v: "x"}, {n: 0}], + [{v: 5}, {n: 5}], + [{v: ""}, {n: 0}], + ], +} + +// --------------------------------------------------------------------------- +// Formatting numbers into text. +{ + name: "rounded amounts rendered with a currency", + graph: { + nodes: [ + {expression: "calc", fields: {gross: "round(net * 1.19, 2)"}}, + {expression: "text", fields: {label: "`${gross} EUR`", plain: "string(gross)"}}, + ], + }, + cases: [ + [{net: 10}, {label: "11.90 EUR", plain: "11.90"}], + [{net: 1}, {label: "1.19 EUR", plain: "1.19"}], + [{net: 0.01}, {label: "0.01 EUR", plain: "0.01"}], + [{net: 100}, {label: "119.00 EUR", plain: "119.00"}], + ], +} + +{ + name: "percentages rendered from a ratio", + graph: {nodes: [{expression: "calc", fields: {pct: "`${round(part / total * 100, 1)}%`"}}]}, + cases: [ + [{part: 1, total: 3}, {pct: "33.3%"}], + [{part: 1, total: 2}, {pct: "50.0%"}], + [{part: 0, total: 5}, {pct: "0%"}], + [{part: 2, total: 3}, {pct: "66.7%"}], + ], +} + +{ + name: "integers from floor, ceil and trunc rendered as text", + graph: {nodes: [{expression: "calc", fields: {f: "string(floor(v))", c: "string(ceil(v))", t: "`${trunc(v)}`"}}]}, + cases: [ + [{v: 1.5}, {f: "1", c: "2", t: "1"}], + [{v: -1.5}, {f: "-2", c: "-1", t: "-1"}], + [{v: 3}, {f: "3", c: "3", t: "3"}], + ], +} + +// --------------------------------------------------------------------------- +// Formatting dates into text. +{ + name: "a date formatted in several patterns", + graph: {nodes: [{expression: "calc", fields: { + iso: "d(day).format('%Y-%m-%d')", + eu: "d(day).format('%d.%m.%Y')", + month: "d(day).format('%B %Y')", + time: "d(day).format('%H:%M')", + }}]}, + cases: [ + [{day: "2024-03-05T14:07:00Z"}, {iso: "2024-03-05", eu: "05.03.2024", month: "March 2024", time: "14:07"}], + [{day: "2023-12-31"}, {iso: "2023-12-31", eu: "31.12.2023", month: "December 2023", time: "00:00"}], + [{day: date('2020-02-29')}, {iso: "2020-02-29", eu: "29.02.2020", month: "February 2020", time: "00:00"}], + ], +} + +{ + name: "a date computed upstream formatted downstream", + graph: { + nodes: [ + {expression: "calc", fields: {due: "d(issued).add(days, 'd')"}}, + {expression: "text", fields: {msg: "`due on ${due.format('%Y-%m-%d')}`", raw: "`${due}`"}}, + ], + }, + cases: [ + [{issued: "2024-01-30", days: 2}, {msg: "due on 2024-02-01", raw: "2024-02-01T00:00:00Z"}], + [{issued: "2024-02-28", days: 1}, {msg: "due on 2024-02-29", raw: "2024-02-29T00:00:00Z"}], + [{issued: "2023-12-31", days: 0}, {msg: "due on 2023-12-31", raw: "2023-12-31T00:00:00Z"}], + ], +} + +{ + name: "the fixed evaluation time formatted", + graph: {nodes: [{expression: "calc", fields: {today: "d().format('%Y-%m-%d')", stamp: "`${d()}`"}}]}, + cases: [ + [{}, {today: "2025-03-20", stamp: "2025-03-20T10:15:30Z"}], + ], +} + +{ + name: "date parts concatenated into text", + graph: {nodes: [{expression: "calc", fields: {label: "`Q${d(day).quarter()} ${d(day).year()}`", dow: "d(day).format('%A')"}}]}, + cases: [ + [{day: "2024-01-15"}, {label: "Q1 2024", dow: "Monday"}], + [{day: "2024-11-30"}, {label: "Q4 2024", dow: "Saturday"}], + ], +} + +{ + name: "an invalid date string formatted", + graph: {nodes: [{expression: "calc", fields: {s: "d(day).format('%Y')"}}]}, + cases: [ + [{day: "2024-01-01"}, {s: "2024"}], + [{day: "not a date"}, {s: "Invalid date"}, "question: an invalid date formats to the text 'Invalid date' instead of failing (see 21-values)"], + ], +} + +{ + name: "a formatted date compared as text in a table", + graph: { + nodes: [ + {expression: "calc", fields: {month: "d(day).format('%m')"}}, + {table: "season", inputs: ["month"], outputs: ["season"], rules: [ + ["'12', '01', '02'", "'winter'"], + ["'06', '07', '08'", "'summer'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{day: "2024-01-10"}, {season: "winter"}], + [{day: "2024-07-04"}, {season: "summer"}], + [{day: "2024-04-01"}, {season: "other"}], + [{day: "2023-12-25T23:00:00Z"}, {season: "winter"}], + ], +} diff --git a/core/engine/tests/spec/graph/35-loops-nested.json5 b/core/engine/tests/spec/graph/35-loops-nested.json5 new file mode 100644 index 00000000..cda70393 --- /dev/null +++ b/core/engine/tests/spec/graph/35-loops-nested.json5 @@ -0,0 +1,573 @@ +// Nested loops: loops inside sub-decisions inside loops, loops over arrays of arrays, loop items +// carrying nested objects, and loops whose result arrays feed later loops. Chapter 13 covers +// the single-level basics; this chapter pins down how loop results compose. + +// --- Arrays of arrays: the item is itself an array ---------------------------------------------- +// An array item is the whole environment of the body; it is read through `$root`. +{ + name: "loop over a matrix computes per-row aggregates", + graph: { + nodes: [{expression: "rows", inputField: "matrix", outputPath: "rows", executionMode: "loop", fields: { + sum: "sum($root)", + max: "max($root)", + first: "$root[0]", + n: "len($root)", + }}], + }, + cases: [ + [{matrix: [[1, 2, 3], [4, 5, 6]]}, {rows: [{sum: 6, max: 3, first: 1, n: 3}, {sum: 15, max: 6, first: 4, n: 3}]}], + [{matrix: [[10], [0.5, 0.25]]}, {rows: [{sum: 10, max: 10, first: 10, n: 1}, {sum: 0.75, max: 0.5, first: 0.5, n: 2}]}], + [{matrix: [[-1, -2]]}, {rows: [{sum: -3, max: -1, first: -1, n: 2}]}], + [{matrix: []}, {rows: []}], + ], +} + +{ + name: "empty inner arrays and null rows in a matrix loop", + graph: { + nodes: [{expression: "rows", inputField: "matrix", outputPath: "rows", executionMode: "loop", fields: { + n: "len($root ?? [])", + empty: "len($root ?? []) == 0", + }}], + }, + cases: [ + [{matrix: [[], [1], null]}, {rows: [{n: 0, empty: true}, {n: 1, empty: false}, {n: 0, empty: true}]}], + [{matrix: [[], []]}, {rows: [{n: 0, empty: true}, {n: 0, empty: true}]}], + [{matrix: [null]}, {rows: [{n: 0, empty: true}]}], + ], +} + +{ + name: "loop over arrays of arrays of objects", + graph: { + nodes: [{expression: "groups", inputField: "groups", outputPath: "out", executionMode: "loop", fields: { + names: "map($root, #.name)", + total: "sum(map($root, #.v))", + }}], + }, + cases: [ + [{groups: [[{name: "a", v: 1}, {name: "b", v: 2}], [{name: "c", v: 3}]]}, {out: [{names: ["a", "b"], total: 3}, {names: ["c"], total: 3}]}], + [{groups: [[]]}, {out: [{names: [], total: 0}]}], + [{groups: [[{name: "x", v: 0.1}, {name: "y", v: 0.2}]]}, {out: [{names: ["x", "y"], total: 0.3}]}], + ], +} + +{ + name: "inputField selects an inner array of a matrix", + graph: { + nodes: [{expression: "cells", inputField: "matrix[1]", outputPath: "cells", executionMode: "loop", fields: {sq: "$root * $root"}}], + }, + cases: [ + [{matrix: [[1], [2, 3]]}, {cells: [{sq: 4}, {sq: 9}]}], + [{matrix: [[1], []]}, {cells: []}], + [{matrix: [[1]]}, "!error"], + [{matrix: [[1], 5]}, "!error"], + ], +} + +{ + name: "inputField flattens a matrix before looping", + graph: { + nodes: [{expression: "cells", inputField: "flatten(matrix)", outputPath: "cells", executionMode: "loop", fields: {v: "$root + 1"}}], + }, + cases: [ + [{matrix: [[1, 2], [3]]}, {cells: [{v: 2}, {v: 3}, {v: 4}]}], + [{matrix: [[], [7]]}, {cells: [{v: 8}]}], + [{matrix: []}, {cells: []}], + ], +} + +// --- Arrays of arrays through sub-decisions --------------------------------------------------- +// A row (an array) is handed to a child whose loop has no inputField, so the child loops over its +// own input. Arrays survive graph-edge merging, so the child's loop node receives the row. +{ + name: "child loops over its array input without inputField", + decisions: { + row: {nodes: [{expression: "cell", executionMode: "loop", fields: {v: "$root * 10"}}]}, + }, + graph: { + nodes: [{decision: "rows", key: "row", inputField: "matrix", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{matrix: [[1, 2], [3]]}, {out: [[{v: 10}, {v: 20}], [{v: 30}]]}], + [{matrix: [[]]}, {out: [[]]}], + [{matrix: []}, {out: []}], + [{matrix: [[0.5], [], [-1]]}, {out: [[{v: 5}], [], [{v: -10}]]}], + ], +} + +{ + name: "child over a matrix row with outputPath builds objects of arrays", + decisions: { + row: {nodes: [{expression: "cell", executionMode: "loop", outputPath: "cells", fields: {v: "$root"}}]}, + }, + graph: { + nodes: [{decision: "rows", key: "row", inputField: "matrix", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{matrix: [[1, 2], [3]]}, {out: [{cells: [{v: 1}, {v: 2}]}, {cells: [{v: 3}]}]}], + [{matrix: [[]]}, {out: [{cells: []}]}], + ], +} + +{ + name: "child receiving a non-array row fails the outer loop", + decisions: { + row: {nodes: [{expression: "cell", executionMode: "loop", fields: {v: "$root"}}]}, + }, + graph: { + nodes: [{decision: "rows", key: "row", inputField: "matrix", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{matrix: [[1]]}, {out: [[{v: 1}]]}], + [{matrix: [[1], {a: 1}]}, "!error"], + [{matrix: [[1], null]}, "!error"], + [{matrix: [[1], 2]}, "!error"], + ], +} + +// --- Loops in sub-decisions in loops --------------------------------------------------------- +// The outer loop runs the child once per item; the child's own loop iterates the item's array. +{ + name: "invoice lines priced inside a per-invoice child", + decisions: { + invoice: {nodes: [ + {expression: "lines", inputField: "lines", outputPath: "lines", executionMode: "loop", passThrough: true, fields: {total: "price * qty"}}, + {expression: "totals", passThrough: true, fields: {subtotal: "sum(map(lines, #.total))", count: "len(lines)"}}, + ]}, + }, + graph: { + nodes: [{decision: "invoices", key: "invoice", inputField: "invoices", outputPath: "invoices", executionMode: "loop"}], + }, + cases: [ + [ + {invoices: [{id: 1, lines: [{price: 2, qty: 2}, {price: 1, qty: 1}]}, {id: 2, lines: []}]}, + {invoices: [ + {id: 1, lines: [{price: 2, qty: 2, total: 4}, {price: 1, qty: 1, total: 1}], subtotal: 5, count: 2}, + {id: 2, lines: [], subtotal: 0, count: 0}, + ]}, + ], + [{invoices: []}, {invoices: []}], + [ + {invoices: [{id: 3, lines: [{price: 0.1, qty: 3}]}]}, + {invoices: [{id: 3, lines: [{price: 0.1, qty: 3, total: 0.3}], subtotal: 0.3, count: 1}]}, + ], + ], +} + +{ + name: "child inner loop error fails the whole outer loop", + decisions: { + invoice: {nodes: [ + {expression: "lines", inputField: "lines", outputPath: "lines", executionMode: "loop", fields: {total: "price * qty"}}, + ]}, + }, + graph: { + nodes: [{decision: "invoices", key: "invoice", inputField: "invoices", outputPath: "invoices", executionMode: "loop"}], + }, + cases: [ + [{invoices: [{lines: [{price: 1, qty: 2}]}]}, {invoices: [{lines: [{total: 2}]}]}], + [{invoices: [{lines: [{price: 1, qty: 2}]}, {lines: [{price: "x", qty: 1}]}]}, "!error"], + [{invoices: [{lines: [{price: 1, qty: 2}]}, {}]}, "!error"], + [{invoices: [{lines: null}]}, "!error"], + ], +} + +{ + name: "child guards its inner loop with a switch", + decisions: { + invoice: { + nodes: [ + {switch: "has", when: ["len(lines ?? []) > 0", ""]}, + {expression: "lines", inputField: "lines", outputPath: "lines", executionMode: "loop", fields: {total: "price * qty"}}, + {expression: "none", fields: {lines: "[]", empty: "true"}}, + ], + edges: ["input -> has", "has:0 -> lines -> output", "has:1 -> none -> output"], + }, + }, + graph: { + nodes: [{decision: "invoices", key: "invoice", inputField: "invoices", outputPath: "invoices", executionMode: "loop"}], + }, + cases: [ + [{invoices: [{lines: [{price: 2, qty: 1}]}, {}, {lines: null}, {lines: []}]}, {invoices: [{lines: [{total: 2}]}, {lines: [], empty: true}, {lines: [], empty: true}, {lines: [], empty: true}]}], + [{invoices: [{}]}, {invoices: [{lines: [], empty: true}]}], + [{invoices: [{lines: [{price: 3, qty: 3}, {price: 1, qty: 0}]}]}, {invoices: [{lines: [{total: 9}, {total: 0}]}]}], + ], +} + +{ + name: "child runs a loop table on each outer item", + decisions: { + basket: {nodes: [ + {table: "vat", inputField: "items", outputPath: "rates", executionMode: "loop", inputs: ["kind"], outputs: ["rate"], rules: [ + ["'food'", "0.05"], + ["", "0.2"], + ]}, + ]}, + }, + graph: { + nodes: [{decision: "baskets", key: "basket", inputField: "baskets", outputPath: "baskets", executionMode: "loop"}], + }, + cases: [ + [{baskets: [{items: [{kind: "food"}, {kind: "tv"}]}, {items: [{kind: "food"}]}]}, {baskets: [{rates: [{rate: 0.05}, {rate: 0.2}]}, {rates: [{rate: 0.05}]}]}], + [{baskets: [{items: []}]}, {baskets: [{rates: []}]}], + [{baskets: []}, {baskets: []}], + ], +} + +{ + name: "three levels: loop, child loop, grandchild loop", + decisions: { + leaf: {nodes: [{expression: "e", fields: {v: "n + 1"}}]}, + mid: {nodes: [{decision: "leaves", key: "leaf", inputField: "leaves", outputPath: "leaves", executionMode: "loop"}]}, + top: {nodes: [{decision: "mids", key: "mid", inputField: "mids", outputPath: "mids", executionMode: "loop"}]}, + }, + graph: { + nodes: [{decision: "tops", key: "top", inputField: "tops", outputPath: "tops", executionMode: "loop"}], + }, + cases: [ + [ + {tops: [{mids: [{leaves: [{n: 1}, {n: 2}]}, {leaves: []}]}, {mids: []}]}, + {tops: [{mids: [{leaves: [{v: 2}, {v: 3}]}, {leaves: []}]}, {mids: []}]}, + ], + [{tops: [{mids: [{leaves: [{n: 0}]}]}]}, {tops: [{mids: [{leaves: [{v: 1}]}]}]}], + [{tops: []}, {tops: []}], + [{tops: [{mids: [{leaves: [{n: "a"}]}]}]}, "!error"], + ], +} + +{ + name: "outer loop count times inner loop count runs the leaf", + decisions: { + cell: {nodes: [{expression: "e", fields: {id: "string(r) + ':' + string(c)"}}]}, + row: {nodes: [{decision: "cells", key: "cell", inputField: "map(cols, {r: r, c: #})", outputPath: "cells", executionMode: "loop"}]}, + }, + graph: { + nodes: [{decision: "rows", key: "row", inputField: "map(rows, {r: #, cols: cols})", outputPath: "grid", executionMode: "loop"}], + }, + cases: [ + [{rows: [1, 2], cols: ["a", "b"]}, {grid: [{cells: [{id: "1:a"}, {id: "1:b"}]}, {cells: [{id: "2:a"}, {id: "2:b"}]}]}], + [{rows: [1], cols: []}, {grid: [{cells: []}]}], + [{rows: [], cols: ["a"]}, {grid: []}], + ], +} + +{ + name: "child $nodes inside a loop sees only the child's nodes", + decisions: { + child: {nodes: [ + {expression: "base", fields: {k: "v * 2"}}, + {expression: "read", fields: {fromBase: "$nodes.base.k", parentVisible: "$nodes.parentCfg != null"}}, + ]}, + }, + graph: { + nodes: [ + {expression: "parentCfg", passThrough: true, fields: {factor: "3"}}, + {decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {out: [{fromBase: 2, parentVisible: false}, {fromBase: 4, parentVisible: false}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "child input node echoes the current item through $nodes", + decisions: { + child: {nodes: [{expression: "e", fields: {same: "$nodes.input.v == v", v: "$nodes.input.v"}}]}, + }, + graph: { + nodes: [{decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}, {v: 3}]}, {out: [{same: true, v: 1}, {same: true, v: 2}, {same: true, v: 3}]}], + [{items: [{v: "a"}]}, {out: [{same: true, v: "a"}]}], + ], +} + +// --- Items carrying nested objects -------------------------------------------------------------- +// Item fields are read by dotted paths; results can write nested keys; passThrough deep-merges. +{ + name: "loop reads deep paths of each item", + graph: { + nodes: [{expression: "each", inputField: "customers", outputPath: "out", executionMode: "loop", fields: { + city: "address.city", + zip: "address.geo.zip ?? 'n/a'", + vip: "profile.tier == 'gold'", + }}], + }, + cases: [ + [ + {customers: [{address: {city: "Oslo", geo: {zip: "0150"}}, profile: {tier: "gold"}}, {address: {city: "Bergen"}, profile: {tier: "silver"}}]}, + {out: [{city: "Oslo", zip: "0150", vip: true}, {city: "Bergen", zip: "n/a", vip: false}]}, + ], + [{customers: [{}]}, {out: [{city: null, zip: "n/a", vip: false}]}], + [{customers: [{address: null, profile: null}]}, {out: [{city: null, zip: "n/a", vip: false}]}], + ], +} + +{ + name: "loop writes nested result keys per item", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: { + "price.net": "net", + "price.gross": "net * 1.2", + "meta.source.kind": "'calc'", + }}], + }, + cases: [ + [{items: [{net: 10}, {net: 0}]}, {out: [{price: {net: 10, gross: 12}, meta: {source: {kind: "calc"}}}, {price: {net: 0, gross: 0}, meta: {source: {kind: "calc"}}}]}], + [{items: [{net: 2.5}]}, {out: [{price: {net: 2.5, gross: 3}, meta: {source: {kind: "calc"}}}]}], + ], +} + +{ + name: "loop passThrough deep-merges nested item objects with results", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: { + "price.gross": "price.net * 2", + "flags.checked": "true", + }}], + }, + cases: [ + [ + {items: [{id: 1, price: {net: 5, currency: "EUR"}, flags: {hot: true}}]}, + {items: [{id: 1, price: {net: 5, currency: "EUR", gross: 10}, flags: {hot: true, checked: true}}]}, + ], + [ + {items: [{id: 2, price: {net: 1}}, {id: 3, price: {net: 0}, flags: null}]}, + {items: [{id: 2, price: {net: 1, gross: 2}, flags: {checked: true}}, {id: 3, price: {net: 0, gross: 0}, flags: {checked: true}}]}, + ], + ], +} + +{ + name: "loop results carry arrays of nested objects", + graph: { + nodes: [{expression: "each", inputField: "orders", outputPath: "out", executionMode: "loop", fields: { + skus: "map(lines, #.product.sku)", + heavy: "filter(lines, #.product.weight > 10)", + }}], + }, + cases: [ + [ + {orders: [{lines: [{product: {sku: "a", weight: 20}}, {product: {sku: "b", weight: 1}}]}]}, + {out: [{skus: ["a", "b"], heavy: [{product: {sku: "a", weight: 20}}]}]}, + ], + [{orders: [{lines: []}, {lines: [{product: {sku: "c", weight: 11}}]}]}, {out: [{skus: [], heavy: []}, {skus: ["c"], heavy: [{product: {sku: "c", weight: 11}}]}]}], + ], +} + +{ + name: "loop over nested objects via an inner field of each item", + graph: { + nodes: [{expression: "each", inputField: "map(orders, #.customer)", outputPath: "customers", executionMode: "loop", fields: {name: "upper(name)"}}], + }, + cases: [ + [{orders: [{customer: {name: "ann"}}, {customer: {name: "bo"}}]}, {customers: [{name: "ANN"}, {name: "BO"}]}], + [{orders: [{customer: {}}]}, "!error", "question: upper(null) is an expression error, so a missing nested field fails the whole loop"], + [{orders: []}, {customers: []}], + ], +} + +{ + name: "item with a nested array processed by a child loop keeps sibling fields with passThrough", + decisions: { + order: {nodes: [{expression: "lines", inputField: "lines", outputPath: "lines", executionMode: "loop", passThrough: true, fields: {ok: "qty > 0"}}]}, + }, + graph: { + nodes: [{decision: "orders", key: "order", inputField: "orders", outputPath: "orders", executionMode: "loop", passThrough: true}], + }, + cases: [ + [ + {batch: "b1", orders: [{id: 1, customer: {name: "ann"}, lines: [{qty: 1}, {qty: 0}]}]}, + {batch: "b1", orders: [{id: 1, customer: {name: "ann"}, lines: [{qty: 1, ok: true}, {qty: 0, ok: false}]}]}, + ], + [{batch: "b2", orders: [{id: 2, lines: []}]}, {batch: "b2", orders: [{id: 2, lines: []}]}], + ], +} + +{ + name: "null results remove item keys under passThrough", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {note: "null", kept: "true"}}], + }, + cases: [ + [{items: [{note: "x", a: 1}]}, {items: [{a: 1, kept: true}]}, "question: passThrough merges the item with its result, and a null result field deletes the item's key instead of setting it to null"], + [{items: [{a: 2}]}, {items: [{a: 2, kept: true}]}], + ], +} + +// --- Loops producing arrays consumed by later loops ----------------------------------------------- +{ + name: "three chained loops each read the previous stage", + graph: { + nodes: [ + {expression: "s1", inputField: "items", outputPath: "s1", executionMode: "loop", fields: {v: "x * 2"}}, + {expression: "s2", inputField: "s1", outputPath: "s2", executionMode: "loop", fields: {v: "v + 1"}}, + {expression: "s3", inputField: "s2", outputPath: "s3", executionMode: "loop", fields: {v: "v * v"}}, + ], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {s3: [{v: 9}, {v: 25}]}], + [{items: [{x: 0}]}, {s3: [{v: 1}]}], + [{items: []}, {s3: []}], + ], +} + +{ + name: "chained loops with passThrough accumulate every stage", + graph: { + nodes: [ + {expression: "s1", inputField: "items", outputPath: "s1", executionMode: "loop", passThrough: true, fields: {v: "x * 2"}}, + {expression: "s2", inputField: "s1", outputPath: "s2", executionMode: "loop", passThrough: true, fields: {w: "v + 1"}}, + ], + }, + cases: [ + [{items: [{x: 1}]}, {items: [{x: 1}], s1: [{x: 1, v: 2}], s2: [{x: 1, v: 2, w: 3}]}], + [{items: []}, {items: [], s1: [], s2: []}], + [{items: [{x: 1}, {x: -1}]}, {items: [{x: 1}, {x: -1}], s1: [{x: 1, v: 2}, {x: -1, v: -2}], s2: [{x: 1, v: 2, w: 3}, {x: -1, v: -2, w: -1}]}], + ], +} + +{ + name: "second loop filters the first loop's results", + graph: { + nodes: [ + {expression: "score", inputField: "items", outputPath: "scored", executionMode: "loop", passThrough: true, fields: {score: "a + b"}}, + {expression: "pick", inputField: "filter(scored, #.score >= 10)", outputPath: "picked", executionMode: "loop", fields: {id: "id", score: "score"}}, + ], + }, + cases: [ + [{items: [{id: 1, a: 5, b: 5}, {id: 2, a: 1, b: 1}, {id: 3, a: 20, b: 0}]}, {picked: [{id: 1, score: 10}, {id: 3, score: 20}]}], + [{items: [{id: 1, a: 0, b: 0}]}, {picked: []}], + [{items: [{id: 7, a: 9.5, b: 0.5}]}, {picked: [{id: 7, score: 10}]}], + ], +} + +{ + name: "a loop producing scalar arrays feeds a loop over scalars", + graph: { + nodes: [ + {expression: "s1", inputField: "items", outputPath: "s1", executionMode: "loop", fields: {v: "x"}}, + {expression: "s2", inputField: "map(s1, #.v)", outputPath: "s2", executionMode: "loop", fields: {d: "$root * 2"}}, + ], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {s2: [{d: 2}, {d: 4}]}], + [{items: []}, {s2: []}], + [{items: [{x: 1}, {}]}, "!error", "question: the second item's v is null; null * 2 is an expression error, so the second loop fails"], + ], +} + +{ + name: "a loop producing nested arrays feeds a flattening loop", + graph: { + nodes: [ + {expression: "split", inputField: "orders", outputPath: "parts", executionMode: "loop", fields: {lines: "map(lines, {sku: #, order: id})"}}, + {expression: "flat", inputField: "flatten(map(parts, #.lines))", outputPath: "flat", executionMode: "loop", fields: {key: "string(order) + '/' + sku"}}, + ], + }, + cases: [ + [{orders: [{id: 1, lines: ["a", "b"]}, {id: 2, lines: ["c"]}]}, {flat: [{key: "1/a"}, {key: "1/b"}, {key: "2/c"}]}], + [{orders: [{id: 1, lines: []}]}, {flat: []}], + [{orders: []}, {flat: []}], + ], +} + +{ + name: "a loop over the previous loop's node output via $nodes", + graph: { + nodes: [ + {expression: "first", inputField: "items", executionMode: "loop", fields: {v: "x + 1"}}, + {expression: "second", inputField: "$nodes.first", outputPath: "out", executionMode: "loop", fields: {w: "v * 10"}}, + ], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {out: [{w: 20}, {w: 30}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "a loop without outputPath feeds a loop without inputField", + graph: { + nodes: [ + {expression: "first", inputField: "items", executionMode: "loop", fields: {v: "x + 1"}}, + {expression: "second", executionMode: "loop", fields: {w: "v * 2"}}, + ], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, [{w: 4}, {w: 6}]], + [{items: []}, []], + [{items: [{x: 0}]}, [{w: 2}]], + ], +} + +{ + name: "a sub-decision loop result consumed by an expression loop", + decisions: { + price: {nodes: [{expression: "p", fields: {total: "price * qty", sku: "sku"}}]}, + }, + graph: { + nodes: [ + {decision: "priced", key: "price", inputField: "lines", outputPath: "priced", executionMode: "loop"}, + {expression: "labels", inputField: "priced", outputPath: "labels", executionMode: "loop", fields: {label: "sku + '=' + string(total)"}}, + ], + }, + cases: [ + [{lines: [{sku: "a", price: 2, qty: 3}, {sku: "b", price: 1, qty: 1}]}, {labels: [{label: "a=6"}, {label: "b=1"}]}], + [{lines: []}, {labels: []}], + ], +} + +{ + name: "an expression loop result consumed by a sub-decision loop", + decisions: { + grade: {nodes: [{table: "g", inputs: ["avg"], outputs: ["grade"], rules: [[">= 80", "'A'"], [">= 50", "'B'"], ["", "'C'"]]}]}, + }, + graph: { + nodes: [ + {expression: "avgs", inputField: "students", outputPath: "avgs", executionMode: "loop", fields: {avg: "avg(scores)", name: "name"}}, + {decision: "grades", key: "grade", inputField: "avgs", outputPath: "grades", executionMode: "loop"}, + ], + }, + cases: [ + [{students: [{name: "a", scores: [90, 80]}, {name: "b", scores: [50, 60]}, {name: "c", scores: [10]}]}, {grades: [{grade: "A"}, {grade: "B"}, {grade: "C"}]}], + [{students: []}, {grades: []}], + ], +} + +{ + name: "a later loop indexes an earlier loop's result through $nodes", + graph: { + nodes: [ + {expression: "rates", inputField: "items", outputPath: "rates", executionMode: "loop", fields: {r: "kind == 'a' ? 0.1 : 0.2"}}, + {expression: "apply", inputField: "$nodes.input.items", outputPath: "out", executionMode: "loop", fields: {tax: "amount * $nodes.rates.rates[i].r"}}, + ], + }, + cases: [ + [{items: [{i: 0, kind: "a", amount: 100}, {i: 1, kind: "b", amount: 10}]}, {out: [{tax: 10}, {tax: 2}]}], + [{items: [{i: 1, kind: "a", amount: 100}, {i: 0, kind: "b", amount: 10}]}, {out: [{tax: 20}, {tax: 1}]}], + [{items: []}, {out: []}], + ], +} + +// --- Big nested loops --------------------------------------------------------------------------- +{ + name: "grid of 8 rows by 8 columns through a child", + decisions: { + row: {nodes: [{expression: "c", inputField: "map(cols, {r: r, c: #})", outputPath: "cells", executionMode: "loop", fields: {p: "r * c"}}]}, + }, + graph: { + nodes: [ + {decision: "rows", key: "row", inputField: "map([1..8], {r: #, cols: [1..8]})", outputPath: "rows", executionMode: "loop"}, + {expression: "agg", fields: {total: "sum(map(rows, sum(map(#.cells, #.p))))", n: "len(flatten(map(rows, #.cells)))", diag: "map(rows, #.cells[0].p)"}}, + ], + }, + cases: [ + [{}, {total: 1296, n: 64, diag: [1, 2, 3, 4, 5, 6, 7, 8]}], + [{ignored: true}, {total: 1296, n: 64, diag: [1, 2, 3, 4, 5, 6, 7, 8]}], + ], +} diff --git a/core/engine/tests/spec/graph/36-loops-tables.json5 b/core/engine/tests/spec/graph/36-loops-tables.json5 new file mode 100644 index 00000000..e3c854f4 --- /dev/null +++ b/core/engine/tests/spec/graph/36-loops-tables.json5 @@ -0,0 +1,712 @@ +// Decision tables in loop mode: the table is evaluated once per item of the selected array. A +// first-hit table yields the matched row's outputs per item (null when nothing matches), a +// collect table yields an array of matched rows per item. Chapter 13 covers the basics; this +// chapter covers outputPath/passThrough combinations, non-matching and incomplete items, large +// arrays and tables reading `$root`/`$nodes` inside a loop. + +// --- First hit: outputPath and passThrough ------------------------------------------------------ +{ + name: "first-hit loop without outputPath outputs the bare array", + graph: { + nodes: [{table: "t", inputField: "items", executionMode: "loop", inputs: ["v"], outputs: ["size"], rules: [ + ["> 100", "'large'"], + ["> 10", "'medium'"], + ["", "'small'"], + ]}], + }, + cases: [ + [{items: [{v: 500}, {v: 50}, {v: 5}]}, [{size: "large"}, {size: "medium"}, {size: "small"}]], + [{items: [{v: 11}]}, [{size: "medium"}]], + [{items: []}, []], + [{items: [{v: 100}, {v: 10}]}, [{size: "medium"}, {size: "small"}]], + ], +} + +{ + name: "first-hit loop with dotted outputs builds nested objects per item", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["v"], outputs: ["r.size", "r.code", "flag"], rules: [ + ["> 10", "'big'", "2", "true"], + ["", "'small'", "1", "false"], + ]}], + }, + cases: [ + [{items: [{v: 20}, {v: 1}]}, {out: [{r: {size: "big", code: 2}, flag: true}, {r: {size: "small", code: 1}, flag: false}]}], + [{items: [{v: 10}]}, {out: [{r: {size: "small", code: 1}, flag: false}]}], + ], +} + +{ + name: "first-hit loop with passThrough and no outputPath", + graph: { + nodes: [{table: "t", inputField: "items", executionMode: "loop", passThrough: true, inputs: ["v"], outputs: ["size"], rules: [ + ["> 10", "'big'"], + ["", "'small'"], + ]}], + }, + cases: [ + [{batch: 1, items: [{v: 20}, {v: 1}]}, [{v: 20, size: "big"}, {v: 1, size: "small"}], "question: the node input merged with the result array yields the array itself, the outer input is dropped (as for expression loops in chapter 13)"], + [{items: []}, [], "question: the node input merged with the result array yields the array itself, the outer input is dropped (as for expression loops in chapter 13)"], + ], +} + +{ + name: "first-hit loop with passThrough writes back over the source array", + graph: { + nodes: [{table: "t", inputField: "order.lines", outputPath: "order.lines", executionMode: "loop", passThrough: true, inputs: ["kind"], outputs: ["vat"], rules: [ + ["'food'", "0.05"], + ["", "0.2"], + ]}], + }, + cases: [ + [ + {order: {id: 9, lines: [{kind: "food", amt: 10}, {kind: "tv", amt: 100}]}}, + {order: {id: 9, lines: [{kind: "food", amt: 10, vat: 0.05}, {kind: "tv", amt: 100, vat: 0.2}]}}, + ], + [{order: {id: 1, lines: []}}, {order: {id: 1, lines: []}}], + [{order: {id: 2, lines: [{}]}, x: true}, {order: {id: 2, lines: [{vat: 0.2}]}, x: true}], + ], +} + +{ + name: "first-hit loop with passThrough to a sibling path keeps the source untouched", + graph: { + nodes: [{table: "t", inputField: "lines", outputPath: "rated", executionMode: "loop", passThrough: true, inputs: ["kind"], outputs: ["vat"], rules: [ + ["'food'", "0.05"], + ["", "0.2"], + ]}], + }, + cases: [ + [{lines: [{kind: "food"}]}, {lines: [{kind: "food"}], rated: [{kind: "food", vat: 0.05}]}], + [{lines: [{kind: "x", vat: 1}]}, {lines: [{kind: "x", vat: 1}], rated: [{kind: "x", vat: 0.2}]}], + [{lines: [], rated: "old"}, {lines: [], rated: []}], + ], +} + +{ + name: "table result overrides item fields of the same name under passThrough", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, inputs: ["status"], outputs: ["status", "meta.mapped"], rules: [ + ["'a'", "'active'", "true"], + ["", "status", "false"], + ]}], + }, + cases: [ + [{items: [{status: "a", meta: {id: 1}}, {status: "z"}]}, {items: [{status: "active", meta: {id: 1, mapped: true}}, {status: "z", meta: {mapped: false}}]}], + [{items: [{status: "a"}]}, {items: [{status: "active", meta: {mapped: true}}]}], + ], +} + +// --- Items failing to match ----------------------------------------------------------------------- +// A first-hit table that matches nothing outputs null for that item. +{ + name: "first-hit loop: non-matching items yield null without outputPath", + graph: { + nodes: [{table: "t", inputField: "items", executionMode: "loop", inputs: ["v"], outputs: ["ok"], rules: [ + ["> 0", "true"], + ]}], + }, + cases: [ + [{items: [{v: 1}, {v: -1}]}, [{ok: true}, null]], + [{items: [{v: -1}, {v: -2}]}, [null, null]], + [{items: [{v: 3}]}, [{ok: true}]], + ], +} + +{ + name: "first-hit loop with passThrough: a non-matching item stays as it was", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, inputs: ["v"], outputs: ["ok"], rules: [ + ["> 0", "true"], + ]}], + }, + cases: [ + [{items: [{v: 1}, {v: -1}]}, {items: [{v: 1, ok: true}, {v: -1}]}], + [{items: [{v: -5, ok: false}]}, {items: [{v: -5, ok: false}]}], + [{items: [{}]}, {items: [{}]}], + ], +} + +{ + name: "first-hit loop: all items failing yields an array of nulls under outputPath", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["kind"], outputs: ["r"], rules: [ + ["'a'", "1"], + ["'b'", "2"], + ]}], + }, + cases: [ + [{items: [{kind: "c"}, {kind: "d"}]}, {out: [null, null]}, "question: a non-matching first-hit table outputs null; in a loop the null lands in the result array (chapter 13)"], + [{items: [{kind: "a"}, {kind: "c"}, {kind: "b"}]}, {out: [{r: 1}, null, {r: 2}]}, "question: a non-matching first-hit table outputs null; in a loop the null lands in the result array (chapter 13)"], + [{items: [{kind: "b"}]}, {out: [{r: 2}]}], + ], +} + +{ + name: "downstream nodes count non-matching loop items", + graph: { + nodes: [ + {table: "t", inputField: "items", outputPath: "hits", executionMode: "loop", inputs: ["v"], outputs: ["v"], rules: [ + [">= 10", "v"], + ]}, + {expression: "agg", fields: {matched: "len(filter(hits, # != null))", missed: "len(filter(hits, # == null))", total: "sum(map(filter(hits, # != null), #.v))"}}, + ], + }, + cases: [ + [{items: [{v: 10}, {v: 1}, {v: 20}]}, {matched: 2, missed: 1, total: 30}], + [{items: [{v: 1}]}, {matched: 0, missed: 1, total: 0}], + [{items: []}, {matched: 0, missed: 0, total: 0}], + ], +} + +{ + name: "an output cell error skips the row for that item only", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: [""], outputs: ["r"], rules: [ + ["", "a + 1"], + ["", "'fallback'"], + ]}], + }, + cases: [ + [{items: [{a: 1}, {a: "x"}, {a: 2}]}, {out: [{r: 2}, {r: "fallback"}, {r: 3}]}], + [{items: [{a: "y"}]}, {out: [{r: "fallback"}]}], + ], +} + +// --- Collect hit policy in loops ---------------------------------------------------------------- +{ + name: "collect loop without outputPath outputs an array of arrays", + graph: { + nodes: [{table: "t", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["v"], outputs: ["tag"], rules: [ + ["> 0", "'pos'"], + ["> 100", "'huge'"], + ["== 0", "'zero'"], + ]}], + }, + cases: [ + [{items: [{v: 500}, {v: 0}, {v: -1}]}, [[{tag: "pos"}, {tag: "huge"}], [{tag: "zero"}], []]], + [{items: [{v: -1}, {v: -2}]}, [[], []]], + [{items: []}, []], + ], +} + +{ + name: "collect loop with passThrough replaces each item by its rows", + graph: { + nodes: [{table: "t", hit: "collect", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, inputs: ["v"], outputs: ["tag"], rules: [ + ["> 0", "'pos'"], + ["> 10", "'big'"], + ]}], + }, + cases: [ + [{id: 1, items: [{v: 20}, {v: -1}]}, {id: 1, items: [[{tag: "pos"}, {tag: "big"}], []]}, "question: passThrough merges each item with an array, and a top-level array replaces the item, so the item fields are lost"], + [{id: 2, items: []}, {id: 2, items: []}], + ], +} + +{ + name: "collect loop rows read item fields in output cells", + graph: { + nodes: [{table: "t", hit: "collect", inputField: "orders", outputPath: "alerts", executionMode: "loop", inputs: ["amount", "country"], outputs: ["code", "msg"], rules: [ + ["> 1000", "", "'AMT'", "'amount ' + string(amount)"], + ["", "'XX'", "'CTY'", "'country ' + country"], + ["> 1000", "'XX'", "'BOTH'", "id"], + ]}], + }, + cases: [ + [ + {orders: [{id: "o1", amount: 5000, country: "XX"}, {id: "o2", amount: 10, country: "DE"}, {id: "o3", amount: 2000, country: "DE"}]}, + {alerts: [ + [{code: "AMT", msg: "amount 5000"}, {code: "CTY", msg: "country XX"}, {code: "BOTH", msg: "o1"}], + [], + [{code: "AMT", msg: "amount 2000"}], + ]}, + ], + [{orders: [{id: "o4", amount: 1, country: "XX"}]}, {alerts: [[{code: "CTY", msg: "country XX"}]]}], + ], +} + +{ + name: "collect loop flattened downstream", + graph: { + nodes: [ + {table: "t", hit: "collect", inputField: "items", outputPath: "tags", executionMode: "loop", inputs: ["v"], outputs: ["tag"], rules: [ + ["> 0", "'pos'"], + ["> 10", "'big'"], + ["", "'seen'"], + ]}, + {expression: "agg", fields: {all: "map(flatten(tags), #.tag)", perItem: "map(tags, len(#))"}}, + ], + }, + cases: [ + [{items: [{v: 20}, {v: 1}, {v: -1}]}, {all: ["pos", "big", "seen", "pos", "seen", "seen"], perItem: [3, 2, 1]}], + [{items: []}, {all: [], perItem: []}], + ], +} + +{ + name: "first-hit loop with per-column collect outputs", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["v"], outputs: ["tier", "reasons[]"], rules: [ + ["> 100", "'gold'", "'over 100'"], + ["> 10", "'silver'", "'over 10'"], + ["> 0", "'bronze'", "'positive'"], + ]}], + }, + cases: [ + [{items: [{v: 500}, {v: 50}, {v: 5}]}, {out: [ + {tier: "gold", reasons: ["over 100", "over 10", "positive"]}, + {tier: "silver", reasons: ["over 10", "positive"]}, + {tier: "bronze", reasons: ["positive"]}, + ]}], + [{items: [{v: 0}, {v: 1}]}, {out: [{reasons: []}, {reasons: ["positive"], tier: "bronze"}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "per-column collect loop with passThrough keeps item fields", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, inputs: ["v"], outputs: ["flags[]"], rules: [ + ["> 0", "'pos'"], + ["> 10", "'big'"], + ]}], + }, + cases: [ + [{items: [{id: 1, v: 20}, {id: 2, v: -1}]}, {items: [{flags: ["pos", "big"], id: 1, v: 20}, {flags: [], id: 2, v: -1}]}], + [{items: [{id: 3, v: 5, flags: ["old"]}]}, {items: [{id: 3, v: 5, flags: ["pos"]}]}], + ], +} + +// --- Items with missing fields -------------------------------------------------------------------- +// A missing input field reads as null; null fails comparisons and matches only empty cells, +// `null` cells or null-aware tests. +{ + name: "missing input fields fall through to the catch-all row", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["age", "country"], outputs: ["r"], rules: [ + [">= 18", "'US'", "'us-adult'"], + [">= 18", "", "'adult'"], + ["", "'US'", "'us'"], + ["", "", "'other'"], + ]}], + }, + cases: [ + [{items: [{age: 20, country: "US"}, {age: 20}, {country: "US"}, {}]}, {out: [{r: "us-adult"}, {r: "adult"}, {r: "us"}, {r: "other"}]}], + [{items: [{age: null, country: null}]}, {out: [{r: "other"}]}], + [{items: [{age: "20", country: "US"}]}, {out: [{r: "us"}]}], + ], +} + +{ + name: "null-aware cells match missing fields per item", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["email"], outputs: ["state"], rules: [ + ["null", "'missing'"], + ["$ == ''", "'empty'"], + ["", "'present'"], + ]}], + }, + cases: [ + [{items: [{}, {email: null}, {email: ""}, {email: "a@b"}]}, {out: [{state: "missing"}, {state: "missing"}, {state: "empty"}, {state: "present"}]}], + [{items: [{email: "x"}]}, {out: [{state: "present"}]}], + ], +} + +{ + name: "nested input fields missing on some items", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["customer.address.country"], outputs: ["zone"], rules: [ + ["'NO', 'SE', 'DK'", "'nordic'"], + ["", "'world'"], + ]}], + }, + cases: [ + [{items: [{customer: {address: {country: "NO"}}}, {customer: {address: {}}}, {customer: {}}, {}, {customer: null}]}, {out: [{zone: "nordic"}, {zone: "world"}, {zone: "world"}, {zone: "world"}, {zone: "world"}]}], + [{items: [{customer: {address: {country: "SE"}}}]}, {out: [{zone: "nordic"}]}], + ], +} + +{ + name: "output cells reading missing fields produce null in the item result", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: [""], outputs: ["name", "label"], rules: [ + ["", "name", "name ?? 'anon'"], + ]}], + }, + cases: [ + [{items: [{name: "a"}, {}]}, {out: [{name: "a", label: "a"}, {name: null, label: "anon"}]}], + [{items: [{name: null}]}, {out: [{name: null, label: "anon"}]}], + ], +} + +{ + name: "items with wrong types fall through rather than erroring", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["n"], outputs: ["r"], rules: [ + ["> 5", "'big'"], + ["[1..5]", "'small'"], + ["", "'unknown'"], + ]}], + }, + cases: [ + [{items: [{n: 10}, {n: 3}, {n: "10"}, {n: true}, {n: [1]}, {n: {}}]}, {out: [{r: "big"}, {r: "small"}, {r: "unknown"}, {r: "unknown"}, {r: "unknown"}, {r: "unknown"}]}], + [{items: [{n: 5}, {n: 1}, {n: 0}]}, {out: [{r: "small"}, {r: "small"}, {r: "unknown"}]}], + ], +} + +{ + name: "scalar and null items against a field-reading table", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["v"], outputs: ["r"], rules: [ + ["> 0", "'pos'"], + ["", "'other'"], + ]}], + }, + cases: [ + [{items: [{v: 1}, null]}, {out: [{r: "pos"}, {r: "other"}]}], + [{items: [{v: 1}, 5, "s"]}, {out: [{r: "pos"}, {r: "other"}, {r: "other"}]}], + ], +} + +// --- `$root` in table loops ---------------------------------------------------------------------- +// In a loop the item is the table's whole environment, so `$root` is the item. +{ + name: "input column $root over string items", + graph: { + nodes: [{table: "t", inputField: "codes", outputPath: "out", executionMode: "loop", inputs: ["$root"], outputs: ["kind", "code"], rules: [ + ["startsWith($, 'A')", "'alpha'", "$root"], + ["'Z9'", "'zed'", "$root"], + ["", "'other'", "$root"], + ]}], + }, + cases: [ + [{codes: ["A1", "Z9", "B2"]}, {out: [{kind: "alpha", code: "A1"}, {kind: "zed", code: "Z9"}, {kind: "other", code: "B2"}]}], + [{codes: [""]}, {out: [{kind: "other", code: ""}]}], + ], +} + +{ + name: "expression-only input column reads $root of object items", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: [null], outputs: ["r"], rules: [ + ["$root.a > $root.b", "'a'"], + ["$root.a < $root.b", "'b'"], + ["", "'tie'"], + ]}], + }, + cases: [ + [{items: [{a: 2, b: 1}, {a: 1, b: 2}, {a: 1, b: 1}]}, {out: [{r: "a"}, {r: "b"}, {r: "tie"}]}], + [{items: [{a: 1}]}, {out: [{r: "tie"}]}], + ], +} + +{ + name: "output cells copy the whole item through $root", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["keep"], outputs: ["item"], rules: [ + ["true", "$root"], + ["", "null"], + ]}], + }, + cases: [ + {input: {items: [{keep: true, x: 1}, {keep: false, x: 2}]}, output: {out: [{item: {keep: true, x: 1}}, {item: null}]}, note: "bug: the input column's `$` reference is stored on the item environment, so $root read in an output cell carries a stray `$` key", engines: "the walker leaks the `$` reference into $root; the compiled engine gives the intended result"}, + {input: {items: [{keep: true}]}, output: {out: [{item: {keep: true}}]}, note: "bug: the input column's `$` reference is stored on the item environment, so $root read in an output cell carries a stray `$` key", engines: "the walker leaks the `$` reference into $root; the compiled engine gives the intended result"}, + ], +} + +{ + name: "single-mode sibling: output cells copy the node input through $root", + graph: { + nodes: [{table: "t", inputField: "item", outputPath: "out", inputs: ["keep"], outputs: ["item"], rules: [ + ["true", "$root"], + ["", "null"], + ]}], + }, + cases: [ + {input: {item: {keep: true, x: 1}}, output: {out: {item: {keep: true, x: 1}}}, note: "bug: the input column's `$` reference is stored on the environment, so $root read in an output cell carries a stray `$` key (not loop-specific)", engines: "the walker leaks the `$` reference into $root; the compiled engine gives the intended result"}, + [{item: {keep: false}}, {out: {item: null}}], + ], +} + +{ + name: "table loop over arrays of arrays reads rows via $root", + graph: { + nodes: [{table: "t", inputField: "rows", outputPath: "out", executionMode: "loop", inputs: ["len($root)"], outputs: ["shape", "head"], rules: [ + ["0", "'empty'", "null"], + ["1", "'single'", "$root[0]"], + ["", "'many'", "$root[0]"], + ]}], + }, + cases: [ + [{rows: [[], [7], [1, 2, 3]]}, {out: [{shape: "empty", head: null}, {shape: "single", head: 7}, {shape: "many", head: 1}]}], + [{rows: [["a", "b"]]}, {out: [{shape: "many", head: "a"}]}], + ], +} + +// --- `$nodes` in table loops --------------------------------------------------------------------- +// The outer input and earlier nodes stay reachable through `$nodes` from every item. +{ + name: "input column compares item fields with an outer threshold", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["v"], outputs: ["over"], rules: [ + ["> $nodes.input.limit", "true"], + ["", "false"], + ]}], + }, + cases: [ + [{limit: 10, items: [{v: 5}, {v: 15}, {v: 10}]}, {out: [{over: false}, {over: true}, {over: false}]}], + [{limit: 0, items: [{v: 1}]}, {out: [{over: true}]}], + [{items: [{v: 1}]}, {out: [{over: false}]}], + ], +} + +{ + name: "input column field is a $nodes path", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["$nodes.input.mode", "v"], outputs: ["r"], rules: [ + ["'strict'", "> 0", "'ok'"], + ["'strict'", "", "'reject'"], + ["", "", "'lenient'"], + ]}], + }, + cases: [ + [{mode: "strict", items: [{v: 1}, {v: 0}]}, {out: [{r: "ok"}, {r: "reject"}]}], + [{mode: "loose", items: [{v: 1}, {v: 0}]}, {out: [{r: "lenient"}, {r: "lenient"}]}], + [{items: [{v: 1}]}, {out: [{r: "lenient"}]}], + ], +} + +{ + name: "output cells combine the item with an earlier node", + graph: { + nodes: [ + {expression: "cfg", fields: {rate: "rate ?? 0.1", currency: "currency ?? 'EUR'"}}, + {table: "t", inputField: "$nodes.input.items", outputPath: "out", executionMode: "loop", inputs: ["taxable"], outputs: ["tax", "currency"], rules: [ + ["true", "amount * $nodes.cfg.rate", "$nodes.cfg.currency"], + ["", "0", "$nodes.cfg.currency"], + ]}, + ], + }, + cases: [ + [{rate: 0.2, items: [{taxable: true, amount: 100}, {taxable: false, amount: 50}]}, {out: [{tax: 20, currency: "EUR"}, {tax: 0, currency: "EUR"}]}], + [{currency: "NOK", items: [{taxable: true, amount: 10}]}, {out: [{tax: 1, currency: "NOK"}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "collect loop with $nodes conditions", + graph: { + nodes: [{table: "t", hit: "collect", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["tags"], outputs: ["hit"], rules: [ + ["contains($, $nodes.input.watch[0])", "$nodes.input.watch[0]"], + ["contains($, $nodes.input.watch[1])", "$nodes.input.watch[1]"], + ]}], + }, + cases: [ + [{watch: ["a", "b"], items: [{tags: ["a", "b"]}, {tags: ["b"]}, {tags: []}]}, {out: [[{hit: "a"}, {hit: "b"}], [{hit: "b"}], []]}], + [{watch: ["x", "y"], items: [{tags: ["a"]}]}, {out: [[]]}], + ], +} + +{ + name: "table loop reads the previous loop's results through $nodes", + graph: { + nodes: [ + {expression: "scores", inputField: "items", outputPath: "scores", executionMode: "loop", fields: {s: "a + b"}}, + {table: "t", inputField: "$nodes.scores.scores", outputPath: "grades", executionMode: "loop", inputs: ["s"], outputs: ["g"], rules: [ + [">= 10", "'high'"], + ["", "'low'"], + ]}, + ], + }, + cases: [ + [{items: [{a: 5, b: 5}, {a: 1, b: 1}]}, {grades: [{g: "high"}, {g: "low"}]}], + [{items: []}, {grades: []}], + ], +} + +// --- Tables in loops combined with other nodes ---------------------------------------------------- +{ + name: "an expression loop enriches items before a table loop", + graph: { + nodes: [ + {expression: "prep", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {total: "price * qty"}}, + {table: "t", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, inputs: ["total"], outputs: ["discount"], rules: [ + [">= 100", "0.1"], + ["", "0"], + ]}, + ], + }, + cases: [ + [{items: [{price: 50, qty: 2}, {price: 5, qty: 1}]}, {items: [{price: 50, qty: 2, total: 100, discount: 0.1}, {price: 5, qty: 1, total: 5, discount: 0}]}], + [{items: []}, {items: []}], + ], +} + +{ + name: "a table loop feeding a sub-decision loop", + decisions: { + label: {nodes: [{expression: "l", fields: {label: "upper(tier) + '-' + string(v)"}}]}, + }, + graph: { + nodes: [ + {table: "t", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, inputs: ["v"], outputs: ["tier"], rules: [ + ["> 10", "'hi'"], + ["", "'lo'"], + ]}, + {decision: "labels", key: "label", inputField: "items", outputPath: "labels", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{v: 20}, {v: 1}]}, {labels: [{label: "HI-20"}, {label: "LO-1"}]}], + [{items: []}, {labels: []}], + ], +} + +{ + name: "switch picks a single-mode or a loop-mode table", + graph: { + nodes: [ + {switch: "s", when: ["type(payload) == 'array'", ""]}, + {table: "many", inputField: "payload", outputPath: "out", executionMode: "loop", inputs: ["v"], outputs: ["r"], rules: [["> 0", "'pos'"], ["", "'neg'"]]}, + {table: "one", inputField: "payload", outputPath: "out", inputs: ["v"], outputs: ["r"], rules: [["> 0", "'pos'"], ["", "'neg'"]]}, + ], + edges: ["input -> s", "s:0 -> many -> output", "s:1 -> one -> output"], + }, + cases: [ + [{payload: [{v: 1}, {v: -1}]}, {out: [{r: "pos"}, {r: "neg"}]}], + [{payload: {v: 1}}, {out: {r: "pos"}}], + [{payload: {v: -1}}, {out: {r: "neg"}}], + [{payload: []}, {out: []}], + ], +} + +// --- Large arrays --------------------------------------------------------------------------------- +{ + name: "first-hit table over 60 generated items", + graph: { + nodes: [ + {table: "t", inputField: "map([1..60], {n: #})", outputPath: "rows", executionMode: "loop", inputs: ["n % 15", "n % 5", "n % 3"], outputs: ["k"], rules: [ + ["0", "", "", "'fizzbuzz'"], + ["", "0", "", "'buzz'"], + ["", "", "0", "'fizz'"], + ["", "", "", "'num'"], + ]}, + {expression: "agg", fields: { + n: "len(rows)", + fizzbuzz: "len(filter(rows, #.k == 'fizzbuzz'))", + buzz: "len(filter(rows, #.k == 'buzz'))", + fizz: "len(filter(rows, #.k == 'fizz'))", + num: "len(filter(rows, #.k == 'num'))", + first: "map(rows[0:4], #.k)", + }}, + ], + }, + cases: [ + [{}, {n: 60, fizzbuzz: 4, buzz: 8, fizz: 16, num: 32, first: ["num", "num", "fizz", "num", "buzz"]}], + [{noise: [1, 2]}, {n: 60, fizzbuzz: 4, buzz: 8, fizz: 16, num: 32, first: ["num", "num", "fizz", "num", "buzz"]}], + ], +} + +{ + name: "first-hit table with passThrough over 55 input items, some missing their score", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 75", "'B'"], + [">= 50", "'C'"], + ]}], + }, + cases: [ + [{items: [{id: 0, score: 11}, {id: 1, score: 48}, {id: 2, score: 85}, {id: 3, score: 21}, {id: 4, score: 58}, {id: 5, score: 95}, {id: 6, score: 31}, {id: 7, score: 68}, {id: 8, score: 4}, {id: 9, score: 41}, {id: 10, score: 78}, {id: 11, score: 14}, {id: 12}, {id: 13, score: 88}, {id: 14, score: 24}, {id: 15, score: 61}, {id: 16, score: 98}, {id: 17, score: 34}, {id: 18, score: 71}, {id: 19, score: 7}, {id: 20, score: 44}, {id: 21, score: 81}, {id: 22, score: 17}, {id: 23, score: 54}, {id: 24, score: 91}, {id: 25}, {id: 26, score: 64}, {id: 27, score: 0}, {id: 28, score: 37}, {id: 29, score: 74}, {id: 30, score: 10}, {id: 31, score: 47}, {id: 32, score: 84}, {id: 33, score: 20}, {id: 34, score: 57}, {id: 35, score: 94}, {id: 36, score: 30}, {id: 37, score: 67}, {id: 38}, {id: 39, score: 40}, {id: 40, score: 77}, {id: 41, score: 13}, {id: 42, score: 50}, {id: 43, score: 87}, {id: 44, score: 23}, {id: 45, score: 60}, {id: 46, score: 97}, {id: 47, score: 33}, {id: 48, score: 70}, {id: 49, score: 6}, {id: 50, score: 43}, {id: 51}, {id: 52, score: 16}, {id: 53, score: 53}, {id: 54, score: 90}]}, {items: [{id: 0, score: 11}, {id: 1, score: 48}, {id: 2, score: 85, grade: "B"}, {id: 3, score: 21}, {id: 4, score: 58, grade: "C"}, {id: 5, score: 95, grade: "A"}, {id: 6, score: 31}, {id: 7, score: 68, grade: "C"}, {id: 8, score: 4}, {id: 9, score: 41}, {id: 10, score: 78, grade: "B"}, {id: 11, score: 14}, {id: 12}, {id: 13, score: 88, grade: "B"}, {id: 14, score: 24}, {id: 15, score: 61, grade: "C"}, {id: 16, score: 98, grade: "A"}, {id: 17, score: 34}, {id: 18, score: 71, grade: "C"}, {id: 19, score: 7}, {id: 20, score: 44}, {id: 21, score: 81, grade: "B"}, {id: 22, score: 17}, {id: 23, score: 54, grade: "C"}, {id: 24, score: 91, grade: "A"}, {id: 25}, {id: 26, score: 64, grade: "C"}, {id: 27, score: 0}, {id: 28, score: 37}, {id: 29, score: 74, grade: "C"}, {id: 30, score: 10}, {id: 31, score: 47}, {id: 32, score: 84, grade: "B"}, {id: 33, score: 20}, {id: 34, score: 57, grade: "C"}, {id: 35, score: 94, grade: "A"}, {id: 36, score: 30}, {id: 37, score: 67, grade: "C"}, {id: 38}, {id: 39, score: 40}, {id: 40, score: 77, grade: "B"}, {id: 41, score: 13}, {id: 42, score: 50, grade: "C"}, {id: 43, score: 87, grade: "B"}, {id: 44, score: 23}, {id: 45, score: 60, grade: "C"}, {id: 46, score: 97, grade: "A"}, {id: 47, score: 33}, {id: 48, score: 70, grade: "C"}, {id: 49, score: 6}, {id: 50, score: 43}, {id: 51}, {id: 52, score: 16}, {id: 53, score: 53, grade: "C"}, {id: 54, score: 90, grade: "A"}]}], + [{items: [{id: 0, score: 22}, {id: 1, score: 59}, {id: 2, score: 96}, {id: 3, score: 32}, {id: 4, score: 69}, {id: 5, score: 5}, {id: 6, score: 42}, {id: 7, score: 79}, {id: 8, score: 15}, {id: 9, score: 52}, {id: 10, score: 89}, {id: 11}, {id: 12, score: 62}, {id: 13, score: 99}, {id: 14, score: 35}, {id: 15, score: 72}, {id: 16, score: 8}, {id: 17, score: 45}, {id: 18, score: 82}, {id: 19, score: 18}, {id: 20, score: 55}, {id: 21, score: 92}, {id: 22, score: 28}, {id: 23, score: 65}, {id: 24}, {id: 25, score: 38}, {id: 26, score: 75}, {id: 27, score: 11}, {id: 28, score: 48}, {id: 29, score: 85}, {id: 30, score: 21}, {id: 31, score: 58}, {id: 32, score: 95}, {id: 33, score: 31}, {id: 34, score: 68}, {id: 35, score: 4}, {id: 36, score: 41}, {id: 37}, {id: 38, score: 14}, {id: 39, score: 51}, {id: 40, score: 88}, {id: 41, score: 24}, {id: 42, score: 61}, {id: 43, score: 98}, {id: 44, score: 34}, {id: 45, score: 71}, {id: 46, score: 7}, {id: 47, score: 44}, {id: 48, score: 81}, {id: 49, score: 17}, {id: 50}, {id: 51, score: 91}, {id: 52, score: 27}, {id: 53, score: 64}, {id: 54, score: 0}]}, {items: [{id: 0, score: 22}, {id: 1, score: 59, grade: "C"}, {id: 2, score: 96, grade: "A"}, {id: 3, score: 32}, {id: 4, score: 69, grade: "C"}, {id: 5, score: 5}, {id: 6, score: 42}, {id: 7, score: 79, grade: "B"}, {id: 8, score: 15}, {id: 9, score: 52, grade: "C"}, {id: 10, score: 89, grade: "B"}, {id: 11}, {id: 12, score: 62, grade: "C"}, {id: 13, score: 99, grade: "A"}, {id: 14, score: 35}, {id: 15, score: 72, grade: "C"}, {id: 16, score: 8}, {id: 17, score: 45}, {id: 18, score: 82, grade: "B"}, {id: 19, score: 18}, {id: 20, score: 55, grade: "C"}, {id: 21, score: 92, grade: "A"}, {id: 22, score: 28}, {id: 23, score: 65, grade: "C"}, {id: 24}, {id: 25, score: 38}, {id: 26, score: 75, grade: "B"}, {id: 27, score: 11}, {id: 28, score: 48}, {id: 29, score: 85, grade: "B"}, {id: 30, score: 21}, {id: 31, score: 58, grade: "C"}, {id: 32, score: 95, grade: "A"}, {id: 33, score: 31}, {id: 34, score: 68, grade: "C"}, {id: 35, score: 4}, {id: 36, score: 41}, {id: 37}, {id: 38, score: 14}, {id: 39, score: 51, grade: "C"}, {id: 40, score: 88, grade: "B"}, {id: 41, score: 24}, {id: 42, score: 61, grade: "C"}, {id: 43, score: 98, grade: "A"}, {id: 44, score: 34}, {id: 45, score: 71, grade: "C"}, {id: 46, score: 7}, {id: 47, score: 44}, {id: 48, score: 81, grade: "B"}, {id: 49, score: 17}, {id: 50}, {id: 51, score: 91, grade: "A"}, {id: 52, score: 27}, {id: 53, score: 64, grade: "C"}, {id: 54, score: 0}]}], + [{items: [{id: 0, score: 33}, {id: 1, score: 70}, {id: 2, score: 6}, {id: 3, score: 43}, {id: 4, score: 80}, {id: 5, score: 16}, {id: 6, score: 53}, {id: 7, score: 90}, {id: 8, score: 26}, {id: 9, score: 63}, {id: 10}, {id: 11, score: 36}, {id: 12, score: 73}, {id: 13, score: 9}, {id: 14, score: 46}, {id: 15, score: 83}, {id: 16, score: 19}, {id: 17, score: 56}, {id: 18, score: 93}, {id: 19, score: 29}, {id: 20, score: 66}, {id: 21, score: 2}, {id: 22, score: 39}, {id: 23}, {id: 24, score: 12}, {id: 25, score: 49}, {id: 26, score: 86}, {id: 27, score: 22}, {id: 28, score: 59}, {id: 29, score: 96}, {id: 30, score: 32}, {id: 31, score: 69}, {id: 32, score: 5}, {id: 33, score: 42}, {id: 34, score: 79}, {id: 35, score: 15}, {id: 36}, {id: 37, score: 89}, {id: 38, score: 25}, {id: 39, score: 62}, {id: 40, score: 99}, {id: 41, score: 35}, {id: 42, score: 72}, {id: 43, score: 8}, {id: 44, score: 45}, {id: 45, score: 82}, {id: 46, score: 18}, {id: 47, score: 55}, {id: 48, score: 92}, {id: 49}, {id: 50, score: 65}, {id: 51, score: 1}, {id: 52, score: 38}, {id: 53, score: 75}, {id: 54, score: 11}]}, {items: [{id: 0, score: 33}, {id: 1, score: 70, grade: "C"}, {id: 2, score: 6}, {id: 3, score: 43}, {id: 4, score: 80, grade: "B"}, {id: 5, score: 16}, {id: 6, score: 53, grade: "C"}, {id: 7, score: 90, grade: "A"}, {id: 8, score: 26}, {id: 9, score: 63, grade: "C"}, {id: 10}, {id: 11, score: 36}, {id: 12, score: 73, grade: "C"}, {id: 13, score: 9}, {id: 14, score: 46}, {id: 15, score: 83, grade: "B"}, {id: 16, score: 19}, {id: 17, score: 56, grade: "C"}, {id: 18, score: 93, grade: "A"}, {id: 19, score: 29}, {id: 20, score: 66, grade: "C"}, {id: 21, score: 2}, {id: 22, score: 39}, {id: 23}, {id: 24, score: 12}, {id: 25, score: 49}, {id: 26, score: 86, grade: "B"}, {id: 27, score: 22}, {id: 28, score: 59, grade: "C"}, {id: 29, score: 96, grade: "A"}, {id: 30, score: 32}, {id: 31, score: 69, grade: "C"}, {id: 32, score: 5}, {id: 33, score: 42}, {id: 34, score: 79, grade: "B"}, {id: 35, score: 15}, {id: 36}, {id: 37, score: 89, grade: "B"}, {id: 38, score: 25}, {id: 39, score: 62, grade: "C"}, {id: 40, score: 99, grade: "A"}, {id: 41, score: 35}, {id: 42, score: 72, grade: "C"}, {id: 43, score: 8}, {id: 44, score: 45}, {id: 45, score: 82, grade: "B"}, {id: 46, score: 18}, {id: 47, score: 55, grade: "C"}, {id: 48, score: 92, grade: "A"}, {id: 49}, {id: 50, score: 65, grade: "C"}, {id: 51, score: 1}, {id: 52, score: 38}, {id: 53, score: 75, grade: "B"}, {id: 54, score: 11}]}], + ], +} + +{ + name: "collect table over 52 items", + graph: { + nodes: [{table: "t", hit: "collect", inputField: "items", outputPath: "tags", executionMode: "loop", inputs: ["v"], outputs: ["tag"], rules: [ + ["> 0", "'pos'"], + ["$ % 2 == 0", "'even'"], + ["> 20", "'big'"], + ]}], + }, + cases: [ + [{items: [{v: -10}, {v: -3}, {v: 4}, {v: 11}, {v: 18}, {v: 25}, {v: -8}, {v: -1}, {v: 6}, {v: 13}, {v: 20}, {v: 27}, {v: -6}, {v: 1}, {v: 8}, {v: 15}, {v: 22}, {v: 29}, {v: -4}, {v: 3}, {v: 10}, {v: 17}, {v: 24}, {v: -9}, {v: -2}, {v: 5}, {v: 12}, {v: 19}, {v: 26}, {v: -7}, {v: 0}, {v: 7}, {v: 14}, {v: 21}, {v: 28}, {v: -5}, {v: 2}, {v: 9}, {v: 16}, {v: 23}, {v: -10}, {v: -3}, {v: 4}, {v: 11}, {v: 18}, {v: 25}, {v: -8}, {v: -1}, {v: 6}, {v: 13}, {v: 20}, {v: 27}]}, {tags: [[{tag: "even"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}, {tag: "big"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}, {tag: "big"}], [], [{tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}, {tag: "big"}], [], [{tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "pos"}, {tag: "even"}, {tag: "big"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}]]}], + [{items: [{v: -5}, {v: 2}, {v: 9}, {v: 16}, {v: 23}, {v: -10}, {v: -3}, {v: 4}, {v: 11}, {v: 18}, {v: 25}, {v: -8}, {v: -1}, {v: 6}, {v: 13}, {v: 20}, {v: 27}, {v: -6}, {v: 1}, {v: 8}, {v: 15}, {v: 22}, {v: 29}, {v: -4}, {v: 3}, {v: 10}, {v: 17}, {v: 24}, {v: -9}, {v: -2}, {v: 5}, {v: 12}, {v: 19}, {v: 26}, {v: -7}, {v: 0}, {v: 7}, {v: 14}, {v: 21}, {v: 28}, {v: -5}, {v: 2}, {v: 9}, {v: 16}, {v: 23}, {v: -10}, {v: -3}, {v: 4}, {v: 11}, {v: 18}, {v: 25}, {v: -8}]}, {tags: [[], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}, {tag: "big"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}, {tag: "big"}], [], [{tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}, {tag: "big"}], [], [{tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "pos"}, {tag: "even"}, {tag: "big"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}], [], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}], [{tag: "pos"}, {tag: "even"}], [{tag: "pos"}, {tag: "big"}], [{tag: "even"}]]}], + ], +} + +{ + name: "equality table with 30 rules over 64 items, unknown and missing codes hit the fallback", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["code"], outputs: ["price", "group"], rules: [ + ["'C00'", "0", "'g0'"], + ["'C01'", "10", "'g1'"], + ["'C02'", "20", "'g2'"], + ["'C03'", "30", "'g0'"], + ["'C04'", "40", "'g1'"], + ["'C05'", "50", "'g2'"], + ["'C06'", "60", "'g0'"], + ["'C07'", "70", "'g1'"], + ["'C08'", "80", "'g2'"], + ["'C09'", "90", "'g0'"], + ["'C10'", "100", "'g1'"], + ["'C11'", "110", "'g2'"], + ["'C12'", "120", "'g0'"], + ["'C13'", "130", "'g1'"], + ["'C14'", "140", "'g2'"], + ["'C15'", "150", "'g0'"], + ["'C16'", "160", "'g1'"], + ["'C17'", "170", "'g2'"], + ["'C18'", "180", "'g0'"], + ["'C19'", "190", "'g1'"], + ["'C20'", "200", "'g2'"], + ["'C21'", "210", "'g0'"], + ["'C22'", "220", "'g1'"], + ["'C23'", "230", "'g2'"], + ["'C24'", "240", "'g0'"], + ["'C25'", "250", "'g1'"], + ["'C26'", "260", "'g2'"], + ["'C27'", "270", "'g0'"], + ["'C28'", "280", "'g1'"], + ["'C29'", "290", "'g2'"], + ["", "-1", "'none'"], + ]}], + }, + cases: [ + [{items: [{code: null}, {code: "C11"}, {code: "C22"}, {code: "C33"}, {code: "C10"}, {}, {code: "C32"}, {code: "C09"}, {code: "C20"}, {code: "C31"}, {code: "C08"}, {code: "C19"}, {code: "C30"}, {code: "C07"}, {code: "C18"}, {code: "C29"}, {code: "C06"}, {code: null}, {code: "C28"}, {code: "C05"}, {code: "C16"}, {code: "C27"}, {code: "C04"}, {code: "C15"}, {code: "C26"}, {code: "C03"}, {code: "C14"}, {code: "C25"}, {}, {code: "C13"}, {code: "C24"}, {code: "C01"}, {code: "C12"}, {code: "C23"}, {code: null}, {code: "C11"}, {code: "C22"}, {code: "C33"}, {code: "C10"}, {code: "C21"}, {code: "C32"}, {code: "C09"}, {code: "C20"}, {code: "C31"}, {code: "C08"}, {code: "C19"}, {code: "C30"}, {code: "C07"}, {code: "C18"}, {code: "C29"}, {code: "C06"}, {}, {code: "C28"}, {code: "C05"}, {code: "C16"}, {code: "C27"}, {code: "C04"}, {code: "C15"}, {code: "C26"}, {code: "C03"}, {code: "C14"}, {code: "C25"}, {code: "C02"}, {code: "C13"}]}, {out: [{price: -1, group: "none"}, {price: 110, group: "g2"}, {price: 220, group: "g1"}, {price: -1, group: "none"}, {price: 100, group: "g1"}, {price: -1, group: "none"}, {price: -1, group: "none"}, {price: 90, group: "g0"}, {price: 200, group: "g2"}, {price: -1, group: "none"}, {price: 80, group: "g2"}, {price: 190, group: "g1"}, {price: -1, group: "none"}, {price: 70, group: "g1"}, {price: 180, group: "g0"}, {price: 290, group: "g2"}, {price: 60, group: "g0"}, {price: -1, group: "none"}, {price: 280, group: "g1"}, {price: 50, group: "g2"}, {price: 160, group: "g1"}, {price: 270, group: "g0"}, {price: 40, group: "g1"}, {price: 150, group: "g0"}, {price: 260, group: "g2"}, {price: 30, group: "g0"}, {price: 140, group: "g2"}, {price: 250, group: "g1"}, {price: -1, group: "none"}, {price: 130, group: "g1"}, {price: 240, group: "g0"}, {price: 10, group: "g1"}, {price: 120, group: "g0"}, {price: 230, group: "g2"}, {price: -1, group: "none"}, {price: 110, group: "g2"}, {price: 220, group: "g1"}, {price: -1, group: "none"}, {price: 100, group: "g1"}, {price: 210, group: "g0"}, {price: -1, group: "none"}, {price: 90, group: "g0"}, {price: 200, group: "g2"}, {price: -1, group: "none"}, {price: 80, group: "g2"}, {price: 190, group: "g1"}, {price: -1, group: "none"}, {price: 70, group: "g1"}, {price: 180, group: "g0"}, {price: 290, group: "g2"}, {price: 60, group: "g0"}, {price: -1, group: "none"}, {price: 280, group: "g1"}, {price: 50, group: "g2"}, {price: 160, group: "g1"}, {price: 270, group: "g0"}, {price: 40, group: "g1"}, {price: 150, group: "g0"}, {price: 260, group: "g2"}, {price: 30, group: "g0"}, {price: 140, group: "g2"}, {price: 250, group: "g1"}, {price: 20, group: "g2"}, {price: 130, group: "g1"}]}], + [{items: [{code: "C03"}, {code: "C14"}, {code: "C25"}, {code: null}, {code: "C13"}, {}, {code: "C01"}, {code: "C12"}, {code: "C23"}, {code: "C00"}, {code: "C11"}, {code: "C22"}, {code: "C33"}, {code: "C10"}, {code: "C21"}, {code: "C32"}, {code: "C09"}, {code: "C20"}, {code: "C31"}, {code: "C08"}, {code: null}, {code: "C30"}, {code: "C07"}, {code: "C18"}, {code: "C29"}, {code: "C06"}, {code: "C17"}, {code: "C28"}, {}, {code: "C16"}, {code: "C27"}, {code: "C04"}, {code: "C15"}, {code: "C26"}, {code: "C03"}, {code: "C14"}, {code: "C25"}, {code: null}, {code: "C13"}, {code: "C24"}, {code: "C01"}, {code: "C12"}, {code: "C23"}, {code: "C00"}, {code: "C11"}, {code: "C22"}, {code: "C33"}, {code: "C10"}, {code: "C21"}, {code: "C32"}, {code: "C09"}, {}, {code: "C31"}, {code: "C08"}, {code: null}, {code: "C30"}, {code: "C07"}, {code: "C18"}, {code: "C29"}, {code: "C06"}, {code: "C17"}, {code: "C28"}, {code: "C05"}, {code: "C16"}]}, {out: [{price: 30, group: "g0"}, {price: 140, group: "g2"}, {price: 250, group: "g1"}, {price: -1, group: "none"}, {price: 130, group: "g1"}, {price: -1, group: "none"}, {price: 10, group: "g1"}, {price: 120, group: "g0"}, {price: 230, group: "g2"}, {price: 0, group: "g0"}, {price: 110, group: "g2"}, {price: 220, group: "g1"}, {price: -1, group: "none"}, {price: 100, group: "g1"}, {price: 210, group: "g0"}, {price: -1, group: "none"}, {price: 90, group: "g0"}, {price: 200, group: "g2"}, {price: -1, group: "none"}, {price: 80, group: "g2"}, {price: -1, group: "none"}, {price: -1, group: "none"}, {price: 70, group: "g1"}, {price: 180, group: "g0"}, {price: 290, group: "g2"}, {price: 60, group: "g0"}, {price: 170, group: "g2"}, {price: 280, group: "g1"}, {price: -1, group: "none"}, {price: 160, group: "g1"}, {price: 270, group: "g0"}, {price: 40, group: "g1"}, {price: 150, group: "g0"}, {price: 260, group: "g2"}, {price: 30, group: "g0"}, {price: 140, group: "g2"}, {price: 250, group: "g1"}, {price: -1, group: "none"}, {price: 130, group: "g1"}, {price: 240, group: "g0"}, {price: 10, group: "g1"}, {price: 120, group: "g0"}, {price: 230, group: "g2"}, {price: 0, group: "g0"}, {price: 110, group: "g2"}, {price: 220, group: "g1"}, {price: -1, group: "none"}, {price: 100, group: "g1"}, {price: 210, group: "g0"}, {price: -1, group: "none"}, {price: 90, group: "g0"}, {price: -1, group: "none"}, {price: -1, group: "none"}, {price: 80, group: "g2"}, {price: -1, group: "none"}, {price: -1, group: "none"}, {price: 70, group: "g1"}, {price: 180, group: "g0"}, {price: 290, group: "g2"}, {price: 60, group: "g0"}, {price: 170, group: "g2"}, {price: 280, group: "g1"}, {price: 50, group: "g2"}, {price: 160, group: "g1"}]}], + [{items: [{code: "C07"}, {code: "C18"}, {code: "C29"}, {code: "C06"}, {code: "C17"}, {}, {code: "C05"}, {code: null}, {code: "C27"}, {code: "C04"}, {code: "C15"}, {code: "C26"}, {code: "C03"}, {code: "C14"}, {code: "C25"}, {code: "C02"}, {code: "C13"}, {code: "C24"}, {code: "C01"}, {code: "C12"}, {code: "C23"}, {code: "C00"}, {code: "C11"}, {code: "C22"}, {code: null}, {code: "C10"}, {code: "C21"}, {code: "C32"}, {}, {code: "C20"}, {code: "C31"}, {code: "C08"}, {code: "C19"}, {code: "C30"}, {code: "C07"}, {code: "C18"}, {code: "C29"}, {code: "C06"}, {code: "C17"}, {code: "C28"}, {code: "C05"}, {code: null}, {code: "C27"}, {code: "C04"}, {code: "C15"}, {code: "C26"}, {code: "C03"}, {code: "C14"}, {code: "C25"}, {code: "C02"}, {code: "C13"}, {}, {code: "C01"}, {code: "C12"}, {code: "C23"}, {code: "C00"}, {code: "C11"}, {code: "C22"}, {code: null}, {code: "C10"}, {code: "C21"}, {code: "C32"}, {code: "C09"}, {code: "C20"}]}, {out: [{price: 70, group: "g1"}, {price: 180, group: "g0"}, {price: 290, group: "g2"}, {price: 60, group: "g0"}, {price: 170, group: "g2"}, {price: -1, group: "none"}, {price: 50, group: "g2"}, {price: -1, group: "none"}, {price: 270, group: "g0"}, {price: 40, group: "g1"}, {price: 150, group: "g0"}, {price: 260, group: "g2"}, {price: 30, group: "g0"}, {price: 140, group: "g2"}, {price: 250, group: "g1"}, {price: 20, group: "g2"}, {price: 130, group: "g1"}, {price: 240, group: "g0"}, {price: 10, group: "g1"}, {price: 120, group: "g0"}, {price: 230, group: "g2"}, {price: 0, group: "g0"}, {price: 110, group: "g2"}, {price: 220, group: "g1"}, {price: -1, group: "none"}, {price: 100, group: "g1"}, {price: 210, group: "g0"}, {price: -1, group: "none"}, {price: -1, group: "none"}, {price: 200, group: "g2"}, {price: -1, group: "none"}, {price: 80, group: "g2"}, {price: 190, group: "g1"}, {price: -1, group: "none"}, {price: 70, group: "g1"}, {price: 180, group: "g0"}, {price: 290, group: "g2"}, {price: 60, group: "g0"}, {price: 170, group: "g2"}, {price: 280, group: "g1"}, {price: 50, group: "g2"}, {price: -1, group: "none"}, {price: 270, group: "g0"}, {price: 40, group: "g1"}, {price: 150, group: "g0"}, {price: 260, group: "g2"}, {price: 30, group: "g0"}, {price: 140, group: "g2"}, {price: 250, group: "g1"}, {price: 20, group: "g2"}, {price: 130, group: "g1"}, {price: -1, group: "none"}, {price: 10, group: "g1"}, {price: 120, group: "g0"}, {price: 230, group: "g2"}, {price: 0, group: "g0"}, {price: 110, group: "g2"}, {price: 220, group: "g1"}, {price: -1, group: "none"}, {price: 100, group: "g1"}, {price: 210, group: "g0"}, {price: -1, group: "none"}, {price: 90, group: "g0"}, {price: 200, group: "g2"}]}], + ], +} + +{ + name: "sub-decision with a table over 50 generated items, aggregated downstream", + decisions: { + band: {nodes: [{table: "t", inputs: ["n"], outputs: ["band"], rules: [ + ["< 10", "'low'"], + ["[10..39]", "'mid'"], + ["", "'high'"], + ]}]}, + }, + graph: { + nodes: [ + {decision: "bands", key: "band", inputField: "map([0..49], {n: #})", outputPath: "bands", executionMode: "loop"}, + {expression: "agg", fields: { + n: "len(bands)", + low: "len(filter(bands, #.band == 'low'))", + mid: "len(filter(bands, #.band == 'mid'))", + high: "len(filter(bands, #.band == 'high'))", + last: "bands[49].band", + }}, + ], + }, + cases: [ + [{}, {n: 50, low: 10, mid: 30, high: 10, last: "high"}], + [{n: 1000}, {n: 50, low: 10, mid: 30, high: 10, last: "high"}], + ], +} diff --git a/core/engine/tests/spec/graph/37-loops-merging.json5 b/core/engine/tests/spec/graph/37-loops-merging.json5 new file mode 100644 index 00000000..9769fff7 --- /dev/null +++ b/core/engine/tests/spec/graph/37-loops-merging.json5 @@ -0,0 +1,529 @@ +// Merging loop results: passThrough of the node input around a loop result, nested outputPath +// writes, several loops over the same array, loop results joined with other branches, and empty +// or null arrays flowing through several loop nodes. Graph merges are deep for objects, replace +// arrays and scalars wholesale, and drop keys whose incoming value is null. + +// --- passThrough: the loop result merged into the node input ------------------------------------- +{ + name: "passThrough loop result replaces an existing scalar at outputPath", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "result", executionMode: "loop", passThrough: true, fields: {v: "x"}}], + }, + cases: [ + [{items: [{x: 1}], result: 5}, {items: [{x: 1}], result: [{x: 1, v: 1}]}], + [{items: [{x: 1}], result: "old"}, {items: [{x: 1}], result: [{x: 1, v: 1}]}], + [{items: [], result: true}, {items: [], result: []}], + ], +} + +{ + name: "passThrough loop result replaces an existing object at outputPath", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "result", executionMode: "loop", passThrough: true, fields: {v: "x"}}], + }, + cases: [ + [{items: [{x: 1}], result: {keep: 1}}, {items: [{x: 1}], result: [{x: 1, v: 1}]}], + [{items: [], result: {keep: 1}}, {items: [], result: []}], + ], +} + +{ + name: "passThrough loop result replaces a longer existing array, not merged index-wise", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "result", executionMode: "loop", passThrough: true, fields: {v: "x"}}], + }, + cases: [ + [{items: [{x: 1}], result: [{a: 1}, {a: 2}, {a: 3}]}, {items: [{x: 1}], result: [{x: 1, v: 1}]}], + [{items: [], result: [1, 2]}, {items: [], result: []}], + [{items: [{x: 1}, {x: 2}], result: [{v: 0, keep: true}]}, {items: [{x: 1}, {x: 2}], result: [{x: 1, v: 1}, {x: 2, v: 2}]}], + ], +} + +{ + name: "passThrough keeps unrelated input fields of every type", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", passThrough: true, fields: {v: "$root"}}], + }, + cases: [ + [{items: [1], s: "a", n: 1.5, b: false, o: {p: {q: 1}}, a: [1, [2]]}, {items: [1], s: "a", n: 1.5, b: false, o: {p: {q: 1}}, a: [1, [2]], out: [{v: 1}]}], + [{items: [], z: 0}, {items: [], z: 0, out: []}], + ], +} + +{ + name: "passThrough drops null-valued input keys at the top level", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", passThrough: true, fields: {v: "$root"}}], + }, + cases: [ + [{items: [1], gone: null, kept: 1}, {items: [1], kept: 1, out: [{v: 1}]}, "question: top-level null keys are dropped from the result while nested nulls survive (chapter 01)"], + [{items: [], gone: null}, {items: [], out: []}, "question: top-level null keys are dropped from the result while nested nulls survive (chapter 01)"], + ], +} + +{ + name: "passThrough loop over a filtered view leaves the original array intact", + graph: { + nodes: [{expression: "each", inputField: "filter(items, #.on)", outputPath: "items", executionMode: "loop", passThrough: true, fields: {seen: "true"}}], + }, + cases: [ + [{items: [{id: 1, on: true}, {id: 2, on: false}]}, {items: [{id: 1, on: true, seen: true}]}], + [{items: [{id: 2, on: false}]}, {items: []}], + ], +} + +{ + name: "passThrough loop does not mutate the input seen by a parallel branch", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {x: "x * 100"}}, + {expression: "orig", fields: {origSum: "sum(map(items, #.x))"}}, + ], + edges: ["input -> each -> output", "input -> orig -> output"], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {items: [{x: 100}, {x: 200}], origSum: 3}], + [{items: []}, {items: [], origSum: 0}], + ], +} + +{ + name: "passThrough loop does not mutate the input seen by a later node", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {x: "x * 100"}}, + {expression: "after", passThrough: true, fields: {now: "sum(map(items, #.x))", before: "sum(map($nodes.input.items, #.x))"}}, + ], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {items: [{x: 100}, {x: 200}], now: 300, before: 3}], + [{items: [{x: 0.5}]}, {items: [{x: 50}], now: 50, before: 0.5}], + ], +} + +// --- Nested outputPath ---------------------------------------------------------------------------- +{ + name: "loop writes a deep outputPath and creates the spine", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "report.sections.lines", executionMode: "loop", fields: {v: "x"}}], + }, + cases: [ + [{items: [{x: 1}]}, {report: {sections: {lines: [{v: 1}]}}}], + [{items: []}, {report: {sections: {lines: []}}}], + ], +} + +{ + name: "deep outputPath with passThrough merges into existing siblings", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "report.sections.lines", executionMode: "loop", passThrough: true, fields: {v: "x"}}], + }, + cases: [ + [{items: [{x: 1}], report: {title: "t", sections: {head: "h"}}}, {items: [{x: 1}], report: {title: "t", sections: {head: "h", lines: [{x: 1, v: 1}]}}}], + [{items: [], report: {sections: {lines: [{old: true}]}}}, {items: [], report: {sections: {lines: []}}}], + [{items: [{x: 2}], report: "flat"}, {items: [{x: 2}], report: {sections: {lines: [{x: 2, v: 2}]}}}], + ], +} + +{ + name: "outputPath through the source array's own parent", + graph: { + nodes: [{expression: "each", inputField: "order.lines", outputPath: "order.priced", executionMode: "loop", passThrough: true, fields: {total: "p * q"}}], + }, + cases: [ + [{order: {id: 1, lines: [{p: 2, q: 3}]}}, {order: {id: 1, lines: [{p: 2, q: 3}], priced: [{p: 2, q: 3, total: 6}]}}], + [{order: {id: 2, lines: []}}, {order: {id: 2, lines: [], priced: []}}], + ], +} + +{ + name: "two loops write sibling nested paths that merge at the output", + graph: { + nodes: [ + {expression: "a", inputField: "xs", outputPath: "res.as", executionMode: "loop", fields: {v: "$root"}}, + {expression: "b", inputField: "xs", outputPath: "res.bs", executionMode: "loop", fields: {w: "$root * 2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{xs: [1, 2]}, {res: {as: [{v: 1}, {v: 2}], bs: [{w: 2}, {w: 4}]}}], + [{xs: []}, {res: {as: [], bs: []}}], + ], +} + +{ + name: "loop writing a nested path next to an expression writing its parent", + graph: { + nodes: [ + {expression: "lines", inputField: "items", outputPath: "report.lines", executionMode: "loop", fields: {v: "x"}}, + {expression: "meta", fields: {"report.count": "len(items)", "report.title": "'r'"}}, + ], + edges: ["input -> lines -> output", "input -> meta -> output"], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {report: {lines: [{v: 1}, {v: 2}], count: 2, title: "r"}}], + [{items: []}, {report: {lines: [], count: 0, title: "r"}}], + ], +} + +// --- Two loops over the same array -------------------------------------------------------------- +{ + name: "two parallel loops over the same array into different paths", + graph: { + nodes: [ + {expression: "net", inputField: "items", outputPath: "net", executionMode: "loop", fields: {v: "price"}}, + {expression: "gross", inputField: "items", outputPath: "gross", executionMode: "loop", fields: {v: "price * 1.25"}}, + ], + edges: ["input -> net -> output", "input -> gross -> output"], + }, + cases: [ + [{items: [{price: 4}, {price: 8}]}, {net: [{v: 4}, {v: 8}], gross: [{v: 5}, {v: 10}]}], + [{items: []}, {net: [], gross: []}], + [{items: [{price: 0}]}, {net: [{v: 0}], gross: [{v: 0}]}], + ], +} + +{ + name: "two sequential passThrough loops over the same array accumulate fields", + graph: { + nodes: [ + {expression: "a", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {a: "x + 1"}}, + {expression: "b", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {b: "a * 2"}}, + ], + }, + cases: [ + [{items: [{x: 1}, {x: 2}]}, {items: [{x: 1, a: 2, b: 4}, {x: 2, a: 3, b: 6}]}], + [{items: []}, {items: []}], + ], +} + +{ + name: "two parallel passThrough loops writing back to the same array", + graph: { + nodes: [ + {expression: "a", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {a: "true"}}, + {expression: "b", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {b: "true"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{items: [{id: 1}]}, {items: [{id: 1, a: true}]}, "question: two branches writing the same array path do not combine per index; one branch's array wins whole (see chapter 13)"], + [{items: [{id: 1}, {id: 2}]}, {items: [{id: 1, a: true}, {id: 2, a: true}]}, "question: two branches writing the same array path do not combine per index; one branch's array wins whole (see chapter 13)"], + ], +} + +{ + name: "parallel expression and table loops over the same array, zipped downstream", + graph: { + nodes: [ + {expression: "names", inputField: "items", outputPath: "names", executionMode: "loop", fields: {n: "upper(name)"}}, + {table: "tiers", inputField: "items", outputPath: "tiers", executionMode: "loop", inputs: ["score"], outputs: ["t"], rules: [[">= 50", "'hi'"], ["", "'lo'"]]}, + {expression: "zip", fields: {labels: "map(names, #.n)", tiers: "map(tiers, #.t)"}}, + ], + edges: ["input -> names -> zip", "input -> tiers -> zip", "zip -> output"], + }, + cases: [ + [{items: [{name: "a", score: 60}, {name: "b", score: 10}]}, {labels: ["A", "B"], tiers: ["hi", "lo"]}], + [{items: []}, {labels: [], tiers: []}], + ], +} + +{ + name: "same array looped by an expression node and a sub-decision", + decisions: { + child: {nodes: [{expression: "c", fields: {sq: "v * v"}}]}, + }, + graph: { + nodes: [ + {expression: "e", inputField: "items", outputPath: "plus", executionMode: "loop", fields: {p: "v + 1"}}, + {decision: "d", key: "child", inputField: "items", outputPath: "squares", executionMode: "loop"}, + ], + edges: ["input -> e -> output", "input -> d -> output"], + }, + cases: [ + [{items: [{v: 2}, {v: 3}]}, {plus: [{p: 3}, {p: 4}], squares: [{sq: 4}, {sq: 9}]}], + [{items: []}, {plus: [], squares: []}], + ], +} + +// --- Loop results joined with other branches ----------------------------------------------------- +{ + name: "loop branch and scalar branch join at a downstream node", + graph: { + nodes: [ + {expression: "lines", inputField: "items", outputPath: "lines", executionMode: "loop", fields: {t: "p * q"}}, + {expression: "fee", fields: {fee: "fee ?? 0"}}, + {expression: "total", fields: {total: "sum(map(lines, #.t)) + fee"}}, + ], + edges: ["input -> lines -> total", "input -> fee -> total", "total -> output"], + }, + cases: [ + [{items: [{p: 2, q: 2}], fee: 1}, {total: 5}], + [{items: [], fee: 3}, {total: 3}], + [{items: [{p: 1, q: 1}, {p: 1, q: 1}]}, {total: 2}], + ], +} + +{ + name: "switch branches: a loop on one side, a constant on the other, joined", + graph: { + nodes: [ + {switch: "s", when: ["mode == 'each'", ""]}, + {expression: "each", inputField: "items", outputPath: "res", executionMode: "loop", fields: {v: "x"}}, + {expression: "bulk", fields: {res: "[{v: 'bulk'}]"}}, + {expression: "count", fields: {n: "len(res)"}}, + ], + edges: ["input -> s", "s:0 -> each -> count", "s:1 -> bulk -> count", "count -> output"], + }, + cases: [ + [{mode: "each", items: [{x: 1}, {x: 2}]}, {n: 2}], + [{mode: "bulk", items: [{x: 1}, {x: 2}]}, {n: 1}], + [{mode: "each", items: []}, {n: 0}], + ], +} + +{ + name: "collect switch runs two loops whose results merge", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["len(a) > 0", "len(b) > 0"]}, + {expression: "la", inputField: "a", outputPath: "ra", executionMode: "loop", fields: {v: "$root"}}, + {expression: "lb", inputField: "b", outputPath: "rb", executionMode: "loop", fields: {v: "$root"}}, + ], + edges: ["input -> s", "s:0 -> la -> output", "s:1 -> lb -> output"], + }, + cases: [ + [{a: [1], b: [2]}, {ra: [{v: 1}], rb: [{v: 2}]}], + [{a: [1], b: []}, {ra: [{v: 1}]}], + [{a: [], b: [2, 3]}, {rb: [{v: 2}, {v: 3}]}], + [{a: [], b: []}, {}], + ], +} + +{ + name: "a branch writing null next to a loop result in a join", + graph: { + nodes: [ + {expression: "lines", inputField: "items", outputPath: "lines", executionMode: "loop", fields: {v: "x"}}, + {expression: "clear", fields: {lines: "null", other: "1"}}, + {expression: "join", passThrough: true, fields: {has: "lines != null"}}, + ], + edges: ["input -> lines -> join", "input -> clear -> join", "join -> output"], + }, + cases: [ + [{items: [{x: 1}]}, {lines: [{v: 1}], other: 1, has: true}, "question: the join merges its incoming branches in order and a null value deletes the key; here the null branch merges first and the loop array lands after it, so the outcome depends on branch order"], + [{items: []}, {lines: [], other: 1, has: true}, "question: the join merges its incoming branches in order and a null value deletes the key; here the null branch merges first and the loop array lands after it, so the outcome depends on branch order"], + ], +} + +{ + name: "loop without outputPath joined with an object branch at the output", + graph: { + nodes: [ + {expression: "each", inputField: "items", executionMode: "loop", fields: {v: "x"}}, + {expression: "meta", fields: {count: "len(items)"}}, + ], + edges: ["input -> each -> output", "input -> meta -> output"], + }, + cases: [ + [{items: [{x: 1}]}, [{v: 1}], "question: a bare array and an object meet at the output; a top-level array replaces the merged object, so the loop array wins and the object branch is lost"], + [{items: []}, [], "question: a bare array and an object meet at the output; a top-level array replaces the merged object, so the loop array wins and the object branch is lost"], + ], +} + +{ + name: "loop result and its input both reach the output", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {v: "x * 2"}}, + ], + edges: ["input -> each -> output", "input -> output"], + }, + cases: [ + [{items: [{x: 1}], k: "a"}, {items: [{x: 1}], k: "a", out: [{v: 2}]}], + [{items: [], out: "old"}, {items: [], out: []}], + ], +} + +{ + name: "join node reads both loops and the original input", + graph: { + nodes: [ + {expression: "a", inputField: "items", outputPath: "doubled", executionMode: "loop", fields: {v: "x * 2"}}, + {expression: "b", inputField: "items", outputPath: "halved", executionMode: "loop", fields: {v: "x / 2"}}, + {expression: "j", fields: {pairs: "map(doubled, #.v)", halves: "map(halved, #.v)", n: "len($nodes.input.items)"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{items: [{x: 2}, {x: 4}]}, {pairs: [4, 8], halves: [1, 2], n: 2}], + [{items: []}, {pairs: [], halves: [], n: 0}], + ], +} + +// --- Empty and null arrays across several loop nodes ------------------------------------------------- +{ + name: "empty array through a chain of three loop nodes of different kinds", + decisions: { + child: {nodes: [{expression: "c", fields: {v: "v"}}]}, + }, + graph: { + nodes: [ + {expression: "e", inputField: "items", outputPath: "s1", executionMode: "loop", fields: {v: "x"}}, + {table: "t", inputField: "s1", outputPath: "s2", executionMode: "loop", inputs: ["v"], outputs: ["v"], rules: [["", "v"]]}, + {decision: "d", key: "child", inputField: "s2", outputPath: "s3", executionMode: "loop"}, + ], + }, + cases: [ + [{items: []}, {s3: []}], + [{items: [{x: 1}, {x: 2}]}, {s3: [{v: 1}, {v: 2}]}], + [{items: [{x: "a"}]}, {s3: [{v: "a"}]}], + ], +} + +{ + name: "a null array fails the loop even when other loops are empty", + graph: { + nodes: [ + {expression: "a", inputField: "as", outputPath: "ra", executionMode: "loop", fields: {v: "$root"}}, + {expression: "b", inputField: "bs", outputPath: "rb", executionMode: "loop", fields: {v: "$root"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{as: [], bs: []}, {ra: [], rb: []}], + [{as: [], bs: null}, "!error"], + [{as: null, bs: []}, "!error"], + [{as: [1]}, "!error"], + ], +} + +{ + name: "inputField with ?? [] tolerates null and missing arrays", + graph: { + nodes: [ + {expression: "a", inputField: "as ?? []", outputPath: "ra", executionMode: "loop", fields: {v: "$root"}}, + {expression: "b", inputField: "bs ?? []", outputPath: "rb", executionMode: "loop", fields: {v: "$root"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{as: null}, {ra: [], rb: []}], + [{}, {ra: [], rb: []}], + [{as: [1], bs: [2]}, {ra: [{v: 1}], rb: [{v: 2}]}], + ], +} + +{ + name: "null items through two chained loops", + graph: { + nodes: [ + {expression: "a", inputField: "items", outputPath: "s1", executionMode: "loop", fields: {v: "$root.x"}}, + {expression: "b", inputField: "s1", outputPath: "s2", executionMode: "loop", fields: {w: "v ?? 'none'"}}, + ], + }, + cases: [ + [{items: [null, {x: 1}]}, {s2: [{w: "none"}, {w: 1}]}], + [{items: [null]}, {s2: [{w: "none"}]}], + [{items: [{}]}, {s2: [{w: "none"}]}], + ], +} + +{ + name: "first-hit table nulls flow into a later loop as null items", + graph: { + nodes: [ + {table: "t", inputField: "items", outputPath: "s1", executionMode: "loop", inputs: ["v"], outputs: ["v"], rules: [["> 0", "v"]]}, + {expression: "b", inputField: "s1", outputPath: "s2", executionMode: "loop", fields: {matched: "$root != null"}}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: -1}]}, {s2: [{matched: true}, {matched: false}]}], + [{items: [{v: -1}]}, {s2: [{matched: false}]}], + [{items: []}, {s2: []}], + ], +} + +{ + name: "collect table yielding empty arrays per item feeds a flattening loop", + graph: { + nodes: [ + {table: "t", hit: "collect", inputField: "items", outputPath: "s1", executionMode: "loop", inputs: ["v"], outputs: ["tag"], rules: [["> 0", "'pos'"], ["> 10", "'big'"]]}, + {expression: "b", inputField: "flatten(s1)", outputPath: "s2", executionMode: "loop", fields: {t: "tag"}}, + ], + }, + cases: [ + [{items: [{v: -1}, {v: -2}]}, {s2: []}], + [{items: [{v: 20}, {v: -1}, {v: 5}]}, {s2: [{t: "pos"}, {t: "big"}, {t: "pos"}]}], + [{items: []}, {s2: []}], + ], +} + +{ + name: "empty loop results with passThrough keep the rest of the input", + graph: { + nodes: [ + {expression: "a", inputField: "as", outputPath: "as", executionMode: "loop", passThrough: true, fields: {v: "1"}}, + {expression: "b", inputField: "bs", outputPath: "bs", executionMode: "loop", passThrough: true, fields: {v: "2"}}, + ], + }, + cases: [ + [{as: [], bs: [], id: 1}, {as: [], bs: [], id: 1}], + [{as: [{}], bs: [], id: 2}, {as: [{v: 1}], bs: [], id: 2}], + [{as: [], bs: [{k: 1}], id: 3}, {as: [], bs: [{k: 1, v: 2}], id: 3}], + ], +} + +{ + name: "loop result fields that are null stay inside the array", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {v: "x", n: "null"}}], + }, + cases: [ + [{items: [{x: 1}, {}]}, {out: [{v: 1, n: null}, {v: null, n: null}]}], + [{items: [{x: null}]}, {out: [{v: null, n: null}]}], + ], +} + +// --- Larger merges ---------------------------------------------------------------------------------- +{ + name: "sub-decision loop with passThrough into a nested path joined with a summary branch", + decisions: { + line: {nodes: [{expression: "l", fields: {total: "price * qty"}}]}, + }, + graph: { + nodes: [ + {decision: "lines", key: "line", inputField: "order.lines", outputPath: "order.lines", executionMode: "loop", passThrough: true}, + {expression: "summary", fields: {"order.count": "len(order.lines)", "order.currency": "order.currency ?? 'EUR'"}}, + {expression: "final", passThrough: true, fields: {"order.total": "sum(map(order.lines, #.total))"}}, + ], + edges: ["input -> lines -> final", "input -> summary -> final", "final -> output"], + }, + cases: [ + [ + {order: {id: 1, lines: [{price: 2, qty: 3}, {price: 1, qty: 1}]}}, + {order: {id: 1, lines: [{price: 2, qty: 3, total: 6}, {price: 1, qty: 1, total: 1}], count: 2, currency: "EUR", total: 7}}, + ], + [{order: {id: 2, lines: [], currency: "NOK"}}, {order: {id: 2, lines: [], count: 0, currency: "NOK", total: 0}}], + [ + {order: {id: 3, lines: [{price: 0.1, qty: 3}]}}, + {order: {id: 3, lines: [{price: 0.1, qty: 3, total: 0.3}], count: 1, currency: "EUR", total: 0.3}}, + ], + ], +} + +{ + name: "loop over 50 generated items joined with a parallel aggregate", + graph: { + nodes: [ + {expression: "each", inputField: "map([1..50], {n: #})", outputPath: "rows", executionMode: "loop", fields: {even: "n % 2 == 0", n: "n"}}, + {expression: "agg", fields: {expected: "sum(map([1..50], #))"}}, + {expression: "check", fields: {sum: "sum(map(rows, #.n))", evens: "len(filter(rows, #.even))", expected: "expected", last: "rows[49].n"}}, + ], + edges: ["input -> each -> check", "input -> agg -> check", "check -> output"], + }, + cases: [ + [{}, {sum: 1275, evens: 25, expected: 1275, last: 50}], + [{rows: "ignored"}, {sum: 1275, evens: 25, expected: 1275, last: 50}], + ], +} diff --git a/core/engine/tests/spec/graph/38-subdecision-transforms.json5 b/core/engine/tests/spec/graph/38-subdecision-transforms.json5 new file mode 100644 index 00000000..899c21b8 --- /dev/null +++ b/core/engine/tests/spec/graph/38-subdecision-transforms.json5 @@ -0,0 +1,893 @@ +// Transform attributes on decision nodes: inputField, outputPath, passThrough and executionMode +// "loop" in every combination, children with schemas, children whose result is an array, an +// empty object or carries nulls, and child errors under each transform. +// +// The decision node evaluates `inputField` (an expression over its own input) to pick the child +// input, runs the child once (single) or once per array item (loop), wraps the result under +// `outputPath`, and with passThrough merges that on top of the node's own input. In loop mode +// passThrough additionally merges every child result over its own item. + +// --- The sixteen combinations, single mode ------------------------------------------------------- +// One child for all combinations: `total` from a and b, `tag` constant. +{ + name: "single: no attributes", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "(a ?? 0) + (b ?? 0)", tag: "'c'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{a: 1, b: 2}, {total: 3, tag: "c"}], + [{a: 1, b: 2, keep: true}, {total: 3, tag: "c"}], + [{}, {total: 0, tag: "c"}], + [{a: 0.1, b: 0.2, tag: "old"}, {total: 0.3, tag: "c"}], + ], +} + +{ + name: "single: inputField", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "(a ?? 0) + (b ?? 0)", tag: "'c'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub"}], + }, + cases: [ + [{sub: {a: 1, b: 2}}, {total: 3, tag: "c"}], + [{sub: {a: 5}, a: 100, b: 100}, {total: 5, tag: "c"}], + [{sub: {}}, {total: 0, tag: "c"}], + [{}, {total: 0, tag: "c"}], + [{sub: null, a: 1}, {total: 0, tag: "c"}], + ], +} + +{ + name: "single: outputPath", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "(a ?? 0) + (b ?? 0)", tag: "'c'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "res"}], + }, + cases: [ + [{a: 1, b: 2}, {res: {total: 3, tag: "c"}}], + [{a: 1, b: 2, res: {old: 1}}, {res: {total: 3, tag: "c"}}], + [{}, {res: {total: 0, tag: "c"}}], + ], +} + +{ + name: "single: passThrough", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "(a ?? 0) + (b ?? 0)", tag: "'c'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, total: 3, tag: "c"}], + [{a: 1, tag: "old", total: "x"}, {a: 1, total: 1, tag: "c"}], + [{}, {total: 0, tag: "c"}], + [{list: [1, 2], o: {p: 1}}, {list: [1, 2], o: {p: 1}, total: 0, tag: "c"}], + ], +} + +{ + name: "single: inputField and outputPath", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "(a ?? 0) + (b ?? 0)", tag: "'c'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub", outputPath: "res"}], + }, + cases: [ + [{sub: {a: 1, b: 2}}, {res: {total: 3, tag: "c"}}], + [{sub: {a: 2}, other: 1}, {res: {total: 2, tag: "c"}}], + [{}, {res: {total: 0, tag: "c"}}], + ], +} + +{ + name: "single: inputField and passThrough", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "(a ?? 0) + (b ?? 0)", tag: "'c'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub", passThrough: true}], + }, + cases: [ + [{sub: {a: 1, b: 2}}, {sub: {a: 1, b: 2}, total: 3, tag: "c"}], + [{sub: {a: 1}, a: 50, total: 9}, {sub: {a: 1}, a: 50, total: 1, tag: "c"}], + [{}, {total: 0, tag: "c"}], + ], +} + +{ + name: "single: outputPath and passThrough", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "(a ?? 0) + (b ?? 0)", tag: "'c'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "res", passThrough: true}], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, res: {total: 3, tag: "c"}}], + [{a: 1, res: {keep: true, tag: "old"}}, {a: 1, res: {keep: true, total: 1, tag: "c"}}], + [{a: 1, res: 7}, {a: 1, res: {total: 1, tag: "c"}}], + [{a: 1, res: [1, 2]}, {a: 1, res: {total: 1, tag: "c"}}], + ], +} + +{ + name: "single: inputField, outputPath and passThrough", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "(a ?? 0) + (b ?? 0)", tag: "'c'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub", outputPath: "sub", passThrough: true}], + }, + cases: [ + [{sub: {a: 1, b: 2}}, {sub: {a: 1, b: 2, total: 3, tag: "c"}}], + [{sub: {a: 1, tag: "old"}, x: 1}, {sub: {a: 1, total: 1, tag: "c"}, x: 1}], + [{x: 1}, {x: 1, sub: {total: 0, tag: "c"}}], + [{sub: null, x: 1}, {x: 1, sub: {total: 0, tag: "c"}}], + ], +} + +// --- The combinations in loop mode ------------------------------------------------------------- +// Loop mode needs an array (the node input itself without inputField). +{ + name: "loop: no inputField loops over an array node input", + decisions: { + child: {nodes: [{expression: "e", fields: {double: "n * 2"}}]}, + }, + graph: { + nodes: [ + {expression: "list", inputField: "nums", executionMode: "loop", fields: {n: "$root"}}, + {decision: "call", key: "child", executionMode: "loop"}, + ], + }, + cases: [ + [{nums: [1, 2]}, [{double: 2}, {double: 4}]], + [{nums: []}, []], + [{nums: [0.5]}, [{double: 1}]], + ], +} + +{ + name: "loop: an object node input without inputField is an error", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "1"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", executionMode: "loop"}], + }, + cases: [ + [{}, "!error"], + [{items: [1, 2]}, "!error"], + ], +} + +{ + name: "loop: inputField", + decisions: { + child: {nodes: [{expression: "e", fields: {double: "n * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", executionMode: "loop"}], + }, + cases: [ + [{items: [{n: 1}, {n: 2}]}, [{double: 2}, {double: 4}]], + [{items: []}, []], + [{items: [{n: -1}], other: true}, [{double: -2}]], + [{items: null}, "!error"], + [{items: "abc"}, "!error"], + ], +} + +{ + name: "loop: inputField and outputPath", + decisions: { + child: {nodes: [{expression: "e", fields: {double: "n * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out.list", executionMode: "loop"}], + }, + cases: [ + [{items: [{n: 1}, {n: 2}]}, {out: {list: [{double: 2}, {double: 4}]}}], + [{items: []}, {out: {list: []}}], + [{items: [{n: 3}], out: {old: 1}}, {out: {list: [{double: 6}]}}], + ], +} + +{ + name: "loop: inputField and passThrough merges each result over its item", + decisions: { + child: {nodes: [{expression: "e", fields: {double: "n * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", inputField: "items", passThrough: true, executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{n: 1}, {n: 2}]}, [{n: 1, double: 2}, {n: 2, double: 4}], "question: with passThrough and no outputPath the array result replaces the whole node input (a top-level array patch replaces the document), so the parent's other keys are lost"], + [{items: [], keep: 1}, [], "question: with passThrough and no outputPath the array result replaces the whole node input (a top-level array patch replaces the document), so the parent's other keys are lost"], + ], +} + +{ + name: "loop: inputField, outputPath and passThrough", + decisions: { + child: {nodes: [{expression: "e", fields: {double: "n * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", inputField: "items", outputPath: "items", passThrough: true, executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{n: 1, id: "a"}, {n: 2, id: "b"}], keep: 1}, {items: [{n: 1, id: "a", double: 2}, {n: 2, id: "b", double: 4}], keep: 1}], + [{items: [], keep: 1}, {items: [], keep: 1}], + [{items: [{n: 1, double: 99}]}, {items: [{n: 1, double: 2}]}], + ], +} + +{ + name: "loop: passThrough to a different outputPath keeps the source array", + decisions: { + child: {nodes: [{expression: "e", fields: {double: "n * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", inputField: "items", outputPath: "done", passThrough: true, executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{n: 1}]}, {items: [{n: 1}], done: [{n: 1, double: 2}]}], + [{items: [{n: 2}, {n: 3}]}, {items: [{n: 2}, {n: 3}], done: [{n: 2, double: 4}, {n: 3, double: 6}]}], + [{items: []}, {items: [], done: []}], + ], +} + +{ + name: "loop: passThrough over scalar items replaces each item by the child result", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "'x'"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", inputField: "nums", outputPath: "out", passThrough: true, executionMode: "loop"}, + ], + }, + cases: [ + [{nums: [1, 2]}, {nums: [1, 2], out: [{v: "x"}, {v: "x"}]}], + [{nums: ["a"]}, {nums: ["a"], out: [{v: "x"}]}], + [{nums: [null]}, {nums: [null], out: [{v: "x"}]}], + ], +} + +{ + name: "loop: mixed item kinds", + decisions: { + child: {nodes: [{expression: "e", fields: {hasN: "n != null"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{n: 1}, {}, {n: null}]}, {out: [{hasN: true}, {hasN: false}, {hasN: false}]}], + [{items: [{n: 1}, 5, "s", true]}, {out: [{hasN: true}, {hasN: false}, {hasN: false}, {hasN: false}]}, "question: scalar items reach the child as {} (edge merging drops non-objects), so n reads null instead of failing"], + [{items: [{n: 1}, [1]]}, "!error", "question: an array item reaches the child unchanged and a member read on an array environment fails, while scalar items are silently replaced by {}"], + ], +} + +{ + name: "loop: explicit single mode treats an array as one input", + decisions: { + child: {nodes: [{expression: "e", fields: {n: "len($root)"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", executionMode: "single"}], + }, + cases: [ + [{items: [1, 2, 3]}, {out: {n: 3}}], + [{items: []}, {out: {n: 0}}], + ], +} + +// --- inputField expressions ---------------------------------------------------------------------- +{ + name: "inputField dotted path into a nested object", + decisions: { + child: {nodes: [{expression: "e", fields: {city: "upper(city ?? 'none')"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "customer.address", outputPath: "res"}], + }, + cases: [ + [{customer: {address: {city: "oslo"}}}, {res: {city: "OSLO"}}], + [{customer: {address: {}}}, {res: {city: "NONE"}}], + [{customer: {}}, {res: {city: "NONE"}}], + [{}, {res: {city: "NONE"}}], + ], +} + +{ + name: "inputField indexing an array", + decisions: { + child: {nodes: [{expression: "e", fields: {name: "name"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "people[0]", outputPath: "first"}], + }, + cases: [ + [{people: [{name: "ann"}, {name: "bo"}]}, {first: {name: "ann"}}], + [{people: []}, {first: {}}], + ], +} + +{ + name: "inputField filtering a list for a loop", + decisions: { + child: {nodes: [{expression: "e", fields: {id: "id"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "filter(items, #.active)", outputPath: "active", executionMode: "loop"}], + }, + cases: [ + [{items: [{id: 1, active: true}, {id: 2, active: false}, {id: 3, active: true}]}, {active: [{id: 1}, {id: 3}]}], + [{items: [{id: 1, active: false}]}, {active: []}], + [{items: []}, {active: []}], + ], +} + +{ + name: "inputField building a list for a loop", + decisions: { + child: {nodes: [{expression: "e", fields: {sq: "v * v"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "map(nums, {v: #})", outputPath: "squares", executionMode: "loop"}], + }, + cases: [ + [{nums: [1, 2, 3]}, {squares: [{sq: 1}, {sq: 4}, {sq: 9}]}], + [{nums: [-0.5]}, {squares: [{sq: 0.25}]}], + [{nums: []}, {squares: []}], + ], +} + +{ + name: "inputField that fails to evaluate", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "1"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "a + 1", outputPath: "out"}], + }, + cases: [ + [{a: 1}, {out: {v: 1}}], + [{a: "x"}, "!error"], + ], +} + +{ + name: "inputField with a syntax error", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "1"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "a +", outputPath: "out"}], + }, + cases: [ + [{a: 1}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "inputField reading $nodes", + decisions: { + child: {nodes: [{expression: "e", fields: {total: "a + b"}}]}, + }, + graph: { + nodes: [ + {expression: "prep", fields: {pair: "{a: x, b: y}"}}, + {decision: "call", key: "child", inputField: "$nodes.prep.pair", outputPath: "out"}, + ], + }, + cases: [ + [{x: 1, y: 2}, {out: {total: 3}}], + [{x: 10, y: -10}, {out: {total: 0}}], + ], +} + +// --- outputPath shapes ------------------------------------------------------------------------- +{ + name: "outputPath three levels deep", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "x"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "a.b.c"}], + }, + cases: [ + [{x: 1}, {a: {b: {c: {v: 1}}}}], + [{x: "s"}, {a: {b: {c: {v: "s"}}}}], + [{}, {a: {b: {c: {}}}}], + ], +} + +{ + name: "outputPath with passThrough merges into an existing nested object", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "x"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "a.b", passThrough: true}], + }, + cases: [ + [{x: 1, a: {b: {old: 1}, c: 2}}, {x: 1, a: {b: {old: 1, v: 1}, c: 2}}], + [{x: 1, a: {c: 2}}, {x: 1, a: {b: {v: 1}, c: 2}}], + [{x: 1, a: 5}, {x: 1, a: {b: {v: 1}}}], + ], +} + +{ + name: "outputPath with an array child result", + decisions: { + child: {nodes: [{expression: "e", inputField: "xs", executionMode: "loop", fields: {v: "$root"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out", passThrough: true}], + }, + cases: [ + [{xs: [1, 2]}, {xs: [1, 2], out: [{v: 1}, {v: 2}]}], + [{xs: [], out: [9, 9]}, {xs: [], out: []}], + ], +} + +// --- Children returning arrays, empty objects and nulls ------------------------------------------- +{ + name: "array child result with passThrough and no outputPath replaces the input", + decisions: { + child: {nodes: [{expression: "e", inputField: "xs", executionMode: "loop", fields: {v: "$root"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{xs: [1, 2], keep: true}, [{v: 1}, {v: 2}], "question: a top-level array result replaces the passed-through input instead of being merged into it"], + [{xs: []}, [], "question: a top-level array result replaces the passed-through input instead of being merged into it"], + ], +} + +{ + name: "array child result in a loop gives an array of arrays", + decisions: { + child: {nodes: [{expression: "e", inputField: "xs", executionMode: "loop", fields: {v: "$root * 10"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "groups", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{groups: [{xs: [1, 2]}, {xs: []}, {xs: [3]}]}, {out: [[{v: 10}, {v: 20}], [], [{v: 30}]]}], + [{groups: []}, {out: []}], + ], +} + +{ + name: "child returning a collect table rows merged into parent", + decisions: { + child: {nodes: [{table: "t", hit: "collect", inputs: ["n"], outputs: ["hit"], rules: [["> 0", "'pos'"], ["> 10", "'big'"]]}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "hits", passThrough: true}], + }, + cases: [ + [{n: 20}, {n: 20, hits: [{hit: "pos"}, {hit: "big"}]}], + [{n: 5}, {n: 5, hits: [{hit: "pos"}]}], + [{n: -1, hits: [{hit: "stale"}]}, {n: -1, hits: []}], + ], +} + +{ + name: "child returning an empty object", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "x"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out", passThrough: true}], + }, + cases: [ + [{x: 1}, {x: 1, out: {v: 1}}], + [{}, {out: {}}], + [{out: {old: 1}}, {out: {old: 1}}], + ], +} + +{ + name: "child null at the top level does not delete a passed-through key", + decisions: { + child: {nodes: [{expression: "e", fields: {status: "null"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{status: "open"}, {status: "open"}], + [{}, {}], + ], +} + +{ + name: "a nested null from the child deletes the passed-through key", + decisions: { + child: {nodes: [{expression: "e", fields: {"info.status": "null", "info.seen": "true"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{info: {status: "open", id: 1}}, {info: {id: 1, seen: true}}], + [{info: {id: 1}}, {info: {id: 1, seen: true}}], + [{}, {info: {seen: true, status: null}}, "question: with no parent object to delete from, the child's nested null is materialized (same merge rule as 11-pass-through)"], + ], +} + +{ + name: "child null under outputPath with passThrough", + decisions: { + child: {nodes: [{expression: "e", fields: {status: "null", seen: "true"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "info", passThrough: true}], + }, + cases: [ + [{info: {status: "open"}}, {info: {status: "open", seen: true}}, "question: the child's final merge drops its top-level null before outputPath wraps it, so the parent's info.status survives while the same null nested one level deeper in the child would delete it"], + [{}, {info: {seen: true}}], + ], +} + +{ + name: "child returning nested arrays and objects", + decisions: { + child: {nodes: [{expression: "e", fields: {"r.list": "[1, [2, 3]]", "r.obj": "{k: {deep: true}}"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{}, {out: {r: {list: [1, [2, 3]], obj: {k: {deep: true}}}}}], + [{r: 1}, {out: {r: {list: [1, [2, 3]], obj: {k: {deep: true}}}}}], + ], +} + +{ + name: "passThrough replaces a parent array with the child's array", + decisions: { + child: {nodes: [{expression: "e", fields: {list: "[9]"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{list: [1, 2, 3]}, {list: [9]}], + [{list: "x"}, {list: [9]}], + [{}, {list: [9]}], + ], +} + +// --- Children with schemas under transforms -------------------------------------------------------- +{ + name: "child input schema validates the inputField selection", + decisions: { + child: {nodes: [ + {input: "in", schema: {type: "object", properties: {age: {type: "number"}}, required: ["age"]}}, + {expression: "e", fields: {adult: "age >= 18"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "person", outputPath: "person", passThrough: true}], + }, + cases: [ + [{person: {age: 20}}, {person: {age: 20, adult: true}}], + [{person: {age: 3}, age: "ignored"}, {person: {age: 3, adult: false}, age: "ignored"}], + [{age: 20}, "!error"], + [{person: {age: "20"}}, "!error"], + ], +} + +{ + name: "child input schema validates each loop item", + decisions: { + child: {nodes: [ + {input: "in", schema: {type: "object", properties: {n: {type: "integer", minimum: 0}}, required: ["n"]}}, + {expression: "e", fields: {half: "n / 2"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{n: 2}, {n: 4}]}, {out: [{half: 1}, {half: 2}]}], + [{items: []}, {out: []}], + [{items: [{n: 2}, {n: -1}]}, "!error"], + [{items: [{n: 2}, {}]}, "!error"], + [{items: [{n: 1.5}]}, "!error"], + ], +} + +{ + name: "child input schema checks the item before passThrough merging", + decisions: { + child: {nodes: [ + {input: "in", schema: {type: "object", additionalProperties: false, properties: {n: {type: "number"}}}}, + {expression: "e", fields: {ok: "true"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "items", passThrough: true, executionMode: "loop"}], + }, + cases: [ + [{items: [{n: 1}], extra: 1}, {items: [{n: 1, ok: true}], extra: 1}], + [{items: [{n: 1, m: 2}]}, "!error"], + ], +} + +{ + name: "child output schema checks the child result, not the wrapped one", + decisions: { + child: {nodes: [ + {expression: "e", fields: {score: "x * 10"}}, + {output: "out", schema: {type: "object", required: ["score"], properties: {score: {type: "number", maximum: 100}}}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "res", passThrough: true}], + }, + cases: [ + [{x: 5}, {x: 5, res: {score: 50}}], + [{x: 10}, {x: 10, res: {score: 100}}], + [{x: 11}, "!error"], + ], +} + +{ + name: "child output schema per loop item", + decisions: { + child: {nodes: [ + {expression: "e", fields: {v: "x"}}, + {output: "out", schema: {type: "object", properties: {v: {type: "string"}}}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{x: "a"}, {x: "b"}]}, {out: [{v: "a"}, {v: "b"}]}], + [{items: [{x: "a"}, {x: 1}]}, "!error"], + [{items: [{}]}, {out: [{}]}], + ], +} + +{ + name: "child input schema with an inputField resolving to null", + decisions: { + child: {nodes: [ + {input: "in", schema: {type: "object"}}, + {expression: "e", fields: {seen: "true"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub", outputPath: "out"}], + }, + cases: [ + [{sub: {}}, {out: {seen: true}}], + [{sub: {a: 1}}, {out: {seen: true}}], + [{}, "!error", "question: a missing inputField selection is validated as null, which an object schema rejects, although the child's expression nodes see it as {}"], + ], +} + +// --- Child errors under each transform --------------------------------------------------------------- +{ + name: "child error with outputPath", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "a * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{a: 1}, {out: {v: 2}}], + [{a: "x"}, "!error"], + [{a: [1]}, "!error"], + ], +} + +{ + name: "child error with passThrough", + decisions: { + child: {nodes: [{custom: "c", kind: "fail", config: {message: "child refused"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true, outputPath: "out"}], + }, + cases: [ + [{}, "!error: child refused"], + [{a: 1}, "!error: child refused"], + ], +} + +{ + name: "child error with inputField", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "a * 2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub"}], + }, + cases: [ + [{sub: {a: 2}}, {v: 4}], + [{sub: {a: true}}, "!error"], + [{sub: {a: 2}, a: "x"}, {v: 4}], + ], +} + +{ + name: "child error on one loop item fails the whole loop", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["ok", ""]}, + {expression: "good", fields: {r: "id"}}, + {custom: "bad", kind: "fail", config: {message: "item rejected"}}, + ], + edges: ["input -> s", "s:0 -> good -> output", "s:1 -> bad -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", passThrough: true, executionMode: "loop"}], + }, + cases: [ + [{items: [{ok: true, id: 1}, {ok: true, id: 2}]}, {items: [{ok: true, id: 1}, {ok: true, id: 2}], out: [{ok: true, id: 1, r: 1}, {ok: true, id: 2, r: 2}]}], + [{items: [{ok: true, id: 1}, {ok: false, id: 2}]}, "!error: item rejected"], + [{items: [{id: 1}]}, "!error: item rejected"], + [{items: []}, {items: [], out: []}], + ], +} + +{ + name: "child error on the first loop item", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "n + 1"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{n: "a"}, {n: 1}]}, "!error"], + [{items: [{n: 1}, {n: 2}, {n: false}]}, "!error"], + [{items: [{n: 1}]}, {out: [{v: 2}]}], + ], +} + +{ + name: "missing child under a loop with no items", + graph: { + nodes: [{decision: "call", key: "nowhere", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: []}, {out: []}, "question: an empty loop never loads the child, so an unknown key goes unnoticed"], + [{items: [{}]}, "!error"], + ], +} + +{ + name: "missing child under outputPath and passThrough", + graph: { + nodes: [{decision: "call", key: "nowhere", outputPath: "out", passThrough: true}], + }, + cases: [ + [{}, "!error"], + [{out: 1}, "!error"], + ], +} + +{ + name: "depth limit inside a loop", + decisions: { + forever: {nodes: [{decision: "again", key: "forever"}]}, + }, + graph: { + nodes: [{decision: "call", key: "forever", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: []}, {out: []}], + [{items: [{}]}, "!error"], + ], +} + +// --- Transforms inside the child ------------------------------------------------------------------- +{ + name: "child node with its own inputField and outputPath", + decisions: { + child: {nodes: [{expression: "e", inputField: "order", outputPath: "order", passThrough: true, fields: {total: "price * qty"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "data", outputPath: "data", passThrough: true}], + }, + cases: [ + [{data: {order: {price: 2, qty: 3}}, id: 1}, {data: {order: {price: 2, qty: 3, total: 6}}, id: 1}], + [{data: {order: {price: 0, qty: 3}}}, {data: {order: {price: 0, qty: 3, total: 0}}}], + ], +} + +{ + name: "child decision node with transforms inside a parent loop", + decisions: { + outer: {nodes: [{decision: "inner", key: "inner", inputField: "parts", outputPath: "parts", passThrough: true, executionMode: "loop"}]}, + inner: {nodes: [{expression: "e", fields: {w: "kg * 1000"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "outer", inputField: "boxes", outputPath: "boxes", passThrough: true, executionMode: "loop"}], + }, + cases: [ + [ + {boxes: [{id: 1, parts: [{kg: 1}, {kg: 0.5}]}, {id: 2, parts: []}]}, + {boxes: [{id: 1, parts: [{kg: 1, w: 1000}, {kg: 0.5, w: 500}]}, {id: 2, parts: []}]}, + ], + [{boxes: []}, {boxes: []}], + ], +} + +// --- Realistic combinations --------------------------------------------------------------------------- +{ + name: "line pricing loop with a summary node after it", + decisions: { + line: {nodes: [ + {table: "rate", inputs: ["category"], outputs: ["vat"], rules: [["'food'", "0.05"], ["'book'", "0"], ["", "0.2"]]}, + {expression: "calc", fields: {net: "$nodes.input.price * $nodes.input.qty", gross: "$nodes.input.price * $nodes.input.qty * (1 + vat)"}}, + ]}, + }, + graph: { + nodes: [ + {decision: "lines", key: "line", inputField: "lines", outputPath: "lines", passThrough: true, executionMode: "loop"}, + {expression: "sum", passThrough: true, fields: {total: "sum(map(lines, #.gross))"}}, + ], + }, + cases: [ + [ + {lines: [{category: "food", price: 10, qty: 2}, {category: "tv", price: 100, qty: 1}]}, + {lines: [{category: "food", price: 10, qty: 2, net: 20, gross: 21}, {category: "tv", price: 100, qty: 1, net: 100, gross: 120}], total: 141}, + ], + [{lines: [{category: "book", price: 5, qty: 1}]}, {lines: [{category: "book", price: 5, qty: 1, net: 5, gross: 5}], total: 5}], + [{lines: []}, {lines: [], total: 0}], + ], +} + +{ + name: "applicant scoring keeps the request next to the result", + decisions: { + score: {nodes: [ + {table: "t", inputs: ["income", "debts"], outputs: ["score"], rules: [ + [">= 50000", "< 10000", "800"], + [">= 50000", "", "650"], + ["", "", "400"], + ]}, + {output: "out", schema: {type: "object", required: ["score"]}}, + ]}, + }, + graph: { + nodes: [ + {decision: "scoring", key: "score", inputField: "applicant", outputPath: "applicant.risk", passThrough: true}, + {expression: "decide", passThrough: true, fields: {approved: "applicant.risk.score >= 600"}}, + ], + }, + cases: [ + [{applicant: {income: 60000, debts: 0}}, {applicant: {income: 60000, debts: 0, risk: {score: 800}}, approved: true}], + [{applicant: {income: 60000, debts: 20000}}, {applicant: {income: 60000, debts: 20000, risk: {score: 650}}, approved: true}], + [{applicant: {income: 1000, debts: 0}}, {applicant: {income: 1000, debts: 0, risk: {score: 400}}, approved: false}], + ], +} diff --git a/core/engine/tests/spec/graph/39-subdecision-chains.json5 b/core/engine/tests/spec/graph/39-subdecision-chains.json5 new file mode 100644 index 00000000..5bb835df --- /dev/null +++ b/core/engine/tests/spec/graph/39-subdecision-chains.json5 @@ -0,0 +1,837 @@ +// Sub-decision topologies: several decision nodes calling the same child, children calling +// grandchildren, sibling sub-decisions on parallel branches merged at a join, children made of +// switches and tables, and deep chains close to the depth limit. +// +// Every decision node evaluates its child independently: calls share no state, whether they +// name the same key or not. Depth counts nesting only (root 0, a graph at depth 10 is refused); +// siblings and sequential calls do not add depth. + +// --- The same child from several nodes ------------------------------------------------------------ +{ + name: "same child called twice in sequence feeds its own result back", + decisions: { + inc: {nodes: [{expression: "e", fields: {n: "(n ?? 0) + 1", calls: "(calls ?? 0) + 1"}}]}, + }, + graph: { + nodes: [ + {decision: "first", key: "inc"}, + {decision: "second", key: "inc"}, + ], + }, + cases: [ + [{n: 0}, {n: 2, calls: 2}], + [{n: 10, calls: 5}, {n: 12, calls: 7}], + [{}, {n: 2, calls: 2}], + ], +} + +{ + name: "same child called three times in sequence with passThrough", + decisions: { + double: {nodes: [{expression: "e", passThrough: true, fields: {v: "v * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "double"}, + {decision: "b", key: "double", passThrough: true}, + {decision: "c", key: "double", outputPath: "last"}, + ], + }, + cases: [ + [{v: 1, id: "x"}, {last: {v: 8, id: "x"}}], + [{v: 0.5}, {last: {v: 4}}], + [{v: -1}, {last: {v: -8}}], + ], +} + +{ + name: "same child on three parallel branches with different inputs", + decisions: { + grade: {nodes: [{table: "t", inputs: ["score"], outputs: ["grade"], rules: [[">= 90", "'A'"], [">= 70", "'B'"], ["", "'C'"]]}]}, + }, + graph: { + nodes: [ + {decision: "math", key: "grade", inputField: "math", outputPath: "grades.math"}, + {decision: "art", key: "grade", inputField: "art", outputPath: "grades.art"}, + {decision: "music", key: "grade", inputField: "music", outputPath: "grades.music"}, + ], + edges: ["input -> math -> output", "input -> art -> output", "input -> music -> output"], + }, + cases: [ + [{math: {score: 95}, art: {score: 75}, music: {score: 10}}, {grades: {math: {grade: "A"}, art: {grade: "B"}, music: {grade: "C"}}}], + [{math: {score: 70}, art: {score: 90}, music: {score: 89.99}}, {grades: {math: {grade: "B"}, art: {grade: "A"}, music: {grade: "B"}}}], + [{}, {grades: {math: {grade: "C"}, art: {grade: "C"}, music: {grade: "C"}}}], + ], +} + +{ + name: "same child in a loop and a single call", + decisions: { + norm: {nodes: [{expression: "e", fields: {v: "trim(lower(s))"}}]}, + }, + graph: { + nodes: [ + {decision: "one", key: "norm", inputField: "title", outputPath: "title"}, + {decision: "many", key: "norm", inputField: "tags", outputPath: "tags", executionMode: "loop"}, + ], + edges: ["input -> one -> output", "input -> many -> output"], + }, + cases: [ + [{title: {s: " Hello "}, tags: [{s: "A"}, {s: " b "}]}, {title: {v: "hello"}, tags: [{v: "a"}, {v: "b"}]}], + [{title: {s: "X"}, tags: []}, {title: {v: "x"}, tags: []}], + ], +} + +{ + name: "same child on both switch branches", + decisions: { + label: {nodes: [{expression: "e", fields: {label: "prefix + ':' + string(n)"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["n >= 0", ""]}, + {expression: "pos", fields: {prefix: "'pos'", n: "n"}}, + {expression: "neg", fields: {prefix: "'neg'", n: "-n"}}, + {decision: "lp", key: "label"}, + {decision: "ln", key: "label"}, + ], + edges: ["input -> s", "s:0 -> pos -> lp -> output", "s:1 -> neg -> ln -> output"], + }, + cases: [ + [{n: 3}, {label: "pos:3"}], + [{n: -4}, {label: "neg:4"}], + [{n: 0}, {label: "pos:0"}], + ], +} + +{ + name: "same child reached by a collect switch on every taken branch", + decisions: { + mark: {nodes: [{expression: "e", fields: {seen: "true"}}]}, + }, + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {decision: "ma", key: "mark", outputPath: "a"}, + {decision: "mb", key: "mark", outputPath: "b"}, + {decision: "mc", key: "mark", outputPath: "c"}, + ], + edges: ["input -> s", "s:0 -> ma -> output", "s:1 -> mb -> output", "s:2 -> mc -> output"], + }, + cases: [ + [{a: true, b: true, c: true}, {a: {seen: true}, b: {seen: true}, c: {seen: true}}], + [{a: true, b: false, c: true}, {a: {seen: true}, c: {seen: true}}], + [{a: false, b: false, c: false}, {}], + ], +} + +// --- Children calling grandchildren --------------------------------------------------------------- +{ + name: "child composes two grandchildren in sequence", + decisions: { + pricing: {nodes: [ + {decision: "base", key: "base", outputPath: "base"}, + {decision: "tax", key: "tax", inputField: "base", outputPath: "tax", passThrough: true}, + {expression: "sum", passThrough: true, fields: {total: "base.amount + tax.amount"}}, + ]}, + base: {nodes: [{expression: "e", fields: {amount: "price * qty"}}]}, + tax: {nodes: [{expression: "e", fields: {amount: "amount * 0.25"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "pricing", outputPath: "pricing"}], + }, + cases: [ + [{price: 10, qty: 2}, {pricing: {base: {amount: 20}, tax: {amount: 5}, total: 25}}], + [{price: 4, qty: 1}, {pricing: {base: {amount: 4}, tax: {amount: 1}, total: 5}}], + [{price: 0, qty: 9}, {pricing: {base: {amount: 0}, tax: {amount: 0}, total: 0}}], + ], +} + +{ + name: "child fans out to two grandchildren and joins them", + decisions: { + profile: { + nodes: [ + {decision: "risk", key: "risk", outputPath: "risk"}, + {decision: "value", key: "value", outputPath: "value"}, + {expression: "combine", fields: {segment: "risk.level == 'low' and value.tier == 'high' ? 'prime' : 'standard'"}}, + ], + edges: ["input -> risk -> combine", "input -> value -> combine", "combine -> output"], + }, + risk: {nodes: [{table: "t", inputs: ["defaults"], outputs: ["level"], rules: [["0", "'low'"], ["", "'high'"]]}]}, + value: {nodes: [{table: "t", inputs: ["spend"], outputs: ["tier"], rules: [[">= 1000", "'high'"], ["", "'low'"]]}]}, + }, + graph: { + nodes: [{decision: "call", key: "profile"}], + }, + cases: [ + [{defaults: 0, spend: 5000}, {segment: "prime"}], + [{defaults: 1, spend: 5000}, {segment: "standard"}], + [{defaults: 0, spend: 10}, {segment: "standard"}], + [{spend: 5000}, {segment: "standard"}], + ], +} + +{ + name: "grandchild result passes up through two outputPaths", + decisions: { + mid: {nodes: [{decision: "leaf", key: "leaf", outputPath: "leaf", passThrough: true}]}, + leaf: {nodes: [{expression: "e", fields: {depth: "2", v: "v + 1"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "mid", outputPath: "mid", passThrough: true}], + }, + cases: [ + [{v: 1}, {v: 1, mid: {v: 1, leaf: {depth: 2, v: 2}}}], + [{v: -1, mid: {old: 1}}, {v: -1, mid: {old: 1, v: -1, mid: {old: 1}, leaf: {depth: 2, v: 0}}}], + ], +} + +{ + name: "grandchild selected by a switch in the child", + decisions: { + router: { + nodes: [ + {switch: "s", when: ["kind == 'person'", "kind == 'company'", ""]}, + {decision: "p", key: "person"}, + {decision: "c", key: "company"}, + {expression: "u", fields: {result: "'unknown'"}}, + ], + edges: ["input -> s", "s:0 -> p -> output", "s:1 -> c -> output", "s:2 -> u -> output"], + }, + person: {nodes: [{expression: "e", fields: {result: "first + ' ' + last"}}]}, + company: {nodes: [{expression: "e", fields: {result: "upper(name)"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "router"}], + }, + cases: [ + [{kind: "person", first: "Ann", last: "Lee"}, {result: "Ann Lee"}], + [{kind: "company", name: "acme"}, {result: "ACME"}], + [{kind: "robot"}, {result: "unknown"}], + [{}, {result: "unknown"}], + ], +} + +{ + name: "grandchild missing only on an untaken child branch", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["legacy", ""]}, + {decision: "old", key: "removed"}, + {decision: "new", key: "current"}, + ], + edges: ["input -> s", "s:0 -> old -> output", "s:1 -> new -> output"], + }, + current: {nodes: [{expression: "e", fields: {version: "2"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{legacy: false}, {version: 2}], + [{}, {version: 2}], + [{legacy: true}, "!error"], + ], +} + +{ + name: "grandchild error stops the child before its later nodes", + decisions: { + child: {nodes: [ + {decision: "check", key: "check", passThrough: true}, + {expression: "after", fields: {reached: "true"}}, + ]}, + check: { + nodes: [ + {switch: "s", when: ["amount <= limit", ""]}, + {expression: "ok", fields: {checked: "true"}}, + {custom: "no", kind: "fail", config: {message: "over limit"}}, + ], + edges: ["input -> s", "s:0 -> ok -> output", "s:1 -> no -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{amount: 5, limit: 10}, {reached: true}], + [{amount: 10, limit: 10}, {reached: true}], + [{amount: 11, limit: 10}, "!error: over limit"], + ], +} + +// --- Sibling sub-decisions joined ----------------------------------------------------------------- +{ + name: "siblings with disjoint keys merge at the output", + decisions: { + left: {nodes: [{expression: "e", fields: {l: "x + 1"}}]}, + right: {nodes: [{expression: "e", fields: {r: "x - 1"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "left"}, + {decision: "b", key: "right"}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{x: 1}, {l: 2, r: 0}], + [{x: 0.5}, {l: 1.5, r: -0.5}], + ], +} + +{ + name: "siblings joined at an expression node", + decisions: { + left: {nodes: [{expression: "e", fields: {l: "x + 1"}}]}, + right: {nodes: [{expression: "e", fields: {r: "x - 1"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "left"}, + {decision: "b", key: "right"}, + {expression: "join", fields: {product: "l * r", sawX: "x != null"}}, + ], + edges: ["input -> a -> join", "input -> b -> join", "join -> output"], + }, + cases: [ + [{x: 3}, {product: 8, sawX: false}], + [{x: 1}, {product: 0, sawX: false}], + [{x: -2}, {product: 3, sawX: false}], + ], +} + +{ + name: "siblings writing the same key collide at the join", + decisions: { + left: {nodes: [{expression: "e", fields: {winner: "'left'", l: "true"}}]}, + right: {nodes: [{expression: "e", fields: {winner: "'right'", r: "true"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "left"}, + {decision: "b", key: "right"}, + {expression: "join", passThrough: true, fields: {joined: "true"}}, + ], + edges: ["input -> a -> join", "input -> b -> join", "join -> output"], + }, + cases: [ + [{}, {winner: "left", l: true, r: true, joined: true}, "question: at a join the first-listed branch wins a shared key (incoming data merges in reverse edge order); nothing in the graph makes the precedence visible"], + [{winner: "input"}, {winner: "left", l: true, r: true, joined: true}, "question: at a join the first-listed branch wins a shared key (incoming data merges in reverse edge order); nothing in the graph makes the precedence visible"], + ], +} + +{ + name: "siblings writing nested keys deep-merge at the join", + decisions: { + left: {nodes: [{expression: "e", fields: {"report.left": "x * 2", "report.shared.a": "1"}}]}, + right: {nodes: [{expression: "e", fields: {"report.right": "x * 3", "report.shared.b": "2"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "left"}, + {decision: "b", key: "right"}, + {expression: "join", fields: {report: "report"}}, + ], + edges: ["input -> a -> join", "input -> b -> join", "join -> output"], + }, + cases: [ + [{x: 1}, {report: {left: 2, right: 3, shared: {a: 1, b: 2}}}], + [{x: 0}, {report: {left: 0, right: 0, shared: {a: 1, b: 2}}}], + ], +} + +{ + name: "siblings under different outputPaths assemble one object", + decisions: { + credit: {nodes: [{table: "t", inputs: ["score"], outputs: ["ok"], rules: [[">= 600", "true"], ["", "false"]]}]}, + fraud: {nodes: [{table: "t", inputs: ["flags"], outputs: ["ok"], rules: [["0", "true"], ["", "false"]]}]}, + kyc: {nodes: [{expression: "e", fields: {ok: "verified == true"}}]}, + }, + graph: { + nodes: [ + {decision: "c", key: "credit", outputPath: "checks.credit"}, + {decision: "f", key: "fraud", outputPath: "checks.fraud"}, + {decision: "k", key: "kyc", outputPath: "checks.kyc"}, + {expression: "verdict", passThrough: true, fields: {approved: "checks.credit.ok and checks.fraud.ok and checks.kyc.ok"}}, + ], + edges: ["input -> c -> verdict", "input -> f -> verdict", "input -> k -> verdict", "verdict -> output"], + }, + cases: [ + [{score: 700, flags: 0, verified: true}, {checks: {credit: {ok: true}, fraud: {ok: true}, kyc: {ok: true}}, approved: true}], + [{score: 500, flags: 0, verified: true}, {checks: {credit: {ok: false}, fraud: {ok: true}, kyc: {ok: true}}, approved: false}], + [{score: 700, flags: 2, verified: false}, {checks: {credit: {ok: true}, fraud: {ok: false}, kyc: {ok: false}}, approved: false}], + [{score: 700, flags: 0}, {checks: {credit: {ok: true}, fraud: {ok: true}, kyc: {ok: false}}, approved: false}], + ], +} + +{ + name: "sibling sub-decision and a plain branch at the join", + decisions: { + child: {nodes: [{expression: "e", fields: {fromChild: "x * 10"}}]}, + }, + graph: { + nodes: [ + {decision: "c", key: "child"}, + {expression: "local", passThrough: true, fields: {fromLocal: "x + 1"}}, + {expression: "join", fields: {sum: "fromChild + fromLocal", x: "x"}}, + ], + edges: ["input -> c -> join", "input -> local -> join", "join -> output"], + }, + cases: [ + [{x: 1}, {sum: 12, x: 1}], + [{x: 0}, {sum: 1, x: 0}], + ], +} + +{ + name: "one sibling failing fails the graph", + decisions: { + ok: {nodes: [{expression: "e", fields: {ok: "true"}}]}, + bad: {nodes: [{expression: "e", fields: {v: "n * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "ok"}, + {decision: "b", key: "bad"}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{n: 2}, {ok: true, v: 4}], + [{n: "x"}, "!error"], + ], +} + +{ + name: "sibling on an untaken branch does not run", + decisions: { + left: {nodes: [{expression: "e", fields: {side: "'left'", v: "n * 2"}}]}, + right: {nodes: [{expression: "e", fields: {side: "'right'"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["n != null", ""]}, + {decision: "a", key: "left"}, + {decision: "b", key: "right"}, + {expression: "join", passThrough: true, fields: {done: "true"}}, + ], + edges: ["input -> s", "s:0 -> a -> join", "s:1 -> b -> join", "join -> output"], + }, + cases: [ + [{n: 2}, {side: "left", v: 4, done: true}], + [{}, {side: "right", done: true}], + ], +} + +{ + name: "siblings returning arrays at a join", + decisions: { + evens: {nodes: [{expression: "e", inputField: "filter(xs, # % 2 == 0)", executionMode: "loop", fields: {even: "$root"}}]}, + odds: {nodes: [{expression: "e", inputField: "filter(xs, # % 2 == 1)", executionMode: "loop", fields: {odd: "$root"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "evens", outputPath: "evens"}, + {decision: "b", key: "odds", outputPath: "odds"}, + {expression: "join", fields: {e: "len(evens)", o: "len(odds)"}}, + ], + edges: ["input -> a -> join", "input -> b -> join", "join -> output"], + }, + cases: [ + [{xs: [1, 2, 3, 4, 5]}, {e: 2, o: 3}], + [{xs: []}, {e: 0, o: 0}], + ], +} + +{ + name: "siblings returning top-level arrays without outputPath", + decisions: { + a: {nodes: [{expression: "e", inputField: "xs", executionMode: "loop", fields: {a: "$root"}}]}, + b: {nodes: [{expression: "e", fields: {b: "true"}}]}, + }, + graph: { + nodes: [ + {decision: "na", key: "a"}, + {decision: "nb", key: "b"}, + ], + edges: ["input -> na -> output", "input -> nb -> output"], + }, + cases: [ + [{xs: [1]}, [{a: 1}], "question: at the output an array result and an object result meet; the array wins and the object branch is dropped"], + [{xs: []}, [], "question: at the output an array result and an object result meet; the array wins and the object branch is dropped"], + ], +} + +// --- Children with switches and tables ----------------------------------------------------------- +{ + name: "child with a switch feeding two tables", + decisions: { + quote: { + nodes: [ + {switch: "s", when: ["type == 'car'", ""]}, + {table: "car", inputs: ["age"], outputs: ["premium"], rules: [["< 25", "900"], ["< 65", "500"], ["", "700"]]}, + {table: "home", inputs: ["value"], outputs: ["premium"], rules: [["> 500000", "1200"], ["", "400"]]}, + ], + edges: ["input -> s", "s:0 -> car -> output", "s:1 -> home -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "quote", outputPath: "quote", passThrough: true}], + }, + cases: [ + [{type: "car", age: 20}, {type: "car", age: 20, quote: {premium: 900}}], + [{type: "car", age: 40}, {type: "car", age: 40, quote: {premium: 500}}], + [{type: "car", age: 70}, {type: "car", age: 70, quote: {premium: 700}}], + [{type: "home", value: 600000}, {type: "home", value: 600000, quote: {premium: 1200}}], + [{value: 1}, {value: 1, quote: {premium: 400}}], + ], +} + +{ + name: "child with a table then a switch on its result", + decisions: { + flow: { + nodes: [ + {table: "tier", passThrough: true, inputs: ["points"], outputs: ["tier"], rules: [[">= 100", "'gold'"], ["", "'basic'"]]}, + {switch: "s", when: ["tier == 'gold'", ""]}, + {expression: "gold", fields: {perk: "'lounge'", tier: "tier"}}, + {expression: "basic", fields: {perk: "'none'", tier: "tier"}}, + ], + edges: ["input -> tier -> s", "s:0 -> gold -> output", "s:1 -> basic -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "flow"}], + }, + cases: [ + [{points: 150}, {perk: "lounge", tier: "gold"}], + [{points: 99}, {perk: "none", tier: "basic"}], + [{}, {perk: "none", tier: "basic"}], + ], +} + +{ + name: "child with a collect table feeding an expression", + decisions: { + fees: {nodes: [ + {table: "t", hit: "collect", inputs: ["international", "express"], outputs: ["fee"], rules: [ + ["true", "", "5"], + ["", "true", "10"], + ["", "", "1"], + ]}, + {expression: "sum", inputField: "{rows: $root}", fields: {fees: "sum(map(rows, #.fee))", count: "len(rows)"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "fees", outputPath: "fees"}], + }, + cases: [ + [{international: true, express: true}, {fees: {fees: 16, count: 3}}], + [{international: false, express: true}, {fees: {fees: 11, count: 2}}], + [{}, {fees: {fees: 1, count: 1}}], + ], +} + +{ + name: "child with a collect switch and a table on each branch", + decisions: { + flags: { + nodes: [ + {switch: "s", hit: "collect", when: ["age != null", "income != null"]}, + {table: "ageT", inputs: ["age"], outputs: ["ageBand"], rules: [["< 30", "'young'"], ["", "'older'"]]}, + {table: "incT", inputs: ["income"], outputs: ["incomeBand"], rules: [["> 100", "'high'"], ["", "'low'"]]}, + ], + edges: ["input -> s", "s:0 -> ageT -> output", "s:1 -> incT -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "flags"}], + }, + cases: [ + [{age: 20, income: 500}, {ageBand: "young", incomeBand: "high"}], + [{age: 50}, {ageBand: "older"}], + [{income: 5}, {incomeBand: "low"}], + [{}, {}], + ], +} + +{ + name: "parent switch on a child's table result", + decisions: { + classify: {nodes: [{table: "t", inputs: ["amount"], outputs: ["band"], rules: [["> 1000", "'high'"], ["", "'low'"]]}]}, + }, + graph: { + nodes: [ + {decision: "cls", key: "classify", passThrough: true}, + {switch: "s", when: ["band == 'high'", ""]}, + {expression: "review", fields: {action: "'review'", amount: "amount"}}, + {expression: "auto", fields: {action: "'auto'"}}, + ], + edges: ["input -> cls -> s", "s:0 -> review -> output", "s:1 -> auto -> output"], + }, + cases: [ + [{amount: 5000}, {action: "review", amount: 5000}], + [{amount: 10}, {action: "auto"}], + [{amount: 1000}, {action: "auto"}], + ], +} + +// --- Deep chains near the depth limit --------------------------------------------------------------- +// The root runs at depth 0. Nine nested children (depth 1-9) run; a tenth (depth 10) is refused. +{ + name: "nine nested levels each adding one", + decisions: { + l1: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1"}}, {decision: "d", key: "l2"}]}, + l2: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1"}}, {decision: "d", key: "l3"}]}, + l3: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1"}}, {decision: "d", key: "l4"}]}, + l4: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1"}}, {decision: "d", key: "l5"}]}, + l5: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1"}}, {decision: "d", key: "l6"}]}, + l6: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1"}}, {decision: "d", key: "l7"}]}, + l7: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1"}}, {decision: "d", key: "l8"}]}, + l8: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1"}}, {decision: "d", key: "l9"}]}, + l9: {nodes: [{expression: "e", passThrough: true, fields: {n: "n + 1", bottom: "true"}}]}, + }, + graph: { + nodes: [{decision: "d", key: "l1"}], + }, + cases: [ + [{n: 0}, {n: 9, bottom: true}], + [{n: 100, keep: "x"}, {n: 109, bottom: true, keep: "x"}], + [{n: "a"}, "!error"], + ], +} + +{ + name: "ten nested levels exceed the depth limit", + decisions: { + l1: {nodes: [{decision: "d", key: "l2"}]}, + l2: {nodes: [{decision: "d", key: "l3"}]}, + l3: {nodes: [{decision: "d", key: "l4"}]}, + l4: {nodes: [{decision: "d", key: "l5"}]}, + l5: {nodes: [{decision: "d", key: "l6"}]}, + l6: {nodes: [{decision: "d", key: "l7"}]}, + l7: {nodes: [{decision: "d", key: "l8"}]}, + l8: {nodes: [{decision: "d", key: "l9"}]}, + l9: {nodes: [{decision: "d", key: "l10"}]}, + l10: {nodes: [{expression: "e", fields: {reached: "true"}}]}, + }, + graph: { + nodes: [{decision: "d", key: "l1"}], + }, + cases: [ + [{}, "!error"], + [{x: 1}, "!error"], + ], +} + +{ + name: "depth limit only on the branch that goes deep", + decisions: { + l1: {nodes: [{decision: "d", key: "l2"}]}, + l2: {nodes: [{decision: "d", key: "l3"}]}, + l3: {nodes: [{decision: "d", key: "l4"}]}, + l4: {nodes: [{decision: "d", key: "l5"}]}, + l5: {nodes: [{decision: "d", key: "l6"}]}, + l6: {nodes: [{decision: "d", key: "l7"}]}, + l7: {nodes: [{decision: "d", key: "l8"}]}, + l8: {nodes: [{decision: "d", key: "l9"}]}, + l9: {nodes: [{decision: "d", key: "l10"}]}, + l10: {nodes: [{expression: "e", fields: {path: "'deep'"}}]}, + shallow: {nodes: [{expression: "e", fields: {path: "'shallow'"}}]}, + }, + graph: { + nodes: [ + {switch: "s", when: ["deep", ""]}, + {decision: "deepCall", key: "l1"}, + {decision: "shallowCall", key: "shallow"}, + ], + edges: ["input -> s", "s:0 -> deepCall -> output", "s:1 -> shallowCall -> output"], + }, + cases: [ + [{deep: false}, {path: "shallow"}], + [{}, {path: "shallow"}], + [{deep: true}, "!error"], + ], +} + +{ + name: "siblings and sequential calls do not add depth", + decisions: { + l1: {nodes: [{decision: "d", key: "l2"}]}, + l2: {nodes: [{decision: "d", key: "l3"}]}, + l3: {nodes: [{decision: "d", key: "l4"}]}, + l4: {nodes: [{decision: "d", key: "l5"}]}, + l5: {nodes: [{decision: "d", key: "l6"}]}, + l6: {nodes: [{decision: "d", key: "l7"}]}, + l7: {nodes: [{decision: "d", key: "l8"}]}, + l8: { + nodes: [ + {decision: "x", key: "leaf", outputPath: "x"}, + {decision: "y", key: "leaf", outputPath: "y"}, + {decision: "z", key: "leaf", inputField: "x", outputPath: "z"}, + ], + edges: ["input -> x -> z -> output", "input -> y -> output"], + }, + leaf: {nodes: [{expression: "e", fields: {v: "(v ?? 0) + 1"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "l1", outputPath: "a"}, + {decision: "b", key: "l1", outputPath: "b"}, + {decision: "c", key: "l1", inputField: "a.z", outputPath: "c"}, + ], + edges: ["input -> a -> c -> output", "input -> b -> output"], + }, + cases: [ + [{v: 1}, {b: {z: {v: 3}, y: {v: 2}}, c: {z: {v: 5}, y: {v: 4}}}], + [{}, {b: {z: {v: 2}, y: {v: 1}}, c: {z: {v: 4}, y: {v: 3}}}], + [{v: -2}, {b: {z: {v: 0}, y: {v: -1}}, c: {z: {v: 2}, y: {v: 1}}}], + ], +} + +{ + name: "a loop at depth nine", + decisions: { + l1: {nodes: [{decision: "d", key: "l2"}]}, + l2: {nodes: [{decision: "d", key: "l3"}]}, + l3: {nodes: [{decision: "d", key: "l4"}]}, + l4: {nodes: [{decision: "d", key: "l5"}]}, + l5: {nodes: [{decision: "d", key: "l6"}]}, + l6: {nodes: [{decision: "d", key: "l7"}]}, + l7: {nodes: [{decision: "d", key: "l8"}]}, + l8: {nodes: [{decision: "d", key: "item", inputField: "items", outputPath: "out", executionMode: "loop"}]}, + item: {nodes: [{expression: "e", fields: {sq: "n * n"}}]}, + }, + graph: { + nodes: [{decision: "d", key: "l1"}], + }, + cases: [ + [{items: [{n: 2}, {n: 3}]}, {out: [{sq: 4}, {sq: 9}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "a loop of children at the depth limit fails only when it has items", + decisions: { + l1: {nodes: [{decision: "d", key: "l2"}]}, + l2: {nodes: [{decision: "d", key: "l3"}]}, + l3: {nodes: [{decision: "d", key: "l4"}]}, + l4: {nodes: [{decision: "d", key: "l5"}]}, + l5: {nodes: [{decision: "d", key: "l6"}]}, + l6: {nodes: [{decision: "d", key: "l7"}]}, + l7: {nodes: [{decision: "d", key: "l8"}]}, + l8: {nodes: [{decision: "d", key: "l9"}]}, + l9: {nodes: [{decision: "d", key: "item", inputField: "items", outputPath: "out", executionMode: "loop"}]}, + item: {nodes: [{expression: "e", fields: {sq: "n * n"}}]}, + }, + graph: { + nodes: [{decision: "d", key: "l1"}], + }, + cases: [ + [{items: []}, {out: []}], + [{items: [{n: 2}]}, "!error"], + ], +} + +{ + name: "recursion over a list stops one call short of the limit", + decisions: { + walk: { + nodes: [ + {switch: "s", when: ["len(rest) > 0", ""]}, + {expression: "step", fields: {rest: "rest[1:]", out: "flatten([out ?? [], [upper(rest[0])]])"}}, + {decision: "again", key: "walk"}, + {expression: "end", fields: {out: "out ?? []"}}, + ], + edges: ["input -> s", "s:0 -> step -> again -> output", "s:1 -> end -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "walk"}], + }, + cases: [ + [{rest: []}, {out: []}], + [{rest: ["a", "b"]}, {out: ["A", "B"]}], + [{rest: ["a", "b", "c", "d", "e", "f", "g", "h"]}, {out: ["A", "B", "C", "D", "E", "F", "G", "H"]}], + [{rest: ["a", "b", "c", "d", "e", "f", "g", "h", "i"]}, "!error"], + ], +} + +{ + name: "depth error inside one sibling fails the whole graph", + decisions: { + forever: {nodes: [{decision: "again", key: "forever"}]}, + fine: {nodes: [{expression: "e", fields: {fine: "true"}}]}, + }, + graph: { + nodes: [ + {decision: "a", key: "fine"}, + {decision: "b", key: "forever"}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, "!error"], + [{x: 1}, "!error"], + ], +} + +// --- Realistic chains ------------------------------------------------------------------------------ +{ + name: "loan pipeline of shared children", + decisions: { + validate: {nodes: [ + {input: "in", schema: {type: "object", required: ["amount", "income"], properties: {amount: {type: "number"}, income: {type: "number"}}}}, + {expression: "e", passThrough: true, fields: {valid: "amount > 0 and income > 0"}}, + ]}, + ratio: {nodes: [{expression: "e", passThrough: true, fields: {dti: "round(amount / income * 100)"}}]}, + decide: { + nodes: [ + {switch: "s", when: ["not valid", "dti <= 30", "dti <= 50", ""]}, + {expression: "invalid", fields: {decision: "'invalid'"}}, + {expression: "approve", fields: {decision: "'approve'"}}, + {table: "manual", inputs: ["income"], outputs: ["decision"], rules: [[">= 100000", "'approve'"], ["", "'refer'"]]}, + {expression: "decline", fields: {decision: "'decline'"}}, + ], + edges: ["input -> s", "s:0 -> invalid -> output", "s:1 -> approve -> output", "s:2 -> manual -> output", "s:3 -> decline -> output"], + }, + }, + graph: { + nodes: [ + {decision: "v", key: "validate"}, + {decision: "r", key: "ratio"}, + {decision: "d", key: "decide", outputPath: "result", passThrough: true}, + ], + }, + cases: [ + [{amount: 20, income: 100}, {amount: 20, income: 100, valid: true, dti: 20, result: {decision: "approve"}}], + [{amount: 40, income: 100}, {amount: 40, income: 100, valid: true, dti: 40, result: {decision: "refer"}}], + [{amount: 40000, income: 100000}, {amount: 40000, income: 100000, valid: true, dti: 40, result: {decision: "approve"}}], + [{amount: 90, income: 100}, {amount: 90, income: 100, valid: true, dti: 90, result: {decision: "decline"}}], + [{amount: 0, income: 100}, {amount: 0, income: 100, valid: false, dti: 0, result: {decision: "invalid"}}], + [{amount: 10}, "!error"], + ], +} + +{ + name: "order with per-line child and per-order grandchild", + decisions: { + order: {nodes: [ + {decision: "lines", key: "line", inputField: "lines", outputPath: "lines", executionMode: "loop"}, + {decision: "totals", key: "totals"}, + ]}, + line: {nodes: [{expression: "e", fields: {amount: "price * qty"}}]}, + totals: {nodes: [{expression: "e", fields: {count: "len(lines)", total: "sum(map(lines, #.amount))"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "order", inputField: "order", outputPath: "summary", passThrough: true}], + }, + cases: [ + [{order: {lines: [{price: 2, qty: 3}, {price: 1.5, qty: 2}]}}, {order: {lines: [{price: 2, qty: 3}, {price: 1.5, qty: 2}]}, summary: {count: 2, total: 9}}], + [{order: {lines: []}}, {order: {lines: []}, summary: {count: 0, total: 0}}], + ], +} diff --git a/core/engine/tests/spec/graph/40-subdecision-data-flow.json5 b/core/engine/tests/spec/graph/40-subdecision-data-flow.json5 new file mode 100644 index 00000000..b75e0d63 --- /dev/null +++ b/core/engine/tests/spec/graph/40-subdecision-data-flow.json5 @@ -0,0 +1,782 @@ +// Data flow across the sub-decision boundary: what a child receives (the decision node's merged +// input, after inputField), what it sees through `$`, `$root` and `$nodes`, what comes back (the +// merge of the child's ending nodes) and how that lands next to the parent's own keys. Also +// functions and custom nodes running inside children. +// +// The child is a separate graph: its `$nodes` holds its own nodes only; the parent's nodes are +// reachable through the child's input node entry (`$nodes..$nodes`, see 15). + +// --- What the child receives --------------------------------------------------------------------- +{ + name: "child receives the output of the node before it, not the request", + decisions: { + child: {nodes: [{expression: "e", fields: {got: "v", raw: "raw"}}]}, + }, + graph: { + nodes: [ + {expression: "prep", fields: {v: "raw * 2"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{raw: 1}, {got: 2}], + [{raw: 0}, {got: 0}], + [{raw: -2.5}, {got: -5}], + ], +} + +{ + name: "child receives the merged input of a join", + decisions: { + child: {nodes: [{expression: "e", fields: {sum: "a + b", keys: "filter(keys($root), not startsWith(#, '$'))"}}]}, + }, + graph: { + nodes: [ + {expression: "pa", fields: {a: "x + 1"}}, + {expression: "pb", fields: {b: "x + 2"}}, + {decision: "call", key: "child"}, + ], + edges: ["input -> pa -> call", "input -> pb -> call", "call -> output"], + }, + cases: [ + [{x: 0}, {sum: 3, keys: ["b", "a"]}, "question: the child's root key order follows the join's merge order (later edge first), not edge order"], + [{x: 10}, {sum: 23, keys: ["b", "a"]}, "question: the child's root key order follows the join's merge order (later edge first), not edge order"], + ], +} + +{ + name: "child $root is its input object", + decisions: { + child: {nodes: [{expression: "e", fields: {root: "$root", n: "len(filter(keys($root), not startsWith(#, '$')))"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub", outputPath: "out"}], + }, + cases: [ + [{sub: {a: 1}}, {out: {root: {a: 1}, n: 1}}], + [{sub: {}}, {out: {root: {}, n: 0}}], + [{sub: {a: {b: [1]}, c: "x"}}, {out: {root: {a: {b: [1]}, c: "x"}, n: 2}}], + ], +} + +{ + name: "child input keeps every value type", + decisions: { + child: {nodes: [{expression: "e", fields: {types: "map(['s', 'n', 'b', 'a', 'o', 'z'], type($root[#]))"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{s: "x", n: 1.5, b: false, a: [1], o: {k: 1}, z: null}, {out: {types: ["string", "number", "bool", "array", "object", "null"]}}], + [{}, {out: {types: ["null", "null", "null", "null", "null", "null"]}}], + ], +} + +{ + name: "child request with a date and nested arrays", + decisions: { + child: {nodes: [{expression: "e", fields: {year: "d(when).year()", total: "sum(flatten(groups))"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{when: "2024-02-29", groups: [[1, 2], [3]]}, {out: {year: 2024, total: 6}}], + [{when: "1999-12-31T23:59:59Z", groups: []}, {out: {year: 1999, total: 0}}], + ], +} + +{ + name: "child input node with a schema receives the inputField selection", + decisions: { + child: {nodes: [ + {input: "req", schema: {type: "object", required: ["id"], properties: {id: {type: "string"}}}}, + {expression: "e", fields: {id: "$nodes.req.id", same: "$nodes.req.id == id"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "customer", outputPath: "out"}], + }, + cases: [ + [{customer: {id: "c1"}}, {out: {id: "c1", same: true}}], + [{customer: {id: "c2", extra: 1}, id: 9}, {out: {id: "c2", same: true}}], + [{customer: {id: 1}}, "!error"], + ], +} + +// --- What comes back -------------------------------------------------------------------------------- +{ + name: "only the child's ending nodes come back", + decisions: { + child: {nodes: [ + {expression: "step1", fields: {internal: "x + 1"}}, + {expression: "step2", fields: {result: "internal * 2"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 1}, {result: 4}], + [{x: -1}, {result: 0}], + ], +} + +{ + name: "child pass-through chain returns the parent's input plus its keys", + decisions: { + child: {nodes: [ + {expression: "a", passThrough: true, fields: {fromA: "1"}}, + {expression: "b", passThrough: true, fields: {fromB: "2"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 1}, {x: 1, fromA: 1, fromB: 2}], + [{fromA: "old"}, {fromA: 1, fromB: 2}], + [{}, {fromA: 1, fromB: 2}], + ], +} + +{ + name: "child output node joins several branches", + decisions: { + child: { + nodes: [ + {expression: "a", fields: {"r.a": "x"}}, + {expression: "b", fields: {"r.b": "x * 2"}}, + {expression: "c", fields: {c: "true"}}, + ], + edges: ["input -> a -> output", "input -> b -> output", "input -> c -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "res"}], + }, + cases: [ + [{x: 1}, {res: {r: {a: 1, b: 2}, c: true}}], + [{x: 0}, {res: {r: {a: 0, b: 0}, c: true}}], + ], +} + +{ + name: "child with a dangling branch drops it from the result", + decisions: { + child: {raw: { + nodes: [ + {id: "i", name: "in", type: "inputNode", content: {}}, + {id: "a", name: "main", type: "expressionNode", content: {expressions: [{id: "x1", key: "main", value: "true"}], passThrough: false}}, + {id: "b", name: "side", type: "expressionNode", content: {expressions: [{id: "x2", key: "side", value: "true"}], passThrough: false}}, + {id: "o", name: "out", type: "outputNode", content: {}}, + ], + edges: [ + {id: "e1", sourceId: "i", targetId: "a"}, + {id: "e2", sourceId: "a", targetId: "o"}, + {id: "e3", sourceId: "i", targetId: "b"}, + ], + }}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{}, {main: true}, "question: the child stops at its output node; a side branch that never reaches the output is not part of the result"], + [{x: 1}, {main: true}, "question: the child stops at its output node; a side branch that never reaches the output is not part of the result"], + ], +} + +{ + name: "parent $nodes of the decision node includes its transforms", + decisions: { + child: {nodes: [{expression: "e", fields: {r: "v * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", outputPath: "res", passThrough: true}, + {expression: "after", fields: {node: "$nodes.call", r: "$nodes.call.res.r"}}, + ], + }, + cases: [ + [{v: 1}, {node: {v: 1, res: {r: 2}}, r: 2}], + [{v: 0, k: "x"}, {node: {v: 0, k: "x", res: {r: 0}}, r: 0}], + ], +} + +{ + name: "parent $nodes of a looping decision node is the array", + decisions: { + child: {nodes: [{expression: "e", fields: {r: "v + 1"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", inputField: "items", executionMode: "loop"}, + {expression: "after", fields: {n: "len($nodes.call)", first: "$nodes.call[0].r"}}, + ], + edges: ["input -> call", "input -> after -> output", "call -> after"], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {n: 2, first: 2}], + [{items: [{v: 9}]}, {n: 1, first: 10}], + ], +} + +{ + name: "parent reads $nodes.input after a child changed the same keys", + decisions: { + child: {nodes: [{expression: "e", passThrough: true, fields: {"a.b": "a.b + 1", n: "n * 10"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {expression: "after", fields: {now: "a.b", n: "n", origB: "$nodes.input.a.b", origN: "$nodes.input.n"}}, + ], + }, + cases: [ + [{a: {b: 1}, n: 2}, {now: 2, n: 20, origB: 1, origN: 2}], + [{a: {b: -1, c: 3}, n: 0}, {now: 0, n: 0, origB: -1, origN: 0}], + ], +} + +// --- Key collisions between child output and parent ---------------------------------------------------- +{ + name: "child key replaces a parent key of another type", + decisions: { + child: {nodes: [{expression: "e", fields: {v: "'child'"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{v: 1}, {v: "child"}], + [{v: {deep: true}}, {v: "child"}], + [{v: [1, 2]}, {v: "child"}], + [{v: null}, {v: "child"}], + ], +} + +{ + name: "child object merges into a parent object of the same name", + decisions: { + child: {nodes: [{expression: "e", fields: {"cfg.mode": "'strict'", "cfg.limits.max": "10"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", passThrough: true}], + }, + cases: [ + [{cfg: {mode: "lax", name: "x"}}, {cfg: {mode: "strict", name: "x", limits: {max: 10}}}], + [{cfg: {limits: {min: 1, max: 99}}}, {cfg: {mode: "strict", limits: {min: 1, max: 10}}}], + [{cfg: "flat"}, {cfg: {mode: "strict", limits: {max: 10}}}], + [{}, {cfg: {mode: "strict", limits: {max: 10}}}], + ], +} + +{ + name: "child keys collide with a parallel parent branch at the output", + decisions: { + child: {nodes: [{expression: "e", fields: {status: "'child'", c: "true"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {expression: "local", fields: {status: "'local'", l: "true"}}, + ], + edges: ["input -> call -> output", "input -> local -> output"], + }, + cases: [ + [{}, {status: "child", c: true, l: true}, "question: at the output fan-in the first-listed branch wins a shared key (the child here); nothing in the graph makes the precedence visible"], + [{status: "req"}, {status: "child", c: true, l: true}, "question: at the output fan-in the first-listed branch wins a shared key (the child here); nothing in the graph makes the precedence visible"], + ], +} + +{ + name: "child key collides with an outputPath segment", + decisions: { + child: {nodes: [{expression: "e", fields: {res: "'flat'"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {decision: "nested", key: "child", outputPath: "res.inner"}, + ], + edges: ["input -> call -> output", "input -> nested -> output"], + }, + cases: [ + [{}, {res: "flat"}, "question: a scalar from the first branch and an object from the second meet at the output; the scalar wins because the second branch is merged first"], + ], +} + +{ + name: "child returning a $nodes key", + decisions: { + child: {nodes: [{custom: "c", kind: "echo"}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", outputPath: "out"}, + {expression: "after", fields: {keys: "keys($nodes.call.out)"}}, + ], + }, + cases: [ + [{x: 1}, {keys: ["x", "$nodes"]}, "question: an echo custom node inside the child forwards its `$nodes` map as a regular key, which survives the child's result and reaches the parent (see 15)"], + ], +} + +{ + name: "child $nodes key dropped from the final result", + decisions: { + child: {nodes: [{custom: "c", kind: "echo"}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{x: 1}, {out: {x: 1}}], + [{}, {out: {}}], + ], +} + +{ + name: "child result with the same key as the decision node name", + decisions: { + child: {nodes: [{expression: "e", fields: {call: "'value'"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {expression: "after", fields: {field: "call", node: "$nodes.call.call"}}, + ], + }, + cases: [ + [{}, {field: "value", node: "value"}], + [{call: 1}, {field: "value", node: "value"}], + ], +} + +// --- The child's own $nodes ------------------------------------------------------------------------------ +{ + name: "child node names shadow nothing in the parent", + decisions: { + child: {nodes: [ + {expression: "calc", fields: {v: "x * 100"}}, + {expression: "read", fields: {mine: "$nodes.calc.v"}}, + ]}, + }, + graph: { + nodes: [ + {expression: "calc", passThrough: true, fields: {v: "x + 1"}}, + {decision: "call", key: "child", passThrough: true}, + {expression: "read", fields: {parentCalc: "$nodes.calc.v", childRead: "mine"}}, + ], + }, + cases: [ + [{x: 1}, {parentCalc: 2, childRead: 100}], + [{x: 0}, {parentCalc: 1, childRead: 0}], + ], +} + +{ + name: "child $nodes.input is the child's own input", + decisions: { + child: {nodes: [{expression: "e", fields: {childInput: "$nodes.input", hasParentKey: "$nodes.input.top != null"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub", outputPath: "out"}], + }, + cases: [ + [{top: 1, sub: {a: 1}}, {out: {childInput: {a: 1}, hasParentKey: false}}], + [{top: 1, sub: {}}, {out: {childInput: {}, hasParentKey: false}}], + ], +} + +{ + name: "child $nodes in a loop belongs to the current item", + decisions: { + child: {nodes: [ + {expression: "first", fields: {v: "n * 2"}}, + {expression: "second", fields: {v: "$nodes.first.v + $nodes.input.n", item: "$nodes.input"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{n: 1}, {n: 2}]}, {out: [{v: 3, item: {n: 1}}, {v: 6, item: {n: 2}}]}], + [{items: [{n: 0}]}, {out: [{v: 0, item: {n: 0}}]}], + ], +} + +{ + name: "child $nodes of an untaken branch is null per item", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["flag", ""]}, + {expression: "yes", fields: {y: "true"}}, + {expression: "no", fields: {n: "true"}}, + {expression: "end", fields: {ranYes: "$nodes.yes != null", ranNo: "$nodes.no != null"}}, + ], + edges: ["input -> s", "s:0 -> yes -> end", "s:1 -> no -> end", "end -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{flag: true}, {flag: false}, {flag: true}]}, {out: [{ranYes: true, ranNo: false}, {ranYes: false, ranNo: true}, {ranYes: true, ranNo: false}]}], + [{items: [{}]}, {out: [{ranYes: false, ranNo: true}]}], + ], +} + +{ + name: "child keys($nodes) lists only the child's nodes", + decisions: { + child: {nodes: [ + {expression: "a", passThrough: true, fields: {a: "1"}}, + {expression: "b", fields: {n: "len(keys($nodes))", a: "'a' in keys($nodes)", input: "'input' in keys($nodes)", parent: "'parentOnly' in keys($nodes)"}}, + ]}, + }, + graph: { + nodes: [ + {expression: "parentOnly", passThrough: true, fields: {p: "1"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{}, {n: 2, a: true, input: true, parent: false}], + [{x: 1}, {n: 2, a: true, input: true, parent: false}], + ], +} + +{ + name: "child table reading its own $nodes", + decisions: { + child: {nodes: [ + {expression: "limits", fields: {max: "cap ?? 100"}}, + {table: "t", inputs: ["$nodes.input.amount"], outputs: ["ok"], rules: [["<= $nodes.limits.max", "true"], ["", "false"]]}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "check"}], + }, + cases: [ + [{amount: 50}, {check: {ok: true}}], + [{amount: 150}, {check: {ok: false}}], + [{amount: 150, cap: 200}, {check: {ok: true}}], + [{amount: 100}, {check: {ok: true}}], + ], +} + +{ + name: "child switch reading its own $nodes", + decisions: { + child: { + nodes: [ + {expression: "score", passThrough: true, fields: {s: "a + b"}}, + {switch: "sw", when: ["$nodes.score.s > 10", ""]}, + {expression: "hi", fields: {r: "'hi'"}}, + {expression: "lo", fields: {r: "'lo'"}}, + ], + edges: ["input -> score -> sw", "sw:0 -> hi -> output", "sw:1 -> lo -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{a: 5, b: 6}, {r: "hi"}], + [{a: 5, b: 5}, {r: "lo"}], + [{a: 0, b: 0}, {r: "lo"}], + ], +} + +{ + name: "child reads a parent node through its input node in a loop and a single call", + decisions: { + child: {nodes: [ + {input: "in"}, + {expression: "e", fields: {v: "n * ($nodes.in.$nodes.cfg.k ?? 1)"}}, + ]}, + }, + graph: { + nodes: [ + {expression: "cfg", passThrough: true, fields: {k: "k ?? 3"}}, + {decision: "one", key: "child", inputField: "single", outputPath: "single"}, + {decision: "many", key: "child", inputField: "items", outputPath: "items", executionMode: "loop"}, + ], + edges: ["input -> cfg", "cfg -> one -> output", "cfg -> many -> output"], + }, + cases: [ + [{single: {n: 2}, items: [{n: 1}, {n: 4}]}, {single: {v: 6}, items: [{v: 3}, {v: 12}]}], + [{k: 10, single: {n: 1}, items: []}, {single: {v: 10}, items: []}], + ], +} + +// --- Functions inside children --------------------------------------------------------------------------- +{ + name: "v2 function in a child computes from the child input", + decisions: { + child: {nodes: [{function: "f", source: """export const handler = async (input) => ({ + names: input.people.map((p) => p.name.toUpperCase()), + count: input.people.length, +});"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out", passThrough: true}], + }, + cases: [ + [{people: [{name: "ann"}, {name: "bo"}]}, {people: [{name: "ann"}, {name: "bo"}], out: {names: ["ANN", "BO"], count: 2}}], + [{people: []}, {people: [], out: {names: [], count: 0}}], + ], +} + +{ + name: "v2 function in a child reads the child's $nodes", + decisions: { + child: {nodes: [ + {expression: "calc", fields: {t: "a * b"}}, + {function: "f", source: """export const handler = async (input) => ({t: input.$nodes.calc.t, a: input.$nodes.input.a, nodes: Object.keys(input.$nodes).sort()});"""}, + ]}, + }, + graph: { + nodes: [ + {expression: "outer", passThrough: true, fields: {o: "1"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{a: 2, b: 3}, {t: 6, a: 2, nodes: ["calc", "input"]}], + [{a: 0, b: 3}, {t: 0, a: 0, nodes: ["calc", "input"]}], + ], +} + +{ + name: "v2 function in a child throwing fails the parent", + decisions: { + child: {nodes: [{function: "f", source: """export const handler = async (input) => { + if (input.n < 0) throw new Error('negative input'); + return {sqrt: Math.sqrt(input.n)}; +};"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{n: 9}, {out: {sqrt: 3}}], + [{n: 0}, {out: {sqrt: 0}}], + [{n: -1}, "!error: negative input"], + ], +} + +{ + name: "v2 function in a looped child", + decisions: { + child: {nodes: [{function: "f", source: """export const handler = async (input) => ({id: input.id, slug: String(input.title).toLowerCase().replace(/\s+/g, '-')});"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "posts", outputPath: "posts", executionMode: "loop"}], + }, + cases: [ + [{posts: [{id: 1, title: "Hello World"}, {id: 2, title: "A B"}]}, {posts: [{id: 1, slug: "hello-world"}, {id: 2, slug: "a-b"}]}], + [{posts: []}, {posts: []}], + ], +} + +{ + name: "v2 function in a child returning an array", + decisions: { + child: {nodes: [{function: "f", source: """export const handler = async (input) => input.xs.map((x) => ({x2: x * 2}));"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "out"}], + }, + cases: [ + [{xs: [1, 2]}, {out: [{x2: 2}, {x2: 4}]}], + [{xs: []}, {out: []}], + ], +} + +{ + name: "v2 function in a child mutating its input does not change the parent", + decisions: { + child: {nodes: [{function: "f", source: """export const handler = async (input) => { + input.data.v = 'changed'; + input.data.list.push(99); + return {done: true}; +};"""}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", passThrough: true}, + {expression: "after", fields: {v: "data.v", list: "data.list", done: "done"}}, + ], + }, + cases: [ + [{data: {v: "orig", list: [1]}}, {v: "orig", list: [1], done: true}], + [{data: {v: 1, list: []}}, {v: 1, list: [], done: true}], + ], +} + +{ + name: "v1 function in a child", + decisions: { + child: {nodes: [{functionV1: "f", source: """const handler = (input) => ({total: input.items.reduce((s, i) => s + i.price, 0)});"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "cart", outputPath: "cart", passThrough: true}], + }, + cases: [ + [{cart: {items: [{price: 2}, {price: 3}]}}, {cart: {items: [{price: 2}, {price: 3}], total: 5}}], + [{cart: {items: []}}, {cart: {items: [], total: 0}}], + ], +} + +{ + name: "function result passes through a child then a parent expression", + decisions: { + child: {nodes: [ + {function: "f", source: """export const handler = async (input) => ({score: input.a * 2 + 1, tag: input.a > 2 ? 'big' : 'small'});"""}, + {expression: "e", passThrough: true, fields: {final: "score * 10"}}, + ]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", outputPath: "res"}, + {expression: "after", fields: {final: "res.final", tag: "res.tag"}}, + ], + }, + cases: [ + [{a: 1}, {final: 30, tag: "small"}], + [{a: 3}, {final: 70, tag: "big"}], + ], +} + +// --- Custom nodes inside children -------------------------------------------------------------------------- +{ + name: "custom render in a child sees the child's input", + decisions: { + child: {nodes: [{custom: "c", kind: "render", config: {line: "{{ name }} owes {{ amount }}"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "invoice", outputPath: "msg"}], + }, + cases: [ + [{invoice: {name: "ann", amount: 5}, name: "outer"}, {msg: {line: "ann owes 5"}}], + [{invoice: {name: "bo", amount: 0.5}}, {msg: {line: "bo owes 0.5"}}], + ], +} + +{ + name: "custom render in a child reads the child's $nodes", + decisions: { + child: {nodes: [ + {expression: "calc", fields: {v: "x * 3"}}, + {custom: "c", kind: "render", config: {line: "{{ $nodes.calc.v }}/{{ $nodes.input.x }}"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{x: 2}, {line: "6/2"}], + [{x: 0}, {line: "0/0"}], + ], +} + +{ + name: "custom config node in a child returns its config", + decisions: { + child: {nodes: [{custom: "c", kind: "config", config: {version: 3, flags: ["a", "b"]}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "cfg", passThrough: true}], + }, + cases: [ + [{x: 1}, {x: 1, cfg: {version: 3, flags: ["a", "b"]}}], + [{cfg: {old: true}}, {cfg: {old: true, version: 3, flags: ["a", "b"]}}], + ], +} + +{ + name: "custom echo in a child returns the child input", + decisions: { + child: {nodes: [{custom: "c", kind: "echo"}]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "sub", outputPath: "copy", passThrough: true}], + }, + cases: [ + [{sub: {a: 1}}, {sub: {a: 1}, copy: {a: 1}}], + [{sub: {}}, {sub: {}, copy: {}}], + ], +} + +{ + name: "custom fail in a looped child stops at the failing item", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["valid", ""]}, + {custom: "ok", kind: "render", config: {msg: "item {{ id }}"}}, + {custom: "bad", kind: "fail", config: {message: "invalid item"}}, + ], + edges: ["input -> s", "s:0 -> ok -> output", "s:1 -> bad -> output"], + }, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{valid: true, id: 1}, {valid: true, id: 2}]}, {out: [{msg: "item 1"}, {msg: "item 2"}]}], + [{items: [{valid: true, id: 1}, {valid: false, id: 2}]}, "!error: invalid item"], + [{items: []}, {out: []}], + ], +} + +// --- Realistic data flow ------------------------------------------------------------------------------------ +{ + name: "enrich in a child, decide in the parent", + decisions: { + enrich: {nodes: [ + {table: "region", inputs: ["country"], outputs: ["region"], rules: [["'DE','FR','IT'", "'EU'"], ["'US','CA'", "'NA'"], ["", "'ROW'"]]}, + {function: "f", source: """export const handler = async (input) => ({region: input.region, local: input.$nodes.input.lang === 'de'});"""}, + ]}, + }, + graph: { + nodes: [ + {decision: "enrich", key: "enrich", inputField: "customer", outputPath: "customer", passThrough: true}, + {switch: "s", when: ["customer.region == 'EU'", ""]}, + {expression: "eu", fields: {vat: "true", local: "customer.local"}}, + {expression: "other", fields: {vat: "false"}}, + ], + edges: ["input -> enrich -> s", "s:0 -> eu -> output", "s:1 -> other -> output"], + }, + cases: [ + [{customer: {country: "DE", lang: "de"}}, {vat: true, local: true}], + [{customer: {country: "FR", lang: "fr"}}, {vat: true, local: false}], + [{customer: {country: "US"}}, {vat: false}], + [{customer: {}}, {vat: false}], + ], +} + +{ + name: "child result feeds a parent table and a second child", + decisions: { + score: {nodes: [{expression: "e", fields: {score: "round(income / 1000) - debts"}}]}, + label: {nodes: [{expression: "e", fields: {label: "band + '-' + string(score)"}}]}, + }, + graph: { + nodes: [ + {decision: "s", key: "score", passThrough: true}, + {table: "band", passThrough: true, inputs: ["score"], outputs: ["band"], rules: [[">= 50", "'A'"], [">= 20", "'B'"], ["", "'C'"]]}, + {decision: "l", key: "label"}, + ], + }, + cases: [ + [{income: 80000, debts: 10}, {label: "A-70"}], + [{income: 30000, debts: 5}, {label: "B-25"}], + [{income: 1000, debts: 5}, {label: "C--4"}], + ], +} diff --git a/core/engine/tests/spec/graph/41-functions-isolation.json5 b/core/engine/tests/spec/graph/41-functions-isolation.json5 new file mode 100644 index 00000000..a01dfe3b --- /dev/null +++ b/core/engine/tests/spec/graph/41-functions-isolation.json5 @@ -0,0 +1,1358 @@ +// Function node isolation: every evaluation of a v2 function node behaves as if it ran in a +// fresh JS runtime. Nothing a handler does (module-level `let`/`var`, mutated `const` objects, +// globals, prototypes, imported module settings, top-level side effects) is visible to another +// evaluation. The compiled engine runs batch rows of shareable sources in one runtime and gives +// sources with module state or global access a fresh runtime per row +// (`nodes/function/v2/isolation.rs`); the batch runner cycles each suite's cases three times, +// so state that survives a row shows up as a mismatch against the walker. Every case below is +// written as an independent evaluation: rows that could observe a previous row expect the +// first-run answer. + +// --- Stateless sources share a runtime safely ------------------------------------------------ +// No module state: plain handlers, scalar constants, helper functions, imports. The results +// must not depend on which rows ran before. + +{ + name: "isolation: a plain arrow handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { let x = input.v ?? 0; x += 1; return { x }; };"""}], + }, + cases: [ + [{v: 1}, {x: 2}], + [{v: 10}, {x: 11}], + [{}, {x: 1}], + [{v: -1}, {x: 0}], + ], +} + +{ + name: "isolation: a scalar module constant", + graph: { + nodes: [{function: "f", source: """const RATE = 0.2; +const LABEL = 'tax'; +export const handler = async (input) => ({ [LABEL]: input.amount * RATE });"""}], + }, + cases: [ + [{amount: 100}, {tax: 20}], + [{amount: 5}, {tax: 1}], + [{amount: 0}, {tax: 0}], + [{amount: -50}, {tax: -10}], + ], +} + +{ + name: "isolation: a constant computed from other constants", + graph: { + nodes: [{function: "f", source: """const BASE = 10 +const LIMIT = BASE * 2 + 1 +const NAME = `limit-${LIMIT}` +export const handler = (input) => ({ over: input.v > LIMIT, name: NAME })"""}], + }, + cases: [ + [{v: 22}, {over: true, name: "limit-21"}], + [{v: 21}, {over: false, name: "limit-21"}], + [{v: 0}, {over: false, name: "limit-21"}], + ], +} + +{ + name: "isolation: helper function declarations", + graph: { + nodes: [{function: "f", source: """function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); } +async function double(v) { return v * 2; } +export const handler = async (input) => ({ v: clamp(await double(input.v), 0, 100) });"""}], + }, + cases: [ + [{v: 10}, {v: 20}], + [{v: 70}, {v: 100}], + [{v: -3}, {v: 0}], + [{v: 50}, {v: 100}], + ], +} + +{ + name: "isolation: a const arrow helper", + graph: { + nodes: [{function: "f", source: """const pct = (v, p) => Math.round(v * p) / 100; +export const handler = async (input) => ({ fee: pct(input.amount, input.rate ?? 3) });"""}], + }, + cases: [ + [{amount: 200}, {fee: 6}], + [{amount: 200, rate: 10}, {fee: 20}], + [{amount: 0}, {fee: 0}], + ], +} + +{ + name: "isolation: an export function declaration handler with helpers", + graph: { + nodes: [{function: "f", source: """function grade(score) { + if (score >= 90) return 'A'; + if (score >= 75) return 'B'; + return 'C'; +} +export async function handler(input) { + return { grades: input.scores.map(grade) }; +}"""}], + }, + cases: [ + [{scores: [95, 80, 10]}, {grades: ["A", "B", "C"]}], + [{scores: []}, {grades: []}], + [{scores: [75]}, {grades: ["B"]}], + ], +} + +{ + name: "isolation: a zod schema declared at module level", + graph: { + nodes: [{function: "f", source: """import { z } from 'zod'; +const Order = z.object({ + id: z.string().min(1), + qty: z.number().int().positive(), + tags: z.array(z.string()).default([]), +}); +export const handler = async (input) => { + const r = Order.safeParse(input.order); + return r.success ? { ok: true, order: r.data } : { ok: false, issues: r.error.issues.length }; +};"""}], + }, + cases: [ + [{order: {id: "a", qty: 2}}, {ok: true, order: {id: "a", qty: 2, tags: []}}], + [{order: {id: "", qty: 2}}, {ok: false, issues: 1}], + [{order: {id: "b", qty: 1, tags: ["x"]}}, {ok: true, order: {id: "b", qty: 1, tags: ["x"]}}], + [{order: {id: "", qty: -1}}, {ok: false, issues: 2}], + [{}, {ok: false, issues: 1}], + ], +} + +{ + name: "isolation: a zod schema with a transform declared at module level", + graph: { + nodes: [{function: "f", source: """import { z } from 'zod'; +const Name = z.string().trim().transform((s) => s.toUpperCase()); +export const handler = async (input) => ({ name: Name.parse(input.name) });"""}], + }, + cases: [ + [{name: " ann "}, {name: "ANN"}], + [{name: "bo"}, {name: "BO"}], + [{name: 1}, "!error"], + [{name: ""}, {name: ""}], + ], +} + +{ + name: "isolation: imports of big.js and dayjs without module state", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +import dayjs from 'dayjs'; +const START = '2024-01-01'; +export const handler = async (input) => ({ + total: new Big(input.a).plus(input.b).toString(), + day: dayjs(START).add(input.days, 'day').format('YYYY-MM-DD'), +});"""}], + }, + cases: [ + [{a: 0.1, b: 0.2, days: 1}, {total: "0.3", day: "2024-01-02"}], + [{a: 1, b: 1, days: 31}, {total: "2", day: "2024-02-01"}], + [{a: -1, b: 0.5, days: 0}, {total: "-0.5", day: "2024-01-01"}], + ], +} + +{ + name: "isolation: words like globalThis inside strings and comments", + graph: { + nodes: [{function: "f", source: """// let counter = 0; globalThis.x = 1; +/* var hits = 0 */ +const WORD = 'globalThis'; +export const handler = async (input) => ({ word: WORD, msg: `no prototype ${input.v} here` });"""}], + }, + cases: [ + [{v: 1}, {word: "globalThis", msg: "no prototype 1 here"}], + [{v: "x"}, {word: "globalThis", msg: "no prototype x here"}], + ], +} + +{ + name: "isolation: an identifier that only contains a shared-state word", + graph: { + nodes: [{function: "f", source: """const selfTest = (v) => v === 1; +const evaluation = 'ok'; +export const handler = async (input) => ({ selfTest: selfTest(input.v), evaluation });"""}], + }, + cases: [ + [{v: 1}, {selfTest: true, evaluation: "ok"}], + [{v: 2}, {selfTest: false, evaluation: "ok"}], + ], +} + +{ + name: "isolation: a top-level await on a constant", + graph: { + nodes: [{function: "f", source: """const SEED = await Promise.resolve(7); +export const handler = async (input) => ({ v: input.v + SEED });"""}], + }, + cases: [ + [{v: 1}, {v: 8}], + [{v: -7}, {v: 0}], + [{v: 0.5}, {v: 7.5}], + ], +} + +{ + name: "isolation: TypeScript annotations on module constants", + graph: { + nodes: [{function: "f", source: """const FACTOR: number = 3; +type Out = { v: number }; +export const handler = async (input: any): Promise => ({ v: input.v * FACTOR });"""}], + }, + cases: [ + [{v: 1}, {v: 3}], + [{v: 2}, {v: 6}], + [{v: 0}, {v: 0}], + ], +} + +// --- Module-level let and var ---------------------------------------------------------------- +// Mutable bindings at module level would count rows if the module instance survived. + +{ + name: "isolation: a module let counter", + graph: { + nodes: [{function: "f", source: """let count = 0; +export const handler = async (input) => { count += 1; return { count, v: input.v }; };"""}], + }, + cases: [ + [{v: 1}, {count: 1, v: 1}], + [{v: 2}, {count: 1, v: 2}], + [{v: 3}, {count: 1, v: 3}], + ], +} + +{ + name: "isolation: a module var counter without semicolons", + graph: { + nodes: [{function: "f", source: """var hits = 0 +export const handler = (input) => ({ hits: ++hits, v: input.v })"""}], + }, + cases: [ + [{v: "a"}, {hits: 1, v: "a"}], + [{v: "b"}, {hits: 1, v: "b"}], + [{}, {hits: 1}], + ], +} + +{ + name: "isolation: a lazily initialised module let", + graph: { + nodes: [{function: "f", source: """let cached; +export const handler = async (input) => { + const fresh = cached === undefined; + cached ??= input.v; + return { fresh, cached }; +};"""}], + }, + cases: [ + [{v: 1}, {fresh: true, cached: 1}], + [{v: 2}, {fresh: true, cached: 2}], + [{v: "x"}, {fresh: true, cached: "x"}], + ], +} + +{ + name: "isolation: an exported let", + graph: { + nodes: [{function: "f", source: """export let total = 0; +export const handler = async (input) => { total += input.v; return { total }; };"""}], + }, + cases: [ + [{v: 5}, {total: 5}], + [{v: 10}, {total: 10}], + [{v: -1}, {total: -1}], + ], +} + +{ + name: "isolation: a let declared after the handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { seen.push(input.v); return { seen: [...seen] }; }; +let seen = [];"""}], + }, + cases: [ + [{v: 1}, {seen: [1]}], + [{v: 2}, {seen: [2]}], + [{v: 3}, {seen: [3]}], + ], +} + +{ + name: "isolation: several let bindings in one declaration", + graph: { + nodes: [{function: "f", source: """let a = 0, b = 100; +export const handler = async (input) => { a += input.v; b -= input.v; return { a, b }; };"""}], + }, + cases: [ + [{v: 1}, {a: 1, b: 99}], + [{v: 2}, {a: 2, b: 98}], + [{v: 0}, {a: 0, b: 100}], + ], +} + +{ + name: "isolation: a let holding the previous input", + graph: { + nodes: [{function: "f", source: """let previous = null; +export const handler = async (input) => { + const out = { previous, changed: previous !== null && previous !== input.v }; + previous = input.v; + return out; +};"""}], + }, + cases: [ + [{v: 1}, {changed: false}], + [{v: 2}, {changed: false}], + [{v: 1}, {changed: false}], + ], +} + +// --- Module-level const objects mutated by the handler --------------------------------------- +// `const` only freezes the binding; the object behind it is per evaluation. + +{ + name: "isolation: a const Map used as a cache", + graph: { + nodes: [{function: "f", source: """const cache = new Map(); +export const handler = async (input) => { + const hit = cache.has(input.key); + cache.set(input.key, (cache.get(input.key) ?? 0) + 1); + return { hit, size: cache.size }; +};"""}], + }, + cases: [ + [{key: "a"}, {hit: false, size: 1}], + [{key: "b"}, {hit: false, size: 1}], + [{key: "a"}, {hit: false, size: 1}], + ], +} + +{ + name: "isolation: a const Set of seen ids", + graph: { + nodes: [{function: "f", source: """const seen = new Set(); +export const handler = async (input) => { + const duplicate = input.ids.some((id) => seen.has(id) || !seen.add(id)); + return { duplicate, seen: seen.size }; +};"""}], + }, + cases: [ + [{ids: [1, 2]}, {duplicate: false, seen: 2}], + [{ids: [2, 3]}, {duplicate: false, seen: 2}], + [{ids: [4, 4]}, {duplicate: true, seen: 1}], + ], +} + +{ + name: "isolation: a const object literal mutated by the handler", + graph: { + nodes: [{function: "f", source: """const state = { calls: 0, last: null }; +export const handler = async (input) => { + state.calls += 1; + const last = state.last; + state.last = input.v; + return { calls: state.calls, hadLast: last !== null }; +};"""}], + }, + cases: [ + [{v: 1}, {calls: 1, hadLast: false}], + [{v: 2}, {calls: 1, hadLast: false}], + [{v: 3}, {calls: 1, hadLast: false}], + ], +} + +{ + name: "isolation: a const array appended to by the handler", + graph: { + nodes: [{function: "f", source: """const log = []; +export const handler = async (input) => { log.push(input.v); return { log: log.slice() }; };"""}], + }, + cases: [ + [{v: "a"}, {log: ["a"]}], + [{v: "b"}, {log: ["b"]}], + [{v: "c"}, {log: ["c"]}], + ], +} + +{ + name: "isolation: a const Map split across lines", + graph: { + nodes: [{function: "f", source: """const totals = + new Map(); +export const handler = async (input) => { + totals.set('sum', (totals.get('sum') ?? 0) + input.v); + return { sum: totals.get('sum') }; +};"""}], + }, + cases: [ + [{v: 1}, {sum: 1}], + [{v: 2}, {sum: 2}], + [{v: 3}, {sum: 3}], + ], +} + +{ + name: "isolation: a const array built by a top-level loop", + graph: { + nodes: [{function: "f", source: """const squares = []; +for (let i = 1; i <= 3; i++) squares.push(i * i); +export const handler = async (input) => { squares.push(input.v); return { squares: [...squares] }; };"""}], + }, + cases: [ + [{v: 0}, {squares: [1, 4, 9, 0]}], + [{v: 100}, {squares: [1, 4, 9, 100]}], + [{v: -1}, {squares: [1, 4, 9, -1]}], + ], +} + +{ + name: "isolation: a mutable array hidden behind a scalar const in one declaration", + graph: { + nodes: [{function: "f", source: """const LIMIT = 5, queue = []; +export const handler = async (input) => { queue.push(input.v); return { queued: queue.length, full: queue.length >= LIMIT }; };"""}], + }, + cases: [ + [{v: 1}, {queued: 1, full: false}], + [{v: 2}, {queued: 1, full: false}], + [{v: 3}, {queued: 1, full: false}], + ], +} + +{ + name: "isolation: a const object made by Object.create", + graph: { + nodes: [{function: "f", source: """const registry = Object.create(null); +export const handler = async (input) => { + const known = input.name in registry; + registry[input.name] = true; + return { known, count: Object.keys(registry).length }; +};"""}], + }, + cases: [ + [{name: "a"}, {known: false, count: 1}], + [{name: "b"}, {known: false, count: 1}], + [{name: "a"}, {known: false, count: 1}], + ], +} + +{ + name: "isolation: a const object parsed from JSON", + graph: { + nodes: [{function: "f", source: """const defaults = JSON.parse('{"count":0,"items":[]}'); +export const handler = async (input) => { + defaults.count += 1; + defaults.items.push(input.v); + return { count: defaults.count, items: defaults.items.slice() }; +};"""}], + }, + cases: [ + [{v: 1}, {count: 1, items: [1]}], + [{v: 2}, {count: 1, items: [2]}], + [{v: 3}, {count: 1, items: [3]}], + ], +} + +{ + name: "isolation: a const array made by Array.from", + graph: { + nodes: [{function: "f", source: """const slots = Array.from({ length: 3 }, () => 0); +export const handler = async (input) => { slots[input.i] += 1; return { slots: [...slots] }; };"""}], + }, + cases: [ + [{i: 0}, {slots: [1, 0, 0]}], + [{i: 1}, {slots: [0, 1, 0]}], + [{i: 0}, {slots: [1, 0, 0]}], + ], +} + +{ + name: "isolation: a const Map wrapped in parentheses", + graph: { + nodes: [{function: "f", source: """const memo = (new Map()); +export const handler = async (input) => { + const cached = memo.has(input.n); + if (!cached) memo.set(input.n, input.n * input.n); + return { cached, sq: memo.get(input.n) }; +};"""}], + }, + cases: [ + [{n: 2}, {cached: false, sq: 4}], + [{n: 3}, {cached: false, sq: 9}], + [{n: 2}, {cached: false, sq: 4}], + ], +} + +{ + name: "isolation: a const object built by Object.assign", + graph: { + nodes: [{function: "f", source: """const settings = Object.assign({}, { mode: 'base' }); +export const handler = async (input) => { + const before = settings.mode; + if (input.mode) settings.mode = input.mode; + return { before, after: settings.mode }; +};"""}], + }, + cases: [ + [{mode: "fast"}, {before: "base", after: "fast"}], + [{}, {before: "base", after: "base"}], + [{mode: "slow"}, {before: "base", after: "slow"}], + [{}, {before: "base", after: "base"}], + ], +} + +{ + name: "isolation: a const object returned by a helper function", + graph: { + nodes: [{function: "f", source: """function makeStore() { return { items: [] }; } +const store = makeStore(); +export const handler = async (input) => { store.items.push(input.v); return { items: store.items.length }; };"""}], + }, + cases: [ + [{v: 1}, {items: 1}], + [{v: 2}, {items: 1}], + [{v: 3}, {items: 1}], + ], +} + +{ + name: "isolation: a closure counter from an immediately invoked function", + graph: { + nodes: [{function: "f", source: """const next = (() => { let n = 0; return () => ++n; })(); +export const handler = async (input) => ({ id: next(), v: input.v });"""}], + }, + cases: [ + [{v: "a"}, {id: 1, v: "a"}], + [{v: "b"}, {id: 1, v: "b"}], + [{v: "c"}, {id: 1, v: "c"}], + ], +} + +{ + name: "isolation: a generator created at module level", + graph: { + nodes: [{function: "f", source: """const ids = (function* () { let i = 100; while (true) yield i++; })(); +export const handler = async (input) => ({ id: ids.next().value });"""}], + }, + cases: [ + [{}, {id: 100}], + [{x: 1}, {id: 100}], + [{x: 2}, {id: 100}], + ], +} + +{ + name: "isolation: a global regular expression keeps lastIndex", + graph: { + nodes: [{function: "f", source: """const DIGITS = /\d+/g; +export const handler = async (input) => ({ match: DIGITS.test(input.s) });"""}], + }, + cases: [ + [{s: "a1"}, {match: true}], + [{s: "b2"}, {match: true}], + [{s: "c3"}, {match: true}], + [{s: "none"}, {match: false}], + ], +} + +{ + name: "isolation: a property stored on a helper function", + graph: { + nodes: [{function: "f", source: """function tick() { tick.count = (tick.count ?? 0) + 1; return tick.count; } +export const handler = async (input) => ({ tick: tick(), v: input.v });"""}], + }, + cases: [ + [{v: 1}, {tick: 1, v: 1}], + [{v: 2}, {tick: 1, v: 2}], + [{v: 3}, {tick: 1, v: 3}], + ], +} + +{ + name: "isolation: a property stored on the handler itself", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + handler.calls = (handler.calls ?? 0) + 1; + return { calls: handler.calls }; +};"""}], + }, + cases: [ + [{}, {calls: 1}], + [{a: 1}, {calls: 1}], + [{a: 2}, {calls: 1}], + ], +} + +{ + name: "isolation: a class with a static counter", + graph: { + nodes: [{function: "f", source: """class Seq { static n = 0; static next() { return ++Seq.n; } } +export const handler = async (input) => ({ n: Seq.next() });"""}], + }, + cases: [ + [{}, {n: 1}], + [{v: 1}, {n: 1}], + [{v: 2}, {n: 1}], + ], +} + +{ + name: "isolation: a frozen const object cannot carry state", + graph: { + nodes: [{function: "f", source: """const LIMITS = Object.freeze({ low: 10, high: 100 }); +export const handler = async (input) => { + try { LIMITS.low = input.v; } catch (e) { return { frozen: true, low: LIMITS.low }; } + return { frozen: false, low: LIMITS.low }; +};"""}], + }, + cases: [ + [{v: 1}, {frozen: true, low: 10}], + [{v: 2}, {frozen: true, low: 10}], + ], +} + +// --- Globals ------------------------------------------------------------------------------- +// The global object, built-in namespaces and the injected `config`/`console` globals are +// per evaluation as well. + +{ + name: "isolation: globalThis written and read back", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const before = globalThis.specCounter ?? 0; + globalThis.specCounter = before + 1; + return { before, v: input.v }; +};"""}], + }, + cases: [ + [{v: 1}, {before: 0, v: 1}], + [{v: 2}, {before: 0, v: 2}], + [{v: 3}, {before: 0, v: 3}], + ], +} + +{ + name: "isolation: globalThis written at module level", + graph: { + nodes: [{function: "f", source: """globalThis.specLoaded = (globalThis.specLoaded ?? 0) + 1; +export const handler = async (input) => ({ loaded: globalThis.specLoaded });"""}], + }, + cases: [ + [{}, {loaded: 1}], + [{a: 1}, {loaded: 1}], + [{a: 2}, {loaded: 1}], + ], +} + +{ + name: "isolation: a global variable declared through Reflect", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const had = Reflect.has(globalThis, 'specFlag'); + Reflect.set(globalThis, 'specFlag', input.v); + return { had }; +};"""}], + }, + cases: [ + [{v: 1}, {had: false}], + [{v: 2}, {had: false}], + ], +} + +{ + name: "isolation: an undeclared assignment is an error in a module", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { leaked = input.v; return { leaked }; };"""}], + }, + cases: [ + [{v: 1}, "!error"], + [{v: 2}, "!error"], + ], +} + +{ + name: "isolation: a property added to Math inside the handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const before = Math.specCalls ?? 0; + Math.specCalls = before + 1; + return { before }; +};"""}], + }, + cases: [ + [{}, {before: 0}], + [{v: 1}, {before: 0}], + [{v: 2}, {before: 0}], + ], +} + +{ + name: "isolation: a built-in method replaced inside the handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const rounded = Math.round(input.v); + Math.round = () => -1; + return { rounded }; +};"""}], + }, + cases: [ + [{v: 1.4}, {rounded: 1}], + [{v: 2.6}, {rounded: 3}], + [{v: -0.4}, {rounded: 0}], + ], +} + +{ + name: "isolation: JSON.stringify replaced inside the handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const text = JSON.stringify(input.o); + JSON.stringify = () => 'patched'; + return { text }; +};"""}], + }, + cases: [ + [{o: {a: 1}}, {text: "{\"a\":1}"}], + [{o: [1, 2]}, {text: "[1,2]"}], + [{o: "s"}, {text: "\"s\""}], + ], +} + +{ + name: "isolation: a property defined on Object with Object.defineProperty", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const had = Object.hasOwn(Object, 'specMarker'); + if (!had) Object.defineProperty(Object, 'specMarker', { value: input.v, configurable: true }); + return { had, marker: Object.specMarker }; +};"""}], + }, + cases: [ + [{v: 1}, {had: false, marker: 1}], + [{v: 2}, {had: false, marker: 2}], + [{v: 3}, {had: false, marker: 3}], + ], +} + +{ + name: "isolation: the config global mutated by the handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const seen = config.specSeen ?? 0; + config.specSeen = seen + 1; + return { seen, iteration: config.iteration }; +};"""}], + }, + cases: [ + [{}, {seen: 0, iteration: 0}], + [{v: 1}, {seen: 0, iteration: 0}], + [{v: 2}, {seen: 0, iteration: 0}], + ], +} + +{ + name: "isolation: the console global patched by the handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const patched = console.specPatched === true; + console.specPatched = true; + return { patched }; +};"""}], + }, + cases: [ + [{}, {patched: false}], + [{v: 1}, {patched: false}], + [{v: 2}, {patched: false}], + ], +} + +{ + name: "isolation: a Symbol.for key is the same in every evaluation", + graph: { + nodes: [{function: "f", source: """const KEY = Symbol.for('spec.key'); +export const handler = async (input) => ({ same: KEY === Symbol.for('spec.key'), name: Symbol.keyFor(KEY) });"""}], + }, + cases: [ + [{}, {same: true, name: "spec.key"}], + [{v: 1}, {same: true, name: "spec.key"}], + ], +} + +// --- Prototypes ------------------------------------------------------------------------------ + +{ + name: "isolation: Array.prototype extended at module level", + graph: { + nodes: [{function: "f", source: """Array.prototype.specLast = function () { return this[this.length - 1]; }; +export const handler = async (input) => ({ last: input.items.specLast() ?? null });"""}], + }, + cases: [ + [{items: [1, 2, 3]}, {last: 3}], + [{items: ["a"]}, {last: "a"}], + [{items: []}, {}], + ], +} + +{ + name: "isolation: a prototype method counted inside the handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const before = String.prototype.specUses ?? 0; + String.prototype.specUses = before + 1; + return { before, upper: input.s.toUpperCase() }; +};"""}], + }, + cases: [ + [{s: "a"}, {before: 0, upper: "A"}], + [{s: "b"}, {before: 0, upper: "B"}], + [{s: "c"}, {before: 0, upper: "C"}], + ], +} + +{ + name: "isolation: a prototype reached through Object.getPrototypeOf", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const proto = Object.getPrototypeOf([]); + const before = proto.specHits ?? 0; + proto.specHits = before + 1; + return { before, len: input.items.length }; +};"""}], + }, + cases: [ + [{items: [1]}, {before: 0, len: 1}], + [{items: [1, 2]}, {before: 0, len: 2}], + [{items: []}, {before: 0, len: 0}], + ], +} + +{ + name: "isolation: a prototype reached through __proto__", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const before = ({}).__proto__.specHits ?? 0; + ({}).__proto__.specHits = before + 1; + return { before, keys: Object.keys(input.o) }; +};"""}], + }, + cases: [ + [{o: {a: 1}}, {before: 0, keys: ["a"]}], + [{o: {}}, {before: 0, keys: []}], + [{o: {b: 2, c: 3}}, {before: 0, keys: ["b", "c"]}], + ], +} + +{ + name: "isolation: an enumerable property on Object.prototype shows up in for-in", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const keys = []; + for (const k in input.o) keys.push(k); + Object.getPrototypeOf({}).specInjected = 1; + return { keys }; +};"""}], + }, + cases: [ + [{o: {a: 1}}, {keys: ["a"]}], + [{o: {b: 1}}, {keys: ["b"]}], + [{o: {}}, {keys: []}], + ], +} + +// --- Top-level side effects ------------------------------------------------------------------- + +{ + name: "isolation: console.log at module level", + graph: { + nodes: [{function: "f", source: """console.log('module loaded'); +export const handler = async (input) => ({ v: input.v });"""}], + }, + cases: [ + [{v: 1}, {v: 1}], + [{v: 2}, {v: 2}], + ], +} + +{ + name: "isolation: a top-level if statement", + graph: { + nodes: [{function: "f", source: """let mode = 'cold'; +if (typeof mode === 'string') { mode = 'warm'; } +export const handler = async (input) => { const was = mode; mode = 'hot'; return { was, v: input.v }; };"""}], + }, + cases: [ + [{v: 1}, {was: "warm", v: 1}], + [{v: 2}, {was: "warm", v: 2}], + [{v: 3}, {was: "warm", v: 3}], + ], +} + +{ + name: "isolation: a top-level try block", + graph: { + nodes: [{function: "f", source: """const flags = {}; +try { flags.ready = true; } catch (e) { flags.ready = false; } +export const handler = async (input) => { const ready = flags.ready; flags.ready = false; return { ready }; };"""}], + }, + cases: [ + [{}, {ready: true}], + [{v: 1}, {ready: true}], + [{v: 2}, {ready: true}], + ], +} + +{ + name: "isolation: a module that throws while loading", + graph: { + nodes: [{function: "f", source: """throw new Error('boot failed'); +export const handler = async (input) => ({ v: input.v });"""}], + }, + cases: [ + [{v: 1}, "!error: boot failed"], + [{v: 2}, "!error: boot failed"], + ], +} + +{ + name: "isolation: a module whose loading fails only on the first import", + graph: { + nodes: [{function: "f", source: """globalThis.specBoots = (globalThis.specBoots ?? 0) + 1; +if (globalThis.specBoots === 1) throw new Error('first boot'); +export const handler = async (input) => ({ v: input.v });"""}], + }, + cases: [ + [{v: 1}, "!error: first boot"], + [{v: 2}, "!error: first boot"], + ], +} + +// --- Imported modules mutated by the handler -------------------------------------------------- +// Imported modules (big.js, dayjs, zod, zen) are module instances of the runtime; settings +// changed by one evaluation are not seen by the next. + +{ + name: "isolation: Big.DP changed by the handler", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => { + const third = new Big(1).div(3).toString(); + if (input.dp !== undefined) Big.DP = input.dp; + return { third }; +};"""}], + }, + cases: [ + [{dp: 2}, {third: "0.33333333333333333333"}], + [{}, {third: "0.33333333333333333333"}], + [{dp: 5}, {third: "0.33333333333333333333"}], + [{}, {third: "0.33333333333333333333"}], + ], +} + +{ + name: "isolation: Big.RM changed by the handler", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => { + const rounded = new Big(input.v).round(0).toNumber(); + Big.RM = Big.roundDown; + return { rounded }; +};"""}], + }, + cases: [ + [{v: 2.5}, {rounded: 3}], + [{v: 3.5}, {rounded: 4}], + [{v: 1.7}, {rounded: 2}], + ], +} + +{ + name: "isolation: Big.DP set at module level is applied on every evaluation", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +Big.DP = 4; +export const handler = async (input) => ({ v: new Big(input.a).div(input.b).toString() });"""}], + }, + cases: [ + [{a: 1, b: 3}, {v: "0.3333"}], + [{a: 2, b: 3}, {v: "0.6667"}], + [{a: 1, b: 8}, {v: "0.125"}], + ], +} + +{ + name: "isolation: a property added to the dayjs function", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => { + const before = dayjs.specCalls ?? 0; + dayjs.specCalls = before + 1; + return { before, year: dayjs(input.d).year() }; +};"""}], + }, + cases: [ + [{d: "2024-01-01"}, {before: 0, year: 2024}], + [{d: "2020-06-30"}, {before: 0, year: 2020}], + [{d: "1999-12-31"}, {before: 0, year: 1999}], + ], +} + +{ + name: "isolation: a module-level zod schema object mutated by the handler", + graph: { + nodes: [{function: "f", source: """import { z } from 'zod'; +const Num = z.number(); +export const handler = async (input) => { + const before = Num.specCalls ?? 0; + Num.specCalls = before + 1; + return { before, ok: Num.safeParse(input.v).success }; +};"""}], + }, + cases: [ + [{v: 1}, {before: 0, ok: true}], + [{v: "1"}, {before: 0, ok: false}], + [{v: 2}, {before: 0, ok: true}], + ], +} + +{ + name: "isolation: the zod namespace is not extensible", + graph: { + nodes: [{function: "f", source: """import { z } from 'zod'; +export const handler = async (input) => { z.specCalls = 1; return { v: input.v }; };"""}], + }, + cases: [ + [{v: 1}, "!error: not extensible"], + [{v: 2}, "!error: not extensible"], + ], +} + +{ + name: "isolation: a property added to the zen module", + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => { + const before = zen.specCalls ?? 0; + zen.specCalls = before + 1; + return { before, sum: zen.evaluateExpression('a + 1', { a: input.a }) }; +};"""}], + }, + cases: [ + [{a: 1}, {before: 0, sum: 2}], + [{a: 2}, {before: 0, sum: 3}], + [{a: 3}, {before: 0, sum: 4}], + ], +} + +// --- Failures do not affect other evaluations ------------------------------------------------ + +{ + name: "isolation: a throwing evaluation between successful ones", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + if (input.fail) throw new Error('row failed'); + return { v: input.v }; +};"""}], + }, + cases: [ + [{v: 1}, {v: 1}], + [{fail: true, v: 2}, "!error: row failed"], + [{v: 3}, {v: 3}], + [{fail: false, v: 4}, {v: 4}], + ], +} + +{ + name: "isolation: a runtime type error between successful ones", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ n: input.o.n * 2 });"""}], + }, + cases: [ + [{o: {n: 1}}, {n: 2}], + [{}, "!error"], + [{o: {n: 5}}, {n: 10}], + [{o: null}, "!error"], + ], +} + +{ + name: "isolation: state mutated before a throw is not seen by the next evaluation", + graph: { + nodes: [{function: "f", source: """const box = { n: 0 }; +export const handler = async (input) => { + box.n += 1; + if (input.fail) throw new Error('after mutation'); + return { n: box.n }; +};"""}], + }, + cases: [ + [{}, {n: 1}], + [{fail: true}, "!error: after mutation"], + [{}, {n: 1}], + ], +} + +{ + name: "isolation: a global set before a throw is not seen by the next evaluation", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const before = globalThis.specBeforeThrow ?? 0; + globalThis.specBeforeThrow = before + 1; + if (input.fail) throw new Error('thrown'); + return { before }; +};"""}], + }, + cases: [ + [{fail: true}, "!error: thrown"], + [{}, {before: 0}], + [{fail: true}, "!error: thrown"], + [{}, {before: 0}], + ], +} + +{ + name: "isolation: a rejected promise between successful ones", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => input.reject ? Promise.reject(new Error('rejected')) : { ok: input.v };"""}], + }, + cases: [ + [{v: 1}, {ok: 1}], + [{reject: true}, "!error: rejected"], + [{v: 2}, {ok: 2}], + ], +} + +// --- $nodes and input per evaluation ---------------------------------------------------------- + +{ + name: "isolation: $nodes belongs to the current evaluation", + graph: { + nodes: [ + {expression: "calc", fields: {double: "v * 2"}}, + {function: "f", source: """export const handler = async (input) => ({ + fromCalc: input.$nodes.calc.double, + fromInput: input.$nodes.input.v, +});"""}, + ], + }, + cases: [ + [{v: 1}, {fromCalc: 2, fromInput: 1}], + [{v: 2}, {fromCalc: 4, fromInput: 2}], + [{v: 3}, {fromCalc: 6, fromInput: 3}], + [{v: -1}, {fromCalc: -2, fromInput: -1}], + ], +} + +{ + name: "isolation: a $nodes snapshot kept in module state", + graph: { + nodes: [ + {expression: "calc", fields: {v: "v"}}, + {function: "f", source: """let firstNodes; +export const handler = async (input) => { + firstNodes ??= input.$nodes; + return { v: firstNodes.calc.v }; +};"""}, + ], + }, + cases: [ + [{v: 1}, {v: 1}], + [{v: 2}, {v: 2}], + [{v: 3}, {v: 3}], + ], +} + +{ + name: "isolation: the input object kept in a module Map", + graph: { + nodes: [{function: "f", source: """const inputs = new Map(); +export const handler = async (input) => { + inputs.set(inputs.size, input); + return { first: inputs.get(0).v }; +};"""}], + }, + cases: [ + [{v: "a"}, {first: "a"}], + [{v: "b"}, {first: "b"}], + [{v: "c"}, {first: "c"}], + ], +} + +{ + name: "isolation: config.iteration in every evaluation", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ iteration: config.iteration, maxDepth: config.maxDepth, v: input.v });"""}], + }, + cases: [ + [{v: 1}, {iteration: 0, maxDepth: 10, v: 1}], + [{v: 2}, {iteration: 0, maxDepth: 10, v: 2}], + ], +} + +// --- Several function nodes in one evaluation ------------------------------------------------ +// Within one evaluation, nodes share the runtime but each node has its own module. + +{ + name: "isolation: two nodes with the same stateful source count separately", + graph: { + nodes: [ + {function: "a", source: """let n = 0; +export const handler = async (input) => ({ ...input, a: ++n });"""}, + {function: "b", source: """let n = 0; +export const handler = async (input) => ({ ...input, b: ++n });"""}, + ], + }, + cases: [ + [{}, {a: 1, b: 1}], + [{x: 1}, {x: 1, a: 1, b: 1}], + [{x: 2}, {x: 2, a: 1, b: 1}], + ], +} + +{ + name: "isolation: a global written by one node is visible to a later node in the same evaluation", + graph: { + nodes: [ + {function: "writer", source: """export const handler = async (input) => { globalThis.specShared = input.v; return { wrote: true }; };"""}, + {function: "reader", source: """export const handler = async (input) => ({ wrote: input.wrote, read: globalThis.specShared ?? 'none' });"""}, + ], + }, + cases: [ + {input: {v: 1}, output: {wrote: true, read: 1}, note: "question: nodes of one evaluation share a JS global object, so one node can pass data to another outside the graph edges", engines: "batched rows run each stateful function node in its own runtime, so globals do not travel between nodes of a row; walker shares one runtime per evaluation"}, + {input: {v: "x"}, output: {wrote: true, read: "x"}, note: "question: nodes of one evaluation share a JS global object, so one node can pass data to another outside the graph edges", engines: "batched rows run each stateful function node in its own runtime, so globals do not travel between nodes of a row; walker shares one runtime per evaluation"}, + [{}, {wrote: true, read: "none"}, "question: nodes of one evaluation share a JS global object, so one node can pass data to another outside the graph edges"], + ], +} + +{ + name: "isolation: a reader of a global that a parallel branch did not write", + graph: { + nodes: [ + {switch: "route", when: ["write", ""]}, + {function: "writer", source: """export const handler = async (input) => { globalThis.specBranch = 'written'; return { branch: 'writer' }; };"""}, + {expression: "skip", fields: {branch: "'skip'"}}, + {function: "reader", source: """export const handler = async (input) => ({ branch: input.branch, seen: globalThis.specBranch ?? 'none' });"""}, + ], + edges: ["input -> route", "route:0 -> writer -> reader", "route:1 -> skip -> reader", "reader -> output"], + }, + cases: [ + {input: {write: true}, output: {branch: "writer", seen: "written"}, engines: "batched rows run each stateful function node in its own runtime, so globals do not travel between nodes of a row; walker shares one runtime per evaluation"}, + [{write: false}, {branch: "skip", seen: "none"}], + {input: {write: true}, output: {branch: "writer", seen: "written"}, engines: "batched rows run each stateful function node in its own runtime, so globals do not travel between nodes of a row; walker shares one runtime per evaluation"}, + [{}, {branch: "skip", seen: "none"}], + ], +} + +{ + name: "isolation: a stateful function inside a looped sub-decision", + decisions: { + item: {nodes: [{function: "count", source: """let n = 0; +export const handler = async (input) => ({ seq: ++n, v: input.v });"""}]}, + }, + graph: { + nodes: [{decision: "each", key: "item", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{v: "a"}, {v: "b"}, {v: "c"}]}, {out: [{seq: 1, v: "a"}, {seq: 1, v: "b"}, {seq: 2, v: "c"}]}, "question: a node called several times in one evaluation gets a fresh module on its first two calls (node:id, then node:id.hash) and reuses the second instance afterwards, so module state is fresh, fresh, then shared"], + [{items: [{v: "x"}]}, {out: [{seq: 1, v: "x"}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "isolation: a stateless function inside a looped sub-decision", + decisions: { + item: {nodes: [{function: "f", source: """const FACTOR = 10; +export const handler = async (input) => ({ v: input.v * FACTOR });"""}]}, + }, + graph: { + nodes: [{decision: "each", key: "item", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {out: [{v: 10}, {v: 20}]}], + [{items: [{v: 0.5}]}, {out: [{v: 5}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "isolation: a looped sub-decision whose function writes a global", + decisions: { + item: {nodes: [{function: "g", source: """export const handler = async (input) => { + const before = globalThis.specItems ?? 0; + globalThis.specItems = before + 1; + return { before }; +};"""}]}, + }, + graph: { + nodes: [{decision: "each", key: "item", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{}, {}, {}]}, {out: [{before: 0}, {before: 1}, {before: 2}]}, "question: loop items of one evaluation share the JS global object"], + [{items: [{}]}, {out: [{before: 0}]}], + [{items: [{}, {}]}, {out: [{before: 0}, {before: 1}]}, "question: loop items of one evaluation share the JS global object"], + ], +} + +{ + name: "isolation: a parent and a child node with the same id and source", + decisions: { + child: {nodes: [{function: "f", source: """let n = 0; +export const handler = async (input) => ({ ...input, n: ++n });"""}]}, + }, + graph: { + nodes: [ + {function: "f", source: """let n = 0; +export const handler = async (input) => ({ ...input, n: ++n });"""}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + {input: {}, output: {n: 1}, note: "question: a child function node with the same id and source as the parent node is declared under a new module name, so its module state starts fresh"}, + {input: {x: 1}, output: {x: 1, n: 1}, note: "question: a child function node with the same id and source as the parent node is declared under a new module name, so its module state starts fresh"}, + ], +} + +{ + name: "isolation: a parent and a child node with the same id and different sources", + decisions: { + child: {nodes: [{function: "f", source: """let n = 100; +export const handler = async (input) => ({ ...input, child: ++n });"""}]}, + }, + graph: { + nodes: [ + {function: "f", source: """let n = 0; +export const handler = async (input) => ({ ...input, parent: ++n });"""}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{}, {parent: 1, child: 101}], + [{x: 1}, {x: 1, parent: 1, child: 101}], + ], +} + +{ + name: "isolation: zen.evaluate of a stateful sub-decision twice in one handler", + decisions: { + counter: {nodes: [{function: "c", source: """let n = 0; +export const handler = async (input) => ({ n: ++n });"""}]}, + }, + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => { + const a = await zen.evaluate('counter', {}); + const b = await zen.evaluate('counter', {}); + return { a: a.result.n, b: b.result.n, v: input.v }; +};"""}], + }, + cases: [ + [{v: 1}, {a: 1, b: 1, v: 1}], + [{v: 2}, {a: 1, b: 1, v: 2}], + ], +} diff --git a/core/engine/tests/spec/graph/42-functions-data.json5 b/core/engine/tests/spec/graph/42-functions-data.json5 new file mode 100644 index 00000000..8a59af76 --- /dev/null +++ b/core/engine/tests/spec/graph/42-functions-data.json5 @@ -0,0 +1,1078 @@ +// Function nodes, data crossing the JS boundary: numbers become doubles on the way in and +// decimals of about 15-16 significant digits on the way out, big.js restores exact decimal +// arithmetic when the values travel as strings, objects and arrays are copied in both +// directions, strings are UTF-16 inside JS, and dates are strings that dayjs parses. +// Chapter 16 has the basic shapes; this chapter goes deeper on each data kind. +// +// Not covered because the process aborts instead of failing the evaluation: a returned object +// graph with a cycle (`a.self = a`), and returned objects nested about 2000 levels deep. Both +// overflow the stack in the JS -> Variable conversion (`nodes/function/v2/serde.rs`). + +// --- Decimals into JS -------------------------------------------------------------------------- +// Inside the handler every number is a double: scale is lost, digits beyond double precision +// are rounded, and String() gives the shortest round-trip form. + +{ + name: "data: String() of decimal inputs inside JS", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ s: String(input.v) });"""}], + }, + cases: [ + [{v: 1.50}, {s: "1.5"}], + [{v: 100}, {s: "100"}], + [{v: 0.1}, {s: "0.1"}], + [{v: 0.12345678901234567890}, {s: "0.12345678901234568"}], + [{v: 1e21}, {s: "1e+21"}], + [{v: 0.0000001}, {s: "1e-7"}], + [{v: -0.000001}, {s: "-0.000001"}], + [{v: 123456789012345678}, {s: "123456789012345680"}], + ], +} + +{ + name: "data: toFixed of decimal inputs follows the double value", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ fixed: input.v.toFixed(input.digits ?? 2) });"""}], + }, + cases: [ + [{v: 1.005}, {fixed: "1.00"}], + [{v: 1.015}, {fixed: "1.01"}], + [{v: 2.5, digits: 0}, {fixed: "3"}], + [{v: 0.125}, {fixed: "0.13"}], + [{v: -1.5, digits: 0}, {fixed: "-2"}], + [{v: 10}, {fixed: "10.00"}], + ], +} + +{ + name: "data: Number.isInteger and integer checks on decimal inputs", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + int: Number.isInteger(input.v), + safe: Number.isSafeInteger(input.v), +});"""}], + }, + cases: [ + [{v: 1}, {int: true, safe: true}], + [{v: 1.0}, {int: true, safe: true}], + [{v: 1.5}, {int: false, safe: false}], + [{v: 9007199254740993}, {int: true, safe: false}], + [{v: -0}, {int: true, safe: true}], + [{v: 1.0000000000000000001}, {int: true, safe: true}], + ], +} + +{ + name: "data: equality of decimals that collapse to the same double", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ same: input.a === input.b });"""}], + }, + cases: [ + [{a: 0.1, b: 0.10}, {same: true}], + [{a: 0.1, b: 0.1000000000000000000001}, {same: true}], + [{a: 9007199254740992, b: 9007199254740993}, {same: true}], + [{a: 0.3, b: 0.30000000000000004}, {same: false}], + [{a: 1, b: 1.000000000000001}, {same: false}], + ], +} + +{ + name: "data: numbers in nested arrays and objects become doubles too", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + sum: input.lines.reduce((s, l) => s + l.amount, 0), + types: input.lines.map((l) => typeof l.amount), +});"""}], + }, + cases: [ + [{lines: [{amount: 0.1}, {amount: 0.2}]}, {sum: 0.3, types: ["number", "number"]}], + [{lines: [{amount: 0.1}, {amount: 0.2}, {amount: 0.3}]}, {sum: 0.6, types: ["number", "number", "number"]}], + [{lines: [{amount: 1.1}, {amount: 2.2}, {amount: 3.3}]}, {sum: 6.6, types: ["number", "number", "number"]}], + [{lines: []}, {sum: 0, types: []}], + ], +} + +{ + name: "data: float artifacts are visible inside JS before they are rounded away", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const sum = input.a + input.b; + return { sum, exact: sum === input.expected, text: String(sum) }; +};"""}], + }, + cases: [ + [{a: 0.1, b: 0.2, expected: 0.3}, {sum: 0.3, exact: false, text: "0.30000000000000004"}], + [{a: 0.5, b: 0.25, expected: 0.75}, {sum: 0.75, exact: true, text: "0.75"}], + [{a: 1.1, b: 2.2, expected: 3.3}, {sum: 3.3, exact: false, text: "3.3000000000000003"}], + [{a: 1, b: 2, expected: 3}, {sum: 3, exact: true, text: "3"}], + ], +} + +// --- Numbers out of JS -------------------------------------------------------------------------- +// Doubles are converted to decimals with 15-16 significant digits (large integral doubles +// keep their exact binary value); values outside the +// decimal range fail the conversion, values below its smallest step become zero. + +{ + name: "data: repeating fractions are cut at the double's precision", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: input.a / input.b });"""}], + }, + cases: [ + [{a: 1, b: 3}, {v: 0.3333333333333333}], + [{a: 2, b: 3}, {v: 0.666666666666667}], + [{a: 10, b: 4}, {v: 2.5}], + [{a: 1, b: 7}, {v: 0.1428571428571429}], + [{a: -1, b: 8}, {v: -0.125}], + ], +} + +{ + name: "data: large and small results", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: input.base ** input.exp });"""}], + }, + cases: [ + [{base: 10, exp: 20}, {v: 100000000000000000000}], + [{base: 10, exp: 28}, {v: 9999999999999999583119736832}, "question: large integral doubles keep their exact binary value while fractions are rounded to about 15 digits, so 1e28 does not come back as 1e28"], + [{base: 2, exp: 64}, {v: 18446744073709551616}], + [{base: 10, exp: -10}, {v: 0.0000000001}], + [{base: 10, exp: -28}, {v: 0.0000000000000000000000000001}], + [{base: 10, exp: -29}, {v: 0}, "question: a non-zero double below the smallest decimal step silently becomes 0"], + [{base: 10, exp: 29}, "!error: failed to convert to number"], + ], +} + +{ + name: "data: special doubles in nested results", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ o: { v: input.pick === 'min' ? Number.MIN_VALUE : input.pick === 'max' ? Number.MAX_VALUE : input.pick === 'eps' ? Number.EPSILON : -0 } });"""}], + }, + cases: [ + [{pick: "min"}, {o: {v: 0}}, "question: Number.MIN_VALUE silently becomes 0"], + [{pick: "eps"}, {o: {v: 0.0000000000000002220446049250}}], + [{pick: "zero"}, {o: {v: 0}}], + [{pick: "max"}, "!error: failed to convert to number"], + ], +} + +{ + name: "data: integer results above the safe range", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: input.n * 1000, big: BigInt(input.n) * 1000n });"""}], + }, + cases: [ + [{n: 9007199254740991}, {v: 9007199254740990976, big: 9007199254740991000}], + [{n: 1}, {v: 1000, big: 1000}], + [{n: -5}, {v: -5000, big: -5000}], + ], +} + +{ + name: "data: a BigInt outside the 64-bit range", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: 2n ** BigInt(input.bits) });"""}], + }, + cases: [ + [{bits: 62}, {v: 4611686018427387904}], + [{bits: 63}, "!error: failed to convert to number", "bug: a BigInt above i64::MAX wraps to -9223372036854775808 instead of failing"], + [{bits: 100}, "!error: failed to convert to number", "bug: a BigInt far outside i64 silently becomes 0 instead of failing"], + ], +} + +{ + name: "data: a JS result feeding exact expression arithmetic", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({ a: input.x / 3, b: input.x * 0.1 });"""}, + {expression: "e", fields: {sum: "a + b", triple: "a * 3", bExact: "b == $nodes.input.x * 0.1"}}, + ], + edges: ["input -> f -> e -> output"], + }, + cases: [ + [{x: 1}, {sum: 0.4333333333333333, triple: 0.9999999999999999, bExact: true}], + [{x: 3}, {sum: 1.3, triple: 3, bExact: true}], + [{x: 0}, {sum: 0, triple: 0, bExact: true}], + ], +} + +// --- big.js ------------------------------------------------------------------------------------- +// Exact decimal arithmetic inside JS. Exactness depends on how the value enters: a number has +// already been through a double, a string keeps every digit. + +{ + name: "data: big.js from strings keeps every digit", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => ({ sum: new Big(input.a).plus(input.b).toString() });"""}], + }, + cases: [ + [{a: "0.1000000000000000000000000001", b: "0.2"}, {sum: "0.3000000000000000000000000001"}], + [{a: "12345678901234567890.5", b: "0.5"}, {sum: "12345678901234567891"}], + [{a: "-0.00000000000000000001", b: "0"}, {sum: "-1e-20"}], + [{a: "1e30", b: "1"}, {sum: "1.000000000000000000000000000001e+30"}], + ], +} + +{ + name: "data: big.js from number inputs sees the double", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => ({ v: new Big(input.v).toString() });"""}], + }, + cases: [ + [{v: 0.1}, {v: "0.1"}], + [{v: 1.50}, {v: "1.5"}], + [{v: 0.1000000000000000000000000001}, {v: "0.1"}], + [{v: 9007199254740993}, {v: "9007199254740992"}], + [{v: 1e21}, {v: "1e+21"}], + ], +} + +{ + name: "data: big.js sums a list exactly where floats drift", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => ({ + exact: input.values.reduce((s, v) => s.plus(v), new Big(0)).toString(), + float: String(input.values.reduce((s, v) => s + v, 0)), +});"""}], + }, + cases: [ + [{values: [0.1, 0.1, 0.1]}, {exact: "0.3", float: "0.30000000000000004"}], + [{values: [0.1, 0.2, 0.3, 0.4]}, {exact: "1", float: "1"}], + [{values: [1.1, 2.2]}, {exact: "3.3", float: "3.3000000000000003"}], + [{values: []}, {exact: "0", float: "0"}], + [{values: [100, -99.99]}, {exact: "0.01", float: "0.010000000000005116"}], + ], +} + +{ + name: "data: big.js division uses 20 decimal places by default", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => ({ q: new Big(input.a).div(input.b).toString() });"""}], + }, + cases: [ + [{a: 1, b: 3}, {q: "0.33333333333333333333"}], + [{a: 2, b: 3}, {q: "0.66666666666666666667"}], + [{a: 10, b: 4}, {q: "2.5"}], + [{a: 1, b: 0}, "!error: Division by zero"], + ], +} + +{ + name: "data: big.js rounding modes", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => { + const v = new Big(input.v); + return { + halfUp: v.round(1, Big.roundHalfUp).toString(), + halfEven: v.round(1, Big.roundHalfEven).toString(), + down: v.round(1, Big.roundDown).toString(), + up: v.round(1, Big.roundUp).toString(), + }; +};"""}], + }, + cases: [ + [{v: "1.25"}, {halfUp: "1.3", halfEven: "1.2", down: "1.2", up: "1.3"}], + [{v: "1.35"}, {halfUp: "1.4", halfEven: "1.4", down: "1.3", up: "1.4"}], + [{v: "-1.25"}, {halfUp: "-1.3", halfEven: "-1.2", down: "-1.2", up: "-1.3"}], + [{v: "2"}, {halfUp: "2", halfEven: "2", down: "2", up: "2"}], + ], +} + +{ + name: "data: big.js comparisons", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => { + const a = new Big(input.a); + return { cmp: a.cmp(input.b), eq: a.eq(input.b), lt: a.lt(input.b), gte: a.gte(input.b) }; +};"""}], + }, + cases: [ + [{a: "0.3", b: "0.30"}, {cmp: 0, eq: true, lt: false, gte: true}], + [{a: 1, b: 2}, {cmp: -1, eq: false, lt: true, gte: false}], + [{a: "-0", b: 0}, {cmp: 0, eq: true, lt: false, gte: true}], + [{a: "10", b: "9.99999999999999999999"}, {cmp: 1, eq: false, lt: false, gte: true}], + ], +} + +{ + name: "data: big.js rejects invalid numbers", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => { + try { return { v: new Big(input.v).toString() }; } catch (e) { return { invalid: true }; } +};"""}], + }, + cases: [ + [{v: "abc"}, {invalid: true}], + [{v: ""}, {invalid: true}], + [{v: null}, {invalid: true}], + [{}, {invalid: true}], + [{v: " 1 "}, {invalid: true}], + [{v: "1e5"}, {v: "100000"}], + ], +} + +{ + name: "data: a Big instance returned as a value", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => ({ big: new Big(input.v), str: new Big(input.v).toString() });"""}], + }, + cases: [ + [{v: "1.5"}, {big: {s: 1, e: 0, c: [1, 5], constructor: "[Constructor]"}, str: "1.5"}, "question: a Big instance is converted field by field (sign, exponent, digits and an own constructor property) instead of to its value"], + [{v: "-120"}, {big: {s: -1, e: 2, c: [1, 2], constructor: "[Constructor]"}, str: "-120"}, "question: a Big instance is converted field by field (sign, exponent, digits and an own constructor property) instead of to its value"], + ], +} + +{ + name: "data: a Big instance through JSON becomes its string", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => JSON.parse(JSON.stringify({ total: new Big(input.a).times(input.b) }));"""}], + }, + cases: [ + [{a: "1.10", b: 3}, {total: "3.3"}], + [{a: "0.1", b: "0.1"}, {total: "0.01"}], + [{a: 0, b: 5}, {total: "0"}], + ], +} + +{ + name: "data: a big.js string result read by a decimal table", + graph: { + nodes: [ + {function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => ({ total: Number(new Big(input.price).times(input.qty).toFixed(2)) });"""}, + {table: "t", inputs: ["total"], outputs: ["band"], rules: [ + ["> 100", "'high'"], + ["[10..100]", "'mid'"], + ["", "'low'"], + ]}, + ], + edges: ["input -> f -> t -> output"], + }, + cases: [ + [{price: "33.335", qty: 3}, {band: "high"}], + [{price: "33.33", qty: 3}, {band: "mid"}], + [{price: "3.33", qty: 3}, {band: "low"}], + [{price: "10", qty: 1}, {band: "mid"}], + ], +} + +{ + name: "data: an amortization schedule with big.js", + graph: { + nodes: [{function: "f", source: """import Big from 'big.js'; +export const handler = async (input) => { + let balance = new Big(input.principal); + const payment = balance.div(input.months).round(2); + const rows = []; + for (let m = 1; m <= input.months; m++) { + const pay = m === input.months ? balance : payment; + balance = balance.minus(pay); + rows.push({ m, pay: pay.toFixed(2), left: balance.toFixed(2) }); + } + return { rows }; +};"""}], + }, + cases: [ + [{principal: "100", months: 3}, {rows: [{m: 1, pay: "33.33", left: "66.67"}, {m: 2, pay: "33.33", left: "33.34"}, {m: 3, pay: "33.34", left: "0.00"}]}], + [{principal: "10", months: 1}, {rows: [{m: 1, pay: "10.00", left: "0.00"}]}], + [{principal: "1", months: 4}, {rows: [{m: 1, pay: "0.25", left: "0.75"}, {m: 2, pay: "0.25", left: "0.50"}, {m: 3, pay: "0.25", left: "0.25"}, {m: 4, pay: "0.25", left: "0.00"}]}], + ], +} + +// --- Large arrays and objects ------------------------------------------------------------------- + +{ + name: "data: a large generated array summed by a following expression", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({ items: Array.from({ length: input.n }, (_, i) => ({ i, price: (i % 10) + 0.5 })) });"""}, + {expression: "e", fields: {count: "len(items)", total: "sum(map(items, #.price))", last: "items[len(items) - 1].i"}}, + ], + }, + cases: [ + [{n: 1000}, {count: 1000, total: 5000, last: 999}], + [{n: 10}, {count: 10, total: 50, last: 9}], + [{n: 1}, {count: 1, total: 0.5, last: 0}], + [{n: 5000}, {count: 5000, total: 25000, last: 4999}], + ], +} + +{ + name: "data: a large generated object with many keys", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => { + const byKey = {}; + for (let i = 0; i < input.n; i++) byKey['k' + i] = i * 2; + return { byKey }; +};"""}, + {expression: "e", fields: {count: "len(keys(byKey))", first: "byKey.k0", last: "byKey['k' + string($nodes.input.n - 1)]"}}, + ], + edges: ["input -> f -> e -> output"], + }, + cases: [ + [{n: 500}, {count: 500, first: 0, last: 998}], + [{n: 1}, {count: 1, first: 0, last: 0}], + [{n: 2000}, {count: 2000, first: 0, last: 3998}], + ], +} + +{ + name: "data: a large input array filtered, sorted and sliced", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const top = input.rows.filter((r) => r.active).sort((a, b) => b.score - a.score || a.id - b.id).slice(0, 3); + return { top: top.map((r) => r.id), count: input.rows.length }; +};"""}], + }, + cases: [ + [{rows: [{id: 1, score: 5, active: true}, {id: 2, score: 9, active: false}, {id: 3, score: 7, active: true}, {id: 4, score: 7, active: true}, {id: 5, score: 1, active: true}]}, {top: [3, 4, 1], count: 5}], + [{rows: []}, {top: [], count: 0}], + [{rows: [{id: 1, score: 0, active: false}]}, {top: [], count: 1}], + ], +} + +{ + name: "data: default sort is lexicographic", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ plain: [...input.v].sort(), numeric: [...input.v].sort((a, b) => a - b) });"""}], + }, + cases: [ + [{v: [10, 9, 1, 100]}, {plain: [1, 10, 100, 9], numeric: [1, 9, 10, 100]}], + [{v: [-1, -10, 2]}, {plain: [-1, -10, 2], numeric: [-10, -1, 2]}], + [{v: [0.5, 0.25]}, {plain: [0.25, 0.5], numeric: [0.25, 0.5]}], + [{v: []}, {plain: [], numeric: []}], + ], +} + +{ + name: "data: a matrix transposed", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ t: input.m[0]?.map((_, c) => input.m.map((row) => row[c])) ?? [] });"""}], + }, + cases: [ + [{m: [[1, 2, 3], [4, 5, 6]]}, {t: [[1, 4], [2, 5], [3, 6]]}], + [{m: [[1]]}, {t: [[1]]}], + [{m: []}, {t: []}], + [{m: [["a", null], [true, 0.5]]}, {t: [["a", true], [null, 0.5]]}], + ], +} + +{ + name: "data: integer-like keys are ordered first by JS", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ keys: Object.keys(input.o) });"""}], + }, + cases: [ + [{o: {b: 1, "10": 2, a: 3, "2": 4}}, {keys: ["2", "10", "b", "a"]}], + [{o: {z: 1, y: 2}}, {keys: ["z", "y"]}], + [{o: {"-1": 1, "1": 2}}, {keys: ["1", "-1"]}], + ], +} + +{ + name: "data: group by into an object of arrays", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const groups = {}; + for (const item of input.items) (groups[item.kind] ??= []).push(item.v); + return { groups }; +};"""}], + }, + cases: [ + [{items: [{kind: "a", v: 1}, {kind: "b", v: 2}, {kind: "a", v: 3}]}, {groups: {a: [1, 3], b: [2]}}], + [{items: []}, {groups: {}}], + [{items: [{kind: "x y", v: null}]}, {groups: {"x y": [null]}}], + ], +} + +// --- Deep nesting ------------------------------------------------------------------------------- + +{ + name: "data: a deeply nested input is read through optional chaining", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ v: input.a?.b?.c?.d?.e?.f?.g?.h ?? 'missing' });"""}], + }, + cases: [ + [{a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}}, {v: 1}], + [{a: {b: {c: {d: {e: {f: {g: {}}}}}}}}, {v: "missing"}], + [{a: {b: {c: null}}}, {v: "missing"}], + [{}, {v: "missing"}], + [{a: {b: {c: {d: {e: {f: {g: {h: [1, {x: 2}]}}}}}}}}, {v: [1, {x: 2}]}], + ], +} + +{ + name: "data: a generated nested chain read by an expression", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => { + let o = { leaf: input.leaf }; + for (let i = 0; i < input.n; i++) o = { next: o }; + return { o }; +};"""}, + {expression: "e", fields: {depth3: "o.next.next.next.leaf"}}, + ], + edges: ["input -> f -> e -> output"], + }, + cases: [ + [{n: 3, leaf: "x"}, {depth3: "x"}], + [{n: 2, leaf: "x"}, {}], + [{n: 200, leaf: 1}, {}], + ], +} + +{ + name: "data: a generated nested chain measured by a second function", + graph: { + nodes: [ + {function: "build", source: """export const handler = async (input) => { + let o = { leaf: true }; + for (let i = 0; i < input.n; i++) o = { next: o, arr: [i] }; + return { o }; +};"""}, + {function: "measure", source: """export const handler = async (input) => { + let depth = 0; + for (let o = input.o; o.next; o = o.next) depth++; + return { depth }; +};"""}, + ], + }, + cases: [ + [{n: 0}, {depth: 0}], + [{n: 10}, {depth: 10}], + [{n: 500}, {depth: 500}], + ], +} + +{ + name: "data: a deep path rebuilt with a modified leaf", + graph: { + nodes: [{function: "f", source: """const setIn = (o, [k, ...rest], v) => rest.length === 0 ? { ...o, [k]: v } : { ...o, [k]: setIn(o?.[k] ?? {}, rest, v) }; +export const handler = async (input) => setIn(input, input.path.split('.'), input.value);"""}], + }, + cases: [ + [{path: "a.b.c", value: 1, a: {b: {c: 0, d: 2}}}, {path: "a.b.c", value: 1, a: {b: {c: 1, d: 2}}}], + [{path: "x.y", value: "new"}, {path: "x.y", value: "new", x: {y: "new"}}], + [{path: "top", value: [1]}, {path: "top", value: [1], top: [1]}], + ], +} + +// --- Mutating the input --------------------------------------------------------------------------- +// The handler receives a copy: whatever it does to `input` is visible only through what it +// returns. Other nodes, `$nodes.input` and the final pass-through keep the original request. + +{ + name: "data: arrays sorted and spliced in place are only changed in the result", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => { + input.items.sort((a, b) => a - b); + input.items.splice(0, 1); + input.tags.reverse(); + return { items: input.items, tags: input.tags }; +};"""}, + {expression: "orig", fields: {origItems: "$nodes.input.items", origTags: "$nodes.input.tags"}}, + ], + edges: ["input -> f -> output", "input -> orig -> output"], + }, + cases: [ + [{items: [3, 1, 2], tags: ["a", "b"]}, {items: [2, 3], tags: ["b", "a"], origItems: [3, 1, 2], origTags: ["a", "b"]}], + [{items: [1], tags: []}, {items: [], tags: [], origItems: [1], origTags: []}], + [{items: [5, 5], tags: ["x"]}, {items: [5], tags: ["x"], origItems: [5, 5], origTags: ["x"]}], + ], +} + +{ + name: "data: Object.assign onto the input then returning it", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => Object.assign(input, { status: 'checked' }, input.patch ?? {});"""}], + }, + cases: [ + [{a: 1}, {a: 1, status: "checked"}], + [{a: 1, patch: {a: 2}}, {a: 2, status: "checked", patch: {a: 2}}], + [{status: "old"}, {status: "checked"}], + [{patch: {status: "patched"}}, {status: "patched", patch: {status: "patched"}}], + ], +} + +{ + name: "data: deleting keys from the input", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + for (const key of input.drop ?? []) delete input[key]; + delete input.drop; + return input; +};"""}], + }, + cases: [ + [{a: 1, b: 2, drop: ["a"]}, {b: 2}], + [{a: 1, drop: []}, {a: 1}], + [{a: 1, drop: ["missing"]}, {a: 1}], + [{a: {deep: 1}, b: [1], drop: ["a", "b"]}, {}], + ], +} + +{ + name: "data: a shallow spread shares nested objects with the input", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const copy = { ...input }; + copy.nested.x = 'changed'; + copy.top = 'changed'; + return { copyX: copy.nested.x, inputX: input.nested.x, inputTop: input.top ?? null }; +};"""}], + }, + cases: [ + [{nested: {x: "orig"}, top: "orig"}, {copyX: "changed", inputX: "changed", inputTop: "orig"}], + [{nested: {}}, {copyX: "changed", inputX: "changed"}], + ], +} + +{ + name: "data: a mutated input does not change the request seen by a later node", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => { input.v = 'mutated'; input.list.push('x'); return { done: true }; };"""}, + {expression: "e", fields: {done: "done", v: "$nodes.input.v", list: "$nodes.input.list"}}, + ], + }, + cases: [ + [{v: 1, list: []}, {done: true, v: 1, list: []}], + [{v: "s", list: [1]}, {done: true, v: "s", list: [1]}], + ], +} + +{ + name: "data: returning a partially modified copy of the input", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + ...input, + customer: { ...input.customer, name: input.customer?.name?.trim() ?? null }, + lines: (input.lines ?? []).map((l) => ({ ...l, total: l.qty * l.price })), +});"""}], + }, + cases: [ + [ + {id: 7, customer: {name: " Ann ", tier: "gold"}, lines: [{qty: 2, price: 1.5}]}, + {id: 7, customer: {name: "Ann", tier: "gold"}, lines: [{qty: 2, price: 1.5, total: 3}]}, + ], + [{id: 8}, {id: 8, customer: {name: null}, lines: []}], + [{customer: {}, lines: []}, {customer: {name: null}, lines: []}], + ], +} + +{ + name: "data: the same input object returned in two places", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { const shared = input.o; shared.tag = 1; return { a: shared, b: shared, list: [shared, shared] }; };"""}], + }, + cases: [ + [{o: {v: 1}}, {a: {v: 1, tag: 1}, b: {v: 1, tag: 1}, list: [{v: 1, tag: 1}, {v: 1, tag: 1}]}], + [{o: {}}, {a: {tag: 1}, b: {tag: 1}, list: [{tag: 1}, {tag: 1}]}], + ], +} + +{ + name: "data: one input object reached through two keys is one JS object", + graph: { + nodes: [ + {expression: "share", fields: {left: "o", right: "o"}}, + {function: "f", source: """export const handler = async (input) => { input.left.tag = 'L'; return { sameObject: input.left === input.right, rightTag: input.right.tag ?? 'none' }; };"""}, + ], + }, + cases: [ + [{o: {v: 1}}, {sameObject: true, rightTag: "L"}, "question: whether two keys holding the same value arrive as one JS object depends on the engine sharing the value internally; values are meant to be copies"], + [{o: {}}, {sameObject: true, rightTag: "L"}, "question: whether two keys holding the same value arrive as one JS object depends on the engine sharing the value internally; values are meant to be copies"], + ], +} + +// --- $nodes in returned values ------------------------------------------------------------------- + +{ + name: "data: returning the $nodes proxy copies the node outputs", + graph: { + nodes: [ + {expression: "e", fields: {a: "x + 1"}}, + {function: "f", source: """export const handler = async (input) => ({ nodes: input.$nodes });"""}, + ], + }, + cases: [ + [{x: 1}, {nodes: {input: {x: 1}, e: {a: 2}}}], + [{x: 0}, {nodes: {input: {x: 0}, e: {a: 1}}}], + ], +} + +{ + name: "data: a nested $nodes key is stripped from the result", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ inner: { $nodes: 1, k: input.k }, list: [{ $nodes: 2, k: input.k }] });"""}], + }, + cases: [ + [{k: 1}, {inner: {k: 1}, list: [{k: 1}]}, "question: $nodes is stripped at every depth of a function result, not only from the top level"], + [{k: "x"}, {inner: {k: "x"}, list: [{k: "x"}]}, "question: $nodes is stripped at every depth of a function result, not only from the top level"], + ], +} + +{ + name: "data: a nested $nodes key in the input reaches the handler", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ inner: input.o.$nodes ?? 'absent', top: typeof input.$nodes });"""}], + }, + cases: [ + [{o: {$nodes: 5}}, {inner: 5, top: "object"}], + [{o: {}}, {inner: "absent", top: "object"}], + ], +} + +// --- Unicode -------------------------------------------------------------------------------------- +// Strings are UTF-16 inside JS: length counts code units, iteration counts code points. + +{ + name: "data: string length in code units and code points", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ units: input.s.length, points: [...input.s].length });"""}], + }, + cases: [ + [{s: "abc"}, {units: 3, points: 3}], + [{s: "é"}, {units: 1, points: 1}], + [{s: "😀"}, {units: 2, points: 1}], + [{s: "👨‍👩‍👧"}, {units: 8, points: 5}], + [{s: "日本語"}, {units: 3, points: 3}], + [{s: ""}, {units: 0, points: 0}], + ], +} + +{ + name: "data: reversing strings with surrogate pairs", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ reversed: [...input.s].reverse().join('') });"""}], + }, + cases: [ + [{s: "abc"}, {reversed: "cba"}], + [{s: "a😀b"}, {reversed: "b😀a"}], + [{s: "日本"}, {reversed: "本日"}], + ], +} + +{ + name: "data: a lone surrogate cannot be returned", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ s: input.s.slice(0, input.n) });"""}], + }, + cases: [ + [{s: "😀x", n: 2}, {s: "😀"}], + [{s: "😀x", n: 1}, "!error: failed to convert to string"], + [{s: "ab", n: 1}, {s: "a"}], + ], +} + +{ + name: "data: case mapping beyond ASCII", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ upper: input.s.toUpperCase(), lower: input.s.toLowerCase() });"""}], + }, + cases: [ + [{s: "straße"}, {upper: "STRASSE", lower: "straße"}], + [{s: "ÉCOLE"}, {upper: "ÉCOLE", lower: "école"}], + [{s: "Ωmega"}, {upper: "ΩMEGA", lower: "ωmega"}], + [{s: "日本"}, {upper: "日本", lower: "日本"}], + ], +} + +{ + name: "data: normalization forms", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + nfc: input.s.normalize('NFC').length, + nfd: input.s.normalize('NFD').length, + same: input.s.normalize('NFC') === input.t.normalize('NFC'), + raw: input.s === input.t, +});"""}], + }, + cases: [ + [{s: "\u00e9", t: "e\u0301"}, {nfc: 1, nfd: 2, same: true, raw: false}], + [{s: "e", t: "e"}, {nfc: 1, nfd: 1, same: true, raw: true}], + [{s: "\u00c5", t: "A\u030a"}, {nfc: 1, nfd: 2, same: true, raw: false}], + ], +} + +{ + name: "data: unicode keys and values round trip", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const out = {}; + for (const [k, v] of Object.entries(input)) if (k !== '$nodes') out[k + '✓'] = v + '!'; + return out; +};"""}], + }, + cases: [ + [{"名前": "太郎"}, {"名前✓": "太郎!"}], + [{"ключ": "значение", "😀": "🎉"}, {"ключ✓": "значение!", "😀✓": "🎉!"}], + [{"": ""}, {"✓": "!"}], + ], +} + +{ + name: "data: control characters and escapes", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + joined: input.parts.join('\n'), + tab: 'a\tb', + nul: 'a\u0000b'.length, + quote: `"${input.parts[0]}"`, +});"""}], + }, + cases: [ + [{parts: ["x", "y"]}, {joined: "x\ny", tab: "a\tb", nul: 3, quote: "\"x\""}], + [{parts: ["é"]}, {joined: "é", tab: "a\tb", nul: 3, quote: "\"é\""}], + ], +} + +{ + name: "data: padding and slicing with multi-unit characters", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ padded: input.s.padStart(5, '*'), first: input.s.codePointAt(0), at: input.s.at(-1) });"""}], + }, + cases: [ + [{s: "ab"}, {padded: "***ab", first: 97, at: "b"}], + [{s: "€"}, {padded: "****€", first: 8364, at: "€"}], + [{s: "😀"}, "!error: failed to convert to string"], + ], +} + +{ + name: "data: sorting unicode strings", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ + plain: [...input.v].sort(), + locale: [...input.v].sort((a, b) => a.localeCompare(b)), +});"""}], + }, + cases: [ + [{v: ["b", "a", "B", "A"]}, {plain: ["A", "B", "a", "b"], locale: ["A", "B", "a", "b"]}, "question: localeCompare in QuickJS compares code units rather than using locale collation"], + [{v: ["é", "e", "f"]}, {plain: ["e", "f", "é"], locale: ["e", "f", "é"]}, "question: localeCompare in QuickJS compares code units rather than using locale collation"], + ], +} + +{ + name: "data: encodeURIComponent and decodeURIComponent", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => { + const enc = encodeURIComponent(input.s); + return { enc, back: decodeURIComponent(enc) === input.s }; +};"""}], + }, + cases: [ + [{s: "a b&c"}, {enc: "a%20b%26c", back: true}], + [{s: "é"}, {enc: "%C3%A9", back: true}], + [{s: "😀"}, {enc: "%F0%9F%98%80", back: true}], + [{s: ""}, {enc: "", back: true}], + ], +} + +{ + name: "data: unicode strings from JS read by a table", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({ city: input.city.normalize('NFC').trim() });"""}, + {table: "t", inputs: ["city"], outputs: ["country"], rules: [ + ["'Zürich'", "'CH'"], + ["'München'", "'DE'"], + ["", "'?'"], + ]}, + ], + }, + cases: [ + [{city: " Zürich "}, {country: "CH"}], + [{city: "Zürich"}, {country: "CH"}], + [{city: "München"}, {country: "DE"}], + [{city: "Zurich"}, {country: "?"}], + ], +} + +// --- Dates through dayjs ------------------------------------------------------------------------ +// Dates enter as strings; dayjs parses them in UTC (the spec time zone) and formats back. + +{ + name: "data: dayjs month arithmetic clamps to the end of the month", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => ({ d: dayjs(input.d).add(input.months, 'month').format('YYYY-MM-DD') });"""}], + }, + cases: [ + [{d: "2024-01-31", months: 1}, {d: "2024-02-29"}], + [{d: "2023-01-31", months: 1}, {d: "2023-02-28"}], + [{d: "2024-03-31", months: -1}, {d: "2024-02-29"}], + [{d: "2024-02-29", months: 12}, {d: "2025-02-28"}], + [{d: "2024-05-15", months: 0}, {d: "2024-05-15"}], + ], +} + +{ + name: "data: dayjs start and end of periods", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => { + const d = dayjs(input.d); + return { + monthStart: d.startOf('month').format('YYYY-MM-DD'), + monthEnd: d.endOf('month').format('YYYY-MM-DD'), + yearEnd: d.endOf('year').format('YYYY-MM-DDTHH:mm:ss'), + days: d.daysInMonth(), + }; +};"""}], + }, + cases: [ + [{d: "2024-02-10"}, {monthStart: "2024-02-01", monthEnd: "2024-02-29", yearEnd: "2024-12-31T23:59:59", days: 29}], + [{d: "2023-02-10"}, {monthStart: "2023-02-01", monthEnd: "2023-02-28", yearEnd: "2023-12-31T23:59:59", days: 28}], + [{d: "2024-12-31T23:00:00Z"}, {monthStart: "2024-12-01", monthEnd: "2024-12-31", yearEnd: "2024-12-31T23:59:59", days: 31}], + ], +} + +{ + name: "data: dayjs differences in months and years", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => { + const a = dayjs(input.from); + const b = dayjs(input.to); + return { months: b.diff(a, 'month'), years: b.diff(a, 'year'), exactYears: b.diff(a, 'year', true) }; +};"""}], + }, + cases: [ + [{from: "2000-02-29", to: "2024-02-28"}, {months: 287, years: 23, exactYears: 23.99731182795699}], + [{from: "2020-01-15", to: "2021-01-15"}, {months: 12, years: 1, exactYears: 1}], + [{from: "2024-01-31", to: "2024-02-29"}, {months: 1, years: 0, exactYears: 0.0833333333333333}, "question: dayjs counts Jan 31 -> Feb 29 as a whole month because both are month ends"], + [{from: "2024-06-01", to: "2024-01-01"}, {months: -5, years: 0, exactYears: -0.4166666666666667}], + ], +} + +{ + name: "data: dayjs age from a birth date", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => ({ age: dayjs(input.on).diff(dayjs(input.born), 'year') });"""}], + }, + cases: [ + [{born: "2000-03-20", on: "2025-03-20"}, {age: 25}], + [{born: "2000-03-21", on: "2025-03-20"}, {age: 24}], + [{born: "2004-02-29", on: "2025-02-28"}, {age: 21}, "question: dayjs treats Feb 28 of a common year as the anniversary of Feb 29"], + [{born: "2004-02-29", on: "2025-03-01"}, {age: 21}], + ], +} + +{ + name: "data: dayjs format tokens", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => ({ s: dayjs(input.d).format(input.fmt) });"""}], + }, + cases: [ + [{d: "2024-07-04T09:05:03Z", fmt: "YYYY/MM/DD HH:mm:ss"}, {s: "2024/07/04 09:05:03"}], + [{d: "2024-07-04T09:05:03Z", fmt: "D MMM YY"}, {s: "4 Jul 24"}], + [{d: "2024-07-04T21:05:03Z", fmt: "h:mm A dddd"}, {s: "9:05 PM Thursday"}], + [{d: "2024-07-04", fmt: "[Q]Q"}, {s: "QQ"}, "question: the quarter token Q is not formatted; the advancedFormat plugin is not bundled"], + ], +} + +{ + name: "data: dayjs unix timestamps and ISO strings", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => { + const d = typeof input.v === 'number' ? dayjs.unix(input.v) : dayjs(input.v); + return { unix: d.unix(), iso: d.toISOString(), ms: d.valueOf() }; +};"""}], + }, + cases: [ + [{v: 0}, {unix: 0, iso: "1970-01-01T00:00:00.000Z", ms: 0}], + [{v: 1700000000}, {unix: 1700000000, iso: "2023-11-14T22:13:20.000Z", ms: 1700000000000}], + [{v: "2024-01-01T00:00:00.500Z"}, {unix: 1704067200, iso: "2024-01-01T00:00:00.500Z", ms: 1704067200500}], + [{v: -86400}, {unix: -86400, iso: "1969-12-31T00:00:00.000Z", ms: -86400000}], + ], +} + +{ + name: "data: dayjs with an invalid date formats as Invalid Date", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => { + const d = dayjs(input.d); + return { valid: d.isValid(), s: d.format('YYYY-MM-DD') }; +};"""}], + }, + cases: [ + [{d: "2024-13-01"}, {valid: true, s: "2025-01-01"}, "question: dayjs parses month 13 by rolling over into the next year instead of rejecting it"], + [{d: "garbage"}, {valid: false, s: "Invalid Date"}], + [{d: "2024-02-30"}, {valid: true, s: "2024-03-01"}], + [{d: "2024-02-28"}, {valid: true, s: "2024-02-28"}], + ], +} + +{ + name: "data: dayjs sorting and comparing dates", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => { + const sorted = [...input.dates].sort((a, b) => dayjs(a).valueOf() - dayjs(b).valueOf()); + return { first: sorted[0] ?? null, last: sorted.at(-1) ?? null, sameDay: dayjs(input.dates[0]).isSame(input.dates[1], 'day') }; +};"""}], + }, + cases: [ + [{dates: ["2024-03-01", "2024-01-15", "2024-02-01"]}, {first: "2024-01-15", last: "2024-03-01", sameDay: false}], + [{dates: ["2024-01-01T08:00:00Z", "2024-01-01T20:00:00Z"]}, {first: "2024-01-01T08:00:00Z", last: "2024-01-01T20:00:00Z", sameDay: true}], + [{dates: ["2023-12-31", "2023-12-31"]}, {first: "2023-12-31", last: "2023-12-31", sameDay: true}], + ], +} + +{ + name: "data: schema date inputs parsed by dayjs", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => ({ next: dayjs(input.d).add(1, 'day').format('YYYY-MM-DD'), weekday: dayjs(input.d).day() });"""}], + }, + cases: [ + [{d: date('2024-05-01')}, {next: "2024-05-02", weekday: 3}], + [{d: date('2024-12-31')}, {next: "2025-01-01", weekday: 2}], + [{d: "2025-03-20"}, {next: "2025-03-21", weekday: 4}], + ], +} + +{ + name: "data: a dayjs object returned as a value", + graph: { + nodes: [{function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => ({ iso: dayjs(input.d).toISOString(), json: JSON.parse(JSON.stringify({ d: dayjs(input.d) })).d });"""}], + }, + cases: [ + [{d: "2024-01-01"}, {iso: "2024-01-01T00:00:00.000Z", json: "2024-01-01T00:00:00.000Z"}], + [{d: "2024-06-15T12:30:00Z"}, {iso: "2024-06-15T12:30:00.000Z", json: "2024-06-15T12:30:00.000Z"}], + ], +} + +{ + name: "data: a date string from JS compared by an expression node", + graph: { + nodes: [ + {function: "f", source: """import dayjs from 'dayjs'; +export const handler = async (input) => ({ due: dayjs(input.start).add(input.days, 'day').format('YYYY-MM-DD') });"""}, + {expression: "e", fields: {due: "due", late: "d(due) < d('2025-03-20')"}}, + ], + edges: ["input -> f -> e -> output"], + }, + cases: [ + [{start: "2025-03-01", days: 10}, {due: "2025-03-11", late: true}], + [{start: "2025-03-15", days: 10}, {due: "2025-03-25", late: false}], + [{start: "2025-03-20", days: 0}, {due: "2025-03-20", late: false}], + ], +} diff --git a/core/engine/tests/spec/graph/43-functions-in-graphs.json5 b/core/engine/tests/spec/graph/43-functions-in-graphs.json5 new file mode 100644 index 00000000..ec34f8a5 --- /dev/null +++ b/core/engine/tests/spec/graph/43-functions-in-graphs.json5 @@ -0,0 +1,823 @@ +// Function nodes in larger graphs: v2 functions between tables, switches and expressions, +// several function nodes in one graph, functions after loops and inside sub-decisions, +// functions reading `$nodes` of several upstream nodes, and how function errors propagate. +// A function node's input is the merged output of its parents (like any other node); its +// output replaces that input for the nodes downstream. + +// --- Between tables, switches and expressions --------------------------------------------------- + +{ + name: "graphs: expression -> function -> table", + graph: { + nodes: [ + {expression: "prep", fields: {total: "price * qty", country: "upper(country)"}}, + {function: "fee", source: """export const handler = async (input) => ({ country: input.country, gross: input.total + (input.country === 'DE' ? 5 : 10) });"""}, + {table: "band", inputs: ["gross", "country"], outputs: ["band"], rules: [ + ["> 100", "'DE'", "'de-high'"], + ["> 100", "", "'high'"], + ["", "", "'low'"], + ]}, + ], + }, + cases: [ + [{price: 50, qty: 2, country: "de"}, {band: "de-high"}], + [{price: 50, qty: 2, country: "fr"}, {band: "high"}], + [{price: 1, qty: 1, country: "de"}, {band: "low"}], + [{price: 45, qty: 2, country: "de"}, {band: "low"}], + [{price: 45, qty: 2, country: "us"}, {band: "low"}], + ], +} + +{ + name: "graphs: table -> function -> expression", + graph: { + nodes: [ + {table: "rate", inputs: ["tier"], outputs: ["rate"], rules: [ + ["'gold'", "0.2"], + ["'silver'", "0.1"], + ["", "0"], + ]}, + {function: "apply", source: """export const handler = async (input) => ({ rate: input.rate, discount: input.$nodes.input.amount * input.rate });"""}, + {expression: "final", fields: {pay: "$nodes.input.amount - discount", rate: "rate"}}, + ], + }, + cases: [ + [{tier: "gold", amount: 100}, {pay: 80, rate: 0.2}], + [{tier: "silver", amount: 50}, {pay: 45, rate: 0.1}], + [{tier: "none", amount: 10}, {pay: 10, rate: 0}], + [{amount: 0}, {pay: 0, rate: 0}], + ], +} + +{ + name: "graphs: a table without a match gives the function an empty input", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["hit"], rules: [ + ["> 10", "true"], + ]}, + {function: "f", source: """export const handler = async (input) => ({ keys: Object.keys(input).filter((k) => k !== '$nodes'), hit: input.hit ?? false });"""}, + ], + }, + cases: [ + [{v: 20}, {keys: ["hit"], hit: true}], + [{v: 1}, {keys: [], hit: false}], + [{}, {keys: [], hit: false}], + ], +} + +{ + name: "graphs: a collect table output arrives as an array", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["tag"], rules: [ + ["> 0", "'positive'"], + ["> 10", "'big'"], + ["", "'any'"], + ]}, + {function: "f", source: """export const handler = async (input) => { + const rows = input.$nodes.t; + return { isArray: Array.isArray(rows), tags: rows.map((r) => r.tag) }; +};"""}, + ], + }, + cases: [ + [{v: 20}, {isArray: true, tags: ["positive", "big", "any"]}], + [{v: 5}, {isArray: true, tags: ["positive", "any"]}], + [{v: -1}, {isArray: true, tags: ["any"]}], + ], +} + +{ + name: "graphs: a function result decides a switch", + graph: { + nodes: [ + {function: "score", source: """export const handler = async (input) => ({ score: (input.signals ?? []).reduce((s, x) => s + x.weight, 0) });"""}, + {switch: "route", when: ["score >= 10", "score >= 5", ""]}, + {expression: "deny", fields: {decision: "'deny'", score: "score"}}, + {expression: "review", fields: {decision: "'review'", score: "score"}}, + {expression: "allow", fields: {decision: "'allow'", score: "score"}}, + ], + edges: ["input -> score -> route", "route:0 -> deny -> output", "route:1 -> review -> output", "route:2 -> allow -> output"], + }, + cases: [ + [{signals: [{weight: 6}, {weight: 6}]}, {decision: "deny", score: 12}], + [{signals: [{weight: 5}]}, {decision: "review", score: 5}], + [{signals: [{weight: 1}, {weight: 0.5}]}, {decision: "allow", score: 1.5}], + [{}, {decision: "allow", score: 0}], + ], +} + +{ + name: "graphs: different functions on each switch branch", + graph: { + nodes: [ + {switch: "route", when: ["kind == 'pct'", "kind == 'flat'", ""]}, + {function: "pct", source: """export const handler = async (input) => ({ price: input.base * (1 - input.value / 100), via: 'pct' });"""}, + {function: "flat", source: """export const handler = async (input) => ({ price: Math.max(0, input.base - input.value), via: 'flat' });"""}, + {expression: "none", fields: {price: "base", via: "'none'"}}, + ], + edges: ["input -> route", "route:0 -> pct -> output", "route:1 -> flat -> output", "route:2 -> none -> output"], + }, + cases: [ + [{kind: "pct", base: 200, value: 10}, {price: 180, via: "pct"}], + [{kind: "flat", base: 200, value: 30}, {price: 170, via: "flat"}], + [{kind: "flat", base: 20, value: 30}, {price: 0, via: "flat"}], + [{base: 99}, {price: 99, via: "none"}], + ], +} + +{ + name: "graphs: functions on several collect-switch branches merge at the output", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["age >= 18", "member", "country == 'NL'"]}, + {function: "adult", source: """export const handler = async (input) => ({ flags: { adult: true }, notes: ['adult'] });"""}, + {function: "member", source: """export const handler = async (input) => ({ flags: { member: true }, notes: ['member'] });"""}, + {function: "local", source: """export const handler = async (input) => ({ flags: { local: true }, notes: ['local'] });"""}, + ], + edges: ["input -> s", "s:0 -> adult -> output", "s:1 -> member -> output", "s:2 -> local -> output"], + }, + cases: [ + [{age: 30, member: true, country: "NL"}, {flags: {adult: true, member: true, local: true}, notes: ["adult"]}], + [{age: 30, member: false, country: "DE"}, {flags: {adult: true}, notes: ["adult"]}], + [{age: 10, member: true, country: "NL"}, {flags: {member: true, local: true}, notes: ["member"]}], + [{age: 10, member: false}, {}], + ], +} + +{ + name: "graphs: a function after a switch join sees the taken branch only", + graph: { + nodes: [ + {switch: "route", when: ["vip", ""]}, + {expression: "vip", fields: {level: "'vip'", limit: "1000"}}, + {expression: "std", fields: {level: "'std'", limit: "100"}}, + {function: "summary", source: """export const handler = async (input) => ({ text: `${input.level}:${input.limit}`, vipRan: 'vip' in input.$nodes, stdRan: 'std' in input.$nodes });"""}, + ], + edges: ["input -> route", "route:0 -> vip -> summary", "route:1 -> std -> summary", "summary -> output"], + }, + cases: [ + [{vip: true}, {text: "vip:1000", vipRan: true, stdRan: false}], + [{vip: false}, {text: "std:100", vipRan: false, stdRan: true}], + [{}, {text: "std:100", vipRan: false, stdRan: true}], + ], +} + +{ + name: "graphs: a function output under a pass-through expression", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({ norm: input.name?.trim().toLowerCase() ?? '', raw: input.name ?? null });"""}, + {expression: "e", passThrough: true, fields: {short: "len(norm) <= 3"}}, + ], + }, + cases: [ + [{name: " Ann "}, {norm: "ann", raw: " Ann ", short: true}], + [{name: "Robert"}, {norm: "robert", raw: "Robert", short: false}], + [{}, {norm: "", short: true}], + ], +} + +{ + name: "graphs: an expression output path feeding a function", + graph: { + nodes: [ + {expression: "e", outputPath: "calc", fields: {double: "v * 2", half: "v / 2"}}, + {function: "f", source: """export const handler = async (input) => ({ keys: Object.keys(input.calc), sum: input.calc.double + input.calc.half });"""}, + ], + }, + cases: [ + [{v: 4}, {keys: ["double", "half"], sum: 10}], + [{v: 1}, {keys: ["double", "half"], sum: 2.5}], + [{v: 0}, {keys: ["double", "half"], sum: 0}], + ], +} + +{ + name: "graphs: a table with an input field after a function", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({ applicant: { age: input.age, income: input.income * 12 } });"""}, + {table: "t", inputField: "applicant", outputPath: "result", inputs: ["age", "income"], outputs: ["ok"], rules: [ + [">= 18", ">= 30000", "true"], + ["", "", "false"], + ]}, + ], + }, + cases: [ + [{age: 30, income: 3000}, {result: {ok: true}}], + [{age: 30, income: 2000}, {result: {ok: false}}], + [{age: 17, income: 9000}, {result: {ok: false}}], + [{age: 18, income: 2500}, {result: {ok: true}}], + ], +} + +// --- Several function nodes --------------------------------------------------------------------- + +{ + name: "graphs: three functions in a chain", + graph: { + nodes: [ + {function: "parse", source: """export const handler = async (input) => ({ parts: input.csv.split(',').map((s) => s.trim()).filter(Boolean) });"""}, + {function: "count", source: """export const handler = async (input) => ({ parts: input.parts, counts: input.parts.reduce((m, p) => ({ ...m, [p]: (m[p] ?? 0) + 1 }), {}) });"""}, + {function: "top", source: """export const handler = async (input) => { + const entries = Object.entries(input.counts).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); + return { top: entries[0]?.[0] ?? null, distinct: entries.length, total: input.parts.length }; +};"""}, + ], + }, + cases: [ + [{csv: "a, b, a, c"}, {top: "a", distinct: 3, total: 4}], + [{csv: "x"}, {top: "x", distinct: 1, total: 1}], + [{csv: "b,a"}, {top: "a", distinct: 2, total: 2}], + [{csv: " , "}, {distinct: 0, total: 0}], + ], +} + +{ + name: "graphs: a diamond of functions joined by a third", + graph: { + nodes: [ + {function: "left", source: """export const handler = async (input) => ({ left: input.v * 2 });"""}, + {function: "right", source: """export const handler = async (input) => ({ right: input.v + 100 });"""}, + {function: "join", source: """export const handler = async (input) => ({ sum: input.left + input.right, fromNodes: input.$nodes.left.left + input.$nodes.right.right });"""}, + ], + edges: ["input -> left -> join", "input -> right -> join", "join -> output"], + }, + cases: [ + [{v: 1}, {sum: 103, fromNodes: 103}], + [{v: 0}, {sum: 100, fromNodes: 100}], + [{v: -50}, {sum: -50, fromNodes: -50}], + ], +} + +{ + name: "graphs: two functions writing the same key meet at a join", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ({ who: 'a', a: true, shared: { a: 1 } });"""}, + {function: "b", source: """export const handler = async (input) => ({ who: 'b', b: true, shared: { b: 2 } });"""}, + {function: "join", source: """export const handler = async (input) => ({ who: input.who, a: input.a ?? false, b: input.b ?? false, shared: input.shared });"""}, + ], + edges: ["input -> a -> join", "input -> b -> join", "join -> output"], + }, + cases: [ + [{}, {who: "a", a: true, b: true, shared: {a: 1, b: 2}}], + [{x: 1}, {who: "a", a: true, b: true, shared: {a: 1, b: 2}}], + ], +} + +{ + name: "graphs: a function and an expression in parallel", + graph: { + nodes: [ + {function: "js", source: """export const handler = async (input) => ({ jsSum: input.items.reduce((s, x) => s + x, 0) });"""}, + {expression: "zen", fields: {zenSum: "sum(items)"}}, + ], + edges: ["input -> js -> output", "input -> zen -> output"], + }, + cases: [ + [{items: [1, 2, 3]}, {jsSum: 6, zenSum: 6}], + [{items: [0.1, 0.2]}, {jsSum: 0.3, zenSum: 0.3}], + [{items: [0.1, 0.2, 0.3]}, {jsSum: 0.6, zenSum: 0.6}], + [{items: []}, {jsSum: 0, zenSum: 0}], + ], +} + +{ + name: "graphs: a later function reads every earlier function by name", + graph: { + nodes: [ + {function: "one", source: """export const handler = async (input) => ({ step: 1 });"""}, + {function: "two", source: """export const handler = async (input) => ({ step: input.step + 1 });"""}, + {function: "three", source: """export const handler = async (input) => ({ step: input.step + 1 });"""}, + {function: "report", source: """export const handler = async (input) => ({ + steps: ['one', 'two', 'three'].map((n) => input.$nodes[n].step), + names: Object.keys(input.$nodes).sort(), +});"""}, + ], + }, + cases: [ + [{}, {steps: [1, 2, 3], names: ["input", "one", "three", "two"]}], + [{step: 99}, {steps: [1, 2, 3], names: ["input", "one", "three", "two"]}], + ], +} + +{ + name: "graphs: v1 and v2 functions in parallel feeding a table", + graph: { + nodes: [ + {function: "v2", source: """export const handler = async (input) => ({ a: input.x > 0 });"""}, + {functionV1: "v1", source: """const handler = (input) => ({ b: input.y > 0 });"""}, + {table: "t", inputs: ["a", "b"], outputs: ["r"], rules: [ + ["true", "true", "'both'"], + ["true", "", "'a'"], + ["", "true", "'b'"], + ["", "", "'none'"], + ]}, + ], + edges: ["input -> v2 -> t", "input -> v1 -> t", "t -> output"], + }, + cases: [ + [{x: 1, y: 1}, {r: "both"}], + [{x: 1, y: 0}, {r: "a"}], + [{x: 0, y: 1}, {r: "b"}], + [{x: 0, y: 0}, {r: "none"}], + ], +} + +// --- Functions reading $nodes of several upstream nodes ------------------------------------------- + +{ + name: "graphs: a function combines a table, an expression and the input", + graph: { + nodes: [ + {table: "risk", inputs: ["score"], outputs: ["risk"], rules: [ + ["< 500", "'high'"], + ["", "'low'"], + ]}, + {expression: "ratio", fields: {dti: "debt / income"}}, + {function: "decide", source: """export const handler = async (input) => { + const n = input.$nodes; + const ok = n.risk.risk === 'low' && n.ratio.dti < 0.4; + return { ok, reason: ok ? null : n.risk.risk === 'high' ? 'score' : 'dti', name: n.input.name }; +};"""}, + ], + edges: ["input -> risk -> decide", "input -> ratio -> decide", "decide -> output"], + }, + cases: [ + [{score: 700, debt: 100, income: 1000, name: "a"}, {ok: true, name: "a"}], + [{score: 400, debt: 100, income: 1000, name: "b"}, {ok: false, reason: "score", name: "b"}], + [{score: 700, debt: 500, income: 1000, name: "c"}, {ok: false, reason: "dti", name: "c"}], + [{score: 500, debt: 0, income: 1, name: "d"}, {ok: true, name: "d"}], + ], +} + +{ + name: "graphs: a function reads a node that is not its parent", + graph: { + nodes: [ + {expression: "first", fields: {a: "x + 1"}}, + {expression: "second", fields: {b: "a * 10"}}, + {function: "f", source: """export const handler = async (input) => ({ b: input.b, a: input.$nodes.first.a, ownInput: Object.keys(input).filter((k) => k !== '$nodes') });"""}, + ], + }, + cases: [ + [{x: 1}, {b: 20, a: 2, ownInput: ["b"]}], + [{x: 0}, {b: 10, a: 1, ownInput: ["b"]}], + [{x: -1}, {b: 0, a: 0, ownInput: ["b"]}], + ], +} + +{ + name: "graphs: $nodes of a loop node is an array", + graph: { + nodes: [ + {expression: "each", inputField: "items", executionMode: "loop", fields: {d: "v * 2"}}, + {function: "f", source: """export const handler = async (input) => ({ + isArray: Array.isArray(input.$nodes.each), + ds: input.$nodes.each.map((r) => r.d), +});"""}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {isArray: true, ds: [2, 4]}], + [{items: [{v: 0.5}]}, {isArray: true, ds: [1]}], + [{items: []}, {isArray: true, ds: []}], + ], +} + +{ + name: "graphs: $nodes of a sub-decision node", + decisions: { + child: {nodes: [{expression: "e", fields: {y: "x * 3", tag: "'child'"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {function: "f", source: """export const handler = async (input) => ({ y: input.$nodes.call.y, tag: input.$nodes.call.tag, direct: input.y });"""}, + ], + }, + cases: [ + [{x: 1}, {y: 3, tag: "child", direct: 3}], + [{x: 0.1}, {y: 0.3, tag: "child", direct: 0.3}], + ], +} + +{ + name: "graphs: $nodes of a switch and a custom node", + graph: { + nodes: [ + {custom: "c", kind: "config", config: {region: "eu"}}, + {switch: "route", when: ["region == 'eu'", ""]}, + {function: "eu", source: """export const handler = async (input) => ({ + region: input.$nodes.c.region, + switchSeen: 'route' in input.$nodes, + switchKeys: Object.keys(input.$nodes.route ?? {}), +});"""}, + {expression: "other", fields: {region: "'other'"}}, + ], + edges: ["input -> c -> route", "route:0 -> eu -> output", "route:1 -> other -> output"], + }, + cases: [ + [{}, {region: "eu", switchSeen: true, switchKeys: ["region"]}], + [{x: 1}, {region: "eu", switchSeen: true, switchKeys: ["region"]}], + ], +} + +{ + name: "graphs: two functions read each other's predecessor outputs", + graph: { + nodes: [ + {expression: "base", fields: {n: "n"}}, + {function: "sq", source: """export const handler = async (input) => ({ sq: input.$nodes.base.n ** 2 });"""}, + {function: "cube", source: """export const handler = async (input) => ({ cube: input.$nodes.base.n ** 3, sqSeen: input.$nodes.sq?.sq ?? null });"""}, + ], + edges: ["input -> base", "base -> sq -> output", "base -> cube -> output"], + }, + cases: [ + [{n: 2}, {sq: 4, cube: 8, sqSeen: 4}, "question: a parallel sibling's output is visible in $nodes when the sibling happens to run first"], + [{n: 3}, {sq: 9, cube: 27, sqSeen: 9}, "question: a parallel sibling's output is visible in $nodes when the sibling happens to run first"], + ], +} + +// --- Functions after loops ---------------------------------------------------------------------- + +{ + name: "graphs: a function after an expression loop with an output path", + graph: { + nodes: [ + {expression: "lines", inputField: "items", outputPath: "lines", executionMode: "loop", fields: {total: "price * qty"}}, + {function: "sum", source: """export const handler = async (input) => ({ count: input.lines.length, total: input.lines.reduce((s, l) => s + l.total, 0) });"""}, + ], + }, + cases: [ + [{items: [{price: 2, qty: 3}, {price: 1.5, qty: 2}]}, {count: 2, total: 9}], + [{items: [{price: 0.1, qty: 3}]}, {count: 1, total: 0.3}], + [{items: []}, {count: 0, total: 0}], + ], +} + +{ + name: "graphs: a function after a table loop", + graph: { + nodes: [ + {table: "grade", inputField: "students", outputPath: "grades", executionMode: "loop", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 70", "'B'"], + ["", "'C'"], + ]}, + {function: "dist", source: """export const handler = async (input) => { + const dist = {}; + for (const g of input.grades) dist[g.grade] = (dist[g.grade] ?? 0) + 1; + return { dist }; +};"""}, + ], + }, + cases: [ + [{students: [{score: 95}, {score: 80}, {score: 10}, {score: 91}]}, {dist: {A: 2, B: 1, C: 1}}], + [{students: [{score: 70}]}, {dist: {B: 1}}], + [{students: []}, {dist: {}}], + ], +} + +{ + name: "graphs: a function builds the array that a loop node iterates", + graph: { + nodes: [ + {function: "expand", source: """export const handler = async (input) => ({ items: Array.from({ length: input.n }, (_, i) => ({ i, sq: i * i })) });"""}, + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {label: "string(i) + ':' + string(sq)"}}, + ], + }, + cases: [ + [{n: 3}, {out: [{label: "0:0"}, {label: "1:1"}, {label: "2:4"}]}], + [{n: 1}, {out: [{label: "0:0"}]}], + [{n: 0}, {out: []}], + ], +} + +{ + name: "graphs: a function between two loops", + graph: { + nodes: [ + {expression: "first", inputField: "items", outputPath: "doubled", executionMode: "loop", fields: {v: "v * 2"}}, + {function: "filter", source: """export const handler = async (input) => ({ kept: input.doubled.filter((x) => x.v > input.$nodes.input.min) });"""}, + {expression: "second", inputField: "kept", outputPath: "out", executionMode: "loop", fields: {v: "v + 1"}}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: 5}, {v: 10}], min: 5}, {out: [{v: 11}, {v: 21}]}], + [{items: [{v: 1}], min: 5}, {out: []}], + [{items: [], min: 0}, {out: []}], + ], +} + +// --- Functions inside sub-decisions ------------------------------------------------------------- + +{ + name: "graphs: a child graph with a function between expressions", + decisions: { + child: {nodes: [ + {expression: "pre", fields: {n: "n + 1"}}, + {function: "mid", source: """export const handler = async (input) => ({ n: input.n * 10 });"""}, + {expression: "post", fields: {n: "n - 1"}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "child"}], + }, + cases: [ + [{n: 1}, {child: {n: 19}}], + [{n: 0}, {child: {n: 9}}], + [{n: -1}, {child: {n: -1}}], + ], +} + +{ + name: "graphs: a looped sub-decision with a function per item", + decisions: { + item: {nodes: [{function: "f", source: """export const handler = async (input) => ({ sku: input.sku.toUpperCase(), net: Math.round(input.price * (1 - (input.discount ?? 0)) * 100) / 100 });"""}]}, + }, + graph: { + nodes: [{decision: "each", key: "item", inputField: "lines", outputPath: "lines", executionMode: "loop"}], + }, + cases: [ + [{lines: [{sku: "a", price: 10}, {sku: "b", price: 20, discount: 0.25}]}, {lines: [{sku: "A", net: 10}, {sku: "B", net: 15}]}], + [{lines: [{sku: "x", price: 0.3, discount: 0.1}]}, {lines: [{sku: "X", net: 0.27}]}], + [{lines: []}, {lines: []}], + ], +} + +{ + name: "graphs: a looped sub-decision whose function reads the child's input node", + decisions: { + item: {nodes: [ + {input: "request"}, + {expression: "e", fields: {double: "v * 2"}}, + {function: "f", source: """export const handler = async (input) => ({ v: input.$nodes.request.v, double: input.$nodes.e.double, iteration: config.iteration })"""}, + ], edges: ["request -> e -> f -> output"]}, + }, + graph: { + nodes: [{decision: "each", key: "item", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {out: [{v: 1, double: 2, iteration: 1}, {v: 2, double: 4, iteration: 1}]}], + [{items: [{v: 0}]}, {out: [{v: 0, double: 0, iteration: 1}]}], + ], +} + +{ + name: "graphs: a function in a child behind a switch in the parent", + decisions: { + premium: {nodes: [{function: "f", source: """export const handler = async (input) => ({ price: input.base * 1.5, plan: 'premium' });"""}]}, + basic: {nodes: [{expression: "e", fields: {price: "base", plan: "'basic'"}}]}, + }, + graph: { + nodes: [ + {switch: "route", when: ["premium", ""]}, + {decision: "p", key: "premium"}, + {decision: "b", key: "basic"}, + ], + edges: ["input -> route", "route:0 -> p -> output", "route:1 -> b -> output"], + }, + cases: [ + [{premium: true, base: 10}, {price: 15, plan: "premium"}], + [{premium: false, base: 10}, {price: 10, plan: "basic"}], + [{base: 3}, {price: 3, plan: "basic"}], + ], +} + +{ + name: "graphs: nested sub-decisions with functions at two levels", + decisions: { + outer: {nodes: [ + {function: "pre", source: """export const handler = async (input) => ({ v: input.v + 1 });"""}, + {decision: "inner", key: "inner"}, + ]}, + inner: {nodes: [{function: "f", source: """export const handler = async (input) => ({ v: input.v * 2, depth: config.iteration })"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "outer"}], + }, + cases: [ + [{v: 1}, {v: 4, depth: 2}], + [{v: 0}, {v: 2, depth: 2}], + ], +} + +{ + name: "graphs: a function calls zen.evaluate on a sibling decision", + decisions: { + tax: {nodes: [{table: "t", inputs: ["country"], outputs: ["rate"], rules: [ + ["'NL'", "0.21"], + ["'DE'", "0.19"], + ["", "0"], + ]}]}, + }, + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => { + const out = []; + for (const line of input.lines) { + const r = await zen.evaluate('tax', { country: line.country }); + out.push(Math.round(line.net * (1 + r.result.rate) * 100) / 100); + } + return { gross: out }; +};"""}], + }, + cases: [ + [{lines: [{net: 100, country: "NL"}, {net: 100, country: "DE"}, {net: 100, country: "US"}]}, {gross: [121, 119, 100]}], + [{lines: []}, {gross: []}], + [{lines: [{net: 9.99, country: "NL"}]}, {gross: [12.09]}], + ], +} + +// --- Error propagation ---------------------------------------------------------------------------- +// A failing function fails the whole evaluation; nothing after it runs, and an error inside a +// sub-decision or a loop item fails the parent too. + +{ + name: "graphs: a function error after a table fails the evaluation", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["kind"], rules: [ + ["> 0", "'pos'"], + ["", "'other'"], + ]}, + {function: "f", source: """export const handler = async (input) => { + if (input.kind !== 'pos') throw new Error('only positive values'); + return { ok: true }; +};"""}, + ], + }, + cases: [ + [{v: 1}, {ok: true}], + [{v: 0}, "!error: only positive values"], + [{}, "!error: only positive values"], + ], +} + +{ + name: "graphs: a function error names the failing node", + graph: { + nodes: [ + {expression: "e", fields: {v: "v"}}, + {function: "validate", source: """export const handler = async (input) => { if (input.v == null) throw new Error('v is required'); return { v: input.v }; };"""}, + ], + }, + cases: [ + [{v: 1}, {v: 1}], + [{}, "!error: \"nodeId\":\"validate\""], + [{v: null}, "!error: v is required"], + ], +} + +{ + name: "graphs: a function error stops nodes after it", + graph: { + nodes: [ + {function: "check", source: """export const handler = async (input) => { if (input.bad) throw new Error('stop'); return input; };"""}, + {custom: "after", kind: "fail", config: {message: "after ran"}}, + ], + }, + cases: [ + [{bad: true}, "!error: stop"], + [{bad: false}, "!error: after ran"], + ], +} + +{ + name: "graphs: a function error on one parallel branch fails the evaluation", + graph: { + nodes: [ + {expression: "ok", fields: {ok: "true"}}, + {function: "bad", source: """export const handler = async (input) => { if (input.fail) throw new Error('branch failed'); return { bad: false }; };"""}, + ], + edges: ["input -> ok -> output", "input -> bad -> output"], + }, + cases: [ + [{fail: false}, {ok: true, bad: false}], + [{fail: true}, "!error: branch failed"], + ], +} + +{ + name: "graphs: a function error inside a sub-decision fails the parent", + decisions: { + child: {nodes: [{function: "f", source: """export const handler = async (input) => { if (input.v < 0) throw new Error('negative in child'); return { v: input.v }; };"""}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{v: 1}, {v: 1}], + [{v: -1}, "!error: negative in child"], + [{v: 0}, {v: 0}], + ], +} + +{ + name: "graphs: a function error in one loop item fails the whole loop", + decisions: { + item: {nodes: [{function: "f", source: """export const handler = async (input) => { if (typeof input.v !== 'number') throw new Error('item is not a number'); return { v: input.v }; };"""}]}, + }, + graph: { + nodes: [{decision: "each", key: "item", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {out: [{v: 1}, {v: 2}]}], + [{items: [{v: 1}, {v: "x"}]}, "!error: item is not a number"], + [{items: [{}]}, "!error: item is not a number"], + [{items: []}, {out: []}], + ], +} + +{ + name: "graphs: a function catching a failing zen.evaluate keeps going", + decisions: { + strict: {nodes: [{function: "g", source: """export const handler = async (input) => { if (!input.ok) throw new Error('strict failed'); return { fine: true }; };"""}]}, + }, + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => { + try { + const r = await zen.evaluate('strict', { ok: input.ok }); + return { result: r.result.fine }; + } catch (e) { + return { caught: String(e.message ?? e).includes('strict failed') }; + } +};"""}], + }, + cases: [ + [{ok: true}, {result: true}], + [{ok: false}, {caught: true}], + ], +} + +{ + name: "graphs: a failing zen.evaluate not caught fails the graph", + decisions: { + strict: {nodes: [{function: "g", source: """export const handler = async (input) => { throw new Error('inner always fails'); };"""}]}, + }, + graph: { + nodes: [{function: "f", source: """import zen from 'zen'; +export const handler = async (input) => { + const r = await zen.evaluate('strict', input); + return { r }; +};"""}], + }, + cases: [ + [{}, "!error: inner always fails"], + [{a: 1}, "!error: inner always fails"], + ], +} + +{ + name: "graphs: an expression error before a function means the function never runs", + graph: { + nodes: [ + {expression: "e", fields: {n: "a + b"}}, + {function: "f", source: """export const handler = async (input) => { throw new Error('function ran'); };"""}, + ], + }, + cases: [ + [{a: 1, b: 2}, "!error: function ran"], + [{a: "x", b: 2}, "!error: \"nodeId\":\"e\""], + ], +} + +{ + name: "graphs: a function returning bad data for a typed table input", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => ({ v: input.raw })"""}, + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["> 10", "'big'"], + ["", "'small'"], + ]}, + ], + }, + cases: [ + [{raw: 20}, {r: "big"}], + [{raw: 5}, {r: "small"}], + [{raw: "20"}, {r: "small"}], + [{raw: null}, {r: "small"}], + [{}, {r: "small"}], + ], +} + +{ + name: "graphs: an output schema rejects a function result", + graph: { + nodes: [ + {function: "f", source: """export const handler = async (input) => input.ok ? { total: 5 } : { total: 'five' };"""}, + {output: "response", schema: {type: "object", properties: {total: {type: "number"}}, required: ["total"]}}, + ], + edges: ["input -> f -> response"], + }, + cases: [ + [{ok: true}, {total: 5}], + [{ok: false}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/44-realistic-insurance.json5 b/core/engine/tests/spec/graph/44-realistic-insurance.json5 new file mode 100644 index 00000000..77a5e307 --- /dev/null +++ b/core/engine/tests/spec/graph/44-realistic-insurance.json5 @@ -0,0 +1,363 @@ +// Realistic insurance decisions modelled on the shapes of the published sample graphs: chained +// pass-through tables writing dotted outputs, expression nodes reading `$` for their own earlier +// keys, column-less rule tables relaying an earlier verdict, collect tables under an outputPath, +// switch gates in front of the pricing path, loops over per-item tables and `$nodes` reads. +// Each suite is one decision exercised across main paths, boundaries, missing data and bad types. + +// --------------------------------------------------------------------------------------------- +// Auto premium: driver risk (input column is an expression over two history fields), base premium +// with `$` self-references, vehicle and coverage factors, then the final product. +{ + name: "auto premium: driver, vehicle and coverage factors over a base premium", + graph: { + nodes: [ + {input: "request"}, + {table: "driverRisk", passThrough: true, inputs: ["customer.age", "customer.history.accidents + customer.history.violations"], outputs: ["risk.age", "risk.category"], rules: [ + ["< 25", "> 1", "1.5", "'high'"], + ["< 25", "", "1.3", "'elevated'"], + ["[25..69]", "> 2", "1.4", "'high'"], + ["[25..69]", "[1..2]", "1.1", "'moderate'"], + ["[25..69]", "", "1", "'low'"], + [">= 70", "", "1.25", "'elevated'"], + ]}, + {expression: "basePremium", passThrough: true, fields: { + "premium.perThousand": "5.5", + "premium.units": "policy.coverage / 1000", + "premium.base": "$.premium.perThousand * $.premium.units", + }}, + {table: "vehicleRisk", passThrough: true, inputs: ["policy.vehicle", "policy.vehicleAge"], outputs: ["risk.vehicle"], rules: [ + ["'sedan'", "< 3", "0.9"], + ["'sedan'", "", "1"], + ["'suv'", "< 5", "1.1"], + ["'suv'", "", "1.2"], + ["'sports'", "", "1.6"], + ["", "", "1.3"], + ]}, + {table: "coverageFactor", passThrough: true, inputs: ["policy.coverageType", "policy.deductible"], outputs: ["risk.coverage"], rules: [ + ["'basic'", ">= 1000", "0.8"], + ["'basic'", "", "0.9"], + ["'full'", ">= 1000", "1.1"], + ["'full'", "", "1.25"], + ]}, + {expression: "final", fields: { + category: "risk.category", + premium: "round(premium.base * risk.age * risk.vehicle * risk.coverage, 2)", + monthly: "round($.premium / 12, 2)", + }}, + {output: "response"}, + ], + }, + cases: [ + [{customer: {age: 30, history: {accidents: 0, violations: 0}}, policy: {coverage: 100000, vehicle: "sedan", vehicleAge: 2, coverageType: "basic", deductible: 1000}}, {category: "low", premium: 396, monthly: 33}], + [{customer: {age: 22, history: {accidents: 1, violations: 1}}, policy: {coverage: 200000, vehicle: "suv", vehicleAge: 3, coverageType: "full", deductible: 500}}, {category: "high", premium: 2268.75, monthly: 189.06}], + [{customer: {age: 24, history: {accidents: 1, violations: 0}}, policy: {coverage: 50000, vehicle: "sports", vehicleAge: 1, coverageType: "basic", deductible: 500}}, {category: "elevated", premium: 514.8, monthly: 42.9}], + [{customer: {age: 25, history: {accidents: 2, violations: 1}}, policy: {coverage: 100000, vehicle: "sedan", vehicleAge: 3, coverageType: "full", deductible: 1000}}, {category: "high", premium: 847, monthly: 70.58}], + [{customer: {age: 69, history: {accidents: 0, violations: 2}}, policy: {coverage: 150000, vehicle: "truck", vehicleAge: 8, coverageType: "basic", deductible: 2500}}, {category: "moderate", premium: 943.8, monthly: 78.65}], + [{customer: {age: 70, history: {accidents: 4, violations: 4}}, policy: {coverage: 100000, vehicle: "suv", vehicleAge: 5, coverageType: "full", deductible: 0}}, {category: "elevated", premium: 1031.25, monthly: 85.94}], + [{customer: {age: 40, history: {accidents: 0, violations: 0}}, policy: {coverage: 0, vehicle: "sedan", vehicleAge: 1, coverageType: "basic", deductible: 1000}}, {category: "low", premium: 0, monthly: 0}], + [{customer: {age: 40, history: {accidents: 0, violations: 0}}, policy: {coverage: 1234567, vehicle: "sedan", vehicleAge: 10, coverageType: "full", deductible: 999.99}}, {category: "low", premium: 8487.65, monthly: 707.3}], + // Missing or mistyped data: a missing history sums null and errors in the input column, so + // the age-only rules decide; a missing age matches no rule and the final product errors. + [{customer: {age: 30}, policy: {coverage: 100000, vehicle: "sedan", vehicleAge: 2, coverageType: "basic", deductible: 1000}}, {category: "low", premium: 396, monthly: 33}], + [{customer: {history: {accidents: 0, violations: 0}}, policy: {coverage: 100000, vehicle: "sedan", vehicleAge: 2, coverageType: "basic", deductible: 1000}}, "!error"], + [{customer: {age: 30, history: {accidents: 0, violations: 0}}, policy: {coverage: 100000, vehicle: "sedan", vehicleAge: 2, coverageType: "gold", deductible: 1000}}, "!error"], + [{customer: {age: 30, history: {accidents: 0, violations: 0}}, policy: {coverage: "100000", vehicle: "sedan", vehicleAge: 2, coverageType: "basic", deductible: 1000}}, "!error"], + [{customer: {age: 30, history: {accidents: 0, violations: 0}}, policy: {coverage: 100000, vehicle: "sedan", coverageType: "basic", deductible: 1000}}, {category: "low", premium: 440, monthly: 36.67}], + [{customer: {age: "30", history: {accidents: 0, violations: 0}}, policy: {coverage: 100000, vehicle: "sedan", vehicleAge: 2, coverageType: "basic", deductible: 1000}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Life underwriting: a collect table gathers risk factors under `riskFactors`, an expression sums +// them, a first-hit referral table decides, and a last expression shapes the answer. +{ + name: "life underwriting: collected risk factors drive a referral decision", + graph: { + nodes: [ + {input: "application"}, + {table: "riskFactors", hit: "collect", outputPath: "riskFactors", passThrough: true, inputs: ["answers.medical", "answers.hospitalized", "answers.conditions", "answers.occupation", "answers.age"], outputs: ["points", "description"], rules: [ + ["true", "", "", "", "", "10", "'high risk medical condition'"], + ["", "true", "", "", "", "5", "'recent hospitalization'"], + ["", "", "> 2", "", "", "7", "'multiple pre-existing conditions'"], + ["", "", "", "'diver', 'pilot', 'miner'", "", "8", "'hazardous occupation'"], + ["", "", "", "", "> 60", "6", "'age over 60'"], + ["", "", "", "", "< 18", "100", "'minor'"], + ]}, + {expression: "score", passThrough: true, fields: { + totalScore: "sum(map(riskFactors ?? [], #.points))", + reasons: "map(riskFactors ?? [], #.description)", + }}, + {table: "referral", passThrough: true, inputs: ["answers.coverage", "totalScore", "answers.incomplete"], outputs: ["underwriting.manualReview", "underwriting.reason", "underwriting.class"], rules: [ + ["> 1500000", "", "", "true", "'coverage above automatic limit'", "'referred'"], + ["", ">= 20", "", "true", "'risk score'", "'referred'"], + ["", "", "true", "true", "'incomplete application'", "'referred'"], + ["", "[10..19]", "", "false", "'rated'", "'substandard'"], + ["", "< 10", "", "false", "'clean'", "'standard'"], + ]}, + {expression: "answer", fields: {decision: "underwriting", score: "totalScore", reasons: "reasons"}}, + ], + }, + cases: [ + [{answers: {age: 35, coverage: 500000}}, {decision: {manualReview: false, reason: "clean", class: "standard"}, score: 0, reasons: []}], + [{answers: {age: 40, coverage: 500000, medical: true}}, {decision: {manualReview: false, reason: "rated", class: "substandard"}, score: 10, reasons: ["high risk medical condition"]}], + [{answers: {age: 40, coverage: 500000, medical: true, hospitalized: true}}, {decision: {manualReview: false, reason: "rated", class: "substandard"}, score: 15, reasons: ["high risk medical condition", "recent hospitalization"]}], + [{answers: {age: 40, coverage: 500000, medical: true, hospitalized: true, conditions: 3}}, {decision: {manualReview: true, reason: "risk score", class: "referred"}, score: 22, reasons: ["high risk medical condition", "recent hospitalization", "multiple pre-existing conditions"]}], + [{answers: {age: 61, coverage: 250000, occupation: "pilot"}}, {decision: {manualReview: false, reason: "rated", class: "substandard"}, score: 14, reasons: ["hazardous occupation", "age over 60"]}], + [{answers: {age: 60, coverage: 250000, conditions: 2}}, {decision: {manualReview: false, reason: "clean", class: "standard"}, score: 0, reasons: []}], + [{answers: {age: 35, coverage: 1500001}}, {decision: {manualReview: true, reason: "coverage above automatic limit", class: "referred"}, score: 0, reasons: []}], + [{answers: {age: 35, coverage: 1500000}}, {decision: {manualReview: false, reason: "clean", class: "standard"}, score: 0, reasons: []}], + [{answers: {age: 35, coverage: 100000, incomplete: true}}, {decision: {manualReview: true, reason: "incomplete application", class: "referred"}, score: 0, reasons: []}], + [{answers: {age: 35, coverage: 100000, incomplete: true, medical: true, occupation: "miner", hospitalized: true}}, {decision: {manualReview: true, reason: "risk score", class: "referred"}, score: 23, reasons: ["high risk medical condition", "recent hospitalization", "hazardous occupation"]}], + [{answers: {age: 17, coverage: 100000}}, {decision: {manualReview: true, reason: "risk score", class: "referred"}, score: 100, reasons: ["minor"]}], + [{answers: {medical: true, hospitalized: true, conditions: 5, occupation: "diver", age: 70, coverage: 2000000}}, {decision: {manualReview: true, reason: "coverage above automatic limit", class: "referred"}, score: 36, reasons: ["high risk medical condition", "recent hospitalization", "multiple pre-existing conditions", "hazardous occupation", "age over 60"]}], + // Bad and missing answers: comparison cells against null or a string fail and do not count. + [{}, {decision: {manualReview: false, reason: "clean", class: "standard"}, score: 0, reasons: []}], + [{answers: {age: 40, coverage: 100000, conditions: "3"}}, {decision: {manualReview: false, reason: "clean", class: "standard"}, score: 0, reasons: []}], + [{answers: {age: 40, coverage: 100000, occupation: "Pilot"}}, {decision: {manualReview: false, reason: "clean", class: "standard"}, score: 0, reasons: []}], + [{answers: {age: 40, coverage: 100000, medical: "yes"}}, {decision: {manualReview: false, reason: "clean", class: "standard"}, score: 0, reasons: []}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Claim validation: three column-less tables, each relaying the previous verdict when it failed, +// then an outcome expression. Dates arrive as plain strings. +{ + name: "claim validation: chained checks relay the first failure", + graph: { + nodes: [ + {input: "claimRequest"}, + {table: "details", passThrough: true, inputs: [null], outputs: ["validation.details.ok", "validation.details.reason"], rules: [ + ["len(trim(claimNumber ?? '')) < 5", "false", "'claim number too short'"], + ["amount == null", "false", "'missing amount'"], + ["amount <= 0", "false", "'amount must be positive'"], + ["", "true", "'ok'"], + ]}, + {table: "policyStatus", passThrough: true, inputs: [null], outputs: ["validation.policy.ok", "validation.policy.reason"], rules: [ + ["!validation.details.ok", "false", "validation.details.reason"], + ["policy.status != 'active'", "false", "'policy ' + (policy.status ?? 'unknown')"], + ["", "true", "'ok'"], + ]}, + {table: "timing", passThrough: true, inputs: [null], outputs: ["validation.timing.ok", "validation.timing.reason"], rules: [ + ["!validation.policy.ok", "false", "validation.policy.reason"], + ["d(incidentDate).isBefore(d(policy.start)) or d(incidentDate).isAfter(d(policy.end))", "false", "'incident outside policy period'"], + ["d(reportedDate).diff(d(incidentDate), 'day') > 30", "false", "'reported too late'"], + ["d(reportedDate).isBefore(d(incidentDate))", "false", "'reported before incident'"], + ["", "true", "'ok'"], + ]}, + {expression: "outcome", fields: { + valid: "validation.timing.ok", + message: "validation.timing.reason", + nextStep: "$.valid ? (amount > 10000 ? 'adjuster' : 'fast-track') : 'reject'", + }}, + ], + }, + cases: [ + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: true, message: "ok", nextStep: "fast-track"}], + [{claimNumber: "CLM-1001", amount: 25000, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: true, message: "ok", nextStep: "adjuster"}], + [{claimNumber: "CLM-1001", amount: 10000, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: true, message: "ok", nextStep: "fast-track"}], + [{claimNumber: "C1", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "claim number too short", nextStep: "reject"}], + [{amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "lapsed", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "claim number too short", nextStep: "reject"}], + [{claimNumber: " ab cd ", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: true, message: "ok", nextStep: "fast-track"}], + [{claimNumber: "CLM-1001", incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "missing amount", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: 0, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "amount must be positive", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: -5, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "amount must be positive", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "lapsed", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "policy lapsed", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "policy unknown", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-03-05"}, {valid: false, message: "policy unknown", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2024-05-31", reportedDate: "2024-06-02", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "incident outside policy period", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2025-05-31", reportedDate: "2025-06-02", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: true, message: "ok", nextStep: "fast-track"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2024-06-01", reportedDate: "2024-06-01", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: true, message: "ok", nextStep: "fast-track"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-03-31", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: true, message: "ok", nextStep: "fast-track"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-04-01", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "reported too late", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: 2500, incidentDate: "2025-03-01", reportedDate: "2025-02-28", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: false, message: "reported before incident", nextStep: "reject"}], + [{claimNumber: "CLM-1001", amount: "2500", incidentDate: "2025-03-01", reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, "!error"], + // A missing incident date is an invalid date: every isBefore/isAfter is false and diff errors, + // so no failing rule fires and the claim validates. The decision has to check presence itself. + [{claimNumber: "CLM-1001", amount: 2500, reportedDate: "2025-03-05", policy: {status: "active", start: "2024-06-01", end: "2025-05-31"}}, {valid: true, message: "ok", nextStep: "fast-track"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Property claim payout: a switch denies inactive policies and uncovered perils, otherwise a +// per-peril limits table feeds a payout capped by the limit and reduced by the deductible. +{ + name: "property coverage: peril limits, deductibles and capped payout", + graph: { + nodes: [ + {switch: "gate", when: ["policy.status != 'active'", "not (peril in (policy.covered ?? []))", ""]}, + {expression: "inactive", fields: {decision: "'denied'", reason: "'policy inactive'", payout: "0"}}, + {expression: "excluded", fields: {decision: "'denied'", reason: "'peril not covered: ' + peril", payout: "0"}}, + {table: "limits", passThrough: true, inputs: ["peril"], outputs: ["limit", "deductible"], rules: [ + ["'fire'", "policy.dwelling", "policy.deductible"], + ["'water'", "min([policy.dwelling, 50000])", "policy.deductible * 2"], + ["'theft'", "policy.contents ?? 0", "policy.deductible"], + ["'wind', 'hail'", "policy.dwelling", "max([policy.deductible, round(policy.dwelling * 0.02)])"], + ]}, + {expression: "payout", fields: { + payout: "max([0, min([loss, limit]) - deductible])", + capped: "loss > limit", + decision: "$.payout > 0 ? 'approved' : 'below deductible'", + reason: "'covered'", + }}, + ], + edges: [ + "input -> gate", + "gate:0 -> inactive -> output", + "gate:1 -> excluded -> output", + "gate:2 -> limits -> payout -> output", + ], + }, + cases: [ + [{peril: "fire", loss: 20000, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, contents: 80000, deductible: 1000}}, {payout: 19000, capped: false, decision: "approved", reason: "covered"}], + [{peril: "fire", loss: 400000, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, contents: 80000, deductible: 1000}}, {payout: 299000, capped: true, decision: "approved", reason: "covered"}], + [{peril: "fire", loss: 300000, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, contents: 80000, deductible: 1000}}, {payout: 299000, capped: false, decision: "approved", reason: "covered"}], + [{peril: "water", loss: 70000, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, contents: 80000, deductible: 1000}}, {payout: 48000, capped: true, decision: "approved", reason: "covered"}], + [{peril: "water", loss: 1500, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, contents: 80000, deductible: 1000}}, {payout: 0, capped: false, decision: "below deductible", reason: "covered"}], + [{peril: "theft", loss: 5000, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, contents: 80000, deductible: 1000}}, {payout: 4000, capped: false, decision: "approved", reason: "covered"}], + [{peril: "theft", loss: 5000, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, deductible: 1000}}, {payout: 0, capped: true, decision: "below deductible", reason: "covered"}], + [{peril: "wind", loss: 10000, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, contents: 80000, deductible: 1000}}, {payout: 4000, capped: false, decision: "approved", reason: "covered"}], + [{peril: "hail", loss: 10000, policy: {status: "active", covered: ["fire", "water", "theft", "wind", "hail"], dwelling: 300000, contents: 80000, deductible: 10000}}, {payout: 0, capped: false, decision: "below deductible", reason: "covered"}], + [{peril: "wind", loss: 1500, policy: {status: "active", covered: ["wind"], dwelling: 30000, deductible: 1000}}, {payout: 500, capped: false, decision: "approved", reason: "covered"}], + [{peril: "fire", loss: 20000, policy: {status: "cancelled", covered: ["fire"], dwelling: 300000, deductible: 1000}}, {decision: "denied", reason: "policy inactive", payout: 0}], + [{peril: "fire", loss: 20000, policy: {covered: ["fire"], dwelling: 300000, deductible: 1000}}, {decision: "denied", reason: "policy inactive", payout: 0}], + [{peril: "flood", loss: 20000, policy: {status: "active", covered: ["fire", "water"], dwelling: 300000, deductible: 1000}}, {decision: "denied", reason: "peril not covered: flood", payout: 0}], + [{peril: "fire", loss: 20000, policy: {status: "active", dwelling: 300000, deductible: 1000}}, {decision: "denied", reason: "peril not covered: fire", payout: 0}], + // Missing peril: the exclusion reason concatenates null; missing or mistyped loss breaks min(). + [{loss: 20000, policy: {status: "active", covered: ["fire"], dwelling: 300000, deductible: 1000}}, "!error"], + [{peril: "fire", policy: {status: "active", covered: ["fire"], dwelling: 300000, deductible: 1000}}, "!error"], + [{peril: "fire", loss: "20000", policy: {status: "active", covered: ["fire"], dwelling: 300000, deductible: 1000}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Household auto: a loop-mode table rates each vehicle, a join brings the request back, and an +// expression applies a multi-car discount to the summed factors. +{ + name: "household auto: per-vehicle rating loop and multi-car discount", + graph: { + nodes: [ + {table: "rates", executionMode: "loop", inputField: "vehicles", outputPath: "rates", inputs: ["type", "year", "usage"], outputs: ["factor", "class"], rules: [ + ["'sports'", "", "", "1.8", "'A'"], + ["", "< 2010", "", "1.3", "'C'"], + ["", "", "'business'", "1.4", "'B'"], + ["'suv', 'truck'", "", "", "1.2", "'B'"], + ["", "", "", "1", "'D'"], + ]}, + {expression: "household", fields: { + count: "len(vehicles)", + classes: "map(rates, #.class)", + discount: "len(vehicles) >= 3 ? 0.15 : (len(vehicles) == 2 ? 0.1 : 0)", + premium: "round(base * sum(map(rates, #.factor)) * (1 - $.discount), 2)", + }}, + ], + edges: ["input -> rates -> household -> output", "input -> household"], + }, + cases: [ + [{base: 600, vehicles: [{type: "sedan", year: 2020, usage: "personal"}]}, {count: 1, classes: ["D"], discount: 0, premium: 600}], + [{base: 600, vehicles: [{type: "sedan", year: 2020, usage: "personal"}, {type: "sports", year: 2023, usage: "personal"}]}, {count: 2, classes: ["D", "A"], discount: 0.1, premium: 1512}], + [{base: 600, vehicles: [{type: "sedan", year: 2005, usage: "personal"}, {type: "suv", year: 2018, usage: "personal"}, {type: "sedan", year: 2022, usage: "business"}]}, {count: 3, classes: ["C", "B", "B"], discount: 0.15, premium: 1989}], + [{base: 600, vehicles: [{type: "sedan", year: 2020}, {type: "sedan", year: 2020}, {type: "sedan", year: 2020}, {type: "sedan", year: 2020}]}, {count: 4, classes: ["D", "D", "D", "D"], discount: 0.15, premium: 2040}], + [{base: 600, vehicles: []}, {count: 0, classes: [], discount: 0, premium: 0}], + [{base: 600, vehicles: [{type: "sedan", usage: "personal"}]}, {count: 1, classes: ["D"], discount: 0, premium: 600}], + [{base: 600, vehicles: [{type: "sedan", year: 2010, usage: "personal"}]}, {count: 1, classes: ["D"], discount: 0, premium: 600}], + [{base: 600, vehicles: [{type: "sedan", year: 2009, usage: "personal"}]}, {count: 1, classes: ["C"], discount: 0, premium: 780}], + [{base: 600, vehicles: [{type: "truck", year: 2015, usage: "business"}]}, {count: 1, classes: ["B"], discount: 0, premium: 840}], + [{base: 600, vehicles: [{type: "sports", year: 2005, usage: "business"}]}, {count: 1, classes: ["A"], discount: 0, premium: 1080}], + [{base: 600, vehicles: [{type: "SUV", year: 2015, usage: "personal"}]}, {count: 1, classes: ["D"], discount: 0, premium: 600}], + [{base: 599.99, vehicles: [{type: "suv", year: 2015}, {type: "sports", year: 2015}]}, {count: 2, classes: ["B", "A"], discount: 0.1, premium: 1619.97}], + [{vehicles: [{type: "sedan", year: 2020}]}, "!error"], + [{base: 600}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Health cost sharing: a network table picks coinsurance and the deductible multiplier, then one +// expression walks deductible, coinsurance and the out-of-pocket maximum through `$`. +{ + name: "health claim: deductible, coinsurance and out-of-pocket maximum", + graph: { + nodes: [ + {table: "network", passThrough: true, inputs: ["claim.network"], outputs: ["share.coinsurance", "share.deductibleMultiplier"], rules: [ + ["'in'", "plan.coinsurance", "1"], + ["'out'", "plan.coinsurance * 2", "2"], + ["", "1", "1"], + ]}, + {expression: "cost", fields: { + allowed: "min([claim.allowed ?? claim.billed, claim.billed])", + deductibleLeft: "max([0, plan.deductible * share.deductibleMultiplier - (ytd.deductiblePaid ?? 0)])", + toDeductible: "min([$.allowed, $.deductibleLeft])", + coins: "round(($.allowed - $.toDeductible) * share.coinsurance, 2)", + oopLeft: "max([0, plan.oopMax - (ytd.oopPaid ?? 0)])", + patient: "min([$.toDeductible + $.coins, $.oopLeft])", + insurer: "$.allowed - $.patient", + }}, + ], + }, + cases: [ + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", billed: 500, allowed: 400}}, {allowed: 400, deductibleLeft: 1000, toDeductible: 400, coins: 0, oopLeft: 5000, patient: 400, insurer: 0}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", billed: 3000, allowed: 2500}, ytd: {deductiblePaid: 1000, oopPaid: 1000}}, {allowed: 2500, deductibleLeft: 0, toDeductible: 0, coins: 500, oopLeft: 4000, patient: 500, insurer: 2000}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", billed: 3000, allowed: 2500}, ytd: {deductiblePaid: 600, oopPaid: 600}}, {allowed: 2500, deductibleLeft: 400, toDeductible: 400, coins: 420, oopLeft: 4400, patient: 820, insurer: 1680}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", billed: 20000, allowed: 18000}, ytd: {deductiblePaid: 1000, oopPaid: 4800}}, {allowed: 18000, deductibleLeft: 0, toDeductible: 0, coins: 3600, oopLeft: 200, patient: 200, insurer: 17800}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", billed: 1000, allowed: 800}, ytd: {deductiblePaid: 1000, oopPaid: 5200}}, {allowed: 800, deductibleLeft: 0, toDeductible: 0, coins: 160, oopLeft: 0, patient: 0, insurer: 800}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "out", billed: 2000}}, {allowed: 2000, deductibleLeft: 2000, toDeductible: 2000, coins: 0, oopLeft: 5000, patient: 2000, insurer: 0}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "out", billed: 5000, allowed: 4000}, ytd: {deductiblePaid: 2000, oopPaid: 2000}}, {allowed: 4000, deductibleLeft: 0, toDeductible: 0, coins: 1600, oopLeft: 3000, patient: 1600, insurer: 2400}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {billed: 3000, allowed: 3000}}, {allowed: 3000, deductibleLeft: 1000, toDeductible: 1000, coins: 2000, oopLeft: 5000, patient: 3000, insurer: 0}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", billed: 100, allowed: 150}}, {allowed: 100, deductibleLeft: 1000, toDeductible: 100, coins: 0, oopLeft: 5000, patient: 100, insurer: 0}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", billed: 0, allowed: 0}}, {allowed: 0, deductibleLeft: 1000, toDeductible: 0, coins: 0, oopLeft: 5000, patient: 0, insurer: 0}], + [{plan: {deductible: 1000, coinsurance: 0.25, oopMax: 5000}, claim: {network: "in", billed: 400, allowed: 333.33}, ytd: {deductiblePaid: 1000}}, {allowed: 333.33, deductibleLeft: 0, toDeductible: 0, coins: 83.33, oopLeft: 5000, patient: 83.33, insurer: 250}], + [{plan: {deductible: 1000, coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", allowed: 400}}, "!error"], + [{plan: {deductible: "1000", coinsurance: 0.2, oopMax: 5000}, claim: {network: "in", billed: 500, allowed: 400}}, "!error"], + [{plan: {deductible: 1000, oopMax: 5000}, claim: {network: "in", billed: 3000, allowed: 3000}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Claims triage: collected fraud indicators are scored, a first-hit switch sends high scores to +// SIU and small clean claims to fast-track, everything else is classed by severity; the severity +// branch reads the score back through `$nodes`. +{ + name: "claims triage: fraud indicators, fast-track and severity routing", + graph: { + nodes: [ + {table: "indicators", hit: "collect", outputPath: "flags", passThrough: true, inputs: ["claim.daysSincePolicyStart", "claim.priorClaims", "claim.amount", "claim.policeReport", "claim.witnesses"], outputs: ["code", "weight"], rules: [ + ["< 30", "", "", "", "", "'new_policy'", "30"], + ["", ">= 3", "", "", "", "'frequent_claimant'", "25"], + ["", "", "> 50000", "false", "", "'large_no_report'", "35"], + ["", "", "", "", "== 0", "'no_witnesses'", "10"], + ]}, + {expression: "fraud", passThrough: true, fields: {fraudScore: "sum(map(flags, #.weight))", codes: "map(flags, #.code)"}}, + {switch: "route", when: ["fraudScore >= 50", "claim.amount <= 2000 and len(flags) == 0", ""]}, + {expression: "siu", fields: {queue: "'SIU'", score: "fraudScore", codes: "codes"}}, + {expression: "fastTrack", fields: {queue: "'fast-track'", score: "fraudScore", autoPay: "claim.amount"}}, + {table: "severity", inputs: ["claim.amount", "claim.injury"], outputs: ["queue", "level"], rules: [ + ["", "true", "'bodily-injury'", "3"], + ["> 25000", "", "'complex'", "2"], + ["", "", "'standard'", "1"], + ]}, + {expression: "assign", fields: {queue: "queue", level: "level", score: "$nodes.fraud.fraudScore"}}, + ], + edges: [ + "input -> indicators -> fraud -> route", + "route:0 -> siu -> output", + "route:1 -> fastTrack -> output", + "route:2 -> severity -> assign -> output", + ], + }, + cases: [ + [{claim: {daysSincePolicyStart: 400, priorClaims: 0, amount: 1500, policeReport: true, witnesses: 1}}, {queue: "fast-track", score: 0, autoPay: 1500}], + [{claim: {daysSincePolicyStart: 400, priorClaims: 0, amount: 2000, policeReport: true, witnesses: 1}}, {queue: "fast-track", score: 0, autoPay: 2000}], + [{claim: {daysSincePolicyStart: 400, priorClaims: 0, amount: 2001, policeReport: true, witnesses: 1}}, {queue: "standard", level: 1, score: 0}], + [{claim: {daysSincePolicyStart: 400, priorClaims: 0, amount: 30000, policeReport: true, witnesses: 1}}, {queue: "complex", level: 2, score: 0}], + [{claim: {daysSincePolicyStart: 400, priorClaims: 0, amount: 30000, policeReport: true, witnesses: 1, injury: true}}, {queue: "bodily-injury", level: 3, score: 0}], + [{claim: {daysSincePolicyStart: 10, priorClaims: 0, amount: 1500, policeReport: true, witnesses: 1}}, {queue: "standard", level: 1, score: 30}], + [{claim: {daysSincePolicyStart: 10, priorClaims: 3, amount: 1500, policeReport: true, witnesses: 1}}, {queue: "SIU", score: 55, codes: ["new_policy", "frequent_claimant"]}], + [{claim: {daysSincePolicyStart: 400, priorClaims: 1, amount: 60000, policeReport: false, witnesses: 0}}, {queue: "complex", level: 2, score: 45}], + [{claim: {daysSincePolicyStart: 29, priorClaims: 1, amount: 60000, policeReport: false, witnesses: 0}}, {queue: "SIU", score: 75, codes: ["new_policy", "large_no_report", "no_witnesses"]}], + [{claim: {daysSincePolicyStart: 30, priorClaims: 2, amount: 1000, policeReport: true, witnesses: 2}}, {queue: "fast-track", score: 0, autoPay: 1000}], + [{claim: {daysSincePolicyStart: 400, priorClaims: 0, amount: 60000, witnesses: 1}}, {queue: "complex", level: 2, score: 0}], + [{claim: {daysSincePolicyStart: 400, priorClaims: 0, amount: 1000}}, {queue: "fast-track", score: 0, autoPay: 1000}], + [{claim: {daysSincePolicyStart: 400, priorClaims: "3", amount: 1000, witnesses: 1}}, {queue: "fast-track", score: 0, autoPay: 1000}], + [{claim: {daysSincePolicyStart: 400, priorClaims: 0, amount: 1000, witnesses: 0, injury: true}}, {queue: "bodily-injury", level: 3, score: 10}], + [{}, {queue: "standard", level: 1, score: 0}], + ], +} diff --git a/core/engine/tests/spec/graph/45-realistic-lending.json5 b/core/engine/tests/spec/graph/45-realistic-lending.json5 new file mode 100644 index 00000000..86821c55 --- /dev/null +++ b/core/engine/tests/spec/graph/45-realistic-lending.json5 @@ -0,0 +1,349 @@ +// Realistic lending decisions modelled on the shapes of the published sample graphs: scorecards +// built from chained pass-through tables writing dotted `eval.*` outputs, affordability gates in +// front of ratio checks, rate pricing from a base table plus collected basis-point adjustments, +// exposure limits from a loop joined with the request, KYC gates over dates, and a bureau score +// sub-decision. Each suite is one decision exercised across main paths, boundaries, missing data +// and bad types. + +// --------------------------------------------------------------------------------------------- +// Credit limit review: three scoring tables, a total, a recommendation band with half-open +// intervals, and a final expression that rounds the change and reads `$` for the new limit. +{ + name: "credit limit review: scorecard bands and the recommended new limit", + graph: { + nodes: [ + {table: "paymentHistory", passThrough: true, inputs: ["account.payments.onTimePct", "account.payments.late12m"], outputs: ["eval.payment.rating", "eval.payment.score"], rules: [ + [">= 95", "<= 0", "'excellent'", "30"], + [">= 90", "<= 1", "'good'", "20"], + [">= 80", "<= 3", "'fair'", "10"], + ["", "", "'poor'", "0"], + ]}, + {table: "utilization", passThrough: true, inputs: ["account.utilization.current", "account.utilization.avg6m"], outputs: ["eval.utilization.rating", "eval.utilization.score"], rules: [ + ["< 30", "< 50", "'low'", "25"], + ["< 50", "", "'moderate'", "15"], + ["< 80", "", "'high'", "5"], + ["", "", "'maxed'", "-10"], + ]}, + {table: "behaviour", passThrough: true, inputs: ["account.behaviour.inquiries", "account.behaviour.years", "account.behaviour.incomeVerified"], outputs: ["eval.behaviour.score"], rules: [ + ["< 1", ">= 3", "true", "25"], + ["< 3", ">= 1", "true", "15"], + ["< 3", "", "", "5"], + ["", "", "", "-5"], + ]}, + {expression: "total", passThrough: true, fields: {totalScore: "eval.payment.score + eval.utilization.score + eval.behaviour.score"}}, + {table: "recommendation", passThrough: true, inputs: ["totalScore"], outputs: ["rec.pct", "rec.why"], rules: [ + ["> 70", "30", "'significant increase'"], + ["[50..70]", "15", "'moderate increase'"], + ["[30..50)", "5", "'small increase'"], + ["[0..30)", "0", "'no change'"], + ["< 0", "-20", "'decrease'"], + ]}, + {expression: "amounts", fields: { + score: "totalScore", + ratings: "[eval.payment.rating, eval.utilization.rating]", + "rec.pct": "rec.pct", + "rec.why": "rec.why", + "rec.change": "round(account.limit * rec.pct / 100)", + "rec.newLimit": "account.limit + $.rec.change", + }}, + ], + }, + cases: [ + [{account: {limit: 5000, payments: {onTimePct: 98, late12m: 0}, utilization: {current: 20, avg6m: 40}, behaviour: {inquiries: 0, years: 5, incomeVerified: true}}}, {score: 80, ratings: ["excellent", "low"], rec: {pct: 30, why: "significant increase", change: 1500, newLimit: 6500}}], + [{account: {limit: 5000, payments: {onTimePct: 95, late12m: 0}, utilization: {current: 30, avg6m: 40}, behaviour: {inquiries: 1, years: 2, incomeVerified: true}}}, {score: 60, ratings: ["excellent", "moderate"], rec: {pct: 15, why: "moderate increase", change: 750, newLimit: 5750}}], + [{account: {limit: 5000, payments: {onTimePct: 92, late12m: 1}, utilization: {current: 29, avg6m: 50}, behaviour: {inquiries: 0, years: 2, incomeVerified: false}}}, {score: 40, ratings: ["good", "moderate"], rec: {pct: 5, why: "small increase", change: 250, newLimit: 5250}}], + [{account: {limit: 5000, payments: {onTimePct: 85, late12m: 3}, utilization: {current: 79, avg6m: 60}, behaviour: {inquiries: 2, years: 0, incomeVerified: true}}}, {score: 20, ratings: ["fair", "high"], rec: {pct: 0, why: "no change", change: 0, newLimit: 5000}}], + [{account: {limit: 5000, payments: {onTimePct: 70, late12m: 6}, utilization: {current: 95, avg6m: 90}, behaviour: {inquiries: 6, years: 1, incomeVerified: true}}}, {score: -15, ratings: ["poor", "maxed"], rec: {pct: -20, why: "decrease", change: -1000, newLimit: 4000}}], + // Band edges: 50 and 70 are both in the closed middle band, 30 opens the half-open small band, + // 0 opens the no-change band. + [{account: {limit: 5000, payments: {onTimePct: 90, late12m: 1}, utilization: {current: 10, avg6m: 10}, behaviour: {inquiries: 2, years: 0, incomeVerified: false}}}, {score: 50, ratings: ["good", "low"], rec: {pct: 15, why: "moderate increase", change: 750, newLimit: 5750}}], + [{account: {limit: 5000, payments: {onTimePct: 99, late12m: 0}, utilization: {current: 10, avg6m: 10}, behaviour: {inquiries: 1, years: 1, incomeVerified: true}}}, {score: 70, ratings: ["excellent", "low"], rec: {pct: 15, why: "moderate increase", change: 750, newLimit: 5750}}], + [{account: {limit: 5000, payments: {onTimePct: 80, late12m: 2}, utilization: {current: 60, avg6m: 60}, behaviour: {inquiries: 2, years: 1, incomeVerified: true}}}, {score: 30, ratings: ["fair", "high"], rec: {pct: 5, why: "small increase", change: 250, newLimit: 5250}}], + [{account: {limit: 5000, payments: {onTimePct: 50, late12m: 9}, utilization: {current: 70, avg6m: 70}, behaviour: {inquiries: 5, years: 9, incomeVerified: true}}}, {score: 0, ratings: ["poor", "high"], rec: {pct: 0, why: "no change", change: 0, newLimit: 5000}}], + [{account: {limit: 3333, payments: {onTimePct: 95, late12m: 0}, utilization: {current: 30, avg6m: 40}, behaviour: {inquiries: 1, years: 2, incomeVerified: true}}}, {score: 60, ratings: ["excellent", "moderate"], rec: {pct: 15, why: "moderate increase", change: 500, newLimit: 3833}}], + // Missing sections fall to each table's catch-all row; a mistyped percentage errors in every + // comparison cell and lands in `poor`. + [{account: {limit: 5000, payments: {onTimePct: 98, late12m: 0}, behaviour: {inquiries: 0, years: 5, incomeVerified: true}}}, {score: 45, ratings: ["excellent", "maxed"], rec: {pct: 5, why: "small increase", change: 250, newLimit: 5250}}], + [{account: {limit: 5000, utilization: {current: 20, avg6m: 40}, behaviour: {inquiries: 0, years: 5, incomeVerified: true}}}, {score: 50, ratings: ["poor", "low"], rec: {pct: 15, why: "moderate increase", change: 750, newLimit: 5750}}], + [{account: {limit: 5000, payments: {onTimePct: "98", late12m: 0}, utilization: {current: 20, avg6m: 40}, behaviour: {inquiries: 0, years: 5, incomeVerified: true}}}, {score: 50, ratings: ["poor", "low"], rec: {pct: 15, why: "moderate increase", change: 750, newLimit: 5750}}], + [{account: {limit: 5000, payments: {onTimePct: 98}, utilization: {current: 20, avg6m: 40}, behaviour: {inquiries: 0, years: 5, incomeVerified: true}}}, {score: 50, ratings: ["poor", "low"], rec: {pct: 15, why: "moderate increase", change: 750, newLimit: 5750}}], + [{account: {payments: {onTimePct: 98, late12m: 0}, utilization: {current: 20, avg6m: 40}, behaviour: {inquiries: 0, years: 5, incomeVerified: true}}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Affordability: an income gate first, then obligations and ratios as pass-through expressions, +// then a first-hit switch into decline, refer and approve. +{ + name: "affordability: income gate, DTI and residual income", + graph: { + nodes: [ + {switch: "incomeGate", when: ["(applicant.income ?? 0) <= 0", ""]}, + {expression: "noIncome", fields: {decision: "'decline'", reason: "'no income'"}}, + {expression: "obligations", passThrough: true, fields: { + "afford.existingDebt": "sum(map(debts ?? [], #.monthly))", + "afford.newPayment": "round(request.amount / request.termMonths, 2)", + }}, + {expression: "ratios", passThrough: true, fields: { + "afford.housing": "housing.payment ?? 0", + "afford.dti": "round((afford.existingDebt + afford.newPayment + $.afford.housing) / applicant.income, 4)", + "afford.residual": "applicant.income - applicant.expenses - afford.existingDebt - afford.newPayment - $.afford.housing", + }}, + {switch: "band", when: ["afford.dti > 0.5 or afford.residual < 0", "afford.dti > 0.36 or afford.residual < 500", ""]}, + {expression: "decline", fields: {decision: "'decline'", reason: "'unaffordable'", dti: "afford.dti", residual: "afford.residual"}}, + {expression: "refer", fields: {decision: "'refer'", dti: "afford.dti", residual: "afford.residual"}}, + {expression: "approve", fields: { + decision: "'approve'", + dti: "afford.dti", + residual: "afford.residual", + maxPayment: "round(applicant.income * 0.36 - afford.existingDebt - afford.housing, 2)", + }}, + ], + edges: [ + "input -> incomeGate", + "incomeGate:0 -> noIncome -> output", + "incomeGate:1 -> obligations -> ratios -> band", + "band:0 -> decline -> output", + "band:1 -> refer -> output", + "band:2 -> approve -> output", + ], + }, + cases: [ + [{applicant: {income: 6000, expenses: 2000}, debts: [{type: "card", monthly: 300}], request: {amount: 12000, termMonths: 24}, housing: {payment: 1200}}, {decision: "approve", dti: 0.3333, residual: 2000, maxPayment: 660}], + [{applicant: {income: 6000, expenses: 2000}, debts: [{type: "card", monthly: 300}], request: {amount: 12000, termMonths: 24}, housing: {payment: 1700}}, {decision: "refer", dti: 0.4167, residual: 1500}], + [{applicant: {income: 6000, expenses: 2000}, debts: [{type: "card", monthly: 300}], request: {amount: 12000, termMonths: 24}, housing: {payment: 2800}}, {decision: "decline", reason: "unaffordable", dti: 0.6, residual: 400}], + [{applicant: {income: 5000, expenses: 1000}, debts: [], request: {amount: 6000, termMonths: 12}, housing: {payment: 1300}}, {decision: "approve", dti: 0.36, residual: 2200, maxPayment: 500}], + [{applicant: {income: 5000, expenses: 3201}, debts: [], request: {amount: 6000, termMonths: 12}, housing: {payment: 800}}, {decision: "refer", dti: 0.26, residual: 499}], + [{applicant: {income: 5000, expenses: 3200}, debts: [], request: {amount: 6000, termMonths: 12}, housing: {payment: 800}}, {decision: "approve", dti: 0.26, residual: 500, maxPayment: 1000}], + [{applicant: {income: 5000, expenses: 4000}, debts: [], request: {amount: 6000, termMonths: 12}, housing: {payment: 800}}, {decision: "decline", reason: "unaffordable", dti: 0.26, residual: -300}], + [{applicant: {income: 4000, expenses: 1000}, request: {amount: 2400, termMonths: 12}}, {decision: "approve", dti: 0.05, residual: 2800, maxPayment: 1440}], + [{applicant: {income: 4000, expenses: 1000}, debts: [{type: "car", monthly: 100}, {type: "card", monthly: 250.5}], request: {amount: 2400, termMonths: 12}}, {decision: "approve", dti: 0.1376, residual: 2449.5, maxPayment: 1089.5}], + [{applicant: {income: 0, expenses: 1000}, request: {amount: 2400, termMonths: 12}}, {decision: "decline", reason: "no income"}], + [{applicant: {expenses: 1000}, request: {amount: 2400, termMonths: 12}}, {decision: "decline", reason: "no income"}], + [{applicant: {income: -100, expenses: 0}, request: {amount: 2400, termMonths: 12}}, {decision: "decline", reason: "no income"}], + [{applicant: {income: 0.01, expenses: 0}, request: {amount: 0, termMonths: 12}}, {decision: "refer", dti: 0, residual: 0.01}], + // A zero term divides by zero, a string income fails the gate's comparison (the default branch + // runs) and then the ratio, and a debt without `monthly` sums null. + [{applicant: {income: 4000, expenses: 1000}, request: {amount: 2400, termMonths: 0}}, "!error"], + [{applicant: {income: "5000", expenses: 1000}, request: {amount: 2400, termMonths: 12}}, "!error"], + [{applicant: {income: 4000, expenses: 1000}, debts: [{type: "card"}], request: {amount: 2400, termMonths: 12}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Loan pricing: base rate, floor and cap by product; collected basis-point adjustments; the rate +// clamped into [floor, cap]; an amortized monthly payment with a negative exponent. +{ + name: "loan pricing: base rate, collected adjustments, clamp and payment", + graph: { + nodes: [ + {table: "base", passThrough: true, inputs: ["product"], outputs: ["pricing.base", "pricing.floor", "pricing.cap"], rules: [ + ["'mortgage'", "5.25", "3.5", "9"], + ["'auto'", "6.5", "4", "15"], + ["'personal'", "9.9", "6", "24.99"], + ]}, + {table: "adjustments", hit: "collect", outputPath: "adjustments", passThrough: true, inputs: ["creditScore", "ltv", "termMonths", "autopay", "product", "customer.years"], outputs: ["code", "bps"], rules: [ + [">= 760", "", "", "", "", "", "'score_prime'", "-50"], + ["< 660", "", "", "", "", "", "'score_subprime'", "200"], + ["< 600", "", "", "", "", "", "'score_deep'", "300"], + ["", "> 0.8", "", "", "'mortgage', 'auto'", "", "'high_ltv'", "75"], + ["", "", "> 60", "", "", "", "'long_term'", "25"], + ["", "", "", "true", "", "", "'autopay'", "-25"], + ["", "", "", "", "", ">= 10", "'loyalty'", "-150"], + ]}, + {expression: "rate", fields: { + raw: "pricing.base + sum(map(adjustments, #.bps)) / 100", + rate: "min([max([$.raw, pricing.floor]), pricing.cap])", + codes: "map(adjustments, #.code)", + monthly: "round(amount * ($.rate / 1200) / (1 - (1 + $.rate / 1200) ^ (-termMonths)), 2)", + }}, + ], + }, + cases: [ + [{product: "mortgage", amount: 300000, termMonths: 360, creditScore: 780, ltv: 0.75, autopay: true, customer: {years: 2}}, {raw: 4.75, rate: 4.75, codes: ["score_prime", "long_term", "autopay"], monthly: 1564.94}], + [{product: "mortgage", amount: 300000, termMonths: 360, creditScore: 700, ltv: 0.9, autopay: false}, {raw: 6.25, rate: 6.25, codes: ["high_ltv", "long_term"], monthly: 1847.15}], + [{product: "auto", amount: 25000, termMonths: 60, creditScore: 650, ltv: 1.1, autopay: true}, {raw: 9, rate: 9, codes: ["score_subprime", "high_ltv", "autopay"], monthly: 518.96}], + [{product: "auto", amount: 25000, termMonths: 72, creditScore: 590, ltv: 0.5}, {raw: 11.75, rate: 11.75, codes: ["score_subprime", "score_deep", "long_term"], monthly: 485.51}], + [{product: "personal", amount: 10000, termMonths: 36, creditScore: 550, autopay: true}, {raw: 14.65, rate: 14.65, codes: ["score_subprime", "score_deep", "autopay"], monthly: 344.94}], + [{product: "personal", amount: 10000, termMonths: 12, creditScore: 820, autopay: true}, {raw: 9.15, rate: 9.15, codes: ["score_prime", "autopay"], monthly: 875.21}], + [{product: "personal", amount: 10000, termMonths: 36, creditScore: 760, ltv: 0.9}, {raw: 9.4, rate: 9.4, codes: ["score_prime"], monthly: 319.86}], + [{product: "personal", amount: 10000, termMonths: 36, creditScore: 660}, {raw: 9.9, rate: 9.9, codes: [], monthly: 322.2}], + [{product: "personal", amount: 10000, termMonths: 36, creditScore: 600}, {raw: 11.9, rate: 11.9, codes: ["score_subprime"], monthly: 331.67}], + // Clamped to the product floor and to the product cap. + [{product: "mortgage", amount: 200000, termMonths: 120, creditScore: 800, ltv: 0.5, autopay: true, customer: {years: 12}}, {raw: 3.25, rate: 3.5, codes: ["score_prime", "long_term", "autopay", "loyalty"], monthly: 1977.72}], + [{product: "mortgage", amount: 200000, termMonths: 360, creditScore: 550, ltv: 0.95}, {raw: 11.25, rate: 9, codes: ["score_subprime", "score_deep", "high_ltv", "long_term"], monthly: 1609.25}], + // Missing score: score cells error and add nothing. Unknown product: no base rate, the sum + // with null errors. A string term fails the `> 60` cell and then the exponent. + [{product: "personal", amount: 10000, termMonths: 36, ltv: 0.9}, {raw: 9.9, rate: 9.9, codes: [], monthly: 322.2}], + [{product: "boat", amount: 10000, termMonths: 36, creditScore: 700}, "!error"], + [{product: "auto", amount: 25000, termMonths: "60", creditScore: 700}, "!error"], + [{product: "auto", amount: 0, termMonths: 60, creditScore: 700, customer: {years: 10}}, {raw: 5, rate: 5, codes: ["loyalty"], monthly: 0}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Exposure limit: a loop expression weighs each existing facility, a segment table supplies the +// caps, both join into one expression that picks the binding constraint and floors to hundreds. +{ + name: "exposure limit: facility loop joined with segment caps", + graph: { + nodes: [ + {expression: "exposure", executionMode: "loop", inputField: "facilities", outputPath: "exposures", fields: { + exposure: "secured == true ? balance * 0.5 : max([limit, balance])", + }}, + {table: "caps", passThrough: true, inputs: ["segment"], outputs: ["caps.product", "caps.incomeMultiple"], rules: [ + ["'retail'", "25000", "0.5"], + ["'premier'", "100000", "1"], + ["'business'", "250000", "2"], + ["", "5000", "0.25"], + ]}, + {expression: "limit", fields: { + currentExposure: "sum(map(exposures, #.exposure))", + incomeCap: "annualIncome * caps.incomeMultiple", + headroom: "max([0, $.incomeCap - $.currentExposure])", + approvedLimit: "floor(min([$.headroom, caps.product, requested ?? caps.product]) / 100) * 100", + constrainedBy: "requested != null and requested <= min([$.headroom, caps.product]) ? 'request' : ($.headroom < caps.product ? 'income' : 'product')", + }}, + ], + edges: ["input -> exposure -> limit -> output", "input -> caps -> limit"], + }, + cases: [ + [{segment: "retail", annualIncome: 60000, facilities: [], requested: 10000}, {currentExposure: 0, incomeCap: 30000, headroom: 30000, approvedLimit: 10000, constrainedBy: "request"}], + [{segment: "retail", annualIncome: 60000, facilities: []}, {currentExposure: 0, incomeCap: 30000, headroom: 30000, approvedLimit: 25000, constrainedBy: "product"}], + [{segment: "retail", annualIncome: 40000, facilities: [{limit: 5000, balance: 2000}]}, {currentExposure: 5000, incomeCap: 20000, headroom: 15000, approvedLimit: 15000, constrainedBy: "income"}], + [{segment: "premier", annualIncome: 150000, facilities: [{limit: 0, balance: 100000, secured: true}], requested: 120000}, {currentExposure: 50000, incomeCap: 150000, headroom: 100000, approvedLimit: 100000, constrainedBy: "product"}], + [{segment: "retail", annualIncome: 40000, facilities: [{limit: 1000, balance: 1500}], requested: 2000}, {currentExposure: 1500, incomeCap: 20000, headroom: 18500, approvedLimit: 2000, constrainedBy: "request"}], + [{segment: "retail", annualIncome: 20000, facilities: [{limit: 8000, balance: 0}, {limit: 4000, balance: 4500}], requested: 5000}, {currentExposure: 12500, incomeCap: 10000, headroom: 0, approvedLimit: 0, constrainedBy: "income"}], + [{segment: "retail", annualIncome: 30001, facilities: []}, {currentExposure: 0, incomeCap: 15000.5, headroom: 15000.5, approvedLimit: 15000, constrainedBy: "income"}], + [{segment: "student", annualIncome: 100000, facilities: []}, {currentExposure: 0, incomeCap: 25000, headroom: 25000, approvedLimit: 5000, constrainedBy: "product"}], + [{annualIncome: 100000, facilities: [], requested: 5000}, {currentExposure: 0, incomeCap: 25000, headroom: 25000, approvedLimit: 5000, constrainedBy: "request"}], + [{segment: "business", annualIncome: 200000, facilities: [{limit: 50000, balance: 10000}, {limit: 0, balance: 80000, secured: true}], requested: 300000}, {currentExposure: 90000, incomeCap: 400000, headroom: 310000, approvedLimit: 250000, constrainedBy: "product"}], + [{segment: "retail", annualIncome: 60000, facilities: [], requested: 0}, {currentExposure: 0, incomeCap: 30000, headroom: 30000, approvedLimit: 0, constrainedBy: "request"}], + [{segment: "retail", annualIncome: 60000, facilities: [{limit: 1000, balance: 0, secured: "yes"}]}, {currentExposure: 1000, incomeCap: 30000, headroom: 29000, approvedLimit: 25000, constrainedBy: "product"}], + // Missing income, a facility without a limit, and no facilities array at all. + [{segment: "retail", facilities: []}, "!error"], + [{segment: "retail", annualIncome: 60000, facilities: [{balance: 100}]}, "!error"], + [{segment: "retail", annualIncome: 60000}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// KYC onboarding gates: derived age and document days left (evaluation time is fixed at +// 2025-03-20T10:15:30Z), a country risk table, then a first-hit switch of ordered gates. +{ + name: "kyc onboarding: ordered gates over sanctions, age, documents and address", + graph: { + nodes: [ + {expression: "derive", passThrough: true, fields: { + "kyc.age": "d().diff(d(customer.dob), 'year')", + "kyc.docDaysLeft": "customer.document.expiry == null ? null : d(customer.document.expiry).diff(d(), 'day')", + }}, + {table: "countryRisk", passThrough: true, inputs: ["customer.country"], outputs: ["kyc.countryRisk"], rules: [ + ["'IR', 'KP', 'SY'", "'prohibited'"], + ["'RU', 'BY', 'VE', 'MM'", "'high'"], + ["'US', 'GB', 'DE', 'FR', 'NL', 'SE'", "'low'"], + ["", "'medium'"], + ]}, + {switch: "gates", when: [ + "customer.sanctionsHit == true or kyc.countryRisk == 'prohibited'", + "kyc.age < 18", + "customer.document.expiry == null", + "kyc.docDaysLeft < 0", + "customer.pep == true or kyc.countryRisk == 'high'", + "customer.addressVerified != true", + "", + ]}, + {expression: "block", fields: {status: "'blocked'", reason: "customer.sanctionsHit == true ? 'sanctions' : 'prohibited country'"}}, + {expression: "minor", fields: {status: "'rejected'", reason: "'underage'", age: "kyc.age"}}, + {expression: "noDocument", fields: {status: "'pending'", reason: "'document missing'"}}, + {expression: "expired", fields: {status: "'pending'", reason: "'document expired'", expiredDays: "-kyc.docDaysLeft"}}, + {expression: "edd", fields: {status: "'enhanced due diligence'", reason: "customer.pep == true ? 'pep' : 'high risk country'"}}, + {expression: "address", fields: {status: "'pending'", reason: "'address unverified'"}}, + {expression: "pass", fields: {status: "'verified'", age: "kyc.age", riskTier: "kyc.countryRisk", renewInDays: "min([kyc.docDaysLeft, 365])"}}, + ], + edges: [ + "input -> derive -> countryRisk -> gates", + "gates:0 -> block -> output", + "gates:1 -> minor -> output", + "gates:2 -> noDocument -> output", + "gates:3 -> expired -> output", + "gates:4 -> edd -> output", + "gates:5 -> address -> output", + "gates:6 -> pass -> output", + ], + }, + cases: [ + [{customer: {dob: "1990-05-01", country: "DE", document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "verified", age: 34, riskTier: "low", renewInDays: 365}], + [{customer: {dob: "1990-05-01", country: "ES", document: {expiry: "2025-06-01"}, addressVerified: true}}, {status: "verified", age: 34, riskTier: "medium", renewInDays: 72}], + [{customer: {dob: "1990-03-20", document: {expiry: "2025-03-20"}, addressVerified: true}}, {status: "verified", age: 35, riskTier: "medium", renewInDays: 0}], + [{customer: {dob: "1990-03-21", country: "US", document: {expiry: "2025-03-19"}, addressVerified: true}}, {status: "pending", reason: "document expired", expiredDays: 1}], + [{customer: {dob: "2007-03-20", country: "US", document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "verified", age: 18, riskTier: "low", renewInDays: 365}], + [{customer: {dob: "2007-03-21", country: "US", document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "rejected", reason: "underage", age: 17}], + [{customer: {dob: "1990-05-01", country: "US", sanctionsHit: true, document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "blocked", reason: "sanctions"}], + [{customer: {dob: "1990-05-01", country: "IR", document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "blocked", reason: "prohibited country"}], + [{customer: {dob: "1990-05-01", country: "RU", document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "enhanced due diligence", reason: "high risk country"}], + [{customer: {dob: "1990-05-01", country: "US", pep: true, document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "enhanced due diligence", reason: "pep"}], + [{customer: {dob: "1990-05-01", country: "US", document: {expiry: "2030-01-01"}}}, {status: "pending", reason: "address unverified"}], + [{customer: {dob: "1990-05-01", country: "US", document: {expiry: "2030-01-01"}, addressVerified: "true"}}, {status: "pending", reason: "address unverified"}], + [{customer: {dob: "2010-01-01", country: "KP", sanctionsHit: false, document: {expiry: "2030-01-01"}}}, {status: "blocked", reason: "prohibited country"}], + [{customer: {dob: "2010-01-01", country: "US", document: {expiry: "2020-01-01"}}}, {status: "rejected", reason: "underage", age: 15}], + [{customer: {dob: "1990-05-01", country: "US", addressVerified: true}}, {status: "pending", reason: "document missing"}], + [{customer: {dob: "1990-05-01", country: "us", document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "verified", age: 34, riskTier: "medium", renewInDays: 365}], + // A missing or unparsable birth date makes the age diff null (dropped from the output); the + // `kyc.age < 18` gate errors on null, counts as false, and the applicant passes as verified. + [{customer: {country: "US", document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "verified", riskTier: "low", renewInDays: 365}], + [{customer: {dob: "not a date", country: "US", document: {expiry: "2030-01-01"}, addressVerified: true}}, {status: "verified", riskTier: "low", renewInDays: 365}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Buy-now-pay-later: a bureau sub-decision bands the applicant under `risk`, a plan table compares +// the cart against the band's exposure (a cell reading another field), and an expression splits +// the cart into installments. +{ + name: "bnpl: bureau band sub-decision, exposure-limited installment plan", + decisions: { + bureau: { + nodes: [ + {table: "band", inputs: ["bureau.score", "bureau.delinquencies"], outputs: ["band", "maxExposure"], rules: [ + [">= 700", "== 0", "'A'", "2000"], + [">= 620", "<= 1", "'B'", "1000"], + [">= 550", "", "'C'", "300"], + ["", "", "'D'", "0"], + ]}, + ], + }, + }, + graph: { + nodes: [ + {decision: "score", key: "bureau", passThrough: true, outputPath: "risk"}, + {table: "plans", passThrough: true, inputs: ["risk.band", "cart.total"], outputs: ["plan.installments", "plan.feePct"], rules: [ + ["'A', 'B'", "<= risk.maxExposure", "4", "0"], + ["'C'", "<= risk.maxExposure", "3", "0.03"], + ["", "", "0", "0"], + ]}, + {expression: "offer", fields: { + approved: "plan.installments > 0", + band: "risk.band", + installments: "plan.installments", + installment: "plan.installments > 0 ? round(cart.total * (1 + plan.feePct) / plan.installments, 2) : 0", + }}, + ], + }, + cases: [ + [{bureau: {score: 720, delinquencies: 0}, cart: {total: 400}}, {approved: true, band: "A", installments: 4, installment: 100}], + [{bureau: {score: 720, delinquencies: 1}, cart: {total: 999.99}}, {approved: true, band: "B", installments: 4, installment: 250}], + [{bureau: {score: 650, delinquencies: 2}, cart: {total: 300}}, {approved: true, band: "C", installments: 3, installment: 103}], + [{bureau: {score: 650, delinquencies: 2}, cart: {total: 301}}, {approved: false, band: "C", installments: 0, installment: 0}], + [{bureau: {score: 500, delinquencies: 0}, cart: {total: 50}}, {approved: false, band: "D", installments: 0, installment: 0}], + [{bureau: {score: 700, delinquencies: 0}, cart: {total: 2000}}, {approved: true, band: "A", installments: 4, installment: 500}], + [{bureau: {score: 700, delinquencies: 0}, cart: {total: 2000.01}}, {approved: false, band: "A", installments: 0, installment: 0}], + [{bureau: {score: 620, delinquencies: 1}, cart: {total: 1000}}, {approved: true, band: "B", installments: 4, installment: 250}], + [{bureau: {score: 619, delinquencies: 0}, cart: {total: 200}}, {approved: true, band: "C", installments: 3, installment: 68.67}], + [{bureau: {score: 720}, cart: {total: 200}}, {approved: true, band: "C", installments: 3, installment: 68.67}], + [{bureau: {score: "720", delinquencies: 0}, cart: {total: 200}}, {approved: false, band: "D", installments: 0, installment: 0}], + [{cart: {total: 200}}, {approved: false, band: "D", installments: 0, installment: 0}], + [{bureau: {score: 720, delinquencies: 0}}, {approved: false, band: "A", installments: 0, installment: 0}], + [{bureau: {score: 720, delinquencies: 0}, cart: {total: 0}}, {approved: true, band: "A", installments: 4, installment: 0}], + ], +} diff --git a/core/engine/tests/spec/graph/46-realistic-commerce.json5 b/core/engine/tests/spec/graph/46-realistic-commerce.json5 new file mode 100644 index 00000000..dfb856e6 --- /dev/null +++ b/core/engine/tests/spec/graph/46-realistic-commerce.json5 @@ -0,0 +1,336 @@ +// Realistic commerce decisions modelled on the shapes of the published sample graphs: cart +// promotions with per-column collect (`promos[]`), billable-weight shipping with rate cells that +// compute from the input, tax rates looked up per line by dynamic key, a reverse-charge switch, +// fraud screening with first-hit severity plus collected reasons and points, loyalty earning, and +// a returns policy over dates. Each suite is one decision exercised across main paths, +// boundaries, missing data and bad types. + +// --------------------------------------------------------------------------------------------- +// Promotions: the best discount is the first matching rule, `promos[]` lists every promotion the +// cart qualifies for. +{ + name: "promotions: best discount first, every qualifying promotion listed", + graph: { + nodes: [ + {expression: "totals", passThrough: true, fields: { + subtotal: "sum(map(items, #.price * #.qty))", + hasElectronics: "some(items, #.category == 'electronics')", + }}, + {table: "promos", passThrough: true, inputs: ["subtotal", "customer.tier", "promoCode", "hasElectronics"], outputs: ["discountPct", "promos[]"], rules: [ + ["", "'vip'", "", "", "0.15", "'VIP15'"], + [">= 200", "", "'BIG20'", "false", "0.2", "'BIG20'"], + [">= 100", "", "", "", "0.1", "'SPEND100'"], + ["", "", "'WELCOME'", "", "0.05", "'WELCOME'"], + ]}, + {expression: "checkout", fields: { + subtotal: "subtotal", + discount: "round(subtotal * (discountPct ?? 0), 2)", + total: "subtotal - $.discount", + promos: "promos ?? []", + }}, + ], + }, + cases: [ + [{items: [{price: 20, qty: 2, category: "books"}]}, {subtotal: 40, discount: 0, total: 40, promos: []}], + [{items: [{price: 20, qty: 5, category: "books"}]}, {subtotal: 100, discount: 10, total: 90, promos: ["SPEND100"]}], + [{items: [{price: 99.99, qty: 1, category: "books"}]}, {subtotal: 99.99, discount: 0, total: 99.99, promos: []}], + [{items: [{price: 50, qty: 3, category: "books"}], customer: {tier: "vip"}}, {subtotal: 150, discount: 22.5, total: 127.5, promos: ["VIP15", "SPEND100"]}], + [{items: [{price: 125, qty: 2, category: "books"}], promoCode: "BIG20"}, {subtotal: 250, discount: 50, total: 200, promos: ["BIG20", "SPEND100"]}], + [{items: [{price: 125, qty: 1, category: "books"}, {price: 125, qty: 1, category: "electronics"}], promoCode: "BIG20"}, {subtotal: 250, discount: 25, total: 225, promos: ["SPEND100"]}], + [{items: [{price: 25, qty: 2, category: "toys"}], promoCode: "WELCOME"}, {subtotal: 50, discount: 2.5, total: 47.5, promos: ["WELCOME"]}], + [{items: [{price: 100, qty: 3, category: "toys"}], promoCode: "WELCOME", customer: {tier: "vip"}}, {subtotal: 300, discount: 45, total: 255, promos: ["VIP15", "SPEND100", "WELCOME"]}], + [{items: [{price: 199.99, qty: 1, category: "toys"}], promoCode: "BIG20"}, {subtotal: 199.99, discount: 20, total: 179.99, promos: ["SPEND100"]}], + [{items: [{price: 125, qty: 2, category: "toys"}], promoCode: "big20"}, {subtotal: 250, discount: 25, total: 225, promos: ["SPEND100"]}], + [{items: [{price: 0.1, qty: 3, category: "toys"}], customer: {tier: "vip"}}, {subtotal: 0.3, discount: 0.05, total: 0.25, promos: ["VIP15"]}], + [{items: []}, {subtotal: 0, discount: 0, total: 0, promos: []}], + [{items: [], customer: {tier: "vip"}}, {subtotal: 0, discount: 0, total: 0, promos: ["VIP15"]}], + [{customer: {tier: "vip"}}, "!error"], + [{items: [{price: 20, qty: "2", category: "books"}]}, "!error"], + [{items: [{price: 20, category: "books"}]}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Shipping: billable weight from actual and dimensional weight, a zone table with a postcode +// cell, a switch for unshippable and free shipping, and rate cells computed from the weight. +// Orders are placed on Thursday 2025-03-20. +{ + name: "shipping: billable weight, zones, free threshold and express", + graph: { + nodes: [ + {expression: "measure", passThrough: true, fields: { + "parcel.dimWeight": "parcel.length == null ? 0 : round(parcel.length * parcel.width * parcel.height / 5000, 2)", + "parcel.billable": "ceil(max([parcel.weight, $.parcel.dimWeight]))", + }}, + {table: "zone", passThrough: true, inputs: ["destination.country", "destination.postcode"], outputs: ["zone", "transitDays"], rules: [ + ["'DE'", "startsWith($, '18') or startsWith($, '25')", "'remote'", "4"], + ["'DE'", "", "'domestic'", "2"], + ["'AT', 'FR', 'NL', 'BE', 'PL'", "", "'eu'", "4"], + ["", "", "'world'", "8"], + ]}, + {switch: "gate", when: [ + "zone == 'world' and parcel.billable > 30", + "zone == 'domestic' and orderTotal >= 50 and service != 'express'", + "", + ]}, + {expression: "unshippable", fields: {shippable: "false", reason: "'too heavy for international'", billable: "parcel.billable"}}, + {expression: "free", fields: { + carrier: "'dhl'", + cost: "0", + eta: "d(orderedAt).add(transitDays, 'day').format('%Y-%m-%d')", + billable: "parcel.billable", + }}, + {table: "rates", passThrough: true, inputs: ["zone", "parcel.billable"], outputs: ["rate.base"], rules: [ + ["'domestic'", "<= 2", "4.99"], + ["'domestic'", "<= 10", "6.99 + 0.5 * (parcel.billable - 2)"], + ["'domestic'", "", "10.99 + 0.4 * (parcel.billable - 10)"], + ["'remote'", "", "9.99 + 0.6 * parcel.billable"], + ["'eu'", "<= 5", "14.5"], + ["'eu'", "", "14.5 + 1.8 * (parcel.billable - 5)"], + ["'world'", "", "29 + 3.5 * parcel.billable"], + ]}, + {expression: "price", fields: { + carrier: "zone == 'world' ? 'ups' : 'dhl'", + cost: "round(rate.base + (service == 'express' ? max([5, rate.base * 0.5]) : 0), 2)", + eta: "d(orderedAt).add(service == 'express' ? max([1, transitDays - 1]) : transitDays, 'day').format('%Y-%m-%d')", + billable: "parcel.billable", + }}, + ], + edges: [ + "input -> measure -> zone -> gate", + "gate:0 -> unshippable -> output", + "gate:1 -> free -> output", + "gate:2 -> rates -> price -> output", + ], + }, + cases: [ + [{orderedAt: "2025-03-20", orderTotal: 30, destination: {country: "DE", postcode: "10115"}, parcel: {weight: 0.8, length: 30, width: 20, height: 10}}, {carrier: "dhl", cost: 4.99, eta: "2025-03-22", billable: 2}], + [{orderedAt: "2025-03-20", orderTotal: 50, destination: {country: "DE", postcode: "10115"}, parcel: {weight: 0.8, length: 30, width: 20, height: 10}}, {carrier: "dhl", cost: 0, eta: "2025-03-22", billable: 2}], + [{orderedAt: "2025-03-20", orderTotal: 49.99, destination: {country: "DE", postcode: "10115"}, parcel: {weight: 2}}, {carrier: "dhl", cost: 4.99, eta: "2025-03-22", billable: 2}], + [{orderedAt: "2025-03-20", orderTotal: 50, service: "express", destination: {country: "DE", postcode: "10115"}, parcel: {weight: 0.8, length: 30, width: 20, height: 10}}, {carrier: "dhl", cost: 9.99, eta: "2025-03-21", billable: 2}], + [{orderedAt: "2025-03-20", orderTotal: 20, destination: {country: "DE", postcode: "80331"}, parcel: {weight: 7.2, length: 10, width: 10, height: 10}}, {carrier: "dhl", cost: 9.99, eta: "2025-03-22", billable: 8}], + [{orderedAt: "2025-03-20", orderTotal: 20, destination: {country: "DE", postcode: "80331"}, parcel: {weight: 25}}, {carrier: "dhl", cost: 16.99, eta: "2025-03-22", billable: 25}], + [{orderedAt: "2025-03-20", orderTotal: 100, destination: {country: "DE", postcode: "18439"}, parcel: {weight: 3}}, {carrier: "dhl", cost: 11.79, eta: "2025-03-24", billable: 3}], + [{orderedAt: "2025-03-20", orderTotal: 100, destination: {country: "DE", postcode: "25980"}, parcel: {weight: 0.4}}, {carrier: "dhl", cost: 10.59, eta: "2025-03-24", billable: 1}], + [{orderedAt: "2025-03-20", orderTotal: 100, destination: {country: "FR", postcode: "75001"}, parcel: {weight: 5, length: 60, width: 40, height: 40}}, {carrier: "dhl", cost: 41.5, eta: "2025-03-24", billable: 20}], + [{orderedAt: "2025-03-20", orderTotal: 100, service: "express", destination: {country: "FR"}, parcel: {weight: 5}}, {carrier: "dhl", cost: 21.75, eta: "2025-03-23", billable: 5}], + [{orderedAt: "2025-03-20", orderTotal: 100, destination: {country: "US", postcode: "10001"}, parcel: {weight: 2}}, {carrier: "ups", cost: 36, eta: "2025-03-28", billable: 2}], + [{orderedAt: "2025-03-20", orderTotal: 100, destination: {country: "US"}, parcel: {weight: 30}}, {carrier: "ups", cost: 134, eta: "2025-03-28", billable: 30}], + [{orderedAt: "2025-03-20", orderTotal: 100, destination: {country: "US"}, parcel: {weight: 30.01}}, {shippable: false, reason: "too heavy for international", billable: 31}], + [{orderedAt: "2025-03-20", orderTotal: 100, destination: {}, parcel: {weight: 1}}, {carrier: "ups", cost: 32.5, eta: "2025-03-28", billable: 1}], + [{orderedAt: "2025-03-20", orderTotal: 10, destination: {country: "DE"}, parcel: {weight: 1}}, {carrier: "dhl", cost: 4.99, eta: "2025-03-22", billable: 1}], + [{orderedAt: "2025-03-20", destination: {country: "DE", postcode: "10115"}, parcel: {weight: 1}}, {carrier: "dhl", cost: 4.99, eta: "2025-03-22", billable: 1}], + // Missing weight, a string weight, and a parcel with only some dimensions. + [{orderedAt: "2025-03-20", orderTotal: 10, destination: {country: "DE"}, parcel: {}}, "!error"], + [{orderedAt: "2025-03-20", orderTotal: 10, destination: {country: "DE"}, parcel: {weight: "2"}}, "!error"], + [{orderedAt: "2025-03-20", orderTotal: 10, destination: {country: "DE"}, parcel: {weight: 1, length: 30}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Sales tax: a rates table writes one rate per category under `rates`, the tax expression looks a +// line's rate up by dynamic key with the standard rate as fallback, and a switch applies the +// reverse charge to cross-border B2B sales inside the EU list. The seller is in DE. +{ + name: "sales tax: per-category rates by dynamic key and reverse charge", + graph: { + nodes: [ + {table: "rates", passThrough: true, inputs: ["shipTo.country"], outputs: ["rates.standard", "rates.food", "rates.books", "rates.digital"], rules: [ + ["'DE'", "0.19", "0.07", "0.07", "0.19"], + ["'FR'", "0.2", "0.055", "0.055", "0.2"], + ["'GB'", "0.2", "0", "0", "0.2"], + ["'US'", "0", "0", "0", "0"], + ]}, + {switch: "b2b", when: ["customer.vatId != null and shipTo.country != 'DE' and shipTo.country in ['FR', 'AT', 'NL']", ""]}, + {expression: "reverseCharge", fields: { + net: "sum(map(lines, #.price * #.qty))", + tax: "0", + gross: "$.net", + reverseCharge: "true", + }}, + {expression: "tax", fields: { + net: "sum(map(lines, #.price * #.qty))", + tax: "round(sum(map(lines, #.price * #.qty * (rates[#.category] ?? rates.standard))), 2)", + gross: "$.net + $.tax", + reverseCharge: "false", + }}, + ], + edges: ["input -> rates -> b2b", "b2b:0 -> reverseCharge -> output", "b2b:1 -> tax -> output"], + }, + cases: [ + [{shipTo: {country: "DE"}, lines: [{price: 100, qty: 1, category: "standard"}, {price: 10, qty: 3, category: "food"}]}, {net: 130, tax: 21.1, gross: 151.1, reverseCharge: false}], + [{shipTo: {country: "FR"}, lines: [{price: 20, qty: 2, category: "books"}, {price: 9.99, qty: 1, category: "digital"}]}, {net: 49.99, tax: 4.2, gross: 54.19, reverseCharge: false}], + [{shipTo: {country: "FR"}, customer: {vatId: "FR123"}, lines: [{price: 20, qty: 2, category: "books"}, {price: 9.99, qty: 1, category: "digital"}]}, {net: 49.99, tax: 0, gross: 49.99, reverseCharge: true}], + [{shipTo: {country: "DE"}, customer: {vatId: "DE999"}, lines: [{price: 100, qty: 1, category: "standard"}]}, {net: 100, tax: 19, gross: 119, reverseCharge: false}], + [{shipTo: {country: "GB"}, customer: {vatId: "GB1"}, lines: [{price: 100, qty: 1, category: "standard"}, {price: 50, qty: 1, category: "food"}]}, {net: 150, tax: 20, gross: 170, reverseCharge: false}], + [{shipTo: {country: "FR"}, customer: {vatId: null}, lines: [{price: 100, qty: 1, category: "standard"}]}, {net: 100, tax: 20, gross: 120, reverseCharge: false}], + [{shipTo: {country: "DE"}, lines: [{price: 40, qty: 1, category: "toys"}]}, {net: 40, tax: 7.6, gross: 47.6, reverseCharge: false}], + [{shipTo: {country: "DE"}, lines: [{price: 0.99, qty: 3, category: "food"}]}, {net: 2.97, tax: 0.21, gross: 3.18, reverseCharge: false}], + [{shipTo: {country: "US"}, lines: [{price: 100, qty: 2, category: "standard"}]}, {net: 200, tax: 0, gross: 200, reverseCharge: false}], + [{shipTo: {country: "DE"}, lines: []}, {net: 0, tax: 0, gross: 0, reverseCharge: false}], + [{shipTo: {country: "NL"}, customer: {vatId: "NL1"}, lines: [{price: 10, qty: 1, category: "food"}]}, {net: 10, tax: 0, gross: 10, reverseCharge: true}], + // A line without a category falls back to the standard rate; an unknown country has no rates; + // a string price fails the arithmetic. + [{shipTo: {country: "DE"}, lines: [{price: 10, qty: 1}]}, {net: 10, tax: 1.9, gross: 11.9, reverseCharge: false}], + [{shipTo: {country: "JP"}, lines: [{price: 10, qty: 1, category: "food"}]}, "!error"], + [{shipTo: {country: "DE"}, lines: [{price: "10", qty: 1, category: "food"}]}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Fraud screening: column-less signal rules; `severity` is first hit while `reasons[]` and +// `points[]` collect from every matching row (the catch-all adds a zero point and no reason). +{ + name: "fraud screening: first-hit severity with collected reasons and points", + graph: { + nodes: [ + {table: "signals", passThrough: true, inputs: [null], outputs: ["severity", "reasons[]", "points[]"], rules: [ + ["payment.cvvMatch == false", "'high'", "'cvv mismatch'", "40"], + ["payment.cardCountry != shipping.country and device.ipCountry != shipping.country", "'high'", "'country mismatch'", "35"], + ["payment.avsMatch == false", "'medium'", "'avs mismatch'", "20"], + ["(payment.attempts24h ?? 0) >= 3", "'medium'", "'velocity'", "15 + 5 * (payment.attempts24h - 3)"], + ["(customer.accountAgeDays ?? 0) < 1 and order.amount > 500", "'medium'", "'new account high value'", "25"], + ["endsWith(customer.email ?? '', '.ru') or contains(customer.email ?? '', '+')", "'low'", "'email pattern'", "5"], + ["", "'none'", "", "0"], + ]}, + {expression: "score", passThrough: true, fields: {score: "sum(points)"}}, + {switch: "decide", when: ["score >= 70 or (severity == 'high' and score >= 40)", "score >= 30", ""]}, + {expression: "decline", fields: {action: "'decline'", score: "score", reasons: "reasons"}}, + {expression: "review", fields: {action: "'review'", score: "score", reasons: "reasons"}}, + {expression: "accept", fields: {action: "'accept'", score: "score"}}, + ], + edges: [ + "input -> signals -> score -> decide", + "decide:0 -> decline -> output", + "decide:1 -> review -> output", + "decide:2 -> accept -> output", + ], + }, + cases: [ + [{order: {amount: 120}, payment: {cardCountry: "DE", avsMatch: true, cvvMatch: true, attempts24h: 1}, customer: {accountAgeDays: 400, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 0}], + [{order: {amount: 120}, payment: {cardCountry: "DE", avsMatch: true, cvvMatch: false, attempts24h: 1}, customer: {accountAgeDays: 400, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "decline", score: 40, reasons: ["cvv mismatch"]}], + [{order: {amount: 120}, payment: {cardCountry: "DE", avsMatch: false, cvvMatch: true, attempts24h: 1}, customer: {accountAgeDays: 400, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 20}], + [{order: {amount: 120}, payment: {cardCountry: "DE", avsMatch: false, cvvMatch: true, attempts24h: 3}, customer: {accountAgeDays: 400, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "review", score: 35, reasons: ["avs mismatch", "velocity"]}], + [{order: {amount: 120}, payment: {cardCountry: "DE", avsMatch: true, cvvMatch: true, attempts24h: 5}, customer: {accountAgeDays: 400, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 25}], + [{order: {amount: 120}, payment: {cardCountry: "US", avsMatch: true, cvvMatch: true, attempts24h: 1}, customer: {accountAgeDays: 400, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "US"}}, {action: "review", score: 35, reasons: ["country mismatch"]}], + [{order: {amount: 120}, payment: {cardCountry: "US", avsMatch: true, cvvMatch: true, attempts24h: 1}, customer: {accountAgeDays: 400, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 0}], + [{order: {amount: 600}, payment: {cardCountry: "DE", avsMatch: true, cvvMatch: true, attempts24h: 1}, customer: {accountAgeDays: 0, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 25}], + [{order: {amount: 600}, payment: {cardCountry: "DE", avsMatch: true, cvvMatch: true, attempts24h: 1}, customer: {accountAgeDays: 0, email: "a+1@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "review", score: 30, reasons: ["new account high value", "email pattern"]}], + [{order: {amount: 500}, payment: {cardCountry: "DE", avsMatch: true, cvvMatch: true, attempts24h: 1}, customer: {accountAgeDays: 0, email: "x@y.ru"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 5}], + [{order: {amount: 120}, payment: {cardCountry: "BR", avsMatch: false, cvvMatch: false, attempts24h: 4}, customer: {accountAgeDays: 400, email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "NG"}}, {action: "decline", score: 115, reasons: ["cvv mismatch", "country mismatch", "avs mismatch", "velocity"]}], + [{order: {amount: 600}, payment: {cardCountry: "DE", avsMatch: false, cvvMatch: true, attempts24h: 7}, customer: {email: "a@b.de"}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "decline", score: 80, reasons: ["avs mismatch", "velocity", "new account high value"]}], + // Missing and mistyped signals. + [{order: {amount: 120}, payment: {cardCountry: "DE"}, customer: {accountAgeDays: 400}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 0}], + [{order: {amount: 120}, payment: {cardCountry: "DE", attempts24h: "5"}, customer: {accountAgeDays: 400}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 0}], + [{order: {amount: 120}, customer: {accountAgeDays: 400}, shipping: {country: "DE"}, device: {ipCountry: "DE"}}, {action: "accept", score: 0}], + [{order: {amount: 120}, payment: {cardCountry: "DE"}, customer: {accountAgeDays: 400}, device: {ipCountry: "DE"}}, {action: "review", score: 35, reasons: ["country mismatch"]}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Loyalty: the tier is re-evaluated from spend and order count, the tier and category pick an +// earning multiplier and bonus, and the expression accumulates the point balance. +{ + name: "loyalty: tier evaluation, earning multiplier and point balance", + graph: { + nodes: [ + {table: "tierEval", passThrough: true, inputs: ["member.lifetimeSpend", "member.ordersYtd"], outputs: ["newTier"], rules: [ + [">= 10000", ">= 24", "'platinum'"], + [">= 5000", ">= 12", "'gold'"], + [">= 1000", "", "'silver'"], + ["", "", "'bronze'"], + ]}, + {table: "earn", passThrough: true, inputs: ["newTier", "purchase.category"], outputs: ["earn.multiplier", "earn.bonus"], rules: [ + ["'platinum'", "", "3", "100"], + ["'gold'", "'electronics'", "1.5", "0"], + ["'gold'", "", "2", "50"], + ["'silver'", "", "1.5", "0"], + ["", "", "1", "0"], + ]}, + {expression: "points", fields: { + tier: "newTier", + tierChanged: "newTier != (member.tier ?? 'bronze')", + earned: "floor(purchase.amount * earn.multiplier) + earn.bonus", + balance: "(member.points ?? 0) + $.earned", + rewardsAvailable: "floor($.balance / 500)", + }}, + ], + }, + cases: [ + [{member: {tier: "silver", lifetimeSpend: 2000, ordersYtd: 3, points: 100}, purchase: {amount: 80, category: "books"}}, {tier: "silver", tierChanged: false, earned: 120, balance: 220, rewardsAvailable: 0}], + [{member: {tier: "silver", lifetimeSpend: 5000, ordersYtd: 12, points: 300}, purchase: {amount: 80, category: "books"}}, {tier: "gold", tierChanged: true, earned: 210, balance: 510, rewardsAvailable: 1}], + [{member: {tier: "gold", lifetimeSpend: 6000, ordersYtd: 20, points: 0}, purchase: {amount: 199.99, category: "electronics"}}, {tier: "gold", tierChanged: false, earned: 299, balance: 299, rewardsAvailable: 0}], + [{member: {tier: "gold", lifetimeSpend: 5000, ordersYtd: 11, points: 0}, purchase: {amount: 10, category: "books"}}, {tier: "silver", tierChanged: true, earned: 15, balance: 15, rewardsAvailable: 0}], + [{member: {tier: "platinum", lifetimeSpend: 10000, ordersYtd: 24, points: 1801}, purchase: {amount: 33.33, category: "books"}}, {tier: "platinum", tierChanged: false, earned: 199, balance: 2000, rewardsAvailable: 4}], + [{member: {tier: "gold", lifetimeSpend: 10000, ordersYtd: 23, points: 0}, purchase: {amount: 10}}, {tier: "gold", tierChanged: false, earned: 70, balance: 70, rewardsAvailable: 0}], + [{member: {lifetimeSpend: 0, ordersYtd: 0}, purchase: {amount: 25.5, category: "books"}}, {tier: "bronze", tierChanged: false, earned: 25, balance: 25, rewardsAvailable: 0}], + [{member: {tier: "silver", points: 499}, purchase: {amount: 1, category: "books"}}, {tier: "bronze", tierChanged: true, earned: 1, balance: 500, rewardsAvailable: 1}], + [{member: {tier: "bronze", lifetimeSpend: 100, points: 100}, purchase: {amount: -50, category: "books"}}, {tier: "bronze", tierChanged: false, earned: -50, balance: 50, rewardsAvailable: 0}], + [{member: {tier: "bronze", lifetimeSpend: 100}, purchase: {amount: 0.99, category: "books"}}, {tier: "bronze", tierChanged: false, earned: 0, balance: 0, rewardsAvailable: 0}], + [{member: {tier: "bronze", lifetimeSpend: "20000", ordersYtd: 30}, purchase: {amount: 10}}, {tier: "bronze", tierChanged: false, earned: 10, balance: 10, rewardsAvailable: 0}], + [{member: {tier: "silver", lifetimeSpend: 2000}, purchase: {category: "books"}}, "!error"], + [{member: {tier: "silver", lifetimeSpend: 2000}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Returns: days since delivery, a return window by category and tier, a switch that accepts +// defective items unconditionally and rejects late returns, then refund terms by condition. +{ + name: "returns: windows, defective override, condition terms and restocking", + graph: { + nodes: [ + {expression: "age", passThrough: true, fields: {daysSinceDelivery: "d(requestedAt).diff(d(deliveredAt), 'day')"}}, + {table: "window", passThrough: true, inputs: ["item.category", "customer.tier"], outputs: ["window"], rules: [ + ["'electronics'", "'vip'", "60"], + ["'electronics'", "", "30"], + ["'final-sale'", "", "0"], + ["", "'vip'", "90"], + ["", "", "45"], + ]}, + {switch: "gate", when: ["reason == 'defective'", "daysSinceDelivery > window", ""]}, + {expression: "defective", fields: {eligible: "true", refundPct: "100", restockingFee: "0", labelPaidBy: "'merchant'", refund: "item.price"}}, + {expression: "late", fields: {eligible: "false", reason: "'outside return window'", daysLate: "daysSinceDelivery - window"}}, + {table: "terms", passThrough: true, inputs: ["item.condition", "item.category"], outputs: ["refundPct", "restockingPct"], rules: [ + ["'new'", "", "100", "0"], + ["'opened'", "'electronics'", "100", "15"], + ["'opened'", "", "100", "0"], + ["'used'", "", "50", "0"], + ["", "", "0", "0"], + ]}, + {expression: "settle", fields: { + eligible: "refundPct > 0", + refundPct: "refundPct", + restockingFee: "round(item.price * restockingPct / 100, 2)", + labelPaidBy: "customer.tier == 'vip' ? 'merchant' : 'customer'", + refund: "round(item.price * refundPct / 100 - $.restockingFee, 2)", + }}, + ], + edges: [ + "input -> age -> window -> gate", + "gate:0 -> defective -> output", + "gate:1 -> late -> output", + "gate:2 -> terms -> settle -> output", + ], + }, + cases: [ + [{deliveredAt: "2025-03-01", requestedAt: "2025-03-20", item: {category: "books", condition: "new", price: 25}}, {eligible: true, refundPct: 100, restockingFee: 0, labelPaidBy: "customer", refund: 25}], + [{deliveredAt: "2025-02-18", requestedAt: "2025-03-20", item: {category: "electronics", condition: "opened", price: 499.99}}, {eligible: true, refundPct: 100, restockingFee: 75, labelPaidBy: "customer", refund: 424.99}], + [{deliveredAt: "2025-02-17", requestedAt: "2025-03-20", item: {category: "electronics", condition: "opened", price: 499.99}}, {eligible: false, reason: "outside return window", daysLate: 1}], + [{deliveredAt: "2025-02-03", requestedAt: "2025-03-20", item: {category: "electronics", condition: "new", price: 499.99}, customer: {tier: "vip"}}, {eligible: true, refundPct: 100, restockingFee: 0, labelPaidBy: "merchant", refund: 499.99}], + [{deliveredAt: "2024-12-20", requestedAt: "2025-03-20", item: {category: "apparel", condition: "new", price: 60}, customer: {tier: "vip"}}, {eligible: true, refundPct: 100, restockingFee: 0, labelPaidBy: "merchant", refund: 60}], + [{deliveredAt: "2024-12-19", requestedAt: "2025-03-20", item: {category: "apparel", condition: "new", price: 60}, customer: {tier: "vip"}}, {eligible: false, reason: "outside return window", daysLate: 1}], + [{deliveredAt: "2025-03-01", requestedAt: "2025-03-20", item: {category: "final-sale", condition: "new", price: 30}}, {eligible: false, reason: "outside return window", daysLate: 19}], + // A zero-day window still admits a same-day request. + [{deliveredAt: "2025-03-20", requestedAt: "2025-03-20", item: {category: "final-sale", condition: "new", price: 30}}, {eligible: true, refundPct: 100, restockingFee: 0, labelPaidBy: "customer", refund: 30}], + [{deliveredAt: "2024-11-01", requestedAt: "2025-03-20", reason: "defective", item: {category: "final-sale", condition: "used", price: 30}}, {eligible: true, refundPct: 100, restockingFee: 0, labelPaidBy: "merchant", refund: 30}], + [{deliveredAt: "2025-03-01", requestedAt: "2025-03-20", item: {category: "apparel", condition: "used", price: 39.99}}, {eligible: true, refundPct: 50, restockingFee: 0, labelPaidBy: "customer", refund: 20}], + [{deliveredAt: "2025-03-01", requestedAt: "2025-03-20", item: {category: "apparel", condition: "damaged", price: 40}}, {eligible: false, refundPct: 0, restockingFee: 0, labelPaidBy: "customer", refund: 0}], + [{deliveredAt: "2025-03-01", requestedAt: "2025-03-20", item: {category: "apparel", price: 40}}, {eligible: false, refundPct: 0, restockingFee: 0, labelPaidBy: "customer", refund: 0}], + [{deliveredAt: "2025-03-01", requestedAt: "2025-03-20", item: {condition: "opened", price: 40}}, {eligible: true, refundPct: 100, restockingFee: 0, labelPaidBy: "customer", refund: 40}], + // Without dates the age is null, `null > window` errors and counts as false, so the return is + // not rejected as late. + [{item: {category: "books", condition: "new", price: 25}}, {eligible: true, refundPct: 100, restockingFee: 0, labelPaidBy: "customer", refund: 25}], + [{deliveredAt: "2025-03-01", requestedAt: "2025-03-20", item: {category: "books", condition: "new", price: "25"}}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/47-realistic-operations.json5 b/core/engine/tests/spec/graph/47-realistic-operations.json5 new file mode 100644 index 00000000..4c9fdc3b --- /dev/null +++ b/core/engine/tests/spec/graph/47-realistic-operations.json5 @@ -0,0 +1,311 @@ +// Realistic operations decisions modelled on the shapes of the published sample graphs: skill +// based assignment with closures over a list of agents, SLA clocks and escalation over dates +// (evaluation time is fixed at Thursday 2025-03-20T10:15:30Z), program eligibility through a +// collect switch whose branches meet at a summary node, appointment scheduling rules with +// collected violations, route planning through a sub-decision loop, and wave planning in a +// function node. Each suite is one decision exercised across main paths, boundaries, missing +// data and bad types. + +// --------------------------------------------------------------------------------------------- +// Ticket assignment: online agents with the ticket's language and product are candidates, the +// least loaded wins (first in list order on a tie); without a candidate a fallback table queues +// the ticket by priority and channel. +{ + name: "ticket assignment: skills, language and load, with a fallback queue", + graph: { + nodes: [ + {expression: "match", passThrough: true, fields: { + candidates: "filter(agents, #.online == true and ticket.language in #.languages and ticket.product in #.skills)", + bestLoad: "len($.candidates) == 0 ? -1 : min(map($.candidates, #.load))", + assignee: "len($.candidates) == 0 ? 'none' : filter($.candidates, #.load == $.bestLoad)[0].id", + }}, + {switch: "route", when: ["assignee != 'none'", ""]}, + {expression: "assigned", fields: {status: "'assigned'", queue: "'agent'", assignee: "assignee"}}, + {table: "fallback", inputs: ["ticket.priority", "ticket.channel"], outputs: ["status", "queue"], rules: [ + ["'p1'", "", "'escalated'", "'on-call'"], + ["", "'phone'", "'queued'", "'callback'"], + ["", "", "'queued'", "'backlog'"], + ]}, + ], + edges: ["input -> match -> route", "route:0 -> assigned -> output", "route:1 -> fallback -> output"], + }, + cases: [ + [{ticket: {language: "en", product: "api", priority: "p2", channel: "email"}, agents: [{id: "a1", online: true, languages: ["en", "de"], skills: ["billing", "api"], load: 3}, {id: "a2", online: true, languages: ["en"], skills: ["api"], load: 1}, {id: "a3", online: false, languages: ["de"], skills: ["billing"], load: 0}, {id: "a4", online: true, languages: ["fr", "en"], skills: ["billing"], load: 3}]}, {status: "assigned", queue: "agent", assignee: "a2"}], + [{ticket: {language: "en", product: "billing", priority: "p2", channel: "email"}, agents: [{id: "a1", online: true, languages: ["en", "de"], skills: ["billing", "api"], load: 3}, {id: "a2", online: true, languages: ["en"], skills: ["api"], load: 1}, {id: "a3", online: false, languages: ["de"], skills: ["billing"], load: 0}, {id: "a4", online: true, languages: ["fr", "en"], skills: ["billing"], load: 3}]}, {status: "assigned", queue: "agent", assignee: "a1"}], + [{ticket: {language: "de", product: "billing", priority: "p2", channel: "email"}, agents: [{id: "a1", online: true, languages: ["en", "de"], skills: ["billing", "api"], load: 3}, {id: "a2", online: true, languages: ["en"], skills: ["api"], load: 1}, {id: "a3", online: false, languages: ["de"], skills: ["billing"], load: 0}, {id: "a4", online: true, languages: ["fr", "en"], skills: ["billing"], load: 3}]}, {status: "assigned", queue: "agent", assignee: "a1"}], + [{ticket: {language: "fr", product: "billing", priority: "p3", channel: "chat"}, agents: [{id: "a1", online: true, languages: ["en", "de"], skills: ["billing", "api"], load: 3}, {id: "a4", online: true, languages: ["fr", "en"], skills: ["billing"], load: 3}]}, {status: "assigned", queue: "agent", assignee: "a4"}], + [{ticket: {language: "fr", product: "api", priority: "p2", channel: "email"}, agents: [{id: "a1", online: true, languages: ["en", "de"], skills: ["billing", "api"], load: 3}, {id: "a4", online: true, languages: ["fr", "en"], skills: ["billing"], load: 3}]}, {status: "queued", queue: "backlog"}], + [{ticket: {language: "fr", product: "api", priority: "p1", channel: "phone"}, agents: [{id: "a4", online: true, languages: ["fr", "en"], skills: ["billing"], load: 3}]}, {status: "escalated", queue: "on-call"}], + [{ticket: {language: "fr", product: "api", priority: "p2", channel: "phone"}, agents: [{id: "a4", online: true, languages: ["fr", "en"], skills: ["billing"], load: 3}]}, {status: "queued", queue: "callback"}], + [{ticket: {language: "en", product: "api", priority: "p2", channel: "email"}, agents: [{id: "z9", online: true, languages: ["en"], skills: ["api"], load: 0}, {id: "a1", online: true, languages: ["en"], skills: ["api"], load: 0}]}, {status: "assigned", queue: "agent", assignee: "z9"}], + [{ticket: {language: "en", product: "api", priority: "p1", channel: "email"}, agents: []}, {status: "escalated", queue: "on-call"}], + [{ticket: {product: "api", priority: "p3", channel: "email"}, agents: [{id: "a2", online: true, languages: ["en"], skills: ["api"], load: 1}]}, {status: "queued", queue: "backlog"}], + [{ticket: {language: "en", product: "api", priority: "p3", channel: "email"}, agents: [{id: "a2", online: "true", languages: ["en"], skills: ["api"], load: 1}]}, {status: "queued", queue: "backlog"}], + [{ticket: {language: "en", product: "api"}, agents: [{id: "a2", online: false, languages: ["en"], skills: ["api"], load: 1}]}, {status: "queued", queue: "backlog"}], + // Bad data: an agent without a languages list breaks `in`, a missing agents list breaks filter. + [{ticket: {language: "en", product: "api", priority: "p2", channel: "email"}, agents: [{id: "a2", online: true, skills: ["api"], load: 1}]}, "!error"], + [{ticket: {language: "en", product: "api", priority: "p2", channel: "email"}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// SLA clock: response and resolution targets by priority and tier, elapsed hours against the +// fixed evaluation time, a response breach measured either from the first response or from now, +// and an escalation band; the final expression reads the clock through `$nodes`. +{ + name: "sla clock: targets, response breach and escalation band", + graph: { + nodes: [ + {table: "targets", passThrough: true, inputs: ["priority", "customer.tier"], outputs: ["sla.responseH", "sla.resolveH"], rules: [ + ["'p1'", "'enterprise'", "1", "4"], + ["'p1'", "", "2", "8"], + ["'p2'", "'enterprise'", "4", "24"], + ["'p2'", "", "8", "48"], + ["'p3'", "", "24", "120"], + ["", "", "48", "240"], + ]}, + {expression: "clock", passThrough: true, fields: { + "sla.responseDue": "d(openedAt).add(sla.responseH, 'hour').format('%Y-%m-%dT%H:%M')", + "sla.elapsedH": "d().diff(d(openedAt), 'minute') / 60", + "sla.responseBreached": "firstResponseAt != null ? d(firstResponseAt).diff(d(openedAt), 'minute') > sla.responseH * 60 : $.sla.elapsedH > sla.responseH", + "sla.pctResolve": "round($.sla.elapsedH / sla.resolveH * 100, 1)", + }}, + {table: "escalation", inputs: ["sla.pctResolve", "sla.responseBreached"], outputs: ["escalation"], rules: [ + [">= 100", "", "'breached'"], + [">= 75", "", "'warning'"], + ["", "true", "'response-missed'"], + ["", "", "'ok'"], + ]}, + {expression: "report", fields: { + escalation: "escalation", + responseDue: "$nodes.clock.sla.responseDue", + responseBreached: "$nodes.clock.sla.responseBreached", + pctResolve: "$nodes.clock.sla.pctResolve", + }}, + ], + }, + cases: [ + [{priority: "p1", customer: {tier: "enterprise"}, openedAt: "2025-03-20T09:15:00Z", firstResponseAt: "2025-03-20T09:45:00Z"}, {escalation: "ok", responseDue: "2025-03-20T10:15", responseBreached: false, pctResolve: 25}], + [{priority: "p1", customer: {tier: "enterprise"}, openedAt: "2025-03-20T09:15:00Z"}, {escalation: "ok", responseDue: "2025-03-20T10:15", responseBreached: false, pctResolve: 25}], + [{priority: "p1", customer: {tier: "enterprise"}, openedAt: "2025-03-20T09:03:00Z"}, {escalation: "response-missed", responseDue: "2025-03-20T10:03", responseBreached: true, pctResolve: 30}], + [{priority: "p1", customer: {tier: "standard"}, openedAt: "2025-03-20T04:15:00Z", firstResponseAt: "2025-03-20T05:00:00Z"}, {escalation: "warning", responseDue: "2025-03-20T06:15", responseBreached: false, pctResolve: 75}], + [{priority: "p1", openedAt: "2025-03-20T02:15:00Z", firstResponseAt: "2025-03-20T02:20:00Z"}, {escalation: "breached", responseDue: "2025-03-20T04:15", responseBreached: false, pctResolve: 100}], + [{priority: "p2", customer: {tier: "enterprise"}, openedAt: "2025-03-19T10:15:00Z", firstResponseAt: "2025-03-19T16:15:00Z"}, {escalation: "breached", responseDue: "2025-03-19T14:15", responseBreached: true, pctResolve: 100}], + [{priority: "p2", customer: {tier: "pro"}, openedAt: "2025-03-19T10:15:00Z", firstResponseAt: "2025-03-19T19:00:00Z"}, {escalation: "response-missed", responseDue: "2025-03-19T18:15", responseBreached: true, pctResolve: 50}], + [{priority: "p2", customer: {tier: "pro"}, openedAt: "2025-03-19T10:15:00Z", firstResponseAt: "2025-03-19T18:15:00Z"}, {escalation: "ok", responseDue: "2025-03-19T18:15", responseBreached: false, pctResolve: 50}], + [{priority: "p3", openedAt: "2025-03-17T10:15:00Z", firstResponseAt: "2025-03-17T12:00:00Z"}, {escalation: "ok", responseDue: "2025-03-18T10:15", responseBreached: false, pctResolve: 60}], + [{priority: "p9", openedAt: "2025-03-10T10:15:00Z", firstResponseAt: "2025-03-10T11:00:00Z"}, {escalation: "breached", responseDue: "2025-03-12T10:15", responseBreached: false, pctResolve: 100}], + [{openedAt: "2025-03-19T10:15:00Z"}, {escalation: "ok", responseDue: "2025-03-21T10:15", responseBreached: false, pctResolve: 10}], + [{priority: "p1", customer: {tier: "enterprise"}, openedAt: "2025-03-20T12:00:00Z"}, {escalation: "ok", responseDue: "2025-03-20T13:00", responseBreached: false, pctResolve: -43.3}], + [{priority: "p3", openedAt: "2025-03-20T10:15:00Z", firstResponseAt: "2025-03-20T10:16:00Z"}, {escalation: "ok", responseDue: "2025-03-21T10:15", responseBreached: false, pctResolve: 0}], + // No opening time, and an unparsable first response. + [{priority: "p3"}, "!error"], + [{priority: "p3", openedAt: "2025-03-20T09:15:00Z", firstResponseAt: "soon"}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Assistance programs: the federal poverty line by household size, income as a percentage of it, +// then a collect switch fans out to every program the household qualifies for; the default +// branch always runs and carries the percentage, and all branches meet at a summary node. +{ + name: "program eligibility: poverty line, collect switch and a summary join", + graph: { + nodes: [ + {table: "fpl", passThrough: true, inputs: ["household.size"], outputs: ["fpl"], rules: [ + ["1", "15060"], + ["2", "20440"], + ["3", "25820"], + ["4", "31200"], + ["> 4", "31200 + 5380 * (household.size - 4)"], + ]}, + {expression: "ratio", passThrough: true, fields: {incomePct: "round(household.income / fpl * 100)"}}, + {switch: "programs", hit: "collect", when: [ + "incomePct <= 138", + "incomePct <= 185 and some(household.members, #.age < 5 or #.pregnant == true)", + "incomePct <= 130", + "incomePct <= 150 and some(household.members, #.age >= 65 or #.disabled == true)", + "", + ]}, + {expression: "medicaid", fields: {"programs.medicaid": "true"}}, + {expression: "wic", fields: {"programs.wic": "true"}}, + {expression: "snap", fields: {"programs.snap.monthly": "max([23, round([0, 292, 536, 768, 975][min([household.size, 4])] - 0.3 * household.income / 12)])"}}, + {expression: "energy", fields: {"programs.energy": "true"}}, + {expression: "base", fields: {incomePct: "incomePct"}}, + {expression: "summary", fields: {incomePct: "incomePct", programs: "programs ?? {}"}}, + ], + edges: [ + "input -> fpl -> ratio -> programs", + "programs:0 -> medicaid -> summary", + "programs:1 -> wic -> summary", + "programs:2 -> snap -> summary", + "programs:3 -> energy -> summary", + "programs:4 -> base -> summary", + "summary -> output", + ], + }, + cases: [ + [{household: {size: 1, income: 12000, members: [{age: 30}]}}, {incomePct: 80, programs: {medicaid: true, snap: {monthly: 23}}}], + [{household: {size: 3, income: 24000, members: [{age: 30}, {age: 28, pregnant: true}, {age: 3}]}}, {incomePct: 93, programs: {medicaid: true, wic: true, snap: {monthly: 168}}}], + [{household: {size: 4, income: 40000, members: [{age: 40}, {age: 38}, {age: 10}, {age: 4}]}}, {incomePct: 128, programs: {medicaid: true, wic: true, snap: {monthly: 23}}}], + [{household: {size: 4, income: 45000, members: [{age: 40}, {age: 38}, {age: 10}, {age: 4}]}}, {incomePct: 144, programs: {wic: true}}], + [{household: {size: 2, income: 25000, members: [{age: 70}, {age: 68}]}}, {incomePct: 122, programs: {medicaid: true, snap: {monthly: 23}, energy: true}}], + [{household: {size: 2, income: 30000, members: [{age: 67}, {age: 60, disabled: true}]}}, {incomePct: 147, programs: {energy: true}}], + [{household: {size: 6, income: 50000, members: [{age: 35}, {age: 33}, {age: 12}, {age: 10}, {age: 8}, {age: 6}]}}, {incomePct: 119, programs: {medicaid: true, snap: {monthly: 23}}}], + [{household: {size: 1, income: 0, members: [{age: 22}]}}, {incomePct: 0, programs: {medicaid: true, snap: {monthly: 292}}}], + [{household: {size: 1, income: 20782.8, members: [{age: 22}]}}, {incomePct: 138, programs: {medicaid: true}}], + [{household: {size: 1, income: 100000, members: [{age: 22}]}}, {incomePct: 664, programs: {}}], + // Members missing: the member conditions error and count as false; the income rules still run. + [{household: {size: 1, income: 12000}}, {incomePct: 80, programs: {medicaid: true, snap: {monthly: 23}}}], + // No poverty line for size 0 or a string size; no income. + [{household: {size: 0, income: 12000, members: []}}, "!error"], + [{household: {size: "2", income: 12000, members: []}}, "!error"], + [{household: {size: 2, members: []}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Appointment scheduling: slot parts are derived once, then a column-less table takes `allowed` +// from the first matching rule and collects every violation through `violations[]`. +{ + name: "scheduling: business hours, holidays, lead time and capacity", + graph: { + nodes: [ + {expression: "parts", passThrough: true, fields: { + "slot.weekday": "d(slot.start).weekday()", + "slot.hour": "d(slot.start).hour()", + "slot.leadH": "d(slot.start).diff(d(), 'hour')", + "slot.date": "d(slot.start).format('%Y-%m-%d')", + }}, + {table: "rules", inputs: [null], outputs: ["allowed", "violations[]"], rules: [ + ["slot.weekday > 5", "false", "'weekend'"], + ["slot.hour < 9 or slot.hour + duration / 60 > 17", "false", "'outside business hours'"], + ["slot.date in holidays", "false", "'holiday'"], + ["slot.leadH < (patient.isNew == true ? 24 : 2)", "false", "'insufficient lead time'"], + ["provider.booked + 1 > provider.capacity", "false", "'provider full'"], + ["", "true", ""], + ]}, + {expression: "result", fields: {allowed: "allowed", violations: "violations", date: "$nodes.parts.slot.date"}}, + ], + }, + cases: [ + [{slot: {start: "2025-03-21T10:00:00Z"}, duration: 30, patient: {isNew: false}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: true, violations: [], date: "2025-03-21"}], + [{slot: {start: "2025-03-21T10:00:00Z"}, duration: 30, patient: {isNew: true}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: false, violations: ["insufficient lead time"], date: "2025-03-21"}], + [{slot: {start: "2025-03-21T10:16:00Z"}, duration: 30, patient: {isNew: true}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: true, violations: [], date: "2025-03-21"}], + [{slot: {start: "2025-03-22T10:00:00Z"}, duration: 30, patient: {isNew: false}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: false, violations: ["weekend"], date: "2025-03-22"}], + [{slot: {start: "2025-03-21T08:30:00Z"}, duration: 30, patient: {isNew: true}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: false, violations: ["outside business hours", "insufficient lead time"], date: "2025-03-21"}], + [{slot: {start: "2025-03-21T16:30:00Z"}, duration: 30, patient: {isNew: false}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: true, violations: [], date: "2025-03-21"}], + [{slot: {start: "2025-03-21T16:30:00Z"}, duration: 90, patient: {isNew: false}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: false, violations: ["outside business hours"], date: "2025-03-21"}], + [{slot: {start: "2025-04-21T10:00:00Z"}, duration: 30, patient: {isNew: false}, provider: {booked: 0, capacity: 8}, holidays: ["2025-04-18", "2025-04-21"]}, {allowed: false, violations: ["holiday"], date: "2025-04-21"}], + [{slot: {start: "2025-03-21T10:00:00Z"}, duration: 30, patient: {isNew: false}, provider: {booked: 8, capacity: 8}, holidays: []}, {allowed: false, violations: ["provider full"], date: "2025-03-21"}], + [{slot: {start: "2025-03-21T10:00:00Z"}, duration: 30, patient: {isNew: false}, provider: {booked: 7, capacity: 8}, holidays: []}, {allowed: true, violations: [], date: "2025-03-21"}], + [{slot: {start: "2025-03-22T07:00:00Z"}, duration: 30, patient: {isNew: true}, provider: {booked: 8, capacity: 8}, holidays: ["2025-03-22"]}, {allowed: false, violations: ["weekend", "outside business hours", "holiday", "provider full"], date: "2025-03-22"}], + [{slot: {start: "2025-03-20T09:00:00Z"}, duration: 30, patient: {isNew: false}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: false, violations: ["insufficient lead time"], date: "2025-03-20"}], + [{slot: {start: "2025-03-20T12:15:30Z"}, duration: 30, patient: {isNew: false}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: true, violations: [], date: "2025-03-20"}], + // Missing reference data: each rule whose condition errors is skipped. + [{slot: {start: "2025-03-21T10:00:00Z"}, duration: 30, patient: {isNew: false}}, {allowed: true, violations: [], date: "2025-03-21"}], + [{slot: {start: "2025-03-21T10:00:00Z"}, patient: {isNew: false}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: true, violations: [], date: "2025-03-21"}], + [{slot: {start: "2025-03-21T10:00:00Z"}, duration: 30, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: true, violations: [], date: "2025-03-21"}], + [{slot: {start: "2025-03-21T07:00:00Z"}, patient: {isNew: false}, provider: {booked: 3, capacity: 8}, holidays: []}, {allowed: false, violations: ["outside business hours"], date: "2025-03-21"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Route planning: a sub-decision runs once per stop (loop mode) to price service minutes, the +// result array joins with the request, and an expression checks the route against the shift. +{ + name: "route planning: per-stop service time sub-decision and shift feasibility", + decisions: { + stopTime: { + nodes: [ + {table: "minutes", inputs: ["type", "parcels"], outputs: ["minutes"], rules: [ + ["'business'", "", "4 + parcels"], + ["'residential'", "<= 2", "3"], + ["'residential'", "", "3 + 0.5 * (parcels - 2)"], + ["'locker'", "", "2"], + ["", "", "6"], + ]}, + ], + }, + }, + graph: { + nodes: [ + {decision: "stops", key: "stopTime", executionMode: "loop", inputField: "route.stops", outputPath: "stopTimes"}, + {expression: "plan", fields: { + stops: "len(route.stops)", + serviceMin: "sum(map(stopTimes, #.minutes))", + driveMin: "route.distanceKm / (route.urban == true ? 25 : 50) * 60", + totalMin: "round($.serviceMin + $.driveMin)", + shiftLeft: "driver.shiftMin - driver.usedMin", + feasible: "$.totalMin <= $.shiftLeft", + overtime: "max([0, $.totalMin - $.shiftLeft])", + }}, + ], + edges: ["input -> stops -> plan -> output", "input -> plan"], + }, + cases: [ + [{route: {stops: [{type: "business", parcels: 3}, {type: "residential", parcels: 1}, {type: "locker", parcels: 5}], distanceKm: 50, urban: true}, driver: {shiftMin: 480, usedMin: 300}}, {stops: 3, serviceMin: 12, driveMin: 120, totalMin: 132, shiftLeft: 180, feasible: true, overtime: 0}], + [{route: {stops: [{type: "residential", parcels: 6}], distanceKm: 100}, driver: {shiftMin: 480, usedMin: 0}}, {stops: 1, serviceMin: 5, driveMin: 120, totalMin: 125, shiftLeft: 480, feasible: true, overtime: 0}], + [{route: {stops: [{type: "residential", parcels: 2}, {type: "farm", parcels: 1}], distanceKm: 10, urban: false}, driver: {shiftMin: 480, usedMin: 0}}, {stops: 2, serviceMin: 9, driveMin: 12, totalMin: 21, shiftLeft: 480, feasible: true, overtime: 0}], + [{route: {stops: [], distanceKm: 25}, driver: {shiftMin: 30, usedMin: 0}}, {stops: 0, serviceMin: 0, driveMin: 30, totalMin: 30, shiftLeft: 30, feasible: true, overtime: 0}], + [{route: {stops: [{type: "business", parcels: 10}], distanceKm: 200, urban: true}, driver: {shiftMin: 480, usedMin: 300}}, {stops: 1, serviceMin: 14, driveMin: 480, totalMin: 494, shiftLeft: 180, feasible: false, overtime: 314}], + [{route: {stops: [{type: "residential", parcels: 3}], distanceKm: 7, urban: true}, driver: {shiftMin: 480, usedMin: 0}}, {stops: 1, serviceMin: 3.5, driveMin: 16.8, totalMin: 20, shiftLeft: 480, feasible: true, overtime: 0}], + [{route: {stops: [{type: "business"}], distanceKm: 0}, driver: {shiftMin: 60, usedMin: 0}}, {stops: 1, serviceMin: 6, driveMin: 0, totalMin: 6, shiftLeft: 60, feasible: true, overtime: 0}], + // A residential stop without parcels: the `<= 2` cell errors, the next row's output cell + // errors too and skips that row, so the catch-all row prices it. + [{route: {stops: [{type: "residential"}], distanceKm: 0}, driver: {shiftMin: 60, usedMin: 0}}, {stops: 1, serviceMin: 6, driveMin: 0, totalMin: 6, shiftLeft: 60, feasible: true, overtime: 0}], + [{route: {stops: [{type: "locker"}], distanceKm: 5}, driver: {shiftMin: 60, usedMin: 60}}, {stops: 1, serviceMin: 2, driveMin: 6, totalMin: 8, shiftLeft: 0, feasible: false, overtime: 8}], + [{route: {distanceKm: 5}, driver: {shiftMin: 60, usedMin: 0}}, "!error"], + [{route: {stops: [{type: "locker"}]}, driver: {shiftMin: 60, usedMin: 0}}, "!error"], + [{route: {stops: [{type: "locker"}], distanceKm: "5"}, driver: {shiftMin: 60, usedMin: 0}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Wave planning: a function node sorts orders by priority then id and packs them first-fit into +// waves of fixed capacity; a table after it picks the shift pattern from the wave count. +{ + name: "wave planning: first-fit packing in a function node, shift by wave count", + graph: { + nodes: [ + {function: "pack", source: """ +export const handler = async (input) => { + const cap = input.waveCapacity; + if (!(cap > 0)) { + throw new Error('waveCapacity must be positive'); + } + const orders = [...(input.orders ?? [])].sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id)); + const waves = []; + for (const o of orders) { + let w = waves.find((x) => x.units + o.units <= cap); + if (!w) { + w = { wave: waves.length + 1, units: 0, orders: [] }; + waves.push(w); + } + w.units += o.units; + w.orders.push(o.id); + } + return { waves, waveCount: waves.length }; +}; +"""}, + {table: "shift", passThrough: true, inputs: ["waveCount"], outputs: ["shift"], rules: [ + ["<= 2", "'day'"], + ["<= 4", "'day+evening'"], + ["", "'overtime'"], + ]}, + ], + }, + cases: [ + [{waveCapacity: 10, orders: [{id: "a", priority: 1, units: 4}, {id: "b", priority: 2, units: 5}, {id: "c", priority: 1, units: 6}]}, {waves: [{wave: 1, units: 10, orders: ["a", "c"]}, {wave: 2, units: 5, orders: ["b"]}], waveCount: 2, shift: "day"}], + [{waveCapacity: 10, orders: []}, {waves: [], waveCount: 0, shift: "day"}], + [{waveCapacity: 10}, {waves: [], waveCount: 0, shift: "day"}], + [{waveCapacity: 10, orders: [{id: "x", priority: 1, units: 12}, {id: "y", priority: 1, units: 3}]}, {waves: [{wave: 1, units: 12, orders: ["x"]}, {wave: 2, units: 3, orders: ["y"]}], waveCount: 2, shift: "day"}], + [{waveCapacity: 10, orders: [{id: "a", priority: 1, units: 7}, {id: "b", priority: 1, units: 5}, {id: "c", priority: 2, units: 3}]}, {waves: [{wave: 1, units: 10, orders: ["a", "c"]}, {wave: 2, units: 5, orders: ["b"]}], waveCount: 2, shift: "day"}], + [{waveCapacity: 10, orders: [{id: "b", priority: 1, units: 2}, {id: "a", priority: 1, units: 2}]}, {waves: [{wave: 1, units: 4, orders: ["a", "b"]}], waveCount: 1, shift: "day"}], + [{waveCapacity: 5, orders: [{id: "a", priority: 1, units: 5}, {id: "b", priority: 1, units: 5}, {id: "c", priority: 1, units: 5}]}, {waves: [{wave: 1, units: 5, orders: ["a"]}, {wave: 2, units: 5, orders: ["b"]}, {wave: 3, units: 5, orders: ["c"]}], waveCount: 3, shift: "day+evening"}], + [{waveCapacity: 4, orders: [{id: "a", priority: 3, units: 4}, {id: "b", priority: 2, units: 4}, {id: "c", priority: 1, units: 4}, {id: "d", priority: 1, units: 3}, {id: "e", priority: 5, units: 1}]}, {waves: [{wave: 1, units: 4, orders: ["c"]}, {wave: 2, units: 4, orders: ["d", "e"]}, {wave: 3, units: 4, orders: ["b"]}, {wave: 4, units: 4, orders: ["a"]}], waveCount: 4, shift: "day+evening"}], + [{waveCapacity: 1, orders: [{id: "a", priority: 1, units: 1}, {id: "b", priority: 1, units: 1}, {id: "c", priority: 1, units: 1}, {id: "d", priority: 1, units: 1}, {id: "e", priority: 1, units: 1}]}, {waves: [{wave: 1, units: 1, orders: ["a"]}, {wave: 2, units: 1, orders: ["b"]}, {wave: 3, units: 1, orders: ["c"]}, {wave: 4, units: 1, orders: ["d"]}, {wave: 5, units: 1, orders: ["e"]}], waveCount: 5, shift: "overtime"}], + [{waveCapacity: 0, orders: [{id: "a", priority: 1, units: 1}]}, "!error: waveCapacity must be positive"], + [{orders: [{id: "a", priority: 1, units: 1}]}, "!error: waveCapacity must be positive"], + ], +} diff --git a/core/engine/tests/spec/graph/48-rows-heterogeneous-types.json5 b/core/engine/tests/spec/graph/48-rows-heterogeneous-types.json5 new file mode 100644 index 00000000..44236f77 --- /dev/null +++ b/core/engine/tests/spec/graph/48-rows-heterogeneous-types.json5 @@ -0,0 +1,1268 @@ +// Rows of one suite whose fields change type from case to case. +// +// The compiled engine evaluates a suite's cases as one batch and as columns: a field that is a +// number in every row becomes a decimal column, strings a text column, booleans a bit column, +// and anything mixed (or nested values, or arrays) an untyped column. Null and missing cells are +// both absent in a column. These suites keep one decision fixed and vary the type of the same +// field across rows, so each node kind meets every value type in the same batch. The expected +// results are the single-row semantics: a row's result never depends on its neighbours. + +// --- Expressions over a field of varying type --------------------------------------------- + +{ + name: "type() of one field across every value type", + graph: { + nodes: [{expression: "e", fields: {t: "type(v)"}}], + }, + cases: [ + [{v: 1}, {t: "number"}], + [{v: -2.5}, {t: "number"}], + [{v: "a"}, {t: "string"}], + [{v: ""}, {t: "string"}], + [{v: true}, {t: "bool"}], + [{v: false}, {t: "bool"}], + [{v: null}, {t: "null"}], + [{}, {t: "null"}], + [{v: [1, 2]}, {t: "array"}], + [{v: []}, {t: "array"}], + [{v: {a: 1}}, {t: "object"}], + [{v: {}}, {t: "object"}], + ], +} + +{ + name: "a numeric field with null and missing rows, defaulted with ??", + graph: { + nodes: [{expression: "e", fields: {r: "(v ?? 0) * 2"}}], + }, + cases: [ + [{v: 1}, {r: 2}], + [{v: 2.5}, {r: 5}], + [{v: null}, {r: 0}], + [{}, {r: 0}], + [{v: 0}, {r: 0}], + [{v: -3}, {r: -6}], + [{v: 0.1}, {r: 0.2}], + [{v: 12345678901234567890.5}, {r: 24691357802469135781}], + [{v: 1.000}, {r: 2}], + ], +} + +{ + name: "a numeric field read without a default errors only on the rows where it is absent", + graph: { + nodes: [{expression: "e", fields: {r: "v + 1"}}], + }, + cases: [ + [{v: 1}, {r: 2}], + [{v: null}, "!error"], + [{v: 41}, {r: 42}], + [{}, "!error"], + [{v: -1}, {r: 0}], + [{v: 0.5}, {r: 1.5}], + ], +} + +{ + name: "a numeric field that is sometimes a numeric string", + graph: { + nodes: [{expression: "e", fields: {r: "isNumeric(v) ? number(v) * 10 : -1"}}], + }, + cases: [ + [{v: 1}, {r: 10}], + [{v: "2"}, {r: 20}], + [{v: "2.5"}, {r: 25}], + [{v: "x"}, {r: -1}], + [{v: ""}, {r: -1}], + [{v: true}, {r: -1}], + [{v: null}, {r: -1}], + [{}, {r: -1}], + [{v: 0.01}, {r: 0.1}], + ], +} + +{ + name: "arithmetic on a field that is a number in some rows and a string in others", + graph: { + nodes: [{expression: "e", fields: {r: "v * 2"}}], + }, + cases: [ + [{v: 3}, {r: 6}], + [{v: "3"}, "!error"], + [{v: 4}, {r: 8}], + [{v: true}, "!error"], + [{v: [1]}, "!error"], + [{v: {a: 1}}, "!error"], + [{v: -0.5}, {r: -1}], + ], +} + +{ + name: "+ adds numbers and concatenates strings, row by row", + graph: { + nodes: [{expression: "e", fields: {r: "a + b"}}], + }, + cases: [ + [{a: 1, b: 2}, {r: 3}], + [{a: "x", b: "y"}, {r: "xy"}], + [{a: 1, b: "y"}, "!error"], + [{a: "x", b: 2}, "!error"], + [{a: 0.1, b: 0.2}, {r: 0.3}], + [{a: "", b: ""}, {r: ""}], + [{a: true, b: 1}, "!error"], + [{a: null, b: 1}, "!error"], + ], +} + +{ + name: "equality against a number literal across value types", + graph: { + nodes: [{expression: "e", fields: {eq: "v == 1", ne: "v != 1"}}], + }, + cases: [ + [{v: 1}, {eq: true, ne: false}], + [{v: 1.0}, {eq: true, ne: false}], + [{v: "1"}, {eq: false, ne: true}], + [{v: true}, {eq: false, ne: true}], + [{v: null}, {eq: false, ne: true}], + [{}, {eq: false, ne: true}], + [{v: [1]}, {eq: false, ne: true}], + [{v: {a: 1}}, {eq: false, ne: true}], + [{v: 2}, {eq: false, ne: true}], + ], +} + +{ + name: "equality against a string literal across value types", + graph: { + nodes: [{expression: "e", fields: {eq: "v == 'a'"}}], + }, + cases: [ + [{v: "a"}, {eq: true}], + [{v: "A"}, {eq: false}], + [{v: ""}, {eq: false}], + [{v: 1}, {eq: false}], + [{v: false}, {eq: false}], + [{v: null}, {eq: false}], + [{}, {eq: false}], + [{v: ["a"]}, {eq: false}], + ], +} + +{ + name: "membership in a mixed literal list across value types", + graph: { + nodes: [{expression: "e", fields: {r: "v in [1, 'a', true]"}}], + }, + cases: [ + [{v: 1}, {r: true}], + [{v: "a"}, {r: true}], + [{v: true}, {r: true}], + [{v: false}, {r: false}], + [{v: "1"}, {r: false}], + [{v: 2}, {r: false}], + [{v: null}, {r: false}], + [{}, {r: false}], + ], +} + +{ + name: "len() over strings and arrays in one field", + graph: { + nodes: [{expression: "e", fields: {n: "len(v)"}}], + }, + cases: [ + [{v: "abc"}, {n: 3}], + [{v: [1, 2]}, {n: 2}], + [{v: ""}, {n: 0}], + [{v: []}, {n: 0}], + [{v: "żółw"}, {n: 4}, "bug: len counts UTF-8 bytes (7) instead of characters, as in the expression spec"], + [{v: ["a", "b", "c", "d"]}, {n: 4}], + [{v: 12}, "!error"], + [{v: true}, "!error"], + ], +} + +{ + name: "string() converts every scalar type", + graph: { + nodes: [{expression: "e", fields: {s: "string(v)"}}], + }, + cases: [ + [{v: 1}, {s: "1"}], + [{v: -2.5}, {s: "-2.5"}], + [{v: "x"}, {s: "x"}], + [{v: true}, {s: "true"}], + [{v: false}, {s: "false"}], + [{v: null}, {s: "null"}], + [{}, {s: "null"}], + [{v: 0}, {s: "0"}], + ], +} + +{ + name: "a ternary on a boolean field with missing and non-boolean rows", + graph: { + nodes: [{expression: "e", fields: {r: "v == true ? 'yes' : 'no'"}}], + }, + cases: [ + [{v: true}, {r: "yes"}], + [{v: false}, {r: "no"}], + [{v: null}, {r: "no"}], + [{}, {r: "no"}], + [{v: 1}, {r: "no"}], + [{v: "true"}, {r: "no"}], + [{v: true}, {r: "yes"}], + ], +} + +{ + name: "logical operators on a boolean field with gaps", + graph: { + nodes: [{expression: "e", fields: {both: "(a ?? false) and (b ?? false)", either: "(a ?? false) or (b ?? false)"}}], + }, + cases: [ + [{a: true, b: true}, {both: true, either: true}], + [{a: true, b: false}, {both: false, either: true}], + [{a: false}, {both: false, either: false}], + [{b: true}, {both: false, either: true}], + [{}, {both: false, either: false}], + [{a: null, b: null}, {both: false, either: false}], + [{a: false, b: false}, {both: false, either: false}], + ], +} + +{ + name: "member access on a field that is sometimes an object", + graph: { + nodes: [{expression: "e", fields: {x: "v.x", has: "v.x != null"}}], + }, + cases: [ + [{v: {x: 1}}, {has: true, x: 1}], + [{v: {x: "s"}}, {has: true, x: "s"}], + [{v: {y: 1}}, {has: false}], + [{v: {}}, {has: false}], + [{v: null}, {has: false}], + [{}, {has: false}], + [{v: {x: [1, 2]}}, {has: true, x: [1, 2]}], + [{v: {x: {deep: true}}}, {has: true, x: {deep: true}}], + ], +} + +{ + name: "copying a field of any type through an expression keeps its value", + graph: { + nodes: [{expression: "e", fields: {copy: "v"}}], + }, + cases: [ + [{v: 1}, {copy: 1}], + [{v: "a"}, {copy: "a"}], + [{v: true}, {copy: true}], + [{v: false}, {copy: false}], + [{v: [1, "a", null]}, {copy: [1, "a", null]}], + [{v: {k: [1]}}, {copy: {k: [1]}}], + [{v: null}, {}], + [{}, {}], + [{v: 0}, {copy: 0}], + [{v: ""}, {copy: ""}], + ], +} + +{ + name: "pass-through keeps a heterogeneous field untouched next to a computed one", + graph: { + nodes: [{expression: "e", passThrough: true, fields: {t: "type(v)"}}], + }, + cases: [ + [{v: 1}, {v: 1, t: "number"}], + [{v: "x"}, {v: "x", t: "string"}], + [{v: [true]}, {v: [true], t: "array"}], + [{v: {a: {b: 1}}}, {v: {a: {b: 1}}, t: "object"}], + [{v: false}, {v: false, t: "bool"}], + [{}, {t: "null"}], + ], +} + +{ + name: "numbers of different scale and magnitude in one column", + graph: { + nodes: [{expression: "e", fields: {r: "round(v, 1)", gt: "v > 1"}}], + }, + cases: [ + [{v: 1}, {r: 1, gt: false}], + [{v: 1.05}, {r: 1.1, gt: true}], + [{v: 1.04}, {r: 1, gt: true}], + [{v: -1.05}, {r: -1.1, gt: false}], + [{v: 0.000001}, {r: 0, gt: false}], + [{v: 1000000000000}, {r: 1000000000000, gt: true}], + [{v: 1.00}, {r: 1, gt: false}], + [{v: 99.99}, {r: 100, gt: true}], + ], +} + +{ + name: "ordering a field across numbers, strings and absent values", + graph: { + nodes: [{expression: "e", fields: {r: "v > 5"}}], + }, + cases: [ + [{v: 6}, {r: true}], + [{v: 5}, {r: false}], + [{v: "6"}, "!error"], + [{v: null}, "!error"], + [{}, "!error"], + [{v: true}, "!error"], + [{v: 5.0001}, {r: true}], + ], +} + +// --- Decision tables over a field of varying type ----------------------------------------- + +{ + name: "first-hit table: rules for every value type of one field", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["> 10", "'big number'"], + ["'gold'", "'gold'"], + ["true", "'true'"], + ["null", "'null'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{v: 11}, {r: "big number"}], + [{v: 10}, {r: "other"}], + [{v: "gold"}, {r: "gold"}], + [{v: "silver"}, {r: "other"}], + [{v: true}, {r: "true"}], + [{v: false}, {r: "other"}], + [{v: null}, {r: "null"}], + [{}, {r: "null"}], + [{v: [11]}, {r: "other"}], + [{v: {a: 1}}, {r: "other"}], + [{v: "11"}, {r: "other"}], + ], +} + +{ + name: "first-hit table: a numeric range column meeting strings and booleans", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["band"], rules: [ + ["[0..50)", "'low'"], + ["[50..80)", "'mid'"], + [">= 80", "'high'"], + ["", "'invalid'"], + ]}, + ], + }, + cases: [ + [{score: 0}, {band: "low"}], + [{score: 49.99}, {band: "low"}], + [{score: 50}, {band: "mid"}], + [{score: 80}, {band: "high"}], + [{score: -1}, {band: "invalid"}], + [{score: "90"}, {band: "invalid"}], + [{score: true}, {band: "invalid"}], + [{score: null}, {band: "invalid"}], + [{}, {band: "invalid"}], + [{score: [50]}, {band: "invalid"}], + ], +} + +{ + name: "first-hit table: a string enum column meeting numbers and missing rows", + graph: { + nodes: [ + {table: "t", inputs: ["tier"], outputs: ["discount"], rules: [ + ["'gold', 'platinum'", "0.2"], + ["'silver'", "0.1"], + ["", "0"], + ]}, + ], + }, + cases: [ + [{tier: "gold"}, {discount: 0.2}], + [{tier: "platinum"}, {discount: 0.2}], + [{tier: "silver"}, {discount: 0.1}], + [{tier: "Gold"}, {discount: 0}], + [{tier: 1}, {discount: 0}], + [{tier: false}, {discount: 0}], + [{tier: null}, {discount: 0}], + [{}, {discount: 0}], + [{tier: ["gold"]}, {discount: 0}], + ], +} + +{ + name: "first-hit table: two input columns of mixed types", + graph: { + nodes: [ + {table: "t", inputs: ["a", "b"], outputs: ["r"], rules: [ + ["> 0", "'x'", "'num-x'"], + ["'k'", "> 0", "'k-num'"], + ["true", "", "'bool'"], + ["", "", "'none'"], + ]}, + ], + }, + cases: [ + [{a: 1, b: "x"}, {r: "num-x"}], + [{a: 1, b: "y"}, {r: "none"}], + [{a: "k", b: 3}, {r: "k-num"}], + [{a: "k", b: "3"}, {r: "none"}], + [{a: true, b: 1}, {r: "bool"}], + [{a: true}, {r: "bool"}], + [{b: "x"}, {r: "none"}], + [{}, {r: "none"}], + [{a: 0, b: "x"}, {r: "none"}], + [{a: null, b: null}, {r: "none"}], + ], +} + +{ + name: "first-hit table: output cells echo the input of any type", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["out"], rules: [ + ["'copy'", "v"], + ["'type'", "type(v)"], + ["", "null"], + ]}, + ], + }, + cases: [ + [{kind: "copy", v: 1}, {out: 1}], + [{kind: "copy", v: "s"}, {out: "s"}], + [{kind: "copy", v: [1, 2]}, {out: [1, 2]}], + [{kind: "copy", v: {a: 1}}, {out: {a: 1}}], + [{kind: "copy", v: false}, {out: false}], + [{kind: "copy"}, {}], + [{kind: "type", v: "s"}, {out: "string"}], + [{kind: "type", v: 2}, {out: "number"}], + [{kind: "other", v: 2}, {}], + ], +} + +{ + name: "first-hit table: $-cells testing the type of the field", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["type($) == 'number' and $ > 0", "'positive'"], + ["type($) == 'string' and len($) > 0", "'text'"], + ["type($) == 'array'", "'list of ' + string(len($))"], + ["type($) == 'object'", "'object'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{v: 3}, {r: "positive"}], + [{v: -3}, {r: "other"}], + [{v: "a"}, {r: "text"}], + [{v: ""}, {r: "other"}], + [{v: [1, 2, 3]}, {r: "list of 3"}], + [{v: []}, {r: "list of 0"}], + [{v: {}}, {r: "object"}], + [{v: true}, {r: "other"}], + [{v: null}, {r: "other"}], + [{}, {r: "other"}], + ], +} + +{ + name: "collect table: rules for several types all evaluated per row", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["m"], rules: [ + ["> 0", "'positive'"], + ["'a', 'b'", "'letter'"], + ["true", "'true'"], + ["$ != null", "'present'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{v: 1}, [{m: "positive"}, {m: "present"}, {m: "any"}]], + [{v: "a"}, [{m: "letter"}, {m: "present"}, {m: "any"}]], + [{v: true}, [{m: "true"}, {m: "present"}, {m: "any"}]], + [{v: false}, [{m: "present"}, {m: "any"}]], + [{v: null}, [{m: "any"}]], + [{}, [{m: "any"}]], + [{v: [1]}, [{m: "present"}, {m: "any"}]], + [{v: -1}, [{m: "present"}, {m: "any"}]], + [{v: "c"}, [{m: "present"}, {m: "any"}]], + ], +} + +{ + name: "collect table with a typed output column fed values of other types", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [ + [">= 0", "n"], + ["", "'seen'"], + ]}, + ], + }, + cases: [ + [{n: 1}, [{v: 1}, {v: "seen"}]], + [{n: 0}, [{v: 0}, {v: "seen"}]], + [{n: -1}, [{v: "seen"}]], + [{n: "1"}, [{v: "seen"}]], + [{}, [{v: "seen"}]], + [{n: 2.75}, [{v: 2.75}, {v: "seen"}]], + ], +} + +{ + name: "per-column collect over a field of mixed types", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["first", "all[]"], rules: [ + ["> 1", "'gt1'", "'gt1'"], + ["> 0", "'gt0'", "'gt0'"], + ["'x'", "'x'", "'x'"], + ["", "'any'", "'any'"], + ]}, + ], + }, + cases: [ + [{v: 2}, {first: "gt1", all: ["gt1", "gt0", "any"]}], + [{v: 1}, {first: "gt0", all: ["gt0", "any"]}], + [{v: "x"}, {first: "x", all: ["x", "any"]}], + [{v: "y"}, {first: "any", all: ["any"]}], + [{v: true}, {first: "any", all: ["any"]}], + [{}, {first: "any", all: ["any"]}], + ], +} + +// --- Switches over a field of varying type ------------------------------------------------ + +{ + name: "first switch routing on the type of a field", + graph: { + nodes: [ + {switch: "s", when: ["type(v) == 'number'", "type(v) == 'string'", "type(v) == 'bool'", ""]}, + {expression: "num", fields: {r: "v * 2"}}, + {expression: "str", fields: {r: "upper(v)"}}, + {expression: "bool", fields: {r: "not v"}}, + {expression: "other", fields: {r: "type(v)"}}, + ], + edges: [ + "input -> s", + "s:0 -> num -> output", + "s:1 -> str -> output", + "s:2 -> bool -> output", + "s:3 -> other -> output", + ], + }, + cases: [ + [{v: 2}, {r: 4}], + [{v: "ab"}, {r: "AB"}], + [{v: true}, {r: false}], + [{v: false}, {r: true}], + [{v: null}, {r: "null"}], + [{}, {r: "null"}], + [{v: [1]}, {r: "array"}], + [{v: {a: 1}}, {r: "object"}], + [{v: -0.5}, {r: -1}], + [{v: ""}, {r: ""}], + ], +} + +{ + name: "first switch whose numeric condition errors on non-numbers falls through", + graph: { + nodes: [ + {switch: "s", when: ["v > 10", "v == 'vip'", ""]}, + {expression: "big", fields: {r: "'big'"}}, + {expression: "vip", fields: {r: "'vip'"}}, + {expression: "rest", fields: {r: "'rest'"}}, + ], + edges: ["input -> s", "s:0 -> big -> output", "s:1 -> vip -> output", "s:2 -> rest -> output"], + }, + cases: [ + [{v: 11}, {r: "big"}], + [{v: 10}, {r: "rest"}], + [{v: "vip"}, {r: "vip"}], + [{v: "11"}, {r: "rest"}], + [{v: true}, {r: "rest"}], + [{v: null}, {r: "rest"}], + [{}, {r: "rest"}], + [{v: [11]}, {r: "rest"}], + ], +} + +{ + name: "collect switch: branches for overlapping type tests", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["v != null", "isNumeric(string(v))", "len(string(v)) > 2"]}, + {expression: "a", fields: {present: "true"}}, + {expression: "b", fields: {numeric: "true"}}, + {expression: "c", fields: {long: "true"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output"], + }, + cases: [ + [{v: 1}, {present: true, numeric: true}], + [{v: 1234}, {present: true, numeric: true, long: true}], + [{v: "12"}, {present: true, numeric: true}], + [{v: "abc"}, {present: true, long: true}], + [{v: true}, {present: true, long: true}], + [{v: null}, {long: true}], + [{}, {long: true}], + [{v: ""}, {present: true}], + ], +} + +// --- Several fields changing type independently ------------------------------------------- + +{ + name: "two fields, each typed in some rows and mixed in others", + graph: { + nodes: [ + {expression: "e", fields: { + a: "type(x) == 'number' ? x : 0", + b: "type(y) == 'string' ? y : 'none'", + both: "type(x) + '/' + type(y)", + }}, + ], + }, + cases: [ + [{x: 1, y: "a"}, {a: 1, b: "a", both: "number/string"}], + [{x: 2, y: "b"}, {a: 2, b: "b", both: "number/string"}], + [{x: "1", y: 2}, {a: 0, b: "none", both: "string/number"}], + [{x: 3}, {a: 3, b: "none", both: "number/null"}], + [{y: "c"}, {a: 0, b: "c", both: "null/string"}], + [{x: true, y: false}, {a: 0, b: "none", both: "bool/bool"}], + [{x: [1], y: {}}, {a: 0, b: "none", both: "array/object"}], + [{}, {a: 0, b: "none", both: "null/null"}], + ], +} + +{ + name: "a chain whose second node reads a field the first node types differently per row", + graph: { + nodes: [ + {expression: "first", fields: {mid: "n > 0 ? n : 'neg'"}}, + {expression: "second", fields: {r: "type(mid) == 'number' ? mid + 1 : mid + '!'"}}, + ], + }, + cases: [ + [{n: 1}, {r: 2}], + [{n: -1}, {r: "neg!"}], + [{n: 5.5}, {r: 6.5}], + [{n: 0}, {r: "neg!"}], + [{n: 100}, {r: 101}], + ], +} + +{ + name: "a table producing a number in some rows and a string in others, read downstream", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "n * 10"], + ["0", "'zero'"], + ["", "false"], + ]}, + {expression: "e", fields: {t: "type(v)", v: "v"}}, + ], + }, + cases: [ + [{n: 1}, {t: "number", v: 10}], + [{n: 0}, {t: "string", v: "zero"}], + [{n: -1}, {t: "bool", v: false}], + [{n: 0.5}, {t: "number", v: 5}], + [{}, {t: "bool", v: false}], + [{n: "x"}, {t: "bool", v: false}], + ], +} + +{ + name: "arrays of uniform and mixed element types in one field", + graph: { + nodes: [ + {expression: "e", fields: { + n: "len(v)", + first: "v[0]", + types: "map(v, type(#))", + }}, + ], + }, + cases: [ + [{v: [1, 2, 3]}, {n: 3, first: 1, types: ["number", "number", "number"]}], + [{v: ["a", "b"]}, {n: 2, first: "a", types: ["string", "string"]}], + [{v: [true, false]}, {n: 2, first: true, types: ["bool", "bool"]}], + [{v: [1, "a", true, null]}, {n: 4, first: 1, types: ["number", "string", "bool", "null"]}], + [{v: [{a: 1}, [2]]}, {n: 2, first: {a: 1}, types: ["object", "array"]}], + [{v: []}, {n: 0, types: []}], + [{v: [0.5]}, {n: 1, first: 0.5, types: ["number"]}], + ], +} + +{ + name: "sum over arrays of numbers with empty and absent rows", + graph: { + nodes: [{expression: "e", fields: {s: "sum(v ?? [])", c: "count(v ?? [], # > 1)"}}], + }, + cases: [ + [{v: [1, 2, 3]}, {s: 6, c: 2}], + [{v: []}, {s: 0, c: 0}], + [{}, {s: 0, c: 0}], + [{v: null}, {s: 0, c: 0}], + [{v: [0.1, 0.2]}, {s: 0.3, c: 0}], + [{v: [-5, 10]}, {s: 5, c: 1}], + [{v: [100]}, {s: 100, c: 1}], + ], +} + +{ + name: "string arrays with membership tests, including empty strings and arrays", + graph: { + nodes: [{expression: "e", fields: {vip: "'vip' in (tags ?? [])", n: "len(tags ?? [])"}}], + }, + cases: [ + [{tags: ["vip", "new"]}, {vip: true, n: 2}], + [{tags: ["new"]}, {vip: false, n: 1}], + [{tags: []}, {vip: false, n: 0}], + [{tags: [""]}, {vip: false, n: 1}], + [{}, {vip: false, n: 0}], + [{tags: ["VIP"]}, {vip: false, n: 1}], + [{tags: ["a", "b", "c", "vip"]}, {vip: true, n: 4}], + ], +} + +{ + name: "boolean arrays: all/some/none across rows", + graph: { + nodes: [{expression: "e", fields: {all: "all(flags, #)", some: "some(flags, #)", none: "none(flags, #)"}}], + }, + cases: [ + [{flags: [true, true]}, {all: true, some: true, none: false}], + [{flags: [true, false]}, {all: false, some: true, none: false}], + [{flags: [false]}, {all: false, some: false, none: true}], + [{flags: []}, {all: true, some: false, none: true}], + [{flags: [false, false, false]}, {all: false, some: false, none: true}], + ], +} + +{ + name: "a field holding a date string in some rows and garbage in others", + graph: { + nodes: [{expression: "e", fields: {y: "isNumeric(v) ? -1 : dateString(date(v))"}}], + }, + cases: [ + [{v: "2024-01-15"}, {y: "2024-01-15 00:00:00"}], + [{v: "2024-02-29"}, {y: "2024-02-29 00:00:00"}], + [{v: "not a date"}, "!error"], + [{v: 5}, {y: -1}], + [{v: "2023-12-31"}, {y: "2023-12-31 00:00:00"}], + ], +} + +// --- Long suites: a mostly typed column with odd rows at irregular positions --------------- +// Cycled three times these cross the 64-row word boundary of the column bitmaps, and the +// stray rows sit at different offsets within each word. + +{ + name: "long: a mostly numeric column with strings, nulls and booleans scattered in", + graph: { + nodes: [ + {expression: "e", fields: {r: "type(v) == 'number' ? v * 3 : 'skip:' + type(v)"}}, + ], + }, + cases: [ + [{v: 1}, {r: 3}], + [{v: 2}, {r: 6}], + [{v: 3}, {r: 9}], + [{v: "4"}, {r: "skip:string"}], + [{v: 5}, {r: 15}], + [{v: 6.5}, {r: 19.5}], + [{v: 7}, {r: 21}], + [{v: null}, {r: "skip:null"}], + [{v: 9}, {r: 27}], + [{v: 10}, {r: 30}], + [{v: 11}, {r: 33}], + [{v: 12}, {r: 36}], + [{v: true}, {r: "skip:bool"}], + [{v: 14}, {r: 42}], + [{v: 15}, {r: 45}], + [{}, {r: "skip:null"}], + [{v: 17}, {r: 51}], + [{v: -18}, {r: -54}], + [{v: 19}, {r: 57}], + [{v: 20}, {r: 60}], + [{v: [21]}, {r: "skip:array"}], + [{v: 22}, {r: 66}], + [{v: 0.23}, {r: 0.69}], + ], +} + +{ + name: "long: a mostly numeric column feeding a table, erroring rows only where a string appears", + graph: { + nodes: [ + {expression: "e", passThrough: true, fields: {d: "v * 2"}}, + {table: "t", inputs: ["d"], outputs: ["band"], rules: [ + ["< 10", "'low'"], + ["[10..30]", "'mid'"], + ["", "'high'"], + ]}, + ], + }, + cases: [ + [{v: 1}, {band: "low"}], + [{v: 5}, {band: "mid"}], + [{v: 15}, {band: "mid"}], + [{v: 16}, {band: "high"}], + [{v: "x"}, "!error"], + [{v: 0}, {band: "low"}], + [{v: 4.99}, {band: "low"}], + [{v: 100}, {band: "high"}], + [{v: -100}, {band: "low"}], + [{v: 7}, {band: "mid"}], + [{v: null}, "!error"], + [{v: 8}, {band: "mid"}], + [{v: 2}, {band: "low"}], + [{v: 3}, {band: "low"}], + [{v: 9}, {band: "mid"}], + [{v: 10}, {band: "mid"}], + [{v: 11}, {band: "mid"}], + [{v: 12}, {band: "mid"}], + [{v: 13}, {band: "mid"}], + [{v: 14}, {band: "mid"}], + [{v: 6}, {band: "mid"}], + [{v: false}, "!error"], + ], +} + +{ + name: "long: a mostly string column with numbers and booleans scattered in, through a switch", + graph: { + nodes: [ + {switch: "s", when: ["startsWith(string(v), 'a')", "v == 1", ""]}, + {expression: "a", fields: {r: "'a:' + v"}}, + {expression: "one", fields: {r: "'one'"}}, + {expression: "rest", fields: {r: "'rest:' + string(v)"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> one -> output", "s:2 -> rest -> output"], + }, + cases: [ + [{v: "apple"}, {r: "a:apple"}], + [{v: "banana"}, {r: "rest:banana"}], + [{v: "avocado"}, {r: "a:avocado"}], + [{v: 1}, {r: "one"}], + [{v: "cherry"}, {r: "rest:cherry"}], + [{v: ""}, {r: "rest:"}], + [{v: "a"}, {r: "a:a"}], + [{v: "Apple"}, {r: "rest:Apple"}], + [{v: true}, {r: "rest:true"}], + [{v: "apricot"}, {r: "a:apricot"}], + [{v: 2}, {r: "rest:2"}], + [{v: "äpfel"}, {r: "rest:äpfel"}], + [{v: "almond"}, {r: "a:almond"}], + [{}, {r: "rest:null"}], + [{v: "date"}, {r: "rest:date"}], + [{v: "acorn"}, {r: "a:acorn"}], + [{v: "elder"}, {r: "rest:elder"}], + [{v: "fig"}, {r: "rest:fig"}], + [{v: "anise"}, {r: "a:anise"}], + [{v: null}, {r: "rest:null"}], + [{v: "grape"}, {r: "rest:grape"}], + [{v: "1"}, {r: "rest:1"}], + ], +} + +{ + name: "long: a boolean column with null and missing rows in a collect table", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["ok", "n"], outputs: ["r"], rules: [ + ["true", "", "'ok'"], + ["false", "", "'not ok'"], + ["", "> 2", "'big'"], + ["null", "", "'unknown'"], + ]}, + ], + }, + cases: [ + [{ok: true, n: 1}, [{r: "ok"}]], + [{ok: false, n: 3}, [{r: "not ok"}, {r: "big"}]], + [{ok: true, n: 3}, [{r: "ok"}, {r: "big"}]], + [{n: 3}, [{r: "big"}, {r: "unknown"}]], + [{ok: null, n: 0}, [{r: "unknown"}]], + [{ok: false}, [{r: "not ok"}]], + [{ok: true}, [{r: "ok"}]], + [{}, [{r: "unknown"}]], + [{ok: true, n: 2}, [{r: "ok"}]], + [{ok: false, n: 2.5}, [{r: "not ok"}, {r: "big"}]], + [{ok: true, n: 100}, [{r: "ok"}, {r: "big"}]], + [{ok: false, n: -1}, [{r: "not ok"}]], + [{ok: true, n: "9"}, [{r: "ok"}]], + [{ok: "true", n: 1}, []], + [{ok: 1, n: 5}, [{r: "big"}]], + [{ok: false, n: 0}, [{r: "not ok"}]], + [{ok: true, n: 0}, [{r: "ok"}]], + [{ok: false, n: 99}, [{r: "not ok"}, {r: "big"}]], + [{ok: true, n: 3}, [{r: "ok"}, {r: "big"}]], + [{ok: null}, [{r: "unknown"}]], + [{ok: true, n: 4}, [{r: "ok"}, {r: "big"}]], + [{ok: false, n: 4}, [{r: "not ok"}, {r: "big"}]], + ], +} + +// --- Access on values of the wrong shape --------------------------------------------------- + +{ + name: "member and index access on a field that is a scalar in some rows", + graph: { + nodes: [{expression: "e", fields: {x: "v.x", i: "v[0]"}}], + }, + cases: [ + [{v: {x: 1}}, {x: 1}], + [{v: [9, 8]}, {i: 9}], + [{v: 5}, {}], + [{v: "str"}, {i: "s"}], + [{v: true}, {}], + [{v: null}, {}], + [{}, {}], + [{v: []}, {}], + [{v: ""}, {}], + ], +} + +{ + name: "contains() on a field that is a string in some rows and an array in others", + graph: { + nodes: [{expression: "e", fields: {r: "contains(v, 'a')"}}], + }, + cases: [ + [{v: "banana"}, {r: true}], + [{v: "xyz"}, {r: false}], + [{v: ["a", "b"]}, {r: true}], + [{v: ["b"]}, {r: false}], + [{v: []}, {r: false}], + [{v: ""}, {r: false}], + [{v: "A"}, {r: false}], + [{v: [1, "a"]}, {r: true}], + ], +} + +{ + name: "string ordering mixed with number ordering in one field", + graph: { + nodes: [ + {table: "t", inputs: ["v"], outputs: ["r"], rules: [ + ["$ == 'm'", "'m'"], + ["type($) == 'string' and $ < 'm'", "'before m'"], + ["type($) == 'string' and $ > 'm'", "'after m'"], + ["type($) == 'number' and $ < 0", "'negative'"], + ["", "'rest'"], + ]}, + ], + }, + cases: [ + [{v: "a"}, {r: "rest"}, "question: strings have no ordering in the expression language, so the cell errors and the rule falls through"], + [{v: "m"}, {r: "m"}], + [{v: "z"}, {r: "rest"}, "question: strings have no ordering in the expression language, so the cell errors and the rule falls through"], + [{v: "M"}, {r: "rest"}, "question: strings have no ordering in the expression language, so the cell errors and the rule falls through"], + [{v: -1}, {r: "negative"}], + [{v: 1}, {r: "rest"}], + [{v: "ma"}, {r: "rest"}, "question: strings have no ordering in the expression language, so the cell errors and the rule falls through"], + [{}, {r: "rest"}], + ], +} + +{ + name: "negative zero, tiny and huge decimals in one column", + graph: { + nodes: [{expression: "e", fields: {zero: "v == 0", pos: "v > 0", s: "v + 0"}}], + }, + cases: [ + [{v: 0}, {zero: true, pos: false, s: 0}], + [{v: -0}, {zero: true, pos: false, s: 0}], + [{v: 0.0000000000000000000000000001}, {zero: false, pos: true, s: 0.0000000000000000000000000001}], + [{v: -0.0000000000000000000000000001}, {zero: false, pos: false, s: -0.0000000000000000000000000001}], + [{v: 79228162514264337593543950335}, {zero: false, pos: true, s: 79228162514264337593543950335}], + [{v: -79228162514264337593543950335}, {zero: false, pos: false, s: -79228162514264337593543950335}], + [{v: 1.5}, {zero: false, pos: true, s: 1.5}], + ], +} + +{ + name: "an output column whose type differs per rule, collected", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "n"], + ["> 1", "'two+'"], + ["> 2", "true"], + ["> 3", "[n]"], + ["> 4", "{n: n}"], + ]}, + ], + }, + cases: [ + [{n: 0}, []], + [{n: 1}, [{v: 1}]], + [{n: 2}, [{v: 2}, {v: "two+"}]], + [{n: 3}, [{v: 3}, {v: "two+"}, {v: true}]], + [{n: 4}, [{v: 4}, {v: "two+"}, {v: true}, {v: [4]}]], + [{n: 5}, [{v: 5}, {v: "two+"}, {v: true}, {v: [5]}, {v: {n: 5}}]], + [{}, []], + ], +} + +// --- Whole inputs that are not objects ----------------------------------------------------- + +{ + name: "the whole input is a scalar, an array or null in some rows", + graph: { + nodes: [{expression: "e", fields: {t: "type(v)", v: "v"}}], + }, + cases: [ + [{v: 1}, {t: "number", v: 1}], + [5, {t: "null"}], + ["s", {t: "null"}], + [[1, 2], "!error", "question: with an array request the expression environment is the array, and reading a field of it errors instead of giving null"], + [null, {t: "null"}], + [true, {t: "null"}], + [{v: "x"}, {t: "string", v: "x"}], + [{}, {t: "null"}], + ], +} + +{ + name: "a non-object input passes straight through an empty graph", + graph: {}, + cases: [ + [{a: 1}, {a: 1}], + [5, {}, "question: a scalar request is replaced by an empty object, as in 01-input-output"], + ["s", {}, "question: a scalar request is replaced by an empty object, as in 01-input-output"], + [[1, {a: 2}], [1, {a: 2}]], + [true, {}, "question: a scalar request is replaced by an empty object, as in 01-input-output"], + [{b: [1]}, {b: [1]}], + ], +} + +// --- Date strings in a text column -------------------------------------------------------- + +{ + name: "date comparisons on a text column with unparseable and absent rows", + graph: { + nodes: [ + {table: "t", inputs: ["since"], outputs: ["r"], rules: [ + ["d($) < d('2024-01-01')", "'old'"], + ["d($) >= d('2024-01-01')", "'new'"], + ["", "'unknown'"], + ]}, + ], + }, + cases: [ + [{since: "2023-06-01"}, {r: "old"}], + [{since: "2024-01-01"}, {r: "new"}], + [{since: "2025-03-20T10:00:00Z"}, {r: "new"}], + [{since: "garbage"}, {r: "old"}, "question: an invalid or null date orders before every valid date instead of erroring (see the expression spec), so the cell matches"], + [{since: ""}, {r: "old"}, "question: an invalid or null date orders before every valid date instead of erroring (see the expression spec), so the cell matches"], + [{}, {r: "old"}, "question: an invalid or null date orders before every valid date instead of erroring (see the expression spec), so the cell matches"], + [{since: "2023-12-31T23:59:59Z"}, {r: "old"}], + [{since: 1700000000}, {r: "old"}], + ], +} + +// --- $nodes across rows that ran different nodes ------------------------------------------- + +{ + name: "$nodes of a branch that ran for some rows and not for others", + graph: { + nodes: [ + {switch: "s", when: ["n > 0", ""]}, + {expression: "pos", fields: {v: "n * 2"}}, + {expression: "neg", fields: {v: "'neg'"}}, + {expression: "join", fields: {fromPos: "$nodes.pos.v", fromNeg: "$nodes.neg.v", t: "type($nodes.pos)"}}, + ], + edges: ["input -> s", "s:0 -> pos -> join", "s:1 -> neg -> join", "join -> output"], + }, + cases: [ + [{n: 1}, {fromPos: 2, t: "object"}], + [{n: -1}, {fromNeg: "neg", t: "null"}], + [{n: 2.5}, {fromPos: 5, t: "object"}], + [{}, {fromNeg: "neg", t: "null"}], + [{n: 0}, {fromNeg: "neg", t: "null"}], + [{n: "x"}, {fromNeg: "neg", t: "null"}], + [{n: 100}, {fromPos: 200, t: "object"}], + ], +} + +{ + name: "collect switch: one key written with a different type by each taken branch", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a == true", "b == true"]}, + {expression: "ea", fields: {v: "1", fromA: "true"}}, + {expression: "eb", fields: {v: "'one'", fromB: "true"}}, + ], + edges: ["input -> s", "s:0 -> ea -> output", "s:1 -> eb -> output"], + }, + cases: [ + [{a: true}, {v: 1, fromA: true}], + [{b: true}, {v: "one", fromB: true}], + [{a: true, b: true}, {v: 1, fromA: true, fromB: true}], + [{}, {}], + [{a: false, b: true}, {v: "one", fromB: true}], + [{a: true, b: false}, {v: 1, fromA: true}], + ], +} + +{ + name: "an expression field referencing earlier fields of varying type through $", + graph: { + nodes: [{expression: "e", fields: [ + ["k", "type(v) == 'number' ? v : len(string(v))"], + ["d", "$.k * 2"], + ["s", "string($.d) + ':' + type(v)"], + ]}], + }, + cases: [ + [{v: 3}, {k: 3, d: 6, s: "6:number"}], + [{v: "abcd"}, {k: 4, d: 8, s: "8:string"}], + [{v: true}, {k: 4, d: 8, s: "8:bool"}], + [{}, {k: 4, d: 8, s: "8:null"}], + [{v: 0.5}, {k: 0.5, d: 1, s: "1.0:number"}], + [{v: ""}, {k: 0, d: 0, s: "0:string"}], + ], +} + +// --- Arrays of one element type with empty and missing rows -------------------------------- +// When every present cell of a field is an array of strings, numbers or booleans, the list +// layout stores the elements in one shared child buffer with per-row offsets. + +{ + name: "lists of strings: indexing, slicing and membership per row", + graph: { + nodes: [{expression: "e", fields: { + first: "tags[0]", + last: "len(tags) > 0 ? tags[len(tags) - 1] : null", + rest: "tags[1:]", + vip: "'vip' in tags", + n: "len(tags)", + }}], + }, + cases: [ + [{tags: ["vip", "new"]}, {first: "vip", last: "new", rest: ["new"], vip: true, n: 2}], + [{tags: ["a"]}, {first: "a", last: "a", rest: [], vip: false, n: 1}], + [{tags: []}, {rest: [], vip: false, n: 0}, "bug: an open-ended slice of an empty array errors (implicit end len-1 is -1), as in the expression spec"], + [{tags: ["", "vip", ""]}, {first: "", last: "", rest: ["vip", ""], vip: true, n: 3}], + [{tags: ["żółw", "日本"]}, {first: "żółw", last: "日本", rest: ["日本"], vip: false, n: 2}], + [{tags: ["x", "y", "z", "vip", "w"]}, {first: "x", last: "w", rest: ["y", "z", "vip", "w"], vip: true, n: 5}], + ], +} + +{ + name: "lists of strings, missing in some rows, through a collect table", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["tags"], outputs: ["r"], rules: [ + ["'vip' in $", "'vip'"], + ["len($) == 0", "'empty'"], + ["some($, startsWith(#, 'x'))", "'x-tag'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{tags: ["vip"]}, [{r: "vip"}, {r: "any"}]], + [{tags: []}, [{r: "empty"}, {r: "any"}]], + [{tags: ["xa", "vip"]}, [{r: "vip"}, {r: "x-tag"}, {r: "any"}]], + [{tags: ["b"]}, [{r: "any"}]], + [{}, [{r: "any"}]], + [{tags: ["x"]}, [{r: "x-tag"}, {r: "any"}]], + ], +} + +{ + name: "lists of numbers: aggregates and element access per row", + graph: { + nodes: [{expression: "e", fields: { + s: "sum(xs)", + mx: "max(xs)", + first: "xs[0]", + doubled: "map(xs, # * 2)", + big: "filter(xs, # > 10)", + has5: "5 in xs", + }}], + }, + cases: [ + [{xs: [1, 2, 3]}, {s: 6, mx: 3, first: 1, doubled: [2, 4, 6], big: [], has5: false}], + [{xs: [5, 15.5]}, {s: 20.5, mx: 15.5, first: 5, doubled: [10, 31], big: [15.5], has5: true}], + [{xs: [-1.25, 0.001]}, {s: -1.249, mx: 0.001, first: -1.25, doubled: [-2.5, 0.002], big: [], has5: false}], + [{xs: [100]}, {s: 100, mx: 100, first: 100, doubled: [200], big: [100], has5: false}], + [{xs: [5.0, 5]}, {s: 10, mx: 5, first: 5, doubled: [10, 10], big: [], has5: true}], + [{xs: [0, 0, 0, 0, 0, 0, 0, 0, 11]}, {s: 11, mx: 11, first: 0, doubled: [0, 0, 0, 0, 0, 0, 0, 0, 22], big: [11], has5: false}], + ], +} + +{ + name: "lists of numbers with empty and missing rows, defaulted", + graph: { + nodes: [{expression: "e", fields: {s: "sum(xs ?? [])", n: "len(xs ?? [])", avg: "len(xs ?? []) > 0 ? avg(xs) : null"}}], + }, + cases: [ + [{xs: [2, 4]}, {s: 6, n: 2, avg: 3}], + [{xs: []}, {s: 0, n: 0}], + [{}, {s: 0, n: 0}], + [{xs: [1]}, {s: 1, n: 1, avg: 1}], + [{xs: null}, {s: 0, n: 0}], + [{xs: [0.1, 0.2, 0.3]}, {s: 0.6, n: 3, avg: 0.2}], + [{xs: [12345678901234567890, 1]}, {s: 12345678901234567891, n: 2, avg: 6172839450617283945.5}], + ], +} + +{ + name: "lists of booleans with empty and missing rows", + graph: { + nodes: [{expression: "e", fields: {any: "some(flags ?? [], #)", n: "count(flags ?? [], #)", first: "(flags ?? [])[0]"}}], + }, + cases: [ + [{flags: [true, false]}, {any: true, n: 1, first: true}], + [{flags: [false, false]}, {any: false, n: 0, first: false}], + [{flags: []}, {any: false, n: 0}], + [{}, {any: false, n: 0}], + [{flags: [false, false, true, true, true]}, {any: true, n: 3, first: false}], + [{flags: [true]}, {any: true, n: 1, first: true}], + ], +} + +{ + name: "a list column copied out unchanged, next to a scalar column", + graph: { + nodes: [{expression: "e", passThrough: true, fields: {n: "len(xs)"}}], + }, + cases: [ + [{xs: [1, 2], k: "a"}, {xs: [1, 2], k: "a", n: 2}], + [{xs: [], k: "b"}, {xs: [], k: "b", n: 0}], + [{xs: [0.5]}, {xs: [0.5], n: 1}], + [{xs: [3, 3, 3], k: ""}, {xs: [3, 3, 3], k: "", n: 3}], + ], +} + +{ + name: "a list field that holds numbers in some rows and strings in others", + graph: { + nodes: [{expression: "e", fields: {t: "map(xs, type(#))", n: "len(xs)"}}], + }, + cases: [ + [{xs: [1, 2]}, {t: ["number", "number"], n: 2}], + [{xs: ["a"]}, {t: ["string"], n: 1}], + [{xs: []}, {t: [], n: 0}], + [{xs: [true]}, {t: ["bool"], n: 1}], + [{xs: [1, "a"]}, {t: ["number", "string"], n: 2}], + ], +} diff --git a/core/engine/tests/spec/graph/49-rows-nested-shapes.json5 b/core/engine/tests/spec/graph/49-rows-nested-shapes.json5 new file mode 100644 index 00000000..82707fbf --- /dev/null +++ b/core/engine/tests/spec/graph/49-rows-nested-shapes.json5 @@ -0,0 +1,628 @@ +// Rows of one suite whose nested shape changes from case to case. +// +// In columnar mode nested objects are flattened into dotted columns (`customer.address.city`) +// and absent sub-objects become absent cells, while arrays (and arrays of objects) stay whole +// values. These suites vary which sub-objects exist, at which depth a key sits, and which keys +// the objects inside arrays carry, so the compiled engine has to rebuild each row's shape from +// sparse columns. Expected results are single-row semantics: missing intermediate objects read +// as null, nothing is invented in the output, and a row's shape never leaks into another row. + +// --- Optional sub-objects ------------------------------------------------------------------- + +{ + name: "a deep read with a default, the chain cut at every depth", + graph: { + nodes: [{expression: "e", fields: {r: "a.b.c.d ?? 'none'"}}], + }, + cases: [ + [{a: {b: {c: {d: 1}}}}, {r: 1}], + [{a: {b: {c: {d: "x"}}}}, {r: "x"}], + [{a: {b: {c: {e: 1}}}}, {r: "none"}], + [{a: {b: {c: {}}}}, {r: "none"}], + [{a: {b: {}}}, {r: "none"}], + [{a: {}}, {r: "none"}], + [{}, {r: "none"}], + [{a: {b: {c: {d: null}}}}, {r: "none"}], + [{a: {b: null}}, {r: "none"}], + [{a: {b: {c: {d: false}}}}, {r: false}], + [{a: {b: {c: {d: 0}}}}, {r: 0}], + ], +} + +{ + name: "an optional address read with fallbacks at two depths", + graph: { + nodes: [{expression: "e", fields: {city: "customer.address.city ?? customer.city ?? 'unknown'"}}], + }, + cases: [ + [{customer: {address: {city: "Berlin"}}}, {city: "Berlin"}], + [{customer: {city: "Paris"}}, {city: "Paris"}], + [{customer: {address: {city: "Rome"}, city: "Paris"}}, {city: "Rome"}], + [{customer: {address: {zip: "1000"}, city: "Oslo"}}, {city: "Oslo"}], + [{customer: {address: {}}}, {city: "unknown"}], + [{customer: {}}, {city: "unknown"}], + [{}, {city: "unknown"}], + [{customer: {address: {city: ""}}}, {city: ""}], + ], +} + +{ + name: "sub-object presence tested directly", + graph: { + nodes: [{expression: "e", fields: { + hasProfile: "customer.profile != null", + profileType: "type(customer.profile)", + age: "customer.profile.age ?? -1", + }}], + }, + cases: [ + [{customer: {profile: {age: 30}}}, {hasProfile: true, profileType: "object", age: 30}], + [{customer: {profile: {}}}, {hasProfile: true, profileType: "object", age: -1}], + [{customer: {profile: null}}, {hasProfile: false, profileType: "null", age: -1}], + [{customer: {}}, {hasProfile: false, profileType: "null", age: -1}], + [{customer: {profile: {age: 0, name: "x"}}}, {hasProfile: true, profileType: "object", age: 0}], + [{}, {hasProfile: false, profileType: "null", age: -1}], + [{customer: {profile: {age: 17.5}}}, {hasProfile: true, profileType: "object", age: 17.5}], + ], +} + +{ + name: "eight levels deep, present in some rows only", + graph: { + nodes: [{expression: "e", fields: {v: "l1.l2.l3.l4.l5.l6.l7.l8", n: "(l1.l2.l3.l4.l5.l6.l7.l8 ?? 0) + 1"}}], + }, + cases: [ + [{l1: {l2: {l3: {l4: {l5: {l6: {l7: {l8: 41}}}}}}}}, {v: 41, n: 42}], + [{l1: {l2: {l3: {l4: {l5: {l6: {l7: {}}}}}}}}, {n: 1}], + [{l1: {l2: {l3: {}}}}, {n: 1}], + [{l1: {l2: {l3: {l4: {l5: {l6: {l7: {l8: -1}}}}}}}}, {v: -1, n: 0}], + [{}, {n: 1}], + [{l1: {l2: {l3: {l4: {l5: {l6: {l7: {l8: 0.5}}}}}}}}, {v: 0.5, n: 1.5}], + ], +} + +{ + name: "siblings in a nested object appear in different rows", + graph: { + nodes: [{expression: "e", fields: { + sum: "(o.a ?? 0) + (o.b ?? 0) + (o.c ?? 0)", + present: "len(filter(['a', 'b', 'c'], o[#] != null))", + }}], + }, + cases: [ + [{o: {a: 1}}, {sum: 1, present: 1}], + [{o: {b: 2}}, {sum: 2, present: 1}], + [{o: {c: 3}}, {sum: 3, present: 1}], + [{o: {a: 1, b: 2}}, {sum: 3, present: 2}], + [{o: {a: 1, b: 2, c: 3}}, {sum: 6, present: 3}], + [{o: {}}, {sum: 0, present: 0}], + [{o: {d: 4}}, {sum: 0, present: 0}], + [{}, {sum: 0, present: 0}], + ], +} + +// --- A path that is an object in some rows and a scalar in others -------------------------- + +{ + name: "a key that is a scalar first, then an object", + graph: { + nodes: [{expression: "e", fields: {t: "type(p)", x: "p.x ?? p"}}], + }, + cases: [ + [{p: 1}, {t: "number", x: 1}], + [{p: "s"}, {t: "string", x: "s"}], + [{p: {x: 2}}, {t: "object", x: 2}], + [{p: {y: 3}}, {t: "object", x: {y: 3}}], + [{p: true}, {t: "bool", x: true}], + [{}, {t: "null"}], + ], +} + +{ + name: "a key that is an object first, then a scalar", + graph: { + nodes: [{expression: "e", fields: {t: "type(p)", x: "p.x ?? p"}}], + }, + cases: [ + [{p: {x: 2}}, {t: "object", x: 2}], + [{p: {x: {y: 1}}}, {t: "object", x: {y: 1}}], + [{p: 1}, {t: "number", x: 1}], + [{p: "s"}, {t: "string", x: "s"}], + [{p: [1]}, {t: "array", x: [1]}], + [{p: {}}, {t: "object", x: {}}], + ], +} + +{ + name: "pass-through keeps every row's own nested shape", + graph: { + nodes: [{expression: "e", passThrough: true, fields: {seen: "true"}}], + }, + cases: [ + [{a: {b: {c: 1}}}, {a: {b: {c: 1}}, seen: true}], + [{a: {b: 2}}, {a: {b: 2}, seen: true}], + [{a: 3}, {a: 3, seen: true}], + [{a: {d: [1, {e: 2}]}}, {a: {d: [1, {e: 2}]}, seen: true}], + [{x: {y: {z: "deep"}}}, {x: {y: {z: "deep"}}, seen: true}], + [{}, {seen: true}], + [{a: {b: {c: 1, c2: 2}, b2: true}}, {a: {b: {c: 1, c2: 2}, b2: true}, seen: true}], + ], +} + +{ + name: "dotted writes merge into a nested object present in some rows only", + graph: { + nodes: [{expression: "e", passThrough: true, fields: {"order.total": "(order.price ?? 0) * (order.qty ?? 1)", "order.meta.checked": "true"}}], + }, + cases: [ + [{order: {price: 10, qty: 2}}, {order: {price: 10, qty: 2, total: 20, meta: {checked: true}}}], + [{order: {price: 5}}, {order: {price: 5, total: 5, meta: {checked: true}}}], + [{order: {qty: 3, meta: {source: "web"}}}, {order: {qty: 3, total: 0, meta: {source: "web", checked: true}}}], + [{}, {order: {total: 0, meta: {checked: true}}}], + [{order: {}}, {order: {total: 0, meta: {checked: true}}}], + [{order: {price: 1.5, qty: 4, meta: {checked: false}}}, {order: {price: 1.5, qty: 4, total: 6, meta: {checked: true}}}], + ], +} + +{ + name: "nested writes into new paths, values absent in some rows", + graph: { + nodes: [{expression: "e", fields: {"out.a.b": "x", "out.a.c": "y", "out.d": "x ?? y"}}], + }, + cases: [ + [{x: 1, y: 2}, {out: {a: {b: 1, c: 2}, d: 1}}], + [{x: 1}, {out: {a: {b: 1, c: null}, d: 1}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{y: 2}, {out: {a: {b: null, c: 2}, d: 2}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{x: "s", y: [1]}, {out: {a: {b: "s", c: [1]}, d: "s"}}], + [{x: {deep: 1}}, {out: {a: {b: {deep: 1}, c: null}, d: {deep: 1}}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + ], +} + +// --- Tables over dotted fields with partial shapes ----------------------------------------- + +{ + name: "table inputs on dotted fields where sub-objects come and go", + graph: { + nodes: [ + {table: "t", inputs: ["customer.profile.age", "customer.country"], outputs: ["r"], rules: [ + [">= 18", "'US'", "'us-adult'"], + [">= 18", "", "'adult'"], + ["< 18", "", "'minor'"], + ["", "'US'", "'us-unknown-age'"], + ["", "", "'unknown'"], + ]}, + ], + }, + cases: [ + [{customer: {profile: {age: 20}, country: "US"}}, {r: "us-adult"}], + [{customer: {profile: {age: 20}, country: "DE"}}, {r: "adult"}], + [{customer: {profile: {age: 20}}}, {r: "adult"}], + [{customer: {profile: {age: 5}, country: "US"}}, {r: "minor"}], + [{customer: {profile: {}, country: "US"}}, {r: "us-unknown-age"}], + [{customer: {country: "US"}}, {r: "us-unknown-age"}], + [{customer: {}}, {r: "unknown"}], + [{}, {r: "unknown"}], + [{customer: {profile: {age: "20"}, country: "US"}}, {r: "us-unknown-age"}], + [{customer: {profile: {age: 18, extra: {x: 1}}, country: "FR"}}, {r: "adult"}], + ], +} + +{ + name: "table outputs to nested paths, some cells null per rule", + graph: { + nodes: [ + {table: "t", inputs: ["score"], outputs: ["result.grade", "result.detail.reason", "result.flags.review"], rules: [ + [">= 90", "'A'", "null", "false"], + [">= 50", "'B'", "'average'", "null"], + ["", "'F'", "'failed'", "true"], + ]}, + ], + }, + cases: [ + [{score: 95}, {result: {grade: "A", detail: {reason: null}, flags: {review: false}}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{score: 60}, {result: {grade: "B", detail: {reason: "average"}, flags: {review: null}}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{score: 10}, {result: {grade: "F", detail: {reason: "failed"}, flags: {review: true}}}], + [{}, {result: {grade: "F", detail: {reason: "failed"}, flags: {review: true}}}], + [{score: 90}, {result: {grade: "A", detail: {reason: null}, flags: {review: false}}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + ], +} + +{ + name: "pass-through table writing beside nested input objects of varying shape", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["applicant.score"], outputs: ["applicant.risk"], rules: [ + [">= 700", "'low'"], + ["", "'high'"], + ]}, + ], + }, + cases: [ + [{applicant: {score: 750, name: "a"}}, {applicant: {score: 750, name: "a", risk: "low"}}], + [{applicant: {score: 600}}, {applicant: {score: 600, risk: "high"}}], + [{applicant: {name: "b", address: {city: "x"}}}, {applicant: {name: "b", address: {city: "x"}, risk: "high"}}], + [{}, {applicant: {risk: "high"}}], + [{applicant: {score: 700, risk: "old"}}, {applicant: {score: 700, risk: "low"}}], + [{other: 1}, {other: 1, applicant: {risk: "high"}}], + ], +} + +{ + name: "collect table over nested arrays of objects, rules testing items", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["order.items"], outputs: ["flag"], rules: [ + ["some($, #.price > 100)", "'expensive'"], + ["some($, #.fragile == true)", "'fragile'"], + ["len($) == 0", "'empty'"], + ["all($, #.sku != null)", "'all-sku'"], + ]}, + ], + }, + cases: [ + [{order: {items: [{price: 150, sku: "a"}]}}, [{flag: "expensive"}, {flag: "all-sku"}]], + [{order: {items: [{price: 5, fragile: true}]}}, [{flag: "fragile"}]], + [{order: {items: [{price: 5, sku: "a"}, {fragile: true, sku: "b"}, {price: 101}]}}, [{flag: "fragile"}], "question: `#.price > 100` errors on the item without a price before reaching the 101 item, so the whole `some` cell fails and the expensive rule is skipped"], + [{order: {items: []}}, [{flag: "empty"}, {flag: "all-sku"}]], + [{order: {items: [{sku: "z"}]}}, [{flag: "all-sku"}]], + [{order: {items: [{}]}}, []], + [{order: {}}, []], + ], +} + +// --- Arrays of objects with differing keys -------------------------------------------------- + +{ + name: "aggregates over items whose keys differ per item and per row", + graph: { + nodes: [{expression: "e", fields: { + total: "sum(map(items, (#.price ?? 0) * (#.qty ?? 1)))", + priced: "count(items, #.price != null)", + skus: "map(filter(items, #.sku != null), #.sku)", + }}], + }, + cases: [ + [{items: [{price: 2, qty: 3, sku: "a"}, {price: 1}]}, {total: 7, priced: 2, skus: ["a"]}], + [{items: [{sku: "x"}, {sku: "y", price: 10}]}, {total: 10, priced: 1, skus: ["x", "y"]}], + [{items: [{qty: 5}]}, {total: 0, priced: 0, skus: []}], + [{items: []}, {total: 0, priced: 0, skus: []}], + [{items: [{price: 0.1, qty: 3}, {price: 0.2, qty: 1, extra: {nested: true}}]}, {total: 0.5, priced: 2, skus: []}], + [{items: [{price: 1, sku: null}, {price: 2, sku: "b"}]}, {total: 3, priced: 2, skus: ["b"]}], + ], +} + +{ + name: "items carrying a key at different depths", + graph: { + nodes: [{expression: "e", fields: {codes: "map(items, #.code ?? #.meta.code ?? #.meta.inner.code ?? 'none')"}}], + }, + cases: [ + [{items: [{code: "a"}, {meta: {code: "b"}}, {meta: {inner: {code: "c"}}}]}, {codes: ["a", "b", "c"]}], + [{items: [{meta: {}}, {meta: {inner: {}}}, {}]}, {codes: ["none", "none", "none"]}], + [{items: [{code: "top", meta: {code: "nested"}}]}, {codes: ["top"]}], + [{items: []}, {codes: []}], + [{items: [{meta: {inner: {code: 1}}}, {code: true}]}, {codes: [1, true]}], + ], +} + +{ + name: "an array field holding objects in some rows and scalars in others", + graph: { + nodes: [{expression: "e", fields: {types: "map(xs, type(#))", n: "len(xs)"}}], + }, + cases: [ + [{xs: [{a: 1}, {b: 2}]}, {types: ["object", "object"], n: 2}], + [{xs: [1, 2, 3]}, {types: ["number", "number", "number"], n: 3}], + [{xs: ["a"]}, {types: ["string"], n: 1}], + [{xs: [{a: 1}, 1, "s", null, [2]]}, {types: ["object", "number", "string", "null", "array"], n: 5}], + [{xs: []}, {types: [], n: 0}], + [{xs: [[], [[]]]}, {types: ["array", "array"], n: 2}], + ], +} + +{ + name: "arrays of arrays of varying length and depth", + graph: { + nodes: [{expression: "e", fields: {lens: "map(m, len(#))", flat: "flatten(m)"}}], + }, + cases: [ + [{m: [[1, 2], [3]]}, {lens: [2, 1], flat: [1, 2, 3]}], + [{m: [[], [1]]}, {lens: [0, 1], flat: [1]}], + [{m: []}, {lens: [], flat: []}], + [{m: [["a"], ["b", "c"]]}, {lens: [1, 2], flat: ["a", "b", "c"]}], + [{m: [[[1]], [2]]}, {lens: [1, 1], flat: [[1], 2]}], + ], +} + +{ + name: "loop over items whose keys differ, results per item", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: { + name: "name ?? 'anon'", + cost: "(price ?? 0) * (qty ?? 1)", + "tags.first": "tags[0]", + }}], + }, + cases: [ + [{items: [{name: "a", price: 2, qty: 2}, {price: 5}]}, {out: [{name: "a", cost: 4, tags: {first: null}}, {name: "anon", cost: 5, tags: {first: null}}]}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{items: [{tags: ["x", "y"]}, {name: "b", tags: []}]}, {out: [{name: "anon", cost: 0, tags: {first: "x"}}, {name: "b", cost: 0, tags: {first: null}}]}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{items: []}, {out: []}], + [{items: [{name: "c", price: 1.25, qty: 4, extra: {deep: 1}}]}, {out: [{name: "c", cost: 5, tags: {first: null}}]}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + ], +} + +{ + name: "loop over a nested array present in some rows only", + graph: { + nodes: [{expression: "each", inputField: "order.lines", outputPath: "lines", executionMode: "loop", fields: {sku: "upper(sku ?? 'none')"}}], + }, + cases: [ + [{order: {lines: [{sku: "a"}, {sku: "b"}]}}, {lines: [{sku: "A"}, {sku: "B"}]}], + [{order: {lines: [{}]}}, {lines: [{sku: "NONE"}]}], + [{order: {lines: []}}, {lines: []}], + [{order: {id: 1}}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "table loop over items whose keys differ", + graph: { + nodes: [{table: "t", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["kind", "weight"], outputs: ["cls"], rules: [ + ["'box'", "> 10", "'heavy-box'"], + ["'box'", "", "'box'"], + ["", "> 10", "'heavy'"], + ["", "", "'other'"], + ]}], + }, + cases: [ + [{items: [{kind: "box", weight: 20}, {kind: "box"}, {weight: 11}, {}]}, {out: [{cls: "heavy-box"}, {cls: "box"}, {cls: "heavy"}, {cls: "other"}]}], + [{items: [{kind: "bag", weight: 1, color: "red"}]}, {out: [{cls: "other"}]}], + [{items: []}, {out: []}], + [{items: [{kind: "box", weight: "20"}]}, {out: [{cls: "box"}]}], + ], +} + +// --- Nested shapes across node boundaries ------------------------------------------------- + +{ + name: "$nodes reads nested output whose shape depends on the row", + graph: { + nodes: [ + {expression: "a", fields: {"res.kind": "kind", "res.detail.n": "n"}}, + {expression: "b", fields: { + kind: "$nodes.a.res.kind ?? 'none'", + n: "$nodes.a.res.detail.n ?? -1", + hasDetail: "$nodes.a.res.detail != null", + }}, + ], + }, + cases: [ + [{kind: "x", n: 1}, {kind: "x", n: 1, hasDetail: true}], + [{kind: "y"}, {kind: "y", n: -1, hasDetail: true}, "question: node a wrote `res.detail.n` as a nested null, so `res.detail` exists as {n: null}"], + [{n: 2}, {kind: "none", n: 2, hasDetail: true}], + [{}, {kind: "none", n: -1, hasDetail: true}, "question: node a wrote `res.detail.n` as a nested null, so `res.detail` exists as {n: null}"], + [{kind: {nested: true}, n: [1]}, {kind: {nested: true}, n: [1], hasDetail: true}], + ], +} + +{ + name: "a sub-decision receiving and returning nested optional objects", + decisions: { + child: {nodes: [{expression: "c", fields: {"out.name": "user.name ?? 'anon'", "out.city": "user.address.city"}}]}, + }, + graph: { + nodes: [{decision: "call", key: "child"}], + }, + cases: [ + [{user: {name: "a", address: {city: "x"}}}, {out: {name: "a", city: "x"}}], + [{user: {name: "b"}}, {out: {name: "b", city: null}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{user: {address: {}}}, {out: {name: "anon", city: null}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{}, {out: {name: "anon", city: null}}, "question: a nested key whose value is null is kept as null (only top-level nulls are dropped), as in 07-table-outputs and 11-pass-through"], + [{user: {address: {city: "y", zip: 1}, other: [1]}}, {out: {name: "anon", city: "y"}}], + ], +} + +{ + name: "a switch on nested optional fields", + graph: { + nodes: [ + {switch: "s", when: ["account.flags.blocked == true", "account.limits.daily > 1000", ""]}, + {expression: "blocked", fields: {r: "'blocked'"}}, + {expression: "high", fields: {r: "'high:' + string(account.limits.daily)"}}, + {expression: "std", fields: {r: "'standard'"}}, + ], + edges: ["input -> s", "s:0 -> blocked -> output", "s:1 -> high -> output", "s:2 -> std -> output"], + }, + cases: [ + [{account: {flags: {blocked: true}, limits: {daily: 5000}}}, {r: "blocked"}], + [{account: {flags: {blocked: false}, limits: {daily: 5000}}}, {r: "high:5000"}], + [{account: {limits: {daily: 2000}}}, {r: "high:2000"}], + [{account: {flags: {}, limits: {daily: 10}}}, {r: "standard"}], + [{account: {flags: {blocked: true}}}, {r: "blocked"}], + [{account: {}}, {r: "standard"}], + [{}, {r: "standard"}], + [{account: {limits: {}}}, {r: "standard"}], + ], +} + +{ + name: "a function node reading nested optional fields", + graph: { + nodes: [{function: "f", source: """export const handler = async (input) => ({ city: input.user?.address?.city ?? 'none', depth: input.user?.address ? 2 : input.user ? 1 : 0 });"""}], + }, + cases: [ + [{user: {address: {city: "x"}}}, {city: "x", depth: 2}], + [{user: {address: {}}}, {city: "none", depth: 2}], + [{user: {}}, {city: "none", depth: 1}], + [{}, {city: "none", depth: 0}], + [{user: {address: {city: "y", zip: 2}}}, {city: "y", depth: 2}], + ], +} + +{ + name: "input keys that contain a dot are not paths", + graph: { + nodes: [{expression: "e", fields: {nested: "a.b ?? 'none'"}}], + }, + cases: [ + [{a: {b: 1}}, {nested: 1}], + [{"a.b": 2}, {nested: "none"}], + [{"a.b": 2, a: {b: 3}}, {nested: 3}], + [{}, {nested: "none"}], + ], +} + +{ + name: "empty objects, nulls and missing keys at depth, copied out", + graph: { + nodes: [{expression: "e", fields: {copy: "a", inner: "a.b"}}], + }, + cases: [ + [{a: {b: {}}}, {copy: {b: {}}, inner: {}}], + [{a: {b: null}}, {copy: {b: null}}], + [{a: {}}, {copy: {}}], + [{a: {b: {c: {}}}}, {copy: {b: {c: {}}}, inner: {c: {}}}], + [{}, {}], + [{a: {b: [{}, {c: null}]}}, {copy: {b: [{}, {c: null}]}, inner: [{}, {c: null}]}], + ], +} + +// --- Long suites: many rows with sparse nested columns -------------------------------------- + +{ + name: "long: sparse nested fields across many rows", + graph: { + nodes: [ + {expression: "e", fields: { + name: "user.name ?? 'anon'", + city: "user.address.city ?? 'nowhere'", + score: "(user.stats.score ?? 0) + (user.stats.bonus ?? 0)", + }}, + ], + }, + cases: [ + [{user: {name: "a"}}, {name: "a", city: "nowhere", score: 0}], + [{user: {address: {city: "b"}}}, {name: "anon", city: "b", score: 0}], + [{user: {stats: {score: 3}}}, {name: "anon", city: "nowhere", score: 3}], + [{user: {stats: {bonus: 2}}}, {name: "anon", city: "nowhere", score: 2}], + [{user: {name: "c", stats: {score: 1, bonus: 1}}}, {name: "c", city: "nowhere", score: 2}], + [{}, {name: "anon", city: "nowhere", score: 0}], + [{user: {}}, {name: "anon", city: "nowhere", score: 0}], + [{user: {address: {}}}, {name: "anon", city: "nowhere", score: 0}], + [{user: {name: "d", address: {city: "e"}, stats: {score: 10}}}, {name: "d", city: "e", score: 10}], + [{user: {name: "f"}}, {name: "f", city: "nowhere", score: 0}], + [{user: {stats: {}}}, {name: "anon", city: "nowhere", score: 0}], + [{user: {address: {city: "g", zip: "1"}}}, {name: "anon", city: "g", score: 0}], + [{user: {stats: {score: 0.5, bonus: 0.25}}}, {name: "anon", city: "nowhere", score: 0.75}], + [{user: {name: "h", stats: {score: -1}}}, {name: "h", city: "nowhere", score: -1}], + [{user: {name: ""}}, {name: "", city: "nowhere", score: 0}], + [{user: {address: {city: ""}}}, {name: "anon", city: "", score: 0}], + [{user: {name: "i", address: {city: "j"}}}, {name: "i", city: "j", score: 0}], + [{user: {stats: {bonus: 100}}}, {name: "anon", city: "nowhere", score: 100}], + [{other: {name: "x"}}, {name: "anon", city: "nowhere", score: 0}], + [{user: {name: "k", stats: {score: 5, bonus: 5}, address: {city: "l"}}}, {name: "k", city: "l", score: 10}], + [{user: {name: "m"}}, {name: "m", city: "nowhere", score: 0}], + [{user: {stats: {score: 7}}}, {name: "anon", city: "nowhere", score: 7}], + ], +} + +{ + name: "long: a table over sparse nested columns", + graph: { + nodes: [ + {table: "t", inputs: ["loan.amount", "loan.applicant.income", "loan.applicant.employed"], outputs: ["decision"], rules: [ + ["> 100000", "", "", "'manual'"], + ["", ">= 50000", "true", "'approve'"], + ["", "", "false", "'decline'"], + ["", "", "", "'review'"], + ]}, + ], + }, + cases: [ + [{loan: {amount: 200000}}, {decision: "manual"}], + [{loan: {amount: 1000, applicant: {income: 60000, employed: true}}}, {decision: "approve"}], + [{loan: {applicant: {income: 60000, employed: true}}}, {decision: "approve"}], + [{loan: {applicant: {employed: false}}}, {decision: "decline"}], + [{loan: {applicant: {income: 10000, employed: true}}}, {decision: "review"}], + [{loan: {}}, {decision: "review"}], + [{}, {decision: "review"}], + [{loan: {amount: 100000, applicant: {income: 50000, employed: true}}}, {decision: "approve"}], + [{loan: {amount: 100001, applicant: {employed: false}}}, {decision: "manual"}], + [{loan: {amount: 5, applicant: {income: 70000}}}, {decision: "review"}], + [{loan: {amount: 5, applicant: {}}}, {decision: "review"}], + [{loan: {applicant: {income: 99999, employed: false}}}, {decision: "decline"}], + [{loan: {amount: 0, applicant: {income: 0, employed: true}}}, {decision: "review"}], + [{loan: {amount: 999999.99}}, {decision: "manual"}], + [{loan: {applicant: {income: 50000.01, employed: true}}}, {decision: "approve"}], + [{loan: {amount: 1}}, {decision: "review"}], + [{loan: {applicant: {employed: true}}}, {decision: "review"}], + [{loan: {amount: 2, applicant: {income: 1, employed: false}}}, {decision: "decline"}], + [{loan: {amount: 3, applicant: {income: 50000, employed: true}}}, {decision: "approve"}], + [{loan: {amount: 150000, applicant: {}}}, {decision: "manual"}], + [{loan: {applicant: {income: 80000, employed: "yes"}}}, {decision: "review"}], + [{loan: {amount: 4}}, {decision: "review"}], + ], +} + +// --- Loops and overlapping keys over shapes that differ per row --------------------------- + +{ + name: "a pass-through loop keeps each item's own keys", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "items", passThrough: true, executionMode: "loop", fields: {seen: "true", cost: "(price ?? 0) * 2"}}], + }, + cases: [ + [{items: [{price: 1, a: 1}, {b: {c: 2}}]}, {items: [{price: 1, a: 1, seen: true, cost: 2}, {b: {c: 2}, seen: true, cost: 0}]}], + [{items: []}, {items: []}], + [{items: [{}], other: "kept"}, {items: [{seen: true, cost: 0}], other: "kept"}], + [{items: [{price: 0.5, tags: ["x"]}, {price: 2, deep: {deeper: {x: 1}}}]}, {items: [{price: 0.5, tags: ["x"], seen: true, cost: 1}, {price: 2, deep: {deeper: {x: 1}}, seen: true, cost: 4}]}], + ], +} + +{ + name: "a loop over an array whose elements are objects in some rows and scalars in others", + graph: { + nodes: [{expression: "each", inputField: "xs", outputPath: "out", executionMode: "loop", fields: {v: "v ?? 'none'"}}], + }, + cases: [ + [{xs: [{v: 1}, {v: "a"}]}, {out: [{v: 1}, {v: "a"}]}], + [{xs: [{}, {w: 1}]}, {out: [{v: "none"}, {v: "none"}]}], + [{xs: [1, 2]}, "!error"], + [{xs: []}, {out: []}], + [{xs: [{v: [1, 2]}]}, {out: [{v: [1, 2]}]}], + ], +} + +{ + name: "expression keys writing a parent and a child path, values varying per row", + graph: { + nodes: [{expression: "e", fields: [["a", "base"], ["a.b", "extra"]]}], + }, + cases: [ + [{base: {x: 1}, extra: 2}, {a: {x: 1, b: 2}}], + [{base: {}, extra: "s"}, {a: {b: "s"}}], + [{extra: 3}, {a: {b: 3}}, "bug: the earlier key `a` evaluated to null, and the later `a.b` write is then lost instead of creating the object, unlike dotted writes into a missing input key (11-pass-through)"], + [{base: {x: 1}}, {a: {x: 1, b: null}}], + [{base: 5, extra: 1}, {a: 5}, "question: `a.b` cannot be written into the scalar the earlier key `a` produced, so it is silently dropped; pass-through dotted writes replace a primitive instead (11-pass-through)"], + [{}, {}, "question: both writes are null; the nested null is not materialized here, unlike other nested null writes"], + ], +} + +{ + name: "a table in loop mode reading dotted fields of items with different depth", + graph: { + nodes: [{table: "t", inputField: "people", outputPath: "out", executionMode: "loop", inputs: ["address.country", "age"], outputs: ["r"], rules: [ + ["'US'", ">= 21", "'us-adult'"], + ["", ">= 18", "'adult'"], + ["'US'", "", "'us'"], + ["", "", "'other'"], + ]}], + }, + cases: [ + [{people: [{address: {country: "US"}, age: 30}, {age: 19}, {address: {country: "US"}}, {}]}, {out: [{r: "us-adult"}, {r: "adult"}, {r: "us"}, {r: "other"}]}], + [{people: [{address: {}, age: 18}, {address: {country: "DE", city: "B"}, age: 10}]}, {out: [{r: "adult"}, {r: "other"}]}], + [{people: []}, {out: []}], + [{people: [{address: {country: "US"}, age: 20}]}, {out: [{r: "adult"}]}], + ], +} diff --git a/core/engine/tests/spec/graph/50-rows-errors-and-branches.json5 b/core/engine/tests/spec/graph/50-rows-errors-and-branches.json5 new file mode 100644 index 00000000..152ee0c0 --- /dev/null +++ b/core/engine/tests/spec/graph/50-rows-errors-and-branches.json5 @@ -0,0 +1,817 @@ +// Rows of one suite that fail in different places or take different routes. +// +// In batch and columnar mode one compiled program runs every row together; a row that errors +// must fail alone, with the error of the node it failed in, and a row taking one switch branch +// must not see the work of rows taking another. Each suite here has many rows: some succeed, +// some fail in the first node, some in a later node, some in a branch only they take; collect +// tables return many rules for some rows and none for others. Expected results are single-row +// semantics. + +// --- Errors in different nodes of a chain -------------------------------------------------- + +{ + name: "a chain of three expression nodes, rows failing in each of them", + graph: { + nodes: [ + {expression: "first", passThrough: true, fields: {a: "x * 2"}}, + {expression: "second", passThrough: true, fields: {b: "a + y"}}, + {expression: "third", fields: {c: "b / z"}}, + ], + }, + cases: [ + [{x: 1, y: 2, z: 2}, {c: 2}], + [{x: "s", y: 2, z: 2}, "!error: \"first\""], + [{x: 1, y: "s", z: 2}, "!error: \"second\""], + [{x: 1, y: 2, z: "s"}, "!error: \"third\""], + [{x: 3, y: 4, z: 5}, {c: 2}], + [{y: 1, z: 1}, "!error: \"first\""], + [{x: 1, z: 1}, "!error: \"second\""], + [{x: 1, y: 1}, "!error: \"third\""], + [{x: 0.5, y: 0, z: 0.5}, {c: 2}], + [{x: 10, y: -20, z: 1}, {c: 0}], + [{x: -1, y: 1, z: -1}, {c: 1}], + [{x: true, y: 1, z: 1}, "!error: \"first\""], + ], +} + +{ + name: "division by zero gives null only on the rows with a zero divisor", + graph: { + nodes: [{expression: "e", fields: {q: "a / b", m: "a % b"}}], + }, + cases: [ + [{a: 10, b: 2}, {q: 5, m: 0}], + [{a: 10, b: 0}, {}], + [{a: 7, b: 3}, {q: 2.3333333333333333333333333333, m: 1}], + [{a: 0, b: 5}, {q: 0, m: 0}], + [{a: 1, b: 0.0}, {}], + [{a: -9, b: 4}, {q: -2.25, m: -1}], + [{a: 1.5, b: 0.5}, {q: 3, m: 0}], + [{a: 0, b: 0}, {}], + [{a: 100, b: -10}, {q: -10, m: 0}], + [{a: 5, b: 1}, {q: 5, m: 0}], + ], +} + +{ + name: "number() parsing fails only the rows with non-numeric text", + graph: { + nodes: [ + {expression: "parse", passThrough: true, fields: {n: "number(raw)"}}, + {expression: "use", fields: {r: "n + 1"}}, + ], + }, + cases: [ + [{raw: "1"}, {r: 2}], + [{raw: "abc"}, "!error: \"parse\""], + [{raw: "2.5"}, {r: 3.5}], + [{raw: "-7"}, {r: -6}], + [{raw: ""}, "!error: \"parse\""], + [{raw: 4}, {r: 5}], + [{raw: "1e2"}, {r: 101}], + [{raw: "12px"}, "!error: \"parse\""], + [{raw: "0"}, {r: 1}], + [{raw: true}, {r: 2}], + [{raw: " 3 "}, {r: 4}], + ], +} + +{ + name: "a table output cell that fails for some matching rows", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["v"], rules: [ + ["'double'", "n * 2"], + ["'upper'", "upper(s)"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [{kind: "double", n: 2}, {v: 4}], + [{kind: "double", n: "2"}, {v: "none"}, "question: a failing output cell drops the rule silently (falls through to the next match) instead of failing the node, as in 06-table-cells and 07-table-outputs"], + [{kind: "upper", s: "ab"}, {v: "AB"}], + [{kind: "upper", s: 3}, {v: "none"}, "question: a failing output cell drops the rule silently (falls through to the next match) instead of failing the node, as in 06-table-cells and 07-table-outputs"], + [{kind: "other", n: "2", s: 3}, {v: "none"}], + [{kind: "double"}, {v: "none"}, "question: a failing output cell drops the rule silently (falls through to the next match) instead of failing the node, as in 06-table-cells and 07-table-outputs"], + [{kind: "upper", s: ""}, {v: ""}], + [{kind: "double", n: -0.5}, {v: -1}], + [{}, {v: "none"}], + [{kind: "upper", s: "żółw"}, {v: "ŻÓŁW"}], + ], +} + +{ + name: "a collect table where only some matching rules have failing outputs", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "'positive'"], + ["> 10", "n * factor"], + ["> 100", "'huge'"], + ]}, + ], + }, + cases: [ + [{n: 1}, [{v: "positive"}]], + [{n: 11, factor: 2}, [{v: "positive"}, {v: 22}]], + [{n: 11}, [{v: "positive"}], "question: a failing output cell drops the rule silently (falls through to the next match) instead of failing the node, as in 06-table-cells and 07-table-outputs"], + [{n: 101, factor: 1}, [{v: "positive"}, {v: 101}, {v: "huge"}]], + [{n: 101, factor: "x"}, [{v: "positive"}, {v: "huge"}], "question: a failing output cell drops the rule silently (falls through to the next match) instead of failing the node, as in 06-table-cells and 07-table-outputs"], + [{n: 0}, []], + [{n: -5, factor: "x"}, []], + [{n: 5, factor: "x"}, [{v: "positive"}]], + [{n: 50, factor: 0.1}, [{v: "positive"}, {v: 5}]], + [{}, []], + ], +} + +{ + name: "rows failing after a table: the table output feeds an expression", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["tier"], outputs: ["rate"], rules: [ + ["'gold'", "0.2"], + ["'silver'", "0.1"], + ["'broken'", "'n/a'"], + ]}, + {expression: "e", fields: {discount: "amount * rate"}}, + ], + }, + cases: [ + [{tier: "gold", amount: 100}, {discount: 20}], + [{tier: "silver", amount: 100}, {discount: 10}], + [{tier: "broken", amount: 100}, "!error: \"e\""], + [{tier: "none", amount: 100}, "!error: \"e\""], + [{tier: "gold"}, "!error: \"e\""], + [{tier: "gold", amount: 0}, {discount: 0}], + [{tier: "silver", amount: 12.5}, {discount: 1.25}], + [{amount: 100}, "!error: \"e\""], + [{tier: "gold", amount: -50}, {discount: -10}], + [{tier: "silver", amount: "100"}, "!error: \"e\""], + ], +} + +// --- Rows taking different switch branches ------------------------------------------------- + +{ + name: "first switch with four branches, each row picking one", + graph: { + nodes: [ + {switch: "s", when: ["score >= 90", "score >= 70", "score >= 50", ""]}, + {expression: "a", fields: {grade: "'A'", bonus: "score - 90"}}, + {expression: "b", fields: {grade: "'B'"}}, + {expression: "c", fields: {grade: "'C'", retake: "true"}}, + {expression: "f", fields: {grade: "'F'", gap: "50 - (score ?? 0)"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output", "s:3 -> f -> output"], + }, + cases: [ + [{score: 95}, {grade: "A", bonus: 5}], + [{score: 90}, {grade: "A", bonus: 0}], + [{score: 89.9}, {grade: "B"}], + [{score: 70}, {grade: "B"}], + [{score: 69}, {grade: "C", retake: true}], + [{score: 50}, {grade: "C", retake: true}], + [{score: 49}, {grade: "F", gap: 1}], + [{score: 0}, {grade: "F", gap: 50}], + [{}, {grade: "F", gap: 50}], + [{score: "95"}, "!error: \"f\""], + [{score: 100}, {grade: "A", bonus: 10}], + [{score: -10}, {grade: "F", gap: 60}], + ], +} + +{ + name: "branch-only failures: a node fails only for the rows routed to it", + graph: { + nodes: [ + {switch: "s", when: ["mode == 'num'", "mode == 'text'", ""]}, + {expression: "num", fields: {r: "value * 2"}}, + {expression: "text", fields: {r: "upper(value)"}}, + {expression: "rest", fields: {r: "'rest'"}}, + ], + edges: ["input -> s", "s:0 -> num -> output", "s:1 -> text -> output", "s:2 -> rest -> output"], + }, + cases: [ + [{mode: "num", value: 2}, {r: 4}], + [{mode: "num", value: "x"}, "!error: \"num\""], + [{mode: "text", value: "x"}, {r: "X"}], + [{mode: "text", value: 2}, "!error: \"text\""], + [{mode: "other", value: "x"}, {r: "rest"}], + [{mode: "other", value: 2}, {r: "rest"}], + [{value: 2}, {r: "rest"}], + [{mode: "num"}, "!error: \"num\""], + [{mode: "text"}, "!error: \"text\""], + [{mode: "num", value: 0.25}, {r: 0.5}], + [{mode: "text", value: "ab cd"}, {r: "AB CD"}], + [{mode: "num", value: -1}, {r: -2}], + ], +} + +{ + name: "a switch whose conditions error for some rows routes them to the default", + graph: { + nodes: [ + {switch: "s", when: ["len(items) > 2", "items[0] > 10", ""]}, + {expression: "many", fields: {r: "'many'"}}, + {expression: "big", fields: {r: "'big first'"}}, + {expression: "rest", fields: {r: "'rest'"}}, + ], + edges: ["input -> s", "s:0 -> many -> output", "s:1 -> big -> output", "s:2 -> rest -> output"], + }, + cases: [ + [{items: [1, 2, 3]}, {r: "many"}], + [{items: [11, 2]}, {r: "big first"}], + [{items: [1, 2]}, {r: "rest"}], + [{items: []}, {r: "rest"}], + [{}, {r: "rest"}], + [{items: "abc"}, {r: "many"}], + [{items: "ab"}, {r: "rest"}], + [{items: ["a", "b"]}, {r: "rest"}], + [{items: 5}, {r: "rest"}], + [{items: [100]}, {r: "big first"}], + [{items: [null, 1]}, {r: "rest"}], + ], +} + +{ + name: "collect switch: rows taking zero, one, two or three branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a == true", "b == true", "c == true"]}, + {expression: "ea", fields: {fromA: "1"}}, + {expression: "eb", fields: {fromB: "2"}}, + {expression: "ec", fields: {fromC: "3"}}, + ], + edges: ["input -> s", "s:0 -> ea -> output", "s:1 -> eb -> output", "s:2 -> ec -> output"], + }, + cases: [ + [{}, {}], + [{a: true}, {fromA: 1}], + [{b: true}, {fromB: 2}], + [{c: true}, {fromC: 3}], + [{a: true, b: true}, {fromA: 1, fromB: 2}], + [{a: true, c: true}, {fromA: 1, fromC: 3}], + [{b: true, c: true}, {fromB: 2, fromC: 3}], + [{a: true, b: true, c: true}, {fromA: 1, fromB: 2, fromC: 3}], + [{a: false, b: false, c: false}, {}], + [{a: "true", b: 1}, {}], + [{a: true, b: false, c: true}, {fromA: 1, fromC: 3}], + ], +} + +{ + name: "collect switch: one taken branch fails for some rows, the whole row fails", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["x > 0", "y > 0"]}, + {expression: "ex", fields: {rx: "x * 10"}}, + {expression: "ey", fields: {ry: "upper(name)"}}, + ], + edges: ["input -> s", "s:0 -> ex -> output", "s:1 -> ey -> output"], + }, + cases: [ + [{x: 1, y: 0}, {rx: 10}], + [{x: 1, y: 1, name: "a"}, {rx: 10, ry: "A"}], + [{x: 1, y: 1}, "!error: \"ey\""], + [{x: 0, y: 1, name: "b"}, {ry: "B"}], + [{x: 0, y: 1, name: 5}, "!error: \"ey\""], + [{x: 0, y: 0}, {}], + [{x: 2, y: 2, name: "c"}, {rx: 20, ry: "C"}], + [{}, {}], + [{x: 1}, {rx: 10}], + [{y: 1, name: "d"}, {ry: "D"}], + [{x: 0.5, y: -1, name: 7}, {rx: 5}], + ], +} + +{ + name: "branches converging on a shared node, rows from either branch", + graph: { + nodes: [ + {switch: "s", when: ["kind == 'a'", ""]}, + {expression: "ea", passThrough: true, fields: {v: "n + 1"}}, + {expression: "eb", passThrough: true, fields: {v: "n - 1"}}, + {expression: "join", fields: {r: "v * 10", kind: "kind"}}, + ], + edges: ["input -> s", "s:0 -> ea -> join", "s:1 -> eb -> join", "join -> output"], + }, + cases: [ + [{kind: "a", n: 1}, {r: 20, kind: "a"}], + [{kind: "b", n: 1}, {r: 0, kind: "b"}], + [{kind: "a", n: 0.5}, {r: 15, kind: "a"}], + [{n: 5}, {r: 40}], + [{kind: "a"}, "!error: \"ea\""], + [{kind: "b"}, "!error: \"eb\""], + [{kind: "a", n: -1}, {r: 0, kind: "a"}], + [{kind: "c", n: 100}, {r: 990, kind: "c"}], + [{kind: "a", n: "1"}, "!error: \"ea\""], + [{kind: "b", n: 2.5}, {r: 15, kind: "b"}], + ], +} + +{ + name: "nested switches: rows reaching four different leaves", + graph: { + nodes: [ + {switch: "outer", when: ["region == 'EU'", ""]}, + {switch: "eu", when: ["amount > 1000", ""]}, + {switch: "other", when: ["amount > 5000", ""]}, + {expression: "euBig", fields: {path: "'eu-big'", fee: "amount * 0.01"}}, + {expression: "euSmall", fields: {path: "'eu-small'", fee: "5"}}, + {expression: "otherBig", fields: {path: "'other-big'", fee: "amount * 0.02"}}, + {expression: "otherSmall", fields: {path: "'other-small'", fee: "10"}}, + ], + edges: [ + "input -> outer", + "outer:0 -> eu", + "outer:1 -> other", + "eu:0 -> euBig -> output", + "eu:1 -> euSmall -> output", + "other:0 -> otherBig -> output", + "other:1 -> otherSmall -> output", + ], + }, + cases: [ + [{region: "EU", amount: 2000}, {path: "eu-big", fee: 20}], + [{region: "EU", amount: 1000}, {path: "eu-small", fee: 5}], + [{region: "US", amount: 6000}, {path: "other-big", fee: 120}], + [{region: "US", amount: 5000}, {path: "other-small", fee: 10}], + [{amount: 10000}, {path: "other-big", fee: 200}], + [{region: "EU"}, {path: "eu-small", fee: 5}], + [{}, {path: "other-small", fee: 10}], + [{region: "EU", amount: "2000"}, {path: "eu-small", fee: 5}], + [{region: "eu", amount: 2000}, {path: "other-small", fee: 10}], + [{region: "EU", amount: 1000.01}, {path: "eu-big", fee: 10.0001}], + [{region: "APAC", amount: 5000.5}, {path: "other-big", fee: 100.01}], + ], +} + +{ + name: "a switch branch that goes straight to the output next to computed branches", + graph: { + nodes: [ + {switch: "s", when: ["skip == true", ""]}, + {expression: "calc", fields: {total: "price * qty"}}, + ], + edges: ["input -> s", "s:0 -> output", "s:1 -> calc -> output"], + }, + cases: [ + [{skip: true, price: 2, qty: 3}, {skip: true, price: 2, qty: 3}], + [{price: 2, qty: 3}, {total: 6}], + [{skip: false, price: 1, qty: 1}, {total: 1}], + [{skip: true}, {skip: true}], + [{price: "x", qty: 1}, "!error: \"calc\""], + [{skip: true, price: "x", qty: 1}, {skip: true, price: "x", qty: 1}], + [{price: 0.5, qty: 4}, {total: 2}], + [{}, "!error: \"calc\""], + [{skip: true, nested: {a: 1}}, {skip: true, nested: {a: 1}}], + [{price: 10, qty: 0}, {total: 0}], + ], +} + +// --- Collect tables with many vs zero matches --------------------------------------------- + +{ + name: "collect table: rows matching zero to five rules", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["k"], rules: [ + ["> 0", "1"], + ["> 10", "2"], + ["> 100", "3"], + ["> 1000", "4"], + ["> 10000", "5"], + ]}, + ], + }, + cases: [ + [{n: 0}, []], + [{n: 1}, [{k: 1}]], + [{n: 11}, [{k: 1}, {k: 2}]], + [{n: 101}, [{k: 1}, {k: 2}, {k: 3}]], + [{n: 1001}, [{k: 1}, {k: 2}, {k: 3}, {k: 4}]], + [{n: 10001}, [{k: 1}, {k: 2}, {k: 3}, {k: 4}, {k: 5}]], + [{n: -1}, []], + [{}, []], + [{n: "50"}, []], + [{n: 10}, [{k: 1}]], + [{n: 99999999}, [{k: 1}, {k: 2}, {k: 3}, {k: 4}, {k: 5}]], + ], +} + +{ + name: "collect table under an output path, counted downstream", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, outputPath: "hits", inputs: ["age", "country"], outputs: ["rule"], rules: [ + [">= 18", "", "'adult'"], + [">= 21", "'US'", "'us-drink'"], + [">= 65", "", "'senior'"], + ["", "'US', 'CA'", "'na'"], + ]}, + {expression: "e", fields: {count: "len(hits)", rules: "map(hits, #.rule)"}}, + ], + }, + cases: [ + [{age: 30, country: "US"}, {count: 3, rules: ["adult", "us-drink", "na"]}], + [{age: 70, country: "US"}, {count: 4, rules: ["adult", "us-drink", "senior", "na"]}], + [{age: 20, country: "US"}, {count: 2, rules: ["adult", "na"]}], + [{age: 10, country: "DE"}, {count: 0, rules: []}], + [{age: 10, country: "CA"}, {count: 1, rules: ["na"]}], + [{}, {count: 0, rules: []}], + [{age: 66}, {count: 2, rules: ["adult", "senior"]}], + [{country: "US"}, {count: 1, rules: ["na"]}], + [{age: 18, country: "FR"}, {count: 1, rules: ["adult"]}], + [{age: 21, country: "CA"}, {count: 2, rules: ["adult", "na"]}], + [{age: "70", country: "US"}, {count: 1, rules: ["na"]}], + ], +} + +{ + name: "per-column collect: zero, one or many values gathered per row", + graph: { + nodes: [ + {table: "t", inputs: ["x"], outputs: ["tags[]", "first"], rules: [ + ["> 0", "'pos'", "'pos'"], + ["> 5", "'gt5'", "'gt5'"], + ["> 50", "'gt50'", "'gt50'"], + ["< 0", "'neg'", "'neg'"], + ]}, + ], + }, + cases: [ + [{x: 1}, {tags: ["pos"], first: "pos"}], + [{x: 6}, {tags: ["pos", "gt5"], first: "pos"}], + [{x: 51}, {tags: ["pos", "gt5", "gt50"], first: "pos"}], + [{x: -1}, {tags: ["neg"], first: "neg"}], + [{x: 0}, {tags: []}], + [{}, {tags: []}], + [{x: 5}, {tags: ["pos"], first: "pos"}], + [{x: 1000}, {tags: ["pos", "gt5", "gt50"], first: "pos"}], + [{x: -0.001}, {tags: ["neg"], first: "neg"}], + [{x: "9"}, {tags: []}], + ], +} + +{ + name: "a loop over items where some rows have failing items", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {t: "price * qty"}}], + }, + cases: [ + [{items: [{price: 1, qty: 2}, {price: 3, qty: 4}]}, {out: [{t: 2}, {t: 12}]}], + [{items: [{price: 1, qty: 2}, {price: "x", qty: 4}]}, "!error"], + [{items: []}, {out: []}], + [{items: [{price: 1}]}, "!error"], + [{items: [{price: 0.5, qty: 0.5}]}, {out: [{t: 0.25}]}], + [{items: [{price: 2, qty: 2}, {price: 2, qty: 2}, {price: 2, qty: 2}]}, {out: [{t: 4}, {t: 4}, {t: 4}]}], + [{}, "!error"], + [{items: "abc"}, "!error"], + [{items: [{price: -1, qty: 3}]}, {out: [{t: -3}]}], + [{items: [{qty: 1}, {price: 1, qty: 1}]}, "!error"], + ], +} + +{ + name: "a sub-decision that fails for some rows", + decisions: { + child: {nodes: [{expression: "inner", fields: {y: "x * 2"}}]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", passThrough: true}, + {expression: "after", fields: {z: "y + 1"}}, + ], + }, + cases: [ + [{x: 1}, {z: 3}], + [{x: "s"}, "!error"], + [{x: 0}, {z: 1}], + [{}, "!error"], + [{x: 2.5}, {z: 6}], + [{x: -1}, {z: -1}], + [{x: true}, "!error"], + [{x: 100}, {z: 201}], + [{x: [1]}, "!error"], + [{x: 0.1}, {z: 1.2}], + ], +} + +{ + name: "a function node that throws for some rows", + graph: { + nodes: [ + {expression: "pre", passThrough: true, fields: {n2: "n * 2"}}, + {function: "f", source: """export const handler = async (input) => { if (input.n2 > 10) throw new Error('too big'); return { r: input.n2 + 1 }; };"""}, + ], + }, + cases: [ + [{n: 1}, {r: 3}], + [{n: 6}, "!error: too big"], + [{n: 5}, {r: 11}], + [{n: "x"}, "!error: \"pre\""], + [{n: 0}, {r: 1}], + [{n: 100}, "!error: too big"], + [{n: -3}, {r: -5}], + [{n: 2.5}, {r: 6}], + [{}, "!error: \"pre\""], + [{n: 5.01}, "!error: too big"], + ], +} + +{ + name: "a custom fail node in one switch branch", + graph: { + nodes: [ + {switch: "s", when: ["ok == true", ""]}, + {expression: "good", fields: {r: "'ok:' + string(n)"}}, + {custom: "bad", kind: "fail", config: {message: "rejected row"}}, + ], + edges: ["input -> s", "s:0 -> good -> output", "s:1 -> bad -> output"], + }, + cases: [ + [{ok: true, n: 1}, {r: "ok:1"}], + [{ok: false, n: 1}, "!error: rejected row"], + [{ok: true, n: "x"}, {r: "ok:x"}], + [{}, "!error: rejected row"], + [{ok: true}, {r: "ok:null"}], + [{ok: "true"}, "!error: rejected row"], + [{ok: true, n: [1]}, "!error"], + [{ok: true, n: 2.5}, {r: "ok:2.5"}], + [{ok: null}, "!error: rejected row"], + [{ok: true, n: false}, {r: "ok:false"}], + ], +} + +// --- Long mixed suites --------------------------------------------------------------------- + +{ + name: "long: a pricing graph with branches, tables, and failures in each stage", + graph: { + nodes: [ + {expression: "base", passThrough: true, fields: {subtotal: "price * qty"}}, + {switch: "route", when: ["member == true", ""]}, + {table: "memberRate", passThrough: true, inputs: ["subtotal"], outputs: ["rate"], rules: [ + [">= 1000", "0.15"], + [">= 100", "0.1"], + ["", "0.05"], + ]}, + {table: "guestRate", passThrough: true, inputs: ["coupon"], outputs: ["rate"], rules: [ + ["'SAVE10'", "0.1"], + ["'BROKEN'", "'oops'"], + ["", "0"], + ]}, + {expression: "final", fields: {total: "round(subtotal * (1 - rate), 2)", rate: "rate"}}, + ], + edges: [ + "input -> base -> route", + "route:0 -> memberRate -> final", + "route:1 -> guestRate -> final", + "final -> output", + ], + }, + cases: [ + [{price: 10, qty: 2, member: true}, {total: 19, rate: 0.05}], + [{price: 50, qty: 2, member: true}, {total: 90, rate: 0.1}], + [{price: 500, qty: 2, member: true}, {total: 850, rate: 0.15}], + [{price: 10, qty: 2}, {total: 20, rate: 0}], + [{price: 10, qty: 2, coupon: "SAVE10"}, {total: 18, rate: 0.1}], + [{price: 10, qty: 2, coupon: "BROKEN"}, "!error: \"final\""], + [{price: "10", qty: 2}, "!error: \"base\""], + [{qty: 2, member: true}, "!error: \"base\""], + [{price: 3.33, qty: 3, member: true}, {total: 9.49, rate: 0.05}], + [{price: 0, qty: 5, member: false, coupon: "SAVE10"}, {total: 0, rate: 0.1}], + [{price: 99.99, qty: 1, member: true}, {total: 94.99, rate: 0.05}], + [{price: 100, qty: 1, member: true}, {total: 90, rate: 0.1}], + [{price: 1, qty: 1000, member: true}, {total: 850, rate: 0.15}], + [{price: 12.5, qty: 4, coupon: "save10"}, {total: 50, rate: 0}], + [{price: 12.5, qty: 4, member: true, coupon: "BROKEN"}, {total: 47.5, rate: 0.05}], + [{price: 7, qty: 0, member: true}, {total: 0, rate: 0.05}], + [{price: 1, qty: -1}, {total: -1, rate: 0}], + [{price: 2, qty: 2, member: "yes", coupon: "SAVE10"}, {total: 3.6, rate: 0.1}], + [{price: 10, member: true}, "!error: \"base\""], + [{price: 1000, qty: 1, member: true, coupon: "SAVE10"}, {total: 850, rate: 0.15}], + [{price: 33.333, qty: 3}, {total: 100, rate: 0}], + [{price: 0.01, qty: 1, coupon: "BROKEN"}, "!error: \"final\""], + ], +} + +{ + name: "long: alternating success and failure rows in one expression node", + graph: { + nodes: [{expression: "e", fields: {r: "a + b"}}], + }, + cases: [ + [{a: 1, b: 1}, {r: 2}], + [{a: 1, b: "x"}, "!error"], + [{a: 2, b: 2}, {r: 4}], + [{a: "x", b: 1}, "!error"], + [{a: 3, b: 3}, {r: 6}], + [{a: 1}, "!error"], + [{a: 4, b: 4}, {r: 8}], + [{b: 1}, "!error"], + [{a: 5, b: 5}, {r: 10}], + [{a: true, b: 1}, "!error"], + [{a: 6, b: 6}, {r: 12}], + [{a: [1], b: 1}, "!error"], + [{a: 7, b: 7}, {r: 14}], + [{a: null, b: null}, "!error"], + [{a: "s", b: "t"}, {r: "st"}], + [{a: 8, b: 8}, {r: 16}], + [{a: 1, b: {x: 1}}, "!error"], + [{a: 9, b: 9}, {r: 18}], + [{a: 0.1, b: 0.2}, {r: 0.3}], + [{a: -1, b: 1}, {r: 0}], + [{a: 10, b: "10"}, "!error"], + [{a: 11, b: 11}, {r: 22}], + ], +} + +{ + name: "long: a collect switch fanning to tables, rows matching any subset", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["income != null", "debt != null", "age != null"]}, + {table: "ti", outputPath: "income", inputs: ["income"], outputs: ["band"], rules: [ + [">= 100000", "'high'"], + [">= 30000", "'mid'"], + ["", "'low'"], + ]}, + {table: "td", outputPath: "debt", inputs: ["debt"], outputs: ["band"], rules: [ + ["> 50000", "'heavy'"], + ["", "'light'"], + ]}, + {expression: "ea", fields: {"age.adult": "age >= 18"}}, + ], + edges: ["input -> s", "s:0 -> ti -> output", "s:1 -> td -> output", "s:2 -> ea -> output"], + }, + cases: [ + [{income: 120000, debt: 60000, age: 40}, {income: {band: "high"}, debt: {band: "heavy"}, age: {adult: true}}], + [{income: 40000}, {income: {band: "mid"}}], + [{debt: 1000}, {debt: {band: "light"}}], + [{age: 10}, {age: {adult: false}}], + [{}, {}], + [{income: 1, age: 18}, {income: {band: "low"}, age: {adult: true}}], + [{debt: 50001, age: 30}, {debt: {band: "heavy"}, age: {adult: true}}], + [{income: 100000, debt: 50000}, {income: {band: "high"}, debt: {band: "light"}}], + [{age: "x"}, "!error: \"ea\""], + [{income: "lots"}, {income: {band: "low"}}], + [{income: 30000, debt: 0, age: 17}, {income: {band: "mid"}, debt: {band: "light"}, age: {adult: false}}], + [{debt: -5}, {debt: {band: "light"}}], + [{income: 99999.99, age: 65}, {income: {band: "mid"}, age: {adult: true}}], + [{income: 0, debt: 0, age: 0}, {income: {band: "low"}, debt: {band: "light"}, age: {adult: false}}], + [{debt: 99999999}, {debt: {band: "heavy"}}], + [{income: 50000, debt: 60000, age: "old"}, "!error: \"ea\""], + [{age: 100}, {age: {adult: true}}], + [{income: 250000}, {income: {band: "high"}}], + [{debt: 50000.01, income: 29999}, {income: {band: "low"}, debt: {band: "heavy"}}], + [{age: 18.5, debt: 1}, {debt: {band: "light"}, age: {adult: true}}], + [{income: 30000}, {income: {band: "mid"}}], + [{income: null, debt: null, age: null}, {}], + ], +} + +// --- Rows whose result kind differs: arrays from one branch, objects from another ---------- + +{ + name: "a switch routing some rows to a collect table (array result) and others to an expression", + graph: { + nodes: [ + {switch: "s", when: ["list == true", ""]}, + {table: "t", hit: "collect", inputs: ["n"], outputs: ["k"], rules: [ + ["> 0", "'a'"], + ["> 1", "'b'"], + ]}, + {expression: "e", fields: {single: "n"}}, + ], + edges: ["input -> s", "s:0 -> t -> output", "s:1 -> e -> output"], + }, + cases: [ + [{list: true, n: 2}, [{k: "a"}, {k: "b"}]], + [{list: true, n: 1}, [{k: "a"}]], + [{list: true, n: 0}, []], + [{n: 2}, {single: 2}], + [{list: false, n: "x"}, {single: "x"}], + [{list: true}, []], + [{}, {}], + [{list: true, n: 5}, [{k: "a"}, {k: "b"}]], + [{n: [1]}, {single: [1]}], + [{list: true, n: -1}, []], + ], +} + +{ + name: "a node input selected by inputField that is an object, array, scalar or missing per row", + graph: { + nodes: [{expression: "e", inputField: "payload", fields: {t: "type(x)", x: "x"}}], + }, + cases: [ + [{payload: {x: 1}}, {t: "number", x: 1}], + [{payload: {x: "s", y: 2}}, {t: "string", x: "s"}], + [{payload: {}}, {t: "null"}], + [{}, {t: "null"}], + [{payload: 5}, "!error", "question: a scalar node input becomes the expression environment and reading a field of it errors, while a scalar request is replaced by an empty object (01-input-output)"], + [{payload: "s"}, "!error", "question: a scalar node input becomes the expression environment and reading a field of it errors, while a scalar request is replaced by an empty object (01-input-output)"], + [{payload: null}, {t: "null"}], + [{payload: {x: {deep: [1]}}}, {t: "object", x: {deep: [1]}}], + [{payload: {x: true}, x: 99}, {t: "bool", x: true}], + [{x: 99}, {t: "null"}], + ], +} + +{ + name: "a sub-decision in loop mode over items whose shapes differ, some failing", + decisions: { + child: {nodes: [{table: "t", inputs: ["kind"], outputs: ["cost"], rules: [ + ["'a'", "price * 2"], + ["'b'", "price + 1"], + ["", "0"], + ]}, {expression: "e", passThrough: true, fields: {checked: "cost >= 0"}}]}, + }, + graph: { + nodes: [{decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}], + }, + cases: [ + [{items: [{kind: "a", price: 2}, {kind: "b", price: 2}, {kind: "c"}]}, {out: [{cost: 4, checked: true}, {cost: 3, checked: true}, {cost: 0, checked: true}]}], + [{items: []}, {out: []}], + [{items: [{kind: "a", price: -1}]}, {out: [{cost: -2, checked: false}]}], + [{items: [{price: 9}]}, {out: [{cost: 0, checked: true}]}], + [{items: [{kind: "a"}]}, {out: [{cost: 0, checked: true}]}, "question: the failing output cell `price * 2` drops rule a silently, so the default rule answers"], + [{items: [{kind: "b", price: 0.5, extra: {x: 1}}, {kind: "a", price: 0.25}]}, {out: [{cost: 1.5, checked: true}, {cost: 0.5, checked: true}]}], + [{}, "!error"], + ], +} + +{ + name: "a fan-in join of two pass-through parents writing one key with types that differ per row", + graph: { + nodes: [ + {expression: "left", passThrough: true, fields: {v: "n > 0 ? n : 'neg'"}}, + {expression: "right", passThrough: true, fields: {w: "n > 0 ? 'pos' : n"}}, + {expression: "join", fields: {v: "v", w: "w", tv: "type(v)", tw: "type(w)"}}, + ], + edges: ["input -> left -> join", "input -> right -> join", "join -> output"], + }, + cases: [ + [{n: 1}, {v: 1, w: "pos", tv: "number", tw: "string"}], + [{n: -1}, {v: "neg", w: -1, tv: "string", tw: "number"}], + [{n: 0}, {v: "neg", w: 0, tv: "string", tw: "number"}], + [{n: 2.5}, {v: 2.5, w: "pos", tv: "number", tw: "string"}], + [{n: "x"}, "!error"], + [{}, "!error"], + [{n: 1000}, {v: 1000, w: "pos", tv: "number", tw: "string"}], + [{n: -0.5}, {v: "neg", w: -0.5, tv: "string", tw: "number"}], + [{n: 3}, {v: 3, w: "pos", tv: "number", tw: "string"}], + [{n: -3}, {v: "neg", w: -3, tv: "string", tw: "number"}], + ], +} + +{ + name: "templates over fields of every type, some rows failing", + graph: { + nodes: [{expression: "e", fields: {s: "`${name}:${n * 2}`"}}], + }, + cases: [ + [{name: "a", n: 1}, {s: "a:2"}], + [{name: 5, n: 1}, {s: "5:2"}], + [{name: true, n: 0.5}, {s: "true:1.0"}], + [{n: 1}, {s: "null:2"}], + [{name: "b", n: "x"}, "!error"], + [{name: "c"}, "!error"], + [{name: "", n: -1}, {s: ":-2"}], + [{name: "d", n: 100}, {s: "d:200"}], + [{name: [1], n: 1}, "!error"], + [{name: "e", n: 0}, {s: "e:0"}], + ], +} + +{ + name: "a table with many rules over mixed rows, matching early, late or never", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["label"], rules: [ + ["1", "'one'"], ["2", "'two'"], ["3", "'three'"], ["4", "'four'"], ["5", "'five'"], + ["6", "'six'"], ["7", "'seven'"], ["8", "'eight'"], ["9", "'nine'"], ["10", "'ten'"], + ["'1'", "'string one'"], ["true", "'bool'"], ["[11..20]", "'teens'"], ["> 20", "'big'"], + ]}, + ], + }, + cases: [ + [{code: 1}, {label: "one"}], + [{code: 10}, {label: "ten"}], + [{code: 5}, {label: "five"}], + [{code: "1"}, {label: "string one"}], + [{code: true}, {label: "bool"}], + [{code: 15}, {label: "teens"}], + [{code: 21}, {label: "big"}], + [{code: 0}, {}], + [{}, {}], + [{code: "x"}, {}], + [{code: 1.0}, {label: "one"}], + [{code: 10.5}, {}], + [{code: false}, {}], + [{code: 20}, {label: "teens"}], + ], +} diff --git a/core/engine/tests/spec/graph/51-input-schema-types.json5 b/core/engine/tests/spec/graph/51-input-schema-types.json5 new file mode 100644 index 00000000..b84e5582 --- /dev/null +++ b/core/engine/tests/spec/graph/51-input-schema-types.json5 @@ -0,0 +1,1228 @@ +// Input schema keywords, one keyword family per suite. +// +// The input node validates the request with a Draft 7 JSON schema before any node runs. Chapter 19 +// pins the basics (required, primitive types, simple bounds, enum, nested required, items, +// additionalProperties, oneOf, if/then); this chapter walks the rest of the keyword set and the +// corners of the ones already covered: type unions, null handling through the null-retry rule, +// exclusive bounds, decimal multipleOf, code-point string lengths, unanchored patterns, formats, +// object/array enums and consts, tuple items, contains, object size keywords, propertyNames, +// patternProperties, dependencies, $ref/definitions, allOf/not/else and boolean schemas. +// +// Null-retry rule (`NodeContext::validate`): when validation fails, null-valued object keys at the +// failing paths are removed and validation is retried, so a null key counts as absent for every +// keyword except a `required` that lists it (a null array item is never removed). +// +// The compiled engine pre-checks columnar rows against a reduced schema (`compiled/schema.rs`: +// type, properties, required, additionalProperties, string enums, nested objects, arrays with +// items) and only sends doubtful rows to the full validator, so the first suites use exactly that +// subset and vary column types and presence across cases. + +// --------------------------------------------------------------------------------------------- +// The columnar pre-check subset: flat properties, every row shape in one suite. +{ + name: "pre-check subset: flat typed properties with required", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["id", "amount"], properties: { + id: {type: "string"}, + amount: {type: "number"}, + count: {type: "integer"}, + active: {type: "boolean"}, + }}}, + {expression: "calc", fields: {id: "id", doubled: "amount * 2", n: "count ?? 0", on: "active ?? false"}}, + ], + }, + cases: [ + [{id: "a", amount: 1.5, count: 2, active: true}, {id: "a", doubled: 3, n: 2, on: true}], + [{id: "b", amount: 0}, {id: "b", doubled: 0, n: 0, on: false}], + [{id: "c", amount: -2, count: 0, active: false}, {id: "c", doubled: -4, n: 0, on: false}], + [{id: "d", amount: "1"}, "!error: /amount"], + [{id: 5, amount: 1}, "!error: /id"], + [{id: "e", amount: 1, count: 1.5}, "!error: /count"], + [{id: "f", amount: 1, count: 3.0}, {id: "f", doubled: 2, n: 3, on: false}], + [{id: "g", amount: 1, active: "yes"}, "!error: /active"], + [{amount: 1}, "!error: id"], + [{id: "h"}, "!error: amount"], + [{id: "i", amount: 1, extra: {deep: [1]}}, {id: "i", doubled: 2, n: 0, on: false}], + ], +} + +{ + name: "pre-check subset: additionalProperties false at the root", + graph: { + nodes: [ + {input: "request", schema: {type: "object", additionalProperties: false, properties: { + a: {type: "number"}, + b: {type: "string"}, + }}}, + {expression: "calc", fields: {sum: "(a ?? 0) + len(b ?? '')"}}, + ], + }, + cases: [ + [{a: 1, b: "xy"}, {sum: 3}], + [{a: 2}, {sum: 2}], + [{b: "xyz"}, {sum: 3}], + [{}, {sum: 0}], + [{a: 1, c: 1}, "!error: NodeError"], + [{c: "x"}, "!error: NodeError"], + [{a: 1, c: null}, {sum: 1}], + [{a: 1, b: {nested: true}}, "!error: /b"], + ], +} + +{ + name: "pre-check subset: string enum and const", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["tier"], properties: { + tier: {type: "string", enum: ["gold", "silver", "bronze"]}, + region: {enum: ["eu", "us"]}, + version: {const: "v2"}, + }}}, + {expression: "calc", fields: {key: "tier + '/' + (region ?? '-') + '/' + (version ?? '-')"}}, + ], + }, + cases: [ + [{tier: "gold"}, {key: "gold/-/-"}], + [{tier: "silver", region: "eu"}, {key: "silver/eu/-"}], + [{tier: "bronze", region: "us", version: "v2"}, {key: "bronze/us/v2"}], + [{tier: "Gold"}, "!error: /tier"], + [{tier: "gold", region: "apac"}, "!error: /region"], + [{tier: "gold", region: 1}, "!error: /region"], + [{tier: "gold", version: "v3"}, "!error: /version"], + [{tier: ""}, "!error: /tier"], + [{tier: 1}, "!error: /tier"], + ], +} + +{ + name: "pre-check subset: nested objects with required members", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["customer"], properties: { + customer: {type: "object", required: ["name"], properties: { + name: {type: "string"}, + age: {type: "integer"}, + address: {type: "object", required: ["city"], properties: {city: {type: "string"}, zip: {type: "string"}}}, + }}, + }}}, + {expression: "calc", fields: {name: "customer.name", city: "customer.address.city ?? 'unknown'"}}, + ], + }, + cases: [ + [{customer: {name: "ann"}}, {name: "ann", city: "unknown"}], + [{customer: {name: "bob", age: 40, address: {city: "Berlin"}}}, {name: "bob", city: "Berlin"}], + [{customer: {name: "cy", address: {city: "Paris", zip: "75001"}}}, {name: "cy", city: "Paris"}], + [{customer: {name: "dee", address: {zip: "1000"}}}, "!error: /customer/address"], + [{customer: {age: 3}}, "!error: /customer"], + [{customer: {name: "eve", age: "3"}}, "!error: /customer/age"], + [{customer: {name: "fay", address: {city: 7}}}, "!error: /customer/address/city"], + [{customer: {name: "gus", address: "Rome"}}, "!error: /customer/address"], + [{}, "!error: customer"], + ], +} + +{ + name: "pre-check subset: nested additionalProperties false", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + point: {type: "object", additionalProperties: false, properties: {x: {type: "number"}, y: {type: "number"}}}, + }}}, + {expression: "calc", fields: {sum: "(point.x ?? 0) + (point.y ?? 0)"}}, + ], + }, + cases: [ + [{point: {x: 1, y: 2}}, {sum: 3}], + [{point: {x: 1}}, {sum: 1}], + [{}, {sum: 0}], + [{point: {x: 1, z: 3}}, "!error: /point"], + [{point: {x: 1, z: {deep: 1}}}, "!error: /point"], + [{point: {x: 1}, other: {z: 1}}, {sum: 1}], + ], +} + +{ + name: "pre-check subset: arrays with typed items", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + nums: {type: "array", items: {type: "number"}}, + tags: {type: "array", items: {type: "string", enum: ["a", "b", "c"]}}, + flags: {type: "array", items: {type: "boolean"}}, + }}}, + {expression: "calc", fields: {total: "sum(nums ?? [])", tagCount: "len(tags ?? [])", anyFlag: "some(flags ?? [], #)"}}, + ], + }, + cases: [ + [{nums: [1, 2], tags: ["a"], flags: [false, true]}, {total: 3, tagCount: 1, anyFlag: true}], + [{nums: [], tags: [], flags: []}, {total: 0, tagCount: 0, anyFlag: false}], + [{nums: [0.5]}, {total: 0.5, tagCount: 0, anyFlag: false}], + [{tags: ["c", "b", "a"]}, {total: 0, tagCount: 3, anyFlag: false}], + [{nums: [1, "2"]}, "!error: /nums/1"], + [{tags: ["a", "d"]}, "!error: /tags/1"], + [{flags: [true, 1]}, "!error: /flags/1"], + [{nums: "1,2"}, "!error: /nums"], + [{nums: [1, null]}, "!error: /nums/1"], + ], +} + +{ + name: "pre-check subset: arrays of objects", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["lines"], properties: { + lines: {type: "array", items: {type: "object", required: ["sku"], properties: {sku: {type: "string"}, qty: {type: "integer"}}}}, + }}}, + {expression: "calc", fields: {skus: "map(lines, #.sku)", qty: "sum(map(lines, #.qty ?? 1))"}}, + ], + }, + cases: [ + [{lines: [{sku: "a", qty: 2}, {sku: "b"}]}, {skus: ["a", "b"], qty: 3}], + [{lines: []}, {skus: [], qty: 0}], + [{lines: [{sku: "a", qty: 2.5}]}, "!error: /lines/0/qty"], + [{lines: [{qty: 1}]}, "!error: /lines/0"], + [{lines: [{sku: "a"}, "b"]}, "!error: /lines/1"], + [{lines: [{sku: "a", qty: null}]}, {skus: ["a"], qty: 1}], + ], +} + +{ + name: "pre-check subset: annotations and $schema are ignored", + graph: { + nodes: [ + {input: "request", schema: { + $schema: "http://json-schema.org/draft-07/schema#", + title: "Request", + description: "annotated", + type: "object", + required: ["n"], + properties: {n: {type: "number", title: "N", description: "a number", default: 5, examples: [1, 2], $comment: "c"}}, + }}, + {expression: "calc", fields: {n: "n"}}, + ], + }, + cases: [ + [{n: 1}, {n: 1}], + [{n: 0}, {n: 0}], + [{}, "!error: n"], + [{n: "5"}, "!error: /n"], + ], +} + +{ + name: "pre-check subset: a required key not listed in properties accepts any value", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["token"], properties: {other: {type: "string"}}}}, + {expression: "calc", fields: {kind: "type(token)"}}, + ], + }, + cases: [ + [{token: "x"}, {kind: "string"}], + [{token: 1}, {kind: "number"}], + [{token: [1]}, {kind: "array"}], + [{token: {a: 1}}, {kind: "object"}], + [{token: false}, {kind: "bool"}], + [{other: "x"}, "!error: token"], + [{token: null}, {kind: "null"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Type unions and nullability. +{ + name: "type unions: a list of types accepts any member", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["v"], properties: {v: {type: ["string", "number"]}}}}, + {expression: "calc", fields: {kind: "type(v)"}}, + ], + }, + cases: [ + [{v: "1"}, {kind: "string"}], + [{v: 1}, {kind: "number"}], + [{v: 1.25}, {kind: "number"}], + [{v: true}, "!error: /v"], + [{v: []}, "!error: /v"], + [{v: {}}, "!error: /v"], + [{v: null}, "!error: /v"], + ], +} + +{ + name: "type unions: integer inside a union with string", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {v: {type: ["integer", "boolean"]}}}}, + {expression: "calc", fields: {kind: "type(v)"}}, + ], + }, + cases: [ + [{v: 3}, {kind: "number"}], + [{v: -3}, {kind: "number"}], + [{v: 3.0}, {kind: "number"}], + [{v: false}, {kind: "bool"}], + [{v: 3.1}, "!error: /v"], + [{v: "3"}, "!error: /v"], + [{}, {kind: "null"}], + ], +} + +{ + name: "nullability: null in the type list, required or not", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["a"], properties: { + a: {type: ["number", "null"]}, + b: {type: ["null", "string"]}, + }}}, + {expression: "calc", fields: {a: "a ?? 'none'", b: "b ?? 'none'"}}, + ], + }, + cases: [ + [{a: 1, b: "x"}, {a: 1, b: "x"}], + [{a: null, b: null}, {a: "none", b: "none"}], + [{a: null}, {a: "none", b: "none"}], + [{b: "x"}, "!error: a"], + [{a: "1"}, "!error: /a"], + [{a: 1, b: 2}, "!error: /b"], + ], +} + +{ + name: "nullability: OpenAPI `nullable` is not a Draft 7 keyword and is ignored", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["a"], properties: {a: {type: "number", nullable: true}}}}, + ], + }, + cases: [ + [{a: 1}, {a: 1}], + [{a: "x"}, "!error: /a"], + [{a: null}, "!error: /a"], + ], +} + +{ + name: "nullability: type null alone", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["gone"], properties: {gone: {type: "null"}}}}, + {expression: "calc", fields: {kind: "type(gone)"}}, + ], + }, + cases: [ + [{gone: null}, {kind: "null"}], + [{gone: 0}, "!error: /gone"], + [{gone: ""}, "!error: /gone"], + [{}, "!error: gone"], + ], +} + +{ + name: "null-retry: a null key that fails a keyword counts as absent", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + s: {type: "string", minLength: 3}, + n: {type: "number", minimum: 10}, + e: {enum: ["x", "y"]}, + o: {type: "object", required: ["k"]}, + a: {type: "array", minItems: 1}, + }}}, + {expression: "calc", fields: {nulls: "len(filter([s, n, e, o, a], # == null))"}}, + ], + }, + cases: [ + [{s: null, n: null, e: null, o: null, a: null}, {nulls: 5}], + [{s: "abc", n: 10, e: "x", o: {k: 1}, a: [1]}, {nulls: 0}], + [{s: null, n: 9}, "!error: /n"], + [{o: {k: null}}, {nulls: 4}], + [{o: {j: 1}}, "!error: /o"], + [{a: [null]}, {nulls: 4}], + ], +} + +{ + name: "null-retry: object size keywords do not count null keys", + graph: { + nodes: [ + {input: "request", schema: {type: "object", maxProperties: 2}}, + ], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2}], + [{a: 1, b: 2, c: null}, {a: 1, b: 2}], + [{a: 1, b: 2, c: 3}, "!error: NodeError"], + [{}, {}], + ], +} + +{ + name: "null-retry: not-required treats a null key as absent", + graph: { + nodes: [ + {input: "request", schema: {type: "object", not: {required: ["legacy"]}}}, + ], + }, + cases: [ + [{}, {}], + [{a: 1}, {a: 1}], + [{legacy: null}, {}], + [{legacy: 1}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Numbers. +{ + name: "numbers: exclusive bounds exclude the edge", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + rate: {type: "number", exclusiveMinimum: 0, exclusiveMaximum: 1}, + }}}, + ], + }, + cases: [ + [{rate: 0.5}, {rate: 0.5}], + [{rate: 0.000001}, {rate: 0.000001}], + [{rate: 0.999999}, {rate: 0.999999}], + [{rate: 0}, "!error: /rate"], + [{rate: 1}, "!error: /rate"], + [{rate: 1.0}, "!error: /rate"], + [{rate: -0.1}, "!error: /rate"], + ], +} + +{ + name: "numbers: negative and fractional bounds", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + temp: {type: "number", minimum: -273.15, maximum: 1000.5}, + }}}, + ], + }, + cases: [ + [{temp: -273.15}, {temp: -273.15}], + [{temp: -273.16}, "!error: /temp"], + [{temp: 1000.5}, {temp: 1000.5}], + [{temp: 1000.51}, "!error: /temp"], + [{temp: 0}, {temp: 0}], + ], +} + +{ + name: "numbers: multipleOf with decimal steps", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + cents: {type: "number", multipleOf: 0.01}, + tenth: {type: "number", multipleOf: 0.1}, + five: {type: "integer", multipleOf: 5}, + }}}, + ], + }, + cases: [ + [{cents: 19.99}, {cents: 19.99}], + [{cents: 0.07}, {cents: 0.07}], + [{cents: 1.005}, "!error: /cents"], + [{tenth: 0.3}, {tenth: 0.3}], + [{tenth: 2.2}, {tenth: 2.2}], + [{tenth: 0.35}, "!error: /tenth"], + [{five: 0}, {five: 0}], + [{five: -15}, {five: -15}], + [{five: 12}, "!error: /five"], + ], +} + +{ + name: "numbers: integer accepts integral decimals and large values", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {i: {type: "integer", minimum: 0}}}}, + {expression: "calc", fields: {next: "i + 1"}}, + ], + }, + cases: [ + [{i: 0}, {next: 1}], + [{i: 10.0}, {next: 11}], + [{i: 9007199254740993}, {next: 9007199254740994}], + [{i: 1e3}, {next: 1001}], + [{i: 0.5}, "!error: /i"], + [{i: -1}, "!error: /i"], + ], +} + +{ + name: "numbers: bounds alone do not imply a type", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {v: {minimum: 5}}}}, + ], + }, + cases: [ + [{v: 5}, {v: 5}], + [{v: 4}, "!error: /v"], + [{v: "4"}, {v: "4"}], + [{v: [1]}, {v: [1]}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Strings. +{ + name: "strings: length counts code points", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {s: {type: "string", minLength: 2, maxLength: 2}}}}, + ], + }, + cases: [ + [{s: "ab"}, {s: "ab"}], + [{s: "äö"}, {s: "äö"}], + [{s: "日本"}, {s: "日本"}], + [{s: "😀😀"}, {s: "😀😀"}], + [{s: "a"}, "!error: /s"], + [{s: "😀"}, "!error: /s"], + [{s: "abc"}, "!error: /s"], + ], +} + +{ + name: "strings: maxLength 0 only accepts the empty string", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {s: {type: "string", maxLength: 0}}}}, + ], + }, + cases: [ + [{s: ""}, {s: ""}], + [{s: " "}, "!error: /s"], + ], +} + +{ + name: "strings: pattern is unanchored unless the regex anchors it", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + loose: {type: "string", pattern: "[0-9]{3}"}, + strict: {type: "string", pattern: "^[0-9]{3}$"}, + }}}, + ], + }, + cases: [ + [{loose: "123"}, {loose: "123"}], + [{loose: "ab1234cd"}, {loose: "ab1234cd"}], + [{loose: "12"}, "!error: /loose"], + [{strict: "123"}, {strict: "123"}], + [{strict: "1234"}, "!error: /strict"], + [{strict: " 123"}, "!error: /strict"], + ], +} + +{ + name: "strings: ECMA regex features in pattern", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + word: {type: "string", pattern: "^\\w+$"}, + alt: {type: "string", pattern: "^(red|green|blue)$"}, + notAdmin: {type: "string", pattern: "^(?!admin$).+$"}, + email: {type: "string", pattern: "^[^@\\s]+@[^@\\s]+\\.[a-z]{2,}$"}, + }}}, + ], + }, + cases: [ + [{word: "a_1"}, {word: "a_1"}], + [{word: "a-1"}, "!error: /word"], + [{alt: "green"}, {alt: "green"}], + [{alt: "greenish"}, "!error: /alt"], + [{notAdmin: "root"}, {notAdmin: "root"}], + [{notAdmin: "admin"}, "!error: /notAdmin"], + [{notAdmin: "administrator"}, {notAdmin: "administrator"}], + [{email: "a@b.io"}, {email: "a@b.io"}], + [{email: "a@b"}, "!error: /email"], + ], +} + +{ + name: "strings: pattern and length do not apply to non-strings", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {v: {pattern: "^x", minLength: 3}}}}, + ], + }, + cases: [ + [{v: "xyz"}, {v: "xyz"}], + [{v: "xy"}, "!error: /v"], + [{v: "abc"}, "!error: /v"], + [{v: 1}, {v: 1}], + [{v: [1]}, {v: [1]}], + ], +} + +// Draft 7 validates formats. date and date-time are replaced by the engine's own date parser +// (chapter 52); the others use the validator's built-in checks. `uuid` is not a Draft 7 format, so it +// is not checked. +{ + name: "strings: built-in formats", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + email: {type: "string", format: "email"}, + ip: {type: "string", format: "ipv4"}, + id: {type: "string", format: "uuid"}, + link: {type: "string", format: "uri"}, + at: {type: "string", format: "time"}, + }}}, + ], + }, + cases: [ + [{email: "a@example.com"}, {email: "a@example.com"}], + [{email: "not-an-email"}, "!error: /email"], + [{ip: "192.168.0.1"}, {ip: "192.168.0.1"}], + [{ip: "256.1.1.1"}, "!error: /ip"], + [{id: "123e4567-e89b-12d3-a456-426614174000"}, {id: "123e4567-e89b-12d3-a456-426614174000"}], + [{id: "123e4567"}, {id: "123e4567"}], + [{link: "https://gorules.io/docs"}, {link: "https://gorules.io/docs"}], + [{link: "no scheme"}, "!error: /link"], + [{at: "10:15:30Z"}, {at: "10:15:30Z"}], + [{at: "25:00:00Z"}, "!error: /at"], + ], +} + +{ + name: "strings: an unknown format is ignored", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {v: {type: "string", format: "iban"}}}}, + ], + }, + cases: [ + [{v: "anything"}, {v: "anything"}], + [{v: 1}, "!error: /v"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Enums and const over structured and numeric values. +{ + name: "enum: numbers compare by value", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {n: {enum: [1, 2.5, 10]}}}}, + ], + }, + cases: [ + [{n: 1}, {n: 1}], + [{n: 1.0}, {n: 1}], + [{n: 2.50}, {n: 2.5}], + [{n: 10}, {n: 10}], + [{n: 3}, "!error: /n"], + [{n: "1"}, "!error: /n"], + [{n: true}, "!error: /n"], + ], +} + +{ + name: "enum: objects and arrays compare structurally", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + shape: {enum: [{kind: "circle"}, {kind: "square", size: 2}]}, + pair: {enum: [[1, 2], ["a"]]}, + }}}, + ], + }, + cases: [ + [{shape: {kind: "circle"}}, {shape: {kind: "circle"}}], + [{shape: {size: 2, kind: "square"}}, {shape: {kind: "square", size: 2}}], + [{shape: {kind: "square"}}, "!error: /shape"], + [{shape: {kind: "circle", r: 1}}, "!error: /shape"], + [{pair: [1, 2]}, {pair: [1, 2]}], + [{pair: [2, 1]}, "!error: /pair"], + [{pair: ["a"]}, {pair: ["a"]}], + ], +} + +{ + name: "const: object, number, boolean and null", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + cfg: {const: {mode: "strict", level: 2}}, + zero: {const: 0}, + yes: {const: true}, + none: {const: null}, + }}}, + ], + }, + cases: [ + [{cfg: {level: 2, mode: "strict"}}, {cfg: {mode: "strict", level: 2}}], + [{cfg: {mode: "strict", level: 2.0}}, {cfg: {mode: "strict", level: 2}}], + [{cfg: {mode: "strict"}}, "!error: /cfg"], + [{zero: 0}, {zero: 0}], + [{zero: 0.0}, {zero: 0}], + [{zero: false}, "!error: /zero"], + [{yes: true}, {yes: true}], + [{yes: 1}, "!error: /yes"], + [{none: null}, {}], + [{none: 0}, "!error: /none"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Arrays. +{ + name: "arrays: tuple items with additionalItems", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + point: {type: "array", items: [{type: "number"}, {type: "number"}], additionalItems: false}, + row: {type: "array", items: [{type: "string"}], additionalItems: {type: "number"}}, + }}}, + ], + }, + cases: [ + [{point: [1, 2]}, {point: [1, 2]}], + [{point: [1]}, {point: [1]}], + [{point: []}, {point: []}], + [{point: [1, 2, 3]}, "!error: /point"], + [{point: ["1", 2]}, "!error: /point/0"], + [{row: ["id", 1, 2.5]}, {row: ["id", 1, 2.5]}], + [{row: ["id"]}, {row: ["id"]}], + [{row: ["id", "x"]}, "!error: /row/1"], + [{row: [1]}, "!error: /row/0"], + ], +} + +{ + name: "arrays: minItems, maxItems and uniqueItems", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + picks: {type: "array", minItems: 2, maxItems: 3, uniqueItems: true}, + }}}, + {expression: "calc", fields: {n: "len(picks ?? [])"}}, + ], + }, + cases: [ + [{picks: [1, 2]}, {n: 2}], + [{picks: ["a", "b", "c"]}, {n: 3}], + [{picks: [1, "1"]}, {n: 2}], + [{picks: [{a: 1}, {a: 2}]}, {n: 2}], + [{picks: [1]}, "!error: /picks"], + [{picks: [1, 2, 3, 4]}, "!error: /picks"], + [{picks: [1, 1]}, "!error: /picks"], + [{picks: [1, 1.0]}, "!error: /picks"], + [{picks: [{a: 1}, {a: 1}]}, "!error: /picks"], + [{picks: [[1], [1]]}, "!error: /picks"], + [{}, {n: 0}], + ], +} + +{ + name: "arrays: contains requires at least one matching item", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + roles: {type: "array", contains: {type: "string", pattern: "^admin"}}, + }}}, + {expression: "calc", fields: {n: "len(roles ?? [])"}}, + ], + }, + cases: [ + [{roles: ["user", "admin-eu"]}, {n: 2}], + [{roles: ["admin"]}, {n: 1}], + [{roles: ["user"]}, "!error: /roles"], + [{roles: []}, "!error: /roles"], + [{roles: [1, "admin"]}, {n: 2}], + [{}, {n: 0}], + ], +} + +{ + name: "arrays: nested arrays of arrays", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["grid"], properties: { + grid: {type: "array", items: {type: "array", minItems: 2, items: {type: "integer"}}}, + }}}, + {expression: "calc", fields: {rows: "len(grid)", total: "sum(map(grid, sum(#)))"}}, + ], + }, + cases: [ + [{grid: [[1, 2], [3, 4, 5]]}, {rows: 2, total: 15}], + [{grid: []}, {rows: 0, total: 0}], + [{grid: [[1, 2], [3]]}, "!error: /grid/1"], + [{grid: [[1, 2.5]]}, "!error: /grid/0/1"], + [{grid: [1, 2]}, "!error: /grid/0"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Object keywords beyond properties. +{ + name: "objects: minProperties on a nested object", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {meta: {type: "object", minProperties: 1}}}}, + ], + }, + cases: [ + [{meta: {a: 1}}, {meta: {a: 1}}], + [{meta: {a: 1, b: 2}}, {meta: {a: 1, b: 2}}], + [{meta: {}}, "!error: /meta"], + [{}, {}], + ], +} + +{ + name: "objects: propertyNames constrains every key", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + scores: {type: "object", propertyNames: {pattern: "^[a-z]+$", maxLength: 5}}, + }}}, + {expression: "calc", fields: {keys: "keys(scores ?? {})"}}, + ], + }, + cases: [ + [{scores: {math: 1, art: 2}}, {keys: ["math", "art"]}], + [{scores: {}}, {keys: []}], + [{scores: {Math: 1}}, "!error: /scores"], + [{scores: {science: 1}}, "!error: /scores"], + ], +} + +{ + name: "objects: patternProperties types keys by name", + graph: { + nodes: [ + {input: "request", schema: {type: "object", patternProperties: { + "^n_": {type: "number"}, + "^s_": {type: "string"}, + }}}, + ], + }, + cases: [ + [{n_a: 1, s_b: "x"}, {n_a: 1, s_b: "x"}], + [{other: true}, {other: true}], + [{n_a: "1"}, "!error: /n_a"], + [{s_b: 2}, "!error: /s_b"], + ], +} + +{ + name: "objects: patternProperties with additionalProperties false", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {id: {type: "string"}}, patternProperties: {"^x-": {}}, additionalProperties: false}}, + ], + }, + cases: [ + [{id: "a"}, {id: "a"}], + [{id: "a", "x-trace": 1}, {id: "a", "x-trace": 1}], + [{id: "a", trace: 1}, "!error: NodeError"], + ], +} + +{ + name: "objects: additionalProperties true is the default", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {a: {type: "number"}}, additionalProperties: true}}, + ], + }, + cases: [ + [{a: 1, b: "x", c: [1]}, {a: 1, b: "x", c: [1]}], + [{a: "1"}, "!error: /a"], + ], +} + +{ + name: "objects: additionalProperties as an object schema", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {id: {type: "string"}}, additionalProperties: { + type: "object", required: ["qty"], properties: {qty: {type: "integer", minimum: 1}}, + }}}, + ], + }, + cases: [ + [{id: "o", apple: {qty: 2}, pear: {qty: 1}}, {id: "o", apple: {qty: 2}, pear: {qty: 1}}], + [{id: "o"}, {id: "o"}], + [{id: "o", apple: {qty: 0}}, "!error: /apple/qty"], + [{id: "o", apple: {}}, "!error: /apple"], + [{id: "o", apple: 3}, "!error: /apple"], + ], +} + +{ + name: "objects: dependencies require sibling keys", + graph: { + nodes: [ + {input: "request", schema: {type: "object", dependencies: { + card: ["cvv", "expiry"], + discount: {required: ["code"], properties: {code: {type: "string", minLength: 4}}}, + }}}, + ], + }, + cases: [ + [{}, {}], + [{card: "4111", cvv: "123", expiry: "12/29"}, {card: "4111", cvv: "123", expiry: "12/29"}], + [{card: "4111", cvv: "123"}, "!error: NodeError"], + [{cvv: "123"}, {cvv: "123"}], + [{discount: 5, code: "SAVE"}, {discount: 5, code: "SAVE"}], + [{discount: 5}, "!error: NodeError"], + [{discount: 5, code: "S"}, "!error: /code"], + [{code: "S"}, {code: "S"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// References. +{ + name: "refs: definitions reused through $ref", + graph: { + nodes: [ + {input: "request", schema: { + type: "object", + definitions: { + money: {type: "object", required: ["amount", "currency"], properties: {amount: {type: "number", minimum: 0}, currency: {type: "string", pattern: "^[A-Z]{3}$"}}}, + }, + required: ["price"], + properties: {price: {$ref: "#/definitions/money"}, fee: {$ref: "#/definitions/money"}}, + }}, + {expression: "calc", fields: {total: "price.amount + (fee.amount ?? 0)"}}, + ], + }, + cases: [ + [{price: {amount: 10, currency: "EUR"}}, {total: 10}], + [{price: {amount: 10, currency: "EUR"}, fee: {amount: 2.5, currency: "EUR"}}, {total: 12.5}], + [{price: {amount: -1, currency: "EUR"}}, "!error: /price/amount"], + [{price: {amount: 10, currency: "eur"}}, "!error: /price/currency"], + [{price: {amount: 10, currency: "EUR"}, fee: {amount: 1}}, "!error: /fee"], + [{}, "!error: price"], + ], +} + +{ + name: "refs: a recursive definition validates every level", + graph: { + nodes: [ + {input: "request", schema: { + type: "object", + definitions: { + node: {type: "object", required: ["name"], properties: {name: {type: "string"}, children: {type: "array", items: {$ref: "#/definitions/node"}}}}, + }, + required: ["tree"], + properties: {tree: {$ref: "#/definitions/node"}}, + }}, + {expression: "calc", fields: {top: "tree.name", kids: "len(tree.children ?? [])"}}, + ], + }, + cases: [ + [{tree: {name: "root"}}, {top: "root", kids: 0}], + [{tree: {name: "root", children: [{name: "a", children: [{name: "a1"}]}, {name: "b"}]}}, {top: "root", kids: 2}], + [{tree: {name: "root", children: [{name: "a", children: [{}]}]}}, "!error: /tree/children/0/children/0"], + [{tree: {name: "root", children: [{name: 1}]}}, "!error: /tree/children/0/name"], + ], +} + +{ + name: "refs: a $ref to an unknown definition fails every request", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {a: {$ref: "#/definitions/missing"}}}}, + ], + }, + cases: [ + [{a: 1}, "!error"], + [{}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Combinators. +{ + name: "anyOf: at least one branch must match", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["contact"], properties: {contact: {anyOf: [ + {type: "string", format: "email"}, + {type: "string", pattern: "^\\+[0-9]{6,}$"}, + {type: "object", required: ["street"]}, + ]}}}}, + {expression: "calc", fields: {kind: "type(contact)"}}, + ], + }, + cases: [ + [{contact: "a@b.io"}, {kind: "string"}], + [{contact: "+4930123456"}, {kind: "string"}], + [{contact: {street: "Main"}}, {kind: "object"}], + [{contact: "12345"}, "!error: /contact"], + [{contact: {city: "Rome"}}, "!error: /contact"], + [{contact: 5}, "!error: /contact"], + ], +} + +{ + name: "oneOf: overlapping branches fail when more than one matches", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {n: {oneOf: [{type: "number", multipleOf: 3}, {type: "number", multipleOf: 5}]}}}}, + ], + }, + cases: [ + [{n: 9}, {n: 9}], + [{n: 10}, {n: 10}], + [{n: 15}, "!error: /n"], + [{n: 7}, "!error: /n"], + [{n: 0}, "!error: /n"], + ], +} + +{ + name: "allOf: every branch applies", + graph: { + nodes: [ + {input: "request", schema: {type: "object", allOf: [ + {required: ["id"]}, + {properties: {id: {type: "string"}}}, + {properties: {id: {minLength: 3}}}, + ]}}, + ], + }, + cases: [ + [{id: "abc"}, {id: "abc"}], + [{id: "ab"}, "!error: /id"], + [{id: 123}, "!error: /id"], + [{}, "!error: id"], + ], +} + +{ + name: "not: excludes a shape", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + code: {type: "string", not: {enum: ["TEST", "DEMO"]}}, + qty: {not: {type: "string"}}, + }}}, + ], + }, + cases: [ + [{code: "PROD"}, {code: "PROD"}], + [{code: "TEST"}, "!error: /code"], + [{qty: 1}, {qty: 1}], + [{qty: [1]}, {qty: [1]}], + [{qty: "1"}, "!error: /qty"], + ], +} + +{ + name: "if/then/else: branches on a discriminator", + graph: { + nodes: [ + {input: "request", schema: { + type: "object", + required: ["country"], + properties: {country: {type: "string"}}, + if: {properties: {country: {const: "US"}}}, + then: {properties: {zip: {type: "string", pattern: "^[0-9]{5}$"}}, required: ["zip"]}, + else: {properties: {zip: {type: "string", minLength: 3}}}, + }}, + ], + }, + cases: [ + [{country: "US", zip: "90210"}, {country: "US", zip: "90210"}], + [{country: "US", zip: "9021"}, "!error: /zip"], + [{country: "US"}, "!error: zip"], + [{country: "DE", zip: "10115"}, {country: "DE", zip: "10115"}], + [{country: "DE"}, {country: "DE"}], + [{country: "DE", zip: "1"}, "!error: /zip"], + ], +} + +{ + name: "combinators: discriminated union of object shapes", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["shape"], properties: {shape: {oneOf: [ + {type: "object", required: ["kind", "r"], properties: {kind: {const: "circle"}, r: {type: "number", exclusiveMinimum: 0}}}, + {type: "object", required: ["kind", "w", "h"], properties: {kind: {const: "rect"}, w: {type: "number"}, h: {type: "number"}}}, + ]}}}}, + {switch: "route", when: ["shape.kind == 'circle'", ""]}, + {expression: "circle", fields: {area: "round(3.14159 * shape.r * shape.r, 2)"}}, + {expression: "rect", fields: {area: "shape.w * shape.h"}}, + ], + edges: ["request -> route", "route:0 -> circle -> output", "route:1 -> rect -> output"], + }, + cases: [ + [{shape: {kind: "circle", r: 1}}, {area: 3.14}], + [{shape: {kind: "rect", w: 2, h: 3}}, {area: 6}], + [{shape: {kind: "circle", r: 0}}, "!error: /shape"], + [{shape: {kind: "rect", w: 2}}, "!error: /shape"], + [{shape: {kind: "triangle"}}, "!error: /shape"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Boolean schemas. +{ + name: "boolean schemas: false forbids a property, true allows anything", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {internal: false, anything: true}}}, + ], + }, + cases: [ + [{anything: [1, {a: "x"}]}, {anything: [1, {a: "x"}]}], + [{}, {}], + [{internal: 1}, "!error: /internal"], + [{internal: null}, {}], + ], +} + +{ + name: "boolean schemas: a root schema of true accepts every request", + graph: { + nodes: [ + {input: "request", schema: true}, + ], + }, + cases: [ + [{a: 1}, {a: 1}], + [{}, {}], + ], +} + +{ + name: "boolean schemas: a root schema of false rejects every request", + graph: { + nodes: [ + {input: "request", schema: false}, + ], + }, + cases: [ + [{a: 1}, "!error: NodeError"], + [{}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Invalid schemas. +{ + name: "invalid schema: an unknown type name fails every request", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {a: {type: "text"}}}}, + ], + }, + cases: [ + [{a: "x"}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "invalid schema: a malformed string schema", + graph: { + nodes: [ + {input: "request", schema: '{"type": "object",'}, + ], + }, + cases: [ + [{a: 1}, {a: 1}, "question: a schema string that is not JSON is silently dropped (no schema), while a JSON schema with an unknown type or a bad $ref fails every request"], + [{}, {}, "question: a schema string that is not JSON is silently dropped (no schema), while a JSON schema with an unknown type or a bad $ref fails every request"], + ], +} + +{ + name: "invalid schema: an invalid pattern fails every request", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {a: {type: "string", pattern: "(unclosed"}}}}, + ], + }, + cases: [ + [{a: "x"}, "!error"], + [{}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dictionaries: `$dictionary` in a schema becomes a string enum of an imported policy dictionary. +{ + name: "dictionaries: $dictionary resolves to the imported dictionary values", + decisions: { + dicts: {policy: {dictionaries: {tier: ["VIP", "STD", ["LOW", "Low priority"]]}}}, + }, + graph: {raw: { + imports: ["dicts"], + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {schema: '{"type":"object","required":["tier"],"properties":{"tier":{"$dictionary":"tier"}}}'}}, + {id: "e", name: "calc", type: "expressionNode", content: {expressions: [{id: "x1", key: "vip", value: "tier == 'VIP'"}]}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [ + {id: "e1", sourceId: "i", targetId: "e"}, + {id: "e2", sourceId: "e", targetId: "o"}, + ], + }}, + cases: [ + [{tier: "VIP"}, {vip: true}], + [{tier: "STD"}, {vip: false}], + [{tier: "LOW"}, {vip: false}], + [{tier: "Low priority"}, "!error: /tier"], + [{tier: "vip"}, "!error: /tier"], + [{tier: 1}, "!error: /tier"], + [{}, "!error: tier"], + ], +} + +{ + name: "dictionaries: $dictionary inside array items and an output schema", + decisions: { + dicts: {policy: {dictionaries: {color: ["red", "green", "blue"]}}}, + }, + graph: {raw: { + imports: ["dicts"], + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {schema: '{"type":"object","properties":{"colors":{"type":"array","items":{"$dictionary":"color"}}}}'}}, + {id: "e", name: "calc", type: "expressionNode", content: {expressions: [{id: "x1", key: "first", value: "colors[0] ?? 'none'"}]}}, + {id: "o", name: "response", type: "outputNode", content: {schema: '{"type":"object","properties":{"first":{"$dictionary":"color"}}}'}}, + ], + edges: [ + {id: "e1", sourceId: "i", targetId: "e"}, + {id: "e2", sourceId: "e", targetId: "o"}, + ], + }}, + cases: [ + [{colors: ["red", "blue"]}, {first: "red"}], + [{colors: ["green"]}, {first: "green"}], + [{colors: ["red", "pink"]}, "!error: /colors/1"], + [{colors: []}, "!error: /first"], + [{}, "!error: /first"], + ], +} + +{ + name: "dictionaries: an unknown dictionary fails every request", + graph: {raw: { + nodes: [ + {id: "i", name: "request", type: "inputNode", content: {schema: '{"type":"object","properties":{"tier":{"$dictionary":"tier"}}}'}}, + {id: "o", name: "response", type: "outputNode", content: {}}, + ], + edges: [{id: "e1", sourceId: "i", targetId: "o"}], + }}, + cases: [ + [{tier: "VIP"}, "!error"], + [{}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/52-input-schema-dates.json5 b/core/engine/tests/spec/graph/52-input-schema-dates.json5 new file mode 100644 index 00000000..f73f7ed9 --- /dev/null +++ b/core/engine/tests/spec/graph/52-input-schema-dates.json5 @@ -0,0 +1,872 @@ +// Input schema date fields. +// +// A string property declared `format: date` or `format: date-time` is validated with the engine's +// own date parser and then becomes a date value on the input node (`nodes/input/dates.rs`, +// `DeclaredDates`). Downstream nodes see a date (`type(x) == 'date'`), and the result renders an +// untouched date as its source text. Chapter 19 covers the basics and chapter 28 the tables; this +// chapter pins which schema shapes convert, which texts the formats accept, where in the request +// conversion reaches (nested objects, arrays, combinators, references), and how the converted +// values behave in expressions, switches, tables, functions and sub-decisions. +// +// A schema counts as a declared date when it has `format: date|date-time`, a `type` of `string` +// or `[string, null]`, and otherwise only annotation keys; or when it is an `anyOf` of exactly a +// declared date and `{type: null}`. Properties are followed through `properties` and `items` +// (and the first `anyOf`/`oneOf`/`allOf` variant that has them). +// +// The compiled engine validates these inputs column-wise and hands the plan converted date +// columns, so most suites mix valid, invalid, null and missing values in one batch. +// Evaluation time is fixed at 2025-03-20T10:15:30Z, UTC. + +// --------------------------------------------------------------------------------------------- +// Which texts the formats accept. Both formats use the same lenient parser. +{ + name: "accepted text: format date", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {expression: "calc", passThrough: true, fields: {kind: "type(day)", y: "year(day)", m: "monthOfYear(day)", dd: "dayOfMonth(day)"}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {day: "2024-01-31", kind: "date", y: 2024, m: 1, dd: 31}], + [{day: "2024-02-29"}, {day: "2024-02-29", kind: "date", y: 2024, m: 2, dd: 29}], + [{day: "2024/01/31"}, {day: "2024/01/31", kind: "date", y: 2024, m: 1, dd: 31}], + [{day: "20240131"}, {day: "20240131", kind: "date", y: 2024, m: 1, dd: 31}], + [{day: "2024-05"}, {day: "2024-05", kind: "date", y: 2024, m: 5, dd: 1}], + [{day: "2024"}, {day: "2024", kind: "date", y: 2024, m: 1, dd: 1}], + [{day: "2024-01-31T10:00:00Z"}, {day: "2024-01-31T10:00:00Z", kind: "date", y: 2024, m: 1, dd: 31}, "question: format date accepts a full date-time text (both formats share one lenient parser)"], + [{day: "2024-01-31 10:00"}, {day: "2024-01-31 10:00", kind: "date", y: 2024, m: 1, dd: 31}], + [{day: "2025-3-8"}, {day: "2025-3-8", kind: "date", y: 2025, m: 3, dd: 8}], + ], +} + +{ + name: "rejected text: format date", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {kind: "type(day)"}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {kind: "date"}], + [{day: "2023-02-29"}, "!error: /day"], + [{day: "2024-13-01"}, "!error: /day"], + [{day: "2024-00-10"}, "!error: /day"], + [{day: "31/01/2024"}, "!error: /day"], + [{day: "Jan 31 2024"}, "!error: /day"], + [{day: ""}, "!error: /day"], + [{day: " 2024-01-31"}, {kind: "date"}, "question: leading whitespace is accepted by format date"], + [{day: "tomorrow"}, "!error: /day"], + [{day: 1706659200}, "!error: /day"], + [{day: true}, "!error: /day"], + [{day: ["2024-01-31"]}, "!error: /day"], + ], +} + +{ + name: "accepted text: format date-time with offsets and fractions", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["at"], properties: {at: {type: "string", format: "date-time"}}}}, + {expression: "calc", passThrough: true, fields: {epoch: "dateString(at)", h: "at.hour()"}}, + ], + }, + cases: [ + [{at: "2024-01-31T10:00:00Z"}, {at: "2024-01-31T10:00:00Z", epoch: "2024-01-31 10:00:00", h: 10}], + [{at: "2024-01-31T10:00:00.250Z"}, {at: "2024-01-31T10:00:00.250Z", epoch: "2024-01-31 10:00:00.250", h: 10}], + [{at: "2024-01-31T10:00:00+02:00"}, {at: "2024-01-31T10:00:00+02:00", epoch: "2024-01-31 08:00:00", h: 8}], + [{at: "2024-01-31T23:30:00-05:00"}, {at: "2024-01-31T23:30:00-05:00", epoch: "2024-02-01 04:30:00", h: 4}], + [{at: "2024-01-31T10:00"}, {at: "2024-01-31T10:00", epoch: "2024-01-31 10:00:00", h: 10}], + [{at: "2024-01-31"}, {at: "2024-01-31", epoch: "2024-01-31 00:00:00", h: 0}], + [{at: "2024-01-31T25:00:00Z"}, "!error: /at"], + [{at: "2024-01-31T10:00:00+25:00"}, "!error: /at"], + [{}, "!error: at"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Which schema shapes convert. +{ + name: "shapes: annotations keep the conversion", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + a: {type: "string", format: "date", title: "A", description: "a date", examples: ["2024-01-01"], $comment: "c"}, + b: {type: "string", format: "date-time", default: "2024-01-01T00:00:00Z", deprecated: true, readOnly: false}, + }}}, + {expression: "calc", fields: {a: "type(a)", b: "type(b)"}}, + ], + }, + cases: [ + [{a: "2024-01-01", b: "2024-01-01T00:00:00Z"}, {a: "date", b: "date"}], + [{a: "2024-01-01"}, {a: "date", b: "null"}], + [{b: "2025-03-20T10:15:30Z"}, {a: "null", b: "date"}], + ], +} + +{ + name: "shapes: nullable through the type list", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + a: {type: ["string", "null"], format: "date"}, + b: {type: ["null", "string"], format: "date-time"}, + }}}, + {expression: "calc", fields: {a: "type(a)", b: "type(b)"}}, + ], + }, + cases: [ + [{a: "2024-01-01", b: "2024-01-01T00:00:00Z"}, {a: "date", b: "date"}], + [{a: null, b: null}, {a: "null", b: "null"}], + [{}, {a: "null", b: "null"}], + [{a: "nope"}, "!error: /a"], + ], +} + +{ + name: "shapes: anyOf of a date and null converts, in either order", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + a: {anyOf: [{type: "string", format: "date"}, {type: "null"}]}, + b: {anyOf: [{type: "null"}, {type: "string", format: "date-time"}], description: "nullable"}, + }}}, + {expression: "calc", fields: {a: "type(a)", b: "type(b)"}}, + ], + }, + cases: [ + [{a: "2024-01-01", b: "2024-01-01T00:00:00Z"}, {a: "date", b: "date"}], + [{a: null, b: null}, {a: "null", b: "null"}], + [{a: "2024-01-01"}, {a: "date", b: "null"}], + [{b: "x"}, "!error: /b"], + ], +} + +{ + name: "shapes: oneOf of a date and null is validated but not converted", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {a: {oneOf: [{type: "string", format: "date"}, {type: "null"}]}}}}, + {expression: "calc", fields: {a: "type(a)"}}, + ], + }, + cases: [ + [{a: "2024-01-01"}, {a: "string"}, "question: oneOf [date, null] is the same nullable date as anyOf [date, null], yet it stays a string"], + [{a: null}, {a: "null"}], + [{a: "x"}, "!error: /a"], + ], +} + +{ + name: "shapes: a date with validation keywords is validated but not converted", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + len: {type: "string", format: "date", minLength: 10}, + pat: {type: "string", format: "date", pattern: "^2024"}, + en: {type: "string", format: "date", enum: ["2024-01-01", "2024-12-31"]}, + }}}, + {expression: "calc", fields: {len: "type(len)", pat: "type(pat)", en: "type(en)"}}, + ], + }, + cases: [ + [{len: "2024-01-01"}, {len: "string", pat: "null", en: "null"}, "question: adding a validation keyword (minLength) to a date field turns off the date conversion, while annotation keywords keep it"], + [{pat: "2024-06-01"}, {len: "null", pat: "string", en: "null"}, "question: adding a validation keyword (pattern) to a date field turns off the date conversion, while annotation keywords keep it"], + [{en: "2024-12-31"}, {len: "null", pat: "null", en: "string"}, "question: adding a validation keyword (enum) to a date field turns off the date conversion, while annotation keywords keep it"], + [{len: "2024"}, "!error: /len"], + [{pat: "2025-01-01"}, "!error: /pat"], + [{en: "2024-06-01"}, "!error: /en"], + ], +} + +{ + name: "shapes: format without a string type is validated but not converted", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {a: {format: "date"}}}}, + {expression: "calc", fields: {a: "type(a)"}}, + ], + }, + cases: [ + [{a: "2024-01-01"}, {a: "string"}, "question: `{format: date}` without `type: string` validates the text as a date but leaves it a string"], + [{a: "nope"}, "!error: /a"], + [{a: 5}, {a: "number"}], + ], +} + +{ + name: "shapes: other formats never convert", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {t: {type: "string", format: "time"}, s: {type: "string"}}}}, + {expression: "calc", fields: {t: "type(t)", s: "type(s)"}}, + ], + }, + cases: [ + [{t: "10:00:00Z", s: "2024-01-01"}, {t: "string", s: "string"}], + [{s: "2024-01-01T00:00:00Z"}, {t: "null", s: "string"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Where conversion reaches. +{ + name: "reach: nested objects at several depths", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + policy: {type: "object", properties: { + start: {type: "string", format: "date"}, + holder: {type: "object", properties: {dob: {type: "string", format: "date"}, name: {type: "string"}}}, + }}, + }}}, + {expression: "calc", fields: {start: "type(policy.start)", dob: "type(policy.holder.dob)", ageAtStart: "policy.start.diff(policy.holder.dob, 'year')"}}, + ], + }, + cases: [ + [{policy: {start: "2024-06-01", holder: {dob: "1990-06-02", name: "x"}}}, {start: "date", dob: "date", ageAtStart: 33}], + [{policy: {start: "2024-06-01", holder: {dob: "1990-06-01"}}}, {start: "date", dob: "date", ageAtStart: 34}], + [{policy: {start: "2024-06-01"}}, {start: "date", dob: "null"}], + [{policy: {start: "2024-06-01", holder: {dob: "1990-02-30"}}}, "!error: /policy/holder/dob"], + ], +} + +{ + name: "reach: arrays of date strings", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {days: {type: "array", items: {type: "string", format: "date"}}}}}, + {expression: "calc", fields: {kinds: "map(days, type(#))", last: "max(days)", first: "min(days)"}}, + ], + }, + cases: [ + [{days: ["2024-03-01", "2024-01-15", "2024-02-10"]}, {kinds: ["date", "date", "date"], last: "2024-03-01", first: "2024-01-15"}], + [{days: ["2025-01-01"]}, {kinds: ["date"], last: "2025-01-01", first: "2025-01-01"}], + [{days: ["2024-01-01", "2024/02/01"]}, {kinds: ["date", "date"], last: "2024/02/01", first: "2024-01-01"}], + [{days: ["2024-01-01", "x"]}, "!error: /days/1"], + [{days: ["2024-01-01", null]}, "!error: /days/1"], + ], +} + +{ + name: "reach: arrays of objects with dates, mapped and filtered", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["visits"], properties: {visits: {type: "array", items: { + type: "object", required: ["on"], properties: {on: {type: "string", format: "date"}, note: {type: "string"}}, + }}}}}, + {expression: "calc", fields: { + recent: "len(filter(visits, #.on >= d('2025-01-01')))", + months: "map(visits, monthOfYear(#.on))", + latest: "len(visits) > 0 ? max(map(visits, #.on)) : null", + }}, + ], + }, + cases: [ + [{visits: [{on: "2024-12-31"}, {on: "2025-01-01"}, {on: "2025-03-01", note: "x"}]}, {recent: 2, months: [12, 1, 3], latest: "2025-03-01"}], + [{visits: [{on: "2023-05-05"}]}, {recent: 0, months: [5], latest: "2023-05-05"}], + [{visits: []}, {recent: 0, months: []}], + [{visits: [{note: "no date"}]}, "!error: /visits/0"], + ], +} + +{ + name: "reach: nullable dates inside array items", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {tasks: {type: "array", items: {type: "object", properties: { + due: {type: ["string", "null"], format: "date"}, + }}}}}}, + {expression: "calc", fields: {kinds: "map(tasks, type(#.due))", open: "len(filter(tasks, #.due == null))"}}, + ], + }, + cases: [ + [{tasks: [{due: "2025-01-01"}, {due: null}, {}]}, {kinds: ["date", "null", "null"], open: 2}], + [{tasks: [{due: "2025-01-01"}]}, {kinds: ["date"], open: 0}], + [{tasks: []}, {kinds: [], open: 0}], + ], +} + +{ + name: "reach: tuple items are validated but not converted", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {range: {type: "array", items: [{type: "string", format: "date"}, {type: "string", format: "date"}]}}}}, + {expression: "calc", fields: {kinds: "map(range, type(#))"}}, + ], + }, + cases: [ + [{range: ["2024-01-01", "2024-12-31"]}, {kinds: ["string", "string"]}, "question: tuple-form items declare both members as dates but conversion only follows a single `items` schema"], + [{range: ["2024-01-01", "x"]}, "!error: /range/1"], + ], +} + +{ + name: "reach: additionalProperties dates are validated but not converted", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {holidays: {type: "object", additionalProperties: {type: "string", format: "date"}}}}}, + {expression: "calc", fields: {xmas: "type(holidays.xmas)"}}, + ], + }, + cases: [ + [{holidays: {xmas: "2024-12-25"}}, {xmas: "string"}, "question: a date declared through additionalProperties is validated as a date but stays a string"], + [{holidays: {xmas: "x"}}, "!error: /holidays/xmas"], + [{holidays: {}}, {xmas: "null"}], + ], +} + +{ + name: "reach: a date behind $ref is validated but not converted", + graph: { + nodes: [ + {input: "request", schema: { + type: "object", + definitions: {day: {type: "string", format: "date"}}, + properties: {from: {$ref: "#/definitions/day"}}, + }}, + {expression: "calc", fields: {from: "type(from)"}}, + ], + }, + cases: [ + [{from: "2024-01-01"}, {from: "string"}, "question: a date declared through $ref is validated as a date but stays a string"], + [{from: "x"}, "!error: /from"], + [{}, {from: "null"}], + ], +} + +{ + name: "reach: properties under allOf convert", + graph: { + nodes: [ + {input: "request", schema: {type: "object", allOf: [{properties: {start: {type: "string", format: "date"}}}]}}, + {expression: "calc", fields: {start: "type(start)"}}, + ], + }, + cases: [ + [{start: "2024-01-01"}, {start: "date"}], + [{start: "x"}, "!error: /start"], + [{}, {start: "null"}], + ], +} + +{ + name: "reach: properties under oneOf only follow the first variant", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["pay"], properties: {pay: {oneOf: [ + {type: "object", required: ["card"], properties: {card: {type: "string"}, expires: {type: "string", format: "date"}}}, + {type: "object", required: ["iban"], properties: {iban: {type: "string"}, mandate: {type: "string", format: "date"}}}, + ]}}}}, + {expression: "calc", fields: {expires: "type(pay.expires)", mandate: "type(pay.mandate)"}}, + ], + }, + cases: [ + [{pay: {card: "4111", expires: "2027-01-31"}}, {expires: "date", mandate: "null"}], + [{pay: {iban: "DE00", mandate: "2024-05-01"}}, {expires: "null", mandate: "date"}, "bug: conversion follows only the first oneOf variant with properties, so the second variant's date stays a string"], + [{pay: {iban: "DE00", mandate: "x"}}, "!error: /pay"], + ], +} + +{ + name: "reach: a root-level properties map converts, siblings stay strings", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {due: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {due: "type(due)", other: "type(other)", nested: "type(meta.due)"}}, + ], + }, + cases: [ + [{due: "2024-01-01", other: "2024-01-01", meta: {due: "2024-01-01"}}, {due: "date", other: "string", nested: "string"}], + [{other: "2024-01-01"}, {due: "null", other: "string", nested: "null"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Converted dates in expressions. +{ + name: "expressions: arithmetic and component functions", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["start"], properties: {start: {type: "string", format: "date"}, days: {type: "integer"}}}}, + {expression: "calc", fields: { + end: "start.add(days ?? 30, 'd')", + endMonth: "start.add(days ?? 30, 'd').month()", + startOfMonth: "start.startOf('month')", + weekday: "start.weekday()", + isPast: "start < d()", + }}, + ], + }, + cases: [ + [{start: "2024-01-31"}, {end: "2024-03-01T00:00:00Z", endMonth: 3, startOfMonth: "2024-01-01T00:00:00Z", weekday: 3, isPast: true}], + [{start: "2024-01-31", days: 1}, {end: "2024-02-01T00:00:00Z", endMonth: 2, startOfMonth: "2024-01-01T00:00:00Z", weekday: 3, isPast: true}], + [{start: "2025-12-01", days: 0}, {end: "2025-12-01T00:00:00Z", endMonth: 12, startOfMonth: "2025-12-01T00:00:00Z", weekday: 1, isPast: false}], + [{start: "2025-03-20T10:15:30Z", days: -1}, {end: "2025-03-19T10:15:30Z", endMonth: 3, startOfMonth: "2025-03-01T00:00:00Z", weekday: 4, isPast: false}], + ], +} + +{ + name: "expressions: comparisons between two declared dates and with strings", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["a", "b"], properties: {a: {type: "string", format: "date"}, b: {type: "string", format: "date-time"}}}}, + {expression: "calc", fields: { + lt: "a < b", + eq: "a == b", + sameDay: "a.isSame(b, 'day')", + eqText: "a == '2024-01-01'", + inText: "a in ['2024-01-01', '2024-06-01']", + }}, + ], + }, + cases: [ + [{a: "2024-01-01", b: "2024-01-01T00:00:00Z"}, {lt: false, eq: true, sameDay: true, eqText: true, inText: true}], + [{a: "2024-01-01", b: "2024-01-01T12:00:00Z"}, {lt: true, eq: false, sameDay: true, eqText: true, inText: true}], + [{a: "2024-06-01", b: "2024-01-01T12:00:00Z"}, {lt: false, eq: false, sameDay: false, eqText: false, inText: true}], + [{a: "2024-12-31", b: "2025-01-01T00:00:00+01:00"}, {lt: true, eq: false, sameDay: true, eqText: false, inText: false}], + ], +} + +{ + name: "expressions: a declared date in a template and string functions", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["day"], properties: {day: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {text: "string(day)", tpl: "`due ${day}`", fmt: "day.format('%d.%m.%Y')"}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {text: "2024-01-31", tpl: "due 2024-01-31", fmt: "31.01.2024"}], + [{day: "2024/02/01"}, {text: "2024/02/01", tpl: "due 2024/02/01", fmt: "01.02.2024"}], + ], +} + +{ + name: "expressions: a declared date reached through $nodes", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {kind: "type($nodes.request.day)", y: "year($nodes.request.day)"}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {kind: "date", y: 2024}], + [{day: "1999-12-31"}, {kind: "date", y: 1999}], + ], +} + +{ + name: "expressions: a missing declared date fails a date function", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {y: "day != null ? year(day) : -1"}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {y: 2024}], + [{day: null}, {y: -1}], + [{}, {y: -1}], + [{day: "bad"}, "!error: /day"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Converted dates in switches and tables. +{ + name: "switch: routes on a declared date", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["due"], properties: {due: {type: "string", format: "date"}}}}, + {switch: "route", when: ["due < d()", "due <= d().add(7, 'd')", ""]}, + {expression: "late", fields: {status: "'overdue'", days: "d().diff(due, 'day')"}}, + {expression: "soon", fields: {status: "'due soon'", days: "due.diff(d().startOf('day'), 'day')"}}, + {expression: "later", fields: {status: "'scheduled'"}}, + ], + edges: ["request -> route", "route:0 -> late -> output", "route:1 -> soon -> output", "route:2 -> later -> output"], + }, + cases: [ + [{due: "2025-03-10"}, {status: "overdue", days: 10}], + [{due: "2025-03-20"}, {status: "overdue", days: 0}], + [{due: "2025-03-21"}, {status: "due soon", days: 1}], + [{due: "2025-03-27"}, {status: "due soon", days: 7}], + [{due: "2025-03-28"}, {status: "scheduled"}], + [{due: "2025-28-03"}, "!error: /due"], + ], +} + +{ + name: "switch: collect mode over date conditions", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["at"], properties: {at: {type: "string", format: "date-time"}}}}, + {switch: "flags", hit: "collect", when: ["at.weekday() >= 6", "at.hour() < 6 or at.hour() >= 22", "monthOfYear(at) == 12"]}, + {expression: "weekend", fields: {weekend: "true"}}, + {expression: "night", fields: {night: "true"}}, + {expression: "december", fields: {december: "true"}}, + ], + edges: ["request -> flags", "flags:0 -> weekend -> output", "flags:1 -> night -> output", "flags:2 -> december -> output"], + }, + cases: [ + [{at: "2024-12-21T23:00:00Z"}, {weekend: true, night: true, december: true}], + [{at: "2024-12-18T12:00:00Z"}, {december: true}], + [{at: "2024-06-15T05:00:00Z"}, {weekend: true, night: true}], + [{at: "2024-06-12T12:00:00Z"}, {}], + [{at: "2024-06-12T23:30:00+02:00"}, {}], + ], +} + +{ + name: "tables: interval and equality cells on a declared date-time", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["at"], properties: {at: {type: "string", format: "date-time"}}}}, + {table: "season", hit: "collect", inputs: ["at"], outputs: ["tag"], rules: [ + ["[d('2024-12-01')..d('2025-03-01'))", "'winter'"], + ["'2024-12-25T00:00:00Z'", "'christmas'"], + ["d('2025-01-01T00:00:00Z')", "'new year'"], + ["> d('2025-03-20')", "'future'"], + ]}, + ], + }, + cases: [ + [{at: "2024-12-25T00:00:00Z"}, [{tag: "winter"}, {tag: "christmas"}]], + [{at: "2025-01-01T00:00:00Z"}, [{tag: "winter"}, {tag: "new year"}]], + [{at: "2025-01-01T01:00:00+01:00"}, [{tag: "winter"}, {tag: "new year"}]], + [{at: "2025-03-01T00:00:00Z"}, []], + [{at: "2025-06-01T00:00:00Z"}, [{tag: "future"}]], + ], +} + +{ + name: "tables: date input column next to a number column, first hit", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["since", "spend"], properties: {since: {type: "string", format: "date"}, spend: {type: "number"}}}}, + {table: "tier", inputs: ["since", "spend"], outputs: ["tier"], rules: [ + ["< d('2020-01-01')", ">= 1000", "'platinum'"], + ["< d('2020-01-01')", "", "'gold'"], + ["", ">= 1000", "'silver'"], + ["", "", "'basic'"], + ]}, + ], + }, + cases: [ + [{since: "2019-12-31", spend: 1000}, {tier: "platinum"}], + [{since: "2019-12-31", spend: 10}, {tier: "gold"}], + [{since: "2020-01-01", spend: 5000}, {tier: "silver"}], + [{since: "2024-06-01", spend: 0}, {tier: "basic"}], + [{since: "2024-06-01", spend: "0"}, "!error: /spend"], + [{since: "never", spend: 0}, "!error: /since"], + ], +} + +{ + name: "tables: loop over items with declared dates and outputs echoing them", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {invoices: {type: "array", items: {type: "object", required: ["due"], properties: {due: {type: "string", format: "date"}, amount: {type: "number"}}}}}}}, + {table: "aging", executionMode: "loop", inputField: "invoices", outputPath: "aging", passThrough: true, inputs: ["d().diff(due, 'day')"], outputs: ["bucket"], rules: [ + ["<= 0", "'current'"], + ["[1..30]", "'1-30'"], + ["", "'30+'"], + ]}, + ], + }, + cases: [ + [{invoices: [{due: "2025-03-25", amount: 1}, {due: "2025-03-01", amount: 2}, {due: "2024-12-01", amount: 3}]}, { + invoices: [{due: "2025-03-25", amount: 1}, {due: "2025-03-01", amount: 2}, {due: "2024-12-01", amount: 3}], + aging: [{due: "2025-03-25", amount: 1, bucket: "current"}, {due: "2025-03-01", amount: 2, bucket: "1-30"}, {due: "2024-12-01", amount: 3, bucket: "30+"}], + }], + [{invoices: []}, {invoices: [], aging: []}], + [{invoices: [{amount: 1}]}, "!error: /invoices/0"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Converted dates crossing node boundaries. +{ + name: "boundaries: a function node receives the source text", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {function: "f", source: """ +export const handler = async (input) => { + return { kind: typeof input.day, day: input.day, len: input.day ? input.day.length : 0 }; +}; +"""}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {kind: "string", day: "2024-01-31", len: 10}], + [{day: "2024/01/31"}, {kind: "string", day: "2024/01/31", len: 10}], + [{}, {kind: "undefined", len: 0}], + ], +} + +{ + name: "boundaries: a function node output is plain text again downstream", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["day"], properties: {day: {type: "string", format: "date"}}}}, + {function: "f", source: """ +export const handler = async (input) => ({ day: input.day }); +"""}, + {expression: "calc", fields: {kind: "type(day)", year: "year(d(day))"}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {kind: "string", year: 2024}], + [{day: "2023-07-04"}, {kind: "string", year: 2023}], + ], +} + +{ + name: "boundaries: a sub-decision without a schema receives the source text", + decisions: { + child: {nodes: [ + {expression: "calc", fields: {kind: "type(day)", next: "d(day).add(1, 'd')"}}, + ]}, + }, + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {kind: "string", next: "2024-02-01T00:00:00Z"}], + [{day: "2024/02/28"}, {kind: "string", next: "2024-02-29T00:00:00Z"}], + ], +} + +{ + name: "boundaries: a sub-decision with its own date schema", + decisions: { + child: {nodes: [ + {input: "in", schema: {type: "object", required: ["day"], properties: {day: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {kind: "type(day)", q: "ceil(monthOfYear(day) / 3)"}}, + ]}, + }, + graph: { + nodes: [ + {expression: "prep", fields: {day: "raw"}}, + {decision: "call", key: "child"}, + ], + }, + cases: [ + [{raw: "2024-01-31"}, {kind: "date", q: 1}], + [{raw: "2024-11-30"}, {kind: "date", q: 4}], + [{raw: "nope"}, "!error: NodeError"], + [{}, "!error: NodeError"], + ], +} + +{ + name: "boundaries: loop sub-decision over date items", + decisions: { + child: {nodes: [ + {input: "in", schema: {type: "object", required: ["on"], properties: {on: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {weekend: "on.weekday() >= 6"}}, + ]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", inputField: "days", executionMode: "loop", outputPath: "flags"}, + ], + }, + cases: [ + [{days: [{on: "2025-03-22"}, {on: "2025-03-24"}]}, {flags: [{weekend: true}, {weekend: false}]}], + [{days: []}, {flags: []}], + [{days: [{on: "2025-03-22"}, {on: "x"}]}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Rendering in the result. +{ + name: "rendering: untouched dates keep their source text, computed dates render as UTC", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["at"], properties: {at: {type: "string", format: "date-time"}}}}, + {expression: "calc", fields: {same: "at", copy: "[at]", wrapped: "{when: at}", moved: "at.add(0, 'd')", utc: "at.tz('UTC')"}}, + ], + }, + cases: [ + [{at: "2024-01-31T10:00:00+02:00"}, {same: "2024-01-31T10:00:00+02:00", copy: ["2024-01-31T10:00:00+02:00"], wrapped: {when: "2024-01-31T10:00:00+02:00"}, moved: "2024-01-31T08:00:00Z", utc: "2024-01-31T08:00:00Z"}], + [{at: "2024-01-31T10:00:00Z"}, {same: "2024-01-31T10:00:00Z", copy: ["2024-01-31T10:00:00Z"], wrapped: {when: "2024-01-31T10:00:00Z"}, moved: "2024-01-31T10:00:00Z", utc: "2024-01-31T10:00:00Z"}], + [{at: "2024-01-31"}, {same: "2024-01-31", copy: ["2024-01-31"], wrapped: {when: "2024-01-31"}, moved: "2024-01-31T00:00:00Z", utc: "2024-01-31T00:00:00Z"}], + ], +} + +{ + name: "rendering: dates in arrays and nested objects pass through unchanged", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: { + days: {type: "array", items: {type: "string", format: "date"}}, + meta: {type: "object", properties: {at: {type: "string", format: "date-time"}}}, + }}}, + ], + }, + cases: [ + [{days: ["2024/01/01", "20240102"], meta: {at: "2024-01-01T00:00:00.5Z"}}, {days: ["2024/01/01", "20240102"], meta: {at: "2024-01-01T00:00:00.5Z"}}], + [{days: []}, {days: []}], + [{meta: {at: "2024-01-01T00:00:00+00:00"}, other: 1}, {meta: {at: "2024-01-01T00:00:00+00:00"}, other: 1}], + [{}, {}], + ], +} + +{ + name: "rendering: passThrough keeps declared dates next to computed fields", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {start: {type: "string", format: "date"}, end: {type: "string", format: "date"}}}}, + {expression: "calc", passThrough: true, fields: {nights: "end.diff(start, 'day')"}}, + ], + }, + cases: [ + [{start: "2025-03-20", end: "2025-03-23"}, {start: "2025-03-20", end: "2025-03-23", nights: 3}], + [{start: "2025-12-30", end: "2026-01-02"}, {start: "2025-12-30", end: "2026-01-02", nights: 3}], + [{start: "2025-03-20", end: "2025-03-20"}, {start: "2025-03-20", end: "2025-03-20", nights: 0}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Rows that mix valid, invalid, null and missing dates, for the batch and columnar engines. +{ + name: "mixed rows: one date column with every presence", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: ["string", "null"], format: "date"}, n: {type: "number"}}}}, + {expression: "calc", fields: {kind: "type(day)", next: "day == null ? null : day.add(n ?? 1, 'd')"}}, + ], + }, + cases: [ + [{day: "2024-01-31", n: 1}, {kind: "date", next: "2024-02-01T00:00:00Z"}], + [{day: null, n: 2}, {kind: "null"}], + [{n: 3}, {kind: "null"}], + [{day: "2024-13-01"}, "!error: /day"], + [{day: "2024-12-31"}, {kind: "date", next: "2025-01-01T00:00:00Z"}], + [{day: 20240101}, "!error: /day"], + [{day: "2024-01-31", n: "1"}, "!error: /n"], + ], +} + +{ + name: "mixed rows: nested date beside plain fields", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["account"], properties: {account: {type: "object", required: ["id"], properties: { + id: {type: "string"}, + opened: {type: "string", format: "date"}, + tier: {type: "string", enum: ["a", "b"]}, + }}}}}, + {expression: "calc", fields: {id: "account.id", years: "account.opened == null ? 0 : d().diff(account.opened, 'year')", tier: "account.tier ?? 'none'"}}, + ], + }, + cases: [ + [{account: {id: "x", opened: "2020-03-20", tier: "a"}}, {id: "x", years: 5, tier: "a"}], + [{account: {id: "y", opened: "2020-03-21"}}, {id: "y", years: 4, tier: "none"}], + [{account: {id: "z"}}, {id: "z", years: 0, tier: "none"}], + [{account: {id: "w", tier: "c"}}, "!error: /account/tier"], + [{account: {id: "v", opened: "2020-02-30"}}, "!error: /account/opened"], + [{account: {opened: "2020-01-01"}}, "!error: /account"], + ], +} + +{ + name: "mixed rows: lists of dates of different lengths", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {days: {type: "array", items: {type: "string", format: "date"}}}}}, + {expression: "calc", fields: {count: "len(days ?? [])", weekend: "len(filter(days ?? [], #.weekday() >= 6))"}}, + ], + }, + cases: [ + [{days: ["2025-03-22", "2025-03-23", "2025-03-24"]}, {count: 3, weekend: 2}], + [{days: []}, {count: 0, weekend: 0}], + [{days: ["2025-03-20"]}, {count: 1, weekend: 0}], + [{}, {count: 0, weekend: 0}], + [{days: ["2025-03-20", "20.03.2025"]}, "!error: /days/1"], + ], +} + +{ + name: "mixed rows: date-looking strings in an undeclared field stay strings next to a declared one", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {due: {type: "string", format: "date"}, label: {type: "string"}}}}, + {expression: "calc", fields: {due: "type(due)", label: "type(label)", same: "due == label"}}, + ], + }, + cases: [ + [{due: "2024-01-01", label: "2024-01-01"}, {due: "date", label: "string", same: true}], + [{due: "2024-01-01", label: "x"}, {due: "date", label: "string", same: false}], + [{label: "2024-01-01"}, {due: "null", label: "string", same: false}], + ], +} + +{ + name: "mixed rows: date values in the request, declared and undeclared", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {due: {type: "string", format: "date-time"}, note: {type: "string"}}}}, + {expression: "calc", fields: {due: "type(due)", other: "type(other)", note: "type(note)"}}, + ], + }, + cases: [ + [{due: date("2024-01-31T00:00:00Z"), other: date("2024-01-31")}, {due: "date", other: "string", note: "null"}], + [{due: "2024-01-31T00:00:00Z", other: "2024-01-31"}, {due: "date", other: "string", note: "null"}], + [{note: date("2024-01-31")}, {due: "null", other: "null", note: "string"}], + [{other: date("2024-01-31")}, {due: "null", other: "string", note: "null"}], + ], +} + +{ + name: "mixed rows: a date format inside not/if subschemas only validates", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {code: {type: "string", not: {format: "date"}}}}}, + {expression: "calc", fields: {kind: "type(code)", n: "len(code ?? '')"}}, + ], + }, + cases: [ + [{code: "ABC"}, {kind: "string", n: 3}], + [{code: "2024-01-01"}, "!error: /code"], + [{code: "2024"}, "!error: /code"], + [{}, {kind: "null", n: 0}], + [{code: "X1"}, {kind: "string", n: 2}], + ], +} + +{ + name: "mixed rows: dates under a pre-check-shaped schema with nested arrays", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["id"], additionalProperties: false, properties: { + id: {type: "string"}, + events: {type: "array", items: {type: "object", required: ["at"], additionalProperties: false, properties: { + at: {type: "string", format: "date-time"}, + kind: {type: "string", enum: ["open", "close"]}, + }}}, + }}}, + {expression: "calc", fields: { + id: "id", + opens: "len(filter(events ?? [], #.kind == 'open'))", + span: "len(events ?? []) < 2 ? 0 : max(map(events, #.at)).diff(min(map(events, #.at)), 'hour')", + }}, + ], + }, + cases: [ + [{id: "a", events: [{at: "2025-03-20T08:00:00Z", kind: "open"}, {at: "2025-03-20T18:00:00Z", kind: "close"}]}, {id: "a", opens: 1, span: 10}], + [{id: "b", events: [{at: "2025-03-20T08:00:00Z"}]}, {id: "b", opens: 0, span: 0}], + [{id: "c"}, {id: "c", opens: 0, span: 0}], + [{id: "d", events: [{at: "2025-03-20T08:00:00Z", kind: "pause"}]}, "!error: /events/0/kind"], + [{id: "e", events: [{at: "2025-03-20T08:00:00Z", extra: 1}]}, "!error: /events/0"], + [{id: "f", events: [{at: "soon"}]}, "!error: /events/0/at"], + [{id: "g", extra: 1}, "!error: NodeError"], + ], +} diff --git a/core/engine/tests/spec/graph/53-output-schemas.json5 b/core/engine/tests/spec/graph/53-output-schemas.json5 new file mode 100644 index 00000000..242c0892 --- /dev/null +++ b/core/engine/tests/spec/graph/53-output-schemas.json5 @@ -0,0 +1,686 @@ +// Output node schemas. +// +// An output node with a schema validates what reaches it (the merge of its incoming edges) after +// the nodes before it ran; a failure is a `NodeError` of the output node naming the failing path. +// The same null-retry rule as on the input node applies, so a null-valued key counts as absent +// for every keyword except `required`. An output schema never converts values (format date does +// not make dates). Chapter 19 covers the basics; this chapter pins output schemas on branching +// graphs (only the branches that reach the output are checked, a branch that fails the schema +// fails only the rows routed to it), several output nodes, non-object results, computed values +// near the keyword boundaries, date values produced upstream, and output schemas of +// sub-decisions in single, loop and nested calls. + +// --------------------------------------------------------------------------------------------- +// Switches: the schema checks whichever branch reached the output. +{ + name: "switch: one branch conforms, the other does not", + graph: { + nodes: [ + {switch: "route", when: ["kind == 'a'", ""]}, + {expression: "good", fields: {price: "base * 2", label: "'A'"}}, + {expression: "bad", fields: {price: "'n/a'", label: "'B'"}}, + {output: "response", schema: {type: "object", required: ["price", "label"], properties: {price: {type: "number"}, label: {type: "string"}}}}, + ], + edges: ["input -> route", "route:0 -> good -> response", "route:1 -> bad -> response"], + }, + cases: [ + [{kind: "a", base: 5}, {price: 10, label: "A"}], + [{kind: "a", base: 0}, {price: 0, label: "A"}], + [{kind: "b", base: 5}, "!error: /price"], + [{base: 5}, "!error: /price"], + [{kind: "a", base: -1.5}, {price: -3, label: "A"}], + ], +} + +{ + name: "switch: a failing branch that is not taken never reaches the schema", + graph: { + nodes: [ + {switch: "route", when: ["amount > 1000", ""]}, + {expression: "review", fields: {status: "'review'", reviewer: "null"}}, + {expression: "auto", fields: {status: "'approved'"}}, + {output: "response", schema: {type: "object", required: ["status"], properties: {status: {enum: ["approved", "review"]}, reviewer: {type: "string"}}}}, + ], + edges: ["input -> route", "route:0 -> review -> response", "route:1 -> auto -> response"], + }, + cases: [ + [{amount: 10}, {status: "approved"}], + [{amount: 1000}, {status: "approved"}], + [{amount: 1001}, {status: "review"}], + [{}, {status: "approved"}], + ], +} + +{ + name: "switch: collect mode merges branches before the schema runs", + graph: { + nodes: [ + {switch: "checks", hit: "collect", when: ["age != null", "income != null"]}, + {expression: "ageCheck", fields: {ageOk: "age >= 18"}}, + {expression: "incomeCheck", fields: {incomeOk: "income >= 1000"}}, + {output: "response", schema: {type: "object", required: ["ageOk", "incomeOk"], properties: {ageOk: {type: "boolean"}, incomeOk: {type: "boolean"}}}}, + ], + edges: ["input -> checks", "checks:0 -> ageCheck -> response", "checks:1 -> incomeCheck -> response"], + }, + cases: [ + [{age: 20, income: 5000}, {ageOk: true, incomeOk: true}], + [{age: 17, income: 10}, {ageOk: false, incomeOk: false}], + [{age: 20}, "!error: incomeOk"], + [{income: 5000}, "!error: ageOk"], + [{}, {}, "question: when no branch reaches the output node its required-key schema never runs and the graph returns an empty result"], + ], +} + +{ + name: "switch: no branch matches and the output is never reached", + graph: { + nodes: [ + {switch: "route", when: ["kind == 'a'"]}, + {expression: "a", fields: {x: "1"}}, + {output: "response", schema: {type: "object", required: ["x"]}}, + ], + edges: ["input -> route", "route:0 -> a -> response"], + }, + cases: [ + [{kind: "a"}, {x: 1}], + [{kind: "b"}, {}, "question: when no branch reaches the output node its required-key schema never runs and the graph returns an empty result"], + [{}, {}, "question: when no branch reaches the output node its required-key schema never runs and the graph returns an empty result"], + ], +} + +{ + name: "switch: a discriminated output schema per branch shape", + graph: { + nodes: [ + {switch: "route", when: ["method == 'card'", "method == 'bank'", ""]}, + {expression: "card", fields: {method: "'card'", last4: "number"}}, + {expression: "bank", fields: {method: "'bank'", iban: "iban"}}, + {expression: "other", fields: {method: "method"}}, + {output: "response", schema: {type: "object", required: ["method"], oneOf: [ + {properties: {method: {const: "card"}}, required: ["last4"]}, + {properties: {method: {const: "bank"}}, required: ["iban"]}, + ]}}, + ], + edges: ["input -> route", "route:0 -> card -> response", "route:1 -> bank -> response", "route:2 -> other -> response"], + }, + cases: [ + [{method: "card", number: "4444"}, {method: "card", last4: "4444"}], + [{method: "bank", iban: "DE001"}, {method: "bank", iban: "DE001"}], + [{method: "bank"}, {method: "bank"}, "question: the bank branch writes {iban: null}, which satisfies `required` in the oneOf, then the null key is dropped from the result"], + [{method: "card"}, {method: "card"}, "question: the card branch writes {last4: null}, which satisfies `required` in the oneOf, then the null key is dropped from the result"], + [{method: "cash"}, "!error: NodeError"], + ], +} + +{ + name: "switch: branches through tables, only the table without a default can miss", + graph: { + nodes: [ + {switch: "route", when: ["segment == 'retail'", ""]}, + {table: "retail", inputs: ["score"], outputs: ["limit"], rules: [ + [">= 700", "5000"], + ["", "1000"], + ]}, + {table: "business", inputs: ["score"], outputs: ["limit"], rules: [ + [">= 700", "50000"], + ["[600..700)", "10000"], + ]}, + {output: "response", schema: {type: "object", required: ["limit"], properties: {limit: {type: "integer", minimum: 1000}}}}, + ], + edges: ["input -> route", "route:0 -> retail -> response", "route:1 -> business -> response"], + }, + cases: [ + [{segment: "retail", score: 750}, {limit: 5000}], + [{segment: "retail", score: 100}, {limit: 1000}], + [{segment: "retail"}, {limit: 1000}], + [{segment: "business", score: 750}, {limit: 50000}], + [{segment: "business", score: 650}, {limit: 10000}], + [{segment: "business", score: 500}, "!error: limit"], + [{segment: "business"}, "!error: limit"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Several output nodes: the first one reached ends the walk. +{ + name: "several outputs: each switch branch has its own output schema", + graph: { + nodes: [ + {switch: "route", when: ["type == 'person'", ""]}, + {expression: "person", fields: {name: "name", age: "age"}}, + {expression: "company", fields: {name: "name", vat: "vat"}}, + {output: "personOut", schema: {type: "object", required: ["name", "age"], properties: {age: {type: "integer", minimum: 0}}}}, + {output: "companyOut", schema: {type: "object", required: ["name", "vat"], properties: {vat: {type: "string", pattern: "^[A-Z]{2}"}}}}, + ], + edges: ["input -> route", "route:0 -> person -> personOut", "route:1 -> company -> companyOut"], + }, + cases: [ + [{type: "person", name: "ann", age: 30}, {name: "ann", age: 30}], + [{type: "person", name: "ann", age: -1}, "!error: /age"], + [{type: "person", name: "ann"}, "!error: age"], + [{type: "company", name: "acme", vat: "DE123"}, {name: "acme", vat: "DE123"}], + [{type: "company", name: "acme", vat: "123"}, "!error: /vat"], + [{type: "company", name: "acme", age: 5}, "!error: vat"], + ], +} + +{ + name: "several outputs: collect switch reaching two outputs", + graph: { + nodes: [ + {switch: "fan", hit: "collect", when: ["true", "true"]}, + {expression: "first", fields: {n: "1"}}, + {expression: "second", fields: {n: "'two'"}}, + {output: "out1", schema: {type: "object", properties: {n: {type: "number"}}}}, + {output: "out2", schema: {type: "object", properties: {n: {type: "number"}}}}, + ], + edges: ["input -> fan", "fan:0 -> first -> out1", "fan:1 -> second -> out2"], + }, + cases: [ + [{}, {n: 1}], + [{x: 1}, {n: 1}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Joins: the schema sees the merge of every incoming edge. +{ + name: "joins: parallel branches complete the required set together", + graph: { + nodes: [ + {expression: "risk", fields: {risk: "(score ?? 1000) < 500 ? 'high' : 'low'"}}, + {table: "price", inputs: ["plan"], outputs: ["price"], rules: [ + ["'basic'", "10"], + ["'pro'", "25"], + ]}, + {output: "response", schema: {type: "object", additionalProperties: false, required: ["risk", "price"], properties: {risk: {enum: ["low", "high"]}, price: {type: "number"}}}}, + ], + edges: ["input -> risk -> response", "input -> price -> response"], + }, + cases: [ + [{score: 700, plan: "basic"}, {risk: "low", price: 10}], + [{score: 100, plan: "pro"}, {risk: "high", price: 25}], + [{score: 100, plan: "enterprise"}, "!error: price"], + [{plan: "basic"}, {risk: "low", price: 10}], + ], +} + +{ + name: "joins: an input edge straight to the output leaks request keys", + graph: { + nodes: [ + {expression: "calc", fields: {total: "a + b"}}, + {output: "response", schema: {type: "object", additionalProperties: false, properties: {total: {type: "number"}, a: {type: "number"}, b: {type: "number"}}}}, + ], + edges: ["input -> calc -> response", "input -> response"], + }, + cases: [ + [{a: 1, b: 2}, {a: 1, b: 2, total: 3}], + [{a: 1, b: 2, c: 3}, "!error: NodeError"], + [{a: 1, b: 2, c: null}, {a: 1, b: 2, total: 3}], + ], +} + +{ + name: "joins: $nodes is not visible to the output schema", + graph: { + nodes: [ + {expression: "calc", fields: {seen: "$nodes.input.a"}}, + {output: "response", schema: {type: "object", additionalProperties: false, properties: {seen: {}}}}, + ], + }, + cases: [ + [{a: 1}, {seen: 1}], + [{a: "x"}, {seen: "x"}], + [{}, {}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Non-object results. +{ + name: "non-object: a collect table output validated as an array", + graph: { + nodes: [ + {table: "hits", hit: "collect", inputs: ["score"], outputs: ["code"], rules: [ + ["> 10", "'A'"], + ["> 20", "'B'"], + ["> 30", "1"], + ]}, + {output: "response", schema: {type: "array", maxItems: 2, items: {type: "object", required: ["code"], properties: {code: {type: "string"}}}}}, + ], + }, + cases: [ + [{score: 15}, [{code: "A"}]], + [{score: 25}, [{code: "A"}, {code: "B"}]], + [{score: 5}, []], + [{score: 35}, "!error: NodeError"], + ], +} + +// A scalar node result becomes {} (chapter 16), so the output schema sees an empty object. +{ + name: "non-object: a function returning a scalar reaches the schema as an empty object", + graph: { + nodes: [ + {function: "f", source: """ +export const handler = async (input) => input.value; +"""}, + {output: "response", schema: {type: "number", minimum: 0}}, + ], + }, + cases: [ + [{value: 5}, "!error: is not of type"], + [{value: 0}, "!error: is not of type"], + [{value: "5"}, "!error: is not of type"], + ], +} + +{ + name: "non-object: an object schema rejects an array result", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["x"], outputs: ["y"], rules: [["", "1"]]}, + {output: "response", schema: {type: "object"}}, + ], + }, + cases: [ + [{x: 1}, "!error: NodeError"], + [{}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Computed values near keyword boundaries. +{ + name: "computed: decimal arithmetic against multipleOf and maximum", + graph: { + nodes: [ + {expression: "calc", fields: {total: "a + b", share: "a / b"}}, + {output: "response", schema: {type: "object", properties: {total: {type: "number", multipleOf: 0.1, maximum: 1}, share: {type: "number"}}}}, + ], + }, + cases: [ + [{a: 0.1, b: 0.2}, {total: 0.3, share: 0.5}], + [{a: 0.5, b: 0.5}, {total: 1, share: 1}], + [{a: 0.7, b: 0.4}, "!error: /total"], + [{a: 0.05, b: 0.1}, "!error: /total"], + ], +} + +{ + name: "computed: integer type on division and rounding results", + graph: { + nodes: [ + {expression: "calc", fields: {half: "n / 2", rounded: "round(n / 3)", floored: "floor(n / 3)"}}, + {output: "response", schema: {type: "object", properties: {half: {type: "integer"}, rounded: {type: "integer"}, floored: {type: "integer"}}}}, + ], + }, + cases: [ + [{n: 4}, {half: 2, rounded: 1, floored: 1}], + [{n: 10}, {half: 5, rounded: 3, floored: 3}], + [{n: 0}, {half: 0, rounded: 0, floored: 0}], + [{n: 5}, "!error: /half"], + ], +} + +{ + name: "computed: strings built by templates against length and pattern", + graph: { + nodes: [ + {expression: "calc", fields: {ref: "`${prefix}-${id}`"}}, + {output: "response", schema: {type: "object", required: ["ref"], properties: {ref: {type: "string", pattern: "^[A-Z]{2}-[0-9]+$", maxLength: 8}}}}, + ], + }, + cases: [ + [{prefix: "AB", id: 1}, {ref: "AB-1"}], + [{prefix: "AB", id: 12345}, {ref: "AB-12345"}], + [{prefix: "AB", id: 123456}, "!error: /ref"], + [{prefix: "ab", id: 1}, "!error: /ref"], + [{prefix: "AB"}, "!error: /ref"], + ], +} + +{ + name: "computed: a null computed value counts as absent", + graph: { + nodes: [ + {expression: "calc", fields: {discount: "vip == true ? 0.1 : null", total: "price"}}, + {output: "response", schema: {type: "object", required: ["total"], properties: {discount: {type: "number", exclusiveMinimum: 0}, total: {type: "number"}}}}, + ], + }, + cases: [ + [{vip: true, price: 10}, {discount: 0.1, total: 10}], + [{vip: false, price: 10}, {total: 10}], + [{price: 10}, {total: 10}], + [{vip: true}, "!error: /total"], + ], +} + +{ + name: "computed: arrays from map and filter against item schemas", + graph: { + nodes: [ + {expression: "calc", fields: {totals: "map(lines, #.qty * #.price)", big: "filter(lines, #.qty > 5)"}}, + {output: "response", schema: {type: "object", properties: { + totals: {type: "array", items: {type: "number", minimum: 0}}, + big: {type: "array", maxItems: 1}, + }}}, + ], + }, + cases: [ + [{lines: [{qty: 1, price: 2}, {qty: 3, price: 4}]}, {totals: [2, 12], big: []}], + [{lines: [{qty: 6, price: 1}]}, {totals: [6], big: [{qty: 6, price: 1}]}], + [{lines: [{qty: 1, price: -2}]}, "!error: /totals/0"], + [{lines: [{qty: 6, price: 1}, {qty: 7, price: 1}]}, "!error: /big"], + [{lines: []}, {totals: [], big: []}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Date values reaching an output schema. +{ + name: "dates: computed dates satisfy string and date formats", + graph: { + nodes: [ + {expression: "calc", fields: {due: "d(start).add(30, 'd')", day: "d(start).format('%Y-%m-%d')"}}, + {output: "response", schema: {type: "object", required: ["due", "day"], properties: { + due: {type: "string", format: "date-time"}, + day: {type: "string", format: "date"}, + }}}, + ], + }, + cases: [ + [{start: "2025-01-01"}, {due: "2025-01-31T00:00:00Z", day: "2025-01-01"}], + [{start: "2024-02-15T12:00:00Z"}, {due: "2024-03-16T12:00:00Z", day: "2024-02-15"}], + ], +} + +{ + name: "dates: declared input dates validated again on the output", + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["day"], properties: {day: {type: "string", format: "date"}}}}, + {expression: "calc", passThrough: true, fields: {next: "day.add(1, 'd')"}}, + {output: "response", schema: {type: "object", additionalProperties: false, required: ["day", "next"], properties: { + day: {type: "string", pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"}, + next: {type: "string", format: "date-time"}, + }}}, + ], + }, + cases: [ + [{day: "2024-01-31"}, {day: "2024-01-31", next: "2024-02-01T00:00:00Z"}], + [{day: "2024-12-31"}, {day: "2024-12-31", next: "2025-01-01T00:00:00Z"}], + [{day: "2024/12/31"}, "!error: /day"], + [{day: "20241231"}, "!error: /day"], + ], +} + +{ + name: "dates: a date value against a non-string type fails", + graph: { + nodes: [ + {expression: "calc", fields: {at: "d(raw)"}}, + {output: "response", schema: {type: "object", properties: {at: {type: "object"}}}}, + ], + }, + cases: [ + [{raw: "2024-01-01"}, "!error: /at"], + [{raw: "2024-01-01T10:00:00Z"}, "!error: /at"], + ], +} + +{ + name: "dates: an enum of date texts compares with the rendered text", + graph: { + nodes: [ + {input: "request", schema: {type: "object", properties: {day: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {same: "day", moved: "day.add(0, 'd')"}}, + {output: "response", schema: {type: "object", properties: { + same: {enum: ["2024-01-01", "2024-06-01"]}, + moved: {enum: ["2024-01-01T00:00:00Z"]}, + }}}, + ], + }, + cases: [ + [{day: "2024-01-01"}, {same: "2024-01-01", moved: "2024-01-01T00:00:00Z"}], + [{day: "2024-06-01"}, "!error: /moved"], + [{day: "2024/01/01"}, "!error: /same"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Sub-decisions. +{ + name: "sub-decision: the child's output schema fails only the rows that break it", + decisions: { + child: {nodes: [ + {table: "grade", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 75", "'B'"], + [">= 50", "'C'"], + ]}, + {output: "out", schema: {type: "object", required: ["grade"], properties: {grade: {enum: ["A", "B", "C"]}}}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", outputPath: "result"}], + }, + cases: [ + [{score: 95}, {result: {grade: "A"}}], + [{score: 80}, {result: {grade: "B"}}], + [{score: 50}, {result: {grade: "C"}}], + [{score: 49}, "!error: grade"], + [{}, "!error: grade"], + ], +} + +{ + name: "sub-decision: loop items where one item fails the child's output schema", + decisions: { + child: {nodes: [ + {expression: "e", fields: {net: "gross - fee"}}, + {output: "out", schema: {type: "object", required: ["net"], properties: {net: {type: "number", minimum: 0}}}}, + ]}, + }, + graph: { + nodes: [{decision: "call", key: "child", inputField: "payments", executionMode: "loop", outputPath: "nets"}], + }, + cases: [ + [{payments: [{gross: 10, fee: 1}, {gross: 5, fee: 5}]}, {nets: [{net: 9}, {net: 0}]}], + [{payments: []}, {nets: []}], + [{payments: [{gross: 10, fee: 1}, {gross: 1, fee: 2}]}, "!error: /net"], + [{payments: [{gross: 10}]}, "!error: NodeError"], + ], +} + +{ + name: "sub-decision: parent and child output schemas both apply", + decisions: { + child: {nodes: [ + {expression: "e", fields: {score: "x * 10"}}, + {output: "out", schema: {type: "object", properties: {score: {type: "number", maximum: 100}}}}, + ]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {output: "response", schema: {type: "object", required: ["score"], properties: {score: {type: "number", minimum: 10}}}}, + ], + }, + cases: [ + [{x: 1}, {score: 10}], + [{x: 10}, {score: 100}], + [{x: 11}, "!error: /score"], + [{x: 0.5}, "!error: /score"], + [{x: 0}, "!error: /score"], + ], +} + +{ + name: "sub-decision: a child output schema on a branch that is not taken", + decisions: { + strict: {nodes: [ + {expression: "e", fields: {v: "'x'"}}, + {output: "out", schema: {type: "object", properties: {v: {type: "number"}}}}, + ]}, + }, + graph: { + nodes: [ + {switch: "route", when: ["useStrict == true", ""]}, + {decision: "call", key: "strict"}, + {expression: "plain", fields: {v: "1"}}, + ], + edges: ["input -> route", "route:0 -> call -> output", "route:1 -> plain -> output"], + }, + cases: [ + [{}, {v: 1}], + [{useStrict: false}, {v: 1}], + [{useStrict: true}, "!error: /v"], + ], +} + +{ + name: "sub-decision: two levels deep, the innermost output schema fails", + decisions: { + inner: {nodes: [ + {expression: "e", fields: {code: "upper(raw)"}}, + {output: "out", schema: {type: "object", required: ["code"], properties: {code: {type: "string", minLength: 3}}}}, + ]}, + middle: {nodes: [ + {decision: "callInner", key: "inner", outputPath: "inner"}, + {output: "out", schema: {type: "object", required: ["inner"]}}, + ]}, + }, + graph: { + nodes: [{decision: "callMiddle", key: "middle"}], + }, + cases: [ + [{raw: "abc"}, {inner: {code: "ABC"}}], + [{raw: "abcd"}, {inner: {code: "ABCD"}}], + [{raw: "ab"}, "!error: /code"], + ], +} + +{ + name: "sub-decision: child output schema with a date it produced", + decisions: { + child: {nodes: [ + {input: "in", schema: {type: "object", required: ["start"], properties: {start: {type: "string", format: "date"}}}}, + {expression: "e", fields: {end: "start.add(months, 'M')"}}, + {output: "out", schema: {type: "object", required: ["end"], properties: {end: {type: "string", format: "date-time"}}}}, + ]}, + }, + graph: { + nodes: [ + {decision: "call", key: "child", outputPath: "term", passThrough: true}, + {expression: "after", fields: {endYear: "year(d(term.end))", kind: "type(term.end)"}}, + ], + }, + cases: [ + [{start: "2024-01-31", months: 1}, {endYear: 2024, kind: "date"}, "question: a date produced inside the child crosses back to the parent as a date value, while the request sent into a child is normalized to text"], + [{start: "2024-11-30", months: 2}, {endYear: 2025, kind: "date"}, "question: a date produced inside the child crosses back to the parent as a date value, while the request sent into a child is normalized to text"], + [{start: "2024-11-30"}, "!error: NodeError"], + [{start: "x", months: 1}, "!error: /start"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Rows with different outcomes in one suite, for the batch and columnar engines. +{ + name: "mixed rows: a pre-check-shaped output schema over many row shapes", + graph: { + nodes: [ + {expression: "calc", fields: {id: "id", score: "points * weight", tier: "points > 50 ? 'gold' : (points > 10 ? 'silver' : tierHint)"}}, + {output: "response", schema: {type: "object", required: ["id", "score"], additionalProperties: false, properties: { + id: {type: "string"}, + score: {type: "number"}, + tier: {type: "string", enum: ["gold", "silver", "bronze"]}, + }}}, + ], + }, + cases: [ + [{id: "a", points: 60, weight: 1}, {id: "a", score: 60, tier: "gold"}], + [{id: "b", points: 20, weight: 0.5}, {id: "b", score: 10, tier: "silver"}], + [{id: "c", points: 5, weight: 2, tierHint: "bronze"}, {id: "c", score: 10, tier: "bronze"}], + [{id: "d", points: 5, weight: 2}, {id: "d", score: 10}], + [{id: "e", points: 5, weight: 2, tierHint: "tin"}, "!error: /tier"], + [{id: 7, points: 5, weight: 2}, "!error: /id"], + [{points: 5, weight: 2}, "!error: id"], + ], +} + +{ + name: "mixed rows: output schema with nested objects and arrays", + graph: { + nodes: [ + {expression: "calc", fields: {"summary.count": "len(items)", "summary.max": "len(items) > 0 ? max(items) : null", "summary.items": "items"}}, + {output: "response", schema: {type: "object", required: ["summary"], properties: {summary: {type: "object", required: ["count"], properties: { + count: {type: "integer", maximum: 3}, + max: {type: "number"}, + items: {type: "array", items: {type: "number"}}, + }}}}}, + ], + }, + cases: [ + [{items: [1, 2, 3]}, {summary: {count: 3, max: 3, items: [1, 2, 3]}}], + [{items: []}, {summary: {count: 0, max: null, items: []}}], + [{items: [5]}, {summary: {count: 1, max: 5, items: [5]}}], + [{items: [1, 2, 3, 4]}, "!error: /summary/count"], + [{items: ["a"]}, "!error: NodeError"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Parent and child graphs whose input/output nodes share ids and names but not schemas. +{ + name: "same node names: parent and child input schemas are kept apart", + decisions: { + child: {nodes: [ + {input: "request", schema: {type: "object", required: ["code"], properties: {code: {type: "string"}}}}, + {expression: "calc", fields: {code: "code"}}, + {output: "response", schema: {type: "object", properties: {code: {type: "string", minLength: 2}}}}, + ]}, + }, + graph: { + nodes: [ + {input: "request", schema: {type: "object", required: ["n"], properties: {n: {type: "number"}}}}, + {expression: "prep", fields: {code: "string(n)"}}, + {decision: "call", key: "child"}, + {output: "response", schema: {type: "object", required: ["code"], properties: {code: {type: "string", maxLength: 3}}}}, + ], + }, + cases: [ + [{n: 12}, {code: "12"}], + [{n: 123}, {code: "123"}], + [{n: 1}, "!error: /code"], + [{n: 1234}, "!error: /code"], + [{n: "12"}, "!error: /n"], + [{}, "!error: n"], + ], +} + +{ + name: "same node names: one child called from two decision nodes", + decisions: { + child: {nodes: [ + {input: "request", schema: {type: "object", required: ["v"], properties: {v: {type: "integer", minimum: 0}}}}, + {expression: "calc", fields: {w: "v * 2"}}, + {output: "response", schema: {type: "object", properties: {w: {type: "integer", maximum: 100}}}}, + ]}, + }, + graph: { + nodes: [ + {decision: "left", key: "child", inputField: "a", outputPath: "l"}, + {decision: "right", key: "child", inputField: "b", outputPath: "r"}, + ], + edges: ["input -> left -> output", "input -> right -> output"], + }, + cases: [ + [{a: {v: 1}, b: {v: 2}}, {l: {w: 2}, r: {w: 4}}], + [{a: {v: 0}, b: {v: 50}}, {l: {w: 0}, r: {w: 100}}], + [{a: {v: 1}, b: {v: 51}}, "!error: /w"], + [{a: {v: -1}, b: {v: 1}}, "!error: /v"], + [{a: {v: 1}, b: {}}, "!error: v"], + ], +} diff --git a/core/engine/tests/spec/graph/54-null-semantics.json5 b/core/engine/tests/spec/graph/54-null-semantics.json5 new file mode 100644 index 00000000..1b7c4910 --- /dev/null +++ b/core/engine/tests/spec/graph/54-null-semantics.json5 @@ -0,0 +1,873 @@ +// Null, missing and empty values produced by each node kind, and how the next node and the graph +// result see them. +// +// Vocabulary: a key is null when it is present with the value null, missing when it is absent, +// and empty when it holds "", [] or {}. Expressions read null and missing alike (`k == null`, +// `type(k)`, `k ?? d`); only `keys(...)` and `$nodes` presence tell them apart. Table cells read +// a missing field as null. +// +// The rules pinned here: +// - A node's output is stored as produced; nulls inside it are kept. +// - At a join and under passThrough a null deletes the key it lands on (merge-patch), so a null +// written over an existing key becomes missing downstream, while a null written on a fresh key +// with a single parent stays null. +// - The graph result is the merge of the ending nodes into an empty object, which drops +// top-level null keys; nested nulls and nulls inside arrays are kept. +// - A node whose whole output is null (a first-hit table with no match, a function returning +// null) contributes nothing to the next node; its `$nodes` entry is null. +// - A node that did not run (a branch a switch did not take) has no `$nodes` entry and is skipped +// by the join. +// +// Most suites end in an observer node `obs` reporting what it sees at `k`: +// t: type(k), has: whether k is a key of its input, d: k ?? 'dflt'. + +// --- Expression nodes ------------------------------------------------------------------------------ +// A field copies the request's `v`: missing and null both produce a null `k`, which the observer +// sees as a present null (a single parent, no merge over an existing key). +{ + name: "expression: a field producing null, empty or falsy values, seen by the next node", + graph: { + nodes: [ + {expression: "p", fields: {k: "v"}}, + {expression: "obs", fields: {t: "type(k)", has: "'k' in keys($root)", d: "k ?? 'dflt'"}}, + ], + }, + cases: [ + [{}, {d: "dflt", has: true, t: "null"}], + [{v: null}, {d: "dflt", has: true, t: "null"}], + [{v: ""}, {d: "", has: true, t: "string"}], + [{v: 0}, {d: 0, has: true, t: "number"}], + [{v: false}, {d: false, has: true, t: "bool"}], + [{v: []}, {d: [], has: true, t: "array"}], + [{v: {}}, {d: {}, has: true, t: "object"}], + [{v: "x"}, {d: "x", has: true, t: "string"}], + ], +} + +{ + name: "expression: the same values in the graph result, top level and nested", + graph: { + nodes: [{expression: "p", fields: {k: "v", "o.k": "v", list: "[v]"}}], + }, + cases: [ + [{}, {list: [null], o: {k: null}}], + [{v: null}, {list: [null], o: {k: null}}], + [{v: ""}, {k: "", list: [""], o: {k: ""}}], + [{v: 0}, {k: 0, list: [0], o: {k: 0}}], + [{v: []}, {k: [], list: [[]], o: {k: []}}], + [{v: {}}, {k: {}, list: [{}], o: {k: {}}}], + ], +} + +{ + name: "expression: a null field read through $nodes keeps the key", + graph: { + nodes: [ + {expression: "p", fields: {k: "v"}}, + {expression: "mid", fields: {other: "1"}}, + {expression: "obs", fields: { + t: "type($nodes.p.k)", + has: "'k' in keys($nodes.p)", + d: "$nodes.p.k ?? 'dflt'", + midHasK: "'k' in keys($root)", + }}, + ], + }, + cases: [ + [{}, {d: "dflt", has: true, midHasK: false, t: "null"}], + [{v: null}, {d: "dflt", has: true, midHasK: false, t: "null"}], + [{v: ""}, {d: "", has: true, midHasK: false, t: "string"}], + [{v: 0}, {d: 0, has: true, midHasK: false, t: "number"}], + ], +} + +{ + name: "expression with passThrough: a null field deletes the request key", + graph: { + nodes: [ + {expression: "p", passThrough: true, fields: {k: "v"}}, + {expression: "obs", fields: {t: "type(k)", has: "'k' in keys($root)", d: "k ?? 'dflt'"}}, + ], + }, + cases: [ + [{k: "old"}, {d: "dflt", has: false, t: "null"}], + [{k: "old", v: null}, {d: "dflt", has: false, t: "null"}], + [{k: "old", v: ""}, {d: "", has: true, t: "string"}], + [{k: "old", v: 0}, {d: 0, has: true, t: "number"}], + [{v: null}, {d: "dflt", has: false, t: "null"}], + [{k: null}, {d: "dflt", has: false, t: "null"}], + [{k: null, v: false}, {d: false, has: true, t: "bool"}], + ], +} + +{ + name: "expression with passThrough: a nested null deletes only the nested key", + graph: { + nodes: [ + {expression: "p", passThrough: true, fields: {"o.k": "v"}}, + {expression: "obs", fields: {t: "type(o.k)", has: "o != null and 'k' in keys(o)", siblings: "o.s ?? 'none'"}}, + ], + }, + cases: [ + [{o: {k: 1, s: 2}}, {has: false, siblings: 2, t: "null"}], + [{o: {k: 1, s: 2}, v: null}, {has: false, siblings: 2, t: "null"}], + [{o: {s: 2}}, {has: false, siblings: 2, t: "null"}], + [{v: null}, {has: true, siblings: "none", t: "null"}], + [{o: null, v: 3}, {has: true, siblings: "none", t: "number"}], + [{o: {k: null}, v: ""}, {has: true, siblings: "none", t: "string"}], + ], +} + +{ + name: "expression: a field producing null under outputPath", + graph: { + nodes: [ + {expression: "p", outputPath: "out", fields: {k: "v"}}, + {expression: "obs", fields: {t: "type(out.k)", has: "'k' in keys(out)", d: "out.k ?? 'dflt'"}}, + ], + }, + cases: [ + [{}, {d: "dflt", has: true, t: "null"}], + [{v: null}, {d: "dflt", has: true, t: "null"}], + [{v: ""}, {d: "", has: true, t: "string"}], + [{v: false}, {d: false, has: true, t: "bool"}], + ], +} + +// --- First-hit tables ------------------------------------------------------------------------------ +// An output cell that evaluates to null writes a null key; a table with no matching rule outputs +// null as a whole, so the next node sees an empty object and `$nodes.p` is null. +{ + name: "first-hit table: matched with a null output, or not matched at all", + graph: { + nodes: [ + {table: "p", inputs: ["m"], outputs: ["k"], rules: [ + ["'yes'", "v"], + ]}, + {expression: "obs", fields: { + t: "type(k)", + has: "'k' in keys($root)", + d: "k ?? 'dflt'", + ran: "$nodes.p != null", + pt: "type($nodes.p)", + }}, + ], + }, + cases: [ + [{m: "yes", v: "x"}, {d: "x", has: true, pt: "object", ran: true, t: "string"}], + [{m: "yes", v: null}, {d: "dflt", has: true, pt: "object", ran: true, t: "null"}], + [{m: "yes"}, {d: "dflt", has: true, pt: "object", ran: true, t: "null"}], + [{m: "yes", v: ""}, {d: "", has: true, pt: "object", ran: true, t: "string"}], + [{m: "no", v: "x"}, {d: "dflt", has: false, pt: "null", ran: false, t: "null"}], + [{v: "x"}, {d: "dflt", has: false, pt: "null", ran: false, t: "null"}], + [{m: null}, {d: "dflt", has: false, pt: "null", ran: false, t: "null"}], + ], +} + +{ + name: "first-hit table: null output cells in the graph result", + graph: { + nodes: [ + {table: "p", inputs: ["m"], outputs: ["k", "o.k", "list"], rules: [ + ["'yes'", "v", "v", "[v]"], + ]}, + ], + }, + cases: [ + [{m: "yes", v: 1}, {k: 1, list: [1], o: {k: 1}}], + [{m: "yes", v: null}, {list: [null], o: {k: null}}], + [{m: "yes"}, {list: [null], o: {k: null}}], + [{m: "no"}, {}], + ], +} + +{ + name: "first-hit table: an empty output cell writes nothing, a null cell writes null", + graph: { + nodes: [ + {table: "p", inputs: ["m"], outputs: ["a", "b"], rules: [ + ["1", "", "null"], + ["2", "null", ""], + ["", "'x'", "'y'"], + ]}, + {expression: "obs", fields: { + aHas: "'a' in keys($root)", + bHas: "'b' in keys($root)", + a: "a ?? 'dflt'", + b: "b ?? 'dflt'", + }}, + ], + }, + cases: [ + [{m: 1}, {a: "dflt", aHas: false, b: "dflt", bHas: true}], + [{m: 2}, {a: "dflt", aHas: true, b: "dflt", bHas: false}], + [{m: 3}, {a: "x", aHas: true, b: "y", bHas: true}], + ], +} + +{ + name: "first-hit table with outputPath: no match writes a null at the path", + graph: { + nodes: [ + {table: "p", outputPath: "res", inputs: ["m"], outputs: ["k"], rules: [["'yes'", "1"]]}, + {expression: "obs", fields: {t: "type(res)", has: "'res' in keys($root)", d: "res.k ?? 'dflt'"}}, + ], + }, + cases: [ + [{m: "yes"}, {d: 1, has: true, t: "object"}], + [{m: "no"}, {d: "dflt", has: true, t: "null"}], + [{}, {d: "dflt", has: true, t: "null"}], + ], +} + +{ + name: "first-hit table with passThrough: no match keeps the input, a null cell deletes", + graph: { + nodes: [ + {table: "p", passThrough: true, inputs: ["m"], outputs: ["k"], rules: [ + ["'del'", "null"], + ["'set'", "'new'"], + ]}, + {expression: "obs", fields: {t: "type(k)", has: "'k' in keys($root)", d: "k ?? 'dflt'"}}, + ], + }, + cases: [ + [{m: "set", k: "old"}, {d: "new", has: true, t: "string"}], + [{m: "del", k: "old"}, {d: "dflt", has: false, t: "null"}], + [{m: "none", k: "old"}, {d: "old", has: true, t: "string"}], + [{m: "none", k: null}, {d: "dflt", has: true, t: "null"}], + [{m: "none"}, {d: "dflt", has: false, t: "null"}], + [{m: "del"}, {d: "dflt", has: false, t: "null"}], + ], +} + +// --- Collect tables -------------------------------------------------------------------------------- +// A collect table outputs an array of rows; with no hits it outputs an empty array. The next node +// receives that array as its input, so field reads see nothing. +{ + name: "collect table: null cells inside rows and an empty result", + graph: { + nodes: [ + {table: "p", hit: "collect", inputs: ["n"], outputs: ["k"], rules: [ + ["> 0", "v"], + ["> 10", "null"], + ]}, + {expression: "obs", fields: { + rows: "len($nodes.p)", + firstK: "type($nodes.p[0].k)", + nulls: "len(filter($nodes.p, # .k == null))", + }}, + ], + }, + cases: [ + [{n: 5, v: "x"}, {firstK: "string", nulls: 0, rows: 1}], + [{n: 5}, {firstK: "null", nulls: 1, rows: 1}], + [{n: 20, v: 1}, {firstK: "number", nulls: 1, rows: 2}], + [{n: 0}, {firstK: "null", nulls: 0, rows: 0}], + [{}, {firstK: "null", nulls: 0, rows: 0}], + ], +} + +// The node after a collect table receives the row array itself as its input, so a bare field +// read has no object to read from. +{ + name: "collect table: a bare field read on the row array input", + graph: { + nodes: [ + {table: "p", hit: "collect", inputs: ["n"], outputs: ["k"], rules: [["> 0", "v"]]}, + {expression: "obs", fields: {t: "type(k)"}}, + ], + }, + cases: [ + [{n: 5, v: "x"}, "!error", "question: a field read on an array node input fails instead of reading null as it does on a scalar input (chapter 01)"], + [{n: 0}, "!error", "question: a field read on an array node input fails instead of reading null as it does on a scalar input (chapter 01)"], + ], +} + +{ + name: "collect table: rows in the graph result keep their nulls", + graph: { + nodes: [ + {table: "p", hit: "collect", inputs: ["n"], outputs: ["k", "o.k"], rules: [ + ["> 0", "v", "v"], + ["> 10", "null", "1"], + ]}, + ], + }, + cases: [ + [{n: 5, v: 1}, [{k: 1, o: {k: 1}}]], + [{n: 5}, [{k: null, o: {k: null}}]], + [{n: 20}, [{k: null, o: {k: null}}, {k: null, o: {k: 1}}]], + [{n: 0}, []], + ], +} + +{ + name: "collect table under outputPath: empty and null-holding row lists", + graph: { + nodes: [ + {table: "p", hit: "collect", outputPath: "rows", inputs: ["n"], outputs: ["k"], rules: [ + ["> 0", "v"], + ]}, + {expression: "obs", fields: {n: "len(rows)", t: "type(rows)", allNull: "all(rows, # .k == null)"}}, + ], + }, + cases: [ + [{n: 1, v: 2}, {allNull: false, n: 1, t: "array"}], + [{n: 1}, {allNull: true, n: 1, t: "array"}], + [{n: 0}, {allNull: true, n: 0, t: "array"}], + [{n: null}, {allNull: true, n: 0, t: "array"}], + ], +} + +{ + name: "first-hit table with a [] column: a null value is gathered, no match gives an empty list", + graph: { + nodes: [ + {table: "p", inputs: ["n"], outputs: ["tags[]", "k"], rules: [ + ["> 10", "'big'", "1"], + ["> 0", "v", "2"], + ]}, + {expression: "obs", fields: {tags: "tags", t: "type(tags)", k: "k ?? 'dflt'"}}, + ], + }, + cases: [ + [{n: 20, v: "x"}, {k: 1, t: "array", tags: ["big", "x"]}], + [{n: 5, v: "x"}, {k: 2, t: "array", tags: ["x"]}], + [{n: 5, v: null}, {k: 2, t: "array", tags: [null]}], + [{n: 5}, {k: 2, t: "array", tags: [null]}], + [{n: 0}, {k: "dflt", t: "array", tags: []}], + ], +} + +// --- Tables reading null and missing values produced upstream ------------------------------------- +// A table cell cannot tell a null key from a missing one: both read as null. +{ + name: "table cells over a null, deleted or missing key produced upstream", + graph: { + nodes: [ + {expression: "p", passThrough: true, fields: {k: "v"}}, + {table: "cls", inputs: ["k"], outputs: ["cls"], rules: [ + ["null", "'null'"], + ["''", "'empty'"], + ["0", "'zero'"], + ["false", "'false'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{}, {cls: "null"}], + [{v: null}, {cls: "null"}], + [{k: "old", v: null}, {cls: "null"}], + [{v: ""}, {cls: "empty"}], + [{v: 0}, {cls: "zero"}], + [{v: false}, {cls: "false"}], + [{v: "a"}, {cls: "other"}], + ], +} + +{ + name: "table cells over the output of an unmatched table", + graph: { + nodes: [ + {table: "p", inputs: ["m"], outputs: ["k"], rules: [["'yes'", "'hit'"]]}, + {table: "cls", inputs: ["k"], outputs: ["cls"], rules: [ + ["null", "'null'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{m: "yes"}, {cls: "other"}], + [{m: "no"}, {cls: "null"}], + [{m: "no", k: "request"}, {cls: "null"}], + ], +} + +{ + name: "table cells over the output of an unmatched table, beside a field-less column", + graph: { + nodes: [ + {table: "p", inputs: ["m"], outputs: ["k"], rules: [["'yes'", "'hit'"]]}, + {table: "cls", inputs: ["k", null], outputs: ["cls"], rules: [ + ["null", "m != 'zzz'", "'null'"], + ["", "", "'other'"], + ]}, + ], + }, + cases: [ + [{m: "yes"}, {cls: "other"}], + [{m: "no"}, {cls: "null"}], + [{m: "no", k: "request"}, {cls: "null"}], + ], +} + +{ + name: "table cells over the output of an unmatched table, beside a computed cell", + graph: { + nodes: [ + {table: "p", inputs: ["m"], outputs: ["k", "m"], rules: [["'yes'", "'hit'", "'yes'"], ["'no'", "", "'no'"]]}, + {table: "cls", inputs: ["k", "m"], outputs: ["cls"], rules: [ + ["null", "", "'null'"], + ["", "len($) > 0", "'other'"], + ["", "", "'none'"], + ]}, + ], + }, + cases: [ + [{m: "yes"}, {cls: "other"}], + [{m: "no"}, {cls: "null"}], + [{m: "no", k: "request"}, {cls: "null"}], + ], +} + +{ + name: "boolean and number cells over the output of an unmatched table, beside a field-less column", + graph: { + nodes: [ + {table: "p", inputs: ["m"], outputs: ["b", "n"], rules: [["'yes'", "true", "5"]]}, + {table: "cls", inputs: ["b", "n", null], outputs: ["bc", "nc"], rules: [ + ["null", "null", "true", "'null'", "'null'"], + ["true", "> 1", "", "'true'", "'big'"], + ["", "", "", "'other'", "'other'"], + ]}, + ], + }, + cases: [ + [{m: "yes"}, {bc: "true", nc: "big"}], + [{m: "no"}, {bc: "null", nc: "null"}], + ], +} + +{ + name: "an absent request field against a null cell, beside a field-less column", + graph: { + nodes: [ + {table: "cls", inputs: ["k", null], outputs: ["cls"], rules: [ + ["null", "true", "'null'"], + ["", "", "'other'"], + ]}, + ], + }, + cases: [ + [{}, {cls: "null"}], + [{k: null}, {cls: "null"}], + [{k: "a"}, {cls: "other"}], + ], +} + +// --- Switch nodes ---------------------------------------------------------------------------------- +// A switch passes its input on unchanged, nulls included. A branch it does not take never runs: its +// node has no $nodes entry and contributes nothing to a later join. +{ + name: "switch: request nulls pass through the switch unchanged", + graph: { + nodes: [ + {switch: "s", when: ["k == null", ""]}, + {expression: "isNull", fields: {branch: "'null'", has: "'k' in keys($root)"}}, + {expression: "notNull", fields: {branch: "'value'", has: "'k' in keys($root)"}}, + ], + edges: ["input -> s", "s:0 -> isNull -> output", "s:1 -> notNull -> output"], + }, + cases: [ + [{k: null}, {branch: "null", has: true}], + [{}, {branch: "null", has: false}], + [{k: ""}, {branch: "value", has: true}], + [{k: 0}, {branch: "value", has: true}], + ], +} + +{ + name: "switch: a branch not taken is missing from $nodes and from the join", + graph: { + nodes: [ + {switch: "s", when: ["go", ""]}, + {expression: "taken", fields: {k: "v"}}, + {expression: "skipped", fields: {other: "1"}}, + {expression: "obs", fields: { + t: "type(k)", + has: "'k' in keys($root)", + takenRan: "$nodes.taken != null", + takenK: "type($nodes.taken.k)", + skippedRan: "$nodes.skipped != null", + }}, + ], + edges: ["input -> s", "s:0 -> taken -> obs", "s:1 -> skipped -> obs", "obs -> output"], + }, + cases: [ + [{go: true, v: 1}, {has: true, skippedRan: false, t: "number", takenK: "number", takenRan: true}], + [{go: true, v: null}, {has: true, skippedRan: false, t: "null", takenK: "null", takenRan: true}], + [{go: true}, {has: true, skippedRan: false, t: "null", takenK: "null", takenRan: true}], + [{go: false, v: 1}, {has: false, skippedRan: true, t: "null", takenK: "null", takenRan: false}], + [{v: 1}, {has: false, skippedRan: true, t: "null", takenK: "null", takenRan: false}], + ], +} + +{ + name: "switch: a null written by the taken branch over a key from the input", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "A", fields: {k: "null"}}, + {expression: "B", fields: {k: "'b'"}}, + {expression: "obs", fields: {t: "type(k)", has: "'k' in keys($root)", d: "k ?? 'dflt'"}}, + ], + edges: ["input -> s", "s:0 -> A -> obs", "s:1 -> B -> obs", "input -> obs", "obs -> output"], + }, + cases: [ + [{a: true, b: true, k: "req"}, {d: "dflt", has: false, t: "null"}], + [{a: true, b: false, k: "req"}, {d: "dflt", has: false, t: "null"}], + [{a: false, b: true, k: "req"}, {d: "b", has: true, t: "string"}], + [{a: false, b: false, k: "req"}, {d: "req", has: true, t: "string"}], + [{a: true, b: false}, {d: "dflt", has: false, t: "null"}], + ], +} + +// --- Loops ----------------------------------------------------------------------------------------- +// A loop outputs one result per item, nulls included; an empty array gives an empty array. +{ + name: "loop: per-item nulls stay in the result array", + graph: { + nodes: [ + {expression: "p", inputField: "items", outputPath: "out", executionMode: "loop", fields: {k: "v"}}, + {expression: "obs", fields: { + n: "len(out)", + nulls: "len(filter(out, # .k == null))", + keyed: "len(filter(out, 'k' in keys(#)))", + }}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: null}, {}]}, {keyed: 3, n: 3, nulls: 2}], + [{items: [{v: ""}, {v: 0}, {v: false}]}, {keyed: 3, n: 3, nulls: 0}], + [{items: []}, {keyed: 0, n: 0, nulls: 0}], + [{items: [null]}, {keyed: 1, n: 1, nulls: 1}], + ], +} + +{ + name: "loop: in the graph result, nulls inside the array survive", + graph: { + nodes: [ + {expression: "p", inputField: "items", outputPath: "out", executionMode: "loop", fields: {k: "v"}}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: null}, {}]}, {out: [{k: 1}, {k: null}, {k: null}]}], + [{items: []}, {out: []}], + [{items: [{}]}, {out: [{k: null}]}], + ], +} + +{ + name: "loop: an unmatched table per item yields null items", + graph: { + nodes: [ + {table: "p", inputField: "items", outputPath: "out", executionMode: "loop", inputs: ["n"], outputs: ["k"], rules: [ + ["> 0", "'pos'"], + ]}, + {expression: "obs", fields: {n: "len(out)", nullItems: "len(filter(out, # == null))", k: "map(out, # == null ? '-' : #.k)"}}, + ], + }, + cases: [ + [{items: [{n: 1}, {n: -1}, {}]}, {k: ["pos", "-", "-"], n: 3, nullItems: 2}], + [{items: [{n: -1}]}, {k: ["-"], n: 1, nullItems: 1}], + [{items: []}, {k: [], n: 0, nullItems: 0}], + ], +} + +{ + name: "loop: with passThrough a null per-item field deletes the item key", + graph: { + nodes: [ + {expression: "p", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {k: "v"}}, + ], + }, + cases: [ + [{items: [{k: "old", v: null}, {k: "old", v: 1}, {k: "old"}]}, {items: [{v: null}, {k: 1, v: 1}, {}]}], + [{items: [{v: null}]}, {items: [{v: null}]}], + [{items: []}, {items: []}], + ], +} + +{ + name: "loop: null, missing and empty sources", + graph: { + nodes: [ + {expression: "p", inputField: "items ?? []", outputPath: "out", executionMode: "loop", fields: {k: "v"}}, + {expression: "obs", fields: {n: "len(out)", t: "type(out)"}}, + ], + }, + cases: [ + [{items: null}, {n: 0, t: "array"}], + [{}, {n: 0, t: "array"}], + [{items: []}, {n: 0, t: "array"}], + [{items: [{v: null}]}, {n: 1, t: "array"}], + ], +} + +// --- Sub-decisions --------------------------------------------------------------------------------- +// A sub-decision returns its graph result, so its top-level nulls are already dropped: the parent +// sees them as missing. Nested nulls cross the boundary. +{ + name: "sub-decision: top-level nulls of the child arrive missing, nested ones null", + decisions: { + child: {nodes: [{expression: "c", fields: {k: "v", "o.k": "v", list: "[v]"}}]}, + }, + graph: { + nodes: [ + {decision: "p", key: "child"}, + {expression: "obs", fields: { + has: "'k' in keys($root)", + nestedHas: "'k' in keys(o)", + nested: "type(o.k)", + list: "list", + viaNodes: "'k' in keys($nodes.p)", + }}, + ], + }, + cases: [ + [{v: 1}, {has: true, list: [1], nested: "number", nestedHas: true, viaNodes: true}], + [{v: null}, {has: false, list: [null], nested: "null", nestedHas: true, viaNodes: false}], + [{}, {has: false, list: [null], nested: "null", nestedHas: true, viaNodes: false}], + [{v: ""}, {has: true, list: [""], nested: "string", nestedHas: true, viaNodes: true}], + ], +} + +{ + name: "sub-decision: a child whose table matches nothing", + decisions: { + child: {nodes: [{table: "t", inputs: ["m"], outputs: ["k"], rules: [["'yes'", "1"]]}]}, + }, + graph: { + nodes: [ + {decision: "p", key: "child"}, + {expression: "obs", fields: {t: "type($nodes.p)", d: "k ?? 'dflt'", n: "len(keys($nodes.p ?? {}))"}}, + ], + }, + cases: [ + [{m: "yes"}, {d: 1, n: 1, t: "object"}], + [{m: "no"}, {d: "dflt", n: 0, t: "object"}], + [{}, {d: "dflt", n: 0, t: "object"}], + ], +} + +{ + name: "sub-decision with passThrough: a child's top-level null cannot delete a parent key", + decisions: { + child: {nodes: [{expression: "c", fields: {k: "v"}}]}, + }, + graph: { + nodes: [ + {decision: "p", key: "child", passThrough: true}, + {expression: "obs", fields: {t: "type(k)", d: "k ?? 'dflt'"}}, + ], + }, + cases: [ + [{k: "old", v: "new"}, {d: "new", t: "string"}], + [{k: "old", v: null}, {d: "old", t: "string"}], + [{k: "old"}, {d: "old", t: "string"}], + [{v: null}, {d: "dflt", t: "null"}], + ], +} + +{ + name: "sub-decision with outputPath: a child returning nothing", + decisions: { + child: {nodes: [{expression: "c", fields: {k: "v"}}]}, + }, + graph: { + nodes: [ + {decision: "p", key: "child", outputPath: "res"}, + {expression: "obs", fields: {t: "type(res)", n: "len(keys(res))", d: "res.k ?? 'dflt'"}}, + ], + }, + cases: [ + [{v: 1}, {d: 1, n: 1, t: "object"}], + [{v: null}, {d: "dflt", n: 0, t: "object"}], + [{}, {d: "dflt", n: 0, t: "object"}], + ], +} + +// --- Function nodes -------------------------------------------------------------------------------- +// A v2 function's result is converted as it is: null and undefined properties both arrive as null. +// A function returning null or undefined as a whole contributes nothing. +{ + name: "function: null, undefined and empty properties", + graph: { + nodes: [ + {function: "p", source: """export const handler = async (input) => ({ k: input.v, u: undefined, n: null, e: '', o: {}, a: [] });"""}, + {expression: "obs", fields: { + t: "type(k)", + has: "'k' in keys($root)", + uHas: "'u' in keys($root)", + u: "type(u)", + n: "type(n)", + e: "e ?? 'dflt'", + o: "o", + a: "a", + }}, + ], + }, + cases: [ + [{v: 1}, {a: [], e: "", has: true, n: "null", o: {}, t: "number", u: "null", uHas: true}], + [{v: null}, {a: [], e: "", has: true, n: "null", o: {}, t: "null", u: "null", uHas: true}], + [{}, {a: [], e: "", has: true, n: "null", o: {}, t: "null", u: "null", uHas: true}], + ], +} + +{ + name: "function: null and undefined properties in the graph result", + graph: { + nodes: [ + {function: "p", source: """export const handler = async (input) => ({ k: input.v, u: undefined, nested: { k: input.v, u: undefined }, list: [input.v, undefined, null] });"""}, + ], + }, + cases: [ + [{v: 1}, {k: 1, list: [1, null, null], nested: {k: 1, u: null}}], + [{v: null}, {list: [null, null, null], nested: {k: null, u: null}}], + [{}, {list: [null, null, null], nested: {k: null, u: null}}], + ], +} + +{ + name: "function: returning null or undefined as a whole", + graph: { + nodes: [ + {function: "p", source: """export const handler = async (input) => input.mode === 'null' ? null : input.mode === 'undef' ? undefined : input.mode === 'empty' ? {} : { k: 1 };"""}, + {expression: "obs", fields: {t: "type($nodes.p)", d: "k ?? 'dflt'"}}, + ], + }, + cases: [ + [{mode: "null"}, {d: "dflt", t: "null"}], + [{mode: "undef"}, {d: "dflt", t: "null"}], + [{mode: "empty"}, {d: "dflt", t: "object"}], + [{mode: "obj"}, {d: 1, t: "object"}], + ], +} + +{ + name: "function: the function sees null and missing request keys differently", + graph: { + nodes: [ + {function: "p", source: """export const handler = async (input) => ({ inKeys: 'k' in input, isNull: input.k === null, isUndef: input.k === undefined, t: typeof input.k });"""}, + ], + }, + cases: [ + [{k: null}, {inKeys: true, isNull: true, isUndef: false, t: "object"}], + [{}, {inKeys: false, isNull: false, isUndef: true, t: "undefined"}], + [{k: ""}, {inKeys: true, isNull: false, isUndef: false, t: "string"}], + [{k: 0}, {inKeys: true, isNull: false, isUndef: false, t: "number"}], + ], +} + +{ + name: "function: a null written upstream with passThrough arrives deleted", + graph: { + nodes: [ + {expression: "e", passThrough: true, fields: {k: "v"}}, + {function: "p", source: """export const handler = async (input) => ({ inKeys: 'k' in input, isNull: input.k === null });"""}, + ], + }, + cases: [ + [{k: "old", v: null}, {inKeys: false, isNull: false}], + [{v: null}, {inKeys: false, isNull: false}], + [{k: null}, {inKeys: false, isNull: false}], + [{k: "old", v: 1}, {inKeys: true, isNull: false}], + ], +} + +// --- Custom nodes ---------------------------------------------------------------------------------- +// The `config` adapter returns its configuration verbatim, nulls included; `render` writes a null +// for a template field it cannot resolve. +{ + name: "custom: a config with null and empty values, seen by the next node", + graph: { + nodes: [ + {custom: "p", kind: "config", config: {k: null, e: "", o: {k: null}, a: [null]}}, + {expression: "obs", fields: { + has: "'k' in keys($root)", + t: "type(k)", + e: "e ?? 'dflt'", + ok: "'k' in keys(o)", + a: "a", + x: "x ?? 'dflt'", + }}, + ], + }, + cases: [ + [{}, {a: [null], e: "", has: true, ok: true, t: "null", x: "dflt"}], + [{k: 1}, {a: [null], e: "", has: true, ok: true, t: "null", x: "dflt"}], + [{x: null}, {a: [null], e: "", has: true, ok: true, t: "null", x: "dflt"}], + ], +} + +{ + name: "custom: config nulls in the graph result", + graph: { + nodes: [{custom: "p", kind: "config", config: {k: null, e: "", o: {k: null}, a: [null]}}], + }, + cases: [ + [{}, {a: [null], e: "", o: {k: null}}], + [{k: 1}, {a: [null], e: "", o: {k: null}}], + ], +} + +{ + name: "custom: echo carries request nulls to the next node", + graph: { + nodes: [ + {custom: "p", kind: "echo", config: {}}, + {expression: "obs", fields: {t: "type(k)", has: "'k' in keys($root)", d: "k ?? 'dflt'"}}, + ], + }, + cases: [ + [{k: null}, {d: "dflt", has: true, t: "null"}], + [{}, {d: "dflt", has: false, t: "null"}], + [{k: ""}, {d: "", has: true, t: "string"}], + ], +} + +// --- The graph result: top level versus nested ------------------------------------------------------ +// Every producer above, writing null both at the top level and one level down, merged into one +// result: only the top-level keys disappear. +{ + name: "result: top-level nulls from every node kind are dropped, nested ones kept", + graph: { + nodes: [ + {expression: "e", fields: {e: "null", "eo.k": "null"}}, + {table: "t", inputs: [""], outputs: ["t", "to.k"], rules: [["", "null", "null"]]}, + {function: "f", source: """export const handler = async () => ({ f: null, fo: { k: null } });"""}, + {custom: "c", kind: "config", config: {c: null, co: {k: null}}}, + ], + edges: ["input -> e -> output", "input -> t -> output", "input -> f -> output", "input -> c -> output"], + }, + cases: [ + [{}, {co: {k: null}, eo: {k: null}, fo: {k: null}, to: {k: null}}], + [{e: 1, t: 1, f: 1, c: 1}, {co: {k: null}, eo: {k: null}, fo: {k: null}, to: {k: null}}], + ], +} + +{ + name: "result: a null deep inside arrays and objects survives", + graph: { + nodes: [{expression: "e", fields: {deep: "{a: [{b: null}, null, [null]], c: {d: {e: null}}}"}}], + }, + cases: [ + [{}, {deep: {a: [{b: null}, null, [null]], c: {d: {e: null}}}}], + ], +} + +{ + name: "result: a top-level null written by the output node's only parent with passThrough", + graph: { + nodes: [{expression: "e", passThrough: true, fields: {k: "v"}}], + }, + cases: [ + [{k: 1, v: null}, {}], + [{v: null}, {}], + [{k: null, v: null}, {}], + [{v: {x: null}}, {k: {x: null}, v: {x: null}}], + ], +} diff --git a/core/engine/tests/spec/graph/55-merge-matrix.json5 b/core/engine/tests/spec/graph/55-merge-matrix.json5 new file mode 100644 index 00000000..60b23f9c --- /dev/null +++ b/core/engine/tests/spec/graph/55-merge-matrix.json5 @@ -0,0 +1,679 @@ +// Merge matrix: every kind of value meeting at a join, for two and three parents, in both +// edge orders, with and without passThrough. Kinds are object, array, scalar (number, string, +// boolean), null and missing. +// +// The rules pinned here (chapter 10 introduces them with hand-written graphs): +// - A join merges its parents' outputs in reverse edge order: the parent whose edge into the +// join was declared first is merged last and wins conflicts. +// - The first parent merged (the last declared) becomes the head when it is an object or an +// array; any other value starts the merge from an empty object. +// - A later object patch deep-merges into an object, and replaces an array or a scalar. +// - A later array patch replaces whatever was merged so far, objects included. +// - A later scalar or null patch at the top level is ignored: a node producing nothing +// object-like does not erase its siblings. +// - Below the top level, values are merge-patched: objects deep-merge, everything else +// replaces, a null deletes the key. +// - The graph result is the merge of the ending nodes into an empty object, which drops +// top-level nulls; a downstream node still sees a null that survived the join. +// +// Parents are mostly v2 function nodes returning `input.a`, so one graph produces every kind +// from the request. A function returning a missing property returns undefined, which the +// engine treats like null. Natural producers (tables, switches, loops) close the chapter. + +// --- Top-level kinds, two parents, observed in the graph result --------------------------------- +// The edge from `a` is declared first, so `a` wins. Each suite fixes the kind `a` returns and runs +// `b` through every kind. +{ + name: "top level: the winner is an object, the loser every kind", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{a: {k: "a", z: 1}, b: {y: 2}, x: 0}, {k: "a", y: 2, z: 1}], + [{a: {k: "a", z: 1}, b: {k: "b"}, x: 0}, {k: "a", z: 1}], + [{a: {k: "a", z: 1}, b: {}, x: 0}, {k: "a", z: 1}], + [{a: {k: "a", z: 1}, b: [1, 2], x: 0}, {k: "a", z: 1}], + [{a: {k: "a", z: 1}, b: [], x: 0}, {k: "a", z: 1}], + [{a: {k: "a", z: 1}, b: 7, x: 0}, {k: "a", z: 1}], + [{a: {k: "a", z: 1}, b: "s", x: 0}, {k: "a", z: 1}], + [{a: {k: "a", z: 1}, b: true, x: 0}, {k: "a", z: 1}], + [{a: {k: "a", z: 1}, b: null, x: 0}, {k: "a", z: 1}], + [{a: {k: "a", z: 1}, x: 0}, {k: "a", z: 1}], + ], +} + +{ + name: "top level: the winner is an array, the loser every kind", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{a: ["a"], b: {y: 2}, x: 0}, ["a"]], + [{a: [{k: "a"}], b: {k: "b"}, x: 0}, [{k: "a"}]], + [{a: ["a"], b: {}, x: 0}, ["a"]], + [{a: [{k: "a"}], b: [1, 2], x: 0}, [{k: "a"}]], + [{a: ["a"], b: [], x: 0}, ["a"]], + [{a: [{k: "a"}], b: 7, x: 0}, [{k: "a"}]], + [{a: ["a"], b: "s", x: 0}, ["a"]], + [{a: [{k: "a"}], b: true, x: 0}, [{k: "a"}]], + [{a: ["a"], b: null, x: 0}, ["a"]], + [{a: [{k: "a"}], x: 0}, [{k: "a"}]], + ], +} + +{ + name: "top level: the winner is a scalar, the loser every kind", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{a: 5, b: {y: 2}, x: 0}, {y: 2}], + [{a: "a", b: {k: "b"}, x: 0}, {k: "b"}], + [{a: false, b: {}, x: 0}, {}], + [{a: 5, b: [1, 2], x: 0}, [1, 2]], + [{a: "a", b: [], x: 0}, []], + [{a: false, b: 7, x: 0}, {}], + [{a: 5, b: "s", x: 0}, {}], + [{a: "a", b: true, x: 0}, {}], + [{a: false, b: null, x: 0}, {}], + [{a: 5, x: 0}, {}], + ], +} + +{ + name: "top level: the winner is null, the loser every kind", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{a: null, b: {y: 2}, x: 0}, {y: 2}], + [{a: null, b: {k: "b"}, x: 0}, {k: "b"}], + [{a: null, b: {}, x: 0}, {}], + [{a: null, b: [1, 2], x: 0}, [1, 2]], + [{a: null, b: [], x: 0}, []], + [{a: null, b: 7, x: 0}, {}], + [{a: null, b: "s", x: 0}, {}], + [{a: null, b: true, x: 0}, {}], + [{a: null, b: null, x: 0}, {}], + [{a: null, x: 0}, {}], + ], +} + +{ + name: "top level: the winner is missing, the loser every kind", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{b: {y: 2}, x: 0}, {y: 2}], + [{b: {k: "b"}, x: 0}, {k: "b"}], + [{b: {}, x: 0}, {}], + [{b: [1, 2], x: 0}, [1, 2]], + [{b: [], x: 0}, []], + [{b: 7, x: 0}, {}], + [{b: "s", x: 0}, {}], + [{b: true, x: 0}, {}], + [{b: null, x: 0}, {}], + [{x: 0}, {}], + ], +} + +// The same pairs with the edges declared in the other order: the roles of `a` and `b` swap +// although the node list is unchanged. +{ + name: "top level: edges declared b first, b wins", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + ], + edges: ["input -> b -> output", "input -> a -> output"], + }, + cases: [ + [{a: {k: "a"}, b: {k: "b"}, x: 0}, {k: "b"}], + [{a: {k: "a"}, b: [1], x: 0}, [1]], + [{a: [1], b: {k: "b"}, x: 0}, {k: "b"}], + [{a: {k: "a"}, b: 5, x: 0}, {k: "a"}], + [{a: 5, b: {k: "b"}, x: 0}, {k: "b"}], + [{a: [1], b: [2, 3], x: 0}, [2, 3]], + [{a: [1], b: null, x: 0}, [1]], + [{a: null, b: [1], x: 0}, [1]], + [{a: "s", b: "t", x: 0}, {}], + [{b: {k: "b"}, x: 0}, {k: "b"}], + ], +} + +// --- Top-level kinds observed by a node after the join ------------------------------------------- +// The join node reports what it received: its type and the value itself under `seen`. +{ + name: "join node: what a node after a two-parent join receives", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + {function: "j", source: """export const handler = async (input) => ({ t: Array.isArray(input) ? "array" : typeof input, seen: input });"""}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{a: {k: "a"}, b: {k: "b", y: 1}, x: 0}, {seen: {k: "a", y: 1}, t: "object"}], + [{a: {k: "a"}, b: [1], x: 0}, {seen: {k: "a"}, t: "object"}], + [{a: [1], b: {k: "b"}, x: 0}, {seen: [1], t: "array"}], + [{a: [1], b: [2], x: 0}, {seen: [1], t: "array"}], + [{a: [], b: {k: "b"}, x: 0}, {seen: [], t: "array"}], + [{a: {}, b: [1], x: 0}, {seen: {}, t: "object"}], + [{a: 7, b: {k: "b"}, x: 0}, {seen: {k: "b"}, t: "object"}], + [{a: {k: "a"}, b: 7, x: 0}, {seen: {k: "a"}, t: "object"}], + [{a: 7, b: [1], x: 0}, {seen: [1], t: "array"}], + [{a: null, b: null, x: 0}, {seen: {}, t: "object"}], + [{x: 0}, {seen: {}, t: "object"}], + [{a: "s", b: true, x: 0}, {seen: {}, t: "object"}], + ], +} + +// --- Key-level kinds: both parents return an object holding `k` (or not) ------------------------- +// Below the top level a scalar or null is a value like any other: a scalar replaces, a null +// deletes, missing leaves the loser alone. The node after the join reports what it sees at `k`. +{ + name: "key level at a join: the winner's k is an object", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ('a' in input ? { k: input.a } : {});"""}, + {function: "b", source: """export const handler = async (input) => ('b' in input ? { k: input.b } : {});"""}, + {expression: "j", fields: {t: "type(k)", has: "'k' in keys($root)", v: "k"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{a: {q: 2}, b: {p: 1}, x: 0}, {has: true, t: "object", v: {p: 1, q: 2}}], + [{a: {q: 2}, b: [1], x: 0}, {has: true, t: "object", v: {q: 2}}], + [{a: {q: 2}, b: 2, x: 0}, {has: true, t: "object", v: {q: 2}}], + [{a: {q: 2}, b: "s", x: 0}, {has: true, t: "object", v: {q: 2}}], + [{a: {q: 2}, b: null, x: 0}, {has: true, t: "object", v: {q: 2}}], + [{a: {q: 2}, x: 0}, {has: true, t: "object", v: {q: 2}}], + ], +} + +{ + name: "key level at a join: the winner's k is an array", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ('a' in input ? { k: input.a } : {});"""}, + {function: "b", source: """export const handler = async (input) => ('b' in input ? { k: input.b } : {});"""}, + {expression: "j", fields: {t: "type(k)", has: "'k' in keys($root)", v: "k"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{a: ["a"], b: {p: 1}, x: 0}, {has: true, t: "array", v: ["a"]}], + [{a: ["a"], b: [1], x: 0}, {has: true, t: "array", v: ["a"]}], + [{a: ["a"], b: 2, x: 0}, {has: true, t: "array", v: ["a"]}], + [{a: ["a"], b: "s", x: 0}, {has: true, t: "array", v: ["a"]}], + [{a: ["a"], b: null, x: 0}, {has: true, t: "array", v: ["a"]}], + [{a: ["a"], x: 0}, {has: true, t: "array", v: ["a"]}], + ], +} + +{ + name: "key level at a join: the winner's k is a scalar", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ('a' in input ? { k: input.a } : {});"""}, + {function: "b", source: """export const handler = async (input) => ('b' in input ? { k: input.b } : {});"""}, + {expression: "j", fields: {t: "type(k)", has: "'k' in keys($root)", v: "k"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{a: 9, b: {p: 1}, x: 0}, {has: true, t: "number", v: 9}], + [{a: "a", b: [1], x: 0}, {has: true, t: "string", v: "a"}], + [{a: true, b: 2, x: 0}, {has: true, t: "bool", v: true}], + [{a: 9, b: "s", x: 0}, {has: true, t: "number", v: 9}], + [{a: "a", b: null, x: 0}, {has: true, t: "string", v: "a"}], + [{a: true, x: 0}, {has: true, t: "bool", v: true}], + ], +} + +{ + name: "key level at a join: the winner's k is null", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ('a' in input ? { k: input.a } : {});"""}, + {function: "b", source: """export const handler = async (input) => ('b' in input ? { k: input.b } : {});"""}, + {expression: "j", fields: {t: "type(k)", has: "'k' in keys($root)", v: "k"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{a: null, b: {p: 1}, x: 0}, {has: false, t: "null"}], + [{a: null, b: [1], x: 0}, {has: false, t: "null"}], + [{a: null, b: 2, x: 0}, {has: false, t: "null"}], + [{a: null, b: "s", x: 0}, {has: false, t: "null"}], + [{a: null, b: null, x: 0}, {has: false, t: "null"}], + [{a: null, x: 0}, {has: false, t: "null"}], + ], +} + +{ + name: "key level at a join: the winner's k is missing", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ('a' in input ? { k: input.a } : {});"""}, + {function: "b", source: """export const handler = async (input) => ('b' in input ? { k: input.b } : {});"""}, + {expression: "j", fields: {t: "type(k)", has: "'k' in keys($root)", v: "k"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{b: {p: 1}, x: 0}, {has: true, t: "object", v: {p: 1}}], + [{b: [1], x: 0}, {has: true, t: "array", v: [1]}], + [{b: 2, x: 0}, {has: true, t: "number", v: 2}], + [{b: "s", x: 0}, {has: true, t: "string", v: "s"}], + [{b: null, x: 0}, {has: true, t: "null"}], + [{x: 0}, {has: false, t: "null"}], + ], +} + +// The same key-level pairs observed directly in the graph result: a surviving top-level null is +// dropped there, nested values are kept. +{ + name: "key level in the graph result", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ('a' in input ? { k: input.a } : {});"""}, + {function: "b", source: """export const handler = async (input) => ('b' in input ? { k: input.b } : {});"""}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{a: {q: 2}, b: {p: 1}, x: 0}, {k: {p: 1, q: 2}}], + [{a: {q: null}, b: {q: 1}, x: 0}, {k: {}}], + [{a: {q: 1}, b: {q: null}, x: 0}, {k: {q: 1}}], + [{a: [1], b: {p: 1}, x: 0}, {k: [1]}], + [{a: {p: 1}, b: [1], x: 0}, {k: {p: 1}}], + [{a: 2, b: null, x: 0}, {k: 2}], + [{a: null, b: 2, x: 0}, {}], + [{b: null, x: 0}, {}], + [{a: null, x: 0}, {}], + [{b: "s", x: 0}, {k: "s"}], + ], +} + +// Deep merge below the top level: nested objects merge key by key at every depth, nested nulls +// from the winner delete, nested nulls from the loser survive. +{ + name: "key level: nested objects under k", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ('a' in input ? { k: input.a } : {});"""}, + {function: "b", source: """export const handler = async (input) => ('b' in input ? { k: input.b } : {});"""}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{a: {m: {x: 1}}, b: {m: {y: 2}}, x: 0}, {k: {m: {x: 1, y: 2}}}], + [{a: {m: {x: 1}}, b: {m: {x: 2, y: 2}}, x: 0}, {k: {m: {x: 1, y: 2}}}], + [{a: {m: {x: null}}, b: {m: {x: 2, y: 2}}, x: 0}, {k: {m: {y: 2}}}], + [{a: {m: {x: 1}}, b: {m: {x: null}}, x: 0}, {k: {m: {x: 1}}}], + [{a: {m: [1]}, b: {m: {x: 2}}, x: 0}, {k: {m: [1]}}], + [{a: {m: {x: 1}}, b: {m: [2]}, x: 0}, {k: {m: {x: 1}}}], + [{a: {m: {}}, b: {m: {x: 2}}, x: 0}, {k: {m: {x: 2}}}], + [{a: {m: 1}, b: {m: {x: 2}}, x: 0}, {k: {m: 1}}], + ], +} + +// --- Three parents --------------------------------------------------------------------------------- +// Edges into the join are declared a, b, c: `c` is the head, then `b`, then `a` is merged last. +// A top-level array anywhere replaces what was merged before it, and an object after an array +// replaces the array, so a parent before the array is lost. +{ + name: "three parents at the output: top-level kinds", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + {function: "c", source: """export const handler = async (input) => input.c;"""}, + ], + edges: ["input -> a -> output", "input -> b -> output", "input -> c -> output"], + }, + cases: [ + [{a: {k: "a"}, b: {k: "b"}, c: {k: "c"}, x: 0}, {k: "a"}], + [{a: {x1: 1}, b: {x2: 2}, c: {x3: 3}, x: 0}, {x1: 1, x2: 2, x3: 3}], + [{a: {k: "a"}, b: [1], c: {z: 1}, x: 0}, {k: "a"}, "question: an array from a middle parent replaces the keys merged before it, so an object parent is lost even though the final winner is an object"], + [{a: [1], b: {k: "b"}, c: {z: 1}, x: 0}, [1]], + [{a: {k: "a"}, b: {z: 1}, c: [1], x: 0}, {k: "a", z: 1}], + [{a: [1], b: [2], c: [3], x: 0}, [1]], + [{a: 5, b: {k: "b"}, c: {z: 1}, x: 0}, {k: "b", z: 1}], + [{a: {k: "a"}, b: 5, c: {z: 1}, x: 0}, {k: "a", z: 1}], + [{a: {k: "a"}, b: {z: 1}, c: 5, x: 0}, {k: "a", z: 1}], + [{a: null, b: null, c: {z: 1}, x: 0}, {z: 1}], + [{b: [1], c: null, x: 0}, [1]], + [{a: 5, b: "s", c: true, x: 0}, {}], + ], +} + +{ + name: "three parents at the output: edges declared c, b, a", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + {function: "c", source: """export const handler = async (input) => input.c;"""}, + ], + edges: ["input -> c -> output", "input -> b -> output", "input -> a -> output"], + }, + cases: [ + [{a: {k: "a"}, b: {k: "b"}, c: {k: "c"}, x: 0}, {k: "c"}], + [{a: {k: "a"}, b: [1], c: {z: 1}, x: 0}, {z: 1}, "question: an array from a middle parent replaces the keys merged before it, so an object parent is lost even though the final winner is an object"], + [{a: {k: "a"}, b: {z: 1}, c: [1], x: 0}, [1]], + [{a: 5, b: {k: "b"}, c: {z: 1}, x: 0}, {k: "b", z: 1}], + [{a: null, b: [1], c: {z: 1}, x: 0}, {z: 1}], + [{a: [1], b: null, c: {z: 1}, x: 0}, {z: 1}], + ], +} + +{ + name: "three parents at a join: key-level kinds", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => ('a' in input ? { k: input.a } : {});"""}, + {function: "b", source: """export const handler = async (input) => ('b' in input ? { k: input.b } : {});"""}, + {function: "c", source: """export const handler = async (input) => ('c' in input ? { k: input.c } : {});"""}, + {expression: "j", fields: {t: "type(k)", has: "'k' in keys($root)", v: "k"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "input -> c -> j", "j -> output"], + }, + cases: [ + [{a: 1, b: 2, c: 3, x: 0}, {has: true, t: "number", v: 1}], + [{a: null, b: 2, c: 3, x: 0}, {has: false, t: "null"}], + [{b: 2, c: 3, x: 0}, {has: true, t: "number", v: 2}], + [{b: null, c: 3, x: 0}, {has: false, t: "null"}], + [{c: null, x: 0}, {has: true, t: "null"}], + [{a: {p: 1}, b: {q: 2}, c: {r: 3}, x: 0}, {has: true, t: "object", v: {p: 1, q: 2, r: 3}}], + [{a: {p: 1}, b: 5, c: {r: 3}, x: 0}, {has: true, t: "object", v: {p: 1}}], + [{a: {p: null}, b: {p: 1, q: 2}, c: {r: 3}, x: 0}, {has: true, t: "object", v: {q: 2, r: 3}}], + [{a: [1], b: {q: 2}, c: null, x: 0}, {has: true, t: "array", v: [1]}], + ], +} + +// --- passThrough at the join ---------------------------------------------------------------------- +// A passThrough node merges its own output over its (already merged) input with the same rules. +// Without passThrough the node returns only its own fields. +{ + name: "passThrough join node over two parents", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + {expression: "j", passThrough: true, fields: {tag: "'j'"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{a: {k: "a"}, b: {k: "b", y: 1}, x: 0}, {k: "a", tag: "j", y: 1}], + [{a: {k: "a"}, b: [1], x: 0}, {k: "a", tag: "j"}], + [{a: [1], b: {k: "b"}, x: 0}, {tag: "j"}, "question: passThrough over a merged input that is an array drops the array; only the node fields remain"], + [{a: [1], b: [2], x: 0}, {tag: "j"}, "question: passThrough over a merged input that is an array drops the array; only the node fields remain"], + [{a: 5, b: {k: "b"}, x: 0}, {k: "b", tag: "j"}], + [{a: null, b: null, x: 0}, {tag: "j"}], + [{b: {y: 1}, x: 0}, {tag: "j", y: 1}], + [{a: {tag: "a"}, b: {tag: "b"}, x: 0}, {tag: "j"}], + [{a: {k: null}, b: {k: "b"}, x: 0}, {tag: "j"}], + ], +} + +{ + name: "join node without passThrough over the same parents", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + {function: "b", source: """export const handler = async (input) => input.b;"""}, + {expression: "j", fields: {tag: "'j'"}}, + ], + edges: ["input -> a -> j", "input -> b -> j", "j -> output"], + }, + cases: [ + [{a: {k: "a"}, b: {k: "b", y: 1}, x: 0}, {tag: "j"}], + [{a: {k: "a"}, b: [1], x: 0}, {tag: "j"}], + [{a: [1], b: {k: "b"}, x: 0}, {tag: "j"}], + [{a: [1], b: [2], x: 0}, {tag: "j"}], + [{a: 5, b: {k: "b"}, x: 0}, {tag: "j"}], + ], +} + +// Parents with passThrough: each parent carries the request, so the request keys meet +// themselves at the join and the parents' own keys conflict on top. +{ + name: "two passThrough parents at the output", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {k: "a", fromA: "true"}}, + {expression: "b", passThrough: true, fields: {k: "b", fromB: "true"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{a: 1, b: 2, x: 0}, {a: 1, b: 2, fromA: true, fromB: true, k: 1, x: 0}], + [{a: null, b: 2, x: 0}, {b: 2, fromA: true, fromB: true, k: 2, x: 0}], + [{a: 1, b: null, x: 0}, {a: 1, fromA: true, fromB: true, k: 1, x: 0}], + [{b: 2, k: "req", x: 0}, {b: 2, fromA: true, fromB: true, k: 2, x: 0}], + [{k: "req", x: 0}, {fromA: true, fromB: true, x: 0}], + [{a: {p: 1}, b: {q: 2}, x: 0}, {a: {p: 1}, b: {q: 2}, fromA: true, fromB: true, k: {p: 1, q: 2}, x: 0}], + [{a: [1], b: {q: 2}, x: 0}, {a: [1], b: {q: 2}, fromA: true, fromB: true, k: [1], x: 0}], + ], +} + +{ + name: "a passThrough parent and a plain parent, plain edge first", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {k: "a", fromA: "true"}}, + {expression: "b", fields: {k: "b", fromB: "true"}}, + ], + edges: ["input -> b -> output", "input -> a -> output"], + }, + cases: [ + [{a: 1, b: 2, x: 0}, {a: 1, b: 2, fromA: true, fromB: true, k: 2, x: 0}], + [{a: null, b: 2, x: 0}, {b: 2, fromA: true, fromB: true, k: 2, x: 0}], + [{a: 1, b: null, x: 0}, {a: 1, fromA: true, fromB: true, x: 0}], + [{b: 2, k: "req", x: 0}, {b: 2, fromA: true, fromB: true, k: 2, x: 0}], + [{k: "req", x: 0}, {fromA: true, fromB: true, x: 0}], + ], +} + +{ + name: "a passThrough parent and a plain parent, passThrough edge first", + graph: { + nodes: [ + {expression: "a", passThrough: true, fields: {k: "a", fromA: "true"}}, + {expression: "b", fields: {k: "b", fromB: "true"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{a: 1, b: 2, x: 0}, {a: 1, b: 2, fromA: true, fromB: true, k: 1, x: 0}], + [{a: null, b: 2, x: 0}, {b: 2, fromA: true, fromB: true, k: 2, x: 0}], + [{a: 1, b: null, x: 0}, {a: 1, fromA: true, fromB: true, k: 1, x: 0}], + [{b: 2, k: "req", x: 0}, {b: 2, fromA: true, fromB: true, k: 2, x: 0}], + [{k: "req", x: 0}, {fromA: true, fromB: true, x: 0}], + ], +} + +// The input node itself as a parent next to a function returning every kind. +{ + name: "the input and a function parent, input edge first", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + ], + edges: ["input -> output", "input -> a -> output"], + }, + cases: [ + [{a: {k: "a"}, k: "req"}, {a: {k: "a"}, k: "req"}], + [{a: [1], k: "req"}, {a: [1], k: "req"}], + [{a: 5, k: "req"}, {a: 5, k: "req"}], + [{a: null, k: "req"}, {k: "req"}], + [{k: "req"}, {k: "req"}], + [{a: {k: null}, k: "req"}, {a: {k: null}, k: "req"}], + ], +} + +{ + name: "the input and a function parent, function edge first", + graph: { + nodes: [ + {function: "a", source: """export const handler = async (input) => input.a;"""}, + ], + edges: ["input -> a -> output", "input -> output"], + }, + cases: [ + [{a: {k: "a"}, k: "req"}, {a: {k: "a"}, k: "a"}], + [{a: [1], k: "req"}, [1]], + [{a: 5, k: "req"}, {a: 5, k: "req"}], + [{a: null, k: "req"}, {k: "req"}], + [{k: "req"}, {k: "req"}], + [{a: {k: null}, k: "req"}, {a: {k: null}}], + ], +} + +// --- Natural producers ------------------------------------------------------------------------------ +// The same rules with the node kinds that produce each kind in practice: an expression object, a +// collect table array, a first-hit table null when no rule matches, and a branch a switch did +// not take (missing: the parent never ran and is skipped by the join). +{ + name: "expression and first-hit table, table edge first", + graph: { + nodes: [ + {expression: "e", fields: {k: "'expr'", e: "true"}}, + {table: "t", inputs: ["n"], outputs: ["k"], rules: [["> 0", "'table'"]]}, + ], + edges: ["input -> t -> output", "input -> e -> output"], + }, + cases: [ + [{n: 1}, {e: true, k: "table"}], + [{n: 0}, {e: true, k: "expr"}], + [{n: null}, {e: true, k: "expr"}], + [{}, {e: true, k: "expr"}], + ], +} + +{ + name: "expression and collect table, table edge first", + graph: { + nodes: [ + {expression: "e", fields: {k: "'expr'", e: "true"}}, + {table: "c", hit: "collect", inputs: ["n"], outputs: ["k"], rules: [["> 0", "'pos'"], ["> 10", "'big'"]]}, + ], + edges: ["input -> c -> output", "input -> e -> output"], + }, + cases: [ + [{n: 1}, [{k: "pos"}]], + [{n: 20}, [{k: "pos"}, {k: "big"}]], + [{n: 0}, []], + [{}, []], + ], +} + +{ + name: "expression and collect table, expression edge first", + graph: { + nodes: [ + {expression: "e", fields: {k: "'expr'", e: "true"}}, + {table: "c", hit: "collect", inputs: ["n"], outputs: ["k"], rules: [["> 0", "'pos'"], ["> 10", "'big'"]]}, + ], + edges: ["input -> e -> output", "input -> c -> output"], + }, + cases: [ + [{n: 1}, {e: true, k: "expr"}], + [{n: 20}, {e: true, k: "expr"}], + [{n: 0}, {e: true, k: "expr"}], + ], +} + +{ + name: "first-hit table and collect table at one join", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["k"], rules: [["> 0", "'table'"]]}, + {table: "c", hit: "collect", inputs: ["n"], outputs: ["k"], rules: [["> 0", "'pos'"], ["> 10", "'big'"]]}, + ], + edges: ["input -> t -> output", "input -> c -> output"], + }, + cases: [ + [{n: 1}, {k: "table"}], + [{n: 20}, {k: "table"}], + [{n: 0}, []], + [{}, []], + ], +} + +{ + name: "a switch decides which parents exist at the join", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["l", "r"]}, + {expression: "left", fields: {k: "'left'", l: "true"}}, + {expression: "right", fields: {k: "'right'", r: "true"}}, + {expression: "j", fields: {k: "k", l: "l ?? false", r: "r ?? false"}}, + ], + edges: ["input -> s", "s:0 -> left -> j", "s:1 -> right -> j", "j -> output"], + }, + cases: [ + [{l: true, r: true}, {k: "left", l: true, r: true}], + [{l: true, r: false}, {k: "left", l: true, r: false}], + [{l: false, r: true}, {k: "right", l: false, r: true}], + [{l: false, r: false}, {}], + ], +} + +{ + name: "a loop result (top-level array) meeting an expression object", + graph: { + nodes: [ + {expression: "loop", inputField: "items", executionMode: "loop", fields: {v: "x"}}, + {expression: "e", fields: {k: "'expr'", e: "true"}}, + ], + edges: ["input -> loop -> output", "input -> e -> output"], + }, + cases: [ + [{items: [{x: 1}]}, [{v: 1}]], + [{items: []}, []], + [{items: [{x: 1}, {x: null}]}, [{v: 1}, {v: null}]], + ], +} + +{ + name: "an expression object meeting a loop result", + graph: { + nodes: [ + {expression: "loop", inputField: "items", executionMode: "loop", fields: {v: "x"}}, + {expression: "e", fields: {k: "'expr'", e: "true"}}, + ], + edges: ["input -> e -> output", "input -> loop -> output"], + }, + cases: [ + [{items: [{x: 1}]}, {e: true, k: "expr"}], + [{items: []}, {e: true, k: "expr"}], + ], +} + diff --git a/core/engine/tests/spec/graph/56-output-assembly.json5 b/core/engine/tests/spec/graph/56-output-assembly.json5 new file mode 100644 index 00000000..e08aa0ce --- /dev/null +++ b/core/engine/tests/spec/graph/56-output-assembly.json5 @@ -0,0 +1,739 @@ +// Output assembly: how the graph result is built from the nodes that end the walk. +// +// The walk stops as soon as the first output node runs. The result is then the merge of every +// visited node without outgoing edges ("ending nodes"), folded into an empty object in node +// declaration order (not edge order), so on a key conflict the later declared ending node wins. +// The fold is a merge-patch: a top-level null from a later ending node deletes the key, an array +// replaces everything merged so far, and a scalar is ignored. `$nodes` keys are stripped from the +// result at every depth. Chapters 01 and 10 introduce output nodes, dead ends and leaves; this +// chapter covers several outputs, leaf merge order, outputPath collisions, deep paths, arrays of +// objects, reserved keys and very wide results. + +// --- Several output nodes -------------------------------------------------------------------------- +// Only the first output node reached contributes; which one is reached depends on the branch taken. +{ + name: "outputs: a switch routes to one of two output nodes", + graph: { + nodes: [ + {switch: "s", when: ["n > 0", ""]}, + {expression: "pos", fields: {sign: "'pos'", n: "n"}}, + {expression: "neg", fields: {sign: "'neg'", abs: "abs(n ?? 0)"}}, + {output: "outPos"}, + {output: "outNeg"}, + ], + edges: ["input -> s", "s:0 -> pos -> outPos", "s:1 -> neg -> outNeg"], + }, + cases: [ + [{n: 2}, {n: 2, sign: "pos"}], + [{n: -3}, {abs: 3, sign: "neg"}], + [{n: 0}, {abs: 0, sign: "neg"}], + [{}, {abs: 0, sign: "neg"}], + ], +} + +{ + name: "outputs: a collect switch taking both branches stops at the first output reached", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "A", fields: {fromA: "true"}}, + {expression: "B", fields: {fromB: "true"}}, + {output: "outA"}, + {output: "outB"}, + ], + edges: ["input -> s", "s:0 -> A -> outA", "s:1 -> B -> outB"], + }, + cases: [ + [{a: true, b: true}, {fromA: true}], + [{a: true, b: false}, {fromA: true}], + [{a: false, b: true}, {fromB: true}], + ], +} + +{ + name: "outputs: two output nodes behind the same join", + graph: { + nodes: [ + {expression: "a", fields: {k: "'a'", x: "1"}}, + {expression: "b", fields: {k: "'b'", y: "2"}}, + {output: "out1"}, + {output: "out2"}, + ], + edges: ["input -> a -> out1", "input -> b -> out1", "a -> out2", "b -> out2"], + }, + cases: [ + [{}, {k: "a", x: 1, y: 2}], + [{k: "req"}, {k: "a", x: 1, y: 2}], + ], +} + +{ + name: "outputs: an output node with an outgoing edge", + graph: { + nodes: [ + {expression: "a", fields: {k: "n + 1"}}, + {output: "mid"}, + {expression: "after", fields: {after: "k * 10"}}, + ], + edges: ["input -> a -> mid -> after"], + }, + cases: [ + [{n: 1}, {}, "question: the walk stops at the output node, but an output node with an outgoing edge is not an ending node, so nothing is merged and the result is empty"], + [{n: 0}, {}, "question: the walk stops at the output node, but an output node with an outgoing edge is not an ending node, so nothing is merged and the result is empty"], + ], +} + +{ + name: "outputs: an output node directly after the input next to a longer branch", + graph: { + nodes: [ + {expression: "calc", fields: {k: "'calc'"}}, + {output: "out"}, + ], + edges: ["input -> calc -> out", "input -> out"], + }, + cases: [ + [{k: "req", n: 1}, {k: "calc", n: 1}], + [{n: 1}, {k: "calc", n: 1}], + [{k: null, n: 1}, {k: "calc", n: 1}], + ], +} + +{ + name: "outputs: an output schema checks only the output reached", + graph: { + nodes: [ + {switch: "s", when: ["strict", ""]}, + {expression: "A", fields: {v: "v"}}, + {expression: "B", fields: {v: "v"}}, + {output: "checked", schema: {type: "object", required: ["v"], properties: {v: {type: "number"}}}}, + {output: "unchecked"}, + ], + edges: ["input -> s", "s:0 -> A -> checked", "s:1 -> B -> unchecked"], + }, + cases: [ + [{strict: true, v: 1}, {v: 1}], + [{strict: true, v: "x"}, "!error"], + [{strict: false, v: "x"}, {v: "x"}], + [{strict: false}, {}], + ], +} + +// --- Leaves without an output node ------------------------------------------------------------------- +// Every visited leaf is merged, in node declaration order: the later declared leaf wins conflicts, +// whatever the edge order. +{ + name: "leaves: two leaves writing the same key, b declared last", + graph: { + nodes: [ + {input: "request"}, + {expression: "a", fields: {k: "'a'", onlyA: "1"}}, + {expression: "b", fields: {k: "'b'", onlyB: "2"}}, + ], + edges: ["request -> a", "request -> b"], + }, + cases: [ + [{}, {k: "b", onlyA: 1, onlyB: 2}], + [{k: "req"}, {k: "b", onlyA: 1, onlyB: 2}], + ], +} + +{ + name: "leaves: the same leaves with the node list reversed", + graph: { + nodes: [ + {input: "request"}, + {expression: "b", fields: {k: "'b'", onlyB: "2"}}, + {expression: "a", fields: {k: "'a'", onlyA: "1"}}, + ], + edges: ["request -> a", "request -> b"], + }, + cases: [ + [{}, {k: "a", onlyA: 1, onlyB: 2}], + [{k: "req"}, {k: "a", onlyA: 1, onlyB: 2}], + ], +} + +{ + name: "leaves: the same leaves with the edges reversed", + graph: { + nodes: [ + {input: "request"}, + {expression: "a", fields: {k: "'a'", onlyA: "1"}}, + {expression: "b", fields: {k: "'b'", onlyB: "2"}}, + ], + edges: ["request -> b", "request -> a"], + }, + cases: [ + [{}, {k: "b", onlyA: 1, onlyB: 2}], + ], +} + +{ + name: "leaves: a null in a later leaf deletes an earlier leaf's key", + graph: { + nodes: [ + {input: "request"}, + {expression: "a", fields: {k: "'a'", nested: "{x: 1, y: 1}"}}, + {expression: "b", fields: {k: "v", nested: "{x: v}"}}, + ], + edges: ["request -> a", "request -> b"], + }, + cases: [ + [{v: 2}, {k: 2, nested: {x: 2, y: 1}}], + [{v: null}, {nested: {y: 1}}], + [{}, {nested: {y: 1}}], + ], +} + +{ + name: "leaves: a null in an earlier leaf does not delete a later leaf's key", + graph: { + nodes: [ + {input: "request"}, + {expression: "b", fields: {k: "v", nested: "{x: v}"}}, + {expression: "a", fields: {k: "'a'", nested: "{x: 1, y: 1}"}}, + ], + edges: ["request -> a", "request -> b"], + }, + cases: [ + [{v: 2}, {k: "a", nested: {x: 1, y: 1}}], + [{v: null}, {k: "a", nested: {x: 1, y: 1}}], + ], +} + +{ + name: "leaves: tables, functions and loops as leaves of every result kind", + graph: { + nodes: [ + {input: "request"}, + {expression: "e", fields: {e: "true"}}, + {table: "first", inputs: ["n"], outputs: ["first"], rules: [["> 0", "'hit'"]]}, + {function: "f", source: """export const handler = async (input) => input.fn;"""}, + ], + edges: ["request -> e", "request -> first", "request -> f"], + }, + cases: [ + [{n: 1}, {e: true, first: "hit"}], + [{n: 0}, {e: true}], + [{n: 1, fn: {f: 1}}, {e: true, f: 1, first: "hit"}], + [{n: 1, fn: {e: false}}, {e: false, first: "hit"}], + [{n: 1, fn: 5}, {e: true, first: "hit"}], + [{n: 1, fn: null}, {e: true, first: "hit"}], + [{n: 1, fn: [1, 2]}, [1, 2]], + ], +} + +{ + name: "leaves: an array leaf declared before an object leaf", + graph: { + nodes: [ + {input: "request"}, + {table: "rows", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [["> 0", "'pos'"], ["", "'any'"]]}, + {expression: "e", fields: {e: "true"}}, + ], + edges: ["request -> rows", "request -> e"], + }, + cases: [ + [{n: 1}, {e: true}, "question: a collect table leaf is discarded when an object leaf is declared after it; the result depends on node declaration order"], + [{n: 0}, {e: true}, "question: a collect table leaf is discarded when an object leaf is declared after it; the result depends on node declaration order"], + ], +} + +{ + name: "leaves: an object leaf declared before an array leaf", + graph: { + nodes: [ + {input: "request"}, + {expression: "e", fields: {e: "true"}}, + {table: "rows", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [["> 0", "'pos'"], ["", "'any'"]]}, + ], + edges: ["request -> rows", "request -> e"], + }, + cases: [ + [{n: 1}, [{r: "pos"}, {r: "any"}]], + [{n: 0}, [{r: "any"}]], + ], +} + +{ + name: "leaves: deep objects from three leaves merge key by key", + graph: { + nodes: [ + {input: "request"}, + {expression: "a", fields: {"r.x.a": "1", "r.shared": "'a'"}}, + {expression: "b", fields: {"r.x.b": "2", "r.shared": "'b'"}}, + {expression: "c", fields: {"r.y": "[3]", "r.shared": "v"}}, + ], + edges: ["request -> a", "request -> b", "request -> c"], + }, + cases: [ + [{v: "c"}, {r: {shared: "c", x: {a: 1, b: 2}, y: [3]}}], + [{v: null}, {r: {x: {a: 1, b: 2}, y: [3]}}], + [{}, {r: {x: {a: 1, b: 2}, y: [3]}}], + ], +} + +{ + name: "leaves: a chain and a single node as two leaves", + graph: { + nodes: [ + {input: "request"}, + {expression: "a1", fields: {k: "n + 1"}}, + {expression: "a2", fields: {k: "k * 10", chain: "true"}}, + {expression: "b", fields: {single: "true", k: "0"}}, + ], + edges: ["request -> a1 -> a2", "request -> b"], + }, + cases: [ + [{n: 1}, {chain: true, k: 0, single: true}], + [{n: 5}, {chain: true, k: 0, single: true}], + ], +} + +{ + name: "leaves: a leaf behind a switch branch not taken contributes nothing", + graph: { + nodes: [ + {input: "request"}, + {switch: "s", when: ["go", ""]}, + {expression: "yes", fields: {k: "'yes'"}}, + {expression: "no", fields: {k: "'no'"}}, + {expression: "always", fields: {always: "true"}}, + ], + edges: ["request -> s", "s:0 -> yes", "s:1 -> no", "request -> always"], + }, + cases: [ + [{go: true}, {always: true, k: "yes"}], + [{go: false}, {always: true, k: "no"}], + ], +} + +// --- outputPath collisions ----------------------------------------------------------------------------- +// Several nodes writing to the same or overlapping output paths: the merge rules decide. +{ + name: "outputPath: two branches with the same path deep-merge", + graph: { + nodes: [ + {expression: "a", outputPath: "res", fields: {k: "'a'", x: "1"}}, + {expression: "b", outputPath: "res", fields: {k: "'b'", y: "2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {res: {k: "a", x: 1, y: 2}}], + [{res: {z: 0}}, {res: {k: "a", x: 1, y: 2}}], + ], +} + +{ + name: "outputPath: a parent path and a child path from two branches", + graph: { + nodes: [ + {expression: "a", outputPath: "res", fields: {k: "'a'", "sub.x": "1"}}, + {expression: "b", outputPath: "res.sub", fields: {y: "2", x: "'b'"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {res: {k: "a", sub: {x: 1, y: 2}}}], + ], +} + +{ + name: "outputPath: the child path declared first wins inside the parent's object", + graph: { + nodes: [ + {expression: "a", outputPath: "res", fields: {k: "'a'", "sub.x": "1"}}, + {expression: "b", outputPath: "res.sub", fields: {y: "2", x: "'b'"}}, + ], + edges: ["input -> b -> output", "input -> a -> output"], + }, + cases: [ + [{}, {res: {k: "a", sub: {x: "b", y: 2}}}], + ], +} + +{ + name: "outputPath: a scalar at the parent path against an object below it", + graph: { + nodes: [ + {expression: "a", fields: {res: "v"}}, + {expression: "b", outputPath: "res.sub", fields: {y: "2"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{v: 5}, {res: 5}], + [{v: null}, {}], + [{v: [1]}, {res: [1]}], + [{v: {other: 1}}, {res: {other: 1, sub: {y: 2}}}], + ], +} + +{ + name: "outputPath: the object below declared first against a scalar at the parent path", + graph: { + nodes: [ + {expression: "a", fields: {res: "v"}}, + {expression: "b", outputPath: "res.sub", fields: {y: "2"}}, + ], + edges: ["input -> b -> output", "input -> a -> output"], + }, + cases: [ + [{v: 5}, {res: {sub: {y: 2}}}], + [{v: null}, {res: {sub: {y: 2}}}], + [{v: [1]}, {res: {sub: {y: 2}}}], + ], +} + +{ + name: "outputPath: a table and a collect table writing the same path", + graph: { + nodes: [ + {table: "t", outputPath: "res", inputs: ["n"], outputs: ["k"], rules: [["> 0", "'first'"]]}, + {table: "c", hit: "collect", outputPath: "res", inputs: ["n"], outputs: ["k"], rules: [["> 0", "'row'"], ["", "'any'"]]}, + ], + edges: ["input -> t -> output", "input -> c -> output"], + }, + cases: [ + [{n: 1}, {res: {k: "first"}}], + [{n: 0}, {}, "question: an unmatched table under an outputPath writes null at the path, which erases the other branch value there; without outputPath an unmatched table is ignored at a join"], + ], +} + +{ + name: "outputPath: chained nodes writing the same path with and without passThrough", + graph: { + nodes: [ + {expression: "a", outputPath: "res", fields: {k: "'a'", x: "1"}}, + {expression: "b", outputPath: "res", passThrough: true, fields: {k: "'b'"}}, + {expression: "c", outputPath: "res", passThrough: true, fields: {y: "res.x + 1"}}, + ], + }, + cases: [ + [{}, {res: {k: "b", x: 1, y: 2}}], + [{res: 1}, {res: {k: "b", x: 1, y: 2}}], + ], +} + +{ + name: "outputPath: a path equal to a request key, without passThrough", + graph: { + nodes: [ + {expression: "a", outputPath: "n", fields: {doubled: "n * 2"}}, + ], + edges: ["input -> a -> output", "input -> output"], + }, + cases: [ + [{n: 2}, {n: {doubled: 4}}], + [{n: 0, other: true}, {n: {doubled: 0}, other: true}], + ], +} + +// --- Deep paths ---------------------------------------------------------------------------------------- +{ + name: "deep: an eight-segment outputPath", + graph: { + nodes: [{expression: "a", outputPath: "l1.l2.l3.l4.l5.l6.l7.l8", fields: {v: "n", "w.x": "[n]"}}], + }, + cases: [ + [{n: 1}, {l1: {l2: {l3: {l4: {l5: {l6: {l7: {l8: {v: 1, w: {x: [1]}}}}}}}}}}], + [{n: null}, {l1: {l2: {l3: {l4: {l5: {l6: {l7: {l8: {v: null, w: {x: [null]}}}}}}}}}}], + ], +} + +{ + name: "deep: two deep paths sharing a long prefix", + graph: { + nodes: [ + {expression: "a", outputPath: "p.q.r.s.left", fields: {v: "1"}}, + {expression: "b", outputPath: "p.q.r.s.right", fields: {v: "2"}}, + {expression: "c", outputPath: "p.q.other", fields: {v: "3"}}, + ], + edges: ["input -> a -> output", "input -> b -> output", "input -> c -> output"], + }, + cases: [ + [{}, {p: {q: {other: {v: 3}, r: {s: {left: {v: 1}, right: {v: 2}}}}}}], + [{p: {q: {keep: true}}}, {p: {q: {other: {v: 3}, r: {s: {left: {v: 1}, right: {v: 2}}}}}}], + ], +} + +{ + name: "deep: a deep outputPath with passThrough over a request holding part of the spine", + graph: { + nodes: [{expression: "a", outputPath: "p.q.r", passThrough: true, fields: {v: "1"}}], + }, + cases: [ + [{}, {p: {q: {r: {v: 1}}}}], + [{p: {keep: 1}}, {p: {keep: 1, q: {r: {v: 1}}}}], + [{p: {q: {r: {old: 1}}}}, {p: {q: {r: {old: 1, v: 1}}}}], + [{p: {q: 5}}, {p: {q: {r: {v: 1}}}}], + [{p: null}, {p: {q: {r: {v: 1}}}}], + ], +} + +{ + name: "deep: a table writing deep output fields under a deep outputPath", + graph: { + nodes: [ + {table: "t", outputPath: "a.b", inputs: ["n"], outputs: ["c.d.e", "c.d.f", "g"], rules: [ + ["> 0", "n", "'pos'", "[n]"], + ["", "0", "null", "[]"], + ]}, + ], + }, + cases: [ + [{n: 1}, {a: {b: {c: {d: {e: 1, f: "pos"}}, g: [1]}}}], + [{n: -1}, {a: {b: {c: {d: {e: 0, f: null}}, g: []}}}], + ], +} + +{ + name: "deep: a loop under a deep outputPath", + graph: { + nodes: [{expression: "each", inputField: "items", outputPath: "x.y.z", executionMode: "loop", fields: {"a.b": "v"}}], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {x: {y: {z: [{a: {b: 1}}, {a: {b: 2}}]}}}], + [{items: []}, {x: {y: {z: []}}}], + ], +} + +{ + name: "deep: sub-decision result placed under a deep path", + decisions: { + child: {nodes: [{expression: "c", fields: {"inner.k": "v", top: "1"}}]}, + }, + graph: { + nodes: [{decision: "d", key: "child", outputPath: "a.b.c"}], + }, + cases: [ + [{v: 1}, {a: {b: {c: {inner: {k: 1}, top: 1}}}}], + [{v: null}, {a: {b: {c: {inner: {k: null}, top: 1}}}}], + ], +} + +// --- Arrays of objects ----------------------------------------------------------------------------------- +{ + name: "arrays: collect table rows with dotted outputs are nested objects", + graph: { + nodes: [ + {table: "t", hit: "collect", outputPath: "rows", inputs: ["n"], outputs: ["id", "meta.kind", "meta.n"], rules: [ + ["> 0", "1", "'pos'", "n"], + ["> 10", "2", "'big'", "n * 2"], + ["", "3", "'any'", "null"], + ]}, + ], + }, + cases: [ + [{n: 20}, {rows: [{id: 1, meta: {kind: "pos", n: 20}}, {id: 2, meta: {kind: "big", n: 40}}, {id: 3, meta: {kind: "any", n: null}}]}], + [{n: 5}, {rows: [{id: 1, meta: {kind: "pos", n: 5}}, {id: 3, meta: {kind: "any", n: null}}]}], + [{n: 0}, {rows: [{id: 3, meta: {kind: "any", n: null}}]}], + ], +} + +{ + name: "arrays: a loop result next to the source array", + graph: { + nodes: [{expression: "each", inputField: "orders", outputPath: "summary", executionMode: "loop", fields: {id: "id", "total.net": "qty * price", "total.items": "qty"}}], + edges: ["input -> each -> output", "input -> output"], + }, + cases: [ + [{orders: [{id: "a", qty: 2, price: 3}, {id: "b", qty: 1, price: 10}]}, {orders: [{id: "a", price: 3, qty: 2}, {id: "b", price: 10, qty: 1}], summary: [{id: "a", total: {items: 2, net: 6}}, {id: "b", total: {items: 1, net: 10}}]}], + [{orders: []}, {orders: [], summary: []}], + ], +} + +{ + name: "arrays: two branches writing an array of objects at the same key", + graph: { + nodes: [ + {expression: "a", fields: {list: "[{id: 1, a: true}, {id: 2, a: true}]"}}, + {expression: "b", fields: {list: "[{id: 1, b: true}]"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {list: [{a: true, id: 1}, {a: true, id: 2}]}], + ], +} + +{ + name: "arrays: a passThrough loop writing back into an array of nested objects", + graph: { + nodes: [{expression: "each", inputField: "people", outputPath: "people", executionMode: "loop", passThrough: true, fields: {"address.full": "address.city + ', ' + address.zip", adult: "age >= 18"}}], + }, + cases: [ + [{people: [{age: 20, address: {city: "x", zip: "1"}}, {age: 3, address: {city: "y", zip: "2"}}]}, {people: [{address: {city: "x", full: "x, 1", zip: "1"}, adult: true, age: 20}, {address: {city: "y", full: "y, 2", zip: "2"}, adult: false, age: 3}]}], + [{people: [], other: 1}, {other: 1, people: []}], + ], +} + +{ + name: "arrays: array of arrays and mixed items survive assembly", + graph: { + nodes: [{expression: "a", fields: {m: "[[1, 2], [], [{x: null}], null, 'x']"}}], + }, + cases: [ + [{}, {m: [[1, 2], [], [{x: null}], null, "x"]}], + ], +} + +// --- Reserved keys ----------------------------------------------------------------------------------------- +// `$nodes` is stripped from the result at every depth; `$` is an ordinary key. +{ + name: "reserved: an outputPath named $nodes", + graph: { + nodes: [{expression: "a", outputPath: "$nodes", fields: {k: "1"}}], + edges: ["input -> a -> output", "input -> output"], + }, + cases: [ + [{x: 1}, {x: 1}], + ], +} + +{ + name: "reserved: a nested $nodes key written by an expression", + graph: { + nodes: [{expression: "a", fields: {"res.$nodes": "1", "res.k": "2"}}], + }, + cases: [ + [{}, {res: {k: 2}}], + ], +} + +{ + name: "reserved: a function returning $nodes and $ keys", + graph: { + nodes: [{function: "f", source: """export const handler = async () => ({ $nodes: 1, $: 2, deep: { $nodes: 3, $: 4 } });"""}], + }, + cases: [ + [{}, {$: 2, deep: {$: 4}}], + ], +} + +{ + name: "reserved: a request with $nodes and $ keys passed straight through", + graph: {}, + cases: [ + [{"$nodes": {a: 1}, "$": 1, deep: {"$nodes": 2}}, {$: 1, deep: {}}, "question: the result cleaner deletes user data under a `$nodes` key at any depth, not only the engine map"], + ], +} + +{ + name: "reserved: a table output column named $ and $nodes", + graph: { + nodes: [{table: "t", inputs: [""], outputs: ["$", "$nodes", "ok"], rules: [["", "1", "2", "3"]]}], + }, + cases: [ + [{}, {$: 1, ok: 3}], + ], +} + +{ + name: "reserved: an outputPath named $", + graph: { + nodes: [{expression: "a", outputPath: "$", fields: {k: "1"}}], + }, + cases: [ + [{}, {$: {k: 1}}], + ], +} + +{ + name: "reserved: a custom config with a $nodes key", + graph: { + nodes: [{custom: "c", kind: "config", config: {"$nodes": 1, keep: {"$nodes": 2, v: 3}}}], + }, + cases: [ + [{}, {keep: {v: 3}}], + ], +} + +// --- Very wide results ----------------------------------------------------------------------------------- +{ + name: "wide: one expression node with 60 fields", + graph: { + nodes: [{expression: "a", fields: {f00: "n + 0", f01: "n + 1", f02: "n + 2", f03: "n + 3", f04: "n + 4", f05: "n + 5", f06: "n + 6", f07: "n + 7", f08: "n + 8", f09: "n + 9", f10: "n + 10", f11: "n + 11", f12: "n + 12", f13: "n + 13", f14: "n + 14", f15: "n + 15", f16: "n + 16", f17: "n + 17", f18: "n + 18", f19: "n + 19", f20: "n + 20", f21: "n + 21", f22: "n + 22", f23: "n + 23", f24: "n + 24", f25: "n + 25", f26: "n + 26", f27: "n + 27", f28: "n + 28", f29: "n + 29", f30: "n + 30", f31: "n + 31", f32: "n + 32", f33: "n + 33", f34: "n + 34", f35: "n + 35", f36: "n + 36", f37: "n + 37", f38: "n + 38", f39: "n + 39", f40: "n + 40", f41: "n + 41", f42: "n + 42", f43: "n + 43", f44: "n + 44", f45: "n + 45", f46: "n + 46", f47: "n + 47", f48: "n + 48", f49: "n + 49", f50: "n + 50", f51: "n + 51", f52: "n + 52", f53: "n + 53", f54: "n + 54", f55: "n + 55", f56: "n + 56", f57: "n + 57", f58: "n + 58", f59: "n + 59"}}], + }, + cases: [ + [{n: 0}, {f00: 0, f01: 1, f02: 2, f03: 3, f04: 4, f05: 5, f06: 6, f07: 7, f08: 8, f09: 9, f10: 10, f11: 11, f12: 12, f13: 13, f14: 14, f15: 15, f16: 16, f17: 17, f18: 18, f19: 19, f20: 20, f21: 21, f22: 22, f23: 23, f24: 24, f25: 25, f26: 26, f27: 27, f28: 28, f29: 29, f30: 30, f31: 31, f32: 32, f33: 33, f34: 34, f35: 35, f36: 36, f37: 37, f38: 38, f39: 39, f40: 40, f41: 41, f42: 42, f43: 43, f44: 44, f45: 45, f46: 46, f47: 47, f48: 48, f49: 49, f50: 50, f51: 51, f52: 52, f53: 53, f54: 54, f55: 55, f56: 56, f57: 57, f58: 58, f59: 59}], + [{n: 100}, {f00: 100, f01: 101, f02: 102, f03: 103, f04: 104, f05: 105, f06: 106, f07: 107, f08: 108, f09: 109, f10: 110, f11: 111, f12: 112, f13: 113, f14: 114, f15: 115, f16: 116, f17: 117, f18: 118, f19: 119, f20: 120, f21: 121, f22: 122, f23: 123, f24: 124, f25: 125, f26: 126, f27: 127, f28: 128, f29: 129, f30: 130, f31: 131, f32: 132, f33: 133, f34: 134, f35: 135, f36: 136, f37: 137, f38: 138, f39: 139, f40: 140, f41: 141, f42: 142, f43: 143, f44: 144, f45: 145, f46: 146, f47: 147, f48: 148, f49: 149, f50: 150, f51: 151, f52: 152, f53: 153, f54: 154, f55: 155, f56: 156, f57: 157, f58: 158, f59: 159}], + ], +} + +{ + name: "wide: two branches of 30 disjoint keys each", + graph: { + nodes: [ + {expression: "a", fields: {a00: "n + 0", a01: "n + 1", a02: "n + 2", a03: "n + 3", a04: "n + 4", a05: "n + 5", a06: "n + 6", a07: "n + 7", a08: "n + 8", a09: "n + 9", a10: "n + 10", a11: "n + 11", a12: "n + 12", a13: "n + 13", a14: "n + 14", a15: "n + 15", a16: "n + 16", a17: "n + 17", a18: "n + 18", a19: "n + 19", a20: "n + 20", a21: "n + 21", a22: "n + 22", a23: "n + 23", a24: "n + 24", a25: "n + 25", a26: "n + 26", a27: "n + 27", a28: "n + 28", a29: "n + 29"}}, + {expression: "b", fields: {b00: "n * 0", b01: "n * 1", b02: "n * 2", b03: "n * 3", b04: "n * 4", b05: "n * 5", b06: "n * 6", b07: "n * 7", b08: "n * 8", b09: "n * 9", b10: "n * 10", b11: "n * 11", b12: "n * 12", b13: "n * 13", b14: "n * 14", b15: "n * 15", b16: "n * 16", b17: "n * 17", b18: "n * 18", b19: "n * 19", b20: "n * 20", b21: "n * 21", b22: "n * 22", b23: "n * 23", b24: "n * 24", b25: "n * 25", b26: "n * 26", b27: "n * 27", b28: "n * 28", b29: "n * 29"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{n: 1}, {a00: 1, a01: 2, a02: 3, a03: 4, a04: 5, a05: 6, a06: 7, a07: 8, a08: 9, a09: 10, a10: 11, a11: 12, a12: 13, a13: 14, a14: 15, a15: 16, a16: 17, a17: 18, a18: 19, a19: 20, a20: 21, a21: 22, a22: 23, a23: 24, a24: 25, a25: 26, a26: 27, a27: 28, a28: 29, a29: 30, b00: 0, b01: 1, b02: 2, b03: 3, b04: 4, b05: 5, b06: 6, b07: 7, b08: 8, b09: 9, b10: 10, b11: 11, b12: 12, b13: 13, b14: 14, b15: 15, b16: 16, b17: 17, b18: 18, b19: 19, b20: 20, b21: 21, b22: 22, b23: 23, b24: 24, b25: 25, b26: 26, b27: 27, b28: 28, b29: 29}], + [{n: 2}, {a00: 2, a01: 3, a02: 4, a03: 5, a04: 6, a05: 7, a06: 8, a07: 9, a08: 10, a09: 11, a10: 12, a11: 13, a12: 14, a13: 15, a14: 16, a15: 17, a16: 18, a17: 19, a18: 20, a19: 21, a20: 22, a21: 23, a22: 24, a23: 25, a24: 26, a25: 27, a26: 28, a27: 29, a28: 30, a29: 31, b00: 0, b01: 2, b02: 4, b03: 6, b04: 8, b05: 10, b06: 12, b07: 14, b08: 16, b09: 18, b10: 20, b11: 22, b12: 24, b13: 26, b14: 28, b15: 30, b16: 32, b17: 34, b18: 36, b19: 38, b20: 40, b21: 42, b22: 44, b23: 46, b24: 48, b25: 50, b26: 52, b27: 54, b28: 56, b29: 58}], + ], +} + +{ + name: "wide: two branches of 40 keys overlapping on 20", + graph: { + nodes: [ + {expression: "a", fields: {k00: "'a'", k01: "'a'", k02: "'a'", k03: "'a'", k04: "'a'", k05: "'a'", k06: "'a'", k07: "'a'", k08: "'a'", k09: "'a'", k10: "'a'", k11: "'a'", k12: "'a'", k13: "'a'", k14: "'a'", k15: "'a'", k16: "'a'", k17: "'a'", k18: "'a'", k19: "'a'", k20: "'a'", k21: "'a'", k22: "'a'", k23: "'a'", k24: "'a'", k25: "'a'", k26: "'a'", k27: "'a'", k28: "'a'", k29: "'a'", k30: "'a'", k31: "'a'", k32: "'a'", k33: "'a'", k34: "'a'", k35: "'a'", k36: "'a'", k37: "'a'", k38: "'a'", k39: "'a'"}}, + {expression: "b", fields: {k20: "'b'", k21: "'b'", k22: "'b'", k23: "'b'", k24: "'b'", k25: "'b'", k26: "'b'", k27: "'b'", k28: "'b'", k29: "'b'", k30: "'b'", k31: "'b'", k32: "'b'", k33: "'b'", k34: "'b'", k35: "'b'", k36: "'b'", k37: "'b'", k38: "'b'", k39: "'b'", k40: "'b'", k41: "'b'", k42: "'b'", k43: "'b'", k44: "'b'", k45: "'b'", k46: "'b'", k47: "'b'", k48: "'b'", k49: "'b'", k50: "'b'", k51: "'b'", k52: "'b'", k53: "'b'", k54: "'b'", k55: "'b'", k56: "'b'", k57: "'b'", k58: "'b'", k59: "'b'"}}, + ], + edges: ["input -> a -> output", "input -> b -> output"], + }, + cases: [ + [{}, {k00: "a", k01: "a", k02: "a", k03: "a", k04: "a", k05: "a", k06: "a", k07: "a", k08: "a", k09: "a", k10: "a", k11: "a", k12: "a", k13: "a", k14: "a", k15: "a", k16: "a", k17: "a", k18: "a", k19: "a", k20: "a", k21: "a", k22: "a", k23: "a", k24: "a", k25: "a", k26: "a", k27: "a", k28: "a", k29: "a", k30: "a", k31: "a", k32: "a", k33: "a", k34: "a", k35: "a", k36: "a", k37: "a", k38: "a", k39: "a", k40: "b", k41: "b", k42: "b", k43: "b", k44: "b", k45: "b", k46: "b", k47: "b", k48: "b", k49: "b", k50: "b", k51: "b", k52: "b", k53: "b", k54: "b", k55: "b", k56: "b", k57: "b", k58: "b", k59: "b"}], + ], +} + +{ + name: "wide: a table with 50 output columns, some null", + graph: { + nodes: [{table: "t", inputs: ["n"], outputs: ["o00", "o01", "o02", "o03", "o04", "o05", "o06", "o07", "o08", "o09", "o10", "o11", "o12", "o13", "o14", "o15", "o16", "o17", "o18", "o19", "o20", "o21", "o22", "o23", "o24", "o25", "o26", "o27", "o28", "o29", "o30", "o31", "o32", "o33", "o34", "o35", "o36", "o37", "o38", "o39", "o40", "o41", "o42", "o43", "o44", "o45", "o46", "o47", "o48", "o49"], rules: [ + ["> 0", "n + 0", "n + 1", "n + 2", "n + 3", "n + 4", "n + 5", "n + 6", "n + 7", "n + 8", "n + 9", "n + 10", "n + 11", "n + 12", "n + 13", "n + 14", "n + 15", "n + 16", "n + 17", "n + 18", "n + 19", "n + 20", "n + 21", "n + 22", "n + 23", "n + 24", "n + 25", "n + 26", "n + 27", "n + 28", "n + 29", "n + 30", "n + 31", "n + 32", "n + 33", "n + 34", "n + 35", "n + 36", "n + 37", "n + 38", "n + 39", "n + 40", "n + 41", "n + 42", "n + 43", "n + 44", "n + 45", "n + 46", "n + 47", "n + 48", "n + 49"], + ["", "null", "'x1'", "'x2'", "'x3'", "'x4'", "'x5'", "'x6'", "'x7'", "'x8'", "'x9'", "null", "'x11'", "'x12'", "'x13'", "'x14'", "'x15'", "'x16'", "'x17'", "'x18'", "'x19'", "null", "'x21'", "'x22'", "'x23'", "'x24'", "'x25'", "'x26'", "'x27'", "'x28'", "'x29'", "null", "'x31'", "'x32'", "'x33'", "'x34'", "'x35'", "'x36'", "'x37'", "'x38'", "'x39'", "null", "'x41'", "'x42'", "'x43'", "'x44'", "'x45'", "'x46'", "'x47'", "'x48'", "'x49'"], + ]}], + }, + cases: [ + [{n: 1}, {o00: 1, o01: 2, o02: 3, o03: 4, o04: 5, o05: 6, o06: 7, o07: 8, o08: 9, o09: 10, o10: 11, o11: 12, o12: 13, o13: 14, o14: 15, o15: 16, o16: 17, o17: 18, o18: 19, o19: 20, o20: 21, o21: 22, o22: 23, o23: 24, o24: 25, o25: 26, o26: 27, o27: 28, o28: 29, o29: 30, o30: 31, o31: 32, o32: 33, o33: 34, o34: 35, o35: 36, o36: 37, o37: 38, o38: 39, o39: 40, o40: 41, o41: 42, o42: 43, o43: 44, o44: 45, o45: 46, o46: 47, o47: 48, o48: 49, o49: 50}], + [{n: 0}, {o01: "x1", o02: "x2", o03: "x3", o04: "x4", o05: "x5", o06: "x6", o07: "x7", o08: "x8", o09: "x9", o11: "x11", o12: "x12", o13: "x13", o14: "x14", o15: "x15", o16: "x16", o17: "x17", o18: "x18", o19: "x19", o21: "x21", o22: "x22", o23: "x23", o24: "x24", o25: "x25", o26: "x26", o27: "x27", o28: "x28", o29: "x29", o31: "x31", o32: "x32", o33: "x33", o34: "x34", o35: "x35", o36: "x36", o37: "x37", o38: "x38", o39: "x39", o41: "x41", o42: "x42", o43: "x43", o44: "x44", o45: "x45", o46: "x46", o47: "x47", o48: "x48", o49: "x49"}], + ], +} + +{ + name: "wide: 60 dotted keys spread over six nested objects", + graph: { + nodes: [{expression: "a", fields: {"g0.h0": "n", "g0.h1": "n", "g0.h2": "n", "g0.h3": "n", "g0.h4": "n", "g0.h5": "n", "g0.h6": "n", "g0.h7": "n", "g0.h8": "n", "g0.h9": "n", "g1.h10": "n", "g1.h11": "n", "g1.h12": "n", "g1.h13": "n", "g1.h14": "n", "g1.h15": "n", "g1.h16": "n", "g1.h17": "n", "g1.h18": "n", "g1.h19": "n", "g2.h20": "n", "g2.h21": "n", "g2.h22": "n", "g2.h23": "n", "g2.h24": "n", "g2.h25": "n", "g2.h26": "n", "g2.h27": "n", "g2.h28": "n", "g2.h29": "n", "g3.h30": "n", "g3.h31": "n", "g3.h32": "n", "g3.h33": "n", "g3.h34": "n", "g3.h35": "n", "g3.h36": "n", "g3.h37": "n", "g3.h38": "n", "g3.h39": "n", "g4.h40": "n", "g4.h41": "n", "g4.h42": "n", "g4.h43": "n", "g4.h44": "n", "g4.h45": "n", "g4.h46": "n", "g4.h47": "n", "g4.h48": "n", "g4.h49": "n", "g5.h50": "n", "g5.h51": "n", "g5.h52": "n", "g5.h53": "n", "g5.h54": "n", "g5.h55": "n", "g5.h56": "n", "g5.h57": "n", "g5.h58": "n", "g5.h59": "n"}}], + }, + cases: [ + [{n: 7}, {g0: {h0: 7, h1: 7, h2: 7, h3: 7, h4: 7, h5: 7, h6: 7, h7: 7, h8: 7, h9: 7}, g1: {h10: 7, h11: 7, h12: 7, h13: 7, h14: 7, h15: 7, h16: 7, h17: 7, h18: 7, h19: 7}, g2: {h20: 7, h21: 7, h22: 7, h23: 7, h24: 7, h25: 7, h26: 7, h27: 7, h28: 7, h29: 7}, g3: {h30: 7, h31: 7, h32: 7, h33: 7, h34: 7, h35: 7, h36: 7, h37: 7, h38: 7, h39: 7}, g4: {h40: 7, h41: 7, h42: 7, h43: 7, h44: 7, h45: 7, h46: 7, h47: 7, h48: 7, h49: 7}, g5: {h50: 7, h51: 7, h52: 7, h53: 7, h54: 7, h55: 7, h56: 7, h57: 7, h58: 7, h59: 7}}], + [{n: null}, {g0: {h0: null, h1: null, h2: null, h3: null, h4: null, h5: null, h6: null, h7: null, h8: null, h9: null}, g1: {h10: null, h11: null, h12: null, h13: null, h14: null, h15: null, h16: null, h17: null, h18: null, h19: null}, g2: {h20: null, h21: null, h22: null, h23: null, h24: null, h25: null, h26: null, h27: null, h28: null, h29: null}, g3: {h30: null, h31: null, h32: null, h33: null, h34: null, h35: null, h36: null, h37: null, h38: null, h39: null}, g4: {h40: null, h41: null, h42: null, h43: null, h44: null, h45: null, h46: null, h47: null, h48: null, h49: null}, g5: {h50: null, h51: null, h52: null, h53: null, h54: null, h55: null, h56: null, h57: null, h58: null, h59: null}}], + ], +} + +{ + name: "wide: passThrough over a 60-key request", + graph: { + nodes: [{expression: "a", passThrough: true, fields: {w00: "'changed'", w59: "null", extra: "true"}}], + }, + cases: [ + [{w00: 0, w01: 1, w02: 2, w03: 3, w04: 4, w05: 5, w06: 6, w07: 7, w08: 8, w09: 9, w10: 10, w11: 11, w12: 12, w13: 13, w14: 14, w15: 15, w16: 16, w17: 17, w18: 18, w19: 19, w20: 20, w21: 21, w22: 22, w23: 23, w24: 24, w25: 25, w26: 26, w27: 27, w28: 28, w29: 29, w30: 30, w31: 31, w32: 32, w33: 33, w34: 34, w35: 35, w36: 36, w37: 37, w38: 38, w39: 39, w40: 40, w41: 41, w42: 42, w43: 43, w44: 44, w45: 45, w46: 46, w47: 47, w48: 48, w49: 49, w50: 50, w51: 51, w52: 52, w53: 53, w54: 54, w55: 55, w56: 56, w57: 57, w58: 58, w59: 59}, {extra: true, w00: "changed", w01: 1, w02: 2, w03: 3, w04: 4, w05: 5, w06: 6, w07: 7, w08: 8, w09: 9, w10: 10, w11: 11, w12: 12, w13: 13, w14: 14, w15: 15, w16: 16, w17: 17, w18: 18, w19: 19, w20: 20, w21: 21, w22: 22, w23: 23, w24: 24, w25: 25, w26: 26, w27: 27, w28: 28, w29: 29, w30: 30, w31: 31, w32: 32, w33: 33, w34: 34, w35: 35, w36: 36, w37: 37, w38: 38, w39: 39, w40: 40, w41: 41, w42: 42, w43: 43, w44: 44, w45: 45, w46: 46, w47: 47, w48: 48, w49: 49, w50: 50, w51: 51, w52: 52, w53: 53, w54: 54, w55: 55, w56: 56, w57: 57, w58: 58}], + [{w00: null, w01: "s1", w02: "s2", w03: null, w04: "s4", w05: "s5", w06: null, w07: "s7", w08: "s8", w09: null, w10: "s10", w11: "s11", w12: null, w13: "s13", w14: "s14", w15: null, w16: "s16", w17: "s17", w18: null, w19: "s19", w20: "s20", w21: null, w22: "s22", w23: "s23", w24: null, w25: "s25", w26: "s26", w27: null, w28: "s28", w29: "s29", w30: null, w31: "s31", w32: "s32", w33: null, w34: "s34", w35: "s35", w36: null, w37: "s37", w38: "s38", w39: null, w40: "s40", w41: "s41", w42: null, w43: "s43", w44: "s44", w45: null, w46: "s46", w47: "s47", w48: null, w49: "s49", w50: "s50", w51: null, w52: "s52", w53: "s53", w54: null, w55: "s55", w56: "s56", w57: null, w58: "s58", w59: "s59"}, {extra: true, w00: "changed", w01: "s1", w02: "s2", w04: "s4", w05: "s5", w07: "s7", w08: "s8", w10: "s10", w11: "s11", w13: "s13", w14: "s14", w16: "s16", w17: "s17", w19: "s19", w20: "s20", w22: "s22", w23: "s23", w25: "s25", w26: "s26", w28: "s28", w29: "s29", w31: "s31", w32: "s32", w34: "s34", w35: "s35", w37: "s37", w38: "s38", w40: "s40", w41: "s41", w43: "s43", w44: "s44", w46: "s46", w47: "s47", w49: "s49", w50: "s50", w52: "s52", w53: "s53", w55: "s55", w56: "s56", w58: "s58"}], + ], +} + +{ + name: "wide: an object literal with 55 keys as one field", + graph: { + nodes: [{expression: "a", outputPath: "res", fields: {d: "{d00: n, d01: n, d02: n, d03: n, d04: n, d05: n, d06: n, d07: n, d08: n, d09: n, d10: n, d11: n, d12: n, d13: n, d14: n, d15: n, d16: n, d17: n, d18: n, d19: n, d20: n, d21: n, d22: n, d23: n, d24: n, d25: n, d26: n, d27: n, d28: n, d29: n, d30: n, d31: n, d32: n, d33: n, d34: n, d35: n, d36: n, d37: n, d38: n, d39: n, d40: n, d41: n, d42: n, d43: n, d44: n, d45: n, d46: n, d47: n, d48: n, d49: n, d50: n, d51: n, d52: n, d53: n, d54: n}"}}], + }, + cases: [ + [{n: 1}, {res: {d: {d00: 1, d01: 1, d02: 1, d03: 1, d04: 1, d05: 1, d06: 1, d07: 1, d08: 1, d09: 1, d10: 1, d11: 1, d12: 1, d13: 1, d14: 1, d15: 1, d16: 1, d17: 1, d18: 1, d19: 1, d20: 1, d21: 1, d22: 1, d23: 1, d24: 1, d25: 1, d26: 1, d27: 1, d28: 1, d29: 1, d30: 1, d31: 1, d32: 1, d33: 1, d34: 1, d35: 1, d36: 1, d37: 1, d38: 1, d39: 1, d40: 1, d41: 1, d42: 1, d43: 1, d44: 1, d45: 1, d46: 1, d47: 1, d48: 1, d49: 1, d50: 1, d51: 1, d52: 1, d53: 1, d54: 1}}}], + ], +} diff --git a/core/engine/tests/spec/graph/57-table-output-shapes.json5 b/core/engine/tests/spec/graph/57-table-output-shapes.json5 new file mode 100644 index 00000000..14d68153 --- /dev/null +++ b/core/engine/tests/spec/graph/57-table-output-shapes.json5 @@ -0,0 +1,841 @@ +// Decision table output shapes: what a matched row writes. Output cells are standard +// expressions, so a cell may build objects, arrays, nested literals, templates or null, and may +// read any field of the node input or `$nodes`. Output columns are dot paths written in column +// order into one fresh object per row; columns sharing a prefix merge into the same parent, and +// a column writing the parent itself replaces or seeds it depending on its position. +// Chapter 07 pins the basic path, null and error rules; this chapter varies the value shapes. + +// --- Object literal cells ------------------------------------------------------------------ + +{ + name: "shapes: an object literal cell built from input fields", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["result"], rules: [ + ["'person'", "{name: first + ' ' + last, adult: age >= 18}"], + ["'company'", "{name: title, adult: true, size: len(staff ?? [])}"], + ["", "{name: null}"], + ]}, + ], + }, + cases: [ + [{kind: "person", first: "Ann", last: "Lee", age: 30}, {result: {name: "Ann Lee", adult: true}}], + [{kind: "person", first: "Bo", last: "Ng", age: 12}, {result: {name: "Bo Ng", adult: false}}], + [{kind: "company", title: "Acme", staff: [1, 2, 3]}, {result: {name: "Acme", adult: true, size: 3}}], + [{kind: "company", title: "Solo"}, {result: {name: "Solo", adult: true, size: 0}}], + [{kind: "other"}, {result: {name: null}}], + [{}, {result: {name: null}}], + ], +} + +{ + name: "shapes: nested object literals several levels deep", + graph: { + nodes: [ + {table: "t", inputs: ["level"], outputs: ["cfg"], rules: [ + ["1", "{a: {b: {c: {d: v}}}}"], + ["2", "{a: {b: [v, {c: v}]}, e: {}}"], + ["", "{}"], + ]}, + ], + }, + cases: [ + [{level: 1, v: 5}, {cfg: {a: {b: {c: {d: 5}}}}}], + [{level: 1, v: "s"}, {cfg: {a: {b: {c: {d: "s"}}}}}], + [{level: 1}, {cfg: {a: {b: {c: {d: null}}}}}], + [{level: 2, v: true}, {cfg: {a: {b: [true, {c: true}]}, e: {}}}], + [{level: 3}, {cfg: {}}], + [{}, {cfg: {}}], + ], +} + +{ + name: "shapes: an object literal cell with quoted, spaced and numeric-looking keys", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["o"], rules: [ + ["{'my key': 1, \"two\": 2, 'a.b': 3}"], + ]}, + ], + }, + cases: [ + [{}, {o: {"my key": 1, two: 2, "a.b": 3}}], + [{o: "replaced"}, {o: {"my key": 1, two: 2, "a.b": 3}}], + ], +} + +{ + name: "shapes: an empty object cell is a value, not an absent output", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["o", "n"], rules: [ + ["'empty'", "{}", "1"], + ["'blank'", "", "2"], + ]}, + ], + }, + cases: [ + [{k: "empty"}, {o: {}, n: 1}], + [{k: "blank"}, {n: 2}], + [{k: "none"}, {}], + ], +} + +{ + name: "shapes: an object cell copying an input object, then adding a sibling column into it", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["profile", "profile.checked"], rules: [ + ["customer", "true"], + ]}, + ], + }, + cases: [ + [{customer: {name: "Ann", tier: "gold"}}, {profile: {name: "Ann", tier: "gold", checked: true}}], + [{customer: {checked: false}}, {profile: {checked: true}}], + [{customer: {}}, {profile: {checked: true}}], + [{customer: null}, {}, "question: `profile` is null and the later `profile.checked` column is silently dropped, so the whole output is empty; writing below a null parent could create the object"], + [{}, {}, "question: `profile` reads a missing field (null) and the later `profile.checked` column is silently dropped"], + [{customer: "text"}, {profile: "text"}, "question: a scalar parent silently drops the nested `profile.checked` column (consistent with chapter 07)"], + ], +} + +// --- Array cells --------------------------------------------------------------------------- + +{ + name: "shapes: array literal cells of mixed element types", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["list"], rules: [ + ["'mixed'", "[1, 'a', true, null, {x: 1}, [2]]"], + ["'empty'", "[]"], + ["'refs'", "[a, b, a + b]"], + ]}, + ], + }, + cases: [ + [{k: "mixed"}, {list: [1, "a", true, null, {x: 1}, [2]]}], + [{k: "empty"}, {list: []}], + [{k: "refs", a: 1, b: 2}, {list: [1, 2, 3]}], + [{k: "refs", a: "x", b: "y"}, {list: ["x", "y", "xy"]}], + [{k: "refs", a: 1, b: "y"}, {}], + [{k: "none"}, {}], + ], +} + +{ + name: "shapes: array cells computed with closures over input lists", + graph: { + nodes: [ + {table: "t", inputs: ["mode"], outputs: ["names", "big", "total"], rules: [ + ["'all'", "map(items, #.name)", "filter(items, #.qty > 1)", "sum(map(items, #.qty))"], + ["'first'", "map(filter(items, #.qty > 0), upper(#.name))", "", "len(items)"], + ]}, + ], + }, + cases: [ + [{mode: "all", items: [{name: "a", qty: 1}, {name: "b", qty: 3}]}, {names: ["a", "b"], big: [{name: "b", qty: 3}], total: 4}], + [{mode: "all", items: []}, {names: [], big: [], total: 0}], + [{mode: "first", items: [{name: "a", qty: 0}, {name: "b", qty: 3}]}, {names: ["B"], total: 2}], + [{mode: "first", items: []}, {names: [], total: 0}], + [{mode: "all"}, {}, "question: closures over a missing list error, so the only matching rule is skipped"], + ], +} + +{ + name: "shapes: an array cell copied from the input is an independent copy per output column", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["a", "b", "a2.inner"], rules: [ + ["tags", "tags", "tags"], + ]}, + ], + }, + cases: [ + [{tags: ["x", "y"]}, {tags: ["x", "y"], a: ["x", "y"], b: ["x", "y"], a2: {inner: ["x", "y"]}}], + [{tags: []}, {tags: [], a: [], b: [], a2: {inner: []}}], + [{tags: [{k: 1}]}, {tags: [{k: 1}], a: [{k: 1}], b: [{k: 1}], a2: {inner: [{k: 1}]}}], + ], +} + +// A slice past the end errors and skips the whole first rule, so `{n: 1, items: [10]}` falls +// through to the catch-all. +{ + name: "shapes: ranges and slices as output cells", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["seq", "head"], rules: [ + ["> 0", "map([1..n], # * 2)", "items[0:1]"], + ["", "[]", "items"], + ]}, + ], + }, + cases: [ + [{n: 3, items: [10, 20, 30]}, {seq: [2, 4, 6], head: [10, 20]}], + [{n: 1, items: [10]}, {seq: [], head: [10]}], + [{n: 1, items: [10, 20]}, {seq: [2], head: [10, 20]}], + [{n: 0, items: [1]}, {seq: [], head: [1]}], + [{items: []}, {seq: [], head: []}], + ], +} + +// --- Template cells ------------------------------------------------------------------------ + +{ + name: "shapes: template string cells interpolate values of every type", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["s"], rules: [ + ["`v=${v}`"], + ]}, + ], + }, + cases: [ + [{v: "text"}, {s: "v=text"}], + [{v: 12.50}, {s: "v=12.50"}], + [{v: -3}, {s: "v=-3"}], + [{v: true}, {s: "v=true"}], + [{v: null}, {s: "v=null"}], + [{}, {s: "v=null"}], + ], +} + +{ + name: "shapes: templates inside objects and arrays", + graph: { + nodes: [ + {table: "t", inputs: ["lang"], outputs: ["msg"], rules: [ + ["'en'", "{title: `Hello ${name}`, lines: [`You owe ${amount}`, `Due ${due}`]}"], + ["'de'", "{title: `Hallo ${name}`, lines: [`Sie schulden ${amount}`]}"], + ]}, + ], + }, + cases: [ + [{lang: "en", name: "Ann", amount: 10, due: "Friday"}, {msg: {title: "Hello Ann", lines: ["You owe 10", "Due Friday"]}}], + [{lang: "de", name: "Jo", amount: 1.5}, {msg: {title: "Hallo Jo", lines: ["Sie schulden 1.5"]}}], + [{lang: "fr", name: "X"}, {}], + ], +} + +{ + name: "shapes: template cells with nested expressions and conditionals", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["label"], rules: [ + [">= 0", "`${n} item${n == 1 ? '' : 's'} (${n * 2} halves)`"], + ["", "`negative: ${abs(n)}`"], + ]}, + ], + }, + cases: [ + [{n: 1}, {label: "1 item (2 halves)"}], + [{n: 0}, {label: "0 items (0 halves)"}], + [{n: 3}, {label: "3 items (6 halves)"}], + [{n: -4}, {label: "negative: 4"}], + ], +} + +// --- Null outputs inside shapes -------------------------------------------------------------- + +{ + name: "shapes: null at different depths of the output", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["top", "nested.v", "obj", "arr"], rules: [ + ["1", "null", "null", "{v: null}", "[null]"], + ["2", "v", "v", "{v: v}", "[v]"], + ]}, + ], + }, + cases: [ + [{k: 1}, {nested: {v: null}, obj: {v: null}, arr: [null]}], + [{k: 2, v: 0}, {top: 0, nested: {v: 0}, obj: {v: 0}, arr: [0]}], + [{k: 2}, {nested: {v: null}, obj: {v: null}, arr: [null]}], + [{k: 2, v: false}, {top: false, nested: {v: false}, obj: {v: false}, arr: [false]}], + ], +} + +{ + name: "shapes: a null parent column followed by a nested column", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "a.b"], rules: [ + ["null", "1"], + ]}, + ], + }, + cases: [ + [{}, {}, "question: a null parent drops the later nested write like a scalar parent does, and the top-level null is then removed, so nothing is written"], + ], +} + +{ + name: "shapes: a nested column followed by a null parent column", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a.b", "a"], rules: [ + ["1", "null"], + ]}, + ], + }, + cases: [ + [{}, {}], + [{a: {b: 0, c: 2}}, {}], + ], +} + +{ + name: "shapes: null output under passThrough deletes, nested null under passThrough deletes too", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["k"], outputs: ["x", "obj.y"], rules: [ + ["'del'", "null", "null"], + ["'set'", "1", "2"], + ]}, + ], + }, + cases: [ + [{k: "del", x: 5, obj: {y: 6, z: 7}}, {k: "del", obj: {z: 7}}], + [{k: "set", x: 5, obj: {y: 6, z: 7}}, {k: "set", x: 1, obj: {y: 2, z: 7}}], + [{k: "del"}, {k: "del", obj: {y: null}}, "question: merging `{obj: {y: null}}` into an input without `obj` keeps the null leaf, while a top-level null leaf is removed; a merge patch would drop it"], + [{k: "other", x: 5}, {k: "other", x: 5}], + ], +} + +// --- Output columns sharing a prefix --------------------------------------------------------- + +{ + name: "prefix: `a.b`, `a.c`, then `a` as an object replaces both", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["a.b", "a.c", "a"], rules: [ + ["1", "1", "2", "{d: 3}"], + ["2", "1", "2", ""], + ["3", "", "", "{d: 3}"], + ["4", "1", "", "5"], + ]}, + ], + }, + cases: [ + [{k: 1}, {a: {d: 3}}], + [{k: 2}, {a: {b: 1, c: 2}}], + [{k: 3}, {a: {d: 3}}], + [{k: 4}, {a: 5}], + ], +} + +{ + name: "prefix: `a` first, then `a.b` and `a.c` merge into the object", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["a", "a.b", "a.c"], rules: [ + ["1", "{d: 3}", "1", "2"], + ["2", "{b: 0, d: 3}", "1", ""], + ["3", "", "1", "2"], + ["4", "{}", "", ""], + ["5", "[1, 2]", "1", ""], + ]}, + ], + }, + cases: [ + [{k: 1}, {a: {d: 3, b: 1, c: 2}}], + [{k: 2}, {a: {b: 1, d: 3}}], + [{k: 3}, {a: {b: 1, c: 2}}], + [{k: 4}, {a: {}}], + [{k: 5}, {a: [1, 2]}, "question: a nested column below an array parent is silently dropped"], + ], +} + +{ + name: "prefix: a column whose name is a prefix of another as a string, not a path (`ab` vs `a.b`)", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "ab", "a.b", "a_b"], rules: [ + ["{}", "1", "2", "3"], + ]}, + ], + }, + cases: [ + [{}, {a: {b: 2}, ab: 1, a_b: 3}], + ], +} + +{ + name: "prefix: deep shared spines from several columns", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["r.x.p", "r.x.q", "r.y", "r.x.z.w", "r.y2.v"], rules: [ + ["'all'", "1", "2", "3", "4", "5"], + ["'some'", "1", "", "3", "", "5"], + ["'none'", "", "", "", "", ""], + ]}, + ], + }, + cases: [ + [{k: "all"}, {r: {x: {p: 1, q: 2, z: {w: 4}}, y: 3, y2: {v: 5}}}], + [{k: "some"}, {r: {x: {p: 1}, y: 3, y2: {v: 5}}}], + [{k: "none"}, {}], + ], +} + +{ + name: "prefix: shared prefix columns in a collect table build one nested object per row", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["fee", "fee.amount", "fee.label"], rules: [ + ["> 0", "{kind: 'base'}", "n", "'base'"], + ["> 10", "", "n * 2", ""], + ["> 100", "{kind: 'bulk'}", "", ""], + ]}, + ], + }, + cases: [ + [{n: 5}, [{fee: {kind: "base", amount: 5, label: "base"}}]], + [{n: 50}, [{fee: {kind: "base", amount: 50, label: "base"}}, {fee: {amount: 100}}]], + [{n: 500}, [{fee: {kind: "base", amount: 500, label: "base"}}, {fee: {amount: 1000}}, {fee: {kind: "bulk"}}]], + [{n: 0}, []], + ], +} + +{ + name: "prefix: a `[]` column and scalar columns under the same parent", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["res.tier", "res.reasons[]", "res.score"], rules: [ + ["> 100", "'gold'", "'over 100'", "3"], + ["> 10", "'silver'", "'over 10'", "2"], + ["> 0", "'bronze'", "'positive'", ""], + ]}, + ], + }, + cases: [ + [{n: 500}, {res: {tier: "gold", score: 3, reasons: ["over 100", "over 10", "positive"]}}], + [{n: 50}, {res: {tier: "silver", score: 2, reasons: ["over 10", "positive"]}}], + [{n: 5}, {res: {tier: "bronze", reasons: ["positive"]}}], + [{n: 0}, {res: {reasons: []}}], + ], +} + +{ + name: "prefix: a `[]` column whose path is below a scalar column", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["res", "res.tags[]"], rules: [ + ["> 10", "'big'", "'a'"], + ["> 0", "'small'", "'b'"], + ]}, + ], + }, + cases: [ + [{n: 50}, {res: "big"}, "question: the gathered `res.tags` array is silently dropped because `res` holds a scalar"], + [{n: 5}, {res: "small"}, "question: the gathered `res.tags` array is silently dropped because `res` holds a scalar"], + [{n: 0}, {res: {tags: []}}], + ], +} + +// --- Many output columns ----------------------------------------------------------------------- + +{ + name: "many columns: twelve outputs of different types from one row", + graph: { + nodes: [ + {table: "t", inputs: ["plan"], outputs: [ + "name", "price", "currency", "active", "limits.users", "limits.storage", + "features", "meta", "trial", "discount", "label", "rank", + ], rules: [ + ["'pro'", "'Pro'", "49.99", "'EUR'", "true", "10", "100", "['sso', 'api']", "{tier: 2}", "null", "0.1", "`Pro for ${seats} seats`", "2"], + ["'free'", "'Free'", "0", "'EUR'", "true", "1", "1", "[]", "{tier: 0}", "14", "", "'Free'", "0"], + ["", "plan", "", "", "false", "", "", "", "", "", "", "", "-1"], + ]}, + ], + }, + cases: [ + [{plan: "pro", seats: 5}, {name: "Pro", price: 49.99, currency: "EUR", active: true, limits: {users: 10, storage: 100}, features: ["sso", "api"], meta: {tier: 2}, discount: 0.1, label: "Pro for 5 seats", rank: 2}], + [{plan: "free"}, {name: "Free", price: 0, currency: "EUR", active: true, limits: {users: 1, storage: 1}, features: [], meta: {tier: 0}, trial: 14, label: "Free", rank: 0}], + [{plan: "legacy"}, {name: "legacy", active: false, rank: -1}], + [{}, {active: false, rank: -1}], + ], +} + +{ + name: "many columns: eleven outputs, each row fills a different subset", + graph: { + nodes: [ + {table: "t", inputs: ["k"], outputs: ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "c11"], rules: [ + ["1", "1", "", "", "", "", "", "", "", "", "", ""], + ["2", "", "2", "", "2", "", "2", "", "2", "", "2", ""], + ["3", "", "", "", "", "", "", "", "", "", "", "11"], + ["4", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"], + ["5", "", "", "", "", "", "", "", "", "", "", ""], + ]}, + ], + }, + cases: [ + [{k: 1}, {c1: 1}], + [{k: 2}, {c2: 2, c4: 2, c6: 2, c8: 2, c10: 2}], + [{k: 3}, {c11: 11}], + [{k: 4}, {c1: 1, c2: 2, c3: 3, c4: 4, c5: 5, c6: 6, c7: 7, c8: 8, c9: 9, c10: 10, c11: 11}], + [{k: 5}, {}], + [{k: 6}, {}], + ], +} + +{ + name: "many columns: ten outputs where one failing cell skips the whole row", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["o1", "o2", "o3", "o4", "o5", "o6", "o7", "o8", "o9", "o10"], rules: [ + ["1", "2", "3", "4", "5", "6", "7", "8", "9", "x + 1"], + ["'a'", "", "", "", "", "", "", "", "", "'fallback'"], + ]}, + ], + }, + cases: [ + [{x: 1}, {o1: 1, o2: 2, o3: 3, o4: 4, o5: 5, o6: 6, o7: 7, o8: 8, o9: 9, o10: 2}], + [{x: "s"}, {o1: "a", o10: "fallback"}], + [{x: null}, {o1: "a", o10: "fallback"}, "question: `null + 1` errors, so the first row is skipped; consistent with chapter 07"], + ], +} + +{ + name: "many columns: twelve outputs per entry in a collect table", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"], rules: [ + ["> 0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"], + ["> 5", "n", "", "n", "", "n", "", "n", "", "n", "", "n", ""], + ]}, + ], + }, + cases: [ + [{n: 1}, [{a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12}]], + [{n: 6}, [{a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12}, {a: 6, c: 6, e: 6, g: 6, i: 6, k: 6}]], + [{n: 0}, []], + ], +} + +// --- Cells reading other columns' inputs --------------------------------------------------------- + +{ + name: "references: output cells read the input fields of the input columns", + graph: { + nodes: [ + {table: "t", inputs: ["age", "country"], outputs: ["summary", "next"], rules: [ + [">= 18", "'US', 'CA'", "country + ':' + string(age)", "age + 1"], + [">= 18", "", "'adult elsewhere ' + country", "age"], + ["", "", "'minor'", "18 - age"], + ]}, + ], + }, + cases: [ + [{age: 30, country: "US"}, {summary: "US:30", next: 31}], + [{age: 30, country: "DE"}, {summary: "adult elsewhere DE", next: 30}], + [{age: 10, country: "US"}, {summary: "minor", next: 8}], + [{age: 18, country: "CA"}, {summary: "CA:18", next: 19}], + ], +} + +{ + name: "references: an output column named like an input field reads the input, not its sibling output", + graph: { + nodes: [ + {table: "t", inputs: ["price"], outputs: ["price", "tax", "total"], rules: [ + ["> 0", "price * 2", "price * 0.1", "price + tax"], + ]}, + ], + }, + cases: [ + [{price: 10, tax: 0}, {price: 20, tax: 1, total: 10}], + [{price: 10, tax: 5}, {price: 20, tax: 1, total: 15}], + [{price: 10}, {}], + ], +} + +{ + name: "references: an input column whose field is an expression is not addressable by name in outputs", + graph: { + nodes: [ + {table: "t", inputs: ["price * qty"], outputs: ["sum", "again"], rules: [ + ["> 10", "price * qty", "$"], + ]}, + ], + }, + cases: [ + [{price: 5, qty: 3}, {sum: 15, again: 15}], + [{price: 1, qty: 3}, {}], + ], +} + +{ + name: "references: output cells read nested fields of other columns' objects", + graph: { + nodes: [ + {table: "t", inputs: ["order.total", "customer.tier"], outputs: ["invoice"], rules: [ + ["> 100", "'gold'", "{to: customer.name, net: order.total * 0.9, items: len(order.lines)}"], + ["> 0", "", "{to: customer.name, net: order.total, items: len(order.lines)}"], + ]}, + ], + }, + cases: [ + [{order: {total: 200, lines: [1, 2]}, customer: {tier: "gold", name: "Ann"}}, {invoice: {to: "Ann", net: 180, items: 2}}], + [{order: {total: 200, lines: []}, customer: {tier: "silver", name: "Bo"}}, {invoice: {to: "Bo", net: 200, items: 0}}], + [{order: {total: 0, lines: []}, customer: {tier: "gold"}}, {}], + ], +} + +// --- Outputs built from $nodes ----------------------------------------------------------------- + +{ + name: "nodes: output cells combine the input with an upstream node", + graph: { + nodes: [ + {expression: "rates", fields: {vat: "0.2", fee: "2"}}, + {table: "t", inputs: ["country"], outputs: ["gross", "applied"], rules: [ + ["'DE'", "net * (1 + $nodes.rates.vat) + $nodes.rates.fee", "$nodes.rates"], + ["", "net", "null"], + ]}, + ], + edges: ["input -> rates", "input -> t -> output", "rates -> t"], + }, + cases: [ + [{country: "DE", net: 100}, {gross: 122, applied: {vat: 0.2, fee: 2}}], + [{country: "FR", net: 100}, {gross: 100}], + ], +} + +{ + name: "nodes: an output cell copying $nodes.input", + graph: { + nodes: [ + {expression: "shape", fields: {k: "'x'"}}, + {table: "t", inputs: ["k"], outputs: ["original", "seen"], rules: [ + ["'x'", "$nodes.input", "k"], + ]}, + ], + }, + cases: [ + [{a: 1}, {original: {a: 1}, seen: "x"}], + [{a: [1, 2], b: null}, {original: {a: [1, 2], b: null}, seen: "x"}], + [{}, {original: {}, seen: "x"}], + ], +} + +{ + name: "nodes: output cells mapping over an upstream collect table", + graph: { + nodes: [ + {table: "rules", hit: "collect", inputs: ["n"], outputs: ["code"], rules: [ + ["> 0", "'POS'"], + ["> 10", "'BIG'"], + ["", "'ANY'"], + ]}, + {table: "t", inputs: [], outputs: ["codes", "count", "first"], rules: [ + ["map($nodes.rules, #.code)", "len($nodes.rules)", "$nodes.rules[0].code"], + ]}, + ], + }, + cases: [ + [{n: 50}, {codes: ["POS", "BIG", "ANY"], count: 3, first: "POS"}], + [{n: 5}, {codes: ["POS", "ANY"], count: 2, first: "POS"}], + [{n: -1}, {codes: ["ANY"], count: 1, first: "ANY"}], + ], +} + +{ + name: "nodes: an output cell reading a node that matched nothing", + graph: { + nodes: [ + {table: "pick", inputs: ["k"], outputs: ["v"], rules: [ + ["'a'", "1"], + ]}, + {table: "t", inputs: [], outputs: ["v", "had", "obj"], rules: [ + ["$nodes.pick.v ?? 0", "$nodes.pick != null", "$nodes.pick"], + ]}, + ], + }, + cases: [ + [{k: "a"}, {v: 1, had: true, obj: {v: 1}}], + [{k: "b"}, {v: 0, had: false}], + ], +} + +{ + name: "nodes: output cells reading nodes on two parallel branches", + graph: { + nodes: [ + {expression: "left", fields: {l: "x * 2"}}, + {expression: "right", fields: {r: "x + 100"}}, + {table: "t", inputs: [null], outputs: ["pair", "max"], rules: [ + ["$nodes.left.l > $nodes.right.r", "[$nodes.left.l, $nodes.right.r]", "$nodes.left.l"], + ["", "[$nodes.left.l, $nodes.right.r]", "$nodes.right.r"], + ]}, + ], + edges: ["input -> left -> t", "input -> right -> t", "t -> output"], + }, + cases: [ + [{x: 200}, {pair: [400, 300], max: 400}], + [{x: 1}, {pair: [2, 101], max: 101}], + [{x: 100}, {pair: [200, 200], max: 200}], + ], +} + +// --- Transform attributes over complex shapes ------------------------------------------------ + +{ + name: "transforms: passThrough deep-merges an object cell into the input object", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: [], outputs: ["cfg"], rules: [ + ["{a: {x: 1}, list: [9]}"], + ]}, + ], + }, + cases: [ + [{cfg: {a: {y: 2}, list: [1, 2], keep: true}}, {cfg: {a: {x: 1, y: 2}, list: [9], keep: true}}], + [{cfg: "scalar"}, {cfg: {a: {x: 1}, list: [9]}}], + [{}, {cfg: {a: {x: 1}, list: [9]}}], + ], +} + +{ + name: "transforms: outputPath wraps nested and array shapes", + graph: { + nodes: [ + {table: "t", outputPath: "out.res", inputs: ["k"], outputs: ["a.b", "list"], rules: [ + ["1", "{c: 1}", "[1, [2]]"], + ]}, + ], + }, + cases: [ + [{k: 1}, {out: {res: {a: {b: {c: 1}}, list: [1, [2]]}}}], + [{k: 2}, {out: {res: null}}], + ], +} + +{ + name: "transforms: loop mode builds one object shape per item", + graph: { + nodes: [ + {table: "t", executionMode: "loop", inputField: "items", outputPath: "out", inputs: ["kind"], outputs: ["view.label", "view.tags"], rules: [ + ["'a'", "`A-${id}`", "[kind, id]"], + ["", "`?-${id}`", "[]"], + ]}, + ], + }, + cases: [ + [{items: [{kind: "a", id: 1}, {kind: "b", id: 2}]}, {out: [{view: {label: "A-1", tags: ["a", 1]}}, {view: {label: "?-2", tags: []}}]}], + [{items: []}, {out: []}], + [{items: [{id: 3}]}, {out: [{view: {label: "?-3", tags: []}}]}], + ], +} + +// --- Special values ----------------------------------------------------------------------------- + +{ + name: "values: date results from output cells", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["day", "ts", "iso"], rules: [ + ["d(at).format('%Y-%m-%d')", "d(at).timestamp()", "d(at).add(1, 'd').format('%Y-%m-%d')"], + ]}, + ], + }, + cases: [ + [{at: "2025-01-31"}, {day: "2025-01-31", ts: 1738281600000, iso: "2025-02-01"}], + [{at: "2024-02-28"}, {day: "2024-02-28", ts: 1709078400000, iso: "2024-02-29"}], + ], +} + +{ + name: "values: exact decimals, large integers and negative zero in output cells", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["a", "b", "c", "d"], rules: [ + ["0.1 + 0.2", "12345678901234567890", "-0", "1.50"], + ]}, + ], + }, + cases: [ + [{}, {a: 0.3, b: 12345678901234567890, c: 0, d: 1.5}], + ], +} + +{ + name: "values: unicode and escapes in string outputs and keys", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["grüße", "s", "obj"], rules: [ + ["'héllo'", "'line\\nbreak'", "{'ключ': '値'}"], + ]}, + ], + }, + cases: [ + [{}, {"grüße": "héllo", s: "line\\nbreak", obj: {"ключ": "値"}}], + ], +} + +// --- Degenerate output columns --------------------------------------------------------------- + +{ + name: "degenerate: an output column with an empty field writes nothing", + graph: { + nodes: [ + {table: "t", inputs: [], outputs: ["", "kept"], rules: [ + ["1", "2"], + ]}, + ], + }, + cases: [ + [{}, {kept: 2}], + ], +} + +{ + name: "degenerate: an output column `[]` with no path writes nothing", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["[]", "kept"], rules: [ + ["> 0", "1", "2"], + ["> 5", "3", "4"], + ]}, + ], + }, + cases: [ + [{n: 10}, {kept: 2}], + [{n: 1}, {kept: 2}], + [{n: 0}, {}], + ], +} + +{ + name: "degenerate: outputs with no output columns at all", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: [], rules: [ + ["> 0"], + ]}, + ], + }, + cases: [ + [{n: 1}, {}], + [{n: 0}, {}], + ], +} + +{ + name: "degenerate: a collect table with no output columns returns one empty object per match", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: [], rules: [ + ["> 0"], + ["> 5"], + [""], + ]}, + ], + }, + cases: [ + [{n: 10}, [{}, {}, {}]], + [{n: 1}, [{}, {}]], + [{n: 0}, [{}]], + ], +} diff --git a/core/engine/tests/spec/graph/58-table-hit-policies.json5 b/core/engine/tests/spec/graph/58-table-hit-policies.json5 new file mode 100644 index 00000000..84183aef --- /dev/null +++ b/core/engine/tests/spec/graph/58-table-hit-policies.json5 @@ -0,0 +1,752 @@ +// Decision table hit policies compared: the same rules run as a first-hit table, a collect table +// and a first-hit table with a per-column `[]` output, side by side in one graph under distinct +// outputPaths so every case shows the three answers together. First hit returns the first +// matching rule's object (null when nothing matches), collect returns every matching rule's +// object in rule order (an empty array when nothing matches), and a `[]` column gathers that +// column's values across matching rules while plain columns come from the first matching rule +// (with no matching rule only the `[]` columns are written, as empty arrays). +// Chapters 04, 05 and 07 pin each policy alone; this chapter contrasts them, and covers empty +// and wildcard-only tables, rule order and the transform attributes for each policy. + +// --- Side by side: identical rules under each policy ------------------------------------------------ + +{ + name: "side by side: overlapping thresholds", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 80", "'B'"], + [">= 70", "'C'"], + ]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["score"], outputs: ["grade"], rules: [ + [">= 90", "'A'"], + [">= 80", "'B'"], + [">= 70", "'C'"], + ]}, + {table: "cols", outputPath: "cols", inputs: ["score"], outputs: ["grade[]"], rules: [ + [">= 90", "'A'"], + [">= 80", "'B'"], + [">= 70", "'C'"], + ]}, + ], + edges: ["input -> first -> output", "input -> all -> output", "input -> cols -> output"], + }, + cases: [ + [{score: 95}, {first: {grade: "A"}, all: [{grade: "A"}, {grade: "B"}, {grade: "C"}], cols: {grade: ["A", "B", "C"]}}], + [{score: 85}, {first: {grade: "B"}, all: [{grade: "B"}, {grade: "C"}], cols: {grade: ["B", "C"]}}], + [{score: 70}, {first: {grade: "C"}, all: [{grade: "C"}], cols: {grade: ["C"]}}], + [{score: 10}, {all: [], cols: {grade: []}}], + [{}, {all: [], cols: {grade: []}}], + [{score: "95"}, {all: [], cols: {grade: []}}], + ], +} + +{ + name: "side by side: disjoint rules give the same single answer under every policy", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["kind"], outputs: ["code"], rules: [ + ["'a'", "1"], + ["'b'", "2"], + ["'c'", "3"], + ]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["kind"], outputs: ["code"], rules: [ + ["'a'", "1"], + ["'b'", "2"], + ["'c'", "3"], + ]}, + {table: "cols", outputPath: "cols", inputs: ["kind"], outputs: ["code[]"], rules: [ + ["'a'", "1"], + ["'b'", "2"], + ["'c'", "3"], + ]}, + ], + edges: ["input -> first -> output", "input -> all -> output", "input -> cols -> output"], + }, + cases: [ + [{kind: "a"}, {first: {code: 1}, all: [{code: 1}], cols: {code: [1]}}], + [{kind: "c"}, {first: {code: 3}, all: [{code: 3}], cols: {code: [3]}}], + [{kind: "d"}, {all: [], cols: {code: []}}], + [{kind: null}, {all: [], cols: {code: []}}], + ], +} + +{ + name: "side by side: several output columns, some empty per rule", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["n"], outputs: ["a", "b"], rules: [ + ["> 0", "'pos'", ""], + ["> 10", "", "'big'"], + ["", "'any'", "'any'"], + ]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["n"], outputs: ["a", "b"], rules: [ + ["> 0", "'pos'", ""], + ["> 10", "", "'big'"], + ["", "'any'", "'any'"], + ]}, + {table: "cols", outputPath: "cols", inputs: ["n"], outputs: ["a", "b[]"], rules: [ + ["> 0", "'pos'", ""], + ["> 10", "", "'big'"], + ["", "'any'", "'any'"], + ]}, + ], + edges: ["input -> first -> output", "input -> all -> output", "input -> cols -> output"], + }, + cases: [ + [{n: 50}, {first: {a: "pos"}, all: [{a: "pos"}, {b: "big"}, {a: "any", b: "any"}], cols: {a: "pos", b: ["big", "any"]}}], + [{n: 5}, {first: {a: "pos"}, all: [{a: "pos"}, {a: "any", b: "any"}], cols: {a: "pos", b: ["any"]}}], + [{n: -5}, {first: {a: "any", b: "any"}, all: [{a: "any", b: "any"}], cols: {a: "any", b: ["any"]}}], + [{}, {first: {a: "any", b: "any"}, all: [{a: "any", b: "any"}], cols: {a: "any", b: ["any"]}}], + ], +} + +{ + name: "side by side: an output cell that errors for some inputs", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "n + bonus"], + ["", "n"], + ]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "n + bonus"], + ["", "n"], + ]}, + {table: "cols", outputPath: "cols", inputs: ["n"], outputs: ["v[]"], rules: [ + ["> 0", "n + bonus"], + ["", "n"], + ]}, + ], + edges: ["input -> first -> output", "input -> all -> output", "input -> cols -> output"], + }, + cases: [ + [{n: 1, bonus: 10}, {first: {v: 11}, all: [{v: 11}, {v: 1}], cols: {v: [11, 1]}}], + [{n: 1, bonus: "x"}, {first: {v: 1}, all: [{v: 1}], cols: {v: [1]}}], + [{n: 1}, {first: {v: 1}, all: [{v: 1}], cols: {v: [1]}}], + [{n: 0, bonus: "x"}, {first: {v: 0}, all: [{v: 0}], cols: {v: [0]}}], + ], +} + +{ + name: "side by side: large indexed tables (eight rules) agree with the small forms", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["c"], outputs: ["v"], rules: [ + ["'a'", "1"], ["'b'", "2"], ["'a', 'b'", "3"], ["'c'", "4"], + ["'d'", "5"], ["'a'", "6"], ["'e'", "7"], ["", "8"], + ]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["c"], outputs: ["v"], rules: [ + ["'a'", "1"], ["'b'", "2"], ["'a', 'b'", "3"], ["'c'", "4"], + ["'d'", "5"], ["'a'", "6"], ["'e'", "7"], ["", "8"], + ]}, + {table: "cols", outputPath: "cols", inputs: ["c"], outputs: ["v[]"], rules: [ + ["'a'", "1"], ["'b'", "2"], ["'a', 'b'", "3"], ["'c'", "4"], + ["'d'", "5"], ["'a'", "6"], ["'e'", "7"], ["", "8"], + ]}, + ], + edges: ["input -> first -> output", "input -> all -> output", "input -> cols -> output"], + }, + cases: [ + [{c: "a"}, {first: {v: 1}, all: [{v: 1}, {v: 3}, {v: 6}, {v: 8}], cols: {v: [1, 3, 6, 8]}}], + [{c: "b"}, {first: {v: 2}, all: [{v: 2}, {v: 3}, {v: 8}], cols: {v: [2, 3, 8]}}], + [{c: "e"}, {first: {v: 7}, all: [{v: 7}, {v: 8}], cols: {v: [7, 8]}}], + [{c: "z"}, {first: {v: 8}, all: [{v: 8}], cols: {v: [8]}}], + [{c: 1}, {first: {v: 8}, all: [{v: 8}], cols: {v: [8]}}], + [{}, {first: {v: 8}, all: [{v: 8}], cols: {v: [8]}}], + ], +} + +{ + name: "side by side: a downstream expression reads all three results", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["n"], outputs: ["fee"], rules: [ + ["> 100", "10"], + ["> 0", "1"], + ]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["n"], outputs: ["fee"], rules: [ + ["> 100", "10"], + ["> 0", "1"], + ]}, + {table: "cols", outputPath: "cols", inputs: ["n"], outputs: ["fee[]"], rules: [ + ["> 100", "10"], + ["> 0", "1"], + ]}, + {expression: "sum", fields: { + first: "first.fee ?? 0", + all: "sum(map(all, #.fee))", + cols: "sum(cols.fee ?? [])", + sameCount: "len(all) == len(cols.fee ?? [])", + }}, + ], + edges: ["input -> first -> sum", "input -> all -> sum", "input -> cols -> sum", "sum -> output"], + }, + cases: [ + [{n: 500}, {first: 10, all: 11, cols: 11, sameCount: true}], + [{n: 5}, {first: 1, all: 1, cols: 1, sameCount: true}], + [{n: 0}, {first: 0, all: 0, cols: 0, sameCount: true}], + ], +} + +// --- Rule order under each policy -------------------------------------------------------------------- + +{ + name: "rule order: collect lists rules in declaration order, reversed rules give a reversed array", + graph: { + nodes: [ + {table: "asc", hit: "collect", outputPath: "asc", inputs: ["n"], outputs: ["r"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ["> 2", "3"], + ]}, + {table: "desc", hit: "collect", outputPath: "desc", inputs: ["n"], outputs: ["r"], rules: [ + ["> 2", "3"], + ["> 1", "2"], + ["> 0", "1"], + ]}, + ], + edges: ["input -> asc -> output", "input -> desc -> output"], + }, + cases: [ + [{n: 3}, {asc: [{r: 1}, {r: 2}, {r: 3}], desc: [{r: 3}, {r: 2}, {r: 1}]}], + [{n: 2}, {asc: [{r: 1}, {r: 2}], desc: [{r: 2}, {r: 1}]}], + [{n: 1}, {asc: [{r: 1}], desc: [{r: 1}]}], + [{n: 0}, {asc: [], desc: []}], + ], +} + +{ + name: "rule order: first hit picks the earliest of the same rules, reversed order picks the other end", + graph: { + nodes: [ + {table: "asc", outputPath: "asc", inputs: ["n"], outputs: ["r"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ["> 2", "3"], + ]}, + {table: "desc", outputPath: "desc", inputs: ["n"], outputs: ["r"], rules: [ + ["> 2", "3"], + ["> 1", "2"], + ["> 0", "1"], + ]}, + ], + edges: ["input -> asc -> output", "input -> desc -> output"], + }, + cases: [ + [{n: 3}, {asc: {r: 1}, desc: {r: 3}}], + [{n: 2}, {asc: {r: 1}, desc: {r: 2}}], + [{n: 1}, {asc: {r: 1}, desc: {r: 1}}], + [{n: 0}, {}], + ], +} + +{ + name: "rule order: a `[]` column follows rule order while the scalar comes from the earliest rule", + graph: { + nodes: [ + {table: "asc", outputPath: "asc", inputs: ["n"], outputs: ["top", "all[]"], rules: [ + ["> 0", "'gt0'", "1"], + ["> 1", "'gt1'", "2"], + ["> 2", "'gt2'", "3"], + ]}, + {table: "desc", outputPath: "desc", inputs: ["n"], outputs: ["top", "all[]"], rules: [ + ["> 2", "'gt2'", "3"], + ["> 1", "'gt1'", "2"], + ["> 0", "'gt0'", "1"], + ]}, + ], + edges: ["input -> asc -> output", "input -> desc -> output"], + }, + cases: [ + [{n: 3}, {asc: {top: "gt0", all: [1, 2, 3]}, desc: {top: "gt2", all: [3, 2, 1]}}], + [{n: 2}, {asc: {top: "gt0", all: [1, 2]}, desc: {top: "gt1", all: [2, 1]}}], + [{n: 1}, {asc: {top: "gt0", all: [1]}, desc: {top: "gt0", all: [1]}}], + ], +} + +{ + name: "rule order: a wildcard rule in the middle of a collect table keeps its position", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["k"], outputs: ["r"], rules: [ + ["'x'", "'first'"], + ["", "'middle'"], + ["'x', 'y'", "'last'"], + ]}, + ], + }, + cases: [ + [{k: "x"}, [{r: "first"}, {r: "middle"}, {r: "last"}]], + [{k: "y"}, [{r: "middle"}, {r: "last"}]], + [{k: "z"}, [{r: "middle"}]], + [{}, [{r: "middle"}]], + ], +} + +{ + name: "rule order: duplicated rules collect duplicates, first hit takes one", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["k"], outputs: ["r", "tags[]"], rules: [ + ["'a'", "1", "'t'"], + ["'a'", "1", "'t'"], + ["'a'", "2", "'u'"], + ]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["k"], outputs: ["r"], rules: [ + ["'a'", "1"], + ["'a'", "1"], + ["'a'", "2"], + ]}, + ], + edges: ["input -> first -> output", "input -> all -> output"], + }, + cases: [ + [{k: "a"}, {first: {r: 1, tags: ["t", "t", "u"]}, all: [{r: 1}, {r: 1}, {r: 2}]}], + [{k: "b"}, {all: [], first: {tags: []}}], + ], +} + +{ + name: "rule order: collect over a large indexed table keeps declaration order across index and fallback rows", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["code", "amount"], outputs: ["r"], rules: [ + ["", "> 1000", "'big'"], + ["'X'", "", "'x1'"], + ["'Y'", "> 10", "'y-mid'"], + ["'X'", "> 10", "'x-mid'"], + ["", "", "'any'"], + ["'Z'", "", "'z'"], + ["'X', 'Z'", "> 500", "'xz-high'"], + ["'X'", "", "'x2'"], + ]}, + ], + }, + cases: [ + [{code: "X", amount: 2000}, [{r: "big"}, {r: "x1"}, {r: "x-mid"}, {r: "any"}, {r: "xz-high"}, {r: "x2"}]], + [{code: "X", amount: 5}, [{r: "x1"}, {r: "any"}, {r: "x2"}]], + [{code: "Z", amount: 600}, [{r: "any"}, {r: "z"}, {r: "xz-high"}]], + [{code: "Y", amount: 50}, [{r: "y-mid"}, {r: "any"}]], + [{code: "Q", amount: 5000}, [{r: "big"}, {r: "any"}]], + [{}, [{r: "any"}]], + ], +} + +// --- Empty tables (no rules) --------------------------------------------------------------------------- + +{ + name: "empty: no rules under each policy", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["n"], outputs: ["v"], rules: []}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["n"], outputs: ["v"], rules: []}, + {table: "cols", outputPath: "cols", inputs: ["n"], outputs: ["v[]"], rules: []}, + ], + edges: ["input -> first -> output", "input -> all -> output", "input -> cols -> output"], + }, + cases: [ + [{n: 1}, {all: [], cols: {v: []}}], + [{}, {all: [], cols: {v: []}}], + ], +} + +{ + name: "empty: no rules and no columns at all", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: [], outputs: [], rules: []}, + {table: "all", hit: "collect", outputPath: "all", inputs: [], outputs: [], rules: []}, + ], + edges: ["input -> first -> output", "input -> all -> output"], + }, + cases: [ + [{n: 1}, {all: []}], + [{}, {all: []}], + ], +} + +{ + name: "empty: a first-hit table with no rules under passThrough keeps the input", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["n"], outputs: ["v"], rules: []}, + ], + }, + cases: [ + [{n: 1, v: 2}, {n: 1, v: 2}], + [{}, {}], + ], +} + +{ + name: "empty: a collect table with no rules under passThrough and outputPath", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, outputPath: "hits", inputs: ["n"], outputs: ["v"], rules: []}, + ], + }, + cases: [ + [{n: 1}, {n: 1, hits: []}], + [{n: 1, hits: [{v: 1}]}, {n: 1, hits: []}], + [{}, {hits: []}], + ], +} + +{ + name: "empty: a `[]` table with no rules under passThrough keeps an existing array", + graph: { + nodes: [ + {table: "t", passThrough: true, inputs: ["n"], outputs: ["tags[]"], rules: []}, + ], + }, + cases: [ + [{n: 1, tags: ["old"]}, {n: 1, tags: []}], + [{n: 1}, {n: 1, tags: []}], + ], +} + +{ + name: "empty: no rules in loop mode under each policy", + graph: { + nodes: [ + {table: "first", executionMode: "loop", inputField: "items", outputPath: "first", inputs: ["n"], outputs: ["v"], rules: []}, + {table: "all", hit: "collect", executionMode: "loop", inputField: "items", outputPath: "all", inputs: ["n"], outputs: ["v"], rules: []}, + {table: "cols", executionMode: "loop", inputField: "items", outputPath: "cols", inputs: ["n"], outputs: ["v[]"], rules: []}, + ], + edges: ["input -> first -> output", "input -> all -> output", "input -> cols -> output"], + }, + cases: [ + [{items: [{n: 1}, {n: 2}]}, {all: [[], []], cols: [{v: []}, {v: []}], first: [null, null]}], + [{items: []}, {first: [], all: [], cols: []}], + ], +} + +{ + name: "empty: a downstream expression after empty tables", + graph: { + nodes: [ + {table: "first", inputs: ["n"], outputs: ["v"], rules: []}, + {table: "all", hit: "collect", inputs: ["n"], outputs: ["v"], rules: []}, + {expression: "e", fields: { + firstNull: "$nodes.first == null", + allLen: "len($nodes.all)", + allType: "type($nodes.all)", + }}, + ], + edges: ["input -> first -> e", "input -> all -> e", "e -> output"], + }, + cases: [ + [{n: 1}, {firstNull: true, allLen: 0, allType: "array"}], + [{}, {firstNull: true, allLen: 0, allType: "array"}], + ], +} + +// --- Wildcard-only tables ------------------------------------------------------------------------------- + +{ + name: "wildcards only: first hit returns the first rule, collect every rule, `[]` every cell", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["a", "b"], outputs: ["v", "w"], rules: [ + ["", "", "1", "'x'"], + ["", "", "2", ""], + ["", "", "", "'z'"], + ]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["a", "b"], outputs: ["v", "w"], rules: [ + ["", "", "1", "'x'"], + ["", "", "2", ""], + ["", "", "", "'z'"], + ]}, + {table: "cols", outputPath: "cols", inputs: ["a", "b"], outputs: ["v", "w[]"], rules: [ + ["", "", "1", "'x'"], + ["", "", "2", ""], + ["", "", "", "'z'"], + ]}, + ], + edges: ["input -> first -> output", "input -> all -> output", "input -> cols -> output"], + }, + cases: [ + [{a: 1, b: 2}, {first: {v: 1, w: "x"}, all: [{v: 1, w: "x"}, {v: 2}, {w: "z"}], cols: {v: 1, w: ["x", "z"]}}], + [{}, {first: {v: 1, w: "x"}, all: [{v: 1, w: "x"}, {v: 2}, {w: "z"}], cols: {v: 1, w: ["x", "z"]}}], + [{a: null, b: [1]}, {first: {v: 1, w: "x"}, all: [{v: 1, w: "x"}, {v: 2}, {w: "z"}], cols: {v: 1, w: ["x", "z"]}}], + ], +} + +{ + name: "wildcards only: a field-less column of empty cells", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: [null, "x"], outputs: ["r"], rules: [ + ["", "", "'one'"], + ["", "", "'two'"], + ]}, + ], + }, + cases: [ + [{x: 1}, [{r: "one"}, {r: "two"}]], + [{}, [{r: "one"}, {r: "two"}]], + ], +} + +{ + name: "wildcards only: eight wildcard rules (index-sized) still return in order", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["k"], outputs: ["i"], rules: [ + ["", "1"], ["", "2"], ["", "3"], ["", "4"], ["", "5"], ["", "6"], ["", "7"], ["", "8"], + ]}, + {table: "f", outputPath: "first", inputs: ["k"], outputs: ["i", "all[]"], rules: [ + ["", "1", "1"], ["", "2", "2"], ["", "3", "3"], ["", "4", "4"], ["", "5", "5"], ["", "6", "6"], ["", "7", "7"], ["", "8", "8"], + ]}, + ], + edges: ["input -> t", "t -> output", "input -> f -> output"], + }, + cases: [ + [{k: "a"}, [{i: 1}, {i: 2}, {i: 3}, {i: 4}, {i: 5}, {i: 6}, {i: 7}, {i: 8}], "question: the collect array and the first-hit object meet at the output node; the array replaces the object rather than merging"], + ], +} + +{ + name: "wildcards only: an all-wildcard collect table with output cells over the input", + graph: { + nodes: [ + {table: "t", hit: "collect", outputPath: "checks", inputs: ["amount"], outputs: ["name", "ok"], rules: [ + ["", "'positive'", "amount > 0"], + ["", "'small'", "amount < 100"], + ["", "'integer'", "amount == round(amount)"], + ]}, + ], + }, + cases: [ + [{amount: 50}, {checks: [{name: "positive", ok: true}, {name: "small", ok: true}, {name: "integer", ok: true}]}], + [{amount: 150.5}, {checks: [{name: "positive", ok: true}, {name: "small", ok: false}, {name: "integer", ok: false}]}], + [{amount: -1}, {checks: [{name: "positive", ok: false}, {name: "small", ok: true}, {name: "integer", ok: true}]}], + [{}, {checks: []}, "question: every check errors on a missing amount (`null > 0`), so every row is dropped"], + ], +} + +{ + name: "wildcards only: loop mode returns every rule for every item", + graph: { + nodes: [ + {table: "t", hit: "collect", executionMode: "loop", inputField: "items", outputPath: "out", inputs: ["v"], outputs: ["tag"], rules: [ + ["", "'a'"], + ["", "v"], + ]}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: "x"}]}, {out: [[{tag: "a"}, {tag: 1}], [{tag: "a"}, {tag: "x"}]]}], + [{items: [{}]}, {out: [[{tag: "a"}, {tag: null}]]}], + [{items: []}, {out: []}], + ], +} + +// --- Collect with transform attributes --------------------------------------------------------------- + +{ + name: "collect transforms: inputField scopes cells and outputs to the sub-object", + graph: { + nodes: [ + {table: "t", hit: "collect", inputField: "order", outputPath: "flags", inputs: ["total", "country"], outputs: ["flag", "of"], rules: [ + ["> 100", "", "'big'", "total"], + ["", "'US'", "'domestic'", "country"], + ["", "", "'seen'", "len(lines ?? [])"], + ]}, + ], + }, + cases: [ + [{order: {total: 200, country: "US", lines: [1]}}, {flags: [{flag: "big", of: 200}, {flag: "domestic", of: "US"}, {flag: "seen", of: 1}]}], + [{order: {total: 50, country: "DE"}}, {flags: [{flag: "seen", of: 0}]}], + [{order: {}}, {flags: [{flag: "seen", of: 0}]}], + [{total: 500}, {flags: [{flag: "seen", of: 0}]}], + ], +} + +{ + name: "collect transforms: dotted outputPath with passThrough keeps sibling objects", + graph: { + nodes: [ + {table: "t", hit: "collect", passThrough: true, outputPath: "result.hits", inputs: ["n"], outputs: ["v"], rules: [ + ["> 0", "1"], + ["> 1", "2"], + ]}, + ], + }, + cases: [ + [{n: 2, result: {score: 9}}, {n: 2, result: {score: 9, hits: [{v: 1}, {v: 2}]}}], + [{n: 0, result: {hits: [{v: 9}]}}, {n: 0, result: {hits: []}}], + [{n: 1}, {n: 1, result: {hits: [{v: 1}]}}], + ], +} + +{ + name: "collect transforms: loop with passThrough and outputPath on each item", + graph: { + nodes: [ + {table: "t", hit: "collect", executionMode: "loop", passThrough: true, inputField: "lines", outputPath: "lines", inputs: ["qty"], outputs: ["flag"], rules: [ + ["> 10", "'bulk'"], + ["> 0", "'some'"], + ]}, + ], + }, + cases: [ + [{id: 1, lines: [{qty: 20}, {qty: 0}]}, {id: 1, lines: [[{flag: "bulk"}, {flag: "some"}], []]}, "question: under loop+passThrough the collected array replaces each item rather than merging with it"], + [{id: 2, lines: []}, {id: 2, lines: []}], + ], +} + +{ + name: "collect transforms: loop, inputField and outputPath reading outer data via $nodes", + graph: { + nodes: [ + {table: "t", hit: "collect", executionMode: "loop", inputField: "users", outputPath: "access", inputs: ["role", null], outputs: ["grant"], rules: [ + ["'admin'", "", "'all'"], + ["", "contains($nodes.input.open, name)", "'open'"], + ["", "", "'read'"], + ]}, + ], + }, + cases: [ + [{open: ["bo"], users: [{name: "ann", role: "admin"}, {name: "bo", role: "user"}]}, {access: [[{grant: "all"}, {grant: "read"}], [{grant: "open"}, {grant: "read"}]]}], + [{open: [], users: [{name: "bo"}]}, {access: [[{grant: "read"}]]}], + ], +} + +// --- `[]` columns mixed with scalars under first hit -------------------------------------------------- + +{ + name: "mixed `[]`: the scalar comes from the first matching rule even when its cell is empty", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["label", "codes[]"], rules: [ + ["> 10", "", "'big'"], + ["> 0", "'positive'", "'pos'"], + ["", "'any'", "'any'"], + ]}, + ], + }, + cases: [ + [{n: 20}, {codes: ["big", "pos", "any"]}], + [{n: 5}, {label: "positive", codes: ["pos", "any"]}], + [{n: 0}, {label: "any", codes: ["any"]}], + ], +} + +{ + name: "mixed `[]`: scalars and arrays interleaved over shared nested paths", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r.tier", "r.why[]", "r.limit", "audit[]"], rules: [ + ["> 100", "'gold'", "'over 100'", "1000", "'r1'"], + ["> 10", "'silver'", "'over 10'", "100", ""], + ["", "'basic'", "", "10", "'r3'"], + ]}, + ], + }, + cases: [ + [{n: 200}, {r: {tier: "gold", why: ["over 100", "over 10"], limit: 1000}, audit: ["r1", "r3"]}], + [{n: 20}, {r: {tier: "silver", why: ["over 10"], limit: 100}, audit: ["r3"]}], + [{n: 1}, {r: {tier: "basic", why: [], limit: 10}, audit: ["r3"]}], + ], +} + +{ + name: "mixed `[]`: collected objects and arrays as values", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["items[]", "count"], rules: [ + ["> 1", "{id: 1, at: n}", "1"], + ["> 0", "[n]", "2"], + ["", "null", "3"], + ]}, + ], + }, + cases: [ + [{n: 2}, {items: [{id: 1, at: 2}, [2], null], count: 1}], + [{n: 1}, {items: [[1], null], count: 2}], + [{n: 0}, {items: [null], count: 3}], + ], +} + +{ + name: "mixed `[]`: loop mode collects per item", + graph: { + nodes: [ + {table: "t", executionMode: "loop", inputField: "items", outputPath: "out", inputs: ["v"], outputs: ["main", "all[]"], rules: [ + ["> 10", "'big'", "'b'"], + ["> 0", "'pos'", "'p'"], + ]}, + ], + }, + cases: [ + [{items: [{v: 20}, {v: 5}, {v: 0}]}, {out: [{all: ["b", "p"], main: "big"}, {all: ["p"], main: "pos"}, {all: []}]}], + [{items: []}, {out: []}], + ], +} + +{ + name: "mixed `[]`: outputPath and passThrough with an existing array at the target", + graph: { + nodes: [ + {table: "t", passThrough: true, outputPath: "res", inputs: ["n"], outputs: ["top", "tags[]"], rules: [ + ["> 1", "'a'", "'x'"], + ["> 0", "'b'", "'y'"], + ]}, + ], + }, + cases: [ + [{n: 2, res: {tags: ["old"], keep: 1}}, {n: 2, res: {top: "a", tags: ["x", "y"], keep: 1}}], + [{n: 1}, {n: 1, res: {top: "b", tags: ["y"]}}], + [{n: 0, res: {tags: ["old"]}}, {n: 0, res: {tags: []}}, "question: no matching rule writes the empty collect list at the output path, replacing the existing object"], + ], +} + +// --- Policies feeding control flow -------------------------------------------------------------------- + +{ + name: "control flow: a switch branches on the size of a collect result", + graph: { + nodes: [ + {table: "t", hit: "collect", outputPath: "flags", inputs: ["amount", "country"], outputs: ["f"], rules: [ + ["> 1000", "", "'amount'"], + ["", "'XX', 'YY'", "'country'"], + ]}, + {switch: "route", when: ["len(flags) >= 2", "len(flags) == 1", ""]}, + {expression: "block", fields: {decision: "'block'"}}, + {expression: "review", fields: {decision: "'review'", why: "flags[0].f"}}, + {expression: "pass", fields: {decision: "'pass'"}}, + ], + edges: ["input -> t -> route", "route:0 -> block -> output", "route:1 -> review -> output", "route:2 -> pass -> output"], + }, + cases: [ + [{amount: 5000, country: "XX"}, {decision: "block"}], + [{amount: 5000, country: "DE"}, {decision: "review", why: "amount"}], + [{amount: 5, country: "YY"}, {decision: "review", why: "country"}], + [{amount: 5, country: "DE"}, {decision: "pass"}], + [{}, {decision: "pass"}], + ], +} + +{ + name: "control flow: a first-hit miss versus an empty collect downstream", + graph: { + nodes: [ + {table: "first", outputPath: "first", inputs: ["k"], outputs: ["v"], rules: [["'a'", "1"]]}, + {table: "all", hit: "collect", outputPath: "all", inputs: ["k"], outputs: ["v"], rules: [["'a'", "1"]]}, + {expression: "e", fields: { + firstMissing: "first == null", + allEmpty: "len(all) == 0", + firstV: "first.v ?? -1", + allV: "all[0].v ?? -1", + }}, + ], + edges: ["input -> first -> e", "input -> all -> e", "e -> output"], + }, + cases: [ + [{k: "a"}, {firstMissing: false, allEmpty: false, firstV: 1, allV: 1}], + [{k: "b"}, {firstMissing: true, allEmpty: true, firstV: -1, allV: -1}], + ], +} diff --git a/core/engine/tests/spec/graph/59-table-cell-expressions.json5 b/core/engine/tests/spec/graph/59-table-cell-expressions.json5 new file mode 100644 index 00000000..4bed0923 --- /dev/null +++ b/core/engine/tests/spec/graph/59-table-cell-expressions.json5 @@ -0,0 +1,814 @@ +// Decision table cells as full expressions. An input cell under a column with a field is a unary +// test where `$` is the column's value; it may be any expression that produces a boolean, so +// closures, ternaries, function calls, date methods and arithmetic on `$` all work, and the cell +// may read other input fields and `$nodes` next to `$`. A cell under a field-less column is a +// standalone boolean expression. A cell that errors or produces a non-boolean does not match. +// Chapter 06 pins the cell forms; this chapter exercises expression-heavy cells and how they +// combine across columns, node data and the equality index. + +// --- Closures over input lists ------------------------------------------------------------------ + +{ + name: "closures: `$` is an array and cells test it with some, all, none and one", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["scores"], outputs: ["r"], rules: [ + ["some($, # >= 90)", "'has top score'"], + ["all($, # >= 50)", "'all pass'"], + ["none($, # < 0)", "'no negatives'"], + ["one($, # == 0)", "'exactly one zero'"], + ]}, + ], + }, + cases: [ + [{scores: [95, 60, 70]}, [{r: "has top score"}, {r: "all pass"}, {r: "no negatives"}]], + [{scores: [10, 0, 20]}, [{r: "no negatives"}, {r: "exactly one zero"}]], + [{scores: [0, 0, -1]}, []], + [{scores: []}, [{r: "all pass"}, {r: "no negatives"}]], + [{scores: null}, []], + [{}, []], + [{scores: 95}, []], + ], +} + +{ + name: "closures: a closure over `$` compares items with another input field", + graph: { + nodes: [ + {table: "t", inputs: ["items", "limit"], outputs: ["r"], rules: [ + ["some($, #.price > limit)", "", "'over limit'"], + ["len(filter($, #.qty > 0)) >= 2", "", "'several in stock'"], + ["", "", "'other'"], + ]}, + ], + }, + cases: [ + [{items: [{price: 5, qty: 1}, {price: 50, qty: 0}], limit: 20}, {r: "over limit"}], + [{items: [{price: 5, qty: 1}, {price: 10, qty: 3}], limit: 20}, {r: "several in stock"}], + [{items: [{price: 5, qty: 1}], limit: 20}, {r: "other"}], + [{items: [{price: 50, qty: 1}], limit: null}, {r: "other"}], + [{items: [], limit: 1}, {r: "other"}], + ], +} + +{ + name: "closures: a scalar `$` tested against a list from the input", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["r"], rules: [ + ["some(blocked, # == $)", "'blocked'"], + ["some(allowed, startsWith($, #))", "'allowed prefix'"], + ["", "'unknown'"], + ]}, + ], + }, + cases: [ + [{code: "X1", blocked: ["X1", "X2"], allowed: ["X"]}, {r: "blocked"}], + [{code: "X3", blocked: ["X1", "X2"], allowed: ["X"]}, {r: "allowed prefix"}], + [{code: "Y3", blocked: ["X1"], allowed: ["X", "Z"]}, {r: "unknown"}], + [{code: "Y3", blocked: [], allowed: []}, {r: "unknown"}], + [{code: "X3"}, {r: "unknown"}], + ], +} + +{ + name: "closures: nested closures and aggregates in cells", + graph: { + nodes: [ + {table: "t", inputs: ["orders"], outputs: ["r"], rules: [ + ["some($, some(#.lines, #.sku == 'GIFT'))", "'has gift'"], + ["sum(map($, sum(map(#.lines, #.qty)))) > 10", "'bulk'"], + ["count($, len(#.lines) == 0) > 0", "'empty order'"], + ["", "'normal'"], + ]}, + ], + }, + cases: [ + [{orders: [{lines: [{sku: "A", qty: 1}]}, {lines: [{sku: "GIFT", qty: 1}]}]}, {r: "has gift"}], + [{orders: [{lines: [{sku: "A", qty: 6}]}, {lines: [{sku: "B", qty: 5}]}]}, {r: "bulk"}], + [{orders: [{lines: [{sku: "A", qty: 1}]}, {lines: []}]}, {r: "empty order"}], + [{orders: [{lines: [{sku: "A", qty: 1}]}]}, {r: "normal"}], + [{orders: []}, {r: "normal"}], + ], +} + +{ + name: "closures: a field-less column with closures next to a field column", + graph: { + nodes: [ + {table: "t", inputs: ["tier", null], outputs: ["r"], rules: [ + ["'gold'", "some(items, #.price > 100)", "'gold with premium item'"], + ["'gold'", "all(items, #.price <= 100)", "'gold standard'"], + ["", "len(items) == 0", "'empty cart'"], + ["", "", "'other'"], + ]}, + ], + }, + cases: [ + [{tier: "gold", items: [{price: 150}]}, {r: "gold with premium item"}], + [{tier: "gold", items: [{price: 50}, {price: 100}]}, {r: "gold standard"}], + [{tier: "gold", items: []}, {r: "gold standard"}], + [{tier: "silver", items: []}, {r: "empty cart"}], + [{tier: "silver", items: [{price: 1}]}, {r: "other"}], + [{tier: "gold"}, {r: "other"}], + ], +} + +// --- Ternaries and conditionals ----------------------------------------------------------------------- + +{ + name: "ternaries: a ternary that yields booleans is a valid test", + graph: { + nodes: [ + {table: "t", inputs: ["amount"], outputs: ["r"], rules: [ + ["vip ? $ > 1000 : $ > 100", "'flag'"], + ["", "'ok'"], + ]}, + ], + }, + cases: [ + [{amount: 500, vip: true}, {r: "ok"}], + [{amount: 1500, vip: true}, {r: "flag"}], + [{amount: 500, vip: false}, {r: "flag"}], + [{amount: 50, vip: false}, {r: "ok"}], + [{amount: 500}, {r: "ok"}], + [{amount: 500, vip: "yes"}, {r: "ok"}], + ], +} + +{ + name: "ternaries: a ternary that yields a value compared afterwards", + graph: { + nodes: [ + {table: "t", inputs: ["kind"], outputs: ["r"], rules: [ + ["($ == 'b2b' ? net : gross) > 1000", "'large'"], + ["", "'small'"], + ]}, + ], + }, + cases: [ + [{kind: "b2b", net: 1500, gross: 10}, {r: "large"}], + [{kind: "b2c", net: 1500, gross: 10}, {r: "small"}], + [{kind: "b2c", net: 10, gross: 1500}, {r: "large"}], + [{kind: "b2b", gross: 1500}, {r: "small"}], + ], +} + +// A unary ternary whose branches are literal values is an equality test: `$ == (cond ? a : b)` +// (unary chapter 07 of the expression spec). Boolean literal branches follow the same rule, so +// `$ > 0 ? true : false` compares `$` with a boolean and never matches a number. +{ + name: "ternaries: a ternary with literal branches is compared with `$`", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["$ > 0 ? 'yes' : 'no'", "'string result'"], + ["$ > 0 ? 1 : 0", "'number result'"], + ["$ > 0 ? true : null", "'boolean result'"], + ["", "'fallback'"], + ]}, + ], + }, + cases: [ + [{n: 1}, {r: "number result"}], + [{n: 0}, {r: "number result"}], + [{n: 5}, {r: "fallback"}, "question: bool-literal branches make the cell `$ == ($ > 0 ? true : null)`, so a positive number never matches; the standard-mode reading of the cell is true (expression spec unary 07)"], + [{n: -5}, {r: "fallback"}], + [{n: true}, {r: "fallback"}], + [{}, {r: "fallback"}], + ], +} + +{ + name: "ternaries: a ternary over another field picks the value `$` must equal", + graph: { + nodes: [ + {table: "t", inputs: ["label"], outputs: ["r"], rules: [ + ["n > 0 ? 'pos' : 'neg'", "'consistent'"], + ["", "'inconsistent'"], + ]}, + ], + }, + cases: [ + [{label: "pos", n: 5}, {r: "consistent"}], + [{label: "neg", n: 5}, {r: "inconsistent"}], + [{label: "neg", n: -1}, {r: "consistent"}], + [{label: "neg", n: 0}, {r: "consistent"}], + [{label: "pos"}, {r: "inconsistent"}], + [{label: null, n: 1}, {r: "inconsistent"}], + ], +} + +{ + name: "ternaries: nested ternaries and `??` in field-less cells", + graph: { + nodes: [ + {table: "t", inputs: [null], outputs: ["r"], rules: [ + ["(country ?? 'US') == 'US' ? age >= 21 : age >= 18", "'may drink'"], + ["", "'may not'"], + ]}, + ], + }, + cases: [ + [{country: "US", age: 20}, {r: "may not"}], + [{country: "US", age: 21}, {r: "may drink"}], + [{country: "DE", age: 18}, {r: "may drink"}], + [{age: 20}, {r: "may not"}], + [{country: null, age: 25}, {r: "may drink"}], + [{country: "DE"}, {r: "may not"}], + ], +} + +{ + name: "ternaries: conditional output cells next to conditional input cells", + graph: { + nodes: [ + {table: "t", inputs: ["qty"], outputs: ["price", "note"], rules: [ + ["$ >= (wholesale ? 10 : 100)", "unit * $ * (wholesale ? 0.8 : 0.9)", "wholesale ? 'wholesale bulk' : 'retail bulk'"], + ["", "unit * qty", "'list'"], + ]}, + ], + }, + cases: [ + [{qty: 10, unit: 2, wholesale: true}, {price: 16, note: "wholesale bulk"}], + [{qty: 10, unit: 2, wholesale: false}, {price: 20, note: "list"}], + [{qty: 100, unit: 1, wholesale: false}, {price: 90, note: "retail bulk"}], + [{qty: 5, unit: 1, wholesale: true}, {price: 5, note: "list"}], + ], +} + +// --- Function calls ------------------------------------------------------------------------------------ + +{ + name: "functions: contains on a string `$` and on an array `$`", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["contains($, 'vip')", "'contains vip'"], + ["contains($, needle)", "'contains needle'"], + ["not contains($, 'x')", "'no x'"], + ]}, + ], + }, + cases: [ + [{v: "a vip x", needle: "a"}, [{r: "contains vip"}, {r: "contains needle"}]], + [{v: ["vip", "y"], needle: "y"}, [{r: "contains vip"}, {r: "contains needle"}, {r: "no x"}]], + [{v: "plain", needle: "z"}, [{r: "no x"}]], + [{v: [], needle: "z"}, [{r: "no x"}]], + [{v: 12, needle: "1"}, []], + [{v: null}, []], + ], +} + +{ + name: "functions: startsWith and endsWith with prefixes from other fields", + graph: { + nodes: [ + {table: "t", inputs: ["file"], outputs: ["r"], rules: [ + ["startsWith($, dir) and endsWith($, ext)", "'match'"], + ["startsWith($, dir)", "'in dir'"], + ["endsWith(lower($), lower(ext))", "'right type, case-insensitive'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{file: "/tmp/a.txt", dir: "/tmp/", ext: ".txt"}, {r: "match"}], + [{file: "/tmp/a.pdf", dir: "/tmp/", ext: ".txt"}, {r: "in dir"}], + [{file: "/home/A.TXT", dir: "/tmp/", ext: ".txt"}, {r: "right type, case-insensitive"}], + [{file: "/home/a.pdf", dir: "/tmp/", ext: ".txt"}, {r: "other"}], + [{file: "/tmp/a.txt", ext: ".txt"}, {r: "right type, case-insensitive"}], + [{file: null, dir: "/tmp/", ext: ".txt"}, {r: "other"}], + ], +} + +{ + name: "functions: string, number and type functions on `$`", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["v"], outputs: ["r"], rules: [ + ["type($) == 'string' and len(trim($)) == 0", "'blank string'"], + ["type($) == 'number' and round($) == $", "'whole number'"], + ["type($) == 'number' and abs($) < 1", "'small magnitude'"], + ["type($) == 'array' and len($) > 1", "'list'"], + ["matches(string($), '^[0-9]+$')", "'digits'"], + ]}, + ], + }, + cases: [ + [{v: " "}, [{r: "blank string"}]], + [{v: 42}, [{r: "whole number"}, {r: "digits"}]], + [{v: -0.5}, [{r: "small magnitude"}]], + [{v: 0}, [{r: "whole number"}, {r: "small magnitude"}, {r: "digits"}]], + [{v: "123"}, [{r: "digits"}]], + [{v: [1, 2]}, [{r: "list"}]], + [{v: true}, []], + ], +} + +{ + name: "functions: keys and values over an object `$`", + graph: { + nodes: [ + {table: "t", inputs: ["flags"], outputs: ["r"], rules: [ + ["contains(keys($), 'admin') and $.admin == true", "'admin'"], + ["len(keys($)) == 0", "'no flags'"], + ["all(values($), # == false)", "'all off'"], + ["", "'mixed'"], + ]}, + ], + }, + cases: [ + [{flags: {admin: true, beta: false}}, {r: "admin"}], + [{flags: {admin: false}}, {r: "all off"}], + [{flags: {}}, {r: "no flags"}], + [{flags: {beta: true, x: false}}, {r: "mixed"}], + [{}, {r: "mixed"}], + ], +} + +// --- Date methods --------------------------------------------------------------------------------------- + +{ + name: "dates: date methods on `$` in cells", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["at"], outputs: ["r"], rules: [ + ["d($).isBefore(d('2025-01-01'))", "'before 2025'"], + ["d($).year() == 2025", "'in 2025'"], + ["d($).weekday() >= 6", "'weekend'"], + ["d($).month() == 12", "'december'"], + ["d($).isValid() == false", "'invalid'"], + ]}, + ], + }, + cases: [ + [{at: "2024-12-28"}, [{r: "before 2025"}, {r: "weekend"}, {r: "december"}]], + [{at: "2025-03-20"}, [{r: "in 2025"}]], + [{at: "2025-03-22"}, [{r: "in 2025"}, {r: "weekend"}]], + [{at: "garbage"}, [{r: "invalid"}]], + [{at: null}, [{r: "invalid"}]], + ], +} + +{ + name: "dates: differences from now and between two fields", + graph: { + nodes: [ + {table: "t", inputs: ["birth", "joined"], outputs: ["r"], rules: [ + ["d().diff(d($), 'year') < 18", "", "'minor'"], + ["", "d().diff(d($), 'day') < 30", "'new member'"], + ["", "d($).diff(d(birth), 'year') < 18", "'joined as a minor'"], + ["", "", "'regular'"], + ]}, + ], + }, + cases: [ + [{birth: "2010-01-01", joined: "2020-01-01"}, {r: "minor"}], + [{birth: "1990-01-01", joined: "2025-03-10"}, {r: "new member"}], + [{birth: "1990-01-01", joined: "2000-01-01"}, {r: "joined as a minor"}], + [{birth: "1990-01-01", joined: "2015-01-01"}, {r: "regular"}], + [{birth: "2007-03-20", joined: "2015-01-01"}, {r: "joined as a minor"}], + [{birth: "2007-03-21", joined: "2024-01-01"}, {r: "minor"}], + ], +} + +{ + name: "dates: date arithmetic compared across columns", + graph: { + nodes: [ + {table: "t", inputs: ["due", "paid"], outputs: ["r"], rules: [ + ["", "d($).isAfter(d(due).add(30, 'd'))", "'very late'"], + ["", "d($).isAfter(d(due))", "'late'"], + ["", "d($).isSame(d(due), 'day')", "'on the day'"], + ["", "", "'early'"], + ]}, + ], + }, + cases: [ + [{due: "2025-01-01", paid: "2025-03-01"}, {r: "very late"}], + [{due: "2025-01-01", paid: "2025-01-31"}, {r: "late"}], + [{due: "2025-01-01", paid: "2025-01-01"}, {r: "on the day"}], + [{due: "2025-01-01", paid: "2024-12-01"}, {r: "early"}], + [{due: "2025-01-01"}, {r: "early"}], + ], +} + +{ + name: "dates: a date computed upstream compared with date methods", + graph: { + nodes: [ + {expression: "prep", fields: {start: "d(start)", end: "d(start).add(days, 'd')"}}, + {table: "t", inputs: ["end"], outputs: ["r", "endDay"], rules: [ + ["$.isAfter(start.endOf('month'))", "'crosses month'", "end.format('%Y-%m-%d')"], + ["", "'same month'", "end.format('%Y-%m-%d')"], + ]}, + ], + edges: ["input -> prep", "prep -> t -> output"], + }, + cases: [ + [{start: "2025-01-25", days: 10}, {r: "crosses month", endDay: "2025-02-04"}], + [{start: "2025-01-01", days: 10}, {r: "same month", endDay: "2025-01-11"}], + [{start: "2025-02-27", days: 1}, {r: "same month", endDay: "2025-02-28"}], + [{start: "2024-02-28", days: 1}, {r: "same month", endDay: "2024-02-29"}], + ], +} + +// --- Arithmetic on `$` --------------------------------------------------------------------------------- + +{ + name: "arithmetic: `$` scaled, offset and compared", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["n"], outputs: ["r"], rules: [ + ["$ * 2 > 10", "'double over 10'"], + ["$ % 2 == 0", "'even'"], + ["$ + offset >= target", "'reaches target'"], + ["abs($ - target) <= 0.5", "'near target'"], + ]}, + ], + }, + cases: [ + [{n: 6, offset: 0, target: 6}, [{r: "double over 10"}, {r: "even"}, {r: "reaches target"}, {r: "near target"}]], + [{n: 3, offset: 2, target: 5}, [{r: "reaches target"}]], + [{n: 4.6, offset: 0, target: 5}, [{r: "near target"}]], + [{n: 0, offset: 0, target: 1}, [{r: "even"}]], + [{n: -4, offset: 0, target: -4}, [{r: "even"}, {r: "reaches target"}, {r: "near target"}]], + [{n: 6}, [{r: "double over 10"}, {r: "even"}]], + [{n: "6", offset: 0, target: 6}, []], + ], +} + +{ + name: "arithmetic: exact decimals in `$` arithmetic", + graph: { + nodes: [ + {table: "t", inputs: ["a"], outputs: ["r"], rules: [ + ["$ + b == 0.3", "'exact'"], + ["", "'not exact'"], + ]}, + ], + }, + cases: [ + [{a: 0.1, b: 0.2}, {r: "exact"}], + [{a: 0.15, b: 0.15}, {r: "exact"}], + [{a: 0.3, b: 0}, {r: "exact"}], + [{a: 0.30000001, b: 0}, {r: "not exact"}], + [{a: 0.1}, {r: "not exact"}], + ], +} + +{ + name: "arithmetic: interval shorthand cannot be combined with arithmetic, use a full comparison", + graph: { + nodes: [ + {table: "t", inputs: ["n"], outputs: ["r"], rules: [ + ["$ * 2 in [10..20]", "'double in band'"], + ["$ / 2 >= 1 and $ / 2 <= 2", "'half in band'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{n: 5}, {r: "double in band"}], + [{n: 10}, {r: "double in band"}], + [{n: 3}, {r: "half in band"}], + [{n: 11}, {r: "other"}], + [{n: 2}, {r: "half in band"}], + ], +} + +{ + name: "arithmetic: a computed field with arithmetic cells over it", + graph: { + nodes: [ + {table: "t", inputs: ["price * qty", "discount"], outputs: ["net"], rules: [ + ["$ > 100", "$ > 0", "price * qty * (1 - discount)"], + ["$ > 100", "", "price * qty"], + ["", "", "price * qty + 5"], + ]}, + ], + }, + cases: [ + [{price: 50, qty: 3, discount: 0.1}, {net: 135}], + [{price: 50, qty: 3, discount: 0}, {net: 150}], + [{price: 50, qty: 3}, {net: 150}], + [{price: 10, qty: 3, discount: 0.5}, {net: 35}], + ], +} + +// --- Field-less columns mixed with field columns ----------------------------------------------- + +{ + name: "mixed columns: field-less cells between two field columns", + graph: { + nodes: [ + {table: "t", inputs: ["age", null, "country"], outputs: ["r"], rules: [ + [">= 18", "income > 1000", "'US'", "'adult earner us'"], + [">= 18", "income > 1000", "", "'adult earner'"], + [">= 18", "", "'US', 'CA'", "'adult na'"], + ["", "student == true", "", "'student'"], + ["", "", "", "'other'"], + ]}, + ], + }, + cases: [ + [{age: 30, income: 2000, country: "US"}, {r: "adult earner us"}], + [{age: 30, income: 2000, country: "DE"}, {r: "adult earner"}], + [{age: 30, income: 10, country: "CA"}, {r: "adult na"}], + [{age: 15, student: true, country: "US"}, {r: "student"}], + [{age: 15, country: "US"}, {r: "other"}], + [{age: 30, country: "US"}, {r: "adult na"}], + ], +} + +{ + name: "mixed columns: a field-less cell after a field column sees the leaked `$`", + graph: { + nodes: [ + {table: "t", inputs: ["a", null], outputs: ["r"], rules: [ + ["> 0", "$ == a", "'field-less sees $ as a'"], + ["", "$ == null", "'no $ bound'"], + ["", "", "'other'"], + ]}, + ], + }, + cases: [ + [{a: 5}, {r: "field-less sees $ as a"}, "question: a field-less cell has no defined `$`, yet it sees the value bound by the previous field column of the row"], + [{a: -5}, {r: "other"}, "question: the failed first rule bound `$` to -5, which the next rule's field-less cell still sees"], + ], +} + +{ + name: "mixed columns: two field-less columns and a field column on the same field", + graph: { + nodes: [ + {table: "t", inputs: [null, "score", null], outputs: ["r"], rules: [ + ["score != null", "> 50", "score < 100", "'mid-high'"], + ["score != null", "<= 50", "", "'low'"], + ["", "", "score == null", "'unscored'"], + ["", "", "", "'other'"], + ]}, + ], + }, + cases: [ + [{score: 70}, {r: "mid-high"}], + [{score: 100}, {r: "other"}], + [{score: 20}, {r: "low"}], + [{}, {r: "unscored"}], + [{score: null}, {r: "unscored"}], + [{score: "x"}, {r: "other"}], + ], +} + +{ + name: "mixed columns: a field-less column in a collect table with a `[]` output", + graph: { + nodes: [ + {table: "t", inputs: ["amount", null], outputs: ["level", "reasons[]"], rules: [ + ["> 1000", "", "'high'", "'amount over 1000'"], + ["", "country != home", "'medium'", "'foreign'"], + ["", "len(prior ?? []) == 0", "'medium'", "'first purchase'"], + ["", "", "'low'", ""], + ]}, + ], + }, + cases: [ + [{amount: 5000, country: "DE", home: "US"}, {level: "high", reasons: ["amount over 1000", "foreign", "first purchase"]}], + [{amount: 10, country: "US", home: "US", prior: [1]}, {level: "low", reasons: []}], + [{amount: 10, country: "DE", home: "US", prior: [1]}, {level: "medium", reasons: ["foreign"]}], + [{amount: 10, country: "US", home: "US"}, {level: "medium", reasons: ["first purchase"]}], + ], +} + +// --- Cells reading `$nodes` and input fields together --------------------------------------------- + +{ + name: "nodes: `$` compared with an upstream node's value", + graph: { + nodes: [ + {expression: "limits", fields: {min: "10", max: "100"}}, + {table: "t", inputs: ["amount"], outputs: ["r"], rules: [ + ["$ < $nodes.limits.min", "'below'"], + ["$ > $nodes.limits.max", "'above'"], + ["[$nodes.limits.min..$nodes.limits.max]", "'within'"], + ]}, + ], + edges: ["input -> limits", "input -> t -> output", "limits -> t"], + }, + cases: [ + [{amount: 5}, {r: "below"}], + [{amount: 500}, {r: "above"}], + [{amount: 10}, {r: "within"}], + [{amount: 100}, {r: "within"}], + [{amount: null}, {}], + ], +} + +{ + name: "nodes: field-less cells relating `$nodes` with input fields", + graph: { + nodes: [ + {expression: "stats", fields: {avg: "len(history) > 0 ? avg(map(history, #.amount)) : 0", n: "len(history)"}}, + {table: "t", inputs: [null, "amount"], outputs: ["r"], rules: [ + ["$nodes.stats.n == 0", "", "'no history'"], + ["", "$ > $nodes.stats.avg * 3", "'spike'"], + ["$nodes.stats.n > 5 and amount < $nodes.stats.avg", "", "'routine'"], + ["", "", "'normal'"], + ]}, + ], + edges: ["input -> stats", "input -> t -> output", "stats -> t"], + }, + cases: [ + [{history: [], amount: 50}, {r: "no history"}], + [{history: [{amount: 10}, {amount: 20}], amount: 100}, {r: "spike"}], + [{history: [{amount: 10}, {amount: 10}, {amount: 10}, {amount: 10}, {amount: 10}, {amount: 10}], amount: 5}, {r: "routine"}], + [{history: [{amount: 10}, {amount: 20}], amount: 20}, {r: "normal"}], + ], +} + +{ + name: "nodes: a column field from `$nodes` next to a column from the input", + graph: { + nodes: [ + {table: "risk", inputs: ["score"], outputs: ["band"], rules: [ + ["> 700", "'low'"], + ["> 500", "'medium'"], + ["", "'high'"], + ]}, + {table: "t", inputs: ["$nodes.risk.band", "amount"], outputs: ["decision", "band"], rules: [ + ["'low'", "", "'approve'", "$nodes.risk.band"], + ["'medium'", "<= limit", "'approve'", "$nodes.risk.band"], + ["'medium'", "", "'review'", "$nodes.risk.band"], + ["", "", "'decline'", "$nodes.risk.band"], + ]}, + ], + edges: ["input -> risk", "input -> t -> output", "risk -> t"], + }, + cases: [ + [{score: 800, amount: 1e6, limit: 0}, {decision: "approve", band: "low"}], + [{score: 600, amount: 100, limit: 500}, {decision: "approve", band: "medium"}], + [{score: 600, amount: 1000, limit: 500}, {decision: "review", band: "medium"}], + [{score: 100, amount: 1}, {decision: "decline", band: "high"}], + [{amount: 1}, {decision: "decline", band: "high"}], + ], +} + +{ + name: "nodes: cells reading `$nodes.input` after an upstream transform changed the input", + graph: { + nodes: [ + {expression: "norm", fields: {code: "upper(code)"}}, + {table: "t", inputs: ["code"], outputs: ["r"], rules: [ + ["$ == $nodes.input.code", "'already upper'"], + ["lower($) == $nodes.input.code", "'was lower'"], + ["", "'mixed'"], + ]}, + ], + }, + cases: [ + [{code: "AB"}, {r: "already upper"}], + [{code: "ab"}, {r: "was lower"}], + [{code: "Ab"}, {r: "mixed"}], + ], +} + +{ + name: "nodes: loop-mode cells reading the item, `$nodes` and the outer input", + graph: { + nodes: [ + {expression: "cfg", fields: {cap: "maxQty"}}, + {table: "t", executionMode: "loop", inputField: "lines", outputPath: "flags", inputs: ["qty", null], outputs: ["f"], rules: [ + ["$ > $nodes.cfg.cap", "", "'over cap'"], + ["", "contains($nodes.input.blocked, sku)", "'blocked sku'"], + ["", "", "'ok'"], + ]}, + ], + edges: ["input -> cfg", "input -> t -> output", "cfg -> t"], + }, + cases: [ + [{maxQty: 10, blocked: ["B"], lines: [{sku: "A", qty: 20}, {sku: "B", qty: 1}, {sku: "C", qty: 1}]}, {flags: [{f: "over cap"}, {f: "blocked sku"}, {f: "ok"}]}], + [{maxQty: 10, blocked: [], lines: []}, {flags: []}], + ], +} + +// --- `$` in output cells and the equality index ------------------------------------------------- + +{ + name: "index: `$` in an output cell of a small table with a range column then an equality column", + graph: { + nodes: [ + {table: "t", inputs: ["amount", "code"], outputs: ["seen"], rules: [ + ["> 0", "'a'", "$"], + ["> 0", "'b'", "$"], + ["> 0", "'c'", "$"], + ]}, + ], + }, + cases: [ + [{amount: 5, code: "a"}, {seen: "a"}, "question: `$` in an output cell is the last bound input column value (chapter 06)"], + [{amount: 5, code: "c"}, {seen: "c"}, "question: `$` in an output cell is the last bound input column value (chapter 06)"], + ], +} + +{ + name: "index: `$` in an output cell of the same table with eight rules (equality-indexed)", + graph: { + nodes: [ + {table: "t", inputs: ["amount", "code"], outputs: ["seen"], rules: [ + ["> 0", "'a'", "$"], + ["> 0", "'b'", "$"], + ["> 0", "'c'", "$"], + ["> 0", "'d'", "$"], + ["> 0", "'e'", "$"], + ["> 0", "'f'", "$"], + ["> 0", "'g'", "$"], + ["> 0", "'h'", "$"], + ]}, + ], + }, + cases: [ + [{amount: 5, code: "a"}, {seen: "a"}, "question: `$` in an output cell is the last bound input column value; the reference walker has no index and gives the code, but with the equality index built (DecisionEngine) the index-decided `code` column is never rebound and `$` is the amount (5)"], + [{amount: 5, code: "h"}, {seen: "h"}, "question: `$` in an output cell is the last bound input column value; the reference walker has no index and gives the code, but with the equality index built (DecisionEngine) the index-decided `code` column is never rebound and `$` is the amount (5)"], + ], +} + +{ + name: "index: expression cells in an indexed table are evaluated in rule order with the indexed ones", + graph: { + nodes: [ + {table: "t", inputs: ["code"], outputs: ["r"], rules: [ + ["'a'", "'eq a'"], + ["startsWith($, 'a')", "'starts a'"], + ["'b'", "'eq b'"], + ["len($) > 3", "'long'"], + ["'c'", "'eq c'"], + ["$ in ['d', 'e']", "'d or e'"], + ["'abcd'", "'eq abcd'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{code: "a"}, {r: "eq a"}], + [{code: "ab"}, {r: "starts a"}], + [{code: "abcd"}, {r: "starts a"}], + [{code: "bcde"}, {r: "long"}], + [{code: "b"}, {r: "eq b"}], + [{code: "e"}, {r: "d or e"}], + [{code: "z"}, {r: "any"}], + [{code: 1}, {r: "any"}], + ], +} + +{ + name: "index: the same indexed table under collect", + graph: { + nodes: [ + {table: "t", hit: "collect", inputs: ["code"], outputs: ["r"], rules: [ + ["'a'", "'eq a'"], + ["startsWith($, 'a')", "'starts a'"], + ["'b'", "'eq b'"], + ["len($) > 3", "'long'"], + ["'c'", "'eq c'"], + ["$ in ['d', 'e']", "'d or e'"], + ["'abcd'", "'eq abcd'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{code: "a"}, [{r: "eq a"}, {r: "starts a"}, {r: "any"}]], + [{code: "abcd"}, [{r: "starts a"}, {r: "long"}, {r: "eq abcd"}, {r: "any"}]], + [{code: "d"}, [{r: "d or e"}, {r: "any"}]], + [{code: null}, [{r: "any"}]], + [{}, [{r: "any"}]], + ], +} + +// --- Realistic combination --------------------------------------------------------------------- + +{ + name: "realistic: fraud screening with closures, dates, `$nodes` and arithmetic", + graph: { + nodes: [ + {expression: "profile", fields: { + avg: "len(history) > 0 ? avg(map(history, #.amount)) : 0", + countries: "map(history, #.country)", + }}, + {table: "t", hit: "collect", outputPath: "hits", inputs: ["amount", "country", null], outputs: ["rule", "weight"], rules: [ + ["$nodes.profile.avg > 0 and $ > $nodes.profile.avg * 5", "", "", "'amount spike'", "40"], + ["", "not contains($nodes.profile.countries, $)", "len(history) > 0", "'new country'", "30"], + ["", "", "d(at).hour() < 6", "'night time'", "10"], + ["", "", "some(history, d(#.at).isSame(d(at), 'day') and #.amount == amount)", "'duplicate'", "50"], + ]}, + {expression: "score", fields: {total: "sum(map(hits, #.weight))", rules: "map(hits, #.rule)"}}, + ], + edges: ["input -> profile", "input -> t", "profile -> t", "t -> score -> output"], + }, + cases: [ + [{amount: 1000, country: "DE", at: "2025-03-20T03:00:00Z", history: [{amount: 100, country: "US", at: "2025-03-01T10:00:00Z"}]}, {total: 80, rules: ["amount spike", "new country", "night time"]}], + [{amount: 100, country: "US", at: "2025-03-01T12:00:00Z", history: [{amount: 100, country: "US", at: "2025-03-01T10:00:00Z"}]}, {total: 50, rules: ["duplicate"]}], + [{amount: 50, country: "US", at: "2025-03-20T12:00:00Z", history: []}, {total: 0, rules: []}], + ], +} diff --git a/core/engine/tests/spec/graph/60-realistic-healthcare.json5 b/core/engine/tests/spec/graph/60-realistic-healthcare.json5 new file mode 100644 index 00000000..d54140e6 --- /dev/null +++ b/core/engine/tests/spec/graph/60-realistic-healthcare.json5 @@ -0,0 +1,509 @@ +// Realistic healthcare decisions: emergency triage through a first-hit switch whose branches +// meet at a wait-target table, benefit cost sharing with deductible and out-of-pocket caps, +// weight and renal dosing checks with first-hit severity plus collected alerts, specialist +// appointment eligibility over dates (evaluation time is fixed at Thursday +// 2025-03-20T10:15:30Z), drug interaction screening through a loop table and a function node, +// and lab result interpretation through a sub-decision in loop mode. Each suite is one decision +// exercised across main paths, boundaries, missing data and bad types. + +// --------------------------------------------------------------------------------------------- +// Emergency triage (ESI-like): a pass-through expression derives the shock index and the +// number of planned resources, a column-less table collects danger-zone vitals through +// `dangerFlags[]`, a first-hit switch assigns the level, and every branch meets at a wait table. +// A condition that errors on a missing value is false as a whole, so a missing pain score hides +// the GCS term next to it. +{ + name: "triage: danger-zone vitals, resources and the acuity level", + graph: { + nodes: [ + {input: "patient"}, + {expression: "vitalsCalc", passThrough: true, fields: { + shockIndex: "round(vitals.hr / vitals.sbp, 2)", + resources: "len(filter(plannedResources ?? [], # in ['labs', 'ecg', 'xray', 'ct', 'iv', 'consult', 'procedure']))", + }}, + {table: "danger", passThrough: true, inputs: [null], outputs: ["dangerFlags[]"], rules: [ + ["vitals.hr > 100", "'tachycardia'"], + ["vitals.rr > 20", "'tachypnea'"], + ["vitals.spo2 < 92", "'hypoxia'"], + ["shockIndex >= 1", "'shock index'"], + ["ageMonths < 3 and vitals.temp >= 38", "'febrile infant'"], + ["", ""], + ]}, + {switch: "esi", when: [ + "airway == 'compromised' or vitals.gcs <= 8 or vitals.spo2 < 85", + "len(dangerFlags) >= 2 or painScore >= 7 or vitals.gcs < 15", + "resources >= 2 or len(dangerFlags) == 1", + "resources == 1", + "", + ]}, + {expression: "resus", fields: {level: "1", area: "'resus'", flags: "dangerFlags"}}, + {expression: "emergent", fields: {level: "2", area: "'acute'", flags: "dangerFlags"}}, + {expression: "urgent", fields: {level: "3", area: "'acute'", flags: "dangerFlags"}}, + {expression: "lessUrgent", fields: {level: "4", area: "'fast-track'", flags: "dangerFlags"}}, + {expression: "nonUrgent", fields: {level: "5", area: "'fast-track'", flags: "dangerFlags"}}, + {table: "waitTarget", passThrough: true, inputs: ["level"], outputs: ["maxWaitMin"], rules: [ + ["1", "0"], + ["2", "10"], + ["3", "30"], + ["4", "60"], + ["5", "120"], + ]}, + {output: "disposition"}, + ], + edges: [ + "patient -> vitalsCalc -> danger -> esi", + "esi:0 -> resus -> waitTarget", + "esi:1 -> emergent -> waitTarget", + "esi:2 -> urgent -> waitTarget", + "esi:3 -> lessUrgent -> waitTarget", + "esi:4 -> nonUrgent -> waitTarget", + "waitTarget -> disposition", + ], + }, + cases: [ + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 80, sbp: 120, rr: 16, spo2: 98, gcs: 15, temp: 37}, plannedResources: []}, {level: 5, area: "fast-track", flags: [], maxWaitMin: 120}], + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 80, sbp: 120, rr: 16, spo2: 98, gcs: 15, temp: 37}, plannedResources: ["labs"]}, {level: 4, area: "fast-track", flags: [], maxWaitMin: 60}], + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 80, sbp: 120, rr: 16, spo2: 98, gcs: 15, temp: 37}, plannedResources: ["labs", "xray", "ice pack"]}, {level: 3, area: "acute", flags: [], maxWaitMin: 30}], + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 110, sbp: 120, rr: 16, spo2: 98, gcs: 15, temp: 37}, plannedResources: []}, {level: 3, area: "acute", flags: ["tachycardia"], maxWaitMin: 30}], + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 125, sbp: 110, rr: 24, spo2: 95, gcs: 15, temp: 37}, plannedResources: ["labs"]}, {level: 2, area: "acute", flags: ["tachycardia", "tachypnea", "shock index"], maxWaitMin: 10}], + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 90, sbp: 120, rr: 16, spo2: 84, gcs: 15, temp: 37}, plannedResources: []}, {level: 1, area: "resus", flags: ["hypoxia"], maxWaitMin: 0}], + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 90, sbp: 120, rr: 16, spo2: 85, gcs: 15, temp: 37}, plannedResources: []}, {level: 3, area: "acute", flags: ["hypoxia"], maxWaitMin: 30}], + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 90, sbp: 120, rr: 16, spo2: 92, gcs: 15, temp: 37}, plannedResources: []}, {level: 5, area: "fast-track", flags: [], maxWaitMin: 120}], + [{ageMonths: 360, airway: "patent", painScore: 0, vitals: {hr: 70, sbp: 130, rr: 12, spo2: 97, gcs: 8, temp: 36.5}, plannedResources: ["ct"]}, {level: 1, area: "resus", flags: [], maxWaitMin: 0}], + [{ageMonths: 360, airway: "patent", painScore: 0, vitals: {hr: 70, sbp: 130, rr: 12, spo2: 97, gcs: 14, temp: 36.5}, plannedResources: ["ct"]}, {level: 2, area: "acute", flags: [], maxWaitMin: 10}], + [{ageMonths: 360, airway: "compromised", painScore: 0, vitals: {hr: 70, sbp: 130, rr: 12, spo2: 97, gcs: 15, temp: 36.5}}, {level: 1, area: "resus", flags: [], maxWaitMin: 0}], + [{ageMonths: 360, airway: "patent", painScore: 7, vitals: {hr: 80, sbp: 120, rr: 16, spo2: 98, gcs: 15, temp: 37}}, {level: 2, area: "acute", flags: [], maxWaitMin: 10}], + [{ageMonths: 360, airway: "patent", painScore: 6, vitals: {hr: 80, sbp: 120, rr: 16, spo2: 98, gcs: 15, temp: 37}}, {level: 5, area: "fast-track", flags: [], maxWaitMin: 120}], + [{ageMonths: 2, airway: "patent", painScore: 0, vitals: {hr: 160, sbp: 80, rr: 40, spo2: 97, gcs: 15, temp: 38}}, {level: 2, area: "acute", flags: ["tachycardia", "tachypnea", "shock index", "febrile infant"], maxWaitMin: 10}], + [{ageMonths: 3, airway: "patent", painScore: 0, vitals: {hr: 90, sbp: 100, rr: 18, spo2: 99, gcs: 15, temp: 38.5}}, {level: 5, area: "fast-track", flags: [], maxWaitMin: 120}], + [{ageMonths: 360, airway: "patent", painScore: 2, vitals: {hr: 100, sbp: 100, rr: 20, spo2: 96, gcs: 15, temp: 37}, plannedResources: ["iv", "labs"]}, {level: 3, area: "acute", flags: ["shock index"], maxWaitMin: 30}], + // Missing pain score: the second condition errors on `painScore >= 7` before reaching the + // GCS term, so a confused patient (GCS 14) is not upgraded. The decision has to default it. + [{ageMonths: 360, airway: "patent", vitals: {hr: 80, sbp: 120, rr: 16, spo2: 98, gcs: 14, temp: 37}}, {level: 5, area: "fast-track", flags: [], maxWaitMin: 120}], + // A missing temperature only skips the febrile-infant rule; a missing airway compares unequal. + [{ageMonths: 1, painScore: 0, vitals: {hr: 90, sbp: 100, rr: 18, spo2: 99, gcs: 15}}, {level: 5, area: "fast-track", flags: [], maxWaitMin: 120}], + // The shock index needs both vitals: a missing or zero systolic pressure (division by zero is + // null) and a string heart rate fail the first expression node. + [{ageMonths: 360, painScore: 0, vitals: {hr: 90, rr: 18, spo2: 99, gcs: 15, temp: 37}}, "!error"], + [{ageMonths: 360, painScore: 0, vitals: {hr: 90, sbp: 0, rr: 18, spo2: 99, gcs: 15, temp: 37}}, "!error"], + [{ageMonths: 360, painScore: 0, vitals: {hr: "90", sbp: 120, rr: 18, spo2: 99, gcs: 15, temp: 37}}, "!error"], + [{ageMonths: 360, painScore: 0, vitals: {hr: 90, sbp: 120, rr: 18, spo2: 99, gcs: 15, temp: 37}, plannedResources: "labs"}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Benefit cost sharing: plan limits and a benefit row by plan, network and category, a gate +// that denies uncovered services and pends missing prior authorization, then the deductible, +// copay and coinsurance are applied in order and capped by the remaining out-of-pocket room. +{ + name: "benefits: deductible, copay, coinsurance and the out-of-pocket cap", + graph: { + nodes: [ + {input: "claim"}, + {table: "planLimits", passThrough: true, inputs: ["plan.type", "service.network"], outputs: ["limits.deductible", "limits.oopMax"], rules: [ + ["'hmo'", "", "500", "4000"], + ["'ppo'", "'in'", "1000", "5000"], + ["'ppo'", "'out'", "2500", "10000"], + ["'hdhp'", "", "3000", "7000"], + ]}, + {table: "benefit", passThrough: true, inputs: ["plan.type", "service.network", "service.category"], outputs: ["benefit.covered", "benefit.copay", "benefit.coinsurance", "benefit.deductibleApplies", "benefit.authRequired"], rules: [ + ["'hmo'", "'out'", "'er'", "true", "150", "0", "false", "false"], + ["'hmo'", "'out'", "", "false", "0", "0", "false", "false"], + ["", "", "'cosmetic'", "false", "0", "0", "false", "false"], + ["'hdhp'", "", "'rx-generic'", "true", "10", "0", "false", "false"], + ["'hdhp'", "", "", "true", "0", "0.2", "true", "false"], + ["", "", "'primary'", "true", "20", "0", "false", "false"], + ["", "'in'", "'specialist'", "true", "40", "0", "false", "false"], + ["", "'out'", "'specialist'", "true", "0", "0.4", "true", "false"], + ["", "", "'er'", "true", "250", "0.1", "true", "false"], + ["", "'in'", "'imaging'", "true", "0", "0.2", "true", "true"], + ["", "'out'", "'imaging'", "true", "0", "0.4", "true", "true"], + ["", "", "'rx-generic'", "true", "10", "0", "false", "false"], + ["", "", "'rx-brand'", "true", "45", "0", "false", "false"], + ]}, + {switch: "gate", when: [ + "benefit == null or benefit.covered == false", + "benefit.authRequired and service.priorAuth != true", + "", + ]}, + {expression: "denied", fields: {status: "'denied'", reason: "'not covered'", planPays: "0", memberPays: "service.charge"}}, + {expression: "pended", fields: {status: "'pended'", reason: "'prior authorization required'", planPays: "0", memberPays: "0"}}, + {expression: "deductible", passThrough: true, fields: { + "calc.dedRemaining": "benefit.deductibleApplies ? max([0, limits.deductible - (accumulators.deductibleMet ?? 0)]) : 0", + "calc.dedApplied": "min([service.charge, $.calc.dedRemaining])", + "calc.afterDed": "service.charge - $.calc.dedApplied", + "calc.copay": "min([benefit.copay, $.calc.afterDed])", + "calc.coins": "round(($.calc.afterDed - $.calc.copay) * benefit.coinsurance, 2)", + "calc.memberRaw": "$.calc.dedApplied + $.calc.copay + $.calc.coins", + }}, + {expression: "oopCap", fields: { + oopRemaining: "max([0, limits.oopMax - (accumulators.oopMet ?? 0)])", + memberPays: "min([calc.memberRaw, $.oopRemaining])", + planPays: "service.charge - $.memberPays", + status: "'approved'", + reason: "$.memberPays < calc.memberRaw ? 'out-of-pocket maximum reached' : 'cost share applied'", + }}, + {output: "adjudication"}, + ], + edges: [ + "claim -> planLimits -> benefit -> gate", + "gate:0 -> denied -> adjudication", + "gate:1 -> pended -> adjudication", + "gate:2 -> deductible -> oopCap -> adjudication", + ], + }, + cases: [ + [{plan: {type: "ppo"}, service: {category: "primary", network: "in", charge: 150}, accumulators: {deductibleMet: 0, oopMet: 0}}, {oopRemaining: 5000, memberPays: 20, planPays: 130, status: "approved", reason: "cost share applied"}], + [{plan: {type: "ppo"}, service: {category: "specialist", network: "in", charge: 300}, accumulators: {deductibleMet: 0, oopMet: 0}}, {oopRemaining: 5000, memberPays: 40, planPays: 260, status: "approved", reason: "cost share applied"}], + [{plan: {type: "ppo"}, service: {category: "specialist", network: "out", charge: 1000}, accumulators: {deductibleMet: 2000, oopMet: 0}}, {oopRemaining: 10000, memberPays: 700, planPays: 300, status: "approved", reason: "cost share applied"}], + [{plan: {type: "ppo"}, service: {category: "er", network: "in", charge: 2000}, accumulators: {deductibleMet: 1000, oopMet: 4800}}, {oopRemaining: 200, memberPays: 200, planPays: 1800, status: "approved", reason: "out-of-pocket maximum reached"}], + [{plan: {type: "ppo"}, service: {category: "er", network: "in", charge: 2000}, accumulators: {deductibleMet: 1000, oopMet: 4575}}, {oopRemaining: 425, memberPays: 425, planPays: 1575, status: "approved", reason: "cost share applied"}], + [{plan: {type: "hmo"}, service: {category: "er", network: "out", charge: 1200}, accumulators: {deductibleMet: 0, oopMet: 0}}, {oopRemaining: 4000, memberPays: 150, planPays: 1050, status: "approved", reason: "cost share applied"}], + [{plan: {type: "hmo"}, service: {category: "specialist", network: "out", charge: 300}, accumulators: {deductibleMet: 0, oopMet: 0}}, {status: "denied", reason: "not covered", planPays: 0, memberPays: 300}], + [{plan: {type: "ppo"}, service: {category: "cosmetic", network: "in", charge: 5000}}, {status: "denied", reason: "not covered", planPays: 0, memberPays: 5000}], + [{plan: {type: "ppo"}, service: {category: "imaging", network: "in", charge: 800}}, {status: "pended", reason: "prior authorization required", planPays: 0, memberPays: 0}], + [{plan: {type: "ppo"}, service: {category: "imaging", network: "in", charge: 800, priorAuth: false}}, {status: "pended", reason: "prior authorization required", planPays: 0, memberPays: 0}], + [{plan: {type: "ppo"}, service: {category: "imaging", network: "in", charge: 800, priorAuth: true}, accumulators: {deductibleMet: 600, oopMet: 600}}, {oopRemaining: 4400, memberPays: 480, planPays: 320, status: "approved", reason: "cost share applied"}], + [{plan: {type: "hdhp"}, service: {category: "primary", network: "in", charge: 150}, accumulators: {deductibleMet: 0, oopMet: 0}}, {oopRemaining: 7000, memberPays: 150, planPays: 0, status: "approved", reason: "cost share applied"}], + [{plan: {type: "hdhp"}, service: {category: "rx-generic", network: "in", charge: 30}, accumulators: {deductibleMet: 0, oopMet: 0}}, {oopRemaining: 7000, memberPays: 10, planPays: 20, status: "approved", reason: "cost share applied"}], + // The HDHP catch-all row sits above the imaging rows, so HDHP imaging needs no authorization. + [{plan: {type: "hdhp"}, service: {category: "imaging", network: "in", charge: 1000}, accumulators: {deductibleMet: 2900, oopMet: 2900}}, {oopRemaining: 4100, memberPays: 280, planPays: 720, status: "approved", reason: "cost share applied"}], + [{plan: {type: "ppo"}, service: {category: "primary", network: "in", charge: 0}}, {oopRemaining: 5000, memberPays: 0, planPays: 0, status: "approved", reason: "cost share applied"}], + [{plan: {type: "ppo"}, service: {category: "primary", network: "in", charge: 12.5}}, {oopRemaining: 5000, memberPays: 12.5, planPays: 0, status: "approved", reason: "cost share applied"}], + [{plan: {type: "ppo"}, service: {category: "specialist", network: "out", charge: 1000}}, {oopRemaining: 10000, memberPays: 1000, planPays: 0, status: "approved", reason: "cost share applied"}], + [{plan: {type: "ppo"}, service: {category: "rx-brand", network: "in", charge: 300}, accumulators: {deductibleMet: 0, oopMet: 5200}}, {oopRemaining: 0, memberPays: 0, planPays: 300, status: "approved", reason: "out-of-pocket maximum reached"}], + [{plan: {type: "ppo"}, service: {category: "specialist", network: "out", charge: 333.33}, accumulators: {deductibleMet: 2500, oopMet: 0}}, {oopRemaining: 10000, memberPays: 133.33, planPays: 200, status: "approved", reason: "cost share applied"}], + // Unknown categories match no benefit row and are denied; a case-mismatched network too. + [{plan: {type: "ppo"}, service: {category: "dental", network: "in", charge: 400}}, {status: "denied", reason: "not covered", planPays: 0, memberPays: 400}], + [{plan: {type: "ppo"}, service: {category: "specialist", network: "IN", charge: 400}}, {status: "denied", reason: "not covered", planPays: 0, memberPays: 400}], + // Without a plan the benefit still matches a plan-agnostic row, but no limits exist and the + // out-of-pocket arithmetic fails; a string charge fails the deductible step. + [{service: {category: "primary", network: "in", charge: 150}}, "!error"], + [{plan: {type: "ppo"}, service: {category: "primary", network: "in", charge: "150"}}, "!error"], + // A missing charge on a denied claim reads as null and the null field is dropped. + [{plan: {type: "ppo"}, service: {category: "cosmetic", network: "in"}}, {status: "denied", reason: "not covered", planPays: 0}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dosing check: creatinine clearance (Cockcroft-Gault, only when a creatinine is known), daily +// and per-kg dose, the formulary reference, a renal factor for renally cleared drugs, then a +// column-less table where `severity` is first hit and `alerts[]` collects every matching row. +{ + name: "dosing: formulary limits, per-kg dose and renal adjustment", + graph: { + nodes: [ + {input: "order"}, + {expression: "derive", passThrough: true, fields: { + "renal.crcl": "patient.scr == null ? null : round((140 - patient.age) * patient.weightKg / (72 * patient.scr) * (patient.sex == 'female' ? 0.85 : 1))", + "dosing.daily": "order.doseMg * order.frequencyPerDay", + "dosing.perKg": "round(order.doseMg / patient.weightKg, 2)", + }}, + {table: "formulary", passThrough: true, inputs: ["order.drug"], outputs: ["ref.mgPerKgMax", "ref.maxSingleMg", "ref.maxDailyMg", "ref.renalCleared"], rules: [ + ["'amoxicillin'", "25", "1000", "3000", "true"], + ["'acetaminophen'", "15", "1000", "4000", "false"], + ["'ibuprofen'", "10", "800", "3200", "true"], + ["'gentamicin'", "2.5", "500", "600", "true"], + ]}, + {table: "renalAdjust", passThrough: true, inputs: ["ref.renalCleared", "renal.crcl"], outputs: ["ref.renalFactor", "ref.renalNote"], rules: [ + ["true", "< 30", "0.5", "'severe renal impairment: halve the daily maximum'"], + ["true", "[30..59]", "0.75", "'moderate renal impairment'"], + ["", "", "1", "null"], + ]}, + {table: "checks", inputs: [null], outputs: ["severity", "alerts[]"], rules: [ + ["ref.maxDailyMg == null", "'block'", "'drug not in formulary'"], + ["order.doseMg > ref.maxSingleMg", "'block'", "'single dose above maximum'"], + ["dosing.daily > ref.maxDailyMg * ref.renalFactor", "'block'", "'daily dose above maximum'"], + ["dosing.perKg > ref.mgPerKgMax", "'warn'", "'dose per kg above reference'"], + ["ref.renalFactor < 1", "'warn'", "ref.renalNote"], + ["", "'ok'", ""], + ]}, + {expression: "result", fields: { + severity: "severity", + alerts: "alerts", + crcl: "$nodes.derive.renal.crcl", + maxDailyMg: "$nodes.renalAdjust.ref.maxDailyMg == null ? null : $nodes.renalAdjust.ref.maxDailyMg * $nodes.renalAdjust.ref.renalFactor", + }}, + {output: "verdict"}, + ], + }, + cases: [ + [{patient: {age: 40, weightKg: 80, sex: "male", scr: 1.0}, order: {drug: "amoxicillin", doseMg: 500, frequencyPerDay: 3}}, {severity: "ok", alerts: [], crcl: 111, maxDailyMg: 3000}], + [{patient: {age: 40, weightKg: 80, sex: "male", scr: 1.0}, order: {drug: "amoxicillin", doseMg: 1000, frequencyPerDay: 4}}, {severity: "block", alerts: ["daily dose above maximum"], crcl: 111, maxDailyMg: 3000}], + [{patient: {age: 40, weightKg: 80, sex: "male", scr: 1.0}, order: {drug: "amoxicillin", doseMg: 1000, frequencyPerDay: 3}}, {severity: "ok", alerts: [], crcl: 111, maxDailyMg: 3000}], + [{patient: {age: 40, weightKg: 80, sex: "male", scr: 1.0}, order: {drug: "amoxicillin", doseMg: 1200, frequencyPerDay: 2}}, {severity: "block", alerts: ["single dose above maximum"], crcl: 111, maxDailyMg: 3000}], + [{patient: {age: 80, weightKg: 60, sex: "female", scr: 1.5}, order: {drug: "amoxicillin", doseMg: 500, frequencyPerDay: 3}}, {severity: "warn", alerts: ["severe renal impairment: halve the daily maximum"], crcl: 28, maxDailyMg: 1500}], + [{patient: {age: 80, weightKg: 60, sex: "female", scr: 1.5}, order: {drug: "amoxicillin", doseMg: 500, frequencyPerDay: 4}}, {severity: "block", alerts: ["daily dose above maximum", "severe renal impairment: halve the daily maximum"], crcl: 28, maxDailyMg: 1500}], + [{patient: {age: 80, weightKg: 60, sex: "male", scr: 1.5}, order: {drug: "amoxicillin", doseMg: 500, frequencyPerDay: 3}}, {severity: "warn", alerts: ["moderate renal impairment"], crcl: 33, maxDailyMg: 2250}], + [{patient: {age: 70, weightKg: 70, sex: "male", scr: 1.2}, order: {drug: "ibuprofen", doseMg: 400, frequencyPerDay: 3}}, {severity: "warn", alerts: ["moderate renal impairment"], crcl: 57, maxDailyMg: 2400}], + [{patient: {age: 68, weightKg: 30, sex: "male", scr: 1.0}, order: {drug: "gentamicin", doseMg: 75, frequencyPerDay: 1}}, {severity: "warn", alerts: ["moderate renal impairment"], crcl: 30, maxDailyMg: 450}], + [{patient: {age: 68, weightKg: 30, sex: "male", scr: 1.0}, order: {drug: "gentamicin", doseMg: 76, frequencyPerDay: 1}}, {severity: "warn", alerts: ["dose per kg above reference", "moderate renal impairment"], crcl: 30, maxDailyMg: 450}], + [{patient: {age: 80, weightKg: 72, sex: "male", scr: 1.0}, order: {drug: "ibuprofen", doseMg: 400, frequencyPerDay: 3}}, {severity: "ok", alerts: [], crcl: 60, maxDailyMg: 3200}], + // Acetaminophen is not renally cleared: severe impairment changes nothing. + [{patient: {age: 80, weightKg: 60, sex: "female", scr: 1.5}, order: {drug: "acetaminophen", doseMg: 1000, frequencyPerDay: 4}}, {severity: "warn", alerts: ["dose per kg above reference"], crcl: 28, maxDailyMg: 4000}], + // Pediatric orders without a creatinine: the clearance is null (and dropped from the result), + // the renal range cells fail against null and the catch-all keeps the full maximum. + [{patient: {age: 6, weightKg: 20}, order: {drug: "acetaminophen", doseMg: 300, frequencyPerDay: 4}}, {severity: "ok", alerts: [], maxDailyMg: 4000}], + [{patient: {age: 6, weightKg: 20}, order: {drug: "acetaminophen", doseMg: 400, frequencyPerDay: 4}}, {severity: "warn", alerts: ["dose per kg above reference"], maxDailyMg: 4000}], + [{patient: {age: 6, weightKg: 20}, order: {drug: "amoxicillin", doseMg: 250, frequencyPerDay: 3}}, {severity: "ok", alerts: [], maxDailyMg: 3000}], + [{patient: {age: 6, weightKg: 20}, order: {drug: "amoxicillin", doseMg: 600, frequencyPerDay: 6}}, {severity: "block", alerts: ["daily dose above maximum", "dose per kg above reference"], maxDailyMg: 3000}], + // Drugs outside the formulary block; the other rules fail against the missing references and + // the null maximum is dropped from the result. + [{patient: {age: 50, weightKg: 70, sex: "male", scr: 1.0}, order: {drug: "warfarin", doseMg: 5, frequencyPerDay: 1}}, {severity: "block", alerts: ["drug not in formulary"], crcl: 88}], + [{patient: {age: 50, weightKg: 70, sex: "male", scr: 1.0}, order: {doseMg: 5, frequencyPerDay: 1}}, {severity: "block", alerts: ["drug not in formulary"], crcl: 88}], + [{patient: {age: 50, weightKg: 70, scr: 1.0}, order: {drug: "Amoxicillin", doseMg: 500, frequencyPerDay: 3}}, {severity: "block", alerts: ["drug not in formulary"], crcl: 88}], + // Bad numbers fail the derive step: zero weight (null per-kg dose), zero creatinine, a string + // dose and a missing frequency. + [{patient: {age: 50, weightKg: 0, scr: 1.0}, order: {drug: "amoxicillin", doseMg: 500, frequencyPerDay: 3}}, "!error"], + [{patient: {age: 50, weightKg: 70, scr: 0}, order: {drug: "amoxicillin", doseMg: 500, frequencyPerDay: 3}}, "!error"], + [{patient: {age: 50, weightKg: 70, scr: 1.0}, order: {drug: "amoxicillin", doseMg: "500", frequencyPerDay: 3}}, "!error"], + [{patient: {age: 50, weightKg: 70, scr: 1.0}, order: {drug: "amoxicillin", doseMg: 500}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Specialist appointment eligibility: age at the appointment and days ahead derived from dates, +// per-specialty rules, a column-less table with first-hit `eligible` and collected `problems[]`, +// then a switch into a booking or a rejection. The referral check defaults missing counters so a +// missing referral is a problem rather than an erroring (and therefore silent) condition. +{ + name: "appointments: coverage, age range, referral, telehealth licensing and horizon", + graph: { + nodes: [ + {input: "booking"}, + {expression: "derive", passThrough: true, fields: { + "calc.ageYears": "d(appt.date).diff(d(patient.dob), 'year')", + "calc.daysAhead": "d(appt.date).diff(d(), 'day')", + "calc.coverageOk": "patient.plan.status == 'active' and not d(appt.date).isAfter(d(patient.plan.end))", + }}, + {table: "specialty", passThrough: true, inputs: ["appt.specialty"], outputs: ["rule.minAge", "rule.maxAge", "rule.referral", "rule.telehealth", "rule.maxDaysAhead"], rules: [ + ["'pediatrics'", "0", "17", "false", "true", "60"], + ["'geriatrics'", "65", "150", "true", "true", "90"], + ["'cardiology'", "18", "150", "true", "false", "120"], + ["'dermatology'", "0", "150", "true", "true", "180"], + ["'psychiatry'", "12", "150", "false", "true", "30"], + ["", "0", "150", "false", "false", "90"], + ]}, + {table: "checks", passThrough: true, inputs: [null], outputs: ["eligible", "problems[]"], rules: [ + ["not calc.coverageOk", "false", "'coverage inactive on appointment date'"], + ["calc.ageYears < rule.minAge or calc.ageYears > rule.maxAge", "false", "'age outside specialty range'"], + ["rule.referral and patient.plan.referralRequired == true and not (referral.specialty == appt.specialty and not d(referral.expires).isBefore(d(appt.date)) and (referral.visitsUsed ?? 0) < (referral.visitsAllowed ?? 0))", "false", "'valid referral required'"], + ["appt.mode == 'telehealth' and (not rule.telehealth or not (patient.state in (provider.licensedStates ?? [])))", "false", "'telehealth not allowed'"], + ["calc.daysAhead > rule.maxDaysAhead", "false", "'too far ahead'"], + ["calc.daysAhead < 0", "false", "'date in the past'"], + ["patient.isNew == true and provider.acceptsNew == false", "false", "'provider not accepting new patients'"], + ["", "true", ""], + ]}, + {switch: "route", when: ["eligible", ""]}, + {expression: "book", fields: {status: "'bookable'", visit: "rule.referral and patient.plan.referralRequired == true ? referral.visitsUsed + 1 : null"}}, + {expression: "reject", fields: {status: "'rejected'", problems: "problems"}}, + {output: "result"}, + ], + edges: [ + "booking -> derive -> specialty -> checks -> route", + "route:0 -> book -> result", + "route:1 -> reject -> result", + ], + }, + cases: [ + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, referral: {specialty: "cardiology", expires: "2025-06-30", visitsUsed: 1, visitsAllowed: 3}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA", "NV"], acceptsNew: true}}, {status: "bookable", visit: 2}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, referral: {specialty: "cardiology", expires: "2025-06-30", visitsUsed: 3, visitsAllowed: 3}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA", "NV"], acceptsNew: true}}, {status: "rejected", problems: ["valid referral required"]}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, referral: {specialty: "cardiology", expires: "2025-04-10", visitsUsed: 0, visitsAllowed: 3}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA", "NV"], acceptsNew: true}}, {status: "bookable", visit: 1}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, referral: {specialty: "cardiology", expires: "2025-04-09", visitsUsed: 0, visitsAllowed: 3}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA", "NV"], acceptsNew: true}}, {status: "rejected", problems: ["valid referral required"]}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, referral: {specialty: "dermatology", expires: "2025-06-30", visitsUsed: 0, visitsAllowed: 3}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA", "NV"], acceptsNew: true}}, {status: "rejected", problems: ["valid referral required"]}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA", "NV"], acceptsNew: true}}, {status: "rejected", problems: ["valid referral required"]}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: false}}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA", "NV"], acceptsNew: true}}, {status: "bookable"}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-04-10", referralRequired: false}}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA"]}}, {status: "bookable"}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "active", end: "2025-04-09", referralRequired: false}}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "in-person"}, provider: {licensedStates: ["CA"]}}, {status: "rejected", problems: ["coverage inactive on appointment date"]}], + [{patient: {dob: "1980-05-01", state: "CA", isNew: false, plan: {status: "terminated", end: "2025-12-31", referralRequired: false}}, appt: {specialty: "cardiology", date: "2025-04-10", mode: "telehealth"}, provider: {licensedStates: ["CA"]}}, {status: "rejected", problems: ["coverage inactive on appointment date", "telehealth not allowed"]}], + [{patient: {dob: "1990-01-15", state: "TX", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, referral: {specialty: "dermatology", expires: "2025-12-31", visitsUsed: 0, visitsAllowed: 1}, appt: {specialty: "dermatology", date: "2025-05-02", mode: "telehealth"}, provider: {licensedStates: ["CA", "NV"]}}, {status: "rejected", problems: ["telehealth not allowed"]}], + [{patient: {dob: "1990-01-15", state: "NV", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, referral: {specialty: "dermatology", expires: "2025-12-31", visitsUsed: 0, visitsAllowed: 1}, appt: {specialty: "dermatology", date: "2025-05-02", mode: "telehealth"}, provider: {licensedStates: ["CA", "NV"]}}, {status: "bookable", visit: 1}], + [{patient: {dob: "1990-01-15", state: "NV", isNew: false, plan: {status: "active", end: "2025-12-31", referralRequired: true}}, referral: {specialty: "dermatology", expires: "2025-12-31", visitsUsed: 0, visitsAllowed: 1}, appt: {specialty: "dermatology", date: "2025-05-02", mode: "telehealth"}, provider: {}}, {status: "rejected", problems: ["telehealth not allowed"]}], + // Age is measured on the appointment date: 18 the day before, 17 one day short of it. + [{patient: {dob: "2007-03-21", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "pediatrics", date: "2025-04-10", mode: "in-person"}, provider: {acceptsNew: true}}, {status: "rejected", problems: ["age outside specialty range"]}], + [{patient: {dob: "2007-04-11", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "pediatrics", date: "2025-04-10", mode: "in-person"}, provider: {acceptsNew: true}}, {status: "bookable"}], + [{patient: {dob: "1960-04-11", state: "CA", plan: {status: "active", end: "2025-12-31", referralRequired: false}}, appt: {specialty: "geriatrics", date: "2025-04-10", mode: "in-person"}}, {status: "rejected", problems: ["age outside specialty range"]}], + [{patient: {dob: "1960-04-10", state: "CA", plan: {status: "active", end: "2025-12-31", referralRequired: false}}, appt: {specialty: "geriatrics", date: "2025-04-10", mode: "in-person"}}, {status: "bookable"}], + // The horizon: days ahead truncate against the fixed evaluation time. + [{patient: {dob: "1990-01-15", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "2025-04-20", mode: "telehealth"}, provider: {licensedStates: ["CA"]}}, {status: "bookable"}], + [{patient: {dob: "1990-01-15", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "2025-04-21", mode: "telehealth"}, provider: {licensedStates: ["CA"]}}, {status: "rejected", problems: ["too far ahead"]}], + [{patient: {dob: "1990-01-15", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "2025-03-20", mode: "in-person"}}, {status: "bookable"}], + [{patient: {dob: "1990-01-15", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "2025-03-19", mode: "in-person"}}, {status: "rejected", problems: ["date in the past"]}], + [{patient: {dob: "1990-01-15", state: "CA", isNew: true, plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "2025-04-01", mode: "in-person"}, provider: {acceptsNew: false}}, {status: "rejected", problems: ["provider not accepting new patients"]}], + [{patient: {dob: "1990-01-15", state: "CA", isNew: true, plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "2025-04-01", mode: "in-person"}, provider: {}}, {status: "bookable"}], + [{patient: {dob: "1990-01-15", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "podiatry", date: "2025-06-18", mode: "telehealth"}, provider: {licensedStates: ["CA"]}}, {status: "rejected", problems: ["telehealth not allowed"]}], + [{patient: {dob: "2015-06-01", state: "TX", isNew: true, plan: {status: "lapsed", end: "2024-12-31", referralRequired: true}}, appt: {specialty: "cardiology", date: "2026-01-05", mode: "telehealth"}, provider: {licensedStates: ["CA"], acceptsNew: false}}, {status: "rejected", problems: ["coverage inactive on appointment date", "age outside specialty range", "valid referral required", "telehealth not allowed", "too far ahead", "provider not accepting new patients"]}], + // Without a birth date or with an unparsable appointment date the diffs are null, every + // comparison against them fails, and the age and horizon rules are silently skipped. + [{patient: {state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "2025-04-01", mode: "in-person"}}, {status: "bookable"}], + [{patient: {dob: "1990-01-15", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "next week", mode: "in-person"}}, {status: "bookable"}], + [{patient: {dob: "2015-01-15", state: "CA", plan: {status: "active", end: "2025-12-31"}}, appt: {specialty: "psychiatry", date: "2026-03-01", mode: "in-person"}}, {status: "rejected", problems: ["coverage inactive on appointment date", "age outside specialty range", "too far ahead"]}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Interaction screening: a loop-mode table classifies each medication, the classification joins +// the request in a function node that checks every distinct pair against class rules and QT +// risk, and a switch holds, counsels or dispenses. +{ + name: "interactions: per-drug class loop, pairwise function check and dispensing action", + graph: { + nodes: [ + {input: "prescription"}, + {table: "classify", executionMode: "loop", inputField: "medications", outputPath: "classified", inputs: ["name"], outputs: ["name", "class", "qt"], rules: [ + ["'warfarin', 'apixaban'", "name", "'anticoagulant'", "false"], + ["'aspirin', 'ibuprofen', 'naproxen'", "name", "'nsaid'", "false"], + ["'sertraline', 'fluoxetine'", "name", "'ssri'", "false"], + ["'citalopram'", "name", "'ssri'", "true"], + ["'tramadol'", "name", "'opioid'", "false"], + ["'azithromycin', 'ondansetron'", "name", "'other'", "true"], + ["", "name", "'unclassified'", "false"], + ]}, + {function: "pairs", source: """ +export const handler = async (input) => { + const meds = input.classified ?? []; + const rules = [ + ['anticoagulant', 'anticoagulant', 'major', 'duplicate anticoagulation'], + ['anticoagulant', 'nsaid', 'major', 'bleeding'], + ['ssri', 'opioid', 'major', 'serotonin syndrome'], + ['ssri', 'nsaid', 'moderate', 'bleeding'], + ['nsaid', 'nsaid', 'moderate', 'duplicate nsaid'], + ]; + const interactions = []; + for (let i = 0; i < meds.length; i++) { + for (let j = i + 1; j < meds.length; j++) { + const a = meds[i]; + const b = meds[j]; + if (a.name === b.name) { + continue; + } + const rule = rules.find(([x, y]) => (a.class === x && b.class === y) || (a.class === y && b.class === x)); + if (rule) { + interactions.push({ pair: [a.name, b.name], severity: rule[2], effect: rule[3] }); + } + if (a.qt && b.qt) { + interactions.push({ pair: [a.name, b.name], severity: 'major', effect: 'qt prolongation' }); + } + } + } + return { interactions, medCount: meds.length, override: input.prescriberOverride === true }; +}; +"""}, + {switch: "action", when: [ + "some(interactions, #.severity == 'major') and not override", + "len(interactions) > 0", + "", + ]}, + {expression: "hold", fields: {action: "'hold'", notify: "'prescriber'", major: "map(filter(interactions, #.severity == 'major'), #.effect)"}}, + {expression: "counsel", fields: {action: "'counsel'", notes: "map(interactions, #.effect + ': ' + #.pair[0] + '+' + #.pair[1])"}}, + {expression: "dispense", fields: {action: "'dispense'", count: "medCount"}}, + {output: "pharmacy"}, + ], + edges: [ + "prescription -> classify -> pairs", + "prescription -> pairs -> action", + "action:0 -> hold -> pharmacy", + "action:1 -> counsel -> pharmacy", + "action:2 -> dispense -> pharmacy", + ], + }, + cases: [ + [{medications: [{name: "warfarin"}, {name: "ibuprofen"}]}, {action: "hold", notify: "prescriber", major: ["bleeding"]}], + [{medications: [{name: "sertraline"}, {name: "ibuprofen"}]}, {action: "counsel", notes: ["bleeding: sertraline+ibuprofen"]}], + [{medications: [{name: "sertraline"}, {name: "tramadol"}, {name: "naproxen"}]}, {action: "hold", notify: "prescriber", major: ["serotonin syndrome"]}], + [{medications: [{name: "citalopram"}, {name: "ondansetron"}]}, {action: "hold", notify: "prescriber", major: ["qt prolongation"]}], + [{medications: [{name: "azithromycin"}, {name: "ondansetron"}, {name: "citalopram"}]}, {action: "hold", notify: "prescriber", major: ["qt prolongation", "qt prolongation", "qt prolongation"]}], + [{medications: [{name: "warfarin"}, {name: "apixaban"}]}, {action: "hold", notify: "prescriber", major: ["duplicate anticoagulation"]}], + [{medications: [{name: "aspirin"}, {name: "ibuprofen"}, {name: "metformin"}]}, {action: "counsel", notes: ["duplicate nsaid: aspirin+ibuprofen"]}], + [{medications: [{name: "fluoxetine"}, {name: "naproxen"}, {name: "aspirin"}]}, {action: "counsel", notes: ["bleeding: fluoxetine+naproxen", "bleeding: fluoxetine+aspirin", "duplicate nsaid: naproxen+aspirin"]}], + [{medications: [{name: "warfarin"}, {name: "ibuprofen"}], prescriberOverride: true}, {action: "counsel", notes: ["bleeding: warfarin+ibuprofen"]}], + [{medications: [{name: "warfarin"}, {name: "ibuprofen"}], prescriberOverride: "yes"}, {action: "hold", notify: "prescriber", major: ["bleeding"]}], + // The same drug listed twice is not a pair; unknown or differently cased names are + // unclassified; an item without a name classifies with a null name. + [{medications: [{name: "warfarin"}, {name: "warfarin"}]}, {action: "dispense", count: 2}], + [{medications: [{name: "metformin"}, {name: "lisinopril"}]}, {action: "dispense", count: 2}], + [{medications: [{name: "Warfarin"}, {name: "ibuprofen"}]}, {action: "dispense", count: 2}], + [{medications: [{dose: 5}, {name: "ibuprofen"}]}, {action: "dispense", count: 2}], + [{medications: [{name: "tramadol"}]}, {action: "dispense", count: 1}], + [{medications: []}, {action: "dispense", count: 0}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Lab results: an expression reshapes the results into rows carrying the patient's sex, a +// sub-decision runs per row in loop mode (reference range by analyte and sex, then a flag table +// whose cells compare against the looked-up limits), a summary joins them and a switch decides +// the notification. Unknown analytes flag as unknown; values that are not numbers fail every +// comparison cell and fall to `normal`, which the decision itself has to guard against. +{ + name: "lab results: reference ranges per analyte through a looped sub-decision", + decisions: { + interpret: { + nodes: [ + {table: "ref", passThrough: true, inputs: ["analyte", "sex"], outputs: ["low", "high", "critLow", "critHigh", "unit"], rules: [ + ["'potassium'", "", "3.5", "5.1", "2.5", "6.5", "'mmol/L'"], + ["'sodium'", "", "135", "145", "120", "160", "'mmol/L'"], + ["'hemoglobin'", "'female'", "12", "15.5", "7", "20", "'g/dL'"], + ["'hemoglobin'", "", "13.5", "17.5", "7", "20", "'g/dL'"], + ["'glucose'", "", "70", "99", "40", "500", "'mg/dL'"], + ]}, + {table: "flag", passThrough: true, inputs: ["low", "value"], outputs: ["flag"], rules: [ + ["null", "", "'unknown'"], + ["", "< critLow", "'critical-low'"], + ["", "> critHigh", "'critical-high'"], + ["", "< low", "'low'"], + ["", "> high", "'high'"], + ["", "", "'normal'"], + ]}, + {expression: "out", fields: {analyte: "analyte", value: "value", flag: "flag", unit: "unit"}}, + ], + }, + }, + graph: { + nodes: [ + {input: "labs"}, + {expression: "rows", fields: {rows: "map(results ?? [], {analyte: lower(#.analyte), value: #.value, sex: patient.sex})"}}, + {decision: "interpret", key: "interpret", executionMode: "loop", inputField: "rows", outputPath: "interpreted"}, + {expression: "summary", fields: { + critical: "map(filter(interpreted, #.flag in ['critical-low', 'critical-high']), #.analyte)", + abnormal: "count(interpreted, #.flag in ['low', 'high', 'critical-low', 'critical-high'])", + unknown: "map(filter(interpreted, #.flag == 'unknown'), #.analyte)", + }}, + {switch: "notify", when: ["len(critical) > 0", "abnormal > 0", ""]}, + {expression: "page", passThrough: true, fields: {action: "'page clinician'"}}, + {expression: "inbox", passThrough: true, fields: {action: "'inbox'"}}, + {expression: "release", passThrough: true, fields: {action: "'release to patient'"}}, + {output: "report"}, + ], + edges: [ + "labs -> rows -> interpret -> summary -> notify", + "notify:0 -> page -> report", + "notify:1 -> inbox -> report", + "notify:2 -> release -> report", + ], + }, + cases: [ + [{patient: {sex: "male"}, results: [{analyte: "potassium", value: 4.0}, {analyte: "sodium", value: 140}]}, {critical: [], abnormal: 0, unknown: [], action: "release to patient"}], + [{patient: {sex: "male"}, results: [{analyte: "potassium", value: 5.2}]}, {critical: [], abnormal: 1, unknown: [], action: "inbox"}], + [{patient: {sex: "male"}, results: [{analyte: "potassium", value: 6.6}]}, {critical: ["potassium"], abnormal: 1, unknown: [], action: "page clinician"}], + [{patient: {sex: "male"}, results: [{analyte: "potassium", value: 6.5}]}, {critical: [], abnormal: 1, unknown: [], action: "inbox"}], + [{patient: {sex: "male"}, results: [{analyte: "potassium", value: 2.5}]}, {critical: [], abnormal: 1, unknown: [], action: "inbox"}], + [{patient: {sex: "male"}, results: [{analyte: "potassium", value: 2.49}]}, {critical: ["potassium"], abnormal: 1, unknown: [], action: "page clinician"}], + [{patient: {sex: "male"}, results: [{analyte: "potassium", value: 3.5}, {analyte: "potassium", value: 5.1}]}, {critical: [], abnormal: 0, unknown: [], action: "release to patient"}], + [{patient: {sex: "female"}, results: [{analyte: "hemoglobin", value: 12.5}]}, {critical: [], abnormal: 0, unknown: [], action: "release to patient"}], + [{patient: {sex: "male"}, results: [{analyte: "hemoglobin", value: 12.5}]}, {critical: [], abnormal: 1, unknown: [], action: "inbox"}], + [{patient: {}, results: [{analyte: "hemoglobin", value: 12.5}]}, {critical: [], abnormal: 1, unknown: [], action: "inbox"}], + [{patient: {sex: "male"}, results: [{analyte: "Glucose", value: 650}]}, {critical: ["glucose"], abnormal: 1, unknown: [], action: "page clinician"}], + [{patient: {sex: "female"}, results: [{analyte: "SODIUM", value: 118}, {analyte: "potassium", value: 6.8}, {analyte: "glucose", value: 65}]}, {critical: ["sodium", "potassium"], abnormal: 3, unknown: [], action: "page clinician"}], + [{patient: {sex: "male"}, results: [{analyte: "troponin", value: 0.04}]}, {critical: [], abnormal: 0, unknown: ["troponin"], action: "release to patient"}], + [{patient: {sex: "male"}, results: [{analyte: "troponin", value: 0.04}, {analyte: "glucose", value: 120}]}, {critical: [], abnormal: 1, unknown: ["troponin"], action: "inbox"}], + [{patient: {sex: "male"}, results: []}, {critical: [], abnormal: 0, unknown: [], action: "release to patient"}], + [{patient: {sex: "male"}}, {critical: [], abnormal: 0, unknown: [], action: "release to patient"}], + // A string or missing value fails every comparison cell and lands on `normal`. + [{patient: {sex: "male"}, results: [{analyte: "potassium", value: "7.9"}]}, {critical: [], abnormal: 0, unknown: [], action: "release to patient"}], + [{patient: {sex: "male"}, results: [{analyte: "potassium"}]}, {critical: [], abnormal: 0, unknown: [], action: "release to patient"}], + // A result without an analyte name fails `lower` in the reshaping expression. + [{patient: {sex: "male"}, results: [{value: 4.0}]}, "!error"], + [{patient: {sex: "male"}, results: {analyte: "potassium", value: 4.0}}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/61-realistic-telco-energy.json5 b/core/engine/tests/spec/graph/61-realistic-telco-energy.json5 new file mode 100644 index 00000000..5e46d5c0 --- /dev/null +++ b/core/engine/tests/spec/graph/61-realistic-telco-energy.json5 @@ -0,0 +1,419 @@ +// Realistic telco and energy decisions: plan recommendation by projecting each catalog plan in a +// loop expression, tiered energy billing with a net-metering switch and a collect table whose +// cells compute the kWh per tier, outage prioritisation with collected points and a collect +// switch fanning out notifications, tariff selection through a sub-decision per tariff that +// switches on the tariff kind, data allowance with rollover and dated add-ons (evaluation time is +// fixed at Thursday 2025-03-20T10:15:30Z), and roaming charges from a loop zone table. Each suite +// is one decision exercised across main paths, boundaries, missing data and bad types. + +// --------------------------------------------------------------------------------------------- +// Plan recommendation: a pass-through expression supplies the catalog, a loop expression costs +// every plan against the usage read through `$nodes`, the cheapest plan wins (catalog order on a +// tie), lines get a multi-line discount and a budget gate splits the answer. +{ + name: "plan recommendation: projected cost per plan, multi-line discount and budget", + graph: { + nodes: [ + {input: "customer"}, + {expression: "catalog", passThrough: true, fields: { + plans: "[{id: 'lite', price: 15, dataGb: 5, minutes: 300, overagePerGb: 10}, {id: 'plus', price: 30, dataGb: 20, minutes: 1000, overagePerGb: 8}, {id: 'max', price: 45, dataGb: 100, minutes: 99999, overagePerGb: 5}]", + }}, + {expression: "cost", executionMode: "loop", inputField: "plans", outputPath: "costed", fields: { + id: "id", + dataOver: "max([0, ceil($nodes.customer.usage.dataGb - dataGb)])", + minuteOver: "max([0, $nodes.customer.usage.minutes - minutes])", + cost: "price + $.dataOver * overagePerGb + $.minuteOver * 0.05", + }}, + {expression: "pick", passThrough: true, fields: { + cheapest: "min(map(costed, #.cost))", + best: "filter(costed, #.cost == $.cheapest)[0]", + lineDiscount: "(lines ?? 1) >= 3 ? 0.1 : 0", + monthly: "round($.best.cost * (lines ?? 1) * (1 - $.lineDiscount), 2)", + }}, + {switch: "budgetGate", when: ["budget != null and monthly > budget", ""]}, + {expression: "overBudget", fields: {recommendation: "best.id", monthly: "monthly", status: "'over budget'", shortfall: "monthly - budget"}}, + {table: "verdict", inputs: ["best.dataOver + best.minuteOver"], outputs: ["recommendation", "monthly", "status"], rules: [ + ["0", "best.id", "monthly", "'fits'"], + ["", "best.id", "monthly", "'fits with overage'"], + ]}, + {output: "offer"}, + ], + edges: [ + "customer -> catalog -> cost -> pick", + "catalog -> pick -> budgetGate", + "budgetGate:0 -> overBudget -> offer", + "budgetGate:1 -> verdict -> offer", + ], + }, + cases: [ + [{usage: {dataGb: 3, minutes: 200}, budget: 20}, {recommendation: "lite", monthly: 15, status: "fits"}], + [{usage: {dataGb: 6, minutes: 200}, budget: 40}, {recommendation: "lite", monthly: 25, status: "fits with overage"}], + [{usage: {dataGb: 6.2, minutes: 200}, budget: 40}, {recommendation: "plus", monthly: 30, status: "fits"}], + [{usage: {dataGb: 5, minutes: 300}, budget: 40}, {recommendation: "lite", monthly: 15, status: "fits"}], + [{usage: {dataGb: 5.01, minutes: 300}, budget: 40}, {recommendation: "lite", monthly: 25, status: "fits with overage"}], + [{usage: {dataGb: 20, minutes: 1200}, budget: 60}, {recommendation: "plus", monthly: 40, status: "fits with overage"}], + [{usage: {dataGb: 50, minutes: 500}, budget: 60}, {recommendation: "max", monthly: 45, status: "fits"}], + // lite and plus both cost 30: the first plan in catalog order wins. + [{usage: {dataGb: 4, minutes: 600}, budget: 60}, {recommendation: "lite", monthly: 30, status: "fits with overage"}], + [{usage: {dataGb: 0, minutes: 0}, budget: 15}, {recommendation: "lite", monthly: 15, status: "fits"}], + [{usage: {dataGb: 3, minutes: 200}, lines: 3, budget: 50}, {recommendation: "lite", monthly: 40.5, status: "fits"}], + [{usage: {dataGb: 3, minutes: 200}, lines: 2, budget: 50}, {recommendation: "lite", monthly: 30, status: "fits"}], + [{usage: {dataGb: 50, minutes: 500}, lines: 4, budget: 150}, {recommendation: "max", monthly: 162, status: "over budget", shortfall: 12}], + [{usage: {dataGb: 3, minutes: 200}, budget: 10}, {recommendation: "lite", monthly: 15, status: "over budget", shortfall: 5}], + [{usage: {dataGb: 3, minutes: 200}}, {recommendation: "lite", monthly: 15, status: "fits"}], + [{usage: {dataGb: 1000, minutes: 100}, budget: 100}, {recommendation: "max", monthly: 4545, status: "over budget", shortfall: 4445}], + // The loop reads the usage through `$nodes`; missing or mistyped usage fails the loop. + [{usage: {minutes: 200}, budget: 20}, "!error"], + [{usage: {dataGb: 3, minutes: "200"}, budget: 20}, "!error"], + [{budget: 20}, "!error"], + // A string budget makes the gate condition error, so it is false and the verdict decides. + [{usage: {dataGb: 3, minutes: 200}, budget: "10"}, {recommendation: "lite", monthly: 15, status: "fits"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Energy bill: net consumption after solar export, a credit branch when the customer exported +// more than imported, otherwise a collect table writes one row per tier crossed (tier sizes scale +// with the billing days), class and region tables add the fixed charge, discount and tax. +{ + name: "energy bill: net metering, tiered kWh by billing days, discount and tax", + graph: { + nodes: [ + {input: "meter"}, + {expression: "net", passThrough: true, fields: { + "bill.netKwh": "usage.importKwh - (usage.exportKwh ?? 0)", + "bill.days": "days ?? 30", + }}, + {switch: "netGate", when: ["bill.netKwh < 0", ""]}, + {expression: "credit", fields: {status: "'credit'", creditKwh: "abs(bill.netKwh)", creditAmount: "round(abs(bill.netKwh) * 0.08, 2)"}}, + {table: "tiers", hit: "collect", outputPath: "tiers", passThrough: true, inputs: ["bill.netKwh"], outputs: ["tier", "kwh", "rate"], rules: [ + ["> 0", "1", "min([bill.netKwh, bill.days * 10])", "0.12"], + ["> bill.days * 10", "2", "min([bill.netKwh, bill.days * 20]) - bill.days * 10", "0.18"], + ["> bill.days * 20", "3", "bill.netKwh - bill.days * 20", "0.25"], + ]}, + {table: "rateClass", passThrough: true, inputs: ["account.class", "account.lowIncome"], outputs: ["adj.fixed", "adj.discount"], rules: [ + ["'residential'", "true", "5", "0.3"], + ["'residential'", "", "12", "0"], + ["'business'", "", "25", "0"], + ]}, + {table: "tax", passThrough: true, inputs: ["account.region"], outputs: ["adj.taxRate"], rules: [ + ["'north'", "0.05"], + ["'south'", "0.07"], + ["", "0.06"], + ]}, + {expression: "total", fields: { + status: "'charge'", + tiersUsed: "len(tiers)", + energy: "round(sum(map(tiers, #.kwh * #.rate)), 2)", + discount: "round($.energy * adj.discount, 2)", + subtotal: "$.energy - $.discount + adj.fixed", + tax: "round($.subtotal * adj.taxRate, 2)", + total: "$.subtotal + $.tax", + }}, + {output: "invoice"}, + ], + edges: [ + "meter -> net -> netGate", + "netGate:0 -> credit -> invoice", + "netGate:1 -> tiers -> rateClass -> tax -> total -> invoice", + ], + }, + cases: [ + [{account: {class: "residential", region: "north"}, usage: {importKwh: 250}}, {status: "charge", tiersUsed: 1, energy: 30, discount: 0, subtotal: 42, tax: 2.1, total: 44.1}], + [{account: {class: "residential", region: "north"}, usage: {importKwh: 450}}, {status: "charge", tiersUsed: 2, energy: 63, discount: 0, subtotal: 75, tax: 3.75, total: 78.75}], + [{account: {class: "residential", region: "north"}, usage: {importKwh: 800}}, {status: "charge", tiersUsed: 3, energy: 140, discount: 0, subtotal: 152, tax: 7.6, total: 159.6}], + [{account: {class: "residential", region: "north"}, usage: {importKwh: 300}}, {status: "charge", tiersUsed: 1, energy: 36, discount: 0, subtotal: 48, tax: 2.4, total: 50.4}], + [{account: {class: "residential", region: "north"}, usage: {importKwh: 300.5}}, {status: "charge", tiersUsed: 2, energy: 36.09, discount: 0, subtotal: 48.09, tax: 2.4, total: 50.49}], + [{account: {class: "residential", region: "north"}, usage: {importKwh: 600}}, {status: "charge", tiersUsed: 2, energy: 90, discount: 0, subtotal: 102, tax: 5.1, total: 107.1}], + [{account: {class: "residential", region: "north", lowIncome: true}, usage: {importKwh: 450}}, {status: "charge", tiersUsed: 2, energy: 63, discount: 18.9, subtotal: 49.1, tax: 2.46, total: 51.56}], + [{account: {class: "residential", region: "north", lowIncome: false}, usage: {importKwh: 450}}, {status: "charge", tiersUsed: 2, energy: 63, discount: 0, subtotal: 75, tax: 3.75, total: 78.75}], + [{account: {class: "business", region: "south"}, usage: {importKwh: 800}, days: 31}, {status: "charge", tiersUsed: 3, energy: 138, discount: 0, subtotal: 163, tax: 11.41, total: 174.41}], + [{account: {class: "residential", region: "east"}, usage: {importKwh: 250}}, {status: "charge", tiersUsed: 1, energy: 30, discount: 0, subtotal: 42, tax: 2.52, total: 44.52}], + [{account: {class: "residential"}, usage: {importKwh: 250}}, {status: "charge", tiersUsed: 1, energy: 30, discount: 0, subtotal: 42, tax: 2.52, total: 44.52}], + // Solar export nets against import; exporting more turns the bill into a credit. + [{account: {class: "residential", region: "north"}, usage: {importKwh: 400, exportKwh: 150}}, {status: "charge", tiersUsed: 1, energy: 30, discount: 0, subtotal: 42, tax: 2.1, total: 44.1}], + [{account: {class: "residential", region: "north"}, usage: {importKwh: 100, exportKwh: 250}}, {status: "credit", creditKwh: 150, creditAmount: 12}], + [{account: {class: "residential", region: "north"}, usage: {importKwh: 0, exportKwh: 12.5}}, {status: "credit", creditKwh: 12.5, creditAmount: 1}], + // Zero net consumption crosses no tier: the collect table writes an empty list. + [{account: {class: "residential", region: "north"}, usage: {importKwh: 200, exportKwh: 200}}, {status: "charge", tiersUsed: 0, energy: 0, discount: 0, subtotal: 12, tax: 0.6, total: 12.6}], + // Zero billing days collapse the first two tiers to zero kWh; every kWh lands in tier 3. + [{account: {class: "residential", region: "north"}, usage: {importKwh: 50}, days: 0}, {status: "charge", tiersUsed: 3, energy: 12.5, discount: 0, subtotal: 24.5, tax: 1.23, total: 25.73}], + // No customer class means no fixed charge or discount and the total fails; a missing or + // string import fails the net step. + [{account: {region: "north"}, usage: {importKwh: 250}}, "!error"], + [{account: {class: "residential", region: "north"}, usage: {exportKwh: 10}}, "!error"], + [{account: {class: "residential", region: "north"}, usage: {importKwh: "250"}}, "!error"], + [{account: {class: "residential", region: "north"}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Outage priority: column-less rules collect `points[]` and `reasons[]` (the catch-all adds a +// zero point and no reason), the score bands into a priority with a restoration target, and a +// collect switch fans out to every notification that applies; the default branch carries the +// priority and all branches meet at a summary. Conditions that error count as not matching, so +// bad or missing fields drop their rule silently. +{ + name: "outage priority: collected points, priority band and fan-out notifications", + graph: { + nodes: [ + {input: "outage"}, + {table: "score", passThrough: true, inputs: [null], outputs: ["points[]", "reasons[]"], rules: [ + ["outage.customers >= 10000", "40", "'large outage'"], + ["outage.customers >= 1000 and outage.customers < 10000", "20", "'medium outage'"], + ["'hospital' in outage.critical", "50", "'hospital affected'"], + ["'water' in outage.critical or 'telecom' in outage.critical", "25", "'critical infrastructure'"], + ["outage.medicalBaseline > 0", "15 + min([outage.medicalBaseline, 10])", "'medical baseline customers'"], + ["outage.weather in ['heat', 'freeze']", "20", "'extreme temperature'"], + ["outage.durationH > 4", "10", "'extended duration'"], + ["", "0", ""], + ]}, + {expression: "total", passThrough: true, fields: {score: "sum(points)"}}, + {table: "priority", passThrough: true, inputs: ["score"], outputs: ["priority", "targetH"], rules: [ + [">= 80", "'P1'", "2"], + ["[40..80)", "'P2'", "4"], + ["[15..40)", "'P3'", "8"], + ["", "'P4'", "24"], + ]}, + {switch: "notify", hit: "collect", when: [ + "outage.customers >= 5000", + "'hospital' in outage.critical", + "outage.customers >= 20000 or priority == 'P1'", + "outage.medicalBaseline > 0", + "", + ]}, + {expression: "regulator", fields: {"notices.regulator": "true"}}, + {expression: "hospital", fields: {"notices.hospital": "true"}}, + {expression: "press", fields: {"notices.press": "true"}}, + {expression: "medical", fields: {"notices.medicalCalls": "outage.medicalBaseline"}}, + {expression: "base", fields: {priority: "priority", targetH: "targetH", score: "score", reasons: "reasons"}}, + {expression: "summary", fields: {priority: "priority", targetH: "targetH", score: "score", reasons: "reasons", notices: "notices ?? {}"}}, + {output: "dispatch"}, + ], + edges: [ + "outage -> score -> total -> priority -> notify", + "notify:0 -> regulator -> summary", + "notify:1 -> hospital -> summary", + "notify:2 -> press -> summary", + "notify:3 -> medical -> summary", + "notify:4 -> base -> summary", + "summary -> dispatch", + ], + }, + cases: [ + [{outage: {customers: 500, durationH: 2, critical: [], medicalBaseline: 0, weather: "clear"}}, {priority: "P4", targetH: 24, score: 0, reasons: [], notices: {}}], + [{outage: {customers: 12000, durationH: 6, critical: ["hospital"], medicalBaseline: 3, weather: "heat"}}, {priority: "P1", targetH: 2, score: 138, reasons: ["large outage", "hospital affected", "medical baseline customers", "extreme temperature", "extended duration"], notices: {regulator: true, hospital: true, press: true, medicalCalls: 3}}], + [{outage: {customers: 1000, durationH: 4, critical: ["water"], medicalBaseline: 0, weather: "clear"}}, {priority: "P2", targetH: 4, score: 45, reasons: ["medium outage", "critical infrastructure"], notices: {}}], + [{outage: {customers: 9999, durationH: 1, critical: [], medicalBaseline: 20, weather: "freeze"}}, {priority: "P2", targetH: 4, score: 65, reasons: ["medium outage", "medical baseline customers", "extreme temperature"], notices: {regulator: true, medicalCalls: 20}}], + [{outage: {customers: 25000, durationH: 1, critical: [], medicalBaseline: 0, weather: "clear"}}, {priority: "P2", targetH: 4, score: 40, reasons: ["large outage"], notices: {regulator: true, press: true}}], + [{outage: {customers: 999, durationH: 5, critical: [], medicalBaseline: 0, weather: "rain"}}, {priority: "P4", targetH: 24, score: 10, reasons: ["extended duration"], notices: {}}], + [{outage: {customers: 999, durationH: 1, critical: [], medicalBaseline: 1, weather: "rain"}}, {priority: "P3", targetH: 8, score: 16, reasons: ["medical baseline customers"], notices: {medicalCalls: 1}}], + [{outage: {customers: 2000, durationH: 5, critical: ["hospital"], medicalBaseline: 0, weather: "clear"}}, {priority: "P1", targetH: 2, score: 80, reasons: ["medium outage", "hospital affected", "extended duration"], notices: {hospital: true, press: true}}], + [{outage: {customers: 4999, durationH: 4, critical: ["telecom", "school"], medicalBaseline: 0, weather: "clear"}}, {priority: "P2", targetH: 4, score: 45, reasons: ["medium outage", "critical infrastructure"], notices: {}}], + [{outage: {customers: 5000, durationH: 0.5, critical: [], medicalBaseline: 0, weather: "clear"}}, {priority: "P3", targetH: 8, score: 20, reasons: ["medium outage"], notices: {regulator: true}}], + [{outage: {customers: 10, durationH: 1, critical: [], medicalBaseline: 0, weather: "heat"}}, {priority: "P3", targetH: 8, score: 20, reasons: ["extreme temperature"], notices: {}}], + // Missing critical facilities: both `in` rules and the hospital branch error and are skipped. + [{outage: {customers: 100, durationH: 1, medicalBaseline: 0, weather: "clear"}}, {priority: "P4", targetH: 24, score: 0, reasons: [], notices: {}}], + // Missing customer count: only the size rules and the size-based notices drop out. + [{outage: {durationH: 1, critical: ["hospital"]}}, {priority: "P2", targetH: 4, score: 50, reasons: ["hospital affected"], notices: {hospital: true}}], + // Strings where numbers are expected fail their rules instead of erroring the decision. + [{outage: {customers: "12000", durationH: "6", critical: [], medicalBaseline: "3", weather: "heat"}}, {priority: "P3", targetH: 8, score: 20, reasons: ["extreme temperature"], notices: {}}], + [{}, {priority: "P4", targetH: 24, score: 0, reasons: [], notices: {}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Tariff selection: an expression pairs each catalog tariff with the usage, a sub-decision runs +// per pair in loop mode (a switch on the tariff kind into flat, tiered and time-of-use formulas, +// joined into the annual cost with the standing charge), then the cheapest priceable tariff is +// compared with the current one. Unknown tariff kinds price to nothing and are left out. +{ + name: "tariff selection: per-tariff sub-decision with a kind switch, saving and advice", + decisions: { + annualCost: { + nodes: [ + {input: "quote"}, + {switch: "kind", when: ["tariff.kind == 'flat'", "tariff.kind == 'tiered'", "tariff.kind == 'tou'", ""]}, + {expression: "flat", passThrough: true, fields: {energy: "usage.annualKwh * tariff.rate"}}, + {expression: "tiered", passThrough: true, fields: {energy: "min([usage.annualKwh, tariff.threshold]) * tariff.rate1 + max([0, usage.annualKwh - tariff.threshold]) * tariff.rate2"}}, + {expression: "tou", passThrough: true, fields: {energy: "usage.annualKwh * usage.peakShare * tariff.peak + usage.annualKwh * (1 - usage.peakShare) * tariff.offPeak"}}, + {expression: "unsupported", passThrough: true, fields: {note: "'unsupported kind ' + tariff.kind"}}, + {expression: "cost", fields: {id: "tariff.id", annual: "energy == null ? null : round(energy + tariff.standing * 365, 2)"}}, + {output: "priced"}, + ], + edges: [ + "quote -> kind", + "kind:0 -> flat -> cost", + "kind:1 -> tiered -> cost", + "kind:2 -> tou -> cost", + "kind:3 -> unsupported -> cost", + "cost -> priced", + ], + }, + }, + graph: { + nodes: [ + {input: "household"}, + {expression: "pairs", fields: { + rows: "map([{id: 'flat-std', kind: 'flat', rate: 0.15, standing: 0.4}, {id: 'tiered-eco', kind: 'tiered', threshold: 3000, rate1: 0.12, rate2: 0.2, standing: 0.3}, {id: 'tou-smart', kind: 'tou', peak: 0.25, offPeak: 0.09, standing: 0.45}, {id: 'legacy-x', kind: 'block', standing: 0.5}], {tariff: #, usage: usage})", + }}, + {decision: "price", key: "annualCost", executionMode: "loop", inputField: "rows", outputPath: "quotes"}, + {expression: "pick", passThrough: true, fields: { + valid: "filter(quotes, #.annual != null)", + cheapest: "min(map($.valid, #.annual))", + best: "filter($.valid, #.annual == $.cheapest)[0]", + current: "filter($.valid, #.id == currentTariff)[0]", + saving: "$.current == null ? null : round($.current.annual - $.best.annual, 2)", + }}, + {table: "advice", passThrough: true, inputs: ["saving"], outputs: ["advice"], rules: [ + ["null", "'no current tariff on record'"], + ["> 100", "'switch'"], + ["> 0", "'consider switching'"], + ["", "'stay'"], + ]}, + {expression: "answer", fields: {best: "best.id", bestAnnual: "best.annual", saving: "saving", advice: "advice", priced: "len(valid)"}}, + {output: "recommendation"}, + ], + edges: [ + "household -> pairs -> price -> pick", + "household -> pick -> advice -> answer -> recommendation", + ], + }, + cases: [ + [{usage: {annualKwh: 3000, peakShare: 0.4}, currentTariff: "flat-std"}, {best: "tiered-eco", bestAnnual: 469.5, saving: 126.5, advice: "switch", priced: 3}], + [{usage: {annualKwh: 3000, peakShare: 0.1}, currentTariff: "tiered-eco"}, {best: "tiered-eco", bestAnnual: 469.5, saving: 0, advice: "stay", priced: 3}], + [{usage: {annualKwh: 6000, peakShare: 0.1}, currentTariff: "flat-std"}, {best: "tou-smart", bestAnnual: 800.25, saving: 245.75, advice: "switch", priced: 3}], + [{usage: {annualKwh: 6000, peakShare: 0.5}, currentTariff: "tiered-eco"}, {best: "flat-std", bestAnnual: 1046, saving: 23.5, advice: "consider switching", priced: 3}], + [{usage: {annualKwh: 3000, peakShare: 0.4}, currentTariff: "tou-smart"}, {best: "tiered-eco", bestAnnual: 469.5, saving: 156.75, advice: "switch", priced: 3}], + [{usage: {annualKwh: 1500, peakShare: 0.4}, currentTariff: "flat-std"}, {best: "tiered-eco", bestAnnual: 289.5, saving: 81.5, advice: "consider switching", priced: 3}], + [{usage: {annualKwh: 1500, peakShare: 0}, currentTariff: "tou-smart"}, {best: "tiered-eco", bestAnnual: 289.5, saving: 9.75, advice: "consider switching", priced: 3}], + [{usage: {annualKwh: 10000, peakShare: 0.2}, currentTariff: "tiered-eco"}, {best: "tou-smart", bestAnnual: 1384.25, saving: 485.25, advice: "switch", priced: 3}], + [{usage: {annualKwh: 4000, peakShare: 1}, currentTariff: "tou-smart"}, {best: "tiered-eco", bestAnnual: 669.5, saving: 494.75, advice: "switch", priced: 3}], + // No usage at all: only the standing charges remain. + [{usage: {annualKwh: 0, peakShare: 0.5}, currentTariff: "flat-std"}, {best: "tiered-eco", bestAnnual: 109.5, saving: 36.5, advice: "consider switching", priced: 3}], + // Without a current tariff, or with one that cannot be priced, the saving is null (and + // dropped from the answer). + [{usage: {annualKwh: 3000, peakShare: 0.4}}, {best: "tiered-eco", bestAnnual: 469.5, advice: "no current tariff on record", priced: 3}], + [{usage: {annualKwh: 3000, peakShare: 0.4}, currentTariff: "legacy-x"}, {best: "tiered-eco", bestAnnual: 469.5, advice: "no current tariff on record", priced: 3}], + [{usage: {annualKwh: 3000, peakShare: 0.4}, currentTariff: "FLAT-STD"}, {best: "tiered-eco", bestAnnual: 469.5, advice: "no current tariff on record", priced: 3}], + // The time-of-use formula needs the peak share; any bad usage value fails the sub-decision. + [{usage: {annualKwh: 3000}, currentTariff: "flat-std"}, "!error"], + [{usage: {annualKwh: "3000", peakShare: 0.4}, currentTariff: "flat-std"}, "!error"], + [{currentTariff: "flat-std"}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Data allowance: plan allowances, rollover capped per plan, add-ons that have not expired yet, +// the cycle day and percentage used, then a column-less first-hit table decides the line state. +// Null speeds and notifications are dropped from the result. +{ + name: "data allowance: rollover cap, dated add-ons, throttling and usage alerts", + graph: { + nodes: [ + {input: "line"}, + {table: "allowance", passThrough: true, inputs: ["line.plan"], outputs: ["allow.baseGb", "allow.rolloverCap", "allow.throttleKbps", "allow.hardCap"], rules: [ + ["'basic'", "5", "0", "128", "true"], + ["'standard'", "15", "15", "512", "false"], + ["'premium'", "50", "50", "1024", "false"], + ["'unlimited'", "100", "0", "1024", "false"], + ]}, + {expression: "balance", passThrough: true, fields: { + "calc.activeAddonGb": "sum(map(filter(addons ?? [], d(#.expires).isAfter(d())), #.gb))", + "calc.rolloverGb": "min([rollover.balanceGb ?? 0, allow.rolloverCap])", + "calc.totalGb": "allow.baseGb + $.calc.rolloverGb + $.calc.activeAddonGb", + "calc.remainingGb": "round($.calc.totalGb - line.usedGb, 2)", + "calc.cycleDay": "d().diff(d(line.cycleStart), 'day') + 1", + "calc.pctUsed": "round(line.usedGb / $.calc.totalGb * 100)", + }}, + {table: "state", inputs: [null], outputs: ["state", "speedKbps", "notify"], rules: [ + ["calc.remainingGb <= 0 and allow.hardCap", "'blocked'", "0", "'data exhausted, buy an add-on'"], + ["calc.remainingGb <= 0", "'throttled'", "allow.throttleKbps", "'speed reduced to ' + string(allow.throttleKbps) + ' kbps'"], + ["calc.pctUsed >= 90", "'full speed'", "null", "'90% used'"], + ["calc.pctUsed >= 75 and calc.cycleDay < 15", "'full speed'", "null", "'75% used early in the cycle'"], + ["", "'full speed'", "null", "null"], + ]}, + {expression: "result", fields: { + state: "state", + speedKbps: "speedKbps", + notify: "notify", + remainingGb: "$nodes.balance.calc.remainingGb", + totalGb: "$nodes.balance.calc.totalGb", + cycleDay: "$nodes.balance.calc.cycleDay", + }}, + {output: "status"}, + ], + }, + cases: [ + [{line: {plan: "standard", usedGb: 10, cycleStart: "2025-03-10"}, rollover: {balanceGb: 5}, addons: []}, {state: "full speed", remainingGb: 10, totalGb: 20, cycleDay: 11}], + [{line: {plan: "standard", usedGb: 16, cycleStart: "2025-03-10"}, rollover: {balanceGb: 5}, addons: []}, {state: "full speed", notify: "75% used early in the cycle", remainingGb: 4, totalGb: 20, cycleDay: 11}], + [{line: {plan: "standard", usedGb: 16, cycleStart: "2025-03-01"}, rollover: {balanceGb: 5}, addons: []}, {state: "full speed", remainingGb: 4, totalGb: 20, cycleDay: 20}], + [{line: {plan: "standard", usedGb: 18, cycleStart: "2025-03-01"}, rollover: {balanceGb: 5}}, {state: "full speed", notify: "90% used", remainingGb: 2, totalGb: 20, cycleDay: 20}], + [{line: {plan: "standard", usedGb: 20, cycleStart: "2025-03-01"}, rollover: {balanceGb: 5}}, {state: "throttled", speedKbps: 512, notify: "speed reduced to 512 kbps", remainingGb: 0, totalGb: 20, cycleDay: 20}], + [{line: {plan: "standard", usedGb: 30.75, cycleStart: "2025-03-01"}, rollover: {balanceGb: 20}}, {state: "throttled", speedKbps: 512, notify: "speed reduced to 512 kbps", remainingGb: -0.75, totalGb: 30, cycleDay: 20}], + [{line: {plan: "basic", usedGb: 5.5, cycleStart: "2025-03-01"}, rollover: {balanceGb: 3}}, {state: "blocked", speedKbps: 0, notify: "data exhausted, buy an add-on", remainingGb: -0.5, totalGb: 5, cycleDay: 20}], + [{line: {plan: "basic", usedGb: 5.5, cycleStart: "2025-03-05"}, addons: [{gb: 2, expires: "2025-03-31"}]}, {state: "full speed", remainingGb: 1.5, totalGb: 7, cycleDay: 16}], + [{line: {plan: "basic", usedGb: 5.5, cycleStart: "2025-03-05"}, addons: [{gb: 2, expires: "2025-03-19"}]}, {state: "blocked", speedKbps: 0, notify: "data exhausted, buy an add-on", remainingGb: -0.5, totalGb: 5, cycleDay: 16}], + [{line: {plan: "basic", usedGb: 5.5, cycleStart: "2025-03-05"}, addons: [{gb: 2, expires: "2025-03-20T10:15:30Z"}, {gb: 1, expires: "2025-03-20T10:15:31Z"}]}, {state: "full speed", notify: "90% used", remainingGb: 0.5, totalGb: 6, cycleDay: 16}], + [{line: {plan: "premium", usedGb: 30, cycleStart: "2025-03-20"}, rollover: {balanceGb: 80}}, {state: "full speed", remainingGb: 70, totalGb: 100, cycleDay: 1}], + [{line: {plan: "unlimited", usedGb: 100, cycleStart: "2025-02-25"}, rollover: {balanceGb: 40}}, {state: "throttled", speedKbps: 1024, notify: "speed reduced to 1024 kbps", remainingGb: 0, totalGb: 100, cycleDay: 24}], + // An add-on without an expiry is an invalid date and never active. + [{line: {plan: "basic", usedGb: 1, cycleStart: "2025-03-10"}, addons: [{gb: 2}]}, {state: "full speed", remainingGb: 4, totalGb: 5, cycleDay: 11}], + // Unknown plans have no allowance, string add-on sizes do not sum, and a missing usage or + // cycle start fails the arithmetic. + [{line: {plan: "kids", usedGb: 1, cycleStart: "2025-03-10"}}, "!error"], + [{line: {plan: "basic", usedGb: 1, cycleStart: "2025-03-10"}, addons: [{gb: "2", expires: "2025-03-31"}]}, "!error"], + [{line: {plan: "basic", cycleStart: "2025-03-10"}}, "!error"], + [{line: {plan: "basic", usedGb: 1}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Roaming: a loop table rates each daily session by destination zone (echoing the volumes with +// defaults), an expression joined with the request totals pay-as-you-go and the day-pass price, +// and a first-hit table picks the billing mode with the spend cap read from the request. +{ + name: "roaming: zone rates per session, day pass and spend cap", + graph: { + nodes: [ + {input: "trip"}, + {table: "zone", executionMode: "loop", inputField: "sessions", outputPath: "rated", inputs: ["country"], outputs: ["zone", "mbRate", "minRate", "mb", "minutes"], rules: [ + ["'FR', 'DE', 'ES', 'IT'", "'eu'", "0", "0", "mb ?? 0", "minutes ?? 0"], + ["'US', 'CA'", "'na'", "0.01", "0.15", "mb ?? 0", "minutes ?? 0"], + ["'CH', 'NO'", "'europe-other'", "0.005", "0.1", "mb ?? 0", "minutes ?? 0"], + ["", "'world'", "0.02", "0.5", "mb ?? 0", "minutes ?? 0"], + ]}, + {expression: "charges", passThrough: true, fields: { + payg: "round(sum(map(rated, #.mb * #.mbRate + #.minutes * #.minRate)), 2)", + roamingDays: "count(rated, #.zone != 'eu')", + passCost: "$.roamingDays * 10", + }}, + {table: "bill", passThrough: true, inputs: ["hasPass", "payg"], outputs: ["billing", "amount"], rules: [ + ["true", "", "'day pass'", "passCost"], + ["", "> spendCap", "'capped'", "spendCap"], + ["", "", "'pay as you go'", "payg"], + ]}, + {expression: "notice", fields: {billing: "billing", amount: "amount", days: "roamingDays", message: "billing == 'capped' ? 'roaming data suspended at the spend cap' : null"}}, + {output: "charge"}, + ], + edges: ["trip -> zone -> charges", "trip -> charges -> bill -> notice -> charge"], + }, + cases: [ + [{sessions: [{country: "FR", mb: 500, minutes: 30}], spendCap: 50}, {billing: "pay as you go", amount: 0, days: 0}], + [{sessions: [{country: "US", mb: 300, minutes: 10}], spendCap: 50}, {billing: "pay as you go", amount: 4.5, days: 1}], + [{sessions: [{country: "US", mb: 1000, minutes: 60}, {country: "CA", mb: 500, minutes: 0}], spendCap: 50}, {billing: "pay as you go", amount: 24, days: 2}], + [{sessions: [{country: "US", mb: 1000, minutes: 60}, {country: "CA", mb: 500, minutes: 0}], spendCap: 50, hasPass: true}, {billing: "day pass", amount: 20, days: 2}], + [{sessions: [{country: "US", mb: 1000, minutes: 60}, {country: "FR", mb: 500, minutes: 0}], spendCap: 50, hasPass: true}, {billing: "day pass", amount: 10, days: 1}], + [{sessions: [{country: "JP", mb: 2000, minutes: 30}], spendCap: 50}, {billing: "capped", amount: 50, days: 1, message: "roaming data suspended at the spend cap"}], + [{sessions: [{country: "JP", mb: 2000, minutes: 30}], spendCap: 100}, {billing: "pay as you go", amount: 55, days: 1}], + [{sessions: [{country: "JP", mb: 2000, minutes: 20}], spendCap: 50}, {billing: "pay as you go", amount: 50, days: 1}], + [{sessions: [{country: "CH", mb: 1000, minutes: 10}, {country: "NO", mb: 333, minutes: 3}], spendCap: 50}, {billing: "pay as you go", amount: 7.97, days: 2}], + [{sessions: [], spendCap: 50}, {billing: "pay as you go", amount: 0, days: 0}], + // Missing country rates as world; missing volumes default to zero inside the loop. + [{sessions: [{mb: 100}, {country: "US"}], spendCap: 50}, {billing: "pay as you go", amount: 2, days: 2}], + // Without a spend cap the cap cell fails against null and pay-as-you-go applies. + [{sessions: [{country: "JP", mb: 2000, minutes: 30}]}, {billing: "pay as you go", amount: 55, days: 1}], + [{sessions: [{country: "JP", mb: 2000, minutes: 30}], hasPass: "yes", spendCap: 50}, {billing: "capped", amount: 50, days: 1, message: "roaming data suspended at the spend cap"}], + [{sessions: [{country: "US", mb: "300", minutes: 10}], spendCap: 50}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/62-realistic-hr-public.json5 b/core/engine/tests/spec/graph/62-realistic-hr-public.json5 new file mode 100644 index 00000000..6babd3ac --- /dev/null +++ b/core/engine/tests/spec/graph/62-realistic-hr-public.json5 @@ -0,0 +1,512 @@ +// Realistic HR and public-sector decisions: weekly payroll from a per-shift loop with daily and +// weekly overtime and a class switch whose unknown branch is a throwing function, leave accrual +// by tenure with a request switch, benefits enrollment with a per-dependent eligibility loop and +// a coverage tier, income tax where one bracket sub-decision is called twice (federal and state, +// each under its own outputPath), a building permit with zoning, collected issues and a collect +// switch of required inspections, and a small-business grant with dated grant history. Evaluation +// time is fixed at Thursday 2025-03-20T10:15:30Z. Each suite is one decision exercised across +// main paths, boundaries, missing data and bad types. + +// --------------------------------------------------------------------------------------------- +// Payroll: a loop expression splits each shift into regular, overtime (over 8 h) and double time +// (over 12 h), the weekly node moves regular hours over 40 into overtime, a switch prices exempt +// and hourly staff (an unknown class reaches a function that throws), then withholding and net. +{ + name: "payroll: daily and weekly overtime, shift premiums and withholding", + graph: { + nodes: [ + {input: "timesheet"}, + {expression: "perShift", executionMode: "loop", inputField: "shifts", outputPath: "split", fields: { + regular: "min([hours, 8])", + overtime: "max([0, min([hours, 12]) - 8])", + double: "max([0, hours - 12])", + nightHours: "night == true ? hours : 0", + holidayHours: "holiday == true ? hours : 0", + }}, + {expression: "weekly", passThrough: true, fields: { + "hours.regularDaily": "sum(map(split, #.regular))", + "hours.weeklyOver": "max([0, $.hours.regularDaily - 40])", + "hours.regular": "$.hours.regularDaily - $.hours.weeklyOver", + "hours.overtime": "sum(map(split, #.overtime)) + $.hours.weeklyOver", + "hours.double": "sum(map(split, #.double))", + "hours.night": "sum(map(split, #.nightHours))", + "hours.holiday": "sum(map(split, #.holidayHours))", + }}, + {switch: "classGate", when: ["employee.class == 'exempt'", "employee.class == 'hourly'", ""]}, + {expression: "exempt", fields: {gross: "employee.salaryWeekly", overtimePay: "0", premiums: "0"}}, + {expression: "hourly", fields: { + base: "hours.regular * employee.rate", + overtimePay: "hours.overtime * employee.rate * 1.5 + hours.double * employee.rate * 2", + premiums: "hours.night * 1.25 + hours.holiday * employee.rate * 0.5", + gross: "$.base + $.overtimePay + $.premiums", + }}, + {function: "unknownClass", source: """ +export const handler = async (input) => { + throw new Error('unknown employee class: ' + input.employee?.class); +}; +"""}, + {table: "withholding", passThrough: true, inputs: ["gross"], outputs: ["withholding"], rules: [ + ["<= 500", "round(gross * 0.1, 2)"], + ["(500..1500]", "round(50 + (gross - 500) * 0.2, 2)"], + ["> 1500", "round(250 + (gross - 1500) * 0.3, 2)"], + ]}, + {expression: "net", passThrough: true, fields: {net: "gross - withholding"}}, + {output: "payslip"}, + ], + edges: [ + "timesheet -> perShift -> weekly", + "timesheet -> weekly -> classGate", + "classGate:0 -> exempt -> withholding", + "classGate:1 -> hourly -> withholding", + "classGate:2 -> unknownClass -> withholding", + "withholding -> net -> payslip", + ], + }, + cases: [ + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}]}, {base: 800, overtimePay: 0, premiums: 0, gross: 800, withholding: 110, net: 690}], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 10}, {hours: 10}, {hours: 10}, {hours: 10}, {hours: 10}]}, {base: 800, overtimePay: 300, premiums: 0, gross: 1100, withholding: 170, net: 930}], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}]}, {base: 800, overtimePay: 240, premiums: 0, gross: 1040, withholding: 158, net: 882}], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 14}]}, {base: 160, overtimePay: 200, premiums: 0, gross: 360, withholding: 36, net: 324}], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 12}]}, {base: 160, overtimePay: 120, premiums: 0, gross: 280, withholding: 28, net: 252}], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 8, night: true}, {hours: 8, night: true}, {hours: 8, night: true}]}, {base: 480, overtimePay: 0, premiums: 30, gross: 510, withholding: 52, net: 458}], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 8, holiday: true}]}, {base: 160, overtimePay: 0, premiums: 80, gross: 240, withholding: 24, net: 216}], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 8, holiday: true, night: true}]}, {base: 160, overtimePay: 0, premiums: 90, gross: 250, withholding: 25, net: 225}], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: 8, night: "yes"}]}, {base: 160, overtimePay: 0, premiums: 0, gross: 160, withholding: 16, net: 144}], + [{employee: {class: "hourly", rate: 20}, shifts: []}, {base: 0, overtimePay: 0, premiums: 0, gross: 0, withholding: 0, net: 0}], + // Withholding band edges: 500 is the top of the first band, 1500 the top of the second. + [{employee: {class: "hourly", rate: 12.5}, shifts: [{hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}]}, {base: 500, overtimePay: 0, premiums: 0, gross: 500, withholding: 50, net: 450}], + [{employee: {class: "hourly", rate: 37.5}, shifts: [{hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}, {hours: 8}]}, {base: 1500, overtimePay: 0, premiums: 0, gross: 1500, withholding: 250, net: 1250}], + [{employee: {class: "hourly", rate: 18.35}, shifts: [{hours: 8.5}, {hours: 8.5}, {hours: 8.5}, {hours: 8.5}, {hours: 8.5}]}, {base: 734, overtimePay: 68.8125, premiums: 0, gross: 802.8125, withholding: 110.56, net: 692.2525}], + [{employee: {class: "exempt", salaryWeekly: 2000}, shifts: [{hours: 12}, {hours: 12}, {hours: 12}, {hours: 12}, {hours: 12}]}, {gross: 2000, overtimePay: 0, premiums: 0, withholding: 400, net: 1600}], + [{employee: {class: "exempt", salaryWeekly: 1000}, shifts: []}, {gross: 1000, overtimePay: 0, premiums: 0, withholding: 150, net: 850}], + // Unknown or missing class: the default branch's function throws. + [{employee: {class: "contractor", rate: 50}, shifts: [{hours: 8}]}, "!error: unknown employee class: contractor"], + [{employee: {rate: 50}, shifts: [{hours: 8}]}, "!error: unknown employee class: undefined"], + // Missing rate, string hours, and an exempt employee without a salary (null gross). + [{employee: {class: "hourly"}, shifts: [{hours: 8}]}, "!error"], + [{employee: {class: "hourly", rate: 20}, shifts: [{hours: "8"}]}, "!error"], + [{employee: {class: "exempt"}, shifts: []}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Leave accrual: tenure and probation from the hire date, an accrual rate and balance cap by +// status and tenure, the period's accrual capped (the excess is forfeited), then a request +// switch whose pass-through branches mark the request and a final node settles the balance. +{ + name: "leave accrual: tenure rates, balance cap, probation and leave requests", + graph: { + nodes: [ + {input: "employee"}, + {expression: "tenure", passThrough: true, fields: { + "emp.years": "d().diff(d(hireDate), 'year')", + "emp.probation": "d().diff(d(hireDate), 'day') < 90", + }}, + {table: "accrualRate", passThrough: true, inputs: ["status", "emp.years"], outputs: ["accrual.perPeriod", "accrual.cap"], rules: [ + ["'part-time'", "", "round(4.62 * (fte ?? 0.5), 2)", "120"], + ["'full-time'", "< 3", "4.62", "160"], + ["'full-time'", "[3..10)", "6.16", "200"], + ["'full-time'", ">= 10", "7.69", "240"], + ]}, + {expression: "accrue", passThrough: true, fields: { + "accrual.earned": "emp.probation ? 0 : accrual.perPeriod", + "accrual.newBalance": "min([balanceHours + $.accrual.earned, accrual.cap])", + "accrual.forfeited": "balanceHours + $.accrual.earned - $.accrual.newBalance", + }}, + {switch: "requestGate", when: [ + "request == null", + "request.hours > accrual.newBalance and request.allowNegative != true", + "some(blackout ?? [], not d(#).isBefore(d(request.start)) and not d(#).isAfter(d(request.end)))", + "", + ]}, + {expression: "noRequest", passThrough: true, fields: {requestStatus: "'none'"}}, + {expression: "insufficient", passThrough: true, fields: {requestStatus: "'denied: insufficient balance'"}}, + {expression: "blackedOut", passThrough: true, fields: {requestStatus: "'denied: blackout period'"}}, + {expression: "approve", passThrough: true, fields: {requestStatus: "'approved'", deducted: "request.hours"}}, + {expression: "settle", fields: { + balance: "accrual.newBalance - (deducted ?? 0)", + earned: "accrual.earned", + forfeited: "accrual.forfeited", + requestStatus: "requestStatus", + }}, + {output: "leave"}, + ], + edges: [ + "employee -> tenure -> accrualRate -> accrue -> requestGate", + "requestGate:0 -> noRequest -> settle", + "requestGate:1 -> insufficient -> settle", + "requestGate:2 -> blackedOut -> settle", + "requestGate:3 -> approve -> settle", + "settle -> leave", + ], + }, + cases: [ + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40}, {balance: 46.16, earned: 6.16, forfeited: 0, requestStatus: "none"}], + [{hireDate: "2023-03-21", status: "full-time", balanceHours: 10}, {balance: 14.62, earned: 4.62, forfeited: 0, requestStatus: "none"}], + [{hireDate: "2022-03-20", status: "full-time", balanceHours: 10}, {balance: 16.16, earned: 6.16, forfeited: 0, requestStatus: "none"}], + [{hireDate: "2022-03-21", status: "full-time", balanceHours: 10}, {balance: 14.62, earned: 4.62, forfeited: 0, requestStatus: "none"}], + [{hireDate: "2015-03-20", status: "full-time", balanceHours: 238}, {balance: 240, earned: 7.69, forfeited: 5.69, requestStatus: "none"}], + [{hireDate: "2015-03-20", status: "full-time", balanceHours: 250}, {balance: 240, earned: 7.69, forfeited: 17.69, requestStatus: "none"}], + // Probation is the first 90 days: nothing accrues on day 69, the full rate on day 90. + [{hireDate: "2025-01-10", status: "full-time", balanceHours: 0}, {balance: 0, earned: 0, forfeited: 0, requestStatus: "none"}], + [{hireDate: "2024-12-20", status: "full-time", balanceHours: 0}, {balance: 4.62, earned: 4.62, forfeited: 0, requestStatus: "none"}], + [{hireDate: "2019-06-01", status: "part-time", fte: 0.6, balanceHours: 50}, {balance: 52.77, earned: 2.77, forfeited: 0, requestStatus: "none"}], + [{hireDate: "2019-06-01", status: "part-time", balanceHours: 119}, {balance: 120, earned: 2.31, forfeited: 1.31, requestStatus: "none"}], + // Requests: approved within the balance (including exactly all of it), denied above it unless + // a negative balance is allowed, denied when a blackout day falls inside the request. + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40, request: {hours: 16, start: "2025-04-07", end: "2025-04-08"}}, {balance: 30.16, earned: 6.16, forfeited: 0, requestStatus: "approved"}], + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40, request: {hours: 46.16, start: "2025-04-07", end: "2025-04-14"}}, {balance: 0, earned: 6.16, forfeited: 0, requestStatus: "approved"}], + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40, request: {hours: 50, start: "2025-04-07", end: "2025-04-14"}}, {balance: 46.16, earned: 6.16, forfeited: 0, requestStatus: "denied: insufficient balance"}], + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40, request: {hours: 50, start: "2025-04-07", end: "2025-04-14", allowNegative: true}}, {balance: -3.84, earned: 6.16, forfeited: 0, requestStatus: "approved"}], + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40, request: {hours: 24, start: "2025-12-22", end: "2025-12-26"}, blackout: ["2025-12-24"]}, {balance: 46.16, earned: 6.16, forfeited: 0, requestStatus: "denied: blackout period"}], + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40, request: {hours: 24, start: "2025-12-22", end: "2025-12-24"}, blackout: ["2025-12-24", "2025-12-31"]}, {balance: 46.16, earned: 6.16, forfeited: 0, requestStatus: "denied: blackout period"}], + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40, request: {hours: 16, start: "2025-12-22", end: "2025-12-23"}, blackout: ["2025-12-24", "2025-12-31"]}, {balance: 30.16, earned: 6.16, forfeited: 0, requestStatus: "approved"}], + // A string request size errors the balance condition (false), passes the blackout check and + // is approved, then the deduction fails. + [{hireDate: "2020-01-15", status: "full-time", balanceHours: 40, request: {hours: "16", start: "2025-04-07", end: "2025-04-08"}}, "!error"], + // No accrual row for contractors, no hire date, no balance. + [{hireDate: "2020-01-15", status: "contractor", balanceHours: 40}, "!error"], + [{status: "full-time", balanceHours: 40}, "!error"], + [{hireDate: "2020-01-15", status: "full-time"}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Benefits enrollment: the enrollment window since the qualifying event, a loop table deciding +// each dependent's eligibility (pass-through, so the request travels with the result), the +// coverage tier from eligible dependents, premium and employer share tables, and the cost per +// paycheck (26 a year). +{ + name: "benefits enrollment: event window, dependent eligibility, tier and paycheck cost", + graph: { + nodes: [ + {input: "enrollment"}, + {expression: "window", passThrough: true, fields: { + "enroll.daysSinceEvent": "d().diff(d(event.date), 'day')", + "enroll.windowDays": "event.type == 'open-enrollment' ? 14 : 30", + "enroll.open": "$.enroll.daysSinceEvent >= 0 and $.enroll.daysSinceEvent <= $.enroll.windowDays", + }}, + {switch: "windowGate", when: ["not enroll.open", ""]}, + {expression: "closed", fields: {status: "'window closed'", daysSinceEvent: "enroll.daysSinceEvent"}}, + {table: "eligibility", executionMode: "loop", passThrough: true, inputField: "dependents", outputPath: "deps", inputs: ["relation", "age", "affidavit"], outputs: ["relation", "eligible", "reason"], rules: [ + ["'spouse'", "", "", "relation", "true", "null"], + ["'partner'", "", "true", "relation", "true", "null"], + ["'partner'", "", "", "relation", "false", "'affidavit required'"], + ["'child'", "< 26", "", "relation", "true", "null"], + ["'child'", "", "", "relation", "false", "'child over 26'"], + ["", "", "", "relation", "false", "'not an eligible relation'"], + ]}, + {expression: "tier", passThrough: true, fields: { + "cover.spouse": "some(deps, #.eligible and #.relation in ['spouse', 'partner'])", + "cover.children": "count(deps, #.eligible and #.relation == 'child')", + "cover.tier": "$.cover.spouse ? ($.cover.children > 0 ? 'family' : 'employee+spouse') : ($.cover.children > 0 ? 'employee+children' : 'employee')", + }}, + {table: "premium", passThrough: true, inputs: ["plan", "cover.tier"], outputs: ["monthlyPremium"], rules: [ + ["'hmo'", "'employee'", "400"], + ["'hmo'", "'employee+spouse'", "850"], + ["'hmo'", "'employee+children'", "750"], + ["'hmo'", "'family'", "1200"], + ["'ppo'", "'employee'", "550"], + ["'ppo'", "'employee+spouse'", "1150"], + ["'ppo'", "'employee+children'", "1000"], + ["'ppo'", "'family'", "1600"], + ]}, + {table: "contribution", passThrough: true, inputs: ["employee.salary"], outputs: ["employerShare"], rules: [ + ["< 40000", "0.9"], + ["[40000..100000)", "0.8"], + ["", "0.7"], + ]}, + {expression: "cost", fields: { + status: "'enrolled'", + tier: "cover.tier", + monthlyPremium: "monthlyPremium", + employerPays: "round(monthlyPremium * employerShare, 2)", + employeePerPaycheck: "round((monthlyPremium - $.employerPays) * 12 / 26, 2)", + ineligible: "map(filter(deps, not #.eligible), #.reason)", + }}, + {output: "election"}, + ], + edges: [ + "enrollment -> window -> windowGate", + "windowGate:0 -> closed -> election", + "windowGate:1 -> eligibility -> tier -> premium -> contribution -> cost -> election", + ], + }, + cases: [ + [{employee: {salary: 50000}, event: {type: "new-hire", date: "2025-03-10"}, plan: "hmo", dependents: []}, {status: "enrolled", tier: "employee", monthlyPremium: 400, employerPays: 320, employeePerPaycheck: 36.92, ineligible: []}], + [{employee: {salary: 50000}, event: {type: "marriage", date: "2025-03-01"}, plan: "hmo", dependents: [{relation: "spouse", age: 33}]}, {status: "enrolled", tier: "employee+spouse", monthlyPremium: 850, employerPays: 680, employeePerPaycheck: 78.46, ineligible: []}], + [{employee: {salary: 50000}, event: {type: "birth", date: "2025-03-19"}, plan: "hmo", dependents: [{relation: "spouse", age: 33}, {relation: "child", age: 0}]}, {status: "enrolled", tier: "family", monthlyPremium: 1200, employerPays: 960, employeePerPaycheck: 110.77, ineligible: []}], + [{employee: {salary: 120000}, event: {type: "new-hire", date: "2025-03-10"}, plan: "ppo", dependents: [{relation: "child", age: 25}, {relation: "child", age: 26}]}, {status: "enrolled", tier: "employee+children", monthlyPremium: 1000, employerPays: 700, employeePerPaycheck: 138.46, ineligible: ["child over 26"]}], + [{employee: {salary: 30000}, event: {type: "new-hire", date: "2025-03-10"}, plan: "hmo", dependents: [{relation: "partner"}, {relation: "child", age: 5}]}, {status: "enrolled", tier: "employee+children", monthlyPremium: 750, employerPays: 675, employeePerPaycheck: 34.62, ineligible: ["affidavit required"]}], + [{employee: {salary: 30000}, event: {type: "new-hire", date: "2025-03-10"}, plan: "hmo", dependents: [{relation: "partner", affidavit: true}, {relation: "child", age: 5}]}, {status: "enrolled", tier: "family", monthlyPremium: 1200, employerPays: 1080, employeePerPaycheck: 55.38, ineligible: []}], + [{employee: {salary: 100000}, event: {type: "new-hire", date: "2025-03-10"}, plan: "ppo", dependents: [{relation: "parent", age: 70}]}, {status: "enrolled", tier: "employee", monthlyPremium: 550, employerPays: 385, employeePerPaycheck: 76.15, ineligible: ["not an eligible relation"]}], + [{employee: {salary: 39999.99}, event: {type: "new-hire", date: "2025-03-10"}, plan: "ppo", dependents: [{relation: "spouse"}, {relation: "spouse"}]}, {status: "enrolled", tier: "employee+spouse", monthlyPremium: 1150, employerPays: 1035, employeePerPaycheck: 53.08, ineligible: []}], + // Window edges: 30 days after a life event, 14 for open enrollment; events in the future + // are not open yet. + [{employee: {salary: 50000}, event: {type: "marriage", date: "2025-02-18"}, plan: "hmo", dependents: []}, {status: "enrolled", tier: "employee", monthlyPremium: 400, employerPays: 320, employeePerPaycheck: 36.92, ineligible: []}], + [{employee: {salary: 50000}, event: {type: "marriage", date: "2025-02-17"}, plan: "hmo", dependents: []}, {status: "window closed", daysSinceEvent: 31}], + [{employee: {salary: 50000}, event: {type: "open-enrollment", date: "2025-03-06"}, plan: "hmo", dependents: []}, {status: "enrolled", tier: "employee", monthlyPremium: 400, employerPays: 320, employeePerPaycheck: 36.92, ineligible: []}], + [{employee: {salary: 50000}, event: {type: "open-enrollment", date: "2025-03-05"}, plan: "hmo", dependents: []}, {status: "window closed", daysSinceEvent: 15}], + [{employee: {salary: 50000}, event: {type: "new-hire", date: "2025-03-25"}, plan: "hmo", dependents: []}, {status: "window closed", daysSinceEvent: -4}], + // A child without an age fails the age cell and lands on the over-26 row; a missing salary + // fails both range cells and gets the lowest share. + [{employee: {salary: 50000}, event: {type: "new-hire", date: "2025-03-10"}, plan: "hmo", dependents: [{relation: "child"}]}, {status: "enrolled", tier: "employee", monthlyPremium: 400, employerPays: 320, employeePerPaycheck: 36.92, ineligible: ["child over 26"]}], + [{employee: {}, event: {type: "new-hire", date: "2025-03-10"}, plan: "hmo", dependents: []}, {status: "enrolled", tier: "employee", monthlyPremium: 400, employerPays: 280, employeePerPaycheck: 55.38, ineligible: []}], + // No event date, no plan. + [{employee: {salary: 50000}, event: {type: "new-hire"}, plan: "hmo", dependents: []}, "!error"], + [{employee: {salary: 50000}, event: {type: "new-hire", date: "2025-03-10"}, dependents: []}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Income tax: the same bracket sub-decision is called twice, once with the federal taxable +// income and brackets (chosen by filing status) and once with the state's, each under its own +// outputPath; a child credit with a phase-out runs on a third branch, and all three join in the +// settlement. +{ + name: "income tax: one bracket sub-decision for federal and state, child credit phase-out", + decisions: { + progressive: { + nodes: [ + {expression: "tax", fields: { + tax: "round(sum(map(brackets, max([0, min([taxable, #.to ?? taxable]) - #.from]) * #.rate)), 2)", + marginal: "len(filter(brackets, taxable > #.from)) == 0 ? 0 : max(map(filter(brackets, taxable > #.from), #.rate))", + }}, + ], + }, + }, + graph: { + nodes: [ + {input: "taxReturn"}, + {table: "deduction", passThrough: true, inputs: ["filingStatus"], outputs: ["fed.standard", "fed.brackets"], rules: [ + ["'single'", "14600", "[{from: 0, to: 11600, rate: 0.1}, {from: 11600, to: 47150, rate: 0.12}, {from: 47150, to: 100525, rate: 0.22}, {from: 100525, rate: 0.24}]"], + ["'married'", "29200", "[{from: 0, to: 23200, rate: 0.1}, {from: 23200, to: 94300, rate: 0.12}, {from: 94300, to: 201050, rate: 0.22}, {from: 201050, rate: 0.24}]"], + ["'head'", "21900", "[{from: 0, to: 16550, rate: 0.1}, {from: 16550, to: 63100, rate: 0.12}, {from: 63100, rate: 0.22}]"], + ]}, + {expression: "fedPrep", fields: { + taxable: "max([0, income.wages + (income.other ?? 0) - max([fed.standard, itemized ?? 0])])", + brackets: "fed.brackets", + }}, + {decision: "fedTax", key: "progressive", outputPath: "federal"}, + {expression: "statePrep", fields: { + taxable: "max([0, income.wages + (income.other ?? 0) - 5000])", + brackets: "[{from: 0, to: 10000, rate: 0.02}, {from: 10000, to: 50000, rate: 0.045}, {from: 50000, rate: 0.06}]", + }}, + {decision: "stateTax", key: "progressive", outputPath: "state"}, + {table: "ctcThreshold", passThrough: true, inputs: ["filingStatus"], outputs: ["ctc.threshold"], rules: [ + ["'married'", "400000"], + ["", "200000"], + ]}, + {expression: "ctc", passThrough: true, fields: { + "ctc.amount": "max([0, (dependents ?? 0) * 2000 - ceil(max([0, income.wages + (income.other ?? 0) - ctc.threshold]) / 1000) * 50])", + }}, + {expression: "settle", fields: { + federalTax: "max([0, federal.tax - ctc.amount])", + stateTax: "state.tax", + totalTax: "$.federalTax + $.stateTax", + withheld: "withheld ?? 0", + balance: "round($.withheld - $.totalTax, 2)", + outcome: "$.balance >= 0 ? 'refund' : 'owed'", + effectiveRate: "income.wages + (income.other ?? 0) == 0 ? 0 : round($.totalTax / (income.wages + (income.other ?? 0)) * 100, 1)", + marginal: "federal.marginal", + }}, + {output: "assessment"}, + ], + edges: [ + "taxReturn -> deduction -> fedPrep -> fedTax -> settle", + "taxReturn -> statePrep -> stateTax -> settle", + "taxReturn -> ctcThreshold -> ctc -> settle", + "settle -> assessment", + ], + }, + cases: [ + [{filingStatus: "single", income: {wages: 60000}, withheld: 8000}, {federalTax: 5216, stateTax: 2300, totalTax: 7516, withheld: 8000, balance: 484, outcome: "refund", effectiveRate: 12.5, marginal: 0.12}], + [{filingStatus: "married", income: {wages: 120000, other: 5000}, dependents: 2, withheld: 9000}, {federalTax: 7182, stateTax: 6200, totalTax: 13382, withheld: 9000, balance: -4382, outcome: "owed", effectiveRate: 10.7, marginal: 0.22}], + [{filingStatus: "single", income: {wages: 10000}, withheld: 500}, {federalTax: 0, stateTax: 100, totalTax: 100, withheld: 500, balance: 400, outcome: "refund", effectiveRate: 1, marginal: 0}], + [{filingStatus: "head", income: {wages: 50000}, dependents: 1, withheld: 3000}, {federalTax: 1041, stateTax: 1775, totalTax: 2816, withheld: 3000, balance: 184, outcome: "refund", effectiveRate: 5.6, marginal: 0.12}], + [{filingStatus: "single", income: {wages: 230000}, dependents: 2, withheld: 50000}, {federalTax: 42238.5, stateTax: 12500, totalTax: 54738.5, withheld: 50000, balance: -4738.5, outcome: "owed", effectiveRate: 23.8, marginal: 0.24}], + [{filingStatus: "single", income: {wages: 60000}, itemized: 20000, withheld: 8000}, {federalTax: 4568, stateTax: 2300, totalTax: 6868, withheld: 8000, balance: 1132, outcome: "refund", effectiveRate: 11.4, marginal: 0.12}], + [{filingStatus: "single", income: {wages: 60000}, itemized: 10000, withheld: 8000}, {federalTax: 5216, stateTax: 2300, totalTax: 7516, withheld: 8000, balance: 484, outcome: "refund", effectiveRate: 12.5, marginal: 0.12}], + // One dollar over the phase-out threshold costs a full 50 step. + [{filingStatus: "single", income: {wages: 200001}, dependents: 1, withheld: 46288.8}, {federalTax: 35588.74, stateTax: 10700.06, totalTax: 46288.8, withheld: 46288.8, balance: 0, outcome: "refund", effectiveRate: 23.1, marginal: 0.24}], + [{filingStatus: "single", income: {wages: 40000}, dependents: 3}, {federalTax: 0, stateTax: 1325, totalTax: 1325, withheld: 0, balance: -1325, outcome: "owed", effectiveRate: 3.3, marginal: 0.12}], + [{filingStatus: "married", income: {wages: 0}}, {federalTax: 0, stateTax: 0, totalTax: 0, withheld: 0, balance: 0, outcome: "refund", effectiveRate: 0, marginal: 0}], + // Bracket edges: taxable income exactly at a bracket boundary keeps the lower marginal rate. + [{filingStatus: "single", income: {wages: 26200}, withheld: 2000}, {federalTax: 1160, stateTax: 704, totalTax: 1864, withheld: 2000, balance: 136, outcome: "refund", effectiveRate: 7.1, marginal: 0.1}], + [{filingStatus: "single", income: {wages: 26201}, withheld: 2000}, {federalTax: 1160.12, stateTax: 704.05, totalTax: 1864.17, withheld: 2000, balance: 135.83, outcome: "refund", effectiveRate: 7.1, marginal: 0.12}], + // Unknown filing status has no standard deduction; missing or string wages fail every branch. + [{filingStatus: "widow", income: {wages: 60000}}, "!error"], + [{filingStatus: "single", income: {}}, "!error"], + [{filingStatus: "single", income: {wages: "60000"}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Building permit: zoning by zone and project type, collected issues, a first-hit switch that +// issues, refers single historic-review cases or rejects, valuation fees with an ADU waiver, and +// a collect switch adding each required inspection before the permit is assembled. +{ + name: "building permit: zoning, issues, historic referral, fees and inspections", + graph: { + nodes: [ + {input: "application"}, + {table: "zoning", passThrough: true, inputs: ["project.zone", "project.type"], outputs: ["zoning.allowed", "zoning.maxHeight", "zoning.minSetback"], rules: [ + ["'C1'", "'adu'", "false", "0", "0"], + ["'R1'", "'adu'", "true", "25", "5"], + ["", "'fence'", "true", "6", "0"], + ["", "'deck'", "true", "12", "3"], + ["'R1', 'R2'", "'addition'", "true", "35", "10"], + ["'C1'", "'addition'", "true", "60", "0"], + ["", "'demolition'", "true", "999", "0"], + ["", "", "false", "0", "0"], + ]}, + {table: "issues", passThrough: true, inputs: [null], outputs: ["issues[]"], rules: [ + ["not zoning.allowed", "'use not permitted in zone'"], + ["project.heightFt > zoning.maxHeight", "'exceeds height limit'"], + ["project.setbackFt < zoning.minSetback", "'setback too small'"], + ["project.historic == true and project.type in ['demolition', 'addition']", "'historic review required'"], + ["not (applicant.licensed == true or applicant.owner == true)", "'licensed contractor or owner-builder required'"], + ["", ""], + ]}, + {switch: "route", when: ["len(issues) == 0", "len(issues) == 1 and issues[0] == 'historic review required'", ""]}, + {expression: "historic", fields: {status: "'referred to historic commission'", issues: "issues"}}, + {expression: "reject", fields: {status: "'rejected'", issues: "issues"}}, + {table: "fees", passThrough: true, inputs: ["project.valuation"], outputs: ["fee.base"], rules: [ + ["< 1000", "0"], + ["[1000..25000)", "75 + project.valuation * 0.01"], + ["[25000..100000)", "325 + (project.valuation - 25000) * 0.008"], + [">= 100000", "925 + (project.valuation - 100000) * 0.005"], + ]}, + {switch: "inspections", hit: "collect", when: [ + "project.type in ['addition', 'adu']", + "project.type in ['addition', 'adu', 'deck']", + "project.type == 'adu' or project.sqft > 500", + "", + ]}, + {expression: "structural", fields: {"inspect.structural": "true"}}, + {expression: "framing", fields: {"inspect.framing": "true"}}, + {expression: "electrical", fields: {"inspect.electrical": "true"}}, + {expression: "base", fields: {fee: "round(fee.base * (project.type == 'adu' ? 0.5 : 1), 2)"}}, + {expression: "permit", fields: {status: "'issued'", fee: "fee", inspections: "inspect ?? {}"}}, + {output: "decision"}, + ], + edges: [ + "application -> zoning -> issues -> route", + "route:1 -> historic -> decision", + "route:2 -> reject -> decision", + "route:0 -> fees -> inspections", + "inspections:0 -> structural -> permit", + "inspections:1 -> framing -> permit", + "inspections:2 -> electrical -> permit", + "inspections:3 -> base -> permit", + "permit -> decision", + ], + }, + cases: [ + [{project: {type: "addition", zone: "R1", valuation: 50000, sqft: 400, heightFt: 20, setbackFt: 15}, applicant: {licensed: true}}, {status: "issued", fee: 525, inspections: {structural: true, framing: true}}], + [{project: {type: "addition", zone: "R2", valuation: 50000, sqft: 600, heightFt: 35, setbackFt: 10}, applicant: {licensed: true}}, {status: "issued", fee: 525, inspections: {structural: true, framing: true, electrical: true}}], + [{project: {type: "adu", zone: "R1", valuation: 120000, sqft: 700, heightFt: 20, setbackFt: 5}, applicant: {owner: true}}, {status: "issued", fee: 512.5, inspections: {structural: true, framing: true, electrical: true}}], + [{project: {type: "addition", zone: "C1", valuation: 250000, sqft: 2000, heightFt: 50, setbackFt: 0}, applicant: {licensed: true}}, {status: "issued", fee: 1675, inspections: {structural: true, framing: true, electrical: true}}], + [{project: {type: "fence", zone: "R1", valuation: 800, heightFt: 6, setbackFt: 0}, applicant: {owner: true}}, {status: "issued", fee: 0, inspections: {}}], + [{project: {type: "deck", zone: "R2", valuation: 1000, sqft: 200, heightFt: 10, setbackFt: 3}, applicant: {owner: true}}, {status: "issued", fee: 85, inspections: {framing: true}}], + [{project: {type: "deck", zone: "R2", valuation: 999.99, sqft: 200, heightFt: 10, setbackFt: 3}, applicant: {owner: true}}, {status: "issued", fee: 0, inspections: {framing: true}}], + [{project: {type: "deck", zone: "R2", valuation: 25000, sqft: 501, heightFt: 12, setbackFt: 3}, applicant: {owner: true}}, {status: "issued", fee: 325, inspections: {framing: true, electrical: true}}], + [{project: {type: "deck", zone: "R2", valuation: 100000, sqft: 200, heightFt: 12, setbackFt: 3}, applicant: {owner: true}}, {status: "issued", fee: 925, inspections: {framing: true}}], + // Demolition without dimensions: the height and setback comparisons fail against null and + // raise no issue; the sqft condition fails too. + [{project: {type: "demolition", zone: "C1", valuation: 30000}, applicant: {licensed: true}}, {status: "issued", fee: 365, inspections: {}}], + // Rejections collect every issue in rule order. + [{project: {type: "adu", zone: "C1", valuation: 120000, sqft: 700, heightFt: 20, setbackFt: 5}, applicant: {owner: true}}, {status: "rejected", issues: ["use not permitted in zone", "exceeds height limit"]}], + [{project: {type: "adu", zone: "R2", valuation: 120000, sqft: 700, heightFt: 20, setbackFt: 5}, applicant: {owner: true}}, {status: "rejected", issues: ["use not permitted in zone", "exceeds height limit"]}], + [{project: {type: "fence", zone: "R1", valuation: 800, heightFt: 7, setbackFt: 0}, applicant: {owner: true}}, {status: "rejected", issues: ["exceeds height limit"]}], + [{project: {type: "deck", zone: "R1", valuation: 8000, heightFt: 10, setbackFt: 2}, applicant: {owner: true}}, {status: "rejected", issues: ["setback too small"]}], + [{project: {type: "addition", zone: "R1", valuation: 50000, sqft: 400, heightFt: 20, setbackFt: 15}, applicant: {licensed: false, owner: false}}, {status: "rejected", issues: ["licensed contractor or owner-builder required"]}], + [{project: {type: "addition", zone: "R1", valuation: 50000, sqft: 400, heightFt: 20, setbackFt: 15}}, {status: "rejected", issues: ["licensed contractor or owner-builder required"]}], + [{project: {type: "addition", valuation: 50000, sqft: 400, heightFt: 20, setbackFt: 15}, applicant: {licensed: true}}, {status: "rejected", issues: ["use not permitted in zone", "exceeds height limit"]}], + // Historic review alone is referred; with another issue the application is rejected. + [{project: {type: "addition", zone: "R1", valuation: 50000, sqft: 400, heightFt: 20, setbackFt: 15, historic: true}, applicant: {licensed: true}}, {status: "referred to historic commission", issues: ["historic review required"]}], + [{project: {type: "addition", zone: "R1", valuation: 50000, sqft: 400, heightFt: 20, setbackFt: 5, historic: true}, applicant: {licensed: true}}, {status: "rejected", issues: ["setback too small", "historic review required"]}], + [{project: {type: "deck", zone: "R1", valuation: 5000, sqft: 100, heightFt: 8, setbackFt: 4, historic: true}, applicant: {owner: true}}, {status: "issued", fee: 125, inspections: {framing: true}}], + // An approvable project without a valuation has no fee row and the fee step fails. + [{project: {type: "addition", zone: "R1", sqft: 400, heightFt: 20, setbackFt: 15}, applicant: {licensed: true}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Small-business grant: grants received in the last three years from a dated history, ordered +// hard exclusions in a first-hit switch, collected priority points, an award band, and an award +// floored to hundreds under the band maximum, the 50k lifetime cap and the remaining budget. +// A missing headcount errors the size condition, which is then false: the exclusion is skipped. +{ + name: "small-business grant: history window, exclusions, priority points and award caps", + graph: { + nodes: [ + {input: "application"}, + {expression: "history", passThrough: true, fields: { + "hist.recent": "filter(priorGrants ?? [], d(#.date).isAfter(d().sub(3, 'year')))", + "hist.recentTotal": "sum(map($.hist.recent, #.amount))", + }}, + {switch: "exclusions", when: [ + "business.employees > 50 or business.revenue > 5000000", + "business.yearsOperating < 1", + "hist.recentTotal >= 50000", + "", + ]}, + {expression: "notSmall", fields: {status: "'ineligible'", reason: "'not a small business'"}}, + {expression: "tooNew", fields: {status: "'ineligible'", reason: "'operating less than a year'"}}, + {expression: "capReached", fields: {status: "'ineligible'", reason: "'lifetime cap reached'"}}, + {table: "scoring", passThrough: true, inputs: [null], outputs: ["points[]"], rules: [ + ["business.county in ['Lake', 'Marsh', 'Pine']", "20"], + ["some(business.ownership ?? [], # in ['woman', 'veteran', 'minority'])", "15"], + ["business.employees <= 10", "10"], + ["business.revenue < 500000", "10"], + ["len(hist.recent) == 0", "5"], + ["", "0"], + ]}, + {expression: "score", passThrough: true, fields: {score: "sum(points)"}}, + {table: "band", passThrough: true, inputs: ["score"], outputs: ["award.pct", "award.max"], rules: [ + [">= 40", "1", "25000"], + ["[25..40)", "0.75", "15000"], + ["[15..25)", "0.5", "10000"], + ["", "0", "0"], + ]}, + {expression: "award", fields: { + amount: "floor(min([request.amount * award.pct, award.max, 50000 - hist.recentTotal, program.remainingBudget]) / 100) * 100", + status: "$.amount > 0 ? 'awarded' : 'not funded'", + score: "score", + }}, + {output: "grant"}, + ], + edges: [ + "application -> history -> exclusions", + "exclusions:0 -> notSmall -> grant", + "exclusions:1 -> tooNew -> grant", + "exclusions:2 -> capReached -> grant", + "exclusions:3 -> scoring -> score -> band -> award -> grant", + ], + }, + cases: [ + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake", ownership: ["veteran"]}, request: {amount: 20000}, program: {remainingBudget: 1000000}}, {amount: 20000, status: "awarded", score: 60}], + [{business: {employees: 10, revenue: 2000000, yearsOperating: 4, county: "Metro", ownership: []}, priorGrants: [{amount: 10000, date: "2023-06-01"}], request: {amount: 30000}, program: {remainingBudget: 1000000}}, {amount: 0, status: "not funded", score: 10}], + [{business: {employees: 10, revenue: 499999, yearsOperating: 2, county: "Metro", ownership: ["woman"]}, request: {amount: 40000}, program: {remainingBudget: 1000000}}, {amount: 25000, status: "awarded", score: 40}], + [{business: {employees: 12, revenue: 400000, yearsOperating: 2, county: "Pine"}, priorGrants: [{amount: 5000, date: "2024-01-10"}], request: {amount: 12345}, program: {remainingBudget: 1000000}}, {amount: 9200, status: "awarded", score: 30}], + [{business: {employees: 30, revenue: 900000, yearsOperating: 2, county: "Marsh"}, priorGrants: [{amount: 5000, date: "2024-01-10"}], request: {amount: 9999}, program: {remainingBudget: 1000000}}, {amount: 4900, status: "awarded", score: 20}], + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake", ownership: ["veteran"]}, request: {amount: 20000}, program: {remainingBudget: 4250}}, {amount: 4200, status: "awarded", score: 60}], + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake", ownership: ["veteran"]}, request: {amount: 20000}, program: {remainingBudget: 0}}, {amount: 0, status: "not funded", score: 60}], + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake", ownership: ["veteran"]}, priorGrants: [{amount: 30000, date: "2023-01-01"}, {amount: 15000, date: "2024-06-30"}], request: {amount: 20000}, program: {remainingBudget: 1000000}}, {amount: 5000, status: "awarded", score: 55}], + // The three-year window: grants older than three years before the evaluation time drop out. + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake", ownership: ["veteran"]}, priorGrants: [{amount: 60000, date: "2022-03-19"}], request: {amount: 20000}, program: {remainingBudget: 1000000}}, {amount: 20000, status: "awarded", score: 60}], + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake", ownership: ["veteran"]}, priorGrants: [{amount: 30000, date: "2023-01-01"}, {amount: 20000, date: "2025-01-15"}], request: {amount: 20000}, program: {remainingBudget: 1000000}}, {status: "ineligible", reason: "lifetime cap reached"}], + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake"}, priorGrants: [{amount: 60000}], request: {amount: 20000}, program: {remainingBudget: 1000000}}, {amount: 20000, status: "awarded", score: 45}], + // Ordered exclusions. + [{business: {employees: 51, revenue: 300000, yearsOperating: 4}, request: {amount: 20000}, program: {remainingBudget: 1000000}}, {status: "ineligible", reason: "not a small business"}], + [{business: {employees: 5, revenue: 5000001, yearsOperating: 0.5}, request: {amount: 20000}, program: {remainingBudget: 1000000}}, {status: "ineligible", reason: "not a small business"}], + [{business: {employees: 50, revenue: 5000000, yearsOperating: 0.5}, request: {amount: 20000}, program: {remainingBudget: 1000000}}, {status: "ineligible", reason: "operating less than a year"}], + [{business: {employees: 50, revenue: 5000000, yearsOperating: 1, county: "lake", ownership: ["Veteran"]}, request: {amount: 20000}, program: {remainingBudget: 1000000}}, {amount: 0, status: "not funded", score: 5}], + // No headcount: the size exclusion and the headcount points are skipped. + [{business: {revenue: 300000, yearsOperating: 4, county: "Lake", ownership: ["veteran"]}, request: {amount: 20000}, program: {remainingBudget: 1000000}}, {amount: 20000, status: "awarded", score: 50}], + // No requested amount or no budget figure fails the award. + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake"}, program: {remainingBudget: 1000000}}, "!error"], + [{business: {employees: 8, revenue: 300000, yearsOperating: 4, county: "Lake"}, request: {amount: 20000}}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/63-realistic-large-graphs.json5 b/core/engine/tests/spec/graph/63-realistic-large-graphs.json5 new file mode 100644 index 00000000..7c363f89 --- /dev/null +++ b/core/engine/tests/spec/graph/63-realistic-large-graphs.json5 @@ -0,0 +1,681 @@ +// Large realistic decisions (20 to 40 nodes counting sub-decisions) that mix every node kind in +// one graph: loops over expressions, tables and sub-decisions, nested sub-decisions, function +// nodes in the middle of the flow, first-hit and collect switches, fan-outs from one switch +// branch into parallel nodes that join again, custom nodes (config, render and fail), `$nodes` +// reads and pass-through chains. Evaluation time is fixed at Thursday 2025-03-20T10:15:30Z. Each +// suite walks the main paths, the knock-out branches, boundaries, missing data and bad types. + +// --------------------------------------------------------------------------------------------- +// Mortgage origination: borrower aggregates, a per-borrower sub-decision in loop mode with +// pass-through, a knock-out switch whose two branches share a custom render letter, a fan-out of +// pricing, mortgage insurance and escrow that joins in an amortization function, an underwriting +// table with first-hit `decision` and collected `conditions[]`, and a collect switch whose +// branches build the result object that a summary node reads. +{ + name: "mortgage origination: knock-outs, pricing fan-out, amortization and underwriting", + decisions: { + borrower: { + nodes: [ + {table: "check", inputs: [null], outputs: ["ok", "reason"], rules: [ + ["age < 18", "false", "name + ': under 18'"], + ["not (residency in ['citizen', 'permanent', 'visa'])", "false", "name + ': residency not eligible'"], + ["score < 620", "false", "name + ': credit score below 620'"], + ["", "true", "'ok'"], + ]}, + ], + }, + }, + graph: { + nodes: [ + {input: "application"}, + {expression: "normalize", passThrough: true, fields: { + "app.income": "sum(map(borrowers, #.income))", + "app.debts": "sum(map(borrowers, #.monthlyDebt ?? 0))", + "app.minScore": "min(map(borrowers, #.score))", + "app.ltv": "round(loan.amount / property.value * 100, 2)", + }}, + {decision: "borrowerCheck", key: "borrower", executionMode: "loop", passThrough: true, inputField: "borrowers", outputPath: "borrowerResults"}, + {switch: "knockout", when: ["some(borrowerResults, not #.ok)", "app.ltv > 97", ""]}, + {expression: "koBorrower", fields: {decision: "'declined'", reason: "filter(borrowerResults, not #.ok)[0].reason"}}, + {expression: "koLtv", fields: {decision: "'declined'", reason: "'LTV ' + string(app.ltv) + '% above 97%'"}}, + {custom: "koLetter", kind: "render", config: {decision: "{{ decision }}", letter: "Your application was declined: {{ reason }}"}}, + {table: "pricing", passThrough: true, inputs: ["app.minScore", "app.ltv"], outputs: ["rate"], rules: [ + [">= 760", "<= 80", "6.25"], + [">= 760", "", "6.5"], + ["[700..760)", "<= 80", "6.75"], + ["[700..760)", "", "7"], + ["[620..700)", "", "7.75"], + ]}, + {table: "pmi", inputs: ["app.ltv"], outputs: ["pmiRate"], rules: [ + ["<= 80", "0"], + ["(80..90]", "0.5"], + ["(90..95]", "0.75"], + ["", "1"], + ]}, + {expression: "escrow", fields: {taxIns: "round((property.taxAnnual + property.insuranceAnnual) / 12, 2)"}}, + {function: "amortize", source: """ +export const handler = async (input) => { + const r = input.rate / 100 / 12; + const n = input.loan.termYears * 12; + const p = input.loan.amount; + const pi = r === 0 ? p / n : (p * r) / (1 - Math.pow(1 + r, -n)); + const pmiMonthly = Math.round((p * input.pmiRate) / 100 / 12 * 100) / 100; + const housing = Math.round((pi + input.taxIns + pmiMonthly) * 100) / 100; + const monthlyIncome = input.app.income / 12; + return { + rate: input.rate, + principalInterest: Math.round(pi * 100) / 100, + pmiMonthly, + housing, + frontDti: Math.round((housing / monthlyIncome) * 1000) / 10, + backDti: Math.round(((housing + input.app.debts) / monthlyIncome) * 1000) / 10, + }; +}; +"""}, + {table: "underwriting", passThrough: true, inputs: [null], outputs: ["decision", "conditions[]"], rules: [ + ["backDti > 50", "'declined'", "'DTI above 50%'"], + ["backDti > 43", "'refer'", "'DTI above 43%: manual review'"], + ["frontDti > 31", "'approve'", "'housing ratio above 31%: verify reserves'"], + ["pmiMonthly > 0", "'approve'", "'mortgage insurance required'"], + ["", "'approve'", ""], + ]}, + {switch: "outcome", hit: "collect", when: [ + "decision == 'approve'", + "decision == 'refer'", + "decision == 'declined'", + "len(conditions) > 0", + "", + ]}, + {expression: "approved", fields: {"result.decision": "'approved'", "result.rate": "rate", "result.payment": "housing"}}, + {expression: "referred", fields: {"result.decision": "'referred'", "result.payment": "housing"}}, + {expression: "declined", fields: {"result.decision": "'declined'"}}, + {expression: "withConditions", fields: {"result.conditions": "conditions"}}, + {expression: "audit", fields: {"audit.frontDti": "frontDti", "audit.backDti": "backDti"}}, + {expression: "summary", fields: { + decision: "result.decision", + rate: "result.rate", + payment: "result.payment", + conditions: "result.conditions ?? []", + dti: "audit", + }}, + {output: "offer"}, + ], + edges: [ + "application -> normalize -> borrowerCheck -> knockout", + "knockout:0 -> koBorrower -> koLetter", + "knockout:1 -> koLtv -> koLetter", + "koLetter -> offer", + "knockout:2 -> pricing -> amortize", + "knockout:2 -> pmi -> amortize", + "knockout:2 -> escrow -> amortize", + "amortize -> underwriting -> outcome", + "outcome:0 -> approved -> summary", + "outcome:1 -> referred -> summary", + "outcome:2 -> declined -> summary", + "outcome:3 -> withConditions -> summary", + "outcome:4 -> audit -> summary", + "summary -> offer", + ], + }, + cases: [ + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 780, income: 120000, monthlyDebt: 500}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "approved", rate: 6.25, payment: 3062.87, conditions: [], dti: {frontDti: 30.6, backDti: 35.6}}], + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 780, income: 120000, monthlyDebt: 500}], loan: {amount: 450000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "approved", rate: 6.5, payment: 3631.81, conditions: ["housing ratio above 31%: verify reserves", "mortgage insurance required"], dti: {frontDti: 36.3, backDti: 41.3}}], + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 780, income: 120000, monthlyDebt: 500}, {name: "ben", age: 41, residency: "permanent", score: 650, income: 30000, monthlyDebt: 400}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "approved", rate: 7.75, payment: 3465.65, conditions: [], dti: {frontDti: 27.7, backDti: 34.9}}], + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 780, income: 95000, monthlyDebt: 500}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "referred", payment: 3062.87, conditions: ["DTI above 43%: manual review", "housing ratio above 31%: verify reserves"], dti: {frontDti: 38.7, backDti: 45}}], + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 780, income: 60000, monthlyDebt: 500}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "declined", conditions: ["DTI above 50%", "DTI above 43%: manual review", "housing ratio above 31%: verify reserves"], dti: {frontDti: 61.3, backDti: 71.3}}], + [{borrowers: [{name: "ana", age: 35, residency: "visa", score: 790, income: 140000}], loan: {amount: 475000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "approved", rate: 6.5, payment: 3899.2, conditions: ["housing ratio above 31%: verify reserves", "mortgage insurance required"], dti: {frontDti: 33.4, backDti: 33.4}}], + [{borrowers: [{name: "cy", age: 50, residency: "citizen", score: 720, income: 90000, monthlyDebt: 1200}], loan: {amount: 300000, termYears: 15}, property: {value: 400000, taxAnnual: 4200, insuranceAnnual: 1200}}, {decision: "declined", conditions: ["DTI above 50%", "DTI above 43%: manual review", "housing ratio above 31%: verify reserves"], dti: {frontDti: 41.4, backDti: 57.4}}], + // LTV exactly 97 passes the knock-out and lands in the top insurance band. + [{borrowers: [{name: "dee", age: 29, residency: "citizen", score: 710, income: 130000, monthlyDebt: 300}], loan: {amount: 485000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "approved", rate: 7, payment: 4230.89, conditions: ["housing ratio above 31%: verify reserves", "mortgage insurance required"], dti: {frontDti: 39.1, backDti: 41.8}}], + // Knock-outs share the rendered letter; `string` keeps the decimal scale of the rounded LTV. + [{borrowers: [{name: "dee", age: 29, residency: "citizen", score: 710, income: 130000}], loan: {amount: 486000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "declined", letter: "Your application was declined: LTV 97.20% above 97%"}], + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 780, income: 120000}, {name: "cy", age: 17, residency: "citizen", score: 700, income: 0}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "declined", letter: "Your application was declined: cy: under 18"}], + [{borrowers: [{name: "ana", age: 35, residency: "tourist", score: 780, income: 120000}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "declined", letter: "Your application was declined: ana: residency not eligible"}], + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 600, income: 120000}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "declined", letter: "Your application was declined: ana: credit score below 620"}], + [{borrowers: [{name: "ana", age: 16, residency: "tourist", score: 500, income: 1}, {name: "bo", age: 15, residency: "citizen", score: 800, income: 1}], loan: {amount: 400000, termYears: 30}, property: {value: 300000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "declined", letter: "Your application was declined: ana: under 18"}], + // A borrower without a residency: `null in [...]` is false, so the residency rule fires. + [{borrowers: [{name: "ana", age: 35, score: 780, income: 120000}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, {decision: "declined", letter: "Your application was declined: ana: residency not eligible"}], + // A zero property value divides to null and fails the rounding; a string income fails the sum. + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 780, income: 120000}], loan: {amount: 400000, termYears: 30}, property: {value: 0, taxAnnual: 6000, insuranceAnnual: 1200}}, "!error"], + [{borrowers: [{name: "ana", age: 35, residency: "citizen", score: 780, income: "120000"}], loan: {amount: 400000, termYears: 30}, property: {value: 500000, taxAnnual: 6000, insuranceAnnual: 1200}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Order fulfillment: a custom config node supplies the warehouse network, a loop expression +// prices the lines, a function allocates each line to a warehouse (same region first) or +// backorders it, a stock gate holds or cancels, the proceed branch fans out to shipping method, +// shipping cost and express surcharge tables that join in the totals, a collect switch adds the +// notes, and a custom render node writes the confirmation message that joins the summary. +{ + name: "order fulfillment: config network, allocation function, shipping fan-out and notes", + graph: { + nodes: [ + {input: "order"}, + {custom: "settings", kind: "config", config: { + warehouses: [ + {id: "east", region: "east", stock: {A: 10, B: 0, C: 5}}, + {id: "west", region: "west", stock: {A: 2, B: 8, C: 0}}, + ], + freeShippingOver: 50, + expressSurcharge: 15, + }}, + {expression: "lines", executionMode: "loop", inputField: "items", outputPath: "lines", fields: { + sku: "sku", + qty: "qty", + lineTotal: "round(qty * price, 2)", + }}, + {function: "allocate", source: """ +export const handler = async (input) => { + const warehouses = input.warehouses ?? []; + const region = input.region; + const ordered = [...warehouses].sort((a, b) => (a.region === region ? 0 : 1) - (b.region === region ? 0 : 1)); + const stock = Object.fromEntries(warehouses.map((w) => [w.id, { ...w.stock }])); + const allocations = []; + const backorders = []; + for (const line of input.lines ?? []) { + const w = ordered.find((x) => (stock[x.id][line.sku] ?? 0) >= line.qty); + if (w) { + stock[w.id][line.sku] -= line.qty; + allocations.push({ sku: line.sku, qty: line.qty, warehouse: w.id }); + } else { + backorders.push({ sku: line.sku, qty: line.qty }); + } + } + const allocated = new Set(allocations.map((a) => a.sku)); + const subtotal = (input.lines ?? []).filter((l) => allocated.has(l.sku)).reduce((s, l) => s + l.lineTotal, 0); + return { + allocations, + backorders, + warehousesUsed: [...new Set(allocations.map((a) => a.warehouse))], + subtotal: Math.round(subtotal * 100) / 100, + speed: input.speed ?? 'standard', + allowPartial: input.allowPartial === true, + settings: { freeShippingOver: input.freeShippingOver, expressSurcharge: input.expressSurcharge }, + }; +}; +"""}, + {switch: "stockGate", when: ["len(backorders) > 0 and not allowPartial", "len(allocations) == 0", ""]}, + {expression: "hold", fields: {status: "'on hold'", backordered: "map(backorders, #.sku)"}}, + {expression: "cancelled", fields: {status: "'cancelled'", reason: "'nothing in stock'"}}, + {table: "shippingMethod", passThrough: true, inputs: ["speed", "len(warehousesUsed)"], outputs: ["ship.method", "ship.days"], rules: [ + ["'express'", "1", "'air'", "1"], + ["'express'", "", "'air'", "2"], + ["", "1", "'ground'", "4"], + ["", "", "'ground'", "6"], + ]}, + {table: "shippingCost", inputs: ["subtotal"], outputs: ["ship.cost"], rules: [ + [">= settings.freeShippingOver", "0"], + ["", "round(5.99 * len(warehousesUsed), 2)"], + ]}, + {expression: "surcharge", fields: {"ship.express": "speed == 'express' ? settings.expressSurcharge : 0"}}, + {expression: "totals", passThrough: true, fields: { + shipping: "ship.cost + ship.express", + total: "round(subtotal + $.shipping, 2)", + }}, + {switch: "notes", hit: "collect", when: ["len(warehousesUsed) > 1", "len(backorders) > 0", "total >= 500", ""]}, + {expression: "splitNote", fields: {"notes.split": "true"}}, + {expression: "backorderNote", fields: {"notes.backordered": "map(backorders, #.sku)"}}, + {expression: "reviewNote", fields: {"notes.fraudReview": "true"}}, + {expression: "baseNote", fields: {status: "'confirmed'", total: "total", shipping: "shipping", method: "ship.method", days: "ship.days"}}, + {expression: "summary", fields: {status: "status", total: "total", shipping: "shipping", method: "method", days: "days", notes: "notes ?? {}"}}, + {custom: "confirmation", kind: "render", config: {message: "Order {{ status }}: {{ total }} via {{ method }}"}}, + {expression: "envelope", passThrough: true, fields: {message: "message"}}, + {output: "fulfillment"}, + ], + edges: [ + "order -> settings -> allocate", + "order -> lines -> allocate", + "order -> allocate -> stockGate", + "stockGate:0 -> hold -> fulfillment", + "stockGate:1 -> cancelled -> fulfillment", + "stockGate:2 -> shippingMethod -> totals", + "stockGate:2 -> shippingCost -> totals", + "stockGate:2 -> surcharge -> totals", + "totals -> notes", + "notes:0 -> splitNote -> summary", + "notes:1 -> backorderNote -> summary", + "notes:2 -> reviewNote -> summary", + "notes:3 -> baseNote -> summary", + "summary -> envelope", + "summary -> confirmation -> envelope", + "envelope -> fulfillment", + ], + }, + cases: [ + [{region: "east", items: [{sku: "A", qty: 2, price: 10}]}, {status: "confirmed", total: 25.99, shipping: 5.99, method: "ground", days: 4, notes: {}, message: "Order confirmed: 25.99 via ground"}], + [{region: "east", items: [{sku: "A", qty: 2, price: 10}, {sku: "B", qty: 1, price: 40}]}, {status: "confirmed", total: 60, shipping: 0, method: "ground", days: 6, notes: {split: true}, message: "Order confirmed: 60 via ground"}], + [{region: "east", speed: "express", items: [{sku: "A", qty: 2, price: 10}]}, {status: "confirmed", total: 40.99, shipping: 20.99, method: "air", days: 1, notes: {}, message: "Order confirmed: 40.99 via air"}], + [{region: "east", speed: "express", items: [{sku: "A", qty: 2, price: 10}, {sku: "B", qty: 1, price: 40}]}, {status: "confirmed", total: 75, shipping: 15, method: "air", days: 2, notes: {split: true}, message: "Order confirmed: 75 via air"}], + [{region: "west", items: [{sku: "A", qty: 2, price: 10}, {sku: "B", qty: 1, price: 40}]}, {status: "confirmed", total: 60, shipping: 0, method: "ground", days: 4, notes: {}, message: "Order confirmed: 60 via ground"}], + [{region: "west", items: [{sku: "A", qty: 3, price: 10}]}, {status: "confirmed", total: 35.99, shipping: 5.99, method: "ground", days: 4, notes: {}, message: "Order confirmed: 35.99 via ground"}], + [{region: "east", items: [{sku: "A", qty: 3, price: 19.99}, {sku: "B", qty: 1, price: 12.5}]}, {status: "confirmed", total: 72.47, shipping: 0, method: "ground", days: 6, notes: {split: true}, message: "Order confirmed: 72.47 via ground"}], + [{region: "east", items: [{sku: "A", qty: 2, price: 24.99}]}, {status: "confirmed", total: 55.97, shipping: 5.99, method: "ground", days: 4, notes: {}, message: "Order confirmed: 55.97 via ground"}], + [{region: "east", items: [{sku: "A", qty: 2, price: 25}]}, {status: "confirmed", total: 50, shipping: 0, method: "ground", days: 4, notes: {}, message: "Order confirmed: 50 via ground"}], + [{region: "east", items: [{sku: "A", qty: 10, price: 60}]}, {status: "confirmed", total: 600, shipping: 0, method: "ground", days: 4, notes: {fraudReview: true}, message: "Order confirmed: 600 via ground"}], + // Without a region no warehouse is preferred and the network order decides. + [{items: [{sku: "A", qty: 1, price: 10}]}, {status: "confirmed", total: 15.99, shipping: 5.99, method: "ground", days: 4, notes: {}, message: "Order confirmed: 15.99 via ground"}], + // Stock gates: hold without partial shipment, ship the rest with it, cancel when nothing ships. + [{region: "east", items: [{sku: "C", qty: 6, price: 10}]}, {status: "on hold", backordered: ["C"]}], + [{region: "east", items: [{sku: "A", qty: 8, price: 10}, {sku: "A", qty: 4, price: 10}]}, {status: "on hold", backordered: ["A"]}], + [{region: "east", allowPartial: true, items: [{sku: "C", qty: 6, price: 10}, {sku: "A", qty: 1, price: 10}]}, {status: "confirmed", total: 15.99, shipping: 5.99, method: "ground", days: 4, notes: {backordered: ["C"]}, message: "Order confirmed: 15.99 via ground"}], + [{region: "east", allowPartial: true, items: [{sku: "C", qty: 6, price: 10}]}, {status: "cancelled", reason: "nothing in stock"}], + [{region: "east", items: []}, {status: "cancelled", reason: "nothing in stock"}], + [{region: "east", items: [{sku: "Z", qty: 1, price: 10}]}, {status: "on hold", backordered: ["Z"]}], + // A line without a price fails the pricing loop. + [{region: "east", items: [{sku: "A", qty: 1}]}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Transaction monitoring: sanctioned customers are refused by a custom fail node; otherwise a +// per-transaction sub-decision (a switch on the type into cash and wire tables) scores each +// transaction in loop mode, an aggregate joins the scores with the request, a function measures +// counterparty and daily velocity, a collect table under `patterns` adds pattern points, and the +// risk band drives a collect switch of filings and actions that meet at a summary. +{ + name: "transaction monitoring: sanctions fail node, per-transaction scoring and filings", + decisions: { + txScore: { + nodes: [ + {input: "tx"}, + {switch: "byType", when: ["type == 'cash'", "type == 'wire'", ""]}, + {table: "cash", passThrough: true, inputs: ["amount"], outputs: ["points", "flag"], rules: [ + [">= 10000", "50", "'ctr threshold'"], + ["[9000..10000)", "30", "'near threshold'"], + ["", "0", "null"], + ]}, + {table: "wire", passThrough: true, inputs: ["country"], outputs: ["points", "flag"], rules: [ + ["'IR', 'KP', 'SY'", "100", "'prohibited jurisdiction'"], + ["'PA', 'KY', 'VG'", "25", "'offshore jurisdiction'"], + ["", "5", "null"], + ]}, + {expression: "other", passThrough: true, fields: {points: "0"}}, + {expression: "result", fields: {id: "id", points: "points", flag: "flag"}}, + {output: "scored"}, + ], + edges: [ + "tx -> byType", + "byType:0 -> cash -> result", + "byType:1 -> wire -> result", + "byType:2 -> other -> result", + "result -> scored", + ], + }, + }, + graph: { + nodes: [ + {input: "batch"}, + {switch: "screen", when: ["customer.sanctioned == true", ""]}, + {custom: "blocked", kind: "fail", config: {message: "sanctioned party: batch blocked"}}, + {table: "countryRisk", passThrough: true, inputs: ["customer.country"], outputs: ["custRisk.country"], rules: [ + ["'IR', 'KP', 'SY'", "'prohibited'"], + ["'PA', 'KY', 'VG'", "'high'"], + ["", "'standard'"], + ]}, + {decision: "scoreTx", key: "txScore", executionMode: "loop", inputField: "transactions", outputPath: "scored"}, + {expression: "aggregate", passThrough: true, fields: { + totalCash: "sum(map(filter(transactions, #.type == 'cash'), #.amount))", + nearThreshold: "count(scored, #.flag == 'near threshold')", + txPoints: "sum(map(scored, #.points))", + flags: "filter(map(scored, #.flag), # != null)", + ctrRequired: "some(scored, #.flag == 'ctr threshold') or $.totalCash > 10000", + }}, + {function: "velocity", source: """ +export const handler = async (input) => { + const txs = input.transactions ?? []; + const byCounterparty = {}; + const byDay = {}; + for (const t of txs) { + byCounterparty[t.counterparty] = (byCounterparty[t.counterparty] ?? 0) + t.amount; + const day = String(t.date).slice(0, 10); + byDay[day] = (byDay[day] ?? 0) + 1; + } + const top = Object.entries(byCounterparty).sort((a, b) => b[1] - a[1])[0]; + return { + counterparties: Object.keys(byCounterparty).length, + topCounterparty: top ? top[0] : null, + maxDailyCount: Math.max(0, ...Object.values(byDay)), + }; +}; +"""}, + {table: "patterns", hit: "collect", passThrough: true, outputPath: "patterns", inputs: [null], outputs: ["rule", "points"], rules: [ + ["nearThreshold >= 2", "'structuring'", "40"], + ["maxDailyCount >= 5", "'high velocity'", "20"], + ["custRisk.country == 'prohibited'", "'prohibited residence'", "100"], + ["custRisk.country == 'high'", "'offshore residence'", "15"], + ["customer.risk == 'high'", "'high risk customer'", "20"], + ]}, + {expression: "risk", passThrough: true, fields: {score: "txPoints + sum(map(patterns, #.points))"}}, + {table: "band", passThrough: true, inputs: ["score"], outputs: ["level"], rules: [ + [">= 100", "'critical'"], + ["[50..100)", "'high'"], + ["[20..50)", "'medium'"], + ["", "'low'"], + ]}, + {switch: "actions", hit: "collect", when: [ + "ctrRequired", + "level in ['critical', 'high']", + "level == 'critical'", + "level == 'medium' or len(patterns) > 0", + "", + ]}, + {expression: "ctr", fields: {"filings.ctr": "true"}}, + {expression: "sar", fields: {"filings.sar": "true"}}, + {expression: "freeze", fields: {"actions.freeze": "true"}}, + {expression: "review", fields: {"actions.review": "true"}}, + {expression: "base", fields: {level: "level", score: "score", flags: "flags", patterns: "map(patterns, #.rule)", top: "topCounterparty"}}, + {expression: "summary", fields: { + level: "level", + score: "score", + flags: "flags", + patterns: "patterns", + top: "top", + filings: "filings ?? {}", + actions: "actions ?? {}", + }}, + {output: "report"}, + ], + edges: [ + "batch -> screen", + "screen:0 -> blocked -> report", + "screen:1 -> countryRisk -> scoreTx -> aggregate", + "countryRisk -> aggregate -> patterns", + "countryRisk -> velocity -> patterns", + "patterns -> risk -> band -> actions", + "actions:0 -> ctr -> summary", + "actions:1 -> sar -> summary", + "actions:2 -> freeze -> summary", + "actions:3 -> review -> summary", + "actions:4 -> base -> summary", + "summary -> report", + ], + }, + cases: [ + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "cash", amount: 500, counterparty: "shop", date: "2025-03-01"}]}, {level: "low", score: 0, flags: [], patterns: [], top: "shop", filings: {}, actions: {}}], + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "cash", amount: 9500, counterparty: "bank", date: "2025-03-01"}, {id: "t2", type: "cash", amount: 9800, counterparty: "bank", date: "2025-03-02"}]}, {level: "critical", score: 100, flags: ["near threshold", "near threshold"], patterns: ["structuring"], top: "bank", filings: {ctr: true, sar: true}, actions: {freeze: true, review: true}}], + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "cash", amount: 10000, counterparty: "bank", date: "2025-03-01"}]}, {level: "high", score: 50, flags: ["ctr threshold"], patterns: [], top: "bank", filings: {ctr: true, sar: true}, actions: {}}], + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "cash", amount: 9000, counterparty: "bank", date: "2025-03-01"}]}, {level: "medium", score: 30, flags: ["near threshold"], patterns: [], top: "bank", filings: {}, actions: {review: true}}], + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "cash", amount: 4000, counterparty: "a", date: "2025-03-01"}, {id: "t2", type: "cash", amount: 4000, counterparty: "b", date: "2025-03-02"}, {id: "t3", type: "cash", amount: 4500, counterparty: "b", date: "2025-03-03"}]}, {level: "low", score: 0, flags: [], patterns: [], top: "b", filings: {ctr: true}, actions: {}}], + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "wire", amount: 3000, country: "KY", counterparty: "fund", date: "2025-03-01"}]}, {level: "medium", score: 25, flags: ["offshore jurisdiction"], patterns: [], top: "fund", filings: {}, actions: {review: true}}], + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "wire", amount: 1000, country: "IR", counterparty: "x", date: "2025-03-01"}]}, {level: "critical", score: 100, flags: ["prohibited jurisdiction"], patterns: [], top: "x", filings: {sar: true}, actions: {freeze: true}}], + [{customer: {risk: "low", country: "PA"}, transactions: [{id: "t1", type: "card", amount: 100, counterparty: "cafe", date: "2025-03-01"}]}, {level: "low", score: 15, flags: [], patterns: ["offshore residence"], top: "cafe", filings: {}, actions: {review: true}}], + [{customer: {risk: "high", country: "US"}, transactions: [{id: "t1", type: "wire", amount: 1000, country: "US", counterparty: "llc", date: "2025-03-01"}]}, {level: "medium", score: 25, flags: [], patterns: ["high risk customer"], top: "llc", filings: {}, actions: {review: true}}], + [{customer: {risk: "low", country: "IR"}, transactions: [{id: "t1", type: "card", amount: 20, counterparty: "kiosk", date: "2025-03-01"}]}, {level: "critical", score: 100, flags: [], patterns: ["prohibited residence"], top: "kiosk", filings: {sar: true}, actions: {freeze: true, review: true}}], + // Velocity: five transactions on one day add the pattern, four do not; the biggest + // counterparty by total amount is reported. + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "card", amount: 10, counterparty: "a", date: "2025-03-05T08:00:00Z"}, {id: "t2", type: "card", amount: 70, counterparty: "b", date: "2025-03-05T09:00:00Z"}, {id: "t3", type: "card", amount: 10, counterparty: "a", date: "2025-03-05T10:00:00Z"}, {id: "t4", type: "card", amount: 10, counterparty: "a", date: "2025-03-05T11:00:00Z"}, {id: "t5", type: "card", amount: 50, counterparty: "a", date: "2025-03-05T12:00:00Z"}]}, {level: "medium", score: 20, flags: [], patterns: ["high velocity"], top: "a", filings: {}, actions: {review: true}}], + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "card", amount: 10, counterparty: "a", date: "2025-03-05T08:00:00Z"}, {id: "t2", type: "card", amount: 70, counterparty: "b", date: "2025-03-05T09:00:00Z"}, {id: "t3", type: "card", amount: 10, counterparty: "a", date: "2025-03-05T10:00:00Z"}, {id: "t4", type: "card", amount: 10, counterparty: "a", date: "2025-03-06T11:00:00Z"}]}, {level: "low", score: 0, flags: [], patterns: [], top: "b", filings: {}, actions: {}}], + // An empty batch has no top counterparty (null, dropped from the summary). + [{customer: {risk: "low", country: "US"}, transactions: []}, {level: "low", score: 0, flags: [], patterns: [], filings: {}, actions: {}}], + // A transaction without a type is scored by the default branch. + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", amount: 25000, counterparty: "x", date: "2025-03-01"}]}, {level: "low", score: 0, flags: [], patterns: [], top: "x", filings: {}, actions: {}}], + // The sanctions gate fails the whole decision through the custom node. + [{customer: {risk: "low", country: "US", sanctioned: true}, transactions: [{id: "t1", type: "cash", amount: 500, counterparty: "shop", date: "2025-03-01"}]}, "!error: sanctioned party: batch blocked"], + [{customer: {risk: "low", country: "US", sanctioned: true}, transactions: []}, "!error: sanctioned party: batch blocked"], + // A string cash amount passes the scoring tables (their cells fail) but not the cash total. + [{customer: {risk: "low", country: "US"}, transactions: [{id: "t1", type: "cash", amount: "9500", counterparty: "bank", date: "2025-03-01"}]}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Flight disruption: route facts, a first-hit eligibility switch whose four branches all write +// `comp.*` and join again, per-passenger rows priced by a sub-decision in loop mode that itself +// calls a care sub-decision (a collect switch of meal, hotel and assistance entitlements), and a +// rebooking function that orders passengers by assistance, cabin and name; the summary joins the +// loop, the function and the shared parent. +{ + name: "flight disruption: compensation, nested care sub-decision and rebooking priority", + decisions: { + care: { + nodes: [ + {input: "row"}, + {switch: "entitlements", hit: "collect", when: ["delayH >= 2", "delayH >= 5", "pax.needsAssistance == true", ""]}, + {expression: "meal", fields: {"care.meal": "band == 'long' ? 30 : 15"}}, + {expression: "hotel", fields: {"care.hotel": "true"}}, + {expression: "assist", fields: {"care.assistance": "true"}}, + {expression: "screened", fields: {"care.screened": "true"}}, + {expression: "careOut", fields: {care: "care"}}, + {output: "careResult"}, + ], + edges: [ + "row -> entitlements", + "entitlements:0 -> meal -> careOut", + "entitlements:1 -> hotel -> careOut", + "entitlements:2 -> assist -> careOut", + "entitlements:3 -> screened -> careOut", + "careOut -> careResult", + ], + }, + passenger: { + nodes: [ + {input: "row"}, + {table: "adjust", passThrough: true, inputs: ["pax.age"], outputs: ["amount"], rules: [ + ["< 2", "0"], + ["", "base"], + ]}, + {decision: "careCall", key: "care"}, + {expression: "out", fields: {name: "pax.name", amount: "amount", care: "care"}}, + {output: "paxResult"}, + ], + edges: ["row -> adjust -> out", "row -> careCall -> out", "out -> paxResult"], + }, + }, + graph: { + nodes: [ + {input: "disruption"}, + {expression: "facts", passThrough: true, fields: { + "f.euFlight": "flight.departureCountry in ['DE', 'FR', 'ES', 'IT', 'NL'] or flight.arrivalCountry in ['DE', 'FR', 'ES', 'IT', 'NL']", + "f.band": "flight.distanceKm <= 1500 ? 'short' : (flight.distanceKm <= 3500 ? 'medium' : 'long')", + "f.delayH": "flight.delayMin / 60", + }}, + {switch: "eligibility", when: [ + "not f.euFlight", + "flight.cause in ['weather', 'strike-atc', 'security']", + "flight.cancelled == true and noticeDays >= 14", + "", + ]}, + {expression: "notCovered", passThrough: true, fields: {"comp.base": "0", "comp.reason": "'outside EU scope'"}}, + {expression: "extraordinary", passThrough: true, fields: {"comp.base": "0", "comp.reason": "'extraordinary circumstances'"}}, + {expression: "noticed", passThrough: true, fields: {"comp.base": "0", "comp.reason": "'cancelled with notice'"}}, + {table: "compBase", passThrough: true, inputs: ["flight.cancelled", "f.band", "f.delayH"], outputs: ["comp.base"], rules: [ + ["true", "'short'", "", "250"], + ["true", "'medium'", "", "400"], + ["true", "'long'", "", "600"], + ["", "'short'", ">= 3", "250"], + ["", "'medium'", ">= 3", "400"], + ["", "'long'", ">= 4", "600"], + ["", "'long'", ">= 3", "300"], + ["", "", "", "0"], + ]}, + {expression: "compReason", passThrough: true, fields: {"comp.reason": "comp.base > 0 ? 'compensation due' : 'delay below threshold'"}}, + {expression: "perPax", passThrough: true, fields: {rows: "map(passengers ?? [], {pax: #, base: comp.base, delayH: f.delayH, band: f.band})"}}, + {decision: "paxComp", key: "passenger", executionMode: "loop", inputField: "rows", outputPath: "paxResults"}, + {function: "rebook", source: """ +export const handler = async (input) => { + const seats = input.seats ?? 0; + const priority = (p) => (p.needsAssistance === true ? 0 : 2) + (p.ticketClass === 'business' ? 0 : 1); + const pax = [...(input.passengers ?? [])].sort((a, b) => priority(a) - priority(b) || a.name.localeCompare(b.name)); + return { rebooked: pax.slice(0, seats).map((p) => p.name), waitlisted: pax.slice(seats).map((p) => p.name) }; +}; +"""}, + {expression: "summary", fields: { + reason: "comp.reason", + totalComp: "sum(map(paxResults, #.amount))", + passengers: "paxResults", + rebooked: "rebooked", + waitlisted: "waitlisted", + }}, + {output: "resolution"}, + ], + edges: [ + "disruption -> facts -> eligibility", + "eligibility:0 -> notCovered -> perPax", + "eligibility:1 -> extraordinary -> perPax", + "eligibility:2 -> noticed -> perPax", + "eligibility:3 -> compBase -> compReason -> perPax", + "perPax -> paxComp -> summary", + "perPax -> rebook -> summary", + "perPax -> summary -> resolution", + ], + }, + cases: [ + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 200, cause: "technical"}, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}, {name: "bob", ticketClass: "business", age: 45}]}, {reason: "compensation due", totalComp: 800, passengers: [{name: "ann", amount: 400, care: {meal: 15, screened: true}}, {name: "bob", amount: 400, care: {meal: 15, screened: true}}], rebooked: ["bob", "ann"], waitlisted: []}], + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 170, cause: "technical"}, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}, {name: "bob", ticketClass: "business", age: 45}]}, {reason: "delay below threshold", totalComp: 0, passengers: [{name: "ann", amount: 0, care: {meal: 15, screened: true}}, {name: "bob", amount: 0, care: {meal: 15, screened: true}}], rebooked: ["bob", "ann"], waitlisted: []}], + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 400, cause: "weather"}, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "extraordinary circumstances", totalComp: 0, passengers: [{name: "ann", amount: 0, care: {meal: 15, hotel: true, screened: true}}], rebooked: ["ann"], waitlisted: []}], + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 0, cancelled: true}, noticeDays: 20, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "cancelled with notice", totalComp: 0, passengers: [{name: "ann", amount: 0, care: {screened: true}}], rebooked: ["ann"], waitlisted: []}], + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 0, cancelled: true}, noticeDays: 14, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "cancelled with notice", totalComp: 0, passengers: [{name: "ann", amount: 0, care: {screened: true}}], rebooked: ["ann"], waitlisted: []}], + [{flight: {departureCountry: "FR", arrivalCountry: "IT", distanceKm: 1000, delayMin: 0, cancelled: true}, noticeDays: 13, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "compensation due", totalComp: 250, passengers: [{name: "ann", amount: 250, care: {screened: true}}], rebooked: ["ann"], waitlisted: []}], + [{flight: {departureCountry: "US", arrivalCountry: "CA", distanceKm: 800, delayMin: 300, cause: "technical"}, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "outside EU scope", totalComp: 0, passengers: [{name: "ann", amount: 0, care: {meal: 15, hotel: true, screened: true}}], rebooked: ["ann"], waitlisted: []}], + [{flight: {departureCountry: "US", arrivalCountry: "NL", distanceKm: 6000, delayMin: 210, cause: "crew"}, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "compensation due", totalComp: 300, passengers: [{name: "ann", amount: 300, care: {meal: 30, screened: true}}], rebooked: ["ann"], waitlisted: []}], + [{flight: {departureCountry: "US", arrivalCountry: "NL", distanceKm: 6000, delayMin: 240, cause: "crew"}, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "compensation due", totalComp: 600, passengers: [{name: "ann", amount: 600, care: {meal: 30, screened: true}}], rebooked: ["ann"], waitlisted: []}], + // Distance band edges: 1500 km is short, 3500 km medium. + [{flight: {departureCountry: "DE", arrivalCountry: "IT", distanceKm: 1500, delayMin: 180, cause: "technical"}, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "compensation due", totalComp: 250, passengers: [{name: "ann", amount: 250, care: {meal: 15, screened: true}}], rebooked: ["ann"], waitlisted: []}], + [{flight: {departureCountry: "DE", arrivalCountry: "IT", distanceKm: 3500, delayMin: 180, cause: "technical"}, seats: 5, passengers: [{name: "ann", ticketClass: "economy", age: 30}]}, {reason: "compensation due", totalComp: 400, passengers: [{name: "ann", amount: 400, care: {meal: 15, screened: true}}], rebooked: ["ann"], waitlisted: []}], + // Infants get no compensation; assistance comes first in rebooking, then business, then name. + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 200, cause: "technical"}, seats: 2, passengers: [{name: "ann", ticketClass: "economy", age: 30}, {name: "bob", ticketClass: "business", age: 45}, {name: "cat", ticketClass: "economy", age: 70, needsAssistance: true}, {name: "dot", ticketClass: "economy", age: 1}]}, {reason: "compensation due", totalComp: 1200, passengers: [{name: "ann", amount: 400, care: {meal: 15, screened: true}}, {name: "bob", amount: 400, care: {meal: 15, screened: true}}, {name: "cat", amount: 400, care: {meal: 15, assistance: true, screened: true}}, {name: "dot", amount: 0, care: {meal: 15, screened: true}}], rebooked: ["cat", "bob"], waitlisted: ["ann", "dot"]}], + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 0, cause: "technical"}, passengers: [{name: "bob", ticketClass: "economy"}, {name: "ann", ticketClass: "economy"}]}, {reason: "delay below threshold", totalComp: 0, passengers: [{name: "bob", amount: 0, care: {screened: true}}, {name: "ann", amount: 0, care: {screened: true}}], rebooked: [], waitlisted: ["ann", "bob"]}], + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 200, cause: "technical"}, seats: 5, passengers: []}, {reason: "compensation due", totalComp: 0, passengers: [], rebooked: [], waitlisted: []}], + // A missing delay fails the facts node; two nameless passengers in the same cabin make the + // rebooking comparator call a method on undefined. + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, cause: "technical"}, seats: 5, passengers: [{name: "ann"}]}, "!error"], + [{flight: {departureCountry: "DE", arrivalCountry: "ES", distanceKm: 1800, delayMin: 0, cause: "technical"}, seats: 5, passengers: [{ticketClass: "economy"}, {ticketClass: "economy"}]}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// SaaS month-end billing: the plan catalog fans out to prorated seats (seat-days from dated +// changes), collected API overage tiers and storage, joined with a loop table pricing add-ons; +// a function applies unexpired credits earliest-expiring first, a tax sub-decision runs under +// `tax`, the invoice reads the dunning state through `$nodes`, the four dunning branches meet in a +// custom echo node, and a custom render memo joins the final invoice. The period is March 2025 +// (30 days between the boundary dates). The memo template keeps each number's decimal scale, as +// `string` does, so values that went through `round(x, 2)` can render with trailing zeros. +{ + name: "saas billing: proration, overage tiers, credits function, tax sub-decision, dunning", + decisions: { + salesTax: { + nodes: [ + {table: "rate", passThrough: true, inputs: ["region", "taxExempt"], outputs: ["rate"], rules: [ + ["", "true", "0"], + ["'CA'", "", "0.0725"], + ["'NY'", "", "0.08875"], + ["'EU'", "", "0.2"], + ["", "", "0"], + ]}, + {expression: "amount", fields: {rate: "rate", amount: "round(taxable * rate, 2)"}}, + ], + }, + }, + graph: { + nodes: [ + {input: "account"}, + {table: "planCatalog", passThrough: true, inputs: ["plan"], outputs: ["price.seat", "included.apiCalls", "included.storageGb"], rules: [ + ["'starter'", "10", "100000", "10"], + ["'team'", "25", "1000000", "100"], + ["'enterprise'", "40", "10000000", "1000"], + ]}, + {expression: "seatsCalc", passThrough: true, fields: { + "calc.periodDays": "d(periodEnd).diff(d(periodStart), 'day')", + "calc.seatDays": "seats.start * $.calc.periodDays + sum(map(seats.changes ?? [], #.delta * d(periodEnd).diff(d(#.date), 'day')))", + "calc.seatCharge": "round($.calc.seatDays * price.seat / $.calc.periodDays, 2)", + }}, + {table: "apiTiers", hit: "collect", passThrough: true, outputPath: "apiTiers", inputs: ["usage.apiCalls - included.apiCalls"], outputs: ["calls", "rate"], rules: [ + ["> 0", "min([usage.apiCalls - included.apiCalls, 1000000])", "0.001"], + ["> 1000000", "usage.apiCalls - included.apiCalls - 1000000", "0.0005"], + ]}, + {expression: "storage", passThrough: true, fields: {"calc.storage": "max([0, ceil(usage.storageGb - included.storageGb)]) * 0.1"}}, + {table: "addonPrice", executionMode: "loop", inputField: "addons", outputPath: "addonLines", inputs: ["code"], outputs: ["code", "amount"], rules: [ + ["'sso'", "code", "(qty ?? 1) * 50"], + ["'audit'", "code", "100"], + ["", "code", "0"], + ]}, + {expression: "subtotal", passThrough: true, fields: { + "calc.usage": "round(sum(map(apiTiers, #.calls * #.rate)), 2)", + "calc.addons": "sum(map(addonLines, #.amount))", + "calc.subtotal": "calc.seatCharge + $.calc.usage + calc.storage + $.calc.addons", + }}, + {function: "applyCredits", source: """ +export const handler = async (input) => { + const end = input.periodEnd; + const usable = (input.credits ?? []) + .filter((c) => !c.expires || c.expires >= end) + .sort((a, b) => String(a.expires ?? '9999').localeCompare(String(b.expires ?? '9999'))); + let due = input.calc.subtotal; + let applied = 0; + for (const c of usable) { + const take = Math.min(c.amount, due); + applied += take; + due -= take; + } + return { + creditsApplied: Math.round(applied * 100) / 100, + taxable: Math.round(due * 100) / 100, + region: input.region, + taxExempt: input.taxExempt === true, + }; +}; +"""}, + {decision: "tax", key: "salesTax", outputPath: "tax"}, + {expression: "invoice", fields: { + seatCharge: "calc.seatCharge", + usage: "calc.usage", + storage: "calc.storage", + addons: "calc.addons", + credits: "creditsApplied", + tax: "tax.amount", + total: "round(taxable + tax.amount, 2)", + }}, + {switch: "dunning", when: ["$nodes.account.paymentFailures >= 3", "$nodes.account.paymentFailures >= 1", "total == 0", ""]}, + {expression: "suspend", passThrough: true, fields: {status: "'suspended'"}}, + {expression: "retry", passThrough: true, fields: {status: "'retry'"}}, + {expression: "nothingDue", passThrough: true, fields: {status: "'paid by credit'"}}, + {expression: "charge", passThrough: true, fields: {status: "'charged'"}}, + {custom: "statusJoin", kind: "echo"}, + {custom: "memo", kind: "render", config: {memo: "{{ status }}: {{ total }} ({{ seatCharge }} seats, {{ usage }} usage)"}}, + {expression: "final", passThrough: true, fields: {memo: "memo"}}, + {output: "bill"}, + ], + edges: [ + "account -> planCatalog -> seatsCalc -> subtotal", + "planCatalog -> apiTiers -> subtotal", + "planCatalog -> storage -> subtotal", + "account -> addonPrice -> subtotal", + "subtotal -> applyCredits -> tax -> invoice", + "subtotal -> invoice", + "applyCredits -> invoice -> dunning", + "dunning:0 -> suspend -> statusJoin", + "dunning:1 -> retry -> statusJoin", + "dunning:2 -> nothingDue -> statusJoin", + "dunning:3 -> charge -> statusJoin", + "statusJoin -> final", + "statusJoin -> memo -> final", + "final -> bill", + ], + }, + cases: [ + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 500000, storageGb: 50}, addons: [], region: "CA"}, {seatCharge: 250, usage: 0, storage: 0, addons: 0, credits: 0, tax: 18.13, total: 268.13, status: "charged", memo: "charged: 268.13 (250 seats, 0 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10, changes: [{date: "2025-03-16", delta: 5}]}, usage: {apiCalls: 500000, storageGb: 50}, addons: [], region: "EU"}, {seatCharge: 312.5, usage: 0, storage: 0, addons: 0, credits: 0, tax: 62.5, total: 375, status: "charged", memo: "charged: 375.00 (312.50 seats, 0 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10, changes: [{date: "2025-03-21", delta: -2}]}, usage: {apiCalls: 500000, storageGb: 50}, addons: [], region: "CA"}, {seatCharge: 233.33, usage: 0, storage: 0, addons: 0, credits: 0, tax: 16.92, total: 250.25, status: "charged", memo: "charged: 250.25 (233.33 seats, 0 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10, changes: [{date: "2025-03-16", delta: 5}, {date: "2025-03-21", delta: -2}]}, usage: {apiCalls: 500000, storageGb: 50}, addons: []}, {seatCharge: 295.83, usage: 0, storage: 0, addons: 0, credits: 0, tax: 0, total: 295.83, status: "charged", memo: "charged: 295.83 (295.83 seats, 0 usage)"}], + // API overage tiers: none at the allowance, one tier, both tiers. + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 4}, usage: {apiCalls: 1000000, storageGb: 50}, addons: []}, {seatCharge: 100, usage: 0, storage: 0, addons: 0, credits: 0, tax: 0, total: 100, status: "charged", memo: "charged: 100 (100 seats, 0 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 4}, usage: {apiCalls: 1500000, storageGb: 50}, addons: []}, {seatCharge: 100, usage: 500, storage: 0, addons: 0, credits: 0, tax: 0, total: 600, status: "charged", memo: "charged: 600 (100 seats, 500.00 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 4}, usage: {apiCalls: 2500000, storageGb: 100.5}, addons: []}, {seatCharge: 100, usage: 1250, storage: 0.1, addons: 0, credits: 0, tax: 0, total: 1350.1, status: "charged", memo: "charged: 1350.1 (100 seats, 1250.00 usage)"}], + [{plan: "starter", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 3}, usage: {apiCalls: 150000, storageGb: 12.2}, addons: [], region: "NY"}, {seatCharge: 30, usage: 50, storage: 0.3, addons: 0, credits: 0, tax: 7.13, total: 87.43, status: "charged", memo: "charged: 87.43 (30 seats, 50.00 usage)"}], + // Add-ons: SSO per quantity (one when missing), a flat audit fee, unknown codes free. + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 4}, usage: {apiCalls: 0, storageGb: 0}, addons: [{code: "sso", qty: 10}, {code: "audit"}, {code: "beta"}, {code: "sso"}]}, {seatCharge: 100, usage: 0, storage: 0, addons: 650, credits: 0, tax: 0, total: 750, status: "charged", memo: "charged: 750 (100 seats, 0 usage)"}], + // Credits: unexpired ones apply before tax, expired ones are ignored, a credit larger than the + // invoice leaves nothing due. + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 0, storageGb: 0}, addons: [], region: "CA", credits: [{amount: 100, expires: "2025-12-31"}]}, {seatCharge: 250, usage: 0, storage: 0, addons: 0, credits: 100, tax: 10.88, total: 160.88, status: "charged", memo: "charged: 160.88 (250 seats, 0 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 0, storageGb: 0}, addons: [], region: "CA", credits: [{amount: 100, expires: "2025-03-30"}]}, {seatCharge: 250, usage: 0, storage: 0, addons: 0, credits: 0, tax: 18.13, total: 268.13, status: "charged", memo: "charged: 268.13 (250 seats, 0 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 0, storageGb: 0}, addons: [], region: "CA", credits: [{amount: 200}, {amount: 100, expires: "2025-04-30"}]}, {seatCharge: 250, usage: 0, storage: 0, addons: 0, credits: 250, tax: 0, total: 0, status: "paid by credit", memo: "paid by credit: 0 (250 seats, 0 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 0, storageGb: 0}, addons: [], region: "EU", taxExempt: true}, {seatCharge: 250, usage: 0, storage: 0, addons: 0, credits: 0, tax: 0, total: 250, status: "charged", memo: "charged: 250 (250 seats, 0 usage)"}], + // Dunning reads the failure count from the request through `$nodes`, before the zero check. + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 0, storageGb: 0}, addons: [], paymentFailures: 1}, {seatCharge: 250, usage: 0, storage: 0, addons: 0, credits: 0, tax: 0, total: 250, status: "retry", memo: "retry: 250 (250 seats, 0 usage)"}], + [{plan: "team", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 0, storageGb: 0}, addons: [], paymentFailures: 3, credits: [{amount: 1000}]}, {seatCharge: 250, usage: 0, storage: 0, addons: 0, credits: 250, tax: 0, total: 0, status: "suspended", memo: "suspended: 0 (250 seats, 0 usage)"}], + // Unknown plans have no seat price; a missing period start makes the period length null. + [{plan: "free", periodStart: "2025-03-01", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 0, storageGb: 0}, addons: []}, "!error"], + [{plan: "team", periodEnd: "2025-03-31", seats: {start: 10}, usage: {apiCalls: 0, storageGb: 0}, addons: []}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/64-expression-optimizations.json5 b/core/engine/tests/spec/graph/64-expression-optimizations.json5 new file mode 100644 index 00000000..c801e7f7 --- /dev/null +++ b/core/engine/tests/spec/graph/64-expression-optimizations.json5 @@ -0,0 +1,1155 @@ +// Expression nodes under batch-oriented optimizations. Every suite here runs many rows that repeat a +// few distinct values, because the compiled engine folds literals, evaluates an expression once per +// distinct key, aliases pure path reads, rewrites `path ?? literal`, builds static object shapes and +// evaluates constant-argument builtins (and `d()`) once per batch. Each case states what the +// row-at-a-time semantics require, so a shortcut that leaks a value between rows, merges values that +// are equal but not identical, or shares a mutable result shows up as a mismatch. + +// --------------------------------------------------------------------------------------------- +// Literal folding: constant subexpressions produce the same value as evaluated per row, next to +// per-row parts of the same expression. +{ + name: "folded literals of every type beside a per-row value", + graph: {nodes: [{expression: "calc", fields: { + n: "1 + 2 * 3", + f: "0.1 + 0.2", + s: "'ab' + 'cd'", + b: "1 < 2 and 'a' != 'b'", + l: "[1, 2, 3][1]", + o: "({k: 1}).k", + len: "len('hello')", + mix: "x + (10 / 4)", + }}]}, + cases: [ + [{x: 1}, {n: 7, f: 0.3, s: "abcd", b: true, l: 2, o: 1, len: 5, mix: 3.5}], + [{x: 1}, {n: 7, f: 0.3, s: "abcd", b: true, l: 2, o: 1, len: 5, mix: 3.5}], + [{x: 2}, {n: 7, f: 0.3, s: "abcd", b: true, l: 2, o: 1, len: 5, mix: 4.5}], + [{x: 0.5}, {n: 7, f: 0.3, s: "abcd", b: true, l: 2, o: 1, len: 5, mix: 3}], + [{x: 1}, {n: 7, f: 0.3, s: "abcd", b: true, l: 2, o: 1, len: 5, mix: 3.5}], + [{}, "!error"], + [{x: -2.5}, {n: 7, f: 0.3, s: "abcd", b: true, l: 2, o: 1, len: 5, mix: 0}], + [{x: 2}, {n: 7, f: 0.3, s: "abcd", b: true, l: 2, o: 1, len: 5, mix: 4.5}], + [{x: "a"}, "!error"], + [{x: 1}, {n: 7, f: 0.3, s: "abcd", b: true, l: 2, o: 1, len: 5, mix: 3.5}], + ], +} + +{ + name: "folded literals keep their decimal scale", + graph: {nodes: [{expression: "calc", fields: { + a: "string(1.50)", + b: "string(1.50 + 0)", + c: "string(2.000 * 1)", + d: "string(x)", + e: "string(x + 0.00)", + }}]}, + cases: [ + [{x: 1}, {a: "1.50", b: "1.50", c: "2.000", d: "1", e: "1.00"}, "bug: adding a zero literal with scale drops its scale (expression spec: 0.00 + 1 prints '1')"], + [{x: 1.0}, {a: "1.50", b: "1.50", c: "2.000", d: "1.0", e: "1.00"}, "bug: adding a zero literal with scale drops its scale (expression spec: 0.00 + 1 prints '1')"], + [{x: 1.00}, {a: "1.50", b: "1.50", c: "2.000", d: "1.00", e: "1.00"}], + [{x: 1}, {a: "1.50", b: "1.50", c: "2.000", d: "1", e: "1.00"}, "bug: adding a zero literal with scale drops its scale (expression spec: 0.00 + 1 prints '1')"], + [{x: 1.000}, {a: "1.50", b: "1.50", c: "2.000", d: "1.000", e: "1.000"}], + [{x: 1.0}, {a: "1.50", b: "1.50", c: "2.000", d: "1.0", e: "1.00"}, "bug: adding a zero literal with scale drops its scale (expression spec: 0.00 + 1 prints '1')"], + [{x: 2.5}, {a: "1.50", b: "1.50", c: "2.000", d: "2.5", e: "2.50"}, "bug: adding a zero literal with scale drops its scale (expression spec: 0.00 + 1 prints '1')"], + [{x: 1}, {a: "1.50", b: "1.50", c: "2.000", d: "1", e: "1.00"}, "bug: adding a zero literal with scale drops its scale (expression spec: 0.00 + 1 prints '1')"], + ], +} + +{ + name: "a folded condition picks one ternary arm for every row", + graph: {nodes: [{expression: "calc", fields: { + always: "1 > 0 ? x : 'never'", + never: "1 > 2 ? x : 'fallback'", + guarded: "false and x > 0", + either: "true or x > 0", + }}]}, + cases: [ + [{x: 1}, {always: 1, never: "fallback", guarded: false, either: true}], + [{x: "s"}, {always: "s", never: "fallback", guarded: false, either: true}], + [{x: 1}, {always: 1, never: "fallback", guarded: false, either: true}], + [{}, {never: "fallback", guarded: false, either: true}], + [{x: null}, {never: "fallback", guarded: false, either: true}], + [{x: [1]}, {always: [1], never: "fallback", guarded: false, either: true}], + [{x: 1}, {always: 1, never: "fallback", guarded: false, either: true}], + [{x: true}, {always: true, never: "fallback", guarded: false, either: true}], + ], +} + +{ + name: "a constant error in an untaken arm does not fail any row", + graph: {nodes: [{expression: "calc", fields: {r: "x > 0 ? x : 'a' + 1"}}]}, + cases: [ + [{x: 1}, {r: 1}], + [{x: 2}, {r: 2}], + [{x: 1}, {r: 1}], + [{x: 0}, "!error"], + [{x: 1}, {r: 1}], + [{x: 5}, {r: 5}], + [{x: -1}, "!error"], + [{x: 1}, {r: 1}], + ], +} + +{ + name: "a fully constant node gives every row the same result", + graph: {nodes: [ + {expression: "consts", fields: {rate: "0.19", label: "'VAT ' + string(19) + '%'", tiers: "['a', 'b']", cfg: "{max: 100, on: true}"}}, + {expression: "use", fields: {rate: "rate", label: "label", first: "tiers[0]", max: "cfg.max", on: "cfg.on"}}, + ]}, + cases: [ + [{}, {rate: 0.19, label: "VAT 19%", first: "a", max: 100, on: true}], + [{rate: 1}, {rate: 0.19, label: "VAT 19%", first: "a", max: 100, on: true}], + [{}, {rate: 0.19, label: "VAT 19%", first: "a", max: 100, on: true}], + [{x: "y"}, {rate: 0.19, label: "VAT 19%", first: "a", max: 100, on: true}], + [{}, {rate: 0.19, label: "VAT 19%", first: "a", max: 100, on: true}], + [{cfg: {max: 1}}, {rate: 0.19, label: "VAT 19%", first: "a", max: 100, on: true}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Keyed evaluation: rows repeat a few distinct values. A result reused for "the same" input must +// be keyed on every value the expression reads, and on identity rather than loose equality. +{ + name: "keyed: a repeated category next to a varying amount", + graph: {nodes: [{expression: "calc", fields: { + price: "tier == 'gold' ? amount * 0.9 : tier == 'silver' ? amount * 0.95 : amount", + label: "upper(tier)", + }}]}, + cases: [ + [{tier: "gold", amount: 100}, {price: 90, label: "GOLD"}], + [{tier: "gold", amount: 200}, {price: 180, label: "GOLD"}], + [{tier: "silver", amount: 100}, {price: 95, label: "SILVER"}], + [{tier: "gold", amount: 100}, {price: 90, label: "GOLD"}], + [{tier: "basic", amount: 100}, {price: 100, label: "BASIC"}], + [{tier: "silver", amount: 20}, {price: 19, label: "SILVER"}], + [{tier: "gold", amount: 0.01}, {price: 0.009, label: "GOLD"}], + [{tier: "basic", amount: 7}, {price: 7, label: "BASIC"}], + [{tier: "gold", amount: 100}, {price: 90, label: "GOLD"}], + [{tier: "silver", amount: 100}, {price: 95, label: "SILVER"}], + [{tier: "gold", amount: 50}, {price: 45, label: "GOLD"}], + [{tier: "basic", amount: 100}, {price: 100, label: "BASIC"}], + [{tier: "gold", amount: 200}, {price: 180, label: "GOLD"}], + [{tier: "silver", amount: 1}, {price: 0.95, label: "SILVER"}], + [{tier: "gold", amount: 100}, {price: 90, label: "GOLD"}], + [{tier: "basic", amount: 0}, {price: 0, label: "BASIC"}], + ], +} + +{ + name: "keyed: numbers equal in value but not in scale render differently", + graph: {nodes: [{expression: "calc", fields: {s: "string(x)", t: "`v=${x}`", eq: "x == 1", sum: "x + 1"}}]}, + cases: [ + [{x: 1}, {s: "1", t: "v=1", eq: true, sum: 2}], + [{x: 1.0}, {s: "1.0", t: "v=1.0", eq: true, sum: 2}], + [{x: 1.00}, {s: "1.00", t: "v=1.00", eq: true, sum: 2}], + [{x: 1}, {s: "1", t: "v=1", eq: true, sum: 2}], + [{x: 1.0}, {s: "1.0", t: "v=1.0", eq: true, sum: 2}], + [{x: 1}, {s: "1", t: "v=1", eq: true, sum: 2}], + [{x: 1.00}, {s: "1.00", t: "v=1.00", eq: true, sum: 2}], + [{x: 2}, {s: "2", t: "v=2", eq: false, sum: 3}], + [{x: 1.0}, {s: "1.0", t: "v=1.0", eq: true, sum: 2}], + [{x: 1}, {s: "1", t: "v=1", eq: true, sum: 2}], + ], +} + +{ + name: "keyed: a number, its string, a boolean and null are distinct keys", + graph: {nodes: [{expression: "calc", fields: {t: "type(x)", isOne: "x == 1", str: "string(x)", isNull: "x == null"}}]}, + cases: [ + [{x: 1}, {t: "number", isOne: true, str: "1", isNull: false}], + [{x: "1"}, {t: "string", isOne: false, str: "1", isNull: false}], + [{x: true}, {t: "bool", isOne: false, str: "true", isNull: false}], + [{x: null}, {t: "null", isOne: false, str: "null", isNull: true}], + [{}, {t: "null", isOne: false, str: "null", isNull: true}], + [{x: 1}, {t: "number", isOne: true, str: "1", isNull: false}], + [{x: "1"}, {t: "string", isOne: false, str: "1", isNull: false}], + [{x: "true"}, {t: "string", isOne: false, str: "true", isNull: false}], + [{x: true}, {t: "bool", isOne: false, str: "true", isNull: false}], + [{x: "null"}, {t: "string", isOne: false, str: "null", isNull: false}], + [{x: 1}, {t: "number", isOne: true, str: "1", isNull: false}], + [{x: null}, {t: "null", isOne: false, str: "null", isNull: true}], + ], +} + +{ + name: "keyed: strings that differ only in case, whitespace or unicode form", + graph: {nodes: [{expression: "calc", fields: {u: "upper(s)", n: "len(s)", isA: "s == 'a'"}}]}, + cases: [ + [{s: "a"}, {u: "A", n: 1, isA: true}], + [{s: "A"}, {u: "A", n: 1, isA: false}], + [{s: "a "}, {u: "A ", n: 2, isA: false}], + [{s: "a"}, {u: "A", n: 1, isA: true}], + [{s: ""}, {u: "", n: 0, isA: false}], + [{s: "é"}, {u: "É", n: 1, isA: false}, "bug: len counts UTF-8 bytes instead of characters (as in the expression spec)"], + [{s: "a"}, {u: "A", n: 1, isA: true}], + [{s: "A"}, {u: "A", n: 1, isA: false}], + [{s: ""}, {u: "", n: 0, isA: false}], + [{s: " a"}, {u: " A", n: 2, isA: false}], + [{s: "a"}, {u: "A", n: 1, isA: true}], + ], +} + +{ + name: "keyed: an expression over two repeated fields keys on both", + graph: {nodes: [{expression: "calc", fields: {key: "region + ':' + plan", fee: "region == 'eu' ? (plan == 'pro' ? 20 : 10) : (plan == 'pro' ? 25 : 12)"}}]}, + cases: [ + [{region: "eu", plan: "pro"}, {key: "eu:pro", fee: 20}], + [{region: "eu", plan: "free"}, {key: "eu:free", fee: 10}], + [{region: "us", plan: "pro"}, {key: "us:pro", fee: 25}], + [{region: "us", plan: "free"}, {key: "us:free", fee: 12}], + [{region: "eu", plan: "pro"}, {key: "eu:pro", fee: 20}], + [{region: "us", plan: "pro"}, {key: "us:pro", fee: 25}], + [{region: "eu", plan: "free"}, {key: "eu:free", fee: 10}], + [{region: "eu", plan: "pro"}, {key: "eu:pro", fee: 20}], + [{region: "us", plan: "free"}, {key: "us:free", fee: 12}], + [{region: "us", plan: "pro"}, {key: "us:pro", fee: 25}], + [{region: "eu", plan: "pro"}, {key: "eu:pro", fee: 20}], + [{region: "us", plan: "free"}, {key: "us:free", fee: 12}], + ], +} + +{ + name: "keyed: an expression reading a repeated field and an earlier per-row field through $", + graph: {nodes: [{expression: "calc", fields: { + base: "qty * 10", + total: "kind == 'bulk' ? $.base * 0.5 : $.base", + tag: "kind + '-' + string($.total)", + }}]}, + cases: [ + [{kind: "bulk", qty: 1}, {base: 10, total: 5, tag: "bulk-5.0"}], + [{kind: "bulk", qty: 2}, {base: 20, total: 10, tag: "bulk-10.0"}], + [{kind: "single", qty: 1}, {base: 10, total: 10, tag: "single-10"}], + [{kind: "bulk", qty: 1}, {base: 10, total: 5, tag: "bulk-5.0"}], + [{kind: "single", qty: 3}, {base: 30, total: 30, tag: "single-30"}], + [{kind: "bulk", qty: 3}, {base: 30, total: 15, tag: "bulk-15.0"}], + [{kind: "single", qty: 1}, {base: 10, total: 10, tag: "single-10"}], + [{kind: "bulk", qty: 2}, {base: 20, total: 10, tag: "bulk-10.0"}], + [{kind: "single", qty: 0}, {base: 0, total: 0, tag: "single-0"}], + [{kind: "bulk", qty: 0}, {base: 0, total: 0, tag: "bulk-0.0"}, "bug: a zero product drops the scale that 10 * 0.5 keeps (5.0)"], + ], +} + +{ + name: "keyed: a repeated value that errors fails only its rows", + graph: {nodes: [{expression: "calc", fields: {next: "v + 1"}}]}, + cases: [ + [{v: 1}, {next: 2}], + [{v: "a"}, "!error"], + [{v: 1}, {next: 2}], + [{v: 2}, {next: 3}], + [{v: "a"}, "!error"], + [{v: 1}, {next: 2}], + [{v: true}, "!error"], + [{v: 2}, {next: 3}], + [{v: "a"}, "!error"], + [{v: 1}, {next: 2}], + [{}, "!error"], + [{v: 1}, {next: 2}], + ], +} + +{ + name: "keyed: a repeated array or object value", + graph: {nodes: [{expression: "calc", fields: {n: "len(xs)", first: "xs[0]", total: "sum(xs)", has: "2 in xs"}}]}, + cases: [ + [{xs: [1, 2]}, {n: 2, first: 1, total: 3, has: true}], + [{xs: [1, 2]}, {n: 2, first: 1, total: 3, has: true}], + [{xs: [2, 1]}, {n: 2, first: 2, total: 3, has: true}], + [{xs: []}, {n: 0, total: 0, has: false}], + [{xs: [1, 2]}, {n: 2, first: 1, total: 3, has: true}], + [{xs: [1, 2, 3]}, {n: 3, first: 1, total: 6, has: true}], + [{xs: [1.0, 2.0]}, {n: 2, first: 1, total: 3, has: true}], + [{xs: []}, {n: 0, total: 0, has: false}], + [{xs: [5]}, {n: 1, first: 5, total: 5, has: false}], + [{xs: [1, 2]}, {n: 2, first: 1, total: 3, has: true}], + ], +} + +{ + name: "keyed: a closure over a repeated array with a per-row multiplier", + graph: {nodes: [{expression: "calc", fields: {scaled: "map(xs, # * k)", big: "filter(xs, # > k)"}}]}, + cases: [ + [{xs: [1, 2, 3], k: 2}, {scaled: [2, 4, 6], big: [3]}], + [{xs: [1, 2, 3], k: 1}, {scaled: [1, 2, 3], big: [2, 3]}], + [{xs: [1, 2, 3], k: 2}, {scaled: [2, 4, 6], big: [3]}], + [{xs: [1, 2, 3], k: 0}, {scaled: [0, 0, 0], big: [1, 2, 3]}], + [{xs: [4], k: 2}, {scaled: [8], big: [4]}], + [{xs: [1, 2, 3], k: 3}, {scaled: [3, 6, 9], big: []}], + [{xs: [4], k: 1}, {scaled: [4], big: [4]}], + [{xs: [1, 2, 3], k: 2}, {scaled: [2, 4, 6], big: [3]}], + [{xs: [], k: 2}, {scaled: [], big: []}], + [{xs: [1, 2, 3], k: 1}, {scaled: [1, 2, 3], big: [2, 3]}], + ], +} + +{ + name: "keyed: a repeated date string and the fixed clock", + graph: {nodes: [{expression: "calc", fields: { + age: "d().diff(d(dob), 'year')", + adult: "d(dob).add(18, 'year') <= d()", + born: "d(dob).format('%Y')", + }}]}, + cases: [ + [{dob: "2000-01-01"}, {age: 25, adult: true, born: "2000"}], + [{dob: "2010-06-15"}, {age: 14, adult: false, born: "2010"}], + [{dob: "2000-01-01"}, {age: 25, adult: true, born: "2000"}], + [{dob: "2007-03-20"}, {age: 18, adult: true, born: "2007"}], + [{dob: "2007-03-21"}, {age: 17, adult: false, born: "2007"}], + [{dob: "2010-06-15"}, {age: 14, adult: false, born: "2010"}], + [{dob: "2000-01-01"}, {age: 25, adult: true, born: "2000"}], + [{dob: "2007-03-20"}, {age: 18, adult: true, born: "2007"}], + [{dob: "2000-01-01T00:00:00Z"}, {age: 25, adult: true, born: "2000"}], + [{dob: "2007-03-21"}, {age: 17, adult: false, born: "2007"}], + ], +} + +{ + name: "keyed: thirty rows over three statuses feeding a switch", + graph: { + nodes: [ + {expression: "norm", fields: {s: "lower(trim(status))", amount: "amount"}}, + {switch: "route", when: ["s == 'open'", "s == 'closed'", ""]}, + {expression: "open", fields: {out: "'O:' + string(amount)"}}, + {expression: "closed", fields: {out: "'C:' + string(amount * 2)"}}, + {expression: "other", fields: {out: "'X:' + s"}}, + ], + edges: ["input -> norm -> route", "route:0 -> open -> output", "route:1 -> closed -> output", "route:2 -> other -> output"], + }, + cases: [ + [{status: "open", amount: 1}, {out: "O:1"}], + [{status: "OPEN", amount: 2}, {out: "O:2"}], + [{status: "closed", amount: 1}, {out: "C:2"}], + [{status: " open ", amount: 3}, {out: "O:3"}], + [{status: "void", amount: 1}, {out: "X:void"}], + [{status: "open", amount: 1}, {out: "O:1"}], + [{status: "closed", amount: 5}, {out: "C:10"}], + [{status: "Closed", amount: 1}, {out: "C:2"}], + [{status: "open", amount: 4}, {out: "O:4"}], + [{status: "void", amount: 2}, {out: "X:void"}], + [{status: "open", amount: 1}, {out: "O:1"}], + [{status: "closed", amount: 1}, {out: "C:2"}], + [{status: "open", amount: 1.5}, {out: "O:1.5"}], + [{status: "", amount: 1}, {out: "X:"}], + [{status: "open", amount: 1}, {out: "O:1"}], + [{status: "closed", amount: 0.5}, {out: "C:1.0"}], + [{status: "open", amount: 2}, {out: "O:2"}], + [{status: "void", amount: 1}, {out: "X:void"}], + [{status: "closed", amount: 1}, {out: "C:2"}], + [{status: "open", amount: 1}, {out: "O:1"}], + [{status: "OPEN", amount: 1}, {out: "O:1"}], + [{status: "closed", amount: 3}, {out: "C:6"}], + [{status: "open", amount: 0}, {out: "O:0"}], + [{status: "void", amount: 0}, {out: "X:void"}], + [{status: "open", amount: 1}, {out: "O:1"}], + [{status: "closed", amount: 1}, {out: "C:2"}], + [{status: "open", amount: 10}, {out: "O:10"}], + [{status: "closed", amount: 10}, {out: "C:20"}], + [{status: "open", amount: 1}, {out: "O:1"}], + [{status: "void", amount: 1}, {out: "X:void"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Aliasing of pure path reads: a field that copies an input path is a value, not a view. Later +// changes to the copy or to the original must not show through the other. +{ + name: "alias: a copied object extended by a later field leaves the original intact", + graph: {nodes: [{expression: "calc", passThrough: true, fields: [ + ["copy", "customer"], + ["copy.tier", "score > 50 ? 'gold' : 'basic'"], + ]}]}, + cases: [ + [{customer: {name: "ann"}, score: 80}, {customer: {name: "ann"}, score: 80, copy: {name: "ann", tier: "gold"}}, "bug: the copy aliases the request object, so writing copy.tier also writes customer.tier (see 03)"], + [{customer: {name: "ann"}, score: 10}, {customer: {name: "ann"}, score: 10, copy: {name: "ann", tier: "basic"}}, "bug: the copy aliases the request object, so writing copy.tier also writes customer.tier (see 03)"], + [{customer: {name: "bob"}, score: 80}, {customer: {name: "bob"}, score: 80, copy: {name: "bob", tier: "gold"}}, "bug: the copy aliases the request object, so writing copy.tier also writes customer.tier (see 03)"], + [{customer: {name: "ann"}, score: 80}, {customer: {name: "ann"}, score: 80, copy: {name: "ann", tier: "gold"}}, "bug: the copy aliases the request object, so writing copy.tier also writes customer.tier (see 03)"], + [{customer: {name: "ann", tier: "x"}, score: 10}, {customer: {name: "ann", tier: "x"}, score: 10, copy: {name: "ann", tier: "basic"}}, "bug: the copy aliases the request object, so writing copy.tier also writes customer.tier (see 03)"], + [{customer: {}, score: 80}, {customer: {}, score: 80, copy: {tier: "gold"}}, "bug: the copy aliases the request object, so writing copy.tier also writes customer.tier (see 03)"], + [{customer: {name: "ann"}, score: 10}, {customer: {name: "ann"}, score: 10, copy: {name: "ann", tier: "basic"}}, "bug: the copy aliases the request object, so writing copy.tier also writes customer.tier (see 03)"], + [{customer: {name: "bob"}, score: 80}, {customer: {name: "bob"}, score: 80, copy: {name: "bob", tier: "gold"}}, "bug: the copy aliases the request object, so writing copy.tier also writes customer.tier (see 03)"], + ], +} + +{ + name: "alias: two copies of one path diverge when each is extended", + graph: {nodes: [{expression: "calc", fields: [ + ["a", "item"], + ["b", "item"], + ["a.side", "'left'"], + ["b.side", "'right'"], + ["b.n", "item.n + 1"], + ]}]}, + cases: [ + [{item: {n: 1}}, {a: {n: 1, side: "left"}, b: {n: 2, side: "right"}}, "bug: both fields alias the same request object, so each sees the other's writes"], + [{item: {n: 1}}, {a: {n: 1, side: "left"}, b: {n: 2, side: "right"}}, "bug: both fields alias the same request object, so each sees the other's writes"], + [{item: {n: 2}}, {a: {n: 2, side: "left"}, b: {n: 3, side: "right"}}, "bug: both fields alias the same request object, so each sees the other's writes"], + [{item: {n: 1, side: "up"}}, {a: {n: 1, side: "left"}, b: {n: 2, side: "right"}}, "bug: both fields alias the same request object, so each sees the other's writes"], + [{item: {n: 1}}, {a: {n: 1, side: "left"}, b: {n: 2, side: "right"}}, "bug: both fields alias the same request object, so each sees the other's writes"], + [{item: {n: 0}}, {a: {n: 0, side: "left"}, b: {n: 1, side: "right"}}, "bug: both fields alias the same request object, so each sees the other's writes"], + ], +} + +{ + name: "alias: a copy taken before the original field is rewritten keeps the old value", + graph: {nodes: [{expression: "calc", fields: [ + ["orig", "data"], + ["snapshot", "$.orig"], + ["orig.flag", "true"], + ["orig.v", "data.v * 2"], + ]}]}, + cases: [ + [{data: {v: 1}}, {orig: {v: 2, flag: true}, snapshot: {v: 1}}], + [{data: {v: 1}}, {orig: {v: 2, flag: true}, snapshot: {v: 1}}], + [{data: {v: 3}}, {orig: {v: 6, flag: true}, snapshot: {v: 3}}], + [{data: {v: 1, w: "x"}}, {orig: {v: 2, w: "x", flag: true}, snapshot: {v: 1, w: "x"}}], + [{data: {v: 1}}, {orig: {v: 2, flag: true}, snapshot: {v: 1}}], + [{data: {v: 0.5}}, {orig: {v: 1, flag: true}, snapshot: {v: 0.5}}], + ], +} + +{ + name: "alias: a copy passed downstream and modified there leaves the upstream original intact", + graph: {nodes: [ + {expression: "copy", passThrough: true, fields: {profile: "customer"}}, + {expression: "edit", passThrough: true, fields: {"profile.name": "upper(profile.name)", "profile.seen": "true"}}, + ]}, + cases: [ + [{customer: {name: "ann"}}, {customer: {name: "ann"}, profile: {name: "ANN", seen: true}}], + [{customer: {name: "ann"}}, {customer: {name: "ann"}, profile: {name: "ANN", seen: true}}], + [{customer: {name: "bob", age: 3}}, {customer: {name: "bob", age: 3}, profile: {name: "BOB", age: 3, seen: true}}], + [{customer: {name: "ann"}}, {customer: {name: "ann"}, profile: {name: "ANN", seen: true}}], + [{customer: {name: ""}}, {customer: {name: ""}, profile: {name: "", seen: true}}], + [{customer: {name: "bob", age: 3}}, {customer: {name: "bob", age: 3}, profile: {name: "BOB", age: 3, seen: true}}], + ], +} + +{ + name: "alias: a copied array survives the original being remapped downstream", + graph: {nodes: [ + {expression: "keep", passThrough: true, fields: {original: "items"}}, + {expression: "change", passThrough: true, fields: {items: "map(items, # * 10)"}}, + ]}, + cases: [ + [{items: [1, 2]}, {items: [10, 20], original: [1, 2]}], + [{items: [1, 2]}, {items: [10, 20], original: [1, 2]}], + [{items: [3]}, {items: [30], original: [3]}], + [{items: []}, {items: [], original: []}], + [{items: [1, 2]}, {items: [10, 20], original: [1, 2]}], + [{items: [0.5, -1]}, {items: [5, -10], original: [0.5, -1]}], + ], +} + +{ + name: "alias: a scalar copy and the original updated separately", + graph: {nodes: [ + {expression: "copy", passThrough: true, fields: {before: "count"}}, + {expression: "bump", passThrough: true, fields: {count: "count + 1"}}, + {expression: "check", passThrough: true, fields: {delta: "count - before"}}, + ]}, + cases: [ + [{count: 1}, {count: 2, before: 1, delta: 1}], + [{count: 1}, {count: 2, before: 1, delta: 1}], + [{count: 5}, {count: 6, before: 5, delta: 1}], + [{count: 1}, {count: 2, before: 1, delta: 1}], + [{count: 0.5}, {count: 1.5, before: 0.5, delta: 1}], + [{count: 5}, {count: 6, before: 5, delta: 1}], + [{count: -1}, {count: 0, before: -1, delta: 1}], + ], +} + +{ + name: "alias: a nested path copied to several outputs, one of them extended downstream", + graph: {nodes: [ + {expression: "spread", fields: {left: "order.address", right: "order.address", city: "order.address.city"}}, + {expression: "edit", passThrough: true, fields: {"left.city": "upper(city)"}}, + ]}, + cases: [ + [{order: {address: {city: "rome", zip: "1"}}}, {left: {city: "ROME", zip: "1"}, right: {city: "rome", zip: "1"}, city: "rome"}], + [{order: {address: {city: "rome", zip: "1"}}}, {left: {city: "ROME", zip: "1"}, right: {city: "rome", zip: "1"}, city: "rome"}], + [{order: {address: {city: "oslo"}}}, {left: {city: "OSLO"}, right: {city: "oslo"}, city: "oslo"}], + [{order: {address: {city: "rome", zip: "1"}}}, {left: {city: "ROME", zip: "1"}, right: {city: "rome", zip: "1"}, city: "rome"}], + [{order: {address: {city: ""}}}, {left: {city: ""}, right: {city: ""}, city: ""}], + ], +} + +{ + name: "alias: a copied request object modified in two parallel branches", + graph: { + nodes: [ + {expression: "copy", fields: {o: "obj"}}, + {expression: "a", passThrough: true, fields: {"o.a": "true"}}, + {expression: "b", passThrough: true, fields: {"o.b": "true"}}, + {expression: "join", fields: {o: "o", n: "len(keys(o))"}}, + ], + edges: ["input -> copy", "copy -> a -> join", "copy -> b -> join", "join -> output"], + }, + cases: [ + [{obj: {x: 1}}, {o: {x: 1, a: true, b: true}, n: 3}], + [{obj: {x: 1}}, {o: {x: 1, a: true, b: true}, n: 3}], + [{obj: {}}, {o: {a: true, b: true}, n: 2}], + [{obj: {x: 2}}, {o: {x: 2, a: true, b: true}, n: 3}], + [{obj: {x: 1}}, {o: {x: 1, a: true, b: true}, n: 3}], + ], +} + +// --------------------------------------------------------------------------------------------- +// `path ?? literal`: only null and missing take the default; every other value of every type is +// kept, including the falsy ones. +{ + name: "coalesce: a number default against values of every type", + graph: {nodes: [{expression: "calc", fields: {v: "x ?? 0", t: "type(x ?? 0)"}}]}, + cases: [ + [{}, {v: 0, t: "number"}], + [{x: null}, {v: 0, t: "number"}], + [{x: 5}, {v: 5, t: "number"}], + [{x: 0}, {v: 0, t: "number"}], + [{x: ""}, {v: "", t: "string"}], + [{x: false}, {v: false, t: "bool"}], + [{x: []}, {v: [], t: "array"}], + [{x: {}}, {v: {}, t: "object"}], + [{}, {v: 0, t: "number"}], + [{x: "0"}, {v: "0", t: "string"}], + [{x: 5}, {v: 5, t: "number"}], + [{x: null}, {v: 0, t: "number"}], + [{x: -0.5}, {v: -0.5, t: "number"}], + [{}, {v: 0, t: "number"}], + ], +} + +{ + name: "coalesce: string, boolean, array, object and null defaults", + graph: {nodes: [{expression: "calc", fields: { + s: "x ?? 'none'", + t: "x ?? true", + f: "x ?? false", + a: "x ?? [1, 2]", + o: "x ?? {k: 'v'}", + n: "x ?? null", + e: "x ?? ''", + }}]}, + cases: [ + [{}, {s: "none", t: true, f: false, a: [1, 2], o: {k: "v"}, e: ""}], + [{x: null}, {s: "none", t: true, f: false, a: [1, 2], o: {k: "v"}, e: ""}], + [{x: "a"}, {s: "a", t: "a", f: "a", a: "a", o: "a", n: "a", e: "a"}], + [{x: false}, {s: false, t: false, f: false, a: false, o: false, n: false, e: false}], + [{x: 0}, {s: 0, t: 0, f: 0, a: 0, o: 0, n: 0, e: 0}], + [{}, {s: "none", t: true, f: false, a: [1, 2], o: {k: "v"}, e: ""}], + [{x: ""}, {s: "", t: "", f: "", a: "", o: "", n: "", e: ""}], + [{x: [3]}, {s: [3], t: [3], f: [3], a: [3], o: [3], n: [3], e: [3]}], + [{x: {k: 1}}, {s: {k: 1}, t: {k: 1}, f: {k: 1}, a: {k: 1}, o: {k: 1}, n: {k: 1}, e: {k: 1}}], + [{x: null}, {s: "none", t: true, f: false, a: [1, 2], o: {k: "v"}, e: ""}], + [{x: "a"}, {s: "a", t: "a", f: "a", a: "a", o: "a", n: "a", e: "a"}], + ], +} + +{ + name: "coalesce: a default array or object is fresh for every row", + graph: {nodes: [ + {expression: "init", fields: {list: "xs ?? []", bag: "o ?? {}", tag: "tag"}}, + {expression: "grow", passThrough: true, fields: {"bag.seen": "tag", size: "len(list)"}}, + ]}, + cases: [ + [{tag: "a"}, {list: [], bag: {seen: "a"}, size: 0, tag: "a"}], + [{tag: "b"}, {list: [], bag: {seen: "b"}, size: 0, tag: "b"}], + [{tag: "a", o: {x: 1}}, {list: [], bag: {x: 1, seen: "a"}, size: 0, tag: "a"}], + [{tag: "c"}, {list: [], bag: {seen: "c"}, size: 0, tag: "c"}], + [{tag: "a", xs: [1]}, {list: [1], bag: {seen: "a"}, size: 1, tag: "a"}], + [{}, {list: [], bag: {}, size: 0}], + [{tag: "b"}, {list: [], bag: {seen: "b"}, size: 0, tag: "b"}], + [{tag: "a"}, {list: [], bag: {seen: "a"}, size: 0, tag: "a"}], + ], +} + +{ + name: "coalesce: a date default and a date-valued path", + graph: {nodes: [{expression: "calc", fields: { + at: "d(when ?? '2024-01-01')", + y: "d(when ?? '2024-01-01').year()", + late: "d(when ?? '2024-01-01') < d()", + }}]}, + cases: [ + [{}, {at: "2024-01-01T00:00:00Z", y: 2024, late: true}], + [{when: "2030-05-05"}, {at: "2030-05-05T00:00:00Z", y: 2030, late: false}], + [{when: null}, {at: "2024-01-01T00:00:00Z", y: 2024, late: true}], + [{}, {at: "2024-01-01T00:00:00Z", y: 2024, late: true}], + [{when: "2025-03-20"}, {at: "2025-03-20T00:00:00Z", y: 2025, late: true}], + [{when: "2030-05-05"}, {at: "2030-05-05T00:00:00Z", y: 2030, late: false}], + [{when: date("2026-01-01")}, {at: "2026-01-01T00:00:00Z", y: 2026, late: false}], + [{}, {at: "2024-01-01T00:00:00Z", y: 2024, late: true}], + ], +} + +{ + name: "coalesce: nested paths with a missing parent, a null parent and a scalar parent", + graph: {nodes: [{expression: "calc", fields: {v: "a.b.c ?? 'dflt'"}}]}, + cases: [ + [{}, {v: "dflt"}], + [{a: null}, {v: "dflt"}], + [{a: {}}, {v: "dflt"}], + [{a: {b: null}}, {v: "dflt"}], + [{a: {b: {c: 1}}}, {v: 1}], + [{a: {b: {c: null}}}, {v: "dflt"}], + [{a: {b: {c: false}}}, {v: false}], + [{}, {v: "dflt"}], + [{a: {b: {c: 1}}}, {v: 1}], + [{a: {b: {c: "x"}}}, {v: "x"}], + [{a: {b: {}}}, {v: "dflt"}], + [{a: {b: {c: 1}}}, {v: 1}], + ], +} + +{ + name: "coalesce: a chain of paths ending in a literal", + graph: {nodes: [{expression: "calc", fields: {v: "primary ?? secondary ?? fallback ?? -1"}}]}, + cases: [ + [{primary: 1, secondary: 2, fallback: 3}, {v: 1}], + [{secondary: 2, fallback: 3}, {v: 2}], + [{fallback: 3}, {v: 3}], + [{}, {v: -1}], + [{primary: null, secondary: null, fallback: null}, {v: -1}], + [{primary: 0, secondary: 2}, {v: 0}], + [{secondary: false}, {v: false}], + [{fallback: ""}, {v: ""}], + [{}, {v: -1}], + [{primary: 1}, {v: 1}], + [{secondary: 2}, {v: 2}], + [{}, {v: -1}], + ], +} + +{ + name: "coalesce: the default used in arithmetic and comparisons", + graph: {nodes: [{expression: "calc", fields: { + total: "(price ?? 0) * (qty ?? 1)", + big: "(price ?? 0) > 100", + label: "(name ?? 'anon') + '#' + string(qty ?? 1)", + }}]}, + cases: [ + [{price: 10, qty: 2, name: "a"}, {total: 20, big: false, label: "a#2"}], + [{price: 10}, {total: 10, big: false, label: "anon#1"}], + [{qty: 5}, {total: 0, big: false, label: "anon#5"}], + [{}, {total: 0, big: false, label: "anon#1"}], + [{price: 200, qty: 0}, {total: 0, big: true, label: "anon#0"}], + [{price: 10, qty: 2, name: "a"}, {total: 20, big: false, label: "a#2"}], + [{price: null, qty: null, name: null}, {total: 0, big: false, label: "anon#1"}], + [{price: 10}, {total: 10, big: false, label: "anon#1"}], + [{price: "10"}, "!error"], + [{}, {total: 0, big: false, label: "anon#1"}], + ], +} + +{ + name: "coalesce: over an earlier field through $ and over an upstream node", + graph: {nodes: [ + {expression: "first", fields: {maybe: "flag == true ? 'set' : null"}}, + {expression: "second", fields: {a: "maybe ?? 'unset'", b: "$.a ?? 'never'", c: "$nodes.first.maybe ?? 'unset'"}}, + ]}, + cases: [ + [{flag: true}, {a: "set", b: "set", c: "set"}], + [{flag: false}, {a: "unset", b: "unset", c: "unset"}], + [{}, {a: "unset", b: "unset", c: "unset"}], + [{flag: true}, {a: "set", b: "set", c: "set"}], + [{flag: false}, {a: "unset", b: "unset", c: "unset"}], + [{flag: true}, {a: "set", b: "set", c: "set"}], + ], +} + +{ + name: "coalesce: a literal on the left never takes the default", + graph: {nodes: [{expression: "calc", fields: {a: "0 ?? x", b: "'' ?? x", c: "false ?? x", d: "null ?? x", e: "null ?? null ?? 'z'"}}]}, + cases: [ + [{x: 1}, {a: 0, b: "", c: false, d: 1, e: "z"}], + [{}, {a: 0, b: "", c: false, e: "z"}], + [{x: "s"}, {a: 0, b: "", c: false, d: "s", e: "z"}], + [{x: 1}, {a: 0, b: "", c: false, d: 1, e: "z"}], + [{x: null}, {a: 0, b: "", c: false, e: "z"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Static object shapes: an object literal with fixed keys holds per-row values; a member that is +// null stays in the object, and the object built for one row is never shared with another. +{ + name: "shapes: static keys mixing literals and per-row paths", + graph: {nodes: [{expression: "calc", fields: {o: "{kind: 'person', name: name, score: score ?? 0, tags: ['a'], nested: {k: 1, v: v}}"}}]}, + cases: [ + [{name: "ann", score: 5, v: true}, {o: {kind: "person", name: "ann", score: 5, tags: ["a"], nested: {k: 1, v: true}}}], + [{name: "ann", score: 5, v: true}, {o: {kind: "person", name: "ann", score: 5, tags: ["a"], nested: {k: 1, v: true}}}], + [{name: "bob"}, {o: {kind: "person", name: "bob", score: 0, tags: ["a"], nested: {k: 1, v: null}}}], + [{}, {o: {kind: "person", name: null, score: 0, tags: ["a"], nested: {k: 1, v: null}}}], + [{name: 7, score: "x", v: [1]}, {o: {kind: "person", name: 7, score: "x", tags: ["a"], nested: {k: 1, v: [1]}}}], + [{name: "ann", score: 5, v: true}, {o: {kind: "person", name: "ann", score: 5, tags: ["a"], nested: {k: 1, v: true}}}], + [{name: null, score: null, v: null}, {o: {kind: "person", name: null, score: 0, tags: ["a"], nested: {k: 1, v: null}}}], + [{name: "cy", score: 1.50, v: {d: 1}}, {o: {kind: "person", name: "cy", score: 1.5, tags: ["a"], nested: {k: 1, v: {d: 1}}}}], + [{name: "bob"}, {o: {kind: "person", name: "bob", score: 0, tags: ["a"], nested: {k: 1, v: null}}}], + [{name: "ann", score: 5, v: false}, {o: {kind: "person", name: "ann", score: 5, tags: ["a"], nested: {k: 1, v: false}}}], + ], +} + +{ + name: "shapes: a literal object extended differently per branch is not shared between rows", + graph: { + nodes: [ + {expression: "make", passThrough: true, fields: {o: "{base: 1}"}}, + {switch: "route", when: ["kind == 'a'", ""]}, + {expression: "a", passThrough: true, fields: {"o.a": "n"}}, + {expression: "b", passThrough: true, fields: {"o.b": "n"}}, + {expression: "out", fields: {o: "o", n: "len(keys(o))"}}, + ], + edges: ["input -> make -> route", "route:0 -> a -> out", "route:1 -> b -> out", "out -> output"], + }, + cases: [ + [{kind: "a", n: 1}, {o: {base: 1, a: 1}, n: 2}], + [{kind: "b", n: 2}, {o: {base: 1, b: 2}, n: 2}], + [{kind: "a", n: 3}, {o: {base: 1, a: 3}, n: 2}], + [{kind: "a", n: 1}, {o: {base: 1, a: 1}, n: 2}], + [{kind: "b", n: 1}, {o: {base: 1, b: 1}, n: 2}], + [{kind: "b", n: 2}, {o: {base: 1, b: 2}, n: 2}], + [{kind: "a", n: 1}, {o: {base: 1, a: 1}, n: 2}], + [{kind: "c", n: 9}, {o: {base: 1, b: 9}, n: 2}], + [{kind: "a", n: 1}, {o: {base: 1, a: 1}, n: 2}], + ], +} + +{ + name: "shapes: a literal array read by a downstream closure with a per-row factor", + graph: {nodes: [ + {expression: "make", passThrough: true, fields: {base: "[1, 2]"}}, + {expression: "grow", fields: {all: "map(base, # * (k ?? 1))", n: "len(base)", base: "base"}}, + ]}, + cases: [ + [{k: 3}, {all: [3, 6], n: 2, base: [1, 2]}], + [{k: 4}, {all: [4, 8], n: 2, base: [1, 2]}], + [{k: 3}, {all: [3, 6], n: 2, base: [1, 2]}], + [{k: "x"}, "!error"], + [{}, {all: [1, 2], n: 2, base: [1, 2]}], + [{k: 3}, {all: [3, 6], n: 2, base: [1, 2]}], + [{k: 0}, {all: [0, 0], n: 2, base: [1, 2]}], + ], +} + +{ + name: "shapes: the same keys holding different value types in different rows", + graph: {nodes: [ + {expression: "build", fields: {o: "{a: a, b: b}"}}, + {expression: "read", fields: {ta: "type(o.a)", tb: "type(o.b)", both: "o.a != null and o.b != null"}}, + ]}, + cases: [ + [{a: 1, b: "x"}, {ta: "number", tb: "string", both: true}], + [{a: "1", b: 2}, {ta: "string", tb: "number", both: true}], + [{a: 1, b: "x"}, {ta: "number", tb: "string", both: true}], + [{a: true}, {ta: "bool", tb: "null", both: false}], + [{b: [1]}, {ta: "null", tb: "array", both: false}], + [{a: {z: 1}, b: {}}, {ta: "object", tb: "object", both: true}], + [{a: 1, b: "x"}, {ta: "number", tb: "string", both: true}], + [{}, {ta: "null", tb: "null", both: false}], + [{a: 1, b: "x"}, {ta: "number", tb: "string", both: true}], + ], +} + +{ + name: "shapes: a static object merged into the input under pass-through", + graph: {nodes: [{expression: "calc", passThrough: true, fields: {meta: "{source: 'calc', id: id, ok: id != null}"}}]}, + cases: [ + [{id: 1}, {id: 1, meta: {source: "calc", id: 1, ok: true}}], + [{id: 1, meta: {old: true}}, {id: 1, meta: {old: true, source: "calc", id: 1, ok: true}}], + [{id: 2}, {id: 2, meta: {source: "calc", id: 2, ok: true}}], + [{}, {meta: {source: "calc", id: null, ok: false}}], + [{id: 1}, {id: 1, meta: {source: "calc", id: 1, ok: true}}], + [{id: 1, meta: {source: "input"}}, {id: 1, meta: {source: "calc", id: 1, ok: true}}], + [{id: 1, meta: "scalar"}, {id: 1, meta: {source: "calc", id: 1, ok: true}}], + [{id: 2}, {id: 2, meta: {source: "calc", id: 2, ok: true}}], + ], +} + +{ + name: "shapes: objects from map with static keys over per-row arrays", + graph: {nodes: [{expression: "calc", fields: {rows: "map(items, {id: #.id, kind: 'line', double: (#.n ?? 0) * 2})"}}]}, + cases: [ + [{items: [{id: 1, n: 1}, {id: 2}]}, {rows: [{id: 1, kind: "line", double: 2}, {id: 2, kind: "line", double: 0}]}], + [{items: [{id: 1, n: 1}]}, {rows: [{id: 1, kind: "line", double: 2}]}], + [{items: []}, {rows: []}], + [{items: [{id: 1, n: 1}, {id: 2}]}, {rows: [{id: 1, kind: "line", double: 2}, {id: 2, kind: "line", double: 0}]}], + [{items: [{n: 5}]}, {rows: [{id: null, kind: "line", double: 10}]}], + [{items: [{id: 1, n: 1}]}, {rows: [{id: 1, kind: "line", double: 2}]}], + ], +} + +{ + name: "shapes: dotted keys build the same static shape in every row", + graph: {nodes: [{expression: "calc", fields: {"r.kind": "'fixed'", "r.value": "v", "r.inner.flag": "v > 0", "r.inner.text": "'x'"}}]}, + cases: [ + [{v: 1}, {r: {kind: "fixed", value: 1, inner: {flag: true, text: "x"}}}], + [{v: -1}, {r: {kind: "fixed", value: -1, inner: {flag: false, text: "x"}}}], + [{v: 1}, {r: {kind: "fixed", value: 1, inner: {flag: true, text: "x"}}}], + [{v: 0}, {r: {kind: "fixed", value: 0, inner: {flag: false, text: "x"}}}], + [{v: 1}, {r: {kind: "fixed", value: 1, inner: {flag: true, text: "x"}}}], + [{v: 2.5}, {r: {kind: "fixed", value: 2.5, inner: {flag: true, text: "x"}}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Constant-argument builtins evaluated once per batch, mixed with per-row arguments. +{ + name: "builtins: constant string functions beside per-row ones", + graph: {nodes: [{expression: "calc", fields: { + c: "upper('x')", + r: "upper(s)", + both: "upper('x') + lower(s)", + starts: "startsWith(s, 'ab')", + has: "contains('abc', s)", + n: "len('abc') + len(s)", + }}]}, + cases: [ + [{s: "ab"}, {c: "X", r: "AB", both: "Xab", starts: true, has: true, n: 5}], + [{s: "Ab"}, {c: "X", r: "AB", both: "Xab", starts: false, has: false, n: 5}], + [{s: "ab"}, {c: "X", r: "AB", both: "Xab", starts: true, has: true, n: 5}], + [{s: "c"}, {c: "X", r: "C", both: "Xc", starts: false, has: true, n: 4}], + [{s: ""}, {c: "X", r: "", both: "X", starts: false, has: true, n: 3}], + [{s: "abd"}, {c: "X", r: "ABD", both: "Xabd", starts: true, has: false, n: 6}], + [{s: "ab"}, {c: "X", r: "AB", both: "Xab", starts: true, has: true, n: 5}], + [{s: "c"}, {c: "X", r: "C", both: "Xc", starts: false, has: true, n: 4}], + ], +} + +{ + name: "builtins: a constant date beside per-row offsets and dates", + graph: {nodes: [{expression: "calc", fields: { + base: "d('2024-01-01')", + shifted: "d('2024-01-01').add(n, 'd')", + gap: "d(s).diff(d('2024-01-01'), 'd')", + after: "d(s) > d('2024-01-01')", + legacy: "date('2024-01-01')", + }}]}, + cases: [ + [{n: 1, s: "2024-01-02"}, {base: "2024-01-01T00:00:00Z", shifted: "2024-01-02T00:00:00Z", gap: 1, after: true, legacy: 1704067200}], + [{n: 1, s: "2024-01-02"}, {base: "2024-01-01T00:00:00Z", shifted: "2024-01-02T00:00:00Z", gap: 1, after: true, legacy: 1704067200}], + [{n: 31, s: "2023-12-31"}, {base: "2024-01-01T00:00:00Z", shifted: "2024-02-01T00:00:00Z", gap: -1, after: false, legacy: 1704067200}], + [{n: 0, s: "2024-01-01"}, {base: "2024-01-01T00:00:00Z", shifted: "2024-01-01T00:00:00Z", gap: 0, after: false, legacy: 1704067200}], + [{n: -1, s: "2025-01-01"}, {base: "2024-01-01T00:00:00Z", shifted: "2023-12-31T00:00:00Z", gap: 366, after: true, legacy: 1704067200}], + [{n: 1, s: "2024-01-02"}, {base: "2024-01-01T00:00:00Z", shifted: "2024-01-02T00:00:00Z", gap: 1, after: true, legacy: 1704067200}], + [{n: 366, s: "2024-03-01"}, {base: "2024-01-01T00:00:00Z", shifted: "2025-01-01T00:00:00Z", gap: 60, after: true, legacy: 1704067200}], + [{n: 0, s: "2024-01-01"}, {base: "2024-01-01T00:00:00Z", shifted: "2024-01-01T00:00:00Z", gap: 0, after: false, legacy: 1704067200}], + ], +} + +{ + name: "builtins: a constant date result chained by a per-row method is not mutated", + graph: {nodes: [{expression: "calc", fields: [ + ["start", "d('2024-03-15')"], + ["moved", "$.start.add(n, 'month')"], + ["again", "$.start"], + ["som", "$.start.startOf(unit)"], + ]}]}, + cases: [ + [{n: 1, unit: "month"}, {start: "2024-03-15T00:00:00Z", moved: "2024-04-15T00:00:00Z", again: "2024-03-15T00:00:00Z", som: "2024-03-01T00:00:00Z"}], + [{n: 2, unit: "year"}, {start: "2024-03-15T00:00:00Z", moved: "2024-05-15T00:00:00Z", again: "2024-03-15T00:00:00Z", som: "2024-01-01T00:00:00Z"}], + [{n: 1, unit: "month"}, {start: "2024-03-15T00:00:00Z", moved: "2024-04-15T00:00:00Z", again: "2024-03-15T00:00:00Z", som: "2024-03-01T00:00:00Z"}], + [{n: -3, unit: "week"}, {start: "2024-03-15T00:00:00Z", moved: "2023-12-15T00:00:00Z", again: "2024-03-15T00:00:00Z", som: "2024-03-11T00:00:00Z"}], + [{n: 0, unit: "day"}, {start: "2024-03-15T00:00:00Z", moved: "2024-03-15T00:00:00Z", again: "2024-03-15T00:00:00Z", som: "2024-03-15T00:00:00Z"}], + [{n: 1, unit: "month"}, {start: "2024-03-15T00:00:00Z", moved: "2024-04-15T00:00:00Z", again: "2024-03-15T00:00:00Z", som: "2024-03-01T00:00:00Z"}], + ], +} + +{ + name: "builtins: constant math and list functions beside per-row arguments", + graph: {nodes: [{expression: "calc", fields: { + m: "max([1, 5, 3])", + mx: "max([1, x])", + r: "round(2.555, 2)", + rx: "round(x, 1)", + s: "sum([0.1, 0.2])", + inList: "x in [1, 2, 3]", + abs: "abs(-2) + abs(x)", + }}]}, + cases: [ + [{x: 2}, {m: 5, mx: 2, r: 2.56, rx: 2, s: 0.3, inList: true, abs: 4}], + [{x: 2}, {m: 5, mx: 2, r: 2.56, rx: 2, s: 0.3, inList: true, abs: 4}], + [{x: 0.25}, {m: 5, mx: 1, r: 2.56, rx: 0.3, s: 0.3, inList: false, abs: 2.25}], + [{x: -7}, {m: 5, mx: 1, r: 2.56, rx: -7, s: 0.3, inList: false, abs: 9}], + [{x: 3}, {m: 5, mx: 3, r: 2.56, rx: 3, s: 0.3, inList: true, abs: 5}], + [{x: 2}, {m: 5, mx: 2, r: 2.56, rx: 2, s: 0.3, inList: true, abs: 4}], + [{x: 1.05}, {m: 5, mx: 1.05, r: 2.56, rx: 1.1, s: 0.3, inList: false, abs: 3.05}], + [{x: 3}, {m: 5, mx: 3, r: 2.56, rx: 3, s: 0.3, inList: true, abs: 5}], + ], +} + +{ + name: "builtins: a constant-argument call whose result is an error fails every row", + graph: {nodes: [{expression: "calc", fields: {ok: "x", bad: "upper(1)"}}]}, + cases: [ + [{x: 1}, "!error"], + [{x: 2}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "builtins: constant regular expressions over per-row strings", + graph: {nodes: [{expression: "calc", fields: {ok: "matches(code, '^[A-Z]{2}[0-9]+$')", digits: "extract(code, '[0-9]+')"}}]}, + cases: [ + [{code: "AB12"}, {ok: true, digits: ["12"]}], + [{code: "ab12"}, {ok: false, digits: ["12"]}], + [{code: "AB12"}, {ok: true, digits: ["12"]}], + [{code: "XY9"}, {ok: true, digits: ["9"]}], + [{code: "AB"}, {ok: false, digits: []}], + [{code: "AB12"}, {ok: true, digits: ["12"]}], + [{code: "XY9"}, {ok: true, digits: ["9"]}], + ], +} + +// --------------------------------------------------------------------------------------------- +// The clock: `d()`, `date('now')` and the now-relative helpers read one fixed instant +// (2025-03-20T10:15:30Z), mixed with per-row dates. +{ + name: "now: d() and date('now') beside per-row dates", + graph: {nodes: [{expression: "calc", fields: { + now: "d()", + legacy: "date('now')", + days: "d(s).diff(d(), 'd')", + past: "d(s) < d()", + sod: "d().startOf('day')", + inAWeek: "d().add(n ?? 7, 'd')", + }}]}, + cases: [ + [{s: "2025-03-21"}, {now: "2025-03-20T10:15:30Z", legacy: 1742465730, days: 0, past: false, sod: "2025-03-20T00:00:00Z", inAWeek: "2025-03-27T10:15:30Z"}], + [{s: "2025-03-22", n: 1}, {now: "2025-03-20T10:15:30Z", legacy: 1742465730, days: 1, past: false, sod: "2025-03-20T00:00:00Z", inAWeek: "2025-03-21T10:15:30Z"}], + [{s: "2025-03-21"}, {now: "2025-03-20T10:15:30Z", legacy: 1742465730, days: 0, past: false, sod: "2025-03-20T00:00:00Z", inAWeek: "2025-03-27T10:15:30Z"}], + [{s: "2025-03-19", n: 0}, {now: "2025-03-20T10:15:30Z", legacy: 1742465730, days: -1, past: true, sod: "2025-03-20T00:00:00Z", inAWeek: "2025-03-20T10:15:30Z"}], + [{s: "2025-03-20T10:15:30Z"}, {now: "2025-03-20T10:15:30Z", legacy: 1742465730, days: 0, past: false, sod: "2025-03-20T00:00:00Z", inAWeek: "2025-03-27T10:15:30Z"}], + [{s: "2024-03-20", n: -1}, {now: "2025-03-20T10:15:30Z", legacy: 1742465730, days: -365, past: true, sod: "2025-03-20T00:00:00Z", inAWeek: "2025-03-19T10:15:30Z"}], + [{s: "2025-03-21"}, {now: "2025-03-20T10:15:30Z", legacy: 1742465730, days: 0, past: false, sod: "2025-03-20T00:00:00Z", inAWeek: "2025-03-27T10:15:30Z"}], + ], +} + +{ + name: "now: isToday, isYesterday and isTomorrow over repeated dates", + graph: {nodes: [{expression: "calc", fields: {today: "d(s).isToday()", yday: "d(s).isYesterday()", tmrw: "d(s).isTomorrow()"}}]}, + cases: [ + [{s: "2025-03-20"}, {today: true, yday: false, tmrw: false}], + [{s: "2025-03-19"}, {today: false, yday: true, tmrw: false}], + [{s: "2025-03-21"}, {today: false, yday: false, tmrw: true}], + [{s: "2025-03-20"}, {today: true, yday: false, tmrw: false}], + [{s: "2025-03-20T23:59:59Z"}, {today: true, yday: false, tmrw: false}], + [{s: "2025-03-19"}, {today: false, yday: true, tmrw: false}], + [{s: "2025-03-22"}, {today: false, yday: false, tmrw: false}], + [{s: "2025-03-20"}, {today: true, yday: false, tmrw: false}], + ], +} + +{ + name: "now: a now-relative threshold in a table next to a per-row date", + graph: {nodes: [ + {expression: "parse", fields: {at: "d(at)"}}, + {table: "t", inputs: ["at"], outputs: ["bucket"], rules: [ + ["< d().sub(30, 'd')", "'stale'"], + ["< d()", "'recent'"], + ["", "'future'"], + ]}, + ]}, + cases: [ + [{at: "2025-01-01"}, {bucket: "stale"}], + [{at: "2025-03-01"}, {bucket: "recent"}], + [{at: "2025-01-01"}, {bucket: "stale"}], + [{at: "2025-04-01"}, {bucket: "future"}], + [{at: "2025-03-01"}, {bucket: "recent"}], + [{at: "2025-02-18T10:15:30Z"}, {bucket: "recent"}], + [{at: "2025-02-18T10:15:29Z"}, {bucket: "stale"}], + [{at: "2025-03-20T10:15:30Z"}, {bucket: "future"}], + [{at: "2025-01-01"}, {bucket: "stale"}], + [{at: "2025-04-01"}, {bucket: "future"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Optimizations meeting each other across nodes: a folded constant, a keyed category, a copy and a +// coalesced default flowing through a table and back into an expression. +{ + name: "combined: keyed categories, coalesced defaults and copies through a table", + graph: {nodes: [ + {expression: "prep", passThrough: true, fields: {segment: "segment ?? 'retail'", original: "order", qty: "order.qty ?? 1"}}, + {table: "rates", passThrough: true, inputs: ["segment"], outputs: ["rate"], rules: [ + ["'retail'", "0.10"], + ["'wholesale'", "0.25"], + ["", "0"], + ]}, + {expression: "final", fields: { + "order.total": "order.price * qty * (1 - rate)", + "order.qty": "qty", + original: "original", + tag: "upper(segment) + '/' + string(rate)", + }}, + ]}, + cases: [ + [{order: {price: 10, qty: 2}}, {order: {total: 18, qty: 2}, original: {price: 10, qty: 2}, tag: "RETAIL/0.10"}], + [{order: {price: 10}, segment: "wholesale"}, {order: {total: 7.5, qty: 1}, original: {price: 10}, tag: "WHOLESALE/0.25"}], + [{order: {price: 10, qty: 2}}, {order: {total: 18, qty: 2}, original: {price: 10, qty: 2}, tag: "RETAIL/0.10"}], + [{order: {price: 4, qty: 1}, segment: "vip"}, {order: {total: 4, qty: 1}, original: {price: 4, qty: 1}, tag: "VIP/0"}], + [{order: {price: 10}, segment: "wholesale"}, {order: {total: 7.5, qty: 1}, original: {price: 10}, tag: "WHOLESALE/0.25"}], + [{order: {price: 10, qty: 2}, segment: null}, {order: {total: 18, qty: 2}, original: {price: 10, qty: 2}, tag: "RETAIL/0.10"}], + [{order: {price: 0.99, qty: 3}}, {order: {total: 2.673, qty: 3}, original: {price: 0.99, qty: 3}, tag: "RETAIL/0.10"}], + [{order: {price: 10, qty: 2}, segment: "wholesale"}, {order: {total: 15, qty: 2}, original: {price: 10, qty: 2}, tag: "WHOLESALE/0.25"}], + [{order: {price: 10, qty: 2}}, {order: {total: 18, qty: 2}, original: {price: 10, qty: 2}, tag: "RETAIL/0.10"}], + [{order: {price: 4, qty: 1}, segment: "vip"}, {order: {total: 4, qty: 1}, original: {price: 4, qty: 1}, tag: "VIP/0"}], + [{order: {qty: 1}}, "!error"], + [{order: {price: 10}, segment: "wholesale"}, {order: {total: 7.5, qty: 1}, original: {price: 10}, tag: "WHOLESALE/0.25"}], + ], +} + +{ + name: "combined: a loop over repeated items with folded constants and per-item coalescing", + graph: {nodes: [ + {expression: "line", inputField: "items", outputPath: "lines", executionMode: "loop", fields: { + sku: "upper(sku ?? 'n/a')", + net: "(price ?? 0) * (qty ?? 1)", + vat: "(price ?? 0) * (qty ?? 1) * 0.2", + kind: "'line'", + }}, + ]}, + cases: [ + [{items: [{sku: "a", price: 10}, {sku: "a", price: 10}, {sku: "b", price: 5, qty: 2}]}, {lines: [ + {sku: "A", net: 10, vat: 2, kind: "line"}, + {sku: "A", net: 10, vat: 2, kind: "line"}, + {sku: "B", net: 10, vat: 2, kind: "line"}, + ]}], + [{items: [{}, {sku: "a"}]}, {lines: [ + {sku: "N/A", net: 0, vat: 0, kind: "line"}, + {sku: "A", net: 0, vat: 0, kind: "line"}, + ]}], + [{items: []}, {lines: []}], + [{items: [{sku: "a", price: 10}, {sku: "a", price: 10}, {sku: "b", price: 5, qty: 2}]}, {lines: [ + {sku: "A", net: 10, vat: 2, kind: "line"}, + {sku: "A", net: 10, vat: 2, kind: "line"}, + {sku: "B", net: 10, vat: 2, kind: "line"}, + ]}], + [{items: [{sku: "a", price: 1.5, qty: 3}]}, {lines: [{sku: "A", net: 4.5, vat: 0.9, kind: "line"}]}], + ], +} + +{ + name: "combined: a sub-decision called with repeated inputs returns per-row results", + decisions: { + child: {nodes: [{expression: "c", fields: {r: "k == 'x' ? v * 2 : v", tag: "upper(k)"}}]}, + }, + graph: {nodes: [{decision: "call", key: "child"}]}, + cases: [ + [{k: "x", v: 1}, {r: 2, tag: "X"}], + [{k: "x", v: 2}, {r: 4, tag: "X"}], + [{k: "y", v: 1}, {r: 1, tag: "Y"}], + [{k: "x", v: 1}, {r: 2, tag: "X"}], + [{k: "y", v: 1}, {r: 1, tag: "Y"}], + [{k: "x", v: 1}, {r: 2, tag: "X"}], + [{k: "y", v: 3}, {r: 3, tag: "Y"}], + [{k: "x", v: 2}, {r: 4, tag: "X"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// More keys that compare equal but are not the same value. +{ + name: "keyed: one instant written with different offsets and viewed in different zones", + graph: {nodes: [{expression: "calc", fields: { + utc: "d(s)", + local: "d(s).tz(zone)", + hour: "d(s).tz(zone).hour()", + textLen: "len(s)", + }}]}, + cases: [ + [{s: "2025-03-20T10:00:00Z", zone: "UTC"}, {utc: "2025-03-20T10:00:00Z", local: "2025-03-20T10:00:00Z", hour: 10, textLen: 20}], + [{s: "2025-03-20T12:00:00+02:00", zone: "UTC"}, {utc: "2025-03-20T10:00:00Z", local: "2025-03-20T10:00:00Z", hour: 10, textLen: 25}], + [{s: "2025-03-20T10:00:00Z", zone: "Asia/Tokyo"}, {utc: "2025-03-20T10:00:00Z", local: "2025-03-20T19:00:00+09:00", hour: 19, textLen: 20}], + [{s: "2025-03-20T10:00:00Z", zone: "UTC"}, {utc: "2025-03-20T10:00:00Z", local: "2025-03-20T10:00:00Z", hour: 10, textLen: 20}], + [{s: "2025-03-20T05:00:00-05:00", zone: "America/New_York"}, {utc: "2025-03-20T10:00:00Z", local: "2025-03-20T06:00:00-04:00", hour: 6, textLen: 25}], + [{s: "2025-03-20T12:00:00+02:00", zone: "Asia/Tokyo"}, {utc: "2025-03-20T10:00:00Z", local: "2025-03-20T19:00:00+09:00", hour: 19, textLen: 25}], + [{s: "2025-03-20T10:00:00Z", zone: "Asia/Tokyo"}, {utc: "2025-03-20T10:00:00Z", local: "2025-03-20T19:00:00+09:00", hour: 19, textLen: 20}], + [{s: "2025-03-20T10:00:00Z", zone: "UTC"}, {utc: "2025-03-20T10:00:00Z", local: "2025-03-20T10:00:00Z", hour: 10, textLen: 20}], + ], +} + +{ + name: "keyed: zero in its different spellings", + graph: {nodes: [{expression: "calc", fields: {s: "string(x)", z: "x == 0", neg: "x < 0", inv: "1 / x"}}]}, + cases: [ + [{x: 0}, {s: "0", z: true, neg: false}], + [{x: 0.0}, {s: "0.0", z: true, neg: false}], + [{x: -0}, {s: "0", z: true, neg: false}], + [{x: 0}, {s: "0", z: true, neg: false}], + [{x: 0.00}, {s: "0.00", z: true, neg: false}], + [{x: 1}, {s: "1", z: false, neg: false, inv: 1}], + [{x: 0.0}, {s: "0.0", z: true, neg: false}], + [{x: -1}, {s: "-1", z: false, neg: true, inv: -1}], + [{x: 0}, {s: "0", z: true, neg: false}], + ], +} + +{ + name: "coalesce: a defaulted column that is mostly the literal feeds a numeric table", + graph: {nodes: [ + {expression: "prep", fields: {score: "score ?? 50"}}, + {table: "t", passThrough: true, inputs: ["score"], outputs: ["band"], rules: [ + ["< 40", "'low'"], + ["[40..60]", "'mid'"], + ["> 60", "'high'"], + ["", "'not a number'"], + ]}, + ]}, + cases: [ + [{}, {score: 50, band: "mid"}], + [{}, {score: 50, band: "mid"}], + [{score: null}, {score: 50, band: "mid"}], + [{}, {score: 50, band: "mid"}], + [{score: 70}, {score: 70, band: "high"}], + [{}, {score: 50, band: "mid"}], + [{score: "70"}, {score: "70", band: "not a number"}], + [{}, {score: 50, band: "mid"}], + [{score: 10}, {score: 10, band: "low"}], + [{}, {score: 50, band: "mid"}], + [{score: true}, {score: true, band: "not a number"}], + [{}, {score: 50, band: "mid"}], + ], +} + +{ + name: "builtins: constant-argument calls and d() inside a loop and a sub-decision", + decisions: { + child: {nodes: [{expression: "c", fields: {now: "d()", base: "d('2024-01-01')", tag: "upper('k') + string(v)"}}]}, + }, + graph: {nodes: [ + {expression: "line", inputField: "items", outputPath: "lines", executionMode: "loop", fields: { + now: "d()", + base: "d('2024-01-01').add(v, 'd')", + tag: "upper('k') + string(v)", + }}, + {decision: "call", key: "child", outputPath: "child", inputField: "first"}, + ], edges: ["input -> line -> output", "input -> call -> output"]}, + cases: [ + [{items: [{v: 1}, {v: 2}, {v: 1}], first: {v: 9}}, { + lines: [ + {now: "2025-03-20T10:15:30Z", base: "2024-01-02T00:00:00Z", tag: "K1"}, + {now: "2025-03-20T10:15:30Z", base: "2024-01-03T00:00:00Z", tag: "K2"}, + {now: "2025-03-20T10:15:30Z", base: "2024-01-02T00:00:00Z", tag: "K1"}, + ], + child: {now: "2025-03-20T10:15:30Z", base: "2024-01-01T00:00:00Z", tag: "K9"}, + }], + [{items: [], first: {v: 0}}, {lines: [], child: {now: "2025-03-20T10:15:30Z", base: "2024-01-01T00:00:00Z", tag: "K0"}}], + [{items: [{v: 31}], first: {v: 1}}, { + lines: [{now: "2025-03-20T10:15:30Z", base: "2024-02-01T00:00:00Z", tag: "K31"}], + child: {now: "2025-03-20T10:15:30Z", base: "2024-01-01T00:00:00Z", tag: "K1"}, + }], + ], +} + +{ + name: "alias: loop items copied out and modified per item", + graph: {nodes: [ + {expression: "copy", passThrough: true, fields: {saved: "items"}}, + {expression: "mark", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {done: "true", n: "n * 2"}}, + ]}, + cases: [ + [{items: [{n: 1}, {n: 2}]}, {items: [{n: 2, done: true}, {n: 4, done: true}], saved: [{n: 1}, {n: 2}]}], + [{items: [{n: 1}, {n: 2}]}, {items: [{n: 2, done: true}, {n: 4, done: true}], saved: [{n: 1}, {n: 2}]}], + [{items: [{n: 1}]}, {items: [{n: 2, done: true}], saved: [{n: 1}]}], + [{items: []}, {items: [], saved: []}], + [{items: [{n: 1}, {n: 2}]}, {items: [{n: 2, done: true}, {n: 4, done: true}], saved: [{n: 1}, {n: 2}]}], + ], +} diff --git a/core/engine/tests/spec/graph/65-numbers-in-graphs.json5 b/core/engine/tests/spec/graph/65-numbers-in-graphs.json5 new file mode 100644 index 00000000..01694a4a --- /dev/null +++ b/core/engine/tests/spec/graph/65-numbers-in-graphs.json5 @@ -0,0 +1,543 @@ +// Numbers across nodes. Every number is an exact decimal (96-bit mantissa, up to 28 fractional +// digits, max 79228162514264337593543950335). These suites follow a number through tables, +// expression chains, loops and sub-decisions: its value and its scale (observed with `string()`) +// must survive every hop, rounding helpers round half away from zero, division by zero is null, +// overflow is an error of the node that overflows, and table cells compare numbers by value. +// 21-values pins single-node precision; here the interest is the hops between nodes. + +// --------------------------------------------------------------------------------------------- +// Scale preservation: the textual scale of a number survives tables, chains, loops and +// sub-decisions, and arithmetic produces the scale decimal arithmetic defines. +{ + name: "scale: a request number keeps its scale through a pass-through table and an expression", + graph: {nodes: [ + {table: "t", passThrough: true, inputs: ["kind"], outputs: ["seen"], rules: [["", "true"]]}, + {expression: "show", fields: {s: "string(amount)", v: "amount"}}, + ]}, + cases: [ + [{amount: 1.50, kind: "a"}, {s: "1.50", v: 1.5}], + [{amount: 2.000}, {s: "2.000", v: 2}], + [{amount: 0.10}, {s: "0.10", v: 0.1}], + [{amount: 100}, {s: "100", v: 100}], + [{amount: -0.0500}, {s: "-0.0500", v: -0.05}], + ], +} + +{ + name: "scale: a table output cell keeps the scale it is written with", + graph: {nodes: [ + {table: "t", inputs: ["band"], outputs: ["rate"], rules: [ + ["'a'", "1.50"], + ["'b'", "2.000"], + ["'c'", "0.1"], + ["", "5"], + ]}, + {expression: "show", fields: {s: "string(rate)", twice: "string(rate * 2)", plus: "string(rate + 1)"}}, + ]}, + cases: [ + [{band: "a"}, {s: "1.50", twice: "3.00", plus: "2.50"}], + [{band: "b"}, {s: "2.000", twice: "4.000", plus: "3.000"}], + [{band: "c"}, {s: "0.1", twice: "0.2", plus: "1.1"}], + [{band: "z"}, {s: "5", twice: "10", plus: "6"}], + ], +} + +{ + name: "scale: arithmetic scale follows decimal rules across a chain", + graph: {nodes: [ + {expression: "a", fields: {sum: "x + y", prod: "x * y", diff: "x - y"}}, + {expression: "b", fields: {sum: "string(sum)", prod: "string(prod)", diff: "string(diff)"}}, + ]}, + cases: [ + [{x: 1.10, y: 2.2}, {sum: "3.30", prod: "2.420", diff: "-1.10"}], + [{x: 1.5, y: 2}, {sum: "3.5", prod: "3.0", diff: "-0.5"}], + [{x: 0.25, y: 0.75}, {sum: "1.00", prod: "0.1875", diff: "-0.50"}], + [{x: 10, y: 0.010}, {sum: "10.010", prod: "0.100", diff: "9.990"}], + ], +} + +{ + name: "scale: a number crosses a sub-decision boundary unchanged", + decisions: { + child: {nodes: [{expression: "c", fields: {s: "string(v)", next: "v * 1"}}]}, + }, + graph: {nodes: [ + {decision: "call", key: "child"}, + {expression: "after", fields: {s: "s", next: "string(next)"}}, + ]}, + cases: [ + [{v: 1.50}, {s: "1.50", next: "1.50"}], + [{v: 3}, {s: "3", next: "3"}], + [{v: 0.000001}, {s: "0.000001", next: "0.000001"}], + [{v: 12345678901234567890.12}, {s: "12345678901234567890.12", next: "12345678901234567890.12"}], + ], +} + +{ + name: "scale: per-item numbers keep their scale through a loop node", + graph: {nodes: [ + {expression: "line", inputField: "items", outputPath: "lines", executionMode: "loop", fields: {s: "string(price)", total: "string(price * qty)"}}, + ]}, + cases: [ + [{items: [{price: 1.50, qty: 2}, {price: 2, qty: 1.5}, {price: 0.333, qty: 3}]}, {lines: [{s: "1.50", total: "3.00"}, {s: "2", total: "3.0"}, {s: "0.333", total: "0.999"}]}], + [{items: [{price: 9.99, qty: 0}]}, {lines: [{s: "9.99", total: "0.00"}]}, "bug: a zero product drops its scale (9.99 * 0 prints '0'), as zero sums do in the expression spec"], + [{items: []}, {lines: []}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Rounding helpers across nodes: half away from zero, a places argument read from the request, the +// rounded value feeding a table. +{ + name: "rounding: round, floor, ceil and trunc on positive and negative halves", + graph: {nodes: [{expression: "calc", fields: {r: "round(x)", f: "floor(x)", c: "ceil(x)", t: "trunc(x)", r1: "round(x, 1)"}}]}, + cases: [ + [{x: 0.5}, {r: 1, f: 0, c: 1, t: 0, r1: 0.5}], + [{x: -0.5}, {r: -1, f: -1, c: 0, t: 0, r1: -0.5}], + [{x: 1.45}, {r: 1, f: 1, c: 2, t: 1, r1: 1.5}], + [{x: -1.45}, {r: -1, f: -2, c: -1, t: -1, r1: -1.5}], + [{x: 2.55}, {r: 3, f: 2, c: 3, t: 2, r1: 2.6}], + [{x: 7}, {r: 7, f: 7, c: 7, t: 7, r1: 7}], + [{x: 0.04999}, {r: 0, f: 0, c: 1, t: 0, r1: 0}], + ], +} + +{ + name: "rounding: the number of places comes from the request", + graph: {nodes: [{expression: "calc", fields: {r: "round(x, p)", s: "string(round(x, p))"}}]}, + cases: [ + [{x: 3.14159, p: 0}, {r: 3, s: "3"}], + [{x: 3.14159, p: 2}, {r: 3.14, s: "3.14"}], + [{x: 3.14159, p: 4}, {r: 3.1416, s: "3.1416"}], + [{x: 3.14159, p: 10}, {r: 3.14159, s: "3.14159"}], + [{x: 2.5, p: 0}, {r: 3, s: "3"}], + [{x: 9.995, p: 2}, {r: 10, s: "10.00"}], + ], +} + +{ + name: "rounding: rounded money totals from a loop summed downstream", + graph: {nodes: [ + {expression: "line", inputField: "items", outputPath: "lines", executionMode: "loop", fields: {net: "round(price * qty * (1 - discount), 2)"}}, + {expression: "total", fields: {total: "sum(map(lines, #.net))", text: "string(sum(map(lines, #.net)))"}}, + ]}, + cases: [ + [{items: [{price: 19.99, qty: 3, discount: 0.15}, {price: 0.99, qty: 7, discount: 0}]}, {total: 57.90, text: "57.90"}], + [{items: [{price: 10, qty: 1, discount: 0.333}]}, {total: 6.67, text: "6.67"}], + [{items: [{price: 0.005, qty: 1, discount: 0}, {price: 0.005, qty: 1, discount: 0}]}, {total: 0.02, text: "0.02"}], + [{items: []}, {total: 0, text: "0"}], + ], +} + +{ + name: "rounding: a rounded score lands in the band the unrounded score misses", + graph: {nodes: [ + {expression: "score", passThrough: true, fields: {rounded: "round(raw)"}}, + {table: "band", inputs: ["raw", "rounded"], outputs: ["rawBand", "roundedBand"], hit: "collect", rules: [ + ["[0..50)", "", "'low'", ""], + ["[50..100]", "", "'high'", ""], + ["", "[0..50)", "", "'low'"], + ["", "[50..100]", "", "'high'"], + ]}, + ]}, + cases: [ + [{raw: 49.5}, [{rawBand: "low"}, {roundedBand: "high"}]], + [{raw: 49.49}, [{rawBand: "low"}, {roundedBand: "low"}]], + [{raw: 50}, [{rawBand: "high"}, {roundedBand: "high"}]], + [{raw: 99.5}, [{rawBand: "high"}, {roundedBand: "high"}]], + [{raw: 100.4}, [{roundedBand: "high"}]], + [{raw: 100.5}, []], + [{raw: -0.5}, []], + ], +} + +{ + name: "rounding: an allocation split three ways and the remainder", + graph: {nodes: [ + {expression: "split", passThrough: true, fields: {share: "floor(total / 3 * 100) / 100"}}, + {expression: "rest", fields: {share: "share", last: "total - share * 2", check: "share * 2 + (total - share * 2) == total"}}, + ]}, + cases: [ + [{total: 100}, {share: 33.33, last: 33.34, check: true}], + [{total: 10}, {share: 3.33, last: 3.34, check: true}], + [{total: 0.01}, {share: 0, last: 0.01, check: true}], + [{total: 9}, {share: 3, last: 3, check: true}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Division: exact where the quotient terminates, 28 digits where it does not, null on division by +// zero (so the field is dropped unless it is defaulted). +{ + name: "division: terminating and repeating quotients", + graph: {nodes: [{expression: "calc", fields: {q: "a / b"}}]}, + cases: [ + [{a: 10, b: 4}, {q: 2.5}], + [{a: 1, b: 3}, {q: 0.3333333333333333333333333333}], + [{a: 2, b: 3}, {q: 0.6666666666666666666666666667}], + [{a: 1, b: 8}, {q: 0.125}], + [{a: -7, b: 2}, {q: -3.5}], + [{a: 0.3, b: 0.1}, {q: 3}], + [{a: 1, b: 0.0001}, {q: 10000}], + ], +} + +{ + name: "division: a repeating quotient multiplied back in a later node", + graph: {nodes: [ + {expression: "a", fields: {third: "x / 3", x: "x"}}, + {expression: "b", fields: {back: "third * 3", rounded: "round(third * 3, 10)", equal: "round(third * 3, 10) == x"}}, + ]}, + cases: [ + [{x: 1}, {back: 0.9999999999999999999999999999, rounded: 1, equal: true}], + [{x: 2}, {back: 2.0000000000000000000000000001, rounded: 2, equal: true}], + [{x: 3}, {back: 3, rounded: 3, equal: true}], + [{x: 0}, {back: 0, rounded: 0, equal: true}], + ], +} + +{ + name: "division: by zero yields null, the field is dropped and a default can fill it", + graph: {nodes: [ + {expression: "ratio", passThrough: true, fields: {ratio: "a / b"}}, + {expression: "use", fields: {ratio: "ratio", safe: "ratio ?? 0", isNull: "ratio == null"}}, + ]}, + cases: [ + [{a: 1, b: 2}, {ratio: 0.5, safe: 0.5, isNull: false}], + [{a: 1, b: 0}, {safe: 0, isNull: true}], + [{a: 0, b: 0}, {safe: 0, isNull: true}], + [{a: -5, b: 0.0}, {safe: 0, isNull: true}], + [{a: 0, b: 5}, {ratio: 0, safe: 0, isNull: false}], + ], +} + +{ + name: "division: a null quotient in arithmetic downstream is an error", + graph: {nodes: [ + {expression: "ratio", fields: {ratio: "a / b"}}, + {expression: "pct", fields: {pct: "ratio * 100"}}, + ]}, + cases: [ + [{a: 1, b: 4}, {pct: 25}], + [{a: 1, b: 0}, "!error"], + [{a: 3, b: 3}, {pct: 100}], + ], +} + +{ + name: "division: modulo across signs and by zero", + graph: {nodes: [{expression: "calc", fields: {m: "a % b"}}]}, + cases: [ + [{a: 7, b: 3}, {m: 1}], + [{a: -7, b: 3}, {m: -1}], + [{a: 7, b: -3}, {m: 1}], + [{a: 7.5, b: 2}, {m: 1.5}], + [{a: 7, b: 0}, {}], + ], +} + +{ + name: "division: a ratio computed upstream drives a table", + graph: {nodes: [ + {expression: "dti", fields: {dti: "debt / income"}}, + {table: "t", inputs: ["dti"], outputs: ["decision"], rules: [ + ["<= 0.36", "'approve'"], + ["(0.36..0.43]", "'review'"], + ["> 0.43", "'decline'"], + ["", "'no income'"], + ]}, + ]}, + cases: [ + [{debt: 36, income: 100}, {decision: "approve"}], + [{debt: 1, income: 3}, {decision: "approve"}], + [{debt: 43, income: 100}, {decision: "review"}], + [{debt: 3, income: 7}, {decision: "review"}], + [{debt: 44, income: 100}, {decision: "decline"}], + [{debt: 10, income: 0}, {decision: "no income"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Magnitudes: the largest decimal passes through; arithmetic that leaves the range errors in the +// node that computes it; tiny values round to the 28th fractional digit. +{ + name: "magnitudes: the largest decimal passes through tables and expressions", + graph: {nodes: [ + {table: "t", passThrough: true, inputs: ["x"], outputs: ["big"], rules: [["> 0", "true"], ["", "false"]]}, + {expression: "e", fields: {same: "x", minus: "x - 1", s: "string(x)", big: "big"}}, + ]}, + cases: [ + [{x: 79228162514264337593543950335}, {same: 79228162514264337593543950335, minus: 79228162514264337593543950334, s: "79228162514264337593543950335", big: true}], + [{x: -79228162514264337593543950335}, "!error"], + ], +} + +{ + name: "magnitudes: overflow fails the node that overflows, not the one before", + graph: {nodes: [ + {expression: "a", fields: {x: "x * 1000"}}, + {expression: "b", fields: {x: "x * 1000"}}, + ]}, + cases: [ + [{x: 1}, {x: 1000000}], + [{x: 79228162514264337593543950}, "!error: \"nodeId\":\"b\""], + [{x: 79228162514264337593543951}, "!error: \"nodeId\":\"a\""], + [{x: 79228162514264337593543950335}, "!error: \"nodeId\":\"a\""], + ], +} + +{ + name: "magnitudes: overflow in a table output cell skips the row", + graph: {nodes: [ + {table: "t", inputs: ["k"], outputs: ["v"], rules: [ + ["'big'", "x * x"], + ["", "x"], + ]}, + ]}, + cases: [ + [{k: "small", x: 79228162514264337593543950335}, {v: 79228162514264337593543950335}], + [{k: "big", x: 1000}, {v: 1000000}], + [{k: "big", x: 10000000000000000}, {v: 10000000000000000}, "question: an overflowing output cell turns its row into a non-match and the catch-all wins, instead of failing the node (see 07)"], + ], +} + +{ + name: "magnitudes: a sum over many large values overflows", + graph: {nodes: [{expression: "calc", fields: {total: "sum(xs)"}}]}, + cases: [ + [{xs: [39614081257132168796771975167, 39614081257132168796771975168]}, {total: 79228162514264337593543950335}], + [{xs: [39614081257132168796771975168, 39614081257132168796771975168]}, "!error"], + [{xs: [79228162514264337593543950335, -1, 1]}, {total: 79228162514264337593543950335}], + ], +} + +{ + name: "magnitudes: tiny values and products below the smallest step", + graph: {nodes: [ + {expression: "a", fields: {p: "x * y"}}, + {expression: "b", fields: {p: "p", zero: "p == 0", s: "string(p)"}}, + ]}, + cases: [ + [{x: 0.0000000000000000000000000001, y: 1}, {p: 0.0000000000000000000000000001, zero: false, s: "0.0000000000000000000000000001"}], + [{x: 0.00000000000001, y: 0.00000000000001}, {p: 0.0000000000000000000000000001, zero: false, s: "0.0000000000000000000000000001"}], + [{x: 0.0000000000000000000000000001, y: 0.1}, {p: 0, zero: true, s: "0.0000000000000000000000000000"}], + [{x: 0.0000000000000000000000000001, y: 0.5}, {p: 0, zero: true, s: "0.0000000000000000000000000000"}], + ], +} + +{ + name: "magnitudes: values with 28 fractional digits survive a chain of nodes", + graph: {nodes: [ + {expression: "a", passThrough: true, fields: {y: "x + 0.0000000000000000000000000001"}}, + {table: "t", passThrough: true, inputs: ["y"], outputs: ["above"], rules: [["> x", "true"], ["", "false"]]}, + {expression: "c", fields: {y: "y", above: "above", gap: "y - x"}}, + ]}, + cases: [ + [{x: 1}, {y: 1.0000000000000000000000000001, above: true, gap: 0.0000000000000000000000000001}], + [{x: 0}, {y: 0.0000000000000000000000000001, above: true, gap: 0.0000000000000000000000000001}], + [{x: -1}, {y: -0.9999999999999999999999999999, above: true, gap: 0.0000000000000000000000000001}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Numbers carried as strings: a numeric string is a string until it is converted. number() keeps +// the scale of the text, rejects malformed text, and the converted value behaves as a number in +// tables and arithmetic downstream. +{ + name: "strings: number() converts upstream and the next node does arithmetic", + graph: {nodes: [ + {expression: "parse", fields: {amount: "number(amount)"}}, + {expression: "use", fields: {double: "amount * 2", s: "string(amount)"}}, + ]}, + cases: [ + [{amount: "12"}, {double: 24, s: "12"}], + [{amount: "1.50"}, {double: 3, s: "1.50"}], + [{amount: " -0.25 "}, {double: -0.5, s: "-0.25"}], + [{amount: "1e3"}, {double: 2000, s: "1000"}], + [{amount: 7}, {double: 14, s: "7"}], + [{amount: "1,000"}, "!error"], + [{amount: ""}, "!error"], + [{}, "!error"], + ], +} + +{ + name: "strings: a numeric string meets a numeric table only after conversion", + graph: {nodes: [ + {table: "raw", passThrough: true, inputs: ["v"], outputs: ["rawHit"], rules: [["> 10", "true"], ["", "false"]]}, + {table: "converted", passThrough: true, inputs: ["number(v)"], outputs: ["convHit"], rules: [["> 10", "true"], ["", "false"]]}, + {expression: "out", fields: {rawHit: "rawHit", convHit: "convHit"}}, + ]}, + cases: [ + [{v: "20"}, {rawHit: false, convHit: true}], + [{v: 20}, {rawHit: true, convHit: true}], + [{v: "5"}, {rawHit: false, convHit: false}], + [{v: "10.01"}, {rawHit: false, convHit: true}], + ], +} + +{ + name: "strings: isNumeric guards a conversion of mixed rows", + graph: {nodes: [{expression: "calc", fields: {n: "isNumeric(v) ? number(v) : 0", ok: "isNumeric(v)"}}]}, + cases: [ + [{v: "42"}, {n: 42, ok: true}], + [{v: "4.20"}, {n: 4.2, ok: true}], + [{v: "abc"}, {n: 0, ok: false}], + [{v: ""}, {n: 0, ok: false}], + [{v: 3}, {n: 3, ok: true}], + [{v: null}, {n: 0, ok: false}], + ], +} + +{ + name: "strings: a number turned into a string and back keeps its value", + graph: {nodes: [ + {expression: "a", fields: {text: "string(x)"}}, + {expression: "b", fields: {back: "number(text)", same: "number(text) == x", text: "text"}}, + ]}, + cases: [ + [{x: 1.50}, {back: 1.5, same: false, text: "1.50"}], + [{x: 0.1}, {back: 0.1, same: false, text: "0.1"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Integer and decimal forms compare by value in table cells, switch conditions and membership. +{ + name: "equality: an integer cell matches decimal forms of the same value", + graph: {nodes: [ + {table: "t", inputs: ["v"], outputs: ["hit"], rules: [ + ["1", "'one'"], + ["2.0", "'two'"], + ["2.50", "'two and a half'"], + ["", "'other'"], + ]}, + ]}, + cases: [ + [{v: 1}, {hit: "one"}], + [{v: 1.0}, {hit: "one"}], + [{v: 1.000}, {hit: "one"}], + [{v: 2}, {hit: "two"}], + [{v: 2.00}, {hit: "two"}], + [{v: 2.5}, {hit: "two and a half"}], + [{v: 2.500}, {hit: "two and a half"}], + [{v: 1.0000000000000000000000000001}, {hit: "other"}], + [{v: "1"}, {hit: "other"}], + ], +} + +{ + name: "equality: list cells and negated cells with mixed scales", + graph: {nodes: [ + {table: "t", inputs: ["v"], outputs: ["hit"], rules: [ + ["1, 2.0, 3.00", "'listed'"], + ["!= 4", "'not four'"], + ["", "'four'"], + ]}, + ]}, + cases: [ + [{v: 1.0}, {hit: "listed"}], + [{v: 2}, {hit: "listed"}], + [{v: 3}, {hit: "listed"}], + [{v: 4.00}, {hit: "four"}], + [{v: 4}, {hit: "four"}], + [{v: 5}, {hit: "not four"}], + ], +} + +{ + name: "equality: a computed decimal meets integer point cells in an indexed table", + graph: {nodes: [ + {expression: "calc", fields: {code: "a * b"}}, + {table: "t", inputs: ["code"], outputs: ["label"], rules: [ + ["1", "'c1'"], ["2", "'c2'"], ["3", "'c3'"], ["4", "'c4'"], ["5", "'c5'"], + ["6", "'c6'"], ["7", "'c7'"], ["8", "'c8'"], ["9", "'c9'"], ["10", "'c10'"], + ["", "'none'"], + ]}, + ]}, + cases: [ + [{a: 0.5, b: 4}, {label: "c2"}], + [{a: 2.5, b: 2}, {label: "c5"}], + [{a: 1.10, b: 10}, {label: "none"}], + [{a: 0.3, b: 10}, {label: "c3"}], + [{a: 3.3, b: 3}, {label: "none"}], + [{a: 1, b: 10}, {label: "c10"}], + ], +} + +{ + name: "equality: switch conditions and membership compare by value", + graph: { + nodes: [ + {switch: "s", when: ["v == 1", "v in [2, 3.0]", ""]}, + {expression: "one", fields: {r: "'one'"}}, + {expression: "list", fields: {r: "'list'"}}, + {expression: "other", fields: {r: "'other'"}}, + ], + edges: ["input -> s", "s:0 -> one -> output", "s:1 -> list -> output", "s:2 -> other -> output"], + }, + cases: [ + [{v: 1.00}, {r: "one"}], + [{v: 2.0}, {r: "list"}], + [{v: 3}, {r: "list"}], + [{v: 3.000}, {r: "list"}], + [{v: "3"}, {r: "other"}], + [{v: 4}, {r: "other"}], + ], +} + +{ + name: "equality: interval boundaries with trailing zeros", + graph: {nodes: [ + {table: "t", inputs: ["v"], outputs: ["in"], rules: [ + ["[1.0..2.00]", "true"], + ["", "false"], + ]}, + ]}, + cases: [ + [{v: 1}, {in: true}], + [{v: 2}, {in: true}], + [{v: 2.000}, {in: true}], + [{v: 0.99999}, {in: false}], + [{v: 2.0000000000000000000000000001}, {in: false}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Aggregates of decimals across nodes. +{ + name: "aggregates: sum, avg, min and max over decimals from a loop", + graph: {nodes: [ + {expression: "line", inputField: "items", outputPath: "lines", executionMode: "loop", fields: {v: "price * qty"}}, + {expression: "agg", fields: { + sum: "sum(map(lines, #.v))", + avg: "avg(map(lines, #.v))", + min: "min(map(lines, #.v))", + max: "max(map(lines, #.v))", + }}, + ]}, + cases: [ + [{items: [{price: 0.1, qty: 1}, {price: 0.2, qty: 1}, {price: 0.3, qty: 1}]}, {sum: 0.6, avg: 0.2, min: 0.1, max: 0.3}], + [{items: [{price: 1, qty: 1}, {price: 1, qty: 1}, {price: 2, qty: 1}]}, {sum: 4, avg: 1.3333333333333333333333333333, min: 1, max: 2}], + [{items: [{price: -1.5, qty: 2}, {price: 1.5, qty: 2}]}, {sum: 0, avg: 0, min: -3, max: 3}], + [{items: [{price: 9.99, qty: 3}]}, {sum: 29.97, avg: 29.97, min: 29.97, max: 29.97}], + ], +} + +{ + name: "aggregates: collected table outputs summed downstream", + graph: {nodes: [ + {table: "fees", hit: "collect", inputs: ["amount"], outputs: ["fee"], rules: [ + ["> 0", "0.30"], + ["> 100", "amount * 0.029"], + ["> 1000", "amount * 0.001"], + ]}, + {expression: "sum", fields: {total: "sum(map($root, #.fee))", count: "len($root)"}}, + ]}, + cases: [ + [{amount: 50}, {total: 0.3, count: 1}], + [{amount: 200}, {total: 6.1, count: 2}], + [{amount: 2000}, {total: 60.3, count: 3}], + [{amount: 0}, {total: 0, count: 0}], + ], +} diff --git a/core/engine/tests/spec/graph/66-dates-in-graphs.json5 b/core/engine/tests/spec/graph/66-dates-in-graphs.json5 new file mode 100644 index 00000000..8c817f8c --- /dev/null +++ b/core/engine/tests/spec/graph/66-dates-in-graphs.json5 @@ -0,0 +1,474 @@ +// Dates across nodes. A date built with `d(...)` is a date value: it flows into the next expression +// node, a table cell or a loop item as a date and renders as ISO text only in the result. The clock +// is fixed at 2025-03-20T10:15:30Z (a Thursday), time zone UTC. Weeks start on Monday; month +// arithmetic clamps to the last day of the target month; `diff` truncates toward zero. 21-values +// and 28-table-dates pin single-node behaviour; these suites chain the operations across nodes. + +// --------------------------------------------------------------------------------------------- +// Arithmetic chains: add, sub, startOf/endOf and diff spread over several nodes. +{ + name: "chains: add months, end of month, then the distance in days", + graph: {nodes: [ + {expression: "shift", fields: {start: "d(start)", moved: "d(start).add(n, 'month')"}}, + {expression: "eom", passThrough: true, fields: {eom: "moved.endOf('month')"}}, + {expression: "dist", fields: {moved: "moved", eom: "eom", days: "eom.diff(start, 'day')"}}, + ]}, + cases: [ + [{start: "2024-01-31", n: 1}, {moved: "2024-02-29T00:00:00Z", eom: "2024-02-29T23:59:59Z", days: 29}], + [{start: "2025-01-15", n: 1}, {moved: "2025-02-15T00:00:00Z", eom: "2025-02-28T23:59:59Z", days: 44}], + [{start: "2024-12-31", n: 2}, {moved: "2025-02-28T00:00:00Z", eom: "2025-02-28T23:59:59Z", days: 59}], + [{start: "2024-03-31", n: -1}, {moved: "2024-02-29T00:00:00Z", eom: "2024-02-29T23:59:59Z", days: -30}], + [{start: "2025-06-10T15:00:00Z", n: 0}, {moved: "2025-06-10T15:00:00Z", eom: "2025-06-30T23:59:59Z", days: 20}], + ], +} + +{ + name: "chains: month clamping step by step differs from one jump", + graph: {nodes: [ + {expression: "one", fields: {one: "d(s).add(1, 'month')", s: "s"}}, + {expression: "two", fields: {stepwise: "one.add(1, 'month')", direct: "d(s).add(2, 'month')"}}, + ]}, + cases: [ + [{s: "2025-01-31"}, {stepwise: "2025-03-28T00:00:00Z", direct: "2025-03-31T00:00:00Z"}], + [{s: "2024-01-31"}, {stepwise: "2024-03-29T00:00:00Z", direct: "2024-03-31T00:00:00Z"}], + [{s: "2024-08-31"}, {stepwise: "2024-10-30T00:00:00Z", direct: "2024-10-31T00:00:00Z"}], + [{s: "2025-03-15"}, {stepwise: "2025-05-15T00:00:00Z", direct: "2025-05-15T00:00:00Z"}], + [{s: "2023-12-31T08:30:00Z"}, {stepwise: "2024-02-29T08:30:00Z", direct: "2024-02-29T08:30:00Z"}], + ], +} + +{ + name: "chains: add then sub returns to the start except across a month clamp", + graph: {nodes: [ + {expression: "fwd", passThrough: true, fields: {fwd: "d(s).add(n, unit)"}}, + {expression: "back", fields: {back: "fwd.sub(n, unit)", same: "fwd.sub(n, unit) == d(s)"}}, + ]}, + cases: [ + [{s: "2025-03-20", n: 10, unit: "d"}, {back: "2025-03-20T00:00:00Z", same: true}], + [{s: "2025-03-20T10:00:00Z", n: 36, unit: "h"}, {back: "2025-03-20T10:00:00Z", same: true}], + [{s: "2025-03-20", n: 3, unit: "w"}, {back: "2025-03-20T00:00:00Z", same: true}], + [{s: "2025-01-31", n: 1, unit: "month"}, {back: "2025-01-28T00:00:00Z", same: false}], + [{s: "2024-02-29", n: 1, unit: "year"}, {back: "2024-02-28T00:00:00Z", same: false}, "bug: adding or subtracting a year from Feb 29 gives an invalid date instead of clamping to Feb 28 as months do (expression spec)"], + [{s: "2025-05-31", n: 1, unit: "quarter"}, {back: "2025-05-31T00:00:00Z", same: true}], + ], +} + +{ + name: "chains: start and end of week, quarter and year on a date built upstream", + graph: {nodes: [ + {expression: "parse", fields: {at: "d(s)"}}, + {expression: "bounds", fields: { + wk: "at.startOf('week')", + wkEnd: "at.endOf('week')", + q: "at.startOf('quarter')", + yEnd: "at.endOf('year')", + dow: "at.weekday()", + }}, + ]}, + cases: [ + [{s: "2025-03-20T10:15:30Z"}, {wk: "2025-03-17T00:00:00Z", wkEnd: "2025-03-23T23:59:59Z", q: "2025-01-01T00:00:00Z", yEnd: "2025-12-31T23:59:59Z", dow: 4}], + [{s: "2025-10-26"}, {wk: "2025-10-20T00:00:00Z", wkEnd: "2025-10-26T23:59:59Z", q: "2025-10-01T00:00:00Z", yEnd: "2025-12-31T23:59:59Z", dow: 7}], + [{s: "2024-02-29"}, {wk: "2024-02-26T00:00:00Z", wkEnd: "2024-03-03T23:59:59Z", q: "2024-01-01T00:00:00Z", yEnd: "2024-12-31T23:59:59Z", dow: 4}], + [{s: "2024-12-30"}, {wk: "2024-12-30T00:00:00Z", wkEnd: "2025-01-05T23:59:59Z", q: "2024-10-01T00:00:00Z", yEnd: "2024-12-31T23:59:59Z", dow: 1}], + ], +} + +{ + name: "chains: comparisons between two dates built upstream", + graph: {nodes: [ + {expression: "parse", fields: {a: "d(a)", b: "d(b)"}}, + {expression: "cmp", fields: { + before: "a.isBefore(b)", + after: "a.isAfter(b)", + sameDay: "a.isSame(b, 'day')", + sameMonth: "a.isSame(b, 'month')", + sob: "a.isSameOrBefore(b)", + lt: "a < b", + }}, + ]}, + cases: [ + [{a: "2025-03-20T08:00:00Z", b: "2025-03-20T20:00:00Z"}, {before: true, after: false, sameDay: true, sameMonth: true, sob: true, lt: true}], + [{a: "2025-03-31", b: "2025-04-01"}, {before: true, after: false, sameDay: false, sameMonth: false, sob: true, lt: true}], + [{a: "2025-04-01", b: "2025-03-31"}, {before: false, after: true, sameDay: false, sameMonth: false, sob: false, lt: false}], + [{a: "2025-01-01", b: "2025-01-01T00:00:00Z"}, {before: false, after: false, sameDay: true, sameMonth: true, sob: true, lt: false}], + [{a: "2024-03-15", b: "2025-03-15"}, {before: true, after: false, sameDay: false, sameMonth: false, sob: true, lt: true}], + ], +} + +{ + name: "chains: a computed due date formatted at the end of the chain", + graph: {nodes: [ + {expression: "due", fields: {due: "d(s).add(30, 'd')"}}, + {expression: "fmt", fields: { + text: "due.format('%Y-%m-%d')", + long: "due.format('%A, %-d %B %Y')", + stamp: "due.format('%Y-%m-%dT%H:%M:%S')", + }}, + ]}, + cases: [ + [{s: "2025-03-20"}, {text: "2025-04-19", long: "Saturday, 19 April 2025", stamp: "2025-04-19T00:00:00"}], + [{s: "2024-02-01"}, {text: "2024-03-02", long: "Saturday, 2 March 2024", stamp: "2024-03-02T00:00:00"}], + [{s: "2025-12-15T13:45:00Z"}, {text: "2026-01-14", long: "Wednesday, 14 January 2026", stamp: "2026-01-14T13:45:00"}], + ], +} + +{ + name: "chains: set and date parts across nodes", + graph: {nodes: [ + {expression: "first", fields: {payday: "d(s).set('day', 25)"}}, + {expression: "parts", fields: {payday: "payday", y: "payday.year()", m: "payday.month()", q: "payday.quarter()", doy: "payday.dayOfYear()", leap: "payday.isLeapYear()"}}, + ]}, + cases: [ + [{s: "2025-03-20"}, {payday: "2025-03-25T00:00:00Z", y: 2025, m: 3, q: 1, doy: 84, leap: false}], + [{s: "2024-12-01T09:00:00Z"}, {payday: "2024-12-25T09:00:00Z", y: 2024, m: 12, q: 4, doy: 360, leap: true}], + [{s: "2025-07-31"}, {payday: "2025-07-25T00:00:00Z", y: 2025, m: 7, q: 3, doy: 206, leap: false}], + ], +} + +// --------------------------------------------------------------------------------------------- +// The fixed clock: rules relative to now. d() is 2025-03-20T10:15:30Z everywhere in a run. +{ + name: "now: an age computed upstream and banded in a table", + graph: {nodes: [ + {expression: "age", fields: {age: "d().diff(d(dob), 'year')"}}, + {table: "band", passThrough: true, inputs: ["age"], outputs: ["band"], rules: [ + ["< 18", "'minor'"], + ["[18..65)", "'adult'"], + ["", "'senior'"], + ]}, + ]}, + cases: [ + [{dob: "2007-03-20"}, {age: 18, band: "adult"}], + [{dob: "2007-03-21"}, {age: 17, band: "minor"}], + [{dob: "1960-03-20"}, {age: 65, band: "senior"}], + [{dob: "1960-03-21"}, {age: 64, band: "adult"}], + [{dob: "2025-03-20"}, {age: 0, band: "minor"}], + [{dob: "2007-03-20T10:15:31Z"}, {age: 17, band: "minor"}], + ], +} + +{ + name: "now: days left until expiry drive a status table", + graph: {nodes: [ + {expression: "left", fields: {daysLeft: "d(expires).diff(d().startOf('day'), 'd')"}}, + {table: "status", passThrough: true, inputs: ["daysLeft"], outputs: ["status"], rules: [ + ["< 0", "'expired'"], + ["[0..7]", "'expiring'"], + ["", "'active'"], + ]}, + ]}, + cases: [ + [{expires: "2025-03-19"}, {daysLeft: -1, status: "expired"}], + [{expires: "2025-03-20"}, {daysLeft: 0, status: "expiring"}], + [{expires: "2025-03-20T23:59:59Z"}, {daysLeft: 0, status: "expiring"}], + [{expires: "2025-03-27"}, {daysLeft: 7, status: "expiring"}], + [{expires: "2025-03-28"}, {daysLeft: 8, status: "active"}], + [{expires: "2025-02-01"}, {daysLeft: -47, status: "expired"}], + ], +} + +{ + name: "now: windows relative to now in a collect table", + graph: {nodes: [ + {table: "windows", hit: "collect", inputs: ["d(at)"], outputs: ["w"], rules: [ + ["[d().startOf('month')..d().endOf('month')]", "'this month'"], + [">= d().startOf('week')", "'since monday'"], + ["< d().startOf('year')", "'last year or older'"], + ]}, + ]}, + cases: [ + [{at: "2025-03-17"}, [{w: "this month"}, {w: "since monday"}]], + [{at: "2025-03-16T23:59:59Z"}, [{w: "this month"}]], + [{at: "2024-12-31T23:59:59Z"}, [{w: "last year or older"}]], + [{at: "2025-03-31T23:59:59Z"}, [{w: "this month"}, {w: "since monday"}]], + [{at: "2025-04-01"}, [{w: "since monday"}]], + [{at: "2025-02-15"}, []], + ], +} + +{ + name: "now: now in named time zones", + graph: {nodes: [{expression: "calc", fields: {local: "d(zone)", hour: "d(zone).hour()", same: "d(zone) == d()", day: "d(zone).format('%Y-%m-%d')"}}]}, + cases: [ + [{zone: "Europe/Berlin"}, {local: "2025-03-20T11:15:30+01:00", hour: 11, same: true, day: "2025-03-20"}], + [{zone: "America/New_York"}, {local: "2025-03-20T06:15:30-04:00", hour: 6, same: true, day: "2025-03-20"}], + [{zone: "Asia/Tokyo"}, {local: "2025-03-20T19:15:30+09:00", hour: 19, same: true, day: "2025-03-20"}], + [{zone: "Asia/Kolkata"}, {local: "2025-03-20T15:45:30+05:30", hour: 15, same: true, day: "2025-03-20"}], + [{zone: "Pacific/Kiritimati"}, {local: "2025-03-21T00:15:30+14:00", hour: 0, same: true, day: "2025-03-21"}], + ], +} + +{ + name: "now: isToday, isYesterday and isTomorrow on dates built upstream", + graph: {nodes: [ + {expression: "parse", fields: {at: "d(s)"}}, + {switch: "when", when: ["at.isYesterday()", "at.isToday()", "at.isTomorrow()", ""]}, + {expression: "y", fields: {r: "'yesterday'"}}, + {expression: "t", fields: {r: "'today'"}}, + {expression: "m", fields: {r: "'tomorrow'"}}, + {expression: "o", fields: {r: "'other'"}}, + ], + edges: ["input -> parse -> when", "when:0 -> y -> output", "when:1 -> t -> output", "when:2 -> m -> output", "when:3 -> o -> output"]}, + cases: [ + [{s: "2025-03-19T23:59:59Z"}, {r: "yesterday"}], + [{s: "2025-03-20T00:00:00Z"}, {r: "today"}], + [{s: "2025-03-20T23:59:59Z"}, {r: "today"}], + [{s: "2025-03-21"}, {r: "tomorrow"}], + [{s: "2025-03-22"}, {r: "other"}], + [{s: "2025-03-20T23:30:00-05:00"}, {r: "tomorrow"}], + [{s: "garbage"}, {r: "other"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Time zones: offset strings are instants (rendered in UTC); `d(s, zone)` keeps the zone through +// later nodes; `tz()` converts; comparisons are by instant. +{ + name: "zones: offset strings normalize to UTC and keep that through later nodes", + graph: {nodes: [ + {expression: "parse", fields: {at: "d(s)"}}, + {expression: "use", fields: {at: "at", day: "at.format('%Y-%m-%d')", hour: "at.hour()", today: "at.isToday()"}}, + ]}, + cases: [ + [{s: "2025-03-20T23:30:00-05:00"}, {at: "2025-03-21T04:30:00Z", day: "2025-03-21", hour: 4, today: false}], + [{s: "2025-03-21T01:00:00+02:00"}, {at: "2025-03-20T23:00:00Z", day: "2025-03-20", hour: 23, today: true}], + [{s: "2025-03-20T00:00:00+14:00"}, {at: "2025-03-19T10:00:00Z", day: "2025-03-19", hour: 10, today: false}], + [{s: "2025-03-20T10:15:30Z"}, {at: "2025-03-20T10:15:30Z", day: "2025-03-20", hour: 10, today: true}], + [{s: "2025-03-20T05:45:00+05:45"}, {at: "2025-03-20T00:00:00Z", day: "2025-03-20", hour: 0, today: true}], + ], +} + +{ + name: "zones: a zoned date keeps its zone in later nodes", + graph: {nodes: [ + {expression: "parse", fields: {local: "d(s, zone)"}}, + {expression: "use", fields: {local: "local", sod: "local.startOf('day')", utc: "local.tz('UTC')", h: "local.hour()"}}, + ]}, + cases: [ + [{s: "2025-03-20 08:00", zone: "Europe/Berlin"}, {local: "2025-03-20T08:00:00+01:00", sod: "2025-03-20T00:00:00+01:00", utc: "2025-03-20T07:00:00Z", h: 8}], + [{s: "2025-07-01 08:00", zone: "Europe/Berlin"}, {local: "2025-07-01T08:00:00+02:00", sod: "2025-07-01T00:00:00+02:00", utc: "2025-07-01T06:00:00Z", h: 8}], + [{s: "2025-03-20 08:00", zone: "America/New_York"}, {local: "2025-03-20T08:00:00-04:00", sod: "2025-03-20T00:00:00-04:00", utc: "2025-03-20T12:00:00Z", h: 8}], + [{s: "2025-03-20 08:00", zone: "Asia/Tokyo"}, {local: "2025-03-20T08:00:00+09:00", sod: "2025-03-20T00:00:00+09:00", utc: "2025-03-19T23:00:00Z", h: 8}], + ], +} + +{ + name: "zones: instants with different offsets compared in a table", + graph: {nodes: [ + {expression: "parse", fields: {a: "d(a)", b: "d(b)"}}, + {table: "cmp", inputs: ["a"], outputs: ["r"], rules: [ + ["< b", "'earlier'"], + ["b", "'same'"], + ["", "'later'"], + ]}, + ]}, + cases: [ + [{a: "2025-03-20T12:00:00+02:00", b: "2025-03-20T10:00:00Z"}, {r: "same"}], + [{a: "2025-03-20T12:00:00+01:00", b: "2025-03-20T12:00:00Z"}, {r: "earlier"}], + [{a: "2025-03-20T09:00:00-05:00", b: "2025-03-20T12:00:00Z"}, {r: "later"}], + [{a: "2025-03-20T00:00:00+09:00", b: "2025-03-19T15:00:00Z"}, {r: "same"}], + ], +} + +{ + name: "zones: the day of an instant depends on the zone it is viewed in", + graph: {nodes: [ + {expression: "at", fields: {at: "d(s)"}}, + {expression: "days", fields: { + utc: "at.format('%Y-%m-%d')", + tokyo: "at.tz('Asia/Tokyo').format('%Y-%m-%d')", + ny: "at.tz('America/New_York').format('%Y-%m-%d')", + sameInstant: "at.tz('Asia/Tokyo') == at", + }}, + ]}, + cases: [ + [{s: "2025-03-20T02:00:00Z"}, {utc: "2025-03-20", tokyo: "2025-03-20", ny: "2025-03-19", sameInstant: true}], + [{s: "2025-03-20T16:00:00Z"}, {utc: "2025-03-20", tokyo: "2025-03-21", ny: "2025-03-20", sameInstant: true}], + [{s: "2025-03-20T12:00:00Z"}, {utc: "2025-03-20", tokyo: "2025-03-20", ny: "2025-03-20", sameInstant: true}], + ], +} + +{ + name: "zones: schema date-time fields with offsets compared to now", + graph: {nodes: [ + {input: "request", schema: {type: "object", properties: {at: {type: "string", format: "date-time"}}}}, + {expression: "calc", fields: {past: "d(at) < d()", hours: "d().diff(d(at), 'hour')"}}, + ]}, + cases: [ + [{at: "2025-03-20T12:15:30+02:00"}, {past: false, hours: 0}], + [{at: "2025-03-20T05:15:30-05:00"}, {past: false, hours: 0}], + [{at: "2025-03-20T04:15:30-05:00"}, {past: true, hours: 1}], + [{at: "2025-03-19T10:15:30Z"}, {past: true, hours: 24}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dates inside loops and tables. +{ + name: "loops: per-invoice due dates and lateness aggregated afterwards", + graph: {nodes: [ + {expression: "line", inputField: "items", outputPath: "lines", executionMode: "loop", fields: { + due: "d(issued).add(terms, 'd')", + overdue: "d(issued).add(terms, 'd') < d()", + daysLate: "d(issued).add(terms, 'd') < d() ? d().diff(d(issued).add(terms, 'd'), 'd') : 0", + }}, + {expression: "agg", passThrough: true, fields: {overdueCount: "count(lines, #.overdue)", maxLate: "max(map(lines, #.daysLate))"}}, + ]}, + cases: [ + [ + {items: [{issued: "2025-01-01", terms: 30}, {issued: "2025-03-01", terms: 30}, {issued: "2025-02-15", terms: 14}]}, + {lines: [ + {due: "2025-01-31T00:00:00Z", overdue: true, daysLate: 48}, + {due: "2025-03-31T00:00:00Z", overdue: false, daysLate: 0}, + {due: "2025-03-01T00:00:00Z", overdue: true, daysLate: 19}, + ], overdueCount: 2, maxLate: 48}, + ], + [{items: [{issued: "2025-03-20", terms: 0}]}, {lines: [{due: "2025-03-20T00:00:00Z", overdue: true, daysLate: 0}], overdueCount: 1, maxLate: 0}], + [{items: [{issued: "2024-02-29", terms: 365}]}, {lines: [{due: "2025-02-28T00:00:00Z", overdue: true, daysLate: 20}], overdueCount: 1, maxLate: 20}], + ], +} + +{ + name: "loops: a table per item buckets dates by the current month", + graph: {nodes: [ + {table: "bucket", inputField: "items", outputPath: "buckets", executionMode: "loop", inputs: ["d(at)"], outputs: ["b"], rules: [ + ["< d().startOf('month')", "'previous'"], + ["< d().startOf('month').add(1, 'month')", "'current'"], + ["", "'future'"], + ]}, + ]}, + cases: [ + [{items: [{at: "2025-02-28T23:59:59Z"}, {at: "2025-03-01"}, {at: "2025-03-31T23:59:59Z"}, {at: "2025-04-01"}]}, {buckets: [{b: "previous"}, {b: "current"}, {b: "current"}, {b: "future"}]}], + [{items: []}, {buckets: []}], + [{items: [{at: "2025-03-01T00:00:00+01:00"}]}, {buckets: [{b: "previous"}]}], + ], +} + +{ + name: "loops: dates filtered and sorted by a closure after a loop", + graph: {nodes: [ + {expression: "parse", inputField: "events", outputPath: "events", executionMode: "loop", fields: {name: "name", at: "d(at)"}}, + {expression: "pick", fields: { + upcoming: "map(filter(events, #.at > d()), #.name)", + past: "count(events, #.at < d())", + first: "min(map(events, #.at.timestamp()))", + }}, + ]}, + cases: [ + [{events: [{name: "a", at: "2025-03-21"}, {name: "b", at: "2025-03-19"}, {name: "c", at: "2025-12-01"}]}, {upcoming: ["a", "c"], past: 1, first: 1742342400000}], + [{events: [{name: "x", at: "2020-01-01"}]}, {upcoming: [], past: 1, first: 1577836800000}], + ], +} + +{ + name: "tables: output cells produce dates read downstream", + graph: {nodes: [ + {table: "renew", passThrough: true, inputs: ["plan"], outputs: ["renewal"], rules: [ + ["'monthly'", "d(start).add(1, 'month')"], + ["'yearly'", "d(start).add(1, 'year')"], + ["", "d(start)"], + ]}, + {expression: "use", fields: {renewal: "renewal", text: "renewal.format('%Y-%m-%d')", inDays: "renewal.diff(d(start), 'd')"}}, + ]}, + cases: [ + [{start: "2024-01-31", plan: "monthly"}, {renewal: "2024-02-29T00:00:00Z", text: "2024-02-29", inDays: 29}], + [{start: "2024-02-29", plan: "yearly"}, {renewal: "2025-02-28T00:00:00Z", text: "2025-02-28", inDays: 365}, "bug: adding or subtracting a year from Feb 29 gives an invalid date instead of clamping to Feb 28 as months do (expression spec)"], + [{start: "2025-03-20", plan: "trial"}, {renewal: "2025-03-20T00:00:00Z", text: "2025-03-20", inDays: 0}], + [{start: "2025-12-31T18:00:00Z", plan: "monthly"}, {renewal: "2026-01-31T18:00:00Z", text: "2026-01-31", inDays: 31}], + ], +} + +{ + name: "tables: a date computed upstream against date cells of every kind", + graph: {nodes: [ + {expression: "calc", fields: {due: "d(s).add(grace, 'd')"}}, + {table: "t", hit: "collect", inputs: ["due"], outputs: ["tag"], rules: [ + ["< d('2025-01-01')", "'old'"], + ["[d('2025-03-01')..d('2025-03-31')]", "'march'"], + ["d('2025-03-20')", "'exact'"], + ["> d()", "'future'"], + ]}, + ]}, + cases: [ + [{s: "2024-12-01", grace: 10}, [{tag: "old"}]], + [{s: "2025-03-10", grace: 10}, [{tag: "march"}, {tag: "exact"}]], + [{s: "2025-03-10", grace: 11}, [{tag: "march"}, {tag: "future"}]], + [{s: "2025-03-25", grace: 10}, [{tag: "future"}]], + [{s: "2025-03-01", grace: 0}, [{tag: "march"}]], + ], +} + +{ + name: "tables: a first-hit table on a date difference in months", + graph: {nodes: [ + {expression: "tenure", fields: {months: "d().diff(d(since), 'month')"}}, + {table: "level", passThrough: true, inputs: ["months"], outputs: ["level"], rules: [ + [">= 24", "'veteran'"], + [">= 6", "'regular'"], + ["", "'new'"], + ]}, + ]}, + cases: [ + [{since: "2023-03-20"}, {months: 24, level: "veteran"}], + [{since: "2023-03-21"}, {months: 23, level: "regular"}], + [{since: "2024-09-20"}, {months: 6, level: "regular"}], + [{since: "2024-09-21"}, {months: 5, level: "new"}], + [{since: "2025-03-20"}, {months: 0, level: "new"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dates across other boundaries: sub-decisions, switches, invalid values, numeric timestamps. +{ + name: "boundaries: a date passed into a sub-decision", + decisions: { + child: {nodes: [{expression: "c", fields: {t: "type(due)", next: "d(due).add(1, 'd')"}}]}, + }, + graph: {nodes: [ + {expression: "make", fields: {due: "d(s).add(1, 'month')"}}, + {decision: "call", key: "child"}, + ]}, + cases: [ + [{s: "2025-01-31"}, {t: "date", next: "2025-03-01T00:00:00Z"}], + [{s: "2025-03-20T10:00:00Z"}, {t: "date", next: "2025-04-21T10:00:00Z"}], + ], +} + +{ + name: "boundaries: an invalid date propagates through later nodes", + graph: {nodes: [ + {expression: "parse", fields: {at: "d(s)"}}, + {expression: "use", fields: {valid: "at.isValid()", next: "at.add(1, 'd')", before: "at < d()"}}, + ]}, + cases: [ + [{s: "2025-03-01"}, {valid: true, next: "2025-03-02T00:00:00Z", before: true}], + [{s: "garbage"}, {valid: false, next: "Invalid date", before: true}, "question: an invalid date orders before every valid date instead of comparing false (expression spec)"], + [{}, {valid: false, next: "Invalid date", before: true}, "question: an invalid date orders before every valid date instead of comparing false (expression spec)"], + [{s: 1700000000000}, {valid: true, next: "2023-11-15T22:13:20Z", before: true}], + [{s: "2025-02-30"}, {valid: false, next: "Invalid date", before: true}, "question: an invalid date orders before every valid date instead of comparing false (expression spec)"], + ], +} + +{ + name: "boundaries: schema date fields used directly as dates in a chain", + graph: {nodes: [ + {input: "request", schema: {type: "object", properties: {start: {type: "string", format: "date"}}}}, + {expression: "calc", fields: {end: "d(start).add(1, 'w')", wd: "d(start).weekday()", raw: "start"}}, + ]}, + cases: [ + [{start: "2025-03-20"}, {end: "2025-03-27T00:00:00Z", wd: 4, raw: "2025-03-20"}], + [{start: "2024-02-29"}, {end: "2024-03-07T00:00:00Z", wd: 4, raw: "2024-02-29"}], + ], +} + +{ + name: "boundaries: legacy date() timestamps beside d() values", + graph: {nodes: [ + {expression: "calc", fields: {ts: "date(s)", ms: "d(s).timestamp()", agree: "date(s) * 1000 == d(s).timestamp()", nowTs: "date('now')"}}, + ]}, + cases: [ + [{s: "2025-03-20"}, {ts: 1742428800, ms: 1742428800000, agree: true, nowTs: 1742465730}], + [{s: "1970-01-01T00:00:00Z"}, {ts: 0, ms: 0, agree: true, nowTs: 1742465730}], + [{s: "2025-03-20T10:15:30+01:00"}, {ts: 1742462130, ms: 1742462130000, agree: true, nowTs: 1742465730}], + ], +} diff --git a/core/engine/tests/spec/graph/67-switch-row-splits.json5 b/core/engine/tests/spec/graph/67-switch-row-splits.json5 new file mode 100644 index 00000000..1e482543 --- /dev/null +++ b/core/engine/tests/spec/graph/67-switch-row-splits.json5 @@ -0,0 +1,1072 @@ +// Collect switches whose rows split across many branch combinations. Every true condition +// routes, so one suite's cases take different subsets of branches; the compiled engine groups +// rows by their condition outcome set and evaluates each group's child segment once, which is +// what these suites stress: many outcome sets per suite, conditions over earlier node outputs, +// joins reading `$nodes` of branches that ran or not, and row-specific errors. + + +// --------------------------------------------------------------------------------------- +// Independent conditions over separate fields: every outcome set is its own group. +// --------------------------------------------------------------------------------------- + + +{ + name: "three conditions over three fields, all eight combinations", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a > 0", "b == 'y'", "c"]}, + {expression: "na", fields: {ka: "a * 10"}}, + {expression: "nb", fields: {kb: "'B'"}}, + {expression: "nc", fields: {kc: "true"}}, + ], + edges: ["input -> s", "s:0 -> na -> output", "s:1 -> nb -> output", "s:2 -> nc -> output"], + }, + cases: [ + [{a: 5, b: "y", c: true}, {ka: 50, kb: "B", kc: true}], + [{a: 5, b: "y", c: false}, {ka: 50, kb: "B"}], + [{a: 5, b: "n", c: true}, {ka: 50, kc: true}], + [{a: 5, b: "n", c: false}, {ka: 50}], + [{a: -1, b: "y", c: true}, {kb: "B", kc: true}], + [{a: -1, b: "y", c: false}, {kb: "B"}], + [{a: -1, b: "n", c: true}, {kc: true}], + [{a: -1, b: "n", c: false}, {}], + [{}, {}], + [{a: 3}, {ka: 30}], + [{b: "y", c: true}, {kb: "B", kc: true}], + [{a: null, b: null, c: null}, {}], + [{a: 1, b: "Y", c: "true"}, {ka: 10}], + [{a: 0, b: "y", c: true}, {kb: "B", kc: true}], + ], +} + +// Overlapping ranges: the outcome set is a function of one value; neighbouring values land in +// different groups. +{ + name: "four overlapping conditions over one number", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n > 0", "n > 10", "n % 2 == 0", "n < 100"]}, + {expression: "p", fields: {pos: "n + 1"}}, + {expression: "b", fields: {big: "n - 10"}}, + {expression: "e", fields: {even: "n / 2"}}, + {expression: "m", fields: {small: "true"}}, + ], + edges: ["input -> s", "s:0 -> p -> output", "s:1 -> b -> output", "s:2 -> e -> output", "s:3 -> m -> output"], + }, + cases: [ + [{n: -6}, {even: -3, small: true}], + [{n: -5}, {small: true}], + [{n: 0}, {even: 0, small: true}], + [{n: 1}, {pos: 2, small: true}], + [{n: 2}, {pos: 3, even: 1, small: true}], + [{n: 7}, {pos: 8, small: true}], + [{n: 10}, {pos: 11, even: 5, small: true}], + [{n: 11}, {pos: 12, big: 1, small: true}], + [{n: 12}, {pos: 13, big: 2, even: 6, small: true}], + [{n: 99}, {pos: 100, big: 89, small: true}], + [{n: 100}, {pos: 101, big: 90, even: 50}], + [{n: 101}, {pos: 102, big: 91}], + [{n: 150}, {pos: 151, big: 140, even: 75}], + [{n: 3}, {pos: 4, small: true}], + ], +} + +// Thirty outcome sets in one suite. Each branch adds one key under `hit`, merged deeply. +{ + name: "five flags, thirty of the thirty-two combinations, branches nest under one key", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["f0", "f1", "f2", "f3", "f4"]}, + {expression: "n0", fields: {"hit.b0": "true", id0: "id"}}, + {expression: "n1", fields: {"hit.b1": "true"}}, + {expression: "n2", fields: {"hit.b2": "true"}}, + {expression: "n3", fields: {"hit.b3": "true"}}, + {expression: "n4", fields: {"hit.b4": "true", id4: "id * 2"}}, + ], + edges: ["input -> s", "s:0 -> n0 -> output", "s:1 -> n1 -> output", "s:2 -> n2 -> output", "s:3 -> n3 -> output", "s:4 -> n4 -> output"], + }, + cases: [ + [{f0: false, f1: false, f2: false, f3: false, f4: false, id: 0}, {}], + [{f0: false, f1: false, f2: false, f3: false, f4: true, id: 1}, {hit: {b4: true}, id4: 2}], + [{f0: false, f1: false, f2: false, f3: true, f4: false, id: 2}, {hit: {b3: true}}], + [{f0: false, f1: false, f2: false, f3: true, f4: true, id: 3}, {hit: {b3: true, b4: true}, id4: 6}], + [{f0: false, f1: false, f2: true, f3: false, f4: false, id: 4}, {hit: {b2: true}}], + [{f0: false, f1: false, f2: true, f3: false, f4: true, id: 5}, {hit: {b2: true, b4: true}, id4: 10}], + [{f0: false, f1: false, f2: true, f3: true, f4: false, id: 6}, {hit: {b2: true, b3: true}}], + [{f0: false, f1: false, f2: true, f3: true, f4: true, id: 7}, {hit: {b2: true, b3: true, b4: true}, id4: 14}], + [{f0: false, f1: true, f2: false, f3: false, f4: false, id: 8}, {hit: {b1: true}}], + [{f0: false, f1: true, f2: false, f3: false, f4: true, id: 9}, {hit: {b1: true, b4: true}, id4: 18}], + [{f0: false, f1: true, f2: false, f3: true, f4: false, id: 10}, {hit: {b1: true, b3: true}}], + [{f0: false, f1: true, f2: true, f3: false, f4: false, id: 11}, {hit: {b1: true, b2: true}}], + [{f0: false, f1: true, f2: true, f3: false, f4: true, id: 12}, {hit: {b1: true, b2: true, b4: true}, id4: 24}], + [{f0: false, f1: true, f2: true, f3: true, f4: false, id: 13}, {hit: {b1: true, b2: true, b3: true}}], + [{f0: false, f1: true, f2: true, f3: true, f4: true, id: 14}, {hit: {b1: true, b2: true, b3: true, b4: true}, id4: 28}], + [{f0: true, f1: false, f2: false, f3: false, f4: false, id: 15}, {hit: {b0: true}, id0: 15}], + [{f0: true, f1: false, f2: false, f3: false, f4: true, id: 16}, {hit: {b0: true, b4: true}, id0: 16, id4: 32}], + [{f0: true, f1: false, f2: false, f3: true, f4: false, id: 17}, {hit: {b0: true, b3: true}, id0: 17}], + [{f0: true, f1: false, f2: false, f3: true, f4: true, id: 18}, {hit: {b0: true, b3: true, b4: true}, id0: 18, id4: 36}], + [{f0: true, f1: false, f2: true, f3: false, f4: false, id: 19}, {hit: {b0: true, b2: true}, id0: 19}], + [{f0: true, f1: false, f2: true, f3: false, f4: true, id: 20}, {hit: {b0: true, b2: true, b4: true}, id0: 20, id4: 40}], + [{f0: true, f1: false, f2: true, f3: true, f4: true, id: 21}, {hit: {b0: true, b2: true, b3: true, b4: true}, id0: 21, id4: 42}], + [{f0: true, f1: true, f2: false, f3: false, f4: false, id: 22}, {hit: {b0: true, b1: true}, id0: 22}], + [{f0: true, f1: true, f2: false, f3: false, f4: true, id: 23}, {hit: {b0: true, b1: true, b4: true}, id0: 23, id4: 46}], + [{f0: true, f1: true, f2: false, f3: true, f4: false, id: 24}, {hit: {b0: true, b1: true, b3: true}, id0: 24}], + [{f0: true, f1: true, f2: false, f3: true, f4: true, id: 25}, {hit: {b0: true, b1: true, b3: true, b4: true}, id0: 25, id4: 50}], + [{f0: true, f1: true, f2: true, f3: false, f4: false, id: 26}, {hit: {b0: true, b1: true, b2: true}, id0: 26}], + [{f0: true, f1: true, f2: true, f3: false, f4: true, id: 27}, {hit: {b0: true, b1: true, b2: true, b4: true}, id0: 27, id4: 54}], + [{f0: true, f1: true, f2: true, f3: true, f4: false, id: 28}, {hit: {b0: true, b1: true, b2: true, b3: true}, id0: 28}], + [{f0: true, f1: true, f2: true, f3: true, f4: true, id: 29}, {hit: {b0: true, b1: true, b2: true, b3: true, b4: true}, id0: 29, id4: 58}], + ], +} + +// A default branch in the middle under collect: always taken, so it never creates a new +// group but rides along with every one. A null `base` is dropped from the output. +{ + name: "three conditions and a default branch: the default joins every group", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["x > 1", "", "x > 2", "tag == 'z'"]}, + {expression: "a", fields: {gt1: "true"}}, + {expression: "d", fields: {base: "x"}}, + {expression: "b", fields: {gt2: "true"}}, + {expression: "z", fields: {zed: "tag"}}, + ], + edges: ["input -> s", "s:0 -> a -> output", "s:1 -> d -> output", "s:2 -> b -> output", "s:3 -> z -> output"], + }, + cases: [ + [{x: 0}, {base: 0}], + [{x: 2}, {base: 2, gt1: true}], + [{x: 3}, {base: 3, gt1: true, gt2: true}], + [{x: 3, tag: "z"}, {base: 3, gt1: true, gt2: true, zed: "z"}], + [{tag: "z"}, {zed: "z"}], + [{}, {}], + [{x: null, tag: null}, {}], + [{x: "5", tag: "z"}, {base: "5", zed: "z"}], + [{x: 2, tag: "y"}, {base: 2, gt1: true}], + [{x: 100}, {base: 100, gt1: true, gt2: true}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Conflicting writes per combination. On a key written by several taken branches the +// branch whose edge into the merge point was declared first wins (see 09). +// --------------------------------------------------------------------------------------- + + +{ + name: "three branches writing one key: the earliest declared edge wins in every combination", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "A", fields: {who: "'A'", a: "true"}}, + {expression: "B", fields: {who: "'B'", b: "true"}}, + {expression: "C", fields: {who: "'C'", c: "true"}}, + ], + edges: ["input -> s", "s:0 -> A -> output", "s:1 -> B -> output", "s:2 -> C -> output"], + }, + cases: [ + [{a: true, b: true, c: true}, {a: true, b: true, c: true, who: "A"}], + [{a: true, b: true, c: false}, {a: true, b: true, who: "A"}], + [{a: true, b: false, c: true}, {a: true, c: true, who: "A"}], + [{a: true, b: false, c: false}, {a: true, who: "A"}], + [{a: false, b: true, c: true}, {b: true, c: true, who: "B"}], + [{a: false, b: true, c: false}, {b: true, who: "B"}], + [{a: false, b: false, c: true}, {c: true, who: "C"}], + [{a: false, b: false, c: false}, {}], + ], +} + +{ + name: "the same switch with edges into the output declared in reverse", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "A", fields: {who: "'A'", a: "true"}}, + {expression: "B", fields: {who: "'B'", b: "true"}}, + {expression: "C", fields: {who: "'C'", c: "true"}}, + ], + edges: ["input -> s", "s:0 -> A", "s:1 -> B", "s:2 -> C", "C -> output", "B -> output", "A -> output"], + }, + cases: [ + [{a: true, b: true, c: true}, {a: true, b: true, c: true, who: "C"}], + [{a: true, b: true, c: false}, {a: true, b: true, who: "B"}], + [{a: true, b: false, c: true}, {a: true, c: true, who: "C"}], + [{a: true, b: false, c: false}, {a: true, who: "A"}], + [{a: false, b: true, c: true}, {b: true, c: true, who: "C"}], + [{a: false, b: true, c: false}, {b: true, who: "B"}], + [{a: false, b: false, c: true}, {c: true, who: "C"}], + [{a: false, b: false, c: false}, {}], + ], +} + +{ + name: "a null written by the winning branch removes the other branch's value", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["q", "p"]}, + {expression: "Q", fields: {v: "null", q: "true"}}, + {expression: "P", fields: {v: "'p'"}}, + ], + edges: ["input -> s", "s:0 -> Q -> output", "s:1 -> P -> output"], + }, + cases: [ + [{p: true, q: true}, {q: true}], + [{p: true, q: false}, {v: "p"}], + [{p: false, q: true}, {q: true}], + [{p: false, q: false}, {}], + [{}, {}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Conditions that read earlier node outputs: the switch input is a computed object, and +// `$nodes` gives access to nodes further back, including the request. +// --------------------------------------------------------------------------------------- + + +// The switch input is `pre`'s output only; branches reach the request through `$nodes.input`. +{ + name: "conditions read flags an earlier expression node computed", + graph: { + nodes: [ + {expression: "pre", fields: {risky: "(amount ?? 0) > 1000", foreign: "country != 'US'", vip: "vip == true"}}, + {switch: "s", hit: "collect", when: ["risky", "foreign", "vip", "risky and vip"]}, + {expression: "r", fields: {review: "$nodes.input.amount"}}, + {expression: "f", fields: {fx: "$nodes.input.country"}}, + {expression: "v", fields: {perk: "'lounge'"}}, + {expression: "x", fields: {fast: "vip and risky"}}, + ], + edges: ["input -> pre -> s", "s:0 -> r -> output", "s:1 -> f -> output", "s:2 -> v -> output", "s:3 -> x -> output"], + }, + cases: [ + [{amount: 50, country: "US", vip: false}, {}], + [{amount: 5000, country: "US", vip: false}, {review: 5000}], + [{amount: 50, country: "DE", vip: false}, {fx: "DE"}], + [{amount: 50, country: "US", vip: true}, {perk: "lounge"}], + [{amount: 5000, country: "DE", vip: false}, {review: 5000, fx: "DE"}], + [{amount: 5000, country: "US", vip: true}, {review: 5000, perk: "lounge", fast: true}], + [{amount: 50, country: "FR", vip: true}, {fx: "FR", perk: "lounge"}], + [{amount: 5000, country: "JP", vip: true}, {review: 5000, fx: "JP", perk: "lounge", fast: true}], + [{amount: 1000, country: "US", vip: true}, {perk: "lounge"}], + [{country: "US"}, {}], + [{amount: 1001}, {review: 1001}], + [{amount: null, country: null, vip: null}, {}], + ], +} + +{ + name: "conditions read an earlier table's band and the request through $nodes.input", + graph: { + nodes: [ + {table: "band", inputs: ["score"], outputs: ["band"], rules: [[">= 80", "'A'"], [">= 50", "'B'"], ["", "'C'"]]}, + {switch: "s", hit: "collect", when: ["band == 'A'", "band in ['A', 'B']", "$nodes.input.late == true", "band == 'C' and $nodes.input.late == true"]}, + {expression: "g", fields: {gold: "true"}}, + {expression: "e", fields: {eligible: "band"}}, + {expression: "p", fields: {penalty: "5"}}, + {expression: "x", fields: {reject: "true"}}, + ], + edges: ["input -> band -> s", "s:0 -> g -> output", "s:1 -> e -> output", "s:2 -> p -> output", "s:3 -> x -> output"], + }, + cases: [ + [{score: 90, late: false}, {gold: true, eligible: "A"}], + [{score: 90, late: true}, {gold: true, eligible: "A", penalty: 5}], + [{score: 60, late: false}, {eligible: "B"}], + [{score: 60, late: true}, {eligible: "B", penalty: 5}], + [{score: 10, late: false}, {}], + [{score: 10, late: true}, {penalty: 5, reject: true}], + [{late: true}, {penalty: 5, reject: true}], + [{}, {}], + [{score: "high", late: true}, {penalty: 5, reject: true}], + [{score: 80}, {gold: true, eligible: "A"}], + [{score: 50, late: true}, {eligible: "B", penalty: 5}], + [{score: 49}, {}], + ], +} + +{ + name: "conditions over the merged outputs of two parallel nodes and $nodes of one of them", + graph: { + nodes: [ + {expression: "p1", fields: {dbl: "x * 2"}}, + {expression: "p2", fields: {neg: "-y"}}, + {switch: "s", hit: "collect", when: ["dbl > 10", "$nodes.p2.neg < 0", "dbl + neg == 0", ""]}, + {expression: "a", fields: {big: "$nodes.p1.dbl"}}, + {expression: "b", fields: {ypos: "true"}}, + {expression: "c", fields: {balanced: "true"}}, + {expression: "d", fields: {seen: "dbl"}}, + ], + edges: ["input -> p1 -> s", "input -> p2 -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output", "s:3 -> d -> output"], + }, + cases: [ + [{x: 1, y: 2}, {ypos: true, balanced: true, seen: 2}], + [{x: 6, y: 12}, {big: 12, ypos: true, balanced: true, seen: 12}], + [{x: 6, y: 0}, {big: 12, seen: 12}], + [{x: 0, y: 0}, {balanced: true, seen: 0}], + [{x: -3, y: -6}, {balanced: true, seen: -6}], + [{x: 10, y: 1}, {big: 20, ypos: true, seen: 20}], + [{x: 2, y: -1}, {seen: 4}], + [{x: 5, y: 10}, {ypos: true, balanced: true, seen: 10}], + [{x: 7, y: 14}, {big: 14, ypos: true, balanced: true, seen: 14}], + [{x: 3, y: 3}, {ypos: true, seen: 6}], + ], +} + +{ + name: "conditions read request fields a non-passThrough node dropped", + graph: { + nodes: [ + {expression: "calc", fields: {total: "qty * price"}}, + {switch: "s", hit: "collect", when: ["total > 100", "$nodes.input.coupon != null", "$nodes.input.qty > 10", ""]}, + {expression: "a", fields: {bulk: "true"}}, + {expression: "b", fields: {coupon: "$nodes.input.coupon"}}, + {expression: "c", fields: {qtyNote: "$nodes.input.qty"}}, + {expression: "d", fields: {total: "total"}}, + ], + edges: ["input -> calc -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output", "s:3 -> d -> output"], + }, + cases: [ + [{qty: 1, price: 10}, {total: 10}], + [{qty: 20, price: 10}, {total: 200, bulk: true, qtyNote: 20}], + [{qty: 20, price: 1}, {total: 20, qtyNote: 20}], + [{qty: 2, price: 100, coupon: "C1"}, {total: 200, bulk: true, coupon: "C1"}], + [{qty: 11, price: 1, coupon: "X"}, {total: 11, coupon: "X", qtyNote: 11}], + [{qty: 50, price: 50, coupon: "Y"}, {total: 2500, bulk: true, coupon: "Y", qtyNote: 50}], + [{qty: 5, price: 20}, {total: 100}], + [{qty: 0, price: 5, coupon: null}, {total: 0}], + ], +} + + +// --------------------------------------------------------------------------------------- +// A join after collect branches: it runs on the merged outputs of the branches that were +// taken and reads `$nodes` of all of them, null for the ones that were not. +// --------------------------------------------------------------------------------------- + + +// `v` on the join input is the merged value: the earliest declared edge into the join wins. +// With no branch taken the join is not reached and the result is empty. +{ + name: "a join reads $nodes of four branches in thirteen combinations", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c", "d"]}, + {expression: "A", fields: {v: "'a'", w: "1"}}, + {expression: "B", fields: {v: "'b'", w: "2"}}, + {expression: "C", fields: {v: "'c'", w: "4"}}, + {expression: "D", fields: {v: "'d'", w: "8"}}, + {expression: "join", fields: {mask: "($nodes.A.w ?? 0) + ($nodes.B.w ?? 0) + ($nodes.C.w ?? 0) + ($nodes.D.w ?? 0)", ran: "filter(['A', 'B', 'C', 'D'], $nodes[#] != null)", firstV: "v"}}, + ], + edges: ["input -> s", "s:0 -> A -> join", "s:1 -> B -> join", "s:2 -> C -> join", "s:3 -> D -> join", "join -> output"], + }, + cases: [ + [{a: false, b: false, c: false, d: false}, {}], + [{a: false, b: false, c: false, d: true}, {mask: 8, ran: ["D"], firstV: "d"}], + [{a: false, b: false, c: true, d: false}, {mask: 4, ran: ["C"], firstV: "c"}], + [{a: false, b: false, c: true, d: true}, {mask: 12, ran: ["C", "D"], firstV: "c"}], + [{a: false, b: true, c: false, d: false}, {mask: 2, ran: ["B"], firstV: "b"}], + [{a: false, b: true, c: true, d: false}, {mask: 6, ran: ["B", "C"], firstV: "b"}], + [{a: false, b: true, c: true, d: true}, {mask: 14, ran: ["B", "C", "D"], firstV: "b"}], + [{a: true, b: false, c: false, d: false}, {mask: 1, ran: ["A"], firstV: "a"}], + [{a: true, b: false, c: false, d: true}, {mask: 9, ran: ["A", "D"], firstV: "a"}], + [{a: true, b: false, c: true, d: true}, {mask: 13, ran: ["A", "C", "D"], firstV: "a"}], + [{a: true, b: true, c: false, d: false}, {mask: 3, ran: ["A", "B"], firstV: "a"}], + [{a: true, b: true, c: true, d: false}, {mask: 7, ran: ["A", "B", "C"], firstV: "a"}], + [{a: true, b: true, c: true, d: true}, {mask: 15, ran: ["A", "B", "C", "D"], firstV: "a"}], + [{a: true, b: null}, {mask: 1, ran: ["A"], firstV: "a"}], + ], +} + +{ + name: "passThrough branches into a passThrough join: the input survives every combination", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["x", "y", "z"]}, + {expression: "X", passThrough: true, fields: {fx: "1"}}, + {expression: "Y", passThrough: true, fields: {fy: "2"}}, + {expression: "Z", passThrough: true, fields: {fz: "3"}}, + {expression: "join", passThrough: true, fields: {count: "len(filter([$nodes.X, $nodes.Y, $nodes.Z], # != null))", sum: "(fx ?? 0) + (fy ?? 0) + (fz ?? 0)"}}, + ], + edges: ["input -> s", "s:0 -> X -> join", "s:1 -> Y -> join", "s:2 -> Z -> join", "join -> output"], + }, + cases: [ + [{x: true, y: true, z: true}, {x: true, y: true, z: true, fx: 1, fy: 2, fz: 3, count: 3, sum: 6}], + [{x: true, y: true, z: false}, {x: true, y: true, z: false, fx: 1, fy: 2, count: 2, sum: 3}], + [{x: true, y: false, z: true}, {x: true, y: false, z: true, fx: 1, fz: 3, count: 2, sum: 4}], + [{x: true, y: false, z: false}, {x: true, y: false, z: false, fx: 1, count: 1, sum: 1}], + [{x: false, y: true, z: true}, {x: false, y: true, z: true, fy: 2, fz: 3, count: 2, sum: 5}], + [{x: false, y: true, z: false}, {x: false, y: true, z: false, fy: 2, count: 1, sum: 2}], + [{x: false, y: false, z: true}, {x: false, y: false, z: true, fz: 3, count: 1, sum: 3}], + [{x: false, y: false, z: false}, {}], + [{x: true, extra: "e"}, {x: true, extra: "e", fx: 1, count: 1, sum: 1}], + [{y: true, z: true, extra: [1, 2]}, {y: true, z: true, extra: [1, 2], fy: 2, fz: 3, count: 2, sum: 5}], + ], +} + +// Conditions test membership in an input array; rows cover most of the 32 outcome sets. +{ + name: "five branches feed a join that spells which ran", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["0 in flags", "1 in flags", "2 in flags", "3 in flags", "4 in flags"]}, + {expression: "A", fields: {c: "'A'"}}, + {expression: "B", fields: {c: "'B'"}}, + {expression: "C", fields: {c: "'C'"}}, + {expression: "D", fields: {c: "'D'"}}, + {expression: "E", fields: {c: "'E'"}}, + {expression: "join", fields: {ran: "map(filter(['A', 'B', 'C', 'D', 'E'], $nodes[#] != null), $nodes[#].c)", code: "($nodes.A.c ?? '') + ($nodes.B.c ?? '') + ($nodes.C.c ?? '') + ($nodes.D.c ?? '') + ($nodes.E.c ?? '')", n: "len($.ran)", last: "$.ran[len($.ran) - 1]"}}, + ], + edges: ["input -> s", "s:0 -> A -> join", "s:1 -> B -> join", "s:2 -> C -> join", "s:3 -> D -> join", "s:4 -> E -> join", "join -> output"], + }, + cases: [ + [{v: 0, flags: []}, {}], + [{v: 1, flags: [4]}, {ran: ["E"], code: "E", n: 1, last: "E"}], + [{v: 2, flags: [3]}, {ran: ["D"], code: "D", n: 1, last: "D"}], + [{v: 3, flags: [3, 4]}, {ran: ["D", "E"], code: "DE", n: 2, last: "E"}], + [{v: 4, flags: [2]}, {ran: ["C"], code: "C", n: 1, last: "C"}], + [{v: 5, flags: [2, 3]}, {ran: ["C", "D"], code: "CD", n: 2, last: "D"}], + [{v: 6, flags: [2, 3, 4]}, {ran: ["C", "D", "E"], code: "CDE", n: 3, last: "E"}], + [{v: 7, flags: [1, 4]}, {ran: ["B", "E"], code: "BE", n: 2, last: "E"}], + [{v: 8, flags: [1, 3]}, {ran: ["B", "D"], code: "BD", n: 2, last: "D"}], + [{v: 9, flags: [1, 2]}, {ran: ["B", "C"], code: "BC", n: 2, last: "C"}], + [{v: 10, flags: [1, 2, 4]}, {ran: ["B", "C", "E"], code: "BCE", n: 3, last: "E"}], + [{v: 11, flags: [1, 2, 3, 4]}, {ran: ["B", "C", "D", "E"], code: "BCDE", n: 4, last: "E"}], + [{v: 12, flags: [0]}, {ran: ["A"], code: "A", n: 1, last: "A"}], + [{v: 13, flags: [0, 3]}, {ran: ["A", "D"], code: "AD", n: 2, last: "D"}], + [{v: 14, flags: [0, 3, 4]}, {ran: ["A", "D", "E"], code: "ADE", n: 3, last: "E"}], + [{v: 15, flags: [0, 2, 4]}, {ran: ["A", "C", "E"], code: "ACE", n: 3, last: "E"}], + [{v: 16, flags: [0, 2, 3]}, {ran: ["A", "C", "D"], code: "ACD", n: 3, last: "D"}], + [{v: 17, flags: [0, 2, 3, 4]}, {ran: ["A", "C", "D", "E"], code: "ACDE", n: 4, last: "E"}], + [{v: 18, flags: [0, 1]}, {ran: ["A", "B"], code: "AB", n: 2, last: "B"}], + [{v: 19, flags: [0, 1, 4]}, {ran: ["A", "B", "E"], code: "ABE", n: 3, last: "E"}], + [{v: 20, flags: [0, 1, 3, 4]}, {ran: ["A", "B", "D", "E"], code: "ABDE", n: 4, last: "E"}], + [{v: 21, flags: [0, 1, 2]}, {ran: ["A", "B", "C"], code: "ABC", n: 3, last: "C"}], + [{v: 22, flags: [0, 1, 2, 4]}, {ran: ["A", "B", "C", "E"], code: "ABCE", n: 4, last: "E"}], + [{v: 23, flags: [0, 1, 2, 3]}, {ran: ["A", "B", "C", "D"], code: "ABCD", n: 4, last: "D"}], + [{v: 24, flags: [0, 1, 2, 3, 4]}, {ran: ["A", "B", "C", "D", "E"], code: "ABCDE", n: 5, last: "E"}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Two switches in sequence: the outcome set of the second depends on what the first +// switch's branches wrote, so groups split twice. +// --------------------------------------------------------------------------------------- + + +{ + name: "a second collect switch routes on the keys the first switch's branches wrote", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["n > 0", "n % 2 == 0", "n > 100"]}, + {expression: "p", fields: {p: "1"}}, + {expression: "e", fields: {e: "1"}}, + {expression: "h", fields: {h: "1"}}, + {expression: "mid", fields: {score: "(p ?? 0) + (e ?? 0) + (h ?? 0)", e: "e", h: "h"}}, + {switch: "s2", hit: "collect", when: ["score >= 2", "e != null", "h == null"]}, + {expression: "m", fields: {multi: "score"}}, + {expression: "v", fields: {evenSeen: "true"}}, + {expression: "x", fields: {notHuge: "true"}}, + ], + edges: ["input -> s1", "s1:0 -> p -> mid", "s1:1 -> e -> mid", "s1:2 -> h -> mid", "mid -> s2", "s2:0 -> m -> output", "s2:1 -> v -> output", "s2:2 -> x -> output"], + }, + cases: [ + [{n: -3}, {}], + [{n: -2}, {evenSeen: true, notHuge: true}], + [{n: 0}, {evenSeen: true, notHuge: true}], + [{n: 1}, {notHuge: true}], + [{n: 2}, {multi: 2, evenSeen: true, notHuge: true}], + [{n: 3}, {notHuge: true}], + [{n: 4}, {multi: 2, evenSeen: true, notHuge: true}], + [{n: 101}, {multi: 2}], + [{n: 102}, {multi: 3, evenSeen: true}], + [{n: 1000}, {multi: 3, evenSeen: true}], + [{n: 7}, {notHuge: true}], + [{n: -100}, {evenSeen: true, notHuge: true}], + ], +} + +// The collect switch has three possible predecessors, one taken per row. +{ + name: "a first switch picks a mode node, both mode nodes feed one collect switch", + graph: { + nodes: [ + {switch: "kindSw", when: ["kind == 'a'", "kind == 'b'", ""]}, + {expression: "ma", passThrough: true, fields: {mode: "'strict'", lim: "10"}}, + {expression: "mb", passThrough: true, fields: {mode: "'loose'", lim: "100"}}, + {expression: "mc", passThrough: true, fields: {mode: "'none'", lim: "0"}}, + {switch: "s", hit: "collect", when: ["mode == 'strict'", "amt > lim", "mode != 'none' and amt > 0", ""]}, + {expression: "st", fields: {strict: "true"}}, + {expression: "ov", fields: {over: "amt - lim"}}, + {expression: "ch", fields: {charged: "mode"}}, + {expression: "md", fields: {mode: "$nodes.ma.mode ?? $nodes.mb.mode ?? $nodes.mc.mode"}}, + ], + edges: ["input -> kindSw", "kindSw:0 -> ma -> s", "kindSw:1 -> mb -> s", "kindSw:2 -> mc -> s", "s:0 -> st -> output", "s:1 -> ov -> output", "s:2 -> ch -> output", "s:3 -> md -> output"], + }, + cases: [ + [{kind: "a", amt: 5}, {strict: true, charged: "strict", mode: "strict"}], + [{kind: "a", amt: 50}, {strict: true, over: 40, charged: "strict", mode: "strict"}], + [{kind: "b", amt: 50}, {charged: "loose", mode: "loose"}], + [{kind: "b", amt: 500}, {over: 400, charged: "loose", mode: "loose"}], + [{kind: "c", amt: 5}, {over: 5, mode: "none"}], + [{kind: "c", amt: 0}, {mode: "none"}], + [{amt: -1}, {mode: "none"}], + [{kind: "a", amt: 0}, {strict: true, mode: "strict"}], + [{kind: "b", amt: 0}, {mode: "loose"}], + [{kind: "a", amt: 11}, {strict: true, over: 1, charged: "strict", mode: "strict"}], + ], +} + +// Fourteen rows over the 4x4 outcome sets of the two levels. +{ + name: "a collect switch nested in one branch of a collect switch", + graph: { + nodes: [ + {switch: "outer", hit: "collect", when: ["a", "b"]}, + {switch: "inner", hit: "collect", when: ["x > 0", "y > 0"]}, + {expression: "ax", fields: {ax: "true"}}, + {expression: "ay", fields: {ay: "true"}}, + {expression: "bb", fields: {b: "true"}}, + ], + edges: ["input -> outer", "outer:0 -> inner", "inner:0 -> ax -> output", "inner:1 -> ay -> output", "outer:1 -> bb -> output"], + }, + cases: [ + [{a: true, b: true, x: 1, y: 1}, {ax: true, ay: true, b: true}], + [{a: true, b: true, x: 1, y: 0}, {ax: true, b: true}], + [{a: true, b: true, x: 0, y: 1}, {ay: true, b: true}], + [{a: true, b: true, x: 0, y: 0}, {b: true}], + [{a: true, b: false, x: 1, y: 1}, {ax: true, ay: true}], + [{a: true, b: false, x: 1, y: 0}, {ax: true}], + [{a: true, b: false, x: 0, y: 1}, {ay: true}], + [{a: true, b: false, x: 0, y: 0}, {}], + [{a: false, b: true, x: 1, y: 1}, {b: true}], + [{a: false, b: true, x: 1, y: 0}, {b: true}], + [{a: false, b: true, x: 0, y: 1}, {b: true}], + [{a: false, b: true, x: 0, y: 0}, {b: true}], + [{a: false, b: false, x: 1, y: 1}, {}], + [{a: false, b: false, x: 1, y: 0}, {}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Branches of different node kinds under one collect switch: tables, loops, sub-decisions +// and functions each run only for the rows that route to them. +// --------------------------------------------------------------------------------------- + + +{ + name: "four branches of four node kinds in thirteen combinations", + decisions: { + child: { + nodes: [ + {expression: "c", fields: {child: "score + 1"}}, + ], + }, + }, + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["t", "l", "d", "f"]}, + {table: "tab", inputs: ["score"], outputs: ["grade"], rules: [[">= 50", "'hi'"], ["", "'lo'"]]}, + {expression: "loop", inputField: "items", outputPath: "doubled", executionMode: "loop", fields: {d: "$root * 2"}}, + {decision: "sub", key: "child"}, + {function: "fn", source: """export const handler = async (input) => ({fn: input.items.length});"""}, + ], + edges: ["input -> s", "s:0 -> tab -> output", "s:1 -> loop -> output", "s:2 -> sub -> output", "s:3 -> fn -> output"], + }, + cases: [ + [{t: true, l: true, d: true, f: true, score: 10, items: [1, 2]}, {grade: "lo", doubled: [{d: 2}, {d: 4}], child: 11, fn: 2}], + [{t: true, l: true, d: true, f: false, score: 60, items: []}, {grade: "hi", doubled: [], child: 61}], + [{t: true, l: true, d: false, f: true, score: 50, items: [3]}, {grade: "hi", doubled: [{d: 6}], fn: 1}], + [{t: true, l: false, d: true, f: true, score: 10, items: [1, 2]}, {grade: "lo", child: 11, fn: 2}], + [{t: true, l: false, d: true, f: false, score: 60, items: []}, {grade: "hi", child: 61}], + [{t: true, l: false, d: false, f: true, score: 50, items: [3]}, {grade: "hi", fn: 1}], + [{t: true, l: false, d: false, f: false, score: 0, items: [4, 5, 6]}, {grade: "lo"}], + [{t: false, l: true, d: true, f: true, score: 10, items: [1, 2]}, {doubled: [{d: 2}, {d: 4}], child: 11, fn: 2}], + [{t: false, l: true, d: false, f: true, score: 50, items: [3]}, {doubled: [{d: 6}], fn: 1}], + [{t: false, l: true, d: false, f: false, score: 0, items: [4, 5, 6]}, {doubled: [{d: 8}, {d: 10}, {d: 12}]}], + [{t: false, l: false, d: true, f: false, score: 60, items: []}, {child: 61}], + [{t: false, l: false, d: false, f: true, score: 50, items: [3]}, {fn: 1}], + [{t: false, l: false, d: false, f: false, score: 0, items: [4, 5, 6]}, {}], + ], +} + +{ + name: "branches with nested outputPaths sharing a prefix merge deeply in every combination", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "A", outputPath: "res.x", fields: {a: "v"}}, + {expression: "B", outputPath: "res.x", fields: {b: "v * 2"}}, + {expression: "C", outputPath: "res", fields: {c: "[v]"}}, + ], + edges: ["input -> s", "s:0 -> A -> output", "s:1 -> B -> output", "s:2 -> C -> output"], + }, + cases: [ + [{a: true, b: true, c: true, v: 1}, {res: {x: {a: 1, b: 2}, c: [1]}}], + [{a: true, b: true, c: false, v: 2}, {res: {x: {a: 2, b: 4}}}], + [{a: true, b: false, c: true, v: 3}, {res: {x: {a: 3}, c: [3]}}], + [{a: true, b: false, c: false, v: 4}, {res: {x: {a: 4}}}], + [{a: false, b: true, c: true, v: 5}, {res: {x: {b: 10}, c: [5]}}], + [{a: false, b: true, c: false, v: 6}, {res: {x: {b: 12}}}], + [{a: false, b: false, c: true, v: 7}, {res: {c: [7]}}], + [{a: false, b: false, c: false, v: 8}, {}], + [{a: true, c: true, v: 0}, {res: {x: {a: 0}, c: [0]}}], + [{b: true, v: -2}, {res: {x: {b: -4}}}], + ], +} + +{ + name: "a first-hit table and a per-column collect table on two branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["t1", "t2"]}, + {table: "size", inputs: ["n"], outputs: ["size"], rules: [["> 100", "'L'"], ["> 10", "'M'"], ["", "'S'"]]}, + {table: "tagger", inputs: ["n"], outputs: ["tags[]"], rules: [["> 0", "'pos'"], ["", "'any'"]]}, + ], + edges: ["input -> s", "s:0 -> size -> output", "s:1 -> tagger -> output"], + }, + cases: [ + [{t1: true, t2: true, n: 5}, {size: "S", tags: ["pos", "any"]}], + [{t1: true, t2: false, n: 50}, {size: "M"}], + [{t1: false, t2: true, n: 500}, {tags: ["pos", "any"]}], + [{t1: false, t2: false, n: -4}, {}], + [{t1: true, t2: true, n: 12}, {size: "M", tags: ["pos", "any"]}], + [{t1: true, t2: true, n: -1}, {size: "S", tags: ["any"]}], + [{t1: false, t2: true, n: 7}, {tags: ["pos", "any"]}], + [{t1: true, t2: false, n: 101}, {size: "L"}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Row-specific failures. An error in a taken branch fails only the rows that take it; an +// erroring condition is false for that row only. +// --------------------------------------------------------------------------------------- + + +{ + name: "a branch that fails for some inputs fails only the rows routed to it", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "A", fields: {ok: "true"}}, + {expression: "B", fields: {twice: "x * 2"}}, + {expression: "C", fields: {c: "true"}}, + ], + edges: ["input -> s", "s:0 -> A -> output", "s:1 -> B -> output", "s:2 -> C -> output"], + }, + cases: [ + [{a: true, b: false, c: true, x: "nope"}, {ok: true, c: true}], + [{a: true, b: true, c: false, x: "nope"}, "!error"], + [{a: true, b: true, c: true, x: 3}, {ok: true, twice: 6, c: true}], + [{a: false, b: true, c: false, x: 4}, {twice: 8}], + [{a: false, b: true, c: true, x: [1]}, "!error"], + [{a: false, b: false, c: true}, {c: true}], + [{a: true, b: true, x: null}, "!error"], + [{a: true, c: true, x: 1}, {ok: true, c: true}], + [{b: true, x: 0}, {twice: 0}], + ], +} + +{ + name: "a failing custom node on one branch beside two healthy branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["d", "fail", "a > 1"]}, + {expression: "D", fields: {dated: "true"}}, + {custom: "F", kind: "fail", config: {message: "custom stop"}}, + {expression: "A", fields: {a: "true"}}, + ], + edges: ["input -> s", "s:0 -> D -> output", "s:1 -> F -> output", "s:2 -> A -> output"], + }, + cases: [ + [{d: true, a: 2}, {dated: true, a: true}], + [{d: true, a: 2, fail: true}, "!error: custom stop"], + [{fail: true}, "!error: custom stop"], + [{a: 0}, {}], + [{a: 5, fail: false}, {a: true}], + [{d: false, a: 3}, {a: true}], + ], +} + +{ + name: "conditions that error for some rows' value types are false for those rows", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["n + 1 > 5", "startsWith(s, 'x')", "n > 0"]}, + {expression: "A", fields: {big: "true"}}, + {expression: "B", fields: {xs: "true"}}, + {expression: "C", fields: {pos: "true"}}, + ], + edges: ["input -> s", "s:0 -> A -> output", "s:1 -> B -> output", "s:2 -> C -> output"], + }, + cases: [ + [{n: 5, s: "xy"}, {big: true, xs: true, pos: true}], + [{n: "abc", s: "xa"}, {xs: true}], + [{n: [1], s: "y"}, {}], + [{n: 1, s: 5}, {pos: true}], + [{n: 10, s: null}, {big: true, pos: true}], + [{}, {}], + [{n: {a: 1}, s: "x"}, {xs: true}], + [{n: 0, s: ""}, {}], + [{n: true, s: "xx"}, {xs: true}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Shared nodes and sibling reads. A node fed by several branches runs once on their merged +// outputs; a branch node reading a sibling branch through `$nodes` sees it only if it already ran. +// --------------------------------------------------------------------------------------- + + +{ + name: "one node reached from two branches runs once in every combination", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "pa", fields: {fromA: "1"}}, + {expression: "pb", fields: {fromB: "2"}}, + {expression: "shared", fields: {sharedSaw: "(fromA ?? 0) + (fromB ?? 0)"}}, + {expression: "onlyA", fields: {onlyA: "true"}}, + {expression: "onlyC", fields: {onlyC: "true"}}, + ], + edges: ["input -> s", "s:0 -> pa -> shared -> output", "s:1 -> pb -> shared", "s:0 -> onlyA -> output", "s:2 -> onlyC -> output"], + }, + cases: [ + [{a: true, b: true, c: true}, {onlyA: true, sharedSaw: 3, onlyC: true}], + [{a: true, b: true, c: false}, {onlyA: true, sharedSaw: 3}], + [{a: true, b: false, c: true}, {onlyA: true, sharedSaw: 1, onlyC: true}], + [{a: true, b: false, c: false}, {onlyA: true, sharedSaw: 1}], + [{a: false, b: true, c: true}, {sharedSaw: 2, onlyC: true}], + [{a: false, b: true, c: false}, {sharedSaw: 2}], + [{a: false, b: false, c: true}, {onlyC: true}], + [{a: false, b: false, c: false}, {}], + [{a: true, c: null}, {onlyA: true, sharedSaw: 1}], + ], +} + +// `A -> B` makes A a parent of B: B runs when either parent ran, and reads A through `$nodes` +// only when A was on a taken branch. +{ + name: "a branch node also fed by the sibling branch runs when either branch is taken", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "A", fields: {a: "v"}}, + {expression: "gate", passThrough: true, fields: {}}, + {expression: "B", fields: {bSawA: "$nodes.A != null", fromA: "$nodes.A.a ?? -1"}}, + ], + edges: ["input -> s", "s:0 -> A -> output", "s:1 -> gate -> B -> output", "A -> B"], + }, + cases: [ + [{a: true, b: true, v: 3}, {a: 3, bSawA: true, fromA: 3}], + [{a: false, b: true, v: 3}, {bSawA: false, fromA: -1}], + [{a: true, b: false, v: 4}, {a: 4, bSawA: true, fromA: 4}], + [{a: false, b: false, v: 1}, {}], + [{a: true, b: true, v: 0}, {a: 0, bSawA: true, fromA: 0}], + [{b: true, v: 9}, {bSawA: false, fromA: -1}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Heterogeneous rows: the same switch over inputs whose value types and key presence vary, +// with passThrough branches carrying different shapes through. +// --------------------------------------------------------------------------------------- + + +{ + name: "routing on the type of one field with passThrough branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["type(v) == 'number'", "type(v) == 'string'", "type(v) == 'array'", "v == null", ""]}, + {expression: "N", passThrough: true, fields: {num: "v * 2"}}, + {expression: "S", passThrough: true, fields: {str: "upper(v)"}}, + {expression: "A", passThrough: true, fields: {count: "len(v)"}}, + {expression: "Z", fields: {missing: "true"}}, + {expression: "K", fields: {kind: "type(v)"}}, + ], + edges: ["input -> s", "s:0 -> N -> output", "s:1 -> S -> output", "s:2 -> A -> output", "s:3 -> Z -> output", "s:4 -> K -> output"], + }, + cases: [ + [{v: 3}, {v: 3, num: 6, kind: "number"}], + [{v: "ab"}, {v: "ab", str: "AB", kind: "string"}], + [{v: [1, 2]}, {v: [1, 2], count: 2, kind: "array"}], + [{v: null}, {missing: true, kind: "null"}], + [{}, {missing: true, kind: "null"}], + [{v: true}, {kind: "bool"}], + [{v: {a: 1}}, {kind: "object"}], + [{v: 0, other: "o"}, {v: 0, other: "o", num: 0, kind: "number"}], + [{v: "", other: [1]}, {v: "", other: [1], str: "", kind: "string"}], + [{v: [], n: {x: 1}}, {v: [], n: {x: 1}, count: 0, kind: "array"}], + ], +} + +{ + name: "four conditions over one enum field, overlapping sets", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["tier in ['a', 'b']", "tier in ['b', 'c']", "tier != null and tier != 'a'", "tier == null"]}, + {expression: "AB", fields: {ab: "true"}}, + {expression: "BC", fields: {bc: "true"}}, + {expression: "NA", fields: {notA: "tier"}}, + {expression: "NN", fields: {none: "true"}}, + ], + edges: ["input -> s", "s:0 -> AB -> output", "s:1 -> BC -> output", "s:2 -> NA -> output", "s:3 -> NN -> output"], + }, + cases: [ + [{tier: "a"}, {ab: true}], + [{tier: "b"}, {ab: true, bc: true, notA: "b"}], + [{tier: "c"}, {bc: true, notA: "c"}], + [{tier: "d"}, {notA: "d"}], + [{tier: null}, {none: true}], + [{}, {none: true}], + [{tier: 1}, {notA: 1}], + [{tier: "B"}, {notA: "B"}], + [{tier: ["a"]}, {notA: ["a"]}], + ], +} + +{ + name: "conditions over $nodes of a table that matched nothing for some rows", + graph: { + nodes: [ + {table: "grade", inputs: ["score"], outputs: ["g"], rules: [[">= 90", "'A'"], [">= 70", "'B'"]]}, + {switch: "s", hit: "collect", when: ["$nodes.grade != null", "$nodes.grade == null", "$nodes.input.score < 0"]}, + {expression: "G", fields: {graded: "$nodes.grade.g"}}, + {expression: "U", fields: {ungraded: "true"}}, + {expression: "N", fields: {negative: "true"}}, + ], + edges: ["input -> grade -> s", "s:0 -> G -> output", "s:1 -> U -> output", "s:2 -> N -> output"], + }, + cases: [ + [{score: 95}, {graded: "A"}], + [{score: 75}, {graded: "B"}], + [{score: 10}, {ungraded: true}], + [{score: -5}, {ungraded: true, negative: true}], + [{}, {ungraded: true}], + [{score: "x"}, {ungraded: true}], + [{score: 90}, {graded: "A"}], + [{score: 69}, {ungraded: true}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Collect switches inside loops: each item takes its own outcome set, so one row splits +// into groups per item. +// --------------------------------------------------------------------------------------- + + +{ + name: "a child collect switch per loop item", + decisions: { + line: { + nodes: [ + {switch: "s", hit: "collect", when: ["q > 10", "p > 100", "gift == true", ""]}, + {expression: "b", fields: {bulk: "true"}}, + {expression: "pr", fields: {premium: "true"}}, + {expression: "g", fields: {wrap: "'gift'"}}, + {expression: "l", fields: {line: "q * p"}}, + ], + edges: ["input -> s", "s:0 -> b -> output", "s:1 -> pr -> output", "s:2 -> g -> output", "s:3 -> l -> output"], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "line", inputField: "items", outputPath: "lines", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{q: 1, p: 5}, {q: 20, p: 5}, {q: 1, p: 500}, {q: 20, p: 500, gift: true}]}, {lines: [{line: 5}, {bulk: true, line: 100}, {premium: true, line: 500}, {bulk: true, premium: true, wrap: "gift", line: 10000}]}], + [{items: [{q: 3, p: 3, gift: true}]}, {lines: [{wrap: "gift", line: 9}]}], + [{items: []}, {lines: []}], + [{items: [{q: 11, p: 101}, {q: 10, p: 100}, {q: 0, p: 0, gift: false}]}, {lines: [{bulk: true, premium: true, line: 1111}, {line: 1000}, {line: 0}]}], + [{items: [{q: 2, p: 200, gift: true}, {q: 12, p: 1, gift: true}, {q: 12, p: 120}, {q: 1, p: 1}, {q: 50, p: 50}]}, {lines: [{premium: true, wrap: "gift", line: 400}, {bulk: true, wrap: "gift", line: 12}, {bulk: true, premium: true, line: 1440}, {line: 1}, {bulk: true, line: 2500}]}], + ], +} + +// The child reads the parent request via `$nodes..$nodes.input`. +// An item taking no branch yields `{}`. +{ + name: "per-item conditions compare against the parent request through the child input view", + decisions: { + check: { + nodes: [ + {input: "item"}, + {switch: "s", hit: "collect", when: ["n > ($nodes.item.$nodes.input.limit ?? 10)", "n % 2 == 0"]}, + {expression: "o", fields: {over: "n - ($nodes.item.$nodes.input.limit ?? 10)"}}, + {expression: "e", fields: {even: "true"}}, + ], + edges: ["item -> s", "s:0 -> o -> output", "s:1 -> e -> output"], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "check", inputField: "items", outputPath: "out", executionMode: "loop"}, + ], + }, + cases: [ + [{limit: 3, items: [{n: 1}, {n: 2}, {n: 4}, {n: 5}]}, {out: [{}, {even: true}, {over: 1, even: true}, {over: 2}]}], + [{items: [{n: 10}, {n: 11}, {n: 12}]}, {out: [{even: true}, {over: 1}, {over: 2, even: true}]}], + [{limit: 0, items: [{n: 0}, {n: 1}]}, {out: [{even: true}, {over: 1}]}], + [{limit: 100, items: [{n: 7}, {n: 8}]}, {out: [{}, {even: true}]}], + [{limit: 5, items: []}, {out: []}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Edge shapes per combination: branches straight to the output, two handles into one node, +// dead ends without an output node, and a switch input whose shape varies between rows. +// --------------------------------------------------------------------------------------- + + +{ + name: "a branch straight to the output next to computed branches", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "B", fields: {b2: "true"}}, + {expression: "C", fields: {c2: "true"}}, + ], + edges: ["input -> s", "s:0 -> output", "s:1 -> B -> output", "s:2 -> C -> output"], + }, + cases: [ + [{a: true, b: true, c: true}, {a: true, b: true, c: true, b2: true, c2: true}], + [{a: true, b: true, c: false}, {a: true, b: true, c: false, b2: true}], + [{a: true, b: false, c: true}, {a: true, b: false, c: true, c2: true}], + [{a: true, b: false, c: false}, {a: true, b: false, c: false}], + [{a: false, b: true, c: true}, {b2: true, c2: true}], + [{a: false, b: true, c: false}, {b2: true}], + [{a: false, b: false, c: true}, {c2: true}], + [{a: false, b: false, c: false}, {}], + [{a: true, x: [1], y: {z: null}}, {a: true, x: [1], y: {z: null}}], + ], +} + +// X runs once when either handle routes to it. +{ + name: "two handles of one collect switch into the same node", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b"]}, + {expression: "X", fields: {ran: "true", aFlag: "a == true", bFlag: "b == true"}}, + ], + edges: ["input -> s", "s:0 -> X", "s:1 -> X", "X -> output"], + }, + cases: [ + [{a: true, b: true}, {ran: true, aFlag: true, bFlag: true}], + [{a: true, b: false}, {ran: true, aFlag: true, bFlag: false}], + [{a: false, b: true}, {ran: true, aFlag: false, bFlag: true}], + [{a: false, b: false}, {}], + [{a: true}, {ran: true, aFlag: true, bFlag: false}], + [{}, {}], + ], +} + +// Without an output node the result merges the dead ends that ran (see 25). +{ + name: "collect branches ending in dead ends of a graph without an output node", + graph: { + nodes: [ + {input: "input"}, + {switch: "s", hit: "collect", when: ["a", "b", "c"]}, + {expression: "A", fields: {a: "1"}}, + {expression: "B", fields: {b: "2"}}, + {expression: "C", fields: {c: "3"}}, + ], + edges: ["input -> s", "s:0 -> A", "s:1 -> B", "s:2 -> C"], + }, + cases: [ + [{a: true, b: true, c: true}, {a: 1, b: 2, c: 3}], + [{a: true, b: true, c: false}, {a: 1, b: 2}], + [{a: true, b: false, c: true}, {a: 1, c: 3}], + [{a: true, b: false, c: false}, {a: 1}], + [{a: false, b: true, c: true}, {b: 2, c: 3}], + [{a: false, b: true, c: false}, {b: 2}], + [{a: false, b: false, c: true}, {c: 3}], + [{a: false, b: false, c: false}, {}], + ], +} + +{ + name: "the switch input is a bare array whose length varies per row", + graph: { + nodes: [ + {expression: "each", inputField: "xs", executionMode: "loop", fields: {v: "$root * 2"}}, + {switch: "s", hit: "collect", when: ["len($nodes.each) > 2", "$nodes.each[0].v > 5", "len($nodes.each) == 0", ""]}, + {expression: "L", fields: {long: "len($nodes.each)"}}, + {expression: "H", fields: {bigHead: "$nodes.each[0].v"}}, + {expression: "E", fields: {empty: "true"}}, + {expression: "D", fields: {echo: "map($nodes.each, #.v)"}}, + ], + edges: ["input -> each -> s", "s:0 -> L -> output", "s:1 -> H -> output", "s:2 -> E -> output", "s:3 -> D -> output"], + }, + cases: [ + [{xs: []}, {empty: true, echo: []}], + [{xs: [1]}, {echo: [2]}], + [{xs: [3]}, {bigHead: 6, echo: [6]}], + [{xs: [1, 2, 3]}, {long: 3, echo: [2, 4, 6]}], + [{xs: [9, 9, 9, 9]}, {long: 4, bigHead: 18, echo: [18, 18, 18, 18]}], + [{xs: [0, 0]}, {echo: [0, 0]}], + ], +} + +// `inner` hangs off P only, so it runs only when P ran; it still reads E through `$nodes`. +// E is declared before inner, so when both ran E is visible. +{ + name: "an inner collect switch reads $nodes of outer branch nodes that may not have run", + graph: { + nodes: [ + {switch: "outer", hit: "collect", when: ["n > 0", "n % 2 == 0"]}, + {expression: "P", fields: {posV: "n"}}, + {expression: "E", fields: {evenV: "n"}}, + {switch: "inner", hit: "collect", when: ["$nodes.P.posV > 10", "$nodes.P != null and $nodes.E != null"]}, + {expression: "IB", fields: {innerBig: "true"}}, + {expression: "IO", fields: {innerBoth: "true"}}, + ], + edges: ["input -> outer", "outer:0 -> P -> output", "outer:1 -> E -> output", "P -> inner", "inner:0 -> IB -> output", "inner:1 -> IO -> output"], + }, + cases: [ + [{n: -4}, {evenV: -4}], + [{n: -1}, {}], + [{n: 0}, {evenV: 0}], + [{n: 1}, {posV: 1}], + [{n: 2}, {posV: 2, evenV: 2, innerBoth: true}], + [{n: 11}, {posV: 11, innerBig: true}], + [{n: 12}, {posV: 12, evenV: 12, innerBig: true, innerBoth: true}], + [{n: 13}, {posV: 13, innerBig: true}], + [{n: 20}, {posV: 20, evenV: 20, innerBig: true, innerBoth: true}], + ], +} + +{ + name: "null, missing, false, zero and empty string each take their own outcome set", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["v == null", "v == false", "v == 0", "v == ''", "v != null and v != false"]}, + {expression: "N", fields: {isNull: "true"}}, + {expression: "F", fields: {isFalse: "true"}}, + {expression: "Z", fields: {isZero: "true"}}, + {expression: "S", fields: {isEmpty: "true"}}, + {expression: "T", fields: {truthyish: "true"}}, + ], + edges: ["input -> s", "s:0 -> N -> output", "s:1 -> F -> output", "s:2 -> Z -> output", "s:3 -> S -> output", "s:4 -> T -> output"], + }, + cases: [ + [{v: null}, {isNull: true}], + [{}, {isNull: true}], + [{v: false}, {isFalse: true}], + [{v: 0}, {isZero: true, truthyish: true}], + [{v: ""}, {isEmpty: true, truthyish: true}], + [{v: true}, {truthyish: true}], + [{v: 1}, {truthyish: true}], + [{v: "x"}, {truthyish: true}], + [{v: []}, {truthyish: true}], + [{v: {}}, {truthyish: true}], + ], +} diff --git a/core/engine/tests/spec/graph/68-nodes-across-branches.json5 b/core/engine/tests/spec/graph/68-nodes-across-branches.json5 new file mode 100644 index 00000000..f6304a0f --- /dev/null +++ b/core/engine/tests/spec/graph/68-nodes-across-branches.json5 @@ -0,0 +1,665 @@ +// `$nodes` across branch combinations: reads of nodes on taken and untaken branches, whole +// node objects, `$nodes.input` after transforms, `$nodes` inside loop bodies and children, and +// node names that collide with input keys, field keys and reserved words. Basics are in 15; +// this chapter varies which branches ran from case to case. + + +// --------------------------------------------------------------------------------------- +// Presence of branch nodes per combination. A node that did not run reads as null, whole or +// by member; `keys($nodes)` lists only nodes that ran. +// --------------------------------------------------------------------------------------- + + +// `n` counts input, s and the branch nodes that ran. +{ + name: "presence flags of three collect branches read by a join", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a == true", "b == true", "c == true"]}, + {expression: "A", fields: {v: "10"}}, + {expression: "B", fields: {v: "2"}}, + {expression: "C", fields: {v: "3"}}, + {expression: "join", fields: {ranA: "$nodes.A != null", ranB: "$nodes.B != null", ranC: "$nodes.C != null", aVal: "$nodes.A.v ?? 'none'", bc: "($nodes.B.v ?? 0) + ($nodes.C.v ?? 0)", n: "len(keys($nodes))"}}, + ], + edges: ["input -> s", "s:0 -> A -> join", "s:1 -> B -> join", "s:2 -> C -> join", "join -> output"], + }, + cases: [ + [{a: true, b: true, c: true}, {ranA: true, ranB: true, ranC: true, aVal: 10, bc: 5, n: 5}], + [{a: true, b: true, c: false}, {ranA: true, ranB: true, ranC: false, aVal: 10, bc: 2, n: 4}], + [{a: true, b: false, c: true}, {ranA: true, ranB: false, ranC: true, aVal: 10, bc: 3, n: 4}], + [{a: true, b: false, c: false}, {ranA: true, ranB: false, ranC: false, aVal: 10, bc: 0, n: 3}], + [{a: false, b: true, c: true}, {ranA: false, ranB: true, ranC: true, aVal: "none", bc: 5, n: 4}], + [{a: false, b: true, c: false}, {ranA: false, ranB: true, ranC: false, aVal: "none", bc: 2, n: 3}], + [{a: false, b: false, c: true}, {ranA: false, ranB: false, ranC: true, aVal: "none", bc: 3, n: 3}], + [{a: false, b: false, c: false}, {}], + [{a: "yes", b: true}, {ranA: false, ranB: true, ranC: false, aVal: "none", bc: 2, n: 3}], + ], +} + +{ + name: "one of three first-hit branches ran; whole node objects and members", + graph: { + nodes: [ + {switch: "s", when: ["k == 'a'", "k == 'b'", ""]}, + {expression: "A", fields: {v: "1"}}, + {expression: "B", fields: {v: "'two'"}}, + {expression: "C", fields: {v: "[3]"}}, + {expression: "join", fields: {ran: "$nodes.A != null ? 'A' : $nodes.B != null ? 'B' : 'C'", aIsNull: "$nodes.A == null", bIsNull: "$nodes.B == null", cIsNull: "$nodes.C == null", value: "$nodes.A.v ?? $nodes.B.v ?? $nodes.C.v", sees: "$nodes.A ?? $nodes.B ?? $nodes.C"}}, + ], + edges: ["input -> s", "s:0 -> A -> join", "s:1 -> B -> join", "s:2 -> C -> join", "join -> output"], + }, + cases: [ + [{k: "a"}, {ran: "A", aIsNull: false, bIsNull: true, cIsNull: true, value: 1, sees: {v: 1}}], + [{k: "b"}, {ran: "B", aIsNull: true, bIsNull: false, cIsNull: true, value: "two", sees: {v: "two"}}], + [{k: "c"}, {ran: "C", aIsNull: true, bIsNull: true, cIsNull: false, value: [3], sees: {v: [3]}}], + [{}, {ran: "C", aIsNull: true, bIsNull: true, cIsNull: false, value: [3], sees: {v: [3]}}], + [{k: null}, {ran: "C", aIsNull: true, bIsNull: true, cIsNull: false, value: [3], sees: {v: [3]}}], + [{k: "A"}, {ran: "C", aIsNull: true, bIsNull: true, cIsNull: false, value: [3], sees: {v: [3]}}], + ], +} + +{ + name: "deep member and index reads on untaken branch nodes are null", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", ""]}, + {expression: "A", fields: {"x.y.z": "3", "x.y.w": "'leaf'"}}, + {expression: "B", fields: {list: "[{v: 7}, {v: 8}]"}}, + {expression: "D", fields: {}}, + {expression: "join", fields: {depth: "$nodes.A.x.y.z ?? 'unset'", tail: "$nodes['A']['x']['y']['w']", list0: "$nodes.B.list[0].v", missing: "$nodes.B.list[5].v ?? $nodes.Z.q ?? 'fallback'"}}, + ], + edges: ["input -> s", "s:0 -> A -> join", "s:1 -> B -> join", "s:2 -> D -> join", "join -> output"], + }, + cases: [ + [{a: true, b: true}, {depth: 3, tail: "leaf", list0: 7, missing: "fallback"}], + [{a: true, b: false}, {depth: 3, tail: "leaf", missing: "fallback"}], + [{a: false, b: true}, {depth: "unset", list0: 7, missing: "fallback"}], + [{a: false, b: false}, {depth: "unset", missing: "fallback"}], + ], +} + +{ + name: "the keys of $nodes per combination", + graph: { + nodes: [ + {switch: "s", hit: "collect", when: ["a", "b", ""]}, + {expression: "A", fields: {v: "1"}}, + {expression: "B", fields: {v: "2"}}, + {expression: "D", fields: {v: "3"}}, + {expression: "join", fields: {ran: "filter(['A', 'B', 'D', 'input', 's'], # in keys($nodes))", n: "len(keys($nodes))"}}, + ], + edges: ["input -> s", "s:0 -> A -> join", "s:1 -> B -> join", "s:2 -> D -> join", "join -> output"], + }, + cases: [ + [{a: true, b: true}, {ran: ["A", "B", "D", "input", "s"], n: 5}], + [{a: true, b: false}, {ran: ["A", "D", "input", "s"], n: 4}], + [{a: false, b: true}, {ran: ["B", "D", "input", "s"], n: 4}], + [{a: false, b: false}, {ran: ["D", "input", "s"], n: 3}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Switches routing on `$nodes` of nodes on branches of an earlier switch, taken or not. +// --------------------------------------------------------------------------------------- + + +// `input -> s2` keeps s2 reachable when s1 routes nowhere. +{ + name: "a collect switch over $nodes of an earlier collect switch's branches", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["x > 0", "y > 0"]}, + {expression: "px", fields: {v: "x"}}, + {expression: "py", fields: {v: "y"}}, + {switch: "s2", hit: "collect", when: ["$nodes.px.v > 5", "$nodes.py.v > 5", "$nodes.px == null and $nodes.py == null", "$nodes.px != null and $nodes.py != null"]}, + {expression: "bx", fields: {bigX: "$nodes.px.v"}}, + {expression: "by", fields: {bigY: "$nodes.py.v"}}, + {expression: "nn", fields: {none: "true"}}, + {expression: "bo", fields: {both: "$nodes.px.v + $nodes.py.v"}}, + ], + edges: ["input -> s1", "s1:0 -> px -> s2", "s1:1 -> py -> s2", "input -> s2", "s2:0 -> bx -> output", "s2:1 -> by -> output", "s2:2 -> nn -> output", "s2:3 -> bo -> output"], + }, + cases: [ + [{x: 0, y: 0}, {none: true}], + [{x: 0, y: 4}, {}], + [{x: 0, y: 8}, {bigY: 8}], + [{x: 3, y: 0}, {}], + [{x: 3, y: 4}, {both: 7}], + [{x: 3, y: 8}, {bigY: 8, both: 11}], + [{x: 9, y: 0}, {bigX: 9}], + [{x: 9, y: 4}, {bigX: 9, both: 13}], + [{x: 9, y: 8}, {bigX: 9, bigY: 8, both: 17}], + [{x: 6}, {bigX: 6}], + [{y: 7}, {bigY: 7}], + ], +} + +{ + name: "a table reads its input column from whichever branch node ran", + graph: { + nodes: [ + {switch: "s", when: ["route == 'a'", "route == 'b'", ""]}, + {expression: "A", fields: {n: "15"}}, + {expression: "B", fields: {n: "55"}}, + {expression: "C", fields: {n: "$nodes.input.fallback ?? 0"}}, + {table: "t", inputs: [{field: "$nodes.A.n ?? $nodes.B.n ?? $nodes.C.n", name: "src"}], outputs: ["tier"], rules: [[">= 50", "'high'"], [">= 10", "'mid'"], ["", "'low'"]]}, + ], + edges: ["input -> s", "s:0 -> A -> t", "s:1 -> B -> t", "s:2 -> C -> t", "t -> output"], + }, + cases: [ + [{route: "a"}, {tier: "mid"}], + [{route: "b"}, {tier: "high"}], + [{route: "c", fallback: 99}, {tier: "high"}], + [{fallback: 3}, {tier: "low"}], + [{route: "c"}, {tier: "low"}], + [{route: "a", fallback: 99}, {tier: "mid"}], + ], +} + +{ + name: "a function node sees untaken branch nodes as undefined", + graph: { + nodes: [ + {switch: "s", when: ["a", ""]}, + {expression: "A", fields: {v: "1"}}, + {expression: "B", fields: {v: "2"}}, + {function: "f", source: """export const handler = async (input) => ({aType: typeof input.$nodes.A, bType: typeof input.$nodes.B, v: (input.$nodes.A ?? input.$nodes.B).v});"""}, + ], + edges: ["input -> s", "s:0 -> A -> f", "s:1 -> B -> f", "f -> output"], + }, + cases: [ + [{a: true}, {aType: "object", bType: "undefined", v: 1}], + [{a: false}, {aType: "undefined", bType: "object", v: 2}], + [{}, {aType: "undefined", bType: "object", v: 2}], + ], +} + +{ + name: "custom node templates over taken and untaken branch nodes", + graph: { + nodes: [ + {switch: "s", when: ["a", ""]}, + {expression: "A", fields: {v: "1"}}, + {expression: "B", fields: {v: "2"}}, + {custom: "c", kind: "render", config: {msg: "A={{ $nodes.A.v }}", other: "B={{ $nodes.B.v }}"}}, + ], + edges: ["input -> s", "s:0 -> A -> c", "s:1 -> B -> c", "c -> output"], + }, + cases: [ + [{a: true}, {msg: "A=1", other: "B=null"}, "question: a node that did not run renders as the text null inside a template, like a missing value (see 18)"], + [{a: false}, {msg: "A=null", other: "B=2"}, "question: a node that did not run renders as the text null inside a template, like a missing value (see 18)"], + [{}, {msg: "A=null", other: "B=2"}, "question: a node that did not run renders as the text null inside a template, like a missing value (see 18)"], + ], +} + + +// --------------------------------------------------------------------------------------- +// Whole node objects as values: the output of tables, loops, passThrough nodes and +// sub-decisions read through `$nodes` and copied or compared. +// --------------------------------------------------------------------------------------- + + +{ + name: "whole outputs of four node kinds copied by a later node", + graph: { + nodes: [ + {table: "first", inputs: ["n"], outputs: ["band", "meta.src"], rules: [["> 5", "'hi'", "'t'"], ["", "'lo'", "'t'"]]}, + {table: "coll", hit: "collect", inputs: ["n"], outputs: ["k"], rules: [["> 0", "'pos'"], ["> 5", "'big'"]]}, + {expression: "loop", inputField: "items", executionMode: "loop", fields: {sq: "$root * $root"}}, + {expression: "pt", passThrough: true, outputPath: "wrapped", fields: {m: "n * 10"}}, + {expression: "snap", fields: {first: "$nodes.first", coll: "$nodes.coll", loop: "$nodes.loop", pt: "$nodes.pt"}}, + ], + edges: ["input -> first -> snap", "input -> coll -> snap", "input -> loop -> snap", "input -> pt -> snap", "snap -> output"], + }, + cases: [ + [{n: 7, items: [1, 2]}, {first: {band: "hi", meta: {src: "t"}}, coll: [{k: "pos"}, {k: "big"}], loop: [{sq: 1}, {sq: 4}], pt: {n: 7, items: [1, 2], wrapped: {m: 70}}}], + [{n: 1, items: []}, {first: {band: "lo", meta: {src: "t"}}, coll: [{k: "pos"}], loop: [], pt: {n: 1, items: [], wrapped: {m: 10}}}], + [{n: -1, items: [3]}, {first: {band: "lo", meta: {src: "t"}}, coll: [], loop: [{sq: 9}], pt: {n: -1, items: [3], wrapped: {m: -10}}}], + ], +} + +// Deep equality of node outputs; key order does not matter. +{ + name: "equality of whole node outputs", + graph: { + nodes: [ + {expression: "A", fields: {x: "p", y: "q"}}, + {expression: "B", fields: {y: "q", x: "p"}}, + {expression: "C", fields: {x: "p"}}, + {expression: "cmp", fields: {ab: "$nodes.A == $nodes.B", ac: "$nodes.A == $nodes.C", cx: "$nodes.C == {x: p}", nn: "$nodes.missing == $nodes.other"}}, + ], + edges: ["input -> A -> cmp", "input -> B -> cmp", "input -> C -> cmp", "cmp -> output"], + }, + cases: [ + [{p: 1, q: 2}, {ab: true, ac: false, cx: true, nn: true}, "bug: == on objects is always false, even for equal node outputs (expression spec 03-equality)"], + [{p: "a", q: [1]}, {ab: true, ac: false, cx: true, nn: true}, "bug: == on objects is always false, even for equal node outputs (expression spec 03-equality)"], + [{p: true, q: "x"}, {ab: true, ac: false, cx: true, nn: true}, "bug: == on objects is always false, even for equal node outputs (expression spec 03-equality)"], + ], +} + +{ + name: "a sub-decision's whole result and its absence on an untaken branch", + decisions: { + child: { + nodes: [ + {expression: "e", fields: {r: "x * 2", tag: "'c'"}}, + ], + }, + }, + graph: { + nodes: [ + {switch: "s", when: ["go", ""]}, + {decision: "call", key: "child"}, + {expression: "skip", fields: {skipped: "true"}}, + {expression: "after", fields: {child: "$nodes.call ?? 'not called'", n: "len(keys($nodes.call ?? {}))"}}, + ], + edges: ["input -> s", "s:0 -> call -> after", "s:1 -> skip -> after", "after -> output"], + }, + cases: [ + [{go: true, x: 2}, {child: {r: 4, tag: "c"}, n: 2}], + [{go: true, x: 0}, {child: {r: 0, tag: "c"}, n: 2}], + [{go: false, x: 2}, {child: "not called", n: 0}], + [{x: 2}, {child: "not called", n: 0}], + ], +} + +{ + name: "$nodes of a child whose switch routes nowhere is an empty object", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["x > 0"]}, + {expression: "p", fields: {r: "'pos'"}}, + ], + edges: ["input -> s", "s:0 -> p -> output"], + }, + }, + graph: { + nodes: [ + {decision: "call", key: "child"}, + {expression: "after", fields: {isNull: "$nodes.call == null", count: "len(keys($nodes.call ?? {}))", r: "$nodes.call.r ?? 'none'"}}, + ], + }, + cases: [ + [{x: 5}, {isNull: false, count: 1, r: "pos"}], + [{x: -5}, {isNull: false, count: 0, r: "none"}], + [{}, {isNull: false, count: 0, r: "none"}], + ], +} + + +// --------------------------------------------------------------------------------------- +// `$nodes.input` after transforms: it stays the request as sent, whatever passThrough, loops +// writing back, outputPaths or sub-decisions did on the way. +// --------------------------------------------------------------------------------------- + + +{ + name: "$nodes.input after a chain that overwrites, removes and nests keys", + graph: { + nodes: [ + {expression: "over", passThrough: true, fields: {a: "a * 100", b: "null"}}, + {expression: "nest", passThrough: true, outputPath: "c", fields: {inner: "true"}}, + {expression: "drop", fields: {onlyA: "a", cNow: "c"}}, + {expression: "look", fields: {nowA: "onlyA", origA: "$nodes.input.a", origB: "$nodes.input.b", origC: "$nodes.input.c", cNow: "cNow"}}, + ], + }, + cases: [ + [{a: 1, b: 2, c: 3}, {nowA: 100, origA: 1, origB: 2, origC: 3, cNow: {inner: true}}], + [{a: 2, c: {k: 1}}, {nowA: 200, origA: 2, origC: {k: 1}, cNow: {k: 1, inner: true}}], + [{a: 0, b: "x"}, {nowA: 0, origA: 0, origB: "x", cNow: {inner: true}}], + ], +} + +// The second loop is passThrough-free and reads `$nodes.input` inside its body: the request, +// not the incremented array its own input carries. +{ + name: "$nodes.input after a passThrough loop wrote back into the source array", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "items", executionMode: "loop", passThrough: true, fields: {v: "v + 1", seen: "true"}}, + {expression: "nest", passThrough: true, inputField: "items", outputPath: "second", executionMode: "loop", fields: {orig: "$nodes.input.items"}}, + {expression: "look", fields: {now: "map(items, #.v)", orig: "map($nodes.input.items, #.v)", origSeen: "map($nodes.input.items, #.seen ?? false)", secondLen: "len(second)", inner: "second[0].orig ?? 'none'"}}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: 2}]}, {now: [2, 3], orig: [1, 2], origSeen: [false, false], secondLen: 2, inner: [{v: 1}, {v: 2}]}], + [{items: [{v: 0}]}, {now: [1], orig: [0], origSeen: [false], secondLen: 1, inner: [{v: 0}]}], + [{items: []}, {now: [], orig: [], origSeen: [], secondLen: 0, inner: "none"}], + ], +} + +{ + name: "$nodes.input inside a child is the child's input, after the parent transformed it", + decisions: { + child: { + nodes: [ + {expression: "e", fields: {childX: "$nodes.input.x", childTag: "$nodes.input.tag"}}, + ], + }, + }, + graph: { + nodes: [ + {expression: "pre", fields: {x: "x * 10", tag: "'pre'"}}, + {decision: "call", key: "child"}, + {expression: "after", passThrough: true, fields: {parentX: "$nodes.input.x"}}, + ], + }, + cases: [ + [{x: 1}, {childX: 10, childTag: "pre", parentX: 1}], + [{x: 0.5}, {childX: 5, childTag: "pre", parentX: 0.5}], + ], +} + +{ + name: "$nodes.input on every branch of a collect switch after a transform", + graph: { + nodes: [ + {expression: "pre", fields: {n: "n + 1"}}, + {switch: "s", hit: "collect", when: ["n > 1", "$nodes.input.n > 1", ""]}, + {expression: "A", fields: {a: "[n, $nodes.input.n]"}}, + {expression: "B", fields: {b: "[n, $nodes.input.n]"}}, + {expression: "C", fields: {c: "$nodes.input"}}, + ], + edges: ["input -> pre -> s", "s:0 -> A -> output", "s:1 -> B -> output", "s:2 -> C -> output"], + }, + cases: [ + [{n: 5}, {a: [6, 5], b: [6, 5], c: {n: 5}}], + [{n: 1}, {a: [2, 1], c: {n: 1}}], + [{n: 0}, {c: {n: 0}}], + [{n: 1.5, extra: true}, {a: [2.5, 1.5], b: [2.5, 1.5], c: {n: 1.5, extra: true}}], + ], +} + +{ + name: "$nodes.input with a renamed input node is reached by its name", + graph: { + nodes: [ + {input: "request"}, + {expression: "pre", fields: {v: "v * 2"}}, + {expression: "look", fields: {byName: "$nodes.request.v", byInput: "$nodes.input.v ?? 'none'", now: "v"}}, + ], + }, + cases: [ + [{v: 3}, {byName: 3, byInput: "none", now: 6}], + [{v: 0}, {byName: 0, byInput: "none", now: 0}], + ], +} + + +// --------------------------------------------------------------------------------------- +// `$nodes` inside loop bodies: expression, table and sub-decision loops reading nodes on +// taken and untaken branches, and the loop node itself. +// --------------------------------------------------------------------------------------- + + +{ + name: "an expression loop reads a branch node that may not have run", + graph: { + nodes: [ + {switch: "s", when: ["big", ""]}, + {expression: "B", passThrough: true, fields: {mult: "10"}}, + {expression: "S", passThrough: true, fields: {}}, + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {v: "$root * ($nodes.B.mult ?? 1)", bigRan: "$nodes.B != null"}}, + ], + edges: ["input -> s", "s:0 -> B -> each", "s:1 -> S -> each", "each -> output"], + }, + cases: [ + [{big: true, items: [1, 2]}, {out: [{v: 10, bigRan: true}, {v: 20, bigRan: true}]}], + [{big: false, items: [1, 2]}, {out: [{v: 1, bigRan: false}, {v: 2, bigRan: false}]}], + [{items: [3]}, {out: [{v: 3, bigRan: false}]}], + [{big: true, items: []}, {out: []}], + ], +} + +// `$nodes.each` after the loop is the loop node's output, here `{out: [...]}` because of the +// outputPath. +{ + name: "a loop body cannot see its own node, earlier items or later nodes", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {self: "$nodes.each == null", later: "$nodes.after == null", v: "$root"}}, + {expression: "after", passThrough: true, fields: {n: "len($nodes.each.out)"}}, + ], + }, + cases: [ + [{items: [1, 2]}, {out: [{self: true, later: true, v: 1}, {self: true, later: true, v: 2}], n: 2}], + [{items: []}, {out: [], n: 0}], + ], +} + +{ + name: "a table loop compares items against whichever branch node set the limit", + graph: { + nodes: [ + {switch: "s", when: ["strict", ""]}, + {expression: "st", fields: {lim: "5"}}, + {expression: "lo", fields: {lim: "50"}}, + {expression: "wrap", fields: {rows: "map($nodes.input.xs, {x: #})"}}, + {table: "chk", inputField: "rows", outputPath: "res", executionMode: "loop", inputs: [{field: "x <= ($nodes.st.lim ?? $nodes.lo.lim)", name: "ok"}], outputs: ["ok"], rules: [["true", "true"], ["", "false"]]}, + ], + edges: ["input -> s", "s:0 -> st -> wrap", "s:1 -> lo -> wrap", "wrap -> chk -> output"], + }, + cases: [ + [{strict: true, xs: [1, 6, 60]}, {res: [{ok: true}, {ok: false}, {ok: false}]}], + [{strict: false, xs: [1, 6, 60]}, {res: [{ok: true}, {ok: true}, {ok: false}]}], + [{xs: [50, 51]}, {res: [{ok: true}, {ok: false}]}], + [{strict: true, xs: []}, {res: []}], + ], +} + +{ + name: "sub-decision loop items read a parent branch node through the child input view", + decisions: { + child: { + nodes: [ + {input: "item"}, + {expression: "e", fields: {v: "n + ($nodes.item.$nodes.V.bonus ?? 0)", vipNode: "$nodes.item.$nodes.V != null"}}, + ], + }, + }, + graph: { + nodes: [ + {switch: "s", when: ["vip", ""]}, + {expression: "V", passThrough: true, fields: {bonus: "100"}}, + {expression: "N", passThrough: true, fields: {}}, + {decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}, + ], + edges: ["input -> s", "s:0 -> V -> each", "s:1 -> N -> each", "each -> output"], + }, + cases: [ + [{vip: true, items: [{n: 1}, {n: 2}]}, {out: [{v: 101, vipNode: true}, {v: 102, vipNode: true}]}], + [{vip: false, items: [{n: 1}]}, {out: [{v: 1, vipNode: false}]}], + [{items: []}, {out: []}], + [{vip: true, items: [{n: -100}]}, {out: [{v: 0, vipNode: true}]}], + ], +} + +{ + name: "inside a looped child, $nodes of the child's own branches differ per item", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["k > 0", ""]}, + {expression: "A", fields: {p: "'A'"}}, + {expression: "B", fields: {p: "'B'"}}, + {expression: "j", fields: {path: "$nodes.A.p ?? $nodes.B.p", aNull: "$nodes.A == null", bNull: "$nodes.B == null"}}, + ], + edges: ["input -> s", "s:0 -> A -> j", "s:1 -> B -> j", "j -> output"], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{k: 1}, {k: -1}, {k: 2}]}, {out: [{path: "A", aNull: false, bNull: true}, {path: "B", aNull: true, bNull: false}, {path: "A", aNull: false, bNull: true}]}], + [{items: [{k: 0}]}, {out: [{path: "B", aNull: true, bNull: false}]}], + [{items: []}, {out: []}], + ], +} + +// `prices` without outputPath outputs the bare array, so `share` takes its items from +// `$nodes.input`. +{ + name: "closures inside a loop body read $nodes of an earlier loop", + graph: { + nodes: [ + {expression: "prices", inputField: "items", executionMode: "loop", fields: {p: "price * qty"}}, + {expression: "share", inputField: "$nodes.input.items", outputPath: "shares", executionMode: "loop", fields: {share: "price * qty / sum(map($nodes.prices, #.p))", rank: "len(filter($nodes.prices, #.p > price * qty)) + 1"}}, + ], + }, + cases: [ + [{items: [{price: 1, qty: 1}, {price: 3, qty: 1}]}, {shares: [{share: 0.25, rank: 2}, {share: 0.75, rank: 1}]}], + [{items: [{price: 2, qty: 5}]}, {shares: [{share: 1, rank: 1}]}], + [{items: []}, {shares: []}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Name collisions: node names equal to input keys, to field keys, to the input node's +// default name, to other nodes, and to words with meaning in expressions. +// --------------------------------------------------------------------------------------- + + +{ + name: "a node named like an input key: the bare key reads the input, $nodes the node", + graph: { + nodes: [ + {expression: "amount", passThrough: true, fields: {doubled: "amount * 2"}}, + {expression: "after", fields: {key: "amount", node: "$nodes.amount.doubled", nodeObj: "$nodes.amount"}}, + ], + }, + cases: [ + [{amount: 3}, {key: 3, node: 6, nodeObj: {amount: 3, doubled: 6}}], + [{amount: 0}, {key: 0, node: 0, nodeObj: {amount: 0, doubled: 0}}], + ], +} + +{ + name: "a field key equal to a node name does not shadow $nodes", + graph: { + nodes: [ + {expression: "calc", fields: {v: "x + 1"}}, + {expression: "after", fields: {calc: "'shadow'", read: "$nodes.calc.v", local: "$.calc"}}, + ], + }, + cases: [ + [{x: 1}, {calc: "shadow", read: 2, local: "shadow"}], + [{x: -1}, {calc: "shadow", read: 0, local: "shadow"}], + ], +} + +{ + name: "a node named input next to an input node named request", + graph: { + nodes: [ + {input: "request"}, + {expression: "input", fields: {fake: "true", x: "x * 2"}}, + {expression: "after", fields: {viaInput: "$nodes.input", viaRequest: "$nodes.request.x"}}, + ], + }, + cases: [ + [{x: 1}, {viaInput: {fake: true, x: 2}, viaRequest: 1}], + [{x: 5}, {viaInput: {fake: true, x: 10}, viaRequest: 5}], + ], +} + +// Names are not unique in raw JDM; on exclusive branches only one of the two runs. +{ + name: "two nodes with the same name on exclusive branches (raw JDM)", + graph: {raw: {nodes: [{id: "in", name: "input", type: "inputNode", content: {}}, {id: "sw", name: "s", type: "switchNode", content: {hitPolicy: "first", statements: [{id: "h0", condition: "a"}, {id: "h1", condition: ""}]}}, {id: "d1", name: "dup", type: "expressionNode", content: {expressions: [{id: "x", key: "v", value: "'first'"}]}}, {id: "d2", name: "dup", type: "expressionNode", content: {expressions: [{id: "x", key: "v", value: "'second'"}]}}, {id: "af", name: "after", type: "expressionNode", content: {expressions: [{id: "x", key: "seen", value: "$nodes.dup.v"}]}}, {id: "out", name: "output", type: "outputNode", content: {}}], edges: [{id: "e0", sourceId: "in", targetId: "sw"}, {id: "e1", sourceId: "sw", targetId: "d1", sourceHandle: "h0"}, {id: "e2", sourceId: "sw", targetId: "d2", sourceHandle: "h1"}, {id: "e3", sourceId: "d1", targetId: "af"}, {id: "e4", sourceId: "d2", targetId: "af"}, {id: "e5", sourceId: "af", targetId: "out"}]}}, + cases: [ + [{a: true}, {seen: "first"}], + [{a: false}, {seen: "second"}], + ], +} + +{ + name: "node names that are expression keywords or operators via bracket access", + graph: { + nodes: [ + {expression: "true", fields: {v: "1"}}, + {expression: "null", fields: {v: "2"}}, + {expression: "and", fields: {v: "3"}}, + {expression: "$", fields: {v: "4"}}, + {expression: "after", fields: {t: "$nodes['true'].v", n: "$nodes['null'].v", a: "$nodes['and'].v", d: "$nodes['$'].v", dot: "$nodes.and.v"}}, + ], + edges: ["input -> true -> after", "input -> null -> after", "input -> and -> after", "input -> $ -> after", "after -> output"], + }, + cases: [ + [{}, {t: 1, n: 2, a: 3, d: 4, dot: 3}], + [{v: 9}, {t: 1, n: 2, a: 3, d: 4, dot: 3}], + ], +} + +{ + name: "a node named after a field of its own output, read by the next switch", + graph: { + nodes: [ + {expression: "flag", fields: {flag: "x > 0"}}, + {switch: "s", hit: "collect", when: ["flag", "$nodes.flag.flag", "$nodes.flag == true"]}, + {expression: "A", fields: {a: "true"}}, + {expression: "B", fields: {b: "true"}}, + {expression: "C", fields: {c: "true"}}, + ], + edges: ["input -> flag -> s", "s:0 -> A -> output", "s:1 -> B -> output", "s:2 -> C -> output"], + }, + cases: [ + [{x: 1}, {a: true, b: true}], + [{x: 0}, {}], + [{flag: true, x: -1}, {}], + ], +} + +{ + name: "the request carrying a key named like a branch node", + graph: { + nodes: [ + {switch: "s", when: ["go", ""]}, + {expression: "A", fields: {v: "'node'"}}, + {expression: "B", fields: {}}, + {expression: "after", fields: {fromNodes: "$nodes.A.v ?? 'none'", fromInput: "$nodes.input.A.v ?? 'none'"}}, + ], + edges: ["input -> s", "s:0 -> A -> after", "s:1 -> B -> after", "after -> output"], + }, + cases: [ + [{go: true, A: {v: "input"}}, {fromNodes: "node", fromInput: "input"}], + [{go: false, A: {v: "input"}}, {fromNodes: "none", fromInput: "input"}], + [{go: false}, {fromNodes: "none", fromInput: "none"}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Dynamic node names: the name read from `$nodes` comes from the request and differs per +// case, including names of untaken branches and unknown names. +// --------------------------------------------------------------------------------------- + + +// A and B are not passThrough, so `after` reads the name from `$nodes.input`. +{ + name: "$nodes indexed by a name from the request", + graph: { + nodes: [ + {switch: "s", when: ["a", ""]}, + {expression: "A", fields: {v: "'a-out'"}}, + {expression: "B", fields: {v: "'b-out'"}}, + {expression: "after", fields: {got: "$nodes.input.pick == 'input' ? 'input' : ($nodes[$nodes.input.pick].v ?? 'missing')"}}, + ], + edges: ["input -> s", "s:0 -> A -> after", "s:1 -> B -> after", "after -> output"], + }, + cases: [ + [{a: true, pick: "A"}, {got: "a-out"}], + [{a: true, pick: "B"}, {got: "missing"}], + [{a: false, pick: "B"}, {got: "b-out"}], + [{a: false, pick: "A"}, {got: "missing"}], + [{a: true, pick: "input"}, {got: "input"}], + [{a: true, pick: "zzz"}, {got: "missing"}], + [{a: true}, {got: "missing"}], + [{a: true, pick: 1}, {got: "missing"}], + ], +} diff --git a/core/engine/tests/spec/graph/69-loops-advanced.json5 b/core/engine/tests/spec/graph/69-loops-advanced.json5 new file mode 100644 index 00000000..a15898e8 --- /dev/null +++ b/core/engine/tests/spec/graph/69-loops-advanced.json5 @@ -0,0 +1,659 @@ +// Loops beyond the basics of 13 and 35-37: inputField expressions that filter, map, slice and +// flatten; arrays inside objects with results written to nested outputPaths; loops whose results +// drive switches; `$root` inside loop bodies; sub-decision loops with schemas; and arrays of 100 +// or more items. + + +// --------------------------------------------------------------------------------------- +// inputField expressions. The loop iterates whatever array the expression yields; items are +// the values of that array, not of the source. +// --------------------------------------------------------------------------------------- + + +{ + name: "inputField filter with a threshold from the request", + graph: { + nodes: [ + {expression: "each", inputField: "filter(items, #.n > (min ?? 0))", outputPath: "out", executionMode: "loop", fields: {name: "name", big: "n > 10"}}, + ], + }, + cases: [ + [{min: 1, items: [{name: "a", n: 0}, {name: "b", n: 5}, {name: "c", n: 50}]}, {out: [{name: "b", big: false}, {name: "c", big: true}]}], + [{items: [{name: "a", n: -1}, {name: "b", n: 11}]}, {out: [{name: "b", big: true}]}], + [{min: 100, items: [{name: "a", n: 5}]}, {out: []}], + [{min: 0, items: []}, {out: []}], + ], +} + +{ + name: "inputField map builds the item objects", + graph: { + nodes: [ + {expression: "each", inputField: "map(prices, {p: #, idx: 0})", outputPath: "out", executionMode: "loop", fields: {gross: "p * 1.2", idx: "idx", orig: "$root.p"}}, + ], + }, + cases: [ + [{prices: [10, 0.5]}, {out: [{gross: 12, idx: 0, orig: 10}, {gross: 0.6, idx: 0, orig: 0.5}]}], + [{prices: []}, {out: []}], + [{prices: [-5]}, {out: [{gross: -6, idx: 0, orig: -5}]}], + ], +} + +{ + name: "inputField maps scalars into objects, so fields read by name", + graph: { + nodes: [ + {expression: "each", inputField: "map(names, {name: #, len: len(#)})", outputPath: "out", executionMode: "loop", fields: {label: "upper(name) + ':' + string(len)"}}, + ], + }, + cases: [ + [{names: ["ann", "bo"]}, {out: [{label: "ANN:3"}, {label: "BO:2"}]}], + [{names: [""]}, {out: [{label: ":0"}]}], + [{names: []}, {out: []}], + ], +} + +// Slices are inclusive of both ends (expression spec 04-slices). +{ + name: "inputField slices of the source array", + graph: { + nodes: [ + {expression: "head", inputField: "xs[0:1]", outputPath: "head", executionMode: "loop", fields: {v: "$root"}}, + {expression: "tail", inputField: "xs[2:]", outputPath: "tail", executionMode: "loop", fields: {v: "$root"}}, + ], + edges: ["input -> head -> output", "input -> tail -> output"], + }, + cases: [ + [{xs: [1, 2, 3, 4]}, {head: [{v: 1}, {v: 2}], tail: [{v: 3}, {v: 4}]}], + [{xs: [5, 6, 7]}, {head: [{v: 5}, {v: 6}], tail: [{v: 7}]}], + [{xs: [1, 2]}, {head: [{v: 1}, {v: 2}], tail: []}], + [{xs: [1]}, "!error", "question: a slice end past the array errors rather than clamping (expression spec 04-slices), so the loop node fails"], + ], +} + +{ + name: "inputField flattens the line arrays of every order", + graph: { + nodes: [ + {expression: "each", inputField: "flatten(map(orders, #.lines))", outputPath: "lines", executionMode: "loop", fields: {sku: "sku", qty2: "qty * 2"}}, + ], + }, + cases: [ + [{orders: [{lines: [{sku: "a", qty: 1}, {sku: "b", qty: 2}]}, {lines: [{sku: "c", qty: 3}]}]}, {lines: [{sku: "a", qty2: 2}, {sku: "b", qty2: 4}, {sku: "c", qty2: 6}]}], + [{orders: [{lines: []}, {lines: [{sku: "x", qty: 0}]}]}, {lines: [{sku: "x", qty2: 0}]}], + [{orders: []}, {lines: []}], + ], +} + +{ + name: "inputField with a fallback for a null or missing array", + graph: { + nodes: [ + {expression: "each", inputField: "items ?? defaults ?? []", outputPath: "out", executionMode: "loop", fields: {v: "v"}}, + ], + }, + cases: [ + [{items: [{v: 1}]}, {out: [{v: 1}]}], + [{items: null, defaults: [{v: "d"}]}, {out: [{v: "d"}]}], + [{defaults: [{v: "d"}, {v: "e"}]}, {out: [{v: "d"}, {v: "e"}]}], + [{}, {out: []}], + [{items: []}, {out: []}], + ], +} + +{ + name: "inputField yielding a non-array fails the node", + graph: { + nodes: [ + {expression: "each", inputField: "pick == 1 ? items : pick == 2 ? first : name", outputPath: "out", executionMode: "loop", fields: {v: "v"}}, + ], + }, + cases: [ + [{pick: 1, items: [{v: 1}], first: {v: 2}, name: "x"}, {out: [{v: 1}]}], + [{pick: 2, items: [{v: 1}], first: {v: 2}, name: "x"}, "!error"], + [{pick: 3, items: [{v: 1}], first: {v: 2}, name: "x"}, "!error"], + [{pick: 3, items: [], name: null}, "!error"], + ], +} + +// `cfg` is not passThrough, so the request only reaches the loop through `$nodes.input`. +{ + name: "inputField reads an earlier node and the request together", + graph: { + nodes: [ + {expression: "cfg", fields: {keep: "['a', 'c']"}}, + {expression: "each", inputField: "filter($nodes.input.items, #.k in $nodes.cfg.keep)", outputPath: "kept", executionMode: "loop", fields: {k: "k"}}, + ], + }, + cases: [ + [{items: [{k: "a"}, {k: "b"}, {k: "c"}]}, {kept: [{k: "a"}, {k: "c"}]}], + [{items: [{k: "b"}]}, {kept: []}], + [{items: [{k: "c"}, {k: "c"}]}, {kept: [{k: "c"}, {k: "c"}]}], + ], +} + +{ + name: "a table loop over a filtered and mapped inputField", + graph: { + nodes: [ + {table: "t", inputField: "map(filter(scores, # != null), {s: #})", outputPath: "graded", executionMode: "loop", inputs: ["s"], outputs: ["g"], rules: [[">= 90", "'A'"], [">= 50", "'B'"], ["", "'C'"]]}, + {expression: "flat", fields: {graded: "map(graded, #.g)"}}, + ], + }, + cases: [ + [{scores: [95, null, 50, 3]}, {graded: ["A", "B", "C"]}], + [{scores: [null]}, {graded: []}], + [{scores: [90, 89.99]}, {graded: ["A", "B"]}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Arrays inside objects, with results written to nested outputPaths. A dotted outputPath +// creates the missing spine; with passThrough the rest of the input is kept around it. +// --------------------------------------------------------------------------------------- + + +{ + name: "an array two levels deep, results under a sibling nested path", + graph: { + nodes: [ + {expression: "each", inputField: "cart.lines", outputPath: "cart.priced", passThrough: true, executionMode: "loop", fields: {total: "qty * price"}}, + ], + }, + cases: [ + [{cart: {id: 7, lines: [{qty: 2, price: 3}]}}, {cart: {id: 7, lines: [{qty: 2, price: 3}], priced: [{qty: 2, price: 3, total: 6}]}}], + [{cart: {lines: []}, x: 1}, {cart: {lines: [], priced: []}, x: 1}], + [{cart: {lines: [{qty: 1, price: 0.1}, {qty: 3, price: 0.1}]}}, {cart: {lines: [{qty: 1, price: 0.1}, {qty: 3, price: 0.1}], priced: [{qty: 1, price: 0.1, total: 0.1}, {qty: 3, price: 0.1, total: 0.3}]}}], + ], +} + +// passThrough applies per item too: each result merges into its item, and the result array +// replaces the source array in place. +{ + name: "a loop writes back into the array it reads, three levels deep", + graph: { + nodes: [ + {expression: "each", inputField: "a.b.items", outputPath: "a.b.items", passThrough: true, executionMode: "loop", fields: {done: "true"}}, + ], + }, + cases: [ + [{a: {b: {items: [{id: 1}, {id: 2}], meta: "m"}, c: 1}}, {a: {b: {items: [{id: 1, done: true}, {id: 2, done: true}], meta: "m"}, c: 1}}], + [{a: {b: {items: []}}}, {a: {b: {items: []}}}], + ], +} + +{ + name: "a loop over an array inside each element of an outer array via a child", + decisions: { + dept: { + nodes: [ + {expression: "raise", inputField: "staff", outputPath: "pay", executionMode: "loop", fields: {p: "pay + 1"}}, + {expression: "name", fields: {name: "$nodes.input.name"}}, + ], + edges: ["input -> raise -> output", "input -> name -> output"], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "dept", inputField: "company.depts", outputPath: "report.depts", executionMode: "loop"}, + ], + }, + cases: [ + [{company: {depts: [{name: "x", staff: [{pay: 10}, {pay: 20}]}, {name: "y", staff: []}]}}, {report: {depts: [{name: "x", pay: [{p: 11}, {p: 21}]}, {name: "y", pay: []}]}}], + [{company: {depts: []}}, {report: {depts: []}}], + ], +} + +{ + name: "two loops over two arrays of one object write into one nested result object", + graph: { + nodes: [ + {expression: "ins", inputField: "acct.credits", outputPath: "summary.in", executionMode: "loop", fields: {v: "amount"}}, + {expression: "outs", inputField: "acct.debits", outputPath: "summary.out", executionMode: "loop", fields: {v: "-amount"}}, + {expression: "net", passThrough: true, fields: {"summary.net": "sum(map(summary.in, #.v)) + sum(map(summary.out, #.v))"}}, + ], + edges: ["input -> ins -> net", "input -> outs -> net", "net -> output"], + }, + cases: [ + [{acct: {credits: [{amount: 10}], debits: [{amount: 3}, {amount: 2}]}}, {summary: {in: [{v: 10}], out: [{v: -3}, {v: -2}], net: 5}}], + [{acct: {credits: [], debits: []}}, {summary: {in: [], out: [], net: 0}}], + [{acct: {credits: [{amount: 1}, {amount: 1}], debits: []}}, {summary: {in: [{v: 1}, {v: 1}], out: [], net: 2}}], + ], +} + +{ + name: "a table loop over a nested array writes to an outputPath under the source's parent", + graph: { + nodes: [ + {table: "t", inputField: "policy.drivers", outputPath: "policy.risk", passThrough: true, executionMode: "loop", inputs: ["age"], outputs: ["band", "load"], rules: [["< 25", "'young'", "1.5"], [">= 70", "'senior'", "1.2"], ["", "'std'", "1"]]}, + ], + }, + cases: [ + [{policy: {id: "p", drivers: [{age: 20}, {age: 40}, {age: 80}]}}, {policy: {id: "p", drivers: [{age: 20}, {age: 40}, {age: 80}], risk: [{age: 20, band: "young", load: 1.5}, {age: 40, band: "std", load: 1}, {age: 80, band: "senior", load: 1.2}]}}], + [{policy: {drivers: [{}]}}, {policy: {drivers: [{}], risk: [{band: "std", load: 1}]}}], + ], +} + +{ + name: "an outputPath of a loop that collides with a scalar in the input", + graph: { + nodes: [ + {expression: "each", inputField: "xs", outputPath: "meta.out", passThrough: true, executionMode: "loop", fields: {v: "$root"}}, + ], + }, + cases: [ + [{xs: [1], meta: {keep: true}}, {xs: [1], meta: {keep: true, out: [{v: 1}]}}], + [{xs: [1], meta: "scalar"}, {xs: [1], meta: {out: [{v: 1}]}}], + [{xs: [1], meta: null}, {xs: [1], meta: {out: [{v: 1}]}}], + [{xs: [1], meta: [9]}, {xs: [1], meta: {out: [{v: 1}]}}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Loops feeding switches: routing on aggregates of the loop result, on the loop's `$nodes` +// entry, and per item inside a child. +// --------------------------------------------------------------------------------------- + + +{ + name: "a collect switch over aggregates of a loop result", + graph: { + nodes: [ + {expression: "each", inputField: "xs", outputPath: "res", executionMode: "loop", fields: {v: "$root * 2"}}, + {switch: "s", hit: "collect", when: ["len(res) == 0", "some(res, #.v > 10)", "len(res) > 0 and all(res, #.v > 0)", "sum(map(res, #.v)) > 20"]}, + {expression: "e", fields: {empty: "true"}}, + {expression: "b", fields: {someBig: "true"}}, + {expression: "p", fields: {allPos: "true"}}, + {expression: "u", fields: {sumBig: "sum(map(res, #.v))"}}, + ], + edges: ["input -> each -> s", "s:0 -> e -> output", "s:1 -> b -> output", "s:2 -> p -> output", "s:3 -> u -> output"], + }, + cases: [ + [{xs: []}, {empty: true}], + [{xs: [1]}, {allPos: true}], + [{xs: [6]}, {someBig: true, allPos: true}], + [{xs: [6, 6]}, {someBig: true, allPos: true, sumBig: 24}], + [{xs: [-1, 20]}, {someBig: true, sumBig: 38}], + [{xs: [0]}, {}], + [{xs: [1, 2, 3]}, {allPos: true}], + [{xs: [11, -11]}, {someBig: true}], + [{xs: [5, 5, 1]}, {allPos: true, sumBig: 22}], + ], +} + +// The loop has no outputPath, so the switch input is an array; the conditions read it +// through `$nodes`. +{ + name: "a first switch routes on a bare loop array read through $nodes", + graph: { + nodes: [ + {expression: "each", inputField: "xs", executionMode: "loop", fields: {v: "$root + 1"}}, + {switch: "s", when: ["len($nodes.each) == 0", "$nodes.each[0].v > 5", ""]}, + {expression: "n", fields: {route: "'none'"}}, + {expression: "f", fields: {route: "'firstBig'", first: "$nodes.each[0].v"}}, + {expression: "o", fields: {route: "'other'", n: "len($nodes.each)"}}, + ], + edges: ["input -> each -> s", "s:0 -> n -> output", "s:1 -> f -> output", "s:2 -> o -> output"], + }, + cases: [ + [{xs: []}, {route: "none"}], + [{xs: [10]}, {route: "firstBig", first: 11}], + [{xs: [1, 100]}, {route: "other", n: 2}], + [{xs: [5, 5]}, {route: "firstBig", first: 6}], + [{xs: [4.5]}, {route: "firstBig", first: 5.5}], + ], +} + +{ + name: "a looped child routes every item through its own switch", + decisions: { + tax: { + nodes: [ + {switch: "s", when: ["type == 'book'", "type == 'food'", ""]}, + {expression: "b", fields: {tax: "0", kind: "'book'"}}, + {expression: "f", fields: {tax: "price * 0.05", kind: "'food'"}}, + {expression: "o", fields: {tax: "(price ?? 0) * 0.2", kind: "'other'"}}, + ], + edges: ["input -> s", "s:0 -> b -> output", "s:1 -> f -> output", "s:2 -> o -> output"], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "tax", inputField: "items", outputPath: "taxed", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{type: "book", price: 10}, {type: "food", price: 20}, {type: "toy", price: 5}]}, {taxed: [{tax: 0, kind: "book"}, {tax: 1.0, kind: "food"}, {tax: 1.0, kind: "other"}]}], + [{items: [{price: 10}]}, {taxed: [{tax: 2.0, kind: "other"}]}], + [{items: []}, {taxed: []}], + [{items: [{type: "food", price: 0}, {type: "book", price: 1}]}, {taxed: [{tax: 0.0, kind: "food"}, {tax: 0, kind: "book"}]}], + ], +} + +{ + name: "a loop validates rows, a switch accepts or rejects the batch", + graph: { + nodes: [ + {expression: "check", inputField: "rows", outputPath: "checked", passThrough: true, executionMode: "loop", fields: {bad: "amount == null or amount < 0"}}, + {switch: "s", when: ["some(checked, #.bad)", ""]}, + {expression: "rej", fields: {status: "'reject'", badCount: "len(filter(checked, #.bad))"}}, + {expression: "acc", fields: {status: "'accept'", total: "sum(map(rows, #.amount))"}}, + ], + edges: ["input -> check -> s", "s:0 -> rej -> output", "s:1 -> acc -> output"], + }, + cases: [ + [{rows: [{amount: 1}, {amount: 2}]}, {status: "accept", total: 3}], + [{rows: [{amount: 1}, {amount: -2}]}, {status: "reject", badCount: 1}], + [{rows: [{}, {amount: -1}, {amount: 3}]}, {status: "reject", badCount: 2}], + [{rows: []}, {status: "accept", total: 0}], + ], +} + +{ + name: "a switch picks which loop runs over the same array, then a join reads both", + graph: { + nodes: [ + {switch: "s", when: ["mode == 'sum'", ""]}, + {expression: "dbl", inputField: "xs", executionMode: "loop", fields: {v: "$root * 2"}}, + {expression: "neg", inputField: "xs", executionMode: "loop", fields: {v: "-$root"}}, + {expression: "join", fields: {which: "$nodes.dbl != null ? 'dbl' : 'neg'", vals: "map($nodes.dbl ?? $nodes.neg, #.v)"}}, + ], + edges: ["input -> s", "s:0 -> dbl -> join", "s:1 -> neg -> join", "join -> output"], + }, + cases: [ + [{mode: "sum", xs: [1, 2]}, {which: "dbl", vals: [2, 4]}], + [{mode: "x", xs: [1, 2]}, {which: "neg", vals: [-1, -2]}], + [{xs: []}, {which: "neg", vals: []}], + [{mode: "sum", xs: []}, {which: "dbl", vals: []}], + ], +} + + +// --------------------------------------------------------------------------------------- +// `$root` in loop bodies is the current item: an object, a scalar, an array or null. `$` is +// the item's own result so far. +// --------------------------------------------------------------------------------------- + + +{ + name: "$root of object items: whole item and member access", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {copy: "$root", b: "$root.b ?? 'nob'", a: "$root.a", plain: "a"}}, + ], + }, + cases: [ + [{items: [{a: 1}, {a: 2, b: 3}]}, {out: [{copy: {a: 1}, b: "nob", a: 1, plain: 1}, {copy: {a: 2, b: 3}, b: 3, a: 2, plain: 2}]}], + [{items: [{}]}, {out: [{copy: {}, b: "nob", a: null, plain: null}]}], + ], +} + +{ + name: "$root of mixed scalar items with type checks", + graph: { + nodes: [ + {expression: "each", inputField: "xs", outputPath: "out", executionMode: "loop", fields: {t: "type($root)", isNum: "type($root) == 'number'", twice: "type($root) == 'number' ? $root * 2 : null"}}, + ], + }, + cases: [ + [{xs: [1, "a", true, null]}, {out: [{t: "number", isNum: true, twice: 2}, {t: "string", isNum: false, twice: null}, {t: "bool", isNum: false, twice: null}, {t: "null", isNum: false, twice: null}]}], + [{xs: [[1], {a: 1}]}, {out: [{t: "array", isNum: false, twice: null}, {t: "object", isNum: false, twice: null}]}], + ], +} + +{ + name: "$root of array items indexes and aggregates the inner array", + graph: { + nodes: [ + {expression: "each", inputField: "rows", outputPath: "out", executionMode: "loop", fields: {first: "$root[0]", total: "sum($root)", n: "len($root)"}}, + ], + }, + cases: [ + [{rows: [[1, 2], [3], []]}, {out: [{first: 1, total: 3, n: 2}, {first: 3, total: 3, n: 1}, {first: null, total: 0, n: 0}]}], + ], +} + +{ + name: "$ accumulates per item and resets for the next", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {base: "$root.v * 10", plus: "$.base + 1", self: "$root.v == $.base / 10"}}, + ], + }, + cases: [ + [{items: [{v: 1}, {v: 2}, {v: 3}]}, {out: [{base: 10, plus: 11, self: true}, {base: 20, plus: 21, self: true}, {base: 30, plus: 31, self: true}]}], + [{items: [{v: 0}]}, {out: [{base: 0, plus: 1, self: true}]}], + ], +} + +{ + name: "$root inside closures of a loop body is still the item", + graph: { + nodes: [ + {expression: "each", inputField: "groups", outputPath: "out", executionMode: "loop", fields: {above: "filter($root.vals, # > $root.limit)", scaled: "map($root.vals, # * len($root.vals))"}}, + ], + }, + cases: [ + [{groups: [{limit: 1, vals: [0, 1, 2, 3]}, {limit: 10, vals: [5]}]}, {out: [{above: [2, 3], scaled: [0, 4, 8, 12]}, {above: [], scaled: [5]}]}], + [{groups: [{limit: 0, vals: []}]}, {out: [{above: [], scaled: []}]}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Sub-decision loops with schemas: the child's input schema validates every item, its +// output schema every item result; one failing item fails the parent. +// --------------------------------------------------------------------------------------- + + +{ + name: "child input schema with an enum and a default switch per item", + decisions: { + child: { + nodes: [ + {input: "in", schema: {type: "object", required: ["kind", "n"], properties: {kind: {enum: ["a", "b"]}, n: {type: "number"}}}}, + {switch: "s", when: ["kind == 'a'", ""]}, + {expression: "ea", fields: {r: "'A' + string(n)"}}, + {expression: "eo", fields: {r: "'other'"}}, + ], + edges: ["in -> s", "s:0 -> ea -> output", "s:1 -> eo -> output"], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{kind: "a", n: 1}, {kind: "b", n: 2}]}, {out: [{r: "A1"}, {r: "other"}]}], + [{items: [{kind: "c", n: 1}]}, "!error: NodeError"], + [{items: [{kind: "a", n: 1}, {kind: "a"}]}, "!error: NodeError"], + [{items: []}, {out: []}], + ], +} + +{ + name: "child input schema with a date format: items get date values", + decisions: { + child: { + nodes: [ + {input: "in", schema: {type: "object", required: ["due"], properties: {due: {type: "string", format: "date"}}}}, + {expression: "e", fields: {overdue: "due < d('2025-03-20')", year: "due.year()"}}, + ], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{due: "2025-03-01"}, {due: "2025-04-01"}]}, {out: [{overdue: true, year: 2025}, {overdue: false, year: 2025}]}], + [{items: [{due: "not a date"}]}, "!error: NodeError"], + [{items: []}, {out: []}], + ], +} + +{ + name: "child output schema rejects one item's result", + decisions: { + child: { + nodes: [ + {expression: "e", fields: {pct: "n"}}, + {output: "out", schema: {type: "object", required: ["pct"], properties: {pct: {type: "number", minimum: 0, maximum: 100}}}}, + ], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{n: 1}, {n: 50}]}, {out: [{pct: 1}, {pct: 50}]}], + [{items: [{n: 1}, {n: 101}]}, "!error: NodeError"], + [{items: [{n: -1}]}, "!error: NodeError"], + ], +} + +// Only selected items are validated: an inactive item without an id never reaches the child. +{ + name: "child schema validates items selected by a filtering inputField", + decisions: { + child: { + nodes: [ + {input: "in", schema: {type: "object", required: ["id"], properties: {id: {type: "string"}}}}, + {expression: "e", fields: {id: "upper(id)"}}, + ], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "child", inputField: "filter(items, #.active == true)", outputPath: "out", executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{active: true, id: "a"}, {active: false}, {active: true, id: "b"}]}, {out: [{id: "A"}, {id: "B"}]}], + [{items: [{active: false, id: 5}]}, {out: []}], + [{items: [{active: true, id: 5}]}, "!error: NodeError"], + ], +} + +{ + name: "child schema with passThrough writes validated items back", + decisions: { + child: { + nodes: [ + {input: "in", schema: {type: "object", properties: {q: {type: "integer", minimum: 1}}}}, + {expression: "e", passThrough: true, fields: {ok: "true"}}, + ], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "child", inputField: "items", outputPath: "items", passThrough: true, executionMode: "loop"}, + ], + }, + cases: [ + [{items: [{q: 2}], other: "kept"}, {items: [{q: 2, ok: true}], other: "kept"}], + [{items: [{q: 0}]}, "!error: NodeError"], + [{items: [], other: 1}, {items: [], other: 1}], + ], +} + + +// --------------------------------------------------------------------------------------- +// Arrays of 100 or more items. Results keep item order and every item is processed. +// --------------------------------------------------------------------------------------- + + +{ + name: "expression loop over 120 items with an aggregate", + graph: { + nodes: [ + {expression: "each", inputField: "items", outputPath: "out", executionMode: "loop", fields: {id: "id", sq: "v * v"}}, + {expression: "agg", fields: {n: "len(out)", total: "sum(map(out, #.sq))", last: "out[len(out) - 1].id", firstSq: "out[0].sq"}}, + ], + }, + cases: [ + [{items: [{id: 0, v: 0}, {id: 1, v: 7}, {id: 2, v: 14}, {id: 3, v: 21}, {id: 4, v: 5}, {id: 5, v: 12}, {id: 6, v: 19}, {id: 7, v: 3}, {id: 8, v: 10}, {id: 9, v: 17}, {id: 10, v: 1}, {id: 11, v: 8}, {id: 12, v: 15}, {id: 13, v: 22}, {id: 14, v: 6}, {id: 15, v: 13}, {id: 16, v: 20}, {id: 17, v: 4}, {id: 18, v: 11}, {id: 19, v: 18}, {id: 20, v: 2}, {id: 21, v: 9}, {id: 22, v: 16}, {id: 23, v: 0}, {id: 24, v: 7}, {id: 25, v: 14}, {id: 26, v: 21}, {id: 27, v: 5}, {id: 28, v: 12}, {id: 29, v: 19}, {id: 30, v: 3}, {id: 31, v: 10}, {id: 32, v: 17}, {id: 33, v: 1}, {id: 34, v: 8}, {id: 35, v: 15}, {id: 36, v: 22}, {id: 37, v: 6}, {id: 38, v: 13}, {id: 39, v: 20}, {id: 40, v: 4}, {id: 41, v: 11}, {id: 42, v: 18}, {id: 43, v: 2}, {id: 44, v: 9}, {id: 45, v: 16}, {id: 46, v: 0}, {id: 47, v: 7}, {id: 48, v: 14}, {id: 49, v: 21}, {id: 50, v: 5}, {id: 51, v: 12}, {id: 52, v: 19}, {id: 53, v: 3}, {id: 54, v: 10}, {id: 55, v: 17}, {id: 56, v: 1}, {id: 57, v: 8}, {id: 58, v: 15}, {id: 59, v: 22}, {id: 60, v: 6}, {id: 61, v: 13}, {id: 62, v: 20}, {id: 63, v: 4}, {id: 64, v: 11}, {id: 65, v: 18}, {id: 66, v: 2}, {id: 67, v: 9}, {id: 68, v: 16}, {id: 69, v: 0}, {id: 70, v: 7}, {id: 71, v: 14}, {id: 72, v: 21}, {id: 73, v: 5}, {id: 74, v: 12}, {id: 75, v: 19}, {id: 76, v: 3}, {id: 77, v: 10}, {id: 78, v: 17}, {id: 79, v: 1}, {id: 80, v: 8}, {id: 81, v: 15}, {id: 82, v: 22}, {id: 83, v: 6}, {id: 84, v: 13}, {id: 85, v: 20}, {id: 86, v: 4}, {id: 87, v: 11}, {id: 88, v: 18}, {id: 89, v: 2}, {id: 90, v: 9}, {id: 91, v: 16}, {id: 92, v: 0}, {id: 93, v: 7}, {id: 94, v: 14}, {id: 95, v: 21}, {id: 96, v: 5}, {id: 97, v: 12}, {id: 98, v: 19}, {id: 99, v: 3}, {id: 100, v: 10}, {id: 101, v: 17}, {id: 102, v: 1}, {id: 103, v: 8}, {id: 104, v: 15}, {id: 105, v: 22}, {id: 106, v: 6}, {id: 107, v: 13}, {id: 108, v: 20}, {id: 109, v: 4}, {id: 110, v: 11}, {id: 111, v: 18}, {id: 112, v: 2}, {id: 113, v: 9}, {id: 114, v: 16}, {id: 115, v: 0}, {id: 116, v: 7}, {id: 117, v: 14}, {id: 118, v: 21}, {id: 119, v: 5}]}, {n: 120, total: 19686, last: 119, firstSq: 0}], + [{items: [{id: 0, v: 0}, {id: 1, v: 7}, {id: 2, v: 14}, {id: 3, v: 21}, {id: 4, v: 5}, {id: 5, v: 12}, {id: 6, v: 19}, {id: 7, v: 3}, {id: 8, v: 10}, {id: 9, v: 17}, {id: 10, v: 1}, {id: 11, v: 8}, {id: 12, v: 15}, {id: 13, v: 22}, {id: 14, v: 6}, {id: 15, v: 13}, {id: 16, v: 20}, {id: 17, v: 4}, {id: 18, v: 11}, {id: 19, v: 18}, {id: 20, v: 2}, {id: 21, v: 9}, {id: 22, v: 16}, {id: 23, v: 0}, {id: 24, v: 7}, {id: 25, v: 14}, {id: 26, v: 21}, {id: 27, v: 5}, {id: 28, v: 12}, {id: 29, v: 19}, {id: 30, v: 3}, {id: 31, v: 10}, {id: 32, v: 17}, {id: 33, v: 1}, {id: 34, v: 8}, {id: 35, v: 15}, {id: 36, v: 22}, {id: 37, v: 6}, {id: 38, v: 13}, {id: 39, v: 20}, {id: 40, v: 4}, {id: 41, v: 11}, {id: 42, v: 18}, {id: 43, v: 2}, {id: 44, v: 9}, {id: 45, v: 16}, {id: 46, v: 0}, {id: 47, v: 7}, {id: 48, v: 14}, {id: 49, v: 21}, {id: 50, v: 5}, {id: 51, v: 12}, {id: 52, v: 19}, {id: 53, v: 3}, {id: 54, v: 10}, {id: 55, v: 17}, {id: 56, v: 1}, {id: 57, v: 8}, {id: 58, v: 15}, {id: 59, v: 22}, {id: 60, v: 6}, {id: 61, v: 13}, {id: 62, v: 20}, {id: 63, v: 4}, {id: 64, v: 11}, {id: 65, v: 18}, {id: 66, v: 2}, {id: 67, v: 9}, {id: 68, v: 16}, {id: 69, v: 0}, {id: 70, v: 7}, {id: 71, v: 14}, {id: 72, v: 21}, {id: 73, v: 5}, {id: 74, v: 12}, {id: 75, v: 19}, {id: 76, v: 3}, {id: 77, v: 10}, {id: 78, v: 17}, {id: 79, v: 1}, {id: 80, v: 8}, {id: 81, v: 15}, {id: 82, v: 22}, {id: 83, v: 6}, {id: 84, v: 13}, {id: 85, v: 20}, {id: 86, v: 4}, {id: 87, v: 11}, {id: 88, v: 18}, {id: 89, v: 2}, {id: 90, v: 9}, {id: 91, v: 16}, {id: 92, v: 0}, {id: 93, v: 7}, {id: 94, v: 14}, {id: 95, v: 21}, {id: 96, v: 5}, {id: 97, v: 12}, {id: 98, v: 19}, {id: 99, v: 3}, {id: 100, v: 10}]}, {n: 101, total: 16505, last: 100, firstSq: 0}], + [{items: [{id: 60, v: 6}, {id: 61, v: 13}, {id: 62, v: 20}, {id: 63, v: 4}, {id: 64, v: 11}, {id: 65, v: 18}, {id: 66, v: 2}, {id: 67, v: 9}, {id: 68, v: 16}, {id: 69, v: 0}, {id: 70, v: 7}, {id: 71, v: 14}, {id: 72, v: 21}, {id: 73, v: 5}, {id: 74, v: 12}, {id: 75, v: 19}, {id: 76, v: 3}, {id: 77, v: 10}, {id: 78, v: 17}, {id: 79, v: 1}, {id: 80, v: 8}, {id: 81, v: 15}, {id: 82, v: 22}, {id: 83, v: 6}, {id: 84, v: 13}, {id: 85, v: 20}, {id: 86, v: 4}, {id: 87, v: 11}, {id: 88, v: 18}, {id: 89, v: 2}, {id: 90, v: 9}, {id: 91, v: 16}, {id: 92, v: 0}, {id: 93, v: 7}, {id: 94, v: 14}, {id: 95, v: 21}, {id: 96, v: 5}, {id: 97, v: 12}, {id: 98, v: 19}, {id: 99, v: 3}, {id: 100, v: 10}, {id: 101, v: 17}, {id: 102, v: 1}, {id: 103, v: 8}, {id: 104, v: 15}, {id: 105, v: 22}, {id: 106, v: 6}, {id: 107, v: 13}, {id: 108, v: 20}, {id: 109, v: 4}, {id: 110, v: 11}, {id: 111, v: 18}, {id: 112, v: 2}, {id: 113, v: 9}, {id: 114, v: 16}, {id: 115, v: 0}, {id: 116, v: 7}, {id: 117, v: 14}, {id: 118, v: 21}, {id: 119, v: 5}]}, {n: 60, total: 9708, last: 119, firstSq: 36}], + ], +} + +{ + name: "table loop over 150 items counted per band", + graph: { + nodes: [ + {table: "t", inputField: "items", outputPath: "b", executionMode: "loop", inputs: ["v"], outputs: ["band"], rules: [[">= 15", "'hi'"], [">= 5", "'mid'"], ["", "'lo'"]]}, + {expression: "count", fields: {hi: "len(filter(b, #.band == 'hi'))", mid: "len(filter(b, #.band == 'mid'))", lo: "len(filter(b, #.band == 'lo'))", tenth: "b[9].band"}}, + ], + }, + cases: [ + [{items: [{v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}, {v: 15}, {v: 26}, {v: 6}, {v: 17}, {v: 28}, {v: 8}, {v: 19}, {v: 30}, {v: 10}, {v: 21}, {v: 1}, {v: 12}, {v: 23}, {v: 3}, {v: 14}, {v: 25}, {v: 5}, {v: 16}, {v: 27}, {v: 7}, {v: 18}, {v: 29}, {v: 9}, {v: 20}, {v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}, {v: 15}, {v: 26}, {v: 6}, {v: 17}, {v: 28}, {v: 8}, {v: 19}, {v: 30}, {v: 10}, {v: 21}, {v: 1}, {v: 12}, {v: 23}, {v: 3}, {v: 14}, {v: 25}, {v: 5}, {v: 16}, {v: 27}, {v: 7}, {v: 18}, {v: 29}, {v: 9}, {v: 20}, {v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}, {v: 15}, {v: 26}, {v: 6}, {v: 17}, {v: 28}, {v: 8}, {v: 19}, {v: 30}, {v: 10}, {v: 21}, {v: 1}, {v: 12}, {v: 23}, {v: 3}, {v: 14}, {v: 25}, {v: 5}, {v: 16}, {v: 27}, {v: 7}, {v: 18}, {v: 29}, {v: 9}, {v: 20}, {v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}, {v: 15}, {v: 26}, {v: 6}, {v: 17}, {v: 28}, {v: 8}, {v: 19}, {v: 30}, {v: 10}, {v: 21}, {v: 1}, {v: 12}, {v: 23}, {v: 3}, {v: 14}, {v: 25}, {v: 5}, {v: 16}, {v: 27}, {v: 7}, {v: 18}, {v: 29}, {v: 9}, {v: 20}, {v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}, {v: 15}, {v: 26}, {v: 6}, {v: 17}, {v: 28}, {v: 8}, {v: 19}, {v: 30}, {v: 10}, {v: 21}, {v: 1}, {v: 12}, {v: 23}, {v: 3}, {v: 14}, {v: 25}, {v: 5}, {v: 16}, {v: 27}]}, {hi: 77, mid: 48, lo: 25, tenth: "mid"}], + [{items: [{v: 27}, {v: 16}, {v: 5}, {v: 25}, {v: 14}, {v: 3}, {v: 23}, {v: 12}, {v: 1}, {v: 21}, {v: 10}, {v: 30}, {v: 19}, {v: 8}, {v: 28}, {v: 17}, {v: 6}, {v: 26}, {v: 15}, {v: 4}, {v: 24}, {v: 13}, {v: 2}, {v: 22}, {v: 11}, {v: 0}, {v: 20}, {v: 9}, {v: 29}, {v: 18}, {v: 7}, {v: 27}, {v: 16}, {v: 5}, {v: 25}, {v: 14}, {v: 3}, {v: 23}, {v: 12}, {v: 1}, {v: 21}, {v: 10}, {v: 30}, {v: 19}, {v: 8}, {v: 28}, {v: 17}, {v: 6}, {v: 26}, {v: 15}, {v: 4}, {v: 24}, {v: 13}, {v: 2}, {v: 22}, {v: 11}, {v: 0}, {v: 20}, {v: 9}, {v: 29}, {v: 18}, {v: 7}, {v: 27}, {v: 16}, {v: 5}, {v: 25}, {v: 14}, {v: 3}, {v: 23}, {v: 12}, {v: 1}, {v: 21}, {v: 10}, {v: 30}, {v: 19}, {v: 8}, {v: 28}, {v: 17}, {v: 6}, {v: 26}, {v: 15}, {v: 4}, {v: 24}, {v: 13}, {v: 2}, {v: 22}, {v: 11}, {v: 0}, {v: 20}, {v: 9}, {v: 29}, {v: 18}, {v: 7}, {v: 27}, {v: 16}, {v: 5}, {v: 25}, {v: 14}, {v: 3}, {v: 23}, {v: 12}, {v: 1}, {v: 21}, {v: 10}, {v: 30}, {v: 19}, {v: 8}, {v: 28}, {v: 17}, {v: 6}, {v: 26}, {v: 15}, {v: 4}, {v: 24}, {v: 13}, {v: 2}, {v: 22}, {v: 11}, {v: 0}, {v: 20}, {v: 9}, {v: 29}, {v: 18}, {v: 7}, {v: 27}, {v: 16}, {v: 5}, {v: 25}, {v: 14}, {v: 3}, {v: 23}, {v: 12}, {v: 1}, {v: 21}, {v: 10}, {v: 30}, {v: 19}, {v: 8}, {v: 28}, {v: 17}, {v: 6}, {v: 26}, {v: 15}, {v: 4}, {v: 24}, {v: 13}, {v: 2}, {v: 22}, {v: 11}, {v: 0}]}, {hi: 77, mid: 48, lo: 25, tenth: "hi"}], + [{items: [{v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}, {v: 15}, {v: 26}, {v: 6}, {v: 17}, {v: 28}, {v: 8}, {v: 19}, {v: 30}, {v: 10}, {v: 21}, {v: 1}, {v: 12}, {v: 23}, {v: 3}, {v: 14}, {v: 25}, {v: 5}, {v: 16}, {v: 27}, {v: 7}, {v: 18}, {v: 29}, {v: 9}, {v: 20}, {v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}, {v: 15}, {v: 26}, {v: 6}, {v: 17}, {v: 28}, {v: 8}, {v: 19}, {v: 30}, {v: 10}, {v: 21}, {v: 1}, {v: 12}, {v: 23}, {v: 3}, {v: 14}, {v: 25}, {v: 5}, {v: 16}, {v: 27}, {v: 7}, {v: 18}, {v: 29}, {v: 9}, {v: 20}, {v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}, {v: 15}, {v: 26}, {v: 6}, {v: 17}, {v: 28}, {v: 8}, {v: 19}, {v: 30}, {v: 10}, {v: 21}, {v: 1}, {v: 12}, {v: 23}, {v: 3}, {v: 14}, {v: 25}, {v: 5}, {v: 16}, {v: 27}, {v: 7}, {v: 18}, {v: 29}, {v: 9}, {v: 20}, {v: 0}, {v: 11}, {v: 22}, {v: 2}, {v: 13}, {v: 24}, {v: 4}]}, {hi: 50, mid: 32, lo: 18, tenth: "mid"}], + ], +} + +{ + name: "sub-decision loop with a switch over 100 items", + decisions: { + child: { + nodes: [ + {switch: "s", when: ["n > 0", "n < 0", ""]}, + {expression: "p", fields: {sign: "'pos'", abs: "n"}}, + {expression: "m", fields: {sign: "'neg'", abs: "-n"}}, + {expression: "z", fields: {sign: "'zero'", abs: "0"}}, + ], + edges: ["input -> s", "s:0 -> p -> output", "s:1 -> m -> output", "s:2 -> z -> output"], + }, + }, + graph: { + nodes: [ + {decision: "each", key: "child", inputField: "items", outputPath: "out", executionMode: "loop"}, + {expression: "agg", fields: {pos: "len(filter(out, #.sign == 'pos'))", zero: "len(filter(out, #.sign == 'zero'))", absSum: "sum(map(out, #.abs))", at50: "out[50]"}}, + ], + }, + cases: [ + [{items: [{n: -50}, {n: -49}, {n: -48}, {n: -47}, {n: -46}, {n: -45}, {n: -44}, {n: -43}, {n: -42}, {n: -41}, {n: -40}, {n: -39}, {n: -38}, {n: -37}, {n: -36}, {n: -35}, {n: -34}, {n: -33}, {n: -32}, {n: -31}, {n: -30}, {n: -29}, {n: -28}, {n: -27}, {n: -26}, {n: -25}, {n: -24}, {n: -23}, {n: -22}, {n: -21}, {n: -20}, {n: -19}, {n: -18}, {n: -17}, {n: -16}, {n: -15}, {n: -14}, {n: -13}, {n: -12}, {n: -11}, {n: -10}, {n: -9}, {n: -8}, {n: -7}, {n: -6}, {n: -5}, {n: -4}, {n: -3}, {n: -2}, {n: -1}, {n: 0}, {n: 1}, {n: 2}, {n: 3}, {n: 4}, {n: 5}, {n: 6}, {n: 7}, {n: 8}, {n: 9}, {n: 10}, {n: 11}, {n: 12}, {n: 13}, {n: 14}, {n: 15}, {n: 16}, {n: 17}, {n: 18}, {n: 19}, {n: 20}, {n: 21}, {n: 22}, {n: 23}, {n: 24}, {n: 25}, {n: 26}, {n: 27}, {n: 28}, {n: 29}, {n: 30}, {n: 31}, {n: 32}, {n: 33}, {n: 34}, {n: 35}, {n: 36}, {n: 37}, {n: 38}, {n: 39}, {n: 40}, {n: 41}, {n: 42}, {n: 43}, {n: 44}, {n: 45}, {n: 46}, {n: 47}, {n: 48}, {n: 49}]}, {pos: 49, zero: 1, absSum: 2500, at50: {sign: "zero", abs: 0}}], + [{items: [{n: 49}, {n: 48}, {n: 47}, {n: 46}, {n: 45}, {n: 44}, {n: 43}, {n: 42}, {n: 41}, {n: 40}, {n: 39}, {n: 38}, {n: 37}, {n: 36}, {n: 35}, {n: 34}, {n: 33}, {n: 32}, {n: 31}, {n: 30}, {n: 29}, {n: 28}, {n: 27}, {n: 26}, {n: 25}, {n: 24}, {n: 23}, {n: 22}, {n: 21}, {n: 20}, {n: 19}, {n: 18}, {n: 17}, {n: 16}, {n: 15}, {n: 14}, {n: 13}, {n: 12}, {n: 11}, {n: 10}, {n: 9}, {n: 8}, {n: 7}, {n: 6}, {n: 5}, {n: 4}, {n: 3}, {n: 2}, {n: 1}, {n: 0}, {n: -1}, {n: -2}, {n: -3}, {n: -4}, {n: -5}, {n: -6}, {n: -7}, {n: -8}, {n: -9}, {n: -10}, {n: -11}, {n: -12}, {n: -13}, {n: -14}, {n: -15}, {n: -16}, {n: -17}, {n: -18}, {n: -19}, {n: -20}, {n: -21}, {n: -22}, {n: -23}, {n: -24}, {n: -25}, {n: -26}, {n: -27}, {n: -28}, {n: -29}, {n: -30}, {n: -31}, {n: -32}, {n: -33}, {n: -34}, {n: -35}, {n: -36}, {n: -37}, {n: -38}, {n: -39}, {n: -40}, {n: -41}, {n: -42}, {n: -43}, {n: -44}, {n: -45}, {n: -46}, {n: -47}, {n: -48}, {n: -49}, {n: -50}]}, {pos: 49, zero: 1, absSum: 2500, at50: {sign: "neg", abs: 1}}], + ], +} + +{ + name: "130 scalars through a filtering inputField and passThrough", + graph: { + nodes: [ + {expression: "each", inputField: "map(filter(xs, # % 3 == 0), {x: #})", outputPath: "thirds", passThrough: true, executionMode: "loop", fields: {half: "x / 2"}}, + {expression: "agg", fields: {n: "len(thirds)", inputN: "len(xs)", lastHalf: "thirds[len(thirds) - 1].half"}}, + ], + }, + cases: [ + [{xs: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129]}, {n: 44, inputN: 130, lastHalf: 64.5}], + [{xs: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129]}, {n: 43, inputN: 129, lastHalf: 64.5}], + ], +} + +{ + name: "110 items routed by a collect switch after the loop", + graph: { + nodes: [ + {expression: "each", inputField: "rows", outputPath: "res", executionMode: "loop", fields: {k: "k", flag: "amt > 100"}}, + {switch: "s", hit: "collect", when: ["len(res) > 100", "some(res, #.flag)", "len(filter(res, #.k == 'k0')) == 22", ""]}, + {expression: "a", fields: {many: "true"}}, + {expression: "b", fields: {flagged: "len(filter(res, #.flag))"}}, + {expression: "c", fields: {k0: "true"}}, + {expression: "d", fields: {n: "len(res)"}}, + ], + edges: ["input -> each -> s", "s:0 -> a -> output", "s:1 -> b -> output", "s:2 -> c -> output", "s:3 -> d -> output"], + }, + cases: [ + [{rows: [{k: "k0", amt: 0}, {k: "k1", amt: 1}, {k: "k2", amt: 2}, {k: "k3", amt: 3}, {k: "k4", amt: 4}, {k: "k0", amt: 5}, {k: "k1", amt: 6}, {k: "k2", amt: 7}, {k: "k3", amt: 8}, {k: "k4", amt: 9}, {k: "k0", amt: 10}, {k: "k1", amt: 11}, {k: "k2", amt: 12}, {k: "k3", amt: 13}, {k: "k4", amt: 14}, {k: "k0", amt: 15}, {k: "k1", amt: 16}, {k: "k2", amt: 17}, {k: "k3", amt: 18}, {k: "k4", amt: 19}, {k: "k0", amt: 20}, {k: "k1", amt: 21}, {k: "k2", amt: 22}, {k: "k3", amt: 23}, {k: "k4", amt: 24}, {k: "k0", amt: 25}, {k: "k1", amt: 26}, {k: "k2", amt: 27}, {k: "k3", amt: 28}, {k: "k4", amt: 29}, {k: "k0", amt: 30}, {k: "k1", amt: 31}, {k: "k2", amt: 32}, {k: "k3", amt: 33}, {k: "k4", amt: 34}, {k: "k0", amt: 35}, {k: "k1", amt: 36}, {k: "k2", amt: 37}, {k: "k3", amt: 38}, {k: "k4", amt: 39}, {k: "k0", amt: 40}, {k: "k1", amt: 41}, {k: "k2", amt: 42}, {k: "k3", amt: 43}, {k: "k4", amt: 44}, {k: "k0", amt: 45}, {k: "k1", amt: 46}, {k: "k2", amt: 47}, {k: "k3", amt: 48}, {k: "k4", amt: 49}, {k: "k0", amt: 50}, {k: "k1", amt: 51}, {k: "k2", amt: 52}, {k: "k3", amt: 53}, {k: "k4", amt: 54}, {k: "k0", amt: 55}, {k: "k1", amt: 56}, {k: "k2", amt: 57}, {k: "k3", amt: 58}, {k: "k4", amt: 59}, {k: "k0", amt: 60}, {k: "k1", amt: 61}, {k: "k2", amt: 62}, {k: "k3", amt: 63}, {k: "k4", amt: 64}, {k: "k0", amt: 65}, {k: "k1", amt: 66}, {k: "k2", amt: 67}, {k: "k3", amt: 68}, {k: "k4", amt: 69}, {k: "k0", amt: 70}, {k: "k1", amt: 71}, {k: "k2", amt: 72}, {k: "k3", amt: 73}, {k: "k4", amt: 74}, {k: "k0", amt: 75}, {k: "k1", amt: 76}, {k: "k2", amt: 77}, {k: "k3", amt: 78}, {k: "k4", amt: 79}, {k: "k0", amt: 80}, {k: "k1", amt: 81}, {k: "k2", amt: 82}, {k: "k3", amt: 83}, {k: "k4", amt: 84}, {k: "k0", amt: 85}, {k: "k1", amt: 86}, {k: "k2", amt: 87}, {k: "k3", amt: 88}, {k: "k4", amt: 89}, {k: "k0", amt: 90}, {k: "k1", amt: 91}, {k: "k2", amt: 92}, {k: "k3", amt: 93}, {k: "k4", amt: 94}, {k: "k0", amt: 95}, {k: "k1", amt: 96}, {k: "k2", amt: 97}, {k: "k3", amt: 98}, {k: "k4", amt: 99}, {k: "k0", amt: 100}, {k: "k1", amt: 101}, {k: "k2", amt: 102}, {k: "k3", amt: 103}, {k: "k4", amt: 104}, {k: "k0", amt: 105}, {k: "k1", amt: 106}, {k: "k2", amt: 107}, {k: "k3", amt: 108}, {k: "k4", amt: 109}]}, {many: true, flagged: 9, k0: true, n: 110}], + [{rows: [{k: "k0", amt: 0}, {k: "k1", amt: 1}, {k: "k2", amt: 2}, {k: "k3", amt: 3}, {k: "k4", amt: 4}, {k: "k0", amt: 5}, {k: "k1", amt: 6}, {k: "k2", amt: 7}, {k: "k3", amt: 8}, {k: "k4", amt: 9}, {k: "k0", amt: 10}, {k: "k1", amt: 11}, {k: "k2", amt: 12}, {k: "k3", amt: 13}, {k: "k4", amt: 14}, {k: "k0", amt: 15}, {k: "k1", amt: 16}, {k: "k2", amt: 17}, {k: "k3", amt: 18}, {k: "k4", amt: 19}, {k: "k0", amt: 20}, {k: "k1", amt: 21}, {k: "k2", amt: 22}, {k: "k3", amt: 23}, {k: "k4", amt: 24}, {k: "k0", amt: 25}, {k: "k1", amt: 26}, {k: "k2", amt: 27}, {k: "k3", amt: 28}, {k: "k4", amt: 29}, {k: "k0", amt: 30}, {k: "k1", amt: 31}, {k: "k2", amt: 32}, {k: "k3", amt: 33}, {k: "k4", amt: 34}, {k: "k0", amt: 35}, {k: "k1", amt: 36}, {k: "k2", amt: 37}, {k: "k3", amt: 38}, {k: "k4", amt: 39}, {k: "k0", amt: 40}, {k: "k1", amt: 41}, {k: "k2", amt: 42}, {k: "k3", amt: 43}, {k: "k4", amt: 44}, {k: "k0", amt: 45}, {k: "k1", amt: 46}, {k: "k2", amt: 47}, {k: "k3", amt: 48}, {k: "k4", amt: 49}, {k: "k0", amt: 50}, {k: "k1", amt: 51}, {k: "k2", amt: 52}, {k: "k3", amt: 53}, {k: "k4", amt: 54}, {k: "k0", amt: 55}, {k: "k1", amt: 56}, {k: "k2", amt: 57}, {k: "k3", amt: 58}, {k: "k4", amt: 59}, {k: "k0", amt: 60}, {k: "k1", amt: 61}, {k: "k2", amt: 62}, {k: "k3", amt: 63}, {k: "k4", amt: 64}, {k: "k0", amt: 65}, {k: "k1", amt: 66}, {k: "k2", amt: 67}, {k: "k3", amt: 68}, {k: "k4", amt: 69}, {k: "k0", amt: 70}, {k: "k1", amt: 71}, {k: "k2", amt: 72}, {k: "k3", amt: 73}, {k: "k4", amt: 74}, {k: "k0", amt: 75}, {k: "k1", amt: 76}, {k: "k2", amt: 77}, {k: "k3", amt: 78}, {k: "k4", amt: 79}, {k: "k0", amt: 80}, {k: "k1", amt: 81}, {k: "k2", amt: 82}, {k: "k3", amt: 83}, {k: "k4", amt: 84}, {k: "k0", amt: 85}, {k: "k1", amt: 86}, {k: "k2", amt: 87}, {k: "k3", amt: 88}, {k: "k4", amt: 89}, {k: "k0", amt: 90}, {k: "k1", amt: 91}, {k: "k2", amt: 92}, {k: "k3", amt: 93}, {k: "k4", amt: 94}, {k: "k0", amt: 95}, {k: "k1", amt: 96}, {k: "k2", amt: 97}, {k: "k3", amt: 98}, {k: "k4", amt: 99}]}, {n: 100}], + [{rows: [{k: "k0", amt: 5}, {k: "k1", amt: 6}, {k: "k2", amt: 7}, {k: "k3", amt: 8}, {k: "k4", amt: 9}, {k: "k0", amt: 10}, {k: "k1", amt: 11}, {k: "k2", amt: 12}, {k: "k3", amt: 13}, {k: "k4", amt: 14}, {k: "k0", amt: 15}, {k: "k1", amt: 16}, {k: "k2", amt: 17}, {k: "k3", amt: 18}, {k: "k4", amt: 19}, {k: "k0", amt: 20}, {k: "k1", amt: 21}, {k: "k2", amt: 22}, {k: "k3", amt: 23}, {k: "k4", amt: 24}, {k: "k0", amt: 25}, {k: "k1", amt: 26}, {k: "k2", amt: 27}, {k: "k3", amt: 28}, {k: "k4", amt: 29}, {k: "k0", amt: 30}, {k: "k1", amt: 31}, {k: "k2", amt: 32}, {k: "k3", amt: 33}, {k: "k4", amt: 34}, {k: "k0", amt: 35}, {k: "k1", amt: 36}, {k: "k2", amt: 37}, {k: "k3", amt: 38}, {k: "k4", amt: 39}, {k: "k0", amt: 40}, {k: "k1", amt: 41}, {k: "k2", amt: 42}, {k: "k3", amt: 43}, {k: "k4", amt: 44}, {k: "k0", amt: 45}, {k: "k1", amt: 46}, {k: "k2", amt: 47}, {k: "k3", amt: 48}, {k: "k4", amt: 49}, {k: "k0", amt: 50}, {k: "k1", amt: 51}, {k: "k2", amt: 52}, {k: "k3", amt: 53}, {k: "k4", amt: 54}, {k: "k0", amt: 55}, {k: "k1", amt: 56}, {k: "k2", amt: 57}, {k: "k3", amt: 58}, {k: "k4", amt: 59}, {k: "k0", amt: 60}, {k: "k1", amt: 61}, {k: "k2", amt: 62}, {k: "k3", amt: 63}, {k: "k4", amt: 64}, {k: "k0", amt: 65}, {k: "k1", amt: 66}, {k: "k2", amt: 67}, {k: "k3", amt: 68}, {k: "k4", amt: 69}, {k: "k0", amt: 70}, {k: "k1", amt: 71}, {k: "k2", amt: 72}, {k: "k3", amt: 73}, {k: "k4", amt: 74}, {k: "k0", amt: 75}, {k: "k1", amt: 76}, {k: "k2", amt: 77}, {k: "k3", amt: 78}, {k: "k4", amt: 79}, {k: "k0", amt: 80}, {k: "k1", amt: 81}, {k: "k2", amt: 82}, {k: "k3", amt: 83}, {k: "k4", amt: 84}, {k: "k0", amt: 85}, {k: "k1", amt: 86}, {k: "k2", amt: 87}, {k: "k3", amt: 88}, {k: "k4", amt: 89}, {k: "k0", amt: 90}, {k: "k1", amt: 91}, {k: "k2", amt: 92}, {k: "k3", amt: 93}, {k: "k4", amt: 94}, {k: "k0", amt: 95}, {k: "k1", amt: 96}, {k: "k2", amt: 97}, {k: "k3", amt: 98}, {k: "k4", amt: 99}, {k: "k0", amt: 100}, {k: "k1", amt: 101}, {k: "k2", amt: 102}, {k: "k3", amt: 103}, {k: "k4", amt: 104}, {k: "k0", amt: 105}, {k: "k1", amt: 106}, {k: "k2", amt: 107}, {k: "k3", amt: 108}, {k: "k4", amt: 109}]}, {many: true, flagged: 9, n: 105}], + ], +} diff --git a/core/engine/tests/spec/graph/70-generated-a.json5 b/core/engine/tests/spec/graph/70-generated-a.json5 new file mode 100644 index 00000000..bbee17c0 --- /dev/null +++ b/core/engine/tests/spec/graph/70-generated-a.json5 @@ -0,0 +1,5680 @@ +// Generated graphs, profile a: 3-8 nodes, expression-heavy, about a third tables, few switches and loops, mostly clean rows. +// +// Generator: scratchpad gen/graphgen.py, `python3 graphgen.py a`, seed 70017, 80 suites. +// Random DAGs mixing expression nodes (arithmetic, string, boolean, ternary and `??` over input +// fields, earlier keys via `$` and ancestors via `$nodes`), first/collect tables with random cells +// (equality, ranges, lists, wildcards, null), first/collect switches with random conditions, +// passThrough/outputPath/inputField choices and loops over `items`. Rows vary types per field: +// numbers, strings, bools, null, missing, wrong types, nested objects and arrays. +// +// Outputs recorded from the walker; this chapter exists to differential-test the engines. + +{ + name: "ga000: 4 nodes, expr, switch, expr, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k1: "code ?? tier", + k2: "min([-(-(0.5)), len(`v${(b ?? 0)}-${(code ?? '?')}`)])", + "m.k3": "(((vip ?? false)) or (b >= (b ?? 0))) or (tier != 'gold')", + }}, + {switch: "s2", when: ["len(lower((tier ?? 'none'))) < (max([b, k2])) / 10", "(((vip ?? false)) or (0.5 < (k2 ?? -1))) or ((vip ?? false))", ""]}, + {expression: "e3", passThrough: true, fields: { + k4: "((vip ?? false) ? (k2 ?? 1) * len((tier ?? '?')) : (b ?? k1 ?? 0))", + k5: "((k2 ?? -1) * floor(b))", + k6: "1", + "m.k3": "tier ?? k2", + }}, + {table: "t4", inputs: ["code"], outputs: ["k8", "k9"], rules: [ + ["", "false", "'low'"], + ["null", "false", "'high'"], + ["", "(m.k3 ?? false)", "'mid'"], + ["$ != 'gold'", "(b ?? 0) * -4 * (b ?? 1) - 2.25 in [0..10]", "string(0.5 == (k2 ?? -1) + (k2 ?? -1))"], + ["$ != ''", "false", "'mid'"], + ["'silver', 'bronze'", "(b ?? -1) in [0..10]", "'mid'"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "e1 -> e3", + "s2:0 -> t4", + "e1 -> output", + "s2:1 -> output", + "s2:2 -> output", + "e3 -> output", + "t4 -> output", + ], + }, + cases: [ + [{code: "Gold", vip: true, tier: "gold", b: 10, nums: []}, {b: 10, code: "Gold", k1: "Gold", k2: 0.5, k4: 2.0, k5: 5.0, k6: 1, m: {k3: true}, nums: [], tier: "gold", vip: true}], + [{code: "a", vip: true, cust: {age: 31, tier: "Gold", active: true}, tier: "bronze", b: 2, nums: [101, 0, 0.1, 99, 0.5]}, {b: 2, code: "a", cust: {active: true, age: 31, tier: "Gold"}, k1: "a", k2: 0.5, k4: 3.0, k5: 1.0, k6: 1, m: {k3: true}, nums: [101, 0, 0.1, 99, 0.5], tier: "bronze", vip: true}], + [{code: "gold", vip: false, cust: {age: 2.5, tier: "gold", active: true}, tier: "b", b: 10, nums: []}, {b: 10, code: "gold", cust: {active: true, age: 2.5, tier: "gold"}, k1: "gold", k2: 0.5, k4: 10, k5: 5.0, k6: 1, m: {k3: true}, nums: [], tier: "b", vip: false}], + [{code: "b", vip: false, cust: {age: -0.1, tier: "gold ", active: false}, tier: "gold ", b: 1, nums: [{x: 1}]}, {b: 1, code: "b", cust: {active: false, age: -0.1, tier: "gold "}, k1: "b", k2: 0.5, k4: 1, k5: 0.5, k6: 1, m: {k3: true}, nums: [{x: 1}], tier: "gold ", vip: false}], + [{code: "bronze", vip: true, cust: {age: 10, tier: "b", active: true}, b: 2.5, nums: [-25, -25, 1, 99, 0.1]}, {b: 2.5, code: "bronze", cust: {active: true, age: 10, tier: "b"}, k1: "bronze", k2: 0.5, k4: 0.5, k5: 1.0, k6: 1, m: {k3: true}, nums: [-25, -25, 1, 99, 0.1], vip: true}], + [{code: "", vip: true, cust: {age: 5, tier: "zz", active: true}, tier: "b", b: 3, nums: [11, -25, 50]}, {b: 3, code: "", cust: {active: true, age: 5, tier: "zz"}, k1: "", k2: 0.5, k4: 0.5, k5: 1.5, k6: 1, m: {k3: true}, nums: [11, -25, 50], tier: "b", vip: true}], + [{code: "silver", vip: false, cust: {age: 99, tier: "gold", active: true}, tier: "gold ", nums: [11]}, "!error"], + [{code: "bronze", vip: true, cust: {age: 21, tier: "a", active: true}, tier: null, b: -0.1, nums: [], extra: "e"}, {b: -0.1, code: "bronze", cust: {active: true, age: 21, tier: "a"}, extra: "e", k1: "bronze", k2: 0.5, k4: 0.5, k5: -0.5, k6: 1, m: {k3: true}, nums: [], vip: true}], + [{code: "gold", vip: 0, cust: {age: -25, tier: "b", active: false}, tier: "Gold", b: -1, nums: null}, "!error"], + [{code: "Gold", vip: false, cust: {tier: "silver", active: false}, tier: "zz", b: null, nums: [2]}, "!error"], + [{code: "Gold", vip: false, cust: {age: 0.5, tier: "x", active: false}, tier: null, b: 1, nums: [-25, 11, 21, 10, -1]}, {b: 1, code: "Gold", cust: {active: false, age: 0.5, tier: "x"}, k1: "Gold", k2: 0.5, k4: 1, k5: 0.5, k6: 1, m: {k3: true}, nums: [-25, 11, 21, 10, -1], vip: false}], + [{code: "gold ", vip: true, cust: {age: null, tier: "b", active: true}, tier: "b", b: null, nums: [3, 5]}, "!error"], + [{code: "zz", vip: false, cust: {age: -25, tier: "Gold", active: true}, tier: "bronze", b: 1, nums: null}, {b: 1, code: "zz", cust: {active: true, age: -25, tier: "Gold"}, k1: "zz", k2: 0.5, k4: 1, k5: 0.5, k6: 1, m: {k3: true}, tier: "bronze", vip: false}], + [{code: "", cust: {age: -0.1, tier: "b", active: true}, tier: "Gold", nums: null}, "!error"], + [{code: "", vip: false, cust: null, tier: "zz", b: 11, nums: []}, {b: 11, code: "", k1: "", k2: 0.5, k4: 11, k5: 5.5, k6: 1, m: {k3: true}, nums: [], tier: "zz", vip: false}], + [{code: "x", vip: false, cust: null, tier: 5, b: 2, nums: [7]}, {b: 2, code: "x", k1: "x", k2: 0.5, k4: 2, k5: 1.0, k6: 1, m: {k3: true}, nums: [7], tier: 5, vip: false}], + [{code: "b", cust: null, tier: null, b: 1, nums: null}, {b: 1, code: "b", k1: "b", k2: 0.5, k4: 1, k5: 0.5, k6: 1, m: {k3: true}}], + [{code: "gold ", vip: false, cust: {age: -1, tier: "gold ", active: true}, tier: "b", nums: "1,2", extra: {deep: {x: 1}}}, "!error"], + [{code: "b", vip: null, cust: {age: 21, tier: "bronze", active: true}, b: -0.1}, {b: -0.1, code: "b", cust: {active: true, age: 21, tier: "bronze"}, k1: "b", k2: 0.5, k4: -0.1, k5: -0.5, k6: 1, m: {k3: true}}], + [{code: "", vip: false, cust: "cust", tier: "b", b: 2.5, nums: [101]}, {b: 2.5, code: "", cust: "cust", k1: "", k2: 0.5, k4: 2.5, k5: 1.0, k6: 1, m: {k3: true}, nums: [101], tier: "b", vip: false}], + ], +} + +{ + name: "ga001: 6 nodes, loop expr, switch, expr, switch, table, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k10: "(tag ?? '?')", + k11: "min([-(len((tag ?? ''))), (0.5) + (price ?? -1)])", + k12: "(tag ?? '?')", + k13: "qty", + }}, + {switch: "s2", when: ["(-4 in [0..10])", "not (-4 > 3)", "(2.25 == (1)) or (-4 == 1)"]}, + {expression: "e3", fields: { + k14: "vip ?? vip", + }}, + {switch: "s4", when: ["(not (0 == 2)) and (false)", "0.5 < (0 ?? k14 ?? 0)", "-(2) > 2.25 + 100 * (10)", ""]}, + {table: "t5", inputs: ["vip"], outputs: ["k15", "m.k16"], rules: [ + ["false", "true", "-5"], + ["null", "false", "(true ? 0.5 : 2.25) + -4 % 3"], + ["true", "false", "2"], + ["", "not (endsWith((tier ?? ''), 'g'))", "(0 ?? k14 ?? 0)"], + ["", "((vip ?? false)) or ((vip ?? false))", "0"], + ]}, + {expression: "e6", passThrough: true, fields: { + "m.k17": "min([((m.k16 ?? 0)) / 2, (m.k16 ?? 0)]) in [1..100]", + k18: "string('gold' in ['gold', 'silver', 'a']) + '-' + 'none'", + k19: "-((m.k16) * 2 + (m.k16 ?? -1))", + k20: "0", + }}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "s2:2 -> e3", + "e3 -> s4", + "s4:2 -> t5", + "s2:2 -> t5", + "e3 -> e6", + "t5 -> e6", + "s2:0 -> output", + "s4:0 -> output", + "s4:1 -> output", + "s4:3 -> output", + "e6 -> output", + ], + }, + cases: [ + [{items: [1, 2], vip: true, tier: true}, "!error"], + [{items: [{price: 3, qty: -1, tag: null}, {price: 2.5, qty: 50, tag: ""}], vip: false, extra: "e"}, {}], + [{items: [{price: -14, qty: 21}, {price: 1000, tag: "gold "}], vip: false, tier: "b"}, {}], + [{items: [{price: 99, qty: -0.1, tag: "zz"}, {price: 5, qty: -1, tag: "a"}], vip: false, tier: "zz", extra: "e"}, {}], + [{items: [], vip: null, tier: "silver"}, {}], + [{items: [{price: 3, qty: 99, tag: "gold "}], vip: null}, {}], + [{items: "items", vip: true, tier: "Gold"}, "!error"], + [{items: [{price: true, qty: 100, tag: "bronze"}, {price: 99, qty: 0, tag: "Gold"}], tier: "x"}, "!error"], + [{items: [{qty: 0.5, tag: "gold "}, {price: 3, qty: 7, tag: "gold "}, {price: 18, tag: "x"}, {price: 1, qty: 3, tag: "gold"}], vip: false, tier: null}, {}], + [{items: [], vip: true, tier: "a"}, {}], + [{items: [{price: 2}, {price: 3, qty: 3, tag: "Gold"}, {price: 27, qty: 100, tag: "bronze"}], vip: true, tier: "x"}, {}], + [{items: [{price: 3, qty: 50}], vip: false, tier: "gold "}, {}], + [{items: [{price: 10, qty: 5, tag: "gold "}, {price: 99, qty: -0.1, tag: ""}], vip: true, tier: ""}, {}], + [{items: [{price: 21, qty: 18, tag: ""}, {price: 11, qty: 101, tag: "silver"}, {price: "abc", qty: 18, tag: "gold"}, {price: 18, qty: 0, tag: "silver"}], vip: true, tier: "b", extra: "e"}, "!error"], + [{items: [{price: 101, qty: 99, tag: "Gold"}, {price: -1, qty: 0, tag: "bronze"}, {price: 21, qty: 18, tag: "Gold"}], vip: false, tier: null}, {}], + [{items: [{price: 99, qty: 99, tag: {t: "x"}}, {price: 0, tag: "Gold"}, {price: 99, qty: 99, tag: "gold "}, {price: 2.5, qty: 50, tag: ""}], vip: true, tier: ["gold"]}, "!error"], + [{items: [{price: 1, qty: 2, tag: "gold "}, {price: 111, qty: 21, tag: "zz"}, {qty: 10}], vip: false, tier: "bronze"}, {}], + [{items: [{price: -0.1, tag: "b"}, {price: 55, qty: 11, tag: 5}], vip: true, tier: "gold"}, "!error"], + ], +} + +{ + name: "ga002: 7 nodes, table, table, expr, table, expr, table, expr", + graph: { + nodes: [ + {table: "t1", inputs: ["n"], outputs: ["k21", "k21"], rules: [ + ["18, 19", "0.5 + (cust.age ?? 1) > (-(0.5))", "1"], + ["!= 10", "true", "1 + (n ?? 1) % 2 * max([b, (n ?? 0)])"], + ["null", "true", "0"], + ["", "((n ?? -1)) % 3 <= -4", "2"], + ]}, + {table: "t2", inputs: ["lower((s ?? 'none'))", "(cust.tier ?? '')", "lower(s)"], outputs: ["k23"], outputPath: "res", rules: [ + ["'gold'", "$ != ''", "'gold', 'gold'", "false"], + ["startsWith($, 'g')", "null", "'silver', 'b'", "string((k21 ?? 1) in [-5..5]) in ['gold', 'silver', 'a']"], + ["'x'", "", "not('gold')", "false"], + ["'', 'gold'", "'gold'", "", "true"], + ["'a'", "", "$ != 'a'", "false"], + ["$ != 'a'", "not('gold')", "'a', 'b'", "true"], + ["", "", "", "true"], + ]}, + {expression: "e3", outputPath: "lines", fields: { + k24: "(b ?? 0) + 0 - b", + k25: "(0 - 1 in [1..100] ? string(res.k23) + ' ' + (res.k23 ? ($.k26 ?? '') : 'x') : `v${(n ?? -1)}-${'gold'}`)", + k26: "(contains('none' + '' + '', 'a') ? upper('gold') : 'gold')", + }}, + {table: "t4", inputs: ["(n ?? b ?? 0) + round(0)"], outputs: ["res.k28"], rules: [ + ["$ > -1 and $ < 4", "0.25"], + ["(50..51)", "1"], + ["not(0)", "0"], + ["!= 0", "(((true) and (false)) or ((cust.active ?? false)) ? -4 % 2 % 2 : 2 + abs((n ?? 1)))"], + ["(50..60)", "(n ?? 1) * (b ?? 1) + (b ?? 1) - (n ?? 1) + (n ?? -1)"], + ]}, + {expression: "e5", passThrough: true, fields: { + k29: "string(string((res.k28 ?? 1)) != 'x')", + k30: "('A-1' == 'silver' ? (res.k28 ?? 0) : (res.k28 ?? res.k28 ?? 0)) - (false ? (0.5) / 2 : (false ? (res.k28 ?? 1) : res.k28))", + k31: "abs(res.k28) < (0 - 0)", + }}, + {table: "t6", inputs: ["(-4) / 0.5 % 7", "string((0))"], outputs: ["k32"], rules: [ + ["[100..105]", "startsWith($, 'x')", "'A-1' in ['gold', 'silver', 'a']"], + ["< 21", "", "false"], + ["$ > 50 and $ < 55", "null", "false"], + ["!= 10", "startsWith($, 's')", "false"], + ]}, + {expression: "e7", passThrough: true, fields: { + k33: "string(endsWith((lines.k26 ?? '?'), 'g'))", + k34: "k29", + }}, + ], + edges: [ + "input -> t1", + "input -> t2", + "t1 -> t2", + "t2 -> e3", + "input -> e3", + "input -> t4", + "t4 -> e5", + "t2 -> t6", + "e3 -> e7", + "e5 -> e7", + "t1 -> output", + "t6 -> output", + "e7 -> output", + ], + }, + cases: [ + [{code: "gold", b: 7, s: "zz", n: -1, cust: {age: 10, tier: "b", active: null}}, {k21: -6, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0, k25: "v-1-gold", k26: "gold"}, res: {k28: 3}}], + [{b: -1, s: "a", n: 0.1, cust: {age: 0.5, tier: "b"}}, {k21: 1.01, k29: "true", k30: 0.00, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0, k25: "v0.1-gold", k26: "gold"}, res: {k28: 0.25}}], + [{code: "zz", s: "b", n: 2, cust: 5}, "!error"], + [{code: "Gold", b: 0.1, s: "gold", cust: {tier: "gold ", active: true}}, {k21: 1.1, k29: "true", k30: 0.00, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0.0, k25: "v-1-gold", k26: "gold"}, res: {k28: 0.25}}], + [{code: null, b: null, s: null, n: 0.1, cust: {age: 50, tier: "gold", active: true}}, "!error"], + [{code: "gold", s: "a", n: 0.5, cust: null}, "!error"], + [{code: "silver", b: 100, s: "b", n: 7, cust: {age: 1000000000000000000000, tier: "zz", active: true}}, {k21: 101, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0, k25: "v7-gold", k26: "gold"}, res: {k28: 0}}], + [{code: "zz", b: 7, s: true, n: 21, cust: null}, {k21: 22, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0, k25: "v21-gold", k26: "gold"}, res: {k28: 23}}], + [{code: true, b: null, s: "silver", n: 50}, "!error"], + [{code: null, s: "a", n: -1, cust: {age: 10, tier: "zz", active: true}}, "!error"], + [{b: 0.5, s: "silver", n: 99, cust: []}, {k21: 100, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0.0, k25: "v99-gold", k26: "gold"}, res: {k28: 101}}], + [{code: "", b: 2.5, s: "gold", n: 68, cust: "cust"}, {k21: 1, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0.0, k25: "v68-gold", k26: "gold"}, res: {k28: 70}}], + [{b: 0.1, s: "x", cust: "cust"}, {k21: 1.1, k29: "true", k30: 0.00, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0.0, k25: "v-1-gold", k26: "gold"}, res: {k28: 0.25}}], + [{code: "bronze", b: null, n: 1000000000000000000000, cust: "cust"}, "!error"], + [{code: "gold", b: null, s: "silver", n: 11, cust: {age: 11, tier: "x", active: null}}, "!error"], + [{code: "x", b: 100, s: "gold", n: 50, cust: {age: null, tier: "gold", active: true}}, {k21: 1, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0, k25: "v50-gold", k26: "gold"}, res: {k28: 0}}], + [{code: {t: "x"}, b: -0.1, s: "b", n: 19.99, cust: {age: 1000000000000000000000, tier: "gold", active: false}, extra: 1}, {k21: 40.7801, k29: "true", k30: 0.00, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0.0, k25: "v19.99-gold", k26: "gold"}, res: {k28: 21.99}}], + [{code: "", b: null, s: "zz", n: 10, cust: {age: 7, tier: "", active: false}}, "!error"], + [{code: "a", b: 18, s: null, n: 101}, {k21: 102, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0, k25: "v101-gold", k26: "gold"}, res: {k28: 103}}], + [{code: "gold ", s: "b", n: 101, cust: {age: 0.1, tier: "", active: null}}, "!error"], + [{code: "b", b: 0, s: "gold", n: 100}, {k21: 1, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0, k25: "v100-gold", k26: "gold"}, res: {k28: 102}}], + [{code: "gold ", b: null, s: "b", n: 5, cust: {age: 5, tier: "x"}, extra: [1, 2]}, "!error"], + [{code: "bronze", s: "b", n: 50, cust: {age: -1, tier: "zz", active: false}}, "!error"], + [{code: "zz", b: 2.5, s: "bronze", n: 11, cust: {age: 2, tier: "a", active: false}}, {k21: 12, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0.0, k25: "v11-gold", k26: "gold"}, res: {k28: 13}}], + [{code: "a", b: {v: 1}, n: 2, cust: {age: 50, tier: "gold", active: true}}, "!error"], + [{code: "gold ", b: 100, s: "", n: 19.99, cust: {age: 1000000000000000000000, tier: "zz", active: true}, extra: {deep: {x: 1}}}, {k21: 200.00, k29: "true", k30: 0, k31: false, k32: false, k33: "false", k34: "true", lines: {k24: 0, k25: "v19.99-gold", k26: "gold"}, res: {k28: 0}}], + ], +} + +{ + name: "ga003: 3 nodes, table, table, expr", + graph: { + nodes: [ + {table: "t1", inputs: ["string((2) / 10)", "string(((vip ?? false)) and ((vip ?? false)))"], outputs: ["k35", "k35"], rules: [ + ["null", "startsWith($, 'g')", "2", "0.25"], + ["", "startsWith($, 'g')", "100", "-5"], + ["startsWith($, 'x')", "startsWith($, 'a')", "2", "1"], + ["", "", "2", "0"], + ]}, + {table: "t2", inputs: ["k35", "(k35 ?? -1) + k35"], outputs: ["k37"], passThrough: true, outputPath: "lines", rules: [ + ["$ > 10 and $ < 60", "null", "'mid'"], + ["100", "[-1..0]", "'high'"], + ["100", ">= 10", "''"], + ["not(1)", "5", "'low'"], + ["null", "", "'high'"], + ["$ > 0 and $ < 10", "not(10)", "upper('x')"], + ["", "", "string((endsWith('x', 'x')))"], + ]}, + {expression: "e3", fields: { + k38: "0.5", + k39: "upper('none') + ':' + ((vip ?? false) ? tier : 'A-1') + '' + string(true)", + "g.k40": "max([-(2), 2.25 * -4])", + k41: "(tier ?? '')", + }}, + ], + edges: [ + "input -> t1", + "t1 -> t2", + "input -> e3", + "t2 -> output", + "e3 -> output", + ], + }, + cases: [ + [{cust: [], nums: [-1, 18, 19.99, 0, 21], vip: false, tier: "b"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "b", lines: {k37: "true"}}], + [{cust: {age: 2, tier: "a", active: true}, nums: [-25, 2], vip: false}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "", lines: {k37: "true"}}], + [{cust: {age: 10, tier: "x"}, nums: [10, -0.1], vip: true, tier: null}, "!error"], + [{cust: {age: -0.1, tier: null, active: true}, nums: [], vip: "true"}, "!error"], + [{cust: {age: 0, tier: null, active: true}, nums: [], vip: false}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "", lines: {k37: "true"}}], + [{cust: {age: 5, tier: "gold", active: false}, nums: [2], tier: "x"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "x", lines: {k37: "true"}}], + [{cust: {age: 1000000000000000000000, tier: "", active: true}, nums: [], vip: null, tier: "b"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "b", lines: {k37: "true"}}], + [{cust: [], vip: true}, "!error"], + [{nums: [{x: 1}], vip: true, tier: ""}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:true", k41: "", lines: {k37: "true"}}], + [{cust: {age: 18, tier: "zz", active: false}, nums: [], vip: false, tier: "zz"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "zz", lines: {k37: "true"}}], + [{cust: {age: 7, tier: "a", active: true}, nums: [99], tier: "bronze"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "bronze", lines: {k37: "true"}}], + [{cust: {age: 0.1, tier: "a", active: true}, vip: false, tier: "gold "}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "gold ", lines: {k37: "true"}}], + [{nums: [11, 11], vip: 1}, "!error"], + [{cust: {age: 1000000000000000000000, tier: "gold", active: true}, nums: "1,2", vip: false, tier: "silver"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "silver", lines: {k37: "true"}}], + [{cust: {age: 2.5, tier: "gold", active: true}, nums: null, vip: true, tier: "x"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:xtrue", k41: "x", lines: {k37: "true"}}], + [{cust: {age: 1000, tier: "Gold", active: true}, nums: [2.5], vip: "no", tier: true, extra: "e"}, "!error"], + [{cust: {age: 1000, tier: "gold", active: false}, nums: null, tier: "Gold", extra: [1, 2]}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "Gold", lines: {k37: "true"}}], + [{cust: {age: 2, tier: "b", active: true}, nums: [30], vip: true, extra: {deep: {x: 1}}}, "!error"], + [{nums: [0.5], vip: true, tier: "bronze"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:bronzetrue", k41: "bronze", lines: {k37: "true"}}], + [{cust: 5, nums: null, vip: true, tier: "zz"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:zztrue", k41: "zz", lines: {k37: "true"}}], + [{cust: {age: 19.99, tier: "b", active: true}, nums: "1,2", vip: false, tier: null, extra: [1, 2]}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "", lines: {k37: "true"}}], + [{cust: {tier: "gold ", active: true}, nums: [-0.1, 2.5], vip: 1, tier: ["gold"]}, "!error"], + [{cust: {age: 1000000000000000000000, tier: "b", active: true}, nums: [-1], vip: false, tier: ""}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:A-1true", k41: "", lines: {k37: "true"}}], + [{cust: {age: 11, tier: "gold", active: true}, nums: [], vip: true, tier: "Gold"}, {g: {k40: -2}, k35: 0, k38: 0.5, k39: "NONE:Goldtrue", k41: "Gold", lines: {k37: "true"}}], + ], +} + +{ + name: "ga004: 6 nodes, switch, expr, switch, switch*, table*, table", + graph: { + nodes: [ + {switch: "s1", when: ["startsWith(upper(`v${0}-${(code ?? '')}`), 'g')", ""]}, + {expression: "e2", fields: { + "res.k42": "(((n ?? -1))) - 1", + k43: "'x'", + k44: "a ?? $.k43", + }}, + {switch: "s3", when: ["'none' != 'gold'", "n == null", "(upper((code ?? '?')) in ['gold', 'silver', 'a'])"]}, + {switch: "s4", hit: "collect", when: ["(a ?? a ?? 0) in [0..10]", "(a ?? 1) in [0..10]"]}, + {table: "t5", hit: "collect", inputs: ["(code ?? 'none')", "string(0 - (n ?? -1))", "code"], outputs: ["k45[]", "m.k46"], outputPath: "lines", rules: [ + ["startsWith($, 's')", "$ != 'gold'", "null", "(n ?? 0)", "false"], + ["", "$ != 'gold'", "", "-5", "false"], + ["", "not('x')", "'silver', 'gold'", "(((flag ?? false) ? (code ?? '?') : 'x') in ['gold', 'silver', 'a'] ? (false ? (n ?? 0) : (n ?? -1)) * (a ?? 0) % 2 : (n ?? a ?? 0))", "true"], + ["", "null", "'a', 'gold'", "0.25", "(flag ?? false)"], + ]}, + {table: "t6", inputs: ["string((0.5) / 10)", "a"], outputs: ["k47", "k48"], rules: [ + ["", "[1..51]", "false", "(flag ?? false)"], + ["null", "<= 10", "true", "true"], + ["", "", "false", "true"], + ]}, + ], + edges: [ + "input -> s1", + "input -> e2", + "s1:0 -> s3", + "s3:1 -> s4", + "s3:2 -> t5", + "s3:2 -> t6", + "s4:0 -> t6", + "e2 -> output", + "s3:0 -> output", + "s4:1 -> output", + "t5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{flag: false, code: "gold ", n: 11, vip: null, a: 2}, {k43: "x", k44: 2, res: {k42: 10}}], + [{flag: false, code: "gold ", n: -0.1, vip: true}, {k43: "x", k44: "x", res: {k42: -1.1}}], + [{flag: true, code: "gold", n: -25, vip: true, a: -25}, {k43: "x", k44: -25, res: {k42: -26}}], + [{flag: true, code: "zz", vip: false, a: 0.1}, {k43: "x", k44: 0.1, res: {k42: -2}}], + [{flag: false, code: "", n: 99, vip: true, a: 11, extra: {deep: {x: 1}}}, {k43: "x", k44: 11, res: {k42: 98}}], + [{flag: true, code: "gold", n: -0.1, a: 100}, {k43: "x", k44: 100, res: {k42: -1.1}}], + [{flag: false, code: "x", n: -9, vip: true}, {k43: "x", k44: "x", res: {k42: -10}}], + [{flag: false, code: "zz", n: 0.5, vip: null, a: 1000}, {k43: "x", k44: 1000, res: {k42: -0.5}}], + [{flag: false, code: "gold ", n: 26, vip: false, a: null}, {k43: "x", k44: "x", res: {k42: 25}}], + [{flag: false, code: "gold", n: 18, a: null, extra: "e"}, {k43: "x", k44: "x", res: {k42: 17}}], + [{flag: false, code: "zz", a: 0.1}, {k43: "x", k44: 0.1, res: {k42: -2}}], + [{flag: null, code: null, n: 18, vip: false, a: null}, {k43: "x", k44: "x", res: {k42: 17}}], + [{flag: true, code: "gold ", n: 99, vip: false, a: 1000000000000000000000}, {k43: "x", k44: 1000000000000000000000, res: {k42: 98}}], + [{flag: true, code: "bronze", n: 11, vip: false, a: 22}, {k43: "x", k44: 22, res: {k42: 10}}], + ], +} + +{ + name: "ga005: 4 nodes, expr, table, table, table*", + graph: { + nodes: [ + {expression: "e1", outputPath: "o.p", fields: { + k49: "string(vip) == 'x'", + }}, + {table: "t2", inputs: ["100", "(2.25) / 0.5 + -4", "'gold'"], outputs: ["k50"], passThrough: true, rules: [ + ["< 10", ">= 100", "startsWith($, 'x')", "'high'"], + ["null", "", "", "''"], + ["[5..15]", "0", "", "'low'"], + ]}, + {table: "t3", inputs: ["n", "((vip ?? false) ? 'gold' + ' ' + 'A-1' : 'x' + '' + 'x')", "price"], outputs: ["k51", "k52"], rules: [ + ["50, 100", "null", "<= 55", "''", "false"], + ["", "'x', 'bronze'", "< -1", "'A-1'", "true"], + [">= 21", "''", "[-1..9]", "''", "true"], + ["> 5", "$ != 'gold'", "5", "'high'", "true"], + ["", "", "", "string(not ('none' in ['gold', 'silver', 'a']))", "false"], + ]}, + {table: "t4", hit: "collect", inputs: ["string(false)", "`v${0.5}-${'gold'}`", "1 + len('A-1')"], outputs: ["k53"], outputPath: "out", rules: [ + ["startsWith($, 's')", "startsWith($, 's')", "not(21)", "true"], + ["$ != 'gold'", "null", "> -1", "k52"], + ["$ != ''", "$ != 'x'", "!= 21", "true"], + ["startsWith($, '')", "'a'", "[50..60)", "true"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "input -> t3", + "t3 -> t4", + "t2 -> output", + "t4 -> output", + ], + }, + cases: [ + [{a: 0, price: 100, vip: true, nums: [50], score: 5, extra: [1, 2]}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 111, n: 19.99, price: 1000000000000000000000, vip: false, nums: [100, 50, 101], score: 18}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{n: 99, price: 2.5, vip: false, nums: [50, 0.5], score: 1}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: null, n: 19.99, price: 19.99, vip: false, nums: null, score: null}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 7, n: 0.1, price: 1000, vip: 1, score: null}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 0.1, n: null, price: null, vip: false, nums: [21], score: 100}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{n: 11, price: 0.1, vip: false, nums: [-1, 7, 2]}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 21, n: {v: 1}, price: 99, vip: true, nums: [11], score: 11, extra: "e"}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{n: 0.5, price: 21, vip: false, nums: [], score: 2.5}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: "5", n: 10, price: true, vip: true, nums: [50, 100, 21, -1, 0.1], score: 2}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 1, n: -25, price: 2, vip: false, nums: [], score: 87}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 0.1, n: "5", price: 79, vip: false, score: 100}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 3, n: 2, price: 5, vip: false, nums: [0.1, 2], score: 1}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 100, n: -1, price: 32, vip: false, nums: [0, 1, 0.1], score: 1000000000000000000000}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 99, n: 100, price: -1, nums: 7, score: 21}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 0, n: 7, price: null, vip: true, nums: [18], score: 2.5}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: -1, n: 21, price: 1, vip: 1, score: 1000}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 50, n: 3, price: 1, vip: true, nums: [19.99, 101, 18, 99, 99], score: -0.1}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 19.99, n: -0.1, price: 2.5, vip: false, nums: [3, 1000], score: 2.5}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 1, n: 0.5, price: 3, vip: true, nums: []}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 21, n: 18, vip: null, score: 0.1, extra: {deep: {x: 1}}}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 50, n: 1000000000000000000000, price: 5, vip: true, nums: [100], score: -25}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 2.5, n: 0.5, price: 0, vip: false, nums: [101, 0], score: null}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 2.5, n: 1000, price: 50, vip: false, nums: [10, 99, 0.5, 99, 11], score: 5}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: [1], n: 2, price: [1], vip: false, nums: [0.1, 99, 10], score: 1}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: 1000000000000000000000, n: -25, price: 2, vip: false, nums: [], extra: "e"}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{n: 7, price: [1], vip: false, nums: [0.1, 50, 1000, 1000000000000000000000, 10], score: 1000000000000000000000, extra: {deep: {x: 1}}}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{n: null, price: 2, vip: true, nums: [0.1, 101, 7, 100, 100], score: -25}, {o: {p: {k49: false}}, out: [{k53: true}]}], + [{a: -0.1, n: 0.5, price: 21, vip: true, nums: [0.5, 2, 18], score: 3}, {o: {p: {k49: false}}, out: [{k53: true}]}], + ], +} + +{ + name: "ga006: 4 nodes, switch*, expr, expr, table*", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["(code ?? 'none') == 'x'", ""]}, + {expression: "e2", passThrough: true, fields: { + k54: "false", + k55: "(sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0))) == 100 + b ? 'none' : 'gold')", + k56: "`${(n ?? 0)}-${''}`", + k57: "score ?? tier", + }}, + {expression: "e3", passThrough: true, fields: { + k58: "(score ?? 0) + score + (b ?? 0) * 2 + 3", + k59: "(((score ?? -1) > 0) or ((score ?? -1) in [1..100])) and (abs(2) <= (b ?? 0))", + k60: "tier ?? score", + }}, + {table: "t4", hit: "collect", inputs: ["(b ?? 1)"], outputs: ["m.k61", "k62"], outputPath: "o.p", rules: [ + ["< 1", "false", "(k56 ?? '?')"], + ["null", "true", "'gold'"], + ["", "(b ?? -1) < 0.5", "''"], + ]}, + ], + edges: [ + "input -> s1", + "s1:1 -> e2", + "s1:1 -> e3", + "e2 -> t4", + "s1:0 -> output", + "e3 -> output", + "t4 -> output", + ], + }, + cases: [ + [{nums: [-25, 99, 2, 0, 18], code: "x", n: 7, score: 18, items: [{price: 19.99, qty: 50}, {qty: 1000000000000000000000, tag: "a"}], extra: 1}, "!error"], + [{nums: [0.5], code: "b", tier: "", n: 1000, score: -0.1, items: [], b: 5}, {b: 5, code: "b", items: [], k58: 12.8, k59: false, k60: "", n: 1000, nums: [0.5], o: {p: [{k62: "", m: {k61: false}}]}, score: -0.1, tier: ""}], + [{nums: null, tier: "zz", n: 3, score: 11, items: [{price: 0.1, qty: 100, tag: ""}, {price: 54, qty: 0.5, tag: "silver"}, {price: 0.5, qty: 2, tag: ""}, {qty: -0.1, tag: "zz"}], b: 10}, {b: 10, items: [{price: 0.1, qty: 100, tag: ""}, {price: 54, qty: 0.5, tag: "silver"}, {price: 0.5, qty: 2, tag: ""}, {qty: -0.1, tag: "zz"}], k58: 45, k59: true, k60: "zz", n: 3, o: {p: [{k62: "", m: {k61: false}}]}, score: 11, tier: "zz"}], + [{nums: [1, 99], code: "", tier: "bronze", n: 0, score: 5, items: [{qty: -25, tag: null}, {price: -25, qty: 101, tag: ""}, {price: 1000000000000000000000, qty: 2.5, tag: "bronze"}], b: 0.5}, {b: 0.5, code: "", items: [{qty: -25, tag: null}, {price: -25, qty: 101, tag: ""}, {price: 1000000000000000000000, qty: 2.5, tag: "bronze"}], k58: 14.0, k59: false, k60: "bronze", n: 0, nums: [1, 99], o: {p: [{k62: "0-", m: {k61: false}}, {k62: "", m: {k61: false}}]}, score: 5, tier: "bronze"}], + [{nums: [21, 2], code: "gold ", tier: "", n: 19.99, score: 99, items: null, b: 1, extra: {deep: {x: 1}}}, {b: 1, code: "gold ", extra: {deep: {x: 1}}, k58: 203, k59: false, k60: "", n: 19.99, nums: [21, 2], o: {p: [{k62: "", m: {k61: false}}]}, score: 99, tier: ""}], + [{nums: [0.1, 1000000000000000000000], code: "a", tier: "bronze", items: [{price: null, qty: 99, tag: "zz"}], b: null}, "!error"], + [{nums: [11], tier: "zz", n: -1, score: 1, items: [{price: 19.99, qty: 10, tag: "bronze"}, {price: null, qty: 18}], b: 19.99}, {b: 19.99, items: [{price: 19.99, qty: 10, tag: "bronze"}, {price: null, qty: 18}], k58: 44.98, k59: true, k60: "zz", n: -1, nums: [11], o: {p: [{k62: "", m: {k61: false}}]}, score: 1, tier: "zz"}], + [{nums: [21, 101, 2, 1000000000000000000000, 2], code: "a", tier: "zz", n: 50, score: 0, items: [{price: 19.99, qty: null, tag: "gold"}, {price: 103, qty: 10, tag: "Gold"}, {qty: null, tag: "Gold"}], b: 18}, {b: 18, code: "a", items: [{price: 19.99, qty: null, tag: "gold"}, {price: 103, qty: 10, tag: "Gold"}, {qty: null, tag: "Gold"}], k58: 39, k59: false, k60: "zz", n: 50, nums: [21, 101, 2, 1000000000000000000000, 2], o: {p: [{k62: "", m: {k61: false}}]}, score: 0, tier: "zz"}], + [{nums: [21, 100, 2.5, 101, 2.5], code: "bronze", tier: "b", n: 2.5, score: 1000000000000000000000, items: [{price: 18, qty: 11, tag: "b"}, {price: 1000, qty: 101, tag: ""}, {qty: 0, tag: ""}], b: -13}, {b: -13, code: "bronze", items: [{price: 18, qty: 11, tag: "b"}, {price: 1000, qty: 101, tag: ""}, {qty: 0, tag: ""}], k58: 1999999999999999999977, k59: false, k60: "b", n: 2.5, nums: [21, 100, 2.5, 101, 2.5], o: {p: [{k62: "2.5-", m: {k61: false}}, {k62: "", m: {k61: true}}]}, score: 1000000000000000000000, tier: "b"}], + [{nums: [1000000000000000000000, 50, 1000], code: "silver", tier: "x", n: 18, score: null, items: [{price: 1000, qty: 100, tag: "a"}], b: 18}, "!error"], + [{nums: [0, 50, -0.1, 2.5, 3], code: "gold", tier: "gold ", score: 0.5, items: [{price: 99, qty: 1, tag: "bronze"}, {price: null, qty: 1000, tag: ""}, {price: 19.99, qty: 1000, tag: "zz"}], b: 3}, {b: 3, code: "gold", items: [{price: 99, qty: 1, tag: "bronze"}, {price: null, qty: 1000, tag: ""}, {price: 19.99, qty: 1000, tag: "zz"}], k58: 10.0, k59: true, k60: "gold ", nums: [0, 50, -0.1, 2.5, 3], o: {p: [{k62: "", m: {k61: false}}]}, score: 0.5, tier: "gold "}], + [{nums: [], code: "Gold", n: 0.5, score: 100, items: [], b: 100, extra: 1}, {b: 100, code: "Gold", extra: 1, items: [], k58: 403, k59: true, k60: 100, n: 0.5, nums: [], o: {p: [{k62: "", m: {k61: false}}]}, score: 100}], + [{nums: [103, 100, 1000000000000000000000], code: "bronze", tier: "bronze", n: -1, score: null, items: [{price: 1000000000000000000000, qty: 100, tag: ""}], b: 2.5}, "!error"], + [{code: "a", tier: "bronze", n: 11, score: 10, items: null, b: 1000000000000000000000, extra: 1}, {b: 1000000000000000000000, code: "a", extra: 1, k58: 2000000000000000000023, k59: true, k60: "bronze", n: 11, o: {p: [{k62: "", m: {k61: false}}]}, score: 10, tier: "bronze"}], + [{nums: [7, 41], code: "b", tier: "gold", n: 10, score: 3, b: -1}, {b: -1, code: "b", k58: 7, k59: false, k60: "gold", n: 10, nums: [7, 41], o: {p: [{k62: "10-", m: {k61: false}}, {k62: "", m: {k61: true}}]}, score: 3, tier: "gold"}], + [{nums: [100, 1000000000000000000000, 10, 1000, 18], code: "silver", tier: "gold ", n: 2.5, score: 18, items: [], b: 0}, {b: 0, code: "silver", items: [], k58: 39, k59: false, k60: "gold ", n: 2.5, nums: [100, 1000000000000000000000, 10, 1000, 18], o: {p: [{k62: "2.5-", m: {k61: false}}, {k62: "", m: {k61: true}}]}, score: 18, tier: "gold "}], + [{nums: [], code: "", tier: "silver", n: -25, score: 0.5, items: [{qty: 18, tag: "bronze"}, {price: 10, tag: null}], b: null}, "!error"], + [{nums: [0, 0.5, 2], code: "b", tier: "Gold", n: null, score: 7, items: [{price: 0.1, qty: 99, tag: "Gold"}, {price: 11, qty: 99}, {price: 11, tag: "gold "}]}, "!error"], + [{nums: [0, 2], tier: "gold ", n: 1000, items: [{price: -25, qty: 0, tag: "b"}], b: 11}, "!error"], + [{nums: [46, 0, 2.5, 1000000000000000000000, 0.1], code: "x", tier: "b", n: 99, items: [{price: 3, qty: -0.1, tag: "b"}, {price: 18, qty: -0.1, tag: "gold"}, {price: -0.1, qty: 46, tag: "gold "}, {price: null, qty: 99, tag: ""}], b: 10, extra: [1, 2]}, "!error"], + [{nums: [18, 3, 2, 2.5, 115], code: "gold", tier: "bronze", n: null, score: 7, items: [{price: null, qty: 5, tag: "bronze"}, {price: 0.5, qty: 1000, tag: "x"}], b: 1000000000000000000000, extra: {deep: {x: 1}}}, {b: 1000000000000000000000, code: "gold", extra: {deep: {x: 1}}, items: [{price: null, qty: 5, tag: "bronze"}, {price: 0.5, qty: 1000, tag: "x"}], k58: 2000000000000000000017, k59: true, k60: "bronze", nums: [18, 3, 2, 2.5, 115], o: {p: [{k62: "", m: {k61: false}}]}, score: 7, tier: "bronze"}], + [{nums: [-1, 112, 0.5], code: "a", tier: "zz", n: null, score: 3, items: [], b: 2}, {b: 2, code: "a", items: [], k58: 13, k59: true, k60: "zz", nums: [-1, 112, 0.5], o: {p: [{k62: "", m: {k61: false}}]}, score: 3, tier: "zz"}], + [{nums: [36, 0.1, 11, 2.5, -1], tier: "zz", n: 3, score: null, items: [{price: 1000, qty: null, tag: ""}, {price: -1, qty: 10, tag: "gold"}, {price: -1, qty: 10, tag: "bronze"}], b: 11}, "!error"], + [{nums: [21, 0.1, 7], code: "a", tier: "", score: 0, items: [{price: 18, qty: -1, tag: "gold"}, {price: 90, qty: 1000000000000000000000}], b: 19.99}, {b: 19.99, code: "a", items: [{price: 18, qty: -1, tag: "gold"}, {price: 90, qty: 1000000000000000000000}], k58: 42.98, k59: false, k60: "", nums: [21, 0.1, 7], o: {p: [{k62: "", m: {k61: false}}]}, score: 0, tier: ""}], + [{nums: [], code: "gold ", tier: "b", n: 100, score: 99, items: [{price: 0.1, qty: 1000000000000000000000, tag: "bronze"}, {price: 7, qty: 1, tag: null}, {price: 3, qty: 100, tag: "gold "}, {price: 1, qty: 5, tag: "Gold"}], b: 2}, {b: 2, code: "gold ", items: [{price: 0.1, qty: 1000000000000000000000, tag: "bronze"}, {price: 7, qty: 1, tag: null}, {price: 3, qty: 100, tag: "gold "}, {price: 1, qty: 5, tag: "Gold"}], k58: 205, k59: true, k60: "b", n: 100, nums: [], o: {p: [{k62: "", m: {k61: false}}]}, score: 99, tier: "b"}], + ], +} + +{ + name: "ga007: 8 nodes, expr, switch*, expr, switch, switch, expr, expr, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "cust", fields: { + k63: "string(min([(age ?? 1), age])) != 'x'", + k64: "age ?? tier", + }}, + {switch: "s2", hit: "collect", when: ["100 != 10", "(endsWith(((k63 ?? false) ? '' : 'A-1'), 'x')) and (-(0) < 2.25)", ""]}, + {expression: "e3", fields: { + k65: "vip ?? cust.active", + k66: "vip ?? vip", + "m.k67": "'gold'", + }}, + {switch: "s4", when: ["a == null", "(flag ?? false)"]}, + {switch: "s5", when: ["(k63 ?? false)", "2 - 2.25 * 0 < (100) * (3)", ""]}, + {expression: "e6", passThrough: true, fields: { + k68: "k63 ?? k63", + k69: "k63 ?? k63", + k70: "(len('none')) / 2", + "g.k71": "k63 ?? k63", + }}, + {expression: "e7", passThrough: true, fields: { + k72: "'x'", + k73: "100", + k74: "2.25 - (2 - 10)", + }}, + {expression: "e8", fields: { + k75: "0.5 + 2 * (true ? 1 : 2.25) * (-4 + 0)", + }}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "input -> e3", + "input -> s4", + "s2:2 -> s5", + "s5:1 -> e6", + "s5:0 -> e7", + "e1 -> e8", + "e3 -> e8", + "s2:0 -> output", + "s2:1 -> output", + "s4:1 -> output", + "s5:2 -> output", + "e6 -> output", + "e7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{vip: true, flag: false, cust: {age: 3, tier: "bronze", active: true}}, {k63: true, k64: 3, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: false, flag: true, cust: {age: 1000000000000000000000, tier: "gold", active: false}}, {k63: true, k64: 1000000000000000000000, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: true, cust: {age: 0.5, tier: "x", active: true}}, {k63: true, k64: 0.5, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: false, flag: true, cust: {age: 50, tier: "bronze", active: true}}, {k63: true, k64: 50, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: true, flag: true, extra: "e"}, "!error"], + [{vip: false, flag: false, cust: {age: 7, tier: "a", active: true}}, {k63: true, k64: 7, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: false, flag: false, cust: {tier: "silver", active: false}}, "!error"], + [{vip: false, flag: true, cust: null}, "!error"], + [{vip: true, flag: true, cust: {age: 100, tier: "zz", active: true}, extra: 1}, {k63: true, k64: 100, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: true, flag: false, cust: {age: 1000000000000000000000, tier: true}}, {k63: true, k64: 1000000000000000000000, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{flag: 0, cust: {age: 19.99, tier: "silver", active: true}}, {k63: true, k64: 19.99, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{flag: true, cust: {age: 1000000000000000000000, tier: "gold ", active: true}}, {k63: true, k64: 1000000000000000000000, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: true, cust: {age: -25, tier: "", active: null}}, {k63: true, k64: -25, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: false, flag: false, cust: {age: 2.5, tier: "zz", active: true}}, {k63: true, k64: 2.5, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: false, flag: true, cust: {age: 21, tier: "b", active: false}}, {k63: true, k64: 21, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: true, flag: true, cust: {age: 2.5, tier: "x", active: false}}, {k63: true, k64: 2.5, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: true, flag: true, cust: {age: 0.5, tier: "", active: true}}, {k63: true, k64: 0.5, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + [{vip: false, flag: true, cust: {age: 2, tier: "gold ", active: 1}}, {k63: true, k64: 2, k72: "x", k73: 100, k74: 10.25, k75: -7.5}], + ], +} + +{ + name: "ga008: 5 nodes, table*, expr, expr, switch, table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["b"], outputs: ["k76[]", "k76"], passThrough: true, outputPath: "o.p", rules: [ + ["< 18", "false", "'low'"], + ["[1..2)", "false", "''"], + ]}, + {expression: "e2", fields: { + k78: "2", + k79: "contains(tier + ' ' + string(true), 'g')", + }}, + {expression: "e3", passThrough: true, fields: { + k81: "min([(a ?? 1), len((tier ?? '?'))])", + }}, + {switch: "s4", when: ["-((b ?? 1)) + max(nums ?? [0]) > 0", "(a ?? 0) * ceil((a ?? 1)) <= score", ""]}, + {table: "t5", inputs: ["score"], outputs: ["k78", "g.k83"], rules: [ + ["$ > 50 and $ < 60", "false", "'low'"], + ["> 100", "true", "(tier ?? '')"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "input -> e2", + "t1 -> e3", + "t1 -> s4", + "s4:0 -> t5", + "s4:1 -> t5", + "e2 -> output", + "e3 -> output", + "s4:2 -> output", + "t5 -> output", + ], + }, + cases: [ + [{a: 1, tier: "Gold", nums: [1, 5, 2.5, -1, 21], score: 21, price: null, b: 100, n: 100}, {a: 1, b: 100, k78: 2, k79: false, k81: 1, n: 100, nums: [1, 5, 2.5, -1, 21], o: {p: []}, score: 21, tier: "Gold"}], + [{a: -25, tier: "bronze", nums: [], score: -25, price: 19.99, b: 2.5, n: 2.5}, {a: -25, b: 2.5, k78: 2, k79: false, k81: -25, n: 2.5, nums: [], o: {p: [{k76: "low"}]}, price: 19.99, score: -25, tier: "bronze"}], + [{tier: "x", nums: [16, -25], score: -0.1, price: 21, b: 1000, n: 5}, {b: 1000, k78: 2, k79: false, k81: 1, n: 5, nums: [16, -25], o: {p: []}, price: 21, score: -0.1, tier: "x"}], + [{a: 50, tier: "b", score: 0.1, price: 19.99, b: 0, n: 0}, {a: 50, b: 0, k78: 2, k79: false, k81: 1, n: 0, o: {p: [{k76: "low"}]}, price: 19.99, score: 0.1, tier: "b"}], + [{a: 1000, tier: "b", nums: [21, 1000000000000000000000, 2], score: -25, price: 12, b: null, n: 0.5}, {a: 1000, k78: 2, k79: false, k81: 1, n: 0.5, nums: [21, 1000000000000000000000, 2], o: {p: []}, price: 12, score: -25, tier: "b"}], + [{a: 99, tier: "x", nums: [-25, 100, 2.5], score: null, price: -1, b: 3, n: 11, extra: {deep: {x: 1}}}, {a: 99, b: 3, extra: {deep: {x: 1}}, k78: 2, k79: false, k81: 1, n: 11, nums: [-25, 100, 2.5], o: {p: [{k76: "low"}]}, price: -1, tier: "x"}], + [{a: 18, tier: "", nums: [100, 50, 50], score: 11, price: 0, b: 18}, {a: 18, b: 18, k78: 2, k79: false, k81: 0, nums: [100, 50, 50], o: {p: []}, price: 0, score: 11, tier: ""}], + [{a: 100, tier: "silver", nums: [], score: 11, price: null, b: 7, n: 0, extra: 1}, {a: 100, b: 7, extra: 1, k78: 2, k79: false, k81: 6, n: 0, nums: [], o: {p: [{k76: "low"}]}, score: 11, tier: "silver"}], + [{a: null, tier: "b", nums: [], score: 0.5, b: 100, n: 1}, {b: 100, k78: 2, k79: false, k81: 1, n: 1, nums: [], o: {p: []}, score: 0.5, tier: "b"}], + [{a: 0.5, tier: "b", nums: [101, 7, 7, -1, 1000000000000000000000], score: 99, price: 0.5, b: 100, n: 11}, {a: 0.5, b: 100, k78: 2, k79: false, k81: 0.5, n: 11, nums: [101, 7, 7, -1, 1000000000000000000000], o: {p: []}, price: 0.5, score: 99, tier: "b"}], + [{a: 101, nums: [2, 18], price: 1, b: 1000, n: 5, extra: {deep: {x: 1}}}, "!error"], + [{a: null, tier: "a", nums: [2.5], score: null, price: 21, b: 1000, n: 1}, {b: 1000, k78: 2, k79: false, k81: 1, n: 1, nums: [2.5], o: {p: []}, price: 21, tier: "a"}], + [{a: 10, nums: [100, 50, -25], score: null, price: 11, b: 0.5}, "!error"], + [{a: 7, tier: "x", nums: [7], score: null, price: 10, n: 100}, {a: 7, k78: 2, k79: false, k81: 1, n: 100, nums: [7], o: {p: []}, price: 10, tier: "x"}], + [{tier: "a", nums: [3, -0.1], price: 0, b: 0.1, n: -0.1}, {b: 0.1, k78: 2, k79: false, k81: 1, n: -0.1, nums: [3, -0.1], o: {p: [{k76: "low"}]}, price: 0, tier: "a"}], + [{tier: "a", nums: [5, 0, -10], score: 2.5, price: 3, b: 19.99, n: 1000000000000000000000}, {b: 19.99, k78: 2, k79: false, k81: 1, n: 1000000000000000000000, nums: [5, 0, -10], o: {p: []}, price: 3, score: 2.5, tier: "a"}], + [{a: 3, tier: "x", nums: [3, 98, 21], score: 11, price: 0.1, b: -25}, {a: 3, b: -25, k78: 2, k79: false, k81: 1, nums: [3, 98, 21], o: {p: [{k76: "low"}]}, price: 0.1, score: 11, tier: "x"}], + [{a: 1000000000000000000000, nums: [101, -25, 7], score: 19.99, price: 68, b: 10, n: 1000000000000000000000}, "!error"], + [{tier: "silver", nums: null, score: 1000000000000000000000, price: 0.1, b: -1}, {b: -1, g: {k83: "silver"}, k78: 2, k79: false, k81: 1, o: {p: [{k76: "low"}]}, price: 0.1, score: 1000000000000000000000, tier: "silver"}], + [{a: 0.1, tier: "silver", nums: [], score: 18, price: 18, b: 2.5, n: -1}, {a: 0.1, b: 2.5, k78: 2, k79: false, k81: 0.1, n: -1, nums: [], o: {p: [{k76: "low"}]}, price: 18, score: 18, tier: "silver"}], + ], +} + +{ + name: "ga009: 8 nodes, expr, switch, switch*, expr, expr, expr, switch, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k84: "s == null", + }}, + {switch: "s2", when: ["string((flag ?? false)) + '-' + `${0}-${(code ?? 'none')}` in ['gold', 'silver', 'a']", "'A-1' != ''", "(flag ?? false)", ""]}, + {switch: "s3", hit: "collect", when: ["b != null", ""]}, + {expression: "e4", fields: { + k85: "(100) / 3", + k86: "(s ?? '?')", + }}, + {expression: "e5", outputPath: "lines", fields: { + k87: "(2 + (price ?? -1) != min([10, (a ?? 0)]) ? ((price ?? -1) in [1..100] ? (s ?? 'none') : (code ?? '?')) : (s ?? '?') + ' ' + s + '-' + (code ?? '?'))", + k88: "$.k87 ?? s", + k89: "max([-((b ?? 0) % 2), 1 * (a ?? -1) - price])", + "g.k90": "a ?? price", + }}, + {expression: "e6", outputPath: "o.p", fields: { + "g.k90": "flag", + k92: "trim((s ?? '?')) + '' + string((a ?? -1) < 2.25)", + }}, + {switch: "s7", when: ["(lines.k89 ?? 0) % 2 * -((lines.k89 ?? -1)) == ((false) or (true) ? (true ? (lines.k89 ?? -1) : -4) : ((lines.k89 ?? -1)))", "(lines.k89 == null) and ((lines.k89 ?? lines.g.k90 ?? 0) in [1..100])", "lines.k87 == null", ""]}, + {table: "t8", inputs: ["lines.k89"], outputs: ["k93", "k94"], rules: [ + ["[-1..9)", "-5", "true"], + ["!= 1", "(lines.k89 ?? -1)", "false"], + ["<= 0", "10", "true"], + ["", "2", "true"], + ]}, + ], + edges: [ + "input -> e1", + "input -> s2", + "s2:1 -> s3", + "s2:2 -> e4", + "s3:1 -> e5", + "s3:1 -> e6", + "e5 -> s7", + "s7:1 -> t8", + "e1 -> output", + "s2:0 -> output", + "s2:3 -> output", + "s3:0 -> output", + "e4 -> output", + "e6 -> output", + "s7:0 -> output", + "s7:2 -> output", + "t8 -> output", + ], + }, + cases: [ + [{b: -0.1, s: "gold", code: "a", flag: null, a: 5, price: 3}, {a: 5, b: -0.1, code: "a", k84: false, o: {p: {g: {k90: null}, k92: "goldfalse"}}, price: 3, s: "gold"}], + [{b: 100, s: null, code: "a", flag: false, a: -1, price: 99, extra: 1}, {a: -1, b: 100, code: "a", extra: 1, flag: false, k84: true, lines: {g: {k90: -1}, k87: "none", k88: "none", k89: -0}, o: {p: {g: {k90: false}, k92: "?true"}}, price: 99}], + [{b: 101, s: "Gold", code: "a", flag: false, a: 100}, "!error"], + [{b: 0, s: "a", code: "gold", flag: false, a: 1000, price: 99}, {a: 1000, b: 0, code: "gold", flag: false, k84: false, o: {p: {g: {k90: false}, k92: "afalse"}}, price: 99, s: "a"}], + [{b: 2, s: "zz", code: "silver", flag: true, a: null, price: 1}, {b: 2, code: "silver", flag: true, k84: false, lines: {g: {k90: 1}, k87: "zz", k88: "zz", k89: -0}, o: {p: {g: {k90: true}, k92: "zztrue"}}, price: 1, s: "zz"}], + [{b: 1000000000000000000000, s: "Gold", code: "Gold", a: 100, price: 101}, {a: 100, b: 1000000000000000000000, code: "Gold", k84: false, lines: {g: {k90: 100}, k87: "Gold", k88: "Gold", k89: -0}, o: {p: {g: {k90: null}, k92: "Goldfalse"}}, price: 101, s: "Gold"}], + [{b: 1000, s: "silver", code: "gold", flag: false, a: 1, price: 50}, {a: 1, b: 1000, code: "gold", flag: false, k84: false, lines: {g: {k90: 1}, k87: "silver", k88: "silver", k89: -0}, o: {p: {g: {k90: false}, k92: "silvertrue"}}, price: 50, s: "silver"}], + [{b: 1000000000000000000000, code: "bronze", flag: true, a: 101, price: -25, extra: "e"}, {a: 101, b: 1000000000000000000000, code: "bronze", extra: "e", flag: true, k84: true, o: {p: {g: {k90: true}, k92: "?false"}}, price: -25}], + [{b: 0.5, s: "gold", code: "x", flag: true, a: 21}, "!error"], + [{b: 21, s: "gold ", code: "silver", flag: false, a: -0.1, price: 3}, {a: -0.1, b: 21, code: "silver", flag: false, k84: false, lines: {g: {k90: -0.1}, k87: "gold ", k88: "gold ", k89: -1}, o: {p: {g: {k90: false}, k92: "goldtrue"}}, price: 3, s: "gold "}], + [{b: 1, s: "a", code: null, flag: null, a: 1, price: 100}, {a: 1, b: 1, k84: false, lines: {g: {k90: 1}, k87: "a", k88: "a", k89: -1}, o: {p: {g: {k90: null}, k92: "atrue"}}, price: 100, s: "a"}], + [{s: null, code: "silver", flag: true, a: 11, price: 1}, {a: 11, code: "silver", flag: true, k84: true, o: {p: {g: {k90: true}, k92: "?false"}}, price: 1}], + [{b: 101, s: "zz", code: "Gold", a: 3, price: 0.1}, {a: 3, b: 101, code: "Gold", k84: false, o: {p: {g: {k90: null}, k92: "zzfalse"}}, price: 0.1, s: "zz"}], + [{b: null, s: "a", code: "zz", flag: true, price: 5}, {code: "zz", flag: true, k84: false, lines: {g: {k90: 5}, k87: "a", k88: "a", k89: -0}, o: {p: {g: {k90: true}, k92: "atrue"}}, price: 5, s: "a"}], + [{b: 2, code: "gold ", flag: false, a: 50, price: 10}, {a: 50, b: 2, code: "gold ", flag: false, k84: true, o: {p: {g: {k90: false}, k92: "?false"}}, price: 10}], + [{b: 18, s: "gold ", code: "zz", flag: true, a: 1, price: 99}, {a: 1, b: 18, code: "zz", flag: true, k84: false, lines: {g: {k90: 1}, k87: "gold ", k88: "gold ", k89: -0}, o: {p: {g: {k90: true}, k92: "goldtrue"}}, price: 99, s: "gold "}], + [{b: 51, s: "", flag: true, price: 3}, {b: 51, flag: true, k84: false, lines: {g: {k90: 3}, k87: "", k88: "", k89: -1}, o: {p: {g: {k90: true}, k92: "true"}}, price: 3, s: ""}], + [{b: 0, s: "x", code: "bronze", flag: true, a: 1000, price: 0.1}, {a: 1000, b: 0, code: "bronze", flag: true, k84: false, o: {p: {g: {k90: true}, k92: "xfalse"}}, price: 0.1, s: "x"}], + [{b: 101, s: null, flag: true, a: 21, price: 50}, {a: 21, b: 101, flag: true, k84: true, lines: {g: {k90: 21}, k87: "none", k88: "none", k89: -1}, o: {p: {g: {k90: true}, k92: "?false"}}, price: 50}], + [{b: 50, s: "gold", code: "a", flag: true, a: 101, price: 1000000000000000000000}, {a: 101, b: 50, code: "a", flag: true, k84: false, lines: {g: {k90: 101}, k87: "a", k88: "a", k89: -0}, o: {p: {g: {k90: true}, k92: "goldfalse"}}, price: 1000000000000000000000, s: "gold"}], + [{b: -1, s: "Gold", code: "b", flag: false, price: 18}, {b: -1, code: "b", flag: false, k84: false, o: {p: {g: {k90: false}, k92: "Goldtrue"}}, price: 18, s: "Gold"}], + [{b: 1000000000000000000000, s: "", code: null, flag: false, a: 2.5}, "!error"], + [{b: 21, s: "gold", flag: true, a: 19.99, price: 1}, {a: 19.99, b: 21, flag: true, k84: false, o: {p: {g: {k90: true}, k92: "goldfalse"}}, price: 1, s: "gold"}], + [{b: -25, s: "bronze", code: "a", flag: true, a: 18, price: null}, "!error"], + [{b: 99, s: "x", code: "a", flag: true, a: 100, price: 0.5, extra: {deep: {x: 1}}}, {a: 100, b: 99, code: "a", extra: {deep: {x: 1}}, flag: true, k84: false, o: {p: {g: {k90: true}, k92: "xfalse"}}, price: 0.5, s: "x"}], + [{b: 0, code: null, flag: false, a: null, price: -25}, {b: 0, flag: false, k84: true, o: {p: {g: {k90: false}, k92: "?true"}}, price: -25}], + [{b: 11, s: "b", code: "x", flag: true, a: 21, price: 3}, {a: 21, b: 11, code: "x", flag: true, k84: false, o: {p: {g: {k90: true}, k92: "bfalse"}}, price: 3, s: "b"}], + ], +} + +{ + name: "ga010: 3 nodes, switch, loop expr, expr", + graph: { + nodes: [ + {switch: "s1", when: ["(((true)))", "false"]}, + {expression: "e2", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k95: "tag ?? qty", + k96: "price", + k97: "(qty ?? 1)", + k98: "tag ?? price", + }}, + {expression: "e3", fields: { + "res.k99": "(not (((vip ?? false))))", + k100: "(a ?? a ?? 0) - -((a ?? 0))", + k101: "a ?? code", + }}, + ], + edges: [ + "input -> s1", + "input -> e2", + "s1:1 -> e3", + "s1:0 -> output", + "e2 -> output", + "e3 -> output", + ], + }, + cases: [ + [{vip: false, code: "zz", items: [{price: 2.5, qty: 50, tag: "zz"}], a: 1000000000000000000000, nums: []}, {a: 1000000000000000000000, code: "zz", items: [{price: 2.5, qty: 50, tag: "zz"}], nums: [], res: [{k95: "zz", k96: 2.5, k97: 50, k98: "zz", price: 2.5, qty: 50, tag: "zz"}], vip: false}], + [{vip: true, code: null, items: [{price: 99, qty: 7, tag: "zz"}, {price: 99, qty: 21, tag: "b"}, {qty: 1000}, {price: 7, qty: 0, tag: "gold"}], a: 21}, {a: 21, items: [{price: 99, qty: 7, tag: "zz"}, {price: 99, qty: 21, tag: "b"}, {qty: 1000}, {price: 7, qty: 0, tag: "gold"}], res: [{k95: "zz", k96: 99, k97: 7, k98: "zz", price: 99, qty: 7, tag: "zz"}, {k95: "b", k96: 99, k97: 21, k98: "b", price: 99, qty: 21, tag: "b"}, {k95: 1000, k97: 1000, qty: 1000}, {k95: "gold", k96: 7, k97: 0, k98: "gold", price: 7, qty: 0, tag: "gold"}], vip: true}], + [{vip: false, code: "silver", items: [{price: 7, qty: 1, tag: "zz"}, {price: -25, tag: "gold "}, {price: 21, qty: 19.99, tag: "silver"}], a: 3}, {a: 3, code: "silver", items: [{price: 7, qty: 1, tag: "zz"}, {price: -25, tag: "gold "}, {price: 21, qty: 19.99, tag: "silver"}], res: [{k95: "zz", k96: 7, k97: 1, k98: "zz", price: 7, qty: 1, tag: "zz"}, {k95: "gold ", k96: -25, k97: 1, k98: "gold ", price: -25, tag: "gold "}, {k95: "silver", k96: 21, k97: 19.99, k98: "silver", price: 21, qty: 19.99, tag: "silver"}], vip: false}], + [{vip: true, code: "a", a: 19.99, nums: [18, 100, 0.1]}, "!error"], + [{vip: true, code: "bronze", items: [{price: 100, qty: 1, tag: "a"}, {price: null, qty: 5, tag: "x"}, {price: 7, qty: 21, tag: "b"}], a: 11, nums: null}, {a: 11, code: "bronze", items: [{price: 100, qty: 1, tag: "a"}, {price: null, qty: 5, tag: "x"}, {price: 7, qty: 21, tag: "b"}], res: [{k95: "a", k96: 100, k97: 1, k98: "a", price: 100, qty: 1, tag: "a"}, {k95: "x", k97: 5, k98: "x", price: null, qty: 5, tag: "x"}, {k95: "b", k96: 7, k97: 21, k98: "b", price: 7, qty: 21, tag: "b"}], vip: true}], + [{vip: false, code: "", items: [{price: 5, qty: 0, tag: ""}, {price: -1, qty: -0.1, tag: "bronze"}, {price: 21, qty: 19.99, tag: "b"}, {price: 1, qty: 19.99, tag: "gold"}], a: null, nums: [-0.1, 0]}, {code: "", items: [{price: 5, qty: 0, tag: ""}, {price: -1, qty: -0.1, tag: "bronze"}, {price: 21, qty: 19.99, tag: "b"}, {price: 1, qty: 19.99, tag: "gold"}], nums: [-0.1, 0], res: [{k95: "", k96: 5, k97: 0, k98: "", price: 5, qty: 0, tag: ""}, {k95: "bronze", k96: -1, k97: -0.1, k98: "bronze", price: -1, qty: -0.1, tag: "bronze"}, {k95: "b", k96: 21, k97: 19.99, k98: "b", price: 21, qty: 19.99, tag: "b"}, {k95: "gold", k96: 1, k97: 19.99, k98: "gold", price: 1, qty: 19.99, tag: "gold"}], vip: false}], + [{vip: true, code: "Gold", items: [{price: 0, qty: -0.1, tag: null}, {price: 0.5, qty: 11, tag: "gold "}, {price: 19.99, qty: 11, tag: "zz"}], nums: [-1, 5, 21, 100, -3]}, {code: "Gold", items: [{price: 0, qty: -0.1, tag: null}, {price: 0.5, qty: 11, tag: "gold "}, {price: 19.99, qty: 11, tag: "zz"}], nums: [-1, 5, 21, 100, -3], res: [{k95: -0.1, k96: 0, k97: -0.1, k98: 0, price: 0, qty: -0.1, tag: null}, {k95: "gold ", k96: 0.5, k97: 11, k98: "gold ", price: 0.5, qty: 11, tag: "gold "}, {k95: "zz", k96: 19.99, k97: 11, k98: "zz", price: 19.99, qty: 11, tag: "zz"}], vip: true}], + [{a: -0.1, nums: [19.99, 21, 99]}, "!error"], + [{vip: false, code: "gold", items: [{price: 101, qty: 7, tag: ""}, {price: null, qty: 19.99, tag: "silver"}], a: 2.5, nums: [0.5]}, {a: 2.5, code: "gold", items: [{price: 101, qty: 7, tag: ""}, {price: null, qty: 19.99, tag: "silver"}], nums: [0.5], res: [{k95: "", k96: 101, k97: 7, k98: "", price: 101, qty: 7, tag: ""}, {k95: "silver", k97: 19.99, k98: "silver", price: null, qty: 19.99, tag: "silver"}], vip: false}], + [{vip: false, code: "b", items: [{price: 100, qty: 0.5, tag: "x"}, {price: 0.5, qty: 1, tag: null}, {price: 0.1, qty: 1000, tag: ""}, {price: 0.1, qty: 0.1, tag: ""}], nums: [], extra: [1, 2]}, {code: "b", extra: [1, 2], items: [{price: 100, qty: 0.5, tag: "x"}, {price: 0.5, qty: 1, tag: null}, {price: 0.1, qty: 1000, tag: ""}, {price: 0.1, qty: 0.1, tag: ""}], nums: [], res: [{k95: "x", k96: 100, k97: 0.5, k98: "x", price: 100, qty: 0.5, tag: "x"}, {k95: 1, k96: 0.5, k97: 1, k98: 0.5, price: 0.5, qty: 1, tag: null}, {k95: "", k96: 0.1, k97: 1000, k98: "", price: 0.1, qty: 1000, tag: ""}, {k95: "", k96: 0.1, k97: 0.1, k98: "", price: 0.1, qty: 0.1, tag: ""}], vip: false}], + [{vip: true, code: null, a: null, nums: [], extra: 1}, "!error"], + [{vip: false, code: "", items: [{price: 19.99, qty: 99, tag: "x"}, {price: 11, tag: ""}], a: -10, nums: []}, {a: -10, code: "", items: [{price: 19.99, qty: 99, tag: "x"}, {price: 11, tag: ""}], nums: [], res: [{k95: "x", k96: 19.99, k97: 99, k98: "x", price: 19.99, qty: 99, tag: "x"}, {k95: "", k96: 11, k97: 1, k98: "", price: 11, tag: ""}], vip: false}], + [{vip: false, code: "x", items: [{price: 1000, qty: 5, tag: null}, {price: 7, qty: 99, tag: null}, {price: -1, qty: 19.99, tag: "zz"}, {price: 2.5, qty: 18, tag: "b"}], a: 5, nums: [0.1]}, {a: 5, code: "x", items: [{price: 1000, qty: 5, tag: null}, {price: 7, qty: 99, tag: null}, {price: -1, qty: 19.99, tag: "zz"}, {price: 2.5, qty: 18, tag: "b"}], nums: [0.1], res: [{k95: 5, k96: 1000, k97: 5, k98: 1000, price: 1000, qty: 5, tag: null}, {k95: 99, k96: 7, k97: 99, k98: 7, price: 7, qty: 99, tag: null}, {k95: "zz", k96: -1, k97: 19.99, k98: "zz", price: -1, qty: 19.99, tag: "zz"}, {k95: "b", k96: 2.5, k97: 18, k98: "b", price: 2.5, qty: 18, tag: "b"}], vip: false}], + [{vip: true, code: "zz", items: [{price: 5, qty: 99, tag: "gold"}, {price: 10, qty: 7, tag: ""}], a: 0.1, nums: [5, 2.5, -1, 99, 1]}, {a: 0.1, code: "zz", items: [{price: 5, qty: 99, tag: "gold"}, {price: 10, qty: 7, tag: ""}], nums: [5, 2.5, -1, 99, 1], res: [{k95: "gold", k96: 5, k97: 99, k98: "gold", price: 5, qty: 99, tag: "gold"}, {k95: "", k96: 10, k97: 7, k98: "", price: 10, qty: 7, tag: ""}], vip: true}], + [{vip: false, code: "gold", items: [{price: -0.1, qty: 1000000000000000000000}, {price: 10, qty: -1, tag: "b"}, {qty: 2, tag: "gold "}, {price: 101, qty: 1000, tag: "gold"}], a: null, nums: [2.5, 1000, 19.99, 100, 2]}, {code: "gold", items: [{price: -0.1, qty: 1000000000000000000000}, {price: 10, qty: -1, tag: "b"}, {qty: 2, tag: "gold "}, {price: 101, qty: 1000, tag: "gold"}], nums: [2.5, 1000, 19.99, 100, 2], res: [{k95: 1000000000000000000000, k96: -0.1, k97: 1000000000000000000000, k98: -0.1, price: -0.1, qty: 1000000000000000000000}, {k95: "b", k96: 10, k97: -1, k98: "b", price: 10, qty: -1, tag: "b"}, {k95: "gold ", k97: 2, k98: "gold ", qty: 2, tag: "gold "}, {k95: "gold", k96: 101, k97: 1000, k98: "gold", price: 101, qty: 1000, tag: "gold"}], vip: false}], + [{vip: false, code: "silver", items: [{price: 1000000000000000000000, qty: 1, tag: null}, {price: 0.5, tag: "zz"}, {price: 21, qty: 10, tag: "x"}], a: null}, {code: "silver", items: [{price: 1000000000000000000000, qty: 1, tag: null}, {price: 0.5, tag: "zz"}, {price: 21, qty: 10, tag: "x"}], res: [{k95: 1, k96: 1000000000000000000000, k97: 1, k98: 1000000000000000000000, price: 1000000000000000000000, qty: 1, tag: null}, {k95: "zz", k96: 0.5, k97: 1, k98: "zz", price: 0.5, tag: "zz"}, {k95: "x", k96: 21, k97: 10, k98: "x", price: 21, qty: 10, tag: "x"}], vip: false}], + [{vip: false, code: "gold ", items: [{price: 21, qty: 11, tag: "bronze"}, {tag: ""}, {price: 18, qty: 1000000000000000000000, tag: ""}, {price: 11, qty: null, tag: "gold"}], a: 0.5, nums: [0.5, -0.1, 50]}, {a: 0.5, code: "gold ", items: [{price: 21, qty: 11, tag: "bronze"}, {tag: ""}, {price: 18, qty: 1000000000000000000000, tag: ""}, {price: 11, qty: null, tag: "gold"}], nums: [0.5, -0.1, 50], res: [{k95: "bronze", k96: 21, k97: 11, k98: "bronze", price: 21, qty: 11, tag: "bronze"}, {k95: "", k97: 1, k98: "", tag: ""}, {k95: "", k96: 18, k97: 1000000000000000000000, k98: "", price: 18, qty: 1000000000000000000000, tag: ""}, {k95: "gold", k96: 11, k97: 1, k98: "gold", price: 11, qty: null, tag: "gold"}], vip: false}], + [{vip: true, items: [{price: 10, tag: "gold "}, {price: 1000, qty: 11, tag: null}, {price: 12, qty: 2.5, tag: "silver"}], a: 0.5, nums: null}, {a: 0.5, items: [{price: 10, tag: "gold "}, {price: 1000, qty: 11, tag: null}, {price: 12, qty: 2.5, tag: "silver"}], res: [{k95: "gold ", k96: 10, k97: 1, k98: "gold ", price: 10, tag: "gold "}, {k95: 11, k96: 1000, k97: 11, k98: 1000, price: 1000, qty: 11, tag: null}, {k95: "silver", k96: 12, k97: 2.5, k98: "silver", price: 12, qty: 2.5, tag: "silver"}], vip: true}], + [{vip: true, code: "", items: [{price: 0.1, qty: 100, tag: "zz"}, {price: 7, qty: null, tag: "silver"}, {price: 2.5, qty: 1000, tag: "gold"}], a: 50}, {a: 50, code: "", items: [{price: 0.1, qty: 100, tag: "zz"}, {price: 7, qty: null, tag: "silver"}, {price: 2.5, qty: 1000, tag: "gold"}], res: [{k95: "zz", k96: 0.1, k97: 100, k98: "zz", price: 0.1, qty: 100, tag: "zz"}, {k95: "silver", k96: 7, k97: 1, k98: "silver", price: 7, qty: null, tag: "silver"}, {k95: "gold", k96: 2.5, k97: 1000, k98: "gold", price: 2.5, qty: 1000, tag: "gold"}], vip: true}], + [{vip: true, code: "b", items: [{price: 72, qty: null, tag: "zz"}], a: null}, {code: "b", items: [{price: 72, qty: null, tag: "zz"}], res: [{k95: "zz", k96: 72, k97: 1, k98: "zz", price: 72, qty: null, tag: "zz"}], vip: true}], + [{vip: true, code: "gold ", items: [{price: 1000, qty: null, tag: "b"}, {price: 3, tag: ""}, {price: 11, qty: -0.1, tag: ""}, {price: 10, qty: 2, tag: "Gold"}], a: 11, nums: [3, 99]}, {a: 11, code: "gold ", items: [{price: 1000, qty: null, tag: "b"}, {price: 3, tag: ""}, {price: 11, qty: -0.1, tag: ""}, {price: 10, qty: 2, tag: "Gold"}], nums: [3, 99], res: [{k95: "b", k96: 1000, k97: 1, k98: "b", price: 1000, qty: null, tag: "b"}, {k95: "", k96: 3, k97: 1, k98: "", price: 3, tag: ""}, {k95: "", k96: 11, k97: -0.1, k98: "", price: 11, qty: -0.1, tag: ""}, {k95: "Gold", k96: 10, k97: 2, k98: "Gold", price: 10, qty: 2, tag: "Gold"}], vip: true}], + [{vip: false, code: "gold", items: [], nums: null}, {code: "gold", items: [], res: [], vip: false}], + [{vip: true, code: null, items: [{price: 0.5, qty: 3, tag: "bronze"}, {price: 101, qty: 2.5, tag: "gold "}, {price: null, tag: "a"}], a: 15, nums: [50, 0, 104], extra: 1}, {a: 15, extra: 1, items: [{price: 0.5, qty: 3, tag: "bronze"}, {price: 101, qty: 2.5, tag: "gold "}, {price: null, tag: "a"}], nums: [50, 0, 104], res: [{k95: "bronze", k96: 0.5, k97: 3, k98: "bronze", price: 0.5, qty: 3, tag: "bronze"}, {k95: "gold ", k96: 101, k97: 2.5, k98: "gold ", price: 101, qty: 2.5, tag: "gold "}, {k95: "a", k97: 1, k98: "a", price: null, tag: "a"}], vip: true}], + [{vip: null, code: "x", items: [{price: 21, qty: 1, tag: "a"}], a: 101}, {a: 101, code: "x", items: [{price: 21, qty: 1, tag: "a"}], res: [{k95: "a", k96: 21, k97: 1, k98: "a", price: 21, qty: 1, tag: "a"}]}], + ], +} + +{ + name: "ga011: 7 nodes, expr, expr, table*, table, switch, expr, table", + graph: { + nodes: [ + {expression: "e1", outputPath: "res", fields: { + k102: "score ?? $.k102", + k104: "s", + }}, + {expression: "e2", passThrough: true, fields: { + k105: "(price) + (b ?? -1) + (price ?? 0) + ceil(2.25) % 3", + k106: "cust.age", + }}, + {table: "t3", hit: "collect", inputs: ["(k106)", null], outputs: ["m.k107", "k108"], outputPath: "lines", rules: [ + ["", "", "false", "string(false) + ':' + (cust.tier ?? '?') == 'gold'"], + ["not(1)", "5", "true", "true"], + ["$ > 10 and $ < 11", "null", "true", "false"], + ]}, + {table: "t4", inputField: "cust", inputs: ["age", "age", "active", null], outputs: ["k109"], rules: [ + ["< 5", "", "false", "", "10"], + ["< 100", "", "null", "", "0.25"], + ["null", "!= 10", "$ == true", "$ != null", "0"], + ["100, 110", "(5..6)", "", "5", "10"], + ["> 18", "$ > 0 and $ < 5", "$ == true", "true", "2"], + ["!= 18", "[5..15)", "false", "'gold'", "10"], + ["", "", "", "", "0.25"], + ]}, + {switch: "s5", when: ["(false) and (false)"]}, + {expression: "e6", passThrough: true, outputPath: "out", fields: { + k110: "len(string(3)) < -((0.5) / 10)", + k111: "(2 % 3 * (-4)) / 0.5", + k112: "res.k104 != null", + k113: "res.k104 ?? res.k104", + }}, + {table: "t7", inputs: ["'none'"], outputs: ["k114", "k115"], rules: [ + ["'', 'b'", "10", "0.25"], + ["'x', 'gold'", "10", "((2))"], + ["", "2", "2"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> e2", + "e2 -> t3", + "e1 -> t3", + "e2 -> t4", + "e2 -> s5", + "t3 -> e6", + "e1 -> e6", + "t3 -> t7", + "t4 -> output", + "s5:0 -> output", + "e6 -> output", + "t7 -> output", + ], + }, + cases: [ + [{b: null, price: 0.5, score: null, cust: {age: null, tier: "silver", active: 1}, s: 5}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: 5}, res: {k102: null, k104: 5}}], + [{price: 99, score: 1000, cust: null, s: "bronze"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "bronze"}, res: {k102: 1000, k104: "bronze"}}], + [{b: 0, price: 2.5, score: null, cust: {age: 2.5, tier: "gold", active: true}, s: "b"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "b"}, res: {k102: null, k104: "b"}}], + [{b: 1, price: 2, score: 11, cust: {age: null, tier: "Gold", active: true}, s: 5}, {k109: 0, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: 5}, res: {k102: 11, k104: 5}}], + [{b: -25, price: 21, score: 99, s: "x"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "x"}, res: {k102: 99, k104: "x"}}], + [{b: 100, score: 1000000000000000000000, cust: {age: null, tier: "Gold"}, s: ["gold"]}, "!error"], + [{price: 18, score: null, cust: null, s: "gold", extra: [1, 2]}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "gold"}, res: {k102: null, k104: "gold"}}], + [{b: 2.5, price: 19.99, score: null, cust: {age: 7, tier: "gold ", active: false}, s: "zz"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "zz"}, res: {k102: null, k104: "zz"}}], + [{b: 0.5, price: 1000000000000000000000, score: -25, cust: {age: 0.5, tier: "x", active: true}, s: "gold"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "gold"}, res: {k102: -25, k104: "gold"}}], + [{b: 101, price: 50, score: 1000, cust: {age: 6, tier: null, active: false}, s: "b"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "b"}, res: {k102: 1000, k104: "b"}}], + [{b: 1, price: 18, score: 1, cust: {age: true, tier: "", active: false}}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: false, k113: null}, res: {k102: 1, k104: null}}], + [{b: 100, price: 5, score: 3, cust: {age: 7, tier: "Gold", active: true}, s: "x"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "x"}, res: {k102: 3, k104: "x"}}], + [{b: 101, price: {v: 1}, score: -25, cust: {age: 5, tier: "silver"}}, "!error"], + [{b: 21, price: 88, score: {v: 1}, cust: {age: 99, tier: "", active: false}, s: "Gold", extra: "e"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "Gold"}, res: {k102: {v: 1}, k104: "Gold"}}], + [{b: 2.5, price: null, cust: {age: 0.5, tier: "Gold", active: false}, s: "Gold"}, "!error"], + [{b: 50, price: 100, score: 7, cust: {age: 5, tier: "a", active: false}, s: ""}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: ""}, res: {k102: 7, k104: ""}}], + [{b: 0.5, price: 3, score: -0.1, cust: null, s: "Gold"}, {k109: 0.25, k114: 2, k115: 2, lines: [{k108: false, m: {k107: false}}], out: {k110: false, k111: -16.0, k112: true, k113: "Gold"}, res: {k102: -0.1, k104: "Gold"}}], + ], +} + +{ + name: "ga012: 6 nodes, expr, expr, expr, expr, table*, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k116: "(2.25 != (price ?? 0)) or (price != null)", + }}, + {expression: "e2", fields: { + k117: "tier ?? tier", + }}, + {expression: "e3", fields: { + k118: "((false) ? 'none' : (tier ?? ''))", + k119: "a == null", + k120: "(price ?? 1)", + k121: "(tier ?? '?')", + }}, + {expression: "e4", passThrough: true, fields: { + k122: "a != null", + k123: "tier ?? price", + "m.k124": "(price > max([(price ?? 1), 2])) and ((price ?? -1) * price < len(tier))", + k125: "tier ?? tier", + }}, + {table: "t5", hit: "collect", inputs: ["m.k124", "m.k124", "price", null], outputs: ["m.k126", "k127"], outputPath: "o.p", rules: [ + ["", "false", "(100..101)", "", "''", "(len('A-1')) / 2 != ((price ?? k123 ?? 0)) / 10"], + ["false", "true", "> 18", "null", "''", "(price ?? 0) != (0.5) % 7"], + ["", "null", "null", "5", "'high'", "true"], + ["", "$ == true", "", "null", "'low'", "false"], + ]}, + {expression: "e6", passThrough: true, fields: { + k128: "(0.5 + 0.5)", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> e3", + "input -> e4", + "e4 -> t5", + "t5 -> e6", + "e2 -> output", + "e3 -> output", + "t5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{price: 10, tier: "x", nums: [0.1, -12, 10, 100, 11]}, {k117: "x", k118: "x", k119: true, k120: 10, k121: "x", k128: 1.0, o: {p: []}}], + [{price: 100, tier: "b", nums: [21, 19.99, 21], extra: "e"}, {k117: "b", k118: "b", k119: true, k120: 100, k121: "b", k128: 1.0, o: {p: []}}], + [{price: 11, tier: "x", nums: null}, {k117: "x", k118: "x", k119: true, k120: 11, k121: "x", k128: 1.0, o: {p: []}}], + [{price: 99, tier: "Gold", nums: [1, 11, 3, 1000, 1]}, {k117: "Gold", k118: "Gold", k119: true, k120: 99, k121: "Gold", k128: 1.0, o: {p: []}}], + [{price: 18, tier: "a", nums: [100]}, {k117: "a", k118: "a", k119: true, k120: 18, k121: "a", k128: 1.0, o: {p: []}}], + [{price: 1000, tier: "silver", nums: []}, {k117: "silver", k118: "silver", k119: true, k120: 1000, k121: "silver", k128: 1.0, o: {p: []}}], + [{price: 100, tier: "silver", extra: {deep: {x: 1}}}, {k117: "silver", k118: "silver", k119: true, k120: 100, k121: "silver", k128: 1.0, o: {p: []}}], + [{tier: "bronze", nums: [7, 99, 1000, 3, 18]}, "!error"], + [{price: 2.5, tier: ["gold"], nums: [0, 3, 19.99, 10, 17]}, {k117: ["gold"], k118: ["gold"], k119: true, k120: 2.5, k121: ["gold"], k128: 1.0, o: {p: []}}], + [{nums: null}, "!error"], + [{price: 11, tier: null, nums: [5]}, {k118: "", k119: true, k120: 11, k121: "?", k128: 1.0, o: {p: []}}], + [{price: -0.1, tier: 5, nums: [], extra: [1, 2]}, {k117: 5, k118: 5, k119: true, k120: -0.1, k121: 5, k128: 1.0, o: {p: []}}], + [{price: null, tier: "Gold", nums: [65, -1, -25, 5, 101], extra: {deep: {x: 1}}}, "!error"], + [{price: 11, tier: ["gold"], nums: [-25, 1000, 21, 100, 2]}, {k117: ["gold"], k118: ["gold"], k119: true, k120: 11, k121: ["gold"], k128: 1.0, o: {p: []}}], + [{price: 11, tier: "Gold", nums: [11]}, {k117: "Gold", k118: "Gold", k119: true, k120: 11, k121: "Gold", k128: 1.0, o: {p: []}}], + [{price: -0.1, tier: "zz", nums: "1,2"}, {k117: "zz", k118: "zz", k119: true, k120: -0.1, k121: "zz", k128: 1.0, o: {p: []}}], + [{price: 7, tier: null, nums: [0.1, 50]}, {k118: "", k119: true, k120: 7, k121: "?", k128: 1.0, o: {p: []}}], + [{price: 101, tier: "zz", nums: []}, {k117: "zz", k118: "zz", k119: true, k120: 101, k121: "zz", k128: 1.0, o: {p: []}}], + [{price: 21, tier: null, nums: null}, {k118: "", k119: true, k120: 21, k121: "?", k128: 1.0, o: {p: []}}], + [{price: 1000, tier: "gold", nums: []}, {k117: "gold", k118: "gold", k119: true, k120: 1000, k121: "gold", k128: 1.0, o: {p: []}}], + [{price: true, tier: ["gold"], nums: [7, 0.1, 50]}, "!error"], + [{price: 18, tier: "zz", nums: [50, 2.5]}, {k117: "zz", k118: "zz", k119: true, k120: 18, k121: "zz", k128: 1.0, o: {p: []}}], + [{price: 0.1, nums: [5, 19.99, 5, 1000000000000000000000, -25]}, {k118: "", k119: true, k120: 0.1, k121: "?", k128: 1.0, o: {p: []}}], + [{price: 0.1, tier: 5, nums: null}, {k117: 5, k118: 5, k119: true, k120: 0.1, k121: 5, k128: 1.0, o: {p: []}}], + ], +} + +{ + name: "ga013: 6 nodes, expr, expr, expr, table*, table*, table", + graph: { + nodes: [ + {expression: "e1", outputPath: "res", fields: { + k129: "len(upper(s + ' ' + 'none'))", + k130: "(price ?? 1) + ($.k129) / 10", + }}, + {expression: "e2", passThrough: true, fields: { + "m.k131": "res.k129", + k132: "-4", + k133: "res.k129 ?? res.k129", + }}, + {expression: "e3", fields: { + "res.k134": "(s ?? '?')", + "res.k135": "b ?? price", + }}, + {table: "t4", hit: "collect", inputs: ["3", "((false) or (false) ? res.k134 + ' ' + (res.k134 ?? '?') : (res.k134 ?? ''))", "(res.k134 ?? '?')"], outputs: ["k136"], outputPath: "o.p", rules: [ + ["!= 21", "", "$ != 'silver'", "100"], + ["(10..60)", "null", "", "-5"], + ["not(100)", "$ != ''", "null", "100"], + ["", "", "", "-(len(res.k134) % 7)"], + ]}, + {table: "t5", hit: "collect", inputs: ["'none'"], outputs: ["k137[]"], rules: [ + ["null", "'gold'"], + ["'gold', 'gold'", "string((contains('A-1', 'x')) or (true))"], + ["'a'", "string(true)"], + ["", "'high'"], + ["", "'gold'"], + ]}, + {table: "t6", inputs: ["2.25", "(len('x'))", "string(true)"], outputs: ["k138", "k139"], rules: [ + ["", "!= -1", "'', 'bronze'", "true", "`v${-4}-${''}`"], + ["", "21", "", "true", "'high'"], + ["1, 11", "> 21", "not('')", "false", "trim('A-1')"], + ["!= 5", "[1..11)", "startsWith($, 'x')", "true", "'high'"], + ["18, 19", "[10..60)", "startsWith($, 'g')", "false", "string((100 in [0..10]) and (true))"], + ["-1", "<= 15", "$ != 'a'", "(ceil(3)) <= (1 == 0.5 ? 1 : ceil(0))", "''"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> e3", + "e3 -> t4", + "t4 -> t5", + "t5 -> t6", + "e2 -> output", + "t6 -> output", + ], + }, + cases: [ + [{score: 0.1, vip: false, b: 2, price: 18, s: null, flag: false}, "!error"], + [{score: 1000000000000000000000, vip: true, b: 101, price: 5, s: "silver", flag: 1}, {k132: -4, k133: 11, m: {k131: 11}, res: {k129: 11, k130: 6.10}}], + [{score: 18, vip: false, b: 18, price: 8, s: "Gold", flag: false}, {k132: -4, k133: 9, m: {k131: 9}, res: {k129: 9, k130: 8.90}}], + [{score: 43, vip: false, b: true, price: 0, s: "b", flag: false}, {k132: -4, k133: 6, m: {k131: 6}, res: {k129: 6, k130: 0.60}}], + [{score: 1, vip: null, b: "abc", price: 2, s: true, flag: false}, "!error"], + [{score: 2, vip: false, b: -0.1, price: 50, s: "gold ", flag: true}, {k132: -4, k133: 10, m: {k131: 10}, res: {k129: 10, k130: 51}}], + [{score: "abc", vip: false, b: -0.1, price: 66, s: "gold", flag: true}, {k132: -4, k133: 9, m: {k131: 9}, res: {k129: 9, k130: 66.90}}], + [{score: 50, vip: false, b: -1, price: 50, s: "Gold", flag: null}, {k132: -4, k133: 9, m: {k131: 9}, res: {k129: 9, k130: 50.90}}], + [{score: 1000000000000000000000, vip: true, b: 99, price: 49, s: "a", flag: true}, {k132: -4, k133: 6, m: {k131: 6}, res: {k129: 6, k130: 49.60}}], + [{score: 0.5, vip: false, b: 11, price: 2, s: "x", flag: true, extra: [1, 2]}, {k132: -4, k133: 6, m: {k131: 6}, res: {k129: 6, k130: 2.60}}], + [{score: 0.1, vip: false, b: 18, price: 2.5, s: "gold ", flag: false, extra: 1}, {k132: -4, k133: 10, m: {k131: 10}, res: {k129: 10, k130: 3.5}}], + [{score: 2.5, vip: false, b: 100, price: 101, s: ""}, {k132: -4, k133: 5, m: {k131: 5}, res: {k129: 5, k130: 101.50}}], + [{score: 11, vip: true, b: 3, price: -0.1, flag: "no"}, "!error"], + [{score: 99, vip: true, b: 18, price: -25, s: "gold", flag: null}, {k132: -4, k133: 9, m: {k131: 9}, res: {k129: 9, k130: -24.10}}], + [{score: "abc", vip: true, b: 99, price: -25, s: "a", flag: true}, {k132: -4, k133: 6, m: {k131: 6}, res: {k129: 6, k130: -24.40}}], + [{score: 5, vip: false, b: "5", price: -25, s: "", flag: true}, {k132: -4, k133: 5, m: {k131: 5}, res: {k129: 5, k130: -24.50}}], + [{score: 2, vip: false, b: 5, price: 3, s: "b", flag: true}, {k132: -4, k133: 6, m: {k131: 6}, res: {k129: 6, k130: 3.60}}], + [{score: 7, vip: false, b: null, price: [1], s: "x", flag: false}, "!error"], + [{score: 7, vip: 0, b: 11, price: 99, flag: false}, "!error"], + [{score: 0, vip: false, b: 1000000000000000000000, price: 11, s: "x", flag: false}, {k132: -4, k133: 6, m: {k131: 6}, res: {k129: 6, k130: 11.60}}], + [{score: 99, vip: false, b: 5, price: 7, s: "gold ", flag: 1}, {k132: -4, k133: 10, m: {k131: 10}, res: {k129: 10, k130: 8}}], + [{score: 10, b: 1, price: 5, s: "b", flag: false}, {k132: -4, k133: 6, m: {k131: 6}, res: {k129: 6, k130: 5.60}}], + ], +} + +{ + name: "ga014: 3 nodes, expr, expr, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "out", fields: { + k140: "tier ?? price", + k141: "'none'", + k142: "(true ? (price ?? 0) : (a ?? -1) + 2) % 2", + }}, + {expression: "e2", fields: { + k143: "((2) > (a ?? -1) + (price ?? 0) ? (a ?? 0) : 0.5)", + }}, + {table: "t3", inputs: ["a", "a", "(tier ?? 'none')"], outputs: ["k144", "k145"], passThrough: true, rules: [ + ["!= 18", "$ > 21 and $ < 31", "startsWith($, 's')", "'mid'", "false"], + ["", "> 10", "startsWith($, 's')", "'mid'", "(string((vip ?? false)) in ['gold', 'silver', 'a']) or (true)"], + ["", "not(-1)", "$ != 'a'", "'high'", "false"], + ["(10..15)", "null", "", "'mid'", "true"], + ["< 0", "(10..20)", "'x', 'gold'", "'low'", "(vip ?? false)"], + ]}, + ], + edges: [ + "input -> e1", + "input -> e2", + "input -> t3", + "e1 -> output", + "e2 -> output", + "t3 -> output", + ], + }, + cases: [ + [{nums: [7, 0], vip: null, a: 0.5, tier: "a", price: 7}, {a: 0.5, k143: 0.5, nums: [7, 0], out: {k140: "a", k141: "none", k142: 1}, price: 7, tier: "a"}], + [{nums: [0.1, 101, -1], vip: false, a: 0.5, tier: "gold ", price: 7, extra: "e"}, {a: 0.5, extra: "e", k143: 0.5, nums: [0.1, 101, -1], out: {k140: "gold ", k141: "none", k142: 1}, price: 7, tier: "gold ", vip: false}], + [{nums: [], vip: null, a: 7, tier: "gold ", price: 21, extra: "e"}, {a: 7, extra: "e", k143: 0.5, nums: [], out: {k140: "gold ", k141: "none", k142: 1}, price: 21, tier: "gold "}], + [{nums: [18, 1000, 2], vip: true, a: 2.5, tier: "silver", price: 0}, {a: 2.5, k143: 0.5, nums: [18, 1000, 2], out: {k140: "silver", k141: "none", k142: 0}, price: 0, tier: "silver", vip: true}], + [{nums: [], vip: true, a: 0.1, tier: "gold ", price: 3}, {a: 0.1, k143: 0.5, nums: [], out: {k140: "gold ", k141: "none", k142: 1}, price: 3, tier: "gold ", vip: true}], + [{nums: [], vip: false, a: 2.5, tier: "gold ", price: 2.5}, {a: 2.5, k143: 0.5, nums: [], out: {k140: "gold ", k141: "none", k142: 0.5}, price: 2.5, tier: "gold ", vip: false}], + [{nums: [-25], vip: true, a: 21, price: 7}, {a: 21, k143: 0.5, nums: [-25], out: {k140: 7, k141: "none", k142: 1}, price: 7, vip: true}], + [{nums: [3, 2], vip: false, a: 0.1, tier: "zz", price: 5}, {a: 0.1, k143: 0.5, nums: [3, 2], out: {k140: "zz", k141: "none", k142: 1}, price: 5, tier: "zz", vip: false}], + [{nums: [1], vip: false, tier: "x", price: 82, extra: "e"}, {extra: "e", k143: 0.5, nums: [1], out: {k140: "x", k141: "none", k142: 0}, price: 82, tier: "x", vip: false}], + [{nums: [50, 0, 1000000000000000000000, 11, 1000000000000000000000], a: null, tier: "a", price: null}, {k143: 0, nums: [50, 0, 1000000000000000000000, 11, 1000000000000000000000], out: {k140: "a", k141: "none", k142: 0}, tier: "a"}], + [{vip: false, a: 1, tier: "b", price: 3}, {a: 1, k143: 0.5, out: {k140: "b", k141: "none", k142: 1}, price: 3, tier: "b", vip: false}], + [{nums: [101, 7], vip: false, a: 100, tier: "bronze", price: 21}, {a: 100, k143: 0.5, nums: [101, 7], out: {k140: "bronze", k141: "none", k142: 1}, price: 21, tier: "bronze", vip: false}], + [{nums: [], vip: true, tier: "Gold", price: null}, {k143: 0, nums: [], out: {k140: "Gold", k141: "none", k142: 0}, tier: "Gold", vip: true}], + [{nums: [], vip: true, a: -25, tier: "", price: 19.99}, {a: -25, k143: -25, nums: [], out: {k140: "", k141: "none", k142: 1.99}, price: 19.99, tier: "", vip: true}], + [{nums: [100], vip: null, a: 2, tier: "silver"}, {a: 2, k143: 0.5, nums: [100], out: {k140: "silver", k141: "none", k142: 0}, tier: "silver"}], + [{vip: true, a: -0.1, tier: "bronze", price: 50}, {a: -0.1, k143: 0.5, out: {k140: "bronze", k141: "none", k142: 0}, price: 50, tier: "bronze", vip: true}], + [{nums: [1000000000000000000000], vip: true, a: 2, tier: "gold ", price: null}, {a: 2, k143: 0.5, nums: [1000000000000000000000], out: {k140: "gold ", k141: "none", k142: 0}, tier: "gold ", vip: true}], + [{nums: [-1], vip: true, a: 0.1, tier: null, price: 1}, {a: 0.1, k143: 0.1, nums: [-1], out: {k140: 1, k141: "none", k142: 1}, price: 1, vip: true}], + [{nums: [19.99, 3], a: 1, tier: "x", price: 101, extra: 1}, {a: 1, extra: 1, k143: 0.5, nums: [19.99, 3], out: {k140: "x", k141: "none", k142: 1}, price: 101, tier: "x"}], + [{nums: [-25, 3, 99, 21, 18], vip: false, a: -0.1, tier: null, price: 2.5, extra: [1, 2]}, {a: -0.1, extra: [1, 2], k143: 0.5, nums: [-25, 3, 99, 21, 18], out: {k140: 2.5, k141: "none", k142: 0.5}, price: 2.5, vip: false}], + [{nums: [-0.1], vip: false, a: 18, tier: "silver", price: 99}, {a: 18, k143: 0.5, k144: "mid", k145: true, nums: [-0.1], out: {k140: "silver", k141: "none", k142: 1}, price: 99, tier: "silver", vip: false}], + [{nums: [19.99, 2, 0.1, 0.1, 1000000000000000000000], vip: false, a: 0.1, tier: "Gold", price: -0.1}, {a: 0.1, k143: 0.1, nums: [19.99, 2, 0.1, 0.1, 1000000000000000000000], out: {k140: "Gold", k141: "none", k142: -0.1}, price: -0.1, tier: "Gold", vip: false}], + [{nums: [1, 0.5, 3, 92, 0], vip: false, a: 113, tier: "", price: 99}, {a: 113, k143: 0.5, nums: [1, 0.5, 3, 92, 0], out: {k140: "", k141: "none", k142: 1}, price: 99, tier: "", vip: false}], + [{nums: [], vip: null, a: 2, tier: "x"}, {a: 2, k143: 0.5, nums: [], out: {k140: "x", k141: "none", k142: 0}, tier: "x"}], + [{nums: [100, 5, 1], vip: null, a: 1000000000000000000000, tier: "silver", price: 2.5}, {a: 1000000000000000000000, k143: 0.5, k144: "mid", k145: true, nums: [100, 5, 1], out: {k140: "silver", k141: "none", k142: 0.5}, price: 2.5, tier: "silver"}], + [{nums: [19.99, 3, 2.5, 19.99, 18], vip: true, a: 5, tier: "b", price: 0.1, extra: {deep: {x: 1}}}, {a: 5, extra: {deep: {x: 1}}, k143: 0.5, nums: [19.99, 3, 2.5, 19.99, 18], out: {k140: "b", k141: "none", k142: 0.1}, price: 0.1, tier: "b", vip: true}], + ], +} + +{ + name: "ga015: 8 nodes, table*, expr, switch, expr, switch, switch*, table*, table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["a"], outputs: ["k146"], outputPath: "res", rules: [ + ["$ > 5 and $ < 15", "'low'"], + ["10", "(s ?? 'none') + ' ' + (true ? (code ?? 'none') : (s ?? '?')) + ' ' + lower((code ?? ''))"], + ["18", "'mid'"], + ["", "'high'"], + ]}, + {expression: "e2", fields: { + k147: "floor(0.5)", + "g.k148": "(true)", + }}, + {switch: "s3", when: ["(k147 ?? -1) % 7 in [1..100]", ""]}, + {expression: "e4", passThrough: true, outputPath: "res", fields: { + k149: "lower(`${k147}-${'x'}`)", + k150: "-((((k147 ?? 0)) / 4) / 3)", + k151: "(not ((k147 ?? -1) < 2.25)) or (string((g.k148 ?? false)) in ['gold', 'silver', 'a'])", + }}, + {switch: "s5", when: ["(k147 ?? k147 ?? 0) > ((res.k150 ?? -1)) + (k147) / 10", "('gold' + '-' + (res.k149 ?? '?') in ['gold', 'silver', 'a'])"]}, + {switch: "s6", hit: "collect", when: ["((g.k148 ?? false)) and (((k147 ?? -1)) / 3 != min([(k147 ?? 1), (k147 ?? 1)]))", "len(upper('x')) > k147", ""]}, + {table: "t7", hit: "collect", inputs: ["k147", "k147"], outputs: ["k150[]", "k153"], passThrough: true, rules: [ + ["!= 21", "[5..15)", "true", "false"], + ["[1..51]", "[18..23]", "(contains('', 'g')) or (lower('none') in ['gold', 'silver', 'a'])", "(g.k148 ?? false)"], + ["(100..150)", "$ > 50 and $ < 51", "true", "((g.k148 ?? false)) or (not ((k147 ?? 0) < (k147 ?? 1)))"], + ["", "$ > 50 and $ < 55", "false", "true"], + ]}, + {table: "t8", inputs: ["g.k148"], outputs: ["k146", "k155"], rules: [ + ["$ == true", "'gold'", "'gold'"], + ["true", "''", "'high'"], + ["false", "'high'", "'mid'"], + ["true", "'mid'", "'mid'"], + ["true", "'mid'", "'gold'"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "e2 -> s3", + "e2 -> e4", + "s3:0 -> s5", + "e4 -> s5", + "e2 -> s6", + "s6:0 -> t7", + "t7 -> t8", + "s3:1 -> output", + "e4 -> output", + "s5:0 -> output", + "s5:1 -> output", + "s6:1 -> output", + "s6:2 -> output", + "t8 -> output", + ], + }, + cases: [ + [{price: -25, a: 2, items: [{price: 101, qty: 101, tag: "a"}, {price: 1000000000000000000000, qty: 10}], vip: false, code: "b", nums: [], s: "Gold"}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 18, a: 1, items: [{price: 0.5, qty: 100, tag: "a"}, {price: 10, qty: 19.99, tag: "Gold"}, {price: -25, qty: 43, tag: "x"}, {price: 0, qty: 11, tag: "gold"}], vip: true, code: "gold ", nums: [], s: "Gold"}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: null, a: 19.99, items: [{price: 21, qty: -1, tag: "bronze"}], code: "silver", nums: [0.5, -1, 11], s: null}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 19.99, a: 2.5, items: [{price: -25, qty: 99, tag: "gold "}], vip: true, code: "bronze", nums: [], s: "silver"}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 1000000000000000000000, a: 0, items: [], vip: false, code: "silver", nums: null, s: ""}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 19.99, a: -1, items: [{qty: 2, tag: ""}, {price: 1000000000000000000000, qty: 0.5, tag: "bronze"}], vip: true, code: "b", nums: [3], s: "gold"}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 10, a: 50, items: [{price: -25, qty: null, tag: "x"}, {price: 100, qty: 0.1, tag: "gold"}, {price: 0.1, qty: -25, tag: "zz"}], vip: true, nums: [], s: "x"}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{a: 0, items: [{price: 1000000000000000000000, qty: 0}, {price: 1, qty: 7, tag: "Gold"}], vip: false, code: "silver", nums: [-0.1, 100, 0, 19.99, 18], s: "gold", extra: [1, 2]}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 5, a: 101, items: [{price: 3, qty: 50, tag: "bronze"}, {price: 2.5, qty: 0, tag: "x"}, {price: 3, qty: 5, tag: "bronze"}], vip: false, code: "gold", nums: [0, 0.1], s: "Gold"}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 0.5, a: 50, items: [{price: 10, qty: -1, tag: null}, {price: 50, qty: null, tag: "gold "}], vip: false, code: "silver", nums: [21], s: "zz"}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 11, a: null, items: [{price: 19.99, qty: 101, tag: "silver"}, {price: 0.5, qty: 0, tag: "Gold"}], vip: false, code: "b", nums: [11, 100, 101, 19.99, 114]}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 120, a: 0.1, items: [{price: 99, qty: null, tag: "x"}, {price: 0.1, qty: 0, tag: "zz"}, {price: 3, qty: 10, tag: ""}], vip: true, code: "gold", nums: [], s: "gold "}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{price: 2, a: 3, vip: false, code: "bronze", nums: [11, 10, 100, -25, 0.1], s: "gold "}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + [{items: [{price: 7, qty: 3, tag: "x"}, {price: 50, qty: 7, tag: "gold "}, {price: 1000000000000000000000, qty: 3, tag: "b"}, {price: 3, qty: 1, tag: "gold"}], vip: true, code: "", nums: [], s: "a"}, {g: {k148: true}, k147: 0, res: {k149: "0-x", k150: -0, k151: false}}], + ], +} + +{ + name: "ga016: 3 nodes, table*, expr, table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["-4"], outputs: ["k156[]"], rules: [ + ["< 100", "true"], + ["!= 100", "false"], + ["21, 26", "true"], + ["[10..60)", "(code == null) and ((flag ?? false))"], + ]}, + {expression: "e2", passThrough: true, fields: { + k157: "trim(string((flag ?? false))) + '' + ((flag ?? false) ? (s ?? 'none') : `n=${(price ?? 1)}-${code}`)", + }}, + {table: "t3", inputs: ["''", "string(3 == 3)", "((true) or (false) ? 2 : 100)"], outputs: ["k158"], rules: [ + ["'x', 'gold'", "not('x')", "", "true"], + ["'silver', 'gold'", "$ != ''", "1, 2", "`n=${2.25}-${'none'}` == ''"], + ["not('gold')", "startsWith($, 's')", "0", "false"], + ["", "not('')", "", "false"], + ["'x'", "", "", "false"], + ["", "'x'", "[100..105)", "false"], + ["", "", "", "false"], + ]}, + ], + edges: [ + "input -> t1", + "input -> e2", + "t1 -> t3", + "t1 -> output", + "e2 -> output", + "t3 -> output", + ], + }, + cases: [ + [{flag: false, items: [], a: 1, tier: "gold ", s: "gold ", code: "a", price: 1000}, [{k156: true}, {k156: false}]], + [{flag: true, items: [{price: 1000000000000000000000, tag: "bronze"}, {price: 1000000000000000000000, qty: null}, {price: null, tag: "zz"}, {qty: 2, tag: "Gold"}], a: 101, tier: "", s: null, code: "x"}, [{k156: true}, {k156: false}]], + [{flag: null, items: [{price: 2.5, qty: -1}], a: 2, tier: null, s: null, code: "Gold", price: 101, extra: 1}, [{k156: true}, {k156: false}]], + [{flag: false, items: [{price: 2.5, qty: -25, tag: "gold"}, {price: 5, qty: 100, tag: "gold"}], a: 50, tier: "x", s: "Gold", code: null, price: 1}, [{k156: true}, {k156: false}]], + [{flag: true, items: [], a: 5, tier: "gold ", s: "silver", code: "gold", price: 99}, [{k156: true}, {k156: false}]], + [{flag: true, items: [], a: 0.5, tier: "zz", s: "silver", code: "Gold", price: 19.99}, [{k156: true}, {k156: false}]], + [{flag: false, items: [], tier: "a", s: null, code: "zz", price: null, extra: [1, 2]}, [{k156: true}, {k156: false}]], + [{flag: true, items: [{price: 21, qty: null, tag: "Gold"}, {price: -25, qty: 1000000000000000000000, tag: "a"}], a: 2.5, tier: "gold", s: "zz", code: "x", price: 100}, [{k156: true}, {k156: false}]], + [{flag: 0, items: [{price: 21, qty: 1000, tag: "b"}, {price: 0.1, qty: null, tag: "gold"}, {price: 3, qty: -1, tag: ""}, {price: -1, qty: 2}], a: true, tier: "x", s: "gold", code: "zz", price: {v: 1}, extra: 1}, "!error"], + [{flag: true, items: [{price: 3, qty: 18}, {price: 3, qty: 1000000000000000000000, tag: null}, {price: -0.1, qty: null, tag: null}], tier: "", s: "b", code: "x", price: 101}, [{k156: true}, {k156: false}]], + [{flag: false, items: null, a: 1000000000000000000000, tier: "x", s: "Gold", code: null, price: 99}, [{k156: true}, {k156: false}]], + [{flag: false, items: [{price: 0.1, qty: 0.1, tag: "zz"}, {price: 11, qty: 99, tag: ""}], a: 21, tier: "zz", s: "bronze", code: "a"}, [{k156: true}, {k156: false}]], + [{flag: false, a: 11, tier: "a", s: "a", price: 50}, [{k156: true}, {k156: false}]], + [{flag: false, items: [{price: 0.5, qty: 7, tag: null}, {price: 0, qty: 50, tag: "bronze"}, {price: 21, qty: 18, tag: "x"}], tier: "", s: "", code: "", price: 2.5}, [{k156: true}, {k156: false}]], + [{flag: null, items: [{price: 2.5, qty: -25, tag: "gold "}, {price: 18, qty: 100, tag: "gold"}], a: [1], tier: null, s: "silver", code: "silver", price: 7}, [{k156: true}, {k156: false}]], + [{flag: true, items: [{qty: 18, tag: "a"}], a: -25, tier: "gold", s: "", code: "zz", price: 1, extra: {deep: {x: 1}}}, [{k156: true}, {k156: false}]], + [{flag: true, items: [{price: 0.1, qty: 5, tag: "gold "}, {price: 1000000000000000000000, qty: 5, tag: "x"}], a: 7, tier: "silver", s: "silver", code: "b", price: 99}, [{k156: true}, {k156: false}]], + [{flag: false, items: [{qty: 101, tag: "gold"}], a: 50, tier: "gold", s: "gold", price: 3, extra: {deep: {x: 1}}}, [{k156: true}, {k156: false}]], + [{items: [{price: 71, qty: 0, tag: "x"}, {price: null, qty: 2.5}], a: 0.5, tier: "Gold", s: "gold ", code: "a", price: 11}, [{k156: true}, {k156: false}]], + [{flag: false, items: [{price: 5, qty: 99, tag: "x"}, {price: 1000, qty: 18, tag: "Gold"}], a: 11, tier: "", s: "gold", code: "a", price: "abc"}, [{k156: true}, {k156: false}]], + [{flag: false, items: [{price: 11, qty: 0.5, tag: "zz"}, {price: -1, qty: -25, tag: "a"}, {price: null, qty: 100, tag: "Gold"}, {qty: 19.99, tag: "zz"}], a: 7, tier: "Gold", s: "bronze", code: "gold", price: 101}, [{k156: true}, {k156: false}]], + [{flag: true, items: [{price: 2.5, qty: null, tag: ""}, {price: 11, qty: 19.99, tag: "a"}, {price: null, qty: -1, tag: "b"}], a: 1000000000000000000000, tier: "b", s: "b", code: "b", price: 18}, [{k156: true}, {k156: false}]], + [{flag: false, items: [{price: 18, qty: null}], a: 0.5, tier: "", s: "silver", code: "silver", price: 0.5}, [{k156: true}, {k156: false}]], + [{flag: true, items: [{price: 0.5, qty: 1000000000000000000000, tag: "gold"}, {price: null, qty: 1, tag: "zz"}, {price: 7, tag: "a"}], a: 18, tier: "zz", s: true, price: [1]}, "!error"], + [{flag: false, items: null, a: -25, tier: "Gold", s: "silver", price: 11}, [{k156: true}, {k156: false}]], + ], +} + +{ + name: "ga017: 7 nodes, table, table*, expr, expr, expr, switch, table", + graph: { + nodes: [ + {table: "t1", inputs: ["(score ?? 0)", "vip"], outputs: ["k159"], passThrough: true, rules: [ + ["(50..60)", "", "lower((s ?? '?')) + '-' + (code ?? 'none') != 'silver'"], + ["!= 18", "", "false"], + ["null", "$ == true", "(b ?? -1) >= (((price ?? -1)) / 2)"], + ["", "", "true"], + ]}, + {table: "t2", hit: "collect", inputs: ["code"], outputs: ["k160"], outputPath: "lines", rules: [ + ["null", "0"], + ["not('x')", "2"], + ["$ != 'x'", "2"], + ["startsWith($, 'g')", "-(((b ?? -1))) % 7"], + ["$ != 'x'", "0.25"], + ["", "0"], + ["", "0"], + ]}, + {expression: "e3", fields: { + k159: "2.25 - score", + k162: "(((($.k159 ?? 0))) / 0.5)", + k163: "(b ?? 1)", + k164: "string(vip) + '' + code == 'silver'", + }}, + {expression: "e4", fields: { + k165: "k164", + "g.k166": "k164 ?? k163", + k167: "k164 ?? k162", + k168: "(k162 ?? 0)", + }}, + {expression: "e5", fields: { + k169: "(k159 != null) or (true)", + "m.k170": "k159", + k171: "((true) ? (($.k169 ? (k168 ?? -1) : 2)) : ((vip ?? false) ? (score ?? -1) : -(b)))", + "res.k172": "$.k169 ?? s", + }}, + {switch: "s6", when: ["vip", "(b ?? 1) == (price ?? 1) * -4 * (score ?? 1)", ""]}, + {table: "t7", inputs: ["score", "(score ?? 0)", "(code ?? 'none')", null], outputs: ["g.k173"], passThrough: true, rules: [ + ["null", "", "'x', 'b'", "true", "'high'"], + ["$ > 50 and $ < 51", ">= 21", "", "", "'high'"], + ["null", "not(1)", "startsWith($, 's')", "'gold'", "'gold'"], + ["50, 55", "[0..1]", "'x'", "true", "'mid'"], + ["<= 23", "< 5", "$ != 'x'", "true", "'high'"], + ["", "$ > 18 and $ < 19", "", "'gold'", "'low'"], + ]}, + ], + edges: [ + "input -> t1", + "input -> t2", + "t1 -> e3", + "e3 -> e4", + "t1 -> e5", + "e4 -> e5", + "input -> s6", + "s6:1 -> t7", + "s6:0 -> t7", + "t2 -> output", + "e4 -> output", + "e5 -> output", + "s6:2 -> output", + "t7 -> output", + ], + }, + cases: [ + [{s: "bronze", vip: true, code: null, price: 1, b: 101, score: 10}, "!error"], + [{s: "Gold", vip: true, code: "gold ", price: 2, b: 0.1, score: -0.1}, {b: 0.1, code: "gold ", g: {k166: false, k173: "high"}, k165: false, k167: false, k168: 4.7, k169: true, k171: 4.7, lines: [{k160: 2}, {k160: -0.1}, {k160: 0.25}, {k160: 0}, {k160: 0}], m: {k170: false}, price: 2, res: {k172: true}, s: "Gold", score: -0.1, vip: true}], + [{s: "silver", vip: true, code: null, price: 0.1, b: 21, score: -14, extra: [1, 2]}, "!error"], + [{s: "Gold", vip: 1, code: "bronze", price: 19.99, b: 7, score: 18, extra: 1}, {b: 7, code: "bronze", extra: 1, g: {k166: false}, k165: false, k167: false, k168: -31.5, k169: true, k171: -31.5, lines: [{k160: 2}, {k160: 0.25}, {k160: 0}, {k160: 0}], m: {k170: true}, price: 19.99, res: {k172: true}, s: "Gold", score: 18, vip: 1}], + [{s: "gold", vip: true, code: "silver", price: null, b: 11, score: 32}, {b: 11, code: "silver", g: {k166: false}, k165: false, k167: false, k168: -59.5, k169: true, k171: -59.5, lines: [{k160: 2}, {k160: 0.25}, {k160: 0}, {k160: 0}], m: {k170: false}, res: {k172: true}, s: "gold", score: 32, vip: true}], + [{s: "bronze", vip: true, code: "gold ", price: 2.5, b: 101, score: 2}, {b: 101, code: "gold ", g: {k166: false, k173: "high"}, k165: false, k167: false, k168: 0.5, k169: true, k171: 0.5, lines: [{k160: 2}, {k160: -3}, {k160: 0.25}, {k160: 0}, {k160: 0}], m: {k170: false}, price: 2.5, res: {k172: true}, s: "bronze", score: 2, vip: true}], + [{s: "gold ", vip: true, code: "gold", b: 11, score: -1}, {b: 11, code: "gold", g: {k166: false, k173: "high"}, k165: false, k167: false, k168: 6.5, k169: true, k171: 6.5, lines: [{k160: 2}, {k160: -4}, {k160: 0.25}, {k160: 0}, {k160: 0}], m: {k170: false}, res: {k172: true}, s: "gold ", score: -1, vip: true}], + [{s: "a", vip: false, code: "", price: 10, b: 3, score: "5"}, "!error"], + [{s: "b", vip: null, code: "gold", price: 50, b: 1000000000000000000000, score: -25}, {b: 1000000000000000000000, code: "gold", g: {k166: false}, k165: false, k167: false, k168: 54.5, k169: true, k171: 54.5, lines: [{k160: 2}, {k160: -6}, {k160: 0.25}, {k160: 0}, {k160: 0}], m: {k170: false}, price: 50, res: {k172: true}, s: "b", score: -25}], + [{s: "gold ", vip: true, code: "zz", price: -0.1, b: -25, score: 1000000000000000000000}, {b: -25, code: "zz", g: {k166: false}, k165: false, k167: false, k168: -1999999999999999999995.5, k169: true, k171: -1999999999999999999995.5, lines: [{k160: 2}, {k160: 0.25}, {k160: 0}, {k160: 0}], m: {k170: false}, price: -0.1, res: {k172: true}, s: "gold ", score: 1000000000000000000000, vip: true}], + [{s: true, vip: false, code: null, price: 2.5, b: "abc", score: null, extra: [1, 2]}, "!error"], + [{s: null, vip: true, code: "b", price: 10, b: 2.5, score: 2.5, extra: {deep: {x: 1}}}, {b: 2.5, code: "b", extra: {deep: {x: 1}}, g: {k166: false, k173: "high"}, k165: false, k167: false, k168: -0.5, k169: true, k171: -0.5, lines: [{k160: 2}, {k160: 0.25}, {k160: 0}, {k160: 0}], m: {k170: false}, price: 10, res: {k172: true}, score: 2.5, vip: true}], + ], +} + +{ + name: "ga018: 5 nodes, switch, loop table, table, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["((vip ?? false))", "endsWith(((price ?? -1) >= 10 ? (items ?? [])[0].tag ?? 'none' : ((vip ?? false) ? (code ?? 'none') : (s ?? '?'))), 'x')", "string(2.25 < (score ?? 0)) == 'x'", ""]}, + {table: "t2", inputField: "items", executionMode: "loop", inputs: ["qty", "tag", "(0.5)"], outputs: ["k174", "k175"], outputPath: "res", rules: [ + ["$ > -1 and $ < 9", "'silver', 'bronze'", "[10..20)", "'mid'", "''"], + ["", "''", "< 100", "'high'", "(tag ?? '?')"], + ["", "", "", "'mid'", "'low'"], + ]}, + {table: "t3", inputs: ["len('none') % 7", "string((price ?? -1) < (b ?? 0))"], outputs: ["k176", "k177"], rules: [ + ["", "", "true", "(b ?? 0) * (score ?? b ?? 0) - (score ?? -1) % 7"], + ["not(5)", "'x'", "false", "((true) ? (price ?? 0) : len((code ?? '?'))) + 3"], + ]}, + {expression: "e4", passThrough: true, fields: { + k178: "max([10 + 2, 3 + min([(score ?? -1), (score ?? -1)])])", + k179: "s ?? s", + }}, + {table: "t5", inputs: ["`${(b ?? 0)}-${(code ?? '?')}`", "vip", "price"], outputs: ["k180"], outputPath: "out", rules: [ + ["'x', 'bronze'", "", "", "0"], + ["not('silver')", "$ == true", "[50..100]", "0.25"], + ["", "", "", "0"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> t2", + "s1:1 -> t3", + "s1:2 -> e4", + "s1:0 -> t5", + "s1:3 -> output", + "t2 -> output", + "t3 -> output", + "e4 -> output", + "t5 -> output", + ], + }, + cases: [ + [{code: "x", b: 10, price: 99, vip: true, score: 10, items: [{price: -25, qty: 0.1, tag: "a"}, {price: 7, qty: -1}], s: "gold"}, {out: {k180: 0}, res: [{k174: "mid", k175: "low"}, {k174: "mid", k175: "low"}]}], + [{code: "zz", b: 101, vip: false, score: 0.5, items: [{price: 1, qty: 19.99}, {price: -1, qty: 2, tag: "x"}], s: ""}, {b: 101, code: "zz", items: [{price: 1, qty: 19.99}, {price: -1, qty: 2, tag: "x"}], s: "", score: 0.5, vip: false}], + [{code: "x", b: 50, price: 11, vip: null, score: 19.99, items: [{tag: "zz"}, {price: 5, qty: -25, tag: "a"}], s: "Gold"}, {b: 50, code: "x", items: [{tag: "zz"}, {price: 5, qty: -25, tag: "a"}], price: 11, s: "Gold", score: 19.99}], + [{code: "gold ", b: 50, price: 21, vip: false, score: 1000000000000000000000, items: [{qty: 0.5, tag: ""}], s: "gold"}, {b: 50, code: "gold ", items: [{qty: 0.5, tag: ""}], price: 21, s: "gold", score: 1000000000000000000000, vip: false}], + [{code: {t: "x"}, b: 99, price: null, vip: true, score: 100, items: [{price: null, qty: 11, tag: "Gold"}, {price: 5, qty: 0.1, tag: "silver"}], s: true}, {out: {k180: 0}, res: [{k174: "mid", k175: "low"}, {k174: "mid", k175: "low"}]}], + [{b: 3, price: 0, vip: true, score: 7, items: [{price: 1000000000000000000000, qty: 19.99, tag: "Gold"}], s: null}, {out: {k180: 0}, res: [{k174: "mid", k175: "low"}]}], + [{code: "", b: 0, price: 100, vip: true, score: 11, items: [{price: 19.99, qty: 2.5, tag: ""}], s: "b"}, {out: {k180: 0}, res: [{k174: "high", k175: ""}]}], + [{code: "a", b: 1000000000000000000000, price: 18, items: [{qty: 5, tag: "Gold"}, {price: 21, qty: -1}, {price: null, qty: -0.1, tag: "bronze"}, {price: 3, qty: 10, tag: "bronze"}], s: null}, {b: 1000000000000000000000, code: "a", items: [{qty: 5, tag: "Gold"}, {price: 21, qty: -1}, {price: null, qty: -0.1, tag: "bronze"}, {price: 3, qty: 10, tag: "bronze"}], price: 18}], + [{code: "bronze", b: 9, price: 18, vip: true, s: "a"}, "!error"], + [{code: null, b: 18, price: 1000, vip: false, score: 11, items: [{price: 0.1, qty: 1000, tag: "b"}, {price: 0, qty: 18, tag: "bronze"}], s: "zz"}, {b: 18, items: [{price: 0.1, qty: 1000, tag: "b"}, {price: 0, qty: 18, tag: "bronze"}], price: 1000, s: "zz", score: 11, vip: false}], + [{code: "bronze", b: [1], price: 21, vip: null, score: 3, items: [], s: "b"}, {b: [1], code: "bronze", items: [], price: 21, s: "b", score: 3}], + [{code: "x", b: -1, price: 100, vip: false, score: 18, items: [{price: 21, qty: 5, tag: "b"}, {price: 92, qty: -1, tag: "b"}], s: "zz"}, {b: -1, code: "x", items: [{price: 21, qty: 5, tag: "b"}, {price: 92, qty: -1, tag: "b"}], price: 100, s: "zz", score: 18, vip: false}], + [{code: "x", b: 10, price: -0.1, vip: false, score: 5, items: [{price: -25, qty: null, tag: null}, {price: 11, qty: 99, tag: "zz"}, {price: 2, qty: 0.5, tag: "x"}], s: "bronze"}, {b: 10, code: "x", items: [{price: -25, qty: null, tag: null}, {price: 11, qty: 99, tag: "zz"}, {price: 2, qty: 0.5, tag: "x"}], price: -0.1, s: "bronze", score: 5, vip: false}], + [{code: "", b: 7, vip: false, score: 50, items: [], s: "b"}, {b: 7, code: "", items: [], s: "b", score: 50, vip: false}], + [{code: "bronze", b: 1000, price: 21, score: 2.5, items: [{price: -1, qty: 21, tag: "a"}, {tag: 5}], s: null}, {b: 1000, code: "bronze", items: [{price: -1, qty: 21, tag: "a"}, {tag: 5}], price: 21, score: 2.5}], + [{code: "zz", b: 1, price: 3, vip: false, score: 5, items: [{price: 7, qty: 3}, {price: 0.5, qty: 21, tag: "x"}], s: "x"}, {k176: true, k177: 0}], + [{code: "zz", b: null, price: 99, vip: false, score: 5, items: null, s: "a"}, {code: "zz", price: 99, s: "a", score: 5, vip: false}], + [{code: null, b: 99, price: 101, vip: false, items: [{price: 2, qty: null, tag: "gold "}, {price: -1, qty: 100, tag: "bronze"}]}, {b: 99, items: [{price: 2, qty: null, tag: "gold "}, {price: -1, qty: 100, tag: "bronze"}], price: 101, vip: false}], + [{code: "Gold", b: 1000000000000000000000, price: 0, vip: false, score: 0, items: [{price: 11, qty: 10, tag: "a"}], s: null}, {b: 1000000000000000000000, code: "Gold", items: [{price: 11, qty: 10, tag: "a"}], price: 0, score: 0, vip: false}], + [{code: "zz", b: 18, price: true, vip: false, score: 18, items: [{price: 100, tag: null}, {price: null, qty: -0.1, tag: "gold "}], s: "gold "}, {b: 18, code: "zz", items: [{price: 100, tag: null}, {price: null, qty: -0.1, tag: "gold "}], price: true, s: "gold ", score: 18, vip: false}], + [{code: "silver", b: 14, price: 11, vip: true, score: 21, items: [{price: 7, qty: 11, tag: ""}, {price: 101, qty: 18, tag: "b"}, {price: 2, tag: "a"}], s: "x"}, {out: {k180: 0}, res: [{k174: "high", k175: ""}, {k174: "mid", k175: "low"}, {k174: "mid", k175: "low"}]}], + [{code: "a", b: 21, price: 0.5, vip: true, score: 101, items: [{price: 101, qty: 21, tag: "Gold"}, {price: 19.99, qty: -0.1, tag: "Gold"}, {price: 2.5, qty: 39, tag: "x"}], s: {t: "x"}}, {out: {k180: 0}, res: [{k174: "mid", k175: "low"}, {k174: "mid", k175: "low"}, {k174: "mid", k175: "low"}]}], + [{code: "gold ", b: 19.99, price: 32, vip: false, score: -25, items: [{price: 0.1, qty: 1, tag: ""}], s: "zz", extra: 1}, {b: 19.99, code: "gold ", extra: 1, items: [{price: 0.1, qty: 1, tag: ""}], price: 32, s: "zz", score: -25, vip: false}], + ], +} + +{ + name: "ga019: 6 nodes, table, table, switch, switch, expr, table", + graph: { + nodes: [ + {table: "t1", inputs: ["n", "score"], outputs: ["k181", "k181"], passThrough: true, rules: [ + ["!= 50", "[0..10]", "`${(score ?? -1)}-${''}` + '' + 'none'", "'mid'"], + ["$ > 21 and $ < 22", "<= 22", "'mid'", "''"], + ["[50..100)", "(18..23)", "'high'", "'low'"], + ]}, + {table: "t2", inputs: ["((true ? (n ?? -1) : -4))", "vip"], outputs: ["k183", "k181"], rules: [ + [">= 10", "false", "false", "0"], + [">= 1", "true", "ceil((score ?? 1)) * sum(nums ?? []) < len('x')", "2"], + ["", "false", "true", "0.5"], + ["(50..51)", "$ == true", "true", "2"], + [">= 1", "null", "true", "10"], + ["", "", "false", "1"], + ]}, + {switch: "s3", when: ["(not ((score ?? -1) == 0.5)) or (true)", "((n ?? 1)) > ceil((0))", ""]}, + {switch: "s4", when: ["(vip ?? false)", "(k183 != null) or ((contains('A-1', 'x')) or (a != null))", "a == null", ""]}, + {expression: "e5", passThrough: true, fields: { + "m.k185": "((k181 ?? 1))", + k186: "0.5", + k187: "k181", + k188: "'A-1'", + }}, + {table: "t6", inputs: ["m.k185", "k183"], outputs: ["k189", "k190"], passThrough: true, outputPath: "res", rules: [ + ["< 10", "null", "false", "true"], + ["(21..26)", "$ == true", "true", "false"], + ["> 1", "false", "false", "true"], + ["18", "", "(true) or (k183)", "false"], + ["[21..26)", "true", "false", "(startsWith(string((k183 ?? false)), '')) and ((k183 ?? false))"], + ["> 1", "false", "false", "(not (10 == (k187 ?? -1))) or (true)"], + ["", "", "true", "false"], + ]}, + ], + edges: [ + "input -> t1", + "input -> t2", + "input -> s3", + "t2 -> s4", + "s3:0 -> s4", + "t2 -> e5", + "s4:2 -> e5", + "e5 -> t6", + "t1 -> output", + "s3:2 -> output", + "s4:3 -> output", + "t6 -> output", + ], + }, + cases: [ + [{score: null, n: 1, vip: null, nums: [1000000000000000000000, 21, 18, -25, 0]}, {k181: 10, k183: true, k186: 0.5, k187: 10, k188: "A-1", m: {k185: 10}, n: 1, nums: [1000000000000000000000, 21, 18, -25, 0], res: {k189: true, k190: false}}], + [{score: 2.5, n: 1000, vip: false, nums: [0.1, 1], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, k181: "mid", k183: false, k186: 0.5, k187: 0, k188: "A-1", m: {k185: 0}, n: 1000, nums: [0.1, 1], res: {k189: true, k190: false}, score: 2.5, vip: false}], + [{n: 2, vip: true, nums: [1000, 2.5, 0.1]}, {k181: 2, k183: false, k186: 0.5, k187: 2, k188: "A-1", m: {k185: 2}, n: 2, nums: [1000, 2.5, 0.1], res: {k189: false, k190: true}, vip: true}], + [{score: null, n: 21, vip: true, nums: [2.5]}, {k181: 2, k183: false, k186: 0.5, k187: 2, k188: "A-1", m: {k185: 2}, n: 21, nums: [2.5], res: {k189: false, k190: true}, vip: true}], + [{score: 7, n: -0.1, nums: [50, 1000000000000000000000, 36]}, {k181: "mid", k183: false, k186: 0.5, k187: 1, k188: "A-1", m: {k185: 1}, n: -0.1, nums: [50, 1000000000000000000000, 36], res: {k189: true, k190: false}, score: 7}], + [{score: 0, n: -0.1, vip: true, nums: [10]}, {k181: "mid", k183: false, k186: 0.5, k187: 1, k188: "A-1", m: {k185: 1}, n: -0.1, nums: [10], res: {k189: true, k190: false}, score: 0, vip: true}], + [{score: 7, n: null, vip: false, nums: [1000000000000000000000, 3, 1, 19.99, -25]}, {k181: "mid", k183: true, k186: 0.5, k187: 0.5, k188: "A-1", m: {k185: 0.5}, nums: [1000000000000000000000, 3, 1, 19.99, -25], res: {k189: true, k190: false}, score: 7, vip: false}], + [{score: 10, n: 50, vip: true, nums: [1000, -1, 10]}, {k181: 2, k183: false, k186: 0.5, k187: 2, k188: "A-1", m: {k185: 2}, n: 50, nums: [1000, -1, 10], res: {k189: false, k190: true}, score: 10, vip: true}], + [{score: -0.1, n: 7, vip: true, nums: []}, {k181: 2, k183: true, k186: 0.5, k187: 2, k188: "A-1", m: {k185: 2}, n: 7, nums: [], res: {k189: true, k190: false}, score: -0.1, vip: true}], + [{score: 1, n: 11, vip: true, nums: [3, 1000000000000000000000]}, {k181: "mid", k183: false, k186: 0.5, k187: 2, k188: "A-1", m: {k185: 2}, n: 11, nums: [3, 1000000000000000000000], res: {k189: false, k190: true}, score: 1, vip: true}], + [{score: 101, n: 7, vip: true, nums: []}, {k181: 2, k183: true, k186: 0.5, k187: 2, k188: "A-1", m: {k185: 2}, n: 7, nums: [], res: {k189: true, k190: false}, score: 101, vip: true}], + [{score: -25, n: 0.1, vip: false, nums: [50, 0.5, 7]}, {k181: 0.5, k183: true, k186: 0.5, k187: 0.5, k188: "A-1", m: {k185: 0.5}, n: 0.1, nums: [50, 0.5, 7], res: {k189: true, k190: false}, score: -25, vip: false}], + [{score: 99, n: 2.5, vip: true, nums: [101, 3, 0.5, 11, 1000]}, {k181: 2, k183: false, k186: 0.5, k187: 2, k188: "A-1", m: {k185: 2}, n: 2.5, nums: [101, 3, 0.5, 11, 1000], res: {k189: false, k190: true}, score: 99, vip: true}], + [{score: -1, vip: false, nums: [0.5, 19.99, 99], extra: "e"}, {extra: "e", k181: 0.5, k183: true, k186: 0.5, k187: 0.5, k188: "A-1", m: {k185: 0.5}, nums: [0.5, 19.99, 99], res: {k189: true, k190: false}, score: -1, vip: false}], + [{score: null, n: 0.1, nums: [100, 1000000000000000000000]}, {k181: 1, k183: false, k186: 0.5, k187: 1, k188: "A-1", m: {k185: 1}, n: 0.1, nums: [100, 1000000000000000000000], res: {k189: true, k190: false}}], + [{score: 1000000000000000000000, n: 19.99, nums: []}, {k181: 10, k183: true, k186: 0.5, k187: 10, k188: "A-1", m: {k185: 10}, n: 19.99, nums: [], res: {k189: true, k190: false}, score: 1000000000000000000000}], + [{n: 7, vip: false, nums: [5, 0.1, -1, 7, 101]}, {k181: 0.5, k183: true, k186: 0.5, k187: 0.5, k188: "A-1", m: {k185: 0.5}, n: 7, nums: [5, 0.1, -1, 7, 101], res: {k189: true, k190: false}, vip: false}], + ], +} + +{ + name: "ga020: 7 nodes, loop expr, expr, table*, expr, expr, table, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + k191: "tag ?? qty", + "g.k192": "(qty ?? 0)", + k193: "(price ?? -1) * ((true) or (false) ? -((price ?? -1)) : max([qty, (qty ?? 1)]))", + "g.k194": "((price ?? 0)) + (true ? 0 : (qty ?? 0)) >= (price ?? $.k191 ?? 0)", + }}, + {expression: "e2", outputPath: "out", fields: { + k195: "null", + }}, + {table: "t3", hit: "collect", inputField: "cust", inputs: ["age", "age", "active"], outputs: ["res.k196", "k195"], outputPath: "lines", rules: [ + ["< 21", "> 1", "null", "true", "false"], + [">= 5", "", "null", "false", "true"], + ["18", "<= 26", "false", "false", "`n=${2}-${''}` == 'silver'"], + ]}, + {expression: "e4", passThrough: true, outputPath: "out", fields: { + "g.k198": "`${-4}-${'x'}`", + k199: "null", + }}, + {expression: "e5", fields: { + k195: "'A-1'", + k201: "-(0)", + k202: "string(($.k201 ?? 0) <= $.k201 * 100)", + k203: "not (ceil(1) in [1..100])", + }}, + {table: "t6", inputs: ["string(false) + '-' + string(false)", "(min([2.25, 100]))", "'x'"], outputs: ["k195", "res.k205"], outputPath: "res", rules: [ + ["startsWith($, 'x')", "0, 1", "'x'", "false", "-5"], + ["'gold'", ">= 0", "$ != 'gold'", "not (-(1) in [1..100])", "100"], + ["not('')", ">= 10", "", "true", "100"], + ["$ != ''", "!= 100", "$ != 'silver'", "true", "-4"], + ["not('a')", "-1", "$ != ''", "('' in ['gold', 'silver', 'a']) or (true)", "100"], + ]}, + {expression: "e7", outputPath: "res", fields: { + "g.k192": "res.k195 ?? res.res.k205", + k207: "res.res.k205 ?? res.k195", + k208: "abs((res.res.k205))", + "m.k209": "`v${res.res.k205}-${'gold'}`", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> t3", + "e1 -> e4", + "e2 -> e5", + "e2 -> t6", + "t6 -> e7", + "t3 -> output", + "e4 -> output", + "e5 -> output", + "e7 -> output", + ], + }, + cases: [ + [{b: 1000000000000000000000, vip: false, cust: {age: 0.1, tier: "Gold", active: null}, a: {v: 1}, items: [{price: 19.99, tag: null}, {price: 101, qty: 21, tag: "a"}, {price: 51, qty: [1], tag: "gold "}], score: 0.1}, {k195: "A-1", k201: -0, k202: "true", k203: false, lines: [], out: {g: {k198: "-4-x"}, k199: null}, res: {g: {k192: true}, k207: -4, k208: 4, m: {k209: "v-4-gold"}}}], + [{b: 11, vip: 1, cust: 5, a: 7, items: [{price: 1000000000000000000000, qty: 0.1, tag: "zz"}, {price: 19.99, qty: 18, tag: ""}, {price: 0.5, qty: 2.5}, {price: 62, qty: -0.1, tag: ["gold"]}], price: 7, score: 1000000000000000000000}, "!error"], + [{b: 1, vip: false, cust: {age: 21, active: true}, items: [], price: 99, score: 101}, {k195: "A-1", k201: -0, k202: "true", k203: false, lines: [], out: {g: {k198: "-4-x"}, k199: null}, res: {g: {k192: true}, k207: -4, k208: 4, m: {k209: "v-4-gold"}}}], + [{b: 2, vip: true, cust: null, a: "abc", items: [{price: -0.1, qty: -1, tag: "zz"}, {price: 99, qty: -1, tag: {t: "x"}}], price: 99, score: 101}, {k195: "A-1", k201: -0, k202: "true", k203: false, lines: [], out: {g: {k198: "-4-x"}, k199: null}, res: {g: {k192: true}, k207: -4, k208: 4, m: {k209: "v-4-gold"}}}], + [{vip: false, cust: {age: 5, tier: "gold ", active: false}, a: [1], items: [{price: 0.5, qty: 14, tag: "x"}, {price: null, qty: 101, tag: "Gold"}], price: 2, score: 3}, "!error"], + [{b: 0.5, vip: true, cust: {tier: "b", active: true}, a: null, items: [{price: 1000000000000000000000, qty: 21, tag: "silver"}, {price: true, qty: 101, tag: ""}, {price: 0, tag: "silver"}], price: 1000}, "!error"], + [{b: 10, vip: false, cust: {age: 72, tier: "", active: true}, items: [], price: null, score: 1000000000000000000000}, {k195: "A-1", k201: -0, k202: "true", k203: false, lines: [], out: {g: {k198: "-4-x"}, k199: null}, res: {g: {k192: true}, k207: -4, k208: 4, m: {k209: "v-4-gold"}}}], + [{b: 100, vip: true, cust: {age: -0.1, tier: null, active: true}, a: 1000000000000000000000, items: [{price: 1, qty: 10, tag: "gold"}, {price: -25, tag: ""}], score: 1000000000000000000000, extra: "e"}, {k195: "A-1", k201: -0, k202: "true", k203: false, lines: [], out: {g: {k198: "-4-x"}, k199: null}, res: {g: {k192: true}, k207: -4, k208: 4, m: {k209: "v-4-gold"}}}], + [{b: 0.1, cust: {age: 1000000000000000000000, tier: {t: "x"}, active: false}, a: {v: 1}, items: [], price: 2, extra: "e"}, {k195: "A-1", k201: -0, k202: "true", k203: false, lines: [], out: {g: {k198: "-4-x"}, k199: null}, res: {g: {k192: true}, k207: -4, k208: 4, m: {k209: "v-4-gold"}}}], + [{b: 3, vip: null, cust: {age: 100, tier: "x", active: true}, a: -0.1, items: [{price: 99, qty: 5}, {price: 3, tag: "gold "}, {qty: -0.1, tag: "b"}], price: 36, score: 99}, "!error"], + [{b: 99, vip: true, cust: {age: {v: 1}, tier: "b", active: false}, a: -0.1, items: [], price: 99, score: {v: 1}}, {k195: "A-1", k201: -0, k202: "true", k203: false, lines: [], out: {g: {k198: "-4-x"}, k199: null}, res: {g: {k192: true}, k207: -4, k208: 4, m: {k209: "v-4-gold"}}}], + [{b: 1, vip: true, cust: {age: 50, active: false}, a: 100, items: [{price: 10, qty: 99, tag: "Gold"}, {price: 11, qty: -25, tag: "gold "}], price: -1, score: 7}, {k195: "A-1", k201: -0, k202: "true", k203: false, lines: [], out: {g: {k198: "-4-x"}, k199: null}, res: {g: {k192: true}, k207: -4, k208: 4, m: {k209: "v-4-gold"}}}], + ], +} + +{ + name: "ga021: 7 nodes, table, table, expr, table, switch, switch, table", + graph: { + nodes: [ + {table: "t1", inputs: ["max([2.25, (score ?? 1)]) * abs((score ?? 1))", "score", "s"], outputs: ["k210"], rules: [ + ["null", "null", "", "-5"], + ["[21..26)", ">= 50", "not('')", "score"], + ["", "", "", "-5"], + ]}, + {table: "t2", inputs: ["'x' + ' ' + 'A-1' + ':' + string(0)", "-(floor(0))"], outputs: ["k211", "k212"], rules: [ + ["$ != ''", "$ > 0 and $ < 50", "0.25", "(k210 ?? 0) - -((k210 ?? -1)) + (false ? (k210 ?? -1) : (0.5) / 10)"], + ["", "not(50)", "-5", "k210"], + ["startsWith($, 'x')", "5", "2", "10"], + ["startsWith($, '')", "null", "100", "2"], + ["'', 'gold'", "!= 18", "1", "100"], + ["'x', 'bronze'", "<= 51", "2", "max([-((2)), (k210 ?? 1)])"], + ]}, + {expression: "e3", fields: { + k213: "k210 ?? k210", + k214: "len('none')", + "m.k215": "'A-1'", + }}, + {table: "t4", inputs: ["((k214 ?? 1) % 3)"], outputs: ["k216"], outputPath: "lines", rules: [ + ["", "(m.k215 ?? '') + ':' + string(k214 != null)"], + ["0, 5", "m.k215"], + ["100, 150", "(string(false) in ['gold', 'silver', 'a'] ? 'gold' : string(false))"], + ["", "'low'"], + ]}, + {switch: "s5", when: ["startsWith((m.k215 ?? '?'), 'x')"]}, + {switch: "s6", when: ["false", "(k210 < (k214 ?? 0) ? '' : (m.k215 ?? 'none')) != 'silver'", "not ((true ? (m.k215 ?? '?') : m.k215) in ['gold', 'silver', 'a'])"]}, + {table: "t7", inputs: ["s", "s", "-((score ?? -1) - (score ?? 1))"], outputs: ["k217", "m.k218"], rules: [ + ["'x'", "$ != 'gold'", "", "false", "false"], + ["", "not('x')", "<= 71", "string(true) + '-' + (s ?? '?') != 'gold'", "true"], + ["", "null", "(100..101)", "true", "true"], + ["", "", "", "true", "(0 + 0) >= 2.25"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> t2", + "t1 -> e3", + "e3 -> t4", + "e3 -> s5", + "t1 -> s5", + "e3 -> s6", + "t1 -> s6", + "input -> t7", + "t2 -> output", + "t4 -> output", + "s5:0 -> output", + "s6:0 -> output", + "s6:2 -> output", + "t7 -> output", + ], + }, + cases: [ + [{s: "gold ", nums: [5, 3, 0.1, 0.1, 19.99], score: 0.1}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: null, nums: null, score: null}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "gold ", nums: [11, 21], score: 58}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{nums: null}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "silver", nums: [19.99, 5, -25], score: 0.1}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "gold", nums: [1000000000000000000000], score: -25, extra: 1}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: null, nums: [-25], score: 11}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "b", nums: [0.5], score: 7}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{nums: [0, 0.1, 0, 99, 7], score: 50}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "b", nums: null, score: 10, extra: 1}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "", nums: [0, -1, 7, 0.5, 0.5], score: -0.1}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "silver", nums: [61, 99, 3], score: 71}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "x", nums: [50, 46], score: 21, extra: {deep: {x: 1}}}, {k217: false, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "gold ", nums: [-25], score: 2}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{nums: [0.1], score: 7}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "Gold", nums: [3, 100, -0.1, 5, 72], score: 7}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "silver", nums: [5], score: 0.5}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: "", nums: [2.5, 2, 0.5, -25, 11], score: 101}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + [{s: null, nums: null, score: 3}, {k217: true, lines: {k216: "A-1:true"}, m: {k218: false}}], + ], +} + +{ + name: "ga022: 8 nodes, expr, expr, expr, expr, expr, expr, table, expr", + graph: { + nodes: [ + {expression: "e1", fields: { + k219: "(vip ?? false)", + }}, + {expression: "e2", fields: { + k220: "((k219 ?? false)) and (2 * 10 == 3 * 2)", + k221: "0 + (-(2)) / 2", + "res.k222": "`${3}-${'gold'}` + '-' + 'x' + '-' + 'none' + '' + '' + ':' + ''", + }}, + {expression: "e3", passThrough: true, fields: { + "m.k224": "a ?? code", + }}, + {expression: "e4", outputPath: "res", fields: { + k225: "(b ?? -1)", + }}, + {expression: "e5", passThrough: true, outputPath: "out", fields: { + k221: "(res.k225 ?? 0)", + "m.k227": "'none'", + "g.k228": "k219 ?? res.k225", + }}, + {expression: "e6", fields: { + "res.k229": "floor(($nodes.e5.k221 ?? -1))", + }}, + {table: "t7", inputs: ["1", "string('' != 'x')"], outputs: ["k230"], rules: [ + ["5, 6", "not('silver')", "true"], + ["", "", "false"], + ["", "null", "true"], + ]}, + {expression: "e8", fields: { + k231: "res.k222 == null", + k232: "((k221 ?? 1) < k221 ? len((res.k222 ?? '')) : (k221 ?? 1) * -4) != -(2.25) - (k221 ?? 1) + 100", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> e3", + "input -> e4", + "e4 -> e5", + "e1 -> e5", + "e5 -> e6", + "e1 -> t7", + "e2 -> e8", + "e3 -> output", + "e6 -> output", + "t7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{s: "silver", code: "gold", price: 1000, a: 100, vip: false}, {a: 100, code: "gold", k230: false, k231: false, k232: true, m: {k224: 100}, price: 1000, res: {k229: -1}, s: "silver", vip: false}], + [{s: "a", b: -0.1, price: 50, a: 5, vip: false, extra: "e"}, {a: 5, b: -0.1, extra: "e", k230: false, k231: false, k232: true, m: {k224: 5}, price: 50, res: {k229: -1}, s: "a", vip: false}], + [{s: "gold ", b: -25, code: "zz", price: 1000, a: 7}, {a: 7, b: -25, code: "zz", k230: false, k231: false, k232: true, m: {k224: 7}, price: 1000, res: {k229: -1}, s: "gold "}], + [{s: "b", b: 3, code: "x", price: 100, a: 50, vip: false, extra: 1}, {a: 50, b: 3, code: "x", extra: 1, k230: false, k231: false, k232: true, m: {k224: 50}, price: 100, res: {k229: -1}, s: "b", vip: false}], + [{b: 2.5, code: "x", a: -25, vip: false}, {a: -25, b: 2.5, code: "x", k230: false, k231: false, k232: true, m: {k224: -25}, res: {k229: -1}, vip: false}], + [{s: {t: "x"}, code: null, price: -0.1, a: 18, vip: null}, {a: 18, k230: false, k231: false, k232: true, m: {k224: 18}, price: -0.1, res: {k229: -1}, s: {t: "x"}}], + [{s: "bronze", b: true, code: "a", price: 0.1, a: 21, vip: false, extra: [1, 2]}, {a: 21, b: true, code: "a", extra: [1, 2], k230: false, k231: false, k232: true, m: {k224: 21}, price: 0.1, res: {k229: -1}, s: "bronze", vip: false}], + [{b: null, code: "b", price: 2, a: 0.5}, {a: 0.5, code: "b", k230: false, k231: false, k232: true, m: {k224: 0.5}, price: 2, res: {k229: -1}}], + [{s: "a", b: 100, code: "gold", price: 101, a: 10, vip: false, extra: {deep: {x: 1}}}, {a: 10, b: 100, code: "gold", extra: {deep: {x: 1}}, k230: false, k231: false, k232: true, m: {k224: 10}, price: 101, res: {k229: -1}, s: "a", vip: false}], + [{s: "x", b: 1, code: "Gold", price: -25, a: 10, vip: null}, {a: 10, b: 1, code: "Gold", k230: false, k231: false, k232: true, m: {k224: 10}, price: -25, res: {k229: -1}, s: "x"}], + [{s: "bronze", b: 5, code: "", price: 21, a: 19.99, vip: true}, {a: 19.99, b: 5, code: "", k230: false, k231: false, k232: true, m: {k224: 19.99}, price: 21, res: {k229: -1}, s: "bronze", vip: true}], + [{s: null, b: null, code: "gold ", price: -0.1, a: 50, vip: false}, {a: 50, code: "gold ", k230: false, k231: false, k232: true, m: {k224: 50}, price: -0.1, res: {k229: -1}, vip: false}], + ], +} + +{ + name: "ga023: 4 nodes, switch, expr, table, table", + graph: { + nodes: [ + {switch: "s1", when: ["((code ?? '') in ['gold', 'silver', 'a']) and ((0.5 != (a ?? -1)) and ((true)))", "b == null", ""]}, + {expression: "e2", outputPath: "o.p", fields: { + "res.k233": "(true ? (b ?? b ?? 0) : b % 3)", + "g.k234": "b ?? code", + k236: "a ?? n", + }}, + {table: "t3", inputs: ["code", "b", "n + (b ?? -1)"], outputs: ["k237"], outputPath: "o.p", rules: [ + ["", "50, 100", "not(100)", "false"], + ["'silver', 'bronze'", "> 10", "$ > 5 and $ < 15", "false"], + ]}, + {table: "t4", inputs: ["n", null], outputs: ["m.k238"], rules: [ + ["> 1", "", "ceil(((b ?? -1))) in [0..10]"], + ["(1..11)", "'gold'", "false"], + [">= 10", "5", "true"], + ["<= 15", "$ != null", "false"], + ["", "null", "true"], + ["", "", "true"], + ]}, + ], + edges: [ + "input -> s1", + "input -> e2", + "s1:2 -> t3", + "s1:1 -> t4", + "s1:0 -> output", + "e2 -> output", + "t3 -> output", + "t4 -> output", + ], + }, + cases: [ + [{n: 1000000000000000000000, a: 1, code: "bronze", b: 10}, {o: {p: {g: {k234: 10}, k236: 1, res: {k233: 10}}}}], + [{n: 114, a: 100, b: 5, extra: 1}, {o: {p: {g: {k234: 5}, k236: 100, res: {k233: 5}}}}], + [{n: 5, code: "gold", b: -25, extra: {deep: {x: 1}}}, {b: -25, code: "gold", extra: {deep: {x: 1}}, n: 5, o: {p: {g: {k234: -25}, k236: 5, res: {k233: -25}}}}], + [{n: 10, a: 11, code: "a", b: 11}, {a: 11, b: 11, code: "a", n: 10, o: {p: {g: {k234: 11}, k236: 11, res: {k233: 11}}}}], + [{n: 101, code: null, b: 0.5}, {o: {p: {g: {k234: 0.5}, k236: 101, res: {k233: 0.5}}}}], + [{n: 21, a: 1, code: "Gold", b: 1000000000000000000000}, {o: {p: {g: {k234: 1000000000000000000000}, k236: 1, res: {k233: 1000000000000000000000}}}}], + [{n: 2, a: 5, code: "zz", b: 1000}, {o: {p: {g: {k234: 1000}, k236: 5, res: {k233: 1000}}}}], + [{n: 3, a: 101, code: "bronze", b: 0.1}, {o: {p: {g: {k234: 0.1}, k236: 101, res: {k233: 0.1}}}}], + [{n: -0.1, a: 99, code: "b", b: 19.99}, {o: {p: {g: {k234: 19.99}, k236: 99, res: {k233: 19.99}}}}], + [{n: 2, a: 1, code: "", b: -0.1}, {o: {p: {g: {k234: -0.1}, k236: 1, res: {k233: -0.1}}}}], + [{code: "gold", b: 1000000000000000000000}, {b: 1000000000000000000000, code: "gold", o: {p: {g: {k234: 1000000000000000000000}, k236: null, res: {k233: 1000000000000000000000}}}}], + [{n: 21, a: 19.99, code: "silver", b: 1, extra: {deep: {x: 1}}}, {a: 19.99, b: 1, code: "silver", extra: {deep: {x: 1}}, n: 21, o: {p: {g: {k234: 1}, k236: 19.99, res: {k233: 1}}}}], + [{n: 1000, a: 1000, code: "silver", b: 100}, {a: 1000, b: 100, code: "silver", n: 1000, o: {p: {g: {k234: 100}, k236: 1000, res: {k233: 100}}}}], + [{n: null, a: 0, b: null}, {m: {k238: true}, o: {p: {g: {k234: null}, k236: 0, res: {k233: 0}}}}], + [{n: 100, a: 19.99, code: "zz", b: -25}, {o: {p: {g: {k234: -25}, k236: 19.99, res: {k233: -25}}}}], + [{n: 11, a: 1000, code: "gold ", b: null}, {m: {k238: false}, o: {p: {g: {k234: "gold "}, k236: 1000, res: {k233: 0}}}}], + [{n: 18, a: -0.1, code: "bronze", b: -0.1}, {o: {p: {g: {k234: -0.1}, k236: -0.1, res: {k233: -0.1}}}}], + ], +} + +{ + name: "ga024: 6 nodes, switch, expr, table, expr, table, expr", + graph: { + nodes: [ + {switch: "s1", when: ["not (((code ?? 'none') in ['gold', 'silver', 'a']))", "(((price ?? -1) in [1..100]) or ((false) and (true))) and (3 % 3 >= ceil(a))", ""]}, + {expression: "e2", fields: { + k239: "b ?? b", + k240: "'x'", + k241: "string(not (b <= (n ?? 0)))", + k242: "(a)", + }}, + {table: "t3", inputs: ["code"], outputs: ["k243"], rules: [ + ["null", "1"], + ["$ != 'silver'", "0"], + ["'x'", "0.25"], + ["", "(b ?? 0)"], + ["", "((price ?? n ?? 0)) / 4 * (n ?? 1) + abs((n ?? -1))"], + ["''", "0"], + ]}, + {expression: "e4", fields: { + k244: "'none'", + }}, + {table: "t5", inputs: ["code", "abs(1) * (2.25) / 3", "code"], outputs: ["k245"], rules: [ + ["", "[21..22]", "", "true"], + ["'', 'b'", "> 18", "", "false"], + ]}, + {expression: "e6", passThrough: true, fields: { + "g.k246": "(b) % 7 + min([(b ?? -1), (b ?? 0)])", + k247: "string(string(false) in ['gold', 'silver', 'a'])", + k248: "(2.25)", + }}, + ], + edges: [ + "input -> s1", + "s1:1 -> e2", + "s1:2 -> t3", + "t3 -> e4", + "s1:2 -> t5", + "input -> e6", + "s1:0 -> output", + "e2 -> output", + "e4 -> output", + "t5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{n: 1000, price: 10, b: null, code: null, a: 7}, "!error"], + [{n: 2.5, price: 19.99, b: 0.5, code: "Gold", a: 101}, {a: 101, b: 0.5, code: "Gold", g: {k246: 1.0}, k247: "false", k248: 2.25, n: 2.5, price: 19.99}], + [{n: -1, price: 100, b: null, code: "gold ", a: 2}, "!error"], + [{n: 2.5, price: null, b: 50, code: "zz", a: 11}, {a: 11, b: 50, code: "zz", g: {k246: 51}, k247: "false", k248: 2.25, n: 2.5}], + [{n: 11, price: null, b: 1000000000000000000000, code: "bronze", a: 2.5}, {a: 2.5, b: 1000000000000000000000, code: "bronze", g: {k246: 1000000000000000000006}, k247: "false", k248: 2.25, n: 11}], + [{n: 7, price: 100, b: -25, code: "x", a: 5}, {a: 5, b: -25, code: "x", g: {k246: -29}, k247: "false", k248: 2.25, n: 7, price: 100}], + [{n: 0.5, price: 50, b: 2, a: null}, {b: 2, g: {k246: 4}, k247: "false", k248: 2.25, n: 0.5, price: 50}], + [{n: 2, price: 0.5, b: 2, code: "gold", a: 7}, {a: 7, b: 2, code: "gold", g: {k246: 4}, k244: "none", k247: "false", k248: 2.25, n: 2, price: 0.5}], + [{n: 1000000000000000000000, b: 104, code: "Gold", a: 7}, {a: 7, b: 104, code: "Gold", g: {k246: 110}, k247: "false", k248: 2.25, n: 1000000000000000000000}], + [{n: -25, price: 1, b: 1, code: "gold ", a: 99, extra: {deep: {x: 1}}}, {a: 99, b: 1, code: "gold ", extra: {deep: {x: 1}}, g: {k246: 2}, k247: "false", k248: 2.25, n: -25, price: 1}], + [{n: 7, price: 1000, b: -25, code: "Gold", a: 1000, extra: "e"}, {a: 1000, b: -25, code: "Gold", extra: "e", g: {k246: -29}, k247: "false", k248: 2.25, n: 7, price: 1000}], + [{n: null, b: 100, code: "zz", a: 0.1}, {a: 0.1, b: 100, code: "zz", g: {k246: 102}, k247: "false", k248: 2.25}], + [{n: 0.5, price: 10, b: 2, code: "x", a: 0.1}, {a: 0.1, b: 2, code: "x", g: {k246: 4}, k247: "false", k248: 2.25, n: 0.5, price: 10}], + [{n: -25, price: null, b: 101, code: null, a: 1000}, {a: 1000, b: 101, g: {k246: 104}, k247: "false", k248: 2.25, n: -25}], + ], +} + +{ + name: "ga025: 5 nodes, switch, table*, table, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["((not ((vip ?? false))) or (a == null)) and (((price ?? -1)) / 4 >= len('none'))", ""]}, + {table: "t2", hit: "collect", inputs: ["((100))"], outputs: ["g.k249", "g.k249"], passThrough: true, outputPath: "lines", rules: [ + ["> 10", "'A-1' + '' + lower('none')", "10"], + ["", "'low'", "1"], + ["10", "(true ? (true ? 'A-1' : '') + '-' + string(false) : (not ((vip ?? false)) ? (true ? 'gold' : 'x') : string(price)))", "0"], + ]}, + {table: "t3", inputs: ["(floor(1)) / 2", "string(((vip ?? false)) or (true))", "vip", null], outputs: ["m.k251"], rules: [ + ["$ > 0 and $ < 1", "$ != ''", "false", "", "1"], + ["50, 100", "null", "", "", "10"], + ["", "", "", "", "2"], + ]}, + {expression: "e4", outputPath: "res", fields: { + k252: "score ?? score", + k253: "'none'", + }}, + {table: "t5", inputs: ["string((price ?? 1) > (price ?? -1))", "price"], outputs: ["k254", "k255"], rules: [ + ["not('silver')", "null", "false", "'gold'"], + ["", "< 10", "true", "'gold'"], + ["not('x')", "$ > -1 and $ < 49", "(false ? (price ?? 1) : (score ?? 1)) + -(1) < (score ?? 0)", "'low'"], + ["''", "not(18)", "contains('A-1', 'x')", "''"], + ["not('a')", "", "false", "string('none' == 'silver') + ' ' + 'A-1'"], + ["'gold', 'bronze'", "-1, 9", "false", "'gold'"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> t2", + "input -> t3", + "input -> e4", + "input -> t5", + "s1:1 -> output", + "t2 -> output", + "t3 -> output", + "e4 -> output", + "t5 -> output", + ], + }, + cases: [ + [{score: null, vip: false, price: 11}, {m: {k251: 1}, price: 11, res: {k252: null, k253: "none"}, vip: false}], + [{score: 0.1, vip: true, price: 99}, {lines: [{g: {k249: 10}}, {g: {k249: 1}}], m: {k251: 2}, price: 99, res: {k252: 0.1, k253: "none"}, score: 0.1, vip: true}], + [{score: 2, vip: true, price: 5}, {k254: true, k255: "gold", m: {k251: 2}, price: 5, res: {k252: 2, k253: "none"}, score: 2, vip: true}], + [{score: 3, vip: true, price: 2}, {k254: true, k255: "gold", m: {k251: 2}, price: 2, res: {k252: 3, k253: "none"}, score: 3, vip: true}], + [{score: 99, vip: false, price: 1000}, {lines: [{g: {k249: 10}}, {g: {k249: 1}}], m: {k251: 1}, price: 1000, res: {k252: 99, k253: "none"}, score: 99, vip: false}], + [{score: -0.1, vip: false, price: 5}, {k254: true, k255: "gold", m: {k251: 1}, price: 5, res: {k252: -0.1, k253: "none"}, score: -0.1, vip: false}], + [{score: null, vip: true, price: true}, {m: {k251: 2}, price: true, res: {k252: null, k253: "none"}, vip: true}], + [{score: 21, vip: true, price: -1}, {k254: true, k255: "gold", m: {k251: 2}, price: -1, res: {k252: 21, k253: "none"}, score: 21, vip: true}], + [{score: -1, vip: true, price: 7}, {k254: true, k255: "gold", m: {k251: 2}, price: 7, res: {k252: -1, k253: "none"}, score: -1, vip: true}], + [{score: 18, vip: true, price: 18, extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, lines: [{g: {k249: 10}}, {g: {k249: 1}}], m: {k251: 2}, price: 18, res: {k252: 18, k253: "none"}, score: 18, vip: true}], + [{score: 19.99, vip: true}, {m: {k251: 2}, res: {k252: 19.99, k253: "none"}, score: 19.99, vip: true}], + [{score: 3, vip: false, price: 1000}, {lines: [{g: {k249: 10}}, {g: {k249: 1}}], m: {k251: 1}, price: 1000, res: {k252: 3, k253: "none"}, score: 3, vip: false}], + [{score: 5, vip: null, price: 1}, {k254: true, k255: "gold", m: {k251: 2}, price: 1, res: {k252: 5, k253: "none"}, score: 5}], + [{score: 100, vip: true, price: 21}, {lines: [{g: {k249: 10}}, {g: {k249: 1}}], m: {k251: 2}, price: 21, res: {k252: 100, k253: "none"}, score: 100, vip: true}], + [{score: 99, vip: false, price: 2.5}, {k254: true, k255: "gold", m: {k251: 1}, price: 2.5, res: {k252: 99, k253: "none"}, score: 99, vip: false}], + [{score: 11, vip: false, price: -25}, {k254: true, k255: "gold", m: {k251: 1}, price: -25, res: {k252: 11, k253: "none"}, score: 11, vip: false}], + [{score: 2, vip: null, price: 18}, {lines: [{g: {k249: 10}}, {g: {k249: 1}}], m: {k251: 2}, price: 18, res: {k252: 2, k253: "none"}, score: 2}], + ], +} + +{ + name: "ga026: 6 nodes, table*, switch*, expr, expr, table, table*", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["n"], outputs: ["k256[]", "k257"], passThrough: true, outputPath: "res", rules: [ + [">= 50", "(score ?? -1)", "'mid'"], + ["(50..51)", "1", "(code ?? '?')"], + ["", "0.25", "'gold'"], + ["<= 150", "2", "'gold'"], + ["[5..15)", "0.25", "'low'"], + ["", "1", "string(len(items ?? []))"], + ]}, + {switch: "s2", hit: "collect", when: ["((a ?? 0)) + (n ?? 1) * score in [-5..5]", ""]}, + {expression: "e3", fields: { + k257: "code ?? code", + k259: "2.25 <= 3", + k260: "code ?? $.k259", + }}, + {expression: "e4", fields: { + k261: "a * min([(a ?? -1), score]) <= (score ?? a ?? 0)", + k262: "a ?? vip", + }}, + {table: "t5", inputs: ["vip", "code"], outputs: ["k263", "k264"], rules: [ + ["false", "", "10", "'low'"], + ["false", "", "0", "code"], + ["false", "", "0", "''"], + ["true", "not('x')", "len('none' + '-' + string(3))", "'low'"], + ["", "", "2", "''"], + ]}, + {table: "t6", hit: "collect", inputs: ["(0 ?? k262 ?? 0)", "k261", "`${0.5}-${'none'}`", null], outputs: ["k265", "k266"], outputPath: "res", rules: [ + ["[10..15]", "true", "not('x')", "", "false", "(((0.5)))"], + ["not(5)", "$ == true", "", "null", "true", "1"], + ["", "", "", "", "false", "0.25"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> s2", + "s2:0 -> e3", + "s2:1 -> e4", + "s2:0 -> e4", + "e4 -> t5", + "s2:0 -> t5", + "e4 -> t6", + "e3 -> output", + "t5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{code: "gold", vip: false, items: [], score: -1, flag: false, a: 50, n: null}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "Gold", vip: true, items: [{price: 2.5, qty: 11, tag: "zz"}], score: 2.5, flag: false, a: 19.99, n: 28}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: null, vip: true, items: [{price: null, qty: 19.99, tag: "Gold"}, {price: null, tag: "a"}, {price: 1000, qty: 1000, tag: "a"}, {price: 19.99, qty: -25, tag: "zz"}], score: 10, flag: false, a: 18, n: 2.5, extra: {deep: {x: 1}}}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "silver", vip: true, items: [{price: -25, qty: null, tag: "silver"}], score: 21, flag: false, a: 2.5, n: 21}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "gold", vip: null, items: [{qty: 0.1, tag: "a"}], score: 18, flag: false, a: 78, n: 101}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "gold", vip: false, items: [], score: -1, flag: true, a: 3, n: 2.5}, {k257: "gold", k259: true, k260: "gold", k263: 10, k264: "low", res: [{k265: false, k266: 0.25}]}], + [{code: "zz", vip: false, items: [], score: 0, flag: false, a: null, n: 1}, "!error"], + [{code: "b", vip: true, items: [{price: 1, tag: "Gold"}, {price: 18, qty: 18, tag: ""}], score: 21, flag: true, a: 65, n: 19.99}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "Gold", vip: true, items: [{price: 21, tag: "b"}, {price: 10, qty: 0, tag: "zz"}, {price: 18, qty: 27, tag: "zz"}, {price: 99, qty: 99, tag: "b"}], score: 21, flag: false, a: 0.1, n: 0.1}, {k257: "Gold", k259: true, k260: "Gold", k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "silver", items: [{price: 1000000000000000000000, qty: 10, tag: "x"}], score: 2.5, flag: true, a: 2.5}, {k257: "silver", k259: true, k260: "silver", k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: null, vip: false, items: [{price: -25, qty: 1, tag: "a"}, {price: -0.1, qty: 7, tag: "zz"}, {price: 11, qty: 3, tag: "silver"}, {price: 19.99, qty: 5, tag: "x"}], score: 0.5, flag: true, a: 99, n: 10}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "x", vip: false, items: [{price: 2, qty: 0}, {price: 19.99, qty: 19.99, tag: "silver"}, {price: 21, qty: 1000000000000000000000, tag: "silver"}, {price: 1000, qty: 0.1, tag: "gold "}], score: 18, flag: true, a: 10, n: -1}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "zz", vip: null, items: [{price: 101, qty: 0.1, tag: "Gold"}, {price: 2, qty: 19.99, tag: ""}], score: 1000, flag: false, a: null, n: 1}, "!error"], + [{code: "x", vip: true, items: [{price: 0.1, qty: 0, tag: "zz"}, {price: 1, qty: 2.5, tag: "gold "}, {price: 5, qty: 100, tag: "b"}], score: 2, flag: true, a: 1000000000000000000000, n: 1}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{vip: true, items: [], score: 100, flag: false, n: null}, "!error"], + [{code: "gold", vip: false, items: [{price: 10, qty: 50, tag: "zz"}, {price: null, qty: 5, tag: "gold "}, {}, {price: 11, qty: 21, tag: "Gold"}], score: 106, flag: true, a: 19.99, n: 2.5}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "Gold", vip: false, items: [{price: 5, qty: 0, tag: "a"}, {price: 100, qty: 1000, tag: null}, {price: 2.5, qty: 5, tag: "gold"}], score: 19.99, flag: false, a: 18, extra: [1, 2]}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "b", vip: false, items: [{price: null, qty: 2.5, tag: ""}, {qty: 0.1, tag: "b"}, {price: -0.1, tag: "b"}], score: 11, flag: true, a: 1000000000000000000000, n: 21}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "silver", vip: true, items: [{price: 1, qty: -1, tag: "b"}], score: 19.99, flag: true, n: -1}, "!error"], + [{code: "x", vip: true, items: [], score: 50, flag: false, a: 99, n: 2}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + [{code: "bronze", vip: false, items: [{price: 0.5, qty: 1000, tag: null}], score: 50, a: 0, n: 0}, {k257: "bronze", k259: true, k260: "bronze", k263: 10, k264: "low", res: [{k265: false, k266: 0.25}]}], + [{code: "gold", vip: false, items: [{price: null, tag: "x"}, {price: 0, qty: 1, tag: "a"}, {price: 2, qty: -0.1, tag: "x"}], score: null, flag: true, a: 1000, n: 1000}, "!error"], + [{code: "bronze", vip: false, items: [{price: 0, qty: 5, tag: "x"}, {price: 0.1, qty: 1000000000000000000000, tag: "silver"}], flag: true, a: -1, n: 10}, "!error"], + [{code: "", vip: false, items: [], score: 21, flag: null, a: 0.1, extra: {deep: {x: 1}}}, {k263: 2, k264: "", res: [{k265: false, k266: 0.25}]}], + ], +} + +{ + name: "ga027: 6 nodes, switch*, expr, expr, expr, expr, table", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["(not (startsWith('gold', 'x'))) and (`n=${3}-${'A-1'}` in ['gold', 'silver', 'a'])", "cust.tier + '-' + 'A-1' + '-' + upper('') == 'gold'", ""]}, + {expression: "e2", inputField: "cust", fields: { + k267: "trim((tier ?? 'none'))", + k269: "len(`n=${100}-${(tier ?? 'none')}` + '-' + string($.k267))", + }}, + {expression: "e3", fields: { + "g.k271": "false", + k269: "(((k269 ?? -1)))", + k273: "(true) and ((not (false)) and (false))", + }}, + {expression: "e4", fields: { + "g.k275": "len(string((price ?? a ?? 0)))", + k276: "true", + k277: "((a ?? -1))", + k278: "(-(price)) >= ((price ?? -1) == 0.5 ? 100 : -(($.k277 ?? 1)))", + }}, + {expression: "e5", outputPath: "res", fields: { + k279: "string(true) + ':' + 'none' + '-' + (k267 ?? '?') + ':' + 'gold'", + }}, + {table: "t6", inputs: ["res.k279"], outputs: ["k280"], passThrough: true, rules: [ + ["'silver'", "2"], + ["", "-5"], + ["'gold', 'bronze'", "2"], + ["startsWith($, 's')", "2"], + ["", "1"], + ["'gold'", "0.25"], + ["", "abs(round((0 ?? 1 ?? 0)))"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> e2", + "e2 -> e3", + "s1:2 -> e4", + "e2 -> e5", + "e5 -> t6", + "s1:1 -> output", + "e3 -> output", + "e4 -> output", + "t6 -> output", + ], + }, + cases: [ + [{price: 18, cust: {age: 50, tier: "gold", active: false}, a: 5}, {g: {k275: 2}, k276: true, k277: 5, k278: false}], + [{price: 2.5, cust: {age: 1, tier: "bronze", active: false}, a: 19.99}, {g: {k275: 3}, k276: true, k277: 19.99, k278: true}], + [{price: 0.5, cust: null, a: 0.1}, {g: {k275: 3}, k276: true, k277: 0.1, k278: false}], + [{price: 5, cust: {age: 1, tier: "bronze", active: true}, a: 100, extra: [1, 2]}, {g: {k275: 1}, k276: true, k277: 100, k278: true}], + [{price: 100, cust: {age: 21, tier: null, active: false}, a: null}, {g: {k275: 3}, k276: true, k277: -1, k278: false}], + [{price: 10, cust: {age: 3, tier: "bronze", active: false}, a: 2.5}, {g: {k275: 2}, k276: true, k277: 2.5, k278: false}], + [{cust: {age: -0.1, tier: "a", active: false}, a: 99, extra: {deep: {x: 1}}}, "!error"], + [{price: -25, cust: {age: 2, active: null}, a: 2}, {g: {k275: 3}, k276: true, k277: 2, k278: true}], + [{price: 50, cust: {age: 21, tier: "silver", active: true}, a: 1000000000000000000000}, {g: {k275: 2}, k276: true, k277: 1000000000000000000000, k278: true}], + [{price: 50, cust: {age: 99, active: true}}, {g: {k275: 2}, k276: true, k277: -1, k278: false}], + [{price: 0.1, cust: {age: 7, tier: "zz", active: true}, a: 3}, {g: {k275: 3}, k276: true, k277: 3, k278: true}], + [{price: null, cust: {age: 19.99, tier: "", active: false}, a: 21}, "!error"], + [{price: 8, cust: null, a: 3}, {g: {k275: 1}, k276: true, k277: 3, k278: false}], + [{price: 50, cust: {tier: "a", active: true}, a: 2.5}, {g: {k275: 2}, k276: true, k277: 2.5, k278: false}], + [{price: null, cust: {age: 1000000000000000000000, tier: "gold", active: true}}, "!error"], + [{price: 7, cust: {age: 21, tier: "zz", active: false}, a: 21, extra: {deep: {x: 1}}}, {g: {k275: 1}, k276: true, k277: 21, k278: true}], + [{price: null, cust: {age: 101, tier: "Gold", active: true}}, "!error"], + [{price: -25, a: 115}, {g: {k275: 3}, k276: true, k277: 115, k278: true}], + [{price: 50, a: 19.99, extra: 1}, {g: {k275: 2}, k276: true, k277: 19.99, k278: false}], + [{price: null, cust: null, a: 99}, "!error"], + [{price: 0.1, cust: {age: 3, tier: "a", active: true}, a: 50}, {g: {k275: 3}, k276: true, k277: 50, k278: true}], + [{price: -1, cust: null, a: 21, extra: 1}, {g: {k275: 2}, k276: true, k277: 21, k278: true}], + [{price: -25, cust: null, a: 0}, {g: {k275: 3}, k276: true, k277: 0, k278: true}], + [{price: 2.5, cust: {age: 99, tier: "gold ", active: false}, a: 0.5}, {g: {k275: 3}, k276: true, k277: 0.5, k278: false}], + [{price: 99, cust: {age: 100, tier: "silver", active: true}, a: 21, extra: [1, 2]}, {g: {k275: 2}, k276: true, k277: 21, k278: false}], + [{price: 0, cust: null, a: 1}, {g: {k275: 1}, k276: true, k277: 1, k278: true}], + ], +} + +{ + name: "ga028: 5 nodes, expr, expr, expr, table, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "res", fields: { + k281: "(len('A-1'))", + k282: "0", + k283: "flag ?? flag", + k284: "flag ?? price", + }}, + {expression: "e2", passThrough: true, fields: { + k283: "price != null", + }}, + {expression: "e3", passThrough: true, fields: { + k286: "'x' != 'x'", + k287: "flag ?? score", + }}, + {table: "t4", inputs: ["k283", "a"], outputs: ["res.k288"], rules: [ + ["true", "< -1", "0"], + ["", "> 1", "2"], + ["true", "", "2"], + ["", "", "(price ?? 0)"], + ]}, + {expression: "e5", passThrough: true, fields: { + k289: "''", + "g.k290": "(((res.k282 ?? -1) <= 10) and (((flag ?? false)) or ((vip ?? false))))", + k291: "100", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "input -> e3", + "e2 -> t4", + "e1 -> e5", + "e3 -> output", + "t4 -> output", + "e5 -> output", + ], + }, + cases: [ + [{flag: true, vip: false, cust: null, price: 7, nums: []}, {flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [], price: 7, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, vip: false}], + [{flag: true, vip: false, cust: {age: 1, tier: "Gold", active: false}, score: 7, price: -25, nums: [99]}, {cust: {active: false, age: 1, tier: "Gold"}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [99], price: -25, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, score: 7, vip: false}], + [{a: -1, flag: true, vip: true, cust: {age: 101, tier: "silver", active: true}, score: null, price: 99, nums: [-1, 91]}, {a: -1, cust: {active: true, age: 101, tier: "silver"}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [-1, 91], price: 99, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, vip: true}], + [{a: -25, flag: false, vip: true, cust: {age: 2, tier: "", active: false}, score: 101, nums: [1000000000000000000000, 18]}, {a: -25, cust: {active: false, age: 2, tier: ""}, flag: false, g: {k290: true}, k286: false, k287: false, k289: "", k291: 100, nums: [1000000000000000000000, 18], res: {k281: 3, k282: 0, k283: false, k284: false, k288: 0}, score: 101, vip: true}], + [{a: 3, vip: false, cust: {age: 1, tier: "gold", active: true}, price: 10, nums: []}, {a: 3, cust: {active: true, age: 1, tier: "gold"}, g: {k290: false}, k286: false, k289: "", k291: 100, nums: [], price: 10, res: {k281: 3, k282: 0, k283: null, k284: 10, k288: 2}, vip: false}], + [{a: 68, flag: true, vip: null, cust: {age: 99, tier: "silver", active: true}, score: -25, price: 1, nums: [0.5, 11, 10, 101, 0]}, {a: 68, cust: {active: true, age: 99, tier: "silver"}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [0.5, 11, 10, 101, 0], price: 1, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, score: -25}], + [{a: 2, flag: true, vip: false, cust: {age: 0.5, tier: "zz", active: true}, score: 50, price: null, nums: [-1, 101, -25, -0.1, 3]}, {a: 2, cust: {active: true, age: 0.5, tier: "zz"}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [-1, 101, -25, -0.1, 3], res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, score: 50, vip: false}], + [{a: -1, flag: true, vip: null, cust: {age: 1000000000000000000000, tier: "", active: false}, score: 3, price: 11, nums: [], extra: "e"}, {a: -1, cust: {active: false, age: 1000000000000000000000, tier: ""}, extra: "e", flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [], price: 11, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, score: 3}], + [{a: 0.5, flag: true, vip: false, cust: {age: 0, tier: "gold ", active: false}, score: 11, price: null, nums: [7, -1, 7, -25, 2.5]}, {a: 0.5, cust: {active: false, age: 0, tier: "gold "}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [7, -1, 7, -25, 2.5], res: {k281: 3, k282: 0, k283: true, k284: true, k288: 0}, score: 11, vip: false}], + [{a: 99, flag: true, vip: null, cust: {age: -1, tier: null, active: true}, score: 50, price: 19.99, extra: 1}, {a: 99, cust: {active: true, age: -1, tier: null}, extra: 1, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, price: 19.99, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, score: 50}], + [{flag: true, vip: null, cust: {age: 2.5, tier: "", active: false}, score: 19.99, price: 10}, {cust: {active: false, age: 2.5, tier: ""}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, price: 10, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, score: 19.99}], + [{a: 101, flag: false, vip: false, cust: {age: 0, tier: "zz", active: true}, score: 1, price: 0.1, nums: [-25, 50], extra: 1}, {a: 101, cust: {active: true, age: 0, tier: "zz"}, extra: 1, flag: false, g: {k290: false}, k286: false, k287: false, k289: "", k291: 100, nums: [-25, 50], price: 0.1, res: {k281: 3, k282: 0, k283: false, k284: false, k288: 2}, score: 1, vip: false}], + [{a: 2.5, flag: null, vip: true, cust: {age: 1, tier: "zz", active: false}, score: 45, price: 2.5, nums: [7, 101]}, {a: 2.5, cust: {active: false, age: 1, tier: "zz"}, g: {k290: true}, k286: false, k287: 45, k289: "", k291: 100, nums: [7, 101], price: 2.5, res: {k281: 3, k282: 0, k283: null, k284: 2.5, k288: 2}, score: 45, vip: true}], + [{flag: true, vip: true, cust: {age: 100, tier: "gold", active: false}, score: 1000, price: null}, {cust: {active: false, age: 100, tier: "gold"}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 0}, score: 1000, vip: true}], + [{a: null, flag: true, vip: true, cust: {age: 1000000000000000000000, tier: "zz", active: true}, score: null, price: 0, nums: []}, {cust: {active: true, age: 1000000000000000000000, tier: "zz"}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [], price: 0, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, vip: true}], + [{a: -25, flag: false, vip: false, cust: {age: 100, tier: "", active: false}, score: 2.5, price: 18, nums: [0.1]}, {a: -25, cust: {active: false, age: 100, tier: ""}, flag: false, g: {k290: false}, k286: false, k287: false, k289: "", k291: 100, nums: [0.1], price: 18, res: {k281: 3, k282: 0, k283: false, k284: false, k288: 0}, score: 2.5, vip: false}], + [{a: 5, flag: true, vip: false, cust: null, score: 1000, price: 100}, {a: 5, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, price: 100, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, score: 1000, vip: false}], + [{a: 3, flag: false, cust: {age: 19.99}, score: -0.1, price: -25}, {a: 3, cust: {age: 19.99}, flag: false, g: {k290: false}, k286: false, k287: false, k289: "", k291: 100, price: -25, res: {k281: 3, k282: 0, k283: false, k284: false, k288: 2}, score: -0.1}], + [{a: -25, flag: false, vip: null, cust: null, score: 99, price: -1, nums: []}, {a: -25, flag: false, g: {k290: false}, k286: false, k287: false, k289: "", k291: 100, nums: [], price: -1, res: {k281: 3, k282: 0, k283: false, k284: false, k288: 0}, score: 99}], + [{a: 5, flag: false, vip: true, cust: {age: 50, tier: "bronze", active: true}, score: 0.1, price: 3, nums: [1000000000000000000000]}, {a: 5, cust: {active: true, age: 50, tier: "bronze"}, flag: false, g: {k290: true}, k286: false, k287: false, k289: "", k291: 100, nums: [1000000000000000000000], price: 3, res: {k281: 3, k282: 0, k283: false, k284: false, k288: 2}, score: 0.1, vip: true}], + [{a: 21, flag: true, vip: false, cust: {tier: "x", active: false}, score: null, nums: [7]}, {a: 21, cust: {active: false, tier: "x"}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [7], res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, vip: false}], + [{a: -1, vip: true, score: 0.1, price: 1000, nums: [10, 3, 10, 7, -25]}, {a: -1, g: {k290: true}, k286: false, k287: 0.1, k289: "", k291: 100, nums: [10, 3, 10, 7, -25], price: 1000, res: {k281: 3, k282: 0, k283: null, k284: 1000, k288: 2}, score: 0.1, vip: true}], + [{a: 5, flag: true, vip: false, cust: {age: 11, tier: "gold", active: false}, score: 7, price: 50, nums: [0.1, 11, 101, 5, 0.5]}, {a: 5, cust: {active: false, age: 11, tier: "gold"}, flag: true, g: {k290: true}, k286: false, k287: true, k289: "", k291: 100, nums: [0.1, 11, 101, 5, 0.5], price: 50, res: {k281: 3, k282: 0, k283: true, k284: true, k288: 2}, score: 7, vip: false}], + ], +} + +{ + name: "ga029: 8 nodes, expr, expr, table, table*, switch*, expr, table, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k292: "(flag ?? false)", + k293: "n", + k294: "s != 'gold'", + }}, + {expression: "e2", fields: { + k295: "string(n == null)", + k296: "((code ?? '') in ['gold', 'silver', 'a'] ? -((n ?? 1)) * (n ?? -1) + (n ?? 1) : -((n ?? 0) - (n ?? 1)))", + k297: "min([-(n) + 10, (n) + (cust.age ?? -1)])", + }}, + {table: "t3", inputs: ["flag"], outputs: ["k298", "k299"], outputPath: "out", rules: [ + ["$ == true", "startsWith((s ?? ''), 'x')", "0.25"], + ["", "endsWith(((true) ? (s ?? '?') : (s ?? 'none')), 'g')", "10"], + ["true", "false", "0"], + ["null", "(cust.age ?? 1) + (n ?? -1) * (n ?? 1) > 0", "1"], + ["", "false", "0"], + ]}, + {table: "t4", hit: "collect", inputs: ["k293", "n", null], outputs: ["k300"], passThrough: true, outputPath: "res", rules: [ + ["(18..19)", "(5..6)", "$ != null", "1"], + ["[18..23)", "!= 5", "'gold'", "1"], + ["[0..50]", "!= 5", "", "1"], + ["", "", "", "10"], + ]}, + {switch: "s5", hit: "collect", when: ["k294 == null", "(k293 ?? n ?? 0) % 7 > max([min([0.5, (n ?? 1)]), 0.5 * n])"]}, + {expression: "e6", fields: { + k301: "code", + k302: "((flag ?? false)) and ((k292 ?? false))", + k303: "len((code ?? 'none')) % 2", + }}, + {table: "t7", inputs: ["s"], outputs: ["k304"], outputPath: "res", rules: [ + ["$ != 'gold'", "false"], + ["", "true"], + ["'silver'", "true"], + ["", "((cust.active ?? false)) and (startsWith(string((k293 ?? 1)), 'a'))"], + ["", "'A-1' == 'silver'"], + ["$ != 'silver'", "false"], + ["", "not ((cust.active ?? false))"], + ]}, + {table: "t8", inputs: ["(k301 ?? '')"], outputs: ["k305", "k306"], passThrough: true, rules: [ + ["", "'high'", "len('gold')"], + ["'a', 'b'", "'gold'", "2"], + ["", "''", "10"], + ]}, + ], + edges: [ + "input -> e1", + "input -> e2", + "input -> t3", + "e1 -> t4", + "e1 -> s5", + "s5:1 -> e6", + "e1 -> e6", + "s5:1 -> t7", + "e6 -> t8", + "e1 -> output", + "e2 -> output", + "t3 -> output", + "t4 -> output", + "t7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{code: "", n: 7, flag: true, cust: {age: -25, tier: null, active: true}}, {code: "", cust: {active: true, age: -25, tier: null}, flag: true, k292: true, k293: 7, k294: true, k295: "false", k296: -0, k297: -18, k301: "", k302: true, k303: 0, k305: "high", k306: 4, n: 7, out: {k298: false, k299: 0.25}, res: [{k300: 1}, {k300: 10}]}], + [{code: "x", flag: false, s: "x", cust: {age: null, tier: ""}}, "!error"], + [{code: "silver", n: 0, flag: false, s: "x", cust: {age: 2.5, tier: "gold ", active: true}}, {code: "silver", cust: {active: true, age: 2.5, tier: "gold "}, flag: false, k292: false, k293: 0, k294: true, k295: "false", k296: 0, k297: 2.5, k301: "silver", k302: false, k303: 0, k305: "high", k306: 4, n: 0, out: {k298: false, k299: 10}, res: [{k300: 1}, {k300: 10}], s: "x"}], + [{code: "silver", n: 0.1, flag: "no", s: "x", cust: [], extra: 1}, "!error"], + [{code: "Gold", n: 21, flag: false, s: "silver", cust: {age: 0.5, tier: "silver", active: false}}, {code: "Gold", cust: {active: false, age: 0.5, tier: "silver"}, flag: false, k292: false, k293: 21, k294: true, k295: "false", k296: -0, k297: -11, k301: "Gold", k302: false, k303: 0, k305: "high", k306: 4, n: 21, out: {k298: false, k299: 10}, res: [{k300: 1}, {k300: 10}], s: "silver"}], + [{code: "Gold", n: 7, flag: null, s: null, cust: {age: 18, tier: {t: "x"}, active: 0}, extra: 1}, {code: "Gold", cust: {active: 0, age: 18, tier: {t: "x"}}, extra: 1, k292: false, k293: 7, k294: true, k295: "false", k296: -0, k297: 3, k301: "Gold", k302: false, k303: 0, k305: "high", k306: 4, n: 7, out: {k298: false, k299: 10}, res: [{k300: 1}, {k300: 10}]}], + [{code: null, n: 2, flag: false, s: "silver", cust: {age: 2.5, tier: "a", active: true}}, {cust: {active: true, age: 2.5, tier: "a"}, flag: false, k292: false, k293: 2, k294: true, k295: "false", k296: -0, k297: 4.5, k302: false, k303: 0, k305: "high", k306: 4, n: 2, out: {k298: false, k299: 10}, res: [{k300: 1}, {k300: 10}], s: "silver"}], + [{code: "zz", n: 5, flag: true, s: true, cust: {age: 11, tier: "silver", active: false}}, {code: "zz", cust: {active: false, age: 11, tier: "silver"}, flag: true, k292: true, k293: 5, k294: true, k295: "false", k296: -0, k297: 5, k301: "zz", k302: true, k303: 0, k305: "high", k306: 4, n: 5, out: {k298: false, k299: 0}, res: [{k300: 10}], s: true}], + [{code: "gold", n: 50, s: "b", cust: {age: 5, tier: "x"}}, {code: "gold", cust: {age: 5, tier: "x"}, k292: false, k293: 50, k294: true, k295: "false", k296: -2450, k297: -40, k301: "gold", k302: false, k303: 0, k305: "high", k306: 4, n: 50, out: {k298: false, k299: 10}, res: [{k300: 1}, {k300: 10}], s: "b"}], + [{code: "silver", n: 10, flag: true, s: "Gold", cust: {age: 2, tier: "a", active: "true"}, extra: "e"}, {code: "silver", cust: {active: "true", age: 2, tier: "a"}, extra: "e", flag: true, k292: true, k293: 10, k294: true, k295: "false", k296: -90, k297: 0, k301: "silver", k302: true, k303: 0, k305: "high", k306: 4, n: 10, out: {k298: false, k299: 0.25}, res: [{k300: 1}, {k300: 10}], s: "Gold"}], + [{n: 10, s: "Gold", cust: {age: 0.5, tier: "zz", active: 0}}, {cust: {active: 0, age: 0.5, tier: "zz"}, k292: false, k293: 10, k294: true, k295: "false", k296: -0, k297: 0, k302: false, k303: 0, k305: "high", k306: 4, n: 10, out: {k298: false, k299: 10}, res: [{k300: 1}, {k300: 10}], s: "Gold"}], + [{code: "bronze", n: 100, flag: false, s: null, cust: {age: 0.5, tier: "gold", active: true}}, {code: "bronze", cust: {active: true, age: 0.5, tier: "gold"}, flag: false, k292: false, k293: 100, k294: true, k295: "false", k296: -0, k297: -90, k301: "bronze", k302: false, k303: 0, k305: "high", k306: 4, n: 100, out: {k298: false, k299: 10}, res: [{k300: 10}]}], + [{code: "", n: null, flag: true, s: "", cust: {tier: null, active: false}}, "!error"], + [{code: ["gold"], n: null, flag: false, s: "silver", cust: {age: -25, tier: "gold", active: false}}, "!error"], + [{code: "zz", n: 99, flag: "no", s: "bronze", cust: {tier: "x", active: true}}, "!error"], + [{code: "x", n: 10, flag: 1, s: "a", cust: {age: {v: 1}, tier: "Gold", active: true}}, "!error"], + [{code: "silver", n: 0, flag: true, s: "silver", cust: {age: 21, tier: "", active: true}}, {code: "silver", cust: {active: true, age: 21, tier: ""}, flag: true, k292: true, k293: 0, k294: true, k295: "false", k296: 0, k297: 10, k301: "silver", k302: true, k303: 0, k305: "high", k306: 4, n: 0, out: {k298: false, k299: 0.25}, res: [{k300: 1}, {k300: 10}], s: "silver"}], + [{code: {t: "x"}, n: 101, flag: true, s: "Gold", cust: {age: 0, tier: "silver", active: false}, extra: [1, 2]}, "!error"], + [{code: "b", n: 2.5, flag: true, s: "b", cust: {age: 0.5, tier: "x"}}, {code: "b", cust: {age: 0.5, tier: "x"}, flag: true, k292: true, k293: 2.5, k294: true, k295: "false", k296: -0.0, k297: 3.0, k301: "b", k302: true, k303: 1, k305: "high", k306: 4, n: 2.5, out: {k298: false, k299: 0.25}, res: [{k300: 1}, {k300: 10}], s: "b"}], + [{code: "zz", n: 109, flag: false, s: "bronze", cust: {age: 1, tier: "b", active: true}}, {code: "zz", cust: {active: true, age: 1, tier: "b"}, flag: false, k292: false, k293: 109, k294: true, k295: "false", k296: -0, k297: -99, k301: "zz", k302: false, k303: 0, k305: "high", k306: 4, n: 109, out: {k298: false, k299: 10}, res: [{k300: 10}], s: "bronze"}], + ], +} + +{ + name: "ga030: 7 nodes, expr, table, switch, expr, table, expr, table", + graph: { + nodes: [ + {expression: "e1", fields: { + "res.k307": "(code ?? '') in ['gold', 'silver', 'a']", + k308: "(`v${b}-${(code ?? '')}` == 'x') and ((true))", + }}, + {table: "t2", inputs: ["res.k307", "2", "((-4))"], outputs: ["k309", "k310"], passThrough: true, rules: [ + ["false", "$ > 50 and $ < 60", "5", "'low'", "'high'"], + ["$ == true", "<= 1", "[100..101)", "'low'", "string(2.25)"], + ["true", "10", ">= 100", "'low'", "'mid'"], + ["true", "not(21)", "21, 22", "'A-1'", "'gold'"], + ["", "", "", "''", "'gold'"], + ]}, + {switch: "s3", when: ["(2.25 + b in [1..100])", "(b ?? price ?? 0) == ((true) and (true) ? 3 + 100 : (price ?? 0) * 1)", "not (code != null)"]}, + {expression: "e4", passThrough: true, fields: { + k311: "((abs(b)) / 10)", + "g.k312": "lower((code ?? 'none'))", + "res.k313": "b ?? code", + k314: "true", + }}, + {table: "t5", inputs: ["code", "g.k312"], outputs: ["k315", "k316"], outputPath: "lines", rules: [ + ["null", "'silver', 'bronze'", "string((code ?? '?') in ['gold', 'silver', 'a'])", "false"], + ["", "", "string((code ?? '?') != 'gold') + ' ' + string(((k311 ?? 0)))", "false"], + ["startsWith($, 's')", "$ != 'x'", "'gold'", "not ((price ?? 1) % 7 < 10 * (price ?? 1))"], + ["", "not('')", "'gold'", "max([(price ?? 1), ((b ?? -1)) / 0.5]) <= ((2.25) / 2)"], + ["$ != ''", "", "''", "true"], + ["", "null", "''", "true"], + ["", "", "string(((b ?? 0)) - (price ?? res.k313 ?? 0))", "false"], + ]}, + {expression: "e6", fields: { + k317: "(code ?? '?')", + k318: "(price ?? b ?? 0)", + k319: "(price ?? 0)", + k320: "true", + }}, + {table: "t7", inputs: ["lines.k316", "k311"], outputs: ["res.k313"], rules: [ + ["", "5", "true"], + ["true", "> 18", "true"], + ["$ == true", ">= 0", "false"], + ["null", "$ > 21 and $ < 71", "((k311 ?? res.k313 ?? 0)) > (k311 ?? -1) * (price ?? res.k313 ?? 0)"], + ["", "<= 22", "false"], + ["$ == true", ">= 50", "false"], + ["", "", "3 in [-5..5]"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "input -> s3", + "s3:1 -> e4", + "input -> e4", + "s3:1 -> t5", + "e4 -> t5", + "s3:1 -> e6", + "e4 -> t7", + "t5 -> t7", + "t2 -> output", + "s3:2 -> output", + "e6 -> output", + "t7 -> output", + ], + }, + cases: [ + [{price: [1], b: true, code: "b"}, "!error"], + [{price: 1000, b: -1, code: "a", extra: {deep: {x: 1}}}, {k308: false, k309: "", k310: "gold", res: {k307: true, k313: false}}], + [{price: 2, b: -0.1}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{b: 21, code: "Gold"}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 7, b: 7, code: "gold", extra: 1}, {k308: false, k309: "", k310: "gold", res: {k307: true, k313: false}}], + [{price: [1], b: "5", code: "a"}, "!error"], + [{price: -0.1, b: 5, code: "gold "}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 18, b: 50, code: null}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: true}}], + [{price: 1000000000000000000000, b: true, code: "zz"}, "!error"], + [{price: null, b: 50, code: "a"}, {k308: false, k309: "", k310: "gold", res: {k307: true, k313: true}}], + [{price: 7, b: 0, code: "Gold"}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 7, b: 0.1}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: null, b: true, code: "zz"}, "!error"], + [{price: null, b: 7, code: "b"}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 21, b: 18, code: "b"}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 2, b: -0.1, code: "silver"}, {k308: false, k309: "", k310: "gold", res: {k307: true, k313: false}}], + [{price: 21, b: 2, code: "zz"}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 7, b: 101, code: ""}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 99, b: 0, code: "gold"}, {k308: false, k309: "", k310: "gold", res: {k307: true, k313: false}}], + [{price: 11, b: 1000}, {b: 1000, k308: false, k309: "", k310: "gold", price: 11, res: {k307: false, k313: true}}], + [{price: 5, code: "a"}, "!error"], + [{price: null, b: 101, code: null}, {b: 101, k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 0.5, b: 101, code: "a"}, {k308: false, k309: "", k310: "gold", res: {k307: true, k313: false}}], + [{price: 1000000000000000000000, b: 2.5, code: "b"}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: 101, b: 19.99, code: "b"}, {k308: false, k309: "", k310: "gold", res: {k307: false, k313: false}}], + [{price: -0.1, b: 3, code: "silver"}, {k308: false, k309: "", k310: "gold", res: {k307: true, k313: false}}], + [{price: 50, b: 1000, code: "gold"}, {k308: false, k309: "", k310: "gold", res: {k307: true, k313: true}}], + ], +} + +{ + name: "ga031: 8 nodes, switch, expr, table, expr, table, expr, loop table, table", + graph: { + nodes: [ + {switch: "s1", when: ["count(nums ?? [], # > 10) < (n ?? 0)", ""]}, + {expression: "e2", fields: { + "m.k322": "n ?? vip", + k323: "((b ?? 0) * b - (n ?? 1)) / 2", + k324: "(code ?? 'none')", + "res.k325": "(b ?? -1)", + }}, + {table: "t3", inputs: ["string((res.k325 ?? -1))", "lower((true ? 'gold' : k324))", "k324"], outputs: ["k324"], rules: [ + ["startsWith($, 'g')", "$ != ''", "not('')", "'gold'"], + ["startsWith($, '')", "null", "'x'", "''"], + ["", "", "", "string((res.k325 ?? 0))"], + ]}, + {expression: "e4", fields: { + "res.k327": "b ?? b", + k329: "n ?? vip", + k330: "(code ?? 'none')", + }}, + {table: "t5", inputs: ["(b ?? 1)", "lower(((items ?? [])[1].tag ?? '') + '!')"], outputs: ["k331"], rules: [ + ["<= 22", "'a', 'bronze'", "(b ?? 0)"], + ["(10..20)", "startsWith($, 'g')", "0.25"], + ]}, + {expression: "e6", fields: { + k332: "k331 ?? k331", + k333: "k331 ?? k331", + k334: "(('x' in ['gold', 'silver', 'a']) and ((true) or (false)) ? k331 : 1)", + }}, + {table: "t7", inputField: "items", executionMode: "loop", inputs: ["price", "((price ?? -1) + 1)", "price"], outputs: ["k335"], outputPath: "res", rules: [ + ["0, 50", "< 100", "$ > 21 and $ < 22", "''"], + ["-1", "!= 5", "!= 1", "'high'"], + ["", "", "", "`${(price ?? -1)}-${(tag ?? '')}`"], + ]}, + {table: "t8", inputs: ["k330"], outputs: ["k336"], passThrough: true, rules: [ + ["", "(false)"], + ["not('')", "false"], + ["", "true"], + ["null", "true"], + ["$ != 'a'", "endsWith((k330 in ['gold', 'silver', 'a'] ? (k330 ?? '?') + '-' + (k330 ?? '?') : (false ? k330 : (k330 ?? 'none'))), 'x')"], + ["", "false"], + ["", "(true ? (k334 ?? 0) : 1) + abs(-4) >= (k334) % 7"], + ]}, + ], + edges: [ + "input -> s1", + "s1:1 -> e2", + "input -> e2", + "e2 -> t3", + "s1:1 -> e4", + "t3 -> e4", + "s1:1 -> t5", + "t3 -> t5", + "t5 -> e6", + "input -> t7", + "e6 -> t8", + "e4 -> t8", + "t3 -> output", + "t5 -> output", + "e6 -> output", + "t7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{code: "x", items: 3, b: -0.1, nums: [102], tier: "x", vip: false, n: 19.99}, "!error"], + [{code: "b", items: [{price: -25, qty: null, tag: true}, {price: 1, qty: -2, tag: "Gold"}], b: 5, nums: [3, 100], tier: "x", vip: false, n: 10}, {k324: "5", k330: "none", k334: 1, k336: false, res: [{k335: "-25-true"}, {k335: "1-Gold"}]}], + [{code: {t: "x"}, b: null, nums: [-25], tier: "gold ", vip: null, n: 7}, "!error"], + [{code: "b", items: null, b: 1000, nums: [50, 5], tier: "x", vip: true, extra: 1}, "!error"], + [{items: [{price: 0, qty: 100, tag: "a"}, {price: 100}], b: 21, nums: [1000, 21, 5, -1, 50], tier: "a", vip: true, n: null}, {k324: "21", k329: true, k330: "none", k334: 1, k336: false, res: [{k335: "0-a"}, {k335: "100-"}]}], + [{code: "bronze", items: [{price: 2.5, qty: 99}], b: null, nums: [], tier: null, vip: "true", n: 10}, "!error"], + [{code: "silver", items: [{price: 0.5, qty: 7, tag: "gold"}, {price: 7, qty: 99, tag: "a"}], b: 11, nums: null, tier: "zz", vip: false, n: {v: 1}}, "!error"], + [{code: "zz", items: [{price: null, qty: 2.5, tag: "gold "}, {price: 11, qty: null, tag: "zz"}], nums: 7, tier: "x", vip: false, n: 21}, "!error"], + [{code: "a", items: [{price: 50, qty: 5, tag: true}, {price: 2, qty: 11, tag: "silver"}, {price: 19.99, qty: 2, tag: "a"}, {price: 100, qty: true, tag: "x"}], b: 1000, nums: null, tier: "silver", vip: true, n: 0.5}, {k324: "1000", k330: "none", k334: 1, k336: false, res: [{k335: "50-true"}, {k335: "2-silver"}, {k335: "19.99-a"}, {k335: "100-x"}]}], + [{code: "gold", items: [{price: 50, tag: "a"}, {price: -0.1, qty: 10, tag: "b"}], b: 1000000000000000000000, nums: [7], tier: "bronze", vip: null, n: 11}, "!error"], + [{code: "bronze", items: [{price: 5, qty: 19.99}, {price: 5, qty: null, tag: null}], b: 1, nums: [99], tier: "zz", vip: true, n: 7}, {k324: "1", k330: "none", k334: 1, k336: false, res: [{k335: "5-"}, {k335: "5-"}]}], + [{code: "bronze", items: [{price: 2.5, qty: 2.5, tag: ""}, {price: 0.5, qty: 19.99, tag: "gold "}, {price: 1, qty: 0, tag: "x"}, {price: 100, qty: 1000000000000000000000, tag: "x"}], b: {v: 1}, nums: [], tier: "Gold", vip: "true", n: null}, "!error"], + [{code: "a", nums: null, vip: null, n: 7}, "!error"], + [{code: "bronze", items: [{price: 11, qty: -0.1, tag: {t: "x"}}, {price: 11, qty: 0, tag: "x"}], b: 0, nums: [3, -1, -1, -25, -0.1], tier: "x", n: "abc"}, "!error"], + [{code: "Gold", items: null, b: null, nums: [], tier: "", vip: false, n: 101, extra: "e"}, "!error"], + [{code: "silver", items: [{price: 11, qty: 19.99}], b: -0.1, nums: [99, 7, -1], tier: "gold ", vip: true, n: 0.5, extra: {deep: {x: 1}}}, {k324: "-0.1", k329: 0.5, k330: "silver", k334: 1, k336: false, res: [{k335: "11-"}]}], + ], +} + +{ + name: "ga032: 8 nodes, table, expr, switch, expr, loop expr, table*, expr, expr", + graph: { + nodes: [ + {table: "t1", inputs: ["n", null], outputs: ["k337"], passThrough: true, outputPath: "res", rules: [ + ["[-1..9)", "5", "false"], + ["(100..110)", "", "false"], + ["", "", "true"], + ]}, + {expression: "e2", fields: { + k338: "(b ?? 0)", + k339: "abs(b * cust.age) != ((cust.active ?? false) ? (score ?? 0) + (score ?? -1) : max([(b ?? 0), ($.k338 ?? -1)]))", + k340: "n", + k341: "(cust.tier ?? '')", + }}, + {switch: "s3", when: ["string(0) != 'x'", ""]}, + {expression: "e4", passThrough: true, outputPath: "res", fields: { + k342: "(k340 ?? k338 ?? 0)", + k343: "string(($.k342 ?? 0) + (k338 ?? -1) * ((k339 ?? false) ? (k338 ?? 0) : k340))", + k337: "k338 ?? k340", + k345: "1 != (k340)", + }}, + {expression: "e5", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k346: "upper(tag)", + }}, + {table: "t6", hit: "collect", inputField: "cust", inputs: ["((age ?? -1))", "age"], outputs: ["k347[]"], outputPath: "lines", rules: [ + ["null", "<= 9", "10"], + ["> -1", ">= 21", "1"], + ["!= 0", ">= 100", "-5"], + ["null", "null", "-5"], + ["", "", "10"], + ]}, + {expression: "e7", passThrough: true, fields: { + k348: "(code in ['gold', 'silver', 'a'] ? string(false) : 'none') + '' + string((k339 ?? false)) + ':' + (code ?? '?') + '-' + 'gold'", + k349: "(k340 != null ? string((cust.age ?? 1)) : string(len(filter(items ?? [], #.tag == 'gold'))))", + k350: "(max([(k338 ?? 1), 1])) / 0.5 != abs(0.5 * 1)", + }}, + {expression: "e8", fields: { + k351: "code ?? s", + k352: "(code ?? 'none')", + k353: "code ?? $.k352", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "input -> s3", + "e2 -> e4", + "input -> e5", + "e5 -> t6", + "s3:1 -> e7", + "e4 -> e7", + "e5 -> e8", + "t1 -> output", + "s3:0 -> output", + "e4 -> output", + "t6 -> output", + "e7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{cust: {age: 0, tier: "silver", active: false}, s: "", score: 99, items: [{price: 19.99, qty: 18, tag: "b"}, {price: 21, qty: -0.1, tag: "Gold"}, {price: null, qty: 1000, tag: "bronze"}, {price: 5, qty: 19.99}], n: 5, b: 1000000000000000000000, code: "x"}, "!error"], + [{cust: {age: 1000, active: false}, s: "a", score: -25, items: [{price: 101, qty: 0, tag: "Gold"}, {price: null, qty: 0, tag: "gold"}, {price: 2.5, qty: 50, tag: "bronze"}, {price: 1, qty: 1000, tag: "b"}], n: 2.5, b: 2.5, code: null}, {b: 2.5, cust: {active: false, age: 1000}, items: [{price: 101, qty: 0, tag: "Gold"}, {price: null, qty: 0, tag: "gold"}, {price: 2.5, qty: 50, tag: "bronze"}, {price: 1, qty: 1000, tag: "b"}], k338: 2.5, k339: true, k340: 2.5, k341: "", k348: "nonetrue:?-gold", k349: "1", k350: true, k351: "a", k352: "none", k353: "none", lines: [{k347: 1}, {k347: -5}, {k347: 10}], n: 2.5, res: {k337: true, k342: 2.5, k343: "8.75", k345: true}, s: "a", score: -25}], + [{cust: {age: 2.5, tier: "Gold", active: false}, s: "bronze", score: 101, items: [{price: 2.5, qty: 1000, tag: "a"}, {price: 5, qty: 7, tag: "b"}, {price: 7, qty: 75, tag: "a"}, {price: -25, tag: "gold"}], n: 21, b: 99, code: "b"}, {b: 99, code: "b", cust: {active: false, age: 2.5, tier: "Gold"}, items: [{price: 2.5, qty: 1000, tag: "a"}, {price: 5, qty: 7, tag: "b"}, {price: 7, qty: 75, tag: "a"}, {price: -25, tag: "gold"}], k338: 99, k339: true, k340: 21, k341: "Gold", k348: "nonetrue:?-gold", k349: "1", k350: true, k351: "b", k352: "b", k353: "b", lines: [{k347: 10}], n: 21, res: {k337: true, k342: 21, k343: "9822", k345: true}, s: "bronze", score: 101}], + [{cust: {age: 100, active: null}, s: "", score: 100, items: [{price: 3, qty: 21, tag: "gold"}, {price: -0.1, qty: 50, tag: "bronze"}], n: -25, b: null, code: "x"}, "!error"], + [{cust: {age: 101, tier: "gold ", active: true}, s: "b", score: 99, items: [{price: 11, qty: -0.1, tag: "silver"}], n: null, b: null, code: "b"}, "!error"], + [{cust: {age: -1, tier: "", active: true}, s: "gold ", score: 2.5, items: [{price: 50, qty: null, tag: "bronze"}, {price: 0, qty: 1, tag: "silver"}, {price: 19.99, qty: 2, tag: "gold "}], n: 11, b: null, code: "b"}, "!error"], + [{cust: null, s: "gold ", score: 101, items: [{price: 101, qty: 11, tag: "gold"}], n: 101, b: 0, code: null}, "!error"], + [{cust: {age: 21, tier: "zz", active: true}, s: "x", score: 99, n: 7, b: 101, code: "bronze"}, "!error"], + [{cust: {age: 98, tier: "zz", active: true}, s: "", score: 7, items: [{price: 18, qty: 2.5, tag: "gold "}], n: null, b: 0.1, code: "b", extra: {deep: {x: 1}}}, {b: 0.1, code: "b", cust: {active: true, age: 98, tier: "zz"}, extra: {deep: {x: 1}}, items: [{price: 18, qty: 2.5, tag: "gold "}], k338: 0.1, k339: true, k341: "zz", k348: "nonetrue:?-gold", k349: "0", k350: true, k351: "b", k352: "b", k353: "b", lines: [{k347: 1}, {k347: 10}], res: {k337: true, k342: 0.1, k343: "0.11", k345: true}, s: "", score: 7}], + [{cust: {age: 0.5, tier: "a", active: true}, score: 21, items: [{price: 101, qty: 0.1, tag: "a"}], n: 1000, b: 11, code: "Gold"}, {b: 11, code: "Gold", cust: {active: true, age: 0.5, tier: "a"}, items: [{price: 101, qty: 0.1, tag: "a"}], k338: 11, k339: true, k340: 1000, k341: "a", k348: "nonetrue:?-gold", k349: "1", k350: true, k351: "Gold", k352: "Gold", k353: "Gold", lines: [{k347: 10}], n: 1000, res: {k337: true, k342: 1000, k343: "1121", k345: true}, score: 21}], + [{cust: {age: 21, tier: "Gold", active: false}, s: "silver", score: 0.5, items: [{price: -0.1, qty: null, tag: "x"}, {price: -25, qty: 99, tag: "silver"}], n: null, b: 1000000000000000000000, code: ""}, "!error"], + [{s: "zz", score: -1, items: [{qty: 0, tag: "silver"}, {price: null, qty: 3, tag: "a"}, {price: 1000000000000000000000, qty: 50, tag: "gold"}, {price: -1, qty: 101, tag: "silver"}], n: 101, code: "", extra: "e"}, "!error"], + [{cust: {tier: "b", active: false}, s: "a", items: [{price: -25, tag: "x"}], n: 18, b: 0.1, code: "gold"}, "!error"], + [{cust: {age: 11, tier: "bronze", active: false}, score: 11, items: [{price: -25, qty: 10, tag: "gold"}, {price: null, qty: null, tag: "b"}, {price: 44, qty: 1, tag: "gold"}], n: 99, b: 2.5, code: "b"}, {b: 2.5, code: "b", cust: {active: false, age: 11, tier: "bronze"}, items: [{price: -25, qty: 10, tag: "gold"}, {price: null, qty: null, tag: "b"}, {price: 44, qty: 1, tag: "gold"}], k338: 2.5, k339: true, k340: 99, k341: "bronze", k348: "nonetrue:?-gold", k349: "1", k350: true, k351: "b", k352: "b", k353: "b", lines: [{k347: 10}], n: 99, res: {k337: true, k342: 99, k343: "105.25", k345: true}, score: 11}], + [{cust: null, score: 2.5, items: [{price: 0, qty: null, tag: "silver"}, {price: 7, qty: -1, tag: "gold "}], n: 2.5, b: 10, code: null}, "!error"], + [{cust: {tier: "b", active: false}, s: "a", score: 0, n: 0.1, b: 101, code: "x"}, "!error"], + [{cust: {age: 100, tier: "zz", active: false}, s: null, score: 3, items: null, n: 100, b: null, code: "Gold"}, "!error"], + [{cust: {age: 50, tier: "silver", active: false}, s: "silver", score: 2, items: [{price: 1, qty: 11, tag: "gold"}, {price: 100, qty: 18, tag: "Gold"}, {price: 0.1, qty: 0.1, tag: "bronze"}, {price: 100, qty: 7, tag: "zz"}], n: 2.5, b: 5, code: "Gold"}, {b: 5, code: "Gold", cust: {active: false, age: 50, tier: "silver"}, items: [{price: 1, qty: 11, tag: "gold"}, {price: 100, qty: 18, tag: "Gold"}, {price: 0.1, qty: 0.1, tag: "bronze"}, {price: 100, qty: 7, tag: "zz"}], k338: 5, k339: true, k340: 2.5, k341: "silver", k348: "nonetrue:?-gold", k349: "1", k350: true, k351: "Gold", k352: "Gold", k353: "Gold", lines: [{k347: 1}, {k347: 10}], n: 2.5, res: {k337: true, k342: 2.5, k343: "27.5", k345: true}, s: "silver", score: 2}], + [{cust: {age: null, tier: "x", active: true}, s: "silver", score: 1, items: [{price: -1, qty: -25, tag: "zz"}], n: 21, b: 1000000000000000000000, code: "gold "}, "!error"], + [{cust: {age: 5, tier: "x", active: true}, score: null, items: [{price: 0.1, qty: -1, tag: "b"}, {price: 1, qty: 1000, tag: "gold "}, {price: 1000, qty: -25, tag: "silver"}, {price: 5, qty: 19.99, tag: "silver"}], n: 10, b: null, code: "gold "}, "!error"], + [{cust: {age: null, tier: "b", active: false}, s: "gold ", score: -1, items: [{price: -0.1, qty: 2.5, tag: "Gold"}, {price: 3, qty: 50, tag: "b"}, {price: 10, qty: 99, tag: "silver"}, {price: 5, qty: 18, tag: "zz"}], b: -1, code: "Gold"}, "!error"], + [{cust: {age: 0.5, tier: "Gold", active: true}, s: "gold ", items: [{price: 1000000000000000000000, qty: 19.99, tag: "zz"}, {price: -25, qty: 3, tag: "Gold"}, {price: 99, qty: 2.5, tag: null}, {price: 21, qty: 1000000000000000000000, tag: "zz"}], n: 1000, b: 0.5, code: "gold "}, "!error"], + [{cust: {tier: null, active: true}, s: "x", score: 100, items: [], n: 101, b: 2}, "!error"], + [{cust: {age: 0.5, active: false}, s: "silver", score: 21, items: [{price: 2.5, qty: 99, tag: "Gold"}, {price: 1000000000000000000000, qty: 0}], b: 101, code: "x"}, "!error"], + [{cust: {age: 11, tier: "", active: false}, s: "a", score: 1, items: [{qty: 101}, {price: 100, qty: 50, tag: "zz"}], n: 35, b: 100, code: "gold "}, "!error"], + [{cust: {age: -1, tier: "gold "}, s: "x", score: 5, items: [{price: 0.1, qty: 7, tag: "Gold"}], n: 19.99, b: 7, code: "zz"}, {b: 7, code: "zz", cust: {age: -1, tier: "gold "}, items: [{price: 0.1, qty: 7, tag: "Gold"}], k338: 7, k339: false, k340: 19.99, k341: "gold ", k348: "nonefalse:?-gold", k349: "1", k350: true, k351: "zz", k352: "zz", k353: "zz", lines: [{k347: 10}], n: 19.99, res: {k337: true, k342: 19.99, k343: "159.92", k345: true}, s: "x", score: 5}], + [{s: "a", score: 1, items: [], n: 0.1, b: 2.5, code: "Gold", extra: {deep: {x: 1}}}, "!error"], + [{cust: {age: 50, active: false}, s: "bronze", score: 21, items: [{price: -25, qty: 100}, {price: 1000000000000000000000, qty: 10, tag: "gold"}, {price: 100, qty: 2, tag: "a"}, {price: 50, qty: 1000000000000000000000, tag: "gold"}], n: 21, b: null, code: "x"}, "!error"], + [{cust: {age: 10, tier: "silver", active: false}, s: "", score: 2.5, items: [], n: 5, b: 99, code: "silver"}, {b: 99, code: "silver", cust: {active: false, age: 10, tier: "silver"}, items: [], k338: 99, k339: true, k340: 5, k341: "silver", k348: "nonetrue:?-gold", k349: "1", k350: true, k351: "silver", k352: "silver", k353: "silver", lines: [{k347: 10}], n: 5, res: {k337: true, k342: 5, k343: "9806", k345: true}, s: "", score: 2.5}], + ], +} + +{ + name: "ga033: 5 nodes, expr, expr, table, switch*, expr", + graph: { + nodes: [ + {expression: "e1", fields: { + k354: "vip", + }}, + {expression: "e2", passThrough: true, fields: { + k356: "k354 ?? k354", + }}, + {table: "t3", inputs: ["n"], outputs: ["k357"], rules: [ + ["< 10", "10"], + [">= 21", "10"], + ["null", "min([(price ?? n ?? 0), ((price ?? n ?? 0))])"], + ["", "0"], + ]}, + {switch: "s4", hit: "collect", when: ["(-4) / 3 == ceil(-4 * (price ?? 1))", "(vip ?? false)", "not (((price ?? -1) <= 0.5) and (cust.tier != 'silver'))", ""]}, + {expression: "e5", fields: { + k358: "s != ''", + k359: "('x' != 'gold' ? (s ?? '?') : lower((($.k358 ?? false) ? 'A-1' : (code ?? 'none'))))", + k357: "$.k359 ?? s", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> t3", + "input -> s4", + "s4:2 -> e5", + "e1 -> output", + "e2 -> output", + "t3 -> output", + "s4:0 -> output", + "s4:3 -> output", + "e5 -> output", + ], + }, + cases: [ + [{cust: {age: 0.5, tier: "silver", active: null}, nums: [0.5], price: 10, vip: false, code: "gold ", n: 21}, {code: "gold ", cust: {active: null, age: 0.5, tier: "silver"}, k354: false, k356: false, k357: 10, k358: true, k359: "?", n: 21, nums: [0.5], price: 10, vip: false}], + [{s: "x", cust: {age: 0.5, tier: "silver", active: false}, price: 7, vip: false}, {cust: {active: false, age: 0.5, tier: "silver"}, k354: false, k356: false, k357: 7, k358: true, k359: "x", price: 7, s: "x", vip: false}], + [{s: null, cust: {age: 5, tier: "silver", active: true}, price: -0.1, vip: false, code: "gold", n: 101, extra: {deep: {x: 1}}}, {code: "gold", cust: {active: true, age: 5, tier: "silver"}, extra: {deep: {x: 1}}, k354: false, k356: false, k357: 10, k358: true, k359: "?", n: 101, price: -0.1, vip: false}], + [{s: "gold", cust: {age: -25, tier: "gold ", active: false}, nums: null, price: 1, vip: true, code: "gold", n: 101}, {code: "gold", cust: {active: false, age: -25, tier: "gold "}, k354: true, k356: true, k357: 10, k358: true, k359: "gold", n: 101, price: 1, s: "gold", vip: true}], + [{s: "", cust: null, price: 0.1, vip: true, code: null, n: 50}, {k354: true, k356: true, k357: 10, n: 50, price: 0.1, s: "", vip: true}], + [{s: "gold ", cust: {tier: "silver", active: true}, nums: [21, 1000000000000000000000, -25], price: -1, code: "gold", n: 50}, {code: "gold", cust: {active: true, tier: "silver"}, k357: 10, k358: true, k359: "gold ", n: 50, nums: [21, 1000000000000000000000, -25], price: -1, s: "gold "}], + [{s: "gold", cust: {age: 5, tier: "gold", active: true}, nums: [0.5, 10, 21], price: 3, vip: false, code: "gold", n: 11}, {code: "gold", cust: {active: true, age: 5, tier: "gold"}, k354: false, k356: false, k357: 0, k358: true, k359: "gold", n: 11, nums: [0.5, 10, 21], price: 3, s: "gold", vip: false}], + [{s: "bronze", cust: {age: 1000, tier: "a", active: false}, nums: [99], price: 50, vip: true, code: "zz", n: 50, extra: "e"}, {code: "zz", cust: {active: false, age: 1000, tier: "a"}, extra: "e", k354: true, k356: true, k357: 10, k358: true, k359: "bronze", n: 50, nums: [99], price: 50, s: "bronze", vip: true}], + [{s: "x", cust: {age: 0.5, tier: "bronze", active: null}, nums: [0.1, 0.1, -25, 11, 50], price: 1, vip: true, code: "Gold", n: 50}, {code: "Gold", cust: {active: null, age: 0.5, tier: "bronze"}, k354: true, k356: true, k357: 10, k358: true, k359: "x", n: 50, nums: [0.1, 0.1, -25, 11, 50], price: 1, s: "x", vip: true}], + [{s: "zz", cust: {age: 19.99, tier: "a", active: false}, nums: [1], vip: true, code: "bronze", n: 1000000000000000000000}, {code: "bronze", cust: {active: false, age: 19.99, tier: "a"}, k354: true, k356: true, k357: 10, n: 1000000000000000000000, nums: [1], s: "zz", vip: true}], + [{s: "zz", cust: null, nums: [-0.1, 0], price: 1, vip: null, code: "Gold", n: -0.1}, {code: "Gold", k357: 10, k358: true, k359: "zz", n: -0.1, nums: [-0.1, 0], price: 1, s: "zz"}], + [{s: "x", cust: {age: 19.99, tier: null}, nums: null, vip: true, code: "Gold", n: 21}, {code: "Gold", cust: {age: 19.99, tier: null}, k354: true, k356: true, k357: 10, n: 21, s: "x", vip: true}], + [{s: "gold", cust: {age: 1, tier: "b", active: false}, nums: [7, -25, 101], price: 0.1, vip: true, code: "gold", n: 11}, {code: "gold", cust: {active: false, age: 1, tier: "b"}, k354: true, k356: true, k357: 0, n: 11, nums: [7, -25, 101], price: 0.1, s: "gold", vip: true}], + [{s: null, cust: {age: 2, tier: "Gold", active: false}, nums: [5, 1, -0.1], price: -1, vip: true, code: "zz", n: 50}, {code: "zz", cust: {active: false, age: 2, tier: "Gold"}, k354: true, k356: true, k357: 10, n: 50, nums: [5, 1, -0.1], price: -1, vip: true}], + [{s: "zz", cust: {age: 0.1, tier: "gold", active: false}, nums: [100], price: -0.1, vip: true, code: "gold", n: -0.1}, {code: "gold", cust: {active: false, age: 0.1, tier: "gold"}, k354: true, k356: true, k357: 10, n: -0.1, nums: [100], price: -0.1, s: "zz", vip: true}], + [{s: "gold ", cust: {age: 0, tier: "x", active: false}, nums: [7, 10, 18], price: 101, vip: true, code: "gold"}, {code: "gold", cust: {active: false, age: 0, tier: "x"}, k354: true, k356: true, k357: 101, k358: true, k359: "gold ", nums: [7, 10, 18], price: 101, s: "gold ", vip: true}], + [{cust: {age: 10, tier: "a", active: true}, nums: [-25, -25], price: 2.5, vip: true, code: "Gold", n: 5, extra: 1}, {code: "Gold", cust: {active: true, age: 10, tier: "a"}, extra: 1, k354: true, k356: true, k357: 10, k358: true, k359: "?", n: 5, nums: [-25, -25], price: 2.5, vip: true}], + [{s: "b", cust: {age: 5, tier: "x", active: false}, nums: [], price: null, code: "bronze", n: 21}, {code: "bronze", cust: {active: false, age: 5, tier: "x"}, k357: 10, n: 21, nums: [], s: "b"}], + [{s: "zz", cust: {age: 0.5, tier: "gold ", active: true}, nums: [1000, 18], price: -1, vip: false, code: "silver", n: 0.1}, {code: "silver", cust: {active: true, age: 0.5, tier: "gold "}, k354: false, k356: false, k357: 10, n: 0.1, nums: [1000, 18], price: -1, s: "zz", vip: false}], + [{s: "a", cust: {age: 18, tier: "silver", active: false}, nums: [-25, 11, 0.5], price: 99, vip: false, code: "a", n: 0.5}, {code: "a", cust: {active: false, age: 18, tier: "silver"}, k354: false, k356: false, k357: 10, k358: true, k359: "a", n: 0.5, nums: [-25, 11, 0.5], price: 99, s: "a", vip: false}], + [{s: "bronze", cust: {age: -25, active: true}, nums: [-1, 99], price: 2, vip: false, code: "silver", n: -0.1}, {code: "silver", cust: {active: true, age: -25}, k354: false, k356: false, k357: 10, k358: true, k359: "bronze", n: -0.1, nums: [-1, 99], price: 2, s: "bronze", vip: false}], + [{s: "", cust: {age: 3, tier: "b", active: true}, nums: [11, 101, 2], price: 101, code: "silver", n: 1000000000000000000000}, {code: "silver", cust: {active: true, age: 3, tier: "b"}, k357: 10, k358: false, k359: "", n: 1000000000000000000000, nums: [11, 101, 2], price: 101, s: ""}], + [{s: "b", cust: {age: 21, tier: "a", active: false}, nums: [18, 101], price: 0, vip: false, code: "Gold", n: -0.1}, {code: "Gold", cust: {active: false, age: 21, tier: "a"}, k354: false, k356: false, k357: 10, n: -0.1, nums: [18, 101], price: 0, s: "b", vip: false}], + [{s: "zz", cust: {age: 50, tier: "", active: true}, nums: [3, 2, 101, 2.5, 1000], price: 2.5, code: "Gold", n: null}, {code: "Gold", cust: {active: true, age: 50, tier: ""}, k357: 2.5, k358: true, k359: "zz", nums: [3, 2, 101, 2.5, 1000], price: 2.5, s: "zz"}], + [{cust: {age: 2, tier: null, active: false}, nums: [1], price: 21, vip: false, code: "gold ", n: -1}, {code: "gold ", cust: {active: false, age: 2, tier: null}, k354: false, k356: false, k357: 10, k358: true, k359: "?", n: -1, nums: [1], price: 21, vip: false}], + [{s: null, cust: null, nums: [19.99, 10, 21], price: 1, vip: false, n: -1}, {k354: false, k356: false, k357: 10, k358: true, k359: "?", n: -1, nums: [19.99, 10, 21], price: 1, vip: false}], + [{cust: {age: 2.5, tier: "x", active: true}, vip: null, n: 101}, {cust: {active: true, age: 2.5, tier: "x"}, k357: 10, n: 101}], + [{s: "gold ", cust: {age: 101, tier: "b", active: true}, nums: null, price: 99, vip: true, code: "zz", n: -0.1, extra: [1, 2]}, {code: "zz", cust: {active: true, age: 101, tier: "b"}, extra: [1, 2], k354: true, k356: true, k357: 10, k358: true, k359: "gold ", n: -0.1, price: 99, s: "gold ", vip: true}], + ], +} + +{ + name: "ga034: 8 nodes, loop expr, expr, expr, expr, switch, table, table, table", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k361: "0 * (qty ?? -1) - len((tag ?? '?')) + abs(((price ?? -1)))", + k362: "((tag ?? '?') + '' + 'A-1' == 'x') and ((0.5 == (price ?? -1)) or ((false) and (false)))", + }}, + {expression: "e2", passThrough: true, fields: { + "res.k363": "(startsWith(s, 'x') ? 1 * 0 + 2 : (b ?? -1))", + }}, + {expression: "e3", fields: { + "res.k363": "(contains(string(res.k363), '') ? ((res.k363 ?? -1) * (price ?? 1)) : count(nums ?? [], # > 10))", + k365: "string(len(filter(items ?? [], #.tag == 'gold')))", + k366: "(cust.age ?? -1)", + k367: "len(string(cust.active)) + price", + }}, + {expression: "e4", passThrough: true, fields: { + k368: "min([100, ((b ?? 1) in [-5..5] ? (price ?? 1) + (b ?? 1) : (cust.age ?? 1) + b)])", + k369: "lower(((items ?? [])[1].tag ?? '') + '!')", + k370: "a == null", + }}, + {switch: "s5", when: ["(false)", ""]}, + {table: "t6", inputs: ["(k365 ?? '?')", "(k367 ?? 0)", "'none' + '' + k365 + ' ' + (k365 ?? '?')"], outputs: ["k371"], passThrough: true, rules: [ + ["$ != ''", "> 0", "not('x')", "`n=${0.5}-${(k365 ?? '?')}` + '-' + (k365 ?? '?')"], + ["$ != 'x'", "", "", "''"], + ["$ != 'a'", "[10..60)", "$ != 'gold'", "'gold'"], + ["startsWith($, 'g')", ">= 18", "$ != ''", "'mid'"], + ]}, + {table: "t7", inputs: ["k366", null], outputs: ["k372"], outputPath: "res", rules: [ + ["null", "'gold'", "2"], + ["", "true", "100"], + ["[5..55)", "$ != null", "2"], + ["[21..71]", "5", "0"], + ]}, + {table: "t8", inputs: ["string(true) + '-' + (k365 ?? '?')", "res.k363", "k367"], outputs: ["g.k373", "k374"], passThrough: true, rules: [ + ["", "", ">= 0", "''", "0.25"], + ["", "not(18)", "50, 55", "'high'", "-5"], + ["''", "not(50)", "50, 60", "'low'", "10"], + ["'x', 'gold'", "null", "null", "'low'", "1"], + ["", "", "", "'low'", "1"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "e2 -> e3", + "e1 -> e3", + "input -> e4", + "e3 -> s5", + "s5:0 -> t6", + "e4 -> t7", + "e3 -> t7", + "s5:0 -> t8", + "s5:1 -> output", + "t6 -> output", + "t7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{items: [], nums: [], tier: "x", cust: {age: null, tier: "bronze", active: false}, b: 21, s: "gold", price: null}, "!error"], + [{items: [{price: 11, qty: {v: 1}, tag: "x"}, {price: 5, qty: -0.1, tag: "gold"}], nums: [11, 100], tier: "x", cust: {age: 21, tier: "gold", active: true}, b: 100, s: "x", price: 100}, "!error"], + [{items: [{price: 101, qty: 5, tag: "gold "}], nums: [], tier: "silver", cust: {age: 1, tier: "zz", active: false}, b: 1, s: "b", price: 10}, {k365: "0", k366: 1, k367: 15, res: {k363: 10, k372: 100}}], + [{items: [{price: 50, qty: -25, tag: "gold"}], nums: [-10, -1, 11], cust: null, b: 19.99, s: "zz", price: null}, "!error"], + [{items: [{price: 10, qty: 11, tag: "gold "}], nums: [-1], tier: null, cust: {age: 1000, tier: "", active: false}, b: 2.5, s: "zz", price: 0.5, extra: [1, 2]}, {k365: "0", k366: 1000, k367: 5.5, res: {k363: 1.25, k372: 100}}], + [{items: [{price: 99, qty: 11, tag: "a"}, {price: 2, qty: 18, tag: "zz"}], nums: [5, 1000000000000000000000, 0], tier: "x", cust: {active: false}, b: null, s: "silver", price: -1}, {k365: "0", k366: -1, k367: 4, res: {k363: 1, k372: 100}}], + [{items: [{price: "5", qty: 18, tag: "zz"}, {price: 99, qty: 2, tag: ""}, {price: -0.1, qty: 2.5, tag: null}, {price: 53, tag: "gold "}], tier: "", cust: {age: 18, tier: "zz", active: false}, b: 99, s: "", price: 50}, "!error"], + [{items: [], nums: 7, tier: "gold", cust: 5, b: 11, s: null, price: 7}, "!error"], + [{items: [{qty: 101, tag: "gold"}], nums: [5, 1000, 5], tier: "bronze", cust: {age: -0.1, tier: "a", active: true}, b: 0.1, s: "a", price: 1000000000000000000000}, {k365: "1", k366: -0.1, k367: 1000000000000000000004, res: {k363: 100000000000000000000.0, k372: 100}}], + [{items: [{price: 11, qty: 5, tag: "silver"}, {price: 3, qty: 3, tag: "b"}], nums: [21, -1], tier: true, cust: {age: 11, tier: null, active: false}, b: 105, s: "zz", price: 18}, {k365: "0", k366: 11, k367: 23, res: {k363: 1890, k372: 100}}], + [{items: [{price: 7, qty: -0.1, tag: null}, {qty: -1, tag: "a"}, {price: 0.1, qty: -0.1, tag: "silver"}], nums: [7, 101, 11], tier: "zz", cust: {age: 0, tier: "b", active: true}, b: -0.1, s: null, price: null}, "!error"], + [{items: [{price: 11, qty: -1, tag: "gold "}, {price: 23, qty: 0, tag: "zz"}, {price: -25, tag: null}], nums: [0.5], tier: true, cust: {age: 11, tier: "a", active: true}, b: 1000000000000000000000, s: "b", price: -0.1}, {k365: "0", k366: 11, k367: 3.9, res: {k363: -100000000000000000000.0, k372: 100}}], + [{items: [{price: 0.1, qty: 21, tag: "silver"}, {price: 0.1, qty: 0.1, tag: "b"}, {price: 100, qty: 18, tag: "b"}, {price: 1000000000000000000000, qty: 18, tag: "silver"}], nums: [100], tier: "gold", cust: {age: 5, tier: "x", active: true}, b: 100, price: 11}, "!error"], + [{items: [{price: 0.1, qty: 5, tag: "x"}, {price: 21, tag: "x"}, {price: 21, qty: 0.5, tag: "bronze"}, {price: 5, qty: 1000, tag: "silver"}], nums: [3, 0], tier: "b", cust: {age: 21, tier: "b", active: false}, b: 86, s: "x", price: -1}, {k365: "0", k366: 21, k367: 4, res: {k363: -2, k372: 100}}], + [{items: [{price: -1, qty: 2, tag: "b"}, {price: 7, qty: 3, tag: ""}], nums: null, tier: "x", cust: null, b: 100, s: "bronze", extra: 1}, "!error"], + ], +} + +{ + name: "ga035: 6 nodes, switch*, expr, expr, expr, loop expr, table*", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["true", "(cust.active ?? false)", "(false)"]}, + {expression: "e2", fields: { + k375: "(10 == (a ?? -1) * (a ?? 0)) or (true)", + k376: "'A-1'", + k377: "(a ?? 0)", + }}, + {expression: "e3", fields: { + k378: "max([3, (a ?? a ?? 0)])", + k379: "a != null", + }}, + {expression: "e4", outputPath: "res", fields: { + k380: "max([((k377 ?? -1)), len((k376 ?? 'none'))]) * (k378 ?? 1)", + k381: "(k376 ?? '')", + "g.k382": "not (((false)) or (-4 in [1..100]))", + }}, + {expression: "e5", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + k383: "(tag ?? '?') == 'gold'", + }}, + {table: "t6", hit: "collect", inputs: ["k378"], outputs: ["k384", "k385"], passThrough: true, outputPath: "res", rules: [ + ["", "'mid'", "'gold'"], + ["> 18", "''", "''"], + ["", "'low'", "'high'"], + ["1", "string((k379 ?? false))", "((k379 ?? false) ? ((k378 ?? -1) != (k378 ?? 0) ? ((k379 ?? false) ? '' : 'A-1') : 'gold' + ':' + 'A-1') : '')"], + ["<= 0", "'mid'", "'high'"], + ["< 18", "string(100) + '-' + 'gold'", "'high'"], + ]}, + ], + edges: [ + "input -> s1", + "input -> e2", + "s1:0 -> e3", + "e3 -> e4", + "e2 -> e4", + "s1:0 -> e5", + "e3 -> t6", + "s1:1 -> output", + "s1:2 -> output", + "e4 -> output", + "e5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{s: "b", items: [{price: 108, qty: 0}, {price: 7, qty: 19.99, tag: null}, {price: 10, qty: 7, tag: "gold"}, {price: 7, qty: {v: 1}}], a: 101, tier: "a", cust: {age: 0.1, tier: "a", active: true}, extra: 1}, {a: 101, cust: {active: true, age: 0.1, tier: "a"}, extra: 1, items: [{price: 108, qty: 0}, {price: 7, qty: 19.99, tag: null}, {price: 10, qty: 7, tag: "gold"}, {price: 7, qty: {v: 1}}], k378: 101, k379: true, out: [{k383: false}, {k383: false}, {k383: true}, {k383: false}], res: {g: {k382: true}, k380: 10201, k381: "A-1"}, s: "b", tier: "a"}], + [{s: {t: "x"}, items: [{qty: 1000, tag: "b"}, {price: 101, qty: true, tag: "b"}], a: -25, cust: {age: 100, active: true}}, {a: -25, cust: {active: true, age: 100}, items: [{qty: 1000, tag: "b"}, {price: 101, qty: true, tag: "b"}], k378: 3, k379: true, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}, s: {t: "x"}}], + [{s: "b", items: [{price: 2.5, qty: "5", tag: ""}, {price: 5, qty: 10, tag: "b"}], a: null, tier: "silver", cust: null}, {k378: 3, k379: false, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: "", a: -1, tier: "gold ", cust: {age: 3, tier: "zz", active: false}}, "!error"], + [{s: "gold", items: [{price: 101, qty: 5, tag: "zz"}, {price: 18, tag: "gold "}, {price: 2.5, tag: ""}], a: 19.99, tier: ["gold"], cust: {age: 7, tier: "Gold", active: false}}, {k378: 19.99, k379: true, out: [{k383: false}, {k383: false}, {k383: false}], res: {g: {k382: true}, k380: 399.6001, k381: "A-1"}}], + [{s: ["gold"], items: [{price: 0.5, qty: -25}, {price: 3, qty: 101, tag: "Gold"}, {price: 11, qty: 50, tag: "gold"}, {price: 101, tag: "Gold"}], a: 0, tier: "Gold", cust: {age: 21, tier: "bronze"}, extra: "e"}, {k378: 3, k379: true, out: [{k383: false}, {k383: false}, {k383: true}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: "zz", items: [{price: 18, qty: 5, tag: "Gold"}, {price: 18, qty: 0.5, tag: "bronze"}], a: -1, cust: {age: 9, tier: "gold", active: null}}, {k378: 3, k379: true, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: "", items: [{price: 101, qty: true, tag: "gold "}], a: 0, tier: null, cust: {age: 99, tier: "b", active: true}}, {a: 0, cust: {active: true, age: 99, tier: "b"}, items: [{price: 101, qty: true, tag: "gold "}], k378: 3, k379: true, out: [{k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}, s: ""}], + [{s: null, items: [], a: null, tier: "a", cust: {age: 2, tier: "x", active: false}}, {k378: 3, k379: false, out: [], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: "zz", items: [{price: 1000, qty: 99, tag: "zz"}, {price: 50, qty: 11, tag: "zz"}], a: 0.1, tier: null, cust: {age: 5, tier: "zz", active: null}}, {k378: 3, k379: true, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: "Gold", items: [{price: 0, qty: 18}, {price: -1, qty: 3, tag: null}], tier: 5, cust: {tier: "x", active: false}}, {k378: 3, k379: false, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: null, items: [{price: 50, qty: 1, tag: "zz"}, {price: 1000, qty: 0.1, tag: "Gold"}], a: -0.1, tier: "bronze", cust: {age: 0.1, tier: "a", active: true}}, {a: -0.1, cust: {active: true, age: 0.1, tier: "a"}, items: [{price: 50, qty: 1, tag: "zz"}, {price: 1000, qty: 0.1, tag: "Gold"}], k378: 3, k379: true, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}, tier: "bronze"}], + [{s: ["gold"], items: [{price: 5, tag: "zz"}, {price: 100, qty: 50, tag: "bronze"}], a: 100, tier: "bronze", cust: {age: 1000, tier: "gold", active: "true"}}, {k378: 100, k379: true, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 10000, k381: "A-1"}}], + [{s: "x", items: [{price: 7, qty: 50, tag: "Gold"}, {price: -25, qty: 0.5, tag: null}], a: "abc", tier: "bronze", cust: {age: 50, tier: "Gold", active: false}}, "!error"], + [{s: "zz", items: [{price: 19.99, tag: "Gold"}, {price: 11, qty: 21, tag: "zz"}], tier: "silver", cust: {age: -0.1, tier: "b", active: false}}, {k378: 3, k379: false, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: ["gold"], items: [{price: 50, qty: 0.5, tag: "silver"}], a: 50, tier: "silver", cust: {age: 1000000000000000000000, tier: "silver", active: false}}, {k378: 50, k379: true, out: [{k383: false}], res: {g: {k382: true}, k380: 2500, k381: "A-1"}}], + [{s: "bronze", items: [{price: 1, qty: -25, tag: "zz"}, {price: 1000000000000000000000, qty: 1, tag: ""}, {price: 0.5, qty: 11, tag: "gold"}], a: 2, tier: "x", cust: []}, {k378: 3, k379: true, out: [{k383: false}, {k383: false}, {k383: true}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: "", items: [{price: {v: 1}, qty: 0.1, tag: "silver"}, {price: 0, tag: "silver"}], tier: "a", cust: {age: 1, tier: null, active: true}}, {cust: {active: true, age: 1, tier: null}, items: [{price: {v: 1}, qty: 0.1, tag: "silver"}, {price: 0, tag: "silver"}], k378: 3, k379: false, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}, s: "", tier: "a"}], + [{s: "silver", items: [{price: 19.99, qty: 2, tag: "x"}], a: 0.1, tier: "Gold", cust: {age: "5", tier: "silver", active: true}}, {a: 0.1, cust: {active: true, age: "5", tier: "silver"}, items: [{price: 19.99, qty: 2, tag: "x"}], k378: 3, k379: true, out: [{k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}, s: "silver", tier: "Gold"}], + [{s: ["gold"], items: [{price: 2, qty: 2, tag: "b"}, {price: 50, qty: 2.5, tag: "a"}, {price: [1], tag: ""}, {price: 68, qty: 19.99, tag: ["gold"]}], a: 0.5, tier: true, cust: {age: -1, active: true}}, {a: 0.5, cust: {active: true, age: -1}, items: [{price: 2, qty: 2, tag: "b"}, {price: 50, qty: 2.5, tag: "a"}, {price: [1], tag: ""}, {price: 68, qty: 19.99, tag: ["gold"]}], k378: 3, k379: true, out: [{k383: false}, {k383: false}, {k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}, s: ["gold"], tier: true}], + [{s: "gold ", items: [{qty: 1, tag: {t: "x"}}], a: 11, tier: "gold ", cust: {age: 11, tier: "b", active: true}}, {a: 11, cust: {active: true, age: 11, tier: "b"}, items: [{qty: 1, tag: {t: "x"}}], k378: 11, k379: true, out: [{k383: false}], res: {g: {k382: true}, k380: 121, k381: "A-1"}, s: "gold ", tier: "gold "}], + [{s: "a", items: [{price: 109, qty: null, tag: "x"}], tier: "silver", cust: null}, {k378: 3, k379: false, out: [{k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + [{s: 5, items: [{price: 1000000000000000000000, qty: -0.1, tag: "bronze"}, {price: 99, qty: null, tag: "gold "}], a: 1000, tier: "x", cust: {age: 100, tier: "", active: true}}, {a: 1000, cust: {active: true, age: 100, tier: ""}, items: [{price: 1000000000000000000000, qty: -0.1, tag: "bronze"}, {price: 99, qty: null, tag: "gold "}], k378: 1000, k379: true, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 1000000, k381: "A-1"}, s: 5, tier: "x"}], + [{s: "gold ", items: [{price: 0.5, qty: 11}], a: [1], tier: "gold", cust: {age: 50, tier: "Gold", active: false}}, "!error"], + [{s: "silver", items: [{price: 101, qty: 1000}, {price: 11, qty: 0, tag: "b"}, {price: -16, qty: 1}, {price: 21, qty: 101, tag: "bronze"}], a: "5", cust: {age: 7, active: false}}, "!error"], + [{s: null, items: [{price: 7, qty: null, tag: "zz"}, {price: 18, qty: {v: 1}, tag: ""}], a: null, tier: "a", cust: {age: 10, active: null}, extra: [1, 2]}, {k378: 3, k379: false, out: [{k383: false}, {k383: false}], res: {g: {k382: true}, k380: 9, k381: "A-1"}}], + ], +} + +{ + name: "ga036: 7 nodes, expr, table, expr, expr, switch, expr, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + "m.k386": "(price ?? -1)", + }}, + {table: "t2", inputField: "cust", inputs: ["age"], outputs: ["k387"], outputPath: "res", rules: [ + ["(18..28)", "false"], + ["[50..100]", "true"], + ["!= 1", "true"], + [">= 0", "true"], + ["!= 21", "true"], + ["", "true"], + ]}, + {expression: "e3", fields: { + k388: "'A-1' + ' ' + string((true))", + k389: "((score ?? price ?? 0) + (a ?? -1))", + "res.k390": "score", + }}, + {expression: "e4", outputPath: "res", fields: { + "res.k390": "k388", + }}, + {switch: "s5", when: ["(k389 ?? -1) in [0..10]"]}, + {expression: "e6", fields: { + k388: "'' != 'x'", + }}, + {expression: "e7", passThrough: true, fields: { + k393: "ceil(-(3)) - 0", + }}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "input -> e3", + "t2 -> e3", + "t2 -> e4", + "e3 -> e4", + "e3 -> s5", + "t2 -> e6", + "e6 -> e7", + "e3 -> output", + "e4 -> output", + "s5:0 -> output", + "e7 -> output", + ], + }, + cases: [ + [{score: -1, tier: "", a: "5", s: true, code: "b", extra: [1, 2]}, "!error"], + [{score: 5, tier: "x", price: "abc", a: 1000, s: "bronze", code: "b"}, {k388: "A-1 true", k389: 1005, k393: -3, res: {k390: 5, res: {k390: "A-1 true"}}}], + [{score: 1, cust: {tier: "gold"}, price: 19.99, a: 0, s: "x", code: "gold "}, {k388: "A-1 true", k389: 1, k393: -3, res: {k390: 1, res: {k390: "A-1 true"}}}], + [{score: 101, tier: null, cust: {age: 0.1, tier: "silver", active: true}, price: 18, a: 2.5, s: "bronze"}, {k388: "A-1 true", k389: 103.5, k393: -3, res: {k390: 101, res: {k390: "A-1 true"}}}], + [{score: [1], tier: "a", cust: {age: 10, tier: "a", active: false}, price: true, a: [1], s: null, code: null, extra: "e"}, "!error"], + [{score: 3, tier: "x", cust: {age: 1000000000000000000000, tier: "x"}, price: 10, a: null, s: "zz", code: "Gold"}, {k388: "A-1 true", k389: 2, k393: -3, res: {k390: 3, res: {k390: "A-1 true"}}}], + [{score: 101, tier: "gold", cust: {age: 7, tier: "gold", active: true}, price: null, a: 99, code: null}, {k388: "A-1 true", k389: 200, k393: -3, res: {k390: 101, res: {k390: "A-1 true"}}}], + [{score: 50, tier: "a", cust: {age: 5, active: true}, price: null, a: 99, s: null, code: null}, {k388: "A-1 true", k389: 149, k393: -3, res: {k390: 50, res: {k390: "A-1 true"}}}], + [{score: 1000000000000000000000, tier: "", cust: {age: -0.1, tier: "Gold", active: null}, price: 1000000000000000000000, a: 50, s: "a", code: "bronze"}, {k388: "A-1 true", k389: 1000000000000000000050, k393: -3, res: {k390: 1000000000000000000000, res: {k390: "A-1 true"}}}], + [{score: null, tier: "gold", cust: {age: 1000, tier: "a", active: true}, price: 10, a: -0.1, s: "gold", code: "x", extra: 1}, {k388: "A-1 true", k389: 9.9, k393: -3, res: {res: {k390: "A-1 true"}}}], + [{score: 1, tier: "x", cust: {age: 2}, price: 5, a: 3, s: true, code: null}, {k388: "A-1 true", k389: 4, k393: -3, res: {k390: 1, res: {k390: "A-1 true"}}}], + [{score: 50, cust: {age: 1000, tier: "Gold", active: true}, price: null, a: 21, s: "gold", code: ""}, {k388: "A-1 true", k389: 71, k393: -3, res: {k390: 50, res: {k390: "A-1 true"}}}], + [{score: null, cust: {age: 11, tier: "bronze", active: false}, price: 1000, a: {v: 1}, code: "zz"}, "!error"], + [{score: 21, tier: "bronze", cust: {age: 1, tier: "b", active: false}, price: 0.1, a: 1, s: "gold", code: "a"}, {k388: "A-1 true", k389: 22, k393: -3, res: {k390: 21, res: {k390: "A-1 true"}}}], + [{score: null, cust: {age: 19.99, tier: "", active: true}, a: 21, s: "zz", code: "silver", extra: "e"}, {k388: "A-1 true", k389: 21, k393: -3, res: {res: {k390: "A-1 true"}}}], + [{score: 0.5, tier: "x", cust: {tier: null, active: true}, price: 3, a: 3, s: "silver", code: "", extra: "e"}, {k388: "A-1 true", k389: 3.5, k393: -3, res: {k390: 0.5, res: {k390: "A-1 true"}}}], + [{score: 99, tier: "Gold", cust: {age: -0.1, tier: "a", active: true}, price: 2, a: -0.1, s: 5, code: "gold "}, {k388: "A-1 true", k389: 98.9, k393: -3, res: {k390: 99, res: {k390: "A-1 true"}}}], + [{score: 1000000000000000000000, tier: "Gold", cust: null, price: 2, a: 1, s: "a", code: "Gold"}, {k388: "A-1 true", k389: 1000000000000000000001, k393: -3, res: {k390: 1000000000000000000000, res: {k390: "A-1 true"}}}], + [{score: 21, tier: "gold ", cust: {age: 18, tier: "x", active: false}, price: {v: 1}, a: 19.99, s: "a", code: "Gold"}, {k388: "A-1 true", k389: 40.99, k393: -3, res: {k390: 21, res: {k390: "A-1 true"}}}], + ], +} + +{ + name: "ga037: 8 nodes, table, switch*, expr, switch*, table*, table*, expr, table", + graph: { + nodes: [ + {table: "t1", inputs: ["a"], outputs: ["k394"], rules: [ + ["!= 0", "1"], + ["1, 51", "-5"], + ["< 50", "10"], + ["$ > 1 and $ < 2", "10"], + ]}, + {switch: "s2", hit: "collect", when: ["(endsWith('none' + '-' + 'x', '')) and (not ((true) and (false)))", "(k394 ?? 1) < (k394 ?? -1) + (k394 ?? 0) + (k394)"]}, + {expression: "e3", passThrough: true, outputPath: "res", fields: { + "m.k395": "code", + k396: "n ?? code", + }}, + {switch: "s4", hit: "collect", when: ["(k394 ?? -1) + (k394 ?? -1) + k394 % 3 == (k394 ?? -1)", "((k394 ?? 1) == (k394 ?? -1) + (k394 ?? 0)) and (true)"]}, + {table: "t5", hit: "collect", inputs: ["n"], outputs: ["k397", "res.k398"], outputPath: "lines", rules: [ + ["< -1", "true", "0"], + ["<= 60", "true", "1"], + ["not(18)", "false", "1"], + ["!= 21", "false", "100"], + ["", "true", "0"], + ["", "false", "-5"], + ]}, + {table: "t6", hit: "collect", inputs: ["k394", "k394", "k394"], outputs: ["k399[]"], outputPath: "res", rules: [ + ["[0..10]", "!= 1", "null", "((k394 ?? 1) * (k394 ?? 0) * ((k394 ?? 0)))"], + ["<= 22", "<= 105", "> 18", "100"], + ["", "$ > 10 and $ < 20", "<= 51", "0"], + ["< 18", "$ > 100 and $ < 105", "18", "(k394 ?? -1)"], + ["$ > 50 and $ < 55", "-1", "!= -1", "0.25"], + ["", "", "", "0.25"], + ]}, + {expression: "e7", fields: { + k396: "(false ? 100 : (k394 ?? 1)) * (k394 ?? 1) * (k394 ?? -1) + (k394 ?? 0) * (k394)", + k401: "a != null", + k402: "(2 * (k394 ?? -1) >= ((k394 ?? 1)) / 0.5)", + "res.k403": "ceil(k394 - k394) * (k394 + (k394 ?? 0))", + }}, + {table: "t8", inputs: ["(res.m.k395 ?? 'none') + ':' + string(false)", "a", "res.m.k395"], outputs: ["k404", "k405"], outputPath: "out", rules: [ + ["'x', 'bronze'", "$ > -1 and $ < 9", "null", "(code ?? '')", "'mid'"], + ["$ != 'gold'", "> 1", "startsWith($, 'g')", "'high'", "''"], + ["startsWith($, 'g')", "[21..22)", "null", "'gold'", "string((true) or (10 > (price ?? 1)))"], + ["", ">= 5", "'gold'", "'mid'", "'gold'"], + ["", "", "", "'' + '-' + (res.m.k395 ?? 'none')", "`${(a ?? 1)}-${''}`"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> s2", + "input -> e3", + "t1 -> s4", + "s2:1 -> s4", + "e3 -> t5", + "s2:0 -> t6", + "s2:0 -> e7", + "e3 -> t8", + "t5 -> output", + "t6 -> output", + "e7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{price: 50, n: 18, a: null, nums: [-0.1], code: "gold"}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-gold", k405: "1-"}, res: [{k399: 0.25}]}], + [{n: {v: 1}, a: 0.1, nums: [99]}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-none", k405: "0.1-"}, res: [{k399: 0.25}]}], + [{price: 19.99, n: -1, a: 100, code: "bronze", extra: 1}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-bronze", k405: "100-"}, res: [{k399: 0.25}]}], + [{price: 64, n: null, a: null, nums: [10, 50, 18, 99, 5], code: "gold"}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-gold", k405: "1-"}, res: [{k399: 0.25}]}], + [{price: -0.1, n: 100, a: 2, nums: [7], code: 5, extra: 1}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], res: [{k399: 0.25}]}], + [{price: true, n: 5, a: 7, nums: [0.5, 1000000000000000000000, -0.1, 101, 99], code: "silver", extra: 1}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-silver", k405: "7-"}, res: [{k399: 0.25}]}], + [{price: null, n: 3, a: 2.5, nums: null, code: "silver"}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-silver", k405: "2.5-"}, res: [{k399: 0.25}]}], + [{price: 19.99, n: 84, a: 1000000000000000000000, nums: [-25, 94], code: null}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-none", k405: "1000000000000000000000-"}, res: [{k399: 0.25}]}], + [{price: "abc", a: 19.99, nums: [], code: "gold "}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "high", k405: ""}, res: [{k399: 0.25}]}], + [{price: 104, n: 19.99, a: 101, code: "gold"}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "high", k405: ""}, res: [{k399: 0.25}]}], + [{price: 99, n: 101, a: 5, nums: [5, 18, 1, 100, 7], code: "gold "}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "high", k405: ""}, res: [{k399: 0.25}]}], + [{n: 0, a: 7, nums: [-1, 101, 2], code: "gold"}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "high", k405: ""}, res: [{k399: 0.25}]}], + [{price: 100, n: 3, a: 5, code: null}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-none", k405: "5-"}, res: [{k399: 0.25}]}], + [{price: 5, n: 7, a: 21, nums: [1, -1]}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-none", k405: "21-"}, res: [{k399: 0.25}]}], + [{price: null, n: [1], a: 0.1, nums: [-5, 18, 1000, 101, 2.5], code: null, extra: {deep: {x: 1}}}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-none", k405: "0.1-"}, res: [{k399: 0.25}]}], + [{price: -0.1, n: 10, a: 19.99, nums: 7, code: "silver"}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-silver", k405: "19.99-"}, res: [{k399: 0.25}]}], + [{price: 99, n: 2.5, a: 0, nums: [1000000000000000000000, -25], code: "", extra: [1, 2]}, {k394: 10, k396: 1100, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-", k405: "0-"}, res: [{k399: 0.25}]}], + [{price: 2.5, n: 18, a: 3, nums: [-1]}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-none", k405: "3-"}, res: [{k399: 0.25}]}], + [{price: 11, n: -1, a: -1, code: "gold"}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: true, res: {k398: 1}}, {k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-gold", k405: "-1-"}, res: [{k399: 0.25}]}], + [{price: 2.5, n: null, a: 50, nums: [2, 11, 3, 10, 9], code: "x", extra: "e"}, {k394: 1, k396: 2, k401: false, k402: true, lines: [{k397: false, res: {k398: 100}}, {k397: true, res: {k398: 0}}, {k397: false, res: {k398: -5}}], out: {k404: "-x", k405: "50-"}, res: [{k399: 0.25}]}], + ], +} + +{ + name: "ga038: 6 nodes, expr, switch*, table, table*, table*, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "out", fields: { + k406: "('x' != 'gold' ? 'A-1' : 'gold' + ' ' + 'gold')", + k407: "string((price ?? 1))", + }}, + {switch: "s2", hit: "collect", when: ["(price ?? 0) * (n ?? 0) * 10 in [0..10]", ""]}, + {table: "t3", inputs: ["price", "((false) or (true) ? (b ?? 0) * (b ?? 1) : len(out.k406))"], outputs: ["k408", "k409"], rules: [ + ["10", "", "true", "'high'"], + ["1, 6", "", "false", "upper((out.k407 ?? 'none'))"], + ]}, + {table: "t4", hit: "collect", inputField: "cust", inputs: ["tier"], outputs: ["k410"], rules: [ + ["not('a')", "trim((tier ?? ''))"], + ["null", "'low'"], + ["$ != ''", "'mid'"], + ["'silver'", "(tier ?? '?')"], + ["null", "''"], + ["startsWith($, 'g')", "'gold'"], + ]}, + {table: "t5", hit: "collect", inputs: ["`n=${2.25}-${'A-1'}`"], outputs: ["k411", "k412"], passThrough: true, outputPath: "o.p", rules: [ + ["", "'gold'", "10"], + ["$ != 'silver'", "'mid'", "-5"], + ]}, + {table: "t6", inputs: ["k408", "3", null], outputs: ["k411"], passThrough: true, rules: [ + ["true", "5, 15", "null", "'mid'"], + ["null", "[100..110)", "null", "((0.5 in [-5..5]) and (2.25 != 1) ? (k409 ?? '') : string((k408 ?? false)) + ' ' + (k409 ?? 'none'))"], + ["$ == true", "> 5", "", "`n=${-4}-${(k409 ?? '')}`"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "input -> s2", + "e1 -> t3", + "s2:1 -> t4", + "s2:1 -> t5", + "t3 -> t6", + "s2:0 -> output", + "t4 -> output", + "t5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{cust: {age: 0, tier: "Gold", active: false}, price: 0, n: 21, b: 18, extra: 1}, {b: 18, cust: {active: false, age: 0, tier: "Gold"}, extra: 1, n: 21, out: {k406: "A-1", k407: "0"}, price: 0}], + [{cust: {age: 19.99, tier: "gold", active: true}, price: 7, n: 50, b: null}, [{k410: "mid"}, {k410: "gold"}]], + [{cust: {age: 0, tier: "Gold", active: false}, price: 1, n: -0.1, b: null, extra: 1}, [{k410: "mid"}]], + [{cust: {age: 11, tier: "b", active: true}, price: 1, n: 101, b: 100}, [{k410: "mid"}]], + [{cust: {age: 2, tier: "gold ", active: false}, price: 3, n: 50, b: 2}, [{k410: "mid"}, {k410: "gold"}]], + [{cust: {age: 99, tier: "gold ", active: true}, price: 1000000000000000000000, n: -0.1, b: 2.5}, [{k410: "mid"}, {k410: "gold"}]], + [{cust: {age: null, tier: "silver", active: false}, price: 1, n: 1000000000000000000000, b: 2.5}, [{k410: "mid"}, {k410: "silver"}]], + [{cust: {age: -0.1, tier: "zz", active: false}, price: 101, n: 101, b: 18}, [{k410: "mid"}]], + [{price: 50, n: 101, b: null, extra: "e"}, [{k410: "low"}, {k410: "mid"}, {k410: ""}]], + [{cust: {tier: "x", active: true}, price: 101, n: 21, b: 10}, [{k410: "mid"}]], + [{cust: {age: 18, tier: "x", active: true}, price: 1000, n: -0.1}, [{k410: "mid"}]], + [{cust: {age: 99, tier: "silver", active: true}, price: 5, b: null}, {cust: {active: true, age: 99, tier: "silver"}, out: {k406: "A-1", k407: "5"}, price: 5}], + [{cust: {age: 10, tier: "gold", active: false}, price: 2.5, n: 99, b: 0.1}, [{k410: "mid"}, {k410: "gold"}]], + [{cust: {age: 10, tier: "bronze", active: false}, price: 5, n: 2, b: 2}, [{k410: "mid"}]], + [{cust: {age: 1000000000000000000000, tier: "gold ", active: true}, price: 50, n: 0.5, b: 99}, [{k410: "mid"}, {k410: "gold"}]], + [{cust: {age: 18, tier: "a", active: false}, price: 1, n: -0.1, b: 18}, [{k410: "mid"}]], + [{cust: {age: -0.1, tier: "gold ", active: true}, price: 3}, {cust: {active: true, age: -0.1, tier: "gold "}, out: {k406: "A-1", k407: "3"}, price: 3}], + [{cust: {age: 19.99, tier: "Gold", active: null}, price: 19.99, n: null, b: 0.5}, {b: 0.5, cust: {active: null, age: 19.99, tier: "Gold"}, out: {k406: "A-1", k407: "19.99"}, price: 19.99}], + [{cust: {age: 0.1, tier: "b", active: true}, price: -1, n: 2.5, b: 18}, [{k410: "mid"}]], + [{cust: {age: 1000, tier: "Gold", active: true}, price: 1, n: 19.99, b: 50}, [{k410: "mid"}]], + [{cust: {tier: null, active: true}, b: 100}, {b: 100, cust: {active: true, tier: null}, out: {k406: "A-1", k407: "1"}}], + [{cust: {age: 0.5, tier: null, active: false}, price: 11, n: 50, b: 1000}, [{k410: "low"}, {k410: "mid"}, {k410: ""}]], + [{cust: {age: null, tier: "gold", active: true}, n: 21, b: 0.1}, {b: 0.1, cust: {active: true, age: null, tier: "gold"}, n: 21, out: {k406: "A-1", k407: "1"}}], + [{cust: {age: 2.5, tier: "silver", active: false}, price: 7, n: 1000000000000000000000, b: 1000000000000000000000}, [{k410: "mid"}, {k410: "silver"}]], + [{cust: null, price: 1000000000000000000000, n: -1, b: null}, [{k410: "low"}, {k410: "mid"}, {k410: ""}]], + [{cust: {age: 1000, tier: "Gold", active: true}, price: null, n: 0.5, b: 10}, {b: 10, cust: {active: true, age: 1000, tier: "Gold"}, n: 0.5, out: {k406: "A-1", k407: "1"}}], + [{cust: {age: 5, active: false}, price: 0, n: 1000, b: 2}, {b: 2, cust: {active: false, age: 5}, n: 1000, out: {k406: "A-1", k407: "0"}, price: 0}], + [{cust: {age: 10, tier: "b", active: true}, price: 2, b: 50}, {b: 50, cust: {active: true, age: 10, tier: "b"}, out: {k406: "A-1", k407: "2"}, price: 2}], + ], +} + +{ + name: "ga039: 8 nodes, table*, table*, table, switch, expr, switch*, table, table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["tier", "code", null], outputs: ["k414", "k415"], passThrough: true, outputPath: "out", rules: [ + ["''", "", "$ != null", "'low'", "contains((tier ?? '?'), 'g')"], + ["null", "startsWith($, '')", "null", "'low'", "true"], + ["null", "'a', 'b'", "true", "(tier ?? '')", "true"], + ["null", "", "", "(code ?? '?')", "false"], + ["not('silver')", "", "$ != null", "'none'", "true"], + ["null", "", "5", "'gold' + ':' + (tier ?? '') + ':' + (code ?? '?') + '' + 'none'", "(price ?? price ?? 0) > min([0.5, 2 % 7])"], + ["", "", "", "'x'", "false"], + ]}, + {table: "t2", hit: "collect", inputs: ["code", "tier", "(price ?? 1) * 3"], outputs: ["k416"], outputPath: "res", rules: [ + ["null", "startsWith($, 'a')", "[-1..9]", "(tier ?? '?')"], + ["startsWith($, 'x')", "'a'", "!= 18", "''"], + ["$ != 'a'", "startsWith($, 's')", "not(50)", "''"], + ["not('')", "null", "[1..11)", "''"], + ["not('')", "startsWith($, 'x')", "!= 0", "'mid'"], + ]}, + {table: "t3", inputs: ["0.5"], outputs: ["k416", "k416"], passThrough: true, rules: [ + ["(5..15)", "((0.5) in [1..100])", "0.5"], + ["[5..55)", "true", "-5"], + ["$ > 10 and $ < 60", "true", "100"], + ["$ > 50 and $ < 100", "false", "10"], + ["-1", "true", "(2) + abs((1) / 4)"], + ]}, + {switch: "s4", when: ["(3 + 2) in [0..10]", "a != null", "not (((false) and (true)))", ""]}, + {expression: "e5", fields: { + k419: "null", + k420: "-(min([0, 0.5])) * -((2.25) / 10)", + k421: "a != null", + }}, + {switch: "s6", hit: "collect", when: ["false", "(ceil(2) != 0) or (0.5 * -4 >= 2.25 * 2)", "contains((contains('none', 'x') ? 'A-1' : 'x'), 'a')", ""]}, + {table: "t7", inputs: ["string(3 - 0.5)", "len('x')", "-4", null], outputs: ["k422"], passThrough: true, rules: [ + ["startsWith($, 's')", "[21..31)", "", "null", "'gold'"], + ["'a', 'gold'", "", "(18..28)", "", "'low'"], + ["startsWith($, 's')", "0", "", "", "'low'"], + ["", "null", "", "true", "lower('gold')"], + ["", "", "", "", "`n=${1}-${'A-1'}` + '' + 'gold'"], + ]}, + {table: "t8", inputs: ["k416", "k416 * (k416 ?? k416 ?? 0)", "'x'"], outputs: ["k423"], passThrough: true, rules: [ + ["null", "100, 110", "startsWith($, 's')", "string(((k416 ?? -1) <= -4) or ((true) or (false)))"], + ["not(50)", "(10..60)", "$ != 'a'", "'low'"], + ["(50..55)", "!= 18", "", "'low'"], + ["[10..15)", "null", "", "'gold'"], + ["< 5", "[21..31)", "'a', 'gold'", "''"], + ["", "", "", "'high'"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> t2", + "t2 -> t3", + "t2 -> s4", + "s4:2 -> e5", + "s4:3 -> s6", + "s6:2 -> t7", + "t3 -> t8", + "s4:1 -> output", + "e5 -> output", + "s6:1 -> output", + "s6:3 -> output", + "t7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{price: 21, code: null, tier: "zz"}, {k423: "high", res: []}], + [{code: null, tier: "silver", extra: {deep: {x: 1}}}, {k423: "high", res: []}], + [{price: 100, code: "gold ", tier: "zz"}, {k423: "high", res: []}], + [{price: 3, code: "silver", tier: "bronze"}, {k423: "high", res: []}], + [{price: 0.5, code: "bronze", tier: "zz"}, {k423: "high", res: []}], + [{price: null, code: "silver", tier: "b"}, {k423: "high", res: []}], + [{price: 21, code: "Gold", tier: "gold ", extra: [1, 2]}, {k423: "high", res: []}], + [{code: null, tier: "x"}, {k423: "high", res: []}], + [{price: 21, code: "gold ", tier: null}, {k423: "high", res: []}], + [{price: 1000, code: "b", tier: "a"}, {k423: "high", res: []}], + [{code: "gold ", tier: "x"}, {k423: "high", res: []}], + [{price: -1, code: "", tier: "gold "}, {k423: "high", res: []}], + [{price: 3, code: "bronze", tier: "x", extra: [1, 2]}, {k423: "high", res: []}], + [{price: 21, code: "b", tier: "", extra: 1}, {k423: "high", res: []}], + [{price: 1000, code: "x", tier: "bronze", extra: [1, 2]}, {k423: "high", res: []}], + [{price: 99, code: "silver", tier: "zz", extra: [1, 2]}, {k423: "high", res: []}], + [{price: null, tier: "silver"}, {k423: "high", res: []}], + [{price: -25, tier: "Gold"}, {k423: "high", res: []}], + [{price: 1000, code: "Gold", tier: ""}, {k423: "high", res: []}], + [{price: 3, code: "bronze", tier: "x"}, {k423: "high", res: []}], + [{price: 100, code: "x", tier: "zz"}, {k423: "high", res: []}], + [{price: -25, code: "a", tier: "bronze"}, {k423: "high", res: []}], + [{price: 101, code: "bronze", tier: "gold "}, {k423: "high", res: []}], + [{price: 2, tier: "silver"}, {k423: "high", res: []}], + [{price: 19.99, tier: "zz"}, {k423: "high", res: []}], + [{price: 21, code: "Gold", tier: "bronze", extra: 1}, {k423: "high", res: []}], + [{code: "", tier: null}, {k423: "high", res: []}], + [{price: 0.1, code: "silver", tier: "b"}, {k423: "high", res: []}], + ], +} + +{ + name: "ga040: 3 nodes, expr, expr, expr", + graph: { + nodes: [ + {expression: "e1", outputPath: "res", fields: { + "m.k424": "(b ?? -1) + 2 - len('A-1') >= (b ?? 1)", + }}, + {expression: "e2", fields: { + "m.k425": "res.m.k424 ?? res.m.k424", + "m.k426": "(3) / 3", + }}, + {expression: "e3", passThrough: true, fields: { + k427: "not ((((flag ?? false)) and ((flag ?? false))) or (not ((flag ?? false))))", + k428: "(score ?? 0)", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "e2 -> e3", + "input -> e3", + "e3 -> output", + ], + }, + cases: [ + [{flag: true, cust: null, score: -0.1, b: 0.5}, {b: 0.5, flag: true, k427: false, k428: -0.1, m: {k425: false, k426: 1}, score: -0.1}], + [{flag: false, cust: {age: 19.99, tier: "a", active: false}, score: 11, b: -1}, {b: -1, cust: {active: false, age: 19.99, tier: "a"}, flag: false, k427: false, k428: 11, m: {k425: false, k426: 1}, score: 11}], + [{flag: true, cust: {age: 2.5, tier: "x", active: true}, score: 0.1, b: 11}, {b: 11, cust: {active: true, age: 2.5, tier: "x"}, flag: true, k427: false, k428: 0.1, m: {k425: false, k426: 1}, score: 0.1}], + [{flag: null, cust: {age: 19.99, tier: "", active: false}, score: 0, b: 0}, {b: 0, cust: {active: false, age: 19.99, tier: ""}, k427: false, k428: 0, m: {k425: false, k426: 1}, score: 0}], + [{flag: false, cust: {age: 100, tier: "", active: false}, score: 0.1, b: 21}, {b: 21, cust: {active: false, age: 100, tier: ""}, flag: false, k427: false, k428: 0.1, m: {k425: false, k426: 1}, score: 0.1}], + [{flag: false, score: -25, b: 101}, {b: 101, flag: false, k427: false, k428: -25, m: {k425: false, k426: 1}, score: -25}], + [{flag: false, cust: {active: false}, score: 3, b: 112}, {b: 112, cust: {active: false}, flag: false, k427: false, k428: 3, m: {k425: false, k426: 1}, score: 3}], + [{cust: {age: 0, tier: "b", active: false}, score: 2, b: 96}, {b: 96, cust: {active: false, age: 0, tier: "b"}, k427: false, k428: 2, m: {k425: false, k426: 1}, score: 2}], + [{flag: true, cust: {age: null, tier: "Gold", active: null}, score: 10, b: -0.1}, {b: -0.1, cust: {active: null, age: null, tier: "Gold"}, flag: true, k427: false, k428: 10, m: {k425: false, k426: 1}, score: 10}], + [{flag: true, cust: {age: -0.1, tier: "gold ", active: false}, score: 0.5, b: null}, {cust: {active: false, age: -0.1, tier: "gold "}, flag: true, k427: false, k428: 0.5, m: {k425: false, k426: 1}, score: 0.5}], + [{flag: true, cust: {age: 7, tier: "Gold", active: true}, score: 3, b: 2.5}, {b: 2.5, cust: {active: true, age: 7, tier: "Gold"}, flag: true, k427: false, k428: 3, m: {k425: false, k426: 1}, score: 3}], + [{flag: true, cust: {age: 50, tier: "x", active: true}, score: 3, b: null}, {cust: {active: true, age: 50, tier: "x"}, flag: true, k427: false, k428: 3, m: {k425: false, k426: 1}, score: 3}], + [{flag: true, cust: {age: 108, tier: "x", active: false}, b: 3}, {b: 3, cust: {active: false, age: 108, tier: "x"}, flag: true, k427: false, k428: 0, m: {k425: false, k426: 1}}], + [{flag: false, cust: {age: 99, tier: "Gold", active: true}, score: 1000, b: 2}, {b: 2, cust: {active: true, age: 99, tier: "Gold"}, flag: false, k427: false, k428: 1000, m: {k425: false, k426: 1}, score: 1000}], + [{flag: true, cust: null, score: 0, b: 21}, {b: 21, flag: true, k427: false, k428: 0, m: {k425: false, k426: 1}, score: 0}], + [{flag: true, cust: {age: -0.1, tier: "bronze", active: true}, score: -0.1, b: 3}, {b: 3, cust: {active: true, age: -0.1, tier: "bronze"}, flag: true, k427: false, k428: -0.1, m: {k425: false, k426: 1}, score: -0.1}], + [{flag: false, score: 5, extra: [1, 2]}, {extra: [1, 2], flag: false, k427: false, k428: 5, m: {k425: false, k426: 1}, score: 5}], + [{flag: null, cust: {age: 101, tier: "zz", active: false}, b: 100}, {b: 100, cust: {active: false, age: 101, tier: "zz"}, k427: false, k428: 0, m: {k425: false, k426: 1}}], + [{cust: {age: 19.99, tier: "gold ", active: true}, score: 5, b: 0}, {b: 0, cust: {active: true, age: 19.99, tier: "gold "}, k427: false, k428: 5, m: {k425: false, k426: 1}, score: 5}], + [{flag: false, cust: {age: 0.1, tier: "gold", active: true}, score: 1000, b: 1000000000000000000000, extra: 1}, {b: 1000000000000000000000, cust: {active: true, age: 0.1, tier: "gold"}, extra: 1, flag: false, k427: false, k428: 1000, m: {k425: false, k426: 1}, score: 1000}], + ], +} + +{ + name: "ga041: 8 nodes, table, expr, expr, expr, table, expr, switch, expr", + graph: { + nodes: [ + {table: "t1", inputs: ["vip", "string((score ?? 1)) + '-' + (code ?? '?') + '' + (code ?? '')", "sum(nums ?? []) + score - (price ?? 0)"], outputs: ["k429"], passThrough: true, rules: [ + ["null", "'x'", "[50..100)", "true"], + ["$ == true", "'silver', 'bronze'", "!= 21", "true"], + ]}, + {expression: "e2", passThrough: true, fields: { + k430: "string(not (((vip ?? false))))", + k431: "max([floor(len(code)), (price ?? price ?? 0)])", + }}, + {expression: "e3", fields: { + k429: "price - (score ?? 1) + score + (price ?? 0) != (0.5) / 3 * len(nums ?? [])", + }}, + {expression: "e4", fields: { + k433: "'none' + ':' + (code ?? 'none')", + k434: "string(true) + ' ' + ((vip ?? false) ? code : $.k433) in ['gold', 'silver', 'a']", + }}, + {table: "t5", inputs: ["(code ?? 'none')"], outputs: ["k435"], passThrough: true, rules: [ + ["$ != 'gold'", "false"], + ["", "false"], + ]}, + {expression: "e6", passThrough: true, fields: { + "m.k436": "(price ?? -1)", + k437: "price - (score ?? -1)", + }}, + {switch: "s7", when: ["endsWith('', 'g')"]}, + {expression: "e8", inputField: "cust", fields: { + k438: "$nodes.t1.k429 ?? tier", + k439: "(age ?? -1)", + "res.k440": "(age ?? age ?? 0)", + k441: "active ?? $.k439", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "t1 -> e3", + "input -> e4", + "input -> t5", + "t5 -> e6", + "e4 -> e6", + "e4 -> s7", + "t1 -> e8", + "e2 -> output", + "e3 -> output", + "e4 -> output", + "e6 -> output", + "s7:0 -> output", + "e8 -> output", + ], + }, + cases: [ + [{cust: {age: -25, tier: "silver", active: false}, code: "gold", price: -17, nums: [0.1, -0.1, -0.1, 11, 18], score: 0.5}, {code: "gold", cust: {active: false, age: -25, tier: "silver"}, k429: true, k430: "true", k431: 4, k433: "none:gold", k434: false, k435: false, k437: -17.5, k438: "silver", k439: -25, k441: false, m: {k436: -17}, nums: [0.1, -0.1, -0.1, 11, 18], price: -17, res: {k440: -25}, score: 0.5}], + [{cust: {age: null, active: false}, vip: null, code: "a", price: 18, nums: [], score: -0.1}, {code: "a", cust: {active: false, age: null}, k429: true, k430: "true", k431: 18, k433: "none:a", k434: false, k435: false, k437: 18.1, k439: -1, k441: false, m: {k436: 18}, nums: [], price: 18, res: {k440: 0}, score: -0.1}], + [{cust: {age: 2.5, tier: ""}, vip: false, nums: [100, 11, 1], score: -1, extra: [1, 2]}, "!error"], + [{cust: {age: 2, tier: "zz", active: false}, vip: true, price: 21, nums: [0.1, 3, 21], score: 0.1}, "!error"], + [{cust: {age: -0.1, tier: "x", active: true}, vip: true, code: null, price: 1, nums: [-1, 1], score: -25}, "!error"], + [{cust: {age: 1, tier: "gold ", active: true}, vip: true, code: "silver", price: 48, nums: [2], score: -25}, {code: "silver", cust: {active: true, age: 1, tier: "gold "}, k429: true, k430: "false", k431: 48, k433: "none:silver", k434: false, k435: false, k437: 73, k438: "gold ", k439: 1, k441: true, m: {k436: 48}, nums: [2], price: 48, res: {k440: 1}, score: -25, vip: true}], + [{cust: {age: 21, tier: "gold "}, vip: false, code: "gold", price: null, nums: [], score: 18}, "!error"], + [{cust: {age: 50, tier: "x", active: true}, vip: false, code: "x", price: 7, nums: [], score: 2.5, extra: "e"}, {code: "x", cust: {active: true, age: 50, tier: "x"}, extra: "e", k429: true, k430: "true", k431: 7, k433: "none:x", k434: false, k435: false, k437: 4.5, k438: "x", k439: 50, k441: true, m: {k436: 7}, nums: [], price: 7, res: {k440: 50}, score: 2.5, vip: false}], + [{cust: {active: false}, code: "b", price: -25, nums: [], score: 0}, {code: "b", cust: {active: false}, k429: true, k430: "true", k431: 1, k433: "none:b", k434: false, k435: false, k437: -25, k439: -1, k441: false, m: {k436: -25}, nums: [], price: -25, res: {k440: 0}, score: 0}], + [{cust: {age: 100, tier: "x", active: true}, vip: true, code: "gold ", price: 5, nums: [50, -25, 18, 7, -25], score: 11}, {code: "gold ", cust: {active: true, age: 100, tier: "x"}, k429: true, k430: "false", k431: 5, k433: "none:gold ", k434: false, k435: false, k437: -6, k438: "x", k439: 100, k441: true, m: {k436: 5}, nums: [50, -25, 18, 7, -25], price: 5, res: {k440: 100}, score: 11, vip: true}], + [{cust: {age: 7, tier: "bronze", active: true}, vip: true, code: "Gold", price: 10, nums: [-25, 0.5], score: -0.1}, {code: "Gold", cust: {active: true, age: 7, tier: "bronze"}, k429: true, k430: "false", k431: 10, k433: "none:Gold", k434: false, k435: false, k437: 10.1, k438: "bronze", k439: 7, k441: true, m: {k436: 10}, nums: [-25, 0.5], price: 10, res: {k440: 7}, score: -0.1, vip: true}], + [{cust: {age: 0.1, tier: "a", active: null}, price: 101, nums: [3], score: 0}, "!error"], + [{cust: {tier: "Gold", active: false}, vip: true, code: "Gold", price: null, nums: [99], score: 0.1}, "!error"], + [{cust: {age: -1, tier: "Gold", active: true}, vip: true, code: "silver", price: -25, nums: [0.1, 1000000000000000000000], score: 0.5}, {code: "silver", cust: {active: true, age: -1, tier: "Gold"}, k429: true, k430: "false", k431: 6, k433: "none:silver", k434: false, k435: false, k437: -25.5, k438: "Gold", k439: -1, k441: true, m: {k436: -25}, nums: [0.1, 1000000000000000000000], price: -25, res: {k440: -1}, score: 0.5, vip: true}], + [{cust: {age: 0, tier: "a", active: true}, vip: true, code: "silver", price: 18, nums: null, score: 19.99}, {code: "silver", cust: {active: true, age: 0, tier: "a"}, k429: true, k430: "false", k431: 18, k433: "none:silver", k434: false, k435: false, k437: -1.99, k438: "a", k439: 0, k441: true, m: {k436: 18}, price: 18, res: {k440: 0}, score: 19.99, vip: true}], + [{cust: {age: 1, tier: "Gold", active: false}, vip: true, code: "gold ", price: 21, nums: [19.99, 21], score: 18}, {code: "gold ", cust: {active: false, age: 1, tier: "Gold"}, k429: true, k430: "false", k431: 21, k433: "none:gold ", k434: false, k435: false, k437: 3, k438: "Gold", k439: 1, k441: false, m: {k436: 21}, nums: [19.99, 21], price: 21, res: {k440: 1}, score: 18, vip: true}], + [{cust: {age: 1000000000000000000000, tier: "", active: true}, vip: true, code: "Gold", nums: [100, 21, -25, -25, 2], score: 1000000000000000000000}, "!error"], + [{cust: {age: 18, tier: "a", active: false}, vip: true, code: "x", price: 1, nums: [2.5, -1, 100, 73, 2.5], score: 18}, {code: "x", cust: {active: false, age: 18, tier: "a"}, k429: true, k430: "false", k431: 1, k433: "none:x", k434: false, k435: false, k437: -17, k438: "a", k439: 18, k441: false, m: {k436: 1}, nums: [2.5, -1, 100, 73, 2.5], price: 1, res: {k440: 18}, score: 18, vip: true}], + [{cust: {age: 5, active: false}, vip: true, code: "", price: -0.1, nums: [0, 1000, 2.5], extra: 1}, "!error"], + [{cust: {age: 99, active: true}, vip: true, code: "", price: 1, nums: [5], score: 2.5}, {code: "", cust: {active: true, age: 99}, k429: true, k430: "false", k431: 1, k433: "none:", k434: false, k435: false, k437: -1.5, k439: 99, k441: true, m: {k436: 1}, nums: [5], price: 1, res: {k440: 99}, score: 2.5, vip: true}], + [{cust: null, vip: null, code: "silver", price: 3, nums: [99, 2.5, 1000]}, "!error"], + [{cust: {age: null, tier: "a", active: true}, vip: null, code: "gold", price: 1000000000000000000000, nums: [], score: 1000000000000000000000}, {code: "gold", cust: {active: true, age: null, tier: "a"}, k429: true, k430: "true", k431: 1000000000000000000000, k433: "none:gold", k434: false, k435: false, k437: 0, k438: "a", k439: -1, k441: true, m: {k436: 1000000000000000000000}, nums: [], price: 1000000000000000000000, res: {k440: 0}, score: 1000000000000000000000}], + [{cust: {age: 1000000000000000000000, tier: "Gold", active: false}, vip: false, code: "Gold", price: 5, nums: [11, 50, 2, 0, -25], score: 99, extra: "e"}, {code: "Gold", cust: {active: false, age: 1000000000000000000000, tier: "Gold"}, extra: "e", k429: true, k430: "true", k431: 5, k433: "none:Gold", k434: false, k435: false, k437: -94, k438: "Gold", k439: 1000000000000000000000, k441: false, m: {k436: 5}, nums: [11, 50, 2, 0, -25], price: 5, res: {k440: 1000000000000000000000}, score: 99, vip: false}], + [{cust: {age: 19.99, tier: "a", active: false}, vip: true, code: "Gold", price: -25, nums: null, score: 3}, {code: "Gold", cust: {active: false, age: 19.99, tier: "a"}, k429: true, k430: "false", k431: 4, k433: "none:Gold", k434: false, k435: false, k437: -28, k438: "a", k439: 19.99, k441: false, m: {k436: -25}, price: -25, res: {k440: 19.99}, score: 3, vip: true}], + ], +} + +{ + name: "ga042: 4 nodes, table, expr, expr, table", + graph: { + nodes: [ + {table: "t1", inputs: ["flag"], outputs: ["k442", "k443"], outputPath: "lines", rules: [ + ["null", "'high'", "(tier ?? '')"], + ["", "''", "'low'"], + ["false", "`v${(n ?? 1)}-${(tier ?? '?')}`", "(tier ?? '?')"], + ["true", "(tier ?? '')", "(tier ?? 'none')"], + ["null", "'gold'", "'gold'"], + ["true", "(tier ?? '')", "''"], + ]}, + {expression: "e2", fields: { + k444: "((price ?? 1)) - (10) / 2 - ((n ?? 0) > (price ?? 1) ? round(3) : (n ?? -1))", + }}, + {expression: "e3", passThrough: true, fields: { + k442: "lines.k442 ?? lines.k443", + k446: "0", + k447: "lines.k442 ?? lines.k443", + }}, + {table: "t4", inputs: ["tier"], outputs: ["k448", "k449"], rules: [ + ["'', 'bronze'", "'gold'", "(count(nums ?? [], # > 10) >= n) and ((((flag ?? false))) and (n in [1..100]))"], + ["startsWith($, 'a')", "'high'", "true"], + ["", "(lines.k443 ?? '') + '-' + string(false) + '' + (lines.k443 ?? '?')", "(flag ?? false)"], + ["'x'", "'low'", "true"], + ["not('silver')", "(tier ?? '?')", "true"], + ["", "(lines.k442 ?? 'none')", "false"], + ]}, + ], + edges: [ + "input -> t1", + "input -> e2", + "t1 -> e2", + "t1 -> e3", + "e3 -> t4", + "input -> t4", + "e2 -> output", + "t4 -> output", + ], + }, + cases: [ + [{tier: "Gold", n: 21, price: 0, vip: false}, {k444: -8, k448: "Gold-falseGold", k449: false}], + [{flag: false, tier: null, n: 100, price: 18, nums: [1000, 0.1, 99, 0, -1], vip: true}, {k444: 10, k448: "low-falselow", k449: false}], + [{flag: false, tier: "", n: 7, price: {v: 1}, nums: [], vip: true, extra: {deep: {x: 1}}}, "!error"], + [{flag: true, tier: "silver", n: 1000000000000000000000, nums: [19.99, 20, 21], vip: true}, {k444: -7, k448: "low-falselow", k449: true}], + [{flag: "true", tier: "silver", n: -0.1, price: 0.1, nums: [84, -0.1]}, {k444: -4.8, k448: "low-falselow", k449: "true"}], + [{flag: true, tier: "zz", n: 100, price: 1000, nums: [-25, 1, 100], vip: false}, {k444: 895, k448: "low-falselow", k449: true}], + [{flag: null, tier: "zz", n: 50, price: 1000, nums: [3, 7, 21, 19.99, 10], vip: "no", extra: [1, 2]}, {k444: 945, k448: "zz-falsezz", k449: false}], + [{flag: false, tier: "zz", n: 101, price: 101, nums: [68, 5, 10], vip: true}, {k444: -5, k448: "low-falselow", k449: false}], + [{flag: true, tier: "Gold", n: 18, price: 2, nums: [-25, 0.1], vip: "true"}, {k444: -6, k448: "low-falselow", k449: true}], + [{flag: true, tier: "", n: 11, price: null}, {k444: -7, k448: "gold", k449: false}], + [{flag: true, n: 116, price: 21, nums: [50, 19.99, -25], vip: false}, {k444: 13, k448: "low-falselow", k449: true}], + [{flag: false, tier: "gold", n: null, price: 10, nums: [3, 2.5], vip: true}, {k444: 6, k448: "low-falselow", k449: false}], + [{flag: false, tier: "a", n: 19.99, price: "abc", nums: [0.5, 1000], vip: true}, "!error"], + [{flag: false, tier: "gold ", n: 19.99, price: 21, nums: [], vip: false}, {k444: -3.99, k448: "low-falselow", k449: false}], + [{flag: false, tier: null, n: 100, price: 100, vip: true}, {k444: -5, k448: "low-falselow", k449: false}], + [{flag: true, tier: "b", n: 75, price: 1, nums: [], vip: false}, {k444: -7, k448: "low-falselow", k449: true}], + [{flag: false, tier: null, n: -1, price: null, nums: [0.5, 1000, 7, 2, 101], vip: false}, {k444: -3, k448: "low-falselow", k449: false}], + ], +} + +{ + name: "ga043: 6 nodes, expr, table, expr, expr, loop expr, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k450: "sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0)))", + }}, + {table: "t2", inputs: ["b"], outputs: ["k451", "k450"], passThrough: true, outputPath: "o.p", rules: [ + ["> 50", "-5", "-4"], + ["0, 50", "(n ?? 1)", "100"], + ["null", "-5", "(tier != null ? sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0))) : (b ?? -1)) % 3"], + ["<= 55", "(b ?? 0)", "1"], + ["(21..22)", "-5", "100"], + ["", "0", "0.25"], + ]}, + {expression: "e3", fields: { + k453: "b ?? tier", + k454: "tier ?? tier", + }}, + {expression: "e4", passThrough: true, fields: { + k455: "b ?? tier", + k456: "-4", + k457: "false", + }}, + {expression: "e5", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + k458: "(-(-(3)))", + }}, + {expression: "e6", fields: { + k459: "3", + k460: "(k450 ?? -1) + (b ?? -1) + count(items ?? [], (#.qty ?? 0) > 1) - 2 % 2", + k457: "((false) and (true) ? string(false) : string((k450 ?? 1))) + ':' + string(max([100, (b ?? 0)]))", + k462: "min([(b ?? -1), 0.5])", + }}, + ], + edges: [ + "input -> e1", + "input -> t2", + "input -> e3", + "t2 -> e4", + "input -> e4", + "e1 -> e5", + "e1 -> e6", + "e3 -> output", + "e4 -> output", + "e5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{tier: "bronze", items: [], b: null, n: {v: 1}, extra: "e"}, {extra: "e", items: [], k453: "bronze", k454: "bronze", k455: "bronze", k456: -4, k457: false, k459: 3, k460: -1, k462: -1, n: {v: 1}, o: {p: {k450: 0, k451: -5}}, out: [], tier: "bronze"}], + [{tier: "a", items: [{price: -1, qty: 0.5, tag: "bronze"}, {price: 50, qty: 0.5, tag: "b"}], b: 99, n: 5}, {b: 99, items: [{price: -1, qty: 0.5, tag: "bronze"}, {price: 50, qty: 0.5, tag: "b"}], k453: 99, k454: "a", k455: 99, k456: -4, k457: false, k459: 3, k460: 123.5, k462: 0.5, n: 5, o: {p: {k450: -4, k451: -5}}, out: [{k458: 3}, {k458: 3}], tier: "a"}], + [{items: [], b: 19.99, n: 21}, {b: 19.99, items: [], k453: 19.99, k455: 19.99, k456: -4, k457: false, k459: 3, k460: 19.99, k462: 0.5, n: 21, o: {p: {k450: 1, k451: 19.99}}, out: []}], + [{tier: "", items: [], b: -25, n: 18, extra: 1}, {b: -25, extra: 1, items: [], k453: -25, k454: "", k455: -25, k456: -4, k457: false, k459: 3, k460: -25, k462: -25, n: 18, o: {p: {k450: 1, k451: -25}}, out: [], tier: ""}], + [{tier: "silver", items: 3, b: 5, n: 0.5}, "!error"], + [{items: [{price: -1, qty: 0.1, tag: "silver"}], b: 0, n: 50}, {b: 0, items: [{price: -1, qty: 0.1, tag: "silver"}], k453: 0, k455: 0, k456: -4, k457: false, k459: 3, k460: -0.1, k462: 0, n: 50, o: {p: {k450: 100, k451: 50}}, out: [{k458: 3}]}], + [{tier: "zz", items: [{price: 19.99, qty: 19.99, tag: 5}, {price: 2, qty: 1, tag: "gold"}, {price: 19.99, qty: -25, tag: ""}], b: 99, extra: {deep: {x: 1}}}, {b: 99, extra: {deep: {x: 1}}, items: [{price: 19.99, qty: 19.99, tag: 5}, {price: 2, qty: 1, tag: "gold"}, {price: 19.99, qty: -25, tag: ""}], k453: 99, k454: "zz", k455: 99, k456: -4, k457: false, k459: 3, k460: 1.8501, k462: 0.5, o: {p: {k450: -4, k451: -5}}, out: [{k458: 3}, {k458: 3}, {k458: 3}], tier: "zz"}], + [{tier: "bronze", items: [], b: 3, n: 101}, {b: 3, items: [], k453: 3, k454: "bronze", k455: 3, k456: -4, k457: false, k459: 3, k460: 3, k462: 0.5, n: 101, o: {p: {k450: 1, k451: 3}}, out: [], tier: "bronze"}], + [{tier: "", items: [{price: 100, qty: -25, tag: "a"}, {price: 1000, qty: 1, tag: "silver"}], b: 101, n: 50}, {b: 101, items: [{price: 100, qty: -25, tag: "a"}, {price: 1000, qty: 1, tag: "silver"}], k453: 101, k454: "", k455: 101, k456: -4, k457: false, k459: 3, k460: -1399, k462: 0.5, n: 50, o: {p: {k450: -4, k451: -5}}, out: [{k458: 3}, {k458: 3}], tier: ""}], + [{tier: "Gold", items: [{price: 5, qty: -0.1, tag: ""}, {price: 19.99, qty: -0.1, tag: ""}], b: 2, n: 11}, {b: 2, items: [{price: 5, qty: -0.1, tag: ""}, {price: 19.99, qty: -0.1, tag: ""}], k453: 2, k454: "Gold", k455: 2, k456: -4, k457: false, k459: 3, k460: -0.499, k462: 0.5, n: 11, o: {p: {k450: 1, k451: 2}}, out: [{k458: 3}, {k458: 3}], tier: "Gold"}], + [{tier: "silver", items: null, b: 11, n: 118}, "!error"], + [{tier: "silver", items: [{price: 7, qty: 21, tag: "x"}], b: -1, n: -25, extra: {deep: {x: 1}}}, {b: -1, extra: {deep: {x: 1}}, items: [{price: 7, qty: 21, tag: "x"}], k453: -1, k454: "silver", k455: -1, k456: -4, k457: false, k459: 3, k460: 147, k462: -1, n: -25, o: {p: {k450: 1, k451: -1}}, out: [{k458: 3}], tier: "silver"}], + [{tier: "gold", items: [{price: 7, qty: 1000, tag: "bronze"}, {price: null, qty: 19.99, tag: "bronze"}, {price: -0.1, qty: 0, tag: "Gold"}, {price: 0.5, qty: 3, tag: "b"}], b: 18, n: 50}, {b: 18, items: [{price: 7, qty: 1000, tag: "bronze"}, {price: null, qty: 19.99, tag: "bronze"}, {price: -0.1, qty: 0, tag: "Gold"}, {price: 0.5, qty: 3, tag: "b"}], k453: 18, k454: "gold", k455: 18, k456: -4, k457: false, k459: 3, k460: 7022.5, k462: 0.5, n: 50, o: {p: {k450: 1, k451: 18}}, out: [{k458: 3}, {k458: 3}, {k458: 3}, {k458: 3}], tier: "gold"}], + ], +} + +{ + name: "ga044: 5 nodes, expr, table*, expr, table, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "out", fields: { + k463: "3 > -((price ?? -1))", + }}, + {table: "t2", hit: "collect", inputs: ["price"], outputs: ["k464"], outputPath: "out", rules: [ + ["", "'gold'"], + [">= 1", "'low'"], + ]}, + {expression: "e3", passThrough: true, outputPath: "o.p", fields: { + k465: "startsWith('x', 'a')", + k466: "max([10, -4])", + }}, + {table: "t4", inputs: ["a", "((a ?? a ?? 0))", "string(1) + '' + code"], outputs: ["k467"], passThrough: true, rules: [ + ["[100..110)", "$ > 1 and $ < 51", "'a'", "true"], + ["< 0", "not(21)", "'x'", "(vip ?? false)"], + ["!= 50", "(50..51)", "''", "true"], + ["18", "[18..68]", "", "true"], + ["$ > 10 and $ < 20", "(18..68)", "null", "false"], + ]}, + {table: "t5", inputs: ["(s ?? 'none')", "s", "s"], outputs: ["k468", "k469"], rules: [ + ["", "'silver', 'b'", "null", "true", "-(min([((price ?? 1)), -((a ?? 1))]))"], + ["$ != 'a'", "''", "null", "true", "1"], + ["$ != 'gold'", "$ != 'x'", "'gold'", "true", "100"], + ["", "'', 'b'", "'gold', 'bronze'", "false", "2"], + ["null", "null", "", "((price ?? -1) != (a ?? -1) ? price : ((a ?? 1)) / 4) < (a ?? 0) * (a ?? 0) % 7", "(a ?? -1)"], + ["not('x')", "'silver', 'bronze'", "", "true", "len((code ?? 'none'))"], + ["", "", "", "false", "(price ?? 0)"], + ]}, + ], + edges: [ + "input -> e1", + "input -> t2", + "t2 -> e3", + "t2 -> t4", + "input -> t4", + "t4 -> t5", + "e1 -> output", + "e3 -> output", + "t4 -> output", + "t5 -> output", + ], + }, + cases: [ + [{s: "b", a: null, vip: null, code: "silver"}, {code: "silver", k468: false, k469: 0, o: {p: {k465: false, k466: 10}}, out: {k463: true}, s: "b"}], + [{s: "a", a: 100, vip: true, price: 10, code: "Gold"}, {a: 100, code: "Gold", k468: false, k469: 10, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 10, s: "a", vip: true}], + [{a: 2, vip: true, price: 21, code: "gold"}, {a: 2, code: "gold", k468: false, k469: 21, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 21, vip: true}], + [{s: null, a: -25, vip: false, price: 11, code: true}, {a: -25, code: true, k468: false, k469: 11, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 11, vip: false}], + [{s: "x", a: "abc", price: true, code: "gold "}, "!error"], + [{s: "a", a: -1, vip: 0, price: 1000000000000000000000, code: "a"}, {a: -1, code: "a", k468: false, k469: 1000000000000000000000, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 1000000000000000000000, s: "a", vip: 0}], + [{s: "gold ", a: null, vip: false, price: 44, code: "zz"}, {code: "zz", k468: false, k469: 44, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 44, s: "gold ", vip: false}], + [{s: "silver", a: -25, vip: false, price: "abc", code: "silver"}, "!error"], + [{s: "x", a: 2, vip: 1, price: [1], code: "", extra: "e"}, "!error"], + [{s: "b", a: -8, vip: true, code: "silver"}, {a: -8, code: "silver", k468: false, k469: 0, o: {p: {k465: false, k466: 10}}, out: {k463: true}, s: "b", vip: true}], + [{s: "gold ", a: -1, vip: "no", price: true, code: "gold "}, "!error"], + [{s: "zz", a: 0.5, price: -7, code: "gold", extra: "e"}, {a: 0.5, code: "gold", extra: "e", k468: false, k469: -7, o: {p: {k465: false, k466: 10}}, out: {k463: false}, price: -7, s: "zz"}], + [{s: null, a: 21, vip: true, code: "x"}, {a: 21, code: "x", k468: false, k469: 0, o: {p: {k465: false, k466: 10}}, out: {k463: true}, vip: true}], + [{s: "x", a: 18, vip: false, price: {v: 1}, code: "gold"}, "!error"], + [{s: "a", a: null, price: 101, code: "silver"}, {code: "silver", k468: false, k469: 101, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 101, s: "a"}], + [{s: null, a: 100, vip: false, price: 99, code: ["gold"]}, {a: 100, code: ["gold"], k468: false, k469: 99, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 99, vip: false}], + [{s: "a", a: 1000, vip: null, price: 11, code: "silver"}, {a: 1000, code: "silver", k468: false, k469: 11, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 11, s: "a"}], + [{s: "zz", a: null, vip: false, price: 7, code: "a"}, {code: "a", k468: false, k469: 7, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 7, s: "zz", vip: false}], + [{s: null, a: 1000, vip: false, price: 5, code: "bronze", extra: {deep: {x: 1}}}, {a: 1000, code: "bronze", extra: {deep: {x: 1}}, k468: false, k469: 5, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 5, vip: false}], + [{s: "silver", a: 7, vip: false, price: 2.5, code: "zz"}, {a: 7, code: "zz", k468: false, k469: 2.5, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 2.5, s: "silver", vip: false}], + [{s: "gold", a: 0, vip: true, price: 2.5, code: "a"}, {a: 0, code: "a", k468: false, k469: 2.5, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 2.5, s: "gold", vip: true}], + [{s: "a", a: -1, vip: true, price: 100, code: "Gold"}, {a: -1, code: "Gold", k468: false, k469: 100, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 100, s: "a", vip: true}], + [{s: null, a: 1, vip: true, price: 1, code: ["gold"]}, {a: 1, code: ["gold"], k468: false, k469: 1, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 1, vip: true}], + [{s: "bronze", a: null, price: null, code: "gold", extra: 1}, {code: "gold", extra: 1, k468: false, k469: 0, o: {p: {k465: false, k466: 10}}, out: {k463: true}, s: "bronze"}], + [{s: "bronze", a: -1, vip: true, price: 3, code: "silver"}, {a: -1, code: "silver", k468: false, k469: 3, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 3, s: "bronze", vip: true}], + [{s: "gold", a: 101, vip: null, price: -1, code: "gold"}, {a: 101, code: "gold", k468: false, k469: -1, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: -1, s: "gold"}], + [{s: "", a: 1000000000000000000000, vip: true, price: 18, code: "gold", extra: {deep: {x: 1}}}, {a: 1000000000000000000000, code: "gold", extra: {deep: {x: 1}}, k468: false, k469: 18, o: {p: {k465: false, k466: 10}}, out: {k463: true}, price: 18, s: "", vip: true}], + ], +} + +{ + name: "ga045: 6 nodes, table, switch, table, table*, table*, table*", + graph: { + nodes: [ + {table: "t1", inputs: ["string(false)", "tier", "n"], outputs: ["k470"], passThrough: true, rules: [ + ["startsWith($, 'x')", "", ">= 5", "'high'"], + ["", "null", "(5..6)", "'mid'"], + ["$ != ''", "", "[0..50]", "`v${1}-${'A-1'}`"], + ["'', 'bronze'", "startsWith($, '')", "> 100", "'low'"], + ["", "", "", "'low'"], + ]}, + {switch: "s2", when: ["cust.active", "(100 * (n ?? 1) < ((n ?? 1))) and (false)", "(s ?? 'none') != 'silver'", ""]}, + {table: "t3", inputs: ["tier", "k470"], outputs: ["k471", "k472"], passThrough: true, rules: [ + ["", "''", "false", "2"], + ["$ != 'silver'", "null", "a == null", "10"], + ["not('silver')", "null", "not ((n ?? n ?? 0) <= (n ?? 1))", "2"], + ["null", "$ != 'silver'", "true", "0.25"], + ["'x', 'b'", "", "false", "1"], + ["startsWith($, '')", "$ != 'x'", "true", "0.25"], + ]}, + {table: "t4", hit: "collect", inputs: ["s", "tier", "3 * -4 * -4"], outputs: ["k473[]"], outputPath: "res", rules: [ + ["'gold'", "''", "not(0)", "10"], + ["", "not('x')", "[1..2]", "1"], + ["startsWith($, 'x')", "not('gold')", "not(100)", "-5"], + ["not('')", "", "21", "-(-((n ?? 1) % 7))"], + ]}, + {table: "t5", hit: "collect", inputs: ["k472", "n", "n"], outputs: ["k474"], passThrough: true, outputPath: "o.p", rules: [ + ["$ > -1 and $ < 4", "", "not(50)", "true"], + ["", "[50..60]", "[100..101)", "(((k472 ?? 0)) / 3) != ceil(k472)"], + ["10", "$ > 18 and $ < 28", "!= -1", "false"], + ["", "", "", "false"], + ]}, + {table: "t6", hit: "collect", inputs: ["n", "n"], outputs: ["k475"], rules: [ + ["<= 49", "[1..6)", "100"], + ["> 21", "> 100", "(n ?? k472 ?? 0)"], + ["21, 31", "", "-5"], + ]}, + ], + edges: [ + "input -> t1", + "input -> s2", + "t1 -> t3", + "t1 -> t4", + "t3 -> t5", + "t3 -> t6", + "s2:0 -> output", + "s2:1 -> output", + "s2:3 -> output", + "t4 -> output", + "t5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{n: -1, code: null, s: "b", cust: null, tier: "b"}, {k470: "low", k471: false, k472: 1, n: -1, o: {p: [{k474: false}]}, res: [], s: "b", tier: "b"}], + [{n: 0.1, code: "Gold", s: "", cust: {age: 2.5, tier: "x", active: false}, tier: "zz"}, {code: "Gold", cust: {active: false, age: 2.5, tier: "x"}, k470: "v1-A-1", k471: true, k472: 0.25, n: 0.1, o: {p: [{k474: false}]}, res: [], s: "", tier: "zz"}], + [{n: null, code: "gold", s: "bronze", tier: {t: "x"}}, {code: "gold", k470: "low", o: {p: [{k474: false}]}, res: [], s: "bronze", tier: {t: "x"}}], + [{n: [1], code: "silver", s: "", tier: "zz"}, {code: "silver", k470: "low", k471: true, k472: 0.25, n: [1], o: {p: [{k474: false}]}, res: [], s: "", tier: "zz"}], + [{n: 2, code: "a", s: "gold", cust: {age: 3, tier: "gold"}, tier: null}, {code: "a", cust: {age: 3, tier: "gold"}, k470: "v1-A-1", k471: true, k472: 0.25, n: 2, o: {p: [{k474: false}]}, res: [], s: "gold"}], + [{n: 7, code: "zz", s: "b", cust: {age: [1], tier: "gold ", active: true}, tier: "zz"}, {code: "zz", cust: {active: true, age: [1], tier: "gold "}, k470: "v1-A-1", k471: true, k472: 0.25, n: 7, o: {p: [{k474: false}]}, res: [], s: "b", tier: "zz"}], + [{n: -0.1, code: "", s: "zz", tier: "b"}, {code: "", k470: "low", k471: false, k472: 1, n: -0.1, o: {p: [{k474: false}]}, res: [], s: "zz", tier: "b"}], + [{n: 1000, code: null, s: "bronze", cust: {age: -0.1, tier: "x", active: true}, tier: null}, {cust: {active: true, age: -0.1, tier: "x"}, k470: "low", k471: true, k472: 0.25, n: 1000, o: {p: [{k474: false}]}, res: [], s: "bronze"}], + [{n: 1, code: true, s: true, cust: {age: 5, tier: null, active: false}}, {code: true, cust: {active: false, age: 5, tier: null}, k470: "v1-A-1", k471: true, k472: 0.25, n: 1, o: {p: [{k474: false}]}, res: [], s: true}], + [{n: 2, code: "gold ", s: "bronze", cust: {age: 11, tier: "bronze", active: true}, tier: "b"}, {code: "gold ", cust: {active: true, age: 11, tier: "bronze"}, k470: "v1-A-1", k471: false, k472: 1, n: 2, o: {p: [{k474: false}]}, res: [], s: "bronze", tier: "b"}], + [{code: "silver", s: "x", cust: null, tier: ""}, {code: "silver", k470: "low", k471: true, k472: 0.25, o: {p: [{k474: false}]}, res: [], s: "x", tier: ""}], + [{n: 15, code: "zz", s: "b", cust: {age: [1], tier: "b", active: false}, tier: "gold"}, {code: "zz", cust: {active: false, age: [1], tier: "b"}, k470: "v1-A-1", k471: true, k472: 0.25, n: 15, o: {p: [{k474: false}]}, res: [], s: "b", tier: "gold"}], + [{n: {v: 1}, code: "silver", s: "", cust: [], tier: null}, {code: "silver", cust: [], k470: "low", k471: true, k472: 0.25, n: {v: 1}, o: {p: [{k474: false}]}, res: [], s: ""}], + [{code: "gold", s: "gold ", cust: {age: 0.5, active: false}, tier: "a"}, {code: "gold", cust: {active: false, age: 0.5}, k470: "low", k471: true, k472: 0.25, o: {p: [{k474: false}]}, res: [], s: "gold ", tier: "a"}], + [{n: 19.99, code: "silver", s: "b", cust: {age: [1], tier: "silver", active: false}, tier: "silver"}, {code: "silver", cust: {active: false, age: [1], tier: "silver"}, k470: "v1-A-1", k471: true, k472: 0.25, n: 19.99, o: {p: [{k474: false}]}, res: [], s: "b", tier: "silver"}], + [{n: 3, code: "", cust: null, tier: "gold "}, {code: "", k470: "v1-A-1", k471: true, k472: 0.25, n: 3, o: {p: [{k474: false}]}, res: [], tier: "gold "}], + [{n: null, code: "gold", s: "zz", cust: {age: null, tier: "a", active: true}, tier: "zz"}, {code: "gold", cust: {active: true, age: null, tier: "a"}, k470: "low", k471: true, k472: 0.25, o: {p: [{k474: false}]}, res: [], s: "zz", tier: "zz"}], + [{n: null, code: "silver", s: "zz", cust: [{age: 3}], tier: null}, {code: "silver", cust: [{age: 3}], k470: "low", k471: true, k472: 0.25, o: {p: [{k474: false}]}, res: [], s: "zz"}], + [{n: 7, code: "b", s: "b", cust: {age: 39, tier: "", active: false}, tier: "Gold"}, {code: "b", cust: {active: false, age: 39, tier: ""}, k470: "v1-A-1", k471: true, k472: 0.25, n: 7, o: {p: [{k474: false}]}, res: [], s: "b", tier: "Gold"}], + [{n: null, s: "zz", tier: "gold "}, {k470: "low", k471: true, k472: 0.25, o: {p: [{k474: false}]}, res: [], s: "zz", tier: "gold "}], + [{n: null, s: "silver", cust: null, tier: "b"}, {k470: "low", k471: false, k472: 1, o: {p: [{k474: false}]}, res: [], s: "silver", tier: "b"}], + [{n: 2, code: "gold", s: "zz", cust: [], tier: "gold "}, {code: "gold", cust: [], k470: "v1-A-1", k471: true, k472: 0.25, n: 2, o: {p: [{k474: false}]}, res: [], s: "zz", tier: "gold "}], + [{n: 0.1, code: "gold ", s: "", cust: null, tier: "b"}, {code: "gold ", k470: "v1-A-1", k471: false, k472: 1, n: 0.1, o: {p: [{k474: false}]}, res: [], s: "", tier: "b"}], + [{n: "5", code: "gold", s: "bronze", cust: {age: 0.1, tier: "zz", active: null}, tier: "silver"}, {code: "gold", cust: {active: null, age: 0.1, tier: "zz"}, k470: "low", k471: true, k472: 0.25, n: "5", o: {p: [{k474: false}]}, res: [], s: "bronze", tier: "silver"}], + [{n: 5, code: 5, s: "", cust: {age: 99, active: true}, tier: ""}, {code: 5, cust: {active: true, age: 99}, k470: "v1-A-1", k471: true, k472: 0.25, n: 5, o: {p: [{k474: false}]}, res: [], s: "", tier: ""}], + [{code: ["gold"], s: "Gold", cust: {age: 7, tier: "bronze", active: true}, tier: "b", extra: 1}, {code: ["gold"], cust: {active: true, age: 7, tier: "bronze"}, extra: 1, k470: "low", k471: false, k472: 1, o: {p: [{k474: false}]}, res: [], s: "Gold", tier: "b"}], + [{code: "silver", cust: {age: "abc", tier: "bronze", active: true}, tier: null}, {code: "silver", cust: {active: true, age: "abc", tier: "bronze"}, k470: "low", k471: true, k472: 0.25, o: {p: [{k474: false}]}, res: []}], + ], +} + +{ + name: "ga046: 6 nodes, loop expr, expr, expr, expr, table, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "lines", fields: { + k476: "min([qty, 3 + (price ?? 1) * (qty ?? 1) % 2])", + }}, + {expression: "e2", passThrough: true, fields: { + "m.k477": "len(tier + '' + '') <= (score ?? -1)", + k478: "string(contains((tier ?? '') + '' + (s ?? 'none'), 'a'))", + k479: "b ?? score", + k480: "string((s ?? 'none') != '')", + }}, + {expression: "e3", fields: { + k481: "((b ?? -1) >= 10 % 7 ? (score ?? 1) : len(s + ' ' + k478))", + k482: "2 + (b ?? -1)", + }}, + {expression: "e4", fields: { + k476: "(b ?? score ?? 0)", + k484: "(startsWith((s ?? '?'), 'a')) or (false)", + }}, + {table: "t5", inputs: ["m.k477", "k476", null], outputs: ["res.k485"], passThrough: true, rules: [ + ["false", "> 0", "5", "m.k477 != null"], + ["false", "< 0", "null", "true"], + ["false", "not(-1)", "", "true"], + ["false", "null", "null", "false"], + ["", "< 5", "5", "false"], + ["null", "10, 60", "", "false"], + ["", "", "", "false"], + ]}, + {expression: "e6", outputPath: "o.p", fields: { + "g.k486": "(endsWith(string(0), 'x') ? string(false) : 'A-1')", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e2 -> e3", + "input -> e4", + "e1 -> e4", + "e2 -> t5", + "e4 -> t5", + "e3 -> e6", + "t5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{b: 19.99, s: "x", nums: [-25, 25, 11, 2.5, 5], score: 3, items: [{price: 10, qty: 1000, tag: "gold "}, {price: -25, qty: 2, tag: "a"}], tier: "Gold", vip: true}, {b: 19.99, items: [{price: 10, qty: 1000, tag: "gold "}, {price: -25, qty: 2, tag: "a"}], k476: 19.99, k478: "false", k479: 19.99, k480: "true", k484: false, m: {k477: false}, nums: [-25, 25, 11, 2.5, 5], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "x", score: 3, tier: "Gold", vip: true}], + [{s: "a", nums: [0.1, 100, -0.1], score: 11, items: [], tier: "b", vip: true}, {items: [], k476: 11, k478: "true", k479: 11, k480: "true", k484: true, m: {k477: true}, nums: [0.1, 100, -0.1], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "a", score: 11, tier: "b", vip: true}], + [{b: 10, s: "b", nums: [-0.1, 1000000000000000000000], score: "abc", items: [{price: 21, qty: 19.99, tag: "Gold"}, {price: 2.5, qty: -1, tag: ""}], tier: "gold", vip: true}, "!error"], + [{b: 85, s: "zz", nums: [], score: -10, items: [{price: "5", qty: null, tag: "gold "}, {price: "abc", qty: -0.1, tag: "x"}], tier: "gold", vip: false}, "!error"], + [{b: 21, s: "bronze", nums: null, score: 0.5, items: [{price: -0.1, qty: 0, tag: "a"}, {price: 2.5, qty: 100, tag: null}], tier: "a", vip: false}, {b: 21, items: [{price: -0.1, qty: 0, tag: "a"}, {price: 2.5, qty: 100, tag: null}], k476: 21, k478: "true", k479: 21, k480: "true", k484: false, m: {k477: false}, o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "bronze", score: 0.5, tier: "a", vip: false}], + [{b: 100, s: "b", nums: ["1", 2], score: true, items: [1, 2], tier: "gold", vip: true}, "!error"], + [{b: null, s: "Gold", nums: [], score: 100, items: [{price: 2.5, qty: 0.1, tag: "b"}, {price: -0.1, qty: 19.99, tag: null}, {price: 18, qty: 11, tag: "x"}], tier: "a", vip: false}, {items: [{price: 2.5, qty: 0.1, tag: "b"}, {price: -0.1, qty: 19.99, tag: null}, {price: 18, qty: 11, tag: "x"}], k476: 100, k478: "true", k479: 100, k480: "true", k484: false, m: {k477: true}, nums: [], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "Gold", score: 100, tier: "a", vip: false}], + [{b: 0.1, s: "a", nums: null, score: 101, tier: {t: "x"}, vip: true}, "!error"], + [{b: 19, nums: [], score: 18, items: [], tier: "b", vip: false}, {b: 19, items: [], k476: 19, k478: "false", k479: 19, k480: "true", k484: false, m: {k477: true}, nums: [], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, score: 18, tier: "b", vip: false}], + [{b: 99, s: "gold", nums: [], items: [{price: 1000000000000000000000, qty: 99, tag: "bronze"}], tier: true}, "!error"], + [{b: 0.5, s: "silver", nums: [], score: 73, items: [{price: 1000000000000000000000, qty: 1}, {price: null, qty: -0.1, tag: "bronze"}], tier: "gold ", vip: true, extra: [1, 2]}, {b: 0.5, extra: [1, 2], items: [{price: 1000000000000000000000, qty: 1}, {price: null, qty: -0.1, tag: "bronze"}], k476: 0.5, k478: "false", k479: 0.5, k480: "true", k484: false, m: {k477: true}, nums: [], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "silver", score: 73, tier: "gold ", vip: true}], + [{b: -25, s: "silver", nums: [5, 19.99, 1, 0, 1000], items: [{price: 0.5, qty: 7, tag: "a"}, {price: 1, qty: 2.5, tag: "silver"}], tier: "zz", vip: "no", extra: "e"}, {b: -25, extra: "e", items: [{price: 0.5, qty: 7, tag: "a"}, {price: 1, qty: 2.5, tag: "silver"}], k476: -25, k478: "false", k479: -25, k480: "true", k484: false, m: {k477: false}, nums: [5, 19.99, 1, 0, 1000], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "silver", tier: "zz", vip: "no"}], + [{s: "bronze", nums: [50, 72, 18, 1000000000000000000000, 101], score: 19.99, items: [{price: 3, qty: 19.99, tag: null}, {price: 2.5, qty: 7, tag: "bronze"}, {price: null, qty: -25, tag: "a"}, {price: 1, qty: 1000, tag: "a"}], tier: "b", vip: false}, {items: [{price: 3, qty: 19.99, tag: null}, {price: 2.5, qty: 7, tag: "bronze"}, {price: null, qty: -25, tag: "a"}, {price: 1, qty: 1000, tag: "a"}], k476: 19.99, k478: "false", k479: 19.99, k480: "true", k484: false, m: {k477: true}, nums: [50, 72, 18, 1000000000000000000000, 101], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "bronze", score: 19.99, tier: "b", vip: false}], + [{b: 99, s: "bronze", nums: [-0.1, 7], score: 99, items: [{price: 0.1, qty: 101, tag: ""}, {price: 99, qty: 10, tag: "gold "}], tier: "silver", vip: false}, {b: 99, items: [{price: 0.1, qty: 101, tag: ""}, {price: 99, qty: 10, tag: "gold "}], k476: 99, k478: "false", k479: 99, k480: "true", k484: false, m: {k477: true}, nums: [-0.1, 7], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "bronze", score: 99, tier: "silver", vip: false}], + [{b: 3, s: "x", nums: [], items: [{price: 99, qty: 99, tag: "gold "}], tier: "silver", vip: false}, {b: 3, items: [{price: 99, qty: 99, tag: "gold "}], k476: 3, k478: "false", k479: 3, k480: "true", k484: false, m: {k477: false}, nums: [], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "x", tier: "silver", vip: false}], + [{b: 5, s: "silver", nums: [120], score: 10, items: [{price: null, qty: null, tag: "bronze"}, {price: 0, qty: 99}, {price: 50, qty: 5, tag: "zz"}, {price: 10, tag: "zz"}], tier: "bronze", vip: false}, "!error"], + [{b: 7, s: "silver", nums: [21, 19.99], score: 0, items: [{price: 0.1, qty: 0.1, tag: "silver"}, {price: 99, qty: 7, tag: ""}], tier: "b", vip: null}, {b: 7, items: [{price: 0.1, qty: 0.1, tag: "silver"}, {price: 99, qty: 7, tag: ""}], k476: 7, k478: "false", k479: 7, k480: "true", k484: false, m: {k477: false}, nums: [21, 19.99], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "silver", score: 0, tier: "b"}], + [{b: 0, s: "zz", nums: [89, 100], score: 7, items: [{price: 10, qty: 100, tag: "bronze"}, {price: 1000000000000000000000, qty: 101, tag: "silver"}, {price: -1, qty: 2.5, tag: "gold"}], tier: "silver", vip: true}, {b: 0, items: [{price: 10, qty: 100, tag: "bronze"}, {price: 1000000000000000000000, qty: 101, tag: "silver"}, {price: -1, qty: 2.5, tag: "gold"}], k476: 0, k478: "false", k479: 0, k480: "true", k484: false, m: {k477: true}, nums: [89, 100], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "zz", score: 7, tier: "silver", vip: true}], + [{b: 0.5, nums: [7, 7], score: true, items: null, tier: "silver", vip: false}, "!error"], + [{b: 0.1, s: "a", nums: [10, 1, 1000000000000000000000], score: 50, items: [{price: 33, qty: 2.5, tag: "b"}, {price: 3, qty: 10, tag: ""}], tier: {t: "x"}, vip: true}, "!error"], + [{s: "a", nums: [18], items: [{price: 0.1, qty: 19.99, tag: "x"}, {price: 100, qty: 7, tag: "Gold"}, {price: 2, qty: 2, tag: "bronze"}, {price: 10, qty: 21}], tier: "gold ", vip: false}, {items: [{price: 0.1, qty: 19.99, tag: "x"}, {price: 100, qty: 7, tag: "Gold"}, {price: 2, qty: 2, tag: "bronze"}, {price: 10, qty: 21}], k476: 0, k478: "true", k480: "true", k484: true, m: {k477: false}, nums: [18], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "a", tier: "gold ", vip: false}], + [{b: true, s: "gold", nums: [], items: [{price: -25, qty: 2.5, tag: "x"}], tier: "silver", vip: "no"}, "!error"], + [{b: null, s: null, score: 11, tier: "x", vip: false}, "!error"], + [{s: "", nums: null, score: 3, items: [{price: -1, qty: 0, tag: "gold"}, {price: 1, qty: 99, tag: "a"}], tier: "Gold", vip: true}, {items: [{price: -1, qty: 0, tag: "gold"}, {price: 1, qty: 99, tag: "a"}], k476: 3, k478: "false", k479: 3, k480: "false", k484: false, m: {k477: false}, o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "", score: 3, tier: "Gold", vip: true}], + [{s: "silver", score: -0.1, items: [{price: -0.1, qty: 3, tag: "b"}, {price: 0.5, qty: null, tag: "gold"}, {price: 2, qty: 101, tag: "zz"}], vip: null, extra: "e"}, "!error"], + [{b: 2, s: "b", nums: [18, -25], score: 2.5, items: [], tier: "b", vip: true}, {b: 2, items: [], k476: 2, k478: "false", k479: 2, k480: "true", k484: false, m: {k477: true}, nums: [18, -25], o: {p: {g: {k486: "A-1"}}}, res: {k485: false}, s: "b", score: 2.5, tier: "b", vip: true}], + ], +} + +{ + name: "ga047: 4 nodes, expr, loop table, loop table, table", + graph: { + nodes: [ + {expression: "e1", outputPath: "res", fields: { + k487: "max([floor(cust.age), len((cust.tier ?? 'none'))]) * (cust.age ?? cust.age ?? 0)", + k488: "len('x')", + k489: "cust.age ?? vip", + }}, + {table: "t2", inputField: "items", executionMode: "loop", inputs: ["qty", "qty", "qty", null], outputs: ["k488", "k491"], outputPath: "res", rules: [ + ["null", "[0..10]", "<= 9", "'gold'", "10", "(tag ?? '?')"], + ["null", "[5..15]", "", "$ != null", "(price ?? 1)", "'low'"], + ["100, 105", "< 18", "5, 6", "true", "(qty ?? 0) * (price ?? 0)", "'mid'"], + ["< 10", "", "18", "", "1", "(tag ?? '') + '-' + string(len((tag ?? '?')))"], + ["", "", "", "", "100", "'gold'"], + ]}, + {table: "t3", inputField: "items", executionMode: "loop", inputs: ["price", "price"], outputs: ["k492", "k493"], passThrough: true, outputPath: "out", rules: [ + ["!= 50", "50, 100", "false", "100"], + ["null", "", "true", "-5"], + ["not(50)", "[21..26]", "false", "0.25"], + ["!= 0", "[-1..0)", "true", "0.25"], + ["< -1", "", "not (false)", "2"], + ["", "", "true", "0"], + ]}, + {table: "t4", inputs: ["'none'", "'x'", "0.5 * ceil(2.25)"], outputs: ["k494"], passThrough: true, rules: [ + ["startsWith($, 'g')", "not('a')", "[10..60)", "string(true)"], + ["startsWith($, 'x')", "", "5", "'low'"], + ["''", "'silver'", "", "'gold'"], + ["", "", "> 5", "''"], + ["", "", "", "'gold'"], + ]}, + ], + edges: [ + "input -> e1", + "input -> t2", + "input -> t3", + "t2 -> t4", + "e1 -> output", + "t3 -> output", + "t4 -> output", + ], + }, + cases: [ + [{cust: {age: 5, tier: "", active: "no"}, n: [1], items: [{price: 1000, qty: 1, tag: "b"}], vip: true, extra: 1}, {cust: {active: "no", age: 5, tier: ""}, extra: 1, items: [{price: 1000, qty: 1, tag: "b"}], k494: "gold", n: [1], out: [{k492: true, k493: 0, price: 1000, qty: 1, tag: "b"}], res: {k487: 25, k488: 1, k489: 5}, vip: true}], + [{n: 1, items: [{price: 2, qty: -25, tag: true}, {price: 1000, qty: -1, tag: "bronze"}, {price: 1, qty: -0.1, tag: "x"}], vip: false}, "!error"], + [{cust: [{age: 3}], n: 11, items: [{price: 106, qty: -1, tag: "zz"}, {price: 2, qty: 0.1, tag: true}, {price: 101, qty: 100, tag: ""}], vip: false}, "!error"], + [{cust: {age: 11, tier: "b", active: false}, n: 120, items: [], vip: null}, {cust: {active: false, age: 11, tier: "b"}, items: [], k494: "gold", n: 120, out: [], res: {k487: 121, k488: 1, k489: 11}}], + [{cust: "cust", n: 0, items: [{price: null, qty: 1000, tag: "gold"}], vip: true}, "!error"], + [{cust: null, n: [1], vip: false}, "!error"], + [{n: 10, vip: true}, "!error"], + [{cust: [], n: 2, items: [{price: 10, qty: 18, tag: ""}], vip: true}, "!error"], + [{cust: {age: 10, tier: "x", active: null}, n: 2, items: [{price: 100, qty: 50, tag: "Gold"}, {price: 21, qty: null, tag: null}, {price: -1, qty: 5, tag: "b"}], vip: true}, {cust: {active: null, age: 10, tier: "x"}, items: [{price: 100, qty: 50, tag: "Gold"}, {price: 21, qty: null, tag: null}, {price: -1, qty: 5, tag: "b"}], k494: "gold", n: 2, out: [{k492: false, k493: 100, price: 100, qty: 50, tag: "Gold"}, {k492: true, k493: 0, price: 21, qty: null, tag: null}, {k492: true, k493: 0.25, price: -1, qty: 5, tag: "b"}], res: {k487: 100, k488: 1, k489: 10}, vip: true}], + [{cust: {age: 10, tier: "gold", active: false}, n: 2.5, items: [{price: 19.99, qty: 18, tag: "gold"}], vip: false}, {cust: {active: false, age: 10, tier: "gold"}, items: [{price: 19.99, qty: 18, tag: "gold"}], k494: "gold", n: 2.5, out: [{k492: true, k493: 0, price: 19.99, qty: 18, tag: "gold"}], res: {k487: 100, k488: 1, k489: 10}, vip: false}], + [{cust: null, n: 18, items: [{price: 21, qty: 5, tag: null}, {price: 21, qty: 21, tag: "zz"}, {price: 0.5, qty: 5, tag: "x"}], vip: null, extra: [1, 2]}, "!error"], + [{cust: {age: 1000000000000000000000, tier: "a", active: true}, n: -0.1, items: [{price: 21, qty: 19.99, tag: "Gold"}], vip: true}, "!error"], + [{cust: {age: 73, tier: "Gold", active: null}, n: 100, items: [{price: 101, qty: -0.1, tag: "x"}], vip: false}, {cust: {active: null, age: 73, tier: "Gold"}, items: [{price: 101, qty: -0.1, tag: "x"}], k494: "gold", n: 100, out: [{k492: true, k493: 0, price: 101, qty: -0.1, tag: "x"}], res: {k487: 5329, k488: 1, k489: 73}, vip: false}], + [{cust: {age: null, tier: "zz"}, items: [1, 2], vip: true}, "!error"], + [{cust: {age: 101, active: false}, n: 2.5, items: [{price: 10, qty: 3, tag: ""}, {price: 10, qty: 25, tag: "Gold"}], vip: true, extra: 1}, {cust: {active: false, age: 101}, extra: 1, items: [{price: 10, qty: 3, tag: ""}, {price: 10, qty: 25, tag: "Gold"}], k494: "gold", n: 2.5, out: [{k492: true, k493: 0, price: 10, qty: 3, tag: ""}, {k492: true, k493: 0, price: 10, qty: 25, tag: "Gold"}], res: {k487: 10201, k488: 1, k489: 101}, vip: true}], + ], +} + +{ + name: "ga048: 5 nodes, expr, table, loop expr, switch, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "o.p", fields: { + k495: "lower(((items ?? [])[1].tag ?? '') + '!')", + k496: "-(len((code ?? ''))) % 7", + }}, + {table: "t2", inputs: ["code"], outputs: ["m.k497"], rules: [ + ["", "'gold'"], + ["startsWith($, 'g')", "'low'"], + ]}, + {expression: "e3", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k498: "tag ?? tag", + k499: "string(startsWith((tag ?? ''), 'g'))", + }}, + {switch: "s4", when: ["a == null", ""]}, + {table: "t5", inputs: ["3"], outputs: ["k500"], passThrough: true, rules: [ + ["$ > -1 and $ < 4", "10"], + ["(-1..4)", "0"], + ["21", "-5"], + ["!= 100", "0.5"], + ["!= 10", "1"], + ["", "0"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "input -> e3", + "e3 -> s4", + "s4:1 -> t5", + "t2 -> output", + "s4:0 -> output", + "t5 -> output", + ], + }, + cases: [ + [{n: 0, score: 3, nums: [7, -3], flag: true, items: [{price: 101, qty: 0.5, tag: "a"}, {price: 10, qty: 0.5, tag: "a"}], extra: "e"}, {m: {k497: "gold"}, res: [{k498: "a", k499: "false"}, {k498: "a", k499: "false"}]}], + [{n: 10, code: "silver", score: null, cust: {age: 7, active: true}, nums: [], flag: true, items: [{price: -1, qty: "abc", tag: ""}]}, {m: {k497: "gold"}, res: [{k498: "", k499: "false"}]}], + [{n: 50, score: 99, cust: {age: 19.99, tier: "zz", active: false}, nums: [1000, 101, -1], flag: true, items: [{price: 19.99, qty: -25, tag: "b"}, {price: 1000, qty: 3, tag: "a"}]}, {m: {k497: "gold"}, res: [{k498: "b", k499: "false"}, {k498: "a", k499: "false"}]}], + [{n: 101, code: "gold", score: null, cust: {age: 10, tier: "gold", active: true}, items: [{qty: 0.5, tag: "x"}, {price: 21, qty: null, tag: "zz"}]}, {m: {k497: "gold"}, res: [{k498: "x", k499: "false"}, {k498: "zz", k499: "false"}]}], + [{n: -1, code: true, score: {v: 1}, nums: [], flag: false, items: []}, "!error"], + [{n: -1, code: "", score: null, cust: {age: 101, tier: "", active: true}, nums: 7, flag: true, items: [{price: -0.1, qty: 7, tag: "Gold"}]}, {m: {k497: "gold"}, res: [{k498: "Gold", k499: "false"}]}], + [{n: -0.1, code: "gold", score: {v: 1}, cust: {age: null, tier: "a", active: false}, nums: [], flag: true, items: [{price: {v: 1}, qty: 37, tag: ""}, {price: -0.1, qty: 1000, tag: ""}]}, {m: {k497: "gold"}, res: [{k498: "", k499: "false"}, {k498: "", k499: "false"}]}], + [{n: null, code: "gold", score: {v: 1}, cust: {age: 1000, tier: "", active: true}, nums: [-0.1], flag: true, items: [{price: 0.5, qty: -1, tag: null}]}, {m: {k497: "gold"}, res: [{k498: null, k499: "false"}]}], + [{n: -25, code: "b", score: 0, cust: {active: false}, nums: [50, 7, 0.1], flag: false, items: [{price: 10, qty: 11, tag: ""}, {price: 7, qty: 21, tag: "a"}, {price: 2.5, qty: 50, tag: "x"}]}, {m: {k497: "gold"}, res: [{k498: "", k499: "false"}, {k498: "a", k499: "false"}, {k498: "x", k499: "false"}]}], + [{code: "gold", score: "abc", cust: {age: 2.5, tier: "zz", active: true}, nums: [100, 101, 2.5], flag: true, items: [{price: 50, qty: -0.1}, {price: -0.1, qty: -0.1}, {price: 11, qty: 19.99, tag: "gold "}]}, {m: {k497: "gold"}, res: [{k498: null, k499: "false"}, {k498: null, k499: "false"}, {k498: "gold ", k499: "true"}]}], + [{n: 2.5, code: "a", cust: {age: -25, tier: "a", active: false}, nums: [5, 2.5, 0.5, 1000, 0.1], flag: true, items: [{price: -0.1, qty: null, tag: "bronze"}, {price: -25, qty: -1, tag: "b"}]}, {m: {k497: "gold"}, res: [{k498: "bronze", k499: "false"}, {k498: "b", k499: "false"}]}], + [{n: 1000, code: "gold", score: 0.1, cust: {age: -25, tier: "bronze", active: false}, nums: [-0.1], flag: true, items: [{price: 10, qty: -25, tag: "bronze"}, {price: 3, tag: "b"}, {price: 101, qty: 90, tag: "Gold"}, {price: 5, qty: 48, tag: "silver"}]}, {m: {k497: "gold"}, res: [{k498: "bronze", k499: "false"}, {k498: "b", k499: "false"}, {k498: "Gold", k499: "false"}, {k498: "silver", k499: "false"}]}], + [{n: 11, code: "silver", score: -0.1, cust: {age: 0.5, tier: "", active: true}, nums: [10, 3, 19.99, 7, 101], flag: true, items: [{qty: 1, tag: "a"}]}, {m: {k497: "gold"}, res: [{k498: "a", k499: "false"}]}], + [{n: 0, code: "x", score: null, cust: {age: -25, tier: "gold", active: true}, nums: ["1", 2], flag: null, items: []}, {m: {k497: "gold"}, res: []}], + [{code: "Gold", score: 0.1, cust: {age: 5, tier: "gold ", active: true}, nums: [76, -14], flag: true, items: [{price: 10, qty: null, tag: "gold"}, {price: -25, qty: 50, tag: "gold "}, {price: 0.5, qty: 3, tag: "silver"}]}, {m: {k497: "gold"}, res: [{k498: "gold", k499: "true"}, {k498: "gold ", k499: "true"}, {k498: "silver", k499: "false"}]}], + [{n: 3, code: "bronze", score: 18, cust: {age: 7, tier: "gold", active: false}, nums: [1, 100, 0.5], flag: true, items: [{price: 3, qty: -0.1, tag: "gold"}, {price: 2.5, qty: 1}]}, {m: {k497: "gold"}, res: [{k498: "gold", k499: "true"}, {k498: null, k499: "false"}]}], + [{n: null, code: null, score: 50, cust: {age: -0.1, tier: "gold", active: true}, nums: [0.5], flag: null, items: null}, "!error"], + [{n: 2, code: "silver", score: 21, cust: {age: 101, tier: "zz", active: true}, nums: [], flag: false, items: [{price: 1000, qty: 2.5, tag: "silver"}, {price: 2.5, qty: 2, tag: "gold"}, {price: -0.1, qty: 50, tag: "gold "}], extra: {deep: {x: 1}}}, {m: {k497: "gold"}, res: [{k498: "silver", k499: "false"}, {k498: "gold", k499: "true"}, {k498: "gold ", k499: "true"}]}], + [{n: 18, code: "gold", score: 101, cust: {age: 10, tier: "silver", active: true}, nums: [0, 100, 99, 5, -25], items: []}, {m: {k497: "gold"}, res: []}], + [{code: "zz", cust: null, nums: [99, 1000000000000000000000, 11], flag: false, items: 3}, "!error"], + [{n: 2, code: "b", score: 1000, cust: {age: null, tier: "x", active: true}, nums: [7], flag: true, items: [{price: 0.5, qty: 2, tag: "x"}, {price: 5, qty: 50, tag: "silver"}, {price: 0, qty: -1, tag: "bronze"}, {price: 19.99, qty: 100, tag: null}], extra: [1, 2]}, {m: {k497: "gold"}, res: [{k498: "x", k499: "false"}, {k498: "silver", k499: "false"}, {k498: "bronze", k499: "false"}, {k498: null, k499: "false"}]}], + [{code: "bronze", score: 0.1, cust: {age: 7, tier: "b", active: true}, nums: null, flag: false, items: [{price: 18, qty: 21, tag: "a"}, {price: -1, qty: 1000, tag: "Gold"}]}, {m: {k497: "gold"}, res: [{k498: "a", k499: "false"}, {k498: "Gold", k499: "false"}]}], + [{n: 100, code: "a", score: 11, cust: {age: -25, tier: "Gold", active: true}, nums: [0, -25, 0.5, 7, -0.1], flag: false, items: null}, "!error"], + [{n: 10, code: true, score: 10, flag: false, items: [{price: 18, tag: "x"}, {price: 9, qty: 101, tag: "x"}]}, "!error"], + [{n: 0.1, code: "", score: 0.5, cust: {age: null, active: true}, nums: [], flag: "no", items: [{price: -25, qty: 18, tag: "gold "}, {price: 1, qty: 0.1, tag: "x"}, {price: 0, qty: -0.1, tag: "b"}]}, {m: {k497: "gold"}, res: [{k498: "gold ", k499: "true"}, {k498: "x", k499: "false"}, {k498: "b", k499: "false"}]}], + [{n: 50, code: "zz", score: 7, cust: {age: 7, tier: "b", active: true}, nums: [1000000000000000000000, 2, 19.99, -25, 0], flag: false, items: [{price: 19.99, tag: "x"}, {price: 3, qty: 21, tag: "a"}]}, {m: {k497: "gold"}, res: [{k498: "x", k499: "false"}, {k498: "a", k499: "false"}]}], + [{n: -25, code: null, score: 7, cust: [], nums: [7, 1000000000000000000000], flag: 0, items: [{price: 0.5, qty: -0.1, tag: null}, {price: 1000, qty: 5, tag: "silver"}, {price: -1, qty: 40}]}, {m: {k497: "gold"}, res: [{k498: null, k499: "false"}, {k498: "silver", k499: "false"}, {k498: null, k499: "false"}]}], + [{n: -0.1, code: null, score: 0, cust: {age: 5, tier: "b", active: null}, nums: [10], flag: false, items: [{price: 2, qty: 21, tag: "Gold"}, {price: -1, qty: 19.99, tag: "silver"}]}, {m: {k497: "gold"}, res: [{k498: "Gold", k499: "false"}, {k498: "silver", k499: "false"}]}], + ], +} + +{ + name: "ga049: 6 nodes, expr, expr, table, expr, table*, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k501: "not (price * 1 > min([-4, 1]))", + }}, + {expression: "e2", passThrough: true, fields: { + k502: "code == null", + k503: "price ?? code", + }}, + {table: "t3", inputs: ["a", "price", "(price in [1..100] ? (price ?? 1) * (price ?? 0) : floor((price ?? 1)))", null], outputs: ["res.k504"], rules: [ + ["$ > 1 and $ < 6", "$ > 100 and $ < 101", "50, 55", "true", "'low'"], + ["!= 1", ">= 21", "(-1..4)", "null", "'high'"], + ["", "", "", "", "'high'"], + ]}, + {expression: "e4", fields: { + k505: "(tier ?? '?')", + k506: "($.k505 ?? '?')", + k507: "string(round((price ?? 0))) + '-' + (code ?? '?') + '-' + trim((code ?? 'none'))", + }}, + {table: "t5", hit: "collect", inputs: ["len((res.k504 ?? '')) % 2", "((10))", "res.k504", null], outputs: ["k508", "k509"], passThrough: true, outputPath: "out", rules: [ + ["< 50", ">= -1", "$ != ''", "", "a != null", "'gold'"], + ["!= 5", ">= 5", "null", "'gold'", "false", "'high'"], + ["", "(100..105)", "startsWith($, 's')", "null", "false", "'high'"], + ["[0..50)", "<= 4", "'x'", "$ != null", "3 + 0 == ((2))", "((0 == 2.25) and ((false)) ? string(true) : (res.k504 ?? ''))"], + ["", "", "", "", "true", "''"], + ]}, + {expression: "e6", passThrough: true, fields: { + k510: "k507 ?? a", + "res.k511": "string(tier == null)", + k512: "upper('') + ' ' + (tier ?? 'none') + '' + (endsWith(cust.tier, 'x') ? tier + '-' + tier : string((price ?? 1)))", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> t3", + "e1 -> e4", + "t3 -> e4", + "t3 -> t5", + "e2 -> e6", + "e4 -> e6", + "t5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{a: 96, tier: "gold", cust: {age: 18, tier: "zz", active: true}, price: null}, "!error"], + [{a: 10, tier: "bronze", code: "x", cust: {age: -1, tier: "gold ", active: false}, price: 2}, {a: 10, code: "x", cust: {active: false, age: -1, tier: "gold "}, k501: false, k502: false, k503: 2, k505: "bronze", k506: "bronze", k507: "2-x-x", k510: "2-x-x", k512: " bronze2", out: [{k508: false, k509: "gold"}, {k508: true, k509: ""}], price: 2, res: {k504: "high", k511: "false"}, tier: "bronze"}], + [{a: 101, tier: "bronze", code: "gold", cust: {age: 1000, tier: "", active: false}, price: 0.1}, {a: 101, code: "gold", cust: {active: false, age: 1000, tier: ""}, k501: false, k502: false, k503: 0.1, k505: "bronze", k506: "bronze", k507: "0-gold-gold", k510: "0-gold-gold", k512: " bronze0.1", out: [{k508: false, k509: "gold"}, {k508: true, k509: ""}], price: 0.1, res: {k504: "high", k511: "false"}, tier: "bronze"}], + [{a: 5, tier: "zz", code: "gold", cust: null, price: 3}, "!error"], + [{a: null, tier: "bronze", code: "gold ", cust: {tier: "x", active: false}, price: null}, "!error"], + [{a: 3, tier: "x", cust: {age: -1, tier: "bronze", active: true}, price: null}, "!error"], + [{tier: "gold", code: "a", cust: {age: -1, tier: "a", active: false}, price: 0.5}, {code: "a", cust: {active: false, age: -1, tier: "a"}, k501: false, k502: false, k503: 0.5, k505: "gold", k506: "gold", k507: "1-a-a", k510: "1-a-a", k512: " gold0.5", out: [{k508: false, k509: "gold"}, {k508: true, k509: ""}], price: 0.5, res: {k504: "high", k511: "false"}, tier: "gold"}], + [{a: 18, tier: "gold ", code: "gold ", cust: {age: -0.1, tier: "zz", active: false}, price: -25}, {a: 18, code: "gold ", cust: {active: false, age: -0.1, tier: "zz"}, k501: true, k502: false, k503: -25, k505: "gold ", k506: "gold ", k507: "-25-gold -gold", k510: "-25-gold -gold", k512: " gold -25", out: [{k508: false, k509: "gold"}, {k508: true, k509: ""}], price: -25, res: {k504: "high", k511: "false"}, tier: "gold "}], + [{a: -0.1, code: "gold ", cust: {age: 11, tier: "gold ", active: false}, price: 11}, {a: -0.1, code: "gold ", cust: {active: false, age: 11, tier: "gold "}, k501: false, k502: false, k503: 11, k505: "?", k506: "?", k507: "11-gold -gold", k510: "11-gold -gold", k512: " none11", out: [{k508: false, k509: "gold"}, {k508: true, k509: ""}], price: 11, res: {k504: "high", k511: "true"}}], + [{a: 99, tier: "gold ", code: "bronze", cust: {age: 11, tier: "Gold", active: true}, price: 0.5}, {a: 99, code: "bronze", cust: {active: true, age: 11, tier: "Gold"}, k501: false, k502: false, k503: 0.5, k505: "gold ", k506: "gold ", k507: "1-bronze-bronze", k510: "1-bronze-bronze", k512: " gold 0.5", out: [{k508: false, k509: "gold"}, {k508: true, k509: ""}], price: 0.5, res: {k504: "high", k511: "false"}, tier: "gold "}], + [{tier: "bronze", code: null, price: null}, "!error"], + [{a: 18, tier: "gold ", code: "b", cust: {age: 1, tier: "silver", active: false}, price: 5}, {a: 18, code: "b", cust: {active: false, age: 1, tier: "silver"}, k501: false, k502: false, k503: 5, k505: "gold ", k506: "gold ", k507: "5-b-b", k510: "5-b-b", k512: " gold 5", out: [{k508: false, k509: "gold"}, {k508: true, k509: ""}], price: 5, res: {k504: "high", k511: "false"}, tier: "gold "}], + [{a: 0.1, tier: null, code: "silver", cust: {age: null, tier: "zz", active: true}, price: 0.5, extra: 1}, {a: 0.1, code: "silver", cust: {active: true, age: null, tier: "zz"}, extra: 1, k501: false, k502: false, k503: 0.5, k505: "?", k506: "?", k507: "1-silver-silver", k510: "1-silver-silver", k512: " none0.5", out: [{k508: false, k509: "gold"}, {k508: true, k509: ""}], price: 0.5, res: {k504: "high", k511: "true"}}], + [{tier: "x", code: "gold", price: 50, extra: 1}, "!error"], + ], +} + +{ + name: "ga050: 4 nodes, expr, switch*, switch, table", + graph: { + nodes: [ + {expression: "e1", fields: { + k513: "(price ?? price ?? 0) * (score ?? price ?? 0) * (endsWith((s ?? 'none'), 'a') ? 10 : -(score))", + k514: "len((code ?? '')) + ($.k513 ?? 0) >= (score ?? -1)", + k515: "$.k513 * (score ?? 0) * $.k513 * (b ?? 0)", + }}, + {switch: "s2", hit: "collect", when: ["code + ' ' + (code ?? '') == 'silver'", "not (0 in [-5..5])"]}, + {switch: "s3", when: ["(len('x') > (k513 ?? k513 ?? 0)) or ((false) and (k514))", "(k514 ?? false)", "false", ""]}, + {table: "t4", inputs: ["k513", "k513"], outputs: ["k516"], rules: [ + ["$ > 21 and $ < 26", "18", "string((0 % 2))"], + ["> 100", "10", "''"], + ["", "", "'low'"], + ]}, + ], + edges: [ + "input -> e1", + "input -> s2", + "e1 -> s3", + "s3:0 -> t4", + "s3:1 -> t4", + "s2:0 -> output", + "s3:2 -> output", + "t4 -> output", + ], + }, + cases: [ + [{score: 2.5, price: 0.1, n: 3, cust: null, s: "silver", code: "", b: 5}, {k516: "low"}], + [{score: -1, price: 11, n: 100, cust: {age: 50, tier: "a", active: true}, s: "silver", code: "gold ", b: 29}, {k516: "low"}], + [{score: -1, price: 99, n: -18, cust: {age: null, tier: "silver", active: true}, s: "b", code: "silver", b: -1}, {k516: "low"}], + [{score: 101, price: 18, n: 10, code: "gold ", b: -25}, {k516: "low"}], + [{score: null, price: 1000000000000000000000, n: 1, cust: {age: -0.1, tier: "bronze", active: false}, s: "b", code: "Gold", b: 1000000000000000000000}, "!error"], + [{score: 0.1, price: 0.5, n: 104, cust: {age: 7, tier: "silver", active: false}, s: "zz", code: "bronze", b: -0.1}, {k516: "low"}], + [{score: null, price: 50, n: 1000000000000000000000, cust: {age: 1, active: false}, s: "a", code: null, b: 100}, {k516: "low"}], + [{score: 2, price: 5, n: 5, cust: {age: -0.1, tier: "gold", active: false}, code: "Gold", b: 2.5}, {k516: "low"}], + [{score: 19.99, price: 101, cust: {age: -0.1, tier: "b", active: true}, s: "silver", code: "Gold", b: 99}, {k516: "low"}], + [{price: 0.5, n: 1000, cust: null, s: "gold ", code: null, b: 2.5, extra: {deep: {x: 1}}}, "!error"], + [{score: 1, price: 101, n: null, cust: {age: 99, tier: "Gold", active: true}, code: "gold ", b: 1000000000000000000000}, {k516: "low"}], + [{score: 21, price: 11, n: 2.5, cust: {age: 7, tier: "silver", active: true}, s: "", code: "gold", b: 50}, {k516: "low"}], + [{score: 19.99, price: 35, n: 101, cust: {age: 100, tier: "", active: true}, code: "Gold", b: -25, extra: 1}, {k516: "low"}], + [{score: 3, price: 5, n: 11, cust: {age: 5, tier: "gold", active: true}, s: "gold ", code: "bronze", b: 12, extra: [1, 2]}, {k516: "low"}], + [{score: 116, price: 3, n: -0.1, cust: {age: 100, tier: "gold ", active: false}, s: "", code: "gold", b: 7}, {k516: "low"}], + [{price: 11, n: 1, cust: {age: -1, tier: "gold ", active: false}, s: "", code: "zz", b: null}, "!error"], + [{score: 1000000000000000000000, price: 99, n: 21, cust: {age: null, tier: "Gold", active: false}, s: "x", code: "silver", b: 1}, "!error"], + [{score: 0, price: null, n: null, cust: {age: 7, tier: "silver", active: true}, s: "gold ", code: "a", b: null}, {k516: "low"}], + [{score: 18, price: -1, n: -1, cust: {age: 1000000000000000000000, tier: "b", active: true}, s: "bronze", code: null, b: 1000}, {k516: "low"}], + [{score: 1, price: 2, n: 10, cust: {age: -1, active: true}, s: "x", code: "zz", b: 7}, {k516: "low"}], + [{score: 7, price: null, n: 21, cust: {age: -0.1, tier: "b", active: false}, s: "zz", code: "Gold", b: 2.5}, {k516: "low"}], + [{score: 3, price: 0.5, n: 5, cust: {age: 18, tier: "silver"}, s: "bronze", code: "gold ", b: 1000}, {k516: "low"}], + [{score: 18, price: 100, n: 1000000000000000000000, cust: {age: -1, tier: "x", active: false}, s: "gold"}, {k516: "low"}], + [{score: 101, price: 30, n: 21, cust: {age: 0.1, tier: "a", active: true}, s: "gold", code: "silver", b: 10}, {k516: "low"}], + [{score: null, price: 2, cust: {age: 1000000000000000000000, tier: "silver", active: false}, s: "silver", code: "zz", b: 11}, "!error"], + [{score: 11, price: 2.5, n: 7, cust: {age: -3, tier: "gold", active: false}, s: "gold ", code: "x", b: null}, {k516: "low"}], + ], +} + +{ + name: "ga051: 8 nodes, expr, expr, expr, expr, switch, expr, table, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "out", fields: { + k517: "a ?? s", + "g.k518": "score ?? vip", + k519: "upper(string(3)) != 'gold'", + }}, + {expression: "e2", passThrough: true, fields: { + k520: "(score) / 2", + }}, + {expression: "e3", fields: { + "g.k521": "(score ?? 0)", + }}, + {expression: "e4", passThrough: true, fields: { + k522: "(score == null) or ((((vip ?? false)) or (false)) and (vip))", + k523: "trim(s) + '-' + ($nodes.e1.k519 ? (s ?? '') : 'gold') in ['gold', 'silver', 'a']", + "m.k524": "((flag ?? false))", + }}, + {switch: "s5", when: ["(a % 7) >= (a ?? 1)"]}, + {expression: "e6", fields: { + k525: "n", + "m.k524": "out.k519 ?? vip", + "g.k527": "(s ?? '')", + k528: "((score ?? -1) - -4 < (n ?? -1))", + }}, + {table: "t7", inputs: ["s", "string((vip ?? false)) + '' + string((out.k519 ?? false))"], outputs: ["k529", "k517"], passThrough: true, rules: [ + ["", "'gold'", "(k522 ?? false)", "'high'"], + ["startsWith($, 's')", "$ != 'gold'", "false", "'mid'"], + ["", "", "score != null", "'high'"], + ["'gold', 'b'", "", "false", "((vip ?? false) ? `n=${-4}-${(s ?? '')}` : trim((s ?? '?') + '-' + s))"], + ["$ != ''", "$ != ''", "true", "'high'"], + ["startsWith($, 's')", "startsWith($, '')", "false", "'high'"], + ]}, + {expression: "e8", passThrough: true, fields: { + k531: "(((vip ?? false) ? ((a ?? 1)) : 10)) / 3", + k532: "-((n ?? 0) * (k520 ?? 0) % 2)", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "e1 -> e3", + "e1 -> e4", + "input -> e4", + "e2 -> s5", + "s5:0 -> e6", + "e4 -> t7", + "s5:0 -> e8", + "e3 -> output", + "e6 -> output", + "t7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{n: 50, a: 2, s: "x", score: 19.99, flag: true}, "!error"], + [{n: 1000, a: 99, s: "gold ", vip: true, score: 19.99, flag: false, extra: {deep: {x: 1}}}, "!error"], + [{n: 1, a: 50, s: "bronze", score: null, flag: true}, "!error"], + [{n: 1, a: 1000, s: null, vip: false, score: 21, flag: false}, "!error"], + [{n: 19.99, s: "x", vip: true, score: null, flag: false, extra: 1}, "!error"], + [{n: 17, a: 3, s: "gold", vip: false, score: 100, flag: true}, "!error"], + [{s: "bronze", vip: true, score: 21, flag: false}, "!error"], + [{n: 10, a: null, vip: false, score: null, flag: false}, "!error"], + [{n: -0.1, a: 19.99, s: "b", vip: null, score: 7, flag: true}, "!error"], + [{n: 0.5, s: null, score: 0, flag: true}, "!error"], + [{n: 0.1, a: 5, s: "bronze", vip: false, score: 2.5, flag: false, extra: [1, 2]}, "!error"], + [{n: 100, a: 18, vip: false, score: 0.5, flag: true}, "!error"], + [{n: 21, a: 100, s: "x", vip: false, score: 0.1, flag: true}, "!error"], + [{n: 1000000000000000000000, a: -25, s: "gold ", vip: false, score: 0.5, flag: false, extra: {deep: {x: 1}}}, "!error"], + [{n: 1, a: 1000000000000000000000, s: "", flag: null, extra: {deep: {x: 1}}}, "!error"], + [{n: 0.5, a: 11, s: "gold", vip: true, score: 3, flag: false}, "!error"], + [{n: 0, a: -25, s: "gold ", vip: false, score: -0.1, extra: "e"}, "!error"], + ], +} + +{ + name: "ga052: 5 nodes, loop expr, expr, expr, table, table", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "out", fields: { + "res.k533": "price", + k534: "tag", + k535: "(qty ?? price ?? 0)", + k536: "(qty ?? qty ?? 0)", + }}, + {expression: "e2", fields: { + k537: "(price ?? 1) % 3", + }}, + {expression: "e3", passThrough: true, fields: { + k538: "code ?? code", + k539: "vip ?? price", + k540: "string((price ?? 1))", + k541: "(code ?? '')", + }}, + {table: "t4", inputs: ["k537"], outputs: ["k542"], passThrough: true, rules: [ + ["(0..5)", "true"], + ["21, 22", "true"], + ["", "false"], + ["<= 9", "true"], + ]}, + {table: "t5", inputField: "cust", inputs: ["age", "tier", "age"], outputs: ["k543"], passThrough: true, outputPath: "res", rules: [ + ["", "$ != 'a'", "$ > 10 and $ < 20", "'mid'"], + ["18", "not('silver')", "[100..110)", "''"], + ["> 100", "", "[1..51]", "'mid'"], + ["< 5", "", "null", "'gold'"], + ["10", "''", "not(21)", "((age ?? 1) + (age ?? -1) > (age ?? -1) ? string(((active ?? false)) and (false)) : tier)"], + ["5, 15", "", "", "'low'"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> e3", + "e2 -> t4", + "e3 -> t5", + "e2 -> output", + "t4 -> output", + "t5 -> output", + ], + }, + cases: [ + [{code: "a", price: 7, items: [{price: 0.5, qty: 7, tag: "gold"}], nums: [10, 1000, 1], cust: {age: 3, tier: "silver", active: "no"}, vip: false}, {code: "a", cust: {active: "no", age: 3, tier: "silver"}, items: [{price: 0.5, qty: 7, tag: "gold"}], k537: 1, k538: "a", k539: false, k540: "7", k541: "a", k542: true, nums: [10, 1000, 1], price: 7, vip: false}], + [{code: "Gold", price: null, items: [], nums: [], cust: {age: 11, active: true}, vip: true}, {code: "Gold", cust: {active: true, age: 11}, items: [], k537: 1, k538: "Gold", k539: true, k540: "1", k541: "Gold", k542: true, nums: [], res: {k543: "mid"}, vip: true}], + [{code: "b", price: 0.1, items: [{price: 3, qty: 101, tag: "gold"}, {price: 101, qty: 11, tag: "a"}, {qty: 0.5, tag: "Gold"}, {price: [1], qty: 29}], nums: null, cust: {age: 100, tier: "silver", active: false}, vip: false}, {code: "b", cust: {active: false, age: 100, tier: "silver"}, items: [{price: 3, qty: 101, tag: "gold"}, {price: 101, qty: 11, tag: "a"}, {qty: 0.5, tag: "Gold"}, {price: [1], qty: 29}], k537: 0.1, k538: "b", k539: false, k540: "0.1", k541: "b", k542: true, price: 0.1, vip: false}], + [{code: "", price: 88, items: [{price: 100, qty: 19.99, tag: "gold "}], nums: [2], vip: false}, {code: "", items: [{price: 100, qty: 19.99, tag: "gold "}], k537: 1, k538: "", k539: false, k540: "88", k541: "", k542: true, nums: [2], price: 88, vip: false}], + [{code: {t: "x"}, price: -25, items: [{price: 1, qty: 0.5, tag: "silver"}], nums: [61, 2.5, -0.1], cust: null, vip: false}, {code: {t: "x"}, items: [{price: 1, qty: 0.5, tag: "silver"}], k537: -1, k538: {t: "x"}, k539: false, k540: "-25", k541: {t: "x"}, k542: false, nums: [61, 2.5, -0.1], price: -25, vip: false}], + [{code: "a", price: 18, items: [{price: 100, qty: 7, tag: "b"}], nums: [], cust: {age: 1000, tier: "", active: false}, vip: false}, {code: "a", cust: {active: false, age: 1000, tier: ""}, items: [{price: 100, qty: 7, tag: "b"}], k537: 0, k538: "a", k539: false, k540: "18", k541: "a", k542: false, nums: [], price: 18, vip: false}], + [{code: "zz", price: 19.99, items: [{price: 18, qty: 18, tag: "zz"}, {price: 2.5, qty: 3}], nums: [7, 21, 0, 101, -0.1], cust: {age: 24, tier: "gold ", active: false}, vip: true}, {code: "zz", cust: {active: false, age: 24, tier: "gold "}, items: [{price: 18, qty: 18, tag: "zz"}, {price: 2.5, qty: 3}], k537: 1.99, k538: "zz", k539: true, k540: "19.99", k541: "zz", k542: true, nums: [7, 21, 0, 101, -0.1], price: 19.99, vip: true}], + [{code: "x", price: 3, items: [{price: -0.1, qty: 19.99, tag: "zz"}, {price: 101, qty: 7, tag: "Gold"}], nums: null, cust: {age: -0.1, active: true}, vip: true}, {code: "x", cust: {active: true, age: -0.1}, items: [{price: -0.1, qty: 19.99, tag: "zz"}, {price: 101, qty: 7, tag: "Gold"}], k537: 0, k538: "x", k539: true, k540: "3", k541: "x", k542: false, price: 3, vip: true}], + [{code: "zz", price: -25, items: [{price: 2.5, qty: 101, tag: ""}, {price: 5, qty: -1, tag: ""}], nums: [18, 1, 0.5], cust: {tier: "bronze", active: true}}, {code: "zz", cust: {active: true, tier: "bronze"}, items: [{price: 2.5, qty: 101, tag: ""}, {price: 5, qty: -1, tag: ""}], k537: -1, k538: "zz", k539: -25, k540: "-25", k541: "zz", k542: false, nums: [18, 1, 0.5], price: -25}], + [{code: "", price: -0.1, items: [{qty: 1000000000000000000000, tag: null}, {price: 0, qty: 21, tag: "gold"}, {qty: -0.1, tag: "zz"}, {price: 99, qty: 87, tag: "Gold"}], nums: [], cust: [{age: 3}], vip: false}, {code: "", cust: [{age: 3}], items: [{qty: 1000000000000000000000, tag: null}, {price: 0, qty: 21, tag: "gold"}, {qty: -0.1, tag: "zz"}, {price: 99, qty: 87, tag: "Gold"}], k537: -0.1, k538: "", k539: false, k540: "-0.1", k541: "", k542: false, nums: [], price: -0.1, vip: false}], + [{code: "a", price: 19.99, items: [{price: 19.99, qty: -0.1, tag: "a"}, {price: 99, qty: 1, tag: "x"}, {price: 19.99, qty: 3, tag: "bronze"}, {qty: -0.1, tag: "a"}], nums: [-25, 99], cust: {age: 5, tier: "gold ", active: true}, vip: true}, {code: "a", cust: {active: true, age: 5, tier: "gold "}, items: [{price: 19.99, qty: -0.1, tag: "a"}, {price: 99, qty: 1, tag: "x"}, {price: 19.99, qty: 3, tag: "bronze"}, {qty: -0.1, tag: "a"}], k537: 1.99, k538: "a", k539: true, k540: "19.99", k541: "a", k542: true, nums: [-25, 99], price: 19.99, res: {k543: "low"}, vip: true}], + [{code: "silver", price: 5, items: [{price: -1, qty: 0.5, tag: "b"}, {price: null, qty: 99, tag: "gold "}], nums: [99, 3, 21], cust: [], vip: false}, {code: "silver", cust: [], items: [{price: -1, qty: 0.5, tag: "b"}, {price: null, qty: 99, tag: "gold "}], k537: 2, k538: "silver", k539: false, k540: "5", k541: "silver", k542: true, nums: [99, 3, 21], price: 5, vip: false}], + [{code: "gold", nums: [0, 5], cust: {active: true}, vip: true}, "!error"], + [{code: "gold ", nums: [1, 114, 7, 5, 101], cust: {age: 5, tier: "a", active: true}, vip: false}, "!error"], + [{code: "gold ", price: null, items: [1, 2], nums: [2.5, 28, 2.5], cust: {age: 0.5, tier: "silver", active: true}, vip: true}, "!error"], + [{code: "b", price: 0, items: [], nums: [2], cust: null, vip: true}, {code: "b", items: [], k537: 0, k538: "b", k539: true, k540: "0", k541: "b", k542: false, nums: [2], price: 0, vip: true}], + [{code: "Gold", price: true, items: [{price: 1000, qty: 19.99, tag: "zz"}, {price: 10, qty: 1, tag: "silver"}, {price: 11, tag: "b"}, {price: 0.5, qty: -25, tag: "Gold"}], nums: [21, 99], cust: {age: 5, tier: "bronze", active: false}, vip: false}, "!error"], + [{code: "x", price: 101, items: [{price: 1000, qty: 0.1, tag: "bronze"}, {price: 21, qty: 99, tag: "Gold"}], cust: {age: null, tier: "Gold", active: null}, vip: false}, {code: "x", cust: {active: null, age: null, tier: "Gold"}, items: [{price: 1000, qty: 0.1, tag: "bronze"}, {price: 21, qty: 99, tag: "Gold"}], k537: 2, k538: "x", k539: false, k540: "101", k541: "x", k542: true, price: 101, vip: false}], + [{code: "bronze", price: 2.5, items: [{price: 0.5, qty: 1000, tag: "gold "}, {price: 57, qty: 7}, {price: 2, qty: 11, tag: "x"}, {price: null, qty: 1, tag: ""}], nums: [-25], cust: 5, vip: true}, {code: "bronze", cust: 5, items: [{price: 0.5, qty: 1000, tag: "gold "}, {price: 57, qty: 7}, {price: 2, qty: 11, tag: "x"}, {price: null, qty: 1, tag: ""}], k537: 2.5, k538: "bronze", k539: true, k540: "2.5", k541: "bronze", k542: true, nums: [-25], price: 2.5, vip: true}], + [{code: "gold ", items: [{qty: 99, tag: "gold"}], nums: [2.5], cust: null, vip: false}, {code: "gold ", items: [{qty: 99, tag: "gold"}], k537: 1, k538: "gold ", k539: false, k540: "1", k541: "gold ", k542: true, nums: [2.5], vip: false}], + [{code: "b", price: 5, items: {price: 1}, nums: [], cust: {age: 1000, tier: "silver", active: true}, vip: true}, "!error"], + [{code: null, price: 0.5, items: [{price: 69, qty: -1, tag: "b"}, {price: 1000000000000000000000, qty: 19.99, tag: "gold "}, {price: 50, qty: 5, tag: "gold"}, {price: 18, qty: 19.99, tag: "Gold"}], nums: null, cust: {age: 1000000000000000000000, tier: "silver", active: true}, vip: null, extra: 1}, {cust: {active: true, age: 1000000000000000000000, tier: "silver"}, extra: 1, items: [{price: 69, qty: -1, tag: "b"}, {price: 1000000000000000000000, qty: 19.99, tag: "gold "}, {price: 50, qty: 5, tag: "gold"}, {price: 18, qty: 19.99, tag: "Gold"}], k537: 0.5, k539: 0.5, k540: "0.5", k541: "", k542: true, price: 0.5}], + ], +} + +{ + name: "ga053: 8 nodes, expr, switch*, table*, expr, expr, switch, table*, table*", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k544: "b ?? b", + "res.k545": "floor(b) + len(string(false))", + k546: "-((b ?? 0) * 100)", + }}, + {switch: "s2", hit: "collect", when: ["false", ""]}, + {table: "t3", hit: "collect", inputs: ["price", "string(false)"], outputs: ["k547", "k548"], passThrough: true, outputPath: "res", rules: [ + ["[50..55]", "", "endsWith('x', 'x')", "true"], + ["null", "'gold'", "true", "true"], + ["<= 60", "null", "price != null", "false"], + ]}, + {expression: "e4", passThrough: true, outputPath: "out", fields: { + k549: "len('')", + }}, + {expression: "e5", passThrough: true, fields: { + k549: "vip ?? b", + k551: "vip ?? score", + k552: "2", + }}, + {switch: "s6", when: ["not (false)"]}, + {table: "t7", hit: "collect", inputs: ["k546", "score"], outputs: ["g.k553", "k554"], passThrough: true, outputPath: "lines", rules: [ + ["< 1", "$ > 18 and $ < 28", "'high'", "''"], + ["[5..55]", "not(1)", "'' + '-' + upper('none')", "'high'"], + [">= 0", "> -1", "''", "''"], + ["21, 26", "not(18)", "'mid'", "string((k546 ?? -1)) + ' ' + ((vip ?? false) ? 'x' : 'gold') + '' + ''"], + ["not(10)", "!= 1", "'high'", "''"], + ["5, 55", "not(18)", "'low'", "'low'"], + ]}, + {table: "t8", hit: "collect", inputs: ["out.k549", "vip", "b"], outputs: ["k555[]", "k556"], passThrough: true, outputPath: "out", rules: [ + ["1", "true", ">= 0", "0.25", "100"], + ["!= 50", "null", "", "2", "2"], + ["[-1..49)", "", ">= 18", "10", "2"], + ["(10..20)", "$ == true", "$ > 21 and $ < 71", "10", "10"], + ]}, + ], + edges: [ + "input -> e1", + "input -> s2", + "e1 -> s2", + "input -> t3", + "t3 -> e4", + "t3 -> e5", + "e5 -> s6", + "e4 -> s6", + "e5 -> t7", + "e1 -> t7", + "t7 -> t8", + "e4 -> t8", + "s2:0 -> output", + "s6:0 -> output", + "t8 -> output", + ], + }, + cases: [ + [{vip: false, score: 0, b: 18, price: 1000000000000000000000}, {b: 18, k544: 18, k546: -1800, k549: false, k551: false, k552: 2, lines: [], out: {k549: 0}, price: 1000000000000000000000, res: [], score: 0, vip: false}], + [{vip: true, score: null, b: 101}, {b: 101, k544: 101, k546: -10100, k549: true, k551: true, k552: 2, lines: [], out: {k549: 0}, res: [], vip: true}], + [{vip: false, score: true, b: 0.5, price: 55}, {b: 0.5, k544: 0.5, k546: -50.0, k549: false, k551: false, k552: 2, lines: [], out: {k549: 0}, price: 55, res: [{k547: true, k548: true}], score: true, vip: false}], + [{vip: false, score: 21, b: -25, price: true, extra: [1, 2]}, {b: -25, extra: [1, 2], k544: -25, k546: 2500, k549: false, k551: false, k552: 2, lines: [{g: {k553: ""}, k554: ""}], out: {k549: 0}, price: true, res: [], score: 21, vip: false}], + [{vip: false, score: 0.5, b: 19.99, price: 0.1}, {b: 19.99, k544: 19.99, k546: -1999.00, k549: false, k551: false, k552: 2, lines: [], out: {k549: 0}, price: 0.1, res: [], score: 0.5, vip: false}], + [{vip: false, score: 3, b: [1], price: 0.1}, "!error"], + [{vip: null, score: null, b: 100, price: {v: 1}}, {b: 100, k544: 100, k546: -10000, k549: 100, k552: 2, lines: [], out: {k549: 0}, price: {v: 1}, res: []}], + [{vip: null, score: 5, b: 5, price: 0.5}, {b: 5, k544: 5, k546: -500, k549: 5, k551: 5, k552: 2, lines: [], out: {k549: 0}, price: 0.5, res: [], score: 5}], + [{vip: true, score: 10, b: {v: 1}, price: 101}, "!error"], + [{vip: null, score: -0.1, b: 0, price: 18}, {b: 0, k544: 0, k546: -0, k549: 0, k551: -0.1, k552: 2, lines: [{g: {k553: ""}, k554: ""}], out: {k549: 0}, price: 18, res: [], score: -0.1}], + [{score: 100, b: -0.1, price: 0.1}, {b: -0.1, k544: -0.1, k546: 10.0, k549: -0.1, k551: 100, k552: 2, lines: [{g: {k553: ""}, k554: ""}], out: {k549: 0}, price: 0.1, res: [], score: 100}], + [{vip: null, b: -25, price: 2}, {b: -25, k544: -25, k546: 2500, k549: -25, k552: 2, lines: [], out: {k549: 0}, price: 2, res: []}], + [{vip: false, score: 101, b: 101, price: 19.99}, {b: 101, k544: 101, k546: -10100, k549: false, k551: false, k552: 2, lines: [], out: {k549: 0}, price: 19.99, res: [], score: 101, vip: false}], + [{score: 50}, "!error"], + [{vip: null, score: -25, b: -0.1, price: 2}, {b: -0.1, k544: -0.1, k546: 10.0, k549: -0.1, k551: -25, k552: 2, lines: [], out: {k549: 0}, price: 2, res: [], score: -25}], + [{vip: null, score: 19.99, b: 34, price: 21}, {b: 34, k544: 34, k546: -3400, k549: 34, k551: 19.99, k552: 2, lines: [{g: {k553: "high"}, k554: ""}], out: {k549: 0}, price: 21, res: [], score: 19.99}], + [{vip: true, score: [1], b: 1, price: -25}, {b: 1, k544: 1, k546: -100, k549: true, k551: true, k552: 2, lines: [], out: {k549: 0}, price: -25, res: [], score: [1], vip: true}], + [{vip: null, score: {v: 1}, b: {v: 1}, price: {v: 1}}, "!error"], + [{vip: true, score: null, b: 99, price: null}, {b: 99, k544: 99, k546: -9900, k549: true, k551: true, k552: 2, lines: [], out: {k549: 0}, res: [], vip: true}], + [{vip: 1, score: 21, b: -25, price: 101}, {b: -25, k544: -25, k546: 2500, k549: 1, k551: 1, k552: 2, lines: [{g: {k553: ""}, k554: ""}], out: {k549: 0}, price: 101, res: [], score: 21, vip: 1}], + [{vip: false, score: 99, b: 11, price: [1]}, {b: 11, k544: 11, k546: -1100, k549: false, k551: false, k552: 2, lines: [], out: {k549: 0}, price: [1], res: [], score: 99, vip: false}], + [{vip: false, score: "abc", price: "5", extra: 1}, "!error"], + [{vip: true, score: 0.1, b: 10, price: true}, {b: 10, k544: 10, k546: -1000, k549: true, k551: true, k552: 2, lines: [], out: {k549: 0}, price: true, res: [], score: 0.1, vip: true}], + [{vip: false, score: 0.1, b: 31, price: 1000000000000000000000}, {b: 31, k544: 31, k546: -3100, k549: false, k551: false, k552: 2, lines: [], out: {k549: 0}, price: 1000000000000000000000, res: [], score: 0.1, vip: false}], + [{vip: true, score: 99, b: null, price: -25}, "!error"], + ], +} + +{ + name: "ga054: 5 nodes, table*, expr, expr, expr, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["s", "vip", "b", null], outputs: ["k557"], outputPath: "res", rules: [ + ["", "null", "[5..15]", "$ != null", "(b ?? 0) * len(trim((code ?? '?')))"], + ["startsWith($, 'x')", "", "[1..6)", "null", "(b ?? 1)"], + ["", "false", "not(50)", "'gold'", "10"], + ["", "false", "-1", "null", "100"], + ["", "", "", "", "0"], + ]}, + {expression: "e2", inputField: "cust", passThrough: true, outputPath: "out", fields: { + k557: "active ?? active", + k559: "(age ?? age ?? 0) * (age)", + k560: "((active ?? false) ? tier : (tier ?? 'none'))", + }}, + {expression: "e3", fields: { + "g.k561": "true", + }}, + {expression: "e4", outputPath: "lines", fields: { + k562: "(0 > out.k559) and ((b ?? 0) - (cust.age ?? 0) >= len('gold'))", + k560: "$.k562 ?? code", + k564: "(out.k559 ?? 1)", + k565: "vip", + }}, + {expression: "e5", outputPath: "out", fields: { + k566: "true", + k567: "(0 ?? 1 ?? 0)", + k568: "true", + "m.k569": "(100 + ($.k567 ?? 0) <= min([-4, 1])) and (true)", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "t1 -> e3", + "e2 -> e4", + "t1 -> e5", + "e3 -> output", + "e4 -> output", + "e5 -> output", + ], + }, + cases: [ + [{cust: {age: 1, tier: "gold", active: false}, flag: true, code: "x", b: 1, vip: false, s: "x"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 1, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 18, active: false}, flag: true, code: "zz", b: 0.5, vip: false, s: ""}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 324, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: -1, tier: "gold", active: true}, flag: false, code: null, b: 10, vip: null, s: "silver"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 1, k565: null}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 11, tier: "Gold", active: true}, flag: true, code: "x", b: -1, vip: false, s: "silver"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 121, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: -1, tier: "gold", active: true}, flag: true, code: "silver", b: 39, vip: false, s: "gold"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 1, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {tier: "zz", active: null}, flag: false, code: "gold ", b: 5, vip: false, s: "Gold"}, "!error"], + [{cust: {age: 0.1, tier: "zz", active: false}, flag: false, code: "silver", b: 10, vip: null}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 0.01, k565: null}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 101, tier: "silver", active: false}, flag: true, code: "", b: 12, vip: false, s: "Gold"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 10201, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 0.5, tier: "gold", active: true}, flag: true, code: "Gold", b: 21, vip: false, s: "silver"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 0.25, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{flag: false, code: "gold", b: null, vip: true, s: "Gold"}, "!error"], + [{cust: {age: 105, tier: "a", active: true}, code: "x", b: 101, s: "b"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 11025, k565: null}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 100, tier: "silver", active: true}, flag: true, code: "gold ", b: 0.5, vip: false, s: "gold"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 10000, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 89, tier: "", active: true}, flag: true, code: "", b: 0.5, vip: true}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 7921, k565: true}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 93, tier: "silver", active: true}, flag: null, b: 0, vip: true, s: "x", extra: [1, 2]}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 8649, k565: true}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 11, tier: "b", active: false}, flag: true, code: "zz", b: 100, vip: true, s: ""}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 121, k565: true}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: -0.1, active: true}, flag: true, code: "a", vip: false, s: null}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 0.01, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 100, tier: "zz", active: true}, flag: true, code: "gold", b: 5}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 10000, k565: null}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{flag: false, code: "", b: 1000, vip: false, s: "b"}, "!error"], + [{cust: {age: 50, tier: "Gold", active: false}, flag: false, code: "silver", b: 18, vip: false, s: "a"}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 2500, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + [{cust: {age: 100, tier: "gold", active: false}, flag: null, code: "silver", vip: false, s: ""}, {g: {k561: true}, lines: {k560: false, k562: false, k564: 10000, k565: false}, out: {k566: true, k567: 0, k568: true, m: {k569: false}}}], + ], +} + +{ + name: "ga055: 8 nodes, expr, expr, expr, table, expr, expr, table, table", + graph: { + nodes: [ + {expression: "e1", fields: { + k570: "string(((true)) and ((n ?? 1) > (a ?? -1)))", + k571: "(vip ?? false)", + k572: "(min([(2.25) / 10, ((a ?? -1)) / 10]))", + }}, + {expression: "e2", outputPath: "res", fields: { + k573: "string(k571)", + k575: "-4 * (k572 ?? 0) * (k572 ?? 1) + 1 < (true ? 2 : 3) % 2", + k576: "(true) and (startsWith('A-1', 'x'))", + }}, + {expression: "e3", fields: { + "res.k577": "k570 ?? k571", + }}, + {table: "t4", inputs: ["(res.k573 ?? 'none')", "(res.k573 ?? '')", "string(100 < 0.5)", null], outputs: ["k578", "res.k579"], passThrough: true, rules: [ + ["", "startsWith($, '')", "startsWith($, 'g')", "", "'gold'", "0"], + ["", "'a'", "$ != 'gold'", "true", "'low'", "100"], + ["null", "'silver', 'b'", "$ != 'gold'", "null", "'high'", "0.25"], + ["'', 'b'", "'a', 'gold'", "'silver'", "5", "''", "2"], + ["", "", "", "", "'high'", "-5"], + ]}, + {expression: "e5", fields: { + "g.k580": "(10) * (1 - (res.k579 ?? -1))", + k581: "((-4)) * res.k579 % 2 * 10 + (res.k579 ?? 0)", + k582: "-(-4 + (res.k579 ?? 0)) == (res.k579 ?? 0) + (res.k579 ?? 0) * (res.k579 ?? 1)", + "m.k583": "res.k573 ?? res.k576", + }}, + {expression: "e6", fields: { + k575: "(res.k579 ?? 1)", + k585: "(not ((res.k576 ?? false)) ? string((res.k579 ?? -1)) : (k578 ?? '?')) + ' ' + string(($.k575 ?? -1) > 2.25)", + k586: "(res.k576 ?? false)", + }}, + {table: "t7", inputs: ["100"], outputs: ["g.k587", "k588"], outputPath: "res", rules: [ + ["!= 0", "'gold'", "''"], + ["", "'low'", "'gold'"], + ["> 1", "'high'", "'gold'"], + ["[50..60]", "'low'", "'low'"], + ]}, + {table: "t8", inputs: ["0.5 - 0.5 - -4 + 0", "(((res.k575 ?? false) ? 0.5 : -4))", "(res.k573 ?? '')"], outputs: ["k589"], rules: [ + ["null", "1, 2", "", "'gold'"], + ["not(18)", "< 0", "$ != 'gold'", "(res.k573 ?? '?') + '-' + `v${0}-${(res.k573 ?? 'none')}`"], + ["1", "$ > 10 and $ < 15", "null", "'gold'"], + ["", "", "", "'high'"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "e1 -> e3", + "e2 -> t4", + "t4 -> e5", + "e2 -> e6", + "t4 -> e6", + "e3 -> t7", + "e2 -> t7", + "e2 -> t8", + "e3 -> output", + "t4 -> output", + "e5 -> output", + "e6 -> output", + "t7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{flag: true, n: 1000, vip: null, code: "Gold", a: 3, tier: "b"}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "true", k579: -5, k588: ""}}], + [{flag: true, n: -25, vip: false, nums: [0.1, 1000000000000000000000, 101, 11, 1], code: null, tier: "", extra: {deep: {x: 1}}}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "false", k579: -5, k588: ""}}], + [{flag: true, n: 5, vip: true, nums: [], code: "silver", a: -25, tier: "a"}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "true"}, res: {g: {k587: "gold"}, k573: "true", k575: true, k576: false, k577: "true", k579: -5, k588: ""}}], + [{flag: false, n: 2.5, vip: false, nums: [99, -25], code: "gold ", a: 2.5, tier: "gold ", extra: 1}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "false", k579: -5, k588: ""}}], + [{n: 109, vip: false, nums: [-0.1, 5], code: "gold ", a: 1000, tier: "bronze"}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "false", k579: -5, k588: ""}}], + [{flag: false, n: -0.1, vip: false, nums: [3, 1000000000000000000000, 0.1], code: "a", a: 2, tier: ""}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "false", k579: -5, k588: ""}}], + [{flag: true, n: 7, vip: true, nums: [11], code: "b", a: 2, tier: "x"}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "true"}, res: {g: {k587: "gold"}, k573: "true", k575: false, k576: false, k577: "true", k579: -5, k588: ""}}], + [{flag: true, n: 11, vip: true, nums: [2.5, 100], code: "bronze", a: 3, tier: "b"}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "true"}, res: {g: {k587: "gold"}, k573: "true", k575: false, k576: false, k577: "true", k579: -5, k588: ""}}], + [{flag: true, n: 0.1, vip: false, code: "gold ", a: null, tier: "x"}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "true", k579: -5, k588: ""}}], + [{flag: false, n: 0.5, a: 11}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "false", k579: -5, k588: ""}}], + [{flag: false, n: 100, vip: true, nums: [], a: 50, tier: "x", extra: {deep: {x: 1}}}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "true"}, res: {g: {k587: "gold"}, k573: "true", k575: false, k576: false, k577: "true", k579: -5, k588: ""}}], + [{flag: false, n: null, vip: null, nums: [-0.1, -0.1, 1], code: "zz", a: 2.5, extra: {deep: {x: 1}}}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "false", k579: -5, k588: ""}}], + [{flag: false, n: 1000000000000000000000, vip: false, nums: [], code: "gold ", a: 100, tier: "gold "}, {g: {k580: 60}, k575: -5, k578: "high", k581: -5, k582: false, k585: "-5 false", k586: false, k589: "high", m: {k583: "false"}, res: {g: {k587: "gold"}, k573: "false", k575: false, k576: false, k577: "true", k579: -5, k588: ""}}], + ], +} + +{ + name: "ga056: 6 nodes, switch, table*, switch, table*, switch, table", + graph: { + nodes: [ + {switch: "s1", when: ["(a == null) and ((3 != (b ?? 1)) or ((false) or (false)))", "max([((cust.active ?? false) ? (score ?? -1) : (score ?? 1)), -((score ?? -1))]) in [1..100]", "((a ?? -1)) + 0.5 + score > (a ?? -1)", ""]}, + {table: "t2", hit: "collect", inputs: ["score", "((a ?? -1) >= (score ?? 1) ? 2 + (cust.age ?? -1) : (score) / 0.5)", "`v${score}-${(s ?? 'none')}`"], outputs: ["k590", "m.k591"], passThrough: true, rules: [ + [">= 10", "(10..20)", "'x', 'b'", "'low'", "'low'"], + ["[5..10)", "<= 51", "$ != 'silver'", "''", "'high'"], + ["18", "null", "", "''", "string((a ?? 0)) + ' ' + (s ?? '?') + '' + upper('none' + '' + s)"], + ["null", "< 18", "not('gold')", "'high'", "(s ?? '')"], + ["$ > -1 and $ < 4", "(50..100)", "startsWith($, '')", "'high'", "upper(`${(score ?? -1)}-${(s ?? '?')}`)"], + ["(100..101)", "(10..20)", "''", "'high'", "string(true) + '-' + string((b ?? 0)) + '' + s"], + ["", "", "", "'mid'", "'high'"], + ]}, + {switch: "s3", when: ["cust.active", "a == null", "(not (contains((s ?? ''), 'a'))) and (contains('', 'a'))", ""]}, + {table: "t4", hit: "collect", inputs: ["score", "string(1 >= (b ?? 0))", "upper((s ?? 'none'))"], outputs: ["k592"], outputPath: "lines", rules: [ + ["[10..15)", "'a'", "not('')", "false"], + ["(21..31)", "", "", "(true) and (trim('none') != 'silver')"], + ["!= 18", "null", "null", "false"], + ["", "$ != 'silver'", "", "endsWith((tier ?? ''), '')"], + ["", "$ != 'a'", "startsWith($, 'a')", "true"], + ["-1, 4", "'a', 'b'", "null", "true"], + ]}, + {switch: "s5", when: ["not (((tier ?? 'none') != 'x') and ((true) and (true)))", "false", ""]}, + {table: "t6", inputs: ["0", "((0.5))", "(2.25 - -4)"], outputs: ["k593"], rules: [ + [">= 21", "", "18, 23", "-5"], + [">= 50", "", "1, 6", "0.25"], + ["> -1", "> 100", "", "(1)"], + ["[1..51]", "$ > 10 and $ < 15", "<= 55", "2"], + [">= 50", "<= 68", "", "10"], + ]}, + ], + edges: [ + "input -> s1", + "s1:2 -> t2", + "s1:3 -> s3", + "t2 -> s3", + "s3:0 -> t4", + "s3:2 -> s5", + "t4 -> t6", + "s1:0 -> output", + "s1:1 -> output", + "s3:1 -> output", + "s3:3 -> output", + "s5:1 -> output", + "t6 -> output", + ], + }, + cases: [ + [{tier: null, a: 5, s: "b", cust: {age: 99, tier: "gold ", active: false}, score: 5}, {a: 5, cust: {active: false, age: 99, tier: "gold "}, s: "b", score: 5}], + [{tier: "b", s: "bronze", cust: {age: 11, tier: "Gold", active: false}, score: 80, b: 1000}, {b: 1000, cust: {active: false, age: 11, tier: "Gold"}, s: "bronze", score: 80, tier: "b"}], + [{tier: "gold", a: 0.5, s: "gold ", cust: {age: 11, tier: "gold ", active: false}, score: 21, b: -0.1}, {a: 0.5, b: -0.1, cust: {active: false, age: 11, tier: "gold "}, s: "gold ", score: 21, tier: "gold"}], + [{tier: "bronze", a: 0.1, s: "zz", cust: {age: 1000, tier: ["gold"], active: false}, score: 2.5, b: 101}, {a: 0.1, b: 101, cust: {active: false, age: 1000, tier: ["gold"]}, s: "zz", score: 2.5, tier: "bronze"}], + [{tier: "x", a: 100, s: null, cust: {age: 10, tier: "gold", active: true}, score: 99, b: 0}, {a: 100, b: 0, cust: {active: true, age: 10, tier: "gold"}, score: 99, tier: "x"}], + [{tier: "a", a: null, s: "", cust: {age: 5, tier: "x", active: false}, score: 5, b: 5}, {b: 5, cust: {active: false, age: 5, tier: "x"}, s: "", score: 5, tier: "a"}], + [{tier: "zz", a: 50, s: "Gold", cust: {age: null, active: "no"}, score: 1000, b: 0.1}, [{k590: "mid", m: {k591: "high"}}]], + [{tier: "zz", a: 1, s: "a", cust: {age: 2, tier: "", active: null}, score: -0.1, b: 1}, [{k590: "mid", m: {k591: "high"}}]], + [{tier: "silver", a: 21, s: null, cust: null, b: 100}, {a: 21, b: 100, tier: "silver"}], + [{tier: "zz", a: 1, s: "Gold", cust: {age: 99, tier: "gold", active: false}, score: 101, b: -0.1}, [{k590: "mid", m: {k591: "high"}}]], + [{tier: "b", a: 1000, s: null, cust: null, score: 7, b: "5"}, {a: 1000, b: "5", score: 7, tier: "b"}], + [{tier: "a", a: 1, s: "x", cust: {age: 2, tier: "a", active: true}, score: 99, b: -25}, {a: 1, b: -25, cust: {active: true, age: 2, tier: "a"}, s: "x", score: 99, tier: "a"}], + [{tier: "gold", a: 1000, s: "x", cust: {age: 50, tier: "gold ", active: true}, score: 18, b: 18}, {a: 1000, b: 18, cust: {active: true, age: 50, tier: "gold "}, s: "x", score: 18, tier: "gold"}], + [{tier: "bronze", a: 18, s: "b", cust: {age: 1000000000000000000000, tier: "gold", active: true}, score: -1, b: 5}, {a: 18, b: 5, cust: {active: true, age: 1000000000000000000000, tier: "gold"}, s: "b", score: -1, tier: "bronze"}], + [{tier: true, a: -25, s: null, cust: {age: 11, tier: "x", active: "no"}, score: 10, b: 1000000000000000000000}, [{k590: "mid", m: {k591: "high"}}]], + [{tier: "x", a: 101, s: "a", cust: {age: 19.99, tier: "b", active: false}, score: 0.5, b: -25}, [{k590: "mid", m: {k591: "high"}}]], + [{tier: "bronze", a: 1, s: "b", score: -25, b: 100}, {a: 1, b: 100, s: "b", score: -25, tier: "bronze"}], + [{a: 11, s: "", cust: {age: 5, tier: "gold", active: true}, score: 5, b: -25}, {a: 11, b: -25, cust: {active: true, age: 5, tier: "gold"}, s: "", score: 5}], + [{tier: "zz", a: 2.5, s: "zz", cust: {tier: "gold", active: false}, score: 100, b: 1000000000000000000000}, {a: 2.5, b: 1000000000000000000000, cust: {active: false, tier: "gold"}, s: "zz", score: 100, tier: "zz"}], + [{tier: "silver", a: -0.1, s: {t: "x"}, cust: 5, score: 3, b: 19.99}, {a: -0.1, b: 19.99, cust: 5, s: {t: "x"}, score: 3, tier: "silver"}], + ], +} + +{ + name: "ga057: 5 nodes, table*, expr, expr, loop expr, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["vip", "tier"], outputs: ["k594[]"], outputPath: "res", rules: [ + ["false", "'silver'", "(price ?? 1) > -4 * len(nums ?? [])"], + ["$ == true", "'silver', 'bronze'", "false"], + ["true", "", "false"], + ]}, + {expression: "e2", fields: { + k595: "(min([1 - 3, 2.25 * 1]))", + }}, + {expression: "e3", passThrough: true, outputPath: "res", fields: { + k596: "vip ?? vip", + }}, + {expression: "e4", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k597: "(qty ?? 1) % 2", + k598: "string(((price ?? -1)) + max([(price ?? 1), price]))", + }}, + {expression: "e5", passThrough: true, fields: { + "g.k599": "min([(k595 ?? 1) % 7 % 3, -((price ?? 1)) - ((k595 ?? 1)) / 2])", + }}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "e2 -> e3", + "input -> e3", + "e3 -> e4", + "e4 -> e5", + "e5 -> output", + ], + }, + cases: [ + [{vip: false, tier: "", price: null, nums: [], items: [{price: 50, qty: 19.99, tag: ""}, {price: -1, qty: 0.5, tag: "gold"}], extra: 1}, {extra: 1, g: {k599: -2}, items: [{price: 50, qty: 19.99, tag: ""}, {price: -1, qty: 0.5, tag: "gold"}], k595: -2, nums: [], res: [{k597: 1.99, k598: "100", price: 50, qty: 19.99, tag: ""}, {k597: 0.5, k598: "-2", price: -1, qty: 0.5, tag: "gold"}], tier: "", vip: false}], + [{vip: false, tier: "gold", price: 0.5, nums: [7, -0.1], items: [{price: 0.1, qty: 52, tag: "silver"}, {price: 0.1, qty: 103, tag: "Gold"}]}, {g: {k599: -2}, items: [{price: 0.1, qty: 52, tag: "silver"}, {price: 0.1, qty: 103, tag: "Gold"}], k595: -2, nums: [7, -0.1], price: 0.5, res: [{k597: 0, k598: "0.2", price: 0.1, qty: 52, tag: "silver"}, {k597: 1, k598: "0.2", price: 0.1, qty: 103, tag: "Gold"}], tier: "gold", vip: false}], + [{vip: true, tier: "gold", price: 99, nums: [], items: null}, "!error"], + [{tier: "zz", price: -1, nums: [], items: [{price: 11, qty: 1000000000000000000000, tag: null}, {price: null, qty: 1000000000000000000000, tag: "x"}]}, "!error"], + [{tier: null, nums: null, items: [{price: 7, qty: 1, tag: "gold"}, {price: 99, qty: -25, tag: ""}]}, {g: {k599: -2}, items: [{price: 7, qty: 1, tag: "gold"}, {price: 99, qty: -25, tag: ""}], k595: -2, res: [{k597: 1, k598: "14", price: 7, qty: 1, tag: "gold"}, {k597: -1, k598: "198", price: 99, qty: -25, tag: ""}]}], + [{vip: false, tier: "gold ", price: -1, nums: [21, -0.1, 0, -25, -0.1], items: [{price: 11, qty: 18, tag: "Gold"}, {price: 100, qty: 0.5, tag: "gold "}, {price: 0.5, qty: 0, tag: "b"}]}, {g: {k599: -2}, items: [{price: 11, qty: 18, tag: "Gold"}, {price: 100, qty: 0.5, tag: "gold "}, {price: 0.5, qty: 0, tag: "b"}], k595: -2, nums: [21, -0.1, 0, -25, -0.1], price: -1, res: [{k597: 0, k598: "22", price: 11, qty: 18, tag: "Gold"}, {k597: 0.5, k598: "200", price: 100, qty: 0.5, tag: "gold "}, {k597: 0, k598: "1.0", price: 0.5, qty: 0, tag: "b"}], tier: "gold ", vip: false}], + [{vip: false, tier: "silver", price: 19.99, nums: [101, -25, 50], items: [{price: 1000, qty: 18, tag: "bronze"}]}, {g: {k599: -18.99}, items: [{price: 1000, qty: 18, tag: "bronze"}], k595: -2, nums: [101, -25, 50], price: 19.99, res: [{k597: 0, k598: "2000", price: 1000, qty: 18, tag: "bronze"}], tier: "silver", vip: false}], + [{vip: "true", tier: "zz", price: -25, nums: [18, 99, 99, 106, 2.5], items: null}, "!error"], + [{vip: false, tier: "", price: 86, nums: [], items: []}, {g: {k599: -85}, items: [], k595: -2, nums: [], price: 86, res: [], tier: "", vip: false}], + [{vip: true, tier: "Gold", price: 99, nums: [100], items: [{price: 50, qty: {v: 1}, tag: "bronze"}, {price: 10, qty: 2.5, tag: "Gold"}]}, "!error"], + [{vip: false, tier: "x", price: 50, nums: [7, 100, -25, 18, 101], items: [{price: 100, qty: 1000000000000000000000, tag: "bronze"}, {price: 5, qty: 101, tag: "a"}, {price: null, qty: 101, tag: "x"}, {price: 99, tag: "gold"}]}, "!error"], + [{vip: false, tier: "silver", nums: [{x: 1}], items: [{price: 1, qty: "5", tag: "silver"}]}, "!error"], + [{price: 2, nums: [5], items: [{price: 2.5, qty: 5, tag: ""}, {price: 1, qty: 1000, tag: "a"}, {price: 1000, qty: 11}, {price: 0, qty: 99, tag: "bronze"}]}, {g: {k599: -2}, items: [{price: 2.5, qty: 5, tag: ""}, {price: 1, qty: 1000, tag: "a"}, {price: 1000, qty: 11}, {price: 0, qty: 99, tag: "bronze"}], k595: -2, nums: [5], price: 2, res: [{k597: 1, k598: "5.0", price: 2.5, qty: 5, tag: ""}, {k597: 0, k598: "2", price: 1, qty: 1000, tag: "a"}, {k597: 1, k598: "2000", price: 1000, qty: 11}, {k597: 1, k598: "0", price: 0, qty: 99, tag: "bronze"}]}], + [{vip: null, tier: "zz", price: 10, nums: [-0.1, 10, -1], items: [{price: null, qty: 11, tag: "bronze"}, {price: 1000, qty: 10, tag: "Gold"}]}, "!error"], + [{vip: null, tier: "gold ", price: -25, items: [], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, g: {k599: -2}, items: [], k595: -2, price: -25, res: [], tier: "gold "}], + [{vip: true, tier: "zz", price: 3, nums: [101], items: [{price: 50, qty: 0.1, tag: "zz"}, {price: 2, qty: 19.99, tag: "bronze"}, {price: 1000, qty: 100}]}, {g: {k599: -2}, items: [{price: 50, qty: 0.1, tag: "zz"}, {price: 2, qty: 19.99, tag: "bronze"}, {price: 1000, qty: 100}], k595: -2, nums: [101], price: 3, res: [{k597: 0.1, k598: "100", price: 50, qty: 0.1, tag: "zz"}, {k597: 1.99, k598: "4", price: 2, qty: 19.99, tag: "bronze"}, {k597: 0, k598: "2000", price: 1000, qty: 100}], tier: "zz", vip: true}], + [{vip: true, tier: "a", price: 5, nums: [2, 0.1, 3], items: [{price: 0, qty: 2.5, tag: "a"}, {price: 7, qty: 0.1, tag: "b"}], extra: [1, 2]}, {extra: [1, 2], g: {k599: -4}, items: [{price: 0, qty: 2.5, tag: "a"}, {price: 7, qty: 0.1, tag: "b"}], k595: -2, nums: [2, 0.1, 3], price: 5, res: [{k597: 0.5, k598: "0", price: 0, qty: 2.5, tag: "a"}, {k597: 0.1, k598: "14", price: 7, qty: 0.1, tag: "b"}], tier: "a", vip: true}], + [{vip: true, tier: "bronze", price: -20, nums: [1000], items: []}, {g: {k599: -2}, items: [], k595: -2, nums: [1000], price: -20, res: [], tier: "bronze", vip: true}], + [{vip: false, tier: "a", nums: [], items: [{price: 1000, qty: "abc", tag: "bronze"}, {price: 99, qty: 5, tag: "zz"}]}, "!error"], + [{vip: null, tier: "Gold", price: 50, nums: [10], items: [{price: 19.99, tag: ""}, {price: 19.99, qty: 84, tag: ""}, {price: 2.5, qty: 1000000000000000000000, tag: "gold "}]}, {g: {k599: -49}, items: [{price: 19.99, tag: ""}, {price: 19.99, qty: 84, tag: ""}, {price: 2.5, qty: 1000000000000000000000, tag: "gold "}], k595: -2, nums: [10], price: 50, res: [{k597: 1, k598: "39.98", price: 19.99, tag: ""}, {k597: 0, k598: "39.98", price: 19.99, qty: 84, tag: ""}, {k597: 0, k598: "5.0", price: 2.5, qty: 1000000000000000000000, tag: "gold "}], tier: "Gold"}], + ], +} + +{ + name: "ga058: 4 nodes, expr, expr, expr, table", + graph: { + nodes: [ + {expression: "e1", fields: { + k601: "tier ?? tier", + }}, + {expression: "e2", passThrough: true, fields: { + k602: "(code ?? '') + '' + (items ?? [])[0].tag ?? 'none' + ' ' + 'x'", + k603: "tier ?? a", + k604: "(a ?? -1)", + }}, + {expression: "e3", fields: { + k605: "string((tier ?? '') + ':' + code in ['gold', 'silver', 'a'])", + }}, + {table: "t4", inputs: ["a", null], outputs: ["k606", "k607"], rules: [ + ["$ > -1 and $ < 9", "'gold'", "false", "-5"], + ["", "", "false", "('' != 'x' ? ('none' != 'silver' ? len((k605 ?? '')) : ((a ?? 0))) : (floor((score ?? -1))) / 3)"], + ["<= 31", "5", "false", "2 - (len((k605 ?? 'none'))) / 0.5"], + ["", "", "(10 in [-5..5]) or (floor(100) < score * (score ?? 0))", "-5"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> e2", + "e2 -> e3", + "input -> t4", + "e3 -> t4", + "t4 -> output", + ], + }, + cases: [ + [{score: 1, tier: "silver", flag: null, code: "zz", a: 1, s: null, items: [], extra: {deep: {x: 1}}}, {k606: false, k607: 5}], + [{score: 18, tier: "silver", flag: false, vip: false, code: "gold ", a: 2, s: "gold", items: [{price: 81, qty: 1000000000000000000000, tag: "Gold"}, {price: 3, qty: 0.1, tag: "a"}, {price: -1, qty: 1000000000000000000000, tag: "a"}]}, {k606: false, k607: 5}], + [{score: -1, tier: "", flag: true, vip: true, code: "x", a: 10, s: null, items: []}, {k606: false, k607: 5}], + [{score: 2.5, tier: "zz", flag: true, vip: true, code: "zz", a: 0, s: "Gold", items: [{qty: 1000, tag: "b"}, {price: 2.5, qty: -1, tag: "bronze"}]}, {k606: false, k607: 5}], + [{score: 65, tier: "", flag: false, vip: true, code: "x", a: 19.99, s: "", items: [], extra: 1}, {k606: false, k607: 5}], + [{score: null, tier: "silver", flag: true, vip: true, code: "b", s: null, items: []}, {k606: false, k607: 5}], + [{score: 0.1, tier: null, flag: null, vip: false, code: "a", a: 99, s: "bronze", items: [{price: 3, qty: 100, tag: "bronze"}, {price: 3, qty: 3, tag: ""}, {price: 99, qty: -1, tag: "gold "}, {price: -25, qty: 11, tag: "gold "}]}, {k606: false, k607: 5}], + [{score: -25, tier: "gold ", flag: false, vip: true, a: -0.1, s: "Gold", items: "items"}, "!error"], + [{score: 5, tier: 5, flag: null, vip: false, code: "b", a: 5, items: []}, "!error"], + [{score: 1, tier: "a", flag: false, vip: true, code: "gold", a: -0.1, s: "b", items: [{price: "abc", qty: 11, tag: "bronze"}, {price: 0, qty: 0.1, tag: "gold"}]}, {k606: false, k607: 5}], + [{score: [1], tier: null, flag: false, code: "b", a: 0.5, s: "a", items: [{price: 2.5, qty: [1], tag: "x"}]}, {k606: false, k607: 5}], + [{score: 99, tier: "gold ", flag: true, vip: false, code: "gold ", a: 3, s: "silver", items: [], extra: "e"}, {k606: false, k607: 5}], + [{score: 1000, tier: "gold", flag: null, vip: true, code: "Gold", a: 0, s: "a", items: [{price: 7, tag: "x"}, {price: 100, qty: 1, tag: "zz"}, {price: 21, qty: null}, {price: 99, qty: 1000, tag: "gold"}]}, {k606: false, k607: 5}], + [{score: 11, tier: 5, flag: true, vip: false, code: null, a: -25, s: "gold ", items: [{price: 19.99, qty: 0.1, tag: "b"}, {price: 7, qty: 3, tag: "gold"}, {price: 2.5, qty: null, tag: "b"}]}, "!error"], + [{score: 1000, tier: "a", flag: false, vip: false, code: "Gold", s: "b", items: [{price: 1000, qty: 11, tag: ""}, {price: 0.5, qty: 0.1, tag: ["gold"]}, {price: 50, qty: 7, tag: "x"}]}, {k606: false, k607: 5}], + [{score: -25, flag: true, vip: false, code: "b", a: 2, items: [{qty: 1000, tag: "Gold"}, {price: -25, qty: 3, tag: "zz"}]}, {k606: false, k607: 5}], + [{score: null, tier: "silver", flag: false, vip: false, code: "gold", a: 115, s: "a", items: [{price: null, qty: -1, tag: "Gold"}, {price: 50, qty: null, tag: "silver"}]}, {k606: false, k607: 5}], + ], +} + +{ + name: "ga059: 5 nodes, expr, loop expr, expr, loop expr, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k608: "string('gold' + '-' + (tier ?? '') in ['gold', 'silver', 'a'])", + k609: "(b ?? 1) % 2", + }}, + {expression: "e2", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k610: "price ?? price", + k611: "len((tag ?? '') + '' + 'x') + qty + price % 3", + }}, + {expression: "e3", outputPath: "res", fields: { + k612: "(k609 ?? -1)", + k613: "(k609 ?? 1)", + k614: "trim((tier ?? '')) + '-' + (tier ?? '?') + '-' + 'none'", + }}, + {expression: "e4", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "o.p", fields: { + k615: "tag ?? tag", + }}, + {expression: "e5", passThrough: true, outputPath: "out", fields: { + k616: "string((false)) == 'gold'", + k617: "(score ?? res.k612 ?? 0)", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e1 -> e3", + "e2 -> e3", + "e1 -> e4", + "e3 -> e4", + "e4 -> e5", + "e1 -> output", + "e4 -> output", + "e5 -> output", + ], + }, + cases: [ + [{b: 10, tier: "b", score: 50, items: [{price: 101, qty: 18, tag: "gold "}, {qty: -0.1, tag: "gold "}], extra: [1, 2]}, "!error"], + [{tier: "zz", score: 50, items: [{price: 5, qty: 19.99, tag: "zz"}]}, {items: [{price: 5, qty: 19.99, tag: "zz"}], k608: "false", k609: 1, o: {p: [{k615: "zz", price: 5, qty: 19.99, tag: "zz"}]}, out: {k616: false, k617: 50}, res: {k612: 1, k613: 1, k614: "zz-zz-none"}, score: 50, tier: "zz"}], + [{b: 5, tier: null, score: 3, items: [{price: 0, qty: 0.1, tag: "Gold"}, {price: 3, tag: "x"}, {price: 21, qty: 0, tag: "x"}, {price: 7, qty: 0.1, tag: ""}]}, "!error"], + [{b: -25, tier: null, score: 18, items: [{qty: 1000, tag: "gold "}]}, "!error"], + [{b: 99, tier: "x", score: -25, items: []}, {b: 99, items: [], k608: "false", k609: 1, o: {p: []}, out: {k616: false, k617: -25}, res: {k612: 1, k613: 1, k614: "x-x-none"}, score: -25, tier: "x"}], + [{b: 101, tier: "bronze", score: 1000, items: [{price: 10, qty: 10, tag: ""}, {price: 1000, qty: null, tag: "gold"}], extra: "e"}, "!error"], + [{b: 19.99, tier: "gold ", score: 100, items: [{price: 100, qty: 7, tag: "Gold"}, {price: 50, qty: 101, tag: "Gold"}, {price: 1000000000000000000000, qty: 5, tag: "a"}]}, {b: 19.99, items: [{price: 100, qty: 7, tag: "Gold"}, {price: 50, qty: 101, tag: "Gold"}, {price: 1000000000000000000000, qty: 5, tag: "a"}], k608: "false", k609: 1.99, o: {p: [{k615: "Gold", price: 100, qty: 7, tag: "Gold"}, {k615: "Gold", price: 50, qty: 101, tag: "Gold"}, {k615: "a", price: 1000000000000000000000, qty: 5, tag: "a"}]}, out: {k616: false, k617: 100}, res: {k612: 1.99, k613: 1.99, k614: "gold-gold -none"}, score: 100, tier: "gold "}], + [{b: 0.5, tier: null, score: -1, items: [{price: 101, qty: 0.5, tag: "x"}, {qty: 50}, {price: 99, qty: 2.5, tag: "silver"}], extra: "e"}, "!error"], + [{b: 10, tier: "silver", score: 100, items: [{price: 99, qty: -25, tag: "Gold"}, {price: 10, qty: 2}]}, {b: 10, items: [{price: 99, qty: -25, tag: "Gold"}, {price: 10, qty: 2}], k608: "false", k609: 0, o: {p: [{k615: "Gold", price: 99, qty: -25, tag: "Gold"}, {price: 10, qty: 2}]}, out: {k616: false, k617: 100}, res: {k612: 0, k613: 0, k614: "silver-silver-none"}, score: 100, tier: "silver"}], + [{b: -1, tier: "zz", score: 18, items: [{price: 19.99, qty: 5, tag: ""}, {price: 50, qty: 18, tag: "Gold"}, {price: 10, qty: 1, tag: ""}, {price: 99, qty: 18, tag: "silver"}]}, {b: -1, items: [{price: 19.99, qty: 5, tag: ""}, {price: 50, qty: 18, tag: "Gold"}, {price: 10, qty: 1, tag: ""}, {price: 99, qty: 18, tag: "silver"}], k608: "false", k609: -1, o: {p: [{k615: "", price: 19.99, qty: 5, tag: ""}, {k615: "Gold", price: 50, qty: 18, tag: "Gold"}, {k615: "", price: 10, qty: 1, tag: ""}, {k615: "silver", price: 99, qty: 18, tag: "silver"}]}, out: {k616: false, k617: 18}, res: {k612: -1, k613: -1, k614: "zz-zz-none"}, score: 18, tier: "zz"}], + [{b: 50, tier: "Gold", score: 18, items: [{price: 18, qty: 0.5, tag: ""}, {price: 10, qty: 5, tag: "bronze"}]}, {b: 50, items: [{price: 18, qty: 0.5, tag: ""}, {price: 10, qty: 5, tag: "bronze"}], k608: "false", k609: 0, o: {p: [{k615: "", price: 18, qty: 0.5, tag: ""}, {k615: "bronze", price: 10, qty: 5, tag: "bronze"}]}, out: {k616: false, k617: 18}, res: {k612: 0, k613: 0, k614: "Gold-Gold-none"}, score: 18, tier: "Gold"}], + [{b: 18, score: 1000, items: [{price: -0.1, qty: 18, tag: ""}]}, {b: 18, items: [{price: -0.1, qty: 18, tag: ""}], k608: "false", k609: 0, o: {p: [{k615: "", price: -0.1, qty: 18, tag: ""}]}, out: {k616: false, k617: 1000}, res: {k612: 0, k613: 0, k614: "-?-none"}, score: 1000}], + [{tier: "Gold", score: 1000, items: [{price: 3, qty: 1000000000000000000000, tag: "gold "}, {price: 99, qty: null, tag: null}]}, "!error"], + [{b: 21, tier: "Gold", score: 2, items: []}, {b: 21, items: [], k608: "false", k609: 1, o: {p: []}, out: {k616: false, k617: 2}, res: {k612: 1, k613: 1, k614: "Gold-Gold-none"}, score: 2, tier: "Gold"}], + [{b: 7, tier: "bronze", score: 100, items: [{price: 100, qty: 10, tag: ""}, {price: 11, qty: -0.1, tag: "gold "}]}, {b: 7, items: [{price: 100, qty: 10, tag: ""}, {price: 11, qty: -0.1, tag: "gold "}], k608: "false", k609: 1, o: {p: [{k615: "", price: 100, qty: 10, tag: ""}, {k615: "gold ", price: 11, qty: -0.1, tag: "gold "}]}, out: {k616: false, k617: 100}, res: {k612: 1, k613: 1, k614: "bronze-bronze-none"}, score: 100, tier: "bronze"}], + [{b: 19.99, tier: "", score: 0.1, items: []}, {b: 19.99, items: [], k608: "false", k609: 1.99, o: {p: []}, out: {k616: false, k617: 0.1}, res: {k612: 1.99, k613: 1.99, k614: "--none"}, score: 0.1, tier: ""}], + [{b: 11, score: 100, items: [{price: 11, qty: null, tag: ""}, {price: 5, qty: 2, tag: null}]}, "!error"], + [{b: 11, tier: "gold ", score: 10, items: [{price: 11, qty: 5, tag: "b"}]}, {b: 11, items: [{price: 11, qty: 5, tag: "b"}], k608: "false", k609: 1, o: {p: [{k615: "b", price: 11, qty: 5, tag: "b"}]}, out: {k616: false, k617: 10}, res: {k612: 1, k613: 1, k614: "gold-gold -none"}, score: 10, tier: "gold "}], + [{b: 104, tier: "a", score: 50, items: [{qty: 21, tag: "x"}, {price: 99, qty: null, tag: "silver"}, {price: 99, qty: 11, tag: "x"}]}, "!error"], + [{b: -1, tier: "zz", score: -1, items: [{price: 25, qty: -25, tag: "silver"}, {price: null, tag: "Gold"}, {price: 0, qty: -0.1}]}, "!error"], + [{b: 19.99, tier: "gold ", score: 21, items: [{price: 0.1, qty: 2.5, tag: "gold"}, {price: 21, qty: 100, tag: "silver"}], extra: "e"}, {b: 19.99, extra: "e", items: [{price: 0.1, qty: 2.5, tag: "gold"}, {price: 21, qty: 100, tag: "silver"}], k608: "false", k609: 1.99, o: {p: [{k615: "gold", price: 0.1, qty: 2.5, tag: "gold"}, {k615: "silver", price: 21, qty: 100, tag: "silver"}]}, out: {k616: false, k617: 21}, res: {k612: 1.99, k613: 1.99, k614: "gold-gold -none"}, score: 21, tier: "gold "}], + [{b: 0.5, tier: "bronze", items: [{price: 5, qty: 101, tag: null}]}, {b: 0.5, items: [{price: 5, qty: 101, tag: null}], k608: "false", k609: 0.5, o: {p: [{price: 5, qty: 101, tag: null}]}, out: {k616: false, k617: 0.5}, res: {k612: 0.5, k613: 0.5, k614: "bronze-bronze-none"}, tier: "bronze"}], + [{b: 0, score: 1, items: [{price: 3, qty: 3, tag: "gold"}, {price: 1000000000000000000000, qty: 62, tag: null}, {price: null, qty: 0.5, tag: "silver"}], extra: "e"}, "!error"], + [{b: -0.1, tier: "gold ", score: 3, items: [{price: -1, qty: 2.5, tag: "bronze"}, {price: 0.1, qty: null, tag: "x"}]}, "!error"], + [{b: null, tier: null, score: 11, items: [{qty: -1, tag: ""}, {price: 18, qty: 2.5, tag: null}, {price: 0.5, qty: 2.5, tag: "Gold"}, {price: 1000, qty: 0, tag: ""}]}, "!error"], + [{b: 0, tier: "", score: 21, items: [{price: 0.1, qty: -1, tag: ""}, {price: 0.1, qty: -18, tag: null}]}, {b: 0, items: [{price: 0.1, qty: -1, tag: ""}, {price: 0.1, qty: -18, tag: null}], k608: "false", k609: 0, o: {p: [{k615: "", price: 0.1, qty: -1, tag: ""}, {price: 0.1, qty: -18, tag: null}]}, out: {k616: false, k617: 21}, res: {k612: 0, k613: 0, k614: "--none"}, score: 21, tier: ""}], + ], +} + +{ + name: "ga060: 3 nodes, expr, switch, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k618: "flag ?? flag", + k619: "(price ?? 0) - (price ?? -1) + (price ?? -1) + (price ?? 0) * price", + k620: "(tier ?? 'none')", + k621: "3", + }}, + {switch: "s2", when: ["(k619 ?? 1) != ((k621 ?? 0) + cust.age)", ""]}, + {table: "t3", inputs: ["trim(string((flag ?? false)))", "`n=${(k621 ?? 1)}-${(s ?? '')}`"], outputs: ["k622", "k623"], rules: [ + ["$ != 'gold'", "$ != 'gold'", "false", "false"], + ["", "'', 'b'", "false", "true"], + ["startsWith($, 'x')", "null", "(tier ?? '?') in ['gold', 'silver', 'a']", "false"], + ["'a'", "startsWith($, 'x')", "true", "true"], + ["$ != ''", "'', 'gold'", "false", "-4 <= (-4) / 10"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "s2:1 -> t3", + "t3 -> output", + ], + }, + cases: [ + [{items: [], flag: true, nums: [3], price: 1000000000000000000000, s: "gold ", tier: "silver"}, "!error"], + [{items: [{price: 99, tag: "silver"}, {price: 21, qty: null, tag: null}, {price: 11, qty: 99, tag: null}], flag: true, nums: null, price: 0.1, s: "", tier: "a"}, {k622: false, k623: false}], + [{items: [{price: 10, qty: 2, tag: "gold "}, {price: 21, qty: 100, tag: "gold"}, {price: null, tag: "bronze"}], flag: true, nums: [], price: 18, s: "zz", cust: {age: 99}, tier: "bronze"}, {}], + [{items: [{price: -0.1, qty: null, tag: "silver"}], flag: true, nums: [100, 0, 7], price: 18, s: "b", cust: {age: -25, tier: "gold", active: false}, tier: "silver"}, {}], + [{items: [{price: -25, tag: "zz"}, {price: 19.99, qty: 21, tag: "gold"}], flag: false, nums: [2, -25, 3, 3, 99], price: 21, cust: {age: 100, tier: "b", active: true}, tier: "a"}, {}], + [{items: [{price: 64, qty: 18, tag: "x"}, {price: 18, qty: 88, tag: "x"}, {price: 50, qty: 100, tag: "x"}], flag: false, nums: [18, 50, 1000000000000000000000, 99, 19.99], price: 1000, s: "silver", cust: {age: 5, tier: "x", active: true}, tier: "x"}, {}], + [{items: [{price: null, qty: 99, tag: "a"}], flag: false, nums: [-1, 7, 1000000000000000000000, 0.5, 3], price: 0.1, s: "bronze", cust: {age: 7, tier: "a", active: false}, tier: "b"}, {}], + [{items: null, flag: null, nums: [50, 5], price: -1, s: "", cust: {age: null, tier: "zz", active: true}, tier: null}, {k622: false, k623: false}], + [{items: [{price: 1000000000000000000000, qty: 0}, {price: 0, qty: 2}, {price: 19.99, qty: null, tag: "silver"}], flag: true, nums: [11, 100, 11, 21, 7], price: null, s: "bronze", cust: {age: null, tier: "silver", active: true}, extra: [1, 2]}, "!error"], + [{items: [{price: 18, qty: -25, tag: "bronze"}, {price: 5, qty: 1000}, {price: 7, qty: 82, tag: "Gold"}], flag: false, nums: [10], price: 2, s: "bronze", cust: {age: 50, tier: null, active: true}, tier: "Gold"}, {}], + [{items: [{price: 2, qty: 101, tag: "x"}, {price: 101, qty: 3, tag: "gold "}, {price: 3, qty: 1, tag: "b"}, {price: 0, qty: null, tag: ""}], flag: null, nums: [100], price: 0.1, s: "silver", cust: {age: 0.5, tier: "b", active: false}, tier: "gold"}, {}], + [{items: [{price: 1, qty: 0, tag: "a"}], flag: false, nums: [-0.1, 11, 2.5, 2.5, 1000000000000000000000], price: 101, s: "gold", cust: {age: 1000000000000000000000, tier: "gold", active: true}, tier: "Gold"}, {}], + [{items: [{price: 5, qty: 19.99, tag: "silver"}, {price: 10, qty: 2, tag: ""}, {price: -1, qty: 2}, {price: -1, qty: 5, tag: "a"}], flag: false, nums: [50, 5, 7], price: 19.99, s: "b", cust: {age: 3, tier: "silver", active: false}, tier: "silver"}, {}], + ], +} + +{ + name: "ga061: 8 nodes, switch, table, loop expr, expr, expr, table, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["(score ?? -1) != (score ?? -1)", "vip != null", ""]}, + {table: "t2", inputs: ["score", "(score ?? -1)", "score"], outputs: ["k624"], rules: [ + ["(100..101)", "0", "$ > 18 and $ < 68", "2"], + ["[1..2]", "$ > 10 and $ < 20", "", "min([min([(score ?? score ?? 0), (score ?? -1)]), (b ?? 1)])"], + ["<= 10", "$ > 5 and $ < 15", "[0..10)", "-5"], + ["", "", "", "round(((true ? (n ?? -1) : score)))"], + ]}, + {expression: "e3", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k625: "((false ? (tag ?? 'none') : tag) != '' ? `n=${0}-${tag}` : ((qty ?? 1) >= (price ?? 1) ? (tag ?? '?') : string((qty ?? -1))))", + "m.k626": "price ?? qty", + k627: "false", + }}, + {expression: "e4", fields: { + k628: "(score ?? 1) % 2", + k629: "0.5 - -4 % 2 % 7", + }}, + {expression: "e5", outputPath: "lines", fields: { + "res.k630": "(abs((0) / 3)) / 2", + }}, + {table: "t6", inputs: ["lines.res.k630", "((lines.res.k630 ?? -1) + lines.res.k630)"], outputs: ["k631"], outputPath: "res", rules: [ + [">= 10", "", "true"], + ["< 10", "[50..60)", "false"], + ["< 21", "[21..71)", "true"], + ["$ > -1 and $ < 0", "(-1..0)", "(lines.res.k630 ?? 1) != (0) - (lines.res.k630 ?? 0) - (lines.res.k630 ?? -1)"], + ]}, + {expression: "e7", fields: { + k632: "1", + k633: "null", + k634: "($.k632 ?? 0) * -((0.5))", + }}, + {table: "t8", inputs: ["((k628))", "k628", "'gold'"], outputs: ["k635"], passThrough: true, rules: [ + ["not(10)", "[-1..49]", "", "true"], + ["<= 6", "(0..1)", "startsWith($, 's')", "false"], + ["", "", "", "false"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> t2", + "s1:0 -> e3", + "s1:1 -> e4", + "e3 -> e5", + "e5 -> t6", + "e3 -> e7", + "e4 -> t8", + "e5 -> t8", + "s1:2 -> output", + "t2 -> output", + "t6 -> output", + "e7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{score: -0.1, s: "Gold", b: 50, vip: "true", tier: "", items: [{price: 21}, {price: 101, qty: 100}]}, {k628: -0.1, k629: 0.5, k635: false}], + [{n: 50, score: 19.99, s: null, b: 0.1, vip: false, tier: 5, items: [{price: 1, qty: 18, tag: null}, {price: 21, qty: 1000000000000000000000, tag: "zz"}]}, {k628: 1.99, k629: 0.5, k635: false}], + [{n: null, score: 100, s: "bronze", b: 11, vip: "true", tier: "bronze", items: []}, {k628: 0, k629: 0.5, k635: false}], + [{n: null, score: 5, s: "", b: 19.99, vip: true, tier: "Gold", items: [{price: true, tag: "gold "}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: null, score: null, s: "zz", b: 19.99, vip: false, items: [{price: 0, qty: 21, tag: "bronze"}, {price: null, qty: 2, tag: "zz"}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: 21, score: 99, s: "bronze", b: null, vip: true, tier: null, items: [{price: -1, qty: 2.5, tag: "silver"}, {price: 11, qty: 11, tag: ["gold"]}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: 18, score: 21, s: "gold ", b: 0.1, vip: true, tier: "", items: [{qty: 10, tag: "a"}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: 0.1, score: 100, s: "zz", b: 0, vip: true, tier: "gold ", items: [{price: 5, qty: 2.5, tag: "gold"}, {price: -25, qty: 1, tag: ["gold"]}]}, {k628: 0, k629: 0.5, k635: false}], + [{n: 11, score: 2, b: 18, vip: true, tier: true, items: [{price: 3, qty: 99, tag: "b"}, {price: 2, qty: -0.1, tag: "x"}, {price: 1000, qty: null, tag: null}]}, {k628: 0, k629: 0.5, k635: false}], + [{s: "a", b: 101, vip: false, tier: "", items: [{price: null, qty: 1000, tag: "b"}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: 5, score: 3, s: "Gold", b: 1000000000000000000000, vip: false, tier: "Gold", items: [{price: 21, qty: 0, tag: "silver"}, {price: 1000, qty: 2, tag: "b"}]}, {k628: 1, k629: 0.5, k635: false}], + [{score: -1, s: "Gold", b: 0.5, vip: true, tier: "gold ", items: [{price: 2.5, qty: 19.99, tag: "b"}, {tag: ""}, {price: 5, qty: 11, tag: "a"}]}, {k628: -1, k629: 0.5, k635: false}], + [{n: null, score: -25, s: "", b: 10, vip: false, tier: "silver", items: [{price: 115, qty: 3}, {qty: 10, tag: "zz"}, {price: null, qty: 1, tag: "a"}, {price: 5, qty: -1, tag: "gold "}]}, {k628: -1, k629: 0.5, k635: false}], + [{n: null, score: 11, b: -0.1, vip: false, tier: ""}, {k628: 1, k629: 0.5, k635: false}], + [{n: 11, score: 19.99, s: "", b: 0.5, vip: "true", tier: "silver", items: [{price: null, qty: 2.5, tag: ""}, {qty: -25, tag: "gold"}, {price: 50, qty: true, tag: "Gold"}]}, {k628: 1.99, k629: 0.5, k635: false}], + [{n: null, s: null, b: 2, vip: null, tier: "zz", items: [{price: null, qty: 50, tag: ""}, {qty: 0.5, tag: "gold "}, {price: null, qty: -25, tag: "gold"}, {price: 5, qty: 0, tag: ""}], extra: "e"}, {b: 2, extra: "e", items: [{price: null, qty: 50, tag: ""}, {qty: 0.5, tag: "gold "}, {price: null, qty: -25, tag: "gold"}, {price: 5, qty: 0, tag: ""}], tier: "zz"}], + [{n: -1, s: "bronze", vip: false, tier: "x", items: []}, {k628: 1, k629: 0.5, k635: false}], + [{n: 0, score: -0.1, s: "silver", vip: false, tier: "x", items: [{price: 11, qty: null, tag: "zz"}, {price: -1, qty: -1, tag: "a"}]}, {k628: -0.1, k629: 0.5, k635: false}], + [{n: 0, score: 2, s: "Gold", b: null, vip: false, tier: "zz", items: [{price: 18, qty: 1, tag: "silver"}, {price: 1000, qty: -0.1, tag: "b"}]}, {k628: 0, k629: 0.5, k635: false}], + [{n: 18, score: 109, s: "a", b: 21, vip: true, tier: "gold ", items: [{price: 7, qty: 19.99, tag: "a"}, {price: 0.5, qty: 2, tag: "b"}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: 2.5, score: 1, s: "Gold", b: -1, vip: true, tier: "x", items: [{price: 0.1, qty: 0, tag: null}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: [1], score: 2.5, b: 2.5, vip: true, tier: "zz", items: [{price: 2, qty: 7, tag: "x"}, {price: {v: 1}, qty: 11, tag: "b"}, {price: 1, qty: true, tag: "gold"}, {price: 0.1, qty: 10}]}, {k628: 0.5, k629: 0.5, k635: false}], + [{n: -25, score: 19.99, s: "b", b: -1, vip: true, tier: "bronze", items: [{price: 21, qty: 0.1, tag: "Gold"}, {price: 8, qty: 1000, tag: null}], extra: {deep: {x: 1}}}, {k628: 1.99, k629: 0.5, k635: false}], + [{score: null, s: "x", b: {v: 1}, vip: false, tier: "bronze", items: [{price: 52, qty: 1, tag: "silver"}, {price: 50, qty: 2.5, tag: "bronze"}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: 100, score: 1000, s: "silver", b: 11, tier: true, items: [{price: 0, qty: 19.99, tag: "gold"}, {price: 0.1, qty: 18, tag: "silver"}, {price: 101, qty: 100, tag: "Gold"}]}, {b: 11, items: [{price: 0, qty: 19.99, tag: "gold"}, {price: 0.1, qty: 18, tag: "silver"}, {price: 101, qty: 100, tag: "Gold"}], n: 100, s: "silver", score: 1000, tier: true}], + [{n: 2, score: 7, s: "gold", b: 1, vip: false, tier: "a", items: [{price: 1, qty: 21, tag: "zz"}, {qty: 50, tag: null}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: 101, score: 1, s: true, b: 18, tier: "silver", items: [1, 2], extra: "e"}, {b: 18, extra: "e", items: [1, 2], n: 101, s: true, score: 1, tier: "silver"}], + [{n: -1, score: 101, s: 5, b: 74, vip: true, tier: null, items: [{price: 11, qty: -25, tag: "b"}, {price: 5, qty: 50, tag: "gold "}]}, {k628: 1, k629: 0.5, k635: false}], + [{n: 19.99, score: -0.1, b: null, vip: true, tier: "a", items: [{price: 26, qty: -5, tag: "zz"}]}, {k628: -0.1, k629: 0.5, k635: false}], + ], +} + +{ + name: "ga062: 3 nodes, expr, expr, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "cust", passThrough: true, fields: { + k636: "(not (100 in [1..100])) and (false)", + k637: "((-4) / 10 * age + age)", + }}, + {expression: "e2", passThrough: true, fields: { + k638: "flag ?? flag", + }}, + {expression: "e3", passThrough: true, fields: { + k639: "code ?? k636", + k640: "(k637 ?? -1) * (k637 ?? -1) * (k637 == null ? (2.25) / 4 : 10)", + k641: "(k637 ?? 0) * -(len((code ?? '')))", + k642: "(tier ?? 'none')", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e2 -> e3", + "e1 -> e3", + "e1 -> output", + "e3 -> output", + ], + }, + cases: [ + [{code: "bronze", tier: "b", flag: false, cust: null}, "!error"], + [{code: "zz", tier: "a", cust: null}, "!error"], + [{code: "zz", tier: "gold ", flag: true, cust: null}, "!error"], + [{code: "gold ", tier: null, flag: false, cust: {age: 0.1, tier: "silver", active: true}}, {code: "gold ", cust: {active: true, age: 0.1, tier: "silver"}, flag: false, k636: false, k637: 0.060, k638: false, k639: "gold ", k640: 0.036000, k641: -0.300, k642: "none"}], + [{code: "zz", tier: "x", flag: null, cust: {age: 0, tier: "b", active: false}}, {code: "zz", cust: {active: false, age: 0, tier: "b"}, k636: false, k637: 0, k639: "zz", k640: 0, k641: 0, k642: "x", tier: "x"}], + [{code: "gold ", tier: "zz", flag: false}, "!error"], + [{code: "", flag: false, cust: {age: null, tier: "Gold", active: null}}, "!error"], + [{code: "a", tier: "b", flag: false, cust: {age: 50, tier: "a", active: false}}, {code: "a", cust: {active: false, age: 50, tier: "a"}, flag: false, k636: false, k637: 30.00, k638: false, k639: "a", k640: 9000.0000, k641: -30.00, k642: "b", tier: "b"}], + [{code: null, tier: "", cust: null}, "!error"], + [{code: "gold ", flag: false, cust: {age: 21, tier: "a", active: false}, extra: [1, 2]}, {code: "gold ", cust: {active: false, age: 21, tier: "a"}, extra: [1, 2], flag: false, k636: false, k637: 12.60, k638: false, k639: "gold ", k640: 1587.6000, k641: -63.00, k642: "none"}], + [{code: "gold", tier: "a", flag: false, cust: {age: -0.1, active: true}}, {code: "gold", cust: {active: true, age: -0.1}, flag: false, k636: false, k637: -0.060, k638: false, k639: "gold", k640: 0.036000, k641: 0.240, k642: "a", tier: "a"}], + [{code: "gold", tier: "", flag: true, cust: {age: 2, tier: "", active: true}}, {code: "gold", cust: {active: true, age: 2, tier: ""}, flag: true, k636: false, k637: 1.20, k638: true, k639: "gold", k640: 14.4000, k641: -4.80, k642: "", tier: ""}], + [{code: "", tier: "a", flag: false, cust: {age: 1, tier: null, active: true}, extra: "e"}, {code: "", cust: {active: true, age: 1, tier: null}, extra: "e", flag: false, k636: false, k637: 0.60, k638: false, k639: "", k640: 3.6000, k641: 0, k642: "a", tier: "a"}], + [{code: "zz", tier: "bronze", flag: null, cust: {age: 11, tier: "gold ", active: false}}, {code: "zz", cust: {active: false, age: 11, tier: "gold "}, k636: false, k637: 6.60, k639: "zz", k640: 435.6000, k641: -13.20, k642: "bronze", tier: "bronze"}], + [{code: "Gold", tier: "gold", flag: null, cust: {age: 50, tier: "zz", active: false}, extra: "e"}, {code: "Gold", cust: {active: false, age: 50, tier: "zz"}, extra: "e", k636: false, k637: 30.00, k639: "Gold", k640: 9000.0000, k641: -120.00, k642: "gold", tier: "gold"}], + [{code: null, tier: "a", flag: null, cust: {age: 0, tier: "b", active: false}}, {cust: {active: false, age: 0, tier: "b"}, k636: false, k637: 0, k639: false, k640: 0, k641: 0, k642: "a", tier: "a"}], + [{code: null, tier: "Gold", cust: {age: 2, tier: "silver", active: null}}, {cust: {active: null, age: 2, tier: "silver"}, k636: false, k637: 1.20, k639: false, k640: 14.4000, k641: 0, k642: "Gold", tier: "Gold"}], + [{code: "Gold", tier: "gold", flag: false, cust: {age: 5, tier: "a", active: false}, extra: 1}, {code: "Gold", cust: {active: false, age: 5, tier: "a"}, extra: 1, flag: false, k636: false, k637: 3.00, k638: false, k639: "Gold", k640: 90.0000, k641: -12.00, k642: "gold", tier: "gold"}], + [{code: "gold", tier: "x", flag: true, cust: {age: 100, tier: "silver", active: false}, extra: 1}, {code: "gold", cust: {active: false, age: 100, tier: "silver"}, extra: 1, flag: true, k636: false, k637: 60.00, k638: true, k639: "gold", k640: 36000.0000, k641: -240.00, k642: "x", tier: "x"}], + [{code: "gold ", tier: "x", flag: false, extra: 1}, "!error"], + [{code: "x", tier: "gold", flag: false, cust: {age: 7, active: null}}, {code: "x", cust: {active: null, age: 7}, flag: false, k636: false, k637: 4.20, k638: false, k639: "x", k640: 176.4000, k641: -4.20, k642: "gold", tier: "gold"}], + [{code: "x", tier: "zz", flag: true, cust: {age: 50, tier: "silver", active: true}}, {code: "x", cust: {active: true, age: 50, tier: "silver"}, flag: true, k636: false, k637: 30.00, k638: true, k639: "x", k640: 9000.0000, k641: -30.00, k642: "zz", tier: "zz"}], + [{code: "x", tier: "b", flag: false, cust: null}, "!error"], + [{code: "b", tier: "silver", flag: false, cust: {tier: "Gold", active: false}, extra: [1, 2]}, "!error"], + [{code: "bronze", tier: "b", flag: true, cust: {age: -0.1, tier: "a", active: true}}, {code: "bronze", cust: {active: true, age: -0.1, tier: "a"}, flag: true, k636: false, k637: -0.060, k638: true, k639: "bronze", k640: 0.036000, k641: 0.360, k642: "b", tier: "b"}], + [{code: "gold", tier: "bronze", flag: null, cust: {age: 18, active: true}, extra: {deep: {x: 1}}}, {code: "gold", cust: {active: true, age: 18}, extra: {deep: {x: 1}}, k636: false, k637: 10.80, k639: "gold", k640: 1166.4000, k641: -43.20, k642: "bronze", tier: "bronze"}], + [{code: "b", tier: "Gold", flag: false, cust: {age: 7, tier: "b", active: false}}, {code: "b", cust: {active: false, age: 7, tier: "b"}, flag: false, k636: false, k637: 4.20, k638: false, k639: "b", k640: 176.4000, k641: -4.20, k642: "Gold", tier: "Gold"}], + [{code: "Gold", tier: "bronze", flag: true, cust: {tier: "silver", active: false}}, "!error"], + [{code: "silver", tier: "Gold", flag: true, cust: {age: null, tier: "b", active: true}}, "!error"], + ], +} + +{ + name: "ga063: 8 nodes, table, expr, table*, expr, expr, expr, expr, expr", + graph: { + nodes: [ + {table: "t1", inputs: ["s"], outputs: ["k643", "k644"], outputPath: "res", rules: [ + ["'gold'", "0", "string((vip ?? false))"], + ["not('x')", "len(string((a ?? 1) in [0..10]))", "'high'"], + ["not('a')", "(a ?? 1)", "''"], + ]}, + {expression: "e2", fields: { + k645: "s ?? a", + k646: "vip ?? vip", + k647: "0.5", + }}, + {table: "t3", hit: "collect", inputs: ["vip"], outputs: ["k648"], passThrough: true, outputPath: "out", rules: [ + ["$ == true", "true"], + ["true", "true"], + ]}, + {expression: "e4", fields: { + k649: "res.k643 ?? res.k644", + }}, + {expression: "e5", fields: { + k650: "res.k644 ?? res.k644", + k651: "(res.k643 ?? 1)", + }}, + {expression: "e6", fields: { + k652: "a ?? s", + k653: "(vip ? ((true ? (a ?? 0) : 3)) : (a ?? -1))", + }}, + {expression: "e7", fields: { + k654: "a ?? a", + }}, + {expression: "e8", fields: { + k655: "k651 ?? k651", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "input -> t3", + "t1 -> e4", + "input -> e4", + "t1 -> e5", + "t3 -> e6", + "t3 -> e7", + "e5 -> e8", + "e2 -> output", + "e4 -> output", + "e6 -> output", + "e7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{vip: true, s: {t: "x"}, a: null}, {k645: {t: "x"}, k646: true, k647: 0.5, k652: {t: "x"}, k653: 0, k655: 1}], + [{vip: true, s: "gold", a: -25}, {k645: "gold", k646: true, k647: 0.5, k649: 0, k652: -25, k653: -25, k654: -25, k655: 0}], + [{vip: false, s: {t: "x"}, a: {v: 1}}, {k645: {t: "x"}, k646: false, k647: 0.5, k652: {v: 1}, k653: {v: 1}, k654: {v: 1}, k655: 1}], + [{vip: true, s: "gold", a: 1000}, {k645: "gold", k646: true, k647: 0.5, k649: 0, k652: 1000, k653: 1000, k654: 1000, k655: 0}], + [{vip: false, s: null, a: 3}, {k645: 3, k646: false, k647: 0.5, k652: 3, k653: 3, k654: 3, k655: 1}], + [{vip: true, s: "zz", a: 11}, {k645: "zz", k646: true, k647: 0.5, k652: 11, k653: 11, k654: 11, k655: 1}], + [{vip: true, s: "bronze", a: {v: 1}, extra: 1}, {k645: "bronze", k646: true, k647: 0.5, k652: {v: 1}, k653: {v: 1}, k654: {v: 1}, k655: 1}], + [{vip: true, s: "x"}, {k645: "x", k646: true, k647: 0.5, k652: "x", k653: 0, k655: 1}], + [{vip: false, s: "gold ", a: null, extra: [1, 2]}, {k645: "gold ", k646: false, k647: 0.5, k652: "gold ", k653: -1, k655: 1}], + [{vip: null, a: null}, "!error"], + [{s: "gold ", a: null}, "!error"], + [{vip: false, s: "bronze", a: -25}, {k645: "bronze", k646: false, k647: 0.5, k652: -25, k653: -25, k654: -25, k655: 1}], + [{vip: true, s: "Gold", a: 1}, {k645: "Gold", k646: true, k647: 0.5, k652: 1, k653: 1, k654: 1, k655: 1}], + [{vip: true, s: "Gold"}, {k645: "Gold", k646: true, k647: 0.5, k652: "Gold", k653: 0, k655: 1}], + [{vip: false, s: "bronze", a: 0}, {k645: "bronze", k646: false, k647: 0.5, k652: 0, k653: 0, k654: 0, k655: 1}], + [{vip: false, s: "silver"}, {k645: "silver", k646: false, k647: 0.5, k652: "silver", k653: -1, k655: 1}], + [{vip: false, s: "a", a: 50}, {k645: "a", k646: false, k647: 0.5, k652: 50, k653: 50, k654: 50, k655: 1}], + [{vip: false, s: "bronze", a: 99}, {k645: "bronze", k646: false, k647: 0.5, k652: 99, k653: 99, k654: 99, k655: 1}], + [{vip: true, s: "", a: 2.5, extra: [1, 2]}, {k645: "", k646: true, k647: 0.5, k652: 2.5, k653: 2.5, k654: 2.5, k655: 1}], + [{vip: true, s: "gold ", a: 1000}, {k645: "gold ", k646: true, k647: 0.5, k652: 1000, k653: 1000, k654: 1000, k655: 1}], + [{vip: true, s: "bronze", a: 2}, {k645: "bronze", k646: true, k647: 0.5, k652: 2, k653: 2, k654: 2, k655: 1}], + [{vip: false, s: "", a: null}, {k645: "", k646: false, k647: 0.5, k652: "", k653: -1, k655: 1}], + [{s: "silver", a: 21}, "!error"], + [{vip: true, s: "bronze", a: 1000000000000000000000}, {k645: "bronze", k646: true, k647: 0.5, k652: 1000000000000000000000, k653: 1000000000000000000000, k654: 1000000000000000000000, k655: 1}], + ], +} + +{ + name: "ga064: 3 nodes, table*, table, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["s", "s"], outputs: ["g.k656"], passThrough: true, rules: [ + ["startsWith($, 'x')", "", "'low'"], + ["$ != 'gold'", "startsWith($, '')", "'gold'"], + ["$ != ''", "", "'mid'"], + ]}, + {table: "t2", inputs: ["b"], outputs: ["k657", "k657"], rules: [ + ["< -1", "false", "1"], + ["null", "true", "100"], + ["18", "false", "10"], + ]}, + {expression: "e3", fields: { + k659: "b ?? b", + k660: "(n ?? -1)", + k661: "(0.5 + (n ?? 0)) <= (n ?? -1)", + }}, + ], + edges: [ + "input -> t1", + "t1 -> t2", + "t1 -> e3", + "t2 -> output", + "e3 -> output", + ], + }, + cases: [ + [{tier: "b", n: 2, a: 2, nums: [-0.1], b: 3, s: "silver"}, "!error"], + [{tier: "silver", a: 101, nums: [0.1, 0.1], b: 2.5, s: "gold"}, "!error"], + [{tier: "x", n: 3, a: 1, nums: [3, 18, 2.5, 1, 50], b: 1000, s: "bronze"}, "!error"], + [{tier: "gold", n: null, a: 10, nums: [10, 50], b: 19.99}, "!error"], + [{tier: "x", n: [1], a: 101, nums: null, b: 18, s: "silver"}, "!error"], + [{tier: "b", n: 5, a: 99, b: true, s: null}, "!error"], + [{tier: "silver", nums: [11, 1, 5], b: 101, s: "silver"}, "!error"], + [{tier: "gold ", n: 100, a: null, nums: [10], b: 50, s: "b"}, "!error"], + [{tier: "Gold", n: 2, a: 50, nums: [1000, 1], b: 3, s: {t: "x"}}, "!error"], + [{tier: "Gold", n: 21, nums: [2, -1, 100], b: 100}, "!error"], + [{tier: "b", n: 2, s: "a"}, "!error"], + [{tier: "gold", n: -25, a: null, nums: [], b: -0.1, s: "bronze"}, "!error"], + [{tier: "Gold", n: 2.5, a: 50, nums: [0.1, -1], b: 5, s: "Gold", extra: "e"}, "!error"], + [{tier: "silver", n: 5, a: null, nums: ["1", 2], b: 7, s: "b"}, "!error"], + [{tier: "Gold", n: "abc", a: 18, nums: [], b: 75, s: "silver"}, "!error"], + [{tier: "b", n: 1, a: 3, nums: [31], b: 1000, s: "Gold"}, "!error"], + [{tier: "a", n: null, a: 2.5, nums: [21, 10], b: 100, s: "b"}, "!error"], + [{n: 2, a: 1000000000000000000000, nums: [11, 99, 0, 18, 19.99], b: 0.1, s: 5}, "!error"], + [{tier: "Gold", n: 99, a: 5, nums: "1,2", b: 18, s: null}, "!error"], + [{tier: "silver", n: 5, a: -25, nums: null, b: 1}, "!error"], + [{tier: "a", n: 3, a: 100, nums: [11, 0, 0.1, -25, 99], b: 0.5}, "!error"], + [{tier: null, n: 1, nums: [-1, -15, 0.5, 5, 0.1], b: 21, s: "Gold"}, "!error"], + [{tier: ["gold"], n: 0, a: 0.5, nums: [2.5], s: "silver"}, "!error"], + [{tier: "silver", n: 1000, a: 1000, nums: "1,2", b: 10, s: "Gold"}, "!error"], + [{tier: "b", n: 11, a: null, nums: [21, 0, 18, 19.99, 10], b: "abc", s: "bronze"}, "!error"], + [{tier: "a", n: -0.1, a: 1000, nums: null, b: 10, s: "gold", extra: "e"}, "!error"], + [{tier: "gold", a: 5, nums: [3, 7], b: 11, s: "gold"}, "!error"], + ], +} + +{ + name: "ga065: 6 nodes, table*, expr, switch, switch, table*, table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["price", "price", "flag"], outputs: ["k662", "k662"], outputPath: "o.p", rules: [ + ["[0..5]", "> 18", "$ == true", "'low'", "true"], + ["21, 26", "not(50)", "$ == true", "'x' + '-' + string(((flag ?? false)))", "true"], + ["", "[5..55)", "$ == true", "(s ?? '?')", "true"], + ["not(100)", "50", "null", "(flag == null ? string((flag ?? false)) + ' ' + (s ?? '') : string(((flag ?? false)) and ((flag ?? false))))", "not (endsWith(upper((s ?? '?')), ''))"], + ["$ > 50 and $ < 55", "<= 10", "$ == true", "'low'", "true"], + ["", "", "", "'low'", "false"], + ]}, + {expression: "e2", fields: { + k664: "len('gold' + ' ' + upper('x'))", + k665: "''", + }}, + {switch: "s3", when: ["(string((flag ?? false)) in ['gold', 'silver', 'a'])", "(b ?? -1) <= (b ?? -1)", ""]}, + {switch: "s4", when: ["(k665 ?? 'none') in ['gold', 'silver', 'a']", "max([(false ? (k664 ?? -1) : (b ?? 0)), (k664 ?? -1) % 7]) >= max([(b ?? b ?? 0), 2])", ""]}, + {table: "t5", hit: "collect", inputs: ["k665", "(k665 ?? 'none')"], outputs: ["g.k666", "k667"], outputPath: "res", rules: [ + ["", "not('a')", "'low'", "ceil((price ?? 0))"], + ["startsWith($, '')", "", "(s ?? '')", "2"], + ["null", "", "'mid'", "2"], + ]}, + {table: "t6", inputs: ["k664"], outputs: ["k662", "k669"], passThrough: true, rules: [ + ["< 10", "true", "1"], + ["[5..10)", "false", "0"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "t1 -> s3", + "input -> s3", + "s3:1 -> s4", + "e2 -> s4", + "s4:2 -> t5", + "s4:1 -> t6", + "s3:0 -> output", + "t5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{b: 0, price: 2.5, s: "zz", flag: true, extra: [1, 2]}, {b: 0, extra: [1, 2], flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 2.5, s: "zz"}], + [{price: [1], s: "a", flag: false, extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, flag: false, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: [1], s: "a"}], + [{b: 11, price: null, s: "x", flag: true}, {b: 11, flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, s: "x"}], + [{b: 0.5, price: "abc", s: "b", flag: true}, {b: 0.5, flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: "abc", s: "b"}], + [{b: 101, price: 2, s: "bronze", flag: false}, {b: 101, flag: false, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 2, s: "bronze"}], + [{b: 21, price: 2.5, s: "zz", flag: false}, {b: 21, flag: false, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 2.5, s: "zz"}], + [{b: 0.1, price: 1000000000000000000000, s: "bronze", flag: null}, {b: 0.1, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 1000000000000000000000, s: "bronze"}], + [{b: 100, price: 101, s: null, flag: false}, {b: 100, flag: false, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 101}], + [{b: 1000, price: 2.5, s: "bronze", flag: true}, {b: 1000, flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 2.5, s: "bronze"}], + [{b: 50, price: 19.99, flag: true, extra: 1}, {b: 50, extra: 1, flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: true}, {k662: false}]}, price: 19.99}], + [{b: null, s: "silver"}, {k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, s: "silver"}], + [{b: 1000000000000000000000, s: "x", flag: true}, {b: 1000000000000000000000, flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, s: "x"}], + [{b: 10, price: 3, s: "gold ", flag: false}, {b: 10, flag: false, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 3, s: "gold "}], + [{b: 0.5, price: -0.1, s: "bronze", flag: null}, {b: 0.5, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: -0.1, s: "bronze"}], + [{b: 1000000000000000000000, price: null, s: "x", flag: true}, {b: 1000000000000000000000, flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, s: "x"}], + [{b: 2, price: 2.5, s: "a", flag: true}, {b: 2, flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 2.5, s: "a"}], + [{b: 2, price: 101, s: "a", flag: true}, {b: 2, flag: true, k662: true, k664: 6, k665: "", k669: 1, o: {p: [{k662: false}]}, price: 101, s: "a"}], + ], +} + +{ + name: "ga066: 6 nodes, expr, switch*, expr, expr, table, table*", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k670: "0.5", + k671: "abs(($.k670 ?? 1)) * ($.k670 ?? -1) - -((vip ? 1 : 10))", + }}, + {switch: "s2", hit: "collect", when: ["not ((vip ?? false))", "`${0.5}-${'none'}` in ['gold', 'silver', 'a']", "(k670 ?? -1) in [0..10]"]}, + {expression: "e3", passThrough: true, fields: { + k672: "string((k670 ?? 0))", + }}, + {expression: "e4", passThrough: true, fields: { + k673: "(k670 ?? 0)", + }}, + {table: "t5", inputs: ["code"], outputs: ["k674", "k674"], rules: [ + ["", "false", "(len(code) >= (k670 ?? 1) * (n ?? 0))"], + ["startsWith($, 's')", "false", "true"], + ["not('silver')", "(not (n > n))", "(not ((k670 ?? 1) > (k671 ?? 1))) and ((vip ?? false))"], + ]}, + {table: "t6", hit: "collect", inputs: ["code", "code", "a"], outputs: ["k676[]", "k677"], rules: [ + ["'silver', 'bronze'", "", "(0..1)", "true", "-5"], + ["$ != 'silver'", "$ != 'gold'", "1, 11", "false", "10"], + ["startsWith($, 'g')", "", "[50..51)", "startsWith(`n=${(k671 ?? 0)}-${''}`, 'a')", "0.25"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "s2:0 -> e3", + "s2:0 -> e4", + "s2:2 -> t5", + "s2:1 -> t6", + "e3 -> output", + "e4 -> output", + "t5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{a: 10, vip: null, code: "silver", nums: [2, 11, -11], items: [{price: 50, qty: 18, tag: "gold"}, {price: -0.1, qty: 21, tag: "bronze"}], n: -1}, "!error"], + [{a: -1, vip: false, code: null, nums: "1,2", items: [{price: 26, qty: 10, tag: "a"}, {price: -8, tag: "gold "}, {price: true, qty: "5", tag: "gold "}], n: 11}, {a: -1, items: [{price: 26, qty: 10, tag: "a"}, {price: -8, tag: "gold "}, {price: true, qty: "5", tag: "gold "}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, n: 11, nums: "1,2", vip: false}], + [{a: 5, vip: null, code: "gold ", nums: [], items: [{qty: 5, tag: true}, {price: 21, qty: -0.1, tag: true}, {price: 0.1, qty: 0.5, tag: "gold "}, {price: 100, qty: 10, tag: "Gold"}], n: 1}, "!error"], + [{a: -25, vip: 1, items: [{price: "abc", qty: "5", tag: "zz"}], n: 101}, "!error"], + [{a: null, vip: false, nums: [1], items: [1, 2], n: 101}, {items: [1, 2], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, n: 101, nums: [1], vip: false}], + [{a: 0.1, vip: false, code: "gold ", nums: [1000, 99, 7], items: [], n: 21}, {a: 0.1, code: "gold ", items: [], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, k674: false, n: 21, nums: [1000, 99, 7], vip: false}], + [{a: -1, vip: "no", code: "Gold", nums: [-1, -0.1], items: [{price: -1, qty: 11, tag: "x"}], n: 0.1}, "!error"], + [{a: 99, vip: false, code: "Gold", nums: [-25], items: [{price: 21, qty: null, tag: "gold "}, {price: -1, qty: 18}], n: 5}, {a: 99, code: "Gold", items: [{price: 21, qty: null, tag: "gold "}, {price: -1, qty: 18}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, k674: true, n: 5, nums: [-25], vip: false}], + [{a: 2.5, vip: true, code: "silver", nums: [2.5, 7], items: [{price: 18, qty: -0.1, tag: "gold "}, {price: 2.5, qty: 5, tag: "bronze"}, {price: 101, qty: 2.5, tag: null}, {price: 10, qty: 1000000000000000000000, tag: null}], n: 21}, {k674: false}], + [{a: 1000000000000000000000, vip: false, code: null, nums: [], items: [], n: true}, {a: 1000000000000000000000, items: [], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, n: true, nums: [], vip: false}], + [{a: -0.1, vip: true, code: "Gold", nums: [1], items: [{price: -1, qty: 7, tag: "gold "}, {price: 11, qty: null, tag: null}], n: 1000000000000000000000}, {k674: false}], + [{a: 11, code: "x", nums: [-25, 2.5, 5, 2, 101], items: [{price: 11, qty: 18, tag: "silver"}, {price: 99, qty: 1000, tag: "a"}, {price: 5, tag: "silver"}, {price: 100, qty: 11, tag: "gold "}], n: null}, "!error"], + [{a: 1000000000000000000000, vip: true, code: "silver", nums: [-1, 2], items: [{price: 1000, qty: 99, tag: "zz"}, {price: 2.5, qty: 100, tag: "silver"}, {price: null, qty: -0.1, tag: "x"}, {price: 1, qty: 19.99, tag: "Gold"}], n: -0.1}, {k674: true}], + [{a: 18, vip: false, code: "silver", nums: [1000000000000000000000, 0], items: [{qty: true, tag: "b"}, {price: 95, qty: 11, tag: "gold "}, {price: 10, qty: 0, tag: "gold "}], n: 1}, {a: 18, code: "silver", items: [{qty: true, tag: "b"}, {price: 95, qty: 11, tag: "gold "}, {price: 10, qty: 0, tag: "gold "}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, k674: true, n: 1, nums: [1000000000000000000000, 0], vip: false}], + [{a: 2.5, vip: false, items: [{price: 0.5, qty: 100, tag: "b"}], n: 2.5}, {a: 2.5, items: [{price: 0.5, qty: 100, tag: "b"}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, n: 2.5, vip: false}], + [{a: null, vip: false, code: "b", nums: [], items: [{price: 0.5, qty: 1, tag: "gold "}, {price: 2, qty: true, tag: "zz"}, {price: 2, qty: 97, tag: null}], n: "abc"}, {code: "b", items: [{price: 0.5, qty: 1, tag: "gold "}, {price: 2, qty: true, tag: "zz"}, {price: 2, qty: 97, tag: null}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, n: "abc", nums: [], vip: false}], + [{a: 50, vip: true, code: "gold", nums: [2], items: [], n: 2.5}, {k674: true}], + [{a: 0, vip: 1, code: "", nums: 7, items: [{price: 0, qty: 50, tag: "Gold"}]}, "!error"], + [{a: 2, vip: true, code: "bronze", nums: [], items: [{price: 21, qty: 11, tag: 5}, {price: 0.1, qty: -25, tag: "zz"}, {price: 99, qty: -1, tag: "x"}, {price: 19.99, qty: 11, tag: "bronze"}], n: 50}, {k674: false}], + [{vip: true, code: "bronze", nums: null, items: [{price: 21, qty: 7, tag: "a"}, {price: 53, qty: 11, tag: "a"}, {price: 1000, qty: 10, tag: "gold "}, {qty: 2.5, tag: "x"}], n: 2.5}, {k674: true}], + [{a: 0, vip: true, items: [{qty: 0, tag: "bronze"}, {}], n: null}, {}], + [{a: 18, vip: false, code: "b", nums: [21], items: [{price: 101, qty: 101, tag: "Gold"}, {price: 2, qty: 2.5, tag: "Gold"}, {price: 100, qty: 0, tag: "zz"}], n: -1}, {a: 18, code: "b", items: [{price: 101, qty: 101, tag: "Gold"}, {price: 2, qty: 2.5, tag: "Gold"}, {price: 100, qty: 0, tag: "zz"}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, k674: true, n: -1, nums: [21], vip: false}], + [{a: 0.1, vip: false, code: "silver", nums: [], items: [{price: 100, qty: -1, tag: "b"}, {price: 19.99, qty: 18, tag: "zz"}], n: 1}, {a: 0.1, code: "silver", items: [{price: 100, qty: -1, tag: "b"}, {price: 19.99, qty: 18, tag: "zz"}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, k674: true, n: 1, nums: [], vip: false}], + [{a: null, vip: 0, code: "x", nums: [1, -25, 7], n: 99}, "!error"], + [{vip: true, code: "b", nums: [2, 50], items: [], n: 100}, {k674: false}], + [{a: 18, vip: null, code: 5, nums: [], items: [{price: 3, qty: 0, tag: "bronze"}, {price: true, qty: 0, tag: "gold"}, {price: 10, qty: 2.5}, {price: 5, qty: 0, tag: "gold"}], n: [1]}, "!error"], + [{a: 19.99, vip: true, code: "b", nums: [0.1], items: [{price: 18, qty: 1, tag: "b"}, {price: null, qty: 50, tag: "Gold"}, {price: 0, qty: 5, tag: "gold"}, {price: 50, qty: 11, tag: "a"}], n: 0.1}, {k674: true}], + [{a: 7, vip: false, code: "zz", nums: [0, 18, -0.1, -25, 7], items: [{price: -1, qty: 1000, tag: "x"}, {price: 2, qty: null, tag: "b"}], n: 5}, {a: 7, code: "zz", items: [{price: -1, qty: 1000, tag: "x"}, {price: 2, qty: null, tag: "b"}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, k674: false, n: 5, nums: [0, 18, -0.1, -25, 7], vip: false}], + [{a: 50, vip: null, code: "a", nums: [50, 1000000000000000000000, 1], items: [{price: 21}], n: -25}, "!error"], + [{a: 10, vip: false, nums: [0.5], items: [{price: 21, qty: 0.1, tag: "bronze"}, {qty: 1000}, {price: 50, qty: 1, tag: "a"}], n: 18}, {a: 10, items: [{price: 21, qty: 0.1, tag: "bronze"}, {qty: 1000}, {price: 50, qty: 1, tag: "a"}], k670: 0.5, k671: 10.25, k672: "0.5", k673: 0.5, n: 18, nums: [0.5], vip: false}], + ], +} + +{ + name: "ga067: 6 nodes, switch, switch, expr, expr, expr, table*", + graph: { + nodes: [ + {switch: "s1", when: ["(score ?? 0) in [0..10]", ""]}, + {switch: "s2", when: ["(score ?? 0) in [-5..5]"]}, + {expression: "e3", fields: { + "m.k678": "score", + k679: "vip ?? vip", + k680: "score * (b ?? -1) % 3 < len('none') % 3", + k681: "10 * 3 * (b ?? 1) >= ((score ?? -1)) * -4", + }}, + {expression: "e4", passThrough: true, fields: { + k682: "(score ?? 0)", + }}, + {expression: "e5", fields: { + "res.k683": "('none' != 'x' ? (score ?? 0) : ((m.k678 ?? 1)) / 0.5)", + k684: "lower(string((score ?? 1)))", + }}, + {table: "t6", hit: "collect", inputs: ["(2.25 * 2)"], outputs: ["m.k685"], passThrough: true, outputPath: "res", rules: [ + ["[100..150)", "'mid'"], + ["[1..51)", "'high'"], + ["", "'high'"], + ["(18..19)", "upper('A-1')"], + ["", "'gold'"], + ]}, + ], + edges: [ + "input -> s1", + "input -> s2", + "s1:1 -> e3", + "e3 -> e4", + "s2:0 -> e4", + "e4 -> e5", + "e3 -> t6", + "s2:0 -> t6", + "s1:0 -> output", + "e5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{score: 5, vip: true, b: 11}, {b: 11, k684: "5", res: {k683: 5}, score: 5, vip: true}], + [{score: 50, vip: false}, {k679: false, k680: true, k681: true, k684: "1", m: {k678: 50}, res: {k683: 0}}], + [{score: 11, vip: false, b: 19.99}, {k679: false, k680: true, k681: true, k684: "1", m: {k678: 11}, res: {k683: 0}}], + [{score: 101, vip: true, b: 1000}, {k679: true, k680: false, k681: true, k684: "1", m: {k678: 101}, res: {k683: 0}}], + [{score: -0.1, vip: false, b: -0.1}, {b: -0.1, k679: false, k680: true, k681: false, k684: "-0.1", m: {k678: -0.1}, res: {k683: -0.1}, score: -0.1, vip: false}], + [{score: 18, vip: true, b: 50}, {k679: true, k680: true, k681: true, k684: "1", m: {k678: 18}, res: {k683: 0}}], + [{score: -25, vip: 0, b: 11, extra: "e"}, {k679: 0, k680: true, k681: true, k684: "1", m: {k678: -25}, res: {k683: 0}}], + [{score: -1, vip: false, b: 11}, {b: 11, k679: false, k680: true, k681: true, k684: "-1", m: {k678: -1}, res: {k683: -1}, score: -1, vip: false}], + [{score: -0.1, vip: false, b: [1], extra: {deep: {x: 1}}}, "!error"], + [{score: 50, vip: false, extra: [1, 2]}, {k679: false, k680: true, k681: true, k684: "1", m: {k678: 50}, res: {k683: 0}}], + [{score: 101, vip: false, b: 2.5}, {k679: false, k680: true, k681: true, k684: "1", m: {k678: 101}, res: {k683: 0}}], + [{score: 1, vip: false, b: -25}, {b: -25, k684: "1", res: {k683: 1}, score: 1, vip: false}], + [{score: "abc", vip: "true", b: 21}, "!error"], + [{score: -0.1, vip: false, b: -0.1, extra: {deep: {x: 1}}}, {b: -0.1, extra: {deep: {x: 1}}, k679: false, k680: true, k681: false, k684: "-0.1", m: {k678: -0.1}, res: {k683: -0.1}, score: -0.1, vip: false}], + [{score: 101, vip: null, b: 7, extra: "e"}, {k680: false, k681: true, k684: "1", m: {k678: 101}, res: {k683: 0}}], + [{score: 2.5, vip: false, b: 5, extra: {deep: {x: 1}}}, {b: 5, extra: {deep: {x: 1}}, k684: "2.5", res: {k683: 2.5}, score: 2.5, vip: false}], + [{score: -0.1, vip: "no", b: 2, extra: "e"}, {b: 2, extra: "e", k679: "no", k680: true, k681: true, k684: "-0.1", m: {k678: -0.1}, res: {k683: -0.1}, score: -0.1, vip: "no"}], + [{score: 0.5, vip: true, b: 2}, {b: 2, k684: "0.5", res: {k683: 0.5}, score: 0.5, vip: true}], + [{score: 18, vip: false, b: 5}, {k679: false, k680: true, k681: true, k684: "1", m: {k678: 18}, res: {k683: 0}}], + [{score: 0.1, vip: false, b: -1}, {b: -1, k684: "0.1", res: {k683: 0.1}, score: 0.1, vip: false}], + [{score: -1, vip: false, b: 5}, {b: 5, k679: false, k680: true, k681: true, k684: "-1", m: {k678: -1}, res: {k683: -1}, score: -1, vip: false}], + [{score: 2, vip: true, b: 0.1}, {b: 0.1, k684: "2", res: {k683: 2}, score: 2, vip: true}], + ], +} + +{ + name: "ga068: 6 nodes, switch, table*, expr, expr, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["min([(-4), (a ?? 0)]) in [0..10]", "(len('')) / 10 == len('A-1')", "false", ""]}, + {table: "t2", hit: "collect", inputs: ["a"], outputs: ["k686", "k687"], passThrough: true, rules: [ + ["> 100", "'gold'", "false"], + ["-1", "'mid'", "'' + '' + 'x' + ' ' + string((a ?? -1)) in ['gold', 'silver', 'a']"], + ["< 0", "'high'", "true"], + ["!= 5", "'A-1'", "(10) in [-5..5]"], + ["null", "''", "false"], + [">= 18", "'gold'", "-((a ?? 1)) in [0..10]"], + ["", "'high'", "true"], + ]}, + {expression: "e3", inputField: "cust", outputPath: "out", fields: { + "g.k688": "age ?? age", + k689: "(age ?? age ?? 0)", + k690: "endsWith('', 'g')", + k691: "string(3 * (age ?? 0) <= age + 3)", + }}, + {expression: "e4", outputPath: "out", fields: { + k692: "(a ?? a ?? 0)", + k693: "-((a ?? 1))", + "res.k694": "$.k692 ?? $.k693", + k695: "($.k693 ?? 0)", + }}, + {expression: "e5", passThrough: true, fields: { + k696: "out.k689", + }}, + {table: "t6", inputs: ["out.k690", "out.k690"], outputs: ["k697"], rules: [ + ["$ == true", "true", "false"], + ["", "true", "true"], + ["$ == true", "false", "false"], + ["", "", "true"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> t2", + "input -> e3", + "s1:0 -> e4", + "e3 -> e5", + "e3 -> t6", + "e4 -> t6", + "s1:2 -> output", + "s1:3 -> output", + "t2 -> output", + "e5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{cust: {age: 50, tier: "silver", active: false}, a: 99, nums: [7, 10, 0], extra: {deep: {x: 1}}}, {a: 99, cust: {active: false, age: 50, tier: "silver"}, extra: {deep: {x: 1}}, k696: 50, k697: true, nums: [7, 10, 0], out: {g: {k688: 50}, k689: 50, k690: false, k691: "false"}}], + [{cust: {age: 100, tier: "Gold", active: false}, a: 100, nums: null}, {a: 100, cust: {active: false, age: 100, tier: "Gold"}, k696: 100, k697: true, out: {g: {k688: 100}, k689: 100, k690: false, k691: "false"}}], + [{cust: null, a: null}, "!error"], + [{cust: 5, a: 1}, "!error"], + [{cust: {age: 19.99, tier: "x", active: false}, a: 0.1, nums: [0.5]}, {a: 0.1, cust: {active: false, age: 19.99, tier: "x"}, k696: 19.99, k697: true, nums: [0.5], out: {g: {k688: 19.99}, k689: 19.99, k690: false, k691: "false"}}], + [{cust: {age: 50, tier: "zz", active: false}, a: 3, nums: [101, 36, 11]}, {a: 3, cust: {active: false, age: 50, tier: "zz"}, k696: 50, k697: true, nums: [101, 36, 11], out: {g: {k688: 50}, k689: 50, k690: false, k691: "false"}}], + [{cust: {age: 71, tier: "x", active: false}, a: 0}, {a: 0, cust: {active: false, age: 71, tier: "x"}, k696: 71, k697: true, out: {g: {k688: 71}, k689: 71, k690: false, k691: "false"}}], + [{cust: {age: -25, tier: "bronze", active: true}, a: 5, nums: [-1, 0, 7, 1, -1], extra: 1}, {a: 5, cust: {active: true, age: -25, tier: "bronze"}, extra: 1, k696: -25, k697: true, nums: [-1, 0, 7, 1, -1], out: {g: {k688: -25}, k689: -25, k690: false, k691: "true"}}], + [{cust: {age: 21, tier: "b", active: false}, a: 21, nums: []}, {a: 21, cust: {active: false, age: 21, tier: "b"}, k696: 21, k697: true, nums: [], out: {g: {k688: 21}, k689: 21, k690: false, k691: "false"}}], + [{cust: {age: 50, tier: "Gold", active: false}, a: 57, nums: []}, {a: 57, cust: {active: false, age: 50, tier: "Gold"}, k696: 50, k697: true, nums: [], out: {g: {k688: 50}, k689: 50, k690: false, k691: "false"}}], + [{cust: {age: 1, tier: "gold ", active: true}, a: 19.99, nums: [2.5, 1, 50]}, {a: 19.99, cust: {active: true, age: 1, tier: "gold "}, k696: 1, k697: true, nums: [2.5, 1, 50], out: {g: {k688: 1}, k689: 1, k690: false, k691: "true"}}], + [{cust: {age: 2.5, tier: "zz", active: false}, a: -0.1, nums: [5]}, {a: -0.1, cust: {active: false, age: 2.5, tier: "zz"}, k696: 2.5, k697: true, nums: [5], out: {g: {k688: 2.5}, k689: 2.5, k690: false, k691: "false"}}], + [{cust: {age: 11, tier: "zz", active: true}, a: 10, nums: [21, 99, 3, 5, 0]}, {a: 10, cust: {active: true, age: 11, tier: "zz"}, k696: 11, k697: true, nums: [21, 99, 3, 5, 0], out: {g: {k688: 11}, k689: 11, k690: false, k691: "false"}}], + [{cust: {tier: null, active: true}, a: -0.1, nums: []}, "!error"], + [{cust: {age: 11, tier: "bronze", active: true}}, {cust: {active: true, age: 11, tier: "bronze"}, k696: 11, k697: true, out: {g: {k688: 11}, k689: 11, k690: false, k691: "false"}}], + [{cust: {age: 2, active: "no"}, a: 10, extra: 1}, {a: 10, cust: {active: "no", age: 2}, extra: 1, k696: 2, k697: true, out: {g: {k688: 2}, k689: 2, k690: false, k691: "false"}}], + ], +} + +{ + name: "ga069: 3 nodes, table, switch*, expr", + graph: { + nodes: [ + {table: "t1", inputs: ["price", "price", "lower(string(false))"], outputs: ["k698", "k699"], rules: [ + ["[1..2)", "", "'x', 'b'", "'high'", "'mid'"], + ["< 5", "<= 20", "", "'high'", "string((not (true) ? (a ?? score ?? 0) : (false ? (a ?? 1) : -4)))"], + ["!= 100", "<= 71", "null", "'low'", "'gold'"], + ["", "< 1", "$ != 'gold'", "'high'", "''"], + ["$ > 5 and $ < 55", "(1..51)", "null", "(string(true) in ['gold', 'silver', 'a'] ? string((false) or (true)) : ((true) and (false) ? `${0}-${'none'}` : string(true)))", "'low'"], + ["", "", "", "(s ?? 'none')", "'low'"], + ]}, + {switch: "s2", hit: "collect", when: ["contains(string((a ?? 1)), 'g')", "len(s) * floor((price ?? -1)) in [1..100]", ""]}, + {expression: "e3", passThrough: true, outputPath: "o.p", fields: { + "g.k700": "k698 ?? k698", + k701: "min([(0 ?? 1 ?? 0) * 0, len(upper((k698 ?? '?')))])", + }}, + ], + edges: [ + "input -> t1", + "input -> s2", + "t1 -> e3", + "s2:0 -> output", + "s2:2 -> output", + "e3 -> output", + ], + }, + cases: [ + [{score: 1000, nums: [-1, 18, 2.5], a: 100, price: 0.1, s: "zz"}, {a: 100, k698: "high", k699: "-4", nums: [-1, 18, 2.5], o: {p: {g: {k700: "high"}, k701: 0}}, price: 0.1, s: "zz", score: 1000}], + [{score: 5, nums: [21, 1000000000000000000000, -1], a: 0.5, price: 2.5, s: "Gold"}, {a: 0.5, k698: "high", k699: "-4", nums: [21, 1000000000000000000000, -1], o: {p: {g: {k700: "high"}, k701: 0}}, price: 2.5, s: "Gold", score: 5}], + [{score: 10, nums: [50], a: null, price: -25, s: "bronze"}, {k698: "high", k699: "-4", nums: [50], o: {p: {g: {k700: "high"}, k701: 0}}, price: -25, s: "bronze", score: 10}], + [{score: 18, nums: [], price: 18, s: "a"}, {k698: "a", k699: "low", nums: [], o: {p: {g: {k700: "a"}, k701: 0}}, price: 18, s: "a", score: 18}], + [{score: -19, nums: [], a: 0, price: 0, s: "zz"}, {a: 0, k698: "high", k699: "-4", nums: [], o: {p: {g: {k700: "high"}, k701: 0}}, price: 0, s: "zz", score: -19}], + [{score: null, nums: null, a: {v: 1}, price: -1, s: "bronze", extra: "e"}, {a: {v: 1}, extra: "e", k698: "high", k699: "-4", o: {p: {g: {k700: "high"}, k701: 0}}, price: -1, s: "bronze"}], + [{nums: [29], a: [1], price: 100, s: "zz"}, {a: [1], k698: "zz", k699: "low", nums: [29], o: {p: {g: {k700: "zz"}, k701: 0}}, price: 100, s: "zz"}], + [{score: 11, nums: [19.99, 1000000000000000000000], price: 101, s: null}, {k698: "none", k699: "low", nums: [19.99, 1000000000000000000000], o: {p: {g: {k700: "none"}, k701: 0}}, price: 101, score: 11}], + [{score: 2, nums: [99, 100, 0.5, 2, 2.5], a: 50, price: true, s: "gold"}, {a: 50, k698: "gold", k699: "low", nums: [99, 100, 0.5, 2, 2.5], o: {p: {g: {k700: "gold"}, k701: 0}}, price: true, s: "gold", score: 2}], + [{score: -0.1, nums: null, a: 101, price: -0.1, s: null}, {a: 101, k698: "high", k699: "-4", o: {p: {g: {k700: "high"}, k701: 0}}, price: -0.1, score: -0.1}], + [{score: 2, nums: [0], price: 0.1, s: null, extra: 1}, {extra: 1, k698: "high", k699: "-4", nums: [0], o: {p: {g: {k700: "high"}, k701: 0}}, price: 0.1, score: 2}], + [{nums: null, a: 11, price: 19.99, s: "b"}, {a: 11, k698: "b", k699: "low", o: {p: {g: {k700: "b"}, k701: 0}}, price: 19.99, s: "b"}], + [{score: 99, nums: [1000], a: 1000, price: 0, s: "gold"}, {a: 1000, k698: "high", k699: "-4", nums: [1000], o: {p: {g: {k700: "high"}, k701: 0}}, price: 0, s: "gold", score: 99}], + [{score: {v: 1}, nums: [2.5, -25, 99, 46, 1], a: 119, price: -0.1, s: "bronze", extra: "e"}, {a: 119, extra: "e", k698: "high", k699: "-4", nums: [2.5, -25, 99, 46, 1], o: {p: {g: {k700: "high"}, k701: 0}}, price: -0.1, s: "bronze", score: {v: 1}}], + [{score: 7, nums: [3, 1000000000000000000000, -1], a: "abc", price: 50, s: "bronze"}, {a: "abc", k698: "bronze", k699: "low", nums: [3, 1000000000000000000000, -1], o: {p: {g: {k700: "bronze"}, k701: 0}}, price: 50, s: "bronze", score: 7}], + [{score: 100, nums: [], a: 1, price: 100, s: "b"}, {a: 1, k698: "b", k699: "low", nums: [], o: {p: {g: {k700: "b"}, k701: 0}}, price: 100, s: "b", score: 100}], + [{score: -0.1, nums: [101, -0.1], a: 2, price: 0.5, s: ""}, {a: 2, k698: "high", k699: "-4", nums: [101, -0.1], o: {p: {g: {k700: "high"}, k701: 0}}, price: 0.5, s: "", score: -0.1}], + [{score: 0.5, nums: [2, 2.5], a: -25, price: 99, s: "gold "}, {a: -25, k698: "gold ", k699: "low", nums: [2, 2.5], o: {p: {g: {k700: "gold "}, k701: 0}}, price: 99, s: "gold ", score: 0.5}], + [{score: 0.5, nums: [-25], a: null, s: 5}, "!error"], + ], +} + +{ + name: "ga070: 6 nodes, expr, table, table, table, table, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k702: "string(not ((s ?? '') in ['gold', 'silver', 'a']))", + k703: "((true) ? ((price ?? 1)) : (false ? (score ?? -1) : 10))", + k704: "len(string(true)) * price", + }}, + {table: "t2", inputs: ["score", "`n=${3}-${'A-1'}`", "(score ?? 0)"], outputs: ["k705"], rules: [ + ["", "", "null", "0.25"], + ["0, 1", "null", "null", "1"], + ["", "$ != ''", ">= 18", "2"], + ["not(50)", "null", "$ > 21 and $ < 31", "-5"], + ]}, + {table: "t3", inputs: ["k705"], outputs: ["m.k706", "k707"], outputPath: "o.p", rules: [ + ["!= 18", "false", "0"], + ["< 50", "(true) and (((k705 ?? -1) <= (k705 ?? 0)))", "0"], + ["5, 55", "false", "100"], + ["21", "false", "0"], + ["> 0", "true", "(-((k705 ?? 0))) + (-4)"], + [">= -1", "true", "10"], + ["", "true", "max([(k705 ?? 1) - (k705 ?? 1), (k705 ?? 0)]) - (k705) - ((k705 ?? -1))"], + ]}, + {table: "t4", inputs: ["k702"], outputs: ["k708", "res.k709"], outputPath: "res", rules: [ + ["null", "2", "'high'"], + ["$ != 'gold'", "1", "'gold'"], + ["", "0", "'high'"], + ]}, + {table: "t5", inputs: ["((k705 ?? 0))", "k705", "k705"], outputs: ["k710"], outputPath: "lines", rules: [ + ["!= 1", "", "(5..55)", "(false ? lower('A-1') + '' + 'none' : 'gold')"], + ["< 1", "[-1..9]", "not(-1)", "trim('x' + ':' + 'x') + ':' + ''"], + ["[21..22]", "> 5", "", "'high'"], + ["!= 10", "(1..51)", "", "'low'"], + ["[100..150]", "<= 5", "<= 150", "string('x' in ['gold', 'silver', 'a'])"], + ]}, + {expression: "e6", fields: { + k711: "((o.p.k707)) * (o.p.k707 ?? o.p.k707 ?? 0)", + }}, + ], + edges: [ + "input -> e1", + "input -> t2", + "t2 -> t3", + "t2 -> t4", + "e1 -> t4", + "t2 -> t5", + "t3 -> e6", + "t3 -> output", + "t4 -> output", + "t5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{price: 5, s: "", tier: "b", score: 1000000000000000000000, code: "bronze"}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 21, s: "Gold", tier: "Gold", score: null, code: "zz"}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 1000000000000000000000, s: "zz", tier: "zz", score: -1, code: "bronze"}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: null, s: "a", tier: "gold", score: 10, code: "gold "}, "!error"], + [{price: 0, s: "zz", tier: "zz", score: null, code: "b"}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 1, s: null, tier: "bronze", score: 109, code: "bronze"}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: -25, s: "bronze", tier: "bronze", score: 10, code: ""}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: -1, s: "gold ", tier: null, code: "gold", extra: [1, 2]}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 1000000000000000000000, s: "", tier: "silver", score: 19.99, code: null}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 1, s: "bronze", tier: "Gold", score: null, code: null, extra: [1, 2]}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: null, s: "gold", tier: "Gold", score: 2.5, code: ""}, "!error"], + [{price: 0.5, s: "zz", tier: "Gold", score: 5, code: ""}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 2, s: "gold", tier: "a", score: 0.5, extra: {deep: {x: 1}}}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 5, s: "a", tier: "b", score: 5, code: "x"}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: -0.1, s: "b", tier: "b", score: -3, code: "gold"}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 99, s: "x", tier: "b", score: 19.99, extra: {deep: {x: 1}}}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 101, s: "x", tier: "x", score: -3, extra: "e"}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 1000, s: "a", tier: "gold ", score: 18, code: "zz"}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{s: "x", tier: "", score: 1000, code: "gold"}, "!error"], + [{price: 0.1, s: "bronze", tier: "gold", score: 21, code: "bronze"}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 18, s: "silver", tier: "bronze", code: "bronze"}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 99, s: "Gold", score: -0.1, code: "silver"}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: -25, s: "gold ", tier: "x", score: 99, code: "b", extra: "e"}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{s: "gold", tier: "gold", score: 21, code: null}, "!error"], + [{price: 100, tier: null, score: 19.99, code: "b"}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{s: "silver", tier: "a", score: null, code: "b"}, "!error"], + [{s: "bronze", tier: "Gold", score: 21, code: "Gold"}, "!error"], + [{price: 1000000000000000000000, s: "Gold", tier: "gold ", code: "gold", extra: [1, 2]}, {k711: 0, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + [{price: 2.5, s: "a", tier: null, score: 18, code: null}, {k711: 0, lines: {k710: "low"}, o: {p: {k707: 0, m: {k706: false}}}, res: {k708: 1, res: {k709: "gold"}}}], + ], +} + +{ + name: "ga071: 5 nodes, table*, table*, table*, expr, table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["a"], outputs: ["k712[]", "k713"], outputPath: "res", rules: [ + ["", "true", "'low'"], + ["null", "not (flag != null)", "''"], + ["", "true", "'high'"], + ]}, + {table: "t2", hit: "collect", inputs: ["2.25", "len('gold') % 2", "trim(string(false))"], outputs: ["k714[]", "k715"], outputPath: "lines", rules: [ + ["$ > 5 and $ < 6", "100", "$ != 'x'", "true", "(a != null)"], + ["[1..11)", "", "$ != 'silver'", "'x' in ['gold', 'silver', 'a']", "true"], + ["[50..100]", "[-1..49)", "'x'", "false", "true"], + ["!= 10", "$ > 50 and $ < 51", "", "false", "true"], + ["(-1..9)", "0, 1", "$ != 'x'", "true", "'A-1' in ['gold', 'silver', 'a']"], + ["[50..51]", "", "'x'", "false", "false"], + ["", "", "", "true", "false"], + ]}, + {table: "t3", hit: "collect", inputs: ["a", "a"], outputs: ["m.k716"], outputPath: "o.p", rules: [ + ["not(21)", "-1, 4", "true"], + ["", "[-1..4)", "true"], + ["!= 21", "null", "true"], + ["$ > 50 and $ < 100", "", "false"], + ["$ > 50 and $ < 51", "not(50)", "false"], + ["", "", "false"], + ]}, + {expression: "e4", fields: { + k713: "(a ?? 0)", + k718: "cust.active ?? vip", + }}, + {table: "t5", inputs: ["-4"], outputs: ["k719", "k720"], passThrough: true, rules: [ + ["not(1)", "'mid'", "(false)"], + ["null", "''", "true"], + ["", "'high'", "false"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> t2", + "t2 -> t3", + "input -> t3", + "input -> e4", + "t2 -> e4", + "t1 -> t5", + "t3 -> output", + "e4 -> output", + "t5 -> output", + ], + }, + cases: [ + [{flag: false, code: "b", cust: {age: 11, active: false}, s: "Gold", a: 99, vip: true, nums: [-0.1], extra: 1}, {k713: 99, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: false}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "gold", cust: {age: 0.1, tier: "bronze", active: true}, s: "b", a: 99, vip: null, nums: [2, -25, 33]}, {k713: 99, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: false}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: true, code: "b", cust: {age: -0.1, tier: null, active: true}, s: "a", a: 7, nums: [2]}, {k713: 7, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "", cust: {age: 7, active: false}, s: "Gold", a: 19.99, vip: false, nums: []}, {k713: 19.99, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: null, code: "Gold", cust: {age: 0, tier: "Gold", active: false}, s: "silver", a: 2, vip: true, nums: [3, 7]}, {k713: 2, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: null, code: "", cust: {age: 2, tier: "", active: false}, s: "", a: 0.5, vip: false}, {k713: 0.5, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{code: "bronze", cust: {age: 100, tier: "x", active: false}, s: "silver", a: 7, vip: false, nums: [67, 21]}, {k713: 7, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "zz", cust: {age: 0.1, tier: "", active: true}, s: "gold ", a: -0.1, vip: true, nums: [101, 101]}, {k713: -0.1, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: true, code: "x", cust: {age: 11, tier: "", active: false}, s: "bronze", a: 7, vip: false, nums: [-25, 0.5, 1]}, {k713: 7, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{code: "Gold", cust: {age: 10, tier: "a", active: false}, s: "Gold", a: 2, vip: false, nums: []}, {k713: 2, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "gold ", cust: {age: 5, tier: null, active: false}, s: null, a: 5, vip: true, nums: [99, 1, 2.5, 101, 19.99]}, {k713: 5, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: true, code: "gold", cust: {age: 2.5, tier: "b", active: false}, s: "", a: 2, vip: null, nums: []}, {k713: 2, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "gold", cust: {age: 3, tier: "bronze", active: false}, s: "x", a: 2, vip: true, nums: [1, -1]}, {k713: 2, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{code: "zz", cust: {age: 3, tier: "b", active: true}, s: "a", a: 1, vip: true, nums: []}, {k713: 1, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "zz", cust: null, s: "zz", a: null, vip: true, nums: []}, {k713: 0, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: false, k713: ""}, {k712: true, k713: "high"}]}], + [{flag: true, code: "gold", cust: {age: 101, tier: "gold", active: true}, s: "silver", a: 11, vip: true, nums: null}, {k713: 11, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: true, code: "silver", cust: {age: 3, tier: "gold", active: null}, s: "gold", a: 50, vip: false, nums: [100]}, {k713: 50, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "b", cust: {age: 5, tier: "", active: true}, a: 2.5, vip: true, nums: []}, {k713: 2.5, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "zz", cust: {age: 1000000000000000000000, tier: "zz", active: true}, s: "bronze", a: -0.1, vip: false, nums: null}, {k713: -0.1, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: true, code: "zz", cust: {age: 56, active: true}, s: "zz", a: 21, vip: null, nums: [10, 18]}, {k713: 21, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: true, cust: {age: 2, tier: "Gold", active: false}, s: "gold", a: 24, vip: false, nums: [1000000000000000000000, 11, 3]}, {k713: 24, k718: false, k719: "high", k720: false, o: {p: [{m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: false, code: "b", cust: {age: 100, tier: "zz", active: true}, a: 99, vip: false, nums: [0]}, {k713: 99, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: false}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + [{flag: true, code: "a", cust: {age: 18, tier: "a", active: true}, a: 0.5, vip: false, nums: []}, {k713: 0.5, k718: true, k719: "high", k720: false, o: {p: [{m: {k716: true}}, {m: {k716: false}}]}, res: [{k712: true, k713: "low"}, {k712: true, k713: "high"}]}], + ], +} + +{ + name: "ga072: 6 nodes, expr, expr, expr, expr, expr, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k721: "(tier ?? 'none')", + k722: "tier ?? $.k721", + }}, + {expression: "e2", inputField: "cust", outputPath: "out", fields: { + k723: "tier == null", + k724: "active ?? active", + k725: "lower(upper('x'))", + k726: "trim(string((age ?? -1)) + ':' + upper('x'))", + }}, + {expression: "e3", fields: { + k727: "((0 ?? cust.age ?? 0)) / 10", + }}, + {expression: "e4", fields: { + k728: "(k721 ?? '') != 'x'", + k729: "string(true) != ''", + k731: "vip ?? tier", + }}, + {expression: "e5", fields: { + k732: "(k727 ?? -1)", + k733: "true", + "res.k734": "((k727)) % 2", + k735: "(k727 ?? -1)", + }}, + {expression: "e6", fields: { + k736: "((k727 ?? -1)) / 0.5 + ((true) and (false) ? ((k727 ?? 0)) : (k727 ?? 0))", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> e3", + "e1 -> e4", + "e3 -> e5", + "e3 -> e6", + "e2 -> output", + "e4 -> output", + "e5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{cust: {age: -0.1, tier: "gold", active: "no"}, vip: true, tier: "x"}, {k728: false, k729: true, k731: true, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: "no", k725: "x", k726: "-0.1:X"}, res: {k734: 0}}], + [{cust: {age: -25, tier: "zz", active: 0}, vip: true, tier: "zz", extra: [1, 2]}, {k728: true, k729: true, k731: true, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: 0, k725: "x", k726: "-25:X"}, res: {k734: 0}}], + [{cust: {age: 21, tier: "silver", active: true}, vip: true, tier: "b"}, {k728: true, k729: true, k731: true, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: true, k725: "x", k726: "21:X"}, res: {k734: 0}}], + [{cust: {age: "5", tier: "gold", active: true}, vip: true, tier: "Gold"}, {k728: true, k729: true, k731: true, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: true, k725: "x", k726: "5:X"}, res: {k734: 0}}], + [{cust: {age: -0.1, tier: "x", active: false}, vip: false, tier: "x"}, {k728: false, k729: true, k731: false, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: false, k725: "x", k726: "-0.1:X"}, res: {k734: 0}}], + [{cust: {age: 0, tier: "bronze", active: false}, vip: false, tier: "x"}, {k728: false, k729: true, k731: false, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: false, k725: "x", k726: "0:X"}, res: {k734: 0}}], + [{cust: {age: 19.99, tier: "Gold", active: true}, vip: "no", tier: true}, {k728: true, k729: true, k731: "no", k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: true, k725: "x", k726: "19.99:X"}, res: {k734: 0}}], + [{cust: {age: 18, tier: "b", active: false}, vip: false, tier: {t: "x"}}, {k728: true, k729: true, k731: false, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: false, k725: "x", k726: "18:X"}, res: {k734: 0}}], + [{cust: null, vip: false, tier: "b"}, {k728: true, k729: true, k731: false, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: true, k724: null, k725: "x", k726: "-1:X"}, res: {k734: 0}}], + [{cust: {age: 10, tier: "silver", active: false}, vip: null, tier: "b"}, {k728: true, k729: true, k731: "b", k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: false, k725: "x", k726: "10:X"}, res: {k734: 0}}], + [{cust: {age: 100, tier: "gold", active: true}, vip: "true", tier: "x"}, {k728: false, k729: true, k731: "true", k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: true, k725: "x", k726: "100:X"}, res: {k734: 0}}], + [{cust: {age: 21, tier: "a", active: false}, vip: true, tier: "silver"}, {k728: true, k729: true, k731: true, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: false, k725: "x", k726: "21:X"}, res: {k734: 0}}], + [{cust: {age: null, tier: "x", active: false}, tier: 5}, {k728: true, k729: true, k731: 5, k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: false, k725: "x", k726: "-1:X"}, res: {k734: 0}}], + [{cust: {age: 11, tier: "gold", active: false}, vip: null, tier: "x"}, {k728: false, k729: true, k731: "x", k732: 0, k733: true, k735: 0, k736: 0, out: {k723: false, k724: false, k725: "x", k726: "11:X"}, res: {k734: 0}}], + ], +} + +{ + name: "ga073: 3 nodes, switch, expr, table*", + graph: { + nodes: [ + {switch: "s1", when: ["(true)", "true"]}, + {expression: "e2", outputPath: "out", fields: { + k737: "price ?? cust.age", + }}, + {table: "t3", hit: "collect", inputs: ["(cust.tier ?? 'none')", "(price ?? 0) % 7", "price"], outputs: ["res.k739", "k740"], rules: [ + ["startsWith($, '')", "[10..60]", "not(0)", "'low'", "1"], + ["startsWith($, 'g')", "<= 1", "100", "'high'", "1"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> e2", + "s1:0 -> t3", + "input -> t3", + "s1:1 -> output", + "e2 -> output", + "t3 -> output", + ], + }, + cases: [ + [{cust: {age: 19.99, tier: "a", active: true}, b: -25, price: 50}, {out: {k737: 50}}], + [{cust: {age: 50, tier: "Gold", active: false}, b: -1, price: 0}, {out: {k737: 0}}], + [{b: 0.5, price: 11, extra: 1}, {out: {k737: 11}}], + [{cust: {age: 1000000000000000000000, tier: "silver", active: false}, b: null, price: 7}, {out: {k737: 7}}], + [{b: 10, price: 21}, {out: {k737: 21}}], + [{cust: {age: -25, tier: "zz", active: true}, b: 21, price: 1000000000000000000000}, {out: {k737: 1000000000000000000000}}], + [{cust: {age: 7, active: true}, b: 7, price: 1}, {out: {k737: 1}}], + [{cust: {age: 3, tier: "bronze", active: true}, b: 19.99, price: 7}, {out: {k737: 7}}], + [{cust: {age: 18, tier: "silver", active: false}, b: 0, price: 1000}, {out: {k737: 1000}}], + [{cust: null, b: 101, price: 100}, {out: {k737: 100}}], + [{cust: {age: 0, tier: "gold", active: true}, b: null, price: 101}, {out: {k737: 101}}], + [{cust: {age: 11, tier: "Gold", active: true}, b: 11, price: 0, extra: 1}, {out: {k737: 0}}], + [{cust: {age: null, tier: null, active: false}, b: 18, price: 18}, {out: {k737: 18}}], + [{cust: {age: 101, tier: "zz", active: true}, b: 18, price: 11}, {out: {k737: 11}}], + [{cust: {age: 0.1, tier: "bronze", active: true}, b: 1000}, {out: {k737: 0.1}}], + [{cust: {age: 19.99, tier: "a", active: false}, b: 50, price: 10, extra: "e"}, {out: {k737: 10}}], + [{cust: {age: 11, tier: "Gold", active: true}, b: null, price: 1000000000000000000000}, {out: {k737: 1000000000000000000000}}], + [{cust: {age: 7, tier: "zz", active: false}, b: 21}, {out: {k737: 7}}], + [{cust: {age: -1, tier: "gold", active: null}, b: 3, price: -1}, {out: {k737: -1}}], + ], +} + +{ + name: "ga074: 7 nodes, table, table*, table, switch, table, table, table*", + graph: { + nodes: [ + {table: "t1", inputs: ["price", "n", "lower(string(true))"], outputs: ["k741"], rules: [ + ["[-1..49]", "> 0", "", "true"], + ["[1..6]", "<= 9", "", "(not ((s ?? 'none') == 'gold')) or ((n ?? 0) < (score ?? 1))"], + ["18, 23", "$ > 100 and $ < 105", "", "false"], + ["!= 1", "50", "$ != 'gold'", "false"], + ["not(100)", "!= 10", "null", "false"], + ["", "", "", "flag != null"], + ]}, + {table: "t2", hit: "collect", inputs: ["(max([0.5, 0]))", "2.25"], outputs: ["k742[]"], outputPath: "out", rules: [ + ["$ > 21 and $ < 22", "!= 21", "((-4)) / 4 * -4"], + ["!= 100", "!= 50", "0"], + ["(-1..9)", "[50..55]", "len('none')"], + ["", "", "len('' + '-' + '') % 7"], + ]}, + {table: "t3", inputs: ["k741", "(3) + (1) / 4"], outputs: ["k743", "k744"], passThrough: true, rules: [ + ["true", "not(18)", "false", "true"], + ["$ == true", "$ > 1 and $ < 6", "a != null", "(a == null) and (len('A-1') < abs(0.5))"], + ["", "", "false", "-(-(0)) != (0.5 + 3)"], + ]}, + {switch: "s4", when: ["1 >= 3"]}, + {table: "t5", inputs: ["3 + 1 % 2", "(-(1))", null], outputs: ["k745", "k746"], passThrough: true, outputPath: "lines", rules: [ + ["not(5)", "null", "", "10 + 10 * 0 != 10", "true"], + ["[-1..9]", ">= 5", "", "true", "true"], + ["not(5)", "<= 23", "$ != null", "true", "true"], + ["", "", "", "true", "true"], + ]}, + {table: "t6", inputs: ["((false ? 3 : 0.5))", "100"], outputs: ["k747"], passThrough: true, rules: [ + ["", "not(21)", "'gold'"], + ["null", "null", "''"], + ["not(5)", "not(5)", "'low'"], + ["", "", "'high'"], + ["", "", "`n=${3}-${''}`"], + ]}, + {table: "t7", hit: "collect", inputs: ["string(min([10, 0]))", "`${3}-${'A-1'}`"], outputs: ["k748[]", "k749"], passThrough: true, outputPath: "lines", rules: [ + ["not('x')", "", "100", "a != null"], + ["startsWith($, '')", "", "10", "false"], + ["'x'", "null", "2", "false"], + ["'gold', 'b'", "'x'", "0.25", "true"], + ["$ != ''", "null", "0 * 100", "true"], + ["'gold', 'bronze'", "startsWith($, 'x')", "1", "(2 % 3 < (true ? 2 : 3))"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> t2", + "t1 -> t3", + "t2 -> s4", + "s4:0 -> t5", + "t1 -> t5", + "s4:0 -> t6", + "t5 -> t7", + "t2 -> output", + "t3 -> output", + "t6 -> output", + "t7 -> output", + ], + }, + cases: [ + [{price: 0.5, n: 3, flag: true, s: "gold ", items: [{price: 18, qty: [1], tag: "bronze"}, {price: 2, qty: -0.1, tag: null}], nums: [-25, 11]}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 7, n: 50, flag: true, s: "gold ", items: [], nums: [100, 50, 101, 21, 1], score: 18}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 19.99, n: 1000000000000000000000, flag: true, s: null, items: [], nums: [3], score: 1}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: -0.1, n: 2, flag: null, s: "x", items: [{price: 5, qty: 0, tag: "gold"}, {price: 2.5, qty: 11, tag: null}], nums: [3]}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 23, n: 10, flag: true, s: "silver", items: [{price: true, qty: 0}, {price: -1, qty: 0.5, tag: "gold"}, {price: 19.99, qty: 5, tag: "zz"}], nums: null}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 103, n: -1, flag: true, s: "x", items: [{price: -1, qty: -1, tag: "x"}, {price: -0.1, qty: -1, tag: "silver"}, {price: -1, qty: 0, tag: "b"}], nums: [], score: 44}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 99, n: 19.99, flag: false, s: "a", items: [{price: "5", qty: true, tag: ""}], nums: [11, 10], score: [1]}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 0.5, n: 99, s: "gold", nums: "1,2", score: true}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: -0.1, n: 19.99, flag: true, s: "a", items: [{price: [1], qty: [1], tag: "zz"}, {price: 3, qty: 0.1, tag: "x"}], nums: [3, -25]}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 2, n: 21, flag: true, s: "x", items: [{qty: null, tag: "silver"}], nums: [{x: 1}], score: 50}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 7, n: 1, s: "gold", items: [{price: true, qty: 99, tag: "gold"}, {price: null, qty: 11, tag: "x"}], nums: [0.5, -25], score: 1000000000000000000000}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: -0.1, n: 5, flag: true, s: "a", items: [], nums: [5], score: null, extra: [1, 2]}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 1000, n: null, s: ["gold"], items: [], nums: [11], score: 3}, {k741: false, k743: false, k744: true, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{n: -25, flag: true, s: true, items: [{price: null, qty: 18, tag: "b"}, {price: 21, qty: 99, tag: {t: "x"}}], nums: [11, 7], score: 2}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 11, n: 0.1, flag: true, s: ["gold"], nums: [19.99, 0, 1000], score: 10}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: true, n: true, flag: false, s: "silver", items: [], nums: null, score: 0}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 21, flag: false, s: "gold ", items: [{price: 99, qty: 21, tag: ["gold"]}, {price: 7, qty: 11, tag: null}, {price: 18, tag: "gold"}], nums: [-1, 92, 0.1, 0.1, 0], score: 101}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 100, n: 0, flag: null, s: "zz", items: [], nums: [2, 5], score: "5", extra: [1, 2]}, {k741: false, k743: false, k744: true, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 1000000000000000000000, s: "silver", items: [], nums: [50, 18], score: 0.5, extra: 1}, {k741: false, k743: false, k744: true, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 11, n: 5, flag: false, s: "gold", items: [{price: 19.99, qty: 10, tag: "b"}, {price: 10, qty: 50}, {price: 50, qty: 10, tag: null}, {price: -1, qty: 21}], nums: [1000, 2.5, 0.1, 19.99, 18], score: true}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: null, n: 19.99, s: "bronze", items: [{price: null, qty: 0.1, tag: true}, {qty: 2, tag: "b"}, {price: 50, qty: 100, tag: "bronze"}], nums: [], score: 19.99}, {k741: false, k743: false, k744: true, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 99, n: 35, flag: true, s: "a", items: [], nums: [5], score: 21}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: null, n: 0.1, flag: false, s: "b", items: [{price: 21, qty: 5, tag: "silver"}], nums: [10, 1, -0.1], score: 1}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 10, n: 19.99, flag: true, items: [], nums: [50, 3, 101, 7, 2.5], score: 1000}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + [{price: 99, flag: 0, s: "x", items: [{price: 1000, qty: 18, tag: ""}, {qty: null, tag: "x"}], nums: [5], score: 21}, {k741: true, k743: false, k744: false, lines: [{k748: 10, k749: false}], out: [{k742: 0}, {k742: 1}]}], + ], +} + +{ + name: "ga075: 7 nodes, loop expr, switch, expr, expr, table, switch, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k750: "max([price, price])", + "m.k751": "max([(price ?? qty ?? 0), (false ? 0.5 : (qty ?? -1))]) * 2.25 * ($.k750 ?? -1) * -4", + k752: "contains((tag ?? '?') + ':' + 'none' + ':' + string((qty ?? 1)), 'g')", + }}, + {switch: "s2", when: ["true", "(false)", "not ((n ?? score ?? 0) == (n ?? 0) - 1)", ""]}, + {expression: "e3", fields: { + k753: "'gold'", + k754: "not (not (true))", + k755: "startsWith(`${(n ?? 1)}-${''}`, '')", + }}, + {expression: "e4", fields: { + k756: "k755", + k752: "k755 ?? s", + }}, + {table: "t5", inputs: ["(k753 ?? '')", null], outputs: ["k758"], outputPath: "res", rules: [ + ["", "", "'low'"], + ["''", "null", "upper(string((2.25)))"], + ["'gold', 'gold'", "'gold'", "'high'"], + ["'x'", "true", "'low'"], + ["", "", "'high'"], + ]}, + {switch: "s6", when: ["(code == null) or (code != null)", "score != null"]}, + {expression: "e7", outputPath: "o.p", fields: { + k759: "k756 ?? k756", + k760: "'x'", + k761: "k756 ?? k756", + "res.k762": "(abs(10)) + 1 + -4 * 3", + }}, + ], + edges: [ + "input -> e1", + "input -> s2", + "input -> e3", + "s2:2 -> e4", + "e3 -> e4", + "e3 -> t5", + "s2:3 -> s6", + "input -> s6", + "e4 -> e7", + "e1 -> output", + "s2:0 -> output", + "s2:1 -> output", + "t5 -> output", + "s6:0 -> output", + "s6:1 -> output", + "e7 -> output", + ], + }, + cases: [ + [{score: null, n: 1000000000000000000000, b: 2, code: "Gold", s: "", items: [{price: null, qty: 99, tag: "gold"}]}, "!error"], + [{score: 21, nums: null, n: null, b: 101, code: "zz", s: "Gold", items: [{price: 7, qty: 18, tag: "zz"}, {price: 50, qty: 1, tag: "a"}]}, {b: 101, code: "zz", items: [{price: 7, qty: 18, tag: "zz"}, {price: 50, qty: 1, tag: "a"}], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 7, k752: false, m: {k751: -1134.00}}, {k750: 50, k752: false, m: {k751: -22500.00}}], s: "Gold", score: 21}], + [{score: 0.5, nums: [], n: null, b: 0, code: "gold ", s: "x", items: [{price: 19.99, qty: 0, tag: "Gold"}, {price: 2.5, qty: null, tag: "Gold"}]}, {b: 0, code: "gold ", items: [{price: 19.99, qty: 0, tag: "Gold"}, {price: 2.5, qty: null, tag: "Gold"}], nums: [], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 19.99, k752: false, m: {k751: -3596.400900}}, {k750: 2.5, k752: false, m: {k751: -56.2500}}], s: "x", score: 0.5}], + [{score: 100, nums: [], n: 99, b: 10, code: "Gold", s: "Gold", items: [{qty: 101, tag: ""}, {price: 10, qty: 5, tag: ""}]}, "!error"], + [{score: 3, nums: [-1, 5, 0.5, 50, 0.1], n: 0.5, b: 10, code: null, s: null, items: [{price: 0, qty: 18, tag: "Gold"}, {price: 99, qty: 26, tag: "b"}]}, {b: 10, items: [{price: 0, qty: 18, tag: "Gold"}, {price: 99, qty: 26, tag: "b"}], n: 0.5, nums: [-1, 5, 0.5, 50, 0.1], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 0, k752: false, m: {k751: 0}}, {k750: 99, k752: false, m: {k751: -88209.00}}], score: 3}], + [{score: 1000000000000000000000, nums: [101, 2.5, 101, 101, 101], n: 5, code: "x", s: null, items: [{price: 101, qty: -1, tag: "zz"}, {qty: null, tag: "x"}]}, "!error"], + [{score: 1, nums: [19.99, 0, 1000, 2.5, 50], n: 11, b: "5", code: "Gold", s: "zz", items: [{price: true, qty: 0.1, tag: "bronze"}]}, "!error"], + [{score: -25, nums: [-25, -1], n: 0.1, b: 3, code: "a", s: "silver", items: [{price: 100, qty: -25, tag: "Gold"}, {price: 50, qty: 5, tag: "zz"}, {price: -1, qty: 101, tag: "x"}, {price: 2, qty: 19.99}], extra: [1, 2]}, {b: 3, code: "a", extra: [1, 2], items: [{price: 100, qty: -25, tag: "Gold"}, {price: 50, qty: 5, tag: "zz"}, {price: -1, qty: 101, tag: "x"}, {price: 2, qty: 19.99}], n: 0.1, nums: [-25, -1], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 100, k752: false, m: {k751: -90000.00}}, {k750: 50, k752: false, m: {k751: -22500.00}}, {k750: -1, k752: false, m: {k751: 909.00}}, {k750: 2, k752: false, m: {k751: -359.8200}}], s: "silver", score: -25}], + [{score: null, nums: [5, 1000], n: "abc", b: 10, code: "x", s: "gold ", items: [{price: 5, qty: 3}]}, {b: 10, code: "x", items: [{price: 5, qty: 3}], n: "abc", nums: [5, 1000], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 5, k752: false, m: {k751: -225.00}}], s: "gold "}], + [{score: 21, nums: null, n: 11, b: 0.1, code: "x", items: [{price: -25, qty: 0, tag: "gold"}, {price: 21, qty: null, tag: null}, {price: 100, qty: -25, tag: "x"}]}, {b: 0.1, code: "x", items: [{price: -25, qty: 0, tag: "gold"}, {price: 21, qty: null, tag: null}, {price: 100, qty: -25, tag: "x"}], n: 11, o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: -25, k752: true, m: {k751: 0}}, {k750: 21, k752: false, m: {k751: -3969.00}}, {k750: 100, k752: false, m: {k751: -90000.00}}], score: 21}], + [{score: -0.1, nums: [2], n: -0.1, b: -1, code: "gold ", s: null, items: [{price: 1000000000000000000000, qty: 0.5, tag: ""}, {qty: true, tag: "Gold"}, {price: 21, qty: -1, tag: "b"}]}, "!error"], + [{score: 19.99, nums: null, n: "5", b: 0.5, code: null, s: "bronze", items: [{price: -25, qty: 11, tag: "zz"}]}, {b: 0.5, items: [{price: -25, qty: 11, tag: "zz"}], n: "5", o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: -25, k752: false, m: {k751: 2475.00}}], s: "bronze", score: 19.99}], + [{score: 1000000000000000000000, nums: [19.99, 0, 1000], n: 99, b: 99, code: "gold ", s: "gold ", items: [{price: 1, qty: 5, tag: "bronze"}]}, {b: 99, code: "gold ", items: [{price: 1, qty: 5, tag: "bronze"}], n: 99, nums: [19.99, 0, 1000], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 1, k752: false, m: {k751: -45.00}}], s: "gold ", score: 1000000000000000000000}], + [{score: 100, n: 10, code: "gold ", s: null, items: [{price: 3, tag: null}], extra: "e"}, {code: "gold ", extra: "e", items: [{price: 3, tag: null}], n: 10, o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 3, k752: false, m: {k751: -81.00}}], score: 100}], + [{score: 2.5, nums: [7, 10], n: null, b: 1, code: null, s: "zz", items: [{price: -25, qty: 2, tag: "silver"}, {price: null, qty: 10, tag: ""}]}, "!error"], + [{nums: [21, 101], n: null, b: 0, code: "a", s: "gold", items: [{price: null, qty: -25, tag: "gold"}]}, "!error"], + [{score: null, nums: [0.1, 11, 19.99], n: 19.99, b: 0.1, code: "x", s: ["gold"], items: [{price: 100, qty: -0.1, tag: "a"}]}, {b: 0.1, code: "x", items: [{price: 100, qty: -0.1, tag: "a"}], n: 19.99, nums: [0.1, 11, 19.99], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 100, k752: false, m: {k751: -90000.00}}], s: ["gold"]}], + [{score: 100, nums: [7, 99, 10, -4, 0.5], n: 18, b: 1000000000000000000000, code: {t: "x"}, s: 5, items: [{price: 100, qty: null, tag: "bronze"}]}, {b: 1000000000000000000000, code: {t: "x"}, items: [{price: 100, qty: null, tag: "bronze"}], n: 18, nums: [7, 99, 10, -4, 0.5], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 100, k752: false, m: {k751: -90000.00}}], s: 5, score: 100}], + [{score: 1, nums: [19.99, 1000, 99], n: 3, b: null, code: null, s: "", items: []}, {items: [], n: 3, nums: [19.99, 1000, 99], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [], s: "", score: 1}], + [{score: 1, nums: [{x: 1}], n: 1, b: 19.99, code: "a", s: "silver", items: []}, {b: 19.99, code: "a", items: [], n: 1, nums: [{x: 1}], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [], s: "silver", score: 1}], + [{score: null, nums: [], b: 7, code: "b", s: "b", items: [{price: 0.5, qty: 3, tag: "Gold"}, {price: 101, qty: 2, tag: "x"}]}, {b: 7, code: "b", items: [{price: 0.5, qty: 3, tag: "Gold"}, {price: 101, qty: 2, tag: "x"}], nums: [], o: {p: {k759: true, k760: "x", k761: true, res: {k762: -1}}}, res: [{k750: 0.5, k752: false, m: {k751: -13.500}}, {k750: 101, k752: false, m: {k751: -91809.00}}], s: "b"}], + ], +} + +{ + name: "ga076: 5 nodes, expr, table, table, table*, table", + graph: { + nodes: [ + {expression: "e1", outputPath: "lines", fields: { + k763: "b ?? tier", + k764: "flag ?? b", + "m.k765": "flag ?? tier", + k766: "not (not (not (false)))", + }}, + {table: "t2", inputs: ["(-(3))"], outputs: ["g.k767", "m.k765"], rules: [ + ["[18..28]", "100", "10"], + ["<= 55", "-5", "0.25"], + ["", "(round(2.25) > 10 + 100 ? (2.25 + 1) / 0.5 : floor(2 - 10))", "0.25"], + ]}, + {table: "t3", inputs: ["b", "b"], outputs: ["k769", "k764"], rules: [ + ["null", "not(10)", "false", "'mid'"], + ["0, 1", "null", "true", "'high'"], + ["[100..101)", "", "true", "'A-1'"], + ["!= 0", "!= 5", "true", "((b ?? -1) - 3 <= (b ?? b ?? 0) ? tier : (tier ?? ''))"], + ]}, + {table: "t4", hit: "collect", inputs: ["m.k765", "-((b ?? -1))", "g.k767", null], outputs: ["k771"], outputPath: "res", rules: [ + ["[10..15)", "[18..23)", "(5..10)", "", "true"], + ["18, 68", "not(10)", "10, 11", "null", "false"], + ["< 100", "[50..100]", "50, 100", "'gold'", "(vip ?? false)"], + [">= 1", "not(21)", ">= 18", "5", "(flag ?? false)"], + ["", "", "", "", "true"], + ]}, + {table: "t5", inputs: ["2 % 3", "(k764 ?? '?') + ' ' + k764 + '' + 'none'", "(2) + (-4) / 0.5"], outputs: ["k772"], passThrough: true, outputPath: "out", rules: [ + ["[0..1)", "startsWith($, 's')", "> 100", "'mid'"], + ["> 100", "", "$ > 10 and $ < 20", "'mid'"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "input -> t3", + "input -> t4", + "t2 -> t4", + "t3 -> t5", + "t4 -> output", + "t5 -> output", + ], + }, + cases: [ + [{b: 1000, vip: false, items: [{price: -25, qty: 100, tag: ["gold"]}, {price: 5, qty: 50, tag: "a"}], cust: {age: 100, tier: "silver", active: true}, tier: "x", flag: null}, {k764: "x", k769: true, res: [{k771: true}]}], + [{b: 0, items: [{price: null, qty: 0.5, tag: ""}], tier: "x", flag: false}, {res: [{k771: true}]}], + [{b: -1, items: [], tier: "", flag: false}, {k764: "", k769: true, res: [{k771: true}]}], + [{b: 3, vip: true, items: [], cust: {age: 3, tier: "a", active: null}, flag: true, extra: 1}, {k769: true, res: [{k771: true}]}], + [{b: 98, vip: false, items: 3, cust: {age: 5, tier: "zz", active: false}, tier: "zz", flag: true, extra: "e"}, {k764: "zz", k769: true, res: [{k771: true}]}], + [{b: -0.1, vip: false, items: "items", cust: {age: null, tier: "b", active: false}, tier: ["gold"], flag: false}, {k764: ["gold"], k769: true, res: [{k771: true}]}], + [{b: null, vip: true, items: [{price: 3, qty: 21, tag: "x"}, {price: {v: 1}, qty: 2.5, tag: "gold "}], cust: {age: 0.1, tier: "", active: "true"}, tier: true, flag: true}, {k764: true, k769: true, res: [{k771: true}]}], + [{b: 3, vip: "no", items: [{price: 18, qty: 0, tag: "zz"}], cust: {age: 10, tier: "", active: false}, tier: 5, flag: false}, {k764: 5, k769: true, res: [{k771: true}]}], + [{b: 21, vip: false, items: [{price: 19.99, qty: -1, tag: "gold"}, {price: 2, qty: 0.5, tag: "bronze"}, {price: 50, qty: -1, tag: "a"}], cust: {tier: "b", active: true}, tier: "b", flag: 0, extra: [1, 2]}, {k764: "b", k769: true, res: [{k771: true}]}], + [{b: "abc", vip: false, items: [{price: -25, qty: 1000, tag: "a"}, {price: 0.5, qty: 19.99}], cust: {age: 0.5, tier: "zz", active: true}, tier: "gold", flag: false}, {res: [{k771: true}]}], + [{b: 18, vip: true, items: [{price: 50, qty: 100, tag: true}, {price: {v: 1}, qty: 2.5, tag: "gold"}, {price: -1, qty: 21, tag: null}], cust: {age: -25, tier: "gold ", active: false}, tier: "silver", flag: true}, {k764: "silver", k769: true, res: [{k771: true}]}], + [{b: 1, vip: false, items: [{price: 5, qty: 50, tag: "x"}, {qty: -25, tag: "bronze"}], cust: {age: -0.1, tier: "silver", active: true}, tier: true, flag: true}, {k764: true, k769: true, res: [{k771: true}]}], + [{b: 10, vip: true, items: [{price: 62, qty: 2.5, tag: "gold"}, {qty: 7, tag: "bronze"}, {price: 1000000000000000000000, qty: -0.1, tag: "x"}], cust: {age: 19.99, tier: "zz", active: true}, tier: "bronze", flag: false}, {k764: "bronze", k769: true, res: [{k771: true}]}], + [{b: 10, vip: true, items: [{price: 5, tag: "Gold"}, {price: 2, qty: 19.99, tag: "Gold"}], cust: {age: 0.1, tier: "b", active: null}, tier: "Gold", flag: true}, {k764: "Gold", k769: true, res: [{k771: true}]}], + [{vip: false, items: "items", cust: {age: 19.99, tier: "Gold", active: false}, tier: "x", flag: null, extra: {deep: {x: 1}}}, {k764: "x", k769: true, res: [{k771: true}]}], + [{b: -25, vip: true, items: [{price: 1, qty: 99, tag: {t: "x"}}], cust: {age: 1000, tier: null, active: true}, tier: "", flag: "true"}, {k764: "", k769: true, res: [{k771: true}]}], + [{b: -0.1, vip: "no", items: [{price: 101, qty: 7, tag: ""}, {qty: 50, tag: "x"}, {price: true, qty: 0.5}, {price: 0.5, qty: 0.1, tag: "a"}], tier: "bronze", flag: true}, {k764: "bronze", k769: true, res: [{k771: true}]}], + [{b: 21, vip: null, items: [{price: 0.5, qty: 2.5, tag: "gold"}, {price: 1000, qty: 1000, tag: "silver"}], cust: {age: 118, tier: "x", active: true}, tier: "silver", flag: false}, {k764: "silver", k769: true, res: [{k771: true}]}], + ], +} + +{ + name: "ga077: 6 nodes, expr, switch*, expr, expr, table, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "cust", fields: { + k773: "`${(age ?? -1)}-${(tier ?? 'none')}`", + k774: "upper(trim('none'))", + k775: "string(((active ?? false) ? 10 : (age ?? 0)) in [-5..5])", + k776: "(((age ?? -1)) / 2 < (age)) and (active == null)", + }}, + {switch: "s2", hit: "collect", when: ["(((true) and ((k776 ?? false))) or ('x' != '')) or (-4 != (100))", "false", "startsWith((k775 ?? ''), 'g')", ""]}, + {expression: "e3", fields: { + k777: "string(2 * 100 == 2 + -4)", + k778: "k773 ?? $.k777", + k779: "100", + }}, + {expression: "e4", passThrough: true, fields: { + k773: "1", + k781: "(3) != 10", + }}, + {table: "t5", inputField: "cust", inputs: ["active", "age"], outputs: ["k782", "k783"], outputPath: "out", rules: [ + ["", "", "'high'", "(age ?? 1) % 3"], + ["false", "[-1..0]", "'gold'", "0.5 + (age == null ? (age ?? -1) : (age ?? 0))"], + ["true", "10", "lower((tier ?? '')) + '-' + 'gold'", "0.25"], + ["$ == true", "18, 68", "'' + ':' + string(0.5)", "1"], + ["null", "100", "`v${(age ?? 0)}-${(tier ?? '')}`", "(age ?? 1) + ((age ?? 0) + (age ?? 0))"], + ["true", "!= 100", "'gold'", "1"], + ]}, + {expression: "e6", fields: { + k784: "k774 ?? k776", + k785: "k775 ?? k773", + }}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "s2:3 -> e3", + "s2:3 -> e4", + "input -> t5", + "s2:0 -> e6", + "e1 -> output", + "s2:2 -> output", + "e3 -> output", + "e4 -> output", + "t5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{nums: [0.1, 101], price: -25, cust: {age: 7, tier: "b", active: true}, score: {v: 1}, extra: {deep: {x: 1}}}, {k773: "7-b", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "7-b", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 1}}], + [{nums: [2.5], price: "5", cust: {age: 101, tier: "a", active: true}, score: 5}, {k773: "101-a", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "101-a", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 2}}], + [{nums: [100, 21], price: 99, score: 11, extra: "e"}, "!error"], + [{nums: [], price: 2.5, cust: {age: 0, tier: "zz", active: true}, score: 21}, {k773: "0-zz", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "0-zz", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 0}}], + [{price: 21, cust: {age: 11, tier: "Gold", active: false}, score: 100}, {k773: "11-Gold", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "11-Gold", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 2}}], + [{nums: [5, 0], price: 1000, cust: null, score: 35}, "!error"], + [{nums: 7, price: 100, cust: {age: 2, tier: "zz", active: true}, score: 7}, {k773: "2-zz", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "2-zz", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 2}}], + [{nums: [100, 1000, 96, 1000, 1], price: null, score: "5"}, "!error"], + [{nums: [2, 11], price: null, cust: {age: -1, tier: "b", active: true}, score: 21, extra: "e"}, {k773: "-1-b", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "-1-b", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: -1}}], + [{nums: null, price: 0.1, cust: {age: 1000000000000000000000, active: true}, score: 59}, {k773: "1000000000000000000000-none", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "1000000000000000000000-none", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 1}}], + [{nums: "1,2", price: 7, cust: [{age: 3}], score: -3}, "!error"], + [{nums: [0.1, 100], price: 1, cust: null, score: -0.1}, "!error"], + [{nums: [], price: 0, cust: {age: 10, tier: "gold ", active: 0}, score: 18}, "!error"], + [{nums: [7, 101, 101, -25, 1000], price: 101, cust: null, score: 1000000000000000000000}, "!error"], + [{nums: null, price: 1000000000000000000000, cust: {age: 10, tier: "a", active: true}, score: null}, {k773: "10-a", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "10-a", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 1}}], + [{nums: [19.99, 1000000000000000000000, 99, 99, 21], price: 2, cust: {age: [1], tier: "gold ", active: false}, score: -25}, "!error"], + [{nums: null, price: 1, cust: {age: 50, tier: "a", active: false}, score: 5}, {k773: "50-a", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "50-a", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 2}}], + [{nums: [5, 19.99], price: 3, cust: null, score: 19.99}, "!error"], + [{nums: [1, 100, 2.5, 7, -12], price: 100, cust: [{age: 3}], score: 99}, "!error"], + [{nums: [11], price: 50, cust: {age: 1000, tier: "zz", active: false}, score: 99}, {k773: "1000-zz", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "1000-zz", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 1}}], + [{nums: "1,2", price: 2.5, cust: {age: 1000, active: false}, score: null, extra: 1}, {k773: "1000-none", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "1000-none", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 1}}], + [{nums: [], price: null, cust: "cust", score: 11}, "!error"], + [{nums: null, price: -1, cust: {age: 7, tier: "gold ", active: false}, score: "5"}, {k773: "7-gold ", k774: "NONE", k775: "false", k776: false, k777: "false", k778: "7-gold ", k779: 100, k781: true, k784: "NONE", k785: "false", out: {k782: "high", k783: 1}}], + [{nums: [2, -25, 18, 0.1, 50], price: 100, cust: null, score: -25}, "!error"], + [{nums: [7, 0, 3], price: 11, cust: null, score: 11}, "!error"], + [{cust: {age: null, tier: "silver", active: true}, score: 0.5}, "!error"], + [{price: 11, cust: "cust", score: 100}, "!error"], + [{nums: [50, 7, 18], price: [1], cust: {age: 3, tier: "gold", active: false}, score: 19.99}, {k773: "3-gold", k774: "NONE", k775: "true", k776: false, k777: "false", k778: "3-gold", k779: 100, k781: true, k784: "NONE", k785: "true", out: {k782: "high", k783: 0}}], + [{nums: [101, -25, 99, 1000, 0.5], price: 5, cust: {age: "5", tier: "gold", active: false}, score: 101}, "!error"], + [{nums: [-0.1, 99, 34], price: null, cust: null, score: 10}, "!error"], + ], +} + +{ + name: "ga078: 8 nodes, expr, table, table*, switch, expr, expr, expr, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "cust", fields: { + k786: "((endsWith((tier ?? '?'), '')))", + }}, + {table: "t2", inputs: ["trim('' + ':' + 'gold')", "k786", null], outputs: ["k787", "k788"], rules: [ + ["'silver', 'bronze'", "$ == true", "'gold'", "`v${1}-${'A-1'}`", "''"], + ["", "true", "", "'low'", "'x'"], + ["", "", "5", "''", "lower(((k786 ?? false) ? '' : '')) + ' ' + `${1}-${'A-1'}`"], + ]}, + {table: "t3", hit: "collect", inputs: ["score", "code"], outputs: ["k789", "k790"], outputPath: "res", rules: [ + ["<= 11", "null", "'mid'", "false"], + ["[1..6)", "'a'", "'none'", "true"], + ["", "''", "'mid'", "false"], + ["< 5", "", "'gold'", "true"], + ["<= 55", "", "'gold'", "false"], + ["", "", "'mid'", "false"], + ]}, + {switch: "s4", when: ["len((k788 ?? '')) + 100 * 2.25 < 100 * 3 % 3", "(((false) and (true)))", "0 - 1 in [-5..5]"]}, + {expression: "e5", fields: { + k791: "0", + k792: "string(10 + 3) + ' ' + ''", + k793: "'none'", + k794: "len(upper('none') + '' + (true ? 'x' : 'gold'))", + }}, + {expression: "e6", passThrough: true, outputPath: "res", fields: { + k795: "false", + k796: "3 in [0..10]", + k797: "0.5 + -4 + 2 * 2.25", + k798: "$.k795", + }}, + {expression: "e7", outputPath: "out", fields: { + k799: "string((0) / 0.5 in [-5..5])", + }}, + {expression: "e8", fields: { + k800: "string((3))", + k801: "string(1 > 0.5) + ':' + (contains((k788 ?? ''), 'a') ? ($nodes.t2.k788 ?? '') : string(false))", + }}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "input -> t3", + "t3 -> s4", + "t2 -> s4", + "t3 -> e5", + "t3 -> e6", + "s4:2 -> e7", + "s4:2 -> e8", + "s4:0 -> output", + "s4:1 -> output", + "e5 -> output", + "e6 -> output", + "e7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{score: 99, cust: {age: 99, tier: "x", active: false}, b: -10, code: ""}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 11, b: 3}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 1, cust: {age: 18, tier: "b", active: false}, b: 0, code: "gold "}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 0, cust: {age: 18, tier: "b", active: false}, b: 11, code: "gold"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 7, b: 98, code: "silver"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 3, cust: {age: 7, tier: "", active: false}, b: null, code: "bronze"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{cust: {age: 99, tier: "gold", active: false}, b: 100, code: "bronze"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 1000, cust: {age: 3, tier: "b", active: false}, code: "gold"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 7, cust: {age: -25, tier: "gold", active: true}, code: "b"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: null, code: "bronze"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: null, cust: {age: 100, tier: "silver", active: true}, b: 76, code: "silver"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 0.1, cust: {age: null, tier: "", active: true}, b: 2, code: "Gold"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: -1, cust: {age: 12, tier: "gold ", active: true}, b: 2.5, code: "gold"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 71, cust: {age: null, tier: "bronze", active: null}, b: 5, code: "zz"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: -25, cust: {age: null, tier: "x", active: false}, b: -0.1, code: "x"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: null, cust: {age: 1000000000000000000000, tier: "a", active: false}, b: 2.5, code: "b"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 50, cust: {age: 1000000000000000000000, tier: "b", active: true}, b: null, code: "gold "}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 3, cust: {age: 11, tier: "a", active: null}, b: 5, code: "zz"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: null, cust: {age: 10, tier: "Gold", active: true}, b: 2, code: "x"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: 100, cust: {age: null, tier: "a", active: true}, b: 66, code: ""}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + [{score: -25, cust: {age: 21, tier: "Gold", active: true}, b: 11, code: "silver"}, {k791: 0, k792: "13 ", k793: "none", k794: 5, k800: "3", k801: "true:false", out: {k799: "true"}, res: {k795: false, k796: true, k797: 1.00, k798: false}}], + ], +} + +{ + name: "ga079: 3 nodes, switch*, expr, expr", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["(sum(nums ?? []) < (flag ? (n ?? -1) : (n ?? 0))) and (flag == null)", "((false ? 'A-1' : 'gold') in ['gold', 'silver', 'a']) or (false)"]}, + {expression: "e2", fields: { + k802: "n ?? n", + }}, + {expression: "e3", passThrough: true, fields: { + k803: "min([sum(nums ?? []), ((n ?? -1) < (n ?? -1) ? (n ?? k802 ?? 0) : (n ?? 0))])", + k804: "trim(('A-1' in ['gold', 'silver', 'a'] ? '' : ((flag ?? false) ? 'none' : '')))", + k805: "($.k804 ?? '')", + k806: "((n ?? -1)) / 0.5 * (n ?? 0) == (n ?? 0) + (n ?? 0)", + }}, + ], + edges: [ + "input -> s1", + "s1:0 -> e2", + "e2 -> e3", + "s1:1 -> e3", + "e3 -> output", + ], + }, + cases: [ + [{nums: [-0.1, 7, -0.1], n: 1000000000000000000000, flag: true, items: []}, "!error"], + [{nums: [], n: 1000000000000000000000, flag: true, items: [{price: 21, qty: 2, tag: "gold"}, {price: -25, qty: -1, tag: ""}], extra: [1, 2]}, "!error"], + [{nums: [7], n: 1000, flag: true, items: [{price: 50, qty: null}, {price: 0, qty: -25}]}, {flag: true, items: [{price: 50, qty: null}, {price: 0, qty: -25}], k803: 7, k804: "none", k805: "none", k806: false, n: 1000, nums: [7]}], + [{n: 21, flag: false, items: [{price: 2.5, qty: 1000, tag: "Gold"}, {qty: 99, tag: "Gold"}, {price: 10, qty: -1, tag: "Gold"}, {price: -0.1, tag: ""}]}, {flag: false, items: [{price: 2.5, qty: 1000, tag: "Gold"}, {qty: 99, tag: "Gold"}, {price: 10, qty: -1, tag: "Gold"}, {price: -0.1, tag: ""}], k803: 0, k804: "", k805: "", k806: false, n: 21}], + [{nums: [1, 2.5], n: 50, flag: false, items: [{price: 114, tag: "Gold"}, {price: -25, qty: 101, tag: "x"}, {price: 91, qty: 7, tag: "silver"}, {price: 0.1, qty: 7, tag: "bronze"}]}, {flag: false, items: [{price: 114, tag: "Gold"}, {price: -25, qty: 101, tag: "x"}, {price: 91, qty: 7, tag: "silver"}, {price: 0.1, qty: 7, tag: "bronze"}], k803: 3.5, k804: "", k805: "", k806: false, n: 50, nums: [1, 2.5]}], + [{nums: [], n: 10, flag: true, items: [{price: 1, qty: 11, tag: "a"}]}, {flag: true, items: [{price: 1, qty: 11, tag: "a"}], k803: 0, k804: "none", k805: "none", k806: false, n: 10, nums: []}], + [{nums: [2, 0.5, 10, 11, 0], n: 18, flag: false, items: [{price: 5, qty: 18, tag: "b"}, {price: -1, qty: 50, tag: "gold "}]}, {flag: false, items: [{price: 5, qty: 18, tag: "b"}, {price: -1, qty: 50, tag: "gold "}], k803: 18, k804: "", k805: "", k806: false, n: 18, nums: [2, 0.5, 10, 11, 0]}], + [{nums: [110, 99, 50, 1000000000000000000000, 99], n: 18, flag: true, items: [{price: -0.1, qty: 10, tag: "silver"}, {price: 50, qty: 0.5, tag: ""}, {price: 21, qty: 100, tag: "b"}]}, {flag: true, items: [{price: -0.1, qty: 10, tag: "silver"}, {price: 50, qty: 0.5, tag: ""}, {price: 21, qty: 100, tag: "b"}], k803: 18, k804: "none", k805: "none", k806: false, n: 18, nums: [110, 99, 50, 1000000000000000000000, 99]}], + [{nums: [], n: 0.1, flag: true, items: []}, {flag: true, items: [], k803: 0, k804: "none", k805: "none", k806: false, n: 0.1, nums: []}], + [{nums: [5, 11, -1], n: 50, flag: true, items: [{price: -25, qty: 0.1, tag: "b"}, {qty: 2.5, tag: "b"}]}, {flag: true, items: [{price: -25, qty: 0.1, tag: "b"}, {qty: 2.5, tag: "b"}], k803: 15, k804: "none", k805: "none", k806: false, n: 50, nums: [5, 11, -1]}], + [{nums: [0.5], n: 0.1, flag: false, items: []}, {flag: false, items: [], k803: 0.1, k804: "", k805: "", k806: false, n: 0.1, nums: [0.5]}], + [{nums: [], n: 21, flag: true, items: [{price: 19.99, qty: 0, tag: "x"}]}, {flag: true, items: [{price: 19.99, qty: 0, tag: "x"}], k803: 0, k804: "none", k805: "none", k806: false, n: 21, nums: []}], + [{nums: null, n: null, flag: true, items: [{price: 100, qty: 0.1, tag: "x"}, {price: 2, qty: 1000, tag: "a"}]}, {flag: true, items: [{price: 100, qty: 0.1, tag: "x"}, {price: 2, qty: 1000, tag: "a"}], k803: 0, k804: "none", k805: "none", k806: true}], + [{nums: [0.1, 101, 0, -1, 19.99], n: 2.5, flag: true, items: [{price: 2.5, tag: null}], extra: 1}, {extra: 1, flag: true, items: [{price: 2.5, tag: null}], k803: 2.5, k804: "none", k805: "none", k806: false, n: 2.5, nums: [0.1, 101, 0, -1, 19.99]}], + [{nums: [], n: -1, flag: true, items: [{price: 5, qty: 101, tag: "silver"}]}, {flag: true, items: [{price: 5, qty: 101, tag: "silver"}], k803: -1, k804: "none", k805: "none", k806: false, n: -1, nums: []}], + [{nums: null, flag: false, items: [{price: 0.1, qty: 101, tag: "b"}, {price: 99, qty: 10, tag: ""}]}, {flag: false, items: [{price: 0.1, qty: 101, tag: "b"}, {price: 99, qty: 10, tag: ""}], k803: 0, k804: "", k805: "", k806: true}], + [{nums: [-0.1, 2.5, 0.1], n: 2, flag: false, items: []}, {flag: false, items: [], k803: 2, k804: "", k805: "", k806: false, n: 2, nums: [-0.1, 2.5, 0.1]}], + [{nums: [68, 2.5, 0.1], n: 11, flag: false, items: [{price: 3, qty: null, tag: "bronze"}, {price: 99, qty: null, tag: "gold "}, {price: 101, qty: 0.1, tag: "zz"}, {price: -25, qty: null, tag: "bronze"}]}, {flag: false, items: [{price: 3, qty: null, tag: "bronze"}, {price: 99, qty: null, tag: "gold "}, {price: 101, qty: 0.1, tag: "zz"}, {price: -25, qty: null, tag: "bronze"}], k803: 11, k804: "", k805: "", k806: false, n: 11, nums: [68, 2.5, 0.1]}], + [{nums: [50, 0.1], n: 0.5, flag: false, items: [{qty: 0.5, tag: "b"}, {price: 18, qty: 0, tag: "gold "}, {price: -0.1, tag: "gold "}]}, {flag: false, items: [{qty: 0.5, tag: "b"}, {price: 18, qty: 0, tag: "gold "}, {price: -0.1, tag: "gold "}], k803: 0.5, k804: "", k805: "", k806: false, n: 0.5, nums: [50, 0.1]}], + [{nums: [3], flag: true, items: [{price: 19.99, qty: 0, tag: ""}, {qty: 19.99, tag: "gold "}]}, {flag: true, items: [{price: 19.99, qty: 0, tag: ""}, {qty: 19.99, tag: "gold "}], k803: 0, k804: "none", k805: "none", k806: true, nums: [3]}], + [{n: 7, flag: true, items: [{price: 100, qty: null, tag: "gold "}]}, {flag: true, items: [{price: 100, qty: null, tag: "gold "}], k803: 0, k804: "none", k805: "none", k806: false, n: 7}], + [{nums: [10, 10], n: 1, flag: true, items: [{price: 0.1, qty: 101, tag: "x"}, {price: 21, qty: -0.1, tag: "Gold"}]}, {flag: true, items: [{price: 0.1, qty: 101, tag: "x"}, {price: 21, qty: -0.1, tag: "Gold"}], k803: 1, k804: "none", k805: "none", k806: true, n: 1, nums: [10, 10]}], + [{nums: [19.99], n: null, flag: true, items: [{price: 2.5, qty: 0.1, tag: "gold "}, {price: 100, qty: 7, tag: "gold"}]}, {flag: true, items: [{price: 2.5, qty: 0.1, tag: "gold "}, {price: 100, qty: 7, tag: "gold"}], k803: 0, k804: "none", k805: "none", k806: true, nums: [19.99]}], + [{nums: [50], n: 11, flag: true, items: [{price: 101, qty: 0.5, tag: "zz"}, {price: 0, qty: 18, tag: "gold "}, {price: 18, qty: 100, tag: ""}, {price: 21, qty: 5, tag: "b"}]}, {flag: true, items: [{price: 101, qty: 0.5, tag: "zz"}, {price: 0, qty: 18, tag: "gold "}, {price: 18, qty: 100, tag: ""}, {price: 21, qty: 5, tag: "b"}], k803: 11, k804: "none", k805: "none", k806: false, n: 11, nums: [50]}], + [{nums: [18, 1000, -25, 18, 1000], n: 1000000000000000000000, flag: false, items: [{price: null, qty: -1, tag: "bronze"}, {price: 100, qty: 99, tag: "bronze"}, {price: 101, qty: null, tag: null}, {price: 19.99, qty: 0.1, tag: "bronze"}]}, "!error"], + ], +} diff --git a/core/engine/tests/spec/graph/71-generated-b.json5 b/core/engine/tests/spec/graph/71-generated-b.json5 new file mode 100644 index 00000000..a0f8f442 --- /dev/null +++ b/core/engine/tests/spec/graph/71-generated-b.json5 @@ -0,0 +1,7021 @@ +// Generated graphs, profile b: 6-12 nodes, more switches (half collect), loops over items, inputField/outputPath/passThrough, dirtier rows. +// +// Generator: scratchpad gen/graphgen.py, `python3 graphgen.py b`, seed 71029, 80 suites. +// Random DAGs mixing expression nodes (arithmetic, string, boolean, ternary and `??` over input +// fields, earlier keys via `$` and ancestors via `$nodes`), first/collect tables with random cells +// (equality, ranges, lists, wildcards, null), first/collect switches with random conditions, +// passThrough/outputPath/inputField choices and loops over `items`. Rows vary types per field: +// numbers, strings, bools, null, missing, wrong types, nested objects and arrays. +// +// Outputs recorded from the walker; this chapter exists to differential-test the engines. + +{ + name: "gb000: 7 nodes, switch, table, expr, table, table*, table, expr", + graph: { + nodes: [ + {switch: "s1", when: ["0.5 - 10 + 3 == sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0)))", "true", ""]}, + {table: "t2", inputs: ["(false ? 3 + 10 : -4)"], outputs: ["k1"], rules: [ + ["[100..101)", "true"], + ["!= 5", "(endsWith((code ?? 'none'), 'g')) or (len((code ?? '?')) >= 1 * 2)"], + ["> 100", "false"], + ["not(10)", "true"], + ["", "(-4 == -(2.25))"], + ]}, + {expression: "e3", passThrough: true, fields: { + k2: "s ?? k1", + }}, + {table: "t4", inputs: ["lower(((k1 ?? false) ? '' : s))", null], outputs: ["res.k3"], rules: [ + ["startsWith($, '')", "true", "'high'"], + ["not('silver')", "true", "'low'"], + ["null", "$ != null", "string((s == null) and (not (true)))"], + ["", "5", "'high'"], + ["null", "", "'high'"], + ["'gold'", "", "'low'"], + ["", "", "'high'"], + ]}, + {table: "t5", hit: "collect", inputs: ["k1", "100"], outputs: ["k4", "m.k5"], outputPath: "lines", rules: [ + ["false", "(21..31)", "1", "-4"], + ["null", "[18..19]", "1 + 2 * len(items ?? []) + 0", "10"], + ["$ == true", "10, 20", "-5", "2"], + ["null", "[50..60)", "min([(2), (0 != 10 ? 0.5 : len(nums ?? []))])", "0.25"], + ["true", "<= 1", "10", "-5"], + ["", "", "0 * len(nums ?? [])", "(2)"], + ]}, + {table: "t6", inputs: ["(res.k3 ?? '?') + '' + string(false)", "res.k3", "ceil(2.25 - 10)"], outputs: ["k6"], passThrough: true, outputPath: "res", rules: [ + ["not('gold')", "'gold'", "$ > -1 and $ < 4", "0.25"], + ["", "not('')", "< 10", "100"], + ["null", "not('x')", "<= 105", "3"], + ]}, + {expression: "e7", passThrough: true, fields: { + "res.k7": "''", + k6: "null", + k9: "lower(string((true)))", + }}, + ], + edges: [ + "input -> s1", + "s1:2 -> t2", + "t2 -> e3", + "input -> e3", + "e3 -> t4", + "t2 -> t5", + "s1:2 -> t5", + "t4 -> t6", + "t5 -> t6", + "t5 -> e7", + "s1:1 -> output", + "t6 -> output", + "e7 -> output", + ], + }, + cases: [ + [{code: "gold ", s: "a", nums: [10, 11, 2], items: [{price: -0.1, tag: "bronze"}, {price: 5, qty: 0.5, tag: "gold"}]}, {code: "gold ", items: [{price: -0.1, tag: "bronze"}, {price: 5, qty: 0.5, tag: "gold"}], nums: [10, 11, 2], s: "a"}], + [{code: "zz", s: null, nums: [19.99, 18, 1000], items: []}, {code: "zz", items: [], nums: [19.99, 18, 1000]}], + [{code: "silver", s: "", nums: [1000000000000000000000, 0, 18, 50, 5], items: [{price: "abc", qty: -1, tag: "bronze"}, {price: 101, qty: 0.1, tag: "x"}]}, {code: "silver", items: [{price: "abc", qty: -1, tag: "bronze"}, {price: 101, qty: 0.1, tag: "x"}], nums: [1000000000000000000000, 0, 18, 50, 5], s: ""}], + [{code: "bronze", s: "b", nums: [2.5, -1, 0.5, 2.5, 2], items: [{price: 18, qty: null, tag: "b"}]}, {code: "bronze", items: [{price: 18, qty: null, tag: "b"}], nums: [2.5, -1, 0.5, 2.5, 2], s: "b"}], + [{code: "a", s: "silver", nums: [], items: [{price: 0.1, qty: 19.99, tag: "silver"}, {price: 0.1, qty: 99, tag: "zz"}, {price: null, tag: ""}], extra: "e"}, {code: "a", extra: "e", items: [{price: 0.1, qty: 19.99, tag: "silver"}, {price: 0.1, qty: 99, tag: "zz"}, {price: null, tag: ""}], nums: [], s: "silver"}], + [{s: null, nums: [19.99, 19.99, 101], items: []}, {items: [], nums: [19.99, 19.99, 101]}], + [{code: "a", s: "a", nums: [11, 101], items: []}, {code: "a", items: [], nums: [11, 101], s: "a"}], + [{s: "gold ", nums: [21, 5], items: [{price: 1, qty: 1000, tag: "zz"}, {price: 18, qty: -0.1, tag: "Gold"}]}, {items: [{price: 1, qty: 1000, tag: "zz"}, {price: 18, qty: -0.1, tag: "Gold"}], nums: [21, 5], s: "gold "}], + [{code: "a", nums: [0.1, 0.1, 46, -0.1, -0.1], items: []}, {code: "a", items: [], nums: [0.1, 0.1, 46, -0.1, -0.1]}], + [{code: "zz", s: "x", nums: [21, 100, 50], items: [{price: 10, qty: 99, tag: null}, {price: 1000, qty: 2.5, tag: "bronze"}, {price: 0.5, qty: "5", tag: null}, {price: 2.5}]}, {code: "zz", items: [{price: 10, qty: 99, tag: null}, {price: 1000, qty: 2.5, tag: "bronze"}, {price: 0.5, qty: "5", tag: null}, {price: 2.5}], nums: [21, 100, 50], s: "x"}], + [{code: "silver", s: "b", nums: [{x: 1}], items: [{price: 1000, qty: 1000, tag: "zz"}, {price: 10, qty: 21, tag: "gold "}]}, {code: "silver", items: [{price: 1000, qty: 1000, tag: "zz"}, {price: 10, qty: 21, tag: "gold "}], nums: [{x: 1}], s: "b"}], + [{code: "bronze", s: "gold ", nums: null, items: "items"}, {code: "bronze", items: "items", s: "gold "}], + [{code: null, s: "gold", nums: null, items: [{price: 0.5, qty: 2, tag: ""}]}, {items: [{price: 0.5, qty: 2, tag: ""}], s: "gold"}], + [{code: "gold ", s: "Gold", nums: [{x: 1}], items: []}, {code: "gold ", items: [], nums: [{x: 1}], s: "Gold"}], + [{code: "b", s: "zz", nums: [1000], items: [{price: 1000000000000000000000, qty: 7, tag: null}]}, {code: "b", items: [{price: 1000000000000000000000, qty: 7, tag: null}], nums: [1000], s: "zz"}], + [{code: "gold", s: "b", items: [{price: 1000000000000000000000, qty: 100, tag: ""}, {price: 0.1, qty: 2, tag: "zz"}, {price: 21, qty: 101}, {price: -0.1, qty: 0, tag: ""}]}, {code: "gold", items: [{price: 1000000000000000000000, qty: 100, tag: ""}, {price: 0.1, qty: 2, tag: "zz"}, {price: 21, qty: 101}, {price: -0.1, qty: 0, tag: ""}], s: "b"}], + [{s: ["gold"], nums: [101, 10, 2.5, -25, 18], items: [{price: true, qty: -1, tag: {t: "x"}}, {price: 100, tag: ""}, {price: 7, qty: 1000000000000000000000, tag: "b"}]}, {items: [{price: true, qty: -1, tag: {t: "x"}}, {price: 100, tag: ""}, {price: 7, qty: 1000000000000000000000, tag: "b"}], nums: [101, 10, 2.5, -25, 18], s: ["gold"]}], + [{code: "", s: "Gold", items: []}, {code: "", items: [], s: "Gold"}], + [{code: "b", s: "gold", nums: [-0.1, 2, 50, 50, 101], items: [{price: 2.5, qty: true, tag: "bronze"}, {qty: 0.5, tag: {t: "x"}}]}, {code: "b", items: [{price: 2.5, qty: true, tag: "bronze"}, {qty: 0.5, tag: {t: "x"}}], nums: [-0.1, 2, 50, 50, 101], s: "gold"}], + [{code: "zz", s: "a", nums: [18, 7, 18], items: [{price: null, qty: 1, tag: "zz"}]}, {code: "zz", items: [{price: null, qty: 1, tag: "zz"}], nums: [18, 7, 18], s: "a"}], + [{code: "gold ", s: "zz", nums: [0], items: [{price: null, qty: 0.1, tag: "gold"}, {price: 5, qty: null, tag: "Gold"}, {price: 2, qty: 0, tag: "silver"}, {price: 5, qty: 100}]}, {code: "gold ", items: [{price: null, qty: 0.1, tag: "gold"}, {price: 5, qty: null, tag: "Gold"}, {price: 2, qty: 0, tag: "silver"}, {price: 5, qty: 100}], nums: [0], s: "zz"}], + [{code: {t: "x"}, s: "a", nums: [101, 2], items: [{price: 18, tag: "gold"}], extra: [1, 2]}, {code: {t: "x"}, extra: [1, 2], items: [{price: 18, tag: "gold"}], nums: [101, 2], s: "a"}], + [{code: "gold ", s: "gold", nums: [99, 19.99], items: []}, {code: "gold ", items: [], nums: [99, 19.99], s: "gold"}], + [{code: null, s: null, nums: [1000], items: [{price: 18, qty: 2, tag: null}]}, {items: [{price: 18, qty: 2, tag: null}], nums: [1000]}], + [{code: ["gold"], s: "zz", nums: [10, 11, 2.5, 5, -25], items: [{price: 5, qty: -0.1, tag: "zz"}, {price: 21, qty: 99, tag: "zz"}]}, {code: ["gold"], items: [{price: 5, qty: -0.1, tag: "zz"}, {price: 21, qty: 99, tag: "zz"}], nums: [10, 11, 2.5, 5, -25], s: "zz"}], + [{code: "Gold", s: null, items: [{price: 0.5, qty: 2, tag: "x"}]}, {code: "Gold", items: [{price: 0.5, qty: 2, tag: "x"}]}], + [{code: "x", s: "Gold", nums: [-1], items: [{price: 99, qty: 1000000000000000000000, tag: true}]}, {code: "x", items: [{price: 99, qty: 1000000000000000000000, tag: true}], nums: [-1], s: "Gold"}], + ], +} + +{ + name: "gb001: 10 nodes, expr, switch, table, table*, expr, expr, table*, switch, table*, table*", + graph: { + nodes: [ + {expression: "e1", fields: { + "m.k10": "vip ?? n", + k11: "n + 2 * 2.25 * (price ?? -1)", + k12: "(((s ?? '') in ['gold', 'silver', 'a']) or ((vip ?? false)) ? (n ?? 1) % 7 * (a ?? -1) + 0.5 : (len('none')))", + k13: "((a ?? 1)) * (n ?? 1) * (n ?? -1) != (price ?? 1)", + }}, + {switch: "s2", when: ["contains('', 'a')", "price < (k11 ?? 0)"]}, + {table: "t3", inputs: ["vip"], outputs: ["k13"], rules: [ + ["true", "'gold'"], + ["null", "'high'"], + ["true", "'mid'"], + ["true", "'gold'"], + ["", "'gold'"], + ]}, + {table: "t4", hit: "collect", inputs: ["k13"], outputs: ["k15"], outputPath: "lines", rules: [ + ["", "not ((k13 ?? false))"], + ["", "true"], + ["$ == true", "false"], + ["", "(k13 ?? false)"], + ]}, + {expression: "e5", fields: { + "g.k16": "string((score * k12) / 2)", + }}, + {expression: "e6", outputPath: "res", fields: { + k13: "`${(score ?? 0)}-${(k13 ?? 'none')}`", + k18: "((vip ?? false)) or ((vip ?? false))", + "g.k19": "len('')", + "m.k20": "price ?? $.k18", + }}, + {table: "t7", hit: "collect", inputs: ["2.25", "2", "len((g.k16 ?? '?') + '' + g.k16)", null], outputs: ["m.k21"], rules: [ + ["<= 9", "< 50", "[50..100)", "", "1"], + ["<= 15", "21, 31", "", "", "0"], + ["not(-1)", "not(1)", ">= 18", "", "len((g.k16 ?? ''))"], + ["[0..10)", "!= 50", "not(1)", "$ != null", "100"], + ["< 50", "null", "!= -1", "null", "10"], + ["(100..105)", "[-1..49)", "!= 5", "'gold'", "0.25"], + ]}, + {switch: "s8", when: ["endsWith(string(res.g.k19 == (res.g.k19 ?? 1)), 'a')", "res.k13 in ['gold', 'silver', 'a']", "3 - ceil((res.g.k19 ?? 1)) == -(res.g.k19)", ""]}, + {table: "t9", hit: "collect", inputs: ["res.g.k19", "res.g.k19"], outputs: ["k22[]", "k23"], outputPath: "res", rules: [ + ["!= 21", "[0..5]", "1", "true"], + [">= 10", "!= 10", "0", "false"], + ["", "null", "abs((2.25) - (res.g.k19 ?? -1) * 0.5)", "false"], + ["", "<= 10", "1", "false"], + ]}, + {table: "t10", hit: "collect", inputs: ["'gold'", "2", "0.5"], outputs: ["k24"], outputPath: "o.p", rules: [ + ["", "> 100", "not(-1)", "false"], + ["startsWith($, 'g')", "[21..26]", "<= 9", "true"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "input -> s2", + "input -> t3", + "e1 -> t4", + "s2:1 -> e5", + "t3 -> e6", + "input -> e6", + "e5 -> t7", + "e6 -> s8", + "t4 -> s8", + "s8:3 -> t9", + "t9 -> t10", + "s2:0 -> output", + "t7 -> output", + "s8:1 -> output", + "s8:2 -> output", + "t10 -> output", + ], + }, + cases: [ + [{nums: [], s: "gold", a: [1], n: 3, vip: false, score: 101, price: 1}, "!error"], + [{nums: [50, 0.5, 50, 50, -0.1], s: "zz", a: null, n: 10, vip: true, score: 18, price: -0.1}, []], + [{nums: [11], a: 1000, n: null, vip: false, price: 7}, "!error"], + [{nums: [{x: 1}], s: "zz", a: 50, n: 7, vip: 0, score: 7, price: 1}, "!error"], + [{nums: [5, 100, 11], s: "b", a: 1000, n: 19.99, vip: false, score: 73}, {o: {p: []}}], + [{nums: [2, 0.5], s: "bronze", a: 0, vip: true, score: 2.5, price: 10}, "!error"], + [{nums: [50, 1000000000000000000000], s: "x", a: 99, n: 0, vip: true, score: 1, price: 2.5}, []], + [{s: "gold", a: -25, n: 5, vip: false, score: null, price: 3}, "!error"], + [{nums: [0.1], s: null, a: 0, vip: true, score: {v: 1}, price: 1}, "!error"], + [{nums: [19.99, 0, 50, 29, 5], s: "x", a: 50, n: 100, vip: null, score: 1000, price: -11, extra: {deep: {x: 1}}}, []], + [{nums: [7, 21], s: "zz", a: 101, n: 1000, vip: true, score: -25, price: 5}, []], + [{nums: [100], s: null, a: null, n: 18, vip: false, score: 21, price: 21}, []], + [{nums: [11, 1000000000000000000000, -25], s: "x", a: 0.5, vip: false, score: 18}, "!error"], + [{s: "gold ", a: -0.1, n: 50, vip: false, score: 0, price: 1000000000000000000000}, []], + [{nums: [18, 114], s: ["gold"], a: 1000, n: 21, vip: false, score: 19.99, price: 7}, "!error"], + [{nums: null, s: "b", a: 2.5, n: 10, vip: true, score: 50, price: 99}, []], + [{nums: [0], s: "x", a: 19, n: -25, vip: true, score: 100, price: [1]}, "!error"], + [{nums: "1,2", s: null, a: 3, n: 21, vip: false, score: 21, price: 1000}, []], + [{nums: [2, 100, -25], s: "gold ", a: -25, n: 6, vip: true, score: 5}, {o: {p: []}}], + [{nums: null, s: "x", a: null, n: null, vip: false, score: 3, price: 19.99}, "!error"], + [{nums: [], s: 5, a: 10, n: 101, vip: true, score: true, price: -25}, "!error"], + [{nums: [2, 3, 7], s: "silver", a: 5, n: null, vip: null, score: 7, price: 99}, "!error"], + [{nums: [3, 1000, 21], s: "x", a: null, n: 1000000000000000000000, vip: false, score: 1, price: 5}, "!error"], + [{nums: [2.5], s: null, n: 1, vip: null, score: 11, price: 21}, []], + [{nums: "1,2", s: "gold", a: 100, n: true, vip: false, score: null, price: 21}, "!error"], + [{nums: [99, 1000000000000000000000], s: "zz", a: 19.99, n: 50, vip: null, score: null, price: "abc"}, "!error"], + [{nums: [0.1, 0.1], s: "a", a: null, n: 5, vip: true, score: 19.99, price: null}, {o: {p: []}}], + ], +} + +{ + name: "gb002: 7 nodes, expr, table*, switch*, table, switch*, loop expr, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "res", fields: { + "res.k25": "-((a ?? 1))", + }}, + {table: "t2", hit: "collect", inputs: ["(b ?? b ?? 0)"], outputs: ["g.k26", "k27"], passThrough: true, outputPath: "res", rules: [ + ["<= 71", "0.25", "0"], + ["null", "-5", "10"], + ]}, + {switch: "s3", hit: "collect", when: ["((true ? (n ?? 1) : b)) <= (score ?? b ?? 0) * (a ?? price ?? 0)"]}, + {table: "t4", inputs: ["b", "upper('gold')"], outputs: ["k28", "k29"], rules: [ + [">= 10", "'a', 'bronze'", "true", "-5"], + ["$ > 50 and $ < 100", "$ != ''", "true", "0"], + ["not(-1)", "'silver'", "true", "0"], + ["", "", "true", "10"], + ]}, + {switch: "s5", hit: "collect", when: ["endsWith(string(a), '')", "(a ?? -1) % 7 in [-5..5]", ""]}, + {expression: "e6", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + "res.k30": "tag ?? qty", + }}, + {expression: "e7", fields: { + "res.k31": "count(items ?? [], (#.qty ?? 0) > 1)", + k32: "'x'", + "m.k33": "'none'", + k34: "((-4)) in [0..10]", + }}, + ], + edges: [ + "input -> e1", + "input -> t2", + "e1 -> s3", + "e1 -> t4", + "s3:0 -> t4", + "t2 -> s5", + "s5:1 -> e6", + "s5:0 -> e7", + "t4 -> output", + "e6 -> output", + "e7 -> output", + ], + }, + cases: [ + [{b: 50, score: [1], n: -1, a: null, items: [{price: 1, qty: 101, tag: "gold"}, {price: 101, qty: -0.1, tag: null}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "gold"}}, {res: {k30: -0.1}}]}], + [{b: 18, score: "abc", n: 99, price: 0.1, a: null, items: [{qty: 2, tag: "gold"}, {price: 3, qty: 2.5, tag: null}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "gold"}}, {res: {k30: 2.5}}]}], + [{cust: {age: -0.1, tier: "x", active: false}, b: 2.5, score: 21, n: 7, price: null, a: 1000000000000000000000, items: [{price: 1000, qty: -0.1, tag: "a"}, {price: 50, qty: 101, tag: ""}], extra: 1}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: {k31: 1}}], + [{cust: {age: 11, tier: "", active: 0}, b: 1, score: 99, n: 21, price: 10, items: []}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: []}], + [{cust: {age: 1, tier: "gold", active: false}, b: 100, score: 0.1, n: 3, price: 3, items: [{price: -1, qty: -25, tag: true}, {price: 0.5, qty: 1000, tag: "bronze"}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: true}}, {res: {k30: "bronze"}}]}], + [{cust: {age: 1000, tier: "Gold", active: null}, b: null, score: 99, n: 21, price: 7, a: 0.1, items: [{price: {v: 1}, qty: 101}, {price: 100, qty: 1000000000000000000000, tag: "zz"}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: 101}}, {res: {k30: "zz"}}]}], + [{cust: {age: 19.99, tier: "bronze", active: false}, b: 99, score: 3, n: 3, price: 1, a: null, items: [{price: 3, qty: 2.5, tag: "x"}, {price: 0, qty: 0.1, tag: "a"}]}, {k28: true, k29: 0, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "x"}}, {res: {k30: "a"}}]}], + [{cust: {age: 0.5, tier: "silver", active: true}, b: 1000000000000000000000, score: -0.1, price: 60, a: 0, items: [{price: 11, qty: 10, tag: "zz"}, {price: 19.99, qty: 99, tag: "silver"}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "zz"}}, {res: {k30: "silver"}}]}], + [{cust: {age: 99, tier: "Gold", active: false}, b: 101, score: null, n: {v: 1}, price: 2, a: null, items: [{price: 2, tag: "bronze"}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "bronze"}}]}], + [{cust: {age: 0.1, tier: "zz", active: false}, b: 1000000000000000000000, score: null, n: 2, price: 100, a: 21, items: [{price: 11, qty: 2, tag: "silver"}, {price: 0.5, qty: 11, tag: "a"}, {price: 21, tag: "a"}, {price: null, qty: 5, tag: ["gold"]}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "silver"}}, {res: {k30: "a"}}, {res: {k30: "a"}}, {res: {k30: ["gold"]}}]}], + [{cust: {age: null, tier: "gold", active: 0}, b: 99, score: 18, n: 0, price: 1, items: [{price: 18, qty: null, tag: "a"}, {price: -25, qty: 100, tag: "zz"}]}, {k28: true, k29: 0, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "a"}}, {res: {k30: "zz"}}]}], + [{cust: {age: 2, tier: "bronze", active: false}, b: 101, score: null, n: 21, price: "abc", a: 1000000000000000000000, items: [{price: -25, qty: {v: 1}, tag: "Gold"}, {price: 101, qty: 3, tag: "x"}, {price: 2.5, qty: 2, tag: "Gold"}]}, "!error"], + [{cust: {age: 7, tier: "a", active: null}, b: [1], score: 7, price: 18, a: 50, items: []}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: []}], + [{cust: {tier: null}, b: 18, score: -1, n: 18, price: 5, a: -25, items: [{price: -25, tag: "gold"}, {price: 77, qty: 11, tag: ""}, {price: 21, qty: 1000000000000000000000, tag: "Gold"}, {price: 100, qty: 5, tag: "gold"}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "gold"}}, {res: {k30: ""}}, {res: {k30: "Gold"}}, {res: {k30: "gold"}}]}], + [{cust: {age: 3, tier: null, active: false}, b: -25, score: 19.99, n: 2.5, price: 19.99, a: 1, items: [{price: 1000000000000000000000, qty: 3, tag: "Gold"}, {price: 18, qty: 0, tag: null}, {qty: 2}], extra: [1, 2]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "Gold"}}, {res: {k30: 0}}, {res: {k30: 2}}]}], + [{cust: {age: 101, tier: "Gold", active: false}, b: 10, score: 11, n: -25, price: 1000, a: "abc"}, "!error"], + [{cust: {age: "abc", tier: "gold", active: true}, b: 18, score: 2, n: 7, price: 11, a: 1000000000000000000000, items: [{price: 50, qty: 101, tag: "Gold"}, {price: 19.99, qty: [1], tag: "a"}, {price: 7, qty: 2.5, tag: true}, {qty: 101, tag: ""}]}, "!error"], + [{cust: {age: 19.99, tier: "bronze", active: 0}, b: 11, score: 11, n: "abc", price: 2, a: 32, items: [{price: 10, qty: 3, tag: "Gold"}, {price: "5", qty: 19.99, tag: "gold "}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "Gold"}}, {res: {k30: "gold "}}]}], + [{b: 0, score: 0.1, a: true, items: [{price: 2.5, qty: 19.99, tag: "Gold"}, {price: 3, qty: 1, tag: "a"}]}, "!error"], + [{cust: "cust", b: 1000000000000000000000, n: 1000000000000000000000, price: 1000, a: 21, items: [{price: 10, qty: 1000, tag: "a"}, {price: 0, qty: 0, tag: "x"}, {price: 21, qty: 11, tag: "a"}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "a"}}, {res: {k30: "x"}}, {res: {k30: "a"}}]}], + [{cust: {age: 0.1, tier: null, active: false}, b: 0, score: 50, n: 19.99, price: 2, a: -25, items: [{price: 19.99, qty: 18}, {price: 10, qty: 100, tag: "x"}, {price: -1, qty: 101, tag: null}, {price: 101, qty: 1000000000000000000000, tag: "x"}], extra: [1, 2]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: 18}}, {res: {k30: "x"}}, {res: {k30: 101}}, {res: {k30: "x"}}]}], + [{cust: {age: null, tier: "zz", active: null}, b: 19.99, score: -25, n: 11, price: null, a: 0.1, items: [{price: 2.5, qty: null, tag: "b"}, {price: 2.5, qty: 5, tag: "b"}, {price: 1000000000000000000000, qty: 1000, tag: null}, {price: 5, qty: 61, tag: "silver"}]}, {k28: true, k29: 10, k32: "x", k34: false, m: {k33: "none"}, res: [{res: {k30: "b"}}, {res: {k30: "b"}}, {res: {k30: 1000}}, {res: {k30: "silver"}}]}], + ], +} + +{ + name: "gb003: 10 nodes, table*, expr, switch, switch, loop expr, loop table, loop expr, table, expr, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["b"], outputs: ["k35", "k36"], passThrough: true, outputPath: "res", rules: [ + ["!= 50", "0.25", "2"], + ["[100..101)", "0", "-(max([b + (b ?? -1), round((b ?? 1))]))"], + ["<= 60", "1", "(b ?? -1)"], + ["$ > 10 and $ < 20", "-5", "1"], + ["", "-5", "10"], + ["< 5", "(max([(b ?? 0), (b ?? -1)]) < (b ?? 0) ? len(`n=${b}-${'gold'}`) : 0 + (b ?? 1) * 1 % 3)", "2"], + ["", "1", "10"], + ]}, + {expression: "e2", passThrough: true, outputPath: "res", fields: { + k37: "(flag ?? false)", + k38: "max([((b ?? 1) + (b ?? 0)), floor((b ?? -1) % 2)])", + }}, + {switch: "s3", when: ["flag", "(flag ?? false)", ""]}, + {switch: "s4", when: ["((flag ?? false)) and (false)", "((flag ?? false)) or ((b != null) or (flag))", "not ((flag != null))", ""]}, + {expression: "e5", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + "m.k39": "'gold'", + }}, + {table: "t6", inputField: "items", executionMode: "loop", inputs: ["(price ?? -1)"], outputs: ["k40"], outputPath: "out", rules: [ + ["< 1", "(((false) and (true)) ? string((false) and (true)) : (tag ?? ''))"], + ["not(0)", "'gold'"], + [">= 21", "'mid'"], + ["> 0", "'gold'"], + ["< 10", "''"], + ["", "'low'"], + ]}, + {expression: "e7", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + k41: "true", + k36: "qty + qty % 2", + }}, + {table: "t8", inputs: ["(3) + 1 * 10", "(0 ?? 1 ?? 0)"], outputs: ["m.k43", "k44"], outputPath: "lines", rules: [ + ["5, 6", "50, 100", "10", "-((0.5)) + 0.5"], + ["not(100)", ">= 18", "-5", "(0 ?? 1 ?? 0)"], + ["not(0)", "[50..55]", "10", "len(string((true) and (false)))"], + ["< 100", "[5..10)", "-5", "2"], + ["[50..60]", "$ > 18 and $ < 19", "100", "-5"], + ]}, + {expression: "e9", fields: { + k45: "flag ?? flag", + "m.k46": "trim(string(0.5 + (lines.m.k43 ?? 1)))", + }}, + {expression: "e10", fields: { + k47: "null", + k48: "$nodes.t1.k35 * 0 * (10) / 4 * (0) % 3", + k49: "(true)", + }}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "input -> s3", + "t1 -> s4", + "s3:0 -> s4", + "s4:1 -> e5", + "s4:3 -> e5", + "s4:2 -> t6", + "s4:3 -> e7", + "t6 -> e7", + "e7 -> t8", + "t8 -> e9", + "s3:0 -> e9", + "t6 -> e10", + "e2 -> output", + "s3:1 -> output", + "e5 -> output", + "t6 -> output", + "e9 -> output", + "e10 -> output", + ], + }, + cases: [ + [{code: "Gold", flag: true, b: 18, tier: {t: "x"}, items: []}, {b: 18, code: "Gold", flag: true, items: [], k45: true, m: {k46: "1.5"}, res: {k37: true, k38: 36}, tier: {t: "x"}}], + [{code: "b", flag: null, b: 3, tier: "silver", items: []}, {b: 3, code: "b", items: [], res: {k37: false, k38: 6}, tier: "silver"}], + [{code: "Gold", flag: true, tier: "gold", items: 3, extra: 1}, "!error"], + [{code: "b", flag: 1, b: 3, tier: "bronze", items: [{price: 100, qty: null, tag: 5}, {price: {v: 1}, qty: 0.5, tag: null}]}, "!error"], + [{code: "zz", flag: 1, b: 2, tier: "x", items: [{price: 99, tag: "bronze"}, {price: 101, qty: 0.1, tag: 5}, {price: 11, qty: 21, tag: "b"}]}, "!error"], + [{code: "gold", flag: true, b: 1000, tier: null, items: [{price: 5, qty: "abc", tag: "a"}, {price: 1000, qty: 2, tag: "silver"}, {price: -0.1, qty: 11, tag: 5}, {price: 21, qty: 100, tag: "b"}]}, {b: 1000, code: "gold", flag: true, items: [{price: 5, qty: "abc", tag: "a"}, {price: 1000, qty: 2, tag: "silver"}, {price: -0.1, qty: 11, tag: 5}, {price: 21, qty: 100, tag: "b"}], k45: true, m: {k46: "1.5"}, res: {k37: true, k38: 2000}}], + [{code: "gold ", flag: false, b: -1, tier: ["gold"], items: [{price: -1, qty: 0, tag: "gold"}, {price: 2.5, qty: 100, tag: "x"}, {price: -16, qty: 52, tag: ""}, {price: 50, qty: -0.1, tag: ["gold"]}]}, {b: -1, code: "gold ", flag: false, items: [{price: -1, qty: 0, tag: "gold"}, {price: 2.5, qty: 100, tag: "x"}, {price: -16, qty: 52, tag: ""}, {price: 50, qty: -0.1, tag: ["gold"]}], res: {k37: false, k38: -1}, tier: ["gold"]}], + [{code: "a", b: 99, tier: "", items: [{price: 10, qty: 3, tag: "a"}, {price: 101, qty: "abc", tag: "zz"}, {price: 101, qty: 2, tag: "b"}]}, {b: 99, code: "a", items: [{price: 10, qty: 3, tag: "a"}, {price: 101, qty: "abc", tag: "zz"}, {price: 101, qty: 2, tag: "b"}], res: {k37: false, k38: 198}, tier: ""}], + [{code: null, flag: true, b: 0, tier: "x", items: [{price: 2.5, qty: 3, tag: "gold "}, {price: 99, qty: 2, tag: "Gold"}, {tag: null}, {price: -0.1, qty: 100, tag: null}], extra: 1}, {b: 0, extra: 1, flag: true, items: [{price: 2.5, qty: 3, tag: "gold "}, {price: 99, qty: 2, tag: "Gold"}, {tag: null}, {price: -0.1, qty: 100, tag: null}], k45: true, m: {k46: "1.5"}, res: {k37: true, k38: 0}, tier: "x"}], + [{code: "x", flag: "no", b: 2.5, tier: "gold", items: [{price: 100, qty: "5"}, {price: {v: 1}, qty: 1, tag: "x"}, {price: [1], qty: 18, tag: "a"}]}, "!error"], + [{code: "", flag: null, b: "5", tier: "gold ", items: [{price: 2.5, qty: 5}]}, "!error"], + [{code: null, flag: true, b: true, tier: "gold ", items: [{price: 1000, qty: {v: 1}, tag: "Gold"}, {qty: -1, tag: "zz"}]}, "!error"], + [{code: "bronze", flag: "no", b: 21, tier: "a", items: [1, 2]}, "!error"], + [{code: "gold ", flag: true, b: null, tier: "gold", items: [{price: 21, qty: 21, tag: "bronze"}, {price: "5", qty: 1000, tag: "b"}]}, {code: "gold ", flag: true, items: [{price: 21, qty: 21, tag: "bronze"}, {price: "5", qty: 1000, tag: "b"}], k45: true, m: {k46: "1.5"}, res: {k37: true, k38: 1}, tier: "gold"}], + [{code: "bronze", flag: true, b: -0.1, tier: "Gold"}, "!error"], + [{code: "b", flag: null, tier: "", items: [{price: 11, qty: -1, tag: "gold"}, {price: 50, qty: null, tag: "Gold"}]}, "!error"], + ], +} + +{ + name: "gb004: 10 nodes, expr, expr, switch*, table, table, table, table*, switch*, table, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + "m.k50": "(tier ?? '')", + k51: "tier + '-' + (tier ?? '?')", + "g.k53": "tier", + }}, + {expression: "e2", passThrough: true, fields: { + k54: "(a ?? 1) * (not (vip) ? (false ? b : (a ?? -1)) : len(tier))", + k55: "upper('' + '' + (tier ?? 'none')) != 'silver'", + }}, + {switch: "s3", hit: "collect", when: ["(b ?? 0) in [-5..5]"]}, + {table: "t4", inputField: "cust", inputs: ["age", "active"], outputs: ["g.k56", "res.k57"], rules: [ + ["<= 2", "null", "'mid'", "100"], + ["$ > 10 and $ < 60", "false", "'gold'", "0.25"], + ["", "$ == true", "''", "-((age ?? -1) % 3)"], + ["not(21)", "true", "''", "(age ?? 1) % 7"], + ["!= 100", "", "'none'", "0.25"], + ]}, + {table: "t5", inputs: ["res.k57"], outputs: ["g.k58", "m.k59"], passThrough: true, rules: [ + ["not(0)", "'gold'", "''"], + ["> 100", "''", "'high'"], + ]}, + {table: "t6", inputs: ["m.k59"], outputs: ["k60"], outputPath: "res", rules: [ + ["not('gold')", "-5"], + ["''", "len(string((g.k58 ?? '') == 'x'))"], + ["not('')", "-5"], + ["'a'", "2"], + ["null", "10"], + ["'silver', 'bronze'", "0"], + ["", "100"], + ]}, + {table: "t7", hit: "collect", inputs: ["(tier ?? '?')"], outputs: ["m.k61"], outputPath: "out", rules: [ + ["", "true"], + ["$ != 'gold'", "false"], + ["$ != 'silver'", "false"], + ["'', 'b'", "false"], + ["", "true"], + ]}, + {switch: "s8", hit: "collect", when: ["contains((true ? string(true) : g.k58), 'x')", "false", "(((res.k57 ?? -1)) / 2) >= res.k57 - res.k57"]}, + {table: "t9", inputs: ["'x'"], outputs: ["k62", "m.k63"], outputPath: "res", rules: [ + ["$ != ''", "false", "'mid'"], + ["not('silver')", "false", "'high'"], + ["$ != 'x'", "false", "''"], + ["", "false", "''"], + ["", "(true) and (2 > len(''))", "(false ? 'A-1' : 'none' + '-' + 'gold') + ' ' + 'x'"], + ]}, + {expression: "e10", outputPath: "lines", fields: { + "m.k61": "(res.k57 ?? 1)", + "res.k65": "true", + k66: "string((res.k57 ?? res.k60 ?? 0) - (res.k57 ?? 0))", + k67: "(100 * 100 - (res.k57 ?? -1) + (res.k60 ?? 1))", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e2 -> s3", + "input -> s3", + "input -> t4", + "t4 -> t5", + "t5 -> t6", + "s3:0 -> t7", + "t6 -> t7", + "t5 -> s8", + "t7 -> t9", + "t6 -> e10", + "t5 -> e10", + "e1 -> output", + "s8:0 -> output", + "s8:2 -> output", + "t9 -> output", + "e10 -> output", + ], + }, + cases: [ + [{a: 0.1, tier: "gold", items: [], b: 18, n: 50, cust: null, vip: null}, "!error"], + [{a: 10, tier: "silver", items: [], b: 50, n: 1000000000000000000000, cust: {age: 1000, tier: "Gold", active: false}, vip: false}, {a: 10, b: 50, cust: {active: false, age: 1000, tier: "Gold"}, g: {k53: "silver", k56: "none"}, items: [], k51: "silver-silver", lines: {k66: "0.00", k67: 10009.75, m: {k61: 0.25}, res: {k65: true}}, m: {k50: "silver"}, n: 1000000000000000000000, res: {k57: 0.25, k62: false, m: {k63: "mid"}}, tier: "silver", vip: false}], + [{a: 101, tier: "Gold", items: [], b: "5", n: 1000, cust: {age: 21, tier: null, active: true}, vip: true}, {a: 101, b: "5", cust: {active: true, age: 21, tier: null}, g: {k53: "Gold", k56: ""}, items: [], k51: "Gold-Gold", lines: {k66: "-0", k67: 10010, m: {k61: -0}, res: {k65: true}}, m: {k50: "Gold"}, n: 1000, res: {k57: -0, k62: false, m: {k63: "mid"}}, tier: "Gold", vip: true}], + [{a: 3, tier: null, items: [], b: 10, n: 1000000000000000000000, cust: {age: 2.5, tier: "", active: true}, vip: true, extra: {deep: {x: 1}}}, "!error"], + [{a: 7, tier: "Gold", items: [], b: -1, n: 1, cust: {age: 0, tier: "gold ", active: true}, vip: true}, {a: 7, b: -1, cust: {active: true, age: 0, tier: "gold "}, g: {k53: "Gold", k56: ""}, items: [], k51: "Gold-Gold", lines: {k66: "-0", k67: 10010, m: {k61: -0}, res: {k65: true}}, m: {k50: "Gold"}, n: 1, res: {k57: -0, k62: false, m: {k63: "mid"}}, tier: "Gold", vip: true}], + [{a: null, items: [{price: 0, qty: 0, tag: null}], b: 5, n: 2, cust: null}, "!error"], + [{a: 3, tier: "", items: [{price: 100, tag: "Gold"}, {price: 101, qty: 1000000000000000000000, tag: "b"}], b: 11, n: 50, cust: {age: 2, tier: "bronze", active: true}, vip: false}, {a: 3, b: 11, cust: {active: true, age: 2, tier: "bronze"}, g: {k53: ""}, items: [{price: 100, tag: "Gold"}, {price: 101, qty: 1000000000000000000000, tag: "b"}], k51: "-", lines: {k66: "0", k67: 10012, m: {k61: -2}, res: {k65: true}}, m: {k50: ""}, n: 50, res: {k62: false, m: {k63: "mid"}}, tier: "", vip: false}], + [{a: 50, tier: 5, items: [{price: "abc", qty: 50, tag: "gold "}, {price: -1, qty: 5, tag: "silver"}, {price: 100, qty: "abc", tag: "zz"}], b: 0.1, n: 0.5, cust: {age: 11, tier: "a", active: true}, extra: [1, 2]}, "!error"], + [{a: null, items: [], b: [1], n: 0, cust: [], vip: false}, "!error"], + [{a: 0.5, tier: null, items: [], b: 1, n: 19.99, cust: {age: -1, tier: "Gold", active: true}, vip: false}, "!error"], + [{tier: "x", items: [], b: 15, n: 10, vip: false}, {b: 15, g: {k53: "x", k56: "none"}, items: [], k51: "x-x", lines: {k66: "0.00", k67: 10009.75, m: {k61: 0.25}, res: {k65: true}}, m: {k50: "x"}, n: 10, res: {k57: 0.25, k62: false, m: {k63: "mid"}}, tier: "x", vip: false}], + [{a: 99, tier: "b", items: [{qty: 5, tag: "a"}, {price: 0.5, qty: 0.1, tag: null}], b: true, n: 22, cust: {age: 11, tier: "bronze", active: false}}, "!error"], + [{a: 10, tier: {t: "x"}, n: 7, cust: {age: -1, tier: "gold ", active: null}, vip: true}, "!error"], + [{a: 78, tier: "a", items: [{price: 0.1, qty: -25, tag: true}, {price: 3, qty: 2.5, tag: ""}], b: -0.1, n: 1000, cust: {age: 21, tier: "a", active: true}, vip: false}, {a: 78, b: -0.1, cust: {active: true, age: 21, tier: "a"}, g: {k53: "a", k56: ""}, items: [{price: 0.1, qty: -25, tag: true}, {price: 3, qty: 2.5, tag: ""}], k51: "a-a", lines: {k66: "-0", k67: 10010, m: {k61: -0}, res: {k65: true}}, m: {k50: "a"}, n: 1000, res: {k57: -0, k62: false, m: {k63: "mid"}}, tier: "a", vip: false}], + [{a: 99, tier: "gold", items: [{price: -1, qty: 2.5, tag: "gold "}, {price: {v: 1}, qty: 99, tag: "silver"}], b: 99, n: 50, cust: {age: 18, tier: "a", active: true}, vip: true}, {a: 99, b: 99, cust: {active: true, age: 18, tier: "a"}, g: {k53: "gold", k56: ""}, items: [{price: -1, qty: 2.5, tag: "gold "}, {price: {v: 1}, qty: 99, tag: "silver"}], k51: "gold-gold", lines: {k66: "-0", k67: 10010, m: {k61: -0}, res: {k65: true}}, m: {k50: "gold"}, n: 50, res: {k57: -0, k62: false, m: {k63: "mid"}}, tier: "gold", vip: true}], + [{a: 21, tier: "gold ", items: [{price: -1, qty: -0.1, tag: "x"}], n: 19.99, cust: {age: 19.99, tier: "gold ", active: true}, vip: true}, {a: 21, cust: {active: true, age: 19.99, tier: "gold "}, g: {k53: "gold "}, items: [{price: -1, qty: -0.1, tag: "x"}], k51: "gold -gold ", lines: {k66: "0.00", k67: 10011.99, m: {k61: -1.99}, res: {k65: true}}, m: {k50: "gold "}, n: 19.99, res: {k62: false, m: {k63: "mid"}}, tier: "gold ", vip: true}], + [{a: -25, tier: "zz", items: [{price: 101, qty: 21, tag: "gold "}], b: 101, n: 10, cust: {age: 11, tier: "silver", active: true}, vip: null, extra: "e"}, "!error"], + [{a: 50, tier: "gold ", items: [], b: 2, n: 101, vip: 1}, "!error"], + [{tier: "x", items: [], b: "5", n: 52, cust: null, vip: false, extra: 1}, {b: "5", extra: 1, g: {k53: "x", k56: "none"}, items: [], k51: "x-x", lines: {k66: "0.00", k67: 10009.75, m: {k61: 0.25}, res: {k65: true}}, m: {k50: "x"}, n: 52, res: {k57: 0.25, k62: false, m: {k63: "mid"}}, tier: "x", vip: false}], + [{a: 19.99, tier: 5, items: [{price: 11, qty: 19.99, tag: "x"}, {price: 2, qty: 37, tag: "gold "}, {price: 100, qty: -1, tag: ""}, {price: -0.1, qty: -1, tag: "zz"}], b: 2.5, cust: {age: 11, tier: "zz", active: true}, vip: "true", extra: {deep: {x: 1}}}, "!error"], + ], +} + +{ + name: "gb005: 9 nodes, switch, switch, loop expr, switch, loop table*, table, switch*, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["contains(string('A-1' != 'silver'), '')", "flag", ""]}, + {switch: "s2", when: ["'gold' + ' ' + 'A-1' + '-' + ((flag ?? false) ? 'none' : cust.tier) == 'silver'", "(sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0)))) <= (0.5 * (a ?? -1)) / 10"]}, + {expression: "e3", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k68: "lower(string(false)) + ':' + `v${1}-${(tag ?? '')}`", + }}, + {switch: "s4", when: ["endsWith((cust.tier ?? '?'), '')"]}, + {table: "t5", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["(price == null ? string(qty) : string(qty))", "tag"], outputs: ["m.k69", "k70"], passThrough: true, outputPath: "o.p", rules: [ + ["startsWith($, 's')", "", "1", "(tag ?? 'none')"], + ["'x'", "'x'", "2", "'mid'"], + ["null", "'a'", "2", "'gold'"], + ["$ != 'a'", "", "-5", "'mid'"], + ["", "'a'", "1", "'gold'"], + ["startsWith($, 's')", "startsWith($, 'g')", "100", "'gold'"], + ]}, + {table: "t6", inputs: ["'gold' + ':' + string(0.5)"], outputs: ["k71", "k72"], rules: [ + ["not('silver')", "true", "false"], + ["startsWith($, 'x')", "(not ((true) or (true))) or ('gold' == 'x')", "true"], + ["'gold', 'b'", "true", "true"], + ["", "false", "false"], + ]}, + {switch: "s7", hit: "collect", when: ["(a != null) or (not (not (true)))"]}, + {expression: "e8", fields: { + "m.k73": "(((price ?? -1)) != 3) and (contains('', ''))", + "res.k74": "flag ?? flag", + }}, + {table: "t9", inputs: ["(2.25 * 2.25) / 3"], outputs: ["k75", "k76"], passThrough: true, outputPath: "out", rules: [ + ["", "100", "-5"], + ["[10..15)", "-5", "100"], + ]}, + ], + edges: [ + "input -> s1", + "s1:2 -> s2", + "s2:0 -> e3", + "s2:1 -> s4", + "s2:1 -> t5", + "e3 -> t6", + "e3 -> s7", + "t5 -> e8", + "e8 -> t9", + "s1:0 -> output", + "s4:0 -> output", + "t6 -> output", + "s7:0 -> output", + "t9 -> output", + ], + }, + cases: [ + [{cust: {age: 0, tier: "zz", active: "no"}, price: 3, flag: 0, items: [{price: 107, qty: 4, tag: ""}], extra: [1, 2]}, {cust: {active: "no", age: 0, tier: "zz"}, extra: [1, 2], flag: 0, items: [{price: 107, qty: 4, tag: ""}], price: 3}], + [{a: -1, price: 100, flag: false, items: [{price: true, qty: [1], tag: "zz"}, {price: 1000, qty: 1, tag: "Gold"}, {price: 19.99, qty: 19.99, tag: null}]}, {a: -1, flag: false, items: [{price: true, qty: [1], tag: "zz"}, {price: 1000, qty: 1, tag: "Gold"}, {price: 19.99, qty: 19.99, tag: null}], price: 100}], + [{cust: 5, a: "abc", price: true, flag: true, items: [{price: 1000, qty: null, tag: "zz"}, {price: 101, qty: 5, tag: "Gold"}]}, {a: "abc", cust: 5, flag: true, items: [{price: 1000, qty: null, tag: "zz"}, {price: 101, qty: 5, tag: "Gold"}], price: true}], + [{cust: "cust", a: null, flag: true, items: [{price: 0.5, qty: 7, tag: "gold "}, {price: 21, qty: 2, tag: "Gold"}]}, {cust: "cust", flag: true, items: [{price: 0.5, qty: 7, tag: "gold "}, {price: 21, qty: 2, tag: "Gold"}]}], + [{cust: null, a: 19.99, price: 99, flag: 0, items: [{price: 21, qty: 0.1, tag: "gold"}, {price: 7, qty: 50, tag: "silver"}]}, {a: 19.99, flag: 0, items: [{price: 21, qty: 0.1, tag: "gold"}, {price: 7, qty: 50, tag: "silver"}], price: 99}], + [{a: 27, price: 50, flag: true, items: [], extra: 1}, {a: 27, extra: 1, flag: true, items: [], price: 50}], + [{cust: {age: null, tier: "gold", active: true}, a: true, price: 21, flag: 1, items: [], extra: {deep: {x: 1}}}, {a: true, cust: {active: true, age: null, tier: "gold"}, extra: {deep: {x: 1}}, flag: 1, items: [], price: 21}], + [{cust: "cust", a: true, price: 100, flag: null, items: []}, {a: true, cust: "cust", items: [], price: 100}], + [{cust: {age: 101, tier: "zz", active: true}, price: {v: 1}, flag: true, items: []}, {cust: {active: true, age: 101, tier: "zz"}, flag: true, items: [], price: {v: 1}}], + [{cust: {age: 11, tier: "a", active: "true"}, a: 5, price: -1, flag: false, items: {price: 1}}, {a: 5, cust: {active: "true", age: 11, tier: "a"}, flag: false, items: {price: 1}, price: -1}], + [{cust: null, a: 99, price: 18, flag: true, items: [{price: 5, tag: null}]}, {a: 99, flag: true, items: [{price: 5, tag: null}], price: 18}], + [{cust: {age: 5, tier: 5, active: false}, a: "abc", flag: 0, items: [{price: 11, qty: 101, tag: 5}, {price: "abc", qty: 21, tag: "x"}, {price: 1, qty: "5", tag: "x"}]}, {a: "abc", cust: {active: false, age: 5, tier: 5}, flag: 0, items: [{price: 11, qty: 101, tag: 5}, {price: "abc", qty: 21, tag: "x"}, {price: 1, qty: "5", tag: "x"}]}], + [{cust: {age: 10, tier: "silver", active: false}, a: 99, price: true, flag: false, items: [{price: 5, tag: "gold"}]}, {a: 99, cust: {active: false, age: 10, tier: "silver"}, flag: false, items: [{price: 5, tag: "gold"}], price: true}], + [{cust: {age: -25, tier: "gold ", active: true}, a: 21, price: 18, flag: true, items: [{price: {v: 1}, qty: null, tag: "zz"}, {price: 101, qty: 7, tag: "gold "}]}, {a: 21, cust: {active: true, age: -25, tier: "gold "}, flag: true, items: [{price: {v: 1}, qty: null, tag: "zz"}, {price: 101, qty: 7, tag: "gold "}], price: 18}], + [{cust: {age: "5", tier: "", active: true}, a: -1, price: 3, flag: "no", items: [{price: 10, qty: 5, tag: ""}, {price: 50, qty: "5", tag: "silver"}, {price: 3, qty: "5", tag: "bronze"}], extra: [1, 2]}, {a: -1, cust: {active: true, age: "5", tier: ""}, extra: [1, 2], flag: "no", items: [{price: 10, qty: 5, tag: ""}, {price: 50, qty: "5", tag: "silver"}, {price: 3, qty: "5", tag: "bronze"}], price: 3}], + [{cust: {age: true, tier: "gold"}, a: null, price: 7, flag: false, items: [{price: 50, qty: "5", tag: "b"}, {price: 5, qty: 5, tag: "zz"}]}, {cust: {age: true, tier: "gold"}, flag: false, items: [{price: 50, qty: "5", tag: "b"}, {price: 5, qty: 5, tag: "zz"}], price: 7}], + [{cust: {age: 1000, tier: "bronze", active: true}, a: "abc", price: 10, flag: false, items: [{price: 99, qty: -25, tag: "a"}, {price: {v: 1}, qty: 100, tag: "a"}, {price: 99, qty: 19.99, tag: "bronze"}]}, {a: "abc", cust: {active: true, age: 1000, tier: "bronze"}, flag: false, items: [{price: 99, qty: -25, tag: "a"}, {price: {v: 1}, qty: 100, tag: "a"}, {price: 99, qty: 19.99, tag: "bronze"}], price: 10}], + [{cust: {age: 3, tier: "x", active: false}, a: 2, price: null, flag: false, items: [{price: 5, qty: 21, tag: "zz"}, {price: 10, qty: -25, tag: "silver"}, {price: 2.5, qty: "abc", tag: "silver"}]}, {a: 2, cust: {active: false, age: 3, tier: "x"}, flag: false, items: [{price: 5, qty: 21, tag: "zz"}, {price: 10, qty: -25, tag: "silver"}, {price: 2.5, qty: "abc", tag: "silver"}]}], + [{cust: {age: -25, tier: "zz", active: true}, a: -1, price: 0, flag: true, items: [{price: 2, qty: 5, tag: "silver"}]}, {a: -1, cust: {active: true, age: -25, tier: "zz"}, flag: true, items: [{price: 2, qty: 5, tag: "silver"}], price: 0}], + [{cust: "cust", a: null, price: true, flag: true}, {cust: "cust", flag: true, price: true}], + [{cust: {age: 99, tier: ["gold"], active: "no"}, a: true, price: true, flag: false, items: [{price: {v: 1}, qty: 3, tag: true}, {price: 19.99, qty: null, tag: true}, {price: 101, qty: 7, tag: "a"}, {qty: 19.99, tag: "a"}]}, {a: true, cust: {active: "no", age: 99, tier: ["gold"]}, flag: false, items: [{price: {v: 1}, qty: 3, tag: true}, {price: 19.99, qty: null, tag: true}, {price: 101, qty: 7, tag: "a"}, {qty: 19.99, tag: "a"}], price: true}], + [{cust: [], a: 5, price: 100, flag: "true", items: [{price: 21, tag: "a"}, {price: 11, qty: 11, tag: "zz"}, {price: 19.99, tag: ""}, {price: 0, qty: null, tag: true}]}, {a: 5, cust: [], flag: "true", items: [{price: 21, tag: "a"}, {price: 11, qty: 11, tag: "zz"}, {price: 19.99, tag: ""}, {price: 0, qty: null, tag: true}], price: 100}], + [{cust: [{age: 3}], a: 82, price: 21, flag: true, items: 3}, {a: 82, cust: [{age: 3}], flag: true, items: 3, price: 21}], + [{cust: 5, a: 1, price: 0.1, flag: "true", items: [{price: 0, qty: "abc", tag: "x"}]}, {a: 1, cust: 5, flag: "true", items: [{price: 0, qty: "abc", tag: "x"}], price: 0.1}], + [{cust: null, a: 5, price: 21, flag: 0, items: null}, {a: 5, flag: 0, price: 21}], + [{cust: {age: -1, tier: "Gold", active: false}, a: 7, price: null, flag: false, items: [{price: 3, qty: 1000, tag: "bronze"}]}, {a: 7, cust: {active: false, age: -1, tier: "Gold"}, flag: false, items: [{price: 3, qty: 1000, tag: "bronze"}]}], + ], +} + +{ + name: "gb006: 7 nodes, loop expr, switch, loop expr, expr, loop expr, table, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + "g.k77": "qty ?? tag", + }}, + {switch: "s2", when: ["(score) + (b ?? 0) >= (endsWith('x', 'x') ? (b ?? 1) * (score ?? -1) : len(items ?? []))", "lower(((items ?? [])[1].tag ?? '') + '!') != 'silver'", ""]}, + {expression: "e3", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "o.p", fields: { + k78: "ceil((price ?? 1))", + k79: "string((tag in ['gold', 'silver', 'a'] ? ($.k78 ?? -1) : 0 + ($.k78 ?? -1)))", + k80: "''", + }}, + {expression: "e4", fields: { + k81: "(b ?? b ?? 0)", + }}, + {expression: "e5", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k82: "false", + k83: "qty", + }}, + {table: "t6", inputs: ["k81", "`v${(k81 ?? 1)}-${'none'}`"], outputs: ["k84"], passThrough: true, outputPath: "out", rules: [ + [">= 5", "'x', 'bronze'", "0"], + ["[18..19]", "$ != 'gold'", "-5"], + ["21", "", "1"], + ["> 21", "not('gold')", "(k81 ?? 0) * ((true ? (k81 ?? 0) : (k81 ?? -1)))"], + ["", "", "len('x') + (k81 ?? 1) % 7 + (k81 ?? -1) * (k81 ?? 1)"], + ]}, + {expression: "e7", passThrough: true, fields: { + "m.k85": "(k81 ?? -1) % 7 + -(k81 + k81)", + k86: "k81", + "res.k87": "k81 ?? k81", + }}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "s2:0 -> e3", + "s2:0 -> e4", + "s2:1 -> e4", + "s2:1 -> e5", + "e4 -> t6", + "e4 -> e7", + "e1 -> output", + "e3 -> output", + "e5 -> output", + "t6 -> output", + "e7 -> output", + ], + }, + cases: [ + [{b: 10, vip: true, items: [{price: 18, qty: 21, tag: "a"}, {price: -0.1, qty: null, tag: "silver"}]}, {b: 10, items: [{price: 18, qty: 21, tag: "a"}, {price: -0.1, qty: null, tag: "silver"}], k81: 10, k86: 10, m: {k85: -17}, out: {k84: 104}, res: [{g: {k77: 21}, price: 18, qty: 21, tag: "a"}, {g: {k77: "silver"}, price: -0.1, qty: null, tag: "silver"}], vip: true}], + [{b: -1, vip: "no", score: 21, items: [{price: 0.5, qty: -0.1}, {qty: null, tag: "x"}, {price: null, qty: -1, tag: "gold "}]}, {b: -1, items: [{price: 0.5, qty: -0.1}, {qty: null, tag: "x"}, {price: null, qty: -1, tag: "gold "}], k81: -1, k86: -1, m: {k85: 1}, o: {p: [{k78: 1, k79: "1", k80: "", price: 0.5, qty: -0.1}, {k78: 1, k79: "1", k80: "", qty: null, tag: "x"}, {k78: 1, k79: "1", k80: "", price: null, qty: -1, tag: "gold "}]}, out: {k84: 1}, res: [{g: {k77: -0.1}, price: 0.5, qty: -0.1}, {g: {k77: "x"}, qty: null, tag: "x"}, {g: {k77: -1}, price: null, qty: -1, tag: "gold "}], score: 21, vip: "no"}], + [{vip: true, score: 5, items: [], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, items: [], k81: 0, k86: 0, m: {k85: -0}, o: {p: []}, out: {k84: 1}, res: [], score: 5, vip: true}], + [{b: 1, vip: true, score: 101, items: "items"}, "!error"], + [{vip: false, score: 0.1, items: [{price: 99, qty: 0.1, tag: "zz"}, {price: true, qty: 2.5, tag: "Gold"}, {qty: 3, tag: ""}, {price: 1000, qty: -0.1, tag: null}]}, "!error"], + [{b: 1000000000000000000000, score: 19.99, items: [{price: 19.99, qty: 1000000000000000000000, tag: "silver"}, {price: null, qty: 99, tag: ""}]}, {b: 1000000000000000000000, items: [{price: 19.99, qty: 1000000000000000000000, tag: "silver"}, {price: null, qty: 99, tag: ""}], k81: 1000000000000000000000, k86: 1000000000000000000000, m: {k85: -1999999999999999999994}, res: [{g: {k77: 1000000000000000000000}, price: 19.99, qty: 1000000000000000000000, tag: "silver"}, {g: {k77: 99}, price: null, qty: 99, tag: ""}], score: 19.99}], + [{b: 5, vip: true, items: [{price: 1, qty: 50, tag: ""}, {price: 0.5, qty: 18, tag: "Gold"}]}, {b: 5, items: [{price: 1, qty: 50, tag: ""}, {price: 0.5, qty: 18, tag: "Gold"}], k81: 5, k86: 5, m: {k85: -5}, out: {k84: 31}, res: [{g: {k77: 50}, price: 1, qty: 50, tag: ""}, {g: {k77: 18}, price: 0.5, qty: 18, tag: "Gold"}], vip: true}], + [{vip: true, score: null, items: [{price: 18, qty: null, tag: "silver"}, {price: -0.1, qty: -25, tag: "gold "}, {price: 10, qty: 1, tag: "b"}, {price: 19.99, qty: 14, tag: "a"}]}, {items: [{price: 18, qty: null, tag: "silver"}, {price: -0.1, qty: -25, tag: "gold "}, {price: 10, qty: 1, tag: "b"}, {price: 19.99, qty: 14, tag: "a"}], k81: 0, k86: 0, m: {k85: -0}, out: {k84: 1}, res: [{g: {k77: "silver"}, price: 18, qty: null, tag: "silver"}, {g: {k77: -25}, price: -0.1, qty: -25, tag: "gold "}, {g: {k77: 1}, price: 10, qty: 1, tag: "b"}, {g: {k77: 14}, price: 19.99, qty: 14, tag: "a"}], vip: true}], + [{b: null, score: 99, items: [{qty: 7, tag: "gold"}, {price: 1000000000000000000000, tag: "Gold"}]}, {items: [{qty: 7, tag: "gold"}, {price: 1000000000000000000000, tag: "Gold"}], k81: 0, k86: 0, m: {k85: -0}, o: {p: [{k78: 1, k79: "1", k80: "", qty: 7, tag: "gold"}, {k78: 1000000000000000000000, k79: "1000000000000000000000", k80: "", price: 1000000000000000000000, tag: "Gold"}]}, out: {k84: 1}, res: [{g: {k77: 7}, qty: 7, tag: "gold"}, {g: {k77: "Gold"}, price: 1000000000000000000000, tag: "Gold"}], score: 99}], + [{b: null, score: 1000, items: [{price: 1000000000000000000000, qty: 99, tag: "gold "}, {price: 50, qty: -12, tag: "a"}]}, {items: [{price: 1000000000000000000000, qty: 99, tag: "gold "}, {price: 50, qty: -12, tag: "a"}], k81: 0, k86: 0, m: {k85: -0}, o: {p: [{k78: 1000000000000000000000, k79: "1000000000000000000000", k80: "", price: 1000000000000000000000, qty: 99, tag: "gold "}, {k78: 50, k79: "50", k80: "", price: 50, qty: -12, tag: "a"}]}, out: {k84: 1}, res: [{g: {k77: 99}, price: 1000000000000000000000, qty: 99, tag: "gold "}, {g: {k77: -12}, price: 50, qty: -12, tag: "a"}], score: 1000}], + [{b: 2, vip: false, score: 100, items: [], extra: [1, 2]}, {b: 2, extra: [1, 2], items: [], k81: 2, k86: 2, m: {k85: -2}, out: {k84: 7}, res: [], score: 100, vip: false}], + [{b: 0.1, vip: true, score: 101, items: [{price: 10, qty: 50, tag: "silver"}, {price: 5, qty: null, tag: "x"}, {price: -25, qty: -0.1, tag: ["gold"]}, {price: 1000000000000000000000, qty: 1000000000000000000000, tag: "x"}]}, "!error"], + [{b: 21, score: 101, items: [{price: -25, qty: 2.5, tag: "gold "}], extra: {deep: {x: 1}}}, {b: 21, extra: {deep: {x: 1}}, items: [{price: -25, qty: 2.5, tag: "gold "}], k81: 21, k86: 21, m: {k85: -42}, out: {k84: 1}, res: [{g: {k77: 2.5}, price: -25, qty: 2.5, tag: "gold "}], score: 101}], + [{b: -25, vip: null, score: 101, items: [{price: 0.5, qty: 99, tag: "Gold"}, {price: 101, qty: null, tag: null}]}, {b: -25, items: [{price: 0.5, qty: 99, tag: "Gold"}, {price: 101, qty: null, tag: null}], k81: -25, k86: -25, m: {k85: 46}, o: {p: [{k78: 1, k79: "1", k80: "", price: 0.5, qty: 99, tag: "Gold"}, {k78: 101, k79: "101", k80: "", price: 101, qty: null, tag: null}]}, out: {k84: 622}, res: [{g: {k77: 99}, price: 0.5, qty: 99, tag: "Gold"}, {g: {k77: null}, price: 101, qty: null, tag: null}], score: 101}], + [{b: -0.1, vip: false, score: -0.1, items: [{price: 1000, qty: -25, tag: "b"}], extra: 1}, {b: -0.1, extra: 1, items: [{price: 1000, qty: -25, tag: "b"}], k81: -0.1, k86: -0.1, m: {k85: 0.1}, out: {k84: 0.91}, res: [{g: {k77: -25}, price: 1000, qty: -25, tag: "b"}], score: -0.1, vip: false}], + [{b: 2, vip: false, score: 18, items: [{price: 0.1, qty: -25, tag: "x"}, {price: 11, qty: 1000, tag: ""}, {qty: 100, tag: "gold"}]}, {b: 2, items: [{price: 0.1, qty: -25, tag: "x"}, {price: 11, qty: 1000, tag: ""}, {qty: 100, tag: "gold"}], k81: 2, k86: 2, m: {k85: -2}, out: {k84: 7}, res: [{g: {k77: -25}, price: 0.1, qty: -25, tag: "x"}, {g: {k77: 1000}, price: 11, qty: 1000, tag: ""}, {g: {k77: 100}, qty: 100, tag: "gold"}], score: 18, vip: false}], + [{b: 19.99, score: -0.1, items: [{price: null, qty: 100, tag: "a"}, {price: 11, qty: 7, tag: "Gold"}]}, {b: 19.99, items: [{price: null, qty: 100, tag: "a"}, {price: 11, qty: 7, tag: "Gold"}], k81: 19.99, k86: 19.99, m: {k85: -33.99}, o: {p: [{k78: 1, k79: "1", k80: "", price: null, qty: 100, tag: "a"}, {k78: 11, k79: "11", k80: "", price: 11, qty: 7, tag: "Gold"}]}, out: {k84: 406.5901}, res: [{g: {k77: 100}, price: null, qty: 100, tag: "a"}, {g: {k77: 7}, price: 11, qty: 7, tag: "Gold"}], score: -0.1}], + [{b: 1, vip: false, score: 0, items: [{price: 3, qty: 2, tag: "silver"}, {price: 2, qty: null, tag: "b"}, {price: 2.5, qty: -25, tag: null}]}, {b: 1, items: [{price: 3, qty: 2, tag: "silver"}, {price: 2, qty: null, tag: "b"}, {price: 2.5, qty: -25, tag: null}], k81: 1, k86: 1, m: {k85: -1}, o: {p: [{k78: 3, k79: "3", k80: "", price: 3, qty: 2, tag: "silver"}, {k78: 2, k79: "2", k80: "", price: 2, qty: null, tag: "b"}, {k78: 3, k79: "3", k80: "", price: 2.5, qty: -25, tag: null}]}, out: {k84: 3}, res: [{g: {k77: 2}, price: 3, qty: 2, tag: "silver"}, {g: {k77: "b"}, price: 2, qty: null, tag: "b"}, {g: {k77: -25}, price: 2.5, qty: -25, tag: null}], score: 0, vip: false}], + [{b: 0, vip: true, score: 10, items: [{price: -1, qty: 99, tag: "Gold"}, {price: 2.5, qty: 10, tag: "x"}, {price: 100, qty: 11, tag: "b"}]}, {b: 0, items: [{price: -1, qty: 99, tag: "Gold"}, {price: 2.5, qty: 10, tag: "x"}, {price: 100, qty: 11, tag: "b"}], k81: 0, k86: 0, m: {k85: -0}, o: {p: [{k78: -1, k79: "-1", k80: "", price: -1, qty: 99, tag: "Gold"}, {k78: 3, k79: "3", k80: "", price: 2.5, qty: 10, tag: "x"}, {k78: 100, k79: "100", k80: "", price: 100, qty: 11, tag: "b"}]}, out: {k84: 1}, res: [{g: {k77: 99}, price: -1, qty: 99, tag: "Gold"}, {g: {k77: 10}, price: 2.5, qty: 10, tag: "x"}, {g: {k77: 11}, price: 100, qty: 11, tag: "b"}], score: 10, vip: true}], + ], +} + +{ + name: "gb007: 11 nodes, loop expr, switch, switch, loop table*, switch, switch*, expr, expr, switch, expr, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k88: "false", + }}, + {switch: "s2", when: ["true"]}, + {switch: "s3", when: ["not ((n != null) or ((code ?? 'none') == ''))", "contains(string(startsWith(code, 'g')), 'x')", ""]}, + {table: "t4", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["string((price ?? 0))"], outputs: ["g.k89", "k90"], outputPath: "lines", rules: [ + ["", "true", "-4 * max([(qty ?? 1), 2.25]) - ((qty ?? 0)) + ((price ?? 1))"], + ["'x'", "a == null", "10"], + ["'a', 'b'", "false", "0"], + ["", "false", "-5"], + ]}, + {switch: "s5", when: ["not ((n in [1..100]) or (not (false)))", "(((n ?? 1)) / 2) / 10 != (100 * (n ?? -1)) / 4", ""]}, + {switch: "s6", hit: "collect", when: ["code != null", "(((n ?? -1))) >= len(lower(((items ?? [])[1].tag ?? '') + '!'))", ""]}, + {expression: "e7", fields: { + "g.k89": "n ?? n", + k92: "flag ?? flag", + k93: "n ?? flag", + k94: "ceil((n ?? -1)) * -((n ?? -1))", + }}, + {expression: "e8", outputPath: "res", fields: { + k95: "-(abs(max([-4, (n ?? 0)])))", + k96: "(n ?? 1) + (-4) + 1", + k97: "(n ?? 1)", + }}, + {switch: "s9", when: ["false", "sum(map(items ?? [], #.price ?? 0)) in [-5..5]", ""]}, + {expression: "e10", passThrough: true, outputPath: "lines", fields: { + k98: "null", + k99: "upper('')", + k100: "(100) * 2", + }}, + {expression: "e11", fields: { + k101: "flag ?? n", + k102: "(flag ? (n ?? -1) : -4) * 3 - n != ((n ?? 0) - n)", + }}, + ], + edges: [ + "input -> e1", + "input -> s2", + "input -> s3", + "e1 -> s3", + "s3:2 -> t4", + "s3:1 -> t4", + "s3:2 -> s5", + "s5:0 -> s6", + "s6:2 -> e7", + "s2:0 -> e8", + "t4 -> e8", + "s6:2 -> s9", + "t4 -> e10", + "s9:0 -> e11", + "s5:1 -> output", + "s6:0 -> output", + "e7 -> output", + "e8 -> output", + "s9:1 -> output", + "s9:2 -> output", + "e10 -> output", + "e11 -> output", + ], + }, + cases: [ + [{code: null, items: [{price: -0.1, qty: 0, tag: "zz"}, {price: 1000, qty: 2, tag: "Gold"}], flag: true, n: 11, tier: "Gold"}, {flag: true, items: [{price: -0.1, qty: 0, tag: "zz"}, {price: 1000, qty: 2, tag: "Gold"}], lines: {k100: 200, k98: null, k99: ""}, n: 11, res: [{k88: false, price: -0.1, qty: 0, tag: "zz"}, {k88: false, price: 1000, qty: 2, tag: "Gold"}], tier: "Gold"}], + [{code: "b", items: [{price: -0.1, qty: 10, tag: "bronze"}, {price: -25, qty: 0, tag: {t: "x"}}, {price: -1, qty: 7, tag: "silver"}], flag: true, n: 11, tier: null, extra: 1}, {code: "b", extra: 1, flag: true, items: [{price: -0.1, qty: 10, tag: "bronze"}, {price: -25, qty: 0, tag: {t: "x"}}, {price: -1, qty: 7, tag: "silver"}], lines: {k100: 200, k98: null, k99: ""}, n: 11, res: [{k88: false, price: -0.1, qty: 10, tag: "bronze"}, {k88: false, price: -25, qty: 0, tag: {t: "x"}}, {k88: false, price: -1, qty: 7, tag: "silver"}]}], + [{items: [{price: 21, qty: 3, tag: "zz"}, {price: 11, qty: 99, tag: "gold "}], flag: false, n: {v: 1}, tier: "x", extra: 1}, "!error"], + [{items: [{price: 2.5, qty: 99, tag: "silver"}, {price: 0.1, tag: "a"}], flag: false, n: [1], tier: "bronze", extra: "e"}, "!error"], + [{code: "zz", items: [{price: {v: 1}, qty: 5, tag: null}, {price: 2, qty: 18, tag: "zz"}, {price: 0.1, tag: "a"}, {price: null, qty: 3, tag: true}], flag: 0, n: [1], tier: "silver"}, "!error"], + [{code: true, items: [{price: 5, qty: null, tag: "gold "}], flag: null, n: 5, tier: null}, {code: true, items: [{price: 5, qty: null, tag: "gold "}], lines: {k100: 200, k98: null, k99: ""}, n: 5, res: [{k88: false, price: 5, qty: null, tag: "gold "}]}], + [{code: "Gold", items: [], flag: true, tier: "silver"}, {res: {k95: -0, k96: -2, k97: 1}}], + [{code: ["gold"], items: [{price: 11, qty: -1, tag: "silver"}, {price: 0, qty: 0, tag: "zz"}, {price: -1, qty: -1, tag: ""}, {price: 0.1, tag: "bronze"}], flag: false, n: 18, tier: "zz"}, {code: ["gold"], flag: false, items: [{price: 11, qty: -1, tag: "silver"}, {price: 0, qty: 0, tag: "zz"}, {price: -1, qty: -1, tag: ""}, {price: 0.1, tag: "bronze"}], lines: {k100: 200, k98: null, k99: ""}, n: 18, res: [{k88: false, price: 11, qty: -1, tag: "silver"}, {k88: false, price: 0, qty: 0, tag: "zz"}, {k88: false, price: -1, qty: -1, tag: ""}, {k88: false, price: 0.1, tag: "bronze"}], tier: "zz"}], + [{code: "zz", items: [{price: -1, qty: 18, tag: "x"}, {price: 1000000000000000000000, qty: 1000000000000000000000, tag: "zz"}, {price: 11, qty: null, tag: "x"}, {price: 3, qty: 1000, tag: "Gold"}], flag: false, n: null, tier: "x"}, {res: {k95: -0, k96: -2, k97: 1}}], + [{code: "gold", items: [{price: 100, qty: 5, tag: "x"}], flag: true, n: 2.5, tier: "bronze"}, {code: "gold", flag: true, items: [{price: 100, qty: 5, tag: "x"}], lines: {k100: 200, k98: null, k99: ""}, n: 2.5, res: [{k88: false, price: 100, qty: 5, tag: "x"}], tier: "bronze"}], + [{items: [{qty: 1000000000000000000000, tag: "bronze"}, {price: 2.5, qty: 50, tag: "Gold"}, {price: -0.1, qty: 18, tag: "silver"}, {price: -25, qty: 1000000000000000000000, tag: "zz"}], flag: true, n: 1000, tier: "bronze"}, {flag: true, items: [{qty: 1000000000000000000000, tag: "bronze"}, {price: 2.5, qty: 50, tag: "Gold"}, {price: -0.1, qty: 18, tag: "silver"}, {price: -25, qty: 1000000000000000000000, tag: "zz"}], lines: {k100: 200, k98: null, k99: ""}, n: 1000, res: [{k88: false, qty: 1000000000000000000000, tag: "bronze"}, {k88: false, price: 2.5, qty: 50, tag: "Gold"}, {k88: false, price: -0.1, qty: 18, tag: "silver"}, {k88: false, price: -25, qty: 1000000000000000000000, tag: "zz"}], tier: "bronze"}], + [{code: "zz", items: [{price: 0.5, qty: 2, tag: ""}, {qty: 11, tag: "gold "}, {price: 21, qty: 1000000000000000000000, tag: "b"}], n: 2, tier: null}, {code: "zz", items: [{price: 0.5, qty: 2, tag: ""}, {qty: 11, tag: "gold "}, {price: 21, qty: 1000000000000000000000, tag: "b"}], lines: {k100: 200, k98: null, k99: ""}, n: 2, res: [{k88: false, price: 0.5, qty: 2, tag: ""}, {k88: false, qty: 11, tag: "gold "}, {k88: false, price: 21, qty: 1000000000000000000000, tag: "b"}]}], + [{code: "gold ", items: [{price: 50, qty: 5, tag: "silver"}], flag: false, n: 7, tier: 5}, {code: "gold ", flag: false, items: [{price: 50, qty: 5, tag: "silver"}], lines: {k100: 200, k98: null, k99: ""}, n: 7, res: [{k88: false, price: 50, qty: 5, tag: "silver"}], tier: 5}], + [{code: null, items: [{price: 18, qty: 2.5, tag: null}, {price: 18, qty: 10, tag: "gold"}, {price: -25, tag: "bronze"}, {price: null, qty: 1000, tag: null}], n: 5, tier: "zz"}, {items: [{price: 18, qty: 2.5, tag: null}, {price: 18, qty: 10, tag: "gold"}, {price: -25, tag: "bronze"}, {price: null, qty: 1000, tag: null}], lines: {k100: 200, k98: null, k99: ""}, n: 5, res: [{k88: false, price: 18, qty: 2.5, tag: null}, {k88: false, price: 18, qty: 10, tag: "gold"}, {k88: false, price: -25, tag: "bronze"}, {k88: false, price: null, qty: 1000, tag: null}], tier: "zz"}], + [{code: "a", items: [{price: 0.1, qty: 1, tag: "zz"}, {price: 0.5, qty: null, tag: "gold "}], flag: false, n: 2.5, tier: "bronze"}, {code: "a", flag: false, items: [{price: 0.1, qty: 1, tag: "zz"}, {price: 0.5, qty: null, tag: "gold "}], lines: {k100: 200, k98: null, k99: ""}, n: 2.5, res: [{k88: false, price: 0.1, qty: 1, tag: "zz"}, {k88: false, price: 0.5, qty: null, tag: "gold "}], tier: "bronze"}], + [{items: [{price: 5, qty: 3, tag: "bronze"}, {price: 2.5, qty: null, tag: "zz"}], flag: false, n: 99, tier: null}, {flag: false, items: [{price: 5, qty: 3, tag: "bronze"}, {price: 2.5, qty: null, tag: "zz"}], lines: {k100: 200, k98: null, k99: ""}, n: 99, res: [{k88: false, price: 5, qty: 3, tag: "bronze"}, {k88: false, price: 2.5, qty: null, tag: "zz"}]}], + [{code: "b", items: [{price: 11, qty: 99, tag: "gold "}, {price: 1000000000000000000000, qty: 21, tag: ""}], flag: true, n: 100, tier: "", extra: "e"}, {code: "b", extra: "e", flag: true, items: [{price: 11, qty: 99, tag: "gold "}, {price: 1000000000000000000000, qty: 21, tag: ""}], lines: {k100: 200, k98: null, k99: ""}, n: 100, res: [{k88: false, price: 11, qty: 99, tag: "gold "}, {k88: false, price: 1000000000000000000000, qty: 21, tag: ""}], tier: ""}], + [{code: "bronze", items: [], n: 11, tier: "Gold"}, {code: "bronze", items: [], lines: {k100: 200, k98: null, k99: ""}, n: 11, res: [], tier: "Gold"}], + [{code: "zz", items: [], flag: false, n: 5, tier: "gold", extra: 1}, {code: "zz", extra: 1, flag: false, items: [], lines: {k100: 200, k98: null, k99: ""}, n: 5, res: [], tier: "gold"}], + [{code: "bronze", items: [{price: 3, qty: 11, tag: "a"}, {price: 2, qty: 19.99, tag: "gold "}], flag: true, n: 2, tier: "b", extra: 1}, {code: "bronze", extra: 1, flag: true, items: [{price: 3, qty: 11, tag: "a"}, {price: 2, qty: 19.99, tag: "gold "}], lines: {k100: 200, k98: null, k99: ""}, n: 2, res: [{k88: false, price: 3, qty: 11, tag: "a"}, {k88: false, price: 2, qty: 19.99, tag: "gold "}], tier: "b"}], + [{code: "", items: [{price: 1, qty: 0.5, tag: "bronze"}, {price: 0.5, qty: 1000, tag: ""}, {price: 10, qty: 99, tag: "Gold"}], flag: true, n: -25, tier: "bronze", extra: {deep: {x: 1}}}, {code: "", extra: {deep: {x: 1}}, flag: true, items: [{price: 1, qty: 0.5, tag: "bronze"}, {price: 0.5, qty: 1000, tag: ""}, {price: 10, qty: 99, tag: "Gold"}], lines: {k100: 200, k98: null, k99: ""}, n: -25, res: [{k88: false, price: 1, qty: 0.5, tag: "bronze"}, {k88: false, price: 0.5, qty: 1000, tag: ""}, {k88: false, price: 10, qty: 99, tag: "Gold"}], tier: "bronze"}], + ], +} + +{ + name: "gb008: 7 nodes, table*, switch*, switch, switch*, expr, expr, table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputField: "cust", inputs: ["active"], outputs: ["k103"], passThrough: true, outputPath: "out", rules: [ + ["$ == true", "string((-4)) in ['gold', 'silver', 'a']"], + ["false", "true"], + ["$ == true", "true"], + ["false", "(active ?? false)"], + ]}, + {switch: "s2", hit: "collect", when: ["a == null", "false", "false"]}, + {switch: "s3", when: ["(-((price ?? -1)) >= (price ?? 0))", "true"]}, + {switch: "s4", hit: "collect", when: ["((false) and ('none' != 'gold')) or (cust.active)", ""]}, + {expression: "e5", inputField: "cust", passThrough: true, fields: { + k104: "(age ?? 1)", + "res.k105": "`v${age}-${(tier ?? '?')}`", + }}, + {expression: "e6", fields: { + k106: "(not (a == null) ? 'x' : `n=${(price ?? -1)}-${(cust.tier ?? '?')}`)", + }}, + {table: "t7", inputField: "cust", inputs: ["age"], outputs: ["k106", "k106"], passThrough: true, rules: [ + ["> 0", "''", "false"], + ["5", "'gold'", "(((active ?? false) ? 'gold' : (tier ?? '')) == 'silver') or (not ((active ?? false)))"], + ["(1..6)", "string(-((age ?? 0)))", "true"], + [">= 50", "'high'", "-(-4 * (age ?? 0)) in [1..100]"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> s2", + "input -> s2", + "s2:1 -> s3", + "s2:2 -> s4", + "s2:1 -> s4", + "s4:0 -> e5", + "s4:1 -> e5", + "e5 -> e6", + "s4:0 -> e6", + "e6 -> t7", + "s2:2 -> t7", + "s3:0 -> output", + "s3:1 -> output", + "t7 -> output", + ], + }, + cases: [ + [{items: [{price: 1000, qty: -25}, {price: 1, qty: 2, tag: "gold "}, {price: -0.1, qty: 0.1}, {price: 21, qty: 0.5, tag: null}], cust: {age: 18, tier: "gold ", active: false}, price: 0.1}, {}], + [{items: [{price: 101, qty: -0.1, tag: "zz"}, {price: 7, qty: -0.1, tag: "b"}], cust: {age: 2.5, tier: "x", active: false}, price: null}, {}], + [{items: [{price: -25, qty: 7, tag: "gold"}, {price: null, qty: 0, tag: "zz"}], cust: {age: 1000, tier: "bronze", active: true}, price: 11}, {}], + [{items: [{price: 101, qty: 101, tag: "silver"}], cust: {age: null, tier: "b", active: false}, price: -1}, {}], + [{items: [], cust: {age: 101, tier: "silver", active: false}, price: 10}, {}], + [{items: [{price: 0.5, qty: 101, tag: null}, {price: 0.5, qty: 3}], cust: {age: 0, tier: "a", active: true}, price: 2, extra: [1, 2]}, {}], + [{items: [{price: null, qty: 5, tag: "silver"}, {price: 5, qty: 11, tag: "b"}], cust: {age: 0.5, tier: "b"}, price: null}, {}], + [{items: [{price: null, tag: null}, {price: 101, qty: 0.5, tag: "gold"}], cust: null, price: 21}, {}], + [{items: [], price: 0}, {}], + [{items: [], price: 11}, {}], + [{items: [{price: 5, qty: 0.1, tag: "gold "}, {price: 1000000000000000000000, qty: null, tag: "zz"}, {price: null, qty: 21}], cust: {age: [1], tier: "a"}, price: 1}, {}], + [{items: [{qty: -0.1}], cust: {age: 0.5, tier: "Gold", active: true}, price: 7}, {}], + [{cust: {age: 97, tier: "silver", active: null}, price: null, extra: [1, 2]}, {}], + [{items: [{price: -25, qty: 100, tag: "x"}, {price: 100, qty: 3, tag: "x"}], cust: {age: -0.1, tier: "", active: false}, price: 0, extra: [1, 2]}, {}], + [{items: [], cust: {age: 5, tier: "bronze", active: true}, price: 1, extra: "e"}, {}], + [{items: [{price: 11, qty: 99}, {price: 1, qty: 1, tag: "gold"}, {price: -0.1, qty: 50, tag: "bronze"}], price: 0.5}, {}], + [{items: [{price: 101, qty: 100, tag: "Gold"}], cust: {age: 11, tier: "gold ", active: false}, price: -25}, {}], + [{items: [], price: 1}, {}], + [{items: [], cust: {age: 3, tier: null, active: true}, price: 101}, {}], + [{items: [{price: 2, qty: 0.5, tag: null}, {price: 101, qty: 101, tag: "Gold"}, {price: 101, qty: 1, tag: ""}], cust: {age: 1, tier: ""}, price: -25, extra: "e"}, {}], + [{items: [{price: -0.1, qty: 1000000000000000000000, tag: "gold"}, {price: 3, qty: 2.5, tag: "zz"}], cust: {age: 2.5, tier: "gold ", active: false}, price: 21}, {}], + [{items: [{price: 3, qty: null, tag: "b"}, {price: null, qty: -1, tag: "gold "}, {price: 1000, qty: 1, tag: null}], cust: {age: 2.5, tier: "a", active: false}, price: 21}, {}], + [{items: [{price: 2, qty: 11, tag: "a"}, {price: 7, qty: -0.1, tag: "a"}, {price: 19.99, qty: 2.5, tag: "silver"}, {price: 19.99, qty: 0, tag: "Gold"}], cust: {age: 50, tier: "zz", active: true}, price: 99}, {}], + ], +} + +{ + name: "gb009: 11 nodes, expr, table*, expr, table, loop expr, switch, loop expr, table, expr, table, table", + graph: { + nodes: [ + {expression: "e1", outputPath: "out", fields: { + k109: "((score ?? -1) + ((score ?? -1)))", + k110: "round(-((score ?? 1)) * score)", + }}, + {table: "t2", hit: "collect", inputField: "cust", inputs: ["active", "((active ?? false) ? (age ?? age ?? 0) : (age ?? -1))", "active"], outputs: ["res.k111", "k112"], passThrough: true, rules: [ + ["true", "", "", "len((tier ?? '')) + floor((age ?? -1)) <= ceil(10)", "true"], + ["", "[1..6]", "true", "(len((tier ?? 'none'))) / 0.5 == 0", "false"], + ["null", "(21..31)", "true", "true", "true"], + ["false", "1, 11", "true", "(tier ?? '?') != ''", "true"], + ]}, + {expression: "e3", inputField: "cust", passThrough: true, fields: { + k113: "age * 1 * age * -((age ?? -1))", + k114: "(0)", + }}, + {table: "t4", inputs: ["string(not (false))"], outputs: ["k115"], passThrough: true, rules: [ + ["startsWith($, 'a')", "2"], + ["startsWith($, 'g')", "10"], + ["startsWith($, 'a')", "100"], + ["", "100"], + ["", "((score ?? -1) + (score ?? 1)) * max([(2) / 3, (score ?? 1) - (score ?? 0)])"], + ]}, + {expression: "e5", inputField: "items", executionMode: "loop", outputPath: "o.p", fields: { + k109: "qty ?? tag", + }}, + {switch: "s6", when: ["(true) or (true)", "`v${100}-${s}` + '-' + lower(((items ?? [])[1].tag ?? '') + '!') in ['gold', 'silver', 'a']", "endsWith(string(1), '')", ""]}, + {expression: "e7", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k117: "(ceil(((price ?? 1)) / 10)) / 10", + }}, + {table: "t8", inputs: ["floor((score ?? -1)) % 3", "`${(score ?? 1)}-${(s ?? '')}`"], outputs: ["k113", "k119"], outputPath: "res", rules: [ + ["< 18", "", "'low'", "0.25"], + ["$ > 0 and $ < 10", "not('gold')", "''", "-5"], + ["not(10)", "null", "'gold'", "1"], + ["50", "not('a')", "'gold'", "0"], + ["null", "startsWith($, '')", "string(trim((s ?? '?')) == '')", "(score ?? -1) * (false ? 0.5 : -4) * ((1))"], + ["", "null", "'low'", "10"], + ["", "", "''", "10"], + ]}, + {expression: "e9", inputField: "cust", fields: { + k120: "tier ?? active", + k121: "(active ?? false)", + k122: "((($.k121 ?? false)) and (((active ?? false)))) and (string(false) in ['gold', 'silver', 'a'])", + }}, + {table: "t10", inputs: ["k121", null], outputs: ["g.k123"], outputPath: "res", rules: [ + ["null", "'gold'", "10"], + ["$ == true", "'gold'", "-5"], + ["null", "", "10"], + ["$ == true", "null", "100"], + ["", "5", "10"], + ["null", "5", "(0 ?? k120 ?? 0)"], + ["", "", "-5"], + ]}, + {table: "t11", inputs: ["res.g.k123", "res.g.k123", null], outputs: ["k124", "k125"], passThrough: true, rules: [ + ["< 100", ">= 1", "null", "string(10)", "true"], + ["$ > 100 and $ < 105", "", "5", "''", "false"], + ["> 100", "not(21)", "5", "string(startsWith('none', 'a'))", "true"], + ]}, + ], + edges: [ + "input -> e1", + "input -> t2", + "t2 -> e3", + "input -> t4", + "t2 -> e5", + "t2 -> s6", + "e3 -> e7", + "s6:3 -> t8", + "e7 -> e9", + "t2 -> e9", + "e9 -> t10", + "t10 -> t11", + "e1 -> output", + "t4 -> output", + "e5 -> output", + "s6:2 -> output", + "t8 -> output", + "e9 -> output", + "t11 -> output", + ], + }, + cases: [ + [{items: [{price: 10, qty: 0.5, tag: "gold "}, {qty: 10, tag: null}, {price: 3, qty: 19.99, tag: "Gold"}], score: 18, s: "silver", cust: {age: 0.5, tier: "bronze", active: false}}, "!error"], + [{items: [{qty: 2.5, tag: "gold"}, {price: null, qty: 2, tag: "zz"}, {price: 21, qty: 101, tag: "bronze"}, {price: 0, qty: -25, tag: "zz"}], score: 19.99, s: "bronze", cust: {age: -1, tier: "silver", active: true}}, "!error"], + [{items: [], score: 21, s: "b"}, "!error"], + [{items: [{price: 7, qty: 101, tag: "x"}, {price: 18, qty: 0.1, tag: "zz"}, {price: null, qty: 5, tag: "gold"}, {price: 11, qty: 99, tag: "x"}], score: 0.5, s: "", cust: {age: 0.5, tier: null, active: false}}, "!error"], + [{items: [{price: 1, qty: 1000000000000000000000, tag: ""}, {price: 0, qty: 113, tag: "a"}], cust: {age: null, tier: "bronze", active: true}}, "!error"], + [{items: [], score: 18, s: null, cust: {age: 0.1, tier: "", active: true}}, "!error"], + [{items: [{price: 10, qty: 10, tag: ""}], cust: {age: 19.99, active: true}}, "!error"], + [{items: [{price: 50, qty: 0.1, tag: "silver"}, {price: 1, qty: 5, tag: "x"}], score: 0.1, s: "silver", cust: {age: 2, tier: "a", active: false}}, "!error"], + [{items: null, score: 11, s: "x", cust: {age: 99, tier: "bronze", active: true}}, "!error"], + [{items: [], score: 50, s: "silver", cust: {age: 0.1, tier: "zz", active: true}, extra: 1}, "!error"], + [{items: [{price: 1000000000000000000000, qty: 100, tag: "a"}, {price: 100, qty: 50, tag: "a"}, {price: 0.1, qty: 0, tag: null}], score: 1000, s: "", cust: {age: 101, tier: "Gold", active: false}, extra: [1, 2]}, "!error"], + [{items: [{price: 1000, qty: null, tag: "bronze"}, {price: 7, qty: 78, tag: "bronze"}], score: 0, s: "gold", cust: {age: 1000000000000000000000, tier: "a", active: false}}, "!error"], + [{score: 3, s: null, cust: {age: 11, tier: "zz", active: true}}, "!error"], + [{items: [{price: 0, qty: 0.5, tag: "zz"}, {price: 5, tag: "gold "}, {qty: 1000000000000000000000, tag: "b"}, {price: 1000, qty: 21, tag: ""}], score: 0.1, s: "", cust: {age: 10, tier: "bronze", active: true}}, "!error"], + [{items: [{price: 11, qty: 100, tag: "zz"}, {qty: 1, tag: "silver"}, {price: 50, qty: 50, tag: "Gold"}], score: 10, s: "b"}, "!error"], + [{items: [{price: -1, qty: 1000000000000000000000, tag: ""}, {price: -1, qty: 1, tag: "a"}], score: -0.1, s: "zz", cust: {age: 3, tier: "gold", active: true}, extra: "e"}, "!error"], + [{items: [{price: 100, qty: 2, tag: "bronze"}, {price: 2.5, qty: 2.5, tag: "a"}], score: null, s: "b", cust: {age: 11, tier: null, active: false}}, "!error"], + [{items: [{price: 2, qty: 1000000000000000000000, tag: null}, {qty: null, tag: "gold"}, {price: 2.5, qty: 18, tag: "zz"}, {price: 101, qty: 1000, tag: null}], score: 3, cust: null}, "!error"], + ], +} + +{ + name: "gb010: 12 nodes, loop table, table, expr, table*, switch*, switch, switch, table*, switch, switch*, expr, table*", + graph: { + nodes: [ + {table: "t1", inputField: "items", executionMode: "loop", inputs: ["tag", "price", "price", null], outputs: ["res.k126"], outputPath: "res", rules: [ + ["'gold', 'b'", "[18..28)", "$ > 5 and $ < 10", "true", "false"], + ["null", "", "", "", "false"], + ]}, + {table: "t2", inputs: ["s", "b", "b"], outputs: ["k127"], outputPath: "res", rules: [ + ["'gold'", "", "100", "'gold'"], + ["'silver', 'gold'", "$ > 5 and $ < 55", ">= 5", "'mid'"], + ["'a'", "not(5)", "<= 15", "(s ?? '') + '-' + ''"], + ["startsWith($, 'x')", "> 21", "", "(s ?? 'none')"], + ["", "> 50", "[21..71]", "''"], + ["", "0, 50", "(-1..0)", "'gold'"], + ["", "", "", "''"], + ]}, + {expression: "e3", fields: { + "m.k128": "n ?? b", + "m.k129": "n != null", + k130: "'' != 'silver'", + }}, + {table: "t4", hit: "collect", inputs: ["len((m.k129 ? 'A-1' : ''))", "k130", "m.k129"], outputs: ["k131"], passThrough: true, outputPath: "lines", rules: [ + ["", "false", "null", "'high'"], + ["(5..55)", "true", "", "'mid'"], + ["100, 101", "$ == true", "false", "''"], + ["[18..19)", "true", "", "'mid'"], + ["", "", "", "''"], + ]}, + {switch: "s5", hit: "collect", when: ["not (floor(-4) in [-5..5])", "(100 % 2) > (1 * 0)", "(10) in [1..100]", ""]}, + {switch: "s6", when: ["string(-4 + 2) == 'gold'", "((not (false)) or (not ((k130 ?? false)))) and (endsWith(`n=${0.5}-${''}`, 'g'))", "false"]}, + {switch: "s7", when: ["min([(true ? 3 : 100), max([0, 10])]) > 1"]}, + {table: "t8", hit: "collect", inputs: ["k130"], outputs: ["k132", "k133"], passThrough: true, rules: [ + ["true", "''", "1"], + ["null", "''", "0.25"], + ["", "'A-1'", "2"], + ["null", "''", "0.25"], + ["false", "'gold'", "1"], + ["", "string('gold' + '' + '' == '')", "-5"], + ]}, + {switch: "s9", when: ["(m.k129 ?? false)", "(k130 ?? false)", ""]}, + {switch: "s10", hit: "collect", when: ["true", ""]}, + {expression: "e11", outputPath: "out", fields: { + "res.k134": "'x'", + "g.k135": "k130 ?? m.k129", + k136: "-(2.25) + -4 in [0..10]", + }}, + {table: "t12", hit: "collect", inputs: ["string('none' != 'silver')", "0.5 + -(100)", "k130"], outputs: ["k133"], passThrough: true, outputPath: "lines", rules: [ + ["not('silver')", "< -1", "$ == true", "true"], + ["startsWith($, '')", "[10..15]", "null", "true"], + ["not('gold')", "10, 20", "$ == true", "'gold' in ['gold', 'silver', 'a']"], + ["", "18", "false", "true"], + ["'silver'", "", "", "true"], + ["'', 'bronze'", "", "$ == true", "not (`n=${2.25}-${'none'}` in ['gold', 'silver', 'a'])"], + ["", "", "", "true"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> t2", + "input -> t2", + "input -> e3", + "t2 -> e3", + "t1 -> t4", + "e3 -> t4", + "e3 -> s5", + "s5:0 -> s6", + "s5:3 -> s7", + "t4 -> s7", + "s6:0 -> t8", + "t8 -> s9", + "s9:0 -> s10", + "s9:1 -> s10", + "s10:0 -> e11", + "s10:0 -> t12", + "s6:1 -> output", + "s6:2 -> output", + "s7:0 -> output", + "s10:1 -> output", + "e11 -> output", + "t12 -> output", + ], + }, + cases: [ + [{nums: null, score: "abc", items: [{price: 1000000000000000000000, tag: "zz"}, {price: 7, qty: 19.99, tag: null}], b: 1000, s: "b", n: 11}, {k130: true, lines: [{k131: ""}], m: {k128: 11, k129: true}, res: [null, {res: {k126: false}}]}], + [{nums: [5, 2.5, 1000], score: 99, items: [{price: 99, tag: "bronze"}, {price: 0, qty: 101, tag: "a"}], b: -25, s: "Gold", n: 10, extra: "e"}, {k130: true, lines: [{k131: ""}], m: {k128: 10, k129: true}, res: [null, null]}], + [{nums: "1,2", score: 116, items: [{price: 101, qty: null, tag: "bronze"}, {price: -1, qty: -0.1, tag: "gold"}, {price: 8, qty: 0.1, tag: ""}], b: 19.99}, {k130: true, lines: [{k131: ""}], m: {k128: 19.99, k129: false}, res: [null, null, null]}], + [{nums: [18, 3], score: 0, items: [], b: 7, s: "b", n: 99}, {k130: true, lines: [{k131: ""}], m: {k128: 99, k129: true}, res: []}], + [{nums: null, score: 101, items: "items", b: 0.1, n: 7, extra: "e"}, "!error"], + [{nums: [10], score: "abc", items: null, b: 100, s: "gold", n: 7}, "!error"], + [{nums: [19.99, 0, 3, 7, 10], score: null, items: [], b: 7, s: "silver", n: 19.99}, {k130: true, lines: [{k131: ""}], m: {k128: 19.99, k129: true}, res: []}], + [{score: -1, items: [{price: 1000000000000000000000, qty: 7, tag: "bronze"}], b: 100, s: "Gold", n: null}, {k130: true, lines: [{k131: ""}], m: {k128: 100, k129: false}, res: [null]}], + [{nums: [99, -25], score: null, items: "items", b: 10, s: "silver", n: 3}, "!error"], + [{nums: null, score: 10, items: [{price: 3, qty: -1, tag: "silver"}], b: 10, s: "", n: 1}, {k130: true, lines: [{k131: ""}], m: {k128: 1, k129: true}, res: [null]}], + [{nums: [-0.1, 2.5, 18, 10, 2.5], score: -25, items: [{price: 0.5, qty: 0.5, tag: null}, {price: 7, qty: 101, tag: "silver"}], s: "x", n: 7}, {k130: true, lines: [{k131: ""}], m: {k128: 7, k129: true}, res: [{res: {k126: false}}, null]}], + [{nums: null, score: 0, items: {price: 1}, b: 100, s: null}, "!error"], + [{nums: null, score: 1000, items: [{price: 7, qty: 3, tag: "Gold"}, {price: 2, qty: 3, tag: null}, {price: 19.99, qty: 101, tag: "Gold"}, {price: -0.1, qty: 1}], b: -0.1, s: "silver", n: 1000}, {k130: true, lines: [{k131: ""}], m: {k128: 1000, k129: true}, res: [null, {res: {k126: false}}, null, {res: {k126: false}}]}], + [{nums: ["1", 2], score: 18, items: [{price: 1000, qty: 99, tag: "gold "}, {price: 101, qty: true, tag: "x"}], b: -1, s: "zz", n: 21}, {k130: true, lines: [{k131: ""}], m: {k128: 21, k129: true}, res: [null, null]}], + [{nums: [50], score: -0.1, items: [{price: 11, qty: 100, tag: "b"}], b: 1000000000000000000000, s: ["gold"], n: 11}, {k130: true, lines: [{k131: ""}], m: {k128: 11, k129: true}, res: [null]}], + ], +} + +{ + name: "gb011: 6 nodes, switch, table*, expr, table*, switch, loop table", + graph: { + nodes: [ + {switch: "s1", when: ["(flag ?? false)", "10 + 10 - 0 + 2 in [0..10]", ""]}, + {table: "t2", hit: "collect", inputs: ["flag"], outputs: ["k138", "m.k139"], passThrough: true, outputPath: "lines", rules: [ + ["", "true", "'gold'"], + ["null", "true", "s"], + ]}, + {expression: "e3", fields: { + k140: "((((flag ?? false)) ? 1 + 2.25 : 2 - 3))", + "res.k141": "max([(true ? ($.k140 ?? $.k140 ?? 0) : ceil(3)), (0.5 - -4)])", + }}, + {table: "t4", hit: "collect", inputs: ["(code ?? '') + ' ' + code + ' ' + code", "min([len('gold'), max([3, 0])])", "flag"], outputs: ["k142[]", "m.k143"], outputPath: "res", rules: [ + ["''", "> 50", "null", "true", "(0.5 + 2 != len('x')) or ((flag ?? false))"], + ["", "[-1..49]", "null", "sum(map(items ?? [], #.price ?? 0)) != 0.5", "true"], + ["not('gold')", "[5..6)", "true", "true", "true"], + ["", "", "", "true", "(0.5 * 2 >= 1) or ((false) and (3 == 1))"], + ]}, + {switch: "s5", when: ["(flag ?? false)", "true", "0 <= len(((flag ?? false) ? '' : ''))", ""]}, + {table: "t6", inputField: "items", executionMode: "loop", inputs: ["`n=${3}-${'none'}`", "((price)) / 2"], outputs: ["k144"], outputPath: "lines", rules: [ + ["startsWith($, 'x')", ">= 21", "0"], + ["'gold'", "", "100"], + ["startsWith($, 'g')", "", "0"], + ["startsWith($, 's')", "", "10"], + ["'silver', 'bronze'", "[21..71]", "0.25"], + ["'silver', 'bronze'", "<= 11", "-5"], + ["", "", "0"], + ]}, + ], + edges: [ + "input -> s1", + "input -> t2", + "s1:1 -> e3", + "s1:2 -> t4", + "s1:2 -> s5", + "t4 -> s5", + "s5:3 -> t6", + "s1:0 -> output", + "t2 -> output", + "e3 -> output", + "t4 -> output", + "s5:0 -> output", + "s5:2 -> output", + "t6 -> output", + ], + }, + cases: [ + [{flag: 0, code: "silver", s: "", items: [{price: -1, qty: 0.1, tag: "silver"}, {price: 99, qty: 58, tag: ""}, {price: -25, qty: 1000, tag: "zz"}, {price: 1000, qty: -1, tag: "b"}]}, {code: "silver", flag: 0, items: [{price: -1, qty: 0.1, tag: "silver"}, {price: 99, qty: 58, tag: ""}, {price: -25, qty: 1000, tag: "zz"}, {price: 1000, qty: -1, tag: "b"}], lines: [{k138: true, m: {k139: "gold"}}], res: [{k142: true, m: {k143: true}}], s: ""}], + [{flag: false, s: "a", items: [{price: 50, qty: 2.5, tag: ""}, {price: 5, qty: 11, tag: "x"}]}, {flag: false, items: [{price: 50, qty: 2.5, tag: ""}, {price: 5, qty: 11, tag: "x"}], lines: [{k138: true, m: {k139: "gold"}}], res: [{k142: true, m: {k143: true}}], s: "a"}], + [{flag: null, code: "bronze", s: "x", items: [{price: 7, qty: 3, tag: "gold "}, {price: 1000, qty: 5, tag: {t: "x"}}]}, {code: "bronze", items: [{price: 7, qty: 3, tag: "gold "}, {price: 1000, qty: 5, tag: {t: "x"}}], lines: [{k138: true, m: {k139: "gold"}}, {k138: true, m: {k139: "x"}}], res: [{k142: true, m: {k143: true}}, {k142: true, m: {k143: true}}], s: "x"}], + [{code: "gold ", s: "Gold", items: [{price: 21, qty: null, tag: "b"}], extra: "e"}, {code: "gold ", extra: "e", items: [{price: 21, qty: null, tag: "b"}], lines: [{k138: true, m: {k139: "gold"}}, {k138: true, m: {k139: "Gold"}}], res: [{k142: true, m: {k143: true}}, {k142: true, m: {k143: true}}], s: "Gold"}], + [{flag: true, code: "", s: "bronze", items: [{price: -25, qty: 21, tag: "x"}, {qty: 0.5, tag: "x"}, {qty: -25, tag: "bronze"}]}, {code: "", flag: true, items: [{price: -25, qty: 21, tag: "x"}, {qty: 0.5, tag: "x"}, {qty: -25, tag: "bronze"}], lines: [{k138: true, m: {k139: "gold"}}], s: "bronze"}], + [{flag: false, code: "gold ", s: "a", items: [{price: -25, qty: 119, tag: null}, {price: 1000000000000000000000, tag: "gold "}, {price: 0.5, qty: 1000, tag: "a"}, {price: 1, qty: 1000000000000000000000, tag: "Gold"}]}, {code: "gold ", flag: false, items: [{price: -25, qty: 119, tag: null}, {price: 1000000000000000000000, tag: "gold "}, {price: 0.5, qty: 1000, tag: "a"}, {price: 1, qty: 1000000000000000000000, tag: "Gold"}], lines: [{k138: true, m: {k139: "gold"}}], res: [{k142: true, m: {k143: true}}], s: "a"}], + [{flag: true, code: "b", s: "silver", items: [{qty: -1, tag: "zz"}, {price: 2, qty: -1, tag: "silver"}, {price: -1, qty: 0, tag: "a"}]}, {code: "b", flag: true, items: [{qty: -1, tag: "zz"}, {price: 2, qty: -1, tag: "silver"}, {price: -1, qty: 0, tag: "a"}], lines: [{k138: true, m: {k139: "gold"}}], s: "silver"}], + [{flag: false, code: "a", s: "", items: [{price: -25, qty: [1], tag: "gold"}]}, {code: "a", flag: false, items: [{price: -25, qty: [1], tag: "gold"}], lines: [{k138: true, m: {k139: "gold"}}], res: [{k142: true, m: {k143: true}}], s: ""}], + [{code: "x", s: ["gold"], items: [{price: 2.5, qty: 101, tag: "bronze"}, {price: 101, qty: null, tag: null}, {price: 2, qty: -25, tag: ["gold"]}]}, {code: "x", items: [{price: 2.5, qty: 101, tag: "bronze"}, {price: 101, qty: null, tag: null}, {price: 2, qty: -25, tag: ["gold"]}], lines: [{k138: true, m: {k139: "gold"}}, {k138: true, m: {k139: ["gold"]}}], res: [{k142: true, m: {k143: true}}, {k142: true, m: {k143: true}}], s: ["gold"]}], + [{flag: true, code: "zz", items: [{price: null, qty: 2, tag: "zz"}, {price: 0.1, qty: true, tag: null}]}, {code: "zz", flag: true, items: [{price: null, qty: 2, tag: "zz"}, {price: 0.1, qty: true, tag: null}], lines: [{k138: true, m: {k139: "gold"}}]}], + [{flag: null, s: "gold ", items: []}, {items: [], lines: [{k138: true, m: {k139: "gold"}}, {k138: true, m: {k139: "gold "}}], res: [{k142: true, m: {k143: true}}, {k142: true, m: {k143: true}}], s: "gold "}], + [{flag: false, code: "x", s: "gold", items: [{price: -25, qty: 7, tag: "zz"}]}, {code: "x", flag: false, items: [{price: -25, qty: 7, tag: "zz"}], lines: [{k138: true, m: {k139: "gold"}}], res: [{k142: true, m: {k143: true}}], s: "gold"}], + [{flag: false, code: "x", s: null, items: [{price: 50, qty: null, tag: "Gold"}, {price: 11, qty: 2, tag: "bronze"}, {price: 100, qty: -1, tag: "b"}, {price: 99, tag: "zz"}]}, {code: "x", flag: false, items: [{price: 50, qty: null, tag: "Gold"}, {price: 11, qty: 2, tag: "bronze"}, {price: 100, qty: -1, tag: "b"}, {price: 99, tag: "zz"}], lines: [{k138: true, m: {k139: "gold"}}], res: [{k142: true, m: {k143: true}}]}], + ], +} + +{ + name: "gb012: 8 nodes, loop table*, loop expr, loop table, switch, table*, switch*, table, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["tag"], outputs: ["k145[]", "m.k146"], passThrough: true, outputPath: "out", rules: [ + ["", "false", "''"], + ["null", "false", "(tag ?? '?')"], + ["''", "(false ? (price ?? 1) : (qty ?? 1)) + -4 + (price ?? -1) >= 10", "'mid'"], + ["not('gold')", "endsWith((tag ?? ''), 'a')", "'gold'"], + ["startsWith($, '')", "false", "'high'"], + ["startsWith($, 'a')", "(price ?? 1) == 10 + (qty ?? 0) % 2", "'mid'"], + ["", "false", "string((qty ?? -1))"], + ]}, + {expression: "e2", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + k147: "((not (true)) or ((false) or (true))) or (-4 in [1..100])", + }}, + {table: "t3", inputField: "items", executionMode: "loop", inputs: ["len(tag) + 0"], outputs: ["k148", "res.k149"], outputPath: "res", rules: [ + ["10", "'mid'", "(tag ?? '?')"], + ["50", "'gold'", "'low'"], + ["!= 5", "string(false)", "'low'"], + ["18, 68", "'mid'", "'high'"], + ["null", "'low'", "'high'"], + ["> 18", "'mid'", "string((qty ?? 1) * (price ?? 0) != (qty ?? 0) * (price ?? 0))"], + ["", "string((price + (price ?? 1)))", "'mid'"], + ]}, + {switch: "s4", when: ["true", "(false)", "string(-4) == 'silver'", ""]}, + {table: "t5", hit: "collect", inputs: ["-((0 ?? 1 ?? 0))", "'none'", "(endsWith('', 'a') ? 'gold' : lower(''))"], outputs: ["k150[]"], outputPath: "res", rules: [ + ["$ > 1 and $ < 11", "'gold'", "startsWith($, 'x')", "'low'"], + [">= 18", "", "'gold', 'bronze'", "'mid'"], + ["> 18", "not('')", "'silver'", "'low'"], + ["not(18)", "not('silver')", "'x', 'bronze'", "'high'"], + ]}, + {switch: "s6", hit: "collect", when: ["((flag != null) or ((false))) and (b * 2 <= 100)"]}, + {table: "t7", inputField: "cust", inputs: ["active", "age"], outputs: ["k151"], passThrough: true, outputPath: "lines", rules: [ + ["false", "<= 71", "false"], + ["null", "", "false"], + ["", "", "false"], + ]}, + {expression: "e8", passThrough: true, fields: { + "g.k152": "flag ?? s", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "input -> t3", + "e2 -> s4", + "s4:3 -> t5", + "s4:0 -> t5", + "input -> s6", + "t5 -> t7", + "s6:0 -> t7", + "t7 -> e8", + "t1 -> output", + "t3 -> output", + "s4:2 -> output", + "e8 -> output", + ], + }, + cases: [ + [{items: [], b: -0.1, s: "bronze", flag: null, cust: {tier: "", active: false}}, {b: -0.1, cust: {active: false, tier: ""}, g: {k152: null}, items: [], lines: {k151: false}, out: [], res: [], s: "bronze"}], + [{items: [{price: -0.1, qty: 10, tag: "x"}, {price: 21, qty: 0, tag: "a"}, {price: null, qty: 10, tag: "b"}, {price: 18, qty: null, tag: "bronze"}], b: 1, s: "", cust: {age: 1, tier: null, active: false}, vip: false}, {b: 1, cust: {active: false, age: 1, tier: null}, g: {k152: null}, items: [{price: -0.1, qty: 10, tag: "x"}, {price: 21, qty: 0, tag: "a"}, {price: null, qty: 10, tag: "b"}, {price: 18, qty: null, tag: "bronze"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "10"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "mid"}}, {k145: false, m: {k146: "0"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "10"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "-1"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}], s: "", vip: false}], + [{items: [], b: 3, s: "gold ", flag: true, cust: {age: null, tier: "zz", active: true}, vip: false}, {b: 3, cust: {active: true, age: null, tier: "zz"}, flag: true, g: {k152: true}, items: [], lines: {k151: false}, out: [], res: [], s: "gold ", vip: false}], + [{items: [{price: 101, qty: 64, tag: "silver"}, {price: 100, qty: 1, tag: "gold "}], b: 0.5, s: "silver", flag: null, cust: {age: 99, tier: "gold", active: false}, vip: false, extra: [1, 2]}, {b: 0.5, cust: {active: false, age: 99, tier: "gold"}, extra: [1, 2], g: {k152: null}, items: [{price: 101, qty: 64, tag: "silver"}, {price: 100, qty: 1, tag: "gold "}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "64"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "1"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "200", res: {k149: "mid"}}], s: "silver", vip: false}], + [{items: [{price: 3, qty: 101, tag: "gold"}, {price: 1000000000000000000000, qty: -25, tag: "x"}, {price: 99, qty: 1000000000000000000000}], b: 11, s: "bronze", flag: true, cust: {age: 100, tier: "x", active: true}, vip: true}, {b: 11, cust: {active: true, age: 100, tier: "x"}, flag: true, g: {k152: true}, items: [{price: 3, qty: 101, tag: "gold"}, {price: 1000000000000000000000, qty: -25, tag: "x"}, {price: 99, qty: 1000000000000000000000}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "101"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "-25"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "?"}}, {k145: false, m: {k146: "1000000000000000000000"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}, {k148: "198", res: {k149: "mid"}}], s: "bronze", vip: true}], + [{items: [{price: 0.5, qty: 19.99, tag: null}], b: 52, s: "gold ", cust: {age: 2.5, tier: "silver", active: false}, vip: false}, {b: 52, cust: {active: false, age: 2.5, tier: "silver"}, g: {k152: null}, items: [{price: 0.5, qty: 19.99, tag: null}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "?"}}, {k145: false, m: {k146: "19.99"}}]], res: [{k148: "1.0", res: {k149: "mid"}}], s: "gold ", vip: false}], + [{items: [{price: 5, qty: -25, tag: "a"}, {price: 0, qty: 100, tag: null}, {price: 99, qty: 62, tag: "b"}, {price: -25, qty: 1000, tag: "Gold"}], b: 0.1, flag: true, cust: null, vip: true}, {b: 0.1, flag: true, g: {k152: true}, items: [{price: 5, qty: -25, tag: "a"}, {price: 0, qty: 100, tag: null}, {price: 99, qty: 62, tag: "b"}, {price: -25, qty: 1000, tag: "Gold"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "mid"}}, {k145: false, m: {k146: "-25"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "?"}}, {k145: false, m: {k146: "100"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "62"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "1000"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "0", res: {k149: "mid"}}, {k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}], vip: true}], + [{items: [], b: 50, s: "", flag: null, vip: false}, {b: 50, g: {k152: null}, items: [], lines: {k151: false}, out: [], res: [], s: "", vip: false}], + [{items: [{price: 2, qty: -25, tag: "gold "}, {price: 50, qty: 7, tag: "a"}, {price: 0, tag: "bronze"}], b: 2.5, s: "", flag: false, vip: false}, {b: 2.5, flag: false, g: {k152: false}, items: [{price: 2, qty: -25, tag: "gold "}, {price: 50, qty: 7, tag: "a"}, {price: 0, tag: "bronze"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "-25"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "mid"}}, {k145: false, m: {k146: "7"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "-1"}}]], res: [{k148: "4", res: {k149: "mid"}}, {k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}], s: "", vip: false}], + [{items: [{price: -25, qty: 7, tag: "bronze"}, {price: 100, qty: 10, tag: "x"}], b: 11, s: "gold ", flag: false, cust: {age: 2, tier: "a", active: true}, extra: [1, 2]}, {b: 11, cust: {active: true, age: 2, tier: "a"}, extra: [1, 2], flag: false, g: {k152: false}, items: [{price: -25, qty: 7, tag: "bronze"}, {price: 100, qty: 10, tag: "x"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "7"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "10"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}], s: "gold "}], + [{items: [{price: 0.5, qty: 3, tag: "Gold"}, {price: 2, qty: 2, tag: "x"}], b: 7, s: "b", flag: false, cust: {age: 32, tier: "x", active: false}, vip: false}, {b: 7, cust: {active: false, age: 32, tier: "x"}, flag: false, g: {k152: false}, items: [{price: 0.5, qty: 3, tag: "Gold"}, {price: 2, qty: 2, tag: "x"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "3"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "2"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}], s: "b", vip: false}], + [{items: [{price: 0, qty: 101, tag: "silver"}, {price: 101, qty: 0, tag: "x"}], b: 2, s: "silver", flag: false, cust: {age: -0.1, tier: "a", active: true}, vip: false, extra: "e"}, {b: 2, cust: {active: true, age: -0.1, tier: "a"}, extra: "e", flag: false, g: {k152: false}, items: [{price: 0, qty: 101, tag: "silver"}, {price: 101, qty: 0, tag: "x"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "101"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "0"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}], s: "silver", vip: false}], + [{items: [{price: 0.5, qty: 11, tag: "bronze"}, {price: 101, qty: 2.5}, {price: 0, qty: 1000000000000000000000, tag: "Gold"}, {price: -1, qty: 100}], b: 101, s: "x", flag: null, cust: null, vip: true}, {b: 101, g: {k152: null}, items: [{price: 0.5, qty: 11, tag: "bronze"}, {price: 101, qty: 2.5}, {price: 0, qty: 1000000000000000000000, tag: "Gold"}, {price: -1, qty: 100}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "11"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "?"}}, {k145: false, m: {k146: "2.5"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "1000000000000000000000"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "?"}}, {k145: false, m: {k146: "100"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "202", res: {k149: "mid"}}, {k148: "false", res: {k149: "low"}}, {k148: "-2", res: {k149: "mid"}}], s: "x", vip: true}], + [{items: [{price: 18, qty: null, tag: "silver"}, {price: 69, qty: 1000000000000000000000, tag: "gold "}, {price: null, qty: 1, tag: "silver"}, {price: 1000000000000000000000, qty: 21, tag: "silver"}], b: 2, s: "zz", flag: true, cust: {age: 21, tier: "Gold", active: true}, vip: true}, {b: 2, cust: {active: true, age: 21, tier: "Gold"}, flag: true, g: {k152: true}, items: [{price: 18, qty: null, tag: "silver"}, {price: 69, qty: 1000000000000000000000, tag: "gold "}, {price: null, qty: 1, tag: "silver"}, {price: 1000000000000000000000, qty: 21, tag: "silver"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "-1"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "1000000000000000000000"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "1"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "21"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "138", res: {k149: "mid"}}, {k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}], s: "zz", vip: true}], + [{items: [], b: 2, flag: true, cust: {age: -25, tier: "a", active: false}, vip: null}, {b: 2, cust: {active: false, age: -25, tier: "a"}, flag: true, g: {k152: true}, items: [], lines: {k151: false}, out: [], res: []}], + [{items: [{price: 0.1, qty: 2.5, tag: "b"}, {price: -0.1, qty: 101, tag: "gold "}], s: "b", flag: true, cust: {tier: "a", active: true}, vip: null}, {cust: {active: true, tier: "a"}, flag: true, g: {k152: null}, items: [{price: 0.1, qty: 2.5, tag: "b"}, {price: -0.1, qty: 101, tag: "gold "}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "2.5"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "101"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "-0.2", res: {k149: "mid"}}], s: "b"}], + [{items: [{price: -1, qty: 1, tag: ""}, {price: 99, qty: 2, tag: "gold"}], b: 10, flag: true, cust: null, vip: false}, {b: 10, flag: true, g: {k152: true}, items: [{price: -1, qty: 1, tag: ""}, {price: 99, qty: 2, tag: "gold"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "mid"}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "1"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "2"}}]], res: [{k148: "false", res: {k149: "low"}}, {k148: "false", res: {k149: "low"}}], vip: false}], + [{items: [{price: 101, qty: 1}, {price: 10, qty: 10, tag: "silver"}], b: 87, s: "b", flag: null, cust: {age: 7, tier: "gold"}, vip: null}, {b: 87, cust: {age: 7, tier: "gold"}, g: {k152: null}, items: [{price: 101, qty: 1}, {price: 10, qty: 10, tag: "silver"}], lines: {k151: false}, out: [[{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "?"}}, {k145: false, m: {k146: "1"}}], [{k145: false, m: {k146: ""}}, {k145: false, m: {k146: "high"}}, {k145: false, m: {k146: "10"}}]], res: [{k148: "202", res: {k149: "mid"}}, {k148: "false", res: {k149: "low"}}], s: "b"}], + ], +} + +{ + name: "gb013: 11 nodes, expr, loop table, switch, switch, expr, switch, expr, loop table*, expr, expr, table", + graph: { + nodes: [ + {expression: "e1", fields: { + k153: "b", + }}, + {table: "t2", inputField: "items", executionMode: "loop", inputs: ["3 * (price ?? 0) % 2", "price", "'none'"], outputs: ["k154", "g.k155"], outputPath: "o.p", rules: [ + ["$ > 5 and $ < 55", "not(1)", "not('silver')", "false", "'mid'"], + ["[50..55)", "<= 28", "null", "false", "'mid'"], + ["$ > 50 and $ < 51", "(-1..4)", "", "true", "(not ((price ?? 1) > price) ? `v${(qty ?? 1)}-${'A-1'}` : string(a == null))"], + ["< 50", "!= 10", "null", "true", "''"], + ]}, + {switch: "s3", when: ["abs((k153 ?? -1) * (k153 ?? -1)) in [1..100]", ""]}, + {switch: "s4", when: ["flag != null", "round(((k153 ?? 0)) / 2) in [1..100]"]}, + {expression: "e5", fields: { + k156: "-((b ?? 0) * 0.5 * 100)", + }}, + {switch: "s6", when: ["(b ?? -1) % 2 > (b > (k153 ?? -1) ? max([1, (b ?? 1)]) : min([(k153 ?? -1), (b ?? 0)]))", "((flag ?? false))", ""]}, + {expression: "e7", passThrough: true, outputPath: "lines", fields: { + k157: "(k153 ?? k153 ?? 0)", + k158: "flag ?? code", + k159: "((true ? 100 : (k153 ?? -1)) < k153) or (('' != 'gold') and (true))", + }}, + {table: "t8", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["qty"], outputs: ["k160"], passThrough: true, outputPath: "res", rules: [ + ["[100..110)", "2"], + ["> 50", "0.25"], + ["< 18", "0"], + ["", "0.25"], + ]}, + {expression: "e9", outputPath: "res", fields: { + "m.k161": "(lines.k157 ?? -1)", + }}, + {expression: "e10", outputPath: "o.p", fields: { + k162: "abs((k153 ?? -1) * 100)", + }}, + {table: "t11", inputs: ["res.m.k161", "((res.m.k161 ?? 0)) / 4"], outputs: ["k163"], outputPath: "lines", rules: [ + ["< 18", "!= 10", "((res.m.k161 ?? 1)) % 2"], + ["< 18", "< 21", "2"], + ["", "!= 21", "100"], + ["[5..10]", "< -1", "100"], + ["(10..60)", "", "0.25"], + ]}, + ], + edges: [ + "input -> e1", + "input -> t2", + "e1 -> s3", + "input -> s3", + "s3:0 -> s4", + "s4:0 -> e5", + "e5 -> s6", + "s3:1 -> s6", + "s3:0 -> e7", + "s6:2 -> t8", + "e7 -> e9", + "e1 -> e10", + "e9 -> t11", + "t2 -> output", + "s4:1 -> output", + "s6:0 -> output", + "t8 -> output", + "e10 -> output", + "t11 -> output", + ], + }, + cases: [ + [{b: 7, flag: false, code: 5, nums: [9, 2.5, 100], items: []}, "!error"], + [{b: 101, flag: true, code: "b", nums: [18], items: [{price: 101, qty: 1000, tag: "a"}, {price: 1000000000000000000000, qty: 1, tag: "gold "}]}, {o: {p: [null, null]}}], + [{flag: false, code: "", nums: [21, 50, 84], items: [{price: 50, tag: "silver"}, {price: "5", qty: 2.5, tag: "gold "}]}, "!error"], + [{b: 1, flag: 1, nums: ["1", 2], items: [{price: 99, qty: 1, tag: "a"}, {price: 2.5, qty: 104, tag: "zz"}, {price: 10, qty: 118, tag: "a"}, {price: null, tag: "Gold"}], extra: [1, 2]}, "!error"], + [{b: 100, flag: true, code: null, nums: [5, 10], items: [{price: null, qty: 0.1, tag: "silver"}]}, {o: {p: [null]}}], + [{b: 18, flag: true, code: "Gold", nums: [10, 1000, 7, -1, 0.1], items: []}, {o: {p: []}}], + [{b: {v: 1}, flag: "no", code: "a", nums: [0.5, 1, 21, 18, 3], items: [{price: {v: 1}, qty: 2}, {price: 21, qty: 0.1, tag: "gold"}, {price: -1, qty: 2, tag: null}, {price: 0.5, qty: 1, tag: "a"}]}, "!error"], + [{b: -25, code: "gold", nums: [18, -0.1, 101, 2, 29], items: [{price: 0.5, qty: 99, tag: "b"}, {price: 119, qty: null, tag: "bronze"}]}, {b: -25, code: "gold", items: [{price: 0.5, qty: 99, tag: "b"}, {price: 119, qty: null, tag: "bronze"}], k153: -25, nums: [18, -0.1, 101, 2, 29], o: {p: [null, null]}}], + [{b: 0.1, flag: "true", code: null, nums: null, items: null}, "!error"], + [{b: -25, flag: 0, code: null, items: [{price: 7, qty: 10, tag: "zz"}, {price: -1, qty: -1, tag: "a"}, {price: 1, qty: 10, tag: "zz"}, {price: -0.1, tag: null}]}, {b: -25, flag: 0, items: [{price: 7, qty: 10, tag: "zz"}, {price: -1, qty: -1, tag: "a"}, {price: 1, qty: 10, tag: "zz"}, {price: -0.1, tag: null}], k153: -25, o: {p: [null, null, null, null]}}], + [{b: -1, flag: true, code: "silver", nums: [1000000000000000000000], items: [{price: 99, qty: true, tag: "gold "}, {price: 100, qty: 99, tag: ""}, {price: null, qty: 7, tag: true}, {price: 1000000000000000000000, qty: null, tag: 5}]}, "!error"], + [{b: "abc", flag: true, code: "silver", nums: [], items: []}, "!error"], + [{b: 119, flag: true, nums: null, items: [{price: 0.5, qty: 0, tag: "gold "}, {price: 5, qty: "5", tag: null}], extra: [1, 2]}, {o: {p: [null, null]}}], + [{b: 1000, flag: true, code: "Gold", nums: [19.99], items: "items"}, "!error"], + ], +} + +{ + name: "gb014: 9 nodes, expr, switch, table*, expr, table*, expr, table, expr, table", + graph: { + nodes: [ + {expression: "e1", outputPath: "out", fields: { + k164: "(flag ?? false)", + k165: "(flag) and (((price ?? 0) in [1..100]) or (-4 != 0))", + k166: "cust.age", + }}, + {switch: "s2", when: ["((out.k165 ?? false))", "len(`n=${out.k166}-${'gold'}`) > 0 * len('x')", ""]}, + {table: "t3", hit: "collect", inputs: ["out.k166", "out.k165"], outputs: ["k167"], passThrough: true, outputPath: "res", rules: [ + ["", "", "true"], + ["not(50)", "$ == true", "(true) and (((out.k166 ?? -1) in [0..10]) or ('gold' in ['gold', 'silver', 'a']))"], + ["< -1", "", "true"], + ["> 21", "true", "false"], + ]}, + {expression: "e4", fields: { + "res.k168": "max([out.k166, 0.5]) - len('A-1') - (round((out.k166 ?? -1)))", + k169: "(out.k166 == null ? 0 : (3)) in [1..100]", + }}, + {table: "t5", hit: "collect", inputs: ["b", "out.k166", "b"], outputs: ["k170"], passThrough: true, outputPath: "lines", rules: [ + ["5", "", "", "'none'"], + ["<= 101", "1, 6", "> 1", "''"], + ["5, 10", "$ > 100 and $ < 105", "$ > 1 and $ < 2", "''"], + ["null", "[1..11]", "<= 10", "'gold'"], + ["[18..23)", "[0..50]", "[21..71]", "'high'"], + ]}, + {expression: "e6", passThrough: true, fields: { + k171: "(endsWith(string((out.k164 ?? false)), '') ? (cust.tier != null ? '' : `${price}-${'none'}`) : upper('gold' + ':' + 'x'))", + }}, + {table: "t7", inputs: ["(0.5) + len('')", "res.k168"], outputs: ["res.k172", "k173"], rules: [ + [">= 1", "> 18", "false", "100"], + ["> 100", "", "false", "100"], + ["(5..15)", "[100..110]", "(k169 ?? false)", "0.25"], + ["$ > 50 and $ < 55", "not(18)", "true", "-5"], + ["[50..55]", "50", "true", "((res.k168 ?? 0) % 3) / 0.5"], + ["", "", "true", "(0.5)"], + ]}, + {expression: "e8", passThrough: true, fields: { + k174: "(out.k166 ?? -1)", + k175: "len('A-1')", + k176: "100 * out.k166", + k177: "((out.k166 ?? out.k166 ?? 0) * 100)", + }}, + {table: "t9", inputs: ["k173"], outputs: ["k178"], rules: [ + ["$ > 50 and $ < 100", "false"], + ["<= 1", "false"], + ["> 10", "res.k172 == null"], + ["", "(((res.k172 ?? false)))"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "s2:2 -> t3", + "s2:1 -> e4", + "s2:1 -> t5", + "input -> t5", + "t5 -> e6", + "t3 -> e6", + "e4 -> t7", + "t3 -> e8", + "t7 -> t9", + "s2:0 -> output", + "e6 -> output", + "e8 -> output", + "t9 -> output", + ], + }, + cases: [ + [{items: [{price: [1], qty: -0.1, tag: "bronze"}, {price: 0.5, qty: 3, tag: "bronze"}], price: null, b: 0.1, cust: {age: 36, tier: "gold ", active: true}, flag: false}, {b: 0.1, cust: {active: true, age: 36, tier: "gold "}, flag: false, items: [{price: [1], qty: -0.1, tag: "bronze"}, {price: 0.5, qty: 3, tag: "bronze"}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: 36}}], + [{items: [{price: 50, qty: 50, tag: "x"}, {price: 18, qty: -0.1, tag: "x"}], price: -0.1, b: -1, cust: {age: 5, tier: "bronze", active: false}, flag: false}, {b: -1, cust: {active: false, age: 5, tier: "bronze"}, flag: false, items: [{price: 50, qty: 50, tag: "x"}, {price: 18, qty: -0.1, tag: "x"}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: 5}, price: -0.1}], + [{items: [], b: null, cust: {age: 99, tier: "gold", active: false}, flag: false}, {cust: {active: false, age: 99, tier: "gold"}, flag: false, items: [], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: 99}}], + [{items: [{price: 85, qty: 111, tag: null}], price: 2, b: 1, cust: {age: -1, tier: "gold"}, flag: false}, {b: 1, cust: {age: -1, tier: "gold"}, flag: false, items: [{price: 85, qty: 111, tag: null}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: -1}, price: 2}], + [{items: [{price: 0.1, qty: 21}, {price: null, qty: 100, tag: "Gold"}, {price: 3, qty: 0.1, tag: "silver"}, {price: 19.99, tag: "a"}], price: 19.99, b: 99, cust: {age: 99, tier: "b", active: true}, flag: 0}, "!error"], + [{items: [{price: 3, qty: 10, tag: "silver"}, {price: 77, qty: 21}], price: 21, b: null, cust: {age: 21, active: false}, flag: true}, {cust: {active: false, age: 21}, flag: true, items: [{price: 3, qty: 10, tag: "silver"}, {price: 77, qty: 21}], k171: "21-none", lines: [], out: {k164: true, k165: true, k166: 21}, price: 21}], + [{items: [{price: -25, qty: 21, tag: null}, {price: 19.99, qty: 5, tag: "a"}], b: null, cust: {age: 1000000000000000000000, tier: "b", active: false}, flag: true}, {cust: {active: false, age: 1000000000000000000000, tier: "b"}, flag: true, items: [{price: -25, qty: 21, tag: null}, {price: 19.99, qty: 5, tag: "a"}], k171: "", lines: [], out: {k164: true, k165: true, k166: 1000000000000000000000}}], + [{items: [{price: 2, qty: 5, tag: "bronze"}], price: 100, b: 1000, cust: {age: -25, tier: "zz", active: true}, flag: false}, {b: 1000, cust: {active: true, age: -25, tier: "zz"}, flag: false, items: [{price: 2, qty: 5, tag: "bronze"}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: -25}, price: 100}], + [{items: [{qty: 1000000000000000000000, tag: "gold"}, {price: 18, qty: null, tag: "a"}, {price: 78, qty: 99, tag: null}, {price: 11, qty: 5, tag: "gold "}], price: 18, b: 99, cust: {age: 101, tier: "gold ", active: true}, flag: true}, {b: 99, cust: {active: true, age: 101, tier: "gold "}, flag: true, items: [{qty: 1000000000000000000000, tag: "gold"}, {price: 18, qty: null, tag: "a"}, {price: 78, qty: 99, tag: null}, {price: 11, qty: 5, tag: "gold "}], k171: "", lines: [], out: {k164: true, k165: true, k166: 101}, price: 18}], + [{items: [{qty: -0.1, tag: {t: "x"}}, {price: 3, qty: 5, tag: "silver"}], price: 0.5, b: 19.99, cust: {age: 0.1, tier: "x"}, flag: false}, {b: 19.99, cust: {age: 0.1, tier: "x"}, flag: false, items: [{qty: -0.1, tag: {t: "x"}}, {price: 3, qty: 5, tag: "silver"}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: 0.1}, price: 0.5}], + [{items: [], price: -1, b: 0, cust: {age: 3, tier: "a"}, flag: true}, {b: 0, cust: {age: 3, tier: "a"}, flag: true, items: [], k171: "", lines: [], out: {k164: true, k165: true, k166: 3}, price: -1}], + [{items: [], price: 50, b: 100, cust: {age: 2.5, tier: "", active: false}, flag: false}, {b: 100, cust: {active: false, age: 2.5, tier: ""}, flag: false, items: [], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: 2.5}, price: 50}], + [{items: [{price: 0.5, qty: 19.99, tag: ""}, {price: 2.5, qty: 100}, {price: 50, qty: 5, tag: "b"}, {price: 100, qty: 99, tag: "gold "}], price: 11, b: 50, cust: {age: -0.1, tier: "", active: true}, flag: false}, {b: 50, cust: {active: true, age: -0.1, tier: ""}, flag: false, items: [{price: 0.5, qty: 19.99, tag: ""}, {price: 2.5, qty: 100}, {price: 50, qty: 5, tag: "b"}, {price: 100, qty: 99, tag: "gold "}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: -0.1}, price: 11}], + [{items: "items", price: 10, b: 19.99, cust: {age: 22, tier: null, active: true}, flag: false}, {b: 19.99, cust: {active: true, age: 22, tier: null}, flag: false, items: "items", k171: "10-none", k178: false, lines: [], out: {k164: false, k165: false, k166: 22}, price: 10}], + [{items: [{qty: 100, tag: "x"}], price: null, b: 0.5, cust: {age: 0.5, tier: "a", active: false}, flag: true, extra: [1, 2]}, {b: 0.5, cust: {active: false, age: 0.5, tier: "a"}, extra: [1, 2], flag: true, items: [{qty: 100, tag: "x"}], k171: "", lines: [], out: {k164: true, k165: true, k166: 0.5}}], + [{items: [{qty: 101}, {price: 10, qty: 69, tag: "gold "}], price: 3, b: 1, flag: true}, {b: 1, flag: true, items: [{qty: 101}, {price: 10, qty: 69, tag: "gold "}], k171: "3-none", lines: [], out: {k164: true, k165: true, k166: null}, price: 3}], + [{items: [{price: 50, qty: 100, tag: null}, {price: -1, qty: 1, tag: "zz"}], price: 2.5, b: 2.5, cust: {tier: "", active: true}, flag: false}, "!error"], + [{items: [{price: 5, qty: 101, tag: "silver"}], price: 100, b: 5, flag: true, extra: [1, 2]}, {b: 5, extra: [1, 2], flag: true, items: [{price: 5, qty: 101, tag: "silver"}], k171: "100-none", lines: [{k170: "none"}], out: {k164: true, k165: true, k166: null}, price: 100}], + [{items: [{price: null, qty: 18, tag: "gold "}, {price: 1000000000000000000000, qty: 99, tag: "bronze"}, {qty: 0, tag: "b"}, {price: 18, tag: "silver"}], price: -0.1, b: 12, cust: {age: -0.1, tier: null, active: false}, flag: null}, "!error"], + [{items: [{price: 0.5, qty: 3}], b: 18, cust: {age: 11, tier: "b", active: true}, flag: true}, {b: 18, cust: {active: true, age: 11, tier: "b"}, flag: true, items: [{price: 0.5, qty: 3}], k171: "", lines: [], out: {k164: true, k165: true, k166: 11}}], + [{items: [{qty: 5, tag: "bronze"}, {price: -1, qty: 1000}, {price: 0, qty: null, tag: "gold"}], price: 50, b: 5, cust: {age: 1, tier: "bronze", active: true}, flag: "no"}, "!error"], + [{items: [{price: 19.99, qty: 100, tag: "gold"}, {price: 2, qty: -25, tag: "zz"}], price: 1000000000000000000000, b: 19.99, cust: {age: 0.1, tier: "Gold", active: true}, flag: false, extra: "e"}, {b: 19.99, cust: {active: true, age: 0.1, tier: "Gold"}, extra: "e", flag: false, items: [{price: 19.99, qty: 100, tag: "gold"}, {price: 2, qty: -25, tag: "zz"}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: 0.1}, price: 1000000000000000000000}], + [{items: [{qty: 5, tag: "zz"}, {price: 0.5, qty: -25, tag: "bronze"}], price: 112, b: null, cust: {age: 82, tier: null, active: true}}, "!error"], + [{items: [{price: -1, qty: 1000, tag: ""}, {price: "abc", qty: -15, tag: null}], price: 1000000000000000000000, b: 0, cust: {age: 11, tier: "gold", active: null}, flag: false}, {b: 0, cust: {active: null, age: 11, tier: "gold"}, flag: false, items: [{price: -1, qty: 1000, tag: ""}, {price: "abc", qty: -15, tag: null}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: 11}, price: 1000000000000000000000}], + [{items: [{price: 35, qty: 1, tag: "silver"}, {price: 0.1, qty: 21, tag: "x"}, {price: 1, qty: -25, tag: ""}, {price: -0.1, qty: -25, tag: "x"}], price: 18, b: null, cust: {age: 0, tier: "", active: true}, flag: false}, {cust: {active: true, age: 0, tier: ""}, flag: false, items: [{price: 35, qty: 1, tag: "silver"}, {price: 0.1, qty: 21, tag: "x"}, {price: 1, qty: -25, tag: ""}, {price: -0.1, qty: -25, tag: "x"}], k171: "", k178: false, lines: [], out: {k164: false, k165: false, k166: 0}, price: 18}], + [{items: [{price: 10, qty: 99, tag: "gold"}, {price: 0, qty: 2, tag: "bronze"}, {price: 112, qty: 18, tag: ""}, {price: 19.99, qty: 100, tag: "b"}], price: 11, b: 11, cust: {age: -25, tier: null, active: true}, flag: true}, {b: 11, cust: {active: true, age: -25, tier: null}, flag: true, items: [{price: 10, qty: 99, tag: "gold"}, {price: 0, qty: 2, tag: "bronze"}, {price: 112, qty: 18, tag: ""}, {price: 19.99, qty: 100, tag: "b"}], k171: "11-none", lines: [], out: {k164: true, k165: true, k166: -25}, price: 11}], + [{items: [{price: 3, qty: 3, tag: "zz"}, {price: 1000, qty: 0, tag: "zz"}], price: 11, b: 2.5, cust: {age: 1000, tier: "gold ", active: null}}, "!error"], + [{items: [{price: 18, qty: 2, tag: "a"}, {price: -0.1, qty: 21}, {price: 100, qty: 5, tag: "gold "}], price: 0, b: -0.1, cust: {age: 7, tier: "a", active: true}, flag: true}, {b: -0.1, cust: {active: true, age: 7, tier: "a"}, flag: true, items: [{price: 18, qty: 2, tag: "a"}, {price: -0.1, qty: 21}, {price: 100, qty: 5, tag: "gold "}], k171: "", lines: [], out: {k164: true, k165: true, k166: 7}, price: 0}], + ], +} + +{ + name: "gb015: 7 nodes, expr, table, table, expr, expr, table, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k179: "-4 * (n ?? score ?? 0)", + k180: "min([(score ?? -1), $.k179]) * (n ?? price ?? 0) >= ((price ?? 1))", + k181: "price", + }}, + {table: "t2", inputs: ["(code ?? '')"], outputs: ["k182"], outputPath: "res", rules: [ + ["'gold'", "(k179 ?? 0) * k179 + len((s ?? ''))"], + ["'gold'", "(k181 ?? 0)"], + ["$ != ''", "0.25"], + ["null", "10"], + ["$ != 'silver'", "(((k180 ?? false)) ? (k179 + 2) : len('gold' + ':' + 'gold'))"], + ["'gold'", "10"], + ["", "-(-(3) - (score ?? 0))"], + ]}, + {table: "t3", inputs: ["k180", "score + 0 * ((k181 ?? 0))"], outputs: ["k183"], rules: [ + ["false", "null", "0"], + ["true", "", "((k179 ?? -1) + (-4))"], + ["", "", "0.25"], + ]}, + {expression: "e4", fields: { + k184: "''", + "res.k185": "((100) - ((k183 ?? 0)))", + k179: "`v${k183}-${'x'}`", + k180: "(k183 ?? -1)", + }}, + {expression: "e5", passThrough: true, outputPath: "out", fields: { + k188: "((k180 ?? false) ? code + ':' + (s ?? '') + '-' + 'x' + ' ' + (code ?? '?') : 'gold' + '-' + (code ?? '?') + ' ' + string(price))", + "m.k189": "(2) + min([len(s), len((tier ?? ''))])", + k190: "k180 ?? n", + "m.k191": "(score ?? k179 ?? 0)", + }}, + {table: "t6", inputs: ["res.k182", "100", "res.k182"], outputs: ["k192"], rules: [ + ["$ > 5 and $ < 15", "not(0)", ">= 100", "true"], + ["$ > 0 and $ < 10", "", "$ > 1 and $ < 6", "false"], + ["> 1", "$ > 50 and $ < 51", "(1..11)", "false"], + ["!= 0", "<= 68", ">= 0", "true"], + ]}, + {expression: "e7", fields: { + "res.k193": "not (((true) and (true)) and ((true) and (false)))", + "res.k194": "-4 % 2", + }}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "e1 -> t3", + "input -> t3", + "t3 -> e4", + "e1 -> e5", + "t2 -> t6", + "input -> e7", + "t3 -> e7", + "e4 -> output", + "e5 -> output", + "t6 -> output", + "e7 -> output", + ], + }, + cases: [ + [{code: "x", price: null, score: 2.5, n: 100, tier: "bronze", s: "silver"}, {code: "x", k179: "v0.25-x", k180: 0.25, k184: "", n: 100, out: {k188: "gold-x null", k190: false, m: {k189: 8, k191: 2.5}}, res: {k185: 99.75, k193: true, k194: 0}, s: "silver", score: 2.5, tier: "bronze"}], + [{code: "", price: 19.99, score: 5, n: 1000000000000000000000, tier: "Gold", s: "Gold"}, "!error"], + [{code: "silver", price: 2.5, score: 99, n: 0, tier: null, s: "x"}, {code: "silver", k179: "v0.25-x", k180: 0.25, k181: 2.5, k184: "", n: 0, out: {k188: "gold-silver 2.5", k190: false, m: {k189: 2, k191: 99}}, price: 2.5, res: {k185: 99.75, k193: true, k194: 0}, s: "x", score: 99}], + [{code: "gold ", price: 10, score: 50, n: null, tier: "a"}, "!error"], + [{code: "", price: 0, score: 1000000000000000000000, n: 3, tier: "x", s: "bronze"}, {code: "", k179: "v0.25-x", k180: 0.25, k181: 0, k184: "", n: 3, out: {k188: "gold- 0", k190: false, m: {k189: 3, k191: 1000000000000000000000}}, price: 0, res: {k185: 99.75, k193: true, k194: 0}, s: "bronze", score: 1000000000000000000000, tier: "x"}], + [{code: "silver", price: 2, score: 0.1, n: 1, tier: "", s: "a"}, {code: "silver", k179: "v0.25-x", k180: 0.25, k181: 2, k184: "", n: 1, out: {k188: "gold-silver 2", k190: false, m: {k189: 2, k191: 0.1}}, price: 2, res: {k185: 99.75, k193: true, k194: 0}, s: "a", score: 0.1, tier: ""}], + [{code: "bronze", price: 0.1, score: 100, n: 2.5, tier: "Gold", s: "silver"}, {code: "bronze", k179: "v0.25-x", k180: 0.25, k181: 0.1, k184: "", n: 2.5, out: {k188: "gold-bronze 0.1", k190: false, m: {k189: 6, k191: 100}}, price: 0.1, res: {k185: 99.75, k193: true, k194: 0}, s: "silver", score: 100, tier: "Gold"}], + [{code: "Gold", price: 0, score: null, n: 1000, tier: "x"}, "!error"], + [{code: "b", price: null, score: 11, n: 21, tier: "gold ", s: "b"}, {code: "b", k179: "v0.25-x", k180: 0.25, k184: "", n: 21, out: {k188: "gold-b null", k190: false, m: {k189: 3, k191: 11}}, res: {k185: 99.75, k193: true, k194: 0}, s: "b", score: 11, tier: "gold "}], + [{code: "x", price: 0.1, score: 7, n: 3, tier: "b", s: "bronze"}, {code: "x", k179: "v0.25-x", k180: 0.25, k181: 0.1, k184: "", n: 3, out: {k188: "gold-x 0.1", k190: false, m: {k189: 3, k191: 7}}, price: 0.1, res: {k185: 99.75, k193: true, k194: 0}, s: "bronze", score: 7, tier: "b"}], + [{code: "silver", price: 1000, score: 1, n: 99, tier: "x", s: "a"}, {code: "silver", k179: "v0.25-x", k180: 0.25, k181: 1000, k184: "", n: 99, out: {k188: "gold-silver 1000", k190: false, m: {k189: 3, k191: 1}}, price: 1000, res: {k185: 99.75, k193: true, k194: 0}, s: "a", score: 1, tier: "x"}], + [{code: null, price: 0.5, tier: "a"}, "!error"], + [{code: "b", price: 11, score: 7, n: -25, tier: "b", s: "gold "}, {code: "b", k179: "v0.25-x", k180: 0.25, k181: 11, k184: "", n: -25, out: {k188: "gold-b 11", k190: false, m: {k189: 3, k191: 7}}, price: 11, res: {k185: 99.75, k193: true, k194: 0}, s: "gold ", score: 7, tier: "b"}], + [{code: "Gold", price: 0, score: 2.5, n: -0.1, tier: "", s: "a"}, {code: "Gold", k179: "v0.25-x", k180: 0.25, k181: 0, k184: "", n: -0.1, out: {k188: "gold-Gold 0", k190: false, m: {k189: 2, k191: 2.5}}, price: 0, res: {k185: 99.75, k193: true, k194: 0}, s: "a", score: 2.5, tier: ""}], + [{code: "", price: 7, score: 2.5, n: 0.5, tier: "a", s: null, extra: {deep: {x: 1}}}, "!error"], + [{code: "Gold", price: 5, score: 3, n: 7, tier: "bronze", s: "zz"}, {code: "Gold", k179: "v0.25-x", k180: 0.25, k181: 5, k184: "", n: 7, out: {k188: "gold-Gold 5", k190: false, m: {k189: 4, k191: 3}}, price: 5, res: {k185: 99.75, k193: true, k194: 0}, s: "zz", score: 3, tier: "bronze"}], + [{code: "Gold", price: 18, score: 0.5, tier: "b", s: "zz"}, {code: "Gold", k179: "v0.25-x", k180: 0.25, k181: 18, k184: "", out: {k188: "gold-Gold 18", k190: false, m: {k189: 3, k191: 0.5}}, price: 18, res: {k185: 99.75, k193: true, k194: 0}, s: "zz", score: 0.5, tier: "b"}], + [{code: "a", price: 11, score: 1, n: -0.1, tier: "bronze"}, "!error"], + [{code: "zz", price: 18, score: 5, n: 2, tier: "b", s: "x", extra: 1}, {code: "zz", extra: 1, k179: "v0.25-x", k180: 0.25, k181: 18, k184: "", n: 2, out: {k188: "gold-zz 18", k190: false, m: {k189: 3, k191: 5}}, price: 18, res: {k185: 99.75, k193: true, k194: 0}, s: "x", score: 5, tier: "b"}], + [{code: "Gold", price: 1, score: 101, n: 5, tier: "zz", s: "gold "}, {code: "Gold", k179: "v0.25-x", k180: 0.25, k181: 1, k184: "", n: 5, out: {k188: "gold-Gold 1", k190: false, m: {k189: 4, k191: 101}}, price: 1, res: {k185: 99.75, k193: true, k194: 0}, s: "gold ", score: 101, tier: "zz"}], + [{code: "bronze", price: 1000000000000000000000, score: 2, n: 3, tier: "b"}, "!error"], + [{code: "Gold", score: 21, n: null, tier: "silver", s: "b"}, {code: "Gold", k179: "v0.25-x", k180: 0.25, k184: "", out: {k188: "gold-Gold null", k190: false, m: {k189: 3, k191: 21}}, res: {k185: 99.75, k193: true, k194: 0}, s: "b", score: 21, tier: "silver"}], + [{code: "gold", price: 1000000000000000000000, score: -1, n: 11, s: "gold ", extra: [1, 2]}, {code: "gold", extra: [1, 2], k179: "v0.25-x", k180: 0.25, k181: 1000000000000000000000, k184: "", n: 11, out: {k188: "gold-gold 1000000000000000000000", k190: false, m: {k189: 2, k191: -1}}, price: 1000000000000000000000, res: {k185: 99.75, k193: true, k194: 0}, s: "gold ", score: -1}], + ], +} + +{ + name: "gb016: 8 nodes, expr, switch, expr, table*, switch*, expr, table, loop table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "out", fields: { + k195: "b", + }}, + {switch: "s2", when: ["(tier ?? 'none') + '' + s + '' + string(0.5) == 'gold'", ""]}, + {expression: "e3", passThrough: true, outputPath: "lines", fields: { + k196: "trim(string((flag ?? false))) != 'silver'", + k197: "$.k196 ?? score", + }}, + {table: "t4", hit: "collect", inputs: ["tier"], outputs: ["k198", "k199"], outputPath: "res", rules: [ + ["null", "''", "(b ?? 0) < -((b ?? 0))"], + ["", "'low'", "true"], + ["", "''", "true"], + ]}, + {switch: "s5", hit: "collect", when: ["b * 10 % 2 < (b ?? 0)", "(tier ?? '?') in ['gold', 'silver', 'a']", "startsWith(lower('A-1'), 'g')"]}, + {expression: "e6", fields: { + k200: "1 + floor(100)", + k201: "(($.k200))", + }}, + {table: "t7", inputs: ["'none' + ':' + `v${(k201 ?? 0)}-${'none'}`"], outputs: ["k202"], passThrough: true, rules: [ + ["", "''"], + ["null", "'low'"], + ["null", "'low'"], + ]}, + {table: "t8", inputField: "items", executionMode: "loop", inputs: ["string(0 < (qty ?? 0))", "qty", "qty"], outputs: ["k203", "k204"], passThrough: true, outputPath: "res", rules: [ + ["", "", "1", "true", "'gold'"], + ["null", "!= 18", "not(10)", "false", "string(true)"], + ["null", "null", "10, 20", "true", "'gold'"], + ["", "", "$ > 50 and $ < 51", "true", "string(false)"], + ]}, + ], + edges: [ + "input -> e1", + "input -> s2", + "s2:0 -> e3", + "s2:1 -> t4", + "e3 -> s5", + "t4 -> e6", + "e6 -> t7", + "s2:1 -> t8", + "e1 -> output", + "s5:2 -> output", + "t7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{flag: false, items: [], s: null, score: 0.5, b: 39, tier: ""}, {b: 39, flag: false, items: [], k200: 101, k201: 101, k202: "", out: {k195: 39}, res: [], score: 0.5, tier: ""}], + [{flag: true, items: [{price: 0.5, qty: 50, tag: "b"}, {price: 19.99, qty: 11}, {price: 21, qty: 18, tag: "b"}, {price: 11, qty: 5}], s: "", score: 1000000000000000000000, b: 99, tier: "zz"}, {b: 99, flag: true, items: [{price: 0.5, qty: 50, tag: "b"}, {price: 19.99, qty: 11}, {price: 21, qty: 18, tag: "b"}, {price: 11, qty: 5}], k200: 101, k201: 101, k202: "", out: {k195: 99}, res: [{price: 0.5, qty: 50, tag: "b"}, {price: 19.99, qty: 11}, {price: 21, qty: 18, tag: "b"}, {price: 11, qty: 5}], s: "", score: 1000000000000000000000, tier: "zz"}], + [{flag: false, items: [{price: -0.1, qty: -1, tag: "silver"}], s: null, score: 19.99, b: -0.1, tier: "gold "}, {b: -0.1, flag: false, items: [{price: -0.1, qty: -1, tag: "silver"}], k200: 101, k201: 101, k202: "", out: {k195: -0.1}, res: [{price: -0.1, qty: -1, tag: "silver"}], score: 19.99, tier: "gold "}], + [{flag: false, items: [{tag: ""}, {price: 2, qty: 101, tag: "b"}], s: "a", b: 101, tier: "a"}, {b: 101, flag: false, items: [{tag: ""}, {price: 2, qty: 101, tag: "b"}], k200: 101, k201: 101, k202: "", out: {k195: 101}, res: [{tag: ""}, {price: 2, qty: 101, tag: "b"}], s: "a", tier: "a"}], + [{flag: false, items: [{price: null, qty: 120, tag: ""}], s: "Gold", score: 2.5, b: 5, tier: "a", extra: [1, 2]}, {b: 5, extra: [1, 2], flag: false, items: [{price: null, qty: 120, tag: ""}], k200: 101, k201: 101, k202: "", out: {k195: 5}, res: [{price: null, qty: 120, tag: ""}], s: "Gold", score: 2.5, tier: "a"}], + [{flag: true, items: [{price: 0, qty: 0, tag: "gold"}, {price: 5, qty: 0}], s: "Gold", score: 1000000000000000000000, tier: null}, {flag: true, items: [{price: 0, qty: 0, tag: "gold"}, {price: 5, qty: 0}], k200: 101, k201: 101, k202: "", out: {k195: null}, res: [{price: 0, qty: 0, tag: "gold"}, {price: 5, qty: 0}], s: "Gold", score: 1000000000000000000000}], + [{flag: false, items: [{price: 1000000000000000000000, qty: 50, tag: "bronze"}], s: "gold ", score: -25, b: 0.5, tier: "x"}, {b: 0.5, flag: false, items: [{price: 1000000000000000000000, qty: 50, tag: "bronze"}], k200: 101, k201: 101, k202: "", out: {k195: 0.5}, res: [{price: 1000000000000000000000, qty: 50, tag: "bronze"}], s: "gold ", score: -25, tier: "x"}], + [{flag: null, items: [{price: 21, qty: -0.1, tag: "zz"}, {price: -1, qty: 99, tag: "Gold"}], s: "x", score: 1000000000000000000000, b: 99, tier: "bronze"}, {b: 99, items: [{price: 21, qty: -0.1, tag: "zz"}, {price: -1, qty: 99, tag: "Gold"}], k200: 101, k201: 101, k202: "", out: {k195: 99}, res: [{price: 21, qty: -0.1, tag: "zz"}, {price: -1, qty: 99, tag: "Gold"}], s: "x", score: 1000000000000000000000, tier: "bronze"}], + [{flag: true, items: [{price: 50, qty: 5, tag: "bronze"}, {price: 3, tag: "zz"}, {price: 7, qty: 1000, tag: "gold"}, {price: -25, qty: 0.1, tag: "zz"}], s: "", score: 99, b: 18, tier: "b", extra: "e"}, {b: 18, extra: "e", flag: true, items: [{price: 50, qty: 5, tag: "bronze"}, {price: 3, tag: "zz"}, {price: 7, qty: 1000, tag: "gold"}, {price: -25, qty: 0.1, tag: "zz"}], k200: 101, k201: 101, k202: "", out: {k195: 18}, res: [{price: 50, qty: 5, tag: "bronze"}, {price: 3, tag: "zz"}, {price: 7, qty: 1000, tag: "gold"}, {price: -25, qty: 0.1, tag: "zz"}], s: "", score: 99, tier: "b"}], + [{flag: null, items: [{price: 2, qty: 50, tag: "a"}], s: "Gold", score: 0, b: 0, tier: "gold"}, {b: 0, items: [{price: 2, qty: 50, tag: "a"}], k200: 101, k201: 101, k202: "", out: {k195: 0}, res: [{price: 2, qty: 50, tag: "a"}], s: "Gold", score: 0, tier: "gold"}], + [{flag: false, items: [{qty: 1, tag: "b"}, {price: 3, qty: 19.99, tag: "bronze"}], s: "b", score: 18, b: 3, tier: "b"}, {b: 3, flag: false, items: [{qty: 1, tag: "b"}, {price: 3, qty: 19.99, tag: "bronze"}], k200: 101, k201: 101, k202: "", out: {k195: 3}, res: [{k203: true, k204: "gold", qty: 1, tag: "b"}, {price: 3, qty: 19.99, tag: "bronze"}], s: "b", score: 18, tier: "b"}], + [{flag: true, items: [{price: 51, qty: -1, tag: "Gold"}, {price: 101, qty: 0, tag: "Gold"}, {price: null, qty: 1000, tag: "x"}], s: "b", score: 19.99, b: 3, tier: "gold "}, {b: 3, flag: true, items: [{price: 51, qty: -1, tag: "Gold"}, {price: 101, qty: 0, tag: "Gold"}, {price: null, qty: 1000, tag: "x"}], k200: 101, k201: 101, k202: "", out: {k195: 3}, res: [{price: 51, qty: -1, tag: "Gold"}, {price: 101, qty: 0, tag: "Gold"}, {price: null, qty: 1000, tag: "x"}], s: "b", score: 19.99, tier: "gold "}], + [{flag: true, items: [{price: 99, qty: 3, tag: "x"}, {price: 3, qty: 10, tag: "silver"}, {price: null, qty: 50, tag: "gold "}], s: "", score: 5, b: 2.5, tier: null}, {b: 2.5, flag: true, items: [{price: 99, qty: 3, tag: "x"}, {price: 3, qty: 10, tag: "silver"}, {price: null, qty: 50, tag: "gold "}], k200: 101, k201: 101, k202: "", out: {k195: 2.5}, res: [{price: 99, qty: 3, tag: "x"}, {price: 3, qty: 10, tag: "silver"}, {price: null, qty: 50, tag: "gold "}], s: "", score: 5}], + [{flag: false, items: [{price: 99, qty: -25, tag: null}, {price: -25, qty: 7, tag: ""}], s: "Gold", score: 1, b: 0, tier: "a"}, {b: 0, flag: false, items: [{price: 99, qty: -25, tag: null}, {price: -25, qty: 7, tag: ""}], k200: 101, k201: 101, k202: "", out: {k195: 0}, res: [{price: 99, qty: -25, tag: null}, {price: -25, qty: 7, tag: ""}], s: "Gold", score: 1, tier: "a"}], + [{flag: false, items: [{price: 99, qty: 7, tag: "gold"}, {price: -25, qty: null}], s: "gold ", score: 0.1, b: 118, tier: "silver"}, {b: 118, flag: false, items: [{price: 99, qty: 7, tag: "gold"}, {price: -25, qty: null}], k200: 101, k201: 101, k202: "", out: {k195: 118}, res: [{price: 99, qty: 7, tag: "gold"}, {price: -25, qty: null}], s: "gold ", score: 0.1, tier: "silver"}], + [{flag: true, items: [{price: 10, qty: 99, tag: ""}], s: "gold", score: 18, b: 32, tier: "Gold"}, {b: 32, flag: true, items: [{price: 10, qty: 99, tag: ""}], k200: 101, k201: 101, k202: "", out: {k195: 32}, res: [{price: 10, qty: 99, tag: ""}], s: "gold", score: 18, tier: "Gold"}], + [{flag: null, items: [{price: 21, qty: 0, tag: "gold "}, {price: 11, qty: 22, tag: "x"}], s: "gold ", b: 99, tier: "gold "}, {b: 99, items: [{price: 21, qty: 0, tag: "gold "}, {price: 11, qty: 22, tag: "x"}], k200: 101, k201: 101, k202: "", out: {k195: 99}, res: [{price: 21, qty: 0, tag: "gold "}, {price: 11, qty: 22, tag: "x"}], s: "gold ", tier: "gold "}], + [{flag: null, items: [{qty: -0.1, tag: "zz"}, {price: null, qty: 99, tag: "x"}], s: "gold", score: -0.1, tier: "bronze"}, {items: [{qty: -0.1, tag: "zz"}, {price: null, qty: 99, tag: "x"}], k200: 101, k201: 101, k202: "", out: {k195: null}, res: [{qty: -0.1, tag: "zz"}, {price: null, qty: 99, tag: "x"}], s: "gold", score: -0.1, tier: "bronze"}], + [{items: [{price: 11, qty: 7, tag: "x"}, {price: 3, qty: 1000, tag: "a"}], s: "b", score: 0.5, b: 18, tier: "gold"}, {b: 18, items: [{price: 11, qty: 7, tag: "x"}, {price: 3, qty: 1000, tag: "a"}], k200: 101, k201: 101, k202: "", out: {k195: 18}, res: [{price: 11, qty: 7, tag: "x"}, {price: 3, qty: 1000, tag: "a"}], s: "b", score: 0.5, tier: "gold"}], + [{flag: null, items: [{price: null, qty: 10, tag: "gold "}, {price: null, qty: 2, tag: "silver"}, {price: 0.5, qty: 18, tag: "Gold"}, {price: null, tag: "x"}], s: "a", score: 21, b: 19.99, tier: "a"}, {b: 19.99, items: [{price: null, qty: 10, tag: "gold "}, {price: null, qty: 2, tag: "silver"}, {price: 0.5, qty: 18, tag: "Gold"}, {price: null, tag: "x"}], k200: 101, k201: 101, k202: "", out: {k195: 19.99}, res: [{price: null, qty: 10, tag: "gold "}, {price: null, qty: 2, tag: "silver"}, {price: 0.5, qty: 18, tag: "Gold"}, {price: null, tag: "x"}], s: "a", score: 21, tier: "a"}], + [{flag: true, items: [{price: null, qty: 0.1, tag: "silver"}, {price: 99, qty: 0.1, tag: "Gold"}, {price: 0.5, qty: -0.1, tag: null}], s: "", score: 64, b: 0, tier: "Gold"}, {b: 0, flag: true, items: [{price: null, qty: 0.1, tag: "silver"}, {price: 99, qty: 0.1, tag: "Gold"}, {price: 0.5, qty: -0.1, tag: null}], k200: 101, k201: 101, k202: "", out: {k195: 0}, res: [{price: null, qty: 0.1, tag: "silver"}, {price: 99, qty: 0.1, tag: "Gold"}, {price: 0.5, qty: -0.1, tag: null}], s: "", score: 64, tier: "Gold"}], + [{flag: true, items: [{price: 1000, qty: -0.1, tag: "zz"}, {price: 0.5, qty: null, tag: "gold "}], s: "b", score: 100, b: 50, tier: ""}, {b: 50, flag: true, items: [{price: 1000, qty: -0.1, tag: "zz"}, {price: 0.5, qty: null, tag: "gold "}], k200: 101, k201: 101, k202: "", out: {k195: 50}, res: [{price: 1000, qty: -0.1, tag: "zz"}, {price: 0.5, qty: null, tag: "gold "}], s: "b", score: 100, tier: ""}], + [{flag: false, items: [{price: 2, qty: 0.5, tag: "zz"}, {price: 11, tag: "b"}], s: "x", score: 1000, b: 18, tier: "Gold", extra: {deep: {x: 1}}}, {b: 18, extra: {deep: {x: 1}}, flag: false, items: [{price: 2, qty: 0.5, tag: "zz"}, {price: 11, tag: "b"}], k200: 101, k201: 101, k202: "", out: {k195: 18}, res: [{price: 2, qty: 0.5, tag: "zz"}, {price: 11, tag: "b"}], s: "x", score: 1000, tier: "Gold"}], + [{flag: false, items: [{price: 1, qty: 1, tag: "zz"}, {price: 10, qty: 2, tag: "Gold"}], s: "silver", score: 120, b: 0.5, tier: "zz"}, {b: 0.5, flag: false, items: [{price: 1, qty: 1, tag: "zz"}, {price: 10, qty: 2, tag: "Gold"}], k200: 101, k201: 101, k202: "", out: {k195: 0.5}, res: [{k203: true, k204: "gold", price: 1, qty: 1, tag: "zz"}, {price: 10, qty: 2, tag: "Gold"}], s: "silver", score: 120, tier: "zz"}], + [{flag: true, items: [{price: 1, qty: 0.5, tag: "gold "}, {price: 101, qty: -1, tag: "x"}, {price: 57, qty: 113, tag: "gold"}, {price: 1000, qty: 100, tag: "gold "}], s: "zz", score: -1, b: null, tier: "silver"}, {flag: true, items: [{price: 1, qty: 0.5, tag: "gold "}, {price: 101, qty: -1, tag: "x"}, {price: 57, qty: 113, tag: "gold"}, {price: 1000, qty: 100, tag: "gold "}], k200: 101, k201: 101, k202: "", out: {k195: null}, res: [{price: 1, qty: 0.5, tag: "gold "}, {price: 101, qty: -1, tag: "x"}, {price: 57, qty: 113, tag: "gold"}, {price: 1000, qty: 100, tag: "gold "}], s: "zz", score: -1, tier: "silver"}], + [{flag: true, items: [{qty: null, tag: "gold "}, {price: 19.99, qty: 19.99, tag: "a"}], s: "Gold", score: 7, b: -1, tier: "zz"}, {b: -1, flag: true, items: [{qty: null, tag: "gold "}, {price: 19.99, qty: 19.99, tag: "a"}], k200: 101, k201: 101, k202: "", out: {k195: -1}, res: [{qty: null, tag: "gold "}, {price: 19.99, qty: 19.99, tag: "a"}], s: "Gold", score: 7, tier: "zz"}], + ], +} + +{ + name: "gb017: 10 nodes, loop table, expr, loop expr, table, table, table, switch, expr, switch, table", + graph: { + nodes: [ + {table: "t1", inputField: "items", executionMode: "loop", inputs: ["(tag ?? 'none')", null], outputs: ["k205", "k206"], outputPath: "res", rules: [ + ["'x'", "", "`${2.25}-${(tag ?? 'none')}` == 'x'", "true"], + ["null", "true", "(tag ?? '?') == 'silver'", "false"], + ["", "", "true", "false"], + ]}, + {expression: "e2", outputPath: "lines", fields: { + k205: "a != null", + "g.k208": "'x'", + }}, + {expression: "e3", inputField: "items", executionMode: "loop", outputPath: "lines", fields: { + "res.k209": "price ?? tag", + "res.k210": "price ?? qty", + }}, + {table: "t4", inputs: ["1 - (2)", "2"], outputs: ["k211"], passThrough: true, rules: [ + ["null", "(5..55)", "'low'"], + ["100", "5", "'mid'"], + [">= -1", ">= 50", "'mid'"], + ["", "", "'mid'"], + ]}, + {table: "t5", inputs: ["`n=${1}-${'A-1'}`", "'none'", "2 * 2.25 - -(3)", null], outputs: ["res.k212"], passThrough: true, outputPath: "out", rules: [ + ["null", "$ != 'a'", "not(-1)", "'gold'", "false"], + ["startsWith($, 'x')", "$ != ''", "10", "5", "true"], + ["startsWith($, 's')", "null", "(0..1)", "", "true"], + ["not('a')", "null", "< 0", "true", "false"], + ]}, + {table: "t6", inputs: ["out.res.k212"], outputs: ["k213", "k214"], passThrough: true, rules: [ + ["$ == true", "0", "(false ? 100 : 0.5) - (10) in [0..10]"], + ["$ == true", "0.25", "true"], + ["null", "-(((100)))", "false"], + ]}, + {switch: "s7", when: ["not (true)", ""]}, + {expression: "e8", passThrough: true, fields: { + k215: "-4", + "m.k216": "((out.res.k212 ?? false)) and (10 * -4 in [-5..5])", + k217: "($.k215 ?? 1)", + }}, + {switch: "s9", when: ["true", "(contains('A-1' + ':' + 'x', 'g')) or ('A-1' != 'gold')", "false", ""]}, + {table: "t10", inputs: ["len('gold') * (0 ?? 1 ?? 0)"], outputs: ["k218"], outputPath: "res", rules: [ + ["(0..5)", "(100) + (false ? 1 : 0) * 0 + -4"], + ["0, 50", "10"], + ["[5..15)", "10"], + ["[18..23)", "2"], + ["$ > -1 and $ < 0", "-5"], + ["", "-4"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "input -> e3", + "t1 -> t4", + "t1 -> t5", + "t5 -> t6", + "e3 -> t6", + "t5 -> s7", + "s7:0 -> e8", + "t1 -> s9", + "s9:3 -> t10", + "e2 -> output", + "t4 -> output", + "t6 -> output", + "s7:1 -> output", + "e8 -> output", + "s9:2 -> output", + "t10 -> output", + ], + }, + cases: [ + [{cust: {age: null, tier: "bronze", active: false}, items: [{qty: 18, tag: null}, {price: 1, qty: 19.99, tag: ""}], flag: true, tier: "", nums: [11], a: 18}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: 5, tier: "Gold", active: false}, items: [], flag: true, tier: "", nums: [7], a: 18}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: []}], + [{cust: {tier: "zz", active: false}, items: null, flag: false, tier: null, nums: [], a: null}, "!error"], + [{cust: {age: 0, tier: "zz"}, items: [], tier: "silver", nums: [2.5, 11, 0], a: 50, extra: {deep: {x: 1}}}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: []}], + [{cust: {age: 3, tier: "bronze", active: true}, items: [], flag: true, tier: "x", nums: [], a: 21}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: []}], + [{cust: {age: -1, tier: "a", active: true}, items: [{price: 0.5, qty: 19.99}, {price: 100, qty: 2.5, tag: ""}], flag: true, tier: "", nums: [100, 1000, 101, 5, 21], a: 5}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: -11, tier: "a", active: false}, items: [{price: 2, qty: 0}, {price: null, qty: 1, tag: ""}], flag: false, tier: "zz", nums: null, a: 19.99}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: 2.5, tier: "", active: true}, items: [{price: null, tag: "bronze"}, {price: 3, qty: 10, tag: ""}, {price: 100, qty: 99, tag: "silver"}], flag: true, tier: "bronze", nums: [2.5, 0.1, 1000000000000000000000, 1000000000000000000000, 99], a: 7, extra: 1}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}, {k205: true, k206: false}]}], + [{items: [{price: 100, qty: 0.1, tag: null}, {price: 21, qty: 3, tag: "b"}, {price: 80, qty: -25, tag: "zz"}], flag: true, tier: "x", nums: [], a: 19.99}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: 1000, tier: "", active: false}, items: [], flag: false, tier: "x", nums: [3, -0.1], a: null}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: []}], + [{cust: {age: 0.1, tier: "x", active: true}, items: [{price: 100, qty: 0.1, tag: ""}, {price: 2.5, qty: null, tag: "gold "}], flag: null, tier: "gold ", a: 7}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: 11, tier: "gold ", active: false}, items: [{price: -0.1, qty: null, tag: "b"}, {price: 99, qty: 3, tag: "gold "}], flag: false, tier: "x", a: 101}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: null, items: [{qty: 7, tag: "silver"}, {price: 0.5, qty: 18, tag: "gold"}, {price: 19.99, tag: "bronze"}], flag: true, tier: "x", nums: [7, 0.1], a: 100}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: 19.99, tier: "Gold", active: false}, items: [{price: 1, qty: 100, tag: null}], flag: false, tier: "zz", nums: [50, 0.1], a: 101}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}]}], + [{items: [{price: -25, qty: 10, tag: "b"}, {price: 83, qty: 0, tag: "silver"}], flag: true, tier: "Gold", nums: [], a: -0.1, extra: "e"}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: null, items: [{price: 101, qty: 19.99, tag: "zz"}, {price: 50, qty: -25, tag: "x"}], tier: "bronze", nums: [], a: 1000000000000000000000}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: false, k206: true}]}], + [{cust: {age: 0.5, tier: "x", active: false}, items: [], flag: false, tier: "zz", nums: [101, -25, 19.99], a: 5, extra: [1, 2]}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: []}], + [{cust: {age: 0.5, tier: "gold ", active: false}, items: [{price: 21, qty: -0.1, tag: "Gold"}, {price: 1000000000000000000000, qty: 0, tag: "x"}], flag: false, tier: "gold", nums: [0, 99, 1000], a: 21}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: false, k206: true}]}], + [{cust: {age: 1000000000000000000000, tier: "gold ", active: false}, items: [], flag: false, tier: "Gold", nums: [], a: 10}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: []}], + [{cust: {tier: "zz", active: true}, items: [{price: 18, tag: "gold "}, {price: 10, qty: 5}], flag: false, tier: "a", nums: [1, 101, 14, 10, 7], a: 11}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: -1, tier: "", active: false}, items: [{price: -0.1, qty: 7, tag: "bronze"}], flag: true, tier: "b", nums: [99]}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}]}], + [{cust: {age: 10, active: true}, items: [{price: 5, qty: 50, tag: "gold "}, {price: 1, qty: -1, tag: "gold"}, {price: -0.1, qty: 100, tag: "x"}], flag: false, tier: "bronze", nums: [7], a: 7}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}, {k205: false, k206: true}]}], + [{cust: {age: -25, tier: "gold ", active: null}, items: [{price: 1000000000000000000000, qty: 19.99, tag: "b"}, {price: null, qty: -25, tag: "a"}], flag: false, tier: "zz", nums: [0, 50, 99, 10, 19.99], a: 1}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: 2, tier: "gold ", active: true}, items: [{price: -25, qty: 58, tag: "Gold"}, {qty: -25, tag: null}, {qty: 18, tag: "bronze"}], flag: false, tier: "silver", nums: [5]}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: null, active: false}, items: [{price: 19.99, qty: 7, tag: "Gold"}], flag: false, tier: "x", nums: [99, 3], a: null}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}]}], + [{cust: {age: 7, tier: "Gold", active: true}, items: [{price: 18, qty: 7, tag: "bronze"}, {price: 1000, qty: 99, tag: "zz"}, {price: 101, qty: 21, tag: ""}, {price: 2.5, qty: null, tag: "bronze"}], flag: true, tier: null, nums: [10, 50], a: 99}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}, {k205: true, k206: false}, {k205: true, k206: false}]}], + [{cust: {age: 50, tier: "a", active: false}, items: [{price: 10, qty: -25, tag: "gold"}, {price: null, qty: 18, tag: "silver"}], tier: "gold", nums: [18, 1000000000000000000000, -1], a: 1000000000000000000000}, {k211: "mid", k213: -100, k214: false, lines: {g: {k208: "x"}, k205: false}, res: [{k205: true, k206: false}, {k205: true, k206: false}]}], + ], +} + +{ + name: "gb018: 6 nodes, loop table, loop expr, loop expr, expr, loop expr, expr", + graph: { + nodes: [ + {table: "t1", inputField: "items", executionMode: "loop", inputs: ["qty", "price", null], outputs: ["k219", "k220"], passThrough: true, outputPath: "lines", rules: [ + ["null", "$ > 100 and $ < 150", "null", "false", "`v${(price ?? 1)}-${(tag ?? '')}`"], + ["10, 11", "", "true", "true", "string(0 in [1..100])"], + ]}, + {expression: "e2", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "lines", fields: { + k221: "false", + k222: "qty ?? price", + k223: "(1) * min([(price ?? -1), (qty ?? 1)]) + abs(price)", + }}, + {expression: "e3", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k224: "-4 > (-4 * (qty ?? -1))", + k221: "(price ?? qty ?? 0)", + "g.k226": "(tag ?? '?')", + k220: "0.5 + len((tag ?? '')) * 1", + }}, + {expression: "e4", outputPath: "lines", fields: { + k223: "((cust.age ?? -1) <= a * 0.5) or ((b < b) and ((true) or (true)))", + "m.k229": "trim((code ?? '?')) in ['gold', 'silver', 'a']", + "m.k230": "(s ?? 'none') + ' ' + ((false) and (false) ? `${(b ?? 1)}-${(s ?? '')}` : `n=${b}-${(s ?? '?')}`)", + "res.k231": "(floor(sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0)))))", + }}, + {expression: "e5", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + "m.k232": "tag ?? price", + k233: "(tag ?? '?')", + k234: "len((tag ?? 'none'))", + }}, + {expression: "e6", fields: { + k235: "max([floor(0) * (0.5), (3 % 3)])", + }}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "input -> e2", + "input -> e3", + "e3 -> e4", + "input -> e4", + "e2 -> e5", + "e5 -> e6", + "e4 -> output", + "e6 -> output", + ], + }, + cases: [ + [{code: "gold ", s: "gold", b: 1, cust: {age: 2, tier: "bronze", active: false}, nums: [2], a: null, items: null}, "!error"], + [{code: "b", s: "silver", b: -1, cust: null, nums: [50], a: 7, items: [{price: 5, qty: 18, tag: "a"}, {price: 50, qty: 76, tag: "bronze"}]}, {k235: 0, lines: {k223: true, m: {k229: false, k230: "silver n=-1-silver"}, res: {k231: 3890}}}], + [{s: "b", b: 3, cust: {age: 100, tier: "bronze", active: false}, nums: null, a: 19.99, items: [{price: 50, qty: -13, tag: "x"}, {price: 18, qty: 99, tag: "a"}, {price: -25, qty: 0.5, tag: "zz"}, {price: 1000, qty: 2.5, tag: "a"}]}, {k235: 0, lines: {k223: false, m: {k229: false, k230: "b n=3-b"}, res: {k231: 3619}}}], + [{s: "bronze", b: 0.1, cust: {age: 21, tier: null, active: false}, nums: [1, 1000], a: 19.99, items: [{price: 1, qty: 19.99, tag: "Gold"}]}, {k235: 0, lines: {k223: false, m: {k229: false, k230: "bronze n=0.1-bronze"}, res: {k231: 19}}}], + [{code: "a", s: "gold ", b: 1000, cust: {age: 21, tier: "b", active: false}, nums: [60, 1000000000000000000000], a: 7, items: [{price: 100, tag: "zz"}, {price: 0, qty: 73, tag: "gold"}, {price: -1, qty: 50, tag: "x"}]}, {k235: 0, lines: {k223: false, m: {k229: true, k230: "gold n=1000-gold "}, res: {k231: -50}}}], + [{code: "gold", s: "bronze", b: 21, cust: {age: 20, tier: null, active: true}, nums: [], a: 1000, items: [{price: 3, qty: 5, tag: ""}, {price: 18, qty: 2.5, tag: "a"}, {price: 2, qty: null, tag: ""}, {price: 100, qty: -25, tag: "gold "}]}, {k235: 0, lines: {k223: true, m: {k229: true, k230: "bronze n=21-bronze"}, res: {k231: -2440}}}], + [{code: "silver", s: "gold", b: null, cust: {age: 101, tier: "zz", active: null}, nums: [7, -25], items: []}, "!error"], + [{code: "Gold", s: "bronze", b: 50, nums: [7, 19.99], a: 1, items: [{price: 19.99, qty: -1, tag: "x"}, {price: 2.5, qty: -0.1, tag: "gold"}, {price: 5, qty: 2.5, tag: "Gold"}, {price: 10, qty: 99, tag: "bronze"}], extra: "e"}, {k235: 0, lines: {k223: true, m: {k229: false, k230: "bronze n=50-bronze"}, res: {k231: 982}}}], + [{code: "", s: "zz", b: 99, cust: {age: 5, tier: "gold", active: true}, nums: [], a: 100, items: [{price: -0.1, qty: 21, tag: "silver"}, {price: 11, qty: 11, tag: "b"}]}, {k235: 0, lines: {k223: true, m: {k229: false, k230: "zz n=99-zz"}, res: {k231: 118}}}], + [{code: "silver", s: "silver", b: 11, cust: {age: 21, tier: "", active: false}, a: 39, items: [{price: 101, qty: -1, tag: "zz"}]}, {k235: 0, lines: {k223: false, m: {k229: true, k230: "silver n=11-silver"}, res: {k231: -101}}}], + [{code: "gold", s: "silver", b: 101, cust: {age: 1000, tier: "x", active: true}, nums: [50], a: 18, items: [{price: 7, qty: -25, tag: ""}, {price: 100, qty: 0.5, tag: "silver"}]}, {k235: 0, lines: {k223: false, m: {k229: true, k230: "silver n=101-silver"}, res: {k231: -125}}}], + [{s: "gold", b: -25, cust: {age: 1000, tier: "b", active: false}, nums: [-0.1, 1000000000000000000000, 101, 2.5, 11], a: 1, items: [{price: 101, qty: 0.5, tag: null}, {price: 0, qty: 0.5, tag: "zz"}, {price: 50, qty: 21}], extra: 1}, {k235: 0, lines: {k223: false, m: {k229: false, k230: "gold n=-25-gold"}, res: {k231: 1100}}}], + [{b: 100, cust: {age: 99, tier: null, active: true}, nums: [21], a: 3, items: [{price: 5, qty: 1, tag: "zz"}, {price: 0.5, qty: 0.5, tag: "Gold"}, {price: 1, tag: "silver"}]}, {k235: 0, lines: {k223: false, m: {k229: false, k230: "none n=100-?"}, res: {k231: 5}}}], + [{code: "gold ", b: 100, cust: {age: 1, tier: "gold", active: false}, nums: [0.5, 1000], a: 99, items: [{price: 1, qty: 10, tag: "Gold"}, {price: -25, qty: null, tag: "gold "}, {price: 0.5, qty: 14, tag: "gold "}, {qty: 0.5, tag: "bronze"}]}, "!error"], + [{code: "x", s: "silver", b: -0.1, cust: {age: 10, tier: "b", active: true}, nums: [1, 1000000000000000000000, 18, -0.1, 7], a: 1000, items: [{price: 1000000000000000000000, qty: 2, tag: "x"}]}, {k235: 0, lines: {k223: true, m: {k229: false, k230: "silver n=-0.1-silver"}, res: {k231: 2000000000000000000000}}}], + [{code: null, s: "x", b: 50, cust: {tier: "x", active: true}, nums: [2.5, 50, 5, 7, 0], a: 107, items: [{price: -0.1, qty: 0.1, tag: "b"}, {price: 0.5, qty: 0.5, tag: "gold "}, {price: 7, qty: -25, tag: "b"}, {price: 5, qty: -0.1, tag: "x"}]}, {k235: 0, lines: {k223: true, m: {k229: false, k230: "x n=50-x"}, res: {k231: -176}}}], + [{code: "gold", s: "gold", b: 99, cust: {age: 0.5, tier: "bronze", active: true}, nums: null, a: 1, items: [{price: 24, qty: -1, tag: "x"}, {price: -25, qty: -0.1, tag: "b"}]}, {k235: 0, lines: {k223: true, m: {k229: true, k230: "gold n=99-gold"}, res: {k231: -22}}}], + [{code: "gold", s: "x", cust: {age: 5, tier: "gold", active: true}, nums: [10, 18], a: 1000, items: [{price: 21, qty: 1000, tag: "x"}]}, {k235: 0, lines: {k223: true, m: {k229: true, k230: "x n=null-x"}, res: {k231: 21000}}}], + [{code: "gold ", s: "Gold", b: -25, cust: {age: 2, tier: "b", active: null}, nums: [], a: 2, items: [{price: 1000000000000000000000, qty: 3, tag: "Gold"}, {price: 7, qty: 7, tag: "a"}, {price: 2.5, qty: 5, tag: "a"}, {price: 99, qty: 11, tag: "gold "}]}, {k235: 0, lines: {k223: false, m: {k229: true, k230: "Gold n=-25-Gold"}, res: {k231: 3000000000000000001150}}}], + [{s: "bronze", b: 5, cust: {age: 21, tier: "x", active: false}, nums: [5], items: [{price: 100, qty: 101, tag: "zz"}, {price: 1000000000000000000000, qty: 21, tag: "gold "}], extra: "e"}, "!error"], + [{code: "x", s: "zz", b: 11, cust: {age: 99, tier: "bronze", active: null}, nums: [], a: 1000000000000000000000, items: [{price: 19.99, qty: 118, tag: null}]}, {k235: 0, lines: {k223: true, m: {k229: false, k230: "zz n=11-zz"}, res: {k231: 2358}}}], + [{code: null, s: "gold", b: 50, cust: {age: 18, tier: "", active: false}, nums: [21], a: 101, items: []}, {k235: 0, lines: {k223: true, m: {k229: false, k230: "gold n=50-gold"}, res: {k231: 0}}}], + [{code: null, s: "gold ", b: 1000000000000000000000, cust: {tier: "Gold", active: false}, nums: [50, -1], a: 100, items: []}, {k235: 0, lines: {k223: true, m: {k229: false, k230: "gold n=1000000000000000000000-gold "}, res: {k231: 0}}}], + [{code: null, s: "gold ", b: 50, cust: {age: 21, tier: "silver", active: true}, nums: [5, -25, 50, 99, 0], items: [{price: 1, qty: 11, tag: "bronze"}]}, "!error"], + ], +} + +{ + name: "gb019: 8 nodes, expr, expr, table, expr, expr, expr, expr, expr", + graph: { + nodes: [ + {expression: "e1", fields: { + k236: "contains(lower(s), 'a')", + k237: "(n ?? 0) * (price ?? price ?? 0) * ((n ?? -1) >= (price ?? -1) ? ((n ?? 1)) : (100) / 0.5)", + }}, + {expression: "e2", passThrough: true, fields: { + k238: "len(`v${(price ?? -1)}-${'none'}`) in [-5..5]", + k239: "floor((n ?? 0)) % 2", + k240: "flag ?? vip", + "m.k241": "min([(price ?? -1) * (price), (price ?? 0)])", + }}, + {table: "t3", inputs: ["vip"], outputs: ["res.k242"], outputPath: "out", rules: [ + ["null", "false"], + ["$ == true", "true"], + ["", "(((n ?? 1) in [0..10]) and ((vip))) and ((n ?? -1) % 3 < ((n ?? 0)))"], + ["false", "false"], + ["null", "false"], + ["$ == true", "false"], + ]}, + {expression: "e4", passThrough: true, fields: { + "g.k243": "string(1)", + "res.k244": "2.25", + }}, + {expression: "e5", outputPath: "lines", fields: { + k245: "n", + k246: "k238 ?? s", + }}, + {expression: "e6", outputPath: "out", fields: { + k247: "2.25 * ceil(-4) * (a != null ? (1) / 2 : 100 * 0.5)", + }}, + {expression: "e7", passThrough: true, fields: { + "g.k248": "(endsWith($nodes.e4.g.k243 + ':' + g.k243, 'x')) or (g.k243 != null)", + k249: "res.k244", + "m.k250": "(res.k244 ?? 0)", + }}, + {expression: "e8", outputPath: "o.p", fields: { + "g.k251": "(lines.k245 ?? 1)", + k252: "(contains(string(false), 'x'))", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "input -> t3", + "t3 -> e4", + "e2 -> e5", + "t3 -> e6", + "e4 -> e7", + "e6 -> e8", + "e5 -> e8", + "e1 -> output", + "e7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{flag: true, price: null, n: 99, vip: true, s: ["gold"]}, "!error"], + [{flag: true, price: 100, n: null, vip: false, s: "bronze"}, {g: {k243: "1", k248: true}, k236: false, k237: 0, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 1}, k252: false}}, out: {res: {k242: false}}, res: {k244: 2.25}}], + [{flag: "true", price: 0.5, n: 0, vip: false, s: "bronze"}, {g: {k243: "1", k248: true}, k236: false, k237: 0, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 0}, k252: false}}, out: {res: {k242: false}}, res: {k244: 2.25}}], + [{price: 101, n: 18, s: "b", extra: {deep: {x: 1}}}, {g: {k243: "1", k248: true}, k236: false, k237: 363600, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 18}, k252: false}}, out: {res: {k242: false}}, res: {k244: 2.25}}], + [{flag: true, price: null, n: -0.1, vip: false, s: "a", extra: 1}, "!error"], + [{flag: false, price: true, n: 100, vip: false, s: "zz"}, "!error"], + [{flag: true, price: -25, n: 1, vip: false, s: ["gold"]}, "!error"], + [{flag: false, price: 46, n: "abc", vip: true, s: "bronze"}, "!error"], + [{flag: true, price: "5", n: 34, vip: true, s: "bronze"}, "!error"], + [{flag: false, price: 1000000000000000000000, n: [1], vip: true, s: null}, "!error"], + [{price: 10, n: 100, vip: true, s: "x"}, {g: {k243: "1", k248: true}, k236: false, k237: 100000, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 100}, k252: false}}, out: {res: {k242: true}}, res: {k244: 2.25}}], + [{flag: true, price: 50, n: 1, vip: null, s: "x", extra: "e"}, {g: {k243: "1", k248: true}, k236: false, k237: 10000, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 1}, k252: false}}, out: {res: {k242: false}}, res: {k244: 2.25}}], + [{flag: null, price: 5, n: null, s: "x", extra: [1, 2]}, {g: {k243: "1", k248: true}, k236: false, k237: 0, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 1}, k252: false}}, out: {res: {k242: false}}, res: {k244: 2.25}}], + [{flag: false, price: 1000, n: 1000, vip: false}, "!error"], + [{flag: 0, price: -0.1, n: -0.1, vip: null, s: null, extra: {deep: {x: 1}}}, "!error"], + [{price: null, n: [1], vip: true, s: "gold "}, "!error"], + [{flag: true, price: 2.5, n: 0, vip: false, s: "Gold"}, {g: {k243: "1", k248: true}, k236: false, k237: 0, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 0}, k252: false}}, out: {res: {k242: false}}, res: {k244: 2.25}}], + [{flag: true, price: -1, n: 19.99, vip: false, s: true}, "!error"], + [{price: 1000, n: 18, vip: false, s: "b"}, {g: {k243: "1", k248: true}, k236: false, k237: 3600000, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 18}, k252: false}}, out: {res: {k242: false}}, res: {k244: 2.25}}], + [{flag: false, price: null, n: 3, vip: false, s: null}, "!error"], + [{flag: false, price: 99, n: 0.1, vip: true, s: "zz"}, {g: {k243: "1", k248: true}, k236: false, k237: 1980.0, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 0.1}, k252: false}}, out: {res: {k242: true}}, res: {k244: 2.25}}], + [{flag: false, price: 7, n: 7, vip: 1, s: null}, "!error"], + [{flag: true, price: 1000000000000000000000, n: 18, vip: true, s: "b"}, "!error"], + [{flag: "no", price: 101, n: 21, vip: false}, "!error"], + [{flag: false, price: 24, n: null, vip: false, s: "bronze"}, {g: {k243: "1", k248: true}, k236: false, k237: 0, k249: 2.25, m: {k250: 2.25}, o: {p: {g: {k251: 1}, k252: false}}, out: {res: {k242: false}}, res: {k244: 2.25}}], + [{flag: false, price: 11, n: true, vip: "true", s: "a"}, "!error"], + ], +} + +{ + name: "gb020: 7 nodes, switch, switch*, loop expr, expr, switch*, switch, table", + graph: { + nodes: [ + {switch: "s1", when: ["((code ?? '') + '' + (code ?? '') in ['gold', 'silver', 'a'])", "(((score ?? 1) >= (score ?? -1)) and (flag != null))"]}, + {switch: "s2", hit: "collect", when: ["(score ?? -1) in [-5..5]", "flag", ""]}, + {expression: "e3", inputField: "items", executionMode: "loop", outputPath: "lines", fields: { + k253: "((qty ?? -1) <= (3) ? qty : 1)", + }}, + {expression: "e4", passThrough: true, fields: { + "res.k254": "score", + k253: "(score >= (score ?? score ?? 0)) or ((startsWith(code, 'a')) and (score >= (score ?? 0)))", + "g.k256": "string(not ('' in ['gold', 'silver', 'a']))", + "m.k257": "upper(($.k253 ? 'x' : (code ?? '?'))) == 'x'", + }}, + {switch: "s5", hit: "collect", when: ["(score == null) and (not ((m.k257 ?? false)))", "contains(lower(lower(((items ?? [])[1].tag ?? '') + '!')), 'g')", "code != ''"]}, + {switch: "s6", when: ["not ((score ?? 1) > 10 - res.k254)", "(score ?? res.k254 ?? 0) == (res.k254 ?? 1)", "string(startsWith('none', 'a')) != 'gold'"]}, + {table: "t7", inputs: ["code", "score"], outputs: ["k258"], passThrough: true, rules: [ + ["'silver'", "", "0.25"], + ["startsWith($, 'x')", "$ > 18 and $ < 28", "(-4 < (score ?? 0) ? max([(score ?? 1), 10]) : (score ?? 1) + (score ?? 0)) + -(((flag ?? false) ? (score ?? -1) : (score ?? 0)))"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> s2", + "s2:2 -> e3", + "s2:1 -> e4", + "e4 -> s5", + "e3 -> s5", + "s5:2 -> s6", + "s2:1 -> t7", + "s1:1 -> output", + "s5:0 -> output", + "s5:1 -> output", + "s6:0 -> output", + "s6:1 -> output", + "t7 -> output", + ], + }, + cases: [ + [{flag: false, nums: [10, 19.99, 0, 18, 0.5], score: 1000000000000000000000, items: [{price: {v: 1}, qty: 21, tag: "gold "}, {price: 99, qty: 3, tag: "gold"}]}, {flag: false, items: [{price: {v: 1}, qty: 21, tag: "gold "}, {price: 99, qty: 3, tag: "gold"}], nums: [10, 19.99, 0, 18, 0.5], score: 1000000000000000000000}], + [{flag: true, nums: [10], code: true, score: 0.1, items: [{price: 10, qty: 7, tag: "gold"}, {price: null, qty: 2.5, tag: {t: "x"}}]}, {code: true, flag: true, items: [{price: 10, qty: 7, tag: "gold"}, {price: null, qty: 2.5, tag: {t: "x"}}], nums: [10], score: 0.1}], + [{nums: [], code: "", score: 19.99, items: [{price: -1, qty: 1000000000000000000000, tag: "Gold"}, {price: 100, qty: {v: 1}, tag: "b"}], extra: [1, 2]}, {}], + [{nums: [], code: "Gold", items: []}, {}], + [{flag: true, nums: [], code: "gold", score: {v: 1}, items: [{price: 11, qty: "5", tag: "bronze"}], extra: {deep: {x: 1}}}, {}], + [{flag: false, nums: [], code: "x", score: 3, items: null}, {code: "x", flag: false, nums: [], score: 3}], + [{flag: false, nums: 7, code: "silver", score: 18, items: [{price: 2, qty: 3, tag: ["gold"]}, {price: 19.99, qty: -0.1, tag: "Gold"}]}, {code: "silver", flag: false, items: [{price: 2, qty: 3, tag: ["gold"]}, {price: 19.99, qty: -0.1, tag: "Gold"}], nums: 7, score: 18}], + [{flag: false, nums: [3, 7, -0.1], code: "bronze", score: "abc"}, {}], + [{flag: 0, nums: [11, 2.5, 99], code: "gold", score: null, items: []}, {code: "gold", flag: 0, items: [], nums: [11, 2.5, 99]}], + [{flag: 0, nums: [], code: "zz", score: 50, items: [{price: 1000000000000000000000, qty: 101, tag: 5}, {price: 1000, qty: "5", tag: "Gold"}, {price: -0.1, qty: 2, tag: "b"}, {price: 7, qty: 21, tag: "x"}]}, {code: "zz", flag: 0, items: [{price: 1000000000000000000000, qty: 101, tag: 5}, {price: 1000, qty: "5", tag: "Gold"}, {price: -0.1, qty: 2, tag: "b"}, {price: 7, qty: 21, tag: "x"}], nums: [], score: 50}], + [{nums: [], code: "Gold", score: 3, items: [{price: 5, qty: 21, tag: "b"}, {price: 50, qty: 18, tag: "a"}]}, {}], + [{flag: false, nums: [], code: 5, score: {v: 1}, items: [{price: -1, qty: 100, tag: "silver"}, {price: -0.1, qty: "5", tag: "a"}, {price: 0, qty: 101, tag: "x"}]}, {}], + [{flag: true, nums: [1000000000000000000000, 100, 11], code: "Gold", score: 0, items: [{price: 7, qty: 10, tag: "gold "}, {price: -1, qty: 21, tag: "gold"}]}, {code: "Gold", flag: true, items: [{price: 7, qty: 10, tag: "gold "}, {price: -1, qty: 21, tag: "gold"}], nums: [1000000000000000000000, 100, 11], score: 0}], + [{flag: false, score: 101, items: [{price: 60, qty: 99, tag: "zz"}, {price: [1], qty: 1000, tag: "silver"}, {price: "abc", qty: 2.5, tag: "x"}]}, {flag: false, items: [{price: 60, qty: 99, tag: "zz"}, {price: [1], qty: 1000, tag: "silver"}, {price: "abc", qty: 2.5, tag: "x"}], score: 101}], + [{flag: false, nums: [{x: 1}], code: "gold ", score: 11, items: [{price: 0.1, qty: 99}, {price: {v: 1}, qty: {v: 1}, tag: "silver"}, {price: 99, qty: 1000, tag: "Gold"}, {price: 10, qty: 0.1, tag: "silver"}]}, {code: "gold ", flag: false, items: [{price: 0.1, qty: 99}, {price: {v: 1}, qty: {v: 1}, tag: "silver"}, {price: 99, qty: 1000, tag: "Gold"}, {price: 10, qty: 0.1, tag: "silver"}], nums: [{x: 1}], score: 11}], + [{flag: true, nums: [], score: 2, items: []}, {flag: true, items: [], nums: [], score: 2}], + [{flag: false, nums: ["1", 2], code: "a", score: 1, items: [{price: 100, qty: 0.1, tag: ""}]}, {code: "a", flag: false, items: [{price: 100, qty: 0.1, tag: ""}], nums: ["1", 2], score: 1}], + [{nums: [21, 0.1, 5], code: "", score: 1000, items: [{price: null, qty: 1000, tag: "b"}]}, {}], + [{flag: 1, nums: [-0.1, 2.5, 11, 100, 18], code: "silver", score: 7, items: [{price: 2.5, qty: 19.99, tag: "Gold"}, {price: 5, qty: 7, tag: "b"}, {price: 5, qty: 5, tag: "Gold"}, {price: 0.5, qty: 100, tag: "bronze"}]}, {code: "silver", flag: 1, items: [{price: 2.5, qty: 19.99, tag: "Gold"}, {price: 5, qty: 7, tag: "b"}, {price: 5, qty: 5, tag: "Gold"}, {price: 0.5, qty: 100, tag: "bronze"}], nums: [-0.1, 2.5, 11, 100, 18], score: 7}], + [{flag: "no", nums: 7, code: {t: "x"}, score: {v: 1}, items: [{price: 19.99, qty: 100, tag: null}, {price: 50, qty: 100, tag: "a"}, {price: 11, tag: 5}, {price: 1000000000000000000000, qty: 2.5, tag: "bronze"}]}, {}], + [{flag: true, nums: [7], code: "Gold", score: 50, items: [{price: 21, qty: 9, tag: "gold "}, {price: 1000, qty: "5", tag: "silver"}]}, {code: "Gold", flag: true, items: [{price: 21, qty: 9, tag: "gold "}, {price: 1000, qty: "5", tag: "silver"}], nums: [7], score: 50}], + [{nums: [], code: "bronze", score: -25, items: []}, {}], + [{flag: true, nums: [-0.1], score: true, items: [{price: -1, qty: 3, tag: ""}, {price: 18, qty: 93, tag: null}]}, {}], + [{flag: false, nums: [7], code: "silver", score: true, items: []}, {}], + ], +} + +{ + name: "gb021: 8 nodes, switch*, expr, table*, switch*, expr, loop expr, expr, expr", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["not (vip)", ""]}, + {expression: "e2", passThrough: true, fields: { + k259: "vip", + k260: "(a ?? -1)", + }}, + {table: "t3", hit: "collect", inputs: ["s", "b"], outputs: ["k261", "k262"], outputPath: "o.p", rules: [ + ["startsWith($, 'x')", "-1", "2", "(tier ?? 'none')"], + ["null", "not(5)", "(a ?? -1) % 7", "(s ?? '?')"], + ]}, + {switch: "s4", hit: "collect", when: ["score > ((a ?? 0))", "(score ?? 0) != (score ?? -1)"]}, + {expression: "e5", passThrough: true, fields: { + k263: "score ?? tier", + }}, + {expression: "e6", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "lines", fields: { + "g.k264": "string((2.25) <= ((qty ?? -1)))", + }}, + {expression: "e7", passThrough: true, outputPath: "out", fields: { + k265: "k259", + k266: "(not (((k259 ?? false))) ? lower(string(false)) : ((true) ? (vip ? tier : (tier ?? '?')) : trim(s)))", + k267: "(not (b < 0) ? (s ?? '?') : string(len(filter(items ?? [], #.tag == 'gold'))) + '' + (tier ?? '?'))", + }}, + {expression: "e8", passThrough: true, fields: { + k268: "abs((score ?? -1) * ((vip ?? false) ? (b ?? 1) : (k260 ?? 1)))", + k269: "trim(s) + '-' + string((b ?? 0) * (k260 ?? 1))", + k270: "2 + (score ?? 1) - 0.5 in [1..100]", + "m.k271": "round((a ?? k263 ?? 0))", + }}, + ], + edges: [ + "input -> s1", + "s1:0 -> e2", + "s1:1 -> t3", + "input -> t3", + "e2 -> s4", + "e2 -> e5", + "t3 -> e5", + "e5 -> e6", + "input -> e6", + "s4:1 -> e7", + "e6 -> e8", + "s4:0 -> output", + "e7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{b: {v: 1}, score: -1, vip: true, s: "zz", tier: "gold", items: [{price: 0, qty: true, tag: ""}, {price: 2.5, tag: "x"}]}, "!error"], + [{score: 11, vip: false, s: "Gold", a: -25, tier: "Gold"}, "!error"], + [{b: -0.1, score: -25, vip: false, s: "gold", a: 3, tier: "a", items: [{price: 21, qty: 50, tag: ""}, {price: 7, qty: 0.1, tag: null}, {price: null, qty: 0.5, tag: "x"}, {price: 3, qty: 2.5, tag: "gold"}]}, {a: 3, b: -0.1, items: [{price: 21, qty: 50, tag: ""}, {price: 7, qty: 0.1, tag: null}, {price: null, qty: 0.5, tag: "x"}, {price: 3, qty: 2.5, tag: "gold"}], k259: false, k260: 3, k263: -25, k268: 75, k269: "gold--0.3", k270: false, lines: [{g: {k264: "true"}, price: 21, qty: 50, tag: ""}, {g: {k264: "false"}, price: 7, qty: 0.1, tag: null}, {g: {k264: "false"}, price: null, qty: 0.5, tag: "x"}, {g: {k264: "true"}, price: 3, qty: 2.5, tag: "gold"}], m: {k271: 3}, o: {p: []}, s: "gold", score: -25, tier: "a", vip: false}], + [{b: -25, s: "Gold", a: 99, tier: "gold ", items: [{price: 10, qty: 7, tag: "b"}, {price: 0.1, qty: 1000000000000000000000, tag: "gold "}]}, {a: 99, b: -25, items: [{price: 10, qty: 7, tag: "b"}, {price: 0.1, qty: 1000000000000000000000, tag: "gold "}], k268: 1, k269: "Gold--25", k270: true, lines: [{g: {k264: "true"}, price: 10, qty: 7, tag: "b"}, {g: {k264: "true"}, price: 0.1, qty: 1000000000000000000000, tag: "gold "}], m: {k271: 99}, o: {p: []}, s: "Gold", tier: "gold "}], + [{b: 18, score: 101, vip: true, s: "silver", a: 2, tier: "x", items: [{price: "abc", qty: 99, tag: "silver"}, {price: 10, qty: 7, tag: null}, {price: 101, qty: 50, tag: "Gold"}, {price: 10, qty: 5, tag: "zz"}]}, {a: 2, b: 18, items: [{price: "abc", qty: 99, tag: "silver"}, {price: 10, qty: 7, tag: null}, {price: 101, qty: 50, tag: "Gold"}, {price: 10, qty: 5, tag: "zz"}], k268: 1818, k269: "silver-18", k270: false, lines: [{g: {k264: "true"}, price: "abc", qty: 99, tag: "silver"}, {g: {k264: "true"}, price: 10, qty: 7, tag: null}, {g: {k264: "true"}, price: 101, qty: 50, tag: "Gold"}, {g: {k264: "true"}, price: 10, qty: 5, tag: "zz"}], m: {k271: 2}, o: {p: []}, s: "silver", score: 101, tier: "x", vip: true}], + [{b: 0.5, score: null, vip: true, s: "", a: {v: 1}, tier: null, items: [{price: 0, qty: 1000, tag: "gold"}, {price: 5, qty: 1000, tag: null}, {price: 101, qty: 0, tag: "gold"}]}, "!error"], + [{score: -25, vip: false, s: "", tier: null, items: [{price: 1000, qty: 29, tag: ""}]}, {items: [{price: 1000, qty: 29, tag: ""}], k259: false, k260: -1, k263: -25, k268: 25, k269: "-0", k270: false, lines: [{g: {k264: "true"}, price: 1000, qty: 29, tag: ""}], m: {k271: -25}, o: {p: []}, s: "", score: -25, vip: false}], + [{b: 2.5, score: 0.5, vip: true, s: "gold", a: [1], tier: "zz", items: [{price: -0.1, qty: 3, tag: "Gold"}, {price: -25, qty: 7, tag: "gold "}, {price: 0, qty: 19.99, tag: "Gold"}]}, "!error"], + [{b: 1, score: -0.1, vip: true, s: "gold ", a: -1, tier: "gold ", items: [{price: 101, qty: 2.5, tag: null}]}, {a: -1, b: 1, items: [{price: 101, qty: 2.5, tag: null}], k268: 0.1, k269: "gold-1", k270: true, lines: [{g: {k264: "true"}, price: 101, qty: 2.5, tag: null}], m: {k271: -1}, o: {p: []}, s: "gold ", score: -0.1, tier: "gold ", vip: true}], + [{score: null, vip: true, s: "", a: 101, tier: "", items: 3}, "!error"], + [{b: 3, score: 2.5, vip: true, s: {t: "x"}, a: 2.5, tier: "bronze", items: [{price: 0.5, qty: 5, tag: ""}, {price: 91, qty: 31, tag: "zz"}]}, "!error"], + [{b: 50, score: -0.1, vip: false, s: "bronze", a: 0.1, tier: "silver", items: [{price: 18, qty: 2, tag: ""}]}, {a: 0.1, b: 50, items: [{price: 18, qty: 2, tag: ""}], k259: false, k260: 0.1, k263: -0.1, k268: 0.01, k269: "bronze-5.0", k270: true, lines: [{g: {k264: "false"}, price: 18, qty: 2, tag: ""}], m: {k271: 0}, o: {p: []}, s: "bronze", score: -0.1, tier: "silver", vip: false}], + [{b: 10, score: 5, s: "gold ", a: 1, tier: "Gold", items: [{price: 18, qty: 7, tag: "Gold"}, {price: -25, qty: 2.5, tag: ""}]}, {a: 1, b: 10, items: [{price: 18, qty: 7, tag: "Gold"}, {price: -25, qty: 2.5, tag: ""}], k268: 5, k269: "gold-10", k270: true, lines: [{g: {k264: "true"}, price: 18, qty: 7, tag: "Gold"}, {g: {k264: "true"}, price: -25, qty: 2.5, tag: ""}], m: {k271: 1}, o: {p: []}, s: "gold ", score: 5, tier: "Gold"}], + [{b: 5, score: 7, vip: "true", s: "b", a: 99, tier: "gold ", items: [{price: 19.99, qty: -25, tag: "zz"}, {price: null, tag: "Gold"}]}, "!error"], + [{b: -1, score: 8, vip: true, a: 5, tier: ["gold"], items: []}, "!error"], + [{b: 18, score: 5, vip: null, s: "b", a: 19.99, tier: "Gold", items: [{price: -25, qty: 18, tag: "gold "}, {price: 0.1, tag: 5}]}, {a: 19.99, b: 18, items: [{price: -25, qty: 18, tag: "gold "}, {price: 0.1, tag: 5}], k268: 5, k269: "b-18", k270: true, lines: [{g: {k264: "true"}, price: -25, qty: 18, tag: "gold "}, {g: {k264: "false"}, price: 0.1, tag: 5}], m: {k271: 20}, o: {p: []}, s: "b", score: 5, tier: "Gold"}], + [{b: 100, score: 1000, vip: 0, s: "zz", a: 21, tier: "gold ", items: []}, "!error"], + [{b: 99, score: 45, vip: null, s: "gold ", a: 43, tier: "a", items: [{price: 2, qty: 19.99, tag: ""}], extra: {deep: {x: 1}}}, {a: 43, b: 99, extra: {deep: {x: 1}}, items: [{price: 2, qty: 19.99, tag: ""}], k268: 45, k269: "gold-99", k270: true, lines: [{g: {k264: "true"}, price: 2, qty: 19.99, tag: ""}], m: {k271: 43}, o: {p: []}, s: "gold ", score: 45, tier: "a"}], + [{b: -1, score: 11, vip: true, s: "bronze", a: 101, tier: "b", items: [{price: null, qty: 50, tag: "silver"}, {price: {v: 1}, qty: -25, tag: "bronze"}, {price: -1, qty: 18, tag: "bronze"}, {price: null, qty: 100, tag: "zz"}]}, {a: 101, b: -1, items: [{price: null, qty: 50, tag: "silver"}, {price: {v: 1}, qty: -25, tag: "bronze"}, {price: -1, qty: 18, tag: "bronze"}, {price: null, qty: 100, tag: "zz"}], k268: 11, k269: "bronze--1", k270: true, lines: [{g: {k264: "true"}, price: null, qty: 50, tag: "silver"}, {g: {k264: "false"}, price: {v: 1}, qty: -25, tag: "bronze"}, {g: {k264: "true"}, price: -1, qty: 18, tag: "bronze"}, {g: {k264: "true"}, price: null, qty: 100, tag: "zz"}], m: {k271: 101}, o: {p: []}, s: "bronze", score: 11, tier: "b", vip: true}], + [{b: 50, score: 50, vip: true, s: "silver", a: 0, tier: 5}, "!error"], + [{b: 21, score: -0.1, vip: true, s: "silver", a: 28, tier: "bronze", items: [{price: 1000000000000000000000, qty: 0.5, tag: "gold "}, {price: -0.1, qty: 18, tag: "b"}]}, {a: 28, b: 21, items: [{price: 1000000000000000000000, qty: 0.5, tag: "gold "}, {price: -0.1, qty: 18, tag: "b"}], k268: 2.1, k269: "silver-21", k270: true, lines: [{g: {k264: "false"}, price: 1000000000000000000000, qty: 0.5, tag: "gold "}, {g: {k264: "true"}, price: -0.1, qty: 18, tag: "b"}], m: {k271: 28}, o: {p: []}, s: "silver", score: -0.1, tier: "bronze", vip: true}], + [{b: 19.99, score: 5, vip: false, s: "b", a: 0.5, tier: "a", items: [{price: 10, qty: 101, tag: ""}]}, {a: 0.5, b: 19.99, items: [{price: 10, qty: 101, tag: ""}], k259: false, k260: 0.5, k263: 5, k268: 2.5, k269: "b-9.995", k270: true, lines: [{g: {k264: "true"}, price: 10, qty: 101, tag: ""}], m: {k271: 1}, o: {p: []}, s: "b", score: 5, tier: "a", vip: false}], + [{b: 76, score: 2.5, vip: true, s: "b", a: 0.5, tier: null, items: [{qty: [1], tag: "zz"}, {price: -0.1, tag: "a"}]}, "!error"], + [{b: 18, score: 101, vip: true, s: "zz", a: 101, tier: "x", items: [], extra: 1}, {a: 101, b: 18, extra: 1, items: [], k268: 1818, k269: "zz-18", k270: false, lines: [], m: {k271: 101}, o: {p: []}, s: "zz", score: 101, tier: "x", vip: true}], + ], +} + +{ + name: "gb022: 9 nodes, table, loop expr, expr, table, expr, switch, switch*, expr, table", + graph: { + nodes: [ + {table: "t1", inputs: ["b"], outputs: ["k272"], outputPath: "res", rules: [ + ["", "true"], + ["> 100", "((a ?? 1) >= ((a ?? -1)) / 3) or ((flag ?? false))"], + ]}, + {expression: "e2", inputField: "items", executionMode: "loop", outputPath: "lines", fields: { + k273: "(-4 + (price ?? 1) in [-5..5])", + }}, + {expression: "e3", passThrough: true, fields: { + "m.k274": "abs(1 % 2 * 10 + 3)", + k275: "null", + k276: "null", + }}, + {table: "t4", inputs: ["m.k274", "m.k274", "res.k272"], outputs: ["k277"], rules: [ + ["!= 21", "< 1", "null", "false"], + ["", ">= -1", "null", "false"], + ["", "", "", "false"], + ]}, + {expression: "e5", passThrough: true, fields: { + "m.k278": "min([((b ?? -1)), round(a)]) + sum(map(items ?? [], #.price ?? 0))", + k279: "len(string(b) + '-' + '')", + k280: "len(code + ' ' + '') * ($.k279 ?? 0)", + k281: "b", + }}, + {switch: "s6", when: ["(res.k272 ?? false)"]}, + {switch: "s7", hit: "collect", when: ["(0 % 3) < min([(-4), (0.5)])", "(-4 != (0) / 4) or (res.k272)"]}, + {expression: "e8", passThrough: true, outputPath: "res", fields: { + "res.k282": "(b ?? b ?? 0)", + }}, + {table: "t9", inputs: ["(0 ?? 1 ?? 0) - (0)"], outputs: ["k283", "k284"], passThrough: true, outputPath: "res", rules: [ + ["18, 68", "2", "0"], + ["not(21)", "0 % 2", "10"], + ["100, 110", "10", "0"], + ["< 18", "10", "-(len(string((res.k272 ?? false))))"], + ]}, + ], + edges: [ + "input -> t1", + "input -> e2", + "e2 -> e3", + "e3 -> t4", + "t1 -> t4", + "input -> e5", + "e2 -> e5", + "t1 -> s6", + "s6:0 -> s7", + "input -> e8", + "s7:0 -> t9", + "e2 -> output", + "t4 -> output", + "e5 -> output", + "s7:1 -> output", + "e8 -> output", + "t9 -> output", + ], + }, + cases: [ + [{s: "b", flag: false, code: "Gold", b: 1, items: [{price: 21, qty: 99, tag: "gold "}, {qty: null}], nums: [50, 10], a: 10}, {a: 10, b: 1, code: "Gold", flag: false, items: [{price: 21, qty: 99, tag: "gold "}, {qty: null}], k277: false, k279: 2, k280: 10, k281: 1, lines: [{k273: false}, {k273: true}], m: {k278: 22}, nums: [50, 10], res: {k272: true, res: {k282: 1}}, s: "b"}], + [{s: null, flag: true, code: "x", b: 21, items: [], nums: [3], a: 21, extra: 1}, {a: 21, b: 21, code: "x", extra: 1, flag: true, items: [], k277: false, k279: 3, k280: 6, k281: 21, lines: [], m: {k278: 21}, nums: [3], res: {k272: true, res: {k282: 21}}}], + [{s: {t: "x"}, flag: false, code: 5, b: 7, items: null, nums: [-17]}, "!error"], + [{s: "gold ", flag: false, code: "Gold", items: [{price: 2.5, qty: {v: 1}, tag: "a"}, {qty: true, tag: "gold"}, {price: null, qty: 18, tag: "b"}, {price: 21, qty: 100, tag: ""}], nums: [99], a: -1}, {a: -1, code: "Gold", flag: false, items: [{price: 2.5, qty: {v: 1}, tag: "a"}, {qty: true, tag: "gold"}, {price: null, qty: 18, tag: "b"}, {price: 21, qty: 100, tag: ""}], k277: false, k279: 5, k280: 25, lines: [{k273: true}, {k273: true}, {k273: true}, {k273: false}], m: {k278: 22.5}, nums: [99], res: {k272: true, res: {k282: 0}}, s: "gold "}], + [{s: "gold", flag: false, code: "x", items: [{price: "abc", qty: 21, tag: "gold "}, {price: 1000, qty: 2.5, tag: "silver"}, {price: 0.5, qty: 3, tag: "silver"}, {price: {v: 1}, qty: 0.5, tag: null}], nums: [0.1], a: 101}, "!error"], + [{s: "silver", code: "a", b: -0.1, items: [{price: 1000000000000000000000, qty: 18, tag: ""}, {price: 1000000000000000000000, qty: null, tag: "a"}], nums: [{x: 1}], a: -25}, {a: -25, b: -0.1, code: "a", items: [{price: 1000000000000000000000, qty: 18, tag: ""}, {price: 1000000000000000000000, qty: null, tag: "a"}], k277: false, k279: 5, k280: 10, k281: -0.1, lines: [{k273: false}, {k273: false}], m: {k278: 1999999999999999999975}, nums: [{x: 1}], res: {k272: true, res: {k282: -0.1}}, s: "silver"}], + [{s: {t: "x"}, flag: true, code: "gold", items: null, nums: 7, a: 99}, "!error"], + [{s: "silver", flag: true, code: null, items: [{tag: "bronze"}], nums: null, a: {v: 1}}, "!error"], + [{s: "b", flag: true, b: 1, items: [{price: -1, qty: 1, tag: "bronze"}, {price: 3, qty: null, tag: null}], nums: [50, 2.5, 50, -0.1, 0.5], a: 0.1}, "!error"], + [{s: "a", code: "bronze", b: null, items: 3, nums: [{x: 1}], a: 0.5}, "!error"], + [{s: null, flag: false, code: "zz", b: 44, items: [{price: true, qty: 50, tag: "silver"}], nums: "1,2", a: null}, "!error"], + [{s: "bronze", flag: "no", code: "zz", b: null, items: [], nums: [100, 1000000000000000000000, 45, 2, 0.1], a: null, extra: {deep: {x: 1}}}, "!error"], + [{s: "a", flag: 0, code: "a", b: -0.1, a: 1000000000000000000000}, "!error"], + [{s: "", flag: false, code: "bronze", b: -0.1, items: [{price: 100, qty: 1000000000000000000000, tag: "a"}, {price: 21}], nums: [2.5, 99, -14, 1, 1], a: "5", extra: [1, 2]}, "!error"], + [{s: "silver", flag: true, code: "bronze", b: -0.1, items: [{price: true, qty: 0.1, tag: "gold "}, {price: 63, qty: 2, tag: "gold "}], nums: [{x: 1}], extra: {deep: {x: 1}}}, "!error"], + [{s: "x", flag: "no", code: 5, b: 99, items: [{price: -25, qty: true}, {price: 7, qty: -1, tag: "gold "}, {price: 1000000000000000000000, qty: {v: 1}, tag: "x"}, {price: true, qty: 11, tag: {t: "x"}}], nums: [19.99, 7, 1000000000000000000000], a: 0.1, extra: 1}, "!error"], + [{s: "b", flag: false, code: "silver", items: [{price: 5, qty: -1, tag: "gold"}, {price: 19.99, qty: 11, tag: "b"}], nums: [100], a: [1]}, "!error"], + [{s: "", flag: 0, b: 11, items: [{price: 101, qty: 2.5, tag: "Gold"}, {price: 11, qty: 2.5, tag: "x"}, {price: 100, qty: 1000000000000000000000, tag: "b"}, {price: 2.5, qty: 18, tag: "a"}], nums: [{x: 1}], a: 19.99, extra: {deep: {x: 1}}}, "!error"], + [{s: null, flag: true, code: "silver", b: "5", items: [{price: 19.99, qty: 18, tag: "a"}, {price: 2, qty: "5", tag: {t: "x"}}, {price: -25, qty: 0.5, tag: "Gold"}, {price: 1000, qty: 21, tag: "silver"}], nums: 7, a: 21}, "!error"], + [{s: "Gold", flag: false, code: "", b: 19.99, items: 3, nums: [18, 0], a: -1}, "!error"], + [{code: 5, b: "abc", items: [], nums: [101, 2, 0, -25, 2.5], a: "5"}, "!error"], + ], +} + +{ + name: "gb023: 6 nodes, table, table*, switch*, expr, expr, table", + graph: { + nodes: [ + {table: "t1", inputs: ["s"], outputs: ["k285", "k286"], outputPath: "out", rules: [ + ["$ != 'a'", "'mid'", "true"], + ["", "(s ?? '?')", "(n ?? -1) + (score ?? 0) + (a ?? 0) in [-5..5]"], + ["$ != ''", "'low'", "true"], + ["startsWith($, 'a')", "''", "true"], + ["not('x')", "'x'", "false"], + ["not('')", "'high'", "false"], + ["", "'gold'", "true"], + ]}, + {table: "t2", hit: "collect", inputs: ["out.k286"], outputs: ["k287", "k288"], outputPath: "o.p", rules: [ + ["$ == true", "true", "1"], + ["", "true", "10"], + ["false", "false", "0"], + ["true", "false", "1"], + ["", "false", "10"], + ]}, + {switch: "s3", hit: "collect", when: ["-(ceil(3)) < 0 % 7 + len('')", "(0 >= (1)) and (a == null)", "true"]}, + {expression: "e4", outputPath: "o.p", fields: { + k289: "-(-4)", + }}, + {expression: "e5", passThrough: true, fields: { + k290: "-(1 - (0))", + }}, + {table: "t6", inputs: ["string(0.5 + 100)", "'x'", "(-(0))"], outputs: ["k291"], rules: [ + ["'', 'gold'", "", "!= 1", "false"], + ["", "null", "< 5", "false"], + ["'a'", "startsWith($, 'a')", ">= 5", "false"], + ["not('')", "'x', 'gold'", "", "true"], + ["'silver'", "", "", "true"], + ["null", "null", "(100..150)", "false"], + ["", "", "", "false"], + ]}, + ], + edges: [ + "input -> t1", + "input -> t2", + "t1 -> t2", + "t2 -> s3", + "t2 -> e4", + "s3:1 -> e5", + "s3:2 -> t6", + "e4 -> output", + "e5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{s: "zz", score: 18, n: null, tier: "", a: true, vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{s: "gold", score: 3, n: null, b: 11, tier: "gold", a: 0, vip: false, extra: "e"}, {k291: false, o: {p: {k289: 4}}}], + [{score: 18, n: 3, b: -1, a: 0.1, vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "", score: -0.1, b: 1000, tier: "silver", a: null, vip: false, extra: 1}, {k291: false, o: {p: {k289: 4}}}], + [{s: "x", score: 3, n: 1000000000000000000000, b: 1, tier: "a", vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{s: "zz", score: 5, n: 21, b: 18, tier: "gold ", a: 100, vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "Gold", score: 2.5, n: 1000, b: 19.99, tier: "Gold", a: 0.5, vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{s: null, n: 18, b: null, tier: "zz", vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "silver", score: 0, n: 101, tier: "Gold", a: 101, vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "gold ", score: 3, n: null, b: -12, tier: "b", a: 101, vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{s: "Gold", score: -25, n: 99, b: -0.1, tier: "Gold", a: 1, vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "bronze", score: 2, n: "5", b: null, tier: "silver", vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "b", score: 3, n: 2, tier: "a", a: null, vip: null}, {k291: false, o: {p: {k289: 4}}}], + [{s: "gold ", score: -25, n: 0, b: 21, a: -20, vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{score: 100, n: 7, b: -16, tier: ["gold"], a: -1, vip: true, extra: 1}, {k291: false, o: {p: {k289: 4}}}], + [{s: "gold", score: 0.5, n: {v: 1}, b: 1000, tier: "", a: 0.1, vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{s: "gold ", score: 0.5, n: 99, b: null, tier: "gold", a: 1000, vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "silver", score: -0.1, n: 1, tier: "silver", a: null, vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{s: "x", n: 99, tier: "silver", a: 19.99, vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "b", n: 99, b: null, tier: "x", a: -0.1, vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{s: "a", score: 100, n: -1, tier: "", a: 0.5, vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "x", score: 101, n: 7, b: 100, tier: "a", a: 2.5, vip: false}, {k291: false, o: {p: {k289: 4}}}], + [{s: "x", score: -25, n: 2, b: 1000, tier: "silver", a: 11, vip: true, extra: {deep: {x: 1}}}, {k291: false, o: {p: {k289: 4}}}], + [{s: "b", n: 0, b: 2, tier: "a", a: 10, vip: true}, {k291: false, o: {p: {k289: 4}}}], + [{s: "gold", score: 0.5, b: {v: 1}, tier: "", a: 104, vip: false, extra: [1, 2]}, {k291: false, o: {p: {k289: 4}}}], + [{s: "Gold", score: -1, n: null, b: null, tier: "gold", a: 1000000000000000000000, vip: null}, {k291: false, o: {p: {k289: 4}}}], + ], +} + +{ + name: "gb024: 8 nodes, loop expr, expr, expr, switch*, expr, expr, table, table", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", outputPath: "lines", fields: { + "m.k292": "(price ?? 1)", + k293: "-(3)", + k294: "((true) ? string((price ?? -1) == price) : string(not (false)))", + }}, + {expression: "e2", fields: { + k296: "-4 <= 100", + k297: "max([2 * abs(2), ('none' == 'gold' ? (1) : len('none'))])", + }}, + {expression: "e3", passThrough: true, fields: { + k298: "k297", + k299: "not (string(k296) != 'x')", + }}, + {switch: "s4", hit: "collect", when: ["len('') - k297 != ((k297)) / 0.5", "(k296 ?? false)", ""]}, + {expression: "e5", passThrough: true, fields: { + k300: "cust.active ?? k299", + k301: "endsWith((endsWith('x', '') ? string(len(filter(items ?? [], #.tag == 'gold'))) : `${(b ?? 0)}-${cust.tier}`), 'g')", + k302: "'x'", + "g.k303": "k299 ?? price", + }}, + {expression: "e6", passThrough: true, fields: { + k304: "`${(k297 ?? 1)}-${'A-1'}`", + }}, + {table: "t7", inputs: ["k296", "k297", "k297"], outputs: ["k305", "k306"], rules: [ + ["$ == true", "", "> 21", "false", "2"], + ["false", "<= 4", "", "false", "10"], + ]}, + {table: "t8", inputs: ["k297"], outputs: ["k300", "k308"], rules: [ + ["", "false", "'gold'"], + ["!= 0", "true", "''"], + ["< 21", "false", "'low'"], + ["not(10)", "true", "'none'"], + ["", "true", "'high'"], + ["1", "true", "'high'"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "e2 -> e3", + "e2 -> s4", + "e3 -> e5", + "input -> e5", + "s4:1 -> e6", + "e6 -> t7", + "s4:0 -> t8", + "e2 -> output", + "s4:2 -> output", + "e5 -> output", + "t7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{b: -25, items: [{price: 101, qty: 100, tag: "b"}, {price: -25, qty: -0.1, tag: null}], cust: "cust"}, {b: -25, cust: "cust", g: {k303: false}, items: [{price: 101, qty: 100, tag: "b"}, {price: -25, qty: -0.1, tag: null}], k296: true, k297: 4, k298: 4, k299: false, k300: false, k301: false, k302: "x", k308: "gold"}], + [{price: 100, b: 1, items: [{price: -25, qty: null, tag: ""}, {price: 0.5, qty: 10, tag: "x"}, {price: {v: 1}, qty: 19.99, tag: "b"}], cust: {age: 7, tier: "bronze", active: true}}, {b: 1, cust: {active: true, age: 7, tier: "bronze"}, g: {k303: false}, items: [{price: -25, qty: null, tag: ""}, {price: 0.5, qty: 10, tag: "x"}, {price: {v: 1}, qty: 19.99, tag: "b"}], k296: true, k297: 4, k298: 4, k299: false, k300: true, k301: false, k302: "x", k308: "gold", price: 100}], + [{price: 5, b: [1], items: [{price: 5, qty: 5, tag: ""}], cust: {age: null, tier: "", active: true}}, {b: [1], cust: {active: true, age: null, tier: ""}, g: {k303: false}, items: [{price: 5, qty: 5, tag: ""}], k296: true, k297: 4, k298: 4, k299: false, k300: true, k301: false, k302: "x", k308: "gold", price: 5}], + [{price: true, b: 3, items: [{price: 18, qty: 21, tag: "gold "}, {price: 100, qty: 3, tag: "gold "}], extra: 1}, {b: 3, extra: 1, g: {k303: false}, items: [{price: 18, qty: 21, tag: "gold "}, {price: 100, qty: 3, tag: "gold "}], k296: true, k297: 4, k298: 4, k299: false, k300: false, k301: false, k302: "x", k308: "gold", price: true}], + [{price: null, b: 50, items: [{price: 10, qty: 11, tag: "Gold"}, {price: 5, qty: -25, tag: "zz"}], cust: null}, {b: 50, g: {k303: false}, items: [{price: 10, qty: 11, tag: "Gold"}, {price: 5, qty: -25, tag: "zz"}], k296: true, k297: 4, k298: 4, k299: false, k300: false, k301: false, k302: "x", k308: "gold"}], + [{price: {v: 1}, items: [{price: 18, qty: 101, tag: null}, {price: 2, qty: 0.5, tag: "gold "}, {price: 18, qty: 21, tag: "gold "}], cust: {age: -0.1, tier: {t: "x"}, active: true}, extra: 1}, {cust: {active: true, age: -0.1, tier: {t: "x"}}, extra: 1, g: {k303: false}, items: [{price: 18, qty: 101, tag: null}, {price: 2, qty: 0.5, tag: "gold "}, {price: 18, qty: 21, tag: "gold "}], k296: true, k297: 4, k298: 4, k299: false, k300: true, k301: false, k302: "x", k308: "gold", price: {v: 1}}], + [{price: [1], b: 99, items: [{price: 100, qty: null, tag: "silver"}, {price: -1, qty: 1, tag: "silver"}], cust: {age: 1, tier: "a", active: false}}, {b: 99, cust: {active: false, age: 1, tier: "a"}, g: {k303: false}, items: [{price: 100, qty: null, tag: "silver"}, {price: -1, qty: 1, tag: "silver"}], k296: true, k297: 4, k298: 4, k299: false, k300: false, k301: false, k302: "x", k308: "gold", price: [1]}], + [{price: null, b: 21, cust: {age: 7, tier: "silver", active: true}}, "!error"], + [{price: 14, b: 0, items: [{price: -1, qty: 10, tag: "gold"}]}, {b: 0, g: {k303: false}, items: [{price: -1, qty: 10, tag: "gold"}], k296: true, k297: 4, k298: 4, k299: false, k300: false, k301: false, k302: "x", k308: "gold", price: 14}], + [{price: 1, b: 21, items: [], cust: {age: -1, tier: "x", active: false}}, {b: 21, cust: {active: false, age: -1, tier: "x"}, g: {k303: false}, items: [], k296: true, k297: 4, k298: 4, k299: false, k300: false, k301: false, k302: "x", k308: "gold", price: 1}], + [{b: -1, items: [], cust: {age: 19.99, tier: "x", active: false}}, {b: -1, cust: {active: false, age: 19.99, tier: "x"}, g: {k303: false}, items: [], k296: true, k297: 4, k298: 4, k299: false, k300: false, k301: false, k302: "x", k308: "gold"}], + [{price: 99, items: [{price: 1000000000000000000000, qty: 100, tag: "gold"}, {price: 100, qty: -0.1, tag: "x"}], cust: {age: 5, tier: "silver", active: false}}, {cust: {active: false, age: 5, tier: "silver"}, g: {k303: false}, items: [{price: 1000000000000000000000, qty: 100, tag: "gold"}, {price: 100, qty: -0.1, tag: "x"}], k296: true, k297: 4, k298: 4, k299: false, k300: false, k301: false, k302: "x", k308: "gold", price: 99}], + [{price: "abc", b: 10, items: [{price: 5, qty: 5, tag: "a"}, {price: 5, qty: 1, tag: "a"}, {price: 1000, qty: [1], tag: "b"}, {price: 0.5, qty: 1000000000000000000000, tag: "x"}], cust: {age: 18, tier: "zz", active: true}}, {b: 10, cust: {active: true, age: 18, tier: "zz"}, g: {k303: false}, items: [{price: 5, qty: 5, tag: "a"}, {price: 5, qty: 1, tag: "a"}, {price: 1000, qty: [1], tag: "b"}, {price: 0.5, qty: 1000000000000000000000, tag: "x"}], k296: true, k297: 4, k298: 4, k299: false, k300: true, k301: false, k302: "x", k308: "gold", price: "abc"}], + ], +} + +{ + name: "gb025: 9 nodes, switch*, switch, switch*, loop expr, expr, loop expr, expr, expr, expr", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["(n ?? -1) < -((n ?? 1))", "code == null", "false", ""]}, + {switch: "s2", when: ["((code ?? '') in ['gold', 'silver', 'a'])", "round((n ?? 1)) * ceil((price ?? -1)) == ((n ?? -1) + (price ?? -1))", "((price ?? 0) * n) in [0..10]", ""]}, + {switch: "s3", hit: "collect", when: ["(price ?? 1) != (n ?? -1)"]}, + {expression: "e4", inputField: "items", executionMode: "loop", outputPath: "o.p", fields: { + k309: "(tag ?? '')", + }}, + {expression: "e5", passThrough: true, outputPath: "res", fields: { + k311: "-((n ?? -1) * (n ?? 0))", + "res.k312": "ceil((count(nums ?? [], # > 10)))", + k313: "(code ?? '') + ' ' + string(code in ['gold', 'silver', 'a'])", + }}, + {expression: "e6", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k314: "price", + }}, + {expression: "e7", fields: { + k309: "code == null", + k316: "max([(true ? (price ?? -1) : (n ?? 0)), (price ?? n ?? 0)]) - price", + }}, + {expression: "e8", passThrough: true, outputPath: "o.p", fields: { + k317: "-4", + "m.k318": "(code ?? '')", + "m.k319": "-(-(res.k311))", + k320: "(res.res.k312 ?? res.res.k312 ?? 0)", + }}, + {expression: "e9", passThrough: true, fields: { + k321: "(false ? (res.k311 ?? 1) : $nodes.e5.k311)", + "res.k322": "code ?? n", + k323: "price ?? res.res.k312", + }}, + ], + edges: [ + "input -> s1", + "s1:0 -> s2", + "s1:1 -> s3", + "s2:2 -> e4", + "s2:2 -> e5", + "e5 -> e6", + "s1:1 -> e7", + "e6 -> e8", + "e6 -> e9", + "s1:2 -> output", + "s1:3 -> output", + "s2:0 -> output", + "s2:3 -> output", + "e4 -> output", + "e7 -> output", + "e8 -> output", + "e9 -> output", + ], + }, + cases: [ + [{price: null, nums: [11], n: 101, code: "gold", items: []}, {code: "gold", items: [], n: 101, nums: [11]}], + [{price: -0.1, nums: [0], n: null, code: "a", items: [], extra: {deep: {x: 1}}}, {code: "a", extra: {deep: {x: 1}}, items: [], nums: [0], price: -0.1}], + [{price: null, nums: [{x: 1}], n: 10, code: "gold ", items: [{price: 1000, qty: 21, tag: "a"}, {price: "abc", qty: [1], tag: ""}], extra: {deep: {x: 1}}}, {code: "gold ", extra: {deep: {x: 1}}, items: [{price: 1000, qty: 21, tag: "a"}, {price: "abc", qty: [1], tag: ""}], n: 10, nums: [{x: 1}]}], + [{price: true, nums: ["1", 2], n: 19.99, code: "bronze", items: [{price: null}]}, {code: "bronze", items: [{price: null}], n: 19.99, nums: ["1", 2], price: true}], + [{price: [1], nums: [], n: 50, code: {t: "x"}, items: []}, {code: {t: "x"}, items: [], n: 50, nums: [], price: [1]}], + [{nums: [], n: 1, code: "", items: [{price: true, qty: 11, tag: "b"}, {price: 2, qty: "5", tag: "Gold"}]}, {code: "", items: [{price: true, qty: 11, tag: "b"}, {price: 2, qty: "5", tag: "Gold"}], n: 1, nums: []}], + [{price: 99, nums: [-1], n: null, code: ["gold"], items: [{price: 5, qty: 0, tag: "bronze"}, {price: 19.99, qty: 101, tag: "zz"}, {price: -25, qty: 5, tag: "bronze"}]}, {code: ["gold"], items: [{price: 5, qty: 0, tag: "bronze"}, {price: 19.99, qty: 101, tag: "zz"}, {price: -25, qty: 5, tag: "bronze"}], nums: [-1], price: 99}], + [{price: 21, nums: [1000000000000000000000, 7], n: 7, code: "bronze", items: [{price: 18, qty: 10, tag: null}]}, {code: "bronze", items: [{price: 18, qty: 10, tag: null}], n: 7, nums: [1000000000000000000000, 7], price: 21}], + [{price: 18, nums: [2.5, 1], n: 18, code: null, items: [{price: 101, qty: -25, tag: "Gold"}]}, {items: [{price: 101, qty: -25, tag: "Gold"}], k309: true, k316: 0, n: 18, nums: [2.5, 1], price: 18}], + [{nums: [{x: 1}], n: null, code: "bronze", items: [{price: 0.5, qty: 21, tag: "gold"}, {price: 7, qty: 2.5, tag: "bronze"}]}, {code: "bronze", items: [{price: 0.5, qty: 21, tag: "gold"}, {price: 7, qty: 2.5, tag: "bronze"}], nums: [{x: 1}]}], + [{nums: null, code: "gold ", items: [{price: 11, qty: -25, tag: "a"}]}, {code: "gold ", items: [{price: 11, qty: -25, tag: "a"}]}], + [{price: 26, nums: "1,2", n: 0.5, code: "x", items: [{price: 2.5, qty: 2.5, tag: "zz"}, {price: null, qty: "abc", tag: ""}, {price: 33, qty: 7, tag: "gold "}]}, {code: "x", items: [{price: 2.5, qty: 2.5, tag: "zz"}, {price: null, qty: "abc", tag: ""}, {price: 33, qty: 7, tag: "gold "}], n: 0.5, nums: "1,2", price: 26}], + [{price: 5, nums: [], n: 5, code: "bronze", items: [{price: true, qty: "5", tag: ""}, {price: 0.5, qty: 50, tag: ""}, {price: 1, qty: 19.99, tag: "gold "}]}, {code: "bronze", items: [{price: true, qty: "5", tag: ""}, {price: 0.5, qty: 50, tag: ""}, {price: 1, qty: 19.99, tag: "gold "}], n: 5, nums: [], price: 5}], + [{price: -25, nums: null, n: 1000, code: "x", items: [1, 2]}, {code: "x", items: [1, 2], n: 1000, price: -25}], + [{price: 50, nums: [100, 99, 11, 3, 5], n: 18, code: null, items: []}, {items: [], k309: true, k316: 0, n: 18, nums: [100, 99, 11, 3, 5], price: 50}], + [{price: "5", nums: ["1", 2], n: 0, code: "silver", items: null}, {code: "silver", n: 0, nums: ["1", 2], price: "5"}], + [{price: 7, nums: [], n: 1000, code: null}, {k309: true, k316: 0, n: 1000, nums: [], price: 7}], + [{price: -25, nums: [], code: "", items: [{price: 0, qty: 100, tag: "zz"}]}, {code: "", items: [{price: 0, qty: 100, tag: "zz"}], nums: [], price: -25}], + [{price: 101, nums: [], n: 5, code: null, items: [{price: true, qty: 82, tag: true}, {price: 21, qty: 11, tag: ""}], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, items: [{price: true, qty: 82, tag: true}, {price: 21, qty: 11, tag: ""}], k309: true, k316: 0, n: 5, nums: [], price: 101}], + ], +} + +{ + name: "gb026: 6 nodes, loop expr, loop expr, expr, table*, table, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "o.p", fields: { + k324: "contains(upper(tag), 'a')", + k325: "'A-1'", + k326: "price ?? price", + }}, + {expression: "e2", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "o.p", fields: { + k327: "(1)", + k328: "-((qty ?? 0))", + k329: "len(tag)", + }}, + {expression: "e3", passThrough: true, fields: { + k330: "b", + k327: "'gold'", + k332: "count(items ?? [], (#.qty ?? 0) > 1) != ($.k330 ?? 1) + (price ?? 0)", + k333: "price", + }}, + {table: "t4", hit: "collect", inputs: ["b", "-(price)"], outputs: ["k334"], outputPath: "lines", rules: [ + ["[5..15)", "", "false"], + ["(10..11)", "[5..6]", "true"], + ["< 50", "[5..10]", "string(round((b ?? 0))) in ['gold', 'silver', 'a']"], + ["$ > 10 and $ < 15", "[100..105]", "true"], + ["", "", "false"], + ]}, + {table: "t5", inputs: ["price"], outputs: ["k335", "k336"], rules: [ + ["!= 21", "string((items ?? [])[0].tag ?? 'none' != 'silver')", "(((false) or (false)))"], + ["not(100)", "'mid'", "true"], + ]}, + {expression: "e6", passThrough: true, fields: { + k337: "k327 ?? k327", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e2 -> e3", + "e1 -> t4", + "e2 -> t5", + "e3 -> e6", + "e1 -> output", + "t4 -> output", + "t5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{nums: 7, b: 0.1, price: 11}, "!error"], + [{nums: ["1", 2], b: -0.1, price: [1], items: [{price: 0.5, qty: null, tag: "x"}, {price: 2, qty: 50, tag: "bronze"}]}, "!error"], + [{nums: 7, price: true, items: [1, 2]}, "!error"], + [{nums: [5], b: 5, price: "abc"}, "!error"], + [{nums: [{x: 1}], b: {v: 1}, price: 18, items: [{price: 3, qty: 101, tag: "x"}, {price: "abc", qty: 10, tag: "Gold"}, {price: 0.5, qty: 2}]}, "!error"], + [{nums: [3, 3], b: 11, price: 11, items: [], extra: 1}, {b: 11, extra: 1, items: [], k327: "gold", k330: 11, k332: true, k333: 11, k335: "true", k336: false, k337: "gold", lines: [{k334: false}, {k334: false}], nums: [3, 3], o: {p: []}, price: 11}], + [{nums: [-1, 18, 2.5, 5, 18], price: 1000, items: [{price: -1, qty: 50, tag: "zz"}, {price: 2.5, qty: 1, tag: "b"}, {price: 2.5, qty: 2, tag: "b"}], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, items: [{price: -1, qty: 50, tag: "zz"}, {price: 2.5, qty: 1, tag: "b"}, {price: 2.5, qty: 2, tag: "b"}], k327: "gold", k332: true, k333: 1000, k335: "true", k336: false, k337: "gold", lines: [{k334: false}], nums: [-1, 18, 2.5, 5, 18], o: {p: [{k324: false, k325: "A-1", k326: -1, price: -1, qty: 50, tag: "zz"}, {k324: false, k325: "A-1", k326: 2.5, price: 2.5, qty: 1, tag: "b"}, {k324: false, k325: "A-1", k326: 2.5, price: 2.5, qty: 2, tag: "b"}]}, price: 1000}], + [{nums: ["1", 2], b: 2, items: [{price: "abc", qty: 0.5, tag: "silver"}, {price: 0.5, qty: 0, tag: "gold"}, {qty: null, tag: "b"}, {price: 101, qty: 2, tag: "gold "}]}, {b: 2, items: [{price: "abc", qty: 0.5, tag: "silver"}, {price: 0.5, qty: 0, tag: "gold"}, {qty: null, tag: "b"}, {price: 101, qty: 2, tag: "gold "}], k327: "gold", k330: 2, k332: true, k335: "false", k336: false, k337: "gold", lines: [{k334: false}], nums: ["1", 2], o: {p: [{k324: false, k325: "A-1", k326: "abc", price: "abc", qty: 0.5, tag: "silver"}, {k324: false, k325: "A-1", k326: 0.5, price: 0.5, qty: 0, tag: "gold"}, {k324: false, k325: "A-1", qty: null, tag: "b"}, {k324: false, k325: "A-1", k326: 101, price: 101, qty: 2, tag: "gold "}]}}], + [{nums: [19.99, 21, -0.1, 1000, 11], b: 50, price: 50, items: []}, {b: 50, items: [], k327: "gold", k330: 50, k332: true, k333: 50, k335: "true", k336: false, k337: "gold", lines: [{k334: false}], nums: [19.99, 21, -0.1, 1000, 11], o: {p: []}, price: 50}], + [{b: 2, price: "abc", items: [{price: 1, qty: {v: 1}, tag: "Gold"}], extra: {deep: {x: 1}}}, "!error"], + [{nums: [], b: 18, price: 11, items: [{price: 0.1, qty: null, tag: "b"}, {price: 1000, qty: 99, tag: "b"}]}, {b: 18, items: [{price: 0.1, qty: null, tag: "b"}, {price: 1000, qty: 99, tag: "b"}], k327: "gold", k330: 18, k332: true, k333: 11, k335: "true", k336: false, k337: "gold", lines: [{k334: false}], nums: [], o: {p: [{k324: false, k325: "A-1", k326: 0.1, price: 0.1, qty: null, tag: "b"}, {k324: false, k325: "A-1", k326: 1000, price: 1000, qty: 99, tag: "b"}]}, price: 11}], + [{nums: [], price: 2, items: [{price: 1000, qty: 100}, {price: 1000000000000000000000, qty: 1, tag: "gold"}, {price: 2, qty: 19.99, tag: "gold"}, {price: -25, qty: 5, tag: "gold"}]}, "!error"], + [{nums: [19.99, 5, 7], price: 2.5, items: [{price: 0.5, qty: 3, tag: "x"}, {price: -25, qty: 0, tag: "b"}]}, {items: [{price: 0.5, qty: 3, tag: "x"}, {price: -25, qty: 0, tag: "b"}], k327: "gold", k332: true, k333: 2.5, k335: "true", k336: false, k337: "gold", lines: [{k334: false}], nums: [19.99, 5, 7], o: {p: [{k324: false, k325: "A-1", k326: 0.5, price: 0.5, qty: 3, tag: "x"}, {k324: false, k325: "A-1", k326: -25, price: -25, qty: 0, tag: "b"}]}, price: 2.5}], + [{b: {v: 1}, price: 11, items: [{price: 2, qty: 2, tag: "Gold"}, {price: 0.5, qty: 2.5, tag: "gold"}, {price: 10, qty: 5, tag: 5}], extra: {deep: {x: 1}}}, "!error"], + [{nums: [2.5, 101], b: 3, price: 7, items: []}, {b: 3, items: [], k327: "gold", k330: 3, k332: true, k333: 7, k335: "true", k336: false, k337: "gold", lines: [{k334: false}], nums: [2.5, 101], o: {p: []}, price: 7}], + [{nums: [-1, 21], b: -0.1, items: [{price: -0.1, qty: -25, tag: null}, {price: null, qty: 19.99, tag: "b"}], extra: "e"}, "!error"], + [{nums: [19.99, 0.5], b: 101, price: 100, items: [{price: [1], qty: 52, tag: {t: "x"}}], extra: "e"}, "!error"], + [{nums: [-25], b: 10, price: 1000000000000000000000, items: [{price: 101, qty: 5, tag: "bronze"}, {price: -1, qty: 1000, tag: "gold "}, {price: {v: 1}, qty: "5"}]}, "!error"], + [{nums: [100, 0.1, 100, 10, 19.99], b: 7, price: 2, items: []}, {b: 7, items: [], k327: "gold", k330: 7, k332: true, k333: 2, k335: "true", k336: false, k337: "gold", lines: [{k334: false}, {k334: false}], nums: [100, 0.1, 100, 10, 19.99], o: {p: []}, price: 2}], + [{nums: [0.1], b: [1], price: "5", items: [{price: 10, qty: 19.99, tag: ["gold"]}, {price: null, qty: 11, tag: "gold "}, {price: true, qty: 19.99, tag: "silver"}]}, "!error"], + [{nums: [{x: 1}], b: null, price: "abc", items: [{price: 100, qty: 2.5, tag: "x"}, {price: 2.5, qty: 5}, {qty: "abc", tag: "a"}]}, "!error"], + [{nums: [75], b: true, price: null, items: [{price: -0.1, qty: 0.5, tag: "Gold"}, {price: -25, qty: -25}]}, "!error"], + [{nums: [-25, 109], b: 0.5, price: 10, items: [{price: 18, tag: "gold "}], extra: [1, 2]}, {b: 0.5, extra: [1, 2], items: [{price: 18, tag: "gold "}], k327: "gold", k330: 0.5, k332: true, k333: 10, k335: "true", k336: false, k337: "gold", lines: [{k334: false}], nums: [-25, 109], o: {p: [{k324: false, k325: "A-1", k326: 18, price: 18, tag: "gold "}]}, price: 10}], + [{nums: [], b: {v: 1}, price: 0, items: [{price: 1000, qty: [1], tag: ["gold"]}, {price: -0.1, qty: 50, tag: "Gold"}]}, "!error"], + [{nums: [0.5, 50], b: 19.99, price: {v: 1}, items: [{price: 0.5, qty: 18, tag: {t: "x"}}, {qty: 10, tag: "bronze"}]}, "!error"], + [{nums: [], b: 19.99, price: 0, items: null}, "!error"], + ], +} + +{ + name: "gb027: 11 nodes, table, expr, expr, expr, table, switch*, expr, switch*, switch, loop expr, loop table", + graph: { + nodes: [ + {table: "t1", inputs: ["(price > -4 ? string(false) : (false ? 'none' : s))"], outputs: ["k338"], rules: [ + ["'x'", "2"], + ["'x', 'bronze'", "(price ?? 0) * a"], + ["", "0"], + ]}, + {expression: "e2", passThrough: true, fields: { + k339: "(k338 ?? 1)", + k340: "k338 ?? k338", + k341: "(k338 + (k338 ?? $.k340 ?? 0))", + }}, + {expression: "e3", passThrough: true, fields: { + k342: "(price) / 4 + (price ?? 1) >= -4", + "res.k343": "-(a)", + }}, + {expression: "e4", fields: { + "res.k343": "max(nums ?? [0])", + k345: "a ?? s", + k346: "len(upper((items ?? [])[0].tag ?? 'none'))", + k347: "s ?? s", + }}, + {table: "t5", inputs: ["'x' + '' + `${(k338 ?? 0)}-${''}`"], outputs: ["k348", "k349"], rules: [ + ["", "''", "(k338 ?? 1)"], + ["null", "string(((k338 ?? -1) % 7))", "1"], + ["'gold', 'b'", "'high'", "(k338 ?? 0) * 0"], + ["", "'mid'", "10"], + ]}, + {switch: "s6", hit: "collect", when: ["min([k339 % 2, -4 + k339]) in [0..10]"]}, + {expression: "e7", outputPath: "lines", fields: { + "g.k350": "'A-1'", + k351: "k339 ?? k338", + "m.k352": "(k339 ?? -1) * len('x') <= k338", + }}, + {switch: "s8", hit: "collect", when: ["(price > (a ?? -1) ? s : (s ?? '')) != 'x'", "true"]}, + {switch: "s9", when: ["'A-1' in ['gold', 'silver', 'a']", ""]}, + {expression: "e10", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + k353: "string((qty ?? 0) % 7 * (price ?? 0))", + "m.k354": "(0.5)", + k355: "(len(string(false)))", + }}, + {table: "t11", inputField: "items", executionMode: "loop", inputs: ["string((false) or (true))", "price"], outputs: ["k356", "k357"], passThrough: true, outputPath: "o.p", rules: [ + ["startsWith($, 's')", "< 100", "100", "''"], + ["null", "5", "(qty ?? price ?? 0)", "'high'"], + ["null", "", "(price ?? price ?? 0)", "''"], + ["", "100, 101", "min([2.25, (price ?? 1)])", "''"], + ["$ != 'silver'", "!= 5", "10", "'mid'"], + ["", "", "0", "'low'"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "input -> e3", + "input -> e4", + "t1 -> t5", + "e2 -> s6", + "e2 -> e7", + "input -> s8", + "e4 -> s8", + "e3 -> s9", + "s8:1 -> e10", + "s9:0 -> t11", + "t5 -> output", + "s6:0 -> output", + "e7 -> output", + "s8:0 -> output", + "s9:1 -> output", + "e10 -> output", + "t11 -> output", + ], + }, + cases: [ + [{items: [{price: 101, qty: 3, tag: null}, {price: 10, qty: 11, tag: "x"}, {price: 19.99, tag: "bronze"}, {price: 0.1, qty: -0.1, tag: "a"}], a: null, price: -14, s: null, nums: [99, 99, 18, 1000000000000000000000, -0.1]}, "!error"], + [{a: 7, price: 10, s: "gold", nums: [0, 99, 1000000000000000000000, 19.99, 1000]}, "!error"], + [{items: [{price: 100, qty: 21, tag: ""}, {price: 11, qty: 21, tag: "a"}, {price: null, qty: 107}], a: null, price: 2.5, s: "", nums: [-25, 21]}, "!error"], + [{items: [{price: 7, qty: -25, tag: "gold "}, {price: -0.1, qty: 0.1, tag: "b"}, {price: 1000, qty: 2, tag: "a"}, {price: null, qty: 7, tag: "a"}], a: 5, price: null, s: null, nums: [18]}, "!error"], + [{items: [{qty: -1, tag: "bronze"}, {price: 2, qty: null, tag: true}], a: 1000, price: 11, s: "silver", nums: [0]}, {a: 1000, items: [{qty: -1, tag: "bronze"}, {price: 2, qty: null, tag: true}], k342: true, k345: 1000, k346: 6, k347: "silver", k348: "", k349: 0, lines: {g: {k350: "A-1"}, k351: 0, m: {k352: true}}, nums: [0], out: [{k353: "0", k355: 5, m: {k354: 0.5}}, {k353: "0", k355: 5, m: {k354: 0.5}}], price: 11, res: {k343: 0}, s: "silver"}], + [{items: [{price: 2.5, qty: 0.1}, {price: null, qty: 50, tag: "bronze"}], a: 1, price: 39, s: "zz", nums: [50, 1000, 0, 1, -25]}, {a: 1, items: [{price: 2.5, qty: 0.1}, {price: null, qty: 50, tag: "bronze"}], k342: true, k345: 1, k346: 4, k347: "zz", k348: "", k349: 0, lines: {g: {k350: "A-1"}, k351: 0, m: {k352: true}}, nums: [50, 1000, 0, 1, -25], out: [{k353: "0.25", k355: 5, m: {k354: 0.5}}, {k353: "0", k355: 5, m: {k354: 0.5}}], price: 39, res: {k343: 1000}, s: "zz"}], + [{items: [{price: 19.99, qty: 1000, tag: ""}], price: null, s: "zz", nums: [-0.1, 3]}, "!error"], + [{items: [], a: 11, s: null, nums: []}, "!error"], + [{items: [{price: 100, qty: 0, tag: "Gold"}, {price: 10, qty: -1, tag: "gold "}, {price: -0.1, qty: 1000, tag: ""}, {price: 0.5, qty: 99}], a: -25, price: 21, s: "zz", nums: [3, -0.1, 2.5, 5, -0.1]}, {a: -25, items: [{price: 100, qty: 0, tag: "Gold"}, {price: 10, qty: -1, tag: "gold "}, {price: -0.1, qty: 1000, tag: ""}, {price: 0.5, qty: 99}], k342: true, k345: -25, k346: 4, k347: "zz", k348: "", k349: 0, lines: {g: {k350: "A-1"}, k351: 0, m: {k352: true}}, nums: [3, -0.1, 2.5, 5, -0.1], out: [{k353: "0", k355: 5, m: {k354: 0.5}}, {k353: "-10", k355: 5, m: {k354: 0.5}}, {k353: "-0.6", k355: 5, m: {k354: 0.5}}, {k353: "0.5", k355: 5, m: {k354: 0.5}}], price: 21, res: {k343: 5}, s: "zz"}], + [{items: [{price: 1000000000000000000000, qty: 3, tag: "bronze"}, {price: 0.1, qty: 19.99, tag: "bronze"}], price: 2.5, nums: [100, -25]}, "!error"], + [{a: 18, price: 50, s: null, nums: null}, "!error"], + [{items: [{price: 1, qty: -0.1, tag: "bronze"}], a: 11, price: null, nums: [19.99, 1]}, "!error"], + [{items: [{price: 101, qty: 18, tag: "a"}, {price: 0.1, tag: "x"}, {price: 2.5, qty: 3, tag: "bronze"}], a: 21, price: 0, s: "x", nums: [3, 19.99, 19.99]}, {a: 21, items: [{price: 101, qty: 18, tag: "a"}, {price: 0.1, tag: "x"}, {price: 2.5, qty: 3, tag: "bronze"}], k342: true, k348: "", k349: 0, lines: {g: {k350: "A-1"}, k351: 0, m: {k352: true}}, nums: [3, 19.99, 19.99], out: [{k353: "404", k355: 5, m: {k354: 0.5}}, {k353: "0", k355: 5, m: {k354: 0.5}}, {k353: "7.5", k355: 5, m: {k354: 0.5}}], price: 0, res: {k343: -21}, s: "x"}], + [{items: [{tag: "silver"}, {qty: 50, tag: "gold"}, {qty: 0.1, tag: "gold"}], a: 2.5, price: 100, s: "Gold", nums: [-25]}, {a: 2.5, items: [{tag: "silver"}, {qty: 50, tag: "gold"}, {qty: 0.1, tag: "gold"}], k342: true, k345: 2.5, k346: 6, k347: "Gold", k348: "", k349: 0, lines: {g: {k350: "A-1"}, k351: 0, m: {k352: true}}, nums: [-25], out: [{k353: "0", k355: 5, m: {k354: 0.5}}, {k353: "0", k355: 5, m: {k354: 0.5}}, {k353: "0", k355: 5, m: {k354: 0.5}}], price: 100, res: {k343: -25}, s: "Gold"}], + [{items: [{price: {v: 1}, qty: 0}, {price: 0.1, qty: 50, tag: ""}, {price: 99, qty: 11, tag: "bronze"}], a: 0, price: 1000000000000000000000, s: "", nums: [1000, 0]}, "!error"], + [{items: [{price: 5, qty: 1, tag: "a"}, {price: 101, qty: 1000000000000000000000, tag: "bronze"}, {price: true, qty: 18, tag: "gold"}, {price: 5, qty: 18, tag: "Gold"}], a: 2, price: 50, nums: [-1, 0.1, 50, 3, -25]}, "!error"], + [{items: [], a: 50, price: 19.99, s: "Gold", nums: [-1, 101, -25]}, {a: 50, items: [], k342: true, k345: 50, k346: 4, k347: "Gold", k348: "", k349: 0, lines: {g: {k350: "A-1"}, k351: 0, m: {k352: true}}, nums: [-1, 101, -25], out: [], price: 19.99, res: {k343: 101}, s: "Gold"}], + ], +} + +{ + name: "gb028: 8 nodes, table*, switch, table, expr, expr, switch, table, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["string((score ?? 0))", "score"], outputs: ["k358[]"], passThrough: true, outputPath: "res", rules: [ + ["null", "< 5", "0.25"], + ["", "< 0", "1"], + ["$ != 'a'", "(50..51)", "1"], + ["", "[18..23)", "(n ?? 0)"], + ["", "", "n"], + ]}, + {switch: "s2", when: ["10 in [-5..5]", "false", ""]}, + {table: "t3", inputs: ["string(n != null)", "(a ?? 0)", "(false ? 'x' : 'gold') + '-' + 'x' + '-' + 'none'"], outputs: ["k359", "res.k360"], passThrough: true, outputPath: "o.p", rules: [ + ["startsWith($, '')", "<= 10", "", "1", "''"], + ["'', 'bronze'", "(-1..9)", "null", "-5", "string(string(false) in ['gold', 'silver', 'a'])"], + ["", "(21..26)", "null", "-5", "((n ?? 1) >= -4 ? 'gold' : '')"], + ["", "", "null", "0.25", "'high'"], + ["$ != 'a'", "", "", "((((score ?? 1))) / 0.5) / 2", "'low'"], + ]}, + {expression: "e4", passThrough: true, fields: { + k361: "(a ?? -1)", + }}, + {expression: "e5", outputPath: "res", fields: { + k362: "a ?? o.p.res.k360", + k363: "(score ?? -1) <= max(nums ?? [0])", + k364: "o.p.k359 % 3", + k365: "-((a ?? $.k362 ?? 0))", + }}, + {switch: "s6", when: ["(false) and (contains('A-1' + '' + 'none', 'a'))", ""]}, + {table: "t7", inputs: ["(k361 ?? -1)", "score"], outputs: ["k366"], rules: [ + ["", "50, 55", "(o.p.res.k360 ?? 'none')"], + ["", "< 5", "'A-1'"], + ["(50..55)", "100, 105", "''"], + ["", "[100..110]", "'high'"], + ["$ > -1 and $ < 9", "[21..22]", "(o.p.res.k360 ?? '')"], + ["[-1..9)", "1, 51", "string(((o.p.res.k360 ?? '') == '') or (endsWith((o.p.res.k360 ?? 'none'), 'a')))"], + ]}, + {expression: "e8", passThrough: true, fields: { + "m.k367": "a ?? n", + k368: "string(a + (score ?? 1) >= 3)", + }}, + ], + edges: [ + "input -> t1", + "t1 -> s2", + "t1 -> t3", + "t3 -> e4", + "t3 -> e5", + "s2:2 -> s6", + "e4 -> t7", + "s6:0 -> e8", + "s2:1 -> output", + "t3 -> output", + "e5 -> output", + "s6:1 -> output", + "t7 -> output", + "e8 -> output", + ], + }, + cases: [ + [{a: 0.1, n: 2, score: 99}, {a: 0.1, n: 2, o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 2}], score: 99}], + [{a: 99, nums: [], n: null, score: -0.1}, "!error"], + [{a: 5, nums: [], n: 0, score: -25}, "!error"], + [{a: -25, nums: [2, 105], n: 0.5, score: 5}, {a: -25, n: 0.5, nums: [2, 105], o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 0.5}], score: 5}], + [{a: -0.1, nums: [1000], n: 101, score: 10}, {a: -0.1, n: 101, nums: [1000], o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 101}], score: 10}], + [{a: 1, nums: [50, 1000], n: 0, score: 18}, {a: 1, n: 0, nums: [50, 1000], o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 0}, {k358: 0}], score: 18}], + [{a: -0.1, nums: [], n: 21, score: 50}, "!error"], + [{a: 50, nums: [10, 2.5, 99, 99, 7], n: 2.5, score: 19.99, extra: "e"}, {a: 50, extra: "e", n: 2.5, nums: [10, 2.5, 99, 99, 7], o: {p: {k359: 19.990, res: {k360: "low"}}}, res: [{k358: 2.5}, {k358: 2.5}], score: 19.99}], + [{a: 82, nums: [18, 1000, 64, 10, 18], score: 5}, {a: 82, nums: [18, 1000, 64, 10, 18], o: {p: {k359: 5, res: {k360: "low"}}}, res: [{k358: null}], score: 5}], + [{a: 1000000000000000000000, nums: [3, 2], n: 3, score: 7}, {a: 1000000000000000000000, n: 3, nums: [3, 2], o: {p: {k359: 7.0, res: {k360: "low"}}}, res: [{k358: 3}], score: 7}], + [{a: 21, nums: [19.99, 19.99, -0.1, 18, 18], n: 99, score: 0.1, extra: [1, 2]}, {a: 21, extra: [1, 2], k366: "A-1", n: 99, nums: [19.99, 19.99, -0.1, 18, 18], o: {p: {k359: 0.10, res: {k360: "low"}}}, res: [{k358: 99}], score: 0.1}], + [{a: 0, nums: null, n: 21, score: 0.5, extra: "e"}, {a: 0, extra: "e", k366: "A-1", n: 21, o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 21}], score: 0.5}], + [{a: 0.5, n: 2, score: null}, {a: 0.5, n: 2, o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 2}]}], + [{a: 50, nums: [3, 1000000000000000000000, 99], score: -17}, {a: 50, k366: "A-1", nums: [3, 1000000000000000000000, 99], o: {p: {k359: -17.0, res: {k360: "low"}}}, res: [{k358: 1}, {k358: null}], score: -17}], + [{a: 21, nums: [], n: 50}, "!error"], + [{a: 74, nums: [1000000000000000000000], n: -15, score: 10}, {a: 74, n: -15, nums: [1000000000000000000000], o: {p: {k359: 10, res: {k360: "low"}}}, res: [{k358: -15}], score: 10}], + [{a: 1000, nums: [99], n: null, score: 3}, {a: 1000, k366: "A-1", nums: [99], o: {p: {k359: 3.0, res: {k360: "low"}}}, res: [{k358: null}], score: 3}], + [{a: -1, nums: [19.99, 21, 21, 1000000000000000000000, 50], n: 0.1, score: 99}, {a: -1, n: 0.1, nums: [19.99, 21, 21, 1000000000000000000000, 50], o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 0.1}], score: 99}], + [{a: -1, nums: [3, 1000000000000000000000, 18, 11, -25], n: 5, score: 0.1}, {a: -1, k366: "A-1", n: 5, nums: [3, 1000000000000000000000, 18, 11, -25], o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 5}], score: 0.1}], + [{a: 1, nums: null, n: 1000, score: null}, {a: 1, n: 1000, o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 1000}]}], + [{a: 18, nums: [0.1, 7, 1000000000000000000000], n: 19.99, score: 0}, {a: 18, k366: "A-1", n: 19.99, nums: [0.1, 7, 1000000000000000000000], o: {p: {k359: 0, res: {k360: "low"}}}, res: [{k358: 19.99}], score: 0}], + [{a: -1, nums: [71, -1], score: -1}, {a: -1, k366: "A-1", nums: [71, -1], o: {p: {k359: 1, res: {k360: ""}}}, res: [{k358: 1}, {k358: null}], score: -1}], + [{nums: [7, 19.99, 101], n: 1, extra: {deep: {x: 1}}}, "!error"], + [{a: 11, nums: [0.5, 18, 5, 19.99, 3], n: 11, score: 11}, {a: 11, n: 11, nums: [0.5, 18, 5, 19.99, 3], o: {p: {k359: 11.0, res: {k360: "low"}}}, res: [{k358: 11}], score: 11}], + ], +} + +{ + name: "gb029: 11 nodes, switch, switch, switch, table, switch, switch, expr, expr, switch*, switch, table", + graph: { + nodes: [ + {switch: "s1", when: ["(true) and (startsWith(trim(code), ''))", "(a ?? 1) < score", "true", ""]}, + {switch: "s2", when: ["not ((true ? (tier ?? '?') : (tier ?? 'none')) != 'gold')", "'gold' + '' + 'none' + ' ' + string(true) in ['gold', 'silver', 'a']", "true", ""]}, + {switch: "s3", when: ["max([0.5, price]) + -((a ?? -1)) > a", "((score ?? 1) * -4 in [-5..5])", "true", ""]}, + {table: "t4", inputs: ["score"], outputs: ["g.k369", "k370"], passThrough: true, outputPath: "res", rules: [ + ["(21..22)", "(tier ?? 'none') + ' ' + upper(string(true))", "(true) or (contains(string(false), ''))"], + ["<= 100", "'mid'", "true"], + ["", "'high'", "true"], + ["5", "(code ?? '?')", "true"], + ["10", "'mid'", "(floor((n ?? 1)) in [0..10]) or ((score ?? -1) > 2.25 * (score ?? -1))"], + [">= -1", "'mid'", "false"], + ]}, + {switch: "s5", when: ["string(true) + ' ' + (false ? (tier ?? '') : '') != 'gold'", "false", ""]}, + {switch: "s6", when: ["(a ?? 1) % 3 in [-5..5]", "len(string((score ?? 1))) > ((a ?? 1)) / 0.5", "code == null"]}, + {expression: "e7", fields: { + k371: "tier ?? a", + k372: "3 <= count(nums ?? [], # > 10)", + }}, + {expression: "e8", passThrough: true, outputPath: "o.p", fields: { + "res.k373": "'x'", + k371: "(code ?? '')", + }}, + {switch: "s9", hit: "collect", when: ["k372", "(((a ?? 0) < (price ?? 0)) or (score > price)) and (((price ?? 0) == (score ?? 0)))", ""]}, + {switch: "s10", when: ["true", "false", "false"]}, + {table: "t11", inputs: ["price", "code", "(n ?? -1)"], outputs: ["m.k375"], passThrough: true, rules: [ + ["!= 50", "'silver'", "< 5", "false"], + ["< 100", "null", "$ > 18 and $ < 19", "true"], + ["[50..100]", "'x'", "< 18", "false"], + ["[50..55]", "not('x')", "null", "true"], + ["null", "", ">= 10", "false"], + ["-1, 49", "", "(10..20)", "false"], + ["", "", "", "true"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> s2", + "s2:0 -> s3", + "s3:0 -> t4", + "s3:1 -> s5", + "s1:2 -> s5", + "s5:1 -> s6", + "s6:1 -> e7", + "s3:2 -> e8", + "e7 -> s9", + "s6:2 -> s9", + "s3:1 -> s10", + "s10:0 -> t11", + "s1:1 -> output", + "s1:3 -> output", + "s2:1 -> output", + "s2:3 -> output", + "t4 -> output", + "s5:2 -> output", + "s6:0 -> output", + "e8 -> output", + "s9:0 -> output", + "s9:1 -> output", + "s9:2 -> output", + "s10:1 -> output", + "s10:2 -> output", + "t11 -> output", + ], + }, + cases: [ + [{code: "Gold", score: 1000000000000000000000, n: -1, a: 18, tier: "Gold", nums: [], price: 2}, {}], + [{code: 5, score: 2.5, n: null, a: 2.5, tier: "b", nums: [1000000000000000000000, 1, 101], price: 18, extra: {deep: {x: 1}}}, {}], + [{code: "gold", score: 1000000000000000000000, n: -25, tier: "b", price: null}, {}], + [{code: "b", score: 0.5, n: 21, a: 0.1, tier: "silver", nums: [2, 1000000000000000000000, 5], price: 0.1}, {}], + [{code: "Gold", score: 86, a: null, tier: "gold ", nums: [], price: 3}, {}], + [{code: "Gold", score: 101, a: 27, tier: "b", nums: null, price: -0.1}, {}], + [{score: -1, n: null, a: null, tier: "", nums: [-25, 0, 99, 1, 10], price: 10}, {}], + [{code: null, n: 2.5, a: 10, tier: "gold", nums: null, price: 1000000000000000000000}, {}], + [{code: "silver", score: 11, n: -0.1, a: 0.1, tier: "Gold", nums: [3, 21, -0.1, 101, 10], price: 1000000000000000000000, extra: [1, 2]}, {}], + [{code: "", score: "5", n: 1000, a: "abc", tier: "gold ", nums: [21, 22, -1], price: 10, extra: {deep: {x: 1}}}, {}], + [{code: "gold", score: 18, n: -25, a: [1], tier: "gold ", nums: [3, 21, 1000000000000000000000], extra: 1}, {}], + [{code: "Gold", score: 2.5, n: 11, a: -1, tier: "", nums: [3], price: 3, extra: "e"}, {}], + [{code: "gold ", score: 76, n: 5, a: null, nums: [21, -25], price: "abc", extra: "e"}, {}], + [{code: "Gold", score: 0.5, n: 18, a: null, tier: "", nums: [1, 3, 76, 1000000000000000000000, 18], price: 0.5}, {}], + [{code: "gold", score: null, n: 7, tier: "Gold", nums: [3, 1000000000000000000000, 50, 100, 0.5], price: 2.5}, {}], + [{code: "", score: 2.5, a: null, tier: null, nums: [2.5, 50], price: 7}, {}], + [{code: "x", score: 5, n: 3, a: 3, tier: "Gold", nums: null, price: 2}, {}], + [{code: "x", score: 0.1, n: 3, a: 99, nums: [5, 22, 11], price: 101}, {}], + ], +} + +{ + name: "gb030: 10 nodes, switch, expr, expr, switch*, switch, table, expr, table*, switch*, expr", + graph: { + nodes: [ + {switch: "s1", when: ["(a ?? 1) - (a ?? 1) % 7 != ((true) ? 3 : (1))", ""]}, + {expression: "e2", passThrough: true, outputPath: "lines", fields: { + "g.k376": "tier != null", + k377: "(10 * (cust.age ?? -1)) / 10 + ((cust.age ?? -1)) * (a ?? -1)", + }}, + {expression: "e3", outputPath: "res", fields: { + k378: "(true ? (a ?? lines.k377 ?? 0) : ((lines.k377 ?? 1)))", + k379: "('none' == 'silver') or ((10) in [-5..5])", + k380: "lines.g.k376", + "res.k381": "lines.k377", + }}, + {switch: "s4", hit: "collect", when: ["max([(a ?? -1), ((lines.k377 ?? -1)) / 2]) >= -((lines.k377 ?? 1))", "not (false)"]}, + {switch: "s5", when: ["(a ?? 0) in [0..10]", "(max([2.25, (lines.k377 ?? 1)])) <= 2.25", "(lines.g.k376 ?? false)", ""]}, + {table: "t6", inputs: ["string((true) or ((lines.g.k376 ?? false)))", "lines.g.k376"], outputs: ["g.k382", "k380"], rules: [ + ["", "$ == true", "10", "string(((a ?? 1)) >= (lines.k377 ?? -1) * (a ?? 1))"], + ["'silver', 'gold'", "$ == true", "-5", "'mid'"], + ["", "true", "-5", "'mid'"], + ["not('')", "", "1", "'none'"], + ]}, + {expression: "e7", inputField: "cust", passThrough: true, fields: { + k384: "active ?? tier", + }}, + {table: "t8", hit: "collect", inputField: "cust", inputs: ["age * 2.25 * age % 7", "tier", "age", null], outputs: ["g.k385"], passThrough: true, outputPath: "res", rules: [ + ["!= 0", "'gold', 'gold'", ">= 18", "true", "false"], + ["null", "null", "!= -1", "", "true"], + ["null", "$ != ''", "", "true", "true"], + ["<= 11", "$ != 'silver'", "", "'gold'", "true"], + ["", "null", "not(10)", "", "false"], + ["(0..5)", "not('x')", ">= 0", "true", "(not (((active ?? false)) or ((active ?? false)))) and ((active ?? false))"], + ]}, + {switch: "s9", hit: "collect", when: ["round((res.res.k381)) == (lines.k377 ?? -1)", "string(tier in ['gold', 'silver', 'a']) in ['gold', 'silver', 'a']", "(((cust.age ?? 0) == (a ?? 1)) and ((lines.k377 ?? -1) <= 100))", ""]}, + {expression: "e10", fields: { + k386: "'none'", + k387: "string(upper((s ?? '')) != 'gold')", + k388: "cust.age ?? res.k380", + k377: "((res.k378 ?? -1) + (a ?? 0) <= 3 + res.k378 ? (lines.k377 ?? 0) : (res.k378 ?? -1))", + }}, + ], + edges: [ + "input -> s1", + "input -> e2", + "s1:1 -> e2", + "e2 -> e3", + "e2 -> s4", + "s4:0 -> s5", + "s5:0 -> t6", + "s4:1 -> e7", + "s5:2 -> t8", + "t8 -> s9", + "e3 -> s9", + "s9:1 -> e10", + "s1:0 -> output", + "s5:1 -> output", + "t6 -> output", + "e7 -> output", + "s9:2 -> output", + "e10 -> output", + ], + }, + cases: [ + [{s: "a", cust: {age: 21, tier: "gold ", active: null}, a: 0.5}, {a: 0.5, cust: {active: null, age: 21, tier: "gold "}, k384: "gold ", lines: {g: {k376: false}, k377: 31.5}, s: "a"}], + [{tier: "a", s: "a", cust: {age: 2.5, tier: "x", active: true}, a: 50, extra: "e"}, {a: 50, cust: {active: true, age: 2.5, tier: "x"}, extra: "e", k384: true, lines: {g: {k376: true}, k377: 127.5}, s: "a", tier: "a"}], + [{tier: "b", s: "zz", a: 50}, {a: 50, lines: {g: {k376: true}, k377: -51}, s: "zz", tier: "b"}], + [{tier: "zz", s: "x", cust: {age: 18, tier: "a", active: false}, a: 100}, {a: 100, cust: {active: false, age: 18, tier: "a"}, k384: false, lines: {g: {k376: true}, k377: 1818}, s: "x", tier: "zz"}], + [{tier: "bronze", s: "silver", cust: {age: 3, tier: "bronze", active: true}, a: 0.5}, {a: 0.5, cust: {active: true, age: 3, tier: "bronze"}, g: {k382: 10}, k380: "false", k384: true, lines: {g: {k376: true}, k377: 4.5}, s: "silver", tier: "bronze"}], + [{tier: "x", s: "x", cust: {age: -1, tier: null, active: null}, a: -1}, {a: -1, cust: {active: null, age: -1, tier: null}, lines: {g: {k376: true}, k377: 0}, s: "x", tier: "x"}], + [{tier: "", s: "silver", cust: {age: 101, tier: "gold", active: false}, a: 0}, {a: 0, cust: {active: false, age: 101, tier: "gold"}, g: {k382: 10}, k380: "true", k384: false, lines: {g: {k376: true}, k377: 101}, s: "silver", tier: ""}], + [{tier: "b", s: "zz", cust: {age: -0.1, active: true}, a: 0}, {a: 0, cust: {active: true, age: -0.1}, k384: true, lines: {g: {k376: true}, k377: -0.1}, s: "zz", tier: "b"}], + [{tier: "bronze", s: "a", a: 1000, extra: 1}, {a: 1000, extra: 1, lines: {g: {k376: true}, k377: -1001}, s: "a", tier: "bronze"}], + [{tier: "x", s: "x", cust: {age: 99, tier: "gold ", active: true}, a: 0.5}, {a: 0.5, cust: {active: true, age: 99, tier: "gold "}, g: {k382: 10}, k380: "false", k384: true, lines: {g: {k376: true}, k377: 148.5}, s: "x", tier: "x"}], + [{tier: "gold", s: "gold", cust: {age: 11, tier: "silver", active: false}, a: 11, extra: 1}, {a: 11, cust: {active: false, age: 11, tier: "silver"}, extra: 1, k384: false, lines: {g: {k376: true}, k377: 132}, s: "gold", tier: "gold"}], + [{tier: "a", s: "bronze", cust: null, a: 100}, {a: 100, lines: {g: {k376: true}, k377: -101}, s: "bronze", tier: "a"}], + [{tier: "", s: "silver", cust: null, a: null, extra: [1, 2]}, {extra: [1, 2], g: {k382: 10}, k380: "true", lines: {g: {k376: true}, k377: 0}, s: "silver", tier: ""}], + [{tier: "gold ", s: "gold ", cust: {age: -25, tier: "Gold", active: true}, a: 3}, {a: 3, cust: {active: true, age: -25, tier: "Gold"}, k384: true, lines: {g: {k376: true}, k377: -100}, s: "gold ", tier: "gold "}], + [{tier: "gold ", s: "silver", cust: {age: 100, tier: "x", active: true}, a: 0}, {a: 0, cust: {active: true, age: 100, tier: "x"}, g: {k382: 10}, k380: "true", k384: true, lines: {g: {k376: true}, k377: 100}, s: "silver", tier: "gold "}], + [{tier: "", s: "x", cust: {age: 11, tier: "a", active: false}, a: 10}, {a: 10, cust: {active: false, age: 11, tier: "a"}, g: {k382: 10}, k380: "false", k384: false, lines: {g: {k376: true}, k377: 121}, s: "x", tier: ""}], + [{tier: "x", s: "bronze", a: 50}, {a: 50, lines: {g: {k376: true}, k377: -51}, s: "bronze", tier: "x"}], + [{tier: "x", s: "b", cust: {age: 0.5, tier: "x", active: false}, a: 0}, {a: 0, cust: {active: false, age: 0.5, tier: "x"}, g: {k382: 10}, k380: "true", k384: false, lines: {g: {k376: true}, k377: 0.5}, s: "b", tier: "x"}], + [{tier: "b", cust: {age: -0.1, tier: "Gold"}, a: 7}, {a: 7, cust: {age: -0.1, tier: "Gold"}, g: {k382: 10}, k380: "true", k384: "Gold", lines: {g: {k376: true}, k377: -0.8}, tier: "b"}], + [{tier: "gold", s: "a", cust: {age: 50, tier: "zz", active: false}, a: 100}, {a: 100, cust: {active: false, age: 50, tier: "zz"}, k384: false, lines: {g: {k376: true}, k377: 5050}, s: "a", tier: "gold"}], + [{tier: "Gold", s: "silver", cust: {age: 50, tier: "a", active: false}, a: 99, extra: {deep: {x: 1}}}, {a: 99, cust: {active: false, age: 50, tier: "a"}, extra: {deep: {x: 1}}, k384: false, lines: {g: {k376: true}, k377: 5000}, s: "silver", tier: "Gold"}], + [{tier: "bronze", cust: {age: 5, tier: "gold ", active: true}, a: -25}, {a: -25, cust: {active: true, age: 5, tier: "gold "}, k384: true, lines: {g: {k376: true}, k377: -120}, tier: "bronze"}], + [{tier: "x", s: "", cust: {age: 100, tier: "gold ", active: true}, a: 18}, {a: 18, cust: {active: true, age: 100, tier: "gold "}, k384: true, lines: {g: {k376: true}, k377: 1900}, s: "", tier: "x"}], + [{tier: "Gold", s: "a", cust: {age: null, tier: "x", active: false}, a: 1}, {a: 1, cust: {active: false, age: null, tier: "x"}, k384: false, lines: {g: {k376: true}, k377: -2}, s: "a", tier: "Gold"}], + [{s: null, cust: {age: 11, tier: "a", active: null}, a: null}, {cust: {active: null, age: 11, tier: "a"}, k384: "a", lines: {g: {k376: false}, k377: 0}}], + ], +} + +{ + name: "gb031: 7 nodes, switch, switch, table, table, expr, table, expr", + graph: { + nodes: [ + {switch: "s1", when: ["(score ?? -1) in [1..100]"]}, + {switch: "s2", when: ["(a ?? 1) + (score) / 3 == price", ""]}, + {table: "t3", inputs: ["score", "(a ?? 0)"], outputs: ["res.k390", "k391"], rules: [ + ["(21..31)", "<= 5", "'gold'", "false"], + ["<= 19", "< 10", "'gold'", "true"], + ["[5..15)", "18, 68", "lower('none')", "false"], + ["< 18", "!= 50", "'mid'", "true"], + [">= 21", "!= 18", "string((cust.age ?? 0) <= (price ?? -1)) + '-' + 'none' + ' ' + (false ? (cust.tier ?? '?') : 'x')", "true"], + ["< 100", "not(5)", "'gold'", "true"], + ["", "", "string(((false ? 3 : (a ?? 0))))", "true"], + ]}, + {table: "t4", inputField: "cust", inputs: ["active", null], outputs: ["k392"], outputPath: "out", rules: [ + ["null", "$ != null", "true"], + ["true", "$ != null", "false"], + ["$ == true", "$ != null", "false"], + ["null", "$ != null", "false"], + ["", "", "false"], + ["false", "", "false"], + ]}, + {expression: "e5", passThrough: true, outputPath: "lines", fields: { + k393: "res.k390 != 'gold'", + k394: "$nodes.t3.res.k390 ?? res.k390", + "m.k395": "round(((out.k392 ?? false) ? (10) : 0))", + k396: "'gold'", + }}, + {table: "t6", inputs: ["ceil(score)"], outputs: ["k397"], rules: [ + ["", "false"], + ["21, 71", "false"], + ["18, 19", "true"], + ]}, + {expression: "e7", passThrough: true, fields: { + k398: "not (not (10 == 2))", + k399: "max([(2.25), min([-4, 0])]) * (0 ?? 1 ?? 0)", + k400: "res.k390 ?? res.k390", + }}, + ], + edges: [ + "input -> s1", + "input -> s2", + "s2:1 -> t3", + "s2:0 -> t4", + "t4 -> e5", + "t3 -> e5", + "s1:0 -> t6", + "t3 -> e7", + "t6 -> e7", + "e5 -> output", + "e7 -> output", + ], + }, + cases: [ + [{a: -25, price: 50, cust: {age: -0.1, tier: null, active: false}, score: 19.99}, {k391: true, k397: false, k398: false, k399: 0, k400: "-25", lines: {k393: true, k394: "-25", k396: "gold", m: {k395: 0}}, res: {k390: "-25"}}], + [{price: 19.99, cust: {age: 1000, tier: "a"}, score: 5}, {k391: true, k397: false, k398: false, k399: 0, k400: "gold", lines: {k393: false, k394: "gold", k396: "gold", m: {k395: 0}}, res: {k390: "gold"}}], + [{a: 1000, price: 1000000000000000000000, cust: {age: 101, tier: "gold "}, score: 0.1}, {k391: true, k398: false, k399: 0, k400: "mid", lines: {k393: true, k394: "mid", k396: "gold", m: {k395: 0}}, res: {k390: "mid"}}], + [{a: "abc", price: 1000, cust: 5, score: 2, extra: [1, 2]}, {k391: true, k397: false, k398: false, k399: 0, k400: "mid", lines: {k393: true, k394: "mid", k396: "gold", m: {k395: 0}}, res: {k390: "mid"}}], + [{a: 5, price: -1, cust: {age: 7, tier: "bronze", active: false}, score: 10, extra: "e"}, {k391: true, k397: false, k398: false, k399: 0, k400: "gold", lines: {k393: false, k394: "gold", k396: "gold", m: {k395: 0}}, res: {k390: "gold"}}], + [{a: null, cust: {age: 10, tier: "bronze", active: false}, score: "5", extra: [1, 2]}, {k391: true, k398: false, k399: 0, k400: "0", lines: {k393: true, k394: "0", k396: "gold", m: {k395: 0}}, res: {k390: "0"}}], + [{a: "abc", price: 30, cust: {age: -1, tier: "a", active: false}, score: 99}, {k391: true, k397: false, k398: false, k399: 0, k400: "true-none x", lines: {k393: true, k394: "true-none x", k396: "gold", m: {k395: 0}}, res: {k390: "true-none x"}}], + [{a: -0.1, price: 1000, cust: null, score: 19.99}, {k391: true, k397: false, k398: false, k399: 0, k400: "-0.1", lines: {k393: true, k394: "-0.1", k396: "gold", m: {k395: 0}}, res: {k390: "-0.1"}}], + [{a: 1000000000000000000000, price: {v: 1}, cust: {age: 5, tier: "gold", active: true}, score: 10}, {k391: true, k397: false, k398: false, k399: 0, k400: "mid", lines: {k393: true, k394: "mid", k396: "gold", m: {k395: 0}}, res: {k390: "mid"}}], + [{a: 2.5, price: null, cust: {age: 19.99, tier: "Gold", active: true}, score: -1}, {k391: true, k398: false, k399: 0, k400: "gold", lines: {k393: false, k394: "gold", k396: "gold", m: {k395: 0}}, res: {k390: "gold"}}], + [{a: 50, price: 11, cust: {age: 1000000000000000000000, tier: "bronze", active: true}, score: 11}, {k391: true, k397: false, k398: false, k399: 0, k400: "50", lines: {k393: true, k394: "50", k396: "gold", m: {k395: 0}}, res: {k390: "50"}}], + [{a: 11, price: 0.1, score: true}, {k391: true, k398: false, k399: 0, k400: "11", lines: {k393: true, k394: "11", k396: "gold", m: {k395: 0}}, res: {k390: "11"}}], + [{a: 5, price: 100, cust: {age: -25, tier: "silver", active: true}, score: -25}, {k391: true, k398: false, k399: 0, k400: "gold", lines: {k393: false, k394: "gold", k396: "gold", m: {k395: 0}}, res: {k390: "gold"}}], + [{a: 1000000000000000000000, price: null, cust: {age: null, tier: "a", active: true}, score: 100}, {k391: true, k397: false, k398: false, k399: 0, k400: "false-none x", lines: {k393: true, k394: "false-none x", k396: "gold", m: {k395: 0}}, res: {k390: "false-none x"}}], + [{price: null, cust: {tier: "silver", active: false}, score: 3}, {k391: true, k397: false, k398: false, k399: 0, k400: "gold", lines: {k393: false, k394: "gold", k396: "gold", m: {k395: 0}}, res: {k390: "gold"}}], + [{a: 1000000000000000000000, price: -1, cust: {age: 118, tier: "gold ", active: true}, score: -0.1}, {k391: true, k398: false, k399: 0, k400: "mid", lines: {k393: true, k394: "mid", k396: "gold", m: {k395: 0}}, res: {k390: "mid"}}], + [{a: 50, price: -1, cust: {age: 2.5, tier: "Gold", active: null}, score: 99}, {k391: true, k397: false, k398: false, k399: 0, k400: "false-none x", lines: {k393: true, k394: "false-none x", k396: "gold", m: {k395: 0}}, res: {k390: "false-none x"}}], + [{price: 19.99, cust: {age: -18, tier: "zz", active: false}, score: true}, {k391: true, k398: false, k399: 0, k400: "0", lines: {k393: true, k394: "0", k396: "gold", m: {k395: 0}}, res: {k390: "0"}}], + [{a: 19.99, price: null, cust: {age: 18, tier: true, active: false}, score: 21}, {k391: true, k397: false, k398: false, k399: 0, k400: "false-none x", lines: {k393: true, k394: "false-none x", k396: "gold", m: {k395: 0}}, res: {k390: "false-none x"}}], + [{a: -0.1, price: 1000000000000000000000, cust: {age: 5, tier: "bronze", active: true}, score: 0.5}, {k391: true, k398: false, k399: 0, k400: "gold", lines: {k393: false, k394: "gold", k396: "gold", m: {k395: 0}}, res: {k390: "gold"}}], + ], +} + +{ + name: "gb032: 10 nodes, switch, expr, loop expr, loop expr, switch*, loop expr, expr, loop table, expr, loop table*", + graph: { + nodes: [ + {switch: "s1", when: ["tier != 'silver'", "(b ?? -1) * 0.5 % 2 >= len(((flag ?? false) ? (code ?? '?') : (tier ?? 'none')))", ""]}, + {expression: "e2", passThrough: true, fields: { + k401: "code ?? b", + k402: "-(100)", + "g.k403": "max([abs((b ?? -1)) - b, -(len((code ?? '?')))])", + }}, + {expression: "e3", inputField: "items", executionMode: "loop", outputPath: "lines", fields: { + k404: "len(string(false)) < -((qty ?? -1)) % 2", + k405: "price", + "g.k406": "tag ?? tag", + k407: "price", + }}, + {expression: "e4", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k408: "(qty) + 0.5 < ((price ?? -1)) * (qty ?? 1) - 2.25", + k409: "qty ?? tag", + k410: "(('' in ['gold', 'silver', 'a'] ? -((qty ?? 1)) : 3 + 1))", + "g.k411": "floor(((price ?? 0)))", + }}, + {switch: "s5", hit: "collect", when: ["(k402 ?? 0) * (k402 ?? -1) == (g.k403 ?? k401 ?? 0)", "not (false)", ""]}, + {expression: "e6", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "lines", fields: { + k412: "string(false)", + }}, + {expression: "e7", inputField: "cust", fields: { + "g.k413": "age + (age) in [0..10]", + "g.k414": "(tier ?? 'none') in ['gold', 'silver', 'a']", + k415: "round((age ?? -1))", + "g.k416": "age ?? age", + }}, + {table: "t8", inputField: "items", executionMode: "loop", inputs: ["(0)", "price"], outputs: ["k417"], outputPath: "res", rules: [ + ["!= 5", "null", "'high'"], + ["null", ">= 21", "'gold'"], + ["[50..55]", "$ > 1 and $ < 2", "'gold'"], + [">= -1", "(18..68)", "'high'"], + ["", "", "'high'"], + ]}, + {expression: "e9", passThrough: true, fields: { + k418: "round(0) + (0 ?? 1 ?? 0) * (0 ?? 1 ?? 0)", + "res.k419": "(100 * ($.k418 ?? 1)) % 7", + }}, + {table: "t10", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["tag", "price"], outputs: ["k420[]", "k421"], outputPath: "res", rules: [ + ["", "", "0.25", "-5"], + ["", "$ > 100 and $ < 150", "100", "(len((tag ?? '?'))) % 7"], + ["'silver', 'gold'", ">= 0", "0.25", "1"], + ["'a', 'b'", "not(18)", "-5", "100"], + ["null", "null", "2", "100"], + ["", "", "0.25", "100"], + ]}, + ], + edges: [ + "input -> s1", + "input -> e2", + "s1:0 -> e2", + "e2 -> e3", + "e2 -> e4", + "e4 -> s5", + "s5:0 -> e6", + "e2 -> e7", + "s5:1 -> t8", + "t8 -> e9", + "e6 -> t10", + "s1:2 -> output", + "e3 -> output", + "s5:2 -> output", + "e7 -> output", + "e9 -> output", + "t10 -> output", + ], + }, + cases: [ + [{b: 21, items: [{qty: 19.99, tag: "a"}, {price: -0.1, qty: -1, tag: "bronze"}, {price: 7, qty: 50}], cust: {age: 1000000000000000000000, tier: "x"}, code: "gold", flag: true}, {b: 21, code: "gold", cust: {age: 1000000000000000000000, tier: "x"}, flag: true, g: {k403: 0, k413: false, k414: false, k416: 1000000000000000000000}, items: [{qty: 19.99, tag: "a"}, {price: -0.1, qty: -1, tag: "bronze"}, {price: 7, qty: 50}], k401: "gold", k402: -100, k415: 1000000000000000000000, k418: 0, lines: [{g: {k406: "a"}, k404: false, k405: null, k407: null}, {g: {k406: "bronze"}, k404: false, k405: -0.1, k407: -0.1}, {g: {k406: null}, k404: false, k405: 7, k407: 7}], res: [{g: {k411: 0}, k408: false, k409: 19.99, k410: 4, qty: 19.99, tag: "a"}, {g: {k411: -1}, k408: false, k409: -1, k410: 4, price: -0.1, qty: -1, tag: "bronze"}, {g: {k411: 7}, k408: true, k409: 50, k410: 4, price: 7, qty: 50}]}], + [{b: 7, items: [{price: 0.5, qty: 1, tag: "b"}, {price: 2.5, qty: 19.99, tag: "gold"}, {price: 0.5, qty: 18, tag: ""}, {price: 5, qty: 21, tag: "silver"}], cust: {age: 100, tier: "b", active: false}, tier: "gold", code: null, flag: false}, {b: 7, cust: {active: false, age: 100, tier: "b"}, flag: false, g: {k403: 0, k413: false, k414: false, k416: 100}, items: [{price: 0.5, qty: 1, tag: "b"}, {price: 2.5, qty: 19.99, tag: "gold"}, {price: 0.5, qty: 18, tag: ""}, {price: 5, qty: 21, tag: "silver"}], k401: 7, k402: -100, k415: 100, k418: 0, lines: [{g: {k406: "b"}, k404: false, k405: 0.5, k407: 0.5}, {g: {k406: "gold"}, k404: false, k405: 2.5, k407: 2.5}, {g: {k406: ""}, k404: false, k405: 0.5, k407: 0.5}, {g: {k406: "silver"}, k404: false, k405: 5, k407: 5}], res: [{g: {k411: 0}, k408: false, k409: 1, k410: 4, price: 0.5, qty: 1, tag: "b"}, {g: {k411: 2}, k408: true, k409: 19.99, k410: 4, price: 2.5, qty: 19.99, tag: "gold"}, {g: {k411: 0}, k408: false, k409: 18, k410: 4, price: 0.5, qty: 18, tag: ""}, {g: {k411: 5}, k408: true, k409: 21, k410: 4, price: 5, qty: 21, tag: "silver"}], tier: "gold"}], + [{b: 0.1, items: [{price: 10, qty: 99, tag: "zz"}, {qty: 99, tag: "a"}, {price: 11, qty: 1, tag: "x"}, {price: 3, qty: 10, tag: "gold"}], cust: {age: 5, tier: "zz", active: false}, tier: null, code: "", flag: true}, {b: 0.1, code: "", cust: {active: false, age: 5, tier: "zz"}, flag: true, g: {k403: -0, k413: true, k414: false, k416: 5}, items: [{price: 10, qty: 99, tag: "zz"}, {qty: 99, tag: "a"}, {price: 11, qty: 1, tag: "x"}, {price: 3, qty: 10, tag: "gold"}], k401: "", k402: -100, k415: 5, k418: 0, lines: [{g: {k406: "zz"}, k404: false, k405: 10, k407: 10}, {g: {k406: "a"}, k404: false, k405: null, k407: null}, {g: {k406: "x"}, k404: false, k405: 11, k407: 11}, {g: {k406: "gold"}, k404: false, k405: 3, k407: 3}], res: [{g: {k411: 10}, k408: true, k409: 99, k410: 4, price: 10, qty: 99, tag: "zz"}, {g: {k411: 0}, k408: false, k409: 99, k410: 4, qty: 99, tag: "a"}, {g: {k411: 11}, k408: true, k409: 1, k410: 4, price: 11, qty: 1, tag: "x"}, {g: {k411: 3}, k408: true, k409: 10, k410: 4, price: 3, qty: 10, tag: "gold"}]}], + [{b: 0, items: [{price: 5, qty: 18, tag: "gold"}, {price: 10, qty: 1, tag: "x"}, {price: -7, qty: 0, tag: "bronze"}, {price: null, qty: 5, tag: "bronze"}], cust: {age: 2.5, tier: "zz", active: false}, tier: "bronze", code: "Gold", flag: true}, {b: 0, code: "Gold", cust: {active: false, age: 2.5, tier: "zz"}, flag: true, g: {k403: 0, k413: true, k414: false, k416: 2.5}, items: [{price: 5, qty: 18, tag: "gold"}, {price: 10, qty: 1, tag: "x"}, {price: -7, qty: 0, tag: "bronze"}, {price: null, qty: 5, tag: "bronze"}], k401: "Gold", k402: -100, k415: 3, k418: 0, lines: [{g: {k406: "gold"}, k404: false, k405: 5, k407: 5}, {g: {k406: "x"}, k404: false, k405: 10, k407: 10}, {g: {k406: "bronze"}, k404: false, k405: -7, k407: -7}, {g: {k406: "bronze"}, k404: false, k405: null, k407: null}], res: [{g: {k411: 5}, k408: true, k409: 18, k410: 4, price: 5, qty: 18, tag: "gold"}, {g: {k411: 10}, k408: true, k409: 1, k410: 4, price: 10, qty: 1, tag: "x"}, {g: {k411: -7}, k408: false, k409: 0, k410: 4, price: -7, qty: 0, tag: "bronze"}, {g: {k411: 0}, k408: false, k409: 5, k410: 4, price: null, qty: 5, tag: "bronze"}], tier: "bronze"}], + [{b: 19.99, items: [{tag: "zz"}, {price: 99, qty: 50, tag: "x"}, {price: null, qty: -25, tag: "Gold"}, {price: -25, tag: "zz"}], cust: {age: 10, tier: "Gold", active: false}, tier: "b", code: "gold"}, "!error"], + [{b: -25, items: [{price: 11, qty: 0, tag: null}], cust: {age: 100, tier: "Gold", active: false}, code: "zz", flag: false}, {b: -25, code: "zz", cust: {active: false, age: 100, tier: "Gold"}, flag: false, g: {k403: 50, k413: false, k414: false, k416: 100}, items: [{price: 11, qty: 0, tag: null}], k401: "zz", k402: -100, k415: 100, k418: 0, lines: [{g: {k406: null}, k404: false, k405: 11, k407: 11}], res: [{g: {k411: 11}, k408: false, k409: 0, k410: 4, price: 11, qty: 0, tag: null}]}], + [{b: 0.1, items: [{price: 5, qty: 0.1, tag: "a"}, {price: 100, qty: 0, tag: ""}], cust: {age: 100, active: false}, code: "gold ", flag: false}, {b: 0.1, code: "gold ", cust: {active: false, age: 100}, flag: false, g: {k403: 0.0, k413: false, k414: false, k416: 100}, items: [{price: 5, qty: 0.1, tag: "a"}, {price: 100, qty: 0, tag: ""}], k401: "gold ", k402: -100, k415: 100, k418: 0, lines: [{g: {k406: "a"}, k404: false, k405: 5, k407: 5}, {g: {k406: ""}, k404: false, k405: 100, k407: 100}], res: [{g: {k411: 5}, k408: false, k409: 0.1, k410: 4, price: 5, qty: 0.1, tag: "a"}, {g: {k411: 100}, k408: false, k409: 0, k410: 4, price: 100, qty: 0, tag: ""}]}], + [{b: 3, items: [{price: 2.5, qty: 7, tag: "gold"}, {price: null, qty: -25, tag: "zz"}], cust: {age: 0.1, tier: "", active: false}, tier: "gold ", code: "Gold", flag: false}, {b: 3, code: "Gold", cust: {active: false, age: 0.1, tier: ""}, flag: false, g: {k403: 0, k413: true, k414: false, k416: 0.1}, items: [{price: 2.5, qty: 7, tag: "gold"}, {price: null, qty: -25, tag: "zz"}], k401: "Gold", k402: -100, k415: 0, k418: 0, lines: [{g: {k406: "gold"}, k404: false, k405: 2.5, k407: 2.5}, {g: {k406: "zz"}, k404: false, k405: null, k407: null}], res: [{g: {k411: 2}, k408: true, k409: 7, k410: 4, price: 2.5, qty: 7, tag: "gold"}, {g: {k411: 0}, k408: true, k409: -25, k410: 4, price: null, qty: -25, tag: "zz"}], tier: "gold "}], + [{b: 0.5, items: [{price: 99, qty: 10, tag: "bronze"}], cust: {age: 21, tier: "b", active: false}, tier: "silver", code: "a", flag: true}, {b: 0.5, code: "a", cust: {active: false, age: 21, tier: "b"}, flag: true, g: {k403: 0.0, k413: false, k414: false, k416: 21}, items: [{price: 99, qty: 10, tag: "bronze"}], k401: "a", k402: -100, k415: 21, k418: 0, lines: [{g: {k406: "bronze"}, k404: false, k405: 99, k407: 99}], res: [{g: {k411: 99}, k408: true, k409: 10, k410: 4, price: 99, qty: 10, tag: "bronze"}], tier: "silver"}], + [{b: 19.99, items: [{price: 18, tag: "a"}, {price: 1000, qty: null, tag: "gold "}], cust: {age: 3, tier: "gold ", active: false}, tier: "bronze", code: "Gold", flag: true}, "!error"], + [{b: 101, items: [], cust: {age: 3, tier: "x", active: true}, tier: "zz", flag: true, extra: 1}, {b: 101, cust: {active: true, age: 3, tier: "x"}, extra: 1, flag: true, g: {k403: 0, k413: true, k414: false, k416: 3}, items: [], k401: 101, k402: -100, k415: 3, k418: 0, lines: [], res: [], tier: "zz"}], + [{b: 5, items: [{price: 5, qty: 2, tag: "gold "}, {price: 101, tag: "gold "}], cust: {age: null, tier: null, active: true}, code: "x", flag: null, extra: "e"}, "!error"], + [{b: 0.1, items: [{qty: 21, tag: "zz"}, {price: 1, qty: 0.5, tag: "silver"}, {price: 2, qty: 2.5, tag: "b"}, {price: 3}], cust: {age: 26, tier: "x", active: false}, tier: "Gold", code: "gold ", flag: true}, "!error"], + [{items: null, cust: {age: 18, tier: "a", active: false}, tier: "x", flag: null}, "!error"], + ], +} + +{ + name: "gb033: 11 nodes, table*, expr, switch, table, table*, table, loop expr, expr, expr, expr, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["vip", "s", "s"], outputs: ["k422", "k423"], passThrough: true, outputPath: "res", rules: [ + ["null", "null", "", "false", "2"], + ["false", "startsWith($, 'g')", "", "true", "(a ?? -1)"], + ["true", "", "null", "false", "((price ?? 0)) / 2"], + ["false", "", "not('silver')", "false", "-5"], + ["true", "not('')", "'silver', 'b'", "false", "-5"], + ["false", "$ != 'silver'", "", "false", "2"], + ]}, + {expression: "e2", passThrough: true, fields: { + k424: "max([(price ?? -1), len(items ?? [])]) < (price ?? 1)", + "g.k425": "string(len(filter(items ?? [], #.tag == 'gold')))", + }}, + {switch: "s3", when: ["tier + '' + (tier ?? '') + ':' + lower(((items ?? [])[1].tag ?? '') + '!') == 'x'", "not (ceil((price ?? 0)) != min([(a ?? 1), price]))", "(not (vip == null)) and (a == null)", ""]}, + {table: "t4", inputs: ["tier", "tier", "s"], outputs: ["k422"], passThrough: true, rules: [ + ["'gold'", "'a', 'gold'", "''", "2"], + ["", "$ != 'a'", "$ != 'a'", "2"], + ["", "not('silver')", "not('gold')", "-5"], + ["'a', 'b'", "'a', 'gold'", "$ != 'silver'", "1 * (a ?? 1) * ((a ?? 1))"], + ["", "null", "'silver', 'b'", "0.25"], + ["", "", "", "(price ?? 0) * ((price ?? -1))"], + ]}, + {table: "t5", hit: "collect", inputs: ["s", "price", "vip"], outputs: ["k427[]", "res.k428"], outputPath: "o.p", rules: [ + ["'x', 'bronze'", "", "null", "true", "1"], + ["startsWith($, 's')", "", "false", "true", "1"], + ]}, + {table: "t6", inputs: ["''", "(1)"], outputs: ["res.k429"], outputPath: "o.p", rules: [ + ["'a'", "<= 15", "'mid'"], + ["$ != 'gold'", "", "'gold'"], + ["null", "null", "`${0.5}-${'gold'}` + '' + lower((true ? 'x' : 'x'))"], + ["'x', 'b'", "[100..105]", "'gold' + ' ' + 'x'"], + ["", "[0..1]", "''"], + ["", ">= 0", "''"], + ["", "", "'high'"], + ]}, + {expression: "e7", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k430: "(price ?? qty ?? 0)", + k422: "(tag ?? 'none')", + }}, + {expression: "e8", outputPath: "res", fields: { + "g.k432": "endsWith(string(2 != 2.25), 'g')", + "res.k433": "'A-1'", + "g.k434": "0.5", + k435: "null", + }}, + {expression: "e9", outputPath: "o.p", fields: { + k436: "null", + k437: "null", + }}, + {expression: "e10", passThrough: true, fields: { + "res.k438": "vip ?? vip", + k439: "vip", + "m.k440": "string(price in [0..10]) + ':' + upper(string((vip ?? false)))", + k441: "s ?? s", + }}, + {expression: "e11", fields: { + k442: "null", + "g.k443": "string((2.25) / 4 in [-5..5])", + k444: "3 + 10 + 1 * len('gold')", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "t1 -> s3", + "s3:3 -> t4", + "t4 -> t5", + "input -> t5", + "t5 -> t6", + "s3:0 -> e7", + "e7 -> e8", + "t5 -> e9", + "t1 -> e10", + "t5 -> e11", + "e2 -> output", + "s3:1 -> output", + "t6 -> output", + "e8 -> output", + "e9 -> output", + "e10 -> output", + "e11 -> output", + ], + }, + cases: [ + [{price: 101, tier: "x", vip: "true", items: [{price: [1], qty: 97, tag: "gold"}, {price: null, qty: 99, tag: "silver"}], s: {t: "x"}, a: 99}, {a: 99, g: {k425: "1", k443: "true"}, items: [{price: [1], qty: 97, tag: "gold"}, {price: null, qty: 99, tag: "silver"}], k424: false, k439: "true", k441: {t: "x"}, k444: 17, m: {k440: "false:TRUE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 101, res: {k438: "true"}, s: {t: "x"}, tier: "x", vip: "true"}], + [{price: 1000, tier: "zz", vip: null, items: [{price: 11, qty: 101, tag: "x"}, {price: 50, qty: null, tag: "a"}], s: "Gold", a: 0}, {a: 0, g: {k425: "0", k443: "true"}, items: [{price: 11, qty: 101, tag: "x"}, {price: 50, qty: null, tag: "a"}], k424: false, k441: "Gold", k444: 17, m: {k440: "false:FALSE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 1000, res: {k438: null}, s: "Gold", tier: "zz"}], + [{price: [1], tier: "gold", vip: 0, items: [{price: -1, qty: 11, tag: 5}, {price: 0, qty: 101, tag: ["gold"]}], s: "bronze", a: {v: 1}, extra: [1, 2]}, "!error"], + [{price: 1, tier: "gold", vip: false, items: [{price: null, qty: 7, tag: null}, {price: 21, qty: 0}, {price: -1, qty: -1, tag: "gold"}], s: null, a: null, extra: "e"}, {extra: "e", g: {k425: "1", k443: "true"}, items: [{price: null, qty: 7, tag: null}, {price: 21, qty: 0}, {price: -1, qty: -1, tag: "gold"}], k424: false, k439: false, k444: 17, m: {k440: "true:FALSE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 1, res: [{k422: false, k423: 2}], tier: "gold", vip: false}], + [{price: 0.5, tier: ["gold"], vip: false, items: [{price: null, qty: 100, tag: ["gold"]}, {price: 11, qty: -1, tag: "bronze"}], a: -0.1}, {a: -0.1, g: {k425: "0", k443: "true"}, items: [{price: null, qty: 100, tag: ["gold"]}, {price: 11, qty: -1, tag: "bronze"}], k424: false, k439: false, k444: 17, m: {k440: "true:FALSE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 0.5, res: {k438: false}, tier: ["gold"], vip: false}], + [{price: 1, tier: 5, vip: 0, items: [{price: 32, qty: 99, tag: "bronze"}, {price: 1, tag: "Gold"}, {price: 3, qty: "abc", tag: "gold"}, {price: -0.1, qty: 50, tag: ""}], s: 5, a: 19.99}, {a: 19.99, g: {k425: "1", k443: "true"}, items: [{price: 32, qty: 99, tag: "bronze"}, {price: 1, tag: "Gold"}, {price: 3, qty: "abc", tag: "gold"}, {price: -0.1, qty: 50, tag: ""}], k424: false, k439: 0, k441: 5, k444: 17, m: {k440: "true:0"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 1, res: [], s: 5, tier: 5, vip: 0}], + [{price: -1, tier: "gold", vip: true, items: [{price: 5, tag: "x"}, {price: 5, qty: 2, tag: "zz"}, {price: [1], qty: 50, tag: null}, {price: 7, qty: 19.99, tag: null}], s: "", a: 1}, {a: 1, g: {k425: "0", k443: "true"}, items: [{price: 5, tag: "x"}, {price: 5, qty: 2, tag: "zz"}, {price: [1], qty: 50, tag: null}, {price: 7, qty: 19.99, tag: null}], k424: false, k439: true, k441: "", k444: 17, m: {k440: "false:TRUE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: -1, res: [], s: "", tier: "gold", vip: true}], + [{price: 1000000000000000000000, tier: "b", vip: true, items: [{price: 11, qty: 3, tag: "zz"}, {price: 1, qty: 101, tag: "Gold"}], s: {t: "x"}}, {g: {k425: "0", k443: "true"}, items: [{price: 11, qty: 3, tag: "zz"}, {price: 1, qty: 101, tag: "Gold"}], k424: false, k439: true, k441: {t: "x"}, k444: 17, m: {k440: "false:TRUE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 1000000000000000000000, res: {k438: true}, s: {t: "x"}, tier: "b", vip: true}], + [{price: 7, tier: {t: "x"}, vip: false, items: [{price: 100, qty: 2, tag: "gold "}, {price: -25, qty: 1, tag: "gold"}, {price: -0.1, qty: 1000, tag: "x"}, {price: 19.99, qty: 18, tag: "x"}], s: {t: "x"}, a: 50}, {a: 50, g: {k425: "1", k443: "true"}, items: [{price: 100, qty: 2, tag: "gold "}, {price: -25, qty: 1, tag: "gold"}, {price: -0.1, qty: 1000, tag: "x"}, {price: 19.99, qty: 18, tag: "x"}], k424: false, k439: false, k441: {t: "x"}, k444: 17, m: {k440: "true:FALSE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 7, res: [{k422: false, k423: 2}], s: {t: "x"}, tier: {t: "x"}, vip: false}], + [{price: [1], tier: "Gold", vip: true, items: [{price: 5, qty: 1000, tag: "silver"}, {price: null, qty: null, tag: "silver"}, {price: 7, tag: ""}], s: 5, a: 1000}, "!error"], + [{price: true, tier: 5, vip: false, items: [{price: 7, qty: 10, tag: "bronze"}, {price: 11, qty: -25, tag: null}, {price: {v: 1}, qty: 0, tag: "b"}, {price: 3, qty: 19.99, tag: "Gold"}], s: "bronze", a: true}, "!error"], + [{price: -1, tier: 5, vip: false, items: [{price: 101, qty: -1, tag: "silver"}, {price: 0, qty: 1000000000000000000000, tag: "gold "}, {price: 0.5, qty: 2.5, tag: "zz"}], s: "gold ", a: {v: 1}}, {a: {v: 1}, g: {k425: "0", k443: "true"}, items: [{price: 101, qty: -1, tag: "silver"}, {price: 0, qty: 1000000000000000000000, tag: "gold "}, {price: 0.5, qty: 2.5, tag: "zz"}], k424: false, k439: false, k441: "gold ", k444: 17, m: {k440: "false:FALSE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: -1, res: {k438: false}, s: "gold ", tier: 5, vip: false}], + [{price: 3, tier: null, vip: true, items: [{price: 19.99, qty: -25, tag: ""}, {price: -1, tag: 5}], s: "silver", a: 10}, {a: 10, g: {k425: "0", k443: "true"}, items: [{price: 19.99, qty: -25, tag: ""}, {price: -1, tag: 5}], k424: false, k439: true, k441: "silver", k444: 17, m: {k440: "true:TRUE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 3, res: [], s: "silver", vip: true}], + [{price: 1, tier: "", vip: 1, items: 3, s: "x", a: [1]}, "!error"], + [{price: 18, tier: "zz", vip: null, items: [{price: 2.5, qty: 21, tag: "zz"}, {price: 19.99, qty: 0, tag: "silver"}], s: "b", a: -0.1}, {a: -0.1, g: {k425: "0", k443: "true"}, items: [{price: 2.5, qty: 21, tag: "zz"}, {price: 19.99, qty: 0, tag: "silver"}], k424: false, k441: "b", k444: 17, m: {k440: "false:FALSE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 18, res: {k438: null}, s: "b", tier: "zz"}], + [{price: 3, tier: "b", vip: null, items: [{price: -20, qty: 0.1, tag: "gold"}, {price: 1000000000000000000000, tag: "a"}, {price: -1, qty: 0.1, tag: true}], s: ["gold"], a: -0.1, extra: "e"}, {a: -0.1, extra: "e", g: {k425: "1", k443: "true"}, items: [{price: -20, qty: 0.1, tag: "gold"}, {price: 1000000000000000000000, tag: "a"}, {price: -1, qty: 0.1, tag: true}], k424: false, k441: ["gold"], k444: 17, m: {k440: "true:FALSE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 3, res: {k438: null}, s: ["gold"], tier: "b"}], + [{price: {v: 1}, tier: 5, vip: true, items: [{price: 2, qty: 101, tag: "zz"}, {price: 10, qty: 54, tag: "zz"}], a: 0.1}, "!error"], + [{price: 100, tier: "", vip: false, items: [{qty: "abc", tag: "gold"}], s: "gold", a: -1, extra: [1, 2]}, {a: -1, extra: [1, 2], g: {k425: "1", k443: "true"}, items: [{qty: "abc", tag: "gold"}], k424: false, k439: false, k441: "gold", k444: 17, m: {k440: "false:FALSE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 100, res: {k438: false}, s: "gold", tier: "", vip: false}], + [{price: {v: 1}, tier: "gold ", vip: true, items: [{price: 21, qty: 19.99, tag: "gold "}, {qty: 5, tag: "Gold"}], s: 5, a: 0}, "!error"], + [{price: 0.1, tier: ["gold"], vip: true, items: [{price: 1000, qty: null, tag: null}, {price: 10, tag: "bronze"}, {price: 11, qty: -1, tag: "silver"}], s: "gold", a: null}, {g: {k425: "0", k443: "true"}, items: [{price: 1000, qty: null, tag: null}, {price: 10, tag: "bronze"}, {price: 11, qty: -1, tag: "silver"}], k424: false, k439: true, k441: "gold", k444: 17, m: {k440: "true:TRUE"}, o: {p: {k436: null, k437: null, res: {k429: "gold"}}}, price: 0.1, res: {k438: true}, s: "gold", tier: ["gold"], vip: true}], + ], +} + +{ + name: "gb034: 12 nodes, loop table, loop table, expr, table, expr, table, expr, loop expr, table*, expr, switch*, table*", + graph: { + nodes: [ + {table: "t1", inputField: "items", executionMode: "loop", inputs: ["qty", "tag"], outputs: ["k445"], outputPath: "lines", rules: [ + ["10", "'x', 'b'", "true"], + ["[1..6)", "'', 'b'", "false"], + ["$ > 21 and $ < 71", "", "false"], + ]}, + {table: "t2", inputField: "items", executionMode: "loop", inputs: ["qty"], outputs: ["k446", "m.k447"], passThrough: true, outputPath: "res", rules: [ + ["< 100", "100", "false"], + ["21, 22", "100", "true"], + ["18", "1", "false"], + ["$ > 50 and $ < 55", "0.25", "true"], + ["", "2", "(price == (qty ?? 0) ? `${(qty ?? 0)}-${'gold'}` : 'none') in ['gold', 'silver', 'a']"], + ]}, + {expression: "e3", passThrough: true, fields: { + k448: "a ?? a", + }}, + {table: "t4", inputs: ["3", "''"], outputs: ["m.k449", "k445"], passThrough: true, rules: [ + ["50, 55", "$ != 'silver'", "'none'", "false"], + ["<= 23", "null", "''", "false"], + ["100, 105", "'gold', 'bronze'", "'low'", "true"], + ]}, + {expression: "e5", passThrough: true, fields: { + k451: "a + sum(map(items ?? [], #.price ?? 0))", + }}, + {table: "t6", inputs: ["a", "((a ?? -1))", "(not (true) ? a * a : a + (a ?? 1))"], outputs: ["k452", "k453"], passThrough: true, rules: [ + [">= -1", "100, 110", "5, 10", "2", "true"], + ["", "[-1..49]", "$ > -1 and $ < 9", "0.25", "((3) / 4 > (true ? (a ?? 1) : (a ?? 1))) or (a == null)"], + ["[50..60)", "not(18)", "5", "100", "true"], + ["", "", "", "0.25", "true"], + ["", "", "", "0", "false"], + ]}, + {expression: "e7", fields: { + k454: "lower(string(false))", + k455: "string((a ?? 1) + (k451))", + }}, + {expression: "e8", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + k456: "tag ?? qty", + k457: "`${(qty ?? 0)}-${(tag ?? '?')}`", + }}, + {table: "t9", hit: "collect", inputs: ["(k451 ?? 1) * a * (k451 ?? 1)", "k455", "upper((items ?? [])[0].tag ?? 'none')"], outputs: ["k458"], passThrough: true, rules: [ + ["-1, 0", "'x', 'b'", "'gold', 'gold'", "0"], + ["$ > 50 and $ < 100", "", "null", "100"], + ["[18..19]", "startsWith($, 's')", "not('')", "ceil((a ?? -1)) * 3"], + ["(5..6)", "", "", "(a ?? 0)"], + ["(5..6)", "", "not('')", "100"], + ["not(10)", "$ != 'gold'", "not('a')", "100"], + ]}, + {expression: "e10", passThrough: true, outputPath: "lines", fields: { + k459: "(endsWith('gold' + '' + '', 'x') ? round(min([2.25, a])) : -4)", + }}, + {switch: "s11", hit: "collect", when: ["not (((k451 ?? 1) in [0..10]))"]}, + {table: "t12", hit: "collect", inputs: ["m.k449", "(0 != 100 ? m.k449 + ' ' + 'x' : m.k449)"], outputs: ["g.k460", "k461"], outputPath: "res", rules: [ + ["startsWith($, 'x')", "startsWith($, 'g')", "(((k445 ?? false)) and (false) ? min([3, 0.5]) : 2) * 0.5", "0.25"], + ["'', 'bronze'", "startsWith($, 's')", "100", "1"], + ["", "", "10", "1"], + ]}, + ], + edges: [ + "input -> t1", + "input -> t2", + "t1 -> e3", + "t2 -> e3", + "t1 -> t4", + "e3 -> e5", + "e3 -> t6", + "e5 -> e7", + "t6 -> e8", + "e7 -> t9", + "e5 -> t9", + "t2 -> e10", + "e5 -> s11", + "t4 -> t12", + "e8 -> output", + "t9 -> output", + "e10 -> output", + "s11:0 -> output", + "t12 -> output", + ], + }, + cases: [ + [{items: [{price: -0.1, qty: null, tag: "bronze"}], a: 101, nums: [5, 0.1]}, {out: [{k456: "bronze", k457: "0-bronze"}]}], + [{items: [], nums: null}, "!error"], + [{items: [], a: 11, nums: [101, 3, 19.99], extra: 1}, {out: []}], + [{items: [], a: "5", nums: [101]}, "!error"], + [{items: [{price: [1], qty: 11, tag: "bronze"}, {price: true, qty: 11, tag: "gold "}], a: 1, nums: [-1, 10]}, "!error"], + [{items: [{price: 19.99, qty: 50, tag: "silver"}, {price: null, qty: 101, tag: ""}, {price: 1000, qty: 2.5, tag: "zz"}, {price: 18, qty: 0.1}], a: 10, nums: [3]}, {out: [{k456: "silver", k457: "50-silver"}, {k456: "", k457: "101-"}, {k456: "zz", k457: "2.5-zz"}, {k456: 0.1, k457: "0.1-?"}]}], + [{items: [{price: 19.99, qty: null, tag: "x"}, {price: 50, qty: 1000000000000000000000, tag: "gold"}, {price: 0.1, qty: -25, tag: "bronze"}, {price: 7, qty: 0.5, tag: "gold"}], nums: [-0.1]}, "!error"], + [{items: [{price: {v: 1}, qty: -25, tag: "silver"}, {price: 1000, tag: "zz"}], a: 1, nums: [100]}, "!error"], + [{items: [{qty: 0.1, tag: "a"}], a: 50, nums: [1000000000000000000000, 0.1, -0.1], extra: 1}, {out: [{k456: "a", k457: "0.1-a"}]}], + [{items: [{price: 5, qty: null, tag: "silver"}, {price: null, qty: 0, tag: "zz"}], a: 3, nums: [85, 0.1, 1000]}, {out: [{k456: "silver", k457: "0-silver"}, {k456: "zz", k457: "0-zz"}]}], + [{items: [1, 2], a: 99, nums: [0.5]}, "!error"], + [{items: [], nums: [114, 5]}, "!error"], + [{items: [{price: -25, qty: 21, tag: "silver"}, {price: true, qty: 1000, tag: "gold"}], a: 99, nums: [10]}, "!error"], + [{items: [{price: 99, tag: "zz"}], nums: [19.99, 7]}, "!error"], + [{items: [{price: 5, qty: 1, tag: "gold"}], a: null, nums: [99, 1000000000000000000000, 100]}, "!error"], + [{items: [{price: 1, qty: 99, tag: "Gold"}], a: 3, nums: [1000, 1000]}, {out: [{k456: "Gold", k457: "99-Gold"}]}], + [{items: [{price: 101, tag: "gold"}, {price: null, qty: 2, tag: "gold "}, {price: 7, qty: 45, tag: "silver"}], a: 3}, {out: [{k456: "gold", k457: "0-gold"}, {k456: "gold ", k457: "2-gold "}, {k456: "silver", k457: "45-silver"}]}], + [{items: [{price: 3, qty: -25, tag: "bronze"}, {price: 0.5, qty: -25, tag: "bronze"}], a: 2, nums: [10, 21, 11]}, {out: [{k456: "bronze", k457: "-25-bronze"}, {k456: "bronze", k457: "-25-bronze"}]}], + [{items: [{price: null, qty: -1, tag: null}], a: 10, nums: [21, 1000000000000000000000, 100]}, {out: [{k456: -1, k457: "-1-?"}]}], + [{items: [{price: 101, qty: 5, tag: "Gold"}, {price: -0.1, qty: -3, tag: ""}], a: 2.5, nums: [], extra: 1}, {out: [{k456: "Gold", k457: "5-Gold"}, {k456: "", k457: "-3-"}]}], + [{items: [{price: -0.1, qty: 11, tag: ""}, {price: true, qty: 1000, tag: "zz"}], a: 1, nums: [1000]}, "!error"], + ], +} + +{ + name: "gb035: 9 nodes, table*, loop table*, loop expr, switch, switch, table, expr, loop table*, table*", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputField: "cust", inputs: ["tier"], outputs: ["k462"], passThrough: true, outputPath: "res", rules: [ + ["startsWith($, 's')", "((active ?? false))"], + ["", "true"], + ["$ != 'a'", "false"], + ["'gold'", "true"], + ["", "false"], + ["", "false"], + ]}, + {table: "t2", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["len(string(true))", "tag"], outputs: ["k463[]"], outputPath: "res", rules: [ + ["not(0)", "'silver', 'gold'", "(qty ?? 1)"], + ["5, 55", "'x'", "0.25"], + ["", "'gold', 'b'", "2"], + ["", "$ != 'gold'", "(((qty ?? -1) + 0))"], + ]}, + {expression: "e3", inputField: "items", executionMode: "loop", outputPath: "o.p", fields: { + "m.k464": "2", + }}, + {switch: "s4", when: ["-(ceil(3)) != -4 - 0.5 % 2", ""]}, + {switch: "s5", when: ["a == null", "a != null"]}, + {table: "t6", inputs: ["(len('A-1')) / 10"], outputs: ["k465", "k466"], outputPath: "lines", rules: [ + ["null", "true", "100"], + ["[-1..4)", "true", "100"], + ["null", "false", "-5"], + ]}, + {expression: "e7", passThrough: true, fields: { + "res.k467": "null", + k468: "null", + "m.k469": "null", + k470: "(0 ?? $.k468 ?? 0)", + }}, + {table: "t8", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["`v${3}-${tag}`", "qty"], outputs: ["k471", "m.k472"], outputPath: "res", rules: [ + ["'x', 'gold'", "(18..68)", "0.25", "100"], + ["'a', 'bronze'", "!= 21", "-5", "1"], + ["", "null", "100", "1"], + ["startsWith($, 'g')", "[5..55]", "3", "-((qty ?? 1)) + (price ?? 0) * (price ?? 0) + qty"], + ["", "[50..60)", "-5", "-5"], + ["", "> 18", "0", "-5"], + ]}, + {table: "t9", hit: "collect", inputs: ["'' + '' + 'none' + '-' + 'none'", "10 + 0 % 7", "((2.25))"], outputs: ["k473"], passThrough: true, rules: [ + ["'x'", ">= 5", "not(0)", "'A-1'"], + ["null", "$ > 100 and $ < 110", "[21..26]", "'gold'"], + ["", "5", "", "''"], + ["", "(100..150)", "$ > 5 and $ < 6", "'gold'"], + ["", "", ">= 0", "'mid'"], + ["startsWith($, 's')", "", ">= 50", "'high'"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> t2", + "t1 -> e3", + "input -> e3", + "e3 -> s4", + "e3 -> s5", + "s5:1 -> t6", + "s5:1 -> e7", + "t1 -> t8", + "t8 -> t9", + "t2 -> output", + "s4:0 -> output", + "t6 -> output", + "e7 -> output", + "t9 -> output", + ], + }, + cases: [ + [{cust: {tier: "silver", active: false}, tier: "a", b: 5, score: 100, a: 19.99, items: [{price: 11, qty: 1000, tag: null}, {price: 21, qty: 11, tag: "bronze"}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 1000}], [{k463: 11}]]}], + [{cust: {age: -25, tier: "bronze", active: true}, tier: "Gold", b: 21, score: "5", a: -1, items: null}, "!error"], + [{cust: {age: 99, tier: null, active: false}, tier: "gold ", b: 0, score: 0.5, a: 50, items: [{price: 22, qty: 1000000000000000000000, tag: ""}, {price: true, qty: 0.5, tag: "gold"}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 1000000000000000000000}], [{k463: 2}]]}], + [{cust: {age: 1, tier: "", active: true}, tier: "gold ", b: 10, score: 101, a: 5, items: [{price: 100, qty: true, tag: "silver"}, {price: 10, qty: 99, tag: "Gold"}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[], [{k463: 99}]]}], + [{tier: "silver", b: 0.5, score: "abc", a: 10, items: [{price: null, qty: 21, tag: "b"}]}, {o: {p: [{m: {k464: 2}}]}, res: [[{k463: 2}, {k463: 21}]]}], + [{b: 19.99, score: true, a: 2, items: [{price: {v: 1}, qty: -7, tag: "Gold"}, {qty: -0.1, tag: "bronze"}], extra: 1}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: -7}], [{k463: -0.1}]]}], + [{cust: {age: 11, tier: "a", active: true}, score: 1000, a: {v: 1}, items: [{price: 5, qty: 18, tag: null}, {price: 0.5, qty: [1], tag: ["gold"]}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 18}], []]}], + [{cust: {age: 19.99, tier: "zz", active: false}, tier: "zz", b: [1], score: {v: 1}, a: -0.1, items: [{price: 7, qty: 1000000000000000000000, tag: ""}, {price: [1], qty: -0.1, tag: 5}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 1000000000000000000000}], [{k463: -0.1}]]}], + [{tier: ["gold"], b: 5, score: 54, a: 2, items: [{price: 10, qty: 3, tag: "x"}, {price: null, qty: 3, tag: "x"}, {price: 19.99, qty: 112, tag: null}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 3}], [{k463: 3}], [{k463: 112}]]}], + [{cust: {age: -25, tier: "silver", active: 1}, tier: null, b: 0.5, score: null, a: 0.5, items: []}, {o: {p: []}, res: []}], + [{cust: {age: -0.1, tier: true, active: true}, tier: "gold ", b: 10, score: 10, a: 21, items: [{price: 99, qty: 5, tag: "b"}]}, {o: {p: [{m: {k464: 2}}]}, res: [[{k463: 2}, {k463: 5}]]}], + [{cust: {tier: "b", active: false}, tier: "a", b: 21, score: {v: 1}, a: 21, items: [{price: 1000, qty: 1000, tag: "zz"}]}, {o: {p: [{m: {k464: 2}}]}, res: [[{k463: 1000}]]}], + [{cust: {age: 5, tier: "x", active: true}, tier: "zz", b: 0, score: {v: 1}, a: -1, items: [{price: 18, qty: 21, tag: "gold"}, {qty: 101, tag: "bronze"}, {price: 10, qty: 2.5, tag: "a"}], extra: 1}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 2}], [{k463: 101}], [{k463: 2.5}]]}], + [{cust: {age: 21, active: true}, tier: "gold ", b: 7, score: true, a: 1000000000000000000000, items: []}, {o: {p: []}, res: []}], + [{cust: "cust", tier: "zz", b: 19.99, score: 0.1, a: 50, items: [{price: 3, qty: null, tag: {t: "x"}}]}, {o: {p: [{m: {k464: 2}}]}, res: [[{k463: -1}]]}], + [{cust: {age: 19.99, tier: "gold ", active: true}, tier: ["gold"], b: 3, score: null, a: 3, items: 3}, "!error"], + [{cust: {age: 100, active: false}, tier: "silver", b: 1, score: {v: 1}, a: 1000, items: [{price: 99, qty: 0, tag: "Gold"}, {price: 10, tag: "x"}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 0}], [{k463: -1}]]}], + [{cust: {age: 100, tier: "silver", active: true}, tier: 5, b: "abc", score: -1, items: [{price: 5, qty: 1000, tag: null}, {price: 0.1, qty: null, tag: "gold "}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 1000}], [{k463: -1}]]}], + [{cust: {age: 99, tier: "Gold"}, tier: "a", b: null, score: 23, a: 0.5, items: 3, extra: {deep: {x: 1}}}, "!error"], + [{cust: {age: 3, tier: "gold "}, tier: {t: "x"}, b: 1000, score: "5", a: 50, items: [{price: true, qty: 2, tag: "bronze"}, {price: 21, qty: 99, tag: "b"}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 2}], [{k463: 2}, {k463: 99}]]}], + [{cust: {age: 0.1, tier: "silver", active: true}, tier: "bronze", b: [1], score: 1000000000000000000000, a: 0.5, items: [{price: null, qty: 11, tag: ["gold"]}, {qty: 1, tag: "b"}, {price: true, qty: 99, tag: "silver"}, {price: 99, qty: -25}], extra: 1}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}, {m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 11}], [{k463: 2}, {k463: 1}], [{k463: 99}], [{k463: -25}]]}], + [{cust: {age: 1000, tier: "bronze", active: false}, tier: "b", b: 1000, score: 19.99, a: 21, items: [{price: 100, qty: 1000, tag: true}, {price: "abc", tag: "silver"}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: 1000}], [{k463: -1}]]}], + [{cust: {age: 18, active: true}, tier: "zz", b: 19.99, score: 100, a: "abc", items: [{price: 3, tag: ""}, {price: 7, qty: 3, tag: ["gold"]}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: -1}], [{k463: 3}]]}], + [{cust: {age: 1, tier: {t: "x"}, active: false}, tier: "gold", b: null, score: [1], a: 7, items: [{price: -25, qty: null, tag: "zz"}, {price: 1000, qty: -25, tag: "x"}, {price: -0.1, qty: 3, tag: "gold"}, {price: 7, qty: 18, tag: "bronze"}]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}, {m: {k464: 2}}, {m: {k464: 2}}]}, res: [[{k463: -1}], [{k463: -25}], [{k463: 2}], [{k463: 18}]]}], + [{cust: {age: 11, tier: "zz", active: 1}, tier: "zz", b: 10, score: 1, a: 2, items: [{price: 99, qty: 10, tag: "b"}]}, {o: {p: [{m: {k464: 2}}]}, res: [[{k463: 2}, {k463: 10}]]}], + [{cust: {tier: null, active: false}, tier: "a", b: 99, a: -1, items: [1, 2]}, {o: {p: [{m: {k464: 2}}, {m: {k464: 2}}]}, res: [[], []]}], + ], +} + +{ + name: "gb036: 7 nodes, loop expr, loop expr, switch*, switch, expr, switch*, expr", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k474: "(qty ?? qty ?? 0) % 3", + k475: "tag ?? $.k474", + }}, + {expression: "e2", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k476: "string(((true) or (true)) and (true))", + k477: "(min([(qty), min([2.25, qty])]))", + k478: "len(string((qty ?? 1) * (price ?? -1)))", + k479: "(qty ?? 0)", + }}, + {switch: "s3", hit: "collect", when: ["(0.5 + 10 > max([0.5, 100]))", ""]}, + {switch: "s4", when: ["endsWith(string(false) + ':' + (false ? 'x' : ''), '')", "2 <= -(1 * 0.5)", "(3) != 1", ""]}, + {expression: "e5", fields: { + k480: "2 + 10 * 3", + k481: "null", + }}, + {switch: "s6", hit: "collect", when: ["true", "(0) + -4 > max([(true ? 2.25 : 0), (1) / 3])", ""]}, + {expression: "e7", fields: { + k483: "string((true ? -(10) : (2) / 4))", + k484: "null", + "m.k485": "(0.5 * 10 in [1..100])", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e2 -> s3", + "s3:1 -> s4", + "e2 -> s4", + "s4:1 -> e5", + "s4:2 -> e5", + "s4:3 -> s6", + "s4:2 -> e7", + "s6:0 -> e7", + "e1 -> output", + "s3:0 -> output", + "s4:0 -> output", + "e5 -> output", + "s6:2 -> output", + "e7 -> output", + ], + }, + cases: [ + [{s: "gold", tier: "a", vip: true, price: 50, score: 11, b: 7, cust: {age: null, tier: "", active: true}, items: [{}, {price: null, qty: 11, tag: "Gold"}, {price: 101, qty: 2, tag: "a"}, {price: -1, qty: 19.99, tag: "silver"}]}, "!error"], + [{vip: true, score: 18, items: [{price: 7, qty: 18, tag: "zz"}, {qty: -0.1, tag: "bronze"}]}, {items: [{price: 7, qty: 18, tag: "zz"}, {qty: -0.1, tag: "bronze"}], res: [{k474: 0, k475: "zz", price: 7, qty: 18, tag: "zz"}, {k474: -0.1, k475: "bronze", qty: -0.1, tag: "bronze"}], score: 18, vip: true}], + [{s: "", tier: "b", vip: true, price: 10, score: 0.1, b: 21, cust: {age: 2.5, tier: null, active: true}, items: []}, {b: 21, cust: {active: true, age: 2.5, tier: null}, items: [], price: 10, res: [], s: "", score: 0.1, tier: "b", vip: true}], + [{s: "gold", tier: "silver", vip: true, price: 10, score: 2.5, b: 1000000000000000000000, cust: null, items: [{price: 50, qty: 10, tag: "a"}, {price: 19.99, qty: 2.5, tag: ""}]}, {b: 1000000000000000000000, items: [{price: 50, qty: 10, tag: "a"}, {price: 19.99, qty: 2.5, tag: ""}], price: 10, res: [{k474: 1, k475: "a", price: 50, qty: 10, tag: "a"}, {k474: 2.5, k475: "", price: 19.99, qty: 2.5, tag: ""}], s: "gold", score: 2.5, tier: "silver", vip: true}], + [{s: "", tier: "a", vip: true, price: 1000000000000000000000, b: 99, cust: {age: 19.99, tier: "a", active: true}, items: [{price: 21, qty: 1}, {price: 5, qty: -1, tag: null}]}, {b: 99, cust: {active: true, age: 19.99, tier: "a"}, items: [{price: 21, qty: 1}, {price: 5, qty: -1, tag: null}], price: 1000000000000000000000, res: [{k474: 1, k475: 1, price: 21, qty: 1}, {k474: -1, k475: -1, price: 5, qty: -1, tag: null}], s: "", tier: "a", vip: true}], + [{tier: "silver", vip: false, price: 99, score: -25, b: -13, cust: {age: -1, tier: "silver", active: false}, items: [{price: 10, qty: 50, tag: "zz"}, {price: 11, qty: 18, tag: "silver"}]}, {b: -13, cust: {active: false, age: -1, tier: "silver"}, items: [{price: 10, qty: 50, tag: "zz"}, {price: 11, qty: 18, tag: "silver"}], price: 99, res: [{k474: 2, k475: "zz", price: 10, qty: 50, tag: "zz"}, {k474: 0, k475: "silver", price: 11, qty: 18, tag: "silver"}], score: -25, tier: "silver", vip: false}], + [{s: "bronze", tier: null, vip: false, price: null, score: -0.1, b: null, cust: {age: -25, tier: "silver", active: true}, items: [{price: null, qty: 0.5, tag: "x"}, {price: null, qty: 10, tag: "gold "}], extra: 1}, {cust: {active: true, age: -25, tier: "silver"}, extra: 1, items: [{price: null, qty: 0.5, tag: "x"}, {price: null, qty: 10, tag: "gold "}], res: [{k474: 0.5, k475: "x", price: null, qty: 0.5, tag: "x"}, {k474: 1, k475: "gold ", price: null, qty: 10, tag: "gold "}], s: "bronze", score: -0.1, vip: false}], + [{s: "Gold", tier: "Gold", vip: null, price: 99, score: 2, b: 2, items: [{price: 50, qty: 99, tag: "bronze"}, {price: 101, qty: -1, tag: "a"}, {price: 50, qty: 2, tag: "x"}]}, {b: 2, items: [{price: 50, qty: 99, tag: "bronze"}, {price: 101, qty: -1, tag: "a"}, {price: 50, qty: 2, tag: "x"}], price: 99, res: [{k474: 0, k475: "bronze", price: 50, qty: 99, tag: "bronze"}, {k474: -1, k475: "a", price: 101, qty: -1, tag: "a"}, {k474: 2, k475: "x", price: 50, qty: 2, tag: "x"}], s: "Gold", score: 2, tier: "Gold"}], + [{tier: "silver", vip: false, price: 33, score: 42, b: 18, cust: {age: 50, tier: null}, items: [{price: 11, qty: 18, tag: "gold "}, {price: 10, qty: 5, tag: ""}, {price: 2.5, tag: "zz"}]}, "!error"], + [{s: null, tier: "x", price: 7, b: 7, cust: {age: 101, tier: "gold", active: false}, items: [{price: 7, qty: 99, tag: "bronze"}, {price: 18, qty: 2.5, tag: "x"}]}, {b: 7, cust: {active: false, age: 101, tier: "gold"}, items: [{price: 7, qty: 99, tag: "bronze"}, {price: 18, qty: 2.5, tag: "x"}], price: 7, res: [{k474: 0, k475: "bronze", price: 7, qty: 99, tag: "bronze"}, {k474: 2.5, k475: "x", price: 18, qty: 2.5, tag: "x"}], tier: "x"}], + [{s: "silver", tier: "a", vip: true, price: 2, score: null, b: 11, cust: {age: -0.1, active: false}, items: []}, {b: 11, cust: {active: false, age: -0.1}, items: [], price: 2, res: [], s: "silver", tier: "a", vip: true}], + [{s: "Gold", tier: "Gold", price: 1, b: 101, cust: {tier: "Gold", active: false}, items: [{price: 99, qty: 0, tag: "bronze"}, {qty: 18, tag: "a"}, {price: 0.5, qty: 24, tag: "zz"}, {price: 7, qty: -25, tag: "x"}]}, {b: 101, cust: {active: false, tier: "Gold"}, items: [{price: 99, qty: 0, tag: "bronze"}, {qty: 18, tag: "a"}, {price: 0.5, qty: 24, tag: "zz"}, {price: 7, qty: -25, tag: "x"}], price: 1, res: [{k474: 0, k475: "bronze", price: 99, qty: 0, tag: "bronze"}, {k474: 0, k475: "a", qty: 18, tag: "a"}, {k474: 0, k475: "zz", price: 0.5, qty: 24, tag: "zz"}, {k474: -1, k475: "x", price: 7, qty: -25, tag: "x"}], s: "Gold", tier: "Gold"}], + [{s: "x", tier: "zz", vip: true, price: 50, score: 21, cust: {age: -25, tier: "silver", active: false}, items: [{price: 99, qty: 0, tag: ""}, {price: 2, qty: 100, tag: "zz"}, {price: 1000000000000000000000, qty: 1000000000000000000000, tag: "silver"}, {price: -1, qty: 1, tag: "zz"}]}, "!error"], + [{s: "a", tier: "gold", vip: true, price: 1000, score: 50, b: 18, cust: null, items: [{price: 21, qty: 0, tag: "x"}, {price: 56, qty: -0.1, tag: "a"}, {price: 1000000000000000000000, qty: 10, tag: "silver"}]}, {b: 18, items: [{price: 21, qty: 0, tag: "x"}, {price: 56, qty: -0.1, tag: "a"}, {price: 1000000000000000000000, qty: 10, tag: "silver"}], price: 1000, res: [{k474: 0, k475: "x", price: 21, qty: 0, tag: "x"}, {k474: -0.1, k475: "a", price: 56, qty: -0.1, tag: "a"}, {k474: 1, k475: "silver", price: 1000000000000000000000, qty: 10, tag: "silver"}], s: "a", score: 50, tier: "gold", vip: true}], + [{s: null, tier: "", vip: true, price: 10, score: 19.99, b: 21, cust: {age: 0.5, tier: "x", active: false}, items: []}, {b: 21, cust: {active: false, age: 0.5, tier: "x"}, items: [], price: 10, res: [], score: 19.99, tier: "", vip: true}], + [{s: "gold ", tier: "", vip: true, price: 100, score: null, b: 55, items: [{price: 5, qty: 19.99, tag: ""}, {price: 19.99, qty: 100, tag: ""}, {price: 3, qty: 0.1, tag: "gold "}, {price: 2.5, qty: 1, tag: "zz"}]}, {b: 55, items: [{price: 5, qty: 19.99, tag: ""}, {price: 19.99, qty: 100, tag: ""}, {price: 3, qty: 0.1, tag: "gold "}, {price: 2.5, qty: 1, tag: "zz"}], price: 100, res: [{k474: 1.99, k475: "", price: 5, qty: 19.99, tag: ""}, {k474: 1, k475: "", price: 19.99, qty: 100, tag: ""}, {k474: 0.1, k475: "gold ", price: 3, qty: 0.1, tag: "gold "}, {k474: 1, k475: "zz", price: 2.5, qty: 1, tag: "zz"}], s: "gold ", tier: "", vip: true}], + [{s: "gold ", tier: "gold ", vip: false, price: 100, score: 5, b: 3, cust: {age: 1000}, items: [{price: null, qty: 7, tag: "b"}, {price: 10, qty: 10, tag: ""}, {price: null, qty: 19.99, tag: "b"}, {price: 108, qty: null, tag: "Gold"}]}, "!error"], + [{s: "b", price: 10, score: 1000000000000000000000, b: 1000000000000000000000, cust: null, items: [{price: -0.1, qty: 18, tag: "zz"}, {price: 10, qty: 99, tag: "silver"}, {price: 100, tag: ""}, {price: 99, qty: -1, tag: "a"}], extra: "e"}, "!error"], + ], +} + +{ + name: "gb037: 7 nodes, switch, table, expr, expr, switch, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["(contains(string((vip ?? false)), 'x')) and (vip)", ""]}, + {table: "t2", inputs: ["b", "b"], outputs: ["k486", "k487"], passThrough: true, rules: [ + ["$ > 10 and $ < 15", "!= 0", "'mid'", "'high'"], + ["", "$ > 1 and $ < 11", "'high'", "'mid'"], + ["<= 68", "< 0", "'high'", "'low'"], + ["not(0)", "[21..26]", "'mid'", "'mid'"], + ["not(5)", "< 10", "'high'", "'mid'"], + ["(50..55)", "(0..1)", "'gold'", "'low'"], + ["", "", "'' + '-' + (tier ?? 'none')", "'mid'"], + ]}, + {expression: "e3", passThrough: true, fields: { + k487: "(tier ?? '?')", + k489: "not (((b ?? 1)) >= 2.25 * (b ?? -1))", + }}, + {expression: "e4", outputPath: "lines", fields: { + k490: "string(max(nums ?? [0]) < 2.25)", + "res.k491": "(3) <= ((b) / 4)", + k492: "vip ?? tier", + k493: "min([(b ?? -1) * b, len(tier)]) + ceil((b ?? 1))", + }}, + {switch: "s5", when: ["(vip ?? false)", "not ((contains((tier ?? 'none'), 'x')) or (-4 == (b ?? 0)))"]}, + {expression: "e6", passThrough: true, fields: { + k493: "0", + k495: "0", + k496: "k487 ?? b", + k497: "((b < (b ?? 0) ? (b ?? 1) : ((b ?? 1))))", + }}, + {table: "t7", inputs: ["lines.k490", "lines.k493", "lines.res.k491"], outputs: ["k498", "k499"], passThrough: true, rules: [ + ["'a'", "< 50", "", "string(((lines.k493 ?? 1)) == (3))", "-5"], + ["'silver'", "$ > 5 and $ < 10", "", "'gold'", "0.25"], + ["$ != 'gold'", ">= 0", "null", "''", "((-((lines.k493 ?? -1))) / 10)"], + ["''", "<= 15", "$ == true", "'low'", "(0 * (lines.k493 ?? 1) + (lines.k493 ?? 0))"], + ["$ != 'gold'", "[10..60]", "false", "'gold'", "100"], + ]}, + ], + edges: [ + "input -> s1", + "s1:1 -> t2", + "s1:0 -> e3", + "s1:1 -> e3", + "s1:1 -> e4", + "input -> s5", + "e3 -> e6", + "e4 -> t7", + "t2 -> output", + "s5:0 -> output", + "e6 -> output", + "t7 -> output", + ], + }, + cases: [ + [{flag: false, vip: true, tier: "gold ", nums: null}, "!error"], + [{flag: "true", vip: 0, tier: "silver", nums: null, b: 0.1}, {b: 0.1, flag: "true", k486: "-silver", k487: "mid", k489: true, k493: 0, k495: 0, k496: "silver", k497: 0.1, lines: {k490: "true", k492: 0, k493: 1.01, res: {k491: false}}, tier: "silver", vip: 0}], + [{flag: false, vip: 1, tier: true, nums: [2.5, 100, 18], b: 19.99}, "!error"], + [{flag: false, vip: false, tier: "gold", nums: [3], b: [1]}, "!error"], + [{flag: true, vip: true, tier: "x", nums: ["1", 2], b: 2.5}, "!error"], + [{flag: true, vip: false, nums: [], b: "abc"}, "!error"], + [{flag: false, vip: "no", tier: true, nums: "1,2", b: 2.5}, "!error"], + [{flag: null, vip: false, tier: "a", nums: "1,2", b: {v: 1}}, "!error"], + [{flag: false, vip: true, tier: "x", nums: [2.5, 100], b: 1000}, {b: 1000, flag: false, k486: "-x", k487: "mid", k489: true, k493: 0, k495: 0, k496: "x", k497: 1000, lines: {k490: "false", k492: true, k493: 1001, res: {k491: true}}, nums: [2.5, 100], tier: "x", vip: true}], + [{flag: false, vip: null, tier: null, nums: ["1", 2], b: null}, "!error"], + [{flag: true, vip: true, tier: "zz", nums: [3, 0.1, 5, 100, 7], b: [1]}, "!error"], + [{flag: false, vip: false, tier: "a", nums: null, b: 100}, {b: 100, flag: false, k486: "-a", k487: "mid", k489: true, k493: 0, k495: 0, k496: "a", k497: 100, lines: {k490: "true", k492: false, k493: 101, res: {k491: true}}, tier: "a", vip: false}], + [{flag: true, vip: 0, tier: "a", nums: []}, "!error"], + [{flag: "no", vip: "no", tier: 5, nums: [7, 2], b: 11}, "!error"], + [{flag: false, tier: "bronze", nums: null, b: 3}, {b: 3, flag: false, k486: "high", k487: "mid", k489: true, k493: 0, k495: 0, k496: "bronze", k497: 3, lines: {k490: "true", k492: "bronze", k493: 9, res: {k491: false}}, tier: "bronze"}], + [{flag: true, vip: null, nums: [], b: 19.99}, "!error"], + [{flag: false, tier: null, nums: [1], b: null, extra: "e"}, "!error"], + [{flag: false, vip: true, nums: [-25, 101, 101], b: -1}, "!error"], + [{flag: true, vip: null, tier: null, nums: [7], b: -0.1}, "!error"], + [{flag: false, vip: false, tier: "bronze", nums: null, b: 0.5, extra: 1}, {b: 0.5, extra: 1, flag: false, k486: "-bronze", k487: "mid", k489: true, k493: 0, k495: 0, k496: "bronze", k497: 0.5, lines: {k490: "true", k492: false, k493: 1.25, res: {k491: false}}, tier: "bronze", vip: false}], + [{flag: true, vip: "no", tier: "silver", b: 10}, {b: 10, flag: true, k486: "high", k487: "mid", k489: true, k493: 0, k495: 0, k496: "silver", k497: 10, k498: "gold", k499: 100, lines: {k490: "true", k492: "no", k493: 16, res: {k491: false}}, tier: "silver", vip: "no"}], + [{flag: true, tier: "zz", nums: null, b: 99}, {b: 99, flag: true, k486: "-zz", k487: "mid", k489: true, k493: 0, k495: 0, k496: "zz", k497: 99, lines: {k490: "true", k492: "zz", k493: 101, res: {k491: true}}, tier: "zz"}], + [{flag: true, vip: null, tier: {t: "x"}, nums: 7, b: 2.5}, "!error"], + [{flag: null, tier: true, nums: [0.1], b: "abc"}, "!error"], + [{flag: true, vip: false, tier: "Gold", nums: [99], b: 96, extra: 1}, {b: 96, extra: 1, flag: true, k486: "-Gold", k487: "mid", k489: true, k493: 0, k495: 0, k496: "Gold", k497: 96, lines: {k490: "false", k492: false, k493: 100, res: {k491: true}}, nums: [99], tier: "Gold", vip: false}], + [{flag: true, vip: true, tier: true, nums: [50, 10], b: 1000, extra: [1, 2]}, "!error"], + [{flag: false, vip: null, tier: "zz", nums: [7, 3], b: 99}, {b: 99, flag: false, k486: "-zz", k487: "mid", k489: true, k493: 0, k495: 0, k496: "zz", k497: 99, lines: {k490: "false", k492: "zz", k493: 101, res: {k491: true}}, nums: [7, 3], tier: "zz"}], + [{flag: true, vip: 1, tier: "gold", nums: [99, 2.5], b: 10}, {b: 10, flag: true, k486: "high", k487: "mid", k489: true, k493: 0, k495: 0, k496: "gold", k497: 10, k498: "gold", k499: 100, lines: {k490: "false", k492: 1, k493: 14, res: {k491: false}}, nums: [99, 2.5], tier: "gold", vip: 1}], + ], +} + +{ + name: "gb038: 12 nodes, expr, table*, table*, expr, expr, expr, expr, table, expr, table, table, expr", + graph: { + nodes: [ + {expression: "e1", fields: { + k500: "code ?? code", + }}, + {table: "t2", hit: "collect", inputs: ["-4", "100"], outputs: ["k501[]"], outputPath: "res", rules: [ + ["", ">= -1", "''"], + ["0, 50", "[10..11)", "'mid'"], + ["not(10)", "50", "''"], + ["18", "null", "'mid'"], + ["", "<= 15", "''"], + ]}, + {table: "t3", hit: "collect", inputs: ["string(a == null)", "'gold' + '' + 'none' + '' + string(false)", "10"], outputs: ["k502", "k503"], passThrough: true, outputPath: "out", rules: [ + ["not('')", "not('a')", "< 1", "'gold'", "3"], + ["", "", "(100..110)", "string(not (100 > 0.5))", "0.25"], + ["startsWith($, '')", "$ != 'gold'", "!= 21", "string(true)", "0"], + ["'gold'", "'a'", "!= 18", "'mid'", "0.25"], + ]}, + {expression: "e4", fields: { + "m.k504": "null", + "m.k505": "true", + }}, + {expression: "e5", passThrough: true, outputPath: "o.p", fields: { + "res.k506": "(endsWith('', 'a'))", + k507: "'A-1'", + k508: "round(1 + 2.25) <= 3", + }}, + {expression: "e6", fields: { + "m.k509": "(1 * 0 != 3 * 100)", + "m.k510": "false", + k511: "string((1) < (100))", + k512: "string(true)", + }}, + {expression: "e7", passThrough: true, fields: { + k513: "100", + "res.k514": "-4 in [1..100]", + "res.k516": "((100) / 2) / 3 % 2", + }}, + {table: "t8", inputs: ["m.k510"], outputs: ["k517"], rules: [ + ["true", "''"], + ["false", "'gold'"], + ["null", "string((k512 ?? '') + '' + '' != 'gold')"], + ["null", "'high'"], + ["", "'mid'"], + ]}, + {expression: "e9", passThrough: true, fields: { + k518: "o.p.k507 + ':' + string((o.p.res.k506 ?? false)) in ['gold', 'silver', 'a']", + k519: "2.25 % 3", + k520: "true", + k521: "o.p.k507 ?? o.p.k507", + }}, + {table: "t10", inputs: ["k513", "k511"], outputs: ["m.k522"], passThrough: true, outputPath: "res", rules: [ + ["$ > 100 and $ < 150", "null", "0"], + ["null", "'x'", "-5"], + ["", "'a'", "floor((k513 ?? 1))"], + ["< -1", "not('')", "1"], + ]}, + {table: "t11", inputs: ["`n=${0.5}-${(k517 ?? 'none')}`"], outputs: ["k523"], passThrough: true, rules: [ + ["''", "'mid'"], + ["null", "'low'"], + ["", "(ceil(1) != min([-4, 2.25]) ? (2 < 100 ? lower((k517 ?? '?')) : string(-4)) : (k517 ?? '?'))"], + ]}, + {expression: "e12", passThrough: true, fields: { + k524: "(res.k514 ? (res.k516 ?? res.k516 ?? 0) * len(k512) : (((m.k509 ?? false) ? 0.5 : 0.5)))", + "g.k525": "-((res.m.k522 ?? 1)) in [0..10]", + }}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "t2 -> t3", + "t3 -> e4", + "t2 -> e5", + "t3 -> e6", + "t3 -> e7", + "e7 -> t8", + "e6 -> t8", + "e5 -> e9", + "e6 -> t10", + "e7 -> t10", + "t8 -> t11", + "t10 -> e12", + "e4 -> output", + "t8 -> output", + "e9 -> output", + "t11 -> output", + "e12 -> output", + ], + }, + cases: [ + [{nums: [-0.1, 5, -1, 18, 100], flag: false, code: "gold", a: -25}, "!error"], + [{nums: "1,2", flag: true, code: "bronze", a: 18}, "!error"], + [{nums: [-0.1, 1000], flag: false, code: "bronze", a: 11}, "!error"], + [{code: "bronze", a: 99}, "!error"], + [{nums: [{x: 1}], flag: null, code: "gold", a: 1000}, "!error"], + [{flag: false, code: "", a: 19.99}, "!error"], + [{nums: null, flag: true, code: "Gold", a: 5, extra: [1, 2]}, "!error"], + [{nums: [2.5, -7, 3, 1000, -25], flag: true, code: "a"}, "!error"], + [{nums: [19.99, 0.1], flag: true, code: "a", a: true}, "!error"], + [{nums: [], flag: true, code: "x", a: 0.1}, "!error"], + [{flag: null, code: ["gold"], a: 7}, "!error"], + [{nums: [], flag: true, code: "a", a: -1}, "!error"], + [{nums: [], flag: false, code: {t: "x"}, a: 7}, "!error"], + [{nums: 7, flag: false, code: "bronze", a: 3}, "!error"], + [{nums: [-1], flag: true, code: "zz", a: 1000, extra: {deep: {x: 1}}}, "!error"], + [{nums: [], flag: true, code: "silver", a: "abc"}, "!error"], + [{nums: "1,2", flag: "no", a: null}, "!error"], + [{flag: 1, code: "", a: "abc"}, "!error"], + [{nums: [1000000000000000000000, 101, 101, 3, 100], code: "a", a: {v: 1}}, "!error"], + [{nums: [2.5, 99, 0.5], flag: true, code: "gold", a: null}, "!error"], + [{nums: [1000, -0.1, 100, -1, 0.5], flag: true, code: "gold ", a: 19.99, extra: {deep: {x: 1}}}, "!error"], + [{nums: [0, 10, 18, 73, 1000000000000000000000], flag: true, code: "Gold", a: 99}, "!error"], + [{nums: ["1", 2], flag: true, code: null, a: [1]}, "!error"], + [{nums: [1000000000000000000000, 50, 3, 18, 99], flag: false, code: "x", a: "5"}, "!error"], + [{nums: [{x: 1}], flag: false, code: null, a: 0.5}, "!error"], + [{nums: [101], flag: "true", code: "bronze", a: 18}, "!error"], + ], +} + +{ + name: "gb039: 6 nodes, table*, expr, expr, table*, expr, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["tier"], outputs: ["res.k526", "k527"], passThrough: true, outputPath: "out", rules: [ + ["'a'", "1", "true"], + ["startsWith($, 's')", "100", "false"], + ["'a', 'bronze'", "10", "((score ?? 1) > max([(score ?? 0), (a ?? 0)])) and (not (contains((tier ?? '?'), 'x')))"], + ["not('x')", "2", "true"], + ["", "0", "(score ?? -1) in [1..100]"], + ["null", "0.25", "((score ?? -1) * (b ?? 0) in [1..100]) or ((flag ?? false))"], + ]}, + {expression: "e2", passThrough: true, fields: { + k528: "tier ?? tier", + }}, + {expression: "e3", passThrough: true, fields: { + k529: "not ((tier ?? '?') == 'silver')", + "m.k530": "(tier ?? '?') + '-' + string((a ?? -1) in [1..100])", + k528: "score ?? tier", + }}, + {table: "t4", hit: "collect", inputs: ["tier"], outputs: ["k532"], passThrough: true, rules: [ + ["'a'", "false"], + ["'x'", "false"], + ["not('gold')", "not ((0.5 >= (a ?? -1)))"], + ["", "(tier ?? '') in ['gold', 'silver', 'a']"], + ]}, + {expression: "e5", passThrough: true, fields: { + k528: "(ceil(score * 2))", + "res.k534": "tier", + "res.k526": "tier ?? a", + }}, + {expression: "e6", passThrough: true, fields: { + k536: "(100 * (b ?? 0)) + ((b ?? -1) * (b ?? 1)) / 10", + k537: "$.k536 != null", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "t1 -> e2", + "input -> e3", + "e2 -> t4", + "t1 -> e5", + "e5 -> e6", + "e2 -> e6", + "e2 -> output", + "e3 -> output", + "t4 -> output", + "e6 -> output", + ], + }, + cases: [ + [{b: 0.1, flag: false, a: 101, tier: "zz"}, "!error"], + [{b: 1000000000000000000000, score: 100, flag: false, a: 7, tier: null}, "!error"], + [{b: 0.5, flag: false, a: 7}, "!error"], + [{b: 1, score: 100, flag: true, a: 1000, tier: "gold "}, {a: 1000, b: 1, flag: true, k528: "gold ", k529: true, m: {k530: "gold -false"}, out: [{k527: true, res: {k526: 0}}], score: 100, tier: "gold "}], + [{b: -25, flag: true, a: 0.1, tier: "x"}, "!error"], + [{score: 19.99, flag: false, a: null, tier: "a"}, {flag: false, k528: "a", k529: true, m: {k530: "a-false"}, out: [{k527: true, res: {k526: 1}}, {k527: false, res: {k526: 10}}, {k527: true, res: {k526: 0}}], score: 19.99, tier: "a"}], + [{b: 5, score: 1000000000000000000000, flag: false, a: null, tier: "gold"}, {b: 5, flag: false, k528: "gold", k529: true, m: {k530: "gold-false"}, out: [{k527: false, res: {k526: 0}}], score: 1000000000000000000000, tier: "gold"}], + [{score: 0.1, flag: false, a: 19.99, tier: "b"}, {a: 19.99, flag: false, k528: "b", k529: true, m: {k530: "b-true"}, out: [{k527: false, res: {k526: 0}}], score: 0.1, tier: "b"}], + [{b: 1, score: 11, flag: false, a: 19.99, tier: ""}, {a: 19.99, b: 1, flag: false, k528: "", k529: true, m: {k530: "-true"}, out: [{k527: true, res: {k526: 0}}], score: 11, tier: ""}], + [{b: 21, score: 21, flag: false, a: 3, tier: "zz"}, {a: 3, b: 21, flag: false, k528: "zz", k529: true, m: {k530: "zz-true"}, out: [{k527: true, res: {k526: 0}}], score: 21, tier: "zz"}], + [{b: 18, score: 10, flag: true, tier: "", extra: 1}, {b: 18, extra: 1, flag: true, k528: "", k529: true, m: {k530: "-false"}, out: [{k527: true, res: {k526: 0}}], score: 10, tier: ""}], + [{b: 1000, score: 7, flag: false, a: 7, tier: "gold "}, {a: 7, b: 1000, flag: false, k528: "gold ", k529: true, m: {k530: "gold -true"}, out: [{k527: true, res: {k526: 0}}], score: 7, tier: "gold "}], + [{b: null, score: 14, flag: true, tier: "gold "}, {flag: true, k528: "gold ", k529: true, m: {k530: "gold -false"}, out: [{k527: true, res: {k526: 0}}], score: 14, tier: "gold "}], + [{score: 0.5, flag: true, a: 0.5, tier: "b", extra: {deep: {x: 1}}}, {a: 0.5, extra: {deep: {x: 1}}, flag: true, k528: "b", k529: true, m: {k530: "b-false"}, out: [{k527: false, res: {k526: 0}}], score: 0.5, tier: "b"}], + [{b: 1000000000000000000000, score: -0.1, flag: false, a: 10, tier: "a", extra: {deep: {x: 1}}}, "!error"], + [{b: null, score: 2.5, flag: true, a: 7, tier: "zz"}, {a: 7, flag: true, k528: "zz", k529: true, m: {k530: "zz-true"}, out: [{k527: true, res: {k526: 0}}], score: 2.5, tier: "zz"}], + [{b: -1, score: 0.1, flag: true, a: 0.5, tier: "Gold"}, {a: 0.5, b: -1, flag: true, k528: "Gold", k529: true, m: {k530: "Gold-false"}, out: [{k527: false, res: {k526: 0}}], score: 0.1, tier: "Gold"}], + [{b: -0.1, score: 1000000000000000000000, flag: true, a: -1, tier: "gold"}, {a: -1, b: -0.1, flag: true, k528: "gold", k529: true, m: {k530: "gold-false"}, out: [{k527: false, res: {k526: 0}}], score: 1000000000000000000000, tier: "gold"}], + [{b: 2, score: 1000000000000000000000, flag: false, a: -1, tier: "a"}, {a: -1, b: 2, flag: false, k528: "a", k529: true, m: {k530: "a-false"}, out: [{k527: true, res: {k526: 1}}, {k527: false, res: {k526: 10}}, {k527: false, res: {k526: 0}}], score: 1000000000000000000000, tier: "a"}], + [{b: 2.5, score: 50, flag: true, a: 3, tier: null}, {a: 3, b: 2.5, flag: true, k528: 50, k529: true, m: {k530: "?-true"}, out: [{k527: true, res: {k526: 0}}, {k527: true, res: {k526: 0.25}}], score: 50}], + [{b: 0, score: 2, flag: false, a: 100, tier: "b"}, {a: 100, b: 0, flag: false, k528: "b", k529: true, m: {k530: "b-true"}, out: [{k527: true, res: {k526: 0}}], score: 2, tier: "b"}], + [{b: 10, score: 1000000000000000000000, flag: true, a: 18, tier: ""}, {a: 18, b: 10, flag: true, k528: "", k529: true, m: {k530: "-true"}, out: [{k527: false, res: {k526: 0}}], score: 1000000000000000000000, tier: ""}], + [{b: 101, score: -1, flag: null, a: 50, tier: "b"}, {a: 50, b: 101, k528: "b", k529: true, m: {k530: "b-true"}, out: [{k527: false, res: {k526: 0}}], score: -1, tier: "b"}], + [{b: null, score: 101, flag: true, extra: [1, 2]}, {extra: [1, 2], flag: true, k528: 101, k529: true, m: {k530: "?-false"}, out: [{k527: false, res: {k526: 0}}, {k527: true, res: {k526: 0.25}}], score: 101}], + ], +} + +{ + name: "gb040: 11 nodes, expr, expr, expr, table*, table, switch*, expr, expr, switch, expr, expr", + graph: { + nodes: [ + {expression: "e1", fields: { + k538: "ceil((price ?? 1))", + }}, + {expression: "e2", fields: { + "res.k539": "(2.25 * 2.25) != ((flag ?? false) ? (a ?? 0) : (false ? (a ?? -1) : 0.5))", + k540: "lower(string((flag) or (flag)))", + }}, + {expression: "e3", fields: { + k541: "-((res.k539 ? a : (price ?? -1)) * ((price ?? 0)) / 3)", + k542: "(a ?? $.k541 ?? 0)", + k543: "(len('gold') < (price)) and (price in [1..100])", + }}, + {table: "t4", hit: "collect", inputs: ["tier"], outputs: ["k544", "m.k545"], passThrough: true, rules: [ + ["startsWith($, 'a')", "'gold'", "false"], + ["'x', 'b'", "(tier ?? '')", "0.5 < round((a ?? -1))"], + ]}, + {table: "t5", inputs: ["res.k539"], outputs: ["k546", "k547"], rules: [ + ["", "'gold'", "'high'"], + ["$ == true", "'mid'", "'high'"], + ["true", "'gold'", "'mid'"], + ["$ == true", "''", "'mid'"], + ["", "'gold'", "''"], + ["true", "'high'", "''"], + ]}, + {switch: "s6", hit: "collect", when: ["true", "not (k543 == null)", "contains('A-1' + ':' + 'A-1' + '' + 'x' + ' ' + '', 'x')", ""]}, + {expression: "e7", passThrough: true, fields: { + k548: "`${(k542 ?? -1)}-${''}`", + "res.k549": "k542", + k550: "lower(string((k543 ?? false)) + ':' + 'none')", + }}, + {expression: "e8", passThrough: true, fields: { + k551: "k542", + k552: "(k541) - 2", + "m.k545": "len($nodes.e2.k540) * (false ? (k542 ?? -1) : $nodes.e3.k542) + len('none') % 3", + }}, + {switch: "s9", when: ["(k543 ?? false)", ""]}, + {expression: "e10", outputPath: "o.p", fields: { + k554: "false", + }}, + {expression: "e11", fields: { + k555: "3 - (k541 ?? 1) * k541 != 100 * k541 + (k552)", + k556: "string(string((k542 ?? 1)) != 'x')", + k557: "`n=${-4}-${'x'}` in ['gold', 'silver', 'a']", + "res.k558": "(((k551 ?? 1)) / 10)", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "input -> e3", + "e2 -> e3", + "input -> t4", + "e2 -> t5", + "e3 -> s6", + "s6:2 -> e7", + "s6:1 -> e8", + "e8 -> s9", + "e3 -> e10", + "s9:0 -> e11", + "e1 -> output", + "t4 -> output", + "t5 -> output", + "s6:0 -> output", + "s6:3 -> output", + "e7 -> output", + "e10 -> output", + "e11 -> output", + ], + }, + cases: [ + [{a: [1], nums: [0.1, 99], price: "abc", code: "Gold", flag: null, tier: "gold "}, "!error"], + [{a: null, nums: [5, 100, 1000000000000000000000], price: "5", code: 5, flag: true, tier: "Gold", extra: [1, 2]}, "!error"], + [{a: 0.1, nums: [3, -1], price: 7, code: "silver", flag: true, tier: {t: "x"}, extra: {deep: {x: 1}}}, {k538: 7}], + [{a: "5", nums: ["1", 2], price: null, code: "", flag: true, tier: "silver"}, "!error"], + [{a: "5", nums: [-25, 21, 3], price: 100, code: "gold ", flag: false, tier: ["gold"], extra: [1, 2]}, "!error"], + [{a: "abc", nums: [101, 21], price: "5", code: "Gold", flag: true, tier: "gold"}, "!error"], + [{a: "abc", price: [1], code: "bronze", flag: true}, "!error"], + [{a: 3, nums: [-1, 21, 99, 19.99, 5], price: 1, code: "Gold", flag: false, tier: ["gold"]}, {k538: 1}], + [{a: "abc", nums: [], price: "5", flag: true}, "!error"], + [{a: "abc", nums: [], price: 10, code: "Gold", flag: true, tier: "Gold"}, "!error"], + [{a: {v: 1}, nums: [2, 101, 0.5, 0.5, 11], price: true, code: "bronze", tier: ""}, "!error"], + [{a: 2.5, nums: [53], price: 2.5, code: "zz", flag: null, tier: null}, "!error"], + [{a: 3, nums: null, price: 100, code: 5, flag: true, tier: {t: "x"}}, {k538: 100}], + [{a: 2, nums: "1,2", price: [1], code: "x", tier: "silver"}, "!error"], + ], +} + +{ + name: "gb041: 10 nodes, expr, expr, switch, expr, switch, table, table, expr, expr, table", + graph: { + nodes: [ + {expression: "e1", fields: { + k559: "flag ?? s", + k560: "flag ?? flag", + k561: "((flag ?? false)) or (s != null)", + }}, + {expression: "e2", passThrough: true, fields: { + k562: "(price ?? a ?? 0) + (price ?? -1)", + k563: "a ?? flag", + }}, + {switch: "s3", when: ["(string(10) in ['gold', 'silver', 'a']) or (k561)", "k561 != null"]}, + {expression: "e4", passThrough: true, outputPath: "res", fields: { + k561: "(0 ?? k559 ?? 0)", + k565: "`n=${1}-${''}`", + }}, + {switch: "s5", when: ["(((k561 ?? false)) or (res.k561 != 0)) or (k561)", "startsWith(string((k561) and (true)), '')", ""]}, + {table: "t6", inputs: ["res.k565", "res.k561", "res.k565"], outputs: ["k559", "k567"], rules: [ + ["null", "not(50)", "", "''", "true"], + ["not('silver')", "(18..23)", "null", "'gold'", "false"], + ["$ != 'silver'", "null", "null", "'high'", "false"], + ["$ != 'gold'", "$ > 100 and $ < 110", "", "'low'", "(res.k561 ?? 1) + (res.k561 ?? k560 ?? 0) <= ((res.k561 ?? -1) != (res.k561 ?? 1) ? ((res.k561 ?? 0)) : -((res.k561 ?? 0)))"], + ["'x'", "5, 15", "", "(res.k565 ?? '')", "false"], + ]}, + {table: "t7", inputs: ["flag", "s", "price"], outputs: ["k568"], rules: [ + ["true", "not('x')", "", "(endsWith((s ?? ''), '') ? ((price ?? 0)) / 0.5 : -4) - ((price ?? -1) == (a ?? -1) ? (a ?? -1) : (1) / 2)"], + ["null", "not('')", "!= 50", "1"], + ["true", "startsWith($, 's')", "21", "100"], + ["null", "startsWith($, 'g')", "not(-1)", "0"], + ["false", "startsWith($, '')", "", "0"], + ]}, + {expression: "e8", outputPath: "out", fields: { + k569: "true", + }}, + {expression: "e9", outputPath: "res", fields: { + "res.k570": "(res.k565 ?? '?') + '' + string(res.k561 > 1)", + k571: "(len(res.k565))", + k561: "`v${res.k561}-${'none'}` == 'x'", + }}, + {table: "t10", inputs: ["'A-1'"], outputs: ["k573", "k574"], passThrough: true, rules: [ + ["", "true", "'high'"], + ["", "true", "string((0.5 <= 2) or (((k561 ?? false)) and ((k561 ?? false))))"], + ["'a'", "true", "'mid'"], + ["'a'", "((2.25) in [0..10]) or ((k561 ?? false))", "'gold'"], + ["", "true", "'gold'"], + ]}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e1 -> s3", + "s3:0 -> e4", + "e4 -> s5", + "s5:0 -> t6", + "s5:1 -> t6", + "input -> t7", + "t7 -> e8", + "s5:2 -> e9", + "e1 -> t10", + "e2 -> output", + "s3:1 -> output", + "t6 -> output", + "e8 -> output", + "e9 -> output", + "t10 -> output", + ], + }, + cases: [ + [{s: ["gold"], a: 99, flag: true, price: null}, {a: 99, flag: true, k559: true, k560: true, k561: true, k562: 98, k563: 99, k573: true, k574: "high", out: {k569: true}, s: ["gold"]}], + [{s: "gold ", a: {v: 1}, flag: false, price: 50}, {a: {v: 1}, flag: false, k559: false, k560: false, k561: true, k562: 100, k563: {v: 1}, k573: true, k574: "high", out: {k569: true}, price: 50, s: "gold "}], + [{s: "gold", a: 2.5, flag: true, price: 0}, {a: 2.5, flag: true, k559: true, k560: true, k561: true, k562: 0, k563: 2.5, k573: true, k574: "high", out: {k569: true}, price: 0, s: "gold"}], + [{s: "a", a: 11, flag: true, price: null}, {a: 11, flag: true, k559: true, k560: true, k561: true, k562: 10, k563: 11, k573: true, k574: "high", out: {k569: true}, s: "a"}], + [{s: null, a: 0.5, flag: true, price: 11}, {a: 0.5, flag: true, k559: true, k560: true, k561: true, k562: 22, k563: 0.5, k573: true, k574: "high", out: {k569: true}, price: 11}], + [{s: null, a: 0.1, flag: true, price: -25}, {a: 0.1, flag: true, k559: true, k560: true, k561: true, k562: -50, k563: 0.1, k573: true, k574: "high", out: {k569: true}, price: -25}], + [{s: null, a: 2, flag: false, price: 3}, {a: 2, flag: false, k559: false, k560: false, k561: false, k562: 6, k563: 2, k573: true, k574: "high", out: {k569: true}, price: 3}], + [{s: "silver", flag: true, price: 19.99}, {flag: true, k559: true, k560: true, k561: true, k562: 39.98, k563: true, k573: true, k574: "high", out: {k569: true}, price: 19.99, s: "silver"}], + [{s: "x", a: 0.5, price: null}, {a: 0.5, k559: "x", k561: true, k562: -0.5, k563: 0.5, k573: true, k574: "high", out: {k569: true}, s: "x"}], + [{a: 10, price: 11}, {a: 10, k561: false, k562: 22, k563: 10, k573: true, k574: "high", out: {k569: true}, price: 11}], + [{s: "zz", a: 18, flag: "true", price: 3}, "!error"], + [{s: ["gold"], a: 18, flag: false, price: -11}, {a: 18, flag: false, k559: false, k560: false, k561: true, k562: -22, k563: 18, k573: true, k574: "high", out: {k569: true}, price: -11, s: ["gold"]}], + [{s: "b", a: 5, flag: 1, price: 21}, "!error"], + [{s: "gold ", a: true, flag: false, price: 19.99}, {a: true, flag: false, k559: false, k560: false, k561: true, k562: 39.98, k563: true, k573: true, k574: "high", out: {k569: true}, price: 19.99, s: "gold "}], + [{s: "", a: 2.5, flag: true, price: 21}, {a: 2.5, flag: true, k559: true, k560: true, k561: true, k562: 42, k563: 2.5, k573: true, k574: "high", out: {k569: true}, price: 21, s: ""}], + [{s: "bronze", a: 5, flag: false}, {a: 5, flag: false, k559: false, k560: false, k561: true, k562: 4, k563: 5, k573: true, k574: "high", out: {k569: true}, s: "bronze"}], + [{s: "silver", a: 100, flag: false}, {a: 100, flag: false, k559: false, k560: false, k561: true, k562: 99, k563: 100, k573: true, k574: "high", out: {k569: true}, s: "silver"}], + [{s: "zz", a: 99, flag: null, price: null}, {a: 99, k559: "zz", k561: true, k562: 98, k563: 99, k573: true, k574: "high", out: {k569: true}, s: "zz"}], + ], +} + +{ + name: "gb042: 6 nodes, switch, switch*, expr, switch*, switch, expr", + graph: { + nodes: [ + {switch: "s1", when: ["false", "(score ?? -1) + 2 - min([n, n]) != n * -4 * max([2.25, score])", ""]}, + {switch: "s2", hit: "collect", when: ["false", "n in [1..100]", "(a == null)"]}, + {expression: "e3", passThrough: true, fields: { + "g.k575": "s ?? n", + k576: "s ?? s", + "m.k577": "(s != null ? string(true) : (s ?? '') + '-' + s) + ':' + (s ?? 'none')", + k578: "(true ? string(true) : string((s ?? 'none') in ['gold', 'silver', 'a']))", + }}, + {switch: "s4", hit: "collect", when: ["(n < (score ?? 0) ? score : 2 + n) == (100)", "n in [1..100]", ""]}, + {switch: "s5", when: ["'A-1' in ['gold', 'silver', 'a']", "(s == null ? (n ?? 1) : (score ?? -1)) != 3", "a != null", ""]}, + {expression: "e6", passThrough: true, outputPath: "res", fields: { + k579: "2 >= 0", + k580: "(n ?? -1)", + k581: "lower('none') != ''", + "m.k582": "not ((endsWith('gold', 'g')) and (startsWith((s ?? ''), 'g')))", + }}, + ], + edges: [ + "input -> s1", + "s1:0 -> s2", + "s1:1 -> e3", + "s2:0 -> s4", + "input -> s5", + "s5:2 -> e6", + "s1:2 -> output", + "s2:1 -> output", + "e3 -> output", + "s4:1 -> output", + "s4:2 -> output", + "s5:1 -> output", + "s5:3 -> output", + "e6 -> output", + ], + }, + cases: [ + [{s: "x", n: 99, score: 99}, {g: {k575: "x"}, k576: "x", k578: "true", m: {k577: "true:x"}, n: 99, s: "x", score: 99}], + [{s: 5, n: 101, score: 1000}, "!error"], + [{s: "bronze", n: 0.5, score: 100}, {g: {k575: "bronze"}, k576: "bronze", k578: "true", m: {k577: "true:bronze"}, n: 0.5, s: "bronze", score: 100}], + [{s: "b", n: -0.1, score: 1000000000000000000000}, {g: {k575: "b"}, k576: "b", k578: "true", m: {k577: "true:b"}, n: -0.1, s: "b", score: 1000000000000000000000}], + [{s: "gold ", n: true, score: "5"}, {n: true, s: "gold ", score: "5"}], + [{s: 5, n: 100, score: 19.99}, "!error"], + [{s: "x", n: 38, score: 11}, {g: {k575: "x"}, k576: "x", k578: "true", m: {k577: "true:x"}, n: 38, s: "x", score: 11}], + [{s: "bronze", n: {v: 1}, score: 108}, {n: {v: 1}, s: "bronze", score: 108}], + [{s: "a", n: 99, score: "abc"}, {n: 99, s: "a", score: "abc"}], + [{n: "abc", score: 21}, {n: "abc", score: 21}], + [{s: null, n: -0.1, score: -0.1}, "!error"], + [{s: "zz", n: -25, score: 1}, {g: {k575: "zz"}, k576: "zz", k578: "true", m: {k577: "true:zz"}, n: -25, s: "zz", score: 1}], + [{s: "a", n: "5", score: 21}, {n: "5", s: "a", score: 21}], + [{s: "bronze", n: 99, score: 2}, {g: {k575: "bronze"}, k576: "bronze", k578: "true", m: {k577: "true:bronze"}, n: 99, s: "bronze", score: 2}], + [{s: 5, n: 18, score: true}, {n: 18, s: 5, score: true}], + [{s: {t: "x"}, n: [1], score: 1000000000000000000000}, {n: [1], s: {t: "x"}, score: 1000000000000000000000}], + [{n: true, score: "abc"}, {n: true, score: "abc"}], + [{s: "x", n: 0.1, score: 11}, {g: {k575: "x"}, k576: "x", k578: "true", m: {k577: "true:x"}, n: 0.1, s: "x", score: 11}], + [{s: "x", n: -1, score: [1]}, {n: -1, s: "x", score: [1]}], + [{s: "bronze", n: 2, score: null}, {n: 2, s: "bronze"}], + [{s: {t: "x"}, n: 100, score: 0.1}, "!error"], + [{s: "zz", n: 50, score: 1000000000000000000000}, {g: {k575: "zz"}, k576: "zz", k578: "true", m: {k577: "true:zz"}, n: 50, s: "zz", score: 1000000000000000000000}], + [{score: 19.99}, {score: 19.99}], + [{s: null, n: -1, score: {v: 1}}, {n: -1, score: {v: 1}}], + [{s: "a", n: {v: 1}, score: {v: 1}, extra: 1}, {extra: 1, n: {v: 1}, s: "a", score: {v: 1}}], + ], +} + +{ + name: "gb043: 7 nodes, expr, switch*, switch*, table*, loop expr, switch, expr", + graph: { + nodes: [ + {expression: "e1", fields: { + k583: "(score ?? 0)", + }}, + {switch: "s2", hit: "collect", when: ["(cust.active ?? false)", "((endsWith((tier ?? ''), ''))) and (score + (score ?? 1) in [-5..5])", "score in [-5..5]", ""]}, + {switch: "s3", hit: "collect", when: ["flag", ""]}, + {table: "t4", hit: "collect", inputs: ["score"], outputs: ["m.k584"], outputPath: "res", rules: [ + ["", "''"], + ["1, 51", "string(((false) or (flag)) and ((flag ?? false)))"], + ["(50..51)", "'gold'"], + ["!= 10", "''"], + ["", "string(string((flag ?? false)) == 'silver')"], + ["", "''"], + ]}, + {expression: "e5", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "o.p", fields: { + "m.k584": "(price ?? 1)", + k583: "((price ?? 1))", + k587: "round(($.k583 ?? price ?? 0)) >= round(0.5) * qty", + }}, + {switch: "s6", when: ["('' == 'gold') or ((score == score) or (2 != score))", "(tier ?? 'none') in ['gold', 'silver', 'a']", "(min([(score ?? 1), score])) in [0..10]", ""]}, + {expression: "e7", inputField: "cust", passThrough: true, outputPath: "lines", fields: { + k588: "abs(min([age, (age ?? -1)]) % 7)", + k589: "active ?? tier", + "res.k590": "active ?? age", + }}, + ], + edges: [ + "input -> e1", + "input -> s2", + "s2:1 -> s3", + "s3:0 -> t4", + "s2:0 -> e5", + "e5 -> s6", + "e1 -> e7", + "s6:3 -> e7", + "s2:2 -> output", + "t4 -> output", + "e7 -> output", + ], + }, + cases: [ + [{items: [{price: 7, qty: null, tag: {t: "x"}}, {price: 0.5, qty: 100, tag: "zz"}], tier: "", score: 100, flag: true, cust: {age: -25, tier: ["gold"], active: false}, extra: {deep: {x: 1}}}, "!error"], + [{items: [{price: 101, qty: 7, tag: ""}, {price: 100, qty: 1000, tag: "a"}, {price: 11, tag: ""}], tier: null, score: 1, flag: true, cust: {age: -0.1, tier: "a", active: false}}, "!error"], + [{items: [{qty: 2, tag: null}, {price: 2, qty: 1000, tag: "silver"}, {price: 19.99, qty: 1, tag: "a"}, {price: -25, qty: 0, tag: "gold"}], tier: "", score: "abc", flag: true, cust: {age: null, tier: "x", active: true}}, "!error"], + [{items: [{price: 18, qty: 0.1, tag: "a"}, {price: 21, qty: -15, tag: "gold "}], tier: "gold", score: 10, flag: false, cust: {age: -1, tier: "bronze", active: 0}, extra: 1}, "!error"], + [{score: -25, flag: false}, "!error"], + [{items: [], tier: "Gold", score: 1, flag: false, cust: {age: 0.5, tier: null, active: false}, extra: "e"}, "!error"], + [{items: [{price: 1000, tag: "gold"}, {price: 100, qty: 18}], tier: "silver", score: 101, flag: false, cust: {age: -25, tier: "b", active: true}}, "!error"], + [{items: [{price: 0, qty: 19.99, tag: "bronze"}, {price: 5, qty: -1, tag: "silver"}], tier: null, score: 99}, "!error"], + [{items: [], tier: "gold", score: 19.99, flag: true, cust: {age: 2, tier: "x", active: true}}, "!error"], + [{items: [{qty: 0, tag: "Gold"}, {price: true, tag: "gold "}], tier: "x", score: 50, flag: true}, "!error"], + [{items: [{price: 18, qty: 2}], tier: "silver", score: 0, flag: true, cust: null}, "!error"], + [{items: [{qty: 2.5, tag: "zz"}, {price: 49, qty: 0, tag: "Gold"}, {price: 7, qty: 0, tag: "silver"}, {price: 2.5, qty: 1000, tag: "x"}], tier: null, score: -25, flag: true, cust: {age: 101, tier: "gold", active: true}}, "!error"], + [{items: [], score: 1000, flag: false, cust: {age: -0.1, tier: ""}}, "!error"], + [{items: [{price: null, qty: 10, tag: "bronze"}, {price: 0.5, qty: 11, tag: "Gold"}, {price: 5, qty: 10, tag: "zz"}], tier: "b", score: -0.1, flag: false, cust: {age: 0.5, tier: "bronze", active: false}, extra: "e"}, "!error"], + [{items: [], tier: null, score: 10, flag: true, cust: {age: 7, tier: "", active: true}}, "!error"], + ], +} + +{ + name: "gb044: 9 nodes, switch*, loop expr, expr, loop table*, table, loop expr, loop table*, switch*, loop table*", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["false", "(not (not (false))) or (contains(trim((tier ?? '?')), 'g'))"]}, + {expression: "e2", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k591: "price ?? qty", + "res.k592": "'A-1'", + }}, + {expression: "e3", passThrough: true, fields: { + k593: "flag ?? tier", + }}, + {table: "t4", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["price", "tag", "string(0.5 * 0)"], outputs: ["k594[]"], outputPath: "res", rules: [ + ["< 1", "not('x')", "startsWith($, 's')", "false"], + ["<= 6", "'silver', 'bronze'", "not('a')", "false"], + ["<= 71", "$ != ''", "startsWith($, 'a')", "false"], + ["not(18)", "'a', 'b'", "not('silver')", "true"], + ["", "'gold', 'bronze'", "startsWith($, 's')", "false"], + ["!= -1", "", "", "true"], + ]}, + {table: "t5", inputs: ["n"], outputs: ["k595", "k593"], passThrough: true, outputPath: "res", rules: [ + ["null", "(tier ?? 'none')", "'gold'"], + ["> 21", "''", "'high'"], + ["not(0)", "'gold'", "`n=${(n ?? -1)}-${'gold'}`"], + ["$ > 18 and $ < 28", "'low'", "string(((b ?? -1)) * 0.5)"], + ]}, + {expression: "e6", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "out", fields: { + "g.k597": "`${qty}-${'gold'}` + ' ' + string(price) in ['gold', 'silver', 'a']", + k598: "not (('x' != 'silver') or ((tag ?? '?') in ['gold', 'silver', 'a']))", + }}, + {table: "t7", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["tag", "price"], outputs: ["k599[]", "k600"], passThrough: true, outputPath: "res", rules: [ + ["startsWith($, 'a')", "50", "true", "''"], + ["", "not(100)", "true", "''"], + ["", "", "true", "'mid'"], + ]}, + {switch: "s8", hit: "collect", when: ["(n - (b ?? 0)) >= round(0) * len(tier)", "((flag ?? false)) and (1 >= 10 * (b ?? -1))", "true", ""]}, + {table: "t9", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["qty", "(tag ?? 'none')"], outputs: ["k601"], outputPath: "res", rules: [ + ["[10..11)", "not('silver')", "(qty ?? 0)"], + ["<= 101", "", "(price ?? -1)"], + ["$ > 50 and $ < 100", "", "((price)) / 4 % 7"], + ["(1..6)", "null", "0.25"], + ["null", "null", "0"], + ["", "", "10"], + ]}, + ], + edges: [ + "input -> s1", + "s1:1 -> e2", + "s1:1 -> e3", + "e3 -> t4", + "s1:1 -> t5", + "input -> e6", + "s1:1 -> t7", + "e6 -> s8", + "s1:0 -> s8", + "s8:0 -> t9", + "s8:1 -> t9", + "e2 -> output", + "t4 -> output", + "t5 -> output", + "t7 -> output", + "s8:3 -> output", + "t9 -> output", + ], + }, + cases: [ + [{s: "", items: [{price: 2, qty: 101, tag: "silver"}, {price: 0, qty: 11}, {price: -12, qty: 1, tag: true}, {price: null, tag: null}], n: 11, tier: null, flag: true, b: 1000}, {b: 1000, flag: true, items: [{price: 2, qty: 101, tag: "silver"}, {price: 0, qty: 11}, {price: -12, qty: 1, tag: true}, {price: null, tag: null}], n: 11, out: [{g: {k597: false}, k598: false, price: 2, qty: 101, tag: "silver"}, {g: {k597: false}, k598: false, price: 0, qty: 11}, {g: {k597: false}, k598: false, price: -12, qty: 1, tag: true}, {g: {k597: false}, k598: false, price: null, tag: null}], s: ""}], + [{s: "zz", items: [{qty: 100, tag: "a"}, {price: 1000, qty: 1000000000000000000000, tag: ""}], n: "5", tier: null, flag: true, b: true}, {b: true, flag: true, items: [{qty: 100, tag: "a"}, {price: 1000, qty: 1000000000000000000000, tag: ""}], n: "5", out: [{g: {k597: false}, k598: false, qty: 100, tag: "a"}, {g: {k597: false}, k598: false, price: 1000, qty: 1000000000000000000000, tag: ""}], s: "zz"}], + [{s: null, items: [{price: 1000000000000000000000, qty: -25, tag: "x"}, {price: 1000, qty: -1, tag: "x"}], n: -0.1, tier: 5, flag: false, b: -25}, {b: -25, flag: false, items: [{price: 1000000000000000000000, qty: -25, tag: "x"}, {price: 1000, qty: -1, tag: "x"}], n: -0.1, out: [{g: {k597: false}, k598: false, price: 1000000000000000000000, qty: -25, tag: "x"}, {g: {k597: false}, k598: false, price: 1000, qty: -1, tag: "x"}], tier: 5}], + [{s: null, items: [{price: 99, qty: {v: 1}, tag: "bronze"}, {price: 5, qty: -0.1, tag: "b"}, {price: -25, qty: true, tag: "Gold"}, {price: 1000000000000000000000, qty: 101, tag: "x"}], n: -0.1, tier: "gold", flag: true, b: 2.5}, "!error"], + [{items: [], n: 5, tier: "gold", flag: true, b: -1}, {b: -1, flag: true, items: [], n: 5, out: [], res: [], tier: "gold"}], + [{s: "bronze", items: [{price: 105, qty: 16, tag: ""}], n: 0.1, tier: 5, flag: false, b: 5}, {b: 5, flag: false, items: [{price: 105, qty: 16, tag: ""}], n: 0.1, out: [{g: {k597: false}, k598: false, price: 105, qty: 16, tag: ""}], s: "bronze", tier: 5}], + [{s: null, items: [{price: 3, qty: 99, tag: "bronze"}, {price: 0.5, qty: 101, tag: "zz"}, {price: 3, qty: -25, tag: "zz"}], n: 0, tier: "Gold", flag: true}, {flag: true, items: [{price: 3, qty: 99, tag: "bronze"}, {price: 0.5, qty: 101, tag: "zz"}, {price: 3, qty: -25, tag: "zz"}], n: 0, out: [{g: {k597: false}, k598: false, price: 3, qty: 99, tag: "bronze"}, {g: {k597: false}, k598: false, price: 0.5, qty: 101, tag: "zz"}, {g: {k597: false}, k598: false, price: 3, qty: -25, tag: "zz"}], res: [[{k601: 3}, {k601: 0.75}, {k601: 10}], [{k601: 0.5}, {k601: 10}], [{k601: 3}, {k601: 10}]], tier: "Gold"}], + [{s: null, items: [{price: -1, qty: null, tag: "Gold"}, {price: 41, qty: 18}], n: 1000000000000000000000, tier: "gold ", flag: false, b: 99, extra: {deep: {x: 1}}}, {b: 99, extra: {deep: {x: 1}}, flag: false, items: [{price: -1, qty: null, tag: "Gold"}, {price: 41, qty: 18}], n: 1000000000000000000000, out: [{g: {k597: false}, k598: false, price: -1, qty: null, tag: "Gold"}, {g: {k597: false}, k598: false, price: 41, qty: 18}], res: [{k591: -1, price: -1, qty: null, res: {k592: "A-1"}, tag: "Gold"}, {k591: 41, price: 41, qty: 18, res: {k592: "A-1"}}], tier: "gold "}], + [{s: "b", items: null, n: [1], tier: null, flag: true, b: 7, extra: [1, 2]}, "!error"], + [{s: "zz", items: [{price: 100, tag: "bronze"}, {price: -0.1, qty: 1000, tag: "zz"}, {price: 1000, qty: 11, tag: "x"}], n: -1, tier: "b", flag: null, extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, items: [{price: 100, tag: "bronze"}, {price: -0.1, qty: 1000, tag: "zz"}, {price: 1000, qty: 11, tag: "x"}], n: -1, out: [{g: {k597: false}, k598: false, price: 100, tag: "bronze"}, {g: {k597: false}, k598: false, price: -0.1, qty: 1000, tag: "zz"}, {g: {k597: false}, k598: false, price: 1000, qty: 11, tag: "x"}], s: "zz", tier: "b"}], + [{s: null, items: [{price: 2, qty: null, tag: "x"}, {price: 100, qty: "5", tag: {t: "x"}}], n: 5, tier: "silver", flag: false, b: null}, {flag: false, items: [{price: 2, qty: null, tag: "x"}, {price: 100, qty: "5", tag: {t: "x"}}], n: 5, out: [{g: {k597: false}, k598: false, price: 2, qty: null, tag: "x"}, {g: {k597: false}, k598: false, price: 100, qty: "5", tag: {t: "x"}}], res: [[{k601: 10}], [{k601: 10}]], tier: "silver"}], + [{s: "gold ", items: [], n: "abc", flag: null, b: 1}, {b: 1, items: [], n: "abc", out: [], s: "gold "}], + [{items: [1, 2], n: 10, flag: false, b: 100}, "!error"], + [{s: "zz", items: [], tier: true, flag: 1, b: 1000}, {b: 1000, flag: 1, items: [], out: [], s: "zz", tier: true}], + [{s: ["gold"], items: [{price: 18, qty: 11, tag: "bronze"}, {price: 19.99, qty: -0.1, tag: "Gold"}], n: true, tier: true, flag: false, b: "5"}, {b: "5", flag: false, items: [{price: 18, qty: 11, tag: "bronze"}, {price: 19.99, qty: -0.1, tag: "Gold"}], n: true, out: [{g: {k597: false}, k598: false, price: 18, qty: 11, tag: "bronze"}, {g: {k597: false}, k598: false, price: 19.99, qty: -0.1, tag: "Gold"}], s: ["gold"], tier: true}], + [{s: "gold", items: [{price: 30, qty: 11, tag: "zz"}, {price: 2, qty: null, tag: "bronze"}, {price: 2, qty: -1, tag: ""}], n: 7, tier: "gold ", b: 5}, {b: 5, items: [{price: 30, qty: 11, tag: "zz"}, {price: 2, qty: null, tag: "bronze"}, {price: 2, qty: -1, tag: ""}], n: 7, out: [{g: {k597: false}, k598: false, price: 30, qty: 11, tag: "zz"}, {g: {k597: false}, k598: false, price: 2, qty: null, tag: "bronze"}, {g: {k597: false}, k598: false, price: 2, qty: -1, tag: ""}], res: [{k591: 30, price: 30, qty: 11, res: {k592: "A-1"}, tag: "zz"}, {k591: 2, price: 2, qty: null, res: {k592: "A-1"}, tag: "bronze"}, {k591: 2, price: 2, qty: -1, res: {k592: "A-1"}, tag: ""}], s: "gold", tier: "gold "}], + [{s: "silver", items: [{price: 3, qty: 21}], n: {v: 1}, tier: "Gold", flag: true, b: 50}, {b: 50, flag: true, items: [{price: 3, qty: 21}], n: {v: 1}, out: [{g: {k597: false}, k598: false, price: 3, qty: 21}], s: "silver", tier: "Gold"}], + [{s: "gold", items: [{price: 5, qty: 11, tag: 5}, {price: 1000, qty: 7, tag: "gold"}], n: [1], tier: "zz", flag: null, b: 0.5, extra: 1}, {b: 0.5, extra: 1, items: [{price: 5, qty: 11, tag: 5}, {price: 1000, qty: 7, tag: "gold"}], n: [1], out: [{g: {k597: false}, k598: false, price: 5, qty: 11, tag: 5}, {g: {k597: false}, k598: false, price: 1000, qty: 7, tag: "gold"}], s: "gold", tier: "zz"}], + [{s: "", items: [{price: 101, qty: 10, tag: "a"}, {price: 50, qty: -25, tag: "b"}, {price: 18, qty: 3, tag: "a"}], n: -1, tier: "", flag: "true", b: 99}, {b: 99, flag: "true", items: [{price: 101, qty: 10, tag: "a"}, {price: 50, qty: -25, tag: "b"}, {price: 18, qty: 3, tag: "a"}], n: -1, out: [{g: {k597: false}, k598: false, price: 101, qty: 10, tag: "a"}, {g: {k597: false}, k598: false, price: 50, qty: -25, tag: "b"}, {g: {k597: false}, k598: false, price: 18, qty: 3, tag: "a"}], s: "", tier: ""}], + [{s: "x", n: 19.99, tier: null, flag: true, b: 0}, "!error"], + [{s: "b", items: [{price: 50, qty: 19.99, tag: ""}, {price: 0, qty: 21, tag: null}], n: 0.1, tier: "gold", flag: true, b: 3}, {b: 3, flag: true, items: [{price: 50, qty: 19.99, tag: ""}, {price: 0, qty: 21, tag: null}], n: 0.1, out: [{g: {k597: false}, k598: false, price: 50, qty: 19.99, tag: ""}, {g: {k597: false}, k598: false, price: 0, qty: 21, tag: null}], res: [{k591: 50, price: 50, qty: 19.99, res: {k592: "A-1"}, tag: ""}, {k591: 0, price: 0, qty: 21, res: {k592: "A-1"}, tag: null}], s: "b", tier: "gold"}], + [{s: null, items: [{price: -1, qty: 2.5, tag: "silver"}, {price: "5", qty: 5, tag: "zz"}], n: 18, tier: "a", flag: true, b: true, extra: [1, 2]}, {b: true, extra: [1, 2], flag: true, items: [{price: -1, qty: 2.5, tag: "silver"}, {price: "5", qty: 5, tag: "zz"}], n: 18, out: [{g: {k597: false}, k598: false, price: -1, qty: 2.5, tag: "silver"}, {g: {k597: false}, k598: false, price: "5", qty: 5, tag: "zz"}], tier: "a"}], + [{s: "Gold", items: [{price: -0.1, qty: -25, tag: "gold "}, {price: 1000, qty: 3, tag: null}], n: 5, tier: "Gold", flag: true, b: 50}, {b: 50, flag: true, items: [{price: -0.1, qty: -25, tag: "gold "}, {price: 1000, qty: 3, tag: null}], n: 5, out: [{g: {k597: false}, k598: false, price: -0.1, qty: -25, tag: "gold "}, {g: {k597: false}, k598: false, price: 1000, qty: 3, tag: null}], s: "Gold", tier: "Gold"}], + [{items: [{price: 101, qty: 100, tag: "b"}], n: null, tier: "", flag: 0, b: 1000}, {b: 1000, flag: 0, items: [{price: 101, qty: 100, tag: "b"}], out: [{g: {k597: false}, k598: false, price: 101, qty: 100, tag: "b"}], tier: ""}], + [{s: "", items: [], n: -1, tier: "a", flag: true, b: "abc"}, {b: "abc", flag: true, items: [], n: -1, out: [], s: "", tier: "a"}], + ], +} + +{ + name: "gb045: 10 nodes, switch, switch, expr, table, expr, expr, expr, expr, table, expr", + graph: { + nodes: [ + {switch: "s1", when: ["(((score ?? 0) in [-5..5]) or (a != null))", "(a ?? score ?? 0) in [1..100]", "ceil(sum(nums ?? [])) < score + a + (score ?? 0) * score", ""]}, + {switch: "s2", when: ["true", "(lower('none') in ['gold', 'silver', 'a']) or (((a ?? -1) in [-5..5]))", ""]}, + {expression: "e3", fields: { + "g.k602": "'none' + '' + 'gold' + '-' + '' != 'silver'", + "m.k603": "a", + k604: "3 % 7", + }}, + {table: "t4", inputs: ["(score - a)", "100 + (score ?? -1) + a * 0.5"], outputs: ["res.k605", "res.k606"], passThrough: true, rules: [ + ["not(0)", "null", "false", "''"], + ["< 1", "", "true", "'low'"], + ]}, + {expression: "e5", passThrough: true, outputPath: "o.p", fields: { + k607: "g.k602 ?? k604", + k608: "-((m.k603 ?? -1)) + ((k604 ?? 1)) / 10 * (k604 ?? 0) * (m.k603 ?? 1)", + k609: "string(m.k603)", + k610: "'none'", + }}, + {expression: "e6", passThrough: true, outputPath: "out", fields: { + k611: "((m.k603)) / 2", + k612: "k604 ?? m.k603", + k613: "min([((true ? (k604 ?? 1) : (k604 ?? 1))) / 3, (m.k603 ?? 0)])", + }}, + {expression: "e7", fields: { + k614: "0.5", + k615: "string(($nodes.e3.m.k603 ?? k604 ?? 0))", + }}, + {expression: "e8", outputPath: "o.p", fields: { + k616: "k615 ?? k615", + k604: "((k614 - (k614 ?? 1)))", + k618: "floor(k614 * k614) % 7", + k619: "(($nodes.e3.k604 ?? $.k616 ?? 0))", + }}, + {table: "t9", inputs: ["'gold'", "trim('none')", "(o.p.k618 ?? -1)", null], outputs: ["k620"], rules: [ + ["not('')", "'x', 'b'", "> 1", "", "'high'"], + ["'gold'", "'gold', 'b'", "[10..11)", "", "'low'"], + ["", "startsWith($, 's')", "!= 100", "", "'mid'"], + ["'x', 'gold'", "not('silver')", ">= 1", "'gold'", "'high'"], + ["startsWith($, 's')", "", "!= 50", "5", "'high'"], + ]}, + {expression: "e10", passThrough: true, fields: { + k621: "(k614 ?? 0) % 2 > ((false ? 0.5 : k614))", + k622: "(false) and ((false ? 10 : k614) > -((k614 ?? -1)))", + k623: "k614", + "g.k624": "string((k614 ?? 0)) + ':' + (k615 ?? 'none') in ['gold', 'silver', 'a']", + }}, + ], + edges: [ + "input -> s1", + "input -> s2", + "s1:3 -> e3", + "input -> t4", + "e3 -> e5", + "e3 -> e6", + "e3 -> e7", + "e7 -> e8", + "e8 -> t9", + "e7 -> e10", + "s1:0 -> output", + "s1:1 -> output", + "s1:2 -> output", + "s2:0 -> output", + "s2:1 -> output", + "s2:2 -> output", + "t4 -> output", + "e5 -> output", + "e6 -> output", + "t9 -> output", + "e10 -> output", + ], + }, + cases: [ + [{score: 99}, {score: 99}], + [{nums: [], a: 1000000000000000000000, score: 11}, {a: 1000000000000000000000, nums: [], res: {k605: true, k606: "low"}, score: 11}], + [{nums: [0.5], a: "abc", score: 7}, {a: "abc", nums: [0.5], score: 7}], + [{nums: [], a: 1000000000000000000000, score: 0.5}, {a: 1000000000000000000000, nums: [], res: {k605: true, k606: "low"}, score: 0.5}], + [{nums: [1000, 1000000000000000000000], a: 100, score: -0.1}, {a: 100, nums: [1000, 1000000000000000000000], res: {k605: true, k606: "low"}, score: -0.1}], + [{nums: [1, 11, 2.5, 99, 99], a: -25, score: 11}, {a: -25, nums: [1, 11, 2.5, 99, 99], score: 11}], + [{a: 100, score: 0.5}, {a: 100, res: {k605: true, k606: "low"}, score: 0.5}], + [{nums: [0.5, 2, 5], a: 7, score: 0.5}, {a: 7, nums: [0.5, 2, 5], res: {k605: true, k606: "low"}, score: 0.5}], + [{nums: [], a: [1], score: 19.99}, {a: [1], nums: [], score: 19.99}], + [{nums: [1, 0.1], a: 101, score: 5}, {a: 101, nums: [1, 0.1], res: {k605: true, k606: "low"}, score: 5}], + [{nums: [21, -0.1], a: 19.99, score: 18}, {a: 19.99, nums: [21, -0.1], res: {k605: true, k606: "low"}, score: 18}], + [{nums: [-0.1], score: -25}, "!error"], + [{nums: [0.5, 2.5, 0.5], a: 3, score: 92}, {a: 3, nums: [0.5, 2.5, 0.5], score: 92}], + [{nums: [101, 18, 18, 21, 1000000000000000000000], a: 18, score: 7}, {a: 18, nums: [101, 18, 18, 21, 1000000000000000000000], res: {k605: true, k606: "low"}, score: 7}], + ], +} + +{ + name: "gb046: 8 nodes, switch, switch*, switch, table, table, expr, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["(vip ?? false)", ""]}, + {switch: "s2", hit: "collect", when: ["true", "not (1 * (a ?? 1) in [1..100])", "vip != null", ""]}, + {switch: "s3", when: ["a - len(tier) != ((a) / 4)", ""]}, + {table: "t4", inputs: ["a"], outputs: ["k625", "k626"], outputPath: "lines", rules: [ + ["21", "0.25", "''"], + ["> 10", "10", "'high'"], + ["not(0)", "10", "(tier ?? '?')"], + ["", "2", "'high'"], + ]}, + {table: "t5", inputField: "cust", inputs: ["age"], outputs: ["g.k627", "k626"], passThrough: true, rules: [ + ["[10..20)", "(age ?? 1)", "'high'"], + ["<= 150", "1", "'low'"], + ["not(50)", "2", "''"], + ["not(10)", "2", "'high'"], + ["> 100", "-((max([2.25, (age ?? 1)])) / 0.5)", "(tier ?? '')"], + ["not(21)", "-5", "'mid'"], + ["", "10", "`${(age ?? 0)}-${'x'}`"], + ]}, + {expression: "e6", passThrough: true, fields: { + k629: "min([a, (cust.age ?? -1)])", + }}, + {expression: "e7", inputField: "cust", passThrough: true, outputPath: "out", fields: { + k630: "2 - age + (age ?? 0) - len((tier ?? 'none')) + (age ?? age ?? 0)", + k631: "(tier ?? '?')", + k632: "upper((((active ?? false)) ? (tier ?? 'none') + ':' + tier : ((active ?? false) ? tier : tier)))", + }}, + {table: "t8", inputs: ["a", "tier", "tier", null], outputs: ["res.k633"], passThrough: true, outputPath: "out", rules: [ + ["not(10)", "''", "startsWith($, 'g')", "5", "false"], + ["", "", "", "null", "false"], + ["[0..10]", "startsWith($, '')", "$ != 'gold'", "null", "true"], + [">= 1", "not('')", "'', 'b'", "null", "false"], + ["not(10)", "", "not('gold')", "null", "true"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> s2", + "s1:1 -> s3", + "s2:2 -> s3", + "s1:1 -> t4", + "s2:3 -> t5", + "s3:0 -> e6", + "t5 -> e6", + "s3:1 -> e7", + "s2:2 -> t8", + "s2:1 -> output", + "t4 -> output", + "e6 -> output", + "e7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{tier: "Gold", cust: null, vip: false, a: 3}, {a: 3, k629: -1, lines: {k625: 2, k626: "high"}, tier: "Gold", vip: false}], + [{cust: {age: 101, tier: "", active: true}, vip: true, a: 99}, {a: 99, cust: {active: true, age: 101, tier: ""}, g: {k627: 1}, k626: "low", k629: 99, out: {k630: 103, k631: "", k632: ":"}, vip: true}], + [{tier: "gold ", cust: null, vip: true, a: 3}, {a: 3, g: {k627: 10}, k626: "0-x", k629: -1, tier: "gold ", vip: true}], + [{tier: "b", cust: {age: 10, tier: "x", active: false}, vip: false, a: null}, {cust: {active: false, age: 10, tier: "x"}, lines: {k625: 2, k626: "high"}, out: {k630: 11, k631: "x", k632: "X"}, tier: "b", vip: false}], + [{cust: {age: 2, tier: null, active: false}, vip: true, a: 18}, "!error"], + [{tier: "Gold", cust: {age: 1000, tier: "silver", active: true}, vip: true, a: null}, "!error"], + [{tier: "Gold", cust: {age: true, tier: "gold", active: true}, vip: false, a: 2.5, extra: {deep: {x: 1}}}, "!error"], + [{tier: "gold ", cust: {age: -0.1, tier: "zz", active: true}, vip: true}, "!error"], + [{tier: "Gold", cust: {age: 19.99, tier: "b"}, vip: true, a: 2}, {a: 2, cust: {age: 19.99, tier: "b"}, g: {k627: 19.99}, k626: "high", k629: 2, tier: "Gold", vip: true}], + [{tier: "zz", cust: {age: 11, tier: "b", active: false}, a: 19.99}, {a: 19.99, cust: {active: false, age: 11, tier: "b"}, k629: 11, lines: {k625: 10, k626: "high"}, tier: "zz"}], + [{tier: "b", cust: {age: 2, tier: "gold", active: true}, vip: true, a: 11}, {a: 11, cust: {active: true, age: 2, tier: "gold"}, g: {k627: 1}, k626: "low", k629: 2, tier: "b", vip: true}], + [{tier: "gold", cust: [{age: 3}], vip: false, a: 1000000000000000000000}, {a: 1000000000000000000000, cust: [{age: 3}], k629: -1, lines: {k625: 10, k626: "high"}, tier: "gold", vip: false}], + [{cust: {age: 7, tier: "a", active: false}, vip: true, a: {v: 1}}, "!error"], + [{tier: "gold ", cust: {age: 100, tier: "bronze", active: true}, vip: false, a: true}, {a: true, cust: {active: true, age: 100, tier: "bronze"}, lines: {k625: 2, k626: "high"}, out: {k630: 96, k631: "bronze", k632: "BRONZE:BRONZE"}, tier: "gold ", vip: false}], + [{tier: "bronze", cust: {age: -0.1, tier: "bronze", active: true}, vip: true, a: -1}, {a: -1, cust: {active: true, age: -0.1, tier: "bronze"}, g: {k627: 1}, k626: "low", k629: -1, tier: "bronze", vip: true}], + [{tier: "b", cust: {age: null, tier: "", active: false}, vip: true, a: -25}, {a: -25, cust: {active: false, age: null, tier: ""}, g: {k627: 10}, k626: "0-x", k629: -25, tier: "b", vip: true}], + [{tier: "bronze", cust: {age: 7, tier: "silver", active: true}, vip: false, a: 1000}, {a: 1000, cust: {active: true, age: 7, tier: "silver"}, k629: 7, lines: {k625: 10, k626: "high"}, tier: "bronze", vip: false}], + [{tier: null, cust: {age: 114, tier: "Gold", active: false}, vip: null, a: 1000000000000000000000, extra: [1, 2]}, {a: 1000000000000000000000, cust: {active: false, age: 114, tier: "Gold"}, extra: [1, 2], lines: {k625: 10, k626: "high"}, out: {k630: 112, k631: "Gold", k632: "GOLD"}}], + [{tier: {t: "x"}, cust: {age: 3, tier: "", active: true}, vip: false, a: 1000000000000000000000}, {a: 1000000000000000000000, cust: {active: true, age: 3, tier: ""}, lines: {k625: 10, k626: "high"}, out: {k630: 5, k631: "", k632: ":"}, tier: {t: "x"}, vip: false}], + [{tier: null, cust: {age: 1000, tier: "gold ", active: true}, a: 18}, {a: 18, cust: {active: true, age: 1000, tier: "gold "}, lines: {k625: 10, k626: "high"}, out: {k630: 997, k631: "gold ", k632: "GOLD :GOLD "}}], + [{tier: "", vip: false, a: 5}, {a: 5, k629: -1, lines: {k625: 2, k626: "high"}, tier: "", vip: false}], + [{tier: "a", cust: {age: null, tier: "gold ", active: true}, vip: true, a: 2.5, extra: "e"}, {a: 2.5, cust: {active: true, age: null, tier: "gold "}, extra: "e", g: {k627: 10}, k626: "0-x", k629: -1, tier: "a", vip: true}], + [{tier: "x", cust: {age: 1000, tier: "gold", active: true}, vip: false, extra: {deep: {x: 1}}}, {cust: {active: true, age: 1000, tier: "gold"}, extra: {deep: {x: 1}}, lines: {k625: 2, k626: "high"}, out: {k630: 998, k631: "gold", k632: "GOLD:GOLD"}, tier: "x", vip: false}], + [{tier: true, cust: {age: 1000000000000000000000, tier: "silver", active: true}, vip: false, a: "5"}, {a: "5", cust: {active: true, age: 1000000000000000000000, tier: "silver"}, lines: {k625: 2, k626: "high"}, out: {k630: 999999999999999999996, k631: "silver", k632: "SILVER:SILVER"}, tier: true, vip: false}], + [{tier: "zz", cust: {age: 101, tier: "Gold", active: false}, vip: false, a: 0}, {a: 0, cust: {active: false, age: 101, tier: "Gold"}, k629: 0, lines: {k625: 2, k626: "high"}, tier: "zz", vip: false}], + [{tier: "x", cust: {age: 0.5, tier: "a", active: true}, vip: false, a: 2}, {a: 2, cust: {active: true, age: 0.5, tier: "a"}, k629: 0.5, lines: {k625: 2, k626: "high"}, tier: "x", vip: false}], + [{cust: [{age: 3}], vip: true, a: 101}, "!error"], + [{tier: "b", cust: {age: 11, tier: null, active: false}, vip: null, a: -1}, {a: -1, cust: {active: false, age: 11, tier: null}, k629: -1, lines: {k625: 2, k626: "high"}, tier: "b"}], + [{tier: "Gold", cust: {age: 100, tier: "", active: false}, a: 21}, {a: 21, cust: {active: false, age: 100, tier: ""}, k629: 21, lines: {k625: 0.25, k626: ""}, tier: "Gold"}], + [{tier: "b", cust: {age: 0.1, tier: "", active: true}, vip: true, a: 100, extra: 1}, {a: 100, cust: {active: true, age: 0.1, tier: ""}, extra: 1, g: {k627: 1}, k626: "low", k629: 0.1, tier: "b", vip: true}], + ], +} + +{ + name: "gb047: 12 nodes, table, table, switch, switch*, switch*, expr, table*, expr, table*, expr, table*, table*", + graph: { + nodes: [ + {table: "t1", inputs: ["a", "flag", "a"], outputs: ["k634", "k635"], outputPath: "res", rules: [ + ["$ > 1 and $ < 6", "false", "[1..2]", "((a ?? 0) * (score ?? 0) > 2.25) or (string((flag ?? false)) in ['gold', 'silver', 'a'])", "0.5"], + ["[10..15]", "true", "", "false", "a * 10 + (price ?? 1) * len((tier ?? 'none'))"], + ["18", "", "> 50", "len((tier ?? '')) >= cust.age + (a ?? 0) + (price ?? score ?? 0)", "0"], + ["", "false", ">= 18", "true", "(price ?? -1)"], + ["< 1", "$ == true", "< 0", "false", "2"], + ["< -1", "$ == true", "1", "true", "100"], + ["", "", "", "endsWith((tier ?? 'none'), 'x')", "(score ?? 1) * ((score ?? 0)) + -(max([(price ?? 0), (score ?? 0)]))"], + ]}, + {table: "t2", inputField: "cust", inputs: ["active", "active", "age"], outputs: ["k636", "k634"], outputPath: "res", rules: [ + ["false", "", "10, 60", "-4 * (age ?? 1) + ((age ?? 0)) + age", "'high'"], + ["null", "null", "< 50", "100", "''"], + ["null", "$ == true", "(10..20)", "(age ?? 1)", "'mid'"], + ["$ == true", "null", "<= 100", "len((tier ?? 'none') + '' + (tier ?? '')) + (round((age ?? -1)))", "'gold'"], + ["", "", "", "100", "tier"], + ]}, + {switch: "s3", when: ["res.k635 == null", "contains(((res.k634 ?? false) ? (res.k634 ? 'A-1' : 'A-1') : string((res.k634 ?? false))), 'a')", "(10 * (res.k635 ?? 0) > (res.k635 ?? res.k635 ?? 0)) and ((res.k634) or ((res.k635 ?? 1) == 0.5))"]}, + {switch: "s4", hit: "collect", when: ["res.k634", "(len('gold') in [1..100]) or ((true ? res.k635 : (res.k635 ?? -1)) == (res.k635 ?? 0) + (res.k635 ?? 0))", "not (string(true) == 'gold')", ""]}, + {switch: "s5", hit: "collect", when: ["price == res.k635", "string(res.k635) != 'silver'"]}, + {expression: "e6", outputPath: "lines", fields: { + k638: "(((res.k635 ?? 1)) / 2) % 2", + k639: "'A-1'", + "m.k640": "res.k635 ?? res.k635", + }}, + {table: "t7", hit: "collect", inputs: ["res.k634", "res.k634", "res.k634", null], outputs: ["k636[]", "k642"], passThrough: true, outputPath: "out", rules: [ + ["", "$ == true", "null", "true", "'low'", "0"], + ["null", "true", "$ == true", "", "'mid'", "2"], + ["$ == true", "true", "true", "$ != null", "'low'", "0"], + ["$ == true", "null", "$ == true", "", "'low'", "-5"], + ["true", "null", "$ == true", "5", "string((price ?? 1))", "1"], + ["true", "null", "true", "true", "'high'", "0"], + ]}, + {expression: "e8", outputPath: "res", fields: { + k643: "'A-1'", + }}, + {table: "t9", hit: "collect", inputField: "cust", inputs: ["age"], outputs: ["k644", "k645"], passThrough: true, outputPath: "out", rules: [ + ["(21..26)", "2", "'mid'"], + ["[50..100]", "100", "'low'"], + ["(-1..0)", "10", "string((age ?? 0) - (age ?? -1) % 2)"], + ["", "10", "string(not ((active ?? false))) + '' + string((age ?? 1) - (age ?? 0))"], + ["[5..6]", "10", "''"], + ]}, + {expression: "e10", passThrough: true, outputPath: "res", fields: { + k646: "(0.5) + -4 % 2 > (price ?? score ?? 0)", + k647: "`${(score ?? 0)}-${tier}`", + k648: "flag ?? flag", + k649: "tier ?? vip", + }}, + {table: "t11", hit: "collect", inputs: ["0.5"], outputs: ["g.k650", "k651"], rules: [ + ["> 18", "false", "'low'"], + ["", "true", "'low'"], + ["", "(false) and (1 % 7 < ceil(2.25))", "(trim('none') in ['gold', 'silver', 'a'] ? (res.k643 ?? '?') : (res.k643 ?? ''))"], + ["5", "`v${1}-${(res.k643 ?? '')}` == 'silver'", "'low'"], + [">= 5", "true", "'mid'"], + ["", "true", "'high'"], + ]}, + {table: "t12", hit: "collect", inputs: ["res.k634", null], outputs: ["k652"], passThrough: true, outputPath: "res", rules: [ + ["true", "true", "false"], + ["false", "", "true"], + ["null", "'gold'", "false"], + ["true", "$ != null", "false"], + ["", "", "true"], + ]}, + ], + edges: [ + "input -> t1", + "input -> t2", + "t1 -> s3", + "s3:1 -> s4", + "s4:1 -> s5", + "input -> s5", + "s4:3 -> e6", + "s4:3 -> t7", + "s5:1 -> t7", + "s5:1 -> e8", + "e6 -> e8", + "t7 -> t9", + "s5:1 -> t9", + "t7 -> e10", + "e8 -> t11", + "e10 -> t12", + "t2 -> output", + "s3:2 -> output", + "e8 -> output", + "t9 -> output", + "t11 -> output", + "t12 -> output", + ], + }, + cases: [ + [{cust: {age: 0.5, tier: "gold ", active: true}, vip: true, flag: true, a: 0.1, price: 0.5, tier: "gold", score: 1}, {a: 0.1, cust: {active: true, age: 0.5, tier: "gold "}, flag: true, out: [{k644: 10, k645: "false0.0"}], price: 0.5, res: {k634: "gold ", k635: 0, k636: 100, k643: "A-1"}, score: 1, tier: "gold", vip: true}], + [{cust: [], vip: "true", flag: false, a: 101, price: 1000000000000000000000, tier: ["gold"]}, "!error"], + [{cust: 5, vip: false, flag: false, a: null, price: 2, tier: "silver", score: 101}, {cust: 5, flag: false, out: [], price: 2, score: 101, tier: "silver", vip: false}], + [{cust: null, vip: true, flag: true, a: null, price: "5", tier: null, score: 100}, "!error"], + [{cust: {age: -25, tier: "x", active: false}, vip: false, flag: "true", a: {v: 1}, price: 3, tier: "b", score: {v: 1}}, "!error"], + [{cust: {age: 3, tier: "", active: false}, a: 2.5, price: 0.1, tier: "", score: 2}, {a: 2.5, cust: {active: false, age: 3, tier: ""}, out: [{k644: 10, k645: "true0"}], price: 0.1, res: {k634: "", k635: 2, k636: 100, k643: "A-1"}, score: 2, tier: ""}], + [{cust: "cust", vip: false, flag: true, a: 0.5, price: null, tier: "Gold", score: 50}, {a: 0.5, cust: "cust", flag: true, out: [], score: 50, tier: "Gold", vip: false}], + [{vip: false, flag: true, a: 0.5, tier: "silver", score: 18}, {a: 0.5, flag: true, out: [{k644: 10, k645: "true1"}], res: {k635: 306, k636: 100, k643: "A-1"}, score: 18, tier: "silver", vip: false}], + [{cust: {age: 100, tier: "b", active: false}, vip: true, flag: false, a: 10, price: 19.99, score: 101}, {a: 10, cust: {active: false, age: 100, tier: "b"}, flag: false, out: [{k644: 100, k645: "low"}, {k644: 10, k645: "true0"}], price: 19.99, res: {k634: "b", k635: 10100, k636: 100, k643: "A-1"}, score: 101, vip: true}], + [{cust: [], vip: true, flag: null, a: 2, price: 7, tier: null, score: 0}, {a: 2, cust: [], out: [], price: 7, score: 0, vip: true}], + [{cust: [], vip: true, flag: false, a: -25, price: 1000000000000000000000, tier: "silver", score: null}, {a: -25, cust: [], flag: false, out: [], price: 1000000000000000000000, tier: "silver", vip: true}], + [{vip: false, flag: true, a: 0.1, price: null, tier: "silver", score: 1}, {a: 0.1, flag: true, out: [{k644: 10, k645: "true1"}], res: {k635: 0, k636: 100, k643: "A-1"}, score: 1, tier: "silver", vip: false}], + [{cust: {age: 11, tier: "a"}, vip: true, flag: "true", a: 11, price: -1, tier: "a", score: {v: 1}}, "!error"], + ], +} + +{ + name: "gb048: 11 nodes, expr, expr, table, table, expr, expr, expr, expr, expr, switch, expr", + graph: { + nodes: [ + {expression: "e1", outputPath: "out", fields: { + k653: "upper('') + '-' + (tier ?? 'none')", + "m.k654": "(0.5)", + k655: "(b ?? 1) % 3 % 7 + b", + k656: "100", + }}, + {expression: "e2", passThrough: true, fields: { + k657: "100", + k658: "true", + k659: "upper(string(($.k658 ?? false)) + ':' + (out.k653 ?? 'none'))", + k660: "out.k655 != null", + }}, + {table: "t3", inputs: ["b", "k658"], outputs: ["k661", "k662"], passThrough: true, outputPath: "res", rules: [ + ["1", "null", "true", "'low'"], + [">= 10", "", "true", "'low'"], + ["!= 50", "true", "(out.k653 ?? '') in ['gold', 'silver', 'a']", "`${(b ?? 0)}-${'gold'}`"], + [">= 1", "false", "false", "''"], + ["18, 28", "$ == true", "false", "'mid'"], + ["", "", "(vip) or (not ((k658) or ((k660 ?? false))))", "'high'"], + ]}, + {table: "t4", inputs: ["out.k653", "(3) / 2", "out.m.k654"], outputs: ["k663", "k664"], passThrough: true, rules: [ + ["'a', 'gold'", "<= 4", "<= 6", "-(abs((out.k656 ?? 0))) - (not (false) ? (10) : (out.k655 ?? -1) * (out.m.k654 ?? 1))", "100"], + ["startsWith($, 's')", "< 5", "50, 51", "-5", "1"], + ["not('a')", "null", "<= 26", "100", "0"], + ["'silver'", "18", "> 21", "-5", "0.25"], + ["'', 'b'", "null", "> 10", "0", "(out.m.k654 ?? -1)"], + ]}, + {expression: "e5", passThrough: true, fields: { + k665: "(k663 ?? 1) + (-((out.m.k654 ?? 0)))", + }}, + {expression: "e6", passThrough: true, fields: { + k666: "true", + "m.k667": "'x' in ['gold', 'silver', 'a']", + }}, + {expression: "e7", outputPath: "o.p", fields: { + k668: "out.k653 ?? k665", + k669: "(((k663 ?? k664 ?? 0)))", + }}, + {expression: "e8", fields: { + k670: "ceil(((out.k656) / 3))", + k671: "out.k655", + k672: "out.k653 ?? out.k653", + }}, + {expression: "e9", fields: { + k673: "(endsWith(string(false), 'a'))", + "res.k674": "false", + "g.k675": "(out.k655 == null ? trim(string($.k673)) : `${out.k655}-${out.k653}`)", + }}, + {switch: "s10", when: ["0 * 2 < -(10)"]}, + {expression: "e11", fields: { + "res.k676": "(true ? (out.m.k654 ?? 0) : out.k656) + -4 - 2 != ((out.m.k654 ?? 1)) / 10", + "m.k677": "out.m.k654 ?? out.m.k654", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "e2 -> t3", + "input -> t3", + "e1 -> t4", + "t4 -> e5", + "e2 -> e6", + "e5 -> e7", + "e5 -> e8", + "e5 -> e9", + "e9 -> s10", + "e1 -> e11", + "t3 -> output", + "e5 -> output", + "e6 -> output", + "e7 -> output", + "e8 -> output", + "s10:0 -> output", + "e11 -> output", + ], + }, + cases: [ + [{s: "b", flag: true, tier: ["gold"], vip: 0}, "!error"], + [{s: "b", flag: 0, tier: "b", vip: false, b: 7}, {b: 7, flag: 0, k657: 100, k658: true, k659: "TRUE:-B", k660: true, k665: 0.5, k666: true, k670: 34, k671: 8, k672: "-b", m: {k667: false, k677: 0.5}, o: {p: {k668: "-b", k669: 0}}, out: {k653: "-b", k655: 8, k656: 100, m: {k654: 0.5}}, res: {k661: false, k662: "7-gold", k676: true}, s: "b", tier: "b", vip: false}], + [{s: "Gold", flag: false, tier: "gold", vip: "no", b: -25}, {b: -25, flag: false, k657: 100, k658: true, k659: "TRUE:-GOLD", k660: true, k665: 0.5, k666: true, k670: 34, k671: -26, k672: "-gold", m: {k667: false, k677: 0.5}, o: {p: {k668: "-gold", k669: 0}}, out: {k653: "-gold", k655: -26, k656: 100, m: {k654: 0.5}}, res: {k661: false, k662: "-25-gold", k676: true}, s: "Gold", tier: "gold", vip: "no"}], + [{s: "zz", flag: 0, tier: true, vip: true, b: 18}, "!error"], + [{s: "a", tier: ["gold"], vip: true, b: 101}, "!error"], + [{s: true, flag: false, tier: "zz", vip: true, b: {v: 1}}, "!error"], + [{s: "gold ", flag: true, tier: "", b: "5"}, "!error"], + [{s: 5, flag: true, tier: {t: "x"}, vip: 1, b: 18}, "!error"], + [{s: "Gold", flag: null, tier: "zz", vip: null, b: 50}, {b: 50, k657: 100, k658: true, k659: "TRUE:-ZZ", k660: true, k665: 0.5, k666: true, k670: 34, k671: 52, k672: "-zz", m: {k667: false, k677: 0.5}, o: {p: {k668: "-zz", k669: 0}}, out: {k653: "-zz", k655: 52, k656: 100, m: {k654: 0.5}}, res: {k661: true, k662: "low", k676: true}, s: "Gold", tier: "zz"}], + [{s: "x", flag: 1}, "!error"], + [{s: "", flag: true, tier: "x", vip: true, b: 2}, {b: 2, flag: true, k657: 100, k658: true, k659: "TRUE:-X", k660: true, k665: 0.5, k666: true, k670: 34, k671: 4, k672: "-x", m: {k667: false, k677: 0.5}, o: {p: {k668: "-x", k669: 0}}, out: {k653: "-x", k655: 4, k656: 100, m: {k654: 0.5}}, res: {k661: false, k662: "2-gold", k676: true}, s: "", tier: "x", vip: true}], + [{s: "gold", flag: false, tier: null, vip: false, b: "abc"}, "!error"], + [{s: true, flag: "no", vip: false, b: 0.5}, {b: 0.5, flag: "no", k657: 100, k658: true, k659: "TRUE:-NONE", k660: true, k665: 0.5, k666: true, k670: 34, k671: 1.0, k672: "-none", m: {k667: false, k677: 0.5}, o: {p: {k668: "-none", k669: 0}}, out: {k653: "-none", k655: 1.0, k656: 100, m: {k654: 0.5}}, res: {k661: false, k662: "0.5-gold", k676: true}, s: true, vip: false}], + [{s: "b", flag: true, tier: "zz", vip: false, b: null}, "!error"], + [{s: "x", flag: true, tier: "a", vip: true, b: 5, extra: "e"}, {b: 5, extra: "e", flag: true, k657: 100, k658: true, k659: "TRUE:-A", k660: true, k665: 0.5, k666: true, k670: 34, k671: 7, k672: "-a", m: {k667: false, k677: 0.5}, o: {p: {k668: "-a", k669: 0}}, out: {k653: "-a", k655: 7, k656: 100, m: {k654: 0.5}}, res: {k661: false, k662: "5-gold", k676: true}, s: "x", tier: "a", vip: true}], + [{s: "", flag: true, vip: false, b: 18}, {b: 18, flag: true, k657: 100, k658: true, k659: "TRUE:-NONE", k660: true, k665: 0.5, k666: true, k670: 34, k671: 18, k672: "-none", m: {k667: false, k677: 0.5}, o: {p: {k668: "-none", k669: 0}}, out: {k653: "-none", k655: 18, k656: 100, m: {k654: 0.5}}, res: {k661: true, k662: "low", k676: true}, s: "", vip: false}], + [{s: true, flag: false, tier: "zz", vip: false, b: 101}, {b: 101, flag: false, k657: 100, k658: true, k659: "TRUE:-ZZ", k660: true, k665: 0.5, k666: true, k670: 34, k671: 103, k672: "-zz", m: {k667: false, k677: 0.5}, o: {p: {k668: "-zz", k669: 0}}, out: {k653: "-zz", k655: 103, k656: 100, m: {k654: 0.5}}, res: {k661: true, k662: "low", k676: true}, s: true, tier: "zz", vip: false}], + [{s: null, flag: "true", tier: "gold ", vip: 1, b: 19.99, extra: [1, 2]}, {b: 19.99, extra: [1, 2], flag: "true", k657: 100, k658: true, k659: "TRUE:-GOLD ", k660: true, k665: 0.5, k666: true, k670: 34, k671: 21.98, k672: "-gold ", m: {k667: false, k677: 0.5}, o: {p: {k668: "-gold ", k669: 0}}, out: {k653: "-gold ", k655: 21.98, k656: 100, m: {k654: 0.5}}, res: {k661: true, k662: "low", k676: true}, tier: "gold ", vip: 1}], + [{s: "", flag: true, tier: "silver", vip: true, b: "5"}, "!error"], + ], +} + +{ + name: "gb049: 10 nodes, expr, table*, table, switch, expr, table, table, expr, switch, expr", + graph: { + nodes: [ + {expression: "e1", fields: { + k678: "flag ?? s", + }}, + {table: "t2", hit: "collect", inputs: ["'x'"], outputs: ["k680[]"], outputPath: "out", rules: [ + ["startsWith($, '')", "true"], + ["null", "true"], + ["", "true"], + ]}, + {table: "t3", inputs: ["'gold' + ' ' + upper('none')", "-4"], outputs: ["m.k681", "k682"], rules: [ + ["", "not(100)", "string(contains(string(true), 'x'))", "true"], + ["startsWith($, '')", "[5..10)", "'mid'", "false"], + ["startsWith($, 'x')", "!= -1", "'high'", "true"], + ["null", "null", "string((true) or (not (true)))", "false"], + ["", "", "'gold'", "false"], + ]}, + {switch: "s4", when: ["3 > len('A-1') % 7"]}, + {expression: "e5", passThrough: true, fields: { + k683: "-4 * len('none')", + }}, + {table: "t6", inputs: ["m.k681", "k683"], outputs: ["g.k684", "res.k685"], rules: [ + ["", "", "(k683 ?? 1) * ((k683 ?? 1))", "upper(`v${2.25}-${'gold'}`) != ''"], + ["not('')", "(0..50)", "-5", "true"], + ["'silver'", "", "100", "false"], + ["null", "[5..10)", "0", "true"], + ["not('gold')", "", "0", "endsWith((m.k681 ?? ''), 'x')"], + ["'x'", "", "(k683 ?? 1) * ((k683 ?? 1)) - (((k683 ?? -1)))", "false"], + ]}, + {table: "t7", inputs: ["g.k684", "g.k684"], outputs: ["k686", "k687"], rules: [ + ["[1..11)", "50", "false", "'low'"], + ["!= 100", "not(1)", "false", "(m.k681 ?? '')"], + ["", "", "true", "string(abs((g.k684 ?? -1) % 3))"], + ]}, + {expression: "e8", passThrough: true, fields: { + k688: "min([2, 2 + -4])", + k689: "m.k681 ?? m.k681", + "g.k690": "(m.k681 ?? 'none')", + "g.k691": "100", + }}, + {switch: "s9", when: ["(lower('') == 'silver')", ""]}, + {expression: "e10", fields: { + "g.k692": "null", + k693: "(true ? string(-4) : upper(trim('A-1')))", + }}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "t2 -> t3", + "e1 -> s4", + "t3 -> s4", + "e1 -> e5", + "e5 -> t6", + "t3 -> t6", + "s4:0 -> t7", + "t6 -> t7", + "s4:0 -> e8", + "t6 -> s9", + "t2 -> e10", + "t2 -> output", + "t7 -> output", + "e8 -> output", + "s9:0 -> output", + "e10 -> output", + ], + }, + cases: [ + [{nums: [], score: 2, s: "", cust: [], flag: true}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 0.5, nums: [50], score: -25, s: "a", cust: {age: 2, tier: null, active: true}, flag: true}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 1000000000000000000000, nums: [101], score: -25, s: "a", cust: {age: -25, tier: "gold", active: false}, flag: true, extra: 1}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 0, score: null, s: 5, cust: {age: 101, tier: "bronze", active: false}, flag: true, extra: "e"}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 21, nums: [-25, 10, 10, 50, 101], score: 18, cust: {age: 99, tier: null, active: true}, flag: false}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 0.5, nums: [], s: "zz", cust: {age: 3, tier: "b"}, flag: true}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 101, nums: null, score: null, s: "silver", cust: "cust", flag: false}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 5, nums: [], score: 2, s: null, cust: {age: 100, tier: "bronze", active: false}, flag: false}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 101, nums: [-0.1, 1, 2, 2, 99], score: -1, s: "Gold", cust: {age: 101, tier: "", active: true}, flag: true}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{nums: [21], score: null, s: "b", cust: {age: 0, tier: "zz", active: true}, flag: false}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 1000000000000000000000, nums: [{x: 1}], score: 99, s: "", cust: {age: [1], tier: "", active: true}, flag: false}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: null, nums: [2], score: 101, s: "b", cust: null}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 0, nums: [100, 18, 0.5], score: "abc", s: "gold", cust: {age: 99, tier: "", active: false}, flag: 1, extra: "e"}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 10, nums: [0.1, 109, 3], score: -0.1, s: "Gold", cust: {age: 2, tier: null}, flag: "no"}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: null, nums: [-1, -0.1, 1000000000000000000000, 10, 7], score: 1, s: "", cust: null, flag: null}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 3, nums: [101], score: 46, s: "gold", cust: {age: null, tier: "b", active: true}, flag: true}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 50, nums: [0.1, 19.99, 2], score: 7, s: "bronze", flag: true}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: -0.1, score: 3, s: "a", cust: "cust"}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + [{n: 21, nums: [18], s: "gold", cust: [{age: 3}], flag: false}, {g: {k692: null}, k686: true, k687: "1", k693: "-4", out: [{k680: true}, {k680: true}]}], + ], +} + +{ + name: "gb050: 6 nodes, loop table, switch, expr, expr, expr, expr", + graph: { + nodes: [ + {table: "t1", inputField: "items", executionMode: "loop", inputs: ["qty", "price"], outputs: ["m.k694", "m.k694"], outputPath: "out", rules: [ + ["", "0", "-(price) * (price ?? -1) - (10) / 0.5", "true"], + [">= -1", "<= 55", "100", "(true)"], + [">= 50", "10, 20", "0", "false"], + ["", "", "-(max([(qty ?? -1), (qty ?? 1)]) + (qty ?? 1))", "false"], + ]}, + {switch: "s2", when: ["startsWith(string((false ? 2.25 : 1)), 'x')", "startsWith('none', '')", "(string(true) != 'x') or ((3 == 0.5))", ""]}, + {expression: "e3", passThrough: true, fields: { + "res.k696": "null", + k697: "null", + k698: "(0 ?? 1 ?? 0) > (10)", + k699: "(-4 == 0 - 0.5 ? trim('A-1') + ' ' + string($.k698) : string('gold' == ''))", + }}, + {expression: "e4", outputPath: "o.p", fields: { + k700: "null", + k701: "null", + k702: "max([-4, -(1)])", + "m.k703": "('A-1' == 'silver' ? 3 : (100 + 2.25))", + }}, + {expression: "e5", fields: { + k704: "(0.5)", + k705: "string(not (true)) + ':' + 'x'", + }}, + {expression: "e6", fields: { + "g.k706": "'x'", + "m.k703": "(len('x') == max([3, 0.5]) ? 0 : ((false ? 0.5 : 3)))", + "m.k708": "ceil(0)", + }}, + ], + edges: [ + "input -> t1", + "t1 -> s2", + "s2:2 -> e3", + "s2:1 -> e4", + "s2:2 -> e5", + "s2:3 -> e6", + "s2:0 -> output", + "e3 -> output", + "e4 -> output", + "e5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{code: "", a: 1000, items: [{price: -0.1, qty: 7, tag: "bronze"}, {price: 10, qty: 101, tag: "gold"}, {qty: 19.99, tag: "bronze"}, {price: 0, qty: 10}], price: 19.99, nums: [50, 1000], n: null}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "Gold", a: -0.1, items: [{price: 1000000000000000000000, qty: 1, tag: ""}, {price: 1000, qty: 101, tag: "x"}], price: 1000, nums: [-25], n: 3}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{a: 0, items: [{price: 21, qty: 3, tag: ""}], price: 2.5, n: 100}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "zz", flag: false, a: 50, items: [{price: 0.1, qty: 3, tag: "zz"}, {price: -1, qty: 1000, tag: "gold "}, {price: -0.1, tag: "a"}, {price: 50, qty: 21, tag: "bronze"}], price: 19.99, nums: [50, 2], n: 50}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "zz", flag: false, a: 10, items: [{price: 1000, qty: -0.1, tag: "x"}, {price: 0.1, qty: 7, tag: "silver"}, {price: 11, qty: 2, tag: "a"}], price: 2.5, nums: [10], n: 2}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "bronze", a: 99, items: [{price: null, qty: 0.1, tag: ""}], price: 5, nums: [], n: 7}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "Gold", flag: false, a: 1000000000000000000000, items: [{price: -25, qty: -0.1, tag: null}, {price: 3, qty: 21, tag: "gold "}], price: 19.99, nums: [99], n: 50, extra: 1}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "x", flag: true, a: 1, items: [], price: 19.99, nums: [86, 100, -0.1], n: 0.5}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "a", flag: false, items: [{price: 5, qty: -0.1, tag: "x"}, {price: 10, qty: 1000, tag: "bronze"}], price: 50, nums: [], n: -1}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "silver", flag: false, a: -25, items: [{price: 18, qty: 3, tag: "b"}], price: 1000000000000000000000, nums: [10], n: 101}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "", flag: true, a: 1000000000000000000000, items: [{qty: 18, tag: "silver"}, {qty: 18, tag: null}], price: -0.1, nums: [], n: 19.99}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "bronze", flag: false, a: 1000, items: [{price: -0.1, qty: -0.1, tag: null}], price: 18, nums: [11, -0.1], n: 18}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{flag: true, a: -9, items: [{qty: 10, tag: "b"}, {price: 0.1, qty: 5, tag: "Gold"}, {price: 100, qty: 0, tag: "x"}], price: -0.1, nums: [], n: 1000000000000000000000}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "Gold", flag: true, a: 19.99, items: [{price: 0, qty: 18, tag: "a"}], price: 3, nums: [18, 0.1, 0, 18, -25], n: 0}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{flag: false, a: 18, items: [{price: 101, qty: 0.5, tag: "Gold"}, {price: 5, tag: "x"}, {price: 100, qty: 7, tag: "gold"}], price: 50, nums: [], n: 1000}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "gold ", flag: true, a: 2, items: [{qty: 1, tag: "x"}], price: null, nums: [10, 2.5], n: -25}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "gold ", a: -0.1, items: [{price: -25, qty: 99, tag: ""}, {qty: -0.1, tag: "gold"}], price: null, nums: [101, 11, 0.5, 18, 11], n: null}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "b", flag: false, a: 1000000000000000000000, price: 7, nums: [5], n: 11}, "!error"], + [{code: null, flag: false, a: 2, price: 1000000000000000000000, nums: [101, -25], n: 100}, "!error"], + [{code: "Gold", flag: true, a: 101, items: [], price: 2.5, nums: [101, 1000], n: 21}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: null, flag: false, a: 50, items: [{price: -1, qty: 1, tag: "silver"}, {price: 1, qty: 10, tag: "a"}], price: 7, nums: [3, -0.1], n: 7, extra: {deep: {x: 1}}}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{flag: false, a: 1000, items: [{price: 101, qty: 1000, tag: "a"}, {price: 2.5, qty: -25, tag: "bronze"}, {price: 10, qty: 99, tag: "x"}], price: -12, nums: [19.99, 50], n: null}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "b", flag: false, a: 3, items: [{tag: ""}], nums: [18, 21, 5], n: 7}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{flag: false, a: 0, items: [], price: -25, nums: [18, 0.5, 50, 5, 50], n: 0}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + [{code: "Gold", flag: true, a: 19, items: [], price: -6, nums: [], n: 100}, {o: {p: {k700: null, k701: null, k702: -1, m: {k703: 102.25}}}}], + ], +} + +{ + name: "gb051: 6 nodes, switch*, switch*, loop table*, loop expr, table, table", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["(a ?? -1) != (a ?? 1)"]}, + {switch: "s2", hit: "collect", when: ["sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0))) <= floor((a ?? 1))", "string((flag ?? false)) == 'silver'", "2.25 in [0..10]", ""]}, + {table: "t3", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["qty", "price", "max([(qty) / 0.5, price])"], outputs: ["g.k709", "k710"], passThrough: true, outputPath: "res", rules: [ + ["<= 15", "", "!= 0", "'low'", "0"], + ["null", "$ > 0 and $ < 5", "> 5", "'high'", "0.25"], + ["[100..150]", "0", "(10..60)", "'gold'", "100"], + ["(5..15)", "", "!= 5", "string((true) or (true))", "10"], + ["", "", "", "(a == null ? 'x' + '' + string(false) : (tag ?? '?'))", "10"], + ]}, + {expression: "e4", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k711: "ceil(((price ?? 0)))", + k712: "string(qty + len((tag ?? '?')))", + }}, + {table: "t5", inputs: ["s", "code", "a"], outputs: ["k712", "k714"], rules: [ + ["'silver'", "'a', 'b'", "", "(`v${1}-${'gold'}` in ['gold', 'silver', 'a'] ? code : lower((false ? 'gold' : s)))", "''"], + ["null", "'x'", "<= 6", "'mid'", "'high'"], + ]}, + {table: "t6", inputs: ["min([0, 2]) - 3", "2.25"], outputs: ["m.k715"], passThrough: true, rules: [ + ["> 21", "(-1..0)", "false"], + ["!= 1", "!= 10", "true"], + ["", "> 5", "true"], + ["(1..6)", "> 18", "true"], + ["", "", "true"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> s2", + "input -> s2", + "s2:2 -> t3", + "s2:2 -> e4", + "s1:0 -> e4", + "s2:2 -> t5", + "s2:3 -> t5", + "t5 -> t6", + "s2:0 -> output", + "s2:1 -> output", + "t3 -> output", + "e4 -> output", + "t6 -> output", + ], + }, + cases: [ + [{s: "zz", flag: null, code: "Gold", a: 7, nums: [21, 99, 18, -0.1, 0], vip: true, items: [{price: 62, qty: 18, tag: ""}, {price: 2, qty: 50, tag: "Gold"}]}, {a: 7, code: "Gold", items: [{price: 62, qty: 18, tag: ""}, {price: 2, qty: 50, tag: "Gold"}], m: {k715: true}, nums: [21, 99, 18, -0.1, 0], res: [[{g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "xfalse"}, k710: 10}]], s: "zz", vip: true}], + [{s: "gold", flag: false, code: true, tier: "bronze", a: 3, nums: [100, -1], vip: false, items: [{price: 5, qty: 0, tag: "silver"}, {price: 100, qty: 1, tag: "zz"}, {price: -25, qty: 10, tag: "zz"}]}, {a: 3, code: true, flag: false, items: [{price: 5, qty: 0, tag: "silver"}, {price: 100, qty: 1, tag: "zz"}, {price: -25, qty: 10, tag: "zz"}], m: {k715: true}, nums: [100, -1], res: [[{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "low"}, k710: 0}, {g: {k709: "true"}, k710: 10}, {g: {k709: "xfalse"}, k710: 10}]], s: "gold", tier: "bronze", vip: false}], + [{s: "silver", flag: true, code: "", tier: "b", nums: [1, 7], vip: true, items: [{price: 101, qty: null, tag: "Gold"}], extra: {deep: {x: 1}}}, "!error"], + [{s: 5, flag: false, code: "x", tier: "zz", a: 1000, nums: [10, 21], vip: true, items: 3}, "!error"], + [{s: "b", flag: false, code: "zz", tier: "bronze", a: 18, nums: [5, 18, 0, 101, 3], vip: false, items: [{price: -0.1, qty: 2, tag: 5}]}, "!error"], + [{s: null, flag: 0, code: "gold", tier: "Gold", a: 1000000000000000000000, nums: [1000, 11], vip: null, items: [{price: 99, qty: 0.5, tag: "a"}, {price: -1, qty: 3, tag: "bronze"}]}, {a: 1000000000000000000000, code: "gold", flag: 0, items: [{price: 99, qty: 0.5, tag: "a"}, {price: -1, qty: 3, tag: "bronze"}], m: {k715: true}, nums: [1000, 11], res: [[{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}]], tier: "Gold"}], + [{s: "bronze", flag: 0, code: "b", tier: "silver", a: null, nums: [23, 0, 0.1], items: [{price: -1, qty: 3, tag: "silver"}, {price: 2.5, qty: 99}, {price: 72, qty: 1000000000000000000000, tag: "gold"}, {price: 0.5, qty: 0.5, tag: null}]}, {code: "b", flag: 0, items: [{price: -1, qty: 3, tag: "silver"}, {price: 2.5, qty: 99}, {price: 72, qty: 1000000000000000000000, tag: "gold"}, {price: 0.5, qty: 0.5, tag: null}], m: {k715: true}, nums: [23, 0, 0.1], res: [[{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}]], s: "bronze", tier: "silver"}], + [{s: "Gold", flag: false, code: true, tier: "silver", a: -25, nums: null, vip: false, items: [{price: 50, qty: 0.5, tag: "Gold"}, {price: 1000, qty: 1}, {price: 1000, qty: 22, tag: "zz"}, {price: {v: 1}, qty: 18, tag: "zz"}]}, "!error"], + [{flag: 0, code: "Gold", tier: "zz", nums: [], vip: "true", items: [{price: 5, qty: 1000000000000000000000, tag: "gold "}, {price: -1, qty: 11, tag: ""}, {price: -0.1, qty: {v: 1}, tag: "gold"}], extra: 1}, "!error"], + [{s: true, flag: false, code: "Gold", tier: "x", a: 21, nums: [11], vip: false, items: [{price: 11, qty: 19.99, tag: ""}, {price: 2.5, qty: 2, tag: "x"}, {price: 3, qty: -0.1, tag: "gold "}, {price: 10, qty: 1000000000000000000000, tag: "gold "}]}, {a: 21, code: "Gold", flag: false, items: [{price: 11, qty: 19.99, tag: ""}, {price: 2.5, qty: 2, tag: "x"}, {price: 3, qty: -0.1, tag: "gold "}, {price: 10, qty: 1000000000000000000000, tag: "gold "}], m: {k715: true}, nums: [11], res: [[{g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "xfalse"}, k710: 10}]], s: true, tier: "x", vip: false}], + [{s: "b", flag: false, tier: "b", vip: null, items: [{price: 0.1, qty: 0, tag: 5}, {qty: 2, tag: "silver"}, {price: 2.5, qty: -1, tag: "bronze"}]}, "!error"], + [{flag: true, code: "x", tier: "gold", a: 1000, nums: [18], vip: true, items: [{price: 0.1, qty: 2, tag: "b"}, {price: 0.1, qty: 100, tag: ""}]}, {a: 1000, code: "x", flag: true, items: [{price: 0.1, qty: 2, tag: "b"}, {price: 0.1, qty: 100, tag: ""}], m: {k715: true}, nums: [18], res: [[{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "xfalse"}, k710: 10}]], tier: "gold", vip: true}], + [{s: 5, flag: false, code: "zz", tier: "Gold", a: 5, nums: [3, 99, 3], vip: "no", items: [{price: {v: 1}, qty: 101, tag: ""}, {price: 100, qty: 21, tag: ""}]}, "!error"], + [{s: "gold ", flag: false, code: true, a: 2, nums: [18, 0, 7]}, "!error"], + [{s: "gold ", flag: 0, code: "Gold", tier: {t: "x"}, a: 0.5, nums: [1000, 1000000000000000000000, 11], vip: "no", items: [{price: 1000, tag: null}, {price: 1, tag: 5}]}, "!error"], + [{s: "x", flag: true, code: "b", tier: {t: "x"}, a: 100, nums: [-25, 7, 0], vip: "no", items: [{price: -1, qty: 2, tag: "zz"}, {price: 21, qty: 101, tag: "zz"}, {price: 35, qty: 7, tag: "b"}, {price: 18, qty: 79, tag: "a"}], extra: {deep: {x: 1}}}, {a: 100, code: "b", extra: {deep: {x: 1}}, flag: true, items: [{price: -1, qty: 2, tag: "zz"}, {price: 21, qty: 101, tag: "zz"}, {price: 35, qty: 7, tag: "b"}, {price: 18, qty: 79, tag: "a"}], m: {k715: true}, nums: [-25, 7, 0], res: [[{g: {k709: "low"}, k710: 0}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "low"}, k710: 0}, {g: {k709: "true"}, k710: 10}, {g: {k709: "xfalse"}, k710: 10}], [{g: {k709: "xfalse"}, k710: 10}]], s: "x", tier: {t: "x"}, vip: "no"}], + [{s: "Gold", flag: null, code: 5, tier: "bronze", a: 101, nums: [1000, 101, 99], vip: false, items: [{price: 11, qty: 100, tag: "a"}, {price: 11, qty: -1, tag: null}, {price: 2, qty: null}]}, "!error"], + ], +} + +{ + name: "gb052: 11 nodes, switch*, switch*, expr, switch, switch*, expr, loop expr, loop table, switch, expr, table*", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["not ('' in ['gold', 'silver', 'a'])", "vip == null", "ceil(a * -4) >= len((s ?? '') + ' ' + tier)", ""]}, + {switch: "s2", hit: "collect", when: ["(a ?? -1) * (a ?? 0) + len(s) >= (a ?? 1) * a * a", "`${a}-${(s ?? '?')}` != 'silver'"]}, + {expression: "e3", fields: { + "res.k716": "vip ?? a", + k717: "((a ?? 1) * a) == -4", + k718: "abs(a)", + }}, + {switch: "s4", when: ["((tier in ['gold', 'silver', 'a'])) and (true)", ""]}, + {switch: "s5", hit: "collect", when: ["vip", "startsWith((s ?? ''), 'x')"]}, + {expression: "e6", fields: { + "m.k719": "(((vip ?? false)) and ((vip ?? false)) ? (s ?? 'none') + ':' + (s ?? 'none') : (items ?? [])[0].tag ?? 'none') + ' ' + string(vip)", + "g.k720": "count(items ?? [], (#.qty ?? 0) > 1)", + k721: "100", + k722: "false", + }}, + {expression: "e7", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "lines", fields: { + k723: "max([(not (true) ? (3) : len('A-1')), (qty ?? qty ?? 0)])", + k724: "string(false)", + k725: "string(1)", + k726: "string(max([2.25, (price ?? -1)])) in ['gold', 'silver', 'a']", + }}, + {table: "t8", inputField: "items", executionMode: "loop", inputs: ["tag", "price", "price"], outputs: ["k727", "k728"], outputPath: "out", rules: [ + ["'x', 'b'", "", "", "2", "false"], + ["startsWith($, 's')", "0", "1, 2", "0", "false"], + ["null", ">= -1", ">= 21", "0.25", "false"], + ["", "", "", "10", "true"], + ]}, + {switch: "s9", when: ["((vip ?? false)) and (3 <= a)", "(-(10)) == (a ?? a ?? 0) + (a ?? 1)", ""]}, + {expression: "e10", passThrough: true, fields: { + k729: "'x'", + k730: "null", + k731: "`n=${0}-${($.k729 ?? '?')}`", + }}, + {table: "t11", hit: "collect", inputs: ["a", "a", "s"], outputs: ["g.k732", "k733"], outputPath: "o.p", rules: [ + ["", "18, 19", "startsWith($, '')", "(tier ?? '?')", "true"], + ["5", ">= 21", "null", "lower(((items ?? [])[1].tag ?? '') + '!')", "true"], + ["", "< 21", "", "'high'", "false"], + ["<= 0", "100, 150", "", "'gold'", "true"], + ["", "", "", "((vip ?? false) ? string(vip) : (tier ?? '') + '' + '') + ':' + string((a ?? -1) >= (a ?? 1))", "true"], + ]}, + ], + edges: [ + "input -> s1", + "s1:2 -> s2", + "s2:0 -> e3", + "s1:2 -> s4", + "s2:0 -> s4", + "s4:0 -> s5", + "s5:0 -> e6", + "s4:0 -> e7", + "s1:3 -> e7", + "s1:2 -> t8", + "s5:0 -> t8", + "e7 -> s9", + "t8 -> e10", + "s9:1 -> t11", + "s1:0 -> output", + "e3 -> output", + "e6 -> output", + "s9:0 -> output", + "e10 -> output", + "t11 -> output", + ], + }, + cases: [ + [{a: 0.1, tier: "", vip: true, s: "a", items: [{price: 19.99, qty: 0}, {price: 7, qty: 1000000000000000000000, tag: ""}, {price: 10, qty: null, tag: "bronze"}]}, {a: 0.1, items: [{price: 19.99, qty: 0}, {price: 7, qty: 1000000000000000000000, tag: ""}, {price: 10, qty: null, tag: "bronze"}], s: "a", tier: "", vip: true}], + [{a: -25, vip: false, s: "gold ", items: [{price: 0, qty: 7, tag: "gold"}]}, {a: -25, items: [{price: 0, qty: 7, tag: "gold"}], s: "gold ", vip: false}], + [{a: 11, tier: "Gold", vip: false, s: "gold ", items: [{price: 7, qty: 5, tag: "zz"}, {price: 11, qty: 7, tag: "a"}, {price: -0.1, tag: "gold"}, {price: 99, qty: 99, tag: ""}]}, {a: 11, items: [{price: 7, qty: 5, tag: "zz"}, {price: 11, qty: 7, tag: "a"}, {price: -0.1, tag: "gold"}, {price: 99, qty: 99, tag: ""}], s: "gold ", tier: "Gold", vip: false}], + [{a: 21, tier: "", vip: true, s: "zz", items: [{price: 0.5, qty: 1, tag: "b"}, {price: -25, qty: null}], extra: "e"}, {a: 21, extra: "e", items: [{price: 0.5, qty: 1, tag: "b"}, {price: -25, qty: null}], lines: [{k723: 3, k724: "false", k725: "1", k726: false, price: 0.5, qty: 1, tag: "b"}, {k723: 3, k724: "false", k725: "1", k726: false, price: -25, qty: null}], s: "zz", tier: "", vip: true}], + [{a: 100, tier: "x", vip: false, s: "x", items: []}, {a: 100, items: [], s: "x", tier: "x", vip: false}], + [{a: 19.99, tier: "x", vip: null, s: "x", items: [{price: 3, qty: 5, tag: "bronze"}, {price: 100, qty: -25, tag: "bronze"}]}, {a: 19.99, items: [{price: 3, qty: 5, tag: "bronze"}, {price: 100, qty: -25, tag: "bronze"}], s: "x", tier: "x"}], + [{a: 0, tier: "x", vip: true, s: "Gold"}, "!error"], + [{tier: "gold ", vip: true, s: "bronze", items: [{price: 101, qty: 99, tag: "b"}], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, items: [{price: 101, qty: 99, tag: "b"}], s: "bronze", tier: "gold ", vip: true}], + [{a: -25, tier: null, vip: false, s: "gold", items: [{price: 5, qty: null, tag: "bronze"}, {price: 11, tag: "bronze"}]}, {a: -25, items: [{price: 5, qty: null, tag: "bronze"}, {price: 11, tag: "bronze"}], s: "gold", vip: false}], + [{tier: "silver", vip: false, s: "b", items: [], extra: [1, 2]}, {extra: [1, 2], items: [], s: "b", tier: "silver", vip: false}], + [{a: -8, tier: "x", vip: false, s: "gold ", items: [{price: 1000000000000000000000, qty: 100, tag: "zz"}]}, {a: -8, items: [{price: 1000000000000000000000, qty: 100, tag: "zz"}], k717: false, k718: 8, k729: "x", k731: "n=0-x", out: [{k727: 10, k728: true}], res: {k716: false}, s: "gold ", tier: "x", vip: false}], + [{a: 19.99, tier: "bronze", vip: true, s: "b", items: [], extra: [1, 2]}, {a: 19.99, extra: [1, 2], items: [], lines: [], s: "b", tier: "bronze", vip: true}], + [{a: 113, vip: true, s: "b", items: [{price: 0.1, qty: 1000, tag: "x"}]}, {a: 113, items: [{price: 0.1, qty: 1000, tag: "x"}], lines: [{k723: 1000, k724: "false", k725: "1", k726: false, price: 0.1, qty: 1000, tag: "x"}], s: "b", vip: true}], + [{a: 0.1, tier: "silver", vip: true, s: null, items: [{price: 100, qty: 101, tag: "silver"}, {price: null, qty: -0.1, tag: "gold"}]}, {a: 0.1, items: [{price: 100, qty: 101, tag: "silver"}, {price: null, qty: -0.1, tag: "gold"}], tier: "silver", vip: true}], + [{tier: "a", vip: true, s: "Gold", items: [{price: 0.1, qty: null, tag: "gold"}, {price: 19.99, qty: -25}, {price: 10, qty: 1000, tag: "silver"}]}, {items: [{price: 0.1, qty: null, tag: "gold"}, {price: 19.99, qty: -25}, {price: 10, qty: 1000, tag: "silver"}], s: "Gold", tier: "a", vip: true}], + [{a: 0.5, tier: "a", vip: true, s: "a", items: [{price: null, qty: 0.5, tag: "gold"}, {price: 1000, qty: 83, tag: "Gold"}, {qty: 2.5}]}, {a: 0.5, items: [{price: null, qty: 0.5, tag: "gold"}, {price: 1000, qty: 83, tag: "Gold"}, {qty: 2.5}], s: "a", tier: "a", vip: true}], + [{a: 21, tier: "a", vip: false, s: "b", items: [], extra: "e"}, {a: 21, extra: "e", items: [], s: "b", tier: "a", vip: false}], + [{a: 21, tier: "x", vip: false, s: "a", items: [{price: 50, qty: 1000, tag: "silver"}, {price: null, tag: "x"}]}, {a: 21, items: [{price: 50, qty: 1000, tag: "silver"}, {price: null, tag: "x"}], s: "a", tier: "x", vip: false}], + [{a: 50, tier: "silver", vip: true, items: []}, {a: 50, items: [], lines: [], tier: "silver", vip: true}], + ], +} + +{ + name: "gb053: 7 nodes, switch*, expr, switch*, table*, loop expr, loop expr, table*", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["-(a) > 100", ""]}, + {expression: "e2", passThrough: true, fields: { + k734: "sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0)))", + k735: "s ?? flag", + k736: "n ?? s", + }}, + {switch: "s3", hit: "collect", when: ["100 in [0..10]", "flag", "not ((false) or (score >= (price ?? 0)))"]}, + {table: "t4", hit: "collect", inputs: ["s", "a", null], outputs: ["k737[]", "k738"], passThrough: true, outputPath: "lines", rules: [ + ["'', 'gold'", "[5..6)", "", "-5", "'mid'"], + ["startsWith($, 'x')", "5", "'gold'", "0", "''"], + ["", "21, 71", "$ != null", "1", "''"], + ["", "", "", "(a ?? -1)", "'low'"], + ]}, + {expression: "e5", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "lines", fields: { + k739: "qty ?? tag", + k740: "string(len((tag ?? 'none')) != qty)", + "g.k741": "tag ?? qty", + k742: "price ?? price", + }}, + {expression: "e6", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + k743: "tag ?? price", + k744: "len(((price ?? 1) in [-5..5] ? (tag ?? '?') : (false ? 'gold' : (tag ?? ''))))", + k745: "tag + ' ' + upper('none') + '' + tag", + k746: "qty ?? qty", + }}, + {table: "t7", hit: "collect", inputs: ["min([(0.5), (n ?? -1) + (price ?? -1)])"], outputs: ["k747[]"], outputPath: "res", rules: [ + [">= -1", "string(not ((score ?? 0) >= (score ?? 0)))"], + ["null", "(not ((a ?? -1) <= 1) ? lower((s ?? 'none')) : string(false))"], + ["> 5", "(s ?? 'none')"], + ]}, + ], + edges: [ + "input -> s1", + "input -> e2", + "input -> s3", + "s1:1 -> s3", + "s3:1 -> t4", + "s3:2 -> e5", + "s3:2 -> e6", + "t4 -> t7", + "e6 -> t7", + "s1:0 -> output", + "e2 -> output", + "s3:0 -> output", + "e5 -> output", + "t7 -> output", + ], + }, + cases: [ + [{items: [{price: 101, qty: 50, tag: "bronze"}, {price: 0, qty: -25, tag: {t: "x"}}], score: 18, flag: true, a: 2, price: 7, n: 99}, {a: 2, flag: true, items: [{price: 101, qty: 50, tag: "bronze"}, {price: 0, qty: -25, tag: {t: "x"}}], k734: 5050, k735: true, k736: 99, n: 99, price: 7, res: [{k747: "false"}], score: 18}], + [{items: [{price: 18, qty: 99, tag: "bronze"}, {price: 1000000000000000000000, qty: 3, tag: "gold"}], score: null, flag: false, a: 112, price: 2.5, n: 100, s: "silver"}, {a: 112, flag: false, items: [{price: 18, qty: 99, tag: "bronze"}, {price: 1000000000000000000000, qty: 3, tag: "gold"}], k734: 3000000000000000001782, k735: "silver", k736: 100, n: 100, price: 2.5, s: "silver"}], + [{items: [{price: 5, tag: "silver"}, {price: 3, tag: ""}, {price: 99, qty: -25, tag: "a"}, {price: 11, qty: null}], score: 3, flag: false, a: -25, price: 18, n: -0.1, s: "gold ", extra: 1}, "!error"], + [{a: 2.5, price: 1, n: 21, s: "x"}, {a: 2.5, k734: 0, k735: "x", k736: 21, n: 21, price: 1, s: "x"}], + [{items: [{price: 101, qty: 2.5, tag: {t: "x"}}, {price: 50, qty: 0.5, tag: "silver"}], score: null, flag: false, a: 1000, price: null, n: 18, s: "x"}, {a: 1000, flag: false, items: [{price: 101, qty: 2.5, tag: {t: "x"}}, {price: 50, qty: 0.5, tag: "silver"}], k734: 277.5, k735: "x", k736: 18, n: 18, s: "x"}], + [{items: 3, score: 7, flag: true, a: 1, price: 19.99, n: 11, s: null}, "!error"], + [{items: [{price: 99, qty: -0.1, tag: "silver"}, {price: 0.5, qty: 1000, tag: "a"}], score: -1, flag: false, a: 101, price: -1, n: 101, s: "Gold"}, {a: 101, flag: false, items: [{price: 99, qty: -0.1, tag: "silver"}, {price: 0.5, qty: 1000, tag: "a"}], k734: 490.1, k735: "Gold", k736: 101, n: 101, price: -1, s: "Gold", score: -1}], + [{items: [{price: 11, qty: 19.99, tag: "bronze"}, {price: 0.1, qty: 11, tag: "gold"}], score: 100, flag: true, a: -0.1, price: null, n: 0.5, s: "gold "}, {a: -0.1, flag: true, items: [{price: 11, qty: 19.99, tag: "bronze"}, {price: 0.1, qty: 11, tag: "gold"}], k734: 220.99, k735: "gold ", k736: 0.5, n: 0.5, res: [{k747: "false"}], s: "gold ", score: 100}], + [{items: [{price: 0.5, qty: -0.1, tag: "gold "}], score: 11, flag: null, a: {v: 1}, price: null, n: [1]}, {a: {v: 1}, items: [{price: 0.5, qty: -0.1, tag: "gold "}], k734: -0.05, k736: [1], n: [1], score: 11}], + [{items: [{price: 0.5, qty: -1, tag: null}, {price: 5, qty: -25, tag: "zz"}, {price: null, qty: null}], flag: false, a: 5, price: 7, n: 101, s: "x"}, {a: 5, flag: false, items: [{price: 0.5, qty: -1, tag: null}, {price: 5, qty: -25, tag: "zz"}, {price: null, qty: null}], k734: -125.5, k735: "x", k736: 101, n: 101, price: 7, s: "x"}], + [{items: [], score: 0.1, flag: 0, a: 7, price: null, n: 50, s: "x"}, {a: 7, flag: 0, items: [], k734: 0, k735: "x", k736: 50, n: 50, s: "x", score: 0.1}], + [{items: [{price: 21, qty: 2, tag: "bronze"}, {price: -1, qty: 1000, tag: ""}, {price: 1, qty: 1}, {price: -0.1, qty: null, tag: "bronze"}], score: null, flag: false, a: 101, price: "abc", n: 7, s: "Gold"}, {a: 101, flag: false, items: [{price: 21, qty: 2, tag: "bronze"}, {price: -1, qty: 1000, tag: ""}, {price: 1, qty: 1}, {price: -0.1, qty: null, tag: "bronze"}], k734: -957, k735: "Gold", k736: 7, n: 7, price: "abc", s: "Gold"}], + [{items: [{price: -25, tag: "b"}, {price: 50, qty: 3, tag: "x"}, {tag: "Gold"}, {price: 5, qty: 101, tag: "zz"}], score: 21, flag: true, a: -0.1, price: {v: 1}, n: null, s: ""}, {a: -0.1, flag: true, items: [{price: -25, tag: "b"}, {price: 50, qty: 3, tag: "x"}, {tag: "Gold"}, {price: 5, qty: 101, tag: "zz"}], k734: 655, k735: "", k736: "", price: {v: 1}, res: [], s: "", score: 21}], + [{items: [{price: 50, qty: 11, tag: ""}], score: "5", flag: true, a: 101, price: 50, n: 100, s: null}, {a: 101, flag: true, items: [{price: 50, qty: 11, tag: ""}], k734: 550, k735: true, k736: 100, n: 100, price: 50, res: [], score: "5"}], + [{items: [{price: 10, qty: 50, tag: "Gold"}], score: 2.5, flag: "no", a: 50, n: 1000, s: "Gold"}, {a: 50, flag: "no", items: [{price: 10, qty: 50, tag: "Gold"}], k734: 500, k735: "Gold", k736: 1000, n: 1000, s: "Gold", score: 2.5}], + [{items: [{price: 0, qty: 50, tag: "bronze"}, {qty: 92, tag: "a"}, {price: 99, qty: 10, tag: "a"}], score: 2, flag: true, a: true, price: 2.5, n: -0.1, s: "a"}, {a: true, flag: true, items: [{price: 0, qty: 50, tag: "bronze"}, {qty: 92, tag: "a"}, {price: 99, qty: 10, tag: "a"}], k734: 990, k735: "a", k736: -0.1, lines: [{g: {k741: "bronze"}, k739: 50, k740: "true", k742: 0, price: 0, qty: 50, tag: "bronze"}, {g: {k741: "a"}, k739: 92, k740: "true", qty: 92, tag: "a"}, {g: {k741: "a"}, k739: 10, k740: "true", k742: 99, price: 99, qty: 10, tag: "a"}], n: -0.1, price: 2.5, res: [{k747: "false"}], s: "a", score: 2}], + [{items: [{price: -25, qty: -0.1, tag: "x"}], score: 5, flag: false, a: -1, n: null, s: "zz"}, {a: -1, flag: false, items: [{price: -25, qty: -0.1, tag: "x"}], k734: 2.5, k735: "zz", k736: "zz", s: "zz", score: 5}], + [{items: [{price: 2, qty: 23, tag: "b"}, {price: 3, qty: 50}, {qty: 1, tag: 5}, {price: 0.5, qty: 18, tag: "gold"}], score: 0, flag: 0, a: "abc", price: 2.5, n: "abc", s: null}, "!error"], + [{items: [{price: 5, qty: 0.1}, {qty: true, tag: "gold "}], score: 0.5, flag: false, a: 0, price: 100, s: "bronze"}, "!error"], + [{items: [{price: null, qty: 101, tag: "Gold"}, {price: null, qty: 99, tag: "gold "}, {price: 0, qty: 101, tag: "silver"}], score: 100, flag: false, a: 0.1, n: 3, s: "x"}, {a: 0.1, flag: false, items: [{price: null, qty: 101, tag: "Gold"}, {price: null, qty: 99, tag: "gold "}, {price: 0, qty: 101, tag: "silver"}], k734: 0, k735: "x", k736: 3, n: 3, s: "x", score: 100}], + [{items: [{price: 2.5, qty: 7, tag: "silver"}, {price: 21, qty: 19.99, tag: "gold "}, {price: 21, qty: 10, tag: 5}, {price: 0.1, qty: 21, tag: "gold "}], score: 99, flag: false, a: 1000, price: -1, n: 19.99, s: "gold "}, {a: 1000, flag: false, items: [{price: 2.5, qty: 7, tag: "silver"}, {price: 21, qty: 19.99, tag: "gold "}, {price: 21, qty: 10, tag: 5}, {price: 0.1, qty: 21, tag: "gold "}], k734: 649.39, k735: "gold ", k736: 19.99, n: 19.99, price: -1, s: "gold ", score: 99}], + [{items: [{price: null, qty: -25, tag: null}, {price: 18, qty: 2.5, tag: true}], score: 0.5, flag: true, a: 1000000000000000000000, price: 19.99, n: 100, s: "zz"}, "!error"], + [{items: [], score: 0, flag: false, a: 18, price: 101, n: null, s: "x"}, {a: 18, flag: false, items: [], k734: 0, k735: "x", k736: "x", lines: [], price: 101, res: [{k747: "false"}], s: "x", score: 0}], + [{items: [], score: 100, flag: true, a: 7, price: 5, n: 7, extra: {deep: {x: 1}}}, {a: 7, extra: {deep: {x: 1}}, flag: true, items: [], k734: 0, k735: true, k736: 7, n: 7, price: 5, res: [{k747: "false"}], score: 100}], + [{items: [{price: 10, qty: 50, tag: "bronze"}], score: 10, a: -11, price: 70, n: 100, s: true}, {a: -11, items: [{price: 10, qty: 50, tag: "bronze"}], k734: 500, k735: true, k736: 100, lines: [{g: {k741: "bronze"}, k739: 50, k740: "true", k742: 10, price: 10, qty: 50, tag: "bronze"}], n: 100, price: 70, res: [{k747: "false"}], s: true, score: 10}], + [{items: [{price: 18, qty: -1, tag: "gold"}, {price: null, qty: null, tag: "a"}, {price: 101, qty: 10}, {price: "5", qty: 5, tag: null}], score: 101, flag: true, a: 0.5, n: 0, s: "Gold"}, "!error"], + [{items: [], flag: false, a: 10, price: 21, n: 50, s: "zz"}, {a: 10, flag: false, items: [], k734: 0, k735: "zz", k736: 50, n: 50, price: 21, s: "zz"}], + [{items: [], score: -25, flag: null, a: 1, n: 2, s: "Gold"}, {a: 1, items: [], k734: 0, k735: "Gold", k736: 2, lines: [], n: 2, res: [{k747: "false"}], s: "Gold", score: -25}], + ], +} + +{ + name: "gb054: 7 nodes, expr, loop expr, loop table*, loop table, expr, switch, table", + graph: { + nodes: [ + {expression: "e1", outputPath: "lines", fields: { + k748: "-(-(score))", + k749: "score ?? score", + k750: "(score ?? 0) * (-((score ?? 1))) / 4", + k751: "$.k748 ?? score", + }}, + {expression: "e2", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "o.p", fields: { + k752: "string(not (10 in [0..10]))", + "res.k753": "-(price)", + "res.k754": "`${(qty ?? 0)}-${(tag ?? 'none')}`", + k750: "`n=${-4}-${(tag ?? 'none')}`", + }}, + {table: "t3", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["price"], outputs: ["k756", "k757"], outputPath: "res", rules: [ + ["not(-1)", "'mid'", "true"], + ["!= -1", "'low'", "false"], + ["10, 15", "(tag ?? '?')", "true"], + ["null", "'gold'", "false"], + ["(21..71)", "'mid'", "false"], + ["< 21", "'mid'", "false"], + ]}, + {table: "t4", inputField: "items", executionMode: "loop", inputs: ["tag"], outputs: ["m.k758"], passThrough: true, outputPath: "out", rules: [ + ["'silver'", "false"], + ["$ != ''", "false"], + ["", "true"], + ["not('x')", "true"], + ["", "false"], + ]}, + {expression: "e5", passThrough: true, outputPath: "lines", fields: { + k759: "score", + "m.k760": "($.k759 ?? 1)", + }}, + {switch: "s6", when: ["true", "false", ""]}, + {table: "t7", inputs: ["2"], outputs: ["k761", "m.k762"], rules: [ + [">= 21", "-(ceil(2 + 0.5))", "`v${-4}-${'gold'}`"], + ["$ > 10 and $ < 20", "2", "string(string(2) in ['gold', 'silver', 'a'])"], + ["10", "-5", "'low'"], + ["10", "2", "'gold'"], + ["null", "(2.25) / 3", "''"], + ]}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e2 -> t3", + "e1 -> t3", + "e2 -> t4", + "e2 -> e5", + "t3 -> s6", + "s6:1 -> t7", + "t4 -> output", + "e5 -> output", + "s6:0 -> output", + "t7 -> output", + ], + }, + cases: [ + [{code: true, tier: "gold", items: []}, "!error"], + [{score: 1000, code: "", tier: "silver", items: [{price: 11, qty: 1000000000000000000000, tag: "bronze"}, {price: 5, qty: true, tag: "x"}, {price: 2, qty: 0.1}, {price: 0.5, qty: 101, tag: "b"}]}, {code: "", items: [{price: 11, qty: 1000000000000000000000, tag: "bronze"}, {price: 5, qty: true, tag: "x"}, {price: 2, qty: 0.1}, {price: 0.5, qty: 101, tag: "b"}], lines: {k759: 1000, m: {k760: 1000}}, o: {p: [{k750: "n=-4-bronze", k752: "false", price: 11, qty: 1000000000000000000000, res: {k753: -11, k754: "1000000000000000000000-bronze"}, tag: "bronze"}, {k750: "n=-4-x", k752: "false", price: 5, qty: true, res: {k753: -5, k754: "true-x"}, tag: "x"}, {k750: "n=-4-none", k752: "false", price: 2, qty: 0.1, res: {k753: -2, k754: "0.1-none"}}, {k750: "n=-4-b", k752: "false", price: 0.5, qty: 101, res: {k753: -0.5, k754: "101-b"}, tag: "b"}]}, out: [{m: {k758: false}, price: 11, qty: 1000000000000000000000, tag: "bronze"}, {m: {k758: false}, price: 5, qty: true, tag: "x"}, {m: {k758: false}, price: 2, qty: 0.1}, {m: {k758: false}, price: 0.5, qty: 101, tag: "b"}], res: [[{k756: "low", k757: false}, {k756: "mid", k757: false}], [{k756: "low", k757: false}, {k756: "mid", k757: false}], [{k756: "low", k757: false}, {k756: "mid", k757: false}], [{k756: "low", k757: false}, {k756: "mid", k757: false}]], score: 1000, tier: "silver"}], + [{score: 0, code: {t: "x"}, tier: ["gold"], items: []}, {code: {t: "x"}, items: [], lines: {k759: 0, m: {k760: 0}}, o: {p: []}, out: [], res: [], score: 0, tier: ["gold"]}], + [{score: null, tier: "silver", items: [{price: -25, tag: "silver"}]}, "!error"], + [{score: {v: 1}, code: "silver", tier: "Gold", items: [{price: 79, qty: 101, tag: true}, {price: 7, qty: 1000000000000000000000, tag: ""}, {price: 19.99, qty: 1000000000000000000000, tag: "zz"}]}, "!error"], + [{score: 68, code: "Gold", tier: {t: "x"}, items: [{price: 7, tag: "b"}]}, {code: "Gold", items: [{price: 7, tag: "b"}], lines: {k759: 68, m: {k760: 68}}, o: {p: [{k750: "n=-4-b", k752: "false", price: 7, res: {k753: -7, k754: "0-b"}, tag: "b"}]}, out: [{m: {k758: false}, price: 7, tag: "b"}], res: [[{k756: "low", k757: false}, {k756: "mid", k757: false}]], score: 68, tier: {t: "x"}}], + [{score: 0, code: "a", tier: "zz", items: 3}, "!error"], + [{score: 11, code: "gold ", tier: "b", items: []}, {code: "gold ", items: [], lines: {k759: 11, m: {k760: 11}}, o: {p: []}, out: [], res: [], score: 11, tier: "b"}], + [{code: "gold ", tier: "gold ", items: [{price: 0.1, qty: 3, tag: "a"}, {price: 0.5, qty: 0, tag: "Gold"}, {price: 50, qty: 3, tag: null}, {price: 21, qty: 10, tag: "gold"}]}, "!error"], + [{score: null, tier: null, items: [{price: 3, qty: 1, tag: 5}, {price: 7, qty: 19.99, tag: true}, {price: 0.1, qty: 2}], extra: 1}, "!error"], + [{score: 2, code: 5, items: [{price: -25, qty: -0.1, tag: "gold "}, {price: 2.5, qty: "abc", tag: true}]}, {code: 5, items: [{price: -25, qty: -0.1, tag: "gold "}, {price: 2.5, qty: "abc", tag: true}], lines: {k759: 2, m: {k760: 2}}, o: {p: [{k750: "n=-4-gold ", k752: "false", price: -25, qty: -0.1, res: {k753: 25, k754: "-0.1-gold "}, tag: "gold "}, {k750: "n=-4-true", k752: "false", price: 2.5, qty: "abc", res: {k753: -2.5, k754: "abc-true"}, tag: true}]}, out: [{m: {k758: false}, price: -25, qty: -0.1, tag: "gold "}, {m: {k758: false}, price: 2.5, qty: "abc", tag: true}], res: [[{k756: "low", k757: false}, {k756: "mid", k757: false}], [{k756: "low", k757: false}, {k756: "mid", k757: false}]], score: 2}], + [{score: 0, code: "zz", tier: "", items: {price: 1}}, "!error"], + [{score: 0.1, code: "bronze", tier: "Gold", items: [{price: 101, qty: 1000, tag: ""}, {price: 2, qty: null, tag: ""}], extra: {deep: {x: 1}}}, {code: "bronze", extra: {deep: {x: 1}}, items: [{price: 101, qty: 1000, tag: ""}, {price: 2, qty: null, tag: ""}], lines: {k759: 0.1, m: {k760: 0.1}}, o: {p: [{k750: "n=-4-", k752: "false", price: 101, qty: 1000, res: {k753: -101, k754: "1000-"}, tag: ""}, {k750: "n=-4-", k752: "false", price: 2, qty: null, res: {k753: -2, k754: "0-"}, tag: ""}]}, out: [{m: {k758: true}, price: 101, qty: 1000, tag: ""}, {m: {k758: true}, price: 2, qty: null, tag: ""}], res: [[{k756: "low", k757: false}], [{k756: "low", k757: false}, {k756: "mid", k757: false}]], score: 0.1, tier: "Gold"}], + [{score: true, items: [{price: 2.5, qty: 3, tag: "a"}, {price: 96, qty: 21, tag: "silver"}, {price: 0.5, qty: [1], tag: "a"}]}, "!error"], + [{score: 0.5, code: null, tier: "x", items: [{price: 1000000000000000000000, qty: 1, tag: "silver"}, {price: null, qty: 11, tag: ""}, {price: -0.1, qty: 1000, tag: "zz"}, {price: 21, qty: [1], tag: "b"}]}, "!error"], + [{code: "", tier: {t: "x"}, items: []}, "!error"], + [{score: "5", code: "a", tier: true, items: [{price: 10, qty: 1000000000000000000000, tag: "gold "}, {price: null, qty: -1, tag: true}, {price: 101, qty: -0.1, tag: ""}]}, "!error"], + ], +} + +{ + name: "gb055: 11 nodes, loop expr, expr, table, loop table*, expr, switch, expr, switch*, loop table*, table, table", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "out", fields: { + k763: "len(tag) + (qty == 0.5 ? qty - (price ?? -1) : (price ?? -1) - (price ?? 0))", + k764: "(price ?? 0) % 7 - (qty) - (len(tag))", + k765: "((tag ?? '') in ['gold', 'silver', 'a'] ? string((tag ?? 'none') != 'gold') : string(tag == null))", + }}, + {expression: "e2", fields: { + k766: "false", + k767: "(n ?? -1) - 1 + 3 % 2", + k768: "(score ?? -1)", + k769: "tier ?? tier", + }}, + {table: "t3", inputs: ["n", "score", null], outputs: ["m.k770", "k771"], passThrough: true, rules: [ + ["> 5", "$ > 100 and $ < 105", "null", "1", "'low'"], + ["", "", "", "10", "'low'"], + ["", "", "", "10", "(s ?? 'none')"], + ]}, + {table: "t4", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["tag", "tag", "tag"], outputs: ["res.k772"], passThrough: true, outputPath: "lines", rules: [ + ["not('gold')", "startsWith($, 'a')", "$ != 'silver'", "true"], + ["'gold'", "", "", "true"], + ["'silver', 'b'", "", "startsWith($, 'a')", "true"], + ["startsWith($, '')", "''", "", "false"], + ["not('a')", "null", "'silver'", "true"], + ]}, + {expression: "e5", fields: { + "res.k773": "'gold'", + k774: "(len(string(0.5))) / 4", + "m.k775": "`${k768}-${'none'}`", + }}, + {switch: "s6", when: ["trim(`v${(k767 ?? 1)}-${'none'}`) != ''", "(k767 * k774) > ((k768 ?? 0) * (k768 ?? -1))", "((k766 ?? false))"]}, + {expression: "e7", passThrough: true, outputPath: "out", fields: { + k776: "min([(k774) / 0.5, (((k767 ?? 0)) / 10) / 10])", + k769: "(k766 ? (k766 ? round((k767 ?? -1)) : k768) : (((k768 ?? -1))))", + k778: "((k766 ?? false) ? (m.k775 ?? '') + '' + (m.k775 ?? '?') : (m.k775 ?? '?')) != 'silver'", + k779: "round(($nodes.e2.k768 ?? 0) % 2)", + }}, + {switch: "s8", hit: "collect", when: ["(k766 ?? false)", ""]}, + {table: "t9", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["price", "qty", "((qty ?? 0)) / 4 * 10 + qty"], outputs: ["res.k780"], outputPath: "lines", rules: [ + ["[5..10)", "", "<= 11", "((contains((tag ?? '?'), 'a')) ? (qty ?? 0) : ((qty ?? 1)))"], + ["< 5", "> -1", "0, 50", "1"], + ["-1", "[5..15]", "100, 110", "0"], + ]}, + {table: "t10", inputs: ["k767"], outputs: ["k781", "k782"], rules: [ + ["> -1", "(m.k775 ?? '?')", "'gold'"], + ["<= 150", "(res.k773 ?? 'none')", "''"], + ["0", "'gold'", "'gold'"], + ]}, + {table: "t11", inputs: ["m.k775", null], outputs: ["k783"], passThrough: true, outputPath: "lines", rules: [ + ["'a'", "null", "'gold'"], + ["'x', 'gold'", "5", "'mid'"], + ["$ != 'gold'", "5", "''"], + ["startsWith($, 'g')", "5", "'low'"], + ["startsWith($, 'a')", "5", "'low'"], + ["", "", "''"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "input -> t3", + "input -> t4", + "e2 -> e5", + "e2 -> s6", + "e5 -> s6", + "s6:1 -> e7", + "s6:1 -> s8", + "input -> t9", + "t9 -> t10", + "s8:0 -> t10", + "s8:0 -> t11", + "t3 -> output", + "t4 -> output", + "e5 -> output", + "s6:0 -> output", + "s6:2 -> output", + "e7 -> output", + "s8:1 -> output", + "t9 -> output", + "t10 -> output", + "t11 -> output", + ], + }, + cases: [ + [{n: 1000000000000000000000, tier: "x", s: "gold", b: 2.5, score: 0.1, items: [{qty: 100, tag: "silver"}, {price: 10, qty: -25, tag: "a"}]}, {b: 2.5, items: [{qty: 100, tag: "silver"}, {price: 10, qty: -25, tag: "a"}], k766: false, k767: 1000000000000000000000, k768: 0.1, k769: "x", k771: "low", k774: 0.75, lines: [[], []], m: {k770: 10, k775: "0.1-none"}, n: 1000000000000000000000, res: {k773: "gold"}, s: "gold", score: 0.1, tier: "x"}], + [{n: 0.5, tier: "", b: 0, score: 11, items: [{price: null, qty: 11, tag: "zz"}, {price: 99, qty: 7, tag: "Gold"}], extra: 1}, {b: 0, extra: 1, items: [{price: null, qty: 11, tag: "zz"}, {price: 99, qty: 7, tag: "Gold"}], k766: false, k767: 0.5, k768: 11, k769: "", k771: "low", k774: 0.75, lines: [[], []], m: {k770: 10, k775: "11-none"}, n: 0.5, res: {k773: "gold"}, score: 11, tier: ""}], + [{n: 18, tier: "Gold", s: "", b: null, score: 11, items: []}, {items: [], k766: false, k767: 18, k768: 11, k769: "Gold", k771: "low", k774: 0.75, lines: [], m: {k770: 10, k775: "11-none"}, n: 18, res: {k773: "gold"}, s: "", score: 11, tier: "Gold"}], + [{n: 0, tier: "gold", s: "gold ", b: null, score: 5, items: [{price: 7, qty: 5, tag: "silver"}], extra: [1, 2]}, {extra: [1, 2], items: [{price: 7, qty: 5, tag: "silver"}], k766: false, k767: 0, k768: 5, k769: "gold", k771: "low", k774: 0.75, lines: [[]], m: {k770: 10, k775: "5-none"}, n: 0, res: {k773: "gold"}, s: "gold ", score: 5, tier: "gold"}], + [{n: 3, s: "zz", b: -1, score: 1000000000000000000000, items: [{price: -25, qty: -1, tag: "gold "}, {price: 101, qty: 21, tag: "gold"}], extra: 1}, {b: -1, extra: 1, items: [{price: -25, qty: -1, tag: "gold "}, {price: 101, qty: 21, tag: "gold"}], k766: false, k767: 3, k768: 1000000000000000000000, k771: "low", k774: 0.75, lines: [[], [{res: {k772: true}}]], m: {k770: 10, k775: "1000000000000000000000-none"}, n: 3, res: {k773: "gold"}, s: "zz", score: 1000000000000000000000}], + [{n: 0, tier: "gold", s: "gold ", b: null, score: 21, items: [{price: 50, qty: -1, tag: null}]}, "!error"], + [{n: -1, tier: "x", s: "b", b: 18, score: 101, items: [{price: 0, qty: 7, tag: "x"}, {qty: null, tag: "zz"}, {price: -25, tag: "Gold"}]}, "!error"], + [{n: 0.1, tier: "bronze", s: "", b: 50, score: 2.5, items: [{price: 18, qty: 1000000000000000000000, tag: ""}]}, {b: 50, items: [{price: 18, qty: 1000000000000000000000, tag: ""}], k766: false, k767: 0.1, k768: 2.5, k769: "bronze", k771: "low", k774: 0.75, lines: [[{res: {k772: false}}]], m: {k770: 10, k775: "2.5-none"}, n: 0.1, res: {k773: "gold"}, s: "", score: 2.5, tier: "bronze"}], + [{n: 0.1, tier: "", s: "bronze", b: 5, score: 99, items: [{price: 0.5, qty: 2, tag: "gold "}, {price: -25, qty: 2.5, tag: ""}]}, {b: 5, items: [{price: 0.5, qty: 2, tag: "gold "}, {price: -25, qty: 2.5, tag: ""}], k766: false, k767: 0.1, k768: 99, k769: "", k771: "low", k774: 0.75, lines: [[], [{res: {k772: false}}]], m: {k770: 10, k775: "99-none"}, n: 0.1, res: {k773: "gold"}, s: "bronze", score: 99, tier: ""}], + [{n: 2.5, tier: "gold", s: "gold ", b: 99, score: 18, items: [{price: 1000000000000000000000, qty: 0.1}]}, "!error"], + [{n: 2.5, s: "", b: 1000000000000000000000, score: -0.1, items: [{price: null, tag: "silver"}, {price: -0.1, qty: 1000000000000000000000, tag: "zz"}]}, "!error"], + [{n: 18, tier: "b", s: null, b: 3, score: 3, items: [{price: 0, qty: -25, tag: "b"}]}, {b: 3, items: [{price: 0, qty: -25, tag: "b"}], k766: false, k767: 18, k768: 3, k769: "b", k771: "low", k774: 0.75, lines: [[]], m: {k770: 10, k775: "3-none"}, n: 18, res: {k773: "gold"}, score: 3, tier: "b"}], + [{n: 1, tier: "a", s: "b", b: 0, score: 0.5, items: [{price: 3, qty: 1000, tag: "gold "}]}, {b: 0, items: [{price: 3, qty: 1000, tag: "gold "}], k766: false, k767: 1, k768: 0.5, k769: "a", k771: "low", k774: 0.75, lines: [[]], m: {k770: 10, k775: "0.5-none"}, n: 1, res: {k773: "gold"}, s: "b", score: 0.5, tier: "a"}], + [{n: 0.5, tier: "bronze", s: "gold ", b: 1000, score: 1000, items: [{price: 0.1, qty: 1000, tag: "silver"}, {price: 21, qty: 1, tag: "gold "}]}, {b: 1000, items: [{price: 0.1, qty: 1000, tag: "silver"}, {price: 21, qty: 1, tag: "gold "}], k766: false, k767: 0.5, k768: 1000, k769: "bronze", k771: "low", k774: 0.75, lines: [[], []], m: {k770: 10, k775: "1000-none"}, n: 0.5, res: {k773: "gold"}, s: "gold ", score: 1000, tier: "bronze"}], + [{n: 2, tier: "silver", s: "b", b: 21, score: 0, items: [{price: 1, qty: 101, tag: "gold "}, {price: 7, qty: 1, tag: "bronze"}, {price: 2.5, qty: 0.1, tag: ""}, {price: 0.1, qty: -25, tag: null}]}, "!error"], + [{n: null, tier: "", s: "", b: 1000000000000000000000, score: 0.5, items: []}, {b: 1000000000000000000000, items: [], k766: false, k767: -1, k768: 0.5, k769: "", k771: "low", k774: 0.75, lines: [], m: {k770: 10, k775: "0.5-none"}, res: {k773: "gold"}, s: "", score: 0.5, tier: ""}], + [{n: 99, tier: "zz", s: "gold ", b: 99, score: 5, items: [{price: 7, qty: 99}, {price: -25, tag: "a"}], extra: 1}, "!error"], + ], +} + +{ + name: "gb056: 9 nodes, table, expr, switch*, loop table, expr, loop expr, switch*, table*, expr", + graph: { + nodes: [ + {table: "t1", inputs: ["a", "-(a - (a ?? 0))"], outputs: ["k784"], outputPath: "out", rules: [ + [">= 18", "<= 15", "false"], + ["not(100)", "", "true"], + ["[21..71)", "(5..55)", "true"], + ["(18..23)", ">= 18", "false"], + ["", "< -1", "true"], + ["", "", "false"], + ]}, + {expression: "e2", outputPath: "lines", fields: { + k785: "((b ?? 0))", + }}, + {switch: "s3", hit: "collect", when: ["'' in ['gold', 'silver', 'a']", "'A-1' in ['gold', 'silver', 'a']", "(-(1) > (a ?? 0)) or ((((flag ?? false)) and (false)))"]}, + {table: "t4", inputField: "items", executionMode: "loop", inputs: ["min([(1), (qty)])"], outputs: ["m.k786"], outputPath: "res", rules: [ + ["null", "2"], + ["not(18)", "10"], + ["null", "-5"], + ["[21..31)", "0.25"], + ["", "-4"], + ["", "10"], + ]}, + {expression: "e5", passThrough: true, fields: { + "m.k786": "`v${a}-${'A-1'}`", + k789: "min([(a ?? 1), (b ?? 0) % 2]) + 2.25", + "res.k790": "string(((flag ?? false)) and (contains('A-1', '')))", + }}, + {expression: "e6", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "out", fields: { + "m.k791": "(false) and (0 >= 0 * (qty ?? 1))", + k792: "tag ?? tag", + k793: "qty ?? price", + }}, + {switch: "s7", hit: "collect", when: ["((not (true)) and (a != null)) and ('x' == '')", "lines.k785 == min([0.5, 100]) % 3", "true"]}, + {table: "t8", hit: "collect", inputs: ["((true) and (false) ? string(false) : 'none')", "lines.k785"], outputs: ["k794[]"], outputPath: "o.p", rules: [ + ["", "<= 11", "false"], + ["", "[10..20]", "true"], + ["", "(0..50)", "(endsWith(string((lines.k785 ?? -1)), 'x'))"], + ["$ != 'silver'", "> -1", "true"], + ["'x'", "", "((2 == (lines.k785 ?? -1)) or (lines.k785 in [1..100]))"], + ]}, + {expression: "e9", passThrough: true, outputPath: "out", fields: { + k795: "0.5", + k785: "0 > (lines.k785 ?? 1)", + "m.k797": "`n=${2}-${''}`", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "input -> s3", + "e2 -> t4", + "s3:1 -> t4", + "s3:0 -> e5", + "s3:1 -> e6", + "e2 -> s7", + "s7:1 -> t8", + "s7:2 -> e9", + "t1 -> output", + "t4 -> output", + "e5 -> output", + "e6 -> output", + "t8 -> output", + "e9 -> output", + ], + }, + cases: [ + [{flag: true, items: [], b: -1, a: 1000}, "!error"], + [{flag: true, items: [{price: 1000, qty: null, tag: "Gold"}, {price: 1000, qty: 99, tag: "b"}, {price: 100, qty: 11, tag: ""}, {price: null, qty: -0.1, tag: "gold"}], b: 2.5, a: 0}, "!error"], + [{flag: null, items: [{price: -25, qty: 10, tag: "gold"}, {price: 2.5, qty: 10, tag: "b"}, {price: null, qty: 21, tag: "a"}], b: 2.5, a: 1000000000000000000000}, "!error"], + [{flag: true, items: [{price: 0, qty: -25, tag: "bronze"}, {price: 0.5, qty: 50, tag: "x"}, {price: 10, qty: 2, tag: ""}], b: 5, a: 21}, "!error"], + [{flag: false, items: [{price: -0.1, qty: 101, tag: "gold"}, {price: 0.5, qty: -0.1, tag: "b"}, {price: 99, qty: 100, tag: "x"}, {price: -18, qty: -1, tag: "b"}], b: 11, a: 101, extra: {deep: {x: 1}}}, "!error"], + [{flag: false, items: [{price: -25, qty: -1, tag: "b"}], b: 0.1, a: 0.1}, "!error"], + [{flag: false, items: [{price: 3, qty: 1, tag: "b"}, {price: 99, qty: 10, tag: "gold"}, {price: 19.99, qty: 18, tag: "a"}, {price: -11, qty: 1000000000000000000000, tag: "silver"}], b: 120, a: 100}, "!error"], + [{items: [{price: 50, qty: 1, tag: "zz"}, {price: 18, qty: 21, tag: "a"}], b: 100, a: 21}, "!error"], + [{flag: true, items: [{price: 50, qty: 18, tag: "x"}, {price: 0, qty: 0, tag: "gold "}, {price: 7, qty: null, tag: "gold"}, {price: 99, qty: -25, tag: "gold"}], b: 3, a: -25}, "!error"], + [{flag: true, items: [{price: 101, qty: -1}, {price: 3, qty: 0.5, tag: null}], b: 1, a: 50}, "!error"], + [{flag: true, items: [{price: 7, qty: -1, tag: "b"}, {price: 100, qty: 0.1, tag: "Gold"}, {price: 0.1, qty: 101, tag: "zz"}, {price: 1000000000000000000000, qty: 1000, tag: ""}], b: 5, extra: 1}, "!error"], + [{flag: true, items: [{price: null, qty: 0.5, tag: "gold"}, {price: 21, qty: 5, tag: "silver"}, {price: 2.5, tag: "zz"}, {price: 1000, qty: 1000, tag: "gold"}], a: -13, extra: {deep: {x: 1}}}, "!error"], + [{flag: true, items: [{price: 0.1, qty: 21, tag: "gold"}, {price: 1000, qty: 111, tag: null}], b: 50, a: 3}, "!error"], + [{flag: false, items: [{price: 11, qty: 50, tag: "gold"}, {price: -0.1, qty: -1, tag: "gold "}], a: 0}, "!error"], + ], +} + +{ + name: "gb057: 8 nodes, table, expr, switch, table*, switch, expr, expr, table*", + graph: { + nodes: [ + {table: "t1", inputs: ["((score))"], outputs: ["k798", "k799"], passThrough: true, outputPath: "out", rules: [ + ["< 0", "'gold'", "0.25"], + ["21, 31", "'gold'", "0"], + [">= 21", "'mid'", "100"], + ["", "'A-1'", "-5"], + ["", "trim('x') + ' ' + 'none' + '-' + 'A-1' + ':' + string((10) / 4)", "((score ?? 0)) - (n ?? 1)"], + ["", "string(false)", "(b ?? n ?? 0)"], + ["", "'gold'", "b"], + ]}, + {expression: "e2", fields: { + k800: "-(min([(b ?? n ?? 0), (n ?? 1) * n]))", + }}, + {switch: "s3", when: ["(b ?? -1) - 2.25 + (score ?? 1) < -4 + ((n ?? 0))", "-4 != (((b ?? -1)) / 10)", "(b ?? 1) > b"]}, + {table: "t4", hit: "collect", inputs: ["2 + (score ?? -1)", "'gold'", "((b ?? 0) <= (score ?? 0) ? 'gold' : 'x' + ' ' + 'none')"], outputs: ["k801", "g.k802"], passThrough: true, rules: [ + ["10", "not('silver')", "'a'", "false", "false"], + ["$ > 18 and $ < 28", "not('gold')", "null", "false", "startsWith(string(((b ?? 0))), 'g')"], + ["<= 105", "'a'", "$ != 'x'", "false", "false"], + ]}, + {switch: "s5", when: ["true"]}, + {expression: "e6", outputPath: "lines", fields: { + "m.k803": "((n ?? 1) + (score ?? 1) + (1))", + k804: "'gold'", + k805: "(false ? (endsWith('x', 'a') ? 2 : (n) / 0.5) : score)", + }}, + {expression: "e7", passThrough: true, fields: { + k806: "-((n ?? 0))", + }}, + {table: "t8", hit: "collect", inputs: ["b"], outputs: ["k807", "k808"], outputPath: "o.p", rules: [ + ["", "true", "(n ?? b ?? 0) - (n ?? 1)"], + ["<= 23", "true", "2"], + ["(1..6)", "false", "10"], + ["0", "true", "((score ?? 0)) * 3 % 7 * (b ?? b ?? 0)"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "input -> s3", + "s3:2 -> t4", + "s3:2 -> s5", + "s3:2 -> e6", + "s3:2 -> e7", + "s5:0 -> t8", + "e2 -> output", + "s3:0 -> output", + "s3:1 -> output", + "t4 -> output", + "e6 -> output", + "e7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{score: 0, n: 100, b: 1}, {b: 1, k800: -1, n: 100, score: 0}], + [{score: 1000000000000000000000, n: 100, b: 99}, {b: 99, k800: -99, n: 100, score: 1000000000000000000000}], + [{score: null, n: 7, b: 1000}, {b: 1000, k800: -49, n: 7}], + [{score: -25, n: 0.5, b: 11}, {b: 11, k800: -0.25, n: 0.5, score: -25}], + [{score: 101, n: 0, b: -25}, {b: -25, k800: 25, n: 0, score: 101}], + [{n: 1, b: 99}, {b: 99, k800: -1, n: 1}], + [{score: 96, n: -0.1, b: 2}, {b: 2, k800: -0.01, n: -0.1, score: 96}], + [{score: 1000, n: 5, b: null}, {k800: -5, n: 5, score: 1000}], + [{score: 101, n: 5, b: 0, extra: 1}, {b: 0, extra: 1, k800: -0, n: 5, score: 101}], + [{score: 11, n: 1000, b: 0.1, extra: [1, 2]}, {b: 0.1, extra: [1, 2], k800: -0.1, n: 1000, score: 11}], + [{score: 19.99, n: -0.1, b: 10}, {b: 10, k800: -0.01, n: -0.1, score: 19.99}], + [{score: 18, n: 10, b: 99}, {b: 99, k800: -99, n: 10, score: 18}], + [{score: 2, n: 90, b: 19.99}, {b: 19.99, k800: -19.99, n: 90, score: 2}], + [{score: 100, n: 100, b: 1}, {b: 1, k800: -1, n: 100, score: 100}], + [{score: -7, n: 7}, {k800: -7, n: 7, score: -7}], + [{score: null, n: 0.5, b: 5}, {b: 5, k800: -0.25, n: 0.5}], + [{score: 2, n: 50, b: 21}, {b: 21, k800: -21, n: 50, score: 2}], + [{score: -25, b: null}, "!error"], + [{score: 5, n: 3, b: -25, extra: [1, 2]}, {b: -25, extra: [1, 2], k800: 25, n: 3, score: 5}], + [{score: 0, n: 100, b: 7}, {b: 7, k800: -7, n: 100, score: 0}], + [{score: 0, n: 1000, b: 1}, {b: 1, k800: -1, n: 1000, score: 0}], + [{n: -1, b: -0.1}, {b: -0.1, k800: 0.1, n: -1}], + [{score: 0, n: null}, "!error"], + ], +} + +{ + name: "gb058: 7 nodes, switch*, switch, table*, switch*, expr, expr, expr", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["floor((price)) == -((price ?? 1) + n)", "startsWith(`v${(price ?? -1)}-${''}`, '')", "vip"]}, + {switch: "s2", when: ["true", "n == null", ""]}, + {table: "t3", hit: "collect", inputs: ["n", "n", "n"], outputs: ["k809", "k810"], outputPath: "lines", rules: [ + ["$ > 10 and $ < 20", "50, 55", ">= 5", "'gold'", "-5"], + ["$ > 10 and $ < 20", "not(1)", "< 100", "'low'", "100"], + [">= 18", "10, 11", "(10..15)", "'gold'", "0"], + ["> 0", "null", "null", "'gold'", "(price ?? -1)"], + [">= 18", "0", "<= 6", "'gold'", "(n ?? price ?? 0)"], + ["10", "[5..10)", "< 5", "'gold'", "(n ?? -1)"], + ["", "", "", "'low'", "0"], + ]}, + {switch: "s4", hit: "collect", when: ["(n ?? 1) in [-5..5]", ""]}, + {expression: "e5", passThrough: true, fields: { + k811: "0.5", + "res.k812": "2.25 * (-(($.k811 ?? 1)))", + k813: "null", + }}, + {expression: "e6", outputPath: "res", fields: { + k814: "res.k812 ?? res.k812", + k815: "k811", + k816: "k811 ?? k811", + "res.k817": "res.k812 ?? k811", + }}, + {expression: "e7", passThrough: true, outputPath: "res", fields: { + k818: "tier ?? tier", + }}, + ], + edges: [ + "input -> s1", + "s1:0 -> s2", + "s2:1 -> t3", + "s2:1 -> s4", + "t3 -> e5", + "e5 -> e6", + "s2:2 -> e7", + "s1:1 -> output", + "s1:2 -> output", + "s2:0 -> output", + "s4:0 -> output", + "s4:1 -> output", + "e6 -> output", + "e7 -> output", + ], + }, + cases: [ + [{tier: "", n: 3, vip: true, price: 10}, {n: 3, price: 10, tier: "", vip: true}], + [{tier: "gold", vip: null, price: 21, extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, price: 21, tier: "gold"}], + [{tier: "b", n: 0.5, vip: true, price: 10}, {n: 0.5, price: 10, tier: "b", vip: true}], + [{tier: "gold ", n: 101, vip: true, price: 7}, {n: 101, price: 7, tier: "gold ", vip: true}], + [{tier: "", n: 10, vip: false, price: 1000000000000000000000}, {n: 10, price: 1000000000000000000000, tier: "", vip: false}], + [{tier: "", n: 18, vip: true, price: 1}, {n: 18, price: 1, tier: "", vip: true}], + [{tier: "x", n: 3, vip: false, price: 19.99}, {n: 3, price: 19.99, tier: "x", vip: false}], + [{tier: "gold", n: 0, price: 1000000000000000000000, extra: "e"}, {extra: "e", n: 0, price: 1000000000000000000000, tier: "gold"}], + [{tier: "", n: 10, vip: true, price: 18, extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, n: 10, price: 18, tier: "", vip: true}], + [{tier: "b", n: 19.99, vip: true, price: 5}, {n: 19.99, price: 5, tier: "b", vip: true}], + [{tier: null, n: -25, vip: false, price: 1}, {n: -25, price: 1, vip: false}], + [{tier: "silver", n: 1000000000000000000000, vip: true, price: 18}, {n: 1000000000000000000000, price: 18, tier: "silver", vip: true}], + [{tier: "b", n: 2.5, vip: false, price: 0}, {n: 2.5, price: 0, tier: "b", vip: false}], + [{tier: "gold ", n: 3, vip: true}, {n: 3, tier: "gold ", vip: true}], + [{tier: null, n: 1, vip: false, price: -1}, {n: 1, price: -1, vip: false}], + [{n: 99, vip: false, price: -1}, {n: 99, price: -1, vip: false}], + [{tier: "a", n: 0.1, vip: true, price: 99}, {n: 0.1, price: 99, tier: "a", vip: true}], + [{tier: "silver", n: 101, vip: true, price: 99}, {n: 101, price: 99, tier: "silver", vip: true}], + [{tier: "gold ", n: null, price: null, extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, tier: "gold "}], + [{tier: "zz", n: 51, vip: true, price: -0.1, extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, n: 51, price: -0.1, tier: "zz", vip: true}], + [{tier: "Gold", n: null, vip: true, price: 99}, {price: 99, tier: "Gold", vip: true}], + [{tier: "gold", n: 10, vip: true, price: 10}, {n: 10, price: 10, tier: "gold", vip: true}], + [{tier: "zz", n: 0.1, vip: false, price: 7}, {n: 0.1, price: 7, tier: "zz", vip: false}], + [{tier: null, n: null, vip: false, price: 1}, {price: 1, vip: false}], + [{tier: "gold", n: 11, vip: true}, {n: 11, tier: "gold", vip: true}], + [{tier: "", n: -1, vip: true, price: 99}, {n: -1, price: 99, tier: "", vip: true}], + [{tier: "a", n: 19.99, vip: false, price: 100}, {n: 19.99, price: 100, tier: "a", vip: false}], + [{tier: "bronze", n: 100, vip: null}, {n: 100, tier: "bronze"}], + [{tier: "x", n: 1, vip: false, price: 21}, {n: 1, price: 21, tier: "x", vip: false}], + ], +} + +{ + name: "gb059: 6 nodes, expr, table*, expr, loop expr, table*, loop expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + "g.k819": "b ?? flag", + k820: "b + min([b * 2, b])", + k821: "(flag != null ? 'A-1' : 'gold')", + k822: "(flag == null ? (($.k820 ?? b ?? 0)) / 3 : $.k820 + 10 + (b ?? 1) % 7)", + }}, + {table: "t2", hit: "collect", inputs: ["b", null], outputs: ["res.k823"], outputPath: "o.p", rules: [ + ["0", "", "0"], + ["$ > 18 and $ < 28", "$ != null", "100"], + ["", "$ != null", "0"], + [">= -1", "5", "(true ? ((b ?? -1)) : count(items ?? [], (#.qty ?? 0) > 1)) + ((b ?? 1)) / 10 + 1 % 3"], + ["<= 11", "true", "ceil(len((false ? 'x' : 'A-1')))"], + ["", "$ != null", "100"], + ]}, + {expression: "e3", passThrough: true, fields: { + k824: "'gold'", + }}, + {expression: "e4", inputField: "items", executionMode: "loop", outputPath: "o.p", fields: { + "m.k825": "string((qty ?? qty ?? 0) % 2)", + }}, + {table: "t5", hit: "collect", inputs: ["100", "(0 ?? 1 ?? 0)", "0.5 % 3"], outputs: ["k826", "k827"], outputPath: "res", rules: [ + ["", "18", "", "0", "''"], + ["$ > 1 and $ < 2", "not(21)", "not(10)", "100", "''"], + ["[1..6)", "[10..60]", "> -1", "1", "upper('A-1' + '' + `${2.25}-${'gold'}`)"], + ["[18..28)", "", "< -1", "10", "'gold'"], + ["> -1", "(-1..9)", "21, 31", "(0 ?? 1 ?? 0)", "''"], + ["<= 68", "", "$ > 1 and $ < 11", "2", "'x'"], + ["", "", "", "2", "'gold'"], + ]}, + {expression: "e6", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k828: "true", + }}, + ], + edges: [ + "input -> e1", + "input -> t2", + "t2 -> e3", + "input -> e3", + "e3 -> e4", + "t2 -> t5", + "e3 -> e6", + "e1 -> output", + "e4 -> output", + "t5 -> output", + "e6 -> output", + ], + }, + cases: [ + [{items: [{price: -25, qty: 7, tag: "gold"}, {price: 11, qty: 0, tag: "Gold"}], b: 5, flag: true, extra: {deep: {x: 1}}}, {b: 5, extra: {deep: {x: 1}}, flag: true, g: {k819: 5}, items: [{price: -25, qty: 7, tag: "gold"}, {price: 11, qty: 0, tag: "Gold"}], k820: 10, k821: "A-1", k822: 25, o: {p: [{m: {k825: "1"}}, {m: {k825: "0"}}]}, res: [{k826: 2, k827: "gold"}]}], + [{items: [{price: 100, qty: 100, tag: "b"}, {price: 1000000000000000000000, qty: 11, tag: "gold"}, {price: 2.5, qty: 3, tag: "b"}, {price: 5, qty: 19.99, tag: "bronze"}], b: null, flag: true}, "!error"], + [{items: [{qty: 7, tag: "silver"}], b: true, flag: true}, "!error"], + [{items: [{price: -0.1, qty: 0.1, tag: "Gold"}, {price: "5", qty: {v: 1}, tag: "x"}], b: true, flag: false, extra: [1, 2]}, "!error"], + [{items: [], b: 3, flag: false}, {b: 3, flag: false, g: {k819: 3}, items: [], k820: 6, k821: "A-1", k822: 19, o: {p: []}, res: [{k826: 2, k827: "gold"}]}], + [{items: [], b: null, flag: false}, "!error"], + [{items: "items", b: 2, flag: true}, "!error"], + [{items: [{price: null, qty: 99, tag: "bronze"}, {price: 1000000000000000000000, qty: 2.5, tag: "a"}, {price: -1, qty: null, tag: "zz"}, {price: 1000000000000000000000, qty: 99, tag: "b"}], b: "5"}, "!error"], + [{items: [], b: 100, flag: false}, {b: 100, flag: false, g: {k819: 100}, items: [], k820: 200, k821: "A-1", k822: 212, o: {p: []}, res: [{k826: 2, k827: "gold"}]}], + [{items: {price: 1}, b: {v: 1}, flag: null, extra: "e"}, "!error"], + [{items: [], b: 1000, flag: "no"}, {b: 1000, flag: "no", g: {k819: 1000}, items: [], k820: 2000, k821: "A-1", k822: 2016, o: {p: []}, res: [{k826: 2, k827: "gold"}]}], + [{items: [], b: -1, flag: false}, {b: -1, flag: false, g: {k819: -1}, items: [], k820: -3, k821: "A-1", k822: 6, o: {p: []}, res: [{k826: 2, k827: "gold"}]}], + [{items: [{price: 11, qty: 21, tag: "zz"}, {price: 2.5, qty: 19.99, tag: "zz"}], b: 2.5, extra: {deep: {x: 1}}}, {b: 2.5, extra: {deep: {x: 1}}, g: {k819: 2.5}, items: [{price: 11, qty: 21, tag: "zz"}, {price: 2.5, qty: 19.99, tag: "zz"}], k820: 5.0, k821: "gold", k822: 1.6666666666666666666666666667, o: {p: [{m: {k825: "1"}}, {m: {k825: "1.99"}}]}, res: [{k826: 2, k827: "gold"}]}], + [{items: [], b: -1, flag: true}, {b: -1, flag: true, g: {k819: -1}, items: [], k820: -3, k821: "A-1", k822: 6, o: {p: []}, res: [{k826: 2, k827: "gold"}]}], + [{items: {price: 1}, b: 3, flag: null}, "!error"], + [{items: [{price: 21, qty: {v: 1}}, {price: 21, qty: 1, tag: "zz"}, {price: 1000000000000000000000, qty: 99, tag: ""}, {price: 101, qty: 101, tag: null}], b: 99, flag: null, extra: {deep: {x: 1}}}, "!error"], + [{items: [{price: 0, qty: 3, tag: "a"}, {price: -1, qty: 69, tag: {t: "x"}}], b: "5", flag: true}, "!error"], + [{items: [], b: 2, flag: null}, {b: 2, g: {k819: 2}, items: [], k820: 4, k821: "gold", k822: 1.3333333333333333333333333333, o: {p: []}, res: [{k826: 2, k827: "gold"}]}], + [{items: [{price: 18, qty: 68}, {price: -1, qty: 0.5, tag: "x"}], b: 2.5, flag: false}, {b: 2.5, flag: false, g: {k819: 2.5}, items: [{price: 18, qty: 68}, {price: -1, qty: 0.5, tag: "x"}], k820: 5.0, k821: "A-1", k822: 17.5, o: {p: [{m: {k825: "0"}}, {m: {k825: "0.5"}}]}, res: [{k826: 2, k827: "gold"}]}], + [{items: [{price: 0.1, qty: -1, tag: "gold "}, {price: -0.1, qty: 50, tag: "b"}, {price: 109, qty: 2.5, tag: "gold"}, {price: null, qty: 3, tag: "gold"}], b: null, flag: true}, "!error"], + [{items: [{price: 10, qty: 5, tag: "gold "}, {price: 19.99, qty: 3, tag: "bronze"}], b: 99, flag: true}, {b: 99, flag: true, g: {k819: 99}, items: [{price: 10, qty: 5, tag: "gold "}, {price: 19.99, qty: 3, tag: "bronze"}], k820: 198, k821: "A-1", k822: 209, o: {p: [{m: {k825: "1"}}, {m: {k825: "1"}}]}, res: [{k826: 2, k827: "gold"}]}], + [{items: [{price: 11, qty: 2, tag: "x"}, {price: "5", qty: 0, tag: "Gold"}], flag: false}, "!error"], + [{items: [{price: 99, qty: 3, tag: "gold "}, {price: 2, qty: 101, tag: "gold "}], b: -1, flag: null}, {b: -1, g: {k819: -1}, items: [{price: 99, qty: 3, tag: "gold "}, {price: 2, qty: 101, tag: "gold "}], k820: -3, k821: "gold", k822: -1, o: {p: [{m: {k825: "1"}}, {m: {k825: "1"}}]}, res: [{k826: 2, k827: "gold"}]}], + [{items: [{price: -0.1, qty: -0.1, tag: "bronze"}], b: null}, "!error"], + ], +} + +{ + name: "gb060: 9 nodes, expr, expr, expr, switch*, table*, switch, table, switch, expr", + graph: { + nodes: [ + {expression: "e1", fields: { + "m.k829": "(n ?? n ?? 0) in [0..10]", + k831: "(ceil((price ?? 1))) / 2", + }}, + {expression: "e2", outputPath: "lines", fields: { + "m.k832": "((k831 ?? 1)) / 2", + "m.k829": "k831", + k834: "((100))", + "res.k835": "(0)", + }}, + {expression: "e3", fields: { + k836: "len(lower('x'))", + }}, + {switch: "s4", hit: "collect", when: ["(k836 ?? 1) == k836", ""]}, + {table: "t5", hit: "collect", inputs: ["k831"], outputs: ["m.k829"], outputPath: "res", rules: [ + ["< 1", "1"], + ["not(0)", "100"], + ["$ > -1 and $ < 49", "10"], + ["not(0)", "0.25"], + ]}, + {switch: "s6", when: ["true", "((k836 ?? 1) == (k836 ?? k836 ?? 0)) and (true)", ""]}, + {table: "t7", inputs: ["k836 - (k836 ?? 0) % 2", "k836", "trim('gold' + '' + '')"], outputs: ["k838"], passThrough: true, outputPath: "res", rules: [ + ["$ > 1 and $ < 6", "(5..55)", "'', 'b'", "`n=${(k836 ?? -1)}-${'A-1'}`"], + ["", "50, 100", "", "'gold'"], + ["$ > 100 and $ < 110", "[1..51)", "'gold'", "'mid'"], + ["$ > 0 and $ < 50", "<= 150", "not('gold')", "'none'"], + ]}, + {switch: "s8", when: ["a != null", "string((k836 ?? 1) != (k836 ?? 1)) != 'silver'", ""]}, + {expression: "e9", fields: { + k839: "floor(k836 + 1) == ((true ? 1 : 2.25)) / 0.5", + k840: "upper(string(max([(k836 ?? -1), (k836 ?? 1)])))", + k841: "'gold'", + "res.k835": "k836 ?? k836", + }}, + ], + edges: [ + "input -> e1", + "e1 -> e2", + "e2 -> e3", + "input -> e3", + "e3 -> s4", + "e1 -> t5", + "s4:0 -> s6", + "t5 -> s6", + "t5 -> t7", + "s6:2 -> t7", + "s6:0 -> s8", + "s8:1 -> e9", + "t7 -> output", + "s8:2 -> output", + "e9 -> output", + ], + }, + cases: [ + [{code: "b", items: [], flag: false, cust: {age: 50, tier: "zz", active: true}, price: 7, n: {v: 1}, score: 2}, "!error"], + [{code: {t: "x"}, items: [], flag: true, cust: {age: 1000, tier: "a", active: true}, price: 3, n: null, score: true}, {k839: true, k840: "1", k841: "gold", res: {k835: 1}}], + [{code: "silver", items: [], flag: true, cust: [{age: 3}], price: 1, n: 99, score: 2.5, extra: "e"}, {k839: true, k840: "1", k841: "gold", res: {k835: 1}}], + [{code: "a", items: [], flag: false, cust: {age: 1, tier: null, active: true}, price: 2.5, n: 0, score: null}, {k839: true, k840: "1", k841: "gold", res: {k835: 1}}], + [{code: "Gold", items: [{price: -0.1, qty: 3, tag: "Gold"}, {price: 5, qty: "5", tag: "x"}, {price: 21, tag: true}], cust: {age: 114, tier: "gold", active: true}, n: {v: 1}, score: -25}, "!error"], + [{code: "bronze", items: [{price: 0.1, qty: -2, tag: null}, {price: null, qty: 100, tag: "b"}], cust: {age: 99, tier: "b", active: false}, n: 99, score: 2.5}, {k839: true, k840: "1", k841: "gold", res: {k835: 1}}], + [{code: "zz", items: [{price: 3, tag: "silver"}], flag: true, cust: {age: 21, tier: "Gold", active: false}, price: null, n: -1, score: null}, {k839: true, k840: "1", k841: "gold", res: {k835: 1}}], + [{code: "x", items: [{price: 15, qty: 1000000000000000000000, tag: null}, {price: 1, qty: "abc", tag: "b"}], flag: true, price: 5, n: [1], score: null}, "!error"], + [{code: "silver", items: [{price: 0, qty: 1000000000000000000000, tag: "gold "}], flag: true, cust: {age: 11, tier: true, active: false}, price: 1000000000000000000000, n: 0.1, score: 21}, {k839: true, k840: "1", k841: "gold", res: {k835: 1}}], + [{code: "bronze", items: [{price: null, qty: 18, tag: "b"}, {price: 99, qty: 99, tag: ["gold"]}], flag: true, cust: {age: 5, tier: "bronze", active: null}, price: -1, score: 99}, {k839: true, k840: "1", k841: "gold", res: {k835: 1}}], + [{code: "x", items: [], flag: true, cust: {age: 1000000000000000000000, tier: "", active: false}, price: 21, n: 0.1, score: 101}, {k839: true, k840: "1", k841: "gold", res: {k835: 1}}], + [{code: "zz", items: [{price: -1, qty: 11, tag: "Gold"}, {price: true, qty: 50, tag: "b"}, {price: null, qty: 101, tag: ""}, {price: -1, qty: 21, tag: "gold "}], flag: true, cust: {age: 5, tier: "", active: false}, price: 0.1, n: "5", score: null}, "!error"], + ], +} + +{ + name: "gb061: 8 nodes, table*, expr, expr, table, expr, table*, loop expr, table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["code"], outputs: ["g.k843", "k844"], outputPath: "lines", rules: [ + ["not('a')", "'gold'", "false"], + ["'gold'", "'mid'", "false"], + ["'x', 'gold'", "'mid'", "false"], + ["", "'high'", "true"], + ]}, + {expression: "e2", fields: { + k845: "abs(round(1 * -4))", + k846: "$nodes.t1.g.k843", + "g.k847": "null", + }}, + {expression: "e3", passThrough: true, fields: { + k848: "(0.5 + -4 + k845)", + "res.k849": "k845 ?? k845", + "res.k850": "len(k846)", + k851: "$.k848 ?? k846", + }}, + {table: "t4", inputs: ["code", "n", "n"], outputs: ["k852"], outputPath: "o.p", rules: [ + ["null", "not(0)", "[50..100)", "10"], + ["'a', 'gold'", "< 10", "[0..50)", "100"], + ["'', 'gold'", "null", "> 5", "(max([(n ?? 1), -4]) + floor((n ?? 1)))"], + ["not('gold')", "", "not(18)", "1"], + ["", "", "", "2"], + ]}, + {expression: "e5", fields: { + k853: "abs((not (false) ? -4 : (10) / 2))", + "m.k854": "string(((k846 ?? 'none') == 'silver') and (res.k850 >= ($.k853 ?? 1)))", + k855: "k845 ?? res.k850", + }}, + {table: "t6", hit: "collect", inputs: ["res.k850"], outputs: ["res.k850", "g.k857"], outputPath: "lines", rules: [ + ["<= 19", "true", "2"], + ["", "false", "len((k846 ?? 'none') + ':' + (k846 ?? ''))"], + ["> 50", "false", "1"], + ["not(1)", "true", "-(-4)"], + ["null", "endsWith((k846 ?? ''), '')", "0.25"], + ["", "false", "0.25"], + ]}, + {expression: "e7", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + "m.k858": "abs(((2.25)))", + k859: "abs(qty + 1) == ((true) or (true) ? (qty) : min([(qty ?? 0), price]))", + }}, + {table: "t8", inputs: ["abs(o.p.k852)"], outputs: ["m.k858", "k861"], rules: [ + ["!= 1", "'low'", "'mid'"], + ["null", "''", "'gold'"], + ["[21..26]", "`n=${(o.p.k852 ?? 0)}-${'none'}`", "'high'"], + ["[100..105]", "'gold'", "trim('A-1')"], + ["", "'mid'", "'high'"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "e2 -> e3", + "input -> t4", + "e3 -> e5", + "e2 -> t6", + "e3 -> t6", + "input -> e7", + "t4 -> t8", + "e5 -> output", + "t6 -> output", + "e7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{n: 21, nums: [89], tier: "bronze", items: []}, "!error"], + [{n: 18, nums: [1], code: "gold ", tier: "gold", items: [{price: 5, qty: 2.5, tag: "gold "}, {price: 18, qty: 101, tag: "zz"}]}, "!error"], + [{n: 0, nums: [18, -25, 11], tier: "x", items: [{price: -1, qty: 21, tag: "a"}, {price: -1, qty: 2, tag: "a"}]}, "!error"], + [{n: 1000, code: null, tier: "gold ", items: [{price: 88, qty: 0.5, tag: "b"}]}, "!error"], + [{n: 50, nums: [18, 2.5], code: "a", tier: "", items: []}, "!error"], + [{n: 3, nums: [], code: "a", items: [{price: -25, qty: 1000000000000000000000, tag: "zz"}, {price: 50, qty: -11, tag: "x"}]}, "!error"], + [{n: 101, nums: null, code: "x", tier: "x", items: [{price: 41, tag: "b"}, {price: 1, qty: 1000, tag: "zz"}, {price: 99, qty: 7, tag: "b"}, {price: 18, qty: 0.1, tag: "bronze"}]}, "!error"], + [{n: 0.5, code: "gold", tier: "gold", items: [{price: "abc", qty: 1, tag: "Gold"}, {price: {v: 1}, qty: 21, tag: "Gold"}]}, "!error"], + [{n: -1, nums: [18, 1000, 5], code: "silver", tier: "gold ", items: [{price: 7, qty: 7, tag: "Gold"}]}, "!error"], + [{n: 1000, nums: [-1, 1000, 100], code: "Gold", tier: "Gold", items: [{price: -25, qty: 2, tag: "Gold"}, {price: -1, qty: 1, tag: "zz"}]}, "!error"], + [{n: 0, nums: [10, -25, 0.5], code: true, tier: 5, items: [{price: 50, qty: 1000000000000000000000, tag: "gold "}, {price: 7, qty: 1}, {price: 49, qty: 1000000000000000000000, tag: "a"}]}, "!error"], + [{n: 2.5, nums: [11, 18], code: 5, tier: "gold ", items: [{price: 7, qty: 10, tag: "bronze"}, {price: 21, qty: 100, tag: null}]}, "!error"], + [{n: 1, nums: [7, 10], code: "gold ", tier: "zz"}, "!error"], + [{n: 5, nums: 7, code: "bronze", items: [{price: -0.1, qty: 2.5, tag: "Gold"}, {price: [1], qty: 0.5, tag: "Gold"}, {price: 73, qty: 1000000000000000000000, tag: "zz"}]}, "!error"], + [{n: "5", nums: [-1], code: "silver", tier: "zz", items: [{price: 99, qty: 18}, {price: 100, qty: 50, tag: "silver"}], extra: {deep: {x: 1}}}, "!error"], + [{n: 100, nums: [1000000000000000000000], code: "bronze", tier: "zz", items: [{price: 10, qty: -0.1, tag: "Gold"}, {price: null, qty: -0.1, tag: "gold "}, {price: 5, qty: 10, tag: "x"}]}, "!error"], + ], +} + +{ + name: "gb062: 7 nodes, expr, table*, expr, switch, switch, loop expr, expr", + graph: { + nodes: [ + {expression: "e1", outputPath: "lines", fields: { + k862: "score + sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0)))", + k863: "flag ?? flag", + }}, + {table: "t2", hit: "collect", inputs: ["abs(lines.k862)", "lines.k862"], outputs: ["k864[]"], outputPath: "res", rules: [ + ["[100..105)", "<= 55", "'low'"], + ["not(50)", "$ > 50 and $ < 51", "'high'"], + ["", "", "string(('x' == 'silver'))"], + ]}, + {expression: "e3", outputPath: "res", fields: { + "res.k865": "count(items ?? [], (#.qty ?? 0) > 1) - len('A-1') % 7", + k866: "len(items ?? [])", + }}, + {switch: "s4", when: ["(10 >= score * score)", "-((score ?? score ?? 0)) > ceil(1)", "1 == 3", ""]}, + {switch: "s5", when: ["('none' != 'gold' ? `${score}-${'x'}` : (flag ? 'none' : cust.tier)) != 'gold'", "score <= -4 * score", ""]}, + {expression: "e6", inputField: "items", executionMode: "loop", outputPath: "o.p", fields: { + k867: "`v${(price ?? -1)}-${tag}`", + }}, + {expression: "e7", passThrough: true, fields: { + k868: "string(len(((flag ?? false) ? 'A-1' : 'x')))", + k869: "(($.k868 ?? 'none') in ['gold', 'silver', 'a'] ? ((flag ?? false) ? ($.k868 ?? 'none') : 'none') : string((score ?? 0) * (score ?? 1)))", + "m.k870": "min([score, (score ?? 0)]) % 2", + }}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "input -> e3", + "input -> s4", + "t2 -> s4", + "s4:3 -> s5", + "input -> e6", + "s5:0 -> e6", + "s5:2 -> e7", + "e3 -> output", + "s4:1 -> output", + "s4:2 -> output", + "s5:1 -> output", + "e6 -> output", + "e7 -> output", + ], + }, + cases: [ + [{score: 50, items: [{price: 50, qty: 7, tag: "b"}, {price: -0.1, qty: 1000, tag: "zz"}], cust: {age: 3, tier: "a", active: false}, flag: false}, {o: {p: [{k867: "v50-b"}, {k867: "v-0.1-zz"}]}, res: {k866: 2, res: {k865: -1}}}], + [{score: 3, items: [{price: 0, qty: 0.5, tag: null}, {price: 2, qty: 101, tag: "gold"}, {price: -25, qty: 2.5, tag: "gold"}, {price: -1, qty: 5, tag: "b"}], cust: "cust", flag: false}, {o: {p: [{k867: "v0-null"}, {k867: "v2-gold"}, {k867: "v-25-gold"}, {k867: "v-1-b"}]}, res: {k866: 4, res: {k865: 0}}}], + [{score: "abc", items: [{price: -1, qty: 11, tag: "a"}, {price: 19.99, qty: 10, tag: null}, {price: 100, qty: 21, tag: "x"}], cust: [], flag: true, extra: 1}, "!error"], + [{score: 2.5, items: [{price: -0.1, qty: 0, tag: "x"}, {price: 2.5, qty: null, tag: null}, {price: 11, qty: 101, tag: "gold "}], cust: {age: -1, tier: "gold", active: null}, flag: true}, {o: {p: [{k867: "v-0.1-x"}, {k867: "v2.5-null"}, {k867: "v11-gold "}]}, res: {k866: 3, res: {k865: -2}}}], + [{score: 2.5, items: [{price: 10, qty: 100, tag: ""}, {price: 100, qty: 0.1, tag: {t: "x"}}], cust: {age: 101, tier: "x"}}, "!error"], + [{score: 0.1, items: [{price: 21, qty: 99, tag: "a"}, {price: -1, qty: [1], tag: "silver"}], cust: {age: 2.5, tier: "silver", active: true}}, "!error"], + [{score: 36, items: [], flag: false}, {o: {p: []}, res: {k866: 0, res: {k865: -3}}}], + [{score: -1, items: [{price: "abc", qty: 2.5, tag: "silver"}], cust: {age: 1000000000000000000000, tier: "b", active: null}, flag: 1}, "!error"], + [{score: 2, items: [{price: [1], qty: -0.1, tag: ""}], cust: [{age: 3}], flag: null}, "!error"], + [{score: 7, items: [], flag: true}, {o: {p: []}, res: {k866: 0, res: {k865: -3}}}], + [{score: "abc", items: [], cust: {age: 0.5, tier: "", active: true}, flag: true}, "!error"], + [{score: 0.1, items: [{price: 1000, qty: 2.5, tag: "gold"}], cust: {age: 0.5, tier: "a", active: true}, flag: false, extra: 1}, {o: {p: [{k867: "v1000-gold"}]}, res: {k866: 1, res: {k865: -2}}}], + [{score: null, items: [{price: 21, qty: 7, tag: "zz"}, {price: -25, qty: 99, tag: "b"}], cust: {age: -25, tier: "b", active: true}, flag: false}, "!error"], + [{score: 99, items: [{price: null, qty: -1, tag: "gold"}, {price: -25, qty: 19.99, tag: ""}], cust: {age: 29, active: false}, flag: 1}, {o: {p: [{k867: "v-1-gold"}, {k867: "v-25-"}]}, res: {k866: 2, res: {k865: -2}}}], + [{score: "5", items: [{price: 21, qty: 100, tag: "Gold"}], cust: {age: 1000, tier: "b", active: false}, flag: true}, "!error"], + [{score: "5", items: [{price: 1, qty: null, tag: "bronze"}], cust: null, flag: true}, "!error"], + [{score: 10, items: [{qty: 0.5, tag: "Gold"}, {price: 99, qty: 10, tag: "silver"}], cust: {age: 7, tier: "gold", active: true}}, {o: {p: [{k867: "v-1-Gold"}, {k867: "v99-silver"}]}, res: {k866: 2, res: {k865: -2}}}], + [{score: 0, items: [], cust: {age: 0.1, tier: "gold", active: false}, flag: "true", extra: "e"}, {o: {p: []}, res: {k866: 0, res: {k865: -3}}}], + [{score: 0.5, items: [], cust: {age: 1000000000000000000000, tier: "a", active: false}, flag: true}, {o: {p: []}, res: {k866: 0, res: {k865: -3}}}], + [{score: null, items: [{price: 1, qty: 19.99, tag: "Gold"}], cust: {age: true, tier: "gold ", active: false}, flag: true}, "!error"], + [{score: -0.1, items: [], cust: {age: 1000000000000000000000, tier: "", active: false}, flag: true, extra: {deep: {x: 1}}}, {o: {p: []}, res: {k866: 0, res: {k865: -3}}}], + [{score: 7, flag: true}, "!error"], + [{score: 2, items: [{price: -1, qty: 7, tag: "gold "}, {price: -25, qty: 11, tag: "zz"}], cust: null, flag: 0}, {o: {p: [{k867: "v-1-gold "}, {k867: "v-25-zz"}]}, res: {k866: 2, res: {k865: -1}}}], + [{score: 100, items: [{price: 0, qty: -25, tag: null}], cust: {age: 1, tier: "", active: false}, flag: true}, {o: {p: [{k867: "v0-null"}]}, res: {k866: 1, res: {k865: -3}}}], + [{score: 11, items: [{price: 3, qty: 18, tag: "b"}, {price: 3, qty: 10, tag: "silver"}], cust: {age: 5, tier: "a", active: 0}, flag: false}, {o: {p: [{k867: "v3-b"}, {k867: "v3-silver"}]}, res: {k866: 2, res: {k865: -1}}}], + [{score: 0.5, items: [{price: null, qty: 0.5, tag: "gold"}, {price: 5, qty: 10, tag: "bronze"}, {price: 99, qty: 10, tag: ["gold"]}, {price: 5, qty: 101, tag: "gold "}], cust: null, flag: null}, "!error"], + [{score: 11, items: [{price: 100, qty: 11, tag: "gold "}, {price: null, qty: 21, tag: "b"}], cust: {age: 50, tier: "zz", active: true}, flag: false, extra: [1, 2]}, {o: {p: [{k867: "v100-gold "}, {k867: "v-1-b"}]}, res: {k866: 2, res: {k865: -1}}}], + ], +} + +{ + name: "gb063: 6 nodes, switch, table, table, expr, switch*, expr", + graph: { + nodes: [ + {switch: "s1", when: ["true", ""]}, + {table: "t2", inputField: "cust", inputs: ["age", "tier"], outputs: ["g.k871"], rules: [ + ["10, 15", "", "false"], + ["", "startsWith($, 'g')", "true"], + ["> 18", "", "len((tier ?? '')) > (age ?? -1) + len((tier ?? ''))"], + ["50, 100", "null", "(age ?? 1) != (age == null ? -4 - (age ?? 0) : ((age ?? 1)) / 3)"], + ["", "null", "true"], + [">= 18", "not('gold')", "(active ?? false)"], + ["", "", "(active ?? false)"], + ]}, + {table: "t3", inputs: ["'none' + '' + (s ?? '') + ' ' + code + ':' + 'gold'", "ceil(score) - (score ?? 0) * (score ?? 0)", "lower((false ? s : (code ?? 'none')))"], outputs: ["k872", "g.k873"], passThrough: true, rules: [ + ["$ != 'x'", "[100..101)", "startsWith($, '')", "2", "true"], + ["'gold', 'bronze'", ">= 50", "$ != 'x'", "1", "false"], + ["", "!= 18", "null", "100", "(score ?? 0) > (score ?? 0)"], + ["null", "18, 68", "$ != 'gold'", "100", "true"], + ["null", "not(-1)", "", "2", "true"], + ["not('')", "[5..10)", "'', 'bronze'", "(score ?? -1)", "s == null"], + ]}, + {expression: "e4", fields: { + k874: "score ?? g.k871", + k875: "score ?? code", + k876: "((code ?? 'none') == '' ? string((score ?? 1)) + '-' + s : (score == (score ?? 1) ? string((g.k871 ?? false)) : (s ?? '?')))", + k877: "(not (score == (score ?? -1))) and (code != null)", + }}, + {switch: "s5", hit: "collect", when: ["cust.active", "true", "'A-1' in ['gold', 'silver', 'a']"]}, + {expression: "e6", passThrough: true, outputPath: "o.p", fields: { + "g.k878": "(k872 ?? 1)", + "res.k879": "-((score ?? 1))", + "m.k880": "(min([len(code), -4 * score]))", + }}, + ], + edges: [ + "input -> s1", + "s1:0 -> t2", + "input -> t2", + "input -> t3", + "s1:1 -> e4", + "t2 -> e4", + "s1:1 -> s5", + "t3 -> e6", + "t2 -> output", + "e4 -> output", + "s5:1 -> output", + "s5:2 -> output", + "e6 -> output", + ], + }, + cases: [ + [{score: null, cust: {age: null, tier: "gold", active: false}, s: "x", code: "Gold"}, "!error"], + [{score: 0.1, cust: {age: 3, tier: null, active: false}, s: "gold ", code: "Gold"}, {code: "Gold", cust: {active: false, age: 3, tier: null}, g: {k871: true}, k874: true, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -0.4}, res: {k879: -0.1}}}, s: "gold ", score: 0.1}], + [{score: -1, cust: {age: -25, tier: "gold", active: true}, s: "", code: true}, "!error"], + [{score: 5, cust: {age: -0.1, tier: "x", active: 0}, s: "Gold", code: "b"}, {code: "b", cust: {active: 0, age: -0.1, tier: "x"}, g: {k871: 0}, k874: 0, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -20}, res: {k879: -5}}}, s: "Gold", score: 5}], + [{score: 0.5, cust: {age: 1, tier: "bronze", active: true}, s: ["gold"], code: null}, "!error"], + [{score: null, cust: {age: 2, tier: "gold", active: true}, s: "b", code: "zz", extra: "e"}, "!error"], + [{score: 21, cust: {age: 11, tier: "b", active: false}, s: "silver", code: "silver"}, {code: "silver", cust: {active: false, age: 11, tier: "b"}, g: {k871: false}, k874: false, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -84}, res: {k879: -21}}}, s: "silver", score: 21}], + [{score: 11, cust: {age: 0, tier: "silver", active: true}, s: "bronze", code: "gold", extra: {deep: {x: 1}}}, {code: "gold", cust: {active: true, age: 0, tier: "silver"}, extra: {deep: {x: 1}}, g: {k871: true}, k874: true, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -44}, res: {k879: -11}}}, s: "bronze", score: 11}], + [{score: 100, cust: null, s: 5, code: "gold "}, {code: "gold ", g: {k871: true}, k874: true, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -400}, res: {k879: -100}}}, s: 5, score: 100}], + [{score: 1000, cust: {tier: "gold ", active: false}, s: "x"}, "!error"], + [{score: 2, s: "a", code: "zz"}, {code: "zz", g: {k871: true}, k874: true, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -8}, res: {k879: -2}}}, s: "a", score: 2}], + [{score: true, cust: {age: null, tier: true, active: true}, s: "a", code: null}, "!error"], + [{score: 11, cust: {tier: "silver", active: true}, s: "a", code: "silver"}, {code: "silver", cust: {active: true, tier: "silver"}, g: {k871: true}, k874: true, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -44}, res: {k879: -11}}}, s: "a", score: 11}], + [{score: 3, cust: {age: null, tier: "x", active: true}, s: true, code: "a"}, {code: "a", cust: {active: true, age: null, tier: "x"}, g: {k871: true}, k874: true, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -12}, res: {k879: -3}}}, s: true, score: 3}], + [{score: 0.1, cust: {age: 18, tier: "x", active: true}, s: "x", code: "x"}, {code: "x", cust: {active: true, age: 18, tier: "x"}, g: {k871: true}, k874: true, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -0.4}, res: {k879: -0.1}}}, s: "x", score: 0.1}], + [{score: 18, cust: {tier: "b", active: true}, s: "bronze", code: "gold "}, {code: "gold ", cust: {active: true, tier: "b"}, g: {k871: true}, k874: true, k876: "?", k877: false, o: {p: {g: {k878: 1}, m: {k880: -72}, res: {k879: -18}}}, s: "bronze", score: 18}], + [{score: 1000000000000000000000, cust: {age: 5, active: false}, s: "b", code: 5}, "!error"], + ], +} + +{ + name: "gb064: 12 nodes, expr, expr, switch, table, switch, loop table*, table*, table*, switch, loop table*, expr, expr", + graph: { + nodes: [ + {expression: "e1", passThrough: true, outputPath: "lines", fields: { + k881: "(((a ?? 1) > (a ?? -1)) and ((true) and (false)) ? string(((cust.active ?? false)) and (false)) : 'x')", + k883: "a > (a ?? 0) * 1 * abs((a ?? 0))", + }}, + {expression: "e2", passThrough: true, fields: { + k884: "true", + }}, + {switch: "s3", when: ["(a ?? 1) > a", "not (true)"]}, + {table: "t4", inputs: ["string(2 in [1..100])"], outputs: ["k881"], outputPath: "res", rules: [ + ["''", "0"], + ["'a'", "1"], + ["$ != 'a'", "(a ?? a ?? 0)"], + ["not('gold')", "-5"], + ["$ != 'gold'", "100"], + ]}, + {switch: "s5", when: ["len(lines.k881) * (a ?? 0) <= (a ?? 1) * (0.5)", ""]}, + {table: "t6", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["price", "tag", "price"], outputs: ["k886", "k887"], outputPath: "o.p", rules: [ + ["!= 100", "'gold'", "not(1)", "100", "floor(((qty ?? 1))) + (qty ?? -1)"], + ["< 10", "'a', 'b'", "(21..26)", "0.25", "0.25"], + ["!= 1", "", "not(21)", "-(len((tag ?? '') + ' ' + (tag ?? '')))", "len((tag ?? '')) + qty + floor((price ?? 1)) * -(2.25)"], + ["", "'silver'", "null", "10", "10"], + ["", "", "", "(ceil(0.5))", "100"], + ]}, + {table: "t7", hit: "collect", inputs: ["a"], outputs: ["k888[]", "m.k889"], outputPath: "res", rules: [ + ["!= 10", "false", "'high'"], + [">= 50", "(a ?? res.k881 ?? 0) + max([(a ?? 0), 0.5]) < 1", "''"], + ["[10..15)", "(lines.k883 ?? false)", "(((lines.k881 ?? 'none') == 'gold') ? lower((lines.k881 ?? 'none')) + ' ' + string((res.k881 ?? 0)) : ((lines.k883 ?? false) ? (lines.k881 ?? '') : lines.k881) + '-' + (lines.k881 ?? '?'))"], + ["< 100", "false", "''"], + ["[100..101]", "false", "'low'"], + ["[10..11]", "true", "lines.k881"], + ]}, + {table: "t8", hit: "collect", inputs: ["lines.k881", "lines.k881"], outputs: ["k890", "m.k891"], outputPath: "res", rules: [ + ["'gold', 'bronze'", "null", "false", "false"], + ["startsWith($, 'x')", "''", "(lines.k883 ?? false)", "false"], + ["startsWith($, 's')", "'a'", "false", "false"], + ["null", "", "false", "false"], + ["", "", "true", "false"], + ["null", "''", "(lines.k883 ?? false)", "false"], + ["", "", "lines.k883 == null", "true"], + ]}, + {switch: "s9", when: ["false", "false", ""]}, + {table: "t10", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["abs(-4 * (qty ?? 0))"], outputs: ["g.k892", "k893"], outputPath: "o.p", rules: [ + ["<= 2", "'low'", "0"], + ["0", "'low'", "100"], + ["", "'low'", "0"], + ]}, + {expression: "e11", fields: { + k894: "sum(map(items ?? [], #.price ?? 0)) - (a) * (a ?? -1) + (a ?? -1)", + "g.k895": "a ?? $.k894", + k896: "(a ?? a ?? 0)", + "g.k897": "(a ?? a ?? 0)", + }}, + {expression: "e12", passThrough: true, outputPath: "out", fields: { + k898: "res.k881 ?? res.k881", + k899: "(res.k881 ?? -1) % 7 == (res.k881 ?? res.k881 ?? 0) - (res.k881 ?? 1) + (res.k881 ?? 0)", + }}, + ], + edges: [ + "input -> e1", + "input -> e2", + "input -> s3", + "e1 -> s3", + "s3:0 -> t4", + "e1 -> t4", + "s3:1 -> s5", + "s3:0 -> t6", + "s3:1 -> t6", + "s3:0 -> t7", + "t4 -> t7", + "t6 -> t8", + "s5:0 -> t8", + "t8 -> s9", + "t8 -> t10", + "s3:0 -> t10", + "t10 -> e11", + "e2 -> e11", + "s9:1 -> e12", + "t4 -> e12", + "s5:1 -> output", + "t7 -> output", + "s9:0 -> output", + "e11 -> output", + "e12 -> output", + ], + }, + cases: [ + [{items: [], a: null, cust: {age: 0.1, tier: "gold", active: true}, extra: "e"}, "!error"], + [{items: [{price: 19.99, qty: 2, tag: "x"}, {price: 101, qty: 99, tag: "x"}], a: 10, cust: 5}, {g: {k895: 10, k897: 10}, k894: 30.99, k896: 10, out: {k898: 10, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [], a: 2, cust: {age: 0.1, tier: "bronze", active: true}}, {g: {k895: 2, k897: 2}, k894: -2, k896: 2, out: {k898: 2, k899: true}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 0, qty: null, tag: "bronze"}, {price: 5, qty: 21, tag: "x"}, {price: -25, qty: 99, tag: "a"}, {price: 19.99, qty: 50, tag: "gold"}], a: {v: 1}, cust: {age: 99, tier: "Gold", active: false}}, "!error"], + [{items: [{price: 2, qty: 10, tag: "b"}, {price: 7, qty: 50, tag: "silver"}], a: 21, cust: null}, {g: {k895: 21, k897: 21}, k894: -411, k896: 21, out: {k898: 21, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 83, qty: 2.5, tag: "b"}, {price: 0.5, qty: 50, tag: null}], a: null, cust: {age: 7, tier: {t: "x"}, active: true}}, "!error"], + [{items: [{price: 1000000000000000000000, qty: 2.5, tag: "zz"}, {price: 101, qty: 50, tag: "silver"}], a: [1], cust: {age: 60, tier: "x", active: false}}, "!error"], + [{items: [{price: 2.5}], a: 21, cust: {age: 2.5, tier: "a", active: false}}, {g: {k895: 21, k897: 21}, k894: -417.5, k896: 21, out: {k898: 21, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 100, qty: -0.1}, {qty: 101, tag: "gold "}, {price: 1000, qty: 50, tag: "b"}, {price: 1, qty: 101, tag: "b"}], a: null, cust: [{age: 3}]}, "!error"], + [{items: [], a: null, cust: {tier: null, active: true}, extra: [1, 2]}, "!error"], + [{items: [{price: 1000, qty: 1000, tag: "gold "}, {price: 0.1, qty: 7, tag: "bronze"}], a: -1, cust: {age: 21, tier: "", active: false}}, {g: {k895: -1, k897: -1}, k894: 998.1, k896: -1, out: {k898: -1, k899: true}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [], cust: {age: 1000, tier: null, active: true}}, "!error"], + [{items: [{price: 10, qty: 101, tag: "silver"}, {price: 0.5, qty: 99, tag: ""}], a: 11, cust: {age: -1, tier: "a", active: false}}, {g: {k895: 11, k897: 11}, k894: -99.5, k896: 11, out: {k898: 11, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 100, qty: 21, tag: "a"}], a: 100, cust: {age: null, tier: "x", active: null}}, {g: {k895: 100, k897: 100}, k894: -9800, k896: 100, out: {k898: 100, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 50, qty: 19.99, tag: "a"}, {price: 0.1, tag: "gold "}, {price: 11, qty: null, tag: "gold "}, {price: 0, qty: 11, tag: ""}], a: 0.5, cust: {age: 19.99, tier: "Gold", active: false}}, {g: {k895: 0.5, k897: 0.5}, k894: 61.35, k896: 0.5, out: {k898: 0.5, k899: true}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 101, qty: 99, tag: ""}, {price: 10, qty: 99}, {price: 19.99, qty: -25, tag: "bronze"}], a: 0, cust: {age: 1000000000000000000000, tier: "silver", active: false}}, {g: {k895: 0, k897: 0}, k894: 130.99, k896: 0, out: {k898: 0, k899: true}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 1, qty: 7, tag: "bronze"}, {price: 5, qty: 10, tag: "a"}, {price: 5, qty: 1000, tag: "zz"}], a: 1000}, {g: {k895: 1000, k897: 1000}, k894: -998989, k896: 1000, out: {k898: 1000, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 1000, qty: -25}], a: 18, cust: "cust"}, {g: {k895: 18, k897: 18}, k894: 694, k896: 18, out: {k898: 18, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 100, qty: -25, tag: "zz"}], a: 34, cust: 5}, {g: {k895: 34, k897: 34}, k894: -1022, k896: 34, out: {k898: 34, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{qty: null, tag: "Gold"}, {price: 10, qty: null, tag: "zz"}], a: true, cust: {age: 101, tier: "silver", active: true}}, "!error"], + [{items: [{tag: null}, {price: null, qty: 3, tag: true}, {qty: 5, tag: "gold"}], a: 63, cust: 5, extra: "e"}, {g: {k895: 63, k897: 63}, k894: -3906, k896: 63, out: {k898: 63, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{qty: 19.99, tag: "zz"}], a: null, cust: {age: 11, tier: "Gold", active: false}, extra: {deep: {x: 1}}}, "!error"], + [{items: [{price: 99, qty: -25, tag: "bronze"}, {price: 100, qty: 100, tag: "b"}, {price: null, qty: 0, tag: ""}], a: 100, cust: {age: 1000, tier: "gold "}}, {g: {k895: 100, k897: 100}, k894: -9701, k896: 100, out: {k898: 100, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: -0.1, qty: -1, tag: null}, {price: -1, qty: 38, tag: "bronze"}], cust: {age: 18, tier: ["gold"], active: false}}, "!error"], + [{items: [{price: 0.1, qty: 11, tag: "b"}, {price: 11, qty: true, tag: ""}, {price: 10, qty: [1], tag: null}, {price: 2, qty: "5", tag: "x"}], a: 21, cust: {age: -0.1, tier: "gold", active: 1}}, {g: {k895: 21, k897: 21}, k894: -396.9, k896: 21, out: {k898: 21, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 21, qty: 21, tag: "gold"}, {price: 19.99, qty: 11, tag: "silver"}, {price: 7, qty: 1000000000000000000000, tag: "b"}, {price: 0.1, qty: 19, tag: "zz"}], a: 1000, cust: {age: 11, tier: "bronze", active: false}}, {g: {k895: 1000, k897: 1000}, k894: -998951.91, k896: 1000, out: {k898: 1000, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 37, tag: "bronze"}], a: 19.99, cust: {age: 50, tier: "b", active: null}}, {g: {k895: 19.99, k897: 19.99}, k894: -342.6101, k896: 19.99, out: {k898: 19.99, k899: false}, res: [{k888: false, m: {k889: "high"}}]}], + [{items: [{price: 7, qty: 18, tag: "b"}, {price: -1, qty: [1], tag: true}, {price: 0.1, qty: null}, {price: 10, qty: 1, tag: "bronze"}], a: 2, cust: {age: 99, tier: "gold", active: true}}, {g: {k895: 2, k897: 2}, k894: 14.1, k896: 2, out: {k898: 2, k899: true}, res: [{k888: false, m: {k889: "high"}}]}], + ], +} + +{ + name: "gb065: 12 nodes, expr, expr, loop table, switch*, expr, loop table, expr, table, loop expr, table*, switch, loop table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + k900: "1 % 3", + k902: "len((true ? (s ?? 'none') : s))", + }}, + {expression: "e2", passThrough: true, outputPath: "o.p", fields: { + k903: "'gold'", + "m.k904": "0.5", + k902: "`v${3}-${'x'}`", + }}, + {table: "t3", inputField: "items", executionMode: "loop", inputs: ["qty % 3"], outputs: ["m.k907"], passThrough: true, outputPath: "o.p", rules: [ + ["[50..100)", "1"], + ["(1..6)", "(qty ?? -1)"], + ["not(0)", "-5"], + ["10", "1"], + ["50, 51", "1 % 2"], + ["", "0"], + ]}, + {switch: "s4", hit: "collect", when: ["min([0.5, 0 - 2]) < 3", "not (a == null)", "false", ""]}, + {expression: "e5", passThrough: true, fields: { + k908: "s ?? s", + }}, + {table: "t6", inputField: "items", executionMode: "loop", inputs: ["qty", "qty"], outputs: ["k909"], outputPath: "lines", rules: [ + ["[100..105]", "> 21", "-5"], + ["(100..105)", "", "price * ((qty ?? 1)) % 7"], + ]}, + {expression: "e7", passThrough: true, outputPath: "res", fields: { + k910: "(s != 'gold') and (s + '-' + s in ['gold', 'silver', 'a'])", + k911: "count(nums ?? [], # > 10)", + "m.k912": "s ?? s", + }}, + {table: "t8", inputField: "cust", inputs: ["min([-(0), 0.5])"], outputs: ["k913"], rules: [ + ["> 21", "'x'"], + ["$ > 10 and $ < 11", "'high'"], + ["not(18)", "(tier ?? 'none')"], + ["[5..15]", "'mid'"], + ]}, + {expression: "e9", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + "m.k914": "price ?? price", + }}, + {table: "t10", hit: "collect", inputs: ["s"], outputs: ["k915[]"], outputPath: "res", rules: [ + ["not('silver')", "min([-4, 100])"], + ["", "-5"], + ["", "10"], + ]}, + {switch: "s11", when: ["((0) == 0.5)", ""]}, + {table: "t12", inputField: "items", executionMode: "loop", inputs: ["tag", "(price) / 0.5 + (false ? (price ?? 0) : (qty ?? 0))", "qty"], outputs: ["k916"], outputPath: "res", rules: [ + ["'x'", "[1..11)", ">= 5", "'A-1'"], + ["'gold', 'bronze'", ">= 18", "(50..100)", "'gold'"], + ["'silver', 'gold'", "not(0)", "not(10)", "'high'"], + ["$ != 'x'", "> -1", "null", "'low'"], + ["", "$ > 100 and $ < 101", "null", "'mid'"], + ["null", "!= 1", "$ > 0 and $ < 1", "''"], + ["", "", "", "''"], + ]}, + ], + edges: [ + "input -> e1", + "input -> e2", + "e2 -> t3", + "input -> s4", + "s4:3 -> e5", + "s4:1 -> t6", + "s4:3 -> e7", + "e5 -> t8", + "e5 -> e9", + "e2 -> e9", + "s4:2 -> t10", + "e9 -> s11", + "s11:0 -> t12", + "t3 -> t12", + "e1 -> output", + "s4:0 -> output", + "t6 -> output", + "e7 -> output", + "t8 -> output", + "t10 -> output", + "t12 -> output", + ], + }, + cases: [ + [{cust: {age: 11, tier: 5, active: false}, s: "Gold", nums: [0.1], items: [], extra: 1}, {cust: {active: false, age: 11, tier: 5}, extra: 1, items: [], k900: 1, k902: 4, nums: [0.1], res: {k910: false, k911: 0, m: {k912: "Gold"}}, s: "Gold"}], + [{cust: {age: 0.1, tier: "b", active: false}, nums: [10, 21, 18], items: [{price: 1, qty: 2, tag: "gold"}, {price: {v: 1}, qty: 99, tag: "x"}]}, "!error"], + [{cust: {age: -0.1, tier: "gold ", active: true}, nums: [{x: 1}], items: [{price: -1, qty: 2, tag: "bronze"}], extra: [1, 2]}, "!error"], + [{cust: {tier: "", active: true}, s: "gold", items: [{price: 101, qty: 3, tag: "silver"}]}, {cust: {active: true, tier: ""}, items: [{price: 101, qty: 3, tag: "silver"}], k900: 1, k902: 4, res: {k910: false, k911: 0, m: {k912: "gold"}}, s: "gold"}], + [{cust: {tier: null, active: false}, nums: [], items: [{price: 1000, tag: "bronze"}, {price: -0.1, qty: 7, tag: "gold "}]}, "!error"], + [{s: "gold", nums: null, items: [{price: 2.5, qty: {v: 1}}, {price: 101, qty: 10, tag: "silver"}]}, {items: [{price: 2.5, qty: {v: 1}}, {price: 101, qty: 10, tag: "silver"}], k900: 1, k902: 4, res: {k910: false, k911: 0, m: {k912: "gold"}}, s: "gold"}], + [{cust: {age: 50, tier: "a", active: null}, nums: null, items: [{price: null, qty: 21, tag: "bronze"}, {price: 10, qty: 99, tag: "a"}, {price: 0.1, qty: 99, tag: "a"}, {qty: 7, tag: {t: "x"}}]}, "!error"], + [{s: "bronze", items: [{price: 10, qty: 101, tag: "gold "}, {price: null, qty: 1000000000000000000000, tag: ""}], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, items: [{price: 10, qty: 101, tag: "gold "}, {price: null, qty: 1000000000000000000000, tag: ""}], k900: 1, k902: 6, res: {k910: false, k911: 0, m: {k912: "bronze"}}, s: "bronze"}], + [{cust: [{age: 3}], s: true, nums: [2.5], items: [{price: 0, qty: 1, tag: "gold "}], extra: {deep: {x: 1}}}, "!error"], + [{s: "", nums: [-3], items: [{price: 7, qty: 50, tag: ""}, {price: [1], qty: 99, tag: "gold "}]}, {items: [{price: 7, qty: 50, tag: ""}, {price: [1], qty: 99, tag: "gold "}], k900: 1, k902: 0, nums: [-3], res: {k910: false, k911: 0, m: {k912: ""}}, s: ""}], + [{cust: {tier: "a", active: true}, s: "b", nums: [5, 3], items: [{price: 3, qty: 66, tag: "gold "}, {price: null, qty: 1000000000000000000000, tag: 5}], extra: "e"}, {cust: {active: true, tier: "a"}, extra: "e", items: [{price: 3, qty: 66, tag: "gold "}, {price: null, qty: 1000000000000000000000, tag: 5}], k900: 1, k902: 1, nums: [5, 3], res: {k910: false, k911: 0, m: {k912: "b"}}, s: "b"}], + [{cust: {age: 21, tier: "gold", active: false}, s: ["gold"], nums: [7, 1000000000000000000000], items: [{price: 1000000000000000000000, qty: 1}, {price: 0, qty: 0.1, tag: "gold"}, {price: 0, qty: 3, tag: "zz"}, {price: 1000, qty: 99, tag: ""}]}, "!error"], + [{cust: {age: 0.5, tier: "x", active: false}, s: "zz", nums: [100, 7], items: [{price: 1, qty: 0.5, tag: "bronze"}]}, {cust: {active: false, age: 0.5, tier: "x"}, items: [{price: 1, qty: 0.5, tag: "bronze"}], k900: 1, k902: 2, nums: [100, 7], res: {k910: false, k911: 1, m: {k912: "zz"}}, s: "zz"}], + [{s: "gold ", nums: [2.5, 0, 0, 2, 100], items: []}, {items: [], k900: 1, k902: 5, nums: [2.5, 0, 0, 2, 100], res: {k910: false, k911: 1, m: {k912: "gold "}}, s: "gold "}], + [{cust: {age: null, tier: "a", active: true}, s: "a", nums: [], items: [{price: 21, qty: null, tag: "silver"}, {price: -25, qty: null, tag: null}]}, {cust: {active: true, age: null, tier: "a"}, items: [{price: 21, qty: null, tag: "silver"}, {price: -25, qty: null, tag: null}], k900: 1, k902: 1, nums: [], res: {k910: false, k911: 0, m: {k912: "a"}}, s: "a"}], + [{cust: {age: 0.5, tier: null, active: false}, s: "a", nums: [99, 99, 21, 1000, 1000], items: [{price: 1000, qty: -25, tag: ""}, {price: 0, qty: 0.1, tag: "a"}, {price: 0.5, qty: 1, tag: "b"}, {price: 1000, qty: 5, tag: "gold"}]}, {cust: {active: false, age: 0.5, tier: null}, items: [{price: 1000, qty: -25, tag: ""}, {price: 0, qty: 0.1, tag: "a"}, {price: 0.5, qty: 1, tag: "b"}, {price: 1000, qty: 5, tag: "gold"}], k900: 1, k902: 1, nums: [99, 99, 21, 1000, 1000], res: {k910: false, k911: 5, m: {k912: "a"}}, s: "a"}], + [{cust: {age: -1, tier: "silver", active: false}, s: "a", nums: [-0.1], extra: 1}, "!error"], + [{cust: {age: {v: 1}, tier: "bronze", active: true}, s: "", nums: [101, 3, 36], items: []}, {cust: {active: true, age: {v: 1}, tier: "bronze"}, items: [], k900: 1, k902: 0, nums: [101, 3, 36], res: {k910: false, k911: 2, m: {k912: ""}}, s: ""}], + [{cust: null, s: "bronze", nums: null, items: []}, {items: [], k900: 1, k902: 6, res: {k910: false, k911: 0, m: {k912: "bronze"}}, s: "bronze"}], + [{cust: {age: 0.5, active: false}, s: "gold ", nums: [50, 2.5], items: [{qty: 1}]}, {cust: {active: false, age: 0.5}, items: [{qty: 1}], k900: 1, k902: 5, nums: [50, 2.5], res: {k910: false, k911: 1, m: {k912: "gold "}}, s: "gold "}], + [{cust: [], s: "a", nums: [19.99, 18], items: [{qty: 100, tag: "b"}]}, {cust: [], items: [{qty: 100, tag: "b"}], k900: 1, k902: 1, nums: [19.99, 18], res: {k910: false, k911: 2, m: {k912: "a"}}, s: "a"}], + [{cust: {age: "abc", tier: 5, active: true}, s: ["gold"], nums: [5, 100, 21], items: [{price: -25, tag: null}, {price: 100, qty: 0, tag: "gold "}]}, "!error"], + [{cust: {age: 2.5, tier: "gold ", active: true}, s: "b", nums: null, items: [{price: 10, qty: 50, tag: ""}, {price: 7, qty: 0, tag: "b"}]}, {cust: {active: true, age: 2.5, tier: "gold "}, items: [{price: 10, qty: 50, tag: ""}, {price: 7, qty: 0, tag: "b"}], k900: 1, k902: 1, res: {k910: false, k911: 0, m: {k912: "b"}}, s: "b"}], + [{cust: {age: -25, tier: "x", active: false}, s: "zz", nums: [0.5, 21], items: [{price: 0.1, qty: 11, tag: null}, {price: 7, qty: 11, tag: "gold "}]}, {cust: {active: false, age: -25, tier: "x"}, items: [{price: 0.1, qty: 11, tag: null}, {price: 7, qty: 11, tag: "gold "}], k900: 1, k902: 2, nums: [0.5, 21], res: {k910: false, k911: 1, m: {k912: "zz"}}, s: "zz"}], + ], +} + +{ + name: "gb066: 10 nodes, switch, switch, expr, loop expr, switch*, switch, table, table*, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["len('gold') * floor((n ?? 1)) < (b + price)", "((1 == 2.25)) or (true)", ""]}, + {switch: "s2", when: ["a != null", ""]}, + {expression: "e3", passThrough: true, outputPath: "out", fields: { + "res.k917": "len(items ?? []) % 2", + k918: "endsWith(`${(b ?? 1)}-${'none'}`, 'x')", + k919: "price ?? cust.age", + k920: "trim(string((b ?? 1)) + ' ' + 'x')", + }}, + {expression: "e4", inputField: "items", executionMode: "loop", passThrough: true, outputPath: "res", fields: { + "m.k921": "(qty ?? -1)", + "m.k922": "'none'", + k920: "(tag ?? '?')", + k924: "tag ?? tag", + }}, + {switch: "s5", hit: "collect", when: ["(n ?? 0) >= ((b ?? n ?? 0)) / 0.5", ""]}, + {switch: "s6", when: ["false", "not (((n ?? 1) > 2) and (0.5 >= price))", "100 > price + -4 * 0.5"]}, + {table: "t7", inputs: ["b", "(n) / 4 - (price ?? n ?? 0)", "b"], outputs: ["k925", "res.k926"], passThrough: true, rules: [ + ["not(1)", "(18..23)", "[1..11]", "2", "((b ?? 0)) / 3"], + ["> 21", "> -1", "-1, 0", "2", "(price ?? 1)"], + ["not(10)", "$ > 10 and $ < 60", ">= -1", "100", "0.25"], + ["", "", "", "-5", "0.25"], + ]}, + {table: "t8", hit: "collect", inputs: ["n", "price", "string((price ?? 0)) + ' ' + 'x' + '-' + 'x'"], outputs: ["k927[]"], passThrough: true, outputPath: "o.p", rules: [ + ["", "", "null", "true"], + ["$ > 50 and $ < 51", "[5..55]", "null", "true"], + ["[21..71)", "", "not('')", "-((b ?? 1)) < -4"], + ["", "<= 60", "", "false"], + ["", "", "", "(cust.active ?? false)"], + ]}, + {expression: "e9", fields: { + k928: "n ?? b", + }}, + {table: "t10", inputs: ["(price ?? 0)"], outputs: ["k919"], rules: [ + ["(10..11)", "true"], + ["10", "true"], + ["", "true"], + ]}, + ], + edges: [ + "input -> s1", + "s1:2 -> s2", + "s2:0 -> e3", + "s1:1 -> e4", + "s1:1 -> s5", + "e4 -> s6", + "s2:0 -> t7", + "s6:1 -> t8", + "s6:1 -> e9", + "e9 -> t10", + "s6:2 -> t10", + "s1:0 -> output", + "s2:1 -> output", + "e3 -> output", + "s5:0 -> output", + "s6:0 -> output", + "t7 -> output", + "t8 -> output", + "t10 -> output", + ], + }, + cases: [ + [{b: -0.1, items: [], cust: {age: null, tier: "zz", active: true}, price: 100, n: 19.99}, {b: -0.1, cust: {active: true, age: null, tier: "zz"}, items: [], n: 19.99, price: 100}], + [{b: 7, items: [{price: -25, qty: 0, tag: ""}, {price: 50, qty: -0.1, tag: null}], cust: {age: 2, tier: "gold", active: "no"}, price: 2, n: 0.1}, {b: 7, cust: {active: "no", age: 2, tier: "gold"}, items: [{price: -25, qty: 0, tag: ""}, {price: 50, qty: -0.1, tag: null}], n: 0.1, price: 2}], + [{b: 100, items: [{price: 99, qty: 50, tag: null}], cust: {age: null, tier: "bronze", active: true}, price: 99, n: 21}, {b: 100, cust: {active: true, age: null, tier: "bronze"}, items: [{price: 99, qty: 50, tag: null}], n: 21, price: 99}], + [{b: 19.99, items: [], cust: {age: 18, tier: "", active: null}, price: 5, n: 19.99}, {b: 19.99, cust: {active: null, age: 18, tier: ""}, items: [], k919: true, n: 19.99, o: {p: [{k927: false}, {k927: false}]}, price: 5, res: []}], + [{b: 101, items: [{price: 18, qty: true, tag: "b"}, {price: 0, qty: 19.99, tag: "zz"}, {price: 21, qty: "abc", tag: "Gold"}], cust: null, price: 0, n: -1}, {b: 101, items: [{price: 18, qty: true, tag: "b"}, {price: 0, qty: 19.99, tag: "zz"}, {price: 21, qty: "abc", tag: "Gold"}], n: -1, price: 0}], + [{b: {v: 1}, items: [{price: 21, qty: 3, tag: "a"}, {price: -25, qty: 1000, tag: "gold"}], cust: {age: null, tier: "bronze", active: true}, price: 3, n: 50}, {b: {v: 1}, cust: {active: true, age: null, tier: "bronze"}, items: [{price: 21, qty: 3, tag: "a"}, {price: -25, qty: 1000, tag: "gold"}], k919: true, n: 50, o: {p: [{k927: false}, {k927: true}]}, price: 3, res: [{k920: "a", k924: "a", m: {k921: 3, k922: "none"}, price: 21, qty: 3, tag: "a"}, {k920: "gold", k924: "gold", m: {k921: 1000, k922: "none"}, price: -25, qty: 1000, tag: "gold"}]}], + [{b: -1, cust: {age: -0.1, tier: "b", active: 1}, price: 18, n: 100}, "!error"], + [{items: [], cust: {age: 0.5, tier: "gold ", active: false}, price: [1], n: {v: 1}, extra: [1, 2]}, {}], + [{b: 95, items: [], cust: {age: -0.1, tier: "Gold", active: 1}, price: 3, n: "5"}, {k919: true}], + [{b: -1, items: [{price: 11, qty: 5, tag: "x"}, {price: true, qty: 7, tag: "x"}, {price: null, qty: 1000, tag: "silver"}, {price: "abc", qty: 11, tag: "a"}], cust: {age: 99, tier: "", active: false}, price: 99, n: 0.5}, {b: -1, cust: {active: false, age: 99, tier: ""}, items: [{price: 11, qty: 5, tag: "x"}, {price: true, qty: 7, tag: "x"}, {price: null, qty: 1000, tag: "silver"}, {price: "abc", qty: 11, tag: "a"}], n: 0.5, price: 99}], + [{b: 100, items: [{price: 3, qty: 11, tag: "x"}, {price: {v: 1}, qty: 0.5, tag: "Gold"}, {price: 1, qty: -25, tag: ""}, {price: 5, qty: 19.99, tag: "a"}], cust: {age: "5", tier: {t: "x"}, active: null}, price: 5, n: 1000000000000000000000}, {b: 100, cust: {active: null, age: "5", tier: {t: "x"}}, items: [{price: 3, qty: 11, tag: "x"}, {price: {v: 1}, qty: 0.5, tag: "Gold"}, {price: 1, qty: -25, tag: ""}, {price: 5, qty: 19.99, tag: "a"}], k919: true, n: 1000000000000000000000, o: {p: [{k927: false}, {k927: false}]}, price: 5, res: [{k920: "x", k924: "x", m: {k921: 11, k922: "none"}, price: 3, qty: 11, tag: "x"}, {k920: "Gold", k924: "Gold", m: {k921: 0.5, k922: "none"}, price: {v: 1}, qty: 0.5, tag: "Gold"}, {k920: "", k924: "", m: {k921: -25, k922: "none"}, price: 1, qty: -25, tag: ""}, {k920: "a", k924: "a", m: {k921: 19.99, k922: "none"}, price: 5, qty: 19.99, tag: "a"}]}], + [{b: 1000, items: [], cust: {age: 3, tier: null, active: true}, price: 10, n: 1000}, {b: 1000, cust: {active: true, age: 3, tier: null}, items: [], k919: true, n: 1000, o: {p: [{k927: false}, {k927: true}]}, price: 10, res: []}], + [{b: null, items: [{price: true, qty: 1000, tag: "bronze"}], cust: [{age: 3}], price: "abc", n: 18}, {}], + [{b: -0.1, items: [], cust: {age: 100, tier: "gold", active: null}, price: 5, n: 50}, {b: -0.1, cust: {active: null, age: 100, tier: "gold"}, items: [], k919: true, n: 50, o: {p: [{k927: false}, {k927: false}]}, price: 5, res: []}], + [{items: "items", cust: {age: 2.5, tier: null, active: false}, price: "5", n: 10}, "!error"], + ], +} + +{ + name: "gb067: 6 nodes, table*, loop expr, table*, switch, switch*, expr", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["tier"], outputs: ["k930"], passThrough: true, outputPath: "res", rules: [ + ["'x', 'bronze'", "100"], + ["$ != 'gold'", "-5"], + ["", "100"], + ["null", "2"], + ]}, + {expression: "e2", inputField: "items", executionMode: "loop", outputPath: "o.p", fields: { + k931: "true", + k932: "string((tag ?? '?') in ['gold', 'silver', 'a']) != ''", + k933: "(price ?? qty ?? 0) * len(`${price}-${(tag ?? '?')}`)", + }}, + {table: "t3", hit: "collect", inputs: ["1 * 2.25 + 0.5", "string(s != null)"], outputs: ["m.k934", "k935"], passThrough: true, outputPath: "out", rules: [ + ["< 50", "'gold'", "'mid'", "-5"], + ["[5..15)", "null", "'mid'", "10"], + ["[100..101]", "'a', 'gold'", "string(2.25 * 100)", "((-4))"], + [">= 21", "startsWith($, '')", "''", "10"], + ["> 18", "null", "'mid'", "-5"], + ["", "", "'low'", "-5"], + ]}, + {switch: "s4", when: ["(2 == 100 ? 2 : -(2)) == (0) + 1", "false", "false", ""]}, + {switch: "s5", hit: "collect", when: ["(not (endsWith('A-1', 'a'))) and (true)", ""]}, + {expression: "e6", fields: { + "g.k936": "-((100)) * min([0.5, max([0.5, 10])])", + "m.k937": "len('none')", + k938: "string(10 <= 100) + ' ' + string(0.5)", + }}, + ], + edges: [ + "input -> t1", + "input -> e2", + "input -> t3", + "e2 -> t3", + "e2 -> s4", + "s4:0 -> s5", + "s5:1 -> e6", + "t1 -> output", + "t3 -> output", + "s4:1 -> output", + "e6 -> output", + ], + }, + cases: [ + [{tier: "silver", flag: null, s: "silver"}, "!error"], + [{tier: "gold", flag: true, s: "gold", items: []}, {flag: true, items: [], o: {p: []}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: 100}], s: "gold", tier: "gold"}], + [{tier: "bronze", flag: false, s: "x", items: null}, "!error"], + [{tier: "a", flag: null, s: null, items: [{price: 1, tag: "zz"}, {price: 7, qty: 1000000000000000000000, tag: "x"}, {price: 5, tag: "x"}]}, {items: [{price: 1, tag: "zz"}, {price: 7, qty: 1000000000000000000000, tag: "x"}, {price: 5, tag: "x"}], o: {p: [{k931: true, k932: true, k933: 4}, {k931: true, k932: true, k933: 21}, {k931: true, k932: true, k933: 15}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], tier: "a"}], + [{tier: "b", flag: true, s: "b", items: [{tag: ""}]}, {flag: true, items: [{tag: ""}], o: {p: [{k931: true, k932: true, k933: 0}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "b", tier: "b"}], + [{tier: "x", s: "gold ", items: [{price: 10, tag: "Gold"}, {price: 21, qty: 0.5, tag: "b"}, {price: 2, qty: 1000000000000000000000, tag: "b"}, {price: 100, qty: -25, tag: "a"}]}, {items: [{price: 10, tag: "Gold"}, {price: 21, qty: 0.5, tag: "b"}, {price: 2, qty: 1000000000000000000000, tag: "b"}, {price: 100, qty: -25, tag: "a"}], o: {p: [{k931: true, k932: true, k933: 70}, {k931: true, k932: true, k933: 84}, {k931: true, k932: true, k933: 6}, {k931: true, k932: true, k933: 500}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: 100}, {k930: -5}, {k930: 100}], s: "gold ", tier: "x"}], + [{tier: "bronze", flag: false, s: "b", items: null}, "!error"], + [{tier: "Gold", flag: true, s: "silver", items: []}, {flag: true, items: [], o: {p: []}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "silver", tier: "Gold"}], + [{tier: "x", flag: false, s: "zz", items: [{price: 18, qty: 0.5, tag: ""}, {price: 1, qty: 19.99, tag: "x"}], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, flag: false, items: [{price: 18, qty: 0.5, tag: ""}, {price: 1, qty: 19.99, tag: "x"}], o: {p: [{k931: true, k932: true, k933: 54}, {k931: true, k932: true, k933: 3}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: 100}, {k930: -5}, {k930: 100}], s: "zz", tier: "x"}], + [{tier: "Gold", flag: false, items: [{price: 0.5, qty: 18, tag: "gold "}, {price: 19.99, qty: 2.5, tag: "gold "}]}, {flag: false, items: [{price: 0.5, qty: 18, tag: "gold "}, {price: 19.99, qty: 2.5, tag: "gold "}], o: {p: [{k931: true, k932: true, k933: 4.5}, {k931: true, k932: true, k933: 219.89}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], tier: "Gold"}], + [{tier: null, flag: false, s: "b", items: [{price: -1, qty: 0.1, tag: "zz"}, {price: 0.5, qty: 7}, {price: 99, qty: -25, tag: "silver"}, {price: 18, qty: 3, tag: ""}]}, {flag: false, items: [{price: -1, qty: 0.1, tag: "zz"}, {price: 0.5, qty: 7}, {price: 99, qty: -25, tag: "silver"}, {price: 18, qty: 3, tag: ""}], o: {p: [{k931: true, k932: true, k933: -5}, {k931: true, k932: true, k933: 2.5}, {k931: true, k932: true, k933: 891}, {k931: true, k932: true, k933: 54}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}, {k930: 2}], s: "b"}], + [{tier: "zz", flag: true, s: "b", items: []}, {flag: true, items: [], o: {p: []}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "b", tier: "zz"}], + [{tier: "b", flag: false, s: "", items: [{price: 99, qty: -1, tag: "a"}, {price: 10, qty: 101, tag: "b"}], extra: 1}, {extra: 1, flag: false, items: [{price: 99, qty: -1, tag: "a"}, {price: 10, qty: 101, tag: "b"}], o: {p: [{k931: true, k932: true, k933: 396}, {k931: true, k932: true, k933: 40}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "", tier: "b"}], + [{tier: "silver", flag: false, s: "a", items: [], extra: [1, 2]}, {extra: [1, 2], flag: false, items: [], o: {p: []}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "a", tier: "silver"}], + [{tier: "x", flag: true, s: "silver", items: [{price: 18, qty: 5, tag: "gold"}, {price: 2.5, qty: 100, tag: "bronze"}, {tag: "b"}]}, {flag: true, items: [{price: 18, qty: 5, tag: "gold"}, {price: 2.5, qty: 100, tag: "bronze"}, {tag: "b"}], o: {p: [{k931: true, k932: true, k933: 126}, {k931: true, k932: true, k933: 25.0}, {k931: true, k932: true, k933: 0}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: 100}, {k930: -5}, {k930: 100}], s: "silver", tier: "x"}], + [{tier: "silver", flag: true, s: "gold", items: []}, {flag: true, items: [], o: {p: []}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "gold", tier: "silver"}], + [{flag: true, items: [{price: 1, qty: null, tag: ""}]}, {flag: true, items: [{price: 1, qty: null, tag: ""}], o: {p: [{k931: true, k932: true, k933: 2}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}, {k930: 2}]}], + [{tier: "silver", flag: true, s: "", items: [{price: 3, qty: 22, tag: "Gold"}, {price: 10, qty: 0.5, tag: "bronze"}]}, {flag: true, items: [{price: 3, qty: 22, tag: "Gold"}, {price: 10, qty: 0.5, tag: "bronze"}], o: {p: [{k931: true, k932: true, k933: 18}, {k931: true, k932: true, k933: 90}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "", tier: "silver"}], + [{tier: "gold", flag: true, s: "gold", items: [{price: 19.99, qty: 5, tag: ""}, {qty: 7, tag: "x"}]}, {flag: true, items: [{price: 19.99, qty: 5, tag: ""}, {qty: 7, tag: "x"}], o: {p: [{k931: true, k932: true, k933: 119.94}, {k931: true, k932: true, k933: 42}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: 100}], s: "gold", tier: "gold"}], + [{tier: "Gold", flag: false, s: "zz", items: [{price: -25, qty: 21, tag: "silver"}, {price: 10, qty: null, tag: "silver"}]}, {flag: false, items: [{price: -25, qty: 21, tag: "silver"}, {price: 10, qty: null, tag: "silver"}], o: {p: [{k931: true, k932: true, k933: -250}, {k931: true, k932: true, k933: 90}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "zz", tier: "Gold"}], + [{tier: "a", flag: true}, "!error"], + [{tier: "b", s: "gold ", items: [{price: -0.1, qty: 100, tag: "silver"}], extra: "e"}, {extra: "e", items: [{price: -0.1, qty: 100, tag: "silver"}], o: {p: [{k931: true, k932: true, k933: -1.1}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "gold ", tier: "b"}], + [{tier: "bronze", flag: null, s: "zz", items: [{price: 1000, qty: 1000000000000000000000, tag: "bronze"}, {price: 101, qty: 5}, {price: 1000000000000000000000, tag: "gold"}], extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, items: [{price: 1000, qty: 1000000000000000000000, tag: "bronze"}, {price: 101, qty: 5}, {price: 1000000000000000000000, tag: "gold"}], o: {p: [{k931: true, k932: true, k933: 11000}, {k931: true, k932: true, k933: 505}, {k931: true, k932: true, k933: 27000000000000000000000}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: 100}, {k930: -5}, {k930: 100}], s: "zz", tier: "bronze"}], + [{tier: "Gold", flag: true, s: "", items: [{price: -0.1, qty: 10, tag: "b"}, {price: 0.5, qty: 10, tag: ""}]}, {flag: true, items: [{price: -0.1, qty: 10, tag: "b"}, {price: 0.5, qty: 10, tag: ""}], o: {p: [{k931: true, k932: true, k933: -0.6}, {k931: true, k932: true, k933: 2.0}]}, out: [{k935: -5, m: {k934: "low"}}], res: [{k930: -5}, {k930: 100}], s: "", tier: "Gold"}], + ], +} + +{ + name: "gb068: 11 nodes, table, switch*, loop expr, table, expr, table, expr, switch, table*, expr, expr", + graph: { + nodes: [ + {table: "t1", inputs: ["vip", "a * (a ?? 0)", "a"], outputs: ["k939"], passThrough: true, outputPath: "o.p", rules: [ + ["", "[100..150]", "!= 21", "1"], + ["$ == true", "[100..110)", "null", "-5"], + ["$ == true", "not(50)", "", "0"], + ["true", "!= 50", "!= 100", "0"], + ["$ == true", "!= 1", "", "count(items ?? [], (#.qty ?? 0) > 1)"], + ]}, + {switch: "s2", hit: "collect", when: ["(((vip ?? false)) and ((vip) and ((vip ?? false))))", ""]}, + {expression: "e3", inputField: "items", executionMode: "loop", outputPath: "res", fields: { + k940: "-((1 in [-5..5] ? (qty ?? 1) * price : (price ?? -1) - (price ?? -1)))", + }}, + {table: "t4", inputs: ["sum(map(items ?? [], (#.price ?? 0) * (#.qty ?? 0))) + (o.p.k939 ?? -1)", "s", "o.p.k939"], outputs: ["k941", "m.k942"], rules: [ + ["> 5", "'x'", "[100..110)", "string(len(filter(items ?? [], #.tag == 'gold'))) + ' ' + (s ?? 'none')", "true"], + ["null", "", "[-1..49)", "''", "(vip ?? false)"], + ["[5..15]", "'x'", "< 0", "'low'", "false"], + ["", "$ != 'x'", "[1..6)", "'gold'", "true"], + ["18, 28", "", "(-1..9)", "'gold'", "count(items ?? [], (#.qty ?? 0) > 1) - max([(o.p.k939 ?? 1), (a ?? -1)]) <= 2"], + ["", "", "", "'high'", "false"], + ]}, + {expression: "e5", outputPath: "res", fields: { + k943: "lower(((items ?? [])[1].tag ?? '') + '!')", + }}, + {table: "t6", inputs: ["2"], outputs: ["k944"], passThrough: true, outputPath: "out", rules: [ + ["", "'low'"], + ["> 1", "((m.k942 ?? false) ? (k941 ?? '') : (k941 ?? 'none')) + '-' + k941 + '-' + trim(`n=${0}-${(k941 ?? '?')}`)"], + ]}, + {expression: "e7", fields: { + k945: "string(10 * 0 in [0..10])", + "m.k946": "m.k942 ?? $.k945", + k947: "m.k942 ?? m.k942", + "res.k948": "(m.k942 ?? false)", + }}, + {switch: "s8", when: ["contains(upper(string(false)), 'x')", "((m.k942 == null) and ((m.k942)))"]}, + {table: "t9", hit: "collect", inputs: ["m.k942", "k941", null], outputs: ["k949[]"], outputPath: "res", rules: [ + ["true", "", "$ != null", "'low'"], + ["$ == true", "$ != 'a'", "", "'high'"], + ["$ == true", "startsWith($, 'g')", "", "string('none' in ['gold', 'silver', 'a'])"], + ["", "", "", "'low'"], + ]}, + {expression: "e10", passThrough: true, outputPath: "o.p", fields: { + "g.k950": "abs(max([(true ? 100 : 100), 100 * -4]))", + k951: "10 * 0 % 7", + k952: "out.k944 ?? m.k942", + k947: "`n=${($.k951 ?? 0)}-${'gold'}`", + }}, + {expression: "e11", passThrough: true, fields: { + k954: "-(-(10)) + (2.25)", + }}, + ], + edges: [ + "input -> t1", + "input -> s2", + "t1 -> e3", + "t1 -> t4", + "s2:0 -> e5", + "e3 -> t6", + "t4 -> t6", + "t4 -> e7", + "t6 -> s8", + "t6 -> t9", + "s8:1 -> e10", + "s8:1 -> e11", + "s2:1 -> output", + "e5 -> output", + "e7 -> output", + "s8:0 -> output", + "t9 -> output", + "e10 -> output", + "e11 -> output", + ], + }, + cases: [ + [{vip: true, s: "", a: 1, items: [{price: 75, qty: 2, tag: "b"}, {price: -1, qty: 21, tag: "Gold"}]}, {a: 1, items: [{price: 75, qty: 2, tag: "b"}, {price: -1, qty: 21, tag: "Gold"}], k945: "true", k947: false, m: {k946: false}, res: {k943: "gold!", k948: false}, s: "", vip: true}], + [{vip: null, s: "bronze", a: 11, items: [{price: 81, qty: 18}, {price: 99, tag: "Gold"}]}, {a: 11, items: [{price: 81, qty: 18}, {price: 99, tag: "Gold"}], k945: "true", k947: true, m: {k946: true}, res: {k948: true}, s: "bronze"}], + [{vip: false, s: "zz", items: [{price: 1000000000000000000000, qty: 50, tag: "bronze"}, {price: 50, qty: 21}]}, {items: [{price: 1000000000000000000000, qty: 50, tag: "bronze"}, {price: 50, qty: 21}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "zz", vip: false}], + [{s: "", a: -1, items: [{price: 3, qty: 0.5, tag: "a"}]}, {a: -1, items: [{price: 3, qty: 0.5, tag: "a"}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: ""}], + [{vip: false, s: "silver", a: 1000, items: [{price: 7, qty: 0.5, tag: "bronze"}]}, {a: 1000, items: [{price: 7, qty: 0.5, tag: "bronze"}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "silver", vip: false}], + [{vip: true, s: "gold", a: 101, items: [{price: 18, qty: 0.1, tag: "b"}, {price: 99, qty: 5, tag: "silver"}]}, {a: 101, items: [{price: 18, qty: 0.1, tag: "b"}, {price: 99, qty: 5, tag: "silver"}], k945: "true", k947: false, m: {k946: false}, res: {k943: "silver!", k948: false}, s: "gold", vip: true}], + [{vip: false, s: "silver", a: -25, items: [], extra: {deep: {x: 1}}}, {a: -25, extra: {deep: {x: 1}}, items: [], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "silver", vip: false}], + [{vip: true, s: "zz", a: 50, items: [{price: 19.99, qty: 101, tag: "silver"}, {price: 0.5, qty: 1, tag: "a"}]}, {a: 50, items: [{price: 19.99, qty: 101, tag: "silver"}, {price: 0.5, qty: 1, tag: "a"}], k945: "true", k947: false, m: {k946: false}, res: {k943: "a!", k948: false}, s: "zz", vip: true}], + [{vip: true, s: "b", a: 7, items: [{price: 1000, qty: 21, tag: "silver"}, {price: 1000000000000000000000, qty: 0, tag: "x"}, {price: -1, qty: 1000000000000000000000, tag: "silver"}]}, {a: 7, items: [{price: 1000, qty: 21, tag: "silver"}, {price: 1000000000000000000000, qty: 0, tag: "x"}, {price: -1, qty: 1000000000000000000000, tag: "silver"}], k945: "true", k947: false, m: {k946: false}, res: {k943: "x!", k948: false}, s: "b", vip: true}], + [{vip: false, s: "a", items: [{price: 1, qty: -25, tag: "silver"}, {price: 3, qty: 0.5, tag: "silver"}]}, {items: [{price: 1, qty: -25, tag: "silver"}, {price: 3, qty: 0.5, tag: "silver"}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "a", vip: false}], + [{vip: false, s: "bronze", a: 100, items: [{price: -25, qty: 11}, {price: 1000, qty: 0.5, tag: ""}, {price: 5, qty: 19.99, tag: "zz"}]}, {a: 100, items: [{price: -25, qty: 11}, {price: 1000, qty: 0.5, tag: ""}, {price: 5, qty: 19.99, tag: "zz"}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "bronze", vip: false}], + [{vip: true, s: "silver", a: -25, items: [{price: 58, qty: 2.5, tag: "Gold"}, {price: -0.1, qty: 5, tag: "Gold"}]}, {a: -25, items: [{price: 58, qty: 2.5, tag: "Gold"}, {price: -0.1, qty: 5, tag: "Gold"}], k945: "true", k947: false, m: {k946: false}, res: {k943: "gold!", k948: false}, s: "silver", vip: true}], + [{vip: false, s: "silver", a: 2, items: [{price: -0.1, qty: 101, tag: "gold"}, {price: -1, qty: 10, tag: "gold"}]}, {a: 2, items: [{price: -0.1, qty: 101, tag: "gold"}, {price: -1, qty: 10, tag: "gold"}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "silver", vip: false}], + [{vip: false, s: "x", a: -25, items: []}, {a: -25, items: [], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "x", vip: false}], + [{vip: false, s: "gold ", a: -0.1, items: [{price: 19.99, qty: 18, tag: "gold "}, {price: -25, qty: -0.1, tag: ""}]}, {a: -0.1, items: [{price: 19.99, qty: 18, tag: "gold "}, {price: -25, qty: -0.1, tag: ""}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "gold ", vip: false}], + [{vip: false, a: 5, items: [{price: -25, qty: 1, tag: "a"}, {price: -25, qty: -25, tag: "bronze"}, {price: -0.1, qty: 10, tag: "Gold"}, {qty: 1000000000000000000000, tag: "gold"}]}, "!error"], + [{vip: true, s: "zz", a: 11, items: []}, {a: 11, items: [], k945: "true", k947: true, m: {k946: true}, res: {k943: "!", k948: true}, s: "zz", vip: true}], + [{vip: true, s: "x", a: 7, items: [{price: -1, qty: 1, tag: "silver"}, {price: 5, qty: 1000000000000000000000, tag: "silver"}, {price: 101, qty: 18, tag: "Gold"}, {price: 19.99, qty: 1, tag: "b"}]}, {a: 7, items: [{price: -1, qty: 1, tag: "silver"}, {price: 5, qty: 1000000000000000000000, tag: "silver"}, {price: 101, qty: 18, tag: "Gold"}, {price: 19.99, qty: 1, tag: "b"}], k945: "true", k947: false, m: {k946: false}, res: {k943: "silver!", k948: false}, s: "x", vip: true}], + [{vip: true, s: "gold ", a: 3, items: [{price: 19.99, qty: 101, tag: ""}]}, {a: 3, items: [{price: 19.99, qty: 101, tag: ""}], k945: "true", k947: false, m: {k946: false}, res: {k943: "!", k948: false}, s: "gold ", vip: true}], + [{vip: false, s: "", a: 10, items: [{price: -1, qty: 2.5, tag: "x"}, {price: 11, qty: 100}, {price: 10, qty: 0.1, tag: "zz"}, {price: 3, qty: 10, tag: ""}]}, {a: 10, items: [{price: -1, qty: 2.5, tag: "x"}, {price: 11, qty: 100}, {price: 10, qty: 0.1, tag: "zz"}, {price: 3, qty: 10, tag: ""}], k945: "true", k947: true, m: {k946: true}, res: {k948: true}, s: "", vip: false}], + [{s: null, a: 1000000000000000000000, items: [{price: 99, qty: -0.1, tag: "Gold"}, {qty: 7, tag: "b"}]}, "!error"], + [{vip: true, s: "x", a: 1000000000000000000000, items: [{price: 0, qty: 2.5, tag: "silver"}, {price: 10, qty: 18}]}, {a: 1000000000000000000000, items: [{price: 0, qty: 2.5, tag: "silver"}, {price: 10, qty: 18}], k945: "true", k947: false, m: {k946: false}, res: {k943: "!", k948: false}, s: "x", vip: true}], + [{s: "gold", a: -25, items: [{price: 0.5, qty: 11, tag: "silver"}, {price: -1, qty: -1, tag: "x"}, {price: -0.1, tag: "gold "}, {price: 1000000000000000000000, qty: 1, tag: "a"}]}, {a: -25, items: [{price: 0.5, qty: 11, tag: "silver"}, {price: -1, qty: -1, tag: "x"}, {price: -0.1, tag: "gold "}, {price: 1000000000000000000000, qty: 1, tag: "a"}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "gold"}], + [{vip: false, s: "", a: 7, items: [{price: 1000, qty: 99, tag: null}, {price: 0.1, qty: 1, tag: null}]}, {a: 7, items: [{price: 1000, qty: 99, tag: null}, {price: 0.1, qty: 1, tag: null}], k945: "true", k947: false, m: {k946: false}, res: {k948: false}, s: "", vip: false}], + [{vip: false, s: "a", a: 101, items: [{price: 1, qty: -0.1, tag: null}, {qty: 99, tag: "b"}]}, "!error"], + ], +} + +{ + name: "gb069: 8 nodes, switch, switch*, switch, switch, expr, loop expr, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["len(`${(b ?? 1)}-${'x'}`) in [-5..5]", "((cust.active ?? false)) or ('' != 'silver')", ""]}, + {switch: "s2", hit: "collect", when: ["((price ?? -1) + b < price)", "not (false)"]}, + {switch: "s3", when: ["not (((b ?? 0) >= 3))", "(false) and (false)", "(cust.tier ?? 'none') + '' + cust.tier == 'silver'"]}, + {switch: "s4", when: ["not (not ((true) and ((cust.active ?? false))))", ""]}, + {expression: "e5", outputPath: "o.p", fields: { + k955: "100", + k956: "b", + }}, + {expression: "e6", inputField: "items", executionMode: "loop", outputPath: "o.p", fields: { + k957: "string(true)", + k958: "price", + }}, + {expression: "e7", inputField: "cust", passThrough: true, outputPath: "lines", fields: { + "g.k959": "len(`n=${(age ?? 1)}-${(tier ?? '?')}`)", + k960: "(age ?? 1)", + }}, + {table: "t8", inputs: ["price", "(cust.tier ?? '')", "price"], outputs: ["k961"], passThrough: true, rules: [ + ["[5..55]", "$ != ''", "[18..19)", "price != null"], + ["null", "not('')", "not(18)", "true"], + ["!= 100", "'silver', 'gold'", "", "price == null"], + ["(5..10)", "not('a')", "> 18", "len((cust.tier ?? '?')) * -((cust.age ?? 0)) <= (price ?? 0)"], + ["> 50", "null", "5", "false"], + ]}, + ], + edges: [ + "input -> s1", + "input -> s2", + "s1:2 -> s3", + "s3:1 -> s4", + "s3:1 -> e5", + "s4:0 -> e6", + "s4:0 -> e7", + "s2:1 -> t8", + "s1:0 -> output", + "s2:0 -> output", + "s3:2 -> output", + "s4:1 -> output", + "e5 -> output", + "e6 -> output", + "e7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{cust: {age: 50, tier: "a", active: false}, price: -25, items: [{price: 2, qty: 99, tag: "Gold"}, {price: 101, qty: 19.99, tag: "Gold"}]}, {cust: {active: false, age: 50, tier: "a"}, items: [{price: 2, qty: 99, tag: "Gold"}, {price: 101, qty: 19.99, tag: "Gold"}], price: -25}], + [{nums: [], cust: "cust", b: null, items: [{price: 1000000000000000000000, qty: 7, tag: "a"}, {price: 1000000000000000000000, qty: 7, tag: "a"}]}, {cust: "cust", items: [{price: 1000000000000000000000, qty: 7, tag: "a"}, {price: 1000000000000000000000, qty: 7, tag: "a"}], nums: []}], + [{nums: [5], cust: {age: null, tier: "a", active: false}, b: -25, price: -25, items: [{price: 2, qty: 0, tag: ""}, {price: 0.1, qty: -25, tag: "gold"}]}, {b: -25, cust: {active: false, age: null, tier: "a"}, items: [{price: 2, qty: 0, tag: ""}, {price: 0.1, qty: -25, tag: "gold"}], nums: [5], price: -25}], + [{nums: [101, 11], cust: {age: 3, tier: null, active: true}, b: 19.99, price: 19.99, items: "items"}, {b: 19.99, cust: {active: true, age: 3, tier: null}, items: "items", nums: [101, 11], price: 19.99}], + [{nums: 7, cust: {age: 19.99, tier: "zz", active: true}, b: 2, price: 1, items: [{price: 19.99, qty: 2, tag: "b"}, {price: 1, qty: 0, tag: "x"}]}, {b: 2, cust: {active: true, age: 19.99, tier: "zz"}, items: [{price: 19.99, qty: 2, tag: "b"}, {price: 1, qty: 0, tag: "x"}], nums: 7, price: 1}], + [{nums: 7, cust: {age: 0.5, tier: "silver", active: false}, b: 3, price: 1000, items: [{price: 1, tag: "gold "}, {qty: -0.1, tag: "silver"}, {price: -25, qty: -1, tag: null}]}, {b: 3, cust: {active: false, age: 0.5, tier: "silver"}, items: [{price: 1, tag: "gold "}, {qty: -0.1, tag: "silver"}, {price: -25, qty: -1, tag: null}], k961: false, nums: 7, price: 1000}], + [{nums: [], b: -25, price: -25, items: [{price: 26, qty: 11, tag: "zz"}, {price: 2, qty: 0, tag: "zz"}, {price: 1000, tag: "zz"}, {price: 10, qty: 2.5, tag: "Gold"}]}, {b: -25, items: [{price: 26, qty: 11, tag: "zz"}, {price: 2, qty: 0, tag: "zz"}, {price: 1000, tag: "zz"}, {price: 10, qty: 2.5, tag: "Gold"}], nums: [], price: -25}], + [{cust: {age: -25, tier: "bronze"}, b: 50, price: true, items: [{price: -1, qty: 0.5, tag: "bronze"}, {price: 2.5, qty: 21, tag: "gold "}, {price: 7, qty: null, tag: "zz"}]}, {b: 50, cust: {age: -25, tier: "bronze"}, items: [{price: -1, qty: 0.5, tag: "bronze"}, {price: 2.5, qty: 21, tag: "gold "}, {price: 7, qty: null, tag: "zz"}], price: true}], + [{nums: [{x: 1}], cust: {age: 0, tier: "Gold", active: false}, b: 10, price: 101, items: [{price: 2.5, qty: 18, tag: "x"}, {price: 2.5, qty: -25, tag: "silver"}, {price: 1000000000000000000000, qty: 3, tag: "x"}, {qty: null, tag: "Gold"}]}, {b: 10, cust: {active: false, age: 0, tier: "Gold"}, items: [{price: 2.5, qty: 18, tag: "x"}, {price: 2.5, qty: -25, tag: "silver"}, {price: 1000000000000000000000, qty: 3, tag: "x"}, {qty: null, tag: "Gold"}], nums: [{x: 1}], price: 101}], + [{nums: null, cust: {age: 1, tier: "x", active: null}, b: 1, items: []}, {b: 1, cust: {active: null, age: 1, tier: "x"}, items: []}], + [{cust: [], b: null, price: 7, items: [], extra: [1, 2]}, {cust: [], extra: [1, 2], items: [], price: 7}], + [{nums: [0.5, 1000000000000000000000, 3], cust: {age: 0.5, tier: null, active: false}, b: 119, items: [{price: 50, qty: 11, tag: "a"}, {price: 100, qty: 0.1, tag: "b"}, {price: 19.99, qty: 0.5, tag: null}, {price: null, qty: 21, tag: "x"}]}, {b: 119, cust: {active: false, age: 0.5, tier: null}, items: [{price: 50, qty: 11, tag: "a"}, {price: 100, qty: 0.1, tag: "b"}, {price: 19.99, qty: 0.5, tag: null}, {price: null, qty: 21, tag: "x"}], nums: [0.5, 1000000000000000000000, 3]}], + [{nums: [50, 1000], cust: {age: 0.5, tier: "b", active: false}, b: 0, price: 99, items: [{qty: 36, tag: "gold"}]}, {b: 0, cust: {active: false, age: 0.5, tier: "b"}, items: [{qty: 36, tag: "gold"}], nums: [50, 1000], price: 99}], + [{nums: [3, 5], cust: {age: 1000000000000000000000, tier: "gold", active: false}, b: 3, price: 11, items: null}, {b: 3, cust: {active: false, age: 1000000000000000000000, tier: "gold"}, k961: false, nums: [3, 5], price: 11}], + [{nums: [1000], cust: {age: 19.99, tier: "x", active: false}, b: 101, price: -25, items: [{price: 10, qty: 100, tag: "zz"}, {price: 101, qty: 101, tag: "silver"}]}, {b: 101, cust: {active: false, age: 19.99, tier: "x"}, items: [{price: 10, qty: 100, tag: "zz"}, {price: 101, qty: 101, tag: "silver"}], nums: [1000], price: -25}], + [{nums: [101, 3, 50], cust: {age: null, tier: "a", active: false}, b: 21, price: null, items: [{price: 10, qty: null, tag: "Gold"}, {price: 3, qty: 21, tag: "a"}]}, {b: 21, cust: {active: false, age: null, tier: "a"}, items: [{price: 10, qty: null, tag: "Gold"}, {price: 3, qty: 21, tag: "a"}], nums: [101, 3, 50]}], + [{nums: [21, -0.1, 18, 50, 100], b: 7, price: 19.99, items: []}, {b: 7, items: [], nums: [21, -0.1, 18, 50, 100], price: 19.99}], + [{nums: [5, 2, 99], cust: {age: 1000000000000000000000, tier: "Gold", active: true}, b: 18, price: {v: 1}, items: "items"}, {b: 18, cust: {active: true, age: 1000000000000000000000, tier: "Gold"}, items: "items", nums: [5, 2, 99], price: {v: 1}}], + [{nums: [], cust: {age: 3, tier: "b", active: true}, b: null, price: {v: 1}, items: [{price: -25, qty: 5, tag: "a"}]}, {cust: {active: true, age: 3, tier: "b"}, items: [{price: -25, qty: 5, tag: "a"}], nums: [], price: {v: 1}}], + [{nums: [3, 0.1], cust: {age: 0.5, tier: "x", active: false}, b: 99, price: 0.5, items: [{price: 19.99, qty: 3, tag: "gold"}], extra: "e"}, {b: 99, cust: {active: false, age: 0.5, tier: "x"}, extra: "e", items: [{price: 19.99, qty: 3, tag: "gold"}], nums: [3, 0.1], price: 0.5}], + [{nums: [1000, 3, 10], cust: {tier: "gold", active: true}, b: -0.1, items: []}, {b: -0.1, cust: {active: true, tier: "gold"}, items: [], k961: true, nums: [1000, 3, 10]}], + [{b: 1000000000000000000000, price: 1000000000000000000000, items: [{price: 77, tag: "silver"}]}, {b: 1000000000000000000000, items: [{price: 77, tag: "silver"}], price: 1000000000000000000000}], + [{cust: {age: 99, tier: "silver", active: true}, b: 1000000000000000000000, price: 5, items: [{price: 50, qty: 99, tag: "b"}, {price: 100, qty: -1, tag: "gold "}, {price: 100, qty: 18, tag: "silver"}, {price: 2.5, qty: 7, tag: "Gold"}]}, {b: 1000000000000000000000, cust: {active: true, age: 99, tier: "silver"}, items: [{price: 50, qty: 99, tag: "b"}, {price: 100, qty: -1, tag: "gold "}, {price: 100, qty: 18, tag: "silver"}, {price: 2.5, qty: 7, tag: "Gold"}], k961: false, price: 5}], + [{nums: [], cust: {age: 21, tier: "", active: null}, b: 1000, price: 50, items: [{price: 2, qty: 18, tag: "gold "}, {price: 3, qty: null, tag: null}, {price: 2, qty: 1, tag: "bronze"}]}, {b: 1000, cust: {active: null, age: 21, tier: ""}, items: [{price: 2, qty: 18, tag: "gold "}, {price: 3, qty: null, tag: null}, {price: 2, qty: 1, tag: "bronze"}], nums: [], price: 50}], + [{nums: [0.1, 99, 0.5, 99, 10], cust: {age: 1, tier: null, active: null}, b: 3, price: 7, items: [{price: 2.5, qty: null, tag: "silver"}, {price: 2, qty: 21, tag: "a"}]}, {b: 3, cust: {active: null, age: 1, tier: null}, items: [{price: 2.5, qty: null, tag: "silver"}, {price: 2, qty: 21, tag: "a"}], nums: [0.1, 99, 0.5, 99, 10], price: 7}], + [{nums: [], cust: {age: -25, tier: "Gold"}, b: 18, price: null, items: [{price: 100, qty: -25, tag: "b"}, {qty: 1000000000000000000000, tag: "silver"}]}, {b: 18, cust: {age: -25, tier: "Gold"}, items: [{price: 100, qty: -25, tag: "b"}, {qty: 1000000000000000000000, tag: "silver"}], nums: []}], + [{nums: [7, 11, 7, 18, 0.1], cust: [{age: 3}], b: null, items: [{price: [1], qty: 90, tag: "gold"}]}, {cust: [{age: 3}], items: [{price: [1], qty: 90, tag: "gold"}], nums: [7, 11, 7, 18, 0.1]}], + ], +} + +{ + name: "gb070: 8 nodes, switch, table*, switch, expr, expr, expr, expr, table", + graph: { + nodes: [ + {switch: "s1", when: ["(not (code != null)) and ((tier ?? 'none') + '' + s == 'x')"]}, + {table: "t2", hit: "collect", inputs: ["string(price <= 0)"], outputs: ["res.k962", "g.k963"], outputPath: "res", rules: [ + ["'a'", "'low'", "'high'"], + ["not('silver')", "'mid'", "'mid'"], + ]}, + {switch: "s3", when: ["n * max([3, 2.25]) != (price ?? 1) * (n ?? -1) * max(nums ?? [0])", "n >= price", ""]}, + {expression: "e4", fields: { + "m.k964": "null", + "res.k962": "0", + k966: "(-4 + 100 in [-5..5])", + }}, + {expression: "e5", passThrough: true, fields: { + "m.k967": "max([(len('A-1')), 0])", + k968: "-((1 + 0.5) / 10)", + k969: "(2.25)", + k970: "a != null", + }}, + {expression: "e6", outputPath: "res", fields: { + "res.k971": "not ((n ?? 1) != len(nums ?? []))", + }}, + {expression: "e7", fields: { + k972: "m.k967 ?? k969", + k973: "`${(m.k967 ?? -1)}-${'x'}`", + k974: "(m.k967 ?? 0)", + k975: "0.5 != (false ? ($.k974 ?? -1) % 2 : min([3, m.k967]))", + }}, + {table: "t8", inputs: ["0", "upper(string(res.res.k971))", "''"], outputs: ["k976"], passThrough: true, outputPath: "o.p", rules: [ + [">= 21", "'gold', 'b'", "not('silver')", "false"], + ["<= 4", "", "$ != ''", "((0.5) <= 2.25)"], + ["$ > 10 and $ < 11", "not('gold')", "", "true"], + [">= 21", "'gold'", "'x'", "true"], + ["(0..50)", "null", "'', 'gold'", "false"], + ["", "", "", "false"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> t2", + "s1:0 -> s3", + "t2 -> e4", + "t2 -> e5", + "s1:0 -> e6", + "e4 -> e6", + "e5 -> e7", + "e6 -> t8", + "t2 -> output", + "s3:0 -> output", + "s3:1 -> output", + "s3:2 -> output", + "e4 -> output", + "e6 -> output", + "e7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{price: 7, nums: [3, 100], code: "", tier: "b", n: null, s: "bronze"}, {}], + [{price: 99, nums: [2.5, 2, 18], code: "a", tier: "a", n: null, s: "a", extra: 1}, {}], + [{price: 1000, nums: [11], code: "gold", tier: null, n: 3, s: "x"}, {}], + [{price: 7, nums: [], code: "b", tier: "x", n: 0.1, s: "a"}, {}], + [{price: true, nums: null, code: "silver", n: 1, s: "b"}, {}], + [{price: 50, code: "Gold", tier: "x", n: 1, s: "Gold"}, {}], + [{nums: [5, 10, 101, 70, 1000], code: "gold", tier: null, n: 7}, {}], + [{price: 100, nums: [], code: "Gold", tier: "gold ", n: [1], s: "zz"}, {}], + [{price: 10, nums: [18], code: "a", tier: "gold ", n: 19.99, s: "bronze"}, {}], + [{price: 2, nums: [1000], code: "Gold", tier: "gold", n: 50, s: "x"}, {}], + [{price: 0, nums: [], code: "gold ", tier: null, n: 100, s: null}, {}], + [{price: 2.5, nums: [-25, 101], code: "", tier: "x", n: 99, s: "b"}, {}], + [{price: 11, nums: ["1", 2], tier: "gold ", n: 50, s: "zz"}, {}], + [{price: -25, nums: [], code: "gold", tier: "zz", n: 101, s: "gold"}, {}], + [{price: -1, nums: [5, 0], code: true, tier: "bronze", n: null}, {}], + [{price: true, nums: [], code: "zz", tier: "a", n: 1, s: "x"}, {}], + [{price: 0.5, nums: [1000, 18, 0.5], code: {t: "x"}, tier: "a", n: 0.1, s: "a"}, {}], + ], +} + +{ + name: "gb071: 8 nodes, table*, loop table, table*, expr, expr, expr, switch, table*", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["(2.25 in [1..100] ? (true ? 'x' : cust.tier) : 'x')", "code", "score"], outputs: ["k977[]", "k978"], outputPath: "out", rules: [ + ["null", "", "", "'mid'", "((a != null) and ((score ?? 1) in [-5..5]))"], + ["$ != 'x'", "$ != 'x'", "[100..110)", "'gold'", "false"], + ["null", "'x'", "[10..15]", "''", "false"], + ["", "not('silver')", "-1, 49", "'mid'", "(true ? (n ?? 0) : 0) + 1 * 2 in [0..10]"], + ["not('x')", "", "[18..23]", "'mid'", "false"], + ]}, + {table: "t2", inputField: "items", executionMode: "loop", inputs: ["((qty ?? 1))", "qty"], outputs: ["g.k979", "k977"], outputPath: "res", rules: [ + ["> 1", "> 18", "false", "string((qty ?? price ?? 0))"], + ["null", "[21..22)", "false", "'low'"], + ["< 0", "null", "not ((true ? (price ?? 1) : (qty ?? 0)) != ((price ?? -1)))", "''"], + ["null", ">= 10", "(3) == ((price ?? qty ?? 0))", "'high'"], + ["[0..5]", "!= 18", "false", "'high'"], + ]}, + {table: "t3", hit: "collect", inputs: ["10", "'x'", null], outputs: ["g.k979", "g.k982"], passThrough: true, outputPath: "res", rules: [ + ["null", "", "null", "''", "string(0.5 * 1 * 10)"], + ["(10..15)", "null", "", "''", "'high'"], + ["", "", "", "'high'", "''"], + ]}, + {expression: "e4", passThrough: true, outputPath: "res", fields: { + "g.k979": "null", + k978: "-4 in [-5..5]", + }}, + {expression: "e5", passThrough: true, outputPath: "out", fields: { + "res.k985": "null", + k986: "2.25", + "res.k987": "100 + (a == null ? ($.k986 ?? 1) : 0 * ($.k986 ?? 1))", + k988: "$.k986", + }}, + {expression: "e6", passThrough: true, outputPath: "o.p", fields: { + "g.k989": "null", + }}, + {switch: "s7", when: ["((0 ?? res.g.k979 ?? 0) > -(3))", "not (not (-4 != 10))", "(3 in [0..10]) and (not (res.k978))", ""]}, + {table: "t8", hit: "collect", inputs: ["'none'", "string(true) + ':' + 'none'", "upper('A-1')"], outputs: ["m.k990", "g.k991"], passThrough: true, outputPath: "res", rules: [ + ["", "$ != 'gold'", "null", "('' in ['gold', 'silver', 'a'] ? -(3) : 10 % 7) - ceil((0 ?? res.g.k979 ?? 0))", "10"], + ["'silver', 'bronze'", "$ != 'x'", "'a', 'bronze'", "10", "10"], + ["'x', 'bronze'", "$ != 'silver'", "not('')", "len(string(not ((res.k978 ?? false))))", "0"], + ["$ != ''", "not('a')", "'a'", "3", "2"], + ]}, + ], + edges: [ + "input -> t1", + "input -> t2", + "t2 -> t3", + "t1 -> e4", + "t2 -> e4", + "t3 -> e5", + "t2 -> e5", + "t3 -> e6", + "t2 -> e6", + "t3 -> s7", + "e4 -> s7", + "s7:1 -> t8", + "e5 -> output", + "e6 -> output", + "s7:0 -> output", + "s7:3 -> output", + "t8 -> output", + ], + }, + cases: [ + [{b: 0.5, cust: {age: 19.99, tier: "Gold", active: true}, items: [{price: 3, qty: 10, tag: "bronze"}], nums: [19.99, 2, 0.5, 50, 5], score: 21, n: 99, code: "Gold"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 2.5, items: [{price: 3, qty: 50, tag: "zz"}, {price: 1000, qty: 5}], nums: [5, 1000], score: -1, n: 18, code: ""}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 0.1, cust: {age: -25, tier: "a", active: false}, items: [{price: 7, qty: 0.5, tag: "x"}, {price: 99, tag: "bronze"}, {qty: 1, tag: "silver"}, {price: 18, qty: 2.5, tag: "bronze"}], nums: [101, 1], score: 5, n: 10, code: "b"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 10, cust: {age: 1, tier: "x", active: false}, items: [{price: 1, tag: "gold "}, {price: -0.1, qty: 2, tag: "x"}], nums: [], score: 101, n: 50, extra: "e"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 49, cust: {age: 2, tier: "b", active: true}, items: [{qty: null, tag: "silver"}, {price: 0, qty: 2.5}, {price: 21, qty: 19.99, tag: "zz"}], nums: [101, -0.1, 1, 1000000000000000000000, 2.5], score: 1000, n: 2, code: "bronze", extra: 1}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 7, cust: {age: -25, tier: "", active: true}, items: null, nums: [3, 0.5, 1, 21, 21], score: 1000, n: 10, code: "a"}, "!error"], + [{b: null, items: [{price: 5, qty: 11, tag: "gold"}], nums: [11, -25, 0.5], score: 19.99, n: 0.1, code: "zz"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: null, cust: {tier: "silver", active: true}, items: [{price: 21, qty: 2.5, tag: "zz"}], nums: null, score: 1, n: 21, code: "b"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: -1, cust: {age: 19.99, tier: "bronze", active: true}, items: [], score: 18, code: null}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 1000000000000000000000, cust: {age: 0.1, tier: "silver", active: true}, items: [{price: null, qty: null, tag: null}, {price: 0.1, qty: 100, tag: "bronze"}, {price: 2, qty: 11, tag: "bronze"}, {price: 2.5, qty: 1000}], nums: [-1, 19.99, 1], n: 11, code: "Gold"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: -0.1, cust: {age: 1000000000000000000000, tier: "zz", active: true}, items: [{price: null, qty: -25, tag: "x"}, {price: -7, qty: 2, tag: "gold"}], nums: [-12, 7], score: 50, n: null, code: ""}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 1000, items: [{price: 102, qty: -0.1, tag: "a"}, {price: 101, qty: 101, tag: "Gold"}], nums: [], n: 0, code: "zz"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{cust: {age: -25, tier: "gold ", active: true}, items: null, nums: [18, 100, 7], score: 100, n: 0.5, code: "Gold"}, "!error"], + [{b: 50, cust: {age: 100, tier: "b", active: false}, items: [], nums: [21, -1], score: null, n: 21, code: "a"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 43, cust: {age: 0.5, tier: "", active: true}, items: null, nums: null, score: 99, n: 50, code: "gold "}, "!error"], + [{cust: {age: 21, tier: "zz", active: false}, items: [{qty: null, tag: "a"}, {price: 5, qty: 2, tag: "a"}], nums: [10], score: 21, n: 50, code: "b"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 5, cust: {age: null, tier: "Gold", active: false}, items: [], nums: [-1, 1, -0.1, 19.99, 1000], score: 11, n: 2.5, code: "x"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 1000, cust: {age: 19.99, tier: "bronze", active: true}, items: [{price: null, qty: -25, tag: "silver"}, {price: 0.1, qty: 3, tag: "silver"}], nums: [101, 0.1, 1], score: 101, n: 3, code: "x"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 0.5, cust: {age: null, tier: "gold", active: false}, items: [{qty: 19.99, tag: "x"}, {qty: 2, tag: "silver"}, {price: 50, qty: 1, tag: "gold"}, {price: 99, qty: 21, tag: "silver"}], nums: null, score: 5, n: 7, code: "zz"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 2.5, cust: {tier: "a", active: true}, items: null, nums: [5, 3, 2, 50, 5], score: null, code: "silver", extra: "e"}, "!error"], + [{b: 0, cust: {age: 42, tier: "", active: false}, items: [{price: 0.1, qty: 99, tag: "gold"}, {price: null, qty: 1, tag: "a"}, {price: -25, qty: 18, tag: "b"}], nums: [], score: 11, n: 19.99, code: "a"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 3, cust: {age: 1000, tier: "a", active: true}, items: [{price: -25, qty: 89, tag: ""}, {price: 101, tag: null}], nums: [-25], score: 100, n: 21, code: "gold "}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 99, cust: {age: 11, active: true}, items: [{price: 2.5, qty: 1, tag: "Gold"}, {price: 0.5, qty: 101}], nums: [1000, -25], score: -0.1, n: 21, code: "bronze"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: 1, cust: {age: 1, tier: "zz", active: true}, items: [{price: 3, qty: 101}, {price: 18, qty: 7, tag: "gold"}, {price: -0.1, qty: 29, tag: ""}], nums: [1000, 10, 21], score: 0, n: 0.5, code: "x"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + [{b: -1, cust: {age: 3, tier: null, active: false}, items: [{price: 18, qty: 3}, {price: 0.1, qty: 99, tag: "gold"}], nums: [], score: 7, n: 1000000000000000000000, code: "a"}, {o: {p: {g: {k989: null}}}, out: {k986: 2.25, k988: 2.25, res: {k985: null, k987: 102.25}}, res: [{g: {k979: "high", k982: ""}}]}], + ], +} + +{ + name: "gb072: 8 nodes, expr, switch, switch, expr, expr, table*, expr, table*", + graph: { + nodes: [ + {expression: "e1", fields: { + k992: "false", + }}, + {switch: "s2", when: ["3 + (a ?? 1) * (cust.age ?? 1) * (a ?? 1) in [0..10]", "(-4 - (b ?? -1) > 10) and (false)"]}, + {switch: "s3", when: ["not ((b ?? -1) in [1..100])", ""]}, + {expression: "e4", inputField: "cust", fields: { + k993: "tier == 'silver'", + "g.k994": "string(((age ?? 0) >= (age ?? -1)))", + "g.k995": "$.k993 ?? tier", + }}, + {expression: "e5", inputField: "cust", fields: { + k997: "((3) / 4 + -4)", + k998: "($.k997 ?? -1) * round((age) / 10)", + k999: "abs(2.25) * (age != null ? age * (age ?? 0) : age + (age ?? -1))", + }}, + {table: "t6", hit: "collect", inputField: "cust", inputs: ["active"], outputs: ["k1000", "k1001"], passThrough: true, rules: [ + ["$ == true", "true", "((false ? (age ?? -1) : 1)) * -(((age ?? -1)))"], + ["false", "true", "0"], + ["", "true", "10"], + ["false", "true", "-5"], + ]}, + {expression: "e7", passThrough: true, fields: { + k1002: "(((b ?? 1) + (cust.age ?? 0)) / 0.5)", + }}, + {table: "t8", hit: "collect", inputs: ["a"], outputs: ["k1003[]"], passThrough: true, outputPath: "out", rules: [ + ["> 0", "ceil(2 * (b ?? 0) + 10)"], + ["[21..22]", "max(nums ?? [0])"], + ["null", "0.25"], + ["!= 100", "100"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "input -> s2", + "s2:0 -> s3", + "input -> s3", + "s2:1 -> e4", + "input -> e5", + "s2:0 -> t6", + "s3:1 -> e7", + "e7 -> t8", + "e4 -> output", + "e5 -> output", + "t6 -> output", + "t8 -> output", + ], + }, + cases: [ + [{b: 7, flag: true, tier: "zz", cust: {age: 10}, a: 11, nums: [], s: ""}, {a: 11, b: 7, cust: {age: 10}, flag: true, k1002: 34.0, k997: -3.25, k998: -3.25, k999: 225.00, nums: [], out: [{k1003: 24}, {k1003: 100}], s: "", tier: "zz"}], + [{b: 1000000000000000000000, flag: false, tier: "silver", cust: {age: 3, tier: "Gold", active: true}, a: 99, nums: null, s: "bronze"}, {k997: -3.25, k998: 0, k999: 20.25}], + [{b: 5, flag: false, tier: "a", cust: {age: 0.1, tier: "silver"}, a: 19.99, nums: [0.5, 1000000000000000000000, 0, 50, -1]}, {a: 19.99, b: 5, cust: {age: 0.1, tier: "silver"}, flag: false, k1002: 10.20, k997: -3.25, k998: 0, k999: 0.0225, nums: [0.5, 1000000000000000000000, 0, 50, -1], out: [{k1003: 20}, {k1003: 100}], tier: "a"}], + [{b: -25, flag: false, tier: {t: "x"}, cust: {age: 101, tier: "gold ", active: false}, a: 0.5, nums: [10, 2, 18], s: "zz"}, {k997: -3.25, k998: -32.50, k999: 22952.25}], + [{b: 7, flag: false, tier: "a", cust: {age: 1, tier: null, active: true}, a: 100, nums: [], s: null}, {a: 100, b: 7, cust: {active: true, age: 1, tier: null}, flag: false, k1002: 16.0, k997: -3.25, k998: 0, k999: 2.25, nums: [], out: [{k1003: 24}], tier: "a"}], + [{b: 18, flag: false, tier: "b", cust: {age: 21, tier: "gold ", active: null}, a: 19.99, nums: 7, s: "Gold"}, {a: 19.99, b: 18, cust: {active: null, age: 21, tier: "gold "}, flag: false, k1002: 78.0, k997: -3.25, k998: -6.50, k999: 992.25, nums: 7, out: [{k1003: 46}, {k1003: 100}], s: "Gold", tier: "b"}], + [{flag: false, tier: "", cust: {age: 2.5, tier: "gold", active: false}, a: 1000000000000000000000, nums: [18], s: "x", extra: 1}, {k997: -3.25, k998: 0, k999: 14.0625}], + [{b: -0.1, flag: true, tier: "Gold", cust: {age: 21, tier: "gold ", active: true}, a: 99, nums: [101, 99], s: "bronze"}, {k997: -3.25, k998: -6.50, k999: 992.25}], + [{b: null, flag: true, tier: "gold ", cust: {age: -0.1, tier: "a", active: true}, a: 7, nums: 7, s: null}, {k997: -3.25, k998: 0, k999: 0.0225}], + [{b: 7, flag: true, tier: "gold", cust: {age: 0, tier: "x", active: false}, a: 0, s: {t: "x"}}, {k997: -3.25, k998: 0, k999: 0}], + [{b: 1000000000000000000000, flag: false, tier: "Gold", cust: {age: 0.1, tier: "a", active: "no"}, a: 10, nums: [2.5, -1], s: "b"}, {k997: -3.25, k998: 0, k999: 0.0225}], + [{b: 2, flag: false, tier: "x", cust: {age: null, tier: "x", active: false}, a: "5", nums: [5, 19.99, 1, 0, 50], s: "gold "}, "!error"], + [{b: 101, flag: true, tier: "bronze", cust: {age: -0.1, tier: "gold ", active: true}, a: 21, nums: [0], s: null}, {k997: -3.25, k998: 0, k999: 0.0225}], + [{b: 1000000000000000000000, flag: null, tier: "", cust: {age: 1000, tier: "bronze", active: true}, a: 2.5, nums: [2, 0, -1, 99, -25], s: "Gold"}, {k997: -3.25, k998: -325.00, k999: 2250000.00}], + [{b: 11, flag: true, tier: ["gold"], cust: {age: 2, tier: "bronze", active: true}, a: 7, nums: [{x: 1}], s: ""}, {a: 7, b: 11, cust: {active: true, age: 2, tier: "bronze"}, flag: true, k1002: 26.0, k997: -3.25, k998: 0, k999: 9.00, nums: [{x: 1}], out: [{k1003: 32}, {k1003: 100}], s: "", tier: ["gold"]}], + [{b: 101, flag: true, cust: {age: 1000, tier: "a", active: true}, a: 0.1, nums: [50, 7], s: "", extra: {deep: {x: 1}}}, {k997: -3.25, k998: -325.00, k999: 2250000.00}], + ], +} + +{ + name: "gb073: 12 nodes, expr, switch, table, switch*, switch*, switch*, switch, table*, table, expr, expr, table", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: { + "m.k1004": "(true ? ((true) and (false) ? (score ?? 0) * (n ?? 0) : (false ? (n ?? 1) : (score ?? 1))) : (score ?? 1))", + }}, + {switch: "s2", when: ["not ((m.k1004 ?? -1) % 7 <= 1)", "string(len('none')) in ['gold', 'silver', 'a']", "score % 2 + (m.k1004 ?? -1) in [-5..5]", ""]}, + {table: "t3", inputs: ["score", "code", "m.k1004"], outputs: ["k1005", "k1005"], rules: [ + ["> 100", "", "(21..71)", "-5", "true"], + ["<= 11", "not('')", ">= 50", "(tier != null ? ceil((m.k1004 ?? 0)) * ((m.k1004 ?? -1)) / 10 : 0)", "true"], + ["!= 100", "", "[-1..4]", "2", "true"], + ["", "", "(1..2)", "100", "false"], + ["not(18)", "$ != 'a'", "not(-1)", "ceil(((n ?? -1)))", "false"], + ]}, + {switch: "s4", hit: "collect", when: ["true", ""]}, + {switch: "s5", hit: "collect", when: ["(tier ?? '?') in ['gold', 'silver', 'a']"]}, + {switch: "s6", hit: "collect", when: ["(false ? 2 : 2.25) * 0.5 == ((-4))", "('A-1' in ['gold', 'silver', 'a']) or (('gold' == 'gold') and ('' in ['gold', 'silver', 'a']))", "endsWith(string(not (true)), 'x')", ""]}, + {switch: "s7", when: ["false", ""]}, + {table: "t8", hit: "collect", inputs: ["string(not ((k1005 ?? false)))", "(1 + 3)"], outputs: ["k1007"], outputPath: "lines", rules: [ + ["", "[18..23]", "false"], + ["", "> 18", "false"], + ["$ != 'silver'", "", "false"], + ["not('x')", "", "true"], + ["'a', 'bronze'", "$ > 0 and $ < 1", "true"], + ["", "", "true"], + ]}, + {table: "t9", inputs: ["(3) % 2", "k1005", "k1005"], outputs: ["k1008"], rules: [ + ["null", "$ == true", "null", "true"], + ["[-1..0)", "$ == true", "", "false"], + ["", "", "true", "false"], + ]}, + {expression: "e10", passThrough: true, outputPath: "lines", fields: { + k1009: "null", + "g.k1010": "null", + k1011: "floor($nodes.e1.m.k1004 * 100) - (max([-4, 0.5]))", + k1012: "len('x') + ((($nodes.t3.k1005 ?? 1)))", + }}, + {expression: "e11", fields: { + k1005: "upper('') == 'x'", + k1014: "endsWith(trim('gold'), '')", + }}, + {table: "t12", inputs: ["'none' + ':' + `n=${0}-${'none'}`", "k1005"], outputs: ["m.k1015", "g.k1016"], outputPath: "res", rules: [ + ["null", "$ == true", "0", "''"], + ["null", "false", "0", "'mid'"], + ["$ != ''", "", "0.25", "'low'"], + ["'a'", "$ == true", "2", "'x'"], + ["'silver', 'bronze'", "", "1", "'mid'"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> s2", + "input -> s2", + "s2:1 -> t3", + "s2:2 -> t3", + "s2:1 -> s4", + "s2:3 -> s5", + "t3 -> s6", + "s6:2 -> s7", + "s7:1 -> t8", + "s7:1 -> t9", + "t8 -> e10", + "e10 -> e11", + "s7:0 -> t12", + "s2:0 -> output", + "s4:0 -> output", + "s4:1 -> output", + "s5:0 -> output", + "s6:0 -> output", + "s6:3 -> output", + "t9 -> output", + "e11 -> output", + "t12 -> output", + ], + }, + cases: [ + [{nums: [1, 5], code: "Gold", score: -25, tier: "gold", n: 19.99, items: [{price: 10, qty: 21, tag: "zz"}]}, {code: "Gold", items: [{price: 10, qty: 21, tag: "zz"}], m: {k1004: -25}, n: 19.99, nums: [1, 5], score: -25, tier: "gold"}], + [{nums: [], code: "", score: 11, tier: "silver", n: 50, items: [{price: 1, qty: 2, tag: "bronze"}], extra: {deep: {x: 1}}}, {code: "", extra: {deep: {x: 1}}, items: [{price: 1, qty: 2, tag: "bronze"}], m: {k1004: 11}, n: 50, nums: [], score: 11, tier: "silver"}], + [{nums: [0], code: "bronze", score: 101, tier: "b", n: 21, items: [{price: 100, qty: 21, tag: "silver"}, {price: 0.1, qty: 99, tag: "zz"}, {price: 101, qty: null, tag: "b"}]}, {code: "bronze", items: [{price: 100, qty: 21, tag: "silver"}, {price: 0.1, qty: 99, tag: "zz"}, {price: 101, qty: null, tag: "b"}], m: {k1004: 101}, n: 21, nums: [0], score: 101, tier: "b"}], + [{nums: [18, 50], code: "", tier: "bronze", n: 5, items: [{price: 100, qty: 18, tag: "silver"}, {price: 0.5, qty: 99, tag: ""}, {price: 101, qty: 21, tag: ""}], extra: [1, 2]}, {}], + [{nums: [-0.1, 0.1], code: "silver", score: 18, tier: null, items: [{price: 50, qty: null}, {price: 100, qty: 19.99, tag: "gold "}]}, {code: "silver", items: [{price: 50, qty: null}, {price: 100, qty: 19.99, tag: "gold "}], m: {k1004: 18}, nums: [-0.1, 0.1], score: 18}], + [{nums: [3, 78, 81], code: "gold", score: 0.1, tier: "x", n: 2, items: [{price: 1000000000000000000000, qty: 1000, tag: ""}, {qty: 3, tag: null}]}, {k1005: true}], + [{nums: [10, 5, 0.1, 100, 0.5], code: "silver", score: 50, tier: "a", items: [{price: 10, qty: 5, tag: null}, {price: 2, qty: 11, tag: "bronze"}]}, {code: "silver", items: [{price: 10, qty: 5, tag: null}, {price: 2, qty: 11, tag: "bronze"}], m: {k1004: 50}, nums: [10, 5, 0.1, 100, 0.5], score: 50, tier: "a"}], + [{nums: [], code: "x", tier: "b", items: [{price: 21, qty: 2, tag: "b"}, {price: 2.5, tag: "a"}]}, {}], + [{nums: [], code: "silver", score: 101, tier: "zz", n: 11, items: [{price: 19.99, qty: -0.1, tag: "Gold"}, {price: 0, qty: 2}, {price: -1, tag: "gold"}]}, {code: "silver", items: [{price: 19.99, qty: -0.1, tag: "Gold"}, {price: 0, qty: 2}, {price: -1, tag: "gold"}], m: {k1004: 101}, n: 11, nums: [], score: 101, tier: "zz"}], + [{code: "x", score: 100, tier: "silver", n: 1000, items: [{price: 1, qty: 31, tag: "bronze"}, {price: 0, qty: 1, tag: "zz"}, {qty: -0.1, tag: "a"}, {price: 0.1, qty: 1000, tag: ""}]}, {code: "x", items: [{price: 1, qty: 31, tag: "bronze"}, {price: 0, qty: 1, tag: "zz"}, {qty: -0.1, tag: "a"}, {price: 0.1, qty: 1000, tag: ""}], m: {k1004: 100}, n: 1000, score: 100, tier: "silver"}], + [{nums: [100], score: 19.99, tier: "gold ", n: 7, items: [{price: null, qty: -1, tag: "gold "}, {price: null, qty: 5, tag: ""}]}, {items: [{price: null, qty: -1, tag: "gold "}, {price: null, qty: 5, tag: ""}], m: {k1004: 19.99}, n: 7, nums: [100], score: 19.99, tier: "gold "}], + [{nums: [-0.1, 11, 7], code: "", score: -0.1, tier: "a", n: -1, items: [{price: -1, qty: 21, tag: ""}, {price: 21, qty: 18, tag: "gold"}]}, {k1005: true}], + [{nums: null, code: "silver", score: 101, tier: "Gold", n: 7, items: [{price: 11, qty: 1000, tag: "a"}, {price: 18, qty: 0}, {price: 10, qty: 1, tag: ""}, {price: 19.99, qty: 21, tag: "silver"}]}, {code: "silver", items: [{price: 11, qty: 1000, tag: "a"}, {price: 18, qty: 0}, {price: 10, qty: 1, tag: ""}, {price: 19.99, qty: 21, tag: "silver"}], m: {k1004: 101}, n: 7, score: 101, tier: "Gold"}], + [{nums: [], score: 50, tier: "gold ", n: 101, items: [{price: 11, qty: 2, tag: "bronze"}, {price: -1, qty: 1, tag: "silver"}, {price: 0, tag: "gold "}]}, {}], + [{nums: [], code: "Gold", score: null, tier: null, n: 5, items: []}, {}], + [{nums: [19.99, 50, 1], code: "a", score: 54, tier: "Gold", items: [{price: 1000, qty: 101, tag: "gold"}, {price: 99, qty: 7, tag: "x"}, {price: 11, qty: 100, tag: "gold"}, {price: 99, qty: 50, tag: "b"}], extra: "e"}, {code: "a", extra: "e", items: [{price: 1000, qty: 101, tag: "gold"}, {price: 99, qty: 7, tag: "x"}, {price: 11, qty: 100, tag: "gold"}, {price: 99, qty: 50, tag: "b"}], m: {k1004: 54}, nums: [19.99, 50, 1], score: 54, tier: "Gold"}], + [{nums: null, code: "b", score: 21, tier: null, n: 2.5, items: [{price: null, qty: 11, tag: "gold"}], extra: [1, 2]}, {}], + [{nums: [], code: "Gold", score: 2.5, tier: "", n: -15, items: []}, {code: "Gold", items: [], m: {k1004: 2.5}, n: -15, nums: [], score: 2.5, tier: ""}], + [{nums: [], code: "zz", score: 11, n: 2.5, items: [{price: 50, qty: -0.1, tag: "Gold"}, {price: 10, qty: 101, tag: ""}, {price: 1000000000000000000000, qty: 3, tag: "b"}], extra: 1}, {code: "zz", extra: 1, items: [{price: 50, qty: -0.1, tag: "Gold"}, {price: 10, qty: 101, tag: ""}, {price: 1000000000000000000000, qty: 3, tag: "b"}], m: {k1004: 11}, n: 2.5, nums: [], score: 11}], + [{nums: [0.5], score: 21, tier: "b", n: 18, items: [{price: 50, qty: -25, tag: "gold"}, {price: 0.5, qty: 101, tag: ""}, {price: 21, qty: 5, tag: "bronze"}, {price: 0.1, qty: 0.5, tag: "x"}], extra: 1}, {}], + [{nums: [], score: 1, tier: "Gold", n: null, items: []}, {k1005: true}], + [{code: "bronze", score: 2, tier: "bronze", items: [{price: -1, qty: 11, tag: "x"}, {price: 3, qty: -1, tag: "silver"}]}, {code: "bronze", items: [{price: -1, qty: 11, tag: "x"}, {price: 3, qty: -1, tag: "silver"}], m: {k1004: 2}, score: 2, tier: "bronze"}], + [{nums: [7, 5, 0.5], code: "gold", score: -1, tier: "gold", n: 1, items: [{price: null, qty: 101, tag: "silver"}]}, {k1005: true}], + [{nums: [101, -3, 10], code: "zz", score: 100, tier: "b", items: [{price: 99, qty: -1, tag: "x"}, {price: 84, qty: 10, tag: "silver"}, {price: 11, qty: 1, tag: "x"}]}, {code: "zz", items: [{price: 99, qty: -1, tag: "x"}, {price: 84, qty: 10, tag: "silver"}, {price: 11, qty: 1, tag: "x"}], m: {k1004: 100}, nums: [101, -3, 10], score: 100, tier: "b"}], + [{nums: [], code: "", score: 100, tier: "b", n: 50, items: []}, {code: "", items: [], m: {k1004: 100}, n: 50, nums: [], score: 100, tier: "b"}], + [{nums: [99], code: "b", score: 18, tier: "Gold", n: 19.99, items: [{price: null, qty: -25, tag: "Gold"}], extra: [1, 2]}, {code: "b", extra: [1, 2], items: [{price: null, qty: -25, tag: "Gold"}], m: {k1004: 18}, n: 19.99, nums: [99], score: 18, tier: "Gold"}], + [{nums: [0.5, 0.1, 2], code: "gold ", score: 18, n: 1000, items: [{price: -0.1, qty: 7, tag: "gold"}, {price: 100, qty: 0, tag: "silver"}, {price: 11, qty: 11, tag: "gold "}, {price: 3, tag: "b"}]}, {code: "gold ", items: [{price: -0.1, qty: 7, tag: "gold"}, {price: 100, qty: 0, tag: "silver"}, {price: 11, qty: 11, tag: "gold "}, {price: 3, tag: "b"}], m: {k1004: 18}, n: 1000, nums: [0.5, 0.1, 2], score: 18}], + [{nums: [1000, 99, 2, 5, 20], code: "Gold", score: 5, tier: "silver", n: -1, items: []}, {code: "Gold", items: [], m: {k1004: 5}, n: -1, nums: [1000, 99, 2, 5, 20], score: 5, tier: "silver"}], + ], +} + +{ + name: "gb074: 10 nodes, loop expr, switch*, expr, expr, table, switch, loop table, expr, switch*, table", + graph: { + nodes: [ + {expression: "e1", inputField: "items", executionMode: "loop", outputPath: "out", fields: { + "g.k1017": "max([round(min([(qty ?? 1), (qty ?? 0)])), -((price ?? 1)) * price * qty])", + k1018: "true", + }}, + {switch: "s2", hit: "collect", when: ["true", "contains((code ?? 'none'), 'a')", "startsWith('A-1', 'a')", ""]}, + {expression: "e3", passThrough: true, fields: { + "m.k1019": "(price ?? 1) * (price ?? 1) % 7 + (price ?? -1)", + k1020: "price ?? n", + }}, + {expression: "e4", fields: { + k1018: "abs(price)", + "m.k1019": "m.k1019 ?? n", + k1023: "(n ?? -1) % 2", + }}, + {table: "t5", inputs: ["(100 in [0..10] ? (true ? (tier ?? 'none') : (code ?? '')) : string(false))", "price", "price"], outputs: ["m.k1024"], passThrough: true, rules: [ + ["null", "not(5)", "21, 26", "true"], + ["$ != 'x'", "[5..6)", "", "true"], + ]}, + {switch: "s6", when: ["(price ?? price ?? 0) - n * price >= 1", "((false) or (false) ? n : (price ?? 1) + n) == ((price ?? 1)) / 10", "count(items ?? [], (#.qty ?? 0) > 1) in [0..10]", ""]}, + {table: "t7", inputField: "items", executionMode: "loop", inputs: ["price", "tag"], outputs: ["k1018"], passThrough: true, outputPath: "out", rules: [ + ["null", "", "''"], + ["< 0", "'x', 'bronze'", "(tag ?? 'none')"], + ["null", "startsWith($, 'g')", "'high'"], + ["", "", "string((1))"], + ["!= 100", "startsWith($, 's')", "'high'"], + ["null", "null", "lower(string(true)) + '-' + (tag ?? '?')"], + ]}, + {expression: "e8", passThrough: true, fields: { + "m.k1026": "price ?? price", + "m.k1027": "(string(true) != 'x' ? (items ?? [])[0].tag ?? 'none' : lower((tier ?? '?')) + '-' + (code ?? 'none'))", + k1028: "(((n ?? 1)) / 3 < abs((n ?? -1))) and (false)", + k1029: "((price ?? -1))", + }}, + {switch: "s9", hit: "collect", when: ["false", "true", ""]}, + {table: "t10", inputs: ["code", "price", "price"], outputs: ["k1030"], passThrough: true, rules: [ + ["'silver'", "21, 26", "(18..19)", "true"], + ["'silver', 'gold'", "", "[10..11)", "true"], + ["", "> 1", "[0..1]", "(contains('none', 'a')) and ((0.5 == -4) and (false))"], + ["'a', 'gold'", "[21..26]", "[1..2]", "false"], + ["$ != 'gold'", "[5..15)", "$ > 0 and $ < 50", "false"], + ["not('silver')", "not(50)", "50, 100", "true"], + ["", "", "", "false"], + ]}, + ], + edges: [ + "input -> e1", + "input -> s2", + "s2:1 -> e3", + "e3 -> e4", + "s2:2 -> t5", + "s2:1 -> s6", + "s6:1 -> t7", + "t7 -> e8", + "s6:2 -> s9", + "s9:0 -> t10", + "e1 -> output", + "s2:0 -> output", + "e4 -> output", + "t5 -> output", + "s6:0 -> output", + "s6:3 -> output", + "e8 -> output", + "s9:1 -> output", + "s9:2 -> output", + "t10 -> output", + ], + }, + cases: [ + [{n: 101, price: 19.99, code: "b", items: [{price: 101, qty: 0.5, tag: "gold"}, {price: 1000, tag: "bronze"}, {price: 100, qty: null, tag: "b"}, {price: 7, qty: 5, tag: "zz"}], tier: "bronze"}, "!error"], + [{n: 18, price: -0.1, code: true, tier: "b"}, "!error"], + [{n: 100, price: 101, code: "x", items: [{price: 1000000000000000000000, qty: 1000, tag: "x"}, {price: -25, qty: 11, tag: null}]}, "!error"], + [{price: 0.5, code: "bronze", items: [], tier: "x", extra: "e"}, {code: "bronze", extra: "e", items: [], out: [], price: 0.5, tier: "x"}], + [{n: null, price: 0, code: "x", items: [{price: 1, qty: 5, tag: "silver"}, {price: 19.99, qty: 10, tag: "zz"}], tier: "Gold", extra: "e"}, {code: "x", extra: "e", items: [{price: 1, qty: 5, tag: "silver"}, {price: 19.99, qty: 10, tag: "zz"}], out: [{g: {k1017: 5}, k1018: true}, {g: {k1017: 10}, k1018: true}], price: 0, tier: "Gold"}], + [{n: 1, price: 1, code: "zz", items: [{price: 50, qty: [1], tag: "zz"}, {price: 1000, qty: 100, tag: "silver"}, {price: 10, qty: null, tag: "zz"}, {price: 2.5, qty: 63, tag: "zz"}], tier: null}, "!error"], + [{n: 1000000000000000000000, price: 100, code: "bronze", items: [], tier: "gold "}, {code: "bronze", items: [], n: 1000000000000000000000, out: [], price: 100, tier: "gold "}], + [{n: 2.5, price: 99, code: "gold", items: [], tier: "a"}, {code: "gold", items: [], n: 2.5, out: [], price: 99, tier: "a"}], + [{n: 101, price: -0.1, code: "gold", items: []}, {code: "gold", items: [], n: 101, out: [], price: -0.1}], + [{n: 0.5, price: 0.1, code: "zz", items: [], tier: "zz"}, {code: "zz", items: [], n: 0.5, out: [], price: 0.1, tier: "zz"}], + [{n: 50, price: 21, code: "bronze", items: [{price: 19.99, qty: 1000000000000000000000, tag: "bronze"}, {price: null, qty: -1, tag: "b"}, {price: -0.1, qty: 0.5, tag: "gold "}], tier: "zz"}, "!error"], + [{n: 1000, price: 0, code: "b", items: [], tier: "gold"}, {code: "b", items: [], n: 1000, out: [], price: 0, tier: "gold"}], + [{n: 2, price: 19.99, code: "gold ", items: [], tier: "gold"}, {code: "gold ", items: [], n: 2, out: [], price: 19.99, tier: "gold"}], + [{n: 0.1, price: 50, code: "Gold", items: [{price: null, qty: 1, tag: "a"}, {price: 7, qty: 10, tag: "gold "}, {price: -20, qty: 18, tag: {t: "x"}}, {price: 5, tag: "a"}], tier: "Gold"}, "!error"], + [{n: null, code: "gold ", items: [{price: 7, tag: "a"}, {price: 0, qty: 50, tag: "gold "}, {price: 10, tag: "zz"}, {price: 7, qty: 2.5}], tier: "silver"}, "!error"], + [{n: 2, price: 5, code: "zz", items: [{price: 1, qty: -0.1, tag: "b"}, {price: 3, qty: -0.1, tag: "gold"}, {price: 11, qty: 1000, tag: "bronze"}], tier: "bronze"}, {code: "zz", items: [{price: 1, qty: -0.1, tag: "b"}, {price: 3, qty: -0.1, tag: "gold"}, {price: 11, qty: 1000, tag: "bronze"}], n: 2, out: [{g: {k1017: 0.1}, k1018: true}, {g: {k1017: 0.9}, k1018: true}, {g: {k1017: 1000}, k1018: true}], price: 5, tier: "bronze"}], + [{n: 1, price: 50, code: "gold ", items: [{price: 101, qty: 50, tag: true}, {price: 5, qty: 10, tag: "b"}, {price: 21, qty: -0.1, tag: null}], tier: "zz"}, {code: "gold ", items: [{price: 101, qty: 50, tag: true}, {price: 5, qty: 10, tag: "b"}, {price: 21, qty: -0.1, tag: null}], n: 1, out: [{g: {k1017: 50}, k1018: true}, {g: {k1017: 10}, k1018: true}, {g: {k1017: 44.1}, k1018: true}], price: 50, tier: "zz"}], + [{n: 100, price: 21, code: "gold", items: [{price: null, qty: 0.1, tag: "bronze"}], tier: "Gold"}, "!error"], + [{n: 3, price: 99, code: "gold ", items: [{qty: null, tag: "a"}, {price: 5, qty: -0.1, tag: "a"}], tier: "gold "}, "!error"], + [{n: -0.1, price: 10, code: "silver", items: [{price: null, qty: -6, tag: "bronze"}, {price: 0.5, qty: -5, tag: null}], extra: [1, 2]}, "!error"], + [{n: null, price: -1, code: "x", items: [], tier: ["gold"]}, {code: "x", items: [], out: [], price: -1, tier: ["gold"]}], + [{n: {v: 1}, price: true, code: ["gold"], items: [{price: 7, qty: 0.1, tag: "bronze"}, {price: 0.1, qty: 11, tag: "zz"}, {price: 10, qty: 2.5, tag: "Gold"}], tier: "a"}, {code: ["gold"], items: [{price: 7, qty: 0.1, tag: "bronze"}, {price: 0.1, qty: 11, tag: "zz"}, {price: 10, qty: 2.5, tag: "Gold"}], n: {v: 1}, out: [{g: {k1017: 0}, k1018: true}, {g: {k1017: 11}, k1018: true}, {g: {k1017: 3}, k1018: true}], price: true, tier: "a"}], + [{n: null, code: "b", items: [], tier: {t: "x"}}, {code: "b", items: [], out: [], tier: {t: "x"}}], + [{n: 7, price: 0, code: "gold", items: [{price: 3, qty: 101, tag: "zz"}, {price: 19.99, qty: -1, tag: "Gold"}, {price: 10, qty: null}], tier: "gold "}, "!error"], + [{n: 2.5, price: 3, code: "zz", items: [{price: 50, qty: 7}, {price: 1000, qty: 18, tag: "silver"}], tier: null}, {code: "zz", items: [{price: 50, qty: 7}, {price: 1000, qty: 18, tag: "silver"}], n: 2.5, out: [{g: {k1017: 7}, k1018: true}, {g: {k1017: 18}, k1018: true}], price: 3}], + ], +} + +{ + name: "gb075: 11 nodes, expr, table*, expr, expr, expr, expr, expr, table*, switch*, table*, table*", + graph: { + nodes: [ + {expression: "e1", fields: { + k1031: "tier == null", + "res.k1032": "tier", + k1033: "flag ?? score", + }}, + {table: "t2", hit: "collect", inputs: ["k1031", "'A-1'", "upper((res.k1032 ?? '?'))"], outputs: ["k1034[]", "m.k1035"], outputPath: "res", rules: [ + ["true", "not('')", "null", "false", "((3))"], + ["null", "$ != 'x'", "'a'", "false", "0.25"], + ["$ == true", "", "not('a')", "false", "2"], + ["", "", "", "endsWith(lower((res.k1032 ?? '')), 'g')", "10"], + ]}, + {expression: "e3", passThrough: true, fields: { + "g.k1036": "tier", + k1037: "flag", + k1038: "score", + }}, + {expression: "e4", fields: { + "m.k1039": "(contains(`v${(score ?? 1)}-${'x'}`, 'a')) and (contains((tier ?? '?') + ':' + (tier ?? '?'), ''))", + k1040: "flag ?? tier", + k1041: "(score ?? -1)", + }}, + {expression: "e5", fields: { + k1042: "(0 ?? k1033 ?? 0)", + "g.k1043": "(endsWith(string(false), 'a') ? res.k1032 : string(min([-4, 0.5])))", + k1044: "k1031 ?? k1031", + "g.k1045": "k1031 ?? k1031", + }}, + {expression: "e6", passThrough: true, fields: { + k1046: "`n=${(k1042 ?? 1)}-${(g.k1043 ?? 'none')}`", + k1047: "string(false)", + }}, + {expression: "e7", passThrough: true, fields: { + k1048: "score ?? flag", + }}, + {table: "t8", hit: "collect", inputs: ["k1041", "m.k1039"], outputs: ["k1049", "m.k1050"], passThrough: true, rules: [ + ["(5..6)", "null", "''", "2"], + ["null", "$ == true", "'low'", "-5"], + ["(18..28)", "null", "'low'", "0"], + ["[5..15]", "null", "'mid'", "10"], + ["", "", "'high'", "10"], + ]}, + {switch: "s9", hit: "collect", when: ["startsWith('A-1', 'x')", "contains(string(-4), 'a')", ""]}, + {table: "t10", hit: "collect", inputs: ["k1041"], outputs: ["m.k1051", "k1052"], passThrough: true, outputPath: "out", rules: [ + ["", "2", "(true ? string((k1041 ?? -1) % 2) : 'none')"], + ["<= 55", "100", "'gold'"], + ["not(10)", "10", "'low'"], + ["> 50", "100", "'mid'"], + [">= -1", "0", "string(not ((k1041 ?? 0) < 10))"], + ["> 18", "0.25", "''"], + ]}, + {table: "t11", hit: "collect", inputs: ["res.k1032", null], outputs: ["res.k1053"], passThrough: true, outputPath: "o.p", rules: [ + ["startsWith($, 's')", "$ != null", "not ((k1031 ?? false))"], + ["not('x')", "'gold'", "true"], + ["null", "5", "(k1031 ?? false)"], + ["$ != 'a'", "null", "false"], + ["'silver', 'b'", "'gold'", "len('' + ' ' + (res.k1032 ?? '?')) == -4"], + ["not('silver')", "", "(0) / 4 <= (2.25) / 0.5 * abs(10)"], + ["", "", "true"], + ]}, + ], + edges: [ + "input -> e1", + "e1 -> t2", + "input -> e3", + "input -> e4", + "e1 -> e5", + "t2 -> e6", + "e5 -> e6", + "input -> e7", + "e4 -> t8", + "e6 -> s9", + "t8 -> t10", + "e1 -> t11", + "e3 -> output", + "e7 -> output", + "s9:1 -> output", + "s9:2 -> output", + "t10 -> output", + "t11 -> output", + ], + }, + cases: [ + [{flag: "true", nums: [99], score: {v: 1}, tier: "silver"}, "!error"], + [{flag: true, nums: "1,2", score: 18, tier: "silver"}, {flag: true, g: {k1036: "silver", k1043: "-4", k1045: false}, k1031: false, k1033: true, k1037: true, k1038: 18, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 18, nums: "1,2", o: {p: [{res: {k1053: true}}, {res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 18, tier: "silver"}], + [{flag: "true", nums: [{x: 1}], score: 7, tier: "gold"}, {flag: "true", g: {k1036: "gold", k1043: "-4", k1045: false}, k1031: false, k1033: "true", k1037: "true", k1038: 7, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 7, nums: [{x: 1}], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 7, tier: "gold"}], + [{flag: true, nums: [1000, -1, 50], score: "abc", tier: ""}, {flag: true, g: {k1036: "", k1043: "-4", k1045: false}, k1031: false, k1033: true, k1037: true, k1038: "abc", k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: "abc", nums: [1000, -1, 50], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: "abc", tier: ""}], + [{flag: true, nums: [101, -25, 86, 1000, 1000000000000000000000], score: 5, tier: "Gold"}, {flag: true, g: {k1036: "Gold", k1043: "-4", k1045: false}, k1031: false, k1033: true, k1037: true, k1038: 5, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 5, nums: [101, -25, 86, 1000, 1000000000000000000000], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 5, tier: "Gold"}], + [{flag: false, nums: [{x: 1}], score: 21, tier: 5}, {flag: false, g: {k1036: 5, k1043: "-4", k1045: false}, k1031: false, k1033: false, k1037: false, k1038: 21, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 21, nums: [{x: 1}], o: {p: [{res: {k1053: true}}]}, out: [], res: [], score: 21, tier: 5}], + [{flag: false, nums: [99, 1000000000000000000000, 5], score: "abc", tier: {t: "x"}, extra: 1}, "!error"], + [{flag: true, score: 5, tier: ""}, {flag: true, g: {k1036: "", k1043: "-4", k1045: false}, k1031: false, k1033: true, k1037: true, k1038: 5, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 5, o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 5, tier: ""}], + [{flag: false, nums: [11], score: 3, tier: true}, {flag: false, g: {k1036: true, k1043: "-4", k1045: false}, k1031: false, k1033: false, k1037: false, k1038: 3, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 3, nums: [11], o: {p: [{res: {k1053: true}}]}, out: [], res: [], score: 3, tier: true}], + [{flag: true, nums: [1, 1000], score: -0.1, tier: "zz"}, {flag: true, g: {k1036: "zz", k1043: "-4", k1045: false}, k1031: false, k1033: true, k1037: true, k1038: -0.1, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: -0.1, nums: [1, 1000], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: -0.1, tier: "zz"}], + [{flag: false, nums: [99, 18, -1], score: 2, tier: "b"}, {flag: false, g: {k1036: "b", k1043: "-4", k1045: false}, k1031: false, k1033: false, k1037: false, k1038: 2, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 2, nums: [99, 18, -1], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 2, tier: "b"}], + [{flag: false, nums: [-1, -0.1, 11], score: 1, tier: null}, {flag: false, g: {k1043: "-4", k1045: true}, k1031: true, k1033: false, k1037: false, k1038: 1, k1042: 0, k1044: true, k1046: "n=0--4", k1047: "false", k1048: 1, nums: [-1, -0.1, 11], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 1}], + [{flag: false, nums: [5, -25], score: 100, tier: "b"}, {flag: false, g: {k1036: "b", k1043: "-4", k1045: false}, k1031: false, k1033: false, k1037: false, k1038: 100, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 100, nums: [5, -25], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 100, tier: "b"}], + [{flag: "true", nums: [69], score: 10, tier: 5, extra: 1}, {extra: 1, flag: "true", g: {k1036: 5, k1043: "-4", k1045: false}, k1031: false, k1033: "true", k1037: "true", k1038: 10, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 10, nums: [69], o: {p: [{res: {k1053: true}}]}, out: [], res: [], score: 10, tier: 5}], + [{flag: false, nums: [99, 2, 99], score: null, tier: "b", extra: 1}, {extra: 1, flag: false, g: {k1036: "b", k1043: "-4", k1045: false}, k1031: false, k1033: false, k1037: false, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: false, nums: [99, 2, 99], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], tier: "b"}], + [{flag: null, nums: [], score: 7, tier: "x"}, {g: {k1036: "x", k1043: "-4", k1045: false}, k1031: false, k1033: 7, k1038: 7, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 7, nums: [], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 7, tier: "x"}], + [{flag: false, nums: [19.99], score: null, tier: 5, extra: {deep: {x: 1}}}, {extra: {deep: {x: 1}}, flag: false, g: {k1036: 5, k1043: "-4", k1045: false}, k1031: false, k1033: false, k1037: false, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: false, nums: [19.99], o: {p: [{res: {k1053: true}}]}, out: [], res: [], tier: 5}], + [{flag: null, score: 19.99, tier: ""}, {g: {k1036: "", k1043: "-4", k1045: false}, k1031: false, k1033: 19.99, k1038: 19.99, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 19.99, o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 19.99, tier: ""}], + [{flag: false, nums: [1000, -0.1], score: 0, tier: 5}, {flag: false, g: {k1036: 5, k1043: "-4", k1045: false}, k1031: false, k1033: false, k1037: false, k1038: 0, k1042: 0, k1044: false, k1046: "n=0--4", k1047: "false", k1048: 0, nums: [1000, -0.1], o: {p: [{res: {k1053: true}}]}, out: [], res: [], score: 0, tier: 5}], + [{flag: false, nums: [53, 101, 10, 3, 0.1], score: 1000}, {flag: false, g: {k1043: "-4", k1045: true}, k1031: true, k1033: false, k1037: false, k1038: 1000, k1042: 0, k1044: true, k1046: "n=0--4", k1047: "false", k1048: 1000, nums: [53, 101, 10, 3, 0.1], o: {p: [{res: {k1053: true}}]}, out: [], res: [{k1034: false, m: {k1035: 10}}], score: 1000}], + ], +} + +{ + name: "gb076: 6 nodes, table*, expr, switch*, switch*, loop table*, loop table*", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputField: "cust", inputs: ["active"], outputs: ["res.k1054"], passThrough: true, outputPath: "o.p", rules: [ + ["null", "10"], + ["false", "100"], + ["$ == true", "1"], + ["null", "100"], + ["false", "(age ?? -1)"], + ["true", "-5"], + ["", "0.25"], + ]}, + {expression: "e2", inputField: "cust", passThrough: true, fields: { + k1055: "(active ?? false)", + k1056: "0 * ((age ?? -1) + 0.5)", + }}, + {switch: "s3", hit: "collect", when: ["false", ""]}, + {switch: "s4", hit: "collect", when: ["startsWith(string(len(filter(items ?? [], #.tag == 'gold'))) + ':' + (tier ?? '?'), 'a')", "false", ""]}, + {table: "t5", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["tag", "qty", null], outputs: ["k1057"], outputPath: "res", rules: [ + ["not('gold')", "not(5)", "null", "true"], + ["'', 'bronze'", ">= 1", "true", "((false)) or ((tag ?? '') + '-' + (tag ?? '') in ['gold', 'silver', 'a'])"], + ["'silver'", "null", "$ != null", "true"], + ["$ != 'silver'", "$ > 21 and $ < 26", "null", "false"], + ["'', 'gold'", "> 10", "", "((qty ?? -1) > (price ?? 1) ? (tag ?? '') : upper((tag ?? ''))) in ['gold', 'silver', 'a']"], + ["'a'", "$ > 18 and $ < 23", "", "true"], + ]}, + {table: "t6", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["tag", "tag"], outputs: ["k1058[]", "k1059"], passThrough: true, outputPath: "o.p", rules: [ + ["", "'x'", "(-4 + (price ?? -1) == 2.25 % 7)", "true"], + ["$ != 'x'", "", "false", "false"], + ["$ != 'silver'", "not('a')", "false", "true"], + ["", "$ != 'x'", "a == null", "(price ?? 0) + (0.5) / 4 <= (price ?? price ?? 0)"], + ["'a'", "startsWith($, 'a')", "(true) and (tag == null)", "false"], + ]}, + ], + edges: [ + "input -> t1", + "t1 -> e2", + "input -> e2", + "t1 -> s3", + "s3:0 -> s4", + "s3:1 -> t5", + "s4:0 -> t6", + "t1 -> output", + "e2 -> output", + "s4:1 -> output", + "s4:2 -> output", + "t5 -> output", + "t6 -> output", + ], + }, + cases: [ + [{items: [{price: -25, qty: 100, tag: "Gold"}, {price: -1, qty: 0, tag: "zz"}], cust: {age: 2.5, tier: "gold", active: false}, tier: "a", b: null, code: null}, {cust: {active: false, age: 2.5, tier: "gold"}, items: [{price: -25, qty: 100, tag: "Gold"}, {price: -1, qty: 0, tag: "zz"}], k1055: false, k1056: 0, o: {p: [{res: {k1054: 100}}, {res: {k1054: 2.5}}, {res: {k1054: 0.25}}]}, res: [[], []], tier: "a"}], + [{items: [{price: null, qty: -19, tag: "a"}, {price: -1, qty: 1, tag: "x"}], cust: {age: 50, tier: "Gold", active: true}, tier: "bronze", nums: null, b: null, code: "b"}, {code: "b", cust: {active: true, age: 50, tier: "Gold"}, items: [{price: null, qty: -19, tag: "a"}, {price: -1, qty: 1, tag: "x"}], k1055: true, k1056: 0, o: {p: [{res: {k1054: 1}}, {res: {k1054: -5}}, {res: {k1054: 0.25}}]}, res: [[], []], tier: "bronze"}], + [{items: [{price: 10, qty: 5, tag: null}], cust: {age: -0.1, tier: null, active: false}, tier: "gold", nums: [-1, 11], b: null, code: "Gold", extra: 1}, {code: "Gold", cust: {active: false, age: -0.1, tier: null}, extra: 1, items: [{price: 10, qty: 5, tag: null}], k1055: false, k1056: 0, nums: [-1, 11], o: {p: [{res: {k1054: 100}}, {res: {k1054: -0.1}}, {res: {k1054: 0.25}}]}, res: [[]], tier: "gold"}], + [{items: null, cust: {age: 99, tier: "silver", active: null}, tier: "bronze", b: null, code: "Gold", extra: "e"}, "!error"], + [{items: [{price: 0, qty: -0.1, tag: "silver"}, {price: 1000, qty: 100, tag: "bronze"}, {price: 2.5, qty: -1, tag: "a"}], cust: null, tier: "bronze", nums: [], b: 7}, {b: 7, items: [{price: 0, qty: -0.1, tag: "silver"}, {price: 1000, qty: 100, tag: "bronze"}, {price: 2.5, qty: -1, tag: "a"}], k1055: false, k1056: 0, nums: [], o: {p: [{res: {k1054: 10}}, {res: {k1054: 100}}, {res: {k1054: 0.25}}]}, res: [[], [{k1057: false}], []], tier: "bronze"}], + [{items: [], cust: {age: 106, tier: null, active: null}, tier: "b", nums: [0.1, 101], b: -0.1, code: "Gold"}, {b: -0.1, code: "Gold", cust: {active: null, age: 106, tier: null}, items: [], k1055: false, k1056: 0, nums: [0.1, 101], o: {p: [{res: {k1054: 10}}, {res: {k1054: 100}}, {res: {k1054: 0.25}}]}, res: [], tier: "b"}], + [{items: null, cust: {age: 0.1, tier: "zz", active: true}, tier: "", nums: [2], b: 2, code: ""}, "!error"], + [{items: [], cust: {age: 18, tier: "bronze", active: true}, tier: "bronze", nums: [2, 3, 2], b: -25}, {b: -25, cust: {active: true, age: 18, tier: "bronze"}, items: [], k1055: true, k1056: 0, nums: [2, 3, 2], o: {p: [{res: {k1054: 1}}, {res: {k1054: -5}}, {res: {k1054: 0.25}}]}, res: [], tier: "bronze"}], + [{items: [{price: 11, qty: 10, tag: "silver"}, {price: 1000000000000000000000, tag: null}, {price: 3, qty: -25, tag: "silver"}], cust: {age: -25, tier: "b", active: false}, tier: "b", nums: [-25, 7, 0.1], b: 0.5, code: "silver"}, {b: 0.5, code: "silver", cust: {active: false, age: -25, tier: "b"}, items: [{price: 11, qty: 10, tag: "silver"}, {price: 1000000000000000000000, tag: null}, {price: 3, qty: -25, tag: "silver"}], k1055: false, k1056: 0, nums: [-25, 7, 0.1], o: {p: [{res: {k1054: 100}}, {res: {k1054: -25}}, {res: {k1054: 0.25}}]}, res: [[], [], []], tier: "b"}], + [{items: [{price: -0.1, qty: 0, tag: "Gold"}, {price: 99, qty: 2, tag: "Gold"}, {price: 1, qty: -1, tag: "b"}], cust: {age: 2, tier: "zz", active: false}, tier: "silver", nums: [0, 1000000000000000000000, 50], b: 19.99, code: "silver"}, {b: 19.99, code: "silver", cust: {active: false, age: 2, tier: "zz"}, items: [{price: -0.1, qty: 0, tag: "Gold"}, {price: 99, qty: 2, tag: "Gold"}, {price: 1, qty: -1, tag: "b"}], k1055: false, k1056: 0, nums: [0, 1000000000000000000000, 50], o: {p: [{res: {k1054: 100}}, {res: {k1054: 2}}, {res: {k1054: 0.25}}]}, res: [[], [], []], tier: "silver"}], + [{items: [], cust: {age: 1000000000000000000000, tier: "gold ", active: null}, tier: "silver", nums: [11, 100], code: "b"}, {code: "b", cust: {active: null, age: 1000000000000000000000, tier: "gold "}, items: [], k1055: false, k1056: 0, nums: [11, 100], o: {p: [{res: {k1054: 10}}, {res: {k1054: 100}}, {res: {k1054: 0.25}}]}, res: [], tier: "silver"}], + [{items: [{price: -25, qty: -0.1, tag: "gold"}, {price: 99, qty: 5, tag: "x"}], cust: null, tier: "zz", nums: [0], b: 19.99, code: "b"}, {b: 19.99, code: "b", items: [{price: -25, qty: -0.1, tag: "gold"}, {price: 99, qty: 5, tag: "x"}], k1055: false, k1056: 0, nums: [0], o: {p: [{res: {k1054: 10}}, {res: {k1054: 100}}, {res: {k1054: 0.25}}]}, res: [[], []], tier: "zz"}], + [{items: [{price: 100, qty: 1000, tag: "silver"}, {price: 101, qty: 7, tag: "x"}, {price: 11, qty: -0.1, tag: "gold"}, {price: 0.1, qty: 1, tag: "silver"}], cust: {age: 5, tier: "gold", active: false}, tier: "zz", nums: [0.5, 10, 1000000000000000000000, 3, 0.5], b: 5, code: "Gold"}, {b: 5, code: "Gold", cust: {active: false, age: 5, tier: "gold"}, items: [{price: 100, qty: 1000, tag: "silver"}, {price: 101, qty: 7, tag: "x"}, {price: 11, qty: -0.1, tag: "gold"}, {price: 0.1, qty: 1, tag: "silver"}], k1055: false, k1056: 0, nums: [0.5, 10, 1000000000000000000000, 3, 0.5], o: {p: [{res: {k1054: 100}}, {res: {k1054: 5}}, {res: {k1054: 0.25}}]}, res: [[], [], [], []], tier: "zz"}], + [{items: [{qty: 11, tag: "Gold"}, {price: 2.5, qty: 101, tag: "silver"}, {price: 1000000000000000000000, tag: "Gold"}, {price: 21, qty: 18, tag: "gold"}], cust: {age: 7, tier: null, active: false}, tier: "b", nums: [2.5], b: -1, code: "zz", extra: [1, 2]}, {b: -1, code: "zz", cust: {active: false, age: 7, tier: null}, extra: [1, 2], items: [{qty: 11, tag: "Gold"}, {price: 2.5, qty: 101, tag: "silver"}, {price: 1000000000000000000000, tag: "Gold"}, {price: 21, qty: 18, tag: "gold"}], k1055: false, k1056: 0, nums: [2.5], o: {p: [{res: {k1054: 100}}, {res: {k1054: 7}}, {res: {k1054: 0.25}}]}, res: [[], [], [], [{k1057: false}]], tier: "b"}], + [{items: [], cust: {age: 7, tier: "b", active: false}, tier: "silver", nums: [18, -0.1], b: 7, code: "gold ", extra: 1}, {b: 7, code: "gold ", cust: {active: false, age: 7, tier: "b"}, extra: 1, items: [], k1055: false, k1056: 0, nums: [18, -0.1], o: {p: [{res: {k1054: 100}}, {res: {k1054: 7}}, {res: {k1054: 0.25}}]}, res: [], tier: "silver"}], + [{items: [], cust: {age: 18, tier: "x", active: true}, tier: "a", nums: [2.5, 99, 29, 1000, 1000000000000000000000], b: 99, code: "b"}, {b: 99, code: "b", cust: {active: true, age: 18, tier: "x"}, items: [], k1055: true, k1056: 0, nums: [2.5, 99, 29, 1000, 1000000000000000000000], o: {p: [{res: {k1054: 1}}, {res: {k1054: -5}}, {res: {k1054: 0.25}}]}, res: [], tier: "a"}], + [{items: [{price: 2.5, qty: 7}, {price: -1, qty: 5, tag: "a"}, {price: 99, qty: -0.1, tag: "gold "}], cust: {age: 3, tier: "b", active: true}, tier: "gold", nums: [1000000000000000000000], b: 99, code: "gold "}, {b: 99, code: "gold ", cust: {active: true, age: 3, tier: "b"}, items: [{price: 2.5, qty: 7}, {price: -1, qty: 5, tag: "a"}, {price: 99, qty: -0.1, tag: "gold "}], k1055: true, k1056: 0, nums: [1000000000000000000000], o: {p: [{res: {k1054: 1}}, {res: {k1054: -5}}, {res: {k1054: 0.25}}]}, res: [[], [], []], tier: "gold"}], + [{items: [], cust: {age: 50, tier: "gold ", active: true}, tier: null, nums: [-25, 21, 0.1, 18, 1000], b: 99, code: "silver", extra: [1, 2]}, {b: 99, code: "silver", cust: {active: true, age: 50, tier: "gold "}, extra: [1, 2], items: [], k1055: true, k1056: 0, nums: [-25, 21, 0.1, 18, 1000], o: {p: [{res: {k1054: 1}}, {res: {k1054: -5}}, {res: {k1054: 0.25}}]}, res: []}], + [{items: [], cust: {age: 1, tier: "silver", active: false}, tier: "bronze", nums: [1000000000000000000000, 5, 0.5], b: 7, code: "x"}, {b: 7, code: "x", cust: {active: false, age: 1, tier: "silver"}, items: [], k1055: false, k1056: 0, nums: [1000000000000000000000, 5, 0.5], o: {p: [{res: {k1054: 100}}, {res: {k1054: 1}}, {res: {k1054: 0.25}}]}, res: [], tier: "bronze"}], + [{items: [{price: 1000, qty: 18, tag: "x"}, {price: 10, tag: "zz"}, {price: 7, qty: -0.1, tag: "Gold"}], cust: {age: 11, tier: "gold ", active: true}, tier: "b", nums: []}, {cust: {active: true, age: 11, tier: "gold "}, items: [{price: 1000, qty: 18, tag: "x"}, {price: 10, tag: "zz"}, {price: 7, qty: -0.1, tag: "Gold"}], k1055: true, k1056: 0, nums: [], o: {p: [{res: {k1054: 1}}, {res: {k1054: -5}}, {res: {k1054: 0.25}}]}, res: [[], [], []], tier: "b"}], + [{items: [{price: 100, tag: "gold "}, {price: -25, qty: -1, tag: "b"}], cust: {age: 100, tier: "", active: true}, nums: [-1, 0.5, 82, 1, -0.1], b: null, code: null, extra: "e"}, {cust: {active: true, age: 100, tier: ""}, extra: "e", items: [{price: 100, tag: "gold "}, {price: -25, qty: -1, tag: "b"}], k1055: true, k1056: 0, nums: [-1, 0.5, 82, 1, -0.1], o: {p: [{res: {k1054: 1}}, {res: {k1054: -5}}, {res: {k1054: 0.25}}]}, res: [[], []]}], + [{items: [], cust: {age: 18, tier: "", active: true}, nums: [], b: 2.5, code: "gold ", extra: "e"}, {b: 2.5, code: "gold ", cust: {active: true, age: 18, tier: ""}, extra: "e", items: [], k1055: true, k1056: 0, nums: [], o: {p: [{res: {k1054: 1}}, {res: {k1054: -5}}, {res: {k1054: 0.25}}]}, res: []}], + [{items: [], tier: "silver", nums: [1, 1000000000000000000000, -0.1], b: 1000, code: "silver"}, {b: 1000, code: "silver", items: [], k1055: false, k1056: 0, nums: [1, 1000000000000000000000, -0.1], o: {p: [{res: {k1054: 10}}, {res: {k1054: 100}}, {res: {k1054: 0.25}}]}, res: [], tier: "silver"}], + ], +} + +{ + name: "gb077: 12 nodes, switch*, switch, expr, table, table*, switch*, switch, expr, expr, table, expr, expr", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["contains((endsWith(s, 'g') ? (s ?? '?') : string((b ?? 0))), 'x')"]}, + {switch: "s2", when: ["lower((true ? s : s)) in ['gold', 'silver', 'a']", "s == 'gold'", ""]}, + {expression: "e3", passThrough: true, fields: { + k1060: "string(flag) + '' + s + ' ' + (s ?? 'none') + ':' + ''", + k1061: "string(false)", + k1062: "3", + }}, + {table: "t4", inputs: ["s", "flag", "k1062"], outputs: ["g.k1063", "k1064"], passThrough: true, rules: [ + ["'a'", "false", "< 50", "(k1062 ?? -1)", "true"], + ["", "null", "", "(b ?? 0)", "false"], + ["not('silver')", "null", ">= 1", "2", "(not ((false) and (true))) and (not (not (false)))"], + ["", "$ == true", "<= 6", "10", "false"], + ]}, + {table: "t5", hit: "collect", inputs: ["b", "flag", "b"], outputs: ["k1061[]"], outputPath: "res", rules: [ + ["< 21", "null", "-1, 0", "false"], + ["", "", "18, 23", "true"], + ["100, 110", "$ == true", "", "false"], + ["", "", "", "true"], + ]}, + {switch: "s6", hit: "collect", when: ["(g.k1063 ?? 1) > (g.k1063 - n)", "(g.k1063 ?? 0) < (b ?? 1) + (3)", ""]}, + {switch: "s7", when: ["(true)"]}, + {expression: "e8", outputPath: "lines", fields: { + k1066: "len(string((n ?? 1) < b))", + k1067: "((($.k1066 ?? 0) >= -4) or (k1064) ? (k1060 ?? '?') : ((false) and (flag) ? (true ? k1060 : (s ?? '?')) : `n=${($.k1066 ?? -1)}-${(s ?? 'none')}`))", + k1068: "b", + }}, + {expression: "e9", passThrough: true, fields: { + k1062: "((((flag ?? false)) and (false)) and (false))", + k1070: "(len((s ?? ''))) / 10 + (b ?? -1) * b * (b ?? -1)", + k1071: "flag ?? s", + k1072: "(n ?? -1) % 3 - len((s ?? 'none')) + ((n ?? 0)) / 3", + }}, + {table: "t10", inputs: ["lines.k1066", "lines.k1068", "lines.k1068"], outputs: ["k1073", "k1074"], rules: [ + ["[-1..4)", "> -1", "< 50", "true", "'A-1'"], + ["[18..68]", ">= 100", "not(0)", "true", "string(((lines.k1068 ?? -1)) * 2.25 * (lines.k1066 ?? 0))"], + ["", "-1", "5", "false", "'mid'"], + ["> -1", "$ > 10 and $ < 20", "<= 6", "false", "'mid'"], + ["", "", "", "true", "'high'"], + ]}, + {expression: "e11", passThrough: true, fields: { + k1075: "k1062 ?? k1061", + "m.k1076": "(a ?? -1)", + }}, + {expression: "e12", passThrough: true, fields: { + k1077: "(flag ?? false)", + "res.k1078": "b + len(s + '-' + (s ?? ''))", + }}, + ], + edges: [ + "input -> s1", + "s1:0 -> s2", + "input -> s2", + "s2:2 -> e3", + "e3 -> t4", + "s2:0 -> t5", + "s2:2 -> t5", + "t4 -> s6", + "s6:1 -> s7", + "input -> e8", + "s6:0 -> e8", + "s1:0 -> e9", + "e8 -> t10", + "s7:0 -> e11", + "s2:1 -> e12", + "t5 -> output", + "e9 -> output", + "t10 -> output", + "e11 -> output", + "e12 -> output", + ], + }, + cases: [ + [{s: "Gold", n: 2, a: 10, flag: true, b: 3}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + [{s: "", n: 11, a: 100, flag: true, b: 1}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + [{s: "b", n: 99, a: 50, flag: false, b: 0.1}, {a: 50, b: 0.1, flag: false, k1060: "falseb b:", k1061: "false", k1062: 3, k1073: true, k1074: "high", k1075: 3, m: {k1076: 50}, n: 99, res: [{k1061: true}], s: "b"}], + [{s: "x", n: -0.1, a: 99, flag: true, b: 1000}, {a: 99, b: 1000, flag: true, g: {k1063: 10}, k1060: "truex x:", k1061: "false", k1062: 3, k1064: false, k1073: true, k1074: "high", k1075: 3, m: {k1076: 99}, n: -0.1, res: [{k1061: true}], s: "x"}], + [{s: null, n: 2, a: -0.1, flag: true}, "!error"], + [{s: null, n: 0.5, a: 1, flag: true, b: 0.5}, "!error"], + [{n: 10, a: 99, flag: false, b: -0.1}, "!error"], + [{s: "gold ", n: 101, a: null, flag: false, b: null}, "!error"], + [{s: "x", n: 0, flag: true, b: 10, extra: [1, 2]}, {b: 10, extra: [1, 2], flag: true, g: {k1063: 10}, k1060: "truex x:", k1061: "false", k1062: 3, k1064: false, k1073: true, k1074: "high", k1075: 3, m: {k1076: -1}, n: 0, res: [{k1061: true}], s: "x"}], + [{s: "Gold", n: 100, a: 2, flag: false, b: 5}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + [{s: "b", n: 21, a: 0.1, flag: true}, "!error"], + [{n: 1000, a: null, flag: false, b: 0.5, extra: [1, 2]}, "!error"], + [{n: null, a: 0.1, flag: false, b: 3}, "!error"], + [{s: "silver", n: 99, a: 99, flag: true, b: 21}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + [{s: "Gold", n: -25, a: 99, flag: true, b: 19.99}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + [{s: "gold", n: 50, a: 1000, flag: false, b: 5}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + [{s: "", n: 7, a: -25, flag: false, b: 14}, {a: -25, b: 14, flag: false, k1060: "false :", k1061: "false", k1062: 3, k1073: true, k1074: "high", k1075: 3, m: {k1076: -25}, n: 7, res: [{k1061: true}], s: ""}], + [{s: "zz", n: 0.5, a: 99, flag: false, b: null}, "!error"], + [{s: "x", n: 1000000000000000000000, a: 0.1, flag: false, b: 11}, {a: 0.1, b: 11, flag: false, k1060: "falsex x:", k1061: "false", k1062: 3, k1073: true, k1074: "high", k1075: 3, m: {k1076: 0.1}, n: 1000000000000000000000, res: [{k1061: true}], s: "x"}], + [{s: "bronze", n: 50, a: 0.1, flag: true, b: -1}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + [{s: null, n: 1000000000000000000000, a: 19.99, flag: false, b: 100}, "!error"], + [{s: "a", a: 99, flag: true, b: 19.99}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + [{s: "zz", a: 1, flag: false, b: null}, "!error"], + [{n: 99, flag: true, b: null}, "!error"], + [{s: "b", n: 0.5, a: 1, flag: true, b: 50}, {a: 1, b: 50, flag: true, g: {k1063: 10}, k1060: "trueb b:", k1061: "false", k1062: 3, k1064: false, k1073: true, k1074: "high", k1075: 3, m: {k1076: 1}, n: 0.5, res: [{k1061: true}], s: "b"}], + [{s: "bronze", n: 50, a: 11, b: 101}, {a: 11, b: 101, g: {k1063: 101}, k1060: "nullbronze bronze:", k1061: "false", k1062: 3, k1064: false, k1073: true, k1074: "high", k1075: 3, m: {k1076: 11}, n: 50, res: [{k1061: true}], s: "bronze"}], + [{s: "", n: 11, a: -25, flag: true, b: 101, extra: 1}, {a: -25, b: 101, extra: 1, flag: true, g: {k1063: 10}, k1060: "true :", k1061: "false", k1062: 3, k1064: false, k1073: true, k1074: "high", k1075: 3, m: {k1076: -25}, n: 11, res: [{k1061: true}], s: ""}], + [{s: "bronze", n: 18, a: -25, b: 100, extra: "e"}, {a: -25, b: 100, extra: "e", g: {k1063: 100}, k1060: "nullbronze bronze:", k1061: "false", k1062: 3, k1064: false, k1073: true, k1074: "high", k1075: 3, m: {k1076: -25}, n: 18, res: [{k1061: true}], s: "bronze"}], + [{s: "gold ", n: 0.5, a: 7, flag: true, b: 0.1}, {k1073: true, k1074: "high", res: [{k1061: true}]}], + ], +} + +{ + name: "gb078: 9 nodes, switch*, loop table*, expr, loop table, switch*, table*, table, table*, table", + graph: { + nodes: [ + {switch: "s1", hit: "collect", when: ["(b ?? 1) in [0..10]", "-4 != ((code ?? '?') == 'silver' ? -((b ?? 1)) : ((a ?? 0)))", ""]}, + {table: "t2", hit: "collect", inputField: "items", executionMode: "loop", inputs: ["qty", "qty", "price"], outputs: ["res.k1079"], outputPath: "o.p", rules: [ + ["$ > 100 and $ < 150", "[-1..0]", "", "string((true) or (true)) == 'silver'"], + [">= 50", "!= 21", "not(50)", "false"], + ]}, + {expression: "e3", fields: { + "g.k1080": "2 % 7 in [0..10]", + }}, + {table: "t4", inputField: "items", executionMode: "loop", inputs: ["qty"], outputs: ["g.k1081"], passThrough: true, outputPath: "o.p", rules: [ + ["", "true"], + ["null", "true"], + ["10", "false"], + ["not(0)", "false"], + ]}, + {switch: "s5", hit: "collect", when: ["g.k1080", "(-4 >= 10 - 10) or (((true) and ((g.k1080 ?? false))) or (2 == 1))", "1 <= 0.5 * min([100, 0.5])", ""]}, + {table: "t6", hit: "collect", inputs: ["string(not (true))", "'gold' + ' ' + upper('')"], outputs: ["k1082"], rules: [ + ["'a', 'b'", "'x'", "not ((g.k1080 ?? false))"], + ["", "$ != 'gold'", "string((true) and ((g.k1080 ?? false))) in ['gold', 'silver', 'a']"], + ["", "'gold', 'bronze'", "true"], + ]}, + {table: "t7", inputs: ["g.k1080", "(0 ?? 1 ?? 0)", "'x'"], outputs: ["res.k1083"], passThrough: true, outputPath: "o.p", rules: [ + ["", ">= 10", "null", "false"], + ["$ == true", "", "'a'", "false"], + ]}, + {table: "t8", hit: "collect", inputs: ["''", "string(3)", "(0 ?? 1 ?? 0) + (-4)"], outputs: ["res.k1084"], outputPath: "o.p", rules: [ + ["", "'silver', 'gold'", "", "'high'"], + ["", "'x'", ">= 0", "string(-(2.25 * 10))"], + ["startsWith($, 'g')", "'gold', 'bronze'", "", "'low'"], + ["'silver', 'b'", "''", "not(50)", "'high'"], + ["", "'a', 'gold'", "not(-1)", "'low'"], + ["", "", "", "'gold'"], + ]}, + {table: "t9", inputs: ["1"], outputs: ["k1085"], rules: [ + ["[1..2)", "'high'"], + ["< 0", "'high'"], + ["$ > 18 and $ < 19", "'gold'"], + ["", "''"], + ]}, + ], + edges: [ + "input -> s1", + "s1:0 -> t2", + "t2 -> e3", + "t2 -> t4", + "s1:0 -> t4", + "e3 -> s5", + "s5:1 -> t6", + "s5:0 -> t7", + "t6 -> t8", + "t8 -> t9", + "s1:1 -> output", + "s1:2 -> output", + "t4 -> output", + "s5:2 -> output", + "t6 -> output", + "t7 -> output", + "t8 -> output", + "t9 -> output", + ], + }, + cases: [ + [{b: 0.5, n: -0.1, items: [{price: 7, qty: 2, tag: "Gold"}, {price: 10, qty: 101, tag: "silver"}], flag: null, price: {v: 1}, a: 2}, {a: 2, b: 0.5, items: [{price: 7, qty: 2, tag: "Gold"}, {price: 10, qty: 101, tag: "silver"}], n: -0.1, o: {p: [{g: {k1081: true}, price: 7, qty: 2, tag: "Gold"}, {g: {k1081: true}, price: 10, qty: 101, tag: "silver"}]}, price: {v: 1}}], + [{b: 95, items: [{price: null, qty: 1, tag: "x"}], flag: true, price: -25, a: -25, extra: {deep: {x: 1}}}, {a: -25, b: 95, extra: {deep: {x: 1}}, flag: true, items: [{price: null, qty: 1, tag: "x"}], price: -25}], + [{b: 50, code: null, n: 11, items: [{price: [1], qty: 94, tag: "silver"}, {price: 0.5, qty: 3, tag: "a"}], flag: false, a: 21, extra: [1, 2]}, {a: 21, b: 50, extra: [1, 2], flag: false, items: [{price: [1], qty: 94, tag: "silver"}, {price: 0.5, qty: 3, tag: "a"}], n: 11}], + [{b: -25, code: "zz", n: -1, items: [{price: "abc", qty: 1}, {tag: ""}, {price: 0.1, qty: 99, tag: ""}], flag: false, price: 21, a: 99}, {a: 99, b: -25, code: "zz", flag: false, items: [{price: "abc", qty: 1}, {tag: ""}, {price: 0.1, qty: 99, tag: ""}], n: -1, price: 21}], + [{b: 21, code: "", n: 19.99, items: [{price: -1, qty: -0.1, tag: "silver"}], flag: null, price: null, a: 101}, {a: 101, b: 21, code: "", items: [{price: -1, qty: -0.1, tag: "silver"}], n: 19.99}], + [{b: 54, code: "b", n: 0.1, items: [{price: 2, qty: -0.1, tag: "silver"}], flag: false, price: 19.99, a: 11, extra: {deep: {x: 1}}}, {a: 11, b: 54, code: "b", extra: {deep: {x: 1}}, flag: false, items: [{price: 2, qty: -0.1, tag: "silver"}], n: 0.1, price: 19.99}], + [{b: 0, code: "", items: [{price: 1000, qty: -25, tag: "gold "}], flag: false, a: null}, {b: 0, code: "", flag: false, items: [{price: 1000, qty: -25, tag: "gold "}], o: {p: [{g: {k1081: true}, price: 1000, qty: -25, tag: "gold "}]}}], + [{b: 0, code: "", items: [{qty: 18, tag: "silver"}, {price: -25, qty: 50, tag: "bronze"}], flag: true, a: -0.1}, {a: -0.1, b: 0, code: "", flag: true, items: [{qty: 18, tag: "silver"}, {price: -25, qty: 50, tag: "bronze"}], o: {p: [{g: {k1081: true}, qty: 18, tag: "silver"}, {g: {k1081: true}, price: -25, qty: 50, tag: "bronze"}]}}], + [{b: 1, code: null, n: null, items: [{price: 2.5, qty: null, tag: "gold"}, {price: 21, qty: 11, tag: "bronze"}], flag: false, price: 101, a: 99}, {a: 99, b: 1, flag: false, items: [{price: 2.5, qty: null, tag: "gold"}, {price: 21, qty: 11, tag: "bronze"}], o: {p: [{g: {k1081: true}, price: 2.5, qty: null, tag: "gold"}, {g: {k1081: true}, price: 21, qty: 11, tag: "bronze"}]}, price: 101}], + [{b: 5, code: "silver", n: 3, items: [{price: 11, qty: 0.1, tag: "zz"}], flag: 0, price: 5, a: {v: 1}}, {a: {v: 1}, b: 5, code: "silver", flag: 0, items: [{price: 11, qty: 0.1, tag: "zz"}], n: 3, o: {p: [{g: {k1081: true}, price: 11, qty: 0.1, tag: "zz"}]}, price: 5}], + [{b: -0.1, code: "silver", n: 1000000000000000000000, items: [{price: 11, qty: 1, tag: true}, {price: 101, qty: 3, tag: ""}], flag: false, price: -0.1, a: 99}, {a: 99, b: -0.1, code: "silver", flag: false, items: [{price: 11, qty: 1, tag: true}, {price: 101, qty: 3, tag: ""}], n: 1000000000000000000000, price: -0.1}], + [{b: 21, n: 11, items: [{price: -25, qty: 3, tag: "bronze"}, {price: 67, qty: 1000, tag: "Gold"}], flag: false, price: 100, a: 1000000000000000000000}, {a: 1000000000000000000000, b: 21, flag: false, items: [{price: -25, qty: 3, tag: "bronze"}, {price: 67, qty: 1000, tag: "Gold"}], n: 11, price: 100}], + [{b: 1000000000000000000000, code: "b", n: 7, items: [{price: 1000000000000000000000, qty: -25, tag: "silver"}, {price: 101, qty: null, tag: "a"}, {price: 7, qty: 2.5, tag: {t: "x"}}], flag: false, price: -1, a: 2}, {a: 2, b: 1000000000000000000000, code: "b", flag: false, items: [{price: 1000000000000000000000, qty: -25, tag: "silver"}, {price: 101, qty: null, tag: "a"}, {price: 7, qty: 2.5, tag: {t: "x"}}], n: 7, price: -1}], + [{b: 1, code: 5, n: 0.1, items: [{price: 0.1, qty: 5, tag: "Gold"}, {price: 1000, qty: 101, tag: "x"}], flag: false, price: null, a: -1}, {a: -1, b: 1, code: 5, flag: false, items: [{price: 0.1, qty: 5, tag: "Gold"}, {price: 1000, qty: 101, tag: "x"}], n: 0.1, o: {p: [{g: {k1081: true}, price: 0.1, qty: 5, tag: "Gold"}, {g: {k1081: true}, price: 1000, qty: 101, tag: "x"}]}}], + [{b: 100, code: "Gold", n: 5, items: [{price: 99, qty: 18, tag: "silver"}, {price: 10, qty: 1, tag: "bronze"}, {price: -1, qty: 99, tag: "gold"}, {qty: 1000, tag: "bronze"}], price: 0.1, a: null}, {b: 100, code: "Gold", items: [{price: 99, qty: 18, tag: "silver"}, {price: 10, qty: 1, tag: "bronze"}, {price: -1, qty: 99, tag: "gold"}, {qty: 1000, tag: "bronze"}], n: 5, price: 0.1}], + [{b: 2, code: "", n: 18, flag: 1, a: 2}, "!error"], + [{b: -0.1, code: "bronze", n: 19.99, flag: true, price: 5, a: -1}, {a: -1, b: -0.1, code: "bronze", flag: true, n: 19.99, price: 5}], + [{b: 7, code: "silver", n: 10, items: [{price: 7, qty: 50, tag: "a"}], flag: true, price: -0.1, a: 5}, {a: 5, b: 7, code: "silver", flag: true, items: [{price: 7, qty: 50, tag: "a"}], n: 10, o: {p: [{g: {k1081: true}, price: 7, qty: 50, tag: "a"}]}, price: -0.1}], + [{code: "silver", n: 11, items: [{price: 0.5, qty: 0.5, tag: "b"}, {price: 5, qty: -0.1, tag: ""}, {price: 11, qty: 100, tag: ""}, {price: 5, qty: -0.1, tag: "Gold"}], flag: false, price: 2, a: 1000000000000000000000}, {a: 1000000000000000000000, code: "silver", flag: false, items: [{price: 0.5, qty: 0.5, tag: "b"}, {price: 5, qty: -0.1, tag: ""}, {price: 11, qty: 100, tag: ""}, {price: 5, qty: -0.1, tag: "Gold"}], n: 11, o: {p: [{g: {k1081: true}, price: 0.5, qty: 0.5, tag: "b"}, {g: {k1081: true}, price: 5, qty: -0.1, tag: ""}, {g: {k1081: true}, price: 11, qty: 100, tag: ""}, {g: {k1081: true}, price: 5, qty: -0.1, tag: "Gold"}]}, price: 2}], + [{code: "silver", n: 2.5, items: [{price: 0.1, qty: 2, tag: "b"}, {price: 5, tag: "b"}, {price: -1, qty: 18, tag: "a"}, {price: 101, tag: null}], price: 1000000000000000000000, a: -0.1, extra: {deep: {x: 1}}}, {a: -0.1, code: "silver", extra: {deep: {x: 1}}, items: [{price: 0.1, qty: 2, tag: "b"}, {price: 5, tag: "b"}, {price: -1, qty: 18, tag: "a"}, {price: 101, tag: null}], n: 2.5, o: {p: [{g: {k1081: true}, price: 0.1, qty: 2, tag: "b"}, {g: {k1081: true}, price: 5, tag: "b"}, {g: {k1081: true}, price: -1, qty: 18, tag: "a"}, {g: {k1081: true}, price: 101, tag: null}]}, price: 1000000000000000000000}], + [{b: 1, code: "silver", n: 7, items: [{price: 21, qty: 5, tag: "b"}], flag: false, price: 50, a: 1000}, {a: 1000, b: 1, code: "silver", flag: false, items: [{price: 21, qty: 5, tag: "b"}], n: 7, o: {p: [{g: {k1081: true}, price: 21, qty: 5, tag: "b"}]}, price: 50}], + [{b: null, n: 18, items: [{price: 21, qty: -25, tag: ""}, {price: -0.1, qty: 1, tag: "gold"}], price: 2, a: -25}, {a: -25, items: [{price: 21, qty: -25, tag: ""}, {price: -0.1, qty: 1, tag: "gold"}], n: 18, o: {p: [{g: {k1081: true}, price: 21, qty: -25, tag: ""}, {g: {k1081: true}, price: -0.1, qty: 1, tag: "gold"}]}, price: 2}], + [{b: 21, code: "a", n: 0.1, items: [{price: 100, qty: -1, tag: "bronze"}, {price: -0.1, qty: 10, tag: "Gold"}, {price: 3, qty: 1000000000000000000000, tag: "a"}], flag: "no", price: 19.99, a: 1000}, {a: 1000, b: 21, code: "a", flag: "no", items: [{price: 100, qty: -1, tag: "bronze"}, {price: -0.1, qty: 10, tag: "Gold"}, {price: 3, qty: 1000000000000000000000, tag: "a"}], n: 0.1, price: 19.99}], + ], +} + +{ + name: "gb079: 8 nodes, table, expr, table*, expr, expr, expr, table*, table", + graph: { + nodes: [ + {table: "t1", inputs: ["tier", "n", null], outputs: ["k1086", "k1086"], passThrough: true, rules: [ + ["", "[18..28)", "5", "0.25", "`${(n ?? 0)}-${'A-1'}`"], + ["startsWith($, 'a')", "null", "$ != null", "0", "''"], + ["not('silver')", "100", "'gold'", "-5", "''"], + ["not('x')", "[-1..49]", "", "-5", "'mid'"], + ["not('silver')", "> 1", "'gold'", "1", "'high'"], + ["not('gold')", "100", "5", "min([len((false ? (tier ?? 'none') : (tier ?? 'none'))), (true ? (n ?? 1) : (n ?? 1) * 2)])", "''"], + ["", "", "", "0.25", "'high'"], + ]}, + {expression: "e2", passThrough: true, outputPath: "res", fields: { + k1088: "false", + k1089: "n", + }}, + {table: "t3", hit: "collect", inputs: ["lower(lower('none'))"], outputs: ["k1090", "m.k1091"], passThrough: true, outputPath: "lines", rules: [ + ["", "'low'", "((n ?? 1)) / 0.5 - len((k1086 ?? '')) in [0..10]"], + ["not('silver')", "trim((tier ?? '?')) + '-' + (k1086 ?? '')", "false"], + ["null", "'low'", "false"], + ["'x'", "'mid'", "true"], + ["'silver'", "'high'", "false"], + ["", "'high'", "true"], + ]}, + {expression: "e4", fields: { + k1092: "(false) and (true)", + k1093: "string(len('A-1') % 7)", + }}, + {expression: "e5", fields: { + "res.k1094": "100", + k1095: "string(true) + ':' + string((res.k1088 ?? false)) + '' + string((tier ?? '?') in ['gold', 'silver', 'a'])", + k1096: "res.k1089", + }}, + {expression: "e6", passThrough: true, outputPath: "out", fields: { + k1097: "k1092", + }}, + {table: "t7", hit: "collect", inputs: ["n", "n"], outputs: ["k1098"], outputPath: "o.p", rules: [ + ["(0..1)", "", "'gold'"], + ["[100..105)", "[5..55]", "'high'"], + ["(-1..9)", "50, 60", "'mid'"], + ["(1..51)", "> 0", "(k1093 ?? 'none') + '-' + string((k1092 ?? false)) + ':' + `n=${(n ?? 1)}-${(tier ?? '?')}`"], + ]}, + {table: "t8", inputs: ["len((k1093 ?? '?'))", "k1093", "k1092"], outputs: ["k1099"], passThrough: true, outputPath: "o.p", rules: [ + ["$ > 10 and $ < 15", "startsWith($, 'x')", "", "(2.25 > 10 ? -(2.25) : 10 * 3) * (100)"], + ["not(10)", "$ != ''", "", "100"], + ["", "", "true", "2"], + ["(100..110)", "", "", "1"], + ["", "''", "$ == true", "3"], + ["", "", "", "0.25"], + ]}, + ], + edges: [ + "input -> t1", + "input -> e2", + "t1 -> t3", + "input -> t3", + "t1 -> e4", + "e2 -> e5", + "e4 -> e6", + "input -> t7", + "e6 -> t7", + "e4 -> t8", + "t1 -> output", + "t3 -> output", + "e5 -> output", + "t7 -> output", + "t8 -> output", + ], + }, + cases: [ + [{tier: "a", code: "bronze", n: 10, nums: [1, 1000000000000000000000]}, {code: "bronze", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsetrue", k1096: 10, lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], n: 10, nums: [1, 1000000000000000000000], o: {p: [{k1098: "3-false:n=10-a"}]}, res: {k1094: 100}, tier: "a"}], + [{tier: "Gold", code: "gold", nums: 7}, {code: "gold", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsefalse", lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], nums: 7, o: {p: []}, res: {k1094: 100}, tier: "Gold"}], + [{tier: "b", code: "silver", n: 1, nums: [1000000000000000000000, -25, 1000000000000000000000, 2.5, 19.99]}, {code: "silver", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsefalse", k1096: 1, lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], n: 1, nums: [1000000000000000000000, -25, 1000000000000000000000, 2.5, 19.99], o: {p: []}, res: {k1094: 100}, tier: "b"}], + [{tier: "a", code: "bronze", n: 1, nums: [3, -25, 1, -25, 1000000000000000000000]}, {code: "bronze", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsetrue", k1096: 1, lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], n: 1, nums: [3, -25, 1, -25, 1000000000000000000000], o: {p: []}, res: {k1094: 100}, tier: "a"}], + [{tier: "silver", code: "b", n: 65, extra: {deep: {x: 1}}}, {code: "b", extra: {deep: {x: 1}}, k1086: "high", k1092: false, k1093: "3", k1095: "true:falsetrue", k1096: 65, lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], n: 65, o: {p: []}, res: {k1094: 100}, tier: "silver"}], + [{tier: "zz", code: "Gold", n: -1, nums: [21]}, {code: "Gold", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsefalse", k1096: -1, lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], n: -1, nums: [21], o: {p: []}, res: {k1094: 100}, tier: "zz"}], + [{tier: "bronze", code: null, n: 5, nums: [10, 100]}, {k1086: "high", k1092: false, k1093: "3", k1095: "true:falsefalse", k1096: 5, lines: [{k1090: "low", m: {k1091: true}}, {k1090: "high", m: {k1091: true}}], n: 5, nums: [10, 100], o: {p: [{k1098: "3-false:n=5-bronze"}]}, res: {k1094: 100}, tier: "bronze"}], + [{tier: null, code: "silver", n: 101, nums: []}, {code: "silver", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsefalse", k1096: 101, lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], n: 101, nums: [], o: {p: []}, res: {k1094: 100}}], + [{tier: "silver", code: "gold ", nums: [2.5, 101, 0, 0, 18]}, {code: "gold ", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsetrue", lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], nums: [2.5, 101, 0, 0, 18], o: {p: []}, res: {k1094: 100}, tier: "silver"}], + [{tier: null, code: "Gold", n: 5, nums: [{x: 1}]}, {code: "Gold", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsefalse", k1096: 5, lines: [{k1090: "low", m: {k1091: true}}, {k1090: "high", m: {k1091: true}}], n: 5, nums: [{x: 1}], o: {p: [{k1098: "3-false:n=5-?"}]}, res: {k1094: 100}}], + [{tier: "Gold", code: "gold", n: -1, nums: [1000000000000000000000, 5, 2]}, {code: "gold", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsefalse", k1096: -1, lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], n: -1, nums: [1000000000000000000000, 5, 2], o: {p: []}, res: {k1094: 100}, tier: "Gold"}], + [{tier: "b", code: "silver", n: 99, nums: 7}, {code: "silver", k1086: "high", k1092: false, k1093: "3", k1095: "true:falsefalse", k1096: 99, lines: [{k1090: "low", m: {k1091: false}}, {k1090: "high", m: {k1091: true}}], n: 99, nums: 7, o: {p: []}, res: {k1094: 100}, tier: "b"}], + ], +} diff --git a/core/engine/tests/spec/graph/72-generated-minimal.json5 b/core/engine/tests/spec/graph/72-generated-minimal.json5 new file mode 100644 index 00000000..6f7fd2e4 --- /dev/null +++ b/core/engine/tests/spec/graph/72-generated-minimal.json5 @@ -0,0 +1,447 @@ +// Minimal reproductions of the compiled-engine mismatches found by the generated chapters 70 and +// 71 (and by extra seeds of the same generator, scratchpad gen/graphgen.py run with seeds 1-6). +// Each suite was shrunk with gen/shrink.py and then rewritten by hand. Outputs recorded from the +// walker; this chapter exists to differential-test the engines, so every case here pins the +// walker's answer even where the walker's answer itself is questionable (see the notes). + +// --- A. A node environment that is not an object ------------------------------------------------ +// inputField can select a string, number, bool or array, and a loop can iterate over items that +// are not objects. The walker then fails every field read of that environment: in an expression +// the node errors, in a table the input cell fails to match and an output cell drops its output. +// The compiled engine in batch and columnar mode reads such fields as null instead, so `null`, +// `!=` and wildcard-with-`??` cells match and outputs appear. + +{ + name: "A1: table input cell over an inputField that selects a non-object", + graph: { + nodes: [ + {table: "t", inputField: "cust", inputs: ["age"], outputs: ["r"], rules: [ + ["null", "'null'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{cust: {age: 3}}, {r: "other"}], + [{cust: {age: null}}, {r: "null"}], + [{cust: {}}, {r: "null"}], + [{}, {r: "null"}], + [{cust: null}, {r: "null"}], + [{cust: "cust"}, {r: "other"}], + [{cust: 5}, {r: "other"}], + [{cust: true}, {r: "other"}], + [{cust: []}, {r: "other"}], + [{cust: [{age: 3}]}, {r: "other"}], + ], +} + +{ + name: "A1: a not-equal cell matches null in batch over a non-object inputField", + graph: { + nodes: [ + {table: "t", inputField: "cust", inputs: ["age"], outputs: ["r"], rules: [ + ["!= -1", "'gold'"], + ]}, + ], + }, + cases: [ + [{cust: {age: 3}}, {r: "gold"}], + [{cust: {age: -1}}, {}], + [{cust: [{age: 3}]}, {}], + [{cust: "x"}, {}], + [{cust: {}}, {r: "gold"}], + ], +} + +{ + name: "A1: an output cell reading a non-object inputField", + graph: { + nodes: [ + {table: "t", inputField: "cust", inputs: [], outputs: ["r"], rules: [ + ["-((age ?? 1)) % 3"], + ]}, + ], + }, + cases: [ + [{cust: {age: 4}}, {r: -1}], + [{cust: {}}, {r: -1}], + [{cust: [{age: 3}]}, {}], + [{cust: 5}, {}], + [{cust: null}, {r: -1}], + ], +} + +{ + name: "A1: a collect table with outputPath over a non-object inputField", + graph: { + nodes: [ + {table: "t", hit: "collect", inputField: "cust", inputs: [], outputs: ["v"], outputPath: "res", rules: [ + ["-((age ?? 1) + 0.5)"], + ["2"], + ]}, + ], + }, + cases: [ + [{cust: {age: 1}}, {res: [{v: -1.5}, {v: 2}]}], + [{cust: 5}, {res: [{v: 2}]}], + [{cust: "a"}, {res: [{v: 2}]}], + [{cust: {}}, {res: [{v: -1.5}, {v: 2}]}], + ], +} + +{ + name: "A1: a dotted output of a table over a non-object inputField reaches the output node", + graph: { + nodes: [ + {table: "t1", inputField: "cust", inputs: ["age"], outputs: ["g.k"], rules: [ + ["null", "true"], + ]}, + {expression: "e", fields: {other: "1"}}, + ], + edges: ["input -> t1", "input -> e", "t1 -> output", "e -> output"], + }, + cases: [ + [{cust: 5}, {other: 1}], + [{cust: {age: null}}, {g: {k: true}, other: 1}], + [{cust: {age: 2}}, {other: 1}], + [{cust: "c"}, {other: 1}], + ], +} + +{ + name: "A2: a loop table over items that are not objects", + graph: { + nodes: [ + {table: "t", inputField: "items", executionMode: "loop", inputs: [], outputs: ["v"], rules: [ + ["(qty ?? 2) * (price ?? -1)"], + ]}, + ], + }, + cases: [ + [{items: [{qty: 1, price: 3}, {}]}, [{v: 3}, {v: -2}]], + [{items: [1, 2]}, [null, null]], + [{items: ["a"]}, [null]], + [{items: [{price: 2}, 7]}, [{v: 4}, null]], + [{items: []}, []], + ], +} + +{ + name: "A2: a loop table with an input column over items that are not objects", + graph: { + nodes: [ + {table: "t", inputField: "items", executionMode: "loop", inputs: ["qty"], outputs: ["v"], rules: [ + ["null", "'none'"], + ["", "'any'"], + ]}, + ], + }, + cases: [ + [{items: [{qty: 1}, {}]}, [{v: "any"}, {v: "none"}]], + [{items: [1, true]}, [{v: "any"}, {v: "any"}]], + [{items: [[1]]}, [{v: "any"}]], + ], +} + +{ + name: "A3: an expression over a non-object inputField that reads it only in an untaken branch", + graph: { + nodes: [ + {expression: "e", inputField: "cust", fields: {k: "false ? -(age ?? 0) : $.missing", c: "1 + 1"}}, + ], + }, + cases: [ + [{cust: {age: 1}}, {c: 2}], + [{cust: 5}, {c: 2}], + [{cust: "x"}, {c: 2}], + [{cust: []}, {c: 2}], + [{}, {c: 2}], + ], +} + +{ + name: "A4: columnar reports a later field's error for a non-object inputField", + graph: { + nodes: [{expression: "e", inputField: "cust", fields: {r: "(age ?? 0)", t: "len(tier)"}}], + }, + cases: [ + [{cust: []}, "!error"], + [{cust: {age: -25, tier: null}}, "!error"], + [{cust: {age: 5, tier: "Gold"}}, {r: 5, t: 4}], + [{cust: {age: 99, tier: ""}}, {r: 99, t: 0}], + ], +} + +// --- B. A null written at a nested path, when the node's output fans out ---------------------- +// The walker keeps a null written under a dotted key or an outputPath (`{g: {a: null}}`), while a +// top-level null key is dropped. When the writing node feeds both the output node and another +// node whose result is merged at the same join, batch mode drops the nested null (`{g: {}}`). +// Single and columnar mode agree with the walker. + +{ + name: "B: passThrough dotted null, fanned out to the output and through a second passThrough node", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: {"g.a": "score"}}, + {expression: "e2", passThrough: true, fields: {z: "1"}}, + ], + edges: ["input -> e1", "e1 -> e2", "e1 -> output", "e2 -> output"], + }, + cases: [ + {input: {n: 2.5, score: null}, output: {g: {a: null}, n: 2.5, z: 1}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {n: 2.5, score: 1}, output: {g: {a: 1}, n: 2.5, score: 1, z: 1}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {n: 2}, output: {g: {a: null}, n: 2, z: 1}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {score: "s"}, output: {g: {a: "s"}, score: "s", z: 1}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + ], +} + +{ + name: "B: the same graph without the fan-out keeps the null in batch", + graph: { + nodes: [ + {expression: "e1", passThrough: true, fields: {"g.a": "score"}}, + {expression: "e2", passThrough: true, fields: {z: "1"}}, + ], + }, + cases: [ + {input: {n: 2.5, score: null}, output: {g: {a: null}, n: 2.5, z: 1}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {n: 2.5, score: 1}, output: {g: {a: 1}, n: 2.5, score: 1, z: 1}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {n: 2}, output: {g: {a: null}, n: 2, z: 1}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + ], +} + +{ + name: "B: an outputPath null read by a passThrough sibling", + graph: { + nodes: [ + {expression: "e1", outputPath: "lines", fields: {k: "n ?? n"}}, + {expression: "e2", passThrough: true, fields: {j: "lines.other ?? 0"}}, + ], + edges: ["input -> e1", "e1 -> e2", "e2 -> output", "e1 -> output"], + }, + cases: [ + {input: {}, output: {j: 0, lines: {k: null}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {n: 1}, output: {j: 0, lines: {k: 1}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {n: null}, output: {j: 0, lines: {k: null}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {n: "x"}, output: {j: 0, lines: {k: "x"}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + ], +} + +{ + name: "B: a dotted null joined with a passThrough table downstream", + graph: { + nodes: [ + {expression: "e1", fields: {"res.k": "active ?? tier"}}, + {table: "t", inputs: [], outputs: ["done"], passThrough: true, rules: [["true"]]}, + ], + edges: ["input -> e1", "e1 -> output", "e1 -> t", "t -> output"], + }, + cases: [ + {input: {}, output: {done: true, res: {k: null}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {active: true}, output: {done: true, res: {k: true}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {tier: "gold"}, output: {done: true, res: {k: "gold"}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {active: null, tier: null}, output: {done: true, res: {k: null}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + ], +} + +{ + name: "B: a non-matching passThrough table with outputPath writes null under the path", + graph: { + nodes: [ + {table: "t1", inputs: [], outputs: ["a"], rules: [["'mid'"]]}, + {table: "t2", inputs: ["'x'"], outputs: ["v"], passThrough: true, outputPath: "o.p", rules: [ + ["'gold'", "1"], + ]}, + {expression: "e", fields: {s: "score ?? 0"}}, + ], + edges: ["input -> t1", "t1 -> t2", "t2 -> output", "input -> e", "e -> output"], + }, + cases: [ + {input: {}, output: {a: "mid", o: {p: null}, s: 0}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {score: 3}, output: {a: "mid", o: {p: null}, s: 3}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {score: null}, output: {a: "mid", o: {p: null}, s: 0}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + ], +} + +{ + name: "B: a nested null and a collect array meet at the same output key", + graph: { + nodes: [ + {table: "t1", inputs: [], outputs: ["ok"], rules: [["true"]]}, + {expression: "e2", passThrough: true, fields: {"res.k": "missing"}}, + {table: "t3", hit: "collect", inputs: [], outputs: ["v[]"], outputPath: "res", rules: [["10"]]}, + ], + edges: ["input -> t1", "t1 -> e2", "e2 -> output", "t1 -> t3", "t3 -> output"], + }, + cases: [ + {input: {}, output: {ok: true, res: {k: null}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {missing: 1}, output: {ok: true, res: {k: null}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + {input: {missing: null}, output: {ok: true, res: {k: null}}, engines: "OPEN compiled bug: batch mode drops a null written at a nested path when the writing node fans out; single and columnar agree with the walker"}, + ], +} + +// --- C. passThrough over a node input that is an array ------------------------------------------- +// A collect table without outputPath outputs an array. A passThrough table downstream then has an +// array as its input: the walker returns that array and drops the table's own outputs (a +// passThrough expression instead drops the array), and at the output node an array parent also +// discards the object output of a sibling merged after it. Batch and columnar produce `{}` for the +// first and keep every sibling's object for the second. + +{ + name: "C: a matching passThrough table after a collect table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: [], outputs: ["a"], rules: [["'high'"]]}, + {table: "t2", inputs: ["1"], outputs: ["res.v"], passThrough: true, rules: [["not(50)", "100"]]}, + ], + }, + cases: [ + [{}, [{a: "high"}], "question: a passThrough expression over an array input keeps its own fields and drops the array (next suite), while a passThrough table returns the array and drops its matched output `res.v`"], + [{x: 1}, [{a: "high"}], "question: a passThrough expression over an array input keeps its own fields and drops the array (next suite), while a passThrough table returns the array and drops its matched output `res.v`"], + [{a: "in"}, [{a: "high"}], "question: a passThrough expression over an array input keeps its own fields and drops the array (next suite), while a passThrough table returns the array and drops its matched output `res.v`"], + ], +} + +{ + name: "C: a passThrough expression after a collect table", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: ["n"], outputs: ["a"], rules: [["> 0", "'pos'"], ["", "'any'"]]}, + {expression: "e", passThrough: true, fields: {k: "1"}}, + ], + }, + cases: [ + [{n: 1}, {k: 1}], + [{n: -1}, {k: 1}], + [{}, {k: 1}], + ], +} + +{ + name: "C: an array parent at the output node next to object siblings", + graph: { + nodes: [ + {expression: "e1", fields: {a: "n ?? 0"}}, + {expression: "e2", fields: {b: "n ?? 0"}}, + {table: "t1", hit: "collect", inputs: [], outputs: ["c[]"], rules: [["2"]]}, + {table: "t2", inputs: ["'false'"], outputs: ["d"], passThrough: true, rules: [["null", "20"]]}, + ], + edges: ["input -> e1", "input -> e2", "input -> t1", "t1 -> t2", "e1 -> output", "t2 -> output", "e2 -> output"], + }, + cases: [ + [{n: 11}, {a: 11}, "question: the array from t2 at the output node discards e2's object output `b`, but not e1's `a`"], + [{}, {a: 0}, "question: the array from t2 at the output node discards e2's object output `b`, but not e1's `a`"], + [{n: 0}, {a: 0}, "question: the array from t2 at the output node discards e2's object output `b`, but not e1's `a`"], + ], +} + +// --- D. A loop over an array node input reports a different error ------------------------------ +// A loop whose inputField reads a field of an array input: both engines fail, with different +// messages (walker: the VM's `FetchEnv: Unsupported type`; batch and columnar: `Expected an array`). + +{ + name: "D: a loop node whose input is an array", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: [], outputs: ["v"], rules: [["0.25"]]}, + {expression: "e2", inputField: "items", executionMode: "loop", outputPath: "lines", fields: {k: "tag ?? 'none'"}}, + ], + }, + cases: [ + [{}, "!error"], + [{items: [{tag: "a"}]}, "!error"], + ], +} + +// --- E. An expression node whose input is an array ------------------------------------------------ +// After a collect table without outputPath, an expression node's environment is the array of +// matched rows. The walker reads a member path such as `res.x` as null there, while a bare +// identifier (`a`, or an inputField `cust`) fails the node. The compiled engine fails the member +// path too, in single and DecisionEngine mode (batch agrees with the walker), and in batch and +// columnar mode reads the inputField as null and evaluates the node. + +{ + name: "E: a member path read from an array environment", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: [], outputs: ["a"], rules: [["'mid'"]]}, + {expression: "e", fields: {k: "res.x"}}, + ], + }, + cases: [ + [{}, {}, "question: the walker reads `res.x` from an array environment as null but fails on a bare identifier (next suite); one of the two is inconsistent"], + [{res: {x: 1}}, {}, "question: the walker reads `res.x` from an array environment as null but fails on a bare identifier (next suite); one of the two is inconsistent"], + [{a: 1}, {}, "question: the walker reads `res.x` from an array environment as null but fails on a bare identifier (next suite); one of the two is inconsistent"], + ], +} + +{ + name: "E: a bare identifier read from an array environment fails on both engines", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: [], outputs: ["a"], rules: [["'mid'"]]}, + {expression: "e", fields: {k: "a ?? 'none'"}}, + ], + }, + cases: [ + [{}, "!error"], + [{a: 1}, "!error"], + ], +} + +{ + name: "E: an inputField read from an array environment", + graph: { + nodes: [ + {table: "t1", hit: "collect", inputs: [], outputs: ["res.v"], rules: [["1"]]}, + {expression: "e", inputField: "cust", fields: {k: "(active ?? false) and true"}}, + ], + }, + cases: [ + [{}, "!error"], + [{cust: {active: true}}, "!error"], + [{cust: 5}, "!error"], + ], +} + +// --- F. Columnar: a null under an outputPath against an array under the same path ------------------ +// A non-matching passThrough table with outputPath writes null at that path; a loop or collect +// node writes an array at the same path. The walker's merge at the output node lets the null +// win (and drops the key); the columnar result keeps the array. Single and batch agree with the +// walker. Probably the columnar side of B (a nested null treated as absent). + +{ + name: "F: a non-matching passThrough table and a loop table share an outputPath", + graph: { + nodes: [ + {table: "t1", inputs: ["s"], outputs: ["v"], passThrough: true, outputPath: "o.p", rules: [["'gold', 'b'", "true"]]}, + {table: "t2", inputField: "items", executionMode: "loop", inputs: [], outputs: ["res.k"], outputPath: "o.p", rules: [["2"]]}, + ], + edges: ["input -> t1", "input -> t2", "t1 -> output", "t2 -> output"], + }, + cases: [ + {input: {items: [{qty: 0.5, tag: true}, {price: 19.99, qty: 11, tag: "Gold"}, {price: true, tag: "zz"}]}, output: {items: [{qty: 0.5, tag: true}, {price: 19.99, qty: 11, tag: "Gold"}, {price: true, tag: "zz"}], o: {}}, engines: "OPEN compiled bug: columnar keeps the array where the walker lets a null under the same outputPath win"}, + {input: {items: [{qty: 1}], s: "gold"}, output: {items: [{qty: 1}], o: {p: {v: true}}, s: "gold"}, engines: "OPEN compiled bug: columnar keeps the array where the walker lets a null under the same outputPath win"}, + {input: {items: [], s: "x"}, output: {items: [], o: {}, s: "x"}, engines: "OPEN compiled bug: columnar keeps the array where the walker lets a null under the same outputPath win"}, + {input: {items: [{qty: 2}, {qty: 3}]}, output: {items: [{qty: 2}, {qty: 3}], o: {}}, engines: "OPEN compiled bug: columnar keeps the array where the walker lets a null under the same outputPath win"}, + ], +} + +{ + name: "F: a non-matching passThrough table, a passThrough expression and a collect table share an outputPath", + graph: { + nodes: [ + {table: "t1", inputs: ["n"], outputs: ["g.v"], passThrough: true, outputPath: "o.p", rules: [["[5..6)", "'gold'"]]}, + {expression: "e2", passThrough: true, fields: {k: "score"}}, + {table: "t3", hit: "collect", inputs: ["a"], outputs: ["g.w"], outputPath: "o.p", rules: [["> 100", "1"]]}, + {expression: "e5", fields: {c: "o.p.x ?? code"}}, + ], + edges: ["input -> t1", "t1 -> e2", "e2 -> t3", "t1 -> e5", "e2 -> output", "t3 -> output", "e5 -> output"], + }, + cases: [ + {input: {}, output: {o: {}}, engines: "OPEN compiled bug: columnar keeps the array where the walker lets a null under the same outputPath win"}, + {input: {n: 5}, output: {n: 5, o: {p: {g: {v: "gold"}}}}, engines: "OPEN compiled bug: columnar keeps the array where the walker lets a null under the same outputPath win"}, + {input: {a: 101, code: "c"}, output: {a: 101, c: "c", code: "c", o: {}}, engines: "OPEN compiled bug: columnar keeps the array where the walker lets a null under the same outputPath win"}, + {input: {score: 1, n: 7}, output: {k: 1, n: 7, o: {}, score: 1}, engines: "OPEN compiled bug: columnar keeps the array where the walker lets a null under the same outputPath win"}, + ], +} diff --git a/core/engine/tests/spec/policy/00-harness.json5 b/core/engine/tests/spec/policy/00-harness.json5 new file mode 100644 index 00000000..da2c62ee --- /dev/null +++ b/core/engine/tests/spec/policy/00-harness.json5 @@ -0,0 +1,12 @@ +// The harness itself: models, expression blocks, outputs. +{ + name: "one expression block writes a property", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, adult: true}}], + [{customer: {age: 3}}, {customer: {age: 3, adult: false}}], + ], +} diff --git a/core/engine/tests/spec/policy/01-models-and-input.json5 b/core/engine/tests/spec/policy/01-models-and-input.json5 new file mode 100644 index 00000000..444de2a5 --- /dev/null +++ b/core/engine/tests/spec/policy/01-models-and-input.json5 @@ -0,0 +1,799 @@ +// Data models and the input. +// +// A data model declares the INPUT shape of an entity. The entity's root key in the request is the +// model name (`customer: {...}`). Declared properties are inputs: they are validated against their +// declared type, read by blocks, and returned unchanged in the output. Computed properties are the +// ones written by blocks; they are never declared. Writing to a declared property is the +// `InputOverride` compile error. + +// --------------------------------------------------------------------------------------------- +// Input passes through: every input value is returned in the output, computed values are added +// next to it. + +{ + name: "declared inputs pass through next to a computed property", + policy: { + models: {customer: {name: "string", age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {name: "Ann", age: 30}}, {customer: {name: "Ann", age: 30, adult: true}}], + [{customer: {name: "Bob", age: 17}}, {customer: {name: "Bob", age: 17, adult: false}}], + [{customer: {name: "", age: 0}}, {customer: {name: "", age: 0, adult: false}}], + [{customer: {name: "Zed", age: 18}}, {customer: {name: "Zed", age: 18, adult: true}}], + [{customer: {name: "Neg", age: -1}}, {customer: {name: "Neg", age: -1, adult: false}}], + ], +} + +{ + name: "a declared property no block reads still passes through", + policy: { + models: {customer: {name: "string", age: "number", note: "string?"}}, + blocks: [{expression: "customer.label", value: "customer.name"}], + }, + cases: [ + [{customer: {name: "Ann", age: 30}}, {customer: {name: "Ann", age: 30, label: "Ann"}}], + [{customer: {name: "Ann", age: 30, note: "vip"}}, {customer: {name: "Ann", age: 30, note: "vip", label: "Ann"}}], + [{customer: {name: "Ann", note: "x"}}, {customer: {name: "Ann", note: "x", label: "Ann"}}], + ], +} + +{ + name: "undeclared keys on an entity pass through", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20, extra: "x"}}, {customer: {age: 20, extra: "x", adult: true}}], + [{customer: {age: 20, extra: {deep: [1, 2]}}}, {customer: {age: 20, extra: {deep: [1, 2]}, adult: true}}], + [{customer: {age: 20, extra: null}}, {customer: {age: 20, extra: null, adult: true}}], + [{customer: {age: 5, age2: 50}}, {customer: {age: 5, age2: 50, adult: false}}], + ], +} + +{ + name: "extra top-level input keys pass through", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}, meta: {source: "web"}}, {customer: {age: 20, adult: true}, meta: {source: "web"}}], + [{customer: {age: 20}, flag: true, n: 1}, {customer: {age: 20, adult: true}, flag: true, n: 1}], + [{customer: {age: 20}, list: [1, "a", null]}, {customer: {age: 20, adult: true}, list: [1, "a", null]}], + [{customer: {age: 20}, nothing: null}, {customer: {age: 20, adult: true}, nothing: null}], + ], +} + +{ + name: "a policy with only a data model returns the input", + policy: { + models: {customer: {age: "number", name: "string?"}}, + blocks: [], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20}}], + [{customer: {age: 20, name: "Ann"}}, {customer: {age: 20, name: "Ann"}}], + [{}, {}], + [{other: 1}, {other: 1}], + ], +} + +{ + name: "a policy with no blocks at all returns the input", + policy: {blocks: []}, + cases: [ + [{}, {}], + [{a: 1}, {a: 1}], + [{a: {b: [1, 2, {c: null}]}}, {a: {b: [1, 2, {c: null}]}}], + ], +} + +{ + name: "an undeclared entity root key passes through untouched", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}, company: {age: "not validated"}}, {customer: {age: 20, adult: true}, company: {age: "not validated"}}], + [{customer: {age: 20}, Customer: {age: "x"}}, {customer: {age: 20, adult: true}, Customer: {age: "x"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Declared vs undeclared: a computed property is written by a block and must NOT be declared in +// the data model. Declaring it turns the write into a write to an input (`InputOverride`), which +// is a compile error. Evaluation of a policy with compile errors is refused. + +{ + name: "declaring a computed property as optional input is an InputOverride error", + policy: { + models: {customer: {age: "number", adult: "boolean?"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}}, "!error"], + [{customer: {age: 20, adult: false}}, "!error"], + ], +} + +{ + name: "declaring a computed property as required input is an InputOverride error", + policy: { + models: {customer: {age: "number", adult: "boolean"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}}, "!error"], + [{customer: {age: 20, adult: true}}, "!error"], + ], +} + +{ + name: "writing a declared input property is an InputOverride error", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.age", value: "5"}], + }, + cases: [ + [{customer: {age: 20}}, "!error"], + [{customer: {}}, "!error"], + ], +} + +{ + name: "writing below a declared scalar property is an InputOverride error", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.age.months", value: "1"}], + }, + cases: [ + [{customer: {age: 20}}, "!error"], + ], +} + +{ + name: "an undeclared computed property sits next to declared ones", + policy: { + models: {customer: {age: "number", vip: "boolean?"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, adult: true}}], + [{customer: {age: 20, vip: true}}, {customer: {age: 20, vip: true, adult: true}}], + [{customer: {age: 10, vip: false}}, {customer: {age: 10, vip: false, adult: false}}], + ], +} + +{ + name: "an undeclared input key with the computed property's name is overwritten", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20, adult: false}}, {customer: {age: 20, adult: true}}], + [{customer: {age: 10, adult: "yes"}}, {customer: {age: 10, adult: false}}], + [{customer: {age: 10, adult: null}}, {customer: {age: 10, adult: false}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Required vs optional properties. A required property that a block needs must be present and +// not null; the evaluation fails with MissingRequiredInputs before any block runs. An optional +// property may be missing or null, and reads of it give null. + +{ + name: "a missing required property read by a block is an error", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {}}, "!error: MissingRequiredInputs"], + [{customer: {age: null}}, "!error: MissingRequiredInputs"], + [{customer: {other: 1}}, "!error: MissingRequiredInputs"], + [{customer: {age: 18}}, {customer: {age: 18, adult: true}}], + ], +} + +{ + name: "a missing entity root with a required read is an error", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{}, "!error: MissingRequiredInputs"], + [{customer: null}, "!error: MissingRequiredInputs"], + [{other: {age: 20}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a missing required property that no block reads is not an error", + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, adult: true}}], + [{customer: {age: 20, name: null}}, {customer: {age: 20, name: null, adult: true}}], + [{customer: {age: 20, name: "Ann"}}, {customer: {age: 20, name: "Ann", adult: true}}], + ], +} + +{ + name: "every missing required read is reported", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [{expression: "customer.score", value: "customer.age + customer.income"}], + }, + cases: [ + [{customer: {}}, "!error: customer.age"], + [{customer: {}}, "!error: customer.income"], + [{customer: {age: 1}}, "!error: customer.income"], + [{customer: {income: 1}}, "!error: customer.age"], + [{customer: {age: 1, income: 2}}, {customer: {age: 1, income: 2, score: 3}}], + ], +} + +{ + name: "an optional property may be missing or null", + policy: { + models: {customer: {nickname: "string?"}}, + blocks: [{expression: "customer.display", value: "customer.nickname ?? 'anonymous'"}], + }, + cases: [ + [{customer: {}}, {customer: {display: "anonymous"}}], + [{customer: {nickname: null}}, {customer: {nickname: null, display: "anonymous"}}], + [{customer: {nickname: "Al"}}, {customer: {nickname: "Al", display: "Al"}}], + [{customer: {nickname: ""}}, {customer: {nickname: "", display: ""}}], + ], +} + +{ + name: "a read of a missing optional property gives null", + policy: { + models: {customer: {score: "number?"}}, + blocks: [{expression: "customer.copy", value: "customer.score"}], + }, + cases: [ + [{customer: {}}, {customer: {copy: null}}], + [{customer: {score: null}}, {customer: {score: null, copy: null}}], + [{customer: {score: 7}}, {customer: {score: 7, copy: 7}}], + [{customer: {score: 0}}, {customer: {score: 0, copy: 0}}], + ], +} + +{ + name: "an optional entity root may be missing when only optional properties are read", + policy: { + models: {customer: {score: "number?"}}, + blocks: [{expression: "result", value: "customer.score ?? -1"}], + }, + cases: [ + [{customer: {score: 3}}, {customer: {score: 3}, result: 3}], + [{customer: {}}, {customer: {}, result: -1}], + [{}, {result: -1}], + ], +} + +{ + name: "required and optional properties mixed", + policy: { + models: {order: {total: "number", discount: "number?"}}, + blocks: [{expression: "order.due", value: "order.total - (order.discount ?? 0)"}], + }, + cases: [ + [{order: {total: 100}}, {order: {total: 100, due: 100}}], + [{order: {total: 100, discount: 15}}, {order: {total: 100, discount: 15, due: 85}}], + [{order: {total: 100, discount: null}}, {order: {total: 100, discount: null, due: 100}}], + [{order: {discount: 15}}, "!error: MissingRequiredInputs"], + [{order: {total: 0.1, discount: 0.3}}, {order: {total: 0.1, discount: 0.3, due: -0.2}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Wrong input types. A present, non-null value must have the declared type, also for properties +// that no block reads. The whole input is validated before evaluation. + +{ + name: "a number property rejects other types", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: "20"}}, "!error: InputValidationFailed"], + [{customer: {age: true}}, "!error: InputValidationFailed"], + [{customer: {age: [20]}}, "!error: InputValidationFailed"], + [{customer: {age: {value: 20}}}, "!error: InputValidationFailed"], + [{customer: {age: 20.5}}, {customer: {age: 20.5, adult: true}}], + ], +} + +{ + name: "a string property rejects other types", + policy: { + models: {customer: {name: "string"}}, + blocks: [{expression: "customer.greeting", value: "'Hi ' + customer.name"}], + }, + cases: [ + [{customer: {name: 1}}, "!error: InputValidationFailed"], + [{customer: {name: false}}, "!error: InputValidationFailed"], + [{customer: {name: ["Ann"]}}, "!error: InputValidationFailed"], + [{customer: {name: "Ann"}}, {customer: {name: "Ann", greeting: "Hi Ann"}}], + [{customer: {name: ""}}, {customer: {name: "", greeting: "Hi "}}], + ], +} + +{ + name: "a boolean property rejects other types", + policy: { + models: {customer: {active: "boolean"}}, + blocks: [{expression: "customer.status", value: "customer.active ? 'on' : 'off'"}], + }, + cases: [ + [{customer: {active: "true"}}, "!error: InputValidationFailed"], + [{customer: {active: 1}}, "!error: InputValidationFailed"], + [{customer: {active: 0}}, "!error: InputValidationFailed"], + [{customer: {active: true}}, {customer: {active: true, status: "on"}}], + [{customer: {active: false}}, {customer: {active: false, status: "off"}}], + ], +} + +{ + name: "a wrong type on a property no block reads is still rejected", + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20, name: 5}}, "!error: InputValidationFailed"], + [{customer: {age: 20, name: "ok"}}, {customer: {age: 20, name: "ok", adult: true}}], + ], +} + +{ + name: "the validation error names the path and expected type", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: "x"}}, "!error: customer.age"], + ], +} + +{ + name: "an entity root that is not an object is rejected", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: 5}, "!error: InputValidationFailed"], + [{customer: "Ann"}, "!error: InputValidationFailed"], + [{customer: [{age: 20}]}, "!error: InputValidationFailed"], + [{customer: true}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an input that is not an object is rejected", + policy: { + models: {customer: {age: "number?"}}, + blocks: [{expression: "result", value: "1"}], + }, + cases: [ + [[1, 2], "!error: InputValidationFailed"], + [5, "!error: InputValidationFailed"], + ["text", "!error: InputValidationFailed"], + [{}, {result: 1}], + ], +} + +{ + name: "null input values skip validation", + policy: { + models: {customer: {age: "number?", name: "string?", tags: "string[]?"}}, + blocks: [{expression: "customer.known", value: "customer.age != null"}], + }, + cases: [ + [{customer: {age: null, name: null, tags: null}}, {customer: {age: null, name: null, tags: null, known: false}}], + [{customer: {age: 1, name: null}}, {customer: {age: 1, name: null, known: true}}], + ], +} + +{ + name: "undeclared entity keys are not validated", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20, whatever: [1, "two", {three: 3}]}}, {customer: {age: 20, whatever: [1, "two", {three: 3}], adult: true}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Enum strings: `string(a|b|c)`. Only the listed values are accepted; matching is exact +// (case-sensitive, no trimming). + +{ + name: "an enum property accepts listed values", + policy: { + models: {customer: {tier: "string(gold|silver|bronze)"}}, + blocks: [{expression: "customer.premium", value: "customer.tier == 'gold'"}], + }, + cases: [ + [{customer: {tier: "gold"}}, {customer: {tier: "gold", premium: true}}], + [{customer: {tier: "silver"}}, {customer: {tier: "silver", premium: false}}], + [{customer: {tier: "bronze"}}, {customer: {tier: "bronze", premium: false}}], + ], +} + +{ + name: "an enum property rejects other values", + policy: { + models: {customer: {tier: "string(gold|silver|bronze)"}}, + blocks: [{expression: "customer.premium", value: "customer.tier == 'gold'"}], + }, + cases: [ + [{customer: {tier: "platinum"}}, "!error: InputValidationFailed"], + [{customer: {tier: "Gold"}}, "!error: InputValidationFailed"], + [{customer: {tier: " gold"}}, "!error: InputValidationFailed"], + [{customer: {tier: ""}}, "!error: InputValidationFailed"], + [{customer: {tier: 1}}, "!error: InputValidationFailed"], + [{customer: {tier: true}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an optional enum may be missing or null", + policy: { + models: {customer: {tier: "string(gold|silver)?"}}, + blocks: [{expression: "customer.label", value: "customer.tier ?? 'none'"}], + }, + cases: [ + [{customer: {}}, {customer: {label: "none"}}], + [{customer: {tier: null}}, {customer: {tier: null, label: "none"}}], + [{customer: {tier: "silver"}}, {customer: {tier: "silver", label: "silver"}}], + [{customer: {tier: "bronze"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an enum array validates each item", + policy: { + models: {customer: {roles: "string(admin|user)[]"}}, + blocks: [{expression: "customer.isAdmin", value: "'admin' in customer.roles"}], + }, + cases: [ + [{customer: {roles: ["admin", "user"]}}, {customer: {roles: ["admin", "user"], isAdmin: true}}], + [{customer: {roles: ["user"]}}, {customer: {roles: ["user"], isAdmin: false}}], + [{customer: {roles: []}}, {customer: {roles: [], isAdmin: false}}], + [{customer: {roles: ["user", "root"]}}, "!error: InputValidationFailed"], + [{customer: {roles: "admin"}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dates. A `date` property accepts a date string (ISO date or date-time) and is converted to a +// date value before evaluation; the output carries the date value. + +{ + name: "a date property is read as a date", + policy: { + models: {customer: {birth: "date"}}, + blocks: [{expression: "customer.year", value: "d(customer.birth).year()"}], + }, + cases: [ + [{customer: {birth: "2000-05-17"}}, {customer: {birth: date("2000-05-17"), year: 2000}}], + [{customer: {birth: "1999-12-31"}}, {customer: {birth: date("1999-12-31"), year: 1999}}], + [{customer: {birth: "2024-02-29T10:00:00Z"}}, {customer: {birth: date("2024-02-29T10:00:00Z"), year: 2024}}], + ], +} + +{ + name: "a date property supports date comparison against now", + policy: { + models: {contract: {ends: "date"}}, + blocks: [{expression: "contract.expired", value: "d(contract.ends) < d()"}], + }, + cases: [ + [{contract: {ends: "2025-03-19"}}, {contract: {ends: date("2025-03-19"), expired: true}}], + [{contract: {ends: "2025-03-21"}}, {contract: {ends: date("2025-03-21"), expired: false}}], + [{contract: {ends: "2030-01-01"}}, {contract: {ends: date("2030-01-01"), expired: false}}], + ], +} + +{ + name: "a date property rejects non-date strings and other types", + policy: { + models: {contract: {ends: "date"}}, + blocks: [{expression: "contract.expired", value: "d(contract.ends) < d()"}], + }, + cases: [ + [{contract: {ends: "not a date"}}, "!error: InputValidationFailed"], + [{contract: {ends: 20250101}}, "!error: InputValidationFailed"], + [{contract: {ends: true}}, "!error: InputValidationFailed"], + [{contract: {ends: "2025-13-45"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an optional date may be missing or null", + policy: { + models: {contract: {ends: "date?"}}, + blocks: [{expression: "contract.open", value: "contract.ends == null"}], + }, + cases: [ + [{contract: {}}, {contract: {open: true}}], + [{contract: {ends: null}}, {contract: {ends: null, open: true}}], + [{contract: {ends: "2025-01-01"}}, {contract: {ends: date("2025-01-01"), open: false}}], + ], +} + +{ + name: "an empty date string is accepted", + policy: { + models: {contract: {ends: "date?"}}, + blocks: [{expression: "contract.has", value: "contract.ends != null"}], + }, + cases: [ + [{contract: {ends: ""}}, {contract: {ends: "", has: true}}, "question: the validator accepts an empty date string and passes it through as a string, so it is neither a date nor null"], + ], +} + +{ + name: "a date array converts every item", + policy: { + models: {customer: {visits: "date[]"}}, + blocks: [{expression: "customer.count", value: "len(customer.visits)"}], + }, + cases: [ + [{customer: {visits: ["2025-01-01", "2025-02-01"]}}, {customer: {visits: [date("2025-01-01"), date("2025-02-01")], count: 2}}], + [{customer: {visits: []}}, {customer: {visits: [], count: 0}}], + [{customer: {visits: ["2025-01-01", "nope"]}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Arrays of primitives: `number[]`, `string[]`, `boolean[]`. The value must be an array; each +// non-null item must have the element type. + +{ + name: "a number array is read whole", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [{expression: "cart.total", value: "sum(cart.prices)"}], + }, + cases: [ + [{cart: {prices: [1, 2, 3]}}, {cart: {prices: [1, 2, 3], total: 6}}], + [{cart: {prices: []}}, {cart: {prices: [], total: 0}}], + [{cart: {prices: [0.1, 0.2]}}, {cart: {prices: [0.1, 0.2], total: 0.3}}], + [{cart: {prices: [-5]}}, {cart: {prices: [-5], total: -5}}], + ], +} + +{ + name: "a number array rejects wrong item types and non-arrays", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [{expression: "cart.total", value: "sum(cart.prices)"}], + }, + cases: [ + [{cart: {prices: [1, "2"]}}, "!error: InputValidationFailed"], + [{cart: {prices: 5}}, "!error: InputValidationFailed"], + [{cart: {prices: "1,2"}}, "!error: InputValidationFailed"], + [{cart: {prices: {a: 1}}}, "!error: InputValidationFailed"], + [{cart: {prices: [[1]]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a missing required array is an error", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [{expression: "cart.count", value: "len(cart.prices)"}], + }, + cases: [ + [{cart: {}}, "!error: MissingRequiredInputs"], + [{cart: {prices: null}}, "!error: MissingRequiredInputs"], + [{cart: {prices: []}}, {cart: {prices: [], count: 0}}], + ], +} + +{ + name: "an optional array may be missing", + policy: { + models: {cart: {prices: "number[]?"}}, + blocks: [{expression: "cart.count", value: "len(cart.prices ?? [])"}], + }, + cases: [ + [{cart: {}}, {cart: {count: 0}}], + [{cart: {prices: null}}, {cart: {prices: null, count: 0}}], + [{cart: {prices: [4, 5]}}, {cart: {prices: [4, 5], count: 2}}], + ], +} + +{ + name: "null items inside a primitive array are accepted", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [{expression: "cart.count", value: "len(cart.prices)"}], + }, + cases: [ + [{cart: {prices: [1, null, 3]}}, {cart: {prices: [1, null, 3], count: 3}}], + [{cart: {prices: [null]}}, {cart: {prices: [null], count: 1}}], + ], +} + +{ + name: "a string array is read with membership", + policy: { + models: {customer: {tags: "string[]"}}, + blocks: [{expression: "customer.vip", value: "'vip' in customer.tags"}], + }, + cases: [ + [{customer: {tags: ["vip", "new"]}}, {customer: {tags: ["vip", "new"], vip: true}}], + [{customer: {tags: ["new"]}}, {customer: {tags: ["new"], vip: false}}], + [{customer: {tags: []}}, {customer: {tags: [], vip: false}}], + [{customer: {tags: [1]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a boolean array is reduced", + policy: { + models: {checks: {results: "boolean[]"}}, + blocks: [{expression: "checks.allPassed", value: "all(checks.results, #)"}], + }, + cases: [ + [{checks: {results: [true, true]}}, {checks: {results: [true, true], allPassed: true}}], + [{checks: {results: [true, false]}}, {checks: {results: [true, false], allPassed: false}}], + [{checks: {results: []}}, {checks: {results: [], allPassed: true}}], + [{checks: {results: ["true"]}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Several entities in one input. Each root model is its own top-level key. + +{ + name: "two root entities are read side by side", + policy: { + models: {customer: {age: "number"}, order: {total: "number"}}, + blocks: [{expression: "order.allowed", value: "customer.age >= 18 and order.total < 1000"}], + }, + cases: [ + [{customer: {age: 20}, order: {total: 10}}, {customer: {age: 20}, order: {total: 10, allowed: true}}], + [{customer: {age: 17}, order: {total: 10}}, {customer: {age: 17}, order: {total: 10, allowed: false}}], + [{customer: {age: 20}, order: {total: 1000}}, {customer: {age: 20}, order: {total: 1000, allowed: false}}], + [{customer: {age: 20}}, "!error: MissingRequiredInputs"], + [{order: {total: 10}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "each root entity is validated independently", + policy: { + models: {customer: {age: "number"}, order: {total: "number"}}, + blocks: [{expression: "order.big", value: "order.total > 100"}], + }, + cases: [ + [{customer: {age: "x"}, order: {total: 200}}, "!error: InputValidationFailed"], + [{customer: {age: 1}, order: {total: 200}}, {customer: {age: 1}, order: {total: 200, big: true}}], + [{order: {total: 200}}, {order: {total: 200, big: true}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Numbers are exact decimals end to end. + +{ + name: "decimal inputs keep their precision", + policy: { + models: {account: {balance: "number", rate: "number"}}, + blocks: [{expression: "account.interest", value: "account.balance * account.rate"}], + }, + cases: [ + [{account: {balance: 1000.10, rate: 0.015}}, {account: {balance: 1000.1, rate: 0.015, interest: 15.0015}}], + [{account: {balance: 0.1, rate: 3}}, {account: {balance: 0.1, rate: 3, interest: 0.3}}], + [{account: {balance: 123456789012345678, rate: 1}}, {account: {balance: 123456789012345678, rate: 1, interest: 123456789012345678}}], + [{account: {balance: -2.5, rate: -2}}, {account: {balance: -2.5, rate: -2, interest: 5}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Computed properties of entities that are not in the input. A block writing `x.y` where `x` is not +// a declared entity creates a new top-level object. + +{ + name: "a computed root object is created when absent", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "result.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20}, result: {adult: true}}], + [{customer: {age: 2}}, {customer: {age: 2}, result: {adult: false}}], + ], +} + +{ + name: "a top-level computed value is written at the root", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20}, adult: true}], + [{customer: {age: 2}, adult: "stale"}, {customer: {age: 2}, adult: false}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Global data models: their properties are top-level input keys (the model name is not part of +// the path). They follow the same required/optional and type rules as entity properties. + +{ + name: "global properties are top-level inputs", + policy: { + globals: {settings: {taxRate: "number", currency: "string?"}}, + models: {order: {net: "number"}}, + blocks: [{expression: "order.gross", value: "order.net * (1 + taxRate)"}], + }, + cases: [ + [{taxRate: 0.2, order: {net: 100}}, {taxRate: 0.2, order: {net: 100, gross: 120}}], + [{taxRate: 0, order: {net: 100}}, {taxRate: 0, order: {net: 100, gross: 100}}], + [{taxRate: 0.2, currency: "EUR", order: {net: 10}}, {taxRate: 0.2, currency: "EUR", order: {net: 10, gross: 12}}], + [{order: {net: 100}}, "!error: MissingRequiredInputs"], + [{taxRate: null, order: {net: 100}}, "!error: MissingRequiredInputs"], + [{taxRate: "0.2", order: {net: 100}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an optional global may be missing", + policy: { + globals: {settings: {limit: "number?"}}, + blocks: [{expression: "effectiveLimit", value: "limit ?? 100"}], + }, + cases: [ + [{}, {effectiveLimit: 100}], + [{limit: null}, {limit: null, effectiveLimit: 100}], + [{limit: 5}, {limit: 5, effectiveLimit: 5}], + [{limit: "5"}, "!error: InputValidationFailed"], + ], +} + +{ + name: "global enum, date and array properties are validated", + policy: { + globals: {env: {region: "string(eu|us)", today: "date", holidays: "date[]?"}}, + blocks: [{expression: "isEu", value: "region == 'eu'"}], + }, + cases: [ + [{region: "eu", today: "2025-03-20"}, {region: "eu", today: date("2025-03-20"), isEu: true}], + [{region: "us", today: "2025-03-20", holidays: ["2025-12-25"]}, {region: "us", today: date("2025-03-20"), holidays: [date("2025-12-25")], isEu: false}], + [{region: "apac", today: "2025-03-20"}, "!error: InputValidationFailed"], + [{region: "eu", today: "tomorrow"}, "!error: InputValidationFailed"], + [{region: "eu", today: "2025-03-20", holidays: "2025-12-25"}, "!error: InputValidationFailed"], + ], +} + +{ + name: "writing a declared global is an InputOverride error", + policy: { + globals: {settings: {taxRate: "number"}}, + blocks: [{expression: "taxRate", value: "0.5"}], + }, + cases: [ + [{taxRate: 0.2}, "!error"], + ], +} diff --git a/core/engine/tests/spec/policy/02-expression-blocks.json5 b/core/engine/tests/spec/policy/02-expression-blocks.json5 new file mode 100644 index 00000000..7dca5661 --- /dev/null +++ b/core/engine/tests/spec/policy/02-expression-blocks.json5 @@ -0,0 +1,675 @@ +// Expression blocks: `{key, value}` writes the value of one expression to one property path. +// +// The key is the computed property. The value is any expression over inputs and other computed +// properties. A block runs once (singleton entities) and its result is written at the key, +// whatever its type, including null. A runtime error in the expression fails the evaluation. +// Each computed property has exactly one writer. + +// --------------------------------------------------------------------------------------------- +// Result types: the written value keeps the type the expression produced. + +{ + name: "a number result", + policy: { + models: {item: {price: "number", qty: "number"}}, + blocks: [{expression: "item.total", value: "item.price * item.qty"}], + }, + cases: [ + [{item: {price: 2.5, qty: 4}}, {item: {price: 2.5, qty: 4, total: 10}}], + [{item: {price: 0, qty: 4}}, {item: {price: 0, qty: 4, total: 0}}], + [{item: {price: -1.25, qty: 3}}, {item: {price: -1.25, qty: 3, total: -3.75}}], + [{item: {price: 0.1, qty: 0.1}}, {item: {price: 0.1, qty: 0.1, total: 0.01}}], + ], +} + +{ + name: "a string result", + policy: { + models: {person: {first: "string", last: "string"}}, + blocks: [{expression: "person.full", value: "person.first + ' ' + person.last"}], + }, + cases: [ + [{person: {first: "Ada", last: "Lovelace"}}, {person: {first: "Ada", last: "Lovelace", full: "Ada Lovelace"}}], + [{person: {first: "", last: ""}}, {person: {first: "", last: "", full: " "}}], + [{person: {first: "Zoë", last: "Ñ"}}, {person: {first: "Zoë", last: "Ñ", full: "Zoë Ñ"}}], + ], +} + +{ + name: "a boolean result", + policy: { + models: {person: {age: "number", member: "boolean"}}, + blocks: [{expression: "person.eligible", value: "person.age >= 21 and person.member"}], + }, + cases: [ + [{person: {age: 21, member: true}}, {person: {age: 21, member: true, eligible: true}}], + [{person: {age: 21, member: false}}, {person: {age: 21, member: false, eligible: false}}], + [{person: {age: 20, member: true}}, {person: {age: 20, member: true, eligible: false}}], + ], +} + +{ + name: "an array result", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [{expression: "cart.doubled", value: "map(cart.prices, # * 2)"}], + }, + cases: [ + [{cart: {prices: [1, 2]}}, {cart: {prices: [1, 2], doubled: [2, 4]}}], + [{cart: {prices: []}}, {cart: {prices: [], doubled: []}}], + [{cart: {prices: [0.5]}}, {cart: {prices: [0.5], doubled: [1]}}], + ], +} + +{ + name: "an object result", + policy: { + models: {person: {first: "string", age: "number"}}, + blocks: [{expression: "person.summary", value: "{name: person.first, adult: person.age >= 18}"}], + }, + cases: [ + [{person: {first: "Ann", age: 30}}, {person: {first: "Ann", age: 30, summary: {name: "Ann", adult: true}}}], + [{person: {first: "Bo", age: 3}}, {person: {first: "Bo", age: 3, summary: {name: "Bo", adult: false}}}], + ], +} + +{ + name: "a literal result does not depend on input", + policy: { + models: {person: {age: "number?"}}, + blocks: [ + {expression: "constants.n", value: "42"}, + {expression: "constants.s", value: "'fixed'"}, + {expression: "constants.b", value: "false"}, + {expression: "constants.list", value: "[1, 2, 3]"}, + ], + }, + cases: [ + [{}, {constants: {n: 42, s: "fixed", b: false, list: [1, 2, 3]}}], + [{person: {age: 1}}, {person: {age: 1}, constants: {n: 42, s: "fixed", b: false, list: [1, 2, 3]}}], + ], +} + +{ + name: "a date result", + policy: { + models: {loan: {start: "date", months: "number"}}, + blocks: [{expression: "loan.endText", value: "d(loan.start).add(loan.months, 'month').format('%Y-%m-%d')"}], + }, + cases: [ + [{loan: {start: "2025-01-31", months: 1}}, {loan: {start: date("2025-01-31"), months: 1, endText: "2025-02-28"}}], + [{loan: {start: "2024-02-29", months: 12}}, {loan: {start: date("2024-02-29"), months: 12, endText: "2025-02-28"}}], + [{loan: {start: "2025-03-20", months: 0}}, {loan: {start: date("2025-03-20"), months: 0, endText: "2025-03-20"}}], + ], +} + +{ + name: "a result of mixed types is a compile error", + policy: { + models: {item: {kind: "string(n|s|b)"}}, + blocks: [{expression: "item.v", value: "item.kind == 'n' ? 1 : item.kind == 's' ? 'one' : true"}], + }, + cases: [ + [{item: {kind: "n"}}, "!error"], + [{item: {kind: "s"}}, "!error"], + ], +} + +{ + name: "a result that is a value or null", + policy: { + models: {item: {kind: "string(n|s|b)"}}, + blocks: [{expression: "item.v", value: "item.kind == 'n' ? 1 : item.kind == 's' ? 2 : null"}], + }, + cases: [ + [{item: {kind: "n"}}, {item: {kind: "n", v: 1}}], + [{item: {kind: "s"}}, {item: {kind: "s", v: 2}}], + [{item: {kind: "b"}}, {item: {kind: "b", v: null}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Null results: a null value is written as null (the key is present in the output). + +{ + name: "a null literal is written as null", + policy: { + models: {item: {price: "number"}}, + blocks: [{expression: "item.nothing", value: "null"}], + }, + cases: [ + [{item: {price: 1}}, {item: {price: 1, nothing: null}}], + ], +} + +{ + name: "a null result from an optional input is written", + policy: { + models: {item: {discount: "number?"}}, + blocks: [{expression: "item.discountCopy", value: "item.discount"}], + }, + cases: [ + [{item: {}}, {item: {discountCopy: null}}], + [{item: {discount: null}}, {item: {discount: null, discountCopy: null}}], + [{item: {discount: 0}}, {item: {discount: 0, discountCopy: 0}}], + ], +} + +{ + name: "a conditional null result", + policy: { + models: {item: {price: "number"}}, + blocks: [{expression: "item.premium", value: "item.price > 100 ? 'yes' : null"}], + }, + cases: [ + [{item: {price: 150}}, {item: {price: 150, premium: "yes"}}], + [{item: {price: 50}}, {item: {price: 50, premium: null}}], + [{item: {price: 100}}, {item: {price: 100, premium: null}}], + ], +} + +{ + name: "arithmetic on an optional input without a fallback is a compile error", + policy: { + models: {item: {discount: "number?"}}, + blocks: [{expression: "item.half", value: "item.discount / 2"}], + }, + cases: [ + [{item: {discount: 10}}, "!error"], + [{item: {discount: null}}, "!error"], + [{item: {}}, "!error"], + ], +} + +{ + name: "a null-coalesced optional input", + policy: { + models: {item: {discount: "number?"}}, + blocks: [{expression: "item.half", value: "(item.discount ?? 0) / 2"}], + }, + cases: [ + [{item: {discount: 10}}, {item: {discount: 10, half: 5}}], + [{item: {discount: null}}, {item: {discount: null, half: 0}}], + [{item: {}}, {item: {half: 0}}], + ], +} + +{ + name: "a read of an undeclared key of an extra input object", + policy: { + models: {item: {price: "number"}}, + blocks: [{expression: "item.copy", value: "item.price"}], + }, + cases: [ + [{item: {price: 1, junk: 2}}, {item: {price: 1, junk: 2, copy: 1}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Runtime errors: an expression that fails at runtime fails the whole evaluation +// (ExpressionFailed); no partial output is returned. + +{ + name: "division by zero gives null, not an error", + policy: { + models: {ratio: {a: "number", b: "number"}}, + blocks: [{expression: "ratio.q", value: "ratio.a / ratio.b"}], + }, + cases: [ + [{ratio: {a: 1, b: 4}}, {ratio: {a: 1, b: 4, q: 0.25}}], + [{ratio: {a: 1, b: 0}}, {ratio: {a: 1, b: 0, q: null}}], + [{ratio: {a: 0, b: 0}}, {ratio: {a: 0, b: 0, q: null}}], + [{ratio: {a: -3, b: 2}}, {ratio: {a: -3, b: 2, q: -1.5}}], + ], +} + +{ + name: "a failing builtin call fails the evaluation", + policy: { + models: {data: {text: "string"}}, + blocks: [{expression: "data.n", value: "number(data.text)"}], + }, + cases: [ + [{data: {text: "12.5"}}, {data: {text: "12.5", n: 12.5}}], + [{data: {text: "abc"}}, "!error"], + [{data: {text: ""}}, "!error"], + [{data: {text: "-0.5"}}, {data: {text: "-0.5", n: -0.5}}], + ], +} + +{ + name: "the runtime error names the failing block", + policy: { + models: {data: {text: "string"}}, + blocks: [{id: "parse", expression: "data.n", value: "number(data.text)"}], + }, + cases: [ + [{data: {text: "abc"}}, "!error: parse"], + [{data: {text: "abc"}}, "!error: ExpressionFailed"], + [{data: {text: "7"}}, {data: {text: "7", n: 7}}], + ], +} + +{ + name: "an error in one block fails the evaluation even if other blocks succeed", + policy: { + models: {data: {text: "string", k: "number"}}, + blocks: [ + {expression: "data.double", value: "data.k * 2"}, + {expression: "data.n", value: "number(data.text)"}, + ], + }, + cases: [ + [{data: {text: "x", k: 1}}, "!error"], + [{data: {text: "1", k: 1}}, {data: {text: "1", k: 1, double: 2, n: 1}}], + ], +} + +{ + name: "an error in a block that feeds another block fails the evaluation", + policy: { + models: {data: {text: "string"}}, + blocks: [ + {expression: "data.n", value: "number(data.text)"}, + {expression: "data.big", value: "data.n > 1"}, + ], + }, + cases: [ + [{data: {text: "x"}}, "!error"], + [{data: {text: "1.5"}}, {data: {text: "1.5", n: 1.5, big: true}}], + [{data: {text: "0.5"}}, {data: {text: "0.5", n: 0.5, big: false}}], + ], +} + +{ + name: "an error in a branch that is not taken does not fail", + policy: { + models: {ratio: {a: "number", b: "number"}}, + blocks: [{expression: "ratio.q", value: "ratio.b == 0 ? number('bad') : ratio.a / ratio.b"}], + }, + cases: [ + [{ratio: {a: 1, b: 0}}, "!error"], + [{ratio: {a: 1, b: 2}}, {ratio: {a: 1, b: 2, q: 0.5}}], + [{ratio: {a: 3, b: 3}}, {ratio: {a: 3, b: 3, q: 1}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Compile errors: a policy with an invalid expression, an undefined read or a type mismatch has +// error diagnostics and is not evaluated. + +{ + name: "a syntax error is a compile error", + policy: { + models: {item: {price: "number"}}, + blocks: [{expression: "item.bad", value: "item.price +"}], + }, + cases: [ + [{item: {price: 1}}, "!error"], + ], +} + +{ + name: "a read of an undeclared entity property is a compile error", + policy: { + models: {item: {price: "number"}}, + blocks: [{expression: "item.copy", value: "item.cost"}], + }, + cases: [ + [{item: {price: 1}}, "!error"], + [{item: {price: 1, cost: 5}}, "!error"], + ], +} + +{ + name: "a read of an undeclared top-level name is a compile error", + policy: { + models: {item: {price: "number"}}, + blocks: [{expression: "item.copy", value: "missingThing"}], + }, + cases: [ + [{item: {price: 1}}, "!error"], + [{item: {price: 1}, missingThing: 3}, "!error"], + ], +} + +{ + name: "a type mismatch is a compile error", + policy: { + models: {item: {price: "number", name: "string"}}, + blocks: [{expression: "item.bad", value: "item.price - item.name"}], + }, + cases: [ + [{item: {price: 1, name: "x"}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Writes to entity properties: the key is `entity.property`; the value lands on the entity +// object from the input. + +{ + name: "two blocks write two properties of one entity", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.highIncome", value: "customer.income > 50000"}, + ], + }, + cases: [ + [{customer: {age: 30, income: 60000}}, {customer: {age: 30, income: 60000, adult: true, highIncome: true}}], + [{customer: {age: 10, income: 0}}, {customer: {age: 10, income: 0, adult: false, highIncome: false}}], + ], +} + +{ + name: "blocks write properties of two different entities", + policy: { + models: {customer: {age: "number"}, order: {total: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "order.large", value: "order.total > 100"}, + ], + }, + cases: [ + [{customer: {age: 30}, order: {total: 200}}, {customer: {age: 30, adult: true}, order: {total: 200, large: true}}], + [{customer: {age: 3}, order: {total: 2}}, {customer: {age: 3, adult: false}, order: {total: 2, large: false}}], + ], +} + +{ + name: "a block on one entity reads another entity", + policy: { + models: {customer: {age: "number"}, order: {total: "number"}}, + blocks: [{expression: "order.needsReview", value: "customer.age < 21 and order.total > 500"}], + }, + cases: [ + [{customer: {age: 19}, order: {total: 600}}, {customer: {age: 19}, order: {total: 600, needsReview: true}}], + [{customer: {age: 30}, order: {total: 600}}, {customer: {age: 30}, order: {total: 600, needsReview: false}}], + [{customer: {age: 19}, order: {total: 100}}, {customer: {age: 19}, order: {total: 100, needsReview: false}}], + ], +} + +{ + name: "a computed property of an entity with no other input", + policy: { + models: {customer: {age: "number"}, flags: {note: "string?"}}, + blocks: [{expression: "flags.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 30}, flags: {}}, {customer: {age: 30}, flags: {adult: true}}], + [{customer: {age: 30}}, {customer: {age: 30}, flags: {adult: true}}], + [{customer: {age: 30}, flags: {note: "n"}}, {customer: {age: 30}, flags: {note: "n", adult: true}}], + ], +} + +{ + name: "a top-level computed property next to entity writes", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "decision", value: "customer.age >= 18 ? 'approve' : 'decline'"}, + {expression: "customer.adult", value: "customer.age >= 18"}, + ], + }, + cases: [ + [{customer: {age: 30}}, {customer: {age: 30, adult: true}, decision: "approve"}], + [{customer: {age: 3}}, {customer: {age: 3, adult: false}, decision: "decline"}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Reading other computed properties: a block that reads a computed property sees the value the +// writing block produced, regardless of block order (see 03-dependencies). + +{ + name: "a block reads a computed property of the same entity", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.label", value: "customer.adult ? 'adult' : 'minor'"}, + ], + }, + cases: [ + [{customer: {age: 18}}, {customer: {age: 18, adult: true, label: "adult"}}], + [{customer: {age: 17}}, {customer: {age: 17, adult: false, label: "minor"}}], + ], +} + +{ + name: "a block reads a computed top-level property", + policy: { + models: {order: {net: "number"}}, + blocks: [ + {expression: "rate", value: "order.net > 1000 ? 0.1 : 0.2"}, + {expression: "order.tax", value: "order.net * rate"}, + ], + }, + cases: [ + [{order: {net: 100}}, {order: {net: 100, tax: 20}, rate: 0.2}], + [{order: {net: 2000}}, {order: {net: 2000, tax: 200}, rate: 0.1}], + ], +} + +{ + name: "a block reads a computed object field", + policy: { + models: {person: {first: "string", age: "number"}}, + blocks: [ + {expression: "person.summary", value: "{name: person.first, adult: person.age >= 18}"}, + {expression: "person.greeting", value: "person.summary.adult ? 'Hello ' + person.summary.name : 'Hi'"}, + ], + }, + cases: [ + [{person: {first: "Ann", age: 30}}, {person: {first: "Ann", age: 30, summary: {name: "Ann", adult: true}, greeting: "Hello Ann"}}], + [{person: {first: "Bo", age: 3}}, {person: {first: "Bo", age: 3, summary: {name: "Bo", adult: false}, greeting: "Hi"}}], + ], +} + +{ + name: "a block reads a computed array", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [ + {expression: "cart.expensive", value: "filter(cart.prices, # > 10)"}, + {expression: "cart.expensiveCount", value: "len(cart.expensive)"}, + ], + }, + cases: [ + [{cart: {prices: [5, 15, 25]}}, {cart: {prices: [5, 15, 25], expensive: [15, 25], expensiveCount: 2}}], + [{cart: {prices: []}}, {cart: {prices: [], expensive: [], expensiveCount: 0}}], + ], +} + +{ + name: "a computed null read by another block", + policy: { + models: {item: {price: "number"}}, + blocks: [ + {expression: "item.badge", value: "item.price > 100 ? 'premium' : null"}, + {expression: "item.label", value: "item.badge ?? 'standard'"}, + ], + }, + cases: [ + [{item: {price: 150}}, {item: {price: 150, badge: "premium", label: "premium"}}], + [{item: {price: 50}}, {item: {price: 50, badge: null, label: "standard"}}], + ], +} + +{ + name: "a computed value hides a same-named undeclared input key", + policy: { + models: {item: {price: "number"}}, + blocks: [ + {expression: "item.badge", value: "item.price > 100 ? 'premium' : 'basic'"}, + {expression: "item.label", value: "'[' + item.badge + ']'"}, + ], + }, + cases: [ + [{item: {price: 150, badge: "input"}}, {item: {price: 150, badge: "premium", label: "[premium]"}}], + [{item: {price: 50, badge: null}}, {item: {price: 50, badge: "basic", label: "[basic]"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Duplicate writers: two blocks writing the same key is the DuplicateWriter compile error. + +{ + name: "two expression blocks writing the same key", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.tier", value: "'a'"}, + {expression: "customer.tier", value: "'b'"}, + ], + }, + cases: [ + [{customer: {age: 1}}, "!error"], + ], +} + +{ + name: "two expression blocks writing the same top-level key", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "score", value: "customer.age"}, + {expression: "score", value: "customer.age * 2"}, + ], + }, + cases: [ + [{customer: {age: 5}}, "!error"], + ], +} + +{ + name: "a duplicate writer with a reader in between", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.tier", value: "customer.age > 10 ? 'old' : 'young'"}, + {expression: "customer.label", value: "'tier ' + customer.tier"}, + {expression: "customer.tier", value: "'other'"}, + ], + }, + cases: [ + [{customer: {age: 50}}, "!error"], + ], +} + +{ + name: "an expression and a match writing the same key", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.tier", value: "'a'"}, + {match: "customer.tier", arms: [["customer.age > 10", "'b'"], ["", "'c'"]]}, + ], + }, + cases: [ + [{customer: {age: 50}}, "!error"], + ], +} + +{ + name: "same leaf name under different entities is not a duplicate", + policy: { + models: {customer: {age: "number"}, order: {total: "number"}}, + blocks: [ + {expression: "customer.flag", value: "customer.age > 10"}, + {expression: "order.flag", value: "order.total > 10"}, + {expression: "flag", value: "customer.flag and order.flag"}, + ], + }, + cases: [ + [{customer: {age: 50}, order: {total: 50}}, {customer: {age: 50, flag: true}, order: {total: 50, flag: true}, flag: true}], + [{customer: {age: 5}, order: {total: 50}}, {customer: {age: 5, flag: false}, order: {total: 50, flag: true}, flag: false}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Self reference: a block reading its own key is a compile error (SelfReferencingWrite), not a +// way to read the input value of that key. + +{ + name: "a block reading its own key", + policy: { + models: {counter: {start: "number"}}, + blocks: [{expression: "counter.value", value: "(counter.value ?? counter.start) + 1"}], + }, + cases: [ + [{counter: {start: 1}}, "!error"], + [{counter: {start: 1, value: 10}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Expressions with closures, string interpolation and builtins are ordinary values. + +{ + name: "closures over an input array", + policy: { + models: {order: {lines: "number[]"}}, + blocks: [ + {expression: "order.anyLarge", value: "some(order.lines, # > 100)"}, + {expression: "order.allPositive", value: "all(order.lines, # > 0)"}, + {expression: "order.count", value: "count(order.lines, # > 10)"}, + ], + }, + cases: [ + [{order: {lines: [5, 50, 500]}}, {order: {lines: [5, 50, 500], anyLarge: true, allPositive: true, count: 2}}], + [{order: {lines: []}}, {order: {lines: [], anyLarge: false, allPositive: true, count: 0}}], + [{order: {lines: [-1]}}, {order: {lines: [-1], anyLarge: false, allPositive: false, count: 0}}], + ], +} + +{ + name: "a template string", + policy: { + models: {person: {first: "string", age: "number"}}, + blocks: [{expression: "person.text", value: "`${person.first} is ${person.age}`"}], + }, + cases: [ + [{person: {first: "Ann", age: 30}}, {person: {first: "Ann", age: 30, text: "Ann is 30"}}], + [{person: {first: "", age: 0.5}}, {person: {first: "", age: 0.5, text: " is 0.5"}}], + ], +} + +{ + name: "math builtins", + policy: { + models: {n: {x: "number"}}, + blocks: [ + {expression: "n.r", value: "round(n.x)"}, + {expression: "n.f", value: "floor(n.x)"}, + {expression: "n.a", value: "abs(n.x)"}, + ], + }, + cases: [ + [{n: {x: 2.5}}, {n: {x: 2.5, r: 3, f: 2, a: 2.5}}], + [{n: {x: -2.5}}, {n: {x: -2.5, r: -3, f: -3, a: 2.5}}], + [{n: {x: 0}}, {n: {x: 0, r: 0, f: 0, a: 0}}], + ], +} + +{ + name: "many independent blocks", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "s.a", value: "s.v + 1"}, + {expression: "s.b", value: "s.v + 2"}, + {expression: "s.c", value: "s.v + 3"}, + {expression: "s.d", value: "s.v + 4"}, + {expression: "s.e", value: "s.v + 5"}, + {expression: "s.f", value: "s.v + 6"}, + ], + }, + cases: [ + [{s: {v: 0}}, {s: {v: 0, a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}}], + [{s: {v: -6}}, {s: {v: -6, a: -5, b: -4, c: -3, d: -2, e: -1, f: 0}}], + [{s: {v: 0.5}}, {s: {v: 0.5, a: 1.5, b: 2.5, c: 3.5, d: 4.5, e: 5.5, f: 6.5}}], + ], +} diff --git a/core/engine/tests/spec/policy/03-dependencies.json5 b/core/engine/tests/spec/policy/03-dependencies.json5 new file mode 100644 index 00000000..11f3e997 --- /dev/null +++ b/core/engine/tests/spec/policy/03-dependencies.json5 @@ -0,0 +1,629 @@ +// Dependencies between blocks. +// +// Blocks are not executed in document order. A block runs after every block that writes a +// property it reads, so the document order of blocks never changes the result. Chains of computed +// properties resolve transitively, diamonds compute the shared property once, and a cycle between +// computed properties is the CyclicDependency compile error. + +// --------------------------------------------------------------------------------------------- +// Order independence: the same two blocks, in both document orders, give the same output. + +{ + name: "a reader listed before its writer", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.label", value: "customer.adult ? 'adult' : 'minor'"}, + {expression: "customer.adult", value: "customer.age >= 18"}, + ], + }, + cases: [ + [{customer: {age: 30}}, {customer: {age: 30, adult: true, label: "adult"}}], + [{customer: {age: 3}}, {customer: {age: 3, adult: false, label: "minor"}}], + [{customer: {age: 18}}, {customer: {age: 18, adult: true, label: "adult"}}], + ], +} + +{ + name: "a reader listed after its writer", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.label", value: "customer.adult ? 'adult' : 'minor'"}, + ], + }, + cases: [ + [{customer: {age: 30}}, {customer: {age: 30, adult: true, label: "adult"}}], + [{customer: {age: 3}}, {customer: {age: 3, adult: false, label: "minor"}}], + [{customer: {age: 18}}, {customer: {age: 18, adult: true, label: "adult"}}], + ], +} + +{ + name: "a reversed chain of three", + policy: { + models: {order: {net: "number"}}, + blocks: [ + {expression: "order.total", value: "order.net + order.tax"}, + {expression: "order.tax", value: "order.net * order.rate"}, + {expression: "order.rate", value: "order.net > 100 ? 0.1 : 0.2"}, + ], + }, + cases: [ + [{order: {net: 50}}, {order: {net: 50, rate: 0.2, tax: 10, total: 60}}], + [{order: {net: 200}}, {order: {net: 200, rate: 0.1, tax: 20, total: 220}}], + [{order: {net: 100}}, {order: {net: 100, rate: 0.2, tax: 20, total: 120}}], + [{order: {net: 0}}, {order: {net: 0, rate: 0.2, tax: 0, total: 0}}], + ], +} + +{ + name: "a shuffled chain of three", + policy: { + models: {order: {net: "number"}}, + blocks: [ + {expression: "order.tax", value: "order.net * order.rate"}, + {expression: "order.total", value: "order.net + order.tax"}, + {expression: "order.rate", value: "order.net > 100 ? 0.1 : 0.2"}, + ], + }, + cases: [ + [{order: {net: 50}}, {order: {net: 50, rate: 0.2, tax: 10, total: 60}}], + [{order: {net: 200}}, {order: {net: 200, rate: 0.1, tax: 20, total: 220}}], + [{order: {net: 100.5}}, {order: {net: 100.5, rate: 0.1, tax: 10.05, total: 110.55}}], + ], +} + +{ + name: "a long chain listed in reverse", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "s.k", value: "s.j + 1"}, + {expression: "s.j", value: "s.i + 1"}, + {expression: "s.i", value: "s.h + 1"}, + {expression: "s.h", value: "s.g + 1"}, + {expression: "s.g", value: "s.f + 1"}, + {expression: "s.f", value: "s.e + 1"}, + {expression: "s.e", value: "s.d + 1"}, + {expression: "s.d", value: "s.c + 1"}, + {expression: "s.c", value: "s.b + 1"}, + {expression: "s.b", value: "s.a + 1"}, + {expression: "s.a", value: "s.v + 1"}, + ], + }, + cases: [ + [{s: {v: 0}}, {s: {v: 0, a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11}}], + [{s: {v: -11}}, {s: {v: -11, a: -10, b: -9, c: -8, d: -7, e: -6, f: -5, g: -4, h: -3, i: -2, j: -1, k: 0}}], + [{s: {v: 0.5}}, {s: {v: 0.5, a: 1.5, b: 2.5, c: 3.5, d: 4.5, e: 5.5, f: 6.5, g: 7.5, h: 8.5, i: 9.5, j: 10.5, k: 11.5}}], + ], +} + +{ + name: "a chain of string builders in reverse", + policy: { + models: {p: {name: "string"}}, + blocks: [ + {expression: "p.c", value: "p.b + '!'"}, + {expression: "p.b", value: "p.a + ','"}, + {expression: "p.a", value: "upper(p.name)"}, + ], + }, + cases: [ + [{p: {name: "ann"}}, {p: {name: "ann", a: "ANN", b: "ANN,", c: "ANN,!"}}], + [{p: {name: ""}}, {p: {name: "", a: "", b: ",", c: ",!"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Chains across entities and through top-level computed properties. + +{ + name: "a chain across two entities", + policy: { + models: {customer: {age: "number"}, order: {total: "number"}}, + blocks: [ + {expression: "order.discount", value: "customer.senior ? order.total * 0.1 : 0"}, + {expression: "customer.senior", value: "customer.age >= 65"}, + {expression: "order.due", value: "order.total - order.discount"}, + ], + }, + cases: [ + [{customer: {age: 70}, order: {total: 100}}, {customer: {age: 70, senior: true}, order: {total: 100, discount: 10, due: 90}}], + [{customer: {age: 30}, order: {total: 100}}, {customer: {age: 30, senior: false}, order: {total: 100, discount: 0, due: 100}}], + [{customer: {age: 65}, order: {total: 0}}, {customer: {age: 65, senior: true}, order: {total: 0, discount: 0, due: 0}}], + ], +} + +{ + name: "a chain through a top-level computed property", + policy: { + models: {order: {net: "number"}}, + blocks: [ + {expression: "order.tax", value: "order.net * taxRate"}, + {expression: "taxRate", value: "order.net > 1000 ? 0.05 : 0.2"}, + ], + }, + cases: [ + [{order: {net: 100}}, {order: {net: 100, tax: 20}, taxRate: 0.2}], + [{order: {net: 2000}}, {order: {net: 2000, tax: 100}, taxRate: 0.05}], + ], +} + +{ + name: "a chain through a computed object read field by field", + policy: { + models: {p: {a: "number", b: "number"}}, + blocks: [ + {expression: "p.result", value: "p.pair.sum * p.pair.product"}, + {expression: "p.pair", value: "{sum: p.a + p.b, product: p.a * p.b}"}, + ], + }, + cases: [ + [{p: {a: 2, b: 3}}, {p: {a: 2, b: 3, pair: {sum: 5, product: 6}, result: 30}}], + [{p: {a: 0, b: 3}}, {p: {a: 0, b: 3, pair: {sum: 3, product: 0}, result: 0}}], + ], +} + +{ + name: "a chain through a computed array", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [ + {expression: "cart.total", value: "sum(cart.discounted)"}, + {expression: "cart.discounted", value: "map(cart.prices, # * 0.5)"}, + ], + }, + cases: [ + [{cart: {prices: [10, 20]}}, {cart: {prices: [10, 20], discounted: [5, 10], total: 15}}], + [{cart: {prices: []}}, {cart: {prices: [], discounted: [], total: 0}}], + ], +} + +{ + name: "a chain through a match block", + policy: { + models: {customer: {score: "number"}}, + blocks: [ + {expression: "customer.limit", value: "customer.tier == 'gold' ? 10000 : customer.tier == 'silver' ? 5000 : 1000"}, + {match: "customer.tier", arms: [["customer.score >= 800", "'gold'"], ["customer.score >= 600", "'silver'"], ["", "'bronze'"]]}, + ], + }, + cases: [ + [{customer: {score: 850}}, {customer: {score: 850, tier: "gold", limit: 10000}}], + [{customer: {score: 700}}, {customer: {score: 700, tier: "silver", limit: 5000}}], + [{customer: {score: 100}}, {customer: {score: 100, tier: "bronze", limit: 1000}}], + [{customer: {score: 600}}, {customer: {score: 600, tier: "silver", limit: 5000}}], + ], +} + +{ + name: "a match whose conditions read a computed property", + policy: { + models: {customer: {income: "number", debt: "number"}}, + blocks: [ + {match: "customer.risk", arms: [["customer.ratio > 0.5", "'high'"], ["customer.ratio > 0.2", "'medium'"], ["", "'low'"]]}, + {expression: "customer.ratio", value: "customer.debt / customer.income"}, + ], + }, + cases: [ + [{customer: {income: 100, debt: 60}}, {customer: {income: 100, debt: 60, ratio: 0.6, risk: "high"}}], + [{customer: {income: 100, debt: 30}}, {customer: {income: 100, debt: 30, ratio: 0.3, risk: "medium"}}], + [{customer: {income: 100, debt: 0}}, {customer: {income: 100, debt: 0, ratio: 0, risk: "low"}}], + ], +} + +{ + name: "a chain through a decision table", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.message", value: "'segment ' + customer.segment"}, + {table: "segments", inputs: ["customer.band"], outputs: ["customer.segment"], rules: [ + ["'young'", "'A'"], + ["", "'B'"], + ]}, + {expression: "customer.band", value: "customer.age < 30 ? 'young' : 'old'"}, + ], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, band: "young", segment: "A", message: "segment A"}}], + [{customer: {age: 40}}, {customer: {age: 40, band: "old", segment: "B", message: "segment B"}}], + ], +} + +{ + name: "an assertion reads a computed property", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {assertion: "customer.eligible", conditions: ["customer.adult", "customer.income > 1000"]}, + {expression: "customer.adult", value: "customer.age >= 18"}, + ], + }, + cases: [ + [{customer: {age: 30, income: 2000}}, {customer: {age: 30, income: 2000, adult: true, eligible: true}}], + [{customer: {age: 10, income: 2000}}, {customer: {age: 10, income: 2000, adult: false, eligible: false}}], + [{customer: {age: 30, income: 10}}, {customer: {age: 30, income: 10, adult: true, eligible: false}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Diamonds: two computed properties read one shared property; a fourth reads both. + +{ + name: "a diamond", + policy: { + models: {n: {x: "number"}}, + blocks: [ + {expression: "n.bottom", value: "n.left + n.right"}, + {expression: "n.left", value: "n.top * 2"}, + {expression: "n.right", value: "n.top * 3"}, + {expression: "n.top", value: "n.x + 1"}, + ], + }, + cases: [ + [{n: {x: 0}}, {n: {x: 0, top: 1, left: 2, right: 3, bottom: 5}}], + [{n: {x: 1}}, {n: {x: 1, top: 2, left: 4, right: 6, bottom: 10}}], + [{n: {x: -1}}, {n: {x: -1, top: 0, left: 0, right: 0, bottom: 0}}], + ], +} + +{ + name: "a diamond with the shared node listed first", + policy: { + models: {n: {x: "number"}}, + blocks: [ + {expression: "n.top", value: "n.x + 1"}, + {expression: "n.bottom", value: "n.left + n.right"}, + {expression: "n.right", value: "n.top * 3"}, + {expression: "n.left", value: "n.top * 2"}, + ], + }, + cases: [ + [{n: {x: 0}}, {n: {x: 0, top: 1, left: 2, right: 3, bottom: 5}}], + [{n: {x: 9}}, {n: {x: 9, top: 10, left: 20, right: 30, bottom: 50}}], + ], +} + +{ + name: "a diamond whose shared node fails fails once", + policy: { + models: {n: {text: "string"}}, + blocks: [ + {expression: "n.bottom", value: "n.left + n.right"}, + {expression: "n.left", value: "n.top * 2"}, + {expression: "n.right", value: "n.top * 3"}, + {expression: "n.top", value: "number(n.text)"}, + ], + }, + cases: [ + [{n: {text: "1"}}, {n: {text: "1", top: 1, left: 2, right: 3, bottom: 5}}], + [{n: {text: "x"}}, "!error"], + ], +} + +{ + name: "a wide fan-in reads many computed properties", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "s.total", value: "s.a + s.b + s.c + s.d"}, + {expression: "s.a", value: "s.v"}, + {expression: "s.b", value: "s.v * 10"}, + {expression: "s.c", value: "s.v * 100"}, + {expression: "s.d", value: "s.v * 1000"}, + ], + }, + cases: [ + [{s: {v: 1}}, {s: {v: 1, a: 1, b: 10, c: 100, d: 1000, total: 1111}}], + [{s: {v: 0}}, {s: {v: 0, a: 0, b: 0, c: 0, d: 0, total: 0}}], + [{s: {v: 0.1}}, {s: {v: 0.1, a: 0.1, b: 1, c: 10, d: 100, total: 111.1}}], + ], +} + +{ + name: "a wide fan-out of one computed property", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "s.a", value: "s.base + 1"}, + {expression: "s.b", value: "s.base + 2"}, + {expression: "s.c", value: "s.base + 3"}, + {expression: "s.base", value: "s.v * 2"}, + ], + }, + cases: [ + [{s: {v: 1}}, {s: {v: 1, base: 2, a: 3, b: 4, c: 5}}], + [{s: {v: -1}}, {s: {v: -1, base: -2, a: -1, b: 0, c: 1}}], + ], +} + +{ + name: "a double diamond", + policy: { + models: {n: {x: "number"}}, + blocks: [ + {expression: "n.out", value: "n.l2 + n.r2"}, + {expression: "n.l2", value: "n.mid + 1"}, + {expression: "n.r2", value: "n.mid + 2"}, + {expression: "n.mid", value: "n.l1 + n.r1"}, + {expression: "n.l1", value: "n.x + 1"}, + {expression: "n.r1", value: "n.x + 2"}, + ], + }, + cases: [ + [{n: {x: 0}}, {n: {x: 0, l1: 1, r1: 2, mid: 3, l2: 4, r2: 5, out: 9}}], + [{n: {x: 10}}, {n: {x: 10, l1: 11, r1: 12, mid: 23, l2: 24, r2: 25, out: 49}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Independent blocks: blocks with no dependency between them all run and their order does not +// matter. + +{ + name: "independent blocks in any order", + policy: { + models: {p: {a: "number", b: "number"}}, + blocks: [ + {expression: "p.y", value: "p.b * 2"}, + {expression: "p.x", value: "p.a * 2"}, + ], + }, + cases: [ + [{p: {a: 1, b: 2}}, {p: {a: 1, b: 2, x: 2, y: 4}}], + [{p: {a: 0, b: 0}}, {p: {a: 0, b: 0, x: 0, y: 0}}], + ], +} + +{ + name: "two separate chains interleaved", + policy: { + models: {p: {a: "number", b: "number"}}, + blocks: [ + {expression: "p.a3", value: "p.a2 + 1"}, + {expression: "p.b3", value: "p.b2 + 1"}, + {expression: "p.a2", value: "p.a1 + 1"}, + {expression: "p.b2", value: "p.b1 + 1"}, + {expression: "p.a1", value: "p.a + 1"}, + {expression: "p.b1", value: "p.b + 1"}, + ], + }, + cases: [ + [{p: {a: 0, b: 100}}, {p: {a: 0, b: 100, a1: 1, a2: 2, a3: 3, b1: 101, b2: 102, b3: 103}}], + [{p: {a: -3, b: -3}}, {p: {a: -3, b: -3, a1: -2, a2: -1, a3: 0, b1: -2, b2: -1, b3: 0}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Required inputs are those reachable from the computed properties: an input read only by a +// block in a chain is still required. + +{ + name: "an input read deep in a chain is required", + policy: { + models: {order: {net: "number", region: "string"}}, + blocks: [ + {expression: "order.total", value: "order.net + order.tax"}, + {expression: "order.tax", value: "order.region == 'eu' ? order.net * 0.2 : 0"}, + ], + }, + cases: [ + [{order: {net: 100, region: "eu"}}, {order: {net: 100, region: "eu", tax: 20, total: 120}}], + [{order: {net: 100, region: "us"}}, {order: {net: 100, region: "us", tax: 0, total: 100}}], + [{order: {net: 100}}, "!error: order.region"], + [{order: {region: "eu"}}, "!error: order.net"], + ], +} + +{ + name: "a computed property is never required from the input", + policy: { + models: {order: {net: "number"}}, + blocks: [ + {expression: "order.total", value: "order.net + order.tax"}, + {expression: "order.tax", value: "order.net * 0.2"}, + ], + }, + cases: [ + [{order: {net: 10}}, {order: {net: 10, tax: 2, total: 12}}], + [{order: {net: 10, tax: 999}}, {order: {net: 10, tax: 2, total: 12}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Goals: a request with goals computes the goal properties and what they depend on, and nothing +// else. + +{ + name: "a goal computes only its dependency chain", + policy: { + models: {order: {net: "number"}}, + blocks: [ + {expression: "order.total", value: "order.net + order.tax"}, + {expression: "order.tax", value: "order.net * 0.2"}, + {expression: "order.label", value: "'order of ' + string(order.net)"}, + ], + }, + cases: [ + {input: {order: {net: 10}}, goals: ["order.total"], output: {order: {net: 10, tax: 2, total: 12}}}, + {input: {order: {net: 10}}, goals: ["order.tax"], output: {order: {net: 10, tax: 2}}}, + {input: {order: {net: 10}}, goals: ["order.label"], output: {order: {net: 10, label: "order of 10"}}}, + {input: {order: {net: 10}}, output: {order: {net: 10, tax: 2, total: 12, label: "order of 10"}}}, + ], +} + +{ + name: "a goal does not require inputs outside its chain", + policy: { + models: {order: {net: "number", code: "string"}}, + blocks: [ + {expression: "order.tax", value: "order.net * 0.2"}, + {expression: "order.tag", value: "upper(order.code)"}, + ], + }, + cases: [ + {input: {order: {net: 10}}, goals: ["order.tax"], output: {order: {net: 10, tax: 2}}}, + {input: {order: {code: "x"}}, goals: ["order.tag"], output: {order: {code: "x", tag: "X"}}}, + {input: {order: {code: "x"}}, goals: ["order.tax"], output: "!error: MissingRequiredInputs"}, + {input: {order: {net: 10}}, output: "!error: MissingRequiredInputs"}, + ], +} + +{ + name: "a goal skips a failing block outside its chain", + policy: { + models: {data: {text: "string", n: "number"}}, + blocks: [ + {expression: "data.parsed", value: "number(data.text)"}, + {expression: "data.double", value: "data.n * 2"}, + ], + }, + cases: [ + {input: {data: {text: "x", n: 2}}, goals: ["data.double"], output: {data: {text: "x", n: 2, double: 4}}}, + {input: {data: {text: "x", n: 2}}, goals: ["data.parsed"], output: "!error"}, + {input: {data: {text: "x", n: 2}}, output: "!error"}, + ], +} + +{ + name: "an unknown goal is an error", + policy: { + models: {order: {net: "number"}}, + blocks: [{expression: "order.tax", value: "order.net * 0.2"}], + }, + cases: [ + {input: {order: {net: 10}}, goals: ["order.nope"], output: "!error: GoalNotFound"}, + {input: {order: {net: 10}}, goals: ["order.net"], output: {order: {net: 10}}, note: "question: a declared input read by a block is accepted as a goal and evaluates nothing; GoalNotFound only fires for paths absent from the dependency graph"}, + {input: {order: {net: 10}}, goals: ["order"], output: "!error: GoalNotFound"}, + ], +} + +{ + name: "two goals share a diamond", + policy: { + models: {n: {x: "number"}}, + blocks: [ + {expression: "n.left", value: "n.top * 2"}, + {expression: "n.right", value: "n.top * 3"}, + {expression: "n.top", value: "n.x + 1"}, + {expression: "n.other", value: "n.x - 1"}, + ], + }, + cases: [ + {input: {n: {x: 1}}, goals: ["n.left", "n.right"], output: {n: {x: 1, top: 2, left: 4, right: 6}}}, + {input: {n: {x: 1}}, goals: ["n.left"], output: {n: {x: 1, top: 2, left: 4}}}, + {input: {n: {x: 1}}, goals: ["n.top"], output: {n: {x: 1, top: 2}}}, + ], +} + +// --------------------------------------------------------------------------------------------- +// Cycles: two or more computed properties reading each other form a cycle, a compile error. + +{ + name: "a two-property cycle", + policy: { + models: {p: {x: "number"}}, + blocks: [ + {expression: "p.a", value: "p.b + p.x"}, + {expression: "p.b", value: "p.a + 1"}, + ], + }, + cases: [ + {input: {p: {x: 1}}, goals: ["p.a"], output: "!error", note: "question: errors only incidentally: the re-entrant demand of p.a reads null and `null + 1` fails with ExpressionFailed, not a cycle error"}, + {input: {p: {x: 1}}, goals: ["p.b"], output: "!error", note: "question: errors only incidentally (ExpressionFailed on null + number), not a cycle error"}, + [{p: {x: 1}}, "!error"], + [{p: {x: 0}}, "!error"], + ], +} + +{ + name: "a three-property cycle", + policy: { + models: {p: {x: "number"}}, + blocks: [ + {expression: "p.a", value: "p.c + 1"}, + {expression: "p.b", value: "p.a + 1"}, + {expression: "p.c", value: "p.b + p.x"}, + ], + }, + cases: [ + [{p: {x: 1}}, "!error"], + ], +} + +{ + name: "a cycle hidden behind a conditional", + policy: { + models: {p: {x: "number"}}, + blocks: [ + {expression: "p.a", value: "p.x > 0 ? 1 : p.b"}, + {expression: "p.b", value: "p.a + 1"}, + ], + }, + cases: [ + {input: {p: {x: 1}}, goals: ["p.b"], output: "!error"}, + {input: {p: {x: 1}}, goals: ["p.a"], output: "!error", note: "question: errors only incidentally: p.a demands p.b, whose re-entrant read of p.a is null and `null + 1` fails with ExpressionFailed"}, + [{p: {x: 1}}, "!error"], + [{p: {x: -1}}, "!error"], + ], +} + +{ + name: "a cycle with an unrelated property alongside", + policy: { + models: {p: {x: "number"}}, + blocks: [ + {expression: "p.ok", value: "p.x * 2"}, + {expression: "p.a", value: "p.b + 1"}, + {expression: "p.b", value: "p.a + 1"}, + ], + }, + cases: [ + [{p: {x: 1}}, "!error"], + ], +} + +{ + name: "a cycle through a match block", + policy: { + models: {p: {x: "number"}}, + blocks: [ + {match: "p.a", arms: [["p.b > 1", "1"], ["", "2"]]}, + {expression: "p.b", value: "p.a + p.x"}, + ], + }, + cases: [ + [{p: {x: 1}}, "!error"], + ], +} + +{ + name: "a cycle through a top-level property", + policy: { + models: {p: {x: "number"}}, + blocks: [ + {expression: "total", value: "p.part + 1"}, + {expression: "p.part", value: "total - p.x"}, + ], + }, + cases: [ + [{p: {x: 1}}, "!error"], + ], +} + +{ + name: "a cycle through a computed object field", + policy: { + models: {p: {x: "number"}}, + blocks: [ + {expression: "p.obj", value: "{v: p.other + 1}"}, + {expression: "p.other", value: "p.obj.v * 2"}, + ], + }, + cases: [ + [{p: {x: 1}}, "!error"], + ], +} diff --git a/core/engine/tests/spec/policy/04-nested-paths.json5 b/core/engine/tests/spec/policy/04-nested-paths.json5 new file mode 100644 index 00000000..2c9d682f --- /dev/null +++ b/core/engine/tests/spec/policy/04-nested-paths.json5 @@ -0,0 +1,597 @@ +// Nested computed write paths. +// +// A block key may be a dotted path several levels deep (`totals.byTier.gold = v`). The missing +// intermediate objects (the spine) are created, and several blocks writing disjoint leaves of the +// same object assemble it together. A block reading the whole object runs after every block that +// writes into it. Writing an object whole and also writing into it is PartialObjectWrite; writing +// the same leaf twice is DuplicateWriter. + +// --------------------------------------------------------------------------------------------- +// Single nested writes create the spine. + +{ + name: "a two-level top-level path creates its parent", + policy: { + models: {loan: {amount: "number"}}, + blocks: [{expression: "totals.due", value: "loan.amount * 1.1"}], + }, + cases: [ + [{loan: {amount: 100}}, {loan: {amount: 100}, totals: {due: 110}}], + [{loan: {amount: 0}}, {loan: {amount: 0}, totals: {due: 0}}], + [{loan: {amount: 0.5}}, {loan: {amount: 0.5}, totals: {due: 0.55}}], + ], +} + +{ + name: "a four-level top-level path creates every level", + policy: { + models: {loan: {amount: "number"}}, + blocks: [{expression: "totals.byTier.gold.due", value: "loan.amount"}], + }, + cases: [ + [{loan: {amount: 100}}, {loan: {amount: 100}, totals: {byTier: {gold: {due: 100}}}}], + [{loan: {amount: -1}}, {loan: {amount: -1}, totals: {byTier: {gold: {due: -1}}}}], + ], +} + +{ + name: "a deep path under an entity creates the spine on the entity", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.profile.risk.level", value: "customer.age < 25 ? 'high' : 'normal'"}], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, profile: {risk: {level: "high"}}}}], + [{customer: {age: 40}}, {customer: {age: 40, profile: {risk: {level: "normal"}}}}], + ], +} + +{ + name: "a six-level path", + policy: { + models: {s: {v: "number"}}, + blocks: [{expression: "a.b.c.d.e.f", value: "s.v"}], + }, + cases: [ + [{s: {v: 1}}, {s: {v: 1}, a: {b: {c: {d: {e: {f: 1}}}}}}], + [{s: {v: 0}}, {s: {v: 0}, a: {b: {c: {d: {e: {f: 0}}}}}}], + ], +} + +{ + name: "a nested write of null still creates the spine", + policy: { + models: {s: {v: "number?"}}, + blocks: [{expression: "out.inner.value", value: "s.v"}], + }, + cases: [ + [{s: {v: 1}}, {s: {v: 1}, out: {inner: {value: 1}}}], + [{s: {}}, {s: {}, out: {inner: {value: null}}}], + [{s: {v: null}}, {s: {v: null}, out: {inner: {value: null}}}], + ], +} + +{ + name: "a nested write of an object value", + policy: { + models: {s: {v: "number"}}, + blocks: [{expression: "out.inner", value: "{x: s.v, y: s.v * 2}"}], + }, + cases: [ + [{s: {v: 1}}, {s: {v: 1}, out: {inner: {x: 1, y: 2}}}], + [{s: {v: 0}}, {s: {v: 0}, out: {inner: {x: 0, y: 0}}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Several blocks assemble one object from disjoint leaves. + +{ + name: "two blocks write sibling leaves", + policy: { + models: {loan: {amount: "number", fee: "number"}}, + blocks: [ + {expression: "totals.principal", value: "loan.amount"}, + {expression: "totals.fees", value: "loan.fee"}, + ], + }, + cases: [ + [{loan: {amount: 100, fee: 5}}, {loan: {amount: 100, fee: 5}, totals: {principal: 100, fees: 5}}], + [{loan: {amount: 0, fee: 0}}, {loan: {amount: 0, fee: 0}, totals: {principal: 0, fees: 0}}], + ], +} + +{ + name: "blocks write leaves at different depths of one object", + policy: { + models: {loan: {amount: "number", rate: "number"}}, + blocks: [ + {expression: "totals.byTier.gold.due", value: "loan.amount * 2"}, + {expression: "totals.byTier.silver.due", value: "loan.amount"}, + {expression: "totals.grandTotal", value: "loan.amount * 3"}, + {expression: "totals.meta.rate", value: "loan.rate"}, + ], + }, + cases: [ + [{loan: {amount: 10, rate: 0.1}}, {loan: {amount: 10, rate: 0.1}, totals: {byTier: {gold: {due: 20}, silver: {due: 10}}, grandTotal: 30, meta: {rate: 0.1}}}], + [{loan: {amount: 1, rate: 0}}, {loan: {amount: 1, rate: 0}, totals: {byTier: {gold: {due: 2}, silver: {due: 1}}, grandTotal: 3, meta: {rate: 0}}}], + ], +} + +{ + name: "sibling leaves under an entity", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.flags.adult", value: "customer.age >= 18"}, + {expression: "customer.flags.rich", value: "customer.income > 100000"}, + {expression: "customer.flags.both", value: "customer.flags.adult and customer.flags.rich"}, + ], + }, + cases: [ + [{customer: {age: 30, income: 200000}}, {customer: {age: 30, income: 200000, flags: {adult: true, rich: true, both: true}}}], + [{customer: {age: 10, income: 200000}}, {customer: {age: 10, income: 200000, flags: {adult: false, rich: true, both: false}}}], + [{customer: {age: 30, income: 0}}, {customer: {age: 30, income: 0, flags: {adult: true, rich: false, both: false}}}], + ], +} + +{ + name: "leaves from expression, match and table blocks assemble one object", + policy: { + models: {customer: {age: "number", score: "number"}}, + blocks: [ + {expression: "report.age", value: "customer.age"}, + {match: "report.band", arms: [["customer.score >= 700", "'good'"], ["", "'poor'"]]}, + {table: "segments", inputs: ["customer.age"], outputs: ["report.segment"], rules: [ + ["< 30", "'young'"], + ["", "'mature'"], + ]}, + ], + }, + cases: [ + [{customer: {age: 20, score: 800}}, {customer: {age: 20, score: 800}, report: {age: 20, band: "good", segment: "young"}}], + [{customer: {age: 50, score: 100}}, {customer: {age: 50, score: 100}, report: {age: 50, band: "poor", segment: "mature"}}], + ], +} + +{ + name: "a table writes several nested outputs", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {table: "pricing", inputs: ["customer.age"], outputs: ["quote.price.base", "quote.price.currency", "quote.label"], rules: [ + ["< 25", "100", "'EUR'", "'young'"], + ["", "80", "'EUR'", "'standard'"], + ]}, + ], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20}, quote: {price: {base: 100, currency: "EUR"}, label: "young"}}], + [{customer: {age: 40}}, {customer: {age: 40}, quote: {price: {base: 80, currency: "EUR"}, label: "standard"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Reading assembled objects: a read of the whole object, an intermediate object or a leaf runs +// after every contributing block, whatever the document order. + +{ + name: "a reader of the whole object listed before the leaf writers", + policy: { + models: {loan: {amount: "number", fee: "number"}}, + blocks: [ + {expression: "summary", value: "totals.principal + totals.fees"}, + {expression: "totals.principal", value: "loan.amount"}, + {expression: "totals.fees", value: "loan.fee"}, + ], + }, + cases: [ + [{loan: {amount: 100, fee: 5}}, {loan: {amount: 100, fee: 5}, totals: {principal: 100, fees: 5}, summary: 105}], + [{loan: {amount: 1, fee: 0.5}}, {loan: {amount: 1, fee: 0.5}, totals: {principal: 1, fees: 0.5}, summary: 1.5}], + ], +} + +{ + name: "a coarse read of an intermediate object waits for all leaves", + policy: { + models: {loan: {amount: "number"}}, + blocks: [ + {expression: "tierCount", value: "len(keys(totals.byTier))"}, + {expression: "totals.byTier.gold", value: "loan.amount"}, + {expression: "totals.byTier.silver", value: "loan.amount / 2"}, + {expression: "totals.byTier.bronze", value: "loan.amount / 4"}, + ], + }, + cases: [ + [{loan: {amount: 100}}, {loan: {amount: 100}, totals: {byTier: {gold: 100, silver: 50, bronze: 25}}, tierCount: 3}], + [{loan: {amount: 0}}, {loan: {amount: 0}, totals: {byTier: {gold: 0, silver: 0, bronze: 0}}, tierCount: 3}], + ], +} + +{ + name: "a coarse read of the root object waits for all leaves", + policy: { + models: {loan: {amount: "number"}}, + blocks: [ + {expression: "keyList", value: "keys(totals)"}, + {expression: "totals.a", value: "loan.amount"}, + {expression: "totals.b.c", value: "loan.amount"}, + ], + }, + cases: [ + [{loan: {amount: 1}}, {loan: {amount: 1}, totals: {a: 1, b: {c: 1}}, keyList: ["a", "b"]}], + ], +} + +{ + name: "a leaf read of a nested computed value", + policy: { + models: {loan: {amount: "number"}}, + blocks: [ + {expression: "doubleGold", value: "totals.byTier.gold.due * 2"}, + {expression: "totals.byTier.gold.due", value: "loan.amount + 1"}, + ], + }, + cases: [ + [{loan: {amount: 1}}, {loan: {amount: 1}, totals: {byTier: {gold: {due: 2}}}, doubleGold: 4}], + [{loan: {amount: -1}}, {loan: {amount: -1}, totals: {byTier: {gold: {due: 0}}}, doubleGold: 0}], + ], +} + +{ + name: "a leaf read of a field inside an object written whole", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "out.y", value: "calc.inner.y + 1"}, + {expression: "calc.inner", value: "{x: s.v, y: s.v * 10}"}, + ], + }, + cases: [ + [{s: {v: 1}}, {s: {v: 1}, calc: {inner: {x: 1, y: 10}}, out: {y: 11}}], + [{s: {v: 0}}, {s: {v: 0}, calc: {inner: {x: 0, y: 0}}, out: {y: 1}}], + ], +} + +{ + name: "a nested leaf depends on an upstream computed value", + policy: { + models: {loan: {amount: "number"}}, + blocks: [ + {expression: "totals.interest.due", value: "loan.amount * rate"}, + {expression: "rate", value: "loan.amount > 1000 ? 0.05 : 0.1"}, + {expression: "totals.count", value: "len(keys(totals.interest))"}, + ], + }, + cases: [ + [{loan: {amount: 100}}, {loan: {amount: 100}, rate: 0.1, totals: {interest: {due: 10}, count: 1}}], + [{loan: {amount: 2000}}, {loan: {amount: 2000}, rate: 0.05, totals: {interest: {due: 100}, count: 1}}], + ], +} + +{ + name: "a chain between leaves of the same object", + policy: { + models: {loan: {amount: "number"}}, + blocks: [ + {expression: "totals.c", value: "totals.b * 2"}, + {expression: "totals.b", value: "totals.a + 1"}, + {expression: "totals.a", value: "loan.amount"}, + ], + }, + cases: [ + [{loan: {amount: 1}}, {loan: {amount: 1}, totals: {a: 1, b: 2, c: 4}}], + [{loan: {amount: 10}}, {loan: {amount: 10}, totals: {a: 10, b: 11, c: 22}}], + ], +} + +{ + name: "a goal on a nested leaf", + policy: { + models: {loan: {amount: "number"}}, + blocks: [ + {expression: "totals.a", value: "loan.amount"}, + {expression: "totals.b", value: "loan.amount * 2"}, + ], + }, + cases: [ + {input: {loan: {amount: 1}}, goals: ["totals.a"], output: {loan: {amount: 1}, totals: {a: 1}}}, + {input: {loan: {amount: 1}}, goals: ["totals.b"], output: {loan: {amount: 1}, totals: {b: 2}}}, + {input: {loan: {amount: 1}}, goals: ["totals"], output: {loan: {amount: 1}, totals: {a: 1, b: 2}}}, + {input: {loan: {amount: 1}}, output: {loan: {amount: 1}, totals: {a: 1, b: 2}}}, + ], +} + +// --------------------------------------------------------------------------------------------- +// Writing into nested objects of entities. A relationship (`customer.address` is an `address` +// entity) is itself an entity: its computed properties are written through the entity name +// (`address.inEu`) and land on the nested object in the input. Writing through the relationship +// path (`customer.address.inEu`) writes below a declared property, which is InputOverride. + +{ + name: "a computed property on a related entity", + policy: { + models: {customer: {age: "number", address: "address"}, address: {country: "string"}}, + blocks: [{expression: "address.inEu", value: "address.country in ['DE', 'FR']"}], + }, + cases: [ + [{customer: {age: 1, address: {country: "DE"}}}, {customer: {age: 1, address: {country: "DE", inEu: true}}}], + [{customer: {age: 1, address: {country: "US"}}}, {customer: {age: 1, address: {country: "US", inEu: false}}}], + [{customer: {age: 1, address: {country: "FR", zip: "75"}}}, {customer: {age: 1, address: {country: "FR", zip: "75", inEu: true}}}], + ], +} + +{ + name: "a related entity's computed property reads through the relationship path", + policy: { + models: {customer: {age: "number", address: "address"}, address: {country: "string"}}, + blocks: [{expression: "address.label", value: "customer.address.country + '/' + string(customer.age)"}], + }, + cases: [ + [{customer: {age: 1, address: {country: "DE"}}}, {customer: {age: 1, address: {country: "DE", label: "DE/1"}}}], + ], +} + +{ + name: "a root entity reads a related entity's computed property", + policy: { + models: {customer: {age: "number", address: "address"}, address: {country: "string"}}, + blocks: [ + {expression: "customer.discount", value: "customer.address.inEu ? 0.1 : 0"}, + {expression: "address.inEu", value: "address.country in ['DE', 'FR']"}, + ], + }, + cases: [ + [{customer: {age: 1, address: {country: "DE"}}}, {customer: {age: 1, discount: 0.1, address: {country: "DE", inEu: true}}}], + [{customer: {age: 1, address: {country: "US"}}}, {customer: {age: 1, discount: 0, address: {country: "US", inEu: false}}}], + ], +} + +{ + name: "writing through the relationship path is an InputOverride error", + policy: { + models: {customer: {age: "number", address: "address"}, address: {country: "string"}}, + blocks: [{expression: "customer.address.inEu", value: "customer.address.country in ['DE', 'FR']"}], + }, + cases: [ + [{customer: {age: 1, address: {country: "DE"}}}, "!error"], + [{customer: {age: 1, address: {country: "US"}}}, "!error"], + ], +} + +{ + name: "a related entity is validated", + policy: { + models: {customer: {address: "address"}, address: {country: "string"}}, + blocks: [{expression: "address.label", value: "address.country"}], + }, + cases: [ + [{customer: {address: {country: 5}}}, "!error: InputValidationFailed"], + [{customer: {address: "DE"}}, "!error: InputValidationFailed"], + [{customer: {address: {}}}, "!error: MissingRequiredInputs"], + [{customer: {}}, "!error: MissingRequiredInputs"], + [{customer: {address: {country: "DE", extra: 1}}}, {customer: {address: {country: "DE", extra: 1, label: "DE"}}}], + ], +} + +{ + name: "a nested spine under a related entity", + policy: { + models: {customer: {address: "address"}, address: {country: "string"}}, + blocks: [{expression: "address.geo.region", value: "address.country == 'DE' ? 'EU' : 'OTHER'"}], + }, + cases: [ + [{customer: {address: {country: "DE"}}}, {customer: {address: {country: "DE", geo: {region: "EU"}}}}], + [{customer: {address: {country: "BR"}}}, {customer: {address: {country: "BR", geo: {region: "OTHER"}}}}], + ], +} + +{ + name: "a computed property on an optional related entity", + policy: { + models: {customer: {age: "number", address: "address?"}, address: {country: "string?"}}, + blocks: [{expression: "address.known", value: "address.country != null"}], + }, + cases: [ + [{customer: {age: 1, address: {country: "DE"}}}, {customer: {age: 1, address: {country: "DE", known: true}}}], + [{customer: {age: 1, address: {}}}, {customer: {age: 1, address: {known: false}}}], + [{customer: {age: 1, address: {country: null}}}, {customer: {age: 1, address: {country: null, known: false}}}], + [{customer: {age: 1}}, {customer: {age: 1}}], + ], +} + +{ + name: "writing a declared property of a related entity is an InputOverride error", + policy: { + models: {customer: {address: "address"}, address: {country: "string"}}, + blocks: [{expression: "address.country", value: "'XX'"}], + }, + cases: [ + [{customer: {address: {country: "DE"}}}, "!error"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Conflicts with input values. + +{ + name: "a nested write merges into an undeclared input object", + policy: { + models: {loan: {amount: "number"}}, + blocks: [{expression: "totals.due", value: "loan.amount"}], + }, + cases: [ + [{loan: {amount: 5}, totals: {other: 1}}, {loan: {amount: 5}, totals: {other: 1, due: 5}}], + [{loan: {amount: 5}, totals: {due: 99}}, {loan: {amount: 5}, totals: {due: 5}}], + [{loan: {amount: 5}, totals: {}}, {loan: {amount: 5}, totals: {due: 5}}], + ], +} + +{ + name: "a nested write over an undeclared input scalar", + policy: { + models: {loan: {amount: "number"}}, + blocks: [{expression: "totals.due", value: "loan.amount"}], + }, + cases: [ + [{loan: {amount: 5}, totals: 7}, {loan: {amount: 5}, totals: {due: 5}}, "bug: the computed write is silently dropped because the input holds a non-object at the spine; the write should replace it (or the policy should fail), never vanish"], + [{loan: {amount: 5}, totals: "x"}, {loan: {amount: 5}, totals: {due: 5}}, "bug: the computed write is silently dropped because the input holds a non-object at the spine; the write should replace it (or the policy should fail), never vanish"], + [{loan: {amount: 5}, totals: null}, {loan: {amount: 5}, totals: {due: 5}}, "bug: an input null at the spine swallows the computed write; null should behave like a missing key"], + [{loan: {amount: 5}, totals: [1, 2]}, {loan: {amount: 5}, totals: {due: 5}}, "bug: the computed write is silently dropped because the input holds a non-object at the spine; the write should replace it (or the policy should fail), never vanish"], + [{loan: {amount: 5}}, {loan: {amount: 5}, totals: {due: 5}}], + ], +} + +{ + name: "a deep write merges into a deep undeclared input object", + policy: { + models: {loan: {amount: "number"}}, + blocks: [{expression: "totals.byTier.gold", value: "loan.amount"}], + }, + cases: [ + [{loan: {amount: 5}, totals: {byTier: {silver: 1}, keep: true}}, {loan: {amount: 5}, totals: {byTier: {silver: 1, gold: 5}, keep: true}}], + [{loan: {amount: 5}, totals: {byTier: 3}}, {loan: {amount: 5}, totals: {byTier: {gold: 5}}}, "bug: the computed write is silently dropped because the input holds a non-object at the spine; the write should replace it (or the policy should fail), never vanish"], + ], +} + +{ + name: "a nested write under an entity merges with undeclared input keys", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.flags.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20, flags: {vip: true}}}, {customer: {age: 20, flags: {vip: true, adult: true}}}], + [{customer: {age: 20, flags: false}}, {customer: {age: 20, flags: {adult: true}}}, "bug: the computed write is silently dropped because the input holds a non-object at the spine; the write should replace it (or the policy should fail), never vanish"], + [{customer: {age: 20, flags: null}}, {customer: {age: 20, flags: {adult: true}}}, "bug: an input null at the spine swallows the computed write"], + [{customer: {age: 20}}, {customer: {age: 20, flags: {adult: true}}}], + ], +} + +{ + name: "a nested write under a declared scalar is an InputOverride error", + policy: { + models: {customer: {tier: "string"}}, + blocks: [{expression: "customer.tier.code", value: "upper(customer.tier)"}], + }, + cases: [ + [{customer: {tier: "gold"}}, "!error"], + ], +} + +{ + name: "a nested write under a declared primitive array is an InputOverride error", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [{expression: "cart.prices.total", value: "sum(cart.prices)"}], + }, + cases: [ + [{cart: {prices: [1, 2]}}, "!error"], + ], +} + +{ + name: "reads of the input object's other keys are unaffected by the write", + policy: { + models: {loan: {amount: "number"}}, + blocks: [ + {expression: "totals.due", value: "loan.amount"}, + {expression: "totalsDue", value: "totals.due + 1"}, + ], + }, + cases: [ + [{loan: {amount: 5}, totals: {due: 100}}, {loan: {amount: 5}, totals: {due: 5}, totalsDue: 6}], + [{loan: {amount: 5}}, {loan: {amount: 5}, totals: {due: 5}, totalsDue: 6}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Write conflicts. Writing an object whole and writing into it (PartialObjectWrite) would let one +// write silently clobber the other; writing the same nested leaf twice is DuplicateWriter. + +{ + name: "a whole-object write and a nested write into it", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "summary", value: "{a: s.v}"}, + {expression: "summary.b", value: "s.v * 2"}, + ], + }, + cases: [ + [{s: {v: 1}}, "!error"], + ], +} + +{ + name: "a whole-object write and a deep nested write into it", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "summary.inner.deep", value: "s.v"}, + {expression: "summary.inner", value: "{other: s.v}"}, + ], + }, + cases: [ + [{s: {v: 1}}, "!error"], + ], +} + +{ + name: "the same nested leaf written twice", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "totals.byTier.gold", value: "s.v"}, + {expression: "totals.byTier.gold", value: "s.v * 2"}, + ], + }, + cases: [ + [{s: {v: 1}}, "!error"], + ], +} + +{ + name: "a leaf writer that reads its own enclosing object", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "totals.a", value: "s.v"}, + {expression: "totals.count", value: "len(keys(totals))"}, + ], + }, + cases: [ + [{s: {v: 1}}, "!error"], + ], +} + +{ + name: "same leaf names under different parents are not duplicates", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "a.x.value", value: "s.v"}, + {expression: "b.x.value", value: "s.v + 1"}, + {expression: "a.y.value", value: "s.v + 2"}, + ], + }, + cases: [ + [{s: {v: 1}}, {s: {v: 1}, a: {x: {value: 1}, y: {value: 3}}, b: {x: {value: 2}}}], + [{s: {v: 0}}, {s: {v: 0}, a: {x: {value: 0}, y: {value: 2}}, b: {x: {value: 1}}}], + ], +} + +{ + name: "a nested path that shadows a top-level computed name", + policy: { + models: {s: {v: "number"}}, + blocks: [ + {expression: "total", value: "s.v"}, + {expression: "report.total", value: "total * 2"}, + ], + }, + cases: [ + [{s: {v: 3}}, {s: {v: 3}, total: 3, report: {total: 6}}], + [{s: {v: 0}}, {s: {v: 0}, total: 0, report: {total: 0}}], + ], +} diff --git a/core/engine/tests/spec/policy/05-match-blocks.json5 b/core/engine/tests/spec/policy/05-match-blocks.json5 new file mode 100644 index 00000000..5f75a54f --- /dev/null +++ b/core/engine/tests/spec/policy/05-match-blocks.json5 @@ -0,0 +1,773 @@ +// Match blocks: arms are tried in document order, the first arm whose condition is true +// writes its value to the block's key. An arm with an empty condition is the default and +// always matches. Without a matching arm the key is written as null (the analyzer reports +// MissingDefaultBranch for a non-exhaustive match without default, but evaluation still +// runs and falls through to null; diagnostics are not observable from this harness). + +// --------------------------------------------------------------------------- +// Arm order: the first true arm wins, later arms are not consulted. +// --------------------------------------------------------------------------- +{ + name: "first true arm wins in document order", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age >= 65", "'senior'"], + ["customer.age >= 18", "'adult'"], + ["", "'minor'"], + ]}], + }, + cases: [ + [{customer: {age: 70}}, {customer: {age: 70, tier: "senior"}}], + [{customer: {age: 65}}, {customer: {age: 65, tier: "senior"}}], + [{customer: {age: 64.99}}, {customer: {age: 64.99, tier: "adult"}}], + [{customer: {age: 18}}, {customer: {age: 18, tier: "adult"}}], + [{customer: {age: 17}}, {customer: {age: 17, tier: "minor"}}], + [{customer: {age: 0}}, {customer: {age: 0, tier: "minor"}}], + [{customer: {age: -5}}, {customer: {age: -5, tier: "minor"}}], + ], +} + +{ + name: "overlapping arms: the earlier, broader arm shadows the later one", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age >= 18", "'adult'"], + ["customer.age >= 65", "'senior'"], + ["", "'minor'"], + ]}], + }, + cases: [ + [{customer: {age: 70}}, {customer: {age: 70, tier: "adult"}}], + [{customer: {age: 20}}, {customer: {age: 20, tier: "adult"}}], + [{customer: {age: 10}}, {customer: {age: 10, tier: "minor"}}], + ], +} + +{ + name: "identical conditions: only the first arm is ever selected", + policy: { + models: {customer: {vip: "boolean"}}, + blocks: [{match: "customer.label", arms: [ + ["customer.vip", "'first'"], + ["customer.vip", "'second'"], + ["", "'none'"], + ]}], + }, + cases: [ + [{customer: {vip: true}}, {customer: {vip: true, label: "first"}}], + [{customer: {vip: false}}, {customer: {vip: false, label: "none"}}], + ], +} + +{ + name: "an arm after a matched arm is not evaluated, so its error is not raised", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age > 10", "'old'"], + ["customer.name + 1 > 0", "'broken'"], + ["", "'young'"], + ]}], + }, + cases: [ + [{customer: {age: 20, name: "a"}}, {customer: {age: 20, name: "a", tier: "old"}}], + [{customer: {age: 11, name: ""}}, {customer: {age: 11, name: "", tier: "old"}}], + [{customer: {age: 5, name: "a"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "an arm value is only evaluated for the selected arm", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age > 10", "'ok'"], + ["", "customer.name + 1"], + ]}], + }, + cases: [ + [{customer: {age: 20, name: "a"}}, {customer: {age: 20, name: "a", tier: "ok"}}], + [{customer: {age: 2, name: "a"}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------- +// The default arm: an empty condition always matches. +// --------------------------------------------------------------------------- +{ + name: "default arm only", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [["", "'everyone'"]]}], + }, + cases: [ + [{customer: {age: 1}}, {customer: {age: 1, tier: "everyone"}}], + [{customer: {age: 100}}, {customer: {age: 100, tier: "everyone"}}], + ], +} + +{ + name: "default arm placed first shadows every later arm", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [ + ["", "'default'"], + ["customer.age > 10", "'old'"], + ]}], + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, tier: "default"}}], + [{customer: {age: 1}}, {customer: {age: 1, tier: "default"}}], + ], +} + +{ + name: "default arm in the middle: later arms are unreachable", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age > 50", "'old'"], + ["", "'middle'"], + ["customer.age < 10", "'child'"], + ]}], + }, + cases: [ + [{customer: {age: 60}}, {customer: {age: 60, tier: "old"}}], + [{customer: {age: 30}}, {customer: {age: 30, tier: "middle"}}], + [{customer: {age: 5}}, {customer: {age: 5, tier: "middle"}}], + ], +} + +{ + name: "whitespace-only condition is the default arm", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age > 50", "'old'"], + [" ", "'other'"], + ]}], + }, + cases: [ + [{customer: {age: 60}}, {customer: {age: 60, tier: "old"}}], + [{customer: {age: 3}}, {customer: {age: 3, tier: "other"}}], + ], +} + +{ + name: "`_` as a condition is an identifier read, not the default arm", + diagnostics: ["MISSING_DEFAULT_BRANCH", "UNDEFINED_VARIABLE"], + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age > 50", "'old'"], + ["_", "'other'"], + ]}], + }, + cases: [ + [{customer: {age: 60}}, "!error: MissingRequiredInputs", "question: the analyzer message tells users to add a default `_` arm, but on the wire `_` is a plain identifier read and the policy fails with a missing input `_`; only an empty condition is the default"], + [{customer: {age: 3}}, "!error: MissingRequiredInputs", "question: `_` arm is not treated as the default on the wire"], + ], +} + +// --------------------------------------------------------------------------- +// Missing default: no arm matches -> the key is written as null. +// --------------------------------------------------------------------------- +{ + name: "non-exhaustive match without default writes null when nothing matches", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age > 30", "'senior'"], + ["customer.age > 18", "'adult'"], + ]}], + }, + cases: [ + [{customer: {age: 40}}, {customer: {age: 40, tier: "senior"}}], + [{customer: {age: 20}}, {customer: {age: 20, tier: "adult"}}], + [{customer: {age: 18}}, {customer: {age: 18, tier: null}}, "question: the analyzer reports MissingDefaultBranch as an error, yet evaluation runs anyway and writes null; should an error-severity diagnostic block evaluation?"], + [{customer: {age: 1}}, {customer: {age: 1, tier: null}}], + ], +} + +{ + name: "single-arm match without default", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {customer: {flagged: "boolean"}}, + blocks: [{match: "customer.reason", arms: [["customer.flagged", "'manual review'"]]}], + }, + cases: [ + [{customer: {flagged: true}}, {customer: {flagged: true, reason: "manual review"}}], + [{customer: {flagged: false}}, {customer: {flagged: false, reason: null}}], + ], +} + +{ + name: "match with no arms writes null", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: []}], + }, + cases: [ + [{customer: {age: 1}}, {customer: {age: 1, tier: null}}], + [{customer: {age: 99}}, {customer: {age: 99, tier: null}}], + ], +} + +// --------------------------------------------------------------------------- +// Exhaustive (discriminated) matches without default: enum, boolean, numeric range. +// --------------------------------------------------------------------------- +{ + name: "every enum value covered, no default", + policy: { + models: {order: {channel: "string(web|store|phone)"}}, + blocks: [{match: "order.fee", arms: [ + ["order.channel == 'web'", "0"], + ["order.channel == 'store'", "2.5"], + ["order.channel == 'phone'", "5"], + ]}], + }, + cases: [ + [{order: {channel: "web"}}, {order: {channel: "web", fee: 0}}], + [{order: {channel: "store"}}, {order: {channel: "store", fee: 2.5}}], + [{order: {channel: "phone"}}, {order: {channel: "phone", fee: 5}}], + [{order: {channel: "fax"}}, "!error: InputValidationFailed"], + [{order: {channel: "WEB"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "enum covered with `in` lists", + policy: { + models: {order: {channel: "string(web|store|phone)"}}, + blocks: [{match: "order.kind", arms: [ + ["order.channel in ['web']", "'online'"], + ["order.channel in ['store', 'phone']", "'offline'"], + ]}], + }, + cases: [ + [{order: {channel: "web"}}, {order: {channel: "web", kind: "online"}}], + [{order: {channel: "store"}}, {order: {channel: "store", kind: "offline"}}], + [{order: {channel: "phone"}}, {order: {channel: "phone", kind: "offline"}}], + ], +} + +{ + name: "enum partially covered without default writes null for the rest", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {order: {channel: "string(web|store|phone)"}}, + blocks: [{match: "order.kind", arms: [["order.channel == 'web'", "'online'"]]}], + }, + cases: [ + [{order: {channel: "web"}}, {order: {channel: "web", kind: "online"}}], + [{order: {channel: "store"}}, {order: {channel: "store", kind: null}}], + ], +} + +{ + name: "both booleans covered, no default", + policy: { + models: {customer: {verified: "boolean"}}, + blocks: [{match: "customer.limit", arms: [ + ["customer.verified == true", "1000"], + ["customer.verified == false", "100"], + ]}], + }, + cases: [ + [{customer: {verified: true}}, {customer: {verified: true, limit: 1000}}], + [{customer: {verified: false}}, {customer: {verified: false, limit: 100}}], + [{customer: {verified: "yes"}}, "!error: InputValidationFailed"], + [{customer: {verified: 1}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "gap-free numeric range, no default", + policy: { + models: {customer: {score: "number"}}, + blocks: [{match: "customer.band", arms: [ + ["customer.score < 500", "'low'"], + ["customer.score >= 500 and customer.score < 700", "'mid'"], + ["customer.score >= 700", "'high'"], + ]}], + }, + cases: [ + [{customer: {score: 499.999}}, {customer: {score: 499.999, band: "low"}}], + [{customer: {score: 500}}, {customer: {score: 500, band: "mid"}}], + [{customer: {score: 699}}, {customer: {score: 699, band: "mid"}}], + [{customer: {score: 700}}, {customer: {score: 700, band: "high"}}], + [{customer: {score: -1e6}}, {customer: {score: -1e6, band: "low"}}], + [{customer: {score: 1e9}}, {customer: {score: 1e9, band: "high"}}], + ], +} + +{ + name: "numeric range with a gap writes null inside the gap", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {customer: {score: "number"}}, + blocks: [{match: "customer.band", arms: [ + ["customer.score < 500", "'low'"], + ["customer.score > 500", "'high'"], + ]}], + }, + cases: [ + [{customer: {score: 400}}, {customer: {score: 400, band: "low"}}], + [{customer: {score: 500}}, {customer: {score: 500, band: null}}], + [{customer: {score: 501}}, {customer: {score: 501, band: "high"}}], + ], +} + +// --------------------------------------------------------------------------- +// Arm values of different types. +// --------------------------------------------------------------------------- +{ + name: "arms produce values of different types", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {item: {kind: "string(n|s|b|o|a|z)"}}, + blocks: [{match: "item.value", arms: [ + ["item.kind == 'n'", "42.50"], + ["item.kind == 's'", "'text'"], + ["item.kind == 'b'", "true"], + ["item.kind == 'o'", "{x: 1, y: 'two'}"], + ["item.kind == 'a'", "[1, 'a', false]"], + ["item.kind == 'z'", "null"], + ]}], + }, + cases: [ + [{item: {kind: "n"}}, {item: {kind: "n", value: 42.5}}], + [{item: {kind: "s"}}, {item: {kind: "s", value: "text"}}], + [{item: {kind: "b"}}, {item: {kind: "b", value: true}}], + [{item: {kind: "o"}}, {item: {kind: "o", value: {x: 1, y: "two"}}}], + [{item: {kind: "a"}}, {item: {kind: "a", value: [1, "a", false]}}], + [{item: {kind: "z"}}, {item: {kind: "z", value: null}}], + ], +} + +{ + name: "an empty arm value writes null when selected", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.note", arms: [ + ["customer.age > 50", ""], + ["", "'young'"], + ]}], + }, + cases: [ + [{customer: {age: 60}}, {customer: {age: 60, note: null}}], + [{customer: {age: 6}}, {customer: {age: 6, note: "young"}}], + ], +} + +{ + name: "arm values computed from inputs", + policy: { + models: {order: {amount: "number", country: "string"}}, + blocks: [{match: "order.tax", arms: [ + ["order.country == 'DE'", "order.amount * 0.19"], + ["order.country == 'NL'", "round(order.amount * 0.21, 2)"], + ["", "0"], + ]}], + }, + cases: [ + [{order: {amount: 100, country: "DE"}}, {order: {amount: 100, country: "DE", tax: 19}}], + [{order: {amount: 10.10, country: "NL"}}, {order: {amount: 10.10, country: "NL", tax: 2.12}}], + [{order: {amount: 0.1, country: "DE"}}, {order: {amount: 0.1, country: "DE", tax: 0.019}}], + [{order: {amount: 100, country: "US"}}, {order: {amount: 100, country: "US", tax: 0}}], + [{order: {amount: 100, country: ""}}, {order: {amount: 100, country: "", tax: 0}}], + ], +} + +{ + name: "arm value erroring in the selected arm fails the evaluation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {order: {amount: "number", code: "string"}}, + blocks: [{match: "order.x", arms: [ + ["order.amount > 0", "order.code * 2"], + ["", "0"], + ]}], + }, + cases: [ + [{order: {amount: 1, code: "a"}}, "!error: ExpressionFailed"], + [{order: {amount: 0, code: "a"}}, {order: {amount: 0, code: "a", x: 0}}], + ], +} + +// --------------------------------------------------------------------------- +// Conditions that are not booleans. +// --------------------------------------------------------------------------- +{ + name: "a non-boolean condition never matches", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{match: "customer.code", arms: [ + ["customer.age", "'number'"], + ["customer.name", "'string'"], + ["", "'default'"], + ]}], + }, + cases: [ + [{customer: {age: 1, name: "x"}}, {customer: {age: 1, name: "x", code: "default"}}], + [{customer: {age: 0, name: ""}}, {customer: {age: 0, name: "", code: "default"}}], + ], +} + +{ + name: "a condition that errors fails the evaluation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {name: "string"}}, + blocks: [{match: "customer.code", arms: [ + ["customer.name + 1 > 2", "1"], + ["", "2"], + ]}], + }, + cases: [ + [{customer: {name: "x"}}, "!error: ExpressionFailed"], + [{customer: {name: ""}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------- +// Null and missing inputs. +// --------------------------------------------------------------------------- +{ + name: "required input missing or null is reported before evaluation", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [["customer.age > 30", "'senior'"], ["", "'other'"]]}], + }, + cases: [ + [{customer: {age: 40}}, {customer: {age: 40, tier: "senior"}}], + [{customer: {age: null}}, "!error: MissingRequiredInputs"], + [{customer: {}}, "!error: MissingRequiredInputs"], + [{}, "!error: MissingRequiredInputs"], + [{customer: {age: "40"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "optional input: null-guarded arms", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number?"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age == null", "'unknown'"], + ["customer.age > 30", "'senior'"], + ["", "'other'"], + ]}], + }, + cases: [ + [{customer: {age: 40}}, {customer: {age: 40, tier: "senior"}}], + [{customer: {age: 3}}, {customer: {age: 3, tier: "other"}}], + [{customer: {age: null}}, {customer: {age: null, tier: "unknown"}}], + [{customer: {}}, {customer: {tier: "unknown"}}], + ], +} + +{ + name: "optional input: ordering comparison against null errors", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number?"}}, + blocks: [{match: "customer.tier", arms: [ + ["customer.age > 30", "'senior'"], + ["", "'other'"], + ]}], + }, + cases: [ + [{customer: {age: 40}}, {customer: {age: 40, tier: "senior"}}], + [{customer: {age: 30}}, {customer: {age: 30, tier: "other"}}], + [{customer: {age: null}}, "!error: ExpressionFailed"], + [{customer: {}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "optional input: null-coalescing condition", + policy: { + models: {customer: {age: "number?"}}, + blocks: [{match: "customer.tier", arms: [ + ["(customer.age ?? 0) > 30", "'senior'"], + ["", "'other'"], + ]}], + }, + cases: [ + [{customer: {age: 40}}, {customer: {age: 40, tier: "senior"}}], + [{customer: {age: null}}, {customer: {age: null, tier: "other"}}], + [{customer: {}}, {customer: {tier: "other"}}], + ], +} + +{ + name: "optional string compared by equality", + policy: { + models: {customer: {country: "string?"}}, + blocks: [{match: "customer.region", arms: [ + ["customer.country == 'DE'", "'eu'"], + ["customer.country == null", "'unknown'"], + ["", "'world'"], + ]}], + }, + cases: [ + [{customer: {country: "DE"}}, {customer: {country: "DE", region: "eu"}}], + [{customer: {country: "US"}}, {customer: {country: "US", region: "world"}}], + [{customer: {country: ""}}, {customer: {country: "", region: "world"}}], + [{customer: {country: null}}, {customer: {country: null, region: "unknown"}}], + [{customer: {}}, {customer: {region: "unknown"}}], + ], +} + +{ + name: "optional boolean condition: null does not match", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {vip: "boolean?"}}, + blocks: [{match: "customer.label", arms: [ + ["customer.vip", "'vip'"], + ["", "'regular'"], + ]}], + }, + cases: [ + [{customer: {vip: true}}, {customer: {vip: true, label: "vip"}}], + [{customer: {vip: false}}, {customer: {vip: false, label: "regular"}}], + [{customer: {vip: null}}, {customer: {vip: null, label: "regular"}}], + [{customer: {}}, {customer: {label: "regular"}}], + ], +} + +// --------------------------------------------------------------------------- +// Target paths and data flow between blocks. +// --------------------------------------------------------------------------- +{ + name: "nested target path creates the intermediate object", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.risk.level", arms: [["customer.age > 60", "'high'"], ["", "'low'"]]}], + }, + cases: [ + [{customer: {age: 70}}, {customer: {age: 70, risk: {level: "high"}}}], + [{customer: {age: 20}}, {customer: {age: 20, risk: {level: "low"}}}], + ], +} + +{ + name: "a later block reads the match result", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {match: "customer.tier", arms: [["customer.age >= 18", "'adult'"], ["", "'minor'"]]}, + {expression: "customer.canBuy", value: "customer.tier == 'adult'"}, + ], + }, + cases: [ + [{customer: {age: 30}}, {customer: {age: 30, tier: "adult", canBuy: true}}], + [{customer: {age: 3}}, {customer: {age: 3, tier: "minor", canBuy: false}}], + ], +} + +{ + name: "match conditions read an earlier computed property", + policy: { + models: {order: {amount: "number", qty: "number"}}, + blocks: [ + {expression: "order.total", value: "order.amount * order.qty"}, + {match: "order.size", arms: [["order.total >= 1000", "'large'"], ["order.total >= 100", "'medium'"], ["", "'small'"]]}, + ], + }, + cases: [ + [{order: {amount: 500, qty: 2}}, {order: {amount: 500, qty: 2, total: 1000, size: "large"}}], + [{order: {amount: 50, qty: 2}}, {order: {amount: 50, qty: 2, total: 100, size: "medium"}}], + [{order: {amount: 5, qty: 0}}, {order: {amount: 5, qty: 0, total: 0, size: "small"}}], + ], +} + +{ + name: "computed dependency declared after the match block still flows in", + policy: { + models: {order: {amount: "number", qty: "number"}}, + blocks: [ + {match: "order.size", arms: [["order.total >= 100", "'big'"], ["", "'small'"]]}, + {expression: "order.total", value: "order.amount * order.qty"}, + ], + }, + cases: [ + [{order: {amount: 50, qty: 3}}, {order: {amount: 50, qty: 3, total: 150, size: "big"}}], + [{order: {amount: 5, qty: 3}}, {order: {amount: 5, qty: 3, total: 15, size: "small"}}], + ], +} + +{ + name: "chained matches: second match discriminates on the first one's result", + policy: { + models: {customer: {score: "number", income: "number"}}, + blocks: [ + {match: "customer.risk", arms: [["customer.score < 600", "'high'"], ["", "'low'"]]}, + {match: "customer.limit", arms: [ + ["customer.risk == 'high'", "0"], + ["customer.income > 50000", "10000"], + ["", "2000"], + ]}, + ], + }, + cases: [ + [{customer: {score: 500, income: 90000}}, {customer: {score: 500, income: 90000, risk: "high", limit: 0}}], + [{customer: {score: 700, income: 90000}}, {customer: {score: 700, income: 90000, risk: "low", limit: 10000}}], + [{customer: {score: 700, income: 50000}}, {customer: {score: 700, income: 50000, risk: "low", limit: 2000}}], + ], +} + +{ + name: "match reads a global scope value", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + globals: {config: {threshold: "number"}}, + models: {customer: {age: "number"}}, + blocks: [{match: "customer.status", arms: [["customer.age >= config.threshold", "'ok'"], ["", "'too young'"]]}], + }, + cases: [ + [{customer: {age: 18}, config: {threshold: 18}}, {customer: {age: 18, status: "ok"}, config: {threshold: 18}}], + [{customer: {age: 18}, config: {threshold: 21}}, {customer: {age: 18, status: "too young"}, config: {threshold: 21}}], + ], +} + +{ + name: "input properties not in the model pass through untouched", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.tier", arms: [["customer.age > 1", "'a'"], ["", "'b'"]]}], + }, + cases: [ + [{customer: {age: 2, extra: {x: [1]}}, other: true}, {customer: {age: 2, extra: {x: [1]}, tier: "a"}, other: true}], + [{customer: {age: 0, extra: null}}, {customer: {age: 0, extra: null, tier: "b"}}], + ], +} + +{ + name: "goals restrict evaluation to the requested match", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {match: "customer.tier", arms: [["customer.age > 30", "'senior'"], ["", "'junior'"]]}, + {match: "customer.discount", arms: [["customer.age > 60", "0.2"], ["", "0"]]}, + ], + }, + cases: [ + {input: {customer: {age: 70}}, goals: ["customer.tier"], output: {customer: {age: 70, tier: "senior"}}}, + {input: {customer: {age: 70}}, goals: ["customer.discount"], output: {customer: {age: 70, discount: 0.2}}}, + {input: {customer: {age: 10}}, goals: ["customer.tier", "customer.discount"], output: {customer: {age: 10, tier: "junior", discount: 0}}}, + {input: {customer: {age: 10}}, output: {customer: {age: 10, tier: "junior", discount: 0}}}, + ], +} + +// --------------------------------------------------------------------------- +// Per-instance evaluation: a match writing to an iterated entity runs for each instance. +// --------------------------------------------------------------------------- +{ + name: "match on a related entity runs once per instance", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{match: "company.size", arms: [ + ["company.revenue >= 1000000", "'large'"], + ["company.revenue >= 10000", "'medium'"], + ["", "'small'"], + ]}], + }, + cases: [ + [ + {customer: {companies: [{revenue: 2000000}, {revenue: 50000}, {revenue: 1}]}}, + {customer: {companies: [{revenue: 2000000, size: "large"}, {revenue: 50000, size: "medium"}, {revenue: 1, size: "small"}]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + [{customer: {companies: [{revenue: 10000}]}}, {customer: {companies: [{revenue: 10000, size: "medium"}]}}], + ], +} + +{ + name: "per-instance match without default writes null on unmatched instances only", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{match: "company.flag", arms: [["company.revenue < 0", "'loss'"]]}], + }, + cases: [ + [ + {customer: {companies: [{revenue: -1}, {revenue: 5}]}}, + {customer: {companies: [{revenue: -1, flag: "loss"}, {revenue: 5, flag: null}]}}, + ], + ], +} + +{ + name: "parent match aggregates over a per-instance match result", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {match: "company.size", arms: [["company.revenue >= 100", "'big'"], ["", "'small'"]]}, + {match: "customer.profile", arms: [ + ["some(customer.companies, #.size == 'big')", "'has big'"], + ["len(customer.companies) == 0", "'none'"], + ["", "'all small'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 200}, {revenue: 1}]}}, + {customer: {profile: "has big", companies: [{revenue: 200, size: "big"}, {revenue: 1, size: "small"}]}}, + ], + [ + {customer: {companies: [{revenue: 2}]}}, + {customer: {profile: "all small", companies: [{revenue: 2, size: "small"}]}}, + ], + [{customer: {companies: []}}, {customer: {profile: "none", companies: []}}], + ], +} + +// --------------------------------------------------------------------------- +// Dates and strings in conditions. +// --------------------------------------------------------------------------- +{ + name: "date input compared in arms", + policy: { + models: {contract: {start: "date"}}, + blocks: [{match: "contract.era", arms: [ + ["contract.start < d('2020-01-01')", "'legacy'"], + ["contract.start < d('2025-01-01')", "'current'"], + ["", "'new'"], + ]}], + }, + cases: [ + [{contract: {start: date('2019-12-31')}}, {contract: {start: date('2019-12-31'), era: "legacy"}}], + [{contract: {start: date('2020-01-01')}}, {contract: {start: date('2020-01-01'), era: "current"}}], + [{contract: {start: date('2025-03-01')}}, {contract: {start: date('2025-03-01'), era: "new"}}], + ], +} + +{ + name: "string functions in arms", + policy: { + models: {user: {email: "string"}}, + blocks: [{match: "user.kind", arms: [ + ["endsWith(user.email, '@gorules.io')", "'staff'"], + ["contains(user.email, '+')", "'alias'"], + ["len(user.email) == 0", "'empty'"], + ["", "'external'"], + ]}], + }, + cases: [ + [{user: {email: "a@gorules.io"}}, {user: {email: "a@gorules.io", kind: "staff"}}], + [{user: {email: "a+b@x.io"}}, {user: {email: "a+b@x.io", kind: "alias"}}], + [{user: {email: ""}}, {user: {email: "", kind: "empty"}}], + [{user: {email: "x@y.z"}}, {user: {email: "x@y.z", kind: "external"}}], + ], +} diff --git a/core/engine/tests/spec/policy/06-assertion-blocks.json5 b/core/engine/tests/spec/policy/06-assertion-blocks.json5 new file mode 100644 index 00000000..3f645dbe --- /dev/null +++ b/core/engine/tests/spec/policy/06-assertion-blocks.json5 @@ -0,0 +1,632 @@ +// Assertion blocks: every condition is evaluated, then the boolean results are folded left +// to right. A condition's operator joins it to the NEXT condition (the last operator is +// unused). There is no and-over-or precedence: `a or b and c` is `(a or b) and c`. +// `depth` opens a parenthesised group: a run of conditions at a deeper depth is folded on +// its own and joined to what came before with the operator of the condition before it. +// A condition that is not exactly a boolean counts as false. The result is written as a +// boolean to the output path. + +// --------------------------------------------------------------------------- +// Single conditions and constant conditions. +// --------------------------------------------------------------------------- +{ + name: "single condition", + policy: { + models: {x: {p: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: ["x.p"]}], + }, + cases: [ + [{x: {p: true}}, {x: {p: true, ok: true}}], + [{x: {p: false}}, {x: {p: false, ok: false}}], + ], +} + +{ + name: "constant conditions", + diagnostics: ["INVALID_EXPRESSION"], + policy: { + models: {x: {p: "boolean"}}, + blocks: [ + {assertion: "x.t", conditions: ["true"]}, + {assertion: "x.f", conditions: ["false"]}, + {assertion: "x.eq", conditions: ["1 == 1", "'a' != 'b'"]}, + ], + }, + cases: [ + [{x: {p: true}}, {x: {p: true, t: true, f: false, eq: true}}], + [{x: {p: false}}, {x: {p: false, t: true, f: false, eq: true}}], + ], +} + +{ + name: "single condition with a trailing `or` operator: the last operator is unused", + policy: { + models: {x: {p: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"]]}], + }, + cases: [ + [{x: {p: true}}, {x: {p: true, ok: true}}], + [{x: {p: false}}, {x: {p: false, ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Flat `and` and flat `or` chains. +// --------------------------------------------------------------------------- +{ + name: "and chain: all must hold", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: ["x.p", "x.q", "x.r"]}], + }, + cases: [ + [{x: {p: true, q: true, r: true}}, {x: {p: true, q: true, r: true, ok: true}}], + [{x: {p: false, q: true, r: true}}, {x: {p: false, q: true, r: true, ok: false}}], + [{x: {p: true, q: false, r: true}}, {x: {p: true, q: false, r: true, ok: false}}], + [{x: {p: true, q: true, r: false}}, {x: {p: true, q: true, r: false, ok: false}}], + [{x: {p: false, q: false, r: false}}, {x: {p: false, q: false, r: false, ok: false}}], + ], +} + +{ + name: "or chain: any one suffices", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], ["or", "x.q"], ["or", "x.r"]]}], + }, + cases: [ + [{x: {p: false, q: false, r: false}}, {x: {p: false, q: false, r: false, ok: false}}], + [{x: {p: true, q: false, r: false}}, {x: {p: true, q: false, r: false, ok: true}}], + [{x: {p: false, q: true, r: false}}, {x: {p: false, q: true, r: false, ok: true}}], + [{x: {p: false, q: false, r: true}}, {x: {p: false, q: false, r: true, ok: true}}], + [{x: {p: true, q: true, r: true}}, {x: {p: true, q: true, r: true, ok: true}}], + ], +} + +{ + name: "explicit `and` operators are the same as bare strings", + policy: { + models: {x: {p: "boolean", q: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p", 0], ["and", "x.q", 0]]}], + }, + cases: [ + [{x: {p: true, q: true}}, {x: {p: true, q: true, ok: true}}], + [{x: {p: true, q: false}}, {x: {p: true, q: false, ok: false}}], + [{x: {p: false, q: true}}, {x: {p: false, q: true, ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Mixed operators without groups: strict left-to-right fold. +// --------------------------------------------------------------------------- +{ + name: "`p and q or r` folds as `(p and q) or r`", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", "x.q"], "x.r"]}], + }, + cases: [ + [{x: {p: true, q: true, r: false}}, {x: {p: true, q: true, r: false, ok: true}}], + [{x: {p: false, q: true, r: false}}, {x: {p: false, q: true, r: false, ok: false}}], + [{x: {p: false, q: false, r: true}}, {x: {p: false, q: false, r: true, ok: true}}], + [{x: {p: true, q: false, r: false}}, {x: {p: true, q: false, r: false, ok: false}}], + ], +} + +{ + name: "`p or q and r` folds as `(p or q) and r`, without and-over-or precedence", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], ["and", "x.q"], "x.r"]}], + }, + cases: [ + [{x: {p: true, q: false, r: false}}, {x: {p: true, q: false, r: false, ok: false}}, "question: a strict left fold gives false; with the usual and-over-or precedence `p or (q and r)` it would be true. Pinned as left fold, which matches how the editor lists conditions"], + [{x: {p: true, q: true, r: true}}, {x: {p: true, q: true, r: true, ok: true}}], + [{x: {p: false, q: true, r: true}}, {x: {p: false, q: true, r: true, ok: true}}], + [{x: {p: true, q: true, r: false}}, {x: {p: true, q: true, r: false, ok: false}}], + [{x: {p: false, q: false, r: true}}, {x: {p: false, q: false, r: true, ok: false}}], + ], +} + +{ + name: "long alternating chain folds left", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], ["and", "x.q"], ["or", "x.r"], "x.s"]}], + }, + cases: [ + [{x: {p: true, q: false, r: false, s: false}}, {x: {p: true, q: false, r: false, s: false, ok: false}}], + [{x: {p: false, q: false, r: true, s: false}}, {x: {p: false, q: false, r: true, s: false, ok: false}}], + [{x: {p: false, q: false, r: false, s: true}}, {x: {p: false, q: false, r: false, s: true, ok: true}}], + [{x: {p: true, q: true, r: false, s: false}}, {x: {p: true, q: true, r: false, s: false, ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Grouping by depth. +// --------------------------------------------------------------------------- +{ + name: "`p and (q or r)` with a depth-1 group", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", "x.q", 1], ["and", "x.r", 1]]}], + }, + cases: [ + [{x: {p: true, q: true, r: false}}, {x: {p: true, q: true, r: false, ok: true}}], + [{x: {p: true, q: false, r: true}}, {x: {p: true, q: false, r: true, ok: true}}], + [{x: {p: true, q: false, r: false}}, {x: {p: true, q: false, r: false, ok: false}}], + [{x: {p: false, q: true, r: true}}, {x: {p: false, q: true, r: true, ok: false}}], + ], +} + +{ + name: "`p or (q and r)` recovers the precedence reading", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], ["and", "x.q", 1], ["and", "x.r", 1]]}], + }, + cases: [ + [{x: {p: true, q: false, r: false}}, {x: {p: true, q: false, r: false, ok: true}}], + [{x: {p: false, q: true, r: true}}, {x: {p: false, q: true, r: true, ok: true}}], + [{x: {p: false, q: true, r: false}}, {x: {p: false, q: true, r: false, ok: false}}], + [{x: {p: false, q: false, r: false}}, {x: {p: false, q: false, r: false, ok: false}}], + ], +} + +{ + name: "leading group `(p or q)` joined to the next condition by the group's last operator", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 1], ["and", "x.q", 1], ["or", "x.r", 0]]}], + }, + cases: [ + [{x: {p: true, q: false, r: true}}, {x: {p: true, q: false, r: true, ok: true}}], + [{x: {p: true, q: false, r: false}}, {x: {p: true, q: false, r: false, ok: false}}], + [{x: {p: false, q: false, r: true}}, {x: {p: false, q: false, r: true, ok: false}}], + [{x: {p: false, q: true, r: true}}, {x: {p: false, q: true, r: true, ok: true}}], + ], +} + +{ + name: "group in the middle: `(p and (q or r)) and s`", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", "x.q", 1], ["and", "x.r", 1], ["or", "x.s", 0]]}], + }, + cases: [ + [{x: {p: true, q: true, r: false, s: true}}, {x: {p: true, q: true, r: false, s: true, ok: true}}], + [{x: {p: true, q: true, r: false, s: false}}, {x: {p: true, q: true, r: false, s: false, ok: false}}], + [{x: {p: true, q: false, r: false, s: true}}, {x: {p: true, q: false, r: false, s: true, ok: false}}], + [{x: {p: false, q: true, r: true, s: true}}, {x: {p: false, q: true, r: true, s: true, ok: false}}], + ], +} + +{ + name: "nested groups: `p and (q or (r and s))`", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", "x.q", 1], ["and", "x.r", 2], ["and", "x.s", 2]]}], + }, + cases: [ + [{x: {p: true, q: true, r: false, s: false}}, {x: {p: true, q: true, r: false, s: false, ok: true}}], + [{x: {p: true, q: false, r: true, s: true}}, {x: {p: true, q: false, r: true, s: true, ok: true}}], + [{x: {p: true, q: false, r: true, s: false}}, {x: {p: true, q: false, r: true, s: false, ok: false}}], + [{x: {p: false, q: true, r: true, s: true}}, {x: {p: false, q: true, r: true, s: true, ok: false}}], + ], +} + +{ + name: "two groups via nesting: `(p or q) and (r or s)`", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 1], ["and", "x.q", 1], ["or", "x.r", 2], ["and", "x.s", 2]]}], + }, + cases: [ + [{x: {p: true, q: false, r: false, s: true}}, {x: {p: true, q: false, r: false, s: true, ok: true}}], + [{x: {p: false, q: true, r: true, s: false}}, {x: {p: false, q: true, r: true, s: false, ok: true}}], + [{x: {p: true, q: true, r: false, s: false}}, {x: {p: true, q: true, r: false, s: false, ok: false}}], + [{x: {p: false, q: false, r: true, s: true}}, {x: {p: false, q: false, r: true, s: true, ok: false}}], + ], +} + +{ + name: "adjacent runs at the same depth merge into one group", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 1], ["and", "x.q", 1], ["or", "x.r", 1], ["and", "x.s", 1]]}], + }, + cases: [ + [{x: {p: true, q: false, r: false, s: true}}, {x: {p: true, q: false, r: false, s: true, ok: true}}], + [{x: {p: true, q: false, r: false, s: false}}, {x: {p: true, q: false, r: false, s: false, ok: false}}], + [{x: {p: false, q: false, r: false, s: true}}, {x: {p: false, q: false, r: false, s: true, ok: true}}], + ], +} + +{ + name: "depth jump from 0 to 2 opens two groups at once", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", "x.q", 2], ["and", "x.r", 2]]}], + }, + cases: [ + [{x: {p: true, q: false, r: true}}, {x: {p: true, q: false, r: true, ok: true}}], + [{x: {p: true, q: false, r: false}}, {x: {p: true, q: false, r: false, ok: false}}], + [{x: {p: false, q: true, r: true}}, {x: {p: false, q: true, r: true, ok: false}}], + ], +} + +{ + name: "every condition in one group is the same as no group", + policy: { + models: {x: {p: "boolean", q: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 1], ["or", "x.q", 1]]}], + }, + cases: [ + [{x: {p: false, q: true}}, {x: {p: false, q: true, ok: true}}], + [{x: {p: false, q: false}}, {x: {p: false, q: false, ok: false}}], + ], +} + +{ + name: "dropping from depth 2 straight to 0 closes both groups", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], ["and", "x.q", 1], ["or", "x.r", 2], ["or", "x.s", 0]]}], + }, + cases: [ + [{x: {p: false, q: false, r: false, s: true}}, {x: {p: false, q: false, r: false, s: true, ok: true}}], + [{x: {p: false, q: true, r: true, s: false}}, {x: {p: false, q: true, r: true, s: false, ok: true}}], + [{x: {p: true, q: false, r: false, s: false}}, {x: {p: true, q: false, r: false, s: false, ok: true}}], + [{x: {p: false, q: true, r: false, s: false}}, {x: {p: false, q: true, r: false, s: false, ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Non-boolean and null condition values. +// --------------------------------------------------------------------------- +{ + name: "non-boolean condition values count as false", + policy: { + models: {x: {n: "number", s: "string", l: "boolean[]"}}, + blocks: [ + {assertion: "x.byNumber", conditions: ["x.n"]}, + {assertion: "x.byString", conditions: ["x.s"]}, + {assertion: "x.byList", conditions: ["x.l"]}, + {assertion: "x.orNumber", conditions: [["or", "x.n"], "true"]}, + ], + }, + cases: [ + [{x: {n: 1, s: "true", l: [true]}}, {x: {n: 1, s: "true", l: [true], byNumber: false, byString: false, byList: false, orNumber: true}}], + [{x: {n: 0, s: "", l: []}}, {x: {n: 0, s: "", l: [], byNumber: false, byString: false, byList: false, orNumber: true}}], + ], +} + +{ + name: "a null condition value counts as false", + policy: { + models: {x: {p: "boolean?"}}, + blocks: [ + {assertion: "x.isTrue", conditions: ["x.p"]}, + {assertion: "x.isMissing", conditions: ["x.p == null"]}, + {assertion: "x.isNotTrue", conditions: ["x.p != true"]}, + ], + }, + cases: [ + [{x: {p: true}}, {x: {p: true, isTrue: true, isMissing: false, isNotTrue: false}}], + [{x: {p: false}}, {x: {p: false, isTrue: false, isMissing: false, isNotTrue: true}}], + [{x: {p: null}}, {x: {p: null, isTrue: false, isMissing: true, isNotTrue: true}}], + [{x: {}}, {x: {isTrue: false, isMissing: true, isNotTrue: true}}], + ], +} + +{ + name: "optional number: ordering comparison against null errors", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number?"}}, + blocks: [{assertion: "x.ok", conditions: ["x.n > 1"]}], + }, + cases: [ + [{x: {n: 2}}, {x: {n: 2, ok: true}}], + [{x: {n: 1}}, {x: {n: 1, ok: false}}], + [{x: {n: null}}, "!error: ExpressionFailed"], + [{x: {}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "optional number guarded by an `and` condition still errors: conditions do not short-circuit", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number?"}}, + blocks: [{assertion: "x.ok", conditions: ["x.n != null", "x.n > 1"]}], + }, + cases: [ + [{x: {n: 2}}, {x: {n: 2, ok: true}}], + [{x: {n: 0}}, {x: {n: 0, ok: false}}], + [{x: {n: null}}, "!error: ExpressionFailed", "question: every condition is evaluated even after an `and` chain is already false, so a null guard in an earlier condition does not protect a later one; a short-circuit would give false"], + ], +} + +{ + name: "null-safe guard inside one condition", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number?"}}, + blocks: [{assertion: "x.ok", conditions: ["x.n != null and x.n > 1"]}], + }, + cases: [ + [{x: {n: 2}}, {x: {n: 2, ok: true}}], + [{x: {n: null}}, {x: {n: null, ok: false}}], + [{x: {}}, {x: {ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Erroring conditions. +// --------------------------------------------------------------------------- +{ + name: "an erroring condition fails the evaluation regardless of the other results", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {p: "boolean", s: "string"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], "x.s * 2 > 1"]}], + }, + cases: [ + [{x: {p: true, s: "a"}}, "!error: ExpressionFailed"], + [{x: {p: false, s: "a"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "an erroring first condition fails the evaluation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {p: "boolean", s: "string"}}, + blocks: [{assertion: "x.ok", conditions: ["x.s - 1 > 0", "x.p"]}], + }, + cases: [ + [{x: {p: true, s: "a"}}, "!error: ExpressionFailed"], + [{x: {p: false, s: ""}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------- +// Degenerate condition lists. +// --------------------------------------------------------------------------- +{ + name: "empty conditions are skipped", + policy: { + models: {x: {p: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: ["", "x.p", " "]}], + }, + cases: [ + [{x: {p: true}}, {x: {p: true, ok: true}}], + [{x: {p: false}}, {x: {p: false, ok: false}}], + ], +} + +{ + name: "an assertion without conditions writes false", + diagnostics: ["EMPTY_BLOCK"], + policy: { + models: {x: {p: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: []}, {assertion: "x.blank", conditions: ["", " "]}], + }, + cases: [ + [{x: {p: true}}, {x: {p: true, ok: false, blank: false}}], + [{x: {p: false}}, {x: {p: false, ok: false, blank: false}}], + ], +} + +{ + name: "a condition at or beyond the maximum depth is dropped", + diagnostics: ["MAX_DEPTH_EXCEEDED"], + policy: { + models: {x: {p: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["and", "false", 32]]}], + }, + cases: [ + [{x: {p: true}}, {x: {p: true, ok: true}}], + [{x: {p: false}}, {x: {p: false, ok: false}}], + ], +} + +{ + name: "a condition just below the maximum depth is kept", + policy: { + models: {x: {p: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["and", "false", 31]]}], + }, + cases: [ + [{x: {p: true}}, {x: {p: true, ok: false}}], + [{x: {p: false}}, {x: {p: false, ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Missing and invalid inputs. +// --------------------------------------------------------------------------- +{ + name: "required inputs are checked before the assertion runs", + policy: { + models: {customer: {age: "number", country: "string"}}, + blocks: [{assertion: "customer.eligible", conditions: ["customer.age >= 18", "customer.country == 'US'"]}], + }, + cases: [ + [{customer: {age: 18, country: "US"}}, {customer: {age: 18, country: "US", eligible: true}}], + [{customer: {age: 18}}, "!error: MissingRequiredInputs"], + [{customer: {country: "US", age: null}}, "!error: MissingRequiredInputs"], + [{customer: {age: "18", country: "US"}}, "!error: InputValidationFailed"], + [{}, "!error: MissingRequiredInputs"], + ], +} + +// --------------------------------------------------------------------------- +// Outputs and data flow. +// --------------------------------------------------------------------------- +{ + name: "nested output path", + policy: { + models: {loan: {amount: "number"}}, + blocks: [{assertion: "loan.checks.withinLimit", conditions: ["loan.amount <= 10000"]}], + }, + cases: [ + [{loan: {amount: 5000}}, {loan: {amount: 5000, checks: {withinLimit: true}}}], + [{loan: {amount: 10001}}, {loan: {amount: 10001, checks: {withinLimit: false}}}], + ], +} + +{ + name: "assertions chained: a later assertion reads an earlier result", + policy: { + models: {customer: {age: "number", score: "number"}}, + blocks: [ + {assertion: "customer.adult", conditions: ["customer.age >= 18"]}, + {assertion: "customer.goodCredit", conditions: ["customer.score >= 650"]}, + {assertion: "customer.approved", conditions: ["customer.adult", "customer.goodCredit"]}, + ], + }, + cases: [ + [{customer: {age: 30, score: 700}}, {customer: {age: 30, score: 700, adult: true, goodCredit: true, approved: true}}], + [{customer: {age: 30, score: 600}}, {customer: {age: 30, score: 600, adult: true, goodCredit: false, approved: false}}], + [{customer: {age: 10, score: 800}}, {customer: {age: 10, score: 800, adult: false, goodCredit: true, approved: false}}], + ], +} + +{ + name: "assertion consumed by a match block declared before it", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {match: "customer.message", arms: [["customer.adult", "'welcome'"], ["", "'sorry'"]]}, + {assertion: "customer.adult", conditions: ["customer.age >= 18"]}, + ], + }, + cases: [ + [{customer: {age: 18}}, {customer: {age: 18, adult: true, message: "welcome"}}], + [{customer: {age: 17}}, {customer: {age: 17, adult: false, message: "sorry"}}], + ], +} + +{ + name: "assertion reads match and table outputs", + policy: { + models: {order: {amount: "number", country: "string"}}, + blocks: [ + {match: "order.region", arms: [["order.country in ['DE', 'FR', 'NL']", "'eu'"], ["", "'other'"]]}, + {table: "fees", inputs: ["order.amount"], outputs: ["order.fee"], rules: [["< 100", "5"], ["", "0"]]}, + {assertion: "order.freeEuShipping", conditions: ["order.region == 'eu'", "order.fee == 0"]}, + ], + }, + cases: [ + [{order: {amount: 200, country: "DE"}}, {order: {amount: 200, country: "DE", region: "eu", fee: 0, freeEuShipping: true}}], + [{order: {amount: 50, country: "DE"}}, {order: {amount: 50, country: "DE", region: "eu", fee: 5, freeEuShipping: false}}], + [{order: {amount: 200, country: "US"}}, {order: {amount: 200, country: "US", region: "other", fee: 0, freeEuShipping: false}}], + ], +} + +{ + name: "assertion with global scope values", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + globals: {limits: {maxAmount: "number", blocked: "string[]"}}, + models: {order: {amount: "number", country: "string"}}, + blocks: [{assertion: "order.allowed", conditions: ["order.amount <= limits.maxAmount", "not (order.country in limits.blocked)"]}], + }, + cases: [ + [ + {order: {amount: 10, country: "DE"}, limits: {maxAmount: 100, blocked: ["KP"]}}, + {order: {amount: 10, country: "DE", allowed: true}, limits: {maxAmount: 100, blocked: ["KP"]}}, + ], + [ + {order: {amount: 10, country: "KP"}, limits: {maxAmount: 100, blocked: ["KP"]}}, + {order: {amount: 10, country: "KP", allowed: false}, limits: {maxAmount: 100, blocked: ["KP"]}}, + ], + [ + {order: {amount: 1000, country: "DE"}, limits: {maxAmount: 100, blocked: []}}, + {order: {amount: 1000, country: "DE", allowed: false}, limits: {maxAmount: 100, blocked: []}}, + ], + ], +} + +{ + name: "per-instance assertion over a relationship", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", employees: "number"}}, + blocks: [ + {assertion: "company.sme", conditions: ["company.revenue < 50000000", "company.employees < 250"]}, + {assertion: "customer.allSme", conditions: ["all(customer.companies, #.sme)"]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1000, employees: 10}, {revenue: 100000000, employees: 10}]}}, + {customer: {allSme: false, companies: [{revenue: 1000, employees: 10, sme: true}, {revenue: 100000000, employees: 10, sme: false}]}}, + ], + [ + {customer: {companies: [{revenue: 1000, employees: 249}]}}, + {customer: {allSme: true, companies: [{revenue: 1000, employees: 249, sme: true}]}}, + ], + [{customer: {companies: []}}, {customer: {allSme: true, companies: []}}], + ], +} + +{ + name: "conditions over arrays and closures", + policy: { + models: {cart: {items: "number[]"}}, + blocks: [{assertion: "cart.valid", conditions: [ + "len(cart.items) > 0", + ["or", "all(cart.items, # > 0)"], + "sum(cart.items) > 1000", + ]}], + }, + cases: [ + [{cart: {items: [1, 2]}}, {cart: {items: [1, 2], valid: true}}], + [{cart: {items: [1, -2]}}, {cart: {items: [1, -2], valid: false}}], + [{cart: {items: [-1, 2000]}}, {cart: {items: [-1, 2000], valid: true}}], + [{cart: {items: []}}, {cart: {items: [], valid: false}}], + ], +} + +{ + name: "goals restrict evaluation to the requested assertion", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number", s: "string"}}, + blocks: [ + {assertion: "x.positive", conditions: ["x.n > 0"]}, + {assertion: "x.broken", conditions: ["x.s * 2 > 0"]}, + ], + }, + cases: [ + {input: {x: {n: 1, s: "a"}}, goals: ["x.positive"], output: {x: {n: 1, s: "a", positive: true}}}, + {input: {x: {n: -1, s: "a"}}, goals: ["x.positive"], output: {x: {n: -1, s: "a", positive: false}}}, + {input: {x: {n: 1, s: "a"}}, goals: ["x.broken"], output: "!error: ExpressionFailed"}, + {input: {x: {n: 1, s: "a"}}, output: "!error: ExpressionFailed"}, + ], +} + +// --------------------------------------------------------------------------- +// A realistic eligibility check. +// --------------------------------------------------------------------------- +{ + name: "loan eligibility: adult and (good score or (has collateral and low debt))", + policy: { + models: {applicant: {age: "number", score: "number", collateral: "boolean", debtRatio: "number"}}, + blocks: [{assertion: "applicant.eligible", conditions: [ + ["and", "applicant.age >= 18"], + ["or", "applicant.score >= 700", 1], + ["and", "applicant.collateral", 2], + ["and", "applicant.debtRatio < 0.4", 2], + ]}], + }, + cases: [ + [{applicant: {age: 30, score: 720, collateral: false, debtRatio: 0.9}}, {applicant: {age: 30, score: 720, collateral: false, debtRatio: 0.9, eligible: true}}], + [{applicant: {age: 30, score: 600, collateral: true, debtRatio: 0.3}}, {applicant: {age: 30, score: 600, collateral: true, debtRatio: 0.3, eligible: true}}], + [{applicant: {age: 30, score: 600, collateral: true, debtRatio: 0.4}}, {applicant: {age: 30, score: 600, collateral: true, debtRatio: 0.4, eligible: false}}], + [{applicant: {age: 30, score: 600, collateral: false, debtRatio: 0.1}}, {applicant: {age: 30, score: 600, collateral: false, debtRatio: 0.1, eligible: false}}], + [{applicant: {age: 17, score: 800, collateral: true, debtRatio: 0}}, {applicant: {age: 17, score: 800, collateral: true, debtRatio: 0, eligible: false}}], + ], +} diff --git a/core/engine/tests/spec/policy/07-tables-first.json5 b/core/engine/tests/spec/policy/07-tables-first.json5 new file mode 100644 index 00000000..29d5f0ca --- /dev/null +++ b/core/engine/tests/spec/policy/07-tables-first.json5 @@ -0,0 +1,768 @@ +// Decision table blocks with the default `first` hit policy. Each input column names a +// field; its cells are unary tests against that field (`$`). An empty cell is a wildcard. A +// column without a field takes standard boolean expressions. Every output column without +// a `[]` suffix is resolved on its own: it takes the value of the first matched row whose +// cell in that column is non-empty (later rows fill columns an earlier match left empty). +// A column no matched row resolves is written as null. Unlike graph tables, a cell or field +// that fails to evaluate fails the whole policy evaluation. + +// --------------------------------------------------------------------------- +// Basic first-hit selection. +// --------------------------------------------------------------------------- +{ + name: "first matching row wins", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "discount", inputs: ["order.amount"], outputs: ["order.discount"], rules: [ + [">= 1000", "0.15"], + [">= 500", "0.1"], + [">= 100", "0.05"], + ["", "0"], + ]}], + }, + cases: [ + [{order: {amount: 5000}}, {order: {amount: 5000, discount: 0.15}}], + [{order: {amount: 1000}}, {order: {amount: 1000, discount: 0.15}}], + [{order: {amount: 999.99}}, {order: {amount: 999.99, discount: 0.1}}], + [{order: {amount: 500}}, {order: {amount: 500, discount: 0.1}}], + [{order: {amount: 100}}, {order: {amount: 100, discount: 0.05}}], + [{order: {amount: 99}}, {order: {amount: 99, discount: 0}}], + [{order: {amount: -1}}, {order: {amount: -1, discount: 0}}], + ], +} + +{ + name: "an earlier broader row shadows later rows", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.band"], rules: [ + ["> 0", "'positive'"], + ["> 100", "'large'"], + ["", "'other'"], + ]}], + }, + cases: [ + [{order: {amount: 500}}, {order: {amount: 500, band: "positive"}}], + [{order: {amount: 1}}, {order: {amount: 1, band: "positive"}}], + [{order: {amount: 0}}, {order: {amount: 0, band: "other"}}], + ], +} + +// --------------------------------------------------------------------------- +// Wildcards and multiple input columns. +// --------------------------------------------------------------------------- +{ + name: "two input columns, wildcards in either", + policy: { + models: {order: {amount: "number", region: "string"}}, + blocks: [{table: "shipping", inputs: ["order.amount", "order.region"], outputs: ["order.shipping"], rules: [ + [">= 100", "'US'", "0"], + [">= 100", "'EU'", "5"], + ["", "'US'", "10"], + ["", "'EU'", "15"], + ["< 0", "", "-1"], + ]}], + }, + cases: [ + [{order: {amount: 200, region: "US"}}, {order: {amount: 200, region: "US", shipping: 0}}], + [{order: {amount: 200, region: "EU"}}, {order: {amount: 200, region: "EU", shipping: 5}}], + [{order: {amount: 50, region: "US"}}, {order: {amount: 50, region: "US", shipping: 10}}], + [{order: {amount: 50, region: "EU"}}, {order: {amount: 50, region: "EU", shipping: 15}}], + [{order: {amount: -5, region: "JP"}}, {order: {amount: -5, region: "JP", shipping: -1}}], + [{order: {amount: -5, region: "US"}}, {order: {amount: -5, region: "US", shipping: 10}}], + [{order: {amount: 50, region: "JP"}}, {order: {amount: 50, region: "JP", shipping: null}}], + ], +} + +{ + name: "all-wildcard row matches everything", + policy: { + models: {order: {amount: "number", region: "string"}}, + blocks: [{table: "t", inputs: ["order.amount", "order.region"], outputs: ["order.label"], rules: [ + ["", "", "'catch-all'"], + ["> 0", "'US'", "'unreachable'"], + ]}], + }, + cases: [ + [{order: {amount: 1, region: "US"}}, {order: {amount: 1, region: "US", label: "catch-all"}}], + [{order: {amount: -1, region: ""}}, {order: {amount: -1, region: "", label: "catch-all"}}], + ], +} + +{ + name: "whitespace-only cells are wildcards", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.label"], rules: [ + ["> 10", "'big'"], + [" ", "'any'"], + ]}], + }, + cases: [ + [{order: {amount: 20}}, {order: {amount: 20, label: "big"}}], + [{order: {amount: 1}}, {order: {amount: 1, label: "any"}}], + ], +} + +{ + name: "`_` input cell is an identifier read, not a wildcard", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.label"], rules: [ + ["> 10", "'big'"], + ["_", "'any'"], + ]}], + }, + cases: [ + [{order: {amount: 20}}, "!error: MissingRequiredInputs", "question: the analyzer skips `_` cells as wildcards, but at runtime `_` is a plain identifier read and the policy fails with a missing input `_`"], + ], +} + +// --------------------------------------------------------------------------- +// Unary cell forms: comparisons, ranges, lists, `$` expressions, booleans. +// --------------------------------------------------------------------------- +{ + name: "unary cell forms on a number column", + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.kind"], rules: [ + ["0", "'zero'"], + ["[1..5]", "'closed range'"], + ["(5..10)", "'open range'"], + ["10, 20, 30", "'listed'"], + ["$ > 100 and $ % 2 == 0", "'big even'"], + ["< 0", "'negative'"], + ["", "'other'"], + ]}], + }, + cases: [ + [{x: {n: 0}}, {x: {n: 0, kind: "zero"}}], + [{x: {n: 1}}, {x: {n: 1, kind: "closed range"}}], + [{x: {n: 5}}, {x: {n: 5, kind: "closed range"}}], + [{x: {n: 5.5}}, {x: {n: 5.5, kind: "open range"}}], + [{x: {n: 10}}, {x: {n: 10, kind: "listed"}}], + [{x: {n: 20}}, {x: {n: 20, kind: "listed"}}], + [{x: {n: 102}}, {x: {n: 102, kind: "big even"}}], + [{x: {n: 101}}, {x: {n: 101, kind: "other"}}], + [{x: {n: -0.5}}, {x: {n: -0.5, kind: "negative"}}], + ], +} + +{ + name: "unary cell forms on a string column", + policy: { + models: {x: {s: "string"}}, + blocks: [{table: "t", inputs: ["x.s"], outputs: ["x.kind"], rules: [ + ["'gold'", "1"], + ["'silver', 'bronze'", "2"], + ["startsWith($, 'plat')", "3"], + ["len($) == 0", "4"], + ["", "5"], + ]}], + }, + cases: [ + [{x: {s: "gold"}}, {x: {s: "gold", kind: 1}}], + [{x: {s: "silver"}}, {x: {s: "silver", kind: 2}}], + [{x: {s: "bronze"}}, {x: {s: "bronze", kind: 2}}], + [{x: {s: "platinum"}}, {x: {s: "platinum", kind: 3}}], + [{x: {s: ""}}, {x: {s: "", kind: 4}}], + [{x: {s: "Gold"}}, {x: {s: "Gold", kind: 5}}], + ], +} + +{ + name: "boolean column with a range column", + policy: { + models: {x: {b: "boolean", n: "number"}}, + blocks: [{table: "t", inputs: ["x.b", "x.n"], outputs: ["x.o"], rules: [ + ["true", "[1..5]", "1"], + ["false", "(1..5)", "2"], + ["", "", "3"], + ]}], + }, + cases: [ + [{x: {b: true, n: 1}}, {x: {b: true, n: 1, o: 1}}], + [{x: {b: true, n: 5}}, {x: {b: true, n: 5, o: 1}}], + [{x: {b: false, n: 3}}, {x: {b: false, n: 3, o: 2}}], + [{x: {b: false, n: 1}}, {x: {b: false, n: 1, o: 3}}], + [{x: {b: false, n: 5}}, {x: {b: false, n: 5, o: 3}}], + [{x: {b: true, n: 6}}, {x: {b: true, n: 6, o: 3}}], + ], +} + +// --------------------------------------------------------------------------- +// Input columns without a field and computed input fields. +// --------------------------------------------------------------------------- +{ + name: "input column without a field takes boolean expressions", + policy: { + models: {order: {amount: "number", qty: "number"}}, + blocks: [{table: "t", inputs: [null, "order.qty"], outputs: ["order.label"], rules: [ + ["order.amount * order.qty > 1000", "", "'bulk value'"], + ["order.amount > 100", "> 1", "'premium multi'"], + ["", "> 10", "'many'"], + ["", "", "'plain'"], + ]}], + }, + cases: [ + [{order: {amount: 500, qty: 3}}, {order: {amount: 500, qty: 3, label: "bulk value"}}], + [{order: {amount: 200, qty: 2}}, {order: {amount: 200, qty: 2, label: "premium multi"}}], + [{order: {amount: 200, qty: 1}}, {order: {amount: 200, qty: 1, label: "plain"}}], + [{order: {amount: 1, qty: 20}}, {order: {amount: 1, qty: 20, label: "many"}}], + ], +} + +{ + name: "fieldless cell returning a non-boolean does not match", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {order: {amount: "number", note: "string"}}, + blocks: [{table: "t", inputs: [null], outputs: ["order.label"], rules: [ + ["order.amount", "'number'"], + ["order.note", "'string'"], + ["", "'fallback'"], + ]}], + }, + cases: [ + [{order: {amount: 1, note: "x"}}, {order: {amount: 1, note: "x", label: "fallback"}}], + [{order: {amount: 0, note: ""}}, {order: {amount: 0, note: "", label: "fallback"}}], + ], +} + +{ + name: "input field is an expression, not just a path", + policy: { + models: {order: {amount: "number", qty: "number"}}, + blocks: [{table: "t", inputs: ["order.amount * order.qty"], outputs: ["order.tier"], rules: [ + [">= 1000", "'gold'"], + [">= 100", "'silver'"], + ["", "'bronze'"], + ]}], + }, + cases: [ + [{order: {amount: 100, qty: 10}}, {order: {amount: 100, qty: 10, tier: "gold"}}], + [{order: {amount: 50, qty: 2}}, {order: {amount: 50, qty: 2, tier: "silver"}}], + [{order: {amount: 1, qty: 0}}, {order: {amount: 1, qty: 0, tier: "bronze"}}], + ], +} + +{ + name: "input field reads a property computed by another block", + policy: { + models: {order: {amount: "number", qty: "number"}}, + blocks: [ + {table: "t", inputs: ["order.total"], outputs: ["order.tier"], rules: [ + [">= 1000", "'gold'"], + ["", "'standard'"], + ]}, + {expression: "order.total", value: "order.amount * order.qty"}, + ], + }, + cases: [ + [{order: {amount: 500, qty: 2}}, {order: {amount: 500, qty: 2, total: 1000, tier: "gold"}}], + [{order: {amount: 5, qty: 2}}, {order: {amount: 5, qty: 2, total: 10, tier: "standard"}}], + ], +} + +// --------------------------------------------------------------------------- +// No match: every scalar output is written as null. +// --------------------------------------------------------------------------- +{ + name: "no matching row writes null to every output", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.rate", "order.label"], rules: [ + ["> 100", "0.1", "'big'"], + ["[50..100]", "0.05", "'mid'"], + ]}], + }, + cases: [ + [{order: {amount: 150}}, {order: {amount: 150, rate: 0.1, label: "big"}}], + [{order: {amount: 50}}, {order: {amount: 50, rate: 0.05, label: "mid"}}], + [{order: {amount: 49}}, {order: {amount: 49, rate: null, label: null}}], + [{order: {amount: 0}}, {order: {amount: 0, rate: null, label: null}}], + ], +} + +{ + name: "table without rules writes null", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.rate"], rules: []}], + }, + cases: [ + [{order: {amount: 1}}, {order: {amount: 1, rate: null}}], + [{order: {amount: 1000}}, {order: {amount: 1000, rate: null}}], + ], +} + +{ + name: "table without input columns: the first row always matches", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: [], outputs: ["order.rate"], rules: [["0.2"], ["0.3"]]}], + }, + cases: [ + [{order: {amount: 1}}, {order: {amount: 1, rate: 0.2}}], + [{order: {amount: 2}}, {order: {amount: 2, rate: 0.2}}], + ], +} + +// --------------------------------------------------------------------------- +// Multiple outputs: per-column first non-empty value. +// --------------------------------------------------------------------------- +{ + name: "multiple outputs from the same row", + policy: { + models: {customer: {score: "number"}}, + blocks: [{table: "t", inputs: ["customer.score"], outputs: ["customer.tier", "customer.limit", "customer.manual"], rules: [ + [">= 750", "'prime'", "50000", "false"], + [">= 600", "'near'", "10000", "false"], + ["", "'sub'", "0", "true"], + ]}], + }, + cases: [ + [{customer: {score: 800}}, {customer: {score: 800, tier: "prime", limit: 50000, manual: false}}], + [{customer: {score: 650}}, {customer: {score: 650, tier: "near", limit: 10000, manual: false}}], + [{customer: {score: 100}}, {customer: {score: 100, tier: "sub", limit: 0, manual: true}}], + ], +} + +{ + name: "an empty output cell falls through to the next matching row for that column", + policy: { + models: {order: {amount: "number", region: "string"}}, + blocks: [{table: "t", inputs: ["order.amount", "order.region"], outputs: ["order.a", "order.b"], rules: [ + [">= 100", "'US'", "1", ""], + ["", "'US'", "2", "'x'"], + ["", "", "", "'y'"], + ]}], + }, + cases: [ + [{order: {amount: 200, region: "US"}}, {order: {amount: 200, region: "US", a: 1, b: "x"}}], + [{order: {amount: 20, region: "US"}}, {order: {amount: 20, region: "US", a: 2, b: "x"}}], + [{order: {amount: 20, region: "EU"}}, {order: {amount: 20, region: "EU", a: null, b: "y"}}], + ], +} + +{ + name: "an output column empty in every row is always null", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.a", "order.b"], rules: [ + ["> 0", "1", ""], + ["", "2", ""], + ]}], + }, + cases: [ + [{order: {amount: 1}}, {order: {amount: 1, a: 1, b: null}}], + [{order: {amount: -1}}, {order: {amount: -1, a: 2, b: null}}], + ], +} + +{ + name: "outputs to nested paths and to two entities", + diagnostics: ["MIXED_SCOPE"], + policy: { + models: {customer: {age: "number"}, offer: {base: "number"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.segment.name", "offer.price"], rules: [ + ["< 26", "'youth'", "offer.base * 0.5"], + [">= 65", "'senior'", "offer.base * 0.7"], + ["", "'standard'", "offer.base"], + ]}], + }, + cases: [ + [{customer: {age: 20}, offer: {base: 10}}, {customer: {age: 20, segment: {name: "youth"}}, offer: {base: 10, price: 5}}], + [{customer: {age: 70}, offer: {base: 10}}, {customer: {age: 70, segment: {name: "senior"}}, offer: {base: 10, price: 7}}], + [{customer: {age: 40}, offer: {base: 9.99}}, {customer: {age: 40, segment: {name: "standard"}}, offer: {base: 9.99, price: 9.99}}], + ], +} + +{ + name: "output cells of different types", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {k: "string"}}, + blocks: [{table: "t", inputs: ["x.k"], outputs: ["x.v"], rules: [ + ["'n'", "1.50"], + ["'s'", "'str'"], + ["'b'", "false"], + ["'o'", "{a: 1, b: [2]}"], + ["'a'", "[1, 'x']"], + ["'z'", "null"], + ]}], + }, + cases: [ + [{x: {k: "n"}}, {x: {k: "n", v: 1.5}}], + [{x: {k: "s"}}, {x: {k: "s", v: "str"}}], + [{x: {k: "b"}}, {x: {k: "b", v: false}}], + [{x: {k: "o"}}, {x: {k: "o", v: {a: 1, b: [2]}}}], + [{x: {k: "a"}}, {x: {k: "a", v: [1, "x"]}}], + [{x: {k: "z"}}, {x: {k: "z", v: null}}], + [{x: {k: "?"}}, {x: {k: "?", v: null}}], + ], +} + +{ + name: "a `null` output cell counts as a value: it is not a fall-through", + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.v"], rules: [ + ["> 0", "null"], + ["", "'fallback'"], + ]}], + }, + cases: [ + [{x: {n: 1}}, {x: {n: 1, v: null}}], + [{x: {n: 0}}, {x: {n: 0, v: "fallback"}}], + ], +} + +{ + name: "output cells computed from inputs", + policy: { + models: {loan: {amount: "number", years: "number"}}, + blocks: [{table: "t", inputs: ["loan.years"], outputs: ["loan.rate", "loan.interest"], rules: [ + ["<= 5", "0.03", "loan.amount * 0.03 * loan.years"], + ["", "0.05", "loan.amount * 0.05 * loan.years"], + ]}], + }, + cases: [ + [{loan: {amount: 1000, years: 2}}, {loan: {amount: 1000, years: 2, rate: 0.03, interest: 60}}], + [{loan: {amount: 1000, years: 10}}, {loan: {amount: 1000, years: 10, rate: 0.05, interest: 500}}], + [{loan: {amount: 0.1, years: 3}}, {loan: {amount: 0.1, years: 3, rate: 0.03, interest: 0.009}}], + ], +} + +{ + name: "declared output column types are not enforced at runtime", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: [{field: "x.o", type: "number"}], rules: [ + ["> 1", "'str'"], + ["", "1"], + ]}], + }, + cases: [ + [{x: {n: 3}}, {x: {n: 3, o: "str"}}, "question: the column declares `number`; the analyzer reports a TypeMismatch but evaluation writes the string anyway"], + [{x: {n: 1}}, {x: {n: 1, o: 1}}], + ], +} + +{ + name: "two output columns with the same field: later column overwrites", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", inputs: [], outputs: ["x.o", "x.o"], rules: [["1", ""], ["2", "3"]]}], + }, + cases: [ + [{x: {n: 6}}, {x: {n: 6, o: 3}}, "question: both columns target `x.o`; the first resolves to 1 from row 0, the second to 3 from row 1, and the write order decides; the analyzer may report a duplicate writer"], + ], +} + +// --------------------------------------------------------------------------- +// Laziness: rows after the deciding row are not evaluated. +// --------------------------------------------------------------------------- +{ + name: "a failing output cell in an unselected row is not evaluated", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number", s: "string"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.o"], rules: [ + ["> 0", "'ok'"], + ["", "x.s * 2"], + ]}], + }, + cases: [ + [{x: {n: 1, s: "a"}}, {x: {n: 1, s: "a", o: "ok"}}], + [{x: {n: 0, s: "a"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a failing input cell after all outputs are resolved is not evaluated", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number", s: "string"}}, + blocks: [{table: "t", inputs: [null], outputs: ["x.o"], rules: [ + ["x.n > 0", "'ok'"], + ["x.s * 2 > 0", "'bad'"], + ["", "'rest'"], + ]}], + }, + cases: [ + [{x: {n: 1, s: "a"}}, {x: {n: 1, s: "a", o: "ok"}}], + [{x: {n: 0, s: "a"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a failing input field fails the evaluation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number", s: "string"}}, + blocks: [{table: "t", inputs: ["x.s * 2"], outputs: ["x.o"], rules: [["> 1", "1"], ["", "2"]]}], + }, + cases: [ + [{x: {n: 1, s: "a"}}, "!error: ExpressionFailed"], + [{x: {n: 1, s: ""}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------- +// Null, missing and invalid inputs. +// --------------------------------------------------------------------------- +{ + name: "required input missing or of the wrong type", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.o"], rules: [["> 1", "1"], ["", "2"]]}], + }, + cases: [ + [{order: {amount: 2}}, {order: {amount: 2, o: 1}}], + [{order: {}}, "!error: MissingRequiredInputs"], + [{order: {amount: null}}, "!error: MissingRequiredInputs"], + [{order: {amount: "2"}}, "!error: InputValidationFailed"], + [{order: {amount: [2]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "optional input: null against a comparison cell fails the evaluation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number?"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.o"], rules: [ + ["> 5", "'gt'"], + ["", "'any'"], + ]}], + }, + cases: [ + [{x: {n: 6}}, {x: {n: 6, o: "gt"}}], + [{x: {n: 5}}, {x: {n: 5, o: "any"}}], + [{x: {n: null}}, "!error: ExpressionFailed", "question: graph decision tables treat a cell that fails to evaluate as no match (would give 'any'); policy tables fail the whole evaluation"], + [{x: {}}, "!error: ExpressionFailed", "question: same as null; a missing optional input reaches the cell as null"], + ], +} + +{ + name: "optional input: null-tested rows first", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number?"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.o"], rules: [ + ["null", "'none'"], + ["> 5", "'gt'"], + ["", "'any'"], + ]}], + }, + cases: [ + [{x: {n: 6}}, {x: {n: 6, o: "gt"}}], + [{x: {n: 1}}, {x: {n: 1, o: "any"}}], + [{x: {n: null}}, {x: {n: null, o: "none"}}], + [{x: {}}, {x: {o: "none"}}], + ], +} + +{ + name: "optional input: equality and list cells tolerate null", + policy: { + models: {x: {s: "string?"}}, + blocks: [{table: "t", inputs: ["x.s"], outputs: ["x.o"], rules: [ + ["'a'", "1"], + ["'b', 'c'", "2"], + ["", "3"], + ]}], + }, + cases: [ + [{x: {s: "a"}}, {x: {s: "a", o: 1}}], + [{x: {s: "c"}}, {x: {s: "c", o: 2}}], + [{x: {s: null}}, {x: {s: null, o: 3}}], + [{x: {}}, {x: {o: 3}}], + ], +} + +{ + name: "optional input: null-coalescing input field", + policy: { + models: {x: {n: "number?"}}, + blocks: [{table: "t", inputs: ["x.n ?? 0"], outputs: ["x.o"], rules: [ + ["> 5", "'gt'"], + ["", "'le'"], + ]}], + }, + cases: [ + [{x: {n: 6}}, {x: {n: 6, o: "gt"}}], + [{x: {n: null}}, {x: {n: null, o: "le"}}], + [{x: {}}, {x: {o: "le"}}], + ], +} + +// --------------------------------------------------------------------------- +// Enum and date columns. +// --------------------------------------------------------------------------- +{ + name: "enum input column covering every value", + policy: { + models: {order: {channel: "string(web|store|phone)"}}, + blocks: [{table: "t", inputs: ["order.channel"], outputs: ["order.fee"], rules: [ + ["'web'", "0"], + ["'store'", "2"], + ["'phone'", "4"], + ]}], + }, + cases: [ + [{order: {channel: "web"}}, {order: {channel: "web", fee: 0}}], + [{order: {channel: "store"}}, {order: {channel: "store", fee: 2}}], + [{order: {channel: "phone"}}, {order: {channel: "phone", fee: 4}}], + [{order: {channel: "mail"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "date input column", + policy: { + models: {contract: {start: "date"}}, + blocks: [{table: "t", inputs: ["contract.start"], outputs: ["contract.era"], rules: [ + ["< d('2020-01-01')", "'legacy'"], + ["< d('2025-01-01')", "'current'"], + ["", "'new'"], + ]}], + }, + cases: [ + [{contract: {start: date('2019-06-01')}}, {contract: {start: date('2019-06-01'), era: "legacy"}}], + [{contract: {start: date('2024-12-31')}}, {contract: {start: date('2024-12-31'), era: "current"}}], + [{contract: {start: date('2025-01-01')}}, {contract: {start: date('2025-01-01'), era: "new"}}], + ], +} + +// --------------------------------------------------------------------------- +// Interactions: per-instance tables, goals, global scope, downstream blocks. +// --------------------------------------------------------------------------- +{ + name: "table writing to a related entity runs per instance", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", country: "string"}}, + blocks: [{table: "t", inputs: ["company.revenue", "company.country"], outputs: ["company.risk"], rules: [ + ["< 10000", "", "'high'"], + ["", "'XX'", "'high'"], + ["", "", "'low'"], + ]}], + }, + cases: [ + [ + {customer: {companies: [{revenue: 5, country: "DE"}, {revenue: 50000, country: "XX"}, {revenue: 50000, country: "DE"}]}}, + {customer: {companies: [{revenue: 5, country: "DE", risk: "high"}, {revenue: 50000, country: "XX", risk: "high"}, {revenue: 50000, country: "DE", risk: "low"}]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +{ + name: "parent table reads per-instance results", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {table: "risk", inputs: ["company.revenue"], outputs: ["company.risky"], rules: [["< 100", "true"], ["", "false"]]}, + {table: "decision", inputs: ["count(customer.companies, #.risky)"], outputs: ["customer.decision"], rules: [ + ["0", "'approve'"], + ["1", "'review'"], + ["", "'reject'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 500}, {revenue: 1000}]}}, + {customer: {decision: "approve", companies: [{revenue: 500, risky: false}, {revenue: 1000, risky: false}]}}, + ], + [ + {customer: {companies: [{revenue: 50}, {revenue: 1000}]}}, + {customer: {decision: "review", companies: [{revenue: 50, risky: true}, {revenue: 1000, risky: false}]}}, + ], + [ + {customer: {companies: [{revenue: 50}, {revenue: 1}]}}, + {customer: {decision: "reject", companies: [{revenue: 50, risky: true}, {revenue: 1, risky: true}]}}, + ], + ], +} + +{ + name: "table reads global scope", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + globals: {config: {threshold: "number"}}, + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: [null], outputs: ["order.review"], rules: [ + ["order.amount > config.threshold", "true"], + ["", "false"], + ]}], + }, + cases: [ + [{order: {amount: 200}, config: {threshold: 100}}, {order: {amount: 200, review: true}, config: {threshold: 100}}], + [{order: {amount: 50}, config: {threshold: 100}}, {order: {amount: 50, review: false}, config: {threshold: 100}}], + ], +} + +{ + name: "goals select one output column of a table", + policy: { + models: {customer: {score: "number"}}, + blocks: [{table: "t", inputs: ["customer.score"], outputs: ["customer.tier", "customer.limit"], rules: [ + [">= 700", "'A'", "1000"], + ["", "'B'", "100"], + ]}], + }, + cases: [ + {input: {customer: {score: 800}}, goals: ["customer.tier"], output: {customer: {score: 800, tier: "A", limit: 1000}}}, + {input: {customer: {score: 1}}, goals: ["customer.limit"], output: {customer: {score: 1, tier: "B", limit: 100}}}, + {input: {customer: {score: 1}}, output: {customer: {score: 1, tier: "B", limit: 100}}}, + ], +} + +{ + name: "match block consumes a table output", + policy: { + models: {customer: {score: "number"}}, + blocks: [ + {table: "t", inputs: ["customer.score"], outputs: ["customer.band"], rules: [[">= 700", "'A'"], [">= 500", "'B'"]]}, + {match: "customer.message", arms: [["customer.band == 'A'", "'top'"], ["customer.band == null", "'unrated'"], ["", "'ok'"]]}, + ], + }, + cases: [ + [{customer: {score: 800}}, {customer: {score: 800, band: "A", message: "top"}}], + [{customer: {score: 600}}, {customer: {score: 600, band: "B", message: "ok"}}], + [{customer: {score: 100}}, {customer: {score: 100, band: null, message: "unrated"}}], + ], +} + +// --------------------------------------------------------------------------- +// A realistic pricing table. +// --------------------------------------------------------------------------- +{ + name: "insurance premium table", + policy: { + models: {driver: {age: "number", accidents: "number", vehicle: "string(car|van|bike)"}}, + blocks: [{table: "premium", inputs: ["driver.vehicle", "driver.age", "driver.accidents"], outputs: ["driver.base", "driver.surcharge", "driver.decline"], rules: [ + ["", "< 18", "", "", "", "true"], + ["", "", "> 3", "", "", "true"], + ["'bike'", "< 25", "", "900", "", ""], + ["'bike'", "", "", "500", "", ""], + ["", "< 25", "", "1200", "", ""], + ["", "", "[1..3]", "", "200 * driver.accidents", ""], + ["'van'", "", "", "800", "", ""], + ["", "", "", "600", "0", "false"], + ]}], + }, + cases: [ + [{driver: {age: 17, accidents: 0, vehicle: "car"}}, {driver: {age: 17, accidents: 0, vehicle: "car", base: 1200, surcharge: 0, decline: true}}], + [{driver: {age: 40, accidents: 5, vehicle: "car"}}, {driver: {age: 40, accidents: 5, vehicle: "car", base: 600, surcharge: 0, decline: true}}], + [{driver: {age: 20, accidents: 0, vehicle: "bike"}}, {driver: {age: 20, accidents: 0, vehicle: "bike", base: 900, surcharge: 0, decline: false}}], + [{driver: {age: 40, accidents: 2, vehicle: "bike"}}, {driver: {age: 40, accidents: 2, vehicle: "bike", base: 500, surcharge: 400, decline: false}}], + [{driver: {age: 40, accidents: 1, vehicle: "van"}}, {driver: {age: 40, accidents: 1, vehicle: "van", base: 800, surcharge: 200, decline: false}}], + [{driver: {age: 40, accidents: 0, vehicle: "car"}}, {driver: {age: 40, accidents: 0, vehicle: "car", base: 600, surcharge: 0, decline: false}}], + ], +} diff --git a/core/engine/tests/spec/policy/08-tables-collect.json5 b/core/engine/tests/spec/policy/08-tables-collect.json5 new file mode 100644 index 00000000..910fe001 --- /dev/null +++ b/core/engine/tests/spec/policy/08-tables-collect.json5 @@ -0,0 +1,563 @@ +// Collecting decision tables. An output column collects when its field ends in `[]`, or +// when the table's hit policy is `collect` (then every column collects and a `[]` suffix +// is redundant). A collecting column gathers the values of its non-empty cells over ALL +// matched rows, in row order, into an array; with no match it is written as `[]`. Columns +// collect independently, so arrays from one table can differ in length. Scalar columns in +// the same table keep first-hit semantics (first matched row with a non-empty cell, else +// null). + +// --------------------------------------------------------------------------- +// Hit policy `collect`. +// --------------------------------------------------------------------------- +{ + name: "collect gathers every matching row in order", + policy: { + models: {customer: {age: "number"}}, + blocks: [{table: "tags", hit: "collect", inputs: ["customer.age"], outputs: ["customer.tags"], rules: [ + [">= 65", "'senior'"], + [">= 18", "'adult'"], + ["", "'person'"], + ]}], + }, + cases: [ + [{customer: {age: 70}}, {customer: {age: 70, tags: ["senior", "adult", "person"]}}], + [{customer: {age: 65}}, {customer: {age: 65, tags: ["senior", "adult", "person"]}}], + [{customer: {age: 30}}, {customer: {age: 30, tags: ["adult", "person"]}}], + [{customer: {age: 5}}, {customer: {age: 5, tags: ["person"]}}], + ], +} + +{ + name: "collect with no match writes an empty array", + policy: { + models: {customer: {age: "number"}}, + blocks: [{table: "tags", hit: "collect", inputs: ["customer.age"], outputs: ["customer.tags"], rules: [ + [">= 65", "'senior'"], + ["< 18", "'minor'"], + ]}], + }, + cases: [ + [{customer: {age: 70}}, {customer: {age: 70, tags: ["senior"]}}], + [{customer: {age: 10}}, {customer: {age: 10, tags: ["minor"]}}], + [{customer: {age: 30}}, {customer: {age: 30, tags: []}}], + ], +} + +{ + name: "collect table without rules writes empty arrays", + policy: { + models: {customer: {age: "number"}}, + blocks: [{table: "tags", hit: "collect", inputs: ["customer.age"], outputs: ["customer.a", "customer.b"], rules: []}], + }, + cases: [ + [{customer: {age: 1}}, {customer: {age: 1, a: [], b: []}}], + [{customer: {age: 100}}, {customer: {age: 100, a: [], b: []}}], + ], +} + +{ + name: "collect keeps duplicate values", + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: ["x.n"], outputs: ["x.out"], rules: [ + ["> 0", "'pos'"], + ["> 10", "'pos'"], + ["> 100", "'pos'"], + ]}], + }, + cases: [ + [{x: {n: 500}}, {x: {n: 500, out: ["pos", "pos", "pos"]}}], + [{x: {n: 50}}, {x: {n: 50, out: ["pos", "pos"]}}], + [{x: {n: 0}}, {x: {n: 0, out: []}}], + ], +} + +{ + name: "collect with several output columns: each column gathers its own non-empty cells", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: ["order.amount"], outputs: ["order.labels", "order.codes"], rules: [ + [">= 100", "'big'", "1"], + [">= 10", "'mid'", ""], + ["", "", "3"], + ]}], + }, + cases: [ + [{order: {amount: 200}}, {order: {amount: 200, labels: ["big", "mid"], codes: [1, 3]}}], + [{order: {amount: 50}}, {order: {amount: 50, labels: ["mid"], codes: [3]}}], + [{order: {amount: 5}}, {order: {amount: 5, labels: [], codes: [3]}}], + ], +} + +{ + name: "`[]` suffix under hit policy collect is redundant", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: ["order.amount"], outputs: ["order.a[]", "order.b"], rules: [ + ["> 0", "1", "'x'"], + ["> 5", "2", "'y'"], + ]}], + }, + cases: [ + [{order: {amount: 10}}, {order: {amount: 10, a: [1, 2], b: ["x", "y"]}}], + [{order: {amount: 1}}, {order: {amount: 1, a: [1], b: ["x"]}}], + [{order: {amount: 0}}, {order: {amount: 0, a: [], b: []}}], + ], +} + +// --------------------------------------------------------------------------- +// Collected value types. +// --------------------------------------------------------------------------- +{ + name: "collected values of mixed types", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: ["x.n"], outputs: ["x.out"], rules: [ + ["> 0", "1"], + ["> 0", "'two'"], + ["> 0", "true"], + ["> 0", "{k: 4}"], + ["> 0", "[5, 6]"], + ["> 0", "null"], + ]}], + }, + cases: [ + [{x: {n: 1}}, {x: {n: 1, out: [1, "two", true, {k: 4}, [5, 6], null]}}], + [{x: {n: 0}}, {x: {n: 0, out: []}}], + ], +} + +{ + name: "collected cells computed from inputs", + policy: { + models: {order: {amount: "number", qty: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: ["order.qty"], outputs: ["order.fees"], rules: [ + ["> 0", "order.amount * 0.01"], + ["> 10", "order.qty * 0.5"], + ["> 100", "order.amount + order.qty"], + ]}], + }, + cases: [ + [{order: {amount: 1000, qty: 200}}, {order: {amount: 1000, qty: 200, fees: [10, 100, 1200]}}], + [{order: {amount: 0.3, qty: 11}}, {order: {amount: 0.3, qty: 11, fees: [0.003, 5.5]}}], + [{order: {amount: 100, qty: 1}}, {order: {amount: 100, qty: 1, fees: [1]}}], + ], +} + +{ + name: "collect builds an array of objects", + policy: { + models: {applicant: {income: "number", debt: "number"}}, + blocks: [{table: "reasons", hit: "collect", inputs: ["applicant.income", "applicant.debt"], outputs: ["applicant.reasons"], rules: [ + ["< 20000", "", "{code: 'LOW_INCOME', weight: 3}"], + ["", "> 50000", "{code: 'HIGH_DEBT', weight: 2}"], + ["", "> applicant.income", "{code: 'DEBT_OVER_INCOME', weight: 5}"], + ]}], + }, + cases: [ + [ + {applicant: {income: 10000, debt: 60000}}, + {applicant: {income: 10000, debt: 60000, reasons: [{code: "LOW_INCOME", weight: 3}, {code: "HIGH_DEBT", weight: 2}, {code: "DEBT_OVER_INCOME", weight: 5}]}}, + ], + [{applicant: {income: 90000, debt: 1000}}, {applicant: {income: 90000, debt: 1000, reasons: []}}], + [ + {applicant: {income: 30000, debt: 40000}}, + {applicant: {income: 30000, debt: 40000, reasons: [{code: "DEBT_OVER_INCOME", weight: 5}]}}, + ], + ], +} + +{ + name: "collect table without input columns: every row matches", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: [], outputs: ["x.all"], rules: [["x.n"], ["x.n * 2"], ["'c'"]]}], + }, + cases: [ + [{x: {n: 1}}, {x: {n: 1, all: [1, 2, "c"]}}], + [{x: {n: 0}}, {x: {n: 0, all: [0, 0, "c"]}}], + [{x: {n: -2.5}}, {x: {n: -2.5, all: [-2.5, -5, "c"]}}], + ], +} + +{ + name: "collect over string list cells and two inputs", + policy: { + models: {item: {category: "string", price: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: ["item.category", "item.price"], outputs: ["item.labels"], rules: [ + ["'food', 'drink'", "", "'consumable'"], + ["'drink'", "", "'liquid'"], + ["", "> 100", "'expensive'"], + ["", "[0..1]", "'cheap'"], + ["'tool'", "> 100", "'pro tool'"], + ]}], + }, + cases: [ + [{item: {category: "drink", price: 1}}, {item: {category: "drink", price: 1, labels: ["consumable", "liquid", "cheap"]}}], + [{item: {category: "food", price: 50}}, {item: {category: "food", price: 50, labels: ["consumable"]}}], + [{item: {category: "tool", price: 500}}, {item: {category: "tool", price: 500, labels: ["expensive", "pro tool"]}}], + [{item: {category: "toy", price: 0}}, {item: {category: "toy", price: 0, labels: ["cheap"]}}], + [{item: {category: "", price: 50}}, {item: {category: "", price: 50, labels: []}}], + ], +} + +{ + name: "collect with boolean and enum inputs", + policy: { + models: {user: {verified: "boolean", plan: "string(free|pro|team)"}}, + blocks: [{table: "t", inputs: ["user.verified", "user.plan"], outputs: ["user.features[]"], rules: [ + ["", "", "'basic'"], + ["true", "", "'export'"], + ["", "'pro', 'team'", "'api'"], + ["true", "'team'", "'sso'"], + ]}], + }, + cases: [ + [{user: {verified: false, plan: "free"}}, {user: {verified: false, plan: "free", features: ["basic"]}}], + [{user: {verified: true, plan: "free"}}, {user: {verified: true, plan: "free", features: ["basic", "export"]}}], + [{user: {verified: false, plan: "pro"}}, {user: {verified: false, plan: "pro", features: ["basic", "api"]}}], + [{user: {verified: true, plan: "team"}}, {user: {verified: true, plan: "team", features: ["basic", "export", "api", "sso"]}}], + [{user: {verified: true, plan: "enterprise"}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------- +// Per-column collect `[]` in a first-hit table: mixed collect and first columns. +// --------------------------------------------------------------------------- +{ + name: "`tags[]` collects while scalar columns take the first hit", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.tags[]", "order.tier"], rules: [ + [">= 100", "'big'", "'gold'"], + [">= 10", "'mid'", "'silver'"], + ["< 0", "'neg'", "'none'"], + ["", "'any'", "'bronze'"], + ]}], + }, + cases: [ + [{order: {amount: 200}}, {order: {amount: 200, tags: ["big", "mid", "any"], tier: "gold"}}], + [{order: {amount: 50}}, {order: {amount: 50, tags: ["mid", "any"], tier: "silver"}}], + [{order: {amount: 5}}, {order: {amount: 5, tags: ["any"], tier: "bronze"}}], + [{order: {amount: -5}}, {order: {amount: -5, tags: ["neg", "any"], tier: "none"}}], + ], +} + +{ + name: "mixed table with no match: collect column is empty, scalar column is null", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.tags[]", "order.first"], rules: [ + [">= 100", "'big'", "1"], + [">= 10", "'mid'", "2"], + ]}], + }, + cases: [ + [{order: {amount: 100}}, {order: {amount: 100, tags: ["big", "mid"], first: 1}}], + [{order: {amount: 10}}, {order: {amount: 10, tags: ["mid"], first: 2}}], + [{order: {amount: 9}}, {order: {amount: 9, tags: [], first: null}}], + ], +} + +{ + name: "scalar column falls through empty cells while collect gathers everything", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.flags[]", "order.rate"], rules: [ + ["> 1000", "'review'", ""], + ["> 100", "", "0.1"], + ["> 0", "'small-ok'", "0.2"], + ]}], + }, + cases: [ + [{order: {amount: 5000}}, {order: {amount: 5000, flags: ["review", "small-ok"], rate: 0.1}}], + [{order: {amount: 500}}, {order: {amount: 500, flags: ["small-ok"], rate: 0.1}}], + [{order: {amount: 5}}, {order: {amount: 5, flags: ["small-ok"], rate: 0.2}}], + [{order: {amount: 0}}, {order: {amount: 0, flags: [], rate: null}}], + ], +} + +{ + name: "several collect columns and several scalar columns", + policy: { + models: {claim: {amount: "number", type: "string(auto|home|life)"}}, + blocks: [{table: "t", inputs: ["claim.type", "claim.amount"], outputs: ["claim.checks[]", "claim.handler", "claim.docs[]", "claim.priority"], rules: [ + ["", "> 10000", "'fraud'", "'senior'", "'invoice'", "1"], + ["'auto'", "", "'police report'", "'motor'", "'photos'", ""], + ["'home'", "", "", "'property'", "'deed'", ""], + ["", "", "'identity'", "'general'", "", "3"], + ]}], + }, + cases: [ + [ + {claim: {type: "auto", amount: 20000}}, + {claim: {type: "auto", amount: 20000, checks: ["fraud", "police report", "identity"], handler: "senior", docs: ["invoice", "photos"], priority: 1}}, + ], + [ + {claim: {type: "auto", amount: 500}}, + {claim: {type: "auto", amount: 500, checks: ["police report", "identity"], handler: "motor", docs: ["photos"], priority: 3}}, + ], + [ + {claim: {type: "home", amount: 500}}, + {claim: {type: "home", amount: 500, checks: ["identity"], handler: "property", docs: ["deed"], priority: 3}}, + ], + [ + {claim: {type: "life", amount: 500}}, + {claim: {type: "life", amount: 500, checks: ["identity"], handler: "general", docs: [], priority: 3}}, + ], + ], +} + +{ + name: "collect column on a nested path", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.meta.notes[]", "order.meta.level"], rules: [ + ["> 10", "'a'", "2"], + ["> 0", "'b'", "1"], + ]}], + }, + cases: [ + [{order: {amount: 11}}, {order: {amount: 11, meta: {notes: ["a", "b"], level: 2}}}], + [{order: {amount: 1}}, {order: {amount: 1, meta: {notes: ["b"], level: 1}}}], + [{order: {amount: 0}}, {order: {amount: 0, meta: {notes: [], level: null}}}], + ], +} + +{ + name: "whitespace before the `[]` marker is ignored", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.tags []", " order.tier "], rules: [ + ["> 10", "'a'", "1"], + ["> 0", "'b'", "2"], + ]}], + }, + cases: [ + [{order: {amount: 11}}, {order: {amount: 11, tags: ["a", "b"], tier: 1}}], + [{order: {amount: 0}}, {order: {amount: 0, tags: [], tier: null}}], + ], +} + +{ + name: "a misplaced `[]` marker drops the column", + diagnostics: ["INVALID_WRITE_PATH"], + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.items[].tag", "order.tier"], rules: [ + ["> 10", "'a'", "1"], + ["", "'b'", "2"], + ]}], + }, + cases: [ + [{order: {amount: 11}}, {order: {amount: 11, tier: 1}}], + [{order: {amount: 0}}, {order: {amount: 0, tier: 2}}], + ], +} + +{ + name: "a bare `[]` output field drops the column", + diagnostics: ["INVALID_WRITE_PATH"], + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["[]", "order.tier"], rules: [ + ["> 10", "'a'", "1"], + ["", "'b'", "2"], + ]}], + }, + cases: [ + [{order: {amount: 11}}, {order: {amount: 11, tier: 1}}], + [{order: {amount: 0}}, {order: {amount: 0, tier: 2}}], + ], +} + +{ + name: "two collect columns on the same field merge row by row", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.tags[]", "x.tags[]"], rules: [ + ["> 0", "'a1'", "'b1'"], + ["> 1", "'a2'", "'b2'"], + ]}], + }, + cases: [ + [{x: {n: 5}}, {x: {n: 5, tags: ["a1", "b1", "a2", "b2"]}}, "question: both columns write `x.tags`; values interleave row by row in one array, where a duplicate-writer error might be expected"], + [{x: {n: 1}}, {x: {n: 1, tags: ["a1", "b1"]}}], + [{x: {n: 0}}, {x: {n: 0, tags: []}}], + ], +} + +// --------------------------------------------------------------------------- +// Laziness and errors: collecting evaluates every row. +// --------------------------------------------------------------------------- +{ + name: "a failing cell in a later matched row fails a collect table", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number", s: "string"}}, + blocks: [{table: "t", hit: "collect", inputs: ["x.n"], outputs: ["x.out"], rules: [ + ["> 0", "'ok'"], + ["> 10", "x.s * 2"], + ]}], + }, + cases: [ + [{x: {n: 5, s: "a"}}, {x: {n: 5, s: "a", out: ["ok"]}}], + [{x: {n: 50, s: "a"}}, "!error: ExpressionFailed"], + [{x: {n: 0, s: "a"}}, {x: {n: 0, s: "a", out: []}}], + ], +} + +{ + name: "a failing input cell anywhere fails a table with a collect column", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number", s: "string"}}, + blocks: [{table: "t", inputs: [null], outputs: ["x.tags[]", "x.first"], rules: [ + ["x.n > 0", "'pos'", "1"], + ["x.s * 2 > 0", "'bad'", "2"], + ]}], + }, + cases: [ + [{x: {n: 1, s: "a"}}, "!error: ExpressionFailed"], + [{x: {n: 0, s: "a"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a failing cell in an unmatched row is not evaluated", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {n: "number", s: "string"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.tags[]"], rules: [ + ["> 0", "'pos'"], + ["< 0", "x.s * 2"], + ["", "'any'"], + ]}], + }, + cases: [ + [{x: {n: 1, s: "a"}}, {x: {n: 1, s: "a", tags: ["pos", "any"]}}], + [{x: {n: 0, s: "a"}}, {x: {n: 0, s: "a", tags: ["any"]}}], + [{x: {n: -1, s: "a"}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------- +// Null and missing inputs. +// --------------------------------------------------------------------------- +{ + name: "optional input in a collect table", + policy: { + models: {x: {s: "string?"}}, + blocks: [{table: "t", hit: "collect", inputs: ["x.s"], outputs: ["x.out"], rules: [ + ["'a'", "1"], + ["null", "2"], + ["", "3"], + ]}], + }, + cases: [ + [{x: {s: "a"}}, {x: {s: "a", out: [1, 3]}}], + [{x: {s: "b"}}, {x: {s: "b", out: [3]}}], + [{x: {s: null}}, {x: {s: null, out: [2, 3]}}], + [{x: {}}, {x: {out: [2, 3]}}], + ], +} + +{ + name: "required input missing in a collect table", + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: ["x.n"], outputs: ["x.out"], rules: [["> 0", "1"], ["", "2"]]}], + }, + cases: [ + [{x: {n: 1}}, {x: {n: 1, out: [1, 2]}}], + [{x: {}}, "!error: MissingRequiredInputs"], + [{x: {n: "1"}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------- +// Interactions: downstream blocks, per-instance collect, goals. +// --------------------------------------------------------------------------- +{ + name: "downstream blocks read the collected array", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {table: "flags", inputs: ["customer.age", "customer.income"], outputs: ["customer.flags[]"], rules: [ + ["< 18", "", "'minor'"], + ["", "< 1000", "'low income'"], + ["> 90", "", "'elderly'"], + ]}, + {expression: "customer.flagCount", value: "len(customer.flags)"}, + {assertion: "customer.clean", conditions: ["len(customer.flags) == 0"]}, + {match: "customer.route", arms: [ + ["'minor' in customer.flags", "'guardian'"], + ["customer.flagCount > 0", "'manual'"], + ["", "'auto'"], + ]}, + ], + }, + cases: [ + [{customer: {age: 30, income: 5000}}, {customer: {age: 30, income: 5000, flags: [], flagCount: 0, clean: true, route: "auto"}}], + [{customer: {age: 16, income: 0}}, {customer: {age: 16, income: 0, flags: ["minor", "low income"], flagCount: 2, clean: false, route: "guardian"}}], + [{customer: {age: 95, income: 5000}}, {customer: {age: 95, income: 5000, flags: ["elderly"], flagCount: 1, clean: false, route: "manual"}}], + ], +} + +{ + name: "per-instance collect over a relationship", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", country: "string"}}, + blocks: [ + {table: "t", inputs: ["company.revenue", "company.country"], outputs: ["company.warnings[]", "company.score"], rules: [ + ["< 1000", "", "'small'", "1"], + ["", "'XX'", "'sanctioned'", "0"], + ["", "", "", "5"], + ]}, + {expression: "customer.warningCount", value: "sum(map(customer.companies, len(#.warnings)))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10, country: "XX"}, {revenue: 5000, country: "DE"}]}}, + {customer: {warningCount: 2, companies: [{revenue: 10, country: "XX", warnings: ["small", "sanctioned"], score: 1}, {revenue: 5000, country: "DE", warnings: [], score: 5}]}}, + ], + [{customer: {companies: []}}, {customer: {warningCount: 0, companies: []}}], + ], +} + +{ + name: "collect table reading global scope", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + globals: {rules: {limit: "number"}}, + models: {order: {amount: "number"}}, + blocks: [{table: "t", hit: "collect", inputs: [null], outputs: ["order.alerts"], rules: [ + ["order.amount > rules.limit", "'over limit'"], + ["order.amount > rules.limit * 2", "'way over limit'"], + ]}], + }, + cases: [ + [{order: {amount: 300}, rules: {limit: 100}}, {order: {amount: 300, alerts: ["over limit", "way over limit"]}, rules: {limit: 100}}], + [{order: {amount: 150}, rules: {limit: 100}}, {order: {amount: 150, alerts: ["over limit"]}, rules: {limit: 100}}], + [{order: {amount: 50}, rules: {limit: 100}}, {order: {amount: 50, alerts: []}, rules: {limit: 100}}], + ], +} + +{ + name: "goals on a mixed table", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.tags[]", "order.tier"], rules: [ + ["> 10", "'a'", "1"], + ["", "'b'", "2"], + ]}], + }, + cases: [ + {input: {order: {amount: 11}}, goals: ["order.tags"], output: {order: {amount: 11, tags: ["a", "b"], tier: 1}}}, + {input: {order: {amount: 1}}, goals: ["order.tier"], output: {order: {amount: 1, tags: ["b"], tier: 2}}}, + ], +} diff --git a/core/engine/tests/spec/policy/09-relationships.json5 b/core/engine/tests/spec/policy/09-relationships.json5 new file mode 100644 index 00000000..b8b24ccc --- /dev/null +++ b/core/engine/tests/spec/policy/09-relationships.json5 @@ -0,0 +1,795 @@ +// Relationship properties: an entity property whose type names another entity. Array +// relationships (`company[]`) make every block keyed on the target entity run once per member, +// writing into that member. Single relationships (`creditReport`) nest one object. Computed +// properties stay undeclared in the data model (declared properties are inputs, see the last +// section). + +// Per-member expression blocks: one evaluation per array member, written into the member. +{ + name: "per-member expression writes into every member", + policy: { + models: {customer: {name: "string", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + cases: [ + [ + {customer: {name: "a", companies: [{revenue: 50}, {revenue: 200}]}}, + {customer: {name: "a", companies: [{revenue: 50, big: false}, {revenue: 200, big: true}]}}, + ], + [{customer: {name: "b", companies: [{revenue: 101}]}}, {customer: {name: "b", companies: [{revenue: 101, big: true}]}}], + [{customer: {name: "c", companies: []}}, {customer: {name: "c", companies: []}}], + [ + {customer: {name: "d", companies: [{revenue: 100}, {revenue: 100.5}, {revenue: -1}, {revenue: 0}]}}, + {customer: {name: "d", companies: [{revenue: 100, big: false}, {revenue: 100.5, big: true}, {revenue: -1, big: false}, {revenue: 0, big: false}]}}, + ], + ], +} + +// Per-member blocks keep the member's other fields, declared or not. +{ + name: "per-member write keeps unknown member fields", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.double", value: "company.revenue * 2"}], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1, extra: "x", nested: {a: 1}}]}}, + {customer: {companies: [{revenue: 1, extra: "x", nested: {a: 1}, double: 2}]}}, + ], + [ + {customer: {companies: [{revenue: 2.5, tags: []}, {revenue: 0}]}}, + {customer: {companies: [{revenue: 2.5, tags: [], double: 5}, {revenue: 0, double: 0}]}}, + ], + ], +} + +// Several per-member blocks chain inside one member. +{ + name: "per-member blocks chain within a member", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", cost: "number"}}, + blocks: [ + {expression: "company.margin", value: "company.revenue - company.cost"}, + {expression: "company.profitable", value: "company.margin > 0"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10, cost: 4}, {revenue: 3, cost: 5}]}}, + {customer: {companies: [{revenue: 10, cost: 4, margin: 6, profitable: true}, {revenue: 3, cost: 5, margin: -2, profitable: false}]}}, + ], + [{customer: {companies: [{revenue: 1, cost: 1}]}}, {customer: {companies: [{revenue: 1, cost: 1, margin: 0, profitable: false}]}}], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +// Per-member match: the arm is chosen per member. +{ + name: "per-member match picks an arm per member", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{match: "company.tier", arms: [["company.revenue >= 100", "'gold'"], ["company.revenue >= 10", "'silver'"], ["", "'basic'"]]}], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1}, {revenue: 300}, {revenue: 50}]}}, + {customer: {companies: [{revenue: 1, tier: "basic"}, {revenue: 300, tier: "gold"}, {revenue: 50, tier: "silver"}]}}, + ], + [{customer: {companies: [{revenue: 100}]}}, {customer: {companies: [{revenue: 100, tier: "gold"}]}}], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +// Per-member decision table: one table evaluation per member. +{ + name: "per-member table writes per member", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", country: "string"}}, + blocks: [ + {table: "t", inputs: ["company.revenue", "company.country"], outputs: ["company.flag"], rules: [ + ["> 10", "'US'", "'us-hi'"], + ["> 10", "", "'hi'"], + ["", "", "'lo'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1, country: "US"}, {revenue: 300, country: "US"}, {revenue: 50, country: "DE"}]}}, + {customer: {companies: [{revenue: 1, country: "US", flag: "lo"}, {revenue: 300, country: "US", flag: "us-hi"}, {revenue: 50, country: "DE", flag: "hi"}]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + [{customer: {companies: [{revenue: 11, country: "FR"}]}}, {customer: {companies: [{revenue: 11, country: "FR", flag: "hi"}]}}], + ], +} + +// Aggregates over raw member fields: sum/count/filter/map on the relationship array. +{ + name: "aggregates over member input fields", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", name: "string"}}, + blocks: [ + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}, + {expression: "customer.count", value: "len(customer.companies)"}, + {expression: "customer.names", value: "map(customer.companies, #.name)"}, + {expression: "customer.bigNames", value: "map(filter(customer.companies, #.revenue > 100), #.name)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 50, name: "a"}, {revenue: 200, name: "b"}]}}, + {customer: {companies: [{revenue: 50, name: "a"}, {revenue: 200, name: "b"}], total: 250, count: 2, names: ["a", "b"], bigNames: ["b"]}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], total: 0, count: 0, names: [], bigNames: []}}], + [ + {customer: {companies: [{revenue: 0.1, name: "x"}, {revenue: 0.2, name: "y"}, {revenue: 101, name: "z"}]}}, + {customer: {companies: [{revenue: 0.1, name: "x"}, {revenue: 0.2, name: "y"}, {revenue: 101, name: "z"}], total: 101.3, count: 3, names: ["x", "y", "z"], bigNames: ["z"]}}, + ], + ], +} + +// Closures with a named alias over relationship members. +{ + name: "aliased closures over members", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.total", value: "sum(map(customer.companies as c, c.revenue))"}, + {expression: "customer.anyBig", value: "some(customer.companies as c, c.revenue > 100)"}, + {expression: "customer.allPositive", value: "all(customer.companies as c, c.revenue > 0)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 50}, {revenue: 200}]}}, + {customer: {companies: [{revenue: 50}, {revenue: 200}], total: 250, anyBig: true, allPositive: true}}, + ], + [{customer: {companies: [{revenue: -1}]}}, {customer: {companies: [{revenue: -1}], total: -1, anyBig: false, allPositive: false}}], + [{customer: {companies: []}}, {customer: {companies: [], total: 0, anyBig: false, allPositive: true}}], + ], +} + +// Aggregates over computed member properties: the per-member blocks run before the parent reads them. +{ + name: "aggregates over computed member properties", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", name: "string"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "company.fee", value: "company.revenue * 0.1"}, + {expression: "customer.bigCount", value: "count(customer.companies, #.big)"}, + {expression: "customer.fees", value: "sum(map(customer.companies, #.fee))"}, + {expression: "customer.bigNames", value: "map(filter(customer.companies, #.big), #.name)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 50, name: "a"}, {revenue: 200, name: "b"}]}}, + {customer: { + companies: [{revenue: 50, name: "a", big: false, fee: 5}, {revenue: 200, name: "b", big: true, fee: 20}], + bigCount: 1, fees: 25, bigNames: ["b"], + }}, + ], + [{customer: {companies: []}}, {customer: {companies: [], bigCount: 0, fees: 0, bigNames: []}}], + [ + {customer: {companies: [{revenue: 1000, name: "x"}, {revenue: 101, name: "y"}]}}, + {customer: { + companies: [{revenue: 1000, name: "x", big: true, fee: 100}, {revenue: 101, name: "y", big: true, fee: 10.1}], + bigCount: 2, fees: 110.1, bigNames: ["x", "y"], + }}, + ], + ], +} + +// A table on the parent reads an aggregate of computed member properties. +{ + name: "parent table reads aggregated member computeds", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {match: "company.risk", arms: [["company.revenue < 100", "'high'"], ["", "'low'"]]}, + {expression: "customer.highRisk", value: "count(customer.companies, #.risk == 'high')"}, + {table: "t", inputs: ["customer.highRisk"], outputs: ["customer.decision"], rules: [ + ["0", "'approve'"], + ["1", "'review'"], + ["", "'decline'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 500}, {revenue: 300}]}}, + {customer: {companies: [{revenue: 500, risk: "low"}, {revenue: 300, risk: "low"}], highRisk: 0, decision: "approve"}}, + ], + [ + {customer: {companies: [{revenue: 5}, {revenue: 300}]}}, + {customer: {companies: [{revenue: 5, risk: "high"}, {revenue: 300, risk: "low"}], highRisk: 1, decision: "review"}}, + ], + [ + {customer: {companies: [{revenue: 5}, {revenue: 3}]}}, + {customer: {companies: [{revenue: 5, risk: "high"}, {revenue: 3, risk: "high"}], highRisk: 2, decision: "decline"}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], highRisk: 0, decision: "approve"}}], + ], +} + +// Aggregates that have no neutral element on an empty array. +{ + name: "max, min and avg over members", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.maxRevenue", value: "max(map(customer.companies, #.revenue))"}, + {expression: "customer.minRevenue", value: "min(map(customer.companies, #.revenue))"}, + {expression: "customer.avgRevenue", value: "avg(map(customer.companies, #.revenue))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 50}, {revenue: 200}, {revenue: 20}]}}, + {customer: {companies: [{revenue: 50}, {revenue: 200}, {revenue: 20}], maxRevenue: 200, minRevenue: 20, avgRevenue: 90}}, + ], + [ + {customer: {companies: [{revenue: 7}]}}, + {customer: {companies: [{revenue: 7}], maxRevenue: 7, minRevenue: 7, avgRevenue: 7}}, + ], + ], +} + +// Members read properties of the owning entity (parent scope). +{ + name: "member reads a parent input property", + policy: { + models: {customer: {rate: "number", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.fee", value: "company.revenue * customer.rate"}], + }, + cases: [ + [ + {customer: {rate: 2, companies: [{revenue: 3}, {revenue: 4}]}}, + {customer: {rate: 2, companies: [{revenue: 3, fee: 6}, {revenue: 4, fee: 8}]}}, + ], + [{customer: {rate: 0.5, companies: [{revenue: 3}]}}, {customer: {rate: 0.5, companies: [{revenue: 3, fee: 1.5}]}}], + [{customer: {rate: 2, companies: []}}, {customer: {rate: 2, companies: []}}], + ], +} + +// Members read a computed parent property, which itself aggregates over the members. +{ + name: "member share of a parent aggregate", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}, + {expression: "company.share", value: "company.revenue / customer.total"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1}, {revenue: 3}]}}, + {customer: {companies: [{revenue: 1, share: 0.25}, {revenue: 3, share: 0.75}], total: 4}}, + ], + [{customer: {companies: [{revenue: 5}]}}, {customer: {companies: [{revenue: 5, share: 1}], total: 5}}], + [{customer: {companies: []}}, {customer: {companies: [], total: 0}}], + ], +} + +// A parent computed property read by members and by another parent computed. +{ + name: "parent computed feeds members and parent", + policy: { + models: {customer: {age: "number", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.factor", value: "customer.age > 30 ? 2 : 1"}, + {expression: "company.score", value: "company.revenue * customer.factor"}, + {expression: "customer.score", value: "sum(map(customer.companies, #.score))"}, + ], + }, + cases: [ + [ + {customer: {age: 40, companies: [{revenue: 1}, {revenue: 2}]}}, + {customer: {age: 40, factor: 2, companies: [{revenue: 1, score: 2}, {revenue: 2, score: 4}], score: 6}}, + ], + [ + {customer: {age: 20, companies: [{revenue: 1}, {revenue: 2}]}}, + {customer: {age: 20, factor: 1, companies: [{revenue: 1, score: 1}, {revenue: 2, score: 2}], score: 3}}, + ], + [{customer: {age: 20, companies: []}}, {customer: {age: 20, factor: 1, companies: [], score: 0}}], + ], +} + +// Indexing into the relationship array reads members and their computed properties. +{ + name: "index access into members", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "customer.firstBig", value: "customer.companies[0].big"}, + {expression: "customer.lastRevenue", value: "customer.companies[1].revenue"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1}, {revenue: 300}]}}, + {customer: {companies: [{revenue: 1, big: false}, {revenue: 300, big: true}], firstBig: false, lastRevenue: 300}}, + ], + [ + {customer: {companies: [{revenue: 300}]}}, + {customer: {companies: [{revenue: 300, big: true}], firstBig: true, lastRevenue: null}}, + ], + [ + {customer: {companies: []}}, + {customer: {companies: [], firstBig: null, lastRevenue: null}}, + ], + ], +} + +// A computed property holding members (filtered list), then a read through it to a member computed. +{ + name: "computed member lists keep member computeds", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", name: "string"}}, + blocks: [ + {expression: "company.fee", value: "company.revenue / 10"}, + {expression: "customer.profitable", value: "filter(customer.companies, #.revenue > 0)"}, + {expression: "customer.best", value: "customer.profitable[0]"}, + {expression: "customer.bestFee", value: "customer.best.fee"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: -5, name: "a"}, {revenue: 20, name: "b"}]}}, + {customer: { + companies: [{revenue: -5, name: "a", fee: -0.5}, {revenue: 20, name: "b", fee: 2}], + profitable: [{revenue: 20, name: "b", fee: 2}], + best: {revenue: 20, name: "b", fee: 2}, + bestFee: 2, + }}, + ], + [ + {customer: {companies: [{revenue: -5, name: "a"}]}}, + {customer: {companies: [{revenue: -5, name: "a", fee: -0.5}], profitable: [], best: null, bestFee: null}}, + ], + ], +} + +// Mapping members into new objects. +{ + name: "map members into summaries", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", name: "string"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "customer.summaries", value: "map(customer.companies as c, {label: c.name, big: c.big})"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1, name: "a"}, {revenue: 300, name: "b"}]}}, + {customer: { + companies: [{revenue: 1, name: "a", big: false}, {revenue: 300, name: "b", big: true}], + summaries: [{label: "a", big: false}, {label: "b", big: true}], + }}, + ], + [{customer: {companies: []}}, {customer: {companies: [], summaries: []}}], + ], +} + +// Single relationships: one nested object, computed properties on it, read from the parent. +{ + name: "single relationship computed and read by parent", + policy: { + models: {customer: {report: "creditReport"}, creditReport: {score: "number", debt: "number"}}, + blocks: [ + {expression: "creditReport.good", value: "creditReport.score > 700"}, + {expression: "customer.ok", value: "customer.report.good and customer.report.debt < 1000"}, + ], + }, + cases: [ + [{customer: {report: {score: 800, debt: 10}}}, {customer: {report: {score: 800, debt: 10, good: true}, ok: true}}], + [{customer: {report: {score: 600, debt: 10}}}, {customer: {report: {score: 600, debt: 10, good: false}, ok: false}}], + [{customer: {report: {score: 701, debt: 1000}}}, {customer: {report: {score: 701, debt: 1000, good: true}, ok: false}}], + ], +} + +// A single-relationship computed reads the parent. +{ + name: "single relationship member reads parent", + policy: { + models: {customer: {income: "number", report: "creditReport"}, creditReport: {debt: "number"}}, + blocks: [{expression: "creditReport.ratio", value: "creditReport.debt / customer.income"}], + }, + cases: [ + [{customer: {income: 100, report: {debt: 25}}}, {customer: {income: 100, report: {debt: 25, ratio: 0.25}}}], + [{customer: {income: 8, report: {debt: 2}}}, {customer: {income: 8, report: {debt: 2, ratio: 0.25}}}], + ], +} + +// Single relationship absent: reads that need it are missing required inputs. +{ + name: "single relationship missing", + policy: { + models: {customer: {name: "string", report: "creditReport"}, creditReport: {score: "number"}}, + blocks: [{expression: "creditReport.good", value: "creditReport.score > 700"}], + }, + cases: [ + [{customer: {name: "a", report: {score: 900}}}, {customer: {name: "a", report: {score: 900, good: true}}}], + [{customer: {name: "a"}}, "!error: MissingRequiredInputs"], + [{customer: {name: "a", report: {}}}, "!error: MissingRequiredInputs"], + ], +} + +// Optional relationships: null and missing read as null, `??` supplies defaults. +{ + name: "optional relationships with defaults", + policy: { + models: { + customer: {name: "string", companies: "company[]?", report: "creditReport?"}, + company: {revenue: "number"}, + creditReport: {score: "number"}, + }, + blocks: [ + {expression: "customer.n", value: "len(customer.companies ?? [])"}, + {expression: "customer.s", value: "customer.report.score ?? 0"}, + ], + }, + cases: [ + [{customer: {name: "x", companies: null, report: null}}, {customer: {name: "x", companies: null, report: null, n: 0, s: 0}}], + [{customer: {name: "x"}}, {customer: {name: "x", n: 0, s: 0}}], + [ + {customer: {name: "x", companies: [{revenue: 1}], report: {score: 3}}}, + {customer: {name: "x", companies: [{revenue: 1}], report: {score: 3}, n: 1, s: 3}}, + ], + ], +} + +// Optional array relationship with a per-member block: absent arrays run no members. +{ + name: "optional array relationship with per-member block", + policy: { + models: {customer: {name: "string", companies: "company[]?"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "customer.bigCount", value: "count(customer.companies ?? [], #.big)"}, + ], + }, + cases: [ + [ + {customer: {name: "x", companies: [{revenue: 200}]}}, + {customer: {name: "x", companies: [{revenue: 200, big: true}], bigCount: 1}}, + ], + [{customer: {name: "x", companies: []}}, {customer: {name: "x", companies: [], bigCount: 0}}], + [{customer: {name: "x", companies: null}}, {customer: {name: "x", companies: null, bigCount: 0}}], + [{customer: {name: "x"}}, {customer: {name: "x", bigCount: 0}}], + ], +} + +// Required array relationship absent: missing required input. +{ + name: "required array relationship missing", + policy: { + models: {customer: {name: "string", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}], + }, + cases: [ + [{customer: {name: "a", companies: [{revenue: 1}]}}, {customer: {name: "a", companies: [{revenue: 1}], total: 1}}], + [{customer: {name: "a"}}, "!error: MissingRequiredInputs"], + [{customer: {name: "a", companies: []}}, {customer: {name: "a", companies: [], total: 0}}], + ], +} + +// Input validation of relationship values. +{ + name: "relationship values are validated", + policy: { + models: {customer: {companies: "company[]", report: "creditReport?"}, company: {revenue: "number"}, creditReport: {score: "number"}}, + blocks: [{expression: "customer.count", value: "len(customer.companies)"}], + }, + cases: [ + [{customer: {companies: "bad"}}, "!error: InputValidationFailed"], + [{customer: {companies: [1]}}, "!error: InputValidationFailed"], + [{customer: {companies: [{revenue: "1"}]}}, "!error: InputValidationFailed"], + [{customer: {companies: {revenue: 1}}}, "!error: InputValidationFailed"], + [{customer: {companies: [], report: [1]}}, "!error: InputValidationFailed"], + [{customer: {companies: [], report: "r"}}, "!error: InputValidationFailed"], + [{customer: {companies: [], report: {score: true}}}, "!error: InputValidationFailed"], + [{customer: {companies: [{revenue: 1, other: "free"}]}}, {customer: {companies: [{revenue: 1, other: "free"}], count: 1}}], + ], +} + +// Null array items pass validation and are counted, but are not members to evaluate. +{ + name: "null items in a relationship array", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.n", value: "len(customer.companies)"}, + {expression: "customer.real", value: "count(customer.companies, # != null)"}, + ], + }, + cases: [ + [{customer: {companies: [null, {revenue: 2}]}}, {customer: {companies: [null, {revenue: 2}], n: 2, real: 1}}], + [{customer: {companies: [null]}}, {customer: {companies: [null], n: 1, real: 0}}], + ], +} + +// A per-member block over an array containing a null item. +{ + name: "per-member block over a null item", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + cases: [ + [{customer: {companies: [{revenue: 200}]}}, {customer: {companies: [{revenue: 200, big: true}]}}], + [ + {customer: {companies: [null, {revenue: 200}]}}, + "!error: ExpressionFailed", + "question: validation accepts null items in a relationship array, but the per-member block still runs for the null item and fails on `null > 100`; skipping null members looks intended", + ], + ], +} + +// Members missing a declared field: the member's own read sees null. +{ + name: "member missing a field with a default", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.safe", value: "(company.revenue ?? 0) + 1"}, + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue ?? 0))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 5}, {}]}}, + {customer: {companies: [{revenue: 5, safe: 6}, {safe: 1}], total: 5}}, + ], + [ + {customer: {companies: [{revenue: null}, {revenue: 2}]}}, + {customer: {companies: [{revenue: null, safe: 1}, {revenue: 2, safe: 3}], total: 2}}, + ], + [{customer: {companies: [{}, {}]}}, {customer: {companies: [{safe: 1}, {safe: 1}], total: 0}}], + ], +} + +// Members missing a field without a default: comparing null fails the evaluation. +{ + name: "member missing a field without a default", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + cases: [ + [{customer: {companies: [{revenue: 50}, {revenue: 500}]}}, {customer: {companies: [{revenue: 50, big: false}, {revenue: 500, big: true}]}}], + [{customer: {companies: [{revenue: 50}, {}]}}, "!error: ExpressionFailed"], + [{customer: {companies: [{revenue: null}]}}, "!error: ExpressionFailed"], + ], +} + +// A missing member field read through an aggregate that tolerates nulls. +{ + name: "aggregate over members missing fields", + policy: { + models: {customer: {companies: "company[]"}, company: {name: "string", revenue: "number"}}, + blocks: [ + {expression: "customer.names", value: "map(customer.companies, #.name)"}, + {expression: "customer.withRevenue", value: "count(customer.companies, #.revenue != null)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{name: "a", revenue: 1}, {name: "b"}]}}, + {customer: {companies: [{name: "a", revenue: 1}, {name: "b"}], names: ["a", "b"], withRevenue: 1}}, + ], + [ + {customer: {companies: [{revenue: 1}, {}]}}, + {customer: {companies: [{revenue: 1}, {}], names: [null, null], withRevenue: 1}}, + ], + ], +} + +// Two levels of array relationships, aggregated bottom-up through the middle entity. +{ + name: "nested relationships aggregate bottom-up", + policy: { + models: {customer: {companies: "company[]"}, company: {employees: "employee[]"}, employee: {salary: "number"}}, + blocks: [ + {expression: "company.payroll", value: "sum(map(company.employees, #.salary))"}, + {expression: "customer.payroll", value: "sum(map(customer.companies, #.payroll))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{employees: [{salary: 5}, {salary: 20}]}, {employees: []}]}}, + {customer: {companies: [{employees: [{salary: 5}, {salary: 20}], payroll: 25}, {employees: [], payroll: 0}], payroll: 25}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], payroll: 0}}], + [ + {customer: {companies: [{employees: [{salary: 1}]}, {employees: [{salary: 2}, {salary: 3}]}]}}, + {customer: {companies: [{employees: [{salary: 1}], payroll: 1}, {employees: [{salary: 2}, {salary: 3}], payroll: 5}], payroll: 6}}, + ], + ], +} + +// Nested relationships flattened from the top. +{ + name: "nested relationships read from the root", + policy: { + models: {customer: {companies: "company[]"}, company: {employees: "employee[]"}, employee: {salary: "number"}}, + blocks: [ + {expression: "customer.headcount", value: "sum(map(customer.companies, len(#.employees)))"}, + {expression: "customer.salaries", value: "flatMap(customer.companies, map(#.employees, #.salary))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{employees: [{salary: 5}, {salary: 20}]}, {employees: [{salary: 1}]}]}}, + {customer: {companies: [{employees: [{salary: 5}, {salary: 20}]}, {employees: [{salary: 1}]}], headcount: 3, salaries: [5, 20, 1]}}, + ], + [{customer: {companies: [{employees: []}]}}, {customer: {companies: [{employees: []}], headcount: 0, salaries: []}}], + ], +} + +// Per-member blocks on the second level (employee inside company inside customer). +{ + name: "per-member block two levels deep", + policy: { + models: {customer: {companies: "company[]"}, company: {employees: "employee[]"}, employee: {salary: "number"}}, + blocks: [{expression: "employee.high", value: "employee.salary > 10"}], + }, + cases: [ + [ + {customer: {companies: [{employees: [{salary: 5}, {salary: 20}]}, {employees: []}]}}, + {customer: {companies: [{employees: [{salary: 5, high: false}, {salary: 20, high: true}]}, {employees: []}]}}, + "bug: the required-input check looks for employee.salary at company.employees.salary, not under customer.companies[].employees[], and fails with MissingRequiredInputs although every employee has a salary", + ], + [ + {customer: {companies: [{employees: [{salary: 11}]}]}}, + {customer: {companies: [{employees: [{salary: 11, high: true}]}]}}, + "bug: two-level per-member blocks fail the required-input check (MissingRequiredInputs employee.salary)", + ], + ], +} + +// Second-level computed aggregated into the middle level. +{ + name: "second-level computed aggregated by middle level", + policy: { + models: {customer: {companies: "company[]"}, company: {employees: "employee[]"}, employee: {salary: "number"}}, + blocks: [ + {expression: "employee.high", value: "employee.salary > 10"}, + {expression: "company.highCount", value: "count(company.employees, #.high)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{employees: [{salary: 5}, {salary: 20}]}, {employees: []}]}}, + {customer: {companies: [ + {employees: [{salary: 5, high: false}, {salary: 20, high: true}], highCount: 1}, + {employees: [], highCount: 0}, + ]}}, + "bug: MissingRequiredInputs employee.salary for a two-level relationship (see per-member block two levels deep)", + ], + { + input: {customer: {companies: [{employees: [{salary: 30}]}]}}, + goals: ["company.highCount"], + output: {customer: {companies: [{employees: [{salary: 30, high: true}], highCount: 1}]}}, + note: "bug: goals do not avoid the two-level MissingRequiredInputs failure", + }, + ], +} + +// Single relationship nested inside a single relationship. +{ + name: "nested single relationships", + policy: { + models: {customer: {report: "creditReport"}, creditReport: {bureau: "bureau"}, bureau: {name: "string", weight: "number"}}, + blocks: [{expression: "customer.bureauWeight", value: "customer.report.bureau.weight * 2"}], + }, + cases: [ + [ + {customer: {report: {bureau: {name: "x", weight: 3}}}}, + {customer: {report: {bureau: {name: "x", weight: 3}}, bureauWeight: 6}}, + ], + [ + {customer: {report: {bureau: {name: "y", weight: 0.5}}}}, + {customer: {report: {bureau: {name: "y", weight: 0.5}}, bureauWeight: 1}}, + ], + [{customer: {report: {bureau: {name: "y", weight: "1"}}}}, "!error: InputValidationFailed"], + ], +} + +// Single relationship inside an array relationship: per-member reads one level down. +{ + name: "single relationship inside array members", + policy: { + models: {customer: {companies: "company[]"}, company: {address: "address"}, address: {country: "string"}}, + blocks: [ + {expression: "company.domestic", value: "company.address.country == 'US'"}, + {expression: "customer.foreign", value: "count(customer.companies, not #.domestic)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{address: {country: "US"}}, {address: {country: "DE"}}]}}, + {customer: {companies: [{address: {country: "US"}, domestic: true}, {address: {country: "DE"}, domestic: false}], foreign: 1}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], foreign: 0}}], + ], +} + +// Two relationship properties targeting different entities, each iterated on its own. +{ + name: "two array relationships on one entity", + policy: { + models: {customer: {companies: "company[]", loans: "loan[]"}, company: {revenue: "number"}, loan: {amount: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "loan.large", value: "loan.amount > 1000"}, + {expression: "customer.exposure", value: "sum(map(customer.loans, #.amount)) - sum(map(customer.companies, #.revenue))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 200}], loans: [{amount: 5000}, {amount: 10}]}}, + {customer: { + companies: [{revenue: 200, big: true}], + loans: [{amount: 5000, large: true}, {amount: 10, large: false}], + exposure: 4810, + }}, + ], + [ + {customer: {companies: [], loans: []}}, + {customer: {companies: [], loans: [], exposure: 0}}, + ], + ], +} + +// Goals on a per-member property evaluate only the member chain. +{ + name: "goal on a per-member property", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}, + ], + }, + cases: [ + { + input: {customer: {companies: [{revenue: 1}, {revenue: 200}]}}, + goals: ["company.big"], + output: {customer: {companies: [{revenue: 1, big: false}, {revenue: 200, big: true}]}}, + }, + { + input: {customer: {companies: [{revenue: 1}, {revenue: 200}]}}, + goals: ["customer.total"], + output: {customer: {companies: [{revenue: 1}, {revenue: 200}], total: 201}}, + }, + ], +} + +// Declared properties are inputs: a block writing one is an InputOverride diagnostic and is +// dropped from evaluation, both on members and on the root. +{ + name: "declaring a computed member property drops its block", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", big: "boolean?"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1}, {revenue: 300}]}}, + {customer: {companies: [{revenue: 1}, {revenue: 300}]}}, + "question: writing a declared property is an InputOverride error diagnostic; evaluation silently drops the block instead of refusing the policy", + ], + [ + {customer: {companies: [{revenue: 1, big: true}]}}, + {customer: {companies: [{revenue: 1, big: true}]}}, + "question: the declared value passes through untouched since the writing block is dropped", + ], + ], +} diff --git a/core/engine/tests/spec/policy/10-references.json5 b/core/engine/tests/spec/policy/10-references.json5 new file mode 100644 index 00000000..01c574d8 --- /dev/null +++ b/core/engine/tests/spec/policy/10-references.json5 @@ -0,0 +1,556 @@ +// Reference properties (`&entity`): the input holds string ids, and the referenced entities live +// in a top-level pool array named after the target entity (`product: [{id: "p1", ...}]`). Before +// evaluation each id is replaced by the pool object with that `id`. Validation rejects ids that +// are not strings or not present in the pool. + +// Single reference: the id resolves to the pool object, and the output shows the resolved object. +{ + name: "single reference resolves to the pool object", + policy: { + models: {customer: {product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.price", value: "customer.product.price"}], + }, + cases: [ + [ + {customer: {product: "p1"}, product: [{id: "p1", price: 5}]}, + {customer: {product: {id: "p1", price: 5}, price: 5}, product: [{id: "p1", price: 5}]}, + ], + [ + {customer: {product: "p2"}, product: [{id: "p1", price: 5}, {id: "p2", price: 7.5}]}, + {customer: {product: {id: "p2", price: 7.5}, price: 7.5}, product: [{id: "p1", price: 5}, {id: "p2", price: 7.5}]}, + ], + [ + {customer: {product: "p1"}, product: [{id: "p1", price: 0, extra: "kept"}]}, + {customer: {product: {id: "p1", price: 0, extra: "kept"}, price: 0}, product: [{id: "p1", price: 0, extra: "kept"}]}, + ], + ], +} + +// Ids that do not resolve, or are not strings, fail validation. +{ + name: "unresolvable single references", + policy: { + models: {customer: {product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.price", value: "customer.product.price"}], + }, + cases: [ + [{customer: {product: "p2"}, product: [{id: "p1", price: 5}]}, "!error: InputValidationFailed"], + [{customer: {product: "p1"}}, "!error: InputValidationFailed"], + [{customer: {product: "p1"}, product: []}, "!error: InputValidationFailed"], + [{customer: {product: 3}, product: [{id: "p1", price: 5}]}, "!error: InputValidationFailed"], + [{customer: {product: {id: "p1", price: 5}}, product: [{id: "p1", price: 5}]}, "!error: InputValidationFailed"], + [{customer: {product: ""}, product: [{id: "p1", price: 5}]}, "!error: InputValidationFailed"], + [{customer: {product: "P1"}, product: [{id: "p1", price: 5}]}, "!error: InputValidationFailed"], + ], +} + +// A missing reference is a missing input when a block needs it. +{ + name: "missing single reference", + policy: { + models: {customer: {name: "string", product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.price", value: "customer.product.price"}], + }, + cases: [ + [{customer: {name: "a"}, product: [{id: "p1", price: 5}]}, "!error: MissingRequiredInputs"], + [{customer: {name: "a", product: null}, product: [{id: "p1", price: 5}]}, "!error: MissingRequiredInputs"], + [ + {customer: {name: "a", product: "p1"}, product: [{id: "p1", price: 5}]}, + {customer: {name: "a", product: {id: "p1", price: 5}, price: 5}, product: [{id: "p1", price: 5}]}, + ], + ], +} + +// Optional reference with a default. +{ + name: "optional reference with a default", + policy: { + models: {customer: {name: "string", product: "&product?"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.price", value: "customer.product.price ?? 0"}], + }, + cases: [ + [{customer: {name: "a"}, product: [{id: "p1", price: 5}]}, {customer: {name: "a", price: 0}, product: [{id: "p1", price: 5}]}], + [{customer: {name: "a"}}, {customer: {name: "a", price: 0}}], + [{customer: {name: "a", product: null}}, {customer: {name: "a", product: null, price: 0}}], + [ + {customer: {name: "a", product: "p1"}, product: [{id: "p1", price: 5}]}, + {customer: {name: "a", product: {id: "p1", price: 5}, price: 5}, product: [{id: "p1", price: 5}]}, + ], + [{customer: {name: "a", product: "zz"}, product: [{id: "p1", price: 5}]}, "!error: InputValidationFailed"], + ], +} + +// The pool itself is validated as an array of the target entity. +{ + name: "pool validation", + policy: { + models: {customer: {product: "&product?"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.has", value: "customer.product != null"}], + }, + cases: [ + [{customer: {}, product: [{id: "p1", price: 5}]}, {customer: {has: false}, product: [{id: "p1", price: 5}]}], + [{customer: {}, product: {id: "p1", price: 5}}, "!error: InputValidationFailed"], + [{customer: {}, product: [{id: "p1", price: "5"}]}, "!error: InputValidationFailed"], + [{customer: {}, product: [1]}, "!error: InputValidationFailed"], + [{customer: {}, product: [null, {id: "p1", price: 5}]}, {customer: {has: false}, product: [null, {id: "p1", price: 5}]}], + [{customer: {}, product: []}, {customer: {has: false}, product: []}], + ], +} + +// Pool items without a string id cannot be referenced. +{ + name: "pool items need a string id", + policy: { + models: {customer: {product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.price", value: "customer.product.price"}], + }, + cases: [ + [{customer: {product: "p1"}, product: [{price: 5}]}, "!error: InputValidationFailed"], + [{customer: {product: "1"}, product: [{id: 1, price: 5}]}, "!error: InputValidationFailed"], + ], +} + +// Duplicate ids in the pool: the reference resolves to one of them. +{ + name: "duplicate ids in the pool", + policy: { + models: {customer: {product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.price", value: "customer.product.price"}], + }, + cases: [ + [ + {customer: {product: "p1"}, product: [{id: "p1", price: 5}, {id: "p1", price: 9}]}, + {customer: {product: {id: "p1", price: 9}, price: 9}, product: [{id: "p1", price: 5}, {id: "p1", price: 9}]}, + "question: duplicate pool ids are not rejected; the last pool entry wins", + ], + ], +} + +// Array references resolve each id; order and repetition follow the id list, not the pool. +{ + name: "array reference resolves each id", + policy: { + models: {customer: {companies: "&company[]"}, company: {id: "string", revenue: "number"}}, + blocks: [{expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}], + }, + cases: [ + [ + {customer: {companies: ["c1", "c2"]}, company: [{id: "c1", revenue: 50}, {id: "c2", revenue: 200}, {id: "c3", revenue: 7}]}, + {customer: {companies: [{id: "c1", revenue: 50}, {id: "c2", revenue: 200}], total: 250}, company: [{id: "c1", revenue: 50}, {id: "c2", revenue: 200}, {id: "c3", revenue: 7}]}, + ], + [ + {customer: {companies: ["c3", "c1", "c3"]}, company: [{id: "c1", revenue: 50}, {id: "c3", revenue: 7}]}, + {customer: {companies: [{id: "c3", revenue: 7}, {id: "c1", revenue: 50}, {id: "c3", revenue: 7}], total: 64}, company: [{id: "c1", revenue: 50}, {id: "c3", revenue: 7}]}, + ], + [{customer: {companies: []}, company: []}, {customer: {companies: [], total: 0}, company: []}], + [{customer: {companies: []}}, {customer: {companies: [], total: 0}}], + ], +} + +// Array references with unresolvable or ill-typed ids. +{ + name: "array reference validation", + policy: { + models: {customer: {companies: "&company[]"}, company: {id: "string", revenue: "number"}}, + blocks: [{expression: "customer.n", value: "len(customer.companies)"}], + }, + cases: [ + [{customer: {companies: ["c9"]}, company: [{id: "c1", revenue: 50}]}, "!error: InputValidationFailed"], + [{customer: {companies: ["c1"]}}, "!error: InputValidationFailed"], + [{customer: {companies: ["c1", 2]}, company: [{id: "c1", revenue: 50}]}, "!error: InputValidationFailed"], + [{customer: {companies: "c1"}, company: [{id: "c1", revenue: 50}]}, "!error: InputValidationFailed"], + [ + {customer: {companies: ["c1", null]}, company: [{id: "c1", revenue: 50}]}, + {customer: {companies: [{id: "c1", revenue: 50}, null], n: 2}, company: [{id: "c1", revenue: 50}]}, + ], + ], +} + +// Per-member computed on the referenced entity runs over the pool, and references see the result. +{ + name: "per-member computed on a referenced entity", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + models: {customer: {companies: "&company[]"}, company: {id: "string", revenue: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "customer.bigCount", value: "count(customer.companies, #.big)"}, + ], + }, + cases: [ + [ + {customer: {companies: ["c2"]}, company: [{id: "c1", revenue: 50}, {id: "c2", revenue: 200}]}, + { + customer: {companies: [{id: "c2", revenue: 200, big: true}], bigCount: 1}, + company: [{id: "c1", revenue: 50, big: false}, {id: "c2", revenue: 200, big: true}], + }, + ], + [ + {customer: {companies: []}, company: [{id: "c1", revenue: 500}]}, + {customer: {companies: [], bigCount: 0}, company: [{id: "c1", revenue: 500, big: true}]}, + ], + [ + {customer: {companies: ["c1", "c1"]}, company: [{id: "c1", revenue: 500}]}, + {customer: {companies: [{id: "c1", revenue: 500, big: true}, {id: "c1", revenue: 500, big: true}], bigCount: 2}, company: [{id: "c1", revenue: 500, big: true}]}, + ], + ], +} + +// A per-member match on the referenced entity. +{ + name: "per-member match on a referenced entity", + policy: { + models: {customer: {companies: "&company[]"}, company: {id: "string", revenue: "number"}}, + blocks: [ + {match: "company.riskLevel", arms: [["company.revenue >= 200000", "'low'"], ["", "'high'"]]}, + {expression: "customer.totalRevenue", value: "sum(map(customer.companies as c, c.revenue))"}, + ], + }, + cases: [ + [ + {customer: {companies: ["a", "b"]}, company: [{id: "a", revenue: 300000}, {id: "b", revenue: 1}]}, + { + customer: {companies: [{id: "a", revenue: 300000, riskLevel: "low"}, {id: "b", revenue: 1, riskLevel: "high"}], totalRevenue: 300001}, + company: [{id: "a", revenue: 300000, riskLevel: "low"}, {id: "b", revenue: 1, riskLevel: "high"}], + }, + ], + [ + {customer: {companies: ["b"]}, company: [{id: "a", revenue: 300000}, {id: "b", revenue: 1}]}, + { + customer: {companies: [{id: "b", revenue: 1, riskLevel: "high"}], totalRevenue: 1}, + company: [{id: "a", revenue: 300000, riskLevel: "low"}, {id: "b", revenue: 1, riskLevel: "high"}], + }, + ], + ], +} + +// Reading a computed property through a single reference with a dotted path. +{ + name: "computed property through a single reference", + policy: { + models: {customer: {product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "product.gross", value: "product.price * 2"}, + {expression: "customer.gross", value: "customer.product.gross"}, + ], + }, + cases: [ + [ + {customer: {product: "p1"}, product: [{id: "p1", price: 5}, {id: "p2", price: 1}]}, + {customer: {product: {id: "p1", price: 5, gross: 10}, gross: 10}, product: [{id: "p1", price: 5, gross: 10}, {id: "p2", price: 1, gross: 2}]}, + "bug: the required-input check treats customer.product.gross as an input path and fails with MissingRequiredInputs although product.gross is computed for every pool entry", + ], + [ + {customer: {product: "p2"}, product: [{id: "p1", price: 5}, {id: "p2", price: 1}]}, + {customer: {product: {id: "p2", price: 1, gross: 2}, gross: 2}, product: [{id: "p1", price: 5, gross: 10}, {id: "p2", price: 1, gross: 2}]}, + "bug: computed properties are not readable through a single reference (MissingRequiredInputs)", + ], + ], +} + +// Reading computed properties of referenced members through a closure. The read is not tracked as +// a dependency on the target's computed property, so the order falls back to something +// name-dependent: `company` sorts before `customer` and happens to work, `product` does not. +{ + name: "computed property through a reference array closure", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + models: {customer: {products: "&product[]"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "product.gross", value: "product.price * 2"}, + {expression: "customer.gross", value: "map(customer.products, #.gross)"}, + ], + }, + cases: [ + [ + {customer: {products: ["p1", "p2"]}, product: [{id: "p1", price: 5}, {id: "p2", price: 1}]}, + {customer: {products: [{id: "p1", price: 5, gross: 10}, {id: "p2", price: 1, gross: 2}], gross: [10, 2]}, product: [{id: "p1", price: 5, gross: 10}, {id: "p2", price: 1, gross: 2}]}, + "bug: customer.gross runs before product.gross (reads of referenced members' computed properties are not dependencies) and maps to [null, null]", + ], + [ + {customer: {products: []}, product: [{id: "p1", price: 5}]}, + {customer: {products: [], gross: []}, product: [{id: "p1", price: 5, gross: 10}]}, + ], + { + input: {customer: {products: ["p1"]}, product: [{id: "p1", price: 5}]}, + goals: ["customer.gross"], + output: {customer: {products: [{id: "p1", price: 5, gross: 10}], gross: [10]}, product: [{id: "p1", price: 5, gross: 10}]}, + note: "bug: with a goal, product.gross is not demanded at all, so the referenced members never get it", + }, + ], +} + +// The same shape with an entity name that sorts before the reader. +{ + name: "computed property through a reference array closure, early-sorting target", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + models: {customer: {companies: "&company[]"}, company: {id: "string", revenue: "number"}}, + blocks: [ + {expression: "company.gross", value: "company.revenue * 2"}, + {expression: "customer.gross", value: "sum(map(customer.companies, #.gross))"}, + ], + }, + cases: [ + [ + {customer: {companies: ["p1", "p2"]}, company: [{id: "p1", revenue: 5}, {id: "p2", revenue: 1}]}, + {customer: {companies: [{id: "p1", revenue: 5, gross: 10}, {id: "p2", revenue: 1, gross: 2}], gross: 12}, company: [{id: "p1", revenue: 5, gross: 10}, {id: "p2", revenue: 1, gross: 2}]}, + ], + [ + {customer: {companies: []}, company: [{id: "p1", revenue: 5}]}, + {customer: {companies: [], gross: 0}, company: [{id: "p1", revenue: 5, gross: 10}]}, + ], + ], +} + +// Through a relationship (not a reference) the same read is ordered correctly. +{ + name: "computed property through a relationship closure for comparison", + policy: { + models: {customer: {products: "product[]"}, product: {price: "number"}}, + blocks: [ + {expression: "product.gross", value: "product.price * 2"}, + {expression: "customer.gross", value: "map(customer.products, #.gross)"}, + ], + }, + cases: [ + [{customer: {products: [{price: 5}, {price: 1}]}}, {customer: {products: [{price: 5, gross: 10}, {price: 1, gross: 2}], gross: [10, 2]}}], + [{customer: {products: []}}, {customer: {products: [], gross: []}}], + ], +} + +// A computed on the referencing entity combines its own fields with the referenced object. +{ + name: "referencing entity combines own and referenced fields", + policy: { + models: {customer: {qty: "number", product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "customer.total", value: "customer.qty * customer.product.price"}, + {match: "customer.band", arms: [["customer.total >= 100", "'high'"], ["", "'low'"]]}, + ], + }, + cases: [ + [ + {customer: {qty: 3, product: "p1"}, product: [{id: "p1", price: 50}]}, + {customer: {qty: 3, product: {id: "p1", price: 50}, total: 150, band: "high"}, product: [{id: "p1", price: 50}]}, + ], + [ + {customer: {qty: 1, product: "p1"}, product: [{id: "p1", price: 50}]}, + {customer: {qty: 1, product: {id: "p1", price: 50}, total: 50, band: "low"}, product: [{id: "p1", price: 50}]}, + ], + [ + {customer: {qty: 0, product: "p1"}, product: [{id: "p1", price: 50}]}, + {customer: {qty: 0, product: {id: "p1", price: 50}, total: 0, band: "low"}, product: [{id: "p1", price: 50}]}, + ], + ], +} + +// A table input reads through a reference. +{ + name: "table input through a reference", + policy: { + models: {customer: {product: "&product"}, product: {id: "string", category: "string"}}, + blocks: [ + {table: "t", inputs: ["customer.product.category"], outputs: ["customer.discount"], rules: [ + ["'food'", "0.1"], + ["'tech'", "0.2"], + ["", "0"], + ]}, + ], + }, + cases: [ + [ + {customer: {product: "a"}, product: [{id: "a", category: "food"}, {id: "b", category: "tech"}]}, + {customer: {product: {id: "a", category: "food"}, discount: 0.1}, product: [{id: "a", category: "food"}, {id: "b", category: "tech"}]}, + ], + [ + {customer: {product: "b"}, product: [{id: "a", category: "food"}, {id: "b", category: "tech"}]}, + {customer: {product: {id: "b", category: "tech"}, discount: 0.2}, product: [{id: "a", category: "food"}, {id: "b", category: "tech"}]}, + ], + [ + {customer: {product: "c"}, product: [{id: "c", category: "toys"}]}, + {customer: {product: {id: "c", category: "toys"}, discount: 0}, product: [{id: "c", category: "toys"}]}, + ], + ], +} + +// References from members of an array relationship: validation checks the ids against the pool, +// but hydration only visits `.` at the input root, so a member's reference stays +// an id string. +{ + name: "reference inside relationship members", + policy: { + models: { + customer: {companies: "company[]"}, + company: {name: "string", bank: "&bank"}, + bank: {id: "string", rating: "number"}, + }, + blocks: [{expression: "company.bankRating", value: "company.bank.rating"}], + }, + cases: [ + [ + {customer: {companies: [{name: "a", bank: "b1"}]}, bank: [{id: "b1", rating: 3}]}, + {customer: {companies: [{name: "a", bank: {id: "b1", rating: 3}, bankRating: 3}]}, bank: [{id: "b1", rating: 3}]}, + "bug: a reference inside a relationship member is validated against the pool but never resolved; company.bank stays \"b1\" and bankRating is null", + ], + [ + {customer: {companies: [{name: "a", bank: "b2"}, {name: "b", bank: "b1"}]}, bank: [{id: "b1", rating: 3}, {id: "b2", rating: 9}]}, + {customer: {companies: [{name: "a", bank: {id: "b2", rating: 9}, bankRating: 9}, {name: "b", bank: {id: "b1", rating: 3}, bankRating: 3}]}, bank: [{id: "b1", rating: 3}, {id: "b2", rating: 9}]}, + "bug: member references are not hydrated (only root-entity reference fields are)", + ], + [{customer: {companies: [{name: "a", bank: "zz"}]}, bank: [{id: "b1", rating: 3}]}, "!error: InputValidationFailed"], + ], +} + +// A referenced entity that is also reachable by a relationship: the relationship is the source. +{ + name: "entity both referenced and related", + policy: { + models: { + customer: {companies: "company[]", favorite: "&company?"}, + company: {id: "string", revenue: "number"}, + }, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "customer.bigCount", value: "count(customer.companies, #.big)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{id: "c1", revenue: 500}, {id: "c2", revenue: 1}]}}, + {customer: {companies: [{id: "c1", revenue: 500, big: true}, {id: "c2", revenue: 1, big: false}], bigCount: 1}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], bigCount: 0}}], + [ + {customer: {companies: [{id: "c1", revenue: 500}], favorite: "c1"}, company: [{id: "c1", revenue: 500}]}, + {customer: {companies: [{id: "c1", revenue: 500, big: true}], favorite: {id: "c1", revenue: 500}, bigCount: 1}, company: [{id: "c1", revenue: 500}]}, + "question: per-member blocks follow the relationship source (customer.companies), so the resolved reference and the pool do not get the computed property", + ], + ], +} + +// Two references to the same target from one entity. +{ + name: "two references to the same pool", + policy: { + models: {order: {from: "&city", to: "&city"}, city: {id: "string", x: "number"}}, + blocks: [{expression: "order.distance", value: "abs(order.to.x - order.from.x)"}], + }, + cases: [ + [ + {order: {from: "a", to: "b"}, city: [{id: "a", x: 1}, {id: "b", x: 4}]}, + {order: {from: {id: "a", x: 1}, to: {id: "b", x: 4}, distance: 3}, city: [{id: "a", x: 1}, {id: "b", x: 4}]}, + ], + [ + {order: {from: "b", to: "a"}, city: [{id: "a", x: 1}, {id: "b", x: 4}]}, + {order: {from: {id: "b", x: 4}, to: {id: "a", x: 1}, distance: 3}, city: [{id: "a", x: 1}, {id: "b", x: 4}]}, + ], + [ + {order: {from: "a", to: "a"}, city: [{id: "a", x: 1}]}, + {order: {from: {id: "a", x: 1}, to: {id: "a", x: 1}, distance: 0}, city: [{id: "a", x: 1}]}, + ], + ], +} + +// A reference whose target is an entity with a date property: pool dates are converted. +{ + name: "referenced entity with a date property", + policy: { + models: {customer: {policy: "&insurance"}, insurance: {id: "string", start: "date"}}, + blocks: [{expression: "customer.startYear", value: "year(customer.policy.start)"}], + }, + cases: [ + [ + {customer: {policy: "i1"}, insurance: [{id: "i1", start: "2020-05-01"}]}, + {customer: {policy: {id: "i1", start: date("2020-05-01")}, startYear: 2020}, insurance: [{id: "i1", start: date("2020-05-01")}]}, + ], + [{customer: {policy: "i1"}, insurance: [{id: "i1", start: "not a date"}]}, "!error: InputValidationFailed"], + ], +} + +// Optional array reference: absent lists default with `??`. +{ + name: "optional array reference", + policy: { + models: {customer: {name: "string", companies: "&company[]?"}, company: {id: "string", revenue: "number"}}, + blocks: [{expression: "customer.total", value: "sum(map(customer.companies ?? [], #.revenue))"}], + }, + cases: [ + [{customer: {name: "a"}}, {customer: {name: "a", total: 0}}], + [{customer: {name: "a", companies: null}}, {customer: {name: "a", companies: null, total: 0}}], + [ + {customer: {name: "a", companies: ["c1"]}, company: [{id: "c1", revenue: 4}]}, + {customer: {name: "a", companies: [{id: "c1", revenue: 4}], total: 4}, company: [{id: "c1", revenue: 4}]}, + ], + [{customer: {name: "a", companies: ["c1"]}, company: []}, "!error: InputValidationFailed"], + ], +} + +// Index access and filters on resolved reference arrays. +{ + name: "index and filter over resolved references", + policy: { + models: {customer: {companies: "&company[]"}, company: {id: "string", revenue: "number"}}, + blocks: [ + {expression: "customer.firstRevenue", value: "customer.companies[0].revenue"}, + {expression: "customer.bigIds", value: "map(filter(customer.companies, #.revenue > 10), #.id)"}, + ], + }, + cases: [ + [ + {customer: {companies: ["b", "a"]}, company: [{id: "a", revenue: 50}, {id: "b", revenue: 5}]}, + {customer: {companies: [{id: "b", revenue: 5}, {id: "a", revenue: 50}], firstRevenue: 5, bigIds: ["a"]}, company: [{id: "a", revenue: 50}, {id: "b", revenue: 5}]}, + ], + [ + {customer: {companies: []}, company: [{id: "a", revenue: 50}]}, + {customer: {companies: [], firstRevenue: null, bigIds: []}, company: [{id: "a", revenue: 50}]}, + ], + [ + {customer: {companies: ["a", "a"]}, company: [{id: "a", revenue: 50}]}, + {customer: {companies: [{id: "a", revenue: 50}, {id: "a", revenue: 50}], firstRevenue: 50, bigIds: ["a", "a"]}, company: [{id: "a", revenue: 50}]}, + ], + ], +} + +// Goals over a reference read. +{ + name: "goals with references", + policy: { + models: {customer: {qty: "number", product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "customer.total", value: "customer.qty * customer.product.price"}, + {expression: "customer.big", value: "customer.qty > 10"}, + ], + }, + cases: [ + { + input: {customer: {qty: 2, product: "p"}, product: [{id: "p", price: 3}]}, + goals: ["customer.total"], + output: {customer: {qty: 2, product: {id: "p", price: 3}, total: 6}, product: [{id: "p", price: 3}]}, + }, + { + input: {customer: {qty: 20}}, + goals: ["customer.big"], + output: {customer: {qty: 20, big: true}}, + }, + { + input: {customer: {qty: 20, product: "zz"}, product: [{id: "p", price: 3}]}, + goals: ["customer.big"], + output: "!error: InputValidationFailed", + }, + ], +} + +// The pool is plain input: blocks may read it directly. +{ + name: "pool read directly", + diagnostics: ["INVALID_EXPRESSION", "UNREACHABLE_ENTITY_READ"], + policy: { + models: {customer: {product: "&product?"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "catalogSize", value: "len(product)"}], + }, + cases: [ + [{customer: {}, product: [{id: "a", price: 1}, {id: "b", price: 2}]}, {customer: {}, product: [{id: "a", price: 1}, {id: "b", price: 2}], catalogSize: 2}], + [{customer: {}, product: []}, {customer: {}, product: [], catalogSize: 0}], + ], +} diff --git a/core/engine/tests/spec/policy/11-globals.json5 b/core/engine/tests/spec/policy/11-globals.json5 new file mode 100644 index 00000000..e33e2452 --- /dev/null +++ b/core/engine/tests/spec/policy/11-globals.json5 @@ -0,0 +1,409 @@ +// Global-scope data models: their properties live at the top level of the input (the model name +// only groups them). Blocks read globals by bare name and may write new top-level properties. +// As with entities, declared globals are inputs; computed globals stay undeclared. + +// Reading a global number from an entity block. +{ + name: "entity block reads a global", + policy: { + globals: {settings: {rate: "number"}}, + models: {customer: {amount: "number"}}, + blocks: [{expression: "customer.fee", value: "customer.amount * rate"}], + }, + cases: [ + [{customer: {amount: 2}, rate: 3}, {customer: {amount: 2, fee: 6}, rate: 3}], + [{customer: {amount: 2}, rate: 0.5}, {customer: {amount: 2, fee: 1}, rate: 0.5}], + [{customer: {amount: 0}, rate: -1}, {customer: {amount: 0, fee: 0}, rate: -1}], + [{customer: {amount: 2}}, "!error: MissingRequiredInputs"], + [{customer: {amount: 2}, rate: null}, "!error: MissingRequiredInputs"], + [{customer: {amount: 2}, rate: "3"}, "!error: InputValidationFailed"], + ], +} + +// The model name is not part of the path: nesting under it is not the global. +{ + name: "globals are not nested under the model name", + policy: { + globals: {settings: {rate: "number?"}}, + blocks: [{expression: "effective", value: "rate ?? 1"}], + }, + cases: [ + [{rate: 4}, {rate: 4, effective: 4}], + [{settings: {rate: 4}}, {settings: {rate: 4}, effective: 1}], + [{}, {effective: 1}], + [{rate: null}, {rate: null, effective: 1}], + ], +} + +// A policy with only globals: computed globals written at the top level. +{ + name: "global-only policy writes top-level computeds", + policy: { + globals: {settings: {rate: "number", base: "number"}}, + blocks: [ + {expression: "double", value: "rate * 2"}, + {expression: "total", value: "base + double"}, + ], + }, + cases: [ + [{rate: 3, base: 1}, {rate: 3, base: 1, double: 6, total: 7}], + [{rate: 0, base: 0}, {rate: 0, base: 0, double: 0, total: 0}], + [{rate: 1.5, base: -1}, {rate: 1.5, base: -1, double: 3, total: 2}], + [{rate: 1}, "!error: MissingRequiredInputs"], + ], +} + +// Match and table blocks on globals. +{ + name: "match block on a global", + policy: { + globals: {env: {country: "string"}}, + blocks: [{match: "region", arms: [["country == 'US'", "'na'"], ["country in ['DE', 'FR']", "'eu'"], ["", "'other'"]]}], + }, + cases: [ + [{country: "US"}, {country: "US", region: "na"}], + [{country: "FR"}, {country: "FR", region: "eu"}], + [{country: "JP"}, {country: "JP", region: "other"}], + [{country: ""}, {country: "", region: "other"}], + ], +} + +{ + name: "table block on globals", + policy: { + globals: {env: {score: "number", segment: "string"}}, + blocks: [ + {table: "t", inputs: ["score", "segment"], outputs: ["limit"], rules: [ + [">= 700", "'retail'", "5000"], + [">= 700", "", "10000"], + ["", "", "0"], + ]}, + ], + }, + cases: [ + [{score: 750, segment: "retail"}, {score: 750, segment: "retail", limit: 5000}], + [{score: 750, segment: "corp"}, {score: 750, segment: "corp", limit: 10000}], + [{score: 699, segment: "retail"}, {score: 699, segment: "retail", limit: 0}], + [{score: 700, segment: "x"}, {score: 700, segment: "x", limit: 10000}], + ], +} + +// Globals of every primitive type are validated. +{ + name: "global type validation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + globals: {env: {n: "number?", s: "string?", b: "boolean?", d: "date?"}}, + blocks: [{expression: "seen", value: "[n, s, b] "}], + }, + cases: [ + [{n: 1, s: "x", b: true}, {n: 1, s: "x", b: true, seen: [1, "x", true]}], + [{}, {seen: [null, null, null]}], + [{n: "1"}, "!error: InputValidationFailed"], + [{s: 1}, "!error: InputValidationFailed"], + [{b: "true"}, "!error: InputValidationFailed"], + [{d: "nope"}, "!error: InputValidationFailed"], + [{d: 5}, "!error: InputValidationFailed"], + [{d: "2024-01-31"}, {d: date("2024-01-31"), seen: [null, null, null]}], + ], +} + +// Date globals are converted to dates before evaluation. +{ + name: "date global", + policy: { + globals: {env: {asOf: "date"}}, + models: {customer: {born: "date"}}, + blocks: [{expression: "customer.age", value: "year(asOf) - year(customer.born)"}], + }, + cases: [ + [ + {asOf: "2025-01-01", customer: {born: "2000-06-01"}}, + {asOf: date("2025-01-01"), customer: {born: date("2000-06-01"), age: 25}}, + ], + [ + {asOf: "2025-07-01", customer: {born: "1999-12-31"}}, + {asOf: date("2025-07-01"), customer: {born: date("1999-12-31"), age: 26}}, + ], + [ + {asOf: "2024-02-29", customer: {born: "2024-01-01"}}, + {asOf: date("2024-02-29"), customer: {born: date("2024-01-01"), age: 0}}, + ], + [{asOf: "2024-02-30", customer: {born: "2024-01-01"}}, "!error: InputValidationFailed"], + ], +} + +// Array globals. +{ + name: "array globals", + policy: { + globals: {env: {blocked: "string[]", weights: "number[]"}}, + models: {customer: {country: "string"}}, + blocks: [ + {expression: "customer.blocked", value: "customer.country in blocked"}, + {expression: "weightSum", value: "sum(weights)"}, + ], + }, + cases: [ + [ + {blocked: ["RU", "KP"], weights: [1, 2], customer: {country: "KP"}}, + {blocked: ["RU", "KP"], weights: [1, 2], customer: {country: "KP", blocked: true}, weightSum: 3}, + ], + [ + {blocked: [], weights: [], customer: {country: "US"}}, + {blocked: [], weights: [], customer: {country: "US", blocked: false}, weightSum: 0}, + ], + [{blocked: "RU", weights: [], customer: {country: "US"}}, "!error: InputValidationFailed"], + [{blocked: [1], weights: [], customer: {country: "US"}}, "!error: InputValidationFailed"], + [{blocked: [], weights: ["1"], customer: {country: "US"}}, "!error: InputValidationFailed"], + ], +} + +// Enum globals. +{ + name: "enum global", + policy: { + globals: {env: {channel: "string(web|branch)"}}, + blocks: [{expression: "online", value: "channel == 'web'"}], + }, + cases: [ + [{channel: "web"}, {channel: "web", online: true}], + [{channel: "branch"}, {channel: "branch", online: false}], + [{channel: "phone"}, "!error: InputValidationFailed"], + [{channel: 1}, "!error: InputValidationFailed"], + ], +} + +// A computed global read by an entity block and an entity computed read by a global block. +{ + name: "globals and entities feed each other", + policy: { + globals: {env: {baseRate: "number"}}, + models: {customer: {vip: "boolean", amount: "number"}}, + blocks: [ + {expression: "rate", value: "baseRate * 2"}, + {expression: "customer.fee", value: "customer.vip ? 0 : customer.amount * rate"}, + {expression: "summary", value: "'fee=' + string(customer.fee)"}, + ], + }, + cases: [ + [ + {baseRate: 1, customer: {vip: false, amount: 10}}, + {baseRate: 1, rate: 2, customer: {vip: false, amount: 10, fee: 20}, summary: "fee=20"}, + ], + [ + {baseRate: 1, customer: {vip: true, amount: 10}}, + {baseRate: 1, rate: 2, customer: {vip: true, amount: 10, fee: 0}, summary: "fee=0"}, + ], + [ + {baseRate: 2, customer: {vip: false, amount: 3}}, + {baseRate: 2, rate: 4, customer: {vip: false, amount: 3, fee: 12}, summary: "fee=12"}, + ], + ], +} + +// Globals read inside per-member blocks. +{ + name: "per-member blocks read globals", + policy: { + globals: {env: {threshold: "number"}}, + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > threshold"}, + {expression: "bigCount", value: "count(customer.companies, #.big)"}, + ], + }, + cases: [ + [ + {threshold: 100, customer: {companies: [{revenue: 50}, {revenue: 200}]}}, + {threshold: 100, customer: {companies: [{revenue: 50, big: false}, {revenue: 200, big: true}]}, bigCount: 1}, + ], + [ + {threshold: 10, customer: {companies: [{revenue: 50}, {revenue: 200}]}}, + {threshold: 10, customer: {companies: [{revenue: 50, big: true}, {revenue: 200, big: true}]}, bigCount: 2}, + ], + [ + {threshold: 0, customer: {companies: []}}, + {threshold: 0, customer: {companies: []}, bigCount: 0}, + ], + ], +} + +// A global relationship: the global property holds an entity, and blocks on that entity run on it. +{ + name: "global relationship property", + policy: { + globals: {env: {applicant: "person"}}, + models: {person: {age: "number"}}, + blocks: [ + {expression: "person.adult", value: "person.age >= 18"}, + {expression: "eligible", value: "applicant.adult"}, + ], + }, + cases: [ + [{applicant: {age: 30}}, {applicant: {age: 30, adult: true}, eligible: true}], + [{applicant: {age: 3}}, {applicant: {age: 3, adult: false}, eligible: false}], + [{applicant: {age: "x"}}, "!error: InputValidationFailed"], + [{applicant: 5}, "!error: InputValidationFailed"], + ], +} + +// A global array relationship: per-member blocks run over the global array. +{ + name: "global array relationship", + policy: { + globals: {env: {applicants: "person[]"}}, + models: {person: {age: "number"}}, + blocks: [ + {expression: "person.adult", value: "person.age >= 18"}, + {expression: "adults", value: "count(applicants, #.adult)"}, + ], + }, + cases: [ + [ + {applicants: [{age: 30}, {age: 10}]}, + {applicants: [{age: 30, adult: true}, {age: 10, adult: false}], adults: 1}, + ], + [{applicants: []}, {applicants: [], adults: 0}], + [ + {applicants: [{age: 18}]}, + {applicants: [{age: 18, adult: true}], adults: 1}, + ], + ], +} + +// A global reference resolved against the pool. +{ + name: "global reference property", + policy: { + globals: {env: {plan: "&product"}}, + models: {product: {id: "string", price: "number"}}, + blocks: [{expression: "price", value: "plan.price"}], + }, + cases: [ + [{plan: "p1", product: [{id: "p1", price: 9}]}, {plan: {id: "p1", price: 9}, price: 9, product: [{id: "p1", price: 9}]}], + [{plan: "p2", product: [{id: "p1", price: 9}, {id: "p2", price: 1}]}, {plan: {id: "p2", price: 1}, price: 1, product: [{id: "p1", price: 9}, {id: "p2", price: 1}]}], + [{plan: "zz", product: [{id: "p1", price: 9}]}, "!error: InputValidationFailed"], + ], +} + +// Two global models: their properties share the same top-level namespace. +{ + name: "two global models", + policy: { + globals: {a: {x: "number"}, b: {y: "number"}}, + blocks: [{expression: "sum", value: "x + y"}], + }, + cases: [ + [{x: 1, y: 2}, {x: 1, y: 2, sum: 3}], + [{x: -1, y: 1}, {x: -1, y: 1, sum: 0}], + [{x: 1}, "!error: MissingRequiredInputs"], + ], +} + +// Unknown top-level input keys pass through. +{ + name: "unknown top-level keys pass through", + policy: { + globals: {env: {rate: "number"}}, + blocks: [{expression: "double", value: "rate * 2"}], + }, + cases: [ + [{rate: 1, extra: "keep", nested: {a: [1]}}, {rate: 1, extra: "keep", nested: {a: [1]}, double: 2}], + [{rate: 2, double: 99}, {rate: 2, double: 4}], + ], +} + +// Goals on a global computed. +{ + name: "goals on global computeds", + policy: { + globals: {env: {rate: "number", other: "number"}}, + blocks: [ + {expression: "double", value: "rate * 2"}, + {expression: "triple", value: "other * 3"}, + ], + }, + cases: [ + {input: {rate: 2, other: 1}, goals: ["double"], output: {rate: 2, other: 1, double: 4}}, + {input: {rate: 2}, goals: ["double"], output: {rate: 2, double: 4}}, + {input: {rate: 2, other: 1}, goals: ["triple"], output: {rate: 2, other: 1, triple: 3}}, + {input: {rate: 2, other: 1}, goals: ["nope"], output: "!error: GoalNotFound"}, + ], +} + +// Writing a declared global: an InputOverride diagnostic, and the block is dropped at evaluation. +{ + name: "declared global written by a block", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + globals: {env: {rate: "number", label: "string?"}}, + blocks: [{expression: "label", value: "'rate ' + string(rate)"}], + }, + cases: [ + [ + {rate: 3}, + {rate: 3}, + "question: writing a declared global is an InputOverride error diagnostic; evaluation silently drops the block instead of refusing the policy", + ], + { + input: {rate: 3}, + goals: ["label"], + output: "!error: GoalNotFound", + note: "question: a declared-and-written global is not a goal, so naming it fails with GoalNotFound", + }, + ], +} + +// Optional global missing with a default in a nested expression. +{ + name: "optional globals with defaults", + policy: { + globals: {env: {discount: "number?", tags: "string[]?"}}, + models: {order: {total: "number"}}, + blocks: [ + {expression: "order.net", value: "order.total * (1 - (discount ?? 0))"}, + {expression: "order.tagged", value: "len(tags ?? []) > 0"}, + ], + }, + cases: [ + [{order: {total: 100}}, {order: {total: 100, net: 100, tagged: false}}], + [{order: {total: 100}, discount: 0.1, tags: ["a"]}, {order: {total: 100, net: 90, tagged: true}, discount: 0.1, tags: ["a"]}], + [{order: {total: 100}, discount: null, tags: null}, {order: {total: 100, net: 100, tagged: false}, discount: null, tags: null}], + [{order: {total: 100}, tags: []}, {order: {total: 100, net: 100, tagged: false}, tags: []}], + ], +} + +// Nested computed globals: the write path creates the parent object. +{ + name: "nested computed global paths", + policy: { + globals: {env: {a: "number", b: "number"}}, + blocks: [ + {expression: "totals.sum", value: "a + b"}, + {expression: "totals.diff", value: "a - b"}, + {expression: "report", value: "totals.sum * 2"}, + ], + }, + cases: [ + [{a: 3, b: 1}, {a: 3, b: 1, totals: {sum: 4, diff: 2}, report: 8}, "bug: totals.diff is dropped: once totals.sum is read by another block, the sibling nested write is no longer a terminal sink and never runs (same on entity paths like c.totals.diff)"], + [{a: 0, b: 0}, {a: 0, b: 0, totals: {sum: 0, diff: 0}, report: 0}, "bug: totals.diff is dropped: once totals.sum is read by another block, the sibling nested write is no longer a terminal sink and never runs (same on entity paths like c.totals.diff)"], + {input: {a: 3, b: 1}, goals: ["totals.diff", "report"], output: {a: 3, b: 1, totals: {sum: 4, diff: 2}, report: 8}}, + [{a: -1, b: 2.5}, {a: -1, b: 2.5, totals: {sum: 1.5, diff: -3.5}, report: 3}, "bug: totals.diff is dropped: once totals.sum is read by another block, the sibling nested write is no longer a terminal sink and never runs (same on entity paths like c.totals.diff)"], + ], +} + +// A global and an entity property with the same name are different paths. +{ + name: "global and entity property with the same name", + policy: { + globals: {env: {limit: "number"}}, + models: {customer: {limit: "number"}}, + blocks: [{expression: "customer.effective", value: "min([customer.limit, limit])"}], + }, + cases: [ + [{limit: 100, customer: {limit: 50}}, {limit: 100, customer: {limit: 50, effective: 50}}], + [{limit: 10, customer: {limit: 50}}, {limit: 10, customer: {limit: 50, effective: 10}}], + [{customer: {limit: 50}}, "!error: MissingRequiredInputs"], + ], +} diff --git a/core/engine/tests/spec/policy/12-dictionaries.json5 b/core/engine/tests/spec/policy/12-dictionaries.json5 new file mode 100644 index 00000000..5872f852 --- /dev/null +++ b/core/engine/tests/spec/policy/12-dictionaries.json5 @@ -0,0 +1,414 @@ +// Dictionaries and enum-typed properties. A dictionary is a named list of string values with +// labels; a property typed with the dictionary's name (shorthand: the dictionary name as the type) +// accepts only those values. Inline enums (`string(a|b)`) behave the same. At evaluation both are +// plain strings: validation rejects values outside the set, labels never reach the output, and +// computed (undeclared) properties are not checked against any set. + +// A dictionary-typed property: members pass, values compare as plain strings. +{ + name: "dictionary-typed property", + policy: { + dictionaries: {tier: [["VIP", "Very important"], ["STD", "Standard"]]}, + models: {customer: {tier: "tier"}}, + blocks: [{expression: "customer.isVip", value: "customer.tier == 'VIP'"}], + }, + cases: [ + [{customer: {tier: "VIP"}}, {customer: {tier: "VIP", isVip: true}}], + [{customer: {tier: "STD"}}, {customer: {tier: "STD", isVip: false}}], + [{customer: {tier: "GOLD"}}, "!error: InputValidationFailed"], + [{customer: {tier: "vip"}}, "!error: InputValidationFailed"], + [{customer: {tier: "Very important"}}, "!error: InputValidationFailed"], + [{customer: {tier: ""}}, "!error: InputValidationFailed"], + [{customer: {tier: " VIP"}}, "!error: InputValidationFailed"], + [{customer: {tier: 1}}, "!error: InputValidationFailed"], + [{customer: {tier: true}}, "!error: InputValidationFailed"], + [{customer: {tier: ["VIP"]}}, "!error: InputValidationFailed"], + [{customer: {tier: {value: "VIP"}}}, "!error: InputValidationFailed"], + ], +} + +// Labels are metadata only: the output keeps the value. +{ + name: "labels do not appear in the output", + policy: { + dictionaries: {status: [["A", "Active"], ["C", "Closed"]]}, + models: {account: {status: "status"}}, + blocks: [{expression: "account.copy", value: "account.status"}], + }, + cases: [ + [{account: {status: "A"}}, {account: {status: "A", copy: "A"}}], + [{account: {status: "C"}}, {account: {status: "C", copy: "C"}}], + [{account: {status: "Active"}}, "!error: InputValidationFailed"], + ], +} + +// Dictionary entries without a separate label (label equals value). +{ + name: "dictionary with plain entries", + policy: { + dictionaries: {color: ["red", "green", "blue"]}, + models: {item: {color: "color"}}, + blocks: [{match: "item.warm", arms: [["item.color == 'red'", "true"], ["", "false"]]}], + }, + cases: [ + [{item: {color: "red"}}, {item: {color: "red", warm: true}}], + [{item: {color: "green"}}, {item: {color: "green", warm: false}}], + [{item: {color: "blue"}}, {item: {color: "blue", warm: false}}], + [{item: {color: "yellow"}}, "!error: InputValidationFailed"], + ], +} + +// Dictionary values with spaces, punctuation and digits are matched exactly. +{ + name: "dictionary values are exact strings", + policy: { + dictionaries: {code: ["A-1", "b c", "007", "Ünï"]}, + models: {row: {code: "code"}}, + blocks: [{expression: "row.copy", value: "row.code + '!'"}], + }, + cases: [ + [{row: {code: "A-1"}}, {row: {code: "A-1", copy: "A-1!"}}], + [{row: {code: "b c"}}, {row: {code: "b c", copy: "b c!"}}], + [{row: {code: "007"}}, {row: {code: "007", copy: "007!"}}], + [{row: {code: "Ünï"}}, {row: {code: "Ünï", copy: "Ünï!"}}], + [{row: {code: 7}}, "!error: InputValidationFailed"], + [{row: {code: "7"}}, "!error: InputValidationFailed"], + [{row: {code: "bc"}}, "!error: InputValidationFailed"], + ], +} + +// Optional dictionary-typed property: null and missing are allowed. +{ + name: "optional dictionary property", + policy: { + dictionaries: {tier: ["VIP", "STD"]}, + models: {customer: {name: "string", tier: "tier?"}}, + blocks: [{expression: "customer.label", value: "customer.tier ?? 'none'"}], + }, + cases: [ + [{customer: {name: "a", tier: "VIP"}}, {customer: {name: "a", tier: "VIP", label: "VIP"}}], + [{customer: {name: "a"}}, {customer: {name: "a", label: "none"}}], + [{customer: {name: "a", tier: null}}, {customer: {name: "a", tier: null, label: "none"}}], + [{customer: {name: "a", tier: "X"}}, "!error: InputValidationFailed"], + ], +} + +// Required dictionary property missing: a missing input once a block reads it. +{ + name: "required dictionary property missing", + policy: { + dictionaries: {tier: ["VIP", "STD"]}, + models: {customer: {name: "string", tier: "tier"}}, + blocks: [{expression: "customer.isVip", value: "customer.tier == 'VIP'"}], + }, + cases: [ + [{customer: {name: "a", tier: "STD"}}, {customer: {name: "a", tier: "STD", isVip: false}}], + [{customer: {name: "a"}}, "!error: MissingRequiredInputs"], + [{customer: {name: "a", tier: null}}, "!error: MissingRequiredInputs"], + ], +} + +// Arrays of dictionary values: each element is checked, null elements are skipped. +{ + name: "dictionary-typed arrays", + policy: { + dictionaries: {tier: ["VIP", "STD"]}, + models: {customer: {tiers: "tier[]"}}, + blocks: [ + {expression: "customer.first", value: "customer.tiers[0]"}, + {expression: "customer.vipCount", value: "count(customer.tiers, # == 'VIP')"}, + ], + }, + cases: [ + [{customer: {tiers: ["VIP", "STD", "VIP"]}}, {customer: {tiers: ["VIP", "STD", "VIP"], first: "VIP", vipCount: 2}}], + [{customer: {tiers: []}}, {customer: {tiers: [], first: null, vipCount: 0}}], + [{customer: {tiers: ["STD", null]}}, {customer: {tiers: ["STD", null], first: "STD", vipCount: 0}}], + [{customer: {tiers: ["VIP", "GOLD"]}}, "!error: InputValidationFailed"], + [{customer: {tiers: [42]}}, "!error: InputValidationFailed"], + [{customer: {tiers: "VIP"}}, "!error: InputValidationFailed"], + ], +} + +// Dictionary-typed globals. +{ + name: "dictionary-typed global", + policy: { + dictionaries: {tier: ["VIP", "STD"]}, + globals: {env: {defaultTier: "tier?"}}, + models: {customer: {tier: "tier?"}}, + blocks: [{expression: "customer.effective", value: "customer.tier ?? defaultTier ?? 'STD'"}], + }, + cases: [ + [{customer: {tier: "VIP"}, defaultTier: "STD"}, {customer: {tier: "VIP", effective: "VIP"}, defaultTier: "STD"}], + [{customer: {}, defaultTier: "VIP"}, {customer: {effective: "VIP"}, defaultTier: "VIP"}], + [{customer: {}}, {customer: {effective: "STD"}}], + [{customer: {}, defaultTier: "GOLD"}, "!error: InputValidationFailed"], + [{customer: {}, defaultTier: 1}, "!error: InputValidationFailed"], + ], +} + +// Dictionary-typed property on relationship members: every member is validated. +{ + name: "dictionary-typed member property", + policy: { + dictionaries: {risk: ["low", "mid", "high"]}, + models: {customer: {companies: "company[]"}, company: {risk: "risk"}}, + blocks: [ + {expression: "company.weight", value: "company.risk == 'high' ? 3 : company.risk == 'mid' ? 2 : 1"}, + {expression: "customer.weight", value: "sum(map(customer.companies, #.weight))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{risk: "low"}, {risk: "high"}]}}, + {customer: {companies: [{risk: "low", weight: 1}, {risk: "high", weight: 3}], weight: 4}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], weight: 0}}], + [{customer: {companies: [{risk: "mid"}, {risk: "extreme"}]}}, "!error: InputValidationFailed"], + ], +} + +// Dictionary values feed a decision table. +{ + name: "decision table over a dictionary property", + policy: { + dictionaries: {tier: ["VIP", "STD", "NEW"]}, + models: {customer: {tier: "tier", spend: "number"}}, + blocks: [ + {table: "t", inputs: ["customer.tier", "customer.spend"], outputs: ["customer.discount"], rules: [ + ["'VIP'", "", "0.2"], + ["'STD'", ">= 1000", "0.1"], + ["", "", "0"], + ]}, + ], + }, + cases: [ + [{customer: {tier: "VIP", spend: 0}}, {customer: {tier: "VIP", spend: 0, discount: 0.2}}], + [{customer: {tier: "STD", spend: 1000}}, {customer: {tier: "STD", spend: 1000, discount: 0.1}}], + [{customer: {tier: "STD", spend: 999}}, {customer: {tier: "STD", spend: 999, discount: 0}}], + [{customer: {tier: "NEW", spend: 5000}}, {customer: {tier: "NEW", spend: 5000, discount: 0}}], + [{customer: {tier: "OLD", spend: 5000}}, "!error: InputValidationFailed"], + ], +} + +// A match over every dictionary value, with a default arm. +{ + name: "match over every dictionary value", + policy: { + dictionaries: {tier: ["VIP", "STD"]}, + models: {customer: {tier: "tier"}}, + blocks: [{match: "customer.limit", arms: [["customer.tier == 'VIP'", "1000"], ["customer.tier == 'STD'", "100"], ["", "0"]]}], + }, + cases: [ + [{customer: {tier: "VIP"}}, {customer: {tier: "VIP", limit: 1000}}], + [{customer: {tier: "STD"}}, {customer: {tier: "STD", limit: 100}}], + [{customer: {tier: "X"}}, "!error: InputValidationFailed"], + ], +} + +// Computed properties are not checked against a dictionary, even when they hold dictionary-like +// values. +{ + name: "computed values outside any dictionary", + policy: { + dictionaries: {tier: ["gold", "silver"]}, + models: {customer: {score: "number"}}, + blocks: [{expression: "customer.tier", value: "customer.score > 5 ? 'gold' : 'bronze'"}], + }, + cases: [ + [{customer: {score: 6}}, {customer: {score: 6, tier: "gold"}}], + [{customer: {score: 1}}, {customer: {score: 1, tier: "bronze"}}], + [{customer: {score: 5}}, {customer: {score: 5, tier: "bronze"}}], + ], +} + +// A computed property copied from a dictionary-typed input stays a plain string. +{ + name: "dictionary values flow into computeds unchanged", + policy: { + dictionaries: {tier: [["VIP", "Very important"], ["STD", "Standard"]]}, + models: {customer: {tier: "tier"}}, + blocks: [ + {expression: "customer.lower", value: "lower(customer.tier)"}, + {expression: "customer.tiers", value: "[customer.tier, customer.tier]"}, + ], + }, + cases: [ + [{customer: {tier: "VIP"}}, {customer: {tier: "VIP", lower: "vip", tiers: ["VIP", "VIP"]}}], + [{customer: {tier: "STD"}}, {customer: {tier: "STD", lower: "std", tiers: ["STD", "STD"]}}], + ], +} + +// An input key named like a dictionary is plain data; dictionaries are not values in expressions. +{ + name: "dictionary names are not variables", + diagnostics: ["TYPE_MISMATCH", "UNDEFINED_VARIABLE"], + policy: { + dictionaries: {tier: ["VIP", "STD"]}, + blocks: [{expression: "echo", value: "tier"}], + }, + cases: [ + [{tier: "boom"}, {tier: "boom", echo: "boom"}], + [{tier: 1}, {tier: 1, echo: 1}], + [{}, "!error: MissingRequiredInputs"], + ], +} + +// A dictionary with a single entry. +{ + name: "single-entry dictionary", + policy: { + dictionaries: {only: ["X"]}, + models: {row: {v: "only"}}, + blocks: [{expression: "row.ok", value: "row.v == 'X'"}], + }, + cases: [ + [{row: {v: "X"}}, {row: {v: "X", ok: true}}], + [{row: {v: "Y"}}, "!error: InputValidationFailed"], + [{row: {v: "x"}}, "!error: InputValidationFailed"], + ], +} + +// An empty dictionary admits no value. +{ + name: "empty dictionary", + policy: { + dictionaries: {none: []}, + models: {row: {v: "none?", n: "number"}}, + blocks: [{expression: "row.double", value: "row.n * 2"}], + }, + cases: [ + [{row: {n: 1}}, {row: {n: 1, double: 2}}], + [{row: {n: 1, v: null}}, {row: {n: 1, v: null, double: 2}}], + [{row: {n: 1, v: "anything"}}, "!error: InputValidationFailed"], + [{row: {n: 1, v: ""}}, "!error: InputValidationFailed"], + ], +} + +// A dictionary declared in an imported policy types properties in the importing policy. +{ + name: "dictionary from an imported policy", + policy: { + imports: ["shared"], + models: {customer: {tier: "tier"}}, + blocks: [{expression: "customer.isVip", value: "customer.tier == 'VIP'"}], + }, + policies: {shared: {dictionaries: {tier: ["VIP", "STD"]}}}, + cases: [ + [{customer: {tier: "VIP"}}, {customer: {tier: "VIP", isVip: true}}], + [{customer: {tier: "STD"}}, {customer: {tier: "STD", isVip: false}}], + [{customer: {tier: "GOLD"}}, "!error: InputValidationFailed"], + ], +} + +// Inline enums (`string(a|b)`). +{ + name: "inline enum property", + policy: { + models: {customer: {status: "string(active|closed)"}}, + blocks: [{expression: "customer.open", value: "customer.status == 'active'"}], + }, + cases: [ + [{customer: {status: "active"}}, {customer: {status: "active", open: true}}], + [{customer: {status: "closed"}}, {customer: {status: "closed", open: false}}], + [{customer: {status: "Active"}}, "!error: InputValidationFailed"], + [{customer: {status: "pending"}}, "!error: InputValidationFailed"], + [{customer: {status: ""}}, "!error: InputValidationFailed"], + [{customer: {status: 0}}, "!error: InputValidationFailed"], + [{customer: {status: null}}, "!error: MissingRequiredInputs"], + ], +} + +// Inline enum arrays and optional enums. +{ + name: "inline enum arrays and optionals", + policy: { + models: {user: {roles: "string(admin|editor|viewer)[]", plan: "string(free|pro)?"}}, + blocks: [ + {expression: "user.isAdmin", value: "'admin' in user.roles"}, + {expression: "user.paid", value: "(user.plan ?? 'free') == 'pro'"}, + ], + }, + cases: [ + [{user: {roles: ["admin", "viewer"], plan: "pro"}}, {user: {roles: ["admin", "viewer"], plan: "pro", isAdmin: true, paid: true}}], + [{user: {roles: []}}, {user: {roles: [], isAdmin: false, paid: false}}], + [{user: {roles: ["viewer"], plan: null}}, {user: {roles: ["viewer"], plan: null, isAdmin: false, paid: false}}], + [{user: {roles: ["root"]}}, "!error: InputValidationFailed"], + [{user: {roles: ["admin"], plan: "enterprise"}}, "!error: InputValidationFailed"], + [{user: {roles: "admin"}}, "!error: InputValidationFailed"], + ], +} + +// Inline enum on relationship members, used by a per-member match. +{ + name: "inline enum on members with a per-member match", + policy: { + models: {customer: {companies: "company[]"}, company: {region: "string(us|eu)", revenue: "number"}}, + blocks: [ + {match: "company.bonus", arms: [["company.region == 'us'", "company.revenue * 2"], ["company.region == 'eu'", "company.revenue * 3"], ["", "0"]]}, + ], + }, + cases: [ + [ + {customer: {companies: [{region: "us", revenue: 10}, {region: "eu", revenue: 10}]}}, + {customer: {companies: [{region: "us", revenue: 10, bonus: 20}, {region: "eu", revenue: 10, bonus: 30}]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + [{customer: {companies: [{region: "apac", revenue: 10}]}}, "!error: InputValidationFailed"], + ], +} + +// Inline enum global. +{ + name: "inline enum global with a table", + policy: { + globals: {env: {channel: "string(web|branch|phone)"}}, + blocks: [ + {table: "t", inputs: ["channel"], outputs: ["fee"], rules: [ + ["'web'", "0"], + ["'branch'", "5"], + ["", "2"], + ]}, + ], + }, + cases: [ + [{channel: "web"}, {channel: "web", fee: 0}], + [{channel: "branch"}, {channel: "branch", fee: 5}], + [{channel: "phone"}, {channel: "phone", fee: 2}], + [{channel: "fax"}, "!error: InputValidationFailed"], + ], +} + +// Dictionaries and enums are checked before evaluation: every invalid field is reported at once, +// and no block runs. +{ + name: "validation reports before any block runs", + policy: { + dictionaries: {tier: ["VIP", "STD"]}, + models: {customer: {tier: "tier", status: "string(on|off)", n: "number"}}, + blocks: [{expression: "customer.double", value: "customer.n * 2"}], + }, + cases: [ + [{customer: {tier: "VIP", status: "on", n: 1}}, {customer: {tier: "VIP", status: "on", n: 1, double: 2}}], + [{customer: {tier: "X", status: "on", n: 1}}, "!error: customer.tier"], + [{customer: {tier: "VIP", status: "x", n: 1}}, "!error: customer.status"], + [{customer: {tier: "X", status: "x", n: 1}}, "!error: customer.status"], + [{customer: {tier: "X", status: "x", n: 1}}, "!error: customer.tier"], + [{customer: {tier: "X", status: "on"}}, "!error: InputValidationFailed"], + ], +} + +// A property type naming neither an entity nor a dictionary is treated as a relationship to an +// unknown entity: any object passes, scalars fail. +{ + name: "type naming no dictionary", + diagnostics: ["UNDEFINED_VARIABLE", "UNKNOWN_DATA_MODEL_TARGET"], + policy: { + models: {customer: {tier: "tierr"}}, + blocks: [{expression: "customer.seen", value: "customer.tier != null"}], + }, + cases: [ + [{customer: {tier: "VIP"}}, "!error: InputValidationFailed"], + [{customer: {tier: {anything: 1}}}, {customer: {tier: {anything: 1}, seen: true}}], + ], +} diff --git a/core/engine/tests/spec/policy/13-imports.json5 b/core/engine/tests/spec/policy/13-imports.json5 new file mode 100644 index 00000000..3ab53aa4 --- /dev/null +++ b/core/engine/tests/spec/policy/13-imports.json5 @@ -0,0 +1,700 @@ +// Multi-policy workspaces. A policy names other workspace documents in `imports`; the +// importer and everything it imports transitively form one evaluation unit. Blocks of every +// member run (every terminal write of the unit is a root), models and globals merge across +// members, and reads resolve against writers anywhere in the unit. + +// --- A single import: the imported writer feeds the importer ----------------------------- + +{ + name: "an imported block's write is visible to the importer", + policy: { + imports: ["base"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.score", value: "customer.base + 1"}], + }, + policies: { + base: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.base", value: "customer.age * 2"}], + }, + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, base: 40, score: 41}}], + [{customer: {age: 0}}, {customer: {age: 0, base: 0, score: 1}}], + [{customer: {age: -3}}, {customer: {age: -3, base: -6, score: -5}}], + [{customer: {age: 20.5}}, {customer: {age: 20.5, base: 41, score: 42}}], + [{customer: {age: 0.1}}, {customer: {age: 0.1, base: 0.2, score: 1.2}}], + ], +} + +{ + name: "missing input of the imported writer is reported for the importer's goal", + policy: { + imports: ["base"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.score", value: "customer.base + 1"}], + }, + policies: { + base: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.base", value: "customer.age * 2"}], + }, + }, + cases: [ + [{customer: {}}, "!error: MissingRequiredInputs"], + [{customer: {age: null}}, "!error: MissingRequiredInputs"], + [{}, "!error: MissingRequiredInputs"], + [{customer: {age: "x"}}, "!error: InputValidationFailed"], + [{customer: {age: 7}}, {customer: {age: 7, base: 14, score: 15}}], + ], +} + +// --- Imported blocks run even when nothing in the importer reads them -------------------- + +{ + name: "blocks of an imported policy run without being read", + policy: { + imports: ["extras"], + models: {customer: {age: "number", income: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + policies: { + extras: { + models: {customer: {income: "number"}}, + blocks: [{expression: "customer.rich", value: "customer.income > 1000"}], + }, + }, + cases: [ + [{customer: {age: 20, income: 5000}}, {customer: {age: 20, income: 5000, adult: true, rich: true}}], + [{customer: {age: 10, income: 0}}, {customer: {age: 10, income: 0, adult: false, rich: false}}], + [{customer: {age: 18, income: 1000}}, {customer: {age: 18, income: 1000, adult: true, rich: false}}], + [{customer: {age: 18}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "an imported policy with only a data model contributes validation, no writes", + policy: { + imports: ["schema"], + blocks: [{expression: "customer.next", value: "customer.age + 1"}], + }, + policies: { + schema: {models: {customer: {age: "number", name: "string"}}, blocks: []}, + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, next: 21}}], + [{customer: {age: 20, name: "Ann"}}, {customer: {age: 20, name: "Ann", next: 21}}], + [{customer: {age: "20"}}, "!error: InputValidationFailed"], + [{customer: {age: 1, name: 5}}, "!error: InputValidationFailed"], + [{customer: {}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Chains: imports are transitive ------------------------------------------------------ + +{ + name: "a chain of imports: main reads values from every level", + policy: { + imports: ["mid"], + blocks: [{expression: "customer.score", value: "customer.base + customer.mid"}], + }, + policies: { + mid: {imports: ["base"], blocks: [{expression: "customer.mid", value: "customer.base * 10"}]}, + base: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.base", value: "customer.age * 2"}]}, + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, base: 40, mid: 400, score: 440}}], + [{customer: {age: 0}}, {customer: {age: 0, base: 0, mid: 0, score: 0}}], + [{customer: {age: 1.5}}, {customer: {age: 1.5, base: 3, mid: 30, score: 33}}], + [{customer: {age: "1"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a four-level chain mixing a table, a match and an assertion", + policy: { + imports: ["approval"], + blocks: [{expression: "customer.summary", value: "customer.band + ':' + customer.tier + ':' + string(customer.approved)"}], + }, + policies: { + approval: { + imports: ["tiering"], + blocks: [{assertion: "customer.approved", conditions: ["customer.tier != 'none'", "customer.age < 100"]}], + }, + tiering: { + imports: ["banding"], + blocks: [{match: "customer.tier", arms: [["customer.band == 'senior'", "'gold'"], ["customer.band == 'adult'", "'silver'"], ["", "'none'"]]}], + }, + banding: { + models: {customer: {age: "number"}}, + blocks: [{table: "bands", inputs: ["customer.age"], outputs: ["customer.band"], rules: [[">= 65", "'senior'"], [">= 18", "'adult'"], ["", "'minor'"]]}], + }, + }, + cases: [ + [{customer: {age: 70}}, {customer: {age: 70, band: "senior", tier: "gold", approved: true, summary: "senior:gold:true"}}], + [{customer: {age: 30}}, {customer: {age: 30, band: "adult", tier: "silver", approved: true, summary: "adult:silver:true"}}], + [{customer: {age: 10}}, {customer: {age: 10, band: "minor", tier: "none", approved: false, summary: "minor:none:false"}}], + [{customer: {age: 120}}, {customer: {age: 120, band: "senior", tier: "gold", approved: false, summary: "senior:gold:false"}}], + [{customer: {age: 18}}, {customer: {age: 18, band: "adult", tier: "silver", approved: true, summary: "adult:silver:true"}}], + ], +} + +// --- Diamonds: two importers share one base ---------------------------------------------- + +{ + name: "diamond: both branches read the shared base and main joins them", + policy: { + imports: ["left", "right"], + blocks: [{expression: "customer.joined", value: "customer.l + customer.r"}], + }, + policies: { + left: {imports: ["shared"], blocks: [{expression: "customer.l", value: "customer.norm * 2"}]}, + right: {imports: ["shared"], blocks: [{expression: "customer.r", value: "customer.norm + 1"}]}, + shared: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.norm", value: "customer.age / 10"}]}, + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, norm: 2, l: 4, r: 3, joined: 7}}], + [{customer: {age: 0}}, {customer: {age: 0, norm: 0, l: 0, r: 1, joined: 1}}], + [{customer: {age: 5}}, {customer: {age: 5, norm: 0.5, l: 1, r: 1.5, joined: 2.5}}], + [{customer: {age: -10}}, {customer: {age: -10, norm: -1, l: -2, r: 0, joined: -2}}], + [{customer: {}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "diamond: the branches only write, main reads nothing of them", + policy: { + imports: ["left", "right"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.own", value: "customer.age"}], + }, + policies: { + left: {imports: ["shared"], blocks: [{expression: "customer.l", value: "customer.norm > 1"}]}, + right: {imports: ["shared"], blocks: [{expression: "customer.r", value: "customer.norm < 1"}]}, + shared: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.norm", value: "customer.age / 10"}]}, + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, own: 20, norm: 2, l: true, r: false}}], + [{customer: {age: 10}}, {customer: {age: 10, own: 10, norm: 1, l: false, r: false}}], + [{customer: {age: 3}}, {customer: {age: 3, own: 3, norm: 0.3, l: false, r: true}}], + ], +} + +{ + name: "importing the same policy twice and through two paths changes nothing", + policy: { + imports: ["base", "base", "mid"], + blocks: [{expression: "customer.total", value: "customer.base + customer.mid"}], + }, + policies: { + mid: {imports: ["base"], blocks: [{expression: "customer.mid", value: "customer.base * 3"}]}, + base: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.base", value: "customer.age + 1"}]}, + }, + cases: [ + [{customer: {age: 1}}, {customer: {age: 1, base: 2, mid: 6, total: 8}}], + [{customer: {age: 9}}, {customer: {age: 9, base: 10, mid: 30, total: 40}}], + [{customer: {age: -1}}, {customer: {age: -1, base: 0, mid: 0, total: 0}}], + ], +} + +{ + name: "import order does not change the result", + policy: { + imports: ["second", "first"], + blocks: [{expression: "customer.both", value: "customer.a + customer.b"}], + }, + policies: { + first: {models: {customer: {x: "number"}}, blocks: [{expression: "customer.a", value: "customer.x * 2"}]}, + second: {models: {customer: {x: "number"}}, blocks: [{expression: "customer.b", value: "customer.a + 1"}]}, + }, + cases: [ + [{customer: {x: 1}}, {customer: {x: 1, a: 2, b: 3, both: 5}}], + [{customer: {x: 0}}, {customer: {x: 0, a: 0, b: 1, both: 1}}], + [{customer: {x: 2.25}}, {customer: {x: 2.25, a: 4.5, b: 5.5, both: 10}}], + ], +} + +{ + name: "siblings in one unit read each other's writes without importing each other", + policy: { + imports: ["first", "second"], + blocks: [], + }, + policies: { + first: {models: {customer: {x: "number"}}, blocks: [{expression: "customer.a", value: "customer.b * 2"}]}, + second: {models: {customer: {x: "number"}}, blocks: [{expression: "customer.b", value: "customer.x + 1"}]}, + }, + cases: [ + [{customer: {x: 1}}, {customer: {x: 1, a: 4, b: 2}}], + [{customer: {x: 0}}, {customer: {x: 0, a: 2, b: 1}}], + [{customer: {x: -1}}, {customer: {x: -1, a: 0, b: 0}}], + ], +} + +// --- Shared and merged models ------------------------------------------------------------- + +{ + name: "a model declared only in an imported policy types the importer's reads", + policy: { + imports: ["schema"], + blocks: [{expression: "customer.score", value: "customer.age + 1"}], + }, + policies: { + schema: {models: {customer: {age: "number"}}, blocks: []}, + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, score: 21}}], + [{customer: {age: 0}}, {customer: {age: 0, score: 1}}], + [{customer: {age: "x"}}, "!error: InputValidationFailed"], + [{customer: {age: true}}, "!error: InputValidationFailed"], + [{customer: {}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "the same entity declared in two policies merges its properties", + policy: { + imports: ["base"], + models: {customer: {age: "number", name: "string"}}, + blocks: [{expression: "customer.label", value: "customer.name + '#' + string(customer.base)"}], + }, + policies: { + base: {models: {customer: {age: "number", vip: "boolean"}}, blocks: [{expression: "customer.base", value: "customer.vip ? customer.age * 2 : customer.age"}]}, + }, + cases: [ + [{customer: {age: 20, name: "a", vip: true}}, {customer: {age: 20, name: "a", vip: true, base: 40, label: "a#40"}}], + [{customer: {age: 20, name: "b", vip: false}}, {customer: {age: 20, name: "b", vip: false, base: 20, label: "b#20"}}], + [{customer: {age: 20, name: 1, vip: false}}, "!error: InputValidationFailed"], + [{customer: {age: 20, name: "c", vip: "yes"}}, "!error: InputValidationFailed"], + [{customer: {age: 20, name: "d"}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "an entity split across policies with relationships", + policy: { + imports: ["companies"], + models: {customer: {name: "string", companies: "company[]"}}, + blocks: [{expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}], + }, + policies: { + companies: {models: {company: {revenue: "number"}}, blocks: []}, + }, + cases: [ + [{customer: {name: "a", companies: [{revenue: 1}, {revenue: 2}]}}, {customer: {name: "a", companies: [{revenue: 1}, {revenue: 2}], total: 3}}], + [{customer: {name: "b", companies: []}}, {customer: {name: "b", companies: [], total: 0}}], + [{customer: {name: "c", companies: [{revenue: "1"}]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "globals declared in an imported policy are top-level inputs", + policy: { + imports: ["base"], + blocks: [{expression: "total", value: "rate * 100"}], + }, + policies: { + base: {globals: {platform: {factor: "number"}}, blocks: [{expression: "rate", value: "factor / 2"}]}, + }, + cases: [ + [{factor: 3}, {factor: 3, rate: 1.5, total: 150}], + [{factor: 0}, {factor: 0, rate: 0, total: 0}], + [{factor: -0.02}, {factor: -0.02, rate: -0.01, total: -1}], + [{factor: "3"}, "!error: InputValidationFailed"], + [{}, "!error: MissingRequiredInputs"], + [{platform: {factor: 3}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "the importer reads a global declared in an imported policy", + policy: { + imports: ["base"], + models: {order: {amount: "number"}}, + blocks: [{expression: "order.taxed", value: "order.amount * (1 + taxRate)"}], + }, + policies: { + base: {globals: {platform: {taxRate: "number"}}, blocks: []}, + }, + cases: [ + [{taxRate: 0.2, order: {amount: 100}}, {taxRate: 0.2, order: {amount: 100, taxed: 120}}], + [{taxRate: 0, order: {amount: 100}}, {taxRate: 0, order: {amount: 100, taxed: 100}}], + [{taxRate: "0.2", order: {amount: 100}}, "!error: InputValidationFailed"], + [{order: {amount: 100}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Computed properties defined in imported policies ------------------------------------- + +{ + name: "an undeclared computed property written in an imported policy", + policy: { + imports: ["base"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.score", value: "customer.adult ? 1 : 0"}], + }, + policies: { + base: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.adult", value: "customer.age >= 18"}]}, + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, adult: true, score: 1}}], + [{customer: {age: 17}}, {customer: {age: 17, adult: false, score: 0}}], + [{customer: {age: 18}}, {customer: {age: 18, adult: true, score: 1}}], + ], +} + +{ + name: "an imported computed property supplied in the input is overwritten by its writer", + policy: { + imports: ["base"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.score", value: "customer.adult ? 1 : 0"}], + }, + policies: { + base: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.adult", value: "customer.age >= 18"}]}, + }, + cases: [ + [{customer: {age: 20, adult: false}}, {customer: {age: 20, adult: true, score: 1}}], + [{customer: {age: 5, adult: true}}, {customer: {age: 5, adult: false, score: 0}}], + [{customer: {age: 5, adult: "junk"}}, {customer: {age: 5, adult: false, score: 0}}], + ], +} + +{ + name: "a computed property that is also declared in the imported model is treated as input", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + imports: ["base"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.score", value: "customer.adult ? 1 : 0"}], + }, + policies: { + base: {models: {customer: {age: "number", adult: "boolean"}}, blocks: [{expression: "customer.adult", value: "customer.age >= 18"}]}, + }, + cases: [ + {input: {customer: {age: 20}}, output: "!error: MissingRequiredInputs", note: "question: writing a declared model property is an InputOverride error diagnostic; the driver still evaluates, requires the property as input and drops the block's write"}, + {input: {customer: {age: 20, adult: false}}, output: {customer: {age: 20, adult: false, score: 0}}, note: "question: the input value wins over the imported block's write (customer.age >= 18 would give true)"}, + {input: {customer: {age: 5, adult: true}}, output: {customer: {age: 5, adult: true, score: 1}}, note: "question: the input value wins over the imported block's write"}, + ], +} + +{ + name: "an imported match result drives the importer's table", + policy: { + imports: ["tiers"], + blocks: [{table: "discounts", inputs: ["customer.tier", "customer.spend"], outputs: ["customer.discount"], rules: [ + ["'gold'", ">= 1000", "0.2"], + ["'gold'", "", "0.1"], + ["'silver'", "", "0.05"], + ["", "", "0"], + ]}], + }, + policies: { + tiers: { + models: {customer: {points: "number", spend: "number"}}, + blocks: [{match: "customer.tier", arms: [["customer.points >= 100", "'gold'"], ["customer.points >= 50", "'silver'"], ["", "'bronze'"]]}], + }, + }, + cases: [ + [{customer: {points: 150, spend: 2000}}, {customer: {points: 150, spend: 2000, tier: "gold", discount: 0.2}}], + [{customer: {points: 150, spend: 10}}, {customer: {points: 150, spend: 10, tier: "gold", discount: 0.1}}], + [{customer: {points: 50, spend: 5000}}, {customer: {points: 50, spend: 5000, tier: "silver", discount: 0.05}}], + [{customer: {points: 0, spend: 5000}}, {customer: {points: 0, spend: 5000, tier: "bronze", discount: 0}}], + [{customer: {points: 99.9, spend: 1}}, {customer: {points: 99.9, spend: 1, tier: "silver", discount: 0.05}}], + ], +} + +{ + name: "an imported table result feeds the importer's assertion", + policy: { + imports: ["pricing"], + blocks: [{assertion: "customer.approved", conditions: ["customer.basePrice > 0", "customer.basePrice <= customer.budget"]}], + }, + policies: { + pricing: { + models: {customer: {age: "number", budget: "number"}}, + blocks: [{table: "prices", inputs: ["customer.age"], outputs: ["customer.basePrice"], rules: [[">= 65", "80"], [">= 18", "100"], ["", "0"]]}], + }, + }, + cases: [ + [{customer: {age: 35, budget: 100}}, {customer: {age: 35, budget: 100, basePrice: 100, approved: true}}], + [{customer: {age: 35, budget: 99}}, {customer: {age: 35, budget: 99, basePrice: 100, approved: false}}], + [{customer: {age: 70, budget: 90}}, {customer: {age: 70, budget: 90, basePrice: 80, approved: true}}], + [{customer: {age: 5, budget: 1000}}, {customer: {age: 5, budget: 1000, basePrice: 0, approved: false}}], + ], +} + +{ + name: "per-instance writes in an imported policy are aggregated by the importer", + policy: { + imports: ["base"], + blocks: [{expression: "customer.bigCount", value: "count(customer.companies, #.big)"}], + }, + policies: { + base: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + }, + cases: [ + [{customer: {companies: [{revenue: 5}, {revenue: 500}]}}, {customer: {bigCount: 1, companies: [{big: false, revenue: 5}, {big: true, revenue: 500}]}}], + [{customer: {companies: []}}, {customer: {bigCount: 0, companies: []}}], + [{customer: {companies: [{revenue: 101}, {revenue: 1000}, {revenue: 100}]}}, {customer: {bigCount: 2, companies: [{big: true, revenue: 101}, {big: true, revenue: 1000}, {big: false, revenue: 100}]}}], + ], +} + +{ + name: "an importer writes per instance from an imported per-instance value", + policy: { + imports: ["base"], + blocks: [{expression: "company.label", value: "company.big ? 'big' : 'small'"}], + }, + policies: { + base: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + }, + cases: [ + [{customer: {companies: [{revenue: 5}, {revenue: 500}]}}, {customer: {companies: [{revenue: 5, big: false, label: "small"}, {revenue: 500, big: true, label: "big"}]}}], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +// --- Policies that are not imported ------------------------------------------------------- + +{ + name: "a workspace sibling that is not imported does not run", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.score", value: "customer.age + 1"}], + }, + policies: { + other: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.other", value: "customer.age * 2"}]}, + }, + cases: [ + [{customer: {age: 20}}, {customer: {age: 20, score: 21}}], + [{customer: {age: 0}}, {customer: {age: 0, score: 1}}], + ], +} + +{ + name: "a property written only by a non-imported sibling is required input", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.score", value: "customer.other + 1"}], + }, + policies: { + other: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.other", value: "customer.age * 2"}]}, + }, + cases: [ + [{customer: {age: 20}}, "!error: MissingRequiredInputs"], + [{customer: {age: 20, other: 5}}, {customer: {age: 20, other: 5, score: 6}}], + [{customer: {age: 20, other: -1}}, {customer: {age: 20, other: -1, score: 0}}], + ], +} + +{ + name: "an importee does not see its importer's writes as its own unit", + policy: { + imports: ["base"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.top", value: "customer.age * 100"}], + }, + policies: { + base: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.low", value: "customer.age + 1"}]}, + }, + cases: [ + [{customer: {age: 2}}, {customer: {age: 2, low: 3, top: 200}}], + [{customer: {age: 0}}, {customer: {age: 0, low: 1, top: 0}}], + ], +} + +// --- Import errors --------------------------------------------------------------------------- + +{ + name: "a missing import fails evaluation", + diagnostics: ["IMPORT_NOT_FOUND"], + policy: { + imports: ["does-not-exist"], + blocks: [{expression: "x", value: "1 + 1"}], + }, + cases: [ + [{}, "!error: ImportNotFound"], + [{x: 5}, "!error: ImportNotFound"], + [null, "!error: ImportNotFound"], + ], +} + +{ + name: "a missing transitive import fails evaluation", + diagnostics: ["IMPORT_NOT_FOUND"], + policy: { + imports: ["mid"], + blocks: [{expression: "x", value: "y + 1"}], + }, + policies: { + mid: {imports: ["does-not-exist"], blocks: [{expression: "y", value: "2"}]}, + }, + cases: [ + [{}, "!error: ImportNotFound"], + [{y: 1}, "!error: ImportNotFound"], + ], +} + +{ + name: "one missing import among several fails evaluation", + diagnostics: ["IMPORT_NOT_FOUND"], + policy: { + imports: ["base", "gone"], + blocks: [{expression: "x", value: "y + 1"}], + }, + policies: { + base: {blocks: [{expression: "y", value: "2"}]}, + }, + cases: [ + [{}, "!error: ImportNotFound"], + ], +} + +{ + name: "importing a graph document is not an import", + policy: { + imports: ["g"], + blocks: [{expression: "x", value: "1"}], + }, + policies: { + g: {graph: {nodes: [{expression: "e", fields: {y: "1"}}]}}, + }, + cases: [ + {input: {}, output: "!error: ImportNotFound", note: "question: the graph exists in the workspace but a policy import of it reports 'not in the workspace'", engines: "DecisionEngine loads imports itself and reports ContentKindMismatch instead"}, + {input: {y: 2}, output: "!error: ImportNotFound", note: "question: the graph exists in the workspace but a policy import of it reports 'not in the workspace'", engines: "DecisionEngine loads imports itself and reports ContentKindMismatch instead"}, + ], +} + +// --- Circular imports --------------------------------------------------------------------------- +// CircularImport is an error diagnostic, but evaluation does not check diagnostics: a cycle of +// policies evaluates as one unit. + +{ + name: "a policy importing itself evaluates normally", + diagnostics: ["CIRCULAR_IMPORT"], + policy: { + imports: ["main"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.x", value: "customer.age + 1"}], + }, + cases: [ + {input: {customer: {age: 1}}, output: {customer: {age: 1, x: 2}}, note: "question: a self import is a CircularImport error diagnostic, yet evaluation succeeds"}, + {input: {customer: {age: 9}}, output: {customer: {age: 9, x: 10}}, note: "question: a self import is a CircularImport error diagnostic, yet evaluation succeeds"}, + ], +} + +{ + name: "two policies importing each other evaluate as one unit", + diagnostics: ["CIRCULAR_IMPORT"], + policy: { + imports: ["a"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.x", value: "customer.a + 1"}], + }, + policies: {a: {imports: ["main"], blocks: [{expression: "customer.a", value: "customer.age * 2"}]}}, + cases: [ + {input: {customer: {age: 1}}, output: {customer: {age: 1, a: 2, x: 3}}, note: "question: circular imports are an error diagnostic, yet evaluation succeeds"}, + {input: {customer: {age: 0}}, output: {customer: {age: 0, a: 0, x: 1}}, note: "question: circular imports are an error diagnostic, yet evaluation succeeds"}, + {input: {customer: {}}, output: "!error: MissingRequiredInputs"}, + ], +} + +{ + name: "a three-policy import cycle evaluates as one unit", + diagnostics: ["CIRCULAR_IMPORT"], + policy: { + imports: ["a"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.m", value: "customer.b + 1"}], + }, + policies: { + a: {imports: ["b"], blocks: [{expression: "customer.a", value: "customer.age * 2"}]}, + b: {imports: ["main"], blocks: [{expression: "customer.b", value: "customer.a * 3"}]}, + }, + cases: [ + {input: {customer: {age: 1}}, output: {customer: {age: 1, a: 2, b: 6, m: 7}}, note: "question: circular imports are an error diagnostic, yet evaluation succeeds"}, + {input: {customer: {age: 2}}, output: {customer: {age: 2, a: 4, b: 12, m: 13}}, note: "question: circular imports are an error diagnostic, yet evaluation succeeds"}, + ], +} + +{ + name: "a data cycle across circular imports", + policy: { + imports: ["a"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.x", value: "customer.a + 1"}], + }, + policies: {a: {imports: ["main"], blocks: [{expression: "customer.a", value: "customer.x * 2"}]}}, + cases: [ + {input: {customer: {age: 1}}, output: "!error"}, + {input: {customer: {age: 5}}, output: "!error"}, + ], +} + +// --- Writers across the unit --------------------------------------------------------------------- + +{ + name: "the importer and the imported policy write different fields of one entity", + policy: { + imports: ["base"], + models: {order: {qty: "number", price: "number"}}, + blocks: [{expression: "order.total", value: "order.subtotal - order.discount"}], + }, + policies: { + base: { + models: {order: {qty: "number", price: "number"}}, + blocks: [ + {expression: "order.subtotal", value: "order.qty * order.price"}, + {expression: "order.discount", value: "order.subtotal > 100 ? order.subtotal * 0.1 : 0"}, + ], + }, + }, + cases: [ + [{order: {qty: 2, price: 100}}, {order: {qty: 2, price: 100, subtotal: 200, discount: 20, total: 180}}], + [{order: {qty: 1, price: 50}}, {order: {qty: 1, price: 50, subtotal: 50, discount: 0, total: 50}}], + [{order: {qty: 0, price: 50}}, {order: {qty: 0, price: 50, subtotal: 0, discount: 0, total: 0}}], + [{order: {qty: 3, price: 33.34}}, {order: {qty: 3, price: 33.34, subtotal: 100.02, discount: 10.002, total: 90.018}}], + ], +} + +{ + name: "the same property written in the importer and the imported policy", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + imports: ["base"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.base", value: "customer.age + 1"}], + }, + policies: { + base: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.base", value: "customer.age * 2"}]}, + }, + cases: [ + {input: {customer: {age: 20}}, output: {customer: {age: 20, base: 40}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the imported writer and drops the importer's block"}, + {input: {customer: {age: 3}}, output: {customer: {age: 3, base: 6}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the imported writer and drops the importer's block"}, + ], +} + +{ + name: "nested write paths from two policies merge into one object", + policy: { + imports: ["base"], + models: {order: {amount: "number"}}, + blocks: [{expression: "totals.gross", value: "order.amount + totals.tax"}], + }, + policies: { + base: {models: {order: {amount: "number"}}, blocks: [{expression: "totals.tax", value: "order.amount * 0.2"}]}, + }, + cases: [ + [{order: {amount: 100}}, {order: {amount: 100}, totals: {tax: 20, gross: 120}}], + [{order: {amount: 0}}, {order: {amount: 0}, totals: {tax: 0, gross: 0}}], + [{order: {amount: 12.5}}, {order: {amount: 12.5}, totals: {tax: 2.5, gross: 15}}], + ], +} diff --git a/core/engine/tests/spec/policy/14-goals.json5 b/core/engine/tests/spec/policy/14-goals.json5 new file mode 100644 index 00000000..a5401ace --- /dev/null +++ b/core/engine/tests/spec/policy/14-goals.json5 @@ -0,0 +1,402 @@ +// Request goals. A request may name the properties it wants (`goals`); only the blocks those +// goals depend on run, required inputs are checked for that cone only, and the output is the +// input plus the writes that ran. Without goals every terminal write of the unit is a goal. + +// --- One goal evaluates only its cone ------------------------------------------------------ + +{ + name: "a single goal runs only its own block", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.rich", value: "customer.income > 1000"}, + {expression: "customer.both", value: "customer.adult and customer.rich"}, + ], + }, + cases: [ + {input: {customer: {age: 20, income: 5}}, goals: ["customer.adult"], output: {customer: {age: 20, income: 5, adult: true}}}, + {input: {customer: {age: 3, income: 5000}}, goals: ["customer.adult"], output: {customer: {age: 3, income: 5000, adult: false}}}, + {input: {customer: {age: 20, income: 5000}}, goals: ["customer.rich"], output: {customer: {age: 20, income: 5000, rich: true}}}, + {input: {customer: {age: 20, income: 5}}, goals: ["customer.rich"], output: {customer: {age: 20, income: 5, rich: false}}}, + {input: {customer: {age: 20, income: 5000}}, output: {customer: {age: 20, income: 5000, adult: true, rich: true, both: true}}}, + ], +} + +{ + name: "a derived goal pulls in its dependencies but not its siblings", + policy: { + models: {customer: {age: "number", income: "number", city: "string"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.rich", value: "customer.income > 1000"}, + {expression: "customer.both", value: "customer.adult and customer.rich"}, + {expression: "customer.local", value: "customer.city == 'Oslo'"}, + ], + }, + cases: [ + {input: {customer: {age: 20, income: 5000, city: "Oslo"}}, goals: ["customer.both"], output: {customer: {age: 20, income: 5000, city: "Oslo", adult: true, rich: true, both: true}}}, + {input: {customer: {age: 10, income: 5000, city: "Rome"}}, goals: ["customer.both"], output: {customer: {age: 10, income: 5000, city: "Rome", adult: false, rich: true, both: false}}}, + {input: {customer: {age: 20, income: 5000}}, goals: ["customer.both"], output: {customer: {age: 20, income: 5000, adult: true, rich: true, both: true}}}, + {input: {customer: {age: 20, income: 5000, city: "Oslo"}}, goals: ["customer.local"], output: {customer: {age: 20, income: 5000, city: "Oslo", local: true}}}, + {input: {customer: {city: "Rome"}}, goals: ["customer.local"], output: {customer: {city: "Rome", local: false}}}, + ], +} + +{ + name: "an intermediate goal does not run its dependents", + policy: { + models: {o: {qty: "number", price: "number"}}, + blocks: [ + {expression: "o.subtotal", value: "o.qty * o.price"}, + {expression: "o.tax", value: "o.subtotal * 0.25"}, + {expression: "o.total", value: "o.subtotal + o.tax"}, + ], + }, + cases: [ + {input: {o: {qty: 2, price: 10}}, goals: ["o.subtotal"], output: {o: {qty: 2, price: 10, subtotal: 20}}}, + {input: {o: {qty: 2, price: 10}}, goals: ["o.tax"], output: {o: {qty: 2, price: 10, subtotal: 20, tax: 5}}}, + {input: {o: {qty: 2, price: 10}}, goals: ["o.total"], output: {o: {qty: 2, price: 10, subtotal: 20, tax: 5, total: 25}}}, + {input: {o: {qty: 0, price: 10}}, goals: ["o.total"], output: {o: {qty: 0, price: 10, subtotal: 0, tax: 0, total: 0}}}, + {input: {o: {qty: 3, price: 0.1}}, output: {o: {qty: 3, price: 0.1, subtotal: 0.3, tax: 0.075, total: 0.375}}}, + ], +} + +// --- Multiple goals -------------------------------------------------------------------------- + +{ + name: "multiple goals run the union of their cones", + policy: { + models: {customer: {age: "number", income: "number", city: "string"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.rich", value: "customer.income > 1000"}, + {expression: "customer.local", value: "customer.city == 'Oslo'"}, + ], + }, + cases: [ + {input: {customer: {age: 20, income: 5, city: "Oslo"}}, goals: ["customer.adult", "customer.rich"], output: {customer: {age: 20, income: 5, city: "Oslo", adult: true, rich: false}}}, + {input: {customer: {age: 20, income: 5, city: "Oslo"}}, goals: ["customer.rich", "customer.adult"], output: {customer: {age: 20, income: 5, city: "Oslo", adult: true, rich: false}}}, + {input: {customer: {age: 20, income: 5, city: "Oslo"}}, goals: ["customer.adult", "customer.local"], output: {customer: {age: 20, income: 5, city: "Oslo", adult: true, local: true}}}, + {input: {customer: {age: 20, income: 5, city: "Oslo"}}, goals: ["customer.adult", "customer.rich", "customer.local"], output: {customer: {age: 20, income: 5, city: "Oslo", adult: true, rich: false, local: true}}}, + {input: {customer: {age: 20, income: 5, city: "Oslo"}}, goals: ["customer.adult", "customer.adult"], output: {customer: {age: 20, income: 5, city: "Oslo", adult: true}}}, + ], +} + +{ + name: "overlapping goal cones share their common dependency", + policy: { + models: {o: {amount: "number"}}, + blocks: [ + {expression: "o.net", value: "o.amount * 0.8"}, + {expression: "o.fee", value: "o.net * 0.1"}, + {expression: "o.payout", value: "o.net - o.fee"}, + {expression: "o.flag", value: "o.amount > 100"}, + ], + }, + cases: [ + {input: {o: {amount: 100}}, goals: ["o.fee", "o.payout"], output: {o: {amount: 100, net: 80, fee: 8, payout: 72}}}, + {input: {o: {amount: 100}}, goals: ["o.net", "o.flag"], output: {o: {amount: 100, net: 80, flag: false}}}, + {input: {o: {amount: 0}}, goals: ["o.payout"], output: {o: {amount: 0, net: 0, fee: 0, payout: 0}}}, + {input: {o: {amount: 1000}}, goals: ["o.flag"], output: {o: {amount: 1000, flag: true}}}, + ], +} + +// --- Goals limit the required inputs --------------------------------------------------------- + +{ + name: "inputs outside the goal's cone may be missing", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.rich", value: "customer.income > 1000"}, + ], + }, + cases: [ + {input: {customer: {age: 20}}, goals: ["customer.adult"], output: {customer: {age: 20, adult: true}}}, + {input: {customer: {income: 5000}}, goals: ["customer.rich"], output: {customer: {income: 5000, rich: true}}}, + {input: {customer: {age: 20, income: null}}, goals: ["customer.adult"], output: {customer: {age: 20, income: null, adult: true}}}, + {input: {customer: {age: 20}}, output: "!error: MissingRequiredInputs"}, + {input: {customer: {income: 5000}}, goals: ["customer.adult"], output: "!error: MissingRequiredInputs"}, + {input: {customer: {}}, goals: ["customer.adult", "customer.rich"], output: "!error: MissingRequiredInputs"}, + ], +} + +{ + name: "input validation applies to the whole input, not only the goal's cone", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.rich", value: "customer.income > 1000"}, + ], + }, + cases: [ + {input: {customer: {age: "x", income: 5000}}, goals: ["customer.rich"], output: "!error: InputValidationFailed"}, + {input: {customer: {age: 20, income: true}}, goals: ["customer.adult"], output: "!error: InputValidationFailed"}, + {input: {customer: {age: 20, income: 5000}}, goals: ["customer.adult"], output: {customer: {age: 20, income: 5000, adult: true}}}, + ], +} + +{ + name: "an error in a block outside the goal's cone does not surface", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.broken", value: "customer.name * 2"}, + ], + }, + cases: [ + {input: {customer: {age: 20, name: "x"}}, goals: ["customer.adult"], output: {customer: {age: 20, name: "x", adult: true}}}, + {input: {customer: {age: 2, name: "y"}}, goals: ["customer.adult"], output: {customer: {age: 2, name: "y", adult: false}}}, + {input: {customer: {age: 20, name: "x"}}, goals: ["customer.broken"], output: "!error: ExpressionFailed"}, + {input: {customer: {age: 20, name: "x"}}, output: "!error: ExpressionFailed"}, + ], +} + +// --- Goal validation ------------------------------------------------------------------------- + +{ + name: "unknown goals are rejected", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + {input: {customer: {age: 20}}, goals: ["customer.nope"], output: "!error: GoalNotFound"}, + {input: {customer: {age: 20}}, goals: ["nope"], output: "!error: GoalNotFound"}, + {input: {customer: {age: 20}}, goals: [""], output: "!error: GoalNotFound"}, + {input: {customer: {age: 20}}, goals: ["customer.adult", "customer.nope"], output: "!error: GoalNotFound"}, + {input: {customer: {age: 20}}, goals: ["customer.adult.x"], output: "!error: GoalNotFound"}, + {input: {customer: {age: 20}}, goals: ["Customer.Adult"], output: "!error: GoalNotFound"}, + {input: {customer: {age: 20}}, goals: ["customer"], output: "!error: GoalNotFound"}, + {input: {customer: {age: "x"}}, goals: ["customer.nope"], output: "!error: GoalNotFound"}, + ], +} + +{ + name: "a goal naming a read input property is accepted and runs nothing", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + {input: {customer: {age: 20, income: 5}}, goals: ["customer.age"], output: {customer: {age: 20, income: 5}}}, + {input: {customer: {age: 20, income: 5}}, goals: ["customer.income"], output: "!error: GoalNotFound", note: "question: customer.age (read by a block) is an accepted goal while customer.income (declared, never read) is GoalNotFound"}, + {input: {customer: {age: 20, income: 5}}, goals: ["customer.age", "customer.adult"], output: {customer: {age: 20, income: 5, adult: true}}}, + ], +} + +{ + name: "a goal on a property written by a sibling outside the unit is unknown", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + policies: { + other: {models: {customer: {age: "number"}}, blocks: [{expression: "customer.senior", value: "customer.age >= 65"}]}, + }, + cases: [ + {input: {customer: {age: 70}}, goals: ["customer.senior"], output: "!error: GoalNotFound"}, + {input: {customer: {age: 70}}, goals: ["customer.adult"], output: {customer: {age: 70, adult: true}}}, + ], +} + +// --- Goals and block kinds --------------------------------------------------------------------- + +{ + name: "a goal on one output of a multi-output table runs the whole table", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {table: "t", inputs: ["customer.age"], outputs: ["customer.band", "customer.rate"], rules: [["< 18", "'minor'", "0"], ["", "'adult'", "1"]]}, + {expression: "customer.price", value: "100 * customer.rate"}, + ], + }, + cases: [ + {input: {customer: {age: 5}}, goals: ["customer.band"], output: {customer: {age: 5, band: "minor", rate: 0}}}, + {input: {customer: {age: 30}}, goals: ["customer.rate"], output: {customer: {age: 30, band: "adult", rate: 1}}}, + {input: {customer: {age: 30}}, goals: ["customer.price"], output: {customer: {age: 30, band: "adult", rate: 1, price: 100}}}, + {input: {customer: {age: 5}}, output: {customer: {age: 5, band: "minor", rate: 0, price: 0}}}, + ], +} + +{ + name: "goals on match and assertion outputs", + policy: { + models: {customer: {score: "number", age: "number"}}, + blocks: [ + {match: "customer.tier", arms: [["customer.score >= 700", "'prime'"], ["customer.score >= 600", "'near'"], ["", "'sub'"]]}, + {assertion: "customer.eligible", conditions: ["customer.age >= 18", "customer.score >= 600"]}, + ], + }, + cases: [ + {input: {customer: {score: 720, age: 30}}, goals: ["customer.tier"], output: {customer: {score: 720, age: 30, tier: "prime"}}}, + {input: {customer: {score: 650}}, goals: ["customer.tier"], output: {customer: {score: 650, tier: "near"}}}, + {input: {customer: {score: 500, age: 30}}, goals: ["customer.eligible"], output: {customer: {score: 500, age: 30, eligible: false}}}, + {input: {customer: {score: 610, age: 18}}, goals: ["customer.eligible"], output: {customer: {score: 610, age: 18, eligible: true}}}, + {input: {customer: {score: 610}}, goals: ["customer.eligible"], output: "!error: MissingRequiredInputs"}, + {input: {customer: {score: 100, age: 1}}, goals: ["customer.eligible", "customer.tier"], output: {customer: {score: 100, age: 1, tier: "sub", eligible: false}}}, + ], +} + +{ + name: "a goal on a match whose untaken arm reads a computed value", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.big", value: "customer.income * 2"}, + {match: "customer.tier", arms: [["customer.age < 18", "'minor'"], ["", "customer.big > 10 ? 'gold' : 'std'"]]}, + ], + }, + cases: [ + {input: {customer: {age: 30, income: 100}}, goals: ["customer.tier"], output: {customer: {age: 30, income: 100, big: 200, tier: "gold"}}}, + {input: {customer: {age: 30, income: 1}}, goals: ["customer.tier"], output: {customer: {age: 30, income: 1, big: 2, tier: "std"}}}, + {input: {customer: {age: 10, income: 100}}, goals: ["customer.tier"], output: {customer: {age: 10, income: 100, tier: "minor"}}}, + {input: {customer: {age: 10}}, goals: ["customer.tier"], output: "!error: MissingRequiredInputs", note: "question: the arm reading customer.income is not taken, yet the required-input check is static over every arm"}, + {input: {customer: {age: 30}}, goals: ["customer.tier"], output: "!error: MissingRequiredInputs"}, + ], +} + +// Without goals the roots are the terminal writes only; an intermediate read only by an +// unmatched row is never demanded and is absent from the output. +{ + name: "a goal on a table whose unmatched row reads a computed value", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.adultMsg", value: "'adult'"}, + {expression: "customer.childMsg", value: "'child'"}, + {table: "dt", inputs: ["customer.age"], outputs: ["customer.msg"], rules: [[">= 18", "customer.adultMsg"], ["", "customer.childMsg"]]}, + ], + }, + cases: [ + {input: {customer: {age: 30}}, goals: ["customer.msg"], output: {customer: {age: 30, adultMsg: "adult", msg: "adult"}}}, + {input: {customer: {age: 3}}, goals: ["customer.msg"], output: {customer: {age: 3, childMsg: "child", msg: "child"}}}, + {input: {customer: {age: 30}}, output: {customer: {age: 30, adultMsg: "adult", msg: "adult"}}}, + {input: {customer: {age: 3}}, output: {customer: {age: 3, childMsg: "child", msg: "child"}}}, + ], +} + +// --- Goals with nested write paths ----------------------------------------------------------- + +{ + name: "goals on nested computed paths", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "totals.byTier.x", value: "customer.age * 2"}, + {expression: "totals.byTier.y", value: "3"}, + {expression: "totals.count", value: "1"}, + ], + }, + cases: [ + {input: {customer: {age: 5}}, goals: ["totals.byTier.x"], output: {customer: {age: 5}, totals: {byTier: {x: 10}}}}, + {input: {customer: {age: 5}}, goals: ["totals.byTier.y"], output: {customer: {age: 5}, totals: {byTier: {y: 3}}}}, + {input: {customer: {age: 5}}, goals: ["totals.byTier"], output: {customer: {age: 5}, totals: {byTier: {x: 10, y: 3}}}}, + {input: {customer: {age: 5}}, goals: ["totals"], output: {customer: {age: 5}, totals: {byTier: {x: 10, y: 3}, count: 1}}}, + {input: {customer: {age: 5}}, goals: ["totals.count"], output: {customer: {age: 5}, totals: {count: 1}}}, + {input: {customer: {age: 5}}, output: {customer: {age: 5}, totals: {byTier: {x: 10, y: 3}, count: 1}}}, + ], +} + +// --- Goals with per-instance writes -------------------------------------------------------------- + +{ + name: "a goal on a per-instance property", + policy: { + models: {customer: {companies: "company[]", name: "string"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "company.half", value: "company.revenue / 2"}, + {expression: "customer.bigCount", value: "count(customer.companies, #.big)"}, + {expression: "customer.greeting", value: "'Hi ' + customer.name"}, + ], + }, + cases: [ + {input: {customer: {name: "a", companies: [{revenue: 5}, {revenue: 500}]}}, goals: ["company.big"], output: {customer: {name: "a", companies: [{revenue: 5, big: false}, {revenue: 500, big: true}]}}}, + {input: {customer: {name: "a", companies: [{revenue: 5}, {revenue: 500}]}}, goals: ["customer.bigCount"], output: {customer: {name: "a", bigCount: 1, companies: [{revenue: 5, big: false}, {revenue: 500, big: true}]}}}, + {input: {customer: {name: "a", companies: []}}, goals: ["customer.bigCount"], output: {customer: {name: "a", bigCount: 0, companies: []}}}, + {input: {customer: {companies: [{revenue: 8}]}}, goals: ["company.half"], output: {customer: {companies: [{revenue: 8, half: 4}]}}}, + {input: {customer: {name: "b", companies: [{revenue: 8}]}}, goals: ["customer.greeting"], output: {customer: {name: "b", greeting: "Hi b", companies: [{revenue: 8}]}}}, + ], +} + +// --- Goals with globals ---------------------------------------------------------------------------- + +{ + name: "goals on top-level global computations", + policy: { + globals: {platform: {taxRate: "number", fee: "number"}}, + models: {order: {amount: "number"}}, + blocks: [ + {expression: "order.tax", value: "order.amount * taxRate"}, + {expression: "order.fee", value: "fee"}, + {expression: "summary", value: "order.tax + order.fee"}, + ], + }, + cases: [ + {input: {taxRate: 0.1, order: {amount: 50}}, goals: ["order.tax"], output: {taxRate: 0.1, order: {amount: 50, tax: 5}}}, + {input: {fee: 2, order: {amount: 50}}, goals: ["order.fee"], output: {fee: 2, order: {amount: 50, fee: 2}}}, + {input: {fee: 2, taxRate: 0.1, order: {amount: 50}}, goals: ["summary"], output: {fee: 2, taxRate: 0.1, order: {amount: 50, tax: 5, fee: 2}, summary: 7}}, + {input: {fee: 2, order: {amount: 50}}, goals: ["summary"], output: "!error: MissingRequiredInputs"}, + ], +} + +// --- Goals across imports -------------------------------------------------------------------------- + +{ + name: "goals reach into imported policies", + policy: { + imports: ["base"], + models: {customer: {age: "number", income: "number"}}, + blocks: [{expression: "customer.score", value: "customer.base + 1"}], + }, + policies: { + base: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.base", value: "customer.age * 2"}, + {expression: "customer.rich", value: "customer.income > 1000"}, + ], + }, + }, + cases: [ + {input: {customer: {age: 20}}, goals: ["customer.score"], output: {customer: {age: 20, base: 40, score: 41}}}, + {input: {customer: {age: 20}}, goals: ["customer.base"], output: {customer: {age: 20, base: 40}}}, + {input: {customer: {income: 2000}}, goals: ["customer.rich"], output: {customer: {income: 2000, rich: true}}}, + {input: {customer: {age: 1, income: 1}}, output: {customer: {age: 1, income: 1, base: 2, score: 3, rich: false}}}, + {input: {customer: {age: 1}}, output: "!error: MissingRequiredInputs"}, + ], +} + +// --- Goals and input passthrough ----------------------------------------------------------------- + +{ + name: "goals keep unrelated input keys in the output", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}, {expression: "customer.x", value: "1"}], + }, + cases: [ + {input: {customer: {age: 20, extra: [1, 2]}, other: "kept"}, goals: ["customer.adult"], output: {customer: {age: 20, extra: [1, 2], adult: true}, other: "kept"}}, + {input: {customer: {age: 20}, meta: {a: null}}, goals: ["customer.x"], output: {customer: {age: 20, x: 1}, meta: {a: null}}}, + {input: {customer: {age: 20}}, goals: [], output: {customer: {age: 20, adult: true, x: 1}}}, + ], +} + +{ + name: "a goal's computed value replaces a value supplied in the input", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}, {expression: "customer.x", value: "customer.age + 1"}], + }, + cases: [ + {input: {customer: {age: 20, adult: false, x: 0}}, goals: ["customer.adult"], output: {customer: {age: 20, adult: true, x: 0}}}, + {input: {customer: {age: 20, adult: false, x: 0}}, goals: ["customer.x"], output: {customer: {age: 20, adult: false, x: 21}}}, + {input: {customer: {age: 20, adult: false, x: 0}}, output: {customer: {age: 20, adult: true, x: 21}}}, + ], +} diff --git a/core/engine/tests/spec/policy/15-nullability.json5 b/core/engine/tests/spec/policy/15-nullability.json5 new file mode 100644 index 00000000..c831c54b --- /dev/null +++ b/core/engine/tests/spec/policy/15-nullability.json5 @@ -0,0 +1,579 @@ +// Null and missing values in policies. A required property that is read must be present and +// non-null (MissingRequiredInputs otherwise); an optional property (`?`) may be missing or +// null and reads as null. Null flows through expressions with the expression language's rules: +// `??` and `== null` handle it, arithmetic and ordering on null fail the evaluation. + +// --- Optional strings ------------------------------------------------------------------------ + +{ + name: "an optional string defaults with ??", + policy: { + models: {customer: {age: "number", nickname: "string?"}}, + blocks: [{expression: "customer.label", value: "customer.nickname ?? 'anon'"}], + }, + cases: [ + [{customer: {age: 1}}, {customer: {age: 1, label: "anon"}}], + [{customer: {age: 1, nickname: null}}, {customer: {age: 1, nickname: null, label: "anon"}}], + [{customer: {age: 1, nickname: "bob"}}, {customer: {age: 1, nickname: "bob", label: "bob"}}], + [{customer: {age: 1, nickname: ""}}, {customer: {age: 1, nickname: "", label: ""}}], + [{customer: {}}, {customer: {label: "anon"}}], + [{customer: {age: 1, nickname: 5}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "missing and null optionals compare equal to null", + policy: { + models: {customer: {nickname: "string?", score: "number?"}}, + blocks: [ + {expression: "customer.noNick", value: "customer.nickname == null"}, + {expression: "customer.hasScore", value: "customer.score != null"}, + ], + }, + cases: [ + [{customer: {}}, {customer: {noNick: true, hasScore: false}}], + [{customer: {nickname: null, score: null}}, {customer: {nickname: null, score: null, noNick: true, hasScore: false}}], + [{customer: {nickname: "a", score: 0}}, {customer: {nickname: "a", score: 0, noNick: false, hasScore: true}}], + [{customer: {nickname: "", score: -1}}, {customer: {nickname: "", score: -1, noNick: false, hasScore: true}}], + ], +} + +{ + name: "a missing entity reads its optional properties as null", + policy: { + models: {customer: {nickname: "string?"}}, + blocks: [{expression: "label", value: "customer.nickname ?? 'none'"}], + }, + cases: [ + [{}, {label: "none"}], + [{customer: null}, {customer: null, label: "none"}], + {input: null, output: {label: "none"}, note: "bug: a null request passes validation like an empty object, but the store stays null and every write is lost (output null)"}, + [{customer: {nickname: "x"}}, {customer: {nickname: "x"}, label: "x"}], + ], +} + +// --- Optional numbers in arithmetic ----------------------------------------------------------- + +{ + name: "arithmetic on an optional number guarded with ??", + policy: { + models: {customer: {score: "number?"}}, + blocks: [{expression: "customer.next", value: "(customer.score ?? 0) + 1"}], + }, + cases: [ + [{customer: {}}, {customer: {next: 1}}], + [{customer: {score: null}}, {customer: {score: null, next: 1}}], + [{customer: {score: 5}}, {customer: {score: 5, next: 6}}], + [{customer: {score: -1}}, {customer: {score: -1, next: 0}}], + [{customer: {score: 0.5}}, {customer: {score: 0.5, next: 1.5}}], + ], +} + +{ + name: "arithmetic on an unguarded optional number fails when it is null", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {score: "number?"}}, + blocks: [{expression: "customer.next", value: "customer.score + 1"}], + }, + cases: [ + [{customer: {score: 5}}, {customer: {score: 5, next: 6}}], + [{customer: {score: 0}}, {customer: {score: 0, next: 1}}], + [{customer: {}}, "!error: ExpressionFailed"], + [{customer: {score: null}}, "!error: ExpressionFailed"], + [{}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a ternary guard keeps the null branch from evaluating", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {score: "number?"}}, + blocks: [{expression: "customer.doubled", value: "customer.score == null ? 'n/a' : customer.score * 2"}], + }, + cases: [ + [{customer: {}}, {customer: {doubled: "n/a"}}], + [{customer: {score: null}}, {customer: {score: null, doubled: "n/a"}}], + [{customer: {score: 21}}, {customer: {score: 21, doubled: 42}}], + [{customer: {score: 0}}, {customer: {score: 0, doubled: 0}}], + ], +} + +{ + name: "an optional number copied as is writes null", + policy: { + models: {customer: {score: "number?"}}, + blocks: [{expression: "customer.copy", value: "customer.score"}], + }, + cases: [ + [{customer: {}}, {customer: {copy: null}}], + [{customer: {score: null}}, {customer: {score: null, copy: null}}], + [{customer: {score: 3}}, {customer: {score: 3, copy: 3}}], + ], +} + +// --- Required properties: null counts as missing ------------------------------------------------ + +{ + name: "a required property that is null or missing is a missing input", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.a", value: "customer.age + 1"}, + {expression: "customer.b", value: "customer.age == null"}, + ], + }, + cases: [ + [{customer: {age: 4}}, {customer: {age: 4, a: 5, b: false}}], + [{customer: {age: null}}, "!error: MissingRequiredInputs"], + [{customer: {}}, "!error: MissingRequiredInputs"], + [{customer: null}, "!error: MissingRequiredInputs"], + [{}, "!error: MissingRequiredInputs"], + {input: null, output: "!error: MissingRequiredInputs", note: "bug: a null request skips the required-input check that {} gets and fails later with ExpressionFailed"}, + ], +} + +{ + name: "a required property that no block reads may be missing", + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{expression: "customer.greeting", value: "'Hi ' + customer.name"}], + }, + cases: [ + [{customer: {name: "Ann"}}, {customer: {name: "Ann", greeting: "Hi Ann"}}], + [{customer: {name: "Ann", age: null}}, {customer: {name: "Ann", age: null, greeting: "Hi Ann"}}], + [{customer: {name: "Ann", age: 3}}, {customer: {name: "Ann", age: 3, greeting: "Hi Ann"}}], + [{customer: {name: null}}, "!error: MissingRequiredInputs"], + [{customer: {name: "Ann", age: "3"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an undeclared property that is read is required input", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + blocks: [{expression: "out", value: "foo.bar * 2"}], + }, + cases: [ + [{foo: {bar: 2}}, {foo: {bar: 2}, out: 4}], + [{foo: {bar: null}}, "!error: MissingRequiredInputs"], + [{foo: {}}, "!error: MissingRequiredInputs"], + [{}, "!error: MissingRequiredInputs"], + [{foo: {bar: "2"}}, "!error: ExpressionFailed"], + ], +} + +// --- Optional globals ------------------------------------------------------------------------------ + +{ + name: "an optional global may be missing or null", + policy: { + globals: {platform: {rate: "number?"}}, + blocks: [{expression: "out", value: "(rate ?? 1) * 10"}], + }, + cases: [ + [{rate: 2}, {rate: 2, out: 20}], + [{}, {out: 10}], + [{rate: null}, {rate: null, out: 10}], + [{rate: "2"}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a required global that is null is a missing input", + policy: { + globals: {platform: {rate: "number"}}, + blocks: [{expression: "out", value: "rate * 10"}], + }, + cases: [ + [{rate: 2}, {rate: 2, out: 20}], + [{rate: 0}, {rate: 0, out: 0}], + [{rate: null}, "!error: MissingRequiredInputs"], + [{}, "!error: MissingRequiredInputs"], + ], +} + +// --- Optional relationships and arrays ---------------------------------------------------------- + +{ + name: "an optional relationship reads through ??", + policy: { + models: {customer: {report: "report?"}, report: {score: "number"}}, + blocks: [{expression: "customer.s", value: "customer.report.score ?? 0"}], + }, + cases: [ + [{customer: {}}, {customer: {s: 0}}], + [{customer: {report: null}}, {customer: {report: null, s: 0}}], + [{customer: {report: {score: 4}}}, {customer: {report: {score: 4}, s: 4}}], + [{customer: {report: {}}}, "!error: MissingRequiredInputs"], + [{customer: {report: {score: "4"}}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an optional array defaults to an empty list", + policy: { + models: {customer: {list: "number[]?"}}, + blocks: [ + {expression: "customer.n", value: "len(customer.list ?? [])"}, + {expression: "customer.total", value: "sum(customer.list ?? [])"}, + ], + }, + cases: [ + [{customer: {}}, {customer: {n: 0, total: 0}}], + [{customer: {list: null}}, {customer: {list: null, n: 0, total: 0}}], + [{customer: {list: []}}, {customer: {list: [], n: 0, total: 0}}], + [{customer: {list: [1, 2.5]}}, {customer: {list: [1, 2.5], n: 2, total: 3.5}}], + [{customer: {list: ["1"]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "null elements inside a required array of strings", + policy: { + models: {customer: {tags: "string[]"}}, + blocks: [ + {expression: "customer.n", value: "len(customer.tags)"}, + {expression: "customer.nonNull", value: "count(customer.tags, # != null)"}, + ], + }, + cases: [ + [{customer: {tags: []}}, {customer: {tags: [], n: 0, nonNull: 0}}], + [{customer: {tags: ["a", "b"]}}, {customer: {tags: ["a", "b"], n: 2, nonNull: 2}}], + {input: {customer: {tags: [null, "a"]}}, output: {customer: {tags: [null, "a"], n: 2, nonNull: 1}}, note: "question: null elements pass validation of a non-optional string[]"}, + [{customer: {tags: null}}, "!error: MissingRequiredInputs"], + [{customer: {tags: [1]}}, "!error: InputValidationFailed"], + ], +} + +// --- Strict nullable index access: arr[0].x is nullable --------------------------------------- + +{ + name: "an index read on an empty list is null", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.firstRevenue", value: "customer.companies[0].revenue"}], + }, + cases: [ + [{customer: {companies: []}}, {customer: {companies: [], firstRevenue: null}}], + [{customer: {companies: [{revenue: 5}]}}, {customer: {companies: [{revenue: 5}], firstRevenue: 5}}], + [{customer: {companies: [{revenue: 5}, {revenue: 7}]}}, {customer: {companies: [{revenue: 5}, {revenue: 7}], firstRevenue: 5}}], + ], +} + +{ + name: "arithmetic on an index read guarded with ??", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.safe", value: "(customer.companies[0].revenue ?? 0) + 1"}, + {expression: "customer.last", value: "(customer.companies[1].revenue ?? 0) * 2"}, + ], + }, + cases: [ + [{customer: {companies: []}}, {customer: {companies: [], safe: 1, last: 0}}], + [{customer: {companies: [{revenue: 5}]}}, {customer: {companies: [{revenue: 5}], safe: 6, last: 0}}], + [{customer: {companies: [{revenue: 5}, {revenue: 7}]}}, {customer: {companies: [{revenue: 5}, {revenue: 7}], safe: 6, last: 14}}], + ], +} + +{ + name: "unguarded arithmetic on an index read fails on an empty list", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.first", value: "customer.companies[0].revenue + 1"}], + }, + cases: [ + [{customer: {companies: [{revenue: 5}]}}, {customer: {companies: [{revenue: 5}], first: 6}}], + [{customer: {companies: []}}, "!error: ExpressionFailed"], + [{customer: {companies: null}}, "!error: MissingRequiredInputs"], + [{customer: {}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a length guard protects an index read", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {scores: "number[]"}}, + blocks: [{expression: "customer.top", value: "len(customer.scores) > 0 ? customer.scores[0] * 10 : -1"}], + }, + cases: [ + [{customer: {scores: []}}, {customer: {scores: [], top: -1}}], + [{customer: {scores: [3]}}, {customer: {scores: [3], top: 30}}], + [{customer: {scores: [0, 9]}}, {customer: {scores: [0, 9], top: 0}}], + ], +} + +{ + name: "an out-of-range index on a scalar list is null", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {scores: "number[]"}}, + blocks: [ + {expression: "customer.third", value: "customer.scores[2]"}, + {expression: "customer.thirdOr", value: "customer.scores[2] ?? 'none'"}, + ], + }, + cases: [ + [{customer: {scores: []}}, {customer: {scores: [], third: null, thirdOr: "none"}}], + [{customer: {scores: [1, 2]}}, {customer: {scores: [1, 2], third: null, thirdOr: "none"}}], + [{customer: {scores: [1, 2, 3]}}, {customer: {scores: [1, 2, 3], third: 3, thirdOr: 3}}], + ], +} + +// --- Null through match -------------------------------------------------------------------------- + +{ + name: "match on an optional enum falls to the default when null", + policy: { + models: {customer: {tier: "string(gold|silver)?"}}, + blocks: [ + {match: "customer.disc", arms: [["customer.tier == 'gold'", "10"], ["customer.tier == 'silver'", "5"], ["", "0"]]}, + {match: "customer.label", arms: [["customer.tier == null", "'none'"], ["", "customer.tier"]]}, + ], + }, + cases: [ + [{customer: {tier: "gold"}}, {customer: {tier: "gold", disc: 10, label: "gold"}}], + [{customer: {tier: "silver"}}, {customer: {tier: "silver", disc: 5, label: "silver"}}], + [{customer: {tier: null}}, {customer: {tier: null, disc: 0, label: "none"}}], + [{customer: {}}, {customer: {disc: 0, label: "none"}}], + [{customer: {tier: "bronze"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an ordering condition on a null optional fails the match", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {score: "number?"}}, + blocks: [{match: "customer.band", arms: [["customer.score > 10", "'hi'"], ["", "'lo'"]]}], + }, + cases: [ + [{customer: {score: 50}}, {customer: {score: 50, band: "hi"}}], + [{customer: {score: 10}}, {customer: {score: 10, band: "lo"}}], + [{customer: {score: null}}, "!error: ExpressionFailed"], + [{customer: {}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a null guard before an ordering condition", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {score: "number?"}}, + blocks: [{match: "customer.band", arms: [["customer.score == null", "'unknown'"], ["customer.score > 10", "'hi'"], ["", "'lo'"]]}], + }, + cases: [ + [{customer: {score: 50}}, {customer: {score: 50, band: "hi"}}], + [{customer: {score: 10}}, {customer: {score: 10, band: "lo"}}], + [{customer: {score: null}}, {customer: {score: null, band: "unknown"}}], + [{customer: {}}, {customer: {band: "unknown"}}], + ], +} + +{ + name: "a match without default writes null when nothing matches", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {match: "customer.kind", arms: [["customer.age > 10", "'big'"]]}, + {expression: "customer.label", value: "customer.kind ?? 'small'"}, + ], + }, + cases: [ + [{customer: {age: 11}}, {customer: {age: 11, kind: "big", label: "big"}}], + [{customer: {age: 1}}, {customer: {age: 1, kind: null, label: "small"}}], + [{customer: {age: 10}}, {customer: {age: 10, kind: null, label: "small"}}], + ], +} + +{ + name: "a match arm value that is null", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.limit", arms: [["customer.age < 18", "null"], ["", "customer.age * 100"]]}], + }, + cases: [ + [{customer: {age: 5}}, {customer: {age: 5, limit: null}}], + [{customer: {age: 20}}, {customer: {age: 20, limit: 2000}}], + ], +} + +// --- Null through decision tables -------------------------------------------------------------- + +{ + name: "a table over an optional column with an explicit null row", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number?"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.band"], rules: [["null", "'unknown'"], ["< 18", "'minor'"], ["", "'adult'"]]}], + }, + cases: [ + [{customer: {age: 10}}, {customer: {age: 10, band: "minor"}}], + [{customer: {age: 30}}, {customer: {age: 30, band: "adult"}}], + [{customer: {age: null}}, {customer: {age: null, band: "unknown"}}], + [{customer: {}}, {customer: {band: "unknown"}}], + ], +} + +{ + name: "a table with ordering cells over a null optional", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number?"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.band"], rules: [["< 18", "'minor'"], [">= 18", "'adult'"], ["", "'unknown'"]]}], + }, + cases: [ + [{customer: {age: 10}}, {customer: {age: 10, band: "minor"}}], + [{customer: {age: 30}}, {customer: {age: 30, band: "adult"}}], + {input: {customer: {age: null}}, output: {customer: {age: null, band: "unknown"}}, note: "bug: a failing cell (null < 18) aborts the policy; graph decision tables treat a failing cell as no match and fall through"}, + {input: {customer: {}}, output: {customer: {band: "unknown"}}, note: "bug: a failing cell (null < 18) aborts the policy; graph decision tables treat a failing cell as no match and fall through"}, + ], +} + +{ + name: "a table with no matching row over an optional writes null", + policy: { + models: {customer: {code: "string?"}}, + blocks: [{table: "t", inputs: ["customer.code"], outputs: ["customer.region"], rules: [["'NO'", "'north'"], ["'IT'", "'south'"]]}], + }, + cases: [ + [{customer: {code: "NO"}}, {customer: {code: "NO", region: "north"}}], + [{customer: {code: "IT"}}, {customer: {code: "IT", region: "south"}}], + [{customer: {code: "DE"}}, {customer: {code: "DE", region: null}}], + [{customer: {code: null}}, {customer: {code: null, region: null}}], + [{customer: {}}, {customer: {region: null}}], + ], +} + +{ + name: "a table output cell that evaluates to null", + policy: { + models: {customer: {age: "number", nickname: "string?"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.display"], rules: [["< 18", "customer.nickname"], ["", "'adult'"]]}], + }, + cases: [ + [{customer: {age: 5, nickname: "kid"}}, {customer: {age: 5, nickname: "kid", display: "kid"}}], + [{customer: {age: 5}}, {customer: {age: 5, display: null}}], + [{customer: {age: 50}}, {customer: {age: 50, display: "adult"}}], + ], +} + +// --- Null through assertions ------------------------------------------------------------------ + +{ + name: "an assertion over optional values", + policy: { + models: {customer: {nickname: "string?", score: "number?"}}, + blocks: [{assertion: "customer.complete", conditions: ["customer.nickname != null", "(customer.score ?? 0) > 0"]}], + }, + cases: [ + [{customer: {nickname: "a", score: 1}}, {customer: {nickname: "a", score: 1, complete: true}}], + [{customer: {nickname: "a"}}, {customer: {nickname: "a", complete: false}}], + [{customer: {score: 1}}, {customer: {score: 1, complete: false}}], + [{customer: {}}, {customer: {complete: false}}], + [{customer: {nickname: null, score: null}}, {customer: {nickname: null, score: null, complete: false}}], + ], +} + +{ + name: "a table over the null output of an unmatched table", + policy: { + models: {a: {m: "string"}}, + blocks: [ + {table: "p", inputs: ["a.m"], outputs: ["a.k"], rules: [["'yes'", "'hit'"]]}, + {table: "cls", inputs: ["a.k"], outputs: ["a.cls"], rules: [["null", "'null'"], ["", "'other'"]]}, + ], + }, + cases: [ + [{a: {m: "yes"}}, {a: {m: "yes", k: "hit", cls: "other"}}], + [{a: {m: "no"}}, {a: {m: "no", k: null, cls: "null"}}], + ], +} + +{ + name: "a table over the null output of a match without a default arm", + policy: { + models: {a: {m: "string"}}, + blocks: [ + {match: "a.k", arms: [["a.m == 'yes'", "'hit'"], ["", "null"]]}, + {table: "cls", inputs: ["a.k"], outputs: ["a.cls"], rules: [["null", "'null'"], ["", "'other'"]]}, + ], + }, + cases: [ + [{a: {m: "yes"}}, {a: {m: "yes", k: "hit", cls: "other"}}], + [{a: {m: "no"}}, {a: {m: "no", k: null, cls: "null"}}], + ], +} + +{ + name: "boolean and number tables over the null outputs of an unmatched table", + policy: { + models: {a: {m: "string"}}, + blocks: [ + {table: "p", inputs: ["a.m"], outputs: ["a.b", "a.n"], rules: [["'yes'", "true", "5"]]}, + {table: "cls", inputs: ["a.b", "a.n"], outputs: ["a.bc", "a.nc"], rules: [["null", "null", "'null'", "'null'"], ["true", "5", "'true'", "'five'"], ["", "", "'other'", "'other'"]]}, + ], + }, + cases: [ + [{a: {m: "yes"}}, {a: {m: "yes", b: true, n: 5, bc: "true", nc: "five"}}], + [{a: {m: "no"}}, {a: {m: "no", b: null, n: null, bc: "null", nc: "null"}}], + ], +} + +{ + name: "a table over an absent optional field with a null row", + policy: { + models: {a: {k: "string?"}}, + blocks: [{table: "cls", inputs: ["a.k"], outputs: ["a.cls"], rules: [["null", "'null'"], ["", "'other'"]]}], + }, + cases: [ + [{a: {}}, {a: {cls: "null"}}], + [{a: {k: null}}, {a: {k: null, cls: "null"}}], + [{a: {k: "x"}}, {a: {k: "x", cls: "other"}}], + ], +} + +// --- Null through intermediates --------------------------------------------------------------- + +{ + name: "a computed null flows into the next block", + diagnostics: ["INVALID_EXPRESSION"], + policy: { + models: {customer: {email: "string?"}}, + blocks: [ + {expression: "customer.domain", value: "customer.email == null ? null : split(customer.email, '@')[1]"}, + {expression: "customer.corporate", value: "(customer.domain ?? '') == 'acme.com'"}, + {expression: "customer.domainLabel", value: "customer.domain ?? 'none'"}, + ], + }, + cases: [ + [{customer: {email: "a@acme.com"}}, {customer: {email: "a@acme.com", domain: "acme.com", corporate: true, domainLabel: "acme.com"}}], + [{customer: {email: "b@x.org"}}, {customer: {email: "b@x.org", domain: "x.org", corporate: false, domainLabel: "x.org"}}], + [{customer: {}}, {customer: {domain: null, corporate: false, domainLabel: "none"}}], + [{customer: {email: "nodomain"}}, {customer: {email: "nodomain", domain: null, corporate: false, domainLabel: "none"}}], + ], +} + +// --- Null fields on per-instance writes --------------------------------------------------------- + +{ + name: "per-instance writes over optional fields", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number?"}}, + blocks: [ + {expression: "company.known", value: "company.revenue != null"}, + {expression: "company.rev", value: "company.revenue ?? 0"}, + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue ?? 0))"}, + ], + }, + cases: [ + [{customer: {companies: []}}, {customer: {companies: [], total: 0}}], + [{customer: {companies: [{revenue: 5}, {}]}}, {customer: {companies: [{revenue: 5, known: true, rev: 5}, {known: false, rev: 0}], total: 5}}], + [{customer: {companies: [{revenue: null}]}}, {customer: {companies: [{revenue: null, known: false, rev: 0}], total: 0}}], + ], +} diff --git a/core/engine/tests/spec/policy/16-policy-errors.json5 b/core/engine/tests/spec/policy/16-policy-errors.json5 new file mode 100644 index 00000000..8dd0bac8 --- /dev/null +++ b/core/engine/tests/spec/policy/16-policy-errors.json5 @@ -0,0 +1,594 @@ +// Errors at evaluate time. Evaluation fails with one of: +// ImportNotFound, GoalNotFound, InputValidationFailed (input shape vs data model), +// MissingRequiredInputs (a required read is missing or null), ExpressionFailed (a parse or +// runtime error in a block that runs). +// Validation diagnostics (DuplicateWriter, InputOverride, CyclicDependency, +// MissingDefaultBranch, ...) do not stop evaluation; their runtime outcome is pinned here. + +// --- Input validation: the request shape ------------------------------------------------------- + +{ + name: "the request must be an object", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.a", value: "customer.age"}], + }, + cases: [ + [5, "!error: InputValidationFailed"], + ["x", "!error: InputValidationFailed"], + [true, "!error: InputValidationFailed"], + [[1], "!error: InputValidationFailed"], + [[], "!error: InputValidationFailed"], + [{customer: {age: 1}}, {customer: {age: 1, a: 1}}], + ], +} + +{ + name: "an entity value must be an object", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.a", value: "customer.age"}], + }, + cases: [ + [{customer: 5}, "!error: InputValidationFailed"], + [{customer: "x"}, "!error: InputValidationFailed"], + [{customer: [1]}, "!error: InputValidationFailed"], + [{customer: [{age: 1}]}, "!error: InputValidationFailed"], + [{customer: true}, "!error: InputValidationFailed"], + ], +} + +{ + name: "property values must match their declared type", + policy: { + models: {customer: {age: "number", name: "string", vip: "boolean", dob: "date", tier: "string(a|b)"}}, + blocks: [{expression: "customer.ok", value: "true"}], + }, + cases: [ + [{customer: {age: 1, name: "n", vip: true, dob: "2000-01-01", tier: "a"}}, {customer: {age: 1, name: "n", vip: true, dob: "2000-01-01", tier: "a", ok: true}}], + [{customer: {age: "1"}}, "!error: InputValidationFailed"], + [{customer: {age: true}}, "!error: InputValidationFailed"], + [{customer: {age: [1]}}, "!error: InputValidationFailed"], + [{customer: {age: {v: 1}}}, "!error: InputValidationFailed"], + [{customer: {name: 1}}, "!error: InputValidationFailed"], + [{customer: {name: ["n"]}}, "!error: InputValidationFailed"], + [{customer: {vip: "true"}}, "!error: InputValidationFailed"], + [{customer: {vip: 1}}, "!error: InputValidationFailed"], + [{customer: {dob: "yesterday"}}, "!error: InputValidationFailed"], + [{customer: {dob: 20000101}}, "!error: InputValidationFailed"], + [{customer: {tier: "c"}}, "!error: InputValidationFailed"], + [{customer: {tier: "A"}}, "!error: InputValidationFailed"], + [{customer: {}}, {customer: {ok: true}}], + ], +} + +{ + name: "array properties validate every element", + policy: { + models: {customer: {scores: "number[]", companies: "company[]"}, company: {name: "string"}}, + blocks: [{expression: "customer.n", value: "len(customer.scores) + len(customer.companies)"}], + }, + cases: [ + [{customer: {scores: [1, 2], companies: [{name: "a"}]}}, {customer: {scores: [1, 2], companies: [{name: "a"}], n: 3}}], + [{customer: {scores: [1, "2"], companies: []}}, "!error: InputValidationFailed"], + [{customer: {scores: 1, companies: []}}, "!error: InputValidationFailed"], + [{customer: {scores: [], companies: [{name: 1}]}}, "!error: InputValidationFailed"], + [{customer: {scores: [], companies: {name: "a"}}}, "!error: InputValidationFailed"], + [{customer: {scores: [], companies: ["a"]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "unknown input keys are kept and not validated", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.a", value: "customer.age"}], + }, + cases: [ + [{customer: {age: 1, extra: "x"}}, {customer: {age: 1, extra: "x", a: 1}}], + [{other: 1, customer: {age: 1}}, {other: 1, customer: {age: 1, a: 1}}], + [{other: {deep: [null]}, customer: {age: 1}}, {other: {deep: [null]}, customer: {age: 1, a: 1}}], + ], +} + +{ + name: "validation runs before the required-input check", + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{expression: "customer.a", value: "customer.age + 1"}], + }, + cases: [ + [{customer: {name: 5}}, "!error: InputValidationFailed"], + [{customer: {name: "x"}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Required inputs ----------------------------------------------------------------------------- + +{ + name: "every missing required input is reported at once", + policy: { + models: {customer: {a: "number", b: "number", c: "number"}}, + blocks: [{expression: "customer.sum", value: "customer.a + customer.b + customer.c"}], + }, + cases: [ + [{customer: {a: 1, b: 2, c: 3}}, {customer: {a: 1, b: 2, c: 3, sum: 6}}], + [{customer: {a: 1}}, "!error: missing: [\"customer.b\", \"customer.c\"]"], + [{customer: {}}, "!error: missing: [\"customer.a\", \"customer.b\", \"customer.c\"]"], + [{customer: {a: 1, b: null, c: 3}}, "!error: missing: [\"customer.b\"]"], + ], +} + +{ + name: "an undeclared read is a required input", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.a", value: "customer.zzz + 1"}], + }, + cases: [ + [{customer: {age: 1}}, "!error: MissingRequiredInputs"], + [{customer: {age: 1, zzz: 4}}, {customer: {age: 1, zzz: 4, a: 5}}], + [{customer: {age: 1, zzz: "4"}}, "!error: ExpressionFailed"], + ], +} + +// --- Expression failures --------------------------------------------------------------------------- + +{ + name: "a parse error fails the evaluation when the block runs", + diagnostics: ["PARSE_ERROR"], + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.a", value: "customer.age +"}, + {expression: "customer.b", value: "customer.age * 2"}, + ], + }, + cases: [ + [{customer: {age: 1}}, "!error: ExpressionFailed"], + {input: {customer: {age: 1}}, goals: ["customer.b"], output: {customer: {age: 1, b: 2}}}, + {input: {customer: {age: 1}}, goals: ["customer.a"], output: "!error: ExpressionFailed"}, + ], +} + +{ + name: "malformed expressions of several kinds", + diagnostics: ["PARSE_ERROR"], + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.a", value: "(customer.age"}, + {expression: "customer.b", value: "customer.age ==== 1"}, + {expression: "customer.c", value: "foo(customer.age)"}, + {expression: "customer.d", value: "'unterminated"}, + ], + }, + cases: [ + {input: {customer: {age: 1}}, goals: ["customer.a"], output: "!error: ExpressionFailed"}, + {input: {customer: {age: 1}}, goals: ["customer.b"], output: "!error: ExpressionFailed"}, + {input: {customer: {age: 1}}, goals: ["customer.c"], output: "!error: ExpressionFailed"}, + {input: {customer: {age: 1}}, goals: ["customer.d"], output: "!error: ExpressionFailed"}, + ], +} + +{ + name: "operand type errors fail the evaluation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {name: "string", age: "number", vip: "boolean"}}, + blocks: [ + {expression: "customer.a", value: "customer.name + customer.age"}, + {expression: "customer.b", value: "customer.name * 2"}, + {expression: "customer.c", value: "customer.vip + 1"}, + {expression: "customer.d", value: "customer.name > 1"}, + {expression: "customer.e", value: "customer.age + 1"}, + ], + }, + cases: [ + {input: {customer: {name: "x", age: 1, vip: true}}, goals: ["customer.a"], output: "!error: ExpressionFailed"}, + {input: {customer: {name: "x", age: 1, vip: true}}, goals: ["customer.b"], output: "!error: ExpressionFailed"}, + {input: {customer: {name: "x", age: 1, vip: true}}, goals: ["customer.c"], output: "!error: ExpressionFailed"}, + {input: {customer: {name: "x", age: 1, vip: true}}, goals: ["customer.d"], output: "!error: ExpressionFailed"}, + {input: {customer: {name: "x", age: 1, vip: true}}, goals: ["customer.e"], output: {customer: {name: "x", age: 1, vip: true, e: 2}}}, + {input: {customer: {name: "x", age: 1, vip: true}}, output: "!error: ExpressionFailed"}, + ], +} + +{ + name: "division by zero yields null, not an error", + policy: { + models: {customer: {a: "number", b: "number"}}, + blocks: [ + {expression: "customer.q", value: "customer.a / customer.b"}, + {expression: "customer.safe", value: "customer.q ?? 0"}, + ], + }, + cases: [ + [{customer: {a: 6, b: 3}}, {customer: {a: 6, b: 3, q: 2, safe: 2}}], + [{customer: {a: 6, b: 0}}, {customer: {a: 6, b: 0, q: null, safe: 0}}], + [{customer: {a: 0, b: 0}}, {customer: {a: 0, b: 0, q: null, safe: 0}}], + [{customer: {a: -1, b: 0}}, {customer: {a: -1, b: 0, q: null, safe: 0}}], + ], +} + +{ + name: "a failure downstream of a successful block fails the whole evaluation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [ + {expression: "customer.label", value: "customer.name + '!'"}, + {expression: "customer.broken", value: "customer.label - 1"}, + ], + }, + cases: [ + [{customer: {age: 1, name: "x"}}, "!error: ExpressionFailed"], + {input: {customer: {age: 1, name: "x"}}, goals: ["customer.label"], output: {customer: {age: 1, name: "x", label: "x!"}}}, + ], +} + +{ + name: "a failing function call", + policy: { + models: {customer: {code: "string"}}, + blocks: [{expression: "customer.n", value: "number(customer.code)"}], + }, + cases: [ + [{customer: {code: "42"}}, {customer: {code: "42", n: 42}}], + [{customer: {code: "4.5"}}, {customer: {code: "4.5", n: 4.5}}], + [{customer: {code: "abc"}}, "!error: ExpressionFailed"], + [{customer: {code: ""}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "an error in an imported policy's block fails the importer's evaluation", + diagnostics: ["TYPE_MISMATCH", "UNDEFINED_VARIABLE"], + policy: { + imports: ["base"], + models: {customer: {name: "string"}}, + blocks: [{expression: "customer.ok", value: "customer.base != null"}], + }, + policies: { + base: {models: {customer: {name: "string"}}, blocks: [{expression: "customer.base", value: "customer.name * 2"}]}, + }, + cases: [ + [{customer: {name: "x"}}, "!error: policy_path: \"base\""], + [{customer: {name: ""}}, "!error: ExpressionFailed"], + ], +} + +// --- Laziness: blocks that never run cannot fail ------------------------------------------------ + +{ + name: "an erroring dependency of an untaken match arm does not run", + diagnostics: ["TYPE_MISMATCH", "UNDEFINED_VARIABLE"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [ + {expression: "customer.bad", value: "customer.name + 1"}, + {match: "customer.a", arms: [["customer.age > 10", "customer.bad"], ["", "'ok'"]]}, + ], + }, + cases: [ + [{customer: {age: 1, name: "x"}}, {customer: {age: 1, name: "x", a: "ok"}}], + [{customer: {age: 10, name: "x"}}, {customer: {age: 10, name: "x", a: "ok"}}], + [{customer: {age: 11, name: "x"}}, "!error: ExpressionFailed"], + {input: {customer: {age: 1, name: "x"}}, goals: ["customer.a"], output: {customer: {age: 1, name: "x", a: "ok"}}}, + {input: {customer: {age: 1, name: "x"}}, goals: ["customer.bad"], output: "!error: ExpressionFailed"}, + ], +} + +{ + name: "an erroring dependency of an unmatched table row does not run", + diagnostics: ["TYPE_MISMATCH", "UNDEFINED_VARIABLE"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [ + {expression: "customer.bad", value: "customer.name * 3"}, + {table: "t", inputs: ["customer.age"], outputs: ["customer.res"], rules: [["< 18", "customer.bad"], ["", "'fine'"]]}, + ], + }, + cases: [ + [{customer: {age: 30, name: "x"}}, {customer: {age: 30, name: "x", res: "fine"}}], + [{customer: {age: 18, name: "x"}}, {customer: {age: 18, name: "x", res: "fine"}}], + [{customer: {age: 17, name: "x"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "an erroring arm value that is not selected does not run", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{match: "customer.a", arms: [["customer.age > 10", "customer.name * 2"], ["", "customer.age"]]}], + }, + cases: [ + [{customer: {age: 1, name: "x"}}, {customer: {age: 1, name: "x", a: 1}}], + [{customer: {age: 11, name: "x"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a ternary branch that is not taken does not fail", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{expression: "customer.a", value: "customer.age > 10 ? customer.name * 2 : 0"}], + }, + cases: [ + [{customer: {age: 1, name: "x"}}, {customer: {age: 1, name: "x", a: 0}}], + [{customer: {age: 11, name: "x"}}, "!error: ExpressionFailed"], + ], +} + +// --- Assertions -------------------------------------------------------------------------------- + +{ + name: "every assertion condition is evaluated, even after a false one", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{assertion: "customer.ok", conditions: ["customer.age > 1", "customer.name > 1"]}], + }, + cases: [ + [{customer: {age: 5, name: "x"}}, "!error: ExpressionFailed"], + {input: {customer: {age: 0, name: "x"}}, output: "!error: ExpressionFailed", note: "question: the first `and` condition is false, yet the second condition still runs and fails the policy"}, + ], +} + +{ + name: "an assertion over a missing required input", + policy: { + models: {customer: {age: "number"}}, + blocks: [{assertion: "customer.ok", conditions: ["customer.age >= 18"]}], + }, + cases: [ + [{customer: {age: 18}}, {customer: {age: 18, ok: true}}], + [{customer: {}}, "!error: MissingRequiredInputs"], + [{customer: {age: null}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Decision table cells ---------------------------------------------------------------------- + +{ + name: "a malformed input cell fails when the row is tested", + diagnostics: ["PARSE_ERROR"], + policy: { + models: {customer: {age: "number"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.b"], rules: [["> > 1", "1"], ["", "2"]]}], + }, + cases: [ + [{customer: {age: 5}}, "!error: ExpressionFailed"], + [{customer: {age: 0}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a malformed cell in a later row is not reached after a first hit", + diagnostics: ["PARSE_ERROR"], + policy: { + models: {customer: {age: "number"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.b"], rules: [["> 1", "1"], ["> > 1", "2"]]}], + }, + cases: [ + [{customer: {age: 5}}, {customer: {age: 5, b: 1}}], + [{customer: {age: 0}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a failing output cell of the matched row", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.b"], rules: [["< 18", "customer.name * 2"], ["", "'ok'"]]}], + }, + cases: [ + [{customer: {age: 30, name: "x"}}, {customer: {age: 30, name: "x", b: "ok"}}], + [{customer: {age: 3, name: "x"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "an input cell comparing the wrong type", + policy: { + models: {customer: {code: "string"}}, + blocks: [{table: "t", inputs: ["customer.code"], outputs: ["customer.b"], rules: [["> 5", "'big'"], ["", "'other'"]]}], + }, + cases: [ + {input: {customer: {code: "x"}}, output: {customer: {code: "x", b: "other"}}, note: "bug: a failing cell ('x' > 5) aborts the policy; graph decision tables treat a failing cell as no match"}, + ], +} + +// --- Validation diagnostics that do not stop evaluation -------------------------------------------- + +{ + name: "two blocks writing the same property", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.a", value: "1"}, + {expression: "customer.a", value: "2"}, + ], + }, + cases: [ + {input: {customer: {age: 1}}, output: {customer: {age: 1, a: 1}}, note: "question: DuplicateWriter is an error diagnostic; evaluation silently keeps the first writer"}, + {input: {customer: {age: 9}}, output: {customer: {age: 9, a: 1}}, note: "question: DuplicateWriter is an error diagnostic; evaluation silently keeps the first writer"}, + ], +} + +{ + name: "a match and a table writing the same property", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {match: "customer.band", arms: [["customer.age < 18", "'minor'"], ["", "'adult'"]]}, + {table: "t", inputs: ["customer.age"], outputs: ["customer.band"], rules: [["", "'table'"]]}, + ], + }, + cases: [ + {input: {customer: {age: 1}}, output: {customer: {age: 1, band: "minor"}}, note: "question: DuplicateWriter is an error diagnostic; evaluation silently keeps the first writer"}, + {input: {customer: {age: 30}}, output: {customer: {age: 30, band: "adult"}}, note: "question: DuplicateWriter is an error diagnostic; evaluation silently keeps the first writer"}, + ], +} + +{ + name: "a block writing a declared input property", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.age", value: "99"}, + {expression: "customer.b", value: "customer.age + 1"}, + ], + }, + cases: [ + {input: {customer: {age: 1}}, output: {customer: {age: 1, b: 2}}, note: "question: InputOverride is an error diagnostic; evaluation drops the write and keeps the input"}, + {input: {customer: {age: 50}}, output: {customer: {age: 50, b: 51}}, note: "question: InputOverride is an error diagnostic; evaluation drops the write and keeps the input"}, + [{customer: {}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a computed property declared in the model is required input and its write is dropped", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + models: {customer: {age: "number", adult: "boolean"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.label", value: "customer.adult ? 'adult' : 'minor'"}, + ], + }, + cases: [ + {input: {customer: {age: 20}}, output: "!error: MissingRequiredInputs", note: "question: InputOverride is an error diagnostic; evaluation treats the declared property as required input"}, + {input: {customer: {age: 20, adult: false}}, output: {customer: {age: 20, adult: false, label: "minor"}}, note: "question: InputOverride is an error diagnostic; evaluation drops the write and keeps the input"}, + ], +} + +{ + name: "an optional declared property written by a block keeps the input", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + models: {customer: {age: "number", adult: "boolean?"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + {input: {customer: {age: 20}}, output: {customer: {age: 20}}, note: "question: InputOverride is an error diagnostic; evaluation drops the write, so the property stays absent"}, + {input: {customer: {age: 20, adult: false}}, output: {customer: {age: 20, adult: false}}, note: "question: InputOverride is an error diagnostic; evaluation drops the write and keeps the input"}, + ], +} + +{ + name: "a block reading its own write sees the input value", + diagnostics: ["SELF_REFERENCING_WRITE", "UNDEFINED_VARIABLE"], + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.a", value: "(customer.a ?? 0) + 1"}], + }, + cases: [ + {input: {customer: {age: 1}}, output: {customer: {age: 1, a: 1}}}, + {input: {customer: {age: 1, a: 5}}, output: {customer: {age: 1, a: 6}}, note: "question: SelfReferencingWrite is an error diagnostic; evaluation reads the input value of the property being written"}, + ], +} + +{ + name: "two blocks depending on each other", + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer.a", value: "customer.b + 1"}, + {expression: "customer.b", value: "customer.a + 1"}, + {expression: "customer.c", value: "customer.age"}, + ], + }, + cases: [ + {input: {customer: {age: 1}}, output: "!error"}, + {input: {customer: {age: 7}}, output: "!error"}, + ], +} + +{ + name: "a match without a default arm writes null when nothing matches", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.a", arms: [["customer.age > 10", "'big'"]]}], + }, + cases: [ + [{customer: {age: 11}}, {customer: {age: 11, a: "big"}}], + {input: {customer: {age: 1}}, output: {customer: {age: 1, a: null}}, note: "question: MissingDefaultBranch is an error diagnostic; at runtime the match falls through to null"}, + ], +} + +{ + name: "a match with no arms writes null", + policy: { + models: {customer: {age: "number"}}, + blocks: [{match: "customer.a", arms: []}], + }, + cases: [ + {input: {customer: {age: 5}}, output: {customer: {age: 5, a: null}}, note: "question: EmptyBlock is a diagnostic; at runtime the match writes null"}, + ], +} + +{ + name: "an expression block with an empty value writes nothing", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.b", value: ""}, {expression: "customer.c", value: "customer.age"}], + }, + cases: [ + {input: {customer: {age: 5}}, output: {customer: {age: 5, c: 5}}, note: "question: an empty expression block is skipped silently rather than writing null or failing"}, + ], +} + +{ + name: "blocks with invalid write paths are skipped", + diagnostics: ["INVALID_WRITE_PATH"], + policy: { + models: {customer: {age: "number"}}, + blocks: [ + {expression: "customer..a", value: "1"}, + {expression: "", value: "2"}, + {expression: "customer.b", value: "3"}, + ], + }, + cases: [ + {input: {customer: {age: 5}}, output: {customer: {age: 5, b: 3}}, note: "question: InvalidWritePath blocks are dropped silently at evaluate time"}, + ], +} + +// --- Request errors -------------------------------------------------------------------------------- + +{ + name: "an unknown goal is rejected before input validation", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.a", value: "customer.age"}], + }, + cases: [ + {input: {customer: {age: "bad"}}, goals: ["customer.zzz"], output: "!error: GoalNotFound"}, + {input: {customer: {age: "bad"}}, goals: ["customer.a"], output: "!error: InputValidationFailed"}, + {input: {customer: {}}, goals: ["customer.a"], output: "!error: MissingRequiredInputs"}, + ], +} + +{ + name: "a missing import is reported before anything else", + diagnostics: ["IMPORT_NOT_FOUND"], + policy: { + imports: ["gone"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.a", value: "customer.age"}], + }, + cases: [ + {input: {customer: {age: "bad"}}, output: "!error: ImportNotFound"}, + {input: {customer: {age: 1}}, goals: ["customer.zzz"], output: "!error: ImportNotFound"}, + {input: 5, output: "!error: ImportNotFound"}, + ], +} diff --git a/core/engine/tests/spec/policy/17-policy-values.json5 b/core/engine/tests/spec/policy/17-policy-values.json5 new file mode 100644 index 00000000..e4566715 --- /dev/null +++ b/core/engine/tests/spec/policy/17-policy-values.json5 @@ -0,0 +1,525 @@ +// Values through policies: dates, exact decimals, strings, booleans and enums, then realistic +// multi-block policies. Evaluation time is fixed at 2025-03-20T10:15:30Z (UTC). + +// --- Dates ------------------------------------------------------------------------------------ +// A `date` property accepts date strings; an input date is kept as its source text in the +// output, a computed date is written in its full form. + +{ + name: "a date input passes through unchanged", + policy: { + models: {customer: {dob: "date"}}, + blocks: [{expression: "customer.dobCopy", value: "customer.dob"}], + }, + cases: [ + [{customer: {dob: "1990-05-01"}}, {customer: {dob: "1990-05-01", dobCopy: "1990-05-01"}}], + [{customer: {dob: "1990-05-01T10:00:00Z"}}, {customer: {dob: "1990-05-01T10:00:00Z", dobCopy: "1990-05-01T10:00:00Z"}}], + [{customer: {dob: date('2000-02-29')}}, {customer: {dob: "2000-02-29", dobCopy: "2000-02-29"}}], + [{customer: {dob: "not a date"}}, "!error: InputValidationFailed"], + [{customer: {dob: 12345}}, "!error: InputValidationFailed"], + [{customer: {dob: true}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "age from a date of birth", + policy: { + models: {customer: {dob: "date"}}, + blocks: [ + {expression: "customer.age", value: "d().diff(customer.dob, 'year')"}, + {expression: "customer.adult", value: "customer.age >= 18"}, + ], + }, + cases: [ + [{customer: {dob: "1990-05-01"}}, {customer: {dob: "1990-05-01", age: 34, adult: true}}], + [{customer: {dob: "2007-03-20"}}, {customer: {dob: "2007-03-20", age: 18, adult: true}}], + [{customer: {dob: "2007-03-21"}}, {customer: {dob: "2007-03-21", age: 17, adult: false}}], + [{customer: {dob: "2025-01-01"}}, {customer: {dob: "2025-01-01", age: 0, adult: false}}], + [{customer: {dob: "1925-03-20"}}, {customer: {dob: "1925-03-20", age: 100, adult: true}}], + ], +} + +{ + name: "date arithmetic and parts", + policy: { + models: {customer: {dob: "date"}}, + blocks: [ + {expression: "customer.nextYear", value: "customer.dob.add(1, 'year')"}, + {expression: "customer.year", value: "customer.dob.year()"}, + {expression: "customer.month", value: "customer.dob.month()"}, + {expression: "customer.str", value: "customer.dob.format('%Y-%m-%d')"}, + ], + }, + cases: [ + [{customer: {dob: "1990-05-01"}}, {customer: {dob: "1990-05-01", nextYear: "1991-05-01T00:00:00Z", year: 1990, month: 5, str: "1990-05-01"}}], + [{customer: {dob: "1990-05-01T10:00:00Z"}}, {customer: {dob: "1990-05-01T10:00:00Z", nextYear: "1991-05-01T10:00:00Z", year: 1990, month: 5, str: "1990-05-01"}}], + [{customer: {dob: "2024-01-31"}}, {customer: {dob: "2024-01-31", nextYear: "2025-01-31T00:00:00Z", year: 2024, month: 1, str: "2024-01-31"}}], + [{customer: {dob: "1999-12-31"}}, {customer: {dob: "1999-12-31", nextYear: "2000-12-31T00:00:00Z", year: 1999, month: 12, str: "1999-12-31"}}], + ], +} + +{ + name: "comparing dates", + policy: { + models: {contract: {start: "date", end: "date"}}, + blocks: [ + {expression: "contract.active", value: "d().isAfter(contract.start) and d().isBefore(contract.end)"}, + {expression: "contract.days", value: "contract.end.diff(contract.start, 'day')"}, + {expression: "contract.ordered", value: "contract.start < contract.end"}, + ], + }, + cases: [ + [{contract: {start: "2025-01-01", end: "2025-12-31"}}, {contract: {start: "2025-01-01", end: "2025-12-31", active: true, days: 364, ordered: true}}], + [{contract: {start: "2024-01-01", end: "2025-01-01"}}, {contract: {start: "2024-01-01", end: "2025-01-01", active: false, days: 366, ordered: true}}], + [{contract: {start: "2026-01-01", end: "2025-01-01"}}, {contract: {start: "2026-01-01", end: "2025-01-01", active: false, days: -365, ordered: false}}], + [{contract: {start: "2025-03-20", end: "2025-03-21"}}, {contract: {start: "2025-03-20", end: "2025-03-21", active: true, days: 1, ordered: true}}], + ], +} + +{ + name: "optional dates", + diagnostics: ["INVALID_EXPRESSION"], + policy: { + models: {customer: {joined: "date?"}}, + blocks: [ + {expression: "customer.isMember", value: "customer.joined != null"}, + {expression: "customer.tenureYears", value: "customer.joined == null ? 0 : d().diff(customer.joined, 'year')"}, + ], + }, + cases: [ + [{customer: {}}, {customer: {isMember: false, tenureYears: 0}}], + [{customer: {joined: null}}, {customer: {joined: null, isMember: false, tenureYears: 0}}], + [{customer: {joined: "2020-01-01"}}, {customer: {joined: "2020-01-01", isMember: true, tenureYears: 5}}], + [{customer: {joined: "2025-03-01"}}, {customer: {joined: "2025-03-01", isMember: true, tenureYears: 0}}], + [{customer: {joined: "2020-13-01"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a table over a date column", + policy: { + models: {claim: {filed: "date"}}, + blocks: [{table: "t", inputs: ["claim.filed"], outputs: ["claim.period"], rules: [ + ["< d('2025-01-01')", "'old'"], + ["< d('2025-03-01')", "'recent'"], + ["", "'current'"], + ]}], + }, + cases: [ + [{claim: {filed: "2024-06-01"}}, {claim: {filed: "2024-06-01", period: "old"}}], + [{claim: {filed: "2025-01-01"}}, {claim: {filed: "2025-01-01", period: "recent"}}], + [{claim: {filed: "2025-02-28T23:59:59Z"}}, {claim: {filed: "2025-02-28T23:59:59Z", period: "recent"}}], + [{claim: {filed: "2025-03-01"}}, {claim: {filed: "2025-03-01", period: "current"}}], + [{claim: {filed: "2030-01-01"}}, {claim: {filed: "2030-01-01", period: "current"}}], + ], +} + +{ + name: "per-instance date reads", + policy: { + models: {customer: {payments: "payment[]"}, payment: {due: "date", amount: "number"}}, + blocks: [ + {expression: "payment.overdue", value: "payment.due < d()"}, + {expression: "customer.overdueTotal", value: "sum(map(filter(customer.payments, #.due < d()), #.amount))"}, + ], + }, + cases: [ + [{customer: {payments: []}}, {customer: {payments: [], overdueTotal: 0}}], + [ + {customer: {payments: [{due: "2025-01-01", amount: 10}, {due: "2025-12-01", amount: 5}]}}, + {customer: {payments: [{due: "2025-01-01", amount: 10, overdue: true}, {due: "2025-12-01", amount: 5, overdue: false}], overdueTotal: 10}}, + ], + [ + {customer: {payments: [{due: "2025-03-20T10:15:29Z", amount: 1.5}, {due: "2025-03-20T10:15:31Z", amount: 2}]}}, + {customer: {payments: [{due: "2025-03-20T10:15:29Z", amount: 1.5, overdue: true}, {due: "2025-03-20T10:15:31Z", amount: 2, overdue: false}], overdueTotal: 1.5}}, + ], + ], +} + +// --- Exact decimals ------------------------------------------------------------------------------ + +{ + name: "money arithmetic is exact", + policy: { + models: {o: {price: "number", qty: "number"}}, + blocks: [ + {expression: "o.total", value: "o.price * o.qty"}, + {expression: "o.tax", value: "round(o.total * 0.21, 2)"}, + {expression: "o.gross", value: "o.total + o.tax"}, + ], + }, + cases: [ + [{o: {price: 19.99, qty: 3}}, {o: {price: 19.99, qty: 3, total: 59.97, tax: 12.59, gross: 72.56}}], + [{o: {price: 0.1, qty: 3}}, {o: {price: 0.1, qty: 3, total: 0.3, tax: 0.06, gross: 0.36}}], + [{o: {price: 0.1, qty: 0}}, {o: {price: 0.1, qty: 0, total: 0, tax: 0, gross: 0}}], + [{o: {price: 1e3, qty: -2}}, {o: {price: 1000, qty: -2, total: -2000, tax: -420, gross: -2420}}], + [{o: {price: 0.005, qty: 1}}, {o: {price: 0.005, qty: 1, total: 0.005, tax: 0, gross: 0.005}}], + [{o: {price: 123456789.12, qty: 100}}, {o: {price: 123456789.12, qty: 100, total: 12345678912, tax: 2592592571.52, gross: 14938271483.52}}], + ], +} + +{ + name: "division keeps full decimal precision", + policy: { + models: {o: {amount: "number"}}, + blocks: [ + {expression: "o.third", value: "o.amount / 3"}, + {expression: "o.rounded", value: "round(o.amount / 3, 2)"}, + {expression: "o.sum", value: "0.1 + 0.2"}, + ], + }, + cases: [ + [{o: {amount: 1}}, {o: {amount: 1, third: 0.3333333333333333333333333333, rounded: 0.33, sum: 0.3}}], + [{o: {amount: 20}}, {o: {amount: 20, third: 6.6666666666666666666666666667, rounded: 6.67, sum: 0.3}}], + [{o: {amount: 0}}, {o: {amount: 0, third: 0, rounded: 0, sum: 0.3}}], + [{o: {amount: -3}}, {o: {amount: -3, third: -1, rounded: -1, sum: 0.3}}], + ], +} + +{ + name: "decimal inputs compare by value in tables", + policy: { + models: {o: {rate: "number"}}, + blocks: [{table: "t", inputs: ["o.rate"], outputs: ["o.band"], rules: [["[0..0.1)", "'low'"], ["[0.1..0.25]", "'mid'"], ["> 0.25", "'high'"], ["", "'neg'"]]}], + }, + cases: [ + [{o: {rate: 0}}, {o: {rate: 0, band: "low"}}], + [{o: {rate: 0.0999999}}, {o: {rate: 0.0999999, band: "low"}}], + [{o: {rate: 0.1}}, {o: {rate: 0.1, band: "mid"}}], + [{o: {rate: 0.10}}, {o: {rate: 0.1, band: "mid"}}], + [{o: {rate: 0.25}}, {o: {rate: 0.25, band: "mid"}}], + [{o: {rate: 0.2500001}}, {o: {rate: 0.2500001, band: "high"}}], + [{o: {rate: -0.01}}, {o: {rate: -0.01, band: "neg"}}], + ], +} + +{ + name: "aggregates over decimal arrays", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [ + {expression: "cart.sum", value: "sum(cart.prices)"}, + {expression: "cart.avg", value: "len(cart.prices) == 0 ? 0 : avg(cart.prices)"}, + {expression: "cart.max", value: "len(cart.prices) == 0 ? 0 : max(cart.prices)"}, + ], + }, + cases: [ + [{cart: {prices: [0.1, 0.2, 0.3]}}, {cart: {prices: [0.1, 0.2, 0.3], sum: 0.6, avg: 0.2, max: 0.3}}], + [{cart: {prices: [10]}}, {cart: {prices: [10], sum: 10, avg: 10, max: 10}}], + [{cart: {prices: []}}, {cart: {prices: [], sum: 0, avg: 0, max: 0}}], + [{cart: {prices: [-1.5, 1.5]}}, {cart: {prices: [-1.5, 1.5], sum: 0, avg: 0, max: 1.5}}], + ], +} + +// --- Strings, booleans, enums ------------------------------------------------------------------ + +{ + name: "string operations", + policy: { + models: {u: {first: "string", last: "string"}}, + blocks: [ + {expression: "u.full", value: "u.first + ' ' + u.last"}, + {expression: "u.upper", value: "upper(u.full)"}, + {expression: "u.tpl", value: "`${u.last}, ${u.first}`"}, + {expression: "u.long", value: "len(u.full) > 10"}, + ], + }, + cases: [ + [{u: {first: "Ada", last: "Lovelace"}}, {u: {first: "Ada", last: "Lovelace", full: "Ada Lovelace", upper: "ADA LOVELACE", tpl: "Lovelace, Ada", long: true}}], + [{u: {first: "Bo", last: "Li"}}, {u: {first: "Bo", last: "Li", full: "Bo Li", upper: "BO LI", tpl: "Li, Bo", long: false}}], + [{u: {first: "Zoë", last: "Ek"}}, {u: {first: "Zoë", last: "Ek", full: "Zoë Ek", upper: "ZOË EK", tpl: "Ek, Zoë", long: false}}], + [{u: {first: "", last: ""}}, {u: {first: "", last: "", full: " ", upper: " ", tpl: ", ", long: false}}], + ], +} + +{ + name: "boolean logic over flags", + policy: { + models: {u: {vip: "boolean", blocked: "boolean", verified: "boolean"}}, + blocks: [ + {expression: "u.canBuy", value: "u.verified and not u.blocked"}, + {expression: "u.priority", value: "u.vip or u.verified"}, + {expression: "u.mismatch", value: "u.vip != u.verified"}, + ], + }, + cases: [ + [{u: {vip: true, blocked: false, verified: true}}, {u: {vip: true, blocked: false, verified: true, canBuy: true, priority: true, mismatch: false}}], + [{u: {vip: false, blocked: true, verified: true}}, {u: {vip: false, blocked: true, verified: true, canBuy: false, priority: true, mismatch: true}}], + [{u: {vip: false, blocked: false, verified: false}}, {u: {vip: false, blocked: false, verified: false, canBuy: false, priority: false, mismatch: false}}], + [{u: {vip: true, blocked: true, verified: false}}, {u: {vip: true, blocked: true, verified: false, canBuy: false, priority: true, mismatch: true}}], + [{u: {vip: "true", blocked: false, verified: true}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "enum properties in matches and membership tests", + policy: { + models: {u: {tier: "string(bronze|silver|gold)", tags: "string[]"}}, + blocks: [ + {match: "u.rank", arms: [["u.tier == 'gold'", "3"], ["u.tier == 'silver'", "2"], ["u.tier == 'bronze'", "1"]]}, + {expression: "u.premium", value: "u.tier in ['silver', 'gold']"}, + {expression: "u.tagged", value: "'vip' in u.tags"}, + ], + }, + cases: [ + [{u: {tier: "gold", tags: ["vip"]}}, {u: {tier: "gold", tags: ["vip"], rank: 3, premium: true, tagged: true}}], + [{u: {tier: "silver", tags: []}}, {u: {tier: "silver", tags: [], rank: 2, premium: true, tagged: false}}], + [{u: {tier: "bronze", tags: ["a", "vip"]}}, {u: {tier: "bronze", tags: ["a", "vip"], rank: 1, premium: false, tagged: true}}], + [{u: {tier: "platinum", tags: []}}, "!error: InputValidationFailed"], + [{u: {tier: "gold", tags: [1]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "dictionaries validate string values", + policy: { + dictionaries: {country: ["NO", "SE", ["DK", "Denmark"]]}, + models: {u: {country: "country"}}, + blocks: [{expression: "u.nordic", value: "u.country in ['NO', 'SE', 'DK']"}], + }, + cases: [ + [{u: {country: "NO"}}, {u: {country: "NO", nordic: true}}], + [{u: {country: "DK"}}, {u: {country: "DK", nordic: true}}], + [{u: {country: "Denmark"}}, "!error: InputValidationFailed"], + [{u: {country: "US"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "computed values of mixed types", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {u: {n: "number"}}, + blocks: [ + {expression: "u.obj", value: "{double: u.n * 2, label: string(u.n), positive: u.n > 0}"}, + {expression: "u.list", value: "[u.n, u.n + 1, 'x', null, true]"}, + {expression: "u.nested", value: "u.obj.double + 1"}, + ], + }, + cases: [ + [{u: {n: 2}}, {u: {n: 2, obj: {double: 4, label: "2", positive: true}, list: [2, 3, "x", null, true], nested: 5}}], + [{u: {n: -0.5}}, {u: {n: -0.5, obj: {double: -1, label: "-0.5", positive: false}, list: [-0.5, 0.5, "x", null, true], nested: 0}}], + ], +} + +// --- Realistic: loan eligibility ---------------------------------------------------------------- + +{ + name: "loan eligibility", + policy: { + models: { + applicant: {age: "number", income: "number", debts: "number", score: "number", employment: "string(employed|self|unemployed)", country: "string"}, + }, + blocks: [ + {expression: "applicant.dti", value: "applicant.income == 0 ? 1 : round(applicant.debts / applicant.income, 4)"}, + {match: "applicant.risk", arms: [ + ["applicant.score >= 750 and applicant.dti < 0.3", "'low'"], + ["applicant.score >= 650 and applicant.dti < 0.45", "'medium'"], + ["", "'high'"], + ]}, + {assertion: "applicant.basicEligible", conditions: ["applicant.age >= 18", "applicant.age <= 75", "applicant.employment != 'unemployed'", "applicant.country in ['NO', 'SE', 'DK']"]}, + {table: "limits", inputs: ["applicant.risk", "applicant.employment"], outputs: ["applicant.maxLoan"], rules: [ + ["'low'", "'employed'", "applicant.income * 5"], + ["'low'", "'self'", "applicant.income * 3"], + ["'medium'", "'employed'", "applicant.income * 3"], + ["'medium'", "", "applicant.income * 2"], + ["", "", "0"], + ]}, + {expression: "applicant.decision", value: "not applicant.basicEligible ? 'reject' : applicant.maxLoan > 0 ? 'approve' : 'refer'"}, + ], + }, + cases: [ + [ + {applicant: {age: 35, income: 100000, debts: 20000, score: 800, employment: "employed", country: "NO"}}, + {applicant: {age: 35, income: 100000, debts: 20000, score: 800, employment: "employed", country: "NO", dti: 0.2, risk: "low", basicEligible: true, maxLoan: 500000, decision: "approve"}}, + ], + [ + {applicant: {age: 35, income: 100000, debts: 20000, score: 800, employment: "self", country: "SE"}}, + {applicant: {age: 35, income: 100000, debts: 20000, score: 800, employment: "self", country: "SE", dti: 0.2, risk: "low", basicEligible: true, maxLoan: 300000, decision: "approve"}}, + ], + [ + {applicant: {age: 40, income: 60000, debts: 24000, score: 700, employment: "self", country: "DK"}}, + {applicant: {age: 40, income: 60000, debts: 24000, score: 700, employment: "self", country: "DK", dti: 0.4, risk: "medium", basicEligible: true, maxLoan: 120000, decision: "approve"}}, + ], + [ + {applicant: {age: 40, income: 60000, debts: 30000, score: 700, employment: "employed", country: "NO"}}, + {applicant: {age: 40, income: 60000, debts: 30000, score: 700, employment: "employed", country: "NO", dti: 0.5, risk: "high", basicEligible: true, maxLoan: 0, decision: "refer"}}, + ], + [ + {applicant: {age: 17, income: 10000, debts: 0, score: 800, employment: "employed", country: "NO"}}, + {applicant: {age: 17, income: 10000, debts: 0, score: 800, employment: "employed", country: "NO", dti: 0, risk: "low", basicEligible: false, maxLoan: 50000, decision: "reject"}}, + ], + [ + {applicant: {age: 30, income: 0, debts: 0, score: 800, employment: "unemployed", country: "NO"}}, + {applicant: {age: 30, income: 0, debts: 0, score: 800, employment: "unemployed", country: "NO", dti: 1, risk: "high", basicEligible: false, maxLoan: 0, decision: "reject"}}, + ], + [ + {applicant: {age: 50, income: 90000, debts: 9000, score: 760, employment: "employed", country: "US"}}, + {applicant: {age: 50, income: 90000, debts: 9000, score: 760, employment: "employed", country: "US", dti: 0.1, risk: "low", basicEligible: false, maxLoan: 450000, decision: "reject"}}, + ], + [ + {applicant: {age: 75, income: 30000, debts: 8999.99, score: 750, employment: "employed", country: "SE"}}, + {applicant: {age: 75, income: 30000, debts: 8999.99, score: 750, employment: "employed", country: "SE", dti: 0.3, risk: "medium", basicEligible: true, maxLoan: 90000, decision: "approve"}}, + ], + [ + {applicant: {age: 76, income: 30000, debts: 0, score: 650, employment: "self", country: "SE"}}, + {applicant: {age: 76, income: 30000, debts: 0, score: 650, employment: "self", country: "SE", dti: 0, risk: "medium", basicEligible: false, maxLoan: 60000, decision: "reject"}}, + ], + [{applicant: {age: 30, income: 1, debts: 0, score: 700, employment: "retired", country: "NO"}}, "!error: InputValidationFailed"], + [{applicant: {age: 30, income: 1, debts: 0, employment: "employed", country: "NO"}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "loan eligibility with goals", + policy: { + models: { + applicant: {age: "number", income: "number", debts: "number", score: "number"}, + }, + blocks: [ + {expression: "applicant.dti", value: "round(applicant.debts / applicant.income, 4)"}, + {match: "applicant.risk", arms: [["applicant.score >= 750 and applicant.dti < 0.3", "'low'"], ["", "'high'"]]}, + {assertion: "applicant.adult", conditions: ["applicant.age >= 18"]}, + ], + }, + cases: [ + {input: {applicant: {income: 1000, debts: 100, score: 800}}, goals: ["applicant.risk"], output: {applicant: {income: 1000, debts: 100, score: 800, dti: 0.1, risk: "low"}}}, + {input: {applicant: {income: 1000, debts: 500}}, goals: ["applicant.dti"], output: {applicant: {income: 1000, debts: 500, dti: 0.5}}}, + {input: {applicant: {age: 16}}, goals: ["applicant.adult"], output: {applicant: {age: 16, adult: false}}}, + {input: {applicant: {age: 16, income: 3, debts: 1, score: 1}}, output: {applicant: {age: 16, income: 3, debts: 1, score: 1, dti: 0.3333, risk: "high", adult: false}}}, + ], +} + +// --- Realistic: order pricing ------------------------------------------------------------------- + +{ + name: "order pricing with line items, discounts and tax", + policy: { + models: { + order: {items: "item[]", country: "string(NO|SE|DE)", coupon: "string?", member: "boolean"}, + item: {sku: "string", price: "number", qty: "number"}, + }, + blocks: [ + {expression: "item.lineTotal", value: "item.price * item.qty"}, + {expression: "order.subtotal", value: "sum(map(order.items, #.price * #.qty))"}, + {table: "discount", inputs: ["order.member", "order.subtotal"], outputs: ["order.discountRate"], rules: [ + ["true", ">= 1000", "0.15"], + ["true", "", "0.05"], + ["", ">= 1000", "0.1"], + ["", "", "0"], + ]}, + {match: "order.couponOff", arms: [["order.coupon == 'TEN'", "10"], ["order.coupon == 'FIFTY'", "50"], ["", "0"]]}, + {expression: "order.net", value: "max([order.subtotal * (1 - order.discountRate) - order.couponOff, 0])"}, + {match: "order.taxRate", arms: [["order.country == 'NO'", "0.25"], ["order.country == 'SE'", "0.25"], ["order.country == 'DE'", "0.19"]]}, + {expression: "order.tax", value: "round(order.net * order.taxRate, 2)"}, + {expression: "order.total", value: "order.net + order.tax"}, + ], + }, + cases: [ + [ + {order: {items: [{sku: "a", price: 100, qty: 2}], country: "NO", member: false}}, + {order: {items: [{sku: "a", price: 100, qty: 2, lineTotal: 200}], country: "NO", member: false, subtotal: 200, discountRate: 0, couponOff: 0, net: 200, taxRate: 0.25, tax: 50, total: 250}}, + ], + [ + {order: {items: [{sku: "a", price: 100, qty: 2}], country: "DE", member: true, coupon: "TEN"}}, + {order: {items: [{sku: "a", price: 100, qty: 2, lineTotal: 200}], country: "DE", member: true, coupon: "TEN", subtotal: 200, discountRate: 0.05, couponOff: 10, net: 180, taxRate: 0.19, tax: 34.2, total: 214.2}}, + ], + [ + {order: {items: [{sku: "a", price: 600, qty: 1}, {sku: "b", price: 200, qty: 2}], country: "SE", member: true}}, + {order: {items: [{sku: "a", price: 600, qty: 1, lineTotal: 600}, {sku: "b", price: 200, qty: 2, lineTotal: 400}], country: "SE", member: true, subtotal: 1000, discountRate: 0.15, couponOff: 0, net: 850, taxRate: 0.25, tax: 212.5, total: 1062.5}}, + ], + [ + {order: {items: [{sku: "a", price: 999.99, qty: 1}], country: "NO", member: false, coupon: "FIFTY"}}, + {order: {items: [{sku: "a", price: 999.99, qty: 1, lineTotal: 999.99}], country: "NO", member: false, coupon: "FIFTY", subtotal: 999.99, discountRate: 0, couponOff: 50, net: 949.99, taxRate: 0.25, tax: 237.5, total: 1187.49}}, + ], + [ + {order: {items: [{sku: "a", price: 20, qty: 1}], country: "DE", member: false, coupon: "FIFTY"}}, + {order: {items: [{sku: "a", price: 20, qty: 1, lineTotal: 20}], country: "DE", member: false, coupon: "FIFTY", subtotal: 20, discountRate: 0, couponOff: 50, net: 0, taxRate: 0.19, tax: 0, total: 0}}, + ], + [ + {order: {items: [], country: "NO", member: true, coupon: null}}, + {order: {items: [], country: "NO", member: true, coupon: null, subtotal: 0, discountRate: 0.05, couponOff: 0, net: 0, taxRate: 0.25, tax: 0, total: 0}}, + ], + [ + {order: {items: [{sku: "a", price: 0.33, qty: 3}, {sku: "b", price: 0.01, qty: 1}], country: "SE", member: false, coupon: "UNKNOWN"}}, + {order: {items: [{sku: "a", price: 0.33, qty: 3, lineTotal: 0.99}, {sku: "b", price: 0.01, qty: 1, lineTotal: 0.01}], country: "SE", member: false, coupon: "UNKNOWN", subtotal: 1, discountRate: 0, couponOff: 0, net: 1, taxRate: 0.25, tax: 0.25, total: 1.25}}, + ], + [{order: {items: [{sku: "a", price: "1", qty: 1}], country: "NO", member: false}}, "!error: InputValidationFailed"], + [{order: {items: [], country: "US", member: false}}, "!error: InputValidationFailed"], + [{order: {items: [], country: "NO"}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Realistic: insurance premium ----------------------------------------------------------------- + +{ + name: "insurance premium from a driver profile", + policy: { + models: { + driver: {dob: "date", licensed: "date", claims: "claim[]", vehicle: "vehicle"}, + claim: {date: "date", amount: "number"}, + vehicle: {value: "number", kind: "string(car|van|bike)"}, + }, + blocks: [ + {expression: "driver.age", value: "d().diff(driver.dob, 'year')"}, + {expression: "driver.experience", value: "d().diff(driver.licensed, 'year')"}, + {expression: "driver.recentClaims", value: "count(driver.claims, d().diff(#.date, 'year') < 3)"}, + {table: "base", inputs: ["driver.vehicle.kind"], outputs: ["driver.baseRate"], rules: [["'car'", "0.03"], ["'van'", "0.04"], ["'bike'", "0.05"]]}, + {match: "driver.ageFactor", arms: [["driver.age < 25", "1.5"], ["driver.age >= 70", "1.3"], ["", "1"]]}, + {match: "driver.claimFactor", arms: [["driver.recentClaims == 0", "0.9"], ["driver.recentClaims == 1", "1.2"], ["", "1.6"]]}, + {expression: "driver.premium", value: "round(driver.vehicle.value * driver.baseRate * driver.ageFactor * driver.claimFactor * (driver.experience < 2 ? 1.25 : 1), 2)"}, + ], + }, + cases: [ + [ + {driver: {dob: "1980-01-01", licensed: "2000-01-01", claims: [], vehicle: {value: 20000, kind: "car"}}}, + {driver: {dob: "1980-01-01", licensed: "2000-01-01", claims: [], vehicle: {value: 20000, kind: "car"}, age: 45, experience: 25, recentClaims: 0, baseRate: 0.03, ageFactor: 1, claimFactor: 0.9, premium: 540}}, + ], + [ + {driver: {dob: "2003-06-01", licensed: "2024-01-01", claims: [{date: "2024-12-01", amount: 500}], vehicle: {value: 10000, kind: "bike"}}}, + {driver: {dob: "2003-06-01", licensed: "2024-01-01", claims: [{date: "2024-12-01", amount: 500}], vehicle: {value: 10000, kind: "bike"}, age: 21, experience: 1, recentClaims: 1, baseRate: 0.05, ageFactor: 1.5, claimFactor: 1.2, premium: 1125}}, + ], + [ + {driver: {dob: "1950-01-01", licensed: "1970-01-01", claims: [{date: "2020-01-01", amount: 1}, {date: "2023-01-01", amount: 2}, {date: "2024-01-01", amount: 3}], vehicle: {value: 30000, kind: "van"}}}, + {driver: {dob: "1950-01-01", licensed: "1970-01-01", claims: [{date: "2020-01-01", amount: 1}, {date: "2023-01-01", amount: 2}, {date: "2024-01-01", amount: 3}], vehicle: {value: 30000, kind: "van"}, age: 75, experience: 55, recentClaims: 2, baseRate: 0.04, ageFactor: 1.3, claimFactor: 1.6, premium: 2496}}, + ], + [{driver: {dob: "1980-01-01", licensed: "2000-01-01", claims: [], vehicle: {value: 1, kind: "truck"}}}, "!error: InputValidationFailed"], + [{driver: {dob: "1980-01-01", licensed: "2000-01-01", claims: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Realistic: subscription billing with globals ------------------------------------------------ + +{ + name: "subscription billing with global settings", + policy: { + globals: {platform: {vatRate: "number", trialDays: "number"}}, + models: {sub: {started: "date", seats: "number", plan: "string(basic|pro|enterprise)", annual: "boolean"}}, + blocks: [ + {expression: "sub.inTrial", value: "d().diff(sub.started, 'day') < trialDays"}, + {table: "prices", inputs: ["sub.plan"], outputs: ["sub.seatPrice"], rules: [["'basic'", "5"], ["'pro'", "12"], ["'enterprise'", "30"]]}, + {expression: "sub.monthly", value: "sub.inTrial ? 0 : sub.seats * sub.seatPrice * (sub.annual ? 0.8 : 1)"}, + {expression: "sub.vat", value: "round(sub.monthly * vatRate, 2)"}, + {expression: "sub.invoice", value: "sub.monthly + sub.vat"}, + ], + }, + cases: [ + [ + {vatRate: 0.25, trialDays: 14, sub: {started: "2025-03-10", seats: 10, plan: "pro", annual: false}}, + {vatRate: 0.25, trialDays: 14, sub: {started: "2025-03-10", seats: 10, plan: "pro", annual: false, inTrial: true, seatPrice: 12, monthly: 0, vat: 0, invoice: 0}}, + ], + [ + {vatRate: 0.25, trialDays: 14, sub: {started: "2025-01-01", seats: 10, plan: "pro", annual: false}}, + {vatRate: 0.25, trialDays: 14, sub: {started: "2025-01-01", seats: 10, plan: "pro", annual: false, inTrial: false, seatPrice: 12, monthly: 120, vat: 30, invoice: 150}}, + ], + [ + {vatRate: 0.19, trialDays: 0, sub: {started: "2025-03-20", seats: 3, plan: "enterprise", annual: true}}, + {vatRate: 0.19, trialDays: 0, sub: {started: "2025-03-20", seats: 3, plan: "enterprise", annual: true, inTrial: false, seatPrice: 30, monthly: 72, vat: 13.68, invoice: 85.68}}, + ], + [ + {vatRate: 0, trialDays: 30, sub: {started: "2024-01-01", seats: 1, plan: "basic", annual: true}}, + {vatRate: 0, trialDays: 30, sub: {started: "2024-01-01", seats: 1, plan: "basic", annual: true, inTrial: false, seatPrice: 5, monthly: 4, vat: 0, invoice: 4}}, + ], + [{trialDays: 30, sub: {started: "2024-01-01", seats: 1, plan: "basic", annual: true}}, "!error: MissingRequiredInputs"], + ], +} diff --git a/core/engine/tests/spec/policy/18-match-advanced.json5 b/core/engine/tests/spec/policy/18-match-advanced.json5 new file mode 100644 index 00000000..b863f2c5 --- /dev/null +++ b/core/engine/tests/spec/policy/18-match-advanced.json5 @@ -0,0 +1,1065 @@ +// Match blocks in larger policies: many arms, arms that read other computed properties, +// matches that feed tables and assertions, per-member matches over relationships, matches +// over enums and dictionaries (exhaustiveness without a default arm), and discriminated-union +// style models where a `kind` property decides which other fields are meaningful. Chapter 05 +// covers the single-block basics. + +// --------------------------------------------------------------------------- +// Many arms: a long ladder is still first-true-arm-wins in document order. +// --------------------------------------------------------------------------- +{ + name: "ten-arm grade ladder with a default", + policy: { + models: {student: {score: "number"}}, + blocks: [{match: "student.grade", arms: [ + ["student.score >= 97", "'A+'"], + ["student.score >= 93", "'A'"], + ["student.score >= 90", "'A-'"], + ["student.score >= 87", "'B+'"], + ["student.score >= 83", "'B'"], + ["student.score >= 80", "'B-'"], + ["student.score >= 77", "'C+'"], + ["student.score >= 73", "'C'"], + ["student.score >= 70", "'C-'"], + ["student.score >= 60", "'D'"], + ["", "'F'"], + ]}], + }, + cases: [ + [{student: {score: 100}}, {student: {score: 100, grade: "A+"}}], + [{student: {score: 97}}, {student: {score: 97, grade: "A+"}}], + [{student: {score: 96.99}}, {student: {score: 96.99, grade: "A"}}], + [{student: {score: 90}}, {student: {score: 90, grade: "A-"}}], + [{student: {score: 88}}, {student: {score: 88, grade: "B+"}}], + [{student: {score: 83}}, {student: {score: 83, grade: "B"}}], + [{student: {score: 80.5}}, {student: {score: 80.5, grade: "B-"}}], + [{student: {score: 77}}, {student: {score: 77, grade: "C+"}}], + [{student: {score: 75}}, {student: {score: 75, grade: "C"}}], + [{student: {score: 70}}, {student: {score: 70, grade: "C-"}}], + [{student: {score: 69.999}}, {student: {score: 69.999, grade: "D"}}], + [{student: {score: 59}}, {student: {score: 59, grade: "F"}}], + [{student: {score: -3}}, {student: {score: -3, grade: "F"}}], + ], +} + +{ + name: "many arms over two fields with compound conditions", + policy: { + models: {parcel: {zone: "string", weight: "number", express: "boolean"}}, + blocks: [{match: "parcel.rate", arms: [ + ["parcel.zone == 'local' and parcel.weight <= 1 and not parcel.express", "3"], + ["parcel.zone == 'local' and parcel.weight <= 1", "5"], + ["parcel.zone == 'local' and parcel.express", "9"], + ["parcel.zone == 'local'", "6"], + ["parcel.zone in ['eu', 'uk'] and parcel.weight > 10", "40"], + ["parcel.zone in ['eu', 'uk'] and parcel.express", "25"], + ["parcel.zone in ['eu', 'uk']", "15"], + ["parcel.weight > 30 or parcel.zone == 'remote'", "99"], + ["", "50"], + ]}], + }, + cases: [ + [{parcel: {zone: "local", weight: 1, express: false}}, {parcel: {zone: "local", weight: 1, express: false, rate: 3}}], + [{parcel: {zone: "local", weight: 0.5, express: true}}, {parcel: {zone: "local", weight: 0.5, express: true, rate: 5}}], + [{parcel: {zone: "local", weight: 2, express: true}}, {parcel: {zone: "local", weight: 2, express: true, rate: 9}}], + [{parcel: {zone: "local", weight: 2, express: false}}, {parcel: {zone: "local", weight: 2, express: false, rate: 6}}], + [{parcel: {zone: "eu", weight: 11, express: true}}, {parcel: {zone: "eu", weight: 11, express: true, rate: 40}}], + [{parcel: {zone: "uk", weight: 10, express: true}}, {parcel: {zone: "uk", weight: 10, express: true, rate: 25}}], + [{parcel: {zone: "uk", weight: 10, express: false}}, {parcel: {zone: "uk", weight: 10, express: false, rate: 15}}], + [{parcel: {zone: "us", weight: 31, express: false}}, {parcel: {zone: "us", weight: 31, express: false, rate: 99}}], + [{parcel: {zone: "remote", weight: 1, express: true}}, {parcel: {zone: "remote", weight: 1, express: true, rate: 99}}], + [{parcel: {zone: "us", weight: 30, express: true}}, {parcel: {zone: "us", weight: 30, express: true, rate: 50}}], + ], +} + +{ + name: "arm conditions with closures over an array input", + policy: { + models: {cart: {prices: "number[]"}}, + blocks: [{match: "cart.label", arms: [ + ["len(cart.prices) == 0", "'empty'"], + ["all(cart.prices, # == 0)", "'free'"], + ["some(cart.prices, # < 0)", "'refund'"], + ["sum(cart.prices) > 1000", "'big'"], + ["count(cart.prices, # > 100) >= 2", "'several premium'"], + ["", "'normal'"], + ]}], + }, + cases: [ + [{cart: {prices: []}}, {cart: {prices: [], label: "empty"}}], + [{cart: {prices: [0, 0]}}, {cart: {prices: [0, 0], label: "free"}}], + [{cart: {prices: [5, -1]}}, {cart: {prices: [5, -1], label: "refund"}}], + [{cart: {prices: [999, 2]}}, {cart: {prices: [999, 2], label: "big"}}], + [{cart: {prices: [101, 101, 1]}}, {cart: {prices: [101, 101, 1], label: "several premium"}}], + [{cart: {prices: [101, 1]}}, {cart: {prices: [101, 1], label: "normal"}}], + ], +} + +{ + name: "arm values of a long ladder compute from several inputs", + policy: { + models: {loan: {amount: "number", years: "number"}}, + blocks: [{match: "loan.payment", arms: [ + ["loan.years <= 0", "loan.amount"], + ["loan.years == 1", "loan.amount * 1.05"], + ["loan.years <= 3", "round(loan.amount * 1.12 / loan.years, 2)"], + ["loan.years <= 5", "round(loan.amount * 1.2 / loan.years, 2)"], + ["", "round(loan.amount * 1.35 / loan.years, 2)"], + ]}], + }, + cases: [ + [{loan: {amount: 1000, years: 0}}, {loan: {amount: 1000, years: 0, payment: 1000}}], + [{loan: {amount: 1000, years: 1}}, {loan: {amount: 1000, years: 1, payment: 1050}}], + [{loan: {amount: 1000, years: 3}}, {loan: {amount: 1000, years: 3, payment: 373.33}}], + [{loan: {amount: 1000, years: 4}}, {loan: {amount: 1000, years: 4, payment: 300}}], + [{loan: {amount: 1000, years: 9}}, {loan: {amount: 1000, years: 9, payment: 150}}], + [{loan: {amount: 0.01, years: 2}}, {loan: {amount: 0.01, years: 2, payment: 0.01}}], + ], +} + +// --------------------------------------------------------------------------- +// Arms reading other computed properties: expression, assertion, table and match outputs, +// declared before or after the match. +// --------------------------------------------------------------------------- +{ + name: "conditions read an expression, an assertion and a table output", + policy: { + models: {order: {amount: "number", qty: "number", country: "string"}}, + blocks: [ + {match: "order.route", arms: [ + ["order.blocked", "'stop'"], + ["order.total > 1000 and order.band == 'A'", "'priority'"], + ["order.total > 1000", "'review'"], + ["", "'auto'"], + ]}, + {expression: "order.total", value: "order.amount * order.qty"}, + {assertion: "order.blocked", conditions: [["or", "order.country == 'XX'"], "order.qty > 500"]}, + {table: "band", inputs: ["order.country"], outputs: ["order.band"], rules: [["'DE', 'NL'", "'A'"], ["", "'B'"]]}, + ], + }, + cases: [ + [{order: {amount: 10, qty: 600, country: "DE"}}, {order: {amount: 10, qty: 600, country: "DE", total: 6000, blocked: true, band: "A", route: "stop"}}], + [{order: {amount: 1, qty: 1, country: "XX"}}, {order: {amount: 1, qty: 1, country: "XX", total: 1, blocked: true, band: "B", route: "stop"}}], + [{order: {amount: 500, qty: 3, country: "NL"}}, {order: {amount: 500, qty: 3, country: "NL", total: 1500, blocked: false, band: "A", route: "priority"}}], + [{order: {amount: 500, qty: 3, country: "US"}}, {order: {amount: 500, qty: 3, country: "US", total: 1500, blocked: false, band: "B", route: "review"}}], + [{order: {amount: 5, qty: 3, country: "DE"}}, {order: {amount: 5, qty: 3, country: "DE", total: 15, blocked: false, band: "A", route: "auto"}}], + ], +} + +{ + name: "arm values read computed properties; one read only by an unselected arm is not written", + policy: { + models: {order: {amount: "number", member: "boolean"}}, + blocks: [ + {expression: "order.base", value: "order.amount * 1.2"}, + {expression: "order.memberPrice", value: "order.base * 0.9"}, + {match: "order.price", arms: [ + ["order.member", "order.memberPrice"], + ["order.amount > 100", "order.base - 5"], + ["", "order.base"], + ]}, + ], + }, + cases: [ + [{order: {amount: 100, member: true}}, {order: {amount: 100, member: true, base: 120, memberPrice: 108, price: 108}}], + [{order: {amount: 200, member: false}}, {order: {amount: 200, member: false, base: 240, price: 235}}], + [{order: {amount: 50, member: false}}, {order: {amount: 50, member: false, base: 60, price: 60}}], + [{order: {amount: 0, member: true}}, {order: {amount: 0, member: true, base: 0, memberPrice: 0, price: 0}}], + ], +} + +{ + name: "a match reads another match in both conditions and values", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {match: "customer.offer", arms: [ + ["customer.segment == 'youth'", "{segment: customer.segment, rate: 0.01}"], + ["customer.segment == 'senior'", "{segment: customer.segment, rate: 0.02}"], + ["", "{segment: customer.segment, rate: customer.income > 50000 ? 0.03 : 0.04}"], + ]}, + {match: "customer.segment", arms: [ + ["customer.age < 26", "'youth'"], + ["customer.age >= 65", "'senior'"], + ["", "'standard'"], + ]}, + ], + }, + cases: [ + [{customer: {age: 20, income: 0}}, {customer: {age: 20, income: 0, segment: "youth", offer: {segment: "youth", rate: 0.01}}}], + [{customer: {age: 70, income: 0}}, {customer: {age: 70, income: 0, segment: "senior", offer: {segment: "senior", rate: 0.02}}}], + [{customer: {age: 40, income: 60000}}, {customer: {age: 40, income: 60000, segment: "standard", offer: {segment: "standard", rate: 0.03}}}], + [{customer: {age: 40, income: 50000}}, {customer: {age: 40, income: 50000, segment: "standard", offer: {segment: "standard", rate: 0.04}}}], + ], +} + +{ + name: "four chained matches declared in reverse dependency order; `x.a` only feeds one arm of `x.c`", + policy: { + models: {x: {n: "number"}}, + blocks: [ + {match: "x.d", arms: [["x.c == 'big-even-pos'", "1"], ["", "0"]]}, + {match: "x.c", arms: [["x.b == 'even-pos'", "x.a + '-' + x.b"], ["", "x.b"]]}, + {match: "x.b", arms: [["x.n % 2 == 0 and x.n > 0", "'even-pos'"], ["x.n > 0", "'odd-pos'"], ["", "'non-pos'"]]}, + {match: "x.a", arms: [["x.n > 100", "'big'"], ["", "'small'"]]}, + ], + }, + cases: [ + [{x: {n: 102}}, {x: {n: 102, a: "big", b: "even-pos", c: "big-even-pos", d: 1}}], + [{x: {n: 4}}, {x: {n: 4, a: "small", b: "even-pos", c: "small-even-pos", d: 0}}], + [{x: {n: 101}}, {x: {n: 101, b: "odd-pos", c: "odd-pos", d: 0}}], + [{x: {n: 0}}, {x: {n: 0, b: "non-pos", c: "non-pos", d: 0}}], + [{x: {n: -4}}, {x: {n: -4, b: "non-pos", c: "non-pos", d: 0}}], + ], +} + +{ + name: "without goals, a computed read only by an unselected arm is not evaluated or written", + policy: { + models: {x: {n: "number"}}, + blocks: [ + {expression: "x.expensive", value: "x.n * 1000"}, + {expression: "x.cheap", value: "x.n + 1"}, + {match: "x.out", arms: [["x.n > 5", "x.expensive"], ["", "x.cheap"]]}, + ], + }, + cases: [ + [{x: {n: 6}}, {x: {n: 6, expensive: 6000, out: 6000}}], + [{x: {n: 1}}, {x: {n: 1, cheap: 2, out: 2}}], + [{x: {n: 5}}, {x: {n: 5, cheap: 6, out: 6}}], + [{x: {n: -2.5}}, {x: {n: -2.5, cheap: -1.5, out: -1.5}}], + ], +} + +{ + name: "with a goal, only the selected arm's dependencies are evaluated", + policy: { + models: {x: {n: "number"}}, + blocks: [ + {expression: "x.expensive", value: "x.n * 1000"}, + {expression: "x.cheap", value: "x.n + 1"}, + {match: "x.out", arms: [["x.n > 5", "x.expensive"], ["", "x.cheap"]]}, + ], + }, + cases: [ + {input: {x: {n: 6}}, goals: ["x.out"], output: {x: {n: 6, expensive: 6000, out: 6000}}}, + {input: {x: {n: 1}}, goals: ["x.out"], output: {x: {n: 1, cheap: 2, out: 2}}}, + {input: {x: {n: 1}}, goals: ["x.out", "x.expensive"], output: {x: {n: 1, expensive: 1000, cheap: 2, out: 2}}}, + ], +} + +{ + name: "a failing dependency of an unselected arm is not raised, with or without goals", + diagnostics: ["TYPE_MISMATCH", "UNDEFINED_VARIABLE"], + policy: { + models: {x: {n: "number", s: "string"}}, + blocks: [ + {expression: "x.bad", value: "x.s * 2"}, + {match: "x.out", arms: [["x.n > 5", "x.bad"], ["", "'safe'"]]}, + ], + }, + cases: [ + {input: {x: {n: 1, s: "a"}}, goals: ["x.out"], output: {x: {n: 1, s: "a", out: "safe"}}}, + {input: {x: {n: 9, s: "a"}}, goals: ["x.out"], output: "!error: ExpressionFailed"}, + {input: {x: {n: 1, s: "a"}}, output: {x: {n: 1, s: "a", out: "safe"}}}, + {input: {x: {n: 9, s: "a"}}, output: "!error: ExpressionFailed"}, + ], +} + +// --------------------------------------------------------------------------- +// Matches feeding tables and assertions, and the other way round. +// --------------------------------------------------------------------------- +{ + name: "a match result is a table input column", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {match: "customer.segment", arms: [["customer.age < 26", "'youth'"], ["customer.age >= 65", "'senior'"], ["", "'standard'"]]}, + {table: "limits", inputs: ["customer.segment", "customer.income"], outputs: ["customer.limit"], rules: [ + ["'youth'", "", "500"], + ["'senior'", "< 20000", "1000"], + ["'senior'", "", "3000"], + ["", ">= 100000", "20000"], + ["", "", "5000"], + ]}, + ], + }, + cases: [ + [{customer: {age: 20, income: 200000}}, {customer: {age: 20, income: 200000, segment: "youth", limit: 500}}], + [{customer: {age: 70, income: 10000}}, {customer: {age: 70, income: 10000, segment: "senior", limit: 1000}}], + [{customer: {age: 70, income: 50000}}, {customer: {age: 70, income: 50000, segment: "senior", limit: 3000}}], + [{customer: {age: 40, income: 100000}}, {customer: {age: 40, income: 100000, segment: "standard", limit: 20000}}], + [{customer: {age: 40, income: 1}}, {customer: {age: 40, income: 1, segment: "standard", limit: 5000}}], + ], +} + +{ + name: "a match result is read by an assertion with groups", + policy: { + models: {applicant: {score: "number", employed: "boolean", years: "number"}}, + blocks: [ + {match: "applicant.risk", arms: [["applicant.score >= 750", "'low'"], ["applicant.score >= 600", "'medium'"], ["", "'high'"]]}, + {assertion: "applicant.approved", conditions: [ + ["or", "applicant.risk == 'low'"], + ["and", "applicant.risk == 'medium'", 1], + ["or", "applicant.employed", 2], + ["and", "applicant.years >= 5", 2], + ]}, + ], + }, + cases: [ + [{applicant: {score: 800, employed: false, years: 0}}, {applicant: {score: 800, employed: false, years: 0, risk: "low", approved: true}}], + [{applicant: {score: 650, employed: true, years: 0}}, {applicant: {score: 650, employed: true, years: 0, risk: "medium", approved: true}}], + [{applicant: {score: 650, employed: false, years: 5}}, {applicant: {score: 650, employed: false, years: 5, risk: "medium", approved: true}}], + [{applicant: {score: 650, employed: false, years: 4}}, {applicant: {score: 650, employed: false, years: 4, risk: "medium", approved: false}}], + [{applicant: {score: 500, employed: true, years: 10}}, {applicant: {score: 500, employed: true, years: 10, risk: "high", approved: false}}], + ], +} + +{ + name: "table, then match, then table: a sandwich of block kinds", + policy: { + models: {item: {category: "string", price: "number"}}, + blocks: [ + {table: "vat", inputs: ["item.category"], outputs: ["item.vat"], rules: [["'food'", "0.07"], ["'book'", "0"], ["", "0.19"]]}, + {match: "item.vatClass", arms: [["item.vat == 0", "'exempt'"], ["item.vat < 0.1", "'reduced'"], ["", "'standard'"]]}, + {table: "label", inputs: ["item.vatClass", "item.price"], outputs: ["item.label"], rules: [ + ["'exempt'", "", "'no tax'"], + ["'reduced'", "> 100", "'reduced, large'"], + ["'reduced'", "", "'reduced'"], + ["", "", "'standard'"], + ]}, + ], + }, + cases: [ + [{item: {category: "book", price: 10}}, {item: {category: "book", price: 10, vat: 0, vatClass: "exempt", label: "no tax"}}], + [{item: {category: "food", price: 200}}, {item: {category: "food", price: 200, vat: 0.07, vatClass: "reduced", label: "reduced, large"}}], + [{item: {category: "food", price: 2}}, {item: {category: "food", price: 2, vat: 0.07, vatClass: "reduced", label: "reduced"}}], + [{item: {category: "tool", price: 100}}, {item: {category: "tool", price: 100, vat: 0.19, vatClass: "standard", label: "standard"}}], + ], +} + +{ + name: "a match writing an object, read field by field downstream", + policy: { + models: {customer: {tier: "string(free|pro|team)"}}, + blocks: [ + {match: "customer.plan", arms: [ + ["customer.tier == 'free'", "{seats: 1, storage: 5, support: null}"], + ["customer.tier == 'pro'", "{seats: 1, storage: 100, support: 'email'}"], + ["customer.tier == 'team'", "{seats: 10, storage: 1000, support: 'phone'}"], + ]}, + {expression: "customer.storagePerSeat", value: "customer.plan.storage / customer.plan.seats"}, + {table: "sla", inputs: ["customer.plan.support"], outputs: ["customer.sla"], rules: [["'phone'", "4"], ["'email'", "24"], ["", "null"]]}, + {assertion: "customer.hasSupport", conditions: ["customer.plan.support != null"]}, + ], + }, + cases: [ + [{customer: {tier: "free"}}, {customer: {tier: "free", plan: {seats: 1, storage: 5, support: null}, storagePerSeat: 5, sla: null, hasSupport: false}}], + [{customer: {tier: "pro"}}, {customer: {tier: "pro", plan: {seats: 1, storage: 100, support: "email"}, storagePerSeat: 100, sla: 24, hasSupport: true}}], + [{customer: {tier: "team"}}, {customer: {tier: "team", plan: {seats: 10, storage: 1000, support: "phone"}, storagePerSeat: 100, sla: 4, hasSupport: true}}], + ], +} + +{ + name: "a match on a collected table array", + policy: { + models: {user: {age: "number", country: "string"}}, + blocks: [ + {table: "flags", inputs: ["user.age", "user.country"], outputs: ["user.flags[]"], rules: [ + ["< 18", "", "'minor'"], + ["", "'XX'", "'sanctioned'"], + ["> 100", "", "'check age'"], + ]}, + {match: "user.decision", arms: [ + ["'sanctioned' in user.flags", "'deny'"], + ["len(user.flags) >= 2", "'manual'"], + ["len(user.flags) == 1", "'soft review'"], + ["", "'allow'"], + ]}, + ], + }, + cases: [ + [{user: {age: 30, country: "DE"}}, {user: {age: 30, country: "DE", flags: [], decision: "allow"}}], + [{user: {age: 10, country: "DE"}}, {user: {age: 10, country: "DE", flags: ["minor"], decision: "soft review"}}], + [{user: {age: 10, country: "XX"}}, {user: {age: 10, country: "XX", flags: ["minor", "sanctioned"], decision: "deny"}}], + [{user: {age: 101, country: "XX"}}, {user: {age: 101, country: "XX", flags: ["sanctioned", "check age"], decision: "deny"}}], + ], +} + +{ + name: "a match result targets a nested path that a sibling block extends", + policy: { + models: {order: {amount: "number"}}, + blocks: [ + {match: "order.pricing.band", arms: [["order.amount > 100", "'high'"], ["", "'low'"]]}, + {expression: "order.pricing.fee", value: "order.pricing.band == 'high' ? 0 : 4.99"}, + ], + }, + cases: [ + [{order: {amount: 101}}, {order: {amount: 101, pricing: {band: "high", fee: 0}}}], + [{order: {amount: 100}}, {order: {amount: 100, pricing: {band: "low", fee: 4.99}}}], + ], +} + +// --------------------------------------------------------------------------- +// Matches on relationship members. +// --------------------------------------------------------------------------- +{ + name: "per-member match reads a parent input property", + policy: { + models: {customer: {threshold: "number", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{match: "company.status", arms: [ + ["company.revenue >= customer.threshold * 2", "'well above'"], + ["company.revenue >= customer.threshold", "'above'"], + ["", "'below'"], + ]}], + }, + cases: [ + [ + {customer: {threshold: 100, companies: [{revenue: 200}, {revenue: 150}, {revenue: 99}]}}, + {customer: {threshold: 100, companies: [{revenue: 200, status: "well above"}, {revenue: 150, status: "above"}, {revenue: 99, status: "below"}]}}, + ], + [ + {customer: {threshold: 0, companies: [{revenue: 0}, {revenue: -1}]}}, + {customer: {threshold: 0, companies: [{revenue: 0, status: "well above"}, {revenue: -1, status: "below"}]}}, + ], + [{customer: {threshold: 5, companies: []}}, {customer: {threshold: 5, companies: []}}], + ], +} + +{ + name: "per-member match reads a parent aggregate of the members", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.average", value: "avg(map(customer.companies, #.revenue))"}, + {match: "company.relative", arms: [ + ["company.revenue > customer.average", "'above average'"], + ["company.revenue == customer.average", "'average'"], + ["", "'below average'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10}, {revenue: 20}, {revenue: 30}]}}, + {customer: {average: 20, companies: [{revenue: 10, relative: "below average"}, {revenue: 20, relative: "average"}, {revenue: 30, relative: "above average"}]}}, + ], + [ + {customer: {companies: [{revenue: 7}]}}, + {customer: {average: 7, companies: [{revenue: 7, relative: "average"}]}}, + ], + ], +} + +{ + name: "parent match over aggregates of per-member match results", + policy: { + models: {portfolio: {loans: "loan[]"}, loan: {daysLate: "number", amount: "number"}}, + blocks: [ + {match: "loan.state", arms: [ + ["loan.daysLate == 0", "'current'"], + ["loan.daysLate <= 30", "'late'"], + ["loan.daysLate <= 90", "'delinquent'"], + ["", "'default'"], + ]}, + {match: "portfolio.health", arms: [ + ["some(portfolio.loans, #.state == 'default')", "'impaired'"], + ["sum(map(filter(portfolio.loans, #.state == 'delinquent'), #.amount)) > 10000", "'watch'"], + ["count(portfolio.loans, #.state != 'current') > len(portfolio.loans) / 2", "'weak'"], + ["", "'healthy'"], + ]}, + ], + }, + cases: [ + [ + {portfolio: {loans: [{daysLate: 0, amount: 1}, {daysLate: 120, amount: 1}]}}, + {portfolio: {health: "impaired", loans: [{daysLate: 0, amount: 1, state: "current"}, {daysLate: 120, amount: 1, state: "default"}]}}, + ], + [ + {portfolio: {loans: [{daysLate: 60, amount: 20000}, {daysLate: 0, amount: 5}]}}, + {portfolio: {health: "watch", loans: [{daysLate: 60, amount: 20000, state: "delinquent"}, {daysLate: 0, amount: 5, state: "current"}]}}, + ], + [ + {portfolio: {loans: [{daysLate: 10, amount: 1}, {daysLate: 31, amount: 1}, {daysLate: 0, amount: 1}]}}, + {portfolio: {health: "weak", loans: [{daysLate: 10, amount: 1, state: "late"}, {daysLate: 31, amount: 1, state: "delinquent"}, {daysLate: 0, amount: 1, state: "current"}]}}, + ], + [ + {portfolio: {loans: [{daysLate: 10, amount: 1}, {daysLate: 0, amount: 1}]}}, + {portfolio: {health: "healthy", loans: [{daysLate: 10, amount: 1, state: "late"}, {daysLate: 0, amount: 1, state: "current"}]}}, + ], + [{portfolio: {loans: []}}, {portfolio: {health: "healthy", loans: []}}], + ], +} + +// Writing to an entity nested two relationship levels deep is reported as +// UNSUPPORTED_NESTED_ITERATION (only one level of nesting is evaluated); the workspace path +// still runs it and fails the required-input check. +{ + name: "per-member match two levels deep is unsupported", + diagnostics: ["UNREACHABLE_ENTITY_READ", "UNSUPPORTED_NESTED_ITERATION"], + policy: { + models: { + customer: {bonusPool: "number", companies: "company[]"}, + company: {target: "number", employees: "employee[]"}, + employee: {sales: "number"}, + }, + blocks: [{match: "employee.bonus", arms: [ + ["employee.sales >= company.target * 2", "customer.bonusPool * 0.1"], + ["employee.sales >= company.target", "customer.bonusPool * 0.05"], + ["", "0"], + ]}], + }, + cases: [ + [{customer: {bonusPool: 1000, companies: [{target: 10, employees: [{sales: 20}, {sales: 9}]}]}}, "!error: MissingRequiredInputs"], + [{customer: {bonusPool: 0, companies: [{target: 1, employees: []}]}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "middle-level match reads the root and aggregates the level below", + policy: { + models: { + customer: {minHeadcount: "number", companies: "company[]"}, + company: {employees: "employee[]"}, + employee: {sales: "number"}, + }, + blocks: [{match: "company.status", arms: [ + ["len(company.employees) < customer.minHeadcount", "'understaffed'"], + ["sum(map(company.employees, #.sales)) >= 100", "'performing'"], + ["", "'ok'"], + ]}], + }, + cases: [ + [ + {customer: {minHeadcount: 2, companies: [{employees: [{sales: 500}]}, {employees: [{sales: 60}, {sales: 40}]}, {employees: [{sales: 1}, {sales: 2}]}]}}, + {customer: {minHeadcount: 2, companies: [ + {employees: [{sales: 500}], status: "understaffed"}, + {employees: [{sales: 60}, {sales: 40}], status: "performing"}, + {employees: [{sales: 1}, {sales: 2}], status: "ok"}, + ]}}, + ], + [ + {customer: {minHeadcount: 0, companies: [{employees: []}]}}, + {customer: {minHeadcount: 0, companies: [{employees: [], status: "ok"}]}}, + ], + ], +} + +{ + name: "match on a single relationship's fields", + policy: { + models: {customer: {report: "creditReport"}, creditReport: {score: "number", bankrupt: "boolean"}}, + blocks: [ + {match: "creditReport.grade", arms: [["creditReport.bankrupt", "'X'"], ["creditReport.score >= 700", "'A'"], ["", "'B'"]]}, + {match: "customer.decision", arms: [["customer.report.grade == 'A'", "'approve'"], ["customer.report.grade == 'X'", "'decline'"], ["", "'refer'"]]}, + ], + }, + cases: [ + [{customer: {report: {score: 800, bankrupt: false}}}, {customer: {decision: "approve", report: {score: 800, bankrupt: false, grade: "A"}}}], + [{customer: {report: {score: 800, bankrupt: true}}}, {customer: {decision: "decline", report: {score: 800, bankrupt: true, grade: "X"}}}], + [{customer: {report: {score: 650, bankrupt: false}}}, {customer: {decision: "refer", report: {score: 650, bankrupt: false, grade: "B"}}}], + ], +} + +{ + name: "per-member match through a member's single relationship", + policy: { + models: {customer: {companies: "company[]"}, company: {name: "string", address: "address"}, address: {country: "string"}}, + blocks: [{match: "company.jurisdiction", arms: [ + ["company.address.country in ['DE', 'FR', 'NL']", "'EU'"], + ["company.address.country == 'GB'", "'UK'"], + ["", "'ROW'"], + ]}], + }, + cases: [ + [ + {customer: {companies: [{name: "a", address: {country: "DE"}}, {name: "b", address: {country: "GB"}}, {name: "c", address: {country: "US"}}]}}, + {customer: {companies: [ + {name: "a", address: {country: "DE"}, jurisdiction: "EU"}, + {name: "b", address: {country: "GB"}, jurisdiction: "UK"}, + {name: "c", address: {country: "US"}, jurisdiction: "ROW"}, + ]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +{ + name: "parent match reads the first member through an index", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {match: "company.size", arms: [["company.revenue > 100", "'big'"], ["", "'small'"]]}, + {match: "customer.primary", arms: [ + ["len(customer.companies) == 0", "'none'"], + ["customer.companies[0].size == 'big'", "'big primary'"], + ["", "'small primary'"], + ]}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 500}, {revenue: 1}]}}, {customer: {primary: "big primary", companies: [{revenue: 500, size: "big"}, {revenue: 1, size: "small"}]}}], + [{customer: {companies: [{revenue: 1}, {revenue: 500}]}}, {customer: {primary: "small primary", companies: [{revenue: 1, size: "small"}, {revenue: 500, size: "big"}]}}], + [{customer: {companies: []}}, {customer: {primary: "none", companies: []}}], + ], +} + +{ + name: "per-member match whose arm value reads a sibling member computed", + policy: { + models: {invoice: {lines: "line[]"}, line: {qty: "number", price: "number", taxable: "boolean"}}, + blocks: [ + {expression: "line.net", value: "line.qty * line.price"}, + {match: "line.gross", arms: [["line.taxable", "line.net * 1.2"], ["", "line.net"]]}, + {expression: "invoice.total", value: "sum(map(invoice.lines, #.gross))"}, + ], + }, + cases: [ + [ + {invoice: {lines: [{qty: 2, price: 10, taxable: true}, {qty: 1, price: 5, taxable: false}]}}, + {invoice: {total: 29, lines: [{qty: 2, price: 10, taxable: true, net: 20, gross: 24}, {qty: 1, price: 5, taxable: false, net: 5, gross: 5}]}}, + ], + [{invoice: {lines: []}}, {invoice: {total: 0, lines: []}}], + [ + {invoice: {lines: [{qty: 3, price: 0.1, taxable: true}]}}, + {invoice: {total: 0.36, lines: [{qty: 3, price: 0.1, taxable: true, net: 0.3, gross: 0.36}]}}, + ], + ], +} + +{ + name: "per-member match with an optional member field", + policy: { + models: {team: {members: "member[]"}, member: {role: "string?"}}, + blocks: [{match: "member.access", arms: [ + ["member.role == 'admin'", "'all'"], + ["member.role == null", "'none'"], + ["", "'read'"], + ]}], + }, + cases: [ + [ + {team: {members: [{role: "admin"}, {role: null}, {}, {role: "viewer"}]}}, + {team: {members: [{role: "admin", access: "all"}, {role: null, access: "none"}, {access: "none"}, {role: "viewer", access: "read"}]}}, + ], + [{team: {members: []}}, {team: {members: []}}], + ], +} + +{ + name: "per-member lazy arm: a member computed read by one member's selected arm", + policy: { + models: {order: {lines: "line[]"}, line: {qty: "number", price: "number"}}, + blocks: [ + {expression: "line.bulkPrice", value: "line.qty * line.price * 0.8"}, + {match: "line.total", arms: [["line.qty >= 10", "line.bulkPrice"], ["", "line.qty * line.price"]]}, + ], + }, + cases: [ + [ + {order: {lines: [{qty: 10, price: 1}, {qty: 1, price: 5}]}}, + {order: {lines: [{qty: 10, price: 1, bulkPrice: 8, total: 8}, {qty: 1, price: 5, bulkPrice: 4, total: 5}]}}, + "question: once one member selects the arm, its conditional read is evaluated and written for every member, including members whose own arm never reads it; at the root level a property read only by unselected arms is not written at all, so the output shape depends on the other members", + ], + [ + {order: {lines: [{qty: 1, price: 2}, {qty: 2, price: 2}]}}, + {order: {lines: [{qty: 1, price: 2, total: 2}, {qty: 2, price: 2, total: 4}]}}, + ], + [ + {order: {lines: [{qty: 20, price: 1}, {qty: 30, price: 1}]}}, + {order: {lines: [{qty: 20, price: 1, bulkPrice: 16, total: 16}, {qty: 30, price: 1, bulkPrice: 24, total: 24}]}}, + ], + [{order: {lines: []}}, {order: {lines: []}}], + ], +} + +// --------------------------------------------------------------------------- +// Enums and dictionaries: an arm set that covers every value is exhaustive without a default. +// --------------------------------------------------------------------------- +{ + name: "dictionary covered value by value, no default", + policy: { + dictionaries: {tier: [["BR", "Bronze"], ["SI", "Silver"], ["GO", "Gold"], ["PL", "Platinum"]]}, + models: {customer: {tier: "tier"}}, + blocks: [{match: "customer.discount", arms: [ + ["customer.tier == 'BR'", "0"], + ["customer.tier == 'SI'", "0.05"], + ["customer.tier == 'GO'", "0.1"], + ["customer.tier == 'PL'", "0.2"], + ]}], + }, + cases: [ + [{customer: {tier: "BR"}}, {customer: {tier: "BR", discount: 0}}], + [{customer: {tier: "SI"}}, {customer: {tier: "SI", discount: 0.05}}], + [{customer: {tier: "GO"}}, {customer: {tier: "GO", discount: 0.1}}], + [{customer: {tier: "PL"}}, {customer: {tier: "PL", discount: 0.2}}], + [{customer: {tier: "Gold"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "dictionary covered with `in` lists and a reversed equality", + policy: { + dictionaries: {status: ["open", "pending", "closed", "archived"]}, + models: {ticket: {status: "status"}}, + blocks: [{match: "ticket.active", arms: [ + ["ticket.status in ['open', 'pending']", "true"], + ["'closed' == ticket.status", "false"], + ["ticket.status in ['archived']", "false"], + ]}], + }, + cases: [ + [{ticket: {status: "open"}}, {ticket: {status: "open", active: true}}], + [{ticket: {status: "pending"}}, {ticket: {status: "pending", active: true}}], + [{ticket: {status: "closed"}}, {ticket: {status: "closed", active: false}}], + [{ticket: {status: "archived"}}, {ticket: {status: "archived", active: false}}], + ], +} + +{ + name: "enum covered by `or` inside one arm", + policy: { + models: {order: {channel: "string(web|app|store|phone)"}}, + blocks: [{match: "order.kind", arms: [ + ["order.channel == 'web' or order.channel == 'app'", "'digital'"], + ["order.channel == 'store' or order.channel == 'phone'", "'assisted'"], + ]}], + }, + cases: [ + [{order: {channel: "web"}}, {order: {channel: "web", kind: "digital"}}], + [{order: {channel: "app"}}, {order: {channel: "app", kind: "digital"}}], + [{order: {channel: "store"}}, {order: {channel: "store", kind: "assisted"}}], + [{order: {channel: "phone"}}, {order: {channel: "phone", kind: "assisted"}}], + ], +} + +{ + name: "dictionary partially covered without default writes null", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + dictionaries: {status: ["open", "pending", "closed"]}, + models: {ticket: {status: "status"}}, + blocks: [{match: "ticket.sla", arms: [["ticket.status == 'open'", "24"], ["ticket.status == 'pending'", "72"]]}], + }, + cases: [ + [{ticket: {status: "open"}}, {ticket: {status: "open", sla: 24}}], + [{ticket: {status: "pending"}}, {ticket: {status: "pending", sla: 72}}], + [{ticket: {status: "closed"}}, {ticket: {status: "closed", sla: null}}], + ], +} + +{ + name: "optional enum covered value by value is not exhaustive: null falls through", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {order: {channel: "string(web|store)?"}}, + blocks: [{match: "order.fee", arms: [["order.channel == 'web'", "0"], ["order.channel == 'store'", "2"]]}], + }, + cases: [ + [{order: {channel: "web"}}, {order: {channel: "web", fee: 0}}], + [{order: {channel: "store"}}, {order: {channel: "store", fee: 2}}], + [{order: {channel: null}}, {order: {channel: null, fee: null}}], + [{order: {}}, {order: {fee: null}}], + ], +} + +{ + name: "optional enum with an explicit null arm and a default", + policy: { + models: {order: {channel: "string(web|store)?"}}, + blocks: [{match: "order.fee", arms: [ + ["order.channel == null", "-1"], + ["order.channel == 'web'", "0"], + ["", "2"], + ]}], + }, + cases: [ + [{order: {channel: "web"}}, {order: {channel: "web", fee: 0}}], + [{order: {channel: "store"}}, {order: {channel: "store", fee: 2}}], + [{order: {channel: null}}, {order: {channel: null, fee: -1}}], + [{order: {}}, {order: {fee: -1}}], + ], +} + +{ + name: "arms over two different enum paths are not a discriminated union", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {order: {channel: "string(web|store)", plan: "string(free|paid)"}}, + blocks: [{match: "order.label", arms: [ + ["order.channel == 'web'", "'web'"], + ["order.plan == 'free'", "'free store'"], + ["order.channel == 'store'", "'paid store'"], + ]}], + }, + cases: [ + [{order: {channel: "web", plan: "free"}}, {order: {channel: "web", plan: "free", label: "web"}}], + [{order: {channel: "store", plan: "free"}}, {order: {channel: "store", plan: "free", label: "free store"}}], + [{order: {channel: "store", plan: "paid"}}, {order: {channel: "store", plan: "paid", label: "paid store"}}], + ], +} + +{ + name: "numeric cover with intervals and points, no default", + policy: { + models: {x: {n: "number"}}, + blocks: [{match: "x.band", arms: [ + ["x.n < 0", "'negative'"], + ["x.n == 0", "'zero'"], + ["x.n in (0..10]", "'small'"], + ["x.n > 10 and x.n <= 100", "'medium'"], + ["x.n > 100", "'large'"], + ]}], + }, + cases: [ + [{x: {n: -0.001}}, {x: {n: -0.001, band: "negative"}}], + [{x: {n: 0}}, {x: {n: 0, band: "zero"}}], + [{x: {n: 0.001}}, {x: {n: 0.001, band: "small"}}], + [{x: {n: 10}}, {x: {n: 10, band: "small"}}], + [{x: {n: 10.5}}, {x: {n: 10.5, band: "medium"}}], + [{x: {n: 100}}, {x: {n: 100, band: "medium"}}], + [{x: {n: 100.01}}, {x: {n: 100.01, band: "large"}}], + ], +} + +{ + name: "numeric cover with a hole at a single point is not exhaustive", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {x: {n: "number"}}, + blocks: [{match: "x.sign", arms: [["x.n < 0", "-1"], ["x.n > 0", "1"]]}], + }, + cases: [ + [{x: {n: -2}}, {x: {n: -2, sign: -1}}], + [{x: {n: 2}}, {x: {n: 2, sign: 1}}], + [{x: {n: 0}}, {x: {n: 0, sign: null}}], + ], +} + +{ + name: "boolean covered by one `in` arm", + policy: { + models: {x: {b: "boolean"}}, + blocks: [{match: "x.known", arms: [["x.b in [true, false]", "'yes'"]]}], + }, + cases: [ + [{x: {b: true}}, {x: {b: true, known: "yes"}}], + [{x: {b: false}}, {x: {b: false, known: "yes"}}], + ], +} + +{ + name: "enum on members: exhaustive per-member match", + policy: { + models: {cart: {items: "item[]"}, item: {kind: "string(goods|service|fee)", amount: "number"}}, + blocks: [ + {match: "item.vat", arms: [ + ["item.kind == 'goods'", "item.amount * 0.2"], + ["item.kind == 'service'", "item.amount * 0.1"], + ["item.kind == 'fee'", "0"], + ]}, + {expression: "cart.vat", value: "sum(map(cart.items, #.vat))"}, + ], + }, + cases: [ + [ + {cart: {items: [{kind: "goods", amount: 100}, {kind: "service", amount: 50}, {kind: "fee", amount: 3}]}}, + {cart: {vat: 25, items: [{kind: "goods", amount: 100, vat: 20}, {kind: "service", amount: 50, vat: 5}, {kind: "fee", amount: 3, vat: 0}]}}, + ], + [{cart: {items: []}}, {cart: {vat: 0, items: []}}], + [{cart: {items: [{kind: "gift", amount: 1}]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "inline-enum global discriminates a match on an entity", + policy: { + globals: {env: {mode: "string(live|test)"}}, + models: {payment: {amount: "number"}}, + blocks: [{match: "payment.charge", arms: [ + ["mode == 'test'", "0"], + ["mode == 'live'", "payment.amount"], + ]}], + }, + cases: [ + [{payment: {amount: 9}, mode: "live"}, {payment: {amount: 9, charge: 9}, mode: "live"}], + [{payment: {amount: 0.5}, mode: "live"}, {payment: {amount: 0.5, charge: 0.5}, mode: "live"}], + [{payment: {amount: 9}, mode: "test"}, {payment: {amount: 9, charge: 0}, mode: "test"}], + [{payment: {amount: 9}, mode: "dev"}, "!error: InputValidationFailed"], + [{payment: {amount: 9}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "match over a computed literal union is exhaustive without a default", + policy: { + models: {x: {n: "number"}}, + blocks: [ + {match: "x.parity", arms: [["x.n % 2 == 0", "'even'"], ["", "'odd'"]]}, + {match: "x.code", arms: [["x.parity == 'even'", "0"], ["x.parity == 'odd'", "1"]]}, + ], + }, + cases: [ + [{x: {n: 2}}, {x: {n: 2, parity: "even", code: 0}}], + [{x: {n: 3}}, {x: {n: 3, parity: "odd", code: 1}}], + ], +} + +// --------------------------------------------------------------------------- +// Discriminated-union style models: a `kind` field decides which optional fields apply. +// --------------------------------------------------------------------------- +{ + name: "shape area by kind with kind-specific optional fields", + policy: { + models: {shape: {kind: "string(circle|rect|square)", radius: "number?", width: "number?", height: "number?"}}, + blocks: [{match: "shape.area", arms: [ + ["shape.kind == 'circle'", "3 * (shape.radius ?? 0) ^ 2"], + ["shape.kind == 'rect'", "(shape.width ?? 0) * (shape.height ?? 0)"], + ["shape.kind == 'square'", "(shape.width ?? 0) ^ 2"], + ]}], + }, + cases: [ + [{shape: {kind: "circle", radius: 2}}, {shape: {kind: "circle", radius: 2, area: 12}}], + [{shape: {kind: "rect", width: 2, height: 3.5}}, {shape: {kind: "rect", width: 2, height: 3.5, area: 7}}], + [{shape: {kind: "square", width: 4}}, {shape: {kind: "square", width: 4, area: 16}}], + [{shape: {kind: "rect", width: 2}}, {shape: {kind: "rect", width: 2, area: 0}}], + [{shape: {kind: "circle", width: 9, height: 9}}, {shape: {kind: "circle", width: 9, height: 9, area: 0}}], + [{shape: {kind: "triangle"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "union arms read optional fields without defaults: the selected arm's nulls fail", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {shape: {kind: "string(circle|rect)", radius: "number?", width: "number?", height: "number?"}}, + blocks: [{match: "shape.area", arms: [ + ["shape.kind == 'circle'", "3 * shape.radius * shape.radius"], + ["shape.kind == 'rect'", "shape.width * shape.height"], + ]}], + }, + cases: [ + [{shape: {kind: "circle", radius: 1}}, {shape: {kind: "circle", radius: 1, area: 3}}], + [{shape: {kind: "rect", width: 2, height: 5}}, {shape: {kind: "rect", width: 2, height: 5, area: 10}}], + [{shape: {kind: "circle", width: 2, height: 5}}, "!error: ExpressionFailed"], + [{shape: {kind: "rect", radius: 2}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "payment union: arms build differently shaped summaries", + policy: { + models: {payment: {method: "string(card|bank|wallet)", amount: "number", last4: "string?", iban: "string?", provider: "string?"}}, + blocks: [ + {match: "payment.summary", arms: [ + ["payment.method == 'card'", "{kind: 'card', ref: '**** ' + (payment.last4 ?? '????'), fee: round(payment.amount * 0.029 + 0.3, 2)}"], + ["payment.method == 'bank'", "{kind: 'bank', ref: payment.iban ?? 'unknown', fee: 0}"], + ["payment.method == 'wallet'", "{kind: 'wallet', ref: payment.provider ?? 'unknown', fee: round(payment.amount * 0.01, 2)}"], + ]}, + {expression: "payment.net", value: "payment.amount - payment.summary.fee"}, + ], + }, + cases: [ + [ + {payment: {method: "card", amount: 100, last4: "4242"}}, + {payment: {method: "card", amount: 100, last4: "4242", summary: {kind: "card", ref: "**** 4242", fee: 3.2}, net: 96.8}}, + ], + [ + {payment: {method: "bank", amount: 100, iban: "DE89"}}, + {payment: {method: "bank", amount: 100, iban: "DE89", summary: {kind: "bank", ref: "DE89", fee: 0}, net: 100}}, + ], + [ + {payment: {method: "wallet", amount: 50}}, + {payment: {method: "wallet", amount: 50, summary: {kind: "wallet", ref: "unknown", fee: 0.5}, net: 49.5}}, + ], + [ + {payment: {method: "card", amount: 0}}, + {payment: {method: "card", amount: 0, summary: {kind: "card", ref: "**** ????", fee: 0.3}, net: -0.3}}, + ], + ], +} + +{ + name: "per-member union: line items priced by their kind", + policy: { + models: { + order: {lines: "line[]"}, + line: {kind: "string(product|service|discount)", qty: "number?", unitPrice: "number?", hours: "number?", rate: "number?", percent: "number?"}, + }, + blocks: [ + {match: "line.amount", arms: [ + ["line.kind == 'product'", "(line.qty ?? 1) * (line.unitPrice ?? 0)"], + ["line.kind == 'service'", "(line.hours ?? 0) * (line.rate ?? 0)"], + ["line.kind == 'discount'", "0"], + ]}, + {expression: "order.subtotal", value: "sum(map(order.lines, #.amount))"}, + {expression: "order.discountPercent", value: "sum(map(filter(order.lines, #.kind == 'discount'), #.percent ?? 0))"}, + {expression: "order.total", value: "order.subtotal * (1 - order.discountPercent / 100)"}, + ], + }, + cases: [ + [ + {order: {lines: [{kind: "product", qty: 2, unitPrice: 10}, {kind: "service", hours: 1.5, rate: 40}, {kind: "discount", percent: 10}]}}, + {order: {subtotal: 80, discountPercent: 10, total: 72, lines: [ + {kind: "product", qty: 2, unitPrice: 10, amount: 20}, + {kind: "service", hours: 1.5, rate: 40, amount: 60}, + {kind: "discount", percent: 10, amount: 0}, + ]}}, + ], + [ + {order: {lines: [{kind: "product", unitPrice: 5}]}}, + {order: {subtotal: 5, discountPercent: 0, total: 5, lines: [{kind: "product", unitPrice: 5, amount: 5}]}}, + ], + [{order: {lines: []}}, {order: {subtotal: 0, discountPercent: 0, total: 0, lines: []}}], + ], +} + +{ + name: "union with a single-relationship variant per kind", + policy: { + models: { + applicant: {type: "string(person|company)", person: "personInfo?", company: "companyInfo?"}, + personInfo: {age: "number"}, + companyInfo: {years: "number"}, + }, + blocks: [{match: "applicant.eligible", arms: [ + ["applicant.type == 'person'", "(applicant.person.age ?? 0) >= 18"], + ["applicant.type == 'company'", "(applicant.company.years ?? 0) >= 2"], + ]}], + }, + cases: [ + [{applicant: {type: "person", person: {age: 30}}}, {applicant: {type: "person", person: {age: 30}, eligible: true}}], + [{applicant: {type: "person", person: {age: 17}}}, {applicant: {type: "person", person: {age: 17}, eligible: false}}], + [{applicant: {type: "company", company: {years: 2}}}, {applicant: {type: "company", company: {years: 2}, eligible: true}}], + [{applicant: {type: "company", company: {years: 1}}}, {applicant: {type: "company", company: {years: 1}, eligible: false}}], + [{applicant: {type: "company"}}, {applicant: {type: "company", eligible: false}}], + [{applicant: {type: "person", company: {years: 9}}}, {applicant: {type: "person", company: {years: 9}, eligible: false}}], + ], +} + +{ + name: "union kind chosen by a match, then a second exhaustive match discriminates on it", + policy: { + models: {event: {payload: "string"}}, + blocks: [ + {match: "event.kind", arms: [ + ["startsWith(event.payload, 'ERR')", "'error'"], + ["startsWith(event.payload, 'WARN')", "'warning'"], + ["", "'info'"], + ]}, + {match: "event.severity", arms: [ + ["event.kind == 'error'", "3"], + ["event.kind == 'warning'", "2"], + ["event.kind == 'info'", "1"], + ]}, + ], + }, + cases: [ + [{event: {payload: "ERR disk"}}, {event: {payload: "ERR disk", kind: "error", severity: 3}}], + [{event: {payload: "WARN cpu"}}, {event: {payload: "WARN cpu", kind: "warning", severity: 2}}], + [{event: {payload: "ok"}}, {event: {payload: "ok", kind: "info", severity: 1}}], + [{event: {payload: ""}}, {event: {payload: "", kind: "info", severity: 1}}], + ], +} diff --git a/core/engine/tests/spec/policy/19-assertions-advanced.json5 b/core/engine/tests/spec/policy/19-assertions-advanced.json5 new file mode 100644 index 00000000..cc766d6f --- /dev/null +++ b/core/engine/tests/spec/policy/19-assertions-advanced.json5 @@ -0,0 +1,847 @@ +// Assertion blocks in larger policies: deeply grouped conditions (depth 1 to 3), long mixed +// `and`/`or` chains, assertions that read computed values and relationship aggregates, and +// per-member assertions. Chapter 06 covers the basics. Reminder of the fold: a condition's +// operator joins it to the NEXT condition, conditions fold strictly left to right, and a run +// of conditions at a deeper depth is folded on its own, joined to what came before by the +// operator of the condition before the run. Truth-table suites state the intended formula in +// their name. + +// --------------------------------------------------------------------------- +// Depth-3 nesting. Each suite's name is the intended boolean formula; cases cover the full +// truth table (or a fixed sample of it for five variables). +// --------------------------------------------------------------------------- + +{ + name: "`p and (q or (r and (s or t)))`: three nested groups", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean", t: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p", 0], ["or", "x.q", 1], ["and", "x.r", 2], ["or", "x.s", 3], ["or", "x.t", 3]]}], + }, + cases: [ + [{x: {p: false, q: false, r: true, s: false, t: true}}, {x: {p: false, q: false, r: true, s: false, t: true, ok: false}}], + [{x: {p: false, q: true, r: true, s: true, t: false}}, {x: {p: false, q: true, r: true, s: true, t: false, ok: false}}], + [{x: {p: true, q: false, r: true, s: false, t: false}}, {x: {p: true, q: false, r: true, s: false, t: false, ok: false}}], + [{x: {p: true, q: false, r: true, s: false, t: true}}, {x: {p: true, q: false, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: false, r: false, s: true, t: true}}, {x: {p: false, q: false, r: false, s: true, t: true, ok: false}}], + [{x: {p: true, q: true, r: true, s: true, t: false}}, {x: {p: true, q: true, r: true, s: true, t: false, ok: true}}], + [{x: {p: true, q: true, r: false, s: true, t: false}}, {x: {p: true, q: true, r: false, s: true, t: false, ok: true}}], + [{x: {p: true, q: true, r: false, s: true, t: true}}, {x: {p: true, q: true, r: false, s: true, t: true, ok: true}}], + ], +} + +{ + name: "`((p or q) and r) or s`: the formula opens at depth 2", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 2], ["and", "x.q", 2], ["or", "x.r", 1], ["or", "x.s", 0]]}], + }, + cases: [ + [{x: {p: false, q: true, r: false, s: true}}, {x: {p: false, q: true, r: false, s: true, ok: true}}], + [{x: {p: true, q: false, r: true, s: false}}, {x: {p: true, q: false, r: true, s: false, ok: true}}], + [{x: {p: true, q: true, r: true, s: true}}, {x: {p: true, q: true, r: true, s: true, ok: true}}], + [{x: {p: true, q: true, r: true, s: false}}, {x: {p: true, q: true, r: true, s: false, ok: true}}], + [{x: {p: false, q: true, r: true, s: false}}, {x: {p: false, q: true, r: true, s: false, ok: true}}], + [{x: {p: true, q: false, r: true, s: true}}, {x: {p: true, q: false, r: true, s: true, ok: true}}], + [{x: {p: true, q: false, r: false, s: true}}, {x: {p: true, q: false, r: false, s: true, ok: true}}], + [{x: {p: true, q: true, r: false, s: true}}, {x: {p: true, q: true, r: false, s: true, ok: true}}], + ], +} + +{ + name: "`(((p and q) or r) and s)`: everything inside nested groups, from depth 3 down", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p", 3], ["or", "x.q", 3], ["and", "x.r", 2], ["and", "x.s", 1]]}], + }, + cases: [ + [{x: {p: true, q: true, r: true, s: false}}, {x: {p: true, q: true, r: true, s: false, ok: false}}], + [{x: {p: true, q: false, r: false, s: false}}, {x: {p: true, q: false, r: false, s: false, ok: false}}], + [{x: {p: false, q: false, r: false, s: true}}, {x: {p: false, q: false, r: false, s: true, ok: false}}], + [{x: {p: false, q: true, r: false, s: false}}, {x: {p: false, q: true, r: false, s: false, ok: false}}], + [{x: {p: false, q: false, r: true, s: true}}, {x: {p: false, q: false, r: true, s: true, ok: true}}], + [{x: {p: true, q: true, r: false, s: false}}, {x: {p: true, q: true, r: false, s: false, ok: false}}], + [{x: {p: false, q: true, r: true, s: false}}, {x: {p: false, q: true, r: true, s: false, ok: false}}], + [{x: {p: true, q: true, r: true, s: true}}, {x: {p: true, q: true, r: true, s: true, ok: true}}], + ], +} + +{ + name: "`p or (q and (r or (s and t)))`: dropping from depth 3 to the end closes every group", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean", t: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 0], ["and", "x.q", 1], ["or", "x.r", 2], ["and", "x.s", 3], ["and", "x.t", 3]]}], + }, + cases: [ + [{x: {p: false, q: true, r: true, s: true, t: true}}, {x: {p: false, q: true, r: true, s: true, t: true, ok: true}}], + [{x: {p: false, q: false, r: true, s: true, t: false}}, {x: {p: false, q: false, r: true, s: true, t: false, ok: false}}], + [{x: {p: false, q: true, r: true, s: false, t: true}}, {x: {p: false, q: true, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: false, r: false, s: false, t: false}}, {x: {p: false, q: false, r: false, s: false, t: false, ok: false}}], + [{x: {p: false, q: false, r: false, s: true, t: false}}, {x: {p: false, q: false, r: false, s: true, t: false, ok: false}}], + [{x: {p: false, q: true, r: false, s: true, t: true}}, {x: {p: false, q: true, r: false, s: true, t: true, ok: true}}], + [{x: {p: true, q: true, r: true, s: true, t: true}}, {x: {p: true, q: true, r: true, s: true, t: true, ok: true}}], + [{x: {p: true, q: true, r: false, s: true, t: true}}, {x: {p: true, q: true, r: false, s: true, t: true, ok: true}}], + ], +} + +{ + name: "`(p and (q or (r and s))) or t`: depth 3 straight back to 0", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean", t: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p", 1], ["or", "x.q", 2], ["and", "x.r", 3], ["or", "x.s", 3], ["or", "x.t", 0]]}], + }, + cases: [ + [{x: {p: true, q: false, r: true, s: true, t: false}}, {x: {p: true, q: false, r: true, s: true, t: false, ok: true}}], + [{x: {p: false, q: false, r: true, s: true, t: true}}, {x: {p: false, q: false, r: true, s: true, t: true, ok: true}}], + [{x: {p: true, q: false, r: false, s: false, t: true}}, {x: {p: true, q: false, r: false, s: false, t: true, ok: true}}], + [{x: {p: true, q: false, r: true, s: false, t: true}}, {x: {p: true, q: false, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: false, r: false, s: true, t: true}}, {x: {p: false, q: false, r: false, s: true, t: true, ok: true}}], + [{x: {p: true, q: true, r: true, s: true, t: false}}, {x: {p: true, q: true, r: true, s: true, t: false, ok: true}}], + [{x: {p: true, q: true, r: false, s: true, t: false}}, {x: {p: true, q: true, r: false, s: true, t: false, ok: true}}], + [{x: {p: true, q: true, r: true, s: false, t: false}}, {x: {p: true, q: true, r: true, s: false, t: false, ok: true}}], + ], +} + +{ + name: "`p and ((q or r) and s)`: a group that starts with a deeper group", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p", 0], ["or", "x.q", 2], ["and", "x.r", 2], ["and", "x.s", 1]]}], + }, + cases: [ + [{x: {p: true, q: false, r: false, s: false}}, {x: {p: true, q: false, r: false, s: false, ok: false}}], + [{x: {p: false, q: false, r: false, s: false}}, {x: {p: false, q: false, r: false, s: false, ok: false}}], + [{x: {p: true, q: true, r: true, s: true}}, {x: {p: true, q: true, r: true, s: true, ok: true}}], + [{x: {p: false, q: false, r: false, s: true}}, {x: {p: false, q: false, r: false, s: true, ok: false}}], + [{x: {p: true, q: true, r: true, s: false}}, {x: {p: true, q: true, r: true, s: false, ok: false}}], + [{x: {p: true, q: false, r: false, s: true}}, {x: {p: true, q: false, r: false, s: true, ok: false}}], + [{x: {p: true, q: false, r: true, s: false}}, {x: {p: true, q: false, r: true, s: false, ok: false}}], + [{x: {p: false, q: true, r: true, s: false}}, {x: {p: false, q: true, r: true, s: false, ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Sibling groups separated by a shallower condition, and depth going down then up again. +// --------------------------------------------------------------------------- + +{ + name: "`(p or q) and r and (s or t)`: two depth-1 groups around a depth-0 condition", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean", t: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 1], ["and", "x.q", 1], ["and", "x.r", 0], ["or", "x.s", 1], ["and", "x.t", 1]]}], + }, + cases: [ + [{x: {p: true, q: false, r: true, s: true, t: true}}, {x: {p: true, q: false, r: true, s: true, t: true, ok: true}}], + [{x: {p: true, q: true, r: false, s: true, t: false}}, {x: {p: true, q: true, r: false, s: true, t: false, ok: false}}], + [{x: {p: false, q: true, r: true, s: false, t: false}}, {x: {p: false, q: true, r: true, s: false, t: false, ok: false}}], + [{x: {p: false, q: true, r: false, s: true, t: true}}, {x: {p: false, q: true, r: false, s: true, t: true, ok: false}}], + [{x: {p: false, q: false, r: true, s: false, t: true}}, {x: {p: false, q: false, r: true, s: false, t: true, ok: false}}], + [{x: {p: true, q: false, r: false, s: true, t: false}}, {x: {p: true, q: false, r: false, s: true, t: false, ok: false}}], + [{x: {p: true, q: true, r: false, s: false, t: true}}, {x: {p: true, q: true, r: false, s: false, t: true, ok: false}}], + [{x: {p: true, q: false, r: true, s: false, t: true}}, {x: {p: true, q: false, r: true, s: false, t: true, ok: true}}], + ], +} + +{ + name: "`p or (q and r or s and t)`: one group folds left inside, `((q and r) or s) and t`", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean", t: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 0], ["and", "x.q", 1], ["or", "x.r", 1], ["and", "x.s", 1], ["and", "x.t", 1]]}], + }, + cases: [ + [{x: {p: true, q: true, r: false, s: true, t: true}}, {x: {p: true, q: true, r: false, s: true, t: true, ok: true}}], + [{x: {p: true, q: false, r: false, s: true, t: true}}, {x: {p: true, q: false, r: false, s: true, t: true, ok: true}}], + [{x: {p: false, q: false, r: true, s: true, t: true}}, {x: {p: false, q: false, r: true, s: true, t: true, ok: true}}], + [{x: {p: true, q: true, r: true, s: false, t: true}}, {x: {p: true, q: true, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: false, r: false, s: true, t: true}}, {x: {p: false, q: false, r: false, s: true, t: true, ok: true}}], + [{x: {p: true, q: false, r: true, s: false, t: true}}, {x: {p: true, q: false, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: true, r: true, s: false, t: true}}, {x: {p: false, q: true, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: false, r: true, s: false, t: false}}, {x: {p: false, q: false, r: true, s: false, t: false, ok: false}}], + ], +} + +{ + name: "`p or (q and r) or (s and t)`: the second conjunction nests one level deeper", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean", t: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 0], ["and", "x.q", 1], ["or", "x.r", 1], ["and", "x.s", 2], ["and", "x.t", 2]]}], + }, + cases: [ + [{x: {p: true, q: true, r: false, s: true, t: false}}, {x: {p: true, q: true, r: false, s: true, t: false, ok: true}}], + [{x: {p: false, q: true, r: false, s: false, t: false}}, {x: {p: false, q: true, r: false, s: false, t: false, ok: false}}], + [{x: {p: false, q: true, r: true, s: false, t: false}}, {x: {p: false, q: true, r: true, s: false, t: false, ok: true}}], + [{x: {p: true, q: false, r: true, s: true, t: true}}, {x: {p: true, q: false, r: true, s: true, t: true, ok: true}}], + [{x: {p: false, q: false, r: true, s: true, t: true}}, {x: {p: false, q: false, r: true, s: true, t: true, ok: true}}], + [{x: {p: false, q: true, r: true, s: false, t: true}}, {x: {p: false, q: true, r: true, s: false, t: true, ok: true}}], + [{x: {p: true, q: false, r: true, s: false, t: true}}, {x: {p: true, q: false, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: false, r: false, s: false, t: true}}, {x: {p: false, q: false, r: false, s: false, t: true, ok: false}}], + ], +} + +{ + name: "`p and ((q or (r and s)) and t)`: back from depth 2 to 1 continues the same group", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean", t: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p", 0], ["or", "x.q", 1], ["and", "x.r", 2], ["and", "x.s", 2], ["and", "x.t", 1]]}], + }, + cases: [ + [{x: {p: true, q: true, r: true, s: false, t: true}}, {x: {p: true, q: true, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: true, r: true, s: true, t: true}}, {x: {p: false, q: true, r: true, s: true, t: true, ok: false}}], + [{x: {p: false, q: false, r: false, s: true, t: false}}, {x: {p: false, q: false, r: false, s: true, t: false, ok: false}}], + [{x: {p: true, q: false, r: true, s: true, t: false}}, {x: {p: true, q: false, r: true, s: true, t: false, ok: false}}], + [{x: {p: false, q: true, r: true, s: false, t: false}}, {x: {p: false, q: true, r: true, s: false, t: false, ok: false}}], + [{x: {p: true, q: true, r: false, s: false, t: false}}, {x: {p: true, q: true, r: false, s: false, t: false, ok: false}}], + [{x: {p: false, q: false, r: false, s: false, t: false}}, {x: {p: false, q: false, r: false, s: false, t: false, ok: false}}], + [{x: {p: false, q: false, r: true, s: true, t: false}}, {x: {p: false, q: false, r: true, s: true, t: false, ok: false}}], + ], +} + +{ + name: "`((p or (q and r)) and s) or t`: a depth-2 group closes back into its depth-1 group", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean", s: "boolean", t: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p", 1], ["and", "x.q", 2], ["and", "x.r", 2], ["or", "x.s", 1], ["or", "x.t", 1]]}], + }, + cases: [ + [{x: {p: false, q: false, r: false, s: true, t: true}}, {x: {p: false, q: false, r: false, s: true, t: true, ok: true}}], + [{x: {p: true, q: false, r: true, s: true, t: false}}, {x: {p: true, q: false, r: true, s: true, t: false, ok: true}}], + [{x: {p: false, q: true, r: true, s: false, t: false}}, {x: {p: false, q: true, r: true, s: false, t: false, ok: false}}], + [{x: {p: true, q: false, r: true, s: false, t: true}}, {x: {p: true, q: false, r: true, s: false, t: true, ok: true}}], + [{x: {p: false, q: false, r: false, s: true, t: false}}, {x: {p: false, q: false, r: false, s: true, t: false, ok: false}}], + [{x: {p: true, q: true, r: false, s: true, t: false}}, {x: {p: true, q: true, r: false, s: true, t: false, ok: true}}], + [{x: {p: true, q: true, r: false, s: false, t: false}}, {x: {p: true, q: true, r: false, s: false, t: false, ok: false}}], + [{x: {p: false, q: true, r: false, s: false, t: true}}, {x: {p: false, q: true, r: false, s: false, t: true, ok: true}}], + ], +} + +// --------------------------------------------------------------------------- +// Long mixed chains over comparisons (no groups): strict left fold. +// --------------------------------------------------------------------------- +{ + name: "`a and b or c and d or e` folds as `(((a and b) or c) and d) or e`", + policy: { + models: {x: {a: "number", b: "number", c: "number", d: "number", e: "number"}}, + blocks: [{assertion: "x.ok", conditions: [ + ["and", "x.a > 0"], + ["or", "x.b > 0"], + ["and", "x.c > 0"], + ["or", "x.d > 0"], + "x.e > 0", + ]}], + }, + cases: [ + [{x: {a: 1, b: 1, c: 0, d: 0, e: 0}}, {x: {a: 1, b: 1, c: 0, d: 0, e: 0, ok: false}}], + [{x: {a: 1, b: 1, c: 0, d: 1, e: 0}}, {x: {a: 1, b: 1, c: 0, d: 1, e: 0, ok: true}}], + [{x: {a: 0, b: 0, c: 1, d: 1, e: 0}}, {x: {a: 0, b: 0, c: 1, d: 1, e: 0, ok: true}}], + [{x: {a: 0, b: 0, c: 1, d: 0, e: 0}}, {x: {a: 0, b: 0, c: 1, d: 0, e: 0, ok: false}}], + [{x: {a: 0, b: 0, c: 0, d: 0, e: 0.5}}, {x: {a: 0, b: 0, c: 0, d: 0, e: 0.5, ok: true}}], + [{x: {a: -1, b: 5, c: -1, d: 5, e: -1}}, {x: {a: -1, b: 5, c: -1, d: 5, e: -1, ok: false}}], + ], +} + +{ + name: "six `or` conditions then one `and`: `(a or b or c or d or e) and f`", + policy: { + models: {x: {tags: "string[]", vip: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [ + ["or", "'a' in x.tags"], + ["or", "'b' in x.tags"], + ["or", "'c' in x.tags"], + ["or", "'d' in x.tags"], + ["and", "'e' in x.tags"], + "x.vip", + ]}], + }, + cases: [ + [{x: {tags: ["c"], vip: true}}, {x: {tags: ["c"], vip: true, ok: true}}], + [{x: {tags: ["e"], vip: true}}, {x: {tags: ["e"], vip: true, ok: true}}], + [{x: {tags: ["a", "e"], vip: false}}, {x: {tags: ["a", "e"], vip: false, ok: false}}], + [{x: {tags: ["z"], vip: true}}, {x: {tags: ["z"], vip: true, ok: false}}], + [{x: {tags: [], vip: true}}, {x: {tags: [], vip: true, ok: false}}], + ], +} + +{ + name: "a condition holding its own `and`/`or` expression is one operand of the fold", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], "x.q or x.r and false"]}], + }, + cases: [ + [{x: {p: true, q: false, r: true}}, {x: {p: true, q: false, r: true, ok: true}}], + [{x: {p: false, q: true, r: false}}, {x: {p: false, q: true, r: false, ok: true}}], + [{x: {p: false, q: false, r: true}}, {x: {p: false, q: false, r: true, ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Degenerate groups: single-condition groups, empty conditions inside groups. +// --------------------------------------------------------------------------- +{ + name: "a single-condition group is the same as no group: `p and (q) or r`", + policy: { + models: {x: {p: "boolean", q: "boolean", r: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", "x.q", 1], "x.r"]}], + }, + cases: [ + [{x: {p: true, q: true, r: false}}, {x: {p: true, q: true, r: false, ok: true}}], + [{x: {p: false, q: true, r: false}}, {x: {p: false, q: true, r: false, ok: false}}], + [{x: {p: false, q: false, r: true}}, {x: {p: false, q: false, r: true, ok: true}}], + ], +} + +{ + name: "an empty condition inside a group is skipped, its depth with it", + policy: { + models: {x: {p: "boolean", q: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", "", 1], ["and", " ", 2], "x.q"]}], + }, + cases: [ + [{x: {p: true, q: true}}, {x: {p: true, q: true, ok: true}}], + [{x: {p: true, q: false}}, {x: {p: true, q: false, ok: false}}], + [{x: {p: false, q: true}}, {x: {p: false, q: true, ok: false}}], + ], +} + +{ + name: "an operator on a skipped empty condition is lost: `p or ''` then `q` joins with `and`", + policy: { + models: {x: {p: "boolean", q: "boolean"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", ""], "x.q"]}], + }, + cases: [ + [{x: {p: true, q: false}}, {x: {p: true, q: false, ok: false}}], + [{x: {p: false, q: true}}, {x: {p: false, q: true, ok: false}}], + [{x: {p: true, q: true}}, {x: {p: true, q: true, ok: true}}], + ], +} + +// --------------------------------------------------------------------------- +// Null, non-boolean and failing conditions inside groups. +// --------------------------------------------------------------------------- +{ + name: "a null condition inside an `or` group counts as false", + policy: { + models: {x: {p: "boolean", n: "boolean?"}}, + blocks: [{assertion: "x.ok", conditions: [["and", "x.p"], ["or", "x.n", 1], ["or", "x.n == null", 1]]}], + }, + cases: [ + [{x: {p: true, n: true}}, {x: {p: true, n: true, ok: true}}], + [{x: {p: true, n: false}}, {x: {p: true, n: false, ok: false}}], + [{x: {p: true, n: null}}, {x: {p: true, n: null, ok: true}}], + [{x: {p: true}}, {x: {p: true, ok: true}}], + [{x: {p: false}}, {x: {p: false, ok: false}}], + ], +} + +{ + name: "a non-boolean condition inside a deep group counts as false", + policy: { + models: {x: {p: "boolean", n: "number", s: "string"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], ["or", "x.n", 2], ["or", "x.s", 2]]}], + }, + cases: [ + [{x: {p: true, n: 1, s: "true"}}, {x: {p: true, n: 1, s: "true", ok: true}}], + [{x: {p: false, n: 1, s: "true"}}, {x: {p: false, n: 1, s: "true", ok: false}}], + [{x: {p: false, n: 0, s: ""}}, {x: {p: false, n: 0, s: "", ok: false}}], + ], +} + +{ + name: "a failing condition at depth 3 fails the evaluation even when the fold is decided", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {x: {p: "boolean", s: "string"}}, + blocks: [{assertion: "x.ok", conditions: [["or", "x.p"], ["and", "x.p", 1], ["and", "x.p", 2], ["and", "x.s * 2 > 0", 3]]}], + }, + cases: [ + [{x: {p: true, s: "a"}}, "!error: ExpressionFailed"], + [{x: {p: false, s: "a"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "optional number inside a guarded group condition", + policy: { + models: {x: {limit: "number?", amount: "number"}}, + blocks: [{assertion: "x.ok", conditions: [ + ["and", "x.amount > 0"], + ["or", "x.limit == null", 1], + ["or", "(x.limit ?? 0) >= x.amount", 1], + ]}], + }, + cases: [ + [{x: {amount: 10, limit: 20}}, {x: {amount: 10, limit: 20, ok: true}}], + [{x: {amount: 10, limit: 5}}, {x: {amount: 10, limit: 5, ok: false}}], + [{x: {amount: 10, limit: null}}, {x: {amount: 10, limit: null, ok: true}}], + [{x: {amount: 10}}, {x: {amount: 10, ok: true}}], + [{x: {amount: 0}}, {x: {amount: 0, ok: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Assertions reading computed values. +// --------------------------------------------------------------------------- +{ + name: "grouped conditions read an expression, a match and a table output", + policy: { + models: {order: {amount: "number", qty: "number", country: "string"}}, + blocks: [ + {assertion: "order.autoApprove", conditions: [ + ["and", "order.total < 5000"], + ["or", "order.region == 'domestic'", 1], + ["and", "order.risk == 'low'", 2], + ["and", "order.qty < 100", 2], + ]}, + {expression: "order.total", value: "order.amount * order.qty"}, + {match: "order.region", arms: [["order.country == 'DE'", "'domestic'"], ["", "'foreign'"]]}, + {table: "risk", inputs: ["order.country"], outputs: ["order.risk"], rules: [["'XX', 'YY'", "'high'"], ["", "'low'"]]}, + ], + }, + cases: [ + [{order: {amount: 10, qty: 10, country: "DE"}}, {order: {amount: 10, qty: 10, country: "DE", total: 100, region: "domestic", risk: "low", autoApprove: true}}], + [{order: {amount: 10, qty: 10, country: "FR"}}, {order: {amount: 10, qty: 10, country: "FR", total: 100, region: "foreign", risk: "low", autoApprove: true}}], + [{order: {amount: 1, qty: 200, country: "FR"}}, {order: {amount: 1, qty: 200, country: "FR", total: 200, region: "foreign", risk: "low", autoApprove: false}}], + [{order: {amount: 1, qty: 1, country: "XX"}}, {order: {amount: 1, qty: 1, country: "XX", total: 1, region: "foreign", risk: "high", autoApprove: false}}], + [{order: {amount: 100, qty: 50, country: "DE"}}, {order: {amount: 100, qty: 50, country: "DE", total: 5000, region: "domestic", risk: "low", autoApprove: false}}], + ], +} + +{ + name: "an assertion over two other assertions in a group", + policy: { + models: {applicant: {age: "number", income: "number", guarantor: "boolean"}}, + blocks: [ + {assertion: "applicant.adult", conditions: ["applicant.age >= 18"]}, + {assertion: "applicant.solvent", conditions: [["or", "applicant.income >= 30000"], "applicant.guarantor"]}, + {assertion: "applicant.approved", conditions: [["and", "applicant.adult"], ["or", "applicant.solvent", 1], ["or", "applicant.age >= 65", 1]]}, + ], + }, + cases: [ + [{applicant: {age: 30, income: 40000, guarantor: false}}, {applicant: {age: 30, income: 40000, guarantor: false, adult: true, solvent: true, approved: true}}], + [{applicant: {age: 30, income: 0, guarantor: true}}, {applicant: {age: 30, income: 0, guarantor: true, adult: true, solvent: true, approved: true}}], + [{applicant: {age: 30, income: 0, guarantor: false}}, {applicant: {age: 30, income: 0, guarantor: false, adult: true, solvent: false, approved: false}}], + [{applicant: {age: 70, income: 0, guarantor: false}}, {applicant: {age: 70, income: 0, guarantor: false, adult: true, solvent: false, approved: true}}], + [{applicant: {age: 17, income: 99999, guarantor: true}}, {applicant: {age: 17, income: 99999, guarantor: true, adult: false, solvent: true, approved: false}}], + ], +} + +{ + name: "assertion reads a nested field of a computed object", + policy: { + models: {order: {amount: "number"}}, + blocks: [ + {expression: "order.pricing", value: "{net: order.amount, tax: order.amount * 0.2, flags: order.amount > 100 ? ['large'] : []}"}, + {assertion: "order.reviewable", conditions: [["or", "order.pricing.tax > 50"], "'large' in order.pricing.flags"]}, + ], + }, + cases: [ + [{order: {amount: 300}}, {order: {amount: 300, pricing: {net: 300, tax: 60, flags: ["large"]}, reviewable: true}}], + [{order: {amount: 200}}, {order: {amount: 200, pricing: {net: 200, tax: 40, flags: ["large"]}, reviewable: true}}], + [{order: {amount: 50}}, {order: {amount: 50, pricing: {net: 50, tax: 10, flags: []}, reviewable: false}}], + ], +} + +{ + name: "assertion reads a collected table array", + policy: { + models: {user: {age: "number", country: "string", verified: "boolean"}}, + blocks: [ + {table: "flags", inputs: ["user.age", "user.country"], outputs: ["user.flags[]"], rules: [ + ["< 18", "", "'minor'"], + ["", "'XX'", "'sanctioned'"], + ]}, + {assertion: "user.allowed", conditions: [ + ["and", "not ('sanctioned' in user.flags)"], + ["or", "len(user.flags) == 0", 1], + ["or", "user.verified", 1], + ]}, + ], + }, + cases: [ + [{user: {age: 30, country: "DE", verified: false}}, {user: {age: 30, country: "DE", verified: false, flags: [], allowed: true}}], + [{user: {age: 10, country: "DE", verified: true}}, {user: {age: 10, country: "DE", verified: true, flags: ["minor"], allowed: true}}], + [{user: {age: 10, country: "DE", verified: false}}, {user: {age: 10, country: "DE", verified: false, flags: ["minor"], allowed: false}}], + [{user: {age: 30, country: "XX", verified: true}}, {user: {age: 30, country: "XX", verified: true, flags: ["sanctioned"], allowed: false}}], + ], +} + +{ + name: "an assertion feeds a table and a match", + policy: { + models: {loan: {amount: "number", score: "number"}}, + blocks: [ + {assertion: "loan.prime", conditions: [["and", "loan.score >= 700"], "loan.amount <= 50000"]}, + {table: "rate", inputs: ["loan.prime", "loan.amount"], outputs: ["loan.rate"], rules: [ + ["true", "< 10000", "0.03"], + ["true", "", "0.035"], + ["false", "", "0.08"], + ]}, + {match: "loan.channel", arms: [["loan.prime", "'online'"], ["", "'branch'"]]}, + ], + }, + cases: [ + [{loan: {amount: 5000, score: 750}}, {loan: {amount: 5000, score: 750, prime: true, rate: 0.03, channel: "online"}}], + [{loan: {amount: 20000, score: 700}}, {loan: {amount: 20000, score: 700, prime: true, rate: 0.035, channel: "online"}}], + [{loan: {amount: 60000, score: 800}}, {loan: {amount: 60000, score: 800, prime: false, rate: 0.08, channel: "branch"}}], + [{loan: {amount: 100, score: 699}}, {loan: {amount: 100, score: 699, prime: false, rate: 0.08, channel: "branch"}}], + ], +} + +{ + name: "goal on an assertion pulls only its own computed inputs", + policy: { + models: {x: {a: "number", b: "number"}}, + blocks: [ + {expression: "x.sum", value: "x.a + x.b"}, + {expression: "x.product", value: "x.a * x.b"}, + {assertion: "x.sumPositive", conditions: [["or", "x.sum > 0"], "x.a == 0"]}, + {assertion: "x.productPositive", conditions: ["x.product > 0"]}, + ], + }, + cases: [ + {input: {x: {a: 2, b: 3}}, goals: ["x.sumPositive"], output: {x: {a: 2, b: 3, sum: 5, sumPositive: true}}}, + {input: {x: {a: -2, b: 1}}, goals: ["x.productPositive"], output: {x: {a: -2, b: 1, product: -2, productPositive: false}}}, + {input: {x: {a: 0, b: -1}}, output: {x: {a: 0, b: -1, sum: -1, product: 0, sumPositive: true, productPositive: false}}}, + ], +} + +// --------------------------------------------------------------------------- +// Assertions over relationship aggregates. +// --------------------------------------------------------------------------- +{ + name: "aggregates over member input fields, including empty arrays", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", active: "boolean"}}, + blocks: [ + {assertion: "customer.allActive", conditions: ["all(customer.companies, #.active)"]}, + {assertion: "customer.anyLarge", conditions: ["some(customer.companies, #.revenue > 1000)"]}, + {assertion: "customer.noLosses", conditions: ["none(customer.companies, #.revenue < 0)"]}, + {assertion: "customer.diversified", conditions: [["and", "count(customer.companies, #.active) >= 2"], "sum(map(customer.companies, #.revenue)) > 500"]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 2000, active: true}, {revenue: 10, active: true}]}}, + {customer: {companies: [{revenue: 2000, active: true}, {revenue: 10, active: true}], allActive: true, anyLarge: true, noLosses: true, diversified: true}}, + ], + [ + {customer: {companies: [{revenue: -5, active: false}, {revenue: 600, active: true}]}}, + {customer: {companies: [{revenue: -5, active: false}, {revenue: 600, active: true}], allActive: false, anyLarge: false, noLosses: false, diversified: false}}, + ], + [ + {customer: {companies: []}}, + {customer: {companies: [], allActive: true, anyLarge: false, noLosses: true, diversified: false}}, + ], + [ + {customer: {companies: [{revenue: 300, active: true}, {revenue: 300, active: true}, {revenue: -1, active: false}]}}, + {customer: {companies: [{revenue: 300, active: true}, {revenue: 300, active: true}, {revenue: -1, active: false}], allActive: false, anyLarge: false, noLosses: false, diversified: true}}, + ], + ], +} + +{ + name: "aggregates without a neutral element: `avg` guarded inside one condition, `max` of an empty list fails", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {assertion: "customer.highAverage", conditions: ["len(customer.companies) > 0 and avg(map(customer.companies, #.revenue)) > 100"]}, + {assertion: "customer.peakOver", conditions: ["(max(map(customer.companies, #.revenue)) ?? 0) > 1000"]}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 50}, {revenue: 250}]}}, {customer: {companies: [{revenue: 50}, {revenue: 250}], highAverage: true, peakOver: false}}], + [{customer: {companies: [{revenue: 5000}, {revenue: -5000}]}}, {customer: {companies: [{revenue: 5000}, {revenue: -5000}], highAverage: false, peakOver: true}}], + [{customer: {companies: []}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "grouped aggregate conditions over member computeds", + policy: { + models: {portfolio: {minLoans: "number", loans: "loan[]"}, loan: {amount: "number", daysLate: "number"}}, + blocks: [ + {assertion: "loan.performing", conditions: ["loan.daysLate <= 30"]}, + {expression: "loan.exposure", value: "loan.performing ? loan.amount : loan.amount * 2"}, + {assertion: "portfolio.healthy", conditions: [ + ["and", "len(portfolio.loans) >= portfolio.minLoans"], + ["or", "all(portfolio.loans, #.performing)", 1], + ["and", "count(portfolio.loans, not #.performing) == 1", 2], + ["and", "sum(map(portfolio.loans, #.exposure)) < 10000", 2], + ]}, + ], + }, + cases: [ + [ + {portfolio: {minLoans: 1, loans: [{amount: 100, daysLate: 0}, {amount: 200, daysLate: 10}]}}, + {portfolio: {minLoans: 1, healthy: true, loans: [{amount: 100, daysLate: 0, performing: true, exposure: 100}, {amount: 200, daysLate: 10, performing: true, exposure: 200}]}}, + ], + [ + {portfolio: {minLoans: 1, loans: [{amount: 100, daysLate: 60}, {amount: 200, daysLate: 0}]}}, + {portfolio: {minLoans: 1, healthy: true, loans: [{amount: 100, daysLate: 60, performing: false, exposure: 200}, {amount: 200, daysLate: 0, performing: true, exposure: 200}]}}, + ], + [ + {portfolio: {minLoans: 1, loans: [{amount: 6000, daysLate: 60}]}}, + {portfolio: {minLoans: 1, healthy: false, loans: [{amount: 6000, daysLate: 60, performing: false, exposure: 12000}]}}, + ], + [ + {portfolio: {minLoans: 1, loans: [{amount: 1, daysLate: 31}, {amount: 1, daysLate: 31}]}}, + {portfolio: {minLoans: 1, healthy: false, loans: [{amount: 1, daysLate: 31, performing: false, exposure: 2}, {amount: 1, daysLate: 31, performing: false, exposure: 2}]}}, + ], + [ + {portfolio: {minLoans: 3, loans: [{amount: 1, daysLate: 0}]}}, + {portfolio: {minLoans: 3, healthy: false, loans: [{amount: 1, daysLate: 0, performing: true, exposure: 1}]}}, + ], + [{portfolio: {minLoans: 0, loans: []}}, {portfolio: {minLoans: 0, healthy: true, loans: []}}], + ], +} + +{ + name: "assertion over two relationship arrays", + policy: { + models: {customer: {accounts: "account[]", loans: "loan[]"}, account: {balance: "number"}, loan: {outstanding: "number"}}, + blocks: [ + {expression: "customer.assets", value: "sum(map(customer.accounts, #.balance))"}, + {expression: "customer.debt", value: "sum(map(customer.loans, #.outstanding))"}, + {assertion: "customer.creditworthy", conditions: [ + ["or", "len(customer.loans) == 0"], + ["and", "customer.assets >= customer.debt", 1], + ["and", "none(customer.accounts, #.balance < 0)", 1], + ]}, + ], + }, + cases: [ + [ + {customer: {accounts: [{balance: -10}], loans: []}}, + {customer: {accounts: [{balance: -10}], loans: [], assets: -10, debt: 0, creditworthy: true}}, + ], + [ + {customer: {accounts: [{balance: 500}, {balance: 600}], loans: [{outstanding: 1000}]}}, + {customer: {accounts: [{balance: 500}, {balance: 600}], loans: [{outstanding: 1000}], assets: 1100, debt: 1000, creditworthy: true}}, + ], + [ + {customer: {accounts: [{balance: 5000}, {balance: -1}], loans: [{outstanding: 1}]}}, + {customer: {accounts: [{balance: 5000}, {balance: -1}], loans: [{outstanding: 1}], assets: 4999, debt: 1, creditworthy: false}}, + ], + [ + {customer: {accounts: [], loans: [{outstanding: 0.01}]}}, + {customer: {accounts: [], loans: [{outstanding: 0.01}], assets: 0, debt: 0.01, creditworthy: false}}, + ], + ], +} + +{ + name: "aggregate over a filtered and mapped member list", + policy: { + models: {cart: {items: "item[]"}, item: {category: "string", price: "number", qty: "number"}}, + blocks: [{assertion: "cart.freeShipping", conditions: [ + ["or", "sum(map(filter(cart.items, #.category != 'gift card'), #.price * #.qty)) >= 50"], + "some(cart.items, #.category == 'furniture')", + ]}], + }, + cases: [ + [{cart: {items: [{category: "book", price: 20, qty: 3}]}}, {cart: {items: [{category: "book", price: 20, qty: 3}], freeShipping: true}}], + [{cart: {items: [{category: "gift card", price: 100, qty: 1}, {category: "book", price: 5, qty: 1}]}}, {cart: {items: [{category: "gift card", price: 100, qty: 1}, {category: "book", price: 5, qty: 1}], freeShipping: false}}], + [{cart: {items: [{category: "furniture", price: 1, qty: 1}]}}, {cart: {items: [{category: "furniture", price: 1, qty: 1}], freeShipping: true}}], + [{cart: {items: []}}, {cart: {items: [], freeShipping: false}}], + ], +} + +// --------------------------------------------------------------------------- +// Assertions on relationship members. +// --------------------------------------------------------------------------- +{ + name: "per-member assertion with a depth-2 group", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", employees: "number", public: "boolean"}}, + blocks: [{assertion: "company.eligible", conditions: [ + ["and", "company.revenue > 0"], + ["or", "company.public", 1], + ["and", "company.employees >= 10", 2], + ["and", "company.revenue >= 1000000", 2], + ]}], + }, + cases: [ + [ + {customer: {companies: [ + {revenue: 1, employees: 0, public: true}, + {revenue: 1000000, employees: 10, public: false}, + {revenue: 999999, employees: 50, public: false}, + {revenue: 0, employees: 50, public: true}, + ]}}, + {customer: {companies: [ + {revenue: 1, employees: 0, public: true, eligible: true}, + {revenue: 1000000, employees: 10, public: false, eligible: true}, + {revenue: 999999, employees: 50, public: false, eligible: false}, + {revenue: 0, employees: 50, public: true, eligible: false}, + ]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +{ + name: "per-member assertion reads a parent input and a parent computed", + policy: { + models: {customer: {country: "string", companies: "company[]"}, company: {country: "string", revenue: "number"}}, + blocks: [ + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}, + {assertion: "company.material", conditions: [ + ["or", "company.country != customer.country"], + "company.revenue * 4 >= customer.total", + ]}, + ], + }, + cases: [ + [ + {customer: {country: "DE", companies: [{country: "DE", revenue: 10}, {country: "FR", revenue: 10}, {country: "DE", revenue: 80}]}}, + {customer: {country: "DE", total: 100, companies: [ + {country: "DE", revenue: 10, material: false}, + {country: "FR", revenue: 10, material: true}, + {country: "DE", revenue: 80, material: true}, + ]}}, + ], + [ + {customer: {country: "DE", companies: [{country: "DE", revenue: 0}]}}, + {customer: {country: "DE", total: 0, companies: [{country: "DE", revenue: 0, material: true}]}}, + ], + ], +} + +{ + name: "per-member assertion through the member's single relationship", + policy: { + models: {customer: {companies: "company[]"}, company: {address: "address"}, address: {country: "string", verified: "boolean"}}, + blocks: [{assertion: "company.addressOk", conditions: [["and", "company.address.verified"], "company.address.country != 'XX'"]}], + }, + cases: [ + [ + {customer: {companies: [{address: {country: "DE", verified: true}}, {address: {country: "XX", verified: true}}, {address: {country: "DE", verified: false}}]}}, + {customer: {companies: [ + {address: {country: "DE", verified: true}, addressOk: true}, + {address: {country: "XX", verified: true}, addressOk: false}, + {address: {country: "DE", verified: false}, addressOk: false}, + ]}}, + ], + ], +} + +{ + name: "per-member assertions chained, then counted by the parent", + policy: { + models: {order: {lines: "line[]"}, line: {qty: "number", price: "number", stock: "number"}}, + blocks: [ + {assertion: "line.inStock", conditions: ["line.stock >= line.qty"]}, + {assertion: "line.valid", conditions: [["and", "line.inStock"], ["and", "line.qty > 0"], "line.price >= 0"]}, + {assertion: "order.shippable", conditions: [["and", "len(order.lines) > 0"], "all(order.lines, #.valid)"]}, + {expression: "order.invalidCount", value: "count(order.lines, not #.valid)"}, + ], + }, + cases: [ + [ + {order: {lines: [{qty: 1, price: 5, stock: 1}, {qty: 2, price: 0, stock: 10}]}}, + {order: {shippable: true, invalidCount: 0, lines: [{qty: 1, price: 5, stock: 1, inStock: true, valid: true}, {qty: 2, price: 0, stock: 10, inStock: true, valid: true}]}}, + ], + [ + {order: {lines: [{qty: 3, price: 5, stock: 2}, {qty: 0, price: 1, stock: 5}, {qty: 1, price: -1, stock: 5}]}}, + {order: {shippable: false, invalidCount: 3, lines: [ + {qty: 3, price: 5, stock: 2, inStock: false, valid: false}, + {qty: 0, price: 1, stock: 5, inStock: true, valid: false}, + {qty: 1, price: -1, stock: 5, inStock: true, valid: false}, + ]}}, + ], + [{order: {lines: []}}, {order: {shippable: false, invalidCount: 0, lines: []}}], + ], +} + +{ + name: "per-member assertion writes a nested path", + policy: { + models: {team: {members: "member[]"}, member: {age: "number", certified: "boolean"}}, + blocks: [ + {assertion: "member.checks.adult", conditions: ["member.age >= 18"]}, + {assertion: "member.checks.canLead", conditions: [["and", "member.checks.adult"], "member.certified"]}, + ], + }, + cases: [ + [ + {team: {members: [{age: 30, certified: true}, {age: 16, certified: true}, {age: 40, certified: false}]}}, + {team: {members: [ + {age: 30, certified: true, checks: {adult: true, canLead: true}}, + {age: 16, certified: true, checks: {adult: false, canLead: false}}, + {age: 40, certified: false, checks: {adult: true, canLead: false}}, + ]}}, + ], + ], +} + +{ + name: "per-member assertion on an optional member field", + policy: { + models: {team: {members: "member[]"}, member: {score: "number?"}}, + blocks: [{assertion: "member.passed", conditions: [["and", "member.score != null"], "(member.score ?? 0) >= 50"]}], + }, + cases: [ + [ + {team: {members: [{score: 50}, {score: 49}, {score: null}, {}]}}, + {team: {members: [{score: 50, passed: true}, {score: 49, passed: false}, {score: null, passed: false}, {passed: false}]}}, + ], + ], +} + +{ + name: "a per-member condition failing on one member fails the evaluation", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {team: {members: "member[]"}, member: {score: "number?"}}, + blocks: [{assertion: "member.passed", conditions: ["member.score >= 50"]}], + }, + cases: [ + [{team: {members: [{score: 70}, {score: 1}]}}, {team: {members: [{score: 70, passed: true}, {score: 1, passed: false}]}}], + [{team: {members: [{score: 70}, {score: null}]}}, "!error: ExpressionFailed"], + [{team: {members: [{}]}}, "!error: ExpressionFailed"], + [{team: {members: []}}, {team: {members: []}}], + ], +} + +{ + name: "goal on a parent assertion runs the member assertions it aggregates", + policy: { + models: {team: {members: "member[]"}, member: {age: "number"}}, + blocks: [ + {assertion: "member.adult", conditions: ["member.age >= 18"]}, + {assertion: "member.senior", conditions: ["member.age >= 65"]}, + {assertion: "team.allAdults", conditions: ["all(team.members, #.adult)"]}, + ], + }, + cases: [ + {input: {team: {members: [{age: 20}, {age: 70}]}}, goals: ["team.allAdults"], output: {team: {allAdults: true, members: [{age: 20, adult: true}, {age: 70, adult: true}]}}}, + {input: {team: {members: [{age: 10}]}}, goals: ["team.allAdults"], output: {team: {allAdults: false, members: [{age: 10, adult: false}]}}}, + {input: {team: {members: [{age: 10}]}}, output: {team: {allAdults: false, members: [{age: 10, adult: false, senior: false}]}}}, + ], +} + +// --------------------------------------------------------------------------- +// A realistic grouped rule set. +// --------------------------------------------------------------------------- +{ + name: "KYC: verified and ((resident and adult) or (business and (registered or listed)))", + policy: { + models: {party: {verified: "boolean", type: "string(person|business)", resident: "boolean", age: "number", registered: "boolean", listed: "boolean"}}, + blocks: [{assertion: "party.accepted", conditions: [ + ["and", "party.verified"], + ["and", "party.type == 'person'", 1], + ["and", "party.resident", 1], + ["or", "party.age >= 18", 1], + ["and", "party.type == 'business'", 2], + ["or", "party.registered", 3], + ["or", "party.listed", 3], + ]}], + }, + cases: [ + [{party: {verified: true, type: "person", resident: true, age: 30, registered: false, listed: false}}, {party: {verified: true, type: "person", resident: true, age: 30, registered: false, listed: false, accepted: true}}], + [{party: {verified: true, type: "person", resident: false, age: 30, registered: true, listed: true}}, {party: {verified: true, type: "person", resident: false, age: 30, registered: true, listed: true, accepted: false}}], + [{party: {verified: true, type: "business", resident: false, age: 0, registered: true, listed: false}}, {party: {verified: true, type: "business", resident: false, age: 0, registered: true, listed: false, accepted: true}}], + [{party: {verified: true, type: "business", resident: true, age: 50, registered: false, listed: false}}, {party: {verified: true, type: "business", resident: true, age: 50, registered: false, listed: false, accepted: false}}], + [{party: {verified: false, type: "person", resident: true, age: 30, registered: true, listed: true}}, {party: {verified: false, type: "person", resident: true, age: 30, registered: true, listed: true, accepted: false}}], + ], +} diff --git a/core/engine/tests/spec/policy/20-tables-advanced.json5 b/core/engine/tests/spec/policy/20-tables-advanced.json5 new file mode 100644 index 00000000..fac515fc --- /dev/null +++ b/core/engine/tests/spec/policy/20-tables-advanced.json5 @@ -0,0 +1,794 @@ +// Decision table blocks in larger policies: many rules and outputs, outputs spread over +// several paths and entities, tables evaluated per relationship member, tables whose inputs +// are computed by other blocks, and tables mixing collecting (`[]`) and first-hit columns. +// Chapters 07 and 08 cover the single-table basics. + +// --------------------------------------------------------------------------- +// Many rules and many outputs. +// --------------------------------------------------------------------------- +{ + name: "income tax brackets: ten rules, three outputs, computed cells", + policy: { + models: {person: {income: "number"}}, + blocks: [{table: "brackets", inputs: ["person.income"], outputs: ["person.bracket", "person.rate", "person.tax"], rules: [ + ["< 0", "0", "0", "0"], + ["[0..10000]", "1", "0", "0"], + ["(10000..20000]", "2", "0.1", "(person.income - 10000) * 0.1"], + ["(20000..40000]", "3", "0.15", "1000 + (person.income - 20000) * 0.15"], + ["(40000..60000]", "4", "0.2", "4000 + (person.income - 40000) * 0.2"], + ["(60000..80000]", "5", "0.25", "8000 + (person.income - 60000) * 0.25"], + ["(80000..100000]", "6", "0.3", "13000 + (person.income - 80000) * 0.3"], + ["(100000..150000]", "7", "0.35", "19000 + (person.income - 100000) * 0.35"], + ["(150000..250000]", "8", "0.4", "36500 + (person.income - 150000) * 0.4"], + ["", "9", "0.45", "76500 + (person.income - 250000) * 0.45"], + ]}], + }, + cases: [ + [{person: {income: -1}}, {person: {income: -1, bracket: 0, rate: 0, tax: 0}}], + [{person: {income: 0}}, {person: {income: 0, bracket: 1, rate: 0, tax: 0}}], + [{person: {income: 10000}}, {person: {income: 10000, bracket: 1, rate: 0, tax: 0}}], + [{person: {income: 10000.01}}, {person: {income: 10000.01, bracket: 2, rate: 0.1, tax: 0.001}}], + [{person: {income: 20000}}, {person: {income: 20000, bracket: 2, rate: 0.1, tax: 1000}}], + [{person: {income: 30000}}, {person: {income: 30000, bracket: 3, rate: 0.15, tax: 2500}}], + [{person: {income: 60000}}, {person: {income: 60000, bracket: 4, rate: 0.2, tax: 8000}}], + [{person: {income: 70000}}, {person: {income: 70000, bracket: 5, rate: 0.25, tax: 10500}}], + [{person: {income: 100000}}, {person: {income: 100000, bracket: 6, rate: 0.3, tax: 19000}}], + [{person: {income: 120000}}, {person: {income: 120000, bracket: 7, rate: 0.35, tax: 26000}}], + [{person: {income: 250000}}, {person: {income: 250000, bracket: 8, rate: 0.4, tax: 76500}}], + [{person: {income: 1000000}}, {person: {income: 1000000, bracket: 9, rate: 0.45, tax: 414000}}], + ], +} + +{ + name: "shipping matrix: three inputs, twelve rules, four outputs", + policy: { + models: {parcel: {zone: "string(domestic|eu|world)", weight: "number", service: "string(standard|express)"}}, + blocks: [{table: "shipping", inputs: ["parcel.zone", "parcel.service", "parcel.weight"], outputs: ["parcel.carrier", "parcel.price", "parcel.days", "parcel.tracked"], rules: [ + ["'domestic'", "'standard'", "<= 2", "'post'", "4.5", "3", "false"], + ["'domestic'", "'standard'", "<= 20", "'post'", "7.9", "3", "true"], + ["'domestic'", "'express'", "<= 20", "'courier'", "14.9", "1", "true"], + ["'domestic'", "", "", "'freight'", "parcel.weight * 1.1", "5", "true"], + ["'eu'", "'standard'", "<= 2", "'post'", "9.5", "6", "false"], + ["'eu'", "'standard'", "<= 20", "'post'", "16", "6", "true"], + ["'eu'", "'express'", "<= 20", "'courier'", "34", "2", "true"], + ["'eu'", "", "", "'freight'", "parcel.weight * 2.5", "8", "true"], + ["'world'", "'standard'", "<= 2", "'post'", "15", "14", "false"], + ["'world'", "'standard'", "<= 20", "'post'", "45", "14", "true"], + ["'world'", "'express'", "<= 20", "'courier'", "89", "4", "true"], + ["'world'", "", "", "'freight'", "parcel.weight * 6", "21", "true"], + ]}], + }, + cases: [ + [{parcel: {zone: "domestic", service: "standard", weight: 2}}, {parcel: {zone: "domestic", service: "standard", weight: 2, carrier: "post", price: 4.5, days: 3, tracked: false}}], + [{parcel: {zone: "domestic", service: "standard", weight: 2.01}}, {parcel: {zone: "domestic", service: "standard", weight: 2.01, carrier: "post", price: 7.9, days: 3, tracked: true}}], + [{parcel: {zone: "domestic", service: "express", weight: 1}}, {parcel: {zone: "domestic", service: "express", weight: 1, carrier: "courier", price: 14.9, days: 1, tracked: true}}], + [{parcel: {zone: "domestic", service: "express", weight: 30}}, {parcel: {zone: "domestic", service: "express", weight: 30, carrier: "freight", price: 33, days: 5, tracked: true}}], + [{parcel: {zone: "eu", service: "standard", weight: 0.1}}, {parcel: {zone: "eu", service: "standard", weight: 0.1, carrier: "post", price: 9.5, days: 6, tracked: false}}], + [{parcel: {zone: "eu", service: "express", weight: 20}}, {parcel: {zone: "eu", service: "express", weight: 20, carrier: "courier", price: 34, days: 2, tracked: true}}], + [{parcel: {zone: "eu", service: "standard", weight: 100}}, {parcel: {zone: "eu", service: "standard", weight: 100, carrier: "freight", price: 250, days: 8, tracked: true}}], + [{parcel: {zone: "world", service: "standard", weight: 5}}, {parcel: {zone: "world", service: "standard", weight: 5, carrier: "post", price: 45, days: 14, tracked: true}}], + [{parcel: {zone: "world", service: "express", weight: 21}}, {parcel: {zone: "world", service: "express", weight: 21, carrier: "freight", price: 126, days: 21, tracked: true}}], + [{parcel: {zone: "mars", service: "express", weight: 1}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "sparse first-hit table: each of five outputs resolves from a different row", + policy: { + models: {app: {score: "number", country: "string", age: "number"}}, + blocks: [{table: "t", inputs: ["app.score", "app.country", "app.age"], outputs: ["app.decision", "app.reason", "app.limit", "app.rate", "app.reviewer"], rules: [ + ["< 300", "", "", "'decline'", "'score'", "", "", ""], + ["", "'XX'", "", "'decline'", "'country'", "", "", ""], + ["", "", "< 21", "", "'young'", "500", "", "'junior desk'"], + [">= 750", "", "", "'approve'", "", "20000", "0.05", ""], + [">= 600", "", "", "'approve'", "", "5000", "0.09", ""], + ["", "", "", "'refer'", "'default'", "1000", "0.15", "'credit desk'"], + ]}], + }, + cases: [ + [{app: {score: 800, country: "DE", age: 40}}, {app: {score: 800, country: "DE", age: 40, decision: "approve", reason: "default", limit: 20000, rate: 0.05, reviewer: "credit desk"}}], + [{app: {score: 800, country: "DE", age: 19}}, {app: {score: 800, country: "DE", age: 19, decision: "approve", reason: "young", limit: 500, rate: 0.05, reviewer: "junior desk"}}], + [{app: {score: 650, country: "XX", age: 19}}, {app: {score: 650, country: "XX", age: 19, decision: "decline", reason: "country", limit: 500, rate: 0.09, reviewer: "junior desk"}}], + [{app: {score: 100, country: "XX", age: 50}}, {app: {score: 100, country: "XX", age: 50, decision: "decline", reason: "score", limit: 1000, rate: 0.15, reviewer: "credit desk"}}], + [{app: {score: 500, country: "DE", age: 50}}, {app: {score: 500, country: "DE", age: 50, decision: "refer", reason: "default", limit: 1000, rate: 0.15, reviewer: "credit desk"}}], + ], +} + +{ + name: "collect table with ten rules builds an array of objects, aggregated downstream", + policy: { + models: {claim: {amount: "number", type: "string", daysToReport: "number", priorClaims: "number", witness: "boolean"}}, + blocks: [ + {table: "signals", hit: "collect", inputs: ["claim.amount", "claim.type", "claim.daysToReport", "claim.priorClaims", "claim.witness"], outputs: ["claim.signals"], rules: [ + ["> 50000", "", "", "", "", "{code: 'HIGH_AMOUNT', w: 30}"], + ["> 10000", "", "", "", "", "{code: 'MID_AMOUNT', w: 10}"], + ["", "'theft'", "", "", "", "{code: 'THEFT', w: 15}"], + ["", "'theft'", "", "", "false", "{code: 'THEFT_NO_WITNESS', w: 20}"], + ["", "", "> 30", "", "", "{code: 'LATE', w: 25}"], + ["", "", "> 7", "", "", "{code: 'DELAYED', w: 5}"], + ["", "", "", ">= 3", "", "{code: 'FREQUENT', w: 30}"], + ["", "", "", "[1..2]", "", "{code: 'REPEAT', w: 10}"], + ["", "'fire'", "", "> 0", "", "{code: 'REPEAT_FIRE', w: 40}"], + ["< 100", "", "", "", "", "{code: 'SMALL', w: -5}"], + ]}, + {expression: "claim.score", value: "sum(map(claim.signals, #.w))"}, + {expression: "claim.codes", value: "map(claim.signals, #.code)"}, + ], + }, + cases: [ + [ + {claim: {amount: 60000, type: "theft", daysToReport: 40, priorClaims: 3, witness: false}}, + {claim: {amount: 60000, type: "theft", daysToReport: 40, priorClaims: 3, witness: false, + signals: [{code: "HIGH_AMOUNT", w: 30}, {code: "MID_AMOUNT", w: 10}, {code: "THEFT", w: 15}, {code: "THEFT_NO_WITNESS", w: 20}, {code: "LATE", w: 25}, {code: "DELAYED", w: 5}, {code: "FREQUENT", w: 30}], + score: 135, codes: ["HIGH_AMOUNT", "MID_AMOUNT", "THEFT", "THEFT_NO_WITNESS", "LATE", "DELAYED", "FREQUENT"]}}, + ], + [ + {claim: {amount: 50, type: "fire", daysToReport: 1, priorClaims: 1, witness: true}}, + {claim: {amount: 50, type: "fire", daysToReport: 1, priorClaims: 1, witness: true, + signals: [{code: "REPEAT", w: 10}, {code: "REPEAT_FIRE", w: 40}, {code: "SMALL", w: -5}], + score: 45, codes: ["REPEAT", "REPEAT_FIRE", "SMALL"]}}, + ], + [ + {claim: {amount: 500, type: "water", daysToReport: 0, priorClaims: 0, witness: true}}, + {claim: {amount: 500, type: "water", daysToReport: 0, priorClaims: 0, witness: true, signals: [], score: 0, codes: []}}, + ], + ], +} + +// --------------------------------------------------------------------------- +// Outputs over several paths of one entity, and over several entities. +// --------------------------------------------------------------------------- +{ + name: "outputs to several nested paths of one entity", + policy: { + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.pricing.discount", "order.pricing.fees.handling", "order.shipping.method", "order.flags.large"], rules: [ + [">= 1000", "0.1", "0", "'freight'", "true"], + [">= 100", "0.05", "2.5", "'parcel'", "false"], + ["", "0", "5", "'letter'", "false"], + ]}], + }, + cases: [ + [{order: {amount: 1000}}, {order: {amount: 1000, pricing: {discount: 0.1, fees: {handling: 0}}, shipping: {method: "freight"}, flags: {large: true}}}], + [{order: {amount: 150}}, {order: {amount: 150, pricing: {discount: 0.05, fees: {handling: 2.5}}, shipping: {method: "parcel"}, flags: {large: false}}}], + [{order: {amount: 1}}, {order: {amount: 1, pricing: {discount: 0, fees: {handling: 5}}, shipping: {method: "letter"}, flags: {large: false}}}], + ], +} + +{ + name: "outputs into an input object of the entity merge with its fields", + policy: { + models: {order: {amount: "number", meta: "string?"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.extra.band", "order.extra.code"], rules: [ + ["> 10", "'high'", "1"], + ["", "'low'", "2"], + ]}], + }, + cases: [ + [{order: {amount: 20, extra: {keep: true}}}, {order: {amount: 20, extra: {keep: true, band: "high", code: 1}}}], + [{order: {amount: 1, extra: {band: "old"}}}, {order: {amount: 1, extra: {band: "low", code: 2}}}], + [{order: {amount: 1}}, {order: {amount: 1, extra: {band: "low", code: 2}}}], + ], +} + +{ + name: "outputs to two root entities are a mixed-scope error but still evaluate in the workspace", + diagnostics: ["MIXED_SCOPE"], + policy: { + models: {customer: {age: "number"}, account: {balance: "number"}}, + blocks: [{table: "t", inputs: ["customer.age", "account.balance"], outputs: ["customer.segment", "account.limit"], rules: [ + ["< 25", "", "'youth'", "500"], + ["", "> 10000", "'wealthy'", "account.balance * 0.5"], + ["", "", "'standard'", "2000"], + ]}], + }, + cases: [ + [{customer: {age: 20}, account: {balance: 50000}}, {customer: {age: 20, segment: "youth"}, account: {balance: 50000, limit: 500}}], + [{customer: {age: 40}, account: {balance: 50000}}, {customer: {age: 40, segment: "wealthy"}, account: {balance: 50000, limit: 25000}}], + [{customer: {age: 40}, account: {balance: 100}}, {customer: {age: 40, segment: "standard"}, account: {balance: 100, limit: 2000}}], + ], +} + +{ + name: "outputs to an entity and to a global are a mixed-scope error", + diagnostics: ["MIXED_SCOPE"], + policy: { + globals: {run: {mode: "string?"}}, + models: {order: {amount: "number"}}, + blocks: [{table: "t", inputs: ["order.amount"], outputs: ["order.band", "auditLevel"], rules: [ + ["> 100", "'high'", "2"], + ["", "'low'", "1"], + ]}], + }, + cases: [ + [{order: {amount: 101}}, {order: {amount: 101, band: "high"}, auditLevel: 2}], + [{order: {amount: 100}}, {order: {amount: 100, band: "low"}, auditLevel: 1}], + ], +} + +{ + name: "the single-entity alternative: one table per entity", + policy: { + models: {customer: {age: "number"}, account: {balance: "number"}}, + blocks: [ + {table: "segment", inputs: ["customer.age"], outputs: ["customer.segment"], rules: [["< 25", "'youth'"], ["", "'standard'"]]}, + {table: "limit", inputs: ["customer.segment", "account.balance"], outputs: ["account.limit"], rules: [ + ["'youth'", "", "500"], + ["", "> 10000", "account.balance * 0.5"], + ["", "", "2000"], + ]}, + ], + }, + cases: [ + [{customer: {age: 20}, account: {balance: 50000}}, {customer: {age: 20, segment: "youth"}, account: {balance: 50000, limit: 500}}], + [{customer: {age: 40}, account: {balance: 50000}}, {customer: {age: 40, segment: "standard"}, account: {balance: 50000, limit: 25000}}], + [{customer: {age: 40}, account: {balance: 100}}, {customer: {age: 40, segment: "standard"}, account: {balance: 100, limit: 2000}}], + ], +} + +{ + name: "outputs to a parent property and into its single relationship", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + models: {customer: {report: "creditReport"}, creditReport: {score: "number"}}, + blocks: [{table: "t", inputs: ["customer.report.score"], outputs: ["customer.grade", "customer.report.band"], rules: [ + [">= 700", "'A'", "'prime'"], + ["", "'B'", "'subprime'"], + ]}], + }, + cases: [ + [{customer: {report: {score: 750}}}, {customer: {grade: "A", report: {score: 750, band: "prime"}}}, "question: the table writes the new property `band` under the declared single relationship `customer.report`; the analyzer reports INPUT_OVERRIDE (so DecisionEngine refuses the policy), although `report.band` is not declared and the same write keyed as `creditReport.band` is accepted. The workspace path writes it"], + [{customer: {report: {score: 600}}}, {customer: {grade: "B", report: {score: 600, band: "subprime"}}}], + ], +} + +// --------------------------------------------------------------------------- +// Tables evaluated per relationship member. +// --------------------------------------------------------------------------- +{ + name: "per-member table reads member fields and a parent input, several outputs", + policy: { + models: {customer: {currency: "string", accounts: "account[]"}, account: {balance: "number", currency: "string"}}, + blocks: [{table: "t", inputs: ["account.currency", "account.balance"], outputs: ["account.fx", "account.status"], rules: [ + ["customer.currency", "< 0", "false", "'overdrawn'"], + ["customer.currency", "", "false", "'ok'"], + ["", "< 0", "true", "'overdrawn fx'"], + ["", "", "true", "'fx'"], + ]}], + }, + cases: [ + [ + {customer: {currency: "EUR", accounts: [{balance: -5, currency: "EUR"}, {balance: 5, currency: "EUR"}, {balance: -1, currency: "USD"}, {balance: 0, currency: "GBP"}]}}, + {customer: {currency: "EUR", accounts: [ + {balance: -5, currency: "EUR", fx: false, status: "overdrawn"}, + {balance: 5, currency: "EUR", fx: false, status: "ok"}, + {balance: -1, currency: "USD", fx: true, status: "overdrawn fx"}, + {balance: 0, currency: "GBP", fx: true, status: "fx"}, + ]}}, + ], + [ + {customer: {currency: "USD", accounts: [{balance: 1, currency: "EUR"}]}}, + {customer: {currency: "USD", accounts: [{balance: 1, currency: "EUR", fx: true, status: "fx"}]}}, + ], + [{customer: {currency: "USD", accounts: []}}, {customer: {currency: "USD", accounts: []}}], + ], +} + +{ + name: "per-member table input reads a parent aggregate", + policy: { + models: {team: {players: "player[]"}, player: {points: "number"}}, + blocks: [ + {expression: "team.best", value: "max(map(team.players, #.points))"}, + {table: "t", inputs: ["player.points / team.best"], outputs: ["player.tier"], rules: [ + ["1", "'star'"], + [">= 0.5", "'core'"], + ["", "'bench'"], + ]}, + ], + }, + cases: [ + [ + {team: {players: [{points: 40}, {points: 20}, {points: 19}]}}, + {team: {best: 40, players: [{points: 40, tier: "star"}, {points: 20, tier: "core"}, {points: 19, tier: "bench"}]}}, + ], + [ + {team: {players: [{points: 3}, {points: 3}]}}, + {team: {best: 3, players: [{points: 3, tier: "star"}, {points: 3, tier: "star"}]}}, + ], + ], +} + +{ + name: "per-member fieldless column reads the parent", + policy: { + models: {customer: {vip: "boolean", orders: "order[]"}, order: {amount: "number"}}, + blocks: [{table: "t", inputs: [null, "order.amount"], outputs: ["order.shipping"], rules: [ + ["customer.vip", "", "0"], + ["", ">= 50", "0"], + ["", "", "4.95"], + ]}], + }, + cases: [ + [ + {customer: {vip: true, orders: [{amount: 1}, {amount: 100}]}}, + {customer: {vip: true, orders: [{amount: 1, shipping: 0}, {amount: 100, shipping: 0}]}}, + ], + [ + {customer: {vip: false, orders: [{amount: 1}, {amount: 50}]}}, + {customer: {vip: false, orders: [{amount: 1, shipping: 4.95}, {amount: 50, shipping: 0}]}}, + ], + ], +} + +{ + name: "per-member table through the member's single relationship", + policy: { + models: {customer: {companies: "company[]"}, company: {address: "address"}, address: {country: "string"}}, + blocks: [{table: "t", inputs: ["company.address.country"], outputs: ["company.vatRate", "company.region"], rules: [ + ["'DE'", "0.19", "'EU'"], + ["'FR'", "0.2", "'EU'"], + ["'GB'", "0.2", "'UK'"], + ["", "0", "'ROW'"], + ]}], + }, + cases: [ + [ + {customer: {companies: [{address: {country: "DE"}}, {address: {country: "GB"}}, {address: {country: "US"}}]}}, + {customer: {companies: [ + {address: {country: "DE"}, vatRate: 0.19, region: "EU"}, + {address: {country: "GB"}, vatRate: 0.2, region: "UK"}, + {address: {country: "US"}, vatRate: 0, region: "ROW"}, + ]}}, + ], + ], +} + +{ + name: "per-member table on an optional member field with a null rule", + policy: { + models: {team: {members: "member[]"}, member: {grade: "string?"}}, + blocks: [{table: "t", inputs: ["member.grade"], outputs: ["member.bonus"], rules: [ + ["null", "0"], + ["'A'", "1000"], + ["'B', 'C'", "500"], + ["", "100"], + ]}], + }, + cases: [ + [ + {team: {members: [{grade: "A"}, {grade: null}, {}, {grade: "C"}, {grade: "Z"}]}}, + {team: {members: [{grade: "A", bonus: 1000}, {grade: null, bonus: 0}, {bonus: 0}, {grade: "C", bonus: 500}, {grade: "Z", bonus: 100}]}}, + ], + ], +} + +{ + name: "two per-member tables chained, then a parent table over their results", + policy: { + models: {portfolio: {holdings: "holding[]"}, holding: {asset: "string", value: "number"}}, + blocks: [ + {table: "class", inputs: ["holding.asset"], outputs: ["holding.class"], rules: [ + ["'BTC', 'ETH'", "'crypto'"], + ["'BND'", "'bond'"], + ["", "'equity'"], + ]}, + {table: "risk", inputs: ["holding.class", "holding.value"], outputs: ["holding.risk"], rules: [ + ["'crypto'", "", "3"], + ["'equity'", "> 10000", "2"], + ["'equity'", "", "1.5"], + ["", "", "1"], + ]}, + {table: "profile", inputs: ["sum(map(portfolio.holdings, #.risk * #.value)) / sum(map(portfolio.holdings, #.value))"], outputs: ["portfolio.profile"], rules: [ + [">= 2.5", "'aggressive'"], + [">= 1.5", "'balanced'"], + ["", "'conservative'"], + ]}, + ], + }, + cases: [ + [ + {portfolio: {holdings: [{asset: "BTC", value: 100}, {asset: "AAPL", value: 100}]}}, + {portfolio: {profile: "balanced", holdings: [{asset: "BTC", value: 100, class: "crypto", risk: 3}, {asset: "AAPL", value: 100, class: "equity", risk: 1.5}]}}, + ], + [ + {portfolio: {holdings: [{asset: "BND", value: 900}, {asset: "MSFT", value: 100}]}}, + {portfolio: {profile: "conservative", holdings: [{asset: "BND", value: 900, class: "bond", risk: 1}, {asset: "MSFT", value: 100, class: "equity", risk: 1.5}]}}, + ], + [ + {portfolio: {holdings: [{asset: "ETH", value: 10}]}}, + {portfolio: {profile: "aggressive", holdings: [{asset: "ETH", value: 10, class: "crypto", risk: 3}]}}, + ], + ], +} + +{ + name: "per-member mixed collect table, flattened by the parent", + policy: { + models: {shipment: {packages: "package[]"}, package: {weight: "number", fragile: "boolean", hazmat: "boolean"}}, + blocks: [ + {table: "t", inputs: ["package.weight", "package.fragile", "package.hazmat"], outputs: ["package.labels[]", "package.handling"], rules: [ + ["> 30", "", "", "'HEAVY'", "'forklift'"], + ["", "true", "", "'FRAGILE'", "'manual'"], + ["", "", "true", "'HAZMAT'", "'certified'"], + ["", "", "", "", "'standard'"], + ]}, + {expression: "shipment.labels", value: "flatten(map(shipment.packages, #.labels))"}, + {expression: "shipment.manualCount", value: "count(shipment.packages, #.handling != 'standard')"}, + ], + }, + cases: [ + [ + {shipment: {packages: [{weight: 40, fragile: true, hazmat: false}, {weight: 1, fragile: false, hazmat: true}, {weight: 1, fragile: false, hazmat: false}]}}, + {shipment: {labels: ["HEAVY", "FRAGILE", "HAZMAT"], manualCount: 2, packages: [ + {weight: 40, fragile: true, hazmat: false, labels: ["HEAVY", "FRAGILE"], handling: "forklift"}, + {weight: 1, fragile: false, hazmat: true, labels: ["HAZMAT"], handling: "certified"}, + {weight: 1, fragile: false, hazmat: false, labels: [], handling: "standard"}, + ]}}, + ], + [{shipment: {packages: []}}, {shipment: {labels: [], manualCount: 0, packages: []}}], + ], +} + +// --------------------------------------------------------------------------- +// Tables reading computed inputs. +// --------------------------------------------------------------------------- +{ + name: "every input column is computed by a different block kind", + policy: { + models: {order: {amount: "number", qty: "number", country: "string"}}, + blocks: [ + {table: "decision", inputs: ["order.total", "order.region", "order.trusted", "order.band"], outputs: ["order.action"], rules: [ + ["", "", "false", "", "'hold'"], + ["> 1000", "'eu'", "", "'A'", "'fast track'"], + ["> 1000", "", "", "", "'review'"], + ["", "", "", "", "'auto'"], + ]}, + {expression: "order.total", value: "order.amount * order.qty"}, + {match: "order.region", arms: [["order.country in ['DE', 'FR']", "'eu'"], ["", "'other'"]]}, + {assertion: "order.trusted", conditions: [["and", "order.country != 'XX'"], "order.qty < 1000"]}, + {table: "band", inputs: ["order.amount"], outputs: ["order.band"], rules: [[">= 100", "'A'"], ["", "'B'"]]}, + ], + }, + cases: [ + [{order: {amount: 100, qty: 20, country: "DE"}}, {order: {amount: 100, qty: 20, country: "DE", total: 2000, region: "eu", trusted: true, band: "A", action: "fast track"}}], + [{order: {amount: 50, qty: 30, country: "DE"}}, {order: {amount: 50, qty: 30, country: "DE", total: 1500, region: "eu", trusted: true, band: "B", action: "review"}}], + [{order: {amount: 100, qty: 20, country: "US"}}, {order: {amount: 100, qty: 20, country: "US", total: 2000, region: "other", trusted: true, band: "A", action: "review"}}], + [{order: {amount: 1, qty: 1, country: "XX"}}, {order: {amount: 1, qty: 1, country: "XX", total: 1, region: "other", trusted: false, band: "B", action: "hold"}}], + [{order: {amount: 1, qty: 1, country: "FR"}}, {order: {amount: 1, qty: 1, country: "FR", total: 1, region: "eu", trusted: true, band: "B", action: "auto"}}], + ], +} + +{ + name: "input field combines several computed values", + policy: { + models: {invoice: {net: "number", paid: "number"}}, + blocks: [ + {expression: "invoice.gross", value: "invoice.net * 1.2"}, + {expression: "invoice.credit", value: "invoice.paid > invoice.net * 1.2 ? invoice.paid - invoice.net * 1.2 : 0"}, + {table: "t", inputs: ["invoice.gross - invoice.paid + invoice.credit"], outputs: ["invoice.state"], rules: [ + ["0", "'settled'"], + ["< 0", "'impossible'"], + ["<= 1", "'rounding'"], + ["", "'open'"], + ]}, + ], + }, + cases: [ + [{invoice: {net: 100, paid: 120}}, {invoice: {net: 100, paid: 120, gross: 120, credit: 0, state: "settled"}}], + [{invoice: {net: 100, paid: 150}}, {invoice: {net: 100, paid: 150, gross: 120, credit: 30, state: "settled"}}], + [{invoice: {net: 100, paid: 119.5}}, {invoice: {net: 100, paid: 119.5, gross: 120, credit: 0, state: "rounding"}}], + [{invoice: {net: 100, paid: 0}}, {invoice: {net: 100, paid: 0, gross: 120, credit: 0, state: "open"}}], + ], +} + +{ + name: "fieldless columns over a collected array", + policy: { + models: {user: {age: "number", country: "string"}}, + blocks: [ + {table: "flags", inputs: ["user.age", "user.country"], outputs: ["user.flags[]"], rules: [ + ["< 18", "", "'minor'"], + ["", "'XX'", "'sanctioned'"], + ["> 100", "", "'age check'"], + ]}, + {table: "route", inputs: [null, "len(user.flags)"], outputs: ["user.route"], rules: [ + ["'sanctioned' in user.flags", "", "'block'"], + ["", ">= 2", "'manual'"], + ["", "1", "'light'"], + ["", "", "'auto'"], + ]}, + ], + }, + cases: [ + [{user: {age: 30, country: "DE"}}, {user: {age: 30, country: "DE", flags: [], route: "auto"}}], + [{user: {age: 10, country: "DE"}}, {user: {age: 10, country: "DE", flags: ["minor"], route: "light"}}], + [{user: {age: 10, country: "XX"}}, {user: {age: 10, country: "XX", flags: ["minor", "sanctioned"], route: "block"}}], + [{user: {age: 101, country: "DE"}}, {user: {age: 101, country: "DE", flags: ["age check"], route: "light"}}], + ], +} + +{ + name: "input column reads a field of a computed object", + policy: { + models: {order: {amount: "number", member: "boolean"}}, + blocks: [ + {expression: "order.pricing", value: "{net: order.amount, discount: order.member ? 0.1 : 0}"}, + {table: "t", inputs: ["order.pricing.net", "order.pricing.discount"], outputs: ["order.message"], rules: [ + ["> 100", "> 0", "'big member order'"], + ["", "> 0", "'member order'"], + ["> 100", "", "'big order'"], + ["", "", "'order'"], + ]}, + ], + }, + cases: [ + [{order: {amount: 200, member: true}}, {order: {amount: 200, member: true, pricing: {net: 200, discount: 0.1}, message: "big member order"}}], + [{order: {amount: 20, member: true}}, {order: {amount: 20, member: true, pricing: {net: 20, discount: 0.1}, message: "member order"}}], + [{order: {amount: 200, member: false}}, {order: {amount: 200, member: false, pricing: {net: 200, discount: 0}, message: "big order"}}], + [{order: {amount: 20, member: false}}, {order: {amount: 20, member: false, pricing: {net: 20, discount: 0}, message: "order"}}], + ], +} + +{ + name: "three tables chained, declared in reverse order", + policy: { + models: {x: {n: "number"}}, + blocks: [ + {table: "c", inputs: ["x.b"], outputs: ["x.c"], rules: [["'odd'", "x.a * 3"], ["", "x.a / 2"]]}, + {table: "b", inputs: ["x.a % 2"], outputs: ["x.b"], rules: [["0", "'even'"], ["", "'odd'"]]}, + {table: "a", inputs: ["x.n"], outputs: ["x.a"], rules: [["< 0", "-x.n"], ["", "x.n"]]}, + ], + }, + cases: [ + [{x: {n: 4}}, {x: {n: 4, a: 4, b: "even", c: 2}}], + [{x: {n: -3}}, {x: {n: -3, a: 3, b: "odd", c: 9}}], + [{x: {n: 0}}, {x: {n: 0, a: 0, b: "even", c: 0}}], + [{x: {n: 1.5}}, {x: {n: 1.5, a: 1.5, b: "odd", c: 4.5}}], + ], +} + +{ + name: "a computed read only by an unselected row's output cell is not evaluated", + policy: { + models: {x: {n: "number"}}, + blocks: [ + {expression: "x.big", value: "x.n * 1000"}, + {expression: "x.small", value: "x.n / 1000"}, + {table: "t", inputs: ["x.n"], outputs: ["x.out"], rules: [["> 10", "x.big"], ["", "x.small"]]}, + ], + }, + cases: [ + [{x: {n: 11}}, {x: {n: 11, big: 11000, out: 11000}}], + [{x: {n: 10}}, {x: {n: 10, small: 0.01, out: 0.01}}], + [{x: {n: -5}}, {x: {n: -5, small: -0.005, out: -0.005}}], + ], +} + +{ + name: "per-member lazy output cell: a member computed read by one member's selected row", + policy: { + models: {order: {lines: "line[]"}, line: {qty: "number", price: "number"}}, + blocks: [ + {expression: "line.bulkPrice", value: "line.qty * line.price * 0.8"}, + {table: "t", inputs: ["line.qty"], outputs: ["line.total"], rules: [[">= 10", "line.bulkPrice"], ["", "line.qty * line.price"]]}, + ], + }, + cases: [ + [ + {order: {lines: [{qty: 10, price: 1}, {qty: 1, price: 5}]}}, + {order: {lines: [{qty: 10, price: 1, bulkPrice: 8, total: 8}, {qty: 1, price: 5, bulkPrice: 4, total: 5}]}}, + "question: as for match arms, once one member's selected row reads the computed, it is evaluated and written for every member", + ], + [ + {order: {lines: [{qty: 1, price: 2}, {qty: 2, price: 2}]}}, + {order: {lines: [{qty: 1, price: 2, total: 2}, {qty: 2, price: 2, total: 4}]}}, + ], + [ + {order: {lines: [{qty: 20, price: 1}]}}, + {order: {lines: [{qty: 20, price: 1, bulkPrice: 16, total: 16}]}}, + ], + ], +} + +{ + name: "a computed read by an input cell is evaluated even when an earlier row decides", + policy: { + models: {x: {n: "number"}}, + blocks: [ + {expression: "x.limit", value: "x.n * 2"}, + {table: "t", inputs: ["x.n"], outputs: ["x.out"], rules: [["> 10", "'big'"], ["< x.limit", "'under limit'"], ["", "'other'"]]}, + ], + }, + cases: [ + [{x: {n: 11}}, {x: {n: 11, limit: 22, out: "big"}}], + [{x: {n: 5}}, {x: {n: 5, limit: 10, out: "under limit"}}], + [{x: {n: -5}}, {x: {n: -5, limit: -10, out: "other"}}], + ], +} + +{ + name: "a collect column evaluates the computed reads of every matched row", + policy: { + models: {x: {n: "number"}}, + blocks: [ + {expression: "x.double", value: "x.n * 2"}, + {expression: "x.square", value: "x.n * x.n"}, + {table: "t", inputs: ["x.n"], outputs: ["x.all[]"], rules: [["> 0", "x.double"], ["> 5", "x.square"]]}, + ], + }, + cases: [ + [{x: {n: 6}}, {x: {n: 6, double: 12, square: 36, all: [12, 36]}}], + [{x: {n: 2}}, {x: {n: 2, double: 4, all: [4]}}], + [{x: {n: 0}}, {x: {n: 0, all: []}}], + ], +} + +{ + name: "goal on one output column of a table with computed inputs", + policy: { + models: {x: {a: "number", b: "number"}}, + blocks: [ + {expression: "x.sum", value: "x.a + x.b"}, + {expression: "x.unrelated", value: "x.a - x.b"}, + {table: "t", inputs: ["x.sum"], outputs: ["x.sign", "x.size"], rules: [["> 0", "1", "'pos'"], ["< 0", "-1", "'neg'"], ["", "0", "'zero'"]]}, + ], + }, + cases: [ + {input: {x: {a: 1, b: 2}}, goals: ["x.sign"], output: {x: {a: 1, b: 2, sum: 3, sign: 1, size: "pos"}}}, + {input: {x: {a: -1, b: -2}}, goals: ["x.size"], output: {x: {a: -1, b: -2, sum: -3, sign: -1, size: "neg"}}}, + {input: {x: {a: 1, b: -1}}, output: {x: {a: 1, b: -1, sum: 0, unrelated: 2, sign: 0, size: "zero"}}}, + ], +} + +// --------------------------------------------------------------------------- +// Mixed collect and scalar columns. +// --------------------------------------------------------------------------- +{ + name: "eight rules, two collect and two scalar columns with sparse cells", + policy: { + models: {patient: {age: "number", bmi: "number", smoker: "boolean", bp: "number"}}, + blocks: [{table: "t", inputs: ["patient.age", "patient.bmi", "patient.smoker", "patient.bp"], outputs: ["patient.risks[]", "patient.tier", "patient.tests[]", "patient.followUp"], rules: [ + [">= 65", "", "", "", "'age'", "", "'ecg'", "30"], + ["", ">= 30", "", "", "'obesity'", "'high'", "'lipids'", ""], + ["", "", "true", "", "'smoking'", "'high'", "'spirometry'", "60"], + ["", "", "", ">= 140", "'hypertension'", "'high'", "", "14"], + ["", "[25..30)", "", "", "'overweight'", "'medium'", "", ""], + ["", "", "", "[130..140)", "'elevated bp'", "'medium'", "'bp monitor'", ""], + ["< 18", "", "", "", "", "'pediatric'", "", "180"], + ["", "", "", "", "", "'low'", "'annual'", "365"], + ]}], + }, + cases: [ + [ + {patient: {age: 70, bmi: 31, smoker: true, bp: 150}}, + {patient: {age: 70, bmi: 31, smoker: true, bp: 150, risks: ["age", "obesity", "smoking", "hypertension"], tier: "high", tests: ["ecg", "lipids", "spirometry", "annual"], followUp: 30}}, + ], + [ + {patient: {age: 40, bmi: 27, smoker: false, bp: 135}}, + {patient: {age: 40, bmi: 27, smoker: false, bp: 135, risks: ["overweight", "elevated bp"], tier: "medium", tests: ["bp monitor", "annual"], followUp: 365}}, + ], + [ + {patient: {age: 40, bmi: 22, smoker: true, bp: 120}}, + {patient: {age: 40, bmi: 22, smoker: true, bp: 120, risks: ["smoking"], tier: "high", tests: ["spirometry", "annual"], followUp: 60}}, + ], + [ + {patient: {age: 10, bmi: 18, smoker: false, bp: 100}}, + {patient: {age: 10, bmi: 18, smoker: false, bp: 100, risks: [], tier: "pediatric", tests: ["annual"], followUp: 180}}, + ], + [ + {patient: {age: 30, bmi: 20, smoker: false, bp: 110}}, + {patient: {age: 30, bmi: 20, smoker: false, bp: 110, risks: [], tier: "low", tests: ["annual"], followUp: 365}}, + ], + ], +} + +{ + name: "collect column of objects and a scalar computed from the same row", + policy: { + models: {cart: {total: "number", coupon: "string?"}}, + blocks: [ + {table: "promos", inputs: ["cart.total", "cart.coupon"], outputs: ["cart.promos[]", "cart.headline"], rules: [ + ["", "'FREESHIP'", "{code: 'FREESHIP', off: 5}", "'free shipping'"], + [">= 100", "", "{code: 'TEN', off: cart.total * 0.1}", "'10% off'"], + [">= 50", "", "{code: 'FIVE', off: 5}", "'5 off'"], + ["", "", "", "'no promotion'"], + ]}, + {expression: "cart.discount", value: "sum(map(cart.promos, #.off))"}, + {expression: "cart.payable", value: "cart.total - cart.discount"}, + ], + }, + cases: [ + [ + {cart: {total: 200, coupon: "FREESHIP"}}, + {cart: {total: 200, coupon: "FREESHIP", promos: [{code: "FREESHIP", off: 5}, {code: "TEN", off: 20}, {code: "FIVE", off: 5}], headline: "free shipping", discount: 30, payable: 170}}, + ], + [ + {cart: {total: 60}}, + {cart: {total: 60, promos: [{code: "FIVE", off: 5}], headline: "5 off", discount: 5, payable: 55}}, + ], + [ + {cart: {total: 10, coupon: null}}, + {cart: {total: 10, coupon: null, promos: [], headline: "no promotion", discount: 0, payable: 10}}, + ], + ], +} + +{ + name: "mixed table without input columns: scalar takes the first non-empty cell, collect takes all", + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", inputs: [], outputs: ["x.first", "x.all[]"], rules: [ + ["", "x.n"], + ["x.n + 1", "x.n + 1"], + ["x.n + 2", ""], + ]}], + }, + cases: [ + [{x: {n: 1}}, {x: {n: 1, first: 2, all: [1, 2]}}], + [{x: {n: -1}}, {x: {n: -1, first: 0, all: [-1, 0]}}], + ], +} + +{ + name: "a collect column on a hit-first table keeps scanning after every scalar is resolved", + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.kind", "x.matches[]"], rules: [ + ["> 0", "'positive'", "1"], + ["> 10", "'big'", "2"], + ["> 100", "'huge'", "3"], + ["", "'any'", "4"], + ]}], + }, + cases: [ + [{x: {n: 500}}, {x: {n: 500, kind: "positive", matches: [1, 2, 3, 4]}}], + [{x: {n: 50}}, {x: {n: 50, kind: "positive", matches: [1, 2, 4]}}], + [{x: {n: 0}}, {x: {n: 0, kind: "any", matches: [4]}}], + ], +} + +{ + name: "mixed table feeding a match and an assertion", + policy: { + models: {txn: {amount: "number", country: "string", hour: "number"}}, + blocks: [ + {table: "t", inputs: ["txn.amount", "txn.country", "txn.hour"], outputs: ["txn.alerts[]", "txn.score"], rules: [ + ["> 5000", "", "", "'amount'", "50"], + ["", "'XX', 'YY'", "", "'geo'", "40"], + ["", "", "< 6", "'night'", "20"], + ["", "", "", "", "0"], + ]}, + {match: "txn.action", arms: [ + ["len(txn.alerts) >= 2", "'block'"], + ["txn.score >= 40", "'challenge'"], + ["", "'allow'"], + ]}, + {assertion: "txn.notify", conditions: [["or", "'geo' in txn.alerts"], "txn.action == 'block'"]}, + ], + }, + cases: [ + [{txn: {amount: 6000, country: "XX", hour: 12}}, {txn: {amount: 6000, country: "XX", hour: 12, alerts: ["amount", "geo"], score: 50, action: "block", notify: true}}], + [{txn: {amount: 10, country: "XX", hour: 12}}, {txn: {amount: 10, country: "XX", hour: 12, alerts: ["geo"], score: 40, action: "challenge", notify: true}}], + [{txn: {amount: 10, country: "DE", hour: 3}}, {txn: {amount: 10, country: "DE", hour: 3, alerts: ["night"], score: 20, action: "allow", notify: false}}], + [{txn: {amount: 6000, country: "DE", hour: 3}}, {txn: {amount: 6000, country: "DE", hour: 3, alerts: ["amount", "night"], score: 50, action: "block", notify: true}}], + [{txn: {amount: 1, country: "DE", hour: 12}}, {txn: {amount: 1, country: "DE", hour: 12, alerts: [], score: 0, action: "allow", notify: false}}], + ], +} + +{ + name: "goal on the scalar column of a mixed table still writes the collect column", + policy: { + models: {x: {n: "number"}}, + blocks: [{table: "t", inputs: ["x.n"], outputs: ["x.tags[]", "x.tier"], rules: [ + ["> 10", "'a'", "1"], + ["> 5", "'b'", ""], + ["", "'c'", "3"], + ]}], + }, + cases: [ + {input: {x: {n: 11}}, goals: ["x.tier"], output: {x: {n: 11, tags: ["a", "b", "c"], tier: 1}}}, + {input: {x: {n: 6}}, goals: ["x.tier"], output: {x: {n: 6, tags: ["b", "c"], tier: 3}}}, + {input: {x: {n: 1}}, goals: ["x.tags"], output: {x: {n: 1, tags: ["c"], tier: 3}}}, + ], +} diff --git a/core/engine/tests/spec/policy/21-relationships-deep.json5 b/core/engine/tests/spec/policy/21-relationships-deep.json5 new file mode 100644 index 00000000..0f35fe4b --- /dev/null +++ b/core/engine/tests/spec/policy/21-relationships-deep.json5 @@ -0,0 +1,947 @@ +// Deep relationship trees: three levels of entities below the root (customer -> company -> +// department -> employee), mixed with single relationships. Chapter 09 covers one and two +// levels; this chapter pins down how computed properties at each level read their parents and +// their children, how aggregates cross several levels, and what happens when a level is absent. +// +// Every entity has ONE source path: the first relationship that targets it (models sorted by +// name, properties in declaration order). Only the root entity and entities whose source hangs +// directly off the root are written per member; a block writing an entity whose source hangs off +// another sourced entity is an UNSUPPORTED_NESTED_ITERATION error ("only one level of +// relationship nesting is evaluated"). Reads at any depth are plain data access. + +// --------------------------------------------------------------------------- +// Three levels read from the root: nested closures over plain input data. +// --------------------------------------------------------------------------- +{ + name: "root aggregates across three levels", + policy: { + models: { + customer: {name: "string", companies: "company[]"}, + company: {name: "string", departments: "department[]"}, + department: {name: "string", employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "customer.headcount", value: "sum(map(customer.companies, sum(map(#.departments, len(#.employees)))))"}, + {expression: "customer.salaries", value: "flatMap(customer.companies, flatMap(#.departments, map(#.employees, #.salary)))"}, + {expression: "customer.departmentCount", value: "sum(map(customer.companies, len(#.departments)))"}, + ], + }, + cases: [ + [ + {customer: {name: "c", companies: [ + {name: "a", departments: [{name: "x", employees: [{salary: 1}, {salary: 2}]}, {name: "y", employees: [{salary: 3}]}]}, + {name: "b", departments: [{name: "z", employees: [{salary: 4}]}]}, + ]}}, + {customer: {name: "c", companies: [ + {name: "a", departments: [{name: "x", employees: [{salary: 1}, {salary: 2}]}, {name: "y", employees: [{salary: 3}]}]}, + {name: "b", departments: [{name: "z", employees: [{salary: 4}]}]}, + ], headcount: 4, salaries: [1, 2, 3, 4], departmentCount: 3}}, + ], + [ + {customer: {name: "c", companies: []}}, + {customer: {name: "c", companies: [], headcount: 0, salaries: [], departmentCount: 0}}, + ], + [ + {customer: {name: "c", companies: [{name: "a", departments: []}]}}, + {customer: {name: "c", companies: [{name: "a", departments: []}], headcount: 0, salaries: [], departmentCount: 0}}, + ], + [ + {customer: {name: "c", companies: [{name: "a", departments: [{name: "x", employees: []}]}]}}, + {customer: {name: "c", companies: [{name: "a", departments: [{name: "x", employees: []}]}], headcount: 0, salaries: [], departmentCount: 1}}, + ], + [ + {customer: {name: "c", companies: [{name: "a", departments: [{name: "x", employees: [{salary: 0.1}, {salary: 0.2}]}]}, {name: "b", departments: []}]}}, + {customer: {name: "c", companies: [{name: "a", departments: [{name: "x", employees: [{salary: 0.1}, {salary: 0.2}]}]}, {name: "b", departments: []}], headcount: 2, salaries: [0.1, 0.2], departmentCount: 1}}, + ], + ], +} + +// Filtering at one level and aggregating at another, with closure aliases at each level. +{ + name: "aliased closures at every level", + policy: { + models: { + customer: {companies: "company[]"}, + company: {name: "string", departments: "department[]"}, + department: {name: "string", employees: "employee[]"}, + employee: {salary: "number", senior: "boolean"}, + }, + blocks: [ + {expression: "customer.seniorPay", value: "sum(flatMap(customer.companies as c, flatMap(c.departments as d, map(filter(d.employees as e, e.senior), #.salary))))"}, + {expression: "customer.tags", value: "flatMap(customer.companies as c, map(c.departments as d, c.name + '/' + d.name))"}, + ], + }, + cases: [ + [ + {customer: {companies: [ + {name: "a", departments: [{name: "x", employees: [{salary: 10, senior: true}, {salary: 1, senior: false}]}]}, + {name: "b", departments: [{name: "y", employees: [{salary: 5, senior: true}]}, {name: "z", employees: []}]}, + ]}}, + {customer: {companies: [ + {name: "a", departments: [{name: "x", employees: [{salary: 10, senior: true}, {salary: 1, senior: false}]}]}, + {name: "b", departments: [{name: "y", employees: [{salary: 5, senior: true}]}, {name: "z", employees: []}]}, + ], seniorPay: 15, tags: ["a/x", "b/y", "b/z"]}}, + ], + [ + {customer: {companies: [{name: "a", departments: [{name: "x", employees: [{salary: 1, senior: false}]}]}]}}, + {customer: {companies: [{name: "a", departments: [{name: "x", employees: [{salary: 1, senior: false}]}]}], seniorPay: 0, tags: ["a/x"]}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], seniorPay: 0, tags: []}}], + ], +} + +// Index access through three levels: out-of-range indexes read null at any level. A negative +// index (`len([]) - 1`) is an expression error, not null. +{ + name: "index access through three levels", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "customer.first", value: "customer.companies[0].departments[0].employees[0].salary"}, + {expression: "customer.second", value: "customer.companies[0].departments[0].employees[1].salary ?? -1"}, + {expression: "customer.lastCompanyDepts", value: "len(customer.companies[len(customer.companies) - 1].departments ?? [])"}, + ], + }, + cases: [ + [ + {customer: {companies: [{departments: [{employees: [{salary: 7}, {salary: 8}]}]}, {departments: [{employees: []}, {employees: []}]}]}}, + {customer: {companies: [{departments: [{employees: [{salary: 7}, {salary: 8}]}]}, {departments: [{employees: []}, {employees: []}]}], first: 7, second: 8, lastCompanyDepts: 2}}, + ], + [ + {customer: {companies: [{departments: [{employees: [{salary: 7}]}]}]}}, + {customer: {companies: [{departments: [{employees: [{salary: 7}]}]}], first: 7, second: -1, lastCompanyDepts: 1}}, + ], + [ + {customer: {companies: [{departments: [{employees: []}]}]}}, + {customer: {companies: [{departments: [{employees: []}]}], first: null, second: -1, lastCompanyDepts: 1}}, + ], + [ + {customer: {companies: [{departments: []}]}}, + {customer: {companies: [{departments: []}], first: null, second: -1, lastCompanyDepts: 0}}, + ], + [ + {customer: {companies: []}}, + "!error: ExpressionFailed", + ], + ], +} + +// --------------------------------------------------------------------------- +// First-level computeds aggregate the levels below them; the root aggregates first-level +// computeds. The member blocks must finish before the root reads them. +// --------------------------------------------------------------------------- +{ + name: "first level aggregates levels two and three, root aggregates the first level", + policy: { + models: { + customer: {companies: "company[]"}, + company: {name: "string", departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "company.payroll", value: "sum(flatMap(company.departments, map(#.employees, #.salary)))"}, + {expression: "company.headcount", value: "sum(map(company.departments, len(#.employees)))"}, + {expression: "customer.payroll", value: "sum(map(customer.companies, #.payroll))"}, + {expression: "customer.largest", value: "max(map(customer.companies, #.headcount))"}, + ], + }, + cases: [ + [ + {customer: {companies: [ + {name: "a", departments: [{employees: [{salary: 1}, {salary: 2}]}, {employees: [{salary: 3}]}]}, + {name: "b", departments: [{employees: [{salary: 10}]}]}, + ]}}, + {customer: {companies: [ + {name: "a", departments: [{employees: [{salary: 1}, {salary: 2}]}, {employees: [{salary: 3}]}], payroll: 6, headcount: 3}, + {name: "b", departments: [{employees: [{salary: 10}]}], payroll: 10, headcount: 1}, + ], payroll: 16, largest: 3}}, + ], + [ + {customer: {companies: [{name: "a", departments: []}]}}, + {customer: {companies: [{name: "a", departments: [], payroll: 0, headcount: 0}], payroll: 0, largest: 0}}, + ], + [ + {customer: {companies: [{name: "a", departments: [{employees: []}, {employees: [{salary: 2.5}]}]}, {name: "b", departments: [{employees: [{salary: 2.5}]}]}]}}, + {customer: {companies: [ + {name: "a", departments: [{employees: []}, {employees: [{salary: 2.5}]}], payroll: 2.5, headcount: 1}, + {name: "b", departments: [{employees: [{salary: 2.5}]}], payroll: 2.5, headcount: 1}, + ], payroll: 5, largest: 1}}, + ], + ], +} + +// The same tree with the root block declared before the member blocks: document order does not +// matter, dependencies do. +{ + name: "root aggregate declared before the member computeds it reads", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {budget: "number", employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "customer.payroll", value: "sum(map(customer.companies, #.payroll))"}, + {expression: "company.payroll", value: "sum(map(company.departments, #.budget))"}, + {expression: "customer.flag", value: "customer.payroll > 10"}, + ], + }, + cases: [ + [ + {customer: {companies: [{departments: [{budget: 4, employees: []}, {budget: 8, employees: []}]}]}}, + {customer: {companies: [{departments: [{budget: 4, employees: []}, {budget: 8, employees: []}], payroll: 12}], payroll: 12, flag: true}}, + ], + [ + {customer: {companies: [{departments: [{budget: 1, employees: []}]}, {departments: []}]}}, + {customer: {companies: [{departments: [{budget: 1, employees: []}], payroll: 1}, {departments: [], payroll: 0}], payroll: 1, flag: false}}, + ], + ], +} + +// First-level computeds read the root (input and computed) and the levels below. +{ + name: "first level reads root input and deep children", + policy: { + models: { + customer: {limit: "number", companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "company.payroll", value: "sum(flatMap(company.departments, map(#.employees, #.salary)))"}, + {expression: "company.over", value: "company.payroll > customer.limit"}, + {expression: "company.overpaid", value: "count(flatMap(company.departments, #.employees), #.salary > customer.limit)"}, + ], + }, + cases: [ + [ + {customer: {limit: 5, companies: [{departments: [{employees: [{salary: 4}, {salary: 6}]}]}, {departments: [{employees: [{salary: 1}]}]}]}}, + {customer: {limit: 5, companies: [ + {departments: [{employees: [{salary: 4}, {salary: 6}]}], payroll: 10, over: true, overpaid: 1}, + {departments: [{employees: [{salary: 1}]}], payroll: 1, over: false, overpaid: 0}, + ]}}, + ], + [ + {customer: {limit: 0, companies: [{departments: []}]}}, + {customer: {limit: 0, companies: [{departments: [], payroll: 0, over: false, overpaid: 0}]}}, + ], + [ + {customer: {limit: -1, companies: [{departments: [{employees: [{salary: 0}]}, {employees: [{salary: 0}]}]}]}}, + {customer: {limit: -1, companies: [{departments: [{employees: [{salary: 0}]}, {employees: [{salary: 0}]}], payroll: 0, over: true, overpaid: 2}]}}, + ], + [{customer: {limit: 3, companies: []}}, {customer: {limit: 3, companies: []}}], + ], +} + +// A root computed reading the deepest level, read back by first-level members, then +// aggregated again at the root: root -> members -> root through three levels of data. +{ + name: "root computed over leaves feeds first-level members", + policy: { + models: { + customer: {companies: "company[]"}, + company: {name: "string", departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "customer.top", value: "max(flatMap(customer.companies, flatMap(#.departments, map(#.employees, #.salary))))"}, + {expression: "company.hasTop", value: "some(flatMap(company.departments, #.employees), #.salary == customer.top)"}, + {expression: "customer.topCompanies", value: "map(filter(customer.companies, #.hasTop), #.name)"}, + ], + }, + cases: [ + [ + {customer: {companies: [ + {name: "a", departments: [{employees: [{salary: 3}]}]}, + {name: "b", departments: [{employees: [{salary: 1}]}, {employees: [{salary: 9}]}]}, + {name: "c", departments: [{employees: [{salary: 9}]}]}, + ]}}, + {customer: {top: 9, companies: [ + {name: "a", departments: [{employees: [{salary: 3}]}], hasTop: false}, + {name: "b", departments: [{employees: [{salary: 1}]}, {employees: [{salary: 9}]}], hasTop: true}, + {name: "c", departments: [{employees: [{salary: 9}]}], hasTop: true}, + ], topCompanies: ["b", "c"]}}, + ], + [ + {customer: {companies: [{name: "a", departments: [{employees: [{salary: 2}]}]}, {name: "b", departments: []}]}}, + {customer: {top: 2, companies: [{name: "a", departments: [{employees: [{salary: 2}]}], hasTop: true}, {name: "b", departments: [], hasTop: false}], topCompanies: ["a"]}}, + ], + ], +} + +// A root factor feeds members, members feed the root total: a chain that alternates levels. +{ + name: "alternating root and member computeds", + policy: { + models: { + customer: {age: "number", companies: "company[]"}, + company: {departments: "department[]"}, + department: {cost: "number"}, + }, + blocks: [ + {expression: "customer.factor", value: "customer.age >= 40 ? 2 : 1"}, + {expression: "company.cost", value: "sum(map(company.departments, #.cost)) * customer.factor"}, + {expression: "customer.total", value: "sum(map(customer.companies, #.cost))"}, + {expression: "company.share", value: "customer.total == 0 ? 0 : company.cost / customer.total"}, + {expression: "customer.maxShare", value: "max(map(customer.companies, #.share))"}, + ], + }, + cases: [ + [ + {customer: {age: 50, companies: [{departments: [{cost: 1}, {cost: 2}]}, {departments: [{cost: 1}]}]}}, + {customer: {age: 50, factor: 2, total: 8, maxShare: 0.75, companies: [ + {departments: [{cost: 1}, {cost: 2}], cost: 6, share: 0.75}, + {departments: [{cost: 1}], cost: 2, share: 0.25}, + ]}}, + ], + [ + {customer: {age: 20, companies: [{departments: [{cost: 5}]}, {departments: [{cost: 5}]}]}}, + {customer: {age: 20, factor: 1, total: 10, maxShare: 0.5, companies: [ + {departments: [{cost: 5}], cost: 5, share: 0.5}, + {departments: [{cost: 5}], cost: 5, share: 0.5}, + ]}}, + ], + [ + {customer: {age: 20, companies: [{departments: []}]}}, + {customer: {age: 20, factor: 1, total: 0, maxShare: 0, companies: [{departments: [], cost: 0, share: 0}]}}, + ], + ], +} + +// First-level match and table blocks decide on a deep aggregate. +{ + name: "first-level match on a deep aggregate", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "company.headcount", value: "sum(map(company.departments, len(#.employees)))"}, + {match: "company.size", arms: [ + ["company.headcount >= 3", "'large'"], + ["company.headcount >= 1", "'small'"], + ["", "'empty'"], + ]}, + {expression: "customer.sizes", value: "map(customer.companies, #.size)"}, + ], + }, + cases: [ + [ + {customer: {companies: [ + {departments: [{employees: [{salary: 1}, {salary: 1}]}, {employees: [{salary: 1}]}]}, + {departments: [{employees: [{salary: 1}]}]}, + {departments: [{employees: []}]}, + ]}}, + {customer: {companies: [ + {departments: [{employees: [{salary: 1}, {salary: 1}]}, {employees: [{salary: 1}]}], headcount: 3, size: "large"}, + {departments: [{employees: [{salary: 1}]}], headcount: 1, size: "small"}, + {departments: [{employees: []}], headcount: 0, size: "empty"}, + ], sizes: ["large", "small", "empty"]}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], sizes: []}}], + ], +} + +{ + name: "first-level table on a deep aggregate", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "company.payroll", value: "sum(flatMap(company.departments, map(#.employees, #.salary)))"}, + {table: "band", inputs: ["company.payroll"], outputs: ["company.band"], rules: [ + ["> 100", "'high'"], + ["> 0", "'mid'"], + ["", "'none'"], + ]}, + {expression: "customer.highCount", value: "count(customer.companies, #.band == 'high')"}, + ], + }, + cases: [ + [ + {customer: {companies: [{departments: [{employees: [{salary: 60}, {salary: 50}]}]}, {departments: [{employees: [{salary: 5}]}]}]}}, + {customer: {companies: [ + {departments: [{employees: [{salary: 60}, {salary: 50}]}], payroll: 110, band: "high"}, + {departments: [{employees: [{salary: 5}]}], payroll: 5, band: "mid"}, + ], highCount: 1}}, + ], + [ + {customer: {companies: [{departments: [{employees: [{salary: 100}]}]}, {departments: []}]}}, + {customer: {companies: [ + {departments: [{employees: [{salary: 100}]}], payroll: 100, band: "mid"}, + {departments: [], payroll: 0, band: "none"}, + ], highCount: 0}}, + ], + ], +} + +// A first-level closure reads the root inside its predicate. +{ + name: "first-level filter of children against a root property", + policy: { + models: { + customer: {minSize: "number", companies: "company[]"}, + company: {departments: "department[]"}, + department: {name: "string", employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "company.bigDepartments", value: "map(filter(company.departments, len(#.employees) >= customer.minSize), #.name)"}, + ], + }, + cases: [ + [ + {customer: {minSize: 2, companies: [{departments: [{name: "x", employees: [{salary: 1}, {salary: 1}]}, {name: "y", employees: [{salary: 1}]}]}]}}, + {customer: {minSize: 2, companies: [{departments: [{name: "x", employees: [{salary: 1}, {salary: 1}]}, {name: "y", employees: [{salary: 1}]}], bigDepartments: ["x"]}]}}, + ], + [ + {customer: {minSize: 0, companies: [{departments: [{name: "x", employees: []}]}, {departments: []}]}}, + {customer: {minSize: 0, companies: [{departments: [{name: "x", employees: []}], bigDepartments: ["x"]}, {departments: [], bigDepartments: []}]}}, + ], + ], +} + +// --------------------------------------------------------------------------- +// Writing below the first level: refused as UNSUPPORTED_NESTED_ITERATION. With the diagnostic +// pinned, the workspace still runs the policy; the deep block is not evaluated. +// --------------------------------------------------------------------------- +{ + name: "second-level write is refused", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {budget: "number"}, + }, + blocks: [{expression: "department.big", value: "department.budget > 10"}], + }, + cases: [ + [{customer: {companies: [{departments: [{budget: 20}]}]}}, "!error: UNSUPPORTED_NESTED_ITERATION"], + [{customer: {companies: []}}, "!error: UNSUPPORTED_NESTED_ITERATION"], + ], +} + +{ + name: "third-level write is refused", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "employee.high", value: "employee.salary > 10"}, + {expression: "customer.n", value: "len(customer.companies)"}, + ], + }, + cases: [ + [{customer: {companies: [{departments: [{employees: [{salary: 20}]}]}]}}, "!error: UNSUPPORTED_NESTED_ITERATION"], + ], +} + +{ + name: "second-level write through the workspace", + diagnostics: ["UNSUPPORTED_NESTED_ITERATION"], + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {budget: "number"}, + }, + blocks: [ + {expression: "department.big", value: "department.budget > 10"}, + {expression: "customer.n", value: "len(customer.companies)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{departments: [{budget: 20}, {budget: 1}]}]}}, + "!error: MissingRequiredInputs", + "question: run through the workspace, the refused deep block is neither evaluated nor dropped: the required-input check looks for department.budget at company.departments.budget and fails the whole evaluation, including the unrelated customer.n", + ], + [ + {customer: {companies: []}}, + "!error: MissingRequiredInputs", + "question: fails as MissingRequiredInputs department.budget even with no companies at all", + ], + ], +} + +// The workaround that is supported: compute per-child values at the first level as a list. +{ + name: "per-child values computed as a first-level list", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {name: "string", budget: "number"}, + }, + blocks: [ + {expression: "company.departmentFlags", value: "map(company.departments, {name: #.name, big: #.budget > 10})"}, + {expression: "company.bigNames", value: "map(filter(company.departmentFlags, #.big), #.name)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{departments: [{name: "x", budget: 20}, {name: "y", budget: 1}]}]}}, + {customer: {companies: [{ + departments: [{name: "x", budget: 20}, {name: "y", budget: 1}], + departmentFlags: [{name: "x", big: true}, {name: "y", big: false}], + bigNames: ["x"], + }]}}, + ], + [ + {customer: {companies: [{departments: []}, {departments: [{name: "z", budget: 11}]}]}}, + {customer: {companies: [ + {departments: [], departmentFlags: [], bigNames: []}, + {departments: [{name: "z", budget: 11}], departmentFlags: [{name: "z", big: true}], bigNames: ["z"]}, + ]}}, + ], + ], +} + +// --------------------------------------------------------------------------- +// Single and array relationships mixed. +// --------------------------------------------------------------------------- + +// Array -> single -> array: company members with one address holding a list of phones. +{ + name: "array then single then array, read from the first level", + policy: { + models: { + customer: {companies: "company[]"}, + company: {name: "string", office: "office"}, + office: {country: "string", phones: "phone[]"}, + phone: {number: "string", mobile: "boolean"}, + }, + blocks: [ + {expression: "company.mobiles", value: "count(company.office.phones, #.mobile)"}, + {expression: "company.domestic", value: "company.office.country == 'US'"}, + {expression: "customer.mobiles", value: "sum(map(customer.companies, #.mobiles))"}, + ], + }, + cases: [ + [ + {customer: {companies: [ + {name: "a", office: {country: "US", phones: [{number: "1", mobile: true}, {number: "2", mobile: false}]}}, + {name: "b", office: {country: "DE", phones: [{number: "3", mobile: true}]}}, + ]}}, + {customer: {companies: [ + {name: "a", office: {country: "US", phones: [{number: "1", mobile: true}, {number: "2", mobile: false}]}, mobiles: 1, domestic: true}, + {name: "b", office: {country: "DE", phones: [{number: "3", mobile: true}]}, mobiles: 1, domestic: false}, + ], mobiles: 2}}, + ], + [ + {customer: {companies: [{name: "a", office: {country: "US", phones: []}}]}}, + {customer: {companies: [{name: "a", office: {country: "US", phones: []}, mobiles: 0, domestic: true}], mobiles: 0}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], mobiles: 0}}], + ], +} + +// Single -> array -> array: one credit report with accounts, each with payments. +{ + name: "single then array then array, aggregated at the root", + policy: { + models: { + customer: {report: "creditReport"}, + creditReport: {bureau: "string", accounts: "account[]"}, + account: {limit: "number", payments: "payment[]"}, + payment: {late: "boolean"}, + }, + blocks: [ + {expression: "customer.totalLimit", value: "sum(map(customer.report.accounts, #.limit))"}, + {expression: "customer.latePayments", value: "count(flatMap(customer.report.accounts, #.payments), #.late)"}, + {expression: "customer.clean", value: "all(customer.report.accounts, none(#.payments, #.late))"}, + ], + }, + cases: [ + [ + {customer: {report: {bureau: "x", accounts: [{limit: 100, payments: [{late: false}, {late: true}]}, {limit: 50, payments: []}]}}}, + {customer: {report: {bureau: "x", accounts: [{limit: 100, payments: [{late: false}, {late: true}]}, {limit: 50, payments: []}]}, totalLimit: 150, latePayments: 1, clean: false}}, + ], + [ + {customer: {report: {bureau: "x", accounts: [{limit: 1, payments: [{late: false}]}]}}}, + {customer: {report: {bureau: "x", accounts: [{limit: 1, payments: [{late: false}]}]}, totalLimit: 1, latePayments: 0, clean: true}}, + ], + [ + {customer: {report: {bureau: "x", accounts: []}}}, + {customer: {report: {bureau: "x", accounts: []}, totalLimit: 0, latePayments: 0, clean: true}}, + ], + ], +} + +// A computed on the single relationship (directly under the root) aggregates its array. +{ + name: "computed on a root single relationship aggregates its members", + policy: { + models: { + customer: {report: "creditReport"}, + creditReport: {accounts: "account[]"}, + account: {limit: "number", balance: "number"}, + }, + blocks: [ + {expression: "creditReport.utilization", value: "sum(map(creditReport.accounts, #.balance)) / sum(map(creditReport.accounts, #.limit))"}, + {expression: "customer.risky", value: "customer.report.utilization > 0.5"}, + ], + }, + cases: [ + [ + {customer: {report: {accounts: [{limit: 100, balance: 80}, {limit: 100, balance: 40}]}}}, + {customer: {report: {accounts: [{limit: 100, balance: 80}, {limit: 100, balance: 40}], utilization: 0.6}, risky: true}}, + ], + [ + {customer: {report: {accounts: [{limit: 10, balance: 5}]}}}, + {customer: {report: {accounts: [{limit: 10, balance: 5}], utilization: 0.5}, risky: false}}, + ], + ], +} + +// Members of an array that sits inside a root single relationship: one level of iteration, but +// the source hangs off the single relationship. +{ + name: "per-member block on an array inside a single relationship", + policy: { + models: { + customer: {report: "creditReport"}, + creditReport: {accounts: "account[]"}, + account: {limit: "number", balance: "number"}, + }, + blocks: [ + {expression: "account.maxed", value: "account.balance >= account.limit"}, + {expression: "customer.maxedCount", value: "count(customer.report.accounts, #.maxed)"}, + ], + }, + cases: [ + [ + {customer: {report: {accounts: [{limit: 10, balance: 10}, {limit: 10, balance: 1}]}}}, + {customer: {report: {accounts: [{limit: 10, balance: 10, maxed: true}, {limit: 10, balance: 1, maxed: false}]}, maxedCount: 1}}, + "bug: there is only one array level here, but the account source hangs off the creditReport single relationship and the write is refused as UNSUPPORTED_NESTED_ITERATION", + ], + [ + {customer: {report: {accounts: []}}}, + {customer: {report: {accounts: []}, maxedCount: 0}}, + "bug: refused as UNSUPPORTED_NESTED_ITERATION although no nested iteration exists", + ], + ], +} + +// A single relationship nested in a single relationship: writing the inner one. +{ + name: "write on a single relationship nested in a single relationship", + policy: { + models: { + customer: {report: "creditReport"}, + creditReport: {bureau: "bureau"}, + bureau: {weight: "number"}, + }, + blocks: [{expression: "bureau.heavy", value: "bureau.weight > 1"}], + }, + cases: [ + [ + {customer: {report: {bureau: {weight: 3}}}}, + {customer: {report: {bureau: {weight: 3, heavy: true}}}}, + "bug: no iteration is involved at all, yet the write is refused as UNSUPPORTED_NESTED_ITERATION", + ], + ], +} + +// A single relationship under each array member: the per-member block writes on the member and +// reads through its single relationship. +{ + name: "per-member read through a member's single relationship", + policy: { + models: { + customer: {companies: "company[]"}, + company: {revenue: "number", rating: "rating"}, + rating: {score: "number", agency: "string"}, + }, + blocks: [ + {expression: "company.adjusted", value: "company.revenue * company.rating.score"}, + {expression: "customer.agencies", value: "map(customer.companies, #.rating.agency)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10, rating: {score: 0.5, agency: "x"}}, {revenue: 2, rating: {score: 2, agency: "y"}}]}}, + {customer: {companies: [ + {revenue: 10, rating: {score: 0.5, agency: "x"}, adjusted: 5}, + {revenue: 2, rating: {score: 2, agency: "y"}, adjusted: 4}, + ], agencies: ["x", "y"]}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], agencies: []}}], + ], +} + +// Writing on a member's single relationship is a second level of nesting. +{ + name: "write on a single relationship under array members", + policy: { + models: { + customer: {companies: "company[]"}, + company: {rating: "rating"}, + rating: {score: "number"}, + }, + blocks: [{expression: "rating.good", value: "rating.score > 1"}], + }, + cases: [ + [{customer: {companies: [{rating: {score: 2}}]}}, "!error: UNSUPPORTED_NESTED_ITERATION"], + ], +} + +// --------------------------------------------------------------------------- +// Missing levels. +// --------------------------------------------------------------------------- + +// A required middle level absent from a member: the deep read needs it. +{ + name: "required middle level missing", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [{expression: "company.headcount", value: "sum(map(company.departments, len(#.employees)))"}], + }, + cases: [ + [{customer: {companies: [{departments: [{employees: [{salary: 1}]}]}]}}, {customer: {companies: [{departments: [{employees: [{salary: 1}]}], headcount: 1}]}}], + [{customer: {companies: [{}]}}, "!error"], + [{customer: {companies: [{departments: [{employees: [{salary: 1}]}]}, {}]}}, "!error"], + [{customer: {companies: [{departments: null}]}}, "!error"], + ], +} + +// Optional levels at every depth with `??` defaults. +{ + name: "optional levels with defaults", + policy: { + models: { + customer: {companies: "company[]?"}, + company: {departments: "department[]?"}, + department: {employees: "employee[]?"}, + employee: {salary: "number?"}, + }, + blocks: [ + {expression: "customer.payroll", value: "sum(flatMap(customer.companies ?? [], flatMap(#.departments ?? [], map(#.employees ?? [], #.salary ?? 0))))"}, + {expression: "customer.companyCount", value: "len(customer.companies ?? [])"}, + ], + }, + cases: [ + [{customer: {}}, {customer: {payroll: 0, companyCount: 0}}], + [{customer: {companies: null}}, {customer: {companies: null, payroll: 0, companyCount: 0}}], + [{customer: {companies: [{}]}}, {customer: {companies: [{}], payroll: 0, companyCount: 1}}], + [{customer: {companies: [{departments: null}]}}, {customer: {companies: [{departments: null}], payroll: 0, companyCount: 1}}], + [{customer: {companies: [{departments: [{}]}]}}, {customer: {companies: [{departments: [{}]}], payroll: 0, companyCount: 1}}], + [{customer: {companies: [{departments: [{employees: [{}]}]}]}}, {customer: {companies: [{departments: [{employees: [{}]}]}], payroll: 0, companyCount: 1}}], + [ + {customer: {companies: [{departments: [{employees: [{salary: 4}, {salary: null}, {}]}, {}]}, {}]}}, + {customer: {companies: [{departments: [{employees: [{salary: 4}, {salary: null}, {}]}, {}]}, {}], payroll: 4, companyCount: 2}}, + ], + ], +} + +// Optional middle level read per member: missing and null levels give the default. +{ + name: "per-member read of an optional child level", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]?"}, + department: {budget: "number"}, + }, + blocks: [ + {expression: "company.budget", value: "sum(map(company.departments ?? [], #.budget))"}, + {expression: "company.hasDepartments", value: "company.departments != null"}, + ], + }, + cases: [ + [ + {customer: {companies: [{departments: [{budget: 2}, {budget: 3}]}, {}, {departments: null}, {departments: []}]}}, + {customer: {companies: [ + {departments: [{budget: 2}, {budget: 3}], budget: 5, hasDepartments: true}, + {budget: 0, hasDepartments: false}, + {departments: null, budget: 0, hasDepartments: false}, + {departments: [], budget: 0, hasDepartments: true}, + ]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +// A missing optional single relationship in the middle of a path. +{ + name: "optional single relationship in the middle of a deep path", + policy: { + models: { + customer: {companies: "company[]"}, + company: {office: "office?"}, + office: {phones: "phone[]"}, + phone: {mobile: "boolean"}, + }, + blocks: [{expression: "company.mobiles", value: "count(company.office.phones ?? [], #.mobile)"}], + }, + cases: [ + [ + {customer: {companies: [{office: {phones: [{mobile: true}, {mobile: true}]}}, {office: null}, {}]}}, + {customer: {companies: [{office: {phones: [{mobile: true}, {mobile: true}]}, mobiles: 2}, {office: null, mobiles: 0}, {mobiles: 0}]}}, + ], + [{customer: {companies: [{office: {phones: []}}]}}, {customer: {companies: [{office: {phones: []}, mobiles: 0}]}}], + ], +} + +// Null items at deeper levels. +{ + name: "null items at the second and third level", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "customer.departments", value: "sum(map(customer.companies, len(#.departments)))"}, + {expression: "customer.realEmployees", value: "count(flatMap(filter(flatMap(customer.companies, #.departments), # != null), #.employees), # != null)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{departments: [null, {employees: [null, {salary: 1}]}]}]}}, + {customer: {companies: [{departments: [null, {employees: [null, {salary: 1}]}]}], departments: 2, realEmployees: 1}}, + ], + [ + {customer: {companies: [{departments: [{employees: [{salary: 1}, {salary: 2}]}]}]}}, + {customer: {companies: [{departments: [{employees: [{salary: 1}, {salary: 2}]}]}], departments: 1, realEmployees: 2}}, + ], + ], +} + +// --------------------------------------------------------------------------- +// Validation at depth. +// --------------------------------------------------------------------------- +{ + name: "values are validated at every level", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [{expression: "customer.n", value: "len(customer.companies)"}], + }, + cases: [ + [{customer: {companies: [{departments: [{employees: [{salary: 1, extra: "x"}]}], extra: 1}]}}, {customer: {companies: [{departments: [{employees: [{salary: 1, extra: "x"}]}], extra: 1}], n: 1}}], + [{customer: {companies: [{departments: [{employees: [{salary: "1"}]}]}]}}, "!error: InputValidationFailed"], + [{customer: {companies: [{departments: [{employees: {salary: 1}}]}]}}, "!error: InputValidationFailed"], + [{customer: {companies: [{departments: [{employees: [1]}]}]}}, "!error: InputValidationFailed"], + [{customer: {companies: [{departments: {employees: []}}]}}, "!error: InputValidationFailed"], + [{customer: {companies: [{departments: ["x"]}]}}, "!error: InputValidationFailed"], + [{customer: {companies: [{departments: [{employees: [{salary: true}]}]}]}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------- +// Goals in deep trees. +// --------------------------------------------------------------------------- +{ + name: "goals pick one branch of a deep tree", + policy: { + models: { + customer: {companies: "company[]"}, + company: {departments: "department[]"}, + department: {employees: "employee[]"}, + employee: {salary: "number"}, + }, + blocks: [ + {expression: "company.payroll", value: "sum(flatMap(company.departments, map(#.employees, #.salary)))"}, + {expression: "company.headcount", value: "sum(map(company.departments, len(#.employees)))"}, + {expression: "customer.payroll", value: "sum(map(customer.companies, #.payroll))"}, + ], + }, + cases: [ + { + input: {customer: {companies: [{departments: [{employees: [{salary: 1}, {salary: 2}]}]}]}}, + goals: ["customer.payroll"], + output: {customer: {companies: [{departments: [{employees: [{salary: 1}, {salary: 2}]}], payroll: 3}], payroll: 3}}, + }, + { + input: {customer: {companies: [{departments: [{employees: [{salary: 1}, {salary: 2}]}]}]}}, + goals: ["company.headcount"], + output: {customer: {companies: [{departments: [{employees: [{salary: 1}, {salary: 2}]}], headcount: 2}]}}, + }, + { + input: {customer: {companies: [{departments: [{employees: [{salary: 1}, {salary: 2}]}]}]}}, + goals: ["company.payroll", "company.headcount"], + output: {customer: {companies: [{departments: [{employees: [{salary: 1}, {salary: 2}]}], payroll: 3, headcount: 2}]}}, + }, + ], +} + +// --------------------------------------------------------------------------- +// A self-referencing relationship (company.subsidiaries: company[]). The entity's source is +// the first relationship by model name, so `company.subsidiaries` (model `company`) wins over +// `customer.companies`. +// --------------------------------------------------------------------------- +{ + name: "self-referencing relationship read from the root", + policy: { + models: { + customer: {companies: "company[]"}, + company: {revenue: "number", subsidiaries: "company[]?"}, + }, + blocks: [ + {expression: "customer.groupRevenue", value: "sum(map(customer.companies, #.revenue + sum(map(#.subsidiaries ?? [], #.revenue))))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10, subsidiaries: [{revenue: 1}, {revenue: 2}]}, {revenue: 5}]}}, + {customer: {companies: [{revenue: 10, subsidiaries: [{revenue: 1}, {revenue: 2}]}, {revenue: 5}], groupRevenue: 18}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], groupRevenue: 0}}], + ], +} + +{ + name: "per-member block on a self-referencing entity", + policy: { + models: { + customer: {companies: "company[]"}, + company: {revenue: "number", subsidiaries: "company[]?"}, + }, + blocks: [{expression: "company.big", value: "company.revenue > 5"}], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10}, {revenue: 1}]}}, + {customer: {companies: [{revenue: 10, big: true}, {revenue: 1, big: false}]}}, + "bug: company's source is company.subsidiaries (model company sorts before customer), so the per-member block never runs over customer.companies and nothing is written", + ], + [ + {customer: {companies: [{revenue: 10, subsidiaries: [{revenue: 7}]}]}}, + {customer: {companies: [{revenue: 10, subsidiaries: [{revenue: 7}], big: true}]}}, + "bug: the self-referencing source shadows customer.companies; no member is written (whether subsidiaries should also get big is open)", + ], + ], +} diff --git a/core/engine/tests/spec/policy/22-aggregates.json5 b/core/engine/tests/spec/policy/22-aggregates.json5 new file mode 100644 index 00000000..48c500d1 --- /dev/null +++ b/core/engine/tests/spec/policy/22-aggregates.json5 @@ -0,0 +1,904 @@ +// Aggregates over relationship members. Chapter 09 covers the basic sum/count/map/filter over +// member fields and computed member properties; this chapter goes through every aggregate on +// members, on computed member properties, on aggregates of aggregates, on empty collections and +// on collections holding nulls. The aggregate functions themselves are specified by the +// expression suite (06-aggregates); here the point is the engine: per-member blocks finish before +// any aggregate over them runs, empty and absent relationships, and how a failing aggregate +// fails the evaluation. + +// --------------------------------------------------------------------------- +// Every numeric aggregate over a raw member field. +// --------------------------------------------------------------------------- +{ + name: "numeric aggregates over a member field", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.sum", value: "sum(map(customer.companies, #.revenue))"}, + {expression: "customer.avg", value: "avg(map(customer.companies, #.revenue))"}, + {expression: "customer.min", value: "min(map(customer.companies, #.revenue))"}, + {expression: "customer.max", value: "max(map(customer.companies, #.revenue))"}, + {expression: "customer.median", value: "median(map(customer.companies, #.revenue))"}, + {expression: "customer.count", value: "len(customer.companies)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 4}, {revenue: 1}, {revenue: 10}]}}, + {customer: {companies: [{revenue: 4}, {revenue: 1}, {revenue: 10}], sum: 15, avg: 5, min: 1, max: 10, median: 4, count: 3}}, + ], + [ + {customer: {companies: [{revenue: 2}, {revenue: 3}]}}, + {customer: {companies: [{revenue: 2}, {revenue: 3}], sum: 5, avg: 2.5, min: 2, max: 3, median: 2.5, count: 2}}, + ], + [ + {customer: {companies: [{revenue: -1.5}]}}, + {customer: {companies: [{revenue: -1.5}], sum: -1.5, avg: -1.5, min: -1.5, max: -1.5, median: -1.5, count: 1}}, + ], + [ + {customer: {companies: [{revenue: 0.1}, {revenue: 0.2}, {revenue: 0.3}]}}, + {customer: {companies: [{revenue: 0.1}, {revenue: 0.2}, {revenue: 0.3}], sum: 0.6, avg: 0.2, min: 0.1, max: 0.3, median: 0.2, count: 3}}, + ], + [ + {customer: {companies: [{revenue: 7}, {revenue: 7}, {revenue: 7}, {revenue: 7}]}}, + {customer: {companies: [{revenue: 7}, {revenue: 7}, {revenue: 7}, {revenue: 7}], sum: 28, avg: 7, min: 7, max: 7, median: 7, count: 4}}, + ], + ], +} + +// Aggregates with a neutral element on an empty relationship. +{ + name: "empty relationship: aggregates with a neutral element", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", active: "boolean"}}, + blocks: [ + {expression: "customer.sum", value: "sum(map(customer.companies, #.revenue))"}, + {expression: "customer.count", value: "count(customer.companies, #.active)"}, + {expression: "customer.len", value: "len(customer.companies)"}, + {expression: "customer.some", value: "some(customer.companies, #.active)"}, + {expression: "customer.all", value: "all(customer.companies, #.active)"}, + {expression: "customer.none", value: "none(customer.companies, #.active)"}, + {expression: "customer.one", value: "one(customer.companies, #.active)"}, + {expression: "customer.filtered", value: "filter(customer.companies, #.active)"}, + {expression: "customer.mapped", value: "map(customer.companies, #.revenue)"}, + ], + }, + cases: [ + [ + {customer: {companies: []}}, + {customer: {companies: [], sum: 0, count: 0, len: 0, some: false, all: true, none: true, one: false, filtered: [], mapped: []}}, + ], + [ + {customer: {companies: [{revenue: 1, active: true}]}}, + {customer: {companies: [{revenue: 1, active: true}], sum: 1, count: 1, len: 1, some: true, all: true, none: false, one: true, filtered: [{revenue: 1, active: true}], mapped: [1]}}, + ], + [ + {customer: {companies: [{revenue: 1, active: true}, {revenue: 2, active: true}]}}, + {customer: {companies: [{revenue: 1, active: true}, {revenue: 2, active: true}], sum: 3, count: 2, len: 2, some: true, all: true, none: false, one: false, filtered: [{revenue: 1, active: true}, {revenue: 2, active: true}], mapped: [1, 2]}}, + ], + [ + {customer: {companies: [{revenue: 1, active: false}, {revenue: 2, active: true}]}}, + {customer: {companies: [{revenue: 1, active: false}, {revenue: 2, active: true}], sum: 3, count: 1, len: 2, some: true, all: false, none: false, one: true, filtered: [{revenue: 2, active: true}], mapped: [1, 2]}}, + ], + [ + {customer: {companies: [{revenue: 1, active: false}]}}, + {customer: {companies: [{revenue: 1, active: false}], sum: 1, count: 0, len: 1, some: false, all: false, none: true, one: false, filtered: [], mapped: [1]}}, + ], + ], +} + +// Aggregates without a neutral element fail the evaluation on an empty relationship. +{ + name: "empty relationship: avg fails the evaluation", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.avg", value: "avg(map(customer.companies, #.revenue))"}], + }, + cases: [ + [{customer: {companies: [{revenue: 3}, {revenue: 5}]}}, {customer: {companies: [{revenue: 3}, {revenue: 5}], avg: 4}}], + [{customer: {companies: []}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "empty relationship: min and max fail the evaluation", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.min", value: "min(map(customer.companies, #.revenue))"}, + {expression: "customer.max", value: "max(map(customer.companies, #.revenue))"}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 3}]}}, {customer: {companies: [{revenue: 3}], min: 3, max: 3}}], + [{customer: {companies: []}}, "!error: ExpressionFailed"], + ], +} + +// Guarding the empty case keeps the evaluation alive. +{ + name: "guarded aggregates on an empty relationship", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.avg", value: "len(customer.companies) > 0 ? avg(map(customer.companies, #.revenue)) : null"}, + {expression: "customer.max", value: "len(customer.companies) == 0 ? 0 : max(map(customer.companies, #.revenue))"}, + {expression: "customer.mean", value: "len(customer.companies) == 0 ? 0 : sum(map(customer.companies, #.revenue)) / len(customer.companies)"}, + ], + }, + cases: [ + [{customer: {companies: []}}, {customer: {companies: [], avg: null, max: 0, mean: 0}}], + [{customer: {companies: [{revenue: 1}, {revenue: 2}]}}, {customer: {companies: [{revenue: 1}, {revenue: 2}], avg: 1.5, max: 2, mean: 1.5}}], + [{customer: {companies: [{revenue: -4}]}}, {customer: {companies: [{revenue: -4}], avg: -4, max: -4, mean: -4}}], + ], +} + +// A failing aggregate fails the whole evaluation, even when other blocks succeeded. +{ + name: "a failing aggregate fails the whole evaluation", + policy: { + models: {customer: {name: "string", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.label", value: "customer.name + '!'"}, + {expression: "customer.top", value: "max(map(customer.companies, #.revenue))"}, + ], + }, + cases: [ + [{customer: {name: "a", companies: [{revenue: 2}]}}, {customer: {name: "a", companies: [{revenue: 2}], label: "a!", top: 2}}], + [{customer: {name: "a", companies: []}}, "!error: ExpressionFailed"], + ], +} + +// Goals that do not need the failing aggregate succeed. +{ + name: "goals avoid a failing aggregate", + policy: { + models: {customer: {name: "string", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.label", value: "customer.name + '!'"}, + {expression: "customer.top", value: "max(map(customer.companies, #.revenue))"}, + ], + }, + cases: [ + {input: {customer: {name: "a", companies: []}}, goals: ["customer.label"], output: {customer: {name: "a", companies: [], label: "a!"}}}, + {input: {customer: {name: "a", companies: []}}, goals: ["customer.top"], output: "!error: ExpressionFailed"}, + {input: {customer: {name: "b", companies: [{revenue: 9}]}}, goals: ["customer.top"], output: {customer: {name: "b", companies: [{revenue: 9}], top: 9}}}, + ], +} + +// --------------------------------------------------------------------------- +// Boolean aggregates over members: some / all / none / one / count with predicates on fields. +// --------------------------------------------------------------------------- +{ + name: "boolean aggregates with field predicates", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", country: "string"}}, + blocks: [ + {expression: "customer.anyForeign", value: "some(customer.companies, #.country != 'US')"}, + {expression: "customer.allProfitable", value: "all(customer.companies, #.revenue > 0)"}, + {expression: "customer.noneHuge", value: "none(customer.companies, #.revenue > 1000)"}, + {expression: "customer.oneDomestic", value: "one(customer.companies, #.country == 'US')"}, + {expression: "customer.domestic", value: "count(customer.companies, #.country == 'US')"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1, country: "US"}, {revenue: 5, country: "DE"}]}}, + {customer: {companies: [{revenue: 1, country: "US"}, {revenue: 5, country: "DE"}], anyForeign: true, allProfitable: true, noneHuge: true, oneDomestic: true, domestic: 1}}, + ], + [ + {customer: {companies: [{revenue: 1, country: "US"}, {revenue: 0, country: "US"}]}}, + {customer: {companies: [{revenue: 1, country: "US"}, {revenue: 0, country: "US"}], anyForeign: false, allProfitable: false, noneHuge: true, oneDomestic: false, domestic: 2}}, + ], + [ + {customer: {companies: [{revenue: 2000, country: "FR"}]}}, + {customer: {companies: [{revenue: 2000, country: "FR"}], anyForeign: true, allProfitable: true, noneHuge: false, oneDomestic: false, domestic: 0}}, + ], + [ + {customer: {companies: []}}, + {customer: {companies: [], anyForeign: false, allProfitable: true, noneHuge: true, oneDomestic: false, domestic: 0}}, + ], + ], +} + +// Predicates reading the parent entity inside the closure. +{ + name: "aggregate predicates read the parent", + policy: { + models: {customer: {threshold: "number", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.above", value: "count(customer.companies, #.revenue > customer.threshold)"}, + {expression: "customer.allAbove", value: "all(customer.companies, #.revenue > customer.threshold)"}, + {expression: "customer.aboveSum", value: "sum(map(filter(customer.companies, #.revenue > customer.threshold), #.revenue - customer.threshold))"}, + ], + }, + cases: [ + [ + {customer: {threshold: 10, companies: [{revenue: 5}, {revenue: 15}, {revenue: 30}]}}, + {customer: {threshold: 10, companies: [{revenue: 5}, {revenue: 15}, {revenue: 30}], above: 2, allAbove: false, aboveSum: 25}}, + ], + [ + {customer: {threshold: 0, companies: [{revenue: 1}, {revenue: 2}]}}, + {customer: {threshold: 0, companies: [{revenue: 1}, {revenue: 2}], above: 2, allAbove: true, aboveSum: 3}}, + ], + [ + {customer: {threshold: 100, companies: []}}, + {customer: {threshold: 100, companies: [], above: 0, allAbove: true, aboveSum: 0}}, + ], + ], +} + +// --------------------------------------------------------------------------- +// Aggregates over computed member properties of every block kind. +// --------------------------------------------------------------------------- +{ + name: "aggregates over expression-computed member properties", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", cost: "number"}}, + blocks: [ + {expression: "company.profit", value: "company.revenue - company.cost"}, + {expression: "customer.totalProfit", value: "sum(map(customer.companies, #.profit))"}, + {expression: "customer.worst", value: "min(map(customer.companies, #.profit))"}, + {expression: "customer.best", value: "max(map(customer.companies, #.profit))"}, + {expression: "customer.losers", value: "count(customer.companies, #.profit < 0)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10, cost: 4}, {revenue: 3, cost: 5}, {revenue: 8, cost: 8}]}}, + {customer: {companies: [{revenue: 10, cost: 4, profit: 6}, {revenue: 3, cost: 5, profit: -2}, {revenue: 8, cost: 8, profit: 0}], totalProfit: 4, worst: -2, best: 6, losers: 1}}, + ], + [ + {customer: {companies: [{revenue: 0.3, cost: 0.1}]}}, + {customer: {companies: [{revenue: 0.3, cost: 0.1, profit: 0.2}], totalProfit: 0.2, worst: 0.2, best: 0.2, losers: 0}}, + ], + ], +} + +{ + name: "aggregates over match-computed member properties", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {match: "company.tier", arms: [ + ["company.revenue >= 100", "'gold'"], + ["company.revenue >= 10", "'silver'"], + ["", "'bronze'"], + ]}, + {match: "company.weight", arms: [ + ["company.tier == 'gold'", "3"], + ["company.tier == 'silver'", "2"], + ["", "1"], + ]}, + {expression: "customer.weight", value: "sum(map(customer.companies, #.weight))"}, + {expression: "customer.golds", value: "count(customer.companies, #.tier == 'gold')"}, + {expression: "customer.tiers", value: "map(customer.companies, #.tier)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 500}, {revenue: 50}, {revenue: 5}]}}, + {customer: {companies: [ + {revenue: 500, tier: "gold", weight: 3}, + {revenue: 50, tier: "silver", weight: 2}, + {revenue: 5, tier: "bronze", weight: 1}, + ], weight: 6, golds: 1, tiers: ["gold", "silver", "bronze"]}}, + ], + [ + {customer: {companies: [{revenue: 100}, {revenue: 100}]}}, + {customer: {companies: [{revenue: 100, tier: "gold", weight: 3}, {revenue: 100, tier: "gold", weight: 3}], weight: 6, golds: 2, tiers: ["gold", "gold"]}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], weight: 0, golds: 0, tiers: []}}], + ], +} + +{ + name: "aggregates over table-computed member properties", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", country: "string"}}, + blocks: [ + {table: "rate", inputs: ["company.country", "company.revenue"], outputs: ["company.rate"], rules: [ + ["'US'", "> 100", "0.1"], + ["'US'", "", "0.2"], + ["", "", "0.3"], + ]}, + {expression: "company.tax", value: "company.revenue * company.rate"}, + {expression: "customer.tax", value: "sum(map(customer.companies, #.tax))"}, + {expression: "customer.maxRate", value: "max(map(customer.companies, #.rate))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 200, country: "US"}, {revenue: 50, country: "US"}, {revenue: 10, country: "DE"}]}}, + {customer: {companies: [ + {revenue: 200, country: "US", rate: 0.1, tax: 20}, + {revenue: 50, country: "US", rate: 0.2, tax: 10}, + {revenue: 10, country: "DE", rate: 0.3, tax: 3}, + ], tax: 33, maxRate: 0.3}}, + ], + [ + {customer: {companies: [{revenue: 1000, country: "US"}]}}, + {customer: {companies: [{revenue: 1000, country: "US", rate: 0.1, tax: 100}], tax: 100, maxRate: 0.1}}, + ], + ], +} + +{ + name: "aggregates over assertion-computed member properties", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", audited: "boolean"}}, + blocks: [ + {assertion: "company.eligible", conditions: ["company.revenue > 10", "company.audited"]}, + {expression: "customer.eligible", value: "count(customer.companies, #.eligible)"}, + {expression: "customer.allEligible", value: "all(customer.companies, #.eligible)"}, + {expression: "customer.eligibleRevenue", value: "sum(map(filter(customer.companies, #.eligible), #.revenue))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 20, audited: true}, {revenue: 20, audited: false}, {revenue: 5, audited: true}]}}, + {customer: {companies: [ + {revenue: 20, audited: true, eligible: true}, + {revenue: 20, audited: false, eligible: false}, + {revenue: 5, audited: true, eligible: false}, + ], eligible: 1, allEligible: false, eligibleRevenue: 20}}, + ], + [ + {customer: {companies: [{revenue: 11, audited: true}]}}, + {customer: {companies: [{revenue: 11, audited: true, eligible: true}], eligible: 1, allEligible: true, eligibleRevenue: 11}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], eligible: 0, allEligible: true, eligibleRevenue: 0}}], + ], +} + +// A computed member property that is null for some members: null-tolerant aggregates. +{ + name: "computed member property null for some members", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.bonus", value: "company.revenue > 10 ? company.revenue / 10 : null"}, + {expression: "customer.withBonus", value: "count(customer.companies, #.bonus != null)"}, + {expression: "customer.bonusTotal", value: "sum(map(customer.companies, #.bonus ?? 0))"}, + {expression: "customer.bonuses", value: "map(customer.companies, #.bonus)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 50}, {revenue: 5}, {revenue: 20}]}}, + {customer: {companies: [{revenue: 50, bonus: 5}, {revenue: 5, bonus: null}, {revenue: 20, bonus: 2}], withBonus: 2, bonusTotal: 7, bonuses: [5, null, 2]}}, + ], + [ + {customer: {companies: [{revenue: 1}]}}, + {customer: {companies: [{revenue: 1, bonus: null}], withBonus: 0, bonusTotal: 0, bonuses: [null]}}, + ], + ], +} + +// Summing a computed member property that may be null: the type checker refuses the policy +// (INVALID_EXPRESSION), whatever the data. +{ + name: "sum over a nullable computed member property is refused", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.bonus", value: "company.revenue > 10 ? company.revenue / 10 : null"}, + {expression: "customer.bonusTotal", value: "sum(map(customer.companies, #.bonus))"}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 50}, {revenue: 20}]}}, "!error: INVALID_EXPRESSION"], + [{customer: {companies: [{revenue: 50}, {revenue: 1}]}}, "!error: INVALID_EXPRESSION"], + [{customer: {companies: []}}, "!error: INVALID_EXPRESSION"], + ], +} + +// The same policy run through the workspace: sum fails at runtime only when a null is present. +{ + name: "sum over a nullable computed member property through the workspace", + diagnostics: ["INVALID_EXPRESSION"], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.bonus", value: "company.revenue > 10 ? company.revenue / 10 : null"}, + {expression: "customer.bonusTotal", value: "sum(map(customer.companies, #.bonus))"}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 50}, {revenue: 20}]}}, {customer: {companies: [{revenue: 50, bonus: 5}, {revenue: 20, bonus: 2}], bonusTotal: 7}}], + [{customer: {companies: [{revenue: 50}, {revenue: 1}]}}, "!error: ExpressionFailed"], + [{customer: {companies: []}}, {customer: {companies: [], bonusTotal: 0}}], + ], +} + +// --------------------------------------------------------------------------- +// Aggregates of aggregates. +// --------------------------------------------------------------------------- + +// Per-member aggregates over a primitive array on the member, aggregated again at the root. +{ + name: "member aggregates over a primitive array, re-aggregated at the root", + policy: { + models: {customer: {companies: "company[]"}, company: {scores: "number[]"}}, + blocks: [ + {expression: "company.total", value: "sum(company.scores)"}, + {expression: "company.best", value: "len(company.scores) == 0 ? 0 : max(company.scores)"}, + {expression: "customer.grand", value: "sum(map(customer.companies, #.total))"}, + {expression: "customer.bestOfBest", value: "max(map(customer.companies, #.best))"}, + {expression: "customer.avgTotal", value: "avg(map(customer.companies, #.total))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{scores: [1, 2, 3]}, {scores: [10]}, {scores: []}]}}, + {customer: {companies: [{scores: [1, 2, 3], total: 6, best: 3}, {scores: [10], total: 10, best: 10}, {scores: [], total: 0, best: 0}], grand: 16, bestOfBest: 10, avgTotal: 5.3333333333333333333333333333}}, + ], + [ + {customer: {companies: [{scores: [0.5, 0.5]}, {scores: [-1]}]}}, + {customer: {companies: [{scores: [0.5, 0.5], total: 1, best: 0.5}, {scores: [-1], total: -1, best: -1}], grand: 0, bestOfBest: 0.5, avgTotal: 0}}, + ], + ], +} + +// Three stacked aggregates: member sum -> root list -> root aggregate of the list. +{ + name: "chained root aggregates", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.revenues", value: "map(customer.companies, #.revenue)"}, + {expression: "customer.total", value: "sum(customer.revenues)"}, + {expression: "customer.shares", value: "map(customer.revenues, customer.total == 0 ? 0 : # / customer.total)"}, + {expression: "customer.shareSum", value: "sum(customer.shares)"}, + {expression: "customer.dominant", value: "some(customer.shares, # > 0.5)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1}, {revenue: 3}]}}, + {customer: {companies: [{revenue: 1}, {revenue: 3}], revenues: [1, 3], total: 4, shares: [0.25, 0.75], shareSum: 1, dominant: true}}, + ], + [ + {customer: {companies: [{revenue: 1}, {revenue: 1}]}}, + {customer: {companies: [{revenue: 1}, {revenue: 1}], revenues: [1, 1], total: 2, shares: [0.5, 0.5], shareSum: 1, dominant: false}}, + ], + [ + {customer: {companies: [{revenue: 0}]}}, + {customer: {companies: [{revenue: 0}], revenues: [0], total: 0, shares: [0], shareSum: 0, dominant: false}}, + ], + [ + {customer: {companies: []}}, + {customer: {companies: [], revenues: [], total: 0, shares: [], shareSum: 0, dominant: false}}, + ], + ], +} + +// Members compare themselves against a root aggregate over a member computed. +{ + name: "member compares against an aggregate of a member computed", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", cost: "number"}}, + blocks: [ + {expression: "company.margin", value: "company.revenue - company.cost"}, + {expression: "customer.avgMargin", value: "avg(map(customer.companies, #.margin))"}, + {expression: "company.aboveAvg", value: "company.margin > customer.avgMargin"}, + {expression: "customer.aboveCount", value: "count(customer.companies, #.aboveAvg)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10, cost: 2}, {revenue: 10, cost: 8}, {revenue: 6, cost: 1}]}}, + {customer: {avgMargin: 5, aboveCount: 1, companies: [ + {revenue: 10, cost: 2, margin: 8, aboveAvg: true}, + {revenue: 10, cost: 8, margin: 2, aboveAvg: false}, + {revenue: 6, cost: 1, margin: 5, aboveAvg: false}, + ]}}, + ], + [ + {customer: {companies: [{revenue: 3, cost: 1}]}}, + {customer: {avgMargin: 2, aboveCount: 0, companies: [{revenue: 3, cost: 1, margin: 2, aboveAvg: false}]}}, + ], + [{customer: {companies: []}}, "!error: ExpressionFailed"], + ], +} + +// Aggregates over a nested level from a member computed, then over that computed at the root. +{ + name: "nested level aggregated twice", + policy: { + models: {customer: {companies: "company[]"}, company: {loans: "loan[]"}, loan: {amount: "number"}}, + blocks: [ + {expression: "company.exposure", value: "sum(map(company.loans, #.amount))"}, + {expression: "company.loanCount", value: "len(company.loans)"}, + {expression: "customer.exposure", value: "sum(map(customer.companies, #.exposure))"}, + {expression: "customer.avgLoan", value: "sum(map(customer.companies, #.loanCount)) == 0 ? 0 : customer.exposure / sum(map(customer.companies, #.loanCount))"}, + ], + }, + cases: [ + [ + {customer: {companies: [{loans: [{amount: 100}, {amount: 50}]}, {loans: [{amount: 30}]}]}}, + {customer: {companies: [{loans: [{amount: 100}, {amount: 50}], exposure: 150, loanCount: 2}, {loans: [{amount: 30}], exposure: 30, loanCount: 1}], exposure: 180, avgLoan: 60}}, + ], + [ + {customer: {companies: [{loans: []}, {loans: []}]}}, + {customer: {companies: [{loans: [], exposure: 0, loanCount: 0}, {loans: [], exposure: 0, loanCount: 0}], exposure: 0, avgLoan: 0}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], exposure: 0, avgLoan: 0}}], + ], +} + +// --------------------------------------------------------------------------- +// Nulls in collections. +// --------------------------------------------------------------------------- + +// Summing an optional member field is refused statically (INVALID_EXPRESSION); through the +// workspace, map keeps the nulls and sum fails on them at runtime. +{ + name: "sum over an optional member field is refused", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number?"}}, + blocks: [{expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}], + }, + cases: [ + [{customer: {companies: [{revenue: 1}, {revenue: 2}]}}, "!error: INVALID_EXPRESSION"], + [{customer: {companies: []}}, "!error: INVALID_EXPRESSION"], + ], +} + +{ + name: "sum over an optional member field through the workspace", + diagnostics: ["INVALID_EXPRESSION"], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number?"}}, + blocks: [{expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}], + }, + cases: [ + [{customer: {companies: [{revenue: 1}, {revenue: 2}]}}, {customer: {companies: [{revenue: 1}, {revenue: 2}], total: 3}}], + [{customer: {companies: [{revenue: 1}, {revenue: null}]}}, "!error"], + [{customer: {companies: [{revenue: 1}, {}]}}, "!error"], + ], +} + +// Filtering nulls out before aggregating. The type checker does not narrow the element type +// through `filter(..., #.revenue != null)`, so the policy carries INVALID_EXPRESSION errors and +// only runs through the workspace. +{ + name: "nulls filtered out before aggregating", + diagnostics: ["INVALID_EXPRESSION"], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number?"}}, + blocks: [ + {expression: "customer.known", value: "map(filter(customer.companies, #.revenue != null), #.revenue)"}, + {expression: "customer.total", value: "sum(customer.known)"}, + {expression: "customer.max", value: "len(customer.known) == 0 ? null : max(customer.known)"}, + {expression: "customer.unknown", value: "count(customer.companies, #.revenue == null)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 4}, {revenue: null}, {}, {revenue: 9}]}}, + {customer: {companies: [{revenue: 4}, {revenue: null}, {}, {revenue: 9}], known: [4, 9], total: 13, max: 9, unknown: 2}}, + ], + [ + {customer: {companies: [{revenue: null}, {}]}}, + {customer: {companies: [{revenue: null}, {}], known: [], total: 0, max: null, unknown: 2}}, + ], + [ + {customer: {companies: [{revenue: 0}]}}, + {customer: {companies: [{revenue: 0}], known: [0], total: 0, max: 0, unknown: 0}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], known: [], total: 0, max: null, unknown: 0}}], + ], +} + +// Defaults inside the map. +{ + name: "null fields defaulted inside the map", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number?"}}, + blocks: [ + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue ?? 0))"}, + {expression: "customer.min", value: "min(map(customer.companies, #.revenue ?? 0))"}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 5}, {}]}}, {customer: {companies: [{revenue: 5}, {}], total: 5, min: 0}}], + [{customer: {companies: [{revenue: -5}, {revenue: null}]}}, {customer: {companies: [{revenue: -5}, {revenue: null}], total: -5, min: -5}}], + [{customer: {companies: [{revenue: 2}]}}, {customer: {companies: [{revenue: 2}], total: 2, min: 2}}], + ], +} + +// Null items (not members with null fields) in the relationship array. +{ + name: "null items in the array under aggregates", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.len", value: "len(customer.companies)"}, + {expression: "customer.real", value: "filter(customer.companies, # != null)"}, + {expression: "customer.total", value: "sum(map(customer.real, #.revenue))"}, + {expression: "customer.revenues", value: "map(customer.companies, # == null ? null : #.revenue)"}, + ], + }, + cases: [ + [ + {customer: {companies: [null, {revenue: 2}, null, {revenue: 3}]}}, + {customer: {companies: [null, {revenue: 2}, null, {revenue: 3}], len: 4, real: [{revenue: 2}, {revenue: 3}], total: 5, revenues: [null, 2, null, 3]}}, + ], + [ + {customer: {companies: [null]}}, + {customer: {companies: [null], len: 1, real: [], total: 0, revenues: [null]}}, + ], + [ + {customer: {companies: [{revenue: 1}]}}, + {customer: {companies: [{revenue: 1}], len: 1, real: [{revenue: 1}], total: 1, revenues: [1]}}, + ], + ], +} + +// Optional relationships: absent and null arrays. +{ + name: "aggregates over an optional relationship", + policy: { + models: {customer: {companies: "company[]?"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.total", value: "sum(map(customer.companies ?? [], #.revenue))"}, + {expression: "customer.any", value: "some(customer.companies ?? [], #.revenue > 0)"}, + {expression: "customer.all", value: "all(customer.companies ?? [], #.revenue > 0)"}, + {expression: "customer.present", value: "customer.companies != null"}, + ], + }, + cases: [ + [{customer: {}}, {customer: {total: 0, any: false, all: true, present: false}}], + [{customer: {companies: null}}, {customer: {companies: null, total: 0, any: false, all: true, present: false}}], + [{customer: {companies: []}}, {customer: {companies: [], total: 0, any: false, all: true, present: true}}], + [{customer: {companies: [{revenue: 3}]}}, {customer: {companies: [{revenue: 3}], total: 3, any: true, all: true, present: true}}], + [{customer: {companies: [{revenue: 3}, {revenue: -3}]}}, {customer: {companies: [{revenue: 3}, {revenue: -3}], total: 0, any: true, all: false, present: true}}], + ], +} + +// --------------------------------------------------------------------------- +// Aggregates in other block kinds: match conditions, table inputs, assertion conditions. +// --------------------------------------------------------------------------- +{ + name: "aggregate inside match conditions", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", defaulted: "boolean"}}, + blocks: [ + {match: "customer.decision", arms: [ + ["some(customer.companies, #.defaulted)", "'decline'"], + ["sum(map(customer.companies, #.revenue)) >= 100", "'approve'"], + ["len(customer.companies) == 0", "'no-data'"], + ["", "'review'"], + ]}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 500, defaulted: true}]}}, {customer: {companies: [{revenue: 500, defaulted: true}], decision: "decline"}}], + [{customer: {companies: [{revenue: 60, defaulted: false}, {revenue: 40, defaulted: false}]}}, {customer: {companies: [{revenue: 60, defaulted: false}, {revenue: 40, defaulted: false}], decision: "approve"}}], + [{customer: {companies: [{revenue: 99, defaulted: false}]}}, {customer: {companies: [{revenue: 99, defaulted: false}], decision: "review"}}], + [{customer: {companies: []}}, {customer: {companies: [], decision: "no-data"}}], + ], +} + +{ + name: "aggregate as a table input", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}, + {expression: "customer.count", value: "len(customer.companies)"}, + {table: "grade", inputs: ["customer.total", "customer.count"], outputs: ["customer.grade"], rules: [ + [">= 1000", ">= 2", "'A'"], + [">= 1000", "", "'B'"], + ["> 0", "", "'C'"], + ["", "", "'D'"], + ]}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 600}, {revenue: 400}]}}, {customer: {companies: [{revenue: 600}, {revenue: 400}], total: 1000, count: 2, grade: "A"}}], + [{customer: {companies: [{revenue: 1000}]}}, {customer: {companies: [{revenue: 1000}], total: 1000, count: 1, grade: "B"}}], + [{customer: {companies: [{revenue: 1}, {revenue: 2}]}}, {customer: {companies: [{revenue: 1}, {revenue: 2}], total: 3, count: 2, grade: "C"}}], + [{customer: {companies: []}}, {customer: {companies: [], total: 0, count: 0, grade: "D"}}], + [{customer: {companies: [{revenue: -5}]}}, {customer: {companies: [{revenue: -5}], total: -5, count: 1, grade: "D"}}], + ], +} + +{ + name: "aggregate expression directly in a table input field", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {table: "size", inputs: ["len(customer.companies)"], outputs: ["customer.size"], rules: [ + ["0", "'none'"], + ["1", "'single'"], + ["", "'many'"], + ]}, + ], + }, + cases: [ + [{customer: {companies: []}}, {customer: {companies: [], size: "none"}}], + [{customer: {companies: [{revenue: 1}]}}, {customer: {companies: [{revenue: 1}], size: "single"}}], + [{customer: {companies: [{revenue: 1}, {revenue: 2}, {revenue: 3}]}}, {customer: {companies: [{revenue: 1}, {revenue: 2}, {revenue: 3}], size: "many"}}], + ], +} + +{ + name: "aggregates in assertion conditions", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", audited: "boolean"}}, + blocks: [ + {assertion: "customer.ok", conditions: [ + "len(customer.companies) > 0", + "all(customer.companies, #.audited)", + "sum(map(customer.companies, #.revenue)) > 10", + ]}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 20, audited: true}]}}, {customer: {companies: [{revenue: 20, audited: true}], ok: true}}], + [{customer: {companies: [{revenue: 20, audited: false}]}}, {customer: {companies: [{revenue: 20, audited: false}], ok: false}}], + [{customer: {companies: [{revenue: 5, audited: true}, {revenue: 5, audited: true}]}}, {customer: {companies: [{revenue: 5, audited: true}, {revenue: 5, audited: true}], ok: false}}], + [{customer: {companies: []}}, {customer: {companies: [], ok: false}}], + ], +} + +// A collect table on the parent gathering per-member values via an aggregate input. +{ + name: "collect table over aggregate flags", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", country: "string"}}, + blocks: [ + {expression: "customer.foreign", value: "count(customer.companies, #.country != 'US')"}, + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}, + {table: "flags", hit: "collect", inputs: ["customer.foreign", "customer.total"], outputs: ["customer.flags"], rules: [ + ["> 0", "", "'foreign'"], + ["", "> 1000", "'large'"], + ["0", "0", "'empty'"], + ]}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 2000, country: "DE"}]}}, {customer: {companies: [{revenue: 2000, country: "DE"}], foreign: 1, total: 2000, flags: ["foreign", "large"]}}], + [{customer: {companies: [{revenue: 5, country: "US"}]}}, {customer: {companies: [{revenue: 5, country: "US"}], foreign: 0, total: 5, flags: []}}], + [{customer: {companies: []}}, {customer: {companies: [], foreign: 0, total: 0, flags: ["empty"]}}], + ], +} + +// --------------------------------------------------------------------------- +// Other list operations over members: membership, flattening, mode. +// --------------------------------------------------------------------------- +{ + name: "list operations over member fields", + policy: { + models: {customer: {companies: "company[]"}, company: {country: "string", revenue: "number", tags: "string[]"}}, + blocks: [ + {expression: "customer.hasUS", value: "'US' in map(customer.companies, #.country)"}, + {expression: "customer.hasDE", value: "contains(map(customer.companies, #.country), 'DE')"}, + {expression: "customer.tags", value: "flatten(map(customer.companies, #.tags))"}, + {expression: "customer.tagCount", value: "sum(map(customer.companies, len(#.tags)))"}, + {expression: "customer.vip", value: "some(customer.companies, 'vip' in #.tags)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{country: "US", revenue: 3, tags: ["a", "vip"]}, {country: "DE", revenue: 1, tags: []}, {country: "US", revenue: 2, tags: ["b"]}]}}, + {customer: {companies: [{country: "US", revenue: 3, tags: ["a", "vip"]}, {country: "DE", revenue: 1, tags: []}, {country: "US", revenue: 2, tags: ["b"]}], hasUS: true, hasDE: true, tags: ["a", "vip", "b"], tagCount: 3, vip: true}}, + ], + [ + {customer: {companies: [{country: "FR", revenue: 0, tags: ["x", "x"]}]}}, + {customer: {companies: [{country: "FR", revenue: 0, tags: ["x", "x"]}], hasUS: false, hasDE: false, tags: ["x", "x"], tagCount: 2, vip: false}}, + ], + [ + {customer: {companies: []}}, + {customer: {companies: [], hasUS: false, hasDE: false, tags: [], tagCount: 0, vip: false}}, + ], + ], +} + +{ + name: "mode over member values", + policy: { + models: {customer: {companies: "company[]"}, company: {employees: "number"}}, + blocks: [{expression: "customer.typical", value: "mode(map(customer.companies, #.employees))"}], + }, + cases: [ + [{customer: {companies: [{employees: 5}, {employees: 3}, {employees: 5}]}}, {customer: {companies: [{employees: 5}, {employees: 3}, {employees: 5}], typical: 5}}], + [{customer: {companies: [{employees: 1}]}}, {customer: {companies: [{employees: 1}], typical: 1}}], + [{customer: {companies: []}}, "!error: ExpressionFailed"], + ], +} + +// Grouped aggregates built with nested closures. +{ + name: "per-group aggregates via nested closures", + policy: { + models: {customer: {companies: "company[]"}, company: {country: "string", revenue: "number"}}, + blocks: [ + {expression: "customer.byCountry", value: "map(['DE', 'US'] as k, {country: k, total: sum(map(filter(customer.companies, #.country == k), #.revenue))})"}, + ], + }, + cases: [ + [ + {customer: {companies: [{country: "US", revenue: 1}, {country: "DE", revenue: 5}, {country: "US", revenue: 2}]}}, + {customer: {companies: [{country: "US", revenue: 1}, {country: "DE", revenue: 5}, {country: "US", revenue: 2}], byCountry: [{country: "DE", total: 5}, {country: "US", total: 3}]}}, + "bug: the outer alias `k` read inside the inner filter closure is collected as a required input named `k`, and the evaluation fails with MissingRequiredInputs [k]", + ], + [{customer: {companies: [{country: "FR", revenue: 9}]}}, {customer: {companies: [{country: "FR", revenue: 9}], byCountry: [{country: "DE", total: 0}, {country: "US", total: 0}]}}, "bug: MissingRequiredInputs [k] for an outer closure alias"], + [{customer: {companies: []}}, {customer: {companies: [], byCountry: [{country: "DE", total: 0}, {country: "US", total: 0}]}}, "bug: MissingRequiredInputs [k] for an outer closure alias"], + ], +} + +// --------------------------------------------------------------------------- +// Precision and large collections. +// --------------------------------------------------------------------------- +{ + name: "exact decimal aggregates over members", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}, + {expression: "customer.isPoint3", value: "customer.total == 0.3"}, + {expression: "customer.avg", value: "avg(map(customer.companies, #.revenue))"}, + ], + }, + cases: [ + [{customer: {companies: [{revenue: 0.1}, {revenue: 0.2}]}}, {customer: {companies: [{revenue: 0.1}, {revenue: 0.2}], total: 0.3, isPoint3: true, avg: 0.15}}], + [{customer: {companies: [{revenue: 1}, {revenue: 1}, {revenue: 1}]}}, {customer: {companies: [{revenue: 1}, {revenue: 1}, {revenue: 1}], total: 3, isPoint3: false, avg: 1}}], + [{customer: {companies: [{revenue: 1}, {revenue: 2}, {revenue: 2}]}}, {customer: {companies: [{revenue: 1}, {revenue: 2}, {revenue: 2}], total: 5, isPoint3: false, avg: 1.6666666666666666666666666667}}], + [{customer: {companies: [{revenue: 0.1}, {revenue: 0.1}, {revenue: 0.1}]}}, {customer: {companies: [{revenue: 0.1}, {revenue: 0.1}, {revenue: 0.1}], total: 0.3, isPoint3: true, avg: 0.1}}], + ], +} + +{ + name: "aggregates over many members", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.double", value: "company.revenue * 2"}, + {expression: "customer.total", value: "sum(map(customer.companies, #.double))"}, + {expression: "customer.count", value: "count(customer.companies, #.double > 10)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 1}, {revenue: 2}, {revenue: 3}, {revenue: 4}, {revenue: 5}, {revenue: 6}, {revenue: 7}, {revenue: 8}, {revenue: 9}, {revenue: 10}]}}, + {customer: {companies: [ + {revenue: 1, double: 2}, {revenue: 2, double: 4}, {revenue: 3, double: 6}, {revenue: 4, double: 8}, {revenue: 5, double: 10}, + {revenue: 6, double: 12}, {revenue: 7, double: 14}, {revenue: 8, double: 16}, {revenue: 9, double: 18}, {revenue: 10, double: 20}, + ], total: 110, count: 5}}, + ], + [ + {customer: {companies: [{revenue: 100}]}}, + {customer: {companies: [{revenue: 100, double: 200}], total: 200, count: 1}}, + ], + ], +} + +// --------------------------------------------------------------------------- +// Aggregates over global arrays and computed globals. +// --------------------------------------------------------------------------- +{ + name: "aggregates over a global array relationship", + policy: { + models: {company: {revenue: "number"}}, + globals: {portfolio: {companies: "company[]", cap: "number"}}, + blocks: [ + {expression: "company.capped", value: "min([company.revenue, cap])"}, + {expression: "total", value: "sum(map(companies, #.capped))"}, + {expression: "anyCapped", value: "some(companies, #.revenue > cap)"}, + ], + }, + cases: [ + [ + {cap: 10, companies: [{revenue: 5}, {revenue: 50}]}, + {cap: 10, companies: [{revenue: 5, capped: 5}, {revenue: 50, capped: 10}], total: 15, anyCapped: true}, + ], + [{cap: 10, companies: []}, {cap: 10, companies: [], total: 0, anyCapped: false}], + [ + {cap: 0, companies: [{revenue: -1}]}, + {cap: 0, companies: [{revenue: -1, capped: -1}], total: -1, anyCapped: false}, + ], + ], +} diff --git a/core/engine/tests/spec/policy/23-member-blocks.json5 b/core/engine/tests/spec/policy/23-member-blocks.json5 new file mode 100644 index 00000000..1f01d206 --- /dev/null +++ b/core/engine/tests/spec/policy/23-member-blocks.json5 @@ -0,0 +1,923 @@ +// Member blocks: match, table and assertion blocks keyed on an iterated entity run once per +// member and write into that member, like the expression blocks of chapter 09. This chapter +// pins down each block kind per member, member blocks reading globals and the root entity, an +// entity type reached by two relationships, and the order in which member and root blocks run +// when they read each other. + +// --------------------------------------------------------------------------- +// Per-member match blocks. +// --------------------------------------------------------------------------- +{ + name: "per-member match with several arms", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", country: "string"}}, + blocks: [ + {match: "company.segment", arms: [ + ["company.country != 'US'", "'international'"], + ["company.revenue >= 1000", "'enterprise'"], + ["company.revenue >= 100", "'mid'"], + ["", "'small'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 5000, country: "DE"}, {revenue: 5000, country: "US"}, {revenue: 100, country: "US"}, {revenue: 99.99, country: "US"}]}}, + {customer: {companies: [ + {revenue: 5000, country: "DE", segment: "international"}, + {revenue: 5000, country: "US", segment: "enterprise"}, + {revenue: 100, country: "US", segment: "mid"}, + {revenue: 99.99, country: "US", segment: "small"}, + ]}}, + ], + [{customer: {companies: [{revenue: 0, country: "US"}]}}, {customer: {companies: [{revenue: 0, country: "US", segment: "small"}]}}], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +// Arms of a per-member match read the root entity and globals. +{ + name: "per-member match arms read root and globals", + policy: { + models: {customer: {vip: "boolean", companies: "company[]"}, company: {revenue: "number"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {match: "company.priority", arms: [ + ["customer.vip and company.revenue > threshold", "'urgent'"], + ["customer.vip", "'high'"], + ["company.revenue > threshold", "'normal'"], + ["", "'low'"], + ]}, + ], + }, + cases: [ + [ + {threshold: 10, customer: {vip: true, companies: [{revenue: 20}, {revenue: 5}]}}, + {threshold: 10, customer: {vip: true, companies: [{revenue: 20, priority: "urgent"}, {revenue: 5, priority: "high"}]}}, + ], + [ + {threshold: 10, customer: {vip: false, companies: [{revenue: 20}, {revenue: 10}]}}, + {threshold: 10, customer: {vip: false, companies: [{revenue: 20, priority: "normal"}, {revenue: 10, priority: "low"}]}}, + ], + [ + {threshold: -1, customer: {vip: false, companies: [{revenue: 0}]}}, + {threshold: -1, customer: {vip: false, companies: [{revenue: 0, priority: "normal"}]}}, + ], + ], +} + +// Arm values computed from the member, the root and globals. +{ + name: "per-member match arm values are expressions", + policy: { + models: {customer: {discount: "number", companies: "company[]"}, company: {price: "number", promo: "boolean"}}, + globals: {settings: {promoRate: "number"}}, + blocks: [ + {match: "company.net", arms: [ + ["company.promo", "company.price * (1 - promoRate)"], + ["", "company.price * (1 - customer.discount)"], + ]}, + ], + }, + cases: [ + [ + {promoRate: 0.5, customer: {discount: 0.1, companies: [{price: 10, promo: true}, {price: 10, promo: false}]}}, + {promoRate: 0.5, customer: {discount: 0.1, companies: [{price: 10, promo: true, net: 5}, {price: 10, promo: false, net: 9}]}}, + ], + [ + {promoRate: 0, customer: {discount: 0, companies: [{price: 3, promo: true}]}}, + {promoRate: 0, customer: {discount: 0, companies: [{price: 3, promo: true, net: 3}]}}, + ], + ], +} + +// A per-member match without a default arm: members matching no arm get null. +{ + name: "per-member match without a default", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {match: "company.flag", arms: [ + ["company.revenue > 100", "'big'"], + ["company.revenue < 0", "'loss'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 500}, {revenue: 50}, {revenue: -5}]}}, + {customer: {companies: [{revenue: 500, flag: "big"}, {revenue: 50, flag: null}, {revenue: -5, flag: "loss"}]}}, + ], + [{customer: {companies: [{revenue: 0}]}}, {customer: {companies: [{revenue: 0, flag: null}]}}], + ], +} + +// Per-member match reading another per-member computed, then aggregated. +{ + name: "per-member match on a member computed", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", cost: "number"}}, + blocks: [ + {expression: "company.margin", value: "company.revenue == 0 ? 0 : (company.revenue - company.cost) / company.revenue"}, + {match: "company.health", arms: [ + ["company.margin >= 0.3", "'good'"], + ["company.margin >= 0", "'ok'"], + ["", "'bad'"], + ]}, + {expression: "customer.bad", value: "count(customer.companies, #.health == 'bad')"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10, cost: 5}, {revenue: 10, cost: 9}, {revenue: 10, cost: 20}, {revenue: 0, cost: 1}]}}, + {customer: {companies: [ + {revenue: 10, cost: 5, margin: 0.5, health: "good"}, + {revenue: 10, cost: 9, margin: 0.1, health: "ok"}, + {revenue: 10, cost: 20, margin: -1, health: "bad"}, + {revenue: 0, cost: 1, margin: 0, health: "ok"}, + ], bad: 1}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], bad: 0}}], + ], +} + +// --------------------------------------------------------------------------- +// Per-member decision tables. +// --------------------------------------------------------------------------- +{ + name: "per-member table with several inputs and outputs", + policy: { + models: {customer: {companies: "company[]"}, company: {country: "string", employees: "number"}}, + blocks: [ + {table: "classify", inputs: ["company.country", "company.employees"], outputs: ["company.size", "company.fee"], rules: [ + ["'US'", ">= 500", "'large'", "100"], + ["'US'", "", "'small'", "10"], + ["", ">= 500", "'large'", "150"], + ["", "", "'small'", "15"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{country: "US", employees: 500}, {country: "US", employees: 499}, {country: "DE", employees: 1000}, {country: "DE", employees: 1}]}}, + {customer: {companies: [ + {country: "US", employees: 500, size: "large", fee: 100}, + {country: "US", employees: 499, size: "small", fee: 10}, + {country: "DE", employees: 1000, size: "large", fee: 150}, + {country: "DE", employees: 1, size: "small", fee: 15}, + ]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +// A per-member table where some members match no rule: their outputs are null. +{ + name: "per-member table with unmatched members", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {table: "band", inputs: ["company.revenue"], outputs: ["company.band"], rules: [ + ["[0..100)", "'low'"], + ["[100..1000]", "'high'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 50}, {revenue: 100}, {revenue: 5000}, {revenue: -1}]}}, + {customer: {companies: [{revenue: 50, band: "low"}, {revenue: 100, band: "high"}, {revenue: 5000, band: null}, {revenue: -1, band: null}]}}, + ], + [{customer: {companies: [{revenue: 1000}]}}, {customer: {companies: [{revenue: 1000, band: "high"}]}}], + ], +} + +// A per-member table whose inputs read the root entity and a global. +{ + name: "per-member table inputs read root and globals", + policy: { + models: {customer: {region: "string", companies: "company[]"}, company: {revenue: "number"}}, + globals: {settings: {season: "string"}}, + blocks: [ + {table: "rate", inputs: ["customer.region", "season", "company.revenue"], outputs: ["company.rate"], rules: [ + ["'EU'", "'peak'", "> 100", "0.3"], + ["'EU'", "", "", "0.2"], + ["", "'peak'", "", "0.15"], + ["", "", "", "0.1"], + ]}, + ], + }, + cases: [ + [ + {season: "peak", customer: {region: "EU", companies: [{revenue: 200}, {revenue: 50}]}}, + {season: "peak", customer: {region: "EU", companies: [{revenue: 200, rate: 0.3}, {revenue: 50, rate: 0.2}]}}, + ], + [ + {season: "peak", customer: {region: "US", companies: [{revenue: 200}]}}, + {season: "peak", customer: {region: "US", companies: [{revenue: 200, rate: 0.15}]}}, + ], + [ + {season: "low", customer: {region: "US", companies: [{revenue: 200}, {revenue: 1}]}}, + {season: "low", customer: {region: "US", companies: [{revenue: 200, rate: 0.1}, {revenue: 1, rate: 0.1}]}}, + ], + ], +} + +// Per-member table output expressions combine member, root and global values. +{ + name: "per-member table output expressions", + policy: { + models: {customer: {multiplier: "number", companies: "company[]"}, company: {revenue: "number"}}, + globals: {settings: {base: "number"}}, + blocks: [ + {table: "score", inputs: ["company.revenue"], outputs: ["company.score"], rules: [ + ["> 100", "base + company.revenue * customer.multiplier"], + ["", "base"], + ]}, + ], + }, + cases: [ + [ + {base: 1, customer: {multiplier: 2, companies: [{revenue: 200}, {revenue: 5}]}}, + {base: 1, customer: {multiplier: 2, companies: [{revenue: 200, score: 401}, {revenue: 5, score: 1}]}}, + ], + [ + {base: 0, customer: {multiplier: 0.5, companies: [{revenue: 101}]}}, + {base: 0, customer: {multiplier: 0.5, companies: [{revenue: 101, score: 50.5}]}}, + ], + ], +} + +// A per-member collect table: each member gathers its own list. +{ + name: "per-member collect table", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", country: "string"}}, + blocks: [ + {table: "flags", hit: "collect", inputs: ["company.revenue", "company.country"], outputs: ["company.flags"], rules: [ + ["> 1000", "", "'large'"], + ["", "'US'", "'domestic'"], + ["< 0", "", "'loss'"], + ]}, + {expression: "customer.allFlags", value: "flatMap(customer.companies, #.flags)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 2000, country: "US"}, {revenue: 5, country: "DE"}, {revenue: -1, country: "US"}]}}, + {customer: {companies: [ + {revenue: 2000, country: "US", flags: ["large", "domestic"]}, + {revenue: 5, country: "DE", flags: []}, + {revenue: -1, country: "US", flags: ["domestic", "loss"]}, + ], allFlags: ["large", "domestic", "domestic", "loss"]}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], allFlags: []}}], + ], +} + +// A per-member table with a per-column collect next to a first-hit column. +{ + name: "per-member table mixing collect and first-hit columns", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {table: "mixed", inputs: ["company.revenue"], outputs: ["company.tags[]", "company.tier"], rules: [ + ["> 100", "'big'", "'gold'"], + ["> 10", "'medium'", "'silver'"], + ["", "'any'", "'bronze'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 500}, {revenue: 50}, {revenue: 1}]}}, + {customer: {companies: [ + {revenue: 500, tags: ["big", "medium", "any"], tier: "gold"}, + {revenue: 50, tags: ["medium", "any"], tier: "silver"}, + {revenue: 1, tags: ["any"], tier: "bronze"}, + ]}}, + ], + ], +} + +// Two per-member tables chained: the second reads the first's output. +{ + name: "chained per-member tables", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {table: "tier", inputs: ["company.revenue"], outputs: ["company.tier"], rules: [ + ["> 100", "'gold'"], + ["", "'basic'"], + ]}, + {table: "limit", inputs: ["company.tier"], outputs: ["company.limit"], rules: [ + ["'gold'", "company.revenue * 10"], + ["'basic'", "100"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 200}, {revenue: 3}]}}, + {customer: {companies: [{revenue: 200, tier: "gold", limit: 2000}, {revenue: 3, tier: "basic", limit: 100}]}}, + ], + [{customer: {companies: [{revenue: 101}]}}, {customer: {companies: [{revenue: 101, tier: "gold", limit: 1010}]}}], + ], +} + +// --------------------------------------------------------------------------- +// Per-member assertion blocks. +// --------------------------------------------------------------------------- +{ + name: "per-member assertion with an and chain", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", audited: "boolean", country: "string"}}, + blocks: [ + {assertion: "company.eligible", conditions: ["company.revenue > 10", "company.audited", "company.country == 'US'"]}, + ], + }, + cases: [ + [ + {customer: {companies: [ + {revenue: 20, audited: true, country: "US"}, + {revenue: 5, audited: true, country: "US"}, + {revenue: 20, audited: false, country: "US"}, + {revenue: 20, audited: true, country: "DE"}, + ]}}, + {customer: {companies: [ + {revenue: 20, audited: true, country: "US", eligible: true}, + {revenue: 5, audited: true, country: "US", eligible: false}, + {revenue: 20, audited: false, country: "US", eligible: false}, + {revenue: 20, audited: true, country: "DE", eligible: false}, + ]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +{ + name: "per-member assertion with or and groups reading root and globals", + policy: { + models: {customer: {vip: "boolean", companies: "company[]"}, company: {revenue: "number", audited: "boolean"}}, + globals: {settings: {minRevenue: "number"}}, + blocks: [ + {assertion: "company.ok", conditions: [ + ["or", "customer.vip"], + ["and", "company.revenue >= minRevenue", 1], + ["and", "company.audited", 1], + ]}, + ], + }, + cases: [ + [ + {minRevenue: 10, customer: {vip: true, companies: [{revenue: 0, audited: false}]}}, + {minRevenue: 10, customer: {vip: true, companies: [{revenue: 0, audited: false, ok: true}]}}, + ], + [ + {minRevenue: 10, customer: {vip: false, companies: [{revenue: 10, audited: true}, {revenue: 10, audited: false}, {revenue: 9, audited: true}]}}, + {minRevenue: 10, customer: {vip: false, companies: [{revenue: 10, audited: true, ok: true}, {revenue: 10, audited: false, ok: false}, {revenue: 9, audited: true, ok: false}]}}, + ], + ], +} + +// A non-boolean condition counts as false, per member. +{ + name: "per-member assertion on a nullable field", + policy: { + models: {customer: {companies: "company[]"}, company: {audited: "boolean?"}}, + blocks: [{assertion: "company.ok", conditions: ["company.audited"]}], + }, + cases: [ + [ + {customer: {companies: [{audited: true}, {audited: false}, {audited: null}, {}]}}, + {customer: {companies: [{audited: true, ok: true}, {audited: false, ok: false}, {audited: null, ok: false}, {ok: false}]}}, + ], + ], +} + +// A root assertion over per-member assertions. +{ + name: "root assertion over member assertions", + policy: { + models: {customer: {age: "number", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {assertion: "company.ok", conditions: ["company.revenue > 0"]}, + {assertion: "customer.ok", conditions: ["customer.age >= 18", "all(customer.companies, #.ok)"]}, + ], + }, + cases: [ + [ + {customer: {age: 30, companies: [{revenue: 1}, {revenue: 2}]}}, + {customer: {age: 30, ok: true, companies: [{revenue: 1, ok: true}, {revenue: 2, ok: true}]}}, + ], + [ + {customer: {age: 30, companies: [{revenue: 1}, {revenue: 0}]}}, + {customer: {age: 30, ok: false, companies: [{revenue: 1, ok: true}, {revenue: 0, ok: false}]}}, + ], + [ + {customer: {age: 10, companies: []}}, + {customer: {age: 10, ok: false, companies: []}}, + ], + [ + {customer: {age: 18, companies: []}}, + {customer: {age: 18, ok: true, companies: []}}, + ], + ], +} + +// --------------------------------------------------------------------------- +// Member blocks reading the root entity and globals, input and computed. +// --------------------------------------------------------------------------- +{ + name: "member blocks read a computed root property and a computed global", + policy: { + models: {customer: {income: "number", companies: "company[]"}, company: {debt: "number"}}, + globals: {settings: {rate: "number"}}, + blocks: [ + {expression: "adjustedRate", value: "rate * 2"}, + {expression: "customer.capacity", value: "customer.income * adjustedRate"}, + {expression: "company.covered", value: "company.debt <= customer.capacity"}, + ], + }, + cases: [ + [ + {rate: 0.25, customer: {income: 100, companies: [{debt: 50}, {debt: 51}]}}, + {rate: 0.25, adjustedRate: 0.5, customer: {income: 100, capacity: 50, companies: [{debt: 50, covered: true}, {debt: 51, covered: false}]}}, + ], + [ + {rate: 0, customer: {income: 100, companies: [{debt: 0}, {debt: 1}]}}, + {rate: 0, adjustedRate: 0, customer: {income: 100, capacity: 0, companies: [{debt: 0, covered: true}, {debt: 1, covered: false}]}}, + ], + ], +} + +// A member block reading root properties that are missing: required root inputs. +{ + name: "member block reading a missing root input", + policy: { + models: {customer: {rate: "number", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.fee", value: "company.revenue * customer.rate"}], + }, + cases: [ + [{customer: {rate: 2, companies: [{revenue: 3}]}}, {customer: {rate: 2, companies: [{revenue: 3, fee: 6}]}}], + [{customer: {companies: [{revenue: 3}]}}, "!error: MissingRequiredInputs"], + [{customer: {rate: null, companies: [{revenue: 3}]}}, "!error: MissingRequiredInputs"], + ], +} + +// Optional root input with a default inside a member block. +{ + name: "member block with an optional root input", + policy: { + models: {customer: {rate: "number?", companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.fee", value: "company.revenue * (customer.rate ?? 1)"}], + }, + cases: [ + [{customer: {rate: 2, companies: [{revenue: 3}, {revenue: 4}]}}, {customer: {rate: 2, companies: [{revenue: 3, fee: 6}, {revenue: 4, fee: 8}]}}], + [{customer: {companies: [{revenue: 3}]}}, {customer: {companies: [{revenue: 3, fee: 3}]}}], + [{customer: {rate: null, companies: [{revenue: 3}]}}, {customer: {rate: null, companies: [{revenue: 3, fee: 3}]}}], + ], +} + +// Member blocks reading a global array (not the member's own relationship). +{ + name: "member block reads a global list", + policy: { + models: {customer: {companies: "company[]"}, company: {country: "string"}}, + globals: {settings: {sanctioned: "string[]"}}, + blocks: [ + {expression: "company.blocked", value: "company.country in sanctioned"}, + {expression: "customer.blocked", value: "some(customer.companies, #.blocked)"}, + ], + }, + cases: [ + [ + {sanctioned: ["XX", "YY"], customer: {companies: [{country: "US"}, {country: "YY"}]}}, + {sanctioned: ["XX", "YY"], customer: {blocked: true, companies: [{country: "US", blocked: false}, {country: "YY", blocked: true}]}}, + ], + [ + {sanctioned: [], customer: {companies: [{country: "XX"}]}}, + {sanctioned: [], customer: {blocked: false, companies: [{country: "XX", blocked: false}]}}, + ], + ], +} + +// A member block reading other members of its own relationship through the root. +{ + name: "member block reads its siblings", + policy: { + models: {customer: {companies: "company[]"}, company: {name: "string", revenue: "number"}}, + blocks: [ + {expression: "company.rank", value: "count(customer.companies, #.revenue > company.revenue) + 1"}, + {expression: "company.peers", value: "len(customer.companies) - 1"}, + ], + }, + cases: [ + [ + {customer: {companies: [{name: "a", revenue: 5}, {name: "b", revenue: 50}, {name: "c", revenue: 20}]}}, + {customer: {companies: [ + {name: "a", revenue: 5, rank: 3, peers: 2}, + {name: "b", revenue: 50, rank: 1, peers: 2}, + {name: "c", revenue: 20, rank: 2, peers: 2}, + ]}}, + ], + [ + {customer: {companies: [{name: "a", revenue: 5}, {name: "b", revenue: 5}]}}, + {customer: {companies: [{name: "a", revenue: 5, rank: 1, peers: 1}, {name: "b", revenue: 5, rank: 1, peers: 1}]}}, + ], + [{customer: {companies: [{name: "a", revenue: 0}]}}, {customer: {companies: [{name: "a", revenue: 0, rank: 1, peers: 0}]}}], + ], +} + +// Members of a global array read a root entity and a global scalar. +{ + name: "global array members read a root entity", + policy: { + models: {customer: {country: "string"}, company: {country: "string", revenue: "number"}}, + globals: {market: {companies: "company[]", fx: "number"}}, + blocks: [ + {match: "company.relation", arms: [ + ["company.country == customer.country", "'local'"], + ["", "'foreign'"], + ]}, + {expression: "company.converted", value: "company.revenue * fx"}, + ], + }, + cases: [ + [ + {fx: 2, customer: {country: "US"}, companies: [{country: "US", revenue: 1}, {country: "DE", revenue: 3}]}, + {fx: 2, customer: {country: "US"}, companies: [{country: "US", revenue: 1, relation: "local", converted: 2}, {country: "DE", revenue: 3, relation: "foreign", converted: 6}]}, + ], + [ + {fx: 1, customer: {country: "FR"}, companies: []}, + {fx: 1, customer: {country: "FR"}, companies: []}, + ], + ], +} + +// A per-member table whose input is an aggregate over the siblings. +{ + name: "per-member table input compares against siblings", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {table: "position", inputs: ["company.revenue / max(map(customer.companies, #.revenue))"], outputs: ["company.position"], rules: [ + ["1", "'top'"], + [">= 0.5", "'upper'"], + ["", "'lower'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10}, {revenue: 6}, {revenue: 2}]}}, + {customer: {companies: [{revenue: 10, position: "top"}, {revenue: 6, position: "upper"}, {revenue: 2, position: "lower"}]}}, + ], + [ + {customer: {companies: [{revenue: 4}, {revenue: 4}]}}, + {customer: {companies: [{revenue: 4, position: "top"}, {revenue: 4, position: "top"}]}}, + ], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +// --------------------------------------------------------------------------- +// Order of evaluation across members. +// --------------------------------------------------------------------------- + +// A member block reads a computed property of its siblings: every member's first computed +// must exist before any member's second computed runs. +{ + name: "member block reads a sibling computed", + policy: { + models: {customer: {companies: "company[]"}, company: {name: "string", revenue: "number", cost: "number"}}, + blocks: [ + {expression: "company.profit", value: "company.revenue - company.cost"}, + {expression: "company.rank", value: "count(customer.companies, #.profit > company.profit) + 1"}, + ], + }, + cases: [ + [ + {customer: {companies: [{name: "a", revenue: 10, cost: 9}, {name: "b", revenue: 10, cost: 0}, {name: "c", revenue: 10, cost: 5}]}}, + {customer: {companies: [ + {name: "a", revenue: 10, cost: 9, profit: 1, rank: 3}, + {name: "b", revenue: 10, cost: 0, profit: 10, rank: 1}, + {name: "c", revenue: 10, cost: 5, profit: 5, rank: 2}, + ]}}, + ], + [ + {customer: {companies: [{name: "a", revenue: 1, cost: 2}]}}, + {customer: {companies: [{name: "a", revenue: 1, cost: 2, profit: -1, rank: 1}]}}, + ], + ], +} + +// The same, with the reading block declared first. +{ + name: "sibling computed read declared before its writer", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", cost: "number"}}, + blocks: [ + {expression: "company.best", value: "company.profit == max(map(customer.companies, #.profit))"}, + {expression: "company.profit", value: "company.revenue - company.cost"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10, cost: 9}, {revenue: 10, cost: 0}]}}, + {customer: {companies: [{revenue: 10, cost: 9, profit: 1, best: false}, {revenue: 10, cost: 0, profit: 10, best: true}]}}, + ], + [ + {customer: {companies: [{revenue: 3, cost: 1}, {revenue: 4, cost: 2}]}}, + {customer: {companies: [{revenue: 3, cost: 1, profit: 2, best: true}, {revenue: 4, cost: 2, profit: 2, best: true}]}}, + ], + ], +} + +// A sibling read through a per-member match and table. +{ + name: "member match reads a sibling table output", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {table: "tier", inputs: ["company.revenue"], outputs: ["company.tier"], rules: [ + ["> 100", "'gold'"], + ["", "'basic'"], + ]}, + {match: "company.status", arms: [ + ["company.tier == 'gold'", "'leader'"], + ["some(customer.companies, #.tier == 'gold')", "'follower'"], + ["", "'alone'"], + ]}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 5}, {revenue: 500}]}}, + {customer: {companies: [{revenue: 5, tier: "basic", status: "follower"}, {revenue: 500, tier: "gold", status: "leader"}]}}, + ], + [ + {customer: {companies: [{revenue: 5}, {revenue: 6}]}}, + {customer: {companies: [{revenue: 5, tier: "basic", status: "alone"}, {revenue: 6, tier: "basic", status: "alone"}]}}, + ], + ], +} + +// Member -> root -> member -> root, all through computed properties. +{ + name: "member and root blocks interleave", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "customer.flagged", value: "count(customer.companies, #.outlier)"}, + {expression: "company.outlier", value: "company.deviation > 10"}, + {expression: "company.deviation", value: "abs(company.revenue - customer.mean)"}, + {expression: "customer.mean", value: "sum(map(customer.companies, #.revenue)) / len(customer.companies)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 10}, {revenue: 12}, {revenue: 38}]}}, + {customer: {mean: 20, flagged: 1, companies: [ + {revenue: 10, deviation: 10, outlier: false}, + {revenue: 12, deviation: 8, outlier: false}, + {revenue: 38, deviation: 18, outlier: true}, + ]}}, + ], + [ + {customer: {companies: [{revenue: 0}, {revenue: 100}]}}, + {customer: {mean: 50, flagged: 2, companies: [{revenue: 0, deviation: 50, outlier: true}, {revenue: 100, deviation: 50, outlier: true}]}}, + ], + ], +} + +// One failing member fails the evaluation, wherever it sits in the array. +{ + name: "a failing member fails the evaluation", + policy: { + models: {customer: {companies: "company[]"}, company: {code: "string"}}, + blocks: [{expression: "company.n", value: "number(company.code)"}], + }, + cases: [ + [{customer: {companies: [{code: "1"}, {code: "2"}]}}, {customer: {companies: [{code: "1", n: 1}, {code: "2", n: 2}]}}], + [{customer: {companies: [{code: "x"}, {code: "2"}]}}, "!error: ExpressionFailed"], + [{customer: {companies: [{code: "1"}, {code: "x"}]}}, "!error: ExpressionFailed"], + [{customer: {companies: []}}, {customer: {companies: []}}], + ], +} + +// Member order is the array order: per-member writes keep positions. +{ + name: "member writes keep array positions", + policy: { + models: {customer: {companies: "company[]"}, company: {id: "string"}}, + blocks: [ + {expression: "company.tag", value: "'#' + company.id"}, + {expression: "customer.order", value: "map(customer.companies, #.tag)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{id: "c"}, {id: "a"}, {id: "b"}, {id: "a"}]}}, + {customer: {companies: [{id: "c", tag: "#c"}, {id: "a", tag: "#a"}, {id: "b", tag: "#b"}, {id: "a", tag: "#a"}], order: ["#c", "#a", "#b", "#a"]}}, + ], + [{customer: {companies: [{id: ""}]}}, {customer: {companies: [{id: "", tag: "#"}], order: ["#"]}}], + ], +} + +// Per-member blocks writing nested paths inside the member. +{ + name: "per-member nested write paths", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", cost: "number"}}, + blocks: [ + {expression: "company.stats.profit", value: "company.revenue - company.cost"}, + {match: "company.stats.label", arms: [["company.stats.profit > 0", "'profit'"], ["", "'loss'"]]}, + {expression: "customer.labels", value: "map(customer.companies, #.stats.label)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 5, cost: 1}, {revenue: 1, cost: 5}]}}, + {customer: {companies: [ + {revenue: 5, cost: 1, stats: {profit: 4, label: "profit"}}, + {revenue: 1, cost: 5, stats: {profit: -4, label: "loss"}}, + ], labels: ["profit", "loss"]}}, + ], + [{customer: {companies: []}}, {customer: {companies: [], labels: []}}], + ], +} + +// --------------------------------------------------------------------------- +// One entity type reached by two relationships. An entity has a single source path (the first +// relationship targeting it, models sorted by name, properties in order), so per-member +// blocks run over that relationship only. +// --------------------------------------------------------------------------- +{ + name: "two relationships of one entity on the root", + policy: { + models: {customer: {companies: "company[]", subsidiaries: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + cases: [ + [ + {customer: {companies: [{revenue: 200}], subsidiaries: [{revenue: 300}, {revenue: 1}]}}, + {customer: {companies: [{revenue: 200, big: true}], subsidiaries: [{revenue: 300, big: true}, {revenue: 1, big: false}]}}, + "bug: per-member blocks run only over the entity's first relationship (customer.companies); members of customer.subsidiaries are the same entity type and are not evaluated", + ], + [ + {customer: {companies: [], subsidiaries: [{revenue: 300}]}}, + {customer: {companies: [], subsidiaries: [{revenue: 300, big: true}]}}, + "bug: members of the second relationship of the same entity type are not evaluated", + ], + [ + {customer: {companies: [{revenue: 1}], subsidiaries: []}}, + {customer: {companies: [{revenue: 1, big: false}], subsidiaries: []}}, + ], + ], +} + +// Aggregating a member computed over the second relationship: the computed property exists only +// on the first relationship's members, so the type checker reports UNDEFINED_VARIABLE and the +// policy is refused. +{ + name: "aggregate over the second relationship's member computed", + policy: { + models: {customer: {companies: "company[]", subsidiaries: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "customer.bigCompanies", value: "count(customer.companies, #.big)"}, + {expression: "customer.bigSubsidiaries", value: "count(customer.subsidiaries, #.big)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 200}], subsidiaries: [{revenue: 300}]}}, + {customer: {companies: [{revenue: 200, big: true}], subsidiaries: [{revenue: 300, big: true}], bigCompanies: 1, bigSubsidiaries: 1}}, + "bug: the computed `big` is attached only to customer.companies members; reading it on customer.subsidiaries is UNDEFINED_VARIABLE and the policy is refused", + ], + [ + {customer: {companies: [], subsidiaries: []}}, + {customer: {companies: [], subsidiaries: [], bigCompanies: 0, bigSubsidiaries: 0}}, + "bug: refused with UNDEFINED_VARIABLE for customer.subsidiaries[].big", + ], + ], +} + +// A single and an array relationship to the same entity type on the root. +{ + name: "single and array relationship of one entity type", + policy: { + models: {customer: {main: "company", others: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + cases: [ + [ + {customer: {main: {revenue: 500}, others: [{revenue: 1}, {revenue: 200}]}}, + {customer: {main: {revenue: 500, big: true}, others: [{revenue: 1, big: false}, {revenue: 200, big: true}]}}, + "bug: only the first relationship (customer.main) is evaluated; members of customer.others are not", + ], + [ + {customer: {main: {revenue: 5}, others: []}}, + {customer: {main: {revenue: 5, big: false}, others: []}}, + ], + ], +} + +// Two owners of the same entity type: a root entity and a global. The source is chosen by model +// name, so which relationship is evaluated depends on how the models are named. +{ + name: "entity reached from the root and from a global", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + globals: {market: {competitors: "company[]"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + cases: [ + [ + {competitors: [{revenue: 1000}], customer: {companies: [{revenue: 5}]}}, + {competitors: [{revenue: 1000, big: true}], customer: {companies: [{revenue: 5, big: false}]}}, + "bug: only one relationship per entity type is evaluated", + ], + ], +} + +// Two different root entities, each owning an array of the same entity type. +{ + name: "two root entities owning the same member type", + policy: { + models: {buyer: {companies: "company[]"}, seller: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "company.big", value: "company.revenue > 100"}], + }, + cases: [ + [ + {buyer: {companies: [{revenue: 500}]}, seller: {companies: [{revenue: 5}, {revenue: 600}]}}, + {buyer: {companies: [{revenue: 500, big: true}]}, seller: {companies: [{revenue: 5, big: false}, {revenue: 600, big: true}]}}, + "bug: only buyer.companies (first model by name) is evaluated; seller.companies members are not", + ], + [ + {buyer: {companies: []}, seller: {companies: []}}, + {buyer: {companies: []}, seller: {companies: []}}, + ], + ], +} + +// The workaround that works today: distinct entity types per relationship. +{ + name: "distinct entity types per relationship", + policy: { + models: { + customer: {companies: "company[]", subsidiaries: "subsidiary[]"}, + company: {revenue: "number"}, + subsidiary: {revenue: "number"}, + }, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "subsidiary.big", value: "subsidiary.revenue > 100"}, + {expression: "customer.bigCount", value: "count(customer.companies, #.big) + count(customer.subsidiaries, #.big)"}, + ], + }, + cases: [ + [ + {customer: {companies: [{revenue: 200}], subsidiaries: [{revenue: 300}, {revenue: 1}]}}, + {customer: {companies: [{revenue: 200, big: true}], subsidiaries: [{revenue: 300, big: true}, {revenue: 1, big: false}], bigCount: 2}}, + ], + [ + {customer: {companies: [], subsidiaries: []}}, + {customer: {companies: [], subsidiaries: [], bigCount: 0}}, + ], + ], +} + +// --------------------------------------------------------------------------- +// Goals on member blocks. +// --------------------------------------------------------------------------- +{ + name: "goals on per-member match and table blocks", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [ + {table: "tier", inputs: ["company.revenue"], outputs: ["company.tier"], rules: [["> 100", "'gold'"], ["", "'basic'"]]}, + {match: "company.label", arms: [["company.revenue > 10", "'some'"], ["", "'none'"]]}, + {assertion: "company.ok", conditions: ["company.tier == 'gold'"]}, + ], + }, + cases: [ + { + input: {customer: {companies: [{revenue: 200}, {revenue: 5}]}}, + goals: ["company.label"], + output: {customer: {companies: [{revenue: 200, label: "some"}, {revenue: 5, label: "none"}]}}, + }, + { + input: {customer: {companies: [{revenue: 200}, {revenue: 5}]}}, + goals: ["company.ok"], + output: {customer: {companies: [{revenue: 200, tier: "gold", ok: true}, {revenue: 5, tier: "basic", ok: false}]}}, + }, + { + input: {customer: {companies: [{revenue: 200}]}}, + goals: ["company.tier"], + output: {customer: {companies: [{revenue: 200, tier: "gold"}]}}, + }, + ], +} diff --git a/core/engine/tests/spec/policy/24-realistic-kyc.json5 b/core/engine/tests/spec/policy/24-realistic-kyc.json5 new file mode 100644 index 00000000..34802a1b --- /dev/null +++ b/core/engine/tests/spec/policy/24-realistic-kyc.json5 @@ -0,0 +1,698 @@ +// Realistic know-your-customer policies: document checks, individual risk scoring, sanctions and +// PEP screening, business ownership (KYB), country profiles by reference, transaction monitoring, +// goals and dictionaries. Each suite combines several block kinds over related entities and runs +// valid, boundary, missing and invalid data. Evaluation time is fixed at 2025-03-20T10:15:30Z. + +// --- Identity documents ------------------------------------------------------------------------ +// Per-document computeds (expiry, identity kind, usability assertion) feed customer aggregates and +// a status match. A document without an expiry never expires; a member missing `verified` reads +// null and the assertion counts it as false. + +{ + name: "kyc document checks", + policy: { + models: { + customer: {country: "string", documents: "document[]"}, + document: {kind: "string(passport|idcard|license|utility)", expires: "date?", verified: "boolean", issuer: "string"}, + }, + blocks: [ + {expression: "document.expired", value: "(document.expires ?? d('9999-12-31')) < d()"}, + {expression: "document.identity", value: "document.kind != 'utility'"}, + {assertion: "document.usable", conditions: ["document.verified", "not document.expired"]}, + {expression: "customer.validIds", value: "count(customer.documents, #.usable and #.identity)"}, + {expression: "customer.addressProof", value: "some(customer.documents, #.kind == 'utility' and #.usable)"}, + {expression: "customer.foreignDocs", value: "count(customer.documents, #.issuer != customer.country)"}, + {match: "customer.docStatus", arms: [ + ["len(customer.documents) == 0", "'none'"], + ["customer.validIds > 0 and customer.addressProof", "'complete'"], + ["customer.validIds > 0", "'address-missing'"], + ["", "'id-missing'"], + ]}, + ], + }, + cases: [ + [ + {customer: {country: "NO", documents: [{kind: "passport", expires: "2030-01-01", verified: true, issuer: "NO"}, {kind: "utility", verified: true, issuer: "NO"}]}}, + {customer: {country: "NO", validIds: 1, addressProof: true, foreignDocs: 0, docStatus: "complete", documents: [ + {kind: "passport", expires: "2030-01-01", verified: true, issuer: "NO", expired: false, identity: true, usable: true}, + {kind: "utility", verified: true, issuer: "NO", expired: false, identity: false, usable: true}, + ]}}, + ], + [ + {customer: {country: "NO", documents: [{kind: "passport", expires: "2025-03-19", verified: true, issuer: "NO"}]}}, + {customer: {country: "NO", validIds: 0, addressProof: false, foreignDocs: 0, docStatus: "id-missing", documents: [ + {kind: "passport", expires: "2025-03-19", verified: true, issuer: "NO", expired: true, identity: true, usable: false}, + ]}}, + ], + // Expiry boundary: a date-only expiry is midnight, so today's date is already expired. + [ + {customer: {country: "NO", documents: [{kind: "idcard", expires: "2025-03-20", verified: true, issuer: "NO"}, {kind: "license", expires: "2025-03-21", verified: true, issuer: "SE"}]}}, + {customer: {country: "NO", validIds: 1, addressProof: false, foreignDocs: 1, docStatus: "address-missing", documents: [ + {kind: "idcard", expires: "2025-03-20", verified: true, issuer: "NO", expired: true, identity: true, usable: false}, + {kind: "license", expires: "2025-03-21", verified: true, issuer: "SE", expired: false, identity: true, usable: true}, + ]}}, + ], + [ + {customer: {country: "NO", documents: [{kind: "passport", expires: "2025-03-20T10:15:31Z", verified: true, issuer: "NO"}]}}, + {customer: {country: "NO", validIds: 1, addressProof: false, foreignDocs: 0, docStatus: "address-missing", documents: [ + {kind: "passport", expires: "2025-03-20T10:15:31Z", verified: true, issuer: "NO", expired: false, identity: true, usable: true}, + ]}}, + ], + [{customer: {country: "SE", documents: []}}, {customer: {country: "SE", documents: [], validIds: 0, addressProof: false, foreignDocs: 0, docStatus: "none"}}], + [ + {customer: {country: "DE", documents: [{kind: "passport", expires: "2031-01-01", verified: false, issuer: "DE"}, {kind: "utility", verified: true, issuer: "DE"}]}}, + {customer: {country: "DE", validIds: 0, addressProof: true, foreignDocs: 0, docStatus: "id-missing", documents: [ + {kind: "passport", expires: "2031-01-01", verified: false, issuer: "DE", expired: false, identity: true, usable: false}, + {kind: "utility", verified: true, issuer: "DE", expired: false, identity: false, usable: true}, + ]}}, + ], + [ + {customer: {country: "DE", documents: [{kind: "passport", expires: null, verified: true, issuer: "FR"}]}}, + {customer: {country: "DE", validIds: 1, addressProof: false, foreignDocs: 1, docStatus: "address-missing", documents: [ + {kind: "passport", expires: null, verified: true, issuer: "FR", expired: false, identity: true, usable: true}, + ]}}, + ], + [ + {customer: {country: "NO", documents: [ + {kind: "passport", expires: "2029-01-01", verified: true, issuer: "NO"}, + {kind: "passport", expires: "2028-01-01", verified: true, issuer: "GB"}, + {kind: "utility", expires: "2025-01-01", verified: true, issuer: "NO"}, + ]}}, + {customer: {country: "NO", validIds: 2, addressProof: false, foreignDocs: 1, docStatus: "address-missing", documents: [ + {kind: "passport", expires: "2029-01-01", verified: true, issuer: "NO", expired: false, identity: true, usable: true}, + {kind: "passport", expires: "2028-01-01", verified: true, issuer: "GB", expired: false, identity: true, usable: true}, + {kind: "utility", expires: "2025-01-01", verified: true, issuer: "NO", expired: true, identity: false, usable: false}, + ]}}, + ], + [ + {customer: {country: "NO", documents: [{kind: "passport", expires: "2030-01-01", issuer: "NO"}]}}, + {customer: {country: "NO", validIds: 0, addressProof: false, foreignDocs: 0, docStatus: "id-missing", documents: [ + {kind: "passport", expires: "2030-01-01", issuer: "NO", expired: false, identity: true, usable: false}, + ]}}, + ], + [{customer: {country: "NO", documents: [{kind: "selfie", verified: true, issuer: "NO"}]}}, "!error: InputValidationFailed"], + [{customer: {country: "NO", documents: [{kind: "passport", expires: "31/12/2030", verified: true, issuer: "NO"}]}}, "!error: InputValidationFailed"], + [{customer: {country: "NO", documents: [{kind: "passport", verified: "yes", issuer: "NO"}]}}, "!error: InputValidationFailed"], + [{customer: {country: "NO"}}, "!error: MissingRequiredInputs"], + [{customer: {documents: []}}, "!error: MissingRequiredInputs"], + ], +} + +// The natural guard `expires != null and expires < d()` is rejected by the type checker: the +// `!= null` test does not narrow the optional date for the right operand. The workspace path +// still evaluates it correctly. +{ + name: "null-guarded optional expiry", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {documents: "document[]"}, document: {expires: "date?"}}, + blocks: [ + {expression: "document.expired", value: "document.expires != null and document.expires < d()"}, + {expression: "customer.anyExpired", value: "some(customer.documents, #.expired)"}, + ], + }, + cases: [ + { + input: {customer: {documents: [{expires: "2020-01-01"}, {expires: null}, {}]}}, + output: {customer: {anyExpired: true, documents: [{expires: "2020-01-01", expired: true}, {expires: null, expired: false}, {expired: false}]}}, + note: "question: `x != null and x < d()` is a TYPE_MISMATCH error, so DecisionEngine refuses the policy; the left operand guards the right one, so narrowing looks intended", + }, + [{customer: {documents: [{expires: "2030-01-01"}]}}, {customer: {anyExpired: false, documents: [{expires: "2030-01-01", expired: false}]}}], + [{customer: {documents: []}}, {customer: {anyExpired: false, documents: []}}], + ], +} + +// --- Individual risk scoring --------------------------------------------------------------------- +// Country risk from a table with list cells, occupation risk from a match, volume points from a +// nested conditional, an optional cash share defaulted with `??`, then a tier match, a review +// table with two scalar outputs and an onboarding assertion. + +{ + name: "individual risk scoring", + policy: { + models: { + customer: {dob: "date", country: "string", pep: "boolean", occupation: "string(salaried|self|student|retired|cash)", monthlyVolume: "number", cashShare: "number?"}, + }, + blocks: [ + {expression: "customer.age", value: "d().diff(customer.dob, 'year')"}, + {table: "countryRisk", inputs: ["customer.country"], outputs: ["customer.countryRisk"], rules: [ + ["'NO', 'SE', 'DK', 'FI'", "1"], + ["'DE', 'FR', 'NL', 'GB'", "2"], + ["'IR', 'KP', 'SY'", "10"], + ["", "5"], + ]}, + {match: "customer.occupationRisk", arms: [ + ["customer.occupation == 'cash'", "4"], + ["customer.occupation == 'self'", "2"], + ["customer.occupation == 'student'", "1"], + ["", "0"], + ]}, + {expression: "customer.volumePoints", value: "customer.monthlyVolume > 50000 ? 15 : customer.monthlyVolume > 10000 ? 5 : 0"}, + {expression: "customer.score", value: "customer.countryRisk * 5 + customer.occupationRisk * 5 + (customer.pep ? 30 : 0) + customer.volumePoints + ((customer.cashShare ?? 0) > 0.5 ? 10 : 0) + (customer.age < 21 ? 5 : 0)"}, + {match: "customer.riskTier", arms: [ + ["customer.countryRisk >= 10", "'prohibited'"], + ["customer.score >= 50", "'high'"], + ["customer.score >= 25", "'medium'"], + ["", "'low'"], + ]}, + {table: "review", inputs: ["customer.riskTier"], outputs: ["customer.reviewMonths", "customer.edd"], rules: [ + ["'prohibited'", "0", "true"], + ["'high'", "12", "true"], + ["'medium'", "24", "false"], + ["'low'", "36", "false"], + ]}, + {assertion: "customer.onboard", conditions: ["customer.age >= 18", "customer.riskTier != 'prohibited'"]}, + ], + }, + cases: [ + [ + {customer: {dob: "1985-06-15", country: "NO", pep: false, occupation: "salaried", monthlyVolume: 3000}}, + {customer: {dob: "1985-06-15", country: "NO", pep: false, occupation: "salaried", monthlyVolume: 3000, age: 39, countryRisk: 1, occupationRisk: 0, volumePoints: 0, score: 5, riskTier: "low", reviewMonths: 36, edd: false, onboard: true}}, + ], + [ + {customer: {dob: "2005-01-01", country: "SE", pep: false, occupation: "student", monthlyVolume: 12000, cashShare: 0.2}}, + {customer: {dob: "2005-01-01", country: "SE", pep: false, occupation: "student", monthlyVolume: 12000, cashShare: 0.2, age: 20, countryRisk: 1, occupationRisk: 1, volumePoints: 5, score: 20, riskTier: "low", reviewMonths: 36, edd: false, onboard: true}}, + ], + [ + {customer: {dob: "1970-03-20", country: "DE", pep: true, occupation: "self", monthlyVolume: 60000, cashShare: 0.6}}, + {customer: {dob: "1970-03-20", country: "DE", pep: true, occupation: "self", monthlyVolume: 60000, cashShare: 0.6, age: 55, countryRisk: 2, occupationRisk: 2, volumePoints: 15, score: 75, riskTier: "high", reviewMonths: 12, edd: true, onboard: true}}, + ], + [ + {customer: {dob: "1990-01-01", country: "IR", pep: false, occupation: "salaried", monthlyVolume: 100}}, + {customer: {dob: "1990-01-01", country: "IR", pep: false, occupation: "salaried", monthlyVolume: 100, age: 35, countryRisk: 10, occupationRisk: 0, volumePoints: 0, score: 50, riskTier: "prohibited", reviewMonths: 0, edd: true, onboard: false}}, + ], + [ + {customer: {dob: "2008-01-01", country: "NO", pep: false, occupation: "salaried", monthlyVolume: 0}}, + {customer: {dob: "2008-01-01", country: "NO", pep: false, occupation: "salaried", monthlyVolume: 0, age: 17, countryRisk: 1, occupationRisk: 0, volumePoints: 0, score: 10, riskTier: "low", reviewMonths: 36, edd: false, onboard: false}}, + ], + [ + {customer: {dob: "1980-01-01", country: "US", pep: false, occupation: "cash", monthlyVolume: 20000, cashShare: null}}, + {customer: {dob: "1980-01-01", country: "US", pep: false, occupation: "cash", monthlyVolume: 20000, cashShare: null, age: 45, countryRisk: 5, occupationRisk: 4, volumePoints: 5, score: 50, riskTier: "high", reviewMonths: 12, edd: true, onboard: true}}, + ], + // Strict thresholds: 10000 earns no volume points and a cash share of exactly 0.5 none either. + [ + {customer: {dob: "1980-01-01", country: "BR", pep: false, occupation: "salaried", monthlyVolume: 10000, cashShare: 0.5}}, + {customer: {dob: "1980-01-01", country: "BR", pep: false, occupation: "salaried", monthlyVolume: 10000, cashShare: 0.5, age: 45, countryRisk: 5, occupationRisk: 0, volumePoints: 0, score: 25, riskTier: "medium", reviewMonths: 24, edd: false, onboard: true}}, + ], + [ + {customer: {dob: "1960-01-01", country: "FR", pep: true, occupation: "retired", monthlyVolume: 50000}}, + {customer: {dob: "1960-01-01", country: "FR", pep: true, occupation: "retired", monthlyVolume: 50000, age: 65, countryRisk: 2, occupationRisk: 0, volumePoints: 5, score: 45, riskTier: "medium", reviewMonths: 24, edd: false, onboard: true}}, + ], + // Country codes are case-sensitive: `kp` falls to the default row. + [ + {customer: {dob: "1999-03-21", country: "kp", pep: false, occupation: "salaried", monthlyVolume: -5}}, + {customer: {dob: "1999-03-21", country: "kp", pep: false, occupation: "salaried", monthlyVolume: -5, age: 25, countryRisk: 5, occupationRisk: 0, volumePoints: 0, score: 25, riskTier: "medium", reviewMonths: 24, edd: false, onboard: true}}, + ], + [ + {customer: {dob: "2004-03-21", country: "SE", pep: false, occupation: "salaried", monthlyVolume: 0}}, + {customer: {dob: "2004-03-21", country: "SE", pep: false, occupation: "salaried", monthlyVolume: 0, age: 20, countryRisk: 1, occupationRisk: 0, volumePoints: 0, score: 10, riskTier: "low", reviewMonths: 36, edd: false, onboard: true}}, + ], + [{customer: {dob: "1980-01-01", country: "NO", pep: false, occupation: "banker", monthlyVolume: 0}}, "!error: InputValidationFailed"], + [{customer: {dob: "1980-01-01", country: "NO", occupation: "salaried", monthlyVolume: 0}}, "!error: MissingRequiredInputs"], + [{customer: {dob: "1980-01-01", country: "NO", pep: false, occupation: "salaried", monthlyVolume: 0, cashShare: "high"}}, "!error: InputValidationFailed"], + [{customer: {dob: "1980-01-01", country: "NO", pep: null, occupation: "salaried", monthlyVolume: 0}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Sanctions and PEP screening ----------------------------------------------------------------- +// Screening hits are members: a per-hit match grades the hit (an optional date-of-birth match +// lifts a near-certain hit to exact), a per-hit flag marks relevant ones, customer aggregates +// count them, a first-hit table with a `[]` column collects every applicable flag, and a final +// match routes the case. + +{ + name: "sanctions and pep screening", + policy: { + models: { + customer: {name: "string", pep: "boolean", hits: "hit[]"}, + hit: {list: "string(OFAC|EU|UN|PEP|MEDIA)", score: "number", dobMatch: "boolean?"}, + }, + blocks: [ + {match: "hit.strength", arms: [ + ["hit.score >= 0.95 and (hit.dobMatch ?? false)", "'exact'"], + ["hit.score >= 0.85", "'strong'"], + ["hit.score >= 0.7", "'weak'"], + ["", "'noise'"], + ]}, + {expression: "hit.relevant", value: "hit.strength in ['exact', 'strong']"}, + {expression: "customer.sanctionHits", value: "count(customer.hits, #.relevant and #.list in ['OFAC', 'EU', 'UN'])"}, + {expression: "customer.pepConfirmed", value: "customer.pep or some(customer.hits, #.list == 'PEP' and #.relevant)"}, + {expression: "customer.adverseMedia", value: "count(customer.hits, #.list == 'MEDIA' and #.strength != 'noise')"}, + {expression: "customer.weakHits", value: "count(customer.hits, #.strength == 'weak')"}, + {table: "flags", inputs: ["customer.sanctionHits", "customer.pepConfirmed", "customer.adverseMedia"], outputs: ["customer.flags[]"], rules: [ + ["> 0", "", "", "'sanctions'"], + ["", "true", "", "'pep'"], + ["", "", "> 0", "'adverse-media'"], + ]}, + {match: "customer.screening", arms: [ + ["customer.sanctionHits > 0", "'blocked'"], + ["customer.pepConfirmed or customer.adverseMedia > 0", "'edd'"], + ["customer.weakHits > 0", "'review'"], + ["", "'clear'"], + ]}, + ], + }, + cases: [ + [ + {customer: {name: "Kari", pep: false, hits: []}}, + {customer: {name: "Kari", pep: false, hits: [], sanctionHits: 0, pepConfirmed: false, adverseMedia: 0, weakHits: 0, flags: [], screening: "clear"}}, + ], + [ + {customer: {name: "Ivan", pep: false, hits: [{list: "OFAC", score: 0.97, dobMatch: true}]}}, + {customer: {name: "Ivan", pep: false, hits: [{list: "OFAC", score: 0.97, dobMatch: true, strength: "exact", relevant: true}], sanctionHits: 1, pepConfirmed: false, adverseMedia: 0, weakHits: 0, flags: ["sanctions"], screening: "blocked"}}, + ], + [ + {customer: {name: "Ivan", pep: false, hits: [{list: "OFAC", score: 0.97, dobMatch: false}]}}, + {customer: {name: "Ivan", pep: false, hits: [{list: "OFAC", score: 0.97, dobMatch: false, strength: "strong", relevant: true}], sanctionHits: 1, pepConfirmed: false, adverseMedia: 0, weakHits: 0, flags: ["sanctions"], screening: "blocked"}}, + ], + [ + {customer: {name: "Eva", pep: false, hits: [{list: "EU", score: 0.8}]}}, + {customer: {name: "Eva", pep: false, hits: [{list: "EU", score: 0.8, strength: "weak", relevant: false}], sanctionHits: 0, pepConfirmed: false, adverseMedia: 0, weakHits: 1, flags: [], screening: "review"}}, + ], + [ + {customer: {name: "Per", pep: false, hits: [{list: "PEP", score: 0.9}]}}, + {customer: {name: "Per", pep: false, hits: [{list: "PEP", score: 0.9, strength: "strong", relevant: true}], sanctionHits: 0, pepConfirmed: true, adverseMedia: 0, weakHits: 0, flags: ["pep"], screening: "edd"}}, + ], + [ + {customer: {name: "Min", pep: true, hits: []}}, + {customer: {name: "Min", pep: true, hits: [], sanctionHits: 0, pepConfirmed: true, adverseMedia: 0, weakHits: 0, flags: ["pep"], screening: "edd"}}, + ], + [ + {customer: {name: "Ola", pep: false, hits: [{list: "MEDIA", score: 0.72}, {list: "UN", score: 0.5}]}}, + {customer: {name: "Ola", pep: false, hits: [{list: "MEDIA", score: 0.72, strength: "weak", relevant: false}, {list: "UN", score: 0.5, strength: "noise", relevant: false}], sanctionHits: 0, pepConfirmed: false, adverseMedia: 1, weakHits: 1, flags: ["adverse-media"], screening: "edd"}}, + ], + // A null date-of-birth match defaults to false: 0.95 is only strong. Every flag is collected. + [ + {customer: {name: "Ana", pep: false, hits: [{list: "OFAC", score: 0.95, dobMatch: null}, {list: "PEP", score: 0.99, dobMatch: true}, {list: "MEDIA", score: 0.69}, {list: "MEDIA", score: 1}]}}, + {customer: {name: "Ana", pep: false, hits: [ + {list: "OFAC", score: 0.95, dobMatch: null, strength: "strong", relevant: true}, + {list: "PEP", score: 0.99, dobMatch: true, strength: "exact", relevant: true}, + {list: "MEDIA", score: 0.69, strength: "noise", relevant: false}, + {list: "MEDIA", score: 1, strength: "strong", relevant: true}, + ], sanctionHits: 1, pepConfirmed: true, adverseMedia: 1, weakHits: 0, flags: ["sanctions", "pep", "adverse-media"], screening: "blocked"}}, + ], + [ + {customer: {name: "Bo", pep: false, hits: [{list: "UN", score: 0.85}, {list: "EU", score: 0.8499}]}}, + {customer: {name: "Bo", pep: false, hits: [{list: "UN", score: 0.85, strength: "strong", relevant: true}, {list: "EU", score: 0.8499, strength: "weak", relevant: false}], sanctionHits: 1, pepConfirmed: false, adverseMedia: 0, weakHits: 1, flags: ["sanctions"], screening: "blocked"}}, + ], + [ + {customer: {name: "Bo", pep: false, hits: [{list: "EU", score: 0.7}, {list: "PEP", score: 0.6999}]}}, + {customer: {name: "Bo", pep: false, hits: [{list: "EU", score: 0.7, strength: "weak", relevant: false}, {list: "PEP", score: 0.6999, strength: "noise", relevant: false}], sanctionHits: 0, pepConfirmed: false, adverseMedia: 0, weakHits: 1, flags: [], screening: "review"}}, + ], + [{customer: {name: "X", pep: false, hits: [{list: "INTERPOL", score: 0.99}]}}, "!error: InputValidationFailed"], + [{customer: {name: "X", pep: false, hits: [{list: "EU", score: "0.9"}]}}, "!error: InputValidationFailed"], + [{customer: {name: "X", pep: false, hits: [{list: "EU"}]}}, "!error: ExpressionFailed"], + [{customer: {name: "X", pep: false}}, "!error: MissingRequiredInputs"], + [{customer: {name: "X", hits: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Business ownership (KYB) -------------------------------------------------------------------- +// Owners are members: per-owner UBO and pending flags, business aggregates over computed member +// properties, a reasons table collecting across three inputs (list cell over an enum), and a +// decision match whose arms read member computeds through closures. + +{ + name: "business kyb with beneficial owners", + policy: { + models: { + business: {name: "string", country: "string", incorporated: "date", structure: "string(simple|layered|trust)", owners: "owner[]"}, + owner: {name: "string", share: "number", pep: "boolean", country: "string", verified: "boolean"}, + }, + blocks: [ + {expression: "owner.ubo", value: "owner.share >= 25"}, + {expression: "owner.pending", value: "owner.ubo and not owner.verified"}, + {expression: "business.ubos", value: "map(filter(business.owners, #.ubo), #.name)"}, + {expression: "business.declared", value: "sum(map(business.owners, #.share))"}, + {expression: "business.yearsActive", value: "d().diff(business.incorporated, 'year')"}, + {expression: "business.foreignUbo", value: "some(business.owners, #.ubo and #.country != business.country)"}, + {expression: "business.pendingUbos", value: "count(business.owners, #.pending)"}, + {table: "reasons", inputs: ["business.declared", "business.structure", "business.yearsActive"], outputs: ["business.reasons[]"], rules: [ + ["< 75", "", "", "'ownership-incomplete'"], + ["> 100", "", "", "'ownership-overstated'"], + ["", "'trust', 'layered'", "", "'complex-structure'"], + ["", "", "< 2", "'newly-incorporated'"], + ]}, + {match: "business.decision", arms: [ + ["some(business.owners, #.pep and #.ubo)", "'edd'"], + ["business.pendingUbos > 0", "'awaiting-documents'"], + ["len(business.reasons) > 0", "'manual-review'"], + ["", "'approved'"], + ]}, + ], + }, + cases: [ + [ + {business: {name: "Acme", country: "NO", incorporated: "2010-05-01", structure: "simple", owners: [ + {name: "A", share: 60, pep: false, country: "NO", verified: true}, + {name: "B", share: 40, pep: false, country: "NO", verified: true}, + ]}}, + {business: {name: "Acme", country: "NO", incorporated: "2010-05-01", structure: "simple", owners: [ + {name: "A", share: 60, pep: false, country: "NO", verified: true, ubo: true, pending: false}, + {name: "B", share: 40, pep: false, country: "NO", verified: true, ubo: true, pending: false}, + ], ubos: ["A", "B"], declared: 100, yearsActive: 14, foreignUbo: false, pendingUbos: 0, reasons: [], decision: "approved"}}, + ], + [ + {business: {name: "Acme", country: "NO", incorporated: "2010-05-01", structure: "simple", owners: [ + {name: "A", share: 60, pep: false, country: "NO", verified: true}, + {name: "B", share: 40, pep: false, country: "NO", verified: false}, + ]}}, + {business: {name: "Acme", country: "NO", incorporated: "2010-05-01", structure: "simple", owners: [ + {name: "A", share: 60, pep: false, country: "NO", verified: true, ubo: true, pending: false}, + {name: "B", share: 40, pep: false, country: "NO", verified: false, ubo: true, pending: true}, + ], ubos: ["A", "B"], declared: 100, yearsActive: 14, foreignUbo: false, pendingUbos: 1, reasons: [], decision: "awaiting-documents"}}, + ], + [ + {business: {name: "Fan", country: "NO", incorporated: "2015-01-01", structure: "layered", owners: [ + {name: "A", share: 20, pep: false, country: "NO", verified: true}, + {name: "B", share: 20, pep: false, country: "NO", verified: true}, + {name: "C", share: 20, pep: false, country: "NO", verified: false}, + {name: "D", share: 20, pep: false, country: "NO", verified: true}, + {name: "E", share: 20, pep: false, country: "NO", verified: true}, + ]}}, + {business: {name: "Fan", country: "NO", incorporated: "2015-01-01", structure: "layered", owners: [ + {name: "A", share: 20, pep: false, country: "NO", verified: true, ubo: false, pending: false}, + {name: "B", share: 20, pep: false, country: "NO", verified: true, ubo: false, pending: false}, + {name: "C", share: 20, pep: false, country: "NO", verified: false, ubo: false, pending: false}, + {name: "D", share: 20, pep: false, country: "NO", verified: true, ubo: false, pending: false}, + {name: "E", share: 20, pep: false, country: "NO", verified: true, ubo: false, pending: false}, + ], ubos: [], declared: 100, yearsActive: 10, foreignUbo: false, pendingUbos: 0, reasons: ["complex-structure"], decision: "manual-review"}}, + ], + [ + {business: {name: "Tr", country: "NO", incorporated: "2024-06-01", structure: "trust", owners: [{name: "A", share: 50, pep: true, country: "SE", verified: true}]}}, + {business: {name: "Tr", country: "NO", incorporated: "2024-06-01", structure: "trust", owners: [ + {name: "A", share: 50, pep: true, country: "SE", verified: true, ubo: true, pending: false}, + ], ubos: ["A"], declared: 50, yearsActive: 0, foreignUbo: true, pendingUbos: 0, reasons: ["ownership-incomplete", "complex-structure", "newly-incorporated"], decision: "edd"}}, + ], + [ + {business: {name: "Ov", country: "DE", incorporated: "2000-01-01", structure: "simple", owners: [ + {name: "A", share: 70, pep: false, country: "DE", verified: true}, + {name: "B", share: 40, pep: false, country: "DE", verified: true}, + ]}}, + {business: {name: "Ov", country: "DE", incorporated: "2000-01-01", structure: "simple", owners: [ + {name: "A", share: 70, pep: false, country: "DE", verified: true, ubo: true, pending: false}, + {name: "B", share: 40, pep: false, country: "DE", verified: true, ubo: true, pending: false}, + ], ubos: ["A", "B"], declared: 110, yearsActive: 25, foreignUbo: false, pendingUbos: 0, reasons: ["ownership-overstated"], decision: "manual-review"}}, + ], + [ + {business: {name: "Shell", country: "DE", incorporated: "2000-01-01", structure: "simple", owners: []}}, + {business: {name: "Shell", country: "DE", incorporated: "2000-01-01", structure: "simple", owners: [], ubos: [], declared: 0, yearsActive: 25, foreignUbo: false, pendingUbos: 0, reasons: ["ownership-incomplete"], decision: "manual-review"}}, + ], + // A PEP below the UBO threshold does not trigger enhanced due diligence. + [ + {business: {name: "Pp", country: "SE", incorporated: "2001-01-01", structure: "simple", owners: [ + {name: "A", share: 90, pep: false, country: "SE", verified: true}, + {name: "B", share: 10, pep: true, country: "SE", verified: false}, + ]}}, + {business: {name: "Pp", country: "SE", incorporated: "2001-01-01", structure: "simple", owners: [ + {name: "A", share: 90, pep: false, country: "SE", verified: true, ubo: true, pending: false}, + {name: "B", share: 10, pep: true, country: "SE", verified: false, ubo: false, pending: false}, + ], ubos: ["A"], declared: 100, yearsActive: 24, foreignUbo: false, pendingUbos: 0, reasons: [], decision: "approved"}}, + ], + // UBO threshold is inclusive; two full years since incorporation is not new. + [ + {business: {name: "Bd", country: "NO", incorporated: "2023-03-20", structure: "simple", owners: [ + {name: "A", share: 25, pep: false, country: "NO", verified: true}, + {name: "B", share: 24.99, pep: false, country: "GB", verified: false}, + {name: "C", share: 50.01, pep: false, country: "GB", verified: true}, + ]}}, + {business: {name: "Bd", country: "NO", incorporated: "2023-03-20", structure: "simple", owners: [ + {name: "A", share: 25, pep: false, country: "NO", verified: true, ubo: true, pending: false}, + {name: "B", share: 24.99, pep: false, country: "GB", verified: false, ubo: false, pending: false}, + {name: "C", share: 50.01, pep: false, country: "GB", verified: true, ubo: true, pending: false}, + ], ubos: ["A", "C"], declared: 100, yearsActive: 2, foreignUbo: true, pendingUbos: 0, reasons: [], decision: "approved"}}, + ], + [ + {business: {name: "New", country: "NO", incorporated: "2023-03-21", structure: "simple", owners: [{name: "A", share: 100, pep: false, country: "NO", verified: true}]}}, + {business: {name: "New", country: "NO", incorporated: "2023-03-21", structure: "simple", owners: [ + {name: "A", share: 100, pep: false, country: "NO", verified: true, ubo: true, pending: false}, + ], ubos: ["A"], declared: 100, yearsActive: 1, foreignUbo: false, pendingUbos: 0, reasons: ["newly-incorporated"], decision: "manual-review"}}, + ], + [{business: {name: "X", country: "NO", incorporated: "2000-01-01", structure: "partnership", owners: []}}, "!error: InputValidationFailed"], + [{business: {name: "X", country: "NO", incorporated: "2000-01-01", structure: "simple", owners: [{name: "A", share: "50%", pep: false, country: "NO", verified: true}]}}, "!error: InputValidationFailed"], + [{business: {name: "X", country: "NO", incorporated: "2000-01-01", structure: "simple", owners: [{name: "A", pep: false, country: "NO", verified: true}]}}, "!error: ExpressionFailed"], + [{business: {name: "X", country: "NO", incorporated: "2000-01-01", structure: "simple"}}, "!error: MissingRequiredInputs"], + [{business: {name: "X", country: "NO", structure: "simple", owners: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Country profiles by reference --------------------------------------------------------------- +// Nationality and residence are references into a `country` pool; a global sets the enhanced due +// diligence threshold. The assertion is `score >= threshold or fatfExposure`. + +{ + name: "geographic risk from referenced country profiles", + policy: { + globals: {settings: {eddScore: "number"}}, + models: { + customer: {name: "string", nationality: "&country", residence: "&country"}, + country: {id: "string", risk: "number", fatf: "boolean"}, + }, + blocks: [ + {expression: "customer.geoRisk", value: "max([customer.nationality.risk, customer.residence.risk])"}, + {expression: "customer.fatfExposure", value: "customer.nationality.fatf or customer.residence.fatf"}, + {expression: "customer.crossBorder", value: "customer.nationality.id != customer.residence.id"}, + {expression: "customer.score", value: "customer.geoRisk * 10 + (customer.fatfExposure ? 25 : 0) + (customer.crossBorder ? 5 : 0)"}, + {assertion: "customer.edd", conditions: [["or", "customer.score >= eddScore", 0], "customer.fatfExposure"]}, + ], + }, + cases: [ + [ + {eddScore: 40, customer: {name: "a", nationality: "NO", residence: "NO"}, country: [{id: "NO", risk: 1, fatf: false}, {id: "IR", risk: 9, fatf: true}, {id: "AE", risk: 4, fatf: false}]}, + {eddScore: 40, customer: {name: "a", nationality: {id: "NO", risk: 1, fatf: false}, residence: {id: "NO", risk: 1, fatf: false}, geoRisk: 1, fatfExposure: false, crossBorder: false, score: 10, edd: false}, country: [{id: "NO", risk: 1, fatf: false}, {id: "IR", risk: 9, fatf: true}, {id: "AE", risk: 4, fatf: false}]}, + ], + [ + {eddScore: 40, customer: {name: "b", nationality: "NO", residence: "AE"}, country: [{id: "NO", risk: 1, fatf: false}, {id: "AE", risk: 4, fatf: false}]}, + {eddScore: 40, customer: {name: "b", nationality: {id: "NO", risk: 1, fatf: false}, residence: {id: "AE", risk: 4, fatf: false}, geoRisk: 4, fatfExposure: false, crossBorder: true, score: 45, edd: true}, country: [{id: "NO", risk: 1, fatf: false}, {id: "AE", risk: 4, fatf: false}]}, + ], + [ + {eddScore: 40, customer: {name: "c", nationality: "IR", residence: "NO"}, country: [{id: "NO", risk: 1, fatf: false}, {id: "IR", risk: 9, fatf: true}]}, + {eddScore: 40, customer: {name: "c", nationality: {id: "IR", risk: 9, fatf: true}, residence: {id: "NO", risk: 1, fatf: false}, geoRisk: 9, fatfExposure: true, crossBorder: true, score: 120, edd: true}, country: [{id: "NO", risk: 1, fatf: false}, {id: "IR", risk: 9, fatf: true}]}, + ], + // FATF exposure alone triggers EDD even when the score is under the threshold. + [ + {eddScore: 200, customer: {name: "d", nationality: "IR", residence: "IR"}, country: [{id: "IR", risk: 9, fatf: true}]}, + {eddScore: 200, customer: {name: "d", nationality: {id: "IR", risk: 9, fatf: true}, residence: {id: "IR", risk: 9, fatf: true}, geoRisk: 9, fatfExposure: true, crossBorder: false, score: 115, edd: true}, country: [{id: "IR", risk: 9, fatf: true}]}, + ], + [ + {eddScore: 40, customer: {name: "e", nationality: "AE", residence: "AE"}, country: [{id: "AE", risk: 4, fatf: false}]}, + {eddScore: 40, customer: {name: "e", nationality: {id: "AE", risk: 4, fatf: false}, residence: {id: "AE", risk: 4, fatf: false}, geoRisk: 4, fatfExposure: false, crossBorder: false, score: 40, edd: true}, country: [{id: "AE", risk: 4, fatf: false}]}, + ], + [ + {eddScore: 40.5, customer: {name: "f", nationality: "AE", residence: "AE"}, country: [{id: "AE", risk: 4.05, fatf: false}]}, + {eddScore: 40.5, customer: {name: "f", nationality: {id: "AE", risk: 4.05, fatf: false}, residence: {id: "AE", risk: 4.05, fatf: false}, geoRisk: 4.05, fatfExposure: false, crossBorder: false, score: 40.5, edd: true}, country: [{id: "AE", risk: 4.05, fatf: false}]}, + ], + [{eddScore: 40, customer: {name: "g", nationality: "XX", residence: "NO"}, country: [{id: "NO", risk: 1, fatf: false}]}, "!error: InputValidationFailed"], + [{eddScore: 40, customer: {name: "g", nationality: 5, residence: "NO"}, country: [{id: "NO", risk: 1, fatf: false}]}, "!error: InputValidationFailed"], + [{eddScore: 40, customer: {name: "g", nationality: "NO", residence: "NO"}, country: [{id: "NO", risk: "low", fatf: false}]}, "!error: InputValidationFailed"], + [{eddScore: 40, customer: {name: "g", nationality: "NO"}, country: [{id: "NO", risk: 1, fatf: false}]}, "!error: MissingRequiredInputs"], + [{customer: {name: "g", nationality: "NO", residence: "NO"}, country: [{id: "NO", risk: 1, fatf: false}]}, "!error: MissingRequiredInputs"], + [{eddScore: 40, customer: {name: "g", nationality: "NO", residence: "NO"}}, "!error: InputValidationFailed"], + ], +} + +// --- Transaction monitoring ---------------------------------------------------------------------- +// Per-transaction recency, near-threshold cash and corridor flags; account aggregates over recent +// inflows; a hit-policy `collect` table of alerts read by an action match. + +{ + name: "transaction monitoring alerts", + policy: { + models: { + account: {holder: "string", declaredMonthly: "number", txns: "txn[]"}, + txn: {amount: "number", at: "date", channel: "string(cash|wire|card)", direction: "string(in|out)", counterpartyCountry: "string?"}, + }, + blocks: [ + {expression: "txn.recent", value: "d().diff(txn.at, 'day') < 30"}, + {expression: "txn.nearThreshold", value: "txn.channel == 'cash' and txn.amount >= 9000 and txn.amount < 10000"}, + {expression: "txn.highRiskCorridor", value: "(txn.counterpartyCountry ?? '') in ['IR', 'KP', 'SY']"}, + {expression: "account.inflow30", value: "sum(map(filter(account.txns, #.recent and #.direction == 'in'), #.amount))"}, + {expression: "account.structuring", value: "count(account.txns, #.recent and #.nearThreshold) >= 3"}, + {expression: "account.volumeRatio", value: "account.declaredMonthly > 0 ? round(account.inflow30 / account.declaredMonthly, 2) : 0"}, + {expression: "account.corridors", value: "count(account.txns, #.highRiskCorridor)"}, + {table: "alerts", hit: "collect", inputs: ["account.structuring", "account.volumeRatio", "account.corridors"], outputs: ["account.alerts"], rules: [ + ["true", "", "", "'structuring'"], + ["", "> 3", "", "'volume-spike'"], + ["", "", "> 0", "'high-risk-corridor'"], + ]}, + {match: "account.action", arms: [ + ["'structuring' in account.alerts or 'high-risk-corridor' in account.alerts", "'file-sar'"], + ["len(account.alerts) > 0", "'investigate'"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [ + {account: {holder: "a", declaredMonthly: 5000, txns: []}}, + {account: {holder: "a", declaredMonthly: 5000, txns: [], inflow30: 0, structuring: false, volumeRatio: 0, corridors: 0, alerts: [], action: "none"}}, + ], + [ + {account: {holder: "b", declaredMonthly: 10000, txns: [ + {amount: 9500, at: "2025-03-10", channel: "cash", direction: "in"}, + {amount: 9500, at: "2025-03-12", channel: "cash", direction: "in"}, + {amount: 9500, at: "2025-03-15", channel: "cash", direction: "in"}, + ]}}, + {account: {holder: "b", declaredMonthly: 10000, txns: [ + {amount: 9500, at: "2025-03-10", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 9500, at: "2025-03-12", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 9500, at: "2025-03-15", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + ], inflow30: 28500, structuring: true, volumeRatio: 2.85, corridors: 0, alerts: ["structuring"], action: "file-sar"}}, + ], + [ + {account: {holder: "c", declaredMonthly: 5000, txns: [ + {amount: 9500, at: "2025-03-10", channel: "cash", direction: "in"}, + {amount: 9500, at: "2025-03-12", channel: "cash", direction: "in"}, + {amount: 9500, at: "2025-01-01", channel: "cash", direction: "in"}, + ]}}, + {account: {holder: "c", declaredMonthly: 5000, txns: [ + {amount: 9500, at: "2025-03-10", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 9500, at: "2025-03-12", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 9500, at: "2025-01-01", channel: "cash", direction: "in", recent: false, nearThreshold: true, highRiskCorridor: false}, + ], inflow30: 19000, structuring: false, volumeRatio: 3.8, corridors: 0, alerts: ["volume-spike"], action: "investigate"}}, + ], + [ + {account: {holder: "d", declaredMonthly: 1000, txns: [{amount: 50000, at: "2025-03-01", channel: "wire", direction: "out", counterpartyCountry: "IR"}]}}, + {account: {holder: "d", declaredMonthly: 1000, txns: [ + {amount: 50000, at: "2025-03-01", channel: "wire", direction: "out", counterpartyCountry: "IR", recent: true, nearThreshold: false, highRiskCorridor: true}, + ], inflow30: 0, structuring: false, volumeRatio: 0, corridors: 1, alerts: ["high-risk-corridor"], action: "file-sar"}}, + ], + [ + {account: {holder: "e", declaredMonthly: 0, txns: [{amount: 100, at: "2025-03-19", channel: "card", direction: "in", counterpartyCountry: null}]}}, + {account: {holder: "e", declaredMonthly: 0, txns: [ + {amount: 100, at: "2025-03-19", channel: "card", direction: "in", counterpartyCountry: null, recent: true, nearThreshold: false, highRiskCorridor: false}, + ], inflow30: 100, structuring: false, volumeRatio: 0, corridors: 0, alerts: [], action: "none"}}, + ], + // Near-threshold is [9000, 10000); a ratio that rounds to exactly 3 is not a spike. + [ + {account: {holder: "f", declaredMonthly: 9667, txns: [ + {amount: 9000, at: "2025-03-18", channel: "cash", direction: "in"}, + {amount: 9999.99, at: "2025-03-18", channel: "cash", direction: "in"}, + {amount: 10000, at: "2025-03-18", channel: "cash", direction: "in"}, + ]}}, + {account: {holder: "f", declaredMonthly: 9667, txns: [ + {amount: 9000, at: "2025-03-18", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 9999.99, at: "2025-03-18", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 10000, at: "2025-03-18", channel: "cash", direction: "in", recent: true, nearThreshold: false, highRiskCorridor: false}, + ], inflow30: 28999.99, structuring: false, volumeRatio: 3, corridors: 0, alerts: [], action: "none"}}, + ], + // Exactly 30 days ago is no longer recent; one second later still is. + [ + {account: {holder: "g", declaredMonthly: 100, txns: [ + {amount: 100, at: "2025-02-18T10:15:30Z", channel: "card", direction: "in"}, + {amount: 100, at: "2025-02-18T10:15:31Z", channel: "card", direction: "in", counterpartyCountry: "SY"}, + ]}}, + {account: {holder: "g", declaredMonthly: 100, txns: [ + {amount: 100, at: "2025-02-18T10:15:30Z", channel: "card", direction: "in", recent: false, nearThreshold: false, highRiskCorridor: false}, + {amount: 100, at: "2025-02-18T10:15:31Z", channel: "card", direction: "in", counterpartyCountry: "SY", recent: true, nearThreshold: false, highRiskCorridor: true}, + ], inflow30: 100, structuring: false, volumeRatio: 1, corridors: 1, alerts: ["high-risk-corridor"], action: "file-sar"}}, + ], + [ + {account: {holder: "h", declaredMonthly: 1000, txns: [ + {amount: 9100, at: "2025-03-01", channel: "cash", direction: "in"}, + {amount: 9200, at: "2025-03-02", channel: "cash", direction: "in"}, + {amount: 9300, at: "2025-03-03", channel: "cash", direction: "out"}, + {amount: 50, at: "2025-03-25", channel: "card", direction: "in", counterpartyCountry: "KP"}, + ]}}, + {account: {holder: "h", declaredMonthly: 1000, txns: [ + {amount: 9100, at: "2025-03-01", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 9200, at: "2025-03-02", channel: "cash", direction: "in", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 9300, at: "2025-03-03", channel: "cash", direction: "out", recent: true, nearThreshold: true, highRiskCorridor: false}, + {amount: 50, at: "2025-03-25", channel: "card", direction: "in", counterpartyCountry: "KP", recent: true, nearThreshold: false, highRiskCorridor: true}, + ], inflow30: 18350, structuring: true, volumeRatio: 18.35, corridors: 1, alerts: ["structuring", "volume-spike", "high-risk-corridor"], action: "file-sar"}}, + ], + [{account: {holder: "x", declaredMonthly: 1, txns: [{amount: 1, at: "2025-03-01", channel: "crypto", direction: "in"}]}}, "!error: InputValidationFailed"], + [{account: {holder: "x", declaredMonthly: 1, txns: [{amount: 1, at: "2025-03-01", channel: "cash", direction: "sideways"}]}}, "!error: InputValidationFailed"], + [{account: {holder: "x", declaredMonthly: 1, txns: [{at: "2025-03-01", channel: "cash", direction: "in"}]}}, "!error: ExpressionFailed"], + [{account: {holder: "x", txns: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Goals over a due-diligence summary ---------------------------------------------------------- +// A goal evaluates only its cone: required inputs outside it may be missing. + +{ + name: "cdd summary with goals", + policy: { + models: {customer: {age: "number", pep: "boolean", sanctioned: "boolean", docsValid: "boolean", country: "string"}}, + blocks: [ + {assertion: "customer.identityOk", conditions: ["customer.docsValid", "customer.age >= 18"]}, + {match: "customer.risk", arms: [ + ["customer.sanctioned", "'prohibited'"], + ["customer.pep", "'high'"], + ["customer.country in ['NO', 'SE']", "'low'"], + ["", "'medium'"], + ]}, + {table: "outcome", inputs: ["customer.identityOk", "customer.risk"], outputs: ["customer.outcome", "customer.reasons[]"], rules: [ + ["false", "", "'reject'", "'identity'"], + ["", "'prohibited'", "'reject'", "'sanctions'"], + ["", "'high'", "'refer'", "'pep'"], + ["", "", "'accept'", ""], + ]}, + ], + }, + cases: [ + {input: {customer: {age: 17, docsValid: true}}, goals: ["customer.identityOk"], output: {customer: {age: 17, docsValid: true, identityOk: false}}}, + {input: {customer: {age: 40, docsValid: true}}, goals: ["customer.identityOk"], output: {customer: {age: 40, docsValid: true, identityOk: true}}}, + {input: {customer: {sanctioned: false, pep: false, country: "SE"}}, goals: ["customer.risk"], output: {customer: {sanctioned: false, pep: false, country: "SE", risk: "low"}}}, + {input: {customer: {sanctioned: true, pep: false, country: "US"}}, goals: ["customer.risk"], output: {customer: {sanctioned: true, pep: false, country: "US", risk: "prohibited"}}}, + {input: {customer: {age: 30}}, goals: ["customer.risk"], output: "!error: MissingRequiredInputs"}, + { + input: {customer: {age: 30, docsValid: true, sanctioned: false, pep: true, country: "NO"}}, + goals: ["customer.outcome"], + output: {customer: {age: 30, docsValid: true, sanctioned: false, pep: true, country: "NO", identityOk: true, risk: "high", outcome: "refer", reasons: ["pep"]}}, + }, + { + input: {customer: {age: 16, docsValid: false, sanctioned: true, pep: true, country: "NO"}}, + output: {customer: {age: 16, docsValid: false, sanctioned: true, pep: true, country: "NO", identityOk: false, risk: "prohibited", outcome: "reject", reasons: ["identity", "sanctions"]}}, + }, + { + input: {customer: {age: 50, docsValid: true, sanctioned: false, pep: false, country: "DE"}}, + output: {customer: {age: 50, docsValid: true, sanctioned: false, pep: false, country: "DE", identityOk: true, risk: "medium", outcome: "accept", reasons: []}}, + }, + {input: {customer: {age: 50, docsValid: true, sanctioned: false, pep: false}}, output: "!error: MissingRequiredInputs"}, + ], +} + +// --- Dictionaries for country and document codes ------------------------------------------------- +// Dictionary-typed codes are validated on input and behave as plain strings in blocks. + +{ + name: "kyc codes from dictionaries", + policy: { + dictionaries: { + isoCountry: ["NO", "SE", "DE", "IR", ["GB", "United Kingdom"]], + docType: [["P", "Passport"], ["ID", "National id"], ["DL", "Driving licence"]], + }, + models: {applicant: {nationality: "isoCountry", residence: "isoCountry", docType: "docType", secondDoc: "docType?"}}, + blocks: [ + {expression: "applicant.highRisk", value: "applicant.nationality == 'IR' or applicant.residence == 'IR'"}, + {match: "applicant.docWeight", arms: [["applicant.docType == 'P'", "3"], ["applicant.docType == 'ID'", "2"], ["", "1"]]}, + {expression: "applicant.evidence", value: "applicant.docWeight + (applicant.secondDoc == null ? 0 : 1)"}, + {assertion: "applicant.simplified", conditions: ["not applicant.highRisk", "applicant.evidence >= 3", "applicant.nationality == applicant.residence"]}, + ], + }, + cases: [ + [ + {applicant: {nationality: "NO", residence: "NO", docType: "P"}}, + {applicant: {nationality: "NO", residence: "NO", docType: "P", highRisk: false, docWeight: 3, evidence: 3, simplified: true}}, + ], + [ + {applicant: {nationality: "GB", residence: "SE", docType: "ID", secondDoc: "DL"}}, + {applicant: {nationality: "GB", residence: "SE", docType: "ID", secondDoc: "DL", highRisk: false, docWeight: 2, evidence: 3, simplified: false}}, + ], + [ + {applicant: {nationality: "DE", residence: "DE", docType: "DL", secondDoc: null}}, + {applicant: {nationality: "DE", residence: "DE", docType: "DL", secondDoc: null, highRisk: false, docWeight: 1, evidence: 1, simplified: false}}, + ], + [ + {applicant: {nationality: "IR", residence: "IR", docType: "P", secondDoc: "ID"}}, + {applicant: {nationality: "IR", residence: "IR", docType: "P", secondDoc: "ID", highRisk: true, docWeight: 3, evidence: 4, simplified: false}}, + ], + [{applicant: {nationality: "United Kingdom", residence: "NO", docType: "P"}}, "!error: InputValidationFailed"], + [{applicant: {nationality: "NO", residence: "NO", docType: "Passport"}}, "!error: InputValidationFailed"], + [{applicant: {nationality: "NO", residence: "NO", docType: "P", secondDoc: "X"}}, "!error: InputValidationFailed"], + [{applicant: {nationality: "no", residence: "NO", docType: "P"}}, "!error: InputValidationFailed"], + [{applicant: {nationality: "NO", docType: "P"}}, "!error: MissingRequiredInputs"], + ], +} diff --git a/core/engine/tests/spec/policy/25-realistic-underwriting.json5 b/core/engine/tests/spec/policy/25-realistic-underwriting.json5 new file mode 100644 index 00000000..25ccef59 --- /dev/null +++ b/core/engine/tests/spec/policy/25-realistic-underwriting.json5 @@ -0,0 +1,534 @@ +// Realistic credit underwriting policies: affordability from income and debt members, risk-based +// pricing over single relationships and a market global, approval decisions with collected +// reasons, joint applications, asset reserves, product eligibility by reference, and goals. +// Evaluation time is fixed at 2025-03-20T10:15:30Z. + +// --- Affordability ------------------------------------------------------------------------------- +// Per-income haircut table (unverified income counts for nothing), per-debt service with a card +// minimum payment of 3% of the balance, applicant aggregates, a debt-to-income ratio and a band. + +{ + name: "affordability from incomes and debts", + policy: { + models: { + applicant: {housingCost: "number", incomes: "income[]", debts: "debt[]"}, + income: {kind: "string(salary|bonus|rental|benefits)", monthly: "number", verified: "boolean"}, + debt: {kind: "string(card|auto|student|mortgage)", balance: "number", payment: "number?"}, + }, + blocks: [ + {table: "haircut", inputs: ["income.kind", "income.verified"], outputs: ["income.factor"], rules: [ + ["", "false", "0"], + ["'salary', 'benefits'", "", "1"], + ["'rental'", "", "0.75"], + ["'bonus'", "", "0.5"], + ]}, + {expression: "income.qualifying", value: "round(income.monthly * income.factor, 2)"}, + {expression: "debt.service", value: "debt.kind == 'card' ? max([debt.payment ?? 0, round(debt.balance * 0.03, 2)]) : (debt.payment ?? 0)"}, + {expression: "applicant.income", value: "sum(map(applicant.incomes, #.qualifying))"}, + {expression: "applicant.obligations", value: "sum(map(applicant.debts, #.service)) + applicant.housingCost"}, + {expression: "applicant.dti", value: "applicant.income > 0 ? round(applicant.obligations / applicant.income, 4) : 99"}, + {match: "applicant.band", arms: [ + ["applicant.dti <= 0.36", "'comfortable'"], + ["applicant.dti <= 0.43", "'stretched'"], + ["", "'unaffordable'"], + ]}, + ], + }, + cases: [ + [ + {applicant: {housingCost: 1500, incomes: [{kind: "salary", monthly: 5000, verified: true}], debts: []}}, + {applicant: {housingCost: 1500, incomes: [{kind: "salary", monthly: 5000, verified: true, factor: 1, qualifying: 5000}], debts: [], income: 5000, obligations: 1500, dti: 0.3, band: "comfortable"}}, + ], + [ + {applicant: {housingCost: 1200, + incomes: [{kind: "salary", monthly: 4000, verified: true}, {kind: "bonus", monthly: 1000, verified: true}, {kind: "rental", monthly: 800, verified: true}], + debts: [{kind: "card", balance: 2000, payment: 40}, {kind: "auto", balance: 15000, payment: 350}]}}, + {applicant: {housingCost: 1200, + incomes: [{kind: "salary", monthly: 4000, verified: true, factor: 1, qualifying: 4000}, {kind: "bonus", monthly: 1000, verified: true, factor: 0.5, qualifying: 500}, {kind: "rental", monthly: 800, verified: true, factor: 0.75, qualifying: 600}], + debts: [{kind: "card", balance: 2000, payment: 40, service: 60}, {kind: "auto", balance: 15000, payment: 350, service: 350}], + income: 5100, obligations: 1610, dti: 0.3157, band: "comfortable"}}, + ], + [ + {applicant: {housingCost: 1000, incomes: [{kind: "salary", monthly: 6000, verified: false}], debts: []}}, + {applicant: {housingCost: 1000, incomes: [{kind: "salary", monthly: 6000, verified: false, factor: 0, qualifying: 0}], debts: [], income: 0, obligations: 1000, dti: 99, band: "unaffordable"}}, + ], + // A student loan without a payment services nothing; a card without one pays the minimum. + [ + {applicant: {housingCost: 1100, + incomes: [{kind: "benefits", monthly: 1500, verified: true}, {kind: "salary", monthly: 2500, verified: true}], + debts: [{kind: "student", balance: 30000, payment: null}, {kind: "card", balance: 500}]}}, + {applicant: {housingCost: 1100, + incomes: [{kind: "benefits", monthly: 1500, verified: true, factor: 1, qualifying: 1500}, {kind: "salary", monthly: 2500, verified: true, factor: 1, qualifying: 2500}], + debts: [{kind: "student", balance: 30000, payment: null, service: 0}, {kind: "card", balance: 500, service: 15}], + income: 4000, obligations: 1115, dti: 0.2788, band: "comfortable"}}, + ], + [ + {applicant: {housingCost: 1800, incomes: [{kind: "salary", monthly: 5000, verified: true}], debts: []}}, + {applicant: {housingCost: 1800, incomes: [{kind: "salary", monthly: 5000, verified: true, factor: 1, qualifying: 5000}], debts: [], income: 5000, obligations: 1800, dti: 0.36, band: "comfortable"}}, + ], + [ + {applicant: {housingCost: 4300, incomes: [{kind: "salary", monthly: 10000, verified: true}], debts: []}}, + {applicant: {housingCost: 4300, incomes: [{kind: "salary", monthly: 10000, verified: true, factor: 1, qualifying: 10000}], debts: [], income: 10000, obligations: 4300, dti: 0.43, band: "stretched"}}, + ], + [ + {applicant: {housingCost: 4301, incomes: [{kind: "salary", monthly: 10000, verified: true}], debts: []}}, + {applicant: {housingCost: 4301, incomes: [{kind: "salary", monthly: 10000, verified: true, factor: 1, qualifying: 10000}], debts: [], income: 10000, obligations: 4301, dti: 0.4301, band: "unaffordable"}}, + ], + [ + {applicant: {housingCost: 0, + incomes: [{kind: "salary", monthly: 3000, verified: true}, {kind: "rental", monthly: 1000, verified: false}], + debts: [{kind: "mortgage", balance: 200000, payment: 1100}]}}, + {applicant: {housingCost: 0, + incomes: [{kind: "salary", monthly: 3000, verified: true, factor: 1, qualifying: 3000}, {kind: "rental", monthly: 1000, verified: false, factor: 0, qualifying: 0}], + debts: [{kind: "mortgage", balance: 200000, payment: 1100, service: 1100}], + income: 3000, obligations: 1100, dti: 0.3667, band: "stretched"}}, + ], + [ + {applicant: {housingCost: 0, incomes: [], debts: []}}, + {applicant: {housingCost: 0, incomes: [], debts: [], income: 0, obligations: 0, dti: 99, band: "unaffordable"}}, + ], + [ + {applicant: {housingCost: 500, incomes: [{kind: "salary", monthly: 2000, verified: true}], debts: [{kind: "card", balance: 1000, payment: 100}]}}, + {applicant: {housingCost: 500, incomes: [{kind: "salary", monthly: 2000, verified: true, factor: 1, qualifying: 2000}], debts: [{kind: "card", balance: 1000, payment: 100, service: 100}], income: 2000, obligations: 600, dti: 0.3, band: "comfortable"}}, + ], + [ + {applicant: {housingCost: 0, incomes: [{kind: "bonus", monthly: 333.33, verified: true}], debts: [{kind: "card", balance: 333.33}]}}, + {applicant: {housingCost: 0, incomes: [{kind: "bonus", monthly: 333.33, verified: true, factor: 0.5, qualifying: 166.67}], debts: [{kind: "card", balance: 333.33, service: 10}], income: 166.67, obligations: 10, dti: 0.06, band: "comfortable"}}, + ], + [{applicant: {housingCost: 0, incomes: [{kind: "pension", monthly: 1, verified: true}], debts: []}}, "!error: InputValidationFailed"], + [{applicant: {housingCost: 0, incomes: [], debts: [{kind: "card", balance: "500"}]}}, "!error: InputValidationFailed"], + [{applicant: {housingCost: 0, incomes: [{kind: "salary", verified: true}], debts: []}}, "!error: ExpressionFailed"], + [{applicant: {incomes: [], debts: []}}, "!error: MissingRequiredInputs"], + [{applicant: {housingCost: 0, debts: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Risk-based pricing -------------------------------------------------------------------------- +// Single relationships (applicant, property) under the application, a market base rate global, +// a pricing table over three inputs where land always lands in tier D, a first-time-buyer +// discount, an annuity payment using `^`, and two matches. + +{ + name: "risk-based mortgage pricing", + policy: { + globals: {market: {baseRate: "number"}}, + models: { + application: {amount: "number", termYears: "number", applicant: "applicant", property: "property"}, + applicant: {score: "number", firstTime: "boolean"}, + property: {value: "number", kind: "string(house|flat|land)"}, + }, + blocks: [ + {expression: "application.ltv", value: "round(application.amount / application.property.value, 4)"}, + {table: "pricing", inputs: ["application.applicant.score", "application.ltv", "application.property.kind"], outputs: ["application.tier", "application.margin"], rules: [ + ["", "", "'land'", "'D'", "4"], + [">= 760", "<= 0.6", "", "'A'", "0.8"], + [">= 760", "<= 0.8", "", "'A'", "1"], + [">= 700", "<= 0.8", "", "'B'", "1.5"], + [">= 640", "<= 0.9", "", "'C'", "2.5"], + ["", "", "", "'D'", "4"], + ]}, + {expression: "application.rate", value: "baseRate + application.margin - (application.applicant.firstTime and application.tier != 'D' ? 0.25 : 0)"}, + {expression: "application.payment", value: "round(application.amount * (application.rate / 1200) / (1 - (1 + application.rate / 1200) ^ (-application.termYears * 12)), 2)"}, + {match: "application.mortgageInsurance", arms: [["application.ltv > 0.8", "round(application.amount * 0.005 / 12, 2)"], ["", "0"]]}, + {match: "application.offer", arms: [["application.ltv > 0.95", "'decline'"], ["application.tier == 'D'", "'refer'"], ["", "'offer'"]]}, + ], + }, + cases: [ + [ + {baseRate: 4, application: {amount: 300000, termYears: 25, applicant: {score: 780, firstTime: false}, property: {value: 500000, kind: "house"}}}, + {baseRate: 4, application: {amount: 300000, termYears: 25, applicant: {score: 780, firstTime: false}, property: {value: 500000, kind: "house"}, ltv: 0.6, tier: "A", margin: 0.8, rate: 4.8, payment: 1718.99, mortgageInsurance: 0, offer: "offer"}}, + ], + [ + {baseRate: 4, application: {amount: 400000, termYears: 25, applicant: {score: 760, firstTime: true}, property: {value: 500000, kind: "house"}}}, + {baseRate: 4, application: {amount: 400000, termYears: 25, applicant: {score: 760, firstTime: true}, property: {value: 500000, kind: "house"}, ltv: 0.8, tier: "A", margin: 1, rate: 4.75, payment: 2280.47, mortgageInsurance: 0, offer: "offer"}}, + ], + [ + {baseRate: 4, application: {amount: 425000, termYears: 30, applicant: {score: 720, firstTime: false}, property: {value: 500000, kind: "flat"}}}, + {baseRate: 4, application: {amount: 425000, termYears: 30, applicant: {score: 720, firstTime: false}, property: {value: 500000, kind: "flat"}, ltv: 0.85, tier: "C", margin: 2.5, rate: 6.5, payment: 2686.29, mortgageInsurance: 177.08, offer: "offer"}}, + ], + // Land is tier D whatever the score; the first-time discount does not apply to tier D. + [ + {baseRate: 4, application: {amount: 250000, termYears: 20, applicant: {score: 800, firstTime: true}, property: {value: 500000, kind: "land"}}}, + {baseRate: 4, application: {amount: 250000, termYears: 20, applicant: {score: 800, firstTime: true}, property: {value: 500000, kind: "land"}, ltv: 0.5, tier: "D", margin: 4, rate: 8, payment: 2091.10, mortgageInsurance: 0, offer: "refer"}}, + ], + [ + {baseRate: 4, application: {amount: 485000, termYears: 25, applicant: {score: 600, firstTime: false}, property: {value: 500000, kind: "house"}}}, + {baseRate: 4, application: {amount: 485000, termYears: 25, applicant: {score: 600, firstTime: false}, property: {value: 500000, kind: "house"}, ltv: 0.97, tier: "D", margin: 4, rate: 8, payment: 3743.31, mortgageInsurance: 202.08, offer: "decline"}}, + ], + [ + {baseRate: 3.5, application: {amount: 400000, termYears: 30, applicant: {score: 700, firstTime: true}, property: {value: 500000, kind: "flat"}}}, + {baseRate: 3.5, application: {amount: 400000, termYears: 30, applicant: {score: 700, firstTime: true}, property: {value: 500000, kind: "flat"}, ltv: 0.8, tier: "B", margin: 1.5, rate: 4.75, payment: 2086.59, mortgageInsurance: 0, offer: "offer"}}, + ], + [ + {baseRate: 4.75, application: {amount: 200000, termYears: 10, applicant: {score: 759.99, firstTime: false}, property: {value: 400000, kind: "house"}}}, + {baseRate: 4.75, application: {amount: 200000, termYears: 10, applicant: {score: 759.99, firstTime: false}, property: {value: 400000, kind: "house"}, ltv: 0.5, tier: "B", margin: 1.5, rate: 6.25, payment: 2245.60, mortgageInsurance: 0, offer: "offer"}}, + ], + [{baseRate: 4, application: {amount: 1, termYears: 1, applicant: {score: 700, firstTime: false}}}, "!error: MissingRequiredInputs"], + [{application: {amount: 1, termYears: 1, applicant: {score: 700, firstTime: false}, property: {value: 10, kind: "house"}}}, "!error: MissingRequiredInputs"], + [{baseRate: 4, application: {amount: 1, termYears: 1, applicant: {score: 700, firstTime: false}, property: {value: 10, kind: "boat"}}}, "!error: InputValidationFailed"], + [{baseRate: 4, application: {amount: 1, termYears: 1, applicant: {score: 700, firstTime: false}, property: {value: 0, kind: "house"}}}, "!error"], + [{baseRate: "4", application: {amount: 1, termYears: 1, applicant: {score: 700, firstTime: false}, property: {value: 10, kind: "house"}}}, "!error: InputValidationFailed"], + ], +} + +// --- Approval decision with reasons -------------------------------------------------------------- +// A grouped eligibility assertion: adult and at most 70 and (citizen or resident or (visa and two +// years employed)); a bankruptcy look-back over an optional date; a `collect` table of decline +// reasons; a decision match and a summary string. + +{ + name: "approval decision with reasons", + policy: { + models: { + application: { + age: "number", score: "number", dti: "number", ltv: "number", bankruptcies: "number", employmentMonths: "number", + residency: "string(citizen|resident|visa)", lastBankruptcy: "date?", + }, + }, + blocks: [ + {assertion: "application.eligible", conditions: [ + ["and", "application.age >= 18"], + ["and", "application.age <= 70"], + ["or", "application.residency == 'citizen'", 1], + ["or", "application.residency == 'resident'", 1], + ["and", "application.residency == 'visa'", 2], + ["and", "application.employmentMonths >= 24", 2], + ]}, + {expression: "application.recentBankruptcy", value: "application.bankruptcies > 0 and d().diff(application.lastBankruptcy ?? d('1900-01-01'), 'year') < 7"}, + {table: "reasons", hit: "collect", inputs: ["application.score", "application.dti", "application.ltv", "application.employmentMonths"], outputs: ["application.reasons"], rules: [ + ["< 620", "", "", "", "'low-score'"], + ["", "> 0.43", "", "", "'high-dti'"], + ["", "", "> 0.9", "", "'high-ltv'"], + ["", "", "", "< 6", "'short-employment'"], + ]}, + {match: "application.decision", arms: [ + ["not application.eligible or application.recentBankruptcy", "'decline'"], + ["len(application.reasons) == 0", "'approve'"], + ["len(application.reasons) == 1", "'refer'"], + ["", "'decline'"], + ]}, + {expression: "application.summary", value: "application.decision + (len(application.reasons) > 0 ? ' (' + string(len(application.reasons)) + ' reasons)' : '')"}, + ], + }, + cases: [ + [ + {application: {age: 35, score: 720, dti: 0.3, ltv: 0.8, bankruptcies: 0, employmentMonths: 60, residency: "citizen"}}, + {application: {age: 35, score: 720, dti: 0.3, ltv: 0.8, bankruptcies: 0, employmentMonths: 60, residency: "citizen", eligible: true, recentBankruptcy: false, reasons: [], decision: "approve", summary: "approve"}}, + ], + [ + {application: {age: 35, score: 600, dti: 0.3, ltv: 0.8, bankruptcies: 0, employmentMonths: 60, residency: "citizen"}}, + {application: {age: 35, score: 600, dti: 0.3, ltv: 0.8, bankruptcies: 0, employmentMonths: 60, residency: "citizen", eligible: true, recentBankruptcy: false, reasons: ["low-score"], decision: "refer", summary: "refer (1 reasons)"}}, + ], + [ + {application: {age: 35, score: 600, dti: 0.5, ltv: 0.95, bankruptcies: 0, employmentMonths: 3, residency: "resident"}}, + {application: {age: 35, score: 600, dti: 0.5, ltv: 0.95, bankruptcies: 0, employmentMonths: 3, residency: "resident", eligible: true, recentBankruptcy: false, reasons: ["low-score", "high-dti", "high-ltv", "short-employment"], decision: "decline", summary: "decline (4 reasons)"}}, + ], + [ + {application: {age: 29, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 24, residency: "visa"}}, + {application: {age: 29, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 24, residency: "visa", eligible: true, recentBankruptcy: false, reasons: [], decision: "approve", summary: "approve"}}, + ], + [ + {application: {age: 29, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 23, residency: "visa"}}, + {application: {age: 29, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 23, residency: "visa", eligible: false, recentBankruptcy: false, reasons: [], decision: "decline", summary: "decline"}}, + ], + [ + {application: {age: 71, score: 800, dti: 0.1, ltv: 0.4, bankruptcies: 0, employmentMonths: 400, residency: "citizen"}}, + {application: {age: 71, score: 800, dti: 0.1, ltv: 0.4, bankruptcies: 0, employmentMonths: 400, residency: "citizen", eligible: false, recentBankruptcy: false, reasons: [], decision: "decline", summary: "decline"}}, + ], + [ + {application: {age: 18, score: 620, dti: 0.43, ltv: 0.9, bankruptcies: 0, employmentMonths: 6, residency: "resident"}}, + {application: {age: 18, score: 620, dti: 0.43, ltv: 0.9, bankruptcies: 0, employmentMonths: 6, residency: "resident", eligible: true, recentBankruptcy: false, reasons: [], decision: "approve", summary: "approve"}}, + ], + [ + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 1, lastBankruptcy: "2020-01-01", employmentMonths: 100, residency: "citizen"}}, + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 1, lastBankruptcy: "2020-01-01", employmentMonths: 100, residency: "citizen", eligible: true, recentBankruptcy: true, reasons: [], decision: "decline", summary: "decline"}}, + ], + [ + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 1, lastBankruptcy: "2015-01-01", employmentMonths: 100, residency: "citizen"}}, + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 1, lastBankruptcy: "2015-01-01", employmentMonths: 100, residency: "citizen", eligible: true, recentBankruptcy: false, reasons: [], decision: "approve", summary: "approve"}}, + ], + // Look-back boundary: exactly seven years ago is outside the window. + [ + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 2, lastBankruptcy: "2018-03-20", employmentMonths: 100, residency: "citizen"}}, + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 2, lastBankruptcy: "2018-03-20", employmentMonths: 100, residency: "citizen", eligible: true, recentBankruptcy: false, reasons: [], decision: "approve", summary: "approve"}}, + ], + [ + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 1, employmentMonths: 100, residency: "citizen"}}, + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 1, employmentMonths: 100, residency: "citizen", eligible: true, recentBankruptcy: false, reasons: [], decision: "approve", summary: "approve"}}, + ], + [ + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 0, lastBankruptcy: "2024-01-01", employmentMonths: 100, residency: "citizen"}}, + {application: {age: 50, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 0, lastBankruptcy: "2024-01-01", employmentMonths: 100, residency: "citizen", eligible: true, recentBankruptcy: false, reasons: [], decision: "approve", summary: "approve"}}, + ], + [ + {application: {age: 40, score: 619.99, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 5.9, residency: "citizen"}}, + {application: {age: 40, score: 619.99, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 5.9, residency: "citizen", eligible: true, recentBankruptcy: false, reasons: ["low-score", "short-employment"], decision: "decline", summary: "decline (2 reasons)"}}, + ], + [{application: {age: 40, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 5, residency: "tourist"}}, "!error: InputValidationFailed"], + [{application: {age: 40, score: 700, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 5, residency: "citizen", lastBankruptcy: "yesterday"}}, "!error: InputValidationFailed"], + [{application: {age: 40, dti: 0.2, ltv: 0.5, bankruptcies: 0, employmentMonths: 5, residency: "citizen"}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Joint applications -------------------------------------------------------------------------- +// Several applicants as members: per-applicant ratio and eligibility, application aggregates over +// eligible members only, the term capped by the oldest applicant's age at 75, the approved amount +// capped by an income multiple, a status match and a band table over the lowest score. + +{ + name: "joint application capacity", + policy: { + models: { + application: {requested: "number", termYears: "number", applicants: "applicant[]"}, + applicant: {name: "string", income: "number", debts: "number", score: "number", age: "number"}, + }, + blocks: [ + {expression: "applicant.dti", value: "applicant.income > 0 ? round(applicant.debts / applicant.income, 4) : 1"}, + {expression: "applicant.eligible", value: "applicant.age >= 18 and applicant.score >= 600 and applicant.dti < 0.5"}, + {expression: "application.combinedIncome", value: "sum(map(filter(application.applicants, #.eligible), #.income))"}, + {expression: "application.lowestScore", value: "len(application.applicants) == 0 ? 0 : min(map(application.applicants, #.score))"}, + {expression: "application.oldestAge", value: "len(application.applicants) == 0 ? 0 : max(map(application.applicants, #.age))"}, + {expression: "application.maxTerm", value: "min([application.termYears, 75 - application.oldestAge])"}, + {expression: "application.capacity", value: "application.combinedIncome * 4.5"}, + {expression: "application.approved", value: "min([application.requested, application.capacity])"}, + {match: "application.status", arms: [ + ["len(application.applicants) == 0", "'invalid'"], + ["application.combinedIncome == 0", "'decline'"], + ["application.approved < application.requested", "'counter-offer'"], + ["", "'approve'"], + ]}, + {table: "band", inputs: ["application.lowestScore"], outputs: ["application.band"], rules: [ + [">= 750", "'prime'"], + [">= 650", "'near-prime'"], + ["", "'sub-prime'"], + ]}, + ], + }, + cases: [ + [ + {application: {requested: 400000, termYears: 30, applicants: [ + {name: "A", income: 60000, debts: 12000, score: 780, age: 40}, + {name: "B", income: 40000, debts: 30000, score: 640, age: 38}, + ]}}, + {application: {requested: 400000, termYears: 30, applicants: [ + {name: "A", income: 60000, debts: 12000, score: 780, age: 40, dti: 0.2, eligible: true}, + {name: "B", income: 40000, debts: 30000, score: 640, age: 38, dti: 0.75, eligible: false}, + ], combinedIncome: 60000, lowestScore: 640, oldestAge: 40, maxTerm: 30, capacity: 270000, approved: 270000, status: "counter-offer", band: "sub-prime"}}, + ], + [ + {application: {requested: 300000, termYears: 25, applicants: [{name: "A", income: 100000, debts: 0, score: 800, age: 30}]}}, + {application: {requested: 300000, termYears: 25, applicants: [{name: "A", income: 100000, debts: 0, score: 800, age: 30, dti: 0, eligible: true}], combinedIncome: 100000, lowestScore: 800, oldestAge: 30, maxTerm: 25, capacity: 450000, approved: 300000, status: "approve", band: "prime"}}, + ], + [ + {application: {requested: 100000, termYears: 20, applicants: []}}, + {application: {requested: 100000, termYears: 20, applicants: [], combinedIncome: 0, lowestScore: 0, oldestAge: 0, maxTerm: 20, capacity: 0, approved: 0, status: "invalid", band: "sub-prime"}}, + ], + [ + {application: {requested: 100000, termYears: 25, applicants: [{name: "Kid", income: 50000, debts: 0, score: 700, age: 17}]}}, + {application: {requested: 100000, termYears: 25, applicants: [{name: "Kid", income: 50000, debts: 0, score: 700, age: 17, dti: 0, eligible: false}], combinedIncome: 0, lowestScore: 700, oldestAge: 17, maxTerm: 25, capacity: 0, approved: 0, status: "decline", band: "near-prime"}}, + ], + [ + {application: {requested: 450000, termYears: 30, applicants: [ + {name: "A", income: 50000, debts: 10000, score: 700, age: 60}, + {name: "B", income: 50000, debts: 5000, score: 760, age: 30}, + ]}}, + {application: {requested: 450000, termYears: 30, applicants: [ + {name: "A", income: 50000, debts: 10000, score: 700, age: 60, dti: 0.2, eligible: true}, + {name: "B", income: 50000, debts: 5000, score: 760, age: 30, dti: 0.1, eligible: true}, + ], combinedIncome: 100000, lowestScore: 700, oldestAge: 60, maxTerm: 15, capacity: 450000, approved: 450000, status: "approve", band: "near-prime"}}, + ], + [ + {application: {requested: 50000, termYears: 10, applicants: [{name: "A", income: 0, debts: 0, score: 790, age: 45}]}}, + {application: {requested: 50000, termYears: 10, applicants: [{name: "A", income: 0, debts: 0, score: 790, age: 45, dti: 1, eligible: false}], combinedIncome: 0, lowestScore: 790, oldestAge: 45, maxTerm: 10, capacity: 0, approved: 0, status: "decline", band: "prime"}}, + ], + // A ratio of exactly 0.5 is ineligible; an applicant aged 80 leaves a negative term. + [ + {application: {requested: 10000, termYears: 5, applicants: [ + {name: "A", income: 10000, debts: 5000, score: 650, age: 50}, + {name: "B", income: 2000, debts: 0, score: 600, age: 80}, + ]}}, + {application: {requested: 10000, termYears: 5, applicants: [ + {name: "A", income: 10000, debts: 5000, score: 650, age: 50, dti: 0.5, eligible: false}, + {name: "B", income: 2000, debts: 0, score: 600, age: 80, dti: 0, eligible: true}, + ], combinedIncome: 2000, lowestScore: 600, oldestAge: 80, maxTerm: -5, capacity: 9000, approved: 9000, status: "counter-offer", band: "sub-prime"}}, + ], + [ + {application: {requested: 1000.5, termYears: 1, applicants: [{name: "A", income: 222.34, debts: 1, score: 750, age: 18}]}}, + {application: {requested: 1000.5, termYears: 1, applicants: [{name: "A", income: 222.34, debts: 1, score: 750, age: 18, dti: 0.0045, eligible: true}], combinedIncome: 222.34, lowestScore: 750, oldestAge: 18, maxTerm: 1, capacity: 1000.53, approved: 1000.5, status: "approve", band: "prime"}}, + ], + [{application: {requested: 1, termYears: 1, applicants: [{name: "A", income: 1, debts: 0, age: 30}]}}, "!error: ExpressionFailed"], + [{application: {requested: 1, termYears: 1, applicants: [{name: "A", income: 1, debts: 0, score: 700, age: "30"}]}}, "!error: InputValidationFailed"], + [{application: {requested: 1, termYears: 1}}, "!error: MissingRequiredInputs"], + [{application: {termYears: 1, applicants: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Asset reserves ------------------------------------------------------------------------------ +// Per-asset haircut table (pledged assets count for nothing, an optional flag that is null or +// missing is not pledged), liquid value per asset, reserves in whole months of payment. + +{ + name: "asset reserves", + policy: { + models: { + applicant: {monthlyPayment: "number", assets: "asset[]"}, + asset: {kind: "string(cash|stocks|retirement|crypto|property)", value: "number", pledged: "boolean?"}, + }, + blocks: [ + {table: "haircut", inputs: ["asset.pledged", "asset.kind"], outputs: ["asset.haircut"], rules: [ + ["true", "", "1"], + ["", "'cash'", "0"], + ["", "'stocks'", "0.3"], + ["", "'retirement'", "0.4"], + ["", "'crypto'", "0.7"], + ["", "'property'", "1"], + ]}, + {expression: "asset.liquid", value: "round(asset.value * (1 - asset.haircut), 2)"}, + {expression: "applicant.liquidAssets", value: "sum(map(applicant.assets, #.liquid))"}, + {expression: "applicant.reserveMonths", value: "applicant.monthlyPayment > 0 ? floor(applicant.liquidAssets / applicant.monthlyPayment) : 0"}, + {expression: "applicant.liquidKinds", value: "map(filter(applicant.assets, #.liquid > 0), #.kind)"}, + {match: "applicant.reserveGrade", arms: [ + ["applicant.reserveMonths >= 12", "'strong'"], + ["applicant.reserveMonths >= 6", "'adequate'"], + ["applicant.reserveMonths >= 2", "'thin'"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [ + {applicant: {monthlyPayment: 2000, assets: [{kind: "cash", value: 30000}]}}, + {applicant: {monthlyPayment: 2000, assets: [{kind: "cash", value: 30000, haircut: 0, liquid: 30000}], liquidAssets: 30000, reserveMonths: 15, liquidKinds: ["cash"], reserveGrade: "strong"}}, + ], + [ + {applicant: {monthlyPayment: 2000, assets: [{kind: "stocks", value: 10000}, {kind: "retirement", value: 10000}, {kind: "crypto", value: 10000}]}}, + {applicant: {monthlyPayment: 2000, assets: [ + {kind: "stocks", value: 10000, haircut: 0.3, liquid: 7000}, + {kind: "retirement", value: 10000, haircut: 0.4, liquid: 6000}, + {kind: "crypto", value: 10000, haircut: 0.7, liquid: 3000}, + ], liquidAssets: 16000, reserveMonths: 8, liquidKinds: ["stocks", "retirement", "crypto"], reserveGrade: "adequate"}}, + ], + [ + {applicant: {monthlyPayment: 2000, assets: [{kind: "cash", value: 5000, pledged: true}, {kind: "property", value: 500000}]}}, + {applicant: {monthlyPayment: 2000, assets: [{kind: "cash", value: 5000, pledged: true, haircut: 1, liquid: 0}, {kind: "property", value: 500000, haircut: 1, liquid: 0}], liquidAssets: 0, reserveMonths: 0, liquidKinds: [], reserveGrade: "none"}}, + ], + [ + {applicant: {monthlyPayment: 1500, assets: []}}, + {applicant: {monthlyPayment: 1500, assets: [], liquidAssets: 0, reserveMonths: 0, liquidKinds: [], reserveGrade: "none"}}, + ], + // No payment means no reserve requirement is computed: zero months by policy choice. + [ + {applicant: {monthlyPayment: 0, assets: [{kind: "cash", value: 1000, pledged: false}]}}, + {applicant: {monthlyPayment: 0, assets: [{kind: "cash", value: 1000, pledged: false, haircut: 0, liquid: 1000}], liquidAssets: 1000, reserveMonths: 0, liquidKinds: ["cash"], reserveGrade: "none"}}, + ], + [ + {applicant: {monthlyPayment: 1000, assets: [{kind: "cash", value: 12000, pledged: null}, {kind: "crypto", value: 100.01}]}}, + {applicant: {monthlyPayment: 1000, assets: [{kind: "cash", value: 12000, pledged: null, haircut: 0, liquid: 12000}, {kind: "crypto", value: 100.01, haircut: 0.7, liquid: 30}], liquidAssets: 12030, reserveMonths: 12, liquidKinds: ["cash", "crypto"], reserveGrade: "strong"}}, + ], + [ + {applicant: {monthlyPayment: 1000, assets: [{kind: "stocks", value: 3333.33, pledged: false}]}}, + {applicant: {monthlyPayment: 1000, assets: [{kind: "stocks", value: 3333.33, pledged: false, haircut: 0.3, liquid: 2333.33}], liquidAssets: 2333.33, reserveMonths: 2, liquidKinds: ["stocks"], reserveGrade: "thin"}}, + ], + [ + {applicant: {monthlyPayment: 1000, assets: [{kind: "retirement", value: 3000}, {kind: "cash", value: -500}]}}, + {applicant: {monthlyPayment: 1000, assets: [{kind: "retirement", value: 3000, haircut: 0.4, liquid: 1800}, {kind: "cash", value: -500, haircut: 0, liquid: -500}], liquidAssets: 1300, reserveMonths: 1, liquidKinds: ["retirement"], reserveGrade: "none"}}, + ], + [{applicant: {monthlyPayment: 1000, assets: [{kind: "bonds", value: 1}]}}, "!error: InputValidationFailed"], + [{applicant: {monthlyPayment: 1000, assets: [{kind: "cash", value: 1, pledged: "no"}]}}, "!error: InputValidationFailed"], + [{applicant: {monthlyPayment: 1000, assets: [{kind: "cash"}]}}, "!error: ExpressionFailed"], + [{applicant: {assets: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Product eligibility by reference ------------------------------------------------------------ +// The application references a product from a pool; the product's limits drive an eligibility +// assertion, an optional product fee defaults to zero, and the outcome is a match. + +{ + name: "product eligibility by reference", + policy: { + models: { + application: {score: "number", amount: "number", value: "number", product: "&product"}, + product: {id: "string", maxLtv: "number", minScore: "number", rate: "number", fee: "number?"}, + }, + blocks: [ + {expression: "application.ltv", value: "round(application.amount / application.value, 4)"}, + {assertion: "application.eligible", conditions: ["application.score >= application.product.minScore", "application.ltv <= application.product.maxLtv"]}, + {expression: "application.fee", value: "application.product.fee ?? 0"}, + {expression: "application.firstYearCost", value: "round(application.amount * application.product.rate / 100 + application.fee, 2)"}, + {match: "application.outcome", arms: [ + ["application.eligible", "'eligible for ' + application.product.id"], + ["application.score < application.product.minScore", "'score below ' + string(application.product.minScore)"], + ["", "'ltv above ' + string(application.product.maxLtv)"], + ]}, + ], + }, + cases: [ + [ + {application: {score: 720, amount: 160000, value: 200000, product: "fix5"}, product: [{id: "fix5", maxLtv: 0.8, minScore: 700, rate: 4.5, fee: 999}, {id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25}]}, + {application: {score: 720, amount: 160000, value: 200000, product: {id: "fix5", maxLtv: 0.8, minScore: 700, rate: 4.5, fee: 999}, ltv: 0.8, eligible: true, fee: 999, firstYearCost: 8199, outcome: "eligible for fix5"}, product: [{id: "fix5", maxLtv: 0.8, minScore: 700, rate: 4.5, fee: 999}, {id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25}]}, + ], + [ + {application: {score: 650, amount: 160000, value: 200000, product: "fix5"}, product: [{id: "fix5", maxLtv: 0.8, minScore: 700, rate: 4.5, fee: 999}]}, + {application: {score: 650, amount: 160000, value: 200000, product: {id: "fix5", maxLtv: 0.8, minScore: 700, rate: 4.5, fee: 999}, ltv: 0.8, eligible: false, fee: 999, firstYearCost: 8199, outcome: "score below 700"}, product: [{id: "fix5", maxLtv: 0.8, minScore: 700, rate: 4.5, fee: 999}]}, + ], + [ + {application: {score: 650, amount: 170000, value: 200000, product: "var"}, product: [{id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25}]}, + {application: {score: 650, amount: 170000, value: 200000, product: {id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25}, ltv: 0.85, eligible: true, fee: 0, firstYearCost: 8925, outcome: "eligible for var"}, product: [{id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25}]}, + ], + [ + {application: {score: 800, amount: 190000, value: 200000, product: "var"}, product: [{id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25, fee: null}]}, + {application: {score: 800, amount: 190000, value: 200000, product: {id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25, fee: null}, ltv: 0.95, eligible: false, fee: 0, firstYearCost: 9975, outcome: "ltv above 0.9"}, product: [{id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25, fee: null}]}, + ], + [{application: {score: 800, amount: 1, value: 2, product: "gone"}, product: [{id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25}]}, "!error: InputValidationFailed"], + [{application: {score: 800, amount: 1, value: 2}, product: [{id: "var", maxLtv: 0.9, minScore: 620, rate: 5.25}]}, "!error: MissingRequiredInputs"], + [{application: {score: 800, amount: 1, value: 2, product: "var"}, product: [{id: "var", maxLtv: 0.9, rate: 5.25}]}, "!error"], + ], +} + +// --- Goals over an underwriting decision --------------------------------------------------------- +// Each goal pulls only its dependencies; inputs outside the cone may be missing. + +{ + name: "underwriting goals", + policy: { + models: {application: {income: "number", debts: "number", score: "number", amount: "number", value: "number"}}, + blocks: [ + {expression: "application.dti", value: "round(application.debts / application.income, 4)"}, + {expression: "application.ltv", value: "round(application.amount / application.value, 4)"}, + {match: "application.tier", arms: [ + ["application.score >= 740 and application.ltv <= 0.8", "'A'"], + ["application.score >= 680", "'B'"], + ["", "'C'"], + ]}, + {table: "decision", inputs: ["application.tier", "application.dti"], outputs: ["application.decision"], rules: [ + ["", "> 0.45", "'decline'"], + ["'A', 'B'", "", "'approve'"], + ["", "", "'refer'"], + ]}, + ], + }, + cases: [ + {input: {application: {income: 5000, debts: 1000}}, goals: ["application.dti"], output: {application: {income: 5000, debts: 1000, dti: 0.2}}}, + {input: {application: {score: 750, amount: 80, value: 100}}, goals: ["application.tier"], output: {application: {score: 750, amount: 80, value: 100, ltv: 0.8, tier: "A"}}}, + {input: {application: {score: 750, amount: 81, value: 100}}, goals: ["application.tier"], output: {application: {score: 750, amount: 81, value: 100, ltv: 0.81, tier: "B"}}}, + {input: {application: {score: 600, amount: 1, value: 100}}, goals: ["application.tier"], output: {application: {score: 600, amount: 1, value: 100, ltv: 0.01, tier: "C"}}}, + {input: {application: {amount: 1, value: 3}}, goals: ["application.ltv"], output: {application: {amount: 1, value: 3, ltv: 0.3333}}}, + {input: {application: {income: 5000, debts: 1000}}, goals: ["application.tier"], output: "!error: MissingRequiredInputs"}, + { + input: {application: {income: 4000, debts: 2000, score: 800, amount: 50, value: 100}}, + goals: ["application.decision"], + output: {application: {income: 4000, debts: 2000, score: 800, amount: 50, value: 100, dti: 0.5, ltv: 0.5, tier: "A", decision: "decline"}}, + }, + { + input: {application: {income: 4000, debts: 1800, score: 600, amount: 50, value: 100}}, + goals: ["application.decision", "application.dti"], + output: {application: {income: 4000, debts: 1800, score: 600, amount: 50, value: 100, dti: 0.45, ltv: 0.5, tier: "C", decision: "refer"}}, + }, + { + input: {application: {income: 4000, debts: 400, score: 690, amount: 95, value: 100}}, + output: {application: {income: 4000, debts: 400, score: 690, amount: 95, value: 100, dti: 0.1, ltv: 0.95, tier: "B", decision: "approve"}}, + }, + {input: {application: {income: 4000, debts: 400, score: 690, amount: 95}}, output: "!error: MissingRequiredInputs"}, + ], +} diff --git a/core/engine/tests/spec/policy/26-realistic-billing.json5 b/core/engine/tests/spec/policy/26-realistic-billing.json5 new file mode 100644 index 00000000..266a0023 --- /dev/null +++ b/core/engine/tests/spec/policy/26-realistic-billing.json5 @@ -0,0 +1,581 @@ +// Realistic billing policies: invoice lines with discounts and tax classes, credits, dunning +// stages, usage metering, account aging, proration, and currency conversion by reference with +// nested write paths and goals. Evaluation time is fixed at 2025-03-20T10:15:30Z. + +// --- Invoice lines, discounts and tax ------------------------------------------------------------ +// Per-line computeds, a per-line tax table whose first input reads the parent invoice, nested +// totals (`invoice.totals.*`) aggregated from the lines, and B2B reverse charge against a global +// seller country. + +{ + name: "invoice lines with discounts and tax", + policy: { + globals: {seller: {sellerCountry: "string"}}, + models: { + invoice: {customerType: "string(b2b|b2c)", country: "string", lines: "line[]"}, + line: {sku: "string", qty: "number", unitPrice: "number", taxClass: "string(standard|reduced|exempt)", discountPct: "number?"}, + }, + blocks: [ + {expression: "line.gross", value: "line.qty * line.unitPrice"}, + {expression: "line.discount", value: "round(line.gross * (line.discountPct ?? 0) / 100, 2)"}, + {expression: "line.net", value: "line.gross - line.discount"}, + {table: "taxRate", inputs: ["invoice.country", "line.taxClass"], outputs: ["line.taxRate"], rules: [ + ["", "'exempt'", "0"], + ["'NO'", "'standard'", "0.25"], + ["'NO'", "'reduced'", "0.15"], + ["'DE'", "'standard'", "0.19"], + ["'DE'", "'reduced'", "0.07"], + ["", "", "0.2"], + ]}, + {expression: "line.tax", value: "round(line.net * line.taxRate, 2)"}, + {expression: "invoice.reverseCharge", value: "invoice.customerType == 'b2b' and invoice.country != sellerCountry"}, + {expression: "invoice.totals.net", value: "sum(map(invoice.lines, #.net))"}, + {expression: "invoice.totals.tax", value: "sum(map(invoice.lines, #.tax))"}, + {expression: "invoice.totals.taxDue", value: "invoice.reverseCharge ? 0 : invoice.totals.tax"}, + {expression: "invoice.totals.gross", value: "invoice.totals.net + invoice.totals.taxDue"}, + {match: "invoice.note", arms: [ + ["invoice.reverseCharge", "'VAT reverse charged'"], + ["invoice.totals.net == 0", "'nothing to invoice'"], + ["", "'standard'"], + ]}, + ], + }, + cases: [ + [ + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [{sku: "a", qty: 2, unitPrice: 100, taxClass: "standard"}]}}, + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [ + {sku: "a", qty: 2, unitPrice: 100, taxClass: "standard", gross: 200, discount: 0, net: 200, taxRate: 0.25, tax: 50}, + ], reverseCharge: false, totals: {net: 200, tax: 50, taxDue: 50, gross: 250}, note: "standard"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + [ + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [ + {sku: "a", qty: 3, unitPrice: 19.99, taxClass: "standard", discountPct: 10}, + {sku: "b", qty: 1, unitPrice: 50, taxClass: "reduced"}, + {sku: "c", qty: 1, unitPrice: 30, taxClass: "exempt"}, + ]}}, + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [ + {sku: "a", qty: 3, unitPrice: 19.99, taxClass: "standard", discountPct: 10, gross: 59.97, discount: 6, net: 53.97, taxRate: 0.25, tax: 13.49}, + {sku: "b", qty: 1, unitPrice: 50, taxClass: "reduced", gross: 50, discount: 0, net: 50, taxRate: 0.15, tax: 7.5}, + {sku: "c", qty: 1, unitPrice: 30, taxClass: "exempt", gross: 30, discount: 0, net: 30, taxRate: 0, tax: 0}, + ], reverseCharge: false, totals: {net: 133.97, tax: 20.99, taxDue: 20.99, gross: 154.96}, note: "standard"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + [ + {sellerCountry: "NO", invoice: {customerType: "b2b", country: "DE", lines: [{sku: "a", qty: 10, unitPrice: 100, taxClass: "standard", discountPct: 5}]}}, + {sellerCountry: "NO", invoice: {customerType: "b2b", country: "DE", lines: [ + {sku: "a", qty: 10, unitPrice: 100, taxClass: "standard", discountPct: 5, gross: 1000, discount: 50, net: 950, taxRate: 0.19, tax: 180.5}, + ], reverseCharge: true, totals: {net: 950, tax: 180.5, taxDue: 0, gross: 950}, note: "VAT reverse charged"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + [ + {sellerCountry: "NO", invoice: {customerType: "b2b", country: "NO", lines: [{sku: "a", qty: 1, unitPrice: 100, taxClass: "reduced"}]}}, + {sellerCountry: "NO", invoice: {customerType: "b2b", country: "NO", lines: [ + {sku: "a", qty: 1, unitPrice: 100, taxClass: "reduced", gross: 100, discount: 0, net: 100, taxRate: 0.15, tax: 15}, + ], reverseCharge: false, totals: {net: 100, tax: 15, taxDue: 15, gross: 115}, note: "standard"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + [ + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "US", lines: [{sku: "a", qty: 1, unitPrice: 10, taxClass: "standard"}]}}, + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "US", lines: [ + {sku: "a", qty: 1, unitPrice: 10, taxClass: "standard", gross: 10, discount: 0, net: 10, taxRate: 0.2, tax: 2}, + ], reverseCharge: false, totals: {net: 10, tax: 2, taxDue: 2, gross: 12}, note: "standard"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + [ + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: []}}, + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [], reverseCharge: false, totals: {net: 0, tax: 0, taxDue: 0, gross: 0}, note: "nothing to invoice"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + [ + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "DE", lines: [{sku: "free", qty: 1, unitPrice: 9.99, taxClass: "reduced", discountPct: 100}]}}, + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "DE", lines: [ + {sku: "free", qty: 1, unitPrice: 9.99, taxClass: "reduced", discountPct: 100, gross: 9.99, discount: 9.99, net: 0, taxRate: 0.07, tax: 0}, + ], reverseCharge: false, totals: {net: 0, tax: 0, taxDue: 0, gross: 0}, note: "nothing to invoice"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + [ + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [{sku: "hours", qty: 1.5, unitPrice: 80, taxClass: "standard", discountPct: null}]}}, + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [ + {sku: "hours", qty: 1.5, unitPrice: 80, taxClass: "standard", discountPct: null, gross: 120, discount: 0, net: 120, taxRate: 0.25, tax: 30}, + ], reverseCharge: false, totals: {net: 120, tax: 30, taxDue: 30, gross: 150}, note: "standard"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + // A return line with negative quantity offsets the sale, tax included. + [ + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [ + {sku: "a", qty: 2, unitPrice: 100, taxClass: "standard"}, + {sku: "a-return", qty: -1, unitPrice: 100, taxClass: "standard"}, + ]}}, + {sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [ + {sku: "a", qty: 2, unitPrice: 100, taxClass: "standard", gross: 200, discount: 0, net: 200, taxRate: 0.25, tax: 50}, + {sku: "a-return", qty: -1, unitPrice: 100, taxClass: "standard", gross: -100, discount: 0, net: -100, taxRate: 0.25, tax: -25}, + ], reverseCharge: false, totals: {net: 100, tax: 25, taxDue: 25, gross: 125}, note: "standard"}}, "bug: invoice.note reads invoice.totals.net, and the unread sibling writes invoice.totals.tax/taxDue/gross are then not run as terminal goals, together with line.taxRate and line.tax that feed them; they vanish from the output", + ], + [{sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [{sku: "a", qty: 1, unitPrice: 1, taxClass: "zero"}]}}, "!error: InputValidationFailed"], + [{sellerCountry: "NO", invoice: {customerType: "b2g", country: "NO", lines: []}}, "!error: InputValidationFailed"], + [{sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO", lines: [{sku: "a", qty: 1, taxClass: "standard"}]}}, "!error: ExpressionFailed"], + [{invoice: {customerType: "b2c", country: "NO", lines: []}}, "!error: MissingRequiredInputs"], + [{sellerCountry: "NO", invoice: {customerType: "b2c", country: "NO"}}, "!error: MissingRequiredInputs"], + [{sellerCountry: "NO", invoice: {country: "NO", lines: []}}, "!error: MissingRequiredInputs"], + ], +} + +// The root cause in isolation: a block that reads one nested computed (`a.t.x`) hides the +// unread sibling under the same parent (`a.t.y`) from the terminal goals, so it never runs. +// Asking for it as a goal still works. +{ + name: "a read of one nested computed hides its unread sibling", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {match: "a.n", arms: [["a.t.x == 1", "'one'"], ["", "'other'"]]}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: "one"}}, "bug: a.t.y is a terminal write, but because a.n reads a.t.x it is not evaluated and is missing from the output"], + [{a: {v: 5}}, {a: {v: 5, t: {x: 6, y: 7}, n: "other"}}, "bug: a.t.y is a terminal write, but because a.n reads a.t.x it is not evaluated and is missing from the output"], + {input: {a: {v: 1}}, goals: ["a.t.y"], output: {a: {v: 1, t: {y: 3}}}}, + {input: {a: {v: 1}}, goals: ["a.n", "a.t.y"], output: {a: {v: 1, t: {x: 2, y: 3}, n: "other"}}}, + ], +} + +// --- Credits ------------------------------------------------------------------------------------- +// Credits are members with an optional expiry (none means never). Promotional credit is capped +// at 20% of the invoice, other credits apply in full, the excess carries forward. + +{ + name: "credits applied to an invoice", + policy: { + models: { + invoice: {total: "number", credits: "credit[]"}, + credit: {kind: "string(refund|goodwill|promo)", amount: "number", expires: "date?"}, + }, + blocks: [ + {expression: "credit.usable", value: "(credit.expires ?? d('9999-12-31')) >= d()"}, + {expression: "invoice.promoCap", value: "round(invoice.total * 0.2, 2)"}, + {expression: "invoice.promoCredit", value: "min([invoice.promoCap, sum(map(filter(invoice.credits, #.usable and #.kind == 'promo'), #.amount))])"}, + {expression: "invoice.otherCredit", value: "sum(map(filter(invoice.credits, #.usable and #.kind != 'promo'), #.amount))"}, + {expression: "invoice.applied", value: "min([invoice.total, invoice.promoCredit + invoice.otherCredit])"}, + {expression: "invoice.amountDue", value: "invoice.total - invoice.applied"}, + {expression: "invoice.carryForward", value: "invoice.otherCredit - max([invoice.applied - invoice.promoCredit, 0])"}, + {match: "invoice.status", arms: [ + ["invoice.total == 0", "'zero-invoice'"], + ["invoice.amountDue == 0", "'settled-by-credit'"], + ["invoice.applied > 0", "'partially-credited'"], + ["", "'payable'"], + ]}, + ], + }, + cases: [ + [ + {invoice: {total: 100, credits: []}}, + {invoice: {total: 100, credits: [], promoCap: 20, promoCredit: 0, otherCredit: 0, applied: 0, amountDue: 100, carryForward: 0, status: "payable"}}, + ], + [ + {invoice: {total: 100, credits: [{kind: "refund", amount: 30}]}}, + {invoice: {total: 100, credits: [{kind: "refund", amount: 30, usable: true}], promoCap: 20, promoCredit: 0, otherCredit: 30, applied: 30, amountDue: 70, carryForward: 0, status: "partially-credited"}}, + ], + // Promo credit beyond the cap is lost, not carried forward. + [ + {invoice: {total: 100, credits: [{kind: "promo", amount: 50}]}}, + {invoice: {total: 100, credits: [{kind: "promo", amount: 50, usable: true}], promoCap: 20, promoCredit: 20, otherCredit: 0, applied: 20, amountDue: 80, carryForward: 0, status: "partially-credited"}}, + ], + [ + {invoice: {total: 100, credits: [{kind: "refund", amount: 80}, {kind: "goodwill", amount: 40}]}}, + {invoice: {total: 100, credits: [{kind: "refund", amount: 80, usable: true}, {kind: "goodwill", amount: 40, usable: true}], promoCap: 20, promoCredit: 0, otherCredit: 120, applied: 100, amountDue: 0, carryForward: 20, status: "settled-by-credit"}}, + ], + [ + {invoice: {total: 100, credits: [{kind: "promo", amount: 15}, {kind: "refund", amount: 90}]}}, + {invoice: {total: 100, credits: [{kind: "promo", amount: 15, usable: true}, {kind: "refund", amount: 90, usable: true}], promoCap: 20, promoCredit: 15, otherCredit: 90, applied: 100, amountDue: 0, carryForward: 5, status: "settled-by-credit"}}, + ], + // A date-only expiry of today is midnight and already past; a later time today is still usable. + [ + {invoice: {total: 100, credits: [{kind: "refund", amount: 50, expires: "2025-03-19"}, {kind: "goodwill", amount: 5, expires: "2025-03-20"}]}}, + {invoice: {total: 100, credits: [{kind: "refund", amount: 50, expires: "2025-03-19", usable: false}, {kind: "goodwill", amount: 5, expires: "2025-03-20", usable: false}], promoCap: 20, promoCredit: 0, otherCredit: 0, applied: 0, amountDue: 100, carryForward: 0, status: "payable"}}, + ], + [ + {invoice: {total: 100, credits: [{kind: "promo", amount: 10, expires: "2025-03-20T23:59:59Z"}, {kind: "refund", amount: 1, expires: null}]}}, + {invoice: {total: 100, credits: [{kind: "promo", amount: 10, expires: "2025-03-20T23:59:59Z", usable: true}, {kind: "refund", amount: 1, expires: null, usable: true}], promoCap: 20, promoCredit: 10, otherCredit: 1, applied: 11, amountDue: 89, carryForward: 0, status: "partially-credited"}}, + ], + [ + {invoice: {total: 0, credits: [{kind: "refund", amount: 10}]}}, + {invoice: {total: 0, credits: [{kind: "refund", amount: 10, usable: true}], promoCap: 0, promoCredit: 0, otherCredit: 10, applied: 0, amountDue: 0, carryForward: 10, status: "zero-invoice"}}, + ], + [ + {invoice: {total: 49.99, credits: [{kind: "promo", amount: 15}]}}, + {invoice: {total: 49.99, credits: [{kind: "promo", amount: 15, usable: true}], promoCap: 10, promoCredit: 10, otherCredit: 0, applied: 10, amountDue: 39.99, carryForward: 0, status: "partially-credited"}}, + ], + [{invoice: {total: 10, credits: [{kind: "voucher", amount: 1}]}}, "!error: InputValidationFailed"], + [{invoice: {total: 10, credits: [{kind: "refund", amount: 1, expires: "soon"}]}}, "!error: InputValidationFailed"], + [{invoice: {total: 10, credits: [{kind: "refund"}]}}, "!error"], + [{invoice: {credits: []}}, "!error: MissingRequiredInputs"], + [{invoice: {total: 10}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Dunning ------------------------------------------------------------------------------------- +// Days overdue from the due date, a stage match that holds disputed invoices and payment plans +// (an optional flag on a single relationship), a late-fee table with a computed cell, a `collect` +// table of actions keyed on the stage and the reminder count. + +{ + name: "dunning stages, fees and actions", + policy: { + models: { + invoice: {due: "date", amount: "number", paid: "number", disputed: "boolean", reminders: "number", customer: "customer"}, + customer: {vip: "boolean", paymentPlan: "boolean?"}, + }, + blocks: [ + {expression: "invoice.outstanding", value: "invoice.amount - invoice.paid"}, + {expression: "invoice.daysOverdue", value: "invoice.outstanding <= 0 ? 0 : max([d().diff(invoice.due, 'day'), 0])"}, + {match: "invoice.stage", arms: [ + ["invoice.outstanding <= 0", "'paid'"], + ["invoice.disputed or (invoice.customer.paymentPlan ?? false)", "'hold'"], + ["invoice.daysOverdue == 0", "'current'"], + ["invoice.daysOverdue <= 14", "'reminder'"], + ["invoice.daysOverdue <= 30", "'second-notice'"], + ["invoice.daysOverdue <= 60 or invoice.customer.vip", "'final-notice'"], + ["", "'collections'"], + ]}, + {table: "fees", inputs: ["invoice.stage", "invoice.customer.vip"], outputs: ["invoice.lateFee"], rules: [ + ["'second-notice'", "false", "15"], + ["'final-notice'", "false", "max([40, round(invoice.outstanding * 0.02, 2)])"], + ["'collections'", "", "round(invoice.outstanding * 0.1, 2)"], + ["", "", "0"], + ]}, + {table: "actions", hit: "collect", inputs: ["invoice.stage", "invoice.reminders"], outputs: ["invoice.actions"], rules: [ + ["'reminder', 'second-notice', 'final-notice'", "< 3", "'send-email'"], + ["'final-notice'", "", "'send-letter'"], + ["'collections'", "", "'refer-agency'"], + ["'second-notice', 'final-notice', 'collections'", ">= 3", "'call-customer'"], + ["'hold'", "", "'pause-dunning'"], + ]}, + {expression: "invoice.totalDue", value: "invoice.outstanding + invoice.lateFee"}, + ], + }, + cases: [ + [ + {invoice: {due: "2025-04-01", amount: 100, paid: 0, disputed: false, reminders: 0, customer: {vip: false}}}, + {invoice: {due: "2025-04-01", amount: 100, paid: 0, disputed: false, reminders: 0, customer: {vip: false}, outstanding: 100, daysOverdue: 0, stage: "current", lateFee: 0, actions: [], totalDue: 100}}, + ], + [ + {invoice: {due: "2025-03-10", amount: 100, paid: 0, disputed: false, reminders: 0, customer: {vip: false}}}, + {invoice: {due: "2025-03-10", amount: 100, paid: 0, disputed: false, reminders: 0, customer: {vip: false}, outstanding: 100, daysOverdue: 10, stage: "reminder", lateFee: 0, actions: ["send-email"], totalDue: 100}}, + ], + [ + {invoice: {due: "2025-03-06", amount: 100, paid: 0, disputed: false, reminders: 1, customer: {vip: false}}}, + {invoice: {due: "2025-03-06", amount: 100, paid: 0, disputed: false, reminders: 1, customer: {vip: false}, outstanding: 100, daysOverdue: 14, stage: "reminder", lateFee: 0, actions: ["send-email"], totalDue: 100}}, + ], + [ + {invoice: {due: "2025-03-05", amount: 100, paid: 0, disputed: false, reminders: 1, customer: {vip: false}}}, + {invoice: {due: "2025-03-05", amount: 100, paid: 0, disputed: false, reminders: 1, customer: {vip: false}, outstanding: 100, daysOverdue: 15, stage: "second-notice", lateFee: 15, actions: ["send-email"], totalDue: 115}}, + ], + [ + {invoice: {due: "2025-02-01", amount: 3000, paid: 0, disputed: false, reminders: 3, customer: {vip: false}}}, + {invoice: {due: "2025-02-01", amount: 3000, paid: 0, disputed: false, reminders: 3, customer: {vip: false}, outstanding: 3000, daysOverdue: 47, stage: "final-notice", lateFee: 60, actions: ["send-letter", "call-customer"], totalDue: 3060}}, + ], + [ + {invoice: {due: "2024-12-01", amount: 500, paid: 0, disputed: false, reminders: 4, customer: {vip: false}}}, + {invoice: {due: "2024-12-01", amount: 500, paid: 0, disputed: false, reminders: 4, customer: {vip: false}, outstanding: 500, daysOverdue: 109, stage: "collections", lateFee: 50, actions: ["refer-agency", "call-customer"], totalDue: 550}}, + ], + // VIP customers stop at final notice and pay no late fee. + [ + {invoice: {due: "2024-12-01", amount: 500, paid: 0, disputed: false, reminders: 2, customer: {vip: true}}}, + {invoice: {due: "2024-12-01", amount: 500, paid: 0, disputed: false, reminders: 2, customer: {vip: true}, outstanding: 500, daysOverdue: 109, stage: "final-notice", lateFee: 0, actions: ["send-email", "send-letter"], totalDue: 500}}, + ], + [ + {invoice: {due: "2024-12-01", amount: 500, paid: 0, disputed: true, reminders: 4, customer: {vip: false}}}, + {invoice: {due: "2024-12-01", amount: 500, paid: 0, disputed: true, reminders: 4, customer: {vip: false}, outstanding: 500, daysOverdue: 109, stage: "hold", lateFee: 0, actions: ["pause-dunning"], totalDue: 500}}, + ], + [ + {invoice: {due: "2025-01-01", amount: 200, paid: 50, disputed: false, reminders: 0, customer: {vip: false, paymentPlan: true}}}, + {invoice: {due: "2025-01-01", amount: 200, paid: 50, disputed: false, reminders: 0, customer: {vip: false, paymentPlan: true}, outstanding: 150, daysOverdue: 78, stage: "hold", lateFee: 0, actions: ["pause-dunning"], totalDue: 150}}, + ], + [ + {invoice: {due: "2025-01-01", amount: 200, paid: 50, disputed: false, reminders: 0, customer: {vip: false, paymentPlan: null}}}, + {invoice: {due: "2025-01-01", amount: 200, paid: 50, disputed: false, reminders: 0, customer: {vip: false, paymentPlan: null}, outstanding: 150, daysOverdue: 78, stage: "collections", lateFee: 15, actions: ["refer-agency"], totalDue: 165}}, + ], + [ + {invoice: {due: "2024-01-01", amount: 100, paid: 100, disputed: false, reminders: 5, customer: {vip: false}}}, + {invoice: {due: "2024-01-01", amount: 100, paid: 100, disputed: false, reminders: 5, customer: {vip: false}, outstanding: 0, daysOverdue: 0, stage: "paid", lateFee: 0, actions: [], totalDue: 0}}, + ], + [ + {invoice: {due: "2024-01-01", amount: 100, paid: 120, disputed: true, reminders: 0, customer: {vip: true}}}, + {invoice: {due: "2024-01-01", amount: 100, paid: 120, disputed: true, reminders: 0, customer: {vip: true}, outstanding: -20, daysOverdue: 0, stage: "paid", lateFee: 0, actions: [], totalDue: -20}}, + ], + [ + {invoice: {due: "2025-02-18", amount: 1000, paid: 400, disputed: false, reminders: 0, customer: {vip: false}}}, + {invoice: {due: "2025-02-18", amount: 1000, paid: 400, disputed: false, reminders: 0, customer: {vip: false}, outstanding: 600, daysOverdue: 30, stage: "second-notice", lateFee: 15, actions: ["send-email"], totalDue: 615}}, + ], + [ + {invoice: {due: "2025-01-19", amount: 1000, paid: 0, disputed: false, reminders: 0, customer: {vip: false}}}, + {invoice: {due: "2025-01-19", amount: 1000, paid: 0, disputed: false, reminders: 0, customer: {vip: false}, outstanding: 1000, daysOverdue: 60, stage: "final-notice", lateFee: 40, actions: ["send-email", "send-letter"], totalDue: 1040}}, + ], + [{invoice: {due: "2025-01-19", amount: 1000, paid: 0, disputed: false, reminders: 0}}, "!error: MissingRequiredInputs"], + [{invoice: {due: "19.01.2025", amount: 1000, paid: 0, disputed: false, reminders: 0, customer: {vip: false}}}, "!error: InputValidationFailed"], + [{invoice: {due: "2025-01-19", amount: 1000, paid: 0, disputed: false, reminders: 0, customer: {vip: "no"}}}, "!error: InputValidationFailed"], + ], +} + +// --- Usage metering ------------------------------------------------------------------------------ +// A plan table with four scalar outputs, overage beyond the included units, a free first seat, +// an annual discount and an upgrade suggestion. + +{ + name: "usage metering with plan tiers", + policy: { + models: {subscription: {plan: "string(starter|growth|scale)", usage: "number", seats: "number", annual: "boolean"}}, + blocks: [ + {table: "plan", inputs: ["subscription.plan"], outputs: ["subscription.fee", "subscription.included", "subscription.unitPrice", "subscription.seatPrice"], rules: [ + ["'starter'", "0", "1000", "0.01", "0"], + ["'growth'", "49", "10000", "0.008", "10"], + ["'scale'", "299", "100000", "0.005", "8"], + ]}, + {expression: "subscription.overage", value: "max([subscription.usage - subscription.included, 0])"}, + {expression: "subscription.usageCharge", value: "round(subscription.overage * subscription.unitPrice, 2)"}, + {expression: "subscription.seatCharge", value: "max([subscription.seats - 1, 0]) * subscription.seatPrice"}, + {expression: "subscription.subtotal", value: "subscription.fee + subscription.usageCharge + subscription.seatCharge"}, + {expression: "subscription.discount", value: "subscription.annual ? round(subscription.subtotal * 0.15, 2) : 0"}, + {expression: "subscription.total", value: "subscription.subtotal - subscription.discount"}, + {match: "subscription.suggestion", arms: [ + ["subscription.plan == 'starter' and subscription.usageCharge > 49", "'upgrade to growth'"], + ["subscription.plan == 'growth' and subscription.usageCharge > 250", "'upgrade to scale'"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [ + {subscription: {plan: "starter", usage: 500, seats: 1, annual: false}}, + {subscription: {plan: "starter", usage: 500, seats: 1, annual: false, fee: 0, included: 1000, unitPrice: 0.01, seatPrice: 0, overage: 0, usageCharge: 0, seatCharge: 0, subtotal: 0, discount: 0, total: 0, suggestion: "none"}}, + ], + [ + {subscription: {plan: "starter", usage: 7000, seats: 3, annual: false}}, + {subscription: {plan: "starter", usage: 7000, seats: 3, annual: false, fee: 0, included: 1000, unitPrice: 0.01, seatPrice: 0, overage: 6000, usageCharge: 60, seatCharge: 0, subtotal: 60, discount: 0, total: 60, suggestion: "upgrade to growth"}}, + ], + [ + {subscription: {plan: "starter", usage: 5900, seats: 1, annual: false}}, + {subscription: {plan: "starter", usage: 5900, seats: 1, annual: false, fee: 0, included: 1000, unitPrice: 0.01, seatPrice: 0, overage: 4900, usageCharge: 49, seatCharge: 0, subtotal: 49, discount: 0, total: 49, suggestion: "none"}}, + ], + [ + {subscription: {plan: "growth", usage: 10000, seats: 5, annual: true}}, + {subscription: {plan: "growth", usage: 10000, seats: 5, annual: true, fee: 49, included: 10000, unitPrice: 0.008, seatPrice: 10, overage: 0, usageCharge: 0, seatCharge: 40, subtotal: 89, discount: 13.35, total: 75.65, suggestion: "none"}}, + ], + [ + {subscription: {plan: "growth", usage: 50000, seats: 1, annual: false}}, + {subscription: {plan: "growth", usage: 50000, seats: 1, annual: false, fee: 49, included: 10000, unitPrice: 0.008, seatPrice: 10, overage: 40000, usageCharge: 320, seatCharge: 0, subtotal: 369, discount: 0, total: 369, suggestion: "upgrade to scale"}}, + ], + // Half-cent amounts round away from zero; zero seats is not a negative seat charge. + [ + {subscription: {plan: "scale", usage: 123457, seats: 0, annual: true}}, + {subscription: {plan: "scale", usage: 123457, seats: 0, annual: true, fee: 299, included: 100000, unitPrice: 0.005, seatPrice: 8, overage: 23457, usageCharge: 117.29, seatCharge: 0, subtotal: 416.29, discount: 62.44, total: 353.85, suggestion: "none"}}, + ], + [ + {subscription: {plan: "starter", usage: 1000.4, seats: 1, annual: true}}, + {subscription: {plan: "starter", usage: 1000.4, seats: 1, annual: true, fee: 0, included: 1000, unitPrice: 0.01, seatPrice: 0, overage: 0.4, usageCharge: 0, seatCharge: 0, subtotal: 0, discount: 0, total: 0, suggestion: "none"}}, + ], + [{subscription: {plan: "enterprise", usage: 1, seats: 1, annual: false}}, "!error: InputValidationFailed"], + [{subscription: {plan: "growth", seats: 1, annual: false}}, "!error: MissingRequiredInputs"], + [{subscription: {plan: "growth", usage: 1, seats: 1, annual: 1}}, "!error: InputValidationFailed"], + ], +} + +// --- Account aging ------------------------------------------------------------------------------- +// Invoices as members bucketed by a per-invoice table with range cells, account aggregates +// including an object literal of bucket sums, utilization of a credit limit and a credit-hold +// assertion made of `or` conditions. + +{ + name: "account aging and credit hold", + policy: { + models: { + account: {name: "string", creditLimit: "number", invoices: "invoice[]"}, + invoice: {number: "string", amount: "number", paid: "number", due: "date"}, + }, + blocks: [ + {expression: "invoice.open", value: "invoice.amount - invoice.paid"}, + {expression: "invoice.overdueDays", value: "invoice.open > 0 ? max([d().diff(invoice.due, 'day'), 0]) : 0"}, + {table: "bucket", inputs: ["invoice.open", "invoice.overdueDays"], outputs: ["invoice.bucket"], rules: [ + ["<= 0", "", "'closed'"], + ["", "0", "'current'"], + ["", "[1..30]", "'1-30'"], + ["", "[31..90]", "'31-90'"], + ["", "", "'90+'"], + ]}, + {expression: "account.balance", value: "sum(map(account.invoices, #.open))"}, + {expression: "account.overdue", value: "sum(map(filter(account.invoices, #.overdueDays > 0), #.open))"}, + {expression: "account.aging", value: "{current: sum(map(filter(account.invoices, #.bucket == 'current'), #.open)), d30: sum(map(filter(account.invoices, #.bucket == '1-30'), #.open)), d90: sum(map(filter(account.invoices, #.bucket == '31-90'), #.open)), d90plus: sum(map(filter(account.invoices, #.bucket == '90+'), #.open))}"}, + {expression: "account.oldest", value: "len(account.invoices) == 0 ? 0 : max(map(account.invoices, #.overdueDays))"}, + {expression: "account.utilization", value: "account.creditLimit > 0 ? round(account.balance / account.creditLimit, 4) : 0"}, + {assertion: "account.creditHold", conditions: [["or", "account.oldest > 90"], ["or", "account.utilization > 1"], "account.overdue > 5000"]}, + {expression: "account.openNumbers", value: "map(filter(account.invoices, #.bucket != 'closed'), #.number)"}, + ], + }, + cases: [ + [ + {account: {name: "a", creditLimit: 1000, invoices: []}}, + {account: {name: "a", creditLimit: 1000, invoices: [], balance: 0, overdue: 0, aging: {current: 0, d30: 0, d90: 0, d90plus: 0}, oldest: 0, utilization: 0, creditHold: false, openNumbers: []}}, + ], + [ + {account: {name: "b", creditLimit: 5000, invoices: [{number: "I1", amount: 1000, paid: 0, due: "2025-04-01"}, {number: "I2", amount: 500, paid: 500, due: "2025-01-01"}]}}, + {account: {name: "b", creditLimit: 5000, invoices: [ + {number: "I1", amount: 1000, paid: 0, due: "2025-04-01", open: 1000, overdueDays: 0, bucket: "current"}, + {number: "I2", amount: 500, paid: 500, due: "2025-01-01", open: 0, overdueDays: 0, bucket: "closed"}, + ], balance: 1000, overdue: 0, aging: {current: 1000, d30: 0, d90: 0, d90plus: 0}, oldest: 0, utilization: 0.2, creditHold: false, openNumbers: ["I1"]}}, + ], + [ + {account: {name: "c", creditLimit: 10000, invoices: [ + {number: "I1", amount: 2000, paid: 500, due: "2025-03-01"}, + {number: "I2", amount: 3000, paid: 0, due: "2025-01-01"}, + {number: "I3", amount: 400, paid: 0, due: "2024-11-01"}, + ]}}, + {account: {name: "c", creditLimit: 10000, invoices: [ + {number: "I1", amount: 2000, paid: 500, due: "2025-03-01", open: 1500, overdueDays: 19, bucket: "1-30"}, + {number: "I2", amount: 3000, paid: 0, due: "2025-01-01", open: 3000, overdueDays: 78, bucket: "31-90"}, + {number: "I3", amount: 400, paid: 0, due: "2024-11-01", open: 400, overdueDays: 139, bucket: "90+"}, + ], balance: 4900, overdue: 4900, aging: {current: 0, d30: 1500, d90: 3000, d90plus: 400}, oldest: 139, utilization: 0.49, creditHold: true, openNumbers: ["I1", "I2", "I3"]}}, + ], + [ + {account: {name: "d", creditLimit: 1000, invoices: [{number: "I1", amount: 1500, paid: 0, due: "2025-04-01"}]}}, + {account: {name: "d", creditLimit: 1000, invoices: [ + {number: "I1", amount: 1500, paid: 0, due: "2025-04-01", open: 1500, overdueDays: 0, bucket: "current"}, + ], balance: 1500, overdue: 0, aging: {current: 1500, d30: 0, d90: 0, d90plus: 0}, oldest: 0, utilization: 1.5, creditHold: true, openNumbers: ["I1"]}}, + ], + [ + {account: {name: "e", creditLimit: 100000, invoices: [{number: "I1", amount: 6000, paid: 0, due: "2025-03-01"}]}}, + {account: {name: "e", creditLimit: 100000, invoices: [ + {number: "I1", amount: 6000, paid: 0, due: "2025-03-01", open: 6000, overdueDays: 19, bucket: "1-30"}, + ], balance: 6000, overdue: 6000, aging: {current: 0, d30: 6000, d90: 0, d90plus: 0}, oldest: 19, utilization: 0.06, creditHold: true, openNumbers: ["I1"]}}, + ], + // Bucket edges: 30 days is 1-30, 31 is 31-90, 90 is still 31-90 and does not trigger a hold; + // an invoice due earlier today is current. + [ + {account: {name: "f", creditLimit: 0, invoices: [ + {number: "A", amount: 100, paid: 0, due: "2025-02-18"}, + {number: "B", amount: 100, paid: 0, due: "2025-02-17"}, + {number: "C", amount: 100, paid: 0, due: "2024-12-20"}, + {number: "D", amount: 100, paid: 0, due: "2025-03-20"}, + ]}}, + {account: {name: "f", creditLimit: 0, invoices: [ + {number: "A", amount: 100, paid: 0, due: "2025-02-18", open: 100, overdueDays: 30, bucket: "1-30"}, + {number: "B", amount: 100, paid: 0, due: "2025-02-17", open: 100, overdueDays: 31, bucket: "31-90"}, + {number: "C", amount: 100, paid: 0, due: "2024-12-20", open: 100, overdueDays: 90, bucket: "31-90"}, + {number: "D", amount: 100, paid: 0, due: "2025-03-20", open: 100, overdueDays: 0, bucket: "current"}, + ], balance: 400, overdue: 300, aging: {current: 100, d30: 100, d90: 200, d90plus: 0}, oldest: 90, utilization: 0, creditHold: false, openNumbers: ["A", "B", "C", "D"]}}, + ], + [ + {account: {name: "g", creditLimit: 300, invoices: [{number: "X", amount: 100, paid: 150, due: "2020-01-01"}, {number: "Y", amount: 250.5, paid: 0, due: "2025-03-19"}]}}, + {account: {name: "g", creditLimit: 300, invoices: [ + {number: "X", amount: 100, paid: 150, due: "2020-01-01", open: -50, overdueDays: 0, bucket: "closed"}, + {number: "Y", amount: 250.5, paid: 0, due: "2025-03-19", open: 250.5, overdueDays: 1, bucket: "1-30"}, + ], balance: 200.5, overdue: 250.5, aging: {current: 0, d30: 250.5, d90: 0, d90plus: 0}, oldest: 1, utilization: 0.6683, creditHold: false, openNumbers: ["Y"]}}, + ], + [{account: {name: "x", creditLimit: 1, invoices: [{number: "I", amount: 1, paid: 0, due: "2025-02-30"}]}}, "!error: InputValidationFailed"], + [{account: {name: "x", invoices: []}}, "!error: MissingRequiredInputs"], + [{account: {name: "x", creditLimit: 1, invoices: [{number: "I", amount: 1, due: "2025-01-01"}]}}, "!error: ExpressionFailed"], + ], +} + +// --- Proration ----------------------------------------------------------------------------------- +// A mid-period plan change: day counts from dates, the remaining fraction rounded to four places, +// credit for the old price and charge for the new one, and the direction of the change. + +{ + name: "proration on a plan change", + policy: { + models: {change: {periodStart: "date", periodEnd: "date", changedOn: "date", oldPrice: "number", newPrice: "number"}}, + blocks: [ + {expression: "change.periodDays", value: "change.periodEnd.diff(change.periodStart, 'day')"}, + {expression: "change.remainingDays", value: "max([change.periodEnd.diff(change.changedOn, 'day'), 0])"}, + {expression: "change.fraction", value: "change.periodDays > 0 ? round(change.remainingDays / change.periodDays, 4) : 0"}, + {expression: "change.credit", value: "round(change.oldPrice * change.fraction, 2)"}, + {expression: "change.charge", value: "round(change.newPrice * change.fraction, 2)"}, + {expression: "change.net", value: "change.charge - change.credit"}, + {match: "change.kind", arms: [["change.net > 0", "'upgrade'"], ["change.net < 0", "'downgrade'"], ["", "'no-change'"]]}, + ], + }, + cases: [ + [ + {change: {periodStart: "2025-03-01", periodEnd: "2025-04-01", changedOn: "2025-03-17", oldPrice: 31, newPrice: 62}}, + {change: {periodStart: "2025-03-01", periodEnd: "2025-04-01", changedOn: "2025-03-17", oldPrice: 31, newPrice: 62, periodDays: 31, remainingDays: 15, fraction: 0.4839, credit: 15, charge: 30, net: 15, kind: "upgrade"}}, + ], + [ + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-16", oldPrice: 100, newPrice: 40}}, + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-16", oldPrice: 100, newPrice: 40, periodDays: 30, remainingDays: 15, fraction: 0.5, credit: 50, charge: 20, net: -30, kind: "downgrade"}}, + ], + [ + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-16", oldPrice: 10, newPrice: 10}}, + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-16", oldPrice: 10, newPrice: 10, periodDays: 30, remainingDays: 15, fraction: 0.5, credit: 5, charge: 5, net: 0, kind: "no-change"}}, + ], + [ + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-04-05", oldPrice: 10, newPrice: 99}}, + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-04-05", oldPrice: 10, newPrice: 99, periodDays: 30, remainingDays: 0, fraction: 0, credit: 0, charge: 0, net: 0, kind: "no-change"}}, + ], + [ + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-01", oldPrice: 20, newPrice: 50}}, + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-01", oldPrice: 20, newPrice: 50, periodDays: 30, remainingDays: 30, fraction: 1, credit: 20, charge: 50, net: 30, kind: "upgrade"}}, + ], + [ + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-01", changedOn: "2025-03-01", oldPrice: 20, newPrice: 50}}, + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-01", changedOn: "2025-03-01", oldPrice: 20, newPrice: 50, periodDays: 0, remainingDays: 0, fraction: 0, credit: 0, charge: 0, net: 0, kind: "no-change"}}, + ], + [ + {change: {periodStart: "2024-02-01", periodEnd: "2024-03-01", changedOn: "2024-02-15", oldPrice: 29, newPrice: 58}}, + {change: {periodStart: "2024-02-01", periodEnd: "2024-03-01", changedOn: "2024-02-15", oldPrice: 29, newPrice: 58, periodDays: 29, remainingDays: 15, fraction: 0.5172, credit: 15, charge: 30, net: 15, kind: "upgrade"}}, + ], + // A change at noon leaves 14.5 days, counted as 14 whole days. + [ + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-16T12:00:00Z", oldPrice: 30, newPrice: 60}}, + {change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-16T12:00:00Z", oldPrice: 30, newPrice: 60, periodDays: 30, remainingDays: 14, fraction: 0.4667, credit: 14, charge: 28, net: 14, kind: "upgrade"}}, + ], + [{change: {periodStart: "2025-03-01", periodEnd: "2025-03-32", changedOn: "2025-03-01", oldPrice: 1, newPrice: 1}}, "!error: InputValidationFailed"], + [{change: {periodStart: "2025-03-01", periodEnd: "2025-03-31", changedOn: "2025-03-01", newPrice: 1}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Currency conversion with nested paths and goals --------------------------------------------- +// The invoice currency is a reference into a pool carrying the rate and the number of decimals; +// converted amounts are written under `invoice.local.*`. Goals pick a nested leaf or a sibling. + +{ + name: "currency conversion with nested outputs and goals", + policy: { + models: { + invoice: {amount: "number", fees: "number?", currency: "¤cy"}, + currency: {id: "string", rate: "number", decimals: "number"}, + }, + blocks: [ + {expression: "invoice.local.amount", value: "round(invoice.amount * invoice.currency.rate, invoice.currency.decimals)"}, + {expression: "invoice.local.fees", value: "round((invoice.fees ?? 0) * invoice.currency.rate, invoice.currency.decimals)"}, + {expression: "invoice.local.total", value: "invoice.local.amount + invoice.local.fees"}, + {expression: "invoice.label", value: "invoice.currency.id + ' ' + string(invoice.amount)"}, + ], + }, + cases: [ + [ + {invoice: {amount: 100, currency: "EUR"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, + {invoice: {amount: 100, currency: {id: "EUR", rate: 11.5, decimals: 2}, local: {amount: 1150, fees: 0, total: 1150}, label: "EUR 100"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, + ], + [ + {invoice: {amount: 12345, fees: 100, currency: "JPY"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}, {id: "JPY", rate: 0.0712, decimals: 0}]}, + {invoice: {amount: 12345, fees: 100, currency: {id: "JPY", rate: 0.0712, decimals: 0}, local: {amount: 879, fees: 7, total: 886}, label: "JPY 12345"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}, {id: "JPY", rate: 0.0712, decimals: 0}]}, + ], + [ + {invoice: {amount: 19.99, fees: null, currency: "USD"}, currency: [{id: "USD", rate: 10.555, decimals: 2}]}, + {invoice: {amount: 19.99, fees: null, currency: {id: "USD", rate: 10.555, decimals: 2}, local: {amount: 210.99, fees: 0, total: 210.99}, label: "USD 19.99"}, currency: [{id: "USD", rate: 10.555, decimals: 2}]}, + ], + { + input: {invoice: {amount: 100, currency: "EUR"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, + goals: ["invoice.label"], + output: {invoice: {amount: 100, currency: {id: "EUR", rate: 11.5, decimals: 2}, label: "EUR 100"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, + }, + { + input: {invoice: {amount: 2, fees: 1, currency: "EUR"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, + goals: ["invoice.local.total"], + output: {invoice: {amount: 2, fees: 1, currency: {id: "EUR", rate: 11.5, decimals: 2}, local: {amount: 23, fees: 11.5, total: 34.5}}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, + }, + { + input: {invoice: {amount: 2, fees: 1, currency: "EUR"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, + goals: ["invoice.local.fees"], + output: {invoice: {amount: 2, fees: 1, currency: {id: "EUR", rate: 11.5, decimals: 2}, local: {fees: 11.5}}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, + }, + [{invoice: {amount: 1, currency: "GBP"}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, "!error: InputValidationFailed"], + [{invoice: {amount: 1, currency: "EUR"}, currency: [{id: "EUR", rate: "11.5", decimals: 2}]}, "!error: InputValidationFailed"], + [{invoice: {amount: 1}, currency: [{id: "EUR", rate: 11.5, decimals: 2}]}, "!error: MissingRequiredInputs"], + ], +} diff --git a/core/engine/tests/spec/policy/27-policy-dates.json5 b/core/engine/tests/spec/policy/27-policy-dates.json5 new file mode 100644 index 00000000..e16418ce --- /dev/null +++ b/core/engine/tests/spec/policy/27-policy-dates.json5 @@ -0,0 +1,930 @@ +// Dates in policies. A `date` property accepts any text the date parser reads (RFC 3339, ISO +// date, `YYYY-MM-DD HH:MM[:SS]`, slash and compact forms, year-month and year); the value is +// converted to a date before evaluation and keeps its source text, so an input date (or a plain +// copy of it) is written back exactly as it came in. A date computed by an operation is written +// in its full RFC 3339 form. Evaluation time is fixed at 2025-03-20T10:15:30Z, time zone UTC. +// Chapters 01 and 17 cover the basics (formats rejected, age from a birth date, a table over a +// date column); this chapter goes wider. + +// --------------------------------------------------------------------------------------------- +// Accepted text shapes. Every shape the date parser reads is a valid `date` input; the output +// keeps the text unchanged. + +{ + name: "a date property accepts every parseable text shape", + policy: { + models: {event: {at: "date"}}, + blocks: [ + {expression: "event.year", value: "event.at.year()"}, + {expression: "event.day", value: "event.at.day()"}, + ], + }, + cases: [ + [{event: {at: "2025-03-20"}}, {event: {at: "2025-03-20", year: 2025, day: 20}}], + [{event: {at: "2025-03-20 14:30"}}, {event: {at: "2025-03-20 14:30", year: 2025, day: 20}}], + [{event: {at: "2025-03-20 14:30:45"}}, {event: {at: "2025-03-20 14:30:45", year: 2025, day: 20}}], + [{event: {at: "2025-03-20T14:30:45Z"}}, {event: {at: "2025-03-20T14:30:45Z", year: 2025, day: 20}}], + [{event: {at: "2025-03-20T14:30:45.123Z"}}, {event: {at: "2025-03-20T14:30:45.123Z", year: 2025, day: 20}}], + [{event: {at: "2025-03-20T14:30"}}, {event: {at: "2025-03-20T14:30", year: 2025, day: 20}}], + [{event: {at: "2025/03/20"}}, {event: {at: "2025/03/20", year: 2025, day: 20}}], + [{event: {at: "20250320"}}, {event: {at: "20250320", year: 2025, day: 20}}], + [{event: {at: "2025-03"}}, {event: {at: "2025-03", year: 2025, day: 1}}], + [{event: {at: "2025"}}, {event: {at: "2025", year: 2025, day: 1}}], + ], +} + +{ + name: "an offset in the input names an instant shown in the evaluation zone", + policy: { + models: {event: {at: "date"}}, + blocks: [ + {expression: "event.day", value: "event.at.day()"}, + {expression: "event.hour", value: "event.at.hour()"}, + {expression: "event.utc", value: "event.at.format('%Y-%m-%dT%H:%M')"}, + ], + }, + cases: [ + [{event: {at: "2025-03-20T23:30:00-02:00"}}, {event: {at: "2025-03-20T23:30:00-02:00", day: 21, hour: 1, utc: "2025-03-21T01:30"}}], + [{event: {at: "2025-03-20T01:00:00+02:00"}}, {event: {at: "2025-03-20T01:00:00+02:00", day: 19, hour: 23, utc: "2025-03-19T23:00"}}], + [{event: {at: "2025-03-20T12:00:00+00:00"}}, {event: {at: "2025-03-20T12:00:00+00:00", day: 20, hour: 12, utc: "2025-03-20T12:00"}}], + [{event: {at: "2025-03-20T12:00:00Z"}}, {event: {at: "2025-03-20T12:00:00Z", day: 20, hour: 12, utc: "2025-03-20T12:00"}}], + ], +} + +{ + name: "malformed date text is rejected before evaluation", + policy: { + models: {event: {at: "date"}}, + blocks: [{expression: "event.year", value: "event.at.year()"}], + }, + cases: [ + [{event: {at: "2025-02-30"}}, "!error: InputValidationFailed"], + [{event: {at: "2025-13-01"}}, "!error: InputValidationFailed"], + [{event: {at: "2025-03-20 24:00"}}, "!error: InputValidationFailed"], + [{event: {at: "2025-03-20 12:60"}}, "!error: InputValidationFailed"], + [{event: {at: "20-03-2025"}}, "!error: InputValidationFailed"], + [{event: {at: "03/20/2025"}}, "!error: InputValidationFailed"], + [{event: {at: "2025-03-20T"}}, "!error: InputValidationFailed"], + [{event: {at: "today"}}, "!error: InputValidationFailed"], + [{event: {at: "Europe/Berlin"}}, "!error: InputValidationFailed"], + [{event: {at: "March 20, 2025"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "non-string date values are rejected", + policy: { + models: {event: {at: "date"}}, + blocks: [{expression: "event.year", value: "event.at.year()"}], + }, + cases: [ + [{event: {at: 1742465730000}}, "!error: InputValidationFailed"], + [{event: {at: 0}}, "!error: InputValidationFailed"], + [{event: {at: false}}, "!error: InputValidationFailed"], + [{event: {at: ["2025-03-20"]}}, "!error: InputValidationFailed"], + [{event: {at: {date: "2025-03-20"}}}, "!error: InputValidationFailed"], + [{event: {at: "2025-03-20"}}, {event: {at: "2025-03-20", year: 2025}}], + ], +} + +{ + name: "leap days validate only in leap years", + policy: { + models: {event: {at: "date"}}, + blocks: [{expression: "event.next", value: "event.at.add(1, 'day').format('%m-%d')"}], + }, + cases: [ + [{event: {at: "2024-02-29"}}, {event: {at: "2024-02-29", next: "03-01"}}], + [{event: {at: "2000-02-29"}}, {event: {at: "2000-02-29", next: "03-01"}}], + [{event: {at: "2023-02-29"}}, "!error: InputValidationFailed"], + [{event: {at: "1900-02-29"}}, "!error: InputValidationFailed"], + [{event: {at: "2023-02-28"}}, {event: {at: "2023-02-28", next: "03-01"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Output form. A plain copy of an input date keeps the source text; anything that builds a new +// date (d(), add, startOf, ...) writes the full RFC 3339 form in the evaluation zone. + +{ + name: "copies keep the source text, operations write the full form", + policy: { + models: {event: {at: "date"}}, + blocks: [ + {expression: "event.copy", value: "event.at"}, + {expression: "event.wrapped", value: "d(event.at)"}, + {expression: "event.plusZero", value: "event.at.add(0, 'day')"}, + {expression: "event.dayStart", value: "event.at.startOf('day')"}, + ], + }, + cases: [ + [ + {event: {at: "2025-03-20"}}, + {event: {at: "2025-03-20", copy: "2025-03-20", wrapped: "2025-03-20T00:00:00Z", plusZero: "2025-03-20T00:00:00Z", dayStart: "2025-03-20T00:00:00Z"}}, + ], + [ + {event: {at: "2025-03-20 14:30"}}, + {event: {at: "2025-03-20 14:30", copy: "2025-03-20 14:30", wrapped: "2025-03-20T14:30:00Z", plusZero: "2025-03-20T14:30:00Z", dayStart: "2025-03-20T00:00:00Z"}}, + ], + [ + {event: {at: "20250320"}}, + {event: {at: "20250320", copy: "20250320", wrapped: "2025-03-20T00:00:00Z", plusZero: "2025-03-20T00:00:00Z", dayStart: "2025-03-20T00:00:00Z"}}, + ], + [ + {event: {at: "2025-03-20T23:30:00-02:00"}}, + {event: {at: "2025-03-20T23:30:00-02:00", copy: "2025-03-20T23:30:00-02:00", wrapped: "2025-03-21T01:30:00Z", plusZero: "2025-03-21T01:30:00Z", dayStart: "2025-03-21T00:00:00Z"}}, + ], + ], +} + +{ + name: "dates inside computed objects and lists", + policy: { + models: {event: {start: "date", end: "date"}}, + blocks: [ + {expression: "event.span", value: "{from: event.start, to: event.end}"}, + {expression: "event.both", value: "[event.start, event.end]"}, + {expression: "event.shifted", value: "{from: event.start.add(1, 'day')}"}, + ], + }, + cases: [ + [ + {event: {start: "2025-01-01", end: "2025-01-31"}}, + {event: {start: "2025-01-01", end: "2025-01-31", span: {from: "2025-01-01", to: "2025-01-31"}, both: ["2025-01-01", "2025-01-31"], shifted: {from: "2025-01-02T00:00:00Z"}}}, + ], + [ + {event: {start: "2025-01-01T08:00:00Z", end: "2025/02/01"}}, + {event: {start: "2025-01-01T08:00:00Z", end: "2025/02/01", span: {from: "2025-01-01T08:00:00Z", to: "2025/02/01"}, both: ["2025-01-01T08:00:00Z", "2025/02/01"], shifted: {from: "2025-01-02T08:00:00Z"}}}, + ], + ], +} + +{ + name: "date literals and now in computed values", + policy: { + models: {event: {name: "string"}}, + blocks: [ + {expression: "event.now", value: "d()"}, + {expression: "event.fixed", value: "d('2025-12-31')"}, + {expression: "event.today", value: "d().startOf('day')"}, + {expression: "event.label", value: "event.name + ' @ ' + d().format('%Y-%m-%d')"}, + ], + }, + cases: [ + [{event: {name: "a"}}, {event: {name: "a", now: "2025-03-20T10:15:30Z", fixed: "2025-12-31T00:00:00Z", today: "2025-03-20T00:00:00Z", label: "a @ 2025-03-20"}}], + [{event: {name: ""}}, {event: {name: "", now: "2025-03-20T10:15:30Z", fixed: "2025-12-31T00:00:00Z", today: "2025-03-20T00:00:00Z", label: " @ 2025-03-20"}}], + ], +} + +{ + name: "formatting dates into strings", + policy: { + models: {event: {at: "date"}}, + blocks: [ + {expression: "event.iso", value: "event.at.format('%Y-%m-%d')"}, + {expression: "event.time", value: "event.at.format('%H:%M:%S')"}, + {expression: "event.long", value: "event.at.format('%d %B %Y')"}, + {expression: "event.weekday", value: "event.at.format('%A')"}, + ], + }, + cases: [ + [{event: {at: "2025-03-20"}}, {event: {at: "2025-03-20", iso: "2025-03-20", time: "00:00:00", long: "20 March 2025", weekday: "Thursday"}}], + [{event: {at: "2025-12-25 18:05:09"}}, {event: {at: "2025-12-25 18:05:09", iso: "2025-12-25", time: "18:05:09", long: "25 December 2025", weekday: "Thursday"}}], + [{event: {at: "2000-01-01T00:00:00Z"}}, {event: {at: "2000-01-01T00:00:00Z", iso: "2000-01-01", time: "00:00:00", long: "01 January 2000", weekday: "Saturday"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Comparisons. Dates compare by instant, whatever text shape they came in. + +{ + name: "dates in different shapes compare by instant", + policy: { + models: {pair: {a: "date", b: "date"}}, + blocks: [ + {expression: "pair.eq", value: "pair.a == pair.b"}, + {expression: "pair.lt", value: "pair.a < pair.b"}, + {expression: "pair.gte", value: "pair.a >= pair.b"}, + ], + }, + cases: [ + [{pair: {a: "2025-03-20", b: "2025-03-20T00:00:00Z"}}, {pair: {a: "2025-03-20", b: "2025-03-20T00:00:00Z", eq: true, lt: false, gte: true}}], + [{pair: {a: "2025-03-20", b: "20250320"}}, {pair: {a: "2025-03-20", b: "20250320", eq: true, lt: false, gte: true}}], + [{pair: {a: "2025-03-20T02:00:00+02:00", b: "2025-03-20"}}, {pair: {a: "2025-03-20T02:00:00+02:00", b: "2025-03-20", eq: true, lt: false, gte: true}}], + [{pair: {a: "2025-03-20", b: "2025-03-20 00:00:01"}}, {pair: {a: "2025-03-20", b: "2025-03-20 00:00:01", eq: false, lt: true, gte: false}}], + [{pair: {a: "2025-03", b: "2025-02-28"}}, {pair: {a: "2025-03", b: "2025-02-28", eq: false, lt: false, gte: true}}], + [{pair: {a: "2024", b: "2025"}}, {pair: {a: "2024", b: "2025", eq: false, lt: true, gte: false}}], + ], +} + +{ + name: "unit-aware comparisons", + policy: { + models: {pair: {a: "date", b: "date"}}, + blocks: [ + {expression: "pair.sameDay", value: "pair.a.isSame(pair.b, 'day')"}, + {expression: "pair.sameMonth", value: "pair.a.isSame(pair.b, 'month')"}, + {expression: "pair.beforeDay", value: "pair.a.isBefore(pair.b, 'day')"}, + {expression: "pair.afterYear", value: "pair.a.isAfter(pair.b, 'year')"}, + ], + }, + cases: [ + [{pair: {a: "2025-03-20 08:00", b: "2025-03-20 23:00"}}, {pair: {a: "2025-03-20 08:00", b: "2025-03-20 23:00", sameDay: true, sameMonth: true, beforeDay: false, afterYear: false}}], + [{pair: {a: "2025-03-19 23:59", b: "2025-03-20 00:00"}}, {pair: {a: "2025-03-19 23:59", b: "2025-03-20 00:00", sameDay: false, sameMonth: true, beforeDay: true, afterYear: false}}], + [{pair: {a: "2026-01-01", b: "2025-12-31"}}, {pair: {a: "2026-01-01", b: "2025-12-31", sameDay: false, sameMonth: false, beforeDay: false, afterYear: true}}], + [{pair: {a: "2025-02-28", b: "2025-03-01"}}, {pair: {a: "2025-02-28", b: "2025-03-01", sameDay: false, sameMonth: false, beforeDay: true, afterYear: false}}], + ], +} + +{ + name: "comparing with the fixed evaluation time", + policy: { + models: {event: {at: "date"}}, + blocks: [ + {expression: "event.past", value: "event.at < d()"}, + {expression: "event.today", value: "event.at.isSame(d(), 'day')"}, + {expression: "event.thisMonth", value: "event.at.isSame(d(), 'month')"}, + {expression: "event.inDays", value: "event.at.diff(d().startOf('day'), 'day')"}, + ], + }, + cases: [ + [{event: {at: "2025-03-20T10:15:29Z"}}, {event: {at: "2025-03-20T10:15:29Z", past: true, today: true, thisMonth: true, inDays: 0}}], + [{event: {at: "2025-03-20T10:15:31Z"}}, {event: {at: "2025-03-20T10:15:31Z", past: false, today: true, thisMonth: true, inDays: 0}}], + [{event: {at: "2025-03-19"}}, {event: {at: "2025-03-19", past: true, today: false, thisMonth: true, inDays: -1}}], + [{event: {at: "2025-04-01"}}, {event: {at: "2025-04-01", past: false, today: false, thisMonth: false, inDays: 12}}], + [{event: {at: "2024-03-20"}}, {event: {at: "2024-03-20", past: true, today: false, thisMonth: false, inDays: -365}}], + ], +} + +{ + name: "a date between two bounds", + policy: { + models: {policy: {start: "date", end: "date", claim: "date"}}, + blocks: [ + {expression: "policy.covered", value: "policy.claim >= policy.start and policy.claim <= policy.end"}, + {expression: "policy.inRange", value: "policy.claim in [policy.start..policy.end]"}, + ], + }, + cases: [ + [{policy: {start: "2025-01-01", end: "2025-12-31", claim: "2025-06-15"}}, {policy: {start: "2025-01-01", end: "2025-12-31", claim: "2025-06-15", covered: true, inRange: true}}], + [{policy: {start: "2025-01-01", end: "2025-12-31", claim: "2025-01-01"}}, {policy: {start: "2025-01-01", end: "2025-12-31", claim: "2025-01-01", covered: true, inRange: true}}], + [{policy: {start: "2025-01-01", end: "2025-12-31", claim: "2025-12-31"}}, {policy: {start: "2025-01-01", end: "2025-12-31", claim: "2025-12-31", covered: true, inRange: true}}], + [{policy: {start: "2025-01-01", end: "2025-12-31", claim: "2025-12-31 00:00:01"}}, {policy: {start: "2025-01-01", end: "2025-12-31", claim: "2025-12-31 00:00:01", covered: false, inRange: false}}], + [{policy: {start: "2025-01-01", end: "2025-12-31", claim: "2024-12-31"}}, {policy: {start: "2025-01-01", end: "2025-12-31", claim: "2024-12-31", covered: false, inRange: false}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Arithmetic. add/sub with a unit or a duration string, diff in units, start/end of units. + +{ + name: "adding and subtracting with units", + policy: { + models: {loan: {start: "date"}}, + blocks: [ + {expression: "loan.firstDue", value: "loan.start.add(1, 'month')"}, + {expression: "loan.maturity", value: "loan.start.add(5, 'year')"}, + {expression: "loan.grace", value: "loan.start.add(14, 'day')"}, + {expression: "loan.notice", value: "loan.start.sub(2, 'week')"}, + ], + }, + cases: [ + [{loan: {start: "2025-01-15"}}, {loan: {start: "2025-01-15", firstDue: "2025-02-15T00:00:00Z", maturity: "2030-01-15T00:00:00Z", grace: "2025-01-29T00:00:00Z", notice: "2025-01-01T00:00:00Z"}}], + [{loan: {start: "2025-01-31"}}, {loan: {start: "2025-01-31", firstDue: "2025-02-28T00:00:00Z", maturity: "2030-01-31T00:00:00Z", grace: "2025-02-14T00:00:00Z", notice: "2025-01-17T00:00:00Z"}}], + [{loan: {start: "2024-12-20 09:30"}}, {loan: {start: "2024-12-20 09:30", firstDue: "2025-01-20T09:30:00Z", maturity: "2029-12-20T09:30:00Z", grace: "2025-01-03T09:30:00Z", notice: "2024-12-06T09:30:00Z"}}], + [{loan: {start: "2024-03-01"}}, {loan: {start: "2024-03-01", firstDue: "2024-04-01T00:00:00Z", maturity: "2029-03-01T00:00:00Z", grace: "2024-03-15T00:00:00Z", notice: "2024-02-16T00:00:00Z"}}], + ], +} + +{ + name: "an input number of days drives the shift", + policy: { + models: {invoice: {issued: "date", terms: "number"}}, + blocks: [ + {expression: "invoice.due", value: "invoice.issued.add(invoice.terms, 'day')"}, + {expression: "invoice.overdue", value: "invoice.due < d()"}, + ], + }, + cases: [ + [{invoice: {issued: "2025-02-01", terms: 30}}, {invoice: {issued: "2025-02-01", terms: 30, due: "2025-03-03T00:00:00Z", overdue: true}}], + [{invoice: {issued: "2025-03-01", terms: 30}}, {invoice: {issued: "2025-03-01", terms: 30, due: "2025-03-31T00:00:00Z", overdue: false}}], + [{invoice: {issued: "2025-03-20", terms: 0}}, {invoice: {issued: "2025-03-20", terms: 0, due: "2025-03-20T00:00:00Z", overdue: true}}], + [{invoice: {issued: "2025-04-01", terms: -15}}, {invoice: {issued: "2025-04-01", terms: -15, due: "2025-03-17T00:00:00Z", overdue: true}}], + [{invoice: {issued: "2025-03-20"}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "duration strings from input", + policy: { + models: {plan: {start: "date", term: "string"}}, + blocks: [{expression: "plan.end", value: "plan.start.add(plan.term)"}], + }, + cases: [ + [{plan: {start: "2025-01-01", term: "30d"}}, {plan: {start: "2025-01-01", term: "30d", end: "2025-01-31T00:00:00Z"}}], + [{plan: {start: "2025-01-01", term: "1y"}}, {plan: {start: "2025-01-01", term: "1y", end: "2026-01-01T00:00:00Z"}}], + [{plan: {start: "2025-01-01", term: "1M"}}, {plan: {start: "2025-01-01", term: "1M", end: "2025-02-01T00:00:00Z"}}], + [{plan: {start: "2025-01-01", term: "2h 30m"}}, {plan: {start: "2025-01-01", term: "2h 30m", end: "2025-01-01T02:30:00Z"}}], + [{plan: {start: "2025-01-01", term: "1q"}}, {plan: {start: "2025-01-01", term: "1q", end: "2025-04-01T00:00:00Z"}}], + [{plan: {start: "2025-01-01", term: "soon"}}, "!error"], + ], +} + +{ + name: "differences in several units", + policy: { + models: {stay: {checkIn: "date", checkOut: "date"}}, + blocks: [ + {expression: "stay.nights", value: "stay.checkOut.diff(stay.checkIn, 'day')"}, + {expression: "stay.hours", value: "stay.checkOut.diff(stay.checkIn, 'hour')"}, + {expression: "stay.months", value: "stay.checkOut.diff(stay.checkIn, 'month')"}, + ], + }, + cases: [ + [{stay: {checkIn: "2025-03-01", checkOut: "2025-03-08"}}, {stay: {checkIn: "2025-03-01", checkOut: "2025-03-08", nights: 7, hours: 168, months: 0}}], + [{stay: {checkIn: "2025-03-01 15:00", checkOut: "2025-03-02 11:00"}}, {stay: {checkIn: "2025-03-01 15:00", checkOut: "2025-03-02 11:00", nights: 0, hours: 20, months: 0}}], + [{stay: {checkIn: "2025-01-31", checkOut: "2025-03-01"}}, {stay: {checkIn: "2025-01-31", checkOut: "2025-03-01", nights: 29, hours: 696, months: 1}}], + [{stay: {checkIn: "2025-03-08", checkOut: "2025-03-01"}}, {stay: {checkIn: "2025-03-08", checkOut: "2025-03-01", nights: -7, hours: -168, months: 0}}], + [{stay: {checkIn: "2024-02-28", checkOut: "2024-03-01"}}, {stay: {checkIn: "2024-02-28", checkOut: "2024-03-01", nights: 2, hours: 48, months: 0}}], + ], +} + +{ + name: "start and end of a period", + policy: { + models: {event: {at: "date"}}, + blocks: [ + {expression: "event.monthStart", value: "event.at.startOf('month')"}, + {expression: "event.monthEnd", value: "event.at.endOf('month').format('%Y-%m-%d')"}, + {expression: "event.yearStart", value: "event.at.startOf('year')"}, + ], + }, + cases: [ + [{event: {at: "2025-03-20 14:30"}}, {event: {at: "2025-03-20 14:30", monthStart: "2025-03-01T00:00:00Z", monthEnd: "2025-03-31", yearStart: "2025-01-01T00:00:00Z"}}], + [{event: {at: "2024-02-10"}}, {event: {at: "2024-02-10", monthStart: "2024-02-01T00:00:00Z", monthEnd: "2024-02-29", yearStart: "2024-01-01T00:00:00Z"}}], + [{event: {at: "2025-02-10"}}, {event: {at: "2025-02-10", monthStart: "2025-02-01T00:00:00Z", monthEnd: "2025-02-28", yearStart: "2025-01-01T00:00:00Z"}}], + [{event: {at: "2025-12-31T23:59:59Z"}}, {event: {at: "2025-12-31T23:59:59Z", monthStart: "2025-12-01T00:00:00Z", monthEnd: "2025-12-31", yearStart: "2025-01-01T00:00:00Z"}}], + ], +} + +{ + name: "a computed date feeds later blocks", + policy: { + models: {subscription: {started: "date", months: "number"}}, + blocks: [ + {expression: "subscription.renews", value: "subscription.started.add(subscription.months, 'month')"}, + {expression: "subscription.daysLeft", value: "subscription.renews.diff(d().startOf('day'), 'day')"}, + {expression: "subscription.expiringSoon", value: "subscription.daysLeft >= 0 and subscription.daysLeft <= 30"}, + {expression: "subscription.renewYear", value: "subscription.renews.year()"}, + ], + }, + cases: [ + [{subscription: {started: "2024-04-01", months: 12}}, {subscription: {started: "2024-04-01", months: 12, renews: "2025-04-01T00:00:00Z", daysLeft: 12, expiringSoon: true, renewYear: 2025}}], + [{subscription: {started: "2024-04-01", months: 24}}, {subscription: {started: "2024-04-01", months: 24, renews: "2026-04-01T00:00:00Z", daysLeft: 377, expiringSoon: false, renewYear: 2026}}], + [{subscription: {started: "2024-03-01", months: 12}}, {subscription: {started: "2024-03-01", months: 12, renews: "2025-03-01T00:00:00Z", daysLeft: -19, expiringSoon: false, renewYear: 2025}}], + [{subscription: {started: "2025-03-20", months: 0}}, {subscription: {started: "2025-03-20", months: 0, renews: "2025-03-20T00:00:00Z", daysLeft: 0, expiringSoon: true, renewYear: 2025}}], + ], +} + +{ + name: "date parts", + policy: { + models: {event: {at: "date"}}, + blocks: [ + {expression: "event.parts", value: "[event.at.year(), event.at.month(), event.at.day(), event.at.hour(), event.at.minute(), event.at.second()]"}, + {expression: "event.weekday", value: "event.at.weekday()"}, + {expression: "event.quarter", value: "event.at.quarter()"}, + {expression: "event.dayOfYear", value: "event.at.dayOfYear()"}, + ], + }, + cases: [ + [{event: {at: "2025-03-20 14:30:45"}}, {event: {at: "2025-03-20 14:30:45", parts: [2025, 3, 20, 14, 30, 45], weekday: 4, quarter: 1, dayOfYear: 79}}], + [{event: {at: "2025-12-31"}}, {event: {at: "2025-12-31", parts: [2025, 12, 31, 0, 0, 0], weekday: 3, quarter: 4, dayOfYear: 365}}], + [{event: {at: "2024-12-31"}}, {event: {at: "2024-12-31", parts: [2024, 12, 31, 0, 0, 0], weekday: 2, quarter: 4, dayOfYear: 366}}], + [{event: {at: "2025-03-23"}}, {event: {at: "2025-03-23", parts: [2025, 3, 23, 0, 0, 0], weekday: 7, quarter: 1, dayOfYear: 82}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Optional dates. Missing and null read as null; `??` supplies a default date. + +{ + name: "an optional date defaults to now", + policy: { + models: {order: {placed: "date?"}}, + blocks: [ + {expression: "order.effective", value: "order.placed ?? d()"}, + {expression: "order.year", value: "(order.placed ?? d()).year()"}, + ], + }, + cases: [ + [{order: {}}, {order: {effective: "2025-03-20T10:15:30Z", year: 2025}}], + [{order: {placed: null}}, {order: {placed: null, effective: "2025-03-20T10:15:30Z", year: 2025}}], + [{order: {placed: "2020-06-01"}}, {order: {placed: "2020-06-01", effective: "2020-06-01", year: 2020}}], + [{order: {placed: "2020-06-01T12:00:00Z"}}, {order: {placed: "2020-06-01T12:00:00Z", effective: "2020-06-01T12:00:00Z", year: 2020}}], + ], +} + +{ + name: "an optional end date: open-ended ranges", + policy: { + models: {contract: {start: "date", end: "date?"}}, + blocks: [ + {expression: "contract.open", value: "contract.end == null"}, + {expression: "contract.active", value: "contract.start <= d() and (contract.end ?? d()) >= d()"}, + ], + }, + cases: [ + [{contract: {start: "2025-01-01"}}, {contract: {start: "2025-01-01", open: true, active: true}}], + [{contract: {start: "2025-01-01", end: null}}, {contract: {start: "2025-01-01", end: null, open: true, active: true}}], + [{contract: {start: "2025-01-01", end: "2025-02-01"}}, {contract: {start: "2025-01-01", end: "2025-02-01", open: false, active: false}}], + [{contract: {start: "2025-01-01", end: "2025-12-31"}}, {contract: {start: "2025-01-01", end: "2025-12-31", open: false, active: true}}], + [{contract: {start: "2025-04-01"}}, {contract: {start: "2025-04-01", open: true, active: false}}], + [{contract: {end: "2025-12-31"}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a null check does not narrow an optional date inside `or`", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {contract: {start: "date", end: "date?"}}, + blocks: [{expression: "contract.active", value: "contract.start <= d() and (contract.end == null or contract.end >= d())"}], + }, + cases: [ + {input: {contract: {start: "2025-01-01"}}, output: {contract: {start: "2025-01-01", active: true}}, note: "question: the type checker reports TYPE_MISMATCH for `end >= d()` although `end == null or` guards it, so DecisionEngine refuses the policy"}, + [{contract: {start: "2025-01-01", end: "2025-02-01"}}, {contract: {start: "2025-01-01", end: "2025-02-01", active: false}}], + [{contract: {start: "2025-01-01", end: "2025-12-31"}}, {contract: {start: "2025-01-01", end: "2025-12-31", active: true}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Date arrays: every item is converted; closures see dates. + +{ + name: "closures over a date array", + policy: { + models: {customer: {logins: "date[]"}}, + blocks: [ + {expression: "customer.recent", value: "count(customer.logins, #.isAfter(d().sub(7, 'day')))"}, + {expression: "customer.years", value: "map(customer.logins, #.year())"}, + {expression: "customer.anyToday", value: "some(customer.logins, #.isSame(d(), 'day'))"}, + ], + }, + cases: [ + [{customer: {logins: []}}, {customer: {logins: [], recent: 0, years: [], anyToday: false}}], + [{customer: {logins: ["2025-03-19", "2025-03-01", "2024-12-31"]}}, {customer: {logins: ["2025-03-19", "2025-03-01", "2024-12-31"], recent: 1, years: [2025, 2025, 2024], anyToday: false}}], + [{customer: {logins: ["2025-03-20 08:00", "2025-03-14T00:00:00Z"]}}, {customer: {logins: ["2025-03-20 08:00", "2025-03-14T00:00:00Z"], recent: 2, years: [2025, 2025], anyToday: true}}], + [{customer: {logins: ["2025-03-20", "bad"]}}, "!error: InputValidationFailed"], + [{customer: {logins: "2025-03-20"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "filtering a date array keeps the source text", + policy: { + models: {customer: {logins: "date[]"}}, + blocks: [ + {expression: "customer.thisYear", value: "filter(customer.logins, #.year() == 2025)"}, + {expression: "customer.first", value: "customer.logins[0]"}, + ], + }, + cases: [ + [{customer: {logins: ["2025-01-02", "2024-05-05", "2025/03/01"]}}, {customer: {logins: ["2025-01-02", "2024-05-05", "2025/03/01"], thisYear: ["2025-01-02", "2025/03/01"], first: "2025-01-02"}}], + [{customer: {logins: ["2024-05-05"]}}, {customer: {logins: ["2024-05-05"], thisYear: [], first: "2024-05-05"}}], + [{customer: {logins: []}}, {customer: {logins: [], thisYear: [], first: null}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dates on related entities: members of an array relationship, single relationships, nested +// relationships and referenced pool entities are all converted. + +{ + name: "per-member date arithmetic", + policy: { + models: {loan: {installments: "installment[]"}, installment: {due: "date", amount: "number"}}, + blocks: [ + {expression: "installment.daysLate", value: "max([0, d().startOf('day').diff(installment.due, 'day')])"}, + {expression: "installment.penalty", value: "installment.daysLate * 0.5"}, + {expression: "loan.penalties", value: "sum(map(loan.installments, #.penalty))"}, + ], + }, + cases: [ + [{loan: {installments: []}}, {loan: {installments: [], penalties: 0}}], + [ + {loan: {installments: [{due: "2025-03-10", amount: 100}, {due: "2025-04-10", amount: 100}]}}, + {loan: {installments: [{due: "2025-03-10", amount: 100, daysLate: 10, penalty: 5}, {due: "2025-04-10", amount: 100, daysLate: 0, penalty: 0}], penalties: 5}}, + ], + [ + {loan: {installments: [{due: "2025-02-20", amount: 1}, {due: "2025-03-19 23:00", amount: 1}]}}, + {loan: {installments: [{due: "2025-02-20", amount: 1, daysLate: 28, penalty: 14}, {due: "2025-03-19 23:00", amount: 1, daysLate: 0, penalty: 0}], penalties: 14}}, + ], + [{loan: {installments: [{due: "never", amount: 1}]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a member compares its date with a parent date", + policy: { + models: {project: {deadline: "date", tasks: "task[]"}, task: {done: "date"}}, + blocks: [ + {expression: "task.late", value: "task.done > project.deadline"}, + {expression: "project.lateCount", value: "count(project.tasks, #.late)"}, + ], + }, + cases: [ + [ + {project: {deadline: "2025-03-31", tasks: [{done: "2025-03-30"}, {done: "2025-04-02"}, {done: "2025-03-31"}]}}, + {project: {deadline: "2025-03-31", tasks: [{done: "2025-03-30", late: false}, {done: "2025-04-02", late: true}, {done: "2025-03-31", late: false}], lateCount: 1}}, + ], + [ + {project: {deadline: "2025-03-31T12:00:00Z", tasks: [{done: "2025-03-31 12:00:01"}]}}, + {project: {deadline: "2025-03-31T12:00:00Z", tasks: [{done: "2025-03-31 12:00:01", late: true}], lateCount: 1}}, + ], + [{project: {deadline: "2025-03-31", tasks: []}}, {project: {deadline: "2025-03-31", tasks: [], lateCount: 0}}], + ], +} + +{ + name: "dates on a nested single relationship are converted", + policy: { + models: {customer: {account: "account"}, account: {owner: "person"}, person: {born: "date"}}, + blocks: [{expression: "customer.ownerAge", value: "d().diff(customer.account.owner.born, 'year')"}], + }, + cases: [ + [{customer: {account: {owner: {born: "1990-05-01"}}}}, {customer: {account: {owner: {born: "1990-05-01"}}, ownerAge: 34}}], + [{customer: {account: {owner: {born: "2000-03-20"}}}}, {customer: {account: {owner: {born: "2000-03-20"}}, ownerAge: 25}}], + [{customer: {account: {owner: {born: "2000-03-21"}}}}, {customer: {account: {owner: {born: "2000-03-21"}}, ownerAge: 24}}], + [{customer: {account: {owner: {born: "x"}}}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "dates on referenced pool entities are converted", + policy: { + models: {booking: {room: "&room"}, room: {id: "string", availableFrom: "date"}}, + blocks: [ + {expression: "booking.ready", value: "booking.room.availableFrom <= d()"}, + {expression: "booking.from", value: "booking.room.availableFrom"}, + ], + }, + cases: [ + [ + {booking: {room: "r1"}, room: [{id: "r1", availableFrom: "2025-01-01"}, {id: "r2", availableFrom: "2026-01-01"}]}, + {booking: {room: {id: "r1", availableFrom: "2025-01-01"}, ready: true, from: "2025-01-01"}, room: [{id: "r1", availableFrom: "2025-01-01"}, {id: "r2", availableFrom: "2026-01-01"}]}, + ], + [ + {booking: {room: "r2"}, room: [{id: "r1", availableFrom: "2025-01-01"}, {id: "r2", availableFrom: "2026-01-01"}]}, + {booking: {room: {id: "r2", availableFrom: "2026-01-01"}, ready: false, from: "2026-01-01"}, room: [{id: "r1", availableFrom: "2025-01-01"}, {id: "r2", availableFrom: "2026-01-01"}]}, + ], + [{booking: {room: "r1"}, room: [{id: "r1", availableFrom: "soon"}]}, "!error: InputValidationFailed"], + ], +} + +{ + name: "earliest and latest member dates", + policy: { + models: {customer: {orders: "order[]"}, order: {placed: "date"}}, + blocks: [ + {expression: "customer.firstOrder", value: "len(customer.orders) == 0 ? null : min(map(customer.orders, #.placed))"}, + {expression: "customer.lastOrder", value: "len(customer.orders) == 0 ? null : max(map(customer.orders, #.placed))"}, + {expression: "customer.ordersThisYear", value: "count(customer.orders, #.placed.year() == d().year())"}, + ], + }, + cases: [ + [{customer: {orders: []}}, {customer: {orders: [], firstOrder: null, lastOrder: null, ordersThisYear: 0}}], + [ + {customer: {orders: [{placed: "2025-02-01"}, {placed: "2023-07-04"}, {placed: "2025-03-01"}]}}, + {customer: {orders: [{placed: "2025-02-01"}, {placed: "2023-07-04"}, {placed: "2025-03-01"}], firstOrder: "2023-07-04", lastOrder: "2025-03-01", ordersThisYear: 2}}, + ], + [ + {customer: {orders: [{placed: "2025-01-01T10:00:00Z"}, {placed: "2025-01-01 09:00"}]}}, + {customer: {orders: [{placed: "2025-01-01T10:00:00Z"}, {placed: "2025-01-01 09:00"}], firstOrder: "2025-01-01 09:00", lastOrder: "2025-01-01T10:00:00Z", ordersThisYear: 2}}, + ], + ], +} + +// --------------------------------------------------------------------------------------------- +// Global dates: top-level date properties, read by bare name. + +{ + name: "a global as-of date replaces now", + policy: { + globals: {context: {asOf: "date"}}, + models: {customer: {born: "date"}}, + blocks: [ + {expression: "customer.age", value: "asOf.diff(customer.born, 'year')"}, + {expression: "customer.adult", value: "customer.age >= 18"}, + ], + }, + cases: [ + [{asOf: "2025-01-01", customer: {born: "2007-01-01"}}, {asOf: "2025-01-01", customer: {born: "2007-01-01", age: 18, adult: true}}], + [{asOf: "2024-12-31", customer: {born: "2007-01-01"}}, {asOf: "2024-12-31", customer: {born: "2007-01-01", age: 17, adult: false}}], + [{asOf: "2030-06-01T00:00:00Z", customer: {born: "2007-01-01"}}, {asOf: "2030-06-01T00:00:00Z", customer: {born: "2007-01-01", age: 23, adult: true}}], + [{customer: {born: "2007-01-01"}}, "!error: MissingRequiredInputs"], + [{asOf: "now", customer: {born: "2007-01-01"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an optional global date falls back to now", + policy: { + globals: {context: {asOf: "date?"}}, + models: {offer: {expires: "date"}}, + blocks: [{expression: "offer.valid", value: "offer.expires >= (asOf ?? d())"}], + }, + cases: [ + [{offer: {expires: "2025-03-21"}}, {offer: {expires: "2025-03-21", valid: true}}], + [{offer: {expires: "2025-03-19"}}, {offer: {expires: "2025-03-19", valid: false}}], + [{asOf: "2025-03-01", offer: {expires: "2025-03-19"}}, {asOf: "2025-03-01", offer: {expires: "2025-03-19", valid: true}}], + [{asOf: null, offer: {expires: "2025-03-19"}}, {asOf: null, offer: {expires: "2025-03-19", valid: false}}], + [{asOf: 5, offer: {expires: "2025-03-19"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a global holiday list", + policy: { + globals: {calendar: {holidays: "date[]"}}, + models: {shipment: {ships: "date"}}, + blocks: [ + {expression: "shipment.onHoliday", value: "some(holidays, #.isSame(shipment.ships, 'day'))"}, + {expression: "shipment.weekend", value: "shipment.ships.weekday() >= 6"}, + {expression: "shipment.businessDay", value: "not shipment.onHoliday and not shipment.weekend"}, + ], + }, + cases: [ + [{holidays: ["2025-12-25", "2025-12-26"], shipment: {ships: "2025-12-25 10:00"}}, {holidays: ["2025-12-25", "2025-12-26"], shipment: {ships: "2025-12-25 10:00", onHoliday: true, weekend: false, businessDay: false}}], + [{holidays: ["2025-12-25"], shipment: {ships: "2025-12-24"}}, {holidays: ["2025-12-25"], shipment: {ships: "2025-12-24", onHoliday: false, weekend: false, businessDay: true}}], + [{holidays: [], shipment: {ships: "2025-03-22"}}, {holidays: [], shipment: {ships: "2025-03-22", onHoliday: false, weekend: true, businessDay: false}}], + [{holidays: ["xmas"], shipment: {ships: "2025-03-22"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "computed global dates", + policy: { + globals: {context: {period: "string(month|quarter|year)"}}, + blocks: [ + {expression: "periodStart", value: "d().startOf(period)"}, + {expression: "periodEnd", value: "d().endOf(period).format('%Y-%m-%d')"}, + ], + }, + cases: [ + [{period: "month"}, {period: "month", periodStart: "2025-03-01T00:00:00Z", periodEnd: "2025-03-31"}], + [{period: "quarter"}, {period: "quarter", periodStart: "2025-01-01T00:00:00Z", periodEnd: "2025-03-31"}], + [{period: "year"}, {period: "year", periodStart: "2025-01-01T00:00:00Z", periodEnd: "2025-12-31"}], + [{period: "week"}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dates in tables. Cells compare the column's date with date literals; output cells may +// produce dates. + +{ + name: "a table with date equality and range cells", + policy: { + models: {order: {placed: "date"}}, + blocks: [{table: "t", inputs: ["order.placed"], outputs: ["order.promo"], rules: [ + ["d('2025-11-28')", "'black friday'"], + ["[d('2025-12-01')..d('2025-12-24')]", "'advent'"], + [">= d('2025-12-25')", "'post'"], + ["", "'none'"], + ]}], + }, + cases: [ + [{order: {placed: "2025-11-28"}}, {order: {placed: "2025-11-28", promo: "black friday"}}], + [{order: {placed: "2025-11-28 13:00"}}, {order: {placed: "2025-11-28 13:00", promo: "none"}}], + [{order: {placed: "2025-12-01"}}, {order: {placed: "2025-12-01", promo: "advent"}}], + [{order: {placed: "2025-12-24"}}, {order: {placed: "2025-12-24", promo: "advent"}}], + [{order: {placed: "2025-12-24 18:00"}}, {order: {placed: "2025-12-24 18:00", promo: "none"}}], + [{order: {placed: "2026-01-05"}}, {order: {placed: "2026-01-05", promo: "post"}}], + [{order: {placed: "2025-06-01"}}, {order: {placed: "2025-06-01", promo: "none"}}], + ], +} + +{ + name: "a table over a date expression column", + policy: { + models: {customer: {born: "date"}}, + blocks: [{table: "t", inputs: ["d().diff(customer.born, 'year')"], outputs: ["customer.band"], rules: [ + ["< 18", "'minor'"], + ["[18..64]", "'adult'"], + ["", "'senior'"], + ]}], + }, + cases: [ + [{customer: {born: "2010-01-01"}}, {customer: {born: "2010-01-01", band: "minor"}}], + [{customer: {born: "2007-03-20"}}, {customer: {born: "2007-03-20", band: "adult"}}], + [{customer: {born: "2007-03-21"}}, {customer: {born: "2007-03-21", band: "minor"}}], + [{customer: {born: "1960-03-21"}}, {customer: {born: "1960-03-21", band: "adult"}}], + [{customer: {born: "1960-03-20"}}, {customer: {born: "1960-03-20", band: "senior"}}], + ], +} + +{ + name: "table output cells produce dates", + policy: { + models: {claim: {filed: "date", severity: "string(low|high)"}}, + blocks: [{table: "t", inputs: ["claim.severity"], outputs: ["claim.reviewBy", "claim.window"], rules: [ + ["'high'", "claim.filed.add(2, 'day')", "'2d'"], + ["'low'", "claim.filed.add(1, 'month')", "'1M'"], + ]}], + }, + cases: [ + [{claim: {filed: "2025-03-20", severity: "high"}}, {claim: {filed: "2025-03-20", severity: "high", reviewBy: "2025-03-22T00:00:00Z", window: "2d"}}], + [{claim: {filed: "2025-01-31", severity: "low"}}, {claim: {filed: "2025-01-31", severity: "low", reviewBy: "2025-02-28T00:00:00Z", window: "1M"}}], + [{claim: {filed: "2025-12-31 23:00", severity: "high"}}, {claim: {filed: "2025-12-31 23:00", severity: "high", reviewBy: "2026-01-02T23:00:00Z", window: "2d"}}], + ], +} + +{ + name: "a table output cell copying an input date keeps its text", + policy: { + models: {order: {placed: "date", shipped: "date?"}}, + blocks: [{table: "t", inputs: ["order.shipped"], outputs: ["order.lastEvent"], rules: [ + ["null", "order.placed"], + ["", "order.shipped"], + ]}], + }, + cases: [ + [{order: {placed: "2025-03-01"}}, {order: {placed: "2025-03-01", lastEvent: "2025-03-01"}}], + [{order: {placed: "2025-03-01", shipped: null}}, {order: {placed: "2025-03-01", shipped: null, lastEvent: "2025-03-01"}}], + [{order: {placed: "2025-03-01", shipped: "2025-03-04 09:00"}}, {order: {placed: "2025-03-01", shipped: "2025-03-04 09:00", lastEvent: "2025-03-04 09:00"}}], + ], +} + +{ + name: "a per-member table over member dates", + policy: { + models: {fleet: {vehicles: "vehicle[]"}, vehicle: {inspected: "date"}}, + blocks: [ + {table: "t", inputs: ["vehicle.inspected"], outputs: ["vehicle.status"], rules: [ + ["< d().sub(1, 'year')", "'overdue'"], + ["< d().sub(11, 'month')", "'due soon'"], + ["", "'ok'"], + ]}, + {expression: "fleet.overdue", value: "count(fleet.vehicles, #.status == 'overdue')"}, + ], + }, + cases: [ + [{fleet: {vehicles: []}}, {fleet: {vehicles: [], overdue: 0}}], + [ + {fleet: {vehicles: [{inspected: "2024-01-01"}, {inspected: "2024-04-01"}, {inspected: "2025-01-01"}]}}, + {fleet: {vehicles: [{inspected: "2024-01-01", status: "overdue"}, {inspected: "2024-04-01", status: "due soon"}, {inspected: "2025-01-01", status: "ok"}], overdue: 1}}, + ], + [ + {fleet: {vehicles: [{inspected: "2024-03-20T10:15:29Z"}, {inspected: "2024-03-20T10:15:30Z"}]}}, + {fleet: {vehicles: [{inspected: "2024-03-20T10:15:29Z", status: "overdue"}, {inspected: "2024-03-20T10:15:30Z", status: "due soon"}], overdue: 1}}, + ], + ], +} + +{ + name: "a collect table gathers date-based flags", + policy: { + models: {applicant: {born: "date", employedSince: "date"}}, + blocks: [{table: "t", hit: "collect", inputs: ["applicant.born", "applicant.employedSince"], outputs: ["applicant.flags[]"], rules: [ + ["> d().sub(18, 'year')", "", "'underage'"], + ["", "> d().sub(6, 'month')", "'new job'"], + ["", "> d()", "'future employment'"], + ]}], + }, + cases: [ + [{applicant: {born: "1990-01-01", employedSince: "2020-01-01"}}, {applicant: {born: "1990-01-01", employedSince: "2020-01-01", flags: []}}], + [{applicant: {born: "2010-01-01", employedSince: "2025-01-01"}}, {applicant: {born: "2010-01-01", employedSince: "2025-01-01", flags: ["underage", "new job"]}}], + [{applicant: {born: "1990-01-01", employedSince: "2025-06-01"}}, {applicant: {born: "1990-01-01", employedSince: "2025-06-01", flags: ["new job", "future employment"]}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dates in matches and assertions. + +{ + name: "a match bands a date", + policy: { + models: {member: {joined: "date"}}, + blocks: [{match: "member.level", arms: [ + ["member.joined <= d().sub(10, 'year')", "'platinum'"], + ["member.joined <= d().sub(5, 'year')", "'gold'"], + ["member.joined <= d().sub(1, 'year')", "'silver'"], + ["", "'new'"], + ]}], + }, + cases: [ + [{member: {joined: "2010-01-01"}}, {member: {joined: "2010-01-01", level: "platinum"}}], + [{member: {joined: "2015-03-20T10:15:30Z"}}, {member: {joined: "2015-03-20T10:15:30Z", level: "platinum"}}], + [{member: {joined: "2015-03-20T10:15:31Z"}}, {member: {joined: "2015-03-20T10:15:31Z", level: "gold"}}], + [{member: {joined: "2023-01-01"}}, {member: {joined: "2023-01-01", level: "silver"}}], + [{member: {joined: "2025-01-01"}}, {member: {joined: "2025-01-01", level: "new"}}], + ], +} + +{ + name: "match arms produce dates", + policy: { + models: {ticket: {opened: "date", priority: "string(p1|p2|p3)"}}, + blocks: [{match: "ticket.slaDeadline", arms: [ + ["ticket.priority == 'p1'", "ticket.opened.add(4, 'hour')"], + ["ticket.priority == 'p2'", "ticket.opened.add(1, 'day')"], + ["", "ticket.opened"], + ]}], + }, + cases: [ + [{ticket: {opened: "2025-03-20 08:00", priority: "p1"}}, {ticket: {opened: "2025-03-20 08:00", priority: "p1", slaDeadline: "2025-03-20T12:00:00Z"}}], + [{ticket: {opened: "2025-03-20 08:00", priority: "p2"}}, {ticket: {opened: "2025-03-20 08:00", priority: "p2", slaDeadline: "2025-03-21T08:00:00Z"}}], + [{ticket: {opened: "2025-03-20 08:00", priority: "p3"}}, {ticket: {opened: "2025-03-20 08:00", priority: "p3", slaDeadline: "2025-03-20 08:00"}}], + ], +} + +{ + name: "a match over a computed date", + policy: { + models: {ticket: {opened: "date", hours: "number"}}, + blocks: [ + {expression: "ticket.deadline", value: "ticket.opened.add(ticket.hours, 'hour')"}, + {match: "ticket.state", arms: [ + ["ticket.deadline < d()", "'breached'"], + ["ticket.deadline.isSame(d(), 'day')", "'due today'"], + ["", "'on track'"], + ]}, + ], + }, + cases: [ + [{ticket: {opened: "2025-03-19 08:00", hours: 24}}, {ticket: {opened: "2025-03-19 08:00", hours: 24, deadline: "2025-03-20T08:00:00Z", state: "breached"}}], + [{ticket: {opened: "2025-03-19 08:00", hours: 30}}, {ticket: {opened: "2025-03-19 08:00", hours: 30, deadline: "2025-03-20T14:00:00Z", state: "due today"}}], + [{ticket: {opened: "2025-03-19 08:00", hours: 48}}, {ticket: {opened: "2025-03-19 08:00", hours: 48, deadline: "2025-03-21T08:00:00Z", state: "on track"}}], + ], +} + +{ + name: "an assertion over date conditions", + policy: { + models: {passport: {issued: "date", expires: "date"}}, + blocks: [{assertion: "passport.valid", conditions: [ + "passport.issued <= d()", + "passport.expires > d().add(6, 'month')", + "passport.expires.diff(passport.issued, 'year') <= 10", + ]}], + }, + cases: [ + [{passport: {issued: "2020-01-01", expires: "2030-01-01"}}, {passport: {issued: "2020-01-01", expires: "2030-01-01", valid: true}}], + [{passport: {issued: "2020-01-01", expires: "2025-08-01"}}, {passport: {issued: "2020-01-01", expires: "2025-08-01", valid: false}}], + [{passport: {issued: "2025-04-01", expires: "2035-04-01"}}, {passport: {issued: "2025-04-01", expires: "2035-04-01", valid: false}}], + [{passport: {issued: "2015-01-01", expires: "2030-01-01"}}, {passport: {issued: "2015-01-01", expires: "2030-01-01", valid: false}}], + [{passport: {issued: "2020-01-01", expires: "2025-09-20T10:15:31Z"}}, {passport: {issued: "2020-01-01", expires: "2025-09-20T10:15:31Z", valid: true}}], + ], +} + +{ + name: "an or-group assertion with optional dates", + policy: { + models: {account: {closed: "date?", lastLogin: "date?"}}, + blocks: [{assertion: "account.dormant", conditions: [ + ["or", "account.closed != null"], + ["and", "account.lastLogin == null"], + ]}], + }, + cases: [ + [{account: {}}, {account: {dormant: true}}], + [{account: {closed: "2025-01-01"}}, {account: {closed: "2025-01-01", dormant: true}}], + [{account: {lastLogin: "2025-03-01"}}, {account: {lastLogin: "2025-03-01", dormant: false}}], + [{account: {closed: null, lastLogin: null}}, {account: {closed: null, lastLogin: null, dormant: true}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// A realistic combination: rental pricing over a date range. + +{ + name: "rental pricing over a date range", + policy: { + globals: {pricing: {dailyRate: "number", weekendSurcharge: "number"}}, + models: {rental: {pickup: "date", dropoff: "date", promoCode: "string?"}}, + blocks: [ + {expression: "rental.days", value: "max([1, rental.dropoff.diff(rental.pickup, 'day')])"}, + {expression: "rental.startsOnWeekend", value: "rental.pickup.weekday() >= 6"}, + {expression: "rental.leadDays", value: "rental.pickup.diff(d().startOf('day'), 'day')"}, + {match: "rental.earlyBird", arms: [["rental.leadDays >= 30", "0.1"], ["", "0"]]}, + {expression: "rental.price", value: "round(rental.days * dailyRate * (1 - rental.earlyBird) + (rental.startsOnWeekend ? weekendSurcharge : 0), 2)"}, + {expression: "rental.returnBy", value: "rental.pickup.add(rental.days, 'day')"}, + ], + }, + cases: [ + [ + {dailyRate: 40, weekendSurcharge: 15, rental: {pickup: "2025-03-21", dropoff: "2025-03-24"}}, + {dailyRate: 40, weekendSurcharge: 15, rental: {pickup: "2025-03-21", dropoff: "2025-03-24", days: 3, startsOnWeekend: false, leadDays: 1, earlyBird: 0, price: 120, returnBy: "2025-03-24T00:00:00Z"}}, + ], + [ + {dailyRate: 40, weekendSurcharge: 15, rental: {pickup: "2025-05-03", dropoff: "2025-05-10"}}, + {dailyRate: 40, weekendSurcharge: 15, rental: {pickup: "2025-05-03", dropoff: "2025-05-10", days: 7, startsOnWeekend: true, leadDays: 44, earlyBird: 0.1, price: 267, returnBy: "2025-05-10T00:00:00Z"}}, + ], + [ + {dailyRate: 33.33, weekendSurcharge: 0, rental: {pickup: "2025-03-20 09:00", dropoff: "2025-03-20 17:00", promoCode: "X"}}, + {dailyRate: 33.33, weekendSurcharge: 0, rental: {pickup: "2025-03-20 09:00", dropoff: "2025-03-20 17:00", promoCode: "X", days: 1, startsOnWeekend: false, leadDays: 0, earlyBird: 0, price: 33.33, returnBy: "2025-03-21T09:00:00Z"}}, + ], + [{dailyRate: 40, weekendSurcharge: 15, rental: {pickup: "2025-03-21"}}, "!error: MissingRequiredInputs"], + ], +} diff --git a/core/engine/tests/spec/policy/28-policy-strings-enums.json5 b/core/engine/tests/spec/policy/28-policy-strings-enums.json5 new file mode 100644 index 00000000..f1cd98c4 --- /dev/null +++ b/core/engine/tests/spec/policy/28-policy-strings-enums.json5 @@ -0,0 +1,775 @@ +// Strings, enums and dictionaries through policies. A `string` property accepts any string and +// passes it through byte for byte; enums (`string(a|b)`) and dictionary-typed properties accept +// only their listed values, compared exactly. At evaluation every one of them is a plain string. +// Chapters 01, 12 and 17 cover validation basics, labels and simple operations; this chapter +// covers the string content itself, string building, enum use in every block kind, dictionaries +// in tables and unicode. + +// --------------------------------------------------------------------------------------------- +// String content passes through unchanged: whitespace, control characters, quotes, backslashes +// and unicode are data. + +{ + name: "string inputs pass through byte for byte", + policy: { + models: {note: {text: "string"}}, + blocks: [{expression: "note.copy", value: "note.text"}], + }, + cases: [ + [{note: {text: ""}}, {note: {text: "", copy: ""}}], + [{note: {text: " "}}, {note: {text: " ", copy: " "}}], + [{note: {text: "line1\nline2\ttab"}}, {note: {text: "line1\nline2\ttab", copy: "line1\nline2\ttab"}}], + [{note: {text: "say \"hi\" and 'bye'"}}, {note: {text: "say \"hi\" and 'bye'", copy: "say \"hi\" and 'bye'"}}], + [{note: {text: "C:\\path\\to"}}, {note: {text: "C:\\path\\to", copy: "C:\\path\\to"}}], + [{note: {text: "日本語 😀 ünïcödé"}}, {note: {text: "日本語 😀 ünïcödé", copy: "日本語 😀 ünïcödé"}}], + [{note: {text: "null"}}, {note: {text: "null", copy: "null"}}], + [{note: {text: "123"}}, {note: {text: "123", copy: "123"}}], + ], +} + +{ + name: "number-like and boolean-like strings stay strings", + policy: { + models: {row: {code: "string"}}, + blocks: [ + {expression: "row.isZero", value: "row.code == '0'"}, + {expression: "row.kind", value: "type(row.code)"}, + {expression: "row.padded", value: "row.code + '!'"}, + ], + }, + cases: [ + [{row: {code: "0"}}, {row: {code: "0", isZero: true, kind: "string", padded: "0!"}}], + [{row: {code: "00"}}, {row: {code: "00", isZero: false, kind: "string", padded: "00!"}}], + [{row: {code: "true"}}, {row: {code: "true", isZero: false, kind: "string", padded: "true!"}}], + [{row: {code: "1e3"}}, {row: {code: "1e3", isZero: false, kind: "string", padded: "1e3!"}}], + [{row: {code: 0}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "string equality is exact: case, whitespace and unicode normal form matter", + policy: { + models: {pair: {a: "string", b: "string"}}, + blocks: [ + {expression: "pair.same", value: "pair.a == pair.b"}, + {expression: "pair.sameIgnoringCase", value: "lower(pair.a) == lower(pair.b)"}, + {expression: "pair.sameTrimmed", value: "trim(pair.a) == trim(pair.b)"}, + ], + }, + cases: [ + [{pair: {a: "abc", b: "abc"}}, {pair: {a: "abc", b: "abc", same: true, sameIgnoringCase: true, sameTrimmed: true}}], + [{pair: {a: "abc", b: "ABC"}}, {pair: {a: "abc", b: "ABC", same: false, sameIgnoringCase: true, sameTrimmed: false}}], + [{pair: {a: " abc", b: "abc "}}, {pair: {a: " abc", b: "abc ", same: false, sameIgnoringCase: false, sameTrimmed: true}}], + [{pair: {a: "é", b: "e\u0301"}}, {pair: {a: "é", b: "e\u0301", same: false, sameIgnoringCase: false, sameTrimmed: false}}], + [{pair: {a: "Straße", b: "STRASSE"}}, {pair: {a: "Straße", b: "STRASSE", same: false, sameIgnoringCase: false, sameTrimmed: false}}], + [{pair: {a: "", b: ""}}, {pair: {a: "", b: "", same: true, sameIgnoringCase: true, sameTrimmed: true}}], + ], +} + +{ + name: "strings have no ordering", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {pair: {a: "string", b: "string"}}, + blocks: [{expression: "pair.lt", value: "pair.a < pair.b"}], + }, + cases: [ + {input: {pair: {a: "apple", b: "banana"}}, output: "!error: ExpressionFailed", note: "question: ordering operators reject strings (the type checker reports TYPE_MISMATCH and evaluation fails), as in the expression spec; lexicographic order may be intended"}, + [{pair: {a: "b", b: "a"}}, "!error: ExpressionFailed"], + [{pair: {a: "", b: ""}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Unicode through string functions. + +{ + name: "case mapping and trimming of unicode text", + policy: { + models: {person: {name: "string"}}, + blocks: [ + {expression: "person.upper", value: "upper(person.name)"}, + {expression: "person.lower", value: "lower(person.name)"}, + {expression: "person.trimmed", value: "trim(person.name)"}, + ], + }, + cases: [ + [{person: {name: "Øystein"}}, {person: {name: "Øystein", upper: "ØYSTEIN", lower: "øystein", trimmed: "Øystein"}}], + [{person: {name: " Ἀθηνᾶ "}}, {person: {name: " Ἀθηνᾶ ", upper: " ἈΘΗΝΑ\u0342 ", lower: " ἀθηνᾶ ", trimmed: "Ἀθηνᾶ"}}], + [{person: {name: "東京"}}, {person: {name: "東京", upper: "東京", lower: "東京", trimmed: "東京"}}], + [{person: {name: "straße"}}, {person: {name: "straße", upper: "STRASSE", lower: "straße", trimmed: "straße"}}], + [{person: {name: "\tİstanbul\n"}}, {person: {name: "\tİstanbul\n", upper: "\tİSTANBUL\n", lower: "\ti̇stanbul\n", trimmed: "İstanbul"}}], + ], +} + +{ + name: "searching unicode text", + policy: { + models: {msg: {body: "string"}}, + blocks: [ + {expression: "msg.hasHeart", value: "contains(msg.body, '❤')"}, + {expression: "msg.greek", value: "startsWith(msg.body, 'Γειά')"}, + {expression: "msg.parts", value: "split(msg.body, '·')"}, + ], + }, + cases: [ + [{msg: {body: "Γειά·σου·❤"}}, {msg: {body: "Γειά·σου·❤", hasHeart: true, greek: true, parts: ["Γειά", "σου", "❤"]}}], + [{msg: {body: "hello"}}, {msg: {body: "hello", hasHeart: false, greek: false, parts: ["hello"]}}], + [{msg: {body: ""}}, {msg: {body: "", hasHeart: false, greek: false, parts: [""]}}], + [{msg: {body: "··"}}, {msg: {body: "··", hasHeart: false, greek: false, parts: ["", "", ""]}}], + ], +} + +{ + name: "length of unicode strings counts characters", + policy: { + models: {msg: {body: "string"}}, + blocks: [{expression: "msg.length", value: "len(msg.body)"}], + }, + cases: [ + [{msg: {body: "abc"}}, {msg: {body: "abc", length: 3}}], + [{msg: {body: ""}}, {msg: {body: "", length: 0}}], + [{msg: {body: "Zoë"}}, {msg: {body: "Zoë", length: 3}}, "bug: len counts UTF-8 bytes (4), as in the expression spec"], + [{msg: {body: "日本"}}, {msg: {body: "日本", length: 2}}, "bug: len counts UTF-8 bytes (6), as in the expression spec"], + ], +} + +{ + name: "unicode keys and values in undeclared input pass through", + policy: { + models: {customer: {name: "string"}}, + blocks: [{expression: "customer.greeting", value: "'Hej ' + customer.name"}], + }, + cases: [ + [{customer: {name: "Åsa", "größe": 1}}, {customer: {name: "Åsa", "größe": 1, greeting: "Hej Åsa"}}], + [{customer: {name: "李"}, "メタ": {"キー": "値"}}, {customer: {name: "李", greeting: "Hej 李"}, "メタ": {"キー": "値"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Building strings: concatenation, templates, conversion and joins. + +{ + name: "templates interpolate every scalar type, numbers keep their scale", + policy: { + models: {item: {name: "string", qty: "number", price: "number", gift: "boolean"}}, + blocks: [ + {expression: "item.line", value: "`${item.qty} x ${item.name} @ ${item.price}`"}, + {expression: "item.giftNote", value: "`gift: ${item.gift}`"}, + {expression: "item.total", value: "`total ${item.qty * item.price}`"}, + ], + }, + cases: [ + [{item: {name: "pen", qty: 2, price: 1.5, gift: false}}, {item: {name: "pen", qty: 2, price: 1.5, gift: false, line: "2 x pen @ 1.5", giftNote: "gift: false", total: "total 3.0"}}], + [{item: {name: "", qty: 0, price: 0, gift: true}}, {item: {name: "", qty: 0, price: 0, gift: true, line: "0 x @ 0", giftNote: "gift: true", total: "total 0"}}], + [{item: {name: "ünï", qty: 3, price: 0.10, gift: true}}, {item: {name: "ünï", qty: 3, price: 0.10, gift: true, line: "3 x ünï @ 0.10", giftNote: "gift: true", total: "total 0.30"}}], + [{item: {name: "x", qty: -1, price: 1.25, gift: false}}, {item: {name: "x", qty: -1, price: 1.25, gift: false, line: "-1 x x @ 1.25", giftNote: "gift: false", total: "total -1.25"}}], + ], +} + +{ + name: "templates over optional values", + policy: { + models: {person: {first: "string", middle: "string?"}}, + blocks: [ + {expression: "person.raw", value: "`${person.first} ${person.middle}`"}, + {expression: "person.full", value: "trim(person.first + ' ' + (person.middle ?? ''))"}, + ], + }, + cases: [ + [{person: {first: "Ann", middle: "Lee"}}, {person: {first: "Ann", middle: "Lee", raw: "Ann Lee", full: "Ann Lee"}}], + [{person: {first: "Ann"}}, {person: {first: "Ann", raw: "Ann null", full: "Ann"}}], + [{person: {first: "Ann", middle: null}}, {person: {first: "Ann", middle: null, raw: "Ann null", full: "Ann"}}], + [{person: {first: "Ann", middle: ""}}, {person: {first: "Ann", middle: "", raw: "Ann ", full: "Ann"}}], + ], +} + +{ + name: "numbers converted to strings keep their decimal scale", + policy: { + models: {money: {amount: "number", currency: "string"}}, + blocks: [ + {expression: "money.label", value: "string(money.amount) + ' ' + money.currency"}, + {expression: "money.rounded", value: "string(round(money.amount, 2)) + ' ' + money.currency"}, + ], + }, + cases: [ + [{money: {amount: 10, currency: "EUR"}}, {money: {amount: 10, currency: "EUR", label: "10 EUR", rounded: "10 EUR"}}], + [{money: {amount: 10.5, currency: "USD"}}, {money: {amount: 10.5, currency: "USD", label: "10.5 USD", rounded: "10.5 USD"}}], + [{money: {amount: 1.005, currency: "NOK"}}, {money: {amount: 1.005, currency: "NOK", label: "1.005 NOK", rounded: "1.01 NOK"}}], + [{money: {amount: -0.333, currency: "¥"}}, {money: {amount: -0.333, currency: "¥", label: "-0.333 ¥", rounded: "-0.33 ¥"}}], + [{money: {amount: 123456789.123456789, currency: "€"}}, {money: {amount: 123456789.123456789, currency: "€", label: "123456789.123456789 €", rounded: "123456789.12 €"}}], + ], +} + +{ + name: "mapping member strings", + policy: { + models: {team: {members: "member[]"}, member: {name: "string", role: "string(lead|dev)"}}, + blocks: [ + {expression: "member.tag", value: "member.role == 'lead' ? member.name + ' (lead)' : member.name"}, + {expression: "team.roster", value: "map(team.members, #.tag)"}, + {expression: "team.initials", value: "map(team.members, upper(#.name[0:0]))"}, + ], + }, + cases: [ + [{team: {members: []}}, {team: {members: [], roster: [], initials: []}}], + [ + {team: {members: [{name: "ann", role: "lead"}, {name: "bob", role: "dev"}]}}, + {team: {members: [{name: "ann", role: "lead", tag: "ann (lead)"}, {name: "bob", role: "dev", tag: "bob"}], roster: ["ann (lead)", "bob"], initials: ["A", "B"]}}, + ], + [ + {team: {members: [{name: "Zoë", role: "dev"}]}}, + {team: {members: [{name: "Zoë", role: "dev", tag: "Zoë"}], roster: ["Zoë"], initials: ["Z"]}}, + ], + [{team: {members: [{name: "x", role: "boss"}]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a string built across several blocks", + policy: { + models: {address: {street: "string", city: "string", zip: "string", country: "string(NO|SE|US)"}}, + blocks: [ + {expression: "address.line1", value: "trim(address.street)"}, + {match: "address.line2", arms: [ + ["address.country == 'US'", "address.city + ', ' + address.zip"], + ["", "address.zip + ' ' + upper(address.city)"], + ]}, + {expression: "address.label", value: "address.line1 + '\n' + address.line2 + '\n' + address.country"}, + ], + }, + cases: [ + [ + {address: {street: " Storgata 1 ", city: "Oslo", zip: "0155", country: "NO"}}, + {address: {street: " Storgata 1 ", city: "Oslo", zip: "0155", country: "NO", line1: "Storgata 1", line2: "0155 OSLO", label: "Storgata 1\n0155 OSLO\nNO"}}, + ], + [ + {address: {street: "1 Main St", city: "Springfield", zip: "12345", country: "US"}}, + {address: {street: "1 Main St", city: "Springfield", zip: "12345", country: "US", line1: "1 Main St", line2: "Springfield, 12345", label: "1 Main St\nSpringfield, 12345\nUS"}}, + ], + [ + {address: {street: "Götgatan 2", city: "Malmö", zip: "211 20", country: "SE"}}, + {address: {street: "Götgatan 2", city: "Malmö", zip: "211 20", country: "SE", line1: "Götgatan 2", line2: "211 20 MALMÖ", label: "Götgatan 2\n211 20 MALMÖ\nSE"}}, + ], + ], +} + +{ + name: "string slicing and searching on input", + policy: { + models: {account: {iban: "string"}}, + blocks: [ + {expression: "account.country", value: "account.iban[0:1]"}, + {expression: "account.isNorwegian", value: "startsWith(account.iban, 'NO')"}, + {expression: "account.wellFormed", value: "matches(account.iban, '^[A-Z]{2}[0-9]{2}[A-Z0-9]+$')"}, + ], + }, + cases: [ + [{account: {iban: "NO9386011117947"}}, {account: {iban: "NO9386011117947", country: "NO", isNorwegian: true, wellFormed: true}}], + [{account: {iban: "DE89370400440532013000"}}, {account: {iban: "DE89370400440532013000", country: "DE", isNorwegian: false, wellFormed: true}}], + [{account: {iban: "no93 8601"}}, {account: {iban: "no93 8601", country: "no", isNorwegian: false, wellFormed: false}}], + [{account: {iban: "NO"}}, {account: {iban: "NO", country: "NO", isNorwegian: true, wellFormed: false}}], + [{account: {iban: "N"}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// String arrays. + +{ + name: "string arrays: membership, filtering and mapping", + policy: { + models: {post: {tags: "string[]"}}, + blocks: [ + {expression: "post.featured", value: "'featured' in post.tags"}, + {expression: "post.clean", value: "filter(post.tags, trim(#) != '')"}, + {expression: "post.hashtags", value: "map(post.clean, '#' + lower(#))"}, + ], + }, + cases: [ + [{post: {tags: []}}, {post: {tags: [], featured: false, clean: [], hashtags: []}}], + [{post: {tags: ["Featured", "News"]}}, {post: {tags: ["Featured", "News"], featured: false, clean: ["Featured", "News"], hashtags: ["#featured", "#news"]}}], + [{post: {tags: ["featured", " ", ""]}}, {post: {tags: ["featured", " ", ""], featured: true, clean: ["featured"], hashtags: ["#featured"]}}], + [{post: {tags: ["Ünï", "日本"]}}, {post: {tags: ["Ünï", "日本"], featured: false, clean: ["Ünï", "日本"], hashtags: ["#ünï", "#日本"]}}], + [{post: {tags: ["a", 1]}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Enums: values with spaces, punctuation, digits and unicode are matched exactly. + +{ + name: "enum values with spaces, punctuation and unicode", + policy: { + models: {ticket: {state: "string(on hold|in-progress|v2.0|ready ✓)"}}, + blocks: [{expression: "ticket.active", value: "ticket.state != 'on hold'"}], + }, + cases: [ + [{ticket: {state: "on hold"}}, {ticket: {state: "on hold", active: false}}], + [{ticket: {state: "in-progress"}}, {ticket: {state: "in-progress", active: true}}], + [{ticket: {state: "v2.0"}}, {ticket: {state: "v2.0", active: true}}], + [{ticket: {state: "ready ✓"}}, {ticket: {state: "ready ✓", active: true}}], + [{ticket: {state: "on hold"}}, "!error: InputValidationFailed"], + [{ticket: {state: "in_progress"}}, "!error: InputValidationFailed"], + [{ticket: {state: "v2"}}, "!error: InputValidationFailed"], + [{ticket: {state: "ready"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a single-value enum", + policy: { + models: {consent: {given: "string(yes)"}}, + blocks: [{expression: "consent.ok", value: "consent.given == 'yes'"}], + }, + cases: [ + [{consent: {given: "yes"}}, {consent: {given: "yes", ok: true}}], + [{consent: {given: "no"}}, "!error: InputValidationFailed"], + [{consent: {given: "YES"}}, "!error: InputValidationFailed"], + [{consent: {}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "numeric-looking enum values are strings", + policy: { + models: {plan: {seats: "string(1|5|10)"}}, + blocks: [{expression: "plan.label", value: "plan.seats + ' seats'"}], + }, + cases: [ + [{plan: {seats: "1"}}, {plan: {seats: "1", label: "1 seats"}}], + [{plan: {seats: "10"}}, {plan: {seats: "10", label: "10 seats"}}], + [{plan: {seats: 5}}, "!error: InputValidationFailed"], + [{plan: {seats: "5.0"}}, "!error: InputValidationFailed"], + [{plan: {seats: "01"}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Enums in blocks: expressions, matches (exhaustive without a default), tables and assertions. + +{ + name: "an exhaustive match over an enum needs no default", + policy: { + models: {shipment: {speed: "string(standard|express|overnight)", weight: "number"}}, + blocks: [{match: "shipment.cost", arms: [ + ["shipment.speed == 'standard'", "5 + shipment.weight"], + ["shipment.speed == 'express'", "10 + shipment.weight * 2"], + ["shipment.speed == 'overnight'", "25 + shipment.weight * 3"], + ]}], + }, + cases: [ + [{shipment: {speed: "standard", weight: 2}}, {shipment: {speed: "standard", weight: 2, cost: 7}}], + [{shipment: {speed: "express", weight: 2}}, {shipment: {speed: "express", weight: 2, cost: 14}}], + [{shipment: {speed: "overnight", weight: 0.5}}, {shipment: {speed: "overnight", weight: 0.5, cost: 26.5}}], + [{shipment: {speed: "drone", weight: 1}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a match covering only part of an enum without a default", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {shipment: {speed: "string(standard|express|overnight)"}}, + blocks: [{match: "shipment.fast", arms: [ + ["shipment.speed == 'express'", "true"], + ["shipment.speed == 'overnight'", "true"], + ]}], + }, + cases: [ + [{shipment: {speed: "express"}}, {shipment: {speed: "express", fast: true}}], + [{shipment: {speed: "overnight"}}, {shipment: {speed: "overnight", fast: true}}], + [{shipment: {speed: "standard"}}, {shipment: {speed: "standard", fast: null}}], + ], +} + +{ + name: "enum membership against a list of values", + policy: { + models: {order: {status: "string(new|paid|shipped|delivered|cancelled)"}}, + blocks: [ + {expression: "order.open", value: "order.status in ['new', 'paid', 'shipped']"}, + {expression: "order.final", value: "order.status not in ['new', 'paid', 'shipped']"}, + {expression: "order.canCancel", value: "order.status in ['new', 'paid'] and order.status != 'cancelled'"}, + ], + }, + cases: [ + [{order: {status: "new"}}, {order: {status: "new", open: true, final: false, canCancel: true}}], + [{order: {status: "shipped"}}, {order: {status: "shipped", open: true, final: false, canCancel: false}}], + [{order: {status: "delivered"}}, {order: {status: "delivered", open: false, final: true, canCancel: false}}], + [{order: {status: "cancelled"}}, {order: {status: "cancelled", open: false, final: true, canCancel: false}}], + [{order: {status: "returned"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an enum table with list cells and an inequality cell", + policy: { + models: {order: {status: "string(new|paid|shipped|delivered|cancelled)", total: "number"}}, + blocks: [{table: "t", inputs: ["order.status", "order.total"], outputs: ["order.action"], rules: [ + ["'new', 'paid'", "> 1000", "'review'"], + ["'new', 'paid'", "", "'process'"], + ["'cancelled'", "", "'refund'"], + ["!= 'delivered'", "", "'track'"], + ["", "", "'archive'"], + ]}], + }, + cases: [ + [{order: {status: "new", total: 5000}}, {order: {status: "new", total: 5000, action: "review"}}], + [{order: {status: "paid", total: 1000}}, {order: {status: "paid", total: 1000, action: "process"}}], + [{order: {status: "cancelled", total: 1}}, {order: {status: "cancelled", total: 1, action: "refund"}}], + [{order: {status: "shipped", total: 1}}, {order: {status: "shipped", total: 1, action: "track"}}], + [{order: {status: "delivered", total: 1}}, {order: {status: "delivered", total: 1, action: "archive"}}], + ], +} + +{ + name: "a collect table over enum array items", + policy: { + models: {user: {perms: "string(read|write|delete|admin)[]"}}, + blocks: [{table: "t", hit: "collect", inputs: [""], outputs: ["user.risks[]"], rules: [ + ["'delete' in user.perms", "'can delete'"], + ["'admin' in user.perms", "'is admin'"], + ["len(user.perms) == 0", "'no access'"], + ]}], + }, + cases: [ + [{user: {perms: ["read"]}}, {user: {perms: ["read"], risks: []}}], + [{user: {perms: ["read", "delete", "admin"]}}, {user: {perms: ["read", "delete", "admin"], risks: ["can delete", "is admin"]}}], + [{user: {perms: []}}, {user: {perms: [], risks: ["no access"]}}], + [{user: {perms: ["root"]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an assertion over enum values", + policy: { + models: {loan: {purpose: "string(home|car|education|other)", employment: "string(employed|self|unemployed)"}}, + blocks: [{assertion: "loan.eligible", conditions: [ + "loan.employment != 'unemployed'", + ["or", "loan.purpose in ['home', 'education']"], + "loan.employment == 'employed'", + ]}], + }, + cases: [ + [{loan: {purpose: "home", employment: "self"}}, {loan: {purpose: "home", employment: "self", eligible: true}}], + [{loan: {purpose: "car", employment: "employed"}}, {loan: {purpose: "car", employment: "employed", eligible: true}}], + [{loan: {purpose: "car", employment: "self"}}, {loan: {purpose: "car", employment: "self", eligible: false}}], + [{loan: {purpose: "home", employment: "unemployed"}}, {loan: {purpose: "home", employment: "unemployed", eligible: false}}], + [{loan: {purpose: "other", employment: "unemployed"}}, {loan: {purpose: "other", employment: "unemployed", eligible: false}}], + ], +} + +{ + name: "a computed enum-like string drives a later match", + policy: { + models: {customer: {spend: "number"}}, + blocks: [ + {table: "t", inputs: ["customer.spend"], outputs: ["customer.tier"], rules: [ + [">= 10000", "'gold'"], + [">= 1000", "'silver'"], + ["", "'bronze'"], + ]}, + {match: "customer.discount", arms: [ + ["customer.tier == 'gold'", "0.15"], + ["customer.tier == 'silver'", "0.05"], + ["", "0"], + ]}, + ], + }, + cases: [ + [{customer: {spend: 20000}}, {customer: {spend: 20000, tier: "gold", discount: 0.15}}], + [{customer: {spend: 1000}}, {customer: {spend: 1000, tier: "silver", discount: 0.05}}], + [{customer: {spend: 999.99}}, {customer: {spend: 999.99, tier: "bronze", discount: 0}}], + [{customer: {spend: -1}}, {customer: {spend: -1, tier: "bronze", discount: 0}}], + ], +} + +{ + name: "an enum on a referenced pool entity", + policy: { + models: {order: {product: "&product"}, product: {id: "string", category: "string(food|tech|book)"}}, + blocks: [{match: "order.vat", arms: [ + ["order.product.category == 'food'", "0.15"], + ["order.product.category == 'book'", "0"], + ["", "0.25"], + ]}], + }, + cases: [ + [ + {order: {product: "p1"}, product: [{id: "p1", category: "food"}, {id: "p2", category: "tech"}]}, + {order: {product: {id: "p1", category: "food"}, vat: 0.15}, product: [{id: "p1", category: "food"}, {id: "p2", category: "tech"}]}, + ], + [ + {order: {product: "p2"}, product: [{id: "p1", category: "food"}, {id: "p2", category: "tech"}]}, + {order: {product: {id: "p2", category: "tech"}, vat: 0.25}, product: [{id: "p1", category: "food"}, {id: "p2", category: "tech"}]}, + ], + [{order: {product: "p1"}, product: [{id: "p1", category: "toys"}]}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an enum global selects a member formula", + policy: { + globals: {settings: {rounding: "string(up|down|nearest)"}}, + models: {cart: {items: "item[]"}, item: {price: "number"}}, + blocks: [ + {match: "item.charged", arms: [ + ["rounding == 'up'", "ceil(item.price)"], + ["rounding == 'down'", "floor(item.price)"], + ["rounding == 'nearest'", "round(item.price)"], + ]}, + {expression: "cart.total", value: "sum(map(cart.items, #.charged))"}, + ], + }, + cases: [ + [{rounding: "up", cart: {items: [{price: 1.2}, {price: 2.5}]}}, {rounding: "up", cart: {items: [{price: 1.2, charged: 2}, {price: 2.5, charged: 3}], total: 5}}], + [{rounding: "down", cart: {items: [{price: 1.2}, {price: 2.5}]}}, {rounding: "down", cart: {items: [{price: 1.2, charged: 1}, {price: 2.5, charged: 2}], total: 3}}], + [{rounding: "nearest", cart: {items: [{price: 1.2}, {price: 2.5}]}}, {rounding: "nearest", cart: {items: [{price: 1.2, charged: 1}, {price: 2.5, charged: 3}], total: 4}}], + [{rounding: "banker", cart: {items: []}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Dictionaries in tables. + +{ + name: "a dictionary column with list cells", + policy: { + dictionaries: {country: [["NO", "Norway"], ["SE", "Sweden"], ["DK", "Denmark"], ["DE", "Germany"], ["US", "United States"]]}, + models: {shipment: {to: "country", kg: "number"}}, + blocks: [{table: "t", inputs: ["shipment.to", "shipment.kg"], outputs: ["shipment.zone", "shipment.price"], rules: [ + ["'NO'", "", "'domestic'", "5 + shipment.kg"], + ["'SE', 'DK'", "<= 10", "'nordic'", "15"], + ["'SE', 'DK'", "", "'nordic'", "25"], + ["'DE'", "", "'eu'", "40"], + ["", "", "'world'", "80"], + ]}], + }, + cases: [ + [{shipment: {to: "NO", kg: 3}}, {shipment: {to: "NO", kg: 3, zone: "domestic", price: 8}}], + [{shipment: {to: "SE", kg: 10}}, {shipment: {to: "SE", kg: 10, zone: "nordic", price: 15}}], + [{shipment: {to: "DK", kg: 10.5}}, {shipment: {to: "DK", kg: 10.5, zone: "nordic", price: 25}}], + [{shipment: {to: "DE", kg: 1}}, {shipment: {to: "DE", kg: 1, zone: "eu", price: 40}}], + [{shipment: {to: "US", kg: 1}}, {shipment: {to: "US", kg: 1, zone: "world", price: 80}}], + [{shipment: {to: "Norway", kg: 1}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a dictionary table writes dictionary values out", + policy: { + dictionaries: {risk: ["low", "medium", "high"], industry: ["finance", "retail", "mining"]}, + models: {company: {industry: "industry", employees: "number"}}, + blocks: [ + {table: "t", inputs: ["company.industry", "company.employees"], outputs: ["company.risk"], rules: [ + ["'mining'", "", "'high'"], + ["'finance'", "> 1000", "'medium'"], + ["", "", "'low'"], + ]}, + {expression: "company.riskLabel", value: "upper(company.risk)"}, + ], + }, + cases: [ + [{company: {industry: "mining", employees: 5}}, {company: {industry: "mining", employees: 5, risk: "high", riskLabel: "HIGH"}}], + [{company: {industry: "finance", employees: 5000}}, {company: {industry: "finance", employees: 5000, risk: "medium", riskLabel: "MEDIUM"}}], + [{company: {industry: "finance", employees: 1000}}, {company: {industry: "finance", employees: 1000, risk: "low", riskLabel: "LOW"}}], + [{company: {industry: "retail", employees: 50000}}, {company: {industry: "retail", employees: 50000, risk: "low", riskLabel: "LOW"}}], + ], +} + +{ + name: "a per-member table over a dictionary property", + policy: { + dictionaries: {doc: [["pass", "Passport"], ["id", "National ID"], ["dl", "Driving licence"]]}, + models: {applicant: {documents: "document[]"}, document: {kind: "doc", verified: "boolean"}}, + blocks: [ + {table: "t", inputs: ["document.kind", "document.verified"], outputs: ["document.points"], rules: [ + ["'pass'", "true", "50"], + ["'id'", "true", "40"], + ["'dl'", "true", "20"], + ["", "", "0"], + ]}, + {expression: "applicant.score", value: "sum(map(applicant.documents, #.points))"}, + {expression: "applicant.passes", value: "applicant.score >= 60"}, + ], + }, + cases: [ + [{applicant: {documents: []}}, {applicant: {documents: [], score: 0, passes: false}}], + [ + {applicant: {documents: [{kind: "pass", verified: true}, {kind: "dl", verified: true}]}}, + {applicant: {documents: [{kind: "pass", verified: true, points: 50}, {kind: "dl", verified: true, points: 20}], score: 70, passes: true}}, + ], + [ + {applicant: {documents: [{kind: "id", verified: false}, {kind: "pass", verified: true}]}}, + {applicant: {documents: [{kind: "id", verified: false, points: 0}, {kind: "pass", verified: true, points: 50}], score: 50, passes: false}}, + ], + [{applicant: {documents: [{kind: "Passport", verified: true}]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a collect table over a dictionary array", + policy: { + dictionaries: {feature: ["sso", "audit", "api", "export"]}, + models: {account: {features: "feature[]"}}, + blocks: [{table: "t", hit: "collect", inputs: [""], outputs: ["account.addons[]", "account.cost[]"], rules: [ + ["'sso' in account.features", "'SSO pack'", "10"], + ["'audit' in account.features", "'Compliance pack'", "25"], + ["'api' in account.features or 'export' in account.features", "'Integration pack'", "5"], + ]}], + }, + cases: [ + [{account: {features: []}}, {account: {features: [], addons: [], cost: []}}], + [{account: {features: ["sso", "api"]}}, {account: {features: ["sso", "api"], addons: ["SSO pack", "Integration pack"], cost: [10, 5]}}], + [{account: {features: ["export", "audit", "api"]}}, {account: {features: ["export", "audit", "api"], addons: ["Compliance pack", "Integration pack"], cost: [25, 5]}}], + [{account: {features: ["sso", "chat"]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "dictionary values with unicode and spaces in table cells", + policy: { + dictionaries: {city: ["Zürich", "São Paulo", "Kraków", "東京"]}, + models: {office: {city: "city"}}, + blocks: [{table: "t", inputs: ["office.city"], outputs: ["office.region"], rules: [ + ["'Zürich', 'Kraków'", "'Europe'"], + ["'São Paulo'", "'Americas'"], + ["'東京'", "'Asia'"], + ]}], + }, + cases: [ + [{office: {city: "Zürich"}}, {office: {city: "Zürich", region: "Europe"}}], + [{office: {city: "Kraków"}}, {office: {city: "Kraków", region: "Europe"}}], + [{office: {city: "São Paulo"}}, {office: {city: "São Paulo", region: "Americas"}}], + [{office: {city: "東京"}}, {office: {city: "東京", region: "Asia"}}], + [{office: {city: "Zurich"}}, "!error: InputValidationFailed"], + [{office: {city: "Sao Paulo"}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// String columns in tables: exact cells, function cells over `$`, and computed string inputs. + +{ + name: "string cells are exact and case-sensitive", + policy: { + models: {lead: {source: "string"}}, + blocks: [{table: "t", inputs: ["lead.source"], outputs: ["lead.channel"], rules: [ + ["'google'", "'search'"], + ["'Google'", "'search (capitalised)'"], + ["''", "'unknown'"], + ["", "'other'"], + ]}], + }, + cases: [ + [{lead: {source: "google"}}, {lead: {source: "google", channel: "search"}}], + [{lead: {source: "Google"}}, {lead: {source: "Google", channel: "search (capitalised)"}}], + [{lead: {source: "GOOGLE"}}, {lead: {source: "GOOGLE", channel: "other"}}], + [{lead: {source: ""}}, {lead: {source: "", channel: "unknown"}}], + [{lead: {source: " google"}}, {lead: {source: " google", channel: "other"}}], + ], +} + +{ + name: "function cells over a string column", + policy: { + models: {email: {address: "string"}}, + blocks: [{table: "t", inputs: ["email.address"], outputs: ["email.kind"], rules: [ + ["endsWith($, '@example.com')", "'internal'"], + ["contains($, '+')", "'alias'"], + ["matches($, '^[^@]+@[^@]+$')", "'external'"], + ["", "'invalid'"], + ]}], + }, + cases: [ + [{email: {address: "ann@example.com"}}, {email: {address: "ann@example.com", kind: "internal"}}], + [{email: {address: "bob+news@mail.org"}}, {email: {address: "bob+news@mail.org", kind: "alias"}}], + [{email: {address: "cé@exämple.de"}}, {email: {address: "cé@exämple.de", kind: "external"}}], + [{email: {address: "nobody"}}, {email: {address: "nobody", kind: "invalid"}}], + [{email: {address: ""}}, {email: {address: "", kind: "invalid"}}], + ], +} + +{ + name: "a table over a normalised string expression", + policy: { + models: {country: {input: "string"}}, + blocks: [{table: "t", inputs: ["upper(trim(country.input))"], outputs: ["country.code"], rules: [ + ["'NORWAY', 'NORGE', 'NO'", "'NO'"], + ["'SWEDEN', 'SVERIGE', 'SE'", "'SE'"], + ["", "null"], + ]}], + }, + cases: [ + [{country: {input: " norway "}}, {country: {input: " norway ", code: "NO"}}], + [{country: {input: "Norge"}}, {country: {input: "Norge", code: "NO"}}], + [{country: {input: "sverige"}}, {country: {input: "sverige", code: "SE"}}], + [{country: {input: "Finland"}}, {country: {input: "Finland", code: null}}], + [{country: {input: ""}}, {country: {input: "", code: null}}], + ], +} + +{ + name: "table string outputs built from inputs", + policy: { + models: {user: {first: "string", last: "string", formal: "boolean"}}, + blocks: [{table: "t", inputs: ["user.formal"], outputs: ["user.salutation"], rules: [ + ["true", "'Dear ' + user.first + ' ' + upper(user.last)"], + ["false", "`Hi ${user.first}!`"], + ]}], + }, + cases: [ + [{user: {first: "Ada", last: "Lovelace", formal: true}}, {user: {first: "Ada", last: "Lovelace", formal: true, salutation: "Dear Ada LOVELACE"}}], + [{user: {first: "Ada", last: "Lovelace", formal: false}}, {user: {first: "Ada", last: "Lovelace", formal: false, salutation: "Hi Ada!"}}], + [{user: {first: "Jürgen", last: "Weiß", formal: true}}, {user: {first: "Jürgen", last: "Weiß", formal: true, salutation: "Dear Jürgen WEISS"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// A realistic combination: support ticket routing with enums, dictionaries and string rules. + +{ + name: "support ticket routing", + policy: { + dictionaries: {lang: [["en", "English"], ["de", "German"], ["ja", "Japanese"]]}, + models: {ticket: {subject: "string", body: "string", language: "lang", plan: "string(free|pro|enterprise)"}}, + blocks: [ + {expression: "ticket.text", value: "lower(ticket.subject + ' ' + ticket.body)"}, + {expression: "ticket.urgent", value: "contains(ticket.text, 'outage') or contains(ticket.text, 'down') or contains(ticket.text, '至急')"}, + {table: "t", inputs: ["ticket.language"], outputs: ["ticket.queue"], rules: [ + ["'de'", "'dach'"], + ["'ja'", "'apac'"], + ["", "'global'"], + ]}, + {match: "ticket.priority", arms: [ + ["ticket.urgent and ticket.plan == 'enterprise'", "'P1'"], + ["ticket.urgent", "'P2'"], + ["ticket.plan == 'free'", "'P4'"], + ["", "'P3'"], + ]}, + {expression: "ticket.routing", value: "ticket.queue + '/' + ticket.priority"}, + ], + }, + cases: [ + [ + {ticket: {subject: "Site DOWN", body: "help", language: "en", plan: "enterprise"}}, + {ticket: {subject: "Site DOWN", body: "help", language: "en", plan: "enterprise", text: "site down help", urgent: true, queue: "global", priority: "P1", routing: "global/P1"}}, + ], + [ + {ticket: {subject: "Frage", body: "Rechnung", language: "de", plan: "free"}}, + {ticket: {subject: "Frage", body: "Rechnung", language: "de", plan: "free", text: "frage rechnung", urgent: false, queue: "dach", priority: "P4", routing: "dach/P4"}}, + ], + [ + {ticket: {subject: "障害", body: "至急対応", language: "ja", plan: "pro"}}, + {ticket: {subject: "障害", body: "至急対応", language: "ja", plan: "pro", text: "障害 至急対応", urgent: true, queue: "apac", priority: "P2", routing: "apac/P2"}}, + ], + [ + {ticket: {subject: "", body: "", language: "en", plan: "pro"}}, + {ticket: {subject: "", body: "", language: "en", plan: "pro", text: " ", urgent: false, queue: "global", priority: "P3", routing: "global/P3"}}, + ], + [{ticket: {subject: "x", body: "y", language: "fr", plan: "pro"}}, "!error: InputValidationFailed"], + [{ticket: {subject: "x", body: "y", language: "en", plan: "Pro"}}, "!error: InputValidationFailed"], + ], +} diff --git a/core/engine/tests/spec/policy/29-policy-optionals.json5 b/core/engine/tests/spec/policy/29-policy-optionals.json5 new file mode 100644 index 00000000..a11443ec --- /dev/null +++ b/core/engine/tests/spec/policy/29-policy-optionals.json5 @@ -0,0 +1,767 @@ +// Optional values in depth. An optional property (`?`) may be missing or null; reading it gives +// null, and so does reading anything below it. `??` replaces null (and only null) with a default. +// Chapter 15 covers single-level optionals, guards and null through each block kind; this +// chapter follows optionals through chains of relationships and references, optional arrays, +// fallback chains, per-member blocks, tables, matches and assertions, and pins what the output +// looks like when optionals are absent. + +// --------------------------------------------------------------------------------------------- +// Optional chains through relationships. Every hop that is missing or null makes the whole read +// null; the declared types below an absent hop are not required. + +{ + name: "a two-hop optional chain reads null at any missing hop", + policy: { + models: { + customer: {account: "account?"}, + account: {owner: "person?"}, + person: {email: "string?"}, + }, + blocks: [{expression: "customer.contact", value: "customer.account.owner.email ?? 'none'"}], + }, + cases: [ + [{customer: {}}, {customer: {contact: "none"}}], + [{customer: {account: null}}, {customer: {account: null, contact: "none"}}], + [{customer: {account: {}}}, {customer: {account: {}, contact: "none"}}], + [{customer: {account: {owner: null}}}, {customer: {account: {owner: null}, contact: "none"}}], + [{customer: {account: {owner: {}}}}, {customer: {account: {owner: {}}, contact: "none"}}], + [{customer: {account: {owner: {email: null}}}}, {customer: {account: {owner: {email: null}}, contact: "none"}}], + [{customer: {account: {owner: {email: "a@b.c"}}}}, {customer: {account: {owner: {email: "a@b.c"}}, contact: "a@b.c"}}], + [{customer: {account: {owner: {email: 5}}}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "a required property below an optional hop is required only when the hop is present", + policy: { + models: { + customer: {account: "account?"}, + account: {owner: "person"}, + person: {email: "string"}, + }, + blocks: [{expression: "customer.contact", value: "customer.account.owner.email ?? 'none'"}], + }, + cases: [ + [{customer: {}}, {customer: {contact: "none"}}], + [{customer: {account: null}}, {customer: {account: null, contact: "none"}}], + [{customer: {account: {owner: {email: "x@y.z"}}}}, {customer: {account: {owner: {email: "x@y.z"}}, contact: "x@y.z"}}], + [{customer: {account: {}}}, "!error: MissingRequiredInputs"], + [{customer: {account: {owner: {}}}}, "!error: MissingRequiredInputs"], + [{customer: {account: {owner: null}}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "an optional hop below a required relationship", + policy: { + models: { + customer: {profile: "profile"}, + profile: {address: "address?"}, + address: {city: "string"}, + }, + blocks: [{expression: "customer.city", value: "customer.profile.address.city ?? 'unknown'"}], + }, + cases: [ + [{customer: {profile: {}}}, {customer: {profile: {}, city: "unknown"}}], + [{customer: {profile: {address: null}}}, {customer: {profile: {address: null}, city: "unknown"}}], + [{customer: {profile: {address: {city: "Oslo"}}}}, {customer: {profile: {address: {city: "Oslo"}}, city: "Oslo"}}], + {input: {customer: {}}, output: {customer: {city: "unknown"}}, note: "question: the required relationship `profile` is missing but the read goes through the optional `address`, so the required-input check is skipped and the chain reads null; a single-hop read of a missing required relationship is MissingRequiredInputs"}, + {input: {customer: {profile: null}}, output: {customer: {profile: null, city: "unknown"}}, note: "question: as above, a null required relationship is not reported when the read continues through an optional hop"}, + [{customer: {profile: {address: {}}}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "several reads through the same optional relationship", + policy: { + models: {customer: {report: "creditReport?"}, creditReport: {score: "number", defaults: "number?"}}, + blocks: [ + {expression: "customer.hasReport", value: "customer.report != null"}, + {expression: "customer.score", value: "customer.report.score ?? 500"}, + {expression: "customer.defaults", value: "customer.report.defaults ?? 0"}, + {expression: "customer.clean", value: "customer.hasReport and customer.defaults == 0"}, + ], + }, + cases: [ + [{customer: {}}, {customer: {hasReport: false, score: 500, defaults: 0, clean: false}}], + [{customer: {report: null}}, {customer: {report: null, hasReport: false, score: 500, defaults: 0, clean: false}}], + [{customer: {report: {score: 720}}}, {customer: {report: {score: 720}, hasReport: true, score: 720, defaults: 0, clean: true}}], + [{customer: {report: {score: 610, defaults: 2}}}, {customer: {report: {score: 610, defaults: 2}, hasReport: true, score: 610, defaults: 2, clean: false}}], + [{customer: {report: {score: 0, defaults: null}}}, {customer: {report: {score: 0, defaults: null}, hasReport: true, score: 0, defaults: 0, clean: true}}], + [{customer: {report: {defaults: 1}}}, "!error: MissingRequiredInputs"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Optional chains through references. An optional reference may be missing or null; when present +// it must resolve. Reads below it follow the same rules as relationships. + +{ + name: "an optional reference to an entity with an optional relationship", + policy: { + models: { + order: {product: "&product?"}, + product: {id: "string", supplier: "supplier?"}, + supplier: {name: "string"}, + }, + blocks: [{expression: "order.supplier", value: "order.product.supplier.name ?? 'n/a'"}], + }, + cases: [ + [{order: {}}, {order: {supplier: "n/a"}}], + [{order: {product: null}, product: []}, {order: {product: null, supplier: "n/a"}, product: []}], + [ + {order: {product: "p1"}, product: [{id: "p1"}]}, + {order: {product: {id: "p1"}, supplier: "n/a"}, product: [{id: "p1"}]}, + ], + [ + {order: {product: "p1"}, product: [{id: "p1", supplier: {name: "Acme"}}]}, + {order: {product: {id: "p1", supplier: {name: "Acme"}}, supplier: "Acme"}, product: [{id: "p1", supplier: {name: "Acme"}}]}, + ], + [{order: {product: "p9"}, product: [{id: "p1"}]}, "!error: InputValidationFailed"], + [{order: {product: "p1"}, product: [{id: "p1", supplier: {}}]}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "an optional reference array", + policy: { + models: {cart: {items: "&product[]?"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "cart.count", value: "len(cart.items ?? [])"}, + {expression: "cart.total", value: "sum(map(cart.items ?? [], #.price))"}, + ], + }, + cases: [ + [{cart: {}}, {cart: {count: 0, total: 0}}], + [{cart: {items: null}}, {cart: {items: null, count: 0, total: 0}}], + [{cart: {items: []}, product: []}, {cart: {items: [], count: 0, total: 0}, product: []}], + [ + {cart: {items: ["a", "b", "a"]}, product: [{id: "a", price: 2}, {id: "b", price: 3.5}]}, + {cart: {items: [{id: "a", price: 2}, {id: "b", price: 3.5}, {id: "a", price: 2}], count: 3, total: 7.5}, product: [{id: "a", price: 2}, {id: "b", price: 3.5}]}, + ], + [{cart: {items: ["a", "z"]}, product: [{id: "a", price: 2}]}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// `??` defaults: only null is replaced; falsy values are kept. Chains try each operand in turn. + +{ + name: "?? keeps zero, false and the empty string", + policy: { + models: {s: {n: "number?", b: "boolean?", t: "string?", list: "number[]?"}}, + blocks: [ + {expression: "s.n2", value: "s.n ?? 99"}, + {expression: "s.b2", value: "s.b ?? true"}, + {expression: "s.t2", value: "s.t ?? 'default'"}, + {expression: "s.list2", value: "s.list ?? [9]"}, + ], + }, + cases: [ + [{s: {n: 0, b: false, t: "", list: []}}, {s: {n: 0, b: false, t: "", list: [], n2: 0, b2: false, t2: "", list2: []}}], + [{s: {}}, {s: {n2: 99, b2: true, t2: "default", list2: [9]}}], + [{s: {n: null, b: null, t: null, list: null}}, {s: {n: null, b: null, t: null, list: null, n2: 99, b2: true, t2: "default", list2: [9]}}], + [{s: {n: -1, b: true, t: " ", list: [null]}}, {s: {n: -1, b: true, t: " ", list: [null], n2: -1, b2: true, t2: " ", list2: [null]}}], + ], +} + +{ + name: "a fallback chain across entities and globals", + policy: { + globals: {defaults: {defaultCurrency: "string?"}}, + models: {order: {currency: "string?", customer: "buyer?"}, buyer: {currency: "string?"}}, + blocks: [{expression: "order.effectiveCurrency", value: "order.currency ?? order.customer.currency ?? defaultCurrency ?? 'EUR'"}], + }, + cases: [ + [{order: {currency: "NOK", customer: {currency: "SEK"}}, defaultCurrency: "USD"}, {order: {currency: "NOK", customer: {currency: "SEK"}, effectiveCurrency: "NOK"}, defaultCurrency: "USD"}], + [{order: {customer: {currency: "SEK"}}, defaultCurrency: "USD"}, {order: {customer: {currency: "SEK"}, effectiveCurrency: "SEK"}, defaultCurrency: "USD"}], + [{order: {customer: {}}, defaultCurrency: "USD"}, {order: {customer: {}, effectiveCurrency: "USD"}, defaultCurrency: "USD"}], + [{order: {}, defaultCurrency: "USD"}, {order: {effectiveCurrency: "USD"}, defaultCurrency: "USD"}], + [{order: {}}, {order: {effectiveCurrency: "EUR"}}], + [{order: {currency: null, customer: null}, defaultCurrency: null}, {order: {currency: null, customer: null, effectiveCurrency: "EUR"}, defaultCurrency: null}], + [{order: {currency: ""}}, {order: {currency: "", effectiveCurrency: ""}}], + ], +} + +{ + name: "?? over a computed null from a table with no matching row", + policy: { + models: {customer: {country: "string"}}, + blocks: [ + {table: "t", inputs: ["customer.country"], outputs: ["customer.vat"], rules: [ + ["'NO'", "0.25"], + ["'DE'", "0.19"], + ]}, + {expression: "customer.vatOrZero", value: "customer.vat ?? 0"}, + {expression: "customer.known", value: "customer.vat != null"}, + ], + }, + cases: [ + [{customer: {country: "NO"}}, {customer: {country: "NO", vat: 0.25, vatOrZero: 0.25, known: true}}], + [{customer: {country: "DE"}}, {customer: {country: "DE", vat: 0.19, vatOrZero: 0.19, known: true}}], + [{customer: {country: "US"}}, {customer: {country: "US", vat: null, vatOrZero: 0, known: false}}], + [{customer: {country: ""}}, {customer: {country: "", vat: null, vatOrZero: 0, known: false}}], + ], +} + +{ + name: "?? with a default computed by another block", + policy: { + models: {item: {price: "number", override: "number?"}}, + blocks: [ + {expression: "item.listPrice", value: "item.price * 1.25"}, + {expression: "item.finalPrice", value: "item.override ?? item.listPrice"}, + ], + }, + cases: [ + [{item: {price: 100}}, {item: {price: 100, listPrice: 125, finalPrice: 125}}], + [{item: {price: 100, override: 80}}, {item: {price: 100, override: 80, listPrice: 125, finalPrice: 80}}], + [{item: {price: 100, override: null}}, {item: {price: 100, override: null, listPrice: 125, finalPrice: 125}}], + [{item: {price: 100, override: 0}}, {item: {price: 100, override: 0, listPrice: 125, finalPrice: 0}}], + ], +} + +{ + name: "?? inside arithmetic and comparisons", + policy: { + models: {loan: {amount: "number", fee: "number?", cap: "number?"}}, + blocks: [ + {expression: "loan.cost", value: "loan.amount + (loan.fee ?? 0)"}, + {expression: "loan.withinCap", value: "loan.cost <= (loan.cap ?? loan.cost)"}, + ], + }, + cases: [ + [{loan: {amount: 100}}, {loan: {amount: 100, cost: 100, withinCap: true}}], + [{loan: {amount: 100, fee: 5}}, {loan: {amount: 100, fee: 5, cost: 105, withinCap: true}}], + [{loan: {amount: 100, fee: 5, cap: 104}}, {loan: {amount: 100, fee: 5, cap: 104, cost: 105, withinCap: false}}], + [{loan: {amount: 100, cap: 100}}, {loan: {amount: 100, cap: 100, cost: 100, withinCap: true}}], + [{loan: {amount: 0.1, fee: 0.2, cap: 0.3}}, {loan: {amount: 0.1, fee: 0.2, cap: 0.3, cost: 0.3, withinCap: true}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Optional arrays of primitives and of entities. `??` replaces a null array only: an empty array +// is kept, so `max(xs ?? [0])` still fails on `[]`. + +{ + name: "closures over an optional primitive array", + policy: { + models: {user: {scores: "number[]?"}}, + blocks: [ + {expression: "user.best", value: "max(user.scores ?? [0])"}, + {expression: "user.passed", value: "count(user.scores ?? [], # >= 50)"}, + {expression: "user.allPassed", value: "all(user.scores ?? [], # >= 50)"}, + {expression: "user.first", value: "(user.scores ?? [])[0] ?? -1"}, + ], + }, + cases: [ + [{user: {}}, {user: {best: 0, passed: 0, allPassed: true, first: -1}}], + [{user: {scores: null}}, {user: {scores: null, best: 0, passed: 0, allPassed: true, first: -1}}], + [{user: {scores: []}}, "!error: ExpressionFailed"], + [{user: {scores: [40, 70, 55]}}, {user: {scores: [40, 70, 55], best: 70, passed: 2, allPassed: false, first: 40}}], + [{user: {scores: [50]}}, {user: {scores: [50], best: 50, passed: 1, allPassed: true, first: 50}}], + [{user: {scores: ["50"]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an optional enum array", + policy: { + models: {user: {roles: "string(admin|editor|viewer)[]?"}}, + blocks: [ + {expression: "user.isAdmin", value: "'admin' in (user.roles ?? [])"}, + {expression: "user.roleCount", value: "len(user.roles ?? [])"}, + ], + }, + cases: [ + [{user: {}}, {user: {isAdmin: false, roleCount: 0}}], + [{user: {roles: null}}, {user: {roles: null, isAdmin: false, roleCount: 0}}], + [{user: {roles: ["viewer", "admin"]}}, {user: {roles: ["viewer", "admin"], isAdmin: true, roleCount: 2}}], + [{user: {roles: ["owner"]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an optional date array", + policy: { + models: {member: {visits: "date[]?"}}, + blocks: [ + {expression: "member.visitedThisYear", value: "some(member.visits ?? [], #.year() == 2025)"}, + {expression: "member.visitCount", value: "len(member.visits ?? [])"}, + ], + }, + cases: [ + [{member: {}}, {member: {visitedThisYear: false, visitCount: 0}}], + [{member: {visits: null}}, {member: {visits: null, visitedThisYear: false, visitCount: 0}}], + [{member: {visits: ["2024-12-31", "2025-01-02"]}}, {member: {visits: ["2024-12-31", "2025-01-02"], visitedThisYear: true, visitCount: 2}}], + [{member: {visits: ["2024-01-01"]}}, {member: {visits: ["2024-01-01"], visitedThisYear: false, visitCount: 1}}], + [{member: {visits: ["soon"]}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "an optional relationship array with per-member blocks and a parent aggregate", + policy: { + models: {customer: {orders: "order[]?"}, order: {total: "number", coupon: "number?"}}, + blocks: [ + {expression: "order.net", value: "order.total - (order.coupon ?? 0)"}, + {expression: "customer.spend", value: "sum(map(customer.orders ?? [], #.net))"}, + {expression: "customer.usedCoupons", value: "count(customer.orders ?? [], #.coupon != null)"}, + ], + }, + cases: [ + [{customer: {}}, {customer: {spend: 0, usedCoupons: 0}}], + [{customer: {orders: null}}, {customer: {orders: null, spend: 0, usedCoupons: 0}}], + [{customer: {orders: []}}, {customer: {orders: [], spend: 0, usedCoupons: 0}}], + [ + {customer: {orders: [{total: 50, coupon: 5}, {total: 20}, {total: 10, coupon: null}]}}, + {customer: {orders: [{total: 50, coupon: 5, net: 45}, {total: 20, net: 20}, {total: 10, coupon: null, net: 10}], spend: 75, usedCoupons: 1}}, + ], + {input: {customer: {orders: [{coupon: 5}]}}, output: "!error: MissingRequiredInputs", note: "bug: a member missing a required property is not caught by the required-input check (a single relationship is); the per-member block fails with ExpressionFailed instead"}, + ], +} + +{ + name: "optional properties on nested members", + policy: { + models: { + customer: {orders: "order[]"}, + order: {lines: "line[]?"}, + line: {qty: "number", discount: "number?"}, + }, + blocks: [ + {expression: "order.discountedLines", value: "count(order.lines ?? [], #.discount != null)"}, + {expression: "order.units", value: "sum(map(order.lines ?? [], #.qty))"}, + {expression: "customer.units", value: "sum(map(customer.orders, #.units))"}, + ], + }, + cases: [ + [{customer: {orders: []}}, {customer: {orders: [], units: 0}}], + [{customer: {orders: [{}]}}, {customer: {orders: [{discountedLines: 0, units: 0}], units: 0}}], + [ + {customer: {orders: [{lines: [{qty: 2, discount: 0.1}, {qty: 3}, {qty: 1, discount: null}]}, {lines: null}]}}, + {customer: {orders: [{lines: [{qty: 2, discount: 0.1}, {qty: 3}, {qty: 1, discount: null}], discountedLines: 1, units: 6}, {lines: null, discountedLines: 0, units: 0}], units: 6}}, + ], + [{customer: {orders: [{lines: [{qty: "2"}]}]}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Outputs when optionals are absent: absent input keys stay absent, computed values are written +// (as null when nothing else applies), and per-instance blocks of an absent relationship do not +// write anything. + +{ + name: "per-instance blocks of an absent optional relationship write nothing", + policy: { + models: {customer: {name: "string", report: "creditReport?"}, creditReport: {score: "number"}}, + blocks: [ + {expression: "creditReport.good", value: "creditReport.score >= 700"}, + {expression: "customer.goodCredit", value: "customer.report.good ?? false"}, + ], + }, + cases: [ + [{customer: {name: "a"}}, {customer: {name: "a", goodCredit: false}}], + [{customer: {name: "a", report: null}}, {customer: {name: "a", report: null, goodCredit: false}}], + [{customer: {name: "a", report: {score: 750}}}, {customer: {name: "a", report: {score: 750, good: true}, goodCredit: true}}], + [{customer: {name: "a", report: {score: 600}}}, {customer: {name: "a", report: {score: 600, good: false}, goodCredit: false}}], + ], +} + +{ + name: "a computed nested object built from optionals", + policy: { + models: {customer: {email: "string?", phone: "string?"}}, + blocks: [ + {expression: "customer.contact.email", value: "customer.email"}, + {expression: "customer.contact.phone", value: "customer.phone"}, + {expression: "customer.contact.reachable", value: "customer.email != null or customer.phone != null"}, + ], + }, + cases: [ + [{customer: {}}, {customer: {contact: {email: null, phone: null, reachable: false}}}], + [{customer: {email: "a@b.c"}}, {customer: {email: "a@b.c", contact: {email: "a@b.c", phone: null, reachable: true}}}], + [{customer: {phone: "+47 1"}}, {customer: {phone: "+47 1", contact: {email: null, phone: "+47 1", reachable: true}}}], + [{customer: {email: null, phone: null}}, {customer: {email: null, phone: null, contact: {email: null, phone: null, reachable: false}}}], + ], +} + +{ + name: "an absent optional entity root gets its computed properties", + policy: { + models: {customer: {nickname: "string?"}, session: {locale: "string?"}}, + blocks: [ + {expression: "session.lang", value: "session.locale ?? 'en'"}, + {expression: "customer.greeting", value: "(session.lang == 'no' ? 'Hei ' : 'Hello ') + (customer.nickname ?? 'there')"}, + ], + }, + cases: [ + [{}, {session: {lang: "en"}, customer: {greeting: "Hello there"}}], + [{session: {locale: "no"}}, {session: {locale: "no", lang: "no"}, customer: {greeting: "Hei there"}}], + [{customer: {nickname: "Bo"}, session: {}}, {customer: {nickname: "Bo", greeting: "Hello Bo"}, session: {lang: "en"}}], + {input: {customer: null, session: null}, output: {customer: {greeting: "Hello there"}, session: {lang: "en"}}, note: "bug: computed writes into a null entity root are dropped (the output keeps the nulls), while a missing root gets them; elsewhere a null root is treated as missing"}, + ], +} + +{ + name: "an optional copied into a list and an object keeps the nulls", + policy: { + models: {p: {a: "number?", b: "number?"}}, + blocks: [ + {expression: "p.list", value: "[p.a, p.b]"}, + {expression: "p.obj", value: "{a: p.a, b: p.b}"}, + {expression: "p.present", value: "filter([p.a, p.b], # != null)"}, + ], + }, + cases: [ + [{p: {}}, {p: {list: [null, null], obj: {a: null, b: null}, present: []}}], + [{p: {a: 1}}, {p: {a: 1, list: [1, null], obj: {a: 1, b: null}, present: [1]}}], + [{p: {a: 0, b: -1}}, {p: {a: 0, b: -1, list: [0, -1], obj: {a: 0, b: -1}, present: [0, -1]}}], + [{p: {b: 2.5}}, {p: {b: 2.5, list: [null, 2.5], obj: {a: null, b: 2.5}, present: [2.5]}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Optionals in tables: `??` input fields, null rows over chained optionals, two optional columns, +// output cells reading optionals, per-member tables. + +{ + name: "a table over an optional chain with a null row", + policy: { + models: {customer: {report: "creditReport?"}, creditReport: {rating: "string(A|B|C)?"}}, + blocks: [{table: "t", inputs: ["customer.report.rating"], outputs: ["customer.limit"], rules: [ + ["null", "500"], + ["'A'", "10000"], + ["'B'", "5000"], + ["", "1000"], + ]}], + }, + cases: [ + [{customer: {}}, {customer: {limit: 500}}], + [{customer: {report: null}}, {customer: {report: null, limit: 500}}], + [{customer: {report: {}}}, {customer: {report: {}, limit: 500}}], + [{customer: {report: {rating: "A"}}}, {customer: {report: {rating: "A"}, limit: 10000}}], + [{customer: {report: {rating: "B"}}}, {customer: {report: {rating: "B"}, limit: 5000}}], + [{customer: {report: {rating: "C"}}}, {customer: {report: {rating: "C"}, limit: 1000}}], + ], +} + +{ + name: "a table with ?? defaults in its input fields", + policy: { + models: {applicant: {income: "number?", debts: "number?"}}, + blocks: [{table: "t", inputs: ["applicant.income ?? 0", "applicant.debts ?? 0"], outputs: ["applicant.decision"], rules: [ + ["0", "", "'no income'"], + ["", "0", "'approve'"], + ["> 50000", "< 10000", "'approve'"], + ["", "", "'review'"], + ]}], + }, + cases: [ + [{applicant: {}}, {applicant: {decision: "no income"}}], + [{applicant: {income: 30000}}, {applicant: {income: 30000, decision: "approve"}}], + [{applicant: {income: 60000, debts: 5000}}, {applicant: {income: 60000, debts: 5000, decision: "approve"}}], + [{applicant: {income: 60000, debts: 20000}}, {applicant: {income: 60000, debts: 20000, decision: "review"}}], + [{applicant: {income: null, debts: 100}}, {applicant: {income: null, debts: 100, decision: "no income"}}], + [{applicant: {income: 40000, debts: null}}, {applicant: {income: 40000, debts: null, decision: "approve"}}], + ], +} + +{ + name: "a table over two optional columns", + policy: { + models: {contact: {email: "string?", phone: "string?"}}, + blocks: [{table: "t", inputs: ["contact.email", "contact.phone"], outputs: ["contact.channel"], rules: [ + ["null", "null", "'none'"], + ["null", "", "'sms'"], + ["", "", "'email'"], + ]}], + }, + cases: [ + [{contact: {}}, {contact: {channel: "none"}}], + [{contact: {phone: "1"}}, {contact: {phone: "1", channel: "sms"}}], + [{contact: {email: "a@b"}}, {contact: {email: "a@b", channel: "email"}}], + [{contact: {email: "a@b", phone: "1"}}, {contact: {email: "a@b", phone: "1", channel: "email"}}], + [{contact: {email: null, phone: null}}, {contact: {email: null, phone: null, channel: "none"}}], + [{contact: {email: "", phone: null}}, {contact: {email: "", phone: null, channel: "email"}}], + ], +} + +{ + name: "table output cells read optionals", + policy: { + models: {product: {kind: "string(digital|physical)", weight: "number?", shippingOverride: "number?"}}, + blocks: [{table: "t", inputs: ["product.kind"], outputs: ["product.shipping", "product.weightLabel"], rules: [ + ["'digital'", "0", "null"], + ["'physical'", "product.shippingOverride ?? (product.weight ?? 1) * 2", "string(product.weight ?? 0) + ' kg'"], + ]}], + }, + cases: [ + [{product: {kind: "digital"}}, {product: {kind: "digital", shipping: 0, weightLabel: null}}], + [{product: {kind: "physical"}}, {product: {kind: "physical", shipping: 2, weightLabel: "0 kg"}}], + [{product: {kind: "physical", weight: 3}}, {product: {kind: "physical", weight: 3, shipping: 6, weightLabel: "3 kg"}}], + [{product: {kind: "physical", weight: 3, shippingOverride: 0}}, {product: {kind: "physical", weight: 3, shippingOverride: 0, shipping: 0, weightLabel: "3 kg"}}], + ], +} + +{ + name: "a per-member table over optional member properties", + policy: { + models: {household: {people: "person[]"}, person: {age: "number?", student: "boolean?"}}, + blocks: [ + {table: "t", inputs: ["person.age ?? 16", "person.student ?? false"], outputs: ["person.fare"], rules: [ + ["< 16", "", "5"], + ["", "true", "7"], + ["", "", "10"], + ]}, + {expression: "household.total", value: "sum(map(household.people, #.fare))"}, + ], + }, + cases: [ + [{household: {people: []}}, {household: {people: [], total: 0}}], + [ + {household: {people: [{age: 10}, {age: 20, student: true}, {}, {age: 40, student: null}]}}, + {household: {people: [{age: 10, fare: 5}, {age: 20, student: true, fare: 7}, {fare: 10}, {age: 40, student: null, fare: 10}], total: 32}}, + ], + [{household: {people: [{student: false}]}}, {household: {people: [{student: false, fare: 10}], total: 10}}], + ], +} + +{ + name: "a collect table over optional flags", + policy: { + models: {account: {overdraft: "boolean?", frozen: "boolean?", kycDone: "boolean?"}}, + blocks: [{table: "t", hit: "collect", inputs: [""], outputs: ["account.issues[]"], rules: [ + ["account.overdraft == true", "'overdraft'"], + ["account.frozen == true", "'frozen'"], + ["account.kycDone != true", "'kyc missing'"], + ]}], + }, + cases: [ + [{account: {}}, {account: {issues: ["kyc missing"]}}], + [{account: {kycDone: true}}, {account: {kycDone: true, issues: []}}], + [{account: {overdraft: true, frozen: null, kycDone: false}}, {account: {overdraft: true, frozen: null, kycDone: false, issues: ["overdraft", "kyc missing"]}}], + [{account: {overdraft: false, frozen: true, kycDone: true}}, {account: {overdraft: false, frozen: true, kycDone: true, issues: ["frozen"]}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Optionals in matches. + +{ + name: "a match on the presence of optional relationships", + policy: { + models: {applicant: {cosigner: "person?", collateral: "asset?"}, person: {score: "number"}, asset: {value: "number"}}, + blocks: [{match: "applicant.security", arms: [ + ["applicant.cosigner != null and applicant.collateral != null", "'double'"], + ["applicant.collateral != null", "'collateral'"], + ["applicant.cosigner != null", "'cosigner'"], + ["", "'none'"], + ]}], + }, + cases: [ + [{applicant: {}}, {applicant: {security: "none"}}], + [{applicant: {cosigner: {score: 1}}}, {applicant: {cosigner: {score: 1}, security: "cosigner"}}], + [{applicant: {collateral: {value: 1}}}, {applicant: {collateral: {value: 1}, security: "collateral"}}], + [{applicant: {cosigner: {score: 1}, collateral: {value: 1}}}, {applicant: {cosigner: {score: 1}, collateral: {value: 1}, security: "double"}}], + [{applicant: {cosigner: null, collateral: null}}, {applicant: {cosigner: null, collateral: null, security: "none"}}], + ], +} + +{ + name: "match arms read optionals through ??", + policy: { + models: {claim: {amount: "number", deductible: "number?", covered: "boolean?"}}, + blocks: [{match: "claim.payout", arms: [ + ["(claim.covered ?? false) == false", "0"], + ["claim.amount <= (claim.deductible ?? 0)", "0"], + ["", "claim.amount - (claim.deductible ?? 0)"], + ]}], + }, + cases: [ + [{claim: {amount: 1000}}, {claim: {amount: 1000, payout: 0}}], + [{claim: {amount: 1000, covered: true}}, {claim: {amount: 1000, covered: true, payout: 1000}}], + [{claim: {amount: 1000, covered: true, deductible: 250}}, {claim: {amount: 1000, covered: true, deductible: 250, payout: 750}}], + [{claim: {amount: 200, covered: true, deductible: 250}}, {claim: {amount: 200, covered: true, deductible: 250, payout: 0}}], + [{claim: {amount: 1000, covered: false, deductible: 0}}, {claim: {amount: 1000, covered: false, deductible: 0, payout: 0}}], + [{claim: {amount: 1000, covered: null}}, {claim: {amount: 1000, covered: null, payout: 0}}], + ], +} + +{ + name: "a match arm value that reads an optional writes null", + policy: { + models: {user: {nickname: "string?", name: "string", preferNick: "boolean"}}, + blocks: [{match: "user.display", arms: [ + ["user.preferNick", "user.nickname"], + ["", "user.name"], + ]}], + }, + cases: [ + [{user: {name: "Robert", nickname: "Bob", preferNick: true}}, {user: {name: "Robert", nickname: "Bob", preferNick: true, display: "Bob"}}], + [{user: {name: "Robert", preferNick: true}}, {user: {name: "Robert", preferNick: true, display: null}}], + [{user: {name: "Robert", nickname: "Bob", preferNick: false}}, {user: {name: "Robert", nickname: "Bob", preferNick: false, display: "Robert"}}], + ], +} + +{ + name: "a per-member match over an optional member property", + policy: { + models: {team: {players: "player[]"}, player: {position: "string(gk|def|fwd)?"}}, + blocks: [ + {match: "player.role", arms: [ + ["player.position == 'gk'", "'keeper'"], + ["player.position == null", "'unassigned'"], + ["", "'outfield'"], + ]}, + {expression: "team.unassigned", value: "count(team.players, #.role == 'unassigned')"}, + ], + }, + cases: [ + [{team: {players: []}}, {team: {players: [], unassigned: 0}}], + [ + {team: {players: [{position: "gk"}, {}, {position: "fwd"}, {position: null}]}}, + {team: {players: [{position: "gk", role: "keeper"}, {role: "unassigned"}, {position: "fwd", role: "outfield"}, {position: null, role: "unassigned"}], unassigned: 2}}, + ], + [{team: {players: [{position: "mid"}]}}, "!error: InputValidationFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Optionals in assertions. A condition that evaluates to null is not true. + +{ + name: "an assertion condition that reads a null optional boolean is false", + policy: { + models: {user: {verified: "boolean?", active: "boolean"}}, + blocks: [{assertion: "user.ok", conditions: ["user.active", "user.verified"]}], + }, + cases: [ + [{user: {active: true, verified: true}}, {user: {active: true, verified: true, ok: true}}], + [{user: {active: true, verified: false}}, {user: {active: true, verified: false, ok: false}}], + [{user: {active: true}}, {user: {active: true, ok: false}}], + [{user: {active: true, verified: null}}, {user: {active: true, verified: null, ok: false}}], + [{user: {active: false, verified: true}}, {user: {active: false, verified: true, ok: false}}], + ], +} + +{ + name: "an or-group assertion over optional relationships", + policy: { + models: {applicant: {income: "number", cosigner: "person?"}, person: {income: "number"}}, + blocks: [{assertion: "applicant.qualifies", conditions: [ + ["or", "applicant.income >= 50000"], + ["and", "(applicant.cosigner.income ?? 0) >= 50000"], + ]}], + }, + cases: [ + [{applicant: {income: 60000}}, {applicant: {income: 60000, qualifies: true}}], + [{applicant: {income: 10000}}, {applicant: {income: 10000, qualifies: false}}], + [{applicant: {income: 10000, cosigner: {income: 70000}}}, {applicant: {income: 10000, cosigner: {income: 70000}, qualifies: true}}], + [{applicant: {income: 10000, cosigner: {income: 100}}}, {applicant: {income: 10000, cosigner: {income: 100}, qualifies: false}}], + [{applicant: {income: 10000, cosigner: null}}, {applicant: {income: 10000, cosigner: null, qualifies: false}}], + ], +} + +{ + name: "a per-member assertion over optional member values", + policy: { + models: {batch: {parcels: "parcel[]"}, parcel: {weight: "number", insured: "boolean?", value: "number?"}}, + blocks: [ + {assertion: "parcel.ready", conditions: ["parcel.weight <= 30", "(parcel.value ?? 0) < 1000 or parcel.insured == true"]}, + {expression: "batch.allReady", value: "all(batch.parcels, #.ready)"}, + ], + }, + cases: [ + [{batch: {parcels: []}}, {batch: {parcels: [], allReady: true}}], + [ + {batch: {parcels: [{weight: 5}, {weight: 10, value: 5000, insured: true}]}}, + {batch: {parcels: [{weight: 5, ready: true}, {weight: 10, value: 5000, insured: true, ready: true}], allReady: true}}, + ], + [ + {batch: {parcels: [{weight: 5, value: 5000}, {weight: 31}]}}, + {batch: {parcels: [{weight: 5, value: 5000, ready: false}, {weight: 31, ready: false}], allReady: false}}, + ], + ], +} + +// --------------------------------------------------------------------------------------------- +// Null checks do not narrow types. A `!= null` guard joined with `and` (or a ternary) still leaves +// the optional nullable for the type checker, so the policy carries TYPE_MISMATCH and only the +// workspace path evaluates it; at runtime the guard works. + +{ + name: "an and-guard before an ordering comparison", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {score: "number?"}}, + blocks: [{expression: "customer.high", value: "customer.score != null and customer.score > 700"}], + }, + cases: [ + {input: {customer: {score: 800}}, output: {customer: {score: 800, high: true}}, note: "question: `score != null and score > 700` is reported as TYPE_MISMATCH although the guard makes the comparison safe, so DecisionEngine refuses the policy"}, + [{customer: {score: 600}}, {customer: {score: 600, high: false}}], + [{customer: {}}, {customer: {high: false}}], + [{customer: {score: null}}, {customer: {score: null, high: false}}], + ], +} + +{ + name: "a guard through an optional relationship", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {customer: {report: "creditReport?"}, creditReport: {score: "number"}}, + blocks: [{expression: "customer.band", value: "customer.report == null ? 'none' : customer.report.score >= 700 ? 'good' : 'poor'"}], + }, + cases: [ + [{customer: {}}, {customer: {band: "none"}}], + [{customer: {report: null}}, {customer: {report: null, band: "none"}}], + [{customer: {report: {score: 700}}}, {customer: {report: {score: 700}, band: "good"}}], + [{customer: {report: {score: 699}}}, {customer: {report: {score: 699}, band: "poor"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// A realistic combination: insurance quote where most of the profile is optional. + +{ + name: "insurance quote with a sparse profile", + policy: { + globals: {rates: {baseRate: "number", smokerLoading: "number?"}}, + models: { + quote: {driver: "driver", vehicle: "vehicle?", previousClaims: "claim[]?"}, + driver: {age: "number", smoker: "boolean?", licenceYears: "number?"}, + vehicle: {value: "number?"}, + claim: {amount: "number"}, + }, + blocks: [ + {expression: "quote.claimTotal", value: "sum(map(quote.previousClaims ?? [], #.amount))"}, + {match: "quote.ageFactor", arms: [ + ["quote.driver.age < 25", "1.5"], + ["(quote.driver.licenceYears ?? 0) < 3", "1.2"], + ["", "1"], + ]}, + {expression: "quote.smokerFactor", value: "(quote.driver.smoker ?? false) ? 1 + (smokerLoading ?? 0.1) : 1"}, + {expression: "quote.premium", value: "round(baseRate * quote.ageFactor * quote.smokerFactor + (quote.vehicle.value ?? 0) * 0.01 + quote.claimTotal * 0.05, 2)"}, + ], + }, + cases: [ + [ + {baseRate: 500, quote: {driver: {age: 40, licenceYears: 20}}}, + {baseRate: 500, quote: {driver: {age: 40, licenceYears: 20}, claimTotal: 0, ageFactor: 1, smokerFactor: 1, premium: 500}}, + ], + [ + {baseRate: 500, quote: {driver: {age: 22}, vehicle: {value: 20000}, previousClaims: [{amount: 1000}]}}, + {baseRate: 500, quote: {driver: {age: 22}, vehicle: {value: 20000}, previousClaims: [{amount: 1000}], claimTotal: 1000, ageFactor: 1.5, smokerFactor: 1, premium: 1000}}, + ], + [ + {baseRate: 500, smokerLoading: 0.3, quote: {driver: {age: 30, smoker: true}, vehicle: {}}}, + {baseRate: 500, smokerLoading: 0.3, quote: {driver: {age: 30, smoker: true}, vehicle: {}, claimTotal: 0, ageFactor: 1.2, smokerFactor: 1.3, premium: 780}}, + ], + [ + {baseRate: 500, quote: {driver: {age: 30, smoker: true, licenceYears: 5}, vehicle: null, previousClaims: null}}, + {baseRate: 500, quote: {driver: {age: 30, smoker: true, licenceYears: 5}, vehicle: null, previousClaims: null, claimTotal: 0, ageFactor: 1, smokerFactor: 1.1, premium: 550}}, + ], + [{baseRate: 500, quote: {}}, "!error: MissingRequiredInputs"], + [{quote: {driver: {age: 30}}}, "!error: MissingRequiredInputs"], + ], +} diff --git a/core/engine/tests/spec/policy/30-imports-composition.json5 b/core/engine/tests/spec/policy/30-imports-composition.json5 new file mode 100644 index 00000000..40e2c6d5 --- /dev/null +++ b/core/engine/tests/spec/policy/30-imports-composition.json5 @@ -0,0 +1,829 @@ +// Composition across imports. Chapter 13 pins the basics of one unit (single imports, chains, +// diamonds, missing and circular imports). This chapter composes larger units: data models +// assembled from several policies, computed properties threaded through three or more +// policies, conflicting writers and declarations across imports, and dictionaries and globals +// that live in an imported policy but are used elsewhere in the unit. + +// --- Shared models: one entity assembled from several policies --------------------------------- + +// Three policies each declare a slice of `customer`; the importer sees the union and every +// slice is validated. +{ + name: "an entity assembled from three imported slices", + policy: { + imports: ["identity", "finance", "contact"], + blocks: [{expression: "customer.summary", value: "customer.name + ':' + string(customer.income) + ':' + customer.email"}], + }, + policies: { + identity: {models: {customer: {name: "string"}}, blocks: []}, + finance: {models: {customer: {income: "number"}}, blocks: []}, + contact: {models: {customer: {email: "string"}}, blocks: []}, + }, + cases: [ + [{customer: {name: "a", income: 10, email: "a@x"}}, {customer: {name: "a", income: 10, email: "a@x", summary: "a:10:a@x"}}], + [{customer: {name: "", income: 0, email: ""}}, {customer: {name: "", income: 0, email: "", summary: ":0:"}}], + [{customer: {name: "a", income: "10", email: "a@x"}}, "!error: InputValidationFailed"], + [{customer: {name: 1, income: 10, email: "a@x"}}, "!error: InputValidationFailed"], + [{customer: {name: "a", income: 10, email: false}}, "!error: InputValidationFailed"], + [{customer: {name: "a", income: 10}}, "!error: MissingRequiredInputs"], + [{customer: {income: 10}}, "!error: missing: [\"customer.email\", \"customer.name\"]"], + ], +} + +// A slice declared only in a policy deep in the chain still validates input for the root. +{ + name: "a model slice declared three imports deep validates the root's input", + policy: { + imports: ["l1"], + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.next", value: "customer.age + 1"}], + }, + policies: { + l1: {imports: ["l2"], blocks: []}, + l2: {imports: ["l3"], blocks: []}, + l3: {models: {customer: {vip: "boolean", tags: "string[]"}}, blocks: []}, + }, + cases: [ + [{customer: {age: 1}}, {customer: {age: 1, next: 2}}], + [{customer: {age: 1, vip: true, tags: ["a"]}}, {customer: {age: 1, vip: true, tags: ["a"], next: 2}}], + [{customer: {age: 1, vip: "yes"}}, "!error: InputValidationFailed"], + [{customer: {age: 1, tags: "a"}}, "!error: InputValidationFailed"], + [{customer: {age: 1, tags: [1]}}, "!error: InputValidationFailed"], + [{customer: {age: 1, tags: []}}, {customer: {age: 1, tags: [], next: 2}}], + ], +} + +// The same property declared identically in every member is one property. +{ + name: "an identical property declared in every member merges without conflict", + policy: { + imports: ["a", "b"], + models: {order: {amount: "number"}}, + blocks: [{expression: "order.total", value: "order.fromA + order.fromB"}], + }, + policies: { + a: {models: {order: {amount: "number"}}, blocks: [{expression: "order.fromA", value: "order.amount * 2"}]}, + b: {models: {order: {amount: "number"}}, blocks: [{expression: "order.fromB", value: "order.amount + 1"}]}, + }, + cases: [ + [{order: {amount: 3}}, {order: {amount: 3, fromA: 6, fromB: 4, total: 10}}], + [{order: {amount: 0}}, {order: {amount: 0, fromA: 0, fromB: 1, total: 1}}], + [{order: {amount: -0.5}}, {order: {amount: -0.5, fromA: -1, fromB: 0.5, total: -0.5}}], + [{order: {amount: "3"}}, "!error: InputValidationFailed"], + [{order: {}}, "!error: MissingRequiredInputs"], + ], +} + +// A relationship declared in one policy, its target entity declared in another, and the +// per-member blocks living in a third. +{ + name: "a relationship and its target entity come from different imports", + policy: { + imports: ["owner", "companyModel", "companyRules"], + blocks: [{expression: "customer.bigNames", value: "map(filter(customer.companies, #.big), #.name)"}], + }, + policies: { + owner: {models: {customer: {companies: "company[]"}}, blocks: []}, + companyModel: {models: {company: {name: "string", revenue: "number"}}, blocks: []}, + companyRules: {imports: ["companyModel"], blocks: [{expression: "company.big", value: "company.revenue >= 100"}]}, + }, + cases: [ + [{customer: {companies: [{name: "a", revenue: 5}, {name: "b", revenue: 100}]}}, {customer: {bigNames: ["b"], companies: [{name: "a", revenue: 5, big: false}, {name: "b", revenue: 100, big: true}]}}], + [{customer: {companies: []}}, {customer: {bigNames: [], companies: []}}], + [{customer: {companies: [{name: "c", revenue: 1000}]}}, {customer: {bigNames: ["c"], companies: [{name: "c", revenue: 1000, big: true}]}}], + [{customer: {companies: [{name: "c", revenue: "1000"}]}}, "!error: InputValidationFailed"], + [{customer: {companies: [{name: 5, revenue: 1}]}}, "!error: InputValidationFailed"], + ], +} + +// A reference property declared in an import resolves an id against the pool of an entity +// declared in the importer. +{ + name: "a reference declared in an import targets an entity of the importer", + policy: { + imports: ["orders"], + models: {product: {id: "string", price: "number"}}, + blocks: [{expression: "order.cost", value: "order.qty * order.item.price"}], + }, + policies: { + orders: {models: {order: {qty: "number", item: "&product"}}, blocks: []}, + }, + cases: [ + { + input: {product: [{id: "p1", price: 10}, {id: "p2", price: 2.5}], order: {qty: 3, item: "p2"}}, + output: {product: [{id: "p1", price: 10}, {id: "p2", price: 2.5}], order: {qty: 3, item: {id: "p2", price: 2.5}, cost: 7.5}}, + }, + { + input: {product: [{id: "p1", price: 10}], order: {qty: 0, item: "p1"}}, + output: {product: [{id: "p1", price: 10}], order: {qty: 0, item: {id: "p1", price: 10}, cost: 0}}, + }, + {input: {product: [{id: "p1", price: 10}], order: {qty: 1, item: "p9"}}, output: "!error: InputValidationFailed"}, + {input: {product: [{id: "p1", price: 10}], order: {qty: 1, item: 5}}, output: "!error: InputValidationFailed"}, + {input: {order: {qty: 1, item: "p1"}}, output: "!error: InputValidationFailed"}, + ], +} + +// --- Shared models: conflicting declarations --------------------------------------------------- + +{ + name: "a property declared with different types in two imports", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + imports: ["a", "b"], + blocks: [{expression: "customer.copy", value: "customer.code"}], + }, + policies: { + a: {models: {customer: {code: "string"}}, blocks: []}, + b: {models: {customer: {code: "number"}}, blocks: []}, + }, + cases: [ + {input: {customer: {code: "x"}}, output: {customer: {code: "x", copy: "x"}}, note: "question: DataModelCollision is an error diagnostic; the declaration from the policy path that sorts first validates"}, + {input: {customer: {code: 5}}, output: "!error: InputValidationFailed", note: "question: DataModelCollision is an error diagnostic; the declaration from the policy path that sorts first validates"}, + ], +} + +{ + name: "a property required in one import and optional in another", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + imports: ["strict", "loose"], + blocks: [{expression: "customer.label", value: "customer.nick ?? 'none'"}], + }, + policies: { + strict: {models: {customer: {nick: "string"}}, blocks: []}, + loose: {models: {customer: {nick: "string?"}}, blocks: []}, + }, + cases: [ + {input: {customer: {nick: "a"}}, output: {customer: {nick: "a", label: "a"}}}, + {input: {customer: {}}, output: {customer: {label: "none"}}, note: "question: DataModelCollision is an error diagnostic; the optional declaration from 'loose' (sorts first) wins over the required one"}, + {input: {customer: {nick: 1}}, output: "!error: InputValidationFailed"}, + ], +} + +{ + name: "a property declared as an array in one import and a scalar in another", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + imports: ["one", "many"], + blocks: [{expression: "customer.n", value: "1"}], + }, + policies: { + one: {models: {customer: {tag: "string"}}, blocks: []}, + many: {models: {customer: {tag: "string[]"}}, blocks: []}, + }, + cases: [ + {input: {customer: {tag: "a"}}, output: "!error: InputValidationFailed", note: "question: DataModelCollision is an error diagnostic; the array declaration from 'many' (sorts first) validates, not the first import"}, + {input: {customer: {tag: ["a"]}}, output: {customer: {tag: ["a"], n: 1}}, note: "question: DataModelCollision is an error diagnostic; the array declaration from 'many' (sorts first) validates, not the first import"}, + {input: {customer: {}}, output: {customer: {n: 1}}}, + ], +} + +{ + name: "enum values declared differently in two imports", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + imports: ["a", "b"], + blocks: [{expression: "customer.isA", value: "customer.tier == 'a'"}], + }, + policies: { + a: {models: {customer: {tier: "string(a|b)"}}, blocks: []}, + b: {models: {customer: {tier: "string(a|c)"}}, blocks: []}, + }, + cases: [ + {input: {customer: {tier: "a"}}, output: {customer: {tier: "a", isA: true}}}, + {input: {customer: {tier: "b"}}, output: {customer: {tier: "b", isA: false}}, note: "question: DataModelCollision is an error diagnostic; the enum of 'a' (sorts first) validates, the values are not merged"}, + {input: {customer: {tier: "c"}}, output: "!error: InputValidationFailed", note: "question: DataModelCollision is an error diagnostic; the enum of 'a' (sorts first) validates, the values are not merged"}, + ], +} + +// An entity name in one import colliding with a global property name in another. +{ + name: "an entity named like a global property of another import", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + imports: ["entities", "settings"], + blocks: [{expression: "out", value: "1"}], + }, + policies: { + entities: {models: {rate: {value: "number"}}, blocks: []}, + settings: {globals: {platform: {rate: "number"}}, blocks: []}, + }, + cases: [ + {input: {rate: 5}, output: "!error: InputValidationFailed", note: "question: DataModelCollision is an error diagnostic; `rate` validates as the entity"}, + {input: {rate: {value: 5}}, output: {rate: {value: 5}, out: 1}, note: "question: DataModelCollision is an error diagnostic; `rate` validates as the entity and the global declaration is ignored"}, + ], +} + +// --- Computed chains across three or more policies --------------------------------------------- + +{ + name: "a five-policy chain, each level adding one computed property", + policy: { + imports: ["p4"], + blocks: [{expression: "o.p5", value: "o.p4 + 1"}], + }, + policies: { + p4: {imports: ["p3"], blocks: [{expression: "o.p4", value: "o.p3 * 2"}]}, + p3: {imports: ["p2"], blocks: [{expression: "o.p3", value: "o.p2 - 3"}]}, + p2: {imports: ["p1"], blocks: [{expression: "o.p2", value: "o.p1 / 2"}]}, + p1: {models: {o: {x: "number"}}, blocks: [{expression: "o.p1", value: "o.x * 10"}]}, + }, + cases: [ + [{o: {x: 1}}, {o: {x: 1, p1: 10, p2: 5, p3: 2, p4: 4, p5: 5}}], + [{o: {x: 0}}, {o: {x: 0, p1: 0, p2: 0, p3: -3, p4: -6, p5: -5}}], + [{o: {x: 0.3}}, {o: {x: 0.3, p1: 3, p2: 1.5, p3: -1.5, p4: -3, p5: -2}}], + [{o: {x: -2}}, {o: {x: -2, p1: -20, p2: -10, p3: -13, p4: -26, p5: -25}}], + [{o: {}}, "!error: MissingRequiredInputs"], + [{o: {x: "1"}}, "!error: InputValidationFailed"], + ], +} + +// The chain runs backwards: the root writes the base value and the deepest import consumes the +// value computed by its importers. Reads resolve across the unit regardless of import direction. +{ + name: "a chain whose data flows against the import direction", + policy: { + imports: ["mid"], + models: {o: {x: "number"}}, + blocks: [{expression: "o.a", value: "o.x + 1"}], + }, + policies: { + mid: {imports: ["leaf"], blocks: [{expression: "o.b", value: "o.a * 2"}]}, + leaf: {blocks: [{expression: "o.c", value: "o.b * 3"}]}, + }, + cases: [ + [{o: {x: 1}}, {o: {x: 1, a: 2, b: 4, c: 12}}], + [{o: {x: -1}}, {o: {x: -1, a: 0, b: 0, c: 0}}], + [{o: {x: 0.5}}, {o: {x: 0.5, a: 1.5, b: 3, c: 9}}], + [{o: {}}, "!error: MissingRequiredInputs"], + ], +} + +// Each policy in the chain uses a different block kind. +{ + name: "a chain of table, match, assertion and expression in four policies", + policy: { + imports: ["decide"], + blocks: [{expression: "loan.message", value: "loan.approved ? 'approved at ' + string(loan.rate) : 'declined (' + loan.risk + ')'"}], + }, + policies: { + decide: {imports: ["rate"], blocks: [{assertion: "loan.approved", conditions: ["loan.risk != 'high'", "loan.rate < 0.2"]}]}, + rate: {imports: ["risk"], blocks: [{match: "loan.rate", arms: [["loan.risk == 'low'", "0.05"], ["loan.risk == 'medium'", "0.1"], ["", "0.25"]]}]}, + risk: { + models: {loan: {score: "number", amount: "number"}}, + blocks: [{table: "riskTable", inputs: ["loan.score", "loan.amount"], outputs: ["loan.risk"], rules: [ + [">= 700", "< 100000", "'low'"], + [">= 600", "", "'medium'"], + ["", "", "'high'"], + ]}], + }, + }, + cases: [ + [{loan: {score: 750, amount: 5000}}, {loan: {score: 750, amount: 5000, risk: "low", rate: 0.05, approved: true, message: "approved at 0.05"}}], + [{loan: {score: 750, amount: 200000}}, {loan: {score: 750, amount: 200000, risk: "medium", rate: 0.1, approved: true, message: "approved at 0.1"}}], + [{loan: {score: 650, amount: 1}}, {loan: {score: 650, amount: 1, risk: "medium", rate: 0.1, approved: true, message: "approved at 0.1"}}], + [{loan: {score: 500, amount: 1}}, {loan: {score: 500, amount: 1, risk: "high", rate: 0.25, approved: false, message: "declined (high)"}}], + [{loan: {score: 700, amount: 100000}}, {loan: {score: 700, amount: 100000, risk: "medium", rate: 0.1, approved: true, message: "approved at 0.1"}}], + [{loan: {score: 700}}, "!error: MissingRequiredInputs"], + ], +} + +// Per-member computed values chained through three policies, aggregated by the root. +{ + name: "per-member values chained across three policies and aggregated at the root", + policy: { + imports: ["net"], + blocks: [ + {expression: "invoice.total", value: "sum(map(invoice.lines, #.net))"}, + {expression: "invoice.count", value: "len(invoice.lines)"}, + ], + }, + policies: { + net: {imports: ["gross"], blocks: [{expression: "line.net", value: "line.gross - line.discount"}]}, + gross: {imports: ["model"], blocks: [ + {expression: "line.gross", value: "line.qty * line.price"}, + {expression: "line.discount", value: "line.gross > 100 ? line.gross * 0.1 : 0"}, + ]}, + model: {models: {invoice: {lines: "line[]"}, line: {qty: "number", price: "number"}}, blocks: []}, + }, + cases: [ + [ + {invoice: {lines: [{qty: 2, price: 10}, {qty: 1, price: 200}]}}, + {invoice: {total: 200, count: 2, lines: [{qty: 2, price: 10, gross: 20, discount: 0, net: 20}, {qty: 1, price: 200, gross: 200, discount: 20, net: 180}]}}, + ], + [{invoice: {lines: []}}, {invoice: {total: 0, count: 0, lines: []}}], + [ + {invoice: {lines: [{qty: 0, price: 1000}]}}, + {invoice: {total: 0, count: 1, lines: [{qty: 0, price: 1000, gross: 0, discount: 0, net: 0}]}}, + ], + [ + {invoice: {lines: [{qty: 3, price: 33.34}]}}, + {invoice: {total: 90.018, count: 1, lines: [{qty: 3, price: 33.34, gross: 100.02, discount: 10.002, net: 90.018}]}}, + ], + [{invoice: {lines: [{qty: 1}]}}, "!error: ExpressionFailed"], + [{invoice: {lines: [{qty: 1, price: "1"}]}}, "!error: InputValidationFailed"], + ], +} + +// An aggregate computed in one policy flows back into per-member blocks of another. +{ + name: "an aggregate from one import feeds per-member shares in another", + policy: { + imports: ["share"], + blocks: [{expression: "team.check", value: "sum(map(team.members, #.share))"}], + }, + policies: { + share: {imports: ["totals"], blocks: [{expression: "member.share", value: "team.total == 0 ? 0 : member.points / team.total"}]}, + totals: { + models: {team: {members: "member[]"}, member: {points: "number"}}, + blocks: [{expression: "team.total", value: "sum(map(team.members, #.points))"}], + }, + }, + cases: [ + [{team: {members: [{points: 1}, {points: 3}]}}, {team: {total: 4, check: 1, members: [{points: 1, share: 0.25}, {points: 3, share: 0.75}]}}], + [{team: {members: [{points: 0}, {points: 0}]}}, {team: {total: 0, check: 0, members: [{points: 0, share: 0}, {points: 0, share: 0}]}}], + [{team: {members: []}}, {team: {total: 0, check: 0, members: []}}], + [{team: {members: [{points: 5}]}}, {team: {total: 5, check: 1, members: [{points: 5, share: 1}]}}], + ], +} + +// Nested computed write paths built up by three different policies. +{ + name: "a nested result object assembled by three policies", + policy: { + imports: ["taxes", "fees"], + blocks: [{expression: "result.summary.grand", value: "result.lines.net + result.lines.tax + result.lines.fee"}], + }, + policies: { + taxes: {imports: ["base"], blocks: [{expression: "result.lines.tax", value: "result.lines.net * 0.2"}]}, + fees: {imports: ["base"], blocks: [{expression: "result.lines.fee", value: "result.lines.net > 100 ? 0 : 5"}]}, + base: {models: {order: {amount: "number"}}, blocks: [{expression: "result.lines.net", value: "order.amount"}]}, + }, + cases: [ + [{order: {amount: 100}}, {order: {amount: 100}, result: {lines: {net: 100, tax: 20, fee: 5}, summary: {grand: 125}}}], + [{order: {amount: 200}}, {order: {amount: 200}, result: {lines: {net: 200, tax: 40, fee: 0}, summary: {grand: 240}}}], + [{order: {amount: 0}}, {order: {amount: 0}, result: {lines: {net: 0, tax: 0, fee: 5}, summary: {grand: 5}}}], + [{order: {}}, "!error: MissingRequiredInputs"], + ], +} + +// A diamond whose two branches are themselves chains, joined at the root. +{ + name: "a deep diamond: two two-level branches over one base", + policy: { + imports: ["left2", "right2"], + blocks: [{expression: "x.join", value: "x.l2 + ':' + x.r2"}], + }, + policies: { + left2: {imports: ["left1"], blocks: [{expression: "x.l2", value: "upper(x.l1)"}]}, + left1: {imports: ["base"], blocks: [{expression: "x.l1", value: "x.word + 'l'"}]}, + right2: {imports: ["right1"], blocks: [{expression: "x.r2", value: "string(x.r1 * 2)"}]}, + right1: {imports: ["base"], blocks: [{expression: "x.r1", value: "len(x.word)"}]}, + base: {models: {x: {name: "string"}}, blocks: [{expression: "x.word", value: "trim(x.name)"}]}, + }, + cases: [ + [{x: {name: " ab "}}, {x: {name: " ab ", word: "ab", l1: "abl", l2: "ABL", r1: 2, r2: "4", join: "ABL:4"}}], + [{x: {name: ""}}, {x: {name: "", word: "", l1: "l", l2: "L", r1: 0, r2: "0", join: "L:0"}}], + [{x: {name: "Zed"}}, {x: {name: "Zed", word: "Zed", l1: "Zedl", l2: "ZEDL", r1: 3, r2: "6", join: "ZEDL:6"}}], + [{x: {name: 1}}, "!error: InputValidationFailed"], + ], +} + +// Every policy of a chain contributes a terminal write that nobody reads; all of them run. +{ + name: "terminal writes at every level of a chain all run", + policy: { + imports: ["mid"], + blocks: [ + {expression: "c.rootOnly", value: "c.v * 1000"}, + {expression: "c.uses", value: "c.midValue + c.baseValue"}, + ], + }, + policies: { + mid: {imports: ["base"], blocks: [ + {expression: "c.midValue", value: "c.v * 10"}, + {expression: "c.midOnly", value: "c.v > 0"}, + ]}, + base: {models: {c: {v: "number"}}, blocks: [ + {expression: "c.baseValue", value: "c.v"}, + {expression: "c.baseOnly", value: "'base'"}, + ]}, + }, + cases: [ + [{c: {v: 1}}, {c: {v: 1, baseValue: 1, baseOnly: "base", midValue: 10, midOnly: true, rootOnly: 1000, uses: 11}}], + [{c: {v: 0}}, {c: {v: 0, baseValue: 0, baseOnly: "base", midValue: 0, midOnly: false, rootOnly: 0, uses: 0}}], + [{c: {v: -1}}, {c: {v: -1, baseValue: -1, baseOnly: "base", midValue: -10, midOnly: false, rootOnly: -1000, uses: -11}}], + ], +} + +// --- Duplicate writers across imports ---------------------------------------------------------- + +{ + name: "two sibling imports writing the same property", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + imports: ["a", "b"], + models: {c: {v: "number"}}, + blocks: [{expression: "c.read", value: "c.score + 1"}], + }, + policies: { + a: {blocks: [{expression: "c.score", value: "c.v * 2"}]}, + b: {blocks: [{expression: "c.score", value: "c.v * 3"}]}, + }, + cases: [ + {input: {c: {v: 1}}, output: {c: {v: 1, score: 2, read: 3}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the writer from the policy path that sorts first"}, + {input: {c: {v: 10}}, output: {c: {v: 10, score: 20, read: 21}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the writer from the policy path that sorts first"}, + ], +} + +// Swapping the import order of the two writers does not change which writer is kept. +{ + name: "two sibling imports writing the same property, imported in the other order", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + imports: ["b", "a"], + models: {c: {v: "number"}}, + blocks: [{expression: "c.read", value: "c.score + 1"}], + }, + policies: { + a: {blocks: [{expression: "c.score", value: "c.v * 2"}]}, + b: {blocks: [{expression: "c.score", value: "c.v * 3"}]}, + }, + cases: [ + {input: {c: {v: 1}}, output: {c: {v: 1, score: 2, read: 3}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the writer from the policy path that sorts first"}, + {input: {c: {v: 10}}, output: {c: {v: 10, score: 20, read: 21}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the writer from the policy path that sorts first"}, + ], +} + +{ + name: "a writer deep in a chain duplicated by the root", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + imports: ["mid"], + blocks: [{expression: "c.flag", value: "'root'"}], + }, + policies: { + mid: {imports: ["leaf"], blocks: [{expression: "c.copy", value: "c.flag"}]}, + leaf: {models: {c: {v: "number"}}, blocks: [{expression: "c.flag", value: "'leaf'"}]}, + }, + cases: [ + {input: {c: {v: 1}}, output: {c: {v: 1, flag: "leaf", copy: "leaf"}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the deepest import's writer and drops the root's"}, + ], +} + +{ + name: "a table in one import and an expression in another writing the same property", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + imports: ["byTable", "byExpr"], + blocks: [], + }, + policies: { + byTable: {models: {c: {age: "number"}}, blocks: [{table: "t", inputs: ["c.age"], outputs: ["c.band"], rules: [[">= 18", "'adult'"], ["", "'minor'"]]}]}, + byExpr: {models: {c: {age: "number"}}, blocks: [{expression: "c.band", value: "'expr'"}]}, + }, + cases: [ + {input: {c: {age: 20}}, output: {c: {age: 20, band: "expr"}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the writer from 'byExpr' (sorts first)"}, + {input: {c: {age: 5}}, output: {c: {age: 5, band: "expr"}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the writer from 'byExpr' (sorts first)"}, + ], +} + +// Writers of different nested leaves under one object never conflict. +{ + name: "sibling imports writing different leaves of one nested object", + policy: { + imports: ["a", "b", "c"], + models: {o: {n: "number"}}, + blocks: [{expression: "o.total", value: "o.parts.a + o.parts.b + o.parts.c"}], + }, + policies: { + a: {blocks: [{expression: "o.parts.a", value: "o.n"}]}, + b: {blocks: [{expression: "o.parts.b", value: "o.n * 2"}]}, + c: {blocks: [{expression: "o.parts.c", value: "o.n * 3"}]}, + }, + cases: [ + [{o: {n: 1}}, {o: {n: 1, parts: {a: 1, b: 2, c: 3}, total: 6}}], + [{o: {n: 0}}, {o: {n: 0, parts: {a: 0, b: 0, c: 0}, total: 0}}], + [{o: {n: -2.5}}, {o: {n: -2.5, parts: {a: -2.5, b: -5, c: -7.5}, total: -15}}], + ], +} + +// One import writes a whole object while another writes into it. +{ + name: "a whole-object write in one import and a nested write in another", + diagnostics: ["PARTIAL_OBJECT_WRITE"], + policy: { + imports: ["whole", "part"], + models: {o: {n: "number"}}, + blocks: [], + }, + policies: { + whole: {blocks: [{expression: "o.box", value: "{a: o.n}"}]}, + part: {blocks: [{expression: "o.box.b", value: "o.n + 1"}]}, + }, + cases: [ + {input: {o: {n: 1}}, output: {o: {n: 1, box: {b: 2}}}, note: "question: PartialObjectWrite is an error diagnostic ('the whole-object write overwrites the nested writes'), yet the nested write wins and the whole object's `a` is lost"}, + ], +} + +// --- Input overrides across imports ------------------------------------------------------------ + +{ + name: "an import writes a property the importer declares as input", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + imports: ["writer"], + models: {c: {age: "number", band: "string"}}, + blocks: [{expression: "c.label", value: "c.band + '!'"}], + }, + policies: { + writer: {blocks: [{expression: "c.band", value: "c.age >= 18 ? 'adult' : 'minor'"}]}, + }, + cases: [ + {input: {c: {age: 30, band: "given"}}, output: {c: {age: 30, band: "given", label: "given!"}}, note: "question: InputOverride is an error diagnostic; the input value wins and the imported write is dropped"}, + {input: {c: {age: 30}}, output: "!error: MissingRequiredInputs", note: "question: InputOverride is an error diagnostic; the declared property is required input even though an import writes it"}, + ], +} + +{ + name: "the importer writes a property a deep import declares as input", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + imports: ["mid"], + blocks: [{expression: "c.score", value: "c.points * 2"}], + }, + policies: { + mid: {imports: ["leaf"], blocks: [{expression: "c.doubled", value: "c.score + 1"}]}, + leaf: {models: {c: {points: "number", score: "number"}}, blocks: []}, + }, + cases: [ + {input: {c: {points: 5, score: 1}}, output: {c: {points: 5, score: 1, doubled: 2}}, note: "question: InputOverride is an error diagnostic; the input value wins over the root's write"}, + {input: {c: {points: 5}}, output: "!error: MissingRequiredInputs", note: "question: InputOverride is an error diagnostic; the declared property is required input"}, + ], +} + +// --- Globals from imports ------------------------------------------------------------------- + +// A global model split across two imports; every part validates and both are readable. +{ + name: "a global model split across two imports", + policy: { + imports: ["rates", "limits"], + models: {order: {amount: "number"}}, + blocks: [{expression: "order.charge", value: "min([order.amount * taxRate, maxCharge])"}], + }, + policies: { + rates: {globals: {platform: {taxRate: "number"}}, blocks: []}, + limits: {globals: {platform: {maxCharge: "number"}}, blocks: []}, + }, + cases: [ + [{taxRate: 0.1, maxCharge: 50, order: {amount: 100}}, {taxRate: 0.1, maxCharge: 50, order: {amount: 100, charge: 10}}], + [{taxRate: 0.1, maxCharge: 5, order: {amount: 100}}, {taxRate: 0.1, maxCharge: 5, order: {amount: 100, charge: 5}}], + [{taxRate: 0, maxCharge: 0, order: {amount: 0}}, {taxRate: 0, maxCharge: 0, order: {amount: 0, charge: 0}}], + [{taxRate: "0.1", maxCharge: 5, order: {amount: 1}}, "!error: InputValidationFailed"], + [{taxRate: 0.1, maxCharge: true, order: {amount: 1}}, "!error: InputValidationFailed"], + [{taxRate: 0.1, order: {amount: 1}}, "!error: MissingRequiredInputs"], + ], +} + +// A global computed in one import, read by entity blocks in another import and by the root. +{ + name: "a global computed in one import feeds blocks in two other policies", + policy: { + imports: ["rate", "orders"], + blocks: [{expression: "summary", value: "order.net > 85 ? 'high' : 'low'"}], + }, + policies: { + rate: {globals: {settings: {baseRate: "number", promo: "boolean"}}, blocks: [{expression: "effectiveRate", value: "promo ? baseRate / 2 : baseRate"}]}, + orders: {models: {order: {amount: "number"}}, blocks: [{expression: "order.net", value: "order.amount * (1 - effectiveRate)"}]}, + }, + cases: [ + [{baseRate: 0.2, promo: false, order: {amount: 100}}, {baseRate: 0.2, promo: false, effectiveRate: 0.2, order: {amount: 100, net: 80}, summary: "low"}], + [{baseRate: 0.2, promo: true, order: {amount: 100}}, {baseRate: 0.2, promo: true, effectiveRate: 0.1, order: {amount: 100, net: 90}, summary: "high"}], + [{baseRate: 0, promo: true, order: {amount: 7}}, {baseRate: 0, promo: true, effectiveRate: 0, order: {amount: 7, net: 7}, summary: "low"}], + [{baseRate: 0.2, order: {amount: 100}}, "!error: MissingRequiredInputs"], + [{baseRate: 0.2, promo: "no", order: {amount: 100}}, "!error: InputValidationFailed"], + ], +} + +// A global array of entities declared in one import; per-member blocks in another. +{ + name: "a global relationship from one import with member blocks in another", + policy: { + imports: ["catalog", "flags"], + blocks: [{expression: "cheapCount", value: "count(products, #.cheap)"}], + }, + policies: { + catalog: {globals: {store: {products: "product[]"}}, models: {product: {price: "number"}}, blocks: []}, + flags: {imports: ["catalog"], blocks: [{expression: "product.cheap", value: "product.price < 10"}]}, + }, + cases: [ + [{products: [{price: 5}, {price: 50}]}, {products: [{price: 5, cheap: true}, {price: 50, cheap: false}], cheapCount: 1}], + [{products: []}, {products: [], cheapCount: 0}], + [{products: [{price: 9.99}, {price: 10}, {price: 0}]}, {products: [{price: 9.99, cheap: true}, {price: 10, cheap: false}, {price: 0, cheap: true}], cheapCount: 2}], + [{products: [{price: "5"}]}, "!error: InputValidationFailed"], + ], +} + +// An optional global from an import, defaulted by the importer. +{ + name: "an optional global declared in an import", + policy: { + imports: ["settings"], + models: {order: {amount: "number"}}, + blocks: [{expression: "order.total", value: "order.amount + (shipping ?? 0)"}], + }, + policies: { + settings: {globals: {platform: {shipping: "number?"}}, blocks: []}, + }, + cases: [ + [{order: {amount: 10}}, {order: {amount: 10, total: 10}}], + [{shipping: null, order: {amount: 10}}, {shipping: null, order: {amount: 10, total: 10}}], + [{shipping: 4.5, order: {amount: 10}}, {shipping: 4.5, order: {amount: 10, total: 14.5}}], + [{shipping: "4", order: {amount: 10}}, "!error: InputValidationFailed"], + ], +} + +// A global declared twice with the same type in two imports merges. +{ + name: "the same global declared identically in two imports", + policy: { + imports: ["a", "b"], + blocks: [{expression: "both", value: "fromA + fromB"}], + }, + policies: { + a: {globals: {cfg: {factor: "number"}}, blocks: [{expression: "fromA", value: "factor * 2"}]}, + b: {globals: {cfg: {factor: "number"}}, blocks: [{expression: "fromB", value: "factor + 1"}]}, + }, + cases: [ + [{factor: 2}, {factor: 2, fromA: 4, fromB: 3, both: 7}], + [{factor: 0}, {factor: 0, fromA: 0, fromB: 1, both: 1}], + [{factor: "2"}, "!error: InputValidationFailed"], + [{}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "the same global declared with different types in two imports", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + imports: ["a", "b"], + blocks: [{expression: "copy", value: "mode"}], + }, + policies: { + a: {globals: {cfg: {mode: "string"}}, blocks: []}, + b: {globals: {cfg: {mode: "boolean"}}, blocks: []}, + }, + cases: [ + {input: {mode: "x"}, output: {mode: "x", copy: "x"}, note: "question: DataModelCollision is an error diagnostic; the declaration from the policy path that sorts first validates"}, + {input: {mode: true}, output: "!error: InputValidationFailed", note: "question: DataModelCollision is an error diagnostic; the declaration from the policy path that sorts first validates"}, + ], +} + +// --- Dictionaries from imports ----------------------------------------------------------------- + +// A dictionary declared deep in a chain types a property declared by the root. +{ + name: "a dictionary from a deep import types the root's property", + policy: { + imports: ["mid"], + models: {account: {status: "status"}}, + blocks: [{expression: "account.open", value: "account.status == 'A'"}], + }, + policies: { + mid: {imports: ["dicts"], blocks: []}, + dicts: {dictionaries: {status: [["A", "Active"], ["C", "Closed"]]}, blocks: []}, + }, + cases: [ + [{account: {status: "A"}}, {account: {status: "A", open: true}}], + [{account: {status: "C"}}, {account: {status: "C", open: false}}], + [{account: {status: "Active"}}, "!error: InputValidationFailed"], + [{account: {status: "X"}}, "!error: InputValidationFailed"], + [{account: {}}, "!error: MissingRequiredInputs"], + ], +} + +// One dictionary used by properties declared in two different imports. +{ + name: "one dictionary types properties declared in two imports", + policy: { + imports: ["buyer", "seller", "dicts"], + blocks: [{expression: "deal.sameRegion", value: "buyer.region == seller.region"}], + }, + policies: { + buyer: {models: {buyer: {region: "region"}}, blocks: []}, + seller: {models: {seller: {region: "region"}}, blocks: []}, + dicts: {dictionaries: {region: ["EU", "US", "APAC"]}, blocks: []}, + }, + cases: [ + [{buyer: {region: "EU"}, seller: {region: "EU"}}, {buyer: {region: "EU"}, seller: {region: "EU"}, deal: {sameRegion: true}}], + [{buyer: {region: "EU"}, seller: {region: "US"}}, {buyer: {region: "EU"}, seller: {region: "US"}, deal: {sameRegion: false}}], + [{buyer: {region: "EU"}, seller: {region: "LATAM"}}, "!error: InputValidationFailed"], + [{buyer: {region: "eu"}, seller: {region: "EU"}}, "!error: InputValidationFailed"], + ], +} + +// A dictionary-typed global declared in an import, with a table over it in another. +{ + name: "a dictionary-typed global from an import drives a table in another", + policy: { + imports: ["setup", "pricing"], + blocks: [], + }, + policies: { + setup: {dictionaries: {planKind: ["free", "pro", "team"]}, globals: {account: {plan: "planKind"}}, blocks: []}, + pricing: {imports: ["setup"], blocks: [{table: "prices", inputs: ["plan"], outputs: ["price"], rules: [["'free'", "0"], ["'pro'", "10"], ["", "25"]]}]}, + }, + cases: [ + [{plan: "free"}, {plan: "free", price: 0}], + [{plan: "pro"}, {plan: "pro", price: 10}], + [{plan: "team"}, {plan: "team", price: 25}], + [{plan: "enterprise"}, "!error: InputValidationFailed"], + [{}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "the same dictionary declared in two imports", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + imports: ["a", "b"], + models: {c: {tier: "tier"}}, + blocks: [{expression: "c.copy", value: "c.tier"}], + }, + policies: { + a: {dictionaries: {tier: ["gold", "silver"]}, blocks: []}, + b: {dictionaries: {tier: ["gold", "bronze"]}, blocks: []}, + }, + cases: [ + {input: {c: {tier: "gold"}}, output: {c: {tier: "gold", copy: "gold"}}}, + {input: {c: {tier: "silver"}}, output: {c: {tier: "silver", copy: "silver"}}, note: "question: DataModelCollision is an error diagnostic; the dictionary from 'a' (sorts first) validates"}, + {input: {c: {tier: "bronze"}}, output: "!error: InputValidationFailed", note: "question: DataModelCollision is an error diagnostic; the dictionary from 'a' (sorts first) validates"}, + ], +} + +{ + name: "a dictionary in one import named like an entity in another", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + imports: ["dicts", "models"], + blocks: [{expression: "x", value: "1"}], + }, + policies: { + dicts: {dictionaries: {status: ["A", "B"]}, blocks: []}, + models: {models: {status: {code: "string"}}, blocks: []}, + }, + cases: [ + {input: {}, output: {x: 1}}, + {input: {status: {code: "A"}}, output: {status: {code: "A"}, x: 1}}, + ], +} + +// --- Realistic multi-policy workspace ------------------------------------------------------------ + +{ + name: "a shared schema, two rule packs and an orchestrator", + policy: { + imports: ["eligibility", "pricing"], + blocks: [{match: "application.decision", arms: [ + ["not application.eligible", "'reject'"], + ["application.premium > applicant.budget", "'refer'"], + ["", "'accept'"], + ]}], + }, + policies: { + schema: { + dictionaries: {region: ["north", "south"]}, + globals: {platform: {surcharge: "number"}}, + models: {applicant: {age: "number", region: "region", budget: "number"}, application: {coverage: "number"}}, + blocks: [], + }, + eligibility: {imports: ["schema"], blocks: [ + {assertion: "application.eligible", conditions: ["applicant.age >= 18", "applicant.age <= 75", "application.coverage > 0"]}, + ]}, + pricing: {imports: ["schema"], blocks: [ + {table: "base", inputs: ["applicant.region"], outputs: ["application.baseRate"], rules: [["'north'", "0.01"], ["", "0.02"]]}, + {expression: "application.premium", value: "application.coverage * application.baseRate + surcharge"}, + ]}, + }, + cases: [ + [ + {surcharge: 5, applicant: {age: 30, region: "north", budget: 200}, application: {coverage: 10000}}, + {surcharge: 5, applicant: {age: 30, region: "north", budget: 200}, application: {coverage: 10000, eligible: true, baseRate: 0.01, premium: 105, decision: "accept"}}, + ], + [ + {surcharge: 5, applicant: {age: 30, region: "south", budget: 200}, application: {coverage: 10000}}, + {surcharge: 5, applicant: {age: 30, region: "south", budget: 200}, application: {coverage: 10000, eligible: true, baseRate: 0.02, premium: 205, decision: "refer"}}, + ], + [ + {surcharge: 0, applicant: {age: 80, region: "north", budget: 1000}, application: {coverage: 1}}, + {surcharge: 0, applicant: {age: 80, region: "north", budget: 1000}, application: {coverage: 1, eligible: false, baseRate: 0.01, premium: 0.01, decision: "reject"}}, + ], + [ + {surcharge: 0, applicant: {age: 18, region: "south", budget: 0}, application: {coverage: 0}}, + {surcharge: 0, applicant: {age: 18, region: "south", budget: 0}, application: {coverage: 0, eligible: false, baseRate: 0.02, premium: 0, decision: "reject"}}, + ], + [{surcharge: 0, applicant: {age: 18, region: "west", budget: 0}, application: {coverage: 1}}, "!error: InputValidationFailed"], + [{applicant: {age: 18, region: "north", budget: 0}, application: {coverage: 1}}, "!error: MissingRequiredInputs"], + ], +} diff --git a/core/engine/tests/spec/policy/31-goals-advanced.json5 b/core/engine/tests/spec/policy/31-goals-advanced.json5 new file mode 100644 index 00000000..d5984eec --- /dev/null +++ b/core/engine/tests/spec/policy/31-goals-advanced.json5 @@ -0,0 +1,638 @@ +// Advanced request goals. Chapter 14 pins the basics (cones, unions, required-input pruning, +// goal validation). This chapter combines goals with the other features: per-member writes, +// nested write paths, multi-policy units, each block kind as a target, and optional inputs +// that are missing from the request. + +// --- Goals on members --------------------------------------------------------------------------- + +// A member goal runs the member block for every member and nothing that aggregates it. +{ + name: "a member goal whose block reads another member computed value", + policy: { + models: {cart: {items: "item[]", coupon: "string"}, item: {qty: "number", price: "number"}}, + blocks: [ + {expression: "item.gross", value: "item.qty * item.price"}, + {expression: "item.label", value: "string(item.qty) + 'x'"}, + {expression: "item.heavy", value: "item.gross > 100"}, + {expression: "cart.total", value: "sum(map(cart.items, #.gross))"}, + {expression: "cart.code", value: "upper(cart.coupon)"}, + ], + }, + cases: [ + {input: {cart: {items: [{qty: 2, price: 60}, {qty: 1, price: 5}]}}, goals: ["item.heavy"], output: {cart: {items: [{qty: 2, price: 60, gross: 120, heavy: true}, {qty: 1, price: 5, gross: 5, heavy: false}]}}}, + {input: {cart: {items: []}}, goals: ["item.heavy"], output: {cart: {items: []}}}, + {input: {cart: {items: [{qty: 3, price: 1}]}}, goals: ["item.label"], output: {cart: {items: [{qty: 3, price: 1, label: "3x"}]}}}, + {input: {cart: {items: [{qty: 3}]}}, goals: ["item.label"], output: {cart: {items: [{qty: 3, label: "3x"}]}}}, + {input: {cart: {items: [{qty: 2, price: 60}]}}, goals: ["item.heavy", "item.label"], output: {cart: {items: [{qty: 2, price: 60, gross: 120, heavy: true, label: "2x"}]}}}, + {input: {cart: {items: [{qty: 2, price: 60}]}}, goals: ["cart.total"], output: {cart: {total: 120, items: [{qty: 2, price: 60, gross: 120}]}}}, + ], +} + +// A member goal whose member block reads a root-level computed value pulls that value in. +{ + name: "a member goal pulls a parent computed value into its cone", + policy: { + models: {team: {members: "member[]", bonusPool: "number"}, member: {points: "number"}}, + blocks: [ + {expression: "team.totalPoints", value: "sum(map(team.members, #.points))"}, + {expression: "member.bonus", value: "team.totalPoints == 0 ? 0 : team.bonusPool * member.points / team.totalPoints"}, + {expression: "team.size", value: "len(team.members)"}, + ], + }, + cases: [ + {input: {team: {bonusPool: 100, members: [{points: 1}, {points: 3}]}}, goals: ["member.bonus"], output: {team: {bonusPool: 100, totalPoints: 4, members: [{points: 1, bonus: 25}, {points: 3, bonus: 75}]}}}, + {input: {team: {bonusPool: 100, members: [{points: 0}]}}, goals: ["member.bonus"], output: {team: {bonusPool: 100, totalPoints: 0, members: [{points: 0, bonus: 0}]}}}, + {input: {team: {bonusPool: 10, members: []}}, goals: ["member.bonus"], output: {team: {bonusPool: 10, totalPoints: 0, members: []}}}, + {input: {team: {members: [{points: 1}]}}, goals: ["member.bonus"], output: "!error: MissingRequiredInputs"}, + {input: {team: {members: [{points: 1}]}}, goals: ["team.size"], output: {team: {size: 1, members: [{points: 1}]}}}, + {input: {team: {members: [{points: 1}]}}, goals: ["team.totalPoints"], output: {team: {totalPoints: 1, members: [{points: 1}]}}}, + ], +} + +// Goals on members of two different relationships of one owner. +{ + name: "member goals on two relationships of one owner", + policy: { + models: {customer: {companies: "company[]", accounts: "account[]"}, company: {revenue: "number"}, account: {balance: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "account.negative", value: "account.balance < 0"}, + {expression: "customer.risky", value: "some(customer.accounts, #.negative)"}, + ], + }, + cases: [ + {input: {customer: {companies: [{revenue: 500}], accounts: [{balance: -1}]}}, goals: ["company.big"], output: {customer: {companies: [{revenue: 500, big: true}], accounts: [{balance: -1}]}}}, + {input: {customer: {companies: [{revenue: 500}], accounts: [{balance: -1}]}}, goals: ["account.negative"], output: {customer: {companies: [{revenue: 500}], accounts: [{balance: -1, negative: true}]}}}, + {input: {customer: {companies: [{revenue: 5}], accounts: [{balance: 1}]}}, goals: ["company.big", "customer.risky"], output: {customer: {risky: false, companies: [{revenue: 5, big: false}], accounts: [{balance: 1, negative: false}]}}}, + {input: {customer: {companies: [{revenue: 5}]}}, goals: ["company.big"], output: {customer: {companies: [{revenue: 5, big: false}]}}}, + {input: {customer: {accounts: [{balance: 0}]}}, goals: ["account.negative"], output: {customer: {accounts: [{balance: 0, negative: false}]}}}, + ], +} + +// A member goal written by a per-member table and one written by a per-member match. +{ + name: "member goals on a per-member table and a per-member match", + policy: { + models: {order: {lines: "line[]"}, line: {qty: "number", sku: "string"}}, + blocks: [ + {table: "band", inputs: ["line.qty"], outputs: ["line.band"], rules: [[">= 100", "'bulk'"], [">= 10", "'pack'"], ["", "'unit'"]]}, + {match: "line.kind", arms: [["startsWith(line.sku, 'X')", "'special'"], ["", "'normal'"]]}, + {expression: "order.bulkCount", value: "count(order.lines, #.band == 'bulk')"}, + ], + }, + cases: [ + {input: {order: {lines: [{qty: 150, sku: "A1"}, {qty: 1, sku: "X2"}]}}, goals: ["line.band"], output: {order: {lines: [{qty: 150, sku: "A1", band: "bulk"}, {qty: 1, sku: "X2", band: "unit"}]}}}, + {input: {order: {lines: [{qty: 150, sku: "A1"}, {qty: 1, sku: "X2"}]}}, goals: ["line.kind"], output: {order: {lines: [{qty: 150, sku: "A1", kind: "normal"}, {qty: 1, sku: "X2", kind: "special"}]}}}, + {input: {order: {lines: [{qty: 10}]}}, goals: ["line.band"], output: {order: {lines: [{qty: 10, band: "pack"}]}}}, + {input: {order: {lines: [{sku: "X"}]}}, goals: ["line.kind"], output: {order: {lines: [{sku: "X", kind: "special"}]}}}, + {input: {order: {lines: [{qty: 100, sku: "A"}, {qty: 99, sku: "B"}]}}, goals: ["order.bulkCount"], output: {order: {bulkCount: 1, lines: [{qty: 100, sku: "A", band: "bulk"}, {qty: 99, sku: "B", band: "pack"}]}}}, + ], +} + +// A goal on a member property of a global relationship. +{ + name: "a member goal on a global relationship", + policy: { + globals: {store: {products: "product[]", discount: "number"}}, + models: {product: {price: "number"}}, + blocks: [ + {expression: "product.final", value: "product.price * (1 - discount)"}, + {expression: "product.cheap", value: "product.price < 10"}, + {expression: "catalogValue", value: "sum(map(products, #.final))"}, + ], + }, + cases: [ + {input: {discount: 0.5, products: [{price: 10}, {price: 3}]}, goals: ["product.final"], output: {discount: 0.5, products: [{price: 10, final: 5}, {price: 3, final: 1.5}]}}, + {input: {products: [{price: 10}, {price: 3}]}, goals: ["product.cheap"], output: {products: [{price: 10, cheap: false}, {price: 3, cheap: true}]}}, + {input: {products: [{price: 10}]}, goals: ["product.final"], output: "!error: MissingRequiredInputs"}, + {input: {discount: 0, products: [{price: 10}, {price: 3}]}, goals: ["catalogValue"], output: {discount: 0, products: [{price: 10, final: 10}, {price: 3, final: 3}], catalogValue: 13}}, + {input: {discount: 0, products: []}, goals: ["catalogValue", "product.cheap"], output: {discount: 0, products: [], catalogValue: 0}}, + ], +} + +// --- Goals on nested paths ---------------------------------------------------------------------- + +// Nested computed paths under an entity: a goal on a leaf, on its parent object, and on a sibling. +{ + name: "goals on nested computed paths under an entity", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.stats.ageBand", value: "customer.age >= 18 ? 'adult' : 'minor'"}, + {expression: "customer.stats.incomeBand", value: "customer.income > 1000 ? 'high' : 'low'"}, + {expression: "customer.flags.vip", value: "customer.stats.incomeBand == 'high'"}, + ], + }, + cases: [ + {input: {customer: {age: 20}}, goals: ["customer.stats.ageBand"], output: {customer: {age: 20, stats: {ageBand: "adult"}}}}, + {input: {customer: {income: 5000}}, goals: ["customer.stats.incomeBand"], output: {customer: {income: 5000, stats: {incomeBand: "high"}}}}, + {input: {customer: {age: 3, income: 5}}, goals: ["customer.stats"], output: {customer: {age: 3, income: 5, stats: {ageBand: "minor", incomeBand: "low"}}}}, + {input: {customer: {income: 5000}}, goals: ["customer.flags.vip"], output: {customer: {income: 5000, stats: {incomeBand: "high"}, flags: {vip: true}}}, note: "bug: reading customer.stats.incomeBand makes the required-input check demand customer.age, the input of the sibling leaf customer.stats.ageBand"}, + {input: {customer: {income: 5000}}, goals: ["customer.flags"], output: {customer: {income: 5000, stats: {incomeBand: "high"}, flags: {vip: true}}}, note: "bug: reading customer.stats.incomeBand makes the required-input check demand customer.age, the input of the sibling leaf customer.stats.ageBand"}, + {input: {customer: {income: 5000, age: 1}}, goals: ["customer.flags.vip"], output: {customer: {income: 5000, age: 1, stats: {incomeBand: "high"}, flags: {vip: true}}}}, + {input: {customer: {age: 3}}, goals: ["customer.stats"], output: "!error: MissingRequiredInputs"}, + ], +} + +// Without goals every terminal write runs. A sibling leaf under an object that another block +// reads into is still a terminal write. +{ + name: "a terminal nested leaf next to a leaf that is read", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.stats.ageBand", value: "customer.age >= 18 ? 'adult' : 'minor'"}, + {expression: "customer.stats.incomeBand", value: "customer.income > 1000 ? 'high' : 'low'"}, + {expression: "customer.flags.vip", value: "customer.stats.incomeBand == 'high'"}, + ], + }, + cases: [ + {input: {customer: {income: 5000, age: 1}}, output: {customer: {income: 5000, age: 1, stats: {ageBand: "minor", incomeBand: "high"}, flags: {vip: true}}}, note: "bug: the terminal write customer.stats.ageBand is dropped because a sibling leaf of customer.stats is read; its input is still required"}, + {input: {customer: {income: 5, age: 30}}, output: {customer: {income: 5, age: 30, stats: {ageBand: "adult", incomeBand: "low"}, flags: {vip: false}}}, note: "bug: the terminal write customer.stats.ageBand is dropped because a sibling leaf of customer.stats is read; its input is still required"}, + {input: {customer: {income: 5}}, output: "!error: MissingRequiredInputs"}, + {input: {customer: {income: 5, age: 30}}, goals: ["customer.stats.ageBand", "customer.flags.vip"], output: {customer: {income: 5, age: 30, stats: {ageBand: "adult", incomeBand: "low"}, flags: {vip: false}}}}, + ], +} + +// The same over top-level nested paths: a read of one leaf must not depend on its sibling. +{ + name: "a goal reading one top-level nested leaf does not need the sibling's input", + policy: { + models: {o: {a: "number", b: "number"}}, + blocks: [ + {expression: "r.x", value: "o.a"}, + {expression: "r.y", value: "o.b"}, + {expression: "q", value: "r.y + 1"}, + ], + }, + cases: [ + {input: {o: {b: 1}}, goals: ["q"], output: {o: {b: 1}, r: {y: 1}, q: 2}, note: "bug: reading r.y makes the required-input check demand o.a, the input of the sibling leaf r.x"}, + {input: {o: {a: 5, b: 1}}, goals: ["q"], output: {o: {a: 5, b: 1}, r: {y: 1}, q: 2}}, + {input: {o: {a: 5, b: 1}}, goals: ["r.x"], output: {o: {a: 5, b: 1}, r: {x: 5}}}, + {input: {o: {a: 5, b: 1}}, output: {o: {a: 5, b: 1}, r: {x: 5, y: 1}, q: 2}, note: "bug: the terminal write r.x is dropped because its sibling r.y is read"}, + ], +} + +// A goal on a deep leaf whose writer reads a sibling leaf of a different branch. +{ + name: "a goal on a deep nested leaf reading across branches", + policy: { + models: {o: {n: "number"}}, + blocks: [ + {expression: "r.a.b.c", value: "o.n + 1"}, + {expression: "r.a.x", value: "r.a.b.c * 2"}, + {expression: "r.z.y", value: "r.a.x + r.a.b.c"}, + {expression: "r.z.w", value: "'w'"}, + ], + }, + cases: [ + {input: {o: {n: 1}}, goals: ["r.z.y"], output: {o: {n: 1}, r: {a: {b: {c: 2}, x: 4}, z: {y: 6}}}}, + {input: {o: {n: 1}}, goals: ["r.a.b"], output: {o: {n: 1}, r: {a: {b: {c: 2}}}}}, + {input: {o: {n: 1}}, goals: ["r.a"], output: {o: {n: 1}, r: {a: {b: {c: 2}, x: 4}}}}, + {input: {o: {n: 1}}, goals: ["r.z.w"], output: {o: {n: 1}, r: {z: {w: "w"}}}}, + {input: {}, goals: ["r.z.w"], output: {r: {z: {w: "w"}}}}, + {input: {o: {n: 0}}, goals: ["r"], output: {o: {n: 0}, r: {a: {b: {c: 1}, x: 2}, z: {y: 3, w: "w"}}}}, + ], +} + +// Unknown nested goals: a leaf below a written leaf, or a branch nobody writes. +{ + name: "unknown nested goals", + policy: { + models: {o: {n: "number"}}, + blocks: [{expression: "r.a.b", value: "o.n"}], + }, + cases: [ + {input: {o: {n: 1}}, goals: ["r.a.b.c"], output: "!error: GoalNotFound"}, + {input: {o: {n: 1}}, goals: ["r.a.zz"], output: "!error: GoalNotFound"}, + {input: {o: {n: 1}}, goals: ["r.zz"], output: "!error: GoalNotFound"}, + {input: {o: {n: 1}}, goals: ["r.a"], output: {o: {n: 1}, r: {a: {b: 1}}}}, + {input: {o: {n: 1}}, goals: ["r."], output: "!error: GoalNotFound"}, + ], +} + +// A table whose output columns write nested paths; goals on one column or on the parent. +{ + name: "goals on nested table output columns", + policy: { + models: {applicant: {score: "number"}}, + blocks: [ + {table: "t", inputs: ["applicant.score"], outputs: ["decision.terms.rate", "decision.terms.limit"], rules: [[">= 700", "0.05", "10000"], ["", "0.2", "500"]]}, + {expression: "decision.note", value: "'rate ' + string(decision.terms.rate)"}, + ], + }, + cases: [ + {input: {applicant: {score: 720}}, goals: ["decision.terms.rate"], output: {applicant: {score: 720}, decision: {terms: {rate: 0.05, limit: 10000}}}}, + {input: {applicant: {score: 1}}, goals: ["decision.terms.limit"], output: {applicant: {score: 1}, decision: {terms: {rate: 0.2, limit: 500}}}}, + {input: {applicant: {score: 720}}, goals: ["decision.terms"], output: {applicant: {score: 720}, decision: {terms: {rate: 0.05, limit: 10000}}}}, + {input: {applicant: {score: 720}}, goals: ["decision.note"], output: {applicant: {score: 720}, decision: {terms: {rate: 0.05, limit: 10000}, note: "rate 0.05"}}}, + {input: {applicant: {score: 720}}, goals: ["decision"], output: {applicant: {score: 720}, decision: {terms: {rate: 0.05, limit: 10000}, note: "rate 0.05"}}}, + ], +} + +// A nested goal under a per-member property. +{ + name: "a goal on a nested per-member path", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", cost: "number"}}, + blocks: [ + {expression: "company.metrics.margin", value: "company.revenue - company.cost"}, + {expression: "company.metrics.ratio", value: "company.revenue == 0 ? 0 : company.cost / company.revenue"}, + ], + }, + cases: [ + {input: {customer: {companies: [{revenue: 10, cost: 4}]}}, goals: ["company.metrics.margin"], output: {customer: {companies: [{revenue: 10, cost: 4, metrics: {margin: 6}}]}}}, + {input: {customer: {companies: [{revenue: 10, cost: 4}]}}, goals: ["company.metrics"], output: {customer: {companies: [{revenue: 10, cost: 4, metrics: {margin: 6, ratio: 0.4}}]}}}, + {input: {customer: {companies: [{revenue: 0, cost: 4}, {revenue: 8, cost: 2}]}}, goals: ["company.metrics.ratio"], output: {customer: {companies: [{revenue: 0, cost: 4, metrics: {ratio: 0}}, {revenue: 8, cost: 2, metrics: {ratio: 0.25}}]}}}, + {input: {customer: {companies: []}}, goals: ["company.metrics"], output: {customer: {companies: []}}}, + ], +} + +// --- Goals across imports ----------------------------------------------------------------------- + +// A goal on the root's write pulls a chain from four policies; goals on the intermediate +// levels stop at that level. +{ + name: "goals at every level of a four-policy chain", + policy: { + imports: ["p3"], + blocks: [{expression: "o.p4", value: "o.p3 + 1"}], + }, + policies: { + p3: {imports: ["p2"], blocks: [{expression: "o.p3", value: "o.p2 * 2"}, {expression: "o.side3", value: "o.extra"}]}, + p2: {imports: ["p1"], blocks: [{expression: "o.p2", value: "o.p1 + 10"}]}, + p1: {models: {o: {x: "number", extra: "string"}}, blocks: [{expression: "o.p1", value: "o.x * 3"}]}, + }, + cases: [ + {input: {o: {x: 1}}, goals: ["o.p4"], output: {o: {x: 1, p1: 3, p2: 13, p3: 26, p4: 27}}}, + {input: {o: {x: 1}}, goals: ["o.p3"], output: {o: {x: 1, p1: 3, p2: 13, p3: 26}}}, + {input: {o: {x: 1}}, goals: ["o.p2"], output: {o: {x: 1, p1: 3, p2: 13}}}, + {input: {o: {x: 1}}, goals: ["o.p1"], output: {o: {x: 1, p1: 3}}}, + {input: {o: {extra: "e"}}, goals: ["o.side3"], output: {o: {extra: "e", side3: "e"}}}, + {input: {o: {x: 1}}, output: "!error: MissingRequiredInputs"}, + {input: {o: {x: 1, extra: "e"}}, output: {o: {x: 1, extra: "e", p1: 3, p2: 13, p3: 26, p4: 27, side3: "e"}}}, + ], +} + +// Goals choose one branch of a diamond; the other branch's inputs may be missing. +{ + name: "a goal on one diamond branch skips the other branch's inputs", + policy: { + imports: ["left", "right"], + blocks: [{expression: "c.both", value: "c.l + c.r"}], + }, + policies: { + left: {imports: ["base"], models: {c: {lw: "number"}}, blocks: [{expression: "c.l", value: "c.norm * c.lw"}]}, + right: {imports: ["base"], models: {c: {rw: "number"}}, blocks: [{expression: "c.r", value: "c.norm + c.rw"}]}, + base: {models: {c: {v: "number"}}, blocks: [{expression: "c.norm", value: "c.v / 10"}]}, + }, + cases: [ + {input: {c: {v: 20, lw: 3}}, goals: ["c.l"], output: {c: {v: 20, lw: 3, norm: 2, l: 6}}}, + {input: {c: {v: 20, rw: 3}}, goals: ["c.r"], output: {c: {v: 20, rw: 3, norm: 2, r: 5}}}, + {input: {c: {v: 20}}, goals: ["c.norm"], output: {c: {v: 20, norm: 2}}}, + {input: {c: {v: 20, lw: 3, rw: 3}}, goals: ["c.both"], output: {c: {v: 20, lw: 3, rw: 3, norm: 2, l: 6, r: 5, both: 11}}}, + {input: {c: {v: 20, lw: 3}}, goals: ["c.both"], output: "!error: MissingRequiredInputs"}, + {input: {c: {v: 20, lw: 3}}, goals: ["c.l", "c.r"], output: "!error: MissingRequiredInputs"}, + ], +} + +// A goal inside an imported policy whose blocks reach back into the importer's writes. +{ + name: "a goal on an imported block that reads the importer's write", + policy: { + imports: ["consumer"], + models: {c: {v: "number", w: "number"}}, + blocks: [ + {expression: "c.root", value: "c.v * 100"}, + {expression: "c.other", value: "c.w"}, + ], + }, + policies: { + consumer: {blocks: [{expression: "c.consumed", value: "c.root + 1"}]}, + }, + cases: [ + {input: {c: {v: 1}}, goals: ["c.consumed"], output: {c: {v: 1, root: 100, consumed: 101}}}, + {input: {c: {w: 1}}, goals: ["c.other"], output: {c: {w: 1, other: 1}}}, + {input: {c: {w: 1}}, goals: ["c.consumed"], output: "!error: MissingRequiredInputs"}, + {input: {c: {v: 0, w: 0}}, output: {c: {v: 0, w: 0, root: 0, consumed: 1, other: 0}}}, + ], +} + +// A goal on a property written in a policy that is in the workspace but not in the unit. +{ + name: "goals only see the importer's unit, not policies that import it", + policy: { + imports: ["base"], + blocks: [{expression: "c.mine", value: "c.base + 1"}], + }, + policies: { + base: {models: {c: {v: "number"}}, blocks: [{expression: "c.base", value: "c.v"}]}, + outside: {imports: ["main"], blocks: [{expression: "c.outer", value: "c.mine * 2"}]}, + }, + cases: [ + {input: {c: {v: 1}}, goals: ["c.mine"], output: {c: {v: 1, base: 1, mine: 2}}}, + {input: {c: {v: 1}}, goals: ["c.base"], output: {c: {v: 1, base: 1}}}, + {input: {c: {v: 1}}, goals: ["c.outer"], output: "!error: GoalNotFound"}, + {input: {c: {v: 1}}, output: {c: {v: 1, base: 1, mine: 2}}}, + ], +} + +// A goal on an imported global computation. +{ + name: "goals on globals computed in imports", + policy: { + imports: ["rates", "fees"], + models: {order: {amount: "number"}}, + blocks: [{expression: "order.total", value: "order.amount * (1 + rate) + fee"}], + }, + policies: { + rates: {globals: {cfg: {baseRate: "number"}}, blocks: [{expression: "rate", value: "baseRate / 100"}]}, + fees: {globals: {cfg: {feeCents: "number"}}, blocks: [{expression: "fee", value: "feeCents / 100"}]}, + }, + cases: [ + {input: {baseRate: 20}, goals: ["rate"], output: {baseRate: 20, rate: 0.2}}, + {input: {feeCents: 150}, goals: ["fee"], output: {feeCents: 150, fee: 1.5}}, + {input: {baseRate: 20, feeCents: 150}, goals: ["rate", "fee"], output: {baseRate: 20, feeCents: 150, rate: 0.2, fee: 1.5}}, + {input: {baseRate: 20, feeCents: 150, order: {amount: 10}}, goals: ["order.total"], output: {baseRate: 20, feeCents: 150, rate: 0.2, fee: 1.5, order: {amount: 10, total: 13.5}}}, + {input: {baseRate: 20, order: {amount: 10}}, goals: ["order.total"], output: "!error: MissingRequiredInputs"}, + {input: {feeCents: "1"}, goals: ["fee"], output: "!error: InputValidationFailed"}, + ], +} + +// --- Goals on match, table and assertion targets ------------------------------------------------ + +// A match whose arm conditions read values computed by different blocks: the static cone +// includes every arm's reads. +{ + name: "a goal on a match whose arms read different computed values", + policy: { + models: {c: {age: "number", spend: "number"}}, + blocks: [ + {expression: "c.isMinor", value: "c.age < 18"}, + {expression: "c.isBig", value: "c.spend > 1000"}, + {expression: "c.unrelated", value: "'u'"}, + {match: "c.segment", arms: [["c.isMinor", "'youth'"], ["c.isBig", "'premium'"], ["", "'standard'"]]}, + ], + }, + cases: [ + {input: {c: {age: 10, spend: 5000}}, goals: ["c.segment"], output: {c: {age: 10, spend: 5000, isMinor: true, isBig: true, segment: "youth"}}, note: "question: a later arm's condition demands its computed read (c.isBig) even though an earlier arm matched; untaken arm values are lazy, later conditions are not"}, + {input: {c: {age: 30, spend: 5000}}, goals: ["c.segment"], output: {c: {age: 30, spend: 5000, isMinor: false, isBig: true, segment: "premium"}}}, + {input: {c: {age: 30, spend: 1}}, goals: ["c.segment"], output: {c: {age: 30, spend: 1, isMinor: false, isBig: false, segment: "standard"}}}, + {input: {c: {age: 10}}, goals: ["c.segment"], output: "!error: MissingRequiredInputs"}, + {input: {c: {age: 10, spend: 5000}}, goals: ["c.segment", "c.unrelated"], output: {c: {age: 10, spend: 5000, isMinor: true, isBig: true, segment: "youth", unrelated: "u"}}, note: "question: a later arm's condition demands its computed read (c.isBig) even though an earlier arm matched; untaken arm values are lazy, later conditions are not"}, + ], +} + +// A collect table goal and a first-hit table goal in the same policy. +{ + name: "goals on a collect table and a first-hit table", + policy: { + models: {c: {age: "number", country: "string"}}, + blocks: [ + {table: "tags", hit: "collect", inputs: ["c.age", "c.country"], outputs: ["c.tags"], rules: [ + [">= 18", "", "'adult'"], + ["", "'NO'", "'nordic'"], + ["< 30", "", "'young'"], + ]}, + {table: "zone", inputs: ["c.country"], outputs: ["c.zone"], rules: [["'NO'", "'eea'"], ["'US'", "'na'"], ["", "'other'"]]}, + {expression: "c.tagCount", value: "len(c.tags)"}, + ], + }, + cases: [ + {input: {c: {age: 20, country: "NO"}}, goals: ["c.tags"], output: {c: {age: 20, country: "NO", tags: ["adult", "nordic", "young"]}}}, + {input: {c: {country: "US"}}, goals: ["c.zone"], output: {c: {country: "US", zone: "na"}}}, + {input: {c: {age: 40, country: "SE"}}, goals: ["c.tagCount"], output: {c: {age: 40, country: "SE", tags: ["adult"], tagCount: 1}}}, + {input: {c: {age: 40}}, goals: ["c.zone"], output: "!error: MissingRequiredInputs"}, + ], +} + +// Goals on two different outputs of one table owned by different consumers. +{ + name: "goals through two consumers of one multi-output table", + policy: { + models: {c: {score: "number"}}, + blocks: [ + {table: "t", inputs: ["c.score"], outputs: ["c.grade", "c.points"], rules: [[">= 90", "'A'", "4"], [">= 80", "'B'", "3"], ["", "'C'", "2"]]}, + {expression: "c.label", value: "'grade ' + c.grade"}, + {expression: "c.weighted", value: "c.points * 10"}, + ], + }, + cases: [ + {input: {c: {score: 95}}, goals: ["c.label"], output: {c: {score: 95, grade: "A", points: 4, label: "grade A"}}}, + {input: {c: {score: 85}}, goals: ["c.weighted"], output: {c: {score: 85, grade: "B", points: 3, weighted: 30}}}, + {input: {c: {score: 10}}, goals: ["c.label", "c.weighted"], output: {c: {score: 10, grade: "C", points: 2, label: "grade C", weighted: 20}}}, + {input: {c: {score: 90}}, goals: ["c.points"], output: {c: {score: 90, grade: "A", points: 4}}}, + ], +} + +// An assertion target with `or` groups; the goal pulls every condition's reads. +{ + name: "a goal on an assertion with or-conditions over computed values", + policy: { + models: {c: {age: "number", income: "number", guarantor: "boolean"}}, + blocks: [ + {expression: "c.adult", value: "c.age >= 18"}, + {expression: "c.earns", value: "c.income >= 1000"}, + {assertion: "c.ok", conditions: [["and", "c.adult"], ["or", "c.earns", 1], ["and", "c.guarantor", 1]]}, + {expression: "c.msg", value: "c.ok ? 'yes' : 'no'"}, + ], + }, + cases: [ + {input: {c: {age: 20, income: 2000, guarantor: false}}, goals: ["c.ok"], output: {c: {age: 20, income: 2000, guarantor: false, adult: true, earns: true, ok: true}}}, + {input: {c: {age: 20, income: 0, guarantor: true}}, goals: ["c.ok"], output: {c: {age: 20, income: 0, guarantor: true, adult: true, earns: false, ok: true}}}, + {input: {c: {age: 10, income: 0, guarantor: false}}, goals: ["c.msg"], output: {c: {age: 10, income: 0, guarantor: false, adult: false, earns: false, ok: false, msg: "no"}}}, + {input: {c: {age: 20, income: 2000}}, goals: ["c.ok"], output: "!error: MissingRequiredInputs"}, + {input: {c: {age: 20}}, goals: ["c.adult"], output: {c: {age: 20, adult: true}}}, + ], +} + +// A goal on a match whose taken arm reads a value computed in an import. +{ + name: "a goal on a match reading values from two imports", + policy: { + imports: ["risk", "price"], + blocks: [{match: "c.offer", arms: [["c.risk == 'high'", "'none'"], ["", "'offer ' + string(c.price)"]]}], + }, + policies: { + risk: {models: {c: {score: "number"}}, blocks: [{expression: "c.risk", value: "c.score < 500 ? 'high' : 'low'"}]}, + price: {models: {c: {base: "number"}}, blocks: [{expression: "c.price", value: "c.base * 2"}]}, + }, + cases: [ + {input: {c: {score: 700, base: 5}}, goals: ["c.offer"], output: {c: {score: 700, base: 5, risk: "low", price: 10, offer: "offer 10"}}}, + {input: {c: {score: 100, base: 5}}, goals: ["c.offer"], output: {c: {score: 100, base: 5, risk: "high", offer: "none"}}}, + {input: {c: {score: 100}}, goals: ["c.offer"], output: "!error: MissingRequiredInputs"}, + {input: {c: {score: 100}}, goals: ["c.risk"], output: {c: {score: 100, risk: "high"}}}, + ], +} + +// --- Goals combined with missing optional inputs ---------------------------------------------- + +{ + name: "a goal whose cone reads only optional inputs", + policy: { + models: {c: {nick: "string?", age: "number"}}, + blocks: [ + {expression: "c.display", value: "c.nick ?? 'anonymous'"}, + {expression: "c.adult", value: "c.age >= 18"}, + ], + }, + cases: [ + {input: {c: {}}, goals: ["c.display"], output: {c: {display: "anonymous"}}}, + {input: {c: {nick: null}}, goals: ["c.display"], output: {c: {nick: null, display: "anonymous"}}}, + {input: {c: {nick: "z"}}, goals: ["c.display"], output: {c: {nick: "z", display: "z"}}}, + {input: {}, goals: ["c.display"], output: {c: {display: "anonymous"}}}, + {input: {c: {}}, goals: ["c.adult"], output: "!error: MissingRequiredInputs"}, + {input: {c: {nick: 1}}, goals: ["c.display"], output: "!error: InputValidationFailed"}, + ], +} + +{ + name: "a goal over an optional relationship that is missing", + policy: { + models: {c: {companies: "company[]?", name: "string"}, company: {revenue: "number"}}, + blocks: [ + {expression: "company.big", value: "company.revenue > 100"}, + {expression: "c.total", value: "sum(map(c.companies ?? [], #.revenue))"}, + {expression: "c.greeting", value: "'hi ' + c.name"}, + ], + }, + cases: [ + {input: {c: {}}, goals: ["c.total"], output: {c: {total: 0}}}, + {input: {c: {companies: null}}, goals: ["c.total"], output: {c: {companies: null, total: 0}}}, + {input: {c: {companies: [{revenue: 5}, {revenue: 7}]}}, goals: ["c.total"], output: {c: {companies: [{revenue: 5}, {revenue: 7}], total: 12}}}, + {input: {c: {}}, goals: ["company.big"], output: {c: {}}}, + {input: {c: {companies: [{revenue: 500}]}}, goals: ["company.big"], output: {c: {companies: [{revenue: 500, big: true}]}}}, + {input: {c: {name: "a"}}, goals: ["c.greeting"], output: {c: {name: "a", greeting: "hi a"}}}, + ], +} + +{ + name: "a goal over an optional global and a nested optional default", + policy: { + globals: {cfg: {discount: "number?", currency: "string?"}}, + models: {order: {amount: "number"}}, + blocks: [ + {expression: "order.net", value: "order.amount * (1 - (discount ?? 0))"}, + {expression: "order.money.currency", value: "currency ?? 'EUR'"}, + {expression: "order.money.text", value: "string(order.net) + ' ' + order.money.currency"}, + ], + }, + cases: [ + {input: {order: {amount: 10}}, goals: ["order.net"], output: {order: {amount: 10, net: 10}}}, + {input: {discount: 0.5, order: {amount: 10}}, goals: ["order.net"], output: {discount: 0.5, order: {amount: 10, net: 5}}}, + {input: {}, goals: ["order.money.currency"], output: {order: {money: {currency: "EUR"}}}}, + {input: {currency: "NOK"}, goals: ["order.money.currency"], output: {currency: "NOK", order: {money: {currency: "NOK"}}}}, + {input: {order: {amount: 4}}, goals: ["order.money.text"], output: {order: {amount: 4, net: 4, money: {currency: "EUR", text: "4 EUR"}}}}, + {input: {}, goals: ["order.money.text"], output: "!error: MissingRequiredInputs"}, + ], +} + +// A goal whose cone has an optional input read only by a table row that does not match. +{ + name: "a goal on a table reading an optional column", + policy: { + models: {c: {age: "number", nick: "string?"}}, + blocks: [{table: "t", inputs: ["c.age"], outputs: ["c.name"], rules: [["< 18", "c.nick ?? 'kid'"], ["", "'adult'"]]}], + }, + cases: [ + {input: {c: {age: 30}}, goals: ["c.name"], output: {c: {age: 30, name: "adult"}}}, + {input: {c: {age: 3}}, goals: ["c.name"], output: {c: {age: 3, name: "kid"}}}, + {input: {c: {age: 3, nick: "bo"}}, goals: ["c.name"], output: {c: {age: 3, nick: "bo", name: "bo"}}}, + {input: {c: {age: 3, nick: null}}, goals: ["c.name"], output: {c: {age: 3, nick: null, name: "kid"}}}, + {input: {c: {nick: "bo"}}, goals: ["c.name"], output: "!error: MissingRequiredInputs"}, + ], +} + +// An optional input that is missing produces a null computed value; a goal on the dependent +// sees null. +{ + name: "a goal on a value derived from a null optional", + policy: { + models: {c: {bonus: "number?"}}, + blocks: [ + {expression: "c.copy", value: "c.bonus"}, + {expression: "c.isSet", value: "c.copy != null"}, + ], + }, + cases: [ + {input: {c: {}}, goals: ["c.copy"], output: {c: {copy: null}}}, + {input: {c: {}}, goals: ["c.isSet"], output: {c: {copy: null, isSet: false}}}, + {input: {c: {bonus: 0}}, goals: ["c.isSet"], output: {c: {bonus: 0, copy: 0, isSet: true}}}, + {input: {c: {bonus: null}}, goals: ["c.isSet"], output: {c: {bonus: null, copy: null, isSet: false}}}, + ], +} + +// --- Goal sets and output shape ----------------------------------------------------------------- + +// A goal and its own dependency named together behave like the goal alone. +{ + name: "a goal named together with its own dependencies", + policy: { + models: {o: {x: "number"}}, + blocks: [ + {expression: "o.a", value: "o.x + 1"}, + {expression: "o.b", value: "o.a * 2"}, + {expression: "o.c", value: "o.b - 1"}, + ], + }, + cases: [ + {input: {o: {x: 1}}, goals: ["o.c", "o.a"], output: {o: {x: 1, a: 2, b: 4, c: 3}}}, + {input: {o: {x: 1}}, goals: ["o.a", "o.b", "o.c"], output: {o: {x: 1, a: 2, b: 4, c: 3}}}, + {input: {o: {x: 1}}, goals: ["o.b", "o.x"], output: {o: {x: 1, a: 2, b: 4}}}, + {input: {o: {x: 1}}, goals: ["o.c", "o.c", "o.c"], output: {o: {x: 1, a: 2, b: 4, c: 3}}}, + ], +} + +// Goals with whitespace or different case are not normalised. +{ + name: "goal names are matched exactly", + policy: { + models: {o: {x: "number"}}, + blocks: [{expression: "o.total", value: "o.x"}], + }, + cases: [ + {input: {o: {x: 1}}, goals: ["o.total"], output: {o: {x: 1, total: 1}}}, + {input: {o: {x: 1}}, goals: [" o.total"], output: "!error: GoalNotFound"}, + {input: {o: {x: 1}}, goals: ["o.total "], output: "!error: GoalNotFound"}, + {input: {o: {x: 1}}, goals: ["o.Total"], output: "!error: GoalNotFound"}, + {input: {o: {x: 1}}, goals: ["o..total"], output: "!error: GoalNotFound"}, + {input: {o: {x: 1}}, goals: ["o.total."], output: "!error: GoalNotFound"}, + ], +} + +// Goals on a realistic pricing policy split across imports. +{ + name: "goals select parts of a split pricing policy", + policy: { + imports: ["lines", "shipping"], + blocks: [ + {expression: "quote.total", value: "quote.subtotal + quote.shippingCost"}, + {assertion: "quote.valid", conditions: ["quote.total > 0", "len(quote.items) > 0"]}, + ], + }, + policies: { + lines: { + models: {quote: {items: "qitem[]"}, qitem: {qty: "number", unit: "number"}}, + blocks: [ + {expression: "qitem.amount", value: "qitem.qty * qitem.unit"}, + {expression: "quote.subtotal", value: "sum(map(quote.items, #.amount))"}, + ], + }, + shipping: { + models: {quote: {weight: "number", express: "boolean?"}}, + blocks: [{table: "ship", inputs: ["quote.weight", "quote.express ?? false"], outputs: ["quote.shippingCost"], rules: [ + ["", "true", "25"], + ["<= 1", "", "5"], + ["", "", "10"], + ]}], + }, + }, + cases: [ + {input: {quote: {weight: 0.5}}, goals: ["quote.shippingCost"], output: {quote: {weight: 0.5, shippingCost: 5}}}, + {input: {quote: {weight: 3, express: true}}, goals: ["quote.shippingCost"], output: {quote: {weight: 3, express: true, shippingCost: 25}}}, + {input: {quote: {items: [{qty: 2, unit: 3}]}}, goals: ["quote.subtotal"], output: {quote: {subtotal: 6, items: [{qty: 2, unit: 3, amount: 6}]}}}, + {input: {quote: {weight: 2, items: [{qty: 2, unit: 3}]}}, goals: ["quote.total"], output: {quote: {weight: 2, subtotal: 6, shippingCost: 10, total: 16, items: [{qty: 2, unit: 3, amount: 6}]}}}, + {input: {quote: {weight: 2, items: []}}, goals: ["quote.valid"], output: {quote: {weight: 2, subtotal: 0, shippingCost: 10, total: 10, valid: false, items: []}}}, + {input: {quote: {items: []}}, goals: ["quote.valid"], output: "!error: MissingRequiredInputs"}, + ], +} diff --git a/core/engine/tests/spec/policy/32-policy-diagnostics.json5 b/core/engine/tests/spec/policy/32-policy-diagnostics.json5 new file mode 100644 index 00000000..db3c478d --- /dev/null +++ b/core/engine/tests/spec/policy/32-policy-diagnostics.json5 @@ -0,0 +1,1123 @@ +// Policy diagnostics and the evaluation gate. Static analysis of a policy unit produces +// diagnostics with a severity. `DecisionEngine` refuses a policy whose unit has any error +// diagnostic, so a suite without `diagnostics` expects every case to fail with +// `CompilationErrors [codes]`. A suite that pins `diagnostics: [codes]` asserts the exact set of +// error codes and evaluates through the workspace, which runs the policy anyway; those cases pin +// what the editor path does with a broken policy. Warnings and hints never gate evaluation +// (`diagnostics: []` asserts there is no error at all). +// +// Error codes reachable from a policy: PARSE_ERROR, UNDEFINED_VARIABLE, TYPE_MISMATCH, +// INVALID_EXPRESSION, EMPTY_BLOCK, MISSING_DEFAULT_BRANCH, MIXED_SCOPE, MAX_DEPTH_EXCEEDED, +// CYCLIC_DEPENDENCY, DUPLICATE_WRITER, INVALID_WRITE_PATH, INPUT_OVERRIDE, +// SELF_REFERENCING_WRITE, UNREACHABLE_ENTITY_READ, PARTIAL_OBJECT_WRITE, +// UNSUPPORTED_NESTED_ITERATION, DATA_MODEL_COLLISION, UNKNOWN_DATA_MODEL_TARGET, +// DUPLICATE_PROPERTY, DUPLICATE_ENUM_VALUE, INVALID_NAME, IMPORT_NOT_FOUND, CIRCULAR_IMPORT. +// The graph codes (INVALID_GRAPH_STRUCTURE, UNREACHABLE_NODE, MISSING_INPUT_SCHEMA, +// UNRESOLVED_FUNCTION_TYPE, IMPLICIT_ANY, UNCHECKED_NODE) do not apply to policies, and the +// linter codes are hints that the evaluation gate never sees. + +// --- PARSE_ERROR ------------------------------------------------------------------------------- + +{ + name: "PARSE_ERROR: an unterminated expression", + diagnostics: ["PARSE_ERROR"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.a", value: "c.n * (2"}, {expression: "c.b", value: "c.n + 1"}], + }, + cases: [ + [{c: {n: 1}}, "!error: ExpressionFailed"], + {input: {c: {n: 1}}, goals: ["c.b"], output: {c: {n: 1, b: 2}}}, + {input: {c: {n: 1}}, goals: ["c.a"], output: "!error: ExpressionFailed"}, + ], +} + +{ + name: "PARSE_ERROR gates the policy", + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.a", value: "c.n * (2"}, {expression: "c.b", value: "c.n + 1"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"PARSE_ERROR\"]"], + [{c: {}}, "!error: CompilationErrors [\"PARSE_ERROR\"]"], + {input: {c: {n: 1}}, goals: ["c.b"], output: "!error: CompilationErrors [\"PARSE_ERROR\"]"}, + ], +} + +{ + name: "PARSE_ERROR: a call of an unknown function", + diagnostics: ["PARSE_ERROR"], + policy: { + models: {c: {s: "string"}}, + blocks: [{expression: "c.x", value: "nosuch(c.s)"}], + }, + cases: [ + [{c: {s: "a"}}, "!error: ExpressionFailed"], + [{c: {s: ""}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "PARSE_ERROR: a data model without a name", + diagnostics: ["PARSE_ERROR"], + policy: {raw: {imports: [], blocks: [ + {id: "m", type: "dataModel", props: {data: {name: "", scope: "entity", properties: [{id: "p1", name: "age", type: "number", array: false, optional: false}]}}}, + {id: "b0", type: "expression", props: {data: {key: "x", value: "1"}}}, + ]}}, + cases: [ + {input: {}, output: {x: 1}, note: "question: the unnamed data model is dropped and evaluation proceeds"}, + {input: {age: "not validated"}, output: {age: "not validated", x: 1}}, + ], +} + +{ + name: "PARSE_ERROR: a property without a name", + diagnostics: ["PARSE_ERROR"], + policy: {raw: {imports: [], blocks: [ + {id: "m", type: "dataModel", props: {data: {name: "c", scope: "entity", properties: [ + {id: "p1", name: "", type: "number", array: false, optional: false}, + {id: "p2", name: "age", type: "number", array: false, optional: false}, + ]}}}, + {id: "b0", type: "expression", props: {data: {key: "c.x", value: "c.age + 1"}}}, + ]}}, + cases: [ + [{c: {age: 1}}, {c: {age: 1, x: 2}}], + [{c: {age: "1"}}, "!error: InputValidationFailed"], + [{c: {}}, "!error: MissingRequiredInputs"], + ], +} + +// --- UNDEFINED_VARIABLE ------------------------------------------------------------------------ + +{ + name: "UNDEFINED_VARIABLE: a read of an undeclared property", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.missing * 2"}], + }, + cases: [ + [{c: {n: 1}}, "!error: MissingRequiredInputs"], + [{c: {n: 1, missing: 4}}, {c: {n: 1, missing: 4, x: 8}}], + [{c: {n: 1, missing: null}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "UNDEFINED_VARIABLE gates the policy", + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.missing * 2"}], + }, + cases: [ + [{c: {n: 1, missing: 4}}, "!error: CompilationErrors [\"UNDEFINED_VARIABLE\"]"], + [{c: {n: 1}}, "!error: CompilationErrors [\"UNDEFINED_VARIABLE\"]"], + ], +} + +{ + name: "UNDEFINED_VARIABLE with TYPE_MISMATCH: a read of an undeclared entity", + diagnostics: ["TYPE_MISMATCH", "UNDEFINED_VARIABLE"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "ghost.n + 1"}], + }, + cases: [ + [{c: {n: 1}}, "!error: MissingRequiredInputs"], + [{c: {n: 1}, ghost: {n: 2}}, {c: {n: 1, x: 3}, ghost: {n: 2}}], + ], +} + +// --- TYPE_MISMATCH ----------------------------------------------------------------------------- + +{ + name: "TYPE_MISMATCH: membership test against a number", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {c: {age: "number"}}, + blocks: [{expression: "c.a", value: "c.age in 5"}], + }, + cases: [ + [{c: {age: 1}}, "!error: ExpressionFailed"], + [{c: {age: 5}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "TYPE_MISMATCH: indexing and member access on a number read null", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {c: {age: "number"}}, + blocks: [{expression: "c.a", value: "c.age[0]"}, {expression: "c.b", value: "c.age.x"}], + }, + cases: [ + [{c: {age: 1}}, {c: {age: 1, a: null, b: null}}], + [{c: {age: 0}}, {c: {age: 0, a: null, b: null}}], + ], +} + +{ + name: "TYPE_MISMATCH: a table output cell outside the declared column type", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {c: {p: "number"}}, + blocks: [{table: "t", inputs: ["c.p"], outputs: [{field: "c.o", type: "number"}], rules: [["> 0", "'x'"], ["", "1"]]}], + }, + cases: [ + {input: {c: {p: 1}}, output: {c: {p: 1, o: "x"}}, note: "question: the declared column type is not enforced at runtime; the string is written to a number column"}, + [{c: {p: 0}}, {c: {p: 0, o: 1}}], + ], +} + +{ + name: "TYPE_MISMATCH: an unknown declared column type", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {c: {p: "number"}}, + blocks: [{table: "t", inputs: ["c.p"], outputs: [{field: "c.o", type: "foo"}], rules: [["", "1"]]}], + }, + cases: [ + [{c: {p: 1}}, {c: {p: 1, o: 1}}], + [{c: {p: -1}}, {c: {p: -1, o: 1}}], + ], +} + +{ + name: "TYPE_MISMATCH: a field-less input cell that is not a boolean", + diagnostics: ["TYPE_MISMATCH"], + policy: { + models: {c: {p: "number"}}, + blocks: [{table: "t", inputs: [null], outputs: ["c.o"], rules: [["c.p + 1", "1"], ["", "2"]]}], + }, + cases: [ + [{c: {p: 1}}, {c: {p: 1, o: 2}}], + [{c: {p: -1}}, {c: {p: -1, o: 2}}], + ], +} + +{ + name: "TYPE_MISMATCH gates the policy even outside the goal's cone", + policy: { + models: {c: {s: "string", n: "number"}}, + blocks: [{expression: "c.ok", value: "c.n + 1"}, {expression: "c.bad", value: "c.s - 1"}], + }, + cases: [ + [{c: {s: "a", n: 1}}, "!error: CompilationErrors [\"TYPE_MISMATCH\"]"], + {input: {c: {s: "a", n: 1}}, goals: ["c.ok"], output: "!error: CompilationErrors [\"TYPE_MISMATCH\"]"}, + ], +} + +// --- INVALID_EXPRESSION ------------------------------------------------------------------------ + +{ + name: "INVALID_EXPRESSION: a function called with the wrong arity", + diagnostics: ["INVALID_EXPRESSION"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.a", value: "abs(c.n, 1)"}, {expression: "c.b", value: "c.n"}], + }, + cases: [ + [{c: {n: 1}}, "!error: ExpressionFailed"], + {input: {c: {n: -1}}, goals: ["c.b"], output: {c: {n: -1, b: -1}}}, + ], +} + +{ + name: "INVALID_EXPRESSION: a function argument of the wrong type", + diagnostics: ["INVALID_EXPRESSION"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.a", value: "len(c.n)"}], + }, + cases: [ + [{c: {n: 1}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "INVALID_EXPRESSION gates the policy", + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.a", value: "abs(c.n, 1)"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"INVALID_EXPRESSION\"]"], + [{}, "!error: CompilationErrors [\"INVALID_EXPRESSION\"]"], + ], +} + +// --- EMPTY_BLOCK ------------------------------------------------------------------------------- + +// Only an assertion without conditions is an error; empty expressions, matches and tables are +// warnings (see the warning-only section). +{ + name: "EMPTY_BLOCK: an assertion with no conditions", + diagnostics: ["EMPTY_BLOCK"], + policy: { + models: {c: {p: "boolean"}}, + blocks: [{assertion: "c.ok", conditions: []}], + }, + cases: [ + {input: {c: {p: true}}, output: {c: {p: true, ok: false}}, note: "question: an assertion with no conditions writes false rather than a vacuous true"}, + {input: {c: {}}, output: {c: {ok: false}}, note: "question: an assertion with no conditions writes false rather than a vacuous true"}, + ], +} + +{ + name: "EMPTY_BLOCK gates the policy", + policy: { + models: {c: {p: "boolean"}}, + blocks: [{assertion: "c.ok", conditions: []}, {expression: "c.copy", value: "c.p"}], + }, + cases: [ + [{c: {p: true}}, "!error: CompilationErrors [\"EMPTY_BLOCK\"]"], + {input: {c: {p: true}}, goals: ["c.copy"], output: "!error: CompilationErrors [\"EMPTY_BLOCK\"]"}, + ], +} + +// --- MISSING_DEFAULT_BRANCH --------------------------------------------------------------------- + +{ + name: "MISSING_DEFAULT_BRANCH: arms over a string that is not an enum", + diagnostics: ["MISSING_DEFAULT_BRANCH"], + policy: { + models: {c: {s: "string"}}, + blocks: [{match: "c.kind", arms: [["c.s == 'a'", "1"], ["c.s == 'b'", "2"]]}], + }, + cases: [ + [{c: {s: "a"}}, {c: {s: "a", kind: 1}}], + [{c: {s: "b"}}, {c: {s: "b", kind: 2}}], + [{c: {s: "z"}}, {c: {s: "z", kind: null}}], + ], +} + +{ + name: "MISSING_DEFAULT_BRANCH gates the policy", + policy: { + models: {c: {s: "string"}}, + blocks: [{match: "c.kind", arms: [["c.s == 'a'", "1"], ["c.s == 'b'", "2"]]}], + }, + cases: [ + [{c: {s: "a"}}, "!error: CompilationErrors [\"MISSING_DEFAULT_BRANCH\"]"], + [{c: {s: "z"}}, "!error: CompilationErrors [\"MISSING_DEFAULT_BRANCH\"]"], + ], +} + +// Discriminated unions are exhaustive without a default arm: no diagnostic. +{ + name: "no MISSING_DEFAULT_BRANCH for arms covering every enum value", + diagnostics: [], + policy: { + models: {c: {t: "string(a|b)"}}, + blocks: [{match: "c.x", arms: [["c.t == 'a'", "1"], ["c.t == 'b'", "2"]]}], + }, + cases: [ + [{c: {t: "a"}}, {c: {t: "a", x: 1}}], + [{c: {t: "b"}}, {c: {t: "b", x: 2}}], + [{c: {t: "c"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "no MISSING_DEFAULT_BRANCH for arms covering both booleans", + diagnostics: [], + policy: { + models: {c: {p: "boolean"}}, + blocks: [{match: "c.x", arms: [["c.p == true", "'yes'"], ["c.p == false", "'no'"]]}], + }, + cases: [ + [{c: {p: true}}, {c: {p: true, x: "yes"}}], + [{c: {p: false}}, {c: {p: false, x: "no"}}], + ], +} + +{ + name: "no MISSING_DEFAULT_BRANCH for a gap-free numeric range", + diagnostics: [], + policy: { + models: {c: {n: "number"}}, + blocks: [{match: "c.x", arms: [["c.n < 10", "'low'"], ["c.n >= 10", "'high'"]]}], + }, + cases: [ + [{c: {n: 9.99}}, {c: {n: 9.99, x: "low"}}], + [{c: {n: 10}}, {c: {n: 10, x: "high"}}], + [{c: {n: -1000}}, {c: {n: -1000, x: "low"}}], + ], +} + +// --- MIXED_SCOPE ------------------------------------------------------------------------------- + +{ + name: "MIXED_SCOPE: a table writing two entities", + diagnostics: ["MIXED_SCOPE"], + policy: { + models: {customer: {age: "number"}, order: {n: "number"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.a", "order.b"], rules: [[">= 18", "1", "2"], ["", "3", "4"]]}], + }, + cases: [ + [{customer: {age: 20}, order: {n: 1}}, {customer: {age: 20, a: 1}, order: {n: 1, b: 2}}], + [{customer: {age: 2}, order: {n: 1}}, {customer: {age: 2, a: 3}, order: {n: 1, b: 4}}], + ], +} + +{ + name: "MIXED_SCOPE: a table writing an entity and a global", + diagnostics: ["MIXED_SCOPE"], + policy: { + models: {c: {n: "number"}}, + globals: {g: {k: "number"}}, + blocks: [{table: "t", inputs: ["c.n"], outputs: ["c.a", "top"], rules: [["", "1", "2"]]}], + }, + cases: [ + [{c: {n: 1}}, {c: {n: 1, a: 1}, top: 2}], + ], +} + +{ + name: "MIXED_SCOPE gates the policy", + policy: { + models: {customer: {age: "number"}, order: {n: "number"}}, + blocks: [{table: "t", inputs: ["customer.age"], outputs: ["customer.a", "order.b"], rules: [["", "1", "2"]]}], + }, + cases: [ + [{customer: {age: 20}, order: {n: 1}}, "!error: CompilationErrors [\"MIXED_SCOPE\"]"], + ], +} + +// --- MAX_DEPTH_EXCEEDED ------------------------------------------------------------------------- + +{ + name: "MAX_DEPTH_EXCEEDED: an assertion condition nested 32 levels deep", + diagnostics: ["MAX_DEPTH_EXCEEDED"], + policy: { + models: {c: {p: "boolean"}}, + blocks: [{assertion: "c.ok", conditions: [["and", "c.p", 32]]}], + }, + cases: [ + {input: {c: {p: true}}, output: {c: {p: true, ok: false}}, note: "question: the too-deep condition is dropped, leaving an assertion with no conditions that writes false"}, + [{c: {p: false}}, {c: {p: false, ok: false}}], + ], +} + +{ + name: "no MAX_DEPTH_EXCEEDED at depth 31", + diagnostics: [], + policy: { + models: {c: {p: "boolean"}}, + blocks: [{assertion: "c.ok", conditions: [["and", "c.p", 31]]}], + }, + cases: [ + [{c: {p: true}}, {c: {p: true, ok: true}}], + [{c: {p: false}}, {c: {p: false, ok: false}}], + ], +} + +{ + name: "MAX_DEPTH_EXCEEDED gates the policy", + policy: { + models: {c: {p: "boolean"}}, + blocks: [{assertion: "c.ok", conditions: ["c.p", ["and", "c.p", 40]]}], + }, + cases: [ + [{c: {p: true}}, "!error: CompilationErrors [\"MAX_DEPTH_EXCEEDED\"]"], + ], +} + +// --- CYCLIC_DEPENDENCY ------------------------------------------------------------------------- + +{ + name: "CYCLIC_DEPENDENCY: two computed properties reading each other", + diagnostics: ["CYCLIC_DEPENDENCY", "UNDEFINED_VARIABLE"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.a", value: "c.b + 1"}, {expression: "c.b", value: "c.a + 1"}, {expression: "c.k", value: "c.n"}], + }, + cases: [ + {input: {c: {n: 1}}, output: {c: {n: 1, k: 1}}, note: "question: without goals the cyclic writes are silently skipped"}, + {input: {c: {n: 1, a: 1, b: 2}}, output: {c: {n: 1, a: 1, b: 2, k: 1}}, note: "question: without goals the cyclic writes are silently skipped and the input values stay"}, + {input: {c: {n: 1}}, goals: ["c.a"], output: "!error: ExpressionFailed", note: "question: a goal on a cyclic property runs one block of the cycle against a null read"}, + {input: {c: {n: 1}}, goals: ["c.k"], output: {c: {n: 1, k: 1}}}, + ], +} + +{ + name: "CYCLIC_DEPENDENCY gates the policy", + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.a", value: "c.b + 1"}, {expression: "c.b", value: "c.a + 1"}, {expression: "c.k", value: "c.n"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"CYCLIC_DEPENDENCY\", \"UNDEFINED_VARIABLE\"]"], + {input: {c: {n: 1}}, goals: ["c.k"], output: "!error: CompilationErrors [\"CYCLIC_DEPENDENCY\", \"UNDEFINED_VARIABLE\"]"}, + ], +} + +{ + name: "CYCLIC_DEPENDENCY: a three-block cycle across a table and a match", + diagnostics: ["CYCLIC_DEPENDENCY", "UNDEFINED_VARIABLE"], + policy: { + models: {c: {n: "number"}}, + blocks: [ + {expression: "c.a", value: "c.z + 1"}, + {table: "t", inputs: ["c.a"], outputs: ["c.y"], rules: [["> 0", "1"], ["", "0"]]}, + {match: "c.z", arms: [["c.y == 1", "5"], ["", "6"]]}, + ], + }, + cases: [ + {input: {c: {n: 1}}, output: {c: {n: 1}}, note: "question: without goals the cyclic writes are silently skipped"}, + ], +} + +// --- DUPLICATE_WRITER -------------------------------------------------------------------------- + +{ + name: "DUPLICATE_WRITER: an expression and an assertion writing one property", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + models: {c: {n: "number"}}, + blocks: [{assertion: "c.flag", conditions: ["c.n > 0"]}, {expression: "c.flag", value: "'text'"}], + }, + cases: [ + {input: {c: {n: 1}}, output: {c: {n: 1, flag: true}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the first writer"}, + {input: {c: {n: 0}}, output: {c: {n: 0, flag: false}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the first writer"}, + ], +} + +{ + name: "DUPLICATE_WRITER: two tables writing one output column", + diagnostics: ["DUPLICATE_WRITER"], + policy: { + models: {c: {n: "number"}}, + blocks: [ + {table: "t1", inputs: ["c.n"], outputs: ["c.band"], rules: [["", "'one'"]]}, + {table: "t2", inputs: ["c.n"], outputs: ["c.band"], rules: [["", "'two'"]]}, + ], + }, + cases: [ + {input: {c: {n: 1}}, output: {c: {n: 1, band: "one"}}, note: "question: DuplicateWriter is an error diagnostic; evaluation keeps the first writer"}, + ], +} + +{ + name: "DUPLICATE_WRITER gates the policy", + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.v", value: "1"}, {expression: "c.v", value: "2"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"DUPLICATE_WRITER\"]"], + {input: {c: {n: 1}}, goals: ["c.v"], output: "!error: CompilationErrors [\"DUPLICATE_WRITER\"]"}, + ], +} + +// --- INVALID_WRITE_PATH ------------------------------------------------------------------------ + +{ + name: "INVALID_WRITE_PATH: malformed table output fields", + diagnostics: ["INVALID_WRITE_PATH"], + policy: { + models: {c: {p: "number"}}, + blocks: [{table: "t", inputs: ["c.p"], outputs: ["c.a[]b", "[]", "c.ok"], rules: [["", "1", "2", "3"]]}], + }, + cases: [ + {input: {c: {p: 1}}, output: {c: {p: 1, ok: 3}}, note: "question: output columns with invalid paths are dropped silently"}, + ], +} + +{ + name: "INVALID_WRITE_PATH: malformed assertion output paths", + diagnostics: ["INVALID_WRITE_PATH"], + policy: { + models: {c: {p: "boolean"}}, + blocks: [{assertion: "c..ok", conditions: ["c.p"]}, {assertion: "c.fine", conditions: ["c.p"]}], + }, + cases: [ + {input: {c: {p: true}}, output: {c: {p: true, fine: true}}, note: "question: the assertion with an invalid path writes nothing"}, + ], +} + +{ + name: "INVALID_WRITE_PATH gates the policy", + policy: { + models: {c: {p: "number"}}, + blocks: [{expression: "c.", value: "1"}, {expression: "c.b", value: "2"}], + }, + cases: [ + [{c: {p: 1}}, "!error: CompilationErrors [\"INVALID_WRITE_PATH\"]"], + ], +} + +// --- INPUT_OVERRIDE ---------------------------------------------------------------------------- + +{ + name: "INPUT_OVERRIDE: a table writing a declared property", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + models: {c: {age: "number", band: "string"}}, + blocks: [{table: "t", inputs: ["c.age"], outputs: ["c.band"], rules: [[">= 18", "'adult'"], ["", "'minor'"]]}], + }, + cases: [ + {input: {c: {age: 20, band: "given"}}, output: {c: {age: 20, band: "given"}}, note: "question: InputOverride is an error diagnostic; evaluation drops the write and keeps the input"}, + {input: {c: {age: 20}}, output: {c: {age: 20}}, note: "question: InputOverride is an error diagnostic; evaluation drops the write, so the property stays absent"}, + ], +} + +{ + name: "INPUT_OVERRIDE: a nested write below a declared property", + diagnostics: ["INPUT_OVERRIDE"], + policy: { + models: {c: {age: "number", info: "string"}}, + blocks: [{expression: "c.info.extra", value: "c.age"}], + }, + cases: [ + {input: {c: {age: 1, info: "x"}}, output: {c: {age: 1, info: "x"}}, note: "question: InputOverride is an error diagnostic; evaluation drops the write"}, + ], +} + +{ + name: "INPUT_OVERRIDE gates the policy", + policy: { + models: {c: {age: "number"}}, + blocks: [{expression: "c.age", value: "1"}], + }, + cases: [ + [{c: {age: 5}}, "!error: CompilationErrors [\"INPUT_OVERRIDE\"]"], + ], +} + +// --- SELF_REFERENCING_WRITE -------------------------------------------------------------------- + +{ + name: "SELF_REFERENCING_WRITE: a block accumulating into its own output", + diagnostics: ["SELF_REFERENCING_WRITE", "UNDEFINED_VARIABLE"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.t", value: "c.n"}, {expression: "c.u", value: "(c.u ?? 1) + c.t"}], + }, + cases: [ + [{c: {n: 1}}, {c: {n: 1, t: 1, u: 2}}], + {input: {c: {n: 1, u: 10}}, output: {c: {n: 1, t: 1, u: 11}}, note: "question: SelfReferencingWrite is an error diagnostic; evaluation reads the input value of the property being written"}, + ], +} + +{ + name: "SELF_REFERENCING_WRITE: a nested write reading its own parent object", + diagnostics: ["SELF_REFERENCING_WRITE", "UNDEFINED_VARIABLE"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.box.x", value: "c.box"}], + }, + cases: [ + [{c: {n: 1}}, {c: {n: 1, box: {x: null}}}], + ], +} + +{ + name: "SELF_REFERENCING_WRITE gates the policy", + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.u", value: "(c.u ?? 0) + c.n"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"SELF_REFERENCING_WRITE\", \"UNDEFINED_VARIABLE\"]"], + ], +} + +// --- UNREACHABLE_ENTITY_READ ------------------------------------------------------------------- + +{ + name: "UNREACHABLE_ENTITY_READ: an owner block reading a member property directly", + diagnostics: ["UNREACHABLE_ENTITY_READ"], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.x", value: "company.revenue"}], + }, + cases: [ + {input: {customer: {companies: [{revenue: 1}]}}, output: {customer: {companies: [{revenue: 1}], x: null}}, note: "question: the unreachable member read evaluates to null rather than failing"}, + {input: {customer: {companies: []}}, output: {customer: {companies: [], x: null}}, note: "question: the unreachable member read evaluates to null rather than failing"}, + ], +} + +{ + name: "UNREACHABLE_ENTITY_READ gates the policy", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.x", value: "company.revenue"}], + }, + cases: [ + [{customer: {companies: [{revenue: 1}]}}, "!error: CompilationErrors [\"UNREACHABLE_ENTITY_READ\"]"], + ], +} + +// An aggregate over the relationship is the reachable form: no diagnostic. +{ + name: "no UNREACHABLE_ENTITY_READ for an aggregate over the relationship", + diagnostics: [], + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.x", value: "sum(map(customer.companies, #.revenue))"}], + }, + cases: [ + [{customer: {companies: [{revenue: 1}, {revenue: 2}]}}, {customer: {companies: [{revenue: 1}, {revenue: 2}], x: 3}}], + [{customer: {companies: []}}, {customer: {companies: [], x: 0}}], + ], +} + +// --- PARTIAL_OBJECT_WRITE ---------------------------------------------------------------------- + +{ + name: "PARTIAL_OBJECT_WRITE: the whole object written before a nested leaf", + diagnostics: ["PARTIAL_OBJECT_WRITE"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.box", value: "{a: c.n}"}, {expression: "c.box.b", value: "c.n + 1"}], + }, + cases: [ + {input: {c: {n: 1}}, output: {c: {n: 1, box: {a: 1, b: 2}}}, note: "question: the diagnostic says the whole-object write overwrites the nested writes, yet here the nested leaf is merged into the object"}, + {input: {c: {n: 0}}, output: {c: {n: 0, box: {a: 0, b: 1}}}, note: "question: the diagnostic says the whole-object write overwrites the nested writes, yet here the nested leaf is merged into the object"}, + ], +} + +{ + name: "PARTIAL_OBJECT_WRITE: a nested leaf written before the whole object", + diagnostics: ["PARTIAL_OBJECT_WRITE"], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.box.b", value: "c.n + 1"}, {expression: "c.box", value: "{a: c.n}"}], + }, + cases: [ + {input: {c: {n: 1}}, output: {c: {n: 1, box: {b: 2}}}, note: "question: with the nested block first, the whole-object write is lost entirely; the result depends on block order"}, + {input: {c: {n: 0}}, output: {c: {n: 0, box: {b: 1}}}, note: "question: with the nested block first, the whole-object write is lost entirely; the result depends on block order"}, + ], +} + +{ + name: "PARTIAL_OBJECT_WRITE gates the policy", + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.box", value: "{a: c.n}"}, {expression: "c.box.b", value: "c.n + 1"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"PARTIAL_OBJECT_WRITE\"]"], + ], +} + +// --- UNSUPPORTED_NESTED_ITERATION -------------------------------------------------------------- + +{ + name: "UNSUPPORTED_NESTED_ITERATION: a write to a member two relationships deep", + diagnostics: ["UNSUPPORTED_NESTED_ITERATION"], + policy: { + models: {customer: {companies: "company[]"}, company: {employees: "employee[]"}, employee: {salary: "number"}}, + blocks: [{expression: "employee.rich", value: "employee.salary > 10"}], + }, + cases: [ + [{customer: {companies: [{employees: [{salary: 20}]}]}}, "!error: MissingRequiredInputs"], + [{customer: {companies: []}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "UNSUPPORTED_NESTED_ITERATION gates the policy", + policy: { + models: {customer: {companies: "company[]"}, company: {employees: "employee[]"}, employee: {salary: "number"}}, + blocks: [{expression: "employee.rich", value: "employee.salary > 10"}], + }, + cases: [ + [{customer: {companies: [{employees: [{salary: 20}]}]}}, "!error: CompilationErrors [\"UNSUPPORTED_NESTED_ITERATION\"]"], + ], +} + +// --- DATA_MODEL_COLLISION ---------------------------------------------------------------------- + +{ + name: "DATA_MODEL_COLLISION: a dictionary named like an entity", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + dictionaries: {c: ["a"]}, + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n + 1"}], + }, + cases: [ + [{c: {n: 1}}, {c: {n: 1, x: 2}}], + ], +} + +{ + name: "DATA_MODEL_COLLISION: a dictionary named like a global property", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + dictionaries: {mode: ["a"]}, + globals: {g: {mode: "string"}}, + blocks: [{expression: "x", value: "mode + '!'"}], + }, + cases: [ + [{mode: "z"}, {mode: "z", x: "z!"}], + ], +} + +{ + name: "DATA_MODEL_COLLISION: an entity named like a global property", + diagnostics: ["DATA_MODEL_COLLISION"], + policy: { + globals: {g: {c: "number"}}, + models: {c: {n: "number"}}, + blocks: [{expression: "x", value: "1"}], + }, + cases: [ + [{}, {x: 1}], + ], +} + +{ + name: "DATA_MODEL_COLLISION gates the policy", + policy: { + dictionaries: {c: ["a"]}, + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n + 1"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"DATA_MODEL_COLLISION\"]"], + ], +} + +// --- UNKNOWN_DATA_MODEL_TARGET ----------------------------------------------------------------- + +{ + name: "UNKNOWN_DATA_MODEL_TARGET: relationships and references to undeclared entities", + diagnostics: ["UNKNOWN_DATA_MODEL_TARGET"], + policy: { + models: {c: {friend: "ghost", pick: "&phantom"}}, + blocks: [{expression: "c.x", value: "1"}], + }, + cases: [ + [{c: {}}, {c: {x: 1}}], + {input: {c: {friend: {anything: 1}}}, output: {c: {friend: {anything: 1}, x: 1}}}, + ], +} + +{ + name: "UNKNOWN_DATA_MODEL_TARGET gates the policy", + policy: { + models: {c: {friend: "ghost"}}, + blocks: [{expression: "c.x", value: "1"}], + }, + cases: [ + [{c: {}}, "!error: CompilationErrors [\"UNKNOWN_DATA_MODEL_TARGET\"]"], + ], +} + +// --- DUPLICATE_PROPERTY ------------------------------------------------------------------------ + +{ + name: "DUPLICATE_PROPERTY: a property declared twice in one model", + diagnostics: ["DUPLICATE_PROPERTY"], + policy: {raw: {imports: [], blocks: [ + {id: "m", type: "dataModel", props: {data: {name: "c", scope: "entity", properties: [ + {id: "p1", name: "age", type: "number", array: false, optional: false}, + {id: "p2", name: "age", type: "string", array: false, optional: false}, + ]}}}, + {id: "b0", type: "expression", props: {data: {key: "c.x", value: "c.age"}}}, + ]}}, + cases: [ + [{c: {age: 1}}, {c: {age: 1, x: 1}}], + {input: {c: {age: "1"}}, output: "!error: InputValidationFailed", note: "question: the first declaration of a duplicated property wins"}, + ], +} + +{ + name: "DUPLICATE_PROPERTY gates the policy", + policy: {raw: {imports: [], blocks: [ + {id: "m", type: "dataModel", props: {data: {name: "c", scope: "entity", properties: [ + {id: "p1", name: "age", type: "number", array: false, optional: false}, + {id: "p2", name: "age", type: "number", array: false, optional: false}, + ]}}}, + {id: "b0", type: "expression", props: {data: {key: "c.x", value: "c.age"}}}, + ]}}, + cases: [ + [{c: {age: 1}}, "!error: CompilationErrors [\"DUPLICATE_PROPERTY\"]"], + ], +} + +// --- DUPLICATE_ENUM_VALUE ---------------------------------------------------------------------- + +{ + name: "DUPLICATE_ENUM_VALUE: a repeated inline enum value and dictionary value", + diagnostics: ["DUPLICATE_ENUM_VALUE"], + policy: { + dictionaries: {d: ["x", "x", "y"]}, + models: {c: {t: "string(a|a|b)", u: "d?"}}, + blocks: [{expression: "c.x", value: "c.t"}], + }, + cases: [ + [{c: {t: "a"}}, {c: {t: "a", x: "a"}}], + [{c: {t: "b", u: "y"}}, {c: {t: "b", u: "y", x: "b"}}], + [{c: {t: "z"}}, "!error: InputValidationFailed"], + [{c: {t: "a", u: "z"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "DUPLICATE_ENUM_VALUE gates the policy", + policy: { + models: {c: {t: "string(a|a)"}}, + blocks: [{expression: "c.x", value: "c.t"}], + }, + cases: [ + [{c: {t: "a"}}, "!error: CompilationErrors [\"DUPLICATE_ENUM_VALUE\"]"], + ], +} + +// --- INVALID_NAME ------------------------------------------------------------------------------ + +{ + name: "INVALID_NAME: entity and property names with spaces or a leading digit", + diagnostics: ["INVALID_NAME"], + policy: { + models: {"my entity": {age: "number"}, c: {"first name": "string", "2x": "number", n: "number"}}, + blocks: [{expression: "c.x", value: "c.n"}], + }, + cases: [ + [{c: {n: 1}}, {c: {n: 1, x: 1}}], + {input: {c: {n: 1, "2x": "not validated"}}, output: {c: {n: 1, "2x": "not validated", x: 1}}, note: "question: properties with invalid names are dropped from validation"}, + ], +} + +{ + name: "INVALID_NAME: a dictionary name with a dot", + diagnostics: ["INVALID_NAME"], + policy: { + dictionaries: {"a.b": ["x"]}, + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n"}], + }, + cases: [ + [{c: {n: 1}}, {c: {n: 1, x: 1}}], + ], +} + +{ + name: "INVALID_NAME gates the policy", + policy: { + models: {c: {"bad[name]": "string", n: "number"}}, + blocks: [{expression: "c.x", value: "c.n"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"INVALID_NAME\"]"], + ], +} + +// --- IMPORT_NOT_FOUND and CIRCULAR_IMPORT ------------------------------------------------------ + +{ + name: "IMPORT_NOT_FOUND gates the policy", + policy: { + imports: ["gone"], + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n"}], + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"IMPORT_NOT_FOUND\"]"], + [{}, "!error: CompilationErrors [\"IMPORT_NOT_FOUND\"]"], + ], +} + +{ + name: "CIRCULAR_IMPORT gates the policy", + policy: { + imports: ["other"], + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n"}], + }, + policies: {other: {imports: ["main"], blocks: [{expression: "c.y", value: "c.x + 1"}]}}, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"CIRCULAR_IMPORT\"]"], + ], +} + +{ + name: "CIRCULAR_IMPORT: a self import still evaluates through the workspace", + diagnostics: ["CIRCULAR_IMPORT"], + policy: { + imports: ["main"], + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n * 2"}], + }, + cases: [ + {input: {c: {n: 2}}, output: {c: {n: 2, x: 4}}, note: "question: a self import is a CircularImport error diagnostic, yet evaluation succeeds"}, + ], +} + +// --- Errors in other members of the unit ------------------------------------------------------- + +{ + name: "an error diagnostic in an imported policy gates the importer", + policy: { + imports: ["broken"], + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n"}], + }, + policies: {broken: {models: {c: {s: "string"}}, blocks: [{expression: "c.y", value: "c.s * 2"}]}}, + cases: [ + [{c: {n: 1, s: "a"}}, "!error: CompilationErrors [\"TYPE_MISMATCH\"]"], + {input: {c: {n: 1}}, goals: ["c.x"], output: "!error: CompilationErrors [\"TYPE_MISMATCH\"]"}, + ], +} + +{ + name: "an error diagnostic in a deep import gates the root", + policy: { + imports: ["mid"], + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n"}], + }, + policies: { + mid: {imports: ["leaf"], blocks: []}, + leaf: {models: {c: {n: "number"}}, blocks: [{expression: "c.n", value: "1"}]}, + }, + cases: [ + [{c: {n: 1}}, "!error: CompilationErrors [\"INPUT_OVERRIDE\"]"], + ], +} + +{ + name: "an error diagnostic in a workspace policy outside the unit does not gate", + diagnostics: [], + policy: { + models: {c: {n: "number"}}, + blocks: [{expression: "c.x", value: "c.n + 1"}], + }, + policies: {unrelated: {models: {c: {s: "string"}}, blocks: [{expression: "c.y", value: "c.s * 2"}]}}, + cases: [ + [{c: {n: 1}}, {c: {n: 1, x: 2}}], + [{c: {n: -1}}, {c: {n: -1, x: 0}}], + ], +} + +{ + name: "several error codes are reported together, sorted", + policy: { + models: {c: {n: "number", s: "string"}}, + blocks: [ + {expression: "c.n", value: "1"}, + {expression: "c.a", value: "c.s - 1"}, + {expression: "c.b", value: "(c.n"}, + ], + }, + cases: [ + [{c: {n: 1, s: "a"}}, "!error: CompilationErrors [\"INPUT_OVERRIDE\", \"PARSE_ERROR\", \"TYPE_MISMATCH\"]"], + ], +} + +{ + name: "several error codes evaluated through the workspace", + diagnostics: ["INPUT_OVERRIDE", "PARSE_ERROR", "TYPE_MISMATCH"], + policy: { + models: {c: {n: "number", s: "string"}}, + blocks: [ + {expression: "c.n", value: "1"}, + {expression: "c.a", value: "c.s - 1"}, + {expression: "c.b", value: "(c.n"}, + {expression: "c.ok", value: "c.n * 10"}, + ], + }, + cases: [ + [{c: {n: 2, s: "a"}}, "!error: ExpressionFailed"], + {input: {c: {n: 2, s: "a"}}, goals: ["c.ok"], output: {c: {n: 2, s: "a", ok: 20}}}, + {input: {c: {n: 2, s: "a"}}, goals: ["c.b"], output: "!error: ExpressionFailed"}, + ], +} + +// --- Warning-only policies evaluate normally --------------------------------------------------- + +{ + name: "empty expression, match and table blocks are warnings", + diagnostics: [], + policy: { + models: {c: {n: "number"}}, + blocks: [ + {expression: "c.a", value: ""}, + {match: "c.b", arms: []}, + {table: "t", inputs: ["c.n"], outputs: ["c.d"], rules: []}, + {expression: "c.e", value: "c.n + 1"}, + ], + }, + cases: [ + {input: {c: {n: 1}}, output: {c: {n: 1, b: null, d: null, e: 2}}}, + {input: {c: {n: 0}}, output: {c: {n: 0, b: null, d: null, e: 1}}}, + ], +} + +{ + name: "an empty assertion condition is a warning and is skipped", + diagnostics: [], + policy: { + models: {c: {p: "boolean", q: "boolean"}}, + blocks: [{assertion: "c.ok", conditions: ["c.p", "", "c.q"]}], + }, + cases: [ + [{c: {p: true, q: true}}, {c: {p: true, q: true, ok: true}}], + [{c: {p: true, q: false}}, {c: {p: true, q: false, ok: false}}], + [{c: {p: false, q: true}}, {c: {p: false, q: true, ok: false}}], + ], +} + +{ + name: "a table output column without a field is a warning", + diagnostics: [], + policy: { + models: {c: {n: "number"}}, + blocks: [{table: "t", inputs: ["c.n"], outputs: ["c.g", ""], rules: [["> 1", "'big'", "'ignored'"], ["", "'small'", "'ignored'"]]}], + }, + cases: [ + [{c: {n: 5}}, {c: {n: 5, g: "big"}}], + [{c: {n: 1}}, {c: {n: 1, g: "small"}}], + ], +} + +{ + name: "an assertion without an output path is a warning", + diagnostics: [], + policy: { + models: {c: {p: "boolean"}}, + blocks: [{assertion: "", conditions: ["c.p"]}, {expression: "c.copy", value: "c.p"}], + }, + cases: [ + [{c: {p: true}}, {c: {p: true, copy: true}}], + [{c: {p: false}}, {c: {p: false, copy: false}}], + ], +} + +// Linter findings (redundant `??`, redundant parentheses, duplicate table rows, a column that +// never discriminates, matches that could be tables) are hints, not evaluation errors. +{ + name: "linter findings do not gate evaluation", + policy: { + models: {c: {n: "number", m: "number"}}, + blocks: [ + {expression: "c.e", value: "((c.n))"}, + {expression: "c.f", value: "c.n ?? 0"}, + {table: "t2", inputs: ["c.n", "c.m"], outputs: ["c.g"], rules: [["> 1", "", "1"], ["> 1", "", "3"], ["", "", "0"]]}, + {match: "c.h", arms: [["c.n == 1", "'one'"], ["c.n == 2", "'two'"], ["c.n == 3", "'three'"], ["", "'many'"]]}, + ], + }, + cases: [ + [{c: {n: 1, m: 2}}, {c: {n: 1, m: 2, e: 1, f: 1, g: 0, h: "one"}}], + [{c: {n: 5, m: 2}}, {c: {n: 5, m: 2, e: 5, f: 5, g: 1, h: "many"}}], + [{c: {n: 3, m: 0}}, {c: {n: 3, m: 0, e: 3, f: 3, g: 1, h: "three"}}], + ], +} + +{ + name: "a comparison of a string with a number is not a diagnostic", + diagnostics: [], + policy: { + models: {c: {s: "string"}}, + blocks: [{expression: "c.x", value: "c.s == 1"}], + }, + cases: [ + [{c: {s: "a"}}, {c: {s: "a", x: false}}], + [{c: {s: "1"}}, {c: {s: "1", x: false}}], + ], +} diff --git a/core/engine/tests/spec/policy/33-generated-a.json5 b/core/engine/tests/spec/policy/33-generated-a.json5 new file mode 100644 index 00000000..499e6399 --- /dev/null +++ b/core/engine/tests/spec/policy/33-generated-a.json5 @@ -0,0 +1,2820 @@ +// Generated policies, set A. +// +// Generated by gen33.py + run33.py (`python3 run33.py a` in the generator directory of the +// round-three spec session), seed 330000. Suite i is built from seed 330000 + 100 * i + +// attempt, where attempt is the first candidate whose policy has no error diagnostics. +// +// Each suite has a random data model: a root entity with 3-6 primitive fields (number, string, +// boolean, date, enum; about 30% optional) and one relationship array to a child entity with +// 2-4 fields, sometimes a number global. Its blocks (3-8 random expression, match, assertion +// and table blocks, in document order or shuffled) write undeclared computed properties on the +// root, on every member and at the top level; later blocks read earlier ones, giving chains, +// aggregates over member computeds and members reading root computeds. Each suite has 12-30 +// random inputs: valid, missing optional, null optional, boundary values, empty relationships, +// unknown fields and invalid requests (missing or null required, wrong type). +// +// Outputs recorded from the driver; this chapter exists to differential-test the engines. + +// seed 330000 (attempt 0) +{ + name: "a 01: account/companies: 2 expression, 1 match, 3 table; 3 root, 3 per-member, 2 top-level computed", + policy: { + models: {account: {balance: "number", label: "string", dueDate: "date?", region: "string", score: "number?", companies: "company[]"}, company: {rate: "number", plan: "string(basic|plus|premium|trial)?", income: "number", years: "number?"}}, + blocks: [ + {table: "t1", inputs: ["(account.balance + (account.score ?? 0))", "account.balance"], outputs: ["account.eligible", "account.adjusted", "account.decision"], rules: [ + ["> 2", "<= 18", "", "", ""], + ["", "", "", "(account.score ?? 0) <= 250", "account.balance"], + ["", "", "", "account.balance == 50", "account.balance"], + ["<= 2", "", "account.balance > 3", "(account.score ?? 0) > 18", "(account.score ?? 0)"], + ["< 50", ">= 5", "(account.score ?? 0) > 0.5", "0.25 == 1", "account.balance"], + ["", "", "", "account.balance == 5", "(account.score ?? 0)"], + ]}, + {table: "t2", inputs: ["(min(map(account.companies, #.income)) ?? 0)"], outputs: ["flag"], rules: [ + ["0.5, 5", "'DE'"], + ["", ""], + ["<= 0.5", "(account.region + '-' + account.region)"], + ["1.5", "account.region"], + ["<= 0.5", "string((account.decision ?? 0))"], + ["", "(account.label + '-' + account.region)"], + ]}, + {match: "share", arms: [["account.adjusted != null", "(account.score ?? 0) in [50..64]"], ["account.eligible != null", "((account.adjusted ?? false) or (account.adjusted ?? false))"], ["", "(flag ?? '') == 'ok'"]]}, + {expression: "company.risk", value: "upper(((company.years ?? 0) >= (company.years ?? 0) ? (flag ?? '') : (share ? 'high' : account.region)))"}, + {expression: "company.tag", value: "len(company.risk)"}, + {table: "t6", hit: "collect", inputs: ["flag"], outputs: ["company.summary"], rules: [ + ["'ok'", "share"], + ["'DE'", "company.rate >= company.rate"], + ]}, + ], + }, + cases: [ + [{account: {balance: 344, label: " pad ", dueDate: "2024-02-29", region: "O'Neil", score: 7.25, companies: []}}, "!error: ExpressionFailed"], + [{account: {balance: 2, label: "Zed", dueDate: "2024-01-01", region: "O'Neil", companies: [{rate: 0.25, plan: "trial", income: 99999999999999999999, years: 100}, {rate: 5, income: 2}, {rate: 1.5, income: 1, years: -0.01}, {rate: 2, plan: "premium", income: 1e3, years: 10}]}}, {account: {adjusted: true, balance: 2, companies: [{income: 99999999999999999999, plan: "trial", rate: 0.25, risk: "ZED-O'NEIL", summary: [], tag: 10, years: 100}, {income: 2, rate: 5, risk: "ZED-O'NEIL", summary: [], tag: 10}, {income: 1, rate: 1.5, risk: "ZED-O'NEIL", summary: [], tag: 10, years: -0.01}, {income: 1000, plan: "premium", rate: 2, risk: "ZED-O'NEIL", summary: [], tag: 10, years: 10}], decision: 2, dueDate: "2024-01-01", eligible: false, label: "Zed", region: "O'Neil"}, flag: "Zed-O'Neil", share: false}], + [{account: {balance: 1.5, label: "NL", dueDate: "2024-01-01", region: "Zed", score: 50, companies: [{rate: 99.99, plan: false, income: 123456789.123, years: -0.01}, {rate: 3, plan: "premium", income: 2, years: 2}, {rate: 2, plan: "trial", income: 1.5, years: 2}, {rate: 2, plan: "trial", income: 0.000001, years: 0}, {rate: -1, plan: "premium", income: -0.5, years: 99.99}]}}, "!error: InputValidationFailed"], + [{account: {balance: 0.5, label: "a-b-c", dueDate: "2025-03-20T10:15:30Z", region: "O'Neil", score: 10, companies: [{rate: 0.5, plan: null, income: -1, years: null}, {rate: 123456789.123, plan: null, income: 2, years: 1e3}, {rate: 99999999999999999999, income: 0.5}, {rate: -1, plan: null, income: 1.5, years: -0.5}]}}, {account: {adjusted: true, balance: 0.5, companies: [{income: -1, plan: null, rate: 0.5, risk: "O'NEIL-O'NEIL", summary: [], tag: 13, years: null}, {income: 2, plan: null, rate: 123456789.123, risk: "O'NEIL-O'NEIL", summary: [], tag: 13, years: 1000}, {income: 0.5, rate: 99999999999999999999, risk: "O'NEIL-O'NEIL", summary: [], tag: 13}, {income: 1.5, plan: null, rate: -1, risk: "O'NEIL-O'NEIL", summary: [], tag: 13, years: -0.5}], decision: 0.5, dueDate: "2025-03-20T10:15:30Z", eligible: null, label: "a-b-c", region: "O'Neil", score: 10}, flag: "O'Neil-O'Neil", share: false}], + [{account: {balance: 123456789.123, label: "US", dueDate: "1990-06-15", region: "é ü", score: 0.5, companies: [{rate: 1, plan: "premium", income: 100, years: 0.1}]}}, {account: {adjusted: true, balance: 123456789.123, companies: [{income: 100, plan: "premium", rate: 1, risk: "US-É Ü", summary: [], tag: 8, years: 0.1}], decision: 123456789.123, dueDate: "1990-06-15", eligible: null, label: "US", region: "é ü", score: 0.5}, flag: "US-é ü", share: false}], + [{account: {balance: 250, label: "retail", dueDate: "2025-03-20T10:15:30Z", region: "retail", score: 18, companies: [{rate: -0.5, plan: "basic", income: 250, years: 1000}, {rate: 2.50, plan: "trial", income: 0.25, years: 2}, {rate: 5, plan: "premium", income: 1.5, years: 18}, {rate: 7.25, plan: "basic", income: 1, years: 0.1}, {rate: 1.5, plan: "basic", income: 1000, years: 250}]}}, {account: {adjusted: true, balance: 250, companies: [{income: 250, plan: "basic", rate: -0.5, risk: "RETAIL-RETAIL", summary: [], tag: 13, years: 1000}, {income: 0.25, plan: "trial", rate: 2.50, risk: "RETAIL-RETAIL", summary: [], tag: 13, years: 2}, {income: 1.5, plan: "premium", rate: 5, risk: "RETAIL-RETAIL", summary: [], tag: 13, years: 18}, {income: 1, plan: "basic", rate: 7.25, risk: "RETAIL-RETAIL", summary: [], tag: 13, years: 0.1}, {income: 1000, plan: "basic", rate: 1.5, risk: "RETAIL-RETAIL", summary: [], tag: 13, years: 250}], decision: 250, dueDate: "2025-03-20T10:15:30Z", eligible: null, label: "retail", region: "retail", score: 18}, flag: "retail-retail", share: false}], + [{account: {balance: 0.5, label: "3.5", dueDate: "2030-12-31", region: "VIP", score: 50, companies: [], extraField: {nested: true}}}, "!error: ExpressionFailed"], + [{account: {balance: 0.5, label: "US", dueDate: "2030-12-31", region: "O'Neil", score: null, companies: [{rate: 99999999999999999999, income: 250, years: 123456789.123}, {rate: 50, income: 0.25, years: 0.25}, {rate: 2, plan: "premium", income: 0.5}, {rate: 2, plan: null, income: 2, years: 1}]}}, {account: {adjusted: true, balance: 0.5, companies: [{income: 250, rate: 99999999999999999999, risk: "O'NEIL-O'NEIL", summary: [], tag: 13, years: 123456789.123}, {income: 0.25, rate: 50, risk: "O'NEIL-O'NEIL", summary: [], tag: 13, years: 0.25}, {income: 0.5, plan: "premium", rate: 2, risk: "O'NEIL-O'NEIL", summary: [], tag: 13}, {income: 2, plan: null, rate: 2, risk: "O'NEIL-O'NEIL", summary: [], tag: 13, years: 1}], decision: 0.5, dueDate: "2030-12-31", eligible: false, label: "US", region: "O'Neil", score: null}, flag: "O'Neil-O'Neil", share: false}], + [{account: {balance: 2, label: "é ü", dueDate: "2000-01-01", region: "retail", score: 10, companies: [{rate: 250, plan: "premium", income: 3, years: 3}, {rate: -0.5, plan: "plus", income: 0.5, years: -500}, {rate: 250, plan: "trial", income: 18, years: 0.25}]}}, {account: {adjusted: true, balance: 2, companies: [{income: 3, plan: "premium", rate: 250, risk: "DE", summary: [true], tag: 2, years: 3}, {income: 0.5, plan: "plus", rate: -0.5, risk: "DE", summary: [true], tag: 2, years: -500}, {income: 18, plan: "trial", rate: 250, risk: "DE", summary: [true], tag: 2, years: 0.25}], decision: 2, dueDate: "2000-01-01", eligible: null, label: "é ü", region: "retail", score: 10}, flag: "DE", share: false}], + [{account: {balance: 50, label: "US", region: "high", companies: [{rate: 10, plan: "basic", income: 18, years: -0}]}}, {account: {adjusted: true, balance: 50, companies: [{income: 18, plan: "basic", rate: 10, risk: "US-HIGH", summary: [], tag: 7, years: 0}], decision: 50, eligible: null, label: "US", region: "high"}, flag: "US-high", share: false}], + [{account: {balance: 99.99, label: "12", dueDate: "2024-02-29", region: "ok", score: 10, companies: [{rate: -1, income: 1.5, years: 5}, {rate: -500, plan: null, income: 0.5, years: null}, {rate: 123456789.123, income: 0.1}, {rate: 2, plan: "plus", income: 50, years: 0.000001}]}}, {account: {adjusted: true, balance: 99.99, companies: [{income: 1.5, rate: -1, risk: "OK-OK", summary: [], tag: 5, years: 5}, {income: 0.5, plan: null, rate: -500, risk: "OK-OK", summary: [], tag: 5, years: null}, {income: 0.1, rate: 123456789.123, risk: "OK-OK", summary: [], tag: 5}, {income: 50, plan: "plus", rate: 2, risk: "OK-OK", summary: [], tag: 5, years: 0.000001}], decision: 99.99, dueDate: "2024-02-29", eligible: null, label: "12", region: "ok", score: 10}, flag: "ok-ok", share: false}], + [{account: {balance: 0, label: "US", dueDate: "2030-12-31", region: "日本", score: 18, companies: [{rate: 18, plan: "basic", income: 2, years: 0.5}, {rate: 1, plan: "plus", income: 100, years: 65}, {rate: 2.50, plan: "basic", income: -0.01, years: 0}]}}, {account: {adjusted: true, balance: 0, companies: [{income: 2, plan: "basic", rate: 18, risk: "日本-日本", summary: [], tag: 13, years: 0.5}, {income: 100, plan: "plus", rate: 1, risk: "日本-日本", summary: [], tag: 13, years: 65}, {income: -0.01, plan: "basic", rate: 2.50, risk: "日本-日本", summary: [], tag: 13, years: 0}], decision: 0, dueDate: "2030-12-31", eligible: null, label: "US", region: "日本", score: 18}, flag: "日本-日本", share: false}], + [{account: {balance: 100, label: "ok", dueDate: "2000-01-01", region: "", companies: [{rate: 5, plan: "plus", income: 99999999999999999999, years: null}, {rate: 2, income: 5, years: 99999999999999999999}, {rate: 0.000001, plan: "plus", income: 3, years: null}, {rate: 2, income: 2, years: 1}]}}, {account: {adjusted: true, balance: 100, companies: [{income: 99999999999999999999, plan: "plus", rate: 5, risk: "OK-", summary: [], tag: 3, years: null}, {income: 5, rate: 2, risk: "OK-", summary: [], tag: 3, years: 99999999999999999999}, {income: 3, plan: "plus", rate: 0.000001, risk: "OK-", summary: [], tag: 3, years: null}, {income: 2, rate: 2, risk: "OK-", summary: [], tag: 3, years: 1}], decision: 100, dueDate: "2000-01-01", eligible: null, label: "ok", region: ""}, flag: "ok-", share: false}], + [{account: {balance: 65, label: "ok", dueDate: null, region: "DE", score: null, companies: [{rate: 10, plan: null, income: 0.5, years: null}]}}, {account: {adjusted: true, balance: 65, companies: [{income: 0.5, plan: null, rate: 10, risk: "DE", summary: [true], tag: 2, years: null}], decision: 65, dueDate: null, eligible: null, label: "ok", region: "DE", score: null}, flag: "DE", share: false}], + [{account: {balance: 5, label: "DE", dueDate: "2025-03-20T10:15:30Z", region: "ok", score: 5, companies: [{rate: 0.5, income: 0.5}]}}, {account: {adjusted: true, balance: 5, companies: [{income: 0.5, rate: 0.5, risk: "DE", summary: [true], tag: 2}], decision: 5, dueDate: "2025-03-20T10:15:30Z", eligible: true, label: "DE", region: "ok", score: 5}, flag: "DE", share: false}], + [{account: {balance: 2.50, label: "NL", dueDate: null, region: "DE", score: 0.5, companies: []}}, "!error: ExpressionFailed"], + [{account: {balance: 123456789.123, label: "-", dueDate: "2025-03-20", region: "DE", score: 0.5, companies: [{rate: 2, plan: "plus", income: 5, years: 5}, {rate: 0.5, plan: "premium", income: 1e3, years: 1.5}, {rate: 0.000001, plan: "plus", income: 0.1, years: 1}]}}, {account: {adjusted: true, balance: 123456789.123, companies: [{income: 5, plan: "plus", rate: 2, risk: "DE-DE", summary: [], tag: 5, years: 5}, {income: 1000, plan: "premium", rate: 0.5, risk: "DE-DE", summary: [], tag: 5, years: 1.5}, {income: 0.1, plan: "plus", rate: 0.000001, risk: "DE-DE", summary: [], tag: 5, years: 1}], decision: 123456789.123, dueDate: "2025-03-20", eligible: null, label: "-", region: "DE", score: 0.5}, flag: "DE-DE", share: false}], + [{account: {balance: 1e3, label: " pad ", dueDate: "2030-12-31", region: "DE", score: 1000000, companies: [{rate: 2, plan: false, income: 18, years: 99.99}]}}, "!error: InputValidationFailed"], + [{account: {balance: 5, label: "ok", dueDate: "1990-06-15", region: "ok", score: -0.01, companies: [{rate: 1.5, plan: "premium", income: -1, years: -1}, {rate: -0.5, plan: "plus", income: 3, years: 0.25}, {rate: 5, plan: "plus", income: 1, years: 5}, {rate: 0.5, plan: "basic", income: 0.5, years: 1}]}}, {account: {adjusted: true, balance: 5, companies: [{income: -1, plan: "premium", rate: 1.5, risk: "OK-OK", summary: [], tag: 5, years: -1}, {income: 3, plan: "plus", rate: -0.5, risk: "OK-OK", summary: [], tag: 5, years: 0.25}, {income: 1, plan: "plus", rate: 5, risk: "OK-OK", summary: [], tag: 5, years: 5}, {income: 0.5, plan: "basic", rate: 0.5, risk: "OK-OK", summary: [], tag: 5, years: 1}], decision: 5, dueDate: "1990-06-15", eligible: false, label: "ok", region: "ok", score: -0.01}, flag: "ok-ok", share: false}], + [{account: {balance: 99999999999999999999, label: "-", dueDate: "1990-06-15", region: "", score: 3, companies: []}}, "!error: ExpressionFailed"], + [{account: {balance: 65, label: "O'Neil", region: "retail", score: null, companies: []}}, "!error: ExpressionFailed"], + [{account: {balance: 2, label: "Zed", dueDate: null, region: "high", score: null, companies: [{rate: 99999999999999999999, plan: "basic", income: 18}]}}, {account: {adjusted: true, balance: 2, companies: [{income: 18, plan: "basic", rate: 99999999999999999999, risk: "ZED-HIGH", summary: [], tag: 8}], decision: 2, dueDate: null, eligible: false, label: "Zed", region: "high", score: null}, flag: "Zed-high", share: false}], + [{account: {balance: -0.01, label: "日本", dueDate: "2000-01-01", region: "3.5", score: 0, companies: [{rate: 0.1, plan: "premium", income: 1, years: -0.5}], extraField: "x"}}, {account: {adjusted: true, balance: -0.01, companies: [{income: 1, plan: "premium", rate: 0.1, risk: "日本-3.5", summary: [], tag: 10, years: -0.5}], decision: -0.01, dueDate: "2000-01-01", eligible: false, extraField: "x", label: "日本", region: "3.5", score: 0}, flag: "日本-3.5", share: false}], + [{account: {balance: 2.50, label: "abc", dueDate: "2024-02-29", region: "A1", score: null, companies: [{rate: 50, plan: "trial", income: 100}]}}, {account: {adjusted: true, balance: 2.50, companies: [{income: 100, plan: "trial", rate: 50, risk: "ABC-A1", summary: [], tag: 6}], decision: 2.50, dueDate: "2024-02-29", eligible: null, label: "abc", region: "A1", score: null}, flag: "abc-A1", share: false}], + [{account: {balance: 99999999999999999999, label: "abc", dueDate: "2024-02-29", region: " pad ", score: 5, companies: [{rate: 1, plan: false, income: 315, years: 10}, {rate: 0.5, plan: "trial", income: 3, years: -500}, {rate: 1e3, plan: "premium", income: -500, years: 0.5}, {rate: 0.5, plan: "premium", income: -1, years: 2}, {rate: 1, plan: "trial", income: 123456789.123, years: 1.5}]}}, "!error: InputValidationFailed"], + [{account: {balance: 250, label: "DE", dueDate: null, region: "ok", score: 2, companies: [{rate: -0.5, income: 18}]}}, {account: {adjusted: true, balance: 250, companies: [{income: 18, rate: -0.5, risk: "DE-OK", summary: [], tag: 5}], decision: 250, dueDate: null, eligible: null, label: "DE", region: "ok", score: 2}, flag: "DE-ok", share: false}], + [{account: {balance: 18, label: "NL", dueDate: "2025-03-20", region: "Oslo", score: -0.5, companies: [{rate: 250, plan: null, income: 1000, years: 18}]}}, {account: {adjusted: true, balance: 18, companies: [{income: 1000, plan: null, rate: 250, risk: "NL-OSLO", summary: [], tag: 7, years: 18}], decision: 18, dueDate: "2025-03-20", eligible: false, label: "NL", region: "Oslo", score: -0.5}, flag: "NL-Oslo", share: false}], + [{account: {balance: 1.5, label: "A1", dueDate: "2030-12-31", region: "A1", score: 0.5, companies: [{rate: -0.5, plan: "premium", income: 0.1, years: 250}, {rate: 1, plan: "premium", income: 0, years: 18}], extraField: {nested: true}}}, {account: {adjusted: true, balance: 1.5, companies: [{income: 0.1, plan: "premium", rate: -0.5, risk: "A1-A1", summary: [], tag: 5, years: 250}, {income: 0, plan: "premium", rate: 1, risk: "A1-A1", summary: [], tag: 5, years: 18}], decision: 1.5, dueDate: "2030-12-31", eligible: false, extraField: {nested: true}, label: "A1", region: "A1", score: 0.5}, flag: "A1-A1", share: false}], + [{account: {balance: 1000, label: "DE", dueDate: "2024-01-01", region: "x-y", score: 10, companies: []}}, "!error: ExpressionFailed"], + ], +} + +// seed 330100 (attempt 0) +{ + name: "a 02: customer/companies: 1 assertion, 2 expression, 2 match, 3 table; 6 root, 6 per-member, 0 top-level computed", + policy: { + models: {customer: {days: "number", tier: "string(gold|silver|bronze)?", qty: "number", companies: "company[]"}, company: {rate: "number", sku: "string?", vip: "boolean"}}, + blocks: [ + {assertion: "customer.review", conditions: [["or", "not (customer.days != customer.qty)", 1], ["and", "all(customer.companies, (#.vip and #.vip))", 1], ["or", "(customer.tier ?? '') != 'gold'", 0], ["or", "(customer.tier != null and some(customer.companies, (#.vip or #.vip)))", 0], ["or", "(max(map(customer.companies, #.rate)) ?? 0) < customer.days", 1]]}, + {table: "t2", hit: "collect", inputs: [null, "company.vip", "(company.sku ?? '')"], outputs: ["company.quota", "company.exposure"], rules: [ + ["(customer.review or customer.review)", "", "'VIP', 'retail'", "company.sku == null", ""], + ["(company.sku ?? '') in ['high', 'A1']", "true", "'x'", "customer.review", "len((company.sku ?? ''))"], + ["not (company.vip)", "", "$ != 'DE'", "customer.review", "18"], + ["not (customer.review)", "false", "", "some(customer.companies, #.rate != #.rate)", "company.rate"], + ["", "", "", "(customer.review or company.vip)", "sum(map(customer.companies, #.rate))"], + ]}, + {expression: "customer.bonus", value: "customer.tier == null"}, + {match: "company.ok", arms: [["(company.sku ?? '') in ['low', 'x']", "all(customer.companies, #.rate != #.rate)"], ["", "customer.review"]]}, + {match: "customer.adjusted", arms: [["(customer.review or customer.review)", "(customer.review ? customer.days : customer.qty)"], ["some(customer.companies, (#.ok or #.vip))", "customer.days"], ["(max(map(customer.companies, (min(#.exposure) ?? 0))) ?? 0) <= 1.5", "(1000 - customer.days)"], ["customer.tier != null", "ceil(customer.days)"], ["", "customer.qty"]]}, + {table: "t6", inputs: ["(customer.adjusted * customer.days)", null, "customer.days"], outputs: ["customer.eligible", "customer.decision"], rules: [ + ["", "customer.adjusted == customer.days", "!= 2", "customer.bonus", "customer.review"], + ["<= 0.25", "(customer.tier ?? '') in ['silver', 'bronze']", "[10..451]", "customer.review", "customer.bonus"], + ["", "(customer.bonus and customer.review)", "1", "", ""], + ["!= 250", "(customer.review and customer.review)", "> 100", "none(customer.companies, (#.vip and #.ok))", ""], + ["<= 0.25", "customer.tier == null", "<= 0.5", "customer.adjusted > 10", "customer.review"], + ["", "", "", "customer.bonus", ""], + ]}, + {expression: "customer.discount", value: "upper(string(customer.days))"}, + {table: "t8", hit: "collect", inputs: [null, "(company.rate * company.rate)", "company.rate"], outputs: ["company.summary", "company.flag", "company.band"], rules: [ + ["", "5, 5", "[100..511]", "customer.adjusted", "customer.discount", "(company.sku ?? '')"], + ["(company.sku ?? '') == 'ok'", "250, 1.5", "2", "sum(company.exposure)", "", "(customer.discount + '-' + customer.discount)"], + ["not ((customer.decision ?? false))", "< 1000", "", "customer.qty", "customer.discount", "'a'"], + ]}, + ], + }, + cases: [ + [{customer: {days: 1.5, tier: null, qty: 1.5, companies: [{rate: -500, vip: false}, {rate: 5, sku: "abc", vip: true}]}}, {customer: {adjusted: 1.5, bonus: true, companies: [{band: [], exposure: [18, -495], flag: [], ok: true, quota: [true, true], rate: -500, summary: [], vip: false}, {band: [], exposure: [-495], flag: [], ok: true, quota: [true], rate: 5, sku: "abc", summary: [], vip: true}], days: 1.5, decision: true, eligible: true, qty: 1.5, review: true, tier: null}}], + [{customer: {days: 0, tier: "gold", qty: 10, companies: [{rate: 2, sku: "x", vip: false}, {rate: 1000, sku: "a", vip: true}, {rate: 0, sku: "a", vip: true}]}}, {customer: {adjusted: 0, bonus: false, companies: [{band: [], exposure: [18, 1002], flag: [], ok: false, quota: [true, true], rate: 2, sku: "x", summary: [], vip: false}, {band: [], exposure: [1002], flag: [], ok: true, quota: [true], rate: 1000, sku: "a", summary: [], vip: true}, {band: [], exposure: [1002], flag: [], ok: true, quota: [true], rate: 0, sku: "a", summary: [], vip: true}], days: 0, decision: true, eligible: false, qty: 10, review: true, tier: "gold"}}], + [{customer: {days: 1, tier: "gold", qty: -1, companies: []}}, "!error: ExpressionFailed"], + [{customer: {days: 1000, tier: "silver", qty: 0.000001, companies: [{rate: 1, sku: "Oslo", vip: false}]}}, {customer: {adjusted: 1000, bonus: false, companies: [{band: [], exposure: [18, 1], flag: [], ok: true, quota: [true, true], rate: 1, sku: "Oslo", summary: [], vip: false}], days: 1000, decision: true, eligible: false, qty: 0.000001, review: true, tier: "silver"}}], + [{customer: {days: 18, tier: "gold", qty: 0.1, companies: [{rate: 99999999999999999999, sku: "Zed", vip: false}, {rate: 1, sku: "a-b-c", vip: true}]}}, "!error: ExpressionFailed"], + [{customer: {days: 99.99, tier: "bronze", qty: 1000, companies: [{rate: 2, sku: "DE", vip: true}, {rate: 99.99, sku: "O'Neil", vip: true}]}}, {customer: {adjusted: 99.99, bonus: false, companies: [{band: [], exposure: [101.99], flag: [], ok: true, quota: [true], rate: 2, sku: "DE", summary: [], vip: true}, {band: [], exposure: [101.99], flag: [], ok: true, quota: [true], rate: 99.99, sku: "O'Neil", summary: [], vip: true}], days: 99.99, decision: true, eligible: false, qty: 1000, review: true, tier: "bronze"}}], + [{customer: {days: 99999999999999999999, tier: null, qty: 0.5, companies: [{rate: 250, vip: false}]}}, {customer: {adjusted: 99999999999999999999, bonus: true, companies: [{band: [], exposure: [18, 250], flag: [], ok: true, quota: [true, true], rate: 250, summary: [], vip: false}], days: 99999999999999999999, decision: true, eligible: true, qty: 0.5, review: true, tier: null}}], + [{customer: {days: 0.1, qty: 7.25, companies: [{rate: 0.000001, sku: "x", vip: false}, {rate: 100, sku: null, vip: true}, {rate: 1000000, vip: true}]}}, {customer: {adjusted: 0.1, bonus: true, companies: [{band: ["a"], exposure: [18, 0.000001, 1000100.000001], flag: ["0.1"], ok: false, quota: [false, false, false], rate: 0.000001, sku: "x", summary: [7.25], vip: false}, {band: [], exposure: [1000100.000001], flag: [], ok: false, quota: [true], rate: 100, sku: null, summary: [], vip: true}, {band: [], exposure: [1000100.000001], flag: [], ok: false, quota: [true], rate: 1000000, summary: [], vip: true}], days: 0.1, decision: false, discount: "0.1", eligible: true, qty: 7.25, review: false}}], + [{customer: {tier: "gold", qty: 7.25, companies: [{rate: 18, sku: "VIP", vip: false}]}}, "!error: MissingRequiredInputs"], + [{customer: {days: 99.99, tier: "gold", qty: 7.25, companies: [{rate: 413, sku: "VIP", vip: true}], extraField: {nested: true}}}, {customer: {adjusted: 99.99, bonus: false, companies: [{band: [], exposure: [413], flag: [], ok: true, quota: [false, true], rate: 413, sku: "VIP", summary: [], vip: true}], days: 99.99, decision: true, eligible: false, extraField: {nested: true}, qty: 7.25, review: true, tier: "gold"}}], + [{customer: {days: 0.25, qty: 1000, companies: [{rate: 0.5, sku: "ok", vip: false}, {rate: 1000000, vip: true}, {rate: 1000000, sku: "a", vip: false}]}}, {customer: {adjusted: 0.25, bonus: true, companies: [{band: ["a"], exposure: [18, 0.5, 2000000.5], flag: ["0.25"], ok: false, quota: [false, false, false], rate: 0.5, sku: "ok", summary: [1000], vip: false}, {band: [], exposure: [2000000.5], flag: [], ok: false, quota: [true], rate: 1000000, summary: [], vip: true}, {band: [], exposure: [18, 1000000, 2000000.5], flag: [], ok: false, quota: [false, false, false], rate: 1000000, sku: "a", summary: [], vip: false}], days: 0.25, decision: false, discount: "0.25", eligible: true, qty: 1000, review: false}}], + [{customer: {days: 65, tier: "gold", qty: 1, companies: [{rate: 18, sku: "high", vip: false}, {rate: 1000, sku: "high", vip: true}]}}, {customer: {adjusted: 65, bonus: false, companies: [{band: [], exposure: [18, 1018], flag: [], ok: true, quota: [true, true], rate: 18, sku: "high", summary: [], vip: false}, {band: [], exposure: [1018], flag: [], ok: true, quota: [true], rate: 1000, sku: "high", summary: [], vip: true}], days: 65, decision: true, eligible: false, qty: 1, review: true, tier: "gold"}}], + [{customer: {days: 65, qty: -0, companies: [{rate: 0.000001, sku: "low", vip: false}, {rate: 18, sku: " pad ", vip: false}, {rate: 5, sku: "O'Neil", vip: false}, {rate: 100, sku: "x-y", vip: false}]}}, {customer: {adjusted: 0, bonus: true, companies: [{band: ["a"], exposure: [18, 0.000001, 123.000001], flag: ["65"], ok: false, quota: [false, false, false], rate: 0.000001, sku: "low", summary: [0], vip: false}, {band: ["a"], exposure: [18, 18, 123.000001], flag: ["65"], ok: false, quota: [false, false, false], rate: 18, sku: " pad ", summary: [0], vip: false}, {band: ["a"], exposure: [18, 5, 123.000001], flag: ["65"], ok: false, quota: [false, false, false], rate: 5, sku: "O'Neil", summary: [0], vip: false}, {band: [], exposure: [18, 100, 123.000001], flag: [], ok: false, quota: [false, false, false], rate: 100, sku: "x-y", summary: [], vip: false}], days: 65, decision: null, discount: "65", eligible: true, qty: 0, review: false}}], + [{customer: {days: 7.25, tier: "gold", qty: 0, companies: []}}, "!error: ExpressionFailed"], + [{customer: {days: 10, tier: null, qty: 18, companies: []}}, "!error: ExpressionFailed"], + [{customer: {days: 50, qty: 1000, companies: [{rate: 10, sku: "", vip: false}, {rate: -1, vip: false}, {rate: 1, sku: "a", vip: false}, {rate: 0.5, sku: null, vip: false}, {rate: 2.50, sku: "VIP", vip: true}]}}, {customer: {adjusted: 50, bonus: true, companies: [{band: [], exposure: [18, 13.00], flag: [], ok: true, quota: [true, true], rate: 10, sku: "", summary: [], vip: false}, {band: [], exposure: [18, 13.00], flag: [], ok: true, quota: [true, true], rate: -1, summary: [], vip: false}, {band: [], exposure: [18, 13.00], flag: [], ok: true, quota: [true, true], rate: 1, sku: "a", summary: [], vip: false}, {band: [], exposure: [18, 13.00], flag: [], ok: true, quota: [true, true], rate: 0.5, sku: null, summary: [], vip: false}, {band: [], exposure: [13.00], flag: [], ok: true, quota: [false, true], rate: 2.50, sku: "VIP", summary: [], vip: true}], days: 50, decision: true, eligible: true, qty: 1000, review: true}}], + [{customer: {days: 5, tier: "gold", qty: 5, companies: [{rate: 1000, sku: "A1", vip: false}, {rate: -1, sku: "high", vip: false}, {rate: 10, sku: "日本", vip: false}, {rate: 2, sku: "ok", vip: false}, {rate: 5, sku: "none", vip: true}]}}, {customer: {adjusted: 5, bonus: false, companies: [{band: [], exposure: [18, 1016], flag: [], ok: true, quota: [true, true], rate: 1000, sku: "A1", summary: [], vip: false}, {band: [], exposure: [18, 1016], flag: [], ok: true, quota: [true, true], rate: -1, sku: "high", summary: [], vip: false}, {band: [], exposure: [18, 1016], flag: [], ok: true, quota: [true, true], rate: 10, sku: "日本", summary: [], vip: false}, {band: [], exposure: [18, 1016], flag: [], ok: true, quota: [true, true], rate: 2, sku: "ok", summary: [], vip: false}, {band: [], exposure: [1016], flag: [], ok: true, quota: [true], rate: 5, sku: "none", summary: [], vip: true}], days: 5, decision: true, eligible: false, qty: 5, review: true, tier: "gold"}}], + [{customer: {days: 3, tier: "gold", qty: 1000, companies: [{rate: 1000, sku: "VIP", vip: true}], extraField: {nested: true}}}, {customer: {adjusted: 3, bonus: false, companies: [{band: [], exposure: [1000], flag: [], ok: true, quota: [false, true], rate: 1000, sku: "VIP", summary: [], vip: true}], days: 3, decision: true, eligible: false, extraField: {nested: true}, qty: 1000, review: true, tier: "gold"}}], + [{customer: {days: 1, tier: "silver", qty: 0, companies: [{rate: 3, sku: "DE", vip: true}, {rate: 0.5, sku: "VIP", vip: false}]}}, {customer: {adjusted: 1, bonus: false, companies: [{band: [], exposure: [3.5], flag: [], ok: true, quota: [true], rate: 3, sku: "DE", summary: [], vip: true}, {band: [], exposure: [18, 3.5], flag: [], ok: true, quota: [false, true, true], rate: 0.5, sku: "VIP", summary: [], vip: false}], days: 1, decision: true, eligible: false, qty: 0, review: true, tier: "silver"}}], + [{customer: {days: -1, tier: "gold", qty: 10, companies: [{rate: 18, sku: "ok", vip: false}, {rate: 2, sku: "US", vip: false}, {rate: 50, sku: "VIP", vip: true}]}}, {customer: {adjusted: -1, bonus: false, companies: [{band: [], exposure: [18, 70], flag: [], ok: true, quota: [true, true], rate: 18, sku: "ok", summary: [], vip: false}, {band: [], exposure: [18, 70], flag: [], ok: true, quota: [true, true], rate: 2, sku: "US", summary: [], vip: false}, {band: [], exposure: [70], flag: [], ok: true, quota: [false, true], rate: 50, sku: "VIP", summary: [], vip: true}], days: -1, decision: true, eligible: false, qty: 10, review: true, tier: "gold"}}], + [{customer: {days: 1.5, tier: "bronze", qty: 1000, companies: [{rate: 10, sku: "A1", vip: true}]}}, {customer: {adjusted: 1.5, bonus: false, companies: [{band: [], exposure: [10], flag: [], ok: true, quota: [true], rate: 10, sku: "A1", summary: [], vip: true}], days: 1.5, decision: true, eligible: false, qty: 1000, review: true, tier: "bronze"}}], + [{customer: {days: 5, tier: "silver", qty: 2.50, companies: [{rate: 1.5, sku: "high", vip: true}, {rate: 5, sku: "a", vip: false}]}}, {customer: {adjusted: 5, bonus: false, companies: [{band: [], exposure: [6.5], flag: [], ok: true, quota: [true], rate: 1.5, sku: "high", summary: [], vip: true}, {band: [], exposure: [18, 6.5], flag: [], ok: true, quota: [true, true], rate: 5, sku: "a", summary: [], vip: false}], days: 5, decision: true, eligible: false, qty: 2.50, review: true, tier: "silver"}}], + [{customer: {days: 0.5, tier: false, qty: 18, companies: [{rate: 1000000, sku: "A1", vip: true}]}}, "!error: InputValidationFailed"], + [{customer: {days: 2, tier: "gold", qty: 10, companies: [{rate: 1000, sku: "none", vip: false}, {rate: 10, vip: false}]}}, {customer: {adjusted: 2, bonus: false, companies: [{band: [], exposure: [18, 1000, 1010], flag: [], ok: false, quota: [false, false, false], rate: 1000, sku: "none", summary: [], vip: false}, {band: ["a"], exposure: [18, 10, 1010], flag: ["2"], ok: false, quota: [false, false, false], rate: 10, summary: [10], vip: false}], days: 2, decision: null, discount: "2", eligible: false, qty: 10, review: false, tier: "gold"}}], + [{customer: {days: -0.01, tier: "bronze", qty: 5, companies: []}}, "!error: ExpressionFailed"], + [{customer: {days: 0.5, tier: "silver", qty: 1.5, companies: [{rate: -0, sku: "A1", vip: false}]}}, {customer: {adjusted: 0.5, bonus: false, companies: [{band: [], exposure: [18, 0], flag: [], ok: true, quota: [true, true], rate: 0, sku: "A1", summary: [], vip: false}], days: 0.5, decision: true, eligible: false, qty: 1.5, review: true, tier: "silver"}}], + [{customer: {days: 250, tier: "gold", qty: 1, companies: [{rate: 250, sku: " pad ", vip: true}]}}, {customer: {adjusted: 250, bonus: false, companies: [{band: [], exposure: [250], flag: [], ok: true, quota: [true], rate: 250, sku: " pad ", summary: [], vip: true}], days: 250, decision: true, eligible: false, qty: 1, review: true, tier: "gold"}}], + [{customer: {days: 10, tier: "bronze", qty: 18, companies: [{rate: 65, sku: "A1", vip: false}, {rate: -1, vip: false}, {rate: 1.5, vip: false}, {rate: 250, sku: null, vip: true}]}}, {customer: {adjusted: 10, bonus: false, companies: [{band: [], exposure: [18, 315.5], flag: [], ok: true, quota: [true, true], rate: 65, sku: "A1", summary: [], vip: false}, {band: [], exposure: [18, 315.5], flag: [], ok: true, quota: [true, true], rate: -1, summary: [], vip: false}, {band: [], exposure: [18, 315.5], flag: [], ok: true, quota: [true, true], rate: 1.5, summary: [], vip: false}, {band: [], exposure: [315.5], flag: [], ok: true, quota: [true], rate: 250, sku: null, summary: [], vip: true}], days: 10, decision: true, eligible: false, qty: 18, review: true, tier: "bronze"}}], + ], +} + +// seed 330200 (attempt 0) +{ + name: "a 03: claim/lines: 1 expression, 2 match, 1 table; 1 root, 4 per-member, 1 top-level computed", + policy: { + models: {claim: {price: "number?", active: "boolean", days: "number?", priority: "boolean", insured: "boolean", lines: "line[]"}, line: {weight: "number", days: "number", score: "number"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {match: "claim.level", arms: [["none(claim.lines, not (#.weight == 18))", "count(claim.lines, #.days <= #.days) > 100"], ["(claim.days ?? 0) <= 2", "(claim.insured and claim.priority)"], ["not (claim.active)", "claim.insured"], ["none(claim.lines, not (#.score > 2))", "(claim.price ?? 0) < points"], ["", "not (claim.insured)"]]}, + {match: "points", arms: [["(min(map(claim.lines, #.days)) ?? 0) < (claim.price ?? 0)", "(claim.days ?? 0)"], ["claim.days == null", "baseRate"], ["((claim.days ?? 0) + baseRate) == 2", "3"], ["((claim.days ?? 0) * (claim.price ?? 0)) != (claim.price ?? 0)", "abs((baseRate * baseRate))"], ["", "((claim.days ?? 0) * 100)"]]}, + {expression: "line.decision", value: "((line.grade ?? '') + '-' + (line.grade ?? ''))"}, + {table: "t2", inputs: ["points", "(line.weight) / (abs(baseRate) + 1)"], outputs: ["line.grade", "line.summary", "line.quota[]"], rules: [ + ["> 100", "[100..233]", "'US'", "", "line.weight"], + ["", ">= 18", "'high'", "", "(claim.active ? 250 : points)"], + ["", "250, 18", "string((claim.price ?? 0))", "baseRate", "baseRate"], + ]}, + ], + }, + cases: [ + [{baseRate: -2, claim: {price: 1, active: false, days: 18, priority: false, insured: true, lines: []}}, "!error: ExpressionFailed"], + [{baseRate: 100, claim: {price: -500, active: false, days: 18, priority: true, insured: true, lines: [{days: 123456789.123, score: 2.50}]}}, "!error: ExpressionFailed"], + [{baseRate: -2, claim: {price: 1e3, active: true, days: -0, priority: false, insured: true, lines: [{weight: -500, days: -0, score: 5}]}}, {baseRate: -2, claim: {active: true, days: 0, insured: true, level: false, lines: [{days: 0, decision: "-", grade: null, quota: [], score: 5, summary: null, weight: -500}], price: 1000, priority: false}, points: 0}], + [{baseRate: 100, claim: {price: 1, active: false, days: 100, priority: true, insured: true, lines: [{weight: 2.50, days: 250, score: 1e3}, {weight: 2, days: -500, score: 0.000001}, {weight: 100, days: 2, score: 0}]}}, {baseRate: 100, claim: {active: false, days: 100, insured: true, level: true, lines: [{days: 250, decision: "-", grade: null, quota: [], score: 1000, summary: null, weight: 2.50}, {days: -500, decision: "-", grade: null, quota: [], score: 0.000001, summary: null, weight: 2}, {days: 2, decision: "-", grade: null, quota: [], score: 0, summary: null, weight: 100}], price: 1, priority: true}, points: 100}], + [{baseRate: -2, claim: {active: false, priority: true, insured: false, lines: [{weight: 18, days: 0, score: 100}, {weight: 100, days: 99999999999999999999, score: 1000}, {weight: 18, days: 65, score: 3}, {weight: 0.5, days: 1, score: 1000000}, {weight: 18, days: -0.5, score: 0}]}}, {baseRate: -2, claim: {active: false, insured: false, level: false, lines: [{days: 0, decision: "-", grade: null, quota: [], score: 100, summary: null, weight: 18}, {days: 99999999999999999999, decision: "high-high", grade: "high", quota: [0], score: 1000, summary: null, weight: 100}, {days: 65, decision: "-", grade: null, quota: [], score: 3, summary: null, weight: 18}, {days: 1, decision: "-", grade: null, quota: [], score: 1000000, summary: null, weight: 0.5}, {days: -0.5, decision: "-", grade: null, quota: [], score: 0, summary: null, weight: 18}], priority: true}, points: 0}], + [{baseRate: 0, claim: {price: 7.25, active: true, days: 2, priority: true, insured: true, lines: []}}, "!error: ExpressionFailed"], + [{baseRate: 0, claim: {price: null, active: false, days: null, priority: true, insured: true, lines: [{weight: 100, days: -1, score: 119}, {weight: 100, days: 250, score: 5}]}}, {baseRate: 0, claim: {active: false, days: null, insured: true, level: true, lines: [{days: -1, decision: "high-high", grade: "high", quota: [0], score: 119, summary: null, weight: 100}, {days: 250, decision: "high-high", grade: "high", quota: [0], score: 5, summary: null, weight: 100}], price: null, priority: true}, points: 0}], + [{baseRate: 1, claim: {price: 65, active: false, days: 0, priority: true, insured: false, lines: [{weight: 2, days: 250, score: 1}, {weight: 18, days: 0, score: -1}]}}, {baseRate: 1, claim: {active: false, days: 0, insured: false, level: false, lines: [{days: 250, decision: "-", grade: null, quota: [], score: 1, summary: null, weight: 2}, {days: 0, decision: "-", grade: null, quota: [], score: -1, summary: null, weight: 18}], price: 65, priority: true}, points: 0}], + [{baseRate: 1, claim: {price: null, active: true, priority: true, insured: true, lines: [{weight: 2, days: 1, score: 100}, {weight: 123456789.123, days: 100, score: 2}]}}, {baseRate: 1, claim: {active: true, insured: true, level: true, lines: [{days: 1, decision: "-", grade: null, quota: [], score: 100, summary: null, weight: 2}, {days: 100, decision: "high-high", grade: "high", quota: [250], score: 2, summary: null, weight: 123456789.123}], price: null, priority: true}, points: 1}], + [{baseRate: 1, claim: {price: 99999999999999999999, active: true, days: 0.5, priority: true, insured: false, lines: [{weight: -500, days: 18, score: 99.99}, {weight: 18, days: 18, score: 2}, {weight: 1, days: 250, score: 1e3}]}}, {baseRate: 1, claim: {active: true, days: 0.5, insured: false, level: false, lines: [{days: 18, decision: "-", grade: null, quota: [], score: 99.99, summary: null, weight: -500}, {days: 18, decision: "-", grade: null, quota: [], score: 2, summary: null, weight: 18}, {days: 250, decision: "-", grade: null, quota: [], score: 1000, summary: null, weight: 1}], price: 99999999999999999999, priority: true}, points: 0.5}], + [{baseRate: 100, claim: {price: 100, active: true, days: 123456789.123, priority: true, insured: false, lines: []}}, "!error: ExpressionFailed"], + [{baseRate: 10, claim: {price: 5, active: false, days: 1, priority: true, insured: true, lines: [{weight: 0, days: 65, score: 1}, {weight: 99999999999999999999, days: 2, score: 100}]}}, {baseRate: 10, claim: {active: false, days: 1, insured: true, level: true, lines: [{days: 65, decision: "-", grade: null, quota: [], score: 1, summary: null, weight: 0}, {days: 2, decision: "high-high", grade: "high", quota: [1], score: 100, summary: null, weight: 99999999999999999999}], price: 5, priority: true}, points: 1}], + [{baseRate: 1, claim: {price: 100, active: true, days: 250, priority: false, insured: false, lines: [{weight: 1000000, days: 1e3, score: -0}, {weight: 18, days: -0.01, score: 18}, {weight: -0, days: 100, score: 2}, {weight: 250, days: 5, score: 2}], extraField: 1}}, {baseRate: 1, claim: {active: true, days: 250, extraField: 1, insured: false, level: true, lines: [{days: 1000, decision: "high-high", grade: "high", quota: [250], score: 0, summary: null, weight: 1000000}, {days: -0.01, decision: "-", grade: null, quota: [], score: 18, summary: null, weight: 18}, {days: 100, decision: "-", grade: null, quota: [], score: 2, summary: null, weight: 0}, {days: 5, decision: "US-US", grade: "US", quota: [250, 250], score: 2, summary: null, weight: 250}], price: 100, priority: false}, points: 250}], + [{baseRate: 0.5, claim: {price: -1, active: false, days: 2.50, priority: false, insured: true, lines: []}}, "!error: ExpressionFailed"], + [{baseRate: 10, claim: {price: 18, active: true, days: 1, priority: false, insured: true, lines: [{weight: 99999999999999999999, days: 100, score: 1}, {weight: 100, days: 2, score: 1}], extraField: {nested: true}}}, {baseRate: 10, claim: {active: true, days: 1, extraField: {nested: true}, insured: true, level: false, lines: [{days: 100, decision: "high-high", grade: "high", quota: [250], score: 1, summary: null, weight: 99999999999999999999}, {days: 2, decision: "-", grade: null, quota: [], score: 1, summary: null, weight: 100}], price: 18, priority: false}, points: 1}], + [{baseRate: 0.5, claim: {price: 1000, active: false, days: -0.01, priority: true, insured: true, lines: []}}, "!error: ExpressionFailed"], + [{baseRate: 0.5, claim: {price: 1e3, active: true, days: null, priority: false, insured: true, lines: []}}, "!error: ExpressionFailed"], + [{baseRate: 100, claim: {price: 123456789.123, active: true, days: 432, priority: false, insured: false, lines: [{weight: 100, days: 44, score: 5}]}}, {baseRate: 100, claim: {active: true, days: 432, insured: false, level: false, lines: [{days: 44, decision: "-", grade: null, quota: [], score: 5, summary: null, weight: 100}], price: 123456789.123, priority: false}, points: 432}], + [{baseRate: -2, claim: {price: 18, active: false, days: 1, priority: false, insured: true, lines: []}}, "!error: ExpressionFailed"], + [{baseRate: 10, claim: {price: null, active: false, days: null, priority: false, insured: false, lines: [{weight: 0, days: 100, score: 2}]}}, {baseRate: 10, claim: {active: false, days: null, insured: false, level: false, lines: [{days: 100, decision: "-", grade: null, quota: [], score: 2, summary: null, weight: 0}], price: null, priority: false}, points: 10}], + [{baseRate: 1, claim: {price: 2, active: true, days: 1.5, priority: false, insured: false, lines: [{weight: 5, days: 100, score: 1000000}, {weight: 0.5, days: 65, score: 5}, {weight: 3, days: 18, score: 250}, {weight: -0.01, days: 1e3, score: 7.25}]}}, {baseRate: 1, claim: {active: true, days: 1.5, insured: false, level: false, lines: [{days: 100, decision: "-", grade: null, quota: [], score: 1000000, summary: null, weight: 5}, {days: 65, decision: "-", grade: null, quota: [], score: 5, summary: null, weight: 0.5}, {days: 18, decision: "-", grade: null, quota: [], score: 250, summary: null, weight: 3}, {days: 1000, decision: "-", grade: null, quota: [], score: 7.25, summary: null, weight: -0.01}], price: 2, priority: false}, points: 1}], + [{baseRate: 10, claim: {price: 65, active: true, days: null, priority: false, insured: false, lines: [{weight: 100, days: 2, score: 100}, {weight: 1, days: 100, score: 100}, {weight: -500, days: 0, score: 18}, {weight: 1e3, days: 1, score: -0.01}, {weight: 7.25, days: 18, score: 487}]}}, {baseRate: 10, claim: {active: true, days: null, insured: false, level: false, lines: [{days: 2, decision: "-", grade: null, quota: [], score: 100, summary: null, weight: 100}, {days: 100, decision: "-", grade: null, quota: [], score: 100, summary: null, weight: 1}, {days: 0, decision: "-", grade: null, quota: [], score: 18, summary: null, weight: -500}, {days: 1, decision: "high-high", grade: "high", quota: [250], score: -0.01, summary: null, weight: 1000}, {days: 18, decision: "-", grade: null, quota: [], score: 487, summary: null, weight: 7.25}], price: 65, priority: false}, points: 0}], + [{baseRate: 1, claim: {price: 18, active: true, days: 100, priority: true, insured: false, lines: [{weight: 250, days: 100, score: 5}, {weight: 2.50, days: 486, score: 100}]}}, {baseRate: 1, claim: {active: true, days: 100, insured: false, level: false, lines: [{days: 100, decision: "high-high", grade: "high", quota: [250], score: 5, summary: null, weight: 250}, {days: 486, decision: "-", grade: null, quota: [], score: 100, summary: null, weight: 2.50}], price: 18, priority: true}, points: 1}], + [{baseRate: 0.5, claim: {price: 18, active: true, days: 1.5, priority: false, insured: false, lines: [{weight: 100, days: 65, score: 250}]}}, {baseRate: 0.5, claim: {active: true, days: 1.5, insured: false, level: false, lines: [{days: 65, decision: "high-high", grade: "high", quota: [250], score: 250, summary: null, weight: 100}], price: 18, priority: false}, points: 3}], + ], +} + +// seed 330300 (attempt 0) +{ + name: "a 04: applicant/parcels: 2 assertion, 2 expression, 1 match; 1 root, 4 per-member, 0 top-level computed", + policy: { + models: {applicant: {score: "number", country: "string", sku: "string", channel: "string", kind: "string(retail|corporate)", parcels: "parcel[]"}, parcel: {years: "number", tier: "string(gold|silver|bronze)"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {match: "applicant.net", arms: [["none(applicant.parcels, #.years == #.years)", "round(applicant.score)"], ["(factor == 0 and factor > 2)", "count(applicant.parcels, #.years >= #.years)"], ["not (applicant.score > 100)", "(applicant.score + applicant.score)"], ["not (all(applicant.parcels, (#.exposure or #.exposure)))", "((factor * factor)) / (abs((factor * factor)) + 1)"], ["", "min([applicant.score, 5])"]]}, + {expression: "parcel.segment", value: "(string(applicant.net) + '-' + applicant.channel)"}, + {assertion: "parcel.fee", conditions: [["and", "none(applicant.parcels, #.years == 1)", 1], ["and", "(parcel.years == factor and all(applicant.parcels, len(#.segment) > 2))", 1], ["or", "not (applicant.kind in ['corporate', 'retail'])", 0], ["or", "none(applicant.parcels, #.tier != 'bronze')", 0]]}, + {assertion: "parcel.margin", conditions: [["or", "(parcel.exposure ? applicant.score : factor) > applicant.score", 0], ["and", "applicant.score < applicant.score", 2]]}, + {expression: "parcel.exposure", value: "parcel.tier == 'silver'"}, + ], + }, + cases: [ + [{factor: 10, applicant: {score: -1, country: "DE", sku: "é ü", channel: "high", kind: "corporate", parcels: [{years: 0, tier: "gold"}]}}, {applicant: {channel: "high", country: "DE", kind: "corporate", net: -2, parcels: [{exposure: false, fee: false, margin: true, segment: "-2-high", tier: "gold", years: 0}], score: -1, sku: "é ü"}, factor: 10}], + [{factor: 10, applicant: {score: 123456789.123, country: "a-b-c", sku: "-", channel: "Oslo", kind: "corporate", parcels: [{years: 18, tier: "silver"}, {years: 10, tier: "gold"}]}}, {applicant: {channel: "Oslo", country: "a-b-c", kind: "corporate", net: 0.9900990099009900990099009901, parcels: [{exposure: true, fee: false, margin: false, segment: "0.9900990099009900990099009901-Oslo", tier: "silver", years: 18}, {exposure: false, fee: false, margin: false, segment: "0.9900990099009900990099009901-Oslo", tier: "gold", years: 10}], score: 123456789.123, sku: "-"}, factor: 10}], + [{factor: 0, applicant: {score: 0.000001, country: "high", sku: "x-y", channel: "3.5", kind: "retail", parcels: []}}, {applicant: {channel: "3.5", country: "high", kind: "retail", net: 0, parcels: [], score: 0.000001, sku: "x-y"}, factor: 0}], + [{factor: 0, applicant: {score: 10, country: "gold", sku: "a", channel: "-", kind: "corporate", parcels: []}}, {applicant: {channel: "-", country: "gold", kind: "corporate", net: 10, parcels: [], score: 10, sku: "a"}, factor: 0}], + [{factor: -2, applicant: {score: 0.5, country: "a-b-c", sku: "日本", channel: "Zed", kind: "corporate", parcels: [{years: 1000000, tier: "silver"}, {years: -0.5, tier: "bronze"}]}}, {applicant: {channel: "Zed", country: "a-b-c", kind: "corporate", net: 1.0, parcels: [{exposure: true, fee: false, margin: false, segment: "1.0-Zed", tier: "silver", years: 1000000}, {exposure: false, fee: false, margin: false, segment: "1.0-Zed", tier: "bronze", years: -0.5}], score: 0.5, sku: "日本"}, factor: -2}], + [{factor: 0, applicant: {score: 5, country: "x-y", sku: "12", channel: "a-b-c", kind: "retail", parcels: [{years: 1000000, tier: "silver"}]}}, {applicant: {channel: "a-b-c", country: "x-y", kind: "retail", net: 10, parcels: [{exposure: true, fee: false, margin: false, segment: "10-a-b-c", tier: "silver", years: 1000000}], score: 5, sku: "12"}, factor: 0}], + [{factor: -2, applicant: {score: 2, country: "DE", sku: "Oslo", channel: "high", kind: "retail", parcels: [{years: 65, tier: "gold"}, {years: 0.5, tier: "gold"}]}}, {applicant: {channel: "high", country: "DE", kind: "retail", net: 4, parcels: [{exposure: false, fee: false, margin: false, segment: "4-high", tier: "gold", years: 65}, {exposure: false, fee: false, margin: false, segment: "4-high", tier: "gold", years: 0.5}], score: 2, sku: "Oslo"}, factor: -2}], + [{factor: 10, applicant: {score: 100, country: "abc", sku: "A1", channel: "-", kind: "retail", parcels: [{years: 18, tier: "bronze"}, {years: 0.000001, tier: "bronze"}, {years: 100, tier: "silver"}, {years: 0.000001, tier: "bronze"}]}}, {applicant: {channel: "-", country: "abc", kind: "retail", net: 200, parcels: [{exposure: false, fee: false, margin: false, segment: "200--", tier: "bronze", years: 18}, {exposure: false, fee: false, margin: false, segment: "200--", tier: "bronze", years: 0.000001}, {exposure: true, fee: false, margin: false, segment: "200--", tier: "silver", years: 100}, {exposure: false, fee: false, margin: false, segment: "200--", tier: "bronze", years: 0.000001}], score: 100, sku: "A1"}, factor: 10}], + [{factor: 1, applicant: {score: -0.5, country: "Oslo", sku: "NL", channel: "Oslo", kind: "retail", parcels: []}}, {applicant: {channel: "Oslo", country: "Oslo", kind: "retail", net: -1, parcels: [], score: -0.5, sku: "NL"}, factor: 1}], + [{factor: 100, applicant: {score: 0.1, country: "US", sku: "12", channel: "", kind: "retail", parcels: [{years: 2, tier: "silver"}, {years: 5, tier: "gold"}]}}, {applicant: {channel: "", country: "US", kind: "retail", net: 0.2, parcels: [{exposure: true, fee: false, margin: false, segment: "0.2-", tier: "silver", years: 2}, {exposure: false, fee: false, margin: true, segment: "0.2-", tier: "gold", years: 5}], score: 0.1, sku: "12"}, factor: 100}], + [{factor: 100, applicant: {score: 5, country: "Oslo", sku: "Oslo", channel: "Zed", kind: "retail", parcels: [{years: 0, tier: "gold"}, {years: 2.50, tier: "bronze"}]}}, {applicant: {channel: "Zed", country: "Oslo", kind: "retail", net: 10, parcels: [{exposure: false, fee: false, margin: true, segment: "10-Zed", tier: "gold", years: 0}, {exposure: false, fee: false, margin: true, segment: "10-Zed", tier: "bronze", years: 2.50}], score: 5, sku: "Oslo"}, factor: 100}], + [{factor: 1, applicant: {score: 5, country: "a", sku: "O'Neil", channel: "3.5", kind: "retail", parcels: [{years: 2, tier: "gold"}, {years: 65, tier: "silver"}, {years: -0, tier: "silver"}]}}, {applicant: {channel: "3.5", country: "a", kind: "retail", net: 10, parcels: [{exposure: false, fee: false, margin: false, segment: "10-3.5", tier: "gold", years: 2}, {exposure: true, fee: false, margin: false, segment: "10-3.5", tier: "silver", years: 65}, {exposure: true, fee: false, margin: false, segment: "10-3.5", tier: "silver", years: 0}], score: 5, sku: "O'Neil"}, factor: 1}], + [{factor: 10, applicant: {score: 18, country: "high", sku: "Zed", channel: 5, kind: "retail", parcels: [{years: 7.25, tier: "gold"}, {years: 100, tier: "silver"}, {years: 0.5, tier: "bronze"}, {years: 100, tier: "gold"}]}}, "!error: InputValidationFailed"], + [{factor: 0, applicant: {score: -0.5, country: "VIP", sku: "gold", channel: "gold", kind: "retail", parcels: [{years: -1, tier: "silver"}]}}, {applicant: {channel: "gold", country: "VIP", kind: "retail", net: -1.0, parcels: [{exposure: true, fee: false, margin: false, segment: "-1.0-gold", tier: "silver", years: -1}], score: -0.5, sku: "gold"}, factor: 0}], + [{factor: 1, applicant: {score: 489, country: "é ü", sku: "-", channel: "", kind: "corporate", parcels: [{years: 5, tier: "bronze"}, {years: -1, tier: "gold"}, {years: -0, tier: "gold"}, {years: -500, tier: "gold"}]}}, {applicant: {channel: "", country: "é ü", kind: "corporate", net: 0.50, parcels: [{exposure: false, fee: false, margin: false, segment: "0.50-", tier: "bronze", years: 5}, {exposure: false, fee: false, margin: false, segment: "0.50-", tier: "gold", years: -1}, {exposure: false, fee: false, margin: false, segment: "0.50-", tier: "gold", years: 0}, {exposure: false, fee: false, margin: false, segment: "0.50-", tier: "gold", years: -500}], score: 489, sku: "-"}, factor: 1}], + [{factor: 0.5, applicant: {score: -1, country: "VIP", sku: "3.5", channel: "US", kind: "corporate", parcels: []}}, {applicant: {channel: "US", country: "VIP", kind: "corporate", net: -1, parcels: [], score: -1, sku: "3.5"}, factor: 0.5}], + [{factor: 1, applicant: {score: 100, country: "Oslo", sku: "3.5", channel: "DE", kind: "retail", parcels: [{years: 0.5, tier: "gold"}, {years: 1e3, tier: "gold"}, {years: 18, tier: "silver"}, {years: 1e3, tier: "gold"}], extraField: {nested: true}}}, {applicant: {channel: "DE", country: "Oslo", extraField: {nested: true}, kind: "retail", net: 200, parcels: [{exposure: false, fee: false, margin: false, segment: "200-DE", tier: "gold", years: 0.5}, {exposure: false, fee: false, margin: false, segment: "200-DE", tier: "gold", years: 1000}, {exposure: true, fee: false, margin: false, segment: "200-DE", tier: "silver", years: 18}, {exposure: false, fee: false, margin: false, segment: "200-DE", tier: "gold", years: 1000}], score: 100, sku: "3.5"}, factor: 1}], + [{factor: 100, applicant: {score: 1, country: "a-b-c", sku: "DE", channel: "Zed", kind: "retail", parcels: [{years: 1000000, tier: "gold"}], extraField: "x"}}, {applicant: {channel: "Zed", country: "a-b-c", extraField: "x", kind: "retail", net: 2, parcels: [{exposure: false, fee: false, margin: true, segment: "2-Zed", tier: "gold", years: 1000000}], score: 1, sku: "DE"}, factor: 100}], + [{factor: 100, applicant: {score: 0, country: "日本", sku: "retail", channel: "low", kind: "retail", parcels: [{years: 1e3, tier: "gold"}, {years: 1, tier: "silver"}]}}, {applicant: {channel: "low", country: "日本", kind: "retail", net: 0, parcels: [{exposure: false, fee: false, margin: true, segment: "0-low", tier: "gold", years: 1000}, {exposure: true, fee: false, margin: false, segment: "0-low", tier: "silver", years: 1}], score: 0, sku: "retail"}, factor: 100}], + [{factor: 100, applicant: {score: 0, country: "Zed", sku: "日本", channel: "é ü", kind: "corporate", parcels: [{years: 5, tier: "silver"}, {years: -1, tier: "bronze"}]}}, {applicant: {channel: "é ü", country: "Zed", kind: "corporate", net: 0, parcels: [{exposure: true, fee: false, margin: false, segment: "0-é ü", tier: "silver", years: 5}, {exposure: false, fee: false, margin: true, segment: "0-é ü", tier: "bronze", years: -1}], score: 0, sku: "日本"}, factor: 100}], + [{factor: 1, applicant: {score: 0.1, country: "DE", sku: "abc", channel: "US", kind: "retail", parcels: []}}, {applicant: {channel: "US", country: "DE", kind: "retail", net: 0, parcels: [], score: 0.1, sku: "abc"}, factor: 1}], + [{factor: -2, applicant: {score: -1, country: "US", sku: "é ü", channel: "NL", kind: "retail", parcels: [{years: 18, tier: "bronze"}, {years: 99.99, tier: "bronze"}, {years: 0.1, tier: "silver"}, {years: -0, tier: "gold"}, {years: -0.01, tier: "silver"}]}}, {applicant: {channel: "NL", country: "US", kind: "retail", net: -2, parcels: [{exposure: false, fee: false, margin: false, segment: "-2-NL", tier: "bronze", years: 18}, {exposure: false, fee: false, margin: false, segment: "-2-NL", tier: "bronze", years: 99.99}, {exposure: true, fee: false, margin: false, segment: "-2-NL", tier: "silver", years: 0.1}, {exposure: false, fee: false, margin: false, segment: "-2-NL", tier: "gold", years: 0}, {exposure: true, fee: false, margin: false, segment: "-2-NL", tier: "silver", years: -0.01}], score: -1, sku: "é ü"}, factor: -2}], + [{factor: -2, applicant: {score: 0, country: "gold", sku: "high", channel: "Zed", kind: "retail", parcels: [{years: -0, tier: "silver"}, {years: 250, tier: "gold"}, {years: 123456789.123, tier: "gold"}]}}, {applicant: {channel: "Zed", country: "gold", kind: "retail", net: 0, parcels: [{exposure: true, fee: false, margin: false, segment: "0-Zed", tier: "silver", years: 0}, {exposure: false, fee: false, margin: false, segment: "0-Zed", tier: "gold", years: 250}, {exposure: false, fee: false, margin: false, segment: "0-Zed", tier: "gold", years: 123456789.123}], score: 0, sku: "high"}, factor: -2}], + [{factor: 100, applicant: {score: 100, country: " pad ", sku: "US", channel: "US", kind: "corporate", parcels: []}}, {applicant: {channel: "US", country: " pad ", kind: "corporate", net: 100, parcels: [], score: 100, sku: "US"}, factor: 100}], + [{factor: 10, applicant: {score: 0, country: "DE", sku: "3.5", channel: "US", kind: "retail", parcels: [{years: 7.25, tier: "gold"}, {years: -0.01, tier: "bronze"}, {years: 1e3, tier: "bronze"}, {years: 99999999999999999999, tier: "silver"}]}}, {applicant: {channel: "US", country: "DE", kind: "retail", net: 0, parcels: [{exposure: false, fee: false, margin: true, segment: "0-US", tier: "gold", years: 7.25}, {exposure: false, fee: false, margin: true, segment: "0-US", tier: "bronze", years: -0.01}, {exposure: false, fee: false, margin: true, segment: "0-US", tier: "bronze", years: 1000}, {exposure: true, fee: false, margin: false, segment: "0-US", tier: "silver", years: 99999999999999999999}], score: 0, sku: "3.5"}, factor: 10}], + [{factor: 10, applicant: {score: -0.5, country: "x-y", sku: "VIP", channel: "Zed", kind: "corporate", parcels: [{years: 0.000001, tier: "gold"}, {years: 0, tier: "gold"}, {years: 1e3, tier: "gold"}, {years: 7.25, tier: "gold"}], extraField: 1}}, {applicant: {channel: "Zed", country: "x-y", extraField: 1, kind: "corporate", net: -1.0, parcels: [{exposure: false, fee: false, margin: true, segment: "-1.0-Zed", tier: "gold", years: 0.000001}, {exposure: false, fee: false, margin: true, segment: "-1.0-Zed", tier: "gold", years: 0}, {exposure: false, fee: false, margin: true, segment: "-1.0-Zed", tier: "gold", years: 1000}, {exposure: false, fee: false, margin: true, segment: "-1.0-Zed", tier: "gold", years: 7.25}], score: -0.5, sku: "VIP"}, factor: 10}], + [{factor: -2, applicant: {score: -0.01, country: "O'Neil", sku: "US", channel: " pad ", kind: "corporate", parcels: [{years: 0.5, tier: "gold"}, {years: 0.000001, tier: "gold"}]}}, {applicant: {channel: " pad ", country: "O'Neil", kind: "corporate", net: -0.02, parcels: [{exposure: false, fee: false, margin: false, segment: "-0.02- pad ", tier: "gold", years: 0.5}, {exposure: false, fee: false, margin: false, segment: "-0.02- pad ", tier: "gold", years: 0.000001}], score: -0.01, sku: "US"}, factor: -2}], + [{factor: 0.5, applicant: {score: 1000, country: "", sku: "日本", channel: "Oslo", kind: "retail", parcels: [{years: 2, tier: "silver"}]}}, {applicant: {channel: "Oslo", country: "", kind: "retail", net: 5, parcels: [{exposure: true, fee: false, margin: false, segment: "5-Oslo", tier: "silver", years: 2}], score: 1000, sku: "日本"}, factor: 0.5}], + [{factor: 100, applicant: {score: -500, country: "Oslo", sku: "DE", channel: "a", kind: false, parcels: [{years: 100, tier: "silver"}]}}, "!error: InputValidationFailed"], + ], +} + +// seed 330400 (attempt 0) +{ + name: "a 05: shipment/items: 1 assertion, 1 expression, 1 match; 0 root, 3 per-member, 0 top-level computed", + policy: { + models: {shipment: {qty: "number", birthDate: "date?", country: "string", kind: "string(retail|corporate)?", items: "item[]"}, item: {days: "number?", priority: "boolean"}}, + blocks: [ + {assertion: "item.decision", conditions: [["and", "shipment.qty < shipment.qty", 1], ["or", "(item.days ?? 0) in [19..92]", 0]]}, + {match: "item.quota", arms: [["all(shipment.items, (#.days ?? 0) < (#.days ?? 0))", "(item.days ?? 0)"], ["shipment.qty in [23..148]", "round(shipment.qty)"], ["all(shipment.items, (#.decision and #.decision))", "(item.days ?? 0)"], ["item.days != null", "1"], ["", "len(shipment.items)"]]}, + {expression: "item.total", value: "(shipment.country + '-' + shipment.country)"}, + ], + }, + cases: [ + [{shipment: {qty: 99.99, birthDate: "2024-02-29", country: "none", kind: "retail", items: []}}, {shipment: {birthDate: "2024-02-29", country: "none", items: [], kind: "retail", qty: 99.99}}], + [{shipment: {qty: 0.1, birthDate: "2025-03-20T10:15:30Z", country: "US", kind: "retail", items: []}}, {shipment: {birthDate: "2025-03-20T10:15:30Z", country: "US", items: [], kind: "retail", qty: 0.1}}], + [{shipment: {qty: 1000000, country: "US", items: [{days: 10, priority: true}, {days: 7.25, priority: true}, {days: 99.99, priority: false}, {days: 123456789.123, priority: false}, {days: 99999999999999999999, priority: false}]}}, {shipment: {country: "US", items: [{days: 10, decision: false, priority: true, quota: 1, total: "US-US"}, {days: 7.25, decision: false, priority: true, quota: 1, total: "US-US"}, {days: 99.99, decision: false, priority: false, quota: 1, total: "US-US"}, {days: 123456789.123, decision: false, priority: false, quota: 1, total: "US-US"}, {days: 99999999999999999999, decision: false, priority: false, quota: 1, total: "US-US"}], qty: 1000000}}], + [{shipment: {qty: 99999999999999999999, birthDate: "2025-03-20T10:15:30Z", country: "Oslo", kind: "retail", items: [{days: -0, priority: false}]}}, {shipment: {birthDate: "2025-03-20T10:15:30Z", country: "Oslo", items: [{days: 0, decision: false, priority: false, quota: 1, total: "Oslo-Oslo"}], kind: "retail", qty: 99999999999999999999}}], + [{shipment: {qty: 1, country: "DE", kind: null, items: [{days: 1000000, priority: false}, {days: 0.1, priority: false}, {days: -0.5, priority: true}, {days: null, priority: false}]}}, {shipment: {country: "DE", items: [{days: 1000000, decision: false, priority: false, quota: 1, total: "DE-DE"}, {days: 0.1, decision: false, priority: false, quota: 1, total: "DE-DE"}, {days: -0.5, decision: false, priority: true, quota: 1, total: "DE-DE"}, {days: null, decision: false, priority: false, quota: 4, total: "DE-DE"}], kind: null, qty: 1}}], + [{shipment: {qty: 1000, birthDate: "1990-06-15", country: "none", kind: "retail", items: []}}, {shipment: {birthDate: "1990-06-15", country: "none", items: [], kind: "retail", qty: 1000}}], + [{shipment: {qty: 2, birthDate: "2025-03-20", country: "Oslo", items: [{days: null, priority: true}, {days: null, priority: false}]}}, {shipment: {birthDate: "2025-03-20", country: "Oslo", items: [{days: null, decision: false, priority: true, quota: 2, total: "Oslo-Oslo"}, {days: null, decision: false, priority: false, quota: 2, total: "Oslo-Oslo"}], qty: 2}}], + [{shipment: {qty: 58, birthDate: "2000-01-01", country: "none", kind: "corporate", items: [{days: 181, priority: true}]}}, {shipment: {birthDate: "2000-01-01", country: "none", items: [{days: 181, decision: false, priority: true, quota: 58, total: "none-none"}], kind: "corporate", qty: 58}}], + [{shipment: {qty: 250, country: "VIP", items: []}}, {shipment: {country: "VIP", items: [], qty: 250}}], + [{shipment: {qty: 18, birthDate: "2030-12-31", country: "DE", items: [{days: 5, priority: true}, {priority: true}]}}, {shipment: {birthDate: "2030-12-31", country: "DE", items: [{days: 5, decision: false, priority: true, quota: 1, total: "DE-DE"}, {decision: false, priority: true, quota: 2, total: "DE-DE"}], qty: 18}}], + [{shipment: {qty: 5, birthDate: "2024-01-01", country: "NL", kind: null, items: [{days: 2.50, priority: false}, {days: 100, priority: false}, {days: null, priority: true}, {days: null, priority: true}, {priority: false}]}}, {shipment: {birthDate: "2024-01-01", country: "NL", items: [{days: 2.50, decision: false, priority: false, quota: 1, total: "NL-NL"}, {days: 100, decision: false, priority: false, quota: 1, total: "NL-NL"}, {days: null, decision: false, priority: true, quota: 5, total: "NL-NL"}, {days: null, decision: false, priority: true, quota: 5, total: "NL-NL"}, {decision: false, priority: false, quota: 5, total: "NL-NL"}], kind: null, qty: 5}}], + [{shipment: {qty: 7.25, birthDate: "2000-01-01", country: "gold", kind: null, items: [{days: null, priority: false}, {priority: false}, {priority: true}, {days: 1000000, priority: true}, {days: 250, priority: false}]}}, {shipment: {birthDate: "2000-01-01", country: "gold", items: [{days: null, decision: false, priority: false, quota: 5, total: "gold-gold"}, {decision: false, priority: false, quota: 5, total: "gold-gold"}, {decision: false, priority: true, quota: 5, total: "gold-gold"}, {days: 1000000, decision: false, priority: true, quota: 1, total: "gold-gold"}, {days: 250, decision: false, priority: false, quota: 1, total: "gold-gold"}], kind: null, qty: 7.25}}], + [{shipment: {qty: 327, country: "retail", kind: null, items: [{days: 5, priority: true}, {days: null, priority: false}, {days: 250, priority: false}]}}, {shipment: {country: "retail", items: [{days: 5, decision: false, priority: true, quota: 1, total: "retail-retail"}, {days: null, decision: false, priority: false, quota: 3, total: "retail-retail"}, {days: 250, decision: false, priority: false, quota: 1, total: "retail-retail"}], kind: null, qty: 327}}], + [{shipment: {qty: 298, birthDate: "2000-01-01", country: "a", kind: "retail", items: [{days: 5, priority: false}], extraField: {nested: true}}}, {shipment: {birthDate: "2000-01-01", country: "a", extraField: {nested: true}, items: [{days: 5, decision: false, priority: false, quota: 1, total: "a-a"}], kind: "retail", qty: 298}}], + [{shipment: {qty: 0.5, birthDate: "2025-03-20T10:15:30Z", country: "Oslo", kind: "retail", items: [{days: -0.5, priority: true}, {days: 100, priority: false}]}}, {shipment: {birthDate: "2025-03-20T10:15:30Z", country: "Oslo", items: [{days: -0.5, decision: false, priority: true, quota: 1, total: "Oslo-Oslo"}, {days: 100, decision: false, priority: false, quota: 1, total: "Oslo-Oslo"}], kind: "retail", qty: 0.5}}], + [{shipment: {qty: -0.5, birthDate: "1990-06-15", country: "US", kind: "retail", items: [{days: 100, priority: true}, {days: 99999999999999999999, priority: false}]}}, {shipment: {birthDate: "1990-06-15", country: "US", items: [{days: 100, decision: false, priority: true, quota: 1, total: "US-US"}, {days: 99999999999999999999, decision: false, priority: false, quota: 1, total: "US-US"}], kind: "retail", qty: -0.5}}], + [{shipment: {qty: 1, birthDate: null, country: "a", kind: "retail", items: [{days: null, priority: false}]}}, {shipment: {birthDate: null, country: "a", items: [{days: null, decision: false, priority: false, quota: 1, total: "a-a"}], kind: "retail", qty: 1}}], + [{shipment: {qty: -500, birthDate: null, country: "none", kind: "corporate", items: [{days: 1, priority: false}, {days: 7.25, priority: false}, {days: 1000000, priority: true}, {priority: false}]}}, {shipment: {birthDate: null, country: "none", items: [{days: 1, decision: false, priority: false, quota: 1, total: "none-none"}, {days: 7.25, decision: false, priority: false, quota: 1, total: "none-none"}, {days: 1000000, decision: false, priority: true, quota: 1, total: "none-none"}, {decision: false, priority: false, quota: 4, total: "none-none"}], kind: "corporate", qty: -500}}], + [{shipment: {qty: 1, birthDate: null, country: "DE", kind: null, items: [{priority: true}, {days: 0.000001, priority: true}]}}, {shipment: {birthDate: null, country: "DE", items: [{decision: false, priority: true, quota: 2, total: "DE-DE"}, {days: 0.000001, decision: false, priority: true, quota: 1, total: "DE-DE"}], kind: null, qty: 1}}], + [{shipment: {qty: 65, birthDate: "2025-03-20", country: "", kind: "retail", items: [{days: 2, priority: true}, {days: 1000, priority: true}, {days: 99.99, priority: true}]}}, {shipment: {birthDate: "2025-03-20", country: "", items: [{days: 2, decision: false, priority: true, quota: 65, total: "-"}, {days: 1000, decision: false, priority: true, quota: 65, total: "-"}, {days: 99.99, decision: false, priority: true, quota: 65, total: "-"}], kind: "retail", qty: 65}}], + [{shipment: {qty: 1000000, birthDate: null, country: "NL", items: [{days: 1000, priority: false}, {days: 18, priority: false}, {days: null, priority: false}]}}, {shipment: {birthDate: null, country: "NL", items: [{days: 1000, decision: false, priority: false, quota: 1, total: "NL-NL"}, {days: 18, decision: false, priority: false, quota: 1, total: "NL-NL"}, {days: null, decision: false, priority: false, quota: 3, total: "NL-NL"}], qty: 1000000}}], + [{shipment: {qty: 18, birthDate: null, country: "DE", kind: "retail", items: [{priority: false}]}}, {shipment: {birthDate: null, country: "DE", items: [{decision: false, priority: false, quota: 1, total: "DE-DE"}], kind: "retail", qty: 18}}], + [{shipment: {qty: -0, country: "DE", kind: "corporate", items: [{days: -0, priority: false}, {days: -0.5, priority: false}, {priority: false}]}}, {shipment: {country: "DE", items: [{days: 0, decision: false, priority: false, quota: 1, total: "DE-DE"}, {days: -0.5, decision: false, priority: false, quota: 1, total: "DE-DE"}, {decision: false, priority: false, quota: 3, total: "DE-DE"}], kind: "corporate", qty: 0}}], + [{shipment: {qty: null, birthDate: "2025-03-20T10:15:30Z", country: "DE", kind: "retail", items: [{days: 1e3, priority: false}, {days: -1, priority: true}]}}, "!error: MissingRequiredInputs"], + [{shipment: {qty: 1, birthDate: "2024-02-29", country: "Oslo", kind: "corporate", items: [{days: 18, priority: true}]}}, {shipment: {birthDate: "2024-02-29", country: "Oslo", items: [{days: 18, decision: false, priority: true, quota: 1, total: "Oslo-Oslo"}], kind: "corporate", qty: 1}}], + [{shipment: {qty: -1, birthDate: "2024-02-29", country: null, kind: "corporate", items: [{days: 7.25, priority: true}, {days: 0.000001, priority: true}, {days: 100, priority: false}]}}, "!error: MissingRequiredInputs"], + [{shipment: {qty: 2, birthDate: null, country: "Zed", kind: null, items: [{priority: false}]}}, {shipment: {birthDate: null, country: "Zed", items: [{decision: false, priority: false, quota: 1, total: "Zed-Zed"}], kind: null, qty: 2}}], + ], +} + +// seed 330500 (attempt 0) +{ + name: "a 06: customer/companies: 4 expression; 1 root, 2 per-member, 1 top-level computed", + policy: { + models: {customer: {age: "number", code: "string", name: "string?", amount: "number", label: "string", dueDate: "date", companies: "company[]"}, company: {price: "number", rate: "number", flagged: "boolean"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {expression: "company.band", value: "customer.amount"}, + {expression: "company.quota", value: "(avg(map(customer.companies, #.band)) ?? 0)"}, + {expression: "level", value: "(not (contains(customer.code, 'low')) and customer.dueDate < d('2025-01-01'))"}, + {expression: "customer.surcharge", value: "sum(map(customer.companies, #.band))"}, + ], + }, + cases: [ + [{cap: 100, customer: {age: 2, code: "Oslo", name: "Zed", amount: 1, label: "日本", dueDate: "2000-01-01", companies: [{price: 359, rate: 99.99, flagged: false}, {price: 124, rate: 18, flagged: false}]}}, {cap: 100, customer: {age: 2, amount: 1, code: "Oslo", companies: [{band: 1, flagged: false, price: 359, quota: 1, rate: 99.99}, {band: 1, flagged: false, price: 124, quota: 1, rate: 18}], dueDate: "2000-01-01", label: "日本", name: "Zed", surcharge: 2}, level: true}], + [{cap: 100, customer: {age: 1e3, code: "Zed", name: "US", amount: 0.000001, label: "US", dueDate: "2025-03-20", companies: [{price: 1000000, rate: -0.01, flagged: false}]}}, {cap: 100, customer: {age: 1000, amount: 0.000001, code: "Zed", companies: [{band: 0.000001, flagged: false, price: 1000000, quota: 0.000001, rate: -0.01}], dueDate: "2025-03-20", label: "US", name: "US", surcharge: 0.000001}, level: false}], + [{cap: 10, customer: {age: 203, code: "x-y", name: "DE", amount: 99999999999999999999, label: " pad ", dueDate: "2000-01-01", companies: [{price: 10, rate: 2, flagged: true}]}}, {cap: 10, customer: {age: 203, amount: 99999999999999999999, code: "x-y", companies: [{band: 99999999999999999999, flagged: true, price: 10, quota: 99999999999999999999, rate: 2}], dueDate: "2000-01-01", label: " pad ", name: "DE", surcharge: 99999999999999999999}, level: true}], + [{cap: -2, customer: {age: 0.5, code: "US", name: "NL", amount: 123456789.123, label: "US", dueDate: "2030-12-31", companies: [{price: 5, rate: 0, flagged: false}]}}, {cap: -2, customer: {age: 0.5, amount: 123456789.123, code: "US", companies: [{band: 123456789.123, flagged: false, price: 5, quota: 123456789.123, rate: 0}], dueDate: "2030-12-31", label: "US", name: "NL", surcharge: 123456789.123}, level: false}], + [{cap: 0, customer: {age: 250, code: "retail", name: "Zed", amount: 0.1, label: "a", dueDate: "2024-01-01", companies: [{price: 250, rate: -0.01, flagged: true}, {price: 1000, rate: -0.01, flagged: true}], extraField: "x"}}, {cap: 0, customer: {age: 250, amount: 0.1, code: "retail", companies: [{band: 0.1, flagged: true, price: 250, quota: 0.1, rate: -0.01}, {band: 0.1, flagged: true, price: 1000, quota: 0.1, rate: -0.01}], dueDate: "2024-01-01", extraField: "x", label: "a", name: "Zed", surcharge: 0.2}, level: true}], + [{cap: -2, customer: {age: -0.5, code: "DE", name: "Oslo", amount: 1000, label: "retail", dueDate: "2030-12-31", companies: [], extraField: {nested: true}}}, {cap: -2, customer: {age: -0.5, amount: 1000, code: "DE", companies: [], dueDate: "2030-12-31", extraField: {nested: true}, label: "retail", name: "Oslo", surcharge: 0}, level: false}], + [{cap: 0, customer: {age: 2, code: "é ü", name: "12", amount: 0, label: "retail", dueDate: "2000-01-01", companies: [{price: -0, rate: -500, flagged: true}, {price: 250, rate: 1000, flagged: false}, {price: 1000000, rate: -500, flagged: true}, {price: 1e3, rate: 0.5, flagged: true}, {price: 99.99, rate: 7.25, flagged: true}]}}, {cap: 0, customer: {age: 2, amount: 0, code: "é ü", companies: [{band: 0, flagged: true, price: 0, quota: 0, rate: -500}, {band: 0, flagged: false, price: 250, quota: 0, rate: 1000}, {band: 0, flagged: true, price: 1000000, quota: 0, rate: -500}, {band: 0, flagged: true, price: 1000, quota: 0, rate: 0.5}, {band: 0, flagged: true, price: 99.99, quota: 0, rate: 7.25}], dueDate: "2000-01-01", label: "retail", name: "12", surcharge: 0}, level: true}], + [{cap: 1, customer: {age: 85, code: "Oslo", name: "", amount: 7.25, label: "VIP", dueDate: "2025-03-20T10:15:30Z", companies: [{price: 250, rate: -500, flagged: true}, {price: -500, rate: 1, flagged: true}, {price: 0.5, rate: 99999999999999999999, flagged: false}, {price: 2, rate: -0.5, flagged: true}, {price: 99.99, rate: -500, flagged: true}]}}, {cap: 1, customer: {age: 85, amount: 7.25, code: "Oslo", companies: [{band: 7.25, flagged: true, price: 250, quota: 7.25, rate: -500}, {band: 7.25, flagged: true, price: -500, quota: 7.25, rate: 1}, {band: 7.25, flagged: false, price: 0.5, quota: 7.25, rate: 99999999999999999999}, {band: 7.25, flagged: true, price: 2, quota: 7.25, rate: -0.5}, {band: 7.25, flagged: true, price: 99.99, quota: 7.25, rate: -500}], dueDate: "2025-03-20T10:15:30Z", label: "VIP", name: "", surcharge: 36.25}, level: false}], + [{cap: 1, customer: {age: 1, code: "DE", amount: 0.1, label: "gold", dueDate: "2030-12-31", companies: []}}, {cap: 1, customer: {age: 1, amount: 0.1, code: "DE", companies: [], dueDate: "2030-12-31", label: "gold", surcharge: 0}, level: false}], + [{cap: 0.5, customer: {age: 100, code: "VIP", amount: 99999999999999999999, label: "12", dueDate: "2000-01-01", companies: [{price: 65, rate: 99999999999999999999, flagged: false}, {price: 0, rate: -1, flagged: false}, {price: -0, rate: 432, flagged: false}, {price: -0, rate: 0.5, flagged: false}]}}, {cap: 0.5, customer: {age: 100, amount: 99999999999999999999, code: "VIP", companies: [{band: 99999999999999999999, flagged: false, price: 65, quota: 99999999999999999999, rate: 99999999999999999999}, {band: 99999999999999999999, flagged: false, price: 0, quota: 99999999999999999999, rate: -1}, {band: 99999999999999999999, flagged: false, price: 0, quota: 99999999999999999999, rate: 432}, {band: 99999999999999999999, flagged: false, price: 0, quota: 99999999999999999999, rate: 0.5}], dueDate: "2000-01-01", label: "12", surcharge: 399999999999999999996}, level: true}], + [{cap: 10, customer: {age: 123456789.123, code: "", name: null, amount: 2.50, label: "é ü", dueDate: "2025-03-20T10:15:30Z", companies: [{price: 0.1, rate: 0.000001, flagged: true}, {price: 5, rate: -500, flagged: false}]}}, {cap: 10, customer: {age: 123456789.123, amount: 2.50, code: "", companies: [{band: 2.50, flagged: true, price: 0.1, quota: 2.50, rate: 0.000001}, {band: 2.50, flagged: false, price: 5, quota: 2.50, rate: -500}], dueDate: "2025-03-20T10:15:30Z", label: "é ü", name: null, surcharge: 5.00}, level: false}], + [{cap: 10, customer: {age: 18, code: "low", name: "", amount: 0, label: "x-y", dueDate: "2024-01-01", companies: [{price: 5, rate: 2, flagged: true}]}}, {cap: 10, customer: {age: 18, amount: 0, code: "low", companies: [{band: 0, flagged: true, price: 5, quota: 0, rate: 2}], dueDate: "2024-01-01", label: "x-y", name: "", surcharge: 0}, level: false}], + [{cap: 1, customer: {age: 0.1, code: " pad ", name: "a", amount: 2, label: "", dueDate: "2024-02-29", companies: []}}, {cap: 1, customer: {age: 0.1, amount: 2, code: " pad ", companies: [], dueDate: "2024-02-29", label: "", name: "a", surcharge: 0}, level: true}], + ], +} + +// seed 330600 (attempt 0) +{ + name: "a 07: borrower/accounts: 1 expression, 1 match, 2 table; 2 root, 3 per-member, 0 top-level computed", + policy: { + models: {borrower: {limit: "number", kind: "string(retail|corporate)", code: "string", income: "number?", rate: "number", accounts: "acct[]"}, acct: {balance: "number", status: "string(open|closed|pending)", plan: "string(basic|plus|premium|trial)"}}, + blocks: [ + {table: "t1", inputs: [null], outputs: ["borrower.level"], rules: [ + ["((borrower.income ?? 0) == 1 and borrower.limit == 50)", "len(borrower.accounts)"], + ["", "borrower.rate"], + ["borrower.rate < borrower.rate", "borrower.rate"], + ["", "borrower.rate"], + ["not (borrower.rate > 50)", "borrower.limit"], + ]}, + {match: "borrower.quota", arms: [["borrower.level == null", "(borrower.rate > 100 ? borrower.code : borrower.code)"], ["contains(borrower.code, 'retail')", "lower(lower(borrower.code))"], ["", "string(borrower.limit)"]]}, + {table: "t3", inputs: ["borrower.limit", "sum(map(borrower.accounts, #.balance))"], outputs: ["acct.surcharge", "acct.grade"], rules: [ + ["!= 1.5", "[5..455]", "(borrower.income ?? 0) <= 18", "acct.balance <= 1.5"], + ["", "1000", "18 > 0.5", "(borrower.level ?? 0) == 0.5"], + ["[2..235]", "<= 2", "borrower.rate > 1", "(borrower.income ?? 0) <= 1"], + ["", "!= 50", "not ((borrower.level ?? 0) <= 1)", "(borrower.level ?? 0) > 1000"], + ["", ">= 0.25", "borrower.rate <= 50", ""], + ]}, + {expression: "acct.tag", value: "not ((borrower.level ?? 0) <= 250)"}, + ], + }, + cases: [ + [{borrower: {limit: 0.25, kind: "corporate", code: "DE", income: 1000, rate: 0, accounts: []}}, {borrower: {accounts: [], code: "DE", income: 1000, kind: "corporate", level: 0, limit: 0.25, quota: "0.25", rate: 0}}], + [{borrower: {limit: 2, kind: "corporate", code: "retail", income: 5, rate: 3, accounts: [{balance: 10, status: "closed", plan: "trial"}, {balance: 1.5, status: "closed", plan: "basic"}, {balance: 1, status: "open", plan: "premium"}]}}, {borrower: {accounts: [{balance: 10, grade: false, plan: "trial", status: "closed", surcharge: true, tag: false}, {balance: 1.5, grade: true, plan: "basic", status: "closed", surcharge: true, tag: false}, {balance: 1, grade: true, plan: "premium", status: "open", surcharge: true, tag: false}], code: "retail", income: 5, kind: "corporate", level: 3, limit: 2, quota: "retail", rate: 3}}], + [{borrower: {limit: 1, kind: "corporate", code: "A1", income: -500, rate: 5, accounts: [{balance: 18, status: "pending", plan: "trial"}, {balance: 18, status: "open", plan: "basic"}, {balance: 50, status: "closed", plan: "basic"}, {balance: -0, status: "open", plan: "trial"}], extraField: 1}}, {borrower: {accounts: [{balance: 18, grade: false, plan: "trial", status: "pending", surcharge: true, tag: false}, {balance: 18, grade: false, plan: "basic", status: "open", surcharge: true, tag: false}, {balance: 50, grade: false, plan: "basic", status: "closed", surcharge: true, tag: false}, {balance: 0, grade: true, plan: "trial", status: "open", surcharge: true, tag: false}], code: "A1", extraField: 1, income: -500, kind: "corporate", level: 5, limit: 1, quota: "1", rate: 5}}], + [{borrower: {limit: 250, kind: "retail", code: "x-y", income: 250, rate: 0.1, accounts: [{balance: 0, status: "closed", plan: "premium"}]}}, {borrower: {accounts: [{balance: 0, grade: false, plan: "premium", status: "closed", surcharge: false, tag: false}], code: "x-y", income: 250, kind: "retail", level: 0.1, limit: 250, quota: "250", rate: 0.1}}], + [{borrower: {limit: 18, kind: "corporate", code: "-", income: -1, rate: 123456789.123, accounts: [{balance: -0.5, status: "pending", plan: "basic"}], extraField: {nested: true}}}, {borrower: {accounts: [{balance: -0.5, grade: true, plan: "basic", status: "pending", surcharge: true, tag: true}], code: "-", extraField: {nested: true}, income: -1, kind: "corporate", level: 123456789.123, limit: 18, quota: "18", rate: 123456789.123}}], + [{borrower: {limit: 1.5, kind: "retail", code: "3.5", income: 18, rate: -1, accounts: [{balance: 0.5, status: "open", plan: "basic"}, {balance: 7.25, status: "pending", plan: "plus"}, {balance: 99.99, status: "pending", plan: "trial"}, {balance: 0.5, status: "open", plan: "basic"}, {balance: 403, status: "pending", plan: "basic"}]}}, {borrower: {accounts: [{balance: 0.5, grade: false, plan: "basic", status: "open", surcharge: false, tag: false}, {balance: 7.25, grade: false, plan: "plus", status: "pending", surcharge: false, tag: false}, {balance: 99.99, grade: false, plan: "trial", status: "pending", surcharge: false, tag: false}, {balance: 0.5, grade: false, plan: "basic", status: "open", surcharge: false, tag: false}, {balance: 403, grade: false, plan: "basic", status: "pending", surcharge: false, tag: false}], code: "3.5", income: 18, kind: "retail", level: -1, limit: 1.5, quota: "1.5", rate: -1}}], + [{borrower: {limit: 1000, kind: "corporate", code: "12", income: null, rate: 3, accounts: [{balance: 1, status: "closed", plan: "basic"}, {balance: 0.25, status: "pending", plan: "trial"}, {balance: 0.000001, status: "closed", plan: "premium"}, {balance: -500, status: "pending", plan: "basic"}]}}, {borrower: {accounts: [{balance: 1, grade: false, plan: "basic", status: "closed", surcharge: true, tag: false}, {balance: 0.25, grade: false, plan: "trial", status: "pending", surcharge: true, tag: false}, {balance: 0.000001, grade: false, plan: "premium", status: "closed", surcharge: true, tag: false}, {balance: -500, grade: false, plan: "basic", status: "pending", surcharge: true, tag: false}], code: "12", income: null, kind: "corporate", level: 3, limit: 1000, quota: "1000", rate: 3}}], + [{borrower: {limit: 1000, kind: "retail", code: " pad ", income: -0.5, rate: 0.5, accounts: [{balance: 5, status: "open", plan: "premium"}, {balance: -0.01, status: "closed", plan: "basic"}, {balance: 100, status: "open", plan: "plus"}, {balance: 1, status: "open", plan: "plus"}, {balance: 0, status: "open", plan: "trial"}]}}, {borrower: {accounts: [{balance: 5, grade: false, plan: "premium", status: "open", surcharge: true, tag: false}, {balance: -0.01, grade: true, plan: "basic", status: "closed", surcharge: true, tag: false}, {balance: 100, grade: false, plan: "plus", status: "open", surcharge: true, tag: false}, {balance: 1, grade: true, plan: "plus", status: "open", surcharge: true, tag: false}, {balance: 0, grade: true, plan: "trial", status: "open", surcharge: true, tag: false}], code: " pad ", income: -0.5, kind: "retail", level: 0.5, limit: 1000, quota: "1000", rate: 0.5}}], + [{borrower: {limit: 0, kind: "corporate", code: "O'Neil", rate: 1000, accounts: [{balance: 1, status: "pending", plan: "premium"}, {balance: 0.25, status: "pending", plan: "trial"}]}}, {borrower: {accounts: [{balance: 1, grade: false, plan: "premium", status: "pending", surcharge: true, tag: true}, {balance: 0.25, grade: false, plan: "trial", status: "pending", surcharge: true, tag: true}], code: "O'Neil", kind: "corporate", level: 1000, limit: 0, quota: "0", rate: 1000}}], + [{borrower: {limit: 3, kind: "retail", code: " pad ", income: 0.5, rate: 18, accounts: [{balance: 18, status: "open", plan: "premium"}]}}, {borrower: {accounts: [{balance: 18, grade: false, plan: "premium", status: "open", surcharge: true, tag: false}], code: " pad ", income: 0.5, kind: "retail", level: 18, limit: 3, quota: "3", rate: 18}}], + [{borrower: {limit: 2, kind: "retail", code: "NL", income: 2, rate: 79, accounts: []}}, {borrower: {accounts: [], code: "NL", income: 2, kind: "retail", level: 79, limit: 2, quota: "2", rate: 79}}], + [{borrower: {limit: 5, kind: "retail", code: "retail", income: -0, rate: 3, accounts: [{balance: 10, status: "closed", plan: "plus"}, {balance: 5, status: "closed", plan: "basic"}]}}, {borrower: {accounts: [{balance: 10, grade: false, plan: "plus", status: "closed", surcharge: true, tag: false}, {balance: 5, grade: false, plan: "basic", status: "closed", surcharge: true, tag: false}], code: "retail", income: 0, kind: "retail", level: 3, limit: 5, quota: "retail", rate: 3}}], + [{borrower: {limit: 7.25, kind: "retail", code: "NL", rate: 1.5, accounts: [{balance: 0.5, status: "pending", plan: "basic"}]}}, {borrower: {accounts: [{balance: 0.5, grade: true, plan: "basic", status: "pending", surcharge: true, tag: false}], code: "NL", kind: "retail", level: 1.5, limit: 7.25, quota: "7.25", rate: 1.5}}], + [{borrower: {limit: 18, kind: "retail", code: " pad ", income: 0.25, rate: 0.000001, accounts: [{balance: 0.1, status: "open", plan: "premium"}, {balance: 1, status: "open", plan: "trial"}]}}, {borrower: {accounts: [{balance: 0.1, grade: true, plan: "premium", status: "open", surcharge: false, tag: false}, {balance: 1, grade: true, plan: "trial", status: "open", surcharge: false, tag: false}], code: " pad ", income: 0.25, kind: "retail", level: 0.000001, limit: 18, quota: "18", rate: 0.000001}}], + [{borrower: {limit: 50, kind: "retail", code: "abc", income: 202, rate: -500, accounts: [{balance: 1000, status: "closed", plan: "plus"}, {balance: 50, status: "pending", plan: "premium"}, {balance: 18, status: "open", plan: "basic"}, {balance: 50, status: "open", plan: "plus"}]}}, {borrower: {accounts: [{balance: 1000, grade: false, plan: "plus", status: "closed", surcharge: false, tag: false}, {balance: 50, grade: false, plan: "premium", status: "pending", surcharge: false, tag: false}, {balance: 18, grade: false, plan: "basic", status: "open", surcharge: false, tag: false}, {balance: 50, grade: false, plan: "plus", status: "open", surcharge: false, tag: false}], code: "abc", income: 202, kind: "retail", level: -500, limit: 50, quota: "50", rate: -500}}], + [{borrower: {limit: 1000, kind: "retail", code: "A1", income: 10, rate: 50, accounts: [{balance: 250, status: "pending", plan: "basic"}]}}, {borrower: {accounts: [{balance: 250, grade: false, plan: "basic", status: "pending", surcharge: true, tag: false}], code: "A1", income: 10, kind: "retail", level: 50, limit: 1000, quota: "1000", rate: 50}}], + [{borrower: {limit: 5, kind: "retail", code: "x-y", income: 0.000001, rate: -0.5, accounts: [{balance: 1.5, status: "open", plan: "premium"}, {balance: 5, status: "closed", plan: "basic"}, {balance: 123456789.123, status: "open", plan: "plus"}]}}, {borrower: {accounts: [{balance: 1.5, grade: false, plan: "premium", status: "open", surcharge: false, tag: false}, {balance: 5, grade: false, plan: "basic", status: "closed", surcharge: false, tag: false}, {balance: 123456789.123, grade: false, plan: "plus", status: "open", surcharge: false, tag: false}], code: "x-y", income: 0.000001, kind: "retail", level: -0.5, limit: 5, quota: "5", rate: -0.5}}], + [{borrower: {limit: 2, code: "Oslo", income: 1, rate: 1.5, accounts: [{balance: -0.01, status: "pending", plan: "trial"}, {balance: 5, status: "closed", plan: "trial"}, {balance: 10, status: "pending", plan: "premium"}, {balance: 250, status: "open", plan: "premium"}]}}, {borrower: {accounts: [{balance: -0.01, grade: true, plan: "trial", status: "pending", surcharge: true, tag: false}, {balance: 5, grade: false, plan: "trial", status: "closed", surcharge: true, tag: false}, {balance: 10, grade: false, plan: "premium", status: "pending", surcharge: true, tag: false}, {balance: 250, grade: false, plan: "premium", status: "open", surcharge: true, tag: false}], code: "Oslo", income: 1, level: 1.5, limit: 2, quota: "2", rate: 1.5}}], + [{borrower: {limit: 250, kind: "corporate", code: "日本", income: 1000000, rate: 18, accounts: []}}, {borrower: {accounts: [], code: "日本", income: 1000000, kind: "corporate", level: 18, limit: 250, quota: "250", rate: 18}}], + ], +} + +// seed 330700 (attempt 0) +{ + name: "a 08: customer/items: 2 assertion, 2 expression; 0 root, 3 per-member, 1 top-level computed", + policy: { + models: {customer: {limit: "number?", plan: "string(basic|plus|premium|trial)", code: "string", qty: "number", status: "string(open|closed|pending)?", items: "item[]?"}, item: {score: "number", price: "number", amount: "number"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {assertion: "item.decision", conditions: ["(customer.status ?? '') in ['closed', 'pending']", ["and", "customer.plan in ['premium', 'trial']", 1], "customer.code in ['US', 'gold']", ["or", "item.price == item.score", 1], ["or", "(customer.qty < item.score and some((customer.items ?? []), (0.5 > 50 and #.amount == 50)))", 1]]}, + {assertion: "grade", conditions: [["or", "baseRate <= baseRate", 0]]}, + {expression: "item.risk", value: "len((customer.items ?? []))"}, + {expression: "item.weighted", value: "contains(customer.code, 'high')"}, + ], + }, + cases: [ + [{baseRate: 0.5, customer: {limit: 250, plan: "trial", code: "12", qty: 50, status: "open", items: [{score: 5, price: 10, amount: -0}, {score: 2.50, price: -0.5, amount: 123456789.123}, {score: -0.01, price: 1, amount: 10}, {score: 2, price: 99999999999999999999, amount: 10}, {score: -0, price: 250, amount: 0.1}]}}, {baseRate: 0.5, customer: {code: "12", items: [{amount: 0, decision: false, price: 10, risk: 5, score: 5, weighted: false}, {amount: 123456789.123, decision: false, price: -0.5, risk: 5, score: 2.50, weighted: false}, {amount: 10, decision: false, price: 1, risk: 5, score: -0.01, weighted: false}, {amount: 10, decision: false, price: 99999999999999999999, risk: 5, score: 2, weighted: false}, {amount: 0.1, decision: false, price: 250, risk: 5, score: 0, weighted: false}], limit: 250, plan: "trial", qty: 50, status: "open"}, grade: true}], + [{baseRate: 0, customer: {limit: 0.1, plan: "premium", code: "retail", qty: 99.99, status: "closed", items: [{score: 50, price: 2, amount: 1.5}, {score: 2.50, price: 1, amount: -1}]}}, {baseRate: 0, customer: {code: "retail", items: [{amount: 1.5, decision: false, price: 2, risk: 2, score: 50, weighted: false}, {amount: -1, decision: false, price: 1, risk: 2, score: 2.50, weighted: false}], limit: 0.1, plan: "premium", qty: 99.99, status: "closed"}, grade: true}], + [{baseRate: 10, customer: {limit: -0, plan: "trial", code: "gold", qty: -1, status: "open", items: [{score: -0, price: -0.5, amount: 0}, {score: 0, price: 123456789.123, amount: 123456789.123}]}}, {baseRate: 10, customer: {code: "gold", items: [{amount: 0, decision: false, price: -0.5, risk: 2, score: 0, weighted: false}, {amount: 123456789.123, decision: false, price: 123456789.123, risk: 2, score: 0, weighted: false}], limit: 0, plan: "trial", qty: -1, status: "open"}, grade: true}], + [{baseRate: 100, customer: {limit: 0.5, plan: "basic", code: "retail", qty: 0.1, status: "pending", items: [{score: 99.99, price: 250, amount: 123456789.123}, {score: 5, price: 250, amount: -0.01}]}}, {baseRate: 100, customer: {code: "retail", items: [{amount: 123456789.123, decision: false, price: 250, risk: 2, score: 99.99, weighted: false}, {amount: -0.01, decision: false, price: 250, risk: 2, score: 5, weighted: false}], limit: 0.5, plan: "basic", qty: 0.1, status: "pending"}, grade: true}], + [{baseRate: 0, customer: {limit: 1, plan: "basic", code: "VIP", qty: 57}}, {baseRate: 0, customer: {code: "VIP", limit: 1, plan: "basic", qty: 57}, grade: true}], + [{baseRate: -2, customer: {limit: 10, plan: "basic", code: "é ü", qty: 7.25, status: "closed", items: [{score: 0.5, price: 50, amount: 5}, {score: 1000, price: 50, amount: 0.5}, {score: 1e3, price: 123456789.123, amount: 0}, {score: 1000000, price: 0.5, amount: 100}]}}, {baseRate: -2, customer: {code: "é ü", items: [{amount: 5, decision: false, price: 50, risk: 4, score: 0.5, weighted: false}, {amount: 0.5, decision: false, price: 50, risk: 4, score: 1000, weighted: false}, {amount: 0, decision: false, price: 123456789.123, risk: 4, score: 1000, weighted: false}, {amount: 100, decision: false, price: 0.5, risk: 4, score: 1000000, weighted: false}], limit: 10, plan: "basic", qty: 7.25, status: "closed"}, grade: true}], + [{baseRate: 0, customer: {limit: 1000000, plan: "basic", code: "3.5", qty: 10, status: "open", items: []}}, {baseRate: 0, customer: {code: "3.5", items: [], limit: 1000000, plan: "basic", qty: 10, status: "open"}, grade: true}], + [{baseRate: 1, customer: {limit: 123456789.123, plan: "basic", code: "high", qty: 2.50, status: "open", items: []}}, {baseRate: 1, customer: {code: "high", items: [], limit: 123456789.123, plan: "basic", qty: 2.50, status: "open"}, grade: true}], + [{baseRate: -2, customer: {limit: -0.5, plan: "plus", code: "US", qty: 0.1, status: "open", items: [{score: 99.99, price: -500, amount: 99.99}], extraField: "x"}}, {baseRate: -2, customer: {code: "US", extraField: "x", items: [{amount: 99.99, decision: false, price: -500, risk: 1, score: 99.99, weighted: false}], limit: -0.5, plan: "plus", qty: 0.1, status: "open"}, grade: true}], + [{baseRate: -2, customer: {limit: 0.1, plan: "plus", code: "high", qty: 0.5, status: "open", items: [{score: -0.5, price: 1.5, amount: 1}]}}, {baseRate: -2, customer: {code: "high", items: [{amount: 1, decision: false, price: 1.5, risk: 1, score: -0.5, weighted: true}], limit: 0.1, plan: "plus", qty: 0.5, status: "open"}, grade: true}], + [{baseRate: 0.5, customer: {plan: "basic", code: "VIP", qty: 99.99, items: [{score: 99999999999999999999, price: -0.01, amount: 0.000001}, {score: 7.25, price: -500, amount: 0.5}]}}, {baseRate: 0.5, customer: {code: "VIP", items: [{amount: 0.000001, decision: false, price: -0.01, risk: 2, score: 99999999999999999999, weighted: false}, {amount: 0.5, decision: false, price: -500, risk: 2, score: 7.25, weighted: false}], plan: "basic", qty: 99.99}, grade: true}], + [{baseRate: 1, customer: {limit: 1e3, plan: "basic", code: "NL", qty: 50, status: null, items: [{score: 0.5, price: 0.5, amount: 65}]}}, {baseRate: 1, customer: {code: "NL", items: [{amount: 65, decision: false, price: 0.5, risk: 1, score: 0.5, weighted: false}], limit: 1000, plan: "basic", qty: 50, status: null}, grade: true}], + [{baseRate: 1, customer: {limit: 65, plan: "basic", code: "日本", qty: 99999999999999999999, status: "pending", items: []}}, {baseRate: 1, customer: {code: "日本", items: [], limit: 65, plan: "basic", qty: 99999999999999999999, status: "pending"}, grade: true}], + [{baseRate: -2, customer: {limit: 50, plan: "basic", code: " pad ", qty: 0.1, status: "closed", items: [{score: 123456789.123, price: 2, amount: 1.5}, {score: 100, price: 100, amount: 0.000001}, {score: -1, price: 65, amount: 1.5}, {score: 0, price: 0, amount: 1}], extraField: {nested: true}}}, {baseRate: -2, customer: {code: " pad ", extraField: {nested: true}, items: [{amount: 1.5, decision: false, price: 2, risk: 4, score: 123456789.123, weighted: false}, {amount: 0.000001, decision: false, price: 100, risk: 4, score: 100, weighted: false}, {amount: 1.5, decision: false, price: 65, risk: 4, score: -1, weighted: false}, {amount: 1, decision: false, price: 0, risk: 4, score: 0, weighted: false}], limit: 50, plan: "basic", qty: 0.1, status: "closed"}, grade: true}], + [{baseRate: 1, customer: {limit: -0.5, plan: "basic", code: "gold", qty: 0, status: "pending", items: [{score: 18, price: 12, amount: 1.5}, {score: 1000000, price: 99999999999999999999, amount: 2}, {score: 2, price: 0.000001, amount: 1e3}]}}, {baseRate: 1, customer: {code: "gold", items: [{amount: 1.5, decision: false, price: 12, risk: 3, score: 18, weighted: false}, {amount: 2, decision: false, price: 99999999999999999999, risk: 3, score: 1000000, weighted: false}, {amount: 1000, decision: false, price: 0.000001, risk: 3, score: 2, weighted: false}], limit: -0.5, plan: "basic", qty: 0, status: "pending"}, grade: true}], + [{baseRate: 0.5, customer: {limit: 1000000, plan: "premium", code: "Zed", qty: -1, status: "closed", items: [{score: 100, price: 100, amount: 100}, {score: 99.99, price: 0.1, amount: 1000}, {score: 5, price: 2.50, amount: -0.5}, {score: 0.1, price: -0.5, amount: 277}, {score: 18, price: 100, amount: -500}]}}, {baseRate: 0.5, customer: {code: "Zed", items: [{amount: 100, decision: false, price: 100, risk: 5, score: 100, weighted: false}, {amount: 1000, decision: false, price: 0.1, risk: 5, score: 99.99, weighted: false}, {amount: -0.5, decision: false, price: 2.50, risk: 5, score: 5, weighted: false}, {amount: 277, decision: false, price: -0.5, risk: 5, score: 0.1, weighted: false}, {amount: -500, decision: false, price: 100, risk: 5, score: 18, weighted: false}], limit: 1000000, plan: "premium", qty: -1, status: "closed"}, grade: true}], + [{baseRate: 100, customer: {limit: 123456789.123, plan: "plus", code: "O'Neil", qty: 1000000, status: "closed", items: null}}, {baseRate: 100, customer: {code: "O'Neil", items: null, limit: 123456789.123, plan: "plus", qty: 1000000, status: "closed"}, grade: true}], + [{baseRate: 1, customer: {limit: 67, plan: "trial", code: "x-y", qty: 7.25, status: "pending", items: [{score: 1000, price: -0.01, amount: 1000000}, {score: 100, price: -0.01, amount: 0}]}}, {baseRate: 1, customer: {code: "x-y", items: [{amount: 1000000, decision: false, price: -0.01, risk: 2, score: 1000, weighted: false}, {amount: 0, decision: false, price: -0.01, risk: 2, score: 100, weighted: false}], limit: 67, plan: "trial", qty: 7.25, status: "pending"}, grade: true}], + [{baseRate: 1, customer: {limit: null, plan: "premium", code: "NL", qty: 18, status: "closed", items: [{score: 18, price: 0.000001, amount: 50}, {score: 10, price: 1e3, amount: 123456789.123}]}}, {baseRate: 1, customer: {code: "NL", items: [{amount: 50, decision: false, price: 0.000001, risk: 2, score: 18, weighted: false}, {amount: 123456789.123, decision: false, price: 1000, risk: 2, score: 10, weighted: false}], limit: null, plan: "premium", qty: 18, status: "closed"}, grade: true}], + [{baseRate: -2, customer: {limit: 1, plan: "basic", code: "VIP", qty: 250, status: "open", items: [{score: 2, price: -0, amount: 50}]}}, {baseRate: -2, customer: {code: "VIP", items: [{amount: 50, decision: false, price: 0, risk: 1, score: 2, weighted: false}], limit: 1, plan: "basic", qty: 250, status: "open"}, grade: true}], + [{baseRate: 0, customer: {limit: 50, code: "Zed", qty: 0.000001, status: "open", items: [{score: -500, price: 50, amount: 1e3}, {score: 100, price: 1, amount: 487}, {score: -500, price: 0.1, amount: 123456789.123}]}}, "!error: MissingRequiredInputs"], + ], +} + +// seed 330800 (attempt 0) +{ + name: "a 09: shipment/parcels: 1 assertion, 1 match, 1 table; 0 root, 4 per-member, 0 top-level computed", + policy: { + models: {shipment: {age: "number", insured: "boolean", tier: "string(gold|silver|bronze)?", parcels: "parcel[]"}, parcel: {price: "number", age: "number?", dueDate: "date", kind: "string(retail|corporate)"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {table: "t1", inputs: ["shipment.age"], outputs: ["parcel.share", "parcel.tag"], rules: [ + ["!= 10", "10", "shipment.insured"], + ["5, 3", "sum(map(shipment.parcels, (#.age ?? 0)))", "parcel.price < parcel.price"], + ["> 5", "len(shipment.parcels)", "shipment.insured"], + ["5, 2", "len(shipment.parcels)", "not (shipment.insured)"], + ["[18..361]", "", "shipment.insured"], + ["> 3", "2", "shipment.insured"], + ["", "", "shipment.insured"], + ]}, + {assertion: "parcel.health", conditions: ["min([(parcel.share ?? 0), cap]) <= (parcel.share ?? 0)", ["or", "not (shipment.insured)", 0], ["and", "shipment.tier != null", 2]]}, + {match: "parcel.flag", arms: [["none(shipment.parcels, not ((#.tag ?? false)))", "shipment.age"], ["", "(parcel.share ?? 0)"]]}, + ], + }, + cases: [ + [{cap: 0, shipment: {age: -0, insured: false, parcels: [{price: 2, age: 90, dueDate: "1990-06-15", kind: "retail"}, {price: 3, dueDate: "1990-06-15", kind: "retail"}, {price: 3, dueDate: "2025-03-20T10:15:30Z", kind: "corporate"}]}}, {cap: 0, shipment: {age: 0, insured: false, parcels: [{age: 90, dueDate: "1990-06-15", flag: 10, health: true, kind: "retail", price: 2, share: 10, tag: false}, {dueDate: "1990-06-15", flag: 10, health: true, kind: "retail", price: 3, share: 10, tag: false}, {dueDate: "2025-03-20T10:15:30Z", flag: 10, health: true, kind: "corporate", price: 3, share: 10, tag: false}]}}], + [{cap: 100, shipment: {age: 2, insured: true, tier: "gold", parcels: [{price: 18, age: 32, dueDate: "not a date", kind: "retail"}]}}, "!error: InputValidationFailed"], + [{cap: 10, shipment: {age: 359, insured: true, tier: null, parcels: [{price: 18, age: null, dueDate: "1990-06-15", kind: "corporate"}, {price: 5, dueDate: "1990-06-15", kind: "corporate"}, {price: 3, age: null, dueDate: "2025-03-20T10:15:30Z", kind: "retail"}]}}, {cap: 10, shipment: {age: 359, insured: true, parcels: [{age: null, dueDate: "1990-06-15", flag: 359, health: false, kind: "corporate", price: 18, share: 10, tag: true}, {dueDate: "1990-06-15", flag: 359, health: false, kind: "corporate", price: 5, share: 10, tag: true}, {age: null, dueDate: "2025-03-20T10:15:30Z", flag: 359, health: false, kind: "retail", price: 3, share: 10, tag: true}], tier: null}}], + [{cap: 0.5, shipment: {age: 1, insured: true, tier: "bronze", parcels: [{price: -500, age: 5, dueDate: "2025-03-20", kind: "retail"}]}}, {cap: 0.5, shipment: {age: 1, insured: true, parcels: [{age: 5, dueDate: "2025-03-20", flag: 1, health: true, kind: "retail", price: -500, share: 10, tag: true}], tier: "bronze"}}], + [{cap: 1, shipment: {age: -500, insured: false, tier: "gold", parcels: [{price: 0.000001, age: 3, dueDate: "2025-03-20T10:15:30Z", kind: "corporate"}, {price: 250, age: -0.5, dueDate: "2025-03-20T10:15:30Z", kind: "retail"}, {price: 3, age: 2, dueDate: "2024-02-29", kind: "retail"}]}}, {cap: 1, shipment: {age: -500, insured: false, parcels: [{age: 3, dueDate: "2025-03-20T10:15:30Z", flag: 10, health: true, kind: "corporate", price: 0.000001, share: 10, tag: false}, {age: -0.5, dueDate: "2025-03-20T10:15:30Z", flag: 10, health: true, kind: "retail", price: 250, share: 10, tag: false}, {age: 2, dueDate: "2024-02-29", flag: 10, health: true, kind: "retail", price: 3, share: 10, tag: false}], tier: "gold"}}], + [{cap: 1, shipment: {age: 2, insured: false, tier: "gold", parcels: [{price: 123456789.123, age: 18, dueDate: "2025-03-20", kind: "retail"}, {price: 123456789.123, age: 0.5, dueDate: "2024-02-29", kind: "retail"}]}}, {cap: 1, shipment: {age: 2, insured: false, parcels: [{age: 18, dueDate: "2025-03-20", flag: 10, health: true, kind: "retail", price: 123456789.123, share: 10, tag: false}, {age: 0.5, dueDate: "2024-02-29", flag: 10, health: true, kind: "retail", price: 123456789.123, share: 10, tag: false}], tier: "gold"}}], + [{cap: 100, shipment: {age: -1, insured: false, tier: "silver", parcels: [{price: 0.5, age: -500, dueDate: "2030-12-31", kind: "corporate"}, {price: 2, age: 123456789.123, dueDate: "1990-06-15", kind: "retail"}]}}, {cap: 100, shipment: {age: -1, insured: false, parcels: [{age: -500, dueDate: "2030-12-31", flag: 10, health: true, kind: "corporate", price: 0.5, share: 10, tag: false}, {age: 123456789.123, dueDate: "1990-06-15", flag: 10, health: true, kind: "retail", price: 2, share: 10, tag: false}], tier: "silver"}}], + [{cap: -2, shipment: {age: 5, insured: false, parcels: [{price: 10, age: null, dueDate: "1990-06-15", kind: "retail"}, {price: 3, age: 250, dueDate: "2025-03-20", kind: "retail"}, {price: 3, dueDate: "2024-02-29", kind: "retail"}, {price: 0, age: null, dueDate: "2025-03-20T10:15:30Z", kind: "retail"}]}}, {cap: -2, shipment: {age: 5, insured: false, parcels: [{age: null, dueDate: "1990-06-15", flag: 10, health: true, kind: "retail", price: 10, share: 10, tag: false}, {age: 250, dueDate: "2025-03-20", flag: 10, health: true, kind: "retail", price: 3, share: 10, tag: false}, {dueDate: "2024-02-29", flag: 10, health: true, kind: "retail", price: 3, share: 10, tag: false}, {age: null, dueDate: "2025-03-20T10:15:30Z", flag: 10, health: true, kind: "retail", price: 0, share: 10, tag: false}]}}], + [{cap: 10, shipment: {age: 18, insured: true, parcels: [{price: 18, age: null, dueDate: "1990-06-15", kind: "retail"}, {price: 7.25, dueDate: "2030-12-31", kind: "retail"}, {price: 2, age: 5, dueDate: "2024-02-29", kind: "retail"}, {price: 18, age: -1, dueDate: "2025-03-20", kind: "retail"}]}}, {cap: 10, shipment: {age: 18, insured: true, parcels: [{age: null, dueDate: "1990-06-15", flag: 18, health: false, kind: "retail", price: 18, share: 10, tag: true}, {dueDate: "2030-12-31", flag: 18, health: false, kind: "retail", price: 7.25, share: 10, tag: true}, {age: 5, dueDate: "2024-02-29", flag: 18, health: false, kind: "retail", price: 2, share: 10, tag: true}, {age: -1, dueDate: "2025-03-20", flag: 18, health: false, kind: "retail", price: 18, share: 10, tag: true}]}}], + [{cap: 0, shipment: {age: 18, insured: false, tier: "bronze", parcels: [{price: 7.25, age: 5, dueDate: "1990-06-15", kind: "retail"}]}}, {cap: 0, shipment: {age: 18, insured: false, parcels: [{age: 5, dueDate: "1990-06-15", flag: 10, health: true, kind: "retail", price: 7.25, share: 10, tag: false}], tier: "bronze"}}], + [{cap: 10, shipment: {age: 5, insured: false, tier: "gold", parcels: [{price: 1, age: 2, dueDate: "2025-03-20", kind: "retail"}, {price: 3, age: 2, dueDate: "2024-02-29", kind: "retail"}], extraField: {nested: true}}}, {cap: 10, shipment: {age: 5, extraField: {nested: true}, insured: false, parcels: [{age: 2, dueDate: "2025-03-20", flag: 10, health: true, kind: "retail", price: 1, share: 10, tag: false}, {age: 2, dueDate: "2024-02-29", flag: 10, health: true, kind: "retail", price: 3, share: 10, tag: false}], tier: "gold"}}], + [{cap: 0, shipment: {age: -500, insured: false, tier: null, parcels: [{price: 2, age: -0.01, dueDate: "2025-03-20T10:15:30Z", kind: "retail"}, {price: 1e3, dueDate: "2030-12-31", kind: "retail"}]}}, {cap: 0, shipment: {age: -500, insured: false, parcels: [{age: -0.01, dueDate: "2025-03-20T10:15:30Z", flag: 10, health: true, kind: "retail", price: 2, share: 10, tag: false}, {dueDate: "2030-12-31", flag: 10, health: true, kind: "retail", price: 1000, share: 10, tag: false}], tier: null}}], + [{cap: 10, shipment: {age: -500, insured: true, tier: "gold", parcels: []}}, {cap: 10, shipment: {age: -500, insured: true, parcels: [], tier: "gold"}}], + [{cap: 1, shipment: {age: 1000000, insured: true, tier: "gold", parcels: [{price: 2.50, age: 10, dueDate: "2024-01-01"}]}}, {cap: 1, shipment: {age: 1000000, insured: true, parcels: [{age: 10, dueDate: "2024-01-01", flag: 1000000, health: true, price: 2.50, share: 10, tag: true}], tier: "gold"}}], + [{cap: 0.5, shipment: {age: 0.1, insured: false, tier: "gold", parcels: []}}, {cap: 0.5, shipment: {age: 0.1, insured: false, parcels: [], tier: "gold"}}], + [{cap: 1, shipment: {age: -0, insured: false, tier: "gold", parcels: [{price: 99.99, age: 3, dueDate: "1990-06-15", kind: "retail"}]}}, {cap: 1, shipment: {age: 0, insured: false, parcels: [{age: 3, dueDate: "1990-06-15", flag: 10, health: true, kind: "retail", price: 99.99, share: 10, tag: false}], tier: "gold"}}], + [{cap: 0.5, shipment: {age: 18, insured: false, parcels: [{price: 0.1, dueDate: "2000-01-01", kind: "retail"}, {price: 99.99, age: 250, dueDate: "2025-03-20", kind: "retail"}, {price: 10, age: 18, dueDate: "2024-02-29", kind: "corporate"}]}}, {cap: 0.5, shipment: {age: 18, insured: false, parcels: [{dueDate: "2000-01-01", flag: 10, health: true, kind: "retail", price: 0.1, share: 10, tag: false}, {age: 250, dueDate: "2025-03-20", flag: 10, health: true, kind: "retail", price: 99.99, share: 10, tag: false}, {age: 18, dueDate: "2024-02-29", flag: 10, health: true, kind: "corporate", price: 10, share: 10, tag: false}]}}], + [{cap: 100, shipment: {age: 44, insured: true, tier: false, parcels: [{price: 1, age: 2, dueDate: "2000-01-01", kind: "retail"}]}}, "!error: InputValidationFailed"], + ], +} + +// seed 330900 (attempt 0) +{ + name: "a 10: applicant/companies: 1 expression, 4 match, 3 table; 3 root, 5 per-member, 3 top-level computed", + policy: { + models: {applicant: {years: "number", kind: "string(retail|corporate)", code: "string?", urgent: "boolean?", weight: "number?", companies: "company[]"}, company: {days: "number", name: "string"}}, + blocks: [ + {match: "company.grade", arms: [["applicant.kind in ['retail', 'corporate']", "((applicant.code ?? '') + '-' + company.name)"], ["company.days < (applicant.weight ?? 0)", "'gold'"], ["all(applicant.companies, (#.days <= 50 or #.days == 10))", "(applicant.kind != 'corporate' ? company.name : upper((applicant.code ?? '')))"], ["company.days == applicant.years", "(((applicant.urgent ?? false) ? company.name : company.name) + '-' + company.name)"], ["", "(applicant.code ?? '')"]]}, + {table: "t2", inputs: ["applicant.years", "applicant.urgent", null], outputs: ["eligible", "tag"], rules: [ + ["!= 1.5", "false", "(applicant.weight ?? 0) >= (applicant.weight ?? 0)", "", "(applicant.urgent ?? false)"], + ["", "", "", "applicant.years", "(applicant.weight ?? 0) > (applicant.weight ?? 0)"], + ]}, + {table: "t3", inputs: ["applicant.urgent"], outputs: ["bonus"], rules: [ + ["false", "(applicant.code ?? '')"], + ["false", ""], + ]}, + {table: "t4", hit: "collect", inputs: ["applicant.years"], outputs: ["applicant.fee", "applicant.quota", "applicant.exposure"], rules: [ + ["> 2", "(eligible ?? 0)", "(applicant.urgent ?? false)", "(bonus ?? '')"], + [">= 3", "", "(applicant.urgent ?? false)", "(applicant.code ?? '')"], + ["", "(applicant.weight ?? 0)", "not ((tag ?? false))", "(bonus ?? '')"], + ["", "(eligible ?? 0)", "all(applicant.companies, not (#.days > 3))", "trim((applicant.code ?? ''))"], + ]}, + {match: "company.net", arms: [["((tag ?? false) or (applicant.urgent ?? false))", "company.name"], ["len(company.grade) != applicant.years", "upper(company.grade)"], ["bonus == null", "(bonus ?? '')"], ["", "(applicant.code ?? '')"]]}, + {match: "company.decision", arms: [["len(applicant.fee) > 0.5", "(applicant.weight ?? 0)"], ["((applicant.urgent ?? false) and (applicant.urgent ?? false))", "(sum(map(applicant.companies, 10)) * sum(map(applicant.companies, 5)))"], ["(min(map(applicant.companies, 1)) ?? 0) == (eligible ?? 0)", "len((applicant.code ?? ''))"], ["", "((applicant.urgent ?? false) ? (eligible ?? 0) : 50)"]]}, + {expression: "company.adjusted", value: "some(applicant.companies, not (#.days > 3))"}, + {match: "company.bucket", arms: [["none(applicant.companies, #.days > #.decision)", "not (company.adjusted)"], ["(applicant.code ?? '') != 'VIP'", "(applicant.urgent ?? false)"], ["", "(tag ?? false)"]]}, + ], + }, + cases: [ + [{applicant: {years: 250, kind: "corporate", code: "DE", urgent: false, weight: 123456789.123, companies: [{days: 3, name: "a"}, {days: 250, name: "O'Neil"}, {days: 99999999999999999999, name: "é ü"}, {days: 50, name: "12"}]}}, {applicant: {code: "DE", companies: [{bucket: false, days: 3, decision: 123456789.123, grade: "DE-a", name: "a", net: "DE-A"}, {bucket: false, days: 250, decision: 123456789.123, grade: "DE-O'Neil", name: "O'Neil", net: "DE-O'NEIL"}, {bucket: false, days: 99999999999999999999, decision: 123456789.123, grade: "DE-é ü", name: "é ü", net: "DE-É Ü"}, {bucket: false, days: 50, decision: 123456789.123, grade: "DE-12", name: "12", net: "DE-12"}], exposure: ["DE", "DE", "DE", "DE"], fee: [250, 123456789.123, 250], kind: "corporate", quota: [false, false, true, false], urgent: false, weight: 123456789.123, years: 250}, bonus: "DE", eligible: 250, tag: false}], + [{applicant: {years: 3, kind: "retail", urgent: true, weight: -0.5, companies: [{days: 143, name: "DE"}, {days: -0, name: "x-y"}, {days: -0.01, name: "O'Neil"}, {days: 1000000, name: "US"}, {days: 3, name: "O'Neil"}]}}, {applicant: {companies: [{bucket: true, days: 143, decision: -0.5, grade: "-DE", name: "DE", net: "DE"}, {bucket: true, days: 0, decision: -0.5, grade: "-x-y", name: "x-y", net: "x-y"}, {bucket: true, days: -0.01, decision: -0.5, grade: "-O'Neil", name: "O'Neil", net: "O'Neil"}, {bucket: true, days: 1000000, decision: -0.5, grade: "-US", name: "US", net: "US"}, {bucket: true, days: 3, decision: -0.5, grade: "-O'Neil", name: "O'Neil", net: "O'Neil"}], exposure: ["", "", "", ""], fee: [3, -0.5, 3], kind: "retail", quota: [true, true, true, false], urgent: true, weight: -0.5, years: 3}, bonus: null, eligible: 3, tag: false}], + [{applicant: {years: 99999999999999999999, kind: "corporate", urgent: true, weight: 5, companies: [{days: 99999999999999999999, name: "US"}]}}, {applicant: {companies: [{bucket: true, days: 99999999999999999999, decision: 5, grade: "-US", name: "US", net: "US"}], exposure: ["", "", "", ""], fee: [99999999999999999999, 5, 99999999999999999999], kind: "corporate", quota: [true, true, true, false], urgent: true, weight: 5, years: 99999999999999999999}, bonus: null, eligible: 99999999999999999999, tag: false}], + [{applicant: {years: 434, kind: "retail", code: "12", urgent: true, weight: 1.5, companies: [{days: 1e3, name: "12"}, {days: 0.5, name: "3.5"}, {days: 99.99, name: "DE"}, {days: 0.5, name: "12"}]}}, {applicant: {code: "12", companies: [{bucket: true, days: 1000, decision: 1.5, grade: "12-12", name: "12", net: "12"}, {bucket: true, days: 0.5, decision: 1.5, grade: "12-3.5", name: "3.5", net: "3.5"}, {bucket: true, days: 99.99, decision: 1.5, grade: "12-DE", name: "DE", net: "DE"}, {bucket: true, days: 0.5, decision: 1.5, grade: "12-12", name: "12", net: "12"}], exposure: ["", "12", "", "12"], fee: [434, 1.5, 434], kind: "retail", quota: [true, true, true, false], urgent: true, weight: 1.5, years: 434}, bonus: null, eligible: 434, tag: false}], + [{applicant: {years: 3, kind: "retail", code: "a", urgent: true, companies: [{days: 5, name: "DE"}]}}, {applicant: {code: "a", companies: [{bucket: true, days: 5, decision: 0, grade: "a-DE", name: "DE", net: "DE"}], exposure: ["", "a", "", "a"], fee: [3, 0, 3], kind: "retail", quota: [true, true, true, false], urgent: true, years: 3}, bonus: null, eligible: 3, tag: false}], + [{applicant: {years: -0.5, kind: "corporate", code: "abc", urgent: true, weight: 50, companies: [{days: 50, name: "gold"}, {days: 0.000001, name: " pad "}], extraField: 1}}, {applicant: {code: "abc", companies: [{adjusted: true, bucket: false, days: 50, decision: 50, grade: "abc-gold", name: "gold", net: "gold"}, {adjusted: true, bucket: false, days: 0.000001, decision: 50, grade: "abc- pad ", name: " pad ", net: " pad "}], exposure: ["", "abc"], extraField: 1, fee: [50, -0.5], kind: "corporate", quota: [true, false], urgent: true, weight: 50, years: -0.5}, bonus: null, eligible: -0.5, tag: false}], + [{applicant: {years: 99.99, kind: "corporate", code: "Zed", urgent: false, weight: 18, companies: []}}, {applicant: {code: "Zed", companies: [], exposure: ["Zed", "Zed", "Zed", "Zed"], fee: [99.99, 18, 99.99], kind: "corporate", quota: [false, false, true, true], urgent: false, weight: 18, years: 99.99}, bonus: "Zed", eligible: 99.99, tag: false}], + [{applicant: {years: 7.25, kind: "retail", code: null, urgent: true, weight: 250, companies: []}}, {applicant: {code: null, companies: [], exposure: ["", "", "", ""], fee: [7.25, 250, 7.25], kind: "retail", quota: [true, true, true, true], urgent: true, weight: 250, years: 7.25}, bonus: null, eligible: 7.25, tag: false}], + [{applicant: {years: 123456789.123, kind: "retail", code: "VIP", urgent: false, weight: 10, companies: []}}, {applicant: {code: "VIP", companies: [], exposure: ["VIP", "VIP", "VIP", "VIP"], fee: [123456789.123, 10, 123456789.123], kind: "retail", quota: [false, false, true, true], urgent: false, weight: 10, years: 123456789.123}, bonus: "VIP", eligible: 123456789.123, tag: false}], + [{applicant: {years: 18, kind: "corporate", code: null, companies: [{days: 3, name: ""}, {days: 3, name: "12"}, {days: 1, name: "Oslo"}, {days: 2.50, name: "gold"}]}}, {applicant: {code: null, companies: [{bucket: false, days: 3, decision: 0, grade: "-", name: "", net: "-"}, {bucket: false, days: 3, decision: 0, grade: "-12", name: "12", net: "-12"}, {bucket: false, days: 1, decision: 0, grade: "-Oslo", name: "Oslo", net: "-OSLO"}, {bucket: false, days: 2.50, decision: 0, grade: "-gold", name: "gold", net: "-GOLD"}], exposure: ["", "", "", ""], fee: [18, 0, 18], kind: "corporate", quota: [false, false, true, true], years: 18}, bonus: null, eligible: 18, tag: false}], + [{applicant: {years: 0.5, kind: "retail", code: "O'Neil", urgent: true, weight: 1000000, companies: [{days: 1e3, name: "abc"}, {days: 3, name: "gold"}]}}, {applicant: {code: "O'Neil", companies: [{adjusted: true, bucket: false, days: 1000, decision: 1000000, grade: "O'Neil-abc", name: "abc", net: "abc"}, {adjusted: true, bucket: false, days: 3, decision: 1000000, grade: "O'Neil-gold", name: "gold", net: "gold"}], exposure: ["", "O'Neil"], fee: [1000000, 0.5], kind: "retail", quota: [true, false], urgent: true, weight: 1000000, years: 0.5}, bonus: null, eligible: 0.5, tag: false}], + [{applicant: {years: 1000000, kind: "corporate", code: "a-b-c", urgent: false, weight: 2, companies: []}}, {applicant: {code: "a-b-c", companies: [], exposure: ["a-b-c", "a-b-c", "a-b-c", "a-b-c"], fee: [1000000, 2, 1000000], kind: "corporate", quota: [false, false, true, true], urgent: false, weight: 2, years: 1000000}, bonus: "a-b-c", eligible: 1000000, tag: false}], + [{applicant: {years: 250, kind: "corporate", code: "gold", urgent: false, weight: 123456789.123, companies: [{days: 50, name: null}, {days: 3, name: "A1"}, {days: 0.25, name: "3.5"}]}}, "!error: ExpressionFailed"], + [{applicant: {years: 18, kind: "retail", code: "日本", urgent: false, weight: 5, companies: [{days: 10, name: "日本"}, {days: 1000, name: ""}, {days: 5, name: "3.5"}, {days: 18, name: "DE"}, {days: 2.50, name: "12"}]}}, {applicant: {code: "日本", companies: [{bucket: false, days: 10, decision: 5, grade: "日本-日本", name: "日本", net: "日本-日本"}, {bucket: false, days: 1000, decision: 5, grade: "日本-", name: "", net: "日本-"}, {bucket: false, days: 5, decision: 5, grade: "日本-3.5", name: "3.5", net: "日本-3.5"}, {bucket: false, days: 18, decision: 5, grade: "日本-DE", name: "DE", net: "日本-DE"}, {bucket: false, days: 2.50, decision: 5, grade: "日本-12", name: "12", net: "日本-12"}], exposure: ["日本", "日本", "日本", "日本"], fee: [18, 5, 18], kind: "retail", quota: [false, false, true, false], urgent: false, weight: 5, years: 18}, bonus: "日本", eligible: 18, tag: false}], + [{applicant: {years: 18, kind: "retail", code: null, urgent: null, weight: null, companies: [{days: 3, name: ""}]}}, {applicant: {code: null, companies: [{bucket: false, days: 3, decision: 0, grade: "-", name: "", net: "-"}], exposure: ["", "", "", ""], fee: [18, 0, 18], kind: "retail", quota: [false, false, true, true], urgent: null, weight: null, years: 18}, bonus: null, eligible: 18, tag: false}], + [{applicant: {years: -0.01, kind: "retail", urgent: false, weight: 99.99, companies: [{days: 2, name: " pad "}, {days: 1000, name: "-"}]}}, {applicant: {companies: [{bucket: false, days: 2, decision: 99.99, grade: "- pad ", name: " pad ", net: "- PAD "}, {bucket: false, days: 1000, decision: 99.99, grade: "--", name: "-", net: "--"}], exposure: ["", ""], fee: [99.99, -0.01], kind: "retail", quota: [true, false], urgent: false, weight: 99.99, years: -0.01}, bonus: "", eligible: -0.01, tag: false}], + [{applicant: {years: 18, kind: "retail", code: "abc", urgent: true, weight: 100, companies: [{days: 1000000, name: " pad "}]}}, {applicant: {code: "abc", companies: [{bucket: true, days: 1000000, decision: 100, grade: "abc- pad ", name: " pad ", net: " pad "}], exposure: ["", "abc", "", "abc"], fee: [18, 100, 18], kind: "retail", quota: [true, true, true, false], urgent: true, weight: 100, years: 18}, bonus: null, eligible: 18, tag: false}], + [{applicant: {years: 99999999999999999999, kind: "corporate", code: "日本", urgent: true, weight: 2, companies: [{days: 123456789.123, name: "DE"}]}}, {applicant: {code: "日本", companies: [{bucket: true, days: 123456789.123, decision: 2, grade: "日本-DE", name: "DE", net: "DE"}], exposure: ["", "日本", "", "日本"], fee: [99999999999999999999, 2, 99999999999999999999], kind: "corporate", quota: [true, true, true, false], urgent: true, weight: 2, years: 99999999999999999999}, bonus: null, eligible: 99999999999999999999, tag: false}], + [{applicant: {years: "12", kind: "corporate", code: "日本", urgent: false, weight: 0.5, companies: [{days: 1000000, name: "12"}, {days: 0.5, name: "abc"}, {days: 0.5, name: "DE"}, {days: 0.000001, name: "x-y"}]}}, "!error: InputValidationFailed"], + [{applicant: {years: 99.99, kind: "retail", code: "", urgent: false, weight: 0.25, companies: [{days: 65, name: "Zed"}]}}, {applicant: {code: "", companies: [{bucket: false, days: 65, decision: 0.25, grade: "-Zed", name: "Zed", net: "-ZED"}], exposure: ["", "", "", ""], fee: [99.99, 0.25, 99.99], kind: "retail", quota: [false, false, true, false], urgent: false, weight: 0.25, years: 99.99}, bonus: "", eligible: 99.99, tag: false}], + [{applicant: {years: 0, kind: "retail", code: "a", urgent: true, weight: -1, companies: [{days: -1, name: "x-y"}]}}, {applicant: {code: "a", companies: [{adjusted: true, bucket: false, days: -1, decision: -1, grade: "a-x-y", name: "x-y", net: "x-y"}], exposure: ["", "a"], fee: [-1, 0], kind: "retail", quota: [true, true], urgent: true, weight: -1, years: 0}, bonus: null, eligible: 0, tag: false}], + [{applicant: {years: -1, kind: "retail", urgent: false, companies: [{days: 10, name: "-"}, {days: 10, name: "O'Neil"}]}}, {applicant: {companies: [{bucket: false, days: 10, decision: 0, grade: "--", name: "-", net: "--"}, {bucket: false, days: 10, decision: 0, grade: "-O'Neil", name: "O'Neil", net: "-O'NEIL"}], exposure: ["", ""], fee: [0, -1], kind: "retail", quota: [true, false], urgent: false, years: -1}, bonus: "", eligible: -1, tag: false}], + [{applicant: {years: 1, kind: "retail", code: "Oslo", urgent: true, weight: 3, companies: [{days: 123456789.123, name: "12"}, {days: 1e3, name: "VIP"}, {days: 0, name: "DE"}], extraField: 1}}, {applicant: {code: "Oslo", companies: [{bucket: true, days: 123456789.123, decision: 3, grade: "Oslo-12", name: "12", net: "12"}, {bucket: true, days: 1000, decision: 3, grade: "Oslo-VIP", name: "VIP", net: "VIP"}, {bucket: true, days: 0, decision: 3, grade: "Oslo-DE", name: "DE", net: "DE"}], exposure: ["", "Oslo"], extraField: 1, fee: [3, 1], kind: "retail", quota: [true, false], urgent: true, weight: 3, years: 1}, bonus: null, eligible: 1, tag: false}], + [{applicant: {years: 1, kind: "retail", weight: 10, companies: [{days: 3, name: "日本"}, {days: 250, name: "Zed"}]}}, {applicant: {companies: [{bucket: false, days: 3, decision: 10, grade: "-日本", name: "日本", net: "-日本"}, {bucket: false, days: 250, decision: 10, grade: "-Zed", name: "Zed", net: "-ZED"}], exposure: ["", ""], fee: [10, 1], kind: "retail", quota: [true, false], weight: 10, years: 1}, bonus: null, eligible: 1, tag: false}], + [{applicant: {years: 50, kind: "retail", code: "x", urgent: false, weight: 2, companies: [{days: 0.000001, name: "US"}]}}, {applicant: {code: "x", companies: [{adjusted: true, bucket: false, days: 0.000001, decision: 2, grade: "x-US", name: "US", net: "X-US"}], exposure: ["x", "x", "x", "x"], fee: [50, 2, 50], kind: "retail", quota: [false, false, true, true], urgent: false, weight: 2, years: 50}, bonus: "x", eligible: 50, tag: false}], + [{applicant: {years: 2.50, kind: "retail", code: null, urgent: null, weight: 65, companies: [{days: 2, name: "gold"}, {days: 10, name: "VIP"}, {days: 10, name: "US"}]}}, {applicant: {code: null, companies: [{adjusted: true, bucket: false, days: 2, decision: 65, grade: "-gold", name: "gold", net: "-GOLD"}, {adjusted: true, bucket: false, days: 10, decision: 65, grade: "-VIP", name: "VIP", net: "-VIP"}, {adjusted: true, bucket: false, days: 10, decision: 65, grade: "-US", name: "US", net: "-US"}], exposure: ["", "", ""], fee: [2.50, 65, 2.50], kind: "retail", quota: [false, true, false], urgent: null, weight: 65, years: 2.50}, bonus: null, eligible: 2.50, tag: false}], + ], +} + +// seed 331000 (attempt 0) +{ + name: "a 11: claim/parcels: 5 expression, 2 match, 1 table; 3 root, 5 per-member, 0 top-level computed", + policy: { + models: {claim: {years: "number", verified: "boolean", active: "boolean", dueDate: "date?", code: "string", since: "date?", parcels: "parcel[]"}, parcel: {weight: "number", score: "number?", name: "string?", kind: "string(retail|corporate)"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {expression: "parcel.net", value: "(claim.since ?? d('2025-01-01')).add(36, 'month')"}, + {table: "t2", inputs: ["(parcel.score ?? 0)", "claim.verified"], outputs: ["parcel.total"], rules: [ + ["<= 3", "true", "(parcel.score ?? 0)"], + [">= 10", "false", "(avg(map(claim.parcels, (#.score ?? 0))) ?? 0)"], + ["< 250", "false", "(parcel.score ?? 0)"], + ["2, 0", "", "2"], + ["[0.5..500.5]", "", "sum(map(claim.parcels, #.weight))"], + ["", "", "claim.years"], + ]}, + {expression: "claim.penalty", value: "round(claim.years)"}, + {match: "parcel.flag", arms: [["parcel.net < d('2024-01-01')", "(parcel.name ?? '')"], ["not (claim.active)", "(parcel.name ?? '')"], ["(parcel.name ?? '') in ['US', 'retail']", "claim.code"], ["(claim.years <= 0.5 and baseRate >= 100)", "string(claim.penalty)"], ["", "string(baseRate)"]]}, + {expression: "parcel.discount", value: "(avg(map(claim.parcels, (#.score ?? 0))) ?? 0)"}, + {expression: "parcel.exposure", value: "(parcel.total ?? 0)"}, + {expression: "claim.band", value: "(claim.since ?? d('2025-01-01'))"}, + {match: "claim.grade", arms: [["baseRate != baseRate", "claim.code"], ["not (some(claim.parcels, not (#.exposure > 0)))", "claim.code"], ["", "string(claim.penalty)"]]}, + ], + }, + cases: [ + [{baseRate: 0.5, claim: {years: 50, verified: true, active: false, dueDate: "1990-06-15", code: "retail", since: "2025-03-20", parcels: [{weight: 100, score: 0.5, name: "a-b-c", kind: "retail"}]}}, {baseRate: 0.5, claim: {active: false, band: "2025-03-20", code: "retail", dueDate: "1990-06-15", grade: "retail", parcels: [{discount: 0.5, exposure: 0.5, flag: "a-b-c", kind: "retail", name: "a-b-c", net: "2028-03-20T00:00:00Z", score: 0.5, total: 0.5, weight: 100}], since: "2025-03-20", verified: true, years: 50}}], + [{baseRate: -2, claim: {years: 99.99, verified: false, active: false, dueDate: "1990-06-15", code: "a", since: "2024-02-29", parcels: [{weight: 100, score: 10, name: "-", kind: "retail"}]}}, {baseRate: -2, claim: {active: false, band: "2024-02-29", code: "a", dueDate: "1990-06-15", grade: "a", parcels: [{discount: 10, exposure: 10, flag: "-", kind: "retail", name: "-", net: "2027-02-28T00:00:00Z", score: 10, total: 10, weight: 100}], since: "2024-02-29", verified: false, years: 99.99}}], + [{baseRate: 0.5, claim: {years: 0, verified: false, active: true, dueDate: "2000-01-01", code: "é ü", since: "2025-03-20", parcels: [{weight: "12", score: 0.5, name: "gold", kind: "retail"}]}}, "!error: InputValidationFailed"], + [{baseRate: 0.5, claim: {years: 2, verified: true, active: true, dueDate: "1990-06-15", code: "abc", since: "2000-01-01", parcels: [{weight: 10, score: 50, name: "a-b-c", kind: "corporate"}, {weight: 123456789.123, score: 18, name: "US", kind: "corporate"}, {weight: 1, score: -0, name: "日本", kind: "corporate"}]}}, {baseRate: 0.5, claim: {active: true, band: "2000-01-01", code: "abc", dueDate: "1990-06-15", grade: "2", parcels: [{discount: 22.666666666666666666666666667, exposure: 123456800.123, flag: "a-b-c", kind: "corporate", name: "a-b-c", net: "2003-01-01T00:00:00Z", score: 50, total: 123456800.123, weight: 10}, {discount: 22.666666666666666666666666667, exposure: 123456800.123, flag: "US", kind: "corporate", name: "US", net: "2003-01-01T00:00:00Z", score: 18, total: 123456800.123, weight: 123456789.123}, {discount: 22.666666666666666666666666667, exposure: 0, flag: "日本", kind: "corporate", name: "日本", net: "2003-01-01T00:00:00Z", score: 0, total: 0, weight: 1}], penalty: 2, since: "2000-01-01", verified: true, years: 2}}], + [{baseRate: 10, claim: {years: 10, verified: false, active: true, dueDate: "2025-03-20", code: "a", since: "2024-02-29", parcels: [{weight: 1, score: 0, name: "Zed", kind: "retail"}, {weight: 0.1, score: 1, name: "ok", kind: "corporate"}, {weight: 1, score: 250, name: "é ü", kind: "retail"}, {weight: 100, score: -0.01, name: " pad ", kind: "retail"}]}}, {baseRate: 10, claim: {active: true, band: "2024-02-29", code: "a", dueDate: "2025-03-20", grade: "10", parcels: [{discount: 62.7475, exposure: 0, flag: "10", kind: "retail", name: "Zed", net: "2027-02-28T00:00:00Z", score: 0, total: 0, weight: 1}, {discount: 62.7475, exposure: 1, flag: "10", kind: "corporate", name: "ok", net: "2027-02-28T00:00:00Z", score: 1, total: 1, weight: 0.1}, {discount: 62.7475, exposure: 62.7475, flag: "10", kind: "retail", name: "é ü", net: "2027-02-28T00:00:00Z", score: 250, total: 62.7475, weight: 1}, {discount: 62.7475, exposure: -0.01, flag: "10", kind: "retail", name: " pad ", net: "2027-02-28T00:00:00Z", score: -0.01, total: -0.01, weight: 100}], penalty: 10, since: "2024-02-29", verified: false, years: 10}}], + [{baseRate: 0.5, claim: {years: 0.5, verified: true, active: true, code: "O'Neil", parcels: [{weight: 5, score: 65, kind: "corporate"}]}}, {baseRate: 0.5, claim: {active: true, band: "2025-01-01T00:00:00Z", code: "O'Neil", grade: "O'Neil", parcels: [{discount: 65, exposure: 5, flag: "0.5", kind: "corporate", net: "2028-01-01T00:00:00Z", score: 65, total: 5, weight: 5}], verified: true, years: 0.5}}], + [{baseRate: 0, claim: {years: 1000, verified: false, active: true, dueDate: "2024-02-29", code: "a", since: "2030-12-31", parcels: [{weight: 3, score: 85, name: "a", kind: "retail"}]}}, {baseRate: 0, claim: {active: true, band: "2030-12-31", code: "a", dueDate: "2024-02-29", grade: "a", parcels: [{discount: 85, exposure: 85, flag: "0", kind: "retail", name: "a", net: "2033-12-31T00:00:00Z", score: 85, total: 85, weight: 3}], since: "2030-12-31", verified: false, years: 1000}}], + [{baseRate: -2, claim: {years: 0, verified: false, active: true, dueDate: "2024-01-01", code: "Oslo", since: "2025-03-20T10:15:30Z", parcels: [{weight: 0, score: 50, name: "日本", kind: "corporate"}]}}, {baseRate: -2, claim: {active: true, band: "2025-03-20T10:15:30Z", code: "Oslo", dueDate: "2024-01-01", grade: "Oslo", parcels: [{discount: 50, exposure: 50, flag: "-2", kind: "corporate", name: "日本", net: "2028-03-20T10:15:30Z", score: 50, total: 50, weight: 0}], since: "2025-03-20T10:15:30Z", verified: false, years: 0}}], + [{baseRate: 10, claim: {years: 250, verified: true, active: true, code: "gold", since: "2030-12-31", parcels: [{weight: 0.5, score: null, name: null, kind: "corporate"}, {weight: -0.01, score: 0, name: "-", kind: "retail"}, {weight: 100, score: null, name: "Oslo", kind: "retail"}]}}, {baseRate: 10, claim: {active: true, band: "2030-12-31", code: "gold", grade: "250", parcels: [{discount: 0, exposure: 0, flag: "10", kind: "corporate", name: null, net: "2033-12-31T00:00:00Z", score: null, total: 0, weight: 0.5}, {discount: 0, exposure: 0, flag: "10", kind: "retail", name: "-", net: "2033-12-31T00:00:00Z", score: 0, total: 0, weight: -0.01}, {discount: 0, exposure: 0, flag: "10", kind: "retail", name: "Oslo", net: "2033-12-31T00:00:00Z", score: null, total: 0, weight: 100}], penalty: 250, since: "2030-12-31", verified: true, years: 250}}], + [{baseRate: 100, claim: {years: 2, verified: false, active: true, dueDate: null, code: "ok", since: "2025-03-20T10:15:30Z", parcels: [{weight: 100, score: 100, kind: "retail"}, {weight: 0.5, name: "a", kind: "retail"}, {weight: 2, score: 0.1, kind: "retail"}, {weight: -0, score: 2, name: null, kind: "retail"}]}}, {baseRate: 100, claim: {active: true, band: "2025-03-20T10:15:30Z", code: "ok", dueDate: null, grade: "2", parcels: [{discount: 25.525, exposure: 25.525, flag: "100", kind: "retail", net: "2028-03-20T10:15:30Z", score: 100, total: 25.525, weight: 100}, {discount: 25.525, exposure: 0, flag: "100", kind: "retail", name: "a", net: "2028-03-20T10:15:30Z", total: 0, weight: 0.5}, {discount: 25.525, exposure: 0.1, flag: "100", kind: "retail", net: "2028-03-20T10:15:30Z", score: 0.1, total: 0.1, weight: 2}, {discount: 25.525, exposure: 2, flag: "100", kind: "retail", name: null, net: "2028-03-20T10:15:30Z", score: 2, total: 2, weight: 0}], penalty: 2, since: "2025-03-20T10:15:30Z", verified: false, years: 2}}], + [{baseRate: -2, claim: {years: 18, verified: true, active: false, dueDate: null, code: "-", parcels: [{weight: 0.5, score: 99999999999999999999, name: "a", kind: "retail"}]}}, {baseRate: -2, claim: {active: false, band: "2025-01-01T00:00:00Z", code: "-", dueDate: null, grade: "-", parcels: [{discount: 99999999999999999999, exposure: 18, flag: "a", kind: "retail", name: "a", net: "2028-01-01T00:00:00Z", score: 99999999999999999999, total: 18, weight: 0.5}], verified: true, years: 18}}], + [{baseRate: 0, claim: {years: 2, verified: true, active: false, dueDate: "1990-06-15", code: "US", since: "2024-02-29", parcels: [{weight: 99999999999999999999, score: -0.01, name: "a", kind: "retail"}, {weight: 0.5, score: 65, name: "é ü", kind: "retail"}], extraField: "x"}}, {baseRate: 0, claim: {active: false, band: "2024-02-29", code: "US", dueDate: "1990-06-15", extraField: "x", grade: "2", parcels: [{discount: 32.4950, exposure: -0.01, flag: "a", kind: "retail", name: "a", net: "2027-02-28T00:00:00Z", score: -0.01, total: -0.01, weight: 99999999999999999999}, {discount: 32.4950, exposure: 99999999999999999999.5, flag: "é ü", kind: "retail", name: "é ü", net: "2027-02-28T00:00:00Z", score: 65, total: 99999999999999999999.5, weight: 0.5}], penalty: 2, since: "2024-02-29", verified: true, years: 2}}], + [{baseRate: 0.5, claim: {years: 99.99, verified: true, active: false, dueDate: "2000-01-01", code: "12", since: "2025-03-20", parcels: []}}, {baseRate: 0.5, claim: {active: false, band: "2025-03-20", code: "12", dueDate: "2000-01-01", grade: "12", parcels: [], since: "2025-03-20", verified: true, years: 99.99}}], + [{baseRate: 100, claim: {years: 99999999999999999999, verified: true, active: true, dueDate: "2024-01-01", code: "-", parcels: [{weight: 99999999999999999999, score: 1000, kind: "retail"}, {weight: 1e3, name: "DE", kind: "corporate"}, {weight: 0.5, name: "-", kind: "corporate"}]}}, {baseRate: 100, claim: {active: true, band: "2025-01-01T00:00:00Z", code: "-", dueDate: "2024-01-01", grade: "99999999999999999999", parcels: [{discount: 333.33333333333333333333333333, exposure: 99999999999999999999, flag: "100", kind: "retail", net: "2028-01-01T00:00:00Z", score: 1000, total: 99999999999999999999, weight: 99999999999999999999}, {discount: 333.33333333333333333333333333, exposure: 0, flag: "100", kind: "corporate", name: "DE", net: "2028-01-01T00:00:00Z", total: 0, weight: 1000}, {discount: 333.33333333333333333333333333, exposure: 0, flag: "100", kind: "corporate", name: "-", net: "2028-01-01T00:00:00Z", total: 0, weight: 0.5}], penalty: 99999999999999999999, verified: true, years: 99999999999999999999}}], + [{baseRate: 1, claim: {years: 139, verified: false, active: false, dueDate: "2000-01-01", code: "gold", parcels: [{weight: 10, score: 10, kind: "corporate"}]}}, {baseRate: 1, claim: {active: false, band: "2025-01-01T00:00:00Z", code: "gold", dueDate: "2000-01-01", grade: "gold", parcels: [{discount: 10, exposure: 10, flag: "", kind: "corporate", net: "2028-01-01T00:00:00Z", score: 10, total: 10, weight: 10}], verified: false, years: 139}}], + [{baseRate: 0.5, claim: {years: 123456789.123, verified: true, active: false, dueDate: "2030-12-31", code: "ok", since: "2030-12-31", parcels: [{weight: 100, score: 0, name: "x-y", kind: "retail"}, {weight: 2, score: 5, name: "US", kind: "corporate"}, {weight: 294, score: 0.1, name: "O'Neil", kind: "retail"}, {weight: 0.5, score: 100, name: "12", kind: "retail"}]}}, {baseRate: 0.5, claim: {active: false, band: "2030-12-31", code: "ok", dueDate: "2030-12-31", grade: "123456789", parcels: [{discount: 26.275, exposure: 0, flag: "x-y", kind: "retail", name: "x-y", net: "2033-12-31T00:00:00Z", score: 0, total: 0, weight: 100}, {discount: 26.275, exposure: 396.5, flag: "US", kind: "corporate", name: "US", net: "2033-12-31T00:00:00Z", score: 5, total: 396.5, weight: 2}, {discount: 26.275, exposure: 0.1, flag: "O'Neil", kind: "retail", name: "O'Neil", net: "2033-12-31T00:00:00Z", score: 0.1, total: 0.1, weight: 294}, {discount: 26.275, exposure: 396.5, flag: "12", kind: "retail", name: "12", net: "2033-12-31T00:00:00Z", score: 100, total: 396.5, weight: 0.5}], penalty: 123456789, since: "2030-12-31", verified: true, years: 123456789.123}}], + ], +} + +// seed 331100 (attempt 0) +{ + name: "a 12: account/members: 1 assertion, 3 expression, 2 match, 2 table; 4 root, 3 per-member, 3 top-level computed", + policy: { + models: {account: {days: "number", label: "string?", income: "number", members: "member[]"}, member: {rate: "number", amount: "number", kind: "string(retail|corporate)?"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {match: "member.summary", arms: [["not (account.income >= account.days)", "not ((18 == 0.5 or account.days <= 10))"], ["10 > member.amount", "baseRate in [2..100]"], ["(member.kind ?? '') in ['retail', 'corporate']", "account.income in [16..207]"], ["(member.kind ?? '') != 'corporate'", "member.rate > 0.5"], ["", "member.rate > 250"]]}, + {expression: "account.level", value: "(account.label ?? '') != 'US'"}, + {expression: "member.weighted", value: "baseRate >= baseRate"}, + {table: "t4", inputs: ["account.days", null], outputs: ["account.points", "account.decision"], rules: [ + ["< 50", "", "account.income", ""], + ["", "", "account.days", "account.days"], + ]}, + {expression: "member.capped", value: "member.kind == null"}, + {table: "t6", inputs: ["account.points", "(account.decision ?? 0)"], outputs: ["health", "exposure"], rules: [ + ["18, 250", "> 0", "(account.decision ?? 0)", "(account.label ?? '')"], + ["0.25, 0", "> 0.5", "account.days", "(account.label ?? '')"], + ["1000", "<= 0.25", "(avg(map(account.members, #.amount)) ?? 0)", "((account.label ?? '') + '-' + (account.label ?? ''))"], + ["", "", "0.5", "'VIP'"], + ["1000, 18", "", "0.5", "(account.label ?? '')"], + ["5, 3", "", "baseRate", "(account.label ?? '')"], + ]}, + {assertion: "flag", conditions: [["or", "some(account.members, not (#.summary))", 0], ["or", "not (account.level)", 0], ["and", "health == null", 0], ["or", "(health ?? 0) in [13..104]", 2], ["or", "len((account.level ? (account.label ?? '') : 'DE')) > 1", 0]]}, + {match: "account.surcharge", arms: [["all(account.members, (#.summary and #.capped))", "account.level"], ["", "baseRate == 250"]]}, + ], + }, + cases: [ + [{baseRate: 0.5, account: {days: 50, income: 99999999999999999999, members: [{rate: 250, amount: -1, kind: "corporate"}]}}, {account: {days: 50, decision: 50, income: 99999999999999999999, level: true, members: [{amount: -1, capped: false, kind: "corporate", rate: 250, summary: false, weighted: true}], points: 50, surcharge: false}, baseRate: 0.5, exposure: "VIP", flag: false, health: 0.5}], + [{baseRate: 100, account: {days: 3, label: "Zed", income: 1000, members: [{rate: 10, amount: 0, kind: 5}]}}, "!error: InputValidationFailed"], + [{baseRate: 0.5, account: {days: 5, income: 10, members: [{rate: 18, amount: 0.5}]}}, {account: {days: 5, decision: 5, income: 10, level: true, members: [{amount: 0.5, capped: true, rate: 18, summary: false, weighted: true}], points: 10, surcharge: false}, baseRate: 0.5, exposure: "VIP", flag: false, health: 0.5}], + [{baseRate: -2, account: {days: 50, label: "VIP", income: -0.01, members: [{rate: 250, amount: 18, kind: "retail"}]}}, {account: {days: 50, decision: 50, income: -0.01, label: "VIP", level: true, members: [{amount: 18, capped: false, kind: "retail", rate: 250, summary: true, weighted: true}], points: 50, surcharge: false}, baseRate: -2, exposure: "VIP", flag: true, health: 0.5}], + [{baseRate: 0.5, account: {days: 0.5, income: 10, members: [{rate: 5, amount: 10}, {rate: 0.25, amount: 0.5, kind: "retail"}]}}, {account: {days: 0.5, decision: 0.5, income: 10, level: true, members: [{amount: 10, capped: true, rate: 5, summary: true, weighted: true}, {amount: 0.5, capped: false, kind: "retail", rate: 0.25, summary: false, weighted: true}], points: 10, surcharge: false}, baseRate: 0.5, exposure: "VIP", flag: false, health: 0.5}], + [{baseRate: 100, account: {days: -0.5, label: "gold", income: 250, members: [{rate: 250, amount: 1.5, kind: "retail"}, {rate: 1000000, amount: 1000000, kind: "retail"}]}}, {account: {days: -0.5, decision: -0.5, income: 250, label: "gold", level: true, members: [{amount: 1.5, capped: false, kind: "retail", rate: 250, summary: true, weighted: true}, {amount: 1000000, capped: false, kind: "retail", rate: 1000000, summary: false, weighted: true}], points: 250, surcharge: false}, baseRate: 100, exposure: "VIP", flag: true, health: 0.5}], + [{baseRate: 0, account: {days: 18, label: "A1", income: 250, members: [{rate: 5, amount: -500, kind: "retail"}, {rate: 18, amount: 2, kind: "retail"}, {rate: -0, amount: -0.01, kind: "retail"}], extraField: {nested: true}}}, {account: {days: 18, decision: 18, extraField: {nested: true}, income: 250, label: "A1", level: true, members: [{amount: -500, capped: false, kind: "retail", rate: 5, summary: false, weighted: true}, {amount: 2, capped: false, kind: "retail", rate: 18, summary: false, weighted: true}, {amount: -0.01, capped: false, kind: "retail", rate: 0, summary: false, weighted: true}], points: 250, surcharge: false}, baseRate: 0, exposure: "A1", flag: true, health: 18}], + [{baseRate: -2, account: {days: 0.5, label: "O'Neil", income: 5, members: []}}, {account: {days: 0.5, decision: 0.5, income: 5, label: "O'Neil", level: true, members: [], points: 5, surcharge: true}, baseRate: -2, exposure: "VIP", flag: true, health: 0.5}], + [{baseRate: 0.5, account: {days: 0, label: null, income: 10, members: [{rate: 10, amount: 18}, {rate: -1, amount: 7.25, kind: "corporate"}]}}, {account: {days: 0, decision: 0, income: 10, label: null, level: true, members: [{amount: 18, capped: true, rate: 10, summary: true, weighted: true}, {amount: 7.25, capped: false, kind: "corporate", rate: -1, summary: false, weighted: true}], points: 10, surcharge: false}, baseRate: 0.5, exposure: "VIP", flag: false, health: 0.5}], + [{baseRate: 100, account: {days: 0.5, income: 100, members: []}}, {account: {days: 0.5, decision: 0.5, income: 100, level: true, members: [], points: 100, surcharge: true}, baseRate: 100, exposure: "VIP", flag: false, health: 0.5}], + [{baseRate: 1, account: {days: 18, income: 0.25, members: [{rate: 50, amount: 5, kind: null}, {rate: 3, amount: 0.25, kind: "retail"}, {rate: 50, amount: 0}, {rate: 250, amount: 0}, {rate: 0.5, amount: -0.01, kind: "retail"}]}}, {account: {days: 18, decision: 18, income: 0.25, level: true, members: [{amount: 5, capped: true, kind: null, rate: 50, summary: true, weighted: true}, {amount: 0.25, capped: false, kind: "retail", rate: 3, summary: true, weighted: true}, {amount: 0, capped: true, rate: 50, summary: true, weighted: true}, {amount: 0, capped: true, rate: 250, summary: true, weighted: true}, {amount: -0.01, capped: false, kind: "retail", rate: 0.5, summary: true, weighted: true}], points: 0.25, surcharge: false}, baseRate: 1, exposure: "", flag: false, health: 18}], + [{baseRate: 0, account: {days: -0.5, label: "a", income: 10, members: [{rate: 5, amount: 50, kind: "retail"}, {rate: 1.5, amount: 18, kind: "retail"}, {rate: 0, amount: 250, kind: "retail"}], extraField: 1}}, {account: {days: -0.5, decision: -0.5, extraField: 1, income: 10, label: "a", level: true, members: [{amount: 50, capped: false, kind: "retail", rate: 5, summary: false, weighted: true}, {amount: 18, capped: false, kind: "retail", rate: 1.5, summary: false, weighted: true}, {amount: 250, capped: false, kind: "retail", rate: 0, summary: false, weighted: true}], points: 10, surcharge: false}, baseRate: 0, exposure: "VIP", flag: false, health: 0.5}], + [{baseRate: 100, account: {days: 250, label: "12", income: 1000, members: [{rate: 18, amount: 0, kind: "corporate"}, {rate: 1e3, amount: 1000000, kind: "corporate"}]}}, {account: {days: 250, decision: 250, income: 1000, label: "12", level: true, members: [{amount: 0, capped: false, kind: "corporate", rate: 18, summary: true, weighted: true}, {amount: 1000000, capped: false, kind: "corporate", rate: 1000, summary: false, weighted: true}], points: 250, surcharge: false}, baseRate: 100, exposure: "12", flag: true, health: 250}], + [{baseRate: 1, account: {days: 100, label: "a", income: 250, members: []}}, {account: {days: 100, decision: 100, income: 250, label: "a", level: true, members: [], points: 100, surcharge: true}, baseRate: 1, exposure: "VIP", flag: false, health: 0.5}], + [{baseRate: -2, account: {days: 18, label: "retail", income: 0.1, members: [{rate: 1.5, amount: 0, kind: "retail"}, {rate: 1e3, amount: 5, kind: "corporate"}]}}, {account: {days: 18, decision: 18, income: 0.1, label: "retail", level: true, members: [{amount: 0, capped: false, kind: "retail", rate: 1.5, summary: true, weighted: true}, {amount: 5, capped: false, kind: "corporate", rate: 1000, summary: true, weighted: true}], points: 0.1, surcharge: false}, baseRate: -2, exposure: "VIP", flag: true, health: 0.5}], + [{baseRate: 0, account: {days: 7.25, label: " pad ", income: 18, members: [{rate: 5, amount: 5, kind: "retail"}, {rate: 5, amount: 0.5, kind: "corporate"}, {rate: 0.000001, amount: 250, kind: "corporate"}, {rate: 2, amount: 0.25, kind: "retail"}, {rate: 0, amount: 10, kind: "retail"}]}}, {account: {days: 7.25, decision: 7.25, income: 18, label: " pad ", level: true, members: [{amount: 5, capped: false, kind: "retail", rate: 5, summary: false, weighted: true}, {amount: 0.5, capped: false, kind: "corporate", rate: 5, summary: false, weighted: true}, {amount: 250, capped: false, kind: "corporate", rate: 0.000001, summary: true, weighted: true}, {amount: 0.25, capped: false, kind: "retail", rate: 2, summary: false, weighted: true}, {amount: 10, capped: false, kind: "retail", rate: 0, summary: true, weighted: true}], points: 18, surcharge: false}, baseRate: 0, exposure: " pad ", flag: true, health: 7.25}], + [{baseRate: 0.5, account: {days: -1, income: 0.000001, members: [{rate: 18, amount: 0.25, kind: "retail"}, {rate: -0, amount: 0, kind: "corporate"}]}}, {account: {days: -1, decision: -1, income: 0.000001, level: true, members: [{amount: 0.25, capped: false, kind: "retail", rate: 18, summary: false, weighted: true}, {amount: 0, capped: false, kind: "corporate", rate: 0, summary: false, weighted: true}], points: 0.000001, surcharge: false}, baseRate: 0.5, exposure: "VIP", flag: false, health: 0.5}], + [{baseRate: 0.5, account: {days: 0, label: "US", income: 1e3, members: [{rate: 0.5, amount: 1000, kind: "retail"}, {rate: 99999999999999999999, amount: 0.5, kind: "retail"}, {rate: 5, amount: 0.25, kind: "retail"}, {rate: 0.5, amount: 3, kind: "retail"}], extraField: "x"}}, {account: {days: 0, decision: 0, extraField: "x", income: 1000, label: "US", level: false, members: [{amount: 1000, capped: false, kind: "retail", rate: 0.5, summary: false, weighted: true}, {amount: 0.5, capped: false, kind: "retail", rate: 99999999999999999999, summary: false, weighted: true}, {amount: 0.25, capped: false, kind: "retail", rate: 5, summary: false, weighted: true}, {amount: 3, capped: false, kind: "retail", rate: 0.5, summary: false, weighted: true}], points: 1000, surcharge: false}, baseRate: 0.5, exposure: "US-US", flag: true, health: 250.9375}], + [{baseRate: 0, account: {days: 18, label: "DE", income: 99.99, members: [{rate: 0, amount: 10, kind: "corporate"}, {rate: 50, amount: 3, kind: "retail"}], extraField: 1}}, {account: {days: 18, decision: 18, extraField: 1, income: 99.99, label: "DE", level: true, members: [{amount: 10, capped: false, kind: "corporate", rate: 0, summary: true, weighted: true}, {amount: 3, capped: false, kind: "retail", rate: 50, summary: false, weighted: true}], points: 99.99, surcharge: false}, baseRate: 0, exposure: "VIP", flag: true, health: 0.5}], + [{baseRate: 0, account: {days: 100, label: "gold", income: 250, members: [{rate: 214, amount: 50, kind: "retail"}, {rate: 250, amount: 0.5, kind: null}, {rate: 250, amount: 0}, {rate: 65, amount: 1.5, kind: "corporate"}]}}, {account: {days: 100, decision: 100, income: 250, label: "gold", level: true, members: [{amount: 50, capped: false, kind: "retail", rate: 214, summary: false, weighted: true}, {amount: 0.5, capped: true, kind: null, rate: 250, summary: false, weighted: true}, {amount: 0, capped: true, rate: 250, summary: false, weighted: true}, {amount: 1.5, capped: false, kind: "corporate", rate: 65, summary: false, weighted: true}], points: 100, surcharge: false}, baseRate: 0, exposure: "VIP", flag: true, health: 0.5}], + ], +} + +// seed 331200 (attempt 0) +{ + name: "a 13: applicant/vehicles: 1 assertion, 2 match, 1 table; 1 root, 2 per-member, 1 top-level computed", + policy: { + models: {applicant: {balance: "number", kind: "string(retail|corporate)", amount: "number?", code: "string?", vip: "boolean", openedAt: "date", vehicles: "vehicle[]"}, vehicle: {price: "number", score: "number", birthDate: "date?", kind: "string(retail|corporate)"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {match: "vehicle.fee", arms: [["vehicle.kind in ['corporate', 'retail']", "(applicant.code ?? '')"], ["", "'ok'"]]}, + {table: "t2", hit: "collect", inputs: ["vehicle.kind", "applicant.code", null], outputs: ["vehicle.capped"], rules: [ + ["'retail'", "'a'", "", "applicant.vip"], + ["'retail'", "", "vehicle.price <= cap", "applicant.vip"], + ["", "'ok'", "vehicle.fee in ['a', 'ok']", "applicant.vip"], + ["'corporate', 'retail'", "'US'", "", "applicant.vip"], + ]}, + {match: "adjusted", arms: [["((applicant.amount ?? 0) * cap) != (applicant.amount ?? 0)", "(applicant.amount ?? 0)"], ["len((applicant.code ?? '')) > 0", "applicant.openedAt.year()"], ["len((applicant.code ?? '')) > 3", "cap"], ["(none(applicant.vehicles, 3 >= #.score) or all(applicant.vehicles, #.price > #.price))", "(cap + 0)"], ["", "cap"]]}, + {assertion: "applicant.weighted", conditions: [["and", "cap < adjusted", 1], ["or", "1000 != (applicant.amount ?? 0)", 2], "(applicant.balance) / (abs(250) + 1) == 0", ["and", "none(applicant.vehicles, (#.birthDate ?? d('2025-01-01')) >= d('2024-01-01'))", 0]]}, + ], + }, + cases: [ + [{cap: 0.5, applicant: {balance: 65, kind: "corporate", amount: 0.5, code: "ok", vip: false, openedAt: "2000-01-01", vehicles: [{price: 10, score: 0, birthDate: "2025-03-20", kind: "retail"}, {price: 2.50, score: 123456789.123, birthDate: "2030-12-31", kind: "retail"}, {price: 7.25, score: 250, birthDate: "2024-02-29", kind: "corporate"}]}}, {adjusted: 0.5, applicant: {amount: 0.5, balance: 65, code: "ok", kind: "corporate", openedAt: "2000-01-01", vehicles: [{birthDate: "2025-03-20", capped: [false], fee: "ok", kind: "retail", price: 10, score: 0}, {birthDate: "2030-12-31", capped: [false], fee: "ok", kind: "retail", price: 2.50, score: 123456789.123}, {birthDate: "2024-02-29", capped: [false], fee: "ok", kind: "corporate", price: 7.25, score: 250}], vip: false, weighted: false}, cap: 0.5}], + [{cap: 10, applicant: {balance: 0.5, kind: "retail", amount: -0.5, code: "é ü", vip: false, openedAt: "2025-03-20", vehicles: [{price: 250, score: 0.000001, birthDate: "1990-06-15", kind: "retail"}, {price: 0, score: 10, birthDate: "2025-03-20", kind: "corporate"}, {price: 3, score: 99.99, birthDate: "2030-12-31", kind: "retail"}], extraField: 1}}, {adjusted: -0.5, applicant: {amount: -0.5, balance: 0.5, code: "é ü", extraField: 1, kind: "retail", openedAt: "2025-03-20", vehicles: [{birthDate: "1990-06-15", capped: [], fee: "é ü", kind: "retail", price: 250, score: 0.000001}, {birthDate: "2025-03-20", capped: [], fee: "é ü", kind: "corporate", price: 0, score: 10}, {birthDate: "2030-12-31", capped: [false], fee: "é ü", kind: "retail", price: 3, score: 99.99}], vip: false, weighted: false}, cap: 10}], + [{cap: 0, applicant: {balance: 0, kind: "retail", amount: 65, code: "ok", vip: true, openedAt: "2024-01-01", vehicles: [{price: 7.25, score: 0.1, birthDate: "2025-03-20", kind: "retail"}, {price: 100, score: 0, birthDate: null, kind: "retail"}]}}, {adjusted: 65, applicant: {amount: 65, balance: 0, code: "ok", kind: "retail", openedAt: "2024-01-01", vehicles: [{birthDate: "2025-03-20", capped: [true], fee: "ok", kind: "retail", price: 7.25, score: 0.1}, {birthDate: null, capped: [true], fee: "ok", kind: "retail", price: 100, score: 0}], vip: true, weighted: false}, cap: 0}], + [{cap: 1, applicant: {balance: -0.01, kind: "retail", vip: true, openedAt: "2000-01-01", vehicles: [{price: 250, score: 99.99, birthDate: "2024-02-29", kind: "corporate"}]}}, {adjusted: 1, applicant: {balance: -0.01, kind: "retail", openedAt: "2000-01-01", vehicles: [{birthDate: "2024-02-29", capped: [], fee: "", kind: "corporate", price: 250, score: 99.99}], vip: true, weighted: false}, cap: 1}], + [{cap: 1, applicant: {balance: 10, kind: "retail", amount: 0.1, vip: true, openedAt: "2024-01-01", vehicles: [{price: 7.25, score: 1000000, birthDate: "2000-01-01", kind: "retail"}, {price: 446, score: 65, kind: "corporate"}]}}, {adjusted: 1, applicant: {amount: 0.1, balance: 10, kind: "retail", openedAt: "2024-01-01", vehicles: [{birthDate: "2000-01-01", capped: [], fee: "", kind: "retail", price: 7.25, score: 1000000}, {capped: [], fee: "", kind: "corporate", price: 446, score: 65}], vip: true, weighted: false}, cap: 1}], + [{cap: 0.5, applicant: {balance: 0, kind: null, amount: 0.5, code: "ok", vip: true, openedAt: "2000-01-01", vehicles: [{price: 1000, score: 1e3, birthDate: "2000-01-01", kind: "corporate"}, {price: 0.5, score: 250, birthDate: "1990-06-15", kind: "retail"}, {price: 0.1, score: 99.99, birthDate: "2025-03-20", kind: "corporate"}, {price: 1, score: -0.01, birthDate: "2030-12-31", kind: "corporate"}, {price: 0.000001, score: -0.5, birthDate: "2024-02-29", kind: "corporate"}]}}, {adjusted: 0.5, applicant: {amount: 0.5, balance: 0, code: "ok", kind: null, openedAt: "2000-01-01", vehicles: [{birthDate: "2000-01-01", capped: [true], fee: "ok", kind: "corporate", price: 1000, score: 1000}, {birthDate: "1990-06-15", capped: [true, true], fee: "ok", kind: "retail", price: 0.5, score: 250}, {birthDate: "2025-03-20", capped: [true], fee: "ok", kind: "corporate", price: 0.1, score: 99.99}, {birthDate: "2030-12-31", capped: [true], fee: "ok", kind: "corporate", price: 1, score: -0.01}, {birthDate: "2024-02-29", capped: [true], fee: "ok", kind: "corporate", price: 0.000001, score: -0.5}], vip: true, weighted: false}, cap: 0.5}], + [{cap: 0.5, applicant: {balance: 0, kind: "retail", amount: 1e3, code: null, vip: true, openedAt: "1990-06-15", vehicles: [{price: 1000000, score: 0.000001, kind: "corporate"}, {price: -1, score: -1, birthDate: "2024-01-01", kind: "corporate"}, {price: 5, score: 3, birthDate: null, kind: "retail"}]}}, {adjusted: 1000, applicant: {amount: 1000, balance: 0, code: null, kind: "retail", openedAt: "1990-06-15", vehicles: [{capped: [], fee: "", kind: "corporate", price: 1000000, score: 0.000001}, {birthDate: "2024-01-01", capped: [], fee: "", kind: "corporate", price: -1, score: -1}, {birthDate: null, capped: [], fee: "", kind: "retail", price: 5, score: 3}], vip: true, weighted: false}, cap: 0.5}], + [{cap: -2, applicant: {balance: 3, kind: "retail", amount: 0, code: "ok", vip: true, openedAt: "2024-01-01", vehicles: []}}, {adjusted: 2024, applicant: {amount: 0, balance: 3, code: "ok", kind: "retail", openedAt: "2024-01-01", vehicles: [], vip: true, weighted: true}, cap: -2}], + [{cap: 0.5, applicant: {balance: -500, kind: "retail", amount: 90, code: "US", vip: true, openedAt: "2000-01-01", vehicles: [{price: 1000000, score: -0.01, birthDate: "1990-06-15", kind: "corporate"}, {price: 0, score: 123456789.123, birthDate: "1990-06-15", kind: "retail"}]}}, {adjusted: 90, applicant: {amount: 90, balance: -500, code: "US", kind: "retail", openedAt: "2000-01-01", vehicles: [{birthDate: "1990-06-15", capped: [true], fee: "US", kind: "corporate", price: 1000000, score: -0.01}, {birthDate: "1990-06-15", capped: [true, true], fee: "US", kind: "retail", price: 0, score: 123456789.123}], vip: true, weighted: true}, cap: 0.5}], + [{cap: 0.5, applicant: {balance: 0.1, kind: "retail", vip: false, openedAt: "2024-02-29", vehicles: [{price: 250, score: 250, kind: "retail"}, {price: -0, score: 99.99, birthDate: "2025-03-20T10:15:30Z", kind: "corporate"}]}}, {adjusted: 0.5, applicant: {balance: 0.1, kind: "retail", openedAt: "2024-02-29", vehicles: [{capped: [], fee: "", kind: "retail", price: 250, score: 250}, {birthDate: "2025-03-20T10:15:30Z", capped: [], fee: "", kind: "corporate", price: 0, score: 99.99}], vip: false, weighted: false}, cap: 0.5}], + [{cap: 1, applicant: {balance: -0.5, kind: "corporate", amount: 0, code: "12", vip: false, openedAt: "2025-03-20", vehicles: []}}, {adjusted: 2025, applicant: {amount: 0, balance: -0.5, code: "12", kind: "corporate", openedAt: "2025-03-20", vehicles: [], vip: false, weighted: true}, cap: 1}], + [{cap: 10, applicant: {balance: 0, kind: "retail", amount: 0.5, code: "a-b-c", vip: false, openedAt: "1990-06-15", vehicles: [{price: 7.25, score: 65, birthDate: "2025-03-20", kind: "retail"}, {price: 0.5, score: 250, birthDate: "1990-06-15", kind: "corporate"}]}}, {adjusted: 0.5, applicant: {amount: 0.5, balance: 0, code: "a-b-c", kind: "retail", openedAt: "1990-06-15", vehicles: [{birthDate: "2025-03-20", capped: [false], fee: "a-b-c", kind: "retail", price: 7.25, score: 65}, {birthDate: "1990-06-15", capped: [], fee: "a-b-c", kind: "corporate", price: 0.5, score: 250}], vip: false, weighted: false}, cap: 10}], + [{cap: 0.5, applicant: {balance: -0.01, kind: "corporate", amount: 123456789.123, code: "日本", vip: true, openedAt: "2000-01-01", vehicles: [{price: 7.25, score: 177, birthDate: "2024-02-29", kind: "retail"}, {price: 0, score: -0.5, birthDate: "2025-03-20T10:15:30Z", kind: "retail"}]}}, {adjusted: 123456789.123, applicant: {amount: 123456789.123, balance: -0.01, code: "日本", kind: "corporate", openedAt: "2000-01-01", vehicles: [{birthDate: "2024-02-29", capped: [], fee: "日本", kind: "retail", price: 7.25, score: 177}, {birthDate: "2025-03-20T10:15:30Z", capped: [true], fee: "日本", kind: "retail", price: 0, score: -0.5}], vip: true, weighted: false}, cap: 0.5}], + [{cap: 0.5, applicant: {balance: 1000000, kind: "retail", amount: 0, code: " pad ", vip: false, openedAt: "2025-03-20T10:15:30Z", vehicles: [{price: 65, score: 123456789.123, birthDate: "2024-02-29", kind: "retail"}]}}, {adjusted: 2025, applicant: {amount: 0, balance: 1000000, code: " pad ", kind: "retail", openedAt: "2025-03-20T10:15:30Z", vehicles: [{birthDate: "2024-02-29", capped: [], fee: " pad ", kind: "retail", price: 65, score: 123456789.123}], vip: false, weighted: false}, cap: 0.5}], + [{cap: 0, applicant: {balance: 1000000, kind: "retail", amount: null, vip: true, openedAt: "2025-03-20T10:15:30Z", vehicles: [{price: 3, score: 0, birthDate: "2025-03-20T10:15:30Z", kind: "retail"}, {price: 0, score: 2, birthDate: "2024-02-29", kind: "retail"}]}}, {adjusted: 0, applicant: {amount: null, balance: 1000000, kind: "retail", openedAt: "2025-03-20T10:15:30Z", vehicles: [{birthDate: "2025-03-20T10:15:30Z", capped: [], fee: "", kind: "retail", price: 3, score: 0}, {birthDate: "2024-02-29", capped: [true], fee: "", kind: "retail", price: 0, score: 2}], vip: true, weighted: false}, cap: 0}], + [{cap: 100, applicant: {balance: -1, kind: "retail", amount: null, code: null, vip: false, openedAt: "2025-03-20", vehicles: [{price: 100, score: 1000000, kind: "retail"}, {price: 99.99, score: 0.1, kind: "retail"}, {price: 0, score: 0, kind: "corporate"}, {price: 99999999999999999999, score: 0, birthDate: "2024-02-29", kind: "corporate"}, {price: 10, score: 1000000, kind: "corporate"}]}}, {adjusted: 100, applicant: {amount: null, balance: -1, code: null, kind: "retail", openedAt: "2025-03-20", vehicles: [{capped: [false], fee: "", kind: "retail", price: 100, score: 1000000}, {capped: [false], fee: "", kind: "retail", price: 99.99, score: 0.1}, {capped: [], fee: "", kind: "corporate", price: 0, score: 0}, {birthDate: "2024-02-29", capped: [], fee: "", kind: "corporate", price: 99999999999999999999, score: 0}, {capped: [], fee: "", kind: "corporate", price: 10, score: 1000000}], vip: false, weighted: false}, cap: 100}], + [{cap: -2, applicant: {balance: 0.1, kind: "corporate", amount: 99999999999999999999, code: " pad ", vip: true, openedAt: "2025-03-20", vehicles: [{price: -0, score: 18, birthDate: "2024-01-01", kind: "retail"}]}}, {adjusted: 99999999999999999999, applicant: {amount: 99999999999999999999, balance: 0.1, code: " pad ", kind: "corporate", openedAt: "2025-03-20", vehicles: [{birthDate: "2024-01-01", capped: [], fee: " pad ", kind: "retail", price: 0, score: 18}], vip: true, weighted: false}, cap: -2}], + [{cap: 10, applicant: {balance: 18, kind: "retail", amount: 1e3, code: "日本", vip: true, openedAt: "2030-12-31", vehicles: [{price: 65, score: -500, birthDate: "2024-02-29", kind: "corporate"}, {price: 99999999999999999999, score: 1000000, birthDate: "2000-01-01", kind: "retail"}]}}, {adjusted: 1000, applicant: {amount: 1000, balance: 18, code: "日本", kind: "retail", openedAt: "2030-12-31", vehicles: [{birthDate: "2024-02-29", capped: [], fee: "日本", kind: "corporate", price: 65, score: -500}, {birthDate: "2000-01-01", capped: [], fee: "日本", kind: "retail", price: 99999999999999999999, score: 1000000}], vip: true, weighted: false}, cap: 10}], + [{cap: 100, applicant: {balance: 18, kind: "retail", amount: 311, code: "ok", vip: false, openedAt: "1990-06-15", vehicles: []}}, {adjusted: 311, applicant: {amount: 311, balance: 18, code: "ok", kind: "retail", openedAt: "1990-06-15", vehicles: [], vip: false, weighted: true}, cap: 100}], + [{cap: 0, applicant: {balance: 0, kind: "retail", amount: 3, code: "ok", vip: true, openedAt: "1990-06-15", vehicles: [{price: 10, score: 250, birthDate: "2024-01-01", kind: "retail"}, {price: 99.99, score: 1000000, birthDate: "2030-12-31", kind: "retail"}], extraField: {nested: true}}}, {adjusted: 3, applicant: {amount: 3, balance: 0, code: "ok", extraField: {nested: true}, kind: "retail", openedAt: "1990-06-15", vehicles: [{birthDate: "2024-01-01", capped: [true], fee: "ok", kind: "retail", price: 10, score: 250}, {birthDate: "2030-12-31", capped: [true], fee: "ok", kind: "retail", price: 99.99, score: 1000000}], vip: true, weighted: false}, cap: 0}], + [{cap: 100, applicant: {balance: -1, kind: "retail", amount: 5, code: "a", vip: false, vehicles: [{price: 0.5, score: 99.99, birthDate: "2025-03-20T10:15:30Z", kind: "corporate"}, {price: 1000000, score: 65, birthDate: "2024-01-01", kind: "retail"}, {price: 157, score: -1, birthDate: "2000-01-01", kind: "corporate"}, {price: 2.50, score: 5, birthDate: "1990-06-15", kind: "retail"}]}}, "!error: MissingRequiredInputs"], + [{cap: 0.5, applicant: {balance: 0, kind: "corporate", amount: 106, code: "A1", vip: false, openedAt: "2025-03-20T10:15:30Z", vehicles: [{price: 1, score: -1, birthDate: "2030-12-31", kind: "retail"}, {price: 123456789.123, score: -0.5, birthDate: "1990-06-15", kind: "corporate"}, {price: 0.000001, score: -0, birthDate: "2024-02-29", kind: "retail"}, {price: 0.1, score: -0.5, birthDate: "2024-01-01", kind: "retail"}, {price: 1000, score: 1e3, birthDate: "2030-12-31", kind: "retail"}]}}, {adjusted: 106, applicant: {amount: 106, balance: 0, code: "A1", kind: "corporate", openedAt: "2025-03-20T10:15:30Z", vehicles: [{birthDate: "2030-12-31", capped: [], fee: "A1", kind: "retail", price: 1, score: -1}, {birthDate: "1990-06-15", capped: [], fee: "A1", kind: "corporate", price: 123456789.123, score: -0.5}, {birthDate: "2024-02-29", capped: [false], fee: "A1", kind: "retail", price: 0.000001, score: 0}, {birthDate: "2024-01-01", capped: [false], fee: "A1", kind: "retail", price: 0.1, score: -0.5}, {birthDate: "2030-12-31", capped: [], fee: "A1", kind: "retail", price: 1000, score: 1000}], vip: false, weighted: false}, cap: 0.5}], + [{cap: 0, applicant: {balance: 1000, kind: "corporate", vip: false, openedAt: "2030-12-31", vehicles: [{price: 454, score: 2.50, birthDate: "2025-03-20", kind: "retail"}, {price: 1e3, score: 250, birthDate: "1990-06-15", kind: "retail"}, {price: 1, score: 1000, birthDate: "2025-03-20T10:15:30Z", kind: "retail"}, {price: -1, score: 0.5, birthDate: "2024-02-29", kind: "corporate"}, {price: 1000000, score: 250, kind: "retail"}]}}, {adjusted: 0, applicant: {balance: 1000, kind: "corporate", openedAt: "2030-12-31", vehicles: [{birthDate: "2025-03-20", capped: [], fee: "", kind: "retail", price: 454, score: 2.50}, {birthDate: "1990-06-15", capped: [], fee: "", kind: "retail", price: 1000, score: 250}, {birthDate: "2025-03-20T10:15:30Z", capped: [], fee: "", kind: "retail", price: 1, score: 1000}, {birthDate: "2024-02-29", capped: [], fee: "", kind: "corporate", price: -1, score: 0.5}, {capped: [], fee: "", kind: "retail", price: 1000000, score: 250}], vip: false, weighted: false}, cap: 0}], + [{cap: 0, applicant: {balance: -0.01, kind: "corporate", vip: true, openedAt: "1990-06-15", vehicles: [{price: 1000, score: 10, birthDate: null, kind: "retail"}]}}, {adjusted: 0, applicant: {balance: -0.01, kind: "corporate", openedAt: "1990-06-15", vehicles: [{birthDate: null, capped: [], fee: "", kind: "retail", price: 1000, score: 10}], vip: true, weighted: false}, cap: 0}], + [{cap: 0.5, applicant: {balance: 250, kind: "corporate", amount: -1, code: "Zed", vip: true, openedAt: "2025-03-20T10:15:30Z", vehicles: [{price: 99999999999999999999, score: -500, kind: "retail"}, {price: 0.5, score: 1000000, birthDate: "2025-03-20", kind: "retail"}, {price: 1000, score: 5, birthDate: "2025-03-20", kind: "retail"}]}}, {adjusted: -1, applicant: {amount: -1, balance: 250, code: "Zed", kind: "corporate", openedAt: "2025-03-20T10:15:30Z", vehicles: [{capped: [], fee: "Zed", kind: "retail", price: 99999999999999999999, score: -500}, {birthDate: "2025-03-20", capped: [true], fee: "Zed", kind: "retail", price: 0.5, score: 1000000}, {birthDate: "2025-03-20", capped: [], fee: "Zed", kind: "retail", price: 1000, score: 5}], vip: true, weighted: false}, cap: 0.5}], + [{cap: -2, applicant: {balance: 7.25, kind: "retail", code: "NL", vip: true, openedAt: "1990-06-15", vehicles: [{price: -0.01, score: 0, kind: "retail"}, {price: 99.99, score: 1000, kind: "retail"}]}}, {adjusted: 1990, applicant: {balance: 7.25, code: "NL", kind: "retail", openedAt: "1990-06-15", vehicles: [{capped: [], fee: "NL", kind: "retail", price: -0.01, score: 0}, {capped: [], fee: "NL", kind: "retail", price: 99.99, score: 1000}], vip: true, weighted: false}, cap: -2}], + [{cap: 1, applicant: {balance: -0.5, kind: "corporate", code: "é ü", vip: true, openedAt: "2025-03-20", vehicles: [{price: 7.25, score: 123456789.123, kind: "retail"}, {price: 2.50, score: -0.01, birthDate: null, kind: "retail"}, {price: 18, score: 222, birthDate: "2030-12-31", kind: "retail"}]}}, {adjusted: 2025, applicant: {balance: -0.5, code: "é ü", kind: "corporate", openedAt: "2025-03-20", vehicles: [{capped: [], fee: "é ü", kind: "retail", price: 7.25, score: 123456789.123}, {birthDate: null, capped: [], fee: "é ü", kind: "retail", price: 2.50, score: -0.01}, {birthDate: "2030-12-31", capped: [], fee: "é ü", kind: "retail", price: 18, score: 222}], vip: true, weighted: false}, cap: 1}], + [{cap: 100, applicant: {balance: -1, kind: "corporate", amount: 99.99, code: "Zed", vip: false, openedAt: "2024-02-29", vehicles: [{price: 0.000001, score: 0.000001, birthDate: "2025-03-20T10:15:30Z", kind: "retail"}, {price: -1, score: -500, birthDate: "2024-01-01", kind: "corporate"}, {price: 0, score: -500, birthDate: "2025-03-20T10:15:30Z", kind: "corporate"}, {price: 0.1, score: -0.5, birthDate: "2000-01-01", kind: "retail"}]}}, {adjusted: 99.99, applicant: {amount: 99.99, balance: -1, code: "Zed", kind: "corporate", openedAt: "2024-02-29", vehicles: [{birthDate: "2025-03-20T10:15:30Z", capped: [false], fee: "Zed", kind: "retail", price: 0.000001, score: 0.000001}, {birthDate: "2024-01-01", capped: [], fee: "Zed", kind: "corporate", price: -1, score: -500}, {birthDate: "2025-03-20T10:15:30Z", capped: [], fee: "Zed", kind: "corporate", price: 0, score: -500}, {birthDate: "2000-01-01", capped: [false], fee: "Zed", kind: "retail", price: 0.1, score: -0.5}], vip: false, weighted: false}, cap: 100}], + ], +} + +// seed 331300 (attempt 0) +{ + name: "a 14: order/members: 4 expression, 2 match, 2 table; 3 root, 8 per-member, 1 top-level computed", + policy: { + models: {order: {weight: "number", amount: "number", dueDate: "date", channel: "string", members: "member[]"}, member: {age: "number", verified: "boolean", region: "string"}}, + blocks: [ + {table: "t1", inputs: [null, "sum(map(order.members, #.age))"], outputs: ["order.bonus", "order.eligible", "order.fee"], rules: [ + ["order.channel in ['retail', 'ok']", "0.25, 0.25", "order.amount <= 100", "order.channel", "order.amount"], + ["order.dueDate >= d('2024-01-01')", "", "order.amount <= 10", "order.channel", "order.amount"], + ["", "", "", "string(order.weight)", "(order.weight + 0)"], + ["(order.weight <= 1 or order.amount == 0.5)", "<= 50", "order.channel in ['A1', 'Oslo']", "order.channel", "order.weight"], + ["order.weight != order.weight", "", "order.amount <= 2", "order.channel", "order.amount"], + ]}, + {match: "member.review", arms: [["order.eligible != null", "10 < member.age"], ["", "member.verified"]]}, + {match: "member.summary", arms: [["count(order.members, #.age > #.age) > member.age", "((order.bonus ?? false) or member.verified)"], ["(order.fee ?? 0) < 1.5", "order.channel in ['Oslo', 'Oslo']"], ["order.dueDate > d('2024-01-01')", "(order.bonus ?? false)"], ["", "member.review"]]}, + {expression: "member.level", value: "(sum(map(order.members, #.age)) != order.amount ? (((order.fee ?? 0) + (order.fee ?? 0))) / (abs((member.age + member.age)) + 1) : ((member.review ? order.weight : order.weight)) / (abs(order.amount) + 1))"}, + {expression: "member.health", value: "none(order.members, #.region == 'gold')"}, + {table: "t6", hit: "collect", inputs: ["order.weight", "order.dueDate", "member.region"], outputs: ["member.exposure", "member.adjusted", "member.flag"], rules: [ + ["< 1.5", ">= d('2025-03-20')", "'ok', 'gold'", "string(member.level)", "order.weight", "len(order.members)"], + ["<= 0.5", "< d('2000-06-30')", "'x'", "(order.eligible ?? '')", "order.weight", "member.level"], + ["<= 250", ">= d('2024-01-01')", "", "order.channel", "order.amount", "((order.bonus ?? false) ? (order.fee ?? 0) : (order.fee ?? 0))"], + ["3, 0.5", ">= d('2025-01-01')", "startsWith($, 'high')", "(order.eligible ?? '')", "order.amount", "(order.fee ?? 0)"], + ["10, 18", ">= d('2000-06-30')", "startsWith($, 'VIP')", "string(member.age)", "", ""], + ["> 10", ">= d('2025-03-20')", "'Oslo'", "member.region", "0.25", "order.weight"], + ]}, + {expression: "quota", value: "(order.weight + (order.fee ?? 0))"}, + {expression: "member.bucket", value: "order.dueDate"}, + ], + }, + cases: [ + [{order: {weight: 10, amount: 3, dueDate: "1990-06-15", channel: "abc", members: [{age: 0, verified: false, region: "Zed"}, {age: 2.50, verified: false, region: "US"}, {age: 1e3, verified: false, region: "Oslo"}, {age: 2.50, verified: false, region: "O'Neil"}, {age: 0.5, verified: false, region: "A1"}]}}, {order: {amount: 3, bonus: null, channel: "abc", dueDate: "1990-06-15", eligible: "10", fee: 10, members: [{adjusted: [], age: 0, bucket: "1990-06-15", exposure: [], flag: [], health: true, region: "Zed", review: false, summary: false, verified: false}, {adjusted: [], age: 2.50, bucket: "1990-06-15", exposure: [], flag: [], health: true, region: "US", review: false, summary: false, verified: false}, {adjusted: [], age: 1000, bucket: "1990-06-15", exposure: [], flag: [], health: true, region: "Oslo", review: true, summary: true, verified: false}, {adjusted: [], age: 2.50, bucket: "1990-06-15", exposure: [], flag: [], health: true, region: "O'Neil", review: false, summary: false, verified: false}, {adjusted: [], age: 0.5, bucket: "1990-06-15", exposure: [], flag: [], health: true, region: "A1", review: false, summary: false, verified: false}], weight: 10}, quota: 20}], + [{order: {weight: 1000000, amount: 100, dueDate: "2025-03-20", channel: "Oslo", members: [{age: 2, verified: true, region: "Oslo"}, {age: 100, verified: true, region: "a"}, {age: 100, verified: false, region: "-"}, {age: 10, verified: false, region: "Oslo"}, {age: 99.99, verified: false, region: " pad "}]}}, {order: {amount: 100, bonus: false, channel: "Oslo", dueDate: "2025-03-20", eligible: "Oslo", fee: 100, members: [{adjusted: [0.25], age: 2, bucket: "2025-03-20", exposure: ["Oslo"], flag: [1000000], health: true, region: "Oslo", summary: false, verified: true}, {adjusted: [], age: 100, bucket: "2025-03-20", exposure: [], flag: [], health: true, region: "a", summary: false, verified: true}, {adjusted: [], age: 100, bucket: "2025-03-20", exposure: [], flag: [], health: true, region: "-", summary: false, verified: false}, {adjusted: [0.25], age: 10, bucket: "2025-03-20", exposure: ["Oslo"], flag: [1000000], health: true, region: "Oslo", summary: false, verified: false}, {adjusted: [], age: 99.99, bucket: "2025-03-20", exposure: [], flag: [], health: true, region: " pad ", summary: false, verified: false}], weight: 1000000}, quota: 1000100}], + [{order: {weight: 10, amount: 342, dueDate: "2024-02-29", channel: "O'Neil", members: [{age: 0, verified: true, region: "high"}, {age: 50, verified: true, region: "DE"}, {age: 1, verified: false, region: "Oslo"}, {age: 0.1, verified: false, region: "none"}, {age: 2, verified: false, region: "Oslo"}]}}, {order: {amount: 342, bonus: false, channel: "O'Neil", dueDate: "2024-02-29", eligible: "O'Neil", fee: 342, members: [{adjusted: [342], age: 0, bucket: "2024-02-29", exposure: ["O'Neil"], flag: [342], health: true, region: "high", summary: false, verified: true}, {adjusted: [342], age: 50, bucket: "2024-02-29", exposure: ["O'Neil"], flag: [342], health: true, region: "DE", summary: false, verified: true}, {adjusted: [342], age: 1, bucket: "2024-02-29", exposure: ["O'Neil"], flag: [342], health: true, region: "Oslo", summary: false, verified: false}, {adjusted: [342], age: 0.1, bucket: "2024-02-29", exposure: ["O'Neil"], flag: [342], health: true, region: "none", summary: false, verified: false}, {adjusted: [342], age: 2, bucket: "2024-02-29", exposure: ["O'Neil"], flag: [342], health: true, region: "Oslo", summary: false, verified: false}], weight: 10}, quota: 352}], + [{order: {weight: 1, amount: 1, dueDate: "2000-01-01", channel: "Zed", members: [{age: 3, verified: false, region: "Zed"}, {age: 0.25, verified: true, region: "A1"}]}}, {order: {amount: 1, bonus: false, channel: "Zed", dueDate: "2000-01-01", eligible: "1", fee: 1, members: [{adjusted: [], age: 3, bucket: "2000-01-01", exposure: [], flag: [], health: true, region: "Zed", summary: false, verified: false}, {adjusted: [], age: 0.25, bucket: "2000-01-01", exposure: [], flag: [], health: true, region: "A1", summary: false, verified: true}], weight: 1}, quota: 2}], + [{order: {weight: -0.5, amount: 0.25, dueDate: "2024-01-01", channel: "DE", members: [{age: 3, verified: false, region: "O'Neil"}]}}, {order: {amount: 0.25, bonus: true, channel: "DE", dueDate: "2024-01-01", eligible: "DE", fee: 0.25, members: [{adjusted: [0.25], age: 3, bucket: "2024-01-01", exposure: ["DE"], flag: [0.25], health: true, region: "O'Neil", summary: false, verified: false}], weight: -0.5}, quota: -0.25}], + [{order: {weight: 50, amount: 1, dueDate: "2030-12-31", channel: "Oslo", members: [{age: 18, verified: true, region: "high"}, {age: 10, verified: false, region: "VIP"}]}}, {order: {amount: 1, bonus: true, channel: "Oslo", dueDate: "2030-12-31", eligible: "Oslo", fee: 1, members: [{adjusted: [1], age: 18, bucket: "2030-12-31", exposure: ["Oslo"], flag: [1], health: true, region: "high", summary: true, verified: true}, {adjusted: [1], age: 10, bucket: "2030-12-31", exposure: ["Oslo"], flag: [1], health: true, region: "VIP", summary: true, verified: false}], weight: 50}, quota: 51}], + [{order: {weight: 2, amount: 1, dueDate: "2024-01-01", channel: "VIP", members: [{age: 0.5, verified: true, region: "-"}, {age: 10, verified: true, region: "gold"}, {age: 0.5, verified: true, region: "A1"}, {age: 3, verified: true, region: "-"}]}}, {order: {amount: 1, bonus: true, channel: "VIP", dueDate: "2024-01-01", eligible: "VIP", fee: 1, members: [{adjusted: [1], age: 0.5, bucket: "2024-01-01", exposure: ["VIP"], flag: [1], health: false, region: "-", summary: false, verified: true}, {adjusted: [1], age: 10, bucket: "2024-01-01", exposure: ["VIP"], flag: [1], health: false, region: "gold", summary: false, verified: true}, {adjusted: [1], age: 0.5, bucket: "2024-01-01", exposure: ["VIP"], flag: [1], health: false, region: "A1", summary: false, verified: true}, {adjusted: [1], age: 3, bucket: "2024-01-01", exposure: ["VIP"], flag: [1], health: false, region: "-", summary: false, verified: true}], weight: 2}, quota: 3}], + [{order: {weight: 1.5, amount: -500, dueDate: "2024-01-01", channel: "é ü", members: [{age: 0.25, verified: false, region: " pad "}, {age: 3, verified: false, region: "O'Neil"}]}}, {order: {amount: -500, bonus: true, channel: "é ü", dueDate: "2024-01-01", eligible: "é ü", fee: -500, members: [{adjusted: [-500], age: 0.25, bucket: "2024-01-01", exposure: ["é ü"], flag: [-500], health: true, region: " pad ", summary: false, verified: false}, {adjusted: [-500], age: 3, bucket: "2024-01-01", exposure: ["é ü"], flag: [-500], health: true, region: "O'Neil", summary: false, verified: false}], weight: 1.5}, quota: -498.5}], + [{order: {weight: 18, amount: 1, dueDate: "1990-06-15", channel: "Oslo", members: [{age: 18, verified: false, region: "Zed"}, {age: -0, verified: true, region: "Oslo"}]}}, {order: {amount: 1, bonus: null, channel: "Oslo", dueDate: "1990-06-15", eligible: "18", fee: 18, members: [{adjusted: [], age: 18, bucket: "1990-06-15", exposure: [], flag: [], health: true, region: "Zed", review: true, summary: true, verified: false}, {adjusted: [], age: 0, bucket: "1990-06-15", exposure: [], flag: [], health: true, region: "Oslo", review: false, summary: false, verified: true}], weight: 18}, quota: 36}], + [{order: {weight: 0.25, amount: 2, dueDate: "1990-06-15", channel: "Oslo", members: [{age: null, verified: true, region: "A1"}, {age: 10, verified: false, region: "-"}]}}, "!error: ExpressionFailed"], + [{order: {weight: 18, amount: 1, dueDate: "2030-12-31", channel: "日本", members: [{age: 0, verified: false, region: "VIP"}, {age: 250, verified: true, region: "DE"}, {age: 0, verified: true, region: "US"}, {age: 1, verified: true, region: "Oslo"}]}}, {order: {amount: 1, bonus: true, channel: "日本", dueDate: "2030-12-31", eligible: "日本", fee: 1, members: [{adjusted: [1], age: 0, bucket: "2030-12-31", exposure: ["日本", "0"], flag: [1], health: true, region: "VIP", summary: false, verified: false}, {adjusted: [1], age: 250, bucket: "2030-12-31", exposure: ["日本"], flag: [1], health: true, region: "DE", summary: false, verified: true}, {adjusted: [1], age: 0, bucket: "2030-12-31", exposure: ["日本"], flag: [1], health: true, region: "US", summary: false, verified: true}, {adjusted: [1, 0.25], age: 1, bucket: "2030-12-31", exposure: ["日本", "Oslo"], flag: [1, 18], health: true, region: "Oslo", summary: false, verified: true}], weight: 18}, quota: 19}], + [{order: {weight: 1, amount: 5, dueDate: "2024-01-01", channel: "VIP", members: [{age: 1e3, verified: false, region: "Zed"}, {age: 100, verified: true, region: "日本"}, {age: 1e3, verified: true, region: "-"}]}}, {order: {amount: 5, bonus: true, channel: "VIP", dueDate: "2024-01-01", eligible: "VIP", fee: 5, members: [{adjusted: [5], age: 1000, bucket: "2024-01-01", exposure: ["VIP"], flag: [5], health: true, region: "Zed", review: true, summary: true, verified: false}, {adjusted: [5], age: 100, bucket: "2024-01-01", exposure: ["VIP"], flag: [5], health: true, region: "日本", review: true, summary: true, verified: true}, {adjusted: [5], age: 1000, bucket: "2024-01-01", exposure: ["VIP"], flag: [5], health: true, region: "-", review: true, summary: true, verified: true}], weight: 1}, quota: 6}], + ], +} + +// seed 331400 (attempt 0) +{ + name: "a 15: customer/vehicles: 2 expression, 2 match; 2 root, 1 per-member, 1 top-level computed", + policy: { + models: {customer: {limit: "number", age: "number", channel: "string?", price: "number?", dueDate: "date", since: "date", vehicles: "vehicle[]"}, vehicle: {age: "number?", weight: "number"}}, + blocks: [ + {expression: "customer.exposure", value: "customer.since.month()"}, + {match: "review", arms: [["not ((customer.price ?? 0) > 1.5)", "(customer.channel ?? '')"], ["", "(customer.channel ?? '')"]]}, + {expression: "customer.band", value: "((max(map(customer.vehicles, 5)) ?? 0) + len(customer.vehicles))"}, + {match: "vehicle.ok", arms: [["none(customer.vehicles, ((#.age ?? 0) == 1.5 and 0 > 1.5))", "(count(customer.vehicles, #.weight < 250) * (50 - customer.limit))"], ["", "len((customer.channel ?? ''))"]]}, + ], + }, + cases: [ + [{customer: {limit: 1e3, age: 250, channel: null, price: null, dueDate: "1990-06-15", since: "2024-02-29", vehicles: [{age: 250, weight: 1}, {age: -0, weight: -500}, {age: -0, weight: -0.5}, {age: 1000, weight: 1}, {age: null, weight: -0.5}]}}, {customer: {age: 250, band: 10, channel: null, dueDate: "1990-06-15", exposure: 2, limit: 1000, price: null, since: "2024-02-29", vehicles: [{age: 250, ok: -4750, weight: 1}, {age: 0, ok: -4750, weight: -500}, {age: 0, ok: -4750, weight: -0.5}, {age: 1000, ok: -4750, weight: 1}, {age: null, ok: -4750, weight: -0.5}]}, review: ""}], + [{customer: {limit: 250, age: 1.5, channel: "O'Neil", price: 10, dueDate: "2024-01-01", since: "2000-01-01", vehicles: [{age: 123456789.123, weight: 100}, {age: 0.000001, weight: 251}, {age: 1e3, weight: 1.5}, {age: 1e3, weight: 50}, {age: 0, weight: 5}]}}, {customer: {age: 1.5, band: 10, channel: "O'Neil", dueDate: "2024-01-01", exposure: 1, limit: 250, price: 10, since: "2000-01-01", vehicles: [{age: 123456789.123, ok: -800, weight: 100}, {age: 0.000001, ok: -800, weight: 251}, {age: 1000, ok: -800, weight: 1.5}, {age: 1000, ok: -800, weight: 50}, {age: 0, ok: -800, weight: 5}]}, review: "O'Neil"}], + [{customer: {limit: 10, age: 250, channel: "DE", price: 0, dueDate: "1990-06-15", since: "1990-06-15", vehicles: [{age: 100, weight: 0.000001}, {age: 1000000, weight: 1.5}], extraField: "x"}}, {customer: {age: 250, band: 7, channel: "DE", dueDate: "1990-06-15", exposure: 6, extraField: "x", limit: 10, price: 0, since: "1990-06-15", vehicles: [{age: 100, ok: 80, weight: 0.000001}, {age: 1000000, ok: 80, weight: 1.5}]}, review: "DE"}], + [{customer: {limit: 250, age: 0, channel: null, price: null, dueDate: "2030-12-31", since: "2025-03-20", vehicles: []}}, "!error: ExpressionFailed"], + [{customer: {limit: 50, age: -500, channel: false, price: 7.25, dueDate: "2030-12-31", since: "1990-06-15", vehicles: [{age: 2.50, weight: 7.25}, {age: 1000, weight: 0.1}]}}, "!error: InputValidationFailed"], + [{customer: {limit: 250, age: -0.01, channel: "gold", price: -0.5, dueDate: "2024-02-29", since: "2030-12-31", vehicles: [{age: 1, weight: 123456789.123}]}}, {customer: {age: -0.01, band: 6, channel: "gold", dueDate: "2024-02-29", exposure: 12, limit: 250, price: -0.5, since: "2030-12-31", vehicles: [{age: 1, ok: 0, weight: 123456789.123}]}, review: "gold"}], + [{customer: {limit: 18, age: 5, channel: 5, price: 5, dueDate: "2024-02-29", since: "2025-03-20T10:15:30Z", vehicles: [{age: 99999999999999999999, weight: 5}, {age: -1, weight: -0.5}]}}, "!error: InputValidationFailed"], + [{customer: {limit: 0.25, age: 5, channel: "a-b-c", price: 65, dueDate: "2025-03-20T10:15:30Z", since: "2025-03-20T10:15:30Z", vehicles: [{age: -0.5, weight: 5}, {age: 1.5, weight: 7.25}]}}, {customer: {age: 5, band: 7, channel: "a-b-c", dueDate: "2025-03-20T10:15:30Z", exposure: 3, limit: 0.25, price: 65, since: "2025-03-20T10:15:30Z", vehicles: [{age: -0.5, ok: 99.50, weight: 5}, {age: 1.5, ok: 99.50, weight: 7.25}]}, review: "a-b-c"}], + [{customer: {limit: 250, age: -0, channel: "é ü", price: 1000000, dueDate: "2024-02-29", since: "2025-03-20T10:15:30Z", vehicles: [{age: 250, weight: 1000}]}}, {customer: {age: 0, band: 6, channel: "é ü", dueDate: "2024-02-29", exposure: 3, limit: 250, price: 1000000, since: "2025-03-20T10:15:30Z", vehicles: [{age: 250, ok: 0, weight: 1000}]}, review: "é ü"}], + [{customer: {limit: 0.000001, age: 381, channel: "abc", price: 50, dueDate: "2000-01-01", since: "2025-03-20T10:15:30Z", vehicles: [{age: 1.5, weight: 0.1}, {age: 18, weight: 250}, {age: 100, weight: 65}]}}, {customer: {age: 381, band: 8, channel: "abc", dueDate: "2000-01-01", exposure: 3, limit: 0.000001, price: 50, since: "2025-03-20T10:15:30Z", vehicles: [{age: 1.5, ok: 99.999998, weight: 0.1}, {age: 18, ok: 99.999998, weight: 250}, {age: 100, ok: 99.999998, weight: 65}]}, review: "abc"}], + [{customer: {limit: 7.25, age: 1.5, channel: "DE", price: 2.50, dueDate: "2030-12-31", since: "2025-03-20T10:15:30Z", vehicles: [{age: [1], weight: -0}]}}, "!error: InputValidationFailed"], + [{customer: {limit: 0, age: -0.01, channel: null, price: null, dueDate: "2025-03-20", since: "2025-03-20T10:15:30Z", vehicles: [{age: -0, weight: 250}, {age: 250, weight: 0.000001}]}}, {customer: {age: -0.01, band: 7, channel: null, dueDate: "2025-03-20", exposure: 3, limit: 0, price: null, since: "2025-03-20T10:15:30Z", vehicles: [{age: 0, ok: 50, weight: 250}, {age: 250, ok: 50, weight: 0.000001}]}, review: ""}], + [{customer: {limit: 1, age: -0, channel: "é ü", price: 1, dueDate: "2025-03-20T10:15:30Z", since: "2030-12-31", vehicles: [{age: 7.25, weight: -0.5}, {age: 250, weight: 100}, {age: 0, weight: 2.50}, {age: -0, weight: 1.5}]}}, {customer: {age: 0, band: 9, channel: "é ü", dueDate: "2025-03-20T10:15:30Z", exposure: 12, limit: 1, price: 1, since: "2030-12-31", vehicles: [{age: 7.25, ok: 196, weight: -0.5}, {age: 250, ok: 196, weight: 100}, {age: 0, ok: 196, weight: 2.50}, {age: 0, ok: 196, weight: 1.5}]}, review: "é ü"}], + [{customer: {limit: 0.000001, age: 0.25, channel: "DE", price: 5, dueDate: "2030-12-31", since: "2000-01-01", vehicles: [{age: 2.50, weight: -0.5}, {age: 10, weight: -500}, {age: 0.25, weight: 65}, {age: 0.1, weight: 461}, {age: 1000000, weight: 0.1}], extraField: 1}}, {customer: {age: 0.25, band: 10, channel: "DE", dueDate: "2030-12-31", exposure: 1, extraField: 1, limit: 0.000001, price: 5, since: "2000-01-01", vehicles: [{age: 2.50, ok: 199.999996, weight: -0.5}, {age: 10, ok: 199.999996, weight: -500}, {age: 0.25, ok: 199.999996, weight: 65}, {age: 0.1, ok: 199.999996, weight: 461}, {age: 1000000, ok: 199.999996, weight: 0.1}]}, review: "DE"}], + [{customer: {limit: 1e3, age: 65, price: null, dueDate: "1990-06-15", since: "2024-01-01", vehicles: [{age: null, weight: 1}, {weight: 437}, {weight: 0.5}, {age: 412, weight: 0.1}, {age: 123456789.123, weight: 250}]}}, {customer: {age: 65, band: 10, dueDate: "1990-06-15", exposure: 1, limit: 1000, price: null, since: "2024-01-01", vehicles: [{age: null, ok: -2850, weight: 1}, {ok: -2850, weight: 437}, {ok: -2850, weight: 0.5}, {age: 412, ok: -2850, weight: 0.1}, {age: 123456789.123, ok: -2850, weight: 250}]}, review: ""}], + [{customer: {limit: 0, age: 1.5, channel: null, price: null, dueDate: "1990-06-15", since: "2025-03-20T10:15:30Z", vehicles: [{weight: 0.5}]}}, {customer: {age: 1.5, band: 6, channel: null, dueDate: "1990-06-15", exposure: 3, limit: 0, price: null, since: "2025-03-20T10:15:30Z", vehicles: [{ok: 50, weight: 0.5}]}, review: ""}], + [{customer: {limit: 0.5, age: -0.01, channel: null, price: null, dueDate: "2024-01-01", since: "2030-12-31", vehicles: [{age: 1.5, weight: 5}]}}, {customer: {age: -0.01, band: 6, channel: null, dueDate: "2024-01-01", exposure: 12, limit: 0.5, price: null, since: "2030-12-31", vehicles: [{age: 1.5, ok: 49.5, weight: 5}]}, review: ""}], + ], +} + +// seed 331500 (attempt 0) +{ + name: "a 16: applicant/vehicles: 5 expression, 2 match, 1 table; 3 root, 4 per-member, 1 top-level computed", + policy: { + models: {applicant: {price: "number", income: "number", age: "number?", verified: "boolean", flagged: "boolean", limit: "number?", vehicles: "vehicle[]"}, vehicle: {price: "number?", birthDate: "date", flagged: "boolean?", verified: "boolean"}}, + blocks: [ + {table: "t1", inputs: ["(applicant.limit ?? 0)"], outputs: ["applicant.bucket"], rules: [ + ["", "50"], + ["", "0.25"], + ]}, + {expression: "applicant.bonus", value: "((applicant.bucket ?? 0) - applicant.price)"}, + {expression: "summary", value: "((min([applicant.bonus, (applicant.bucket ?? 0)]) + (applicant.bucket ?? 0)) + (applicant.price in [0..2] ? applicant.income : applicant.bonus))"}, + {match: "vehicle.band", arms: [["(applicant.verified or (vehicle.flagged ?? false))", "'a'"], ["vehicle.birthDate.month() <= (vehicle.price ?? 0)", "upper(string(summary))"], ["(avg(map(applicant.vehicles, (#.price ?? 0))) ?? 0) == (vehicle.price ?? 0)", "'x'"], ["", "'retail'"]]}, + {expression: "vehicle.weighted", value: "(applicant.income * 18)"}, + {match: "applicant.health", arms: [["some(applicant.vehicles, #.weighted == (#.price ?? 0))", "((applicant.age ?? 0) * (applicant.age ?? 0))"], ["((applicant.bucket ?? 0) == 5 or applicant.limit == null)", "(applicant.age ?? 0)"], ["", "round((applicant.limit ?? 0))"]]}, + {expression: "vehicle.margin", value: "trim((vehicle.band + '-' + vehicle.band))"}, + {expression: "vehicle.capped", value: "count(applicant.vehicles, ((#.flagged ?? false) or (#.flagged ?? false)))"}, + ], + }, + cases: [ + [{applicant: {price: 0, income: 100, age: 100, verified: true, flagged: true, limit: -500, vehicles: []}}, {applicant: {age: 100, bucket: 50, flagged: true, health: -500, income: 100, limit: -500, price: 0, vehicles: [], verified: true}}], + [{applicant: {price: 100, income: 2.50, age: 7.25, verified: true, flagged: true, limit: 0.5, vehicles: [{price: -0, birthDate: "2024-01-01", flagged: false, verified: false}, {price: 18, birthDate: "2000-01-01", flagged: false, verified: true}, {price: -0, birthDate: "2024-02-29", flagged: false, verified: true}, {price: 18, birthDate: "2024-02-29", flagged: false, verified: false}, {price: -0.5, birthDate: "2030-12-31", flagged: false, verified: false}]}}, {applicant: {age: 7.25, bucket: 50, flagged: true, health: 1, income: 2.50, limit: 0.5, price: 100, vehicles: [{band: "a", birthDate: "2024-01-01", capped: 0, flagged: false, margin: "a-a", price: 0, verified: false, weighted: 45.00}, {band: "a", birthDate: "2000-01-01", capped: 0, flagged: false, margin: "a-a", price: 18, verified: true, weighted: 45.00}, {band: "a", birthDate: "2024-02-29", capped: 0, flagged: false, margin: "a-a", price: 0, verified: true, weighted: 45.00}, {band: "a", birthDate: "2024-02-29", capped: 0, flagged: false, margin: "a-a", price: 18, verified: false, weighted: 45.00}, {band: "a", birthDate: "2030-12-31", capped: 0, flagged: false, margin: "a-a", price: -0.5, verified: false, weighted: 45.00}], verified: true}}], + [{applicant: {price: 65, income: 1, age: 1, verified: false, flagged: true, limit: 1000, vehicles: [{price: 499, birthDate: "2000-01-01", flagged: false, verified: false}, {price: 50, birthDate: "2000-01-01", flagged: true, verified: true}], extraField: {nested: true}}}, {applicant: {age: 1, bonus: -15, bucket: 50, extraField: {nested: true}, flagged: true, health: 1000, income: 1, limit: 1000, price: 65, vehicles: [{band: "20", birthDate: "2000-01-01", capped: 1, flagged: false, margin: "20-20", price: 499, verified: false, weighted: 18}, {band: "a", birthDate: "2000-01-01", capped: 1, flagged: true, margin: "a-a", price: 50, verified: true, weighted: 18}], verified: false}, summary: 20}], + [{applicant: {price: -1, income: 1, verified: false, flagged: false, vehicles: [{price: 1000000, birthDate: "2025-03-20T10:15:30Z", verified: false}, {birthDate: "2024-02-29", verified: false}]}}, {applicant: {bonus: 51, bucket: 50, flagged: false, health: 0, income: 1, price: -1, vehicles: [{band: "151", birthDate: "2025-03-20T10:15:30Z", capped: 0, margin: "151-151", price: 1000000, verified: false, weighted: 18}, {band: "retail", birthDate: "2024-02-29", capped: 0, margin: "retail-retail", verified: false, weighted: 18}], verified: false}, summary: 151}], + [{applicant: {price: 1, income: 65, age: 0, verified: true, flagged: true, limit: 100, vehicles: [{price: 18, birthDate: "2025-03-20", flagged: true, verified: true}, {price: 18, birthDate: "2024-02-29", flagged: true, verified: true}, {price: 50, birthDate: "2025-03-20", flagged: false, verified: true}]}}, {applicant: {age: 0, bucket: 50, flagged: true, health: 100, income: 65, limit: 100, price: 1, vehicles: [{band: "a", birthDate: "2025-03-20", capped: 2, flagged: true, margin: "a-a", price: 18, verified: true, weighted: 1170}, {band: "a", birthDate: "2024-02-29", capped: 2, flagged: true, margin: "a-a", price: 18, verified: true, weighted: 1170}, {band: "a", birthDate: "2025-03-20", capped: 2, flagged: false, margin: "a-a", price: 50, verified: true, weighted: 1170}], verified: true}}], + [{applicant: {price: 0.000001, income: 0.000001, age: 123456789.123, verified: true, flagged: false, limit: -0.01, vehicles: [{price: 65, birthDate: "1990-06-15", flagged: true, verified: true}, {price: 1000000, birthDate: "2000-01-01", flagged: true, verified: false}, {price: 18, birthDate: "2030-12-31", flagged: false, verified: true}, {price: 1e3, birthDate: "2025-03-20T10:15:30Z", flagged: true, verified: true}, {price: 1000, birthDate: "1990-06-15", flagged: false, verified: false}]}}, {applicant: {age: 123456789.123, bucket: 50, flagged: false, health: 0, income: 0.000001, limit: -0.01, price: 0.000001, vehicles: [{band: "a", birthDate: "1990-06-15", capped: 3, flagged: true, margin: "a-a", price: 65, verified: true, weighted: 0.000018}, {band: "a", birthDate: "2000-01-01", capped: 3, flagged: true, margin: "a-a", price: 1000000, verified: false, weighted: 0.000018}, {band: "a", birthDate: "2030-12-31", capped: 3, flagged: false, margin: "a-a", price: 18, verified: true, weighted: 0.000018}, {band: "a", birthDate: "2025-03-20T10:15:30Z", capped: 3, flagged: true, margin: "a-a", price: 1000, verified: true, weighted: 0.000018}, {band: "a", birthDate: "1990-06-15", capped: 3, flagged: false, margin: "a-a", price: 1000, verified: false, weighted: 0.000018}], verified: true}}], + [{applicant: {price: 250, income: 160, age: 65, verified: false, flagged: false, limit: 100, vehicles: [{price: 1e3, birthDate: "2025-03-20T10:15:30Z", flagged: true, verified: false}, {price: 1, birthDate: "2025-03-20T10:15:30Z", flagged: true, verified: false}]}}, {applicant: {age: 65, bucket: 50, flagged: false, health: 100, income: 160, limit: 100, price: 250, vehicles: [{band: "a", birthDate: "2025-03-20T10:15:30Z", capped: 2, flagged: true, margin: "a-a", price: 1000, verified: false, weighted: 2880}, {band: "a", birthDate: "2025-03-20T10:15:30Z", capped: 2, flagged: true, margin: "a-a", price: 1, verified: false, weighted: 2880}], verified: false}}], + [{applicant: {price: 2, income: -0.5, age: null, verified: false, flagged: true, vehicles: []}}, {applicant: {age: null, bucket: 50, flagged: true, health: 0, income: -0.5, price: 2, vehicles: [], verified: false}}], + [{applicant: {price: -0.01, income: 330, age: 99999999999999999999, verified: true, flagged: false, vehicles: [{price: 18, birthDate: "2024-02-29", flagged: true, verified: false}]}}, {applicant: {age: 99999999999999999999, bucket: 50, flagged: false, health: 99999999999999999999, income: 330, price: -0.01, vehicles: [{band: "a", birthDate: "2024-02-29", capped: 1, flagged: true, margin: "a-a", price: 18, verified: false, weighted: 5940}], verified: true}}], + [{applicant: {price: 99999999999999999999, income: 18, age: 1e3, verified: false, flagged: false, limit: 50, vehicles: []}}, {applicant: {age: 1000, bucket: 50, flagged: false, health: 50, income: 18, limit: 50, price: 99999999999999999999, vehicles: [], verified: false}}], + [{applicant: {price: 1e3, income: 99999999999999999999, age: 2, verified: false, flagged: false, limit: 0.5, vehicles: [{price: 3, birthDate: "2025-03-20T10:15:30Z", flagged: true, verified: true}, {price: 65, birthDate: "2025-03-20T10:15:30Z", flagged: false, verified: true}, {price: 100, birthDate: "2000-01-01", flagged: true, verified: true}, {price: 38, birthDate: "2025-03-20", flagged: true, verified: false}, {price: 0.1, birthDate: "2024-02-29", flagged: true, verified: false}]}}, {applicant: {age: 2, bonus: -950, bucket: 50, flagged: false, health: 1, income: 99999999999999999999, limit: 0.5, price: 1000, vehicles: [{band: "a", birthDate: "2025-03-20T10:15:30Z", capped: 4, flagged: true, margin: "a-a", price: 3, verified: true, weighted: 1799999999999999999982}, {band: "-1850", birthDate: "2025-03-20T10:15:30Z", capped: 4, flagged: false, margin: "-1850--1850", price: 65, verified: true, weighted: 1799999999999999999982}, {band: "a", birthDate: "2000-01-01", capped: 4, flagged: true, margin: "a-a", price: 100, verified: true, weighted: 1799999999999999999982}, {band: "a", birthDate: "2025-03-20", capped: 4, flagged: true, margin: "a-a", price: 38, verified: false, weighted: 1799999999999999999982}, {band: "a", birthDate: "2024-02-29", capped: 4, flagged: true, margin: "a-a", price: 0.1, verified: false, weighted: 1799999999999999999982}], verified: false}, summary: -1850}], + [{applicant: {price: 10, income: 7.25, age: 2, verified: true, flagged: false, limit: 2, vehicles: [{price: 18, birthDate: "2025-03-20", flagged: true, verified: false}, {price: 3, birthDate: "2024-02-29", flagged: true, verified: false}]}}, {applicant: {age: 2, bucket: 50, flagged: false, health: 2, income: 7.25, limit: 2, price: 10, vehicles: [{band: "a", birthDate: "2025-03-20", capped: 2, flagged: true, margin: "a-a", price: 18, verified: false, weighted: 130.50}, {band: "a", birthDate: "2024-02-29", capped: 2, flagged: true, margin: "a-a", price: 3, verified: false, weighted: 130.50}], verified: true}}], + [{applicant: {price: 1, income: -1, age: 1, verified: false, flagged: true, limit: null, vehicles: [{price: null, birthDate: "2024-01-01", flagged: null, verified: true}, {price: 1000, birthDate: "2024-01-01", verified: true}, {price: 99999999999999999999, birthDate: "2030-12-31", flagged: null, verified: false}, {price: null, birthDate: "1990-06-15", flagged: false, verified: false}]}}, {applicant: {age: 1, bonus: 49, bucket: 50, flagged: true, health: 1, income: -1, limit: null, price: 1, vehicles: [{band: "retail", birthDate: "2024-01-01", capped: 0, flagged: null, margin: "retail-retail", price: null, verified: true, weighted: -18}, {band: "98", birthDate: "2024-01-01", capped: 0, margin: "98-98", price: 1000, verified: true, weighted: -18}, {band: "98", birthDate: "2030-12-31", capped: 0, flagged: null, margin: "98-98", price: 99999999999999999999, verified: false, weighted: -18}, {band: "retail", birthDate: "1990-06-15", capped: 0, flagged: false, margin: "retail-retail", price: null, verified: false, weighted: -18}], verified: false}, summary: 98}], + [{applicant: {price: 0.1, income: 100, age: -0, verified: false, flagged: false, limit: true, vehicles: [{price: -0, birthDate: "2024-02-29", flagged: true, verified: false}, {price: 5, birthDate: "2024-01-01", flagged: true, verified: true}]}}, "!error: InputValidationFailed"], + [{applicant: {price: 0.000001, income: 100, age: 1e3, verified: false, flagged: false, limit: 18, vehicles: [{price: 1e3, birthDate: "2024-01-01", flagged: false, verified: true}]}}, {applicant: {age: 1000, bonus: 49.999999, bucket: 50, flagged: false, health: 18, income: 100, limit: 18, price: 0.000001, vehicles: [{band: "199.999999", birthDate: "2024-01-01", capped: 0, flagged: false, margin: "199.999999-199.999999", price: 1000, verified: true, weighted: 1800}], verified: false}, summary: 199.999999}], + ], +} + +// seed 331600 (attempt 0) +{ + name: "a 17: shipment/members: 1 assertion, 2 expression, 1 match; 2 root, 2 per-member, 0 top-level computed", + policy: { + models: {shipment: {age: "number", tier: "string(gold|silver|bronze)?", channel: "string", members: "member[]"}, member: {amount: "number", active: "boolean", city: "string?", country: "string"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {assertion: "member.ok", conditions: ["(member.amount < baseRate or shipment.age <= 50)", ["and", "all(shipment.members, #.amount <= 0)", 0]]}, + {expression: "shipment.band", value: "count(shipment.members, #.country != 'none')"}, + {expression: "member.tag", value: "(baseRate * shipment.age)"}, + {match: "shipment.grade", arms: [["(shipment.age > 0.25 ? baseRate : baseRate) <= baseRate", "round(shipment.age, 2)"], ["(shipment.tier ?? '') != 'bronze'", "(shipment.age * sum(map(shipment.members, #.amount)))"], ["shipment.age in [43..235]", "count(shipment.members, #.city == null)"], ["", "shipment.age"]]}, + ], + }, + cases: [ + [{baseRate: 1, shipment: {age: 0, tier: "gold", channel: "A1", members: [{amount: 2.50, active: false, city: "a-b-c", country: "-"}], extraField: {nested: true}}}, {baseRate: 1, shipment: {age: 0, band: 1, channel: "A1", extraField: {nested: true}, grade: 0, members: [{active: false, amount: 2.50, city: "a-b-c", country: "-", ok: false, tag: 0}], tier: "gold"}}], + [{baseRate: 10, shipment: {age: 2.50, tier: "gold", channel: "A1", members: [{amount: 100, active: true, country: "-"}, {amount: -1, active: false, city: " pad ", country: " pad "}, {amount: -1, active: false, city: "DE", country: "US"}, {amount: -1, active: true, city: "a", country: "NL"}]}}, {baseRate: 10, shipment: {age: 2.50, band: 4, channel: "A1", grade: 2.50, members: [{active: true, amount: 100, country: "-", ok: false, tag: 25.00}, {active: false, amount: -1, city: " pad ", country: " pad ", ok: false, tag: 25.00}, {active: false, amount: -1, city: "DE", country: "US", ok: false, tag: 25.00}, {active: true, amount: -1, city: "a", country: "NL", ok: false, tag: 25.00}], tier: "gold"}}], + [{baseRate: 1, shipment: {age: 1000000, tier: "gold", channel: "3.5", members: [{amount: 0, active: true, city: "a", country: "gold"}, {amount: 7.25, active: true, city: "gold", country: "O'Neil"}, {amount: 1000000, active: true, city: "DE", country: "gold"}, {amount: 2, active: false, city: "Zed", country: "NL"}]}}, {baseRate: 1, shipment: {age: 1000000, band: 4, channel: "3.5", grade: 1000000, members: [{active: true, amount: 0, city: "a", country: "gold", ok: false, tag: 1000000}, {active: true, amount: 7.25, city: "gold", country: "O'Neil", ok: false, tag: 1000000}, {active: true, amount: 1000000, city: "DE", country: "gold", ok: false, tag: 1000000}, {active: false, amount: 2, city: "Zed", country: "NL", ok: false, tag: 1000000}], tier: "gold"}}], + [{baseRate: 0.5, shipment: {age: 50, tier: "bronze", channel: "Oslo", members: []}}, {baseRate: 0.5, shipment: {age: 50, band: 0, channel: "Oslo", grade: 50, members: [], tier: "bronze"}}], + [{baseRate: 0.5, shipment: {age: 123456789.123, tier: "gold", channel: "A1", members: [{amount: -500, city: "a", country: "gold"}, {amount: -500, active: false, city: "", country: "é ü"}, {amount: -0, active: false, city: "日本", country: "-"}, {amount: 0.5, active: true, city: "é ü", country: "é ü"}]}}, {baseRate: 0.5, shipment: {age: 123456789.123, band: 4, channel: "A1", grade: 123456789.12, members: [{amount: -500, city: "a", country: "gold", ok: false, tag: 61728394.5615}, {active: false, amount: -500, city: "", country: "é ü", ok: false, tag: 61728394.5615}, {active: false, amount: 0, city: "日本", country: "-", ok: false, tag: 61728394.5615}, {active: true, amount: 0.5, city: "é ü", country: "é ü", ok: false, tag: 61728394.5615}], tier: "gold"}}], + [{baseRate: 10, shipment: {age: 50, tier: "gold", channel: "a", members: [{amount: 99999999999999999999, active: true, country: "gold"}]}}, {baseRate: 10, shipment: {age: 50, band: 1, channel: "a", grade: 50, members: [{active: true, amount: 99999999999999999999, country: "gold", ok: false, tag: 500}], tier: "gold"}}], + [{baseRate: -2, shipment: {age: 65, channel: " pad ", members: []}}, {baseRate: -2, shipment: {age: 65, band: 0, channel: " pad ", grade: 65, members: []}}], + [{baseRate: 0, shipment: {age: 99999999999999999999, channel: "a", members: [{amount: 0, active: false, city: "a-b-c", country: "DE"}, {amount: 1, active: false, city: "gold", country: "Oslo"}, {amount: 10, active: false, city: "US", country: "abc"}, {amount: -0.01, active: false, city: null, country: "DE"}]}}, {baseRate: 0, shipment: {age: 99999999999999999999, band: 4, channel: "a", grade: 99999999999999999999, members: [{active: false, amount: 0, city: "a-b-c", country: "DE", ok: false, tag: 0}, {active: false, amount: 1, city: "gold", country: "Oslo", ok: false, tag: 0}, {active: false, amount: 10, city: "US", country: "abc", ok: false, tag: 0}, {active: false, amount: -0.01, city: null, country: "DE", ok: false, tag: 0}]}}], + [{baseRate: 0, shipment: {age: 99999999999999999999, tier: "bronze", channel: "high", members: []}}, {baseRate: 0, shipment: {age: 99999999999999999999, band: 0, channel: "high", grade: 99999999999999999999, members: [], tier: "bronze"}}], + [{baseRate: 10, shipment: {age: 100, tier: "bronze", channel: "A1", members: [{amount: -1, active: true, city: "Oslo", country: null}, {amount: 65, active: false, city: "A1", country: " pad "}]}}, {baseRate: 10, shipment: {age: 100, band: 2, channel: "A1", grade: 100, members: [{active: true, amount: -1, city: "Oslo", country: null, ok: false, tag: 1000}, {active: false, amount: 65, city: "A1", country: " pad ", ok: false, tag: 1000}], tier: "bronze"}}], + [{baseRate: 10, shipment: {age: 1000000, tier: "gold", channel: "3.5", members: [{amount: 65, active: true, city: "Oslo", country: "VIP"}]}}, {baseRate: 10, shipment: {age: 1000000, band: 1, channel: "3.5", grade: 1000000, members: [{active: true, amount: 65, city: "Oslo", country: "VIP", ok: false, tag: 10000000}], tier: "gold"}}], + [{baseRate: -2, shipment: {age: 0.25, tier: "silver", channel: "12", members: [{amount: 7.25, active: true, city: "12", country: "abc"}, {amount: 0.000001, active: true, city: "none", country: "é ü"}, {amount: 2, active: true, city: "3.5", country: "gold"}, {amount: 1000, active: false, city: "NL", country: "retail"}], extraField: "x"}}, {baseRate: -2, shipment: {age: 0.25, band: 4, channel: "12", extraField: "x", grade: 0.25, members: [{active: true, amount: 7.25, city: "12", country: "abc", ok: false, tag: -0.50}, {active: true, amount: 0.000001, city: "none", country: "é ü", ok: false, tag: -0.50}, {active: true, amount: 2, city: "3.5", country: "gold", ok: false, tag: -0.50}, {active: false, amount: 1000, city: "NL", country: "retail", ok: false, tag: -0.50}], tier: "silver"}}], + [{baseRate: 10, shipment: {age: 1, channel: "Oslo", members: [{amount: 10, active: true, city: "US", country: "DE"}, {amount: 0, active: true, city: "12", country: "日本"}, {amount: -0, active: false, city: "a", country: "a"}, {amount: -0.01, active: false, city: "12", country: "3.5"}, {amount: 292, active: true, city: null, country: "high"}]}}, {baseRate: 10, shipment: {age: 1, band: 5, channel: "Oslo", grade: 1, members: [{active: true, amount: 10, city: "US", country: "DE", ok: false, tag: 10}, {active: true, amount: 0, city: "12", country: "日本", ok: false, tag: 10}, {active: false, amount: 0, city: "a", country: "a", ok: false, tag: 10}, {active: false, amount: -0.01, city: "12", country: "3.5", ok: false, tag: 10}, {active: true, amount: 292, city: null, country: "high", ok: false, tag: 10}]}}], + [{baseRate: 100, shipment: {age: null, tier: "bronze", channel: "US", members: [{amount: -0.01, active: false, city: "3.5", country: ""}]}}, "!error: MissingRequiredInputs"], + [{baseRate: 1, shipment: {age: 5, tier: 5, channel: "a", members: [{amount: 10, active: false, city: "12", country: ""}]}}, "!error: InputValidationFailed"], + [{baseRate: 0.5, shipment: {age: 0.25, channel: "gold", members: [{amount: 2.50, active: false, city: null, country: "NL"}]}}, {baseRate: 0.5, shipment: {age: 0.25, band: 1, channel: "gold", grade: 0.25, members: [{active: false, amount: 2.50, city: null, country: "NL", ok: false, tag: 0.125}]}}], + ], +} + +// seed 331700 (attempt 0) +{ + name: "a 18: account/companies: 2 assertion, 1 expression, 3 match, 2 table; 4 root, 3 per-member, 1 top-level computed", + policy: { + models: {account: {score: "number", active: "boolean", dueDate: "date?", urgent: "boolean", code: "string?", birthDate: "date", companies: "company[]"}, company: {years: "number", code: "string"}}, + blocks: [ + {match: "account.bonus", arms: [["100 > account.score", "account.birthDate.month()"], ["account.score != account.score", "(min(map(account.companies, #.years)) ?? 0)"], ["len((account.code ?? '')) == account.score", "account.score"], ["", "0.25"]]}, + {match: "risk", arms: [["(account.bonus - account.score) < account.bonus", "(account.code ?? '')"], ["account.code != null", "string(account.score)"], ["", "'Oslo'"]]}, + {table: "t3", hit: "collect", inputs: ["account.urgent"], outputs: ["company.flag"], rules: [ + ["true", "(account.code ?? '')"], + ["true", "(account.code ?? '')"], + ]}, + {expression: "account.ok", value: "(account.bonus * (1.5) / (abs(account.score) + 1))"}, + {assertion: "account.capped", conditions: [["and", "all(account.companies, #.years <= 250)", 1], ["or", "(account.urgent and account.urgent)", 0], ["and", "(account.active or account.urgent)", 0], ["or", "some(account.companies, (#.years > 3 and #.years > 2))", 1]]}, + {table: "t6", inputs: ["account.active"], outputs: ["account.band"], rules: [ + ["false", ""], + ["", "sum(map(account.companies, 5))"], + ["true", "account.score"], + ["true", "len(risk)"], + ["true", "(account.bonus * account.score)"], + ["false", "sum(map(account.companies, #.years))"], + ["", "floor(account.score)"], + ]}, + {assertion: "company.eligible", conditions: [["or", "(company.years < 0 or (account.capped and account.capped))", 1]]}, + {match: "company.margin", arms: [["some(account.companies, #.years <= #.years)", "(account.code ?? '')"], ["account.bonus > account.ok", "'gold'"], ["", "string(account.ok)"]]}, + ], + }, + cases: [ + [{account: {score: 5, active: true, dueDate: "2024-01-01", urgent: false, code: "Oslo", birthDate: "2025-03-20T10:15:30Z", companies: [{years: 100, code: "gold"}, {years: 0, code: "O'Neil"}]}}, {account: {active: true, band: 10, birthDate: "2025-03-20T10:15:30Z", bonus: 3, capped: true, code: "Oslo", companies: [{code: "gold", eligible: true, flag: [], margin: "Oslo", years: 100}, {code: "O'Neil", eligible: true, flag: [], margin: "Oslo", years: 0}], dueDate: "2024-01-01", ok: 0.750, score: 5, urgent: false}}], + [{account: {score: 0, active: false, dueDate: "2030-12-31", urgent: true, code: "retail", birthDate: "2000-01-01", companies: [{years: 1, code: "Oslo"}, {years: 3, code: "é ü"}]}}, {account: {active: false, band: 10, birthDate: "2000-01-01", bonus: 1, capped: false, code: "retail", companies: [{code: "Oslo", eligible: false, flag: ["retail", "retail"], margin: "retail", years: 1}, {code: "é ü", eligible: false, flag: ["retail", "retail"], margin: "retail", years: 3}], dueDate: "2030-12-31", ok: 1.5, score: 0, urgent: true}}], + [{account: {score: 10, active: false, dueDate: "1990-06-15", urgent: true, code: "DE", birthDate: "1990-06-15", companies: [{years: -1, code: "US"}, {years: 0.25, code: "日本"}, {years: 250, code: "abc"}, {years: 100, code: "a"}, {years: 1e3, code: "12"}]}}, {account: {active: false, band: 25, birthDate: "1990-06-15", bonus: 6, capped: true, code: "DE", companies: [{code: "US", eligible: true, flag: ["DE", "DE"], margin: "DE", years: -1}, {code: "日本", eligible: true, flag: ["DE", "DE"], margin: "DE", years: 0.25}, {code: "abc", eligible: true, flag: ["DE", "DE"], margin: "DE", years: 250}, {code: "a", eligible: true, flag: ["DE", "DE"], margin: "DE", years: 100}, {code: "12", eligible: true, flag: ["DE", "DE"], margin: "DE", years: 1000}], dueDate: "1990-06-15", ok: 0.8181818181818181818181818182, score: 10, urgent: true}}], + [{account: {active: false, dueDate: "2024-01-01", urgent: true, code: "a", birthDate: "2030-12-31", companies: [{years: 0.000001, code: "retail"}, {years: 250, code: "a-b-c"}, {years: 250, code: "A1"}, {years: 5, code: "DE"}]}}, "!error: MissingRequiredInputs"], + [{account: {score: 99.99, active: true, dueDate: "2000-01-01", urgent: true, code: "NL", birthDate: "2024-02-29", companies: [{years: 7.25, code: "abc"}]}}, {account: {active: true, band: 5, birthDate: "2024-02-29", bonus: 2, capped: true, code: "NL", companies: [{code: "abc", eligible: true, flag: ["NL", "NL"], margin: "NL", years: 7.25}], dueDate: "2000-01-01", ok: 0.0297059114763838003762748787, score: 99.99, urgent: true}}], + [{account: {score: 5, active: true, dueDate: null, urgent: false, code: "abc", birthDate: "2030-12-31", companies: [{years: 0.1, code: "x-y"}]}}, {account: {active: true, band: 5, birthDate: "2030-12-31", bonus: 12, capped: false, code: "abc", companies: [{code: "x-y", eligible: false, flag: [], margin: "abc", years: 0.1}], dueDate: null, ok: 3.0, score: 5, urgent: false}}], + [{account: {score: 0.1, active: false, dueDate: null, urgent: false, code: null, birthDate: "2025-03-20", companies: [{years: -0, code: " pad "}, {years: 100, code: "Oslo"}, {years: 0, code: "x-y"}, {years: 0.25, code: "gold"}]}}, {account: {active: false, band: 20, birthDate: "2025-03-20", bonus: 3, capped: false, code: null, companies: [{code: " pad ", eligible: false, flag: [], margin: "", years: 0}, {code: "Oslo", eligible: false, flag: [], margin: "", years: 100}, {code: "x-y", eligible: false, flag: [], margin: "", years: 0}, {code: "gold", eligible: false, flag: [], margin: "", years: 0.25}], dueDate: null, ok: 4.0909090909090909090909090909, score: 0.1, urgent: false}}], + [{account: {score: 0.25, active: false, dueDate: "2024-01-01", urgent: false, code: "gold", birthDate: "2025-03-20", companies: [{years: 5, code: "12"}]}}, {account: {active: false, band: 5, birthDate: "2025-03-20", bonus: 3, capped: false, code: "gold", companies: [{code: "12", eligible: false, flag: [], margin: "gold", years: 5}], dueDate: "2024-01-01", ok: 3.6, score: 0.25, urgent: false}}], + [{account: {score: 5, active: false, dueDate: "2025-03-20T10:15:30Z", urgent: false, code: "US", birthDate: "1990-06-15", companies: []}}, {account: {active: false, band: 0, birthDate: "1990-06-15", bonus: 6, capped: false, code: "US", companies: [], dueDate: "2025-03-20T10:15:30Z", ok: 1.5, score: 5, urgent: false}}], + [{account: {score: -500, dueDate: "2030-12-31", urgent: false, code: "Oslo", birthDate: "2025-03-20", companies: [{years: 100, code: "A1"}]}}, "!error: MissingRequiredInputs"], + [{account: {score: 99.99, active: true, dueDate: "2025-03-20T10:15:30Z", urgent: true, code: "a-b-c", birthDate: "1990-06-15", companies: [{years: 18, code: "a"}, {years: 5, code: "DE"}]}}, {account: {active: true, band: 10, birthDate: "1990-06-15", bonus: 6, capped: true, code: "a-b-c", companies: [{code: "a", eligible: true, flag: ["a-b-c", "a-b-c"], margin: "a-b-c", years: 18}, {code: "DE", eligible: true, flag: ["a-b-c", "a-b-c"], margin: "a-b-c", years: 5}], dueDate: "2025-03-20T10:15:30Z", ok: 0.0891177344291514011288246361, score: 99.99, urgent: true}}], + [{account: {score: 1000000, active: true, dueDate: "2030-12-31", urgent: false, code: null, birthDate: "2000-01-01", companies: [{years: 5, code: "NL"}]}}, {account: {active: true, band: 5, birthDate: "2000-01-01", bonus: 0.25, capped: true, code: null, companies: [{code: "NL", eligible: true, flag: [], margin: "", years: 5}], dueDate: "2030-12-31", ok: 0.000000374999625000374999625, score: 1000000, urgent: false}}], + [{account: {score: -0, active: false, dueDate: "2030-12-31", urgent: true, code: "gold", birthDate: "2000-01-01", companies: [{years: 18, code: "gold"}, {years: 250, code: "A1"}, {years: 1.5, code: "12"}, {years: 123456789.123, code: " pad "}]}}, {account: {active: false, band: 20, birthDate: "2000-01-01", bonus: 1, capped: true, code: "gold", companies: [{code: "gold", eligible: true, flag: ["gold", "gold"], margin: "gold", years: 18}, {code: "A1", eligible: true, flag: ["gold", "gold"], margin: "gold", years: 250}, {code: "12", eligible: true, flag: ["gold", "gold"], margin: "gold", years: 1.5}, {code: " pad ", eligible: true, flag: ["gold", "gold"], margin: "gold", years: 123456789.123}], dueDate: "2030-12-31", ok: 1.5, score: 0, urgent: true}}], + [{account: {score: 1.5, active: false, dueDate: "2024-01-01", urgent: false, code: "DE", birthDate: "2024-02-29", companies: [{years: -0.5, code: "Oslo"}], extraField: 1}}, {account: {active: false, band: 5, birthDate: "2024-02-29", bonus: 2, capped: false, code: "DE", companies: [{code: "Oslo", eligible: true, flag: [], margin: "DE", years: -0.5}], dueDate: "2024-01-01", extraField: 1, ok: 1.20, score: 1.5, urgent: false}}], + [{account: {score: 1.5, active: true, dueDate: "2025-03-20T10:15:30Z", urgent: false, birthDate: "2030-12-31", companies: [{years: 0.000001, code: " pad "}, {years: 100, code: "日本"}]}}, {account: {active: true, band: 10, birthDate: "2030-12-31", bonus: 12, capped: true, companies: [{code: " pad ", eligible: true, flag: [], margin: "", years: 0.000001}, {code: "日本", eligible: true, flag: [], margin: "", years: 100}], dueDate: "2025-03-20T10:15:30Z", ok: 7.20, score: 1.5, urgent: false}}], + [{account: {score: 0.000001, active: false, dueDate: "2025-03-20", urgent: "true", code: "A1", birthDate: "2025-03-20T10:15:30Z", companies: [{years: -1, code: "Oslo"}]}}, "!error: InputValidationFailed"], + [{account: {score: -500, active: false, dueDate: "2030-12-31", urgent: false, code: "x-y", birthDate: "2000-01-01", companies: [{years: -0, code: "abc"}, {years: 1000000, code: "abc"}, {years: -0.01, code: "Oslo"}, {years: -500, code: "a-b-c"}, {years: 100, code: "-"}]}}, {account: {active: false, band: 25, birthDate: "2000-01-01", bonus: 1, capped: false, code: "x-y", companies: [{code: "abc", eligible: false, flag: [], margin: "x-y", years: 0}, {code: "abc", eligible: false, flag: [], margin: "x-y", years: 1000000}, {code: "Oslo", eligible: true, flag: [], margin: "x-y", years: -0.01}, {code: "a-b-c", eligible: true, flag: [], margin: "x-y", years: -500}, {code: "-", eligible: false, flag: [], margin: "x-y", years: 100}], dueDate: "2030-12-31", ok: 0.0029940119760479041916167665, score: -500, urgent: false}}], + [{account: {score: 7.25, active: true, dueDate: "2025-03-20T10:15:30Z", urgent: true, code: " pad ", birthDate: "2024-01-01", companies: [{years: 0.5, code: "VIP"}, {years: 0.5, code: "Oslo"}]}}, {account: {active: true, band: 10, birthDate: "2024-01-01", bonus: 1, capped: false, code: " pad ", companies: [{code: "VIP", eligible: false, flag: [" pad ", " pad "], margin: " pad ", years: 0.5}, {code: "Oslo", eligible: false, flag: [" pad ", " pad "], margin: " pad ", years: 0.5}], dueDate: "2025-03-20T10:15:30Z", ok: 0.1818181818181818181818181818, score: 7.25, urgent: true}}], + [{account: {score: 123456789.123, active: true, dueDate: "2025-03-20T10:15:30Z", urgent: true, code: "abc", birthDate: "2025-03-20", companies: [{years: 100, code: "gold"}, {years: -1, code: "x-y"}]}}, {account: {active: true, band: 10, birthDate: "2025-03-20", bonus: 0.25, capped: true, code: "abc", companies: [{code: "gold", eligible: true, flag: ["abc", "abc"], margin: "abc", years: 100}, {code: "x-y", eligible: true, flag: ["abc", "abc"], margin: "abc", years: -1}], dueDate: "2025-03-20T10:15:30Z", ok: 0.00000000303750000001123875, score: 123456789.123, urgent: true}}], + [{account: {score: 99999999999999999999, active: false, dueDate: "2025-03-20", urgent: false, code: "12", birthDate: "2025-03-20", companies: []}}, {account: {active: false, band: 0, birthDate: "2025-03-20", bonus: 0.25, capped: false, code: "12", companies: [], dueDate: "2025-03-20", ok: 0.00000000000000000000375, score: 99999999999999999999, urgent: false}}], + [{account: {score: 0.1, active: true, dueDate: null, urgent: false, code: "retail", birthDate: "2000-01-01", companies: [{years: 65, code: "VIP"}, {years: -0.01, code: "abc"}]}}, {account: {active: true, band: 10, birthDate: "2000-01-01", bonus: 1, capped: true, code: "retail", companies: [{code: "VIP", eligible: true, flag: [], margin: "retail", years: 65}, {code: "abc", eligible: true, flag: [], margin: "retail", years: -0.01}], dueDate: null, ok: 1.3636363636363636363636363636, score: 0.1, urgent: false}}], + [{account: {score: 250, active: false, dueDate: "2024-02-29", urgent: false, code: "retail", birthDate: "2025-03-20", companies: [{years: 1, code: "12"}, {years: 1.5, code: "gold"}, {years: 0.1, code: "a-b-c"}, {years: 1000000, code: "gold"}, {years: 99999999999999999999, code: "retail"}]}}, {account: {active: false, band: 25, birthDate: "2025-03-20", bonus: 0.25, capped: false, code: "retail", companies: [{code: "12", eligible: false, flag: [], margin: "retail", years: 1}, {code: "gold", eligible: false, flag: [], margin: "retail", years: 1.5}, {code: "a-b-c", eligible: false, flag: [], margin: "retail", years: 0.1}, {code: "gold", eligible: false, flag: [], margin: "retail", years: 1000000}, {code: "retail", eligible: false, flag: [], margin: "retail", years: 99999999999999999999}], dueDate: "2024-02-29", ok: 0.0014940239043824701195219124, score: 250, urgent: false}}], + [{account: {score: 1.5, active: false, dueDate: "2025-03-20T10:15:30Z", urgent: true, code: "retail", birthDate: "2024-01-01", companies: [{years: 0.5, code: "12"}, {years: 1.5, code: "VIP"}]}}, {account: {active: false, band: 10, birthDate: "2024-01-01", bonus: 1, capped: false, code: "retail", companies: [{code: "12", eligible: false, flag: ["retail", "retail"], margin: "retail", years: 0.5}, {code: "VIP", eligible: false, flag: ["retail", "retail"], margin: "retail", years: 1.5}], dueDate: "2025-03-20T10:15:30Z", ok: 0.60, score: 1.5, urgent: true}}], + [{account: {score: 0.5, active: true, urgent: false, birthDate: "2024-02-29", companies: [{years: 1e3, code: "Zed"}]}}, {account: {active: true, band: 5, birthDate: "2024-02-29", bonus: 2, capped: true, companies: [{code: "Zed", eligible: true, flag: [], margin: "", years: 1000}], ok: 2, score: 0.5, urgent: false}}], + [{account: {score: 10, active: false, dueDate: "2000-01-01", urgent: false, birthDate: "2025-03-20", companies: [{years: 99.99, code: "retail"}]}}, {account: {active: false, band: 5, birthDate: "2025-03-20", bonus: 3, capped: false, companies: [{code: "retail", eligible: false, flag: [], margin: "", years: 99.99}], dueDate: "2000-01-01", ok: 0.4090909090909090909090909091, score: 10, urgent: false}}], + ], +} + +// seed 331800 (attempt 0) +{ + name: "a 19: borrower/vehicles: 4 expression, 1 match, 2 table; 4 root, 4 per-member, 1 top-level computed", + policy: { + models: {borrower: {years: "number", status: "string(open|closed|pending)", urgent: "boolean", vehicles: "vehicle[]"}, vehicle: {score: "number", since: "date?", city: "string"}}, + blocks: [ + {expression: "vehicle.band", value: "sum(map(borrower.vehicles, #.score))"}, + {expression: "vehicle.flag", value: "(vehicle.band * vehicle.score) <= borrower.years"}, + {expression: "borrower.adjusted", value: "string(max([borrower.years, borrower.years]))"}, + {match: "vehicle.surcharge", arms: [["borrower.adjusted == 'gold'", "(vehicle.since == null and some(borrower.vehicles, #.score in [13..137]))"], ["vehicle.since == null", "vehicle.since != null"], ["(vehicle.since ?? d('2025-01-01')) >= d('2024-01-01')", "borrower.urgent"], ["not (none(borrower.vehicles, #.band < #.score))", "((vehicle.flag or borrower.urgent) and borrower.years in [47..156])"], ["", "borrower.urgent"]]}, + {expression: "vehicle.eligible", value: "((not (vehicle.surcharge) and none(borrower.vehicles, #.city != 'low')) or (vehicle.surcharge ? vehicle.score : vehicle.score) <= vehicle.score)"}, + {table: "t6", inputs: ["borrower.status", "borrower.urgent"], outputs: ["quota"], rules: [ + ["'closed'", "false", "borrower.years in [8..95]"], + ["", "", "borrower.urgent"], + ]}, + {table: "t7", inputs: ["quota"], outputs: ["borrower.total", "borrower.weighted", "borrower.share"], rules: [ + ["", "borrower.years", "borrower.urgent", "borrower.urgent"], + ["true", "", "borrower.urgent", "borrower.urgent"], + ["", "", "quota == null", "borrower.urgent"], + ["false", "1000", "(quota ?? false)", "borrower.urgent"], + ["true", "(avg(map(borrower.vehicles, 0.5)) ?? 0)", "(quota ?? false)", "(quota ?? false)"], + ["true", "borrower.years", "borrower.urgent", "borrower.urgent"], + ["false", "borrower.years", "borrower.urgent", "borrower.years in [32..218]"], + ]}, + ], + }, + cases: [ + [{borrower: {years: 1000, status: "closed", urgent: false, vehicles: [{score: 0.5, city: "abc"}, {score: 2.50, since: "2000-01-01", city: "low"}, {score: 123456789.123, city: "a"}]}}, {borrower: {adjusted: "1000", share: false, status: "closed", total: 1000, urgent: false, vehicles: [{band: 123456792.123, city: "abc", eligible: true, score: 0.5, surcharge: false}, {band: 123456792.123, city: "low", eligible: true, score: 2.50, since: "2000-01-01", surcharge: false}, {band: 123456792.123, city: "a", eligible: true, score: 123456789.123, surcharge: false}], weighted: false, years: 1000}, quota: false}], + [{borrower: {years: 0.5, status: "pending", vehicles: [{score: 10, since: "2024-01-01", city: "3.5"}, {score: 1000000, since: "1990-06-15", city: "NL"}]}}, "!error: MissingRequiredInputs"], + [{borrower: {years: 123456789.123, status: "open", urgent: false, vehicles: [{score: 1000, since: "2030-12-31", city: "A1"}, {score: -1, since: "2024-01-01", city: "retail"}, {score: -0, since: "2000-01-01", city: "x-y"}, {score: 99.99, since: "1990-06-15", city: "O'Neil"}, {score: 2, city: "gold"}]}}, {borrower: {adjusted: "123456789.123", share: false, status: "open", total: 123456789.123, urgent: false, vehicles: [{band: 1100.99, city: "A1", eligible: true, score: 1000, since: "2030-12-31", surcharge: false}, {band: 1100.99, city: "retail", eligible: true, score: -1, since: "2024-01-01", surcharge: false}, {band: 1100.99, city: "x-y", eligible: true, score: 0, since: "2000-01-01", surcharge: false}, {band: 1100.99, city: "O'Neil", eligible: true, score: 99.99, since: "1990-06-15", surcharge: false}, {band: 1100.99, city: "gold", eligible: true, score: 2, surcharge: false}], weighted: false, years: 123456789.123}, quota: false}], + [{borrower: {years: 7.25, status: "open", urgent: true, vehicles: [{score: 123456789.123, since: "2024-01-01", city: "12"}, {score: 2.50, since: "2000-01-01", city: "low"}, {score: 65, since: "2024-01-01", city: "日本"}, {score: 2.50, since: "2025-03-20T10:15:30Z", city: "low"}]}}, {borrower: {adjusted: "7.25", share: true, status: "open", total: 7.25, urgent: true, vehicles: [{band: 123456859.123, city: "12", eligible: true, score: 123456789.123, since: "2024-01-01", surcharge: true}, {band: 123456859.123, city: "low", eligible: true, score: 2.50, since: "2000-01-01", surcharge: true}, {band: 123456859.123, city: "日本", eligible: true, score: 65, since: "2024-01-01", surcharge: true}, {band: 123456859.123, city: "low", eligible: true, score: 2.50, since: "2025-03-20T10:15:30Z", surcharge: true}], weighted: true, years: 7.25}, quota: true}], + [{borrower: {years: 1000, status: "pending", urgent: true, vehicles: []}}, {borrower: {adjusted: "1000", share: true, status: "pending", total: 1000, urgent: true, vehicles: [], weighted: true, years: 1000}, quota: true}], + [{borrower: {years: -1, status: "open", urgent: true, vehicles: [{score: 2.50, since: "2025-03-20T10:15:30Z", city: " pad "}, {score: 1000, since: "1990-06-15", city: "-"}, {score: -0, since: "2025-03-20T10:15:30Z", city: "A1"}]}}, {borrower: {adjusted: "-1", share: true, status: "open", total: -1, urgent: true, vehicles: [{band: 1002.50, city: " pad ", eligible: true, score: 2.50, since: "2025-03-20T10:15:30Z", surcharge: true}, {band: 1002.50, city: "-", eligible: true, score: 1000, since: "1990-06-15", surcharge: true}, {band: 1002.50, city: "A1", eligible: true, score: 0, since: "2025-03-20T10:15:30Z", surcharge: true}], weighted: true, years: -1}, quota: true}], + [{borrower: {years: 7.25, status: "open", urgent: true, vehicles: [{score: 65, since: "1990-06-15", city: "a"}, {score: 100, since: "1990-06-15", city: "gold"}, {score: -0, since: "2025-03-20", city: " pad "}]}}, {borrower: {adjusted: "7.25", share: true, status: "open", total: 7.25, urgent: true, vehicles: [{band: 165, city: "a", eligible: true, score: 65, since: "1990-06-15", surcharge: true}, {band: 165, city: "gold", eligible: true, score: 100, since: "1990-06-15", surcharge: true}, {band: 165, city: " pad ", eligible: true, score: 0, since: "2025-03-20", surcharge: true}], weighted: true, years: 7.25}, quota: true}], + [{borrower: {years: 2.50, status: "closed", urgent: false, vehicles: [{score: -0.01, since: "2025-03-20T10:15:30Z", city: "-"}]}}, {borrower: {adjusted: "2.50", share: false, status: "closed", total: 2.50, urgent: false, vehicles: [{band: -0.01, city: "-", eligible: true, score: -0.01, since: "2025-03-20T10:15:30Z", surcharge: false}], weighted: false, years: 2.50}, quota: false}], + [{borrower: {years: -1, status: "closed", urgent: false, vehicles: [{score: 250, since: 20250101, city: "-"}, {score: 0.5, since: "2025-03-20", city: "low"}, {score: 1, since: "2024-02-29", city: "low"}, {score: -1, since: "2025-03-20T10:15:30Z", city: "NL"}]}}, "!error: InputValidationFailed"], + [{borrower: {years: -0.5, status: "pending", urgent: true, vehicles: [{score: 2, since: "2000-01-01", city: "VIP"}], extraField: {nested: true}}}, {borrower: {adjusted: "-0.5", extraField: {nested: true}, share: true, status: "pending", total: -0.5, urgent: true, vehicles: [{band: 2, city: "VIP", eligible: true, score: 2, since: "2000-01-01", surcharge: true}], weighted: true, years: -0.5}, quota: true}], + [{borrower: {years: 0, status: "open", urgent: false, vehicles: [{score: 2, since: "1990-06-15", city: "NL"}, {score: 65, since: "2030-12-31", city: "A1"}, {score: -0, since: "2000-01-01", city: "x"}], extraField: "x"}}, {borrower: {adjusted: "0", extraField: "x", share: false, status: "open", total: 0, urgent: false, vehicles: [{band: 67, city: "NL", eligible: true, score: 2, since: "1990-06-15", surcharge: false}, {band: 67, city: "A1", eligible: true, score: 65, since: "2030-12-31", surcharge: false}, {band: 67, city: "x", eligible: true, score: 0, since: "2000-01-01", surcharge: false}], weighted: false, years: 0}, quota: false}], + [{borrower: {years: 1e3, status: "open", urgent: true, vehicles: [{score: -0.01, since: "2025-03-20T10:15:30Z", city: "gold"}]}}, {borrower: {adjusted: "1000", share: true, status: "open", total: 1000, urgent: true, vehicles: [{band: -0.01, city: "gold", eligible: true, score: -0.01, since: "2025-03-20T10:15:30Z", surcharge: true}], weighted: true, years: 1000}, quota: true}], + [{borrower: {years: 0.000001, status: "pending", urgent: true, vehicles: [{score: -1, city: "O'Neil"}]}}, {borrower: {adjusted: "0.000001", share: true, status: "pending", total: 0.000001, urgent: true, vehicles: [{band: -1, city: "O'Neil", eligible: true, score: -1, surcharge: false}], weighted: true, years: 0.000001}, quota: true}], + [{borrower: {years: 0.5, status: "pending", urgent: true, vehicles: [{score: 250, since: null, city: "é ü"}, {score: 7.25, since: null, city: " pad "}]}}, {borrower: {adjusted: "0.5", share: true, status: "pending", total: 0.5, urgent: true, vehicles: [{band: 257.25, city: "é ü", eligible: true, score: 250, since: null, surcharge: false}, {band: 257.25, city: " pad ", eligible: true, score: 7.25, since: null, surcharge: false}], weighted: true, years: 0.5}, quota: true}], + [{borrower: {years: 231, status: "closed", urgent: true, vehicles: [{score: 7.25, since: "2025-03-20T10:15:30Z", city: "x"}, {score: 5, city: "gold"}, {score: 0.5, since: "2025-03-20T10:15:30Z", city: "gold"}]}}, {borrower: {adjusted: "231", share: true, status: "closed", total: 231, urgent: true, vehicles: [{band: 12.75, city: "x", eligible: true, score: 7.25, since: "2025-03-20T10:15:30Z", surcharge: true}, {band: 12.75, city: "gold", eligible: true, score: 5, surcharge: false}, {band: 12.75, city: "gold", eligible: true, score: 0.5, since: "2025-03-20T10:15:30Z", surcharge: true}], weighted: true, years: 231}, quota: true}], + [{borrower: {years: 5, status: "closed", urgent: false, vehicles: [{score: 99999999999999999999, since: "2024-01-01", city: "O'Neil"}, {score: -1, since: "2000-01-01", city: " pad "}, {score: -0.01, since: "2025-03-20", city: "a-b-c"}]}}, "!error: ExpressionFailed"], + [{borrower: {years: -0, status: "pending", urgent: true, vehicles: []}}, {borrower: {adjusted: "0", share: true, status: "pending", total: 0, urgent: true, vehicles: [], weighted: true, years: 0}, quota: true}], + ], +} + +// seed 331900 (attempt 0) +{ + name: "a 20: applicant/companies: 3 expression, 1 table; 3 root, 1 per-member, 0 top-level computed", + policy: { + models: {applicant: {rate: "number", active: "boolean", age: "number?", label: "string?", companies: "company[]"}, company: {qty: "number?", limit: "number"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {expression: "company.risk", value: "applicant.age != null"}, + {expression: "applicant.segment", value: "sum(map(applicant.companies, #.limit))"}, + {table: "t3", inputs: ["cap"], outputs: ["applicant.level"], rules: [ + ["", "applicant.rate"], + ["< 0.25", "applicant.segment"], + ["", "50"], + ]}, + {expression: "applicant.flag", value: "min([applicant.rate, applicant.rate])"}, + ], + }, + cases: [ + [{cap: 1, applicant: {rate: 2, active: false, age: 50, label: "gold", companies: [{qty: -0.01, limit: -0.01}, {qty: -1, limit: 0.000001}]}}, {applicant: {active: false, age: 50, companies: [{limit: -0.01, qty: -0.01, risk: true}, {limit: 0.000001, qty: -1, risk: true}], flag: 2, label: "gold", level: 2, rate: 2}, cap: 1}], + [{cap: -2, applicant: {rate: -500, active: false, companies: [{limit: 0.5}, {qty: 1000, limit: 1000000}, {qty: null, limit: 1}, {qty: 100, limit: 10}]}}, {applicant: {active: false, companies: [{limit: 0.5, risk: false}, {limit: 1000000, qty: 1000, risk: false}, {limit: 1, qty: null, risk: false}, {limit: 10, qty: 100, risk: false}], flag: -500, level: -500, rate: -500}, cap: -2}], + [{cap: 1, applicant: {rate: -500, active: false, age: 18, label: "x-y", companies: [{qty: 2, limit: 1000}, {qty: 99999999999999999999, limit: -0.01}, {qty: 100, limit: 0.000001}]}}, {applicant: {active: false, age: 18, companies: [{limit: 1000, qty: 2, risk: true}, {limit: -0.01, qty: 99999999999999999999, risk: true}, {limit: 0.000001, qty: 100, risk: true}], flag: -500, label: "x-y", level: -500, rate: -500}, cap: 1}], + [{cap: 1, applicant: {rate: -0, active: true, age: 5, label: "é ü", companies: [{limit: 99.99}, {qty: 1000, limit: -500}, {limit: 1}, {limit: 1}, {qty: 456, limit: -0.01}]}}, {applicant: {active: true, age: 5, companies: [{limit: 99.99, risk: true}, {limit: -500, qty: 1000, risk: true}, {limit: 1, risk: true}, {limit: 1, risk: true}, {limit: -0.01, qty: 456, risk: true}], flag: 0, label: "é ü", level: 0, rate: 0}, cap: 1}], + [{cap: 0.5, applicant: {rate: 5, active: true, age: 99.99, label: "abc", companies: [{qty: 0.5, limit: 0.000001}, {qty: 0.1, limit: 0.1}]}}, {applicant: {active: true, age: 99.99, companies: [{limit: 0.000001, qty: 0.5, risk: true}, {limit: 0.1, qty: 0.1, risk: true}], flag: 5, label: "abc", level: 5, rate: 5}, cap: 0.5}], + [{cap: 10, applicant: {rate: -0.5, active: false, age: 1000, label: "NL", companies: [{qty: 123456789.123, limit: 1000}]}}, {applicant: {active: false, age: 1000, companies: [{limit: 1000, qty: 123456789.123, risk: true}], flag: -0.5, label: "NL", level: -0.5, rate: -0.5}, cap: 10}], + [{cap: 0.5, applicant: {rate: -0, active: true, age: 10, label: "x-y", companies: [{qty: 1e3, limit: -0}, {qty: 7.25, limit: 1000}, {qty: null, limit: 123456789.123}, {limit: 250}]}}, {applicant: {active: true, age: 10, companies: [{limit: 0, qty: 1000, risk: true}, {limit: 1000, qty: 7.25, risk: true}, {limit: 123456789.123, qty: null, risk: true}, {limit: 250, risk: true}], flag: 0, label: "x-y", level: 0, rate: 0}, cap: 0.5}], + [{cap: 0.5, applicant: {rate: 2, active: true, age: 99999999999999999999, label: "-", companies: [{qty: 1000000, limit: 2}, {qty: 65, limit: -0.01}]}}, {applicant: {active: true, age: 99999999999999999999, companies: [{limit: 2, qty: 1000000, risk: true}, {limit: -0.01, qty: 65, risk: true}], flag: 2, label: "-", level: 2, rate: 2}, cap: 0.5}], + [{cap: -2, applicant: {rate: 0.25, active: false, age: -500, label: "abc", companies: [{qty: -1, limit: -0}]}}, {applicant: {active: false, age: -500, companies: [{limit: 0, qty: -1, risk: true}], flag: 0.25, label: "abc", level: 0.25, rate: 0.25}, cap: -2}], + [{cap: 0.5, applicant: {rate: -0, active: false, age: 1000, label: "O'Neil", companies: [{qty: 2.50, limit: 0}]}}, {applicant: {active: false, age: 1000, companies: [{limit: 0, qty: 2.50, risk: true}], flag: 0, label: "O'Neil", level: 0, rate: 0}, cap: 0.5}], + [{cap: 0, applicant: {rate: -0, active: true, age: 10, label: " pad ", companies: [{qty: -0.01, limit: 202}, {qty: 0, limit: 0.25}]}}, {applicant: {active: true, age: 10, companies: [{limit: 202, qty: -0.01, risk: true}, {limit: 0.25, qty: 0, risk: true}], flag: 0, label: " pad ", level: 0, rate: 0}, cap: 0}], + [{cap: 10, applicant: {rate: -0, active: false, age: -1, label: "12", companies: [{qty: null, limit: 5}, {qty: 0.000001, limit: -0.5}, {qty: -0, limit: 0.25}, {qty: 1, limit: 123456789.123}, {qty: 2.50, limit: 1000}]}}, {applicant: {active: false, age: -1, companies: [{limit: 5, qty: null, risk: true}, {limit: -0.5, qty: 0.000001, risk: true}, {limit: 0.25, qty: 0, risk: true}, {limit: 123456789.123, qty: 1, risk: true}, {limit: 1000, qty: 2.50, risk: true}], flag: 0, label: "12", level: 0, rate: 0}, cap: 10}], + [{cap: -2, applicant: {rate: -500, active: true, companies: [{qty: 1000, limit: 7.25}, {limit: 1000000}, {qty: 1000000, limit: 303}]}}, {applicant: {active: true, companies: [{limit: 7.25, qty: 1000, risk: false}, {limit: 1000000, risk: false}, {limit: 303, qty: 1000000, risk: false}], flag: -500, level: -500, rate: -500}, cap: -2}], + ], +} + +// seed 332000 (attempt 0) +{ + name: "a 21: shipment/loans: 1 expression, 2 match, 1 table; 0 root, 4 per-member, 0 top-level computed", + policy: { + models: {shipment: {balance: "number?", name: "string", birthDate: "date?", loans: "loan[]?"}, loan: {score: "number", balance: "number?", weight: "number", price: "number?"}}, + blocks: [ + {expression: "loan.health", value: "trim(loan.adjusted)"}, + {table: "t1", hit: "collect", inputs: ["(shipment.birthDate ?? d('2025-01-01'))"], outputs: ["loan.ok"], rules: [ + ["", "loan.score"], + ["> d('2025-03-20')", "1000"], + ["", "(shipment.balance ?? 0)"], + ["> d('2025-01-01')", "250"], + ]}, + {match: "loan.total", arms: [["len((loan.adjusted + '-' + shipment.name)) > 2", "trim(trim(loan.adjusted))"], ["", "shipment.name"]]}, + {match: "loan.adjusted", arms: [["(shipment.birthDate ?? d('2025-01-01')) < d('2024-01-01')", "((shipment.name + '-' + shipment.name) + '-' + ((shipment.balance ?? 0) > 5 ? shipment.name : shipment.name))"], ["loan.weight in [48..147]", "(loan.score <= 0 ? shipment.name : shipment.name)"], ["not (shipment.name in ['a', 'VIP'])", "shipment.name"], ["", "shipment.name"]]}, + ], + }, + cases: [ + [{shipment: {balance: 2, name: "A1", birthDate: "2024-01-01", loans: []}}, {shipment: {balance: 2, birthDate: "2024-01-01", loans: [], name: "A1"}}], + [{shipment: {balance: [1], name: "NL", birthDate: "2024-02-29", loans: [{score: 0.5, balance: 65, weight: 18, price: -0}, {score: 250, balance: 0.000001, weight: 10, price: 1000}]}}, "!error: InputValidationFailed"], + [{shipment: {balance: 5, name: "NL", birthDate: "2024-01-01", loans: [{score: 2, balance: true, weight: -500, price: -0}]}}, "!error: InputValidationFailed"], + [{shipment: {balance: 1000, name: "x-y", birthDate: "2024-02-29", loans: [{score: -0.5, balance: 18, weight: 5, price: 10}]}}, {shipment: {balance: 1000, birthDate: "2024-02-29", loans: [{adjusted: "x-y", balance: 18, health: "x-y", ok: [-0.5, 1000], price: 10, score: -0.5, total: "x-y", weight: 5}], name: "x-y"}}], + [{shipment: {balance: null, name: "Oslo", birthDate: null, loans: null}}, {shipment: {balance: null, birthDate: null, loans: null, name: "Oslo"}}], + [{shipment: {balance: 0.5, name: "US", birthDate: "2025-03-20T10:15:30Z", loans: [{score: -500, balance: 1000, weight: 18, price: 18}]}}, {shipment: {balance: 0.5, birthDate: "2025-03-20T10:15:30Z", loans: [{adjusted: "US", balance: 1000, health: "US", ok: [-500, 1000, 0.5, 250], price: 18, score: -500, total: "US", weight: 18}], name: "US"}}], + [{shipment: {balance: null, name: " pad ", birthDate: "2025-03-20T10:15:30Z", loans: null}}, {shipment: {balance: null, birthDate: "2025-03-20T10:15:30Z", loans: null, name: " pad "}}], + [{shipment: {balance: 0, name: "O'Neil", loans: [{score: 2, balance: -500, weight: 5, price: 250}, {score: 0.1, balance: null, weight: 0.1, price: null}, {score: 65, balance: 18, weight: 0.5, price: 0.5}, {score: 5, balance: 250, weight: 18, price: 0.5}]}}, {shipment: {balance: 0, loans: [{adjusted: "O'Neil", balance: -500, health: "O'Neil", ok: [2, 0], price: 250, score: 2, total: "O'Neil", weight: 5}, {adjusted: "O'Neil", balance: null, health: "O'Neil", ok: [0.1, 0], price: null, score: 0.1, total: "O'Neil", weight: 0.1}, {adjusted: "O'Neil", balance: 18, health: "O'Neil", ok: [65, 0], price: 0.5, score: 65, total: "O'Neil", weight: 0.5}, {adjusted: "O'Neil", balance: 250, health: "O'Neil", ok: [5, 0], price: 0.5, score: 5, total: "O'Neil", weight: 18}], name: "O'Neil"}}], + [{shipment: {balance: 2, name: "12", birthDate: "2000-01-01", loans: []}}, {shipment: {balance: 2, birthDate: "2000-01-01", loans: [], name: "12"}}], + [{shipment: {balance: -0, name: "NL", birthDate: "2030-12-31", loans: [{score: 0.1, balance: 1e3, weight: 2, price: 99999999999999999999}, {score: 250, balance: 2, weight: 0.000001, price: 250}, {score: 250, balance: 18, weight: -0.5, price: 1e3}]}}, {shipment: {balance: 0, birthDate: "2030-12-31", loans: [{adjusted: "NL", balance: 1000, health: "NL", ok: [0.1, 1000, 0, 250], price: 99999999999999999999, score: 0.1, total: "NL", weight: 2}, {adjusted: "NL", balance: 2, health: "NL", ok: [250, 1000, 0, 250], price: 250, score: 250, total: "NL", weight: 0.000001}, {adjusted: "NL", balance: 18, health: "NL", ok: [250, 1000, 0, 250], price: 1000, score: 250, total: "NL", weight: -0.5}], name: "NL"}}], + [{shipment: {balance: 18, name: "VIP", birthDate: "2025-03-20T10:15:30Z", loans: []}}, {shipment: {balance: 18, birthDate: "2025-03-20T10:15:30Z", loans: [], name: "VIP"}}], + [{shipment: {balance: 0, name: "NL", birthDate: "2024-02-29", loans: []}}, {shipment: {balance: 0, birthDate: "2024-02-29", loans: [], name: "NL"}}], + [{shipment: {balance: 0, name: "NL", birthDate: "2024-01-01", loans: [{score: 0.5, balance: 250, weight: -500, price: 100}, {score: 0.000001, balance: 5, weight: 100, price: 18}]}}, {shipment: {balance: 0, birthDate: "2024-01-01", loans: [{adjusted: "NL", balance: 250, health: "NL", ok: [0.5, 0], price: 100, score: 0.5, total: "NL", weight: -500}, {adjusted: "NL", balance: 5, health: "NL", ok: [0.000001, 0], price: 18, score: 0.000001, total: "NL", weight: 100}], name: "NL"}}], + [{shipment: {balance: null, name: "12", birthDate: null, loans: null}}, {shipment: {balance: null, birthDate: null, loans: null, name: "12"}}], + [{shipment: {balance: 1, name: "a", birthDate: null, loans: [{score: 18, balance: null, weight: 1000, price: 1}]}}, {shipment: {balance: 1, birthDate: null, loans: [{adjusted: "a", balance: null, health: "a", ok: [18, 1], price: 1, score: 18, total: "a", weight: 1000}], name: "a"}}], + [{shipment: {balance: 1e3, name: "DE", birthDate: "2024-01-01", loans: [{score: 1000, balance: 0.000001, weight: 0.5, price: 2}, {score: 18, balance: 123456789.123, weight: 5, price: 1}, {score: -0.01, balance: 1000000, weight: -0, price: 1000}, {score: 100, balance: 7.25, weight: 2, price: -0.5}, {score: 1, balance: 1, weight: -0.5, price: 5}], extraField: "x"}}, {shipment: {balance: 1000, birthDate: "2024-01-01", extraField: "x", loans: [{adjusted: "DE", balance: 0.000001, health: "DE", ok: [1000, 1000], price: 2, score: 1000, total: "DE", weight: 0.5}, {adjusted: "DE", balance: 123456789.123, health: "DE", ok: [18, 1000], price: 1, score: 18, total: "DE", weight: 5}, {adjusted: "DE", balance: 1000000, health: "DE", ok: [-0.01, 1000], price: 1000, score: -0.01, total: "DE", weight: 0}, {adjusted: "DE", balance: 7.25, health: "DE", ok: [100, 1000], price: -0.5, score: 100, total: "DE", weight: 2}, {adjusted: "DE", balance: 1, health: "DE", ok: [1, 1000], price: 5, score: 1, total: "DE", weight: -0.5}], name: "DE"}}], + [{shipment: {balance: true, name: "retail", birthDate: "2025-03-20", loans: []}}, "!error: InputValidationFailed"], + [{shipment: {balance: 1e3, name: "3.5", birthDate: "1990-06-15", loans: [{score: -0, balance: 1000, weight: 0.5, price: 1}]}}, {shipment: {balance: 1000, birthDate: "1990-06-15", loans: [{adjusted: "3.5-3.5-3.5", balance: 1000, health: "3.5-3.5-3.5", ok: [0, 1000], price: 1, score: 0, total: "3.5-3.5-3.5", weight: 0.5}], name: "3.5"}}], + [{shipment: {balance: 0.000001, name: "Zed", birthDate: "2024-02-29", loans: [{score: 0.000001, balance: [1], weight: -500, price: 100}, {score: 18, balance: 1000, weight: 1000000, price: 1e3}, {score: 2, balance: 1000000, weight: 123456789.123, price: 250}]}}, "!error: InputValidationFailed"], + [{shipment: {balance: -1, name: "ok", birthDate: "2030-12-31", loans: [{score: 123456789.123, balance: 5, weight: 24, price: 1000000}, {score: 2.50, balance: 123456789.123, weight: -0.5, price: 0}]}}, {shipment: {balance: -1, birthDate: "2030-12-31", loans: [{adjusted: "ok", balance: 5, health: "ok", ok: [123456789.123, 1000, -1, 250], price: 1000000, score: 123456789.123, total: "ok", weight: 24}, {adjusted: "ok", balance: 123456789.123, health: "ok", ok: [2.50, 1000, -1, 250], price: 0, score: 2.50, total: "ok", weight: -0.5}], name: "ok"}}], + [{shipment: {balance: null, name: "Zed", birthDate: null, loans: null}}, {shipment: {balance: null, birthDate: null, loans: null, name: "Zed"}}], + [{shipment: {balance: 7.25, name: "日本", birthDate: "1990-06-15", loans: [{score: 65, balance: 0, weight: 1000000, price: 1}, {score: -0, balance: 2, weight: 250, price: 5}, {score: 1000, balance: 1000000, weight: 18, price: 100}, {score: 5, balance: 5, weight: 2.50, price: -1}]}}, {shipment: {balance: 7.25, birthDate: "1990-06-15", loans: [{adjusted: "日本-日本-日本", balance: 0, health: "日本-日本-日本", ok: [65, 7.25], price: 1, score: 65, total: "日本-日本-日本", weight: 1000000}, {adjusted: "日本-日本-日本", balance: 2, health: "日本-日本-日本", ok: [0, 7.25], price: 5, score: 0, total: "日本-日本-日本", weight: 250}, {adjusted: "日本-日本-日本", balance: 1000000, health: "日本-日本-日本", ok: [1000, 7.25], price: 100, score: 1000, total: "日本-日本-日本", weight: 18}, {adjusted: "日本-日本-日本", balance: 5, health: "日本-日本-日本", ok: [5, 7.25], price: -1, score: 5, total: "日本-日本-日本", weight: 2.50}], name: "日本"}}], + [{shipment: {balance: 18, birthDate: "2025-03-20", loans: [{score: 250, balance: 1, weight: 18, price: 0}, {score: 5, balance: -0.01, weight: 123456789.123, price: -0.01}]}}, "!error: MissingRequiredInputs"], + ], +} + +// seed 332100 (attempt 0) +{ + name: "a 22: shipment/items: 1 assertion, 2 expression; 2 root, 0 per-member, 1 top-level computed", + policy: { + models: {shipment: {rate: "number?", score: "number?", dueDate: "date", label: "string?", insured: "boolean?", priority: "boolean", items: "item[]"}, item: {days: "number", verified: "boolean", label: "string?"}}, + blocks: [ + {expression: "shipment.adjusted", value: "sum(map(shipment.items, #.days))"}, + {expression: "shipment.total", value: "((shipment.rate ?? 0) + 250)"}, + {assertion: "penalty", conditions: [["and", "(shipment.rate ?? 0) == (shipment.score ?? 0)", 2], ["and", "(shipment.priority ? (shipment.label ?? '') : (shipment.label ?? '')) != 'none'", 1], "not ((shipment.label ?? '') == 'A1')", ["or", "shipment.insured == null", 1]]}, + ], + }, + cases: [ + [{shipment: {rate: 99.99, score: 7.25, dueDate: "1990-06-15", label: "US", insured: true, priority: true, items: [{days: 99.99, verified: true, label: "DE"}]}}, {penalty: false, shipment: {adjusted: 99.99, dueDate: "1990-06-15", insured: true, items: [{days: 99.99, label: "DE", verified: true}], label: "US", priority: true, rate: 99.99, score: 7.25, total: 349.99}}], + [{shipment: {dueDate: "1990-06-15", priority: false, items: [{days: 99.99, verified: false, label: "VIP"}, {days: 250, verified: true, label: "a"}, {days: 1000000, verified: true, label: "x-y"}]}}, {penalty: true, shipment: {adjusted: 1000349.99, dueDate: "1990-06-15", items: [{days: 99.99, label: "VIP", verified: false}, {days: 250, label: "a", verified: true}, {days: 1000000, label: "x-y", verified: true}], priority: false, total: 250}}], + [{shipment: {rate: null, score: 0, dueDate: "2000-01-01", label: null, insured: true, priority: false, items: [{days: 7.25, verified: true, label: "gold"}]}}, {penalty: false, shipment: {adjusted: 7.25, dueDate: "2000-01-01", insured: true, items: [{days: 7.25, label: "gold", verified: true}], label: null, priority: false, rate: null, score: 0, total: 250}}], + [{shipment: {rate: 10, score: 10, dueDate: "2024-01-01", label: null, insured: true, priority: true, items: [{days: 0.1, verified: true, label: null}]}}, {penalty: false, shipment: {adjusted: 0.1, dueDate: "2024-01-01", insured: true, items: [{days: 0.1, label: null, verified: true}], label: null, priority: true, rate: 10, score: 10, total: 260}}], + [{shipment: {rate: -0, score: 1e3, dueDate: "2000-01-01", priority: true, items: [{days: 65, verified: false, label: "a-b-c"}, {days: 10, verified: true}]}}, {penalty: false, shipment: {adjusted: 75, dueDate: "2000-01-01", items: [{days: 65, label: "a-b-c", verified: false}, {days: 10, verified: true}], priority: true, rate: 0, score: 1000, total: 250}}], + [{shipment: {rate: 0.000001, dueDate: "2025-03-20T10:15:30Z", priority: false, items: [{days: 292, verified: true, label: null}]}}, {penalty: false, shipment: {adjusted: 292, dueDate: "2025-03-20T10:15:30Z", items: [{days: 292, label: null, verified: true}], priority: false, rate: 0.000001, total: 250.000001}}], + [{shipment: {rate: 0, score: 99999999999999999999, dueDate: "1990-06-15", label: "NL", insured: true, priority: false, items: [{days: 0, verified: false, label: "VIP"}, {days: -1, verified: false, label: null}]}}, {penalty: false, shipment: {adjusted: -1, dueDate: "1990-06-15", insured: true, items: [{days: 0, label: "VIP", verified: false}, {days: -1, label: null, verified: false}], label: "NL", priority: false, rate: 0, score: 99999999999999999999, total: 250}}], + [{shipment: {rate: 250, score: 0.000001, dueDate: "2030-12-31", label: "Zed", insured: false, priority: true, items: [{verified: false, label: "12"}, {days: 0.000001, verified: true, label: "none"}]}}, "!error: ExpressionFailed"], + [{shipment: {rate: 250, score: 1000, dueDate: "1990-06-15", label: "Zed", insured: false, priority: false, items: [{days: 2.50, verified: true, label: "gold"}, {days: 1, verified: true, label: "O'Neil"}, {days: 10, verified: false, label: "日本"}, {days: 1000000, verified: false, label: "Oslo"}]}}, {penalty: false, shipment: {adjusted: 1000013.50, dueDate: "1990-06-15", insured: false, items: [{days: 2.50, label: "gold", verified: true}, {days: 1, label: "O'Neil", verified: true}, {days: 10, label: "日本", verified: false}, {days: 1000000, label: "Oslo", verified: false}], label: "Zed", priority: false, rate: 250, score: 1000, total: 500}}], + [{shipment: {rate: 0.000001, score: 65, dueDate: "2024-02-29", label: "A1", insured: true, priority: false, items: []}}, {penalty: false, shipment: {adjusted: 0, dueDate: "2024-02-29", insured: true, items: [], label: "A1", priority: false, rate: 0.000001, score: 65, total: 250.000001}}], + [{shipment: {dueDate: "2024-01-01", label: "A1", insured: true, priority: true, items: [{days: 7.25, verified: true, label: "retail"}, {days: 2.50, verified: false, label: "A1"}, {days: 1000, verified: false, label: "Oslo"}, {days: 250, verified: false}, {days: 2.50, verified: true, label: "none"}]}}, {penalty: false, shipment: {adjusted: 1262.25, dueDate: "2024-01-01", insured: true, items: [{days: 7.25, label: "retail", verified: true}, {days: 2.50, label: "A1", verified: false}, {days: 1000, label: "Oslo", verified: false}, {days: 250, verified: false}, {days: 2.50, label: "none", verified: true}], label: "A1", priority: true, total: 250}}], + [{shipment: {rate: 1, score: 7.25, dueDate: "2025-03-20", label: "gold", insured: true, priority: true, items: [{days: 10, verified: false, label: "NL"}]}}, {penalty: false, shipment: {adjusted: 10, dueDate: "2025-03-20", insured: true, items: [{days: 10, label: "NL", verified: false}], label: "gold", priority: true, rate: 1, score: 7.25, total: 251}}], + [{shipment: {rate: 1e3, score: 123456789.123, dueDate: "2025-03-20T10:15:30Z", label: "12", insured: false, priority: false, items: []}}, {penalty: false, shipment: {adjusted: 0, dueDate: "2025-03-20T10:15:30Z", insured: false, items: [], label: "12", priority: false, rate: 1000, score: 123456789.123, total: 1250}}], + [{shipment: {rate: -500, score: -0.5, dueDate: "2024-02-29", label: "3.5", insured: true, priority: false, items: [{days: 1e3, verified: true, label: "Zed"}, {days: 2, verified: true, label: "US"}, {days: 1000, verified: true, label: "DE"}, {days: 5, verified: true, label: "a-b-c"}, {days: -1, verified: true, label: "DE"}]}}, {penalty: false, shipment: {adjusted: 2006, dueDate: "2024-02-29", insured: true, items: [{days: 1000, label: "Zed", verified: true}, {days: 2, label: "US", verified: true}, {days: 1000, label: "DE", verified: true}, {days: 5, label: "a-b-c", verified: true}, {days: -1, label: "DE", verified: true}], label: "3.5", priority: false, rate: -500, score: -0.5, total: -250}}], + [{shipment: {rate: 2, score: 18, dueDate: "2024-02-29", label: "-", insured: true, priority: false, items: [{days: 2.50, verified: true, label: "VIP"}, {days: -0.5, verified: false, label: "3.5"}, {days: 0.5, verified: false, label: "NL"}, {days: 1000, verified: true, label: "a"}, {days: -0.5, verified: true, label: "Zed"}]}}, {penalty: false, shipment: {adjusted: 1002.00, dueDate: "2024-02-29", insured: true, items: [{days: 2.50, label: "VIP", verified: true}, {days: -0.5, label: "3.5", verified: false}, {days: 0.5, label: "NL", verified: false}, {days: 1000, label: "a", verified: true}, {days: -0.5, label: "Zed", verified: true}], label: "-", priority: false, rate: 2, score: 18, total: 252}}], + [{shipment: {rate: 99999999999999999999, score: 0, dueDate: "1990-06-15", label: "12", insured: true, priority: true, items: [{days: 10, verified: true, label: "retail"}], extraField: "x"}}, {penalty: false, shipment: {adjusted: 10, dueDate: "1990-06-15", extraField: "x", insured: true, items: [{days: 10, label: "retail", verified: true}], label: "12", priority: true, rate: 99999999999999999999, score: 0, total: 100000000000000000249}}], + [{shipment: {rate: 99.99, score: 99.99, dueDate: "2025-03-20", label: "-", insured: false, priority: false, items: [{days: -0.01, verified: false, label: "12"}], extraField: "x"}}, {penalty: false, shipment: {adjusted: -0.01, dueDate: "2025-03-20", extraField: "x", insured: false, items: [{days: -0.01, label: "12", verified: false}], label: "-", priority: false, rate: 99.99, score: 99.99, total: 349.99}}], + [{shipment: {dueDate: "1990-06-15", insured: false, priority: true, items: []}}, {penalty: false, shipment: {adjusted: 0, dueDate: "1990-06-15", insured: false, items: [], priority: true, total: 250}}], + [{shipment: {rate: 0.1, score: -500, dueDate: "1990-06-15", label: " pad ", insured: false, priority: false, items: []}}, {penalty: false, shipment: {adjusted: 0, dueDate: "1990-06-15", insured: false, items: [], label: " pad ", priority: false, rate: 0.1, score: -500, total: 250.1}}], + [{shipment: {score: 10, dueDate: "2000-01-01", insured: true, priority: false, items: [{days: 250, verified: false, label: ""}, {days: 99999999999999999999, verified: true}]}}, {penalty: false, shipment: {adjusted: 100000000000000000249, dueDate: "2000-01-01", insured: true, items: [{days: 250, label: "", verified: false}, {days: 99999999999999999999, verified: true}], priority: false, score: 10, total: 250}}], + [{shipment: {rate: 250, score: null, dueDate: "2025-03-20T10:15:30Z", label: null, insured: false, priority: true, items: [{days: 10, verified: false}, {days: 2.50, verified: true, label: "gold"}, {days: 123456789.123, verified: false, label: " pad "}]}}, {penalty: false, shipment: {adjusted: 123456801.623, dueDate: "2025-03-20T10:15:30Z", insured: false, items: [{days: 10, verified: false}, {days: 2.50, label: "gold", verified: true}, {days: 123456789.123, label: " pad ", verified: false}], label: null, priority: true, rate: 250, score: null, total: 500}}], + [{shipment: {rate: -0.01, score: 7.25, dueDate: "2000-01-01", label: "none", insured: false, priority: false, items: [{days: 0.1, verified: false, label: "Zed"}, {days: 1000000, verified: true, label: " pad "}]}}, {penalty: false, shipment: {adjusted: 1000000.1, dueDate: "2000-01-01", insured: false, items: [{days: 0.1, label: "Zed", verified: false}, {days: 1000000, label: " pad ", verified: true}], label: "none", priority: false, rate: -0.01, score: 7.25, total: 249.99}}], + [{shipment: {rate: 5, score: -500, dueDate: "2025-03-20T10:15:30Z", insured: true, priority: false, items: [{days: 7.25, verified: false, label: "O'Neil"}, {days: 123456789.123, verified: false}, {days: -500, verified: false}]}}, {penalty: false, shipment: {adjusted: 123456296.373, dueDate: "2025-03-20T10:15:30Z", insured: true, items: [{days: 7.25, label: "O'Neil", verified: false}, {days: 123456789.123, verified: false}, {days: -500, verified: false}], priority: false, rate: 5, score: -500, total: 255}}], + [{shipment: {dueDate: "2024-02-29", priority: false, items: [{days: 0, verified: true}, {days: 2, verified: false, label: null}]}}, {penalty: true, shipment: {adjusted: 2, dueDate: "2024-02-29", items: [{days: 0, verified: true}, {days: 2, label: null, verified: false}], priority: false, total: 250}}], + [{shipment: {rate: 0, score: 329, dueDate: "1990-06-15", label: "US", priority: false, items: [{days: -0.5, verified: false}, {days: 1, verified: true}, {days: 100, verified: false}, {days: -0, verified: true, label: "a-b-c"}]}}, {penalty: false, shipment: {adjusted: 100.5, dueDate: "1990-06-15", items: [{days: -0.5, verified: false}, {days: 1, verified: true}, {days: 100, verified: false}, {days: 0, label: "a-b-c", verified: true}], label: "US", priority: false, rate: 0, score: 329, total: 250}}], + [{shipment: {rate: 250, score: 10, dueDate: "1990-06-15", label: "", insured: false, priority: false, items: [{days: 0, verified: true, label: "A1"}, {days: 2.50, verified: true, label: "3.5"}, {days: 0.5, verified: true, label: "abc"}, {days: 1e3, verified: false, label: " pad "}], extraField: {nested: true}}}, {penalty: false, shipment: {adjusted: 1003.00, dueDate: "1990-06-15", extraField: {nested: true}, insured: false, items: [{days: 0, label: "A1", verified: true}, {days: 2.50, label: "3.5", verified: true}, {days: 0.5, label: "abc", verified: true}, {days: 1000, label: " pad ", verified: false}], label: "", priority: false, rate: 250, score: 10, total: 500}}], + [{shipment: {rate: 18, score: null, dueDate: "1990-06-15", label: "none", insured: true, priority: false, items: [{days: 250, verified: true}, {days: 5, verified: true, label: "3.5"}, {days: 0.5, verified: false, label: "日本"}, {days: 250, verified: true, label: "O'Neil"}]}}, {penalty: false, shipment: {adjusted: 505.5, dueDate: "1990-06-15", insured: true, items: [{days: 250, verified: true}, {days: 5, label: "3.5", verified: true}, {days: 0.5, label: "日本", verified: false}, {days: 250, label: "O'Neil", verified: true}], label: "none", priority: false, rate: 18, score: null, total: 268}}], + [{shipment: {rate: -1, score: 7.25, dueDate: "2025-03-20T10:15:30Z", label: "é ü", insured: false, priority: true, items: [{days: 65, verified: true, label: "Zed"}, {days: 59, verified: true, label: "12"}, {days: 2, verified: true, label: "3.5"}]}}, {penalty: false, shipment: {adjusted: 126, dueDate: "2025-03-20T10:15:30Z", insured: false, items: [{days: 65, label: "Zed", verified: true}, {days: 59, label: "12", verified: true}, {days: 2, label: "3.5", verified: true}], label: "é ü", priority: true, rate: -1, score: 7.25, total: 249}}], + [{shipment: {rate: 18, score: 0.5, dueDate: "1990-06-15", label: "none", insured: 1, priority: false, items: [{days: 123456789.123, verified: true, label: " pad "}]}}, "!error: InputValidationFailed"], + [{shipment: {rate: -500, score: -0.5, dueDate: "2025-03-20T10:15:30Z", label: "abc", insured: false, priority: true, items: []}}, {penalty: false, shipment: {adjusted: 0, dueDate: "2025-03-20T10:15:30Z", insured: false, items: [], label: "abc", priority: true, rate: -500, score: -0.5, total: -250}}], + ], +} + +// seed 332200 (attempt 0) +{ + name: "a 23: claim/lines: 1 assertion, 2 expression, 3 match, 1 table; 0 root, 6 per-member, 1 top-level computed", + policy: { + models: {claim: {age: "number?", since: "date", weight: "number", qty: "number", code: "string", label: "string", lines: "line[]"}, line: {amount: "number", label: "string"}}, + blocks: [ + {table: "t1", inputs: ["claim.qty", "((claim.age ?? 0) + (claim.age ?? 0))"], outputs: ["line.weighted"], rules: [ + ["3, 1000", "", ""], + ["1.5", "<= 1000", ""], + ["", "", "line.label"], + ["", "< 0", "line.label"], + ["50, 0", ">= 1", "claim.label"], + ["0.25", "", "'low'"], + ["< 10", "", "claim.code"], + ]}, + {match: "line.capped", arms: [["none(claim.lines, 250 == #.amount)", "(claim.age ?? 0)"], ["all(claim.lines, 250 > #.amount)", "line.amount"], ["((claim.age ?? 0) <= 0.5 and claim.qty > 0.5)", "250"], ["", "(claim.weight + claim.weight)"]]}, + {match: "segment", arms: [["(claim.age ?? 0) > claim.weight", "((claim.age ?? 0) <= 3 or claim.weight == 3)"], ["(claim.weight > 100 and claim.weight == 10)", "(10 > 18 and claim.qty > 5)"], ["(claim.qty > 3 ? claim.label : claim.code) != 'a'", "all(claim.lines, #.amount != #.amount)"], ["", "claim.weight == 0.25"]]}, + {match: "line.exposure", arms: [["claim.code == 'high'", "claim.label"], ["line.amount > (claim.age ?? 0)", "trim((line.weighted ?? ''))"], ["claim.age != null", "claim.code"], ["", "(line.weighted ?? '')"]]}, + {expression: "line.points", value: "min([(segment ? 1.5 : 1000), len(claim.lines)]) >= (claim.age ?? 0)"}, + {expression: "line.share", value: "claim.since.add(13, 'month')"}, + {assertion: "line.total", conditions: [["or", "all(claim.lines, #.exposure in ['gold', 'Oslo'])", 0], ["or", "(some(claim.lines, #.capped != #.capped) and (line.points and segment))", 1], "len((line.weighted ?? '')) != claim.weight", ["and", "claim.age != null", 0]]}, + ], + }, + cases: [ + [{claim: {since: "2024-02-29", weight: 3, qty: 65, code: "A1", label: "VIP", lines: [{amount: 18, label: "é ü"}, {amount: 1.5, label: "a"}, {amount: 99999999999999999999, label: "x-y"}, {amount: -0.5, label: "Oslo"}]}}, {claim: {code: "A1", label: "VIP", lines: [{amount: 18, capped: 0, exposure: "é ü", label: "é ü", points: true, share: "2025-03-29T00:00:00Z", total: false, weighted: "é ü"}, {amount: 1.5, capped: 0, exposure: "a", label: "a", points: true, share: "2025-03-29T00:00:00Z", total: false, weighted: "a"}, {amount: 99999999999999999999, capped: 0, exposure: "x-y", label: "x-y", points: true, share: "2025-03-29T00:00:00Z", total: false, weighted: "x-y"}, {amount: -0.5, capped: 0, exposure: "Oslo", label: "Oslo", points: true, share: "2025-03-29T00:00:00Z", total: false, weighted: "Oslo"}], qty: 65, since: "2024-02-29", weight: 3}, segment: false}], + [{claim: {age: 2, since: "2030-12-31", weight: 0.1, qty: 2.50, code: "gold", label: "-", lines: []}}, {claim: {age: 2, code: "gold", label: "-", lines: [], qty: 2.50, since: "2030-12-31", weight: 0.1}, segment: true}], + [{claim: {age: 1000, since: "2030-12-31", weight: 1000, qty: 1.5, code: "Oslo", label: "Oslo", lines: [{amount: 0.000001, label: "VIP"}, {amount: 10, label: "Oslo"}, {amount: -500, label: "é ü"}]}}, {claim: {age: 1000, code: "Oslo", label: "Oslo", lines: [{amount: 0.000001, capped: 1000, exposure: "Oslo", label: "VIP", points: false, share: "2032-01-31T00:00:00Z", total: true, weighted: "VIP"}, {amount: 10, capped: 1000, exposure: "Oslo", label: "Oslo", points: false, share: "2032-01-31T00:00:00Z", total: true, weighted: "Oslo"}, {amount: -500, capped: 1000, exposure: "Oslo", label: "é ü", points: false, share: "2032-01-31T00:00:00Z", total: true, weighted: "é ü"}], qty: 1.5, since: "2030-12-31", weight: 1000}, segment: false}], + [{claim: {age: 10, since: "2024-02-29", weight: 99999999999999999999, qty: 100, code: "Oslo", label: "abc", lines: [], extraField: "x"}}, {claim: {age: 10, code: "Oslo", extraField: "x", label: "abc", lines: [], qty: 100, since: "2024-02-29", weight: 99999999999999999999}, segment: true}], + [{claim: {age: 0, since: "2025-03-20T10:15:30Z", weight: 0.25, qty: 3, code: "DE", label: "DE", lines: [{amount: 2.50, label: "gold"}, {amount: 5, label: "retail"}, {amount: 0.5, label: "low"}, {amount: 1000000, label: "é ü"}]}}, {claim: {age: 0, code: "DE", label: "DE", lines: [{amount: 2.50, capped: 0, exposure: "gold", label: "gold", points: true, share: "2026-04-20T10:15:30Z", total: true, weighted: "gold"}, {amount: 5, capped: 0, exposure: "retail", label: "retail", points: true, share: "2026-04-20T10:15:30Z", total: true, weighted: "retail"}, {amount: 0.5, capped: 0, exposure: "low", label: "low", points: true, share: "2026-04-20T10:15:30Z", total: true, weighted: "low"}, {amount: 1000000, capped: 0, exposure: "é ü", label: "é ü", points: true, share: "2026-04-20T10:15:30Z", total: true, weighted: "é ü"}], qty: 3, since: "2025-03-20T10:15:30Z", weight: 0.25}, segment: false}], + [{claim: {age: 0.000001, since: "2024-02-29", weight: 250, qty: 1, code: "a", label: "DE", lines: [{amount: -0.01, label: "Zed"}, {amount: 10, label: "abc"}, {amount: 1, label: "US"}, {amount: -1, label: "O'Neil"}]}}, {claim: {age: 0.000001, code: "a", label: "DE", lines: [{amount: -0.01, capped: 0.000001, exposure: "a", label: "Zed", points: true, share: "2025-03-29T00:00:00Z", total: true, weighted: "Zed"}, {amount: 10, capped: 0.000001, exposure: "abc", label: "abc", points: true, share: "2025-03-29T00:00:00Z", total: true, weighted: "abc"}, {amount: 1, capped: 0.000001, exposure: "US", label: "US", points: true, share: "2025-03-29T00:00:00Z", total: true, weighted: "US"}, {amount: -1, capped: 0.000001, exposure: "a", label: "O'Neil", points: true, share: "2025-03-29T00:00:00Z", total: true, weighted: "O'Neil"}], qty: 1, since: "2024-02-29", weight: 250}, segment: false}], + [{claim: {age: 3, since: "2025-03-20T10:15:30Z", weight: 250, qty: 0.25, code: "Oslo", label: "", lines: [{amount: 1.5, label: ""}, {amount: 0.25, label: "NL"}]}}, {claim: {age: 3, code: "Oslo", label: "", lines: [{amount: 1.5, capped: 3, exposure: "Oslo", label: "", points: false, share: "2026-04-20T10:15:30Z", total: true, weighted: ""}, {amount: 0.25, capped: 3, exposure: "Oslo", label: "NL", points: false, share: "2026-04-20T10:15:30Z", total: true, weighted: "NL"}], qty: 0.25, since: "2025-03-20T10:15:30Z", weight: 250}, segment: false}], + [{claim: {age: 3, since: "2024-01-01", weight: 3, qty: 250, code: "a", label: "a-b-c", lines: [{amount: 10, label: "VIP"}, {amount: 250, label: "gold"}]}}, {claim: {age: 3, code: "a", label: "a-b-c", lines: [{amount: 10, capped: 6, exposure: "VIP", label: "VIP", points: false, share: "2025-02-01T00:00:00Z", total: false, weighted: "VIP"}, {amount: 250, capped: 6, exposure: "gold", label: "gold", points: false, share: "2025-02-01T00:00:00Z", total: true, weighted: "gold"}], qty: 250, since: "2024-01-01", weight: 3}, segment: false}], + [{claim: {age: 7.25, since: "2025-03-20", weight: 250, qty: 1000, code: "Oslo", label: "Zed", lines: [{amount: 10, label: "a"}, {amount: 250, label: "retail"}, {amount: -500, label: "US"}, {amount: 3, label: "high"}, {amount: 1.5, label: "日本"}]}}, {claim: {age: 7.25, code: "Oslo", label: "Zed", lines: [{amount: 10, capped: 500, exposure: "a", label: "a", points: false, share: "2026-04-20T00:00:00Z", total: true, weighted: "a"}, {amount: 250, capped: 500, exposure: "retail", label: "retail", points: false, share: "2026-04-20T00:00:00Z", total: true, weighted: "retail"}, {amount: -500, capped: 500, exposure: "Oslo", label: "US", points: false, share: "2026-04-20T00:00:00Z", total: true, weighted: "US"}, {amount: 3, capped: 500, exposure: "Oslo", label: "high", points: false, share: "2026-04-20T00:00:00Z", total: true, weighted: "high"}, {amount: 1.5, capped: 500, exposure: "Oslo", label: "日本", points: false, share: "2026-04-20T00:00:00Z", total: true, weighted: "日本"}], qty: 1000, since: "2025-03-20", weight: 250}, segment: false}], + [{claim: {age: 5, since: "2000-01-01", weight: 0.5, qty: 3, code: "US", label: "é ü", lines: [{amount: 2, label: "x-y"}, {amount: 1.5, label: "12"}, {amount: 18, label: " pad "}, {amount: 0.000001, label: "retail"}, {amount: 0.25, label: "-"}]}}, {claim: {age: 5, code: "US", label: "é ü", lines: [{amount: 2, capped: 5, exposure: "US", label: "x-y", points: true, share: "2001-02-01T00:00:00Z", total: true, weighted: "x-y"}, {amount: 1.5, capped: 5, exposure: "US", label: "12", points: true, share: "2001-02-01T00:00:00Z", total: true, weighted: "12"}, {amount: 18, capped: 5, exposure: "pad", label: " pad ", points: true, share: "2001-02-01T00:00:00Z", total: true, weighted: " pad "}, {amount: 0.000001, capped: 5, exposure: "US", label: "retail", points: true, share: "2001-02-01T00:00:00Z", total: true, weighted: "retail"}, {amount: 0.25, capped: 5, exposure: "US", label: "-", points: true, share: "2001-02-01T00:00:00Z", total: true, weighted: "-"}], qty: 3, since: "2000-01-01", weight: 0.5}, segment: false}], + [{claim: {age: 250, since: "2000-01-01", weight: 1.5, qty: 18, code: "a-b-c", label: "Zed", lines: [{amount: 3, label: " pad "}, {amount: 10, label: "-"}, {amount: 10, label: "12"}, {amount: 50, label: "NL"}, {amount: 329, label: "Oslo"}]}}, {claim: {age: 250, code: "a-b-c", label: "Zed", lines: [{amount: 3, capped: 250, exposure: "a-b-c", label: " pad ", points: false, share: "2001-02-01T00:00:00Z", total: true, weighted: " pad "}, {amount: 10, capped: 250, exposure: "a-b-c", label: "-", points: false, share: "2001-02-01T00:00:00Z", total: true, weighted: "-"}, {amount: 10, capped: 250, exposure: "a-b-c", label: "12", points: false, share: "2001-02-01T00:00:00Z", total: true, weighted: "12"}, {amount: 50, capped: 250, exposure: "a-b-c", label: "NL", points: false, share: "2001-02-01T00:00:00Z", total: true, weighted: "NL"}, {amount: 329, capped: 250, exposure: "Oslo", label: "Oslo", points: false, share: "2001-02-01T00:00:00Z", total: true, weighted: "Oslo"}], qty: 18, since: "2000-01-01", weight: 1.5}, segment: false}], + [{claim: {age: 1, since: "2000-01-01", weight: 0.25, qty: -0.5, code: "", label: "low", lines: []}}, {claim: {age: 1, code: "", label: "low", lines: [], qty: -0.5, since: "2000-01-01", weight: 0.25}, segment: true}], + [{claim: {age: 65, since: "1990-06-15", weight: -1, qty: 18, code: "DE", label: "", lines: [{amount: 3, label: "gold"}, {amount: 0, label: "high"}]}}, {claim: {age: 65, code: "DE", label: "", lines: [{amount: 3, capped: 65, exposure: "DE", label: "gold", points: false, share: "1991-07-15T00:00:00Z", total: true, weighted: "gold"}, {amount: 0, capped: 65, exposure: "DE", label: "high", points: false, share: "1991-07-15T00:00:00Z", total: true, weighted: "high"}], qty: 18, since: "1990-06-15", weight: -1}, segment: false}], + [{claim: {age: 100, since: "1990-06-15", weight: 1, qty: 0.5, code: "x-y", label: "a", lines: [{amount: 18, label: "O'Neil"}, {amount: 99.99, label: ""}, {amount: 0.25, label: "low"}, {amount: 0.25, label: "x-y"}]}}, {claim: {age: 100, code: "x-y", label: "a", lines: [{amount: 18, capped: 100, exposure: "x-y", label: "O'Neil", points: false, share: "1991-07-15T00:00:00Z", total: true, weighted: "O'Neil"}, {amount: 99.99, capped: 100, exposure: "x-y", label: "", points: false, share: "1991-07-15T00:00:00Z", total: true, weighted: ""}, {amount: 0.25, capped: 100, exposure: "x-y", label: "low", points: false, share: "1991-07-15T00:00:00Z", total: true, weighted: "low"}, {amount: 0.25, capped: 100, exposure: "x-y", label: "x-y", points: false, share: "1991-07-15T00:00:00Z", total: true, weighted: "x-y"}], qty: 0.5, since: "1990-06-15", weight: 1}, segment: false}], + [{claim: {age: 250, since: "2024-01-01", weight: 0.000001, qty: 99999999999999999999, code: "3.5", label: "gold", lines: [{amount: 123456789.123, label: "a"}]}}, {claim: {age: 250, code: "3.5", label: "gold", lines: [{amount: 123456789.123, capped: 250, exposure: "a", label: "a", points: false, share: "2025-02-01T00:00:00Z", total: true, weighted: "a"}], qty: 99999999999999999999, since: "2024-01-01", weight: 0.000001}, segment: false}], + [{claim: {age: null, since: "2030-12-31", weight: 3, qty: 3, code: "a-b-c", label: "12", lines: [{amount: 1e3, label: " pad "}, {amount: -1, label: "é ü"}]}}, {claim: {age: null, code: "a-b-c", label: "12", lines: [{amount: 1000, capped: 0, exposure: "pad", label: " pad ", points: true, share: "2032-01-31T00:00:00Z", total: false, weighted: " pad "}, {amount: -1, capped: 0, exposure: "é ü", label: "é ü", points: true, share: "2032-01-31T00:00:00Z", total: false, weighted: "é ü"}], qty: 3, since: "2030-12-31", weight: 3}, segment: false}], + [{claim: {age: -0.5, since: "not a date", weight: 1.5, qty: 10, code: "3.5", label: "low", lines: [{amount: 10, label: "VIP"}]}}, "!error: InputValidationFailed"], + [{claim: {age: null, since: "2025-03-20T10:15:30Z", weight: 0.25, qty: 0.25, code: "US", label: "Oslo", lines: [{amount: 7.25, label: "3.5"}, {amount: 1000, label: "12"}, {amount: 0, label: "é ü"}, {amount: 18, label: "a"}, {amount: 0.25, label: "high"}]}}, {claim: {age: null, code: "US", label: "Oslo", lines: [{amount: 7.25, capped: 0, exposure: "3.5", label: "3.5", points: true, share: "2026-04-20T10:15:30Z", total: false, weighted: "3.5"}, {amount: 1000, capped: 0, exposure: "12", label: "12", points: true, share: "2026-04-20T10:15:30Z", total: false, weighted: "12"}, {amount: 0, capped: 0, exposure: "é ü", label: "é ü", points: true, share: "2026-04-20T10:15:30Z", total: false, weighted: "é ü"}, {amount: 18, capped: 0, exposure: "a", label: "a", points: true, share: "2026-04-20T10:15:30Z", total: false, weighted: "a"}, {amount: 0.25, capped: 0, exposure: "high", label: "high", points: true, share: "2026-04-20T10:15:30Z", total: false, weighted: "high"}], qty: 0.25, since: "2025-03-20T10:15:30Z", weight: 0.25}, segment: false}], + [{claim: {age: 18, since: "2030-12-31", weight: 0.5, qty: 65, code: "VIP", label: "12", lines: [{amount: 3, label: "abc"}, {amount: 250, label: "gold"}, {amount: 5, label: "Oslo"}, {amount: 250, label: ""}]}}, {claim: {age: 18, code: "VIP", label: "12", lines: [{amount: 3, capped: 1.0, exposure: "VIP", label: "abc", points: false, share: "2032-01-31T00:00:00Z", total: true, weighted: "abc"}, {amount: 250, capped: 1.0, exposure: "gold", label: "gold", points: false, share: "2032-01-31T00:00:00Z", total: true, weighted: "gold"}, {amount: 5, capped: 1.0, exposure: "VIP", label: "Oslo", points: false, share: "2032-01-31T00:00:00Z", total: true, weighted: "Oslo"}, {amount: 250, capped: 1.0, exposure: "", label: "", points: false, share: "2032-01-31T00:00:00Z", total: true, weighted: ""}], qty: 65, since: "2030-12-31", weight: 0.5}, segment: false}], + [{claim: {age: 100, since: "2025-03-20T10:15:30Z", weight: 0, qty: 0.25, code: " pad ", label: "-", lines: [{amount: 1000000, label: " pad "}]}}, {claim: {age: 100, code: " pad ", label: "-", lines: [{amount: 1000000, capped: 100, exposure: "pad", label: " pad ", points: false, share: "2026-04-20T10:15:30Z", total: true, weighted: " pad "}], qty: 0.25, since: "2025-03-20T10:15:30Z", weight: 0}, segment: false}], + [{claim: {since: "2030-12-31", weight: 1000, qty: 2.50, code: "retail", label: "é ü", lines: [{amount: 1000, label: "a-b-c"}]}}, {claim: {code: "retail", label: "é ü", lines: [{amount: 1000, capped: 0, exposure: "a-b-c", label: "a-b-c", points: true, share: "2032-01-31T00:00:00Z", total: false, weighted: "a-b-c"}], qty: 2.50, since: "2030-12-31", weight: 1000}, segment: false}], + [{claim: {age: 250, since: "2024-01-01", weight: 3, qty: 1.5, code: " pad ", label: "", lines: [{amount: 0.25, label: "日本"}]}}, {claim: {age: 250, code: " pad ", label: "", lines: [{amount: 0.25, capped: 250, exposure: " pad ", label: "日本", points: false, share: "2025-02-01T00:00:00Z", total: true, weighted: "日本"}], qty: 1.5, since: "2024-01-01", weight: 3}, segment: true}], + [{claim: {age: 0.25, since: "2025-03-20", weight: 18, qty: 1.5, code: "NL", label: "é ü", lines: [{amount: 5, label: "a-b-c"}]}}, {claim: {age: 0.25, code: "NL", label: "é ü", lines: [{amount: 5, capped: 0.25, exposure: "a-b-c", label: "a-b-c", points: true, share: "2026-04-20T00:00:00Z", total: true, weighted: "a-b-c"}], qty: 1.5, since: "2025-03-20", weight: 18}, segment: false}], + [{claim: {age: 250, since: "2024-02-29", weight: 2.50, qty: 3, code: "DE", label: " pad ", lines: [{amount: 0.25, label: "Oslo"}, {amount: 65, label: "retail"}]}}, {claim: {age: 250, code: "DE", label: " pad ", lines: [{amount: 0.25, capped: 250, exposure: "DE", label: "Oslo", points: false, share: "2025-03-29T00:00:00Z", total: true, weighted: "Oslo"}, {amount: 65, capped: 250, exposure: "DE", label: "retail", points: false, share: "2025-03-29T00:00:00Z", total: true, weighted: "retail"}], qty: 3, since: "2024-02-29", weight: 2.50}, segment: false}], + [{claim: {since: "2025-03-20", weight: 1e3, qty: 1000, code: "Zed", label: "12", lines: [{amount: 250, label: "Oslo"}]}}, {claim: {code: "Zed", label: "12", lines: [{amount: 250, capped: 250, exposure: "Oslo", label: "Oslo", points: true, share: "2026-04-20T00:00:00Z", total: false, weighted: "Oslo"}], qty: 1000, since: "2025-03-20", weight: 1000}, segment: false}], + [{claim: {since: "2025-03-20", weight: 10, qty: 250, code: "high", label: "A1", lines: [{amount: -500, label: "VIP"}]}}, {claim: {code: "high", label: "A1", lines: [{amount: -500, capped: 0, exposure: "A1", label: "VIP", points: true, share: "2026-04-20T00:00:00Z", total: false, weighted: "VIP"}], qty: 250, since: "2025-03-20", weight: 10}, segment: false}], + ], +} + +// seed 332300 (attempt 0) +{ + name: "a 24: applicant/accounts: 1 assertion, 2 expression, 2 table; 0 root, 4 per-member, 1 top-level computed", + policy: { + models: {applicant: {balance: "number?", region: "string", score: "number", flagged: "boolean", accounts: "acct[]"}, acct: {score: "number?", plan: "string(basic|plus|premium|trial)?"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {expression: "acct.ok", value: "(acct.score ?? 0)"}, + {table: "t2", inputs: ["acct.plan"], outputs: ["acct.bucket"], rules: [ + ["'basic'", "applicant.region"], + ["'premium'", "applicant.region"], + ["", "applicant.region"], + ]}, + {assertion: "points", conditions: ["(applicant.flagged and applicant.flagged)", ["or", "startsWith(lower(applicant.region), 'VIP')", 0]]}, + {table: "t3", inputs: ["applicant.flagged", null], outputs: ["acct.discount"], rules: [ + ["false", "", "applicant.score"], + ["false", "", "cap"], + ["true", "0 == (applicant.balance ?? 0)", "cap"], + ["", "", "count(applicant.accounts, len((#.bucket ?? '')) > 3)"], + ]}, + {expression: "acct.summary", value: "(applicant.flagged ? cap : (acct.score ?? 0)) <= applicant.score"}, + ], + }, + cases: [ + [{cap: 0, applicant: {region: "3.5", score: -0.01, flagged: false, accounts: [{plan: "basic"}, {plan: null}, {plan: "premium"}, {score: 1e3, plan: "premium"}]}}, {applicant: {accounts: [{discount: -0.01, ok: 0, plan: "basic", summary: false}, {discount: -0.01, ok: 0, plan: null, summary: false}, {discount: -0.01, ok: 0, plan: "premium", summary: false}, {discount: -0.01, ok: 1000, plan: "premium", score: 1000, summary: false}], flagged: false, region: "3.5", score: -0.01}, cap: 0, points: false}], + [{cap: 0, applicant: {balance: 100, region: "日本", score: 18, flagged: true, accounts: [{score: 1000, plan: "trial"}]}}, {applicant: {accounts: [{bucket: "日本", discount: 1, ok: 1000, plan: "trial", score: 1000, summary: true}], balance: 100, flagged: true, region: "日本", score: 18}, cap: 0, points: false}], + [{cap: 100, applicant: {balance: 0, region: "x-y", score: 1000, flagged: true, accounts: [{score: 10, plan: "basic"}, {score: -0.01, plan: "trial"}, {score: 0.5, plan: "plus"}, {score: 99999999999999999999, plan: "basic"}, {score: -1, plan: "plus"}], extraField: 1}}, {applicant: {accounts: [{discount: 100, ok: 10, plan: "basic", score: 10, summary: true}, {discount: 100, ok: -0.01, plan: "trial", score: -0.01, summary: true}, {discount: 100, ok: 0.5, plan: "plus", score: 0.5, summary: true}, {discount: 100, ok: 99999999999999999999, plan: "basic", score: 99999999999999999999, summary: true}, {discount: 100, ok: -1, plan: "plus", score: -1, summary: true}], balance: 0, extraField: 1, flagged: true, region: "x-y", score: 1000}, cap: 100, points: false}], + [{cap: -2, applicant: {balance: 250, region: "ok", score: 1000000, flagged: true, accounts: [{score: 0.5, plan: "trial"}, {score: 417, plan: null}, {score: 310}]}}, {applicant: {accounts: [{bucket: "ok", discount: 0, ok: 0.5, plan: "trial", score: 0.5, summary: true}, {bucket: "ok", discount: 0, ok: 417, plan: null, score: 417, summary: true}, {bucket: "ok", discount: 0, ok: 310, score: 310, summary: true}], balance: 250, flagged: true, region: "ok", score: 1000000}, cap: -2, points: false}], + [{cap: 1, applicant: {balance: 0, region: " pad ", score: 123456789.123, flagged: true, accounts: [{score: 2, plan: "basic"}, {score: 180, plan: "plus"}]}}, {applicant: {accounts: [{discount: 1, ok: 2, plan: "basic", score: 2, summary: true}, {discount: 1, ok: 180, plan: "plus", score: 180, summary: true}], balance: 0, flagged: true, region: " pad ", score: 123456789.123}, cap: 1, points: false}], + [{cap: -2, applicant: {balance: 65, region: "x-y", score: 65, flagged: true, accounts: []}}, {applicant: {accounts: [], balance: 65, flagged: true, region: "x-y", score: 65}, cap: -2, points: false}], + [{cap: 1, applicant: {region: "日本", score: 99.99, flagged: false, accounts: [{plan: "trial"}]}}, {applicant: {accounts: [{discount: 99.99, ok: 0, plan: "trial", summary: true}], flagged: false, region: "日本", score: 99.99}, cap: 1, points: false}], + [{cap: 1, applicant: {balance: null, region: "3.5", score: 0, flagged: false, accounts: [{score: null}]}}, {applicant: {accounts: [{discount: 0, ok: 0, score: null, summary: true}], balance: null, flagged: false, region: "3.5", score: 0}, cap: 1, points: false}], + [{cap: 1, applicant: {balance: 472, region: "12", score: -1, flagged: false, accounts: [{score: -0.01, plan: "plus"}, {score: 1000, plan: "plus"}, {score: 0.1, plan: "basic"}, {score: 2, plan: "basic"}]}}, {applicant: {accounts: [{discount: -1, ok: -0.01, plan: "plus", score: -0.01, summary: false}, {discount: -1, ok: 1000, plan: "plus", score: 1000, summary: false}, {discount: -1, ok: 0.1, plan: "basic", score: 0.1, summary: false}, {discount: -1, ok: 2, plan: "basic", score: 2, summary: false}], balance: 472, flagged: false, region: "12", score: -1}, cap: 1, points: false}], + [{cap: 1, applicant: {balance: 123456789.123, region: "a-b-c", score: 123456789.123, flagged: true, accounts: []}}, {applicant: {accounts: [], balance: 123456789.123, flagged: true, region: "a-b-c", score: 123456789.123}, cap: 1, points: false}], + [{cap: 0, applicant: {balance: 2, region: "x-y", score: 250, flagged: true, accounts: []}}, {applicant: {accounts: [], balance: 2, flagged: true, region: "x-y", score: 250}, cap: 0, points: false}], + [{cap: -2, applicant: {balance: -500, region: "12", score: 250, flagged: true, accounts: []}}, {applicant: {accounts: [], balance: -500, flagged: true, region: "12", score: 250}, cap: -2, points: false}], + [{cap: 0.5, applicant: {balance: 99.99, region: "VIP", score: 2.50, flagged: true, accounts: [{plan: "plus"}, {score: 2.50}]}}, {applicant: {accounts: [{bucket: "VIP", discount: 0, ok: 0, plan: "plus", summary: true}, {bucket: "VIP", discount: 0, ok: 2.50, score: 2.50, summary: true}], balance: 99.99, flagged: true, region: "VIP", score: 2.50}, cap: 0.5, points: false}], + [{cap: 100, applicant: {balance: 0, region: "12", score: -1, flagged: false, accounts: []}}, {applicant: {accounts: [], balance: 0, flagged: false, region: "12", score: -1}, cap: 100, points: false}], + [{cap: 100, applicant: {balance: -1, region: "a", score: 2.50, flagged: false, accounts: [{plan: "trial"}, {}, {score: -500}, {score: null, plan: "premium"}]}}, {applicant: {accounts: [{discount: 2.50, ok: 0, plan: "trial", summary: true}, {discount: 2.50, ok: 0, summary: true}, {discount: 2.50, ok: -500, score: -500, summary: true}, {discount: 2.50, ok: 0, plan: "premium", score: null, summary: true}], balance: -1, flagged: false, region: "a", score: 2.50}, cap: 100, points: false}], + [{cap: 0.5, applicant: {balance: 410, region: " pad ", score: -500, flagged: false, accounts: [{score: 1}, {plan: "basic"}, {score: 123456789.123, plan: "plus"}, {}]}}, {applicant: {accounts: [{discount: -500, ok: 1, score: 1, summary: false}, {discount: -500, ok: 0, plan: "basic", summary: false}, {discount: -500, ok: 123456789.123, plan: "plus", score: 123456789.123, summary: false}, {discount: -500, ok: 0, summary: false}], balance: 410, flagged: false, region: " pad ", score: -500}, cap: 0.5, points: false}], + [{cap: 0.5, applicant: {balance: -0.5, region: "-", score: 2.50, flagged: false, accounts: [{score: 0.5, plan: "premium"}, {score: 1, plan: "premium"}]}}, {applicant: {accounts: [{discount: 2.50, ok: 0.5, plan: "premium", score: 0.5, summary: true}, {discount: 2.50, ok: 1, plan: "premium", score: 1, summary: true}], balance: -0.5, flagged: false, region: "-", score: 2.50}, cap: 0.5, points: false}], + [{cap: 1, applicant: {balance: -1, region: "a-b-c", score: 1, flagged: true, accounts: [{score: 0.000001, plan: "basic"}]}}, {applicant: {accounts: [{bucket: "a-b-c", discount: 1, ok: 0.000001, plan: "basic", score: 0.000001, summary: true}], balance: -1, flagged: true, region: "a-b-c", score: 1}, cap: 1, points: false}], + [{cap: 0.5, applicant: {balance: 65, region: "DE", score: 10, flagged: false, accounts: [], extraField: {nested: true}}}, {applicant: {accounts: [], balance: 65, extraField: {nested: true}, flagged: false, region: "DE", score: 10}, cap: 0.5, points: false}], + [{cap: 100, applicant: {balance: null, region: "-", score: 100, flagged: false, accounts: [{score: 2.50, plan: "plus"}]}}, {applicant: {accounts: [{discount: 100, ok: 2.50, plan: "plus", score: 2.50, summary: true}], balance: null, flagged: false, region: "-", score: 100}, cap: 100, points: false}], + [{cap: 1, applicant: {region: "a", score: 123456789.123, flagged: false, accounts: [{}, {plan: "plus"}, {}, {score: 2.50, plan: "basic"}, {score: 1000, plan: "plus"}]}}, {applicant: {accounts: [{discount: 123456789.123, ok: 0, summary: true}, {discount: 123456789.123, ok: 0, plan: "plus", summary: true}, {discount: 123456789.123, ok: 0, summary: true}, {discount: 123456789.123, ok: 2.50, plan: "basic", score: 2.50, summary: true}, {discount: 123456789.123, ok: 1000, plan: "plus", score: 1000, summary: true}], flagged: false, region: "a", score: 123456789.123}, cap: 1, points: false}], + [{cap: 0.5, applicant: {balance: 99.99, region: "日本", score: -500, flagged: "true", accounts: [{score: 0.5, plan: "plus"}, {score: 18, plan: "basic"}]}}, "!error: InputValidationFailed"], + [{cap: 1, applicant: {balance: null, region: "-", score: 1e3, flagged: true, accounts: [{score: null}, {score: null}, {score: 0.1, plan: "trial"}]}}, {applicant: {accounts: [{discount: 1, ok: 0, score: null, summary: true}, {discount: 1, ok: 0, score: null, summary: true}, {discount: 1, ok: 0.1, plan: "trial", score: 0.1, summary: true}], balance: null, flagged: true, region: "-", score: 1000}, cap: 1, points: false}], + [{cap: 100, applicant: {balance: 26, region: "日本", score: 7.25, flagged: false, accounts: [{plan: "basic"}]}}, {applicant: {accounts: [{discount: 7.25, ok: 0, plan: "basic", summary: true}], balance: 26, flagged: false, region: "日本", score: 7.25}, cap: 100, points: false}], + ], +} + +// seed 332400 (attempt 0) +{ + name: "a 25: customer/members: 1 expression, 3 table; 3 root, 4 per-member, 3 top-level computed", + policy: { + models: {customer: {years: "number", income: "number", vip: "boolean", members: "member[]"}, member: {income: "number", verified: "boolean?"}}, + blocks: [ + {table: "t2", inputs: ["member.income"], outputs: ["member.flag", "member.band", "member.summary"], rules: [ + ["", "(customer.vip ? 'a' : 'A1')", "customer.years", "member.income"], + ["< 3", "string(customer.income)", "1.5", ""], + ["< 0.5", "string(customer.years)", "", ""], + ["", "'A1'", "1", "sum(map(customer.members, #.income))"], + ["0.5", "(customer.vip ? 'none' : 'low')", "member.income", "customer.income"], + ["!= 5", "'retail'", "customer.years", "member.income"], + ]}, + {expression: "member.quota", value: "(member.band == null and member.verified == null)"}, + {table: "t1", hit: "collect", inputs: ["customer.years"], outputs: ["customer.rank", "customer.segment", "customer.surcharge"], rules: [ + ["", "'retail'", "customer.vip", "0"], + ["", "string(customer.income)", "(customer.vip and customer.vip)", "customer.years"], + ["", "", "not (customer.vip)", "sum(map(customer.members, #.income))"], + ["", "'high'", "(customer.vip or customer.vip)", "0"], + ["!= 1.5", "'none'", "customer.vip", "customer.years"], + ["", "string(customer.income)", "customer.vip", "customer.years"], + ]}, + {table: "t4", inputs: [null], outputs: ["adjusted", "bonus", "eligible"], rules: [ + ["not (customer.vip)", "customer.income", "'low'", "customer.years"], + ["(customer.vip and customer.vip)", "customer.income", "'US'", "customer.income"], + ["", "sum(map(customer.members, (#.summary ?? 0)))", "'high'", ""], + ["", "customer.years", "string(customer.income)", "(customer.income - customer.income)"], + ["(customer.vip or customer.vip)", "customer.years", "'retail'", "customer.income"], + ["customer.years >= customer.years", "customer.years", "'Oslo'", "len(customer.segment)"], + ["customer.income != customer.income", "customer.income", "'ok'", "customer.years"], + ]}, + ], + }, + cases: [ + [{customer: {years: 0.5, income: -0.01, vip: false, members: [{income: 2, verified: null}]}}, {adjusted: -0.01, bonus: "low", customer: {income: -0.01, members: [{band: 0.5, flag: "A1", income: 2, quota: false, summary: 2, verified: null}], rank: ["retail", "-0.01", "high", "none", "-0.01"], segment: [false, false, true, false, false, false], surcharge: [0, 0.5, 2, 0, 0.5, 0.5], vip: false, years: 0.5}, eligible: 0.5}], + [{customer: {years: 5, income: 250, vip: true, members: []}}, {adjusted: 250, bonus: "US", customer: {income: 250, members: [], rank: ["retail", "250", "high", "none", "250"], segment: [true, true, false, true, true, true], surcharge: [0, 5, 0, 0, 5, 5], vip: true, years: 5}, eligible: 250}], + [{customer: {years: 99.99, income: 1.5, vip: false, members: [{income: [1], verified: true}]}}, "!error: InputValidationFailed"], + [{customer: {years: 2.50, income: 1, vip: true, members: [{income: 1000, verified: false}, {income: 100, verified: false}, {income: 99.99, verified: true}, {income: -0, verified: true}, {income: 0.5, verified: true}]}}, {adjusted: 1, bonus: "US", customer: {income: 1, members: [{band: 2.50, flag: "a", income: 1000, quota: false, summary: 1000, verified: false}, {band: 2.50, flag: "a", income: 100, quota: false, summary: 100, verified: false}, {band: 2.50, flag: "a", income: 99.99, quota: false, summary: 99.99, verified: true}, {band: 2.50, flag: "a", income: 0, quota: false, summary: 0, verified: true}, {band: 2.50, flag: "a", income: 0.5, quota: false, summary: 0.5, verified: true}], rank: ["retail", "1", "high", "none", "1"], segment: [true, true, false, true, true, true], surcharge: [0, 2.50, 1200.49, 0, 2.50, 2.50], vip: true, years: 2.50}, eligible: 1}], + [{customer: {years: 10, income: 0.5, vip: false, members: [{income: 2, verified: null}, {income: 123456789.123}, {income: 1, verified: null}, {income: 0, verified: false}, {income: 100, verified: false}]}}, {adjusted: 0.5, bonus: "low", customer: {income: 0.5, members: [{band: 10, flag: "A1", income: 2, quota: false, summary: 2, verified: null}, {band: 10, flag: "A1", income: 123456789.123, quota: false, summary: 123456789.123}, {band: 10, flag: "A1", income: 1, quota: false, summary: 1, verified: null}, {band: 10, flag: "A1", income: 0, quota: false, summary: 0, verified: false}, {band: 10, flag: "A1", income: 100, quota: false, summary: 100, verified: false}], rank: ["retail", "0.5", "high", "none", "0.5"], segment: [false, false, true, false, false, false], surcharge: [0, 10, 123456892.123, 0, 10, 10], vip: false, years: 10}, eligible: 10}], + [{customer: {years: -0.01, income: 3, vip: true, members: [{income: 1000}, {income: 1.5, verified: null}, {income: -0, verified: true}, {income: 100, verified: false}]}}, {adjusted: 3, bonus: "US", customer: {income: 3, members: [{band: -0.01, flag: "a", income: 1000, quota: false, summary: 1000}, {band: -0.01, flag: "a", income: 1.5, quota: false, summary: 1.5, verified: null}, {band: -0.01, flag: "a", income: 0, quota: false, summary: 0, verified: true}, {band: -0.01, flag: "a", income: 100, quota: false, summary: 100, verified: false}], rank: ["retail", "3", "high", "none", "3"], segment: [true, true, false, true, true, true], surcharge: [0, -0.01, 1101.5, 0, -0.01, -0.01], vip: true, years: -0.01}, eligible: 3}], + [{customer: {years: 1, income: 65, vip: true, members: [{income: 0, verified: true}, {income: 65}, {income: 18, verified: null}, {income: -0, verified: true}]}}, {adjusted: 65, bonus: "US", customer: {income: 65, members: [{band: 1, flag: "a", income: 0, quota: false, summary: 0, verified: true}, {band: 1, flag: "a", income: 65, quota: false, summary: 65}, {band: 1, flag: "a", income: 18, quota: false, summary: 18, verified: null}, {band: 1, flag: "a", income: 0, quota: false, summary: 0, verified: true}], rank: ["retail", "65", "high", "none", "65"], segment: [true, true, false, true, true, true], surcharge: [0, 1, 83, 0, 1, 1], vip: true, years: 1}, eligible: 65}], + [{customer: {years: 18, income: 99.99, vip: false, members: []}}, {adjusted: 99.99, bonus: "low", customer: {income: 99.99, members: [], rank: ["retail", "99.99", "high", "none", "99.99"], segment: [false, false, true, false, false, false], surcharge: [0, 18, 0, 0, 18, 18], vip: false, years: 18}, eligible: 18}], + [{customer: {years: 250, income: 100, vip: true, members: [{income: -500, verified: true}, {income: 0.1, verified: false}]}}, {adjusted: 100, bonus: "US", customer: {income: 100, members: [{band: 250, flag: "a", income: -500, quota: false, summary: -500, verified: true}, {band: 250, flag: "a", income: 0.1, quota: false, summary: 0.1, verified: false}], rank: ["retail", "100", "high", "none", "100"], segment: [true, true, false, true, true, true], surcharge: [0, 250, -499.9, 0, 250, 250], vip: true, years: 250}, eligible: 100}], + [{customer: {years: 2.50, income: 0, vip: true, members: [{income: 2, verified: true}, {income: -1, verified: false}, {income: 0, verified: false}]}}, {adjusted: 0, bonus: "US", customer: {income: 0, members: [{band: 2.50, flag: "a", income: 2, quota: false, summary: 2, verified: true}, {band: 2.50, flag: "a", income: -1, quota: false, summary: -1, verified: false}, {band: 2.50, flag: "a", income: 0, quota: false, summary: 0, verified: false}], rank: ["retail", "0", "high", "none", "0"], segment: [true, true, false, true, true, true], surcharge: [0, 2.50, 1, 0, 2.50, 2.50], vip: true, years: 2.50}, eligible: 0}], + [{customer: {years: 0, income: 3, vip: false, members: []}}, {adjusted: 3, bonus: "low", customer: {income: 3, members: [], rank: ["retail", "3", "high", "none", "3"], segment: [false, false, true, false, false, false], surcharge: [0, 0, 0, 0, 0, 0], vip: false, years: 0}, eligible: 0}], + [{customer: {years: 1000000, income: 100, vip: true, members: [{income: 412}, {income: 1e3, verified: false}]}}, {adjusted: 100, bonus: "US", customer: {income: 100, members: [{band: 1000000, flag: "a", income: 412, quota: false, summary: 412}, {band: 1000000, flag: "a", income: 1000, quota: false, summary: 1000, verified: false}], rank: ["retail", "100", "high", "none", "100"], segment: [true, true, false, true, true, true], surcharge: [0, 1000000, 1412, 0, 1000000, 1000000], vip: true, years: 1000000}, eligible: 100}], + [{customer: {years: 2, income: 0.5, vip: true, members: [{income: 1000, verified: false}, {income: 0.5, verified: true}, {income: 1, verified: false}, {income: 1, verified: true}, {income: 1.5, verified: false}]}}, {adjusted: 0.5, bonus: "US", customer: {income: 0.5, members: [{band: 2, flag: "a", income: 1000, quota: false, summary: 1000, verified: false}, {band: 2, flag: "a", income: 0.5, quota: false, summary: 0.5, verified: true}, {band: 2, flag: "a", income: 1, quota: false, summary: 1, verified: false}, {band: 2, flag: "a", income: 1, quota: false, summary: 1, verified: true}, {band: 2, flag: "a", income: 1.5, quota: false, summary: 1.5, verified: false}], rank: ["retail", "0.5", "high", "none", "0.5"], segment: [true, true, false, true, true, true], surcharge: [0, 2, 1004.0, 0, 2, 2], vip: true, years: 2}, eligible: 0.5}], + [{customer: {years: -500, income: 18, vip: true, members: [{income: 5, verified: true}, {income: 5, verified: null}, {income: 2, verified: true}, {income: 1.5, verified: null}, {income: 18, verified: true}]}}, {adjusted: 18, bonus: "US", customer: {income: 18, members: [{band: -500, flag: "a", income: 5, quota: false, summary: 5, verified: true}, {band: -500, flag: "a", income: 5, quota: false, summary: 5, verified: null}, {band: -500, flag: "a", income: 2, quota: false, summary: 2, verified: true}, {band: -500, flag: "a", income: 1.5, quota: false, summary: 1.5, verified: null}, {band: -500, flag: "a", income: 18, quota: false, summary: 18, verified: true}], rank: ["retail", "18", "high", "none", "18"], segment: [true, true, false, true, true, true], surcharge: [0, -500, 31.5, 0, -500, -500], vip: true, years: -500}, eligible: 18}], + [{customer: {years: -500, income: 1, vip: false, members: [{income: 2, verified: false}, {income: 5, verified: true}, {income: 0.5}, {income: 250, verified: true}, {income: 100}]}}, {adjusted: 1, bonus: "low", customer: {income: 1, members: [{band: -500, flag: "A1", income: 2, quota: false, summary: 2, verified: false}, {band: -500, flag: "A1", income: 5, quota: false, summary: 5, verified: true}, {band: -500, flag: "A1", income: 0.5, quota: false, summary: 0.5}, {band: -500, flag: "A1", income: 250, quota: false, summary: 250, verified: true}, {band: -500, flag: "A1", income: 100, quota: false, summary: 100}], rank: ["retail", "1", "high", "none", "1"], segment: [false, false, true, false, false, false], surcharge: [0, -500, 357.5, 0, -500, -500], vip: false, years: -500}, eligible: -500}], + [{customer: {years: 100, income: 5, vip: true, members: [{income: 18, verified: null}, {income: 18, verified: true}]}}, {adjusted: 5, bonus: "US", customer: {income: 5, members: [{band: 100, flag: "a", income: 18, quota: false, summary: 18, verified: null}, {band: 100, flag: "a", income: 18, quota: false, summary: 18, verified: true}], rank: ["retail", "5", "high", "none", "5"], segment: [true, true, false, true, true, true], surcharge: [0, 100, 36, 0, 100, 100], vip: true, years: 100}, eligible: 5}], + ], +} + +// seed 332500 (attempt 0) +{ + name: "a 26: account/lines: 2 assertion, 1 expression, 3 match, 2 table; 6 root, 2 per-member, 2 top-level computed", + policy: { + models: {account: {income: "number", label: "string", priority: "boolean", vip: "boolean", lines: "line[]"}, line: {price: "number", channel: "string", openedAt: "date", verified: "boolean"}}, + blocks: [ + {assertion: "account.bonus", conditions: [["or", "startsWith((account.health ? 'Oslo' : account.label), 'VIP')", 0], ["and", "account.surcharge <= account.adjusted", 0], ["or", "not (account.health)", 1]]}, + {table: "t4", hit: "collect", inputs: ["account.surcharge"], outputs: ["account.fee", "account.review"], rules: [ + ["", "account.label", "account.income"], + ["!= 2", "account.label", "account.income"], + [">= 3", "account.label", "(account.priority ? account.surcharge : account.surcharge)"], + ["[1..291]", "account.label", ""], + ["", "account.label", "(account.surcharge + account.surcharge)"], + ]}, + {table: "t1", inputs: ["(max(map(account.lines, 0)) ?? 0)", "account.label"], outputs: ["total[]", "margin[]"], rules: [ + ["<= 1000", "", "account.vip", "account.vip"], + ["", "'Oslo'", "account.vip", "account.priority"], + ]}, + {assertion: "account.health", conditions: [["and", "(account.income == account.surcharge and account.surcharge == account.surcharge)", 1]]}, + {match: "line.share", arms: [["some(account.lines, #.price > 0.5)", "len(margin)"], ["", "floor(line.price)"]]}, + {match: "line.tag", arms: [["line.channel == 'gold'", "account.label"], ["line.openedAt >= d('2024-01-01')", "line.channel"], ["", "'none'"]]}, + {match: "account.adjusted", arms: [["not (account.vip)", "(account.surcharge - account.surcharge)"], ["", "account.surcharge"]]}, + {expression: "account.surcharge", value: "len(total)"}, + ], + }, + cases: [ + [{account: {income: -1, label: "VIP", priority: true, vip: true, lines: [{price: 99.99, channel: "x-y", openedAt: "2025-03-20T10:15:30Z", verified: false}, {price: 1000, channel: "abc", openedAt: "2024-01-01", verified: true}]}}, {account: {adjusted: 1, bonus: true, fee: ["VIP", "VIP", "VIP", "VIP"], health: false, income: -1, label: "VIP", lines: [{channel: "x-y", openedAt: "2025-03-20T10:15:30Z", price: 99.99, share: 1, tag: "x-y", verified: false}, {channel: "abc", openedAt: "2024-01-01", price: 1000, share: 1, tag: "abc", verified: true}], priority: true, review: [-1, -1, 2], surcharge: 1, vip: true}, margin: [true], total: [true]}], + [{account: {income: 2, label: "abc", priority: true, vip: false, lines: []}}, "!error: ExpressionFailed"], + [{account: {income: 2, label: "Zed", priority: false, vip: true, lines: []}}, "!error: ExpressionFailed"], + [{account: {income: 0.5, label: "Oslo", priority: true, vip: true, lines: [{price: 100, channel: "O'Neil", openedAt: "2000-01-01", verified: true}, {price: 2.50, channel: "é ü", openedAt: "2024-01-01", verified: true}]}}, {account: {adjusted: 2, bonus: true, fee: ["Oslo", "Oslo", "Oslo"], health: false, income: 0.5, label: "Oslo", lines: [{channel: "O'Neil", openedAt: "2000-01-01", price: 100, share: 2, tag: "none", verified: true}, {channel: "é ü", openedAt: "2024-01-01", price: 2.50, share: 2, tag: "é ü", verified: true}], priority: true, review: [0.5, 4], surcharge: 2, vip: true}, margin: [true, true], total: [true, true]}], + [{account: {income: 0.000001, label: "a", priority: false, vip: false, lines: [{price: -1, channel: "gold", openedAt: "2030-12-31", verified: false}, {price: 2, channel: "A1", openedAt: "2030-12-31", verified: false}], extraField: {nested: true}}}, {account: {adjusted: 0, bonus: false, extraField: {nested: true}, fee: ["a", "a", "a", "a"], health: false, income: 0.000001, label: "a", lines: [{channel: "gold", openedAt: "2030-12-31", price: -1, share: 1, tag: "a", verified: false}, {channel: "A1", openedAt: "2030-12-31", price: 2, share: 1, tag: "A1", verified: false}], priority: false, review: [0.000001, 0.000001, 2], surcharge: 1, vip: false}, margin: [false], total: [false]}], + [{account: {income: -0, label: "Oslo", priority: true, vip: false, lines: [{price: -1, channel: "12", openedAt: "2024-02-29", verified: true}]}}, {account: {adjusted: 0, bonus: false, fee: ["Oslo", "Oslo", "Oslo"], health: false, income: 0, label: "Oslo", lines: [{channel: "12", openedAt: "2024-02-29", price: -1, share: -1, tag: "12", verified: true}], priority: true, review: [0, 4], surcharge: 2, vip: false}, margin: [false, true], total: [false, false]}], + [{account: {income: 99999999999999999999, label: "A1", priority: false, vip: true, lines: []}}, "!error: ExpressionFailed"], + [{account: {income: -500, label: "abc", priority: true, vip: false, lines: []}}, "!error: ExpressionFailed"], + [{account: {income: 2.50, label: "", priority: false, vip: true, lines: [{price: 100, channel: " pad ", openedAt: "2025-03-20T10:15:30Z", verified: true}]}}, {account: {adjusted: 1, bonus: true, fee: ["", "", "", ""], health: false, income: 2.50, label: "", lines: [{channel: " pad ", openedAt: "2025-03-20T10:15:30Z", price: 100, share: 1, tag: " pad ", verified: true}], priority: false, review: [2.50, 2.50, 2], surcharge: 1, vip: true}, margin: [true], total: [true]}], + [{account: {income: 2, label: "a-b-c", priority: true, vip: false, lines: [{price: 0.1, channel: "VIP", openedAt: "2024-01-01", verified: true}, {price: 71, channel: "VIP", openedAt: "2025-03-20T10:15:30Z", verified: true}]}}, {account: {adjusted: 0, bonus: false, fee: ["a-b-c", "a-b-c", "a-b-c", "a-b-c"], health: false, income: 2, label: "a-b-c", lines: [{channel: "VIP", openedAt: "2024-01-01", price: 0.1, share: 1, tag: "VIP", verified: true}, {channel: "VIP", openedAt: "2025-03-20T10:15:30Z", price: 71, share: 1, tag: "VIP", verified: true}], priority: true, review: [2, 2, 2], surcharge: 1, vip: false}, margin: [false], total: [false]}], + [{account: {income: 100, label: "-", priority: true, vip: true, lines: [{price: 1, channel: "a", openedAt: "1990-06-15", verified: true}, {price: -1, channel: "US", openedAt: "2025-03-20T10:15:30Z", verified: true}, {price: -0.5, channel: "A1", openedAt: "2024-02-29", verified: true}, {price: -500, channel: "3.5", openedAt: "2024-01-01", verified: true}, {price: 100, channel: "é ü", openedAt: "2025-03-20", verified: false}], extraField: "x"}}, {account: {adjusted: 1, bonus: true, extraField: "x", fee: ["-", "-", "-", "-"], health: false, income: 100, label: "-", lines: [{channel: "a", openedAt: "1990-06-15", price: 1, share: 1, tag: "none", verified: true}, {channel: "US", openedAt: "2025-03-20T10:15:30Z", price: -1, share: 1, tag: "US", verified: true}, {channel: "A1", openedAt: "2024-02-29", price: -0.5, share: 1, tag: "A1", verified: true}, {channel: "3.5", openedAt: "2024-01-01", price: -500, share: 1, tag: "3.5", verified: true}, {channel: "é ü", openedAt: "2025-03-20", price: 100, share: 1, tag: "é ü", verified: false}], priority: true, review: [100, 100, 2], surcharge: 1, vip: true}, margin: [true], total: [true]}], + [{account: {income: 1000, label: "3.5", priority: true, vip: true, lines: []}}, "!error: ExpressionFailed"], + [{account: {income: 0.5, label: "A1", priority: false, vip: true, lines: [{price: 3, channel: "gold", openedAt: "2024-02-29", verified: false}, {price: 0.1, channel: "retail", openedAt: "2024-01-01", verified: false}, {price: 1e3, channel: "abc", openedAt: "2024-02-29", verified: false}, {price: 0.5, channel: "O'Neil", openedAt: "2024-02-29", verified: false}]}}, {account: {adjusted: 1, bonus: true, fee: ["A1", "A1", "A1", "A1"], health: false, income: 0.5, label: "A1", lines: [{channel: "gold", openedAt: "2024-02-29", price: 3, share: 1, tag: "A1", verified: false}, {channel: "retail", openedAt: "2024-01-01", price: 0.1, share: 1, tag: "retail", verified: false}, {channel: "abc", openedAt: "2024-02-29", price: 1000, share: 1, tag: "abc", verified: false}, {channel: "O'Neil", openedAt: "2024-02-29", price: 0.5, share: 1, tag: "O'Neil", verified: false}], priority: false, review: [0.5, 0.5, 2], surcharge: 1, vip: true}, margin: [true], total: [true]}], + [{account: {income: 0.5, label: "Oslo", priority: false, vip: false, lines: []}}, "!error: ExpressionFailed"], + [{account: {income: 7.25, label: "VIP", priority: false, vip: false, lines: []}}, "!error: ExpressionFailed"], + [{account: {income: 1, label: "O'Neil", priority: true, vip: false, lines: [{price: -0, channel: "abc", openedAt: "2025-03-20", verified: true}, {price: 0.5, channel: "Oslo", openedAt: "2025-03-20T10:15:30Z", verified: true}, {price: 65, channel: "A1", openedAt: "2030-12-31", verified: true}, {price: 18, channel: "x-y", openedAt: "2024-02-29", verified: false}]}}, {account: {adjusted: 0, bonus: false, fee: ["O'Neil", "O'Neil", "O'Neil", "O'Neil"], health: true, income: 1, label: "O'Neil", lines: [{channel: "abc", openedAt: "2025-03-20", price: 0, share: 1, tag: "abc", verified: true}, {channel: "Oslo", openedAt: "2025-03-20T10:15:30Z", price: 0.5, share: 1, tag: "Oslo", verified: true}, {channel: "A1", openedAt: "2030-12-31", price: 65, share: 1, tag: "A1", verified: true}, {channel: "x-y", openedAt: "2024-02-29", price: 18, share: 1, tag: "x-y", verified: false}], priority: true, review: [1, 1, 2], surcharge: 1, vip: false}, margin: [false], total: [false]}], + [{account: {income: -1, label: "A1", priority: true, vip: false, lines: [{price: 1000, channel: "-", openedAt: "2024-02-29", verified: true}, {price: 65, channel: "VIP", openedAt: "2000-01-01", verified: true}, {price: 10, channel: "日本", openedAt: "2025-03-20T10:15:30Z", verified: false}, {price: 123456789.123, channel: "Oslo", openedAt: "2025-03-20T10:15:30Z", verified: false}]}}, {account: {adjusted: 0, bonus: false, fee: ["A1", "A1", "A1", "A1"], health: false, income: -1, label: "A1", lines: [{channel: "-", openedAt: "2024-02-29", price: 1000, share: 1, tag: "-", verified: true}, {channel: "VIP", openedAt: "2000-01-01", price: 65, share: 1, tag: "none", verified: true}, {channel: "日本", openedAt: "2025-03-20T10:15:30Z", price: 10, share: 1, tag: "日本", verified: false}, {channel: "Oslo", openedAt: "2025-03-20T10:15:30Z", price: 123456789.123, share: 1, tag: "Oslo", verified: false}], priority: true, review: [-1, -1, 2], surcharge: 1, vip: false}, margin: [false], total: [false]}], + [{account: {income: -0.5, label: "12", priority: true, vip: true, lines: []}}, "!error: ExpressionFailed"], + [{account: {income: 100, label: "x-y", priority: false, vip: true, lines: [{price: -0.5, channel: "NL", openedAt: "2025-03-20T10:15:30Z", verified: true}, {price: 2, channel: "NL", openedAt: "2024-02-29", verified: false}, {price: 99.99, channel: "none", openedAt: "2024-01-01", verified: false}]}}, {account: {adjusted: 1, bonus: true, fee: ["x-y", "x-y", "x-y", "x-y"], health: false, income: 100, label: "x-y", lines: [{channel: "NL", openedAt: "2025-03-20T10:15:30Z", price: -0.5, share: 1, tag: "NL", verified: true}, {channel: "NL", openedAt: "2024-02-29", price: 2, share: 1, tag: "NL", verified: false}, {channel: "none", openedAt: "2024-01-01", price: 99.99, share: 1, tag: "none", verified: false}], priority: false, review: [100, 100, 2], surcharge: 1, vip: true}, margin: [true], total: [true]}], + [{account: {income: 123456789.123, label: "VIP", priority: false, vip: false, lines: [{price: 99999999999999999999, channel: "", openedAt: "1990-06-15", verified: true}, {price: 406, channel: "-", openedAt: "2000-01-01", verified: true}, {price: -500, channel: "Oslo", openedAt: "2024-01-01", verified: true}]}}, {account: {adjusted: 0, bonus: true, fee: ["VIP", "VIP", "VIP", "VIP"], health: false, income: 123456789.123, label: "VIP", lines: [{channel: "", openedAt: "1990-06-15", price: 99999999999999999999, share: 1, tag: "none", verified: true}, {channel: "-", openedAt: "2000-01-01", price: 406, share: 1, tag: "none", verified: true}, {channel: "Oslo", openedAt: "2024-01-01", price: -500, share: 1, tag: "Oslo", verified: true}], priority: false, review: [123456789.123, 123456789.123, 2], surcharge: 1, vip: false}, margin: [false], total: [false]}], + ], +} + +// seed 332600 (attempt 0) +{ + name: "a 27: applicant/items: 2 assertion, 1 expression, 3 match, 1 table; 3 root, 4 per-member, 2 top-level computed", + policy: { + models: {applicant: {years: "number?", flagged: "boolean?", qty: "number", tier: "string(gold|silver|bronze)?", items: "item[]"}, item: {days: "number", income: "number?", vip: "boolean?", active: "boolean"}}, + blocks: [ + {match: "applicant.quota", arms: [["applicant.flagged == null", "bucket"], ["all(applicant.items, #.vip == null)", "bucket"], ["bucket == 'high'", "((applicant.tier ?? '') in ['gold', 'silver'] ? bucket : bucket)"], ["applicant.years == null", "bucket"], ["", "'x'"]]}, + {assertion: "applicant.exposure", conditions: [["or", "applicant.years != null", 1], ["or", "(all(applicant.items, ((#.vip ?? false) and (#.vip ?? false))) or all(applicant.items, not (#.active)))", 1], ["or", "(applicant.weighted and health)", 2], ["and", "((applicant.flagged ?? false) ? bucket : 'retail') == 'gold'", 0]]}, + {match: "item.review", arms: [["(all(applicant.items, (#.active or (#.vip ?? false))) and some(applicant.items, ((#.vip ?? false) or (#.vip ?? false))))", "string(applicant.qty)"], ["(applicant.years ?? 0) == item.days", "'VIP'"], ["(applicant.tier ?? '') == 'bronze'", "string(applicant.qty)"], ["", "'US'"]]}, + {expression: "health", value: "len(bucket) >= applicant.qty"}, + {assertion: "applicant.weighted", conditions: [["or", "all(applicant.items, #.days >= (#.income ?? 0))", 0], ["or", "((applicant.flagged ?? false) or (applicant.flagged ?? false))", 2], ["or", "applicant.qty < (applicant.years ?? 0)", 2]]}, + {match: "bucket", arms: [["((applicant.flagged ?? false) or (applicant.flagged ?? false))", "string((applicant.years ?? 0))"], ["all(applicant.items, (#.income ?? 0) == 50)", "((applicant.flagged ?? false) ? 'retail' : 'DE')"], ["applicant.qty == (applicant.years ?? 0)", "string((applicant.years ?? 0))"], ["", "string((applicant.years ?? 0))"]]}, + {table: "t4", hit: "collect", inputs: ["applicant.flagged"], outputs: ["item.discount", "item.net", "item.margin"], rules: [ + ["false", "'high'", "item.days", "(item.income ?? 0)"], + ["false", "bucket", "applicant.qty", "(applicant.years ?? 0)"], + ["true", "(item.review + '-' + item.review)", "item.days", "0"], + ["", "item.review", "applicant.qty", "applicant.qty"], + ["", "'VIP'", "((item.vip ?? false) ? applicant.qty : item.days)", "applicant.qty"], + ]}, + ], + }, + cases: [ + [{applicant: {years: 1000000, flagged: null, qty: 139, tier: "gold", items: [{days: -1, vip: false, active: false}, {days: 250, vip: null, active: false}, {days: 7.25, income: 2, vip: null, active: true}, {days: 50, vip: false, active: false}, {days: 18, income: 7.25, active: false}]}}, {applicant: {exposure: true, flagged: null, items: [{active: false, days: -1, discount: ["US", "VIP"], margin: [139, 139], net: [139, -1], review: "US", vip: false}, {active: false, days: 250, discount: ["US", "VIP"], margin: [139, 139], net: [139, 250], review: "US", vip: null}, {active: true, days: 7.25, discount: ["US", "VIP"], income: 2, margin: [139, 139], net: [139, 7.25], review: "US", vip: null}, {active: false, days: 50, discount: ["US", "VIP"], margin: [139, 139], net: [139, 50], review: "US", vip: false}, {active: false, days: 18, discount: ["US", "VIP"], income: 7.25, margin: [139, 139], net: [139, 18], review: "US"}], qty: 139, quota: "1000000", tier: "gold", weighted: true, years: 1000000}, bucket: "1000000", health: false}], + [{applicant: {years: 0.1, qty: 2.50, tier: "gold", items: [{days: 10, active: true}, {days: 5, vip: true, active: false}]}}, {applicant: {exposure: true, items: [{active: true, days: 10, discount: ["2.50", "VIP"], margin: [2.50, 2.50], net: [2.50, 10], review: "2.50"}, {active: false, days: 5, discount: ["2.50", "VIP"], margin: [2.50, 2.50], net: [2.50, 2.50], review: "2.50", vip: true}], qty: 2.50, quota: "0.1", tier: "gold", weighted: true, years: 0.1}, bucket: "0.1", health: true}], + [{applicant: {years: null, flagged: null, qty: 1000000, tier: null, items: [{days: 10, income: null, active: true}, {days: 99.99, income: null, vip: false, active: false}]}}, {applicant: {exposure: false, flagged: null, items: [{active: true, days: 10, discount: ["US", "VIP"], income: null, margin: [1000000, 1000000], net: [1000000, 10], review: "US"}, {active: false, days: 99.99, discount: ["US", "VIP"], income: null, margin: [1000000, 1000000], net: [1000000, 99.99], review: "US", vip: false}], qty: 1000000, quota: "0", tier: null, weighted: true, years: null}, bucket: "0", health: false}], + [{applicant: {qty: 0, tier: "bronze", items: [{days: 0.1, active: false}, {days: 2.50, active: false}]}}, {applicant: {exposure: true, items: [{active: false, days: 0.1, discount: ["0", "VIP"], margin: [0, 0], net: [0, 0.1], review: "0"}, {active: false, days: 2.50, discount: ["0", "VIP"], margin: [0, 0], net: [0, 2.50], review: "0"}], qty: 0, quota: "0", tier: "bronze", weighted: true}, bucket: "0", health: true}], + [{applicant: {years: 99999999999999999999, flagged: true, qty: 10, tier: "silver", items: [{days: 0, income: 99999999999999999999, vip: false, active: true}, {days: -0, income: 100, vip: true, active: false}, {days: 18, income: 99.99, vip: true, active: true}, {days: 2.50, income: 272, vip: true, active: false}, {days: -500, income: -0, vip: false, active: true}], extraField: {nested: true}}}, {applicant: {exposure: true, extraField: {nested: true}, flagged: true, items: [{active: true, days: 0, discount: ["10-10", "10", "VIP"], income: 99999999999999999999, margin: [0, 10, 10], net: [0, 10, 0], review: "10", vip: false}, {active: false, days: 0, discount: ["10-10", "10", "VIP"], income: 100, margin: [0, 10, 10], net: [0, 10, 10], review: "10", vip: true}, {active: true, days: 18, discount: ["10-10", "10", "VIP"], income: 99.99, margin: [0, 10, 10], net: [18, 10, 10], review: "10", vip: true}, {active: false, days: 2.50, discount: ["10-10", "10", "VIP"], income: 272, margin: [0, 10, 10], net: [2.50, 10, 10], review: "10", vip: true}, {active: true, days: -500, discount: ["10-10", "10", "VIP"], income: 0, margin: [0, 10, 10], net: [-500, 10, -500], review: "10", vip: false}], qty: 10, quota: "x", tier: "silver", weighted: true, years: 99999999999999999999}, bucket: "99999999999999999999", health: true}], + [{applicant: {years: 50, flagged: true, qty: 0.1, tier: "gold", items: [{days: 0.000001, income: 250, vip: false, active: true}, {days: 38, income: -0.01, vip: true, active: false}, {days: 7.25, income: 0.1, vip: false, active: false}]}}, {applicant: {exposure: true, flagged: true, items: [{active: true, days: 0.000001, discount: ["US-US", "US", "VIP"], income: 250, margin: [0, 0.1, 0.1], net: [0.000001, 0.1, 0.000001], review: "US", vip: false}, {active: false, days: 38, discount: ["US-US", "US", "VIP"], income: -0.01, margin: [0, 0.1, 0.1], net: [38, 0.1, 0.1], review: "US", vip: true}, {active: false, days: 7.25, discount: ["US-US", "US", "VIP"], income: 0.1, margin: [0, 0.1, 0.1], net: [7.25, 0.1, 7.25], review: "US", vip: false}], qty: 0.1, quota: "x", tier: "gold", weighted: true, years: 50}, bucket: "50", health: true}], + [{applicant: {years: -0.01, flagged: false, qty: 65, tier: "bronze", items: [{days: 1, income: -500, vip: true, active: false}]}}, {applicant: {exposure: true, flagged: false, items: [{active: false, days: 1, discount: ["high", "-0.01", "65", "VIP"], income: -500, margin: [-500, -0.01, 65, 65], net: [1, 65, 65, 65], review: "65", vip: true}], qty: 65, quota: "x", tier: "bronze", weighted: true, years: -0.01}, bucket: "-0.01", health: false}], + [{applicant: {years: -500, flagged: false, qty: 250, tier: "gold", items: [{days: 18, income: 7.25, vip: true, active: false}]}}, {applicant: {exposure: true, flagged: false, items: [{active: false, days: 18, discount: ["high", "-500", "250", "VIP"], income: 7.25, margin: [7.25, -500, 250, 250], net: [18, 250, 250, 250], review: "250", vip: true}], qty: 250, quota: "x", tier: "gold", weighted: true, years: -500}, bucket: "-500", health: false}], + [{applicant: {years: 18, flagged: true, qty: 18, tier: "gold", items: []}}, {applicant: {exposure: true, flagged: true, items: [], qty: 18, quota: "18", tier: "gold", weighted: true, years: 18}, bucket: "18", health: false}], + [{applicant: {years: 0, qty: 18, items: []}}, {applicant: {exposure: true, items: [], qty: 18, quota: "DE", weighted: true, years: 0}, bucket: "DE", health: false}], + [{applicant: {years: -0, flagged: true, qty: 1000000, tier: "gold", items: [{days: 7.25, income: 0.5, vip: false, active: true}]}}, {applicant: {exposure: true, flagged: true, items: [{active: true, days: 7.25, discount: ["US-US", "US", "VIP"], income: 0.5, margin: [0, 1000000, 1000000], net: [7.25, 1000000, 7.25], review: "US", vip: false}], qty: 1000000, quota: "x", tier: "gold", weighted: true, years: 0}, bucket: "0", health: false}], + [{applicant: {years: "12", flagged: false, qty: 0.1, tier: "bronze", items: [{days: 65, income: 1000000, vip: false, active: true}, {days: 5, income: 1, vip: true, active: false}]}}, "!error: InputValidationFailed"], + [{applicant: {years: 5, flagged: true, qty: 1, tier: "gold", items: [{days: -0.5, income: -500, vip: false, active: false}, {days: 2, income: -1, vip: true, active: false}, {days: -1, income: 50, vip: false, active: true}, {days: 1e3, income: 0.1, vip: false, active: false}, {days: 2, income: 18, vip: true, active: false}]}}, {applicant: {exposure: true, flagged: true, items: [{active: false, days: -0.5, discount: ["US-US", "US", "VIP"], income: -500, margin: [0, 1, 1], net: [-0.5, 1, -0.5], review: "US", vip: false}, {active: false, days: 2, discount: ["US-US", "US", "VIP"], income: -1, margin: [0, 1, 1], net: [2, 1, 1], review: "US", vip: true}, {active: true, days: -1, discount: ["US-US", "US", "VIP"], income: 50, margin: [0, 1, 1], net: [-1, 1, -1], review: "US", vip: false}, {active: false, days: 1000, discount: ["US-US", "US", "VIP"], income: 0.1, margin: [0, 1, 1], net: [1000, 1, 1000], review: "US", vip: false}, {active: false, days: 2, discount: ["US-US", "US", "VIP"], income: 18, margin: [0, 1, 1], net: [2, 1, 1], review: "US", vip: true}], qty: 1, quota: "x", tier: "gold", weighted: true, years: 5}, bucket: "5", health: true}], + [{applicant: {years: null, flagged: null, qty: 99.99, tier: null, items: [{days: 99999999999999999999, income: 65, vip: null, active: false}, {days: -0, income: 5, vip: null, active: false}, {days: 0.5, income: 18, vip: null, active: false}, {days: 65, income: 0, active: false}, {days: 1, income: null, vip: null, active: true}]}}, {applicant: {exposure: false, flagged: null, items: [{active: false, days: 99999999999999999999, discount: ["US", "VIP"], income: 65, margin: [99.99, 99.99], net: [99.99, 99999999999999999999], review: "US", vip: null}, {active: false, days: 0, discount: ["VIP", "VIP"], income: 5, margin: [99.99, 99.99], net: [99.99, 0], review: "VIP", vip: null}, {active: false, days: 0.5, discount: ["US", "VIP"], income: 18, margin: [99.99, 99.99], net: [99.99, 0.5], review: "US", vip: null}, {active: false, days: 65, discount: ["US", "VIP"], income: 0, margin: [99.99, 99.99], net: [99.99, 65], review: "US"}, {active: true, days: 1, discount: ["US", "VIP"], income: null, margin: [99.99, 99.99], net: [99.99, 1], review: "US", vip: null}], qty: 99.99, quota: "0", tier: null, weighted: false, years: null}, bucket: "0", health: false}], + [{applicant: {years: 2, flagged: false, qty: 99.99, tier: "gold", items: [{days: -1, income: 65, vip: false, active: false}], extraField: "x"}}, {applicant: {exposure: true, extraField: "x", flagged: false, items: [{active: false, days: -1, discount: ["high", "2", "US", "VIP"], income: 65, margin: [65, 2, 99.99, 99.99], net: [-1, 99.99, 99.99, -1], review: "US", vip: false}], qty: 99.99, quota: "x", tier: "gold", weighted: false, years: 2}, bucket: "2", health: false}], + [{applicant: {years: 0.000001, qty: 5, tier: "gold", items: [{days: 250, income: 7.25, vip: false, active: false}, {days: 1e3, vip: true, active: false}, {days: 99.99, vip: true, active: false}, {days: -0, income: null, vip: true, active: true}, {days: 1000000, income: null, vip: false, active: false}]}}, {applicant: {exposure: true, items: [{active: false, days: 250, discount: ["US", "VIP"], income: 7.25, margin: [5, 5], net: [5, 250], review: "US", vip: false}, {active: false, days: 1000, discount: ["US", "VIP"], margin: [5, 5], net: [5, 5], review: "US", vip: true}, {active: false, days: 99.99, discount: ["US", "VIP"], margin: [5, 5], net: [5, 5], review: "US", vip: true}, {active: true, days: 0, discount: ["US", "VIP"], income: null, margin: [5, 5], net: [5, 5], review: "US", vip: true}, {active: false, days: 1000000, discount: ["US", "VIP"], income: null, margin: [5, 5], net: [5, 1000000], review: "US", vip: false}], qty: 5, quota: "0.000001", tier: "gold", weighted: true, years: 0.000001}, bucket: "0.000001", health: true}], + [{applicant: {years: 1000000, flagged: null, qty: 50, tier: "bronze", items: [{days: 0.000001, active: false}, {days: 0.1, active: false}, {days: -500, income: 123456789.123, vip: true, active: false}, {days: 18, income: 0.000001, vip: false, active: true}, {days: 447, income: 2.50, vip: null, active: true}]}}, {applicant: {exposure: true, flagged: null, items: [{active: false, days: 0.000001, discount: ["50", "VIP"], margin: [50, 50], net: [50, 0.000001], review: "50"}, {active: false, days: 0.1, discount: ["50", "VIP"], margin: [50, 50], net: [50, 0.1], review: "50"}, {active: false, days: -500, discount: ["50", "VIP"], income: 123456789.123, margin: [50, 50], net: [50, 50], review: "50", vip: true}, {active: true, days: 18, discount: ["50", "VIP"], income: 0.000001, margin: [50, 50], net: [50, 18], review: "50", vip: false}, {active: true, days: 447, discount: ["50", "VIP"], income: 2.50, margin: [50, 50], net: [50, 447], review: "50", vip: null}], qty: 50, quota: "1000000", tier: "bronze", weighted: true, years: 1000000}, bucket: "1000000", health: false}], + [{applicant: {years: 7.25, flagged: true, qty: 18, tier: "silver", items: [{days: 100, income: 1000000, vip: true, active: true}, {days: 1000, income: 1000, vip: false, active: true}]}}, {applicant: {exposure: true, flagged: true, items: [{active: true, days: 100, discount: ["18-18", "18", "VIP"], income: 1000000, margin: [0, 18, 18], net: [100, 18, 18], review: "18", vip: true}, {active: true, days: 1000, discount: ["18-18", "18", "VIP"], income: 1000, margin: [0, 18, 18], net: [1000, 18, 1000], review: "18", vip: false}], qty: 18, quota: "x", tier: "silver", weighted: true, years: 7.25}, bucket: "7.25", health: false}], + [{applicant: {years: 123456789.123, qty: -500, tier: "gold", items: [{days: 151, income: 250, active: true}, {days: 99999999999999999999, vip: null, active: false}, {days: 99999999999999999999, income: 10, vip: null, active: true}, {days: 50, vip: false, active: true}, {days: 10, income: 1000, vip: true, active: true}]}}, {applicant: {exposure: true, items: [{active: true, days: 151, discount: ["US", "VIP"], income: 250, margin: [-500, -500], net: [-500, 151], review: "US"}, {active: false, days: 99999999999999999999, discount: ["US", "VIP"], margin: [-500, -500], net: [-500, 99999999999999999999], review: "US", vip: null}, {active: true, days: 99999999999999999999, discount: ["US", "VIP"], income: 10, margin: [-500, -500], net: [-500, 99999999999999999999], review: "US", vip: null}, {active: true, days: 50, discount: ["US", "VIP"], margin: [-500, -500], net: [-500, 50], review: "US", vip: false}, {active: true, days: 10, discount: ["US", "VIP"], income: 1000, margin: [-500, -500], net: [-500, -500], review: "US", vip: true}], qty: -500, quota: "123456789.123", tier: "gold", weighted: true, years: 123456789.123}, bucket: "123456789.123", health: true}], + [{applicant: {years: 0, flagged: true, qty: -0.5, tier: "silver", items: []}}, {applicant: {exposure: true, flagged: true, items: [], qty: -0.5, quota: "0", tier: "silver", weighted: true, years: 0}, bucket: "0", health: true}], + [{applicant: {years: 100, qty: 0.000001, tier: "gold", items: [{days: 123456789.123, income: 0.1, vip: false, active: true}, {days: 0.1, income: 0.1, vip: true, active: false}, {days: -0.5, income: 0.1, vip: true, active: false}, {days: 250, income: 5, active: true}]}}, {applicant: {exposure: true, items: [{active: true, days: 123456789.123, discount: ["0.000001", "VIP"], income: 0.1, margin: [0.000001, 0.000001], net: [0.000001, 123456789.123], review: "0.000001", vip: false}, {active: false, days: 0.1, discount: ["0.000001", "VIP"], income: 0.1, margin: [0.000001, 0.000001], net: [0.000001, 0.000001], review: "0.000001", vip: true}, {active: false, days: -0.5, discount: ["0.000001", "VIP"], income: 0.1, margin: [0.000001, 0.000001], net: [0.000001, 0.000001], review: "0.000001", vip: true}, {active: true, days: 250, discount: ["0.000001", "VIP"], income: 5, margin: [0.000001, 0.000001], net: [0.000001, 250], review: "0.000001"}], qty: 0.000001, quota: "100", tier: "gold", weighted: true, years: 100}, bucket: "100", health: true}], + [{applicant: {years: 1, flagged: null, qty: 99.99, tier: null, items: [{days: 0.1, income: 99999999999999999999, vip: false, active: true}, {days: 5, income: null, active: false}, {days: 1000, income: 1, vip: false, active: false}]}}, {applicant: {exposure: true, flagged: null, items: [{active: true, days: 0.1, discount: ["US", "VIP"], income: 99999999999999999999, margin: [99.99, 99.99], net: [99.99, 0.1], review: "US", vip: false}, {active: false, days: 5, discount: ["US", "VIP"], income: null, margin: [99.99, 99.99], net: [99.99, 5], review: "US"}, {active: false, days: 1000, discount: ["US", "VIP"], income: 1, margin: [99.99, 99.99], net: [99.99, 1000], review: "US", vip: false}], qty: 99.99, quota: "1", tier: null, weighted: false, years: 1}, bucket: "1", health: false}], + [{applicant: {years: 5, flagged: null, qty: 0, tier: null, items: [{days: 65, income: 1, active: true}, {days: -0.5, income: null, vip: null, active: false}, {days: 0.5, income: 2.50, vip: false, active: false}]}}, {applicant: {exposure: true, flagged: null, items: [{active: true, days: 65, discount: ["US", "VIP"], income: 1, margin: [0, 0], net: [0, 65], review: "US"}, {active: false, days: -0.5, discount: ["US", "VIP"], income: null, margin: [0, 0], net: [0, -0.5], review: "US", vip: null}, {active: false, days: 0.5, discount: ["US", "VIP"], income: 2.50, margin: [0, 0], net: [0, 0.5], review: "US", vip: false}], qty: 0, quota: "5", tier: null, weighted: true, years: 5}, bucket: "5", health: true}], + [{applicant: {years: 5, flagged: false, qty: 0, tier: "bronze", items: [{days: 2, income: -0.5, vip: true, active: true}, {days: 18, income: 0, vip: false, active: false}, {days: 68, income: 2.50, vip: false, active: true}, {days: -500, income: 0.1, vip: false, active: true}, {days: -0, income: 0.000001, vip: false, active: false}]}}, {applicant: {exposure: true, flagged: false, items: [{active: true, days: 2, discount: ["high", "5", "0", "VIP"], income: -0.5, margin: [-0.5, 5, 0, 0], net: [2, 0, 0, 0], review: "0", vip: true}, {active: false, days: 18, discount: ["high", "5", "0", "VIP"], income: 0, margin: [0, 5, 0, 0], net: [18, 0, 0, 18], review: "0", vip: false}, {active: true, days: 68, discount: ["high", "5", "0", "VIP"], income: 2.50, margin: [2.50, 5, 0, 0], net: [68, 0, 0, 68], review: "0", vip: false}, {active: true, days: -500, discount: ["high", "5", "0", "VIP"], income: 0.1, margin: [0.1, 5, 0, 0], net: [-500, 0, 0, -500], review: "0", vip: false}, {active: false, days: 0, discount: ["high", "5", "0", "VIP"], income: 0.000001, margin: [0.000001, 5, 0, 0], net: [0, 0, 0, 0], review: "0", vip: false}], qty: 0, quota: "x", tier: "bronze", weighted: true, years: 5}, bucket: "5", health: true}], + [{applicant: {years: -1, flagged: false, qty: -0.5, tier: "bronze", items: [{days: 5, income: -0.5, vip: true, active: true}, {days: 0, income: 0.000001, vip: false, active: true}], extraField: "x"}}, {applicant: {exposure: true, extraField: "x", flagged: false, items: [{active: true, days: 5, discount: ["high", "-1", "-0.5", "VIP"], income: -0.5, margin: [-0.5, -1, -0.5, -0.5], net: [5, -0.5, -0.5, -0.5], review: "-0.5", vip: true}, {active: true, days: 0, discount: ["high", "-1", "-0.5", "VIP"], income: 0.000001, margin: [0.000001, -1, -0.5, -0.5], net: [0, -0.5, -0.5, 0], review: "-0.5", vip: false}], qty: -0.5, quota: "x", tier: "bronze", weighted: false, years: -1}, bucket: "-1", health: true}], + ], +} + +// seed 332700 (attempt 0) +{ + name: "a 28: customer/loans: 3 expression, 1 match, 4 table; 9 root, 3 per-member, 1 top-level computed", + policy: { + models: {customer: {rate: "number?", openedAt: "date", amount: "number", city: "string", loans: "loan[]"}, loan: {limit: "number", verified: "boolean?", kind: "string(retail|corporate)", openedAt: "date"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {expression: "customer.decision", value: "len((factor <= 0.25 ? customer.city : customer.city)) > 1"}, + {match: "segment", arms: [["(customer.rate ?? 0) < factor", "(((customer.level ?? false) ? (customer.rate ?? 0) : factor) - ((customer.exposure ?? false) ? factor : factor))"], ["", "len(customer.grade)"]]}, + {table: "t8", inputs: ["(customer.eligible ?? false)"], outputs: ["customer.penalty"], rules: [ + ["false", "(customer.eligible ?? false)"], + ["", "(customer.level ?? false)"], + ]}, + {expression: "customer.summary", value: "string(len(customer.loans))"}, + {expression: "loan.surcharge", value: "customer.openedAt.year()"}, + {table: "t2", inputs: ["factor"], outputs: ["loan.flag", "loan.bonus[]"], rules: [ + ["1000, 0.25", "10", "loan.limit"], + ["<= 50", "factor", "customer.amount"], + ["< 100", "customer.amount", ""], + ["100, 5", "(loan.limit * loan.limit)", "(customer.rate ?? 0)"], + ["< 1000", "", "(customer.rate ?? 0)"], + ["!= 3", "factor", ""], + ["", "loan.limit", "count(customer.loans, ((#.verified ?? false) and (#.verified ?? false)))"], + ]}, + {table: "t1", hit: "collect", inputs: ["customer.openedAt"], outputs: ["customer.total", "customer.ok", "customer.grade"], rules: [ + ["> d('2025-03-20')", "customer.amount", "(customer.rate ?? 0) > 18", "customer.city"], + ["< d('2000-06-30')", "(customer.rate ?? 0)", "(customer.rate ?? 0) > 0.25", "'low'"], + ["> d('2025-03-20')", "factor", "", "customer.city"], + ["> d('2025-01-01')", "(customer.rate ?? 0)", "factor == 250", "(customer.amount > 18 ? customer.city : 'none')"], + ["> d('2000-06-30')", "len(customer.loans)", "some(customer.loans, #.kind == 'corporate')", "customer.city"], + ["< d('2024-01-01')", "100", "", "customer.city"], + ["", "(avg(map(customer.loans, #.limit)) ?? 0)", "50 > 1000", ""], + ]}, + {table: "t4", inputs: ["customer.decision", "customer.amount", "factor"], outputs: ["customer.exposure", "customer.eligible", "customer.level"], rules: [ + ["false", "", "[10..399]", "customer.decision", "customer.decision", "customer.decision"], + ["false", ">= 3", "50, 0", "customer.decision", "customer.decision", "customer.decision"], + ["", "", "[2..330]", "", "not (customer.decision)", "(customer.rate ?? 0) in [-5..144]"], + ["", "<= 250", "!= 0.25", "", "customer.decision", "customer.rate == null"], + ["true", "!= 100", "<= 10", "", "customer.decision", "all(customer.loans, ((#.verified ?? false) and (#.verified ?? false)))"], + ["false", "", "", "customer.decision", "customer.decision", ""], + ["true", "<= 18", "18", "all(customer.loans, #.verified == null)", "customer.decision", "all(customer.loans, #.verified == null)"], + ]}, + ], + }, + cases: [ + [{factor: 0.5, customer: {rate: 250, openedAt: "2024-02-29", amount: 1, city: "é ü", loans: [{limit: 99.99, verified: true, kind: "retail", openedAt: "2025-03-20T10:15:30Z"}, {limit: 100, verified: true, kind: "corporate", openedAt: "2024-02-29"}, {limit: 10, verified: true, kind: "retail", openedAt: "2025-03-20T10:15:30Z"}, {limit: 18, verified: false, kind: "corporate", openedAt: "2024-01-01"}]}}, {customer: {amount: 1, city: "é ü", decision: true, eligible: true, exposure: null, grade: ["é ü"], level: false, loans: [{bonus: [1, 250, 3], flag: 0.5, kind: "retail", limit: 99.99, openedAt: "2025-03-20T10:15:30Z", surcharge: 2024, verified: true}, {bonus: [1, 250, 3], flag: 0.5, kind: "corporate", limit: 100, openedAt: "2024-02-29", surcharge: 2024, verified: true}, {bonus: [1, 250, 3], flag: 0.5, kind: "retail", limit: 10, openedAt: "2025-03-20T10:15:30Z", surcharge: 2024, verified: true}, {bonus: [1, 250, 3], flag: 0.5, kind: "corporate", limit: 18, openedAt: "2024-01-01", surcharge: 2024, verified: false}], ok: [true, false], openedAt: "2024-02-29", penalty: false, rate: 250, summary: "4", total: [4, 56.9975]}, factor: 0.5, segment: 1}], + [{factor: 10, customer: {rate: 18, openedAt: "2025-03-20", amount: 3, city: "NL", loans: [{limit: -0, kind: "retail", openedAt: "2025-03-20"}, {limit: 1.5, verified: true, kind: "corporate", openedAt: "2024-02-29"}, {limit: 1000, verified: true, kind: "retail", openedAt: "2000-01-01"}, {limit: 18, kind: "retail", openedAt: "2025-03-20"}, {limit: 10, verified: null, kind: "retail", openedAt: "2030-12-31"}]}}, {customer: {amount: 3, city: "NL", decision: true, eligible: false, exposure: null, grade: ["none", "NL"], level: true, loans: [{bonus: [3, 18, 2], flag: 10, kind: "retail", limit: 0, openedAt: "2025-03-20", surcharge: 2025}, {bonus: [3, 18, 2], flag: 10, kind: "corporate", limit: 1.5, openedAt: "2024-02-29", surcharge: 2025, verified: true}, {bonus: [3, 18, 2], flag: 10, kind: "retail", limit: 1000, openedAt: "2000-01-01", surcharge: 2025, verified: true}, {bonus: [3, 18, 2], flag: 10, kind: "retail", limit: 18, openedAt: "2025-03-20", surcharge: 2025}, {bonus: [3, 18, 2], flag: 10, kind: "retail", limit: 10, openedAt: "2030-12-31", surcharge: 2025, verified: null}], ok: [false, true, false], openedAt: "2025-03-20", penalty: false, rate: 18, summary: "5", total: [18, 5, 205.9]}, factor: 10, segment: 2}], + [{factor: 10, customer: {rate: 0, openedAt: "1990-06-15", amount: 1.5, city: "x-y", loans: [{limit: 18, verified: true, kind: "corporate", openedAt: "2000-01-01"}, {limit: -0.01, verified: false, kind: "corporate", openedAt: "2025-03-20T10:15:30Z"}]}}, {customer: {amount: 1.5, city: "x-y", decision: true, eligible: false, exposure: null, grade: ["low", "x-y"], level: true, loans: [{bonus: [1.5, 0, 1], flag: 10, kind: "corporate", limit: 18, openedAt: "2000-01-01", surcharge: 1990, verified: true}, {bonus: [1.5, 0, 1], flag: 10, kind: "corporate", limit: -0.01, openedAt: "2025-03-20T10:15:30Z", surcharge: 1990, verified: false}], ok: [false, false], openedAt: "1990-06-15", penalty: false, rate: 0, summary: "2", total: [0, 100, 8.9950]}, factor: 10, segment: -10}], + [{factor: 10, customer: {openedAt: "2024-02-29", amount: 0, city: "é ü", loans: [{limit: 2, verified: null, kind: "corporate", openedAt: "2025-03-20"}, {limit: 7.25, verified: false, kind: "retail", openedAt: "2030-12-31"}, {limit: 100, verified: true, kind: "corporate", openedAt: "2024-02-29"}, {limit: 100, verified: false, kind: "corporate", openedAt: "2024-02-29"}]}}, {customer: {amount: 0, city: "é ü", decision: true, eligible: false, exposure: null, grade: ["é ü"], level: true, loans: [{bonus: [0, 0, 1], flag: 10, kind: "corporate", limit: 2, openedAt: "2025-03-20", surcharge: 2024, verified: null}, {bonus: [0, 0, 1], flag: 10, kind: "retail", limit: 7.25, openedAt: "2030-12-31", surcharge: 2024, verified: false}, {bonus: [0, 0, 1], flag: 10, kind: "corporate", limit: 100, openedAt: "2024-02-29", surcharge: 2024, verified: true}, {bonus: [0, 0, 1], flag: 10, kind: "corporate", limit: 100, openedAt: "2024-02-29", surcharge: 2024, verified: false}], ok: [true, false], openedAt: "2024-02-29", penalty: false, summary: "4", total: [4, 52.3125]}, factor: 10, segment: -10}], + [{factor: 0, customer: {openedAt: "2024-01-01", amount: 5, city: "NL", loans: []}}, "!error: ExpressionFailed"], + [{factor: 0.5, customer: {rate: 0.25, openedAt: "2025-03-20", amount: 0.25, city: "low", loans: [{limit: 1e3, verified: true, kind: "corporate", openedAt: "1990-06-15"}, {limit: 5, verified: false, kind: "retail", openedAt: "1990-06-15"}]}}, {customer: {amount: 0.25, city: "low", decision: true, eligible: true, exposure: null, grade: ["none", "low"], level: false, loans: [{bonus: [0.25, 0.25, 1], flag: 0.5, kind: "corporate", limit: 1000, openedAt: "1990-06-15", surcharge: 2025, verified: true}, {bonus: [0.25, 0.25, 1], flag: 0.5, kind: "retail", limit: 5, openedAt: "1990-06-15", surcharge: 2025, verified: false}], ok: [false, true, false], openedAt: "2025-03-20", penalty: false, rate: 0.25, summary: "2", total: [0.25, 2, 502.50]}, factor: 0.5, segment: 0.0}], + [{factor: 0.5, customer: {rate: 5, openedAt: "2024-02-29", amount: 10, city: "A1", loans: [{limit: 5, verified: false, kind: "retail", openedAt: "2000-01-01"}, {limit: 1000, verified: false, kind: "retail", openedAt: "1990-06-15"}]}}, {customer: {amount: 10, city: "A1", decision: true, eligible: true, exposure: null, grade: ["A1"], level: false, loans: [{bonus: [10, 5, 0], flag: 0.5, kind: "retail", limit: 5, openedAt: "2000-01-01", surcharge: 2024, verified: false}, {bonus: [10, 5, 0], flag: 0.5, kind: "retail", limit: 1000, openedAt: "1990-06-15", surcharge: 2024, verified: false}], ok: [false, false], openedAt: "2024-02-29", penalty: false, rate: 5, summary: "2", total: [2, 502.50]}, factor: 0.5, segment: 1}], + [{factor: -2, customer: {rate: -500, openedAt: "1990-06-15", amount: 3, city: "日本", loans: [{limit: 1, verified: false, kind: "retail", openedAt: "2030-12-31"}, {limit: 0.5, verified: false, kind: "retail", openedAt: "2024-02-29"}]}}, {customer: {amount: 3, city: "日本", decision: true, eligible: true, exposure: null, grade: ["low", "日本"], level: false, loans: [{bonus: [3, -500, 0], flag: -2, kind: "retail", limit: 1, openedAt: "2030-12-31", surcharge: 1990, verified: false}, {bonus: [3, -500, 0], flag: -2, kind: "retail", limit: 0.5, openedAt: "2024-02-29", surcharge: 1990, verified: false}], ok: [false, false], openedAt: "1990-06-15", penalty: false, rate: -500, summary: "2", total: [-500, 100, 0.750]}, factor: -2, segment: 0}], + [{factor: -2, customer: {openedAt: "2024-01-01", amount: 0.25, city: "A1", loans: [{limit: 1000, kind: "retail", openedAt: "2030-12-31"}, {limit: 5, verified: true, kind: "corporate", openedAt: "2000-01-01"}]}}, {customer: {amount: 0.25, city: "A1", decision: true, eligible: true, exposure: null, grade: ["A1"], level: true, loans: [{bonus: [0.25, 0, 1], flag: -2, kind: "retail", limit: 1000, openedAt: "2030-12-31", surcharge: 2024}, {bonus: [0.25, 0, 1], flag: -2, kind: "corporate", limit: 5, openedAt: "2000-01-01", surcharge: 2024, verified: true}], ok: [true, false], openedAt: "2024-01-01", penalty: true, summary: "2", total: [2, 502.50]}, factor: -2, segment: 1}], + [{factor: 100, customer: {rate: 18, openedAt: "2025-03-20", amount: 10, city: "3.5", loans: [{limit: 50, verified: true, kind: "retail", openedAt: "2030-12-31"}, {limit: 50, verified: true, kind: "retail", openedAt: "2030-12-31"}]}}, {customer: {amount: 10, city: "3.5", decision: true, eligible: false, exposure: null, grade: ["none", "3.5"], level: true, loans: [{bonus: [18, 18, 2], flag: 2500, kind: "retail", limit: 50, openedAt: "2030-12-31", surcharge: 2025, verified: true}, {bonus: [18, 18, 2], flag: 2500, kind: "retail", limit: 50, openedAt: "2030-12-31", surcharge: 2025, verified: true}], ok: [false, false, false], openedAt: "2025-03-20", penalty: false, rate: 18, summary: "2", total: [18, 2, 50]}, factor: 100, segment: -82}], + [{factor: 1, customer: {rate: 99.99, openedAt: "1990-06-15", amount: 50, city: "a-b-c", loans: [{limit: 5, verified: false, kind: "corporate", openedAt: "2025-03-20T10:15:30Z"}, {limit: 10, verified: false, kind: "retail", openedAt: "2000-01-01"}]}}, {customer: {amount: 50, city: "a-b-c", decision: true, eligible: true, exposure: null, grade: ["low", "a-b-c"], level: false, loans: [{bonus: [50, 99.99, 0], flag: 1, kind: "corporate", limit: 5, openedAt: "2025-03-20T10:15:30Z", surcharge: 1990, verified: false}, {bonus: [50, 99.99, 0], flag: 1, kind: "retail", limit: 10, openedAt: "2000-01-01", surcharge: 1990, verified: false}], ok: [true, false], openedAt: "1990-06-15", penalty: false, rate: 99.99, summary: "2", total: [99.99, 100, 7.50]}, factor: 1, segment: 2}], + [{factor: 100, customer: {openedAt: "2024-02-29", amount: 99.99, city: "US", loans: [{limit: 2, verified: false, kind: "retail", openedAt: "2000-01-01"}]}}, {customer: {amount: 99.99, city: "US", decision: true, eligible: false, exposure: null, grade: ["US"], level: true, loans: [{bonus: [0, 0, 0], flag: 4, kind: "retail", limit: 2, openedAt: "2000-01-01", surcharge: 2024, verified: false}], ok: [false, false], openedAt: "2024-02-29", penalty: false, summary: "1", total: [1, 2]}, factor: 100, segment: -100}], + ], +} + +// seed 332800 (attempt 0) +{ + name: "a 29: customer/lines: 4 expression, 2 match, 2 table; 4 root, 1 per-member, 4 top-level computed", + policy: { + models: {customer: {income: "number?", name: "string?", region: "string", plan: "string(basic|plus|premium|trial)", priority: "boolean", lines: "line[]"}, line: {amount: "number", plan: "string(basic|plus|premium|trial)", limit: "number?"}}, + blocks: [ + {expression: "customer.fee", value: "(customer.income ?? 0)"}, + {expression: "customer.penalty", value: "(none(customer.lines, #.plan in ['basic', 'trial']) ? (none(customer.lines, (#.limit ?? 0) <= 250) ? (min(map(customer.lines, (#.limit ?? 0))) ?? 0) : customer.fee) : (all(customer.lines, (#.amount > 100 or (#.limit ?? 0) <= 3)) ? sum(map(customer.lines, (#.limit ?? 0))) : (customer.fee) / (abs(customer.fee) + 1)))"}, + {expression: "level", value: "sum(map(customer.lines, #.amount))"}, + {match: "customer.segment", arms: [["customer.name != null", "'none'"], ["customer.plan == 'plus'", "customer.region"], ["", "'Oslo'"]]}, + {expression: "decision", value: "lower(string(len(customer.lines)))"}, + {match: "line.margin", arms: [["line.plan == 'trial'", "decision"], ["", "customer.segment"]]}, + {table: "t7", inputs: [null], outputs: ["customer.health"], rules: [ + ["customer.income != null", "(customer.priority ? 100 : 1)"], + ["(customer.priority or customer.priority)", "customer.fee"], + ["level >= level", "level"], + ["", "(customer.income ?? 0)"], + ]}, + {table: "t8", inputs: ["customer.name"], outputs: ["risk", "surcharge[]"], rules: [ + ["'x'", "decision", "customer.priority"], + ["", "(customer.name ?? '')", "customer.priority"], + ["'DE'", "(customer.name ?? '')", "customer.priority"], + ["'US'", "(customer.name ?? '')", "customer.priority"], + ["'none'", "'none'", "customer.priority"], + ["'US'", "(customer.name ?? '')", "customer.priority"], + ["", "", ""], + ]}, + ], + }, + cases: [ + [{customer: {income: 100, name: false, region: "A1", plan: "plus", priority: false, lines: [{amount: -0.01, plan: "premium", limit: 100}, {amount: 100, plan: "trial", limit: 1000}]}}, "!error: InputValidationFailed"], + [{customer: {income: null, name: "A1", region: "none", plan: "plus", priority: true, lines: [{amount: 77, plan: "trial", limit: null}, {amount: 2.50, plan: "premium", limit: 7.25}, {amount: 100, plan: "trial"}]}}, {customer: {fee: 0, health: 0, income: null, lines: [{amount: 77, limit: null, margin: "3", plan: "trial"}, {amount: 2.50, limit: 7.25, margin: "none", plan: "premium"}, {amount: 100, margin: "3", plan: "trial"}], name: "A1", penalty: 0, plan: "plus", priority: true, region: "none", segment: "none"}, decision: "3", level: 179.50, risk: "A1", surcharge: [true]}], + [{customer: {income: 100, name: "3.5", region: "A1", plan: "basic", priority: false, lines: [{amount: 65, plan: "premium", limit: 0}, {amount: 1000000, plan: "premium", limit: 99999999999999999999}], extraField: 1}}, {customer: {extraField: 1, fee: 100, health: 1, income: 100, lines: [{amount: 65, limit: 0, margin: "none", plan: "premium"}, {amount: 1000000, limit: 99999999999999999999, margin: "none", plan: "premium"}], name: "3.5", penalty: 100, plan: "basic", priority: false, region: "A1", segment: "none"}, level: 1000065, risk: "3.5", surcharge: [false]}], + [{customer: {income: -0.01, name: "DE", region: "DE", plan: "plus", priority: true, lines: []}}, "!error: ExpressionFailed"], + [{customer: {income: 1000000, name: "abc", region: "", plan: "trial", priority: true, lines: [{amount: 0.1, plan: "basic", limit: 1}, {amount: 250, plan: "premium", limit: 0}, {amount: 99999999999999999999, plan: "basic", limit: 0.25}, {amount: 1.5, plan: "trial", limit: 1000000}]}}, {customer: {fee: 1000000, health: 100, income: 1000000, lines: [{amount: 0.1, limit: 1, margin: "none", plan: "basic"}, {amount: 250, limit: 0, margin: "none", plan: "premium"}, {amount: 99999999999999999999, limit: 0.25, margin: "none", plan: "basic"}, {amount: 1.5, limit: 1000000, margin: "4", plan: "trial"}], name: "abc", penalty: 0.999999000000999999000001, plan: "trial", priority: true, region: "", segment: "none"}, decision: "4", level: 100000000000000000250.6, risk: "abc", surcharge: [true]}], + [{customer: {income: 99999999999999999999, name: "", region: "Oslo", plan: "trial", priority: false, lines: [{amount: -1, plan: "basic", limit: 99.99}]}}, {customer: {fee: 99999999999999999999, health: 1, income: 99999999999999999999, lines: [{amount: -1, limit: 99.99, margin: "none", plan: "basic"}], name: "", penalty: 0.99999999999999999999, plan: "trial", priority: false, region: "Oslo", segment: "none"}, level: -1, risk: "", surcharge: [false]}], + [{customer: {income: 1000000, region: "é ü", plan: "trial", priority: true, lines: [{amount: 65, plan: "plus", limit: null}, {amount: 2.50, plan: "basic", limit: 100}, {amount: 3, plan: "premium"}, {amount: 10, plan: "basic", limit: null}, {amount: 1000, plan: "basic"}]}}, {customer: {fee: 1000000, health: 100, income: 1000000, lines: [{amount: 65, limit: null, margin: "Oslo", plan: "plus"}, {amount: 2.50, limit: 100, margin: "Oslo", plan: "basic"}, {amount: 3, margin: "Oslo", plan: "premium"}, {amount: 10, limit: null, margin: "Oslo", plan: "basic"}, {amount: 1000, margin: "Oslo", plan: "basic"}], penalty: 0.999999000000999999000001, plan: "trial", priority: true, region: "é ü", segment: "Oslo"}, level: 1080.50, risk: "", surcharge: [true]}], + [{customer: {income: 65, name: "Zed", region: "VIP", plan: "premium", priority: false, lines: [{amount: 123456789.123, plan: "premium", limit: 3}, {amount: 0, plan: "trial", limit: 2.50}, {amount: 100, plan: "premium", limit: 7.25}, {amount: 2, plan: "trial", limit: 100}], extraField: {nested: true}}}, {customer: {extraField: {nested: true}, fee: 65, health: 1, income: 65, lines: [{amount: 123456789.123, limit: 3, margin: "none", plan: "premium"}, {amount: 0, limit: 2.50, margin: "4", plan: "trial"}, {amount: 100, limit: 7.25, margin: "none", plan: "premium"}, {amount: 2, limit: 100, margin: "4", plan: "trial"}], name: "Zed", penalty: 0.9848484848484848484848484848, plan: "premium", priority: false, region: "VIP", segment: "none"}, decision: "4", level: 123456891.123, risk: "Zed", surcharge: [false]}], + [{customer: {region: "NL", plan: "basic", priority: true, lines: [{amount: 1, plan: "plus", limit: 1000}, {amount: 5, plan: "plus", limit: null}, {amount: 2.50, plan: "premium", limit: 0.1}]}}, {customer: {fee: 0, health: 0, lines: [{amount: 1, limit: 1000, margin: "Oslo", plan: "plus"}, {amount: 5, limit: null, margin: "Oslo", plan: "plus"}, {amount: 2.50, limit: 0.1, margin: "Oslo", plan: "premium"}], penalty: 0, plan: "basic", priority: true, region: "NL", segment: "Oslo"}, level: 8.50, risk: "", surcharge: [true]}], + [{customer: {income: null, name: null, region: "DE", plan: "basic", priority: true, lines: [{amount: 7.25, plan: "trial"}]}}, {customer: {fee: 0, health: 0, income: null, lines: [{amount: 7.25, margin: "1", plan: "trial"}], name: null, penalty: 0, plan: "basic", priority: true, region: "DE"}, decision: "1", level: 7.25, risk: "", surcharge: [true]}], + [{customer: {name: "DE", region: "DE", plan: "premium", priority: true, lines: [{amount: 100, plan: "basic"}]}}, {customer: {fee: 0, health: 0, lines: [{amount: 100, margin: "none", plan: "basic"}], name: "DE", penalty: 0, plan: "premium", priority: true, region: "DE", segment: "none"}, level: 100, risk: "DE", surcharge: [true, true]}], + [{customer: {income: 100, name: "x-y", region: "abc", plan: "basic", priority: false, lines: [{amount: 0.000001, plan: "trial", limit: 1}, {amount: -1, plan: "basic", limit: -0.5}, {amount: -0.5, plan: "trial", limit: 7.25}], extraField: {nested: true}}}, {customer: {extraField: {nested: true}, fee: 100, health: 1, income: 100, lines: [{amount: 0.000001, limit: 1, margin: "3", plan: "trial"}, {amount: -1, limit: -0.5, margin: "none", plan: "basic"}, {amount: -0.5, limit: 7.25, margin: "3", plan: "trial"}], name: "x-y", penalty: 0.9900990099009900990099009901, plan: "basic", priority: false, region: "abc", segment: "none"}, decision: "3", level: -1.499999, risk: "x-y", surcharge: [false]}], + [{customer: {income: 123456789.123, name: "12", region: "retail", plan: "basic", priority: false, lines: [{amount: 371, plan: "premium", limit: 100}, {amount: 2.50, plan: "plus", limit: 1.5}]}}, {customer: {fee: 123456789.123, health: 1, income: 123456789.123, lines: [{amount: 371, limit: 100, margin: "none", plan: "premium"}, {amount: 2.50, limit: 1.5, margin: "none", plan: "plus"}], name: "12", penalty: 123456789.123, plan: "basic", priority: false, region: "retail", segment: "none"}, level: 373.50, risk: "12", surcharge: [false]}], + [{customer: {income: 65, name: "NL", region: "low", plan: "basic", priority: true, lines: [{amount: 0.5, plan: "trial", limit: 99.99}]}}, {customer: {fee: 65, health: 100, income: 65, lines: [{amount: 0.5, limit: 99.99, margin: "1", plan: "trial"}], name: "NL", penalty: 0.9848484848484848484848484848, plan: "basic", priority: true, region: "low"}, decision: "1", level: 0.5, risk: "NL", surcharge: [true]}], + [{customer: {income: 1.5, name: "US", region: "DE", plan: "basic", priority: true, lines: []}}, "!error: ExpressionFailed"], + [{customer: {income: 123456789.123, name: "abc", region: "US", plan: "basic", priority: true, lines: []}}, "!error: ExpressionFailed"], + [{customer: {income: 100, name: "retail", region: "none", plan: "basic", priority: true, lines: []}}, "!error: ExpressionFailed"], + [{customer: {income: 0.1, name: null, region: "DE", plan: "premium", priority: false, lines: []}}, "!error: ExpressionFailed"], + [{customer: {income: 250, name: "gold", region: "gold", plan: "plus", priority: false, lines: [{amount: -0.5, plan: "basic", limit: 1.5}]}}, {customer: {fee: 250, health: 1, income: 250, lines: [{amount: -0.5, limit: 1.5, margin: "none", plan: "basic"}], name: "gold", penalty: 1.5, plan: "plus", priority: false, region: "gold", segment: "none"}, level: -0.5, risk: "gold", surcharge: [false]}], + ], +} + +// seed 332900 (attempt 0) +{ + name: "a 30: borrower/accounts: 1 assertion, 4 expression, 1 match, 1 table; 1 root, 3 per-member, 3 top-level computed", + policy: { + models: {borrower: {balance: "number", flagged: "boolean", urgent: "boolean", rate: "number?", label: "string", weight: "number", accounts: "acct[]"}, acct: {rate: "number", urgent: "boolean", active: "boolean?"}}, + blocks: [ + {expression: "surcharge", value: "borrower.weight"}, + {expression: "level", value: "sum(map(borrower.accounts, #.rate))"}, + {assertion: "acct.grade", conditions: ["borrower.label != 'low'"]}, + {table: "t4", inputs: ["borrower.weight"], outputs: ["tag"], rules: [ + ["", "borrower.urgent"], + ["", "borrower.urgent"], + ["> 18", "borrower.urgent"], + ["100, 1.5", "borrower.urgent"], + ["> 5", "borrower.flagged"], + ]}, + {expression: "acct.margin", value: "count(borrower.accounts, (#.urgent and #.grade))"}, + {match: "borrower.points", arms: [["trim(borrower.label) != 'Oslo'", "(level < borrower.balance ? ((tag ?? false) ? borrower.label : borrower.label) : borrower.label)"], ["surcharge >= surcharge", "borrower.label"], ["", "(borrower.urgent ? 'none' : borrower.label)"]]}, + {expression: "acct.exposure", value: "acct.margin"}, + ], + }, + cases: [ + [{borrower: {balance: 1e3, flagged: false, urgent: true, label: " pad ", weight: 10, accounts: [{rate: 2, urgent: false, active: null}]}}, {borrower: {accounts: [{active: null, exposure: 0, grade: true, margin: 0, rate: 2, urgent: false}], balance: 1000, flagged: false, label: " pad ", points: " pad ", urgent: true, weight: 10}, level: 2, surcharge: 10, tag: true}], + [{borrower: {balance: 1.5, flagged: false, urgent: false, label: "VIP", weight: 1, accounts: [{rate: 18, urgent: true, active: false}, {rate: 1, urgent: true, active: true}, {rate: 158, urgent: true}, {rate: 0.1, urgent: false, active: false}, {rate: 1.5, urgent: true, active: false}]}}, {borrower: {accounts: [{active: false, exposure: 4, grade: true, margin: 4, rate: 18, urgent: true}, {active: true, exposure: 4, grade: true, margin: 4, rate: 1, urgent: true}, {exposure: 4, grade: true, margin: 4, rate: 158, urgent: true}, {active: false, exposure: 4, grade: true, margin: 4, rate: 0.1, urgent: false}, {active: false, exposure: 4, grade: true, margin: 4, rate: 1.5, urgent: true}], balance: 1.5, flagged: false, label: "VIP", points: "VIP", urgent: false, weight: 1}, level: 178.6, surcharge: 1, tag: false}], + [{borrower: {balance: 100, flagged: true, urgent: true, rate: -0.5, label: "x-y", weight: 7.25, accounts: []}}, {borrower: {accounts: [], balance: 100, flagged: true, label: "x-y", points: "x-y", rate: -0.5, urgent: true, weight: 7.25}, level: 0, surcharge: 7.25, tag: true}], + [{borrower: {balance: 123456789.123, flagged: false, urgent: true, rate: -0.01, label: "Oslo", weight: 5, accounts: [{rate: 0.000001, urgent: false, active: false}, {rate: 1.5, urgent: true, active: true}, {rate: 99.99, urgent: false, active: false}, {rate: 65, urgent: true, active: true}]}}, {borrower: {accounts: [{active: false, exposure: 2, grade: true, margin: 2, rate: 0.000001, urgent: false}, {active: true, exposure: 2, grade: true, margin: 2, rate: 1.5, urgent: true}, {active: false, exposure: 2, grade: true, margin: 2, rate: 99.99, urgent: false}, {active: true, exposure: 2, grade: true, margin: 2, rate: 65, urgent: true}], balance: 123456789.123, flagged: false, label: "Oslo", points: "Oslo", rate: -0.01, urgent: true, weight: 5}, surcharge: 5}], + [{borrower: {balance: 51, flagged: false, urgent: true, rate: null, label: "abc", weight: 1e3, accounts: [{rate: 0.000001, urgent: true, active: true}, {rate: 5, urgent: false, active: false}, {rate: 7.25, urgent: true, active: false}]}}, {borrower: {accounts: [{active: true, exposure: 2, grade: true, margin: 2, rate: 0.000001, urgent: true}, {active: false, exposure: 2, grade: true, margin: 2, rate: 5, urgent: false}, {active: false, exposure: 2, grade: true, margin: 2, rate: 7.25, urgent: true}], balance: 51, flagged: false, label: "abc", points: "abc", rate: null, urgent: true, weight: 1000}, level: 12.250001, surcharge: 1000, tag: true}], + [{borrower: {balance: 0, flagged: true, urgent: false, rate: 1.5, label: "3.5", weight: 123456789.123, accounts: [{rate: 99999999999999999999, urgent: false, active: false}, {rate: 0, urgent: true, active: true}]}}, {borrower: {accounts: [{active: false, exposure: 1, grade: true, margin: 1, rate: 99999999999999999999, urgent: false}, {active: true, exposure: 1, grade: true, margin: 1, rate: 0, urgent: true}], balance: 0, flagged: true, label: "3.5", points: "3.5", rate: 1.5, urgent: false, weight: 123456789.123}, level: 99999999999999999999, surcharge: 123456789.123, tag: false}], + [{borrower: {balance: 100, flagged: false, urgent: true, label: "low", weight: -0.5, accounts: [{rate: 1, urgent: false}, {rate: 0.000001, urgent: true, active: true}]}}, {borrower: {accounts: [{exposure: 0, grade: false, margin: 0, rate: 1, urgent: false}, {active: true, exposure: 0, grade: false, margin: 0, rate: 0.000001, urgent: true}], balance: 100, flagged: false, label: "low", points: "low", urgent: true, weight: -0.5}, level: 1.000001, surcharge: -0.5, tag: true}], + [{borrower: {balance: 7.25, flagged: false, urgent: true, rate: 0.5, label: "-", weight: 5, accounts: []}}, {borrower: {accounts: [], balance: 7.25, flagged: false, label: "-", points: "-", rate: 0.5, urgent: true, weight: 5}, level: 0, surcharge: 5, tag: true}], + [{borrower: {balance: 123456789.123, flagged: true, urgent: true, rate: 0, label: "a", weight: -500, accounts: [{rate: -0.5, urgent: false, active: true}, {rate: 7.25, urgent: false, active: false}, {rate: 1000000, urgent: true, active: true}]}}, {borrower: {accounts: [{active: true, exposure: 1, grade: true, margin: 1, rate: -0.5, urgent: false}, {active: false, exposure: 1, grade: true, margin: 1, rate: 7.25, urgent: false}, {active: true, exposure: 1, grade: true, margin: 1, rate: 1000000, urgent: true}], balance: 123456789.123, flagged: true, label: "a", points: "a", rate: 0, urgent: true, weight: -500}, level: 1000006.75, surcharge: -500, tag: true}], + [{borrower: {balance: 1000, flagged: true, urgent: false, rate: 0.000001, label: "x-y", weight: 18, accounts: []}}, {borrower: {accounts: [], balance: 1000, flagged: true, label: "x-y", points: "x-y", rate: 0.000001, urgent: false, weight: 18}, level: 0, surcharge: 18, tag: false}], + [{borrower: {balance: 0.1, flagged: false, urgent: false, rate: 7.25, label: "O'Neil", weight: 1000, accounts: []}}, {borrower: {accounts: [], balance: 0.1, flagged: false, label: "O'Neil", points: "O'Neil", rate: 7.25, urgent: false, weight: 1000}, level: 0, surcharge: 1000, tag: false}], + [{borrower: {balance: 1000000, flagged: false, urgent: false, label: "Oslo", weight: 1.5, accounts: [{rate: 5, urgent: false, active: null}]}}, {borrower: {accounts: [{active: null, exposure: 0, grade: true, margin: 0, rate: 5, urgent: false}], balance: 1000000, flagged: false, label: "Oslo", points: "Oslo", urgent: false, weight: 1.5}, surcharge: 1.5}], + [{borrower: {balance: 1e3, flagged: true, urgent: true, rate: 2.50, label: "gold", weight: 10, accounts: [{rate: 123456789.123, urgent: false, active: false}, {rate: 2.50, urgent: false, active: true}, {rate: 1000000, urgent: false, active: false}, {rate: 250, urgent: true, active: true}, {rate: 1000, urgent: true, active: true}]}}, {borrower: {accounts: [{active: false, exposure: 2, grade: true, margin: 2, rate: 123456789.123, urgent: false}, {active: true, exposure: 2, grade: true, margin: 2, rate: 2.50, urgent: false}, {active: false, exposure: 2, grade: true, margin: 2, rate: 1000000, urgent: false}, {active: true, exposure: 2, grade: true, margin: 2, rate: 250, urgent: true}, {active: true, exposure: 2, grade: true, margin: 2, rate: 1000, urgent: true}], balance: 1000, flagged: true, label: "gold", points: "gold", rate: 2.50, urgent: true, weight: 10}, level: 124458041.623, surcharge: 10, tag: true}], + [{borrower: {balance: 100, flagged: true, urgent: false, rate: -1, label: "Oslo", weight: 18, accounts: [{rate: 1000, urgent: false, active: true}], extraField: "x"}}, {borrower: {accounts: [{active: true, exposure: 0, grade: true, margin: 0, rate: 1000, urgent: false}], balance: 100, extraField: "x", flagged: true, label: "Oslo", points: "Oslo", rate: -1, urgent: false, weight: 18}, surcharge: 18}], + [{borrower: {balance: 123456789.123, flagged: true, urgent: true, label: "US", weight: -0.01, accounts: []}}, {borrower: {accounts: [], balance: 123456789.123, flagged: true, label: "US", points: "US", urgent: true, weight: -0.01}, level: 0, surcharge: -0.01, tag: true}], + [{borrower: {balance: 123456789.123, flagged: false, urgent: true, rate: 0.1, label: "low", weight: 250, accounts: []}}, {borrower: {accounts: [], balance: 123456789.123, flagged: false, label: "low", points: "low", rate: 0.1, urgent: true, weight: 250}, level: 0, surcharge: 250, tag: true}], + [{borrower: {balance: 99999999999999999999, flagged: false, urgent: true, rate: -0, label: "US", weight: -0.5, accounts: []}}, {borrower: {accounts: [], balance: 99999999999999999999, flagged: false, label: "US", points: "US", rate: 0, urgent: true, weight: -0.5}, level: 0, surcharge: -0.5, tag: true}], + [{borrower: {balance: 65, flagged: true, urgent: false, rate: null, label: "US", weight: 1, accounts: []}}, {borrower: {accounts: [], balance: 65, flagged: true, label: "US", points: "US", rate: null, urgent: false, weight: 1}, level: 0, surcharge: 1, tag: false}], + [{borrower: {balance: 5, flagged: true, urgent: false, rate: -1, label: "abc", weight: 0.1, accounts: [{rate: -0.01, urgent: false, active: false}, {rate: 250, urgent: false, active: true}, {rate: 1000, urgent: true, active: false}, {rate: -1, urgent: false, active: false}], extraField: {nested: true}}}, {borrower: {accounts: [{active: false, exposure: 1, grade: true, margin: 1, rate: -0.01, urgent: false}, {active: true, exposure: 1, grade: true, margin: 1, rate: 250, urgent: false}, {active: false, exposure: 1, grade: true, margin: 1, rate: 1000, urgent: true}, {active: false, exposure: 1, grade: true, margin: 1, rate: -1, urgent: false}], balance: 5, extraField: {nested: true}, flagged: true, label: "abc", points: "abc", rate: -1, urgent: false, weight: 0.1}, level: 1248.99, surcharge: 0.1, tag: false}], + [{borrower: {balance: 99999999999999999999, flagged: true, urgent: true, rate: 1, label: "retail", weight: 0, accounts: [{rate: 123456789.123, urgent: true, active: true}, {rate: -0, urgent: false, active: false}, {rate: 10, urgent: false, active: false}, {rate: 100, urgent: false, active: false}], extraField: 1}}, {borrower: {accounts: [{active: true, exposure: 1, grade: true, margin: 1, rate: 123456789.123, urgent: true}, {active: false, exposure: 1, grade: true, margin: 1, rate: 0, urgent: false}, {active: false, exposure: 1, grade: true, margin: 1, rate: 10, urgent: false}, {active: false, exposure: 1, grade: true, margin: 1, rate: 100, urgent: false}], balance: 99999999999999999999, extraField: 1, flagged: true, label: "retail", points: "retail", rate: 1, urgent: true, weight: 0}, level: 123456899.123, surcharge: 0, tag: true}], + [{borrower: {balance: 5, flagged: true, urgent: false, rate: 448, label: "NL", weight: -1, accounts: [{rate: 18, urgent: true, active: true}, {rate: 99999999999999999999, urgent: true, active: true}, {rate: 65, urgent: false, active: true}, {rate: 2.50, urgent: true, active: true}]}}, {borrower: {accounts: [{active: true, exposure: 3, grade: true, margin: 3, rate: 18, urgent: true}, {active: true, exposure: 3, grade: true, margin: 3, rate: 99999999999999999999, urgent: true}, {active: true, exposure: 3, grade: true, margin: 3, rate: 65, urgent: false}, {active: true, exposure: 3, grade: true, margin: 3, rate: 2.50, urgent: true}], balance: 5, flagged: true, label: "NL", points: "NL", rate: 448, urgent: false, weight: -1}, level: 100000000000000000084.50, surcharge: -1, tag: false}], + [{borrower: {balance: 1000000, flagged: true, urgent: true, label: "low", weight: 1000, accounts: [{rate: 1e3, urgent: true}, {rate: 123456789.123, urgent: true, active: false}, {rate: 0.5, urgent: false, active: null}, {rate: 99999999999999999999, urgent: false, active: null}, {rate: 2.50, urgent: true}]}}, {borrower: {accounts: [{exposure: 0, grade: false, margin: 0, rate: 1000, urgent: true}, {active: false, exposure: 0, grade: false, margin: 0, rate: 123456789.123, urgent: true}, {active: null, exposure: 0, grade: false, margin: 0, rate: 0.5, urgent: false}, {active: null, exposure: 0, grade: false, margin: 0, rate: 99999999999999999999, urgent: false}, {exposure: 0, grade: false, margin: 0, rate: 2.50, urgent: true}], balance: 1000000, flagged: true, label: "low", points: "low", urgent: true, weight: 1000}, level: 100000000000123457791.123, surcharge: 1000, tag: true}], + [{borrower: {balance: 1000, flagged: true, urgent: false, rate: -1, label: "Zed", weight: 99999999999999999999, accounts: [{rate: 5, urgent: false, active: false}, {rate: 99.99, urgent: true, active: true}]}}, {borrower: {accounts: [{active: false, exposure: 1, grade: true, margin: 1, rate: 5, urgent: false}, {active: true, exposure: 1, grade: true, margin: 1, rate: 99.99, urgent: true}], balance: 1000, flagged: true, label: "Zed", points: "Zed", rate: -1, urgent: false, weight: 99999999999999999999}, level: 104.99, surcharge: 99999999999999999999, tag: false}], + [{borrower: {balance: 100, flagged: true, urgent: false, rate: -500, label: "é ü", weight: 123456789.123, accounts: []}}, {borrower: {accounts: [], balance: 100, flagged: true, label: "é ü", points: "é ü", rate: -500, urgent: false, weight: 123456789.123}, level: 0, surcharge: 123456789.123, tag: false}], + [{borrower: {balance: -500, flagged: false, urgent: false, rate: 162, label: "none", weight: 1000, accounts: []}}, {borrower: {accounts: [], balance: -500, flagged: false, label: "none", points: "none", rate: 162, urgent: false, weight: 1000}, level: 0, surcharge: 1000, tag: false}], + [{borrower: {balance: 0.000001, flagged: false, urgent: false, label: "Oslo", weight: 0.5, accounts: [{rate: 18, urgent: true, active: true}, {rate: -500, urgent: false}, {rate: 1000000, urgent: false}]}}, {borrower: {accounts: [{active: true, exposure: 1, grade: true, margin: 1, rate: 18, urgent: true}, {exposure: 1, grade: true, margin: 1, rate: -500, urgent: false}, {exposure: 1, grade: true, margin: 1, rate: 1000000, urgent: false}], balance: 0.000001, flagged: false, label: "Oslo", points: "Oslo", urgent: false, weight: 0.5}, surcharge: 0.5}], + [{borrower: {balance: 7.25, flagged: false, urgent: true, rate: 0.1, label: "none", weight: 123456789.123, accounts: []}}, {borrower: {accounts: [], balance: 7.25, flagged: false, label: "none", points: "none", rate: 0.1, urgent: true, weight: 123456789.123}, level: 0, surcharge: 123456789.123, tag: true}], + [{borrower: {balance: 18, flagged: true, urgent: true, rate: 1000000, label: "Oslo", weight: 7.25, accounts: [{rate: 7.25, urgent: true, active: false}]}}, {borrower: {accounts: [{active: false, exposure: 1, grade: true, margin: 1, rate: 7.25, urgent: true}], balance: 18, flagged: true, label: "Oslo", points: "Oslo", rate: 1000000, urgent: true, weight: 7.25}, surcharge: 7.25}], + ], +} + +// seed 333000 (attempt 0) +{ + name: "a 31: tenant/lines: 1 assertion, 3 expression, 2 match, 1 table; 2 root, 5 per-member, 0 top-level computed", + policy: { + models: {tenant: {price: "number?", since: "date", dueDate: "date", verified: "boolean?", country: "string", lines: "line[]"}, line: {income: "number", code: "string?", country: "string", openedAt: "date"}}, + blocks: [ + {expression: "line.margin", value: "len(line.country)"}, + {assertion: "line.capped", conditions: [["or", "not ((tenant.verified ?? false))", 0], ["and", "(line.margin >= (tenant.price ?? 0) and not ((tenant.verified ?? false)))", 2], ["and", "(min(map(tenant.lines, #.margin)) ?? 0) != line.income", 0], ["and", "sum(map(tenant.lines, 1000)) < line.income", 1], ["and", "line.openedAt.month() == line.margin", 0]]}, + {expression: "line.review", value: "(1.5 * line.margin) != line.income"}, + {expression: "tenant.level", value: "((tenant.verified ?? false) ? tenant.country : tenant.country)"}, + {table: "t5", inputs: ["tenant.verified", "tenant.country", "(2) / (abs((tenant.price ?? 0)) + 1)"], outputs: ["tenant.ok"], rules: [ + ["false", "$ != 'ok'", ">= 250", "tenant.country"], + ["", "", "> 5", ""], + ]}, + {match: "line.quota", arms: [["line.margin < (tenant.price ?? 0)", "(tenant.price ?? 0) < (tenant.price ?? 0)"], ["tenant.price == null", "line.review"], ["", "some(tenant.lines, (#.review and #.capped))"]]}, + {match: "line.surcharge", arms: [["line.margin > line.income", "string(sum(map(tenant.lines, #.income)))"], ["", "(line.country + '-' + tenant.level)"]]}, + ], + }, + cases: [ + [{tenant: {price: 0.5, since: "2024-02-29", dueDate: "2024-01-01", verified: false, country: "Oslo", lines: [{income: 1000, code: null, country: " pad ", openedAt: "2024-01-01"}, {income: 0.5, code: null, country: "A1", openedAt: "1990-06-15"}]}}, {tenant: {country: "Oslo", dueDate: "2024-01-01", level: "Oslo", lines: [{capped: false, code: null, country: " pad ", income: 1000, margin: 6, openedAt: "2024-01-01", quota: false, review: true, surcharge: " pad -Oslo"}, {capped: false, code: null, country: "A1", income: 0.5, margin: 2, openedAt: "1990-06-15", quota: false, review: true, surcharge: "1000.5"}], ok: null, price: 0.5, since: "2024-02-29", verified: false}}], + [{tenant: {price: 18, since: "1990-06-15", dueDate: "2024-01-01", verified: true, country: "ok", lines: []}}, {tenant: {country: "ok", dueDate: "2024-01-01", lines: [], ok: null, price: 18, since: "1990-06-15", verified: true}}], + [{tenant: {price: null, since: "2025-03-20T10:15:30Z", dueDate: "2025-03-20", verified: false, country: "A1", lines: [{income: 99.99, country: "DE", openedAt: "2030-12-31"}]}}, {tenant: {country: "A1", dueDate: "2025-03-20", level: "A1", lines: [{country: "DE", income: 99.99, margin: 2, openedAt: "2030-12-31", quota: true, review: true, surcharge: "DE-A1"}], ok: null, price: null, since: "2025-03-20T10:15:30Z", verified: false}}], + [{tenant: {price: null, since: "2025-03-20T10:15:30Z", dueDate: "2024-02-29", verified: false, country: "é ü", lines: [{income: 250, code: "gold", country: "Oslo", openedAt: "1990-06-15"}, {income: -0.01, country: "DE", openedAt: "1990-06-15"}]}}, {tenant: {country: "é ü", dueDate: "2024-02-29", level: "é ü", lines: [{code: "gold", country: "Oslo", income: 250, margin: 4, openedAt: "1990-06-15", quota: true, review: true, surcharge: "Oslo-é ü"}, {country: "DE", income: -0.01, margin: 2, openedAt: "1990-06-15", quota: true, review: true, surcharge: "249.99"}], ok: null, price: null, since: "2025-03-20T10:15:30Z", verified: false}}], + [{tenant: {price: 100, since: "2030-12-31", dueDate: "2025-03-20T10:15:30Z", verified: true, country: "VIP", lines: [{income: 0.5, code: "gold", country: "-", openedAt: "2000-01-01"}], extraField: 1}}, {tenant: {country: "VIP", dueDate: "2025-03-20T10:15:30Z", extraField: 1, lines: [{code: "gold", country: "-", income: 0.5, margin: 1, openedAt: "2000-01-01", quota: false, surcharge: "0.5"}], ok: null, price: 100, since: "2030-12-31", verified: true}}], + [{tenant: {price: 0.1, since: "2030-12-31", dueDate: "2025-03-20", verified: false, country: "US", lines: [{income: 1e3, code: "abc", country: "a", openedAt: "2000-01-01"}, {income: 18, code: "", country: "ok", openedAt: "2024-01-01"}, {income: 0.5, code: "ok", country: "retail", openedAt: "2024-01-01"}, {income: 2, code: "ok", country: "retail", openedAt: "2025-03-20"}]}}, {tenant: {country: "US", dueDate: "2025-03-20", level: "US", lines: [{capped: false, code: "abc", country: "a", income: 1000, margin: 1, openedAt: "2000-01-01", quota: false, review: true, surcharge: "a-US"}, {capped: false, code: "", country: "ok", income: 18, margin: 2, openedAt: "2024-01-01", quota: false, review: true, surcharge: "ok-US"}, {capped: false, code: "ok", country: "retail", income: 0.5, margin: 6, openedAt: "2024-01-01", quota: false, review: true, surcharge: "1020.5"}, {capped: false, code: "ok", country: "retail", income: 2, margin: 6, openedAt: "2025-03-20", quota: false, review: true, surcharge: "1020.5"}], ok: null, price: 0.1, since: "2030-12-31", verified: false}}], + [{tenant: {price: -1, since: "2025-03-20", dueDate: "2024-01-01", verified: true, country: "Oslo", lines: [{income: 0.000001, code: " pad ", country: "VIP", openedAt: "2000-01-01"}, {income: 18, code: " pad ", country: "DE", openedAt: "2024-01-01"}, {income: 1.5, code: "日本", country: "DE", openedAt: "2025-03-20T10:15:30Z"}, {income: 99.99, code: "3.5", country: "Zed", openedAt: "2024-01-01"}]}}, {tenant: {country: "Oslo", dueDate: "2024-01-01", level: "Oslo", lines: [{capped: false, code: " pad ", country: "VIP", income: 0.000001, margin: 3, openedAt: "2000-01-01", quota: false, review: true, surcharge: "119.490001"}, {capped: false, code: " pad ", country: "DE", income: 18, margin: 2, openedAt: "2024-01-01", quota: false, review: true, surcharge: "DE-Oslo"}, {capped: false, code: "日本", country: "DE", income: 1.5, margin: 2, openedAt: "2025-03-20T10:15:30Z", quota: false, review: true, surcharge: "119.490001"}, {capped: false, code: "3.5", country: "Zed", income: 99.99, margin: 3, openedAt: "2024-01-01", quota: false, review: true, surcharge: "Zed-Oslo"}], ok: null, price: -1, since: "2025-03-20", verified: true}}], + [{tenant: {price: null, since: "2024-01-01", dueDate: "2025-03-20", verified: true, country: "O'Neil", lines: [{income: 1e3, code: null, country: "O'Neil", openedAt: "2025-03-20"}, {income: 244, code: "gold", country: "Oslo", openedAt: "2025-03-20T10:15:30Z"}]}}, {tenant: {country: "O'Neil", dueDate: "2025-03-20", level: "O'Neil", lines: [{code: null, country: "O'Neil", income: 1000, margin: 6, openedAt: "2025-03-20", quota: true, review: true, surcharge: "O'Neil-O'Neil"}, {code: "gold", country: "Oslo", income: 244, margin: 4, openedAt: "2025-03-20T10:15:30Z", quota: true, review: true, surcharge: "Oslo-O'Neil"}], ok: null, price: null, since: "2024-01-01", verified: true}}], + [{tenant: {price: 0, since: "2030-12-31", verified: true, country: "x-y", lines: []}}, {tenant: {country: "x-y", lines: [], ok: null, price: 0, since: "2030-12-31", verified: true}}], + [{tenant: {since: "2025-03-20", dueDate: "2025-03-20", verified: false, country: "ok", lines: [{income: 7.25, code: " pad ", country: "12", openedAt: "2030-12-31"}, {income: 7.25, code: "é ü", country: "Zed", openedAt: "1990-06-15"}]}}, {tenant: {country: "ok", dueDate: "2025-03-20", level: "ok", lines: [{code: " pad ", country: "12", income: 7.25, margin: 2, openedAt: "2030-12-31", quota: true, review: true, surcharge: "12-ok"}, {code: "é ü", country: "Zed", income: 7.25, margin: 3, openedAt: "1990-06-15", quota: true, review: true, surcharge: "Zed-ok"}], ok: null, since: "2025-03-20", verified: false}}], + [{tenant: {price: 5, since: "2025-03-20T10:15:30Z", dueDate: "2025-03-20T10:15:30Z", verified: true, country: "12", lines: [{income: 2.50, code: "retail", country: "ok", openedAt: "2024-01-01"}]}}, {tenant: {country: "12", dueDate: "2025-03-20T10:15:30Z", level: "12", lines: [{code: "retail", country: "ok", income: 2.50, margin: 2, openedAt: "2024-01-01", quota: false, surcharge: "ok-12"}], ok: null, price: 5, since: "2025-03-20T10:15:30Z", verified: true}}], + [{tenant: {price: 0.000001, since: "2024-02-29", dueDate: "2030-12-31", verified: true, country: "Zed", lines: [{income: 123456789.123, code: "x-y", country: "A1", openedAt: "2025-03-20T10:15:30Z"}]}}, {tenant: {country: "Zed", dueDate: "2030-12-31", level: "Zed", lines: [{capped: false, code: "x-y", country: "A1", income: 123456789.123, margin: 2, openedAt: "2025-03-20T10:15:30Z", quota: false, review: true, surcharge: "A1-Zed"}], ok: null, price: 0.000001, since: "2024-02-29", verified: true}}], + [{tenant: {price: 5, since: "2030-12-31", dueDate: "2024-01-01", verified: true, country: "-", lines: [{income: 1000000, code: "日本", country: "12", openedAt: "2030-12-31"}]}}, {tenant: {country: "-", dueDate: "2024-01-01", level: "-", lines: [{code: "日本", country: "12", income: 1000000, margin: 2, openedAt: "2030-12-31", quota: false, surcharge: "12--"}], ok: null, price: 5, since: "2030-12-31", verified: true}}], + [{tenant: {price: 0.5, since: "2024-02-29", dueDate: "1990-06-15", verified: false, country: "ok", lines: [{income: 123456789.123, code: "Zed", country: "gold", openedAt: "1990-06-15"}, {income: 1, code: "ok", country: "gold", openedAt: "2000-01-01"}, {income: 1, code: "ok", country: "gold", openedAt: "2024-02-29"}]}}, {tenant: {country: "ok", dueDate: "1990-06-15", level: "ok", lines: [{capped: false, code: "Zed", country: "gold", income: 123456789.123, margin: 4, openedAt: "1990-06-15", quota: false, review: true, surcharge: "gold-ok"}, {capped: false, code: "ok", country: "gold", income: 1, margin: 4, openedAt: "2000-01-01", quota: false, review: true, surcharge: "123456791.123"}, {capped: false, code: "ok", country: "gold", income: 1, margin: 4, openedAt: "2024-02-29", quota: false, review: true, surcharge: "123456791.123"}], ok: null, price: 0.5, since: "2024-02-29", verified: false}}], + [{tenant: {price: 250, since: "2030-12-31", dueDate: "2025-03-20T10:15:30Z", verified: true, country: "O'Neil", lines: [{income: true, code: "-", country: "12", openedAt: "2030-12-31"}]}}, "!error: InputValidationFailed"], + [{tenant: {price: 18, since: "2000-01-01", dueDate: "2024-01-01", verified: true, country: "", lines: [{income: -0, code: "US", country: "A1", openedAt: "2025-03-20T10:15:30Z"}, {income: 123456789.123, code: "x-y", country: "ok", openedAt: "1990-06-15"}, {income: 123456789.123, code: "é ü", country: "", openedAt: "2025-03-20T10:15:30Z"}, {income: 1000, code: "12", country: "gold", openedAt: "2030-12-31"}]}}, {tenant: {country: "", dueDate: "2024-01-01", level: "", lines: [{code: "US", country: "A1", income: 0, margin: 2, openedAt: "2025-03-20T10:15:30Z", quota: false, surcharge: "246914578.246"}, {code: "x-y", country: "ok", income: 123456789.123, margin: 2, openedAt: "1990-06-15", quota: false, surcharge: "ok-"}, {code: "é ü", country: "", income: 123456789.123, margin: 0, openedAt: "2025-03-20T10:15:30Z", quota: false, surcharge: "-"}, {code: "12", country: "gold", income: 1000, margin: 4, openedAt: "2030-12-31", quota: false, surcharge: "gold-"}], ok: null, price: 18, since: "2000-01-01", verified: true}}], + [{tenant: {since: "2025-03-20", dueDate: "2025-03-20", verified: true, country: "Zed", lines: [{income: 250, code: "a", country: "retail", openedAt: "1990-06-15"}, {income: 5, country: "NL", openedAt: "2025-03-20T10:15:30Z"}, {income: 100, code: null, country: "Oslo", openedAt: "1990-06-15"}, {income: 2, code: null, country: "a", openedAt: "2030-12-31"}, {income: 99999999999999999999, country: "a-b-c", openedAt: "1990-06-15"}]}}, {tenant: {country: "Zed", dueDate: "2025-03-20", level: "Zed", lines: [{code: "a", country: "retail", income: 250, margin: 6, openedAt: "1990-06-15", quota: true, review: true, surcharge: "retail-Zed"}, {country: "NL", income: 5, margin: 2, openedAt: "2025-03-20T10:15:30Z", quota: true, review: true, surcharge: "NL-Zed"}, {code: null, country: "Oslo", income: 100, margin: 4, openedAt: "1990-06-15", quota: true, review: true, surcharge: "Oslo-Zed"}, {code: null, country: "a", income: 2, margin: 1, openedAt: "2030-12-31", quota: true, review: true, surcharge: "a-Zed"}, {country: "a-b-c", income: 99999999999999999999, margin: 5, openedAt: "1990-06-15", quota: true, review: true, surcharge: "a-b-c-Zed"}], ok: null, since: "2025-03-20", verified: true}}], + [{tenant: {price: 1e3, dueDate: "2000-01-01", verified: false, country: "A1", lines: [{income: -500, code: "retail", country: "a", openedAt: "2024-02-29"}]}}, {tenant: {country: "A1", dueDate: "2000-01-01", lines: [{code: "retail", country: "a", income: -500, margin: 1, openedAt: "2024-02-29", quota: false, surcharge: "-500"}], ok: null, price: 1000, verified: false}}], + [{tenant: {price: true, since: "2000-01-01", dueDate: "2000-01-01", verified: false, country: " pad ", lines: []}}, "!error: InputValidationFailed"], + [{tenant: {price: -0.01, since: "2000-01-01", dueDate: "2025-03-20", verified: false, country: "O'Neil", lines: [{income: 250, country: " pad ", openedAt: "2030-12-31"}, {income: 0.000001, code: null, country: "US", openedAt: "2025-03-20"}, {income: 1.5, code: "gold", country: "-", openedAt: "2030-12-31"}, {income: -0, country: "O'Neil", openedAt: "2025-03-20T10:15:30Z"}]}}, {tenant: {country: "O'Neil", dueDate: "2025-03-20", level: "O'Neil", lines: [{capped: false, country: " pad ", income: 250, margin: 6, openedAt: "2030-12-31", quota: false, review: true, surcharge: " pad -O'Neil"}, {capped: false, code: null, country: "US", income: 0.000001, margin: 2, openedAt: "2025-03-20", quota: false, review: true, surcharge: "251.500001"}, {capped: false, code: "gold", country: "-", income: 1.5, margin: 1, openedAt: "2030-12-31", quota: false, review: false, surcharge: "--O'Neil"}, {capped: false, country: "O'Neil", income: 0, margin: 6, openedAt: "2025-03-20T10:15:30Z", quota: false, review: true, surcharge: "251.500001"}], ok: null, price: -0.01, since: "2000-01-01", verified: false}}], + [{tenant: {price: 10, since: "2030-12-31", dueDate: "2025-03-20", verified: null, country: "日本", lines: [{income: 1, code: "a", country: "DE", openedAt: "2000-01-01"}, {income: 2, country: "a", openedAt: "2024-02-29"}, {income: -0.5, code: null, country: "a", openedAt: "2024-01-01"}, {income: 2.50, code: "12", country: "ok", openedAt: "2025-03-20T10:15:30Z"}]}}, {tenant: {country: "日本", dueDate: "2025-03-20", level: "日本", lines: [{code: "a", country: "DE", income: 1, margin: 2, openedAt: "2000-01-01", quota: false, surcharge: "5.00"}, {country: "a", income: 2, margin: 1, openedAt: "2024-02-29", quota: false, surcharge: "a-日本"}, {code: null, country: "a", income: -0.5, margin: 1, openedAt: "2024-01-01", quota: false, surcharge: "5.00"}, {code: "12", country: "ok", income: 2.50, margin: 2, openedAt: "2025-03-20T10:15:30Z", quota: false, surcharge: "ok-日本"}], ok: null, price: 10, since: "2030-12-31", verified: null}}], + [{tenant: {price: 5, since: "2000-01-01", dueDate: "2000-01-01", verified: false, country: "é ü", lines: [{income: 1e3, code: "3.5", country: "O'Neil", openedAt: "1990-06-15"}]}}, {tenant: {country: "é ü", dueDate: "2000-01-01", level: "é ü", lines: [{capped: false, code: "3.5", country: "O'Neil", income: 1000, margin: 6, openedAt: "1990-06-15", quota: false, review: true, surcharge: "O'Neil-é ü"}], ok: null, price: 5, since: "2000-01-01", verified: false}}], + [{tenant: {price: 1, since: "2024-01-01", dueDate: "2024-02-29", verified: true, country: "3.5", lines: [{income: 99999999999999999999, code: "ok", country: "gold", openedAt: "2024-02-29"}]}}, {tenant: {country: "3.5", dueDate: "2024-02-29", level: "3.5", lines: [{capped: false, code: "ok", country: "gold", income: 99999999999999999999, margin: 4, openedAt: "2024-02-29", quota: false, review: true, surcharge: "gold-3.5"}], ok: null, price: 1, since: "2024-01-01", verified: true}}], + [{tenant: {price: -1, since: "1990-06-15", dueDate: null, verified: true, country: "gold", lines: [{income: 250, code: "ok", country: "gold", openedAt: "2024-02-29"}, {income: -0.5, code: "", country: "gold", openedAt: "2024-01-01"}]}}, {tenant: {country: "gold", dueDate: null, level: "gold", lines: [{capped: false, code: "ok", country: "gold", income: 250, margin: 4, openedAt: "2024-02-29", quota: false, review: true, surcharge: "gold-gold"}, {capped: false, code: "", country: "gold", income: -0.5, margin: 4, openedAt: "2024-01-01", quota: false, review: true, surcharge: "249.5"}], ok: null, price: -1, since: "1990-06-15", verified: true}}], + [{tenant: {price: 2, since: "2024-01-01", dueDate: "2025-03-20T10:15:30Z", verified: true, country: "US", lines: [{income: 5, code: "ok", country: "O'Neil", openedAt: "2025-03-20"}]}}, {tenant: {country: "US", dueDate: "2025-03-20T10:15:30Z", lines: [{capped: false, code: "ok", country: "O'Neil", income: 5, margin: 6, openedAt: "2025-03-20", quota: false, review: true, surcharge: "5"}], ok: null, price: 2, since: "2024-01-01", verified: true}}], + [{tenant: {price: 99.99, since: "2000-01-01", dueDate: "1990-06-15", country: "gold", lines: [{income: 0.1, code: "gold", country: "x-y", openedAt: "2025-03-20T10:15:30Z"}, {income: 250, code: null, country: "NL", openedAt: "2024-01-01"}]}}, {tenant: {country: "gold", dueDate: "1990-06-15", level: "gold", lines: [{code: "gold", country: "x-y", income: 0.1, margin: 3, openedAt: "2025-03-20T10:15:30Z", quota: false, surcharge: "250.1"}, {code: null, country: "NL", income: 250, margin: 2, openedAt: "2024-01-01", quota: false, surcharge: "NL-gold"}], ok: null, price: 99.99, since: "2000-01-01"}}], + [{tenant: {since: "2030-12-31", dueDate: "2025-03-20", country: "a", lines: [{income: 1e3, country: "A1", openedAt: "2024-01-01"}, {income: 1, code: "O'Neil", country: "A1", openedAt: "2024-01-01"}]}}, {tenant: {country: "a", dueDate: "2025-03-20", level: "a", lines: [{country: "A1", income: 1000, margin: 2, openedAt: "2024-01-01", quota: true, review: true, surcharge: "A1-a"}, {code: "O'Neil", country: "A1", income: 1, margin: 2, openedAt: "2024-01-01", quota: true, review: true, surcharge: "1001"}], ok: null, since: "2030-12-31"}}], + [{tenant: {price: 5, since: "2025-03-20T10:15:30Z", dueDate: "2024-02-29", verified: "true", country: "gold", lines: [{income: 99.99, code: "gold", country: "", openedAt: "2025-03-20"}, {income: 1.5, code: "Zed", country: "gold", openedAt: "2030-12-31"}, {income: 2.50, code: "-", country: "a", openedAt: "2000-01-01"}, {income: 18, code: "日本", country: "gold", openedAt: "1990-06-15"}, {income: 0.1, code: " pad ", country: "A1", openedAt: "2024-01-01"}]}}, "!error: InputValidationFailed"], + [{tenant: {price: 18, since: "2025-03-20", dueDate: "2025-03-20T10:15:30Z", verified: false, country: "A1", lines: [{income: 250, code: "abc", country: "retail", openedAt: "1990-06-15"}, {income: 2.50, code: "abc", country: "NL", openedAt: "2025-03-20"}]}}, {tenant: {country: "A1", dueDate: "2025-03-20T10:15:30Z", level: "A1", lines: [{code: "abc", country: "retail", income: 250, margin: 6, openedAt: "1990-06-15", quota: false, surcharge: "retail-A1"}, {code: "abc", country: "NL", income: 2.50, margin: 2, openedAt: "2025-03-20", quota: false, surcharge: "NL-A1"}], ok: null, price: 18, since: "2025-03-20", verified: false}}], + [{tenant: {price: 250, since: "2025-03-20T10:15:30Z", dueDate: "2000-01-01", verified: false, country: "3.5", lines: []}}, {tenant: {country: "3.5", dueDate: "2000-01-01", lines: [], ok: null, price: 250, since: "2025-03-20T10:15:30Z", verified: false}}], + ], +} + +// seed 333100 (attempt 0) +{ + name: "a 32: borrower/parcels: 1 expression, 1 match, 2 table; 3 root, 0 per-member, 3 top-level computed", + policy: { + models: {borrower: {score: "number?", dueDate: "date", kind: "string(retail|corporate)", name: "string?", vip: "boolean", parcels: "parcel[]"}, parcel: {limit: "number", country: "string", days: "number", plan: "string(basic|plus|premium|trial)"}}, + blocks: [ + {table: "t1", inputs: ["borrower.vip"], outputs: ["share", "exposure", "review"], rules: [ + ["false", "0.5", "(borrower.name ?? '')", "(borrower.score ?? 0)"], + ["", "(borrower.score ?? 0)", "(borrower.name ?? '')", "(borrower.score ?? 0)"], + ]}, + {match: "borrower.decision", arms: [["borrower.score != null", "(borrower.name ?? '')"], ["(review ?? 0) > (review ?? 0)", "(borrower.name ?? '')"], ["", "(borrower.vip ? (borrower.name ?? '') : (exposure ?? ''))"]]}, + {table: "t3", hit: "collect", inputs: ["sum(map(borrower.parcels, #.limit))", null, "borrower.vip"], outputs: ["borrower.health"], rules: [ + ["", "(borrower.score ?? 0) == (review ?? 0)", "true", "(share ?? 0)"], + ["", "(borrower.vip and borrower.vip)", "true", "(share ?? 0)"], + ["", "", "", "(borrower.score ?? 0)"], + ]}, + {expression: "borrower.flag", value: "(exposure ?? '')"}, + ], + }, + cases: [ + [{borrower: {score: null, dueDate: "2024-02-29", kind: "corporate", name: null, vip: true, parcels: [{limit: -0.5, country: "DE", days: -0, plan: "trial"}, {limit: 99999999999999999999, country: "Zed", days: 499, plan: "trial"}]}}, {borrower: {decision: "", dueDate: "2024-02-29", flag: "", health: [0, 0, 0], kind: "corporate", name: null, parcels: [{country: "DE", days: 0, limit: -0.5, plan: "trial"}, {country: "Zed", days: 499, limit: 99999999999999999999, plan: "trial"}], score: null, vip: true}, exposure: "", review: 0, share: 0}], + [{borrower: {score: -0, dueDate: "2024-01-01", kind: "retail", name: "NL", vip: false, parcels: []}}, {borrower: {decision: "NL", dueDate: "2024-01-01", flag: "NL", health: [0], kind: "retail", name: "NL", parcels: [], score: 0, vip: false}, exposure: "NL", review: 0, share: 0.5}], + [{borrower: {score: -0.01, dueDate: "2024-02-29", kind: "retail", name: "Oslo", vip: true, parcels: [{limit: 0.000001, country: "VIP", days: 123456789.123, plan: "basic"}]}}, {borrower: {decision: "Oslo", dueDate: "2024-02-29", flag: "Oslo", health: [-0.01, -0.01, -0.01], kind: "retail", name: "Oslo", parcels: [{country: "VIP", days: 123456789.123, limit: 0.000001, plan: "basic"}], score: -0.01, vip: true}, exposure: "Oslo", review: -0.01, share: -0.01}], + [{borrower: {score: 10, dueDate: "2025-03-20T10:15:30Z", kind: "retail", name: "3.5", vip: true, parcels: [{limit: 0.000001, country: "O'Neil", days: -0.01, plan: "basic"}, {limit: 1000000, country: "", days: 0.000001, plan: "trial"}, {limit: 10, country: "a", days: 5, plan: "basic"}]}}, {borrower: {decision: "3.5", dueDate: "2025-03-20T10:15:30Z", flag: "3.5", health: [10, 10, 10], kind: "retail", name: "3.5", parcels: [{country: "O'Neil", days: -0.01, limit: 0.000001, plan: "basic"}, {country: "", days: 0.000001, limit: 1000000, plan: "trial"}, {country: "a", days: 5, limit: 10, plan: "basic"}], score: 10, vip: true}, exposure: "3.5", review: 10, share: 10}], + [{borrower: {score: -0.5, dueDate: "1990-06-15", kind: "retail", name: "3.5", vip: false, parcels: [], extraField: {nested: true}}}, {borrower: {decision: "3.5", dueDate: "1990-06-15", extraField: {nested: true}, flag: "3.5", health: [-0.5], kind: "retail", name: "3.5", parcels: [], score: -0.5, vip: false}, exposure: "3.5", review: -0.5, share: 0.5}], + [{borrower: {score: 1, dueDate: "2030-12-31", kind: "retail", name: "x-y", vip: true, parcels: [{limit: 0.5, country: "VIP", days: 0.5, plan: "basic"}, {limit: 5, country: "-", days: -0.5, plan: "premium"}, {limit: 2.50, country: "NL", days: 10, plan: "basic"}]}}, {borrower: {decision: "x-y", dueDate: "2030-12-31", flag: "x-y", health: [1, 1, 1], kind: "retail", name: "x-y", parcels: [{country: "VIP", days: 0.5, limit: 0.5, plan: "basic"}, {country: "-", days: -0.5, limit: 5, plan: "premium"}, {country: "NL", days: 10, limit: 2.50, plan: "basic"}], score: 1, vip: true}, exposure: "x-y", review: 1, share: 1}], + [{borrower: {score: null, dueDate: "2025-03-20", kind: "corporate", name: null, vip: true, parcels: [{limit: -0.5, country: "12", days: 10, plan: "trial"}, {limit: 10, country: "O'Neil", days: 1, plan: "premium"}]}}, {borrower: {decision: "", dueDate: "2025-03-20", flag: "", health: [0, 0, 0], kind: "corporate", name: null, parcels: [{country: "12", days: 10, limit: -0.5, plan: "trial"}, {country: "O'Neil", days: 1, limit: 10, plan: "premium"}], score: null, vip: true}, exposure: "", review: 0, share: 0}], + [{borrower: {score: 2.50, dueDate: null, kind: "retail", name: "US", vip: true, parcels: [{limit: 1, country: "O'Neil", days: 0.000001, plan: "plus"}, {limit: 65, country: "12", days: 65, plan: "basic"}, {limit: 18, country: "-", days: 1, plan: "basic"}, {limit: 0.5, country: "retail", days: 1, plan: "basic"}]}}, {borrower: {decision: "US", dueDate: null, flag: "US", health: [2.50, 2.50, 2.50], kind: "retail", name: "US", parcels: [{country: "O'Neil", days: 0.000001, limit: 1, plan: "plus"}, {country: "12", days: 65, limit: 65, plan: "basic"}, {country: "-", days: 1, limit: 18, plan: "basic"}, {country: "retail", days: 1, limit: 0.5, plan: "basic"}], score: 2.50, vip: true}, exposure: "US", review: 2.50, share: 2.50}], + [{borrower: {score: null, dueDate: "2000-01-01", kind: "retail", name: "VIP", vip: true, parcels: [{limit: 0.000001, country: "gold", days: 2, plan: "trial"}, {limit: 1, country: "12", days: 99999999999999999999, plan: "basic"}, {limit: 0.5, country: "abc", days: 99999999999999999999, plan: "basic"}, {limit: 0, country: "3.5", days: 5, plan: "basic"}]}}, {borrower: {decision: "VIP", dueDate: "2000-01-01", flag: "VIP", health: [0, 0, 0], kind: "retail", name: "VIP", parcels: [{country: "gold", days: 2, limit: 0.000001, plan: "trial"}, {country: "12", days: 99999999999999999999, limit: 1, plan: "basic"}, {country: "abc", days: 99999999999999999999, limit: 0.5, plan: "basic"}, {country: "3.5", days: 5, limit: 0, plan: "basic"}], score: null, vip: true}, exposure: "VIP", review: 0, share: 0}], + [{borrower: {score: 65, dueDate: "2024-01-01", kind: "retail", name: "a", vip: true, parcels: [{limit: 99.99, country: "Oslo", days: 250, plan: "premium"}, {limit: 0, country: "US", days: 123456789.123, plan: "plus"}, {limit: -0.01, country: " pad ", days: 7.25, plan: "premium"}]}}, {borrower: {decision: "a", dueDate: "2024-01-01", flag: "a", health: [65, 65, 65], kind: "retail", name: "a", parcels: [{country: "Oslo", days: 250, limit: 99.99, plan: "premium"}, {country: "US", days: 123456789.123, limit: 0, plan: "plus"}, {country: " pad ", days: 7.25, limit: -0.01, plan: "premium"}], score: 65, vip: true}, exposure: "a", review: 65, share: 65}], + [{borrower: {score: 78, dueDate: "2000-01-01", kind: "corporate", name: false, vip: false, parcels: [{limit: 0, country: "O'Neil", days: 18, plan: "premium"}]}}, "!error: InputValidationFailed"], + [{borrower: {score: 100, dueDate: "2000-01-01", kind: "retail", name: "x-y", vip: true, parcels: [{limit: 1, country: "retail", days: 1, plan: "premium"}]}}, {borrower: {decision: "x-y", dueDate: "2000-01-01", flag: "x-y", health: [100, 100, 100], kind: "retail", name: "x-y", parcels: [{country: "retail", days: 1, limit: 1, plan: "premium"}], score: 100, vip: true}, exposure: "x-y", review: 100, share: 100}], + ], +} + +// seed 333200 (attempt 0) +{ + name: "a 33: account/companies: 3 assertion, 2 match; 2 root, 1 per-member, 2 top-level computed", + policy: { + models: {account: {score: "number", status: "string(open|closed|pending)?", urgent: "boolean", label: "string?", plan: "string(basic|plus|premium|trial)?", verified: "boolean", companies: "company[]"}, company: {weight: "number?", insured: "boolean", openedAt: "date"}}, + blocks: [ + {assertion: "discount", conditions: [["or", "account.plan == null", 1], ["and", "account.score > account.score", 1]]}, + {match: "account.points", arms: [["account.score > account.score", "account.score"], ["some(account.companies, #.weight != null)", "(len(account.companies) * (discount ? 250 : account.score))"], ["", "account.score"]]}, + {assertion: "account.bonus", conditions: ["account.points <= account.points", ["or", "(account.points <= account.points or (account.status ?? '') in ['closed', 'pending'])", 1], ["or", "account.score <= 3", 0]]}, + {assertion: "company.segment", conditions: [["or", "account.score >= account.points", 2], ["or", "some(account.companies, (#.weight ?? 0) > (#.weight ?? 0))", 1]]}, + {match: "total", arms: [["none(account.companies, (#.weight ?? 0) == (#.weight ?? 0))", "(account.label ?? '')"], ["", "(account.label ?? '')"]]}, + ], + }, + cases: [ + [{account: {score: 18, status: "open", urgent: true, label: "retail", plan: "plus", verified: false, companies: [{weight: -1, insured: true, openedAt: "2025-03-20"}, {weight: 1000, insured: false, openedAt: "2025-03-20"}], extraField: {nested: true}}}, {account: {bonus: true, companies: [{insured: true, openedAt: "2025-03-20", segment: false, weight: -1}, {insured: false, openedAt: "2025-03-20", segment: false, weight: 1000}], extraField: {nested: true}, label: "retail", plan: "plus", points: 36, score: 18, status: "open", urgent: true, verified: false}, discount: false, total: "retail"}], + [{account: {score: 65, status: "pending", urgent: true, label: null, plan: null, verified: false, companies: []}}, {account: {bonus: true, companies: [], label: null, plan: null, points: 65, score: 65, status: "pending", urgent: true, verified: false}, total: ""}], + [{account: {score: 100, urgent: false, label: "abc", plan: "trial", verified: false, companies: [{weight: null, insured: true, openedAt: "1990-06-15"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "1990-06-15", segment: true, weight: null}], label: "abc", plan: "trial", points: 100, score: 100, urgent: false, verified: false}, total: "abc"}], + [{account: {score: 99.99, status: "open", urgent: false, label: "NL", verified: true, companies: [{insured: false, openedAt: "2030-12-31"}, {weight: 2.50, insured: true, openedAt: "2030-12-31"}, {insured: true, openedAt: "2030-12-31"}, {weight: 65, insured: false, openedAt: "1990-06-15"}]}}, {account: {bonus: true, companies: [{insured: false, openedAt: "2030-12-31", segment: false}, {insured: true, openedAt: "2030-12-31", segment: false, weight: 2.50}, {insured: true, openedAt: "2030-12-31", segment: false}, {insured: false, openedAt: "1990-06-15", segment: false, weight: 65}], label: "NL", points: 1000, score: 99.99, status: "open", urgent: false, verified: true}, discount: true, total: "NL"}], + [{account: {score: 123456789.123, urgent: true, plan: "premium", verified: false, companies: [{weight: null, insured: false, openedAt: "2024-01-01"}, {weight: 426, insured: false, openedAt: "2000-01-01"}, {weight: 65, insured: false, openedAt: "2030-12-31"}, {insured: false, openedAt: "2025-03-20T10:15:30Z"}, {weight: -1, insured: true, openedAt: "2030-12-31"}]}}, {account: {bonus: true, companies: [{insured: false, openedAt: "2024-01-01", segment: false, weight: null}, {insured: false, openedAt: "2000-01-01", segment: false, weight: 426}, {insured: false, openedAt: "2030-12-31", segment: false, weight: 65}, {insured: false, openedAt: "2025-03-20T10:15:30Z", segment: false}, {insured: true, openedAt: "2030-12-31", segment: false, weight: -1}], plan: "premium", points: 617283945.615, score: 123456789.123, urgent: true, verified: false}, discount: false, total: ""}], + [{account: {score: 99999999999999999999, status: "pending", urgent: false, label: "", plan: "basic", verified: false, companies: [], extraField: 1}}, {account: {bonus: true, companies: [], extraField: 1, label: "", plan: "basic", points: 99999999999999999999, score: 99999999999999999999, status: "pending", urgent: false, verified: false}, total: ""}], + [{account: {score: 1e3, status: "open", urgent: true, label: null, plan: null, verified: false, companies: [{weight: 7.25, insured: false, openedAt: "2000-01-01"}, {weight: 99.99, insured: true, openedAt: "2024-02-29"}, {weight: null, insured: false, openedAt: "2000-01-01"}]}}, {account: {bonus: true, companies: [{insured: false, openedAt: "2000-01-01", segment: true, weight: 7.25}, {insured: true, openedAt: "2024-02-29", segment: true, weight: 99.99}, {insured: false, openedAt: "2000-01-01", segment: true, weight: null}], label: null, plan: null, points: 750, score: 1000, status: "open", urgent: true, verified: false}, discount: true, total: ""}], + [{account: {score: -1, status: "open", urgent: false, label: "a", plan: "premium", verified: false, companies: [{weight: 99.99, insured: true, openedAt: "2024-01-01"}, {weight: 99.99, insured: false, openedAt: "2024-01-01"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "2024-01-01", segment: true, weight: 99.99}, {insured: false, openedAt: "2024-01-01", segment: true, weight: 99.99}], label: "a", plan: "premium", points: -2, score: -1, status: "open", urgent: false, verified: false}, discount: false, total: "a"}], + [{account: {score: 99999999999999999999, status: "pending", urgent: true, label: "retail", plan: "trial", verified: true, companies: [{weight: 18, insured: true, openedAt: "2030-12-31"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "2030-12-31", segment: true, weight: 18}], label: "retail", plan: "trial", points: 99999999999999999999, score: 99999999999999999999, status: "pending", urgent: true, verified: true}, discount: false, total: "retail"}], + [{account: {score: 3, urgent: false, label: "12", verified: false, companies: [{weight: -1, insured: true, openedAt: "2030-12-31"}, {weight: 10, insured: false, openedAt: "1990-06-15"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "2030-12-31", segment: false, weight: -1}, {insured: false, openedAt: "1990-06-15", segment: false, weight: 10}], label: "12", points: 500, score: 3, urgent: false, verified: false}, discount: true, total: "12"}], + [{account: {score: 2, status: "pending", urgent: false, label: "gold", plan: null, verified: true, companies: [{weight: null, insured: true, openedAt: "2025-03-20"}, {weight: -500, insured: false, openedAt: "1990-06-15"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "2025-03-20", segment: false, weight: null}, {insured: false, openedAt: "1990-06-15", segment: false, weight: -500}], label: "gold", plan: null, points: 500, score: 2, status: "pending", urgent: false, verified: true}, discount: true, total: "gold"}], + [{account: {score: 18, status: "open", urgent: true, label: "3.5", verified: false, companies: [{weight: null, insured: false, openedAt: "2025-03-20"}, {weight: -0.01, insured: false, openedAt: "2024-01-01"}]}}, {account: {bonus: true, companies: [{insured: false, openedAt: "2025-03-20", segment: false, weight: null}, {insured: false, openedAt: "2024-01-01", segment: false, weight: -0.01}], label: "3.5", points: 500, score: 18, status: "open", urgent: true, verified: false}, discount: true, total: "3.5"}], + [{account: {status: "pending", urgent: false, label: "abc", plan: "basic", verified: false, companies: [{weight: 18, insured: true, openedAt: "2024-02-29"}]}}, "!error: MissingRequiredInputs"], + [{account: {score: -0.01, status: "open", urgent: false, label: "Zed", plan: "basic", verified: true, companies: []}}, {account: {bonus: true, companies: [], label: "Zed", plan: "basic", points: -0.01, score: -0.01, status: "open", urgent: false, verified: true}, total: "Zed"}], + [{account: {score: 18, status: "open", urgent: false, verified: true, companies: []}}, {account: {bonus: true, companies: [], points: 18, score: 18, status: "open", urgent: false, verified: true}, total: ""}], + [{account: {score: 429, status: "pending", urgent: false, label: "a", plan: "basic", verified: false, companies: [{weight: 123456789.123, insured: false, openedAt: "2000-01-01"}]}}, {account: {bonus: true, companies: [{insured: false, openedAt: "2000-01-01", segment: true, weight: 123456789.123}], label: "a", plan: "basic", points: 429, score: 429, status: "pending", urgent: false, verified: false}, discount: false, total: "a"}], + [{account: {score: 65, status: "pending", urgent: true, label: "é ü", plan: "basic", verified: true, companies: [{weight: 1000, insured: false, openedAt: "2024-02-29"}, {weight: 1e3, insured: false, openedAt: "2024-01-01"}]}}, {account: {bonus: true, companies: [{insured: false, openedAt: "2024-02-29", segment: false, weight: 1000}, {insured: false, openedAt: "2024-01-01", segment: false, weight: 1000}], label: "é ü", plan: "basic", points: 130, score: 65, status: "pending", urgent: true, verified: true}, discount: false, total: "é ü"}], + [{account: {score: 1, status: "open", urgent: false, label: "VIP", plan: "premium", verified: true, companies: [{weight: 0, insured: false, openedAt: "2000-01-01"}, {weight: -1, insured: false, openedAt: "2000-01-01"}, {weight: 0.5, insured: true, openedAt: "2024-01-01"}], extraField: 1}}, {account: {bonus: true, companies: [{insured: false, openedAt: "2000-01-01", segment: false, weight: 0}, {insured: false, openedAt: "2000-01-01", segment: false, weight: -1}, {insured: true, openedAt: "2024-01-01", segment: false, weight: 0.5}], extraField: 1, label: "VIP", plan: "premium", points: 3, score: 1, status: "open", urgent: false, verified: true}, discount: false, total: "VIP"}], + [{account: {score: 10, status: "open", urgent: true, plan: "plus", verified: false, companies: [{weight: null, insured: true, openedAt: "2025-03-20"}, {weight: 1e3, insured: true, openedAt: "1990-06-15"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "2025-03-20", segment: false, weight: null}, {insured: true, openedAt: "1990-06-15", segment: false, weight: 1000}], plan: "plus", points: 20, score: 10, status: "open", urgent: true, verified: false}, discount: false, total: ""}], + [{account: {score: 18, status: "open", urgent: true, label: "NL", plan: null, verified: true, companies: []}}, {account: {bonus: true, companies: [], label: "NL", plan: null, points: 18, score: 18, status: "open", urgent: true, verified: true}, total: "NL"}], + [{account: {score: 0.000001, status: "closed", urgent: true, label: "retail", plan: "basic", verified: false, companies: [{weight: 10, insured: true, openedAt: "1990-06-15"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "1990-06-15", segment: true, weight: 10}], label: "retail", plan: "basic", points: 0.000001, score: 0.000001, status: "closed", urgent: true, verified: false}, discount: false, total: "retail"}], + [{account: {score: 18, status: "closed", urgent: false, verified: true, companies: []}}, {account: {bonus: true, companies: [], points: 18, score: 18, status: "closed", urgent: false, verified: true}, total: ""}], + [{account: {score: -500, status: "closed", urgent: true, label: "12", plan: null, verified: true, companies: [{insured: true, openedAt: "1990-06-15"}, {weight: null, insured: false, openedAt: "2030-12-31"}, {weight: 3, insured: true, openedAt: "2000-01-01"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "1990-06-15", segment: false}, {insured: false, openedAt: "2030-12-31", segment: false, weight: null}, {insured: true, openedAt: "2000-01-01", segment: false, weight: 3}], label: "12", plan: null, points: 750, score: -500, status: "closed", urgent: true, verified: true}, discount: true, total: "12"}], + [{account: {score: 2.50, status: "open", urgent: false, label: null, plan: "basic", verified: true, companies: [{weight: 18, insured: true, openedAt: "2000-01-01"}, {weight: 2.50, insured: true, openedAt: "2025-03-20T10:15:30Z"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "2000-01-01", segment: false, weight: 18}, {insured: true, openedAt: "2025-03-20T10:15:30Z", segment: false, weight: 2.50}], label: null, plan: "basic", points: 5.00, score: 2.50, status: "open", urgent: false, verified: true}, discount: false, total: ""}], + [{account: {score: 0.000001, status: "pending", urgent: false, label: "A1", plan: "basic", verified: true, companies: [{weight: 250, insured: false, openedAt: "1990-06-15"}, {weight: 1, insured: false, openedAt: "2024-01-01"}, {weight: 99.99, insured: true, openedAt: "2030-12-31"}]}}, {account: {bonus: true, companies: [{insured: false, openedAt: "1990-06-15", segment: false, weight: 250}, {insured: false, openedAt: "2024-01-01", segment: false, weight: 1}, {insured: true, openedAt: "2030-12-31", segment: false, weight: 99.99}], label: "A1", plan: "basic", points: 0.000003, score: 0.000001, status: "pending", urgent: false, verified: true}, discount: false, total: "A1"}], + [{account: {score: 180, status: "pending", urgent: true, label: "Zed", plan: "premium", verified: false, companies: [{weight: 99.99, insured: true, openedAt: "2030-12-31"}]}}, {account: {bonus: true, companies: [{insured: true, openedAt: "2030-12-31", segment: true, weight: 99.99}], label: "Zed", plan: "premium", points: 180, score: 180, status: "pending", urgent: true, verified: false}, discount: false, total: "Zed"}], + ], +} + +// seed 333301 (attempt 1) +{ + name: "a 34: applicant/lines: 3 expression, 2 match, 1 table; 3 root, 5 per-member, 0 top-level computed", + policy: { + models: {applicant: {price: "number", limit: "number", label: "string", country: "string?", lines: "line[]"}, line: {balance: "number", limit: "number", plan: "string(basic|plus|premium|trial)?"}}, + blocks: [ + {match: "applicant.summary", arms: [["(applicant.country ?? '') in ['ok', 'gold']", "some(applicant.lines, (#.limit == 10 or #.limit == 2))"], ["", "applicant.limit > 250"]]}, + {table: "t2", inputs: ["(0.25 + line.limit)"], outputs: ["line.decision", "line.health", "line.weighted[]"], rules: [ + ["!= 100", "2", "line.balance", "applicant.label != 'high'"], + ["[100..398]", "5", "applicant.price", "len(applicant.label) > 2"], + ["> 0.5", "", "line.limit", "applicant.summary"], + ["1000", "line.balance", "line.limit", "applicant.country != null"], + ["", "applicant.price", "applicant.limit", ""], + ["< 2", "(applicant.summary ? line.balance : line.balance)", "line.limit", "applicant.summary"], + ]}, + {match: "applicant.exposure", arms: [["none(applicant.lines, not (#.balance == 0))", "(applicant.country ?? '')"], ["applicant.limit == applicant.price", "(applicant.summary ? (applicant.country ?? '') : applicant.label)"], ["", "applicant.label"]]}, + {expression: "line.rank", value: "sum(map(applicant.lines, len(#.weighted)))"}, + {expression: "applicant.net", value: "applicant.price"}, + {expression: "line.risk", value: "(applicant.country ?? '') in ['US', 'low']"}, + ], + }, + cases: [ + [{applicant: {price: 0.25, limit: 99999999999999999999, label: "a", country: "VIP", lines: [{balance: 0, limit: 65, plan: "basic"}, {balance: 0.5, limit: 2, plan: "plus"}], extraField: {nested: true}}}, {applicant: {country: "VIP", exposure: "a", extraField: {nested: true}, label: "a", limit: 99999999999999999999, lines: [{balance: 0, decision: 2, health: 0, limit: 65, plan: "basic", rank: 4, risk: false, weighted: [true, true]}, {balance: 0.5, decision: 2, health: 0.5, limit: 2, plan: "plus", rank: 4, risk: false, weighted: [true, true]}], net: 0.25, price: 0.25, summary: true}}], + [{applicant: {price: 10, limit: 1e3, label: "a", country: "US", lines: [{balance: 2, limit: 7.25, plan: "trial"}, {balance: 100, limit: -0}]}}, {applicant: {country: "US", exposure: "a", label: "a", limit: 1000, lines: [{balance: 2, decision: 2, health: 2, limit: 7.25, plan: "trial", rank: 4, risk: true, weighted: [true, true]}, {balance: 100, decision: 2, health: 100, limit: 0, rank: 4, risk: true, weighted: [true, true]}], net: 10, price: 10, summary: true}}], + [{applicant: {price: 0, limit: 1000, label: "", country: "US", lines: [{balance: 2.50, limit: 1.5, plan: "basic"}]}}, {applicant: {country: "US", exposure: "", label: "", limit: 1000, lines: [{balance: 2.50, decision: 2, health: 2.50, limit: 1.5, plan: "basic", rank: 3, risk: true, weighted: [true, true, true]}], net: 0, price: 0, summary: true}}], + [{applicant: {price: -0, limit: -500, label: "O'Neil", lines: [{balance: 65, limit: 5, plan: null}]}}, {applicant: {exposure: "O'Neil", label: "O'Neil", limit: -500, lines: [{balance: 65, decision: 2, health: 65, limit: 5, plan: null, rank: 2, risk: false, weighted: [true, false]}], net: 0, price: 0, summary: false}}], + [{applicant: {limit: 2, label: "3.5", country: "Zed", lines: []}}, "!error: MissingRequiredInputs"], + [{applicant: {price: 1000, limit: 1.5, label: "A1", country: "A1", lines: [{balance: 400, limit: 1000, plan: "plus"}, {balance: 131, limit: -1, plan: "basic"}, {balance: 2, limit: 3, plan: "basic"}]}}, {applicant: {country: "A1", exposure: "A1", label: "A1", limit: 1.5, lines: [{balance: 400, decision: 2, health: 400, limit: 1000, plan: "plus", rank: 6, risk: false, weighted: [true, false]}, {balance: 131, decision: 2, health: 131, limit: -1, plan: "basic", rank: 6, risk: false, weighted: [true, false]}, {balance: 2, decision: 2, health: 2, limit: 3, plan: "basic", rank: 6, risk: false, weighted: [true, false]}], net: 1000, price: 1000, summary: false}}], + [{applicant: {price: 2, limit: 99.99, label: "gold", country: "US", lines: [{balance: 1000, limit: 0, plan: "trial"}, {balance: 18, limit: 0, plan: "basic"}, {balance: 99999999999999999999, limit: 1, plan: "plus"}, {balance: 0.1, limit: 0.5, plan: "premium"}, {balance: 100, limit: 100, plan: "basic"}], extraField: "x"}}, {applicant: {country: "US", exposure: "gold", extraField: "x", label: "gold", limit: 99.99, lines: [{balance: 1000, decision: 2, health: 1000, limit: 0, plan: "trial", rank: 13, risk: true, weighted: [true, false]}, {balance: 18, decision: 2, health: 18, limit: 0, plan: "basic", rank: 13, risk: true, weighted: [true, false]}, {balance: 99999999999999999999, decision: 2, health: 99999999999999999999, limit: 1, plan: "plus", rank: 13, risk: true, weighted: [true, false, false]}, {balance: 0.1, decision: 2, health: 0.1, limit: 0.5, plan: "premium", rank: 13, risk: true, weighted: [true, false, false]}, {balance: 100, decision: 2, health: 100, limit: 100, plan: "basic", rank: 13, risk: true, weighted: [true, true, false]}], net: 2, price: 2, summary: false}}], + [{applicant: {price: 99999999999999999999, limit: -0, label: "retail", country: "VIP", lines: [{balance: 1000, limit: 0.1, plan: "basic"}]}}, {applicant: {country: "VIP", exposure: "retail", label: "retail", limit: 0, lines: [{balance: 1000, decision: 2, health: 1000, limit: 0.1, plan: "basic", rank: 2, risk: false, weighted: [true, false]}], net: 99999999999999999999, price: 99999999999999999999, summary: false}}], + [{applicant: {price: 10, limit: 123456789.123, label: "low", country: "O'Neil", lines: []}}, {applicant: {country: "O'Neil", exposure: "O'Neil", label: "low", limit: 123456789.123, lines: [], net: 10, price: 10}}], + [{applicant: {price: 1e3, limit: -0.5, label: "", country: null, lines: [{balance: 100, limit: 65, plan: "plus"}]}}, {applicant: {country: null, exposure: "", label: "", limit: -0.5, lines: [{balance: 100, decision: 2, health: 100, limit: 65, plan: "plus", rank: 2, risk: false, weighted: [true, false]}], net: 1000, price: 1000, summary: false}}], + [{applicant: {price: 5, limit: 65, label: "VIP", lines: [{balance: -1, limit: 0.25, plan: "basic"}]}}, {applicant: {exposure: "VIP", label: "VIP", limit: 65, lines: [{balance: -1, decision: 2, health: -1, limit: 0.25, plan: "basic", rank: 2, risk: false, weighted: [true, false]}], net: 5, price: 5, summary: false}}], + [{applicant: {price: 0.000001, limit: 1.5, label: "a-b-c", country: "retail", lines: [{balance: 1, limit: 0, plan: "trial"}, {balance: 1000, limit: 1e3, plan: "basic"}, {balance: -0.01, limit: 1000, plan: "basic"}]}}, {applicant: {country: "retail", exposure: "a-b-c", label: "a-b-c", limit: 1.5, lines: [{balance: 1, decision: 2, health: 1, limit: 0, plan: "trial", rank: 6, risk: false, weighted: [true, false]}, {balance: 1000, decision: 2, health: 1000, limit: 1000, plan: "basic", rank: 6, risk: false, weighted: [true, false]}, {balance: -0.01, decision: 2, health: -0.01, limit: 1000, plan: "basic", rank: 6, risk: false, weighted: [true, false]}], net: 0.000001, price: 0.000001, summary: false}}], + [{applicant: {price: 50, limit: 3, label: "gold", country: "A1", lines: [{balance: 5, limit: 3, plan: "premium"}, {balance: 1e3, limit: 1000, plan: "premium"}]}}, {applicant: {country: "A1", exposure: "gold", label: "gold", limit: 3, lines: [{balance: 5, decision: 2, health: 5, limit: 3, plan: "premium", rank: 4, risk: false, weighted: [true, false]}, {balance: 1000, decision: 2, health: 1000, limit: 1000, plan: "premium", rank: 4, risk: false, weighted: [true, false]}], net: 50, price: 50, summary: false}}], + [{applicant: {price: 99.99, limit: 100, label: "VIP", country: "x-y", lines: [{balance: 5, limit: 0}, {balance: 100, limit: -0.5, plan: "plus"}]}}, {applicant: {country: "x-y", exposure: "VIP", label: "VIP", limit: 100, lines: [{balance: 5, decision: 2, health: 5, limit: 0, rank: 4, risk: false, weighted: [true, false]}, {balance: 100, decision: 2, health: 100, limit: -0.5, plan: "plus", rank: 4, risk: false, weighted: [true, false]}], net: 99.99, price: 99.99, summary: false}}], + [{applicant: {price: 10, limit: 0, label: "NL", country: null, lines: []}}, {applicant: {country: null, exposure: "", label: "NL", limit: 0, lines: [], net: 10, price: 10}}], + [{applicant: {price: 0.5, limit: 10, label: "日本", country: "high", lines: [{balance: 250, limit: 250, plan: "basic"}, {balance: -0.5, limit: 5, plan: "premium"}, {balance: 10, limit: 314, plan: "basic"}]}}, {applicant: {country: "high", exposure: "日本", label: "日本", limit: 10, lines: [{balance: 250, decision: 2, health: 250, limit: 250, plan: "basic", rank: 8, risk: false, weighted: [true, true, false]}, {balance: -0.5, decision: 2, health: -0.5, limit: 5, plan: "premium", rank: 8, risk: false, weighted: [true, false]}, {balance: 10, decision: 2, health: 10, limit: 314, plan: "basic", rank: 8, risk: false, weighted: [true, true, false]}], net: 0.5, price: 0.5, summary: false}}], + [{applicant: {price: 2, limit: 3, label: "日本", country: null, lines: []}}, {applicant: {country: null, exposure: "", label: "日本", limit: 3, lines: [], net: 2, price: 2}}], + [{applicant: {price: 0.25, limit: 0, label: "US", country: "VIP", lines: [], extraField: {nested: true}}}, {applicant: {country: "VIP", exposure: "VIP", extraField: {nested: true}, label: "US", limit: 0, lines: [], net: 0.25, price: 0.25}}], + [{applicant: {price: 123456789.123, limit: 50, label: "abc", country: "é ü", lines: [{balance: 1000000, limit: 2, plan: "plus"}, {balance: 2, limit: 10, plan: "basic"}, {balance: -1, limit: 99.99, plan: "trial"}, {balance: 250, limit: 1.5, plan: "premium"}, {balance: 0.000001, limit: 2, plan: "basic"}]}}, {applicant: {country: "é ü", exposure: "abc", label: "abc", limit: 50, lines: [{balance: 1000000, decision: 2, health: 1000000, limit: 2, plan: "plus", rank: 12, risk: false, weighted: [true, false]}, {balance: 2, decision: 2, health: 2, limit: 10, plan: "basic", rank: 12, risk: false, weighted: [true, false]}, {balance: -1, decision: 2, health: -1, limit: 99.99, plan: "trial", rank: 12, risk: false, weighted: [true, true, false]}, {balance: 250, decision: 2, health: 250, limit: 1.5, plan: "premium", rank: 12, risk: false, weighted: [true, false, false]}, {balance: 0.000001, decision: 2, health: 0.000001, limit: 2, plan: "basic", rank: 12, risk: false, weighted: [true, false]}], net: 123456789.123, price: 123456789.123, summary: false}}], + [{applicant: {price: 250, limit: 2, label: "é ü", country: "gold", lines: [{balance: 0.1, limit: 0, plan: "premium"}]}}, {applicant: {country: "gold", exposure: "é ü", label: "é ü", limit: 2, lines: [{balance: 0.1, decision: 2, health: 0.1, limit: 0, plan: "premium", rank: 2, risk: false, weighted: [true, false]}], net: 250, price: 250, summary: false}}], + [{applicant: {price: 250, limit: 334, label: "12", lines: [{balance: 1e3, limit: 2}, {balance: 2, limit: 123456789.123, plan: null}, {balance: 250, limit: 0.000001, plan: "premium"}, {balance: 2, limit: 2}]}}, {applicant: {exposure: "12", label: "12", limit: 334, lines: [{balance: 1000, decision: 2, health: 1000, limit: 2, rank: 8, risk: false, weighted: [true, true]}, {balance: 2, decision: 2, health: 2, limit: 123456789.123, plan: null, rank: 8, risk: false, weighted: [true, true]}, {balance: 250, decision: 2, health: 250, limit: 0.000001, plan: "premium", rank: 8, risk: false, weighted: [true, true]}, {balance: 2, decision: 2, health: 2, limit: 2, rank: 8, risk: false, weighted: [true, true]}], net: 250, price: 250, summary: true}}], + [{applicant: {price: 2, limit: 1000, label: "gold", country: null, lines: [{balance: 0.5, limit: -0.01, plan: "plus"}]}}, {applicant: {country: null, exposure: "gold", label: "gold", limit: 1000, lines: [{balance: 0.5, decision: 2, health: 0.5, limit: -0.01, plan: "plus", rank: 2, risk: false, weighted: [true, true]}], net: 2, price: 2, summary: true}}], + ], +} + +// seed 333400 (attempt 0) +{ + name: "a 35: order/lines: 1 expression, 2 match, 1 table; 2 root, 2 per-member, 0 top-level computed", + policy: { + models: {order: {age: "number", weight: "number", amount: "number", vip: "boolean?", verified: "boolean", lines: "line[]"}, line: {price: "number?", openedAt: "date", channel: "string"}}, + blocks: [ + {expression: "order.decision", value: "string(order.amount)"}, + {match: "order.ok", arms: [["order.vip != null", "(avg(map(order.lines, ((#.price ?? 0) * (#.price ?? 0)))) ?? 0) > order.weight"], ["", "18 >= order.amount"]]}, + {table: "t1", hit: "collect", inputs: [null, "line.channel", "order.verified"], outputs: ["line.share"], rules: [ + ["order.age in [38..208]", "'VIP', 'low'", "true", "order.amount"], + ["10 != order.age", "", "false", "(3) / (abs(order.amount) + 1)"], + ["", "", "true", "order.weight"], + ["not ((order.vip ?? false))", "'high', 'x'", "false", "250"], + ["", "'none'", "true", "order.amount"], + ]}, + {match: "line.rank", arms: [["((line.price ?? 0)) / (abs(2) + 1) <= order.weight", "line.channel"], ["(min(map(order.lines, (0 + (#.price ?? 0)))) ?? 0) > order.age", "line.channel"], ["order.amount == order.age", "upper(('DE' + '-' + line.channel))"], ["line.openedAt > d('2000-06-30')", "string((line.price ?? 0))"], ["", "line.channel"]]}, + ], + }, + cases: [ + [{order: {age: 3, weight: -1, amount: 0.1, vip: true, verified: false, lines: []}}, "!error: ExpressionFailed"], + [{order: {age: 0, weight: 0.000001, amount: 0.5, vip: true, verified: false, lines: [{price: 1000000, openedAt: "2024-02-29", channel: "none"}, {price: 7.25, openedAt: "2024-02-29", channel: "high"}, {price: 7.25, openedAt: "2024-02-29", channel: "3.5"}, {price: 221, openedAt: "2030-12-31", channel: "US"}]}}, {order: {age: 0, amount: 0.5, decision: "0.5", lines: [{channel: "none", openedAt: "2024-02-29", price: 1000000, rank: "none", share: [2.0]}, {channel: "high", openedAt: "2024-02-29", price: 7.25, rank: "high", share: [2.0]}, {channel: "3.5", openedAt: "2024-02-29", price: 7.25, rank: "3.5", share: [2.0]}, {channel: "US", openedAt: "2030-12-31", price: 221, rank: "US", share: [2.0]}], ok: true, verified: false, vip: true, weight: 0.000001}}], + [{order: {age: 0.000001, weight: 100, amount: 2, vip: false, verified: true, lines: []}}, "!error: ExpressionFailed"], + [{order: {age: 99999999999999999999, weight: -0.01, amount: 0.000001, vip: null, verified: true, lines: [{price: 18, openedAt: "2024-01-01", channel: "A1"}, {openedAt: "2024-01-01", channel: "US"}, {price: null, openedAt: "1990-06-15", channel: "US"}, {openedAt: "2025-03-20", channel: " pad "}]}}, {order: {age: 99999999999999999999, amount: 0.000001, decision: "0.000001", lines: [{channel: "A1", openedAt: "2024-01-01", price: 18, rank: "18", share: [-0.01]}, {channel: "US", openedAt: "2024-01-01", rank: "0", share: [-0.01]}, {channel: "US", openedAt: "1990-06-15", price: null, rank: "US", share: [-0.01]}, {channel: " pad ", openedAt: "2025-03-20", rank: "0", share: [-0.01]}], ok: true, verified: true, vip: null, weight: -0.01}}], + [{order: {age: 3, weight: -500, amount: 65, vip: true, verified: false, lines: [{price: -0, openedAt: "2024-02-29", channel: "high"}, {price: 250, openedAt: "2000-01-01", channel: "retail"}, {openedAt: "2025-03-20", channel: "O'Neil"}]}}, {order: {age: 3, amount: 65, decision: "65", lines: [{channel: "high", openedAt: "2024-02-29", price: 0, rank: "0", share: [0.0454545454545454545454545455]}, {channel: "retail", openedAt: "2000-01-01", price: 250, rank: "retail", share: [0.0454545454545454545454545455]}, {channel: "O'Neil", openedAt: "2025-03-20", rank: "0", share: [0.0454545454545454545454545455]}], ok: true, verified: false, vip: true, weight: -500}}], + [{order: {age: 5, weight: 0.5, amount: 2, vip: false, verified: true, lines: [{price: 10, openedAt: "2025-03-20", channel: "3.5"}, {price: 18, openedAt: "2024-02-29", channel: "Oslo"}], extraField: "x"}}, {order: {age: 5, amount: 2, decision: "2", extraField: "x", lines: [{channel: "3.5", openedAt: "2025-03-20", price: 10, rank: "3.5", share: [0.5]}, {channel: "Oslo", openedAt: "2024-02-29", price: 18, rank: "Oslo", share: [0.5]}], ok: true, verified: true, vip: false, weight: 0.5}}], + [{order: {age: -0.5, weight: -0.5, amount: 0.1, vip: false, verified: false, lines: [{price: 1000, openedAt: "2025-03-20", channel: "Oslo"}]}}, {order: {age: -0.5, amount: 0.1, decision: "0.1", lines: [{channel: "Oslo", openedAt: "2025-03-20", price: 1000, rank: "Oslo", share: [2.7272727272727272727272727273]}], ok: true, verified: false, vip: false, weight: -0.5}}], + [{order: {age: 99.99, weight: -0.5, amount: 2, vip: false, verified: true, lines: [{price: 250, openedAt: "2024-01-01", channel: "VIP"}], extraField: "x"}}, {order: {age: 99.99, amount: 2, decision: "2", extraField: "x", lines: [{channel: "VIP", openedAt: "2024-01-01", price: 250, rank: "VIP", share: [2, -0.5]}], ok: true, verified: true, vip: false, weight: -0.5}}], + [{order: {age: 1000, weight: 3, amount: 10, vip: true, verified: true, lines: [{price: 0.000001, openedAt: "2000-01-01", channel: "US"}]}}, {order: {age: 1000, amount: 10, decision: "10", lines: [{channel: "US", openedAt: "2000-01-01", price: 0.000001, rank: "US", share: [3]}], ok: false, verified: true, vip: true, weight: 3}}], + [{order: {age: -0, weight: 1000, amount: -1, vip: false, verified: false, lines: [{price: 99.99, openedAt: "1990-06-15", channel: "abc"}, {price: -0.01, openedAt: "1990-06-15", channel: "high"}]}}, {order: {age: 0, amount: -1, decision: "-1", lines: [{channel: "abc", openedAt: "1990-06-15", price: 99.99, rank: "abc", share: [1.50]}, {channel: "high", openedAt: "1990-06-15", price: -0.01, rank: "high", share: [1.50, 250]}], ok: true, verified: false, vip: false, weight: 1000}}], + [{order: {age: 0.1, weight: 1000, amount: -500, vip: false, verified: true, lines: [{price: 2, openedAt: "2000-01-01", channel: "日本"}, {price: -0, openedAt: "2025-03-20", channel: "O'Neil"}, {price: 0.5, openedAt: "2000-01-01", channel: "none"}]}}, {order: {age: 0.1, amount: -500, decision: "-500", lines: [{channel: "日本", openedAt: "2000-01-01", price: 2, rank: "日本", share: [1000]}, {channel: "O'Neil", openedAt: "2025-03-20", price: 0, rank: "O'Neil", share: [1000]}, {channel: "none", openedAt: "2000-01-01", price: 0.5, rank: "none", share: [1000, -500]}], ok: false, verified: true, vip: false, weight: 1000}}], + [{order: {age: 5, weight: 1000000, amount: 0, verified: false, lines: [{openedAt: "2025-03-20T10:15:30Z", channel: "US"}]}}, {order: {age: 5, amount: 0, decision: "0", lines: [{channel: "US", openedAt: "2025-03-20T10:15:30Z", rank: "US", share: [3]}], ok: true, verified: false, weight: 1000000}}], + [{order: {age: 1e3, weight: 0.1, amount: 0, vip: true, verified: true, lines: [{openedAt: "2024-01-01", channel: "Zed"}, {price: 250, openedAt: "2024-01-01", channel: " pad "}]}}, {order: {age: 1000, amount: 0, decision: "0", lines: [{channel: "Zed", openedAt: "2024-01-01", rank: "Zed", share: [0.1]}, {channel: " pad ", openedAt: "2024-01-01", price: 250, rank: "250", share: [0.1]}], ok: true, verified: true, vip: true, weight: 0.1}}], + [{order: {age: 65, weight: 99999999999999999999, amount: 99999999999999999999, vip: true, verified: false, lines: [{price: 65, openedAt: "2025-03-20", channel: "-"}], extraField: "x"}}, {order: {age: 65, amount: 99999999999999999999, decision: "99999999999999999999", extraField: "x", lines: [{channel: "-", openedAt: "2025-03-20", price: 65, rank: "-", share: [0.00000000000000000003]}], ok: false, verified: false, vip: true, weight: 99999999999999999999}}], + ], +} + +// seed 333500 (attempt 0) +{ + name: "a 36: shipment/lines: 2 expression, 2 match, 1 table; 3 root, 3 per-member, 0 top-level computed", + policy: { + models: {shipment: {balance: "number", plan: "string(basic|plus|premium|trial)", code: "string", birthDate: "date", lines: "line[]"}, line: {income: "number", priority: "boolean"}}, + blocks: [ + {expression: "line.tag", value: "count(shipment.lines, (#.priority or #.priority))"}, + {match: "shipment.flag", arms: [["shipment.plan != 'trial'", "trim(shipment.code)"], ["", "shipment.code"]]}, + {expression: "shipment.fee", value: "shipment.birthDate < d('2000-06-30')"}, + {match: "shipment.summary", arms: [["not (shipment.fee)", "shipment.balance"], ["contains(shipment.code, 'gold')", "round(shipment.balance, 2)"], ["", "shipment.balance"]]}, + {table: "t5", inputs: ["shipment.birthDate", "line.tag"], outputs: ["line.decision", "line.surcharge"], rules: [ + [">= d('2000-06-30')", "< 3", "line.income", "shipment.birthDate.diff(d('2025-01-01'), 'day')"], + ["> d('2025-01-01')", "> 0", "line.income", "sum(map(shipment.lines, #.income))"], + ["", "<= 100", "line.income", "shipment.birthDate.month()"], + ["< d('2025-03-20')", "< 50", "1.5", ""], + ]}, + ], + }, + cases: [ + [{shipment: {balance: 0.000001, plan: "trial", code: "US", birthDate: "2000-01-01", lines: [{income: 65, priority: false}, {income: -1, priority: true}]}}, {shipment: {balance: 0.000001, birthDate: "2000-01-01", code: "US", fee: true, flag: "US", lines: [{decision: 65, income: 65, priority: false, surcharge: 1, tag: 1}, {decision: -1, income: -1, priority: true, surcharge: 1, tag: 1}], plan: "trial", summary: 0.000001}}], + [{shipment: {balance: 250, plan: "premium", code: "Oslo", birthDate: "2030-12-31", lines: [{income: 0, priority: false}, {income: 1000, priority: false}]}}, {shipment: {balance: 250, birthDate: "2030-12-31", code: "Oslo", fee: false, flag: "Oslo", lines: [{decision: 0, income: 0, priority: false, surcharge: 2190, tag: 0}, {decision: 1000, income: 1000, priority: false, surcharge: 2190, tag: 0}], plan: "premium", summary: 250}}], + [{shipment: {balance: 1000000, plan: "plus", code: "low", birthDate: "2000-01-01", lines: []}}, {shipment: {balance: 1000000, birthDate: "2000-01-01", code: "low", fee: true, flag: "low", lines: [], plan: "plus", summary: 1000000}}], + [{shipment: {balance: 10, plan: "premium", code: "Zed", birthDate: "1990-06-15", lines: []}}, {shipment: {balance: 10, birthDate: "1990-06-15", code: "Zed", fee: true, flag: "Zed", lines: [], plan: "premium", summary: 10}}], + [{shipment: {balance: 0, plan: "basic", code: "Oslo", birthDate: "2030-12-31", lines: []}}, {shipment: {balance: 0, birthDate: "2030-12-31", code: "Oslo", fee: false, flag: "Oslo", lines: [], plan: "basic", summary: 0}}], + [{shipment: {balance: 0.25, plan: "basic", code: "VIP", birthDate: "2024-01-01", lines: [{income: 7.25, priority: true}, {income: 46, priority: true}]}}, {shipment: {balance: 0.25, birthDate: "2024-01-01", code: "VIP", fee: false, flag: "VIP", lines: [{decision: 7.25, income: 7.25, priority: true, surcharge: -366, tag: 2}, {decision: 46, income: 46, priority: true, surcharge: -366, tag: 2}], plan: "basic", summary: 0.25}}], + [{shipment: {balance: 1000, plan: "basic", code: "-", birthDate: "1990-06-15", lines: [{income: 175, priority: true}, {income: -500, priority: true}]}}, {shipment: {balance: 1000, birthDate: "1990-06-15", code: "-", fee: true, flag: "-", lines: [{decision: 175, income: 175, priority: true, surcharge: 6, tag: 2}, {decision: -500, income: -500, priority: true, surcharge: 6, tag: 2}], plan: "basic", summary: 1000}}], + [{shipment: {balance: 10, plan: "basic", code: "日本", birthDate: "2024-01-01", lines: [{income: 7.25, priority: false}, {income: 0, priority: false}]}}, {shipment: {balance: 10, birthDate: "2024-01-01", code: "日本", fee: false, flag: "日本", lines: [{decision: 7.25, income: 7.25, priority: false, surcharge: -366, tag: 0}, {decision: 0, income: 0, priority: false, surcharge: -366, tag: 0}], plan: "basic", summary: 10}}], + [{shipment: {balance: 0.5, plan: "trial", code: "DE", birthDate: "1990-06-15", lines: [{income: 2, priority: false}]}}, {shipment: {balance: 0.5, birthDate: "1990-06-15", code: "DE", fee: true, flag: "DE", lines: [{decision: 2, income: 2, priority: false, surcharge: 6, tag: 0}], plan: "trial", summary: 0.5}}], + [{shipment: {balance: 0.25, plan: "trial", code: "ok", birthDate: "2024-01-01", lines: [{income: 5, priority: true}, {income: 1000, priority: false}, {income: 99999999999999999999, priority: true}, {income: 0, priority: true}]}}, {shipment: {balance: 0.25, birthDate: "2024-01-01", code: "ok", fee: false, flag: "ok", lines: [{decision: 5, income: 5, priority: true, surcharge: 1, tag: 3}, {decision: 1000, income: 1000, priority: false, surcharge: 1, tag: 3}, {decision: 99999999999999999999, income: 99999999999999999999, priority: true, surcharge: 1, tag: 3}, {decision: 0, income: 0, priority: true, surcharge: 1, tag: 3}], plan: "trial", summary: 0.25}}], + [{shipment: {balance: 99999999999999999999, plan: "basic", code: "Oslo", birthDate: "2000-01-01", lines: [{income: 99.99}]}}, "!error: ExpressionFailed"], + [{shipment: {balance: 0, plan: "basic", code: "gold", birthDate: "2025-03-20", lines: [{income: 5, priority: false}]}}, {shipment: {balance: 0, birthDate: "2025-03-20", code: "gold", fee: false, flag: "gold", lines: [{decision: 5, income: 5, priority: false, surcharge: 78, tag: 0}], plan: "basic", summary: 0}}], + [{shipment: {balance: 0.1, plan: "trial", code: "3.5", birthDate: "2024-02-29", lines: [{income: -0.01, priority: true}, {income: 0, priority: true}]}}, {shipment: {balance: 0.1, birthDate: "2024-02-29", code: "3.5", fee: false, flag: "3.5", lines: [{decision: -0.01, income: -0.01, priority: true, surcharge: -307, tag: 2}, {decision: 0, income: 0, priority: true, surcharge: -307, tag: 2}], plan: "trial", summary: 0.1}}], + [{shipment: {balance: 1.5, plan: "plus", code: "low", birthDate: "2030-12-31", lines: []}}, {shipment: {balance: 1.5, birthDate: "2030-12-31", code: "low", fee: false, flag: "low", lines: [], plan: "plus", summary: 1.5}}], + [{shipment: {balance: 65, plan: "premium", code: "é ü", birthDate: "2030-12-31", lines: [{income: 99999999999999999999, priority: true}, {income: 100, priority: false}]}}, {shipment: {balance: 65, birthDate: "2030-12-31", code: "é ü", fee: false, flag: "é ü", lines: [{decision: 99999999999999999999, income: 99999999999999999999, priority: true, surcharge: 2190, tag: 1}, {decision: 100, income: 100, priority: false, surcharge: 2190, tag: 1}], plan: "premium", summary: 65}}], + [{shipment: {balance: -0, plan: "basic", code: "ok", birthDate: "2025-03-20", lines: [{income: 1000000, priority: false}, {income: 2.50, priority: false}, {income: -0.5, priority: false}, {income: 0, priority: true}], extraField: "x"}}, {shipment: {balance: 0, birthDate: "2025-03-20", code: "ok", extraField: "x", fee: false, flag: "ok", lines: [{decision: 1000000, income: 1000000, priority: false, surcharge: 78, tag: 1}, {decision: 2.50, income: 2.50, priority: false, surcharge: 78, tag: 1}, {decision: -0.5, income: -0.5, priority: false, surcharge: 78, tag: 1}, {decision: 0, income: 0, priority: true, surcharge: 78, tag: 1}], plan: "basic", summary: 0}}], + [{shipment: {balance: 99.99, plan: "basic", code: "gold", birthDate: "2024-01-01", lines: [{income: -0, priority: true}]}}, {shipment: {balance: 99.99, birthDate: "2024-01-01", code: "gold", fee: false, flag: "gold", lines: [{decision: 0, income: 0, priority: true, surcharge: -366, tag: 1}], plan: "basic", summary: 99.99}}], + [{shipment: {balance: 0.000001, plan: "basic", code: "DE", birthDate: "2024-01-01", lines: [{income: 0, priority: true}]}}, {shipment: {balance: 0.000001, birthDate: "2024-01-01", code: "DE", fee: false, flag: "DE", lines: [{decision: 0, income: 0, priority: true, surcharge: -366, tag: 1}], plan: "basic", summary: 0.000001}}], + ], +} + +// seed 333600 (attempt 0) +{ + name: "a 37: borrower/parcels: 1 expression, 1 match, 2 table; 1 root, 2 per-member, 3 top-level computed", + policy: { + models: {borrower: {income: "number", flagged: "boolean", score: "number", rate: "number?", urgent: "boolean", amount: "number", parcels: "parcel[]"}, parcel: {age: "number", days: "number", tier: "string(gold|silver|bronze)?", score: "number"}}, + blocks: [ + {match: "parcel.health", arms: [["(parcel.tier ?? '') == 'bronze'", "((borrower.urgent and borrower.urgent) ? string(borrower.score) : string((borrower.rate ?? 0)))"], ["(parcel.tier ?? '') == 'bronze'", "'none'"], ["some(borrower.parcels, (#.tier ?? '') != 'gold')", "trim((borrower.flagged ? 'a' : 'US'))"], ["", "'none'"]]}, + {table: "t2", inputs: ["borrower.income", "borrower.amount", "borrower.flagged"], outputs: ["borrower.capped"], rules: [ + ["< 1", "1000, 100", "", "18"], + ["<= 1.5", "", "false", "5"], + ["[18..50]", "18, 1.5", "", "borrower.income"], + ]}, + {table: "t3", inputs: ["borrower.income", "borrower.amount", "borrower.income"], outputs: ["bonus", "surcharge", "segment"], rules: [ + [">= 18", "5, 18", "", "(borrower.urgent and borrower.urgent)", "string(borrower.income)", "'retail'"], + ["100, 5", "50", "!= 10", "borrower.flagged", "'Oslo'", "(borrower.flagged ? 'Oslo' : 'Oslo')"], + ["", "!= 10", "", "borrower.flagged", "'x'", "'A1'"], + ["", "", "", "borrower.urgent", "'x'", "string(borrower.income)"], + ]}, + {expression: "parcel.summary", value: "(borrower.urgent ? (borrower.capped ?? 0) : borrower.amount)"}, + ], + }, + cases: [ + [{borrower: {income: 1.5, flagged: true, score: 99.99, rate: 0.5, urgent: true, amount: 10, parcels: [{age: 1.5, days: 1000, tier: null, score: -0.01}, {age: 50, days: 1, tier: "silver", score: 7.25}]}}, {bonus: true, borrower: {amount: 10, capped: null, flagged: true, income: 1.5, parcels: [{age: 1.5, days: 1000, health: "a", score: -0.01, summary: 0, tier: null}, {age: 50, days: 1, health: "a", score: 7.25, summary: 0, tier: "silver"}], rate: 0.5, score: 99.99, urgent: true}, segment: "1.5", surcharge: "x"}], + [{borrower: {income: 1.5, flagged: false, score: 50, rate: 1e3, urgent: true, amount: 1.5, parcels: []}}, {bonus: false, borrower: {amount: 1.5, capped: 5, flagged: false, income: 1.5, parcels: [], rate: 1000, score: 50, urgent: true}, segment: "A1", surcharge: "x"}], + [{borrower: {income: 1000, flagged: true, score: -1, rate: 1, urgent: false, amount: 1.5, parcels: []}}, {bonus: true, borrower: {amount: 1.5, capped: null, flagged: true, income: 1000, parcels: [], rate: 1, score: -1, urgent: false}, segment: "A1", surcharge: "x"}], + [{borrower: {income: 5, flagged: false, score: 250, rate: 100, urgent: true, amount: 99.99, parcels: [{age: 2.50, days: 1.5, tier: "gold", score: 50}, {age: -0.5, days: 5, tier: "gold", score: 0.25}]}}, {bonus: false, borrower: {amount: 99.99, capped: null, flagged: false, income: 5, parcels: [{age: 2.50, days: 1.5, health: "none", score: 50, summary: 0, tier: "gold"}, {age: -0.5, days: 5, health: "none", score: 0.25, summary: 0, tier: "gold"}], rate: 100, score: 250, urgent: true}, segment: "A1", surcharge: "x"}], + [{borrower: {income: 50, flagged: true, score: 5, urgent: true, amount: 1000000, parcels: [{age: 2, days: 18, tier: "bronze", score: 0.5}]}}, {bonus: true, borrower: {amount: 1000000, capped: null, flagged: true, income: 50, parcels: [{age: 2, days: 18, health: "5", score: 0.5, summary: 0, tier: "bronze"}], score: 5, urgent: true}, segment: "A1", surcharge: "x"}], + [{borrower: {income: 18, flagged: true, score: 100, rate: null, urgent: true, amount: -500, parcels: [{age: 2.50, days: -0.5, score: 7.25}, {age: 1.5, days: 50, tier: "gold", score: 2}]}}, {bonus: true, borrower: {amount: -500, capped: null, flagged: true, income: 18, parcels: [{age: 2.50, days: -0.5, health: "a", score: 7.25, summary: 0}, {age: 1.5, days: 50, health: "a", score: 2, summary: 0, tier: "gold"}], rate: null, score: 100, urgent: true}, segment: "A1", surcharge: "x"}], + [{borrower: {income: 275, flagged: true, score: 1, rate: 50, urgent: false, amount: 1.5, parcels: [{age: 99999999999999999999, days: 100, score: 5}, {age: 5, days: 0.000001, tier: "gold", score: 100}, {age: 10, days: 1e3, tier: "silver", score: -500}, {age: 1000000, days: 99.99, tier: "gold", score: 18}, {age: 390, days: 18, tier: null, score: 18}]}}, {bonus: true, borrower: {amount: 1.5, capped: null, flagged: true, income: 275, parcels: [{age: 99999999999999999999, days: 100, health: "a", score: 5, summary: 1.5}, {age: 5, days: 0.000001, health: "a", score: 100, summary: 1.5, tier: "gold"}, {age: 10, days: 1000, health: "a", score: -500, summary: 1.5, tier: "silver"}, {age: 1000000, days: 99.99, health: "a", score: 18, summary: 1.5, tier: "gold"}, {age: 390, days: 18, health: "a", score: 18, summary: 1.5, tier: null}], rate: 50, score: 1, urgent: false}, segment: "A1", surcharge: "x"}], + [{borrower: {income: 2, flagged: null, score: 1.5, rate: 18, urgent: true, amount: 100, parcels: [{age: 50, days: 1.5, tier: "bronze", score: -500}, {age: 1000000, days: 2, tier: "bronze", score: 18}, {age: 1000, days: 18, tier: "gold", score: 10}]}}, "!error: MissingRequiredInputs"], + [{borrower: {income: 18, flagged: true, score: 2, rate: -0.5, urgent: false, amount: 18, parcels: [{age: 5, days: 0.1, tier: "bronze", score: 18}, {age: 100, days: 441, score: 1e3}, {age: 123456789.123, days: 50, tier: "gold", score: 1e3}]}}, {bonus: false, borrower: {amount: 18, capped: 18, flagged: true, income: 18, parcels: [{age: 5, days: 0.1, health: "-0.5", score: 18, summary: 18, tier: "bronze"}, {age: 100, days: 441, health: "a", score: 1000, summary: 18}, {age: 123456789.123, days: 50, health: "a", score: 1000, summary: 18, tier: "gold"}], rate: -0.5, score: 2, urgent: false}, segment: "retail", surcharge: "18"}], + [{borrower: {income: 449, flagged: true, score: 1.5, rate: -1, urgent: "true", amount: 65, parcels: [{age: 99999999999999999999, days: 1, tier: "gold", score: 18}]}}, "!error: InputValidationFailed"], + [{borrower: {income: 1.5, flagged: true, score: 0.1, rate: 5, urgent: true, amount: 10, parcels: [{age: 18, days: 5, score: 1e3}]}}, {bonus: true, borrower: {amount: 10, capped: null, flagged: true, income: 1.5, parcels: [{age: 18, days: 5, health: "a", score: 1000, summary: 0}], rate: 5, score: 0.1, urgent: true}, segment: "1.5", surcharge: "x"}], + [{borrower: {income: 250, flagged: true, score: 18, rate: -0, urgent: false, amount: 2, parcels: [{age: 1.5, days: 1, tier: "bronze", score: 18}], extraField: 1}}, {bonus: true, borrower: {amount: 2, capped: null, extraField: 1, flagged: true, income: 250, parcels: [{age: 1.5, days: 1, health: "0", score: 18, summary: 2, tier: "bronze"}], rate: 0, score: 18, urgent: false}, segment: "A1", surcharge: "x"}], + ], +} + +// seed 333700 (attempt 0) +{ + name: "a 38: claim/accounts: 2 assertion, 2 expression, 2 match, 1 table; 3 root, 4 per-member, 1 top-level computed", + policy: { + models: {claim: {income: "number", verified: "boolean?", sku: "string", plan: "string(basic|plus|premium|trial)?", score: "number?", region: "string?", accounts: "acct[]"}, acct: {balance: "number", verified: "boolean?"}}, + blocks: [ + {expression: "eligible", value: "all(claim.accounts, #.exposure == null)"}, + {assertion: "claim.health", conditions: [["or", "startsWith(claim.fee, 'gold')", 2], ["or", "(claim.region ?? '') in ['US', 'Oslo']", 1]]}, + {match: "claim.fee", arms: [["not ((claim.verified ?? false))", "(claim.region ?? '')"], ["some(claim.accounts, #.balance == #.balance)", "lower(((claim.region ?? '') + '-' + claim.sku))"], ["", "claim.sku"]]}, + {match: "acct.adjusted", arms: [["(claim.score ?? 0) != (claim.score ?? 0)", "(claim.region ?? '')"], ["(claim.income + (claim.score ?? 0)) < 18", "(((acct.verified ?? false) ? claim.sku : (claim.region ?? '')) + '-' + ((claim.verified ?? false) ? claim.sku : (claim.region ?? '')))"], ["claim.income > (claim.score ?? 0)", "(claim.region ?? '')"], ["", "claim.sku"]]}, + {table: "t3", inputs: ["claim.income", "claim.score"], outputs: ["acct.exposure", "acct.net[]"], rules: [ + ["10, 250", "", "(claim.region ?? '')", "some(claim.accounts, 2 >= #.balance)"], + ["[1000..1002]", "0.5", "(claim.region ?? '')", "(acct.verified ?? false)"], + ["", "3, 3", "(claim.region ?? '')", "(claim.verified ?? false)"], + ["", "0.5, 0.25", "(claim.region ?? '')", "(claim.verified ?? false)"], + ]}, + {expression: "acct.quota", value: "len(claim.fee)"}, + {assertion: "claim.bucket", conditions: [["or", "claim.income < claim.income", 1], ["and", "claim.income < claim.income", 2]]}, + ], + }, + cases: [ + [{claim: {income: 18, verified: false, sku: " pad ", plan: "basic", score: -0.5, region: "VIP", accounts: []}}, {claim: {accounts: [], bucket: false, fee: "VIP", health: false, income: 18, plan: "basic", region: "VIP", score: -0.5, sku: " pad ", verified: false}, eligible: true}], + [{claim: {income: 1000, verified: true, sku: "US", plan: "plus", score: 1000, region: "12", accounts: [{balance: 113, verified: true}]}}, {claim: {accounts: [{adjusted: "US", balance: 113, exposure: null, net: [], quota: 5, verified: true}], bucket: false, fee: "12-us", health: false, income: 1000, plan: "plus", region: "12", score: 1000, sku: "US", verified: true}, eligible: true}], + [{claim: {income: 99.99, verified: false, sku: "Oslo", plan: "premium", score: 18, region: "é ü", accounts: [{balance: 0.5, verified: true}]}}, {claim: {accounts: [{adjusted: "é ü", balance: 0.5, exposure: null, net: [], quota: 5, verified: true}], bucket: false, fee: "é ü", health: false, income: 99.99, plan: "premium", region: "é ü", score: 18, sku: "Oslo", verified: false}, eligible: true}], + [{claim: {income: 0.25, verified: false, sku: "", plan: "trial", region: "é ü", accounts: [{balance: 100, verified: null}, {balance: 0.5, verified: null}, {balance: 1e3, verified: null}, {balance: -1, verified: null}, {balance: 18, verified: false}]}}, {claim: {accounts: [{adjusted: "é ü-é ü", balance: 100, exposure: null, net: [], quota: 5, verified: null}, {adjusted: "é ü-é ü", balance: 0.5, exposure: null, net: [], quota: 5, verified: null}, {adjusted: "é ü-é ü", balance: 1000, exposure: null, net: [], quota: 5, verified: null}, {adjusted: "é ü-é ü", balance: -1, exposure: null, net: [], quota: 5, verified: null}, {adjusted: "é ü-é ü", balance: 18, exposure: null, net: [], quota: 5, verified: false}], bucket: false, fee: "é ü", health: false, income: 0.25, plan: "trial", region: "é ü", sku: "", verified: false}, eligible: true}], + [{claim: {income: 1000000, verified: null, sku: "O'Neil", plan: null, score: null, region: "", accounts: [{balance: 0.1}]}}, {claim: {accounts: [{adjusted: "", balance: 0.1, exposure: null, net: [], quota: 0}], bucket: false, fee: "", health: false, income: 1000000, plan: null, region: "", score: null, sku: "O'Neil", verified: null}, eligible: true}], + [{claim: {income: 250, verified: false, sku: "DE", plan: "basic", score: 0.5, region: "gold", accounts: [{balance: 0.5, verified: true}, {balance: 18, verified: true}, {balance: 1e3, verified: true}, {balance: 3, verified: false}, {balance: 18, verified: true}]}}, {claim: {accounts: [{adjusted: "gold", balance: 0.5, exposure: "gold", net: [true, false], quota: 4, verified: true}, {adjusted: "gold", balance: 18, exposure: "gold", net: [true, false], quota: 4, verified: true}, {adjusted: "gold", balance: 1000, exposure: "gold", net: [true, false], quota: 4, verified: true}, {adjusted: "gold", balance: 3, exposure: "gold", net: [true, false], quota: 4, verified: false}, {adjusted: "gold", balance: 18, exposure: "gold", net: [true, false], quota: 4, verified: true}], bucket: false, fee: "gold", health: true, income: 250, plan: "basic", region: "gold", score: 0.5, sku: "DE", verified: false}, eligible: false}], + [{claim: {income: 3, verified: false, sku: "Oslo", plan: "trial", score: 1e3, region: "gold", accounts: [{balance: 0, verified: true}], extraField: "x"}}, {claim: {accounts: [{adjusted: "Oslo", balance: 0, exposure: null, net: [], quota: 4, verified: true}], bucket: false, extraField: "x", fee: "gold", health: true, income: 3, plan: "trial", region: "gold", score: 1000, sku: "Oslo", verified: false}, eligible: true}], + [{claim: {income: 3, verified: null, sku: "日本", plan: "trial", score: 2, region: null, accounts: [{balance: 10}, {balance: 3}]}}, {claim: {accounts: [{adjusted: "-", balance: 10, exposure: null, net: [], quota: 0}, {adjusted: "-", balance: 3, exposure: null, net: [], quota: 0}], bucket: false, fee: "", health: false, income: 3, plan: "trial", region: null, score: 2, sku: "日本", verified: null}, eligible: true}], + [{claim: {income: -0.5, sku: "NL", plan: "premium", accounts: [{balance: 2, verified: true}, {balance: 1000}, {balance: 250, verified: false}, {balance: 0}]}}, {claim: {accounts: [{adjusted: "NL-", balance: 2, exposure: null, net: [], quota: 0, verified: true}, {adjusted: "-", balance: 1000, exposure: null, net: [], quota: 0}, {adjusted: "-", balance: 250, exposure: null, net: [], quota: 0, verified: false}, {adjusted: "-", balance: 0, exposure: null, net: [], quota: 0}], bucket: false, fee: "", health: false, income: -0.5, plan: "premium", sku: "NL"}, eligible: true}], + [{claim: {income: 0, verified: "true", sku: "12", plan: "premium", score: 62, region: "retail", accounts: [{balance: 123456789.123, verified: true}, {balance: 250, verified: false}, {balance: 18, verified: false}, {balance: 1000, verified: true}, {balance: 1, verified: true}]}}, "!error: InputValidationFailed"], + [{claim: {income: 2.50, verified: false, sku: "abc", plan: "plus", score: 250, region: "retail", accounts: [{balance: 0.25, verified: false}, {balance: 18, verified: true}]}}, {claim: {accounts: [{adjusted: "abc", balance: 0.25, exposure: null, net: [], quota: 6, verified: false}, {adjusted: "abc", balance: 18, exposure: null, net: [], quota: 6, verified: true}], bucket: false, fee: "retail", health: false, income: 2.50, plan: "plus", region: "retail", score: 250, sku: "abc", verified: false}, eligible: true}], + [{claim: {income: 18, verified: true, sku: "a-b-c", plan: "premium", score: 250, region: "retail", accounts: [{balance: -1, verified: true}, {balance: -0.01, verified: false}], extraField: "x"}}, {claim: {accounts: [{adjusted: "a-b-c", balance: -1, exposure: null, net: [], quota: 12, verified: true}, {adjusted: "a-b-c", balance: -0.01, exposure: null, net: [], quota: 12, verified: false}], bucket: false, extraField: "x", fee: "retail-a-b-c", health: false, income: 18, plan: "premium", region: "retail", score: 250, sku: "a-b-c", verified: true}, eligible: true}], + [{claim: {income: 0, verified: null, sku: "", plan: "basic", score: 0.25, accounts: [{balance: 0.25}]}}, {claim: {accounts: [{adjusted: "-", balance: 0.25, exposure: "", net: [false], quota: 0}], bucket: false, fee: "", health: false, income: 0, plan: "basic", score: 0.25, sku: "", verified: null}, eligible: false}], + [{claim: {income: 1000, verified: true, sku: "12", plan: "plus", score: 0.5, region: "12", accounts: []}}, {claim: {accounts: [], bucket: false, fee: "12", health: false, income: 1000, plan: "plus", region: "12", score: 0.5, sku: "12", verified: true}, eligible: true}], + [{claim: {income: -0, sku: "", plan: "basic", region: "x", accounts: [{balance: 123456789.123, verified: false}, {balance: 99999999999999999999, verified: null}, {balance: 3, verified: null}, {balance: 99.99, verified: null}]}}, {claim: {accounts: [{adjusted: "x-x", balance: 123456789.123, exposure: null, net: [], quota: 1, verified: false}, {adjusted: "x-x", balance: 99999999999999999999, exposure: null, net: [], quota: 1, verified: null}, {adjusted: "x-x", balance: 3, exposure: null, net: [], quota: 1, verified: null}, {adjusted: "x-x", balance: 99.99, exposure: null, net: [], quota: 1, verified: null}], bucket: false, fee: "x", health: false, income: 0, plan: "basic", region: "x", sku: ""}, eligible: true}], + [{claim: {income: 0.5, verified: false, sku: "é ü", plan: "premium", score: 65, region: "gold", accounts: [{balance: 1000000, verified: false}], extraField: "x"}}, {claim: {accounts: [{adjusted: "é ü", balance: 1000000, exposure: null, net: [], quota: 4, verified: false}], bucket: false, extraField: "x", fee: "gold", health: true, income: 0.5, plan: "premium", region: "gold", score: 65, sku: "é ü", verified: false}, eligible: true}], + [{claim: {income: null, verified: false, sku: "3.5", plan: "plus", score: -500, region: "", accounts: [{balance: 99999999999999999999, verified: false}, {balance: 10, verified: true}, {balance: 18, verified: true}, {balance: 10, verified: true}, {balance: 0.25, verified: true}]}}, "!error: MissingRequiredInputs"], + [{claim: {income: 0.25, verified: true, sku: "x-y", plan: "plus", score: null, region: "", accounts: [{balance: 18}]}}, {claim: {accounts: [{adjusted: "-x-y", balance: 18, exposure: null, net: [], quota: 4}], bucket: false, fee: "-x-y", health: false, income: 0.25, plan: "plus", region: "", score: null, sku: "x-y", verified: true}, eligible: true}], + [{claim: {income: 99999999999999999999, verified: false, sku: "12", plan: "trial", score: 0.25, region: "Oslo", accounts: []}}, {claim: {accounts: [], bucket: false, fee: "Oslo", health: true, income: 99999999999999999999, plan: "trial", region: "Oslo", score: 0.25, sku: "12", verified: false}, eligible: true}], + [{claim: {income: 1000000, verified: true, sku: "gold", plan: "basic", score: 3, region: " pad ", accounts: [{balance: 3, verified: true}, {balance: -0, verified: false}]}}, {claim: {accounts: [{adjusted: " pad ", balance: 3, exposure: " pad ", net: [true], quota: 11, verified: true}, {adjusted: " pad ", balance: 0, exposure: " pad ", net: [true], quota: 11, verified: false}], bucket: false, fee: " pad -gold", health: false, income: 1000000, plan: "basic", region: " pad ", score: 3, sku: "gold", verified: true}, eligible: false}], + [{claim: {income: 18, verified: false, sku: "12", plan: "basic", score: 0.5, region: "US", accounts: []}}, {claim: {accounts: [], bucket: false, fee: "US", health: true, income: 18, plan: "basic", region: "US", score: 0.5, sku: "12", verified: false}, eligible: true}], + ], +} + +// seed 333800 (attempt 0) +{ + name: "a 39: borrower/vehicles: 3 expression, 2 match, 3 table; 2 root, 8 per-member, 2 top-level computed", + policy: { + models: {borrower: {price: "number", birthDate: "date", kind: "string(retail|corporate)", days: "number?", vehicles: "vehicle[]"}, vehicle: {balance: "number", channel: "string", since: "date"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {match: "tag", arms: [["borrower.birthDate > d('2000-06-30')", "1000 > 1"], ["", "(1000 <= 1000 or factor <= 1)"]]}, + {table: "t4", inputs: ["vehicle.balance"], outputs: ["vehicle.review[]"], rules: [ + [">= 18", "tag"], + ["<= 18", "tag"], + ["50", "(borrower.days ?? 0) <= vehicle.balance"], + ["250, 1.5", "tag"], + ["> 2", "vehicle.balance in [23..100]"], + ["", "tag"], + ["", ""], + ]}, + {expression: "borrower.share", value: "borrower.days == null"}, + {expression: "vehicle.eligible", value: "round((250 + vehicle.balance), 2)"}, + {table: "t2", hit: "collect", inputs: [null, "len(vehicle.channel)"], outputs: ["vehicle.total", "vehicle.summary", "vehicle.discount"], rules: [ + ["vehicle.since > d('2000-06-30')", "< 1", "1000", "tag", "vehicle.channel"], + ["borrower.days != null", "> 0", "borrower.price", "tag", "(vehicle.channel + '-' + vehicle.channel)"], + ["borrower.days != null", "", "(borrower.days ?? 0)", "borrower.days != null", "vehicle.channel"], + ]}, + {match: "weighted", arms: [["some(borrower.vehicles, #.eligible != #.balance)", "(max(map(borrower.vehicles, #.balance)) ?? 0)"], ["0 > borrower.quota", "borrower.price"], ["borrower.days != null", "(tag ? borrower.price : borrower.price)"], ["", "(borrower.quota + factor)"]]}, + {expression: "borrower.quota", value: "(tag ? 5 : (borrower.days ?? 0))"}, + {table: "t6", inputs: ["factor"], outputs: ["vehicle.surcharge", "vehicle.exposure", "vehicle.segment[]"], rules: [ + ["10", "tag", "borrower.kind != 'corporate'", ""], + ["", "", "all(borrower.vehicles, (#.balance == 100 or #.balance == 50))", "((borrower.days ?? 0) * 0.25)"], + ["!= 250", "tag", "borrower.share", "1000"], + ["<= 2", "borrower.share", "tag", "borrower.price"], + ["!= 3", "tag", "10 <= borrower.quota", "(borrower.days ?? 0)"], + ["", "none(borrower.vehicles, #.balance == #.balance)", "tag", "(borrower.days ?? 0)"], + ]}, + ], + }, + cases: [ + [{factor: -2, borrower: {price: null, birthDate: "1990-06-15", kind: "retail", days: 99.99, vehicles: [{balance: 5, channel: "12", since: "2000-01-01"}]}}, "!error: MissingRequiredInputs"], + [{factor: 0, borrower: {price: 1e3, birthDate: "1990-06-15", kind: "retail", days: 10, vehicles: [{balance: 0, channel: "Oslo", since: "2025-03-20"}]}}, {borrower: {birthDate: "1990-06-15", days: 10, kind: "retail", price: 1000, quota: 5, vehicles: [{balance: 0, channel: "Oslo", discount: ["Oslo-Oslo", "Oslo"], eligible: 250, exposure: false, review: [true, true], segment: [2.50, 1000, 1000, 10, 10], since: "2025-03-20", summary: [true, true], surcharge: true, total: [1000, 10]}]}, factor: 0, tag: true, weighted: 0}], + [{factor: -2, borrower: {price: 1e3, birthDate: "2024-02-29", kind: "corporate", days: null, vehicles: [{balance: 65, channel: "gold", since: "2000-01-01"}, {balance: 1000, channel: "gold", since: "2025-03-20T10:15:30Z"}]}}, {borrower: {birthDate: "2024-02-29", days: null, kind: "corporate", price: 1000, quota: 5, vehicles: [{balance: 65, channel: "gold", discount: [], eligible: 315, exposure: false, review: [true, true, true], segment: [0, 1000, 1000, 0, 0], since: "2000-01-01", summary: [], surcharge: true, total: []}, {balance: 1000, channel: "gold", discount: [], eligible: 1250, exposure: false, review: [true, false, true], segment: [0, 1000, 1000, 0, 0], since: "2025-03-20T10:15:30Z", summary: [], surcharge: true, total: []}]}, factor: -2, tag: true, weighted: 1000}], + [{factor: 0.5, borrower: {price: 10, birthDate: "2025-03-20", kind: "retail", days: null, vehicles: [{balance: 65, channel: "gold", since: "2030-12-31"}, {balance: 1, channel: "12", since: "2000-01-01"}, {balance: 50, channel: "gold", since: "2024-02-29"}, {balance: 3, channel: "3.5", since: "2024-02-29"}, {balance: 1000000, channel: "VIP", since: "2024-01-01"}]}}, {borrower: {birthDate: "2025-03-20", days: null, kind: "retail", price: 10, quota: 5, vehicles: [{balance: 65, channel: "gold", discount: [], eligible: 315, exposure: false, review: [true, true, true], segment: [0, 1000, 10, 0, 0], since: "2030-12-31", summary: [], surcharge: true, total: []}, {balance: 1, channel: "12", discount: [], eligible: 251, exposure: false, review: [true, true], segment: [0, 1000, 10, 0, 0], since: "2000-01-01", summary: [], surcharge: true, total: []}, {balance: 50, channel: "gold", discount: [], eligible: 300, exposure: false, review: [true, true, true, true], segment: [0, 1000, 10, 0, 0], since: "2024-02-29", summary: [], surcharge: true, total: []}, {balance: 3, channel: "3.5", discount: [], eligible: 253, exposure: false, review: [true, false, true], segment: [0, 1000, 10, 0, 0], since: "2024-02-29", summary: [], surcharge: true, total: []}, {balance: 1000000, channel: "VIP", discount: [], eligible: 1000250, exposure: false, review: [true, false, true], segment: [0, 1000, 10, 0, 0], since: "2024-01-01", summary: [], surcharge: true, total: []}]}, factor: 0.5, tag: true, weighted: 1000000}], + [{factor: 100, borrower: {price: 5, birthDate: "2025-03-20", kind: "corporate", days: 18, vehicles: []}}, {borrower: {birthDate: "2025-03-20", days: 18, kind: "corporate", price: 5, quota: 5, vehicles: []}, factor: 100, tag: true, weighted: 5}], + [{factor: -2, borrower: {price: 65, birthDate: "2025-03-20T10:15:30Z", kind: "retail", days: null, vehicles: []}}, {borrower: {birthDate: "2025-03-20T10:15:30Z", days: null, kind: "retail", price: 65, quota: 5, vehicles: []}, factor: -2, tag: true, weighted: 3}], + [{factor: 10, borrower: {price: 18, birthDate: "2025-03-20", kind: "retail", days: null, vehicles: [{balance: 2, channel: "retail", since: "2000-01-01"}, {balance: 50, channel: "Oslo", since: "2025-03-20T10:15:30Z"}, {balance: 1.5, channel: "é ü", since: "2025-03-20"}, {balance: 100, channel: "A1", since: "2025-03-20T10:15:30Z"}, {balance: 250, channel: "-", since: "2024-01-01"}]}}, {borrower: {birthDate: "2025-03-20", days: null, kind: "retail", price: 18, quota: 5, vehicles: [{balance: 2, channel: "retail", discount: [], eligible: 252, exposure: true, review: [true, true], segment: [0, 1000, 0, 0], since: "2000-01-01", summary: [], surcharge: true, total: []}, {balance: 50, channel: "Oslo", discount: [], eligible: 300, exposure: true, review: [true, true, true, true], segment: [0, 1000, 0, 0], since: "2025-03-20T10:15:30Z", summary: [], surcharge: true, total: []}, {balance: 1.5, channel: "é ü", discount: [], eligible: 251.5, exposure: true, review: [true, true, true], segment: [0, 1000, 0, 0], since: "2025-03-20", summary: [], surcharge: true, total: []}, {balance: 100, channel: "A1", discount: [], eligible: 350, exposure: true, review: [true, true, true], segment: [0, 1000, 0, 0], since: "2025-03-20T10:15:30Z", summary: [], surcharge: true, total: []}, {balance: 250, channel: "-", discount: [], eligible: 500, exposure: true, review: [true, true, false, true], segment: [0, 1000, 0, 0], since: "2024-01-01", summary: [], surcharge: true, total: []}]}, factor: 10, tag: true, weighted: 250}], + [{factor: 10, borrower: {price: 123456789.123, birthDate: "2025-03-20", kind: "corporate", days: 1, vehicles: []}}, {borrower: {birthDate: "2025-03-20", days: 1, kind: "corporate", price: 123456789.123, quota: 5, vehicles: []}, factor: 10, tag: true, weighted: 123456789.123}], + [{factor: 100, borrower: {price: 2, birthDate: "2000-01-01", kind: "retail", days: 2, vehicles: [{balance: 1000, channel: "Zed", since: "2000-01-01"}, {balance: 50, channel: "Oslo", since: "2000-01-01"}]}}, {borrower: {birthDate: "2000-01-01", days: 2, kind: "retail", price: 2, quota: 5, vehicles: [{balance: 1000, channel: "Zed", discount: ["Zed-Zed", "Zed"], eligible: 1250, exposure: false, review: [true, false, true], segment: [0.50, 1000, 2, 2], since: "2000-01-01", summary: [true, true], surcharge: true, total: [2, 2]}, {balance: 50, channel: "Oslo", discount: ["Oslo-Oslo", "Oslo"], eligible: 300, exposure: false, review: [true, true, true, true], segment: [0.50, 1000, 2, 2], since: "2000-01-01", summary: [true, true], surcharge: true, total: [2, 2]}]}, factor: 100, tag: true, weighted: 1000}], + [{factor: 10, borrower: {price: 1.5, birthDate: "1990-06-15", kind: "corporate", days: 250, vehicles: []}}, {borrower: {birthDate: "1990-06-15", days: 250, kind: "corporate", price: 1.5, quota: 5, vehicles: []}, factor: 10, tag: true, weighted: 1.5}], + [{factor: -2, borrower: {price: 250, birthDate: "1990-06-15", kind: "retail", days: 5, vehicles: [{balance: 2, channel: "abc", since: "2025-03-20T10:15:30Z"}, {balance: 50, channel: "retail", since: "2025-03-20"}]}}, {borrower: {birthDate: "1990-06-15", days: 5, kind: "retail", price: 250, quota: 5, vehicles: [{balance: 2, channel: "abc", discount: ["abc-abc", "abc"], eligible: 252, exposure: false, review: [true, true], segment: [1.25, 1000, 250, 5, 5], since: "2025-03-20T10:15:30Z", summary: [true, true], surcharge: true, total: [250, 5]}, {balance: 50, channel: "retail", discount: ["retail-retail", "retail"], eligible: 300, exposure: false, review: [true, true, true, true], segment: [1.25, 1000, 250, 5, 5], since: "2025-03-20", summary: [true, true], surcharge: true, total: [250, 5]}]}, factor: -2, tag: true, weighted: 50}], + [{factor: 100, borrower: {price: 0.1, birthDate: "2025-03-20", kind: "retail", days: 1000, vehicles: [{balance: 100, channel: "a", since: "2024-02-29"}, {balance: 250, channel: "3.5", since: "1990-06-15"}, {balance: 10, channel: "gold", since: "2030-12-31"}, {balance: -500, channel: "a", since: "2025-03-20T10:15:30Z"}, {balance: 123456789.123, channel: "gold", since: "2024-01-01"}], extraField: {nested: true}}}, {borrower: {birthDate: "2025-03-20", days: 1000, extraField: {nested: true}, kind: "retail", price: 0.1, quota: 5, vehicles: [{balance: 100, channel: "a", discount: ["a-a", "a"], eligible: 350, exposure: false, review: [true, true, true], segment: [250.00, 1000, 1000, 1000], since: "2024-02-29", summary: [true, true], surcharge: true, total: [0.1, 1000]}, {balance: 250, channel: "3.5", discount: ["3.5-3.5", "3.5"], eligible: 500, exposure: false, review: [true, true, false, true], segment: [250.00, 1000, 1000, 1000], since: "1990-06-15", summary: [true, true], surcharge: true, total: [0.1, 1000]}, {balance: 10, channel: "gold", discount: ["gold-gold", "gold"], eligible: 260, exposure: false, review: [true, false, true], segment: [250.00, 1000, 1000, 1000], since: "2030-12-31", summary: [true, true], surcharge: true, total: [0.1, 1000]}, {balance: -500, channel: "a", discount: ["a-a", "a"], eligible: -250, exposure: false, review: [true, true], segment: [250.00, 1000, 1000, 1000], since: "2025-03-20T10:15:30Z", summary: [true, true], surcharge: true, total: [0.1, 1000]}, {balance: 123456789.123, channel: "gold", discount: ["gold-gold", "gold"], eligible: 123457039.12, exposure: false, review: [true, false, true], segment: [250.00, 1000, 1000, 1000], since: "2024-01-01", summary: [true, true], surcharge: true, total: [0.1, 1000]}]}, factor: 100, tag: true, weighted: 123456789.123}], + ], +} + +// seed 333900 (attempt 0) +{ + name: "a 40: borrower/vehicles: 1 assertion, 1 expression, 1 match; 0 root, 2 per-member, 1 top-level computed", + policy: { + models: {borrower: {days: "number?", priority: "boolean?", city: "string", code: "string?", birthDate: "date", insured: "boolean", vehicles: "vehicle[]"}, vehicle: {limit: "number", urgent: "boolean", income: "number"}}, + blocks: [ + {expression: "vehicle.surcharge", value: "round((avg(map(borrower.vehicles, (#.limit - #.income))) ?? 0))"}, + {match: "risk", arms: [["len(borrower.city) <= 5", "(borrower.code ?? '')"], ["not ((borrower.priority ?? false))", "borrower.city"], ["", "borrower.city"]]}, + {assertion: "vehicle.grade", conditions: [["and", "some(borrower.vehicles, not (#.urgent))", 1], ["or", "not (borrower.insured)", 1], "(vehicle.income != vehicle.income and risk != 'high')", ["or", "not (vehicle.urgent)", 1], ["and", "(borrower.days ?? 0) != vehicle.income", 0]]}, + ], + }, + cases: [ + [{borrower: {city: "retail", code: " pad ", birthDate: "2025-03-20", insured: false, vehicles: [{limit: 0.000001, urgent: false, income: 5}, {limit: -0.01, urgent: true, income: 1}]}}, {borrower: {birthDate: "2025-03-20", city: "retail", code: " pad ", insured: false, vehicles: [{grade: true, income: 5, limit: 0.000001, surcharge: -3, urgent: false}, {grade: true, income: 1, limit: -0.01, surcharge: -3, urgent: true}]}, risk: "retail"}], + [{borrower: {days: 0.1, priority: true, city: "日本", code: "ok", birthDate: "1990-06-15", insured: true, vehicles: []}}, {borrower: {birthDate: "1990-06-15", city: "日本", code: "ok", days: 0.1, insured: true, priority: true, vehicles: []}, risk: "日本"}], + [{borrower: {days: 1, priority: true, city: "Oslo", code: "Oslo", birthDate: "1990-06-15", insured: false, vehicles: [{limit: 1e3, urgent: false, income: 2.50}, {limit: 0.000001, urgent: false, income: 1}, {limit: 1000000, urgent: true, income: 1000000}]}}, {borrower: {birthDate: "1990-06-15", city: "Oslo", code: "Oslo", days: 1, insured: false, priority: true, vehicles: [{grade: true, income: 2.50, limit: 1000, surcharge: 332, urgent: false}, {grade: true, income: 1, limit: 0.000001, surcharge: 332, urgent: false}, {grade: true, income: 1000000, limit: 1000000, surcharge: 332, urgent: true}]}, risk: "Oslo"}], + [{borrower: {days: null, priority: null, city: "ok", code: "日本", birthDate: "2025-03-20", insured: true, vehicles: [{limit: 1, urgent: true, income: -0.01}, {limit: 3, urgent: false, income: 0.5}]}}, {borrower: {birthDate: "2025-03-20", city: "ok", code: "日本", days: null, insured: true, priority: null, vehicles: [{grade: true, income: -0.01, limit: 1, surcharge: 2, urgent: true}, {grade: true, income: 0.5, limit: 3, surcharge: 2, urgent: false}]}, risk: "日本"}], + [{borrower: {days: 3, priority: false, city: "Oslo", code: "A1", birthDate: "2024-02-29", insured: true, vehicles: [{limit: 1e3, urgent: true, income: 18}, {limit: 0.1, urgent: true, income: 99999999999999999999}, {limit: 0.5, urgent: false, income: 0.5}]}}, {borrower: {birthDate: "2024-02-29", city: "Oslo", code: "A1", days: 3, insured: true, priority: false, vehicles: [{grade: true, income: 18, limit: 1000, surcharge: -33333333333333333006, urgent: true}, {grade: true, income: 99999999999999999999, limit: 0.1, surcharge: -33333333333333333006, urgent: true}, {grade: true, income: 0.5, limit: 0.5, surcharge: -33333333333333333006, urgent: false}]}, risk: "A1"}], + [{borrower: {days: null, priority: true, city: "é ü", code: null, birthDate: "2024-01-01", insured: false, vehicles: [{limit: 5, urgent: false, income: 0.000001}]}}, {borrower: {birthDate: "2024-01-01", city: "é ü", code: null, days: null, insured: false, priority: true, vehicles: [{grade: true, income: 0.000001, limit: 5, surcharge: 5, urgent: false}]}, risk: ""}], + [{borrower: {days: 1, priority: true, city: "", code: "Oslo", birthDate: "2000-01-01", insured: false, vehicles: [{limit: 0.5, urgent: false, income: 1}, {limit: 2.50, urgent: true, income: -0.01}, {limit: -500, urgent: true, income: 2}, {limit: 0.1, urgent: true, income: 250}]}}, {borrower: {birthDate: "2000-01-01", city: "", code: "Oslo", days: 1, insured: false, priority: true, vehicles: [{grade: true, income: 1, limit: 0.5, surcharge: -187, urgent: false}, {grade: true, income: -0.01, limit: 2.50, surcharge: -187, urgent: true}, {grade: true, income: 2, limit: -500, surcharge: -187, urgent: true}, {grade: true, income: 250, limit: 0.1, surcharge: -187, urgent: true}]}, risk: "Oslo"}], + [{borrower: {days: 7.25, priority: true, city: "NL", code: "O'Neil", birthDate: "2025-03-20T10:15:30Z", insured: false, vehicles: []}}, {borrower: {birthDate: "2025-03-20T10:15:30Z", city: "NL", code: "O'Neil", days: 7.25, insured: false, priority: true, vehicles: []}, risk: "O'Neil"}], + [{borrower: {days: 10, priority: true, city: "DE", code: "DE", birthDate: "2025-03-20T10:15:30Z", insured: true, vehicles: []}}, {borrower: {birthDate: "2025-03-20T10:15:30Z", city: "DE", code: "DE", days: 10, insured: true, priority: true, vehicles: []}, risk: "DE"}], + [{borrower: {days: null, priority: false, city: "", code: null, birthDate: "2024-01-01", insured: false, vehicles: [{limit: 99.99, urgent: true, income: -0.5}, {limit: 5, urgent: false, income: 18}, {limit: 0.000001, urgent: true, income: 99.99}]}}, {borrower: {birthDate: "2024-01-01", city: "", code: null, days: null, insured: false, priority: false, vehicles: [{grade: true, income: -0.5, limit: 99.99, surcharge: -4, urgent: true}, {grade: true, income: 18, limit: 5, surcharge: -4, urgent: false}, {grade: true, income: 99.99, limit: 0.000001, surcharge: -4, urgent: true}]}, risk: ""}], + [{borrower: {days: -500, priority: false, city: "ok", code: "VIP", birthDate: "2030-12-31", insured: false, vehicles: [{limit: 0.1, urgent: false, income: 5}, {limit: 3, urgent: true, income: 0.5}, {limit: -500, urgent: true, income: 18}], extraField: {nested: true}}}, {borrower: {birthDate: "2030-12-31", city: "ok", code: "VIP", days: -500, extraField: {nested: true}, insured: false, priority: false, vehicles: [{grade: true, income: 5, limit: 0.1, surcharge: -173, urgent: false}, {grade: true, income: 0.5, limit: 3, surcharge: -173, urgent: true}, {grade: true, income: 18, limit: -500, surcharge: -173, urgent: true}]}, risk: "VIP"}], + [{borrower: {city: "NL", code: "a", birthDate: "2024-02-29", insured: true, vehicles: [{limit: 3, urgent: false, income: -0.5}, {limit: 100, urgent: false, income: 2.50}]}}, {borrower: {birthDate: "2024-02-29", city: "NL", code: "a", insured: true, vehicles: [{grade: true, income: -0.5, limit: 3, surcharge: 51, urgent: false}, {grade: true, income: 2.50, limit: 100, surcharge: 51, urgent: false}]}, risk: "a"}], + [{borrower: {days: 100, city: "VIP", birthDate: "2024-01-01", insured: true, vehicles: [{limit: 7.25, urgent: true, income: 100}]}}, {borrower: {birthDate: "2024-01-01", city: "VIP", days: 100, insured: true, vehicles: [{grade: false, income: 100, limit: 7.25, surcharge: -93, urgent: true}]}, risk: ""}], + [{borrower: {days: null, priority: null, city: "O'Neil", code: " pad ", birthDate: "2024-02-29", insured: true, vehicles: [{limit: 123456789.123, urgent: false, income: -1}, {limit: 340, urgent: false, income: 10}, {limit: 0, urgent: false, income: 5}, {limit: 2.50, urgent: false, income: 99.99}]}}, {borrower: {birthDate: "2024-02-29", city: "O'Neil", code: " pad ", days: null, insured: true, priority: null, vehicles: [{grade: true, income: -1, limit: 123456789.123, surcharge: 30864254, urgent: false}, {grade: true, income: 10, limit: 340, surcharge: 30864254, urgent: false}, {grade: true, income: 5, limit: 0, surcharge: 30864254, urgent: false}, {grade: true, income: 99.99, limit: 2.50, surcharge: 30864254, urgent: false}]}, risk: "O'Neil"}], + [{borrower: {days: 1000000, priority: true, city: "DE", birthDate: "1990-06-15", insured: false, vehicles: [{limit: -500, urgent: true, income: 99.99}, {limit: 100, urgent: false, income: -0.01}, {limit: 1000, urgent: false, income: 5}, {limit: 1, urgent: true, income: 1e3}, {limit: -1, urgent: false, income: 250}]}}, {borrower: {birthDate: "1990-06-15", city: "DE", days: 1000000, insured: false, priority: true, vehicles: [{grade: true, income: 99.99, limit: -500, surcharge: -151, urgent: true}, {grade: true, income: -0.01, limit: 100, surcharge: -151, urgent: false}, {grade: true, income: 5, limit: 1000, surcharge: -151, urgent: false}, {grade: true, income: 1000, limit: 1, surcharge: -151, urgent: true}, {grade: true, income: 250, limit: -1, surcharge: -151, urgent: false}]}, risk: ""}], + [{borrower: {days: 1e3, priority: false, city: "high", code: "3.5", birthDate: "1990-06-15", insured: true, vehicles: [{limit: 1e3, urgent: true, income: 1000}]}}, {borrower: {birthDate: "1990-06-15", city: "high", code: "3.5", days: 1000, insured: true, priority: false, vehicles: [{grade: false, income: 1000, limit: 1000, surcharge: 0, urgent: true}]}, risk: "3.5"}], + [{borrower: {days: 1, priority: true, city: "NL", code: "NL", birthDate: "2030-12-31", insured: false, vehicles: [{limit: 0.5, urgent: true, income: 5}, {limit: 0.000001, urgent: false, income: 65}]}}, {borrower: {birthDate: "2030-12-31", city: "NL", code: "NL", days: 1, insured: false, priority: true, vehicles: [{grade: true, income: 5, limit: 0.5, surcharge: -35, urgent: true}, {grade: true, income: 65, limit: 0.000001, surcharge: -35, urgent: false}]}, risk: "NL"}], + ], +} + +// seed 334000 (attempt 0) +{ + name: "a 41: shipment/parcels: 1 expression, 2 match, 1 table; 1 root, 1 per-member, 4 top-level computed", + policy: { + models: {shipment: {price: "number?", since: "date", limit: "number?", score: "number", code: "string", parcels: "parcel[]"}, parcel: {income: "number", score: "number", since: "date"}}, + blocks: [ + {expression: "shipment.segment", value: "ceil((((shipment.price ?? 0) * shipment.score) + len(shipment.code)))"}, + {match: "capped", arms: [["shipment.limit != null", "trim(string((shipment.price ?? 0)))"], ["(not ((shipment.limit ?? 0) <= 10) and shipment.limit != null)", "upper((shipment.code + '-' + shipment.code))"], ["", "shipment.code"]]}, + {table: "t3", hit: "collect", inputs: ["capped", "shipment.since"], outputs: ["grade", "weighted", "risk"], rules: [ + ["", "", "shipment.code", "(shipment.limit ?? 0)", ""], + ["'Oslo', 'ok'", ">= d('2024-01-01')", "capped", "(shipment.price ?? 0)", "shipment.segment == 0.5"], + ["", "", "('a' + '-' + capped)", "shipment.segment", "(shipment.price ?? 0) <= 5"], + ]}, + {match: "parcel.share", arms: [["shipment.score != parcel.income", "sum(map(shipment.parcels, (#.score == 1 ? #.score : #.score)))"], ["not (parcel.income != (shipment.limit ?? 0))", "sum(map(shipment.parcels, max([#.score, #.income])))"], ["floor(shipment.score) != parcel.income", "(shipment.limit ?? 0)"], ["", "parcel.income"]]}, + ], + }, + cases: [ + [{shipment: {price: 1000, since: "2024-02-29", limit: 99999999999999999999, score: -1, code: "Oslo", parcels: [{income: 123456789.123, score: -0.01, since: "2025-03-20"}]}}, {capped: "1000", grade: ["Oslo", "a-1000"], risk: [false], shipment: {code: "Oslo", limit: 99999999999999999999, parcels: [{income: 123456789.123, score: -0.01, share: -0.01, since: "2025-03-20"}], price: 1000, score: -1, segment: -996, since: "2024-02-29"}, weighted: [99999999999999999999, -996]}], + [{shipment: {price: 1000, since: "2024-01-01", limit: null, score: 100, code: "A1", parcels: [{income: 0, score: 100, since: "2024-01-01"}, {income: 250, score: 10, since: "2024-02-29"}, {income: 0.5, score: -0.01, since: "1990-06-15"}, {income: -0.5, score: 2, since: "2000-01-01"}]}}, {capped: "A1", grade: ["A1", "a-A1"], risk: [false], shipment: {code: "A1", limit: null, parcels: [{income: 0, score: 100, share: 111.99, since: "2024-01-01"}, {income: 250, score: 10, share: 111.99, since: "2024-02-29"}, {income: 0.5, score: -0.01, share: 111.99, since: "1990-06-15"}, {income: -0.5, score: 2, share: 111.99, since: "2000-01-01"}], price: 1000, score: 100, segment: 100002, since: "2024-01-01"}, weighted: [0, 100002]}], + [{shipment: {price: -1, since: "2025-03-20", limit: -0.01, score: -500, code: "VIP", parcels: [{income: 1000000, score: 65, since: "2025-03-20"}, {income: 0.5, score: 0.5, since: "1990-06-15"}, {income: 1000, score: 1000000, since: "1990-06-15"}, {income: -0.5, score: 0, since: "2024-02-29"}, {income: 123456789.123, score: 10, since: "2000-01-01"}]}}, {capped: "-1", grade: ["VIP", "a--1"], risk: [true], shipment: {code: "VIP", limit: -0.01, parcels: [{income: 1000000, score: 65, share: 1000075.5, since: "2025-03-20"}, {income: 0.5, score: 0.5, share: 1000075.5, since: "1990-06-15"}, {income: 1000, score: 1000000, share: 1000075.5, since: "1990-06-15"}, {income: -0.5, score: 0, share: 1000075.5, since: "2024-02-29"}, {income: 123456789.123, score: 10, share: 1000075.5, since: "2000-01-01"}], price: -1, score: -500, segment: 503, since: "2025-03-20"}, weighted: [-0.01, 503]}], + [{shipment: {price: 2, since: "2030-12-31", limit: 415, score: 100, code: "-", parcels: [{income: null, score: -0, since: "2025-03-20T10:15:30Z"}, {income: 0.5, score: 5, since: "2030-12-31"}, {income: 1, score: 10, since: "2024-01-01"}, {income: 7.25, score: -0, since: "2024-02-29"}, {income: 5, score: 99.99, since: "2025-03-20T10:15:30Z"}]}}, {capped: "2", grade: ["-", "a-2"], risk: [true], shipment: {code: "-", limit: 415, parcels: [{income: null, score: 0, share: 114.99, since: "2025-03-20T10:15:30Z"}, {income: 0.5, score: 5, share: 114.99, since: "2030-12-31"}, {income: 1, score: 10, share: 114.99, since: "2024-01-01"}, {income: 7.25, score: 0, share: 114.99, since: "2024-02-29"}, {income: 5, score: 99.99, share: 114.99, since: "2025-03-20T10:15:30Z"}], price: 2, score: 100, segment: 201, since: "2030-12-31"}, weighted: [415, 201]}], + [{shipment: {since: "2024-01-01", limit: 0, score: 5, code: "abc", parcels: [{income: 99.99, score: 7.25, since: "2024-02-29"}, {income: 1000000, score: -0.5, since: "2030-12-31"}]}}, {capped: "0", grade: ["abc", "a-0"], risk: [true], shipment: {code: "abc", limit: 0, parcels: [{income: 99.99, score: 7.25, share: 6.75, since: "2024-02-29"}, {income: 1000000, score: -0.5, share: 6.75, since: "2030-12-31"}], score: 5, segment: 3, since: "2024-01-01"}, weighted: [0, 3]}], + [{shipment: {price: -0, since: "2025-03-20", limit: -500, score: -0, code: "a", parcels: [{income: 2.50, score: 18, since: "2000-01-01"}]}}, {capped: "0", grade: ["a", "a-0"], risk: [true], shipment: {code: "a", limit: -500, parcels: [{income: 2.50, score: 18, share: 18, since: "2000-01-01"}], price: 0, score: 0, segment: 1, since: "2025-03-20"}, weighted: [-500, 1]}], + [{shipment: {price: 10, since: "2000-01-01", limit: 1, score: 10, code: "ok", parcels: [], extraField: {nested: true}}}, {capped: "10", grade: ["ok", "a-10"], risk: [false], shipment: {code: "ok", extraField: {nested: true}, limit: 1, parcels: [], price: 10, score: 10, segment: 102, since: "2000-01-01"}, weighted: [1, 102]}], + [{shipment: {price: 2, since: "2024-02-29", limit: null, score: 0, code: "retail", parcels: [{income: 0, score: 0.000001, since: "2025-03-20"}]}}, {capped: "retail", grade: ["retail", "a-retail"], risk: [true], shipment: {code: "retail", limit: null, parcels: [{income: 0, score: 0.000001, share: 0.000001, since: "2025-03-20"}], price: 2, score: 0, segment: 6, since: "2024-02-29"}, weighted: [0, 6]}], + [{shipment: {price: -0.5, since: "1990-06-15", score: 100, code: "ok", parcels: [{income: 18, score: 228, since: "1990-06-15"}]}}, {capped: "ok", grade: ["ok", "a-ok"], risk: [true], shipment: {code: "ok", parcels: [{income: 18, score: 228, share: 228, since: "1990-06-15"}], price: -0.5, score: 100, segment: -48, since: "1990-06-15"}, weighted: [0, -48]}], + [{shipment: {price: 2.50, since: "2024-01-01", limit: 65, score: 1, code: "US", parcels: [{income: -1, score: -0, since: "2025-03-20"}]}}, {capped: "2.50", grade: ["US", "a-2.50"], risk: [true], shipment: {code: "US", limit: 65, parcels: [{income: -1, score: 0, share: 0, since: "2025-03-20"}], price: 2.50, score: 1, segment: 5, since: "2024-01-01"}, weighted: [65, 5]}], + [{shipment: {price: 7.25, since: "2000-01-01", limit: 1e3, score: 10, code: "é ü", parcels: [{income: 10, score: 2.50, since: "2000-01-01"}]}}, {capped: "7.25", grade: ["é ü", "a-7.25"], risk: [false], shipment: {code: "é ü", limit: 1000, parcels: [{income: 10, score: 2.50, share: 10, since: "2000-01-01"}], price: 7.25, score: 10, segment: 78, since: "2000-01-01"}, weighted: [1000, 78]}], + [{shipment: {price: 0.5, since: "1990-06-15", limit: 0.5, score: -1, code: "ok", parcels: [{income: 1, score: -1, since: "2025-03-20"}, {income: 10, score: 10, since: "2025-03-20"}, {income: 250, score: 0.5, since: "1990-06-15"}, {income: 99.99, score: 99999999999999999999, since: "2024-01-01"}, {income: 0.5, score: 0, since: "2024-02-29"}]}}, {capped: "0.5", grade: ["ok", "a-0.5"], risk: [true], shipment: {code: "ok", limit: 0.5, parcels: [{income: 1, score: -1, share: 100000000000000000008.5, since: "2025-03-20"}, {income: 10, score: 10, share: 100000000000000000008.5, since: "2025-03-20"}, {income: 250, score: 0.5, share: 100000000000000000008.5, since: "1990-06-15"}, {income: 99.99, score: 99999999999999999999, share: 100000000000000000008.5, since: "2024-01-01"}, {income: 0.5, score: 0, share: 100000000000000000008.5, since: "2024-02-29"}], price: 0.5, score: -1, segment: 2, since: "1990-06-15"}, weighted: [0.5, 2]}], + [{shipment: {since: "2000-01-01", limit: null, score: 250, code: "retail", parcels: [{income: 0.5, score: 0.5, since: "2024-01-01"}, {income: 10, score: 0.000001, since: "1990-06-15"}, {income: 5, score: 123456789.123, since: "2024-01-01"}]}}, {capped: "retail", grade: ["retail", "a-retail"], risk: [true], shipment: {code: "retail", limit: null, parcels: [{income: 0.5, score: 0.5, share: 123456789.623001, since: "2024-01-01"}, {income: 10, score: 0.000001, share: 123456789.623001, since: "1990-06-15"}, {income: 5, score: 123456789.123, share: 123456789.623001, since: "2024-01-01"}], score: 250, segment: 6, since: "2000-01-01"}, weighted: [0, 6]}], + ], +} + +// seed 334100 (attempt 0) +{ + name: "a 42: order/parcels: 2 expression, 2 match, 3 table; 4 root, 3 per-member, 0 top-level computed", + policy: { + models: {order: {weight: "number", city: "string", since: "date", birthDate: "date?", limit: "number?", parcels: "parcel[]"}, parcel: {qty: "number?", since: "date", priority: "boolean"}}, + blocks: [ + {table: "t1", hit: "collect", inputs: ["order.since", "parcel.qty", "(parcel.qty ?? 0)"], outputs: ["parcel.penalty"], rules: [ + ["", "1", "> 0.5", "(order.birthDate ?? d('2025-01-01')) < d('2025-01-01')"], + ["", "", "", "parcel.priority"], + ]}, + {table: "t3", inputs: ["order.tag"], outputs: ["parcel.margin"], rules: [ + ["2", "count(order.parcels, (#.qty ?? 0) <= (#.qty ?? 0))"], + ["< 1.5", "parcel.since.month()"], + ["0", ""], + ["!= 0.25", "(order.limit ?? 0)"], + ]}, + {expression: "order.bucket", value: "order.city"}, + {table: "t6", inputs: ["order.city", "order.since", "order.bucket"], outputs: ["order.summary"], rules: [ + ["'retail'", "", "'US', 'ok'", "'A1'"], + ["'a'", "< d('2024-01-01')", "'Oslo'", "order.city"], + ["'gold', 'US'", ">= d('2025-03-20')", "startsWith($, 'high')", "order.bucket"], + ["$ != 'US'", "< d('2025-01-01')", "$ != 'a'", "'a'"], + ["'DE'", "", "'low'", "order.bucket"], + ]}, + {match: "parcel.adjusted", arms: [["parcel.since > d('2025-03-20')", "((order.limit ?? 0) * order.weight)"], ["contains(trim(order.city), 'US')", "(parcel.margin ?? 0)"], ["", "order.weight"]]}, + {expression: "order.tag", value: "sum(map(order.parcels, (#.qty ?? 0)))"}, + {match: "order.level", arms: [["startsWith((order.summary ?? ''), 'US')", "(order.summary ?? '')"], ["order.summary == null", "string((order.weight * order.tag))"], ["len(order.city) < (order.limit ?? 0)", "'none'"], ["(some(order.parcels, (#.priority and #.priority)) and all(order.parcels, not (#.priority)))", "(order.summary ?? '')"], ["", "trim(order.city)"]]}, + ], + }, + cases: [ + [{order: {weight: 10, city: "Zed", since: "2024-02-29", parcels: []}}, {order: {bucket: "Zed", city: "Zed", level: "Zed", parcels: [], since: "2024-02-29", summary: "a", weight: 10}}], + [{order: {weight: 0.000001, city: "12", since: "1990-06-15", birthDate: "2025-03-20T10:15:30Z", limit: 1, parcels: [{qty: 2.50, since: "2024-01-01", priority: false}, {qty: 50, since: "2024-02-29", priority: false}, {qty: 0.5, since: "2025-03-20", priority: true}, {qty: 0.5, since: "2024-01-01", priority: true}, {qty: 123456789.123, since: "2030-12-31", priority: true}]}}, {order: {birthDate: "2025-03-20T10:15:30Z", bucket: "12", city: "12", level: "12", limit: 1, parcels: [{adjusted: 0.000001, penalty: [false], priority: false, qty: 2.50, since: "2024-01-01"}, {adjusted: 0.000001, penalty: [false], priority: false, qty: 50, since: "2024-02-29"}, {adjusted: 0.000001, penalty: [true], priority: true, qty: 0.5, since: "2025-03-20"}, {adjusted: 0.000001, penalty: [true], priority: true, qty: 0.5, since: "2024-01-01"}, {adjusted: 0.000001, penalty: [true], priority: true, qty: 123456789.123, since: "2030-12-31"}], since: "1990-06-15", summary: "a", weight: 0.000001}}], + [{order: {weight: 3, city: "日本", since: "2025-03-20", birthDate: "2025-03-20T10:15:30Z", limit: 0.5, parcels: [{qty: 50, since: "2030-12-31", priority: false}]}}, {order: {birthDate: "2025-03-20T10:15:30Z", bucket: "日本", city: "日本", level: "150", limit: 0.5, parcels: [{adjusted: 1.5, penalty: [false], priority: false, qty: 50, since: "2030-12-31"}], since: "2025-03-20", summary: null, tag: 50, weight: 3}}], + [{order: {weight: 0, city: "retail", since: "2024-01-01", birthDate: "2024-02-29", limit: 10, parcels: [{qty: -500, since: "1990-06-15", priority: true}]}}, {order: {birthDate: "2024-02-29", bucket: "retail", city: "retail", level: "none", limit: 10, parcels: [{adjusted: 0, penalty: [true], priority: true, qty: -500, since: "1990-06-15"}], since: "2024-01-01", summary: "a", weight: 0}}], + [{order: {weight: 0, city: "x", since: "2030-12-31", birthDate: null, limit: null, parcels: [{since: "2024-02-29", priority: false}, {qty: 1, since: "2025-03-20", priority: true}]}}, {order: {birthDate: null, bucket: "x", city: "x", level: "0", limit: null, parcels: [{adjusted: 0, penalty: [false], priority: false, since: "2024-02-29"}, {adjusted: 0, penalty: [false, true], priority: true, qty: 1, since: "2025-03-20"}], since: "2030-12-31", summary: null, tag: 1, weight: 0}}], + [{order: {weight: 100, city: "Oslo", since: "2024-01-01", birthDate: "2024-01-01", limit: 1.5, parcels: [{qty: 3, since: "2000-01-01", priority: true}]}}, {order: {birthDate: "2024-01-01", bucket: "Oslo", city: "Oslo", level: "Oslo", limit: 1.5, parcels: [{adjusted: 100, penalty: [true], priority: true, qty: 3, since: "2000-01-01"}], since: "2024-01-01", summary: "a", weight: 100}}], + [{order: {weight: 100, city: "a", since: "2030-12-31", parcels: []}}, {order: {bucket: "a", city: "a", level: "0", parcels: [], since: "2030-12-31", summary: null, tag: 0, weight: 100}}], + [{order: {weight: 3, city: "low", since: "2000-01-01", birthDate: "2024-02-29", parcels: [{qty: -1, since: "2025-03-20T10:15:30Z", priority: false}, {since: "2000-01-01", priority: false}]}}, {order: {birthDate: "2024-02-29", bucket: "low", city: "low", level: "low", parcels: [{adjusted: 0, penalty: [false], priority: false, qty: -1, since: "2025-03-20T10:15:30Z"}, {adjusted: 3, penalty: [false], priority: false, since: "2000-01-01"}], since: "2000-01-01", summary: "a", weight: 3}}], + [{order: {weight: -0.5, city: "A1", since: "2024-01-01", birthDate: "2030-12-31", limit: 0.25, parcels: []}}, {order: {birthDate: "2030-12-31", bucket: "A1", city: "A1", level: "A1", limit: 0.25, parcels: [], since: "2024-01-01", summary: "a", weight: -0.5}}], + [{order: {weight: 0, city: "abc", since: "2024-02-29", birthDate: "1990-06-15", limit: 401, parcels: [{qty: 50, since: "2025-03-20", priority: true}, {qty: 50, since: "2025-03-20T10:15:30Z", priority: true}, {qty: 10, since: "2025-03-20", priority: false}, {qty: 123456789.123, since: "2025-03-20", priority: false}, {qty: 1.5, since: "2025-03-20T10:15:30Z", priority: false}]}}, {order: {birthDate: "1990-06-15", bucket: "abc", city: "abc", level: "none", limit: 401, parcels: [{adjusted: 0, penalty: [true], priority: true, qty: 50, since: "2025-03-20"}, {adjusted: 0, penalty: [true], priority: true, qty: 50, since: "2025-03-20T10:15:30Z"}, {adjusted: 0, penalty: [false], priority: false, qty: 10, since: "2025-03-20"}, {adjusted: 0, penalty: [false], priority: false, qty: 123456789.123, since: "2025-03-20"}, {adjusted: 0, penalty: [false], priority: false, qty: 1.5, since: "2025-03-20T10:15:30Z"}], since: "2024-02-29", summary: "a", weight: 0}}], + [{order: {weight: 0.5, city: "DE", since: "2025-03-20", birthDate: null, parcels: [{qty: 1e3, since: "2030-12-31", priority: true}]}}, {order: {birthDate: null, bucket: "DE", city: "DE", level: "500.0", parcels: [{adjusted: 0, penalty: [true], priority: true, qty: 1000, since: "2030-12-31"}], since: "2025-03-20", summary: null, tag: 1000, weight: 0.5}}], + [{order: {weight: 0.5, city: "ok", since: "2025-03-20T10:15:30Z", birthDate: "2030-12-31", limit: 50, parcels: [{qty: 250, since: "2000-01-01", priority: false}, {qty: 0.000001, since: "2024-01-01", priority: true}, {qty: 10, since: "2025-03-20T10:15:30Z", priority: false}]}}, {order: {birthDate: "2030-12-31", bucket: "ok", city: "ok", level: "130.0000005", limit: 50, parcels: [{adjusted: 0.5, penalty: [false], priority: false, qty: 250, since: "2000-01-01"}, {adjusted: 0.5, penalty: [true], priority: true, qty: 0.000001, since: "2024-01-01"}, {adjusted: 25.0, penalty: [false], priority: false, qty: 10, since: "2025-03-20T10:15:30Z"}], since: "2025-03-20T10:15:30Z", summary: null, tag: 260.000001, weight: 0.5}}], + [{order: {weight: 10, city: "A1", since: "2030-12-31", birthDate: "1990-06-15", limit: 5, parcels: [{qty: -500, since: null, priority: false}]}}, "!error: ExpressionFailed"], + [{order: {weight: 1, city: "US", since: "2025-03-20", birthDate: "2000-01-01", limit: 0, parcels: [{qty: 1, since: "2024-01-01", priority: true}, {qty: 0, since: "2024-01-01", priority: false}, {qty: 1, since: "2024-02-29", priority: false}]}}, {order: {birthDate: "2000-01-01", bucket: "US", city: "US", level: "2", limit: 0, parcels: [{adjusted: 3, margin: 3, penalty: [true, true], priority: true, qty: 1, since: "2024-01-01"}, {adjusted: 3, margin: 3, penalty: [false], priority: false, qty: 0, since: "2024-01-01"}, {adjusted: 3, margin: 3, penalty: [true, false], priority: false, qty: 1, since: "2024-02-29"}], since: "2025-03-20", summary: null, tag: 2, weight: 1}}], + [{order: {weight: 0.1, city: "A1", since: "2000-01-01", birthDate: "2025-03-20", limit: 5, parcels: [{qty: 1.5, since: "2025-03-20T10:15:30Z", priority: true}]}}, {order: {birthDate: "2025-03-20", bucket: "A1", city: "A1", level: "none", limit: 5, parcels: [{adjusted: 0.5, penalty: [true], priority: true, qty: 1.5, since: "2025-03-20T10:15:30Z"}], since: "2000-01-01", summary: "a", weight: 0.1}}], + [{order: {weight: 7.25, city: "gold", since: "2025-03-20", birthDate: "2030-12-31", limit: 1.5, parcels: [{qty: -0, since: "2024-02-29", priority: false}]}}, {order: {birthDate: "2030-12-31", bucket: "gold", city: "gold", level: "0", limit: 1.5, parcels: [{adjusted: 7.25, penalty: [false], priority: false, qty: 0, since: "2024-02-29"}], since: "2025-03-20", summary: null, tag: 0, weight: 7.25}}], + [{order: {weight: 1.5, city: "US", since: "2025-03-20", birthDate: "2025-03-20T10:15:30Z", limit: -0, parcels: [{qty: 250, since: "1990-06-15", priority: true}, {qty: 7.25, since: "2024-02-29", priority: false}, {qty: 1000, since: "2024-01-01", priority: true}, {qty: 2, since: "2000-01-01", priority: true}], extraField: "x"}}, {order: {birthDate: "2025-03-20T10:15:30Z", bucket: "US", city: "US", extraField: "x", level: "1888.875", limit: 0, parcels: [{adjusted: 0, margin: 0, penalty: [true], priority: true, qty: 250, since: "1990-06-15"}, {adjusted: 0, margin: 0, penalty: [false], priority: false, qty: 7.25, since: "2024-02-29"}, {adjusted: 0, margin: 0, penalty: [true], priority: true, qty: 1000, since: "2024-01-01"}, {adjusted: 0, margin: 0, penalty: [true], priority: true, qty: 2, since: "2000-01-01"}], since: "2025-03-20", summary: null, tag: 1259.25, weight: 1.5}}], + [{order: {weight: -500, city: "A1", since: "1990-06-15", birthDate: null, parcels: [{qty: 250, since: "2024-02-29", priority: false}, {qty: null, since: "2025-03-20", priority: true}, {since: "1990-06-15", priority: false}]}}, {order: {birthDate: null, bucket: "A1", city: "A1", level: "A1", parcels: [{adjusted: -500, penalty: [false], priority: false, qty: 250, since: "2024-02-29"}, {adjusted: -500, penalty: [true], priority: true, qty: null, since: "2025-03-20"}, {adjusted: -500, penalty: [false], priority: false, since: "1990-06-15"}], since: "1990-06-15", summary: "a", weight: -500}}], + [{order: {weight: 0, city: "Zed", since: "1990-06-15", birthDate: "2025-03-20", limit: 0, parcels: []}}, {order: {birthDate: "2025-03-20", bucket: "Zed", city: "Zed", level: "Zed", limit: 0, parcels: [], since: "1990-06-15", summary: "a", weight: 0}}], + [{order: {weight: 0.25, city: "3.5", since: "2024-02-29", birthDate: "2025-03-20", limit: 0, parcels: [{qty: 3, since: "2024-02-29", priority: true}, {qty: 123456789.123, since: "2025-03-20", priority: true}], extraField: {nested: true}}}, {order: {birthDate: "2025-03-20", bucket: "3.5", city: "3.5", extraField: {nested: true}, level: "3.5", limit: 0, parcels: [{adjusted: 0.25, penalty: [true], priority: true, qty: 3, since: "2024-02-29"}, {adjusted: 0.25, penalty: [true], priority: true, qty: 123456789.123, since: "2025-03-20"}], since: "2024-02-29", summary: "a", weight: 0.25}}], + [{order: {weight: 10, city: "US", since: "2024-02-29", birthDate: "1990-06-15", limit: 1, parcels: [{qty: true, since: "1990-06-15", priority: true}, {qty: 2, since: "2025-03-20T10:15:30Z", priority: true}, {qty: 65, since: "2025-03-20", priority: true}, {qty: 250, since: "2024-01-01", priority: true}]}}, "!error: InputValidationFailed"], + [{order: {weight: 1, city: "Zed", since: "2024-02-29", birthDate: "2024-02-29", limit: true, parcels: []}}, "!error: InputValidationFailed"], + [{order: {weight: -0.5, city: "日本", since: "2000-01-01", limit: 3, parcels: [{qty: 3, since: "1990-06-15", priority: false}]}}, {order: {bucket: "日本", city: "日本", level: "日本", limit: 3, parcels: [{adjusted: -0.5, penalty: [false], priority: false, qty: 3, since: "1990-06-15"}], since: "2000-01-01", summary: "a", weight: -0.5}}], + [{order: {weight: 1000, since: "1990-06-15", birthDate: "2000-01-01", limit: 10, parcels: []}}, "!error: MissingRequiredInputs"], + [{order: {weight: 250, city: "US", since: "2024-02-29", birthDate: null, limit: 2, parcels: [{qty: 1000000, since: "1990-06-15", priority: true}, {qty: 1, since: "2025-03-20T10:15:30Z", priority: false}]}}, {order: {birthDate: null, bucket: "US", city: "US", level: "250000250", limit: 2, parcels: [{adjusted: 2, margin: 2, penalty: [true], priority: true, qty: 1000000, since: "1990-06-15"}, {adjusted: 500, margin: 2, penalty: [false, false], priority: false, qty: 1, since: "2025-03-20T10:15:30Z"}], since: "2024-02-29", summary: null, tag: 1000001, weight: 250}}], + [{order: {weight: 10, city: "US", since: "2000-01-01", birthDate: null, limit: 1.5, parcels: [{qty: 1000, since: "2024-02-29", priority: true}, {qty: null, since: "2024-02-29", priority: false}]}}, {order: {birthDate: null, bucket: "US", city: "US", level: "10000", limit: 1.5, parcels: [{adjusted: 1.5, margin: 1.5, penalty: [true], priority: true, qty: 1000, since: "2024-02-29"}, {adjusted: 1.5, margin: 1.5, penalty: [false], priority: false, qty: null, since: "2024-02-29"}], since: "2000-01-01", summary: null, tag: 1000, weight: 10}}], + [{order: {weight: 0.5, city: " pad ", since: "2025-03-20", birthDate: "2000-01-01", limit: 99.99, parcels: []}}, {order: {birthDate: "2000-01-01", bucket: " pad ", city: " pad ", level: "0", limit: 99.99, parcels: [], since: "2025-03-20", summary: null, tag: 0, weight: 0.5}}], + [{order: {weight: -1, city: "DE", since: "2024-02-29", birthDate: "1990-06-15", limit: 65, parcels: []}}, {order: {birthDate: "1990-06-15", bucket: "DE", city: "DE", level: "none", limit: 65, parcels: [], since: "2024-02-29", summary: "a", weight: -1}}], + [{order: {weight: 0, city: "retail", since: "2025-03-20T10:15:30Z", birthDate: "2000-01-01", limit: null, parcels: [{qty: 2, since: "2025-03-20T10:15:30Z", priority: true}, {qty: 100, since: "2030-12-31", priority: false}, {since: "2030-12-31", priority: false}, {since: "1990-06-15", priority: true}]}}, {order: {birthDate: "2000-01-01", bucket: "retail", city: "retail", level: "0", limit: null, parcels: [{adjusted: 0, penalty: [true], priority: true, qty: 2, since: "2025-03-20T10:15:30Z"}, {adjusted: 0, penalty: [false], priority: false, qty: 100, since: "2030-12-31"}, {adjusted: 0, penalty: [false], priority: false, since: "2030-12-31"}, {adjusted: 0, penalty: [true], priority: true, since: "1990-06-15"}], since: "2025-03-20T10:15:30Z", summary: null, tag: 102, weight: 0}}], + [{order: {weight: 0.5, city: "US", since: "2030-12-31", birthDate: "2025-03-20", limit: 1, parcels: [{qty: 1.5, since: "2030-12-31", priority: false}]}}, {order: {birthDate: "2025-03-20", bucket: "US", city: "US", level: "0.75", limit: 1, parcels: [{adjusted: 0.5, penalty: [false], priority: false, qty: 1.5, since: "2030-12-31"}], since: "2030-12-31", summary: null, tag: 1.5, weight: 0.5}}], + ], +} + +// seed 334200 (attempt 0) +{ + name: "a 43: tenant/loans: 3 expression, 2 match, 3 table; 9 root, 2 per-member, 2 top-level computed", + policy: { + models: {tenant: {years: "number", active: "boolean", kind: "string(retail|corporate)?", insured: "boolean", channel: "string", loans: "loan[]"}, loan: {income: "number", sku: "string", insured: "boolean", openedAt: "date"}}, + blocks: [ + {expression: "loan.capped", value: "(loan.income) / (abs(0.25) + 1)"}, + {expression: "loan.rank", value: "loan.openedAt.diff(d('2025-01-01'), 'day')"}, + {match: "tenant.review", arms: [["not (tenant.years in [-1..74])", "tenant.kind != null"], ["not (tenant.insured)", "tenant.years >= tenant.years"], ["", "(tenant.active and tenant.active)"]]}, + {match: "tenant.discount", arms: [["(tenant.review and tenant.insured)", "(tenant.kind ?? '') != 'corporate'"], ["", "tenant.active"]]}, + {table: "t5", inputs: ["tenant.insured", null, "tenant.active"], outputs: ["ok", "quota"], rules: [ + ["false", "1.5 > tenant.years", "", "1.5", ""], + ["", "(tenant.kind ?? '') in ['corporate', 'retail']", "true", "(10) / (abs(tenant.years) + 1)", "len(tenant.channel)"], + ]}, + {table: "t6", inputs: ["(tenant.years * tenant.years)"], outputs: ["tenant.flag", "tenant.adjusted", "tenant.bonus"], rules: [ + ["< 0", "(quota ?? 0)", "len(tenant.channel)", "(quota ?? 0)"], + [">= 250", "3", "(ok ?? 0)", "(ok ?? 0)"], + ["< 0.5", "tenant.years", "(ok ?? 0)", "((quota ?? 0) * (quota ?? 0))"], + ["", "(quota ?? 0)", "50", "count(tenant.loans, #.rank in [49..183])"], + ["<= 1000", "", "(ok ?? 0)", "tenant.years"], + ]}, + {expression: "tenant.weighted", value: "(lower(tenant.channel) + '-' + ((tenant.active ? tenant.channel : tenant.channel) + '-' + string((ok ?? 0))))"}, + {table: "t8", inputs: ["tenant.discount"], outputs: ["tenant.grade", "tenant.share", "tenant.points"], rules: [ + ["false", "tenant.weighted", "(tenant.adjusted ?? 0)", "(tenant.review ? tenant.channel : 'high')"], + ["true", "tenant.weighted", "", ""], + ["", "tenant.weighted", "(quota ?? 0)", "tenant.channel"], + ["false", "tenant.channel", "(tenant.adjusted ?? 0)", "tenant.weighted"], + ["", "tenant.weighted", "len(tenant.weighted)", "(tenant.insured ? tenant.channel : tenant.channel)"], + ["true", "tenant.weighted", "", ""], + ]}, + ], + }, + cases: [ + [{tenant: {years: 99.99, active: false, kind: "corporate", insured: false, channel: "x-y", loans: [{income: 1000000, sku: " pad ", insured: true, openedAt: "2024-01-01"}, {income: 3, sku: "NL", insured: false, openedAt: "2024-02-29"}]}}, {ok: null, quota: null, tenant: {active: false, adjusted: 0, bonus: 0, channel: "x-y", discount: false, flag: 3, grade: "x-y-x-y-0", insured: false, kind: "corporate", loans: [{capped: 800000, income: 1000000, insured: true, openedAt: "2024-01-01", sku: " pad "}, {capped: 2.4, income: 3, insured: false, openedAt: "2024-02-29", sku: "NL"}], points: "x-y", review: true, share: 0, weighted: "x-y-x-y-0", years: 99.99}}], + [{tenant: {years: 0.5, active: false, kind: "corporate", channel: "Oslo", loans: [{income: 2.50, sku: "Oslo", insured: true, openedAt: "2024-01-01"}, {income: 18, sku: "-", insured: false, openedAt: "2030-12-31"}]}}, "!error: MissingRequiredInputs"], + [{tenant: {years: -500, active: false, kind: null, insured: false, channel: "gold", loans: [{income: 309, sku: "Oslo", insured: false, openedAt: "2024-01-01"}, {income: 0, sku: "é ü", insured: true, openedAt: "2000-01-01"}, {income: 10, sku: "é ü", insured: false, openedAt: "2030-12-31"}, {income: -0.01, sku: "A1", insured: true, openedAt: "2000-01-01"}]}}, {ok: 1.5, quota: null, tenant: {active: false, adjusted: 1.5, bonus: 1.5, channel: "gold", discount: false, flag: 3, grade: "gold-gold-1.5", insured: false, kind: null, loans: [{capped: 247.2, income: 309, insured: false, openedAt: "2024-01-01", sku: "Oslo"}, {capped: 0, income: 0, insured: true, openedAt: "2000-01-01", sku: "é ü"}, {capped: 8, income: 10, insured: false, openedAt: "2030-12-31", sku: "é ü"}, {capped: -0.008, income: -0.01, insured: true, openedAt: "2000-01-01", sku: "A1"}], points: "high", review: false, share: 1.5, weighted: "gold-gold-1.5", years: -500}}], + [{tenant: {years: -0.01, active: true, kind: "corporate", insured: true, channel: " pad ", loans: [{income: -0.01, sku: "12", openedAt: "2030-12-31"}]}}, {ok: 9.900990099009900990099009901, quota: 6, tenant: {active: true, adjusted: 9.900990099009900990099009901, bonus: 36, channel: " pad ", discount: false, flag: -0.01, grade: " pad - pad -9.900990099009900990099009901", insured: true, kind: "corporate", loans: [{capped: -0.008, income: -0.01, openedAt: "2030-12-31", sku: "12"}], points: " pad ", review: true, share: 9.900990099009900990099009901, weighted: " pad - pad -9.900990099009900990099009901", years: -0.01}}], + [{tenant: {years: 99.99, active: true, kind: "corporate", insured: false, channel: "a", loans: [{income: 163, sku: "high", insured: false, openedAt: "2000-01-01"}, {income: 250, sku: "", insured: true, openedAt: "2000-01-01"}, {income: 1, sku: "gold", insured: false, openedAt: "2024-01-01"}, {income: 18, sku: "O'Neil", insured: false, openedAt: "2024-01-01"}]}}, {ok: 0.099019704921279334587582929, quota: 1, tenant: {active: true, adjusted: 0.099019704921279334587582929, bonus: 0.099019704921279334587582929, channel: "a", discount: true, flag: 3, grade: "a-a-0.099019704921279334587582929", insured: false, kind: "corporate", loans: [{capped: 130.4, income: 163, insured: false, openedAt: "2000-01-01", sku: "high"}, {capped: 200, income: 250, insured: true, openedAt: "2000-01-01", sku: ""}, {capped: 0.8, income: 1, insured: false, openedAt: "2024-01-01", sku: "gold"}, {capped: 14.4, income: 18, insured: false, openedAt: "2024-01-01", sku: "O'Neil"}], points: "a", review: true, share: 1, weighted: "a-a-0.099019704921279334587582929", years: 99.99}}], + [{tenant: {years: -0, active: false, kind: "retail", insured: false, channel: "US", loans: [{income: 65, sku: "3.5", insured: true, openedAt: "2024-01-01"}, {income: 10, sku: "é ü", insured: false, openedAt: "2024-01-01"}, {income: 0.5, sku: "retail", insured: false, openedAt: "2000-01-01"}]}}, {ok: 1.5, quota: null, tenant: {active: false, adjusted: 1.5, bonus: 0, channel: "US", discount: false, flag: 0, grade: "us-US-1.5", insured: false, kind: "retail", loans: [{capped: 52, income: 65, insured: true, openedAt: "2024-01-01", sku: "3.5"}, {capped: 8, income: 10, insured: false, openedAt: "2024-01-01", sku: "é ü"}, {capped: 0.4, income: 0.5, insured: false, openedAt: "2000-01-01", sku: "retail"}], points: "US", review: true, share: 1.5, weighted: "us-US-1.5", years: 0}}], + [{tenant: {years: 3, active: true, kind: "corporate", insured: true, channel: "high", loans: [{income: 10, sku: "VIP", insured: false, openedAt: "2025-03-20T10:15:30Z"}, {income: 1.5, sku: "", insured: false, openedAt: "2000-01-01"}, {income: -0.01, sku: "日本", insured: false, openedAt: "2024-02-29"}, {income: 1.5, sku: "retail", insured: false, openedAt: "2025-03-20"}, {income: 18, sku: "NL", insured: false, openedAt: "2030-12-31"}]}}, {ok: 2.50, quota: 4, tenant: {active: true, adjusted: 50, bonus: 2, channel: "high", discount: false, flag: 4, grade: "high-high-2.50", insured: true, kind: "corporate", loans: [{capped: 8, income: 10, insured: false, openedAt: "2025-03-20T10:15:30Z", rank: 78, sku: "VIP"}, {capped: 1.2, income: 1.5, insured: false, openedAt: "2000-01-01", rank: -9132, sku: ""}, {capped: -0.008, income: -0.01, insured: false, openedAt: "2024-02-29", rank: -307, sku: "日本"}, {capped: 1.2, income: 1.5, insured: false, openedAt: "2025-03-20", rank: 78, sku: "retail"}, {capped: 14.4, income: 18, insured: false, openedAt: "2030-12-31", rank: 2190, sku: "NL"}], points: "high", review: true, share: 50, weighted: "high-high-2.50", years: 3}}], + [{tenant: {years: 123456789.123, active: false, insured: true, channel: "-", loans: [{income: 65, sku: "3.5", insured: false, openedAt: "2030-12-31"}, {income: 0.5, sku: "O'Neil", insured: true, openedAt: "2000-01-01"}]}}, {ok: null, quota: null, tenant: {active: false, adjusted: 0, bonus: 0, channel: "-", discount: false, flag: 3, grade: "----0", insured: true, loans: [{capped: 52, income: 65, insured: false, openedAt: "2030-12-31", sku: "3.5"}, {capped: 0.4, income: 0.5, insured: true, openedAt: "2000-01-01", sku: "O'Neil"}], points: "high", review: false, share: 0, weighted: "----0", years: 123456789.123}}], + [{tenant: {years: 18, active: false, kind: "retail", insured: true, channel: "", loans: [{income: 1.5, sku: "US", insured: true, openedAt: "2024-01-01"}, {income: 18, sku: "retail", insured: true, openedAt: "2025-03-20T10:15:30Z"}, {income: 250, sku: " pad ", insured: false, openedAt: "2000-01-01"}, {income: 0.5, sku: "3.5", insured: true, openedAt: "2025-03-20"}]}}, {ok: null, quota: null, tenant: {active: false, adjusted: 0, bonus: 0, channel: "", discount: false, flag: 3, grade: "--0", insured: true, kind: "retail", loans: [{capped: 1.2, income: 1.5, insured: true, openedAt: "2024-01-01", sku: "US"}, {capped: 14.4, income: 18, insured: true, openedAt: "2025-03-20T10:15:30Z", sku: "retail"}, {capped: 200, income: 250, insured: false, openedAt: "2000-01-01", sku: " pad "}, {capped: 0.4, income: 0.5, insured: true, openedAt: "2025-03-20", sku: "3.5"}], points: "high", review: false, share: 0, weighted: "--0", years: 18}}], + [{tenant: {years: 0, active: true, insured: true, channel: "", loans: [{income: 2, sku: "VIP", insured: false, openedAt: "2024-02-29"}, {income: 18, sku: "abc", insured: false, openedAt: "1990-06-15"}]}}, {ok: null, quota: null, tenant: {active: true, adjusted: 0, bonus: 0, channel: "", discount: true, flag: 0, grade: "--0", insured: true, loans: [{capped: 1.6, income: 2, insured: false, openedAt: "2024-02-29", sku: "VIP"}, {capped: 14.4, income: 18, insured: false, openedAt: "1990-06-15", sku: "abc"}], points: "", review: true, share: 0, weighted: "--0", years: 0}}], + [{tenant: {years: 99999999999999999999, active: false, kind: "retail", insured: true, channel: "NL", loans: [{income: [1], sku: "a-b-c", insured: false, openedAt: "2030-12-31"}, {income: 1e3, sku: "", insured: false, openedAt: "2025-03-20T10:15:30Z"}]}}, "!error: InputValidationFailed"], + [{tenant: {years: 65, active: false, kind: "corporate", insured: true, channel: "é ü", loans: [{income: 24, sku: "a-b-c", insured: true, openedAt: "2025-03-20"}, {income: 1000, sku: "VIP", insured: true, openedAt: "2024-02-29"}]}}, {ok: null, quota: null, tenant: {active: false, adjusted: 0, bonus: 0, channel: "é ü", discount: false, flag: 3, grade: "é ü-é ü-0", insured: true, kind: "corporate", loans: [{capped: 19.2, income: 24, insured: true, openedAt: "2025-03-20", sku: "a-b-c"}, {capped: 800, income: 1000, insured: true, openedAt: "2024-02-29", sku: "VIP"}], points: "high", review: false, share: 0, weighted: "é ü-é ü-0", years: 65}}], + [{tenant: {years: 123456789.123, active: false, kind: "retail", insured: true, channel: "O'Neil", loans: [{income: 10, sku: "gold", insured: true, openedAt: "2024-02-29"}, {income: 18, sku: "日本", insured: false, openedAt: "2000-01-01"}]}}, {ok: null, quota: null, tenant: {active: false, adjusted: 0, bonus: 0, channel: "O'Neil", discount: true, flag: 3, grade: "o'neil-O'Neil-0", insured: true, kind: "retail", loans: [{capped: 8, income: 10, insured: true, openedAt: "2024-02-29", sku: "gold"}, {capped: 14.4, income: 18, insured: false, openedAt: "2000-01-01", sku: "日本"}], points: "O'Neil", review: true, share: 0, weighted: "o'neil-O'Neil-0", years: 123456789.123}}], + [{tenant: {years: 7.25, active: true, kind: "corporate", insured: false, channel: false, loans: [{income: 7.25, sku: "a-b-c", insured: true, openedAt: "2000-01-01"}]}}, "!error: InputValidationFailed"], + ], +} + +// seed 334300 (attempt 0) +{ + name: "a 44: customer/lines: 1 expression, 1 match, 1 table; 5 root, 0 per-member, 0 top-level computed", + policy: { + models: {customer: {limit: "number", verified: "boolean", kind: "string(retail|corporate)", qty: "number", since: "date?", lines: "line[]?"}, line: {limit: "number", since: "date?", kind: "string(retail|corporate)?", age: "number?"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {table: "t1", inputs: ["factor", "customer.qty"], outputs: ["customer.grade", "customer.points", "customer.risk"], rules: [ + ["0.25, 1.5", "[5..320]", "len((customer.lines ?? []))", "customer.verified", "'VIP'"], + ["", "", "(factor * 0.5)", "customer.verified", "'US'"], + ["< 5", "!= 18", "customer.qty", "customer.verified", "'DE'"], + [">= 0.25", "> 18", "customer.limit", "customer.verified", "'high'"], + ["<= 18", "> 1000", "customer.qty", "customer.verified", "(customer.verified ? 'none' : 'gold')"], + ["", "", "10", "(customer.verified and customer.verified)", "'VIP'"], + ]}, + {expression: "customer.discount", value: "some((customer.lines ?? []), (#.kind ?? '') != 'retail')"}, + {match: "customer.penalty", arms: [["(customer.since ?? d('2025-01-01')) < d('2025-01-01')", "(customer.risk ?? '')"], ["floor(customer.qty) >= factor", "((customer.risk ?? '') + '-' + (customer.risk ?? ''))"], ["", "(customer.risk ?? '')"]]}, + ], + }, + cases: [ + [{factor: 0.5, customer: {limit: 18, verified: false, kind: "retail", qty: 0, since: "2000-01-01", lines: [{limit: 1000, since: "2025-03-20T10:15:30Z", kind: "retail", age: 5}, {limit: 0.5, since: "2024-01-01", kind: "retail", age: 250}, {limit: 5, since: "2025-03-20T10:15:30Z", kind: "corporate", age: 0.25}, {limit: 1000000, since: "2025-03-20", kind: "retail", age: 10}, {limit: 10, since: "2024-02-29", kind: "retail", age: 1}]}}, {customer: {discount: true, grade: 0.25, kind: "retail", limit: 18, lines: [{age: 5, kind: "retail", limit: 1000, since: "2025-03-20T10:15:30Z"}, {age: 250, kind: "retail", limit: 0.5, since: "2024-01-01"}, {age: 0.25, kind: "corporate", limit: 5, since: "2025-03-20T10:15:30Z"}, {age: 10, kind: "retail", limit: 1000000, since: "2025-03-20"}, {age: 1, kind: "retail", limit: 10, since: "2024-02-29"}], penalty: "US", points: false, qty: 0, risk: "US", since: "2000-01-01", verified: false}, factor: 0.5}], + [{factor: 1, customer: {limit: 0.5, verified: false, kind: "retail", qty: 99.99, since: null, lines: null}}, {customer: {discount: false, grade: 0.5, kind: "retail", limit: 0.5, lines: null, penalty: "US-US", points: false, qty: 99.99, risk: "US", since: null, verified: false}, factor: 1}], + [{factor: 0, customer: {limit: 2.50, verified: false, kind: "retail", qty: 1.5, since: "2030-12-31", lines: [{limit: 5, since: "2024-02-29", kind: "retail", age: 2}, {limit: 123456789.123, since: "2000-01-01", kind: "retail", age: 2}]}}, {customer: {discount: false, grade: 0, kind: "retail", limit: 2.50, lines: [{age: 2, kind: "retail", limit: 5, since: "2024-02-29"}, {age: 2, kind: "retail", limit: 123456789.123, since: "2000-01-01"}], penalty: "US-US", points: false, qty: 1.5, risk: "US", since: "2030-12-31", verified: false}, factor: 0}], + [{factor: 100, customer: {limit: 0.25, verified: true, kind: "retail", qty: -0, lines: [{limit: 1.5, since: "2024-02-29", kind: null}, {limit: 2, since: "2024-01-01", kind: null, age: 0.5}, {limit: -1, since: "1990-06-15", kind: "retail", age: 99999999999999999999}]}}, {customer: {discount: true, grade: 50.0, kind: "retail", limit: 0.25, lines: [{kind: null, limit: 1.5, since: "2024-02-29"}, {age: 0.5, kind: null, limit: 2, since: "2024-01-01"}, {age: 99999999999999999999, kind: "retail", limit: -1, since: "1990-06-15"}], penalty: "US", points: true, qty: 0, risk: "US", verified: true}, factor: 100}], + [{factor: 1, customer: {limit: 0.5, verified: true, kind: "corporate", qty: 1000, since: "2000-01-01", lines: [{limit: 5, since: "2030-12-31", kind: "retail", age: 18}, {limit: 1000000, since: "2000-01-01", kind: "retail", age: 18}, {limit: 1, since: "1990-06-15", kind: "retail", age: 10}, {limit: 250, since: "1990-06-15", kind: "corporate", age: 1000}]}}, {customer: {discount: true, grade: 0.5, kind: "corporate", limit: 0.5, lines: [{age: 18, kind: "retail", limit: 5, since: "2030-12-31"}, {age: 18, kind: "retail", limit: 1000000, since: "2000-01-01"}, {age: 10, kind: "retail", limit: 1, since: "1990-06-15"}, {age: 1000, kind: "corporate", limit: 250, since: "1990-06-15"}], penalty: "US", points: true, qty: 1000, risk: "US", since: "2000-01-01", verified: true}, factor: 1}], + [{factor: -2, customer: {limit: 18, verified: false, kind: "corporate", qty: 1000000, since: "1990-06-15", lines: [{limit: -0, since: "2030-12-31", kind: false, age: -0}, {limit: 10, since: "2024-01-01", kind: "retail", age: -1}, {limit: 2.50, since: "2025-03-20T10:15:30Z", kind: "corporate", age: 65}, {limit: -0, since: "2030-12-31", kind: "retail", age: -0.5}, {limit: -0.5, since: "2024-02-29", kind: "retail", age: 0.25}]}}, "!error: InputValidationFailed"], + [{factor: -2, customer: {limit: 0.25, verified: true, kind: "retail", qty: -0, since: "2024-02-29", lines: [{limit: 250, since: "2025-03-20"}, {limit: 1, since: "1990-06-15", age: -0}]}}, {customer: {discount: true, grade: -1.0, kind: "retail", limit: 0.25, lines: [{limit: 250, since: "2025-03-20"}, {age: 0, limit: 1, since: "1990-06-15"}], penalty: "US", points: true, qty: 0, risk: "US", since: "2024-02-29", verified: true}, factor: -2}], + [{factor: 0, customer: {limit: 5, verified: true, kind: "corporate", qty: -500, since: "2000-01-01", lines: [{limit: 0.25, since: "2030-12-31", kind: null}]}}, {customer: {discount: true, grade: 0, kind: "corporate", limit: 5, lines: [{kind: null, limit: 0.25, since: "2030-12-31"}], penalty: "US", points: true, qty: -500, risk: "US", since: "2000-01-01", verified: true}, factor: 0}], + [{factor: 100, customer: {limit: 250, verified: true, kind: "retail", qty: true, since: "2030-12-31", lines: []}}, "!error: InputValidationFailed"], + [{factor: 1, customer: {limit: 1000, verified: true, kind: "corporate", qty: 18, since: "2024-02-29", lines: [{limit: 18, since: "2025-03-20T10:15:30Z", kind: "retail", age: 1000}, {limit: 0.5, since: "2030-12-31", kind: "retail", age: 5}, {limit: 250, since: "2030-12-31", kind: "corporate", age: 18}, {limit: 1, since: "2025-03-20T10:15:30Z", kind: "retail", age: 0.5}]}}, {customer: {discount: true, grade: 0.5, kind: "corporate", limit: 1000, lines: [{age: 1000, kind: "retail", limit: 18, since: "2025-03-20T10:15:30Z"}, {age: 5, kind: "retail", limit: 0.5, since: "2030-12-31"}, {age: 18, kind: "corporate", limit: 250, since: "2030-12-31"}, {age: 0.5, kind: "retail", limit: 1, since: "2025-03-20T10:15:30Z"}], penalty: "US", points: true, qty: 18, risk: "US", since: "2024-02-29", verified: true}, factor: 1}], + [{factor: 0.5, customer: {limit: 1e3, verified: true, kind: "retail", qty: 250, since: "2024-01-01", lines: [{limit: 0.5, since: "2025-03-20T10:15:30Z", kind: "retail", age: 0.5}, {limit: 1, since: "2000-01-01", kind: "retail", age: -0.01}, {limit: 2, since: "2025-03-20T10:15:30Z", kind: "retail", age: 1000}, {limit: 18, since: "2030-12-31", kind: "retail", age: 0.1}], extraField: {nested: true}}}, {customer: {discount: false, extraField: {nested: true}, grade: 0.25, kind: "retail", limit: 1000, lines: [{age: 0.5, kind: "retail", limit: 0.5, since: "2025-03-20T10:15:30Z"}, {age: -0.01, kind: "retail", limit: 1, since: "2000-01-01"}, {age: 1000, kind: "retail", limit: 2, since: "2025-03-20T10:15:30Z"}, {age: 0.1, kind: "retail", limit: 18, since: "2030-12-31"}], penalty: "US", points: true, qty: 250, risk: "US", since: "2024-01-01", verified: true}, factor: 0.5}], + [{factor: 0, customer: {limit: 99999999999999999999, verified: false, kind: "retail", qty: 7.25, since: "2025-03-20", lines: [{limit: 7.25, since: "1990-06-15", kind: "corporate", age: 324}], extraField: {nested: true}}}, {customer: {discount: true, extraField: {nested: true}, grade: 0, kind: "retail", limit: 99999999999999999999, lines: [{age: 324, kind: "corporate", limit: 7.25, since: "1990-06-15"}], penalty: "US-US", points: false, qty: 7.25, risk: "US", since: "2025-03-20", verified: false}, factor: 0}], + [{factor: 1, customer: {limit: 0.5, verified: true, kind: "corporate", qty: 0.1, since: "1990-06-15", lines: [{limit: 18, since: "2000-01-01", kind: "retail", age: 99.99}, {limit: 5, since: "1990-06-15", kind: "retail", age: -500}]}}, {customer: {discount: false, grade: 0.5, kind: "corporate", limit: 0.5, lines: [{age: 99.99, kind: "retail", limit: 18, since: "2000-01-01"}, {age: -500, kind: "retail", limit: 5, since: "1990-06-15"}], penalty: "US", points: true, qty: 0.1, risk: "US", since: "1990-06-15", verified: true}, factor: 1}], + [{factor: 10, customer: {limit: 2, verified: false, kind: "retail", qty: 3, since: "2000-01-01", lines: [{limit: 99.99, since: "2024-02-29", kind: "retail", age: 1000}], extraField: "x"}}, {customer: {discount: false, extraField: "x", grade: 5.0, kind: "retail", limit: 2, lines: [{age: 1000, kind: "retail", limit: 99.99, since: "2024-02-29"}], penalty: "US", points: false, qty: 3, risk: "US", since: "2000-01-01", verified: false}, factor: 10}], + [{factor: 100, customer: {limit: 123456789.123, verified: false, kind: "corporate", qty: 1000, since: "2024-02-29", lines: [{limit: 18, since: "2024-01-01", kind: "corporate", age: 1}]}}, {customer: {discount: true, grade: 50.0, kind: "corporate", limit: 123456789.123, lines: [{age: 1, kind: "corporate", limit: 18, since: "2024-01-01"}], penalty: "US", points: false, qty: 1000, risk: "US", since: "2024-02-29", verified: false}, factor: 100}], + [{factor: 1, customer: {limit: 1, verified: false, kind: "corporate", qty: 18, since: "2025-03-20", lines: []}}, {customer: {discount: false, grade: 0.5, kind: "corporate", limit: 1, lines: [], penalty: "US-US", points: false, qty: 18, risk: "US", since: "2025-03-20", verified: false}, factor: 1}], + [{factor: 10, customer: {limit: -500, verified: false, kind: "corporate", qty: 250, since: null, lines: [{limit: 0.5, since: "2030-12-31", age: 1000}]}}, {customer: {discount: true, grade: 5.0, kind: "corporate", limit: -500, lines: [{age: 1000, limit: 0.5, since: "2030-12-31"}], penalty: "US-US", points: false, qty: 250, risk: "US", since: null, verified: false}, factor: 10}], + [{factor: 10, customer: {limit: 100, verified: false, kind: "retail", qty: 99.99, since: "2024-01-01", lines: [{limit: 1000, since: "2025-03-20T10:15:30Z", kind: "retail"}, {limit: 0.25, kind: "corporate", age: 99999999999999999999}, {limit: 250, age: 250}, {limit: 250, age: 100}]}}, {customer: {discount: true, grade: 5.0, kind: "retail", limit: 100, lines: [{kind: "retail", limit: 1000, since: "2025-03-20T10:15:30Z"}, {age: 99999999999999999999, kind: "corporate", limit: 0.25}, {age: 250, limit: 250}, {age: 100, limit: 250}], penalty: "US", points: false, qty: 99.99, risk: "US", since: "2024-01-01", verified: false}, factor: 10}], + [{factor: 10, customer: {limit: 0.5, verified: false, kind: "retail", qty: 1, since: "2000-01-01", lines: [{limit: 3, since: "1990-06-15", kind: "corporate", age: -0.01}, {limit: 99999999999999999999, since: "2024-02-29", kind: "retail", age: 342}, {limit: -0.5, since: "2024-01-01", kind: "corporate", age: 2}, {limit: 3, since: "2025-03-20T10:15:30Z", kind: "retail", age: 2.50}]}}, {customer: {discount: true, grade: 5.0, kind: "retail", limit: 0.5, lines: [{age: -0.01, kind: "corporate", limit: 3, since: "1990-06-15"}, {age: 342, kind: "retail", limit: 99999999999999999999, since: "2024-02-29"}, {age: 2, kind: "corporate", limit: -0.5, since: "2024-01-01"}, {age: 2.50, kind: "retail", limit: 3, since: "2025-03-20T10:15:30Z"}], penalty: "US", points: false, qty: 1, risk: "US", since: "2000-01-01", verified: false}, factor: 10}], + [{factor: 10, customer: {limit: null, verified: true, kind: "retail", qty: 5, since: "2025-03-20", lines: [{limit: 5, since: "2024-02-29", kind: "retail", age: 1000000}, {limit: 18, since: "2000-01-01", kind: "corporate", age: 0.1}]}}, "!error: MissingRequiredInputs"], + [{factor: 10, customer: {limit: 250, verified: false, kind: "retail", qty: 1e3, since: "not a date", lines: [{limit: 1, since: "2000-01-01", kind: "retail", age: 18}]}}, "!error: InputValidationFailed"], + [{factor: 10, customer: {limit: 0.000001, verified: false, kind: "retail", qty: -0, since: "2030-12-31", lines: [{limit: 5, since: "2025-03-20", kind: "corporate", age: 0.25}, {limit: 0.25, since: "2000-01-01", kind: "retail", age: 0.5}, {limit: 0.1, since: "2024-01-01", kind: "retail", age: 5}, {limit: -500, since: "2024-01-01", kind: "retail", age: 0.5}]}}, {customer: {discount: true, grade: 5.0, kind: "retail", limit: 0.000001, lines: [{age: 0.25, kind: "corporate", limit: 5, since: "2025-03-20"}, {age: 0.5, kind: "retail", limit: 0.25, since: "2000-01-01"}, {age: 5, kind: "retail", limit: 0.1, since: "2024-01-01"}, {age: 0.5, kind: "retail", limit: -500, since: "2024-01-01"}], penalty: "US", points: false, qty: 0, risk: "US", since: "2030-12-31", verified: false}, factor: 10}], + [{factor: -2, customer: {limit: 99999999999999999999, verified: false, kind: "retail", qty: 0.5, since: "2025-03-20", lines: [{limit: 10, since: "2024-02-29", kind: null}, {limit: 3, since: "2000-01-01", kind: "retail", age: 65}]}}, {customer: {discount: true, grade: -1.0, kind: "retail", limit: 99999999999999999999, lines: [{kind: null, limit: 10, since: "2024-02-29"}, {age: 65, kind: "retail", limit: 3, since: "2000-01-01"}], penalty: "US-US", points: false, qty: 0.5, risk: "US", since: "2025-03-20", verified: false}, factor: -2}], + [{factor: 10, customer: {limit: 2, verified: true, kind: "corporate", qty: 7.25, since: "1990-06-15", lines: [{limit: 1000, since: "2024-01-01", kind: "retail", age: 1.5}]}}, {customer: {discount: false, grade: 5.0, kind: "corporate", limit: 2, lines: [{age: 1.5, kind: "retail", limit: 1000, since: "2024-01-01"}], penalty: "US", points: true, qty: 7.25, risk: "US", since: "1990-06-15", verified: true}, factor: 10}], + [{factor: 100, customer: {limit: 123456789.123, verified: true, kind: "retail", qty: 1, since: null, lines: [{limit: 0.25, since: "2025-03-20", kind: "retail", age: 0.5}, {limit: 2, since: null, kind: "corporate", age: 250}, {limit: 2, age: null}, {limit: -0.01, age: 1000000}]}}, {customer: {discount: true, grade: 50.0, kind: "retail", limit: 123456789.123, lines: [{age: 0.5, kind: "retail", limit: 0.25, since: "2025-03-20"}, {age: 250, kind: "corporate", limit: 2, since: null}, {age: null, limit: 2}, {age: 1000000, limit: -0.01}], penalty: "US", points: true, qty: 1, risk: "US", since: null, verified: true}, factor: 100}], + [{factor: -2, customer: {limit: 3, verified: true, kind: "corporate", qty: -0.01, since: null, lines: [{limit: 0.5, since: "2030-12-31", kind: "retail", age: 1.5}, {limit: 2, since: "2025-03-20T10:15:30Z", kind: null, age: -0.5}]}}, {customer: {discount: true, grade: -1.0, kind: "corporate", limit: 3, lines: [{age: 1.5, kind: "retail", limit: 0.5, since: "2030-12-31"}, {age: -0.5, kind: null, limit: 2, since: "2025-03-20T10:15:30Z"}], penalty: "US-US", points: true, qty: -0.01, risk: "US", since: null, verified: true}, factor: -2}], + [{factor: 0, customer: {limit: 1, verified: true, kind: "retail", qty: 18, since: "2030-12-31"}}, {customer: {discount: false, grade: 0, kind: "retail", limit: 1, penalty: "US-US", points: true, qty: 18, risk: "US", since: "2030-12-31", verified: true}, factor: 0}], + [{factor: 0, customer: {limit: 0.25, verified: false, kind: "corporate", qty: 3}}, {customer: {discount: false, grade: 0, kind: "corporate", limit: 0.25, penalty: "US-US", points: false, qty: 3, risk: "US", verified: false}, factor: 0}], + ], +} + +// seed 334401 (attempt 1) +{ + name: "a 45: claim/loans: 1 expression, 1 match, 2 table; 2 root, 4 per-member, 0 top-level computed", + policy: { + models: {claim: {balance: "number", plan: "string(basic|plus|premium|trial)?", age: "number", loans: "loan[]"}, loan: {income: "number", dueDate: "date"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {table: "t3", inputs: ["(loan.income * claim.balance)", "loan.share"], outputs: ["loan.quota"], rules: [ + ["250, 3", "3", ""], + ["[250..700]", "5, 10", "(loan.flag ?? 0)"], + ["1, 0.5", "", "(claim.age) / (abs(loan.income) + 1)"], + ["< 0", "1000", "loan.income"], + [">= 50", "50", "threshold"], + ]}, + {match: "claim.points", arms: [["(claim.plan ?? '') in ['plus', 'premium']", "upper((threshold <= 1 ? 'x' : 'A1'))"], ["", "'A1'"]]}, + {expression: "claim.decision", value: "claim.balance"}, + {table: "t1", inputs: ["loan.dueDate", "threshold"], outputs: ["loan.surcharge", "loan.flag", "loan.share"], rules: [ + [">= d('2024-01-01')", ">= 0.25", "'VIP'", "threshold", "loan.income"], + [">= d('2000-06-30')", "", "'none'", "(claim.age) / (abs(claim.age) + 1)", "loan.income"], + ["", "> 50", "", "(min(map(claim.loans, (#.income - 0.25))) ?? 0)", "5"], + [">= d('2000-06-30')", ">= 3", "'low'", "threshold", "loan.income"], + ["< d('2025-03-20')", ">= 1.5", "", "", "100"], + [">= d('2024-01-01')", ">= 0", "'retail'", "threshold", "claim.balance"], + ]}, + ], + }, + cases: [ + [{threshold: 1, claim: {balance: 1e3, plan: 5, age: 50, loans: [{income: 65, dueDate: "2025-03-20T10:15:30Z"}, {income: 0, dueDate: "2025-03-20"}, {income: 5, dueDate: "2024-02-29"}]}}, "!error: InputValidationFailed"], + [{threshold: -2, claim: {balance: -0.01, age: 1000, loans: [{income: 1000, dueDate: "2030-12-31"}]}}, {claim: {age: 1000, balance: -0.01, decision: -0.01, loans: [{dueDate: "2030-12-31", flag: 0.999000999000999000999000999, income: 1000, quota: 1000, share: 1000, surcharge: "none"}], points: "A1"}, threshold: -2}], + [{threshold: 0.5, claim: {balance: 2.50, plan: "basic", loans: [{income: 7.25, dueDate: "2030-12-31"}, {income: 0.1, dueDate: "2024-02-29"}]}}, "!error: MissingRequiredInputs"], + [{threshold: 100, claim: {balance: 18, plan: "premium", age: 0.25, loans: [{income: 250, dueDate: 20250101}]}}, "!error: InputValidationFailed"], + [{threshold: 1, claim: {balance: 250, plan: "premium", age: 3, loans: [], extraField: "x"}}, {claim: {age: 3, balance: 250, decision: 250, extraField: "x", loans: [], plan: "premium", points: "X"}, threshold: 1}], + [{threshold: 0, claim: {balance: 100, plan: "trial", age: 10, loans: [{income: -500, dueDate: "2025-03-20T10:15:30Z"}, {income: 0.25, dueDate: "2030-12-31"}]}}, {claim: {age: 10, balance: 100, decision: 100, loans: [{dueDate: "2025-03-20T10:15:30Z", flag: 0.9090909090909090909090909091, income: -500, quota: null, share: -500, surcharge: "none"}, {dueDate: "2030-12-31", flag: 0.9090909090909090909090909091, income: 0.25, quota: null, share: 0.25, surcharge: "none"}], plan: "trial", points: "A1"}, threshold: 0}], + [{threshold: 10, claim: {balance: 0, plan: "basic", age: -0.01, loans: [{income: 0, dueDate: "2030-12-31"}, {income: 381, dueDate: "1990-06-15"}]}}, {claim: {age: -0.01, balance: 0, decision: 0, loans: [{dueDate: "2030-12-31", flag: 10, income: 0, quota: null, share: 0, surcharge: "VIP"}, {dueDate: "1990-06-15", flag: null, income: 381, quota: null, share: 100, surcharge: null}], plan: "basic", points: "A1"}, threshold: 10}], + [{threshold: -2, claim: {balance: 2.50, age: 250, loans: [{income: 65, dueDate: "1990-06-15"}, {income: 0.5, dueDate: "2025-03-20"}]}}, {claim: {age: 250, balance: 2.50, decision: 2.50, loans: [{dueDate: "1990-06-15", flag: null, income: 65, quota: null, share: null, surcharge: null}, {dueDate: "2025-03-20", flag: 0.9960159362549800796812749004, income: 0.5, quota: null, share: 0.5, surcharge: "none"}], points: "A1"}, threshold: -2}], + [{threshold: 1, claim: {balance: 50, plan: "basic", age: 99.99, loans: [{income: 10, dueDate: "2025-03-20T10:15:30Z"}, {income: 0.5, dueDate: "2025-03-20"}, {income: -0.01, dueDate: "1990-06-15"}]}}, {claim: {age: 99.99, balance: 50, decision: 50, loans: [{dueDate: "2025-03-20T10:15:30Z", flag: 1, income: 10, quota: 1, share: 10, surcharge: "VIP"}, {dueDate: "2025-03-20", flag: 1, income: 0.5, quota: null, share: 0.5, surcharge: "VIP"}, {dueDate: "1990-06-15", flag: null, income: -0.01, quota: null, share: null, surcharge: null}], plan: "basic", points: "A1"}, threshold: 1}], + [{threshold: 1, claim: {balance: 50, plan: "basic", age: 2, loans: []}}, {claim: {age: 2, balance: 50, decision: 50, loans: [], plan: "basic", points: "A1"}, threshold: 1}], + [{threshold: -2, claim: {balance: 5, plan: "basic", age: 1, loans: []}}, {claim: {age: 1, balance: 5, decision: 5, loans: [], plan: "basic", points: "A1"}, threshold: -2}], + [{threshold: 0.5, claim: {balance: -500, plan: null, age: 250, loans: []}}, {claim: {age: 250, balance: -500, decision: -500, loans: [], plan: null, points: "A1"}, threshold: 0.5}], + [{threshold: 0, claim: {balance: null, plan: "basic", age: -500, loans: [{income: 250, dueDate: "2024-02-29"}, {income: -0.5, dueDate: "1990-06-15"}]}}, "!error: MissingRequiredInputs"], + [{threshold: 0.5, claim: {balance: 100, age: 18, loans: [{income: -0.01, dueDate: "2025-03-20T10:15:30Z"}, {income: 100, dueDate: "2000-01-01"}, {income: 1.5, dueDate: "2024-02-29"}, {income: 0.5, dueDate: "1990-06-15"}]}}, {claim: {age: 18, balance: 100, decision: 100, loans: [{dueDate: "2025-03-20T10:15:30Z", flag: 0.5, income: -0.01, quota: null, share: -0.01, surcharge: "VIP"}, {dueDate: "2000-01-01", flag: null, income: 100, quota: null, share: null, surcharge: null}, {dueDate: "2024-02-29", flag: 0.5, income: 1.5, quota: null, share: 1.5, surcharge: "VIP"}, {dueDate: "1990-06-15", flag: null, income: 0.5, quota: null, share: null, surcharge: null}], points: "A1"}, threshold: 0.5}], + [{threshold: 10, claim: {balance: 50, plan: "basic", age: 5, loans: []}}, {claim: {age: 5, balance: 50, decision: 50, loans: [], plan: "basic", points: "A1"}, threshold: 10}], + [{threshold: 0.5, claim: {balance: 2, plan: "trial", age: 100, loans: [{income: 0, dueDate: "2024-02-29"}, {income: 0.5, dueDate: "2025-03-20T10:15:30Z"}, {income: 50, dueDate: "1990-06-15"}]}}, {claim: {age: 100, balance: 2, decision: 2, loans: [{dueDate: "2024-02-29", flag: 0.5, income: 0, quota: null, share: 0, surcharge: "VIP"}, {dueDate: "2025-03-20T10:15:30Z", flag: 0.5, income: 0.5, quota: 66.666666666666666666666666667, share: 0.5, surcharge: "VIP"}, {dueDate: "1990-06-15", flag: null, income: 50, quota: null, share: null, surcharge: null}], plan: "trial", points: "A1"}, threshold: 0.5}], + [{threshold: 0, claim: {balance: [1], plan: "plus", age: 250, loans: [{income: 100, dueDate: "2030-12-31"}, {income: 2, dueDate: "2030-12-31"}]}}, "!error: InputValidationFailed"], + [{threshold: 10, claim: {balance: 50, age: 123456789.123, loans: [{income: 100, dueDate: "2024-02-29"}, {income: -0.5, dueDate: "2000-01-01"}]}}, {claim: {age: 123456789.123, balance: 50, decision: 50, loans: [{dueDate: "2024-02-29", flag: 10, income: 100, quota: null, share: 100, surcharge: "VIP"}, {dueDate: "2000-01-01", flag: null, income: -0.5, quota: null, share: 100, surcharge: null}], points: "A1"}, threshold: 10}], + [{threshold: -2, claim: {balance: 10, age: 50, loans: [{income: 100, dueDate: "1990-06-15"}, {income: 1000, dueDate: "2025-03-20T10:15:30Z"}]}}, {claim: {age: 50, balance: 10, decision: 10, loans: [{dueDate: "1990-06-15", flag: null, income: 100, quota: null, share: null, surcharge: null}, {dueDate: "2025-03-20T10:15:30Z", flag: 0.9803921568627450980392156863, income: 1000, quota: null, share: 1000, surcharge: "none"}], points: "A1"}, threshold: -2}], + [{threshold: -2, claim: {balance: 1000, age: 50, loans: []}}, {claim: {age: 50, balance: 1000, decision: 1000, loans: [], points: "A1"}, threshold: -2}], + [{threshold: 0.5, claim: {balance: 1, age: 1000, loans: [{income: 0.5, dueDate: "2024-01-01"}, {income: 0, dueDate: "2000-01-01"}]}}, {claim: {age: 1000, balance: 1, decision: 1, loans: [{dueDate: "2024-01-01", flag: 0.5, income: 0.5, quota: 666.66666666666666666666666667, share: 0.5, surcharge: "VIP"}, {dueDate: "2000-01-01", flag: null, income: 0, quota: null, share: null, surcharge: null}], points: "A1"}, threshold: 0.5}], + [{threshold: -2, claim: {balance: 1, plan: "basic", age: 0.5, loans: [{income: 2, dueDate: "2030-12-31"}]}}, {claim: {age: 0.5, balance: 1, decision: 1, loans: [{dueDate: "2030-12-31", flag: 0.3333333333333333333333333333, income: 2, quota: null, share: 2, surcharge: "none"}], plan: "basic", points: "A1"}, threshold: -2}], + [{threshold: 10, claim: {balance: 100, plan: "basic", age: 1000, loans: [{income: 7.25, dueDate: "2025-03-20"}, {income: 1e3, dueDate: "2024-01-01"}, {income: 5, dueDate: "2024-01-01"}, {income: -0.01, dueDate: "2025-03-20T10:15:30Z"}]}}, {claim: {age: 1000, balance: 100, decision: 100, loans: [{dueDate: "2025-03-20", flag: 10, income: 7.25, quota: null, share: 7.25, surcharge: "VIP"}, {dueDate: "2024-01-01", flag: 10, income: 1000, quota: null, share: 1000, surcharge: "VIP"}, {dueDate: "2024-01-01", flag: 10, income: 5, quota: 10, share: 5, surcharge: "VIP"}, {dueDate: "2025-03-20T10:15:30Z", flag: 10, income: -0.01, quota: null, share: -0.01, surcharge: "VIP"}], plan: "basic", points: "A1"}, threshold: 10}], + [{threshold: 0, claim: {balance: 1e3, plan: "basic", age: 99999999999999999999, loans: []}}, {claim: {age: 99999999999999999999, balance: 1000, decision: 1000, loans: [], plan: "basic", points: "A1"}, threshold: 0}], + [{threshold: 10, claim: {balance: 1000000, plan: "plus", age: 1.5, loans: [{income: -1, dueDate: "2024-01-01"}], extraField: {nested: true}}}, {claim: {age: 1.5, balance: 1000000, decision: 1000000, extraField: {nested: true}, loans: [{dueDate: "2024-01-01", flag: 10, income: -1, quota: null, share: -1, surcharge: "VIP"}], plan: "plus", points: "A1"}, threshold: 10}], + [{threshold: -2, claim: {balance: 5, plan: "trial", age: 3, loans: []}}, {claim: {age: 3, balance: 5, decision: 5, loans: [], plan: "trial", points: "A1"}, threshold: -2}], + [{threshold: 0, claim: {balance: 50, plan: "basic", age: 0, loans: [{income: 99999999999999999999, dueDate: "2025-03-20T10:15:30Z"}]}}, {claim: {age: 0, balance: 50, decision: 50, loans: [{dueDate: "2025-03-20T10:15:30Z", flag: 0, income: 99999999999999999999, quota: null, share: 99999999999999999999, surcharge: "none"}], plan: "basic", points: "A1"}, threshold: 0}], + [{threshold: 10, claim: {balance: 100, plan: null, age: 0.5, loans: [{income: 50, dueDate: "2024-01-01"}, {income: 0, dueDate: "2024-01-01"}, {income: -0, dueDate: "2000-01-01"}]}}, {claim: {age: 0.5, balance: 100, decision: 100, loans: [{dueDate: "2024-01-01", flag: 10, income: 50, quota: 10, share: 50, surcharge: "VIP"}, {dueDate: "2024-01-01", flag: 10, income: 0, quota: null, share: 0, surcharge: "VIP"}, {dueDate: "2000-01-01", flag: null, income: 0, quota: null, share: 100, surcharge: null}], plan: null, points: "A1"}, threshold: 10}], + [{threshold: 0.5, claim: {balance: 10, plan: "plus", loans: [{income: 100, dueDate: "2025-03-20"}, {income: 10, dueDate: "1990-06-15"}, {income: 1, dueDate: "2025-03-20T10:15:30Z"}, {income: 0.5, dueDate: "2030-12-31"}]}}, "!error: MissingRequiredInputs"], + ], +} + +// seed 334500 (attempt 0) +{ + name: "a 46: tenant/members: 1 expression, 1 match, 2 table; 2 root, 1 per-member, 1 top-level computed", + policy: { + models: {tenant: {years: "number", vip: "boolean?", score: "number", verified: "boolean?", flagged: "boolean", members: "member[]"}, member: {days: "number", priority: "boolean", code: "string?", birthDate: "date?"}}, + blocks: [ + {table: "t2", inputs: ["tenant.flagged"], outputs: ["tenant.capped"], rules: [ + ["", "100"], + ["true", "tenant.score"], + ]}, + {table: "t3", hit: "collect", inputs: [null, "(tenant.vip ?? false)", null], outputs: ["flag"], rules: [ + ["not ((tenant.vip ?? false))", "false", "", "tenant.years"], + ["", "", "", "tenant.years"], + ]}, + {match: "tenant.points", arms: [["1000 == tenant.score", "tenant.flagged"], ["tenant.years < 250", "not (not ((tenant.vip ?? false)))"], ["tenant.years != tenant.years", "tenant.flagged"], ["1000 > tenant.score", "tenant.verified != null"], ["", "tenant.flagged"]]}, + {expression: "member.ok", value: "some(tenant.members, #.code == null)"}, + ], + }, + cases: [ + [{tenant: {years: 18, vip: false, score: 1000, verified: true, flagged: false, members: [{days: 123456789.123, priority: false, code: null, birthDate: "2025-03-20T10:15:30Z"}, {days: 1000, priority: true, code: "-", birthDate: null}, {days: 0.5, priority: false, code: null, birthDate: "2025-03-20"}, {days: 100, priority: false}]}}, {flag: [18, 18], tenant: {capped: 100, flagged: false, members: [{birthDate: "2025-03-20T10:15:30Z", code: null, days: 123456789.123, ok: true, priority: false}, {birthDate: null, code: "-", days: 1000, ok: true, priority: true}, {birthDate: "2025-03-20", code: null, days: 0.5, ok: true, priority: false}, {days: 100, ok: true, priority: false}], points: false, score: 1000, verified: true, vip: false, years: 18}}], + [{tenant: {years: 99.99, vip: false, score: -1, verified: true, flagged: false, members: [{days: 1000, priority: false}, {days: 1, priority: false, birthDate: null}]}}, {flag: [99.99, 99.99], tenant: {capped: 100, flagged: false, members: [{days: 1000, ok: true, priority: false}, {birthDate: null, days: 1, ok: true, priority: false}], points: false, score: -1, verified: true, vip: false, years: 99.99}}], + [{tenant: {years: 0.000001, vip: false, score: 99.99, verified: false, flagged: false, members: [{days: 365, priority: false, code: "a-b-c", birthDate: "2024-01-01"}, {days: 1000000, priority: false, code: "US", birthDate: "2024-01-01"}, {days: 250, priority: false, code: "12", birthDate: "2025-03-20"}, {days: 1000, priority: true, code: "a-b-c", birthDate: "2000-01-01"}]}}, {flag: [0.000001, 0.000001], tenant: {capped: 100, flagged: false, members: [{birthDate: "2024-01-01", code: "a-b-c", days: 365, ok: false, priority: false}, {birthDate: "2024-01-01", code: "US", days: 1000000, ok: false, priority: false}, {birthDate: "2025-03-20", code: "12", days: 250, ok: false, priority: false}, {birthDate: "2000-01-01", code: "a-b-c", days: 1000, ok: false, priority: true}], points: false, score: 99.99, verified: false, vip: false, years: 0.000001}}], + [{tenant: {years: 1000, score: -500, flagged: false, members: [{days: 100, priority: true, code: "VIP", birthDate: "2025-03-20T10:15:30Z"}]}}, {flag: [1000, 1000], tenant: {capped: 100, flagged: false, members: [{birthDate: "2025-03-20T10:15:30Z", code: "VIP", days: 100, ok: false, priority: true}], points: false, score: -500, years: 1000}}], + [{tenant: {years: 1000, vip: true, score: -0, verified: false, flagged: false, members: [{days: 250, priority: false, code: "A1", birthDate: "not a date"}, {days: -0.01, priority: true, code: "Oslo", birthDate: "2000-01-01"}, {days: -0.01, priority: false, code: "12", birthDate: "1990-06-15"}]}}, "!error: InputValidationFailed"], + [{tenant: {years: 1000, vip: true, score: 250, verified: false, flagged: true, members: []}}, {flag: [1000], tenant: {capped: 100, flagged: true, members: [], points: true, score: 250, verified: false, vip: true, years: 1000}}], + [{tenant: {years: 250, vip: true, score: -0, verified: false, flagged: true, members: []}}, {flag: [250], tenant: {capped: 100, flagged: true, members: [], points: true, score: 0, verified: false, vip: true, years: 250}}], + [{tenant: {years: 0.5, score: 0, flagged: true, members: [{days: 65, priority: true, code: "3.5", birthDate: "1990-06-15"}, {days: 250, priority: true, code: "abc", birthDate: "2024-02-29"}]}}, {flag: [0.5, 0.5], tenant: {capped: 100, flagged: true, members: [{birthDate: "1990-06-15", code: "3.5", days: 65, ok: false, priority: true}, {birthDate: "2024-02-29", code: "abc", days: 250, ok: false, priority: true}], points: false, score: 0, years: 0.5}}], + [{tenant: {years: 3, vip: false, score: -500, verified: true, flagged: false, members: [{days: -1, priority: false, code: "3.5", birthDate: "2025-03-20"}]}}, {flag: [3, 3], tenant: {capped: 100, flagged: false, members: [{birthDate: "2025-03-20", code: "3.5", days: -1, ok: false, priority: false}], points: false, score: -500, verified: true, vip: false, years: 3}}], + [{tenant: {years: 100, vip: true, score: 1000, verified: true, flagged: true, members: [{days: 99.99, priority: true, code: "abc", birthDate: "1990-06-15"}, {days: 250, priority: false, code: "", birthDate: "2024-02-29"}, {days: -0, priority: true, code: "Oslo", birthDate: "2024-01-01"}]}}, {flag: [100], tenant: {capped: 100, flagged: true, members: [{birthDate: "1990-06-15", code: "abc", days: 99.99, ok: false, priority: true}, {birthDate: "2024-02-29", code: "", days: 250, ok: false, priority: false}, {birthDate: "2024-01-01", code: "Oslo", days: 0, ok: false, priority: true}], points: true, score: 1000, verified: true, vip: true, years: 100}}], + [{tenant: {years: 0.5, vip: false, score: 0.5, verified: true, flagged: false, members: [], extraField: {nested: true}}}, {flag: [0.5, 0.5], tenant: {capped: 100, extraField: {nested: true}, flagged: false, members: [], points: false, score: 0.5, verified: true, vip: false, years: 0.5}}], + [{tenant: {years: 2.50, score: 0.5, verified: true, flagged: false, members: [{days: 250, priority: true, code: "retail", birthDate: null}]}}, {flag: [2.50, 2.50], tenant: {capped: 100, flagged: false, members: [{birthDate: null, code: "retail", days: 250, ok: false, priority: true}], points: false, score: 0.5, verified: true, years: 2.50}}], + [{tenant: {years: 2, vip: false, score: 100, verified: false, flagged: true, members: []}}, {flag: [2, 2], tenant: {capped: 100, flagged: true, members: [], points: false, score: 100, verified: false, vip: false, years: 2}}], + [{tenant: {years: 2.50, vip: true, score: 0.1, verified: true, flagged: false, members: []}}, {flag: [2.50], tenant: {capped: 100, flagged: false, members: [], points: true, score: 0.1, verified: true, vip: true, years: 2.50}}], + [{tenant: {years: 0.1, vip: null, score: 99999999999999999999, verified: null, flagged: false, members: [{days: 100, priority: true, code: "12"}]}}, {flag: [0.1, 0.1], tenant: {capped: 100, flagged: false, members: [{code: "12", days: 100, ok: false, priority: true}], points: false, score: 99999999999999999999, verified: null, vip: null, years: 0.1}}], + [{tenant: {years: -0.5, vip: false, score: 73, verified: true, flagged: false, members: [{days: 100, priority: true, code: "US", birthDate: "2030-12-31"}, {days: 250, priority: false, code: "DE", birthDate: "2000-01-01"}, {days: 65, priority: true, code: "3.5", birthDate: "2025-03-20T10:15:30Z"}, {days: 250, priority: true, code: "gold", birthDate: "1990-06-15"}]}}, {flag: [-0.5, -0.5], tenant: {capped: 100, flagged: false, members: [{birthDate: "2030-12-31", code: "US", days: 100, ok: false, priority: true}, {birthDate: "2000-01-01", code: "DE", days: 250, ok: false, priority: false}, {birthDate: "2025-03-20T10:15:30Z", code: "3.5", days: 65, ok: false, priority: true}, {birthDate: "1990-06-15", code: "gold", days: 250, ok: false, priority: true}], points: false, score: 73, verified: true, vip: false, years: -0.5}}], + [{tenant: {years: -0.5, vip: true, score: 1e3, verified: false, flagged: true, members: [{days: 99.99, priority: false, code: "retail", birthDate: 20250101}, {days: 10, priority: false, code: "-", birthDate: "2025-03-20"}, {days: -0.01, priority: true, code: "DE", birthDate: "2025-03-20T10:15:30Z"}, {days: 0, priority: true, code: "Oslo", birthDate: "2024-01-01"}]}}, "!error: InputValidationFailed"], + [{tenant: {years: -1, vip: true, score: 5, verified: true, flagged: false, members: [{days: -0.01, priority: true, code: "DE", birthDate: "2025-03-20"}, {days: 123456789.123, priority: true, code: "-", birthDate: "2025-03-20T10:15:30Z"}]}}, {flag: [-1], tenant: {capped: 100, flagged: false, members: [{birthDate: "2025-03-20", code: "DE", days: -0.01, ok: false, priority: true}, {birthDate: "2025-03-20T10:15:30Z", code: "-", days: 123456789.123, ok: false, priority: true}], points: true, score: 5, verified: true, vip: true, years: -1}}], + [{tenant: {years: 1000, score: 7.25, flagged: true, members: [{days: 10, priority: true, code: "é ü", birthDate: "2025-03-20"}, {days: 0.000001, priority: true}, {days: 0.5, priority: true, code: "日本", birthDate: "2024-02-29"}, {days: 100, priority: true, code: "US", birthDate: "2024-01-01"}, {days: 99999999999999999999, priority: true, code: "12"}]}}, {flag: [1000, 1000], tenant: {capped: 100, flagged: true, members: [{birthDate: "2025-03-20", code: "é ü", days: 10, ok: true, priority: true}, {days: 0.000001, ok: true, priority: true}, {birthDate: "2024-02-29", code: "日本", days: 0.5, ok: true, priority: true}, {birthDate: "2024-01-01", code: "US", days: 100, ok: true, priority: true}, {code: "12", days: 99999999999999999999, ok: true, priority: true}], points: false, score: 7.25, years: 1000}}], + [{tenant: {years: 100, score: 1000, verified: true, flagged: false, members: [{days: 250, priority: false, birthDate: "2024-01-01"}]}}, {flag: [100, 100], tenant: {capped: 100, flagged: false, members: [{birthDate: "2024-01-01", days: 250, ok: true, priority: false}], points: false, score: 1000, verified: true, years: 100}}], + [{tenant: {years: 5, vip: true, score: 2.50, verified: true, flagged: false, members: [{days: 1000000, priority: true, code: "Zed", birthDate: "2030-12-31"}]}}, {flag: [5], tenant: {capped: 100, flagged: false, members: [{birthDate: "2030-12-31", code: "Zed", days: 1000000, ok: false, priority: true}], points: true, score: 2.50, verified: true, vip: true, years: 5}}], + [{tenant: {years: 250, vip: false, score: 65, verified: true, flagged: true, members: [{days: 2, priority: true, code: "abc", birthDate: "1990-06-15"}, {days: 3, priority: false, code: "Oslo", birthDate: "2025-03-20"}]}}, {flag: [250, 250], tenant: {capped: 100, flagged: true, members: [{birthDate: "1990-06-15", code: "abc", days: 2, ok: false, priority: true}, {birthDate: "2025-03-20", code: "Oslo", days: 3, ok: false, priority: false}], points: true, score: 65, verified: true, vip: false, years: 250}}], + [{tenant: {years: 192, score: 250, verified: false, flagged: false, members: [{days: 1000, priority: false, code: "Zed"}, {days: 0.000001, priority: false}, {days: 18, priority: false, birthDate: null}, {days: 99999999999999999999, priority: true, birthDate: "2024-01-01"}]}}, {flag: [192, 192], tenant: {capped: 100, flagged: false, members: [{code: "Zed", days: 1000, ok: true, priority: false}, {days: 0.000001, ok: true, priority: false}, {birthDate: null, days: 18, ok: true, priority: false}, {birthDate: "2024-01-01", days: 99999999999999999999, ok: true, priority: true}], points: false, score: 250, verified: false, years: 192}}], + [{tenant: {years: -0, vip: true, score: 0.1, verified: false, flagged: false, members: [{days: 0.1, priority: false, code: "gold", birthDate: null}]}}, {flag: [0], tenant: {capped: 100, flagged: false, members: [{birthDate: null, code: "gold", days: 0.1, ok: false, priority: false}], points: true, score: 0.1, verified: false, vip: true, years: 0}}], + [{tenant: {years: "12", vip: true, score: 65, verified: false, flagged: true, members: []}}, "!error: InputValidationFailed"], + ], +} + +// seed 334600 (attempt 0) +{ + name: "a 47: applicant/parcels: 1 expression, 1 match, 3 table; 7 root, 2 per-member, 0 top-level computed", + policy: { + models: {applicant: {weight: "number", sku: "string", plan: "string(basic|plus|premium|trial)", active: "boolean", openedAt: "date", birthDate: "date?", parcels: "parcel[]?"}, parcel: {price: "number", weight: "number", active: "boolean", openedAt: "date"}}, + blocks: [ + {match: "applicant.exposure", arms: [["applicant.grade in [41..162]", "applicant.sku"], ["applicant.grade in [19..106]", "string(applicant.grade)"], ["(applicant.weight * applicant.weight) <= applicant.weight", "applicant.sku"], ["", "applicant.sku"]]}, + {table: "t1", hit: "collect", inputs: [null, null], outputs: ["applicant.total", "applicant.adjusted", "applicant.points"], rules: [ + ["", "", "applicant.weight", "(applicant.active ? applicant.weight : applicant.weight)", "string(applicant.weight)"], + ["applicant.sku in ['Oslo', 'Oslo']", "applicant.weight in [20..190]", "applicant.weight", "applicant.weight", "applicant.sku"], + ["", "(applicant.active and applicant.active)", "", "applicant.openedAt.year()", "applicant.sku"], + ["applicant.weight < applicant.weight", "applicant.weight <= applicant.weight", "18", "(applicant.weight) / (abs(applicant.weight) + 1)", "applicant.sku"], + ]}, + {table: "t2", hit: "collect", inputs: ["applicant.active", "applicant.plan"], outputs: ["applicant.quota", "applicant.tag"], rules: [ + ["false", "'plus', 'basic'", "5", "applicant.weight"], + ["", "'trial'", "applicant.weight", "3"], + ["false", "'trial', 'plus'", "applicant.weight", "(min(applicant.total) ?? 0)"], + ["", "'trial'", "", "applicant.weight"], + ["", "", "applicant.weight", "1.5"], + ]}, + {table: "t3", inputs: ["applicant.active", "applicant.active"], outputs: ["parcel.capped", "parcel.review"], rules: [ + ["true", "false", "250", "'A1'"], + ["true", "true", "", ""], + ["", "true", "parcel.weight", ""], + ["false", "true", "applicant.weight", "applicant.sku"], + ["", "", "(parcel.price * applicant.weight)", "applicant.sku"], + ]}, + {expression: "applicant.grade", value: "applicant.openedAt.diff(d('2025-01-01'), 'day')"}, + ], + }, + cases: [ + [{applicant: {weight: 250, sku: null, plan: "plus", active: true, openedAt: "2000-01-01", birthDate: "2000-01-01", parcels: [{price: 99.99, weight: 18, active: true, openedAt: "2030-12-31"}]}}, "!error: MissingRequiredInputs"], + [{applicant: {weight: 2, sku: "ok", plan: "plus", active: true, openedAt: "2024-01-01", birthDate: null, parcels: [{price: 1e3, weight: 354, active: false, openedAt: "2024-02-29"}, {price: 3, weight: 1, active: true, openedAt: "2000-01-01"}, {price: 250, weight: -0.5, active: true, openedAt: "2024-01-01"}, {price: 0.1, weight: 0, active: true, openedAt: "2024-01-01"}, {price: 18, weight: 7.25, active: false, openedAt: "1990-06-15"}]}}, {applicant: {active: true, adjusted: [2, 2024], birthDate: null, exposure: "ok", grade: -366, openedAt: "2024-01-01", parcels: [{active: false, capped: 354, openedAt: "2024-02-29", price: 1000, review: "ok", weight: 354}, {active: true, capped: 1, openedAt: "2000-01-01", price: 3, review: "ok", weight: 1}, {active: true, capped: -0.5, openedAt: "2024-01-01", price: 250, review: "ok", weight: -0.5}, {active: true, capped: 0, openedAt: "2024-01-01", price: 0.1, review: "ok", weight: 0}, {active: false, capped: 7.25, openedAt: "1990-06-15", price: 18, review: "ok", weight: 7.25}], plan: "plus", points: ["2", "ok"], quota: [2], sku: "ok", tag: [1.5], total: [2], weight: 2}}], + [{applicant: {weight: 99.99, sku: "low", plan: "plus", active: false, openedAt: "2030-12-31", birthDate: "2024-02-29", parcels: [{price: 1000000, weight: 2, active: false, openedAt: "2000-01-01"}, {price: 0.000001, weight: 156, active: false, openedAt: "2024-02-29"}, {price: 99.99, weight: 0.1, active: true, openedAt: "1990-06-15"}, {price: 5, weight: 7.25, active: true, openedAt: "2030-12-31"}, {price: 0.1, weight: 99999999999999999999, active: true, openedAt: "2000-01-01"}]}}, {applicant: {active: false, adjusted: [99.99], birthDate: "2024-02-29", exposure: "low", grade: 2190, openedAt: "2030-12-31", parcels: [{active: false, capped: 99990000.00, openedAt: "2000-01-01", price: 1000000, review: "low", weight: 2}, {active: false, capped: 0.00009999, openedAt: "2024-02-29", price: 0.000001, review: "low", weight: 156}, {active: true, capped: 9998.0001, openedAt: "1990-06-15", price: 99.99, review: "low", weight: 0.1}, {active: true, capped: 499.95, openedAt: "2030-12-31", price: 5, review: "low", weight: 7.25}, {active: true, capped: 9.999, openedAt: "2000-01-01", price: 0.1, review: "low", weight: 99999999999999999999}], plan: "plus", points: ["99.99"], quota: [5, 99.99, 99.99], sku: "low", tag: [99.99, 99.99, 1.5], total: [99.99], weight: 99.99}}], + [{applicant: {weight: 18, sku: "", plan: "trial", active: true, openedAt: "2024-02-29", birthDate: "2030-12-31", parcels: [{price: 0, weight: 1, active: true, openedAt: "2000-01-01"}, {price: 0.1, weight: 250, active: false, openedAt: "2030-12-31"}]}}, {applicant: {active: true, adjusted: [18, 2024], birthDate: "2030-12-31", exposure: "", grade: -307, openedAt: "2024-02-29", parcels: [{active: true, capped: 1, openedAt: "2000-01-01", price: 0, review: "", weight: 1}, {active: false, capped: 250, openedAt: "2030-12-31", price: 0.1, review: "", weight: 250}], plan: "trial", points: ["18", ""], quota: [18, 18], sku: "", tag: [3, 18, 1.5], total: [18], weight: 18}}], + [{applicant: {weight: 250, sku: "3.5", plan: "plus", active: false, openedAt: "1990-06-15", birthDate: "2024-02-29", parcels: [{price: -0, weight: 18, active: false, openedAt: "2000-01-01"}, {price: 18, weight: 65, active: true, openedAt: "2025-03-20T10:15:30Z"}, {price: 1000000, weight: 0.000001, active: false, openedAt: "2000-01-01"}]}}, {applicant: {active: false, adjusted: [250], birthDate: "2024-02-29", exposure: "3.5", grade: -12619, openedAt: "1990-06-15", parcels: [{active: false, capped: 0, openedAt: "2000-01-01", price: 0, review: "3.5", weight: 18}, {active: true, capped: 4500, openedAt: "2025-03-20T10:15:30Z", price: 18, review: "3.5", weight: 65}, {active: false, capped: 250000000, openedAt: "2000-01-01", price: 1000000, review: "3.5", weight: 0.000001}], plan: "plus", points: ["250"], quota: [5, 250, 250], sku: "3.5", tag: [250, 250, 1.5], total: [250], weight: 250}}], + [{applicant: {weight: -500, sku: "Oslo", plan: "basic", active: false, openedAt: "2025-03-20T10:15:30Z", birthDate: "2030-12-31", parcels: [{price: 2, weight: 250, active: false, openedAt: "1990-06-15"}, {price: 7.25, weight: -0.5, active: false, openedAt: "2030-12-31"}]}}, {applicant: {active: false, adjusted: [-500], birthDate: "2030-12-31", exposure: "Oslo", grade: 78, openedAt: "2025-03-20T10:15:30Z", parcels: [{active: false, capped: -1000, openedAt: "1990-06-15", price: 2, review: "Oslo", weight: 250}, {active: false, capped: -3625.00, openedAt: "2030-12-31", price: 7.25, review: "Oslo", weight: -0.5}], plan: "basic", points: ["-500"], quota: [5, -500], sku: "Oslo", tag: [-500, 1.5], total: [-500], weight: -500}}], + [{applicant: {weight: 2, sku: "A1", plan: "trial", active: true, openedAt: "1990-06-15", birthDate: "2025-03-20", parcels: []}}, {applicant: {active: true, adjusted: [2, 1990], birthDate: "2025-03-20", exposure: "A1", grade: -12619, openedAt: "1990-06-15", parcels: [], plan: "trial", points: ["2", "A1"], quota: [2, 2], sku: "A1", tag: [3, 2, 1.5], total: [2], weight: 2}}], + [{applicant: {weight: -500, sku: "-", plan: "premium", active: false, openedAt: "2024-01-01", birthDate: "2030-12-31", parcels: []}}, {applicant: {active: false, adjusted: [-500], birthDate: "2030-12-31", exposure: "-", grade: -366, openedAt: "2024-01-01", parcels: [], plan: "premium", points: ["-500"], quota: [-500], sku: "-", tag: [1.5], total: [-500], weight: -500}}], + [{applicant: {weight: 0.000001, sku: "US", plan: "basic", active: false, openedAt: "2025-03-20T10:15:30Z", birthDate: "2030-12-31", parcels: [{price: 0.1, weight: 100, active: false, openedAt: "2024-02-29"}], extraField: "x"}}, {applicant: {active: false, adjusted: [0.000001], birthDate: "2030-12-31", exposure: "US", extraField: "x", grade: 78, openedAt: "2025-03-20T10:15:30Z", parcels: [{active: false, capped: 0.0000001, openedAt: "2024-02-29", price: 0.1, review: "US", weight: 100}], plan: "basic", points: ["0.000001"], quota: [5, 0.000001], sku: "US", tag: [0.000001, 1.5], total: [0.000001], weight: 0.000001}}], + [{applicant: {weight: 2, sku: "A1", plan: "plus", active: true, openedAt: "2024-01-01", birthDate: "2024-02-29", parcels: []}}, {applicant: {active: true, adjusted: [2, 2024], birthDate: "2024-02-29", exposure: "A1", grade: -366, openedAt: "2024-01-01", parcels: [], plan: "plus", points: ["2", "A1"], quota: [2], sku: "A1", tag: [1.5], total: [2], weight: 2}}], + [{applicant: {weight: 99.99, sku: "VIP", plan: "basic", active: true, openedAt: "2024-01-01", birthDate: "1990-06-15", parcels: []}}, {applicant: {active: true, adjusted: [99.99, 2024], birthDate: "1990-06-15", exposure: "VIP", grade: -366, openedAt: "2024-01-01", parcels: [], plan: "basic", points: ["99.99", "VIP"], quota: [99.99], sku: "VIP", tag: [1.5], total: [99.99], weight: 99.99}}], + [{applicant: {weight: 250, sku: " pad ", plan: "plus", active: false, openedAt: "1990-06-15", birthDate: "2000-01-01", parcels: [{price: 0.000001, weight: 7.25, active: false, openedAt: "2030-12-31"}, {price: 99.99, weight: 0, active: false, openedAt: "2025-03-20"}, {price: 18, weight: 65, active: false, openedAt: "1990-06-15"}]}}, {applicant: {active: false, adjusted: [250], birthDate: "2000-01-01", exposure: " pad ", grade: -12619, openedAt: "1990-06-15", parcels: [{active: false, capped: 0.000250, openedAt: "2030-12-31", price: 0.000001, review: " pad ", weight: 7.25}, {active: false, capped: 24997.50, openedAt: "2025-03-20", price: 99.99, review: " pad ", weight: 0}, {active: false, capped: 4500, openedAt: "1990-06-15", price: 18, review: " pad ", weight: 65}], plan: "plus", points: ["250"], quota: [5, 250, 250], sku: " pad ", tag: [250, 250, 1.5], total: [250], weight: 250}}], + [{applicant: {weight: -1, sku: "", plan: "basic", active: true, openedAt: "1990-06-15", birthDate: "2030-12-31", parcels: [{price: 7.25, weight: 7.25, active: false, openedAt: "1990-06-15"}]}}, {applicant: {active: true, adjusted: [-1, 1990], birthDate: "2030-12-31", exposure: "", grade: -12619, openedAt: "1990-06-15", parcels: [{active: false, capped: 7.25, openedAt: "1990-06-15", price: 7.25, review: "", weight: 7.25}], plan: "basic", points: ["-1", ""], quota: [-1], sku: "", tag: [1.5], total: [-1], weight: -1}}], + [{applicant: {weight: 2, sku: "a", plan: "basic", active: true, openedAt: "2024-02-29", birthDate: "1990-06-15", parcels: [{price: 2, weight: 18, active: false, openedAt: "1990-06-15"}, {price: 0, weight: 10, active: true, openedAt: "2000-01-01"}], extraField: 1}}, {applicant: {active: true, adjusted: [2, 2024], birthDate: "1990-06-15", exposure: "a", extraField: 1, grade: -307, openedAt: "2024-02-29", parcels: [{active: false, capped: 18, openedAt: "1990-06-15", price: 2, review: "a", weight: 18}, {active: true, capped: 10, openedAt: "2000-01-01", price: 0, review: "a", weight: 10}], plan: "basic", points: ["2", "a"], quota: [2], sku: "a", tag: [1.5], total: [2], weight: 2}}], + [{applicant: {weight: -1, sku: "日本", plan: "trial", active: false, openedAt: "2000-01-01", birthDate: "1990-06-15", parcels: [{price: 18, weight: 1, active: true, openedAt: "2025-03-20T10:15:30Z"}, {price: 1.5, weight: 5, active: false, openedAt: "1990-06-15"}]}}, {applicant: {active: false, adjusted: [-1], birthDate: "1990-06-15", exposure: "日本", grade: -9132, openedAt: "2000-01-01", parcels: [{active: true, capped: -18, openedAt: "2025-03-20T10:15:30Z", price: 18, review: "日本", weight: 1}, {active: false, capped: -1.5, openedAt: "1990-06-15", price: 1.5, review: "日本", weight: 5}], plan: "trial", points: ["-1"], quota: [-1, -1, -1], sku: "日本", tag: [3, -1, -1, 1.5], total: [-1], weight: -1}}], + [{applicant: {weight: 0, sku: "Zed", plan: "plus", active: true, openedAt: "2000-01-01", birthDate: "2024-01-01", parcels: []}}, {applicant: {active: true, adjusted: [0, 2000], birthDate: "2024-01-01", exposure: "Zed", grade: -9132, openedAt: "2000-01-01", parcels: [], plan: "plus", points: ["0", "Zed"], quota: [0], sku: "Zed", tag: [1.5], total: [0], weight: 0}}], + [{applicant: {weight: 65, sku: "Oslo", plan: "premium", active: true, openedAt: "2030-12-31", birthDate: "2024-02-29", parcels: [{price: 0, weight: 18, active: false, openedAt: "2025-03-20"}, {price: 0.5, weight: 1000000, active: false, openedAt: "2024-02-29"}]}}, {applicant: {active: true, adjusted: [65, 65, 2030], birthDate: "2024-02-29", exposure: "Oslo", grade: 2190, openedAt: "2030-12-31", parcels: [{active: false, capped: 18, openedAt: "2025-03-20", price: 0, review: "Oslo", weight: 18}, {active: false, capped: 1000000, openedAt: "2024-02-29", price: 0.5, review: "Oslo", weight: 1000000}], plan: "premium", points: ["65", "Oslo", "Oslo"], quota: [65], sku: "Oslo", tag: [1.5], total: [65, 65], weight: 65}}], + [{applicant: {weight: 0.5, sku: "DE", plan: "trial", active: false, openedAt: "2025-03-20", birthDate: "2000-01-01", parcels: [{price: 1, weight: 10, active: true, openedAt: "2025-03-20T10:15:30Z"}]}}, {applicant: {active: false, adjusted: [0.5], birthDate: "2000-01-01", exposure: "DE", grade: 78, openedAt: "2025-03-20", parcels: [{active: true, capped: 0.5, openedAt: "2025-03-20T10:15:30Z", price: 1, review: "DE", weight: 10}], plan: "trial", points: ["0.5"], quota: [0.5, 0.5, 0.5], sku: "DE", tag: [3, 0.5, 0.5, 1.5], total: [0.5], weight: 0.5}}], + [{applicant: {weight: 0.1, sku: "retail", plan: "premium", active: true, openedAt: "2025-03-20", birthDate: "2024-02-29", parcels: []}}, {applicant: {active: true, adjusted: [0.1, 2025], birthDate: "2024-02-29", exposure: "retail", grade: 78, openedAt: "2025-03-20", parcels: [], plan: "premium", points: ["0.1", "retail"], quota: [0.1], sku: "retail", tag: [1.5], total: [0.1], weight: 0.1}}], + ], +} + +// seed 334700 (attempt 0) +{ + name: "a 48: account/loans: 1 assertion, 2 expression, 1 match, 4 table; 2 root, 9 per-member, 2 top-level computed", + policy: { + models: {account: {weight: "number", tier: "string(gold|silver|bronze)", kind: "string(retail|corporate)", days: "number", active: "boolean", region: "string", loans: "loan[]"}, loan: {score: "number?", country: "string"}}, + blocks: [ + {assertion: "health", conditions: [["and", "account.weight == account.weight", 1]]}, + {table: "t2", inputs: ["account.active"], outputs: ["loan.rank"], rules: [ + ["", "account.days"], + ["true", "18"], + ["false", "account.weight"], + ["false", "account.days"], + ["false", ""], + ]}, + {table: "t3", inputs: ["account.active"], outputs: ["loan.review[]", "loan.capped"], rules: [ + ["", "(loan.rank ?? 0)", "loan.rank == null"], + ["true", "(loan.rank ?? 0)", "health"], + ["true", "max([account.weight, account.days])", "(health or health)"], + ["", "account.weight", "health"], + ["", "(loan.score ?? 0)", "some(account.loans, #.country in ['x', 'retail'])"], + ]}, + {expression: "account.bucket", value: "account.days"}, + {expression: "points", value: "account.kind in ['corporate', 'retail']"}, + {match: "account.margin", arms: [["not (account.active)", "account.region"], ["18 > account.weight", "account.region"], ["none(account.loans, 10 <= (#.rank ?? 0))", "((points ? account.region : account.region) + '-' + account.region)"], ["", "account.region"]]}, + {table: "t7", hit: "collect", inputs: ["account.margin"], outputs: ["loan.share", "loan.band", "loan.level"], rules: [ + ["", "account.margin", "(loan.rank ?? 0)", "loan.country"], + ["'A1', 'a'", "'none'", "18", "((loan.capped ?? false) ? 'VIP' : 'retail')"], + ["", "account.region", "(loan.rank ?? 0)", "loan.country"], + ["startsWith($, 'low')", "(loan.country + '-' + account.margin)", "(loan.score ?? 0)", "'retail'"], + ["startsWith($, 'Oslo')", "(account.margin + '-' + 'Oslo')", "1.5", "account.region"], + ]}, + {table: "t8", inputs: ["account.weight", "account.margin", "(account.weight + account.days)"], outputs: ["loan.summary", "loan.quota", "loan.net"], rules: [ + ["", "", "", "account.days", "", "(loan.score ?? 0) >= (loan.rank ?? 0)"], + ["!= 1000", "", "!= 18", "50", "", "account.active"], + ["", "'US', 'A1'", "!= 1000", "(loan.score ?? 0)", "18", "some(account.loans, contains(#.country, 'none'))"], + ["[0..175]", "", "100", "account.days", "account.weight", "points"], + ["<= 1.5", "", "250", "(loan.score ?? 0)", "", "health"], + ["", "'ok'", "", "account.bucket", "(loan.rank ?? 0)", "len(loan.country) > 1"], + ["", "", "", "account.weight", "round(account.weight, 2)", "points"], + ]}, + ], + }, + cases: [ + [{account: {weight: -1, tier: "silver", kind: "retail", days: 0, active: false, region: "A1", loans: [{score: null, country: "日本"}]}}, {account: {active: false, days: 0, kind: "retail", loans: [{band: [0, 18, 0], capped: false, country: "日本", level: ["日本", "retail", "日本"], net: true, quota: 18, rank: 0, review: [0, -1, 0], score: null, share: ["A1", "none", "A1"], summary: 0}], margin: "A1", region: "A1", tier: "silver", weight: -1}}], + [{account: {weight: 0.000001, tier: "silver", kind: "retail", days: 18, active: false, region: "none", loans: []}}, {account: {active: false, days: 18, kind: "retail", loans: [], margin: "none", region: "none", tier: "silver", weight: 0.000001}}], + [{account: {weight: 18, tier: "gold", kind: "retail", days: 1000, active: true, region: "Oslo", loans: [{score: -0, country: "A1"}]}}, {account: {active: true, days: 1000, kind: "retail", loans: [{band: [1000, 1000, 1.5], capped: false, country: "A1", level: ["A1", "A1", "Oslo"], net: false, quota: 18, rank: 1000, review: [1000, 1000, 1000, 18, 0], score: 0, share: ["Oslo", "Oslo", "Oslo-Oslo"], summary: 1000}], margin: "Oslo", region: "Oslo", tier: "gold", weight: 18}}], + [{account: {weight: -0.01, tier: "bronze", kind: "corporate", days: 2, active: false, region: "x", loans: []}}, {account: {active: false, days: 2, kind: "corporate", loans: [], margin: "x", region: "x", tier: "bronze", weight: -0.01}}], + [{account: {weight: 0, tier: "gold", kind: "corporate", days: 100, active: false, region: "Oslo", loans: [{score: 123456789.123, country: "none"}, {score: -1, country: "x-y"}, {score: 0, country: "DE"}, {score: 0.25, country: "gold"}, {score: 65, country: "DE"}]}}, {account: {active: false, days: 100, kind: "corporate", loans: [{band: [100, 100, 1.5], capped: false, country: "none", level: ["none", "none", "Oslo"], net: true, quota: 0, rank: 100, review: [100, 0, 123456789.123], score: 123456789.123, share: ["Oslo", "Oslo", "Oslo-Oslo"], summary: 100}, {band: [100, 100, 1.5], capped: false, country: "x-y", level: ["x-y", "x-y", "Oslo"], net: false, quota: 0, rank: 100, review: [100, 0, -1], score: -1, share: ["Oslo", "Oslo", "Oslo-Oslo"], summary: 100}, {band: [100, 100, 1.5], capped: false, country: "DE", level: ["DE", "DE", "Oslo"], net: false, quota: 0, rank: 100, review: [100, 0, 0], score: 0, share: ["Oslo", "Oslo", "Oslo-Oslo"], summary: 100}, {band: [100, 100, 1.5], capped: false, country: "gold", level: ["gold", "gold", "Oslo"], net: false, quota: 0, rank: 100, review: [100, 0, 0.25], score: 0.25, share: ["Oslo", "Oslo", "Oslo-Oslo"], summary: 100}, {band: [100, 100, 1.5], capped: false, country: "DE", level: ["DE", "DE", "Oslo"], net: false, quota: 0, rank: 100, review: [100, 0, 65], score: 65, share: ["Oslo", "Oslo", "Oslo-Oslo"], summary: 100}], margin: "Oslo", region: "Oslo", tier: "gold", weight: 0}}], + [{account: {weight: 1.5, tier: "gold", kind: "retail", days: 1000, active: true, region: "x", loans: [{score: null, country: "retail"}]}}, {account: {active: true, days: 1000, kind: "retail", loans: [{band: [1000, 1000], capped: false, country: "retail", level: ["retail", "retail"], net: false, quota: 1.5, rank: 1000, review: [1000, 1000, 1000, 1.5, 0], score: null, share: ["x", "x"], summary: 1000}], margin: "x", region: "x", tier: "gold", weight: 1.5}}], + [{account: {weight: 18, tier: "silver", kind: "retail", days: 0.1, active: true, region: "abc", loans: []}}, {account: {active: true, days: 0.1, kind: "retail", loans: [], margin: "abc-abc", region: "abc", tier: "silver", weight: 18}, points: true}], + [{account: {weight: 5, tier: "silver", kind: "retail", days: 7.25, active: true, region: "A1", loans: []}}, {account: {active: true, days: 7.25, kind: "retail", loans: [], margin: "A1", region: "A1", tier: "silver", weight: 5}}], + [{account: {weight: -0, tier: "gold", kind: "corporate", days: 5, active: true, region: "日本", loans: [{score: null, country: "O'Neil"}, {score: null, country: " pad "}, {score: null, country: "3.5"}, {score: 50, country: "-"}, {score: 1.5, country: "Oslo"}]}}, {account: {active: true, days: 5, kind: "corporate", loans: [{band: [5, 5], capped: false, country: "O'Neil", level: ["O'Neil", "O'Neil"], net: false, quota: 0, rank: 5, review: [5, 5, 5, 0, 0], score: null, share: ["日本", "日本"], summary: 5}, {band: [5, 5], capped: false, country: " pad ", level: [" pad ", " pad "], net: false, quota: 0, rank: 5, review: [5, 5, 5, 0, 0], score: null, share: ["日本", "日本"], summary: 5}, {band: [5, 5], capped: false, country: "3.5", level: ["3.5", "3.5"], net: false, quota: 0, rank: 5, review: [5, 5, 5, 0, 0], score: null, share: ["日本", "日本"], summary: 5}, {band: [5, 5], capped: false, country: "-", level: ["-", "-"], net: true, quota: 0, rank: 5, review: [5, 5, 5, 0, 50], score: 50, share: ["日本", "日本"], summary: 5}, {band: [5, 5], capped: false, country: "Oslo", level: ["Oslo", "Oslo"], net: false, quota: 0, rank: 5, review: [5, 5, 5, 0, 1.5], score: 1.5, share: ["日本", "日本"], summary: 5}], margin: "日本", region: "日本", tier: "gold", weight: 0}}], + [{account: {weight: 250, tier: "gold", kind: "retail", days: 99.99, active: false, region: "low", loans: []}}, {account: {active: false, days: 99.99, kind: "retail", loans: [], margin: "low", region: "low", tier: "gold", weight: 250}}], + [{account: {weight: 18, tier: "bronze", kind: "retail", days: 0.5, active: false, region: "US", loans: [{score: 1, country: "日本"}, {score: 0, country: "NL"}, {score: 18, country: "A1"}, {score: 0.000001, country: "US"}, {score: 0, country: "x"}]}}, {account: {active: false, days: 0.5, kind: "retail", loans: [{band: [0.5, 0.5], capped: false, country: "日本", level: ["日本", "日本"], net: true, quota: 18, rank: 0.5, review: [0.5, 18, 1], score: 1, share: ["US", "US"], summary: 0.5}, {band: [0.5, 0.5], capped: false, country: "NL", level: ["NL", "NL"], net: false, quota: 18, rank: 0.5, review: [0.5, 18, 0], score: 0, share: ["US", "US"], summary: 0.5}, {band: [0.5, 0.5], capped: false, country: "A1", level: ["A1", "A1"], net: true, quota: 18, rank: 0.5, review: [0.5, 18, 18], score: 18, share: ["US", "US"], summary: 0.5}, {band: [0.5, 0.5], capped: false, country: "US", level: ["US", "US"], net: false, quota: 18, rank: 0.5, review: [0.5, 18, 0.000001], score: 0.000001, share: ["US", "US"], summary: 0.5}, {band: [0.5, 0.5], capped: false, country: "x", level: ["x", "x"], net: false, quota: 18, rank: 0.5, review: [0.5, 18, 0], score: 0, share: ["US", "US"], summary: 0.5}], margin: "US", region: "US", tier: "bronze", weight: 18}}], + [{account: {weight: 99999999999999999999, tier: "gold", kind: "retail", days: 1, active: false, region: "retail", loans: []}}, {account: {active: false, days: 1, kind: "retail", loans: [], margin: "retail", region: "retail", tier: "gold", weight: 99999999999999999999}}], + [{account: {weight: 0, tier: "bronze", kind: "retail", days: 65, active: false, region: "3.5", loans: [{score: 0, country: "abc"}, {score: 18, country: " pad "}]}}, {account: {active: false, days: 65, kind: "retail", loans: [{band: [65, 65], capped: false, country: "abc", level: ["abc", "abc"], net: false, quota: 0, rank: 65, review: [65, 0, 0], score: 0, share: ["3.5", "3.5"], summary: 65}, {band: [65, 65], capped: false, country: " pad ", level: [" pad ", " pad "], net: false, quota: 0, rank: 65, review: [65, 0, 18], score: 18, share: ["3.5", "3.5"], summary: 65}], margin: "3.5", region: "3.5", tier: "bronze", weight: 0}}], + [{account: {weight: 0.25, tier: "gold", kind: "corporate", days: 18, active: true, region: "abc", loans: []}}, {account: {active: true, days: 18, kind: "corporate", loans: [], margin: "abc", region: "abc", tier: "gold", weight: 0.25}}], + [{account: {weight: 18, tier: "bronze", kind: "retail", days: 1000000, active: false, region: "A1", loans: [{score: 0.000001, country: "é ü"}, {score: 18, country: "3.5"}, {score: 0, country: "Zed"}, {score: 18, country: "Oslo"}, {score: 1e3, country: ""}]}}, {account: {active: false, days: 1000000, kind: "retail", loans: [{band: [1000000, 18, 1000000], capped: false, country: "é ü", level: ["é ü", "retail", "é ü"], net: false, quota: 18, rank: 1000000, review: [1000000, 18, 0.000001], score: 0.000001, share: ["A1", "none", "A1"], summary: 1000000}, {band: [1000000, 18, 1000000], capped: false, country: "3.5", level: ["3.5", "retail", "3.5"], net: false, quota: 18, rank: 1000000, review: [1000000, 18, 18], score: 18, share: ["A1", "none", "A1"], summary: 1000000}, {band: [1000000, 18, 1000000], capped: false, country: "Zed", level: ["Zed", "retail", "Zed"], net: false, quota: 18, rank: 1000000, review: [1000000, 18, 0], score: 0, share: ["A1", "none", "A1"], summary: 1000000}, {band: [1000000, 18, 1000000], capped: false, country: "Oslo", level: ["Oslo", "retail", "Oslo"], net: false, quota: 18, rank: 1000000, review: [1000000, 18, 18], score: 18, share: ["A1", "none", "A1"], summary: 1000000}, {band: [1000000, 18, 1000000], capped: false, country: "", level: ["", "retail", ""], net: false, quota: 18, rank: 1000000, review: [1000000, 18, 1000], score: 1000, share: ["A1", "none", "A1"], summary: 1000000}], margin: "A1", region: "A1", tier: "bronze", weight: 18}}], + ], +} + +// seed 334800 (attempt 0) +{ + name: "a 49: applicant/items: 4 assertion, 1 expression, 1 table; 4 root, 4 per-member, 0 top-level computed", + policy: { + models: {applicant: {price: "number?", kind: "string(retail|corporate)", years: "number", items: "item[]"}, item: {limit: "number", weight: "number?", since: "date"}}, + blocks: [ + {assertion: "item.rank", conditions: [["or", "applicant.price == null", 1], ["and", "item.since.diff(d('2025-01-01'), 'day') <= 0", 0], ["or", "abs((applicant.price ?? 0)) <= 1.5", 1], ["and", "(item.limit >= (item.weight ?? 0) and (applicant.price ?? 0) == item.limit)", 2]]}, + {assertion: "applicant.summary", conditions: [["or", "(applicant.price ?? 0) in [5..118]", 0], ["and", "18 >= applicant.years", 2], ["and", "applicant.kind in ['corporate', 'retail']", 2], ["or", "all(applicant.items, (#.weight ?? 0) in [12..36])", 0], ["or", "not ((applicant.price ?? 0) <= 2)", 0]]}, + {table: "t3", inputs: ["count(applicant.items, (#.rank or #.rank))"], outputs: ["item.quota", "item.weighted", "item.points"], rules: [ + ["10, 0", "applicant.years", "sum(map(applicant.items, (#.weight ?? 0)))", "(item.weight ?? 0)"], + ["", "item.limit", "applicant.years", "(item.weight ?? 0)"], + ]}, + {assertion: "applicant.discount", conditions: [["and", "applicant.price != null", 1]]}, + {assertion: "applicant.margin", conditions: ["none(applicant.items, (#.weight ?? 0) <= (#.quota ?? 0))", ["and", "none(applicant.items, (#.rank and #.rank))", 0], "applicant.kind != 'retail'"]}, + {expression: "applicant.surcharge", value: "len(applicant.items)"}, + ], + }, + cases: [ + [{applicant: {kind: "corporate", years: 0.000001, items: []}}, {applicant: {discount: false, items: [], kind: "corporate", margin: true, summary: true, surcharge: 0, years: 0.000001}}], + [{applicant: {price: null, kind: "corporate", years: 1000000, items: [{limit: -500, weight: null, since: "2025-03-20"}]}}, {applicant: {discount: false, items: [{limit: -500, points: 0, quota: -500, rank: true, since: "2025-03-20", weight: null, weighted: 1000000}], kind: "corporate", margin: false, price: null, summary: false, surcharge: 1, years: 1000000}}], + [{applicant: {price: 1000000, kind: "corporate", years: 100, items: [{limit: 18, weight: -0.01, since: "2024-01-01"}, {limit: 1.5, weight: -1, since: "2025-03-20"}, {limit: 1000, weight: 1.5, since: "2025-03-20"}]}}, {applicant: {discount: true, items: [{limit: 18, points: -0.01, quota: 100, rank: false, since: "2024-01-01", weight: -0.01, weighted: 0.49}, {limit: 1.5, points: -1, quota: 100, rank: false, since: "2025-03-20", weight: -1, weighted: 0.49}, {limit: 1000, points: 1.5, quota: 100, rank: false, since: "2025-03-20", weight: 1.5, weighted: 0.49}], kind: "corporate", margin: false, price: 1000000, summary: true, surcharge: 3, years: 100}}], + [{applicant: {price: 0.5, kind: "retail", years: 7.25, items: []}}, {applicant: {discount: true, items: [], kind: "retail", margin: false, price: 0.5, summary: true, surcharge: 0, years: 7.25}}], + [{applicant: {price: 0.5, kind: "corporate", years: 2, items: [], extraField: {nested: true}}}, {applicant: {discount: true, extraField: {nested: true}, items: [], kind: "corporate", margin: true, price: 0.5, summary: true, surcharge: 0, years: 2}}], + [{applicant: {price: 99.99, kind: "corporate", years: 0.25, items: [{limit: 10, weight: 99999999999999999999, since: "2030-12-31"}]}}, {applicant: {discount: true, items: [{limit: 10, points: 99999999999999999999, quota: 0.25, rank: false, since: "2030-12-31", weight: 99999999999999999999, weighted: 99999999999999999999}], kind: "corporate", margin: true, price: 99.99, summary: true, surcharge: 1, years: 0.25}}], + [{applicant: {price: 0.5, kind: "corporate", years: -0, items: [{limit: 1, weight: 7.25, since: "2024-01-01"}, {limit: 65, weight: 5, since: "2024-02-29"}]}}, {applicant: {discount: true, items: [{limit: 1, points: 7.25, quota: 1, rank: true, since: "2024-01-01", weight: 7.25, weighted: 0}, {limit: 65, points: 5, quota: 65, rank: true, since: "2024-02-29", weight: 5, weighted: 0}], kind: "corporate", margin: false, price: 0.5, summary: false, surcharge: 2, years: 0}}], + [{applicant: {price: 1000, kind: "retail", years: 2.50, items: [{limit: 1000, weight: 7.25, since: "2030-12-31"}, {limit: 0.000001, weight: -0.5, since: "2000-01-01"}], extraField: "x"}}, {applicant: {discount: true, extraField: "x", items: [{limit: 1000, points: 7.25, quota: 2.50, rank: false, since: "2030-12-31", weight: 7.25, weighted: 6.75}, {limit: 0.000001, points: -0.5, quota: 2.50, rank: false, since: "2000-01-01", weight: -0.5, weighted: 6.75}], kind: "retail", margin: false, price: 1000, summary: true, surcharge: 2, years: 2.50}}], + [{applicant: {price: 18, kind: "corporate", years: 65, items: [{limit: null, weight: 7.25, since: "2024-01-01"}, {limit: 2, weight: 1, since: "2024-02-29"}, {limit: 0.000001, weight: 0, since: "2030-12-31"}, {limit: 1, weight: 1000000, since: "2030-12-31"}]}}, "!error: ExpressionFailed"], + [{applicant: {price: -0.01, kind: "corporate", years: 123456789.123, items: [{limit: 18, weight: 2, since: "2025-03-20T10:15:30Z"}]}}, {applicant: {discount: true, items: [{limit: 18, points: 2, quota: 123456789.123, rank: false, since: "2025-03-20T10:15:30Z", weight: 2, weighted: 2}], kind: "corporate", margin: false, price: -0.01, summary: false, surcharge: 1, years: 123456789.123}}], + [{applicant: {price: 1, kind: "retail", years: 1000, items: [{limit: -500, since: "2030-12-31"}, {limit: 250, weight: 2.50, since: "2030-12-31"}, {limit: 2.50, weight: 1000000, since: "2024-02-29"}, {limit: -500, weight: 290, since: "2025-03-20T10:15:30Z"}, {limit: 140, weight: 1e3, since: "2030-12-31"}]}}, {applicant: {discount: true, items: [{limit: -500, points: 0, quota: -500, rank: false, since: "2030-12-31", weighted: 1000}, {limit: 250, points: 2.50, quota: 250, rank: false, since: "2030-12-31", weight: 2.50, weighted: 1000}, {limit: 2.50, points: 1000000, quota: 2.50, rank: true, since: "2024-02-29", weight: 1000000, weighted: 1000}, {limit: -500, points: 290, quota: -500, rank: false, since: "2025-03-20T10:15:30Z", weight: 290, weighted: 1000}, {limit: 140, points: 1000, quota: 140, rank: false, since: "2030-12-31", weight: 1000, weighted: 1000}], kind: "retail", margin: false, price: 1, summary: false, surcharge: 5, years: 1000}}], + [{applicant: {price: null, kind: "corporate", years: 18, items: [{limit: 65, since: "2025-03-20"}]}}, {applicant: {discount: false, items: [{limit: 65, points: 0, quota: 65, rank: true, since: "2025-03-20", weighted: 18}], kind: "corporate", margin: false, price: null, summary: false, surcharge: 1, years: 18}}], + [{applicant: {price: 2.50, kind: "retail", years: 0, items: [{limit: 0.5, weight: -0, since: "2025-03-20"}, {limit: 0.25, weight: 0, since: "2030-12-31"}, {limit: 100, weight: 2, since: "2025-03-20"}]}}, {applicant: {discount: true, items: [{limit: 0.5, points: 0, quota: 0, rank: false, since: "2025-03-20", weight: 0, weighted: 2}, {limit: 0.25, points: 0, quota: 0, rank: false, since: "2030-12-31", weight: 0, weighted: 2}, {limit: 100, points: 2, quota: 0, rank: false, since: "2025-03-20", weight: 2, weighted: 2}], kind: "retail", margin: false, price: 2.50, summary: true, surcharge: 3, years: 0}}], + [{applicant: {price: 0.000001, kind: "retail", years: 2, items: [{limit: 10, weight: 0, since: "2025-03-20"}, {limit: 0.25, weight: -0.5, since: "2024-01-01"}, {limit: 7.25, weight: 1, since: "1990-06-15"}, {limit: 1000, weight: 10, since: "2030-12-31"}, {limit: 1.5, weight: 123456789.123, since: "2024-02-29"}]}}, {applicant: {discount: true, items: [{limit: 10, points: 0, quota: 10, rank: false, since: "2025-03-20", weight: 0, weighted: 2}, {limit: 0.25, points: -0.5, quota: 0.25, rank: true, since: "2024-01-01", weight: -0.5, weighted: 2}, {limit: 7.25, points: 1, quota: 7.25, rank: true, since: "1990-06-15", weight: 1, weighted: 2}, {limit: 1000, points: 10, quota: 1000, rank: false, since: "2030-12-31", weight: 10, weighted: 2}, {limit: 1.5, points: 123456789.123, quota: 1.5, rank: true, since: "2024-02-29", weight: 123456789.123, weighted: 2}], kind: "retail", margin: false, price: 0.000001, summary: false, surcharge: 5, years: 2}}], + [{applicant: {price: 2.50, kind: "retail", years: 7.25, items: [{limit: 408, weight: 2, since: "2025-03-20T10:15:30Z"}, {limit: 0.1, weight: 0.000001, since: "2025-03-20"}, {limit: 0, weight: 306, since: "2024-02-29"}, {limit: 0.1, weight: 10, since: "2000-01-01"}, {limit: 2.50, weight: 1.5, since: "2024-02-29"}]}}, {applicant: {discount: true, items: [{limit: 408, points: 2, quota: 408, rank: false, since: "2025-03-20T10:15:30Z", weight: 2, weighted: 7.25}, {limit: 0.1, points: 0.000001, quota: 0.1, rank: false, since: "2025-03-20", weight: 0.000001, weighted: 7.25}, {limit: 0, points: 306, quota: 0, rank: false, since: "2024-02-29", weight: 306, weighted: 7.25}, {limit: 0.1, points: 10, quota: 0.1, rank: false, since: "2000-01-01", weight: 10, weighted: 7.25}, {limit: 2.50, points: 1.5, quota: 2.50, rank: true, since: "2024-02-29", weight: 1.5, weighted: 7.25}], kind: "retail", margin: false, price: 2.50, summary: true, surcharge: 5, years: 7.25}}], + [{applicant: {price: 1e3, kind: "corporate", years: 1, items: [{limit: 2, weight: 2, since: "2024-01-01"}, {limit: 1000, since: "2024-01-01"}, {limit: 7.25, weight: 2, since: "1990-06-15"}]}}, {applicant: {discount: true, items: [{limit: 2, points: 2, quota: 2, rank: false, since: "2024-01-01", weight: 2, weighted: 1}, {limit: 1000, points: 0, quota: 1000, rank: true, since: "2024-01-01", weighted: 1}, {limit: 7.25, points: 2, quota: 7.25, rank: false, since: "1990-06-15", weight: 2, weighted: 1}], kind: "corporate", margin: false, price: 1000, summary: true, surcharge: 3, years: 1}}], + [{applicant: {price: -0.01, kind: "retail", years: 1e3, items: []}}, {applicant: {discount: true, items: [], kind: "retail", margin: false, price: -0.01, summary: false, surcharge: 0, years: 1000}}], + [{applicant: {price: 2, kind: "corporate", years: 0, items: []}}, {applicant: {discount: true, items: [], kind: "corporate", margin: true, price: 2, summary: true, surcharge: 0, years: 0}}], + [{applicant: {price: 2.50, kind: "corporate", years: 1000000, items: []}}, {applicant: {discount: true, items: [], kind: "corporate", margin: true, price: 2.50, summary: true, surcharge: 0, years: 1000000}}], + [{applicant: {price: 2, kind: "retail", years: 10, items: [{limit: 2, weight: 2, since: "1990-06-15"}, {limit: -0.01, weight: -0.5, since: "2030-12-31"}, {limit: 0.5, weight: 10, since: "1990-06-15"}, {limit: 1000, weight: -0, since: "2025-03-20T10:15:30Z"}]}}, {applicant: {discount: true, items: [{limit: 2, points: 2, quota: 2, rank: true, since: "1990-06-15", weight: 2, weighted: 10}, {limit: -0.01, points: -0.5, quota: -0.01, rank: false, since: "2030-12-31", weight: -0.5, weighted: 10}, {limit: 0.5, points: 10, quota: 0.5, rank: false, since: "1990-06-15", weight: 10, weighted: 10}, {limit: 1000, points: 0, quota: 1000, rank: false, since: "2025-03-20T10:15:30Z", weight: 0, weighted: 10}], kind: "retail", margin: false, price: 2, summary: false, surcharge: 4, years: 10}}], + [{applicant: {price: 0, kind: "retail", years: 5, items: [{limit: -0.01, weight: true, since: "1990-06-15"}, {limit: 250, weight: -0, since: "2030-12-31"}, {limit: -0, weight: 1, since: "2024-02-29"}, {limit: 2.50, weight: 1e3, since: "1990-06-15"}, {limit: 18, weight: 184, since: "1990-06-15"}]}}, "!error: InputValidationFailed"], + [{applicant: {price: 2, kind: "retail", years: 2, items: [{limit: 10, since: "2030-12-31"}, {limit: 2, weight: null, since: "2025-03-20T10:15:30Z"}]}}, {applicant: {discount: true, items: [{limit: 10, points: 0, quota: 2, rank: false, since: "2030-12-31", weighted: 0}, {limit: 2, points: 0, quota: 2, rank: false, since: "2025-03-20T10:15:30Z", weight: null, weighted: 0}], kind: "retail", margin: false, price: 2, summary: false, surcharge: 2, years: 2}}], + [{applicant: {price: 1000000, kind: "corporate", years: 65, items: [], extraField: "x"}}, {applicant: {discount: true, extraField: "x", items: [], kind: "corporate", margin: true, price: 1000000, summary: true, surcharge: 0, years: 65}}], + [{applicant: {price: 2, kind: "retail", years: true, items: [{limit: -1, weight: -0, since: "2024-02-29"}, {limit: 100, weight: 1e3, since: "2025-03-20"}, {limit: 0, weight: 10, since: "1990-06-15"}]}}, "!error: InputValidationFailed"], + [{applicant: {price: 250, kind: "retail", years: -0.5, items: []}}, {applicant: {discount: true, items: [], kind: "retail", margin: false, price: 250, summary: true, surcharge: 0, years: -0.5}}], + [{applicant: {price: 99.99, kind: "corporate", years: 10, items: [], extraField: {nested: true}}}, {applicant: {discount: true, extraField: {nested: true}, items: [], kind: "corporate", margin: true, price: 99.99, summary: true, surcharge: 0, years: 10}}], + [{applicant: {price: -0.01, kind: "retail", years: 2, items: [{limit: 1000, weight: 5, since: "1990-06-15"}, {limit: 18, weight: 0, since: "2030-12-31"}, {limit: 1000000, weight: 1, since: "2025-03-20T10:15:30Z"}, {limit: 0.25, weight: 0.25, since: "2000-01-01"}], extraField: 1}}, {applicant: {discount: true, extraField: 1, items: [{limit: 1000, points: 5, quota: 1000, rank: true, since: "1990-06-15", weight: 5, weighted: 2}, {limit: 18, points: 0, quota: 18, rank: false, since: "2030-12-31", weight: 0, weighted: 2}, {limit: 1000000, points: 1, quota: 1000000, rank: false, since: "2025-03-20T10:15:30Z", weight: 1, weighted: 2}, {limit: 0.25, points: 0.25, quota: 0.25, rank: true, since: "2000-01-01", weight: 0.25, weighted: 2}], kind: "retail", margin: false, price: -0.01, summary: false, surcharge: 4, years: 2}}], + [{applicant: {price: true, kind: "retail", years: 10, items: [{limit: 18, weight: 1000, since: "2024-01-01"}, {limit: 0.1, weight: -0.5, since: "2024-01-01"}, {limit: -0.5, weight: 5, since: "2024-01-01"}, {limit: 0, weight: 0, since: "2025-03-20T10:15:30Z"}, {limit: 2, weight: 100, since: "2030-12-31"}]}}, "!error: InputValidationFailed"], + [{applicant: {price: 0.5, kind: "retail", years: 5, items: [{limit: -0.5, weight: -1, since: "2024-02-29"}, {limit: 1.5, weight: 18, since: "2025-03-20T10:15:30Z"}], extraField: "x"}}, {applicant: {discount: true, extraField: "x", items: [{limit: -0.5, points: -1, quota: -0.5, rank: true, since: "2024-02-29", weight: -1, weighted: 5}, {limit: 1.5, points: 18, quota: 1.5, rank: false, since: "2025-03-20T10:15:30Z", weight: 18, weighted: 5}], kind: "retail", margin: false, price: 0.5, summary: false, surcharge: 2, years: 5}}], + [{applicant: {price: 5, kind: "retail", years: -0, items: []}}, {applicant: {discount: true, items: [], kind: "retail", margin: false, price: 5, summary: true, surcharge: 0, years: 0}}], + ], +} + +// seed 334900 (attempt 0) +{ + name: "a 50: customer/vehicles: 1 assertion, 2 expression, 2 table; 2 root, 5 per-member, 1 top-level computed", + policy: { + models: {customer: {amount: "number", name: "string", weight: "number", status: "string(open|closed|pending)?", vehicles: "vehicle[]"}, vehicle: {price: "number", qty: "number", verified: "boolean?", weight: "number"}}, + blocks: [ + {assertion: "customer.quota", conditions: [["and", "not (customer.segment > 50)", 1], ["and", "(1 <= 1000 or customer.segment <= 0.5)", 1], ["or", "((customer.amount > 50 or customer.weight > 1000) and customer.status == null)", 1]]}, + {table: "t1", inputs: ["vehicle.weight", "customer.amount"], outputs: ["vehicle.risk", "vehicle.surcharge"], rules: [ + ["", "", "customer.amount", "customer.amount"], + ["", "!= 100", "len(customer.name)", "customer.weight"], + ["", "", "max([vehicle.price, vehicle.weight])", "(vehicle.weight) / (abs(customer.amount) + 1)"], + ["< 18", "!= 10", "vehicle.weight", "vehicle.weight"], + ["[10..408]", "[0.25..289.25]", "(vehicle.price + vehicle.weight)", "(customer.amount) / (abs(customer.weight) + 1)"], + ["100, 0.25", "", "(max(map(customer.vehicles, 0.25)) ?? 0)", "vehicle.price"], + ["250", "> 0", "0.5", ""], + ]}, + {expression: "customer.segment", value: "(len(customer.vehicles) + len(customer.name))"}, + {table: "t2", inputs: ["customer.amount", "vehicle.weight"], outputs: ["vehicle.total", "vehicle.band", "vehicle.margin"], rules: [ + ["1, 2", "", "(vehicle.verified ?? false)", "", "customer.name"], + [">= 100", "", "customer.amount <= (vehicle.risk ?? 0)", "(vehicle.verified ?? false)", "customer.name"], + ["50, 5", "[3..476]", "(vehicle.verified ?? false)", "(vehicle.verified ?? false)", "'A1'"], + ["", "0", "(vehicle.verified ?? false)", "", "'US'"], + ["[1000..1412]", ">= 50", "(vehicle.verified ?? false)", "(vehicle.risk ?? 0) == vehicle.price", "'ok'"], + ["> 0", "< 2", "(vehicle.verified ?? false)", "", "customer.name"], + ]}, + {expression: "grade", value: "((customer.quota ? customer.amount : customer.amount) * (customer.quota ? customer.segment : customer.segment))"}, + ], + }, + cases: [ + [{customer: {amount: 5, name: "NL", weight: 100, vehicles: [{price: 2, qty: 250, verified: false, weight: 0.25}]}}, {customer: {amount: 5, name: "NL", quota: false, segment: 3, vehicles: [{band: null, margin: "NL", price: 2, qty: 250, risk: 5, surcharge: 5, total: false, verified: false, weight: 0.25}], weight: 100}, grade: 15}], + [{customer: {amount: -500, name: "a", weight: 18, status: "open", vehicles: [{price: -0, qty: 18, weight: 0.5}, {price: 10, qty: 0.25, weight: 1000}, {price: 0, qty: 0, weight: 100}, {price: 0.5, qty: 10, verified: true, weight: 0.5}]}}, {customer: {amount: -500, name: "a", quota: false, segment: 5, status: "open", vehicles: [{band: null, margin: null, price: 0, qty: 18, risk: -500, surcharge: -500, total: null, weight: 0.5}, {band: null, margin: null, price: 10, qty: 0.25, risk: -500, surcharge: -500, total: null, weight: 1000}, {band: null, margin: null, price: 0, qty: 0, risk: -500, surcharge: -500, total: null, weight: 100}, {band: null, margin: null, price: 0.5, qty: 10, risk: -500, surcharge: -500, total: null, verified: true, weight: 0.5}], weight: 18}, grade: -2500}], + [{customer: {amount: 2.50, name: "-", weight: 100, status: "pending", vehicles: []}}, {customer: {amount: 2.50, name: "-", quota: false, segment: 1, status: "pending", vehicles: [], weight: 100}, grade: 2.50}], + [{customer: {amount: 5, name: "gold", weight: 100, status: null, vehicles: [{price: 18, qty: -0.5, verified: null, weight: 2}]}}, {customer: {amount: 5, name: "gold", quota: false, segment: 5, status: null, vehicles: [{band: null, margin: null, price: 18, qty: -0.5, risk: 5, surcharge: 5, total: null, verified: null, weight: 2}], weight: 100}, grade: 25}], + [{customer: {amount: 100, name: "gold", weight: 10, status: "open", vehicles: [{price: 5, qty: 0.25, verified: true, weight: -1}, {price: 1000, qty: 5, verified: false, weight: 2}]}}, {customer: {amount: 100, name: "gold", quota: false, segment: 6, status: "open", vehicles: [{band: true, margin: "gold", price: 5, qty: 0.25, risk: 100, surcharge: 100, total: true, verified: true, weight: -1}, {band: false, margin: "gold", price: 1000, qty: 5, risk: 100, surcharge: 100, total: true, verified: false, weight: 2}], weight: 10}, grade: 600}], + [{customer: {amount: 0.5, name: "retail", weight: 100, status: "open", vehicles: [{price: 0.5, qty: 0, verified: true, weight: 5}, {price: 2, qty: 50, verified: true, weight: 2}], extraField: 1}}, {customer: {amount: 0.5, extraField: 1, name: "retail", quota: false, segment: 8, status: "open", vehicles: [{band: null, margin: null, price: 0.5, qty: 0, risk: 0.5, surcharge: 0.5, total: null, verified: true, weight: 5}, {band: null, margin: null, price: 2, qty: 50, risk: 0.5, surcharge: 0.5, total: null, verified: true, weight: 2}], weight: 100}, grade: 4.0}], + [{customer: {amount: 1, name: "a", weight: 1000, status: "open", vehicles: [{price: 0.5, qty: -0.01, verified: false, weight: 250}, {price: -500, qty: 250, verified: true, weight: 1000000}, {price: 2.50, qty: 100, verified: false, weight: 1000000}, {price: 50, qty: 18, verified: true, weight: 100}, {price: 0.5, qty: 0.5, verified: true, weight: 5}]}}, {customer: {amount: 1, name: "a", quota: false, segment: 6, status: "open", vehicles: [{band: null, margin: "a", price: 0.5, qty: -0.01, risk: 1, surcharge: 1, total: false, verified: false, weight: 250}, {band: null, margin: "a", price: -500, qty: 250, risk: 1, surcharge: 1, total: true, verified: true, weight: 1000000}, {band: null, margin: "a", price: 2.50, qty: 100, risk: 1, surcharge: 1, total: false, verified: false, weight: 1000000}, {band: null, margin: "a", price: 50, qty: 18, risk: 1, surcharge: 1, total: true, verified: true, weight: 100}, {band: null, margin: "a", price: 0.5, qty: 0.5, risk: 1, surcharge: 1, total: true, verified: true, weight: 5}], weight: 1000}, grade: 6}], + [{customer: {amount: 18, name: "Oslo", weight: 1000, status: "open", vehicles: [{price: 99.99, qty: 1000, verified: true, weight: 0.25}, {price: 50, qty: 0.5, verified: false, weight: 123456789.123}, {price: 0, qty: -0.01, verified: true, weight: 0.5}], extraField: 1}}, {customer: {amount: 18, extraField: 1, name: "Oslo", quota: false, segment: 7, status: "open", vehicles: [{band: null, margin: "Oslo", price: 99.99, qty: 1000, risk: 18, surcharge: 18, total: true, verified: true, weight: 0.25}, {band: null, margin: null, price: 50, qty: 0.5, risk: 18, surcharge: 18, total: null, verified: false, weight: 123456789.123}, {band: null, margin: "Oslo", price: 0, qty: -0.01, risk: 18, surcharge: 18, total: true, verified: true, weight: 0.5}], weight: 1000}, grade: 126}], + [{customer: {amount: 1000, name: " pad ", weight: 1000, status: "closed", vehicles: [{price: 5, qty: 100, verified: false, weight: 10}, {price: 50, qty: -0.01, verified: false, weight: 0}, {price: 0.25, qty: -0, verified: true, weight: 65}, {price: 2.50, qty: 0.25, verified: false, weight: 5}]}}, {customer: {amount: 1000, name: " pad ", quota: false, segment: 10, status: "closed", vehicles: [{band: false, margin: " pad ", price: 5, qty: 100, risk: 1000, surcharge: 1000, total: true, verified: false, weight: 10}, {band: false, margin: " pad ", price: 50, qty: -0.01, risk: 1000, surcharge: 1000, total: true, verified: false, weight: 0}, {band: true, margin: " pad ", price: 0.25, qty: 0, risk: 1000, surcharge: 1000, total: true, verified: true, weight: 65}, {band: false, margin: " pad ", price: 2.50, qty: 0.25, risk: 1000, surcharge: 1000, total: true, verified: false, weight: 5}], weight: 1000}, grade: 10000}], + [{customer: {amount: 2, name: "retail", weight: 0.5, vehicles: [{price: 7.25, qty: 5, weight: 10}, {price: 0.5, qty: 10, weight: 5}, {price: 10, qty: 2.50, verified: null, weight: 0}, {price: 0.5, qty: -0, verified: true, weight: 100}]}}, {customer: {amount: 2, name: "retail", quota: false, segment: 10, vehicles: [{band: null, margin: "retail", price: 7.25, qty: 5, risk: 2, surcharge: 2, total: false, weight: 10}, {band: null, margin: "retail", price: 0.5, qty: 10, risk: 2, surcharge: 2, total: false, weight: 5}, {band: null, margin: "retail", price: 10, qty: 2.50, risk: 2, surcharge: 2, total: false, verified: null, weight: 0}, {band: null, margin: "retail", price: 0.5, qty: 0, risk: 2, surcharge: 2, total: true, verified: true, weight: 100}], weight: 0.5}, grade: 20}], + [{customer: {amount: -0.5, name: "retail", weight: 0.25, status: "open", vehicles: [{qty: 99999999999999999999, verified: false, weight: 5}, {price: 123456789.123, qty: 2.50, verified: true, weight: 100}, {price: 351, qty: 99999999999999999999, verified: false, weight: 1000}]}}, {customer: {amount: -0.5, name: "retail", quota: false, segment: 9, status: "open", vehicles: [{band: null, margin: null, qty: 99999999999999999999, risk: -0.5, surcharge: -0.5, total: null, verified: false, weight: 5}, {band: null, margin: null, price: 123456789.123, qty: 2.50, risk: -0.5, surcharge: -0.5, total: null, verified: true, weight: 100}, {band: null, margin: null, price: 351, qty: 99999999999999999999, risk: -0.5, surcharge: -0.5, total: null, verified: false, weight: 1000}], weight: 0.25}, grade: -4.5}], + [{customer: {amount: -500, name: "12", weight: 5, vehicles: [{price: -1, qty: 250, verified: null, weight: 18}, {price: 250, qty: 1, verified: null, weight: -1}]}}, {customer: {amount: -500, name: "12", quota: false, segment: 4, vehicles: [{band: null, margin: null, price: -1, qty: 250, risk: -500, surcharge: -500, total: null, verified: null, weight: 18}, {band: null, margin: null, price: 250, qty: 1, risk: -500, surcharge: -500, total: null, verified: null, weight: -1}], weight: 5}, grade: -2000}], + [{customer: {amount: 10, name: "VIP", weight: 2, status: "open", vehicles: []}}, {customer: {amount: 10, name: "VIP", quota: false, segment: 3, status: "open", vehicles: [], weight: 2}, grade: 30}], + [{customer: {amount: 5, name: "US", weight: 250, status: "closed", vehicles: [{price: 100, qty: 0.5, verified: true, weight: -0.01}]}}, {customer: {amount: 5, name: "US", quota: false, segment: 3, status: "closed", vehicles: [{band: null, margin: "US", price: 100, qty: 0.5, risk: 5, surcharge: 5, total: true, verified: true, weight: -0.01}], weight: 250}, grade: 15}], + [{customer: {amount: 0.25, name: "-", weight: 0.5, status: "closed", vehicles: [{price: 0.25, qty: 0, verified: true, weight: 0.000001}, {price: 100, qty: 5, verified: false, weight: 100}, {price: -0.5, qty: 0, verified: true, weight: 50}, {price: 50, qty: 2, verified: true, weight: 18}, {price: 50, qty: 3, verified: true, weight: -0.01}]}}, {customer: {amount: 0.25, name: "-", quota: false, segment: 6, status: "closed", vehicles: [{band: null, margin: "-", price: 0.25, qty: 0, risk: 0.25, surcharge: 0.25, total: true, verified: true, weight: 0.000001}, {band: null, margin: null, price: 100, qty: 5, risk: 0.25, surcharge: 0.25, total: null, verified: false, weight: 100}, {band: null, margin: null, price: -0.5, qty: 0, risk: 0.25, surcharge: 0.25, total: null, verified: true, weight: 50}, {band: null, margin: null, price: 50, qty: 2, risk: 0.25, surcharge: 0.25, total: null, verified: true, weight: 18}, {band: null, margin: "-", price: 50, qty: 3, risk: 0.25, surcharge: 0.25, total: true, verified: true, weight: -0.01}], weight: 0.5}, grade: 1.50}], + [{customer: {amount: 50, name: "US", weight: 0.25, status: null, vehicles: [{price: 50, qty: 5, verified: true, weight: 3}, {price: 1e3, qty: 0.5, weight: 0.25}]}}, {customer: {amount: 50, name: "US", quota: false, segment: 4, status: null, vehicles: [{band: true, margin: "A1", price: 50, qty: 5, risk: 50, surcharge: 50, total: true, verified: true, weight: 3}, {band: null, margin: "US", price: 1000, qty: 0.5, risk: 50, surcharge: 50, total: false, weight: 0.25}], weight: 0.25}, grade: 200}], + [{customer: {amount: 65, name: "é ü", weight: 2.50, vehicles: [{price: 18, qty: 50, verified: false, weight: 0.5}, {price: 3, qty: 0, verified: false, weight: 10}, {price: 0.25, qty: 0.5, verified: true, weight: 100}, {price: 1000, qty: 0.5, verified: null, weight: 1000000}, {price: 1000, qty: 100, verified: null, weight: 10}]}}, {customer: {amount: 65, name: "é ü", quota: true, segment: 10, vehicles: [{band: null, margin: "é ü", price: 18, qty: 50, risk: 65, surcharge: 65, total: false, verified: false, weight: 0.5}, {band: null, margin: null, price: 3, qty: 0, risk: 65, surcharge: 65, total: null, verified: false, weight: 10}, {band: null, margin: null, price: 0.25, qty: 0.5, risk: 65, surcharge: 65, total: null, verified: true, weight: 100}, {band: null, margin: null, price: 1000, qty: 0.5, risk: 65, surcharge: 65, total: null, verified: null, weight: 1000000}, {band: null, margin: null, price: 1000, qty: 100, risk: 65, surcharge: 65, total: null, verified: null, weight: 10}], weight: 2.50}, grade: 650}], + [{customer: {amount: 100, name: "Zed", weight: 0.5, vehicles: [{price: -0.5, qty: 0.25, verified: false, weight: 0}]}}, {customer: {amount: 100, name: "Zed", quota: true, segment: 4, vehicles: [{band: false, margin: "Zed", price: -0.5, qty: 0.25, risk: 100, surcharge: 100, total: true, verified: false, weight: 0}], weight: 0.5}, grade: 400}], + ], +} + +// seed 335000 (attempt 0) +{ + name: "a 51: customer/vehicles: 3 expression, 3 match, 1 table; 2 root, 4 per-member, 1 top-level computed", + policy: { + models: {customer: {limit: "number?", dueDate: "date", days: "number?", verified: "boolean", kind: "string(retail|corporate)?", years: "number", vehicles: "vehicle[]?"}, vehicle: {age: "number?", since: "date", region: "string?", flagged: "boolean?"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {match: "decision", arms: [["contains(string(cap), 'Oslo')", "(customer.verified or customer.verified)"], ["customer.limit == null", "customer.years in [22..82]"], ["", "(customer.kind ?? '') in ['corporate', 'retail']"]]}, + {expression: "vehicle.penalty", value: "vehicle.since"}, + {match: "vehicle.surcharge", arms: [["customer.kind != null", "((vehicle.region ?? '') + '-' + (vehicle.region ?? ''))"], ["", "(vehicle.region ?? '')"]]}, + {expression: "vehicle.health", value: "customer.dueDate"}, + {table: "t5", inputs: ["customer.dueDate"], outputs: ["customer.tag"], rules: [ + ["", "(customer.limit ?? 0)"], + ["", "(customer.days ?? 0)"], + ["", "(customer.days ?? 0)"], + ["> d('2024-01-01')", "customer.total"], + ["", "(customer.days ?? 0)"], + ]}, + {match: "vehicle.flag", arms: [["(some((customer.vehicles ?? []), (#.age ?? 0) < 18) and some((customer.vehicles ?? []), (#.age ?? 0) > (#.age ?? 0)))", "cap"], ["not (customer.verified)", "((decision ? 2 : (customer.limit ?? 0)) + (avg(map((customer.vehicles ?? []), (#.age ?? 0))) ?? 0))"], ["(vehicle.region ?? '') in ['gold', 'VIP']", "customer.total"], ["(customer.verified and customer.verified)", "(min(map((customer.vehicles ?? []), 50)) ?? 0)"], ["", "cap"]]}, + {expression: "customer.total", value: "customer.dueDate.diff(d('2025-01-01'), 'day')"}, + ], + }, + cases: [ + [{cap: 1, customer: {limit: -1, dueDate: "2025-03-20T10:15:30Z", days: 7.25, verified: true, kind: "retail", years: 0.5, vehicles: [{age: -1, since: "2024-01-01", region: "-", flagged: 1}, {age: 0, since: "2030-12-31", region: "DE", flagged: false}, {age: -0, since: "2024-01-01", region: "", flagged: false}, {age: 1000, since: "2024-01-01", region: "Oslo", flagged: true}, {age: 50, since: "2025-03-20", region: "gold", flagged: false}]}}, "!error: InputValidationFailed"], + [{cap: -2, customer: {dueDate: "2030-12-31", verified: false, years: 2.50}}, {cap: -2, customer: {dueDate: "2030-12-31", tag: 0, verified: false, years: 2.50}}], + [{cap: 0, customer: {limit: 0, dueDate: "2024-01-01", days: 1000000, verified: true, kind: "retail", years: 250, vehicles: [{since: "2025-03-20", flagged: true}, {age: 99999999999999999999, since: "2025-03-20T10:15:30Z", region: null, flagged: true}, {since: "2025-03-20T10:15:30Z", flagged: null}, {age: 2, since: "2025-03-20", flagged: true}, {age: 0.5, since: "2000-01-01", flagged: true}]}}, {cap: 0, customer: {days: 1000000, dueDate: "2024-01-01", kind: "retail", limit: 0, tag: 0, vehicles: [{flag: 50, flagged: true, health: "2024-01-01", penalty: "2025-03-20", since: "2025-03-20", surcharge: "-"}, {age: 99999999999999999999, flag: 50, flagged: true, health: "2024-01-01", penalty: "2025-03-20T10:15:30Z", region: null, since: "2025-03-20T10:15:30Z", surcharge: "-"}, {flag: 50, flagged: null, health: "2024-01-01", penalty: "2025-03-20T10:15:30Z", since: "2025-03-20T10:15:30Z", surcharge: "-"}, {age: 2, flag: 50, flagged: true, health: "2024-01-01", penalty: "2025-03-20", since: "2025-03-20", surcharge: "-"}, {age: 0.5, flag: 50, flagged: true, health: "2024-01-01", penalty: "2000-01-01", since: "2000-01-01", surcharge: "-"}], verified: true, years: 250}}], + [{cap: 0.5, customer: {limit: 0, dueDate: "2024-02-29", verified: false, kind: "corporate", years: 0.000001, vehicles: []}}, {cap: 0.5, customer: {dueDate: "2024-02-29", kind: "corporate", limit: 0, tag: 0, vehicles: [], verified: false, years: 0.000001}}], + [{cap: 0.5, customer: {limit: 99999999999999999999, dueDate: "2024-02-29", verified: false, years: -0.5}}, {cap: 0.5, customer: {dueDate: "2024-02-29", limit: 99999999999999999999, tag: 99999999999999999999, verified: false, years: -0.5}}], + [{cap: 1, customer: {limit: 2, dueDate: "2024-02-29", days: 270, verified: false, kind: "retail", years: 2.50, vehicles: [{age: 1000000, since: "2024-02-29", region: "abc", flagged: true}, {age: -1, since: "2024-02-29", region: "NL", flagged: false}]}}, {cap: 1, customer: {days: 270, dueDate: "2024-02-29", kind: "retail", limit: 2, tag: 2, vehicles: [{age: 1000000, flag: 500001.50, flagged: true, health: "2024-02-29", penalty: "2024-02-29", region: "abc", since: "2024-02-29", surcharge: "abc-abc"}, {age: -1, flag: 500001.50, flagged: false, health: "2024-02-29", penalty: "2024-02-29", region: "NL", since: "2024-02-29", surcharge: "NL-NL"}], verified: false, years: 2.50}, decision: true}], + [{cap: 100, customer: {limit: 1e3, dueDate: "2024-02-29", days: 1e3, verified: false, kind: "corporate", years: 18, vehicles: [{age: 0.5, since: "2030-12-31", region: "VIP", flagged: false}, {age: 100, since: "2025-03-20T10:15:30Z", region: "retail", flagged: false}, {age: 0.000001, since: "2030-12-31", region: "x-y", flagged: true}, {age: 18, since: "2024-01-01", region: "é ü", flagged: false}]}}, {cap: 100, customer: {days: 1000, dueDate: "2024-02-29", kind: "corporate", limit: 1000, tag: 1000, vehicles: [{age: 0.5, flag: 31.62500025, flagged: false, health: "2024-02-29", penalty: "2030-12-31", region: "VIP", since: "2030-12-31", surcharge: "VIP-VIP"}, {age: 100, flag: 31.62500025, flagged: false, health: "2024-02-29", penalty: "2025-03-20T10:15:30Z", region: "retail", since: "2025-03-20T10:15:30Z", surcharge: "retail-retail"}, {age: 0.000001, flag: 31.62500025, flagged: true, health: "2024-02-29", penalty: "2030-12-31", region: "x-y", since: "2030-12-31", surcharge: "x-y-x-y"}, {age: 18, flag: 31.62500025, flagged: false, health: "2024-02-29", penalty: "2024-01-01", region: "é ü", since: "2024-01-01", surcharge: "é ü-é ü"}], verified: false, years: 18}, decision: true}], + [{cap: 10, customer: {limit: null, dueDate: "2000-01-01", days: 0.1, verified: false, kind: "retail", years: 1, vehicles: [{since: "2024-01-01", region: null}, {age: 5, since: "2025-03-20T10:15:30Z", region: null}, {age: null, since: "2025-03-20", flagged: null}]}}, {cap: 10, customer: {days: 0.1, dueDate: "2000-01-01", kind: "retail", limit: null, tag: 0, vehicles: [{flag: 1.6666666666666666666666666667, health: "2000-01-01", penalty: "2024-01-01", region: null, since: "2024-01-01", surcharge: "-"}, {age: 5, flag: 1.6666666666666666666666666667, health: "2000-01-01", penalty: "2025-03-20T10:15:30Z", region: null, since: "2025-03-20T10:15:30Z", surcharge: "-"}, {age: null, flag: 1.6666666666666666666666666667, flagged: null, health: "2000-01-01", penalty: "2025-03-20", since: "2025-03-20", surcharge: "-"}], verified: false, years: 1}, decision: false}], + [{cap: 10, customer: {limit: 5, dueDate: "2025-03-20", days: -500, verified: false, kind: "retail", years: 2, vehicles: [{age: -500, since: "2000-01-01", region: "a", flagged: false}, {age: 1, since: "2025-03-20", region: "A1", flagged: false}, {age: -1, since: "2025-03-20T10:15:30Z", region: "DE", flagged: true}, {age: 250, since: "2024-01-01", region: "A1", flagged: true}, {age: 0, since: "2030-12-31", region: "a", flagged: true}]}}, {cap: 10, customer: {days: -500, dueDate: "2025-03-20", kind: "retail", limit: 5, tag: 5, vehicles: [{age: -500, flag: -48, flagged: false, health: "2025-03-20", penalty: "2000-01-01", region: "a", since: "2000-01-01", surcharge: "a-a"}, {age: 1, flag: -48, flagged: false, health: "2025-03-20", penalty: "2025-03-20", region: "A1", since: "2025-03-20", surcharge: "A1-A1"}, {age: -1, flag: -48, flagged: true, health: "2025-03-20", penalty: "2025-03-20T10:15:30Z", region: "DE", since: "2025-03-20T10:15:30Z", surcharge: "DE-DE"}, {age: 250, flag: -48, flagged: true, health: "2025-03-20", penalty: "2024-01-01", region: "A1", since: "2024-01-01", surcharge: "A1-A1"}, {age: 0, flag: -48, flagged: true, health: "2025-03-20", penalty: "2030-12-31", region: "a", since: "2030-12-31", surcharge: "a-a"}], verified: false, years: 2}, decision: true}], + [{cap: 1, customer: {limit: null, dueDate: "2025-03-20", verified: false, kind: "corporate", years: 50, vehicles: [{age: 0, since: "2024-02-29", flagged: true}, {since: "2025-03-20", region: " pad "}, {age: 18, since: "2025-03-20T10:15:30Z"}]}}, {cap: 1, customer: {dueDate: "2025-03-20", kind: "corporate", limit: null, tag: 0, vehicles: [{age: 0, flag: 8, flagged: true, health: "2025-03-20", penalty: "2024-02-29", since: "2024-02-29", surcharge: "-"}, {flag: 8, health: "2025-03-20", penalty: "2025-03-20", region: " pad ", since: "2025-03-20", surcharge: " pad - pad "}, {age: 18, flag: 8, health: "2025-03-20", penalty: "2025-03-20T10:15:30Z", since: "2025-03-20T10:15:30Z", surcharge: "-"}], verified: false, years: 50}, decision: true}], + [{cap: 0, customer: {limit: 65, dueDate: "1990-06-15", days: 1000000, verified: 1, kind: "retail", years: 18, vehicles: [{age: 0.5, since: "2025-03-20T10:15:30Z", region: "NL", flagged: true}]}}, "!error: InputValidationFailed"], + [{cap: 1, customer: {limit: -0.5, dueDate: "2030-12-31", verified: false, kind: "corporate", years: 2.50}}, {cap: 1, customer: {dueDate: "2030-12-31", kind: "corporate", limit: -0.5, tag: -0.5, verified: false, years: 2.50}}], + [{cap: 10, customer: {limit: 229, dueDate: "2024-01-01", days: 0.1, verified: false, kind: "retail", years: 0, vehicles: [{age: -0.5, since: "2024-02-29", region: "O'Neil", flagged: false}, {age: 0, since: "2025-03-20T10:15:30Z", region: "3.5", flagged: false}]}}, {cap: 10, customer: {days: 0.1, dueDate: "2024-01-01", kind: "retail", limit: 229, tag: 229, vehicles: [{age: -0.5, flag: 1.750, flagged: false, health: "2024-01-01", penalty: "2024-02-29", region: "O'Neil", since: "2024-02-29", surcharge: "O'Neil-O'Neil"}, {age: 0, flag: 1.750, flagged: false, health: "2024-01-01", penalty: "2025-03-20T10:15:30Z", region: "3.5", since: "2025-03-20T10:15:30Z", surcharge: "3.5-3.5"}], verified: false, years: 0}, decision: true}], + [{cap: 100, customer: {limit: 1, dueDate: "2025-03-20", days: 2, verified: true, kind: "corporate", years: -1, vehicles: []}}, {cap: 100, customer: {days: 2, dueDate: "2025-03-20", kind: "corporate", limit: 1, tag: 1, vehicles: [], verified: true, years: -1}}], + ], +} + +// seed 335100 (attempt 0) +{ + name: "a 52: shipment/parcels: 1 assertion, 3 expression, 2 match; 1 root, 3 per-member, 2 top-level computed", + policy: { + models: {shipment: {years: "number", city: "string", vip: "boolean?", parcels: "parcel[]"}, parcel: {score: "number", dueDate: "date", code: "string", weight: "number"}}, + blocks: [ + {expression: "parcel.fee", value: "shipment.vip != null"}, + {match: "parcel.quota", arms: [["not ((parcel.fee or (shipment.vip ?? false)))", "(len(shipment.parcels)) / (abs(parcel.weight) + 1)"], ["(parcel.code + '-' + shipment.city) != 'A1'", "len(shipment.parcels)"], ["not (parcel.fee)", "parcel.weight"], ["not ((shipment.vip ?? false))", "((shipment.vip ?? false) ? parcel.score : parcel.score)"], ["", "1000"]]}, + {assertion: "shipment.margin", conditions: [["and", "count(shipment.parcels, #.dueDate >= d('2000-06-30')) <= shipment.years", 2]]}, + {expression: "parcel.net", value: "parcel.dueDate.add(15, 'year')"}, + {match: "health", arms: [["all(shipment.parcels, #.quota in [11..76])", "(shipment.vip ?? false)"], ["shipment.years >= shipment.years", "shipment.city in ['US', 'DE']"], ["not (shipment.vip == null)", "(shipment.years < shipment.years or shipment.years < 1.5)"], ["shipment.vip == null", "(shipment.years > shipment.years or shipment.years >= shipment.years)"], ["", "shipment.margin"]]}, + {expression: "exposure", value: "(shipment.years - shipment.years)"}, + ], + }, + cases: [ + [{shipment: {years: 65, city: "DE", parcels: [{score: 250, dueDate: "2025-03-20T10:15:30Z", code: "-", weight: 1000000}, {score: 18, dueDate: "2000-01-01", code: "A1", weight: -1}]}}, {exposure: 0, health: true, shipment: {city: "DE", parcels: [{code: "-", dueDate: "2025-03-20T10:15:30Z", fee: false, net: "2040-03-20T10:15:30Z", quota: 0.000001999998000001999998, score: 250, weight: 1000000}, {code: "A1", dueDate: "2000-01-01", fee: false, net: "2015-01-01T00:00:00Z", quota: 1, score: 18, weight: -1}], years: 65}}], + [{shipment: {years: -0, city: "a", parcels: [{score: -1, dueDate: "1990-06-15", code: "a-b-c", weight: 99999999999999999999}, {score: 1000, dueDate: "2000-01-01", code: "abc", weight: 5}, {score: 100, dueDate: "2024-01-01", code: "A1", weight: 99.99}]}}, {exposure: 0, health: false, shipment: {city: "a", parcels: [{code: "a-b-c", dueDate: "1990-06-15", fee: false, net: "2005-06-15T00:00:00Z", quota: 0.00000000000000000003, score: -1, weight: 99999999999999999999}, {code: "abc", dueDate: "2000-01-01", fee: false, net: "2015-01-01T00:00:00Z", quota: 0.50, score: 1000, weight: 5}, {code: "A1", dueDate: "2024-01-01", fee: false, net: "2039-01-01T00:00:00Z", quota: 0.0297059114763838003762748787, score: 100, weight: 99.99}], years: 0}}], + [{shipment: {years: 21, city: "12", vip: false, parcels: [{score: 65, dueDate: "2024-02-29", code: "DE", weight: 1000}, {score: 123456789.123, dueDate: "2030-12-31", code: "a", weight: 0.5}]}}, {exposure: 0, health: false, shipment: {city: "12", parcels: [{code: "DE", dueDate: "2024-02-29", fee: true, net: "Invalid date", quota: 2, score: 65, weight: 1000}, {code: "a", dueDate: "2030-12-31", fee: true, net: "2045-12-31T00:00:00Z", quota: 2, score: 123456789.123, weight: 0.5}], vip: false, years: 21}}], + [{shipment: {years: 5, city: "gold", vip: false, parcels: [{score: 65, dueDate: "2025-03-20", code: "Oslo", weight: 123456789.123}, {score: 65, dueDate: "2024-01-01", code: "O'Neil", weight: -500}, {score: -0.5, dueDate: "2025-03-20", code: "-", weight: 123456789.123}, {score: 1000, dueDate: "2024-02-29", code: "NL", weight: 65}]}}, {exposure: 0, health: false, shipment: {city: "gold", parcels: [{code: "Oslo", dueDate: "2025-03-20", fee: true, net: "2040-03-20T00:00:00Z", quota: 4, score: 65, weight: 123456789.123}, {code: "O'Neil", dueDate: "2024-01-01", fee: true, net: "2039-01-01T00:00:00Z", quota: 4, score: 65, weight: -500}, {code: "-", dueDate: "2025-03-20", fee: true, net: "2040-03-20T00:00:00Z", quota: 4, score: -0.5, weight: 123456789.123}, {code: "NL", dueDate: "2024-02-29", fee: true, net: "Invalid date", quota: 4, score: 1000, weight: 65}], vip: false, years: 5}}], + [{shipment: {years: -0.5, city: "US", vip: false, parcels: [{score: 1.5, dueDate: "1990-06-15", code: "-", weight: -0}, {score: 1000, dueDate: "2024-01-01", code: "3.5", weight: 99999999999999999999}, {score: 0.000001, dueDate: "2000-01-01", code: "VIP", weight: 2.50}]}}, {exposure: 0.0, health: true, shipment: {city: "US", parcels: [{code: "-", dueDate: "1990-06-15", fee: true, net: "2005-06-15T00:00:00Z", quota: 3, score: 1.5, weight: 0}, {code: "3.5", dueDate: "2024-01-01", fee: true, net: "2039-01-01T00:00:00Z", quota: 3, score: 1000, weight: 99999999999999999999}, {code: "VIP", dueDate: "2000-01-01", fee: true, net: "2015-01-01T00:00:00Z", quota: 3, score: 0.000001, weight: 2.50}], vip: false, years: -0.5}}], + [{shipment: {years: 0.000001, city: "", vip: false, parcels: [{score: 99.99, dueDate: "2025-03-20T10:15:30Z", code: " pad ", weight: -0.01}, {score: 1000, dueDate: "2025-03-20T10:15:30Z", code: "DE", weight: 1000}], extraField: "x"}}, {exposure: 0.000000, health: false, shipment: {city: "", extraField: "x", parcels: [{code: " pad ", dueDate: "2025-03-20T10:15:30Z", fee: true, net: "2040-03-20T10:15:30Z", quota: 2, score: 99.99, weight: -0.01}, {code: "DE", dueDate: "2025-03-20T10:15:30Z", fee: true, net: "2040-03-20T10:15:30Z", quota: 2, score: 1000, weight: 1000}], vip: false, years: 0.000001}}], + [{shipment: {years: 99999999999999999999, city: "US", vip: false, parcels: [{score: 1000, dueDate: "2030-12-31", code: "x-y", weight: 1.5}, {score: 65, dueDate: "2030-12-31", code: "O'Neil", weight: 10}], extraField: 1}}, {exposure: 0, health: true, shipment: {city: "US", extraField: 1, parcels: [{code: "x-y", dueDate: "2030-12-31", fee: true, net: "2045-12-31T00:00:00Z", quota: 2, score: 1000, weight: 1.5}, {code: "O'Neil", dueDate: "2030-12-31", fee: true, net: "2045-12-31T00:00:00Z", quota: 2, score: 65, weight: 10}], vip: false, years: 99999999999999999999}}], + [{shipment: {years: -0, city: "a-b-c", vip: true, parcels: []}}, {exposure: 0, health: true, shipment: {city: "a-b-c", parcels: [], vip: true, years: 0}}], + [{shipment: {years: 99.99, city: "Oslo", vip: 1, parcels: [{score: 250, dueDate: "1990-06-15", code: "", weight: 99.99}, {score: 99999999999999999999, dueDate: "2025-03-20T10:15:30Z", code: "a-b-c", weight: 2}]}}, "!error: InputValidationFailed"], + [{shipment: {years: 99999999999999999999, city: "O'Neil", vip: false, parcels: [{score: 7.25, dueDate: "2000-01-01", code: "VIP", weight: 0.5}, {score: -1, dueDate: "2024-02-29", code: "Oslo", weight: 5}]}}, {exposure: 0, health: false, shipment: {city: "O'Neil", parcels: [{code: "VIP", dueDate: "2000-01-01", fee: true, net: "2015-01-01T00:00:00Z", quota: 2, score: 7.25, weight: 0.5}, {code: "Oslo", dueDate: "2024-02-29", fee: true, net: "Invalid date", quota: 2, score: -1, weight: 5}], vip: false, years: 99999999999999999999}}], + [{shipment: {years: 99.99, city: "x-y", vip: true, parcels: [{score: 99999999999999999999, dueDate: "2030-12-31", code: "A1", weight: 2}, {score: 250, dueDate: "2030-12-31", code: "US", weight: -500}, {score: 1000, dueDate: "2025-03-20T10:15:30Z", code: "", weight: -0.01}], extraField: "x"}}, {exposure: 0.00, health: false, shipment: {city: "x-y", extraField: "x", parcels: [{code: "A1", dueDate: "2030-12-31", fee: true, net: "2045-12-31T00:00:00Z", quota: 3, score: 99999999999999999999, weight: 2}, {code: "US", dueDate: "2030-12-31", fee: true, net: "2045-12-31T00:00:00Z", quota: 3, score: 250, weight: -500}, {code: "", dueDate: "2025-03-20T10:15:30Z", fee: true, net: "2040-03-20T10:15:30Z", quota: 3, score: 1000, weight: -0.01}], vip: true, years: 99.99}}], + [{shipment: {years: 18, city: "a", vip: true, parcels: [{score: 1000, dueDate: "2000-01-01", code: "é ü", weight: 1000}, {score: 1000, dueDate: "2024-02-29", code: "US", weight: -500}, {score: 250, dueDate: "1990-06-15", code: "-", weight: -500}]}}, {exposure: 0, health: false, shipment: {city: "a", parcels: [{code: "é ü", dueDate: "2000-01-01", fee: true, net: "2015-01-01T00:00:00Z", quota: 3, score: 1000, weight: 1000}, {code: "US", dueDate: "2024-02-29", fee: true, net: "Invalid date", quota: 3, score: 1000, weight: -500}, {code: "-", dueDate: "1990-06-15", fee: true, net: "2005-06-15T00:00:00Z", quota: 3, score: 250, weight: -500}], vip: true, years: 18}}], + [{shipment: {years: 2, city: "A1", vip: false, parcels: [{score: true, dueDate: "2024-01-01", code: "US", weight: 0.5}, {score: 251, dueDate: "2025-03-20", code: "gold", weight: -0}, {score: -0.5, dueDate: "1990-06-15", code: "a-b-c", weight: 1000000}, {score: 99.99, dueDate: "2030-12-31", code: "a", weight: 5}]}}, "!error: InputValidationFailed"], + [{shipment: {years: 18, city: "a-b-c", vip: true, parcels: [{score: 1000000, dueDate: "1990-06-15", code: "Zed", weight: 18}, {score: 99999999999999999999, dueDate: "2024-01-01", code: "日本", weight: 250}, {score: 250, dueDate: "1990-06-15", code: "", weight: 99.99}, {score: 5, dueDate: "2030-12-31", code: "é ü", weight: -0.01}, {score: 99999999999999999999, dueDate: "1990-06-15", code: "a", weight: 1000}]}}, {exposure: 0, health: false, shipment: {city: "a-b-c", parcels: [{code: "Zed", dueDate: "1990-06-15", fee: true, net: "2005-06-15T00:00:00Z", quota: 5, score: 1000000, weight: 18}, {code: "日本", dueDate: "2024-01-01", fee: true, net: "2039-01-01T00:00:00Z", quota: 5, score: 99999999999999999999, weight: 250}, {code: "", dueDate: "1990-06-15", fee: true, net: "2005-06-15T00:00:00Z", quota: 5, score: 250, weight: 99.99}, {code: "é ü", dueDate: "2030-12-31", fee: true, net: "2045-12-31T00:00:00Z", quota: 5, score: 5, weight: -0.01}, {code: "a", dueDate: "1990-06-15", fee: true, net: "2005-06-15T00:00:00Z", quota: 5, score: 99999999999999999999, weight: 1000}], vip: true, years: 18}}], + [{shipment: {years: 0.000001, city: "O'Neil", vip: true, parcels: [{score: -1, dueDate: "2025-03-20", code: "NL", weight: 1}, {score: 0.1, dueDate: "2000-01-01", code: "-", weight: -0}, {score: 5, dueDate: "2024-01-01", code: "retail", weight: 1000}, {score: 0, dueDate: "2024-01-01", code: "A1", weight: 1000}]}}, {exposure: 0.000000, health: false, shipment: {city: "O'Neil", parcels: [{code: "NL", dueDate: "2025-03-20", fee: true, net: "2040-03-20T00:00:00Z", quota: 4, score: -1, weight: 1}, {code: "-", dueDate: "2000-01-01", fee: true, net: "2015-01-01T00:00:00Z", quota: 4, score: 0.1, weight: 0}, {code: "retail", dueDate: "2024-01-01", fee: true, net: "2039-01-01T00:00:00Z", quota: 4, score: 5, weight: 1000}, {code: "A1", dueDate: "2024-01-01", fee: true, net: "2039-01-01T00:00:00Z", quota: 4, score: 0, weight: 1000}], vip: true, years: 0.000001}}], + [{shipment: {years: 1000, city: "Oslo", vip: false, parcels: [{score: 18, dueDate: "2025-03-20", code: "DE", weight: -500}], extraField: {nested: true}}}, {exposure: 0, health: false, shipment: {city: "Oslo", extraField: {nested: true}, parcels: [{code: "DE", dueDate: "2025-03-20", fee: true, net: "2040-03-20T00:00:00Z", quota: 1, score: 18, weight: -500}], vip: false, years: 1000}}], + [{shipment: {years: 123456789.123, city: "US", vip: false, parcels: [{score: 1e3, dueDate: "2025-03-20T10:15:30Z", code: "A1", weight: 328}]}}, {exposure: 0.000, health: true, shipment: {city: "US", parcels: [{code: "A1", dueDate: "2025-03-20T10:15:30Z", fee: true, net: "2040-03-20T10:15:30Z", quota: 1, score: 1000, weight: 328}], vip: false, years: 123456789.123}}], + [{shipment: {years: 100, city: "US", vip: false, parcels: [{score: 1e3, dueDate: "2025-03-20", code: "Zed", weight: 99.99}, {score: 0.000001, dueDate: "2024-01-01", code: "-", weight: 1000}]}}, {exposure: 0, health: true, shipment: {city: "US", parcels: [{code: "Zed", dueDate: "2025-03-20", fee: true, net: "2040-03-20T00:00:00Z", quota: 2, score: 1000, weight: 99.99}, {code: "-", dueDate: "2024-01-01", fee: true, net: "2039-01-01T00:00:00Z", quota: 2, score: 0.000001, weight: 1000}], vip: false, years: 100}}], + [{shipment: {years: 123456789.123, city: "A1", parcels: []}}, {exposure: 0.000, health: false, shipment: {city: "A1", parcels: [], years: 123456789.123}}], + [{shipment: {years: -0, city: "US", vip: false, parcels: [{score: 250, dueDate: "2000-01-01", code: "US", weight: 1.5}]}}, {exposure: 0, health: true, shipment: {city: "US", parcels: [{code: "US", dueDate: "2000-01-01", fee: true, net: "2015-01-01T00:00:00Z", quota: 1, score: 250, weight: 1.5}], vip: false, years: 0}}], + [{shipment: {years: 10, city: "Oslo", vip: null, parcels: [{score: 139, dueDate: "2030-12-31", code: "日本", weight: 250}]}}, {exposure: 0, health: false, shipment: {city: "Oslo", parcels: [{code: "日本", dueDate: "2030-12-31", fee: false, net: "2045-12-31T00:00:00Z", quota: 0.0039840637450199203187250996, score: 139, weight: 250}], vip: null, years: 10}}], + [{shipment: {years: 1000000, city: "Oslo", vip: false, parcels: []}}, {exposure: 0, health: false, shipment: {city: "Oslo", parcels: [], vip: false, years: 1000000}}], + [{shipment: {years: 1.5, city: "a-b-c", vip: 1, parcels: [{score: -0, dueDate: "2025-03-20", code: "x-y", weight: -0.01}, {score: -1, dueDate: "1990-06-15", code: "A1", weight: 5}, {score: 0.000001, dueDate: "2025-03-20", code: "VIP", weight: 250}, {score: 1, dueDate: "2025-03-20", code: "NL", weight: 7.25}, {score: 0.000001, dueDate: "2030-12-31", code: "Oslo", weight: 100}]}}, "!error: InputValidationFailed"], + [{shipment: {years: -500, city: "-", parcels: []}}, {exposure: 0, health: false, shipment: {city: "-", parcels: [], years: -500}}], + [{shipment: {years: 10, city: "retail", vip: null, parcels: []}}, {exposure: 0, health: false, shipment: {city: "retail", parcels: [], vip: null, years: 10}}], + [{shipment: {years: -500, city: "DE", parcels: [{score: 100, dueDate: "2024-01-01", code: "a-b-c", weight: 1.5}, {score: -0.01, dueDate: "2030-12-31", code: " pad ", weight: 2}, {score: 0, dueDate: "2024-02-29", code: "gold", weight: 1.5}, {score: 2.50, dueDate: "1990-06-15", code: "US", weight: -0.5}, {score: 0.000001, dueDate: "2025-03-20", code: "", weight: 104}]}}, {exposure: 0, health: true, shipment: {city: "DE", parcels: [{code: "a-b-c", dueDate: "2024-01-01", fee: false, net: "2039-01-01T00:00:00Z", quota: 2.0, score: 100, weight: 1.5}, {code: " pad ", dueDate: "2030-12-31", fee: false, net: "2045-12-31T00:00:00Z", quota: 1.6666666666666666666666666667, score: -0.01, weight: 2}, {code: "gold", dueDate: "2024-02-29", fee: false, net: "Invalid date", quota: 2.0, score: 0, weight: 1.5}, {code: "US", dueDate: "1990-06-15", fee: false, net: "2005-06-15T00:00:00Z", quota: 3.3333333333333333333333333333, score: 2.50, weight: -0.5}, {code: "", dueDate: "2025-03-20", fee: false, net: "2040-03-20T00:00:00Z", quota: 0.0476190476190476190476190476, score: 0.000001, weight: 104}], years: -500}}], + [{shipment: {years: 0.5, city: "x-y", vip: null, parcels: [{score: -0.01, dueDate: "1990-06-15", code: "O'Neil", weight: 7.25}, {score: 18, dueDate: "2030-12-31", code: "3.5", weight: 5}]}}, {exposure: 0.0, health: false, shipment: {city: "x-y", parcels: [{code: "O'Neil", dueDate: "1990-06-15", fee: false, net: "2005-06-15T00:00:00Z", quota: 0.2424242424242424242424242424, score: -0.01, weight: 7.25}, {code: "3.5", dueDate: "2030-12-31", fee: false, net: "2045-12-31T00:00:00Z", quota: 0.3333333333333333333333333333, score: 18, weight: 5}], vip: null, years: 0.5}}], + [{shipment: {years: -1, city: "DE", vip: false, parcels: [{score: -0, dueDate: "2024-02-29", code: "-", weight: 0.1}]}}, {exposure: 0, health: true, shipment: {city: "DE", parcels: [{code: "-", dueDate: "2024-02-29", fee: true, net: "Invalid date", quota: 1, score: 0, weight: 0.1}], vip: false, years: -1}}], + [{shipment: {years: 10, city: " pad ", vip: true, parcels: [{score: 250, dueDate: "2030-12-31", code: "Oslo", weight: 0.5}, {score: 1, dueDate: "2025-03-20T10:15:30Z", code: "O'Neil", weight: 18}]}}, {exposure: 0, health: false, shipment: {city: " pad ", parcels: [{code: "Oslo", dueDate: "2030-12-31", fee: true, net: "2045-12-31T00:00:00Z", quota: 2, score: 250, weight: 0.5}, {code: "O'Neil", dueDate: "2025-03-20T10:15:30Z", fee: true, net: "2040-03-20T10:15:30Z", quota: 2, score: 1, weight: 18}], vip: true, years: 10}}], + ], +} + +// seed 335200 (attempt 0) +{ + name: "a 53: customer/vehicles: 1 assertion, 3 expression; 3 root, 0 per-member, 1 top-level computed", + policy: { + models: {customer: {rate: "number", vip: "boolean", status: "string(open|closed|pending)?", insured: "boolean", flagged: "boolean", urgent: "boolean", vehicles: "vehicle[]"}, vehicle: {rate: "number?", city: "string?", plan: "string(basic|plus|premium|trial)?", vip: "boolean"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {expression: "customer.segment", value: "(((customer.rate + 0.5) + (customer.rate * customer.rate)) + ((customer.insured ? customer.rate : factor) + (customer.rate - factor)))"}, + {expression: "customer.summary", value: "count(customer.vehicles, (#.rate ?? 0) in [45..51])"}, + {assertion: "customer.bonus", conditions: [["or", "(customer.status ?? '') == 'closed'", 0], ["or", "(customer.vip or discount)", 0], ["or", "(customer.status ?? '') != 'pending'", 0], ["or", "not (customer.vip)", 0], ["and", "some(customer.vehicles, not (#.vip))", 1]]}, + {expression: "discount", value: "((customer.status ?? '') == 'closed' or customer.status == null)"}, + ], + }, + cases: [ + [{factor: -2, customer: {rate: 1, vip: false, status: "pending", insured: false, flagged: false, urgent: true, vehicles: [], extraField: "x"}}, {customer: {bonus: true, extraField: "x", flagged: false, insured: false, rate: 1, segment: 3.5, status: "pending", summary: 0, urgent: true, vehicles: [], vip: false}, discount: false, factor: -2}], + [{factor: 0, customer: {rate: 250, vip: false, status: "open", insured: true, flagged: false, urgent: false, vehicles: []}}, {customer: {bonus: true, flagged: false, insured: true, rate: 250, segment: 63250.5, status: "open", summary: 0, urgent: false, vehicles: [], vip: false}, discount: false, factor: 0}], + [{factor: 0.5, customer: {rate: -1, vip: true, status: null, insured: true, flagged: false, urgent: true, vehicles: [{rate: null, plan: "premium", vip: true}]}}, {customer: {bonus: true, flagged: false, insured: true, rate: -1, segment: -2.0, status: null, summary: 0, urgent: true, vehicles: [{plan: "premium", rate: null, vip: true}], vip: true}, discount: true, factor: 0.5}], + [{factor: -2, customer: {rate: 50, vip: true, status: "open", insured: false, flagged: false, urgent: false, vehicles: []}}, {customer: {bonus: true, flagged: false, insured: false, rate: 50, segment: 2600.5, status: "open", summary: 0, urgent: false, vehicles: [], vip: true}, discount: false, factor: -2}], + [{factor: 1, customer: {rate: 1000000, vip: false, status: "closed", insured: false, flagged: true, urgent: false, vehicles: [{rate: 1000000, city: "retail", plan: "premium", vip: false}, {rate: 250, city: "abc", plan: "basic", vip: true}, {rate: 0.000001, city: " pad ", plan: "trial", vip: false}], extraField: "x"}}, {customer: {bonus: true, extraField: "x", flagged: true, insured: false, rate: 1000000, segment: 1000002000000.5, status: "closed", summary: 0, urgent: false, vehicles: [{city: "retail", plan: "premium", rate: 1000000, vip: false}, {city: "abc", plan: "basic", rate: 250, vip: true}, {city: " pad ", plan: "trial", rate: 0.000001, vip: false}], vip: false}, discount: true, factor: 1}], + [{factor: 100, customer: {rate: 1e3, vip: true, status: "open", insured: true, flagged: true, urgent: true, vehicles: [{rate: -1, plan: null, vip: false}, {rate: 2, city: null, plan: null, vip: false}, {rate: 50, city: null, vip: true}, {city: "Oslo", plan: null, vip: true}]}}, {customer: {bonus: true, flagged: true, insured: true, rate: 1000, segment: 1002900.5, status: "open", summary: 1, urgent: true, vehicles: [{plan: null, rate: -1, vip: false}, {city: null, plan: null, rate: 2, vip: false}, {city: null, rate: 50, vip: true}, {city: "Oslo", plan: null, vip: true}], vip: true}, discount: false, factor: 100}], + [{factor: 0, customer: {rate: 5, vip: true, status: "closed", insured: false, flagged: false, urgent: false, vehicles: [{rate: null, city: null, vip: true}, {rate: 307, city: "x-y", plan: "basic", vip: true}, {city: "retail", plan: "basic", vip: true}, {city: "A1", plan: null, vip: true}]}}, {customer: {bonus: true, flagged: false, insured: false, rate: 5, segment: 35.5, status: "closed", summary: 0, urgent: false, vehicles: [{city: null, rate: null, vip: true}, {city: "x-y", plan: "basic", rate: 307, vip: true}, {city: "retail", plan: "basic", vip: true}, {city: "A1", plan: null, vip: true}], vip: true}, discount: true, factor: 0}], + [{factor: -2, customer: {rate: 7.25, vip: true, insured: false, flagged: true, urgent: false, vehicles: [{rate: -0.01, plan: "basic", vip: true}, {rate: 2, plan: null, vip: false}]}}, {customer: {bonus: true, flagged: true, insured: false, rate: 7.25, segment: 67.5625, summary: 0, urgent: false, vehicles: [{plan: "basic", rate: -0.01, vip: true}, {plan: null, rate: 2, vip: false}], vip: true}, discount: true, factor: -2}], + [{factor: -2, customer: {rate: 1e3, vip: false, insured: false, flagged: false, urgent: false, vehicles: [{rate: null, city: "", vip: true}, {city: "é ü", plan: "premium", vip: false}, {rate: 0.5, vip: false}, {rate: 18, plan: null, vip: true}, {city: "O'Neil", vip: false}]}}, {customer: {bonus: true, flagged: false, insured: false, rate: 1000, segment: 1002000.5, summary: 0, urgent: false, vehicles: [{city: "", rate: null, vip: true}, {city: "é ü", plan: "premium", vip: false}, {rate: 0.5, vip: false}, {plan: null, rate: 18, vip: true}, {city: "O'Neil", vip: false}], vip: false}, discount: true, factor: -2}], + [{factor: -2, customer: {rate: -0.5, vip: false, status: null, insured: true, flagged: false, urgent: true, vehicles: [{rate: null, plan: "basic", vip: true}, {city: "12", plan: null, vip: true}, {rate: 5, plan: null, vip: false}]}}, {customer: {bonus: true, flagged: false, insured: true, rate: -0.5, segment: 1.25, status: null, summary: 0, urgent: true, vehicles: [{plan: "basic", rate: null, vip: true}, {city: "12", plan: null, vip: true}, {plan: null, rate: 5, vip: false}], vip: false}, discount: true, factor: -2}], + [{factor: 10, customer: {rate: 10, vip: false, status: "open", insured: true, flagged: true, urgent: true, vehicles: [{rate: -0, city: "3.5", plan: "premium", vip: true}, {rate: 100, city: "DE", plan: "premium", vip: false}, {rate: 50, city: "DE", plan: "premium", vip: false}, {rate: 10, city: "O'Neil", plan: "trial", vip: true}]}}, {customer: {bonus: true, flagged: true, insured: true, rate: 10, segment: 120.5, status: "open", summary: 1, urgent: true, vehicles: [{city: "3.5", plan: "premium", rate: 0, vip: true}, {city: "DE", plan: "premium", rate: 100, vip: false}, {city: "DE", plan: "premium", rate: 50, vip: false}, {city: "O'Neil", plan: "trial", rate: 10, vip: true}], vip: false}, discount: false, factor: 10}], + [{factor: 100, customer: {rate: 250, vip: true, status: "open", insured: false, flagged: false, urgent: false, vehicles: [{rate: 99.99, city: "日本", plan: "basic", vip: false}, {rate: 1, city: "a-b-c", plan: "basic", vip: false}], extraField: "x"}}, {customer: {bonus: true, extraField: "x", flagged: false, insured: false, rate: 250, segment: 63000.5, status: "open", summary: 0, urgent: false, vehicles: [{city: "日本", plan: "basic", rate: 99.99, vip: false}, {city: "a-b-c", plan: "basic", rate: 1, vip: false}], vip: true}, discount: false, factor: 100}], + [{factor: 1, customer: {rate: 2, vip: false, status: "open", insured: true, flagged: true, urgent: false, vehicles: [{rate: 1, city: "abc", plan: "trial", vip: true}, {rate: 5, city: "日本", plan: "premium", vip: true}, {rate: 0.5, city: "Zed", plan: "basic", vip: true}]}}, {customer: {bonus: true, flagged: true, insured: true, rate: 2, segment: 9.5, status: "open", summary: 0, urgent: false, vehicles: [{city: "abc", plan: "trial", rate: 1, vip: true}, {city: "日本", plan: "premium", rate: 5, vip: true}, {city: "Zed", plan: "basic", rate: 0.5, vip: true}], vip: false}, discount: false, factor: 1}], + [{factor: 0.5, customer: {rate: 1000, vip: false, status: "pending", insured: true, flagged: true, urgent: false, vehicles: [{rate: 123456789.123, city: " pad ", plan: "plus"}]}}, "!error: ExpressionFailed"], + [{factor: -2, customer: {rate: 18, vip: true, status: "closed", insured: false, flagged: false, urgent: true, vehicles: [{rate: -500, city: "US", plan: "plus", vip: true}]}}, {customer: {bonus: true, flagged: false, insured: false, rate: 18, segment: 360.5, status: "closed", summary: 0, urgent: true, vehicles: [{city: "US", plan: "plus", rate: -500, vip: true}], vip: true}, discount: true, factor: -2}], + [{factor: 10, customer: {rate: 5, vip: false, status: "closed", insured: true, flagged: false, urgent: true, vehicles: []}}, {customer: {bonus: true, flagged: false, insured: true, rate: 5, segment: 30.5, status: "closed", summary: 0, urgent: true, vehicles: [], vip: false}, discount: true, factor: 10}], + [{factor: 0, customer: {rate: 0.5, vip: false, status: null, insured: false, flagged: false, urgent: false, vehicles: [{rate: 65, city: "VIP", plan: "trial", vip: true}]}}, {customer: {bonus: true, flagged: false, insured: false, rate: 0.5, segment: 1.75, status: null, summary: 0, urgent: false, vehicles: [{city: "VIP", plan: "trial", rate: 65, vip: true}], vip: false}, discount: true, factor: 0}], + [{factor: 0, customer: {rate: 65, vip: true, status: "closed", insured: true, flagged: true, urgent: false, vehicles: [{rate: 99.99, city: "12", plan: "basic", vip: true}, {rate: 0.1, city: "a", plan: "plus", vip: false}]}}, {customer: {bonus: true, flagged: true, insured: true, rate: 65, segment: 4420.5, status: "closed", summary: 0, urgent: false, vehicles: [{city: "12", plan: "basic", rate: 99.99, vip: true}, {city: "a", plan: "plus", rate: 0.1, vip: false}], vip: true}, discount: true, factor: 0}], + [{factor: -2, customer: {rate: 0.000001, vip: false, status: "open", insured: true, flagged: true, urgent: true, vehicles: [{rate: 5, city: "Zed", plan: "basic", vip: false}]}}, {customer: {bonus: true, flagged: true, insured: true, rate: 0.000001, segment: 2.500003000001, status: "open", summary: 0, urgent: true, vehicles: [{city: "Zed", plan: "basic", rate: 5, vip: false}], vip: false}, discount: false, factor: -2}], + [{factor: 100, customer: {rate: 65, vip: true, status: "open", insured: false, flagged: true, urgent: true, vehicles: [{city: null, vip: true}, {rate: 100, city: "", plan: "plus", vip: false}]}}, {customer: {bonus: true, flagged: true, insured: false, rate: 65, segment: 4355.5, status: "open", summary: 0, urgent: true, vehicles: [{city: null, vip: true}, {city: "", plan: "plus", rate: 100, vip: false}], vip: true}, discount: false, factor: 100}], + [{factor: 0, customer: {rate: 0, vip: true, status: "open", insured: false, flagged: false, urgent: false, vehicles: [{rate: 1, city: "A1", plan: "basic", vip: false}]}}, {customer: {bonus: true, flagged: false, insured: false, rate: 0, segment: 0.5, status: "open", summary: 0, urgent: false, vehicles: [{city: "A1", plan: "basic", rate: 1, vip: false}], vip: true}, discount: false, factor: 0}], + [{factor: -2, customer: {rate: 99.99, vip: false, status: "pending", insured: false, flagged: true, urgent: false, vehicles: [{rate: 65, city: "retail", plan: "plus", vip: false}, {rate: 0.000001, city: "US", plan: "basic", vip: false}, {rate: 0.5, city: "DE", plan: "plus", vip: true}, {rate: -0.01, city: "é ü", plan: "premium", vip: false}]}}, {customer: {bonus: true, flagged: true, insured: false, rate: 99.99, segment: 10198.4801, status: "pending", summary: 0, urgent: false, vehicles: [{city: "retail", plan: "plus", rate: 65, vip: false}, {city: "US", plan: "basic", rate: 0.000001, vip: false}, {city: "DE", plan: "plus", rate: 0.5, vip: true}, {city: "é ü", plan: "premium", rate: -0.01, vip: false}], vip: false}, discount: false, factor: -2}], + [{factor: 10, customer: {rate: 123456789.123, vip: false, insured: true, flagged: false, urgent: true, vehicles: [{rate: null, plan: null, vip: false}, {rate: 99.99, city: "gold", plan: "trial", vip: false}, {rate: -0.01, city: "a", plan: "basic", vip: false}, {rate: null, city: "DE", plan: "premium", vip: false}]}}, {customer: {bonus: true, flagged: false, insured: true, rate: 123456789.123, segment: 15241579150931248.978129, summary: 0, urgent: true, vehicles: [{plan: null, rate: null, vip: false}, {city: "gold", plan: "trial", rate: 99.99, vip: false}, {city: "a", plan: "basic", rate: -0.01, vip: false}, {city: "DE", plan: "premium", rate: null, vip: false}], vip: false}, discount: true, factor: 10}], + [{factor: 10, customer: {rate: 1000, vip: true, status: "open", insured: false, flagged: false, urgent: false, vehicles: [{rate: 1000, city: "Zed", plan: "basic", vip: true}, {rate: 0.1, city: "VIP", plan: "basic", vip: false}, {rate: 5, city: "12", plan: "basic", vip: true}, {rate: 2, city: "NL", plan: "basic", vip: true}, {rate: 0.1, city: " pad ", plan: "plus", vip: false}]}}, {customer: {bonus: true, flagged: false, insured: false, rate: 1000, segment: 1002000.5, status: "open", summary: 0, urgent: false, vehicles: [{city: "Zed", plan: "basic", rate: 1000, vip: true}, {city: "VIP", plan: "basic", rate: 0.1, vip: false}, {city: "12", plan: "basic", rate: 5, vip: true}, {city: "NL", plan: "basic", rate: 2, vip: true}, {city: " pad ", plan: "plus", rate: 0.1, vip: false}], vip: true}, discount: false, factor: 10}], + [{factor: 100, customer: {rate: 50, vip: true, insured: true, flagged: true, urgent: true, vehicles: [{rate: null, plan: "premium", vip: true}, {city: "日本", plan: "premium", vip: true}]}}, {customer: {bonus: true, flagged: true, insured: true, rate: 50, segment: 2550.5, summary: 0, urgent: true, vehicles: [{plan: "premium", rate: null, vip: true}, {city: "日本", plan: "premium", vip: true}], vip: true}, discount: true, factor: 100}], + [{factor: 0, customer: {rate: 168, vip: true, status: "closed", insured: false, flagged: true, urgent: true, vehicles: [{rate: -0, city: "gold", plan: "basic", vip: true}, {rate: -1, city: "NL", plan: "premium", vip: false}]}}, {customer: {bonus: true, flagged: true, insured: false, rate: 168, segment: 28560.5, status: "closed", summary: 0, urgent: true, vehicles: [{city: "gold", plan: "basic", rate: 0, vip: true}, {city: "NL", plan: "premium", rate: -1, vip: false}], vip: true}, discount: true, factor: 0}], + [{factor: 0.5, customer: {rate: 1, vip: true, status: "closed", insured: true, flagged: false, urgent: true, vehicles: [{rate: 123456789.123, city: "O'Neil", plan: "basic", vip: true}]}}, {customer: {bonus: true, flagged: false, insured: true, rate: 1, segment: 4.0, status: "closed", summary: 0, urgent: true, vehicles: [{city: "O'Neil", plan: "basic", rate: 123456789.123, vip: true}], vip: true}, discount: true, factor: 0.5}], + ], +} + +// seed 335300 (attempt 0) +{ + name: "a 54: order/parcels: 1 assertion, 1 expression, 1 match, 2 table; 4 root, 4 per-member, 0 top-level computed", + policy: { + models: {order: {amount: "number?", label: "string?", region: "string", openedAt: "date?", balance: "number", parcels: "parcel[]"}, parcel: {days: "number", score: "number?"}}, + blocks: [ + {expression: "parcel.adjusted", value: "order.amount != null"}, + {table: "t2", inputs: ["order.balance", "order.balance"], outputs: ["order.net", "order.share", "order.review"], rules: [ + [">= 250", "[0.5..387.5]", "order.region", "(order.label ?? '')", "3"], + ["", "1.5", "string(order.balance)", "'x'", "order.balance"], + [">= 1000", "[50..531]", "((order.label ?? '') + '-' + (order.label ?? ''))", "'retail'", "order.balance"], + ["!= 1", "[2..96]", "order.region", "(order.label ?? '')", "(order.amount ?? 0)"], + ["", "", "order.region", "", "order.balance"], + ]}, + {table: "t3", inputs: [null, null], outputs: ["parcel.level", "parcel.tag"], rules: [ + ["order.balance in [12..210]", "(parcel.adjusted and parcel.adjusted)", "'A1'", ""], + ["", "(order.review ?? 0) < (order.amount ?? 0)", "", "parcel.adjusted"], + ["(order.review ?? 0) == 10", "(order.review ?? 0) != 5", "((order.net ?? '') + '-' + 'high')", "order.review == null"], + ["len((order.net ?? '')) > 2", "(order.openedAt ?? d('2025-01-01')) >= d('2024-01-01')", "trim((order.net ?? ''))", "(parcel.adjusted and parcel.adjusted)"], + ["", "", "order.region", "parcel.adjusted"], + ]}, + {match: "parcel.weighted", arms: [["(order.review ?? 0) != (parcel.score ?? 0)", "order.balance"], ["(order.openedAt ?? d('2025-01-01')) >= d('2025-03-20')", "(order.amount ?? 0)"], ["(order.amount ?? 0) >= (parcel.score ?? 0)", "parcel.days"], ["(parcel.adjusted or parcel.adjusted)", "len(order.parcels)"], ["", "250"]]}, + {assertion: "order.penalty", conditions: [["or", "(order.region in ['low', 'low'] or none(order.parcels, #.tag == null))", 1], ["and", "(some(order.parcels, ((#.tag ?? false) or #.adjusted)) or all(order.parcels, (#.adjusted or #.adjusted)))", 0], ["and", "((order.amount ?? 0) > 1000 or order.balance <= 3)", 0]]}, + ], + }, + cases: [ + [{order: {amount: 99.99, label: "x", openedAt: "2025-03-20T10:15:30Z", balance: -0, parcels: [{days: 5, score: 18}, {days: -0.5, score: -0}, {days: 50, score: 2.50}, {days: 50, score: 250}, {days: -0, score: 1000000}]}}, "!error: MissingRequiredInputs"], + [{order: {amount: 1000, label: "3.5", region: "x-y", openedAt: "1990-06-15", balance: 50, parcels: [{days: 50, score: 5}, {days: -0.01, score: 10}, {days: 65, score: 3}]}}, {order: {amount: 1000, balance: 50, label: "3.5", net: "x-y", openedAt: "1990-06-15", parcels: [{adjusted: true, days: 50, level: "A1", score: 5, tag: true, weighted: 50}, {adjusted: true, days: -0.01, level: "A1", score: 10, tag: true, weighted: 50}, {adjusted: true, days: 65, level: "A1", score: 3, tag: true, weighted: 50}], penalty: false, region: "x-y", review: 1000, share: "3.5"}}], + [{order: {amount: 1, label: "a", region: "retail", openedAt: "1990-06-15", balance: 250, parcels: [{days: 0.5, score: 2}, {days: 10, score: 2.50}, {days: 2.50, score: 1000}, {days: 5, score: -500}, {days: 5, score: 1e3}]}}, {order: {amount: 1, balance: 250, label: "a", net: "retail", openedAt: "1990-06-15", parcels: [{adjusted: true, days: 0.5, level: "retail", score: 2, tag: true, weighted: 250}, {adjusted: true, days: 10, level: "retail", score: 2.50, tag: true, weighted: 250}, {adjusted: true, days: 2.50, level: "retail", score: 1000, tag: true, weighted: 250}, {adjusted: true, days: 5, level: "retail", score: -500, tag: true, weighted: 250}, {adjusted: true, days: 5, level: "retail", score: 1000, tag: true, weighted: 250}], penalty: false, region: "retail", review: 3, share: "a"}}], + [{order: {amount: 10, label: "VIP", region: "12", openedAt: "2025-03-20", balance: 2.50, parcels: [{days: -0, score: 10}, {days: 250, score: 0.5}, {days: -1, score: 123456789.123}, {days: 3, score: 50}, {days: 0, score: 250}], extraField: {nested: true}}}, {order: {amount: 10, balance: 2.50, extraField: {nested: true}, label: "VIP", net: "12", openedAt: "2025-03-20", parcels: [{adjusted: true, days: 0, level: "12-high", score: 10, tag: false, weighted: 10}, {adjusted: true, days: 250, level: "12-high", score: 0.5, tag: false, weighted: 2.50}, {adjusted: true, days: -1, level: "12-high", score: 123456789.123, tag: false, weighted: 2.50}, {adjusted: true, days: 3, level: "12-high", score: 50, tag: false, weighted: 2.50}, {adjusted: true, days: 0, level: "12-high", score: 250, tag: false, weighted: 2.50}], penalty: true, region: "12", review: 10, share: "VIP"}}], + [{order: {amount: 1000, label: "-", region: "A1", openedAt: "2000-01-01", balance: 5, parcels: [{days: 50, score: 0.1}], extraField: "x"}}, {order: {amount: 1000, balance: 5, extraField: "x", label: "-", net: "A1", openedAt: "2000-01-01", parcels: [{adjusted: true, days: 50, level: "A1", score: 0.1, tag: true, weighted: 5}], penalty: false, region: "A1", review: 1000, share: "-"}}], + [{order: {amount: 0, label: "A1", region: " pad ", openedAt: "2000-01-01", balance: 5, parcels: []}}, {order: {amount: 0, balance: 5, label: "A1", net: " pad ", openedAt: "2000-01-01", parcels: [], penalty: false, region: " pad ", review: 0, share: "A1"}}], + [{order: {amount: 10, label: "a", region: "US", openedAt: "2000-01-01", balance: 0, parcels: []}}, {order: {amount: 10, balance: 0, label: "a", net: "US", openedAt: "2000-01-01", parcels: [], penalty: true, region: "US", review: 0, share: null}}], + [{order: {region: "retail", openedAt: null, balance: 10, parcels: [{days: 65, score: null}, {days: 10, score: 100}, {days: 0, score: 1.5}]}}, {order: {balance: 10, net: "retail", openedAt: null, parcels: [{adjusted: false, days: 65, level: "retail", score: null, tag: false, weighted: 65}, {adjusted: false, days: 10, level: "retail", score: 100, tag: false, weighted: 10}, {adjusted: false, days: 0, level: "retail", score: 1.5, tag: false, weighted: 10}], penalty: false, region: "retail", review: 0, share: ""}}], + [{order: {amount: 2.50, label: 5, region: "NL", openedAt: "2030-12-31", balance: 99.99, parcels: [{days: 100, score: 99.99}, {days: 1e3, score: 1000}]}}, "!error: InputValidationFailed"], + [{order: {amount: 10, region: "-", balance: 10, parcels: [{days: 50}]}}, {order: {amount: 10, balance: 10, net: "-", parcels: [{adjusted: true, days: 50, level: "--high", tag: false, weighted: 10}], penalty: false, region: "-", review: 10, share: ""}}], + [{order: {amount: 10, label: "VIP", region: "US", openedAt: "2000-01-01", balance: 0.000001, parcels: []}}, {order: {amount: 10, balance: 0.000001, label: "VIP", net: "US", openedAt: "2000-01-01", parcels: [], penalty: true, region: "US", review: 0.000001, share: null}}], + [{order: {amount: 250, label: "日本", region: "VIP", openedAt: "2024-01-01", balance: 0, parcels: []}}, {order: {amount: 250, balance: 0, label: "日本", net: "VIP", openedAt: "2024-01-01", parcels: [], penalty: true, region: "VIP", review: 0, share: null}}], + [{order: {amount: 50, label: "retail", region: 5, openedAt: "2000-01-01", balance: 99.99, parcels: [{days: 2, score: 10}, {days: 7.25, score: 1.5}, {days: 50, score: 433}, {days: 250, score: 1}]}}, "!error: InputValidationFailed"], + [{order: {amount: 50, label: "abc", region: "日本", openedAt: "2024-02-29", balance: 250, parcels: [{days: 0.5, score: 5}]}}, {order: {amount: 50, balance: 250, label: "abc", net: "日本", openedAt: "2024-02-29", parcels: [{adjusted: true, days: 0.5, level: "日本", score: 5, tag: true, weighted: 250}], penalty: false, region: "日本", review: 3, share: "abc"}}], + [{order: {amount: 0.5, region: "NL", balance: 10, parcels: [{days: 1000}]}}, {order: {amount: 0.5, balance: 10, net: "NL", parcels: [{adjusted: true, days: 1000, level: "NL", tag: true, weighted: 10}], penalty: false, region: "NL", review: 0.5, share: ""}}], + [{order: {amount: 3, label: "US", region: "VIP", openedAt: "2030-12-31", balance: 0.5, parcels: [{days: -500, score: 0}, {days: 100, score: 10}, {days: 0, score: 3}], extraField: 1}}, {order: {amount: 3, balance: 0.5, extraField: 1, label: "US", net: "VIP", openedAt: "2030-12-31", parcels: [{adjusted: true, days: -500, level: "VIP", score: 0, tag: true, weighted: 0.5}, {adjusted: true, days: 100, level: "VIP", score: 10, tag: true, weighted: 0.5}, {adjusted: true, days: 0, level: "VIP", score: 3, tag: true, weighted: 0.5}], penalty: true, region: "VIP", review: 0.5, share: null}}], + [{order: {amount: 2.50, label: "日本", region: "Oslo", openedAt: "2024-02-29", balance: 10, parcels: [{days: -500, score: 250}, {days: 18, score: 5}, {days: 250, score: 452}, {days: 0.000001, score: 250}, {days: -1, score: 1000}], extraField: {nested: true}}}, {order: {amount: 2.50, balance: 10, extraField: {nested: true}, label: "日本", net: "Oslo", openedAt: "2024-02-29", parcels: [{adjusted: true, days: -500, level: "Oslo", score: 250, tag: true, weighted: 10}, {adjusted: true, days: 18, level: "Oslo", score: 5, tag: true, weighted: 10}, {adjusted: true, days: 250, level: "Oslo", score: 452, tag: true, weighted: 10}, {adjusted: true, days: 0.000001, level: "Oslo", score: 250, tag: true, weighted: 10}, {adjusted: true, days: -1, level: "Oslo", score: 1000, tag: true, weighted: 10}], penalty: false, region: "Oslo", review: 2.50, share: "日本"}}], + [{order: {amount: 10, label: "3.5", region: "", openedAt: "2000-01-01", balance: 1000, parcels: [{days: 1000000, score: 10}, {days: 10, score: 1.5}, {days: 3, score: 10}, {days: 2.50, score: -500}, {days: 1.5, score: 250}]}}, {order: {amount: 10, balance: 1000, label: "3.5", net: "", openedAt: "2000-01-01", parcels: [{adjusted: true, days: 1000000, level: "", score: 10, tag: true, weighted: 1000}, {adjusted: true, days: 10, level: "", score: 1.5, tag: true, weighted: 1000}, {adjusted: true, days: 3, level: "", score: 10, tag: true, weighted: 1000}, {adjusted: true, days: 2.50, level: "", score: -500, tag: true, weighted: 1000}, {adjusted: true, days: 1.5, level: "", score: 250, tag: true, weighted: 1000}], penalty: false, region: "", review: 1000, share: null}}], + [{order: {region: "x-y", openedAt: "2025-03-20T10:15:30Z", balance: 3, parcels: [{days: 1, score: null}, {days: 194, score: 1.5}]}}, {order: {balance: 3, net: "x-y", openedAt: "2025-03-20T10:15:30Z", parcels: [{adjusted: false, days: 1, level: "x-y", score: null, tag: false, weighted: 0}, {adjusted: false, days: 194, level: "x-y", score: 1.5, tag: false, weighted: 3}], penalty: true, region: "x-y", review: 0, share: ""}}], + [{order: {amount: 10, label: "", region: "日本", openedAt: "1990-06-15", balance: 0.5, parcels: [{days: 0.25, score: -0.01}]}}, {order: {amount: 10, balance: 0.5, label: "", net: "日本", openedAt: "1990-06-15", parcels: [{adjusted: true, days: 0.25, level: "日本", score: -0.01, tag: true, weighted: 0.5}], penalty: true, region: "日本", review: 0.5, share: null}}], + [{order: {amount: -0.01, label: "gold", region: "abc", openedAt: "2025-03-20T10:15:30Z", parcels: [{days: 250, score: 0.000001}]}}, "!error: MissingRequiredInputs"], + [{order: {amount: 1, label: "retail", region: "abc", openedAt: null, balance: 5, parcels: [{days: 10}, {days: 18, score: 7.25}]}}, {order: {amount: 1, balance: 5, label: "retail", net: "abc", openedAt: null, parcels: [{adjusted: true, days: 10, level: "abc", tag: true, weighted: 5}, {adjusted: true, days: 18, level: "abc", score: 7.25, tag: true, weighted: 5}], penalty: false, region: "abc", review: 1, share: "retail"}}], + [{order: {amount: 2, label: null, region: "retail", openedAt: "2000-01-01", balance: 1, parcels: []}}, {order: {amount: 2, balance: 1, label: null, net: "retail", openedAt: "2000-01-01", parcels: [], penalty: true, region: "retail", review: 1, share: null}}], + [{order: {amount: 65, label: "Oslo", region: "12", openedAt: "2024-01-01", balance: 1.5, parcels: []}}, {order: {amount: 65, balance: 1.5, label: "Oslo", net: "1.5", openedAt: "2024-01-01", parcels: [], penalty: true, region: "12", review: 1.5, share: "x"}}], + [{order: {amount: 1000, label: "x", region: "DE", openedAt: null, balance: 50, parcels: [{days: 0.25, score: 1}, {days: 1.5}, {days: 1, score: 0.5}]}}, {order: {amount: 1000, balance: 50, label: "x", net: "DE", openedAt: null, parcels: [{adjusted: true, days: 0.25, level: "A1", score: 1, tag: true, weighted: 50}, {adjusted: true, days: 1.5, level: "A1", tag: true, weighted: 50}, {adjusted: true, days: 1, level: "A1", score: 0.5, tag: true, weighted: 50}], penalty: false, region: "DE", review: 1000, share: "x"}}], + [{order: {amount: 7.25, label: " pad ", region: "A1", openedAt: "2030-12-31", balance: 250, parcels: []}}, {order: {amount: 7.25, balance: 250, label: " pad ", net: "A1", openedAt: "2030-12-31", parcels: [], penalty: false, region: "A1", review: 3, share: " pad "}}], + [{order: {amount: 250, label: "", region: "é ü", openedAt: "2024-02-29", balance: 100, parcels: [], extraField: {nested: true}}}, {order: {amount: 250, balance: 100, extraField: {nested: true}, label: "", net: "é ü", openedAt: "2024-02-29", parcels: [], penalty: false, region: "é ü", review: 100, share: null}}], + ], +} + +// seed 335400 (attempt 0) +{ + name: "a 55: account/members: 4 expression, 2 match, 1 table; 1 root, 6 per-member, 2 top-level computed", + policy: { + models: {account: {days: "number", rate: "number", plan: "string(basic|plus|premium|trial)?", city: "string", birthDate: "date", weight: "number", members: "member[]"}, member: {balance: "number", name: "string"}}, + blocks: [ + {expression: "level", value: "(account.weight + account.rate)"}, + {match: "discount", arms: [["startsWith(account.city, 'x')", "(account.rate == 1000 and 50 <= 1.5)"], ["account.plan == null", "10 == 0"], ["(account.plan ?? '') in ['trial', 'premium']", "not (1.5 != account.weight)"], ["account.plan != null", "account.weight >= account.days"], ["", "all(account.members, (#.points ?? '') in ['US', 'US'])"]]}, + {expression: "member.margin", value: "account.days in [13..197]"}, + {table: "t1", inputs: ["(account.plan ?? '')"], outputs: ["member.points", "member.total[]", "member.ok"], rules: [ + ["'basic', 'trial'", "member.name", "account.weight == 1", "account.days"], + ["", "account.city", "", ""], + ]}, + {expression: "member.segment", value: "string((member.ok ?? 0))"}, + {expression: "member.flag", value: "member.segment"}, + {match: "account.tag", arms: [["(discount or discount)", "(string(level) + '-' + string(level))"], ["(account.plan ?? '') == 'trial'", "((account.city + '-' + account.city) + '-' + (discount ? account.city : account.city))"], ["account.weight >= level", "account.city"], ["", "account.city"]]}, + ], + }, + cases: [ + [{account: {days: 7.25, rate: 10, plan: "basic", city: "NL", birthDate: "2024-02-29", weight: -500, members: [{balance: 50, name: "a"}, {balance: 250, name: "A1"}, {balance: -500, name: "US"}, {balance: -500, name: ""}]}}, {account: {birthDate: "2024-02-29", city: "NL", days: 7.25, members: [{balance: 50, flag: "7.25", margin: false, name: "a", ok: 7.25, points: "a", segment: "7.25", total: [false]}, {balance: 250, flag: "7.25", margin: false, name: "A1", ok: 7.25, points: "A1", segment: "7.25", total: [false]}, {balance: -500, flag: "7.25", margin: false, name: "US", ok: 7.25, points: "US", segment: "7.25", total: [false]}, {balance: -500, flag: "7.25", margin: false, name: "", ok: 7.25, points: "", segment: "7.25", total: [false]}], plan: "basic", rate: 10, tag: "NL", weight: -500}, discount: false, level: -490}], + [{account: {days: 1000000, rate: 46, city: "é ü", birthDate: "2000-01-01", weight: 1000, members: [{balance: 0.000001, name: "日本"}, {balance: 2.50, name: "VIP"}]}}, {account: {birthDate: "2000-01-01", city: "é ü", days: 1000000, members: [{balance: 0.000001, flag: "0", margin: false, name: "日本", ok: null, points: "é ü", segment: "0", total: []}, {balance: 2.50, flag: "0", margin: false, name: "VIP", ok: null, points: "é ü", segment: "0", total: []}], rate: 46, tag: "é ü", weight: 1000}, discount: false, level: 1046}], + [{account: {days: 2, rate: 1.5, plan: null, city: "x", birthDate: "2024-02-29", weight: -500, members: []}}, {account: {birthDate: "2024-02-29", city: "x", days: 2, members: [], plan: null, rate: 1.5, tag: "x", weight: -500}, discount: false, level: -498.5}], + [{account: {days: 10, rate: 7.25, plan: "basic", city: "Zed", birthDate: "2025-03-20T10:15:30Z", weight: 1000, members: [{balance: 1000, name: "x"}]}}, {account: {birthDate: "2025-03-20T10:15:30Z", city: "Zed", days: 10, members: [{balance: 1000, flag: "10", margin: false, name: "x", ok: 10, points: "x", segment: "10", total: [false]}], plan: "basic", rate: 7.25, tag: "1007.25-1007.25", weight: 1000}, discount: true, level: 1007.25}], + [{account: {days: 1.5, rate: -500, plan: "trial", city: "x-y", birthDate: "2024-02-29", weight: 1000000, members: []}}, {account: {birthDate: "2024-02-29", city: "x-y", days: 1.5, members: [], plan: "trial", rate: -500, tag: "x-y-x-y-x-y", weight: 1000000}, discount: false, level: 999500}], + [{account: {days: 10, rate: 50, plan: "trial", city: "-", birthDate: "2025-03-20T10:15:30Z", weight: 5, members: [{balance: 1e3, name: "retail"}, {balance: 50, name: "12"}]}}, {account: {birthDate: "2025-03-20T10:15:30Z", city: "-", days: 10, members: [{balance: 1000, flag: "10", margin: false, name: "retail", ok: 10, points: "retail", segment: "10", total: [false]}, {balance: 50, flag: "10", margin: false, name: "12", ok: 10, points: "12", segment: "10", total: [false]}], plan: "trial", rate: 50, tag: "-----", weight: 5}, discount: false, level: 55}], + [{account: {days: -0.01, rate: 99.99, plan: "plus", city: "VIP", birthDate: "2025-03-20", weight: 10, members: [{balance: 1e3, name: "é ü"}]}}, {account: {birthDate: "2025-03-20", city: "VIP", days: -0.01, members: [{balance: 1000, flag: "0", margin: false, name: "é ü", ok: null, points: "VIP", segment: "0", total: []}], plan: "plus", rate: 99.99, tag: "109.99-109.99", weight: 10}, discount: true, level: 109.99}], + [{account: {days: -0.01, rate: 1, city: "gold", birthDate: "2025-03-20T10:15:30Z", weight: 100, members: [{balance: 0, name: "Zed"}, {balance: 1, name: "US"}]}}, {account: {birthDate: "2025-03-20T10:15:30Z", city: "gold", days: -0.01, members: [{balance: 0, flag: "0", margin: false, name: "Zed", ok: null, points: "gold", segment: "0", total: []}, {balance: 1, flag: "0", margin: false, name: "US", ok: null, points: "gold", segment: "0", total: []}], rate: 1, tag: "gold", weight: 100}, discount: false, level: 101}], + [{account: {days: 0.1, rate: 1, plan: null, city: "abc", birthDate: "2025-03-20T10:15:30Z", weight: 2, members: []}}, {account: {birthDate: "2025-03-20T10:15:30Z", city: "abc", days: 0.1, members: [], plan: null, rate: 1, tag: "abc", weight: 2}, discount: false, level: 3}], + [{account: {days: 0, rate: 485, plan: "plus", city: "VIP", birthDate: "2024-01-01", weight: 18, members: [{balance: 100, name: "abc"}, {balance: 250, name: "日本"}, {balance: 1.5, name: "O'Neil"}, {balance: -0.5, name: "NL"}, {balance: -1, name: "DE"}]}}, {account: {birthDate: "2024-01-01", city: "VIP", days: 0, members: [{balance: 100, flag: "0", margin: false, name: "abc", ok: null, points: "VIP", segment: "0", total: []}, {balance: 250, flag: "0", margin: false, name: "日本", ok: null, points: "VIP", segment: "0", total: []}, {balance: 1.5, flag: "0", margin: false, name: "O'Neil", ok: null, points: "VIP", segment: "0", total: []}, {balance: -0.5, flag: "0", margin: false, name: "NL", ok: null, points: "VIP", segment: "0", total: []}, {balance: -1, flag: "0", margin: false, name: "DE", ok: null, points: "VIP", segment: "0", total: []}], plan: "plus", rate: 485, tag: "503-503", weight: 18}, discount: true, level: 503}], + [{account: {days: 1000, rate: 0.5, plan: "basic", city: "O'Neil", birthDate: "2030-12-31", weight: -0.01, members: [{balance: 123456789.123, name: "Oslo"}, {balance: 185, name: "O'Neil"}]}}, {account: {birthDate: "2030-12-31", city: "O'Neil", days: 1000, members: [{balance: 123456789.123, flag: "1000", margin: false, name: "Oslo", ok: 1000, points: "Oslo", segment: "1000", total: [false]}, {balance: 185, flag: "1000", margin: false, name: "O'Neil", ok: 1000, points: "O'Neil", segment: "1000", total: [false]}], plan: "basic", rate: 0.5, tag: "O'Neil", weight: -0.01}, discount: false, level: 0.49}], + [{account: {days: 1000, rate: 1.5, plan: null, city: "é ü", birthDate: "2024-01-01", weight: 1e3, members: [{balance: 7.25, name: "VIP"}]}}, {account: {birthDate: "2024-01-01", city: "é ü", days: 1000, members: [{balance: 7.25, flag: "0", margin: false, name: "VIP", ok: null, points: "é ü", segment: "0", total: []}], plan: null, rate: 1.5, tag: "é ü", weight: 1000}, discount: false, level: 1001.5}], + [{account: {days: 0.1, rate: 0, plan: "basic", city: "3.5", birthDate: "2025-03-20T10:15:30Z", weight: 1.5, members: [{balance: 5, name: " pad "}]}}, {account: {birthDate: "2025-03-20T10:15:30Z", city: "3.5", days: 0.1, members: [{balance: 5, flag: "0.1", margin: false, name: " pad ", ok: 0.1, points: " pad ", segment: "0.1", total: [false]}], plan: "basic", rate: 0, tag: "1.5-1.5", weight: 1.5}, discount: true, level: 1.5}], + [{account: {days: 65, rate: 175, plan: "basic", city: "O'Neil", birthDate: "1990-06-15", weight: 1000000, members: []}}, {account: {birthDate: "1990-06-15", city: "O'Neil", days: 65, members: [], plan: "basic", rate: 175, tag: "1000175-1000175", weight: 1000000}, discount: true, level: 1000175}], + [{account: {days: 7.25, rate: 0.000001, city: "-", birthDate: "2025-03-20T10:15:30Z", weight: 1000, members: [{balance: 10, name: "retail"}, {balance: 250, name: "abc"}, {balance: 100, name: "é ü"}, {balance: 0.000001, name: "VIP"}]}}, {account: {birthDate: "2025-03-20T10:15:30Z", city: "-", days: 7.25, members: [{balance: 10, flag: "0", margin: false, name: "retail", ok: null, points: "-", segment: "0", total: []}, {balance: 250, flag: "0", margin: false, name: "abc", ok: null, points: "-", segment: "0", total: []}, {balance: 100, flag: "0", margin: false, name: "é ü", ok: null, points: "-", segment: "0", total: []}, {balance: 0.000001, flag: "0", margin: false, name: "VIP", ok: null, points: "-", segment: "0", total: []}], rate: 0.000001, tag: "-", weight: 1000}, discount: false, level: 1000.000001}], + [{account: {days: 2, rate: 7.25, plan: null, city: "O'Neil", birthDate: "2000-01-01", weight: 10, members: [{balance: 50, name: "gold"}, {balance: 10, name: "é ü"}, {balance: 1000, name: "x-y"}]}}, {account: {birthDate: "2000-01-01", city: "O'Neil", days: 2, members: [{balance: 50, flag: "0", margin: false, name: "gold", ok: null, points: "O'Neil", segment: "0", total: []}, {balance: 10, flag: "0", margin: false, name: "é ü", ok: null, points: "O'Neil", segment: "0", total: []}, {balance: 1000, flag: "0", margin: false, name: "x-y", ok: null, points: "O'Neil", segment: "0", total: []}], plan: null, rate: 7.25, tag: "O'Neil", weight: 10}, discount: false, level: 17.25}], + [{account: {days: 18, rate: 0.5, city: "x", birthDate: "1990-06-15", weight: 1000, members: [{balance: -0, name: "US"}, {balance: 1, name: "retail"}, {balance: 1000, name: "3.5"}, {balance: 99999999999999999999, name: "US"}]}}, {account: {birthDate: "1990-06-15", city: "x", days: 18, members: [{balance: 0, flag: "0", margin: true, name: "US", ok: null, points: "x", segment: "0", total: []}, {balance: 1, flag: "0", margin: true, name: "retail", ok: null, points: "x", segment: "0", total: []}, {balance: 1000, flag: "0", margin: true, name: "3.5", ok: null, points: "x", segment: "0", total: []}, {balance: 99999999999999999999, flag: "0", margin: true, name: "US", ok: null, points: "x", segment: "0", total: []}], rate: 0.5, tag: "x", weight: 1000}, discount: false, level: 1000.5}], + ], +} + +// seed 335500 (attempt 0) +{ + name: "a 56: shipment/companies: 3 expression, 1 table; 1 root, 3 per-member, 0 top-level computed", + policy: { + models: {shipment: {qty: "number", amount: "number", balance: "number", vip: "boolean", verified: "boolean", insured: "boolean", companies: "company[]"}, company: {days: "number", income: "number", code: "string", kind: "string(retail|corporate)"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {table: "t1", inputs: ["shipment.amount", "(baseRate * shipment.qty)"], outputs: ["company.surcharge"], rules: [ + ["", ">= 1.5", "baseRate"], + ["", "", "shipment.qty"], + ]}, + {expression: "company.ok", value: "company.kind in ['retail', 'corporate']"}, + {expression: "shipment.share", value: "sum(map(shipment.companies, 0))"}, + {expression: "company.weighted", value: "(((min(map(shipment.companies, 0)) ?? 0) + (shipment.share * shipment.share)) + sum(map(shipment.companies, #.days)))"}, + ], + }, + cases: [ + [{baseRate: 100, shipment: {qty: -0, amount: 99999999999999999999, balance: 7.25, vip: true, verified: true, insured: false, companies: []}}, {baseRate: 100, shipment: {amount: 99999999999999999999, balance: 7.25, companies: [], insured: false, qty: 0, share: 0, verified: true, vip: true}}], + [{baseRate: 100, shipment: {qty: 307, amount: 0.5, balance: 5, vip: false, verified: false, insured: true, companies: [{days: 1, income: 100, code: "O'Neil", kind: "corporate"}, {days: 7.25, income: 1e3, code: " pad ", kind: "retail"}, {days: 2, income: 0.25, code: "x-y", kind: "corporate"}, {days: 1000000, income: 1.5, code: "a", kind: "retail"}]}}, {baseRate: 100, shipment: {amount: 0.5, balance: 5, companies: [{code: "O'Neil", days: 1, income: 100, kind: "corporate", ok: true, surcharge: 100, weighted: 1000010.25}, {code: " pad ", days: 7.25, income: 1000, kind: "retail", ok: true, surcharge: 100, weighted: 1000010.25}, {code: "x-y", days: 2, income: 0.25, kind: "corporate", ok: true, surcharge: 100, weighted: 1000010.25}, {code: "a", days: 1000000, income: 1.5, kind: "retail", ok: true, surcharge: 100, weighted: 1000010.25}], insured: true, qty: 307, share: 0, verified: false, vip: false}}], + [{baseRate: -2, shipment: {qty: 0.25, amount: 0, balance: 5, vip: true, verified: true, insured: false, companies: []}}, {baseRate: -2, shipment: {amount: 0, balance: 5, companies: [], insured: false, qty: 0.25, share: 0, verified: true, vip: true}}], + [{baseRate: 0, shipment: {qty: 1, amount: 1, balance: 123456789.123, vip: true, verified: true, insured: true, companies: [{days: 123456789.123, income: 0.1, code: "abc", kind: "retail"}]}}, {baseRate: 0, shipment: {amount: 1, balance: 123456789.123, companies: [{code: "abc", days: 123456789.123, income: 0.1, kind: "retail", ok: true, surcharge: 1, weighted: 123456789.123}], insured: true, qty: 1, share: 0, verified: true, vip: true}}], + [{baseRate: 1, shipment: {qty: 0.1, amount: 0.5, balance: 0, vip: false, verified: true, insured: false, companies: [{days: -0.5, income: -0.01, code: "", kind: "retail"}, {days: 99999999999999999999, income: 0.1, code: "Zed", kind: "corporate"}, {days: 99.99, income: 0, code: "12", kind: "corporate"}, {days: -0, income: 1000, code: "gold", kind: "retail"}]}}, {baseRate: 1, shipment: {amount: 0.5, balance: 0, companies: [{code: "", days: -0.5, income: -0.01, kind: "retail", ok: true, surcharge: 0.1, weighted: 100000000000000000098.49}, {code: "Zed", days: 99999999999999999999, income: 0.1, kind: "corporate", ok: true, surcharge: 0.1, weighted: 100000000000000000098.49}, {code: "12", days: 99.99, income: 0, kind: "corporate", ok: true, surcharge: 0.1, weighted: 100000000000000000098.49}, {code: "gold", days: 0, income: 1000, kind: "retail", ok: true, surcharge: 0.1, weighted: 100000000000000000098.49}], insured: false, qty: 0.1, share: 0, verified: true, vip: false}}], + [{baseRate: 0, shipment: {qty: 2, amount: 0, balance: -0, vip: true, verified: true, insured: true, companies: [{days: 1, income: 1000, code: "VIP", kind: "corporate"}, {days: -0.01, income: -500, code: "a-b-c", kind: "retail"}]}}, {baseRate: 0, shipment: {amount: 0, balance: 0, companies: [{code: "VIP", days: 1, income: 1000, kind: "corporate", ok: true, surcharge: 2, weighted: 0.99}, {code: "a-b-c", days: -0.01, income: -500, kind: "retail", ok: true, surcharge: 2, weighted: 0.99}], insured: true, qty: 2, share: 0, verified: true, vip: true}}], + [{baseRate: -2, shipment: {qty: 0, amount: -1, balance: 10, vip: false, verified: false, insured: false, companies: [{days: 1.5, income: 1000000, code: " pad ", kind: "retail"}, {days: 0.25, income: -500, code: "O'Neil", kind: "retail"}]}}, {baseRate: -2, shipment: {amount: -1, balance: 10, companies: [{code: " pad ", days: 1.5, income: 1000000, kind: "retail", ok: true, surcharge: 0, weighted: 1.75}, {code: "O'Neil", days: 0.25, income: -500, kind: "retail", ok: true, surcharge: 0, weighted: 1.75}], insured: false, qty: 0, share: 0, verified: false, vip: false}}], + [{baseRate: -2, shipment: {qty: 0, amount: 0.25, balance: 0.1, vip: true, verified: false, insured: false, companies: [{days: 99.99, income: 0.5, code: "Zed", kind: "corporate"}]}}, {baseRate: -2, shipment: {amount: 0.25, balance: 0.1, companies: [{code: "Zed", days: 99.99, income: 0.5, kind: "corporate", ok: true, surcharge: 0, weighted: 99.99}], insured: false, qty: 0, share: 0, verified: false, vip: true}}], + [{baseRate: 0, shipment: {qty: -500, amount: 0, balance: 1e3, vip: false, verified: false, insured: true, companies: []}}, {baseRate: 0, shipment: {amount: 0, balance: 1000, companies: [], insured: true, qty: -500, share: 0, verified: false, vip: false}}], + [{baseRate: -2, shipment: {qty: 99999999999999999999, amount: 2, balance: 0, vip: false, verified: false, insured: true, companies: [{days: 1.5, income: 18, code: "DE", kind: "retail"}]}}, {baseRate: -2, shipment: {amount: 2, balance: 0, companies: [{code: "DE", days: 1.5, income: 18, kind: "retail", ok: true, surcharge: 99999999999999999999, weighted: 1.5}], insured: true, qty: 99999999999999999999, share: 0, verified: false, vip: false}}], + [{baseRate: 10, shipment: {qty: 7.25, amount: 5, balance: 0, vip: false, verified: true, insured: false, companies: [{days: 123456789.123, income: 0, code: "é ü", kind: "retail"}, {days: 123456789.123, income: 0.000001, code: "a-b-c", kind: "corporate"}, {days: 123456789.123, income: 1000000, code: "3.5", kind: "corporate"}, {days: 0, income: -500, code: "abc", kind: "corporate"}]}}, {baseRate: 10, shipment: {amount: 5, balance: 0, companies: [{code: "é ü", days: 123456789.123, income: 0, kind: "retail", ok: true, surcharge: 10, weighted: 370370367.369}, {code: "a-b-c", days: 123456789.123, income: 0.000001, kind: "corporate", ok: true, surcharge: 10, weighted: 370370367.369}, {code: "3.5", days: 123456789.123, income: 1000000, kind: "corporate", ok: true, surcharge: 10, weighted: 370370367.369}, {code: "abc", days: 0, income: -500, kind: "corporate", ok: true, surcharge: 10, weighted: 370370367.369}], insured: false, qty: 7.25, share: 0, verified: true, vip: false}}], + [{baseRate: 100, shipment: {qty: 0.5, amount: 397, balance: -0.5, vip: true, verified: true, insured: false, companies: []}}, {baseRate: 100, shipment: {amount: 397, balance: -0.5, companies: [], insured: false, qty: 0.5, share: 0, verified: true, vip: true}}], + [{baseRate: 0, shipment: {qty: 99999999999999999999, amount: 0.25, balance: 250, vip: true, verified: false, insured: true, companies: []}}, {baseRate: 0, shipment: {amount: 0.25, balance: 250, companies: [], insured: true, qty: 99999999999999999999, share: 0, verified: false, vip: true}}], + ], +} + +// seed 335600 (attempt 0) +{ + name: "a 57: order/parcels: 4 expression, 2 match; 2 root, 3 per-member, 1 top-level computed", + policy: { + models: {order: {qty: "number", openedAt: "date", status: "string(open|closed|pending)", parcels: "parcel[]?"}, parcel: {age: "number?", region: "string?", status: "string(open|closed|pending)?"}}, + blocks: [ + {match: "parcel.adjusted", arms: [["(parcel.share and order.flag)", "len((parcel.region ?? '')) <= parcel.level"], ["order.openedAt < d('2024-01-01')", "(parcel.share or order.flag)"], ["none((order.parcels ?? []), (#.age ?? 0) != (#.age ?? 0))", "order.flag"], ["all((order.parcels ?? []), 10 != (#.age ?? 0))", "contains((parcel.region ?? ''), 'retail')"], ["", "parcel.share"]]}, + {match: "rank", arms: [["(order.flag or order.flag)", "(all((order.parcels ?? []), #.level in [-5..135]) ? order.openedAt.month() : (avg(map((order.parcels ?? []), ((#.age ?? 0) * (#.age ?? 0)))) ?? 0))"], ["", "order.qty"]]}, + {expression: "order.flag", value: "(order.qty <= 250 and order.qty <= 0.25)"}, + {expression: "parcel.level", value: "order.qty"}, + {expression: "order.grade", value: "floor(order.qty)"}, + {expression: "parcel.share", value: "(parcel.status ?? '') in ['open', 'pending']"}, + ], + }, + cases: [ + [{order: {qty: 1e3, openedAt: "2024-02-29", status: "open", parcels: [{age: 1000, region: "a-b-c", status: "open"}]}}, {order: {flag: false, grade: 1000, openedAt: "2024-02-29", parcels: [{adjusted: false, age: 1000, region: "a-b-c", share: true, status: "open"}], qty: 1000, status: "open"}, rank: 1000}], + [{order: {qty: 0.000001, openedAt: "2025-03-20T10:15:30Z", status: "closed", parcels: [{age: 1, region: "US", status: "closed"}, {age: 123456789.123, region: "é ü", status: "open"}]}}, {order: {flag: true, grade: 0, openedAt: "2025-03-20T10:15:30Z", parcels: [{adjusted: true, age: 1, level: 0.000001, region: "US", share: false, status: "closed"}, {adjusted: false, age: 123456789.123, level: 0.000001, region: "é ü", share: true, status: "open"}], qty: 0.000001, status: "closed"}, rank: 3}], + [{order: {qty: 1000000, openedAt: "2024-01-01", status: "open", parcels: [{age: [1], region: " pad ", status: "closed"}]}}, "!error: InputValidationFailed"], + [{order: {qty: -0, openedAt: "2000-01-01", status: "pending", parcels: [{age: 99.99, region: "retail", status: "pending"}], extraField: "x"}}, {order: {extraField: "x", flag: true, grade: 0, openedAt: "2000-01-01", parcels: [{adjusted: false, age: 99.99, level: 0, region: "retail", share: true, status: "pending"}], qty: 0, status: "pending"}, rank: 1}], + [{order: {qty: 0.25, openedAt: "2025-03-20", status: "open", parcels: [{region: null, status: "open"}]}}, {order: {flag: true, grade: 0, openedAt: "2025-03-20", parcels: [{adjusted: true, level: 0.25, region: null, share: true, status: "open"}], qty: 0.25, status: "open"}, rank: 3}], + [{order: {qty: 0.25, openedAt: "2025-03-20T10:15:30Z", status: "closed", parcels: [{age: -500, region: "a", status: "closed"}, {age: 1000000, region: "", status: "open"}]}}, {order: {flag: true, grade: 0, openedAt: "2025-03-20T10:15:30Z", parcels: [{adjusted: true, age: -500, level: 0.25, region: "a", share: false, status: "closed"}, {adjusted: true, age: 1000000, level: 0.25, region: "", share: true, status: "open"}], qty: 0.25, status: "closed"}, rank: 3}], + [{order: {qty: 1, openedAt: "2025-03-20T10:15:30Z", status: "closed", parcels: [{age: -0, region: "", status: "open"}, {age: 123456789.123, region: "", status: "pending"}, {age: 100, region: "A1", status: "closed"}]}}, {order: {flag: false, grade: 1, openedAt: "2025-03-20T10:15:30Z", parcels: [{adjusted: false, age: 0, region: "", share: true, status: "open"}, {adjusted: false, age: 123456789.123, region: "", share: true, status: "pending"}, {adjusted: false, age: 100, region: "A1", share: false, status: "closed"}], qty: 1, status: "closed"}, rank: 1}], + [{order: {qty: 10, openedAt: "2030-12-31", status: "open", parcels: [{age: 1, region: " pad ", status: "open"}, {age: 2.50, region: "abc", status: "open"}]}}, {order: {flag: false, grade: 10, openedAt: "2030-12-31", parcels: [{adjusted: false, age: 1, region: " pad ", share: true, status: "open"}, {adjusted: false, age: 2.50, region: "abc", share: true, status: "open"}], qty: 10, status: "open"}, rank: 10}], + [{order: {qty: 250, openedAt: "2030-12-31", status: "closed", parcels: [{age: 10, region: "retail", status: "open"}, {age: 99.99, region: "NL", status: "closed"}, {age: 10, region: "3.5", status: "closed"}, {age: -500, region: "3.5", status: "open"}, {age: 250, region: "abc", status: "open"}]}}, {order: {flag: false, grade: 250, openedAt: "2030-12-31", parcels: [{adjusted: false, age: 10, region: "retail", share: true, status: "open"}, {adjusted: false, age: 99.99, region: "NL", share: false, status: "closed"}, {adjusted: false, age: 10, region: "3.5", share: false, status: "closed"}, {adjusted: false, age: -500, region: "3.5", share: true, status: "open"}, {adjusted: false, age: 250, region: "abc", share: true, status: "open"}], qty: 250, status: "closed"}, rank: 250}], + [{order: {qty: -500, openedAt: "2025-03-20", status: "open", parcels: [{age: -0, region: "a", status: false}]}}, "!error: InputValidationFailed"], + [{order: {qty: 0.1, openedAt: "1990-06-15", status: "open", parcels: [{age: null, status: "open"}, {region: null}]}}, {order: {flag: true, grade: 0, openedAt: "1990-06-15", parcels: [{adjusted: true, age: null, level: 0.1, share: true, status: "open"}, {adjusted: true, level: 0.1, region: null, share: false}], qty: 0.1, status: "open"}, rank: 6}], + [{order: {qty: 7.25, openedAt: "2030-12-31", status: "closed", parcels: [{age: 99.99, region: "Oslo", status: "open"}, {age: 2, region: "-", status: "open"}, {age: 1000000, region: "日本", status: "pending"}]}}, {order: {flag: false, grade: 7, openedAt: "2030-12-31", parcels: [{adjusted: false, age: 99.99, region: "Oslo", share: true, status: "open"}, {adjusted: false, age: 2, region: "-", share: true, status: "open"}, {adjusted: false, age: 1000000, region: "日本", share: true, status: "pending"}], qty: 7.25, status: "closed"}, rank: 7.25}], + [{order: {qty: 7.25, openedAt: "1990-06-15", status: "open", parcels: [{age: 100, region: "retail", status: false}, {age: 65, region: "Zed", status: "pending"}, {age: 0.5, region: "-", status: "open"}]}}, "!error: InputValidationFailed"], + [{order: {qty: 250, openedAt: "2025-03-20", status: "pending", parcels: [{age: 100, region: "a-b-c", status: "open"}, {age: 0, region: null, status: "open"}]}}, {order: {flag: false, grade: 250, openedAt: "2025-03-20", parcels: [{adjusted: false, age: 100, region: "a-b-c", share: true, status: "open"}, {adjusted: false, age: 0, region: null, share: true, status: "open"}], qty: 250, status: "pending"}, rank: 250}], + [{order: {qty: -1, openedAt: "2025-03-20T10:15:30Z", status: "pending", parcels: [{age: 0.000001, region: "retail", status: "pending"}]}}, {order: {flag: true, grade: -1, openedAt: "2025-03-20T10:15:30Z", parcels: [{adjusted: false, age: 0.000001, level: -1, region: "retail", share: true, status: "pending"}], qty: -1, status: "pending"}, rank: 3}], + [{order: {qty: 10, openedAt: "2024-01-01", status: "open", parcels: [{age: true, region: "", status: "open"}, {age: 0.1, region: "a", status: "open"}]}}, "!error: InputValidationFailed"], + [{order: {qty: 5, openedAt: "2025-03-20", status: "open", parcels: [{age: 0.5, region: "a", status: false}, {age: 100, region: "日本", status: "open"}, {age: 123456789.123, region: "US", status: "pending"}, {age: 1e3, region: "12", status: "closed"}, {age: 0.5, region: "Zed", status: "open"}]}}, "!error: InputValidationFailed"], + [{order: {qty: 123456789.123, openedAt: "2024-02-29", status: "open", parcels: [{age: 99999999999999999999, region: "Oslo", status: "open"}, {age: 0.25, region: "O'Neil", status: "open"}]}}, {order: {flag: false, grade: 123456789, openedAt: "2024-02-29", parcels: [{adjusted: false, age: 99999999999999999999, region: "Oslo", share: true, status: "open"}, {adjusted: false, age: 0.25, region: "O'Neil", share: true, status: "open"}], qty: 123456789.123, status: "open"}, rank: 123456789.123}], + [{order: {qty: 7.25, openedAt: "2025-03-20", status: "pending", parcels: [{age: 1e3, region: "abc", status: "open"}, {age: 1000000, region: "-", status: "open"}, {age: 2, region: "gold", status: "open"}]}}, {order: {flag: false, grade: 7, openedAt: "2025-03-20", parcels: [{adjusted: false, age: 1000, region: "abc", share: true, status: "open"}, {adjusted: false, age: 1000000, region: "-", share: true, status: "open"}, {adjusted: false, age: 2, region: "gold", share: true, status: "open"}], qty: 7.25, status: "pending"}, rank: 7.25}], + ], +} + +// seed 335700 (attempt 0) +{ + name: "a 58: customer/loans: 2 assertion, 4 expression, 1 match, 1 table; 0 root, 3 per-member, 7 top-level computed", + policy: { + models: {customer: {limit: "number?", dueDate: "date", openedAt: "date?", status: "string(open|closed|pending)", code: "string", weight: "number", loans: "loan[]"}, loan: {limit: "number?", amount: "number", urgent: "boolean"}}, + blocks: [ + {expression: "bucket", value: "customer.weight"}, + {expression: "level", value: "customer.code"}, + {expression: "loan.adjusted", value: "loan.limit != null"}, + {table: "t4", inputs: ["customer.weight", "customer.status"], outputs: ["quota", "health", "tag"], rules: [ + ["", "", "level", "level", "(customer.limit ?? 0) > 18"], + ["> 5", "'pending'", "level", "level", ""], + ["", "", "customer.code", "(customer.code + '-' + 'VIP')", "2 <= 1000"], + ["<= 2", "'open', 'closed'", "customer.code", "level", "customer.weight > 0.5"], + ]}, + {match: "loan.total", arms: [["0.25 < (customer.limit ?? 0)", "bucket"], ["", "customer.weight"]]}, + {assertion: "review", conditions: [["or", "all(customer.loans, (#.limit ?? 0) == 0)", 1], ["and", "none(customer.loans, not (#.urgent))", 0], ["or", "(quota ?? '') in ['x', 'US']", 0]]}, + {assertion: "loan.surcharge", conditions: [["and", "(customer.openedAt ?? d('2025-01-01')).year() != loan.amount", 0], ["and", "18 == (loan.limit ?? 0)", 2], ["and", "all(customer.loans, #.amount == #.amount)", 0], ["or", "loan.amount > loan.total", 0]]}, + {expression: "risk", value: "customer.dueDate.add(4, 'year')"}, + ], + }, + cases: [ + [{customer: {limit: null, dueDate: "1990-06-15", openedAt: "2024-02-29", status: "open", code: "gold", weight: 2, loans: [{amount: 2.50, urgent: true}, {limit: null, amount: 2, urgent: false}, {limit: 10, amount: 0.25, urgent: false}, {amount: 5, urgent: false}]}}, {customer: {code: "gold", dueDate: "1990-06-15", limit: null, loans: [{adjusted: false, amount: 2.50, surcharge: false, total: 2, urgent: true}, {adjusted: false, amount: 2, limit: null, surcharge: false, total: 2, urgent: false}, {adjusted: true, amount: 0.25, limit: 10, surcharge: false, total: 2, urgent: false}, {adjusted: false, amount: 5, surcharge: false, total: 2, urgent: false}], openedAt: "2024-02-29", status: "open", weight: 2}, health: "gold", level: "gold", quota: "gold", review: false, risk: "1994-06-15T00:00:00Z", tag: false}], + [{customer: {limit: 1000000, dueDate: "2030-12-31", openedAt: "2025-03-20T10:15:30Z", status: "open", code: "x-y", weight: 0.000001, loans: [{limit: 123456789.123, amount: 123456789.123, urgent: false}]}}, {bucket: 0.000001, customer: {code: "x-y", dueDate: "2030-12-31", limit: 1000000, loans: [{adjusted: true, amount: 123456789.123, limit: 123456789.123, surcharge: false, total: 0.000001, urgent: false}], openedAt: "2025-03-20T10:15:30Z", status: "open", weight: 0.000001}, health: "x-y", level: "x-y", quota: "x-y", review: false, risk: "2034-12-31T00:00:00Z", tag: true}], + [{customer: {limit: 0, dueDate: "2024-02-29", openedAt: "2025-03-20", status: "closed", code: "A1", weight: 99999999999999999999, loans: [{limit: 5, amount: 100, urgent: true}]}}, {customer: {code: "A1", dueDate: "2024-02-29", limit: 0, loans: [{adjusted: true, amount: 100, limit: 5, surcharge: false, total: 99999999999999999999, urgent: true}], openedAt: "2025-03-20", status: "closed", weight: 99999999999999999999}, health: "A1", level: "A1", quota: "A1", review: false, risk: "2028-02-29T00:00:00Z", tag: false}], + [{customer: {limit: -0.01, dueDate: "2000-01-01", openedAt: "2030-12-31", status: "open", code: "gold", weight: 256, loans: [{limit: 5, amount: 0.1, urgent: true}, {limit: 99999999999999999999, amount: 1000, urgent: false}]}}, {customer: {code: "gold", dueDate: "2000-01-01", limit: -0.01, loans: [{adjusted: true, amount: 0.1, limit: 5, surcharge: false, total: 256, urgent: true}, {adjusted: true, amount: 1000, limit: 99999999999999999999, surcharge: false, total: 256, urgent: false}], openedAt: "2030-12-31", status: "open", weight: 256}, health: "gold", level: "gold", quota: "gold", review: false, risk: "2004-01-01T00:00:00Z", tag: false}], + [{customer: {limit: 0.25, dueDate: "1990-06-15", openedAt: "2025-03-20", status: "closed", code: "x", weight: -0, loans: [{limit: 65, amount: 0.000001, urgent: false}, {limit: 10, amount: 100, urgent: true}, {limit: 2, amount: 0.5, urgent: false}, {limit: 18, amount: 295, urgent: false}, {limit: 2, amount: 0.5, urgent: true}], extraField: 1}}, {customer: {code: "x", dueDate: "1990-06-15", extraField: 1, limit: 0.25, loans: [{adjusted: true, amount: 0.000001, limit: 65, surcharge: false, total: 0, urgent: false}, {adjusted: true, amount: 100, limit: 10, surcharge: false, total: 0, urgent: true}, {adjusted: true, amount: 0.5, limit: 2, surcharge: false, total: 0, urgent: false}, {adjusted: true, amount: 295, limit: 18, surcharge: true, total: 0, urgent: false}, {adjusted: true, amount: 0.5, limit: 2, surcharge: false, total: 0, urgent: true}], openedAt: "2025-03-20", status: "closed", weight: 0}, health: "x", level: "x", quota: "x", review: false, risk: "1994-06-15T00:00:00Z", tag: false}], + [{customer: {limit: 2, dueDate: "2000-01-01", openedAt: "2025-03-20", status: "open", code: "-", weight: -0.5, loans: []}}, {customer: {code: "-", dueDate: "2000-01-01", limit: 2, loans: [], openedAt: "2025-03-20", status: "open", weight: -0.5}, health: "-", level: "-", quota: "-", review: false, risk: "2004-01-01T00:00:00Z", tag: false}], + [{customer: {limit: null, dueDate: "1990-06-15", openedAt: null, status: "open", code: "", weight: -0.01, loans: [{limit: 18, amount: 2.50, urgent: true}, {limit: -0, amount: 0.5, urgent: false}, {limit: 0, amount: 227, urgent: true}, {amount: -500, urgent: true}]}}, {customer: {code: "", dueDate: "1990-06-15", limit: null, loans: [{adjusted: true, amount: 2.50, limit: 18, surcharge: true, total: -0.01, urgent: true}, {adjusted: true, amount: 0.5, limit: 0, surcharge: false, total: -0.01, urgent: false}, {adjusted: true, amount: 227, limit: 0, surcharge: false, total: -0.01, urgent: true}, {adjusted: false, amount: -500, surcharge: false, total: -0.01, urgent: true}], openedAt: null, status: "open", weight: -0.01}, health: "", level: "", quota: "", review: false, risk: "1994-06-15T00:00:00Z", tag: false}], + [{customer: {limit: 250, dueDate: "2025-03-20T10:15:30Z", openedAt: "2025-03-20T10:15:30Z", status: "open", code: "a", weight: 99.99, loans: []}}, {customer: {code: "a", dueDate: "2025-03-20T10:15:30Z", limit: 250, loans: [], openedAt: "2025-03-20T10:15:30Z", status: "open", weight: 99.99}, health: "a", level: "a", quota: "a", review: false, risk: "2029-03-20T10:15:30Z", tag: true}], + [{customer: {limit: 0.1, dueDate: "2030-12-31", status: "open", code: "US", weight: -500, loans: [{amount: 18, urgent: false}, {limit: 2.50, amount: 0, urgent: false}, {limit: null, amount: -0, urgent: true}]}}, {customer: {code: "US", dueDate: "2030-12-31", limit: 0.1, loans: [{adjusted: false, amount: 18, surcharge: false, total: -500, urgent: false}, {adjusted: true, amount: 0, limit: 2.50, surcharge: false, total: -500, urgent: false}, {adjusted: false, amount: 0, limit: null, surcharge: false, total: -500, urgent: true}], status: "open", weight: -500}, health: "US", level: "US", quota: "US", review: false, risk: "2034-12-31T00:00:00Z", tag: false}], + [{customer: {dueDate: "2030-12-31", openedAt: "2024-02-29", status: "pending", code: "日本", weight: 0.000001, loans: [{limit: 0, amount: 0, urgent: false}, {amount: 1e3, urgent: true}]}}, {customer: {code: "日本", dueDate: "2030-12-31", loans: [{adjusted: true, amount: 0, limit: 0, surcharge: false, total: 0.000001, urgent: false}, {adjusted: false, amount: 1000, surcharge: false, total: 0.000001, urgent: true}], openedAt: "2024-02-29", status: "pending", weight: 0.000001}, health: "日本", level: "日本", quota: "日本", review: false, risk: "2034-12-31T00:00:00Z", tag: false}], + [{customer: {limit: 2.50, dueDate: "2024-01-01", openedAt: "2000-01-01", status: "open", code: "é ü", weight: 5, loans: [{limit: null, amount: 0.5, urgent: true}, {limit: null, amount: 1000000, urgent: true}, {limit: 0, amount: 123456789.123, urgent: true}]}}, {bucket: 5, customer: {code: "é ü", dueDate: "2024-01-01", limit: 2.50, loans: [{adjusted: false, amount: 0.5, limit: null, surcharge: false, total: 5, urgent: true}, {adjusted: false, amount: 1000000, limit: null, surcharge: false, total: 5, urgent: true}, {adjusted: true, amount: 123456789.123, limit: 0, surcharge: false, total: 5, urgent: true}], openedAt: "2000-01-01", status: "open", weight: 5}, health: "é ü", level: "é ü", quota: "é ü", review: false, risk: "2028-01-01T00:00:00Z", tag: false}], + [{customer: {limit: -0, dueDate: "2024-02-29", openedAt: "2000-01-01", status: "pending", code: "US", weight: 0.5, loans: [{limit: 1, amount: -500, urgent: true}]}}, {customer: {code: "US", dueDate: "2024-02-29", limit: 0, loans: [{adjusted: true, amount: -500, limit: 1, surcharge: false, total: 0.5, urgent: true}], openedAt: "2000-01-01", status: "pending", weight: 0.5}, health: "US", level: "US", quota: "US", review: true, risk: "2028-02-29T00:00:00Z", tag: false}], + [{customer: {limit: 5, dueDate: "2024-02-29", openedAt: "2030-12-31", status: "pending", code: "DE", weight: 5, loans: [{limit: 0.25, amount: -0.5, urgent: true}, {limit: 123456789.123, amount: 250, urgent: true}], extraField: "x"}}, {bucket: 5, customer: {code: "DE", dueDate: "2024-02-29", extraField: "x", limit: 5, loans: [{adjusted: true, amount: -0.5, limit: 0.25, surcharge: false, total: 5, urgent: true}, {adjusted: true, amount: 250, limit: 123456789.123, surcharge: false, total: 5, urgent: true}], openedAt: "2030-12-31", status: "pending", weight: 5}, health: "DE", level: "DE", quota: "DE", review: false, risk: "2028-02-29T00:00:00Z", tag: false}], + [{customer: {limit: 0.000001, dueDate: "2030-12-31", openedAt: "2025-03-20T10:15:30Z", status: "closed", code: "x", weight: 99999999999999999999, loans: []}}, {customer: {code: "x", dueDate: "2030-12-31", limit: 0.000001, loans: [], openedAt: "2025-03-20T10:15:30Z", status: "closed", weight: 99999999999999999999}, health: "x", level: "x", quota: "x", review: true, risk: "2034-12-31T00:00:00Z", tag: false}], + [{customer: {dueDate: "2025-03-20", status: "closed", code: "O'Neil", weight: 0.1, loans: [{limit: 123456789.123, amount: 5, urgent: false}, {limit: 100, amount: -0.5, urgent: false}]}}, {customer: {code: "O'Neil", dueDate: "2025-03-20", loans: [{adjusted: true, amount: 5, limit: 123456789.123, surcharge: false, total: 0.1, urgent: false}, {adjusted: true, amount: -0.5, limit: 100, surcharge: false, total: 0.1, urgent: false}], status: "closed", weight: 0.1}, health: "O'Neil", level: "O'Neil", quota: "O'Neil", review: false, risk: "2029-03-20T00:00:00Z", tag: false}], + [{customer: {limit: 0.000001, dueDate: "2030-12-31", openedAt: "2000-01-01", status: "open", code: "", weight: -1, loans: [{limit: 0, amount: 0.000001, urgent: true}]}}, {customer: {code: "", dueDate: "2030-12-31", limit: 0.000001, loans: [{adjusted: true, amount: 0.000001, limit: 0, surcharge: false, total: -1, urgent: true}], openedAt: "2000-01-01", status: "open", weight: -1}, health: "", level: "", quota: "", review: false, risk: "2034-12-31T00:00:00Z", tag: false}], + [{customer: {limit: null, dueDate: "2024-02-29", openedAt: "2030-12-31", status: "open", code: "x-y", weight: 18, loans: []}}, {customer: {code: "x-y", dueDate: "2024-02-29", limit: null, loans: [], openedAt: "2030-12-31", status: "open", weight: 18}, health: "x-y", level: "x-y", quota: "x-y", review: false, risk: "2028-02-29T00:00:00Z", tag: false}], + [{customer: {limit: 1000, dueDate: "2025-03-20T10:15:30Z", openedAt: "2025-03-20T10:15:30Z", status: "pending", code: "abc", weight: 2, loans: [{limit: 0, amount: 18, urgent: false}, {limit: 99999999999999999999, amount: 1000, urgent: true}, {limit: 250, amount: -0.5, urgent: false}, {limit: 2, amount: 18, urgent: true}, {limit: 250, amount: 10, urgent: true}], extraField: "x"}}, {bucket: 2, customer: {code: "abc", dueDate: "2025-03-20T10:15:30Z", extraField: "x", limit: 1000, loans: [{adjusted: true, amount: 18, limit: 0, surcharge: false, total: 2, urgent: false}, {adjusted: true, amount: 1000, limit: 99999999999999999999, surcharge: false, total: 2, urgent: true}, {adjusted: true, amount: -0.5, limit: 250, surcharge: false, total: 2, urgent: false}, {adjusted: true, amount: 18, limit: 2, surcharge: false, total: 2, urgent: true}, {adjusted: true, amount: 10, limit: 250, surcharge: false, total: 2, urgent: true}], openedAt: "2025-03-20T10:15:30Z", status: "pending", weight: 2}, health: "abc", level: "abc", quota: "abc", review: false, risk: "2029-03-20T10:15:30Z", tag: true}], + [{customer: {limit: 65, dueDate: "2000-01-01", openedAt: "2025-03-20T10:15:30Z", status: "open", code: "", weight: 250, loans: []}}, {customer: {code: "", dueDate: "2000-01-01", limit: 65, loans: [], openedAt: "2025-03-20T10:15:30Z", status: "open", weight: 250}, health: "", level: "", quota: "", review: false, risk: "2004-01-01T00:00:00Z", tag: true}], + [{customer: {limit: true, dueDate: "2000-01-01", openedAt: "2030-12-31", status: "open", code: "US", weight: 10, loans: [{limit: 250, amount: -1, urgent: false}, {limit: 5, amount: 0.5, urgent: true}, {limit: -0.01, amount: -0.5, urgent: true}]}}, "!error: InputValidationFailed"], + [{customer: {limit: 1000, dueDate: "2024-02-29", openedAt: "2025-03-20T10:15:30Z", status: "closed", code: "gold", weight: 1000, loans: [{limit: 99.99, amount: 18, urgent: 1}, {limit: 18, amount: 0, urgent: true}]}}, "!error: InputValidationFailed"], + [{customer: {limit: -0.5, dueDate: "2024-01-01", openedAt: "2000-01-01", status: "pending", code: "", weight: 1000000, loans: [{limit: 1, amount: 2, urgent: false}, {limit: 10, amount: 100, urgent: true}]}}, {customer: {code: "", dueDate: "2024-01-01", limit: -0.5, loans: [{adjusted: true, amount: 2, limit: 1, surcharge: false, total: 1000000, urgent: false}, {adjusted: true, amount: 100, limit: 10, surcharge: false, total: 1000000, urgent: true}], openedAt: "2000-01-01", status: "pending", weight: 1000000}, health: "", level: "", quota: "", review: false, risk: "2028-01-01T00:00:00Z", tag: false}], + [{customer: {limit: 0.25, dueDate: "2025-03-20", openedAt: "2025-03-20T10:15:30Z", status: "pending", code: " pad ", weight: 250, loans: [{limit: 0.5, amount: 0.5, urgent: true}, {limit: 0, amount: 18, urgent: true}, {limit: 2.50, amount: 1, urgent: true}]}}, {customer: {code: " pad ", dueDate: "2025-03-20", limit: 0.25, loans: [{adjusted: true, amount: 0.5, limit: 0.5, surcharge: false, total: 250, urgent: true}, {adjusted: true, amount: 18, limit: 0, surcharge: false, total: 250, urgent: true}, {adjusted: true, amount: 1, limit: 2.50, surcharge: false, total: 250, urgent: true}], openedAt: "2025-03-20T10:15:30Z", status: "pending", weight: 250}, health: " pad ", level: " pad ", quota: " pad ", review: false, risk: "2029-03-20T00:00:00Z", tag: false}], + [{customer: {limit: null, dueDate: "2024-02-29", openedAt: "2025-03-20", status: "pending", code: " pad ", weight: 1, loans: [{limit: null, amount: 1000000, urgent: true}, {limit: 0, amount: 0.000001, urgent: false}, {limit: null, amount: 99999999999999999999, urgent: false}, {limit: 2.50, amount: 5, urgent: false}]}}, {customer: {code: " pad ", dueDate: "2024-02-29", limit: null, loans: [{adjusted: false, amount: 1000000, limit: null, surcharge: false, total: 1, urgent: true}, {adjusted: true, amount: 0.000001, limit: 0, surcharge: false, total: 1, urgent: false}, {adjusted: false, amount: 99999999999999999999, limit: null, surcharge: false, total: 1, urgent: false}, {adjusted: true, amount: 5, limit: 2.50, surcharge: false, total: 1, urgent: false}], openedAt: "2025-03-20", status: "pending", weight: 1}, health: " pad ", level: " pad ", quota: " pad ", review: false, risk: "2028-02-29T00:00:00Z", tag: false}], + [{customer: {limit: 5, dueDate: "1990-06-15", openedAt: "2025-03-20T10:15:30Z", status: "open", code: "x-y", weight: 0.5, loans: [{limit: 1000, amount: 1000, urgent: false}, {limit: 18, amount: -1, urgent: true}, {limit: -0, amount: 0, urgent: true}]}}, {bucket: 0.5, customer: {code: "x-y", dueDate: "1990-06-15", limit: 5, loans: [{adjusted: true, amount: 1000, limit: 1000, surcharge: false, total: 0.5, urgent: false}, {adjusted: true, amount: -1, limit: 18, surcharge: false, total: 0.5, urgent: true}, {adjusted: true, amount: 0, limit: 0, surcharge: false, total: 0.5, urgent: true}], openedAt: "2025-03-20T10:15:30Z", status: "open", weight: 0.5}, health: "x-y", level: "x-y", quota: "x-y", review: false, risk: "1994-06-15T00:00:00Z", tag: false}], + [{customer: {limit: -0, dueDate: "2030-12-31", openedAt: "1990-06-15", code: "", weight: 99999999999999999999, loans: [{limit: -0.5, amount: -0.01, urgent: false}, {limit: 65, amount: 0, urgent: true}, {limit: 0.1, amount: 1000, urgent: true}, {limit: 0.25, amount: 99999999999999999999, urgent: true}, {limit: 0, amount: -0.01, urgent: true}]}}, "!error: MissingRequiredInputs"], + ], +} + +// seed 335800 (attempt 0) +{ + name: "a 59: shipment/parcels: 1 assertion, 3 expression, 2 match, 1 table; 4 root, 4 per-member, 1 top-level computed", + policy: { + models: {shipment: {rate: "number?", amount: "number", kind: "string(retail|corporate)?", age: "number", dueDate: "date", parcels: "parcel[]?"}, parcel: {limit: "number", balance: "number", weight: "number"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {match: "parcel.decision", arms: [["shipment.rate == null", "parcel.weight != threshold"], ["", "(shipment.kind ?? '') != 'corporate'"]]}, + {table: "t2", inputs: [null, "shipment.amount", "shipment.age"], outputs: ["shipment.rank", "shipment.summary", "shipment.fee"], rules: [ + ["", "", ">= 10", "(1000 - shipment.amount)", "'a'", ""], + ["shipment.age == shipment.age", "< 1.5", "> 0.5", "sum(map((shipment.parcels ?? []), (#.balance + #.weight)))", "string(threshold)", "threshold == 1.5"], + ["shipment.age <= (shipment.rate ?? 0)", "", ">= 0.25", "((shipment.rate ?? 0) * (shipment.rate ?? 0))", "(threshold <= 10 ? 'VIP' : 'gold')", "threshold > 3"], + ["((shipment.rate ?? 0) == 50 or 0.5 <= 50)", "2", "", "shipment.amount", "'DE'", "0 <= 0"], + ["threshold in [38..104]", "50", ">= 250", "0", "", ""], + ]}, + {expression: "adjusted", value: "(shipment.summary ?? '') in ['x', 'US']"}, + {match: "parcel.share", arms: [["len((shipment.summary ?? '')) > 2", "((shipment.rate ?? 0)) / (abs(parcel.weight) + 1)"], ["(contains((shipment.summary ?? ''), 'x') and (shipment.rank ?? 0) > parcel.limit)", "shipment.dueDate.month()"], ["shipment.dueDate >= d('2025-01-01')", "shipment.age"], ["not ((parcel.decision or (shipment.fee ?? false)))", "(none((shipment.parcels ?? []), (#.decision and #.decision)) ? parcel.limit : parcel.weight)"], ["", "ceil(parcel.weight)"]]}, + {expression: "parcel.weighted", value: "shipment.dueDate.add(7, 'month')"}, + {expression: "parcel.level", value: "(string((shipment.amount + threshold)) + '-' + trim(((shipment.fee ?? false) ? (shipment.summary ?? '') : (shipment.summary ?? ''))))"}, + {assertion: "shipment.points", conditions: [["or", "(threshold + (shipment.rate ?? 0)) != 5", 0], ["or", "(adjusted and adjusted)", 0], ["or", "(shipment.kind ?? '') in ['retail', 'corporate']", 0]]}, + ], + }, + cases: [ + [{threshold: 100, shipment: {amount: 5, age: 18, dueDate: "2000-01-01"}}, {adjusted: false, shipment: {age: 18, amount: 5, dueDate: "2000-01-01", fee: null, points: true, rank: 995, summary: "a"}, threshold: 100}], + [{threshold: 100, shipment: {amount: 0, age: 1.5, dueDate: "2024-02-29", parcels: [{limit: 1e3, balance: -500, weight: -500}]}}, {adjusted: false, shipment: {age: 1.5, amount: 0, dueDate: "2024-02-29", fee: false, parcels: [{balance: -500, decision: true, level: "100-100", limit: 1000, share: 0, weight: -500, weighted: "2024-09-29T00:00:00Z"}], points: true, rank: -1000, summary: "100"}, threshold: 100}], + [{threshold: 0, shipment: {amount: 0.25, age: 285, dueDate: "2025-03-20", parcels: [{limit: 65, balance: 1000000, weight: 0}, {limit: -1, balance: 2.50, weight: -0}, {limit: -0.5, balance: 1, weight: 3}, {limit: 0.5, balance: 1000, weight: 1000}]}}, {adjusted: false, shipment: {age: 285, amount: 0.25, dueDate: "2025-03-20", fee: false, parcels: [{balance: 1000000, decision: false, level: "0.25-a", limit: 65, share: 285, weight: 0, weighted: "2025-10-20T00:00:00Z"}, {balance: 2.50, decision: false, level: "0.25-a", limit: -1, share: 285, weight: 0, weighted: "2025-10-20T00:00:00Z"}, {balance: 1, decision: true, level: "0.25-a", limit: -0.5, share: 285, weight: 3, weighted: "2025-10-20T00:00:00Z"}, {balance: 1000, decision: true, level: "0.25-a", limit: 0.5, share: 285, weight: 1000, weighted: "2025-10-20T00:00:00Z"}], points: true, rank: 999.75, summary: "a"}, threshold: 0}], + [{threshold: 10, shipment: {rate: null, amount: 1000, kind: null, age: -0, dueDate: "2025-03-20", parcels: [{limit: 18, balance: 50, weight: 0.5}, {limit: -0, balance: 1000, weight: 0.000001}, {limit: 1.5, balance: 50, weight: 5}, {limit: 10, balance: 1000, weight: 0.5}]}}, {adjusted: false, shipment: {age: 0, amount: 1000, dueDate: "2025-03-20", fee: null, kind: null, parcels: [{balance: 50, decision: true, level: "1010-", limit: 18, share: 0, weight: 0.5, weighted: "2025-10-20T00:00:00Z"}, {balance: 1000, decision: true, level: "1010-", limit: 0, share: 0, weight: 0.000001, weighted: "2025-10-20T00:00:00Z"}, {balance: 50, decision: true, level: "1010-", limit: 1.5, share: 0, weight: 5, weighted: "2025-10-20T00:00:00Z"}, {balance: 1000, decision: true, level: "1010-", limit: 10, share: 0, weight: 0.5, weighted: "2025-10-20T00:00:00Z"}], points: true, rank: null, rate: null, summary: null}, threshold: 10}], + [{threshold: 1, shipment: {rate: 1000000, amount: 3, kind: "retail", age: 0.25, dueDate: "2025-03-20", parcels: [{limit: 65, balance: 1, weight: 1000}, {limit: 7.25, balance: 1000, weight: 1000}]}}, {adjusted: false, shipment: {age: 0.25, amount: 3, dueDate: "2025-03-20", fee: false, kind: "retail", parcels: [{balance: 1, decision: true, level: "4-VIP", limit: 65, share: 999.000999000999000999000999, weight: 1000, weighted: "2025-10-20T00:00:00Z"}, {balance: 1000, decision: true, level: "4-VIP", limit: 7.25, share: 999.000999000999000999000999, weight: 1000, weighted: "2025-10-20T00:00:00Z"}], points: true, rank: 1000000000000, rate: 1000000, summary: "VIP"}, threshold: 1}], + [{threshold: -2, shipment: {rate: 123456789.123, amount: 50, kind: "retail", age: 18, dueDate: "2025-03-20T10:15:30Z", parcels: []}}, {adjusted: false, shipment: {age: 18, amount: 50, dueDate: "2025-03-20T10:15:30Z", fee: false, kind: "retail", parcels: [], points: true, rank: 950, rate: 123456789.123, summary: "a"}, threshold: -2}], + [{threshold: 10, shipment: {rate: 1e3, amount: 123456789.123, kind: "corporate", age: 1.5, dueDate: "2000-01-01", parcels: [{limit: 100, balance: -0, weight: 1e3}, {limit: 1e3, balance: 50, weight: 250}]}}, {adjusted: false, shipment: {age: 1.5, amount: 123456789.123, dueDate: "2000-01-01", fee: true, kind: "corporate", parcels: [{balance: 0, decision: false, level: "123456799.123-VIP", limit: 100, share: 0.999000999000999000999000999, weight: 1000, weighted: "2000-08-01T00:00:00Z"}, {balance: 50, decision: false, level: "123456799.123-VIP", limit: 1000, share: 3.9840637450199203187250996016, weight: 250, weighted: "2000-08-01T00:00:00Z"}], points: true, rank: 1000000, rate: 1000, summary: "VIP"}, threshold: 10}], + [{threshold: 10, shipment: {rate: null, amount: 1000, kind: null, age: 7.25, dueDate: "1990-06-15", parcels: null}}, {adjusted: false, shipment: {age: 7.25, amount: 1000, dueDate: "1990-06-15", fee: null, kind: null, parcels: null, points: true, rank: null, rate: null, summary: null}, threshold: 10}], + [{threshold: 0.5, shipment: {rate: 10, amount: 1000, kind: "retail", age: 250, dueDate: "2024-02-29", parcels: [{limit: 2.50, balance: -0.01, weight: 3}, {limit: 3, balance: 487, weight: 2.50}]}}, {adjusted: false, shipment: {age: 250, amount: 1000, dueDate: "2024-02-29", fee: null, kind: "retail", parcels: [{balance: -0.01, decision: true, level: "1000.5-a", limit: 2.50, share: 3, weight: 3, weighted: "2024-09-29T00:00:00Z"}, {balance: 487, decision: true, level: "1000.5-a", limit: 3, share: 3, weight: 2.50, weighted: "2024-09-29T00:00:00Z"}], points: true, rank: 0, rate: 10, summary: "a"}, threshold: 0.5}], + [{threshold: 0, shipment: {rate: 1000000, amount: 2, kind: "retail", age: 169, dueDate: "1990-06-15", parcels: [{limit: 0.5, balance: 50, weight: 0}]}}, {adjusted: false, shipment: {age: 169, amount: 2, dueDate: "1990-06-15", fee: false, kind: "retail", parcels: [{balance: 50, decision: true, level: "2-a", limit: 0.5, share: 0, weight: 0, weighted: "1991-01-15T00:00:00Z"}], points: true, rank: 998, rate: 1000000, summary: "a"}, threshold: 0}], + [{threshold: 0.5, shipment: {amount: 1000, kind: "corporate", age: 50, dueDate: "2024-01-01", parcels: []}}, {adjusted: false, shipment: {age: 50, amount: 1000, dueDate: "2024-01-01", fee: null, kind: "corporate", parcels: [], points: true, rank: 0, summary: "a"}, threshold: 0.5}], + [{threshold: -2, shipment: {rate: null, amount: 100, kind: null, age: 100, dueDate: "2025-03-20T10:15:30Z", parcels: [{limit: 0.5, balance: 99999999999999999999, weight: 10}]}}, {adjusted: false, shipment: {age: 100, amount: 100, dueDate: "2025-03-20T10:15:30Z", fee: null, kind: null, parcels: [{balance: 99999999999999999999, decision: true, level: "98-a", limit: 0.5, share: 100, weight: 10, weighted: "2025-10-20T10:15:30Z"}], points: true, rank: 900, rate: null, summary: "a"}, threshold: -2}], + [{threshold: 1, shipment: {rate: 50, amount: 250, kind: "retail", age: 50, dueDate: "2024-01-01", parcels: [{limit: -500, balance: 72, weight: 2.50}, {limit: 1000, balance: 99999999999999999999, weight: -0.01}, {limit: 50, balance: 5, weight: -1}, {limit: 0, balance: 1, weight: -500}]}}, {adjusted: false, shipment: {age: 50, amount: 250, dueDate: "2024-01-01", fee: false, kind: "retail", parcels: [{balance: 72, decision: true, level: "251-a", limit: -500, share: 3, weight: 2.50, weighted: "2024-08-01T00:00:00Z"}, {balance: 99999999999999999999, decision: true, level: "251-a", limit: 1000, share: -0, weight: -0.01, weighted: "2024-08-01T00:00:00Z"}, {balance: 5, decision: true, level: "251-a", limit: 50, share: -1, weight: -1, weighted: "2024-08-01T00:00:00Z"}, {balance: 1, decision: true, level: "251-a", limit: 0, share: -500, weight: -500, weighted: "2024-08-01T00:00:00Z"}], points: true, rank: 750, rate: 50, summary: "a"}, threshold: 1}], + [{threshold: 0.5, shipment: {rate: 5, amount: 7.25, kind: "corporate", age: -1, dueDate: "2000-01-01", parcels: [{limit: 2, balance: 18, weight: 1000}]}}, {adjusted: false, shipment: {age: -1, amount: 7.25, dueDate: "2000-01-01", fee: null, kind: "corporate", parcels: [{balance: 18, decision: false, level: "7.75-", limit: 2, share: 2, weight: 1000, weighted: "2000-08-01T00:00:00Z"}], points: true, rank: null, rate: 5, summary: null}, threshold: 0.5}], + [{threshold: 1, shipment: {rate: 2.50, amount: -0.5, kind: "retail", age: 1000, dueDate: "1990-06-15", parcels: [{limit: 250, balance: -0.01, weight: 0.5}, {limit: 0, balance: 0.5, weight: 123456789.123}, {limit: 250, balance: 415, weight: 1}], extraField: "x"}}, {adjusted: false, shipment: {age: 1000, amount: -0.5, dueDate: "1990-06-15", extraField: "x", fee: false, kind: "retail", parcels: [{balance: -0.01, decision: true, level: "0.5-a", limit: 250, share: 1, weight: 0.5, weighted: "1991-01-15T00:00:00Z"}, {balance: 0.5, decision: true, level: "0.5-a", limit: 0, share: 123456790, weight: 123456789.123, weighted: "1991-01-15T00:00:00Z"}, {balance: 415, decision: true, level: "0.5-a", limit: 250, share: 1, weight: 1, weighted: "1991-01-15T00:00:00Z"}], points: true, rank: 1000.5, rate: 2.50, summary: "a"}, threshold: 1}], + [{threshold: 0.5, shipment: {rate: 1.5, amount: 0.5, kind: "retail", age: 1000, dueDate: "2025-03-20T10:15:30Z", parcels: [{limit: -0.01, balance: 0, weight: 0.000001}, {limit: 0.5, balance: 50, weight: -0}], extraField: "x"}}, {adjusted: false, shipment: {age: 1000, amount: 0.5, dueDate: "2025-03-20T10:15:30Z", extraField: "x", fee: false, kind: "retail", parcels: [{balance: 0, decision: true, level: "1.0-a", limit: -0.01, share: 1000, weight: 0.000001, weighted: "2025-10-20T10:15:30Z"}, {balance: 50, decision: true, level: "1.0-a", limit: 0.5, share: 1000, weight: 0, weighted: "2025-10-20T10:15:30Z"}], points: true, rank: 999.5, rate: 1.5, summary: "a"}, threshold: 0.5}], + [{threshold: 0, shipment: {rate: 1000, amount: 0.000001, kind: "retail", age: -0.01, dueDate: "2024-01-01", parcels: [{limit: 0.1, balance: 18, weight: 0}, {limit: -500, balance: 5, weight: 250}, {limit: 250, balance: 10, weight: 65}, {limit: 0.5, balance: 18, weight: 50}, {limit: 2.50, balance: 0.25, weight: 1.5}]}}, {adjusted: false, shipment: {age: -0.01, amount: 0.000001, dueDate: "2024-01-01", fee: null, kind: "retail", parcels: [{balance: 18, decision: true, level: "0.000001-", limit: 0.1, share: 0, weight: 0, weighted: "2024-08-01T00:00:00Z"}, {balance: 5, decision: true, level: "0.000001-", limit: -500, share: 250, weight: 250, weighted: "2024-08-01T00:00:00Z"}, {balance: 10, decision: true, level: "0.000001-", limit: 250, share: 65, weight: 65, weighted: "2024-08-01T00:00:00Z"}, {balance: 18, decision: true, level: "0.000001-", limit: 0.5, share: 50, weight: 50, weighted: "2024-08-01T00:00:00Z"}, {balance: 0.25, decision: true, level: "0.000001-", limit: 2.50, share: 2, weight: 1.5, weighted: "2024-08-01T00:00:00Z"}], points: true, rank: null, rate: 1000, summary: null}, threshold: 0}], + [{threshold: 10, shipment: {rate: 50, amount: 0.5, kind: "retail", age: 0.5, dueDate: "2000-01-01", parcels: [{limit: 7.25, balance: -1, weight: 5}, {limit: 10, balance: 10, weight: 0.000001}]}}, {adjusted: false, shipment: {age: 0.5, amount: 0.5, dueDate: "2000-01-01", fee: true, kind: "retail", parcels: [{balance: -1, decision: true, level: "10.5-VIP", limit: 7.25, share: 8.333333333333333333333333333, weight: 5, weighted: "2000-08-01T00:00:00Z"}, {balance: 10, decision: true, level: "10.5-VIP", limit: 10, share: 49.99995000004999995000005, weight: 0.000001, weighted: "2000-08-01T00:00:00Z"}], points: true, rank: 2500, rate: 50, summary: "VIP"}, threshold: 10}], + [{threshold: 0.5, shipment: {rate: -500, amount: 1.5, kind: "retail", age: 0.25, dueDate: "2025-03-20", parcels: [{limit: 2, balance: 0.5, weight: 5}, {limit: 10, balance: 3, weight: 0.5}]}}, {adjusted: false, shipment: {age: 0.25, amount: 1.5, dueDate: "2025-03-20", fee: null, kind: "retail", parcels: [{balance: 0.5, decision: true, level: "2.0-", limit: 2, share: 0.25, weight: 5, weighted: "2025-10-20T00:00:00Z"}, {balance: 3, decision: true, level: "2.0-", limit: 10, share: 0.25, weight: 0.5, weighted: "2025-10-20T00:00:00Z"}], points: true, rank: null, rate: -500, summary: null}, threshold: 0.5}], + [{threshold: 10, shipment: {rate: 1, amount: 10, kind: "corporate", age: 18, dueDate: "2025-03-20", parcels: [{limit: -0.01, balance: -0, weight: 2}, {limit: 99.99, balance: -0.01, weight: 0.000001}]}}, {adjusted: false, shipment: {age: 18, amount: 10, dueDate: "2025-03-20", fee: null, kind: "corporate", parcels: [{balance: 0, decision: false, level: "20-a", limit: -0.01, share: 18, weight: 2, weighted: "2025-10-20T00:00:00Z"}, {balance: -0.01, decision: false, level: "20-a", limit: 99.99, share: 18, weight: 0.000001, weighted: "2025-10-20T00:00:00Z"}], points: true, rank: 990, rate: 1, summary: "a"}, threshold: 10}], + [{threshold: 0, shipment: {rate: 2, amount: 0.5, age: 1.5, dueDate: "1990-06-15", parcels: [{limit: 2, balance: 1000, weight: 2}]}}, {adjusted: false, shipment: {age: 1.5, amount: 0.5, dueDate: "1990-06-15", fee: false, parcels: [{balance: 1000, decision: true, level: "0.5-0", limit: 2, share: 2, weight: 2, weighted: "1991-01-15T00:00:00Z"}], points: true, rank: 1002, rate: 2, summary: "0"}, threshold: 0}], + [{threshold: 100, shipment: {rate: "12", amount: 10, kind: "corporate", age: 50, dueDate: "2025-03-20T10:15:30Z", parcels: [{limit: -1, balance: 5, weight: 3}]}}, "!error: InputValidationFailed"], + [{threshold: 0, shipment: {amount: 250, kind: null, age: 1000000, dueDate: "2025-03-20T10:15:30Z", parcels: [{limit: 2.50, balance: 1000, weight: -1}, {limit: 250, balance: 0.25, weight: 0.1}]}}, {adjusted: false, shipment: {age: 1000000, amount: 250, dueDate: "2025-03-20T10:15:30Z", fee: null, kind: null, parcels: [{balance: 1000, decision: true, level: "250-a", limit: 2.50, share: 1000000, weight: -1, weighted: "2025-10-20T10:15:30Z"}, {balance: 0.25, decision: true, level: "250-a", limit: 250, share: 1000000, weight: 0.1, weighted: "2025-10-20T10:15:30Z"}], points: true, rank: 750, summary: "a"}, threshold: 0}], + [{threshold: 10, shipment: {rate: 250, amount: 3, kind: "retail", age: -0.01, dueDate: "2024-02-29", parcels: []}}, {adjusted: false, shipment: {age: -0.01, amount: 3, dueDate: "2024-02-29", fee: null, kind: "retail", parcels: [], points: true, rank: null, rate: 250, summary: null}, threshold: 10}], + [{threshold: 1, shipment: {rate: 50, amount: -0.01, kind: "retail", age: 99999999999999999999, dueDate: "2024-01-01", parcels: [{limit: 1000, balance: 2.50, weight: 99.99}], extraField: "x"}}, {adjusted: false, shipment: {age: 99999999999999999999, amount: -0.01, dueDate: "2024-01-01", extraField: "x", fee: false, kind: "retail", parcels: [{balance: 2.50, decision: true, level: "0.99-a", limit: 1000, share: 100, weight: 99.99, weighted: "2024-08-01T00:00:00Z"}], points: true, rank: 1000.01, rate: 50, summary: "a"}, threshold: 1}], + ], +} + +// seed 335900 (attempt 0) +{ + name: "a 60: claim/companies: 1 assertion, 1 match, 1 table; 0 root, 1 per-member, 2 top-level computed", + policy: { + models: {claim: {years: "number?", price: "number", birthDate: "date", rate: "number", dueDate: "date", companies: "company[]"}, company: {income: "number", days: "number"}}, + blocks: [ + {table: "t1", inputs: ["claim.price", null, "(claim.rate > 10 ? claim.price : claim.price)"], outputs: ["penalty"], rules: [ + ["[10..332]", "(claim.years ?? 0) == claim.rate", "< 5", "(claim.years ?? 0)"], + ["", "", "", "claim.price"], + [">= 50", "0 != claim.price", ">= 100", "(claim.years ?? 0)"], + ["> 18", "claim.years == null", "", "((claim.years ?? 0) <= 250 ? claim.price : claim.rate)"], + ["", "", "", "100"], + ]}, + {assertion: "adjusted", conditions: ["all(claim.companies, #.income >= #.days)", ["and", "all(claim.companies, #.income >= #.income)", 2], ["or", "claim.birthDate < d('2000-06-30')", 0]]}, + {match: "company.level", arms: [["none(claim.companies, #.days <= #.days)", "(penalty ?? 0)"], ["", "sum(map(claim.companies, round(#.income, 2)))"]]}, + ], + }, + cases: [ + [{claim: {years: 250, price: 250, birthDate: "1990-06-15", rate: 250, dueDate: "1990-06-15", companies: [{income: 1, days: 2}], extraField: "x"}}, {adjusted: false, claim: {birthDate: "1990-06-15", companies: [{days: 2, income: 1, level: 1}], dueDate: "1990-06-15", extraField: "x", price: 250, rate: 250, years: 250}}], + [{claim: {years: 2.50, price: 1000, birthDate: "2024-01-01", rate: -1, dueDate: "2025-03-20", companies: [{income: 18, days: 1000000}, {income: 99.99, days: 384}, {income: 10, days: 1000000}]}}, {adjusted: false, claim: {birthDate: "2024-01-01", companies: [{days: 1000000, income: 18, level: 127.99}, {days: 384, income: 99.99, level: 127.99}, {days: 1000000, income: 10, level: 127.99}], dueDate: "2025-03-20", price: 1000, rate: -1, years: 2.50}}], + [{claim: {years: 2, price: 10, birthDate: "2024-01-01", rate: -0.5, dueDate: "2025-03-20", companies: [{income: 99999999999999999999, days: 0}, {income: 2.50, days: 65}]}}, {adjusted: false, claim: {birthDate: "2024-01-01", companies: [{days: 0, income: 99999999999999999999, level: 100000000000000000001.50}, {days: 65, income: 2.50, level: 100000000000000000001.50}], dueDate: "2025-03-20", price: 10, rate: -0.5, years: 2}}], + [{claim: {years: null, price: 0, birthDate: "2024-02-29", rate: 2.50, dueDate: "1990-06-15", companies: []}}, {adjusted: false, claim: {birthDate: "2024-02-29", companies: [], dueDate: "1990-06-15", price: 0, rate: 2.50, years: null}}], + [{claim: {years: null, price: 5, birthDate: "2000-01-01", rate: 1000000, dueDate: "2024-01-01", companies: [{income: 0.5, days: 0}, {income: -0.01, days: 2}, {income: 99.99, days: 2.50}, {income: 100, days: 3}]}}, {adjusted: false, claim: {birthDate: "2000-01-01", companies: [{days: 0, income: 0.5, level: 200.48}, {days: 2, income: -0.01, level: 200.48}, {days: 2.50, income: 99.99, level: 200.48}, {days: 3, income: 100, level: 200.48}], dueDate: "2024-01-01", price: 5, rate: 1000000, years: null}}], + [{claim: {price: 7.25, birthDate: "2000-01-01", rate: 65, dueDate: "2025-03-20T10:15:30Z", companies: [{income: 0.1, days: 18}]}}, {adjusted: false, claim: {birthDate: "2000-01-01", companies: [{days: 18, income: 0.1, level: 0.1}], dueDate: "2025-03-20T10:15:30Z", price: 7.25, rate: 65}}], + [{claim: {years: null, price: 1e3, birthDate: "2024-02-29", rate: 10, dueDate: "2000-01-01", companies: [{income: 2, days: 2.50}, {income: -0.01, days: 100}, {income: 10, days: 1}, {income: 0.1, days: 1000000}, {income: 0, days: 100}]}}, {adjusted: false, claim: {birthDate: "2024-02-29", companies: [{days: 2.50, income: 2, level: 12.09}, {days: 100, income: -0.01, level: 12.09}, {days: 1, income: 10, level: 12.09}, {days: 1000000, income: 0.1, level: 12.09}, {days: 100, income: 0, level: 12.09}], dueDate: "2000-01-01", price: 1000, rate: 10, years: null}}], + [{claim: {years: 3, price: 1e3, birthDate: "2025-03-20", rate: 0, dueDate: "2025-03-20T10:15:30Z", companies: [{income: 170, days: 250}]}}, {adjusted: false, claim: {birthDate: "2025-03-20", companies: [{days: 250, income: 170, level: 170}], dueDate: "2025-03-20T10:15:30Z", price: 1000, rate: 0, years: 3}}], + [{claim: {price: 50, birthDate: "2024-02-29", rate: 0.000001, dueDate: "2030-12-31", companies: [{income: 2.50, days: -0}, {income: 100, days: 0.5}]}}, {adjusted: false, claim: {birthDate: "2024-02-29", companies: [{days: 0, income: 2.50, level: 102.50}, {days: 0.5, income: 100, level: 102.50}], dueDate: "2030-12-31", price: 50, rate: 0.000001}}], + [{claim: {years: 0.5, price: 100, birthDate: "1990-06-15", rate: 99999999999999999999, dueDate: "1990-06-15", companies: [{income: 250, days: 0.5}, {income: 5, days: 250}, {income: 1000, days: 99999999999999999999}, {income: 5, days: 5}, {income: -0, days: 2.50}]}}, {adjusted: false, claim: {birthDate: "1990-06-15", companies: [{days: 0.5, income: 250, level: 1260}, {days: 250, income: 5, level: 1260}, {days: 99999999999999999999, income: 1000, level: 1260}, {days: 5, income: 5, level: 1260}, {days: 2.50, income: 0, level: 1260}], dueDate: "1990-06-15", price: 100, rate: 99999999999999999999, years: 0.5}}], + [{claim: {years: 1000000, price: 18, birthDate: "2025-03-20", rate: 100, dueDate: "2000-01-01", companies: []}}, {adjusted: false, claim: {birthDate: "2025-03-20", companies: [], dueDate: "2000-01-01", price: 18, rate: 100, years: 1000000}}], + [{claim: {price: 0, birthDate: "1990-06-15", rate: 0.5, dueDate: "2000-01-01", companies: [{income: 5, days: -500}, {income: 18, days: -0}, {income: 1000, days: 5}, {income: 1, days: 0.5}]}}, {adjusted: true, claim: {birthDate: "1990-06-15", companies: [{days: -500, income: 5, level: 1024}, {days: 0, income: 18, level: 1024}, {days: 5, income: 1000, level: 1024}, {days: 0.5, income: 1, level: 1024}], dueDate: "2000-01-01", price: 0, rate: 0.5}}], + [{claim: {price: 10, birthDate: "2030-12-31", rate: 100, dueDate: "1990-06-15", companies: [{income: 250, days: 250}, {income: 99.99, days: 250}]}}, {adjusted: false, claim: {birthDate: "2030-12-31", companies: [{days: 250, income: 250, level: 349.99}, {days: 250, income: 99.99, level: 349.99}], dueDate: "1990-06-15", price: 10, rate: 100}}], + [{claim: {years: -0.5, price: 18, birthDate: "2024-02-29", rate: 3, dueDate: "2000-01-01", companies: [{income: 100, days: 10}, {income: 0.1, days: 1.5}, {income: 1.5, days: 7.25}, {income: 1.5, days: 65}, {income: 7.25, days: 100}]}}, {adjusted: false, claim: {birthDate: "2024-02-29", companies: [{days: 10, income: 100, level: 110.35}, {days: 1.5, income: 0.1, level: 110.35}, {days: 7.25, income: 1.5, level: 110.35}, {days: 65, income: 1.5, level: 110.35}, {days: 100, income: 7.25, level: 110.35}], dueDate: "2000-01-01", price: 18, rate: 3, years: -0.5}}], + [{claim: {years: 10, price: 0.5, birthDate: "1990-06-15", rate: -0.01, dueDate: "2000-01-01", companies: [{income: 1000000, days: 0.5}]}}, {adjusted: true, claim: {birthDate: "1990-06-15", companies: [{days: 0.5, income: 1000000, level: 1000000}], dueDate: "2000-01-01", price: 0.5, rate: -0.01, years: 10}}], + [{claim: {years: null, price: 2, birthDate: "2000-01-01", rate: 10, dueDate: "2024-01-01", companies: [{income: 1000, days: 50}]}}, {adjusted: true, claim: {birthDate: "2000-01-01", companies: [{days: 50, income: 1000, level: 1000}], dueDate: "2024-01-01", price: 2, rate: 10, years: null}}], + [{claim: {years: 2.50, price: 3, birthDate: "2030-12-31", rate: 18, dueDate: "2025-03-20", companies: []}}, {adjusted: false, claim: {birthDate: "2030-12-31", companies: [], dueDate: "2025-03-20", price: 3, rate: 18, years: 2.50}}], + [{claim: {years: 10, price: 0.5, birthDate: "2025-03-20", rate: 100, dueDate: "2025-03-20", companies: [{income: -0, days: 18}, {income: 10, days: 3}, {income: 0, days: -1}, {income: 99.99, days: 0}, {income: 100, days: 10}]}}, {adjusted: false, claim: {birthDate: "2025-03-20", companies: [{days: 18, income: 0, level: 209.99}, {days: 3, income: 10, level: 209.99}, {days: -1, income: 0, level: 209.99}, {days: 0, income: 99.99, level: 209.99}, {days: 10, income: 100, level: 209.99}], dueDate: "2025-03-20", price: 0.5, rate: 100, years: 10}}], + [{claim: {years: 7.25, price: -0, birthDate: "2025-03-20T10:15:30Z", rate: 2, dueDate: "2025-03-20", companies: [{income: 100, days: 1000}]}}, {adjusted: false, claim: {birthDate: "2025-03-20T10:15:30Z", companies: [{days: 1000, income: 100, level: 100}], dueDate: "2025-03-20", price: 0, rate: 2, years: 7.25}}], + [{claim: {years: 3, price: 0.5, birthDate: "2000-01-01", rate: 5, dueDate: "1990-06-15", companies: [{income: 7.25, days: 0}, {income: 99999999999999999999, days: 2}]}}, {adjusted: true, claim: {birthDate: "2000-01-01", companies: [{days: 0, income: 7.25, level: 100000000000000000006.25}, {days: 2, income: 99999999999999999999, level: 100000000000000000006.25}], dueDate: "1990-06-15", price: 0.5, rate: 5, years: 3}}], + [{claim: {years: 1000, price: 10, birthDate: "2030-12-31", rate: -0.5, dueDate: "2024-01-01", companies: [{income: 10, days: 10}, {income: 100, days: 123456789.123}, {income: 1e3, days: 10}, {income: 1000, days: 65}, {income: 50, days: 10}], extraField: {nested: true}}}, {adjusted: false, claim: {birthDate: "2030-12-31", companies: [{days: 10, income: 10, level: 2160}, {days: 123456789.123, income: 100, level: 2160}, {days: 10, income: 1000, level: 2160}, {days: 65, income: 1000, level: 2160}, {days: 10, income: 50, level: 2160}], dueDate: "2024-01-01", extraField: {nested: true}, price: 10, rate: -0.5, years: 1000}}], + [{claim: {years: 7.25, price: 10, birthDate: "2030-12-31", rate: 18, dueDate: "2025-03-20T10:15:30Z", companies: [{income: 250, days: -0.01}, {income: 308, days: 3}, {income: 65, days: 99.99}]}}, {adjusted: false, claim: {birthDate: "2030-12-31", companies: [{days: -0.01, income: 250, level: 623}, {days: 3, income: 308, level: 623}, {days: 99.99, income: 65, level: 623}], dueDate: "2025-03-20T10:15:30Z", price: 10, rate: 18, years: 7.25}}], + [{claim: {years: 1.5, price: 2, birthDate: "2024-01-01", rate: 18, dueDate: "2024-02-29", companies: [{income: 1000, days: 0.000001}, {income: 2, days: 1}]}}, {adjusted: false, claim: {birthDate: "2024-01-01", companies: [{days: 0.000001, income: 1000, level: 1002}, {days: 1, income: 2, level: 1002}], dueDate: "2024-02-29", price: 2, rate: 18, years: 1.5}}], + [{claim: {price: 18, birthDate: "2030-12-31", rate: 1000, dueDate: "2000-01-01", companies: [{income: 250, days: 1.5}]}}, {adjusted: false, claim: {birthDate: "2030-12-31", companies: [{days: 1.5, income: 250, level: 250}], dueDate: "2000-01-01", price: 18, rate: 1000}}], + [{claim: {price: 0.5, birthDate: "2030-12-31", rate: 0, dueDate: "2030-12-31", companies: [{income: 2, days: 100}, {income: 1, days: 3}, {income: 100, days: 100}, {income: 5, days: 1000}]}}, {adjusted: false, claim: {birthDate: "2030-12-31", companies: [{days: 100, income: 2, level: 108}, {days: 3, income: 1, level: 108}, {days: 100, income: 100, level: 108}, {days: 1000, income: 5, level: 108}], dueDate: "2030-12-31", price: 0.5, rate: 0}}], + [{claim: {years: 100, price: 2.50, birthDate: "2024-01-01", rate: 3, dueDate: "2000-01-01", companies: []}}, {adjusted: false, claim: {birthDate: "2024-01-01", companies: [], dueDate: "2000-01-01", price: 2.50, rate: 3, years: 100}}], + [{claim: {years: 5, price: 0.5, birthDate: "2025-03-20T10:15:30Z", rate: 100, dueDate: "2025-03-20T10:15:30Z", companies: [{income: 99999999999999999999, days: 0}]}}, {adjusted: false, claim: {birthDate: "2025-03-20T10:15:30Z", companies: [{days: 0, income: 99999999999999999999, level: 99999999999999999999}], dueDate: "2025-03-20T10:15:30Z", price: 0.5, rate: 100, years: 5}}], + [{claim: {years: 100, price: 0, birthDate: "2025-03-20T10:15:30Z", rate: 10, dueDate: "1990-06-15", companies: [{income: 10, days: 2.50}, {income: 250, days: 7.25}, {income: 18, days: 0.5}, {income: 7.25, days: 1000000}], extraField: "x"}}, {adjusted: false, claim: {birthDate: "2025-03-20T10:15:30Z", companies: [{days: 2.50, income: 10, level: 285.25}, {days: 7.25, income: 250, level: 285.25}, {days: 0.5, income: 18, level: 285.25}, {days: 1000000, income: 7.25, level: 285.25}], dueDate: "1990-06-15", extraField: "x", price: 0, rate: 10, years: 100}}], + [{claim: {years: 250, price: 18, birthDate: "2000-01-01", rate: 100, dueDate: "2025-03-20T10:15:30Z", companies: [], extraField: {nested: true}}}, {adjusted: true, claim: {birthDate: "2000-01-01", companies: [], dueDate: "2025-03-20T10:15:30Z", extraField: {nested: true}, price: 18, rate: 100, years: 250}}], + ], +} diff --git a/core/engine/tests/spec/policy/34-generated-b.json5 b/core/engine/tests/spec/policy/34-generated-b.json5 new file mode 100644 index 00000000..3934777d --- /dev/null +++ b/core/engine/tests/spec/policy/34-generated-b.json5 @@ -0,0 +1,3302 @@ +// Generated policies, set B. +// +// Generated by gen33.py + run33.py (`python3 run33.py b` in the generator directory of the +// round-three spec session), seed 340000. Suite i is built from seed 340000 + 100 * i + +// attempt, where attempt is the first candidate whose policy has no error diagnostics. +// +// Each suite has a random data model: a root entity with 3-6 primitive fields (number, string, +// boolean, date, enum; about 30% optional) and one relationship array to a child entity with +// 2-4 fields, sometimes a number global, a second-level array under the child (read through +// aggregates) and a single relationship on the root. Its blocks (5-12 random expression, match, +// assertion and table blocks, in document order or shuffled) write undeclared computed +// properties on the root, on every member and at the top level; later blocks read earlier ones, +// giving chains, aggregates over member computeds and members reading root computeds. Flavor b +// adds nested write paths (`x.totals.y`), object, filter and map valued computeds, nullable +// computeds, a wider function set (templates, modulo, powers, division, regex, conversions, +// date methods) and occasional 8-14 member arrays. Each suite has 12-30 random inputs: valid, +// missing optional, null optional, boundary values, empty relationships, unknown fields and +// invalid requests (missing or null required, wrong type). +// +// Outputs recorded from the driver; this chapter exists to differential-test the engines. + +// seed 340000 (attempt 0) +{ + name: "b 01: order/items: 2 assertion, 1 expression, 4 match, 1 table; 3 root, 3 per-member, 4 top-level computed", + policy: { + models: {order: {amount: "number?", income: "number", tier: "string(gold|silver|bronze)?", items: "item[]?"}, item: {age: "number", since: "date"}}, + blocks: [ + {table: "t1", inputs: ["order.income", "order.tier", "(order.amount ?? 0)"], outputs: ["totals.tag", "net", "ok"], rules: [ + [">= 250", "'bronze'", "<= 5", "(order.amount ?? 0)", "(order.amount ?? 0)", "(order.income * (order.amount ?? 0))"], + ["", "'silver'", "< 1.5", "(order.amount ?? 0)", "order.income", "order.income"], + ["<= 1000", "'bronze'", "", "", "round((order.amount ?? 0) / 7, 0)", "(order.amount ?? 0)"], + ["< 1", "'bronze'", "", "round((order.amount ?? 0) / 7, 2)", "len((order.items ?? []))", "number(string(order.income))"], + ["", "'bronze'", "!= 0", "order.income", "100", ""], + ]}, + {assertion: "order.summary", conditions: [["and", "not ((totals.tag ?? 0) != (ok ?? 0))", 1]]}, + {match: "item.fee", arms: [["item.since > d('2024-01-01')", "(order.tier ?? '') in ['silver', 'gold']"], ["(order.income) / (abs(item.age) + 1) <= order.income", "(ok ?? 0) in [41..51)"], ["", "order.summary"]]}, + {expression: "item.rank", value: "(not (not (item.fee)) and ((order.summary or order.summary) and order.tier != null))"}, + {match: "order.scores.points", arms: [["(order.tier ?? '') in ['bronze', 'silver']", "(order.summary ? (totals.tag ?? 0) : 50)"], ["(net ?? 0) != (totals.tag ?? 0)", "(ok ?? 0)"], ["order.tier != null", "(ok ?? 0)"], ["", "floor((order.amount ?? 0))"]]}, + {assertion: "order.band", conditions: [["and", "some((order.items ?? []), not (#.fee))", 1], ["and", "order.scores.points != order.income", 2], ["or", "0 > order.income", 1], ["and", "some((order.items ?? []), #.age in [3..138))", 1]]}, + {match: "calc.weighted", arms: [["(totals.tag ?? 0) >= order.income", "order.summary"], ["none((order.items ?? []), #.age in [-5..102))", "order.scores.points in [1..174]"], ["", "ok == null"]]}, + {match: "item.discount", arms: [["all((order.items ?? []), (#.rank and #.rank))", "string(item.age)"], ["5 == order.scores.points", "'none'"], ["", "'x'"]]}, + ], + }, + cases: [ + [{order: {amount: 7.25, income: 2, tier: null, items: null}}, {calc: {weighted: true}, net: null, ok: null, order: {amount: 7.25, band: false, income: 2, items: null, scores: {points: 7}, summary: true, tier: null}, totals: {tag: null}}], + [{order: {amount: null, income: 18, items: []}}, {calc: {weighted: false}, net: null, ok: null, order: {amount: null, band: false, income: 18, items: [], scores: {points: 0}, summary: true}, totals: {tag: null}}], + [{order: {amount: 123456789.123, income: 1, tier: "silver", items: [{age: -0.5, since: "2025-03-20"}, {age: 99.99, since: "2024-01-01"}, {age: 59, since: "2030-12-31"}, {age: 100, since: "2000-01-01"}]}}, {calc: {weighted: true}, net: null, ok: null, order: {amount: 123456789.123, band: true, income: 1, items: [{age: -0.5, discount: "x", fee: true, rank: true, since: "2025-03-20"}, {age: 99.99, discount: "x", fee: false, rank: false, since: "2024-01-01"}, {age: 59, discount: "x", fee: true, rank: true, since: "2030-12-31"}, {age: 100, discount: "x", fee: false, rank: false, since: "2000-01-01"}], scores: {points: 0}, summary: true, tier: "silver"}, totals: {tag: null}}], + [{order: {amount: 10, income: 0, tier: "silver", items: [{age: 100, since: "2030-12-31"}, {age: 2, since: "1990-06-15"}, {age: 2, since: "1990-06-15"}, {age: 250, since: "2025-03-20T10:15:30Z"}, {age: 250, since: "2025-03-20T10:15:30Z"}]}}, {calc: {weighted: true}, net: null, ok: null, order: {amount: 10, band: true, income: 0, items: [{age: 100, discount: "x", fee: true, rank: true, since: "2030-12-31"}, {age: 2, discount: "x", fee: false, rank: false, since: "1990-06-15"}, {age: 2, discount: "x", fee: false, rank: false, since: "1990-06-15"}, {age: 250, discount: "x", fee: true, rank: true, since: "2025-03-20T10:15:30Z"}, {age: 250, discount: "x", fee: true, rank: true, since: "2025-03-20T10:15:30Z"}], scores: {points: 0}, summary: true, tier: "silver"}, totals: {tag: null}}], + [{order: {amount: 0, income: 2, tier: "gold", items: []}}, {calc: {weighted: false}, net: null, ok: null, order: {amount: 0, band: false, income: 2, items: [], scores: {points: 0}, summary: true, tier: "gold"}, totals: {tag: null}}], + [{order: {amount: 65, income: 99.99, items: [{age: 1000000, since: "2025-03-20T10:15:30Z"}]}}, {calc: {weighted: true}, net: null, ok: null, order: {amount: 65, band: false, income: 99.99, items: [{age: 1000000, discount: "x", fee: false, rank: false, since: "2025-03-20T10:15:30Z"}], scores: {points: 65}, summary: true}, totals: {tag: null}}], + [{order: {amount: null, income: 250, tier: "silver", items: []}}, {calc: {weighted: true}, net: 250, ok: 250, order: {amount: null, band: false, income: 250, items: [], scores: {points: 50}, summary: false, tier: "silver"}, totals: {tag: 0}}], + [{order: {amount: 0, income: 0, tier: "silver", items: []}}, {calc: {weighted: true}, net: 0, ok: 0, order: {amount: 0, band: false, income: 0, items: [], scores: {points: 0}, summary: true, tier: "silver"}, totals: {tag: 0}}], + [{order: {amount: null, income: 5, tier: "bronze", items: null}}, {calc: {weighted: false}, net: 0, ok: 0, order: {amount: null, band: false, income: 5, items: null, scores: {points: 0}, summary: true, tier: "bronze"}, totals: {tag: null}}], + [{order: {amount: -0.01, income: 250, tier: "silver", items: [{age: 222, since: "2030-12-31"}, {age: 5, since: "2025-03-20T10:15:30Z"}, {age: 50, since: "2024-02-29"}]}}, {calc: {weighted: false}, net: 250, ok: 250, order: {amount: -0.01, band: true, income: 250, items: [{age: 222, discount: "x", fee: true, rank: false, since: "2030-12-31"}, {age: 5, discount: "x", fee: true, rank: false, since: "2025-03-20T10:15:30Z"}, {age: 50, discount: "x", fee: true, rank: false, since: "2024-02-29"}], scores: {points: 50}, summary: false, tier: "silver"}, totals: {tag: -0.01}}], + [{order: {amount: 123456789.123, income: 5, tier: "gold", items: [{age: 250, since: 20250101}, {age: -0.5, since: "2000-01-01"}, {age: 2.50, since: "2025-03-20T10:15:30Z"}, {age: 0, since: "2024-02-29"}, {age: 1000, since: "2024-02-29"}]}}, "!error: InputValidationFailed"], + [{order: {income: -0, items: []}}, {calc: {weighted: true}, net: null, ok: null, order: {band: false, income: 0, items: [], scores: {points: 0}, summary: true}, totals: {tag: null}}], + [{order: {amount: 2, income: 100, tier: "bronze", items: [{age: 2, since: "2030-12-31"}, {age: 2, since: "1990-06-15"}]}}, {calc: {weighted: false}, net: 0, ok: 2, order: {amount: 2, band: false, income: 100, items: [{age: 2, discount: "x", fee: false, rank: false, since: "2030-12-31"}, {age: 2, discount: "x", fee: false, rank: false, since: "1990-06-15"}], scores: {points: 50}, summary: false, tier: "bronze"}, totals: {tag: 100}}], + [{order: {amount: 1, income: 1, tier: null, items: []}}, {calc: {weighted: true}, net: null, ok: null, order: {amount: 1, band: false, income: 1, items: [], scores: {points: 1}, summary: true, tier: null}, totals: {tag: null}}], + ], +} + +// seed 340100 (attempt 0) +{ + name: "b 02: tenant/items: 4 expression, 3 match, 1 table; 3 root, 4 per-member, 1 top-level computed", + policy: { + models: {tenant: {rate: "number", birthDate: "date", balance: "number", since: "date", active: "boolean?", dueDate: "date?", items: "item[]"}, item: {rate: "number?", since: "date", birthDate: "date", vip: "boolean"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {expression: "tenant.bonus", value: "tenant.active"}, + {expression: "tenant.grade", value: "(tenant.dueDate ?? d('2025-01-01'))"}, + {match: "item.scores.capped", arms: [["item.rate != null", "(`${'none'}/${(item.rate ?? 0)}` + '-' + string(item.vip))"], ["sum(map(tenant.items, round((#.rate ?? 0)))) == tenant.balance", "'x'"], ["threshold in (1..138]", "'VIP'"], ["", "string((tenant.active ?? false))"]]}, + {expression: "item.points", value: "sum([tenant.balance, (item.rate ?? 0), tenant.rate])"}, + {expression: "item.scores.segment", value: "string((min([abs(threshold), 1000]) ^ 2))"}, + {match: "tenant.rank", arms: [["((tenant.active ?? false) or (tenant.active ?? false))", "tenant.rate in (50..107)"], ["all(tenant.items, (#.rate ?? 0) > (#.rate ?? 0))", "(tenant.active ?? false)"], ["not (tenant.rate < threshold)", "(tenant.bonus ?? false)"], ["", "all(tenant.items, not (#.vip))"]]}, + {table: "t7", hit: "collect", inputs: [null], outputs: ["flags.exposure"], rules: [ + ["tenant.birthDate > d('2000-06-30')", "tenant.rate"], + ["tenant.rate == tenant.balance", ""], + ["(tenant.rank and tenant.rank)", "tenant.balance"], + ["(tenant.rank or (tenant.bonus ?? false))", "50"], + ["", "threshold"], + ]}, + {match: "item.tag", arms: [["not ((tenant.bonus ?? false))", "threshold"], ["(some(tenant.items, not (#.vip)) and threshold >= threshold)", "trunc((item.rate ?? 0))"], ["", "item.points"]]}, + ], + }, + cases: [ + [{threshold: -2, tenant: {rate: 10, birthDate: "2025-03-20", balance: 10, since: "1990-06-15", items: [{since: "2024-02-29", birthDate: "2024-01-01", vip: false}, {since: "2024-02-29", birthDate: "2024-02-29", vip: true}, {rate: 250, since: "2024-01-01", birthDate: "2025-03-20", vip: true}, {since: "2025-03-20", birthDate: "2025-03-20", vip: false}, {rate: -0.01, since: "2024-02-29", birthDate: "2030-12-31", vip: true}, {rate: null, since: "2025-03-20T10:15:30Z", birthDate: "2025-03-20", vip: true}, {rate: 1000000, since: "2030-12-31", birthDate: "2030-12-31", vip: true}, {rate: 18, since: "2000-01-01", birthDate: "1990-06-15", vip: true}, {since: "2025-03-20T10:15:30Z", birthDate: "2024-02-29", vip: true}, {rate: 5, since: "2025-03-20", birthDate: "1990-06-15", vip: true}, {rate: 10, since: "2025-03-20T10:15:30Z", birthDate: "2024-02-29", vip: false}, {rate: 1000000, since: "2024-01-01", birthDate: "2024-01-01", vip: false}]}}, {flags: {exposure: [10, -2]}, tenant: {balance: 10, birthDate: "2025-03-20", bonus: null, grade: "2025-01-01T00:00:00Z", items: [{birthDate: "2024-01-01", scores: {capped: "false", segment: "4"}, since: "2024-02-29", tag: -2, vip: false}, {birthDate: "2024-02-29", scores: {capped: "false", segment: "4"}, since: "2024-02-29", tag: -2, vip: true}, {birthDate: "2025-03-20", rate: 250, scores: {capped: "none/250-true", segment: "4"}, since: "2024-01-01", tag: -2, vip: true}, {birthDate: "2025-03-20", scores: {capped: "false", segment: "4"}, since: "2025-03-20", tag: -2, vip: false}, {birthDate: "2030-12-31", rate: -0.01, scores: {capped: "none/-0.01-true", segment: "4"}, since: "2024-02-29", tag: -2, vip: true}, {birthDate: "2025-03-20", rate: null, scores: {capped: "false", segment: "4"}, since: "2025-03-20T10:15:30Z", tag: -2, vip: true}, {birthDate: "2030-12-31", rate: 1000000, scores: {capped: "none/1000000-true", segment: "4"}, since: "2030-12-31", tag: -2, vip: true}, {birthDate: "1990-06-15", rate: 18, scores: {capped: "none/18-true", segment: "4"}, since: "2000-01-01", tag: -2, vip: true}, {birthDate: "2024-02-29", scores: {capped: "false", segment: "4"}, since: "2025-03-20T10:15:30Z", tag: -2, vip: true}, {birthDate: "1990-06-15", rate: 5, scores: {capped: "none/5-true", segment: "4"}, since: "2025-03-20", tag: -2, vip: true}, {birthDate: "2024-02-29", rate: 10, scores: {capped: "none/10-false", segment: "4"}, since: "2025-03-20T10:15:30Z", tag: -2, vip: false}, {birthDate: "2024-01-01", rate: 1000000, scores: {capped: "none/1000000-false", segment: "4"}, since: "2024-01-01", tag: -2, vip: false}], rank: false, rate: 10, since: "1990-06-15"}, threshold: -2}], + [{threshold: 10, tenant: {rate: 1000000, birthDate: "2025-03-20", balance: -0.5, since: "2024-01-01", active: false, dueDate: "2024-02-29", items: [{rate: true, since: "2024-01-01", birthDate: "2025-03-20", vip: false}, {rate: 10, since: "2000-01-01", birthDate: "2024-02-29", vip: true}]}}, "!error: InputValidationFailed"], + [{threshold: -2, tenant: {rate: 250, birthDate: "2024-01-01", balance: -0.5, since: "2025-03-20T10:15:30Z", active: false, dueDate: "1990-06-15", items: [{rate: 250, since: "2024-02-29", birthDate: "2000-01-01", vip: false}, {rate: 10, since: "2024-02-29", birthDate: "2030-12-31", vip: false}, {rate: 1000, since: "2024-02-29", birthDate: "2025-03-20T10:15:30Z", vip: true}, {rate: 7.25, since: "2030-12-31", birthDate: "2025-03-20T10:15:30Z", vip: false}], extraField: "x"}}, {flags: {exposure: [250, -2]}, tenant: {active: false, balance: -0.5, birthDate: "2024-01-01", bonus: false, dueDate: "1990-06-15", extraField: "x", grade: "1990-06-15", items: [{birthDate: "2000-01-01", rate: 250, scores: {capped: "none/250-false", segment: "4"}, since: "2024-02-29", tag: -2, vip: false}, {birthDate: "2030-12-31", rate: 10, scores: {capped: "none/10-false", segment: "4"}, since: "2024-02-29", tag: -2, vip: false}, {birthDate: "2025-03-20T10:15:30Z", rate: 1000, scores: {capped: "none/1000-true", segment: "4"}, since: "2024-02-29", tag: -2, vip: true}, {birthDate: "2025-03-20T10:15:30Z", rate: 7.25, scores: {capped: "none/7.25-false", segment: "4"}, since: "2030-12-31", tag: -2, vip: false}], rank: false, rate: 250, since: "2025-03-20T10:15:30Z"}, threshold: -2}], + [{threshold: -2, tenant: {rate: 5, birthDate: "2025-03-20", balance: 7.25, since: "2025-03-20T10:15:30Z", active: false, dueDate: "2000-01-01", items: [{rate: 1, since: "2024-01-01", birthDate: "2024-02-29", vip: false}, {rate: 10, since: "2025-03-20", birthDate: "2030-12-31", vip: false}, {rate: 1000000, since: "2025-03-20", birthDate: "2025-03-20T10:15:30Z", vip: false}]}}, {flags: {exposure: [5, -2]}, tenant: {active: false, balance: 7.25, birthDate: "2025-03-20", bonus: false, dueDate: "2000-01-01", grade: "2000-01-01", items: [{birthDate: "2024-02-29", rate: 1, scores: {capped: "none/1-false", segment: "4"}, since: "2024-01-01", tag: -2, vip: false}, {birthDate: "2030-12-31", rate: 10, scores: {capped: "none/10-false", segment: "4"}, since: "2025-03-20", tag: -2, vip: false}, {birthDate: "2025-03-20T10:15:30Z", rate: 1000000, scores: {capped: "none/1000000-false", segment: "4"}, since: "2025-03-20", tag: -2, vip: false}], rank: false, rate: 5, since: "2025-03-20T10:15:30Z"}, threshold: -2}], + [{threshold: 10, tenant: {rate: 264, birthDate: "2024-01-01", balance: -0.01, since: "2000-01-01", active: false, dueDate: "1990-06-15", items: [{since: "2024-01-01", birthDate: "2024-02-29", vip: true}, {rate: 10, since: "2025-03-20T10:15:30Z", birthDate: "1990-06-15", vip: false}]}}, {flags: {exposure: [264, 10]}, tenant: {active: false, balance: -0.01, birthDate: "2024-01-01", bonus: false, dueDate: "1990-06-15", grade: "1990-06-15", items: [{birthDate: "2024-02-29", scores: {capped: "VIP", segment: "100"}, since: "2024-01-01", tag: 10, vip: true}, {birthDate: "1990-06-15", rate: 10, scores: {capped: "none/10-false", segment: "100"}, since: "2025-03-20T10:15:30Z", tag: 10, vip: false}], rank: false, rate: 264, since: "2000-01-01"}, threshold: 10}], + [{threshold: -2, tenant: {rate: 2.50, birthDate: "2025-03-20", balance: 100, since: "2024-02-29", items: [{rate: -0.01, since: "2024-02-29", birthDate: "2024-01-01", vip: false}, {rate: 65, since: "1990-06-15", birthDate: "2000-01-01", vip: true}, {rate: -1, since: "2024-02-29", birthDate: "2000-01-01", vip: true}]}}, {flags: {exposure: [2.50, -2]}, tenant: {balance: 100, birthDate: "2025-03-20", bonus: null, grade: "2025-01-01T00:00:00Z", items: [{birthDate: "2024-01-01", rate: -0.01, scores: {capped: "none/-0.01-false", segment: "4"}, since: "2024-02-29", tag: -2, vip: false}, {birthDate: "2000-01-01", rate: 65, scores: {capped: "none/65-true", segment: "4"}, since: "1990-06-15", tag: -2, vip: true}, {birthDate: "2000-01-01", rate: -1, scores: {capped: "none/-1-true", segment: "4"}, since: "2024-02-29", tag: -2, vip: true}], rank: false, rate: 2.50, since: "2024-02-29"}, threshold: -2}], + [{threshold: 100, tenant: {rate: 0.000001, birthDate: "1990-06-15", balance: -0.5, since: "1990-06-15", active: true, dueDate: "2025-03-20", items: [{rate: [1], since: "2024-01-01", birthDate: "1990-06-15", vip: false}, {rate: 10, since: "2030-12-31", birthDate: "2000-01-01", vip: true}, {rate: 0.000001, since: "2025-03-20T10:15:30Z", birthDate: "2000-01-01", vip: true}, {rate: 65, since: "1990-06-15", birthDate: "2025-03-20", vip: false}]}}, "!error: InputValidationFailed"], + [{threshold: 10, tenant: {rate: 99.99, birthDate: "2024-02-29", balance: 2, since: "2030-12-31", dueDate: "2024-02-29", items: []}}, {flags: {exposure: [99.99, 10]}, tenant: {balance: 2, birthDate: "2024-02-29", bonus: null, dueDate: "2024-02-29", grade: "2024-02-29", items: [], rank: false, rate: 99.99, since: "2030-12-31"}, threshold: 10}], + [{threshold: 1, tenant: {rate: 1, birthDate: "2024-01-01", balance: 99.99, since: "2025-03-20", active: true, dueDate: "2024-01-01", items: [{rate: 0.5, since: "2025-03-20T10:15:30Z", birthDate: "2000-01-01", vip: true}, {rate: 1e3, since: "2030-12-31", birthDate: "2025-03-20T10:15:30Z", vip: true}, {rate: -0, since: "2025-03-20", birthDate: "2024-01-01", vip: true}]}}, {flags: {exposure: [1, 50, 1]}, tenant: {active: true, balance: 99.99, birthDate: "2024-01-01", bonus: true, dueDate: "2024-01-01", grade: "2024-01-01", items: [{birthDate: "2000-01-01", points: 101.49, rate: 0.5, scores: {capped: "none/0.5-true", segment: "1"}, since: "2025-03-20T10:15:30Z", tag: 101.49, vip: true}, {birthDate: "2025-03-20T10:15:30Z", points: 1100.99, rate: 1000, scores: {capped: "none/1000-true", segment: "1"}, since: "2030-12-31", tag: 1100.99, vip: true}, {birthDate: "2024-01-01", points: 100.99, rate: 0, scores: {capped: "none/0-true", segment: "1"}, since: "2025-03-20", tag: 100.99, vip: true}], rank: false, rate: 1, since: "2025-03-20"}, threshold: 1}], + [{threshold: -2, tenant: {rate: 10, birthDate: "2000-01-01", balance: 99999999999999999999, since: "2025-03-20", active: true, dueDate: "2024-01-01", items: [{rate: 2.50, since: "2000-01-01", birthDate: "2025-03-20", vip: true}, {rate: 1e3, since: "2025-03-20", birthDate: "2000-01-01", vip: false}, {rate: -0.5, since: "2024-01-01", birthDate: "1990-06-15", vip: false}]}}, {flags: {exposure: [50, -2]}, tenant: {active: true, balance: 99999999999999999999, birthDate: "2000-01-01", bonus: true, dueDate: "2024-01-01", grade: "2024-01-01", items: [{birthDate: "2025-03-20", rate: 2.50, scores: {capped: "none/2.50-true", segment: "4"}, since: "2000-01-01", tag: 2, vip: true}, {birthDate: "2000-01-01", rate: 1000, scores: {capped: "none/1000-false", segment: "4"}, since: "2025-03-20", tag: 1000, vip: false}, {birthDate: "1990-06-15", rate: -0.5, scores: {capped: "none/-0.5-false", segment: "4"}, since: "2024-01-01", tag: -0, vip: false}], rank: false, rate: 10, since: "2025-03-20"}, threshold: -2}], + [{threshold: 0, tenant: {rate: -0.5, birthDate: "1990-06-15", balance: -500, since: "2000-01-01", active: null, dueDate: null, items: [{rate: 18, since: "2024-02-29", birthDate: "2000-01-01", vip: false}, {rate: null, since: "1990-06-15", birthDate: "2024-01-01", vip: true}]}}, {flags: {exposure: [0]}, tenant: {active: null, balance: -500, birthDate: "1990-06-15", bonus: null, dueDate: null, grade: "2025-01-01T00:00:00Z", items: [{birthDate: "2000-01-01", rate: 18, scores: {capped: "none/18-false", segment: "0"}, since: "2024-02-29", tag: 0, vip: false}, {birthDate: "2024-01-01", rate: null, scores: {capped: "false", segment: "0"}, since: "1990-06-15", tag: 0, vip: true}], rank: false, rate: -0.5, since: "2000-01-01"}, threshold: 0}], + [{threshold: 0.5, tenant: {rate: 0.1, birthDate: "1990-06-15", balance: 0.1, since: "2030-12-31", active: false, dueDate: "2030-12-31", items: [{rate: 65, since: "2025-03-20", birthDate: "2024-02-29", vip: false}, {rate: 10, since: "2025-03-20", birthDate: "2024-01-01", vip: true}, {since: "2024-01-01", birthDate: "2024-02-29", vip: false}]}}, {flags: {exposure: [0.5]}, tenant: {active: false, balance: 0.1, birthDate: "1990-06-15", bonus: false, dueDate: "2030-12-31", grade: "2030-12-31", items: [{birthDate: "2024-02-29", rate: 65, scores: {capped: "none/65-false", segment: "0.25"}, since: "2025-03-20", tag: 0.5, vip: false}, {birthDate: "2024-01-01", rate: 10, scores: {capped: "none/10-true", segment: "0.25"}, since: "2025-03-20", tag: 0.5, vip: true}, {birthDate: "2024-02-29", scores: {capped: "false", segment: "0.25"}, since: "2024-01-01", tag: 0.5, vip: false}], rank: false, rate: 0.1, since: "2030-12-31"}, threshold: 0.5}], + [{threshold: 10, tenant: {rate: 0, birthDate: "2030-12-31", balance: -0.01, since: "2025-03-20T10:15:30Z", active: true, dueDate: "2025-03-20T10:15:30Z", items: [{rate: 5, since: "2025-03-20T10:15:30Z", birthDate: "not a date", vip: false}, {rate: 65, since: "1990-06-15", birthDate: "2024-02-29", vip: false}, {rate: 7.25, since: "1990-06-15", birthDate: "2025-03-20T10:15:30Z", vip: false}, {rate: 10, since: "2024-01-01", birthDate: "1990-06-15", vip: true}, {rate: 123456789.123, since: "2025-03-20T10:15:30Z", birthDate: "2025-03-20", vip: false}]}}, "!error: InputValidationFailed"], + [{threshold: -2, tenant: {rate: -500, birthDate: "1990-06-15", balance: 10, since: "2025-03-20", active: true, dueDate: "1990-06-15", items: [{rate: 50, since: "1990-06-15", birthDate: "2000-01-01", vip: false}]}}, {flags: {exposure: [50, -2]}, tenant: {active: true, balance: 10, birthDate: "1990-06-15", bonus: true, dueDate: "1990-06-15", grade: "1990-06-15", items: [{birthDate: "2000-01-01", rate: 50, scores: {capped: "none/50-false", segment: "4"}, since: "1990-06-15", tag: 50, vip: false}], rank: false, rate: -500, since: "2025-03-20"}, threshold: -2}], + [{threshold: 0.5, tenant: {rate: -0, birthDate: "1990-06-15", balance: 1000, since: "2000-01-01", active: false, dueDate: "2025-03-20T10:15:30Z", items: [{rate: 0.5, since: "2025-03-20T10:15:30Z", birthDate: "2000-01-01", vip: false}], extraField: 1}}, {flags: {exposure: [1000, 50, 0.5]}, tenant: {active: false, balance: 1000, birthDate: "1990-06-15", bonus: false, dueDate: "2025-03-20T10:15:30Z", extraField: 1, grade: "2025-03-20T10:15:30Z", items: [{birthDate: "2000-01-01", rate: 0.5, scores: {capped: "none/0.5-false", segment: "0.25"}, since: "2025-03-20T10:15:30Z", tag: 0.5, vip: false}], rank: true, rate: 0, since: "2000-01-01"}, threshold: 0.5}], + [{threshold: 0.5, tenant: {rate: 65, birthDate: "1990-06-15", balance: 5, since: "2024-02-29", items: [{since: "1990-06-15", birthDate: "1990-06-15", vip: true}, {rate: 10, since: "2030-12-31", birthDate: "2000-01-01", vip: false}, {rate: null, since: "2025-03-20T10:15:30Z", birthDate: "2025-03-20", vip: true}]}}, {flags: {exposure: [0.5]}, tenant: {balance: 5, birthDate: "1990-06-15", bonus: null, grade: "2025-01-01T00:00:00Z", items: [{birthDate: "1990-06-15", scores: {capped: "false", segment: "0.25"}, since: "1990-06-15", tag: 0.5, vip: true}, {birthDate: "2000-01-01", rate: 10, scores: {capped: "none/10-false", segment: "0.25"}, since: "2030-12-31", tag: 0.5, vip: false}, {birthDate: "2025-03-20", rate: null, scores: {capped: "false", segment: "0.25"}, since: "2025-03-20T10:15:30Z", tag: 0.5, vip: true}], rank: false, rate: 65, since: "2024-02-29"}, threshold: 0.5}], + ], +} + +// seed 340200 (attempt 0) +{ + name: "b 03: account/lines/payments: 1 assertion, 2 expression, 4 match, 3 table; 3 root, 7 per-member, 4 top-level computed", + policy: { + models: {account: {limit: "number?", label: "string", balance: "number", active: "boolean?", birthDate: "date", rate: "number", lines: "line[]"}, line: {age: "number?", rate: "number", amount: "number", payments: "payment[]"}, payment: {years: "number", plan: "string(basic|plus|premium|trial)"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {table: "t6", inputs: [null, "decision"], outputs: ["line.points", "line.fee"], rules: [ + ["isNumeric(account.label)", "'US'", "", "(account.active ?? false)"], + ["", "", "line.review", "len(decision) > 2"], + ["decision == 'high'", "'none'", "all(line.payments, not (#.years == 5))", "line.surcharge"], + ["", "", "(account.active ?? false)", "matches(decision, '^.{2,}$')"], + ["account.rate > (account.health ?? 0)", "startsWith($, 'Oslo')", "", "(account.calc.margin ?? 0) in [31..80]"], + ["account.calc.margin == null", "", "line.surcharge", ""], + ["account.active == null", "'Oslo'", "line.review", "line.review"], + ]}, + {table: "t1", hit: "collect", inputs: ["account.rate", "account.rate", "number(string((account.limit ?? 0)))"], outputs: ["totals.net", "eligible", "capped"], rules: [ + ["<= 2", "> 18", "< 50", "account.balance", "50", "account.label in ['a', 'DE']"], + ["[50..200]", "50", "!= 0.5", "(account.limit ?? 0)", "0.5", "(account.active ?? false)"], + ["< 2", "", "[0.25..388.25]", "account.balance", "(account.limit ?? 0)", "(account.active ?? false)"], + ["50, 0.25", "!= 5", "", "threshold", "threshold", "(account.active ?? false)"], + ["", "<= 10", "3, 3", "(account.limit ?? 0)", "50", "(account.active ?? false)"], + ["", "> 18", "<= 0.25", "account.rate", "", "(account.active ?? false)"], + ["", "", "", "threshold", "account.rate", "(account.active ?? false)"], + ]}, + {match: "line.scores.exposure", arms: [["(line.age ?? 0) in [15..78]", "account.label"], ["", "account.label"]]}, + {match: "line.surcharge", arms: [["((account.limit ?? 0) >= (account.calc.margin ?? 0) or line.rate > account.balance)", "(account.active ?? false)"], ["matches(`${1000}/${(account.active ?? false)}`, 'a')", "contains(['high', 'none', ''], decision)"], ["decision != 'A1'", "(account.active ?? false)"], ["matches(decision, '[0-9]$')", "(account.active ?? false)"], ["", "(account.active ?? false)"]]}, + {match: "line.ok", arms: [["account.label in ['ok', 'x']", "string(len(line.payments))"], ["account.label in ['ok', 'gold']", "`${2}/${(account.limit ?? 0)}`"], ["", "account.birthDate.format('%Y')"]]}, + {expression: "line.scores.summary", value: "filter(line.payments, #.years != #.years)"}, + {match: "account.bonus", arms: [["account.birthDate > d('2025-03-20')", "sum(map(account.lines, (#.age ?? 0)))"], ["", "((account.limit ?? 0) + (account.calc.margin ?? 0))"]]}, + {expression: "decision", value: "account.label"}, + {assertion: "line.review", conditions: [["or", "account.birthDate < d('2000-06-30')", 1], ["or", "line.age != null", 1]]}, + {table: "t3", inputs: ["account.balance"], outputs: ["account.health", "account.calc.margin"], rules: [ + ["!= 100", "(threshold + (account.limit ?? 0))", "((account.active ?? false) ? threshold : (account.limit ?? 0))"], + ["> 0.25", "", "1.5"], + ["", "", "sum(map(account.lines, max([(#.age ?? 0), 18, #.rate])))"], + ["", "", "threshold"], + ["2, 10", "threshold", "account.rate"], + ]}, + ], + }, + cases: [ + [{threshold: 100, account: {limit: 1000000, label: "DE", balance: 2, active: false, birthDate: "2025-03-20T10:15:30Z", rate: 2.50, lines: []}}, {account: {active: false, balance: 2, birthDate: "2025-03-20T10:15:30Z", bonus: 0, calc: {margin: 1000000}, health: 1000100, label: "DE", limit: 1000000, lines: [], rate: 2.50}, capped: [false], decision: "DE", eligible: [2.50], threshold: 100, totals: {net: [100]}}], + [{threshold: 1, account: {limit: null, label: "-", balance: 0.25, active: false, birthDate: "2024-01-01", rate: 0.000001, lines: [{rate: 18, amount: 3, payments: [{years: 1.5, plan: "trial"}, {years: 50, plan: "basic"}, {years: -500, plan: "trial"}]}, {age: -0, rate: 5, amount: 5, payments: [{years: -1, plan: "premium"}, {years: 0, plan: "basic"}]}, {age: 50, rate: 1000, amount: 3, payments: [{years: 0.5, plan: "premium"}]}, {rate: 1.5, amount: 50, payments: [{years: 10, plan: "basic"}, {years: 0.5, plan: "basic"}, {years: 100, plan: "plus"}]}, {age: 1000, rate: 0.25, amount: 50, payments: [{years: 18, plan: "basic"}, {years: 0.25, plan: "premium"}]}, {age: 0.25, rate: 3, amount: -0.5, payments: [{years: 0.25, plan: "basic"}, {years: 50, plan: "trial"}]}, {age: 2, rate: 5, amount: 2, payments: [{years: 10, plan: "basic"}, {years: 7.25, plan: "trial"}]}, {age: 18, rate: 0.25, amount: 3, payments: [{years: 0.5, plan: "premium"}, {years: 18, plan: "basic"}]}, {age: 1000, rate: 2.50, amount: -0, payments: [{years: 0.5, plan: "basic"}, {years: 3, plan: "basic"}]}, {age: 1, rate: 0, amount: 0, payments: [{years: 250, plan: "basic"}, {years: 250, plan: "basic"}]}, {rate: 18, amount: 0.25, payments: [{years: 18, plan: "basic"}, {years: 176, plan: "premium"}]}, {age: 18, rate: 5, amount: 0.1, payments: [{years: 65, plan: "basic"}, {years: 7.25, plan: "plus"}]}]}}, {account: {active: false, balance: 0.25, birthDate: "2024-01-01", bonus: 0, calc: {margin: 0}, health: 1, label: "-", limit: null, lines: [{amount: 3, fee: false, ok: "2024", payments: [{plan: "trial", years: 1.5}, {plan: "basic", years: 50}, {plan: "trial", years: -500}], points: false, rate: 18, review: false, scores: {exposure: "-", summary: []}}, {age: 0, amount: 5, fee: false, ok: "2024", payments: [{plan: "premium", years: -1}, {plan: "basic", years: 0}], points: true, rate: 5, review: true, scores: {exposure: "-", summary: []}}, {age: 50, amount: 3, fee: false, ok: "2024", payments: [{plan: "premium", years: 0.5}], points: true, rate: 1000, review: true, scores: {exposure: "-", summary: []}}, {amount: 50, fee: false, ok: "2024", payments: [{plan: "basic", years: 10}, {plan: "basic", years: 0.5}, {plan: "plus", years: 100}], points: false, rate: 1.5, review: false, scores: {exposure: "-", summary: []}}, {age: 1000, amount: 50, fee: false, ok: "2024", payments: [{plan: "basic", years: 18}, {plan: "premium", years: 0.25}], points: true, rate: 0.25, review: true, scores: {exposure: "-", summary: []}}, {age: 0.25, amount: -0.5, fee: false, ok: "2024", payments: [{plan: "basic", years: 0.25}, {plan: "trial", years: 50}], points: true, rate: 3, review: true, scores: {exposure: "-", summary: []}}, {age: 2, amount: 2, fee: false, ok: "2024", payments: [{plan: "basic", years: 10}, {plan: "trial", years: 7.25}], points: true, rate: 5, review: true, scores: {exposure: "-", summary: []}}, {age: 18, amount: 3, fee: false, ok: "2024", payments: [{plan: "premium", years: 0.5}, {plan: "basic", years: 18}], points: true, rate: 0.25, review: true, scores: {exposure: "-", summary: []}}, {age: 1000, amount: 0, fee: false, ok: "2024", payments: [{plan: "basic", years: 0.5}, {plan: "basic", years: 3}], points: true, rate: 2.50, review: true, scores: {exposure: "-", summary: []}}, {age: 1, amount: 0, fee: false, ok: "2024", payments: [{plan: "basic", years: 250}, {plan: "basic", years: 250}], points: true, rate: 0, review: true, scores: {exposure: "-", summary: []}}, {amount: 0.25, fee: false, ok: "2024", payments: [{plan: "basic", years: 18}, {plan: "premium", years: 176}], points: false, rate: 18, review: false, scores: {exposure: "-", summary: []}}, {age: 18, amount: 0.1, fee: false, ok: "2024", payments: [{plan: "basic", years: 65}, {plan: "plus", years: 7.25}], points: true, rate: 5, review: true, scores: {exposure: "-", summary: []}}], rate: 0.000001}, capped: [false], decision: "-", eligible: [0.000001], threshold: 1, totals: {net: [1]}}], + [{threshold: 100, account: {label: "12", balance: 2, active: false, birthDate: "2000-01-01", rate: 18, lines: [{age: 10, rate: 99.99, amount: 18, payments: []}, {age: 5, rate: 0.5, amount: 5, payments: [{years: 0.1, plan: "trial"}, {years: 0.25, plan: "basic"}]}]}}, {account: {active: false, balance: 2, birthDate: "2000-01-01", bonus: 0, calc: {margin: 0}, health: 100, label: "12", lines: [{age: 10, amount: 18, fee: false, ok: "2000", payments: [], points: true, rate: 99.99, review: true, scores: {exposure: "12", summary: []}}, {age: 5, amount: 5, fee: false, ok: "2000", payments: [{plan: "trial", years: 0.1}, {plan: "basic", years: 0.25}], points: true, rate: 0.5, review: true, scores: {exposure: "12", summary: []}}], rate: 18}, capped: [false], decision: "12", eligible: [18], threshold: 100, totals: {net: [100]}}], + [{threshold: 0.5, account: {limit: 0.1, label: "x-y", balance: 1000000, birthDate: "2000-01-01", rate: 5, lines: [{rate: 0.25, amount: 250, payments: [{years: 3, plan: "basic"}, {years: 2, plan: "basic"}]}]}}, {account: {balance: 1000000, birthDate: "2000-01-01", bonus: 0.2, calc: {margin: 0.1}, health: 0.6, label: "x-y", limit: 0.1, lines: [{amount: 250, fee: true, ok: "2000", payments: [{plan: "basic", years: 3}, {plan: "basic", years: 2}], points: true, rate: 0.25, review: true, scores: {exposure: "x-y", summary: []}}], rate: 5}, capped: [false], decision: "x-y", eligible: [5], threshold: 0.5, totals: {net: [0.5]}}], + [{threshold: 0, account: {limit: 50, label: "A1", balance: 10, active: true, birthDate: "2025-03-20", rate: 0, lines: []}}, {account: {active: true, balance: 10, birthDate: "2025-03-20", bonus: 50, calc: {margin: 0}, health: 50, label: "A1", limit: 50, lines: [], rate: 0}, capped: [true, true], decision: "A1", eligible: [50, 0], threshold: 0, totals: {net: [10, 0]}}], + [{threshold: 1, account: {limit: 18, label: "VIP", balance: 5, birthDate: "1990-06-15", rate: 0.25, lines: [{rate: 50, amount: 1.5, payments: [{years: 18, plan: "trial"}, {years: 10, plan: "basic"}]}, {age: 10, rate: 0.1, amount: 0.25, payments: []}]}}, {account: {balance: 5, birthDate: "1990-06-15", bonus: 36, calc: {margin: 18}, health: 19, label: "VIP", limit: 18, lines: [{amount: 1.5, fee: true, ok: "1990", payments: [{plan: "trial", years: 18}, {plan: "basic", years: 10}], points: true, rate: 50, review: true, scores: {exposure: "VIP", summary: []}}, {age: 10, amount: 0.25, fee: true, ok: "1990", payments: [], points: true, rate: 0.1, review: true, scores: {exposure: "VIP", summary: []}}], rate: 0.25}, capped: [false, false, false], decision: "VIP", eligible: [18, 1, 0.25], threshold: 1, totals: {net: [5, 1, 1]}}], + [{threshold: 0, account: {limit: 65, label: "low", balance: 50, active: null, birthDate: "2024-01-01", rate: 0.25, lines: [{age: 18, rate: 5, amount: 50, payments: [{years: 0.000001, plan: "plus"}, {years: 0.5, plan: "premium"}, {years: 0.5, plan: "basic"}]}, {age: 5, rate: 3, amount: 1000, payments: [{years: -0.01, plan: "basic"}, {years: 50, plan: "basic"}]}, {rate: 10, amount: 1e3, payments: [{years: 18, plan: "trial"}]}, {age: -1, rate: 3, amount: 1, payments: [{years: 50, plan: "basic"}]}, {age: -500, rate: 3, amount: 5, payments: [{years: 1.5, plan: "trial"}, {years: 10, plan: "basic"}, {years: 1000, plan: "plus"}]}, {age: null, rate: 10, amount: 18, payments: []}, {rate: 3, amount: 1000000, payments: [{years: 250, plan: "basic"}]}, {age: 18, rate: 18, amount: 50, payments: [{years: 2, plan: "plus"}, {years: 3, plan: "basic"}]}, {age: 2, rate: 1000, amount: 50, payments: []}, {age: 0.25, rate: 5, amount: 5, payments: [{years: 1.5, plan: "trial"}, {years: 1, plan: "premium"}]}, {age: 18, rate: 0.25, amount: 0.25, payments: [{years: 18, plan: "trial"}, {years: 100, plan: "plus"}]}, {age: 0.1, rate: 0.5, amount: 1, payments: [{years: 10, plan: "plus"}, {years: 18, plan: "plus"}]}]}}, {account: {active: null, balance: 50, birthDate: "2024-01-01", bonus: 130, calc: {margin: 65}, health: 65, label: "low", limit: 65, lines: [{age: 18, amount: 50, fee: true, ok: "2024", payments: [{plan: "plus", years: 0.000001}, {plan: "premium", years: 0.5}, {plan: "basic", years: 0.5}], points: true, rate: 5, review: true, scores: {exposure: "low", summary: []}}, {age: 5, amount: 1000, fee: true, ok: "2024", payments: [{plan: "basic", years: -0.01}, {plan: "basic", years: 50}], points: true, rate: 3, review: true, scores: {exposure: "low", summary: []}}, {amount: 1000, fee: true, ok: "2024", payments: [{plan: "trial", years: 18}], points: false, rate: 10, review: false, scores: {exposure: "low", summary: []}}, {age: -1, amount: 1, fee: true, ok: "2024", payments: [{plan: "basic", years: 50}], points: true, rate: 3, review: true, scores: {exposure: "low", summary: []}}, {age: -500, amount: 5, fee: true, ok: "2024", payments: [{plan: "trial", years: 1.5}, {plan: "basic", years: 10}, {plan: "plus", years: 1000}], points: true, rate: 3, review: true, scores: {exposure: "low", summary: []}}, {age: null, amount: 18, fee: true, ok: "2024", payments: [], points: false, rate: 10, review: false, scores: {exposure: "low", summary: []}}, {amount: 1000000, fee: true, ok: "2024", payments: [{plan: "basic", years: 250}], points: false, rate: 3, review: false, scores: {exposure: "low", summary: []}}, {age: 18, amount: 50, fee: true, ok: "2024", payments: [{plan: "plus", years: 2}, {plan: "basic", years: 3}], points: true, rate: 18, review: true, scores: {exposure: "low", summary: []}}, {age: 2, amount: 50, fee: true, ok: "2024", payments: [], points: true, rate: 1000, review: true, scores: {exposure: "low", summary: []}}, {age: 0.25, amount: 5, fee: true, ok: "2024", payments: [{plan: "trial", years: 1.5}, {plan: "premium", years: 1}], points: true, rate: 5, review: true, scores: {exposure: "low", summary: []}}, {age: 18, amount: 0.25, fee: true, ok: "2024", payments: [{plan: "trial", years: 18}, {plan: "plus", years: 100}], points: true, rate: 0.25, review: true, scores: {exposure: "low", summary: []}}, {age: 0.1, amount: 1, fee: true, ok: "2024", payments: [{plan: "plus", years: 10}, {plan: "plus", years: 18}], points: true, rate: 0.5, review: true, scores: {exposure: "low", summary: []}}], rate: 0.25}, capped: [false, false, false], decision: "low", eligible: [65, 0, 0.25], threshold: 0, totals: {net: [50, 0, 0]}}], + [{threshold: 0.5, account: {limit: null, label: "ok", balance: 1000, active: false, birthDate: "2030-12-31", rate: 5, lines: [{age: null, rate: 1000, amount: 0.25, payments: [{years: -0, plan: "basic"}, {years: 50, plan: "basic"}, {years: 50, plan: "premium"}]}, {rate: 250, amount: 99999999999999999999, payments: []}, {age: 50, rate: 3, amount: 0.25, payments: [{years: 353, plan: "basic"}, {years: 5, plan: "trial"}]}]}}, {account: {active: false, balance: 1000, birthDate: "2030-12-31", bonus: 50, calc: {margin: 0}, health: 0.5, label: "ok", limit: null, lines: [{age: null, amount: 0.25, fee: false, ok: "3", payments: [{plan: "basic", years: 0}, {plan: "basic", years: 50}, {plan: "premium", years: 50}], points: false, rate: 1000, review: false, scores: {exposure: "ok", summary: []}}, {amount: 99999999999999999999, fee: false, ok: "0", payments: [], points: false, rate: 250, review: false, scores: {exposure: "ok", summary: []}}, {age: 50, amount: 0.25, fee: false, ok: "2", payments: [{plan: "basic", years: 353}, {plan: "trial", years: 5}], points: true, rate: 3, review: true, scores: {exposure: "ok", summary: []}}], rate: 5}, capped: [false], decision: "ok", eligible: [5], threshold: 0.5, totals: {net: [0.5]}}], + [{threshold: 100, account: {limit: null, label: "low", balance: 1.5, birthDate: "2024-02-29", rate: 2, lines: [{rate: 50, amount: 0.000001, payments: [{years: 0.5, plan: "basic"}]}, {age: 5, rate: 2, amount: 10, payments: [{years: 0.25, plan: "basic"}, {years: -1, plan: "basic"}]}]}}, {account: {balance: 1.5, birthDate: "2024-02-29", bonus: 0, calc: {margin: 0}, health: 100, label: "low", limit: null, lines: [{amount: 0.000001, fee: true, ok: "2024", payments: [{plan: "basic", years: 0.5}], points: false, rate: 50, review: false, scores: {exposure: "low", summary: []}}, {age: 5, amount: 10, fee: true, ok: "2024", payments: [{plan: "basic", years: 0.25}, {plan: "basic", years: -1}], points: true, rate: 2, review: true, scores: {exposure: "low", summary: []}}], rate: 2}, capped: [false], decision: "low", eligible: [2], threshold: 100, totals: {net: [100]}}], + [{threshold: 100, account: {limit: 0.25, label: "ok", balance: 2, active: true, birthDate: "2024-01-01", rate: 1000, lines: []}}, {account: {active: true, balance: 2, birthDate: "2024-01-01", bonus: 100.25, calc: {margin: 100}, health: 100.25, label: "ok", limit: 0.25, lines: [], rate: 1000}, capped: [true, true], decision: "ok", eligible: [1000], threshold: 100, totals: {net: [1000, 100]}}], + [{threshold: 100, account: {limit: null, label: "Oslo", balance: 18, active: false, birthDate: "2024-01-01", rate: 100, lines: [{age: 2, rate: 0.25, amount: -0.01, payments: [{years: 0.25, plan: "plus"}]}, {age: null, rate: 0.25, amount: 50, payments: [{years: 18, plan: "plus"}]}, {rate: 1.5, amount: 18, payments: [{years: 2, plan: "basic"}, {years: 2, plan: "basic"}, {years: -1, plan: "trial"}]}, {age: null, rate: 50, amount: 0.000001, payments: []}, {age: null, rate: 0, amount: 1000, payments: [{years: 5, plan: "plus"}]}]}}, {account: {active: false, balance: 18, birthDate: "2024-01-01", bonus: 0, calc: {margin: 0}, health: 100, label: "Oslo", limit: null, lines: [{age: 2, amount: -0.01, fee: true, ok: "2024", payments: [{plan: "plus", years: 0.25}], points: true, rate: 0.25, review: true, scores: {exposure: "Oslo", summary: []}}, {age: null, amount: 50, fee: true, ok: "2024", payments: [{plan: "plus", years: 18}], points: false, rate: 0.25, review: false, scores: {exposure: "Oslo", summary: []}}, {amount: 18, fee: true, ok: "2024", payments: [{plan: "basic", years: 2}, {plan: "basic", years: 2}, {plan: "trial", years: -1}], points: false, rate: 1.5, review: false, scores: {exposure: "Oslo", summary: []}}, {age: null, amount: 0.000001, fee: true, ok: "2024", payments: [], points: false, rate: 50, review: false, scores: {exposure: "Oslo", summary: []}}, {age: null, amount: 1000, fee: true, ok: "2024", payments: [{plan: "plus", years: 5}], points: false, rate: 0, review: false, scores: {exposure: "Oslo", summary: []}}], rate: 100}, capped: [false, false], decision: "Oslo", eligible: [100], threshold: 100, totals: {net: [100, 100]}}], + [{threshold: -2, account: {label: "gold", balance: 0.25, active: null, birthDate: "2000-01-01", rate: 2, lines: [{rate: 1.5, amount: 2, payments: [{years: 50, plan: "basic"}, {years: 50, plan: "plus"}, {years: -0, plan: "premium"}]}, {rate: 250, amount: 5, payments: []}]}}, {account: {active: null, balance: 0.25, birthDate: "2000-01-01", bonus: 0, calc: {margin: 0}, health: -2, label: "gold", lines: [{amount: 2, fee: true, ok: "2/0", payments: [{plan: "basic", years: 50}, {plan: "plus", years: 50}, {plan: "premium", years: 0}], points: true, rate: 1.5, review: true, scores: {exposure: "gold", summary: []}}, {amount: 5, fee: true, ok: "2/0", payments: [], points: true, rate: 250, review: true, scores: {exposure: "gold", summary: []}}], rate: 2}, capped: [false], decision: "gold", eligible: [2], threshold: -2, totals: {net: [-2]}}], + [{threshold: 1, account: {limit: 5, label: "ok", balance: 1.5, active: false, birthDate: "2024-01-01", rate: 100, lines: []}}, {account: {active: false, balance: 1.5, birthDate: "2024-01-01", bonus: 10, calc: {margin: 5}, health: 6, label: "ok", limit: 5, lines: [], rate: 100}, capped: [false], decision: "ok", eligible: [100], threshold: 1, totals: {net: [1]}}], + [{threshold: 1, account: {limit: 0.5, label: "retail", balance: 1.5, active: true, birthDate: "2024-02-29", rate: 0.5, lines: [{age: 0.25, rate: 1, amount: 250, payments: [{years: 123456789.123, plan: "basic"}]}, {age: 0.25, rate: 18, amount: 5, payments: [{years: 18, plan: "basic"}, {years: 5, plan: "basic"}, {years: -0.5, plan: "premium"}]}], extraField: "x"}}, {account: {active: true, balance: 1.5, birthDate: "2024-02-29", bonus: 1.5, calc: {margin: 1}, extraField: "x", health: 1.5, label: "retail", limit: 0.5, lines: [{age: 0.25, amount: 250, fee: true, ok: "2024", payments: [{plan: "basic", years: 123456789.123}], points: true, rate: 1, review: true, scores: {exposure: "retail", summary: []}}, {age: 0.25, amount: 5, fee: true, ok: "2024", payments: [{plan: "basic", years: 18}, {plan: "basic", years: 5}, {plan: "premium", years: -0.5}], points: true, rate: 18, review: true, scores: {exposure: "retail", summary: []}}], rate: 0.5}, capped: [true, true], decision: "retail", eligible: [0.5, 0.5], threshold: 1, totals: {net: [1.5, 1]}}], + [{threshold: -2, account: {limit: 99999999999999999999, label: "low", balance: 5, active: true, birthDate: "2025-03-20T10:15:30Z", rate: 0, lines: []}}, {account: {active: true, balance: 5, birthDate: "2025-03-20T10:15:30Z", bonus: 0, calc: {margin: -2}, health: 99999999999999999997, label: "low", limit: 99999999999999999999, lines: [], rate: 0}, capped: [true], decision: "low", eligible: [0], threshold: -2, totals: {net: [-2]}}], + [{threshold: 0, account: {limit: 1000, label: "a-b-c", balance: 5, active: false, birthDate: "2030-12-31", rate: 2, lines: [{age: 5, rate: 1.5, amount: null, payments: [{years: 1000000, plan: "plus"}, {years: 10, plan: "plus"}]}, {age: 5, rate: 10, amount: 50, payments: [{years: 250, plan: "plus"}, {years: 18, plan: "basic"}]}, {age: 10, rate: 100, amount: 18, payments: [{years: 123456789.123, plan: "basic"}]}]}}, {account: {active: false, balance: 5, birthDate: "2030-12-31", bonus: 20, calc: {margin: 1000}, health: 1000, label: "a-b-c", limit: 1000, lines: [{age: 5, amount: null, fee: true, ok: "2030", payments: [{plan: "plus", years: 1000000}, {plan: "plus", years: 10}], points: true, rate: 1.5, review: true, scores: {exposure: "a-b-c", summary: []}}, {age: 5, amount: 50, fee: true, ok: "2030", payments: [{plan: "plus", years: 250}, {plan: "basic", years: 18}], points: true, rate: 10, review: true, scores: {exposure: "a-b-c", summary: []}}, {age: 10, amount: 18, fee: true, ok: "2030", payments: [{plan: "basic", years: 123456789.123}], points: true, rate: 100, review: true, scores: {exposure: "a-b-c", summary: []}}], rate: 2}, capped: [false], decision: "a-b-c", eligible: [2], threshold: 0, totals: {net: [0]}}], + [{threshold: 1, account: {limit: 5, label: "NL", balance: 3, active: true, birthDate: "2000-01-01", rate: 0.25, lines: [{age: 10, rate: 1000, amount: 100, payments: [{years: 50, plan: "basic"}, {years: 50, plan: "trial"}]}, {age: 3, rate: 2, amount: 5, payments: []}, {age: -1, rate: 0.25, amount: 250, payments: [{years: 5, plan: "plus"}, {years: 1.5, plan: "trial"}, {years: 100, plan: "plus"}]}, {age: 0.000001, rate: 50, amount: 2, payments: [{years: 2, plan: "premium"}, {years: 0.25, plan: "basic"}]}]}}, {account: {active: true, balance: 3, birthDate: "2000-01-01", bonus: 6, calc: {margin: 1}, health: 6, label: "NL", limit: 5, lines: [{age: 10, amount: 100, fee: false, ok: "2000", payments: [{plan: "basic", years: 50}, {plan: "trial", years: 50}], points: true, rate: 1000, review: true, scores: {exposure: "NL", summary: []}}, {age: 3, amount: 5, fee: false, ok: "2000", payments: [], points: true, rate: 2, review: true, scores: {exposure: "NL", summary: []}}, {age: -1, amount: 250, fee: false, ok: "2000", payments: [{plan: "plus", years: 5}, {plan: "trial", years: 1.5}, {plan: "plus", years: 100}], points: true, rate: 0.25, review: true, scores: {exposure: "NL", summary: []}}, {age: 0.000001, amount: 2, fee: false, ok: "2000", payments: [{plan: "premium", years: 2}, {plan: "basic", years: 0.25}], points: true, rate: 50, review: true, scores: {exposure: "NL", summary: []}}], rate: 0.25}, capped: [true, true, true], decision: "NL", eligible: [5, 1, 0.25], threshold: 1, totals: {net: [3, 1, 1]}}], + [{threshold: 100, account: {limit: 65, label: "3.5", balance: 10, active: true, birthDate: "2025-03-20", rate: 3, lines: [{age: null, rate: 5, amount: 0.5, payments: [{years: 0.5, plan: "basic"}, {years: 0.000001, plan: "trial"}]}]}}, {account: {active: true, balance: 10, birthDate: "2025-03-20", bonus: 165, calc: {margin: 100}, health: 165, label: "3.5", limit: 65, lines: [{age: null, amount: 0.5, fee: true, ok: "2025", payments: [{plan: "basic", years: 0.5}, {plan: "trial", years: 0.000001}], points: false, rate: 5, review: false, scores: {exposure: "3.5", summary: []}}], rate: 3}, capped: [true], decision: "3.5", eligible: [3], threshold: 100, totals: {net: [100]}}], + [{threshold: -2, account: {limit: 65, label: "a", balance: 18, active: true, birthDate: "2025-03-20T10:15:30Z", rate: 99.99, lines: [{age: 2, rate: 3, amount: 50, payments: [{years: 3, plan: "plus"}, {years: 18, plan: "plus"}, {years: -0.5, plan: "premium"}]}, {age: 5, rate: 0.5, amount: 2, payments: [{years: 50, plan: "trial"}, {years: 50, plan: "plus"}, {years: 1000000, plan: "premium"}]}, {age: 3, rate: 50, amount: 5, payments: [{years: 0.25, plan: "basic"}, {years: 18, plan: "basic"}]}, {age: 250, rate: 25, amount: 3, payments: [{years: 100, plan: "premium"}, {years: -0, plan: "premium"}]}, {age: 0.25, rate: 18, amount: 0.5, payments: [{years: 0.25, plan: "basic"}, {years: 2.50, plan: "basic"}]}, {age: 1000, rate: 99.99, amount: 5, payments: [{years: 18, plan: "plus"}, {years: 2, plan: "basic"}]}, {age: 10, rate: 50, amount: 1000, payments: [{years: 0, plan: "basic"}, {years: 65, plan: "basic"}]}, {age: 18, rate: 250, amount: 7.25, payments: []}, {age: 1000, rate: 10, amount: 250, payments: [{years: 250, plan: "plus"}, {years: 5, plan: "trial"}]}, {age: 0, rate: 0.25, amount: 0, payments: [{years: 1000, plan: "basic"}, {years: 5, plan: "basic"}]}, {age: 1000, rate: 50, amount: 0.25, payments: [{years: 18, plan: "trial"}, {years: 123456789.123, plan: "plus"}]}]}}, {account: {active: true, balance: 18, birthDate: "2025-03-20T10:15:30Z", bonus: 3288.25, calc: {margin: -2}, health: 63, label: "a", limit: 65, lines: [{age: 2, amount: 50, fee: false, ok: "2025", payments: [{plan: "plus", years: 3}, {plan: "plus", years: 18}, {plan: "premium", years: -0.5}], points: true, rate: 3, review: true, scores: {exposure: "a", summary: []}}, {age: 5, amount: 2, fee: false, ok: "2025", payments: [{plan: "trial", years: 50}, {plan: "plus", years: 50}, {plan: "premium", years: 1000000}], points: true, rate: 0.5, review: true, scores: {exposure: "a", summary: []}}, {age: 3, amount: 5, fee: false, ok: "2025", payments: [{plan: "basic", years: 0.25}, {plan: "basic", years: 18}], points: true, rate: 50, review: true, scores: {exposure: "a", summary: []}}, {age: 250, amount: 3, fee: false, ok: "2025", payments: [{plan: "premium", years: 100}, {plan: "premium", years: 0}], points: true, rate: 25, review: true, scores: {exposure: "a", summary: []}}, {age: 0.25, amount: 0.5, fee: false, ok: "2025", payments: [{plan: "basic", years: 0.25}, {plan: "basic", years: 2.50}], points: true, rate: 18, review: true, scores: {exposure: "a", summary: []}}, {age: 1000, amount: 5, fee: false, ok: "2025", payments: [{plan: "plus", years: 18}, {plan: "basic", years: 2}], points: true, rate: 99.99, review: true, scores: {exposure: "a", summary: []}}, {age: 10, amount: 1000, fee: false, ok: "2025", payments: [{plan: "basic", years: 0}, {plan: "basic", years: 65}], points: true, rate: 50, review: true, scores: {exposure: "a", summary: []}}, {age: 18, amount: 7.25, fee: false, ok: "2025", payments: [], points: true, rate: 250, review: true, scores: {exposure: "a", summary: []}}, {age: 1000, amount: 250, fee: false, ok: "2025", payments: [{plan: "plus", years: 250}, {plan: "trial", years: 5}], points: true, rate: 10, review: true, scores: {exposure: "a", summary: []}}, {age: 0, amount: 0, fee: false, ok: "2025", payments: [{plan: "basic", years: 1000}, {plan: "basic", years: 5}], points: true, rate: 0.25, review: true, scores: {exposure: "a", summary: []}}, {age: 1000, amount: 0.25, fee: false, ok: "2025", payments: [{plan: "trial", years: 18}, {plan: "plus", years: 123456789.123}], points: true, rate: 50, review: true, scores: {exposure: "a", summary: []}}], rate: 99.99}, capped: [true], decision: "a", eligible: [99.99], threshold: -2, totals: {net: [-2]}}], + [{threshold: 10, account: {limit: 0.25, label: "x-y", balance: 10, birthDate: "2025-03-20", rate: 378, lines: [{age: null, rate: 18, amount: 364, payments: [{years: 18, plan: "premium"}, {years: 5, plan: "basic"}, {years: 1e3, plan: "premium"}]}, {rate: 0.25, amount: 250, payments: [{years: 1.5, plan: "basic"}]}, {age: 0.25, rate: 5, amount: -0, payments: [{years: 18, plan: "trial"}, {years: 50, plan: "plus"}]}]}}, {account: {balance: 10, birthDate: "2025-03-20", bonus: 0.50, calc: {margin: 0.25}, health: 10.25, label: "x-y", limit: 0.25, lines: [{age: null, amount: 364, fee: true, ok: "2025", payments: [{plan: "premium", years: 18}, {plan: "basic", years: 5}, {plan: "premium", years: 1000}], points: false, rate: 18, review: false, scores: {exposure: "x-y", summary: []}}, {amount: 250, fee: true, ok: "2025", payments: [{plan: "basic", years: 1.5}], points: false, rate: 0.25, review: false, scores: {exposure: "x-y", summary: []}}, {age: 0.25, amount: 0, fee: true, ok: "2025", payments: [{plan: "trial", years: 18}, {plan: "plus", years: 50}], points: true, rate: 5, review: true, scores: {exposure: "x-y", summary: []}}], rate: 378}, capped: [false, false], decision: "x-y", eligible: [378], threshold: 10, totals: {net: [378, 10]}}], + [{threshold: 1, account: {limit: 2, label: "é ü", balance: 2, birthDate: "2025-03-20T10:15:30Z", rate: 18, lines: [{age: null, rate: 3, amount: 0.25, payments: [{years: 50, plan: "basic"}, {years: 18, plan: "plus"}]}]}}, {account: {balance: 2, birthDate: "2025-03-20T10:15:30Z", bonus: 0, calc: {margin: 2}, health: 3, label: "é ü", limit: 2, lines: [{age: null, amount: 0.25, fee: true, ok: "2025", payments: [{plan: "basic", years: 50}, {plan: "plus", years: 18}], points: false, rate: 3, review: false, scores: {exposure: "é ü", summary: []}}], rate: 18}, capped: [false], decision: "é ü", eligible: [18], threshold: 1, totals: {net: [1]}}], + [{threshold: 10, account: {label: "gold", balance: 3, active: true, birthDate: "2025-03-20T10:15:30Z", rate: 1, lines: [{rate: 0.000001, amount: 3, payments: [{years: 7.25, plan: "basic"}, {years: 1.5, plan: "trial"}, {years: 7.25, plan: "plus"}]}]}}, {account: {active: true, balance: 3, birthDate: "2025-03-20T10:15:30Z", bonus: 0, calc: {margin: 10}, health: 10, label: "gold", lines: [{amount: 3, fee: true, ok: "2/0", payments: [{plan: "basic", years: 7.25}, {plan: "trial", years: 1.5}, {plan: "plus", years: 7.25}], points: false, rate: 0.000001, review: false, scores: {exposure: "gold", summary: []}}], rate: 1}, capped: [true], decision: "gold", eligible: [1], threshold: 10, totals: {net: [10]}}], + [{threshold: 0, account: {limit: 0.25, label: "Oslo", balance: 0.25, active: false, birthDate: "2030-12-31", rate: 0.25, lines: [{age: 100, rate: 5, amount: -0, payments: [{years: 18, plan: "basic"}, {years: 0.000001, plan: "basic"}]}, {age: 3, rate: 0.25, amount: 0.5, payments: [{years: 123456789.123, plan: "premium"}, {years: -500, plan: "basic"}]}, {age: 0.25, rate: 0.25, amount: 50, payments: []}, {age: 50, rate: 250, amount: 2, payments: []}, {age: 250, rate: 1000000, amount: 18, payments: [{years: 99999999999999999999, plan: "premium"}, {years: 1000, plan: "trial"}]}, {age: 18, rate: 18, amount: 0.25, payments: []}, {age: 1e3, rate: 10, amount: 0.25, payments: [{years: 2, plan: "premium"}]}, {age: 10, rate: 0.25, amount: 0.5, payments: [{years: 50, plan: "basic"}]}, {age: 18, rate: 10, amount: 7.25, payments: []}, {age: 0.25, rate: 5, amount: 0.25, payments: []}]}}, {account: {active: false, balance: 0.25, birthDate: "2030-12-31", bonus: 1449.50, calc: {margin: 0.25}, health: 0.25, label: "Oslo", limit: 0.25, lines: [{age: 100, amount: 0, fee: true, ok: "2030", payments: [{plan: "basic", years: 18}, {plan: "basic", years: 0.000001}], points: true, rate: 5, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 3, amount: 0.5, fee: true, ok: "2030", payments: [{plan: "premium", years: 123456789.123}, {plan: "basic", years: -500}], points: true, rate: 0.25, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 0.25, amount: 50, fee: true, ok: "2030", payments: [], points: true, rate: 0.25, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 50, amount: 2, fee: true, ok: "2030", payments: [], points: true, rate: 250, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 250, amount: 18, fee: true, ok: "2030", payments: [{plan: "premium", years: 99999999999999999999}, {plan: "trial", years: 1000}], points: true, rate: 1000000, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 18, amount: 0.25, fee: true, ok: "2030", payments: [], points: true, rate: 18, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 1000, amount: 0.25, fee: true, ok: "2030", payments: [{plan: "premium", years: 2}], points: true, rate: 10, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 10, amount: 0.5, fee: true, ok: "2030", payments: [{plan: "basic", years: 50}], points: true, rate: 0.25, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 18, amount: 7.25, fee: true, ok: "2030", payments: [], points: true, rate: 10, review: true, scores: {exposure: "Oslo", summary: []}}, {age: 0.25, amount: 0.25, fee: true, ok: "2030", payments: [], points: true, rate: 5, review: true, scores: {exposure: "Oslo", summary: []}}], rate: 0.25}, capped: [false, false, false], decision: "Oslo", eligible: [0.25, 0, 0.25], threshold: 0, totals: {net: [0.25, 0, 0]}}], + [{threshold: 0, account: {limit: "12", label: "a", balance: 250, active: true, birthDate: "2025-03-20", rate: 2, lines: [{age: 0.25, rate: 5, amount: 0, payments: [{years: 1, plan: "plus"}]}, {age: 10, rate: 1000, amount: 0, payments: [{years: 5, plan: "basic"}, {years: 123456789.123, plan: "plus"}]}, {age: 5, rate: 0, amount: 50, payments: [{years: -500, plan: "premium"}]}, {age: 1, rate: 50, amount: 10, payments: [{years: 0.25, plan: "trial"}, {years: -500, plan: "premium"}, {years: 3, plan: "basic"}]}]}}, "!error: InputValidationFailed"], + [{threshold: 0, account: {label: "A1", balance: 18, birthDate: "2025-03-20T10:15:30Z", rate: -0.5, lines: [{rate: 0.000001, amount: 1, payments: [{years: 100, plan: "basic"}]}]}}, {account: {balance: 18, birthDate: "2025-03-20T10:15:30Z", bonus: 0, calc: {margin: 0}, health: 0, label: "A1", lines: [{amount: 1, fee: false, ok: "2025", payments: [{plan: "basic", years: 100}], points: false, rate: 0.000001, review: false, scores: {exposure: "A1", summary: []}}], rate: -0.5}, capped: [false], decision: "A1", eligible: [-0.5], threshold: 0, totals: {net: [0]}}], + [{threshold: 0.5, account: {limit: 1.5, label: "a", balance: -0.5, active: false, birthDate: "2024-02-29", rate: 18, lines: [{age: -0.01, rate: 99.99, amount: 50, payments: [{years: 100, plan: "trial"}, {years: 50, plan: "plus"}]}, {age: 1, rate: 1.5, amount: 18, payments: [{years: 2, plan: "trial"}, {years: 0.25, plan: "basic"}, {years: 2.50, plan: "plus"}]}, {age: 5, rate: 5, amount: 10, payments: [{years: 1, plan: "basic"}, {years: 1000, plan: "basic"}, {years: 10, plan: "trial"}]}, {age: 18, rate: 0.25, amount: 3, payments: []}, {age: 100, rate: 2, amount: 10, payments: [{years: 18, plan: "basic"}, {years: 250, plan: "trial"}]}, {age: -500, rate: 123456789.123, amount: 1000000, payments: [{years: 50, plan: "basic"}]}, {age: 99.99, rate: 100, amount: 99.99, payments: [{years: 2, plan: "plus"}, {years: 5, plan: "basic"}, {years: 3, plan: "basic"}]}, {age: 5, rate: 1.5, amount: 5, payments: [{years: 5, plan: "trial"}, {years: 3, plan: "premium"}]}, {age: 0.5, rate: 2, amount: 5, payments: [{years: 5, plan: "basic"}]}, {age: -500, rate: 0.25, amount: 50, payments: [{years: 250, plan: "premium"}]}]}}, {account: {active: false, balance: -0.5, birthDate: "2024-02-29", bonus: 3.0, calc: {margin: 1.5}, health: 2.0, label: "a", limit: 1.5, lines: [{age: -0.01, amount: 50, fee: false, ok: "2024", payments: [{plan: "trial", years: 100}, {plan: "plus", years: 50}], points: true, rate: 99.99, review: true, scores: {exposure: "a", summary: []}}, {age: 1, amount: 18, fee: false, ok: "2024", payments: [{plan: "trial", years: 2}, {plan: "basic", years: 0.25}, {plan: "plus", years: 2.50}], points: true, rate: 1.5, review: true, scores: {exposure: "a", summary: []}}, {age: 5, amount: 10, fee: false, ok: "2024", payments: [{plan: "basic", years: 1}, {plan: "basic", years: 1000}, {plan: "trial", years: 10}], points: true, rate: 5, review: true, scores: {exposure: "a", summary: []}}, {age: 18, amount: 3, fee: false, ok: "2024", payments: [], points: true, rate: 0.25, review: true, scores: {exposure: "a", summary: []}}, {age: 100, amount: 10, fee: false, ok: "2024", payments: [{plan: "basic", years: 18}, {plan: "trial", years: 250}], points: true, rate: 2, review: true, scores: {exposure: "a", summary: []}}, {age: -500, amount: 1000000, fee: false, ok: "2024", payments: [{plan: "basic", years: 50}], points: true, rate: 123456789.123, review: true, scores: {exposure: "a", summary: []}}, {age: 99.99, amount: 99.99, fee: false, ok: "2024", payments: [{plan: "plus", years: 2}, {plan: "basic", years: 5}, {plan: "basic", years: 3}], points: true, rate: 100, review: true, scores: {exposure: "a", summary: []}}, {age: 5, amount: 5, fee: false, ok: "2024", payments: [{plan: "trial", years: 5}, {plan: "premium", years: 3}], points: true, rate: 1.5, review: true, scores: {exposure: "a", summary: []}}, {age: 0.5, amount: 5, fee: false, ok: "2024", payments: [{plan: "basic", years: 5}], points: true, rate: 2, review: true, scores: {exposure: "a", summary: []}}, {age: -500, amount: 50, fee: false, ok: "2024", payments: [{plan: "premium", years: 250}], points: true, rate: 0.25, review: true, scores: {exposure: "a", summary: []}}], rate: 18}, capped: [false], decision: "a", eligible: [18], threshold: 0.5, totals: {net: [0.5]}}], + ], +} + +// seed 340300 (attempt 0) +{ + name: "b 04: applicant/companies: 1 assertion, 5 expression, 2 table; 5 root, 3 per-member, 3 top-level computed", + policy: { + models: {applicant: {price: "number?", tier: "string(gold|silver|bronze)?", priority: "boolean?", years: "number", since: "date?", qty: "number", companies: "company[]"}, company: {years: "number?", name: "string"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {assertion: "margin", conditions: ["(applicant.tier ?? '') != 'bronze'", "(applicant.since ?? d('2025-01-01')).isAfter(d('2025-01-01'), 'month')", ["or", "all(applicant.companies, (#.years ?? 0) <= (#.years ?? 0))", 0], ["or", "cap > applicant.qty", 1], ["or", "matches(`${'x'}/${applicant.qty}`, '^.{2,}$')", 0]]}, + {expression: "segment", value: "{ok: none(applicant.companies, (#.years ?? 0) in [49..158])}"}, + {expression: "applicant.totals.risk", value: "filter(applicant.companies, #.years != null)"}, + {expression: "company.fee", value: "round(len(filter(applicant.companies, ((#.years ?? 0) > 0.25 or 1.5 > 1))) / 7, 3)"}, + {expression: "company.scores.share", value: "(applicant.price ?? 0) in [-3..91]"}, + {table: "t6", hit: "collect", inputs: ["applicant.price"], outputs: ["applicant.grade", "applicant.totals.net", "applicant.totals.bonus"], rules: [ + ["1000", "", "(applicant.tier ?? '') in ['bronze', 'silver']", "100"], + ["18", "-(cap)", "segment.ok", ""], + ]}, + {expression: "company.bucket", value: "applicant.price"}, + {table: "t8", inputs: ["(applicant.tier ?? '')", "applicant.years", "applicant.tier"], outputs: ["applicant.total[]"], rules: [ + ["", ">= 18", "'gold'", "(applicant.price ?? 0)"], + ["", "", "", "100"], + ]}, + ], + }, + cases: [ + [{cap: 100, applicant: {price: -500, tier: "silver", priority: true, years: 100, since: "2024-01-01", qty: 0.25, companies: [{years: 1, name: "Zed"}, {years: 5, name: "日本"}]}}, {applicant: {companies: [{bucket: -500, fee: 0.286, name: "Zed", scores: {share: false}, years: 1}, {bucket: -500, fee: 0.286, name: "日本", scores: {share: false}, years: 5}], grade: [], price: -500, priority: true, qty: 0.25, since: "2024-01-01", tier: "silver", total: [100], totals: {bonus: [], net: [], risk: [{bucket: -500, fee: 0.286, name: "Zed", scores: {share: false}, years: 1}, {bucket: -500, fee: 0.286, name: "日本", scores: {share: false}, years: 5}]}, years: 100}, cap: 100, margin: true}], + [{cap: -2, applicant: {price: -0.01, tier: "bronze", priority: true, years: 0.25, since: "2030-12-31", qty: 1000000, companies: [{years: -0, name: "12"}]}}, {applicant: {companies: [{bucket: -0.01, fee: 0.143, name: "12", scores: {share: true}, years: 0}], grade: [], price: -0.01, priority: true, qty: 1000000, since: "2030-12-31", tier: "bronze", total: [100], totals: {bonus: [], net: [], risk: [{bucket: -0.01, fee: 0.143, name: "12", scores: {share: true}, years: 0}]}, years: 0.25}, cap: -2, margin: true}], + [{cap: 100, applicant: {price: null, tier: null, priority: true, years: 100, since: null, qty: 1000, companies: [{years: 18, name: "日本"}, {name: "high"}]}}, {applicant: {companies: [{bucket: null, fee: 0.286, name: "日本", scores: {share: true}, years: 18}, {bucket: null, fee: 0.286, name: "high", scores: {share: true}}], grade: [], price: null, priority: true, qty: 1000, since: null, tier: null, total: [100], totals: {bonus: [], net: [], risk: [{bucket: null, fee: 0.286, name: "日本", scores: {share: true}, years: 18}]}, years: 100}, cap: 100, margin: true}], + [{cap: 10, applicant: {price: 100, tier: "gold", priority: false, years: 188, since: "2000-01-01", qty: 123456789.123, companies: []}}, {applicant: {companies: [], grade: [], price: 100, priority: false, qty: 123456789.123, since: "2000-01-01", tier: "gold", total: [100, 100], totals: {bonus: [], net: [], risk: []}, years: 188}, cap: 10, margin: true}], + [{cap: 0.5, applicant: {price: 0.25, tier: "gold", priority: false, years: 1000000, since: "2024-02-29", qty: 5, companies: []}}, {applicant: {companies: [], grade: [], price: 0.25, priority: false, qty: 5, since: "2024-02-29", tier: "gold", total: [0.25, 100], totals: {bonus: [], net: [], risk: []}, years: 1000000}, cap: 0.5, margin: true}], + [{cap: 10, applicant: {tier: "gold", priority: true, years: 0, qty: 18, companies: [{name: "high"}, {years: 2, name: "12"}, {name: "abc"}, {years: 1000000, name: " pad "}]}}, {applicant: {companies: [{bucket: null, fee: 0.571, name: "high", scores: {share: true}}, {bucket: null, fee: 0.571, name: "12", scores: {share: true}, years: 2}, {bucket: null, fee: 0.571, name: "abc", scores: {share: true}}, {bucket: null, fee: 0.571, name: " pad ", scores: {share: true}, years: 1000000}], grade: [], priority: true, qty: 18, tier: "gold", total: [100], totals: {bonus: [], net: [], risk: [{bucket: null, fee: 0.571, name: "12", scores: {share: true}, years: 2}, {bucket: null, fee: 0.571, name: " pad ", scores: {share: true}, years: 1000000}]}, years: 0}, cap: 10, margin: true}], + [{cap: 100, applicant: {price: 0.5, tier: null, years: -0.01, since: "2030-12-31", qty: 5, companies: [{years: 99.99, name: "VIP"}, {name: "retail"}, {years: 250, name: "x"}, {years: 1e3, name: " pad "}, {years: 50, name: "US"}, {years: null, name: "A1"}, {years: 1.5, name: "O'Neil"}, {years: 7.25, name: "O'Neil"}]}}, {applicant: {companies: [{bucket: 0.5, fee: 1.143, name: "VIP", scores: {share: true}, years: 99.99}, {bucket: 0.5, fee: 1.143, name: "retail", scores: {share: true}}, {bucket: 0.5, fee: 1.143, name: "x", scores: {share: true}, years: 250}, {bucket: 0.5, fee: 1.143, name: " pad ", scores: {share: true}, years: 1000}, {bucket: 0.5, fee: 1.143, name: "US", scores: {share: true}, years: 50}, {bucket: 0.5, fee: 1.143, name: "A1", scores: {share: true}, years: null}, {bucket: 0.5, fee: 1.143, name: "O'Neil", scores: {share: true}, years: 1.5}, {bucket: 0.5, fee: 1.143, name: "O'Neil", scores: {share: true}, years: 7.25}], grade: [], price: 0.5, qty: 5, since: "2030-12-31", tier: null, total: [100], totals: {bonus: [], net: [], risk: [{bucket: 0.5, fee: 1.143, name: "VIP", scores: {share: true}, years: 99.99}, {bucket: 0.5, fee: 1.143, name: "x", scores: {share: true}, years: 250}, {bucket: 0.5, fee: 1.143, name: " pad ", scores: {share: true}, years: 1000}, {bucket: 0.5, fee: 1.143, name: "US", scores: {share: true}, years: 50}, {bucket: 0.5, fee: 1.143, name: "O'Neil", scores: {share: true}, years: 1.5}, {bucket: 0.5, fee: 1.143, name: "O'Neil", scores: {share: true}, years: 7.25}]}, years: -0.01}, cap: 100, margin: true}], + [{cap: 100, applicant: {priority: true, years: 18, since: null, qty: 18, companies: [{years: null, name: " pad "}, {name: "retail"}]}}, {applicant: {companies: [{bucket: null, fee: 0.286, name: " pad ", scores: {share: true}, years: null}, {bucket: null, fee: 0.286, name: "retail", scores: {share: true}}], grade: [], priority: true, qty: 18, since: null, total: [100], totals: {bonus: [], net: [], risk: []}, years: 18}, cap: 100, margin: true}], + [{cap: 0.5, applicant: {price: 1000, tier: "bronze", priority: false, years: 1, since: "2000-01-01", qty: 50, companies: [], extraField: "x"}}, {applicant: {companies: [], extraField: "x", grade: [], price: 1000, priority: false, qty: 50, since: "2000-01-01", tier: "bronze", total: [100], totals: {bonus: [100], net: [true], risk: []}, years: 1}, cap: 0.5, margin: true}], + [{cap: 0.5, applicant: {price: null, tier: null, priority: null, years: 0.1, since: null, qty: 250, companies: [{years: -0.5, name: "é ü"}, {years: 1, name: "VIP"}, {years: 10, name: ""}, {years: 0, name: "low"}]}}, {applicant: {companies: [{bucket: null, fee: 0.571, name: "é ü", scores: {share: true}, years: -0.5}, {bucket: null, fee: 0.571, name: "VIP", scores: {share: true}, years: 1}, {bucket: null, fee: 0.571, name: "", scores: {share: true}, years: 10}, {bucket: null, fee: 0.571, name: "low", scores: {share: true}, years: 0}], grade: [], price: null, priority: null, qty: 250, since: null, tier: null, total: [100], totals: {bonus: [], net: [], risk: [{bucket: null, fee: 0.571, name: "é ü", scores: {share: true}, years: -0.5}, {bucket: null, fee: 0.571, name: "VIP", scores: {share: true}, years: 1}, {bucket: null, fee: 0.571, name: "", scores: {share: true}, years: 10}, {bucket: null, fee: 0.571, name: "low", scores: {share: true}, years: 0}]}, years: 0.1}, cap: 0.5, margin: true}], + [{cap: 10, applicant: {price: 249, tier: null, priority: null, years: 1000, since: null, qty: 99999999999999999999, companies: [{years: null, name: "日本"}, {name: "NL"}]}}, {applicant: {companies: [{bucket: 249, fee: 0.286, name: "日本", scores: {share: false}, years: null}, {bucket: 249, fee: 0.286, name: "NL", scores: {share: false}}], grade: [], price: 249, priority: null, qty: 99999999999999999999, since: null, tier: null, total: [100], totals: {bonus: [], net: [], risk: []}, years: 1000}, cap: 10, margin: true}], + [{cap: 0.5, applicant: {price: 65, tier: "silver", years: 7.25, qty: 1000000, companies: [{years: null, name: "retail"}, {years: 1000, name: "VIP"}]}}, {applicant: {companies: [{bucket: 65, fee: 0.286, name: "retail", scores: {share: true}, years: null}, {bucket: 65, fee: 0.286, name: "VIP", scores: {share: true}, years: 1000}], grade: [], price: 65, qty: 1000000, tier: "silver", total: [100], totals: {bonus: [], net: [], risk: [{bucket: 65, fee: 0.286, name: "VIP", scores: {share: true}, years: 1000}]}, years: 7.25}, cap: 0.5, margin: true}], + [{cap: 100, applicant: {price: null, tier: "gold", priority: null, years: -0.01, since: null, qty: -0.5, companies: [{years: 1000000, name: "gold"}, {name: "日本"}, {years: 7.25, name: "x"}, {name: "O'Neil"}]}}, {applicant: {companies: [{bucket: null, fee: 0.571, name: "gold", scores: {share: true}, years: 1000000}, {bucket: null, fee: 0.571, name: "日本", scores: {share: true}}, {bucket: null, fee: 0.571, name: "x", scores: {share: true}, years: 7.25}, {bucket: null, fee: 0.571, name: "O'Neil", scores: {share: true}}], grade: [], price: null, priority: null, qty: -0.5, since: null, tier: "gold", total: [100], totals: {bonus: [], net: [], risk: [{bucket: null, fee: 0.571, name: "gold", scores: {share: true}, years: 1000000}, {bucket: null, fee: 0.571, name: "x", scores: {share: true}, years: 7.25}]}, years: -0.01}, cap: 100, margin: true}], + [{cap: -2, applicant: {price: 99.99, tier: null, years: 2.50, since: "2024-02-29", qty: -0.01, companies: [{name: "low"}]}}, {applicant: {companies: [{bucket: 99.99, fee: 0.143, name: "low", scores: {share: false}}], grade: [], price: 99.99, qty: -0.01, since: "2024-02-29", tier: null, total: [100], totals: {bonus: [], net: [], risk: []}, years: 2.50}, cap: -2, margin: true}], + ], +} + +// seed 340400 (attempt 0) +{ + name: "b 05: borrower/parcels: 4 expression, 2 match, 1 table; 6 root, 4 per-member, 1 top-level computed", + policy: { + models: {borrower: {qty: "number", limit: "number", region: "string?", amount: "number", city: "string", parcels: "parcel[]"}, parcel: {age: "number?", kind: "string(retail|corporate)", vip: "boolean?"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {expression: "borrower.risk", value: "map(borrower.parcels, (#.age ?? 0))"}, + {table: "t2", inputs: ["(parcel.age ?? 0)", "(0.5 % (abs((parcel.age ?? 0)) + 1))", "borrower.qty"], outputs: ["parcel.exposure", "parcel.calc.capped"], rules: [ + ["1.5, 100", "2", "", "borrower.city", "(parcel.vip ?? false)"], + [">= 1", "5", "<= 2", "string((parcel.vip ?? false))", ""], + ["<= 250", "!= 2", "1.5, 3", "borrower.city", "(parcel.vip ?? false)"], + ["", "[5..144]", "", "(borrower.region ?? '')", "(parcel.vip ?? false)"], + ]}, + {expression: "grade", value: "filter(borrower.parcels, (#.age ?? 0) >= (#.age ?? 0))"}, + {expression: "borrower.points", value: "{v: 10 > 3, a: round(borrower.amount / 7, 2), n: trunc(borrower.limit)}"}, + {expression: "parcel.discount", value: "borrower.points.a"}, + {match: "parcel.level", arms: [["parcel.exposure == null", "(borrower.city + '-' + 'ok')"], ["isNumeric((parcel.exposure ?? ''))", "string((parcel.vip ?? false))"], ["", "`${borrower.points.v}/${borrower.points.a}`"]]}, + {match: "borrower.meta.summary", arms: [["(borrower.points.v and borrower.points.v)", "`${borrower.points.v}/${(borrower.points.n * borrower.qty)}`"], ["borrower.region == null", "`${10}/${borrower.points.v}`"], ["", "(borrower.region ?? '')"]]}, + ], + }, + cases: [ + [{cap: 1, borrower: {qty: 0.25, limit: 0, region: "a", amount: 2.50, city: "DE", parcels: []}}, {borrower: {amount: 2.50, city: "DE", limit: 0, meta: {summary: "true/0"}, parcels: [], points: {a: 0.36, n: 0, v: true}, qty: 0.25, region: "a", risk: []}, cap: 1, grade: []}], + [{cap: 0.5, borrower: {qty: -0.5, limit: 0.5, region: "x-y", amount: 0.5, city: "abc", parcels: []}}, {borrower: {amount: 0.5, city: "abc", limit: 0.5, meta: {summary: "true/0"}, parcels: [], points: {a: 0.07, n: 0, v: true}, qty: -0.5, region: "x-y", risk: []}, cap: 0.5, grade: []}], + [{cap: -2, borrower: {qty: 250, limit: 1.5, region: "retail", amount: 99.99, city: "DE", parcels: [{age: 5, kind: "corporate", vip: true}]}}, {borrower: {amount: 99.99, city: "DE", limit: 1.5, meta: {summary: "true/250"}, parcels: [{age: 5, calc: {capped: null}, discount: 14.28, exposure: null, kind: "corporate", level: "DE-ok", vip: true}], points: {a: 14.28, n: 1, v: true}, qty: 250, region: "retail", risk: [5]}, cap: -2, grade: [{age: 5, calc: {capped: null}, discount: 14.28, exposure: null, kind: "corporate", level: "DE-ok", vip: true}]}], + [{cap: 1, borrower: {qty: 0.5, limit: 5, region: null, amount: 2, city: "NL", parcels: [{kind: "retail", vip: null}, {age: 5, kind: "retail", vip: null}, {age: 3, kind: "retail", vip: false}, {kind: "corporate"}, {age: 123456789.123, kind: "retail", vip: false}, {age: null, kind: "retail"}, {age: -0.5, kind: "retail", vip: null}, {age: -0.5, kind: "retail", vip: false}, {age: 99999999999999999999, kind: "retail", vip: false}, {age: 1.5, kind: "retail", vip: null}, {age: 100, kind: "retail"}, {age: 10, kind: "corporate"}, {age: 2.50, kind: "retail", vip: null}, {age: 99999999999999999999, kind: "retail"}]}}, {borrower: {amount: 2, city: "NL", limit: 5, meta: {summary: "true/2.5"}, parcels: [{calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: 5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: 3, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {calc: {capped: null}, discount: 0.29, exposure: null, kind: "corporate", level: "NL-ok"}, {age: 123456789.123, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: null, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok"}, {age: -0.5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: -0.5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: 99999999999999999999, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: 1.5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: 100, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok"}, {age: 10, calc: {capped: null}, discount: 0.29, exposure: null, kind: "corporate", level: "NL-ok"}, {age: 2.50, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: 99999999999999999999, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok"}], points: {a: 0.29, n: 5, v: true}, qty: 0.5, region: null, risk: [0, 5, 3, 0, 123456789.123, 0, -0.5, -0.5, 99999999999999999999, 1.5, 100, 10, 2.50, 99999999999999999999]}, cap: 1, grade: [{calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: 5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: 3, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {calc: {capped: null}, discount: 0.29, exposure: null, kind: "corporate", level: "NL-ok"}, {age: 123456789.123, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: null, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok"}, {age: -0.5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: -0.5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: 99999999999999999999, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: 1.5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: 100, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok"}, {age: 10, calc: {capped: null}, discount: 0.29, exposure: null, kind: "corporate", level: "NL-ok"}, {age: 2.50, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok", vip: null}, {age: 99999999999999999999, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "NL-ok"}]}], + [{cap: 10, borrower: {qty: 99999999999999999999, region: "abc", amount: 2, city: "", parcels: [{age: 0.25, kind: "retail", vip: true}, {age: 7.25, kind: "corporate", vip: false}, {age: 7.25, kind: "retail", vip: true}]}}, "!error: MissingRequiredInputs"], + [{cap: 0, borrower: {qty: 2, limit: 99.99, region: "DE", amount: 99.99, city: "VIP", parcels: [{age: 250, kind: "corporate", vip: false}, {age: 99.99, kind: "retail", vip: true}]}}, {borrower: {amount: 99.99, city: "VIP", limit: 99.99, meta: {summary: "true/198"}, parcels: [{age: 250, calc: {capped: null}, discount: 14.28, exposure: null, kind: "corporate", level: "VIP-ok", vip: false}, {age: 99.99, calc: {capped: null}, discount: 14.28, exposure: null, kind: "retail", level: "VIP-ok", vip: true}], points: {a: 14.28, n: 99, v: true}, qty: 2, region: "DE", risk: [250, 99.99]}, cap: 0, grade: [{age: 250, calc: {capped: null}, discount: 14.28, exposure: null, kind: "corporate", level: "VIP-ok", vip: false}, {age: 99.99, calc: {capped: null}, discount: 14.28, exposure: null, kind: "retail", level: "VIP-ok", vip: true}]}], + [{cap: -2, borrower: {qty: 123456789.123, limit: 1.5, region: "retail", amount: -1, city: "", parcels: [{age: 123456789.123, kind: "retail", vip: true}, {kind: "retail", vip: true}, {age: 50, kind: "retail", vip: true}]}}, {borrower: {amount: -1, city: "", limit: 1.5, meta: {summary: "true/123456789.123"}, parcels: [{age: 123456789.123, calc: {capped: null}, discount: -0.14, exposure: null, kind: "retail", level: "-ok", vip: true}, {calc: {capped: null}, discount: -0.14, exposure: null, kind: "retail", level: "-ok", vip: true}, {age: 50, calc: {capped: null}, discount: -0.14, exposure: null, kind: "retail", level: "-ok", vip: true}], points: {a: -0.14, n: 1, v: true}, qty: 123456789.123, region: "retail", risk: [123456789.123, 0, 50]}, cap: -2, grade: [{age: 123456789.123, calc: {capped: null}, discount: -0.14, exposure: null, kind: "retail", level: "-ok", vip: true}, {calc: {capped: null}, discount: -0.14, exposure: null, kind: "retail", level: "-ok", vip: true}, {age: 50, calc: {capped: null}, discount: -0.14, exposure: null, kind: "retail", level: "-ok", vip: true}]}], + [{cap: 10, borrower: {qty: 1, limit: 1000, region: null, amount: -0, city: "Zed", parcels: [{kind: "retail"}]}}, {borrower: {amount: 0, city: "Zed", limit: 1000, meta: {summary: "true/1000"}, parcels: [{calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: "Zed-ok"}], points: {a: 0, n: 1000, v: true}, qty: 1, region: null, risk: [0]}, cap: 10, grade: [{calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: "Zed-ok"}]}], + [{cap: 0.5, borrower: {qty: 2, limit: 2, region: "x-y", amount: 1000, city: "NL", parcels: [{age: 250, kind: null, vip: true}, {age: 1, kind: "retail", vip: false}, {age: 1e3, kind: "retail", vip: true}, {age: 250, kind: "retail", vip: false}, {age: 0.25, kind: "corporate", vip: false}]}}, {borrower: {amount: 1000, city: "NL", limit: 2, meta: {summary: "true/4"}, parcels: [{age: 250, calc: {capped: null}, discount: 142.86, exposure: null, kind: null, level: "NL-ok", vip: true}, {age: 1, calc: {capped: null}, discount: 142.86, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: 1000, calc: {capped: null}, discount: 142.86, exposure: null, kind: "retail", level: "NL-ok", vip: true}, {age: 250, calc: {capped: null}, discount: 142.86, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: 0.25, calc: {capped: null}, discount: 142.86, exposure: null, kind: "corporate", level: "NL-ok", vip: false}], points: {a: 142.86, n: 2, v: true}, qty: 2, region: "x-y", risk: [250, 1, 1000, 250, 0.25]}, cap: 0.5, grade: [{age: 250, calc: {capped: null}, discount: 142.86, exposure: null, kind: null, level: "NL-ok", vip: true}, {age: 1, calc: {capped: null}, discount: 142.86, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: 1000, calc: {capped: null}, discount: 142.86, exposure: null, kind: "retail", level: "NL-ok", vip: true}, {age: 250, calc: {capped: null}, discount: 142.86, exposure: null, kind: "retail", level: "NL-ok", vip: false}, {age: 0.25, calc: {capped: null}, discount: 142.86, exposure: null, kind: "corporate", level: "NL-ok", vip: false}]}], + [{cap: 1, borrower: {qty: 177, limit: 0.1, region: "A1", amount: 1, city: "NL", parcels: []}}, {borrower: {amount: 1, city: "NL", limit: 0.1, meta: {summary: "true/0"}, parcels: [], points: {a: 0.14, n: 0, v: true}, qty: 177, region: "A1", risk: []}, cap: 1, grade: []}], + [{cap: 100, borrower: {qty: 99999999999999999999, limit: 250, region: "3.5", amount: 5, city: "x-y", parcels: [{age: 250, kind: "retail", vip: false}, {age: 10, kind: "corporate", vip: true}, {age: 123456789.123, kind: "retail", vip: false}]}}, {borrower: {amount: 5, city: "x-y", limit: 250, meta: {summary: "true/24999999999999999999750"}, parcels: [{age: 250, calc: {capped: null}, discount: 0.71, exposure: null, kind: "retail", level: "x-y-ok", vip: false}, {age: 10, calc: {capped: null}, discount: 0.71, exposure: null, kind: "corporate", level: "x-y-ok", vip: true}, {age: 123456789.123, calc: {capped: null}, discount: 0.71, exposure: null, kind: "retail", level: "x-y-ok", vip: false}], points: {a: 0.71, n: 250, v: true}, qty: 99999999999999999999, region: "3.5", risk: [250, 10, 123456789.123]}, cap: 100, grade: [{age: 250, calc: {capped: null}, discount: 0.71, exposure: null, kind: "retail", level: "x-y-ok", vip: false}, {age: 10, calc: {capped: null}, discount: 0.71, exposure: null, kind: "corporate", level: "x-y-ok", vip: true}, {age: 123456789.123, calc: {capped: null}, discount: 0.71, exposure: null, kind: "retail", level: "x-y-ok", vip: false}]}], + [{cap: 1, borrower: {qty: 100, limit: 7.25, region: "3.5", amount: 123456789.123, city: "DE", parcels: [{age: 1, kind: "corporate", vip: false}, {age: 123456789.123, kind: "retail", vip: true}], extraField: 1}}, {borrower: {amount: 123456789.123, city: "DE", extraField: 1, limit: 7.25, meta: {summary: "true/700"}, parcels: [{age: 1, calc: {capped: null}, discount: 17636684.16, exposure: null, kind: "corporate", level: "DE-ok", vip: false}, {age: 123456789.123, calc: {capped: null}, discount: 17636684.16, exposure: null, kind: "retail", level: "DE-ok", vip: true}], points: {a: 17636684.16, n: 7, v: true}, qty: 100, region: "3.5", risk: [1, 123456789.123]}, cap: 1, grade: [{age: 1, calc: {capped: null}, discount: 17636684.16, exposure: null, kind: "corporate", level: "DE-ok", vip: false}, {age: 123456789.123, calc: {capped: null}, discount: 17636684.16, exposure: null, kind: "retail", level: "DE-ok", vip: true}]}], + [{cap: 100, borrower: {qty: 0.000001, limit: 0.1, region: null, amount: 3, city: "retail", parcels: [{age: 3, kind: "corporate", vip: true}, {kind: "retail", vip: null}, {age: null, kind: "retail", vip: null}, {age: null, kind: "retail"}, {age: 2, kind: "retail", vip: null}]}}, {borrower: {amount: 3, city: "retail", limit: 0.1, meta: {summary: "true/0"}, parcels: [{age: 3, calc: {capped: null}, discount: 0.43, exposure: null, kind: "corporate", level: "retail-ok", vip: true}, {calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "retail-ok", vip: null}, {age: null, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "retail-ok", vip: null}, {age: null, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "retail-ok"}, {age: 2, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "retail-ok", vip: null}], points: {a: 0.43, n: 0, v: true}, qty: 0.000001, region: null, risk: [3, 0, 0, 0, 2]}, cap: 100, grade: [{age: 3, calc: {capped: null}, discount: 0.43, exposure: null, kind: "corporate", level: "retail-ok", vip: true}, {calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "retail-ok", vip: null}, {age: null, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "retail-ok", vip: null}, {age: null, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "retail-ok"}, {age: 2, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "retail-ok", vip: null}]}], + [{cap: 10, borrower: {qty: 3, limit: 7.25, region: " pad ", amount: 250, city: "gold", parcels: [{age: 0.5, kind: "retail", vip: false}, {age: 1000, kind: "retail", vip: false}, {age: 2, kind: "corporate", vip: false}]}}, {borrower: {amount: 250, city: "gold", limit: 7.25, meta: {summary: "true/21"}, parcels: [{age: 0.5, calc: {capped: false}, discount: 35.71, exposure: "gold", kind: "retail", level: "true/35.71", vip: false}, {age: 1000, calc: {capped: null}, discount: 35.71, exposure: null, kind: "retail", level: "gold-ok", vip: false}, {age: 2, calc: {capped: false}, discount: 35.71, exposure: "gold", kind: "corporate", level: "true/35.71", vip: false}], points: {a: 35.71, n: 7, v: true}, qty: 3, region: " pad ", risk: [0.5, 1000, 2]}, cap: 10, grade: [{age: 0.5, calc: {capped: false}, discount: 35.71, exposure: "gold", kind: "retail", level: "true/35.71", vip: false}, {age: 1000, calc: {capped: null}, discount: 35.71, exposure: null, kind: "retail", level: "gold-ok", vip: false}, {age: 2, calc: {capped: false}, discount: 35.71, exposure: "gold", kind: "corporate", level: "true/35.71", vip: false}]}], + [{cap: 1, borrower: {qty: 2, limit: 1, region: null, amount: 50, city: "A1", parcels: [{kind: "retail"}, {age: null, kind: "retail", vip: false}]}}, {borrower: {amount: 50, city: "A1", limit: 1, meta: {summary: "true/2"}, parcels: [{calc: {capped: null}, discount: 7.14, exposure: null, kind: "retail", level: "A1-ok"}, {age: null, calc: {capped: null}, discount: 7.14, exposure: null, kind: "retail", level: "A1-ok", vip: false}], points: {a: 7.14, n: 1, v: true}, qty: 2, region: null, risk: [0, 0]}, cap: 1, grade: [{calc: {capped: null}, discount: 7.14, exposure: null, kind: "retail", level: "A1-ok"}, {age: null, calc: {capped: null}, discount: 7.14, exposure: null, kind: "retail", level: "A1-ok", vip: false}]}], + [{cap: 0.5, borrower: {qty: 1, limit: 10, region: "NL", amount: 0.25, city: "VIP", parcels: [{age: 1, kind: "retail", vip: false}, {age: 0.1, kind: "retail", vip: false}]}}, {borrower: {amount: 0.25, city: "VIP", limit: 10, meta: {summary: "true/10"}, parcels: [{age: 1, calc: {capped: null}, discount: 0.04, exposure: null, kind: "retail", level: "VIP-ok", vip: false}, {age: 0.1, calc: {capped: null}, discount: 0.04, exposure: null, kind: "retail", level: "VIP-ok", vip: false}], points: {a: 0.04, n: 10, v: true}, qty: 1, region: "NL", risk: [1, 0.1]}, cap: 0.5, grade: [{age: 1, calc: {capped: null}, discount: 0.04, exposure: null, kind: "retail", level: "VIP-ok", vip: false}, {age: 0.1, calc: {capped: null}, discount: 0.04, exposure: null, kind: "retail", level: "VIP-ok", vip: false}]}], + [{cap: 0, borrower: {qty: 2, limit: 0, region: "DE", amount: 1e3, city: "NL", parcels: [{age: 65, kind: "corporate", vip: false}, {age: 355, kind: "retail", vip: true}]}}, {borrower: {amount: 1000, city: "NL", limit: 0, meta: {summary: "true/0"}, parcels: [{age: 65, calc: {capped: null}, discount: 142.86, exposure: null, kind: "corporate", level: "NL-ok", vip: false}, {age: 355, calc: {capped: null}, discount: 142.86, exposure: null, kind: "retail", level: "NL-ok", vip: true}], points: {a: 142.86, n: 0, v: true}, qty: 2, region: "DE", risk: [65, 355]}, cap: 0, grade: [{age: 65, calc: {capped: null}, discount: 142.86, exposure: null, kind: "corporate", level: "NL-ok", vip: false}, {age: 355, calc: {capped: null}, discount: 142.86, exposure: null, kind: "retail", level: "NL-ok", vip: true}]}], + [{cap: -2, borrower: {qty: 1000000, limit: -1, region: "abc", amount: -500, city: "-", parcels: [{age: 1.5, kind: "retail", vip: true}]}}, {borrower: {amount: -500, city: "-", limit: -1, meta: {summary: "true/-1000000"}, parcels: [{age: 1.5, calc: {capped: null}, discount: -71.43, exposure: null, kind: "retail", level: "--ok", vip: true}], points: {a: -71.43, n: -1, v: true}, qty: 1000000, region: "abc", risk: [1.5]}, cap: -2, grade: [{age: 1.5, calc: {capped: null}, discount: -71.43, exposure: null, kind: "retail", level: "--ok", vip: true}]}], + [{cap: 10, borrower: {qty: -500, limit: 2, region: "gold", amount: 0.5, city: "é ü", parcels: [{age: 2.50, kind: "retail", vip: true}]}}, {borrower: {amount: 0.5, city: "é ü", limit: 2, meta: {summary: "true/-1000"}, parcels: [{age: 2.50, calc: {capped: null}, discount: 0.07, exposure: null, kind: "retail", level: "é ü-ok", vip: true}], points: {a: 0.07, n: 2, v: true}, qty: -500, region: "gold", risk: [2.50]}, cap: 10, grade: [{age: 2.50, calc: {capped: null}, discount: 0.07, exposure: null, kind: "retail", level: "é ü-ok", vip: true}]}], + [{cap: 1, borrower: {qty: 0.25, limit: 2, region: "Zed", amount: 10, city: "Oslo", parcels: [{age: 2, kind: "retail"}, {age: 3, kind: "retail", vip: null}, {kind: "retail"}, {age: null, kind: "retail", vip: null}, {kind: "retail", vip: null}]}}, {borrower: {amount: 10, city: "Oslo", limit: 2, meta: {summary: "true/0.50"}, parcels: [{age: 2, calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok"}, {age: 3, calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok", vip: null}, {calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok"}, {age: null, calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok", vip: null}, {calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok", vip: null}], points: {a: 1.43, n: 2, v: true}, qty: 0.25, region: "Zed", risk: [2, 3, 0, 0, 0]}, cap: 1, grade: [{age: 2, calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok"}, {age: 3, calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok", vip: null}, {calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok"}, {age: null, calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok", vip: null}, {calc: {capped: null}, discount: 1.43, exposure: null, kind: "retail", level: "Oslo-ok", vip: null}]}], + [{cap: 1, borrower: {qty: -0, limit: 18, region: "O'Neil", amount: -0.01, city: "NL", parcels: []}}, {borrower: {amount: -0.01, city: "NL", limit: 18, meta: {summary: "true/0"}, parcels: [], points: {a: 0.00, n: 18, v: true}, qty: 0, region: "O'Neil", risk: []}, cap: 1, grade: []}], + [{cap: 0.5, borrower: {qty: 1e3, limit: 0.1, region: "O'Neil", amount: 2, city: "-", parcels: [{kind: "retail", vip: false}, {age: 0.5, kind: "retail"}, {age: 99999999999999999999, kind: "corporate", vip: true}]}}, {borrower: {amount: 2, city: "-", limit: 0.1, meta: {summary: "true/0"}, parcels: [{calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "--ok", vip: false}, {age: 0.5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "--ok"}, {age: 99999999999999999999, calc: {capped: null}, discount: 0.29, exposure: null, kind: "corporate", level: "--ok", vip: true}], points: {a: 0.29, n: 0, v: true}, qty: 1000, region: "O'Neil", risk: [0, 0.5, 99999999999999999999]}, cap: 0.5, grade: [{calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "--ok", vip: false}, {age: 0.5, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "--ok"}, {age: 99999999999999999999, calc: {capped: null}, discount: 0.29, exposure: null, kind: "corporate", level: "--ok", vip: true}]}], + [{cap: 0, borrower: {qty: 18, limit: 7.25, region: "ok", amount: 18, city: "日本", parcels: [{age: 5, kind: "corporate", vip: true}]}}, {borrower: {amount: 18, city: "日本", limit: 7.25, meta: {summary: "true/126"}, parcels: [{age: 5, calc: {capped: null}, discount: 2.57, exposure: null, kind: "corporate", level: "日本-ok", vip: true}], points: {a: 2.57, n: 7, v: true}, qty: 18, region: "ok", risk: [5]}, cap: 0, grade: [{age: 5, calc: {capped: null}, discount: 2.57, exposure: null, kind: "corporate", level: "日本-ok", vip: true}]}], + [{cap: -2, borrower: {qty: 0.5, limit: 250, region: "é ü", amount: 2, city: "Oslo", parcels: [{age: null, kind: "retail", vip: false}, {age: null, kind: "corporate", vip: false}]}}, {borrower: {amount: 2, city: "Oslo", limit: 250, meta: {summary: "true/125.0"}, parcels: [{age: null, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "Oslo-ok", vip: false}, {age: null, calc: {capped: null}, discount: 0.29, exposure: null, kind: "corporate", level: "Oslo-ok", vip: false}], points: {a: 0.29, n: 250, v: true}, qty: 0.5, region: "é ü", risk: [0, 0]}, cap: -2, grade: [{age: null, calc: {capped: null}, discount: 0.29, exposure: null, kind: "retail", level: "Oslo-ok", vip: false}, {age: null, calc: {capped: null}, discount: 0.29, exposure: null, kind: "corporate", level: "Oslo-ok", vip: false}]}], + [{cap: -2, borrower: {qty: 0.1, limit: 7.25, region: "12", amount: -1, city: "é ü", parcels: [{age: 2, kind: "corporate", vip: true}]}}, {borrower: {amount: -1, city: "é ü", limit: 7.25, meta: {summary: "true/0.7"}, parcels: [{age: 2, calc: {capped: null}, discount: -0.14, exposure: null, kind: "corporate", level: "é ü-ok", vip: true}], points: {a: -0.14, n: 7, v: true}, qty: 0.1, region: "12", risk: [2]}, cap: -2, grade: [{age: 2, calc: {capped: null}, discount: -0.14, exposure: null, kind: "corporate", level: "é ü-ok", vip: true}]}], + [{cap: 10, borrower: {qty: 354, limit: 0.5, region: "a-b-c", amount: 3, city: "3.5", parcels: [{age: 1e3, kind: "retail", vip: false}, {age: 1, kind: "retail", vip: true}, {age: 1, kind: "retail", vip: false}, {age: 2, kind: "retail", vip: true}, {age: 0, kind: "retail", vip: false}]}}, {borrower: {amount: 3, city: "3.5", limit: 0.5, meta: {summary: "true/0"}, parcels: [{age: 1000, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: false}, {age: 1, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: true}, {age: 1, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: false}, {age: 2, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: true}, {age: 0, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: false}], points: {a: 0.43, n: 0, v: true}, qty: 354, region: "a-b-c", risk: [1000, 1, 1, 2, 0]}, cap: 10, grade: [{age: 1000, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: false}, {age: 1, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: true}, {age: 1, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: false}, {age: 2, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: true}, {age: 0, calc: {capped: null}, discount: 0.43, exposure: null, kind: "retail", level: "3.5-ok", vip: false}]}], + [{cap: 0.5, borrower: {qty: 5, limit: -0.5, region: "", amount: 65, city: "-", parcels: [{age: 0.5, kind: "retail", vip: false}, {age: 0, kind: "retail", vip: true}, {age: 1.5, kind: "retail", vip: false}, {age: 250, kind: "corporate", vip: false}]}}, {borrower: {amount: 65, city: "-", limit: -0.5, meta: {summary: "true/0"}, parcels: [{age: 0.5, calc: {capped: null}, discount: 9.29, exposure: null, kind: "retail", level: "--ok", vip: false}, {age: 0, calc: {capped: null}, discount: 9.29, exposure: null, kind: "retail", level: "--ok", vip: true}, {age: 1.5, calc: {capped: null}, discount: 9.29, exposure: null, kind: "retail", level: "--ok", vip: false}, {age: 250, calc: {capped: null}, discount: 9.29, exposure: null, kind: "corporate", level: "--ok", vip: false}], points: {a: 9.29, n: -0, v: true}, qty: 5, region: "", risk: [0.5, 0, 1.5, 250]}, cap: 0.5, grade: [{age: 0.5, calc: {capped: null}, discount: 9.29, exposure: null, kind: "retail", level: "--ok", vip: false}, {age: 0, calc: {capped: null}, discount: 9.29, exposure: null, kind: "retail", level: "--ok", vip: true}, {age: 1.5, calc: {capped: null}, discount: 9.29, exposure: null, kind: "retail", level: "--ok", vip: false}, {age: 250, calc: {capped: null}, discount: 9.29, exposure: null, kind: "corporate", level: "--ok", vip: false}]}], + [{cap: 100, borrower: {qty: 1, limit: 123456789.123, region: "-", amount: 1.5, city: "A1", parcels: [{age: 0.1, kind: "corporate", vip: true}, {age: 0, kind: "retail", vip: true}]}}, {borrower: {amount: 1.5, city: "A1", limit: 123456789.123, meta: {summary: "true/123456789"}, parcels: [{age: 0.1, calc: {capped: null}, discount: 0.21, exposure: null, kind: "corporate", level: "A1-ok", vip: true}, {age: 0, calc: {capped: null}, discount: 0.21, exposure: null, kind: "retail", level: "A1-ok", vip: true}], points: {a: 0.21, n: 123456789, v: true}, qty: 1, region: "-", risk: [0.1, 0]}, cap: 100, grade: [{age: 0.1, calc: {capped: null}, discount: 0.21, exposure: null, kind: "corporate", level: "A1-ok", vip: true}, {age: 0, calc: {capped: null}, discount: 0.21, exposure: null, kind: "retail", level: "A1-ok", vip: true}]}], + [{cap: 0.5, borrower: {qty: 1, limit: 1.5, region: "a", city: "-", parcels: []}}, "!error: MissingRequiredInputs"], + [{cap: -2, borrower: {qty: 2, limit: 5, region: null, amount: 0, city: " pad ", parcels: [{age: 10, kind: "retail"}, {age: null, kind: "retail", vip: null}, {kind: "retail"}, {kind: "retail"}, {age: 99.99, kind: "retail", vip: true}]}}, {borrower: {amount: 0, city: " pad ", limit: 5, meta: {summary: "true/10"}, parcels: [{age: 10, calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok"}, {age: null, calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok", vip: null}, {calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok"}, {calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok"}, {age: 99.99, calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok", vip: true}], points: {a: 0, n: 5, v: true}, qty: 2, region: null, risk: [10, 0, 0, 0, 99.99]}, cap: -2, grade: [{age: 10, calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok"}, {age: null, calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok", vip: null}, {calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok"}, {calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok"}, {age: 99.99, calc: {capped: null}, discount: 0, exposure: null, kind: "retail", level: " pad -ok", vip: true}]}], + ], +} + +// seed 340500 (attempt 0) +{ + name: "b 06: claim/parcels: 2 assertion, 4 expression, 5 table; 5 root, 10 per-member, 6 top-level computed", + policy: { + models: {claim: {score: "number?", country: "string", dueDate: "date?", parcels: "parcel[]"}, parcel: {qty: "number", active: "boolean", label: "string?"}}, + blocks: [ + {expression: "parcel.ok", value: "trim(`${parcel.surcharge}/${(parcel.calc.risk ?? 0) == (scores.adjusted ?? 0)}`)"}, + {assertion: "parcel.review", conditions: [["or", "(parcel.calc.penalty ?? 0) in [22..198)", 0], "(parcel.qty) / (abs((scores.adjusted ?? 0)) + 1) <= parcel.qty", ["and", "(parcel.active and (bucket ?? false))", 0], ["or", "(not (parcel.surcharge) or ((bucket ?? false) and (bucket ?? false)))", 1]]}, + {assertion: "parcel.surcharge", conditions: [["or", "((claim.score ?? 0) % (abs((claim.score ?? 0)) + 1)) <= parcel.qty", 0], ["or", "(claim.score ?? 0) <= (claim.score ?? 0)", 0]]}, + {expression: "flags.health", value: "filter(claim.parcels, contains(['low', 'VIP', ''], (#.label ?? '')))"}, + {table: "t5", inputs: ["sum(map(claim.parcels, (#.calc.penalty ?? 0)))", "(claim.dueDate ?? d('2025-01-01'))", "claim.bonus.n"], outputs: ["quota", "fee"], rules: [ + ["5", ">= d('2024-01-01')", "", "'x'", ""], + ["[0.25..453.25]", "", "[250..711]", "claim.country", "'high'"], + ["> 18", "", "!= 0", "(flag ?? '')", "claim.country"], + ]}, + {expression: "parcel.share", value: "(parcel.calc.risk ?? 0) in [9..152]"}, + {table: "t3", inputs: ["(claim.score ?? 0)", "claim.country", "(claim.dueDate ?? d('2025-01-01'))"], outputs: ["scores.adjusted", "bucket", "flag"], rules: [ + ["[1..264]", "", "< d('2025-01-01')", "(0 * (claim.score ?? 0))", "(claim.score ?? 0) > 50", "claim.country"], + [">= 0", "", ">= d('2025-03-20')", "", "(claim.score ?? 0) > 1", "claim.country"], + ["", "", "", "(claim.score ?? 0)", "1 > 2", "claim.country"], + ]}, + {expression: "claim.bonus", value: "{n: trunc((scores.adjusted ?? 0)), a: none(claim.parcels, #.qty <= (#.calc.risk ?? 0))}"}, + {table: "t10", hit: "collect", inputs: ["claim.score", "flag", "claim.score"], outputs: ["parcel.discount", "parcel.total", "parcel.totals.exposure"], rules: [ + ["", "'x'", "", "", "", "parcel.active"], + ["", "'VIP'", "", "parcel.ok", "", ""], + ]}, + {table: "t2", inputs: ["parcel.label", "trunc(parcel.qty)"], outputs: ["parcel.calc.rank[]", "parcel.calc.penalty", "parcel.calc.risk"], rules: [ + ["'VIP'", "<= 0", "", "(claim.score ?? 0)", "(claim.score ?? 0)"], + ["'x'", "", "", "10", ""], + ["'DE'", ">= 3", "isNumeric(claim.country)", "2", "len(filter(claim.parcels, #.qty in [28..132]))"], + ["", ">= 0.25", "parcel.active", "parcel.qty", "parcel.qty"], + ["'a'", "> 18", "parcel.active", "(claim.score ?? 0)", "10"], + ["", "", "", "(claim.score ?? 0)", "(claim.score ?? 0)"], + ]}, + {table: "t8", hit: "collect", inputs: [null], outputs: ["claim.points", "claim.decision"], rules: [ + ["(scores.adjusted ?? 0) != (scores.adjusted ?? 0)", "(quota ?? '')", "(fee ?? '')"], + ["", "(quota ?? '')", "(fee ?? '')"], + ["(claim.dueDate ?? d('2025-01-01')).isBefore(d('2000-06-30'), 'month')", "(flag ?? '')", "'Oslo'"], + ["isNumeric(claim.country)", "(fee ?? '')", ""], + ["len((quota ?? '')) > 3", "(quota ?? '')", ""], + ["", "(fee ?? '')", "(flag ?? '')"], + ["10 == (claim.score ?? 0)", "", "(split((flag ?? ''), '-')[0] ?? 'none')"], + ]}, + ], + }, + cases: [ + [{claim: {score: 0.25, country: " pad ", dueDate: "2000-01-01", parcels: []}}, {bucket: false, claim: {bonus: {a: true, n: 0}, country: " pad ", decision: ["", "Oslo", " pad "], dueDate: "2000-01-01", parcels: [], points: ["", " pad ", ""], score: 0.25}, fee: null, flag: " pad ", flags: {health: []}, quota: null, scores: {adjusted: 0.25}}], + [{claim: {score: 0, country: "-", dueDate: null, parcels: [{qty: 0, active: true, label: "DE"}, {qty: 100, active: true}, {qty: 0.5, active: false, label: "a"}, {qty: 1000, active: true, label: "x"}]}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "-", decision: ["", "-"], dueDate: null, parcels: [{active: true, calc: {penalty: 0, rank: [], risk: 0}, discount: [], label: "DE", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 100, rank: [true], risk: 100}, discount: [], qty: 100, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 0, rank: [], risk: 0}, discount: [], label: "a", qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 10, rank: [true], risk: 1000}, discount: [], label: "x", qty: 1000, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 0}, fee: null, flag: "-", flags: {health: [{active: true, calc: {penalty: 100, rank: [true], risk: 100}, discount: [], qty: 100, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: 0}}], + [{claim: {score: 0.25, country: "Zed", dueDate: "2025-03-20T10:15:30Z", parcels: [{qty: 0.5, active: true, label: "VIP"}, {qty: 10, active: false, label: "Oslo"}, {qty: 0.000001, active: false, label: "US"}, {qty: 0, active: false, label: "a"}, {qty: 1e3, active: false, label: "low"}]}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "Zed", decision: ["", "Zed"], dueDate: "2025-03-20T10:15:30Z", parcels: [{active: true, calc: {penalty: 0.25, rank: [], risk: 0.25}, discount: [], label: "VIP", qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 10, rank: [false], risk: 10}, discount: [], label: "Oslo", qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 0.25, rank: [], risk: 0.25}, discount: [], label: "US", qty: 0.000001, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 0.25, rank: [], risk: 0.25}, discount: [], label: "a", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 1000, rank: [false], risk: 1000}, discount: [], label: "low", qty: 1000, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 0.25}, fee: null, flag: "Zed", flags: {health: [{active: true, calc: {penalty: 0.25, rank: [], risk: 0.25}, discount: [], label: "VIP", qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 1000, rank: [false], risk: 1000}, discount: [], label: "low", qty: 1000, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: 0.25}}], + [{claim: {score: 50, country: "gold", dueDate: "2000-01-01", parcels: []}}, {bucket: false, claim: {bonus: {a: true, n: 0}, country: "gold", decision: ["", "Oslo", "gold"], dueDate: "2000-01-01", parcels: [], points: ["", "gold", ""], score: 50}, fee: null, flag: "gold", flags: {health: []}, quota: null, scores: {adjusted: 0}}], + [{claim: {score: 1, country: "retail", dueDate: "2025-03-20T10:15:30Z", parcels: [{qty: 0.25, active: false, label: "VIP"}]}}, {bucket: false, claim: {bonus: {a: false, n: 1}, country: "retail", decision: ["", "retail"], dueDate: "2025-03-20T10:15:30Z", parcels: [{active: false, calc: {penalty: 1, rank: [], risk: 1}, discount: [], label: "VIP", qty: 0.25, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 1}, fee: null, flag: "retail", flags: {health: [{active: false, calc: {penalty: 1, rank: [], risk: 1}, discount: [], label: "VIP", qty: 0.25, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: 1}}], + [{claim: {score: 10, country: "Zed", dueDate: "2024-02-29", parcels: [{qty: 5, active: true, label: "x"}, {qty: 250, active: false, label: "VIP"}], extraField: 1}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "Zed", decision: ["", "Zed", "Zed"], dueDate: "2024-02-29", extraField: 1, parcels: [{active: true, calc: {penalty: 10, rank: [true], risk: 5}, discount: [], label: "x", qty: 5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 250, rank: [false], risk: 250}, discount: [], label: "VIP", qty: 250, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 10}, fee: null, flag: "Zed", flags: {health: [{active: false, calc: {penalty: 250, rank: [false], risk: 250}, discount: [], label: "VIP", qty: 250, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: 0}}], + [{claim: {score: 99.99, country: "x", parcels: [{qty: 5, active: true, label: null}]}}, {bucket: false, claim: {bonus: {a: false, n: 99}, country: "x", decision: ["", "x"], parcels: [{active: true, calc: {penalty: 5, rank: [true], risk: 5}, discount: [], label: null, qty: 5, review: false, share: false, surcharge: true, total: [], totals: {exposure: [true]}}], points: ["x", ""], score: 99.99}, fee: null, flag: "x", flags: {health: [{active: true, calc: {penalty: 5, rank: [true], risk: 5}, discount: [], label: null, qty: 5, review: false, share: false, surcharge: true, total: [], totals: {exposure: [true]}}]}, quota: "x", scores: {adjusted: 99.99}}], + [{claim: {score: 1000000, country: "low", dueDate: "2024-01-01", parcels: [{qty: 3, active: true, label: ""}]}}, {bucket: false, claim: {bonus: {a: false, n: 1000000}, country: "low", decision: ["", "low"], dueDate: "2024-01-01", parcels: [{active: true, calc: {penalty: 3, rank: [true], risk: 3}, discount: [], label: "", qty: 3, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 1000000}, fee: null, flag: "low", flags: {health: [{active: true, calc: {penalty: 3, rank: [true], risk: 3}, discount: [], label: "", qty: 3, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: 1000000}}], + [{claim: {score: 50, country: "a-b-c", dueDate: "1990-06-15", parcels: [{active: true, label: "12"}, {qty: 0.25, active: true, label: "DE"}, {qty: 0.25, active: false, label: "12"}, {qty: 18, active: false, label: "VIP"}, {qty: -1, active: false, label: "VIP"}]}}, "!error: ExpressionFailed"], + [{claim: {country: "VIP", dueDate: "2025-03-20", parcels: []}}, {bucket: false, claim: {bonus: {a: true, n: 0}, country: "VIP", decision: ["", "VIP"], dueDate: "2025-03-20", parcels: [], points: ["", ""]}, fee: null, flag: "VIP", flags: {health: []}, quota: null, scores: {adjusted: 0}}], + [{claim: {score: 10, country: "VIP", parcels: [{qty: -1, active: false, label: null}, {qty: 1.5, active: true, label: "high"}]}}, {bucket: false, claim: {bonus: {a: false, n: 10}, country: "VIP", decision: ["", "VIP", "VIP"], parcels: [{active: false, calc: {penalty: 10, rank: [], risk: 10}, discount: ["true/true"], label: null, ok: "true/true", qty: -1, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 1.5, rank: [true], risk: 1.5}, discount: ["true/false"], label: "high", ok: "true/false", qty: 1.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 10}, fee: null, flag: "VIP", flags: {health: [{active: false, calc: {penalty: 10, rank: [], risk: 10}, discount: ["true/true"], label: null, ok: "true/true", qty: -1, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: 10}}], + [{claim: {score: -0.5, country: "US", dueDate: "2025-03-20T10:15:30Z", parcels: [{qty: 0, active: false, label: ""}, {qty: 0, active: false, label: "-"}, {qty: 1e3, active: true, label: "Oslo"}, {qty: 5, active: true, label: "-"}, {qty: 10, active: true, label: "NL"}, {qty: 1.5, active: false, label: "x-y"}, {qty: 65, active: false, label: "Oslo"}, {qty: 18, active: true, label: "VIP"}, {qty: 0, active: true, label: "NL"}, {qty: 0, active: true, label: "A1"}, {qty: 0, active: true, label: "NL"}, {qty: 0, active: false, label: "Oslo"}, {qty: 0.25, active: true, label: "VIP"}, {qty: 99999999999999999999, active: false, label: "VIP"}]}}, {bucket: false, claim: {bonus: {a: false, n: -0}, country: "US", decision: ["", "US"], dueDate: "2025-03-20T10:15:30Z", parcels: [{active: false, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "-", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 1000, rank: [true], risk: 1000}, discount: [], label: "Oslo", qty: 1000, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 5, rank: [true], risk: 5}, discount: [], label: "-", qty: 5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 10, rank: [true], risk: 10}, discount: [], label: "NL", qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 1.5, rank: [false], risk: 1.5}, discount: [], label: "x-y", qty: 1.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 65, rank: [false], risk: 65}, discount: [], label: "Oslo", qty: 65, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 18, rank: [true], risk: 18}, discount: [], label: "VIP", qty: 18, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "NL", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "A1", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "NL", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "Oslo", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "VIP", qty: 0.25, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 99999999999999999999, rank: [false], risk: 99999999999999999999}, discount: [], label: "VIP", qty: 99999999999999999999, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: -0.5}, fee: null, flag: "US", flags: {health: [{active: false, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "", qty: 0, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 18, rank: [true], risk: 18}, discount: [], label: "VIP", qty: 18, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: -0.5, rank: [], risk: -0.5}, discount: [], label: "VIP", qty: 0.25, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 99999999999999999999, rank: [false], risk: 99999999999999999999}, discount: [], label: "VIP", qty: 99999999999999999999, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: -0.5}}], + [{claim: {score: 10, country: "3.5", dueDate: "2025-03-20T10:15:30Z", parcels: []}}, {bucket: true, claim: {bonus: {a: true, n: 10}, country: "3.5", decision: ["", "3.5", "3.5"], dueDate: "2025-03-20T10:15:30Z", parcels: [], points: ["", "", ""], score: 10}, fee: null, flag: "3.5", flags: {health: []}, quota: null, scores: {adjusted: 10}}], + [{claim: {score: 2.50, country: false, dueDate: "2024-01-01", parcels: [{qty: 5, active: true, label: "O'Neil"}, {qty: 5, active: true, label: "a"}, {qty: 123456789.123, active: false, label: "abc"}]}}, "!error: InputValidationFailed"], + [{claim: {country: "x", parcels: [{qty: 65, active: false}]}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "x", decision: ["", "x"], parcels: [{active: false, calc: {penalty: 65, rank: [false], risk: 65}, discount: [], qty: 65, review: false, share: true, surcharge: true, total: [], totals: {exposure: [false]}}], points: ["", ""]}, fee: null, flag: "x", flags: {health: [{active: false, calc: {penalty: 65, rank: [false], risk: 65}, discount: [], qty: 65, review: false, share: true, surcharge: true, total: [], totals: {exposure: [false]}}]}, quota: null, scores: {adjusted: 0}}], + [{claim: {score: 0.1, country: "VIP", dueDate: "2025-03-20T10:15:30Z", parcels: [{qty: 2.50, active: false, label: "retail"}, {qty: 10, active: true, label: "abc"}]}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "VIP", decision: ["", "VIP"], dueDate: "2025-03-20T10:15:30Z", parcels: [{active: false, calc: {penalty: 2.50, rank: [false], risk: 2.50}, discount: ["true/false"], label: "retail", ok: "true/false", qty: 2.50, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 10, rank: [true], risk: 10}, discount: ["true/false"], label: "abc", ok: "true/false", qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 0.1}, fee: null, flag: "VIP", flags: {health: []}, quota: null, scores: {adjusted: 0.1}}], + [{claim: {score: 5, country: "VIP", dueDate: "2024-01-01", parcels: [{qty: 491, active: true, label: "12"}]}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "VIP", decision: ["", "VIP"], dueDate: "2024-01-01", parcels: [{active: true, calc: {penalty: 491, rank: [true], risk: 491}, discount: ["true/false"], label: "12", ok: "true/false", qty: 491, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 5}, fee: null, flag: "VIP", flags: {health: []}, quota: null, scores: {adjusted: 0}}], + [{claim: {country: "a-b-c", parcels: [{qty: 10, active: true}, {qty: 10, active: false, label: null}, {qty: 0.25, active: false, label: "A1"}, {qty: 10, active: false}, {qty: 2, active: false}]}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "a-b-c", decision: ["", "a-b-c"], parcels: [{active: true, calc: {penalty: 10, rank: [true], risk: 10}, discount: [], qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 10, rank: [false], risk: 10}, discount: [], label: null, qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 0, rank: [], risk: 0}, discount: [], label: "A1", qty: 0.25, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 10, rank: [false], risk: 10}, discount: [], qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 2, rank: [false], risk: 2}, discount: [], qty: 2, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""]}, fee: null, flag: "a-b-c", flags: {health: [{active: true, calc: {penalty: 10, rank: [true], risk: 10}, discount: [], qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 10, rank: [false], risk: 10}, discount: [], label: null, qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 10, rank: [false], risk: 10}, discount: [], qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 2, rank: [false], risk: 2}, discount: [], qty: 2, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: 0}}], + [{claim: {score: 5, country: "Oslo", dueDate: "2024-01-01", parcels: [{qty: 99.99, active: false, label: "Zed"}, {qty: 0.5, active: true, label: " pad "}, {qty: -1, active: true, label: "A1"}, {qty: -1, active: true, label: "Oslo"}, {qty: 0.25, active: true, label: "Oslo"}]}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "Oslo", decision: ["", "Oslo"], dueDate: "2024-01-01", parcels: [{active: false, calc: {penalty: 99.99, rank: [false], risk: 99.99}, discount: [], label: "Zed", qty: 99.99, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 5, rank: [], risk: 5}, discount: [], label: " pad ", qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 5, rank: [], risk: 5}, discount: [], label: "A1", qty: -1, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 5, rank: [], risk: 5}, discount: [], label: "Oslo", qty: -1, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 5, rank: [], risk: 5}, discount: [], label: "Oslo", qty: 0.25, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""], score: 5}, fee: null, flag: "Oslo", flags: {health: []}, quota: null, scores: {adjusted: 0}}], + [{claim: {country: "x-y", dueDate: "2024-02-29", parcels: [{qty: 250, active: false}, {qty: 10, active: true, label: "x-y"}]}}, {bucket: false, claim: {bonus: {a: false, n: 0}, country: "x-y", decision: ["", "x-y"], dueDate: "2024-02-29", parcels: [{active: false, calc: {penalty: 250, rank: [false], risk: 250}, discount: [], qty: 250, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 10, rank: [true], risk: 10}, discount: [], label: "x-y", qty: 10, review: false, share: true, surcharge: true, total: [], totals: {exposure: []}}], points: ["", ""]}, fee: null, flag: "x-y", flags: {health: [{active: false, calc: {penalty: 250, rank: [false], risk: 250}, discount: [], qty: 250, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}]}, quota: null, scores: {adjusted: 0}}], + [{claim: {score: 2, country: "DE", dueDate: null, parcels: [{qty: 0.5, active: false, label: "O'Neil"}, {qty: 250, active: true, label: null}, {qty: 0.5, active: true}, {qty: 0.5, active: false, label: "VIP"}]}}, {bucket: false, claim: {bonus: {a: false, n: 2}, country: "DE", decision: ["DE", "DE"], dueDate: null, parcels: [{active: false, calc: {penalty: 2, rank: [], risk: 2}, discount: [], label: "O'Neil", qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 250, rank: [true], risk: 250}, discount: [], label: null, qty: 250, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 2, rank: [], risk: 2}, discount: [], qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 2, rank: [], risk: 2}, discount: [], label: "VIP", qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}], points: ["DE", "DE"], score: 2}, fee: "DE", flag: "DE", flags: {health: [{active: true, calc: {penalty: 250, rank: [true], risk: 250}, discount: [], label: null, qty: 250, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: true, calc: {penalty: 2, rank: [], risk: 2}, discount: [], qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}, {active: false, calc: {penalty: 2, rank: [], risk: 2}, discount: [], label: "VIP", qty: 0.5, review: false, share: false, surcharge: true, total: [], totals: {exposure: []}}]}, quota: "DE", scores: {adjusted: 2}}], + [{claim: {score: 0, country: "DE", dueDate: "2024-01-01", parcels: [], extraField: 1}}, {bucket: false, claim: {bonus: {a: true, n: 0}, country: "DE", decision: ["", "DE"], dueDate: "2024-01-01", extraField: 1, parcels: [], points: ["", ""], score: 0}, fee: null, flag: "DE", flags: {health: []}, quota: null, scores: {adjusted: 0}}], + ], +} + +// seed 340600 (attempt 0) +{ + name: "b 07: applicant/lines: 8 expression, 3 match; 3 root, 7 per-member, 2 top-level computed", + policy: { + models: {applicant: {price: "number", vip: "boolean?", balance: "number?", lines: "line[]?"}, line: {days: "number", active: "boolean", vip: "boolean", tier: "string(gold|silver|bronze)"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {expression: "eligible", value: "-(((avg(map((applicant.lines ?? []), #.days)) ?? 0) + (10 - cap)))"}, + {expression: "line.segment", value: "{n: (line.vip and line.vip)}"}, + {match: "applicant.total", arms: [["(1.5 + eligible) == cap", "`${0.25}/${applicant.balance != null}`"], ["isNumeric(((applicant.vip ?? false) ? 'ok' : 'x'))", "'DE'"], ["startsWith(`${eligible}/${(applicant.vip ?? false)}`, 'gold')", "`${eligible}/${(applicant.vip ?? false)}`"], ["", "'high'"]]}, + {match: "line.surcharge", arms: [["not (line.active)", "applicant.total"], ["((applicant.vip ?? false) and (applicant.vip ?? false))", "'A1'"], ["contains(['x', 'high', ''], applicant.total)", "applicant.total"], ["", "'retail'"]]}, + {expression: "line.scores.risk", value: "applicant.balance"}, + {expression: "line.decision", value: "-((line.scores.risk ?? 0))"}, + {expression: "applicant.exposure", value: "string(-(cap))"}, + {expression: "line.points", value: "len(applicant.exposure) > 0"}, + {expression: "quota", value: "cap in (28..226]"}, + {expression: "applicant.meta.capped", value: "cap < 1.5"}, + {match: "line.adjusted", arms: [["isNumeric(applicant.total)", "`${line.points}/${line.vip}`"], ["(avg(map((applicant.lines ?? []), 3)) ?? 0) <= (line.scores.risk ?? 0)", "(split(line.surcharge, '-')[0] ?? 'none')"], ["line.scores.risk == null", "applicant.exposure"], ["", "applicant.total"]]}, + ], + }, + cases: [ + [{cap: -2, applicant: {price: 1000000, vip: null, lines: [{days: 1e3, active: true, vip: false, tier: "silver"}, {days: 0.000001, active: true, vip: false, tier: "silver"}, {days: 65, active: false, vip: false, tier: "gold"}]}}, {applicant: {exposure: "2", lines: [{active: true, adjusted: "2", days: 1000, decision: -0, scores: {risk: null}, segment: {n: false}, tier: "silver", vip: false}, {active: true, adjusted: "2", days: 0.000001, decision: -0, scores: {risk: null}, segment: {n: false}, tier: "silver", vip: false}, {active: false, adjusted: "2", days: 65, decision: -0, scores: {risk: null}, segment: {n: false}, tier: "gold", vip: false}], meta: {capped: true}, price: 1000000, total: "high", vip: null}, cap: -2, eligible: -367.00000033333333333333333333, quota: false}], + [{cap: 0, applicant: {price: 100, vip: false, balance: 123456789.123, lines: [{days: 1, active: true, vip: false, tier: "silver"}]}}, {applicant: {balance: 123456789.123, lines: [{active: true, adjusted: "high", days: 1, decision: -123456789.123, scores: {risk: 123456789.123}, segment: {n: false}, surcharge: "high", tier: "silver", vip: false}], meta: {capped: true}, price: 100, total: "high", vip: false}, cap: 0, eligible: -11, quota: false}], + [{cap: 0, applicant: {price: -0.5, vip: true, balance: 250, lines: []}}, "!error: ExpressionFailed"], + [{cap: -2, applicant: {price: 0.5, vip: false, balance: 99999999999999999999, lines: [{days: 0.1, active: true, vip: true, tier: "bronze"}], extraField: 1}}, {applicant: {balance: 99999999999999999999, extraField: 1, lines: [{active: true, adjusted: "high", days: 0.1, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: true}, surcharge: "high", tier: "bronze", vip: true}], meta: {capped: true}, price: 0.5, total: "high", vip: false}, cap: -2, eligible: -12.1, quota: false}], + [{cap: 0.5, applicant: {price: 1000, vip: false, lines: [{days: 18, active: false, vip: false, tier: "gold"}]}}, {applicant: {exposure: "-0.5", lines: [{active: false, adjusted: "-0.5", days: 18, decision: -0, scores: {risk: null}, segment: {n: false}, tier: "gold", vip: false}], meta: {capped: true}, price: 1000, total: "high", vip: false}, cap: 0.5, eligible: -27.5, quota: false}], + [{cap: 0.5, applicant: {price: 18, vip: false, balance: 1, lines: [{days: 10, active: false, vip: true, tier: "gold"}, {days: 0.000001, active: false, vip: false, tier: "silver"}, {days: -0.5, active: true, vip: true, tier: "bronze"}]}}, {applicant: {balance: 1, lines: [{active: false, adjusted: "high", days: 10, decision: -1, scores: {risk: 1}, segment: {n: true}, tier: "gold", vip: true}, {active: false, adjusted: "high", days: 0.000001, decision: -1, scores: {risk: 1}, segment: {n: false}, tier: "silver", vip: false}, {active: true, adjusted: "high", days: -0.5, decision: -1, scores: {risk: 1}, segment: {n: true}, tier: "bronze", vip: true}], meta: {capped: true}, price: 18, total: "high", vip: false}, cap: 0.5, eligible: -12.666667, quota: false}], + [{cap: 1, applicant: {price: 2.50, vip: false, balance: 99999999999999999999, lines: [{days: 10, active: true, vip: false, tier: "silver"}, {days: 0.25, active: true, vip: true, tier: "silver"}, {days: -0.01, active: false, vip: true, tier: "silver"}, {days: 123456789.123, active: true, vip: true, tier: "gold"}, {days: 3, active: false, vip: false, tier: "bronze"}]}}, {applicant: {balance: 99999999999999999999, lines: [{active: true, adjusted: "high", days: 10, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: false}, surcharge: "high", tier: "silver", vip: false}, {active: true, adjusted: "high", days: 0.25, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: true}, surcharge: "high", tier: "silver", vip: true}, {active: false, adjusted: "high", days: -0.01, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: true}, surcharge: "high", tier: "silver", vip: true}, {active: true, adjusted: "high", days: 123456789.123, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: true}, surcharge: "high", tier: "gold", vip: true}, {active: false, adjusted: "high", days: 3, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: false}, surcharge: "high", tier: "bronze", vip: false}], meta: {capped: true}, price: 2.50, total: "high", vip: false}, cap: 1, eligible: -24691369.47260, quota: false}], + [{cap: 0, applicant: {price: 250, vip: false, balance: 99999999999999999999, lines: [{days: 0.5, active: false, vip: true, tier: "bronze"}, {days: -0, active: true, vip: false, tier: "silver"}, {days: 1, active: true, vip: false, tier: "bronze"}, {days: 100, active: false, vip: true, tier: "gold"}, {days: 1000, active: true, vip: false, tier: "bronze"}]}}, {applicant: {balance: 99999999999999999999, lines: [{active: false, adjusted: "high", days: 0.5, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: true}, surcharge: "high", tier: "bronze", vip: true}, {active: true, adjusted: "high", days: 0, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: false}, surcharge: "high", tier: "silver", vip: false}, {active: true, adjusted: "high", days: 1, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: false}, surcharge: "high", tier: "bronze", vip: false}, {active: false, adjusted: "high", days: 100, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: true}, surcharge: "high", tier: "gold", vip: true}, {active: true, adjusted: "high", days: 1000, decision: -99999999999999999999, scores: {risk: 99999999999999999999}, segment: {n: false}, surcharge: "high", tier: "bronze", vip: false}], meta: {capped: true}, price: 250, total: "high", vip: false}, cap: 0, eligible: -230.3, quota: false}], + [{cap: 1, applicant: {price: 1.5, balance: 0.000001}}, "!error: ExpressionFailed"], + [{cap: 0.5, applicant: {price: 1, vip: true, balance: 99.99, lines: [{days: 2.50, active: false, vip: false, tier: "silver"}, {days: 0, active: false, vip: true, tier: "bronze"}]}}, {applicant: {balance: 99.99, lines: [{active: false, adjusted: "high", days: 2.50, decision: -99.99, scores: {risk: 99.99}, segment: {n: false}, surcharge: "high", tier: "silver", vip: false}, {active: false, adjusted: "high", days: 0, decision: -99.99, scores: {risk: 99.99}, segment: {n: true}, surcharge: "high", tier: "bronze", vip: true}], meta: {capped: true}, price: 1, total: "high", vip: true}, cap: 0.5, eligible: -10.75, quota: false}], + [{cap: 0.5, applicant: {price: 0, vip: false, balance: "12", lines: [{days: 1e3, active: true, vip: true, tier: "gold"}]}}, "!error: InputValidationFailed"], + [{cap: 1, applicant: {price: 10, vip: true, balance: 7.25, lines: [{days: 1.5, active: false, vip: false, tier: "gold"}, {days: 65, active: false, vip: false, tier: "gold"}, {days: 0.000001, active: true, vip: false, tier: "silver"}, {days: 1000000, active: true, vip: true, tier: "bronze"}, {days: 5, active: false, vip: false, tier: "bronze"}]}}, {applicant: {balance: 7.25, lines: [{active: false, adjusted: "high", days: 1.5, decision: -7.25, scores: {risk: 7.25}, segment: {n: false}, surcharge: "high", tier: "gold", vip: false}, {active: false, adjusted: "high", days: 65, decision: -7.25, scores: {risk: 7.25}, segment: {n: false}, surcharge: "high", tier: "gold", vip: false}, {active: true, adjusted: "A1", days: 0.000001, decision: -7.25, scores: {risk: 7.25}, segment: {n: false}, surcharge: "A1", tier: "silver", vip: false}, {active: true, adjusted: "A1", days: 1000000, decision: -7.25, scores: {risk: 7.25}, segment: {n: true}, surcharge: "A1", tier: "bronze", vip: true}, {active: false, adjusted: "high", days: 5, decision: -7.25, scores: {risk: 7.25}, segment: {n: false}, surcharge: "high", tier: "bronze", vip: false}], meta: {capped: true}, price: 10, total: "high", vip: true}, cap: 1, eligible: -200023.30000020, quota: false}], + [{cap: 100, applicant: {price: -0.5, vip: false, balance: -0.5, lines: null}}, "!error: ExpressionFailed"], + [{cap: 0, applicant: {price: 1.5, vip: false, balance: -1, lines: [{days: 0, active: false, vip: false, tier: "gold"}, {days: -0.01, active: false, vip: true, tier: "gold"}]}}, {applicant: {balance: -1, lines: [{active: false, adjusted: "high", days: 0, decision: 1, scores: {risk: -1}, segment: {n: false}, tier: "gold", vip: false}, {active: false, adjusted: "high", days: -0.01, decision: 1, scores: {risk: -1}, segment: {n: true}, tier: "gold", vip: true}], meta: {capped: true}, price: 1.5, total: "high", vip: false}, cap: 0, eligible: -9.9950, quota: false}], + [{cap: 0.5, applicant: {price: 0.5, vip: false, balance: 2.50, lines: [{days: 1000, active: false, vip: false, tier: "gold"}, {days: 1e3, active: true, vip: true, tier: "gold"}], extraField: 1}}, {applicant: {balance: 2.50, extraField: 1, lines: [{active: false, adjusted: "high", days: 1000, decision: -2.50, scores: {risk: 2.50}, segment: {n: false}, tier: "gold", vip: false}, {active: true, adjusted: "high", days: 1000, decision: -2.50, scores: {risk: 2.50}, segment: {n: true}, tier: "gold", vip: true}], meta: {capped: true}, price: 0.5, total: "high", vip: false}, cap: 0.5, eligible: -1009.5, quota: false}], + [{cap: 0.5, applicant: {price: 104, vip: true, balance: 1000, lines: [{days: 0.25, active: false, vip: false, tier: "silver"}, {days: 2.50, active: false, vip: false, tier: "bronze"}]}}, {applicant: {balance: 1000, lines: [{active: false, adjusted: "high", days: 0.25, decision: -1000, scores: {risk: 1000}, segment: {n: false}, surcharge: "high", tier: "silver", vip: false}, {active: false, adjusted: "high", days: 2.50, decision: -1000, scores: {risk: 1000}, segment: {n: false}, surcharge: "high", tier: "bronze", vip: false}], meta: {capped: true}, price: 104, total: "high", vip: true}, cap: 0.5, eligible: -10.8750, quota: false}], + [{cap: 0.5, applicant: {price: -500, vip: true, balance: 65, lines: [{days: 3, active: true, vip: false, tier: "silver"}]}}, {applicant: {balance: 65, lines: [{active: true, adjusted: "A1", days: 3, decision: -65, scores: {risk: 65}, segment: {n: false}, surcharge: "A1", tier: "silver", vip: false}], meta: {capped: true}, price: -500, total: "high", vip: true}, cap: 0.5, eligible: -12.5, quota: false}], + [{cap: 0.5, applicant: {price: -0.01, vip: false, balance: 1.5, lines: []}}, "!error: ExpressionFailed"], + ], +} + +// seed 340700 (attempt 0) +{ + name: "b 08: claim/parcels/drivers + contact: 2 expression, 4 match, 6 table; 1 root, 7 per-member, 2 top-level computed", + policy: { + models: {claim: {rate: "number", qty: "number", flagged: "boolean", since: "date?", parcels: "parcel[]", contact: "contactInfo"}, parcel: {income: "number?", dueDate: "date", openedAt: "date?", drivers: "driver[]"}, driver: {amount: "number", kind: "string(retail|corporate)"}, contactInfo: {rate: "number?", city: "string", plan: "string(basic|plus|premium|trial)"}}, + blocks: [ + {match: "parcel.health", arms: [["sum(map(parcel.drivers, number(string(#.amount)))) > claim.qty", "claim.contact.city"], ["((claim.since ?? d('2025-01-01')) >= d('2025-03-20') or matches(parcel.totals.grade, '^.{2,}$'))", "(split(parcel.totals.grade, '-')[1] ?? 'none')"], ["(none(parcel.drivers, (#.amount == 2 and #.amount > 250)) and (parcel.openedAt ?? d('2025-01-01')) < d('2024-01-01'))", "((claim.flagged and parcel.totals.ok) ? claim.contact.city : (split((claim.contact.penalty ?? ''), '-')[1] ?? 'none'))"], ["", "`${claim.flagged}/${18}`"]]}, + {table: "t11", inputs: ["(parcel.openedAt ?? d('2025-01-01'))", "(claim.qty + 1.5)", "parcel.income"], outputs: ["parcel.scores.weighted"], rules: [ + ["> d('2025-01-01')", "[5..449]", "0", ""], + ["", ">= 3", "3, 50", "1.5"], + ["> d('2024-01-01')", "", "2", "(parcel.income ?? 0)"], + ["< d('2024-01-01')", "250, 1", "1000", ""], + ["", "", "", ""], + ]}, + {table: "t7", hit: "collect", inputs: ["parcel.totals.ok"], outputs: ["parcel.scores.points", "parcel.scores.discount"], rules: [ + ["true", "(claim.exposure ?? false)", "claim.rate"], + ["", "not (claim.flagged)", ""], + ["", "(claim.exposure ?? false)", "claim.rate"], + ["", "parcel.totals.ok", "max([50, (claim.contact.flags.adjusted ?? 0)])"], + ]}, + {table: "t10", hit: "collect", inputs: ["claim.contact.band", "claim.rate"], outputs: ["share"], rules: [ + ["false", "", "0.25"], + ["true", "0.25", ""], + ["", "", "claim.qty"], + ]}, + {table: "t9", inputs: ["claim.qty", "contactInfo.city"], outputs: ["contactInfo.segment", "contactInfo.band", "contactInfo.review"], rules: [ + ["!= 1.5", "", "", "(claim.exposure ?? false)", ""], + ["> 0.25", "", "some(claim.parcels, (#.income ?? 0) in (11..67])", "(claim.exposure ?? false)", "(contactInfo.rate ?? 0) < (contactInfo.flags.adjusted ?? 0)"], + ["<= 0.25", "$ != 'VIP'", "(claim.exposure ?? false)", "(claim.exposure ?? false)", "((claim.exposure ?? false) and (claim.exposure ?? false))"], + ]}, + {table: "t1", inputs: ["floor((contactInfo.rate ?? 0))"], outputs: ["contactInfo.penalty", "contactInfo.flags.adjusted"], rules: [ + ["!= 1000", "contactInfo.city", "claim.qty"], + ["", "contactInfo.city", "0.25"], + ["250, 0", "contactInfo.city", "0"], + ["", "`${claim.flagged}/${claim.flagged}`", "claim.qty"], + ["> 50", "contactInfo.city", ""], + ["", "contactInfo.city", "claim.rate"], + ]}, + {match: "decision", arms: [["(((claim.contact.segment ?? false) and (claim.exposure ?? false)) and (claim.contact.rate ?? 0) == 3)", "claim.contact.city"], ["", "claim.contact.city"]]}, + {match: "parcel.totals.grade", arms: [["isNumeric(string(claim.rate))", "((parcel.totals.ok ? claim.contact.city : (claim.contact.penalty ?? '')) + '-' + (claim.contact.penalty ?? ''))"], ["", "(claim.contact.penalty ?? '')"]]}, + {match: "parcel.totals.ok", arms: [["not (not (claim.flagged))", "some(parcel.drivers, (#.amount <= 2 or #.amount == 50))"], ["contains(['Oslo', 'A1', ''], (claim.contact.penalty ?? ''))", "claim.flagged"], ["some(parcel.drivers, #.amount <= #.amount)", "(startsWith(claim.contact.city, 'gold') and all(parcel.drivers, #.amount in (-1..149]))"], ["", "claim.flagged"]]}, + {expression: "contactInfo.flags.surcharge", value: "filter(claim.parcels, startsWith(#.totals.grade, 'ok'))"}, + {expression: "parcel.scores.net", value: "`${claim.qty}/${(claim.exposure ?? false)}`"}, + {table: "t6", inputs: ["(claim.qty + 0.5)", "claim.flagged"], outputs: ["claim.exposure"], rules: [ + ["0.25, 18", "false", ""], + ["", "true", ""], + ["<= 0.5", "true", "claim.flagged"], + ["", "", ""], + ]}, + ], + }, + cases: [ + [{claim: {rate: 0.000001, qty: 50, flagged: true, parcels: [{dueDate: "2000-01-01", openedAt: null, drivers: [{amount: 0.5, kind: "retail"}, {amount: 99.99, kind: "corporate"}, {amount: 1e3, kind: "retail"}]}, {income: null, dueDate: "2030-12-31", openedAt: "2030-12-31", drivers: [{amount: 50, kind: "retail"}, {amount: 100, kind: "retail"}]}, {income: 0.25, dueDate: "2030-12-31", drivers: [{amount: 1, kind: "retail"}, {amount: 5, kind: "corporate"}, {amount: 18, kind: "corporate"}]}, {income: null, dueDate: "2030-12-31", openedAt: null, drivers: [{amount: 0.25, kind: "retail"}]}], contact: {city: "日本", plan: "basic"}}}, {claim: {contact: {band: false, city: "日本", flags: {adjusted: 50}, penalty: "日本", plan: "basic", review: true, segment: false}, exposure: null, flagged: true, parcels: [{drivers: [{amount: 0.5, kind: "retail"}, {amount: 99.99, kind: "corporate"}, {amount: 1000, kind: "retail"}], dueDate: "2000-01-01", health: "日本", openedAt: null, scores: {discount: [0.000001, 0.000001, 50], net: "50/false", points: [false, false, false, true], weighted: null}, totals: {grade: "日本-日本", ok: true}}, {drivers: [{amount: 50, kind: "retail"}, {amount: 100, kind: "retail"}], dueDate: "2030-12-31", health: "日本", income: null, openedAt: "2030-12-31", scores: {discount: [0.000001, 0.000001, 50], net: "50/false", points: [false, false, false, true], weighted: null}, totals: {grade: "日本-日本", ok: true}}, {drivers: [{amount: 1, kind: "retail"}, {amount: 5, kind: "corporate"}, {amount: 18, kind: "corporate"}], dueDate: "2030-12-31", health: "日本", income: 0.25, scores: {discount: [0.000001, 0.000001, 50], net: "50/false", points: [false, false, false, true], weighted: null}, totals: {grade: "日本-日本", ok: true}}, {drivers: [{amount: 0.25, kind: "retail"}], dueDate: "2030-12-31", health: "日本", income: null, openedAt: null, scores: {discount: [0.000001, 0.000001, 50], net: "50/false", points: [false, false, false, true], weighted: null}, totals: {grade: "日本-日本", ok: true}}], qty: 50, rate: 0.000001}, decision: "日本", share: [0.25, 50]}], + [{claim: {rate: -0.01, qty: 18, flagged: false, since: "2024-02-29", parcels: [{income: 1000000, dueDate: "1990-06-15", drivers: [{amount: 99999999999999999999, kind: "retail"}]}, {income: 100, dueDate: "2025-03-20", openedAt: "2025-03-20", drivers: []}, {income: 100, dueDate: "1990-06-15", drivers: [{amount: 395, kind: "retail"}, {amount: 2.50, kind: "corporate"}]}], contact: {rate: 50, city: "-", plan: "basic"}}}, {claim: {contact: {band: false, city: "-", flags: {adjusted: 18}, penalty: "-", plan: "basic", rate: 50, review: false, segment: false}, exposure: null, flagged: false, parcels: [{drivers: [{amount: 99999999999999999999, kind: "retail"}], dueDate: "1990-06-15", health: "-", income: 1000000, scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "---", ok: false}}, {drivers: [], dueDate: "2025-03-20", health: "", income: 100, openedAt: "2025-03-20", scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "---", ok: false}}, {drivers: [{amount: 395, kind: "retail"}, {amount: 2.50, kind: "corporate"}], dueDate: "1990-06-15", health: "-", income: 100, scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "---", ok: false}}], qty: 18, rate: -0.01, since: "2024-02-29"}, decision: "-", share: [0.25, 18]}], + [{claim: {rate: 250, qty: 10, flagged: true, since: null, parcels: [{income: 1, dueDate: "2025-03-20T10:15:30Z", openedAt: "2025-03-20", drivers: [{amount: 2, kind: "corporate"}]}, {income: 0.25, dueDate: "2000-01-01", openedAt: "2024-01-01", drivers: [{amount: 292, kind: "retail"}, {amount: 250, kind: "retail"}]}], contact: {rate: null, city: "gold", plan: "plus"}}}, {claim: {contact: {band: false, city: "gold", flags: {adjusted: 10}, penalty: "gold", plan: "plus", rate: null, review: true, segment: false}, exposure: null, flagged: true, parcels: [{drivers: [{amount: 2, kind: "corporate"}], dueDate: "2025-03-20T10:15:30Z", health: "gold", income: 1, openedAt: "2025-03-20", scores: {discount: [250, 250, 50], net: "10/false", points: [false, false, false, true], weighted: null}, totals: {grade: "gold-gold", ok: true}}, {drivers: [{amount: 292, kind: "retail"}, {amount: 250, kind: "retail"}], dueDate: "2000-01-01", health: "gold", income: 0.25, openedAt: "2024-01-01", scores: {discount: [250, 50], net: "10/false", points: [false, false, false], weighted: null}, totals: {grade: "gold-gold", ok: false}}], qty: 10, rate: 250, since: null}, decision: "gold", share: [0.25, 10]}], + [{claim: {rate: 18, qty: 50, flagged: false, parcels: [{income: null, dueDate: "2024-02-29", openedAt: null, drivers: []}], contact: {rate: 250, city: "NL", plan: "basic"}}}, {claim: {contact: {band: false, city: "NL", flags: {adjusted: 50}, penalty: "NL", plan: "basic", rate: 250, review: false, segment: false}, exposure: null, flagged: false, parcels: [{drivers: [], dueDate: "2024-02-29", health: "NL", income: null, openedAt: null, scores: {discount: [18, 50], net: "50/false", points: [true, false, false], weighted: null}, totals: {grade: "NL-NL", ok: false}}], qty: 50, rate: 18}, decision: "NL", share: [0.25, 50]}], + [{claim: {rate: -0, qty: 5, flagged: false, since: "2030-12-31", parcels: [{income: 50, dueDate: "2024-02-29", openedAt: "2025-03-20T10:15:30Z", drivers: [{amount: -1, kind: "corporate"}, {amount: 1, kind: "retail"}]}, {income: 50, dueDate: "1990-06-15", openedAt: "2000-01-01", drivers: []}, {income: 1000, dueDate: "2025-03-20T10:15:30Z", openedAt: "2024-02-29", drivers: [{amount: 100, kind: "retail"}, {amount: 18, kind: "retail"}]}, {income: 1, dueDate: "2030-12-31", openedAt: "2024-02-29", drivers: [{amount: -1, kind: "retail"}, {amount: 18, kind: "retail"}]}], contact: {rate: 100, city: "a", plan: "trial"}}}, {claim: {contact: {band: false, city: "a", flags: {adjusted: 5}, penalty: "a", plan: "trial", rate: 100, review: false, segment: true}, exposure: null, flagged: false, parcels: [{drivers: [{amount: -1, kind: "corporate"}, {amount: 1, kind: "retail"}], dueDate: "2024-02-29", health: "a", income: 50, openedAt: "2025-03-20T10:15:30Z", scores: {discount: [0, 50], net: "5/false", points: [true, false, false], weighted: 1.5}, totals: {grade: "a-a", ok: false}}, {drivers: [], dueDate: "1990-06-15", health: "a", income: 50, openedAt: "2000-01-01", scores: {discount: [0, 50], net: "5/false", points: [true, false, false], weighted: 1.5}, totals: {grade: "a-a", ok: false}}, {drivers: [{amount: 100, kind: "retail"}, {amount: 18, kind: "retail"}], dueDate: "2025-03-20T10:15:30Z", health: "a", income: 1000, openedAt: "2024-02-29", scores: {discount: [0, 50], net: "5/false", points: [true, false, false], weighted: null}, totals: {grade: "a-a", ok: false}}, {drivers: [{amount: -1, kind: "retail"}, {amount: 18, kind: "retail"}], dueDate: "2030-12-31", health: "a", income: 1, openedAt: "2024-02-29", scores: {discount: [0, 50], net: "5/false", points: [true, false, false], weighted: null}, totals: {grade: "a-a", ok: false}}], qty: 5, rate: 0, since: "2030-12-31"}, decision: "a", share: [0.25, 5]}], + [{claim: {rate: -0, qty: 3, flagged: false, since: "2025-03-20", parcels: [{income: null, dueDate: "2025-03-20", drivers: [{amount: 99999999999999999999, kind: "corporate"}, {amount: 5, kind: "retail"}]}, {income: 50, dueDate: "2024-01-01", openedAt: "2024-01-01", drivers: [{amount: 100, kind: "retail"}, {amount: 5, kind: "retail"}]}], contact: {city: "-", plan: "basic"}}}, {claim: {contact: {band: false, city: "-", flags: {adjusted: 3}, penalty: "-", plan: "basic", review: true, segment: true}, exposure: null, flagged: false, parcels: [{drivers: [{amount: 99999999999999999999, kind: "corporate"}, {amount: 5, kind: "retail"}], dueDate: "2025-03-20", health: "-", income: null, scores: {discount: [0, 50], net: "3/false", points: [true, false, false], weighted: null}, totals: {grade: "---", ok: false}}, {drivers: [{amount: 100, kind: "retail"}, {amount: 5, kind: "retail"}], dueDate: "2024-01-01", health: "-", income: 50, openedAt: "2024-01-01", scores: {discount: [0, 50], net: "3/false", points: [true, false, false], weighted: 1.5}, totals: {grade: "---", ok: false}}], qty: 3, rate: 0, since: "2025-03-20"}, decision: "-", share: [0.25, 3]}], + [{claim: {rate: 1, qty: 1, flagged: false, since: null, parcels: [{income: 1.5, dueDate: "2024-02-29", drivers: [{amount: -0.01, kind: "retail"}, {amount: 1000, kind: "corporate"}, {amount: -0.5, kind: "retail"}]}, {income: 18, dueDate: "2025-03-20", openedAt: "2025-03-20", drivers: [{amount: 250, kind: "retail"}]}, {dueDate: "2025-03-20T10:15:30Z", openedAt: "2025-03-20", drivers: [{amount: 3, kind: "retail"}]}, {dueDate: "1990-06-15", openedAt: "2024-01-01", drivers: [{amount: 2.50, kind: "corporate"}, {amount: 50, kind: "retail"}]}], contact: {rate: 250, city: "", plan: "basic"}}}, {claim: {contact: {band: false, city: "", flags: {adjusted: 1}, penalty: "", plan: "basic", rate: 250, review: false, segment: true}, exposure: null, flagged: false, parcels: [{drivers: [{amount: -0.01, kind: "retail"}, {amount: 1000, kind: "corporate"}, {amount: -0.5, kind: "retail"}], dueDate: "2024-02-29", health: "", income: 1.5, scores: {discount: [1, 50], net: "1/false", points: [true, false, false], weighted: null}, totals: {grade: "-", ok: false}}, {drivers: [{amount: 250, kind: "retail"}], dueDate: "2025-03-20", health: "", income: 18, openedAt: "2025-03-20", scores: {discount: [1, 50], net: "1/false", points: [true, false, false], weighted: null}, totals: {grade: "-", ok: false}}, {drivers: [{amount: 3, kind: "retail"}], dueDate: "2025-03-20T10:15:30Z", health: "", openedAt: "2025-03-20", scores: {discount: [1, 50], net: "1/false", points: [true, false, false], weighted: null}, totals: {grade: "-", ok: false}}, {drivers: [{amount: 2.50, kind: "corporate"}, {amount: 50, kind: "retail"}], dueDate: "1990-06-15", health: "", openedAt: "2024-01-01", scores: {discount: [1, 50], net: "1/false", points: [true, false, false], weighted: null}, totals: {grade: "-", ok: false}}], qty: 1, rate: 1, since: null}, decision: "", share: [0.25, 1]}], + [{claim: {rate: 0, qty: 10, flagged: false, since: "1990-06-15", parcels: [{income: 1, dueDate: "2025-03-20", openedAt: "2000-01-01", drivers: [{amount: 3, kind: "corporate"}, {amount: 0.25, kind: "retail"}]}, {income: 1, dueDate: "1990-06-15", openedAt: "1990-06-15", drivers: []}], contact: {rate: 50, city: "Oslo", plan: "premium"}}}, {claim: {contact: {band: false, city: "Oslo", flags: {adjusted: 10}, penalty: "Oslo", plan: "premium", rate: 50, review: false, segment: false}, exposure: null, flagged: false, parcels: [{drivers: [{amount: 3, kind: "corporate"}, {amount: 0.25, kind: "retail"}], dueDate: "2025-03-20", health: "Oslo", income: 1, openedAt: "2000-01-01", scores: {discount: [0, 50], net: "10/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [], dueDate: "1990-06-15", health: "Oslo", income: 1, openedAt: "1990-06-15", scores: {discount: [0, 50], net: "10/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}], qty: 10, rate: 0, since: "1990-06-15"}, decision: "Oslo", share: [0.25, 10]}], + [{claim: {rate: -0.01, qty: 18, flagged: false, parcels: [{income: 50, dueDate: "1990-06-15", openedAt: "2025-03-20T10:15:30Z", drivers: [{amount: 1000, kind: "retail"}, {amount: 3, kind: "corporate"}, {amount: -0, kind: "retail"}]}, {income: 7.25, dueDate: "1990-06-15", openedAt: null, drivers: [{amount: 0.25, kind: "retail"}, {amount: 0, kind: "corporate"}]}, {income: null, dueDate: "1990-06-15", openedAt: null, drivers: [{amount: 5, kind: "retail"}, {amount: 2, kind: "retail"}, {amount: 5, kind: "retail"}]}, {dueDate: "2025-03-20T10:15:30Z", openedAt: "2000-01-01", drivers: [{amount: 50, kind: "corporate"}, {amount: 250, kind: "retail"}]}, {dueDate: "2030-12-31", openedAt: null, drivers: [{amount: 3, kind: "corporate"}]}, {income: 2, dueDate: "2000-01-01", openedAt: "1990-06-15", drivers: [{amount: 3, kind: "corporate"}, {amount: 1e3, kind: "retail"}]}, {dueDate: "2024-01-01", drivers: []}, {dueDate: "1990-06-15", openedAt: null, drivers: [{amount: 50, kind: "retail"}, {amount: 50, kind: "corporate"}, {amount: 0.5, kind: "retail"}]}], contact: {city: "Oslo", plan: "basic"}}}, {claim: {contact: {band: false, city: "Oslo", flags: {adjusted: 18}, penalty: "Oslo", plan: "basic", review: true, segment: true}, exposure: null, flagged: false, parcels: [{drivers: [{amount: 1000, kind: "retail"}, {amount: 3, kind: "corporate"}, {amount: 0, kind: "retail"}], dueDate: "1990-06-15", health: "Oslo", income: 50, openedAt: "2025-03-20T10:15:30Z", scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: 1.5}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [{amount: 0.25, kind: "retail"}, {amount: 0, kind: "corporate"}], dueDate: "1990-06-15", health: "Oslo", income: 7.25, openedAt: null, scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [{amount: 5, kind: "retail"}, {amount: 2, kind: "retail"}, {amount: 5, kind: "retail"}], dueDate: "1990-06-15", health: "Oslo", income: null, openedAt: null, scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [{amount: 50, kind: "corporate"}, {amount: 250, kind: "retail"}], dueDate: "2025-03-20T10:15:30Z", health: "Oslo", openedAt: "2000-01-01", scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [{amount: 3, kind: "corporate"}], dueDate: "2030-12-31", health: "Oslo", openedAt: null, scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [{amount: 3, kind: "corporate"}, {amount: 1000, kind: "retail"}], dueDate: "2000-01-01", health: "Oslo", income: 2, openedAt: "1990-06-15", scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [], dueDate: "2024-01-01", health: "Oslo", scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [{amount: 50, kind: "retail"}, {amount: 50, kind: "corporate"}, {amount: 0.5, kind: "retail"}], dueDate: "1990-06-15", health: "Oslo", openedAt: null, scores: {discount: [-0.01, 50], net: "18/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}], qty: 18, rate: -0.01}, decision: "Oslo", share: [0.25, 18]}], + [{claim: {rate: 0.000001, qty: 1.5, flagged: false, since: "2000-01-01", parcels: [], contact: {rate: 0, city: "-", plan: "basic"}}}, {claim: {contact: {band: false, city: "-", flags: {adjusted: 1.5}, penalty: "-", plan: "basic", rate: 0, review: true, segment: false}, exposure: null, flagged: false, parcels: [], qty: 1.5, rate: 0.000001, since: "2000-01-01"}, decision: "-", share: [0.25, 1.5]}], + [{claim: {rate: 2, qty: 5, flagged: true, since: "2024-01-01", parcels: [{income: -0.5, dueDate: "2024-02-29", openedAt: "2025-03-20", drivers: [{amount: -0.01, kind: "retail"}]}, {income: 50, dueDate: "2024-02-29", openedAt: "2025-03-20T10:15:30Z", drivers: [{amount: 250, kind: "corporate"}]}, {income: 1, dueDate: "2025-03-20", openedAt: "2000-01-01", drivers: [{amount: 0, kind: "retail"}, {amount: 50, kind: "corporate"}, {amount: 2, kind: "retail"}]}, {income: 5, dueDate: "2030-12-31", openedAt: "1990-06-15", drivers: [{amount: 0.5, kind: "corporate"}]}], contact: {rate: 18, city: "Oslo", plan: "plus"}}}, {claim: {contact: {band: false, city: "Oslo", flags: {adjusted: 5}, penalty: "Oslo", plan: "plus", rate: 18, review: false, segment: true}, exposure: null, flagged: true, parcels: [{drivers: [{amount: -0.01, kind: "retail"}], dueDate: "2024-02-29", health: "Oslo", income: -0.5, openedAt: "2025-03-20", scores: {discount: [2, 2, 50], net: "5/false", points: [false, false, false, true], weighted: null}, totals: {grade: "Oslo-Oslo", ok: true}}, {drivers: [{amount: 250, kind: "corporate"}], dueDate: "2024-02-29", health: "Oslo", income: 50, openedAt: "2025-03-20T10:15:30Z", scores: {discount: [2, 50], net: "5/false", points: [false, false, false], weighted: 1.5}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [{amount: 0, kind: "retail"}, {amount: 50, kind: "corporate"}, {amount: 2, kind: "retail"}], dueDate: "2025-03-20", health: "Oslo", income: 1, openedAt: "2000-01-01", scores: {discount: [2, 2, 50], net: "5/false", points: [false, false, false, true], weighted: null}, totals: {grade: "Oslo-Oslo", ok: true}}, {drivers: [{amount: 0.5, kind: "corporate"}], dueDate: "2030-12-31", health: "Oslo", income: 5, openedAt: "1990-06-15", scores: {discount: [2, 2, 50], net: "5/false", points: [false, false, false, true], weighted: null}, totals: {grade: "Oslo-Oslo", ok: true}}], qty: 5, rate: 2, since: "2024-01-01"}, decision: "Oslo", share: [0.25, 5]}], + [{claim: {rate: 0.25, qty: -0.01, flagged: false, since: "2000-01-01", parcels: [{income: 1000, dueDate: "2024-01-01", openedAt: "1990-06-15", drivers: [{amount: 0.000001, kind: "retail"}, {amount: 5, kind: "corporate"}]}, {income: 100, dueDate: "2025-03-20T10:15:30Z", openedAt: "2025-03-20T10:15:30Z", drivers: []}, {income: 1.5, dueDate: "2025-03-20", openedAt: "2024-02-29", drivers: [{amount: 10, kind: "corporate"}, {amount: 1, kind: "retail"}]}], contact: {rate: 18, city: "Oslo", plan: "basic"}, extraField: {nested: true}}}, {claim: {contact: {band: false, city: "Oslo", flags: {adjusted: -0.01}, penalty: "Oslo", plan: "basic", rate: 18, review: false, segment: false}, exposure: null, extraField: {nested: true}, flagged: false, parcels: [{drivers: [{amount: 0.000001, kind: "retail"}, {amount: 5, kind: "corporate"}], dueDate: "2024-01-01", health: "Oslo", income: 1000, openedAt: "1990-06-15", scores: {discount: [0.25, 50], net: "-0.01/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [], dueDate: "2025-03-20T10:15:30Z", health: "Oslo", income: 100, openedAt: "2025-03-20T10:15:30Z", scores: {discount: [0.25, 50], net: "-0.01/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}, {drivers: [{amount: 10, kind: "corporate"}, {amount: 1, kind: "retail"}], dueDate: "2025-03-20", health: "Oslo", income: 1.5, openedAt: "2024-02-29", scores: {discount: [0.25, 50], net: "-0.01/false", points: [true, false, false], weighted: null}, totals: {grade: "Oslo-Oslo", ok: false}}], qty: -0.01, rate: 0.25, since: "2000-01-01"}, decision: "Oslo", share: [0.25, -0.01]}], + [{claim: {rate: 1, qty: 65, flagged: true, parcels: [{income: 1, dueDate: "1990-06-15", drivers: [{amount: 1000, kind: "retail"}, {amount: 1.5, kind: "retail"}]}, {dueDate: "2025-03-20", openedAt: "2000-01-01", drivers: [{amount: 1000, kind: "corporate"}, {amount: 1000, kind: "retail"}, {amount: 1, kind: "retail"}]}], contact: {city: "Oslo", plan: "trial"}}}, {claim: {contact: {band: false, city: "Oslo", flags: {adjusted: 65}, penalty: "Oslo", plan: "trial", review: true, segment: false}, exposure: null, flagged: true, parcels: [{drivers: [{amount: 1000, kind: "retail"}, {amount: 1.5, kind: "retail"}], dueDate: "1990-06-15", health: "Oslo", income: 1, scores: {discount: [1, 1, 65], net: "65/false", points: [false, false, false, true], weighted: null}, totals: {grade: "Oslo-Oslo", ok: true}}, {drivers: [{amount: 1000, kind: "corporate"}, {amount: 1000, kind: "retail"}, {amount: 1, kind: "retail"}], dueDate: "2025-03-20", health: "Oslo", openedAt: "2000-01-01", scores: {discount: [1, 1, 65], net: "65/false", points: [false, false, false, true], weighted: null}, totals: {grade: "Oslo-Oslo", ok: true}}], qty: 65, rate: 1}, decision: "Oslo", share: [0.25, 65]}], + [{claim: {rate: 2, qty: 18, flagged: true, since: "2030-12-31", parcels: [{income: 50, dueDate: "2000-01-01", openedAt: "2030-12-31", drivers: [{amount: 0, kind: "retail"}, {amount: 50, kind: "corporate"}]}, {income: 3, dueDate: "2024-01-01", openedAt: "2025-03-20T10:15:30Z", drivers: [{amount: 0, kind: "retail"}]}, {income: 0.25, dueDate: "2025-03-20T10:15:30Z", openedAt: "2000-01-01", drivers: [{amount: 7.25, kind: "corporate"}, {amount: 50, kind: "retail"}, {amount: 18, kind: "retail"}]}, {income: 0.1, dueDate: "2024-01-01", openedAt: "2025-03-20", drivers: []}], contact: {rate: 100, city: "VIP", plan: "basic"}}}, {claim: {contact: {band: false, city: "VIP", flags: {adjusted: 18}, penalty: "VIP", plan: "basic", rate: 100, review: false, segment: true}, exposure: null, flagged: true, parcels: [{drivers: [{amount: 0, kind: "retail"}, {amount: 50, kind: "corporate"}], dueDate: "2000-01-01", health: "VIP", income: 50, openedAt: "2030-12-31", scores: {discount: [2, 2, 50], net: "18/false", points: [false, false, false, true], weighted: 1.5}, totals: {grade: "VIP-VIP", ok: true}}, {drivers: [{amount: 0, kind: "retail"}], dueDate: "2024-01-01", health: "VIP", income: 3, openedAt: "2025-03-20T10:15:30Z", scores: {discount: [2, 2, 50], net: "18/false", points: [false, false, false, true], weighted: 1.5}, totals: {grade: "VIP-VIP", ok: true}}, {drivers: [{amount: 7.25, kind: "corporate"}, {amount: 50, kind: "retail"}, {amount: 18, kind: "retail"}], dueDate: "2025-03-20T10:15:30Z", health: "VIP", income: 0.25, openedAt: "2000-01-01", scores: {discount: [2, 2, 50], net: "18/false", points: [false, false, false, true], weighted: null}, totals: {grade: "VIP-VIP", ok: true}}, {drivers: [], dueDate: "2024-01-01", health: "VIP", income: 0.1, openedAt: "2025-03-20", scores: {discount: [2, 50], net: "18/false", points: [false, false, false], weighted: null}, totals: {grade: "VIP-VIP", ok: false}}], qty: 18, rate: 2, since: "2030-12-31"}, decision: "VIP", share: [0.25, 18]}], + [{claim: {rate: 50, qty: 0.25, flagged: true, since: "1990-06-15", parcels: [], contact: {rate: 0, city: "abc", plan: "basic"}}}, {claim: {contact: {band: false, city: "abc", flags: {adjusted: 0.25}, penalty: "abc", plan: "basic", rate: 0, review: false, segment: false}, exposure: null, flagged: true, parcels: [], qty: 0.25, rate: 50, since: "1990-06-15"}, decision: "abc", share: [0.25, 0.25]}], + [{claim: {rate: 1, qty: 7.25, flagged: true, since: "2024-02-29", parcels: [{income: null, dueDate: "2024-02-29", openedAt: "2025-03-20T10:15:30Z", drivers: [{amount: 3, kind: "retail"}, {amount: 0.25, kind: "retail"}, {amount: 0.25, kind: "retail"}]}, {income: 0.25, dueDate: "2025-03-20", openedAt: "2024-02-29", drivers: [{amount: 99.99, kind: "retail"}, {amount: 1.5, kind: "retail"}]}, {income: 1e3, dueDate: "2025-03-20T10:15:30Z", openedAt: null, drivers: []}], contact: {rate: 18, city: "VIP", plan: "trial"}}}, {claim: {contact: {band: false, city: "VIP", flags: {adjusted: 7.25}, penalty: "VIP", plan: "trial", rate: 18, review: false, segment: false}, exposure: null, flagged: true, parcels: [{drivers: [{amount: 3, kind: "retail"}, {amount: 0.25, kind: "retail"}, {amount: 0.25, kind: "retail"}], dueDate: "2024-02-29", health: "VIP", income: null, openedAt: "2025-03-20T10:15:30Z", scores: {discount: [1, 1, 50], net: "7.25/false", points: [false, false, false, true], weighted: null}, totals: {grade: "VIP-VIP", ok: true}}, {drivers: [{amount: 99.99, kind: "retail"}, {amount: 1.5, kind: "retail"}], dueDate: "2025-03-20", health: "VIP", income: 0.25, openedAt: "2024-02-29", scores: {discount: [1, 1, 50], net: "7.25/false", points: [false, false, false, true], weighted: null}, totals: {grade: "VIP-VIP", ok: true}}, {drivers: [], dueDate: "2025-03-20T10:15:30Z", health: "VIP", income: 1000, openedAt: null, scores: {discount: [1, 50], net: "7.25/false", points: [false, false, false], weighted: null}, totals: {grade: "VIP-VIP", ok: false}}], qty: 7.25, rate: 1, since: "2024-02-29"}, decision: "VIP", share: [0.25, 7.25]}], + ], +} + +// seed 340800 (attempt 0) +{ + name: "b 09: applicant/accounts/drivers: 4 expression, 3 match, 4 table; 4 root, 12 per-member, 2 top-level computed", + policy: { + models: {applicant: {days: "number", flagged: "boolean?", country: "string", priority: "boolean?", amount: "number", vip: "boolean", accounts: "acct[]"}, acct: {weight: "number", rate: "number", verified: "boolean", drivers: "driver[]"}, driver: {balance: "number", years: "number", amount: "number"}}, + blocks: [ + {expression: "acct.bonus", value: "(10 - applicant.amount)"}, + {match: "acct.decision", arms: [["applicant.amount in [7..123)", "applicant.totals.segment.v"], ["", "(acct.margin ?? '')"]]}, + {table: "t4", inputs: ["applicant.days", "applicant.amount"], outputs: ["acct.scores.fee"], rules: [ + ["> 100", "< 0.25", "applicant.days"], + ["", "1", "len(filter(acct.drivers, #.years >= #.balance))"], + ["> 5", "10, 250", "acct.rate"], + ]}, + {expression: "acct.weighted", value: "map(applicant.accounts, #.rate)"}, + {table: "t8", hit: "collect", inputs: ["bucket", "acct.weight", "applicant.vip"], outputs: ["acct.health", "acct.penalty"], rules: [ + ["", "100", "false", "(avg(map(acct.drivers, round(#.amount / 7, 0))) ?? 0)", ""], + ["true", "", "true", "acct.rate", "applicant.totals.segment.v"], + ["false", ">= 5", "false", "(acct.scores.fee ?? 0)", "(acct.margin ?? '')"], + ["", ">= 0.5", "false", "applicant.totals.segment.ok", "applicant.country"], + ]}, + {match: "bucket", arms: [["not ((applicant.priority ?? false))", "isNumeric(string(applicant.days))"], ["", "(applicant.flagged ?? false)"]]}, + {expression: "applicant.totals.segment", value: "{v: applicant.country, ok: ((applicant.amount) / (abs(applicant.days) + 1) + (applicant.days / 3)), a: applicant.amount}"}, + {table: "t3", inputs: ["applicant.priority"], outputs: ["acct.margin", "acct.flag[]"], rules: [ + ["", "applicant.country", "applicant.country"], + ["true", "applicant.country", "(applicant.country + '-' + applicant.country)"], + ["true", "`${acct.rate}/${(applicant.flagged ?? false)}`", "applicant.country"], + ["", "applicant.country", "applicant.country"], + ["true", "", ""], + ["", "'DE'", "applicant.country"], + ["", "trim(applicant.country)", "applicant.country"], + ]}, + {expression: "acct.scores.tag", value: "(applicant.days <= (acct.scores.fee ?? 0) and isNumeric(applicant.country))"}, + {match: "capped", arms: [["matches(applicant.totals.segment.v, '^.{2,}$')", "matches(applicant.country, 'a')"], ["applicant.priority != null", "bucket"], ["applicant.priority == null", "not (applicant.days in [5..49])"], ["", "applicant.totals.segment.ok <= applicant.totals.segment.ok"]]}, + {table: "t10", inputs: ["acct.verified", "applicant.days", "acct.rate"], outputs: ["acct.summary", "acct.eligible", "acct.exposure"], rules: [ + ["true", ">= 0.5", "<= 1000", "applicant.vip", "'ok'", ""], + ["true", "[1000..1284]", "!= 100", "acct.verified", "(acct.margin ?? '')", "applicant.totals.segment.ok"], + ["", "!= 1.5", "<= 2", "acct.verified", "`${applicant.totals.segment.ok}/${acct.rate}`", "applicant.totals.segment.a"], + ["false", "", "", "(applicant.flagged ?? false)", "(acct.margin ?? '')", "applicant.amount"], + ["false", ">= 5", "<= 1", "", "applicant.country", "acct.rate"], + ["true", "", "0", "some(acct.drivers, not (#.amount == 1000))", "applicant.totals.segment.v", "-((acct.scores.fee ?? 0))"], + ]}, + ], + }, + cases: [ + [{applicant: {days: 123456789.123, flagged: false, country: "NL", amount: 5, vip: false, accounts: [{weight: 0.5, rate: 3, verified: false, drivers: []}, {weight: 100, rate: 250, verified: false, drivers: [{balance: 0.5, years: 100, amount: 1.5}, {balance: 1, years: -0, amount: 5}]}]}}, {applicant: {accounts: [{bonus: 5, decision: "NL", drivers: [], eligible: "NL", exposure: 5, flag: ["NL", "NL", "NL", "NL"], health: [41152263.041000040500000000150], margin: "NL", penalty: ["NL"], rate: 3, summary: false, verified: false, weight: 0.5, weighted: [3, 250]}, {bonus: 5, decision: "NL", drivers: [{amount: 1.5, balance: 0.5, years: 100}, {amount: 5, balance: 1, years: 0}], eligible: "NL", exposure: 5, flag: ["NL", "NL", "NL", "NL"], health: [0.50, 41152263.041000040500000000150], margin: "NL", penalty: ["NL"], rate: 250, summary: false, verified: false, weight: 100, weighted: [3, 250]}], amount: 5, country: "NL", days: 123456789.123, flagged: false, totals: {segment: {a: 5, ok: 41152263.041000040500000000150, v: "NL"}}, vip: false}, bucket: true, capped: false}], + [{applicant: {days: 5, flagged: true, country: "VIP", priority: true, amount: 1000, vip: true, accounts: [{weight: 1.5, rate: 99.99, verified: true, drivers: [{balance: 100, years: 5, amount: 0.5}]}, {weight: 0.1, rate: 0.5, verified: true, drivers: [{balance: 100, years: -0.5, amount: 0}, {balance: -0.01, years: 1000, amount: 2.50}, {balance: 1e3, years: 3, amount: -0.01}]}, {weight: 2, rate: 100, verified: false, drivers: [{balance: 1.5, years: 100, amount: 100}, {balance: 10, years: 2.50, amount: 0.25}]}, {weight: 50, rate: 18, verified: false, drivers: [{balance: 0, years: 420, amount: 100}, {balance: 99.99, years: 10, amount: -500}]}]}}, {applicant: {accounts: [{bonus: -990, decision: "VIP", drivers: [{amount: 0.5, balance: 100, years: 5}], eligible: "ok", exposure: null, flag: ["VIP", "VIP-VIP", "VIP", "VIP", "VIP", "VIP"], health: [99.99], margin: "VIP", penalty: ["VIP"], rate: 99.99, summary: true, verified: true, weight: 1.5, weighted: [99.99, 0.5, 100, 18]}, {bonus: -990, decision: "VIP", drivers: [{amount: 0, balance: 100, years: -0.5}, {amount: 2.50, balance: -0.01, years: 1000}, {amount: -0.01, balance: 1000, years: 3}], eligible: "ok", exposure: 1000, flag: ["VIP", "VIP-VIP", "VIP", "VIP", "VIP", "VIP"], health: [0.5], margin: "VIP", penalty: ["VIP"], rate: 0.5, summary: true, verified: true, weight: 0.1, weighted: [99.99, 0.5, 100, 18]}, {bonus: -990, decision: "VIP", drivers: [{amount: 100, balance: 1.5, years: 100}, {amount: 0.25, balance: 10, years: 2.50}], eligible: "VIP", exposure: 1000, flag: ["VIP", "VIP-VIP", "VIP", "VIP", "VIP", "VIP"], health: [100], margin: "VIP", penalty: ["VIP"], rate: 100, summary: true, verified: false, weight: 2, weighted: [99.99, 0.5, 100, 18]}, {bonus: -990, decision: "VIP", drivers: [{amount: 100, balance: 0, years: 420}, {amount: -500, balance: 99.99, years: 10}], eligible: "VIP", exposure: 1000, flag: ["VIP", "VIP-VIP", "VIP", "VIP", "VIP", "VIP"], health: [18], margin: "VIP", penalty: ["VIP"], rate: 18, summary: true, verified: false, weight: 50, weighted: [99.99, 0.5, 100, 18]}], amount: 1000, country: "VIP", days: 5, flagged: true, priority: true, totals: {segment: {a: 1000, ok: 168.33333333333333333333333334, v: "VIP"}}, vip: true}, bucket: true, capped: false}], + [{applicant: {days: 1000, flagged: false, country: "12", priority: false, amount: [1], vip: false, accounts: [{weight: 5, rate: -0.01, verified: true, drivers: [{balance: 250, years: 0, amount: 1}, {balance: 100, years: 100, amount: 10}, {balance: 1000000, years: 7.25, amount: 100}]}, {weight: 0.000001, rate: 0, verified: true, drivers: [{balance: -0.01, years: 5, amount: 0.000001}, {balance: 10, years: -1, amount: 99.99}]}, {weight: -0.01, rate: 99.99, verified: false, drivers: []}, {weight: 1, rate: 100, verified: true, drivers: [{balance: 0, years: 10, amount: 10}, {balance: 2.50, years: 1, amount: 0}]}, {weight: 10, rate: 65, verified: false, drivers: []}, {weight: 2, rate: 100, verified: true, drivers: [{balance: 0.1, years: 2, amount: 1}]}, {weight: 466, rate: 0, verified: false, drivers: []}, {weight: 1.5, rate: 0.5, verified: true, drivers: [{balance: 0.5, years: 1, amount: 1000}, {balance: 18, years: 0.5, amount: 100}, {balance: 0, years: 2, amount: 3}]}, {weight: 0.5, rate: 250, verified: true, drivers: []}]}}, "!error: InputValidationFailed"], + [{applicant: {days: 5, flagged: true, country: "日本", priority: true, amount: 1000, vip: false, accounts: [{weight: 100, rate: 1.5, verified: false, drivers: []}, {weight: 10, rate: 1e3, verified: true, drivers: []}]}}, "!error: ExpressionFailed"], + [{applicant: {days: 5, flagged: null, country: "12", priority: null, amount: -0.01, vip: true, accounts: [{weight: 99.99, rate: 1.5, verified: false, drivers: [{balance: 10, years: 0, amount: 3}]}, {weight: 1.5, rate: 50, verified: false, drivers: [{balance: 2, years: -0.01, amount: 18}, {balance: 0, years: 100, amount: 1.5}]}]}}, {applicant: {accounts: [{bonus: 10.01, decision: "12", drivers: [{amount: 3, balance: 10, years: 0}], eligible: "1.6650000000000000000000000000/1.5", exposure: -0.01, flag: ["12", "12", "12", "12"], health: [1.5], margin: "12", penalty: ["12"], rate: 1.5, summary: false, verified: false, weight: 99.99, weighted: [1.5, 50]}, {bonus: 10.01, decision: "12", drivers: [{amount: 18, balance: 2, years: -0.01}, {amount: 1.5, balance: 0, years: 100}], eligible: "12", exposure: -0.01, flag: ["12", "12", "12", "12"], health: [50], margin: "12", penalty: ["12"], rate: 50, summary: false, verified: false, weight: 1.5, weighted: [1.5, 50]}], amount: -0.01, country: "12", days: 5, flagged: null, priority: null, totals: {segment: {a: -0.01, ok: 1.6650000000000000000000000000, v: "12"}}, vip: true}, bucket: true, capped: false}], + [{applicant: {days: 3, flagged: null, country: "12", priority: null, amount: 0.1, vip: true, accounts: [{weight: 10, rate: -0, verified: false, drivers: [{balance: 0.5, years: 3, amount: 1.5}, {balance: 99999999999999999999, years: 100, amount: 0.25}]}, {weight: 100, rate: 250, verified: false, drivers: [{balance: 1, years: 1.5, amount: 0.5}, {balance: 0.5, years: 1.5, amount: 5}]}, {weight: 1e3, rate: 163, verified: true, drivers: [{balance: 1, years: 0, amount: 250}, {balance: -1, years: 5, amount: 5}, {balance: 5, years: 0.1, amount: 2.50}]}, {weight: 3, rate: 2, verified: false, drivers: [{balance: 0, years: -500, amount: 2.50}, {balance: 5, years: 100, amount: 0.5}]}, {weight: 5, rate: 0.5, verified: true, drivers: [{balance: 1000, years: 0.25, amount: 100}, {balance: 65, years: 0, amount: 2}, {balance: 100, years: 65, amount: 3}]}]}}, {applicant: {accounts: [{bonus: 9.9, decision: "12", drivers: [{amount: 1.5, balance: 0.5, years: 3}, {amount: 0.25, balance: 99999999999999999999, years: 100}], eligible: "1.025/0", exposure: 0.1, flag: ["12", "12", "12", "12"], health: [0], margin: "12", penalty: ["12"], rate: 0, summary: false, verified: false, weight: 10, weighted: [0, 250, 163, 2, 0.5]}, {bonus: 9.9, decision: "12", drivers: [{amount: 0.5, balance: 1, years: 1.5}, {amount: 5, balance: 0.5, years: 1.5}], eligible: "12", exposure: 0.1, flag: ["12", "12", "12", "12"], health: [250], margin: "12", penalty: ["12"], rate: 250, summary: false, verified: false, weight: 100, weighted: [0, 250, 163, 2, 0.5]}, {bonus: 9.9, decision: "12", drivers: [{amount: 250, balance: 1, years: 0}, {amount: 5, balance: -1, years: 5}, {amount: 2.50, balance: 5, years: 0.1}], eligible: "ok", exposure: null, flag: ["12", "12", "12", "12"], health: [163], margin: "12", penalty: ["12"], rate: 163, summary: true, verified: true, weight: 1000, weighted: [0, 250, 163, 2, 0.5]}, {bonus: 9.9, decision: "12", drivers: [{amount: 2.50, balance: 0, years: -500}, {amount: 0.5, balance: 5, years: 100}], eligible: "1.025/2", exposure: 0.1, flag: ["12", "12", "12", "12"], health: [2], margin: "12", penalty: ["12"], rate: 2, summary: false, verified: false, weight: 3, weighted: [0, 250, 163, 2, 0.5]}, {bonus: 9.9, decision: "12", drivers: [{amount: 100, balance: 1000, years: 0.25}, {amount: 2, balance: 65, years: 0}, {amount: 3, balance: 100, years: 65}], eligible: "ok", exposure: 0.1, flag: ["12", "12", "12", "12"], health: [0.5], margin: "12", penalty: ["12"], rate: 0.5, summary: true, verified: true, weight: 5, weighted: [0, 250, 163, 2, 0.5]}], amount: 0.1, country: "12", days: 3, flagged: null, priority: null, totals: {segment: {a: 0.1, ok: 1.025, v: "12"}}, vip: true}, bucket: true, capped: false}], + [{applicant: {days: 100, flagged: false, country: "3.5", priority: false, amount: 3, vip: true, accounts: [{weight: 1000, rate: 5, verified: true, drivers: [{balance: 0, years: -0, amount: 10}, {balance: 0.5, years: 5, amount: 1000}]}, {weight: 5, rate: -500, verified: true, drivers: []}, {weight: 100, rate: 5, verified: true, drivers: [{balance: 2.50, years: 99.99, amount: 0.5}, {balance: 18, years: 5, amount: 0.5}, {balance: 5, years: 1, amount: 65}]}]}}, {applicant: {accounts: [{bonus: 7, decision: "3.5", drivers: [{amount: 10, balance: 0, years: 0}, {amount: 1000, balance: 0.5, years: 5}], eligible: "ok", exposure: null, flag: ["3.5", "3.5", "3.5", "3.5"], health: [5], margin: "3.5", penalty: ["3.5"], rate: 5, summary: true, verified: true, weight: 1000, weighted: [5, -500, 5]}, {bonus: 7, decision: "3.5", drivers: [], eligible: "ok", exposure: 3, flag: ["3.5", "3.5", "3.5", "3.5"], health: [-500], margin: "3.5", penalty: ["3.5"], rate: -500, summary: true, verified: true, weight: 5, weighted: [5, -500, 5]}, {bonus: 7, decision: "3.5", drivers: [{amount: 0.5, balance: 2.50, years: 99.99}, {amount: 0.5, balance: 18, years: 5}, {amount: 65, balance: 5, years: 1}], eligible: "ok", exposure: null, flag: ["3.5", "3.5", "3.5", "3.5"], health: [5], margin: "3.5", penalty: ["3.5"], rate: 5, summary: true, verified: true, weight: 100, weighted: [5, -500, 5]}], amount: 3, country: "3.5", days: 100, flagged: false, priority: false, totals: {segment: {a: 3, ok: 33.363036303630363036303630363, v: "3.5"}}, vip: true}, bucket: true, capped: false}], + [{applicant: {days: 355, flagged: true, country: "DE", priority: false, amount: 0.1, vip: false, accounts: [{weight: 99.99, rate: 65, verified: false, drivers: [{balance: 100, years: 1000, amount: -0.01}]}, {weight: 100, rate: 0.5, verified: true, drivers: []}]}}, "!error: ExpressionFailed"], + [{applicant: {days: 2, flagged: true, country: "日本", priority: false, amount: 99.99, vip: true, accounts: [{weight: 1000, rate: 0.000001, verified: true, drivers: [{balance: -500, years: 1.5, amount: 100}, {balance: 99.99, years: 5, amount: -0}]}]}}, {applicant: {accounts: [{bonus: -89.99, decision: "日本", drivers: [{amount: 100, balance: -500, years: 1.5}, {amount: 0, balance: 99.99, years: 5}], eligible: "ok", exposure: 99.99, flag: ["日本", "日本", "日本", "日本"], health: [0.000001], margin: "日本", penalty: ["日本"], rate: 0.000001, summary: true, verified: true, weight: 1000, weighted: [0.000001]}], amount: 99.99, country: "日本", days: 2, flagged: true, priority: false, totals: {segment: {a: 99.99, ok: 33.996666666666666666666666667, v: "日本"}}, vip: true}, bucket: true, capped: false}], + [{applicant: {days: 50, flagged: true, country: "", priority: true, amount: 1, vip: true, accounts: [{weight: 50, rate: 10, verified: true, drivers: []}, {weight: 100, rate: 250, verified: false, drivers: [{balance: 1000, years: -0.01, amount: 0.1}, {balance: 1000, years: 18, amount: 5}, {balance: -1, years: 7.25, amount: 5}]}]}}, {applicant: {accounts: [{bonus: 9, decision: "", drivers: [], eligible: "ok", exposure: null, flag: ["", "-", "", "", "", ""], health: [10], margin: "", penalty: [""], rate: 10, summary: true, verified: true, weight: 50, weighted: [10, 250]}, {bonus: 9, decision: "", drivers: [{amount: 0.1, balance: 1000, years: -0.01}, {amount: 5, balance: 1000, years: 18}, {amount: 5, balance: -1, years: 7.25}], eligible: "", exposure: 1, flag: ["", "-", "", "", "", ""], health: [250], margin: "", penalty: [""], rate: 250, summary: true, verified: false, weight: 100, weighted: [10, 250]}], amount: 1, country: "", days: 50, flagged: true, priority: true, totals: {segment: {a: 1, ok: 16.686274509803921568627450981, v: ""}}, vip: true}, bucket: true, capped: true}], + [{applicant: {days: 1000000, flagged: false, country: "VIP", priority: false, amount: 250, vip: false, accounts: [{weight: 10, rate: 250, verified: false, drivers: [{balance: 0.5, years: 0, amount: 100}, {balance: 1000000, years: 18, amount: 0.1}, {balance: 1, years: 5, amount: 99999999999999999999}]}, {weight: 2, rate: -500, verified: false, drivers: [{balance: 1, years: 0.5, amount: 1000}, {balance: 5, years: 5, amount: 5}, {balance: 0, years: 1.5, amount: 1.5}]}]}}, {applicant: {accounts: [{bonus: -240, decision: "VIP", drivers: [{amount: 100, balance: 0.5, years: 0}, {amount: 0.1, balance: 1000000, years: 18}, {amount: 99999999999999999999, balance: 1, years: 5}], eligible: "VIP", exposure: 250, flag: ["VIP", "VIP", "VIP", "VIP"], health: [333333.33358333308333358333308], margin: "VIP", penalty: ["VIP"], rate: 250, summary: false, verified: false, weight: 10, weighted: [250, -500]}, {bonus: -240, decision: "VIP", drivers: [{amount: 1000, balance: 1, years: 0.5}, {amount: 5, balance: 5, years: 5}, {amount: 1.5, balance: 0, years: 1.5}], eligible: "333333.33358333308333358333308/-500", exposure: 250, flag: ["VIP", "VIP", "VIP", "VIP"], health: [333333.33358333308333358333308], margin: "VIP", penalty: ["VIP"], rate: -500, summary: false, verified: false, weight: 2, weighted: [250, -500]}], amount: 250, country: "VIP", days: 1000000, flagged: false, priority: false, totals: {segment: {a: 250, ok: 333333.33358333308333358333308, v: "VIP"}}, vip: false}, bucket: true, capped: false}], + [{applicant: {days: 5, flagged: false, country: "Zed", priority: "true", amount: 100, vip: false, accounts: [{weight: 0.5, rate: 0.5, verified: false, drivers: [{balance: 100, years: 99.99, amount: 0.1}, {balance: 0.5, years: 10, amount: 0.5}, {balance: 5, years: 0.5, amount: 5}]}, {weight: 1000000, rate: 5, verified: true, drivers: [{balance: 5, years: 10, amount: 1.5}, {balance: 0.5, years: 100, amount: -500}, {balance: -1, years: -0, amount: 100}]}, {weight: 10, rate: -1, verified: true, drivers: [{balance: 0.5, years: 2.50, amount: 469}]}]}}, "!error: InputValidationFailed"], + [{applicant: {days: -1, flagged: false, country: "NL", priority: true, amount: 1000, vip: true, accounts: [{weight: 10, rate: 100, verified: true, drivers: [{balance: 1000000, years: 0.25, amount: 0.5}, {balance: 0.5, years: 0.5, amount: 0.5}]}]}}, {applicant: {accounts: [{bonus: -990, decision: "NL", drivers: [{amount: 0.5, balance: 1000000, years: 0.25}, {amount: 0.5, balance: 0.5, years: 0.5}], eligible: null, exposure: null, flag: ["NL", "NL-NL", "NL", "NL", "NL", "NL"], health: [], margin: "NL", penalty: [], rate: 100, summary: null, verified: true, weight: 10, weighted: [100]}], amount: 1000, country: "NL", days: -1, flagged: false, priority: true, totals: {segment: {a: 1000, ok: 499.66666666666666666666666667, v: "NL"}}, vip: true}, bucket: false, capped: false}], + [{applicant: {days: -1, flagged: null, country: "a-b-c", priority: false, amount: 100, vip: false, accounts: [{weight: 50, rate: -0.5, verified: true, drivers: [{balance: 5, years: 1000, amount: 1e3}, {balance: 1.5, years: 0.000001, amount: 1.5}]}, {weight: 1000, rate: 0.5, verified: true, drivers: [{balance: 18, years: 100, amount: 402}]}, {weight: -0.01, rate: 100, verified: true, drivers: [{balance: 10, years: 18, amount: 0.5}, {balance: 1000, years: 1000000, amount: 99999999999999999999}, {balance: 1000, years: 5, amount: 10}]}, {weight: 50, rate: 3, verified: false, drivers: [{balance: 1000, years: 99.99, amount: -0.01}, {balance: 5, years: 0.25, amount: 1}, {balance: 0.5, years: 0, amount: 1000}]}, {weight: 1000, rate: 1.5, verified: true, drivers: [{balance: 0.5, years: 0, amount: 100}, {balance: 0.5, years: 1, amount: 1000}]}]}}, {applicant: {accounts: [{bonus: -90, decision: "a-b-c", drivers: [{amount: 1000, balance: 5, years: 1000}, {amount: 1.5, balance: 1.5, years: 0.000001}], eligible: "49.666666666666666666666666667/-0.5", exposure: 100, flag: ["a-b-c", "a-b-c", "a-b-c", "a-b-c"], health: [49.666666666666666666666666667], margin: "a-b-c", penalty: ["a-b-c"], rate: -0.5, summary: true, verified: true, weight: 50, weighted: [-0.5, 0.5, 100, 3, 1.5]}, {bonus: -90, decision: "a-b-c", drivers: [{amount: 402, balance: 18, years: 100}], eligible: "49.666666666666666666666666667/0.5", exposure: 100, flag: ["a-b-c", "a-b-c", "a-b-c", "a-b-c"], health: [49.666666666666666666666666667], margin: "a-b-c", penalty: ["a-b-c"], rate: 0.5, summary: true, verified: true, weight: 1000, weighted: [-0.5, 0.5, 100, 3, 1.5]}, {bonus: -90, decision: "a-b-c", drivers: [{amount: 0.5, balance: 10, years: 18}, {amount: 99999999999999999999, balance: 1000, years: 1000000}, {amount: 10, balance: 1000, years: 5}], eligible: null, exposure: null, flag: ["a-b-c", "a-b-c", "a-b-c", "a-b-c"], health: [], margin: "a-b-c", penalty: [], rate: 100, summary: null, verified: true, weight: -0.01, weighted: [-0.5, 0.5, 100, 3, 1.5]}, {bonus: -90, decision: "a-b-c", drivers: [{amount: -0.01, balance: 1000, years: 99.99}, {amount: 1, balance: 5, years: 0.25}, {amount: 1000, balance: 0.5, years: 0}], eligible: "a-b-c", exposure: 100, flag: ["a-b-c", "a-b-c", "a-b-c", "a-b-c"], health: [49.666666666666666666666666667], margin: "a-b-c", penalty: ["a-b-c"], rate: 3, summary: false, verified: false, weight: 50, weighted: [-0.5, 0.5, 100, 3, 1.5]}, {bonus: -90, decision: "a-b-c", drivers: [{amount: 100, balance: 0.5, years: 0}, {amount: 1000, balance: 0.5, years: 1}], eligible: "49.666666666666666666666666667/1.5", exposure: 100, flag: ["a-b-c", "a-b-c", "a-b-c", "a-b-c"], health: [49.666666666666666666666666667], margin: "a-b-c", penalty: ["a-b-c"], rate: 1.5, summary: true, verified: true, weight: 1000, weighted: [-0.5, 0.5, 100, 3, 1.5]}], amount: 100, country: "a-b-c", days: -1, flagged: null, priority: false, totals: {segment: {a: 100, ok: 49.666666666666666666666666667, v: "a-b-c"}}, vip: false}, bucket: true, capped: true}], + [{applicant: {days: 5, flagged: 1, country: "12", priority: false, amount: 2, vip: false, accounts: [{weight: 5, rate: 99999999999999999999, verified: false, drivers: [{balance: 0.5, years: 7.25, amount: 100}, {balance: 10, years: 1.5, amount: -0}]}, {weight: 0, rate: 1000000, verified: true, drivers: [{balance: 0.5, years: 5, amount: 1.5}, {balance: 1000, years: 0, amount: 250}]}]}}, "!error: InputValidationFailed"], + [{applicant: {days: 0, flagged: true, country: "", priority: false, amount: 3, vip: false, accounts: [{weight: 5, rate: 5, verified: false, drivers: [{balance: 0.25, years: 5, amount: 5}, {balance: 1, years: 10, amount: 1}]}, {weight: 100, rate: 7.25, verified: false, drivers: []}, {weight: 10, rate: 0.1, verified: true, drivers: [{balance: 0.5, years: 100, amount: 10}]}, {weight: 50, rate: 2, verified: true, drivers: [{balance: 1, years: 1.5, amount: 123456789.123}]}]}}, "!error: ExpressionFailed"], + [{applicant: {days: -0, flagged: true, country: "VIP", priority: true, amount: 99999999999999999999, vip: false, accounts: [{weight: 2.50, rate: 5, verified: true, drivers: [{balance: 1, years: 0.5, amount: 1}, {balance: -1, years: 250, amount: 10}, {balance: 1.5, years: 1.5, amount: 1.5}]}, {weight: 0.5, rate: 3, verified: true, drivers: [{balance: 5, years: 5, amount: 250}, {balance: 65, years: 123456789.123, amount: 3}]}]}}, {applicant: {accounts: [{bonus: -99999999999999999989, decision: "VIP", drivers: [{amount: 1, balance: 1, years: 0.5}, {amount: 10, balance: -1, years: 250}, {amount: 1.5, balance: 1.5, years: 1.5}], eligible: null, exposure: null, flag: ["VIP", "VIP-VIP", "VIP", "VIP", "VIP", "VIP"], health: [99999999999999999999], margin: "VIP", penalty: ["VIP"], rate: 5, summary: null, verified: true, weight: 2.50, weighted: [5, 3]}, {bonus: -99999999999999999989, decision: "VIP", drivers: [{amount: 250, balance: 5, years: 5}, {amount: 3, balance: 65, years: 123456789.123}], eligible: null, exposure: null, flag: ["VIP", "VIP-VIP", "VIP", "VIP", "VIP", "VIP"], health: [99999999999999999999], margin: "VIP", penalty: ["VIP"], rate: 3, summary: null, verified: true, weight: 0.5, weighted: [5, 3]}], amount: 99999999999999999999, country: "VIP", days: 0, flagged: true, priority: true, totals: {segment: {a: 99999999999999999999, ok: 99999999999999999999, v: "VIP"}}, vip: false}, bucket: true, capped: false}], + [{applicant: {days: 5, flagged: true, country: "retail", amount: 0, vip: true, accounts: [{weight: 100, rate: 0.25, verified: false, drivers: [{balance: 5, years: 1.5, amount: 5}, {balance: 1, years: 100, amount: 5}]}, {weight: 0.5, rate: 0.5, verified: false, drivers: [{balance: 100, years: 10, amount: 5}, {balance: 1000, years: 1, amount: 10}]}, {weight: 1000000, rate: 2, verified: true, drivers: [{balance: 10, years: 1000000, amount: 100}, {balance: 250, years: 0.5, amount: 1.5}, {balance: 0, years: 1.5, amount: 3}]}, {weight: -0.5, rate: 1000, verified: false, drivers: []}]}}, {applicant: {accounts: [{bonus: 10, decision: "retail", drivers: [{amount: 5, balance: 5, years: 1.5}, {amount: 5, balance: 1, years: 100}], eligible: "1.6666666666666666666666666667/0.25", exposure: 0, flag: ["retail", "retail", "retail", "retail"], health: [0.25], margin: "retail", penalty: ["retail"], rate: 0.25, summary: false, verified: false, weight: 100, weighted: [0.25, 0.5, 2, 1000]}, {bonus: 10, decision: "retail", drivers: [{amount: 5, balance: 100, years: 10}, {amount: 10, balance: 1000, years: 1}], eligible: "1.6666666666666666666666666667/0.5", exposure: 0, flag: ["retail", "retail", "retail", "retail"], health: [0.5], margin: "retail", penalty: ["retail"], rate: 0.5, summary: false, verified: false, weight: 0.5, weighted: [0.25, 0.5, 2, 1000]}, {bonus: 10, decision: "retail", drivers: [{amount: 100, balance: 10, years: 1000000}, {amount: 1.5, balance: 250, years: 0.5}, {amount: 3, balance: 0, years: 1.5}], eligible: "ok", exposure: 0, flag: ["retail", "retail", "retail", "retail"], health: [2], margin: "retail", penalty: ["retail"], rate: 2, summary: true, verified: true, weight: 1000000, weighted: [0.25, 0.5, 2, 1000]}, {bonus: 10, decision: "retail", drivers: [], eligible: "retail", exposure: 0, flag: ["retail", "retail", "retail", "retail"], health: [1000], margin: "retail", penalty: ["retail"], rate: 1000, summary: true, verified: false, weight: -0.5, weighted: [0.25, 0.5, 2, 1000]}], amount: 0, country: "retail", days: 5, flagged: true, totals: {segment: {a: 0, ok: 1.6666666666666666666666666667, v: "retail"}}, vip: true}, bucket: true, capped: true}], + [{applicant: {days: 1e3, flagged: null, country: " pad ", priority: null, amount: 2.50, vip: true, accounts: [{weight: 0, rate: 0.5, verified: true, drivers: []}, {weight: 100, rate: 100, verified: false, drivers: [{balance: 0, years: 5, amount: 5}, {balance: 100, years: 10, amount: 250}]}, {weight: 1, rate: 10, verified: true, drivers: [{balance: 2, years: 10, amount: 100}, {balance: 1, years: 1.5, amount: 1e3}, {balance: 2, years: 3, amount: 5}]}, {weight: 100, rate: 5, verified: false, drivers: [{balance: 123456789.123, years: 2, amount: 250}, {balance: 434, years: 1.5, amount: 1000}]}, {weight: 1, rate: 1, verified: true, drivers: [{balance: 1000, years: 0.5, amount: -0}, {balance: 2.50, years: 10, amount: 5}]}]}}, {applicant: {accounts: [{bonus: 7.50, decision: " pad ", drivers: [], eligible: "ok", exposure: 333.33583083583083583083583083, flag: [" pad ", " pad ", " pad ", " pad "], health: [0.5], margin: " pad ", penalty: [" pad "], rate: 0.5, summary: true, verified: true, weight: 0, weighted: [0.5, 100, 10, 5, 1]}, {bonus: 7.50, decision: " pad ", drivers: [{amount: 5, balance: 0, years: 5}, {amount: 250, balance: 100, years: 10}], eligible: " pad ", exposure: 2.50, flag: [" pad ", " pad ", " pad ", " pad "], health: [100], margin: " pad ", penalty: [" pad "], rate: 100, summary: false, verified: false, weight: 100, weighted: [0.5, 100, 10, 5, 1]}, {bonus: 7.50, decision: " pad ", drivers: [{amount: 100, balance: 2, years: 10}, {amount: 1000, balance: 1, years: 1.5}, {amount: 5, balance: 2, years: 3}], eligible: "ok", exposure: 333.33583083583083583083583083, flag: [" pad ", " pad ", " pad ", " pad "], health: [10], margin: " pad ", penalty: [" pad "], rate: 10, summary: true, verified: true, weight: 1, weighted: [0.5, 100, 10, 5, 1]}, {bonus: 7.50, decision: " pad ", drivers: [{amount: 250, balance: 123456789.123, years: 2}, {amount: 1000, balance: 434, years: 1.5}], eligible: " pad ", exposure: 2.50, flag: [" pad ", " pad ", " pad ", " pad "], health: [5], margin: " pad ", penalty: [" pad "], rate: 5, summary: false, verified: false, weight: 100, weighted: [0.5, 100, 10, 5, 1]}, {bonus: 7.50, decision: " pad ", drivers: [{amount: 0, balance: 1000, years: 0.5}, {amount: 5, balance: 2.50, years: 10}], eligible: "ok", exposure: 333.33583083583083583083583083, flag: [" pad ", " pad ", " pad ", " pad "], health: [1], margin: " pad ", penalty: [" pad "], rate: 1, summary: true, verified: true, weight: 1, weighted: [0.5, 100, 10, 5, 1]}], amount: 2.50, country: " pad ", days: 1000, flagged: null, priority: null, totals: {segment: {a: 2.50, ok: 333.33583083583083583083583083, v: " pad "}}, vip: true}, bucket: true, capped: true}], + [{applicant: {days: -1, flagged: false, country: "é ü", priority: true, amount: 0, vip: true, accounts: [{weight: 0.5, rate: 65, verified: false, drivers: [{balance: 2, years: 1, amount: 474}, {balance: 10, years: 10, amount: 0.5}, {balance: 1, years: 2, amount: 5}]}, {weight: 0.000001, rate: 99.99, verified: true, drivers: [{balance: 0.5, years: 5, amount: 1000000}, {balance: 1000, years: -0, amount: 1}]}, {weight: 1000000, rate: 1.5, verified: false, drivers: [{balance: 10, years: 5, amount: 1000}, {balance: 123456789.123, years: 0.5, amount: 0.5}]}, {weight: 2, rate: 2, verified: false, drivers: [{balance: 0.5, years: 99.99, amount: -0.01}, {balance: 1.5, years: 5, amount: 1}]}, {weight: 26, rate: 0.5, verified: true, drivers: [{balance: 0.5, years: 1000, amount: 1}]}, {weight: 50, rate: 99.99, verified: true, drivers: [{balance: 0.5, years: 10, amount: 250}, {balance: 3, years: 99.99, amount: 99.99}]}, {weight: 10, rate: 99999999999999999999, verified: true, drivers: [{balance: 5, years: 276, amount: 1}]}, {weight: 1000, rate: 7.25, verified: false, drivers: [{balance: 99.99, years: 100, amount: 5}, {balance: 100, years: 1000, amount: 2.50}]}, {weight: 0.5, rate: 1.5, verified: false, drivers: [{balance: 2, years: 0.5, amount: 10}, {balance: 3, years: 123456789.123, amount: 5}, {balance: 5, years: 1000, amount: 100}]}, {weight: 0, rate: 1, verified: true, drivers: [{balance: -1, years: 5, amount: 100}, {balance: 18, years: 5, amount: 0.25}, {balance: 10, years: 10, amount: 0.5}]}]}}, {applicant: {accounts: [{bonus: 10, decision: "é ü", drivers: [{amount: 474, balance: 2, years: 1}, {amount: 0.5, balance: 10, years: 10}, {amount: 5, balance: 1, years: 2}], eligible: "é ü", exposure: 0, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 65, summary: false, verified: false, weight: 0.5, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: 1000000, balance: 0.5, years: 5}, {amount: 1, balance: 1000, years: 0}], eligible: null, exposure: null, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 99.99, summary: null, verified: true, weight: 0.000001, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: 1000, balance: 10, years: 5}, {amount: 0.5, balance: 123456789.123, years: 0.5}], eligible: "-0.3333333333333333333333333333/1.5", exposure: 0, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 1.5, summary: false, verified: false, weight: 1000000, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: -0.01, balance: 0.5, years: 99.99}, {amount: 1, balance: 1.5, years: 5}], eligible: "-0.3333333333333333333333333333/2", exposure: 0, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 2, summary: false, verified: false, weight: 2, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: 1, balance: 0.5, years: 1000}], eligible: "-0.3333333333333333333333333333/0.5", exposure: 0, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 0.5, summary: true, verified: true, weight: 26, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: 250, balance: 0.5, years: 10}, {amount: 99.99, balance: 3, years: 99.99}], eligible: null, exposure: null, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 99.99, summary: null, verified: true, weight: 50, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: 1, balance: 5, years: 276}], eligible: null, exposure: null, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 99999999999999999999, summary: null, verified: true, weight: 10, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: 5, balance: 99.99, years: 100}, {amount: 2.50, balance: 100, years: 1000}], eligible: "é ü", exposure: 0, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 7.25, summary: false, verified: false, weight: 1000, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: 10, balance: 2, years: 0.5}, {amount: 5, balance: 3, years: 123456789.123}, {amount: 100, balance: 5, years: 1000}], eligible: "-0.3333333333333333333333333333/1.5", exposure: 0, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 1.5, summary: false, verified: false, weight: 0.5, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}, {bonus: 10, decision: "é ü", drivers: [{amount: 100, balance: -1, years: 5}, {amount: 0.25, balance: 18, years: 5}, {amount: 0.5, balance: 10, years: 10}], eligible: "-0.3333333333333333333333333333/1", exposure: 0, flag: ["é ü", "é ü-é ü", "é ü", "é ü", "é ü", "é ü"], health: [], margin: "é ü", penalty: [], rate: 1, summary: true, verified: true, weight: 0, weighted: [65, 99.99, 1.5, 2, 0.5, 99.99, 99999999999999999999, 7.25, 1.5, 1]}], amount: 0, country: "é ü", days: -1, flagged: false, priority: true, totals: {segment: {a: 0, ok: -0.3333333333333333333333333333, v: "é ü"}}, vip: true}, bucket: false, capped: false}], + [{applicant: {days: 1000, country: "VIP", amount: 1.5, vip: false, accounts: []}}, {applicant: {accounts: [], amount: 1.5, country: "VIP", days: 1000, totals: {segment: {a: 1.5, ok: 333.33483183483183483183483183, v: "VIP"}}, vip: false}, bucket: true, capped: false}], + [{applicant: {days: 0.5, flagged: true, country: "DE", priority: false, amount: 10, vip: false, accounts: [{weight: 1000, rate: 5, verified: true, drivers: [{balance: -0.01, years: 1, amount: 1000}]}, {weight: 1.5, rate: 100, verified: false, drivers: [{balance: 100, years: 1e3, amount: 1000}]}, {weight: 100, rate: 0.5, verified: true, drivers: [{balance: 1.5, years: 1000, amount: 1.5}, {balance: 250, years: 99.99, amount: 100}]}], extraField: {nested: true}}}, {applicant: {accounts: [{bonus: 0, decision: "DE", drivers: [{amount: 1000, balance: -0.01, years: 1}], eligible: "ok", exposure: null, flag: ["DE", "DE", "DE", "DE"], health: [6.8333333333333333333333333334], margin: "DE", penalty: ["DE"], rate: 5, summary: false, verified: true, weight: 1000, weighted: [5, 100, 0.5]}, {bonus: 0, decision: "DE", drivers: [{amount: 1000, balance: 100, years: 1000}], eligible: "DE", exposure: 10, flag: ["DE", "DE", "DE", "DE"], health: [6.8333333333333333333333333334], margin: "DE", penalty: ["DE"], rate: 100, summary: true, verified: false, weight: 1.5, weighted: [5, 100, 0.5]}, {bonus: 0, decision: "DE", drivers: [{amount: 1.5, balance: 1.5, years: 1000}, {amount: 100, balance: 250, years: 99.99}], eligible: "ok", exposure: 10, flag: ["DE", "DE", "DE", "DE"], health: [7, 6.8333333333333333333333333334], margin: "DE", penalty: ["DE"], rate: 0.5, summary: false, verified: true, weight: 100, weighted: [5, 100, 0.5]}], amount: 10, country: "DE", days: 0.5, extraField: {nested: true}, flagged: true, priority: false, totals: {segment: {a: 10, ok: 6.8333333333333333333333333334, v: "DE"}}, vip: false}, bucket: true, capped: false}], + [{applicant: {days: 1, flagged: false, country: "NL", priority: false, amount: 100, vip: false, accounts: [{weight: -1, rate: 100, verified: false, drivers: [{balance: 10, years: 1000, amount: 100}, {balance: 0, years: 1, amount: 100}]}, {weight: 0.5, rate: 7.25, verified: false, drivers: []}, {weight: 1000, rate: 123456789.123, verified: false, drivers: [{balance: 1, years: 1, amount: 5}, {balance: 0.5, years: 7.25, amount: 2}]}, {weight: 1000, rate: 5, verified: true, drivers: []}], extraField: 1}}, {applicant: {accounts: [{bonus: -90, decision: "NL", drivers: [{amount: 100, balance: 10, years: 1000}, {amount: 100, balance: 0, years: 1}], eligible: "NL", exposure: 100, flag: ["NL", "NL", "NL", "NL"], health: [], margin: "NL", penalty: [], rate: 100, summary: false, verified: false, weight: -1, weighted: [100, 7.25, 123456789.123, 5]}, {bonus: -90, decision: "NL", drivers: [], eligible: "NL", exposure: 100, flag: ["NL", "NL", "NL", "NL"], health: [50.333333333333333333333333333], margin: "NL", penalty: ["NL"], rate: 7.25, summary: false, verified: false, weight: 0.5, weighted: [100, 7.25, 123456789.123, 5]}, {bonus: -90, decision: "NL", drivers: [{amount: 5, balance: 1, years: 1}, {amount: 2, balance: 0.5, years: 7.25}], eligible: "NL", exposure: 100, flag: ["NL", "NL", "NL", "NL"], health: [50.333333333333333333333333333], margin: "NL", penalty: ["NL"], rate: 123456789.123, summary: false, verified: false, weight: 1000, weighted: [100, 7.25, 123456789.123, 5]}, {bonus: -90, decision: "NL", drivers: [], eligible: "ok", exposure: null, flag: ["NL", "NL", "NL", "NL"], health: [50.333333333333333333333333333], margin: "NL", penalty: ["NL"], rate: 5, summary: false, verified: true, weight: 1000, weighted: [100, 7.25, 123456789.123, 5]}], amount: 100, country: "NL", days: 1, extraField: 1, flagged: false, priority: false, totals: {segment: {a: 100, ok: 50.333333333333333333333333333, v: "NL"}}, vip: false}, bucket: true, capped: false}], + [{applicant: {days: 5, flagged: false, country: "VIP", priority: true, amount: 1000000, vip: true, accounts: []}}, {applicant: {accounts: [], amount: 1000000, country: "VIP", days: 5, flagged: false, priority: true, totals: {segment: {a: 1000000, ok: 166668.33333333333333333333334, v: "VIP"}}, vip: true}, bucket: false, capped: false}], + ], +} + +// seed 340900 (attempt 0) +{ + name: "b 10: borrower/companies: 3 expression, 2 match, 2 table; 2 root, 5 per-member, 1 top-level computed", + policy: { + models: {borrower: {balance: "number", city: "string", country: "string", companies: "company[]"}, company: {income: "number", vip: "boolean", weight: "number"}}, + blocks: [ + {table: "t1", inputs: ["company.vip"], outputs: ["company.flags.net", "company.health"], rules: [ + ["true", "company.vip", "company.vip"], + ["", "company.vip", "company.vip"], + ["false", "company.vip", ""], + ["false", "company.vip", "company.vip"], + ["true", "company.vip", "company.vip"], + ["true", "company.vip", "company.vip"], + ["", "company.vip", "company.vip"], + ]}, + {match: "company.decision", arms: [["trunc(borrower.balance) >= borrower.balance", "string(borrower.balance)"], ["", "`${company.income}/${company.vip}`"]]}, + {match: "weighted", arms: [["borrower.balance in [7..152]", "`${borrower.balance == 250}/${len(borrower.country)}`"], ["(borrower.balance * borrower.balance) == 1.5", "borrower.city"], ["none(borrower.companies, #.weight > 1.5)", "(borrower.balance == 1000 ? borrower.country : borrower.city)"], ["", "borrower.city"]]}, + {expression: "company.exposure", value: "(company.income < company.weight ? company.flags.net : null)"}, + {table: "t5", inputs: ["borrower.city", "weighted"], outputs: ["borrower.review[]"], rules: [ + ["startsWith($, 'retail')", "'retail'", "(borrower.balance > 18 ? 250 : borrower.balance)"], + ["", "", "borrower.balance"], + ]}, + {expression: "company.tag", value: "`${company.decision}/${company.vip}`"}, + {expression: "borrower.scores.surcharge", value: "floor((max(borrower.review) ?? 0)) >= 1000"}, + ], + }, + cases: [ + [{borrower: {balance: 1.5, city: " pad ", country: "DE", companies: [{income: -500, vip: true, weight: 18}, {income: 0.1, vip: false, weight: 65}, {income: 1000, vip: false, weight: -0.5}, {income: 1e3, vip: false, weight: 1000}, {income: 1000000, vip: true, weight: 1.5}], extraField: {nested: true}}}, {borrower: {balance: 1.5, city: " pad ", companies: [{decision: "-500/true", exposure: true, flags: {net: true}, health: true, income: -500, tag: "-500/true/true", vip: true, weight: 18}, {decision: "0.1/false", exposure: false, flags: {net: false}, health: false, income: 0.1, tag: "0.1/false/false", vip: false, weight: 65}, {decision: "1000/false", exposure: null, flags: {net: false}, health: false, income: 1000, tag: "1000/false/false", vip: false, weight: -0.5}, {decision: "1000/false", exposure: null, flags: {net: false}, health: false, income: 1000, tag: "1000/false/false", vip: false, weight: 1000}, {decision: "1000000/true", exposure: null, flags: {net: true}, health: true, income: 1000000, tag: "1000000/true/true", vip: true, weight: 1.5}], country: "DE", extraField: {nested: true}, review: [1.5], scores: {surcharge: false}}, weighted: " pad "}], + [{borrower: {balance: 1, city: "retail", country: "retail", companies: [{income: 250, vip: false, weight: 100}, {income: -0.5, vip: false, weight: 1e3}, {income: 1000, vip: true, weight: 0.000001}, {income: 5, vip: true, weight: 0.5}]}}, {borrower: {balance: 1, city: "retail", companies: [{decision: "1", exposure: null, flags: {net: false}, health: false, income: 250, tag: "1/false", vip: false, weight: 100}, {decision: "1", exposure: false, flags: {net: false}, health: false, income: -0.5, tag: "1/false", vip: false, weight: 1000}, {decision: "1", exposure: null, flags: {net: true}, health: true, income: 1000, tag: "1/true", vip: true, weight: 0.000001}, {decision: "1", exposure: null, flags: {net: true}, health: true, income: 5, tag: "1/true", vip: true, weight: 0.5}], country: "retail", review: [1, 1], scores: {surcharge: false}}, weighted: "retail"}], + [{borrower: {balance: -0.01, city: "", country: "x", companies: []}}, {borrower: {balance: -0.01, city: "", companies: [], country: "x", review: [-0.01], scores: {surcharge: false}}, weighted: ""}], + [{borrower: {balance: 18, city: "retail", country: null, companies: [{income: 5, vip: false, weight: 1.5}]}}, "!error: MissingRequiredInputs"], + [{borrower: {balance: -0, city: "O'Neil", country: "VIP", companies: []}}, {borrower: {balance: 0, city: "O'Neil", companies: [], country: "VIP", review: [0], scores: {surcharge: false}}, weighted: "O'Neil"}], + [{borrower: {balance: 0.5, city: "é ü", country: "3.5", companies: [{income: 1000, vip: true, weight: 1.5}, {income: 123456789.123, vip: true, weight: 1.5}]}}, {borrower: {balance: 0.5, city: "é ü", companies: [{decision: "1000/true", exposure: null, flags: {net: true}, health: true, income: 1000, tag: "1000/true/true", vip: true, weight: 1.5}, {decision: "123456789.123/true", exposure: null, flags: {net: true}, health: true, income: 123456789.123, tag: "123456789.123/true/true", vip: true, weight: 1.5}], country: "3.5", review: [0.5], scores: {surcharge: false}}, weighted: "é ü"}], + [{borrower: {balance: 123456789.123, city: "x", country: "VIP", companies: [{income: 1.5, vip: false, weight: 65}, {income: 99999999999999999999, vip: false, weight: 18}, {income: -1, vip: true, weight: 5}, {income: 65, vip: true, weight: 1000}]}}, {borrower: {balance: 123456789.123, city: "x", companies: [{decision: "1.5/false", exposure: false, flags: {net: false}, health: false, income: 1.5, tag: "1.5/false/false", vip: false, weight: 65}, {decision: "99999999999999999999/false", exposure: null, flags: {net: false}, health: false, income: 99999999999999999999, tag: "99999999999999999999/false/false", vip: false, weight: 18}, {decision: "-1/true", exposure: true, flags: {net: true}, health: true, income: -1, tag: "-1/true/true", vip: true, weight: 5}, {decision: "65/true", exposure: true, flags: {net: true}, health: true, income: 65, tag: "65/true/true", vip: true, weight: 1000}], country: "VIP", review: [123456789.123], scores: {surcharge: true}}, weighted: "x"}], + [{borrower: {balance: 1000, city: "low", country: "x-y", companies: [{income: 250, vip: true, weight: 2}, {income: 0.1, vip: false, weight: 99.99}, {income: 1, vip: true, weight: 1000}, {income: 1000, vip: true, weight: 99.99}, {income: 1000, vip: false, weight: 250}, {income: 5, vip: true, weight: 1000}, {income: 18, vip: true, weight: 2}, {income: 65, vip: true, weight: -1}, {income: -0.5, vip: true, weight: 250}, {income: 0.000001, vip: false, weight: 10}, {income: 10, vip: true, weight: 1000}]}}, {borrower: {balance: 1000, city: "low", companies: [{decision: "1000", exposure: null, flags: {net: true}, health: true, income: 250, tag: "1000/true", vip: true, weight: 2}, {decision: "1000", exposure: false, flags: {net: false}, health: false, income: 0.1, tag: "1000/false", vip: false, weight: 99.99}, {decision: "1000", exposure: true, flags: {net: true}, health: true, income: 1, tag: "1000/true", vip: true, weight: 1000}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 1000, tag: "1000/true", vip: true, weight: 99.99}, {decision: "1000", exposure: null, flags: {net: false}, health: false, income: 1000, tag: "1000/false", vip: false, weight: 250}, {decision: "1000", exposure: true, flags: {net: true}, health: true, income: 5, tag: "1000/true", vip: true, weight: 1000}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 18, tag: "1000/true", vip: true, weight: 2}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 65, tag: "1000/true", vip: true, weight: -1}, {decision: "1000", exposure: true, flags: {net: true}, health: true, income: -0.5, tag: "1000/true", vip: true, weight: 250}, {decision: "1000", exposure: false, flags: {net: false}, health: false, income: 0.000001, tag: "1000/false", vip: false, weight: 10}, {decision: "1000", exposure: true, flags: {net: true}, health: true, income: 10, tag: "1000/true", vip: true, weight: 1000}], country: "x-y", review: [1000], scores: {surcharge: true}}, weighted: "low"}], + [{borrower: {balance: 250, city: "3.5", country: "abc", companies: [{income: 123456789.123, vip: true, weight: 0.1}]}}, {borrower: {balance: 250, city: "3.5", companies: [{decision: "250", exposure: null, flags: {net: true}, health: true, income: 123456789.123, tag: "250/true", vip: true, weight: 0.1}], country: "abc", review: [250], scores: {surcharge: false}}, weighted: "3.5"}], + [{borrower: {balance: 18, city: "low", country: "x-y", companies: [{income: 7.25, vip: true, weight: 1e3}, {income: 99.99, vip: false, weight: 18}, {income: 1000, vip: false, weight: -1}]}}, {borrower: {balance: 18, city: "low", companies: [{decision: "18", exposure: true, flags: {net: true}, health: true, income: 7.25, tag: "18/true", vip: true, weight: 1000}, {decision: "18", exposure: null, flags: {net: false}, health: false, income: 99.99, tag: "18/false", vip: false, weight: 18}, {decision: "18", exposure: null, flags: {net: false}, health: false, income: 1000, tag: "18/false", vip: false, weight: -1}], country: "x-y", review: [18], scores: {surcharge: false}}, weighted: "false/3"}], + [{borrower: {balance: -0.5, city: "low", country: "DE", companies: [], extraField: 1}}, {borrower: {balance: -0.5, city: "low", companies: [], country: "DE", extraField: 1, review: [-0.5], scores: {surcharge: false}}, weighted: "low"}], + [{borrower: {balance: -0.01, city: "low", country: "retail", companies: [{income: -0.01, vip: false, weight: 2.50}, {income: 250, vip: true, weight: 10}, {income: 1e3, vip: true, weight: 389}, {income: 5, vip: true, weight: 0.1}]}}, {borrower: {balance: -0.01, city: "low", companies: [{decision: "-0.01", exposure: false, flags: {net: false}, health: false, income: -0.01, tag: "-0.01/false", vip: false, weight: 2.50}, {decision: "-0.01", exposure: null, flags: {net: true}, health: true, income: 250, tag: "-0.01/true", vip: true, weight: 10}, {decision: "-0.01", exposure: null, flags: {net: true}, health: true, income: 1000, tag: "-0.01/true", vip: true, weight: 389}, {decision: "-0.01", exposure: null, flags: {net: true}, health: true, income: 5, tag: "-0.01/true", vip: true, weight: 0.1}], country: "retail", review: [-0.01], scores: {surcharge: false}}, weighted: "low"}], + [{borrower: {balance: 1000, city: "retail", country: "x-y", companies: [{income: 1.5, vip: true, weight: 250}, {income: -500, vip: false, weight: 250}, {income: -0, vip: true, weight: -1}, {income: 99999999999999999999, vip: true, weight: 250}, {income: 1e3, vip: true, weight: 250}, {income: 99.99, vip: true, weight: 2.50}, {income: 2, vip: true, weight: 18}, {income: 250, vip: true, weight: 7.25}, {income: 314, vip: true, weight: -1}, {income: 0.5, vip: true, weight: 123456789.123}]}}, {borrower: {balance: 1000, city: "retail", companies: [{decision: "1000", exposure: true, flags: {net: true}, health: true, income: 1.5, tag: "1000/true", vip: true, weight: 250}, {decision: "1000", exposure: false, flags: {net: false}, health: false, income: -500, tag: "1000/false", vip: false, weight: 250}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 0, tag: "1000/true", vip: true, weight: -1}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 99999999999999999999, tag: "1000/true", vip: true, weight: 250}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 1000, tag: "1000/true", vip: true, weight: 250}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 99.99, tag: "1000/true", vip: true, weight: 2.50}, {decision: "1000", exposure: true, flags: {net: true}, health: true, income: 2, tag: "1000/true", vip: true, weight: 18}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 250, tag: "1000/true", vip: true, weight: 7.25}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 314, tag: "1000/true", vip: true, weight: -1}, {decision: "1000", exposure: true, flags: {net: true}, health: true, income: 0.5, tag: "1000/true", vip: true, weight: 123456789.123}], country: "x-y", review: [250, 1000], scores: {surcharge: true}}, weighted: "retail"}], + [{borrower: {balance: 2, city: "", country: "a-b-c", companies: [{income: 0, vip: true, weight: 0.5}, {income: 1000, vip: true, weight: 250}]}}, {borrower: {balance: 2, city: "", companies: [{decision: "2", exposure: true, flags: {net: true}, health: true, income: 0, tag: "2/true", vip: true, weight: 0.5}, {decision: "2", exposure: null, flags: {net: true}, health: true, income: 1000, tag: "2/true", vip: true, weight: 250}], country: "a-b-c", review: [2], scores: {surcharge: false}}, weighted: ""}], + [{borrower: {balance: 2.50, city: "VIP", country: "abc", companies: [{income: 0.000001, vip: false, weight: 99999999999999999999}, {income: 100, vip: true, weight: 1000}]}}, {borrower: {balance: 2.50, city: "VIP", companies: [{decision: "0.000001/false", exposure: false, flags: {net: false}, health: false, income: 0.000001, tag: "0.000001/false/false", vip: false, weight: 99999999999999999999}, {decision: "100/true", exposure: true, flags: {net: true}, health: true, income: 100, tag: "100/true/true", vip: true, weight: 1000}], country: "abc", review: [2.50], scores: {surcharge: false}}, weighted: "VIP"}], + [{borrower: {balance: 1.5, city: "retail", country: "a-b-c", companies: [{income: 0.1, vip: true, weight: 99999999999999999999}, {income: 1.5, vip: true, weight: 1000}, {income: 1.5, vip: false, weight: 65}, {income: 2.50, vip: false, weight: -1}, {income: -0.5, vip: true, weight: -0.01}, {income: 65, vip: true, weight: 65}, {income: 99.99, vip: true, weight: 250}, {income: 18, vip: true, weight: 65}, {income: 250, vip: false, weight: 1000}, {income: 99999999999999999999, vip: true, weight: 1000000}, {income: 7.25, vip: true, weight: 1000}, {income: -0.5, vip: true, weight: 10}, {income: -1, vip: false, weight: 1000}, {income: 99999999999999999999, vip: true, weight: 100}]}}, {borrower: {balance: 1.5, city: "retail", companies: [{decision: "0.1/true", exposure: true, flags: {net: true}, health: true, income: 0.1, tag: "0.1/true/true", vip: true, weight: 99999999999999999999}, {decision: "1.5/true", exposure: true, flags: {net: true}, health: true, income: 1.5, tag: "1.5/true/true", vip: true, weight: 1000}, {decision: "1.5/false", exposure: false, flags: {net: false}, health: false, income: 1.5, tag: "1.5/false/false", vip: false, weight: 65}, {decision: "2.50/false", exposure: null, flags: {net: false}, health: false, income: 2.50, tag: "2.50/false/false", vip: false, weight: -1}, {decision: "-0.5/true", exposure: true, flags: {net: true}, health: true, income: -0.5, tag: "-0.5/true/true", vip: true, weight: -0.01}, {decision: "65/true", exposure: null, flags: {net: true}, health: true, income: 65, tag: "65/true/true", vip: true, weight: 65}, {decision: "99.99/true", exposure: true, flags: {net: true}, health: true, income: 99.99, tag: "99.99/true/true", vip: true, weight: 250}, {decision: "18/true", exposure: true, flags: {net: true}, health: true, income: 18, tag: "18/true/true", vip: true, weight: 65}, {decision: "250/false", exposure: false, flags: {net: false}, health: false, income: 250, tag: "250/false/false", vip: false, weight: 1000}, {decision: "99999999999999999999/true", exposure: null, flags: {net: true}, health: true, income: 99999999999999999999, tag: "99999999999999999999/true/true", vip: true, weight: 1000000}, {decision: "7.25/true", exposure: true, flags: {net: true}, health: true, income: 7.25, tag: "7.25/true/true", vip: true, weight: 1000}, {decision: "-0.5/true", exposure: true, flags: {net: true}, health: true, income: -0.5, tag: "-0.5/true/true", vip: true, weight: 10}, {decision: "-1/false", exposure: false, flags: {net: false}, health: false, income: -1, tag: "-1/false/false", vip: false, weight: 1000}, {decision: "99999999999999999999/true", exposure: null, flags: {net: true}, health: true, income: 99999999999999999999, tag: "99999999999999999999/true/true", vip: true, weight: 100}], country: "a-b-c", review: [1.5, 1.5], scores: {surcharge: false}}, weighted: "retail"}], + [{borrower: {balance: 99.99, city: "a-b-c", country: "Oslo", companies: [{income: 353, vip: true, weight: 2}, {income: 1.5, vip: true, weight: 0}, {income: 123456789.123, vip: true, weight: 18}, {income: 2, vip: true, weight: 2}, {income: 265, vip: true, weight: 100}]}}, {borrower: {balance: 99.99, city: "a-b-c", companies: [{decision: "353/true", exposure: null, flags: {net: true}, health: true, income: 353, tag: "353/true/true", vip: true, weight: 2}, {decision: "1.5/true", exposure: null, flags: {net: true}, health: true, income: 1.5, tag: "1.5/true/true", vip: true, weight: 0}, {decision: "123456789.123/true", exposure: null, flags: {net: true}, health: true, income: 123456789.123, tag: "123456789.123/true/true", vip: true, weight: 18}, {decision: "2/true", exposure: null, flags: {net: true}, health: true, income: 2, tag: "2/true/true", vip: true, weight: 2}, {decision: "265/true", exposure: null, flags: {net: true}, health: true, income: 265, tag: "265/true/true", vip: true, weight: 100}], country: "Oslo", review: [99.99], scores: {surcharge: false}}, weighted: "false/4"}], + [{borrower: {balance: 250, city: "a-b-c", country: " pad ", companies: [{income: 1000, vip: false, weight: 18}, {income: 100, vip: true, weight: 18}, {income: 10, vip: true, weight: -1}, {income: 100, vip: true, weight: 0.5}, {income: 1e3, vip: true, weight: 250}], extraField: {nested: true}}}, {borrower: {balance: 250, city: "a-b-c", companies: [{decision: "250", exposure: null, flags: {net: false}, health: false, income: 1000, tag: "250/false", vip: false, weight: 18}, {decision: "250", exposure: null, flags: {net: true}, health: true, income: 100, tag: "250/true", vip: true, weight: 18}, {decision: "250", exposure: null, flags: {net: true}, health: true, income: 10, tag: "250/true", vip: true, weight: -1}, {decision: "250", exposure: null, flags: {net: true}, health: true, income: 100, tag: "250/true", vip: true, weight: 0.5}, {decision: "250", exposure: null, flags: {net: true}, health: true, income: 1000, tag: "250/true", vip: true, weight: 250}], country: " pad ", extraField: {nested: true}, review: [250], scores: {surcharge: false}}, weighted: "a-b-c"}], + [{borrower: {balance: 100, city: "retail", country: "", companies: [{income: 18, vip: true, weight: 96}], extraField: 1}}, {borrower: {balance: 100, city: "retail", companies: [{decision: "100", exposure: true, flags: {net: true}, health: true, income: 18, tag: "100/true", vip: true, weight: 96}], country: "", extraField: 1, review: [100], scores: {surcharge: false}}, weighted: "false/0"}], + [{borrower: {balance: 0, city: "retail", country: "abc", companies: [{income: 10, vip: true, weight: 18}, {income: 209, vip: true, weight: 7.25}, {income: 425, vip: true, weight: -0}, {income: -0.01, vip: true, weight: 1.5}, {income: 99999999999999999999, vip: false, weight: 102}, {income: 1.5, vip: true, weight: 0.1}, {income: 250, vip: true, weight: 1e3}, {income: 2.50, vip: false, weight: -0.01}, {income: 1000000, vip: false, weight: 250}, {income: 65, vip: false, weight: 0.000001}, {income: 2, vip: false, weight: 1.5}]}}, {borrower: {balance: 0, city: "retail", companies: [{decision: "0", exposure: true, flags: {net: true}, health: true, income: 10, tag: "0/true", vip: true, weight: 18}, {decision: "0", exposure: null, flags: {net: true}, health: true, income: 209, tag: "0/true", vip: true, weight: 7.25}, {decision: "0", exposure: null, flags: {net: true}, health: true, income: 425, tag: "0/true", vip: true, weight: 0}, {decision: "0", exposure: true, flags: {net: true}, health: true, income: -0.01, tag: "0/true", vip: true, weight: 1.5}, {decision: "0", exposure: null, flags: {net: false}, health: false, income: 99999999999999999999, tag: "0/false", vip: false, weight: 102}, {decision: "0", exposure: null, flags: {net: true}, health: true, income: 1.5, tag: "0/true", vip: true, weight: 0.1}, {decision: "0", exposure: true, flags: {net: true}, health: true, income: 250, tag: "0/true", vip: true, weight: 1000}, {decision: "0", exposure: null, flags: {net: false}, health: false, income: 2.50, tag: "0/false", vip: false, weight: -0.01}, {decision: "0", exposure: null, flags: {net: false}, health: false, income: 1000000, tag: "0/false", vip: false, weight: 250}, {decision: "0", exposure: null, flags: {net: false}, health: false, income: 65, tag: "0/false", vip: false, weight: 0.000001}, {decision: "0", exposure: null, flags: {net: false}, health: false, income: 2, tag: "0/false", vip: false, weight: 1.5}], country: "abc", review: [0, 0], scores: {surcharge: false}}, weighted: "retail"}], + [{borrower: {balance: 18, city: "3.5", country: "abc", companies: [{income: -0, vip: true, weight: 0.5}, {income: 99999999999999999999, vip: true, weight: 1}, {income: 250, vip: false, weight: -500}]}}, {borrower: {balance: 18, city: "3.5", companies: [{decision: "18", exposure: true, flags: {net: true}, health: true, income: 0, tag: "18/true", vip: true, weight: 0.5}, {decision: "18", exposure: null, flags: {net: true}, health: true, income: 99999999999999999999, tag: "18/true", vip: true, weight: 1}, {decision: "18", exposure: null, flags: {net: false}, health: false, income: 250, tag: "18/false", vip: false, weight: -500}], country: "abc", review: [18], scores: {surcharge: false}}, weighted: "false/3"}], + [{borrower: {balance: 1e3, city: "A1", country: "retail", companies: [{income: 0.1, vip: false, weight: 250}, {income: 99.99, vip: false, weight: 65}, {income: 1000000, vip: true, weight: 374}, {income: -500, vip: true, weight: 1.5}]}}, {borrower: {balance: 1000, city: "A1", companies: [{decision: "1000", exposure: false, flags: {net: false}, health: false, income: 0.1, tag: "1000/false", vip: false, weight: 250}, {decision: "1000", exposure: null, flags: {net: false}, health: false, income: 99.99, tag: "1000/false", vip: false, weight: 65}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 1000000, tag: "1000/true", vip: true, weight: 374}, {decision: "1000", exposure: true, flags: {net: true}, health: true, income: -500, tag: "1000/true", vip: true, weight: 1.5}], country: "retail", review: [1000], scores: {surcharge: true}}, weighted: "A1"}], + [{borrower: {balance: 7.25, city: "DE", country: "VIP", companies: [{income: 123456789.123, vip: true, weight: 1}, {income: -0.5, vip: false, weight: -500}]}}, {borrower: {balance: 7.25, city: "DE", companies: [{decision: "123456789.123/true", exposure: null, flags: {net: true}, health: true, income: 123456789.123, tag: "123456789.123/true/true", vip: true, weight: 1}, {decision: "-0.5/false", exposure: null, flags: {net: false}, health: false, income: -0.5, tag: "-0.5/false/false", vip: false, weight: -500}], country: "VIP", review: [7.25], scores: {surcharge: false}}, weighted: "false/3"}], + [{borrower: {balance: 1000, city: "VIP", country: "a", companies: [{income: -0, vip: false, weight: 0.1}, {income: 250, vip: true, weight: 0.000001}, {income: -0.01, vip: false, weight: -0.01}], extraField: {nested: true}}}, {borrower: {balance: 1000, city: "VIP", companies: [{decision: "1000", exposure: false, flags: {net: false}, health: false, income: 0, tag: "1000/false", vip: false, weight: 0.1}, {decision: "1000", exposure: null, flags: {net: true}, health: true, income: 250, tag: "1000/true", vip: true, weight: 0.000001}, {decision: "1000", exposure: null, flags: {net: false}, health: false, income: -0.01, tag: "1000/false", vip: false, weight: -0.01}], country: "a", extraField: {nested: true}, review: [1000], scores: {surcharge: true}}, weighted: "a"}], + [{borrower: {balance: 1, city: "low", country: null, companies: []}}, "!error: MissingRequiredInputs"], + [{borrower: {balance: -0.5, city: "low", country: "NL", companies: [{income: -1, vip: true, weight: 0.5}]}}, {borrower: {balance: -0.5, city: "low", companies: [{decision: "-0.5", exposure: true, flags: {net: true}, health: true, income: -1, tag: "-0.5/true", vip: true, weight: 0.5}], country: "NL", review: [-0.5], scores: {surcharge: false}}, weighted: "low"}], + [{borrower: {balance: 250, city: "12", country: "Oslo", companies: [{income: 5, vip: false, weight: 1000}, {income: 1, vip: false, weight: 1.5}, {income: 7.25, vip: false, weight: -1}, {income: -500, vip: false, weight: 123456789.123}]}}, {borrower: {balance: 250, city: "12", companies: [{decision: "250", exposure: false, flags: {net: false}, health: false, income: 5, tag: "250/false", vip: false, weight: 1000}, {decision: "250", exposure: false, flags: {net: false}, health: false, income: 1, tag: "250/false", vip: false, weight: 1.5}, {decision: "250", exposure: null, flags: {net: false}, health: false, income: 7.25, tag: "250/false", vip: false, weight: -1}, {decision: "250", exposure: false, flags: {net: false}, health: false, income: -500, tag: "250/false", vip: false, weight: 123456789.123}], country: "Oslo", review: [250], scores: {surcharge: false}}, weighted: "12"}], + [{borrower: {balance: -0.01, city: "3.5", country: "a-b-c", companies: [{income: 1000000, vip: true, weight: 1.5}, {income: 1, vip: false, weight: -0.5}]}}, {borrower: {balance: -0.01, city: "3.5", companies: [{decision: "-0.01", exposure: null, flags: {net: true}, health: true, income: 1000000, tag: "-0.01/true", vip: true, weight: 1.5}, {decision: "-0.01", exposure: null, flags: {net: false}, health: false, income: 1, tag: "-0.01/false", vip: false, weight: -0.5}], country: "a-b-c", review: [-0.01], scores: {surcharge: false}}, weighted: "3.5"}], + [{borrower: {balance: 250, city: "abc", country: "abc", companies: [{income: 250, vip: true}, {income: 123456789.123, vip: false, weight: 7.25}, {income: 100, vip: false, weight: 1}, {income: 14, vip: false, weight: 250}]}}, "!error: ExpressionFailed"], + ], +} + +// seed 341000 (attempt 0) +{ + name: "b 11: claim/accounts: 2 assertion, 3 expression, 1 match; 2 root, 6 per-member, 0 top-level computed", + policy: { + models: {claim: {age: "number", active: "boolean", birthDate: "date", dueDate: "date?", accounts: "acct[]?"}, acct: {price: "number?", tier: "string(gold|silver|bronze)", limit: "number", verified: "boolean"}}, + blocks: [ + {expression: "acct.level", value: "{a: -(sum([(acct.price ?? 0), acct.limit, claim.age, (acct.price ?? 0)])), s: (claim.age + -((acct.price ?? 0)))}"}, + {assertion: "acct.surcharge", conditions: [["or", "(acct.limit in [25..106] or none((claim.accounts ?? []), #.limit in [43..90]))", 1], ["and", "acct.tier == 'silver'", 1]]}, + {expression: "acct.scores.margin", value: "((claim.dueDate ?? d('2025-01-01')).isSameOrBefore(d('2025-01-01'), 'year') ? acct.price : null)"}, + {expression: "claim.summary", value: "(claim.dueDate ?? d('2025-01-01'))"}, + {match: "claim.flags.net", arms: [["claim.dueDate != null", "lower((claim.active ? 'Oslo' : 'ok'))"], ["(claim.active and claim.active)", "claim.birthDate.format('%Y')"], ["", "(claim.active ? 'ok' : 'A1')"]]}, + {assertion: "acct.scores.decision", conditions: [["or", "claim.age in (41..192]", 0], ["or", "claim.birthDate.isBefore(d('2025-01-01'), 'day')", 0], "claim.flags.net in ['Oslo', 'gold']"]}, + ], + }, + cases: [ + [{claim: {age: 1e3, active: false, dueDate: "2030-12-31", accounts: [{price: 0, tier: "gold", limit: 1000000, verified: true}, {price: 65, tier: "silver", limit: 2, verified: true}]}}, "!error: MissingRequiredInputs"], + [{claim: {age: 99999999999999999999, active: false, birthDate: "1990-06-15", dueDate: "2025-03-20", accounts: [{price: 0.000001, limit: -0.01, verified: true}, {price: 99.99, tier: "silver", limit: 1000000, verified: true}, {price: -0.5, tier: "silver", limit: 65, verified: false}, {price: 1000, tier: "bronze", limit: 250, verified: true}]}}, {claim: {accounts: [{level: {a: -99999999999999999998.990002, s: 99999999999999999998.999999}, limit: -0.01, price: 0.000001, scores: {decision: true, margin: 0.000001}, surcharge: false, verified: true}, {level: {a: -100000000000001000198.98, s: 99999999999999999899.01}, limit: 1000000, price: 99.99, scores: {decision: true, margin: 99.99}, surcharge: true, tier: "silver", verified: true}, {level: {a: -100000000000000000063.0, s: 99999999999999999999.5}, limit: 65, price: -0.5, scores: {decision: true, margin: -0.5}, surcharge: true, tier: "silver", verified: false}, {level: {a: -100000000000000002249, s: 99999999999999998999}, limit: 250, price: 1000, scores: {decision: true, margin: 1000}, surcharge: false, tier: "bronze", verified: true}], active: false, age: 99999999999999999999, birthDate: "1990-06-15", dueDate: "2025-03-20", flags: {net: "ok"}, summary: "2025-03-20"}}], + [{claim: {age: 65, active: true, birthDate: "2024-02-29", dueDate: "1990-06-15", accounts: [{price: 1e3, tier: "gold", limit: 5, verified: true}, {price: 10, tier: "bronze", limit: 123456789.123, verified: false}]}}, {claim: {accounts: [{level: {a: -2070, s: -935}, limit: 5, price: 1000, scores: {decision: true, margin: 1000}, surcharge: true, tier: "gold", verified: true}, {level: {a: -123456874.123, s: 55}, limit: 123456789.123, price: 10, scores: {decision: true, margin: 10}, surcharge: true, tier: "bronze", verified: false}], active: true, age: 65, birthDate: "2024-02-29", dueDate: "1990-06-15", flags: {net: "oslo"}, summary: "1990-06-15"}}], + [{claim: {age: 10, active: false, birthDate: "2030-12-31", dueDate: "2030-12-31", accounts: []}}, {claim: {accounts: [], active: false, age: 10, birthDate: "2030-12-31", dueDate: "2030-12-31", flags: {net: "ok"}, summary: "2030-12-31"}}], + [{claim: {age: 100, active: false, birthDate: "2030-12-31", dueDate: "2030-12-31", accounts: [], extraField: {nested: true}}}, {claim: {accounts: [], active: false, age: 100, birthDate: "2030-12-31", dueDate: "2030-12-31", extraField: {nested: true}, flags: {net: "ok"}, summary: "2030-12-31"}}], + [{claim: {age: -500, active: false, birthDate: "2025-03-20T10:15:30Z", dueDate: "2030-12-31", accounts: [{price: 2, tier: "gold", limit: 250, verified: true}]}}, {claim: {accounts: [{level: {a: 246, s: -502}, limit: 250, price: 2, scores: {decision: false, margin: null}, surcharge: true, tier: "gold", verified: true}], active: false, age: -500, birthDate: "2025-03-20T10:15:30Z", dueDate: "2030-12-31", flags: {net: "ok"}, summary: "2030-12-31"}}], + [{claim: {age: 99.99, active: true, birthDate: "2000-01-01", dueDate: "1990-06-15", accounts: []}}, {claim: {accounts: [], active: true, age: 99.99, birthDate: "2000-01-01", dueDate: "1990-06-15", flags: {net: "oslo"}, summary: "1990-06-15"}}], + [{claim: {age: 2, active: false, birthDate: "1990-06-15", dueDate: "2000-01-01", accounts: [{price: 0.1, tier: "gold", limit: 250, verified: true}, {price: 7.25, tier: "bronze", limit: 1e3, verified: true}, {price: -1, tier: "gold", limit: 250, verified: false}], extraField: {nested: true}}}, {claim: {accounts: [{level: {a: -252.2, s: 1.9}, limit: 250, price: 0.1, scores: {decision: true, margin: 0.1}, surcharge: true, tier: "gold", verified: true}, {level: {a: -1016.50, s: -5.25}, limit: 1000, price: 7.25, scores: {decision: true, margin: 7.25}, surcharge: true, tier: "bronze", verified: true}, {level: {a: -250, s: 3}, limit: 250, price: -1, scores: {decision: true, margin: -1}, surcharge: true, tier: "gold", verified: false}], active: false, age: 2, birthDate: "1990-06-15", dueDate: "2000-01-01", extraField: {nested: true}, flags: {net: "ok"}, summary: "2000-01-01"}}], + [{claim: {age: -1, active: false, birthDate: "2030-12-31", dueDate: "2024-02-29", accounts: []}}, {claim: {accounts: [], active: false, age: -1, birthDate: "2030-12-31", dueDate: "2024-02-29", flags: {net: "ok"}, summary: "2024-02-29"}}], + [{claim: {age: -1, active: false, birthDate: "2025-03-20", dueDate: "2030-12-31", accounts: [{price: 123456789.123, tier: "gold", limit: 99.99, verified: false}]}}, {claim: {accounts: [{level: {a: -246913677.236, s: -123456790.123}, limit: 99.99, price: 123456789.123, scores: {decision: false, margin: null}, surcharge: true, tier: "gold", verified: false}], active: false, age: -1, birthDate: "2025-03-20", dueDate: "2030-12-31", flags: {net: "ok"}, summary: "2030-12-31"}}], + [{claim: {age: 73, active: false, birthDate: "2000-01-01", accounts: []}}, {claim: {accounts: [], active: false, age: 73, birthDate: "2000-01-01", flags: {net: "A1"}, summary: "2025-01-01T00:00:00Z"}}], + [{claim: {age: 1, active: false, birthDate: "2025-03-20", dueDate: null, accounts: [{tier: "bronze", limit: 5, verified: true}]}}, {claim: {accounts: [{level: {a: -6, s: 1}, limit: 5, scores: {decision: false, margin: null}, surcharge: true, tier: "bronze", verified: true}], active: false, age: 1, birthDate: "2025-03-20", dueDate: null, flags: {net: "A1"}, summary: "2025-01-01T00:00:00Z"}}], + [{claim: {age: 0, active: true, birthDate: "2025-03-20", dueDate: "2025-03-20", accounts: [{price: 65, tier: "bronze", limit: 0.5, verified: true}]}}, {claim: {accounts: [{level: {a: -130.5, s: -65}, limit: 0.5, price: 65, scores: {decision: false, margin: 65}, surcharge: true, tier: "bronze", verified: true}], active: true, age: 0, birthDate: "2025-03-20", dueDate: "2025-03-20", flags: {net: "oslo"}, summary: "2025-03-20"}}], + [{claim: {age: 0.000001, active: false, birthDate: "2024-02-29", accounts: [{tier: "gold", limit: -1, verified: false}, {price: null, tier: "gold", limit: 18, verified: true}, {price: 18, tier: "gold", limit: 273, verified: true}, {price: 10, tier: "bronze", limit: -500, verified: false}, {price: null, tier: "gold", limit: 1, verified: true}, {tier: "bronze", limit: -1, verified: false}, {tier: "gold", limit: 99.99, verified: false}, {price: 1000, tier: "gold", limit: -0, verified: true}, {price: 1, tier: "bronze", limit: 18, verified: false}, {price: 18, tier: "silver", limit: 0.1, verified: false}]}}, {claim: {accounts: [{level: {a: 0.999999, s: 0.000001}, limit: -1, scores: {decision: true, margin: null}, surcharge: true, tier: "gold", verified: false}, {level: {a: -18.000001, s: 0.000001}, limit: 18, price: null, scores: {decision: true, margin: null}, surcharge: true, tier: "gold", verified: true}, {level: {a: -309.000001, s: -17.999999}, limit: 273, price: 18, scores: {decision: true, margin: 18}, surcharge: true, tier: "gold", verified: true}, {level: {a: 479.999999, s: -9.999999}, limit: -500, price: 10, scores: {decision: true, margin: 10}, surcharge: true, tier: "bronze", verified: false}, {level: {a: -1.000001, s: 0.000001}, limit: 1, price: null, scores: {decision: true, margin: null}, surcharge: true, tier: "gold", verified: true}, {level: {a: 0.999999, s: 0.000001}, limit: -1, scores: {decision: true, margin: null}, surcharge: true, tier: "bronze", verified: false}, {level: {a: -99.990001, s: 0.000001}, limit: 99.99, scores: {decision: true, margin: null}, surcharge: true, tier: "gold", verified: false}, {level: {a: -2000.000001, s: -999.999999}, limit: 0, price: 1000, scores: {decision: true, margin: 1000}, surcharge: true, tier: "gold", verified: true}, {level: {a: -20.000001, s: -0.999999}, limit: 18, price: 1, scores: {decision: true, margin: 1}, surcharge: true, tier: "bronze", verified: false}, {level: {a: -36.100001, s: -17.999999}, limit: 0.1, price: 18, scores: {decision: true, margin: 18}, surcharge: true, tier: "silver", verified: false}], active: false, age: 0.000001, birthDate: "2024-02-29", flags: {net: "A1"}, summary: "2025-01-01T00:00:00Z"}}], + [{claim: {age: 10, active: false, birthDate: "1990-06-15", dueDate: "2025-03-20T10:15:30Z", accounts: [{tier: "gold", limit: 2.50, verified: false}, {tier: "gold", limit: 1000, verified: true}]}}, {claim: {accounts: [{level: {a: -12.50, s: 10}, limit: 2.50, scores: {decision: true, margin: null}, surcharge: true, tier: "gold", verified: false}, {level: {a: -1010, s: 10}, limit: 1000, scores: {decision: true, margin: null}, surcharge: true, tier: "gold", verified: true}], active: false, age: 10, birthDate: "1990-06-15", dueDate: "2025-03-20T10:15:30Z", flags: {net: "ok"}, summary: "2025-03-20T10:15:30Z"}}], + [{claim: {age: 7.25, active: false, birthDate: "2024-01-01", dueDate: "2000-01-01", accounts: [{price: 250, tier: "bronze", limit: 1000, verified: true}, {price: 10, tier: "silver", limit: 409, verified: false}]}}, {claim: {accounts: [{level: {a: -1507.25, s: -242.75}, limit: 1000, price: 250, scores: {decision: true, margin: 250}, surcharge: true, tier: "bronze", verified: true}, {level: {a: -436.25, s: -2.75}, limit: 409, price: 10, scores: {decision: true, margin: 10}, surcharge: true, tier: "silver", verified: false}], active: false, age: 7.25, birthDate: "2024-01-01", dueDate: "2000-01-01", flags: {net: "ok"}, summary: "2000-01-01"}}], + [{claim: {age: 100, active: true, birthDate: "2030-12-31", dueDate: null, accounts: null}}, {claim: {accounts: null, active: true, age: 100, birthDate: "2030-12-31", dueDate: null, flags: {net: "2030"}, summary: "2025-01-01T00:00:00Z"}}], + [{claim: {age: 2.50, active: true, birthDate: "2025-03-20", dueDate: null, accounts: [{tier: "bronze", limit: 65, verified: true}, {price: -0.01, tier: "gold", limit: 5, verified: true}]}}, {claim: {accounts: [{level: {a: -67.50, s: 2.50}, limit: 65, scores: {decision: false, margin: null}, surcharge: true, tier: "bronze", verified: true}, {level: {a: -7.48, s: 2.51}, limit: 5, price: -0.01, scores: {decision: false, margin: -0.01}, surcharge: false, tier: "gold", verified: true}], active: true, age: 2.50, birthDate: "2025-03-20", dueDate: null, flags: {net: "2025"}, summary: "2025-01-01T00:00:00Z"}}], + [{claim: {age: -500, active: false, birthDate: "2024-01-01", dueDate: "2025-03-20T10:15:30Z", accounts: [{price: 1000000, tier: "gold", limit: 0, verified: false}]}}, {claim: {accounts: [{level: {a: -1999500, s: -1000500}, limit: 0, price: 1000000, scores: {decision: true, margin: 1000000}, surcharge: true, tier: "gold", verified: false}], active: false, age: -500, birthDate: "2024-01-01", dueDate: "2025-03-20T10:15:30Z", flags: {net: "ok"}, summary: "2025-03-20T10:15:30Z"}}], + [{claim: {age: 7.25, active: false, birthDate: "2025-03-20T10:15:30Z", dueDate: "2024-02-29", accounts: [{tier: "bronze", limit: 1000000, verified: false}, {price: 65, tier: "bronze", limit: 250, verified: false}, {price: 7.25, tier: "gold", limit: 0.5, verified: true}, {tier: "silver", limit: 0.5, verified: false}, {price: null, tier: "gold", limit: 1000000, verified: false}]}}, {claim: {accounts: [{level: {a: -1000007.25, s: 7.25}, limit: 1000000, scores: {decision: false, margin: null}, surcharge: true, tier: "bronze", verified: false}, {level: {a: -387.25, s: -57.75}, limit: 250, price: 65, scores: {decision: false, margin: 65}, surcharge: true, tier: "bronze", verified: false}, {level: {a: -22.25, s: 0.00}, limit: 0.5, price: 7.25, scores: {decision: false, margin: 7.25}, surcharge: true, tier: "gold", verified: true}, {level: {a: -7.75, s: 7.25}, limit: 0.5, scores: {decision: false, margin: null}, surcharge: true, tier: "silver", verified: false}, {level: {a: -1000007.25, s: 7.25}, limit: 1000000, price: null, scores: {decision: false, margin: null}, surcharge: true, tier: "gold", verified: false}], active: false, age: 7.25, birthDate: "2025-03-20T10:15:30Z", dueDate: "2024-02-29", flags: {net: "ok"}, summary: "2024-02-29"}}], + [{claim: {age: -0.5, active: true, birthDate: "2025-03-20T10:15:30Z", dueDate: "2030-12-31", accounts: [{price: -0.5, tier: "silver", limit: 99.99, verified: false}]}}, {claim: {accounts: [{level: {a: -98.49, s: 0.0}, limit: 99.99, price: -0.5, scores: {decision: false, margin: null}, surcharge: true, tier: "silver", verified: false}], active: true, age: -0.5, birthDate: "2025-03-20T10:15:30Z", dueDate: "2030-12-31", flags: {net: "oslo"}, summary: "2030-12-31"}}], + ], +} + +// seed 341100 (attempt 0) +{ + name: "b 12: order/accounts: 2 assertion, 4 expression, 3 match; 6 root, 3 per-member, 0 top-level computed", + policy: { + models: {order: {years: "number", active: "boolean?", score: "number", plan: "string(basic|plus|premium|trial)?", amount: "number", accounts: "acct[]"}, acct: {rate: "number", age: "number", city: "string?"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {expression: "acct.level", value: "(((order.active ?? false) or (order.active ?? false)) ? acct.city : null)"}, + {expression: "acct.segment", value: "string(acct.rate)"}, + {match: "order.calc.penalty", arms: [["len(`${1000}/${order.amount}`) > 3", "order.score"], ["(order.plan ?? '') == 'basic'", "len(order.accounts)"], ["matches(string((order.active ?? false)), 'a')", "min([threshold, (order.years * order.years), sum([order.years, threshold, order.years])])"], ["(order.plan ?? '') in ['plus', 'basic']", "round(order.amount / 7, 2)"], ["", "order.amount"]]}, + {assertion: "order.calc.eligible", conditions: [["or", "some(order.accounts, (0.25 == 0.5 or #.rate == 1))", 0], ["and", "none(order.accounts, #.rate <= 0.25)", 1], ["and", "order.years in [35..226]", 0]]}, + {expression: "order.rank", value: "(round(order.years, 2) * count(order.accounts, #.rate < #.rate))"}, + {match: "acct.fee", arms: [["order.score >= order.amount", "`${(order.active ?? false)}/${order.rank}`"], ["", "string(acct.age)"]]}, + {assertion: "order.calc.margin", conditions: [["or", "some(order.accounts, #.rate in [19..101])", 0], ["and", "(order.amount % (abs(threshold) + 1)) > order.rank", 1], ["and", "order.active != null", 1], ["or", "((order.active ?? false) and order.calc.eligible)", 0]]}, + {match: "order.quota", arms: [["order.calc.penalty <= 250", "'gold'"], ["", "'a'"]]}, + {expression: "order.weighted", value: "filter(order.accounts, #.age <= #.rate)"}, + ], + }, + cases: [ + [{threshold: -2, order: {years: 1e3, active: true, score: 18, plan: "basic", amount: 1e3, accounts: [{rate: 0, age: 0.5, city: "日本"}, {rate: 250, age: 99.99, city: "a"}]}}, {order: {accounts: [{age: 0.5, city: "日本", fee: "0.5", level: "日本", rate: 0, segment: "0"}, {age: 99.99, city: "a", fee: "99.99", level: "a", rate: 250, segment: "250"}], active: true, amount: 1000, calc: {penalty: 18}, plan: "basic", quota: "gold", score: 18, weighted: [{age: 99.99, city: "a", fee: "99.99", level: "a", rate: 250, segment: "250"}], years: 1000}, threshold: -2}], + [{threshold: 0, order: {years: 250, active: false, score: 0, plan: "basic", amount: 0.25, accounts: [{rate: 2, age: 0, city: "x"}, {rate: 0.1, age: 99.99, city: "x"}, {rate: 0, age: 99.99, city: "12"}, {rate: 250, age: -0, city: "gold"}]}}, {order: {accounts: [{age: 0, city: "x", fee: "0", level: null, rate: 2, segment: "2"}, {age: 99.99, city: "x", fee: "99.99", level: null, rate: 0.1, segment: "0.1"}, {age: 99.99, city: "12", fee: "99.99", level: null, rate: 0, segment: "0"}, {age: 0, city: "gold", fee: "0", level: null, rate: 250, segment: "250"}], active: false, amount: 0.25, calc: {penalty: 0}, plan: "basic", quota: "gold", score: 0, weighted: [{age: 0, city: "x", fee: "0", level: null, rate: 2, segment: "2"}, {age: 0, city: "gold", fee: "0", level: null, rate: 250, segment: "250"}], years: 250}, threshold: 0}], + [{threshold: 0.5, order: {years: -0.5, active: false, score: 1e3, plan: "plus", amount: 5, accounts: [{rate: 99999999999999999999, age: 100, city: "x"}, {rate: 10, age: -500, city: "retail"}, {rate: 0.000001, age: 250, city: "Oslo"}, {rate: 0, age: 0.25, city: "x"}, {rate: -0.5, age: 1, city: "日本"}]}}, {order: {accounts: [{age: 100, city: "x", fee: "false/0", level: null, rate: 99999999999999999999, segment: "99999999999999999999"}, {age: -500, city: "retail", fee: "false/0", level: null, rate: 10, segment: "10"}, {age: 250, city: "Oslo", fee: "false/0", level: null, rate: 0.000001, segment: "0.000001"}, {age: 0.25, city: "x", fee: "false/0", level: null, rate: 0, segment: "0"}, {age: 1, city: "日本", fee: "false/0", level: null, rate: -0.5, segment: "-0.5"}], active: false, amount: 5, calc: {penalty: 1000}, plan: "plus", quota: "a", rank: 0, score: 1000, weighted: [{age: 100, city: "x", fee: "false/0", level: null, rate: 99999999999999999999, segment: "99999999999999999999"}, {age: -500, city: "retail", fee: "false/0", level: null, rate: 10, segment: "10"}], years: -0.5}, threshold: 0.5}], + [{threshold: 10, order: {years: 99.99, active: true, score: 10, amount: -500, accounts: [{rate: 10, age: 1, city: "x-y"}, {rate: 1, age: -500, city: "3.5"}]}}, {order: {accounts: [{age: 1, city: "x-y", fee: "true/0", level: "x-y", rate: 10, segment: "10"}, {age: -500, city: "3.5", fee: "true/0", level: "3.5", rate: 1, segment: "1"}], active: true, amount: -500, calc: {penalty: 10}, quota: "gold", rank: 0, score: 10, weighted: [{age: 1, city: "x-y", fee: "true/0", level: "x-y", rate: 10, segment: "10"}, {age: -500, city: "3.5", fee: "true/0", level: "3.5", rate: 1, segment: "1"}], years: 99.99}, threshold: 10}], + [{threshold: 10, order: {years: 2.50, active: true, score: 100, plan: "trial", amount: 0.25, accounts: [{rate: 100, age: 0.5, city: "é ü"}]}}, {order: {accounts: [{age: 0.5, city: "é ü", fee: "true/0", level: "é ü", rate: 100, segment: "100"}], active: true, amount: 0.25, calc: {penalty: 100}, plan: "trial", quota: "gold", rank: 0, score: 100, weighted: [{age: 0.5, city: "é ü", fee: "true/0", level: "é ü", rate: 100, segment: "100"}], years: 2.50}, threshold: 10}], + [{threshold: 100, order: {years: -0, score: 100, plan: null, amount: 99999999999999999999, accounts: []}}, {order: {accounts: [], amount: 99999999999999999999, calc: {penalty: 100}, plan: null, quota: "gold", score: 100, weighted: [], years: 0}, threshold: 100}], + [{threshold: 1, order: {years: 1, active: false, score: 1, plan: "plus", amount: 65, accounts: [{rate: 250, age: 1, city: "-"}, {rate: 99.99, age: 2.50, city: " pad "}, {rate: 1e3, age: 449, city: "3.5"}, {rate: 99999999999999999999, age: 0.25, city: "é ü"}, {rate: 0.5, age: 0.5, city: "x-y"}]}}, {order: {accounts: [{age: 1, city: "-", fee: "1", level: null, rate: 250, segment: "250"}, {age: 2.50, city: " pad ", fee: "2.50", level: null, rate: 99.99, segment: "99.99"}, {age: 449, city: "3.5", fee: "449", level: null, rate: 1000, segment: "1000"}, {age: 0.25, city: "é ü", fee: "0.25", level: null, rate: 99999999999999999999, segment: "99999999999999999999"}, {age: 0.5, city: "x-y", fee: "0.5", level: null, rate: 0.5, segment: "0.5"}], active: false, amount: 65, calc: {penalty: 1}, plan: "plus", quota: "gold", score: 1, weighted: [{age: 1, city: "-", fee: "1", level: null, rate: 250, segment: "250"}, {age: 2.50, city: " pad ", fee: "2.50", level: null, rate: 99.99, segment: "99.99"}, {age: 449, city: "3.5", fee: "449", level: null, rate: 1000, segment: "1000"}, {age: 0.25, city: "é ü", fee: "0.25", level: null, rate: 99999999999999999999, segment: "99999999999999999999"}, {age: 0.5, city: "x-y", fee: "0.5", level: null, rate: 0.5, segment: "0.5"}], years: 1}, threshold: 1}], + [{threshold: -2, order: {years: 7.25, active: true, score: 1, plan: "trial", amount: 18, accounts: []}}, {order: {accounts: [], active: true, amount: 18, calc: {penalty: 1}, plan: "trial", quota: "gold", score: 1, weighted: [], years: 7.25}, threshold: -2}], + [{threshold: 0, order: {years: 99.99, active: true, score: 0, plan: "premium", amount: 7.25, accounts: [{rate: 1000000, age: 250, city: "Zed"}, {rate: 1, age: 0.5, city: "a-b-c"}], extraField: 1}}, {order: {accounts: [{age: 250, city: "Zed", fee: "250", level: "Zed", rate: 1000000, segment: "1000000"}, {age: 0.5, city: "a-b-c", fee: "0.5", level: "a-b-c", rate: 1, segment: "1"}], active: true, amount: 7.25, calc: {penalty: 0}, extraField: 1, plan: "premium", quota: "gold", score: 0, weighted: [{age: 250, city: "Zed", fee: "250", level: "Zed", rate: 1000000, segment: "1000000"}, {age: 0.5, city: "a-b-c", fee: "0.5", level: "a-b-c", rate: 1, segment: "1"}], years: 99.99}, threshold: 0}], + [{threshold: 0, order: {years: 10, score: 10, plan: "premium", amount: 1000, accounts: [{rate: 0.1, age: -500}, {rate: 1e3, age: 0}]}}, {order: {accounts: [{age: -500, fee: "-500", level: null, rate: 0.1, segment: "0.1"}, {age: 0, fee: "0", level: null, rate: 1000, segment: "1000"}], amount: 1000, calc: {penalty: 10}, plan: "premium", quota: "gold", score: 10, weighted: [{age: -500, fee: "-500", level: null, rate: 0.1, segment: "0.1"}, {age: 0, fee: "0", level: null, rate: 1000, segment: "1000"}], years: 10}, threshold: 0}], + [{threshold: 0, order: {years: 7.25, active: false, score: 0.25, plan: "premium", amount: 1000, accounts: [{rate: 7.25, age: 250, city: "US"}, {rate: 0.25, age: 1e3, city: "a"}, {rate: 266, age: 65, city: "x-y"}, {rate: 100, age: 2, city: "12"}]}}, {order: {accounts: [{age: 250, city: "US", fee: "250", level: null, rate: 7.25, segment: "7.25"}, {age: 1000, city: "a", fee: "1000", level: null, rate: 0.25, segment: "0.25"}, {age: 65, city: "x-y", fee: "65", level: null, rate: 266, segment: "266"}, {age: 2, city: "12", fee: "2", level: null, rate: 100, segment: "100"}], active: false, amount: 1000, calc: {penalty: 0.25}, plan: "premium", quota: "gold", score: 0.25, weighted: [{age: 65, city: "x-y", fee: "65", level: null, rate: 266, segment: "266"}, {age: 2, city: "12", fee: "2", level: null, rate: 100, segment: "100"}], years: 7.25}, threshold: 0}], + [{threshold: 0, order: {years: 1000000, active: null, score: 1e3, amount: 10, accounts: [{rate: 1000, age: 1000, city: "-"}]}}, {order: {accounts: [{age: 1000, city: "-", fee: "false/0", level: null, rate: 1000, segment: "1000"}], active: null, amount: 10, calc: {penalty: 1000}, quota: "a", rank: 0, score: 1000, weighted: [{age: 1000, city: "-", fee: "false/0", level: null, rate: 1000, segment: "1000"}], years: 1000000}, threshold: 0}], + [{threshold: 10, order: {years: 1000000, active: true, score: 256, plan: "basic", amount: 99999999999999999999, accounts: [{rate: 0.5, age: 1, city: "é ü"}, {rate: -0.01, age: 1000, city: "12"}]}}, {order: {accounts: [{age: 1, city: "é ü", fee: "1", level: "é ü", rate: 0.5, segment: "0.5"}, {age: 1000, city: "12", fee: "1000", level: "12", rate: -0.01, segment: "-0.01"}], active: true, amount: 99999999999999999999, calc: {penalty: 256}, plan: "basic", quota: "a", score: 256, weighted: [], years: 1000000}, threshold: 10}], + [{threshold: 100, order: {years: 250, active: true, score: -500, plan: "premium", amount: 7.25, accounts: [{rate: -0.01, age: null, city: "é ü"}]}}, "!error: ExpressionFailed"], + [{threshold: 0, order: {years: -500, score: 0.1, amount: 1, accounts: [{rate: 1, age: 378, city: "x"}, {rate: 18, age: 18, city: "a"}]}}, {order: {accounts: [{age: 378, city: "x", fee: "378", level: null, rate: 1, segment: "1"}, {age: 18, city: "a", fee: "18", level: null, rate: 18, segment: "18"}], amount: 1, calc: {penalty: 0.1}, quota: "gold", score: 0.1, weighted: [{age: 18, city: "a", fee: "18", level: null, rate: 18, segment: "18"}], years: -500}, threshold: 0}], + [{threshold: 0, order: {years: 0, active: null, score: 250, plan: null, amount: -1, accounts: [{rate: 0, age: 0.5, city: "retail"}]}}, {order: {accounts: [{age: 0.5, city: "retail", fee: "false/0", level: null, rate: 0, segment: "0"}], active: null, amount: -1, calc: {penalty: 250}, plan: null, quota: "gold", rank: 0, score: 250, weighted: [], years: 0}, threshold: 0}], + [{threshold: 0.5, order: {years: -500, active: null, score: 18, plan: "basic", amount: 2.50, accounts: [{rate: -500, age: 18, city: "US"}]}}, {order: {accounts: [{age: 18, city: "US", fee: "false/0", level: null, rate: -500, segment: "-500"}], active: null, amount: 2.50, calc: {penalty: 18}, plan: "basic", quota: "gold", rank: 0, score: 18, weighted: [], years: -500}, threshold: 0.5}], + [{threshold: 100, order: {years: 99999999999999999999, active: true, score: 0.5, plan: null, amount: 99999999999999999999, accounts: [{rate: 1000, age: 0.25, city: "x-y"}]}}, {order: {accounts: [{age: 0.25, city: "x-y", fee: "0.25", level: "x-y", rate: 1000, segment: "1000"}], active: true, amount: 99999999999999999999, calc: {penalty: 0.5}, plan: null, quota: "gold", score: 0.5, weighted: [{age: 0.25, city: "x-y", fee: "0.25", level: "x-y", rate: 1000, segment: "1000"}], years: 99999999999999999999}, threshold: 100}], + [{threshold: 10, order: {years: 1000, active: false, score: -500, plan: "basic", amount: 2, accounts: [{rate: 0, age: 7.25, city: "US"}, {rate: 250, age: 65, city: "a"}, {rate: 65, age: 7.25, city: "retail"}, {rate: 1, age: 99999999999999999999, city: "3.5"}], extraField: 1}}, {order: {accounts: [{age: 7.25, city: "US", fee: "7.25", level: null, rate: 0, segment: "0"}, {age: 65, city: "a", fee: "65", level: null, rate: 250, segment: "250"}, {age: 7.25, city: "retail", fee: "7.25", level: null, rate: 65, segment: "65"}, {age: 99999999999999999999, city: "3.5", fee: "99999999999999999999", level: null, rate: 1, segment: "1"}], active: false, amount: 2, calc: {penalty: -500}, extraField: 1, plan: "basic", quota: "gold", score: -500, weighted: [{age: 65, city: "a", fee: "65", level: null, rate: 250, segment: "250"}, {age: 7.25, city: "retail", fee: "7.25", level: null, rate: 65, segment: "65"}], years: 1000}, threshold: 10}], + [{threshold: 10, order: {years: 18, active: null, score: 123456789.123, plan: "basic", amount: 1, accounts: [{rate: 18, age: 0.5, city: "VIP"}, {rate: 123456789.123, age: 1000000, city: "gold"}, {rate: 0, age: 123456789.123, city: "-"}, {rate: 250, age: -500, city: "3.5"}, {rate: 5, age: 250}]}}, {order: {accounts: [{age: 0.5, city: "VIP", fee: "false/0", level: null, rate: 18, segment: "18"}, {age: 1000000, city: "gold", fee: "false/0", level: null, rate: 123456789.123, segment: "123456789.123"}, {age: 123456789.123, city: "-", fee: "false/0", level: null, rate: 0, segment: "0"}, {age: -500, city: "3.5", fee: "false/0", level: null, rate: 250, segment: "250"}, {age: 250, fee: "false/0", level: null, rate: 5, segment: "5"}], active: null, amount: 1, calc: {penalty: 123456789.123}, plan: "basic", quota: "a", rank: 0, score: 123456789.123, weighted: [{age: 0.5, city: "VIP", fee: "false/0", level: null, rate: 18, segment: "18"}, {age: 1000000, city: "gold", fee: "false/0", level: null, rate: 123456789.123, segment: "123456789.123"}, {age: -500, city: "3.5", fee: "false/0", level: null, rate: 250, segment: "250"}], years: 18}, threshold: 10}], + [{threshold: 0.5, order: {years: 7.25, active: true, score: 0.000001, plan: "basic", amount: 0.5, accounts: [{rate: 0, age: -1, city: 5}, {rate: 0.5, age: 99.99, city: "VIP"}, {rate: 250, age: 99999999999999999999, city: "12"}, {rate: 2.50, age: 382, city: "US"}]}}, "!error: InputValidationFailed"], + [{threshold: 0, order: {years: 0.1, score: 65, amount: 123456789.123, accounts: []}}, {order: {accounts: [], amount: 123456789.123, calc: {penalty: 65}, quota: "gold", score: 65, weighted: [], years: 0.1}, threshold: 0}], + [{threshold: -2, order: {years: -0.5, active: true, score: -1, plan: "basic", amount: 7.25, accounts: [{rate: 1000000, age: -0, city: "é ü"}, {rate: 0.000001, age: 0.5, city: "x"}, {rate: 123456789.123, age: 65, city: "-"}, {rate: -0.5, age: 0.000001, city: "a-b-c"}], extraField: {nested: true}}}, {order: {accounts: [{age: 0, city: "é ü", fee: "0", level: "é ü", rate: 1000000, segment: "1000000"}, {age: 0.5, city: "x", fee: "0.5", level: "x", rate: 0.000001, segment: "0.000001"}, {age: 65, city: "-", fee: "65", level: "-", rate: 123456789.123, segment: "123456789.123"}, {age: 0.000001, city: "a-b-c", fee: "0.000001", level: "a-b-c", rate: -0.5, segment: "-0.5"}], active: true, amount: 7.25, calc: {penalty: -1}, extraField: {nested: true}, plan: "basic", quota: "gold", score: -1, weighted: [{age: 0, city: "é ü", fee: "0", level: "é ü", rate: 1000000, segment: "1000000"}, {age: 65, city: "-", fee: "65", level: "-", rate: 123456789.123, segment: "123456789.123"}], years: -0.5}, threshold: -2}], + [{threshold: 1, order: {years: 0.25, active: null, score: 250, amount: 462, accounts: [{rate: 0.5, age: -0}]}}, {order: {accounts: [{age: 0, fee: "0", level: null, rate: 0.5, segment: "0.5"}], active: null, amount: 462, calc: {penalty: 250}, quota: "gold", score: 250, weighted: [{age: 0, fee: "0", level: null, rate: 0.5, segment: "0.5"}], years: 0.25}, threshold: 1}], + [{threshold: 1, order: {years: 1e3, active: null, score: 100, plan: "basic", amount: 250, accounts: [{rate: -1, age: 1000, city: null}, {rate: 1, age: 0.5, city: "a"}, {rate: 2, age: 0.000001, city: null}, {rate: 1000, age: 2.50, city: "US"}]}}, {order: {accounts: [{age: 1000, city: null, fee: "1000", level: null, rate: -1, segment: "-1"}, {age: 0.5, city: "a", fee: "0.5", level: null, rate: 1, segment: "1"}, {age: 0.000001, city: null, fee: "0.000001", level: null, rate: 2, segment: "2"}, {age: 2.50, city: "US", fee: "2.50", level: null, rate: 1000, segment: "1000"}], active: null, amount: 250, calc: {penalty: 100}, plan: "basic", quota: "gold", score: 100, weighted: [{age: 0.5, city: "a", fee: "0.5", level: null, rate: 1, segment: "1"}, {age: 0.000001, city: null, fee: "0.000001", level: null, rate: 2, segment: "2"}, {age: 2.50, city: "US", fee: "2.50", level: null, rate: 1000, segment: "1000"}], years: 1000}, threshold: 1}], + [{threshold: -2, order: {years: 1000, active: true, score: 1, plan: "plus", amount: 0.000001, accounts: []}}, {order: {accounts: [], active: true, amount: 0.000001, calc: {penalty: 1}, plan: "plus", quota: "gold", score: 1, weighted: [], years: 1000}, threshold: -2}], + [{threshold: 0.5, order: {years: 10, active: false, score: 1, plan: "trial", amount: 2.50, accounts: []}}, {order: {accounts: [], active: false, amount: 2.50, calc: {penalty: 1}, plan: "trial", quota: "gold", score: 1, weighted: [], years: 10}, threshold: 0.5}], + ], +} + +// seed 341200 (attempt 0) +{ + name: "b 13: applicant/companies: 2 assertion, 5 expression, 2 match, 3 table; 6 root, 11 per-member, 3 top-level computed", + policy: { + models: {applicant: {rate: "number?", channel: "string", plan: "string(basic|plus|premium|trial)?", verified: "boolean", dueDate: "date?", companies: "company[]"}, company: {weight: "number", income: "number", insured: "boolean", name: "string"}}, + blocks: [ + {match: "applicant.calc.exposure", arms: [["applicant.plan == null", "((applicant.rate ?? 0) == (applicant.rate ?? 0) ? applicant.channel : (applicant.dueDate ?? d('2025-01-01')).format('%Y'))"], ["", "applicant.channel"]]}, + {expression: "company.weighted", value: "{a: (min([abs(company.ok.s), 1000]) ^ 3), ok: (applicant.dueDate ?? d('2025-01-01')).diff(d('2025-01-01'), 'day'), v: (applicant.grade ?? false)}"}, + {assertion: "company.flag", conditions: [["and", "company.income in [45..114]", 2], ["or", "(applicant.dueDate ?? d('2025-01-01')) >= d('2024-01-01')", 0], ["and", "len(applicant.calc.exposure) > 3", 1]]}, + {expression: "company.ok", value: "{s: (applicant.rank ?? 0)}"}, + {table: "t1", hit: "collect", inputs: ["applicant.plan", "applicant.rate"], outputs: ["flags.net"], rules: [ + ["'basic'", "", "applicant.verified"], + ["'trial'", "", "applicant.verified"], + ["'basic'", "1", ""], + ["'trial'", "1.5", "(applicant.verified or applicant.verified)"], + ["'premium'", "18", "applicant.verified"], + ["'premium'", "3", "applicant.verified"], + ]}, + {expression: "company.summary", value: "{s: 100, a: all(applicant.companies, matches(#.totals.eligible, '^[A-Z]'))}"}, + {assertion: "applicant.calc.points", conditions: [["and", "(applicant.rate ?? 0) in [20..164]", 0], ["or", "startsWith(lower(applicant.channel), 'a')", 0], ["or", "(applicant.dueDate ?? d('2025-01-01')) > d('2025-01-01')", 0], "startsWith(applicant.channel, 'VIP')"]}, + {match: "company.totals.eligible", arms: [["(avg(map(applicant.companies, trunc(#.weight))) ?? 0) <= (applicant.tag ?? 0)", "upper(applicant.channel)"], ["", "(company.name + '-' + applicant.calc.exposure)"]]}, + {expression: "applicant.health", value: "(min([abs((min(map(applicant.companies, #.income)) ?? 0)), 1000]) ^ 2)"}, + {table: "t11", inputs: ["(applicant.tag ?? 0)"], outputs: ["share"], rules: [ + ["!= 10", ""], + ["> 0.25", ""], + ["!= 1", ""], + ["<= 0.25", "fee"], + ["!= 0.25", "(applicant.grade ?? false)"], + ["", "applicant.calc.points"], + ]}, + {expression: "fee", value: "applicant.calc.exposure in ['Oslo', 'high']"}, + {table: "t5", inputs: [null, "applicant.verified", "(applicant.plan ?? '')"], outputs: ["applicant.grade", "applicant.tag", "applicant.rank"], rules: [ + ["not (applicant.verified)", "false", "'premium'", "applicant.verified", "(applicant.rate ?? 0)", "(applicant.rate ?? 0)"], + ["(applicant.rate ?? 0) in [-5..129]", "", "'trial', 'plus'", "applicant.plan != null", "(applicant.rate ?? 0)", "(applicant.rate ?? 0)"], + ["", "", "", "applicant.calc.points", "", ""], + ]}, + ], + }, + cases: [ + [{applicant: {rate: 99999999999999999999, channel: "gold", plan: "basic", verified: false, dueDate: null, companies: [{weight: 50, income: 10, insured: true, name: "x-y"}, {weight: 99.99, income: 5, insured: false, name: "abc"}]}}, {applicant: {calc: {exposure: "gold", points: false}, channel: "gold", companies: [{flag: true, income: 10, insured: true, name: "x-y", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "x-y-gold"}, weight: 50, weighted: {a: 0, ok: 0, v: false}}, {flag: true, income: 5, insured: false, name: "abc", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "abc-gold"}, weight: 99.99, weighted: {a: 0, ok: 0, v: false}}], dueDate: null, grade: false, health: 25, plan: "basic", rank: null, rate: 99999999999999999999, tag: null, verified: false}, fee: false, flags: {net: [false]}, share: false}], + [{applicant: {rate: 100, channel: "DE", plan: "premium", verified: false, dueDate: "2025-03-20T10:15:30Z", companies: [{weight: 0, income: 0.000001, insured: true, name: "x"}, {weight: 1e3, income: -0, insured: true, name: "low"}]}}, {applicant: {calc: {exposure: "DE"}, channel: "DE", companies: [{flag: false, income: 0.000001, insured: true, name: "x", ok: {s: 100}, summary: {a: false, s: 100}, totals: {eligible: "x-DE"}, weight: 0, weighted: {a: 1000000, ok: 78, v: false}}, {flag: false, income: 0, insured: true, name: "low", ok: {s: 100}, summary: {a: false, s: 100}, totals: {eligible: "low-DE"}, weight: 1000, weighted: {a: 1000000, ok: 78, v: false}}], dueDate: "2025-03-20T10:15:30Z", grade: false, health: 0, plan: "premium", rank: 100, rate: 100, tag: 100, verified: false}, flags: {net: []}, share: false}], + [{applicant: {rate: null, channel: "a-b-c", plan: "trial", verified: false, companies: [{weight: 10, income: -0.01, insured: true, name: "gold"}, {weight: 123456789.123, income: 1000, insured: true, name: "a-b-c"}, {weight: 7.25, income: 1, insured: true, name: "high"}, {weight: 99.99, income: 1.5, insured: false, name: "a-b-c"}, {weight: 7.25, income: 0.25, insured: true, name: ""}, {weight: 2, income: 18, insured: true, name: "O'Neil"}, {weight: -0, income: 0.5, insured: false, name: "high"}, {weight: 100, income: 5, insured: false, name: "retail"}, {weight: -0, income: 18, insured: true, name: "ok"}, {weight: 18, income: 18, insured: false, name: "retail"}, {weight: 1, income: 1.5, insured: false, name: "VIP"}, {weight: 99999999999999999999, income: -0, insured: false, name: "A1"}, {weight: 99999999999999999999, income: 123456789.123, insured: false, name: "low"}, {weight: 10, income: 2, insured: true, name: "A1"}]}}, {applicant: {calc: {exposure: "a-b-c"}, channel: "a-b-c", companies: [{flag: true, income: -0.01, insured: true, name: "gold", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "gold-a-b-c"}, weight: 10, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 1000, insured: true, name: "a-b-c", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "a-b-c-a-b-c"}, weight: 123456789.123, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 1, insured: true, name: "high", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "high-a-b-c"}, weight: 7.25, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 1.5, insured: false, name: "a-b-c", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "a-b-c-a-b-c"}, weight: 99.99, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 0.25, insured: true, name: "", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "-a-b-c"}, weight: 7.25, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 18, insured: true, name: "O'Neil", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "O'Neil-a-b-c"}, weight: 2, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 0.5, insured: false, name: "high", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "high-a-b-c"}, weight: 0, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 5, insured: false, name: "retail", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "retail-a-b-c"}, weight: 100, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 18, insured: true, name: "ok", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "ok-a-b-c"}, weight: 0, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 18, insured: false, name: "retail", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "retail-a-b-c"}, weight: 18, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 1.5, insured: false, name: "VIP", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "VIP-a-b-c"}, weight: 1, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 0, insured: false, name: "A1", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "A1-a-b-c"}, weight: 99999999999999999999, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 123456789.123, insured: false, name: "low", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "low-a-b-c"}, weight: 99999999999999999999, weighted: {a: 0, ok: 0, v: true}}, {flag: true, income: 2, insured: true, name: "A1", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "A1-a-b-c"}, weight: 10, weighted: {a: 0, ok: 0, v: true}}], grade: true, health: 0.0001, plan: "trial", rank: 0, rate: null, tag: 0, verified: false}, fee: false, flags: {net: [false]}, share: false}], + [{applicant: {rate: 0.5, channel: "é ü", plan: "basic", verified: true, dueDate: "2025-03-20", companies: []}}, "!error: ExpressionFailed"], + [{applicant: {rate: 0, channel: "A1", plan: "basic", verified: true, dueDate: "1990-06-15", companies: [{weight: 0.5, income: 10, insured: true, name: "low"}, {weight: -0.01, income: 2, insured: false, name: "VIP"}, {weight: 1.5, income: 371, insured: true, name: "low"}, {weight: 50, income: -0, insured: true, name: "O'Neil"}, {weight: 100, income: 0.25, insured: false, name: ""}]}}, {applicant: {calc: {exposure: "A1", points: false}, channel: "A1", companies: [{flag: false, income: 10, insured: true, name: "low", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "low-A1"}, weight: 0.5, weighted: {a: 0, ok: -12619, v: false}}, {flag: false, income: 2, insured: false, name: "VIP", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "VIP-A1"}, weight: -0.01, weighted: {a: 0, ok: -12619, v: false}}, {flag: false, income: 371, insured: true, name: "low", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "low-A1"}, weight: 1.5, weighted: {a: 0, ok: -12619, v: false}}, {flag: false, income: 0, insured: true, name: "O'Neil", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "O'Neil-A1"}, weight: 50, weighted: {a: 0, ok: -12619, v: false}}, {flag: false, income: 0.25, insured: false, name: "", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "-A1"}, weight: 100, weighted: {a: 0, ok: -12619, v: false}}], dueDate: "1990-06-15", grade: false, health: 0, plan: "basic", rank: null, rate: 0, tag: null, verified: true}, fee: false, flags: {net: [true]}, share: false}], + [{applicant: {rate: 100, channel: "日本", plan: "basic", verified: false, dueDate: "2025-03-20", companies: [{weight: 99.99, income: 100, insured: true, name: "abc"}, {weight: 1e3, income: 2.50, insured: true, name: "A1"}, {weight: 2, income: 10, insured: true, name: "Oslo"}, {weight: 1.5, income: 1000000, insured: true, name: "a"}, {weight: 10, income: 0.5, insured: false, name: " pad "}], extraField: "x"}}, {applicant: {calc: {exposure: "日本", points: true}, channel: "日本", companies: [{flag: true, income: 100, insured: true, name: "abc", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "abc-日本"}, weight: 99.99, weighted: {a: 0, ok: 78, v: true}}, {flag: true, income: 2.50, insured: true, name: "A1", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "A1-日本"}, weight: 1000, weighted: {a: 0, ok: 78, v: true}}, {flag: true, income: 10, insured: true, name: "Oslo", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "Oslo-日本"}, weight: 2, weighted: {a: 0, ok: 78, v: true}}, {flag: true, income: 1000000, insured: true, name: "a", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "a-日本"}, weight: 1.5, weighted: {a: 0, ok: 78, v: true}}, {flag: true, income: 0.5, insured: false, name: " pad ", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: " pad -日本"}, weight: 10, weighted: {a: 0, ok: 78, v: true}}], dueDate: "2025-03-20", extraField: "x", grade: true, health: 0.25, plan: "basic", rank: null, rate: 100, tag: null, verified: false}, fee: false, flags: {net: [false]}, share: false}], + [{applicant: {channel: "A1", plan: null, verified: false, dueDate: "2030-12-31", companies: [{weight: 99.99, income: 7.25, insured: false, name: "low"}, {weight: 1.5, income: 2.50, insured: true, name: "Oslo"}, {weight: 2, income: 18, insured: false, name: "VIP"}, {weight: 3, income: 0.25, insured: false, name: "x-y"}, {weight: -0, income: -500, insured: false, name: "a"}, {weight: 2, income: 250, insured: true, name: "retail"}, {weight: 100, income: 0.1, insured: true, name: "high"}, {weight: -0.01, income: 1.5, insured: false, name: "-"}, {weight: 2, income: -1, insured: true, name: "low"}]}}, {applicant: {calc: {exposure: "A1", points: true}, channel: "A1", companies: [{flag: false, income: 7.25, insured: false, name: "low", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "low-A1"}, weight: 99.99, weighted: {a: 0, ok: 2190, v: true}}, {flag: false, income: 2.50, insured: true, name: "Oslo", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "Oslo-A1"}, weight: 1.5, weighted: {a: 0, ok: 2190, v: true}}, {flag: false, income: 18, insured: false, name: "VIP", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "VIP-A1"}, weight: 2, weighted: {a: 0, ok: 2190, v: true}}, {flag: false, income: 0.25, insured: false, name: "x-y", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "x-y-A1"}, weight: 3, weighted: {a: 0, ok: 2190, v: true}}, {flag: false, income: -500, insured: false, name: "a", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "a-A1"}, weight: 0, weighted: {a: 0, ok: 2190, v: true}}, {flag: false, income: 250, insured: true, name: "retail", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "retail-A1"}, weight: 2, weighted: {a: 0, ok: 2190, v: true}}, {flag: false, income: 0.1, insured: true, name: "high", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "high-A1"}, weight: 100, weighted: {a: 0, ok: 2190, v: true}}, {flag: false, income: 1.5, insured: false, name: "-", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "--A1"}, weight: -0.01, weighted: {a: 0, ok: 2190, v: true}}, {flag: false, income: -1, insured: true, name: "low", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "low-A1"}, weight: 2, weighted: {a: 0, ok: 2190, v: true}}], dueDate: "2030-12-31", grade: true, health: 250000, plan: null, rank: null, tag: null, verified: false}, fee: false, flags: {net: []}, share: false}], + [{applicant: {rate: 0.25, channel: "3.5", plan: "premium", verified: true, dueDate: "2025-03-20", companies: [{weight: 0, income: 18, insured: false, name: "low"}]}}, {applicant: {calc: {exposure: "3.5", points: true}, channel: "3.5", companies: [{flag: false, income: 18, insured: false, name: "low", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "3.5"}, weight: 0, weighted: {a: 0, ok: 78, v: true}}], dueDate: "2025-03-20", grade: true, health: 324, plan: "premium", rank: null, rate: 0.25, tag: null, verified: true}, fee: false, flags: {net: []}, share: false}], + [{applicant: {rate: 0, channel: "a", plan: "trial", verified: false, dueDate: "2025-03-20", companies: [{weight: 10, income: 5, insured: true, name: "Oslo"}, {weight: 1000, income: 10, insured: true, name: "a"}, {weight: 1e3, income: 50, insured: true, name: "Oslo"}], extraField: "x"}}, {applicant: {calc: {exposure: "a"}, channel: "a", companies: [{flag: false, income: 5, insured: true, name: "Oslo", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "Oslo-a"}, weight: 10, weighted: {a: 0, ok: 78, v: true}}, {flag: false, income: 10, insured: true, name: "a", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "a-a"}, weight: 1000, weighted: {a: 0, ok: 78, v: true}}, {flag: true, income: 50, insured: true, name: "Oslo", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "Oslo-a"}, weight: 1000, weighted: {a: 0, ok: 78, v: true}}], dueDate: "2025-03-20", extraField: "x", grade: true, health: 25, plan: "trial", rank: 0, rate: 0, tag: 0, verified: false}, fee: false, flags: {net: [false]}, share: false}], + [{applicant: {rate: 1.5, channel: "Oslo", plan: "plus", verified: false, dueDate: "2025-03-20", companies: [{weight: 1e3, insured: true, name: "3.5"}, {weight: 10, income: 5, insured: false, name: "A1"}]}}, "!error: ExpressionFailed"], + [{applicant: {rate: 2.50, channel: "NL", plan: "trial", verified: true, dueDate: "2000-01-01", companies: [{weight: 0.5, income: 1000000, insured: true, name: "US"}, {weight: 123456789.123, income: 18, insured: false, name: "日本"}, {weight: 3, income: 0.1, insured: false, name: "VIP"}, {weight: 100, income: 0.25, insured: true, name: "retail"}, {weight: 10, income: 5, insured: true, name: "ok"}, {weight: 5, income: 100, insured: false, name: "Oslo"}, {weight: 0.000001, income: 2, insured: false, name: " pad "}, {weight: 18, income: 0.25, insured: false, name: ""}, {weight: 99999999999999999999, income: 1.5, insured: false, name: "Oslo"}, {weight: 1e3, income: 1e3, insured: true, name: "abc"}, {weight: 0.5, income: 0.5, insured: false, name: "Oslo"}, {weight: 1, income: 50, insured: false, name: "Oslo"}]}}, {applicant: {calc: {exposure: "NL"}, channel: "NL", companies: [{flag: false, income: 1000000, insured: true, name: "US", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "US-NL"}, weight: 0.5, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 18, insured: false, name: "日本", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "日本-NL"}, weight: 123456789.123, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 0.1, insured: false, name: "VIP", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "VIP-NL"}, weight: 3, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 0.25, insured: true, name: "retail", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "retail-NL"}, weight: 100, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 5, insured: true, name: "ok", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "ok-NL"}, weight: 10, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 100, insured: false, name: "Oslo", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "Oslo-NL"}, weight: 5, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 2, insured: false, name: " pad ", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: " pad -NL"}, weight: 0.000001, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 0.25, insured: false, name: "", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "-NL"}, weight: 18, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 1.5, insured: false, name: "Oslo", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "Oslo-NL"}, weight: 99999999999999999999, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 1000, insured: true, name: "abc", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "abc-NL"}, weight: 1000, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 0.5, insured: false, name: "Oslo", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "Oslo-NL"}, weight: 0.5, weighted: {a: 15.625, ok: -9132, v: true}}, {flag: false, income: 50, insured: false, name: "Oslo", ok: {s: 2.50}, summary: {a: false, s: 100}, totals: {eligible: "Oslo-NL"}, weight: 1, weighted: {a: 15.625, ok: -9132, v: true}}], dueDate: "2000-01-01", grade: true, health: 0.01, plan: "trial", rank: 2.50, rate: 2.50, tag: 2.50, verified: true}, flags: {net: [true]}, share: true}], + [{applicant: {rate: 18, channel: "gold", plan: "premium", verified: null, dueDate: "1990-06-15", companies: [{weight: 5, income: 0.1, insured: false, name: "VIP"}]}}, "!error: MissingRequiredInputs"], + [{applicant: {channel: "VIP", plan: null, verified: false, dueDate: "2025-03-20T10:15:30Z", companies: [{weight: 5, income: 18, insured: false, name: "ok"}, {weight: 1, income: 0.25, insured: true, name: "12"}, {weight: 2, income: 487, insured: false, name: "DE"}, {weight: 1, income: 99.99, insured: true, name: "a-b-c"}]}}, {applicant: {calc: {exposure: "VIP", points: true}, channel: "VIP", companies: [{flag: false, income: 18, insured: false, name: "ok", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "ok-VIP"}, weight: 5, weighted: {a: 0, ok: 78, v: true}}, {flag: false, income: 0.25, insured: true, name: "12", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "12-VIP"}, weight: 1, weighted: {a: 0, ok: 78, v: true}}, {flag: false, income: 487, insured: false, name: "DE", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "DE-VIP"}, weight: 2, weighted: {a: 0, ok: 78, v: true}}, {flag: true, income: 99.99, insured: true, name: "a-b-c", ok: {s: 0}, summary: {a: false, s: 100}, totals: {eligible: "a-b-c-VIP"}, weight: 1, weighted: {a: 0, ok: 78, v: true}}], dueDate: "2025-03-20T10:15:30Z", grade: true, health: 0.0625, plan: null, rank: null, tag: null, verified: false}, fee: false, flags: {net: []}, share: false}], + [{applicant: {rate: 1, channel: "A1", plan: "premium", verified: true, dueDate: "1990-06-15", companies: [{weight: 65, income: 0.5, insured: true, name: "A1"}]}}, {applicant: {calc: {exposure: "A1", points: false}, channel: "A1", companies: [{flag: false, income: 0.5, insured: true, name: "A1", ok: {s: 0}, summary: {a: true, s: 100}, totals: {eligible: "A1-A1"}, weight: 65, weighted: {a: 0, ok: -12619, v: false}}], dueDate: "1990-06-15", grade: false, health: 0.25, plan: "premium", rank: null, rate: 1, tag: null, verified: true}, fee: false, flags: {net: []}, share: false}], + [{applicant: {rate: 2, channel: "", plan: "plus", verified: false, dueDate: "2000-01-01", companies: [{weight: -500, income: 7.25, insured: true, name: "a-b-c"}, {weight: 10, income: 250, insured: false, name: "DE"}, {weight: -0, income: 2, insured: true, name: "日本"}], extraField: "x"}}, {applicant: {calc: {exposure: ""}, channel: "", companies: [{flag: false, income: 7.25, insured: true, name: "a-b-c", ok: {s: 2}, summary: {a: false, s: 100}, totals: {eligible: ""}, weight: -500, weighted: {a: 8, ok: -9132, v: true}}, {flag: false, income: 250, insured: false, name: "DE", ok: {s: 2}, summary: {a: false, s: 100}, totals: {eligible: ""}, weight: 10, weighted: {a: 8, ok: -9132, v: true}}, {flag: false, income: 2, insured: true, name: "日本", ok: {s: 2}, summary: {a: false, s: 100}, totals: {eligible: ""}, weight: 0, weighted: {a: 8, ok: -9132, v: true}}], dueDate: "2000-01-01", extraField: "x", grade: true, health: 4, plan: "plus", rank: 2, rate: 2, tag: 2, verified: false}, flags: {net: []}, share: true}], + [{applicant: {rate: 0.5, channel: "low", plan: "premium", verified: true, dueDate: "1990-06-15", companies: [{weight: 0, income: 1000000, insured: false, name: "low"}, {weight: 0, income: 10, insured: false, name: "3.5"}]}}, {applicant: {calc: {exposure: "low", points: false}, channel: "low", companies: [{flag: false, income: 1000000, insured: false, name: "low", ok: {s: 0}, summary: {a: true, s: 100}, totals: {eligible: "LOW"}, weight: 0, weighted: {a: 0, ok: -12619, v: false}}, {flag: false, income: 10, insured: false, name: "3.5", ok: {s: 0}, summary: {a: true, s: 100}, totals: {eligible: "LOW"}, weight: 0, weighted: {a: 0, ok: -12619, v: false}}], dueDate: "1990-06-15", grade: false, health: 100, plan: "premium", rank: null, rate: 0.5, tag: null, verified: true}, fee: false, flags: {net: []}, share: false}], + [{applicant: {rate: 100, channel: "retail", plan: "premium", verified: true, dueDate: "2025-03-20T10:15:30Z", companies: []}}, "!error: ExpressionFailed"], + ], +} + +// seed 341300 (attempt 0) +{ + name: "b 14: tenant/parcels/parts: 3 expression, 3 match, 6 table; 11 root, 6 per-member, 1 top-level computed", + policy: { + models: {tenant: {balance: "number?", price: "number", years: "number", weight: "number?", since: "date", parcels: "parcel[]"}, parcel: {amount: "number", days: "number", income: "number", parts: "part[]"}, part: {age: "number?", name: "string?", urgent: "boolean?"}}, + blocks: [ + {table: "t3", inputs: ["(tenant.balance ?? 0)", "tenant.since"], outputs: ["tenant.fee"], rules: [ + ["", ">= d('2025-03-20')", "tenant.price == 0.5"], + ["!= 1.5", "> d('2025-03-20')", "tenant.years <= 5"], + ["[1000..1005]", "< d('2025-01-01')", "(tenant.weight ?? 0) == 100"], + ["<= 1000", "", "tenant.years < 10"], + ["", "< d('2024-01-01')", "(tenant.weight ?? 0) == 1.5"], + ["2, 10", "> d('2000-06-30')", "(tenant.balance ?? 0) <= 5"], + ["!= 100", "< d('2025-01-01')", "tenant.years == 1000"], + ]}, + {match: "tenant.flags.capped", arms: [["tenant.since.isAfter(d('2025-03-20'), 'year')", "`${tenant.discount}/${(tenant.weight ?? 0)}`"], ["not (1000 != (tenant.scores.points ?? 0))", "`${(tenant.fee ?? false)}/${tenant.since.diff(d('2025-01-01'), 'day')}`"], ["matches(tenant.discount, '^[A-Z]')", "(split((split(tenant.discount, '-')[1] ?? 'none'), '-')[1] ?? 'none')"], ["none(tenant.parcels, #.days == 100)", "trim((split(tenant.discount, '-')[0] ?? 'none'))"], ["", "tenant.discount"]]}, + {expression: "tenant.flags.eligible", value: "{v: tenant.flags.capped in ['ok', 'Oslo'], a: all(tenant.parcels, not (#.days > 1))}"}, + {table: "t10", inputs: ["number(string(tenant.price))"], outputs: ["tenant.grade", "tenant.risk", "tenant.summary"], rules: [ + ["100", "(tenant.balance ?? 0)", "tenant.ok", "((tenant.balance ?? 0) % (abs(tenant.years) + 1))"], + ["1.5", "", "tenant.flags.capped", "sum(map(tenant.parcels, #.income))"], + ["", "(tenant.weight ?? 0)", "tenant.flags.capped", "1000"], + ]}, + {table: "t11", inputs: ["parcel.band"], outputs: ["parcel.segment", "parcel.health[]", "parcel.weighted"], rules: [ + ["", "tenant.ok", "parcel.amount", "trunc(parcel.income)"], + ["'low', 'Oslo'", "(split(tenant.flags.capped, '-')[1] ?? 'none')", "(tenant.summary ?? 0)", ""], + ["'US', 'high'", "(tenant.flags.eligible.a ? 'retail' : parcel.band)", "0.25", "((tenant.weight ?? 0) * 250)"], + ["$ != 'retail'", "tenant.discount", "18", "(tenant.summary ?? 0)"], + ["$ != 'US'", "(tenant.risk ?? '')", "(parcel.penalty ?? 0)", "tenant.price"], + ["startsWith($, 'retail')", "(tenant.risk ?? '')", "len(filter(parcel.parts, contains(['A1', 'VIP', ''], (#.name ?? ''))))", "tenant.years"], + ]}, + {table: "t7", hit: "collect", inputs: [null, "(tenant.scores.points ?? 0)", null], outputs: ["tag"], rules: [ + ["not ((tenant.fee ?? false))", "", "tenant.years == tenant.price", "(tenant.fee ?? false)"], + ["", "", "((tenant.fee ?? false) or (tenant.fee ?? false))", "(tenant.fee ?? false)"], + ["((tenant.fee ?? false) or (tenant.fee ?? false))", "!= 1.5", "((tenant.fee ?? false) and (tenant.fee ?? false))", "(tenant.fee ?? false)"], + ]}, + {table: "t1", inputs: ["parcel.income", "parcel.income", "parcel.days"], outputs: ["parcel.penalty"], rules: [ + ["", "< 1000", "!= 0.5", "0.25"], + ["", "1000", "", "tenant.price"], + ["5, 250", "!= 100", "", "3"], + ]}, + {match: "parcel.band", arms: [["isNumeric(string(tenant.price > 5))", "((tenant.balance ?? 0) > 0.5 ? 'A1' : 'none')"], ["parcel.penalty == null", "string((tenant.weight ?? 0))"], ["", "'none'"]]}, + {expression: "parcel.totals.decision", value: "(tenant.balance ?? 0) in [12..29)"}, + {expression: "tenant.ok", value: "('A1' + '-' + tenant.flags.capped)"}, + {match: "tenant.discount", arms: [["((tenant.fee ?? false) or (tenant.fee ?? false))", "tenant.since.format('%Y')"], ["", "'low'"]]}, + {table: "t5", inputs: ["tenant.since", "tenant.since", "tenant.price"], outputs: ["tenant.scores.points"], rules: [ + ["< d('2000-06-30')", ">= d('2024-01-01')", "!= 50", "tenant.years"], + ["", "", ">= 0.25", ""], + ["< d('2025-03-20')", "> d('2025-01-01')", "50", "0"], + ["", "", "", "(tenant.weight ?? 0)"], + ]}, + ], + }, + cases: [ + [{tenant: {balance: 1, price: 100, years: 50, weight: 5, since: "1990-06-15", parcels: [{amount: 1.5, days: 50, income: 1e3, parts: [{age: null, name: null, urgent: false}]}]}}, {tag: [], tenant: {balance: 1, discount: "low", fee: false, flags: {capped: "low"}, grade: 1, ok: "A1-low", parcels: [{amount: 1.5, band: "none", days: 50, health: [1.5, 18, 100], income: 1000, parts: [{age: null, name: null, urgent: false}], penalty: 100, segment: "A1-low", totals: {decision: false}, weighted: 1000}], price: 100, risk: "A1-low", scores: {points: 5}, since: "1990-06-15", summary: 1, weight: 5, years: 50}}], + [{tenant: {balance: null, price: 1, years: 0.000001, weight: null, since: "2025-03-20T10:15:30Z", parcels: [{amount: 2, days: 1000, income: 250, parts: [{age: 5, name: "a"}, {age: 7.25, name: null, urgent: false}]}, {amount: 250, days: 0, income: 100, parts: [{age: 1.5, name: "high", urgent: false}]}]}}, {tag: [], tenant: {balance: null, discount: "low", fee: false, flags: {capped: "low"}, grade: 0, ok: "A1-low", parcels: [{amount: 2, band: "none", days: 1000, health: [2, 18, 0.25], income: 250, parts: [{age: 5, name: "a"}, {age: 7.25, name: null, urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 250}, {amount: 250, band: "none", days: 0, health: [250, 18, 0.25], income: 100, parts: [{age: 1.5, name: "high", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 100}], price: 1, risk: "low", scores: {points: 0}, since: "2025-03-20T10:15:30Z", summary: 1000, weight: null, years: 0.000001}}], + [{tenant: {balance: -0.5, price: 1000, years: 0.25, weight: 100, since: "2024-02-29", parcels: [{amount: 1.5, days: 99.99, income: -0.01, parts: [{age: 10, name: "Oslo", urgent: false}, {age: 1000, name: "Oslo", urgent: false}]}], extraField: "x"}}, {tag: [true, true], tenant: {balance: -0.5, discount: "2024", extraField: "x", fee: true, flags: {capped: "2024"}, grade: 100, ok: "A1-2024", parcels: [{amount: 1.5, band: "none", days: 99.99, health: [1.5, 18, 0.25], income: -0.01, parts: [{age: 10, name: "Oslo", urgent: false}, {age: 1000, name: "Oslo", urgent: false}], penalty: 0.25, segment: "A1-2024", totals: {decision: false}, weighted: -0}], price: 1000, risk: "2024", scores: {points: 100}, since: "2024-02-29", summary: 1000, weight: 100, years: 0.25}}], + [{tenant: {balance: 18, price: 1.5, years: 1.5, weight: null, since: "2025-03-20T10:15:30Z", parcels: [{amount: 5, days: 0, income: 100, parts: [{name: null, urgent: false}, {age: 250, name: null}]}, {amount: 99.99, days: 3, income: 123456789.123, parts: []}, {amount: 50, days: 50, income: 1.5, parts: [{name: null, urgent: true}]}, {amount: 100, days: 100, income: 1000000, parts: []}]}}, {tag: [false], tenant: {balance: 18, discount: "low", fee: false, flags: {capped: "low"}, grade: 0, ok: "A1-low", parcels: [{amount: 5, band: "none", days: 0, health: [5, 18, 0.25], income: 100, parts: [{name: null, urgent: false}, {age: 250, name: null}], penalty: 0.25, segment: "A1-low", totals: {decision: true}, weighted: 100}, {amount: 99.99, band: "0", days: 3, health: [99.99, 18, 0], income: 123456789.123, parts: [], penalty: null, segment: "A1-low", totals: {decision: true}, weighted: 123456789}, {amount: 50, band: "none", days: 50, health: [50, 18, 0.25], income: 1.5, parts: [{name: null, urgent: true}], penalty: 0.25, segment: "A1-low", totals: {decision: true}, weighted: 1}, {amount: 100, band: "0", days: 100, health: [100, 18, 0], income: 1000000, parts: [], penalty: null, segment: "A1-low", totals: {decision: true}, weighted: 1000000}], price: 1.5, risk: "low", scores: {points: 0}, since: "2025-03-20T10:15:30Z", summary: 124456890.623, weight: null, years: 1.5}}], + [{tenant: {balance: 0.25, price: 0.25, years: 3, weight: 100, since: "2024-02-29", parcels: [{amount: 7.25, days: 0, income: 99999999999999999999, parts: [{age: 0.5, name: "US", urgent: true}, {age: 250, name: "A1", urgent: true}]}]}}, {tag: [true, true], tenant: {balance: 0.25, discount: "2024", fee: true, flags: {capped: "2024"}, grade: 100, ok: "A1-2024", parcels: [{amount: 7.25, band: "100", days: 0, health: [7.25, 18, 0], income: 99999999999999999999, parts: [{age: 0.5, name: "US", urgent: true}, {age: 250, name: "A1", urgent: true}], penalty: null, segment: "A1-2024", totals: {decision: false}, weighted: 99999999999999999999}], price: 0.25, risk: "2024", scores: {points: 100}, since: "2024-02-29", summary: 1000, weight: 100, years: 3}}], + [{tenant: {balance: 0.5, price: 1000, years: 250, weight: 1000, since: "2030-12-31", parcels: [{amount: 100, days: 0.5, income: 0, parts: [{age: 50, name: "gold", urgent: true}]}, {amount: 50, days: 5, income: 1000, parts: [{age: 50, name: " pad ", urgent: false}, {age: 0.25, name: "ok", urgent: true}]}, {amount: 250, days: 0, income: 3, parts: [{age: 0.25, name: "retail", urgent: false}]}, {amount: 1000, days: 0, income: 1000, parts: [{age: 50, name: "a-b-c", urgent: true}, {age: 1000, name: "A1", urgent: true}]}]}}, {tag: [], tenant: {balance: 0.5, discount: "low", fee: false, flags: {capped: "low/1000"}, grade: 1000, ok: "A1-low/1000", parcels: [{amount: 100, band: "1000", days: 0.5, health: [100, 18, 0], income: 0, parts: [{age: 50, name: "gold", urgent: true}], penalty: null, segment: "A1-low/1000", totals: {decision: false}, weighted: 0}, {amount: 50, band: "none", days: 5, health: [50, 18, 1000], income: 1000, parts: [{age: 50, name: " pad ", urgent: false}, {age: 0.25, name: "ok", urgent: true}], penalty: 1000, segment: "A1-low/1000", totals: {decision: false}, weighted: 1000}, {amount: 250, band: "none", days: 0, health: [250, 18, 0.25], income: 3, parts: [{age: 0.25, name: "retail", urgent: false}], penalty: 0.25, segment: "A1-low/1000", totals: {decision: false}, weighted: 3}, {amount: 1000, band: "none", days: 0, health: [1000, 18, 1000], income: 1000, parts: [{age: 50, name: "a-b-c", urgent: true}, {age: 1000, name: "A1", urgent: true}], penalty: 1000, segment: "A1-low/1000", totals: {decision: false}, weighted: 1000}], price: 1000, risk: "low/1000", scores: {points: 1000}, since: "2030-12-31", summary: 1000, weight: 1000, years: 250}}], + [{tenant: {price: 1000, years: 5, weight: 100, since: "2025-03-20T10:15:30Z", parcels: []}}, {tag: [], tenant: {discount: "low", fee: false, flags: {capped: "low"}, grade: 100, parcels: [], price: 1000, risk: "low", scores: {points: 100}, since: "2025-03-20T10:15:30Z", summary: 1000, weight: 100, years: 5}}], + [{tenant: {balance: 50, price: 100, years: 18, weight: 5, since: "2024-02-29", parcels: []}}, {tag: [], tenant: {balance: 50, discount: "low", fee: false, flags: {capped: "low"}, grade: 50, ok: "A1-low", parcels: [], price: 100, risk: "A1-low", scores: {points: 5}, since: "2024-02-29", summary: 12, weight: 5, years: 18}}], + [{tenant: {balance: 5, price: 50, years: 0, weight: 1000, since: "2024-02-29", parcels: [{amount: 3, days: 1e3, income: null, parts: [{age: 0.5, name: "retail", urgent: true}, {age: 250, name: "x", urgent: false}, {age: 18, name: "日本", urgent: false}]}, {amount: 99.99, days: 1000, income: 50, parts: [{age: 1000000, name: "A1", urgent: true}]}, {amount: -500, days: 1, income: 0.25, parts: [{age: 1, name: "Oslo", urgent: false}, {age: 7.25, name: "Oslo", urgent: false}]}, {amount: 50, days: 1.5, income: 18, parts: [{age: 0.25, name: "A1", urgent: true}, {age: 250, name: "ok", urgent: true}]}]}}, "!error: ExpressionFailed"], + [{tenant: {balance: 1000, price: 5, years: 10, weight: 99999999999999999999, since: "2025-03-20T10:15:30Z", parcels: [{amount: 2.50, days: 100, income: 1.5, parts: [{age: 0.25, name: "12", urgent: true}, {age: 2, name: "-", urgent: true}]}, {amount: 1000000, days: 1, income: 1000, parts: [{age: 1000000, name: "O'Neil", urgent: true}, {age: 10, name: "-", urgent: false}, {age: 1, name: "US", urgent: false}]}]}}, {tag: [], tenant: {balance: 1000, discount: "low", fee: false, flags: {capped: "low"}, grade: 99999999999999999999, ok: "A1-low", parcels: [{amount: 2.50, band: "none", days: 100, health: [2.50, 18, 0.25], income: 1.5, parts: [{age: 0.25, name: "12", urgent: true}, {age: 2, name: "-", urgent: true}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 1}, {amount: 1000000, band: "none", days: 1, health: [1000000, 18, 5], income: 1000, parts: [{age: 1000000, name: "O'Neil", urgent: true}, {age: 10, name: "-", urgent: false}, {age: 1, name: "US", urgent: false}], penalty: 5, segment: "A1-low", totals: {decision: false}, weighted: 1000}], price: 5, risk: "low", scores: {points: 99999999999999999999}, since: "2025-03-20T10:15:30Z", summary: 1000, weight: 99999999999999999999, years: 10}}], + [{tenant: {balance: 1000, price: 7.25, years: -0.5, since: "2030-12-31", parcels: [{amount: 0.5, days: -0, income: 2.50, parts: []}, {amount: 100, days: 100, income: 1.5, parts: []}, {amount: 10, days: 1000000, income: 10, parts: [{name: "-"}]}]}}, {tag: [], tenant: {balance: 1000, discount: "low", fee: false, flags: {capped: "low/0"}, grade: 0, ok: "A1-low/0", parcels: [{amount: 0.5, band: "none", days: 0, health: [0.5, 18, 0.25], income: 2.50, parts: [], penalty: 0.25, segment: "A1-low/0", totals: {decision: false}, weighted: 2}, {amount: 100, band: "none", days: 100, health: [100, 18, 0.25], income: 1.5, parts: [], penalty: 0.25, segment: "A1-low/0", totals: {decision: false}, weighted: 1}, {amount: 10, band: "none", days: 1000000, health: [10, 18, 0.25], income: 10, parts: [{name: "-"}], penalty: 0.25, segment: "A1-low/0", totals: {decision: false}, weighted: 10}], price: 7.25, risk: "low/0", scores: {points: 0}, since: "2030-12-31", summary: 1000, years: -0.5}}], + [{tenant: {price: 50, years: 10, weight: 0.25, since: "2024-01-01", parcels: []}}, {tag: [], tenant: {discount: "low", fee: false, flags: {capped: "low"}, grade: 0.25, parcels: [], price: 50, risk: "low", scores: {points: 0.25}, since: "2024-01-01", summary: 1000, weight: 0.25, years: 10}}], + [{tenant: {balance: 2, price: 1.5, years: 10, weight: 2, since: "2024-01-01", parcels: []}}, {tag: [], tenant: {balance: 2, discount: "low", fee: false, flags: {capped: "low"}, grade: 2, parcels: [], price: 1.5, risk: "low", scores: {points: 2}, since: "2024-01-01", summary: 0, weight: 2, years: 10}}], + [{tenant: {balance: 0, price: 50, years: 1000, since: "2030-12-31", parcels: [{amount: 0.25, days: 100, income: 99.99, parts: [{name: null, urgent: null}, {age: 1.5, name: null, urgent: false}, {age: null, name: null, urgent: null}]}]}}, {tag: [], tenant: {balance: 0, discount: "low", fee: false, flags: {capped: "low/0"}, grade: 0, ok: "A1-low/0", parcels: [{amount: 0.25, band: "none", days: 100, health: [0.25, 18, 0.25], income: 99.99, parts: [{name: null, urgent: null}, {age: 1.5, name: null, urgent: false}, {age: null, name: null, urgent: null}], penalty: 0.25, segment: "A1-low/0", totals: {decision: false}, weighted: 99}], price: 50, risk: "low/0", scores: {points: 0}, since: "2030-12-31", summary: 1000, years: 1000}}], + [{tenant: {balance: 1000, price: 18, years: 0.5, weight: 1000, since: "2024-02-29", parcels: [{amount: 5, days: 0.1, income: 441, parts: [{age: null, name: "VIP", urgent: false}]}]}}, {tag: [], tenant: {balance: 1000, discount: "low", fee: false, flags: {capped: "false/-307"}, grade: 1000, ok: "A1-false/-307", parcels: [{amount: 5, band: "none", days: 0.1, health: [5, 18, 0.25], income: 441, parts: [{age: null, name: "VIP", urgent: false}], penalty: 0.25, segment: "A1-false/-307", totals: {decision: false}, weighted: 441}], price: 18, risk: "false/-307", scores: {points: 1000}, since: "2024-02-29", summary: 1000, weight: 1000, years: 0.5}}], + [{tenant: {balance: 250, price: 2, years: 1000, weight: 2, since: "2025-03-20", parcels: [{amount: 123456789.123, days: 1, income: 2.50, parts: [{age: 100, name: "日本", urgent: true}, {age: 0.5, name: "abc", urgent: true}, {age: 1e3, name: "A1", urgent: false}]}, {amount: 18, days: 7.25, income: 5, parts: []}, {amount: 18, days: 5, income: 2.50, parts: [{age: -1, name: " pad ", urgent: true}, {age: 99999999999999999999, name: "ok", urgent: true}, {age: 1000, name: "a-b-c", urgent: true}]}]}}, {tag: [], tenant: {balance: 250, discount: "low", fee: false, flags: {capped: "low"}, grade: 2, ok: "A1-low", parcels: [{amount: 123456789.123, band: "none", days: 1, health: [123456789.123, 18, 0.25], income: 2.50, parts: [{age: 100, name: "日本", urgent: true}, {age: 0.5, name: "abc", urgent: true}, {age: 1000, name: "A1", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 2}, {amount: 18, band: "none", days: 7.25, health: [18, 18, 0.25], income: 5, parts: [], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 5}, {amount: 18, band: "none", days: 5, health: [18, 18, 0.25], income: 2.50, parts: [{age: -1, name: " pad ", urgent: true}, {age: 99999999999999999999, name: "ok", urgent: true}, {age: 1000, name: "a-b-c", urgent: true}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 2}], price: 2, risk: "low", scores: {points: 2}, since: "2025-03-20", summary: 1000, weight: 2, years: 1000}}], + [{tenant: {balance: 5, price: 250, years: 123456789.123, weight: 1000, since: "1990-06-15", parcels: [{amount: 10, days: -0, income: 18, parts: [{age: 0.1, name: "Oslo", urgent: false}, {age: 3, name: "a", urgent: false}]}, {amount: 1000, days: 2, income: 10, parts: [{age: 1.5, name: "A1", urgent: true}, {age: 50, name: "日本", urgent: false}]}, {amount: 2, days: 1000, income: 18, parts: [{age: 1000, name: "-", urgent: true}, {age: 250, name: "VIP", urgent: true}]}]}}, {tag: [], tenant: {balance: 5, discount: "low", fee: false, flags: {capped: "false/-12619"}, grade: 1000, ok: "A1-false/-12619", parcels: [{amount: 10, band: "none", days: 0, health: [10, 18, 0.25], income: 18, parts: [{age: 0.1, name: "Oslo", urgent: false}, {age: 3, name: "a", urgent: false}], penalty: 0.25, segment: "A1-false/-12619", totals: {decision: false}, weighted: 18}, {amount: 1000, band: "none", days: 2, health: [1000, 18, 0.25], income: 10, parts: [{age: 1.5, name: "A1", urgent: true}, {age: 50, name: "日本", urgent: false}], penalty: 0.25, segment: "A1-false/-12619", totals: {decision: false}, weighted: 10}, {amount: 2, band: "none", days: 1000, health: [2, 18, 0.25], income: 18, parts: [{age: 1000, name: "-", urgent: true}, {age: 250, name: "VIP", urgent: true}], penalty: 0.25, segment: "A1-false/-12619", totals: {decision: false}, weighted: 18}], price: 250, risk: "false/-12619", scores: {points: 1000}, since: "1990-06-15", summary: 1000, weight: 1000, years: 123456789.123}}], + [{tenant: {balance: 0.25, price: 132, years: 0.25, weight: 1.5, since: "2030-12-31", parcels: [], extraField: "x"}}, {tag: [], tenant: {balance: 0.25, discount: "low", extraField: "x", fee: false, flags: {capped: "low/1.5"}, grade: 1.5, parcels: [], price: 132, risk: "low/1.5", scores: {points: 1.5}, since: "2030-12-31", summary: 1000, weight: 1.5, years: 0.25}}], + [{tenant: {balance: 1000, price: 18, years: 1, weight: 1.5, since: "2024-01-01", parcels: [{amount: 250, days: 100, income: 0.25, parts: [{age: 1.5, name: "US", urgent: true}, {age: 123456789.123, name: "日本", urgent: true}, {age: 10, name: "Oslo", urgent: false}]}, {amount: 29, days: 10, income: 1, parts: [{age: 250, name: "VIP", urgent: true}]}, {amount: 0, days: 99.99, income: 5, parts: []}, {amount: 5, days: 1000, income: 18, parts: [{age: 0.25, name: "Oslo", urgent: true}, {age: 0.5, name: "VIP", urgent: false}]}, {amount: 0.5, days: 10, income: 2, parts: [{age: 0.000001, name: "retail", urgent: true}, {age: 0.000001, name: "DE", urgent: false}]}]}}, {tag: [], tenant: {balance: 1000, discount: "low", fee: false, flags: {capped: "low"}, grade: 1.5, ok: "A1-low", parcels: [{amount: 250, band: "none", days: 100, health: [250, 18, 0.25], income: 0.25, parts: [{age: 1.5, name: "US", urgent: true}, {age: 123456789.123, name: "日本", urgent: true}, {age: 10, name: "Oslo", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 0}, {amount: 29, band: "none", days: 10, health: [29, 18, 0.25], income: 1, parts: [{age: 250, name: "VIP", urgent: true}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 1}, {amount: 0, band: "none", days: 99.99, health: [0, 18, 0.25], income: 5, parts: [], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 5}, {amount: 5, band: "none", days: 1000, health: [5, 18, 0.25], income: 18, parts: [{age: 0.25, name: "Oslo", urgent: true}, {age: 0.5, name: "VIP", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 18}, {amount: 0.5, band: "none", days: 10, health: [0.5, 18, 0.25], income: 2, parts: [{age: 0.000001, name: "retail", urgent: true}, {age: 0.000001, name: "DE", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 2}], price: 18, risk: "low", scores: {points: 1.5}, since: "2024-01-01", summary: 1000, weight: 1.5, years: 1}}], + [{tenant: {price: 1000, years: 50, weight: null, since: "2030-12-31", parcels: [{amount: 1.5, days: 1000, income: 0.25, parts: [{age: 2, name: "VIP"}, {name: " pad "}]}]}}, {tag: [], tenant: {discount: "low", fee: false, flags: {capped: "low/0"}, grade: 0, ok: "A1-low/0", parcels: [{amount: 1.5, band: "none", days: 1000, health: [1.5, 18, 0.25], income: 0.25, parts: [{age: 2, name: "VIP"}, {name: " pad "}], penalty: 0.25, segment: "A1-low/0", totals: {decision: false}, weighted: 0}], price: 1000, risk: "low/0", scores: {points: 0}, since: "2030-12-31", summary: 1000, weight: null, years: 50}}], + [{tenant: {balance: 0.5, price: 5, years: 3, since: "2024-01-01", parcels: [{amount: 100, days: 100, income: 3, parts: [{}]}, {amount: 123456789.123, days: 10, income: 1000, parts: [{age: 1.5, urgent: true}]}, {amount: 1.5, days: 2, income: 10, parts: [{name: "none", urgent: false}, {age: 0.1, name: null, urgent: false}]}, {amount: 99.99, days: 65, income: 100, parts: [{age: 0.25, urgent: false}, {age: null, name: null, urgent: true}]}]}}, {tag: [true, true], tenant: {balance: 0.5, discount: "2024", fee: true, flags: {capped: "2024"}, grade: 0, ok: "A1-2024", parcels: [{amount: 100, band: "none", days: 100, health: [100, 18, 0.25], income: 3, parts: [{}], penalty: 0.25, segment: "A1-2024", totals: {decision: false}, weighted: 3}, {amount: 123456789.123, band: "none", days: 10, health: [123456789.123, 18, 5], income: 1000, parts: [{age: 1.5, urgent: true}], penalty: 5, segment: "A1-2024", totals: {decision: false}, weighted: 1000}, {amount: 1.5, band: "none", days: 2, health: [1.5, 18, 0.25], income: 10, parts: [{name: "none", urgent: false}, {age: 0.1, name: null, urgent: false}], penalty: 0.25, segment: "A1-2024", totals: {decision: false}, weighted: 10}, {amount: 99.99, band: "none", days: 65, health: [99.99, 18, 0.25], income: 100, parts: [{age: 0.25, urgent: false}, {age: null, name: null, urgent: true}], penalty: 0.25, segment: "A1-2024", totals: {decision: false}, weighted: 100}], price: 5, risk: "2024", scores: {points: 0}, since: "2024-01-01", summary: 1000, years: 3}}], + [{tenant: {balance: 99999999999999999999, price: 0.5, years: 0, weight: 0.000001, since: "2024-01-01", parcels: [{amount: 3, days: 0.1, income: 1, parts: [{age: 250, name: "low", urgent: false}]}]}}, {tag: [], tenant: {balance: 99999999999999999999, discount: "low", fee: false, flags: {capped: "low"}, grade: 0.000001, ok: "A1-low", parcels: [{amount: 3, band: "none", days: 0.1, health: [3, 18, 0.25], income: 1, parts: [{age: 250, name: "low", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 1}], price: 0.5, risk: "low", scores: {points: 0.000001}, since: "2024-01-01", summary: 1000, weight: 0.000001, years: 0}}], + [{tenant: {balance: 250, price: 0.5, years: 250, weight: null, since: "2025-03-20", parcels: [{amount: 50, days: 0, income: 50, parts: [{age: 1000, name: "VIP", urgent: null}]}, {amount: 10, days: 1, income: 10, parts: [{name: null, urgent: null}]}]}}, {tag: [true, true], tenant: {balance: 250, discount: "2025", fee: true, flags: {capped: "2025"}, grade: 0, ok: "A1-2025", parcels: [{amount: 50, band: "none", days: 0, health: [50, 18, 0.25], income: 50, parts: [{age: 1000, name: "VIP", urgent: null}], penalty: 0.25, segment: "A1-2025", totals: {decision: false}, weighted: 50}, {amount: 10, band: "none", days: 1, health: [10, 18, 0.25], income: 10, parts: [{name: null, urgent: null}], penalty: 0.25, segment: "A1-2025", totals: {decision: false}, weighted: 10}], price: 0.5, risk: "2025", scores: {points: 0}, since: "2025-03-20", summary: 1000, weight: null, years: 250}}], + [{tenant: {balance: 99999999999999999999, price: 1000000, years: 5, weight: 0.25, since: "2030-12-31", parcels: []}}, {tag: [], tenant: {balance: 99999999999999999999, discount: "low", fee: false, flags: {capped: "low/0.25"}, grade: 0.25, parcels: [], price: 1000000, risk: "low/0.25", scores: {points: 0.25}, since: "2030-12-31", summary: 1000, weight: 0.25, years: 5}}], + [{tenant: {balance: 250, price: 3, years: 1.5, weight: 18, since: "2030-12-31", parcels: [{amount: 50, days: 0.000001, income: 10, parts: [{age: null, name: null, urgent: true}, {age: 10}, {age: null, urgent: false}]}, {amount: 1000, days: 18, income: 239, parts: [{age: 100, name: "A1", urgent: null}, {age: null, name: "Oslo"}]}]}}, {tag: [], tenant: {balance: 250, discount: "low", fee: false, flags: {capped: "low/18"}, grade: 18, ok: "A1-low/18", parcels: [{amount: 50, band: "none", days: 0.000001, health: [50, 18, 0.25], income: 10, parts: [{age: null, name: null, urgent: true}, {age: 10}, {age: null, urgent: false}], penalty: 0.25, segment: "A1-low/18", totals: {decision: false}, weighted: 10}, {amount: 1000, band: "none", days: 18, health: [1000, 18, 0.25], income: 239, parts: [{age: 100, name: "A1", urgent: null}, {age: null, name: "Oslo"}], penalty: 0.25, segment: "A1-low/18", totals: {decision: false}, weighted: 239}], price: 3, risk: "low/18", scores: {points: 18}, since: "2030-12-31", summary: 1000, weight: 18, years: 1.5}}], + [{tenant: {balance: 10, price: 0.5, years: 50, weight: 2.50, since: "1990-06-15", parcels: [{amount: 0.25, days: 100, income: 1000, parts: [{name: "retail", urgent: true}]}, {amount: -1, days: 1, income: 50, parts: [{age: 0.25}]}]}}, {tag: [], tenant: {balance: 10, discount: "low", fee: false, flags: {capped: "low"}, grade: 2.50, ok: "A1-low", parcels: [{amount: 0.25, band: "none", days: 100, health: [0.25, 18, 0.5], income: 1000, parts: [{name: "retail", urgent: true}], penalty: 0.5, segment: "A1-low", totals: {decision: false}, weighted: 1000}, {amount: -1, band: "none", days: 1, health: [-1, 18, 0.25], income: 50, parts: [{age: 0.25}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 50}], price: 0.5, risk: "low", scores: {points: 2.50}, since: "1990-06-15", summary: 1000, weight: 2.50, years: 50}}], + [{tenant: {balance: 250, price: 1000, years: 1, weight: 1000, since: "2030-12-31", parcels: []}}, {tag: [], tenant: {balance: 250, discount: "low", fee: false, flags: {capped: "low/1000"}, grade: 1000, parcels: [], price: 1000, risk: "low/1000", scores: {points: 1000}, since: "2030-12-31", summary: 1000, weight: 1000, years: 1}}], + [{tenant: {balance: 1000, price: 1000, years: 0.000001, weight: 285, since: "2024-02-29", parcels: [{amount: 65, days: 5, income: 50, parts: [{age: 0, name: "low", urgent: true}, {age: 50, name: "US", urgent: false}, {age: 2, name: "US", urgent: false}]}, {amount: 1000, days: 5, income: 1000, parts: [{age: 1, name: "DE", urgent: true}, {age: 0.5, name: "ok", urgent: false}]}, {amount: 1000, days: 18, income: 100, parts: [{age: 2, name: "none", urgent: false}, {age: 0.25, name: "", urgent: true}, {age: 1, name: "VIP", urgent: false}]}, {amount: 1.5, days: 347, income: 1000, parts: [{age: 1000, name: "Zed", urgent: false}, {age: 65, name: "a-b-c", urgent: true}, {age: -0.5, name: "retail", urgent: false}]}, {amount: 1, days: 18, income: 0, parts: []}]}}, {tag: [], tenant: {balance: 1000, discount: "low", fee: false, flags: {capped: "low"}, grade: 285, ok: "A1-low", parcels: [{amount: 65, band: "none", days: 5, health: [65, 18, 0.25], income: 50, parts: [{age: 0, name: "low", urgent: true}, {age: 50, name: "US", urgent: false}, {age: 2, name: "US", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 50}, {amount: 1000, band: "none", days: 5, health: [1000, 18, 1000], income: 1000, parts: [{age: 1, name: "DE", urgent: true}, {age: 0.5, name: "ok", urgent: false}], penalty: 1000, segment: "A1-low", totals: {decision: false}, weighted: 1000}, {amount: 1000, band: "none", days: 18, health: [1000, 18, 0.25], income: 100, parts: [{age: 2, name: "none", urgent: false}, {age: 0.25, name: "", urgent: true}, {age: 1, name: "VIP", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 100}, {amount: 1.5, band: "none", days: 347, health: [1.5, 18, 1000], income: 1000, parts: [{age: 1000, name: "Zed", urgent: false}, {age: 65, name: "a-b-c", urgent: true}, {age: -0.5, name: "retail", urgent: false}], penalty: 1000, segment: "A1-low", totals: {decision: false}, weighted: 1000}, {amount: 1, band: "none", days: 18, health: [1, 18, 0.25], income: 0, parts: [], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 0}], price: 1000, risk: "low", scores: {points: 285}, since: "2024-02-29", summary: 1000, weight: 285, years: 0.000001}}], + [{tenant: {balance: 10, price: -1, years: 65, weight: 1000000, since: "2024-02-29", parcels: [{amount: 5, days: 250, income: 1000, parts: [{age: 2, name: "ok", urgent: true}, {age: 50, name: "Oslo", urgent: false}]}, {amount: 100, days: 100, income: 10, parts: [{age: 1000, name: "ok", urgent: false}, {age: -500, name: " pad ", urgent: true}]}, {amount: 1.5, days: 99999999999999999999, income: 123456789.123, parts: [{age: -0, name: "low", urgent: true}, {age: 0.25, name: "A1", urgent: false}, {age: 1000, name: "none", urgent: false}]}, {amount: 0.25, days: 1000, income: 2.50, parts: [{age: 1, name: "x-y", urgent: false}]}, {amount: 100, days: 0.5, income: 100, parts: [{age: 0, name: "-", urgent: false}]}, {amount: 100, days: 10, income: 1.5, parts: [{age: 250, name: "A1", urgent: true}, {age: 1.5, name: " pad ", urgent: false}]}, {amount: 1000, days: -0.5, income: 1.5, parts: [{age: 2, name: "DE", urgent: true}, {age: 2, name: "Oslo", urgent: true}]}, {amount: 1, days: 100, income: 154, parts: [{age: 0.000001, name: "retail", urgent: true}, {age: 250, name: "high", urgent: false}]}, {amount: 0.25, days: 0.5, income: 0.5, parts: [{age: 0.5, name: "é ü", urgent: false}, {age: 1000, name: "A1", urgent: true}]}, {amount: 0.1, days: 2, income: 0.5, parts: [{age: 5, name: "DE", urgent: true}, {age: 10, name: "Zed", urgent: false}, {age: 5, name: "A1", urgent: true}]}]}}, {tag: [], tenant: {balance: 10, discount: "low", fee: false, flags: {capped: "low"}, grade: 1000000, ok: "A1-low", parcels: [{amount: 5, band: "none", days: 250, health: [5, 18, -1], income: 1000, parts: [{age: 2, name: "ok", urgent: true}, {age: 50, name: "Oslo", urgent: false}], penalty: -1, segment: "A1-low", totals: {decision: false}, weighted: 1000}, {amount: 100, band: "none", days: 100, health: [100, 18, 0.25], income: 10, parts: [{age: 1000, name: "ok", urgent: false}, {age: -500, name: " pad ", urgent: true}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 10}, {amount: 1.5, band: "1000000", days: 99999999999999999999, health: [1.5, 18, 0], income: 123456789.123, parts: [{age: 0, name: "low", urgent: true}, {age: 0.25, name: "A1", urgent: false}, {age: 1000, name: "none", urgent: false}], penalty: null, segment: "A1-low", totals: {decision: false}, weighted: 123456789}, {amount: 0.25, band: "none", days: 1000, health: [0.25, 18, 0.25], income: 2.50, parts: [{age: 1, name: "x-y", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 2}, {amount: 100, band: "1000000", days: 0.5, health: [100, 18, 0], income: 100, parts: [{age: 0, name: "-", urgent: false}], penalty: null, segment: "A1-low", totals: {decision: false}, weighted: 100}, {amount: 100, band: "none", days: 10, health: [100, 18, 0.25], income: 1.5, parts: [{age: 250, name: "A1", urgent: true}, {age: 1.5, name: " pad ", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 1}, {amount: 1000, band: "none", days: -0.5, health: [1000, 18, 0.25], income: 1.5, parts: [{age: 2, name: "DE", urgent: true}, {age: 2, name: "Oslo", urgent: true}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 1}, {amount: 1, band: "none", days: 100, health: [1, 18, 0.25], income: 154, parts: [{age: 0.000001, name: "retail", urgent: true}, {age: 250, name: "high", urgent: false}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 154}, {amount: 0.25, band: "1000000", days: 0.5, health: [0.25, 18, 0], income: 0.5, parts: [{age: 0.5, name: "é ü", urgent: false}, {age: 1000, name: "A1", urgent: true}], penalty: null, segment: "A1-low", totals: {decision: false}, weighted: 0}, {amount: 0.1, band: "none", days: 2, health: [0.1, 18, 0.25], income: 0.5, parts: [{age: 5, name: "DE", urgent: true}, {age: 10, name: "Zed", urgent: false}, {age: 5, name: "A1", urgent: true}], penalty: 0.25, segment: "A1-low", totals: {decision: false}, weighted: 0}], price: -1, risk: "low", scores: {points: 1000000}, since: "2024-02-29", summary: 1000, weight: 1000000, years: 65}}], + [{tenant: {price: -1, years: 0, since: "2024-01-01", parcels: [{amount: 2.50, days: 0.25, income: 2, parts: [{age: 1, name: "VIP"}, {age: 0.5, name: "A1"}, {age: 1, urgent: false}]}, {amount: 3, days: 1000, income: 2, parts: [{urgent: null}, {age: null, name: "a-b-c"}, {name: "high", urgent: false}]}, {amount: -0.5, days: 0.25, income: 0, parts: [{age: null, name: null}]}, {amount: 18, days: 1, income: 18, parts: [{name: "high", urgent: true}, {name: null, urgent: false}]}]}}, {tag: [true, true], tenant: {discount: "2024", fee: true, flags: {capped: "2024"}, grade: 0, ok: "A1-2024", parcels: [{amount: 2.50, band: "none", days: 0.25, health: [2.50, 18, 0.25], income: 2, parts: [{age: 1, name: "VIP"}, {age: 0.5, name: "A1"}, {age: 1, urgent: false}], penalty: 0.25, segment: "A1-2024", totals: {decision: false}, weighted: 2}, {amount: 3, band: "none", days: 1000, health: [3, 18, 0.25], income: 2, parts: [{urgent: null}, {age: null, name: "a-b-c"}, {name: "high", urgent: false}], penalty: 0.25, segment: "A1-2024", totals: {decision: false}, weighted: 2}, {amount: -0.5, band: "none", days: 0.25, health: [-0.5, 18, 0.25], income: 0, parts: [{age: null, name: null}], penalty: 0.25, segment: "A1-2024", totals: {decision: false}, weighted: 0}, {amount: 18, band: "none", days: 1, health: [18, 18, 0.25], income: 18, parts: [{name: "high", urgent: true}, {name: null, urgent: false}], penalty: 0.25, segment: "A1-2024", totals: {decision: false}, weighted: 18}], price: -1, risk: "2024", scores: {points: 0}, since: "2024-01-01", summary: 1000, years: 0}}], + ], +} + +// seed 341400 (attempt 0) +{ + name: "b 15: borrower/members: 2 assertion, 3 expression, 1 match; 1 root, 6 per-member, 2 top-level computed", + policy: { + models: {borrower: {weight: "number", name: "string", plan: "string(basic|plus|premium|trial)", members: "member[]"}, member: {income: "number", plan: "string(basic|plus|premium|trial)", age: "number?", amount: "number"}}, + blocks: [ + {assertion: "member.scores.penalty", conditions: [["or", "matches(string(member.amount == 0.5), '^[A-Z]')", 0], ["and", "borrower.plan in ['trial', 'plus']", 1], ["or", "some(borrower.members, #.income <= #.income)", 1]]}, + {assertion: "member.segment", conditions: [["or", "startsWith(string((member.age ?? 0)), 'A1')", 0], ["or", "avg([1000, member.income, borrower.weight, (member.age ?? 0)]) > member.income", 0], ["and", "member.plan in ['plus', 'basic']", 2], ["and", "(member.scores.penalty ? borrower.name : 'DE') != 'ok'", 2]]}, + {match: "totals.risk", arms: [["isNumeric(`${50 == 0}/${borrower.weight > 0}`)", "borrower.name"], ["(borrower.weight == 1000 and borrower.weight <= 3)", "`${borrower.weight}/${borrower.weight}`"], ["borrower.weight != borrower.weight", "upper(borrower.name)"], ["", "borrower.name"]]}, + {expression: "tag", value: "not (borrower.weight > borrower.weight)"}, + {expression: "borrower.capped", value: "trim(borrower.name)"}, + {expression: "member.flags.discount", value: "{ok: (sum(map(borrower.members, 5)) + -((member.age ?? 0))), a: member.income != borrower.weight, n: (min([abs(len(borrower.members)), 1000]) ^ 0)}"}, + ], + }, + cases: [ + [{borrower: {weight: 437, name: "ok", plan: "plus", members: [{income: -0, plan: "premium", age: 5, amount: 2.50}, {income: 0, plan: "plus", age: 250, amount: 7.25}, {income: 65, plan: "plus", age: 0.000001, amount: 123456789.123}, {income: 5, plan: "trial", age: 0, amount: 65}, {income: 0.5, plan: "premium", age: 5, amount: 0.1}]}}, {borrower: {capped: "ok", members: [{age: 5, amount: 2.50, flags: {discount: {a: true, n: 1, ok: 20}}, income: 0, plan: "premium", scores: {penalty: true}, segment: true}, {age: 250, amount: 7.25, flags: {discount: {a: true, n: 1, ok: -225}}, income: 0, plan: "plus", scores: {penalty: true}, segment: true}, {age: 0.000001, amount: 123456789.123, flags: {discount: {a: true, n: 1, ok: 24.999999}}, income: 65, plan: "plus", scores: {penalty: true}, segment: true}, {age: 0, amount: 65, flags: {discount: {a: true, n: 1, ok: 25}}, income: 5, plan: "trial", scores: {penalty: true}, segment: true}, {age: 5, amount: 0.1, flags: {discount: {a: true, n: 1, ok: 20}}, income: 0.5, plan: "premium", scores: {penalty: true}, segment: true}], name: "ok", plan: "plus", weight: 437}, tag: true, totals: {risk: "ok"}}], + [{borrower: {weight: 1000, name: "", plan: "basic", members: [{income: 0, plan: "trial", age: 99.99, amount: 2.50}]}}, {borrower: {capped: "", members: [{age: 99.99, amount: 2.50, flags: {discount: {a: true, n: 1, ok: -94.99}}, income: 0, plan: "trial", scores: {penalty: false}, segment: true}], name: "", plan: "basic", weight: 1000}, tag: true, totals: {risk: ""}}], + [{borrower: {weight: 1000, name: "12", plan: "plus", members: [{income: 5, plan: "premium", amount: 1000}, {income: 0.5, plan: "plus", amount: 5}, {income: 0, plan: "plus", age: null, amount: 0.000001}]}}, {borrower: {capped: "12", members: [{amount: 1000, flags: {discount: {a: true, n: 1, ok: 15}}, income: 5, plan: "premium", scores: {penalty: true}, segment: true}, {amount: 5, flags: {discount: {a: true, n: 1, ok: 15}}, income: 0.5, plan: "plus", scores: {penalty: true}, segment: true}, {age: null, amount: 0.000001, flags: {discount: {a: true, n: 1, ok: 15}}, income: 0, plan: "plus", scores: {penalty: true}, segment: true}], name: "12", plan: "plus", weight: 1000}, tag: true, totals: {risk: "12"}}], + [{borrower: {weight: 18, name: "O'Neil", plan: "basic", members: [{income: 65, plan: "basic", age: null, amount: 1000}, {income: 0, plan: "trial", age: 18, amount: 3}, {income: -0.5, plan: "basic", age: null, amount: 0.000001}, {income: 123456789.123, plan: "basic", amount: -0.5}]}}, {borrower: {capped: "O'Neil", members: [{age: null, amount: 1000, flags: {discount: {a: true, n: 1, ok: 20}}, income: 65, plan: "basic", scores: {penalty: false}, segment: true}, {age: 18, amount: 3, flags: {discount: {a: true, n: 1, ok: 2}}, income: 0, plan: "trial", scores: {penalty: false}, segment: true}, {age: null, amount: 0.000001, flags: {discount: {a: true, n: 1, ok: 20}}, income: -0.5, plan: "basic", scores: {penalty: false}, segment: true}, {amount: -0.5, flags: {discount: {a: true, n: 1, ok: 20}}, income: 123456789.123, plan: "basic", scores: {penalty: false}, segment: true}], name: "O'Neil", plan: "basic", weight: 18}, tag: true, totals: {risk: "O'Neil"}}], + [{borrower: {weight: 3, name: "Oslo", plan: "plus", members: [{income: 99.99, plan: "premium", age: 0, amount: -0}], extraField: {nested: true}}}, {borrower: {capped: "Oslo", extraField: {nested: true}, members: [{age: 0, amount: 0, flags: {discount: {a: true, n: 1, ok: 5}}, income: 99.99, plan: "premium", scores: {penalty: true}, segment: true}], name: "Oslo", plan: "plus", weight: 3}, tag: true, totals: {risk: "Oslo"}}], + [{borrower: {weight: 3, name: "O'Neil", plan: "trial", members: [{income: 99999999999999999999, plan: "plus", age: 99.99, amount: 1000}, {income: 99.99, plan: "premium", age: 1000000, amount: 7.25}, {income: -500, plan: "premium", age: 100, amount: 0.5}, {income: 2.50, plan: "trial", age: 1e3, amount: 0}, {income: 10, plan: "plus", age: 0.5, amount: 1000}]}}, {borrower: {capped: "O'Neil", members: [{age: 99.99, amount: 1000, flags: {discount: {a: true, n: 1, ok: -74.99}}, income: 99999999999999999999, plan: "plus", scores: {penalty: true}, segment: true}, {age: 1000000, amount: 7.25, flags: {discount: {a: true, n: 1, ok: -999975}}, income: 99.99, plan: "premium", scores: {penalty: true}, segment: true}, {age: 100, amount: 0.5, flags: {discount: {a: true, n: 1, ok: -75}}, income: -500, plan: "premium", scores: {penalty: true}, segment: true}, {age: 1000, amount: 0, flags: {discount: {a: true, n: 1, ok: -975}}, income: 2.50, plan: "trial", scores: {penalty: true}, segment: true}, {age: 0.5, amount: 1000, flags: {discount: {a: true, n: 1, ok: 24.5}}, income: 10, plan: "plus", scores: {penalty: true}, segment: true}], name: "O'Neil", plan: "trial", weight: 3}, tag: true, totals: {risk: "O'Neil"}}], + [{borrower: {weight: 1e3, name: " pad ", plan: "premium", members: [{income: 50, plan: "basic", age: 250, amount: -0.01}, {income: 65, plan: "premium", age: -500, amount: 0.5}, {income: 2, plan: "premium", age: 0, amount: 5}]}}, {borrower: {capped: "pad", members: [{age: 250, amount: -0.01, flags: {discount: {a: true, n: 1, ok: -235}}, income: 50, plan: "basic", scores: {penalty: false}, segment: true}, {age: -500, amount: 0.5, flags: {discount: {a: true, n: 1, ok: 515}}, income: 65, plan: "premium", scores: {penalty: false}, segment: true}, {age: 0, amount: 5, flags: {discount: {a: true, n: 1, ok: 15}}, income: 2, plan: "premium", scores: {penalty: false}, segment: true}], name: " pad ", plan: "premium", weight: 1000}, tag: true, totals: {risk: " pad "}}], + [{borrower: {weight: 5, name: "US", plan: "basic", members: []}}, {borrower: {capped: "US", members: [], name: "US", plan: "basic", weight: 5}, tag: true, totals: {risk: "US"}}], + [{borrower: {weight: 250, name: " pad ", plan: "plus", members: [{income: -0.01, plan: "basic", age: 0, amount: 5}, {income: 1000, plan: "premium", age: 1e3, amount: 18}, {income: 10, plan: "basic", age: 0.5, amount: 0}, {income: 65, plan: "basic", age: 0, amount: 65}, {income: -1, plan: "trial", age: 0.5, amount: 0}]}}, {borrower: {capped: "pad", members: [{age: 0, amount: 5, flags: {discount: {a: true, n: 1, ok: 25}}, income: -0.01, plan: "basic", scores: {penalty: true}, segment: true}, {age: 1000, amount: 18, flags: {discount: {a: true, n: 1, ok: -975}}, income: 1000, plan: "premium", scores: {penalty: true}, segment: false}, {age: 0.5, amount: 0, flags: {discount: {a: true, n: 1, ok: 24.5}}, income: 10, plan: "basic", scores: {penalty: true}, segment: true}, {age: 0, amount: 65, flags: {discount: {a: true, n: 1, ok: 25}}, income: 65, plan: "basic", scores: {penalty: true}, segment: true}, {age: 0.5, amount: 0, flags: {discount: {a: true, n: 1, ok: 24.5}}, income: -1, plan: "trial", scores: {penalty: true}, segment: true}], name: " pad ", plan: "plus", weight: 250}, tag: true, totals: {risk: " pad "}}], + [{borrower: {weight: 0.5, name: "gold", plan: "premium", members: [{income: 18, plan: "basic", amount: 2}, {income: 250, plan: "premium", age: 5, amount: 0}, {income: 18, plan: "plus", age: 1000000, amount: 0.000001}, {income: 99.99, plan: "plus", age: 100, amount: 65}, {income: 0.000001, plan: "basic", amount: 100}, {income: 0.5, plan: "basic", age: -0, amount: 0.5}, {income: -1, plan: "trial", age: 18, amount: 123456789.123}, {income: 0.000001, plan: "trial", age: 0.5, amount: 1e3}]}}, {borrower: {capped: "gold", members: [{amount: 2, flags: {discount: {a: true, n: 1, ok: 40}}, income: 18, plan: "basic", scores: {penalty: false}, segment: true}, {age: 5, amount: 0, flags: {discount: {a: true, n: 1, ok: 35}}, income: 250, plan: "premium", scores: {penalty: false}, segment: true}, {age: 1000000, amount: 0.000001, flags: {discount: {a: true, n: 1, ok: -999960}}, income: 18, plan: "plus", scores: {penalty: false}, segment: true}, {age: 100, amount: 65, flags: {discount: {a: true, n: 1, ok: -60}}, income: 99.99, plan: "plus", scores: {penalty: false}, segment: true}, {amount: 100, flags: {discount: {a: true, n: 1, ok: 40}}, income: 0.000001, plan: "basic", scores: {penalty: false}, segment: true}, {age: 0, amount: 0.5, flags: {discount: {a: false, n: 1, ok: 40}}, income: 0.5, plan: "basic", scores: {penalty: false}, segment: true}, {age: 18, amount: 123456789.123, flags: {discount: {a: true, n: 1, ok: 22}}, income: -1, plan: "trial", scores: {penalty: false}, segment: true}, {age: 0.5, amount: 1000, flags: {discount: {a: true, n: 1, ok: 39.5}}, income: 0.000001, plan: "trial", scores: {penalty: false}, segment: true}], name: "gold", plan: "premium", weight: 0.5}, tag: true, totals: {risk: "gold"}}], + [{borrower: {weight: 216, name: "VIP", plan: "basic", members: []}}, {borrower: {capped: "VIP", members: [], name: "VIP", plan: "basic", weight: 216}, tag: true, totals: {risk: "VIP"}}], + [{borrower: {weight: 18, name: "A1", plan: "premium", members: []}}, {borrower: {capped: "A1", members: [], name: "A1", plan: "premium", weight: 18}, tag: true, totals: {risk: "A1"}}], + [{borrower: {weight: 18, name: "A1", plan: "basic", members: [{income: 18, plan: "basic", age: 0.000001, amount: -0}, {income: 0, plan: "premium", age: 0, amount: 1000}, {income: 0.1, plan: "basic", age: 1e3, amount: 2}, {income: 100, plan: "basic", age: 1000, amount: 99999999999999999999}, {income: 99.99, plan: "trial", age: 50, amount: 2}]}}, {borrower: {capped: "A1", members: [{age: 0.000001, amount: 0, flags: {discount: {a: false, n: 1, ok: 24.999999}}, income: 18, plan: "basic", scores: {penalty: false}, segment: true}, {age: 0, amount: 1000, flags: {discount: {a: true, n: 1, ok: 25}}, income: 0, plan: "premium", scores: {penalty: false}, segment: true}, {age: 1000, amount: 2, flags: {discount: {a: true, n: 1, ok: -975}}, income: 0.1, plan: "basic", scores: {penalty: false}, segment: true}, {age: 1000, amount: 99999999999999999999, flags: {discount: {a: true, n: 1, ok: -975}}, income: 100, plan: "basic", scores: {penalty: false}, segment: true}, {age: 50, amount: 2, flags: {discount: {a: true, n: 1, ok: -25}}, income: 99.99, plan: "trial", scores: {penalty: false}, segment: true}], name: "A1", plan: "basic", weight: 18}, tag: true, totals: {risk: "A1"}}], + [{borrower: {weight: -0.5, name: "3.5", plan: "trial", members: [{income: 5, plan: "premium", age: 1, amount: 10}, {income: 0, plan: "basic", age: 18, amount: 5}, {income: 0, plan: "basic", age: -0.01, amount: 100}], extraField: 1}}, {borrower: {capped: "3.5", extraField: 1, members: [{age: 1, amount: 10, flags: {discount: {a: true, n: 1, ok: 14}}, income: 5, plan: "premium", scores: {penalty: true}, segment: true}, {age: 18, amount: 5, flags: {discount: {a: true, n: 1, ok: -3}}, income: 0, plan: "basic", scores: {penalty: true}, segment: true}, {age: -0.01, amount: 100, flags: {discount: {a: true, n: 1, ok: 15.01}}, income: 0, plan: "basic", scores: {penalty: true}, segment: true}], name: "3.5", plan: "trial", weight: -0.5}, tag: true, totals: {risk: "3.5"}}], + [{borrower: {weight: -0, name: "a-b-c", plan: "premium", members: [{income: 51, plan: "basic", amount: 7.25}, {income: 10, plan: "basic", age: null, amount: 0.1}]}}, {borrower: {capped: "a-b-c", members: [{amount: 7.25, flags: {discount: {a: true, n: 1, ok: 10}}, income: 51, plan: "basic", scores: {penalty: false}, segment: true}, {age: null, amount: 0.1, flags: {discount: {a: true, n: 1, ok: 10}}, income: 10, plan: "basic", scores: {penalty: false}, segment: true}], name: "a-b-c", plan: "premium", weight: 0}, tag: true, totals: {risk: "a-b-c"}}], + [{borrower: {weight: 1000, name: "O'Neil", plan: "plus", members: [{income: 0, plan: "trial", age: 5, amount: 1e3}, {income: 3, plan: "plus", age: 100, amount: 18}]}}, {borrower: {capped: "O'Neil", members: [{age: 5, amount: 1000, flags: {discount: {a: true, n: 1, ok: 5}}, income: 0, plan: "trial", scores: {penalty: true}, segment: true}, {age: 100, amount: 18, flags: {discount: {a: true, n: 1, ok: -90}}, income: 3, plan: "plus", scores: {penalty: true}, segment: true}], name: "O'Neil", plan: "plus", weight: 1000}, tag: true, totals: {risk: "O'Neil"}}], + [{borrower: {weight: 0, name: "a-b-c", plan: "basic", members: [{income: 0.5, plan: "plus", amount: 1e3}, {income: 0.5, plan: "basic", age: 1, amount: 65}, {income: 0, plan: "basic", age: null, amount: 250}]}}, {borrower: {capped: "a-b-c", members: [{amount: 1000, flags: {discount: {a: true, n: 1, ok: 15}}, income: 0.5, plan: "plus", scores: {penalty: false}, segment: true}, {age: 1, amount: 65, flags: {discount: {a: true, n: 1, ok: 14}}, income: 0.5, plan: "basic", scores: {penalty: false}, segment: true}, {age: null, amount: 250, flags: {discount: {a: false, n: 1, ok: 15}}, income: 0, plan: "basic", scores: {penalty: false}, segment: true}], name: "a-b-c", plan: "basic", weight: 0}, tag: true, totals: {risk: "a-b-c"}}], + [{borrower: {weight: 0, name: "A1", plan: "basic", members: [{income: -0, plan: "basic", age: 100, amount: 50}, {income: -1, plan: "basic", age: 3, amount: 7.25}, {income: 2, plan: "premium", age: 350, amount: 1000}]}}, {borrower: {capped: "A1", members: [{age: 100, amount: 50, flags: {discount: {a: false, n: 1, ok: -85}}, income: 0, plan: "basic", scores: {penalty: false}, segment: true}, {age: 3, amount: 7.25, flags: {discount: {a: true, n: 1, ok: 12}}, income: -1, plan: "basic", scores: {penalty: false}, segment: true}, {age: 350, amount: 1000, flags: {discount: {a: true, n: 1, ok: -335}}, income: 2, plan: "premium", scores: {penalty: false}, segment: true}], name: "A1", plan: "basic", weight: 0}, tag: true, totals: {risk: "A1"}}], + [{borrower: {weight: -500, name: "ok", plan: "basic", members: []}}, {borrower: {capped: "ok", members: [], name: "ok", plan: "basic", weight: -500}, tag: true, totals: {risk: "ok"}}], + [{borrower: {weight: 250, name: "gold", plan: "basic", members: [{income: 0, plan: "plus", age: 0, amount: -0}, {income: -1, plan: "basic", age: 250, amount: 3}]}}, {borrower: {capped: "gold", members: [{age: 0, amount: 0, flags: {discount: {a: true, n: 1, ok: 10}}, income: 0, plan: "plus", scores: {penalty: false}, segment: true}, {age: 250, amount: 3, flags: {discount: {a: true, n: 1, ok: -240}}, income: -1, plan: "basic", scores: {penalty: false}, segment: true}], name: "gold", plan: "basic", weight: 250}, tag: true, totals: {risk: "gold"}}], + [{borrower: {weight: 65, name: "Oslo", plan: "basic", members: [{income: 100, plan: "trial", age: 3, amount: -0}, {income: 5, plan: "basic", age: 1000, amount: 0.5}]}}, {borrower: {capped: "Oslo", members: [{age: 3, amount: 0, flags: {discount: {a: true, n: 1, ok: 7}}, income: 100, plan: "trial", scores: {penalty: false}, segment: true}, {age: 1000, amount: 0.5, flags: {discount: {a: true, n: 1, ok: -990}}, income: 5, plan: "basic", scores: {penalty: false}, segment: true}], name: "Oslo", plan: "basic", weight: 65}, tag: true, totals: {risk: "Oslo"}}], + [{borrower: {weight: 5, name: "A1", plan: "basic", members: [{income: -0.5, plan: "basic", age: 65, amount: -500}, {income: 50, plan: "premium", age: 0.000001, amount: 100}, {income: 1, plan: "basic", age: -1, amount: 100}]}}, {borrower: {capped: "A1", members: [{age: 65, amount: -500, flags: {discount: {a: true, n: 1, ok: -50}}, income: -0.5, plan: "basic", scores: {penalty: false}, segment: true}, {age: 0.000001, amount: 100, flags: {discount: {a: true, n: 1, ok: 14.999999}}, income: 50, plan: "premium", scores: {penalty: false}, segment: true}, {age: -1, amount: 100, flags: {discount: {a: true, n: 1, ok: 16}}, income: 1, plan: "basic", scores: {penalty: false}, segment: true}], name: "A1", plan: "basic", weight: 5}, tag: true, totals: {risk: "A1"}}], + [{borrower: {weight: 0.1, name: "ok", plan: "basic", members: []}}, {borrower: {capped: "ok", members: [], name: "ok", plan: "basic", weight: 0.1}, tag: true, totals: {risk: "ok"}}], + [{borrower: {weight: 18, name: "US", plan: "premium", members: [{income: 0.000001, plan: "plus", age: null, amount: 1000}, {income: 1, plan: "plus", age: 123456789.123, amount: 5}, {income: -1, plan: "plus", amount: 65}]}}, {borrower: {capped: "US", members: [{age: null, amount: 1000, flags: {discount: {a: true, n: 1, ok: 15}}, income: 0.000001, plan: "plus", scores: {penalty: false}, segment: true}, {age: 123456789.123, amount: 5, flags: {discount: {a: true, n: 1, ok: -123456774.123}}, income: 1, plan: "plus", scores: {penalty: false}, segment: true}, {amount: 65, flags: {discount: {a: true, n: 1, ok: 15}}, income: -1, plan: "plus", scores: {penalty: false}, segment: true}], name: "US", plan: "premium", weight: 18}, tag: true, totals: {risk: "US"}}], + [{borrower: {weight: 0, name: "-", plan: "plus", members: []}}, {borrower: {capped: "-", members: [], name: "-", plan: "plus", weight: 0}, tag: true, totals: {risk: "-"}}], + [{borrower: {weight: 100, name: "日本", plan: "basic", members: [{income: -500, plan: "basic", age: 0.5, amount: -500}, {income: 100, plan: "premium", age: 1e3, amount: 3}, {income: 0, plan: "trial", age: 0, amount: 0}, {income: 99999999999999999999, plan: "premium", age: 5, amount: 2.50}]}}, {borrower: {capped: "日本", members: [{age: 0.5, amount: -500, flags: {discount: {a: true, n: 1, ok: 19.5}}, income: -500, plan: "basic", scores: {penalty: false}, segment: true}, {age: 1000, amount: 3, flags: {discount: {a: false, n: 1, ok: -980}}, income: 100, plan: "premium", scores: {penalty: false}, segment: true}, {age: 0, amount: 0, flags: {discount: {a: true, n: 1, ok: 20}}, income: 0, plan: "trial", scores: {penalty: false}, segment: true}, {age: 5, amount: 2.50, flags: {discount: {a: true, n: 1, ok: 15}}, income: 99999999999999999999, plan: "premium", scores: {penalty: false}, segment: false}], name: "日本", plan: "basic", weight: 100}, tag: true, totals: {risk: "日本"}}], + [{borrower: {weight: 1000, name: "VIP", plan: "trial", members: [{income: 123456789.123, plan: "trial", age: null, amount: -0.5}, {income: 1000, plan: "basic", age: 1000, amount: -0.5}, {income: -0.01, plan: "plus", amount: 18}, {income: 0, plan: "trial", amount: 100}, {income: 99.99, plan: "premium", age: 65, amount: 2.50}, {income: 1000000, plan: "basic", age: null, amount: 100}, {income: -0.5, plan: "trial", amount: 1000}, {income: 2, plan: "premium", age: 99999999999999999999, amount: -0.01}, {income: 0.000001, plan: "premium", age: 1e3, amount: 0.5}, {income: 123456789.123, plan: "basic", age: 342, amount: 50}, {income: 1000, plan: "plus", age: null, amount: 1}, {income: 0.5, plan: "basic", amount: 250}, {income: 18, plan: "basic", age: null, amount: 18}, {income: -0.01, plan: "basic", amount: 1}]}}, {borrower: {capped: "VIP", members: [{age: null, amount: -0.5, flags: {discount: {a: true, n: 1, ok: 70}}, income: 123456789.123, plan: "trial", scores: {penalty: true}, segment: false}, {age: 1000, amount: -0.5, flags: {discount: {a: false, n: 1, ok: -930}}, income: 1000, plan: "basic", scores: {penalty: true}, segment: true}, {amount: 18, flags: {discount: {a: true, n: 1, ok: 70}}, income: -0.01, plan: "plus", scores: {penalty: true}, segment: true}, {amount: 100, flags: {discount: {a: true, n: 1, ok: 70}}, income: 0, plan: "trial", scores: {penalty: true}, segment: true}, {age: 65, amount: 2.50, flags: {discount: {a: true, n: 1, ok: 5}}, income: 99.99, plan: "premium", scores: {penalty: true}, segment: true}, {age: null, amount: 100, flags: {discount: {a: true, n: 1, ok: 70}}, income: 1000000, plan: "basic", scores: {penalty: true}, segment: true}, {amount: 1000, flags: {discount: {a: true, n: 1, ok: 70}}, income: -0.5, plan: "trial", scores: {penalty: true}, segment: true}, {age: 99999999999999999999, amount: -0.01, flags: {discount: {a: true, n: 1, ok: -99999999999999999929}}, income: 2, plan: "premium", scores: {penalty: true}, segment: true}, {age: 1000, amount: 0.5, flags: {discount: {a: true, n: 1, ok: -930}}, income: 0.000001, plan: "premium", scores: {penalty: true}, segment: true}, {age: 342, amount: 50, flags: {discount: {a: true, n: 1, ok: -272}}, income: 123456789.123, plan: "basic", scores: {penalty: true}, segment: true}, {age: null, amount: 1, flags: {discount: {a: false, n: 1, ok: 70}}, income: 1000, plan: "plus", scores: {penalty: true}, segment: true}, {amount: 250, flags: {discount: {a: true, n: 1, ok: 70}}, income: 0.5, plan: "basic", scores: {penalty: true}, segment: true}, {age: null, amount: 18, flags: {discount: {a: true, n: 1, ok: 70}}, income: 18, plan: "basic", scores: {penalty: true}, segment: true}, {amount: 1, flags: {discount: {a: true, n: 1, ok: 70}}, income: -0.01, plan: "basic", scores: {penalty: true}, segment: true}], name: "VIP", plan: "trial", weight: 1000}, tag: true, totals: {risk: "VIP"}}], + ], +} + +// seed 341500 (attempt 0) +{ + name: "b 16: account/lines + contact: 3 assertion, 5 expression, 2 match, 2 table; 5 root, 2 per-member, 0 top-level computed", + policy: { + models: {account: {balance: "number", label: "string", score: "number?", country: "string?", kind: "string(retail|corporate)", priority: "boolean", lines: "line[]", contact: "contactInfo?"}, line: {qty: "number", birthDate: "date"}, contactInfo: {limit: "number", amount: "number?", age: "number"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {assertion: "account.scores.quota", conditions: [["and", "(account.bonus or account.bonus)", 1]]}, + {expression: "account.flag", value: "number(string(len((account.country ?? ''))))"}, + {match: "line.meta.margin", arms: [["all(account.lines, #.qty < 2)", "(account.contact.age ?? 0)"], ["", "((account.contact.age ?? 0) + line.qty)"]]}, + {match: "contactInfo.calc.health", arms: [["number(string(account.balance)) != (contactInfo.review ?? 0)", "account.balance"], ["", "contactInfo.age"]]}, + {table: "t6", inputs: ["len(account.lines)"], outputs: ["contactInfo.total"], rules: [ + ["", ""], + ["< 3", "len(account.lines)"], + ["", "3"], + ["< 3", "(account.score ?? 0)"], + ["[10..486]", "len((account.country ?? ''))"], + ["", "contactInfo.calc.health"], + ]}, + {expression: "line.summary", value: "account.contact.calc.health == null"}, + {expression: "account.bonus", value: "all(account.lines, #.meta.margin < #.qty)"}, + {assertion: "contactInfo.eligible", conditions: [["and", "startsWith((account.priority ? account.label : (account.country ?? '')), 'gold')", 2], ["or", "isNumeric(`${account.scores.quota}/${account.priority}`)", 0], ["or", "account.score == null", 2], ["or", "isNumeric((account.country ?? ''))", 0]]}, + {expression: "account.rank", value: "-((max(map(account.lines, #.qty)) ?? 0))"}, + {assertion: "account.flags.net", conditions: [["and", "account.contact.fee != null", 2]]}, + {expression: "contactInfo.totals.adjusted", value: "{v: (account.country ?? ''), n: (contactInfo.review ?? 0), a: (account.country ?? '')}"}, + {table: "t1", inputs: ["account.label", "contactInfo.limit", "(account.score ?? 0)"], outputs: ["contactInfo.fee", "contactInfo.review"], rules: [ + ["startsWith($, 'US')", "> 18", "3", "0.25", "factor"], + ["$ != 'Oslo'", "<= 50", "!= 0", "number(string(factor))", ""], + ]}, + ], + }, + cases: [ + [{factor: 0, account: {balance: 3, label: null, score: 2, country: "-", kind: "retail", priority: false, lines: [{qty: 1, birthDate: "2025-03-20T10:15:30Z"}, {qty: 3, birthDate: "1990-06-15"}], contact: {limit: 1000, amount: 99999999999999999999, age: -0}}}, "!error: MissingRequiredInputs"], + [{factor: -2, account: {balance: 100, label: "é ü", score: 5, country: "a-b-c", kind: "corporate", priority: false, lines: [{qty: 0.1, birthDate: "2024-02-29"}, {qty: -500, birthDate: "2024-01-01"}, {qty: 1e3, birthDate: "2000-01-01"}, {qty: 0, birthDate: "2025-03-20T10:15:30Z"}], contact: {limit: 5, amount: 1e3, age: -500}}}, {account: {balance: 100, bonus: true, contact: {age: -500, amount: 1000, calc: {health: 100}, eligible: false, fee: -2, limit: 5, review: null, total: 3, totals: {adjusted: {a: "a-b-c", n: 0, v: "a-b-c"}}}, country: "a-b-c", flag: 5, flags: {net: true}, kind: "corporate", label: "é ü", lines: [{birthDate: "2024-02-29", meta: {margin: -499.9}, qty: 0.1, summary: false}, {birthDate: "2024-01-01", meta: {margin: -1000}, qty: -500, summary: false}, {birthDate: "2000-01-01", meta: {margin: 500}, qty: 1000, summary: false}, {birthDate: "2025-03-20T10:15:30Z", meta: {margin: -500}, qty: 0, summary: false}], priority: false, rank: -1000, score: 5, scores: {quota: true}}, factor: -2}], + [{factor: 100, account: {balance: 1, label: "gold", kind: "retail", priority: true, lines: [{qty: 18, birthDate: "2025-03-20T10:15:30Z"}, {qty: 0.25, birthDate: "2024-02-29"}, {qty: 18, birthDate: "2030-12-31"}], contact: {limit: 1, amount: null, age: 1}}}, {account: {balance: 1, bonus: false, contact: {age: 1, amount: null, calc: {health: 1}, eligible: true, fee: null, limit: 1, review: null, total: 3, totals: {adjusted: {a: "", n: 0, v: ""}}}, flag: 0, flags: {net: false}, kind: "retail", label: "gold", lines: [{birthDate: "2025-03-20T10:15:30Z", meta: {margin: 19}, qty: 18, summary: false}, {birthDate: "2024-02-29", meta: {margin: 1.25}, qty: 0.25, summary: false}, {birthDate: "2030-12-31", meta: {margin: 19}, qty: 18, summary: false}], priority: true, rank: -18, scores: {quota: false}}, factor: 100}], + [{factor: 10, account: {balance: 7.25, label: "A1", score: 0.5, country: "Zed", kind: "corporate", priority: false, lines: [{qty: 3, birthDate: "2000-01-01"}, {qty: 0, birthDate: "2025-03-20T10:15:30Z"}, {qty: 3, birthDate: "2025-03-20"}, {qty: 3, birthDate: "2025-03-20"}], contact: {limit: -0.5, amount: 100, age: -0.01}}}, {account: {balance: 7.25, bonus: true, contact: {age: -0.01, amount: 100, calc: {health: 7.25}, eligible: false, fee: 10, limit: -0.5, review: null, total: 3, totals: {adjusted: {a: "Zed", n: 0, v: "Zed"}}}, country: "Zed", flag: 3, flags: {net: true}, kind: "corporate", label: "A1", lines: [{birthDate: "2000-01-01", meta: {margin: 2.99}, qty: 3, summary: false}, {birthDate: "2025-03-20T10:15:30Z", meta: {margin: -0.01}, qty: 0, summary: false}, {birthDate: "2025-03-20", meta: {margin: 2.99}, qty: 3, summary: false}, {birthDate: "2025-03-20", meta: {margin: 2.99}, qty: 3, summary: false}], priority: false, rank: -3, score: 0.5, scores: {quota: true}}, factor: 10}], + [{factor: 10, account: {balance: 0.1, label: "Oslo", score: -0, country: "12", kind: "retail", priority: false, lines: [{qty: 1000, birthDate: "2030-12-31"}, {qty: 3, birthDate: "2000-01-01"}, {qty: 5, birthDate: "2024-01-01"}, {qty: 0, birthDate: "2024-01-01"}, {qty: 0.5, birthDate: "2025-03-20T10:15:30Z"}, {qty: -0, birthDate: "1990-06-15"}, {qty: 5, birthDate: "2024-01-01"}, {qty: -1, birthDate: "2025-03-20"}, {qty: 5, birthDate: "2030-12-31"}, {qty: 7.25, birthDate: "2024-01-01"}, {qty: 2, birthDate: "2024-01-01"}], contact: null}}, {account: {balance: 0.1, bonus: false, contact: null, country: "12", flag: 2, flags: {net: false}, kind: "retail", label: "Oslo", lines: [{birthDate: "2030-12-31", meta: {margin: 1000}, qty: 1000, summary: true}, {birthDate: "2000-01-01", meta: {margin: 3}, qty: 3, summary: true}, {birthDate: "2024-01-01", meta: {margin: 5}, qty: 5, summary: true}, {birthDate: "2024-01-01", meta: {margin: 0}, qty: 0, summary: true}, {birthDate: "2025-03-20T10:15:30Z", meta: {margin: 0.5}, qty: 0.5, summary: true}, {birthDate: "1990-06-15", meta: {margin: 0}, qty: 0, summary: true}, {birthDate: "2024-01-01", meta: {margin: 5}, qty: 5, summary: true}, {birthDate: "2025-03-20", meta: {margin: -1}, qty: -1, summary: true}, {birthDate: "2030-12-31", meta: {margin: 5}, qty: 5, summary: true}, {birthDate: "2024-01-01", meta: {margin: 7.25}, qty: 7.25, summary: true}, {birthDate: "2024-01-01", meta: {margin: 2}, qty: 2, summary: true}], priority: false, rank: -1000, score: 0, scores: {quota: false}}, factor: 10}], + [{factor: 100, account: {balance: 10, label: "", score: 18, country: "é ü", kind: "retail", priority: true, lines: [{qty: 18, birthDate: "2025-03-20T10:15:30Z"}], contact: {limit: -0.5, amount: 250, age: -0.01}}}, {account: {balance: 10, bonus: true, contact: {age: -0.01, amount: 250, calc: {health: 10}, eligible: false, fee: 100, limit: -0.5, review: null, total: 1, totals: {adjusted: {a: "é ü", n: 0, v: "é ü"}}}, country: "é ü", flag: 5, flags: {net: true}, kind: "retail", label: "", lines: [{birthDate: "2025-03-20T10:15:30Z", meta: {margin: 17.99}, qty: 18, summary: false}], priority: true, rank: -18, score: 18, scores: {quota: true}}, factor: 100}], + [{factor: 10, account: {balance: 123456789.123, label: "retail", score: 1, country: null, kind: "retail", priority: false, lines: [{qty: 50, birthDate: "2024-01-01"}, {qty: 2.50, birthDate: "2000-01-01"}, {qty: 3, birthDate: "2030-12-31"}], contact: null}}, {account: {balance: 123456789.123, bonus: false, contact: null, country: null, flag: 0, flags: {net: false}, kind: "retail", label: "retail", lines: [{birthDate: "2024-01-01", meta: {margin: 50}, qty: 50, summary: true}, {birthDate: "2000-01-01", meta: {margin: 2.50}, qty: 2.50, summary: true}, {birthDate: "2030-12-31", meta: {margin: 3}, qty: 3, summary: true}], priority: false, rank: -50, score: 1, scores: {quota: false}}, factor: 10}], + [{factor: 1, account: {balance: 311, label: "A1", score: 2, country: "NL", kind: "retail", priority: false, lines: [{qty: 1, birthDate: "2024-01-01"}, {qty: 18, birthDate: "1990-06-15"}, {qty: 0.25, birthDate: "2024-01-01"}, {qty: 1, birthDate: "2025-03-20T10:15:30Z"}, {qty: 2, birthDate: "2025-03-20T10:15:30Z"}], contact: {limit: 5, amount: 1000, age: 10}}}, {account: {balance: 311, bonus: false, contact: {age: 10, amount: 1000, calc: {health: 311}, eligible: false, fee: 1, limit: 5, review: null, total: 3, totals: {adjusted: {a: "NL", n: 0, v: "NL"}}}, country: "NL", flag: 2, flags: {net: true}, kind: "retail", label: "A1", lines: [{birthDate: "2024-01-01", meta: {margin: 11}, qty: 1, summary: false}, {birthDate: "1990-06-15", meta: {margin: 28}, qty: 18, summary: false}, {birthDate: "2024-01-01", meta: {margin: 10.25}, qty: 0.25, summary: false}, {birthDate: "2025-03-20T10:15:30Z", meta: {margin: 11}, qty: 1, summary: false}, {birthDate: "2025-03-20T10:15:30Z", meta: {margin: 12}, qty: 2, summary: false}], priority: false, rank: -18, score: 2, scores: {quota: false}}, factor: 1}], + [{factor: 10, account: {balance: 3, label: "O'Neil", kind: "corporate", priority: false, lines: [{qty: 5, birthDate: "2024-02-29"}], contact: null}}, {account: {balance: 3, bonus: false, contact: null, flag: 0, flags: {net: false}, kind: "corporate", label: "O'Neil", lines: [{birthDate: "2024-02-29", meta: {margin: 5}, qty: 5, summary: true}], priority: false, rank: -5, scores: {quota: false}}, factor: 10}], + [{factor: -2, account: {balance: 5, label: "DE", kind: "retail", priority: false, lines: [{qty: 0, birthDate: "2025-03-20T10:15:30Z"}, {qty: 1e3, birthDate: "2024-02-29"}, {qty: 10, birthDate: "1990-06-15"}, {qty: 308, birthDate: "2000-01-01"}, {qty: 250, birthDate: "2024-02-29"}]}}, {account: {balance: 5, bonus: false, flag: 0, flags: {net: false}, kind: "retail", label: "DE", lines: [{birthDate: "2025-03-20T10:15:30Z", meta: {margin: 0}, qty: 0, summary: true}, {birthDate: "2024-02-29", meta: {margin: 1000}, qty: 1000, summary: true}, {birthDate: "1990-06-15", meta: {margin: 10}, qty: 10, summary: true}, {birthDate: "2000-01-01", meta: {margin: 308}, qty: 308, summary: true}, {birthDate: "2024-02-29", meta: {margin: 250}, qty: 250, summary: true}], priority: false, rank: -1000, scores: {quota: false}}, factor: -2}], + [{factor: 0, account: {balance: 7.25, label: "VIP", score: null, country: null, kind: "retail", priority: true, lines: [{qty: 100, birthDate: "2030-12-31"}, {qty: 0.5, birthDate: "2030-12-31"}], contact: {limit: 2.50, amount: 100, age: 0}}}, {account: {balance: 7.25, bonus: false, contact: {age: 0, amount: 100, calc: {health: 7.25}, eligible: true, fee: null, limit: 2.50, review: null, total: 2, totals: {adjusted: {a: "", n: 0, v: ""}}}, country: null, flag: 0, flags: {net: false}, kind: "retail", label: "VIP", lines: [{birthDate: "2030-12-31", meta: {margin: 100}, qty: 100, summary: false}, {birthDate: "2030-12-31", meta: {margin: 0.5}, qty: 0.5, summary: false}], priority: true, rank: -100, score: null, scores: {quota: false}}, factor: 0}], + [{factor: 10, account: {balance: 3, label: "O'Neil", score: null, country: null, kind: "corporate", priority: true, lines: [{qty: 50, birthDate: "2025-03-20T10:15:30Z"}], contact: {limit: 100, age: 10}}}, {account: {balance: 3, bonus: false, contact: {age: 10, calc: {health: 3}, eligible: true, fee: null, limit: 100, review: null, total: 1, totals: {adjusted: {a: "", n: 0, v: ""}}}, country: null, flag: 0, flags: {net: false}, kind: "corporate", label: "O'Neil", lines: [{birthDate: "2025-03-20T10:15:30Z", meta: {margin: 60}, qty: 50, summary: false}], priority: true, rank: -50, score: null, scores: {quota: false}}, factor: 10}], + ], +} + +// seed 341600 (attempt 0) +{ + name: "b 17: claim/members + report: 1 assertion, 3 expression, 2 match, 5 table; 6 root, 5 per-member, 3 top-level computed", + policy: { + models: {claim: {age: "number?", rate: "number?", amount: "number", members: "member[]", report: "creditReport?"}, member: {price: "number", vip: "boolean"}, creditReport: {rate: "number", balance: "number", tier: "string(gold|silver|bronze)"}}, + blocks: [ + {table: "t11", inputs: [null, null, "-((claim.rate ?? 0))"], outputs: ["creditReport.total", "creditReport.penalty", "creditReport.fee"], rules: [ + ["(claim.rate ?? 0) <= 1.5", "claim.age != null", "!= 2", "(bonus ?? false)", "(claim.meta.level ?? false)", ""], + ["not ((claim.meta.level ?? false))", "", "", "all(claim.members, not (#.eligible))", "bonus != null", "1"], + ["(quota ?? '') in ['a', 'low']", "claim.amount == claim.margin.n", "", "(bonus ?? false)", "", ""], + ["creditReport.rate in (36..199]", "(claim.rate ?? 0) == creditReport.rate", "[2..334]", "(claim.meta.level ?? false)", "(claim.meta.level ?? false)", "(claim.age ?? 0)"], + ["", "creditReport.flags.tag.n <= (claim.rate ?? 0)", "", "", "((claim.meta.level ?? false) or (bonus ?? false))", "creditReport.balance"], + ["claim.margin.ok > claim.margin.n", "creditReport.rate >= creditReport.rate", "!= 18", "(claim.meta.level ?? false)", "", "claim.amount"], + ["0.5 >= claim.margin.ok", "creditReport.tier != 'bronze'", "> 5", "(bonus ?? false)", "((claim.meta.level ?? false) or (bonus ?? false))", "(claim.age ?? 0)"], + ]}, + {match: "member.decision", arms: [["trunc(claim.amount) != claim.amount", "contains(['Oslo', 'gold', ''], (quota ?? ''))"], ["", "(bonus ?? false)"]]}, + {assertion: "member.eligible", conditions: ["claim.age == null"]}, + {table: "t4", inputs: ["claim.age", "(claim.report.tier ?? '')", "claim.report.tier"], outputs: ["claim.meta.level", "claim.surcharge"], rules: [ + ["", "'silver', 'bronze'", "", "(claim.report.balance ?? 0) == 0.5", "number(string((claim.age ?? 0)))"], + ["1, 10", "", "", "", "min([(claim.rate ?? 0), 1.5])"], + ["", "", "", "0.25 <= 5", "-((claim.report.balance ?? 0))"], + ]}, + {expression: "claim.margin", value: "{n: len(filter(claim.members, (#.eligible or #.vip))), a: (claim.surcharge ?? 0), ok: round(((claim.age ?? 0) % (abs(1.5) + 1)), 2)}"}, + {expression: "creditReport.flags.tag", value: "{n: len(filter(claim.members, #.price in [47..172]))}"}, + {table: "t5", inputs: ["(claim.report.tier ?? '')"], outputs: ["quota", "bonus"], rules: [ + ["'silver'", "'DE'", "(claim.meta.level ?? false)"], + ["'silver'", "string((claim.report.balance ?? 0))", "((claim.meta.level ?? false) or (claim.meta.level ?? false))"], + ["", "'VIP'", "(claim.meta.level ?? false)"], + ]}, + {match: "member.adjusted", arms: [["isNumeric((quota ?? ''))", "((member.bucket ?? 0) / -6)"], ["claim.report.flags.tag.n == null", "len((quota ?? ''))"], ["not ((claim.report.tier ?? '') == 'bronze')", "claim.margin.a"], ["", "claim.margin.ok"]]}, + {table: "t2", inputs: ["member.vip", "member.vip"], outputs: ["member.bucket"], rules: [ + ["false", "false", ""], + ["false", "true", "min([1000, (claim.report.balance ?? 0), member.summary])"], + ["false", "true", "member.price"], + ["", "true", "2"], + ["", "", "2"], + ]}, + {expression: "member.summary", value: "trunc((max([(claim.rate ?? 0)]) % (abs(median([(claim.rate ?? 0), claim.amount, 1])) + 1)))"}, + {table: "t6", inputs: ["(claim.age ?? 0)", "(claim.meta.level ?? false)", "claim.report.rate"], outputs: ["exposure"], rules: [ + ["<= 0", "false", "", "'retail'"], + ["> 100", "true", "", "`${(claim.meta.level ?? false)}/${(claim.age ?? 0)}`"], + ["", "true", "1.5", "(quota ?? '')"], + ["<= 18", "true", "0.5, 3", "(quota ?? '')"], + [">= 0.25", "true", "50", "'A1'"], + ]}, + ], + }, + cases: [ + [{claim: {age: 0.5, rate: 1000000, amount: 0.25, members: [], report: {rate: 10, balance: 0.5, tier: "silver"}}}, {bonus: true, claim: {age: 0.5, amount: 0.25, margin: {a: 0.5, n: 0, ok: 0.5}, members: [], meta: {level: true}, rate: 1000000, report: {balance: 0.5, fee: 0.5, flags: {tag: {n: 0}}, penalty: true, rate: 10, tier: "silver", total: true}, surcharge: 0.5}, exposure: null, quota: "DE"}], + [{claim: {age: 1000, amount: 1000, members: [{price: 100, vip: false}], report: {rate: 0.25, balance: -0.01, tier: "gold"}}}, {bonus: true, claim: {age: 1000, amount: 1000, margin: {a: 0.01, n: 0, ok: 0.0}, members: [{adjusted: 0.01, decision: true, eligible: false, price: 100, vip: false}], meta: {level: true}, report: {balance: -0.01, fee: null, flags: {tag: {n: 1}}, penalty: true, rate: 0.25, tier: "gold", total: true}, surcharge: 0.01}, exposure: "true/1000", quota: "VIP"}], + [{claim: {age: 0.25, rate: 0, amount: 3, members: [{price: 0.5, vip: true}, {price: 1, vip: false}], report: {rate: 18, balance: 2, tier: "gold"}}}, {bonus: true, claim: {age: 0.25, amount: 3, margin: {a: -2, n: 1, ok: 0.25}, members: [{adjusted: -2, decision: true, eligible: false, price: 0.5, vip: true}, {adjusted: -2, decision: true, eligible: false, price: 1, vip: false}], meta: {level: true}, rate: 0, report: {balance: 2, fee: 2, flags: {tag: {n: 0}}, penalty: true, rate: 18, tier: "gold", total: true}, surcharge: -2}, exposure: null, quota: "VIP"}], + [{claim: {age: 5, rate: 2, amount: true, members: [], report: {rate: 10, balance: 1, tier: "gold"}}}, "!error: InputValidationFailed"], + [{claim: {age: 152, rate: 0.25, amount: 123456789.123, members: [], report: {rate: 18, balance: 3, tier: "bronze"}}}, {bonus: false, claim: {age: 152, amount: 123456789.123, margin: {a: 152, n: 0, ok: 2.0}, members: [], meta: {level: false}, rate: 0.25, report: {balance: 3, fee: 1, flags: {tag: {n: 0}}, penalty: false, rate: 18, tier: "bronze", total: false}, surcharge: 152}, exposure: null, quota: "VIP"}], + [{claim: {age: 1, rate: 0.5, amount: 3, members: [{price: null, vip: true}], report: {rate: 250, balance: 5, tier: "silver"}}}, "!error: ExpressionFailed"], + [{claim: {age: 0.000001, rate: 1, amount: -1, members: [], report: {rate: 0.25, balance: 250, tier: "gold"}}}, {bonus: true, claim: {age: 0.000001, amount: -1, margin: {a: -250, n: 0, ok: 0.00}, members: [], meta: {level: true}, rate: 1, report: {balance: 250, fee: 250, flags: {tag: {n: 0}}, penalty: true, rate: 0.25, tier: "gold", total: true}, surcharge: -250}, exposure: null, quota: "VIP"}], + [{claim: {age: -0, rate: 481, amount: 0.25, members: [], report: {rate: 1.5, balance: 18, tier: "bronze"}}}, {bonus: false, claim: {age: 0, amount: 0.25, margin: {a: 0, n: 0, ok: 0}, members: [], meta: {level: false}, rate: 481, report: {balance: 18, fee: 1, flags: {tag: {n: 0}}, penalty: true, rate: 1.5, tier: "bronze", total: true}, surcharge: 0}, exposure: "retail", quota: "VIP"}], + [{claim: {age: null, amount: 18, members: [{price: 18, vip: true}], report: {rate: 1, balance: 0.1, tier: "gold"}}}, {bonus: true, claim: {age: null, amount: 18, margin: {a: -0.1, n: 1, ok: 0}, members: [{adjusted: -0.1, decision: true, eligible: true, price: 18, vip: true}], meta: {level: true}, report: {balance: 0.1, fee: 0.1, flags: {tag: {n: 0}}, penalty: true, rate: 1, tier: "gold", total: null}, surcharge: -0.1}, exposure: null, quota: "VIP"}], + [{claim: {age: 1, rate: 99999999999999999999, amount: 0, members: [{price: 0.25, vip: true}, {price: -500, vip: true}, {price: 95, vip: true}], report: null}}, {bonus: true, claim: {age: 1, amount: 0, margin: {a: 1.5, n: 3, ok: 1}, members: [{adjusted: 3, decision: true, eligible: false, price: 0.25, vip: true}, {adjusted: 3, decision: true, eligible: false, price: -500, vip: true}, {adjusted: 3, decision: true, eligible: false, price: 95, vip: true}], meta: {level: true}, rate: 99999999999999999999, report: null, surcharge: 1.5}, exposure: null, quota: "VIP"}], + [{claim: {age: 0.5, rate: 10, amount: 0.5, members: [{price: 1, vip: false}], report: null}}, {bonus: true, claim: {age: 0.5, amount: 0.5, margin: {a: -0, n: 0, ok: 0.5}, members: [{adjusted: 3, decision: false, eligible: false, price: 1, vip: false}], meta: {level: true}, rate: 10, report: null, surcharge: -0}, exposure: null, quota: "VIP"}], + [{claim: {age: 3, rate: 250, amount: 1000, members: [{price: 3, vip: false}, {price: 0, vip: false}], report: {rate: 1.5, balance: 0.25, tier: "bronze"}, extraField: 1}}, {bonus: false, claim: {age: 3, amount: 1000, extraField: 1, margin: {a: 3, n: 0, ok: 0.5}, members: [{adjusted: 0.5, decision: false, eligible: false, price: 3, vip: false}, {adjusted: 0.5, decision: false, eligible: false, price: 0, vip: false}], meta: {level: false}, rate: 250, report: {balance: 0.25, fee: 1, flags: {tag: {n: 0}}, penalty: true, rate: 1.5, tier: "bronze", total: true}, surcharge: 3}, exposure: null, quota: "VIP"}], + [{claim: {age: 65, rate: 1, amount: 0.25, members: [{price: 1, vip: false}, {price: 7.25, vip: false}, {price: 10, vip: true}, {price: -0.01, vip: false}], report: {rate: 5, balance: 3, tier: "gold"}}}, {bonus: true, claim: {age: 65, amount: 0.25, margin: {a: -3, n: 1, ok: 0.0}, members: [{adjusted: -3, decision: false, eligible: false, price: 1, vip: false}, {adjusted: -3, decision: false, eligible: false, price: 7.25, vip: false}, {adjusted: -3, decision: false, eligible: false, price: 10, vip: true}, {adjusted: -3, decision: false, eligible: false, price: -0.01, vip: false}], meta: {level: true}, rate: 1, report: {balance: 3, fee: 3, flags: {tag: {n: 0}}, penalty: true, rate: 5, tier: "gold", total: true}, surcharge: -3}, exposure: null, quota: "VIP"}], + ], +} + +// seed 341700 (attempt 0) +{ + name: "b 18: account/members/payments: 2 expression, 1 match, 2 table; 2 root, 3 per-member, 1 top-level computed", + policy: { + models: {account: {income: "number", flagged: "boolean?", limit: "number", weight: "number?", price: "number?", kind: "string(retail|corporate)", members: "member[]"}, member: {qty: "number", channel: "string", code: "string", since: "date", payments: "payment[]"}, payment: {rate: "number"}}, + blocks: [ + {match: "account.tag", arms: [["account.kind != 'retail'", "min([account.limit, account.income])"], ["trunc(account.income) >= (account.weight ?? 0)", "account.income"], ["", "((account.price ?? 0) + 0)"]]}, + {expression: "member.totals.share", value: "map(member.payments, #.rate)"}, + {expression: "account.weighted", value: "filter(account.members, not (#.qty <= 1))"}, + {table: "t4", inputs: [null, "sum(map(account.weighted, #.qty))", "member.code"], outputs: ["member.margin", "member.decision"], rules: [ + ["account.price != null", "!= 1", "startsWith($, 'low')", "50", ""], + ["member.qty != account.limit", "[18..273]", "'a', 'gold'", "(account.weight ?? 0)", "account.tag"], + ["", "> 250", "'gold'", "len(account.weighted)", "50"], + ["account.weight == null", "", "startsWith($, 'a')", "account.income", "len(filter(member.payments, #.rate in [16..66]))"], + ["member.qty > (account.price ?? 0)", ">= 1.5", "'Oslo'", "(account.income % (abs(3) + 1))", "account.tag"], + ["account.tag != (account.price ?? 0)", "> 2", "startsWith($, 'DE')", "((account.price ?? 0) * (account.weight ?? 0))", "(avg(map(member.payments, #.rate)) ?? 0)"], + ]}, + {table: "t5", inputs: ["account.tag", "account.tag"], outputs: ["net"], rules: [ + ["> 3", "", "account.limit"], + ["100", ">= 3", "(100) / (abs(account.tag) + 1)"], + ["", "< 0.5", "account.income"], + ["<= 18", "<= 0.25", "max([(account.price ?? 0), account.limit])"], + [">= 2", "<= 100", ""], + ["", "", "account.limit"], + ]}, + ], + }, + cases: [ + [{account: {income: -0.01, limit: 1000000, weight: -500, price: null, kind: "retail", members: [{qty: 0, channel: "NL", code: "DE", since: "2025-03-20", payments: [{rate: 2}, {rate: 1.5}]}, {qty: 1, channel: "gold", code: "NL", since: "2025-03-20", payments: [{rate: 18}]}, {qty: 100, channel: "NL", code: "DE", since: "2030-12-31", payments: [{rate: 2}, {rate: 1}, {rate: 65}]}]}}, {account: {income: -0.01, kind: "retail", limit: 1000000, members: [{channel: "NL", code: "DE", decision: 1.750, margin: 0, payments: [{rate: 2}, {rate: 1.5}], qty: 0, since: "2025-03-20", totals: {share: [2, 1.5]}}, {channel: "gold", code: "NL", decision: null, margin: null, payments: [{rate: 18}], qty: 1, since: "2025-03-20", totals: {share: [18]}}, {channel: "NL", code: "DE", decision: 22.666666666666666666666666667, margin: 0, payments: [{rate: 2}, {rate: 1}, {rate: 65}], qty: 100, since: "2030-12-31", totals: {share: [2, 1, 65]}}], price: null, tag: -0.01, weight: -500, weighted: [{channel: "NL", code: "DE", decision: 22.666666666666666666666666667, margin: 0, payments: [{rate: 2}, {rate: 1}, {rate: 65}], qty: 100, since: "2030-12-31", totals: {share: [2, 1, 65]}}]}, net: -0.01}], + [{account: {income: 0.25, flagged: true, limit: 123456789.123, weight: 1, price: null, kind: "retail", members: [{qty: 100, channel: "a", code: "O'Neil", since: "2000-01-01", payments: []}, {qty: 99999999999999999999, channel: "a", code: "gold", since: "2024-01-01", payments: []}, {qty: 50, channel: "high", code: "O'Neil", since: "2024-01-01", payments: [{rate: 250}, {rate: 18}]}]}}, {account: {flagged: true, income: 0.25, kind: "retail", limit: 123456789.123, members: [{channel: "a", code: "O'Neil", decision: null, margin: null, payments: [], qty: 100, since: "2000-01-01", totals: {share: []}}, {channel: "a", code: "gold", decision: 50, margin: 3, payments: [], qty: 99999999999999999999, since: "2024-01-01", totals: {share: []}}, {channel: "high", code: "O'Neil", decision: null, margin: null, payments: [{rate: 250}, {rate: 18}], qty: 50, since: "2024-01-01", totals: {share: [250, 18]}}], price: null, tag: 0, weight: 1, weighted: [{channel: "a", code: "O'Neil", decision: null, margin: null, payments: [], qty: 100, since: "2000-01-01", totals: {share: []}}, {channel: "a", code: "gold", decision: 50, margin: 3, payments: [], qty: 99999999999999999999, since: "2024-01-01", totals: {share: []}}, {channel: "high", code: "O'Neil", decision: null, margin: null, payments: [{rate: 250}, {rate: 18}], qty: 50, since: "2024-01-01", totals: {share: [250, 18]}}]}, net: 0.25}], + [{account: {income: -500, flagged: false, limit: 3, price: 99999999999999999999, kind: "retail", members: [{qty: 5, channel: "ok", code: "US", since: "1990-06-15", payments: [{rate: 123456789.123}, {rate: 250}]}, {qty: 100, channel: "DE", code: "A1", since: "2024-02-29", payments: []}, {qty: 2, channel: "x", code: "US", since: "2000-01-01", payments: []}, {qty: -0, channel: "high", code: " pad ", since: "2024-02-29", payments: []}, {qty: -0, channel: "gold", code: "a", since: "1990-06-15", payments: [{rate: 0.5}]}]}}, {account: {flagged: false, income: -500, kind: "retail", limit: 3, members: [{channel: "ok", code: "US", decision: null, margin: null, payments: [{rate: 123456789.123}, {rate: 250}], qty: 5, since: "1990-06-15", totals: {share: [123456789.123, 250]}}, {channel: "DE", code: "A1", decision: null, margin: null, payments: [], qty: 100, since: "2024-02-29", totals: {share: []}}, {channel: "x", code: "US", decision: null, margin: null, payments: [], qty: 2, since: "2000-01-01", totals: {share: []}}, {channel: "high", code: " pad ", decision: null, margin: null, payments: [], qty: 0, since: "2024-02-29", totals: {share: []}}, {channel: "gold", code: "a", decision: 99999999999999999999, margin: 0, payments: [{rate: 0.5}], qty: 0, since: "1990-06-15", totals: {share: [0.5]}}], price: 99999999999999999999, tag: 99999999999999999999, weighted: [{channel: "ok", code: "US", decision: null, margin: null, payments: [{rate: 123456789.123}, {rate: 250}], qty: 5, since: "1990-06-15", totals: {share: [123456789.123, 250]}}, {channel: "DE", code: "A1", decision: null, margin: null, payments: [], qty: 100, since: "2024-02-29", totals: {share: []}}, {channel: "x", code: "US", decision: null, margin: null, payments: [], qty: 2, since: "2000-01-01", totals: {share: []}}]}, net: 3}], + [{account: {income: 100, limit: 0.5, weight: 1000, kind: "retail", members: [{qty: 100, channel: "gold", code: "3.5", since: "2025-03-20T10:15:30Z", payments: [{rate: 100}, {rate: 0}]}, {qty: 3, channel: "low", code: "x", since: "2025-03-20T10:15:30Z", payments: []}]}}, {account: {income: 100, kind: "retail", limit: 0.5, members: [{channel: "gold", code: "3.5", decision: null, margin: null, payments: [{rate: 100}, {rate: 0}], qty: 100, since: "2025-03-20T10:15:30Z", totals: {share: [100, 0]}}, {channel: "low", code: "x", decision: null, margin: null, payments: [], qty: 3, since: "2025-03-20T10:15:30Z", totals: {share: []}}], tag: 0, weight: 1000, weighted: [{channel: "gold", code: "3.5", decision: null, margin: null, payments: [{rate: 100}, {rate: 0}], qty: 100, since: "2025-03-20T10:15:30Z", totals: {share: [100, 0]}}, {channel: "low", code: "x", decision: null, margin: null, payments: [], qty: 3, since: "2025-03-20T10:15:30Z", totals: {share: []}}]}, net: 100}], + [{account: {income: 3, flagged: true, limit: 2, price: 3, kind: "retail", members: [{qty: 100, channel: "high", code: "DE", since: "1990-06-15", payments: [{rate: 1e3}, {rate: 107}]}, {qty: 100, channel: "Zed", code: "Zed", since: "1990-06-15", payments: [{rate: -0.5}]}, {qty: 2, channel: "-", code: "é ü", since: "2024-02-29", payments: [{rate: 0.5}]}, {qty: 1000, channel: "ok", code: "a", since: "1990-06-15", payments: []}]}}, {account: {flagged: true, income: 3, kind: "retail", limit: 2, members: [{channel: "high", code: "DE", decision: null, margin: null, payments: [{rate: 1000}, {rate: 107}], qty: 100, since: "1990-06-15", totals: {share: [1000, 107]}}, {channel: "Zed", code: "Zed", decision: null, margin: null, payments: [{rate: -0.5}], qty: 100, since: "1990-06-15", totals: {share: [-0.5]}}, {channel: "-", code: "é ü", decision: null, margin: null, payments: [{rate: 0.5}], qty: 2, since: "2024-02-29", totals: {share: [0.5]}}, {channel: "ok", code: "a", decision: 0, margin: 3, payments: [], qty: 1000, since: "1990-06-15", totals: {share: []}}], price: 3, tag: 3, weighted: [{channel: "high", code: "DE", decision: null, margin: null, payments: [{rate: 1000}, {rate: 107}], qty: 100, since: "1990-06-15", totals: {share: [1000, 107]}}, {channel: "Zed", code: "Zed", decision: null, margin: null, payments: [{rate: -0.5}], qty: 100, since: "1990-06-15", totals: {share: [-0.5]}}, {channel: "-", code: "é ü", decision: null, margin: null, payments: [{rate: 0.5}], qty: 2, since: "2024-02-29", totals: {share: [0.5]}}, {channel: "ok", code: "a", decision: 0, margin: 3, payments: [], qty: 1000, since: "1990-06-15", totals: {share: []}}]}, net: 2}], + [{account: {income: 0.1, flagged: false, limit: 0.5, weight: 1000, price: 0, members: [{qty: 104, channel: "12", code: "Oslo", since: "2025-03-20T10:15:30Z", payments: [{rate: 100}, {rate: 100}]}, {qty: -1, channel: "US", code: "Oslo", since: "2025-03-20T10:15:30Z", payments: []}]}}, "!error: MissingRequiredInputs"], + [{account: {income: 1.5, flagged: true, limit: 5, weight: 0.5, price: null, kind: "corporate", members: [{qty: 5, channel: "é ü", code: "DE", since: "2030-12-31", payments: [{rate: 0}, {rate: 99999999999999999999}]}]}}, {account: {flagged: true, income: 1.5, kind: "corporate", limit: 5, members: [{channel: "é ü", code: "DE", decision: 49999999999999999999.50, margin: 0, payments: [{rate: 0}, {rate: 99999999999999999999}], qty: 5, since: "2030-12-31", totals: {share: [0, 99999999999999999999]}}], price: null, tag: 1.5, weight: 0.5, weighted: [{channel: "é ü", code: "DE", decision: 49999999999999999999.50, margin: 0, payments: [{rate: 0}, {rate: 99999999999999999999}], qty: 5, since: "2030-12-31", totals: {share: [0, 99999999999999999999]}}]}, net: 5}], + [{account: {income: 2.50, flagged: null, limit: -500, weight: 50, kind: "corporate", members: [{qty: 0.25, channel: "x-y", code: "A1", since: "2024-01-01", payments: [{rate: 2.50}]}, {qty: 1000, channel: "gold", code: "gold", since: "2030-12-31", payments: [{rate: 3}]}]}}, {account: {flagged: null, income: 2.50, kind: "corporate", limit: -500, members: [{channel: "x-y", code: "A1", decision: null, margin: null, payments: [{rate: 2.50}], qty: 0.25, since: "2024-01-01", totals: {share: [2.50]}}, {channel: "gold", code: "gold", decision: 50, margin: 1, payments: [{rate: 3}], qty: 1000, since: "2030-12-31", totals: {share: [3]}}], tag: -500, weight: 50, weighted: [{channel: "gold", code: "gold", decision: 50, margin: 1, payments: [{rate: 3}], qty: 1000, since: "2030-12-31", totals: {share: [3]}}]}, net: 2.50}], + [{account: {income: 0.25, flagged: false, limit: 10, weight: 2.50, price: 18, kind: "retail", members: [{qty: 100, channel: "Zed", code: "US", since: "2024-02-29", payments: [{rate: 1000}, {rate: 100}]}, {qty: 0, channel: "US", code: "gold", since: "2025-03-20T10:15:30Z", payments: []}]}}, {account: {flagged: false, income: 0.25, kind: "retail", limit: 10, members: [{channel: "Zed", code: "US", decision: null, margin: null, payments: [{rate: 1000}, {rate: 100}], qty: 100, since: "2024-02-29", totals: {share: [1000, 100]}}, {channel: "US", code: "gold", decision: 18, margin: 2.50, payments: [], qty: 0, since: "2025-03-20T10:15:30Z", totals: {share: []}}], price: 18, tag: 18, weight: 2.50, weighted: [{channel: "Zed", code: "US", decision: null, margin: null, payments: [{rate: 1000}, {rate: 100}], qty: 100, since: "2024-02-29", totals: {share: [1000, 100]}}]}, net: 10}], + [{account: {income: 100, flagged: null, limit: 2.50, weight: null, price: -0.5, kind: "retail", members: [{qty: -0.5, channel: "O'Neil", code: "high", since: "2000-01-01", payments: []}, {qty: 250, channel: "12", code: "NL", since: "2025-03-20T10:15:30Z", payments: []}, {qty: 1, channel: "A1", code: "DE", since: "2024-02-29", payments: [{rate: 0}, {rate: 358}, {rate: 2}]}, {qty: 5, channel: "US", code: "3.5", since: "2025-03-20", payments: []}]}}, {account: {flagged: null, income: 100, kind: "retail", limit: 2.50, members: [{channel: "O'Neil", code: "high", decision: null, margin: null, payments: [], qty: -0.5, since: "2000-01-01", totals: {share: []}}, {channel: "12", code: "NL", decision: null, margin: null, payments: [], qty: 250, since: "2025-03-20T10:15:30Z", totals: {share: []}}, {channel: "A1", code: "DE", decision: 120, margin: 0, payments: [{rate: 0}, {rate: 358}, {rate: 2}], qty: 1, since: "2024-02-29", totals: {share: [0, 358, 2]}}, {channel: "US", code: "3.5", decision: null, margin: null, payments: [], qty: 5, since: "2025-03-20", totals: {share: []}}], price: -0.5, tag: 100, weight: null, weighted: [{channel: "12", code: "NL", decision: null, margin: null, payments: [], qty: 250, since: "2025-03-20T10:15:30Z", totals: {share: []}}, {channel: "US", code: "3.5", decision: null, margin: null, payments: [], qty: 5, since: "2025-03-20", totals: {share: []}}]}, net: 2.50}], + [{account: {income: 50, flagged: true, limit: 1000, weight: 0, price: 2.50, kind: "retail", members: [{qty: 3, channel: "", code: "a", since: "2000-01-01", payments: [{rate: 10}, {rate: 100}, {rate: 1e3}]}]}}, {account: {flagged: true, income: 50, kind: "retail", limit: 1000, members: [{channel: "", code: "a", decision: null, margin: null, payments: [{rate: 10}, {rate: 100}, {rate: 1000}], qty: 3, since: "2000-01-01", totals: {share: [10, 100, 1000]}}], price: 2.50, tag: 50, weight: 0, weighted: [{channel: "", code: "a", decision: null, margin: null, payments: [{rate: 10}, {rate: 100}, {rate: 1000}], qty: 3, since: "2000-01-01", totals: {share: [10, 100, 1000]}}]}, net: 1000}], + [{account: {income: -0.5, flagged: true, limit: 2.50, weight: 100, price: 1000, kind: "corporate", members: [{qty: 250, channel: "gold", code: "high", since: "2000-01-01", payments: [{rate: 10}, {rate: 0.000001}]}, {qty: 100, channel: "gold", code: "gold", since: "2024-01-01", payments: [{rate: 0.25}, {rate: 2}]}, {qty: 100, channel: "US", code: "gold", since: "2025-03-20", payments: [{rate: 1000}, {rate: 100}]}]}}, {account: {flagged: true, income: -0.5, kind: "corporate", limit: 2.50, members: [{channel: "gold", code: "high", decision: null, margin: null, payments: [{rate: 10}, {rate: 0.000001}], qty: 250, since: "2000-01-01", totals: {share: [10, 0.000001]}}, {channel: "gold", code: "gold", decision: 50, margin: 3, payments: [{rate: 0.25}, {rate: 2}], qty: 100, since: "2024-01-01", totals: {share: [0.25, 2]}}, {channel: "US", code: "gold", decision: 50, margin: 3, payments: [{rate: 1000}, {rate: 100}], qty: 100, since: "2025-03-20", totals: {share: [1000, 100]}}], price: 1000, tag: -0.5, weight: 100, weighted: [{channel: "gold", code: "high", decision: null, margin: null, payments: [{rate: 10}, {rate: 0.000001}], qty: 250, since: "2000-01-01", totals: {share: [10, 0.000001]}}, {channel: "gold", code: "gold", decision: 50, margin: 3, payments: [{rate: 0.25}, {rate: 2}], qty: 100, since: "2024-01-01", totals: {share: [0.25, 2]}}, {channel: "US", code: "gold", decision: 50, margin: 3, payments: [{rate: 1000}, {rate: 100}], qty: 100, since: "2025-03-20", totals: {share: [1000, 100]}}]}, net: -0.5}], + [{account: {income: -0.5, flagged: null, limit: 5, weight: -0.01, price: null, kind: "corporate", members: [{qty: 0.25, channel: "a", code: "Oslo", since: "2025-03-20T10:15:30Z", payments: [{rate: 99999999999999999999}, {rate: 0.25}]}, {qty: 162, channel: "high", code: "abc", since: "2025-03-20T10:15:30Z", payments: []}, {qty: 0, channel: "gold", code: "Oslo", since: "2024-02-29", payments: []}]}}, {account: {flagged: null, income: -0.5, kind: "corporate", limit: 5, members: [{channel: "a", code: "Oslo", decision: -0.5, margin: -0.5, payments: [{rate: 99999999999999999999}, {rate: 0.25}], qty: 0.25, since: "2025-03-20T10:15:30Z", totals: {share: [99999999999999999999, 0.25]}}, {channel: "high", code: "abc", decision: null, margin: null, payments: [], qty: 162, since: "2025-03-20T10:15:30Z", totals: {share: []}}, {channel: "gold", code: "Oslo", decision: null, margin: null, payments: [], qty: 0, since: "2024-02-29", totals: {share: []}}], price: null, tag: -0.5, weight: -0.01, weighted: [{channel: "high", code: "abc", decision: null, margin: null, payments: [], qty: 162, since: "2025-03-20T10:15:30Z", totals: {share: []}}]}, net: -0.5}], + [{account: {income: 7.25, limit: 100, weight: 0, kind: "retail", members: [{qty: 10, channel: "VIP", code: "3.5", since: "2030-12-31", payments: [{rate: 2}, {rate: 0.1}]}, {qty: 0, channel: "gold", code: "retail", since: "2000-01-01", payments: [{rate: 100}, {rate: 0.5}]}]}}, {account: {income: 7.25, kind: "retail", limit: 100, members: [{channel: "VIP", code: "3.5", decision: null, margin: null, payments: [{rate: 2}, {rate: 0.1}], qty: 10, since: "2030-12-31", totals: {share: [2, 0.1]}}, {channel: "gold", code: "retail", decision: null, margin: null, payments: [{rate: 100}, {rate: 0.5}], qty: 0, since: "2000-01-01", totals: {share: [100, 0.5]}}], tag: 7.25, weight: 0, weighted: [{channel: "VIP", code: "3.5", decision: null, margin: null, payments: [{rate: 2}, {rate: 0.1}], qty: 10, since: "2030-12-31", totals: {share: [2, 0.1]}}]}, net: 100}], + [{account: {income: 250, flagged: null, limit: 100, weight: null, price: null, kind: "retail", members: [{qty: 100, channel: "gold", code: "Oslo", since: "2025-03-20T10:15:30Z", payments: [{rate: 1000}]}, {qty: 5, channel: "é ü", code: "gold", since: "2000-01-01", payments: []}, {qty: 65, channel: "ok", code: " pad ", since: "2000-01-01", payments: [{rate: 65}, {rate: 0.1}, {rate: 100}]}]}}, {account: {flagged: null, income: 250, kind: "retail", limit: 100, members: [{channel: "gold", code: "Oslo", decision: 250, margin: 2, payments: [{rate: 1000}], qty: 100, since: "2025-03-20T10:15:30Z", totals: {share: [1000]}}, {channel: "é ü", code: "gold", decision: 250, margin: 0, payments: [], qty: 5, since: "2000-01-01", totals: {share: []}}, {channel: "ok", code: " pad ", decision: null, margin: null, payments: [{rate: 65}, {rate: 0.1}, {rate: 100}], qty: 65, since: "2000-01-01", totals: {share: [65, 0.1, 100]}}], price: null, tag: 250, weight: null, weighted: [{channel: "gold", code: "Oslo", decision: 250, margin: 2, payments: [{rate: 1000}], qty: 100, since: "2025-03-20T10:15:30Z", totals: {share: [1000]}}, {channel: "é ü", code: "gold", decision: 250, margin: 0, payments: [], qty: 5, since: "2000-01-01", totals: {share: []}}, {channel: "ok", code: " pad ", decision: null, margin: null, payments: [{rate: 65}, {rate: 0.1}, {rate: 100}], qty: 65, since: "2000-01-01", totals: {share: [65, 0.1, 100]}}]}, net: 100}], + [{account: {income: 100, flagged: true, limit: 5, weight: -1, price: 10, kind: "retail", members: [{qty: 99999999999999999999, channel: "A1", code: "NL", since: "2000-01-01", payments: []}, {qty: 1, channel: "abc", code: "VIP", since: "2024-02-29", payments: [{rate: 2}, {rate: 2}]}, {qty: 1, channel: "DE", code: "DE", since: "2025-03-20T10:15:30Z", payments: [{rate: 0.000001}, {rate: 1}]}]}}, {account: {flagged: true, income: 100, kind: "retail", limit: 5, members: [{channel: "A1", code: "NL", decision: null, margin: null, payments: [], qty: 99999999999999999999, since: "2000-01-01", totals: {share: []}}, {channel: "abc", code: "VIP", decision: null, margin: null, payments: [{rate: 2}, {rate: 2}], qty: 1, since: "2024-02-29", totals: {share: [2, 2]}}, {channel: "DE", code: "DE", decision: 0.50000050, margin: -10, payments: [{rate: 0.000001}, {rate: 1}], qty: 1, since: "2025-03-20T10:15:30Z", totals: {share: [0.000001, 1]}}], price: 10, tag: 100, weight: -1, weighted: [{channel: "A1", code: "NL", decision: null, margin: null, payments: [], qty: 99999999999999999999, since: "2000-01-01", totals: {share: []}}]}, net: 5}], + [{account: {income: 0.1, flagged: true, limit: 123456789.123, weight: 99.99, price: 2.50, kind: "retail", members: [{qty: 1000000, channel: "12", code: "high", since: "2000-01-01", payments: []}]}}, {account: {flagged: true, income: 0.1, kind: "retail", limit: 123456789.123, members: [{channel: "12", code: "high", decision: null, margin: null, payments: [], qty: 1000000, since: "2000-01-01", totals: {share: []}}], price: 2.50, tag: 2.50, weight: 99.99, weighted: [{channel: "12", code: "high", decision: null, margin: null, payments: [], qty: 1000000, since: "2000-01-01", totals: {share: []}}]}, net: 123456789.123}], + [{account: {income: 3, flagged: false, limit: 2, weight: 0.25, price: -0.01, kind: "retail", members: []}}, {account: {flagged: false, income: 3, kind: "retail", limit: 2, members: [], price: -0.01, tag: 3, weight: 0.25, weighted: []}, net: 2}], + [{account: {income: 250, flagged: true, limit: 0, weight: 1000, price: 18, kind: "retail", members: []}}, {account: {flagged: true, income: 250, kind: "retail", limit: 0, members: [], price: 18, tag: 18, weight: 1000, weighted: []}, net: 0}], + ], +} + +// seed 341800 (attempt 0) +{ + name: "b 19: applicant/companies/parts: 1 assertion, 3 expression, 1 table; 4 root, 3 per-member, 0 top-level computed", + policy: { + models: {applicant: {days: "number", vip: "boolean", rate: "number?", qty: "number?", active: "boolean", score: "number", companies: "company[]"}, company: {balance: "number?", dueDate: "date", flagged: "boolean?", parts: "part[]"}, part: {score: "number?", qty: "number", amount: "number?"}}, + blocks: [ + {expression: "applicant.flags.summary", value: "(min([abs(number(string(((applicant.rate ?? 0) / -6)))), 1000]) ^ 3)"}, + {assertion: "company.rank", conditions: [["or", "(applicant.active and applicant.active)", 0]]}, + {table: "t3", inputs: ["number(string(applicant.score))"], outputs: ["applicant.decision", "applicant.capped", "applicant.flags.penalty[]"], rules: [ + ["", "(applicant.qty ?? 0)", "`${3}/${applicant.active}`", "(applicant.active ? 'none' : 'none')"], + ["<= 250", "18", "'low'", ""], + ["< 2", "applicant.flags.summary", "string(applicant.active)", ""], + ["> 50", "len(filter(applicant.companies, #.balance == null))", "'Oslo'", ""], + ["< 0", "applicant.days", "'A1'", "'x'"], + ["> 0.5", "(applicant.qty ?? 0)", "'x'", "'low'"], + ["", "applicant.flags.summary", "(applicant.active ? 'x' : 'low')", "string(applicant.vip)"], + ]}, + {expression: "company.scores.bonus", value: "map(company.parts, #.qty)"}, + {expression: "company.flag", value: "map(company.parts, (#.score ?? 0))"}, + ], + }, + cases: [ + [{applicant: {days: 2.50, vip: true, qty: 2.50, active: false, score: 0.5, companies: []}}, {applicant: {active: false, capped: "3/false", companies: [], days: 2.50, decision: 2.50, flags: {penalty: ["none", "true"]}, qty: 2.50, score: 0.5, vip: true}}], + [{applicant: {days: -0, vip: false, rate: 2, qty: 5, active: false, score: -0.01, companies: [{balance: 2.50, dueDate: "2000-01-01", flagged: null, parts: [{qty: 1e3, amount: null}, {qty: 1, amount: 99.99}]}, {balance: 2, dueDate: "2030-12-31", flagged: false, parts: []}]}}, {applicant: {active: false, capped: "3/false", companies: [{balance: 2.50, dueDate: "2000-01-01", flag: [0, 0], flagged: null, parts: [{amount: null, qty: 1000}, {amount: 99.99, qty: 1}], rank: false, scores: {bonus: [1000, 1]}}, {balance: 2, dueDate: "2030-12-31", flag: [], flagged: false, parts: [], rank: false, scores: {bonus: []}}], days: 0, decision: 5, flags: {penalty: ["none", "x", "false"]}, qty: 5, rate: 2, score: -0.01, vip: false}}], + [{applicant: {days: 0.1, vip: false, rate: 99.99, qty: 3, active: true, score: 123456789.123, companies: [{balance: 2, dueDate: "1990-06-15", flagged: true, parts: []}, {balance: 1, dueDate: "2024-01-01", flagged: true, parts: [{score: 2, qty: -500, amount: 5}]}, {balance: 1e3, dueDate: "1990-06-15", flagged: true, parts: []}, {balance: 99999999999999999999, dueDate: "2024-01-01", flagged: false, parts: [{score: 0.5, qty: 65, amount: 1000}]}, {balance: 5, dueDate: "2025-03-20", flagged: false, parts: [{score: 50, qty: 1, amount: 50}]}]}}, {applicant: {active: true, capped: "3/true", companies: [{balance: 2, dueDate: "1990-06-15", flag: [], flagged: true, parts: [], rank: true, scores: {bonus: []}}, {balance: 1, dueDate: "2024-01-01", flag: [2], flagged: true, parts: [{amount: 5, qty: -500, score: 2}], rank: true, scores: {bonus: [-500]}}, {balance: 1000, dueDate: "1990-06-15", flag: [], flagged: true, parts: [], rank: true, scores: {bonus: []}}, {balance: 99999999999999999999, dueDate: "2024-01-01", flag: [0.5], flagged: false, parts: [{amount: 1000, qty: 65, score: 0.5}], rank: true, scores: {bonus: [65]}}, {balance: 5, dueDate: "2025-03-20", flag: [50], flagged: false, parts: [{amount: 50, qty: 1, score: 50}], rank: true, scores: {bonus: [1]}}], days: 0.1, decision: 3, flags: {penalty: ["none", "low", "false"]}, qty: 3, rate: 99.99, score: 123456789.123, vip: false}}], + [{applicant: {days: 250, vip: false, rate: 0.5, qty: 5, active: false, score: -0.01, companies: [{balance: 0.5, dueDate: "2025-03-20", flagged: true, parts: [{score: 2, qty: 2, amount: 18}, {score: 2, qty: 1, amount: 0.000001}]}, {balance: 0.000001, dueDate: "2024-01-01", flagged: false, parts: [{score: 0.5, qty: -1, amount: 7.25}]}]}}, {applicant: {active: false, capped: "3/false", companies: [{balance: 0.5, dueDate: "2025-03-20", flag: [2, 2], flagged: true, parts: [{amount: 18, qty: 2, score: 2}, {amount: 0.000001, qty: 1, score: 2}], rank: false, scores: {bonus: [2, 1]}}, {balance: 0.000001, dueDate: "2024-01-01", flag: [0.5], flagged: false, parts: [{amount: 7.25, qty: -1, score: 0.5}], rank: false, scores: {bonus: [-1]}}], days: 250, decision: 5, flags: {penalty: ["none", "x", "false"]}, qty: 5, rate: 0.5, score: -0.01, vip: false}}], + [{applicant: {days: 3, vip: true, rate: null, qty: 50, active: true, score: 123456789.123, companies: [{balance: 5, dueDate: "2024-02-29", flagged: false, parts: [{score: 1, qty: 0, amount: null}, {score: null, qty: 18, amount: null}, {score: null, qty: -0.01}]}]}}, {applicant: {active: true, capped: "3/true", companies: [{balance: 5, dueDate: "2024-02-29", flag: [1, 0, 0], flagged: false, parts: [{amount: null, qty: 0, score: 1}, {amount: null, qty: 18, score: null}, {qty: -0.01, score: null}], rank: true, scores: {bonus: [0, 18, -0.01]}}], days: 3, decision: 50, flags: {penalty: ["none", "low", "true"]}, qty: 50, rate: null, score: 123456789.123, vip: true}}], + [{applicant: {days: 1e3, vip: false, rate: [1], qty: 50, active: true, score: 250, companies: [{balance: 250, dueDate: "2025-03-20T10:15:30Z", flagged: true, parts: [{score: 2, qty: 5, amount: 1e3}, {score: 1, qty: 2, amount: 1}]}, {balance: 0.1, dueDate: "2030-12-31", flagged: false, parts: [{score: -0.01, qty: 1, amount: -500}, {score: 7.25, qty: 0.000001, amount: 2}]}, {balance: 5, dueDate: "2024-01-01", flagged: true, parts: [{score: 1000, qty: 3, amount: 18}, {score: 0.1, qty: 0.5, amount: 250}, {score: 2, qty: 1e3, amount: 0}]}]}}, "!error: InputValidationFailed"], + [{applicant: {days: 277, vip: true, rate: 1000, qty: 0.5, active: true, score: 10, companies: [{balance: -500, dueDate: "2024-02-29", flagged: false, parts: [{score: 0.1, qty: 0.000001, amount: 3}, {score: 2, qty: 1000000, amount: 65}, {score: 2.50, qty: 100, amount: -500}]}, {balance: 0.000001, dueDate: "1990-06-15", flagged: true, parts: [{score: 0, qty: 7.25, amount: 99999999999999999999}]}]}}, {applicant: {active: true, capped: "3/true", companies: [{balance: -500, dueDate: "2024-02-29", flag: [0.1, 2, 2.50], flagged: false, parts: [{amount: 3, qty: 0.000001, score: 0.1}, {amount: 65, qty: 1000000, score: 2}, {amount: -500, qty: 100, score: 2.50}], rank: true, scores: {bonus: [0.000001, 1000000, 100]}}, {balance: 0.000001, dueDate: "1990-06-15", flag: [0], flagged: true, parts: [{amount: 99999999999999999999, qty: 7.25, score: 0}], rank: true, scores: {bonus: [7.25]}}], days: 277, decision: 0.5, flags: {penalty: ["none", "low", "true"]}, qty: 0.5, rate: 1000, score: 10, vip: true}}], + [{applicant: {days: 0, vip: false, active: true, score: 99.99, companies: [{balance: null, dueDate: "1990-06-15", flagged: null, parts: [{qty: 50, amount: -500}, {score: 0, qty: 1000, amount: 100}]}]}}, {applicant: {active: true, capped: "3/true", companies: [{balance: null, dueDate: "1990-06-15", flag: [0, 0], flagged: null, parts: [{amount: -500, qty: 50}, {amount: 100, qty: 1000, score: 0}], rank: true, scores: {bonus: [50, 1000]}}], days: 0, decision: 0, flags: {penalty: ["none", "low", "false"]}, score: 99.99, vip: false}}], + [{applicant: {days: -1, vip: false, rate: 1000000, qty: 1, active: true, score: 1000, companies: [{balance: 7.25, dueDate: "2030-12-31", flagged: false, parts: []}, {balance: 2.50, dueDate: "2000-01-01", flagged: false, parts: []}, {balance: 2.50, dueDate: "2000-01-01", flagged: true, parts: [{score: 65, qty: 2, amount: 0.1}, {score: 99999999999999999999, qty: -500, amount: 421}, {score: 1, qty: 50, amount: 18}]}, {balance: 50, dueDate: "1990-06-15", flagged: false, parts: [{score: 0, qty: -500, amount: 18}, {score: 2, qty: 50, amount: 5}]}, {balance: 0.5, dueDate: "2024-01-01", flagged: false, parts: [{score: 0, qty: 100, amount: 5}, {score: 18, qty: 0, amount: 0.5}, {score: 0.5, qty: 67, amount: 7.25}]}]}}, {applicant: {active: true, capped: "3/true", companies: [{balance: 7.25, dueDate: "2030-12-31", flag: [], flagged: false, parts: [], rank: true, scores: {bonus: []}}, {balance: 2.50, dueDate: "2000-01-01", flag: [], flagged: false, parts: [], rank: true, scores: {bonus: []}}, {balance: 2.50, dueDate: "2000-01-01", flag: [65, 99999999999999999999, 1], flagged: true, parts: [{amount: 0.1, qty: 2, score: 65}, {amount: 421, qty: -500, score: 99999999999999999999}, {amount: 18, qty: 50, score: 1}], rank: true, scores: {bonus: [2, -500, 50]}}, {balance: 50, dueDate: "1990-06-15", flag: [0, 2], flagged: false, parts: [{amount: 18, qty: -500, score: 0}, {amount: 5, qty: 50, score: 2}], rank: true, scores: {bonus: [-500, 50]}}, {balance: 0.5, dueDate: "2024-01-01", flag: [0, 18, 0.5], flagged: false, parts: [{amount: 5, qty: 100, score: 0}, {amount: 0.5, qty: 0, score: 18}, {amount: 7.25, qty: 67, score: 0.5}], rank: true, scores: {bonus: [100, 0, 67]}}], days: -1, decision: 1, flags: {penalty: ["none", "low", "false"]}, qty: 1, rate: 1000000, score: 1000, vip: false}}], + [{applicant: {days: 18, vip: true, rate: null, qty: 65, active: true, score: 250, companies: [{balance: null, dueDate: "2024-02-29", flagged: false, parts: [{score: null, qty: 1, amount: 1e3}, {score: 1, qty: -500, amount: null}]}, {dueDate: "2024-02-29", flagged: true, parts: [{qty: 50, amount: 1}, {score: 0.5, qty: 100, amount: -0}, {score: 1000000, qty: 99999999999999999999, amount: null}]}]}}, {applicant: {active: true, capped: "3/true", companies: [{balance: null, dueDate: "2024-02-29", flag: [0, 1], flagged: false, parts: [{amount: 1000, qty: 1, score: null}, {amount: null, qty: -500, score: 1}], rank: true, scores: {bonus: [1, -500]}}, {dueDate: "2024-02-29", flag: [0, 0.5, 1000000], flagged: true, parts: [{amount: 1, qty: 50}, {amount: 0, qty: 100, score: 0.5}, {amount: null, qty: 99999999999999999999, score: 1000000}], rank: true, scores: {bonus: [50, 100, 99999999999999999999]}}], days: 18, decision: 65, flags: {penalty: ["none", "low", "true"]}, qty: 65, rate: null, score: 250, vip: true}}], + [{applicant: {days: 50, vip: false, rate: 1, qty: 0, active: true, score: 1e3, companies: [{balance: 1e3, dueDate: "2025-03-20", flagged: "true", parts: []}]}}, "!error: InputValidationFailed"], + [{applicant: {days: 1, vip: false, rate: 1000, qty: -0, active: true, score: 0, companies: [{balance: 2, dueDate: "2024-02-29", flagged: false, parts: []}], extraField: 1}}, {applicant: {active: true, capped: "3/true", companies: [{balance: 2, dueDate: "2024-02-29", flag: [], flagged: false, parts: [], rank: true, scores: {bonus: []}}], days: 1, decision: 0, extraField: 1, flags: {penalty: ["none", "false"]}, qty: 0, rate: 1000, score: 0, vip: false}}], + [{applicant: {days: 0.5, vip: true, rate: null, qty: null, active: true, score: 1e3, companies: [{dueDate: "1990-06-15", flagged: true, parts: [{score: null, qty: 99.99, amount: 1000000}, {qty: 0}]}, {balance: 99.99, dueDate: "2025-03-20T10:15:30Z", flagged: true, parts: [{score: 99.99, qty: 50, amount: null}, {qty: 0.000001}]}, {balance: 100, dueDate: "1990-06-15", parts: []}]}}, {applicant: {active: true, capped: "3/true", companies: [{dueDate: "1990-06-15", flag: [0, 0], flagged: true, parts: [{amount: 1000000, qty: 99.99, score: null}, {qty: 0}], rank: true, scores: {bonus: [99.99, 0]}}, {balance: 99.99, dueDate: "2025-03-20T10:15:30Z", flag: [99.99, 0], flagged: true, parts: [{amount: null, qty: 50, score: 99.99}, {qty: 0.000001}], rank: true, scores: {bonus: [50, 0.000001]}}, {balance: 100, dueDate: "1990-06-15", flag: [], parts: [], rank: true, scores: {bonus: []}}], days: 0.5, decision: 0, flags: {penalty: ["none", "low", "true"]}, qty: null, rate: null, score: 1000, vip: true}}], + [{applicant: {days: -0.01, vip: false, rate: 100, qty: -0.01, active: true, score: 2, companies: [{balance: 0.5, dueDate: "2025-03-20", flagged: true, parts: [{score: -0, qty: -0, amount: 0.5}, {score: 18, qty: 250, amount: -0.01}]}, {balance: 65, dueDate: "1990-06-15", flagged: false, parts: [{score: -0, qty: 0.5, amount: 1}]}], extraField: {nested: true}}}, {applicant: {active: true, capped: "3/true", companies: [{balance: 0.5, dueDate: "2025-03-20", flag: [0, 18], flagged: true, parts: [{amount: 0.5, qty: 0, score: 0}, {amount: -0.01, qty: 250, score: 18}], rank: true, scores: {bonus: [0, 250]}}, {balance: 65, dueDate: "1990-06-15", flag: [0], flagged: false, parts: [{amount: 1, qty: 0.5, score: 0}], rank: true, scores: {bonus: [0.5]}}], days: -0.01, decision: -0.01, extraField: {nested: true}, flags: {penalty: ["none", "low", "false"]}, qty: -0.01, rate: 100, score: 2, vip: false}}], + [{applicant: {days: 99999999999999999999, vip: false, rate: 250, active: false, score: 250, companies: [{balance: null, dueDate: "2025-03-20", parts: []}, {balance: 250, dueDate: "1990-06-15", flagged: true, parts: [{score: 0.5, qty: 2.50, amount: 2}, {qty: 0, amount: 50}]}, {balance: 65, dueDate: "2025-03-20T10:15:30Z", parts: [{qty: 123456789.123, amount: -500}]}, {balance: null, dueDate: "2030-12-31", parts: [{score: null, qty: -1}, {qty: -0.5, amount: 65}]}]}}, {applicant: {active: false, capped: "3/false", companies: [{balance: null, dueDate: "2025-03-20", flag: [], parts: [], rank: false, scores: {bonus: []}}, {balance: 250, dueDate: "1990-06-15", flag: [0.5, 0], flagged: true, parts: [{amount: 2, qty: 2.50, score: 0.5}, {amount: 50, qty: 0}], rank: false, scores: {bonus: [2.50, 0]}}, {balance: 65, dueDate: "2025-03-20T10:15:30Z", flag: [0], parts: [{amount: -500, qty: 123456789.123}], rank: false, scores: {bonus: [123456789.123]}}, {balance: null, dueDate: "2030-12-31", flag: [0, 0], parts: [{qty: -1, score: null}, {amount: 65, qty: -0.5}], rank: false, scores: {bonus: [-1, -0.5]}}], days: 99999999999999999999, decision: 0, flags: {penalty: ["none", "low", "false"]}, rate: 250, score: 250, vip: false}}], + [{applicant: {days: -500, vip: false, rate: -1, qty: 50, active: true, score: 65, companies: [{balance: -0.5, dueDate: "2025-03-20", flagged: false, parts: [{score: 1, qty: -0.5, amount: 0.5}]}, {balance: 250, dueDate: "2024-02-29", flagged: true, parts: [{score: 7.25, qty: 50, amount: 0.5}, {score: 50, qty: 1000000, amount: 0.5}]}, {balance: -1, dueDate: "2030-12-31", flagged: true, parts: [{score: 1, qty: 376, amount: -0}, {score: -0, qty: 18, amount: 0}, {score: 0, qty: 1e3, amount: 0.1}]}, {balance: 1, dueDate: "1990-06-15", flagged: true, parts: [{score: 2, qty: 467, amount: 7.25}, {score: 0.5, qty: 18, amount: 0.5}, {score: 3, qty: 2, amount: 2}]}, {balance: 10, dueDate: "2024-01-01", flagged: true, parts: [{score: 389, qty: 50, amount: 123456789.123}, {score: -500, qty: -0.5, amount: 404}, {score: 2, qty: 2.50, amount: -500}]}]}}, {applicant: {active: true, capped: "3/true", companies: [{balance: -0.5, dueDate: "2025-03-20", flag: [1], flagged: false, parts: [{amount: 0.5, qty: -0.5, score: 1}], rank: true, scores: {bonus: [-0.5]}}, {balance: 250, dueDate: "2024-02-29", flag: [7.25, 50], flagged: true, parts: [{amount: 0.5, qty: 50, score: 7.25}, {amount: 0.5, qty: 1000000, score: 50}], rank: true, scores: {bonus: [50, 1000000]}}, {balance: -1, dueDate: "2030-12-31", flag: [1, 0, 0], flagged: true, parts: [{amount: 0, qty: 376, score: 1}, {amount: 0, qty: 18, score: 0}, {amount: 0.1, qty: 1000, score: 0}], rank: true, scores: {bonus: [376, 18, 1000]}}, {balance: 1, dueDate: "1990-06-15", flag: [2, 0.5, 3], flagged: true, parts: [{amount: 7.25, qty: 467, score: 2}, {amount: 0.5, qty: 18, score: 0.5}, {amount: 2, qty: 2, score: 3}], rank: true, scores: {bonus: [467, 18, 2]}}, {balance: 10, dueDate: "2024-01-01", flag: [389, -500, 2], flagged: true, parts: [{amount: 123456789.123, qty: 50, score: 389}, {amount: 404, qty: -0.5, score: -500}, {amount: -500, qty: 2.50, score: 2}], rank: true, scores: {bonus: [50, -0.5, 2.50]}}], days: -500, decision: 50, flags: {penalty: ["none", "low", "false"]}, qty: 50, rate: -1, score: 65, vip: false}}], + ], +} + +// seed 341900 (attempt 0) +{ + name: "b 20: tenant/lines + report: 1 assertion, 4 expression, 1 match, 1 table; 1 root, 5 per-member, 5 top-level computed", + policy: { + models: {tenant: {score: "number?", urgent: "boolean", code: "string", lines: "line[]", report: "creditReport?"}, line: {balance: "number", sku: "string", score: "number", rate: "number?"}, creditReport: {weight: "number"}}, + blocks: [ + {match: "creditReport.capped", arms: [["tenant.score != null", "tenant.code"], ["(review ?? '') in ['retail', 'A1']", "(string(calc.total.v) + '-' + `${(ok ?? 0)}/${creditReport.weight}`)"], ["(review ?? '') in ['low', 'US']", "`${tenant.urgent}/${creditReport.weight}`"], ["(ok ?? 0) in (21..46]", "tenant.code"], ["", "tenant.code"]]}, + {expression: "tenant.meta.penalty", value: "(min([abs((tenant.report.weight ?? 0)), 1000]) ^ 1)"}, + {expression: "line.decision", value: "{v: line.balance, a: line.sku, s: min([1000, (line.rate ?? 0)])}"}, + {expression: "creditReport.flag", value: "filter(tenant.lines, not ((#.tag and #.tag)))"}, + {table: "t2", inputs: ["tenant.code"], outputs: ["review", "ok"], rules: [ + ["'none', 'A1'", "tenant.code", "(tenant.report.weight ?? 0)"], + ["'a'", "tenant.code", "(tenant.report.weight ?? 0)"], + ["$ != 'Oslo'", "tenant.code", "(tenant.report.weight ?? 0)"], + ["$ != 'high'", "tenant.code", ""], + ["", "tenant.code", "(tenant.score ?? 0)"], + ]}, + {expression: "calc.total", value: "{a: (tenant.report.weight ?? 0), v: (ok ?? 0)}"}, + {assertion: "line.tag", conditions: ["all(tenant.lines, 10 < #.score)"]}, + ], + }, + cases: [ + [{tenant: {score: 99.99, urgent: true, code: "A1", lines: [{balance: 1000000, sku: "retail", score: 10, rate: 250}, {balance: -0.5, sku: "a", score: 0.1, rate: 65}, {balance: 0.5, sku: "", score: 1e3, rate: 123456789.123}, {balance: 5, sku: "日本", score: -0, rate: 100}, {balance: 250, sku: "O'Neil", score: 18, rate: 5}], report: {weight: 0}, extraField: 1}}, {ok: 0, review: "A1", tenant: {code: "A1", extraField: 1, lines: [{balance: 1000000, decision: {a: "retail", s: 250, v: 1000000}, rate: 250, score: 10, sku: "retail", tag: false}, {balance: -0.5, decision: {a: "a", s: 65, v: -0.5}, rate: 65, score: 0.1, sku: "a", tag: false}, {balance: 0.5, decision: {a: "", s: 1000, v: 0.5}, rate: 123456789.123, score: 1000, sku: "", tag: false}, {balance: 5, decision: {a: "日本", s: 100, v: 5}, rate: 100, score: 0, sku: "日本", tag: false}, {balance: 250, decision: {a: "O'Neil", s: 5, v: 250}, rate: 5, score: 18, sku: "O'Neil", tag: false}], meta: {penalty: 0}, report: {capped: "A1", flag: [{balance: 1000000, decision: {a: "retail", s: 250, v: 1000000}, rate: 250, score: 10, sku: "retail", tag: false}, {balance: -0.5, decision: {a: "a", s: 65, v: -0.5}, rate: 65, score: 0.1, sku: "a", tag: false}, {balance: 0.5, decision: {a: "", s: 1000, v: 0.5}, rate: 123456789.123, score: 1000, sku: "", tag: false}, {balance: 5, decision: {a: "日本", s: 100, v: 5}, rate: 100, score: 0, sku: "日本", tag: false}, {balance: 250, decision: {a: "O'Neil", s: 5, v: 250}, rate: 5, score: 18, sku: "O'Neil", tag: false}], weight: 0}, score: 99.99, urgent: true}}], + [{tenant: {score: 7.25, urgent: true, code: "x", lines: [{balance: 2.50, sku: "Oslo", score: -1, rate: 99.99}, {balance: -0.5, sku: "high", score: 2.50, rate: 0}], report: {weight: 0.000001}, extraField: "x"}}, {ok: 0.000001, review: "x", tenant: {code: "x", extraField: "x", lines: [{balance: 2.50, decision: {a: "Oslo", s: 99.99, v: 2.50}, rate: 99.99, score: -1, sku: "Oslo", tag: false}, {balance: -0.5, decision: {a: "high", s: 0, v: -0.5}, rate: 0, score: 2.50, sku: "high", tag: false}], meta: {penalty: 0.000001}, report: {capped: "x", flag: [{balance: 2.50, decision: {a: "Oslo", s: 99.99, v: 2.50}, rate: 99.99, score: -1, sku: "Oslo", tag: false}, {balance: -0.5, decision: {a: "high", s: 0, v: -0.5}, rate: 0, score: 2.50, sku: "high", tag: false}], weight: 0.000001}, score: 7.25, urgent: true}}], + [{tenant: {score: 250, urgent: false, code: "O'Neil", lines: [], report: {weight: 2}}}, {ok: 2, review: "O'Neil", tenant: {code: "O'Neil", lines: [], meta: {penalty: 2}, report: {capped: "O'Neil", flag: [], weight: 2}, score: 250, urgent: false}}], + [{tenant: {score: 1e3, urgent: false, code: "a", lines: [{balance: 27, sku: " pad ", score: -0, rate: -0}, {balance: -1, sku: "x", score: 461, rate: 0.1}], report: {weight: 250}}}, {ok: 250, review: "a", tenant: {code: "a", lines: [{balance: 27, decision: {a: " pad ", s: 0, v: 27}, rate: 0, score: 0, sku: " pad ", tag: false}, {balance: -1, decision: {a: "x", s: 0.1, v: -1}, rate: 0.1, score: 461, sku: "x", tag: false}], meta: {penalty: 250}, report: {capped: "a", flag: [{balance: 27, decision: {a: " pad ", s: 0, v: 27}, rate: 0, score: 0, sku: " pad ", tag: false}, {balance: -1, decision: {a: "x", s: 0.1, v: -1}, rate: 0.1, score: 461, sku: "x", tag: false}], weight: 250}, score: 1000, urgent: false}}], + [{tenant: {score: 0.1, urgent: false, code: "-", lines: [{balance: 2.50, score: 65, rate: 0.000001}, {balance: 2, sku: "-", score: 123456789.123, rate: -0.01}, {balance: 10, sku: " pad ", score: 123456789.123, rate: 1000}, {balance: 2.50, sku: "low", score: 1000000, rate: 10}, {balance: 1000, sku: "3.5", score: -1, rate: 0.1}, {balance: 65, sku: "abc", score: 250, rate: -0}, {balance: 1e3, sku: "12", score: -0, rate: 1000}, {balance: 10, sku: "Oslo", score: -0.5, rate: 5}, {balance: 18, sku: "A1", score: -500, rate: 0.000001}], report: {weight: 18}}}, {ok: 18, review: "-", tenant: {code: "-", lines: [{balance: 2.50, decision: {a: null, s: 0.000001, v: 2.50}, rate: 0.000001, score: 65, tag: false}, {balance: 2, decision: {a: "-", s: -0.01, v: 2}, rate: -0.01, score: 123456789.123, sku: "-", tag: false}, {balance: 10, decision: {a: " pad ", s: 1000, v: 10}, rate: 1000, score: 123456789.123, sku: " pad ", tag: false}, {balance: 2.50, decision: {a: "low", s: 10, v: 2.50}, rate: 10, score: 1000000, sku: "low", tag: false}, {balance: 1000, decision: {a: "3.5", s: 0.1, v: 1000}, rate: 0.1, score: -1, sku: "3.5", tag: false}, {balance: 65, decision: {a: "abc", s: 0, v: 65}, rate: 0, score: 250, sku: "abc", tag: false}, {balance: 1000, decision: {a: "12", s: 1000, v: 1000}, rate: 1000, score: 0, sku: "12", tag: false}, {balance: 10, decision: {a: "Oslo", s: 5, v: 10}, rate: 5, score: -0.5, sku: "Oslo", tag: false}, {balance: 18, decision: {a: "A1", s: 0.000001, v: 18}, rate: 0.000001, score: -500, sku: "A1", tag: false}], meta: {penalty: 18}, report: {capped: "-", flag: [{balance: 2.50, decision: {a: null, s: 0.000001, v: 2.50}, rate: 0.000001, score: 65, tag: false}, {balance: 2, decision: {a: "-", s: -0.01, v: 2}, rate: -0.01, score: 123456789.123, sku: "-", tag: false}, {balance: 10, decision: {a: " pad ", s: 1000, v: 10}, rate: 1000, score: 123456789.123, sku: " pad ", tag: false}, {balance: 2.50, decision: {a: "low", s: 10, v: 2.50}, rate: 10, score: 1000000, sku: "low", tag: false}, {balance: 1000, decision: {a: "3.5", s: 0.1, v: 1000}, rate: 0.1, score: -1, sku: "3.5", tag: false}, {balance: 65, decision: {a: "abc", s: 0, v: 65}, rate: 0, score: 250, sku: "abc", tag: false}, {balance: 1000, decision: {a: "12", s: 1000, v: 1000}, rate: 1000, score: 0, sku: "12", tag: false}, {balance: 10, decision: {a: "Oslo", s: 5, v: 10}, rate: 5, score: -0.5, sku: "Oslo", tag: false}, {balance: 18, decision: {a: "A1", s: 0.000001, v: 18}, rate: 0.000001, score: -500, sku: "A1", tag: false}], weight: 18}, score: 0.1, urgent: false}}], + [{tenant: {score: 65, urgent: false, code: "retail", lines: [{balance: 10, sku: "A1", score: 200, rate: -500}], report: {weight: 1e3}, extraField: "x"}}, {ok: 1000, review: "retail", tenant: {code: "retail", extraField: "x", lines: [{balance: 10, decision: {a: "A1", s: -500, v: 10}, rate: -500, score: 200, sku: "A1", tag: true}], meta: {penalty: 1000}, report: {capped: "retail", flag: [], weight: 1000}, score: 65, urgent: false}}], + [{tenant: {score: null, urgent: false, code: "Zed", lines: [{balance: 1000000, sku: "Zed", score: 99.99, rate: 99999999999999999999}, {balance: -0, sku: "A1", score: 1, rate: 2.50}], report: {weight: 1e3}}}, {ok: 1000, review: "Zed", tenant: {code: "Zed", lines: [{balance: 1000000, decision: {a: "Zed", s: 1000, v: 1000000}, rate: 99999999999999999999, score: 99.99, sku: "Zed", tag: false}, {balance: 0, decision: {a: "A1", s: 2.50, v: 0}, rate: 2.50, score: 1, sku: "A1", tag: false}], meta: {penalty: 1000}, report: {capped: "Zed", flag: [{balance: 1000000, decision: {a: "Zed", s: 1000, v: 1000000}, rate: 99999999999999999999, score: 99.99, sku: "Zed", tag: false}, {balance: 0, decision: {a: "A1", s: 2.50, v: 0}, rate: 2.50, score: 1, sku: "A1", tag: false}], weight: 1000}, score: null, urgent: false}}], + [{tenant: {score: 7.25, urgent: false, code: "US", lines: [], report: {weight: -0.01}}}, {ok: -0.01, review: "US", tenant: {code: "US", lines: [], meta: {penalty: 0.01}, report: {capped: "US", flag: [], weight: -0.01}, score: 7.25, urgent: false}}], + [{tenant: {score: 0.5, urgent: false, code: "O'Neil", lines: [], report: {weight: -0.5}}}, {ok: -0.5, review: "O'Neil", tenant: {code: "O'Neil", lines: [], meta: {penalty: 0.5}, report: {capped: "O'Neil", flag: [], weight: -0.5}, score: 0.5, urgent: false}}], + [{tenant: {score: 2, urgent: true, code: "US", lines: [], report: {weight: -1}}}, {ok: -1, review: "US", tenant: {code: "US", lines: [], meta: {penalty: 1}, report: {capped: "US", flag: [], weight: -1}, score: 2, urgent: true}}], + [{tenant: {urgent: false, code: "ok", lines: [{balance: 5, sku: "VIP", score: 5, rate: null}], report: {weight: 7.25}}}, {ok: 7.25, review: "ok", tenant: {code: "ok", lines: [{balance: 5, decision: {a: "VIP", s: 0, v: 5}, rate: null, score: 5, sku: "VIP", tag: false}], meta: {penalty: 7.25}, report: {capped: "ok", flag: [{balance: 5, decision: {a: "VIP", s: 0, v: 5}, rate: null, score: 5, sku: "VIP", tag: false}], weight: 7.25}, urgent: false}}], + [{tenant: {score: null, urgent: false, code: " pad ", lines: [{balance: 0.1, sku: " pad ", score: 123456789.123, rate: 99.99}, {balance: 10, sku: "x-y", score: 1e3}, {balance: 100, sku: "none", score: 465, rate: 10}, {balance: 99.99, sku: "high", score: 0.000001, rate: null}], report: {weight: 10}}}, {ok: 10, review: " pad ", tenant: {code: " pad ", lines: [{balance: 0.1, decision: {a: " pad ", s: 99.99, v: 0.1}, rate: 99.99, score: 123456789.123, sku: " pad ", tag: false}, {balance: 10, decision: {a: "x-y", s: 0, v: 10}, score: 1000, sku: "x-y", tag: false}, {balance: 100, decision: {a: "none", s: 10, v: 100}, rate: 10, score: 465, sku: "none", tag: false}, {balance: 99.99, decision: {a: "high", s: 0, v: 99.99}, rate: null, score: 0.000001, sku: "high", tag: false}], meta: {penalty: 10}, report: {capped: " pad ", flag: [{balance: 0.1, decision: {a: " pad ", s: 99.99, v: 0.1}, rate: 99.99, score: 123456789.123, sku: " pad ", tag: false}, {balance: 10, decision: {a: "x-y", s: 0, v: 10}, score: 1000, sku: "x-y", tag: false}, {balance: 100, decision: {a: "none", s: 10, v: 100}, rate: 10, score: 465, sku: "none", tag: false}, {balance: 99.99, decision: {a: "high", s: 0, v: 99.99}, rate: null, score: 0.000001, sku: "high", tag: false}], weight: 10}, score: null, urgent: false}}], + [{tenant: {score: 123456789.123, urgent: false, code: "Oslo", lines: [], report: {weight: 2}}}, {ok: 123456789.123, review: "Oslo", tenant: {code: "Oslo", lines: [], meta: {penalty: 2}, report: {capped: "Oslo", flag: [], weight: 2}, score: 123456789.123, urgent: false}}], + [{tenant: {score: 0.1, urgent: false, code: "x", lines: [{balance: -500, sku: "日本", score: 99.99, rate: 1e3}, {balance: 18, sku: "-", score: 2.50, rate: -500}, {balance: 65, sku: "Oslo", score: 18, rate: 10}, {balance: 479, sku: "x", score: -500, rate: -1}], report: {weight: 0.1}}}, {ok: 0.1, review: "x", tenant: {code: "x", lines: [{balance: -500, decision: {a: "日本", s: 1000, v: -500}, rate: 1000, score: 99.99, sku: "日本", tag: false}, {balance: 18, decision: {a: "-", s: -500, v: 18}, rate: -500, score: 2.50, sku: "-", tag: false}, {balance: 65, decision: {a: "Oslo", s: 10, v: 65}, rate: 10, score: 18, sku: "Oslo", tag: false}, {balance: 479, decision: {a: "x", s: -1, v: 479}, rate: -1, score: -500, sku: "x", tag: false}], meta: {penalty: 0.1}, report: {capped: "x", flag: [{balance: -500, decision: {a: "日本", s: 1000, v: -500}, rate: 1000, score: 99.99, sku: "日本", tag: false}, {balance: 18, decision: {a: "-", s: -500, v: 18}, rate: -500, score: 2.50, sku: "-", tag: false}, {balance: 65, decision: {a: "Oslo", s: 10, v: 65}, rate: 10, score: 18, sku: "Oslo", tag: false}, {balance: 479, decision: {a: "x", s: -1, v: 479}, rate: -1, score: -500, sku: "x", tag: false}], weight: 0.1}, score: 0.1, urgent: false}}], + [{tenant: {score: 99999999999999999999, urgent: false, code: "Oslo", lines: [{balance: -0.5, sku: "high", score: -0.5, rate: 1}], report: {weight: 0.5}}}, {ok: 99999999999999999999, review: "Oslo", tenant: {code: "Oslo", lines: [{balance: -0.5, decision: {a: "high", s: 1, v: -0.5}, rate: 1, score: -0.5, sku: "high", tag: false}], meta: {penalty: 0.5}, report: {capped: "Oslo", flag: [{balance: -0.5, decision: {a: "high", s: 1, v: -0.5}, rate: 1, score: -0.5, sku: "high", tag: false}], weight: 0.5}, score: 99999999999999999999, urgent: false}}], + [{tenant: {score: null, urgent: false, code: "", lines: [{balance: 1e3, sku: "3.5", score: -0.01}, {balance: 0.5, sku: "3.5", score: 65}, {balance: 123456789.123, sku: "é ü", score: 99999999999999999999, rate: null}, {balance: 1, sku: "high", score: 372}, {balance: -0, sku: "12", score: 2, rate: 7.25}, {balance: 10, sku: "é ü", score: 7.25}, {balance: 1000000, sku: "ok", score: 100, rate: 2}, {balance: 2, sku: "ok", score: 1000000}, {balance: -0.01, sku: "ok", score: -0, rate: 5}, {balance: 7.25, sku: "retail", score: -0.01, rate: 1}, {balance: 1e3, sku: "A1", score: -1, rate: null}], report: null}}, {ok: 0, review: "", tenant: {code: "", lines: [{balance: 1000, decision: {a: "3.5", s: 0, v: 1000}, score: -0.01, sku: "3.5", tag: false}, {balance: 0.5, decision: {a: "3.5", s: 0, v: 0.5}, score: 65, sku: "3.5", tag: false}, {balance: 123456789.123, decision: {a: "é ü", s: 0, v: 123456789.123}, rate: null, score: 99999999999999999999, sku: "é ü", tag: false}, {balance: 1, decision: {a: "high", s: 0, v: 1}, score: 372, sku: "high", tag: false}, {balance: 0, decision: {a: "12", s: 7.25, v: 0}, rate: 7.25, score: 2, sku: "12", tag: false}, {balance: 10, decision: {a: "é ü", s: 0, v: 10}, score: 7.25, sku: "é ü", tag: false}, {balance: 1000000, decision: {a: "ok", s: 2, v: 1000000}, rate: 2, score: 100, sku: "ok", tag: false}, {balance: 2, decision: {a: "ok", s: 0, v: 2}, score: 1000000, sku: "ok", tag: false}, {balance: -0.01, decision: {a: "ok", s: 5, v: -0.01}, rate: 5, score: 0, sku: "ok", tag: false}, {balance: 7.25, decision: {a: "retail", s: 1, v: 7.25}, rate: 1, score: -0.01, sku: "retail", tag: false}, {balance: 1000, decision: {a: "A1", s: 0, v: 1000}, rate: null, score: -1, sku: "A1", tag: false}], meta: {penalty: 0}, report: null, score: null, urgent: false}}], + [{tenant: {score: 0.000001, urgent: true, code: "retail", lines: [{balance: 10, sku: "Oslo", score: 65, rate: -0.5}, {balance: -0.01, sku: "high", score: 1e3, rate: 5}], report: {weight: -0.01}, extraField: "x"}}, {ok: -0.01, review: "retail", tenant: {code: "retail", extraField: "x", lines: [{balance: 10, decision: {a: "Oslo", s: -0.5, v: 10}, rate: -0.5, score: 65, sku: "Oslo", tag: true}, {balance: -0.01, decision: {a: "high", s: 5, v: -0.01}, rate: 5, score: 1000, sku: "high", tag: true}], meta: {penalty: 0.01}, report: {capped: "retail", flag: [], weight: -0.01}, score: 0.000001, urgent: true}}], + [{tenant: {score: 5, urgent: false, code: "日本", lines: [{balance: 1000, sku: "a", score: 396, rate: 1000}, {balance: 1e3, sku: " pad ", score: 10}, {balance: -0, sku: "12", score: 7.25, rate: 0.000001}, {balance: 1000, sku: " pad ", score: -500, rate: 250}], report: {weight: 0.5}}}, {ok: 0.5, review: "日本", tenant: {code: "日本", lines: [{balance: 1000, decision: {a: "a", s: 1000, v: 1000}, rate: 1000, score: 396, sku: "a", tag: false}, {balance: 1000, decision: {a: " pad ", s: 0, v: 1000}, score: 10, sku: " pad ", tag: false}, {balance: 0, decision: {a: "12", s: 0.000001, v: 0}, rate: 0.000001, score: 7.25, sku: "12", tag: false}, {balance: 1000, decision: {a: " pad ", s: 250, v: 1000}, rate: 250, score: -500, sku: " pad ", tag: false}], meta: {penalty: 0.5}, report: {capped: "日本", flag: [{balance: 1000, decision: {a: "a", s: 1000, v: 1000}, rate: 1000, score: 396, sku: "a", tag: false}, {balance: 1000, decision: {a: " pad ", s: 0, v: 1000}, score: 10, sku: " pad ", tag: false}, {balance: 0, decision: {a: "12", s: 0.000001, v: 0}, rate: 0.000001, score: 7.25, sku: "12", tag: false}, {balance: 1000, decision: {a: " pad ", s: 250, v: 1000}, rate: 250, score: -500, sku: " pad ", tag: false}], weight: 0.5}, score: 5, urgent: false}}], + [{tenant: {score: null, urgent: false, code: "O'Neil", lines: [], report: {weight: 65}}}, {ok: 65, review: "O'Neil", tenant: {code: "O'Neil", lines: [], meta: {penalty: 65}, report: {capped: "O'Neil", flag: [], weight: 65}, score: null, urgent: false}}], + [{tenant: {score: null, urgent: true, code: "-", lines: [{balance: 5, sku: "none", score: 0.1}, {balance: 5, sku: "abc", score: 1000, rate: null}, {balance: 7.25, sku: "Oslo", score: 99.99, rate: 0.1}, {balance: -0.5, sku: "a", score: 2, rate: null}, {balance: -0.01, sku: "low", score: -0.5, rate: null}, {balance: 99.99, sku: "a", score: 10, rate: -1}, {balance: 18, sku: "A1", score: 18, rate: null}, {balance: 18, sku: "gold", score: 1000, rate: 100}, {balance: 0.000001, sku: "A1", score: -0.01, rate: -0.5}, {balance: 18, sku: "ok", score: 1, rate: null}, {balance: 1000, sku: "日本", score: 1000000, rate: -0}, {balance: -0.5, sku: "x-y", score: 99999999999999999999, rate: null}], report: null}}, {ok: 0, review: "-", tenant: {code: "-", lines: [{balance: 5, decision: {a: "none", s: 0, v: 5}, score: 0.1, sku: "none", tag: false}, {balance: 5, decision: {a: "abc", s: 0, v: 5}, rate: null, score: 1000, sku: "abc", tag: false}, {balance: 7.25, decision: {a: "Oslo", s: 0.1, v: 7.25}, rate: 0.1, score: 99.99, sku: "Oslo", tag: false}, {balance: -0.5, decision: {a: "a", s: 0, v: -0.5}, rate: null, score: 2, sku: "a", tag: false}, {balance: -0.01, decision: {a: "low", s: 0, v: -0.01}, rate: null, score: -0.5, sku: "low", tag: false}, {balance: 99.99, decision: {a: "a", s: -1, v: 99.99}, rate: -1, score: 10, sku: "a", tag: false}, {balance: 18, decision: {a: "A1", s: 0, v: 18}, rate: null, score: 18, sku: "A1", tag: false}, {balance: 18, decision: {a: "gold", s: 100, v: 18}, rate: 100, score: 1000, sku: "gold", tag: false}, {balance: 0.000001, decision: {a: "A1", s: -0.5, v: 0.000001}, rate: -0.5, score: -0.01, sku: "A1", tag: false}, {balance: 18, decision: {a: "ok", s: 0, v: 18}, rate: null, score: 1, sku: "ok", tag: false}, {balance: 1000, decision: {a: "日本", s: 0, v: 1000}, rate: 0, score: 1000000, sku: "日本", tag: false}, {balance: -0.5, decision: {a: "x-y", s: 0, v: -0.5}, rate: null, score: 99999999999999999999, sku: "x-y", tag: false}], meta: {penalty: 0}, report: null, score: null, urgent: true}}], + [{tenant: {score: 1000000, urgent: false, code: "12", lines: [{balance: 1e3, sku: "é ü", score: 100, rate: 0.000001}], report: {weight: -500}}}, {ok: -500, review: "12", tenant: {code: "12", lines: [{balance: 1000, decision: {a: "é ü", s: 0.000001, v: 1000}, rate: 0.000001, score: 100, sku: "é ü", tag: true}], meta: {penalty: 500}, report: {capped: "12", flag: [], weight: -500}, score: 1000000, urgent: false}}], + ], +} + +// seed 342000 (attempt 0) +{ + name: "b 21: order/accounts + address: 4 expression, 2 table; 4 root, 1 per-member, 3 top-level computed", + policy: { + models: {order: {income: "number", score: "number", name: "string", since: "date?", label: "string?", limit: "number", accounts: "acct[]?", address: "address"}, acct: {days: "number?", label: "string", status: "string(open|closed|pending)?", active: "boolean"}, address: {score: "number?", kind: "string(retail|corporate)", tier: "string(gold|silver|bronze)"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {table: "t1", inputs: ["order.address.tier"], outputs: ["discount", "scores.fee", "total"], rules: [ + ["'silver'", "1", "(order.address.score ?? 0)", "(order.address.score ?? 0)"], + ["'bronze'", "10", "order.score", ""], + ["'bronze'", "(order.limit % (abs(order.limit) + 1))", "(order.income % (abs(order.income) + 1))", "(order.address.score ?? 0)"], + ]}, + {expression: "order.meta.bonus", value: "(order.since ?? d('2025-01-01'))"}, + {table: "t3", inputs: ["order.address.tier", "order.limit"], outputs: ["order.adjusted", "order.net[]"], rules: [ + ["'gold'", "0, 0", "(order.label ?? '')", ""], + ["'gold', 'bronze'", "250", "'x'", "order.score"], + ["", "[250..499]", "((scores.fee ?? 0) <= 10 ? 'gold' : (order.label ?? ''))", "order.limit"], + ["", "", "order.name", ""], + ]}, + {expression: "order.health", value: "`${'ok'}/${(discount ?? 0)}`"}, + {expression: "address.totals.review", value: "{v: order.meta.bonus.diff(d('2025-01-01'), 'day'), n: (address.score ?? 0), a: cap}"}, + {expression: "acct.margin", value: "order.adjusted"}, + ], + }, + cases: [ + [{cap: 10, order: {income: 65, score: 250, name: "x", label: "ok", limit: 0.000001, accounts: [{label: "DE", status: null, active: false}, {days: null, label: "a", status: null, active: true}], address: {score: 10, kind: "corporate", tier: "silver"}}}, {cap: 10, discount: 1, order: {accounts: [{active: false, label: "DE", margin: "x", status: null}, {active: true, days: null, label: "a", margin: "x", status: null}], address: {kind: "corporate", score: 10, tier: "silver", totals: {review: {a: 10, n: 10, v: 0}}}, adjusted: "x", health: "ok/1", income: 65, label: "ok", limit: 0.000001, meta: {bonus: "2025-01-01T00:00:00Z"}, name: "x", net: [], score: 250}, scores: {fee: 10}, total: 10}], + [{cap: 100, order: {income: 0, score: 250, name: "ok", since: "1990-06-15", label: "", limit: -0.01, accounts: [{days: 0, label: "日本", status: "pending", active: false}, {days: 0, label: "A1", status: "open", active: false}], address: {score: null, kind: "retail", tier: "silver"}}}, {cap: 100, discount: 1, order: {accounts: [{active: false, days: 0, label: "日本", margin: "ok", status: "pending"}, {active: false, days: 0, label: "A1", margin: "ok", status: "open"}], address: {kind: "retail", score: null, tier: "silver", totals: {review: {a: 100, n: 0, v: -12619}}}, adjusted: "ok", health: "ok/1", income: 0, label: "", limit: -0.01, meta: {bonus: "1990-06-15"}, name: "ok", net: [], score: 250, since: "1990-06-15"}, scores: {fee: 0}, total: 0}], + [{cap: 100, order: {income: 10, score: 1000, name: "ok", since: "2025-03-20T10:15:30Z", label: "NL", limit: 0, accounts: [{days: -0.5, label: "DE", status: "pending", active: true}], address: {score: 65, kind: "retail", tier: "gold"}}}, {cap: 100, discount: null, order: {accounts: [{active: true, days: -0.5, label: "DE", margin: "NL", status: "pending"}], address: {kind: "retail", score: 65, tier: "gold", totals: {review: {a: 100, n: 65, v: 78}}}, adjusted: "NL", health: "ok/0", income: 10, label: "NL", limit: 0, meta: {bonus: "2025-03-20T10:15:30Z"}, name: "ok", net: [], score: 1000, since: "2025-03-20T10:15:30Z"}, scores: {fee: null}, total: null}], + [{cap: 0.5, order: {income: 99.99, score: 1, name: "gold", since: "2025-03-20T10:15:30Z", label: "Zed", limit: 2, accounts: [], address: {score: 1, kind: "retail", tier: "silver"}}}, {cap: 0.5, discount: 1, order: {accounts: [], address: {kind: "retail", score: 1, tier: "silver", totals: {review: {a: 0.5, n: 1, v: 78}}}, adjusted: "gold", health: "ok/1", income: 99.99, label: "Zed", limit: 2, meta: {bonus: "2025-03-20T10:15:30Z"}, name: "gold", net: [], score: 1, since: "2025-03-20T10:15:30Z"}, scores: {fee: 1}, total: 1}], + [{cap: 100, order: {income: 0.5, score: 1, name: "DE", since: "2025-03-20", label: "ok", limit: -0.5, accounts: [{days: 10, label: "-", status: "open", active: false}], address: {score: -500, kind: "retail", tier: "gold"}}}, {cap: 100, discount: null, order: {accounts: [{active: false, days: 10, label: "-", margin: "DE", status: "open"}], address: {kind: "retail", score: -500, tier: "gold", totals: {review: {a: 100, n: -500, v: 78}}}, adjusted: "DE", health: "ok/0", income: 0.5, label: "ok", limit: -0.5, meta: {bonus: "2025-03-20"}, name: "DE", net: [], score: 1, since: "2025-03-20"}, scores: {fee: null}, total: null}], + [{cap: 10, order: {income: 1e3, score: 1000000, name: "NL", since: "2030-12-31", label: "A1", limit: 10, accounts: [{days: -0.01, label: "VIP", status: "open", active: false}, {days: 1000, label: "NL", status: "open", active: false}, {days: 99.99, label: "retail", status: "open", active: true}, {days: -0.5, label: " pad ", status: "closed", active: true}, {days: 246, label: "é ü", status: "closed", active: true}], address: {score: 0.5, kind: "corporate", tier: "gold"}, extraField: "x"}}, {cap: 10, discount: null, order: {accounts: [{active: false, days: -0.01, label: "VIP", margin: "NL", status: "open"}, {active: false, days: 1000, label: "NL", margin: "NL", status: "open"}, {active: true, days: 99.99, label: "retail", margin: "NL", status: "open"}, {active: true, days: -0.5, label: " pad ", margin: "NL", status: "closed"}, {active: true, days: 246, label: "é ü", margin: "NL", status: "closed"}], address: {kind: "corporate", score: 0.5, tier: "gold", totals: {review: {a: 10, n: 0.5, v: 2190}}}, adjusted: "NL", extraField: "x", health: "ok/0", income: 1000, label: "A1", limit: 10, meta: {bonus: "2030-12-31"}, name: "NL", net: [], score: 1000000, since: "2030-12-31"}, scores: {fee: null}, total: null}], + [{cap: 1, order: {income: 5, score: 1000, name: "a-b-c", since: "2030-12-31", label: "gold", limit: 99999999999999999999, accounts: [], address: {score: 250, kind: "corporate", tier: "gold"}, extraField: {nested: true}}}, {cap: 1, discount: null, order: {accounts: [], address: {kind: "corporate", score: 250, tier: "gold", totals: {review: {a: 1, n: 250, v: 2190}}}, adjusted: "a-b-c", extraField: {nested: true}, health: "ok/0", income: 5, label: "gold", limit: 99999999999999999999, meta: {bonus: "2030-12-31"}, name: "a-b-c", net: [], score: 1000, since: "2030-12-31"}, scores: {fee: null}, total: null}], + [{cap: -2, order: {income: 99.99, score: 99999999999999999999, name: "日本", since: "2025-03-20T10:15:30Z", limit: 10, accounts: [], address: {kind: "retail", tier: "silver"}}}, {cap: -2, discount: 1, order: {accounts: [], address: {kind: "retail", tier: "silver", totals: {review: {a: -2, n: 0, v: 78}}}, adjusted: "日本", health: "ok/1", income: 99.99, limit: 10, meta: {bonus: "2025-03-20T10:15:30Z"}, name: "日本", net: [], score: 99999999999999999999, since: "2025-03-20T10:15:30Z"}, scores: {fee: 0}, total: 0}], + [{cap: 0, order: {income: -0, score: 99999999999999999999, name: "-", since: "1990-06-15", label: "日本", limit: -0.5, accounts: [{days: 1000, label: "Oslo", status: "open", active: false}, {days: -0.5, label: "VIP", status: "open", active: false}, {days: 10, label: "A1", status: "open", active: false}, {days: 0.1, label: "é ü", status: "open", active: true}], address: {score: 1000, kind: "corporate", tier: "silver"}, extraField: {nested: true}}}, {cap: 0, discount: 1, order: {accounts: [{active: false, days: 1000, label: "Oslo", margin: "-", status: "open"}, {active: false, days: -0.5, label: "VIP", margin: "-", status: "open"}, {active: false, days: 10, label: "A1", margin: "-", status: "open"}, {active: true, days: 0.1, label: "é ü", margin: "-", status: "open"}], address: {kind: "corporate", score: 1000, tier: "silver", totals: {review: {a: 0, n: 1000, v: -12619}}}, adjusted: "-", extraField: {nested: true}, health: "ok/1", income: 0, label: "日本", limit: -0.5, meta: {bonus: "1990-06-15"}, name: "-", net: [], score: 99999999999999999999, since: "1990-06-15"}, scores: {fee: 1000}, total: 1000}], + [{cap: 0.5, order: {income: 250, score: 0.5, name: "gold", since: "2030-12-31", label: "US", limit: 2.50, accounts: [{days: 10, label: "VIP", status: "pending", active: true}, {days: 250, label: "abc", status: "open", active: true}, {days: 10, label: "ok", status: "pending", active: false}], address: {score: 10, kind: "retail", tier: "silver"}, extraField: 1}}, {cap: 0.5, discount: 1, order: {accounts: [{active: true, days: 10, label: "VIP", margin: "gold", status: "pending"}, {active: true, days: 250, label: "abc", margin: "gold", status: "open"}, {active: false, days: 10, label: "ok", margin: "gold", status: "pending"}], address: {kind: "retail", score: 10, tier: "silver", totals: {review: {a: 0.5, n: 10, v: 2190}}}, adjusted: "gold", extraField: 1, health: "ok/1", income: 250, label: "US", limit: 2.50, meta: {bonus: "2030-12-31"}, name: "gold", net: [], score: 0.5, since: "2030-12-31"}, scores: {fee: 10}, total: 10}], + [{cap: 1, order: {income: 10, score: 1000, name: "VIP", since: "2024-02-29", label: "gold", limit: 18, accounts: [{days: 0.5, label: "DE", status: "open", active: false}, {days: 250, label: "NL", status: "open", active: true}, {days: 7.25, label: "Zed", status: "open", active: true}, {days: -500, label: "ok", status: "pending", active: true}, {days: 65, label: "NL", status: "open", active: false}, {days: 2.50, label: "A1", status: "pending", active: true}, {days: 250, label: "a", status: "open", active: true}, {days: 1000, label: "é ü", status: "open", active: false}, {days: 250, label: "retail", status: "closed", active: true}], address: {score: 10, kind: "retail", tier: "gold"}, extraField: "x"}}, {cap: 1, discount: null, order: {accounts: [{active: false, days: 0.5, label: "DE", margin: "VIP", status: "open"}, {active: true, days: 250, label: "NL", margin: "VIP", status: "open"}, {active: true, days: 7.25, label: "Zed", margin: "VIP", status: "open"}, {active: true, days: -500, label: "ok", margin: "VIP", status: "pending"}, {active: false, days: 65, label: "NL", margin: "VIP", status: "open"}, {active: true, days: 2.50, label: "A1", margin: "VIP", status: "pending"}, {active: true, days: 250, label: "a", margin: "VIP", status: "open"}, {active: false, days: 1000, label: "é ü", margin: "VIP", status: "open"}, {active: true, days: 250, label: "retail", margin: "VIP", status: "closed"}], address: {kind: "retail", score: 10, tier: "gold", totals: {review: {a: 1, n: 10, v: -307}}}, adjusted: "VIP", extraField: "x", health: "ok/0", income: 10, label: "gold", limit: 18, meta: {bonus: "2024-02-29"}, name: "VIP", net: [], score: 1000, since: "2024-02-29"}, scores: {fee: null}, total: null}], + [{cap: -2, order: {income: 2, score: -500, name: "a", since: "2024-01-01", label: "VIP", limit: 5, accounts: [{days: 250, label: "O'Neil", status: "open", active: true}, {days: 10, label: "x", status: "closed", active: true}, {days: 18, label: "O'Neil", status: "open", active: true}], address: {score: 250, kind: "corporate", tier: "gold"}}}, {cap: -2, discount: null, order: {accounts: [{active: true, days: 250, label: "O'Neil", margin: "a", status: "open"}, {active: true, days: 10, label: "x", margin: "a", status: "closed"}, {active: true, days: 18, label: "O'Neil", margin: "a", status: "open"}], address: {kind: "corporate", score: 250, tier: "gold", totals: {review: {a: -2, n: 250, v: -366}}}, adjusted: "a", health: "ok/0", income: 2, label: "VIP", limit: 5, meta: {bonus: "2024-01-01"}, name: "a", net: [], score: -500, since: "2024-01-01"}, scores: {fee: null}, total: null}], + [{cap: -2, order: {income: 0.5, score: 292, name: "x", since: "2025-03-20T10:15:30Z", label: "VIP", limit: -0.01, accounts: [], address: {score: -0, kind: "corporate", tier: "silver"}}}, {cap: -2, discount: 1, order: {accounts: [], address: {kind: "corporate", score: 0, tier: "silver", totals: {review: {a: -2, n: 0, v: 78}}}, adjusted: "x", health: "ok/1", income: 0.5, label: "VIP", limit: -0.01, meta: {bonus: "2025-03-20T10:15:30Z"}, name: "x", net: [], score: 292, since: "2025-03-20T10:15:30Z"}, scores: {fee: 0}, total: 0}], + [{cap: 100, order: {income: 2, score: -0.5, name: "ok", since: "2000-01-01", label: "", limit: 0.1, accounts: [], address: {score: 250, kind: "retail", tier: "gold"}}}, {cap: 100, discount: null, order: {accounts: [], address: {kind: "retail", score: 250, tier: "gold", totals: {review: {a: 100, n: 250, v: -9132}}}, adjusted: "ok", health: "ok/0", income: 2, label: "", limit: 0.1, meta: {bonus: "2000-01-01"}, name: "ok", net: [], score: -0.5, since: "2000-01-01"}, scores: {fee: null}, total: null}], + [{cap: -2, order: {income: 99.99, score: 1000000, name: "gold", since: "1990-06-15", label: "gold", limit: -500, accounts: [{days: -0.5, label: "VIP", status: "pending", active: false}, {days: 0, label: "3.5", status: "pending", active: false}, {days: 250, label: "x-y", status: "open", active: false}, {days: 1e3, label: "12", status: "open", active: false}], address: {score: 65, kind: "corporate", tier: "bronze"}}}, {cap: -2, discount: 10, order: {accounts: [{active: false, days: -0.5, label: "VIP", margin: "gold", status: "pending"}, {active: false, days: 0, label: "3.5", margin: "gold", status: "pending"}, {active: false, days: 250, label: "x-y", margin: "gold", status: "open"}, {active: false, days: 1000, label: "12", margin: "gold", status: "open"}], address: {kind: "corporate", score: 65, tier: "bronze", totals: {review: {a: -2, n: 65, v: -12619}}}, adjusted: "gold", health: "ok/10", income: 99.99, label: "gold", limit: -500, meta: {bonus: "1990-06-15"}, name: "gold", net: [], score: 1000000, since: "1990-06-15"}, scores: {fee: 1000000}, total: 65}], + [{cap: 0, order: {income: 1000, score: 1e3, name: "é ü", since: "2025-03-20T10:15:30Z", label: "gold", limit: 99.99, accounts: [], address: {score: 250, kind: "retail", tier: "gold"}}}, {cap: 0, discount: null, order: {accounts: [], address: {kind: "retail", score: 250, tier: "gold", totals: {review: {a: 0, n: 250, v: 78}}}, adjusted: "é ü", health: "ok/0", income: 1000, label: "gold", limit: 99.99, meta: {bonus: "2025-03-20T10:15:30Z"}, name: "é ü", net: [], score: 1000, since: "2025-03-20T10:15:30Z"}, scores: {fee: null}, total: null}], + [{cap: 1, order: {income: 250, score: 99.99, name: " pad ", since: "2024-02-29", label: "abc", limit: 7.25, accounts: [], address: {score: 0, kind: "retail", tier: "gold"}}}, {cap: 1, discount: null, order: {accounts: [], address: {kind: "retail", score: 0, tier: "gold", totals: {review: {a: 1, n: 0, v: -307}}}, adjusted: " pad ", health: "ok/0", income: 250, label: "abc", limit: 7.25, meta: {bonus: "2024-02-29"}, name: " pad ", net: [], score: 99.99, since: "2024-02-29"}, scores: {fee: null}, total: null}], + [{cap: 100, order: {income: -0.01, score: -0.01, name: "abc", since: "2025-03-20", label: "a-b-c", limit: 0.1, accounts: [{days: 1e3, label: "日本", status: "closed", active: true}, {days: 1000000, label: "US", status: "closed", active: false}, {days: 1, label: " pad ", status: "closed", active: true}, {days: -0, label: "x", status: "pending", active: false}, {days: 10, label: "x", status: "open", active: false}], address: {score: 1000, kind: "retail", tier: "gold"}, extraField: "x"}}, {cap: 100, discount: null, order: {accounts: [{active: true, days: 1000, label: "日本", margin: "abc", status: "closed"}, {active: false, days: 1000000, label: "US", margin: "abc", status: "closed"}, {active: true, days: 1, label: " pad ", margin: "abc", status: "closed"}, {active: false, days: 0, label: "x", margin: "abc", status: "pending"}, {active: false, days: 10, label: "x", margin: "abc", status: "open"}], address: {kind: "retail", score: 1000, tier: "gold", totals: {review: {a: 100, n: 1000, v: 78}}}, adjusted: "abc", extraField: "x", health: "ok/0", income: -0.01, label: "a-b-c", limit: 0.1, meta: {bonus: "2025-03-20"}, name: "abc", net: [], score: -0.01, since: "2025-03-20"}, scores: {fee: null}, total: null}], + [{cap: 0.5, order: {income: 1000, score: 7.25, name: "retail", label: "x", limit: 0.000001, accounts: [{days: 1, label: "a", active: true}, {days: 250, label: "a", status: null, active: false}], address: {score: 7.25, kind: "corporate", tier: "bronze"}}}, {cap: 0.5, discount: 10, order: {accounts: [{active: true, days: 1, label: "a", margin: "retail"}, {active: false, days: 250, label: "a", margin: "retail", status: null}], address: {kind: "corporate", score: 7.25, tier: "bronze", totals: {review: {a: 0.5, n: 7.25, v: 0}}}, adjusted: "retail", health: "ok/10", income: 1000, label: "x", limit: 0.000001, meta: {bonus: "2025-01-01T00:00:00Z"}, name: "retail", net: [], score: 7.25}, scores: {fee: 7.25}, total: 7.25}], + [{cap: 0.5, order: {income: -1, score: -0.5, name: "é ü", since: "2030-12-31", label: "a", limit: 0.1, accounts: [{days: 1e3, label: "retail", status: "closed", active: true}, {days: 65, label: "DE", status: "open", active: false}], address: {score: 18, kind: "retail", tier: "gold"}}}, {cap: 0.5, discount: null, order: {accounts: [{active: true, days: 1000, label: "retail", margin: "é ü", status: "closed"}, {active: false, days: 65, label: "DE", margin: "é ü", status: "open"}], address: {kind: "retail", score: 18, tier: "gold", totals: {review: {a: 0.5, n: 18, v: 2190}}}, adjusted: "é ü", health: "ok/0", income: -1, label: "a", limit: 0.1, meta: {bonus: "2030-12-31"}, name: "é ü", net: [], score: -0.5, since: "2030-12-31"}, scores: {fee: null}, total: null}], + [{cap: 1, order: {income: 1000, score: 0.5, name: "x", since: "2025-03-20", limit: 463, address: {kind: "retail", tier: "gold"}}}, {cap: 1, discount: null, order: {address: {kind: "retail", tier: "gold", totals: {review: {a: 1, n: 0, v: 78}}}, adjusted: "gold", health: "ok/0", income: 1000, limit: 463, meta: {bonus: "2025-03-20"}, name: "x", net: [463], score: 0.5, since: "2025-03-20"}, scores: {fee: null}, total: null}], + [{cap: 1, order: {income: -1, score: 65, name: "VIP", since: "2025-03-20T10:15:30Z", label: "US", limit: 7.25, accounts: [{days: 1, label: "Zed", status: "closed", active: false}, {days: -500, label: "-", status: "open", active: true}, {days: 1, label: "abc", status: "open", active: true}, {days: 1000000, label: "", status: "pending", active: false}, {days: 5, label: "日本", status: "closed", active: false}], address: {score: -1, kind: "retail", tier: "gold"}}}, {cap: 1, discount: null, order: {accounts: [{active: false, days: 1, label: "Zed", margin: "VIP", status: "closed"}, {active: true, days: -500, label: "-", margin: "VIP", status: "open"}, {active: true, days: 1, label: "abc", margin: "VIP", status: "open"}, {active: false, days: 1000000, label: "", margin: "VIP", status: "pending"}, {active: false, days: 5, label: "日本", margin: "VIP", status: "closed"}], address: {kind: "retail", score: -1, tier: "gold", totals: {review: {a: 1, n: -1, v: 78}}}, adjusted: "VIP", health: "ok/0", income: -1, label: "US", limit: 7.25, meta: {bonus: "2025-03-20T10:15:30Z"}, name: "VIP", net: [], score: 65, since: "2025-03-20T10:15:30Z"}, scores: {fee: null}, total: null}], + [{cap: 0, order: {income: 1000000, score: -0, name: "VIP", since: "2024-02-29", label: "DE", limit: -0.5, accounts: [], address: {score: 250, kind: "corporate", tier: "gold"}}}, {cap: 0, discount: null, order: {accounts: [], address: {kind: "corporate", score: 250, tier: "gold", totals: {review: {a: 0, n: 250, v: -307}}}, adjusted: "VIP", health: "ok/0", income: 1000000, label: "DE", limit: -0.5, meta: {bonus: "2024-02-29"}, name: "VIP", net: [], score: 0, since: "2024-02-29"}, scores: {fee: null}, total: null}], + ], +} + +// seed 342100 (attempt 0) +{ + name: "b 22: shipment/parcels/drivers + contact: 1 assertion, 4 expression, 2 match, 1 table; 4 root, 2 per-member, 0 top-level computed", + policy: { + models: {shipment: {age: "number", kind: "string(retail|corporate)", balance: "number", weight: "number", parcels: "parcel[]", contact: "contactInfo"}, parcel: {balance: "number?", kind: "string(retail|corporate)", channel: "string", drivers: "driver[]?"}, driver: {rate: "number?", price: "number"}, contactInfo: {qty: "number?", since: "date?", status: "string(open|closed|pending)"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {assertion: "contactInfo.decision", conditions: [["or", "all(shipment.parcels, #.balance == null)", 1], ["or", "matches(`${(contactInfo.qty ?? 0) > 1.5}/${shipment.age == 5}`, '^.{2,}$')", 0], ["and", "shipment.kind == 'corporate'", 1], ["and", "(all(shipment.parcels, len(#.channel) > 2) or shipment.balance == shipment.weight)", 1], ["or", "matches(`${'A1'}/${(contactInfo.qty ?? 0)}`, '^.{2,}$')", 2]]}, + {table: "t6", inputs: [null, "shipment.balance", "(shipment.contact.since ?? d('2025-01-01'))"], outputs: ["shipment.meta.rank", "shipment.discount", "shipment.scores.tag"], rules: [ + ["contains(['ok', 'ok', ''], shipment.contact.exposure)", "< 1.5", ">= d('2024-01-01')", "shipment.contact.exposure", "shipment.contact.exposure", "shipment.flag"], + ["startsWith(shipment.contact.exposure, 'A1')", "> 0.25", "> d('2000-06-30')", "'ok'", "string(shipment.contact.decision)", "((shipment.contact.qty ?? 0) * 2)"], + ["baseRate > 18", "", "", "shipment.contact.exposure", "", "baseRate"], + ["shipment.flag <= 10", "100, 1", "", "'US'", "shipment.contact.exposure", "shipment.balance"], + ]}, + {match: "contactInfo.exposure", arms: [["(contactInfo.since ?? d('2025-01-01')).isBefore(d('2025-01-01'), 'month')", "(contactInfo.decision ? 'none' : 'US')"], ["", "'VIP'"]]}, + {expression: "contactInfo.segment", value: "(contactInfo.since ?? d('2025-01-01')) < d('2000-06-30')"}, + {expression: "contactInfo.calc.summary", value: "map(shipment.parcels, number(string((#.balance ?? 0))))"}, + {expression: "parcel.net", value: "(shipment.contact.since ?? d('2025-01-01')).format('%d')"}, + {match: "parcel.bonus", arms: [["some((parcel.drivers ?? []), not (#.price <= 50))", "shipment.weight"], ["matches(`${shipment.contact.decision}/${(shipment.scores.tag ?? 0)}`, 'a')", "(parcel.balance ?? 0)"], ["", "(3 - (parcel.balance ?? 0))"]]}, + {expression: "shipment.flag", value: "shipment.balance"}, + ], + }, + cases: [ + [{baseRate: 0.5, shipment: {age: 18, kind: "retail", balance: 73, weight: true, parcels: [{balance: 1.5, kind: "retail", channel: "NL"}, {balance: 250, kind: "retail", channel: "ok", drivers: []}, {balance: 1000, kind: "corporate", channel: "high", drivers: [{rate: 2, price: 0.25}]}, {balance: 18, kind: "corporate", channel: "ok", drivers: [{rate: -0.5, price: -0}, {rate: 1000000, price: -1}]}], contact: {qty: 99999999999999999999, since: "2025-03-20", status: "pending"}}}, "!error: InputValidationFailed"], + [{baseRate: 10, shipment: {age: 100, balance: 18, weight: 1, parcels: [{balance: 2, kind: "corporate", channel: "US", drivers: [{rate: 1000, price: -0.01}, {rate: 2, price: 10}, {rate: 10, price: 250}]}, {balance: 1.5, kind: "retail", channel: "A1", drivers: null}], contact: {qty: 1e3, since: "2025-03-20T10:15:30Z", status: "open"}}}, "!error: MissingRequiredInputs"], + [{baseRate: -2, shipment: {age: 123456789.123, kind: "retail", balance: 99.99, weight: 0.25, parcels: [], contact: {status: "open"}}}, {baseRate: -2, shipment: {age: 123456789.123, balance: 99.99, contact: {calc: {summary: []}, decision: true, exposure: "VIP", segment: false, status: "open"}, discount: null, flag: 99.99, kind: "retail", meta: {rank: null}, parcels: [], scores: {tag: null}, weight: 0.25}}], + [{baseRate: 10, shipment: {age: 0, kind: "retail", balance: 100, weight: 0.5, parcels: [], contact: {qty: 10, status: "pending"}}}, {baseRate: 10, shipment: {age: 0, balance: 100, contact: {calc: {summary: []}, decision: true, exposure: "VIP", qty: 10, segment: false, status: "pending"}, discount: null, flag: 100, kind: "retail", meta: {rank: null}, parcels: [], scores: {tag: null}, weight: 0.5}}], + [{baseRate: -2, shipment: {age: 2, kind: "retail", balance: 1000, weight: 18, parcels: [{balance: 10, kind: "corporate", channel: "Zed", drivers: [{rate: 5, price: 3}, {rate: 18, price: 1}]}, {balance: 99999999999999999999, kind: "retail", channel: "ok", drivers: null}], contact: {qty: 1, since: "2030-12-31", status: "closed"}}}, {baseRate: -2, shipment: {age: 2, balance: 1000, contact: {calc: {summary: [10, 99999999999999999999]}, decision: true, exposure: "VIP", qty: 1, segment: false, since: "2030-12-31", status: "closed"}, discount: null, flag: 1000, kind: "retail", meta: {rank: null}, parcels: [{balance: 10, bonus: -7, channel: "Zed", drivers: [{price: 3, rate: 5}, {price: 1, rate: 18}], kind: "corporate", net: "31"}, {balance: 99999999999999999999, bonus: -99999999999999999996, channel: "ok", drivers: null, kind: "retail", net: "31"}], scores: {tag: null}, weight: 18}}], + [{baseRate: -2, shipment: {age: 50, kind: "retail", balance: -500, weight: 1, parcels: [{balance: 2.50, kind: "retail", channel: "日本", drivers: [{rate: 65, price: 2}, {rate: 0.000001, price: 5}, {rate: 250, price: 99.99}]}], contact: {qty: 123456789.123, since: "2024-02-29", status: "open"}}}, {baseRate: -2, shipment: {age: 50, balance: -500, contact: {calc: {summary: [2.50]}, decision: true, exposure: "none", qty: 123456789.123, segment: false, since: "2024-02-29", status: "open"}, discount: null, flag: -500, kind: "retail", meta: {rank: null}, parcels: [{balance: 2.50, bonus: 1, channel: "日本", drivers: [{price: 2, rate: 65}, {price: 5, rate: 0.000001}, {price: 99.99, rate: 250}], kind: "retail", net: "29"}], scores: {tag: null}, weight: 1}}], + [{baseRate: 100, shipment: {age: 18, kind: "retail", balance: 10, weight: -0, parcels: [{balance: 18, kind: "corporate", channel: "x", drivers: []}, {balance: 10, kind: "corporate", channel: "-", drivers: [{rate: 3, price: 1000}]}, {balance: 0.25, kind: "retail", channel: "gold", drivers: [{rate: 2.50, price: 50}, {rate: 0.5, price: 2.50}, {rate: 0.5, price: 10}]}, {balance: 1e3, kind: "retail", channel: "x", drivers: [{rate: 2, price: 1e3}, {rate: 18, price: -0.01}]}], contact: {qty: 18, since: "2024-01-01", status: "closed"}}}, {baseRate: 100, shipment: {age: 18, balance: 10, contact: {calc: {summary: [18, 10, 0.25, 1000]}, decision: true, exposure: "none", qty: 18, segment: false, since: "2024-01-01", status: "closed"}, discount: null, flag: 10, kind: "retail", meta: {rank: "none"}, parcels: [{balance: 18, bonus: -15, channel: "x", drivers: [], kind: "corporate", net: "01"}, {balance: 10, bonus: 0, channel: "-", drivers: [{price: 1000, rate: 3}], kind: "corporate", net: "01"}, {balance: 0.25, bonus: 2.75, channel: "gold", drivers: [{price: 50, rate: 2.50}, {price: 2.50, rate: 0.5}, {price: 10, rate: 0.5}], kind: "retail", net: "01"}, {balance: 1000, bonus: 0, channel: "x", drivers: [{price: 1000, rate: 2}, {price: -0.01, rate: 18}], kind: "retail", net: "01"}], scores: {tag: 100}, weight: 0}}], + [{baseRate: 0, shipment: {age: 250, kind: "retail", balance: 0.1, weight: 2, parcels: [{balance: 100, kind: null, channel: "none", drivers: [{rate: 50, price: 99.99}]}, {balance: 5, kind: "retail", channel: "a-b-c", drivers: [{rate: 0.25, price: 0.1}, {rate: 0.5, price: 5}, {rate: 0.5, price: -1}]}, {balance: 1.5, kind: "retail", channel: "Oslo", drivers: [{rate: 2, price: 0.25}, {rate: 2, price: 5}, {rate: 1.5, price: -0}]}, {balance: 100, kind: "corporate", channel: "ok"}, {balance: 2, kind: "retail", channel: "a-b-c", drivers: [{rate: 18, price: 18}, {rate: 1000000, price: -0.5}]}, {balance: 0.25, kind: "corporate", channel: "", drivers: [{rate: 18, price: 1}]}, {balance: 0.5, kind: "retail", channel: "US", drivers: []}, {balance: 1000, kind: "corporate", channel: "US", drivers: null}, {balance: 0.5, kind: "retail", channel: "DE", drivers: [{rate: 18, price: 1000000}, {rate: 10, price: 0.5}]}, {balance: 10, kind: "corporate", channel: "none", drivers: null}], contact: {qty: 111, since: "2024-01-01", status: "closed"}}}, {baseRate: 0, shipment: {age: 250, balance: 0.1, contact: {calc: {summary: [100, 5, 1.5, 100, 2, 0.25, 0.5, 1000, 0.5, 10]}, decision: true, exposure: "none", qty: 111, segment: false, since: "2024-01-01", status: "closed"}, discount: null, flag: 0.1, kind: "retail", meta: {rank: null}, parcels: [{balance: 100, bonus: 2, channel: "none", drivers: [{price: 99.99, rate: 50}], kind: null, net: "01"}, {balance: 5, bonus: -2, channel: "a-b-c", drivers: [{price: 0.1, rate: 0.25}, {price: 5, rate: 0.5}, {price: -1, rate: 0.5}], kind: "retail", net: "01"}, {balance: 1.5, bonus: 1.5, channel: "Oslo", drivers: [{price: 0.25, rate: 2}, {price: 5, rate: 2}, {price: 0, rate: 1.5}], kind: "retail", net: "01"}, {balance: 100, bonus: -97, channel: "ok", kind: "corporate", net: "01"}, {balance: 2, bonus: 1, channel: "a-b-c", drivers: [{price: 18, rate: 18}, {price: -0.5, rate: 1000000}], kind: "retail", net: "01"}, {balance: 0.25, bonus: 2.75, channel: "", drivers: [{price: 1, rate: 18}], kind: "corporate", net: "01"}, {balance: 0.5, bonus: 2.5, channel: "US", drivers: [], kind: "retail", net: "01"}, {balance: 1000, bonus: -997, channel: "US", drivers: null, kind: "corporate", net: "01"}, {balance: 0.5, bonus: 2, channel: "DE", drivers: [{price: 1000000, rate: 18}, {price: 0.5, rate: 10}], kind: "retail", net: "01"}, {balance: 10, bonus: -7, channel: "none", drivers: null, kind: "corporate", net: "01"}], scores: {tag: null}, weight: 2}}], + [{baseRate: 10, shipment: {age: 18, kind: "corporate", balance: 5, weight: 10, parcels: [{balance: 0.000001, kind: "retail", channel: "DE", drivers: [{rate: 99999999999999999999, price: 99999999999999999999}, {rate: 100, price: 1}, {rate: 5, price: 1}]}, {balance: 123456789.123, kind: "corporate", channel: "日本", drivers: [{rate: 0.5, price: 99999999999999999999}, {rate: 0, price: 10}, {rate: -0.01, price: 0.5}]}], contact: {qty: 274, since: "2025-03-20", status: "open"}}}, {baseRate: 10, shipment: {age: 18, balance: 5, contact: {calc: {summary: [0.000001, 123456789.123]}, decision: true, exposure: "VIP", qty: 274, segment: false, since: "2025-03-20", status: "open"}, discount: null, flag: 5, kind: "corporate", meta: {rank: null}, parcels: [{balance: 0.000001, bonus: 10, channel: "DE", drivers: [{price: 99999999999999999999, rate: 99999999999999999999}, {price: 1, rate: 100}, {price: 1, rate: 5}], kind: "retail", net: "20"}, {balance: 123456789.123, bonus: 10, channel: "日本", drivers: [{price: 99999999999999999999, rate: 0.5}, {price: 10, rate: 0}, {price: 0.5, rate: -0.01}], kind: "corporate", net: "20"}], scores: {tag: null}, weight: 10}}], + [{baseRate: 0, shipment: {age: 0.25, kind: "retail", balance: 10, weight: -0, parcels: [{balance: 0, kind: "retail", channel: "DE", drivers: [{rate: 2, price: 250}, {rate: -0.5, price: 1000000}]}, {balance: 2, kind: "retail", channel: "US"}], contact: {qty: -0.01, status: "open"}}}, {baseRate: 0, shipment: {age: 0.25, balance: 10, contact: {calc: {summary: [0, 2]}, decision: true, exposure: "VIP", qty: -0.01, segment: false, status: "open"}, discount: null, flag: 10, kind: "retail", meta: {rank: null}, parcels: [{balance: 0, bonus: 0, channel: "DE", drivers: [{price: 250, rate: 2}, {price: 1000000, rate: -0.5}], kind: "retail", net: "01"}, {balance: 2, bonus: 1, channel: "US", kind: "retail", net: "01"}], scores: {tag: null}, weight: 0}}], + [{baseRate: 10, shipment: {age: 18, kind: "retail", balance: 1000000, weight: 99999999999999999999, parcels: [{balance: 10, kind: "retail", channel: "", drivers: null}, {balance: -1, kind: "corporate", channel: "O'Neil", drivers: [{rate: 1000, price: 1}, {rate: -500, price: 50}]}], contact: {qty: 18, since: "1990-06-15", status: "pending"}, extraField: "x"}}, {baseRate: 10, shipment: {age: 18, balance: 1000000, contact: {calc: {summary: [10, -1]}, decision: true, exposure: "none", qty: 18, segment: true, since: "1990-06-15", status: "pending"}, discount: null, extraField: "x", flag: 1000000, kind: "retail", meta: {rank: null}, parcels: [{balance: 10, bonus: -7, channel: "", drivers: null, kind: "retail", net: "15"}, {balance: -1, bonus: 4, channel: "O'Neil", drivers: [{price: 1, rate: 1000}, {price: 50, rate: -500}], kind: "corporate", net: "15"}], scores: {tag: null}, weight: 99999999999999999999}}], + [{baseRate: 100, shipment: {age: 1e3, kind: "corporate", balance: 123456789.123, weight: 1, parcels: [{balance: 2, kind: "retail", channel: "x", drivers: []}], contact: {qty: 5, since: "2024-01-01", status: "open"}}}, {baseRate: 100, shipment: {age: 1000, balance: 123456789.123, contact: {calc: {summary: [2]}, decision: true, exposure: "none", qty: 5, segment: false, since: "2024-01-01", status: "open"}, discount: null, flag: 123456789.123, kind: "corporate", meta: {rank: "none"}, parcels: [{balance: 2, bonus: 1, channel: "x", drivers: [], kind: "retail", net: "01"}], scores: {tag: 100}, weight: 1}}], + [{baseRate: 0, shipment: {age: 1, kind: "retail", balance: 1e3, weight: 176, parcels: [{balance: 2, kind: "retail", channel: "US", drivers: []}], contact: {qty: 18, since: "2024-02-29", status: "pending"}, extraField: "x"}}, {baseRate: 0, shipment: {age: 1, balance: 1000, contact: {calc: {summary: [2]}, decision: true, exposure: "none", qty: 18, segment: false, since: "2024-02-29", status: "pending"}, discount: null, extraField: "x", flag: 1000, kind: "retail", meta: {rank: null}, parcels: [{balance: 2, bonus: 1, channel: "US", drivers: [], kind: "retail", net: "29"}], scores: {tag: null}, weight: 176}}], + [{baseRate: 0.5, shipment: {age: 99.99, kind: "retail", balance: 10, weight: 123456789.123, parcels: [{kind: "retail", channel: "x", drivers: []}], contact: {status: "pending"}}}, {baseRate: 0.5, shipment: {age: 99.99, balance: 10, contact: {calc: {summary: [0]}, decision: true, exposure: "VIP", segment: false, status: "pending"}, discount: null, flag: 10, kind: "retail", meta: {rank: null}, parcels: [{bonus: 3, channel: "x", drivers: [], kind: "retail", net: "01"}], scores: {tag: null}, weight: 123456789.123}}], + [{baseRate: 1, shipment: {age: 99.99, kind: "retail", balance: 10, weight: 2, parcels: [{balance: 5, kind: "corporate", channel: "NL", drivers: [{rate: 0, price: 0.1}, {rate: 18, price: 0.000001}]}, {balance: 5, kind: "retail", channel: "VIP", drivers: [{rate: 1.5, price: 0.1}, {rate: 1, price: 10}]}, {balance: -0, kind: "retail", channel: "ok", drivers: [{rate: 250, price: 0.5}, {rate: 1, price: -0.5}]}, {balance: 2, kind: "retail", channel: "high", drivers: [{rate: -0.5, price: 1000}, {rate: 65, price: 18}]}], contact: {qty: 250, since: "2025-03-20", status: "pending"}}}, {baseRate: 1, shipment: {age: 99.99, balance: 10, contact: {calc: {summary: [5, 5, 0, 2]}, decision: true, exposure: "VIP", qty: 250, segment: false, since: "2025-03-20", status: "pending"}, discount: null, flag: 10, kind: "retail", meta: {rank: null}, parcels: [{balance: 5, bonus: -2, channel: "NL", drivers: [{price: 0.1, rate: 0}, {price: 0.000001, rate: 18}], kind: "corporate", net: "20"}, {balance: 5, bonus: -2, channel: "VIP", drivers: [{price: 0.1, rate: 1.5}, {price: 10, rate: 1}], kind: "retail", net: "20"}, {balance: 0, bonus: 3, channel: "ok", drivers: [{price: 0.5, rate: 250}, {price: -0.5, rate: 1}], kind: "retail", net: "20"}, {balance: 2, bonus: 2, channel: "high", drivers: [{price: 1000, rate: -0.5}, {price: 18, rate: 65}], kind: "retail", net: "20"}], scores: {tag: null}, weight: 2}}], + [{baseRate: 1, shipment: {age: 1.5, kind: "retail", balance: 10, weight: 3, parcels: [{balance: 0.000001, kind: "corporate", channel: "VIP", drivers: [{rate: 3, price: 1e3}, {rate: 118, price: 1}, {rate: 2, price: 0.25}]}, {balance: 10, kind: "retail", channel: "none", drivers: [{rate: 18, price: 1}, {rate: 1000, price: 0.5}]}], contact: {qty: 100, since: "2000-01-01", status: "pending"}}}, {baseRate: 1, shipment: {age: 1.5, balance: 10, contact: {calc: {summary: [0.000001, 10]}, decision: true, exposure: "none", qty: 100, segment: true, since: "2000-01-01", status: "pending"}, discount: null, flag: 10, kind: "retail", meta: {rank: null}, parcels: [{balance: 0.000001, bonus: 3, channel: "VIP", drivers: [{price: 1000, rate: 3}, {price: 1, rate: 118}, {price: 0.25, rate: 2}], kind: "corporate", net: "01"}, {balance: 10, bonus: -7, channel: "none", drivers: [{price: 1, rate: 18}, {price: 0.5, rate: 1000}], kind: "retail", net: "01"}], scores: {tag: null}, weight: 3}}], + [{baseRate: 10, shipment: {age: 1000000, kind: "retail", balance: 2, weight: 50, parcels: [{balance: null, kind: "retail", channel: "A1", drivers: [{price: 18}, {price: 100}, {rate: 255, price: 18}]}, {balance: 0.1, kind: "retail", channel: "-", drivers: [{rate: null, price: 18}, {price: 18}, {price: 1.5}]}, {balance: 1, kind: "corporate", channel: "DE", drivers: [{rate: 100, price: 10}]}], contact: {qty: 339, since: "2024-02-29", status: "open"}}}, {baseRate: 10, shipment: {age: 1000000, balance: 2, contact: {calc: {summary: [0, 0.1, 1]}, decision: true, exposure: "none", qty: 339, segment: false, since: "2024-02-29", status: "open"}, discount: null, flag: 2, kind: "retail", meta: {rank: null}, parcels: [{balance: null, bonus: 50, channel: "A1", drivers: [{price: 18}, {price: 100}, {price: 18, rate: 255}], kind: "retail", net: "29"}, {balance: 0.1, bonus: 2.9, channel: "-", drivers: [{price: 18, rate: null}, {price: 18}, {price: 1.5}], kind: "retail", net: "29"}, {balance: 1, bonus: 2, channel: "DE", drivers: [{price: 10, rate: 100}], kind: "corporate", net: "29"}], scores: {tag: null}, weight: 50}}], + [{baseRate: 0, shipment: {age: 387, kind: "retail", balance: 123456789.123, weight: 18, parcels: [{balance: 1.5, kind: "corporate", channel: "abc"}], contact: {qty: 18, since: "2024-02-29", status: "open"}}}, {baseRate: 0, shipment: {age: 387, balance: 123456789.123, contact: {calc: {summary: [1.5]}, decision: true, exposure: "none", qty: 18, segment: false, since: "2024-02-29", status: "open"}, discount: null, flag: 123456789.123, kind: "retail", meta: {rank: null}, parcels: [{balance: 1.5, bonus: 1.5, channel: "abc", kind: "corporate", net: "29"}], scores: {tag: null}, weight: 18}}], + [{baseRate: 100, shipment: {age: 99999999999999999999, kind: "retail", balance: 1.5, weight: 10, parcels: [], contact: {qty: 5, since: "2030-12-31", status: "pending"}}}, {baseRate: 100, shipment: {age: 99999999999999999999, balance: 1.5, contact: {calc: {summary: []}, decision: true, exposure: "VIP", qty: 5, segment: false, since: "2030-12-31", status: "pending"}, discount: null, flag: 1.5, kind: "retail", meta: {rank: "VIP"}, parcels: [], scores: {tag: 100}, weight: 10}}], + [{baseRate: 0, shipment: {age: 5, kind: "retail", balance: 18, weight: -0.01, parcels: [{balance: 2, kind: null, channel: "none"}, {balance: 0, kind: "retail", channel: "gold"}], contact: {qty: 99.99, since: "2000-01-01", status: "open"}}}, {baseRate: 0, shipment: {age: 5, balance: 18, contact: {calc: {summary: [2, 0]}, decision: true, exposure: "none", qty: 99.99, segment: true, since: "2000-01-01", status: "open"}, discount: null, flag: 18, kind: "retail", meta: {rank: null}, parcels: [{balance: 2, bonus: 1, channel: "none", kind: null, net: "01"}, {balance: 0, bonus: 3, channel: "gold", kind: "retail", net: "01"}], scores: {tag: null}, weight: -0.01}}], + [{baseRate: 10, shipment: {age: 192, kind: "corporate", balance: null, weight: 0.5, parcels: [{balance: 2, kind: "corporate", channel: "ok", drivers: [{rate: 1.5, price: 10}]}, {balance: 1, kind: "retail", channel: "VIP", drivers: [{rate: 7.25, price: 2}, {rate: -0, price: 123456789.123}, {rate: 50, price: 10}]}, {balance: 250, kind: "corporate", channel: "US"}, {balance: 2.50, kind: "retail", channel: "3.5", drivers: [{rate: 3, price: 1.5}, {rate: 1000000, price: 99999999999999999999}, {rate: 2, price: 5}]}], contact: {qty: 99.99, since: "2024-01-01", status: "closed"}}}, "!error: MissingRequiredInputs"], + [{baseRate: 1, shipment: {age: 65, kind: "retail", balance: 413, weight: 1, parcels: [{balance: 18, channel: "DE"}], contact: {qty: 99.99, since: "1990-06-15", status: "open"}}}, {baseRate: 1, shipment: {age: 65, balance: 413, contact: {calc: {summary: [18]}, decision: true, exposure: "none", qty: 99.99, segment: true, since: "1990-06-15", status: "open"}, discount: null, flag: 413, kind: "retail", meta: {rank: null}, parcels: [{balance: 18, bonus: -15, channel: "DE", net: "15"}], scores: {tag: null}, weight: 1}}], + [{baseRate: 0, shipment: {age: 0, kind: "retail", balance: 18, weight: 0.5, parcels: [{kind: "retail", channel: "gold", drivers: [{rate: 0, price: 250}, {price: 18}, {rate: 10, price: 1000}]}, {kind: "corporate", channel: "retail", drivers: [{rate: null, price: 18}, {price: 1e3}]}, {kind: "retail", channel: "Oslo", drivers: [{rate: 99.99, price: 7.25}]}, {balance: 1.5, kind: "corporate", channel: "high", drivers: [{rate: null, price: 0}, {rate: 1000000, price: -0.01}]}, {balance: null, kind: "retail", channel: "US", drivers: [{rate: 2, price: 1}]}], contact: {status: "open"}}}, {baseRate: 0, shipment: {age: 0, balance: 18, contact: {calc: {summary: [0, 0, 0, 1.5, 0]}, decision: true, exposure: "VIP", segment: false, status: "open"}, discount: null, flag: 18, kind: "retail", meta: {rank: null}, parcels: [{bonus: 0.5, channel: "gold", drivers: [{price: 250, rate: 0}, {price: 18}, {price: 1000, rate: 10}], kind: "retail", net: "01"}, {bonus: 0.5, channel: "retail", drivers: [{price: 18, rate: null}, {price: 1000}], kind: "corporate", net: "01"}, {bonus: 3, channel: "Oslo", drivers: [{price: 7.25, rate: 99.99}], kind: "retail", net: "01"}, {balance: 1.5, bonus: 1.5, channel: "high", drivers: [{price: 0, rate: null}, {price: -0.01, rate: 1000000}], kind: "corporate", net: "01"}, {balance: null, bonus: 3, channel: "US", drivers: [{price: 1, rate: 2}], kind: "retail", net: "01"}], scores: {tag: null}, weight: 0.5}}], + [{baseRate: 0.5, shipment: {age: -500, kind: "corporate", balance: 2, weight: 2, parcels: [{balance: -1, kind: "retail", channel: "A1", drivers: [{rate: 5, price: 123456789.123}]}, {balance: -1, kind: "corporate", channel: "Zed", drivers: [{rate: 0.5, price: -1}, {rate: 50, price: 0.1}]}, {balance: 18, kind: "retail", channel: "", drivers: null}, {balance: 2, kind: "corporate", channel: "VIP", drivers: [{rate: 2.50, price: 10}, {rate: 1.5, price: 18}]}], contact: {qty: 3, since: "2025-03-20T10:15:30Z", status: "closed"}}}, {baseRate: 0.5, shipment: {age: -500, balance: 2, contact: {calc: {summary: [-1, -1, 18, 2]}, decision: true, exposure: "VIP", qty: 3, segment: false, since: "2025-03-20T10:15:30Z", status: "closed"}, discount: null, flag: 2, kind: "corporate", meta: {rank: null}, parcels: [{balance: -1, bonus: 2, channel: "A1", drivers: [{price: 123456789.123, rate: 5}], kind: "retail", net: "20"}, {balance: -1, bonus: 4, channel: "Zed", drivers: [{price: -1, rate: 0.5}, {price: 0.1, rate: 50}], kind: "corporate", net: "20"}, {balance: 18, bonus: -15, channel: "", drivers: null, kind: "retail", net: "20"}, {balance: 2, bonus: 1, channel: "VIP", drivers: [{price: 10, rate: 2.50}, {price: 18, rate: 1.5}], kind: "corporate", net: "20"}], scores: {tag: null}, weight: 2}}], + ], +} + +// seed 342200 (attempt 0) +{ + name: "b 23: customer/vehicles: 1 expression, 4 table; 7 root, 4 per-member, 0 top-level computed", + policy: { + models: {customer: {amount: "number", priority: "boolean?", rate: "number", vehicles: "vehicle[]"}, vehicle: {years: "number?", qty: "number", urgent: "boolean"}}, + blocks: [ + {table: "t1", inputs: ["customer.priority", "customer.priority"], outputs: ["customer.flag", "customer.calc.quota", "customer.risk"], rules: [ + ["false", "false", "customer.amount", "'x'", ""], + ["", "false", "customer.rate", "'DE'", "(customer.priority ?? false)"], + ["true", "false", "2", "'low'", "customer.amount in [25..28)"], + ["true", "", "customer.rate", "", "(customer.priority ?? false)"], + ["false", "false", "1000", "`${'US'}/${(customer.priority ?? false)}`", "(customer.priority ?? false)"], + ["true", "false", "trunc(customer.amount)", "'Oslo'", ""], + ]}, + {table: "t2", inputs: [null], outputs: ["vehicle.meta.penalty", "vehicle.eligible[]", "vehicle.surcharge"], rules: [ + ["customer.amount != 0.25", "(customer.calc.quota ?? '')", "customer.rate", "(customer.risk ?? false)"], + ["(vehicle.years ?? 0) != customer.amount", "string((customer.priority ?? false))", "(1.5 * (vehicle.years ?? 0))", "(customer.risk ?? false)"], + ["", "(customer.calc.quota ?? '')", "", ""], + ["matches((customer.calc.quota ?? ''), 'a')", "(customer.calc.quota ?? '')", "(vehicle.years ?? 0)", "(customer.priority ?? false)"], + ["customer.rate in [14..142]", "'VIP'", "(vehicle.years ?? 0)", "(customer.risk ?? false)"], + ["customer.amount in (50..81]", "'DE'", "(vehicle.years ?? 0)", "(customer.risk ?? false)"], + ["customer.flag != null", "(customer.calc.quota ?? '')", "sum([vehicle.qty, (customer.flag ?? 0)])", "(customer.priority ?? false)"], + ]}, + {table: "t3", inputs: ["((customer.flag ?? 0) - 100)", null], outputs: ["customer.weighted"], rules: [ + ["< 0.5", "", ""], + ["", "", "customer.rate == customer.rate"], + ["> 1", "customer.flag != null", "matches((customer.calc.quota ?? ''), '[0-9]$')"], + [">= 50", "matches((customer.calc.quota ?? ''), '[0-9]$')", "(customer.risk ?? false)"], + ["5", "", ""], + ["!= 18", "((customer.risk ?? false) and (customer.risk ?? false))", ""], + ]}, + {table: "t4", inputs: ["customer.rate", "(customer.priority ?? false)"], outputs: ["customer.points", "customer.adjusted[]", "customer.health"], rules: [ + ["5, 1", "", "", "(customer.calc.quota ?? '')", "((customer.flag ?? 0) - 1.5)"], + ["", "", "trunc((customer.flag ?? 0))", "(customer.calc.quota ?? '')", "customer.rate"], + ]}, + {expression: "vehicle.meta.grade", value: "((sum(vehicle.eligible) % (abs(median([(customer.flag ?? 0), customer.rate, 5])) + 1)) + (min(vehicle.eligible) ?? 0))"}, + ], + }, + cases: [ + [{customer: {amount: 1, priority: 1, rate: 1000, vehicles: [{years: 1, qty: 1000, urgent: true}, {years: 0.5, qty: 2, urgent: true}]}}, "!error: InputValidationFailed"], + [{customer: {amount: 100, rate: 0.000001, vehicles: [{years: null, qty: 18, urgent: true}, {qty: 1, urgent: true}]}}, {customer: {adjusted: [""], amount: 100, calc: {quota: null}, flag: null, health: 0.000001, points: 0, rate: 0.000001, risk: null, vehicles: [{eligible: [0.000001, 0], meta: {grade: 0.000001, penalty: ""}, qty: 18, surcharge: false, urgent: true, years: null}, {eligible: [0.000001, 0], meta: {grade: 0.000001, penalty: ""}, qty: 1, surcharge: false, urgent: true}], weighted: true}}], + [{customer: {amount: 1000, priority: true, rate: 99.99, vehicles: [{years: 1, qty: 5, urgent: false}, {years: 1.5, qty: 1, urgent: true}, {years: 1.5, qty: 5, urgent: false}]}}, {customer: {adjusted: [""], amount: 1000, calc: {quota: null}, flag: 99.99, health: 99.99, points: 99, priority: true, rate: 99.99, risk: true, vehicles: [{eligible: [99.99, 1.5, 1, 104.99], meta: {grade: 6.50, penalty: ""}, qty: 5, surcharge: true, urgent: false, years: 1}, {eligible: [99.99, 2.25, 1.5, 100.99], meta: {grade: 4.25, penalty: ""}, qty: 1, surcharge: true, urgent: true, years: 1.5}, {eligible: [99.99, 2.25, 1.5, 104.99], meta: {grade: 8.25, penalty: ""}, qty: 5, surcharge: true, urgent: false, years: 1.5}], weighted: true}}], + [{customer: {amount: 5, priority: true, rate: 1.5, vehicles: [{years: 99999999999999999999, qty: 123456789.123, urgent: false}, {years: 5, qty: 0.25, urgent: true}, {years: 18, qty: 99.99, urgent: false}]}}, {customer: {adjusted: [""], amount: 5, calc: {quota: null}, flag: 1.5, health: 1.5, points: 1, priority: true, rate: 1.5, risk: true, vehicles: [{eligible: [1.5, 149999999999999999998.5, 123456790.623], meta: {grade: 2.123, penalty: ""}, qty: 123456789.123, surcharge: true, urgent: false, years: 99999999999999999999}, {eligible: [1.5, 1.75], meta: {grade: 2.25, penalty: ""}, qty: 0.25, surcharge: true, urgent: true, years: 5}, {eligible: [1.5, 27.0, 101.49], meta: {grade: 3.99, penalty: ""}, qty: 99.99, surcharge: true, urgent: false, years: 18}], weighted: true}}], + [{customer: {amount: 7.25, priority: false, rate: -500, vehicles: [{years: 100, qty: 2, urgent: true}, {years: 90, qty: 0.5, urgent: true}]}}, {customer: {adjusted: ["x"], amount: 7.25, calc: {quota: "x"}, flag: 7.25, health: -500, points: 7, priority: false, rate: -500, risk: false, vehicles: [{eligible: [-500, 150.0, 9.25], meta: {grade: -504.75, penalty: "x"}, qty: 2, surcharge: false, urgent: true, years: 100}, {eligible: [-500, 135.0, 7.75], meta: {grade: -503.25, penalty: "x"}, qty: 0.5, surcharge: false, urgent: true, years: 90}], weighted: true}}], + [{customer: {amount: 2, priority: true, rate: 1000, vehicles: []}}, {customer: {adjusted: [""], amount: 2, calc: {quota: null}, flag: 1000, health: 1000, points: 1000, priority: true, rate: 1000, risk: true, vehicles: [], weighted: true}}], + [{customer: {amount: 1.5, priority: false, rate: 3, vehicles: [{years: 0, qty: 0.1, urgent: false}]}}, {customer: {adjusted: ["x"], amount: 1.5, calc: {quota: "x"}, flag: 1.5, health: 3, points: 1, priority: false, rate: 3, risk: false, vehicles: [{eligible: [3, 0, 1.6], meta: {grade: 0.6, penalty: "x"}, qty: 0.1, surcharge: false, urgent: false, years: 0}], weighted: true}}], + [{customer: {amount: 0, priority: true, rate: 1.5, vehicles: [{years: 1.5, qty: 18, urgent: false}, {years: 1, qty: 3, urgent: true}, {years: 0, qty: 1, urgent: false}, {years: -0, qty: 65, urgent: false}]}}, {customer: {adjusted: [""], amount: 0, calc: {quota: null}, flag: 1.5, health: 1.5, points: 1, priority: true, rate: 1.5, risk: true, vehicles: [{eligible: [1.5, 2.25, 19.5], meta: {grade: 2.25, penalty: ""}, qty: 18, surcharge: true, urgent: false, years: 1.5}, {eligible: [1.5, 1.5, 4.5], meta: {grade: 1.5, penalty: ""}, qty: 3, surcharge: true, urgent: true, years: 1}, {eligible: [1.5, 2.5], meta: {grade: 3.0, penalty: ""}, qty: 1, surcharge: true, urgent: false, years: 0}, {eligible: [1.5, 66.5], meta: {grade: 2.0, penalty: ""}, qty: 65, surcharge: true, urgent: false, years: 0}], weighted: true}}], + [{customer: {amount: 18, priority: true, rate: 1, vehicles: [{years: 123456789.123, qty: 3, urgent: true}, {years: 1.5, qty: 1e3, urgent: true}, {years: 250, qty: 0.000001, urgent: true}, {years: 0.25, qty: 10, urgent: true}, {years: -1, qty: 1000, urgent: true}]}}, {customer: {adjusted: ["", ""], amount: 18, calc: {quota: null}, flag: 1, health: -0.5, points: 1, priority: true, rate: 1, risk: true, vehicles: [{eligible: [1, 185185183.6845, 4], meta: {grade: 1.6845, penalty: ""}, qty: 3, surcharge: true, urgent: true, years: 123456789.123}, {eligible: [1, 2.25, 1001], meta: {grade: 1.25, penalty: ""}, qty: 1000, surcharge: true, urgent: true, years: 1.5}, {eligible: [1, 375.0, 1.000001], meta: {grade: 2.000001, penalty: ""}, qty: 0.000001, surcharge: true, urgent: true, years: 250}, {eligible: [1, 0.375, 11], meta: {grade: 0.750, penalty: ""}, qty: 10, surcharge: true, urgent: true, years: 0.25}, {eligible: [1, -1.5, 1001], meta: {grade: -1.0, penalty: ""}, qty: 1000, surcharge: true, urgent: true, years: -1}], weighted: true}}], + [{customer: {amount: -0.5, rate: 1.5, vehicles: [{years: null, qty: 0.25, urgent: false}, {years: 268, qty: 1.5, urgent: true}, {years: 100, qty: 1000, urgent: true}, {years: null, qty: 1e3, urgent: false}]}}, {customer: {adjusted: [""], amount: -0.5, calc: {quota: null}, flag: null, health: 1.5, points: 0, rate: 1.5, risk: null, vehicles: [{eligible: [1.5, 0], meta: {grade: 1.5, penalty: ""}, qty: 0.25, surcharge: false, urgent: false, years: null}, {eligible: [1.5, 402.0], meta: {grade: 2.5, penalty: ""}, qty: 1.5, surcharge: false, urgent: true, years: 268}, {eligible: [1.5, 150.0], meta: {grade: 3.0, penalty: ""}, qty: 1000, surcharge: false, urgent: true, years: 100}, {eligible: [1.5, 0], meta: {grade: 1.5, penalty: ""}, qty: 1000, surcharge: false, urgent: false, years: null}], weighted: true}}], + [{customer: {amount: 1, priority: null, rate: 1000, vehicles: [{years: 18, qty: 1.5, urgent: false}]}}, {customer: {adjusted: [""], amount: 1, calc: {quota: null}, flag: null, health: 1000, points: 0, priority: null, rate: 1000, risk: null, vehicles: [{eligible: [1000, 27.0], meta: {grade: 28.0, penalty: ""}, qty: 1.5, surcharge: false, urgent: false, years: 18}], weighted: true}}], + [{customer: {amount: 2.50, priority: true, rate: "12", vehicles: [{years: 1, qty: 5, urgent: true}, {years: -500, qty: 2, urgent: true}, {years: -0.01, qty: 68, urgent: true}]}}, "!error: InputValidationFailed"], + [{customer: {amount: 1, priority: false, rate: -0, vehicles: [{years: 2, qty: 99.99, urgent: false}, {years: 1.5, qty: 1, urgent: true}]}}, {customer: {adjusted: ["x"], amount: 1, calc: {quota: "x"}, flag: 1, health: 0, points: 1, priority: false, rate: 0, risk: false, vehicles: [{eligible: [0, 3.0, 100.99], meta: {grade: 1.99, penalty: "x"}, qty: 99.99, surcharge: false, urgent: false, years: 2}, {eligible: [0, 2.25, 2], meta: {grade: 0.25, penalty: "x"}, qty: 1, surcharge: false, urgent: true, years: 1.5}], weighted: true}}], + [{customer: {amount: -0, priority: false, rate: 2, vehicles: [{years: null, qty: 99999999999999999999, urgent: true}, {years: 5, qty: 18, urgent: false}]}}, {customer: {adjusted: ["x"], amount: 0, calc: {quota: "x"}, flag: 0, health: 2, points: 0, priority: false, rate: 2, risk: false, vehicles: [{eligible: [2, 99999999999999999999], meta: {grade: 4, penalty: "x"}, qty: 99999999999999999999, surcharge: false, urgent: true, years: null}, {eligible: [2, 7.5, 18], meta: {grade: 2.5, penalty: "x"}, qty: 18, surcharge: false, urgent: false, years: 5}], weighted: true}}], + [{customer: {amount: 2, priority: true, rate: 1.5, vehicles: []}}, {customer: {adjusted: [""], amount: 2, calc: {quota: null}, flag: 1.5, health: 1.5, points: 1, priority: true, rate: 1.5, risk: true, vehicles: [], weighted: true}}], + [{customer: {amount: 5, priority: false, rate: 3, vehicles: [{years: -500, qty: -0.5, urgent: true}, {years: 5, qty: 18, urgent: false}, {years: 2, qty: 5, urgent: false}, {qty: 1000, urgent: false}, {years: null, qty: 100, urgent: false}]}}, {customer: {adjusted: ["x"], amount: 5, calc: {quota: "x"}, flag: 5, health: 3, points: 5, priority: false, rate: 3, risk: false, vehicles: [{eligible: [3, -750.0, 4.5], meta: {grade: -754.5, penalty: "x"}, qty: -0.5, surcharge: false, urgent: true, years: -500}, {eligible: [3, 23], meta: {grade: 5, penalty: "x"}, qty: 18, surcharge: false, urgent: false, years: 5}, {eligible: [3, 3.0, 10], meta: {grade: 7.0, penalty: "x"}, qty: 5, surcharge: false, urgent: false, years: 2}, {eligible: [3, 0, 1005], meta: {grade: 0, penalty: "x"}, qty: 1000, surcharge: false, urgent: false}, {eligible: [3, 0, 105], meta: {grade: 0, penalty: "x"}, qty: 100, surcharge: false, urgent: false, years: null}], weighted: true}}], + [{customer: {amount: 18, priority: false, rate: 1, vehicles: [{years: -500, qty: 18, urgent: true}, {years: 100, qty: 99999999999999999999, urgent: true}, {years: 0, qty: 10, urgent: true}, {years: 0.5, qty: 1, urgent: true}, {years: 1000, qty: 7.25, urgent: false}]}}, {customer: {adjusted: ["x", "x"], amount: 18, calc: {quota: "x"}, flag: 18, health: 16.5, points: 18, priority: false, rate: 1, risk: false, vehicles: [{eligible: [1, -750.0, 36], meta: {grade: -755.0, penalty: "x"}, qty: 18, surcharge: false, urgent: true, years: -500}, {eligible: [1, 150.0, 100000000000000000017], meta: {grade: 5.0, penalty: "x"}, qty: 99999999999999999999, surcharge: false, urgent: true, years: 100}, {eligible: [1, 0, 28], meta: {grade: 5, penalty: "x"}, qty: 10, surcharge: false, urgent: true, years: 0}, {eligible: [1, 0.75, 19], meta: {grade: 3.50, penalty: "x"}, qty: 1, surcharge: false, urgent: true, years: 0.5}, {eligible: [1, 1500.0, 25.25], meta: {grade: 3.25, penalty: "x"}, qty: 7.25, surcharge: false, urgent: false, years: 1000}], weighted: true}}], + [{customer: {amount: 1, priority: true, rate: 5, vehicles: [{years: 65, qty: 0.25, urgent: true}], extraField: {nested: true}}}, {customer: {adjusted: ["", ""], amount: 1, calc: {quota: null}, extraField: {nested: true}, flag: 5, health: 3.5, points: 5, priority: true, rate: 5, risk: true, vehicles: [{eligible: [5, 97.5, 5.25], meta: {grade: 10.75, penalty: ""}, qty: 0.25, surcharge: true, urgent: true, years: 65}], weighted: true}}], + [{customer: {amount: 1, priority: true, rate: 2.50, vehicles: [{years: 1e3, qty: 5, urgent: false}, {years: -1, qty: 5, urgent: true}]}}, {customer: {adjusted: [""], amount: 1, calc: {quota: null}, flag: 2.50, health: 2.50, points: 2, priority: true, rate: 2.50, risk: true, vehicles: [{eligible: [2.50, 1500.0, 7.50], meta: {grade: 4.00, penalty: ""}, qty: 5, surcharge: true, urgent: false, years: 1000}, {eligible: [2.50, -1.5, 7.50], meta: {grade: 0.00, penalty: ""}, qty: 5, surcharge: true, urgent: true, years: -1}], weighted: true}}], + [{customer: {amount: 100, priority: false, rate: 5, vehicles: []}}, {customer: {adjusted: ["x", "x"], amount: 100, calc: {quota: "x"}, flag: 100, health: 98.5, points: 100, priority: false, rate: 5, risk: false, vehicles: [], weighted: true}}], + [{customer: {amount: 1e3, priority: true, rate: 5, vehicles: [{years: "12", qty: 100, urgent: true}, {years: 5, qty: 5, urgent: true}, {years: 0.000001, qty: 3, urgent: true}, {years: -0.01, qty: 5, urgent: true}, {years: 50, qty: 1000, urgent: false}]}}, "!error: InputValidationFailed"], + [{customer: {amount: 7.25, rate: -1, vehicles: [{years: null, qty: 1e3, urgent: false}]}}, {customer: {adjusted: [""], amount: 7.25, calc: {quota: null}, flag: null, health: -1, points: 0, rate: -1, risk: null, vehicles: [{eligible: [-1, 0], meta: {grade: -1, penalty: ""}, qty: 1000, surcharge: false, urgent: false, years: null}], weighted: true}}], + [{customer: {amount: 5, rate: 18, vehicles: [{years: null, qty: 18, urgent: false}]}}, {customer: {adjusted: [""], amount: 5, calc: {quota: null}, flag: null, health: 18, points: 0, rate: 18, risk: null, vehicles: [{eligible: [18, 0, 0], meta: {grade: 0, penalty: ""}, qty: 18, surcharge: false, urgent: false, years: null}], weighted: true}}], + [{customer: {amount: 1000, priority: true, rate: 2, vehicles: [{years: 1.5, qty: 99.99, urgent: true}, {years: null, qty: 0.1, urgent: false}]}}, {customer: {adjusted: [""], amount: 1000, calc: {quota: null}, flag: 2, health: 2, points: 2, priority: true, rate: 2, risk: true, vehicles: [{eligible: [2, 2.25, 101.99], meta: {grade: 3.24, penalty: ""}, qty: 99.99, surcharge: true, urgent: true, years: 1.5}, {eligible: [2, 0, 2.1], meta: {grade: 1.1, penalty: ""}, qty: 0.1, surcharge: true, urgent: false, years: null}], weighted: true}}], + [{customer: {amount: 0.5, priority: false, rate: 1e3, vehicles: [{qty: 1, urgent: true}, {years: 2.50, qty: 18, urgent: true}, {qty: 1, urgent: true}, {years: null, qty: 0.5, urgent: false}, {qty: 1.5, urgent: false}]}}, {customer: {adjusted: ["x"], amount: 0.5, calc: {quota: "x"}, flag: 0.5, health: 1000, points: 0, priority: false, rate: 1000, risk: false, vehicles: [{eligible: [1000, 0, 1.5], meta: {grade: 5.5, penalty: "x"}, qty: 1, surcharge: false, urgent: true}, {eligible: [1000, 3.750, 18.5], meta: {grade: 6.000, penalty: "x"}, qty: 18, surcharge: false, urgent: true, years: 2.50}, {eligible: [1000, 0, 1.5], meta: {grade: 5.5, penalty: "x"}, qty: 1, surcharge: false, urgent: true}, {eligible: [1000, 0, 1.0], meta: {grade: 5.0, penalty: "x"}, qty: 0.5, surcharge: false, urgent: false, years: null}, {eligible: [1000, 0, 2.0], meta: {grade: 0, penalty: "x"}, qty: 1.5, surcharge: false, urgent: false}], weighted: true}}], + [{customer: {amount: 0.5, priority: false, rate: 0.5, vehicles: [{years: 123456789.123, qty: -1, urgent: true}, {years: -0.5, qty: 123456789.123, urgent: true}]}}, {customer: {adjusted: ["x"], amount: 0.5, calc: {quota: "x"}, flag: 0.5, health: 0.5, points: 0, priority: false, rate: 0.5, risk: false, vehicles: [{eligible: [0.5, 185185183.6845, -0.5], meta: {grade: -0.3155, penalty: "x"}, qty: -1, surcharge: false, urgent: true, years: 123456789.123}, {eligible: [0.5, -0.75, 123456789.623], meta: {grade: -0.377, penalty: "x"}, qty: 123456789.123, surcharge: false, urgent: true, years: -0.5}], weighted: true}}], + [{customer: {amount: 18, priority: true, rate: 1e3, vehicles: []}}, {customer: {adjusted: [""], amount: 18, calc: {quota: null}, flag: 1000, health: 1000, points: 1000, priority: true, rate: 1000, risk: true, vehicles: [], weighted: true}}], + ], +} + +// seed 342300 (attempt 0) +{ + name: "b 24: shipment/accounts: 1 expression, 2 match, 2 table; 2 root, 6 per-member, 0 top-level computed", + policy: { + models: {shipment: {score: "number?", limit: "number", code: "string?", accounts: "acct[]?"}, acct: {years: "number", city: "string"}}, + blocks: [ + {table: "t4", hit: "collect", inputs: ["(1) / (abs(acct.years) + 1)", "trunc((shipment.score ?? 0))"], outputs: ["acct.calc.quota", "acct.calc.grade", "acct.share"], rules: [ + ["50, 10", "10", "(shipment.bucket ?? 0) <= 3", "shipment.limit >= 3", "(shipment.score ?? 0)"], + ["< 250", "", "acct.years <= 1", "(shipment.score ?? 0) == 1000", "(acct.years / 3)"], + ["!= 10", ">= 1.5", "isNumeric(acct.city)", "(shipment.score ?? 0) <= 100", "shipment.limit"], + ]}, + {match: "acct.net", arms: [["(acct.years) / (abs(50) + 1) != (shipment.bucket ?? 0)", "acct.city"], ["shipment.score != null", "acct.city"], ["", "`${(shipment.score ?? 0) == 50}/${acct.years <= 2}`"]]}, + {expression: "shipment.bucket", value: "shipment.score"}, + {match: "shipment.scores.level", arms: [["((shipment.bucket ?? 0)) / (abs((shipment.bucket ?? 0)) + 1) != shipment.limit", "upper(string((shipment.score ?? 0)))"], ["not (shipment.limit > 1000)", "(shipment.code ?? '')"], ["(shipment.score ?? 0) in (13..57]", "string(shipment.limit)"], ["(shipment.score ?? 0) in [2..75]", "(shipment.code ?? '')"], ["", "(shipment.code ?? '')"]]}, + {table: "t5", inputs: ["shipment.limit"], outputs: ["acct.calc.total", "acct.totals.band"], rules: [ + ["0.5", "acct.years", "acct.years"], + ["< 5", "shipment.limit", "acct.years"], + ["<= 2", "(shipment.bucket ?? 0)", "acct.years"], + ["<= 3", "(shipment.score ?? 0)", "5"], + ["", "(shipment.bucket ?? 0)", "len(acct.calc.quota)"], + ["!= 3", "shipment.limit", "shipment.limit"], + ["", "len(shipment.scores.level)", "acct.years"], + ]}, + ], + }, + cases: [ + [{shipment: {score: 5, limit: 0.5, code: "é ü", accounts: [{years: 99999999999999999999, city: "A1"}, {years: 3, city: " pad "}]}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [false, false], total: 99999999999999999999}, city: "A1", net: "A1", share: [33333333333333333333, 0.5], totals: {band: 99999999999999999999}, years: 99999999999999999999}, {calc: {grade: [false, true], quota: [false, false], total: 3}, city: " pad ", net: " pad ", share: [1, 0.5], totals: {band: 3}, years: 3}], bucket: 5, code: "é ü", limit: 0.5, score: 5}}], + [{shipment: {score: 3, limit: 50, code: "DE", accounts: [{years: -500, city: "DE"}], extraField: 1}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [true, false], total: 3}, city: "DE", net: "DE", share: [-166.66666666666666666666666667, 50], totals: {band: 2}, years: -500}], bucket: 3, code: "DE", extraField: 1, limit: 50, score: 3}}], + [{shipment: {score: 10, limit: 0, code: "VIP", accounts: [{years: 2, city: false}]}}, "!error: InputValidationFailed"], + [{shipment: {score: 65, limit: 250, code: "", accounts: [{years: -0.01, city: "a"}, {years: 100, city: "VIP"}]}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [true, false], total: 65}, city: "a", net: "a", share: [-0.0033333333333333333333333333, 250], totals: {band: 2}, years: -0.01}, {calc: {grade: [false, true], quota: [false, false], total: 65}, city: "VIP", net: "VIP", share: [33.333333333333333333333333333, 250], totals: {band: 2}, years: 100}], bucket: 65, code: "", limit: 250, score: 65}}], + [{shipment: {score: null, limit: 1, accounts: [{years: 0.5, city: "O'Neil"}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [true], total: 1}, city: "O'Neil", net: "O'Neil", share: [0.1666666666666666666666666667], totals: {band: 0.5}, years: 0.5}], bucket: null, limit: 1, score: null}}], + [{shipment: {score: 1, limit: 0.5, code: "é ü", accounts: [{years: 1000000, city: "NL"}, {years: 0.5, city: "-"}, {years: -0.5, city: "3.5"}, {years: 1, city: "日本"}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [false], total: 1000000}, city: "NL", net: "NL", share: [333333.33333333333333333333333], totals: {band: 1000000}, years: 1000000}, {calc: {grade: [false], quota: [true], total: 0.5}, city: "-", net: "-", share: [0.1666666666666666666666666667], totals: {band: 0.5}, years: 0.5}, {calc: {grade: [false], quota: [true], total: -0.5}, city: "3.5", net: "3.5", share: [-0.1666666666666666666666666667], totals: {band: -0.5}, years: -0.5}, {calc: {grade: [false], quota: [true], total: 1}, city: "日本", net: "日本", share: [0.3333333333333333333333333333], totals: {band: 1}, years: 1}], bucket: 1, code: "é ü", limit: 0.5, score: 1}}], + [{shipment: {limit: 2, code: "x-y", accounts: [{years: 1, city: "NL"}, {years: 100, city: ""}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [true], total: 2}, city: "NL", net: "NL", share: [0.3333333333333333333333333333], totals: {band: 1}, years: 1}, {calc: {grade: [false], quota: [false], total: 2}, city: "", net: "", share: [33.333333333333333333333333333], totals: {band: 100}, years: 100}], bucket: null, code: "x-y", limit: 2}}], + [{shipment: {limit: -500, code: "a-b-c"}}, {shipment: {bucket: null, code: "a-b-c", limit: -500}}], + [{shipment: {score: 5, limit: 18, code: "gold", accounts: [{years: 5, city: "a-b-c"}, {years: 2.50, city: "é ü"}, {years: 1000000, city: "x-y"}]}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [false, false], total: 5}, city: "a-b-c", net: "a-b-c", share: [1.6666666666666666666666666667, 18], totals: {band: 2}, years: 5}, {calc: {grade: [false, true], quota: [false, false], total: 5}, city: "é ü", net: "é ü", share: [0.8333333333333333333333333333, 18], totals: {band: 2}, years: 2.50}, {calc: {grade: [false, true], quota: [false, false], total: 5}, city: "x-y", net: "x-y", share: [333333.33333333333333333333333, 18], totals: {band: 2}, years: 1000000}], bucket: 5, code: "gold", limit: 18, score: 5}}], + [{shipment: {score: 2, limit: 0.25, code: "NL", accounts: [{years: 1000000, city: "US"}, {years: 10, city: "NL"}, {years: 10, city: "12"}]}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [false, false], total: 0.25}, city: "US", net: "US", share: [333333.33333333333333333333333, 0.25], totals: {band: 1000000}, years: 1000000}, {calc: {grade: [false, true], quota: [false, false], total: 0.25}, city: "NL", net: "NL", share: [3.3333333333333333333333333333, 0.25], totals: {band: 10}, years: 10}, {calc: {grade: [false, true], quota: [false, true], total: 0.25}, city: "12", net: "12", share: [3.3333333333333333333333333333, 0.25], totals: {band: 10}, years: 10}], bucket: 2, code: "NL", limit: 0.25, score: 2}}], + [{shipment: {score: 250, limit: 0, accounts: [{years: 1000, city: "abc"}]}}, {shipment: {accounts: [{calc: {grade: [false, false], quota: [false, false], total: 0}, city: "abc", net: "abc", share: [333.33333333333333333333333333, 0], totals: {band: 1000}, years: 1000}], bucket: 250, limit: 0, score: 250}}], + [{shipment: {score: 50, limit: 0.000001, accounts: [{years: 65, city: "NL"}, {years: 1000, city: "a-b-c"}]}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [false, false], total: 0.000001}, city: "NL", net: "NL", share: [21.666666666666666666666666667, 0.000001], totals: {band: 65}, years: 65}, {calc: {grade: [false, true], quota: [false, false], total: 0.000001}, city: "a-b-c", net: "a-b-c", share: [333.33333333333333333333333333, 0.000001], totals: {band: 1000}, years: 1000}], bucket: 50, limit: 0.000001, score: 50}}], + [{shipment: {score: null, limit: 250, accounts: [{years: 0.1, city: "A1"}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [true], total: 0}, city: "A1", net: "A1", share: [0.0333333333333333333333333333], totals: {band: 1}, years: 0.1}], bucket: null, limit: 250, score: null}}], + [{shipment: {score: 1000, limit: 1.5, code: "retail", accounts: [{years: 50, city: "日本"}, {years: -0.01, city: "retail"}, {years: 0.5, city: "DE"}, {years: 50, city: "NL"}, {years: -0.01, city: "Zed"}]}}, {shipment: {accounts: [{calc: {grade: [true, false], quota: [false, false], total: 1.5}, city: "日本", net: "日本", share: [16.666666666666666666666666667, 1.5], totals: {band: 50}, years: 50}, {calc: {grade: [true, false], quota: [true, false], total: 1.5}, city: "retail", net: "retail", share: [-0.0033333333333333333333333333, 1.5], totals: {band: -0.01}, years: -0.01}, {calc: {grade: [true, false], quota: [true, false], total: 1.5}, city: "DE", net: "DE", share: [0.1666666666666666666666666667, 1.5], totals: {band: 0.5}, years: 0.5}, {calc: {grade: [true, false], quota: [false, false], total: 1.5}, city: "NL", net: "NL", share: [16.666666666666666666666666667, 1.5], totals: {band: 50}, years: 50}, {calc: {grade: [true, false], quota: [true, false], total: 1.5}, city: "Zed", net: "Zed", share: [-0.0033333333333333333333333333, 1.5], totals: {band: -0.01}, years: -0.01}], bucket: 1000, code: "retail", limit: 1.5, score: 1000}}], + [{shipment: {score: 3, limit: 50, code: "retail", accounts: [{years: 1, city: "US"}, {years: 10, city: "-"}, {years: 65, city: "VIP"}]}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [true, false], total: 3}, city: "US", net: "US", share: [0.3333333333333333333333333333, 50], totals: {band: 2}, years: 1}, {calc: {grade: [false, true], quota: [false, false], total: 3}, city: "-", net: "-", share: [3.3333333333333333333333333333, 50], totals: {band: 2}, years: 10}, {calc: {grade: [false, true], quota: [false, false], total: 3}, city: "VIP", net: "VIP", share: [21.666666666666666666666666667, 50], totals: {band: 2}, years: 65}], bucket: 3, code: "retail", limit: 50, score: 3}}], + [{shipment: {limit: 99.99, code: "é ü", accounts: [{years: 18, city: "12"}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [false], total: 0}, city: "12", net: "12", share: [6], totals: {band: 1}, years: 18}], bucket: null, code: "é ü", limit: 99.99}}], + [{shipment: {score: 0.5, limit: 3, code: "NL", accounts: [{years: 18, city: ""}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [false], total: 3}, city: "", net: "", share: [6], totals: {band: 18}, years: 18}], bucket: 0.5, code: "NL", limit: 3, score: 0.5}}], + [{shipment: {score: 99999999999999999999, limit: -0.01, code: "DE", accounts: []}}, {shipment: {accounts: [], bucket: 99999999999999999999, code: "DE", limit: -0.01, score: 99999999999999999999}}], + [{shipment: {score: 0.000001, limit: 100, code: "Oslo", accounts: [], extraField: {nested: true}}}, {shipment: {accounts: [], bucket: 0.000001, code: "Oslo", extraField: {nested: true}, limit: 100, score: 0.000001}}], + [{shipment: {score: 1, limit: 50, code: "a-b-c", accounts: [{years: 5, city: "retail"}, {years: 10, city: "NL"}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [false], total: 1}, city: "retail", net: "retail", share: [1.6666666666666666666666666667], totals: {band: 1}, years: 5}, {calc: {grade: [false], quota: [false], total: 1}, city: "NL", net: "NL", share: [3.3333333333333333333333333333], totals: {band: 1}, years: 10}], bucket: 1, code: "a-b-c", limit: 50, score: 1}}], + [{shipment: {score: 1.5, limit: -0.5, code: "abc", accounts: [{years: 3, city: "3.5"}, {years: 1, city: " pad "}, {years: 250, city: "日本"}, {years: -0, city: " pad "}, {years: 10, city: "日本"}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [false], total: -0.5}, city: "3.5", net: "3.5", share: [1], totals: {band: 3}, years: 3}, {calc: {grade: [false], quota: [true], total: -0.5}, city: " pad ", net: " pad ", share: [0.3333333333333333333333333333], totals: {band: 1}, years: 1}, {calc: {grade: [false], quota: [false], total: -0.5}, city: "日本", net: "日本", share: [83.33333333333333333333333333], totals: {band: 250}, years: 250}, {calc: {grade: [false], quota: [true], total: -0.5}, city: " pad ", net: " pad ", share: [0], totals: {band: 0}, years: 0}, {calc: {grade: [false], quota: [false], total: -0.5}, city: "日本", net: "日本", share: [3.3333333333333333333333333333], totals: {band: 10}, years: 10}], bucket: 1.5, code: "abc", limit: -0.5, score: 1.5}}], + [{shipment: {score: -0.5, limit: 250, code: "DE", accounts: [{years: 1000, city: "Oslo"}], extraField: {nested: true}}}, {shipment: {accounts: [{calc: {grade: [false], quota: [false], total: -0.5}, city: "Oslo", net: "Oslo", share: [333.33333333333333333333333333], totals: {band: 1}, years: 1000}], bucket: -0.5, code: "DE", extraField: {nested: true}, limit: 250, score: -0.5}}], + [{shipment: {score: 0.5, limit: 250, code: 5, accounts: [{years: 0.25, city: "VIP"}]}}, "!error: InputValidationFailed"], + [{shipment: {score: 1, limit: 50, code: null, accounts: [{years: 100, city: "3.5"}, {years: 1000000, city: ""}, {years: 10, city: "-"}, {years: 5, city: "-"}, {years: 0.1, city: "Zed"}, {years: -0.5, city: "Oslo"}, {years: 0.5, city: "a"}, {years: 10, city: "Zed"}, {years: 50, city: "O'Neil"}, {years: 0.000001, city: "retail"}, {years: 50, city: "O'Neil"}, {years: 65, city: "O'Neil"}, {years: 1, city: "-"}, {years: 5, city: "é ü"}]}}, {shipment: {accounts: [{calc: {grade: [false], quota: [false], total: 1}, city: "3.5", net: "3.5", share: [33.333333333333333333333333333], totals: {band: 1}, years: 100}, {calc: {grade: [false], quota: [false], total: 1}, city: "", net: "", share: [333333.33333333333333333333333], totals: {band: 1}, years: 1000000}, {calc: {grade: [false], quota: [false], total: 1}, city: "-", net: "-", share: [3.3333333333333333333333333333], totals: {band: 1}, years: 10}, {calc: {grade: [false], quota: [false], total: 1}, city: "-", net: "-", share: [1.6666666666666666666666666667], totals: {band: 1}, years: 5}, {calc: {grade: [false], quota: [true], total: 1}, city: "Zed", net: "Zed", share: [0.0333333333333333333333333333], totals: {band: 1}, years: 0.1}, {calc: {grade: [false], quota: [true], total: 1}, city: "Oslo", net: "Oslo", share: [-0.1666666666666666666666666667], totals: {band: 1}, years: -0.5}, {calc: {grade: [false], quota: [true], total: 1}, city: "a", net: "a", share: [0.1666666666666666666666666667], totals: {band: 1}, years: 0.5}, {calc: {grade: [false], quota: [false], total: 1}, city: "Zed", net: "Zed", share: [3.3333333333333333333333333333], totals: {band: 1}, years: 10}, {calc: {grade: [false], quota: [false], total: 1}, city: "O'Neil", net: "O'Neil", share: [16.666666666666666666666666667], totals: {band: 1}, years: 50}, {calc: {grade: [false], quota: [true], total: 1}, city: "retail", net: "retail", share: [0.0000003333333333333333333333], totals: {band: 1}, years: 0.000001}, {calc: {grade: [false], quota: [false], total: 1}, city: "O'Neil", net: "O'Neil", share: [16.666666666666666666666666667], totals: {band: 1}, years: 50}, {calc: {grade: [false], quota: [false], total: 1}, city: "O'Neil", net: "O'Neil", share: [21.666666666666666666666666667], totals: {band: 1}, years: 65}, {calc: {grade: [false], quota: [true], total: 1}, city: "-", net: "-", share: [0.3333333333333333333333333333], totals: {band: 1}, years: 1}, {calc: {grade: [false], quota: [false], total: 1}, city: "é ü", net: "é ü", share: [1.6666666666666666666666666667], totals: {band: 1}, years: 5}], bucket: 1, code: null, limit: 50, score: 1}}], + [{shipment: {score: 123456789.123, limit: -0.01, code: "a-b-c", accounts: [{years: 65, city: "é ü"}, {years: 2, city: "x-y"}, {years: 250, city: "é ü"}]}}, {shipment: {accounts: [{calc: {grade: [false, false], quota: [false, false], total: -0.01}, city: "é ü", net: "é ü", share: [21.666666666666666666666666667, -0.01], totals: {band: 65}, years: 65}, {calc: {grade: [false, false], quota: [false, false], total: -0.01}, city: "x-y", net: "x-y", share: [0.6666666666666666666666666667, -0.01], totals: {band: 2}, years: 2}, {calc: {grade: [false, false], quota: [false, false], total: -0.01}, city: "é ü", net: "é ü", share: [83.33333333333333333333333333, -0.01], totals: {band: 250}, years: 250}], bucket: 123456789.123, code: "a-b-c", limit: -0.01, score: 123456789.123}}], + [{shipment: {limit: 2}}, {shipment: {bucket: null, limit: 2}}], + [{shipment: {score: 2, limit: 50, code: "12", accounts: [{years: 240, city: "a"}]}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [false, false], total: 2}, city: "a", net: "a", share: [80, 50], totals: {band: 2}, years: 240}], bucket: 2, code: "12", limit: 50, score: 2}}], + [{shipment: {score: 100, limit: 0.5, code: "-", accounts: [{years: 0, city: " pad "}]}}, {shipment: {accounts: [{calc: {grade: [false, true], quota: [true, false], total: 0}, city: " pad ", net: " pad ", share: [0, 0.5], totals: {band: 0}, years: 0}], bucket: 100, code: "-", limit: 0.5, score: 100}}], + ], +} + +// seed 342400 (attempt 0) +{ + name: "b 25: account/companies/parts + address: 1 expression, 1 match, 3 table; 1 root, 2 per-member, 0 top-level computed", + policy: { + models: {account: {balance: "number", flagged: "boolean", plan: "string(basic|plus|premium|trial)", companies: "company[]?", address: "address?"}, company: {amount: "number", priority: "boolean", parts: "part[]"}, part: {years: "number", age: "number"}, address: {days: "number", label: "string?", income: "number?"}}, + blocks: [ + {table: "t4", inputs: [null, "address.income"], outputs: ["address.segment[]", "address.penalty", "address.eligible"], rules: [ + ["", "", "(address.income ?? 0)", "", "address.days"], + ["address.income != null", "1", "1.5", "(address.label ?? '')", "(address.income ?? 0)"], + ["1000 == address.days", "10", "address.days", "(address.label ?? '')", "account.balance"], + ["(account.flagged and account.flagged)", "", "(address.income ?? 0)", "'ok'", "(address.income ?? 0)"], + ["", "250, 1.5", "account.balance", "(address.label ?? '')", "(address.income ?? 0)"], + ]}, + {match: "company.grade", arms: [["min([(account.address.days ?? 0), (account.address.days ?? 0), 1, (account.address.days ?? 0)]) < 3", "`${account.flagged}/${(company.priority ? account.balance : (account.address.income ?? 0))}`"], ["none(company.parts, #.age > #.age)", "string(account.balance)"], ["isNumeric((account.address.label ?? ''))", "(account.flagged ? (account.address.label ?? '') : 'a')"], ["", "(account.address.label ?? '')"]]}, + {table: "t2", hit: "collect", inputs: ["((account.address.days ?? 0) / 3)", "account.balance"], outputs: ["company.adjusted"], rules: [ + [">= 1", "<= 0.5", "company.amount"], + ["", "[0.25..91.25]", "company.amount"], + ]}, + {table: "t5", inputs: ["account.balance", "address.days"], outputs: ["address.calc.bonus"], rules: [ + ["[0.25..20.25]", "[100..566]", "account.flagged"], + ["<= 10", ">= 3", "account.flagged"], + ]}, + {expression: "account.surcharge", value: "filter((account.companies ?? []), #.amount < #.amount)"}, + ], + }, + cases: [ + [{account: {balance: 1.5, flagged: false, plan: "trial", companies: [], address: {days: 250, label: "Oslo", income: 250}}}, {account: {address: {calc: {bonus: false}, days: 250, eligible: 250, income: 250, label: "Oslo", penalty: "Oslo", segment: [250, 1.5]}, balance: 1.5, companies: [], flagged: false, plan: "trial", surcharge: []}}], + [{account: {balance: 1, flagged: true, plan: "basic", companies: [{amount: 0.25, priority: false, parts: [{years: -0.01, age: 0}, {years: 1e3, age: 3}]}, {amount: 0.000001, priority: true, parts: [{years: 10, age: 3}, {years: -1, age: 0.25}, {years: -0.01, age: -0.5}]}, {amount: 99999999999999999999, priority: false, parts: []}, {amount: 0.1, priority: true, parts: [{years: 1, age: 100}, {years: 5, age: 1e3}, {years: 1, age: 3}]}, {amount: 1000, priority: false, parts: [{years: 1e3, age: 1000000}, {years: 0.000001, age: 2.50}, {years: 5, age: 0.25}]}, {amount: 1, priority: false, parts: [{years: 102, age: 5}, {years: 10, age: 99.99}]}, {amount: 10, priority: false, parts: [{years: 0.5, age: 18}, {years: 0.000001, age: 1}]}, {amount: 99999999999999999999, priority: false, parts: []}, {amount: 5, priority: false, parts: [{years: 1000000, age: 10}, {years: 5, age: 99.99}, {years: 2, age: 1.5}]}, {amount: -1, priority: false, parts: []}, {amount: 10, priority: false, parts: [{years: 1, age: 65}, {years: 0, age: 18}]}], address: {days: 100, label: "US", income: 65}, extraField: {nested: true}}}, {account: {address: {calc: {bonus: true}, days: 100, eligible: 100, income: 65, label: "US", penalty: "ok", segment: [65, 65]}, balance: 1, companies: [{adjusted: [0.25], amount: 0.25, grade: "true/65", parts: [{age: 0, years: -0.01}, {age: 3, years: 1000}], priority: false}, {adjusted: [0.000001], amount: 0.000001, grade: "true/1", parts: [{age: 3, years: 10}, {age: 0.25, years: -1}, {age: -0.5, years: -0.01}], priority: true}, {adjusted: [99999999999999999999], amount: 99999999999999999999, grade: "true/65", parts: [], priority: false}, {adjusted: [0.1], amount: 0.1, grade: "true/1", parts: [{age: 100, years: 1}, {age: 1000, years: 5}, {age: 3, years: 1}], priority: true}, {adjusted: [1000], amount: 1000, grade: "true/65", parts: [{age: 1000000, years: 1000}, {age: 2.50, years: 0.000001}, {age: 0.25, years: 5}], priority: false}, {adjusted: [1], amount: 1, grade: "true/65", parts: [{age: 5, years: 102}, {age: 99.99, years: 10}], priority: false}, {adjusted: [10], amount: 10, grade: "true/65", parts: [{age: 18, years: 0.5}, {age: 1, years: 0.000001}], priority: false}, {adjusted: [99999999999999999999], amount: 99999999999999999999, grade: "true/65", parts: [], priority: false}, {adjusted: [5], amount: 5, grade: "true/65", parts: [{age: 10, years: 1000000}, {age: 99.99, years: 5}, {age: 1.5, years: 2}], priority: false}, {adjusted: [-1], amount: -1, grade: "true/65", parts: [], priority: false}, {adjusted: [10], amount: 10, grade: "true/65", parts: [{age: 65, years: 1}, {age: 18, years: 0}], priority: false}], extraField: {nested: true}, flagged: true, plan: "basic", surcharge: []}}], + [{account: {balance: 250, flagged: true, plan: "plus", companies: [{amount: 18, priority: false, parts: [{years: -1, age: 18}]}], address: {days: 1000000, label: "-", income: null}}}, {account: {address: {calc: {bonus: null}, days: 1000000, eligible: 1000000, income: null, label: "-", penalty: "ok", segment: [0, 0]}, balance: 250, companies: [{adjusted: [], amount: 18, grade: "true/0", parts: [{age: 18, years: -1}], priority: false}], flagged: true, plan: "plus", surcharge: []}}], + [{account: {balance: 0.000001, flagged: false, plan: "premium", companies: [{amount: -1, priority: false, parts: []}, {amount: 123456789.123, priority: false, parts: [{years: 1.5, age: 100}, {years: -0, age: 50}]}, {amount: 1000, priority: false, parts: []}], address: {days: -1, label: "Zed", income: 5}, extraField: {nested: true}}}, {account: {address: {calc: {bonus: null}, days: -1, eligible: -1, income: 5, label: "Zed", penalty: null, segment: [5]}, balance: 0.000001, companies: [{adjusted: [], amount: -1, grade: "false/5", parts: [], priority: false}, {adjusted: [], amount: 123456789.123, grade: "false/5", parts: [{age: 100, years: 1.5}, {age: 50, years: 0}], priority: false}, {adjusted: [], amount: 1000, grade: "false/5", parts: [], priority: false}], extraField: {nested: true}, flagged: false, plan: "premium", surcharge: []}}], + [{account: {balance: 0, flagged: true, plan: "trial", companies: [{amount: 0.25, priority: true, parts: [{years: 2, age: 1}, {years: 250, age: 3}, {years: 10, age: 2}]}, {amount: 5, priority: false, parts: [{years: 250, age: -500}]}], address: null}}, {account: {address: null, balance: 0, companies: [{adjusted: [], amount: 0.25, grade: "true/0", parts: [{age: 1, years: 2}, {age: 3, years: 250}, {age: 2, years: 10}], priority: true}, {adjusted: [], amount: 5, grade: "true/0", parts: [{age: -500, years: 250}], priority: false}], flagged: true, plan: "trial", surcharge: []}}], + [{account: {balance: 2, flagged: false, plan: "plus", companies: [], address: {days: 1000000, label: "a", income: 10}}}, {account: {address: {calc: {bonus: false}, days: 1000000, eligible: 1000000, income: 10, label: "a", penalty: null, segment: [10]}, balance: 2, companies: [], flagged: false, plan: "plus", surcharge: []}}], + [{account: {balance: 0.5, flagged: true, plan: "plus", companies: [{amount: 18, priority: false, parts: []}, {amount: 100, priority: false, parts: [{years: 10, age: 99.99}, {years: 1, age: 1000}]}, {amount: 0, priority: false, parts: [{years: -0.01, age: 1.5}, {years: 1e3, age: 1.5}]}, {amount: 3, priority: false, parts: [{years: 0.000001, age: 3}, {years: 1, age: 10}]}, {amount: 2.50, priority: true, parts: []}, {amount: 1, priority: true, parts: [{years: -1, age: 5}]}, {amount: 1, priority: true, parts: [{years: 1000, age: 5}]}, {amount: 99.99, priority: true, parts: [{years: 0.25, age: 1}]}, {amount: 0.25, priority: false, parts: [{years: 65, age: 99.99}, {years: 0.25, age: 0.25}]}, {amount: 0.25, priority: false, parts: []}, {amount: 1000, priority: true, parts: [{years: 10, age: 18}]}, {amount: 1, priority: true, parts: [{years: 0.000001, age: 1}, {years: 0.25, age: 0}]}], address: {days: 0.25, income: 2}}}, {account: {address: {calc: {bonus: null}, days: 0.25, eligible: 0.25, income: 2, penalty: "ok", segment: [2, 2]}, balance: 0.5, companies: [{adjusted: [18], amount: 18, grade: "true/2", parts: [], priority: false}, {adjusted: [100], amount: 100, grade: "true/2", parts: [{age: 99.99, years: 10}, {age: 1000, years: 1}], priority: false}, {adjusted: [0], amount: 0, grade: "true/2", parts: [{age: 1.5, years: -0.01}, {age: 1.5, years: 1000}], priority: false}, {adjusted: [3], amount: 3, grade: "true/2", parts: [{age: 3, years: 0.000001}, {age: 10, years: 1}], priority: false}, {adjusted: [2.50], amount: 2.50, grade: "true/0.5", parts: [], priority: true}, {adjusted: [1], amount: 1, grade: "true/0.5", parts: [{age: 5, years: -1}], priority: true}, {adjusted: [1], amount: 1, grade: "true/0.5", parts: [{age: 5, years: 1000}], priority: true}, {adjusted: [99.99], amount: 99.99, grade: "true/0.5", parts: [{age: 1, years: 0.25}], priority: true}, {adjusted: [0.25], amount: 0.25, grade: "true/2", parts: [{age: 99.99, years: 65}, {age: 0.25, years: 0.25}], priority: false}, {adjusted: [0.25], amount: 0.25, grade: "true/2", parts: [], priority: false}, {adjusted: [1000], amount: 1000, grade: "true/0.5", parts: [{age: 18, years: 10}], priority: true}, {adjusted: [1], amount: 1, grade: "true/0.5", parts: [{age: 1, years: 0.000001}, {age: 0, years: 0.25}], priority: true}], flagged: true, plan: "plus", surcharge: []}}], + [{account: {balance: 0, flagged: true, plan: "basic", companies: [{amount: -0.01, priority: true, parts: [{years: 250, age: 1e3}]}, {amount: 0.1, priority: false, parts: [{years: 173, age: 0.1}, {years: 0.25, age: -0}]}], address: {days: 1, label: "x-y", income: -1}}}, {account: {address: {calc: {bonus: null}, days: 1, eligible: 1, income: -1, label: "x-y", penalty: "ok", segment: [-1, -1]}, balance: 0, companies: [{adjusted: [], amount: -0.01, grade: "true/0", parts: [{age: 1000, years: 250}], priority: true}, {adjusted: [], amount: 0.1, grade: "true/-1", parts: [{age: 0.1, years: 173}, {age: 0, years: 0.25}], priority: false}], flagged: true, plan: "basic", surcharge: []}}], + [{account: {balance: 0.25, flagged: true, plan: "plus", companies: [{amount: -1, priority: true, parts: [{years: 10, age: 5}, {years: 1e3, age: 3}]}, {amount: 0, priority: false, parts: [{years: 10, age: 1}, {years: 2, age: 65}]}], address: {days: 5, label: "12", income: 0}, extraField: "x"}}, {account: {address: {calc: {bonus: true}, days: 5, eligible: 5, income: 0, label: "12", penalty: "ok", segment: [0, 0]}, balance: 0.25, companies: [{adjusted: [-1, -1], amount: -1, grade: "true/0.25", parts: [{age: 5, years: 10}, {age: 3, years: 1000}], priority: true}, {adjusted: [0, 0], amount: 0, grade: "true/0", parts: [{age: 1, years: 10}, {age: 65, years: 2}], priority: false}], extraField: "x", flagged: true, plan: "plus", surcharge: []}}], + [{account: {balance: 2, flagged: false, plan: "basic", companies: [{amount: 0.25, priority: false, parts: [{years: 2, age: 1}, {years: 123456789.123, age: 1e3}]}, {amount: 1.5, priority: false, parts: [{years: 1.5, age: -0.01}]}], address: {days: 50, label: "gold", income: 0.5}}}, {account: {address: {calc: {bonus: false}, days: 50, eligible: 50, income: 0.5, label: "gold", penalty: null, segment: [0.5]}, balance: 2, companies: [{adjusted: [0.25], amount: 0.25, grade: "false/0.5", parts: [{age: 1, years: 2}, {age: 1000, years: 123456789.123}], priority: false}, {adjusted: [1.5], amount: 1.5, grade: "false/0.5", parts: [{age: -0.01, years: 1.5}], priority: false}], flagged: false, plan: "basic", surcharge: []}}], + [{account: {balance: 5, flagged: false, plan: "premium", companies: [], address: {days: 2.50, label: "é ü", income: 0.25}}}, {account: {address: {calc: {bonus: null}, days: 2.50, eligible: 2.50, income: 0.25, label: "é ü", penalty: null, segment: [0.25]}, balance: 5, companies: [], flagged: false, plan: "premium", surcharge: []}}], + [{account: {balance: 99.99, flagged: true, plan: "trial", companies: [{amount: 0.5, priority: true, parts: [{years: 1000000, age: -0}, {years: 10, age: 5}]}, {amount: 18, priority: true, parts: []}, {amount: 1000, priority: false, parts: [{years: 1, age: 1.5}, {years: 2, age: -0}, {years: -0, age: 123456789.123}]}, {amount: 2.50, priority: false, parts: []}, {amount: 2.50, priority: true, parts: [{years: -0.5, age: 0.1}]}], address: null}}, {account: {address: null, balance: 99.99, companies: [{adjusted: [], amount: 0.5, grade: "true/99.99", parts: [{age: 0, years: 1000000}, {age: 5, years: 10}], priority: true}, {adjusted: [], amount: 18, grade: "true/99.99", parts: [], priority: true}, {adjusted: [], amount: 1000, grade: "true/0", parts: [{age: 1.5, years: 1}, {age: 0, years: 2}, {age: 123456789.123, years: 0}], priority: false}, {adjusted: [], amount: 2.50, grade: "true/0", parts: [], priority: false}, {adjusted: [], amount: 2.50, grade: "true/99.99", parts: [{age: 0.1, years: -0.5}], priority: true}], flagged: true, plan: "trial", surcharge: []}}], + [{account: {balance: 1, flagged: true, plan: "premium", companies: [], address: null}}, {account: {address: null, balance: 1, companies: [], flagged: true, plan: "premium", surcharge: []}}], + ], +} + +// seed 342500 (attempt 0) +{ + name: "b 26: tenant/parcels/drivers: 2 assertion, 3 expression, 1 match, 2 table; 6 root, 5 per-member, 1 top-level computed", + policy: { + models: {tenant: {qty: "number", urgent: "boolean", plan: "string(basic|plus|premium|trial)", age: "number?", channel: "string", openedAt: "date", parcels: "parcel[]"}, parcel: {score: "number", active: "boolean?", status: "string(open|closed|pending)?", drivers: "driver[]"}, driver: {qty: "number", code: "string?"}}, + blocks: [ + {table: "t4", inputs: ["tenant.band", "tenant.plan", "tenant.urgent"], outputs: ["tenant.decision", "tenant.calc.flag", "tenant.calc.health"], rules: [ + ["'high', 'ok'", "", "true", "number(string(tenant.qty))", "tenant.qty", "tenant.openedAt.format('%Y-%m')"], + ["'VIP', 'VIP'", "", "", "tenant.qty", "2", "'low'"], + ["", "'plus', 'premium'", "true", "", "0.5", "tenant.channel"], + ["", "", "false", "tenant.qty", "tenant.qty", "tenant.channel"], + ["'ok'", "'premium', 'basic'", "true", "", "trunc(tenant.qty)", "tenant.band"], + ["", "", "", "tenant.qty", "(tenant.qty + 0)", "tenant.band"], + ]}, + {match: "tenant.band", arms: [["string((tenant.age ?? 0)) != 'Oslo'", "string(((tenant.age ?? 0) + tenant.qty))"], ["(tenant.plan != 'basic' and tenant.age == null)", "tenant.channel"], ["contains(['VIP', 'none', ''], tenant.channel)", "`${'x'}/${tenant.urgent}`"], ["", "'high'"]]}, + {table: "t6", inputs: ["avg([(tenant.calc.flag ?? 0), (tenant.calc.flag ?? 0), (tenant.age ?? 0), (tenant.calc.flag ?? 0)])", "tenant.adjusted"], outputs: ["tenant.summary"], rules: [ + ["", "false", "tenant.qty"], + ["!= 10", "false", "(tenant.age ?? 0)"], + ]}, + {assertion: "parcel.grade", conditions: [["and", "(tenant.summary ?? 0) <= tenant.qty", 0], ["or", "(tenant.age ?? 0) in [4..53)", 1]]}, + {expression: "tenant.adjusted", value: "tenant.channel == 'ok'"}, + {expression: "parcel.net", value: "{ok: 'high', n: (tenant.age ?? 0)}"}, + {assertion: "scores.ok", conditions: [["or", "all(tenant.parcels, ((#.active ?? false) or (#.active ?? false)))", 1], ["and", "(tenant.calc.health ?? '') != 'A1'", 0], ["or", "(tenant.adjusted or tenant.urgent)", 0], ["and", "(tenant.urgent and tenant.adjusted)", 0], "(isNumeric(tenant.band) or isNumeric((tenant.calc.health ?? '')))"]}, + {expression: "parcel.meta.rank", value: "((1) / (abs(parcel.score) + 1) / -6)"}, + ], + }, + cases: [ + [{tenant: {qty: 2, urgent: false, plan: "basic", age: 2.50, channel: "high", openedAt: "2024-02-29", parcels: [{score: 0, status: "open", drivers: [{qty: 0.000001, code: "retail"}, {qty: 99.99, code: "a-b-c"}]}, {score: 0.1, drivers: [{qty: 7.25, code: "-"}]}, {score: 1000, active: false, status: null, drivers: []}, {score: -0.01, active: null, status: "open", drivers: [{qty: 0.5, code: null}, {qty: 65}, {qty: 0.5, code: "A1"}]}]}}, {scores: {ok: false}, tenant: {adjusted: false, age: 2.50, band: "4.50", calc: {flag: 2, health: "high"}, channel: "high", decision: 2, openedAt: "2024-02-29", parcels: [{drivers: [{code: "retail", qty: 0.000001}, {code: "a-b-c", qty: 99.99}], grade: false, meta: {rank: -0.1666666666666666666666666667}, net: {n: 2.50, ok: "high"}, score: 0, status: "open"}, {drivers: [{code: "-", qty: 7.25}], grade: false, meta: {rank: -0.1515151515151515151515151515}, net: {n: 2.50, ok: "high"}, score: 0.1}, {active: false, drivers: [], grade: false, meta: {rank: -0.0001665001665001665001665002}, net: {n: 2.50, ok: "high"}, score: 1000, status: null}, {active: null, drivers: [{code: null, qty: 0.5}, {qty: 65}, {code: "A1", qty: 0.5}], grade: false, meta: {rank: -0.165016501650165016501650165}, net: {n: 2.50, ok: "high"}, score: -0.01, status: "open"}], plan: "basic", qty: 2, summary: 2, urgent: false}}], + [{tenant: {qty: 1, urgent: false, plan: "trial", age: 123456789.123, channel: "VIP", openedAt: "2025-03-20T10:15:30Z", parcels: [{score: 1000, active: false, status: "closed", drivers: [{qty: 1000, code: "3.5"}]}, {score: 50, active: false, status: "open", drivers: []}, {score: 10, active: true, status: "pending", drivers: [{qty: -0, code: "high"}, {qty: 2, code: " pad "}]}, {score: 18, active: false, status: "open", drivers: [{qty: 50, code: "gold"}]}]}}, {scores: {ok: false}, tenant: {adjusted: false, age: 123456789.123, band: "123456790.123", calc: {flag: 1, health: "VIP"}, channel: "VIP", decision: 1, openedAt: "2025-03-20T10:15:30Z", parcels: [{active: false, drivers: [{code: "3.5", qty: 1000}], grade: false, meta: {rank: -0.0001665001665001665001665002}, net: {n: 123456789.123, ok: "high"}, score: 1000, status: "closed"}, {active: false, drivers: [], grade: false, meta: {rank: -0.0032679738562091503267973856}, net: {n: 123456789.123, ok: "high"}, score: 50, status: "open"}, {active: true, drivers: [{code: "high", qty: 0}, {code: " pad ", qty: 2}], grade: false, meta: {rank: -0.0151515151515151515151515152}, net: {n: 123456789.123, ok: "high"}, score: 10, status: "pending"}, {active: false, drivers: [{code: "gold", qty: 50}], grade: false, meta: {rank: -0.0087719298245614035087719298}, net: {n: 123456789.123, ok: "high"}, score: 18, status: "open"}], plan: "trial", qty: 1, summary: 1, urgent: false}}], + [{tenant: {qty: 2.50, urgent: true, plan: "basic", age: 99.99, channel: "gold", openedAt: "2030-12-31", parcels: []}}, {scores: {ok: true}, tenant: {adjusted: false, age: 99.99, band: "102.49", calc: {flag: 2.50, health: "102.49"}, channel: "gold", decision: 2.50, openedAt: "2030-12-31", parcels: [], plan: "basic", qty: 2.50, summary: 2.50, urgent: true}}], + [{tenant: {qty: 0.5, urgent: false, plan: "basic", age: 0, channel: "low", openedAt: "2024-01-01", parcels: [{score: 250, active: false, status: "open", drivers: []}, {score: 65, active: true, status: "open", drivers: [{qty: 2, code: "high"}]}, {score: 7.25, active: false, status: "open", drivers: [{qty: 10, code: "Oslo"}, {qty: 2, code: "x"}, {qty: 1000000, code: "ok"}]}, {score: 99.99, active: true, status: "closed", drivers: [{qty: -0.5, code: "DE"}]}]}}, {scores: {ok: false}, tenant: {adjusted: false, age: 0, band: "0.5", calc: {flag: 0.5, health: "low"}, channel: "low", decision: 0.5, openedAt: "2024-01-01", parcels: [{active: false, drivers: [], grade: false, meta: {rank: -0.0006640106241699867197875166}, net: {n: 0, ok: "high"}, score: 250, status: "open"}, {active: true, drivers: [{code: "high", qty: 2}], grade: false, meta: {rank: -0.0025252525252525252525252525}, net: {n: 0, ok: "high"}, score: 65, status: "open"}, {active: false, drivers: [{code: "Oslo", qty: 10}, {code: "x", qty: 2}, {code: "ok", qty: 1000000}], grade: false, meta: {rank: -0.0202020202020202020202020202}, net: {n: 0, ok: "high"}, score: 7.25, status: "open"}, {active: true, drivers: [{code: "DE", qty: -0.5}], grade: false, meta: {rank: -0.0016503284153546555764597155}, net: {n: 0, ok: "high"}, score: 99.99, status: "closed"}], plan: "basic", qty: 0.5, summary: 0.5, urgent: false}}], + [{tenant: {qty: 2, urgent: "true", plan: "basic", age: 99.99, channel: "VIP", openedAt: "1990-06-15", parcels: [{score: -0.01, active: false, status: "open", drivers: [{qty: -0.01, code: "none"}, {qty: 0.5, code: "high"}]}, {score: 123456789.123, active: true, status: "pending", drivers: []}, {score: 1000, active: false, status: "pending", drivers: []}, {score: 10, active: false, status: "open", drivers: [{qty: 7.25, code: "abc"}, {qty: 1e3, code: "x"}, {qty: 0.000001, code: "日本"}]}, {score: 1000, active: false, status: "closed", drivers: [{qty: 1e3, code: "high"}]}]}}, "!error: InputValidationFailed"], + [{tenant: {qty: -500, urgent: true, plan: "premium", age: 1, channel: "retail", openedAt: "2030-12-31", parcels: [{score: 0.5, active: true, status: "pending", drivers: []}, {score: 50, active: false, status: "open", drivers: []}, {score: 10, active: false, status: "pending", drivers: [{qty: -500, code: "US"}, {qty: 0.000001, code: "none"}, {qty: 0.5, code: "-"}]}]}}, {scores: {ok: true}, tenant: {adjusted: false, age: 1, band: "-499", calc: {flag: 0.5, health: "retail"}, channel: "retail", decision: -500, openedAt: "2030-12-31", parcels: [{active: true, drivers: [], grade: false, meta: {rank: -0.1111111111111111111111111111}, net: {n: 1, ok: "high"}, score: 0.5, status: "pending"}, {active: false, drivers: [], grade: false, meta: {rank: -0.0032679738562091503267973856}, net: {n: 1, ok: "high"}, score: 50, status: "open"}, {active: false, drivers: [{code: "US", qty: -500}, {code: "none", qty: 0.000001}, {code: "-", qty: 0.5}], grade: false, meta: {rank: -0.0151515151515151515151515152}, net: {n: 1, ok: "high"}, score: 10, status: "pending"}], plan: "premium", qty: -500, summary: -500, urgent: true}}], + [{tenant: {qty: 5, urgent: false, plan: "premium", age: 1000000, channel: "ok", openedAt: "2025-03-20T10:15:30Z", parcels: [{score: 10, active: true, status: "open", drivers: [{qty: -0, code: "VIP"}]}]}}, {scores: {ok: true}, tenant: {adjusted: true, age: 1000000, band: "1000005", calc: {flag: 5, health: "ok"}, channel: "ok", decision: 5, openedAt: "2025-03-20T10:15:30Z", parcels: [{active: true, drivers: [{code: "VIP", qty: 0}], grade: false, meta: {rank: -0.0151515151515151515151515152}, net: {n: 1000000, ok: "high"}, score: 10, status: "open"}], plan: "premium", qty: 5, summary: null, urgent: false}}], + [{tenant: {qty: 1000, urgent: false, plan: "trial", age: 2, channel: "Zed", openedAt: "2030-12-31", parcels: [{score: 10, active: false, status: "open", drivers: []}, {score: 99999999999999999999, active: true, status: "open", drivers: [{qty: 123456789.123, code: "-"}]}, {score: -0.5, active: false, status: "pending", drivers: [{qty: 100, code: "-"}, {qty: 1000, code: "A1"}]}, {score: 10, active: false, status: "open", drivers: [{qty: 450, code: "Zed"}, {qty: -1, code: "a"}]}, {score: 7.25, active: false, status: "closed", drivers: [{qty: 10, code: "high"}, {qty: 1e3, code: "12"}, {qty: 0, code: ""}]}]}}, {scores: {ok: false}, tenant: {adjusted: false, age: 2, band: "1002", calc: {flag: 1000, health: "Zed"}, channel: "Zed", decision: 1000, openedAt: "2030-12-31", parcels: [{active: false, drivers: [], grade: false, meta: {rank: -0.0151515151515151515151515152}, net: {n: 2, ok: "high"}, score: 10, status: "open"}, {active: true, drivers: [{code: "-", qty: 123456789.123}], grade: false, meta: {rank: -0.0000000000000000000016666667}, net: {n: 2, ok: "high"}, score: 99999999999999999999, status: "open"}, {active: false, drivers: [{code: "-", qty: 100}, {code: "A1", qty: 1000}], grade: false, meta: {rank: -0.1111111111111111111111111111}, net: {n: 2, ok: "high"}, score: -0.5, status: "pending"}, {active: false, drivers: [{code: "Zed", qty: 450}, {code: "a", qty: -1}], grade: false, meta: {rank: -0.0151515151515151515151515152}, net: {n: 2, ok: "high"}, score: 10, status: "open"}, {active: false, drivers: [{code: "high", qty: 10}, {code: "12", qty: 1000}, {code: "", qty: 0}], grade: false, meta: {rank: -0.0202020202020202020202020202}, net: {n: 2, ok: "high"}, score: 7.25, status: "closed"}], plan: "trial", qty: 1000, summary: 1000, urgent: false}}], + [{tenant: {qty: 0, urgent: false, plan: "basic", age: 7.25, channel: "high", openedAt: "2000-01-01", parcels: [{score: 10, active: true, status: "closed", drivers: [{qty: 10, code: "O'Neil"}, {qty: -0, code: "none"}]}, {score: 65, active: true, status: "closed", drivers: [{qty: 0.5, code: "high"}]}, {score: -0, active: false, status: "open", drivers: [{qty: 10, code: "é ü"}]}, {score: 0, active: true, status: "closed", drivers: [{qty: 10, code: "A1"}, {qty: 10, code: "VIP"}]}, {score: 1000000, active: true, status: "closed", drivers: [{qty: -0, code: "retail"}, {qty: 1000, code: "3.5"}]}]}}, {scores: {ok: false}, tenant: {adjusted: false, age: 7.25, band: "7.25", calc: {flag: 0, health: "high"}, channel: "high", decision: 0, openedAt: "2000-01-01", parcels: [{active: true, drivers: [{code: "O'Neil", qty: 10}, {code: "none", qty: 0}], grade: true, meta: {rank: -0.0151515151515151515151515152}, net: {n: 7.25, ok: "high"}, score: 10, status: "closed"}, {active: true, drivers: [{code: "high", qty: 0.5}], grade: true, meta: {rank: -0.0025252525252525252525252525}, net: {n: 7.25, ok: "high"}, score: 65, status: "closed"}, {active: false, drivers: [{code: "é ü", qty: 10}], grade: true, meta: {rank: -0.1666666666666666666666666667}, net: {n: 7.25, ok: "high"}, score: 0, status: "open"}, {active: true, drivers: [{code: "A1", qty: 10}, {code: "VIP", qty: 10}], grade: true, meta: {rank: -0.1666666666666666666666666667}, net: {n: 7.25, ok: "high"}, score: 0, status: "closed"}, {active: true, drivers: [{code: "retail", qty: 0}, {code: "3.5", qty: 1000}], grade: true, meta: {rank: -0.0000001666665000001666665}, net: {n: 7.25, ok: "high"}, score: 1000000, status: "closed"}], plan: "basic", qty: 0, summary: 0, urgent: false}}], + [{tenant: {qty: 10, urgent: false, plan: "basic", age: 55, channel: "日本", openedAt: "1990-06-15", parcels: []}}, {scores: {ok: false}, tenant: {adjusted: false, age: 55, band: "65", calc: {flag: 10, health: "日本"}, channel: "日本", decision: 10, openedAt: "1990-06-15", parcels: [], plan: "basic", qty: 10, summary: 10, urgent: false}}], + [{tenant: {qty: 1000, urgent: false, plan: "trial", channel: "gold", openedAt: "2025-03-20", parcels: []}}, {scores: {ok: false}, tenant: {adjusted: false, band: "1000", calc: {flag: 1000, health: "gold"}, channel: "gold", decision: 1000, openedAt: "2025-03-20", parcels: [], plan: "trial", qty: 1000, summary: 1000, urgent: false}}], + [{tenant: {qty: 2, urgent: true, plan: "trial", age: 1e3, channel: "VIP", openedAt: "2024-01-01", parcels: [{score: 1000000, active: true, status: "closed", drivers: [{qty: -0, code: "A1"}, {qty: 1000}]}, {score: 10, active: true, status: "pending", drivers: [{qty: -0.5, code: "12"}, {qty: 10, code: "a-b-c"}]}]}}, {scores: {ok: true}, tenant: {adjusted: false, age: 1000, band: "1002", calc: {flag: 2, health: "1002"}, channel: "VIP", decision: 2, openedAt: "2024-01-01", parcels: [{active: true, drivers: [{code: "A1", qty: 0}, {qty: 1000}], grade: false, meta: {rank: -0.0000001666665000001666665}, net: {n: 1000, ok: "high"}, score: 1000000, status: "closed"}, {active: true, drivers: [{code: "12", qty: -0.5}, {code: "a-b-c", qty: 10}], grade: false, meta: {rank: -0.0151515151515151515151515152}, net: {n: 1000, ok: "high"}, score: 10, status: "pending"}], plan: "trial", qty: 2, summary: 2, urgent: true}}], + [{tenant: {qty: 99.99, urgent: false, plan: "basic", age: 0.000001, channel: "ok", openedAt: "2030-12-31", parcels: []}}, {scores: {ok: true}, tenant: {adjusted: true, age: 0.000001, band: "99.990001", calc: {flag: 99.99, health: "ok"}, channel: "ok", decision: 99.99, openedAt: "2030-12-31", parcels: [], plan: "basic", qty: 99.99, summary: null, urgent: false}}], + [{tenant: {qty: 2.50, urgent: true, plan: "basic", age: null, channel: "VIP", openedAt: "2024-02-29", parcels: [{score: 1, active: true, drivers: [{qty: -0.5, code: "none"}]}]}}, {scores: {ok: true}, tenant: {adjusted: false, age: null, band: "2.50", calc: {flag: 2.50, health: "2.50"}, channel: "VIP", decision: 2.50, openedAt: "2024-02-29", parcels: [{active: true, drivers: [{code: "none", qty: -0.5}], grade: false, meta: {rank: -0.0833333333333333333333333333}, net: {n: 0, ok: "high"}, score: 1}], plan: "basic", qty: 2.50, summary: 2.50, urgent: true}}], + [{tenant: {qty: 65, urgent: true, plan: "trial", age: 1000, channel: "VIP", openedAt: "2024-02-29", parcels: [{score: 1, active: true, status: "closed", drivers: []}]}}, {scores: {ok: true}, tenant: {adjusted: false, age: 1000, band: "1065", calc: {flag: 65, health: "1065"}, channel: "VIP", decision: 65, openedAt: "2024-02-29", parcels: [{active: true, drivers: [], grade: false, meta: {rank: -0.0833333333333333333333333333}, net: {n: 1000, ok: "high"}, score: 1, status: "closed"}], plan: "trial", qty: 65, summary: 65, urgent: true}}], + [{tenant: {qty: 1, urgent: false, plan: "basic", channel: "日本", openedAt: "2024-02-29", parcels: [{score: 2, active: false, drivers: [{qty: -0.01, code: "A1"}]}, {score: 10, active: false, drivers: [{qty: 99.99}, {qty: 100}]}]}}, {scores: {ok: false}, tenant: {adjusted: false, band: "1", calc: {flag: 1, health: "日本"}, channel: "日本", decision: 1, openedAt: "2024-02-29", parcels: [{active: false, drivers: [{code: "A1", qty: -0.01}], grade: false, meta: {rank: -0.0555555555555555555555555556}, net: {n: 0, ok: "high"}, score: 2}, {active: false, drivers: [{qty: 99.99}, {qty: 100}], grade: false, meta: {rank: -0.0151515151515151515151515152}, net: {n: 0, ok: "high"}, score: 10}], plan: "basic", qty: 1, summary: 1, urgent: false}}], + [{tenant: {qty: 1, urgent: true, plan: "plus", channel: "ok", openedAt: "1990-06-15", parcels: [{score: 7.25, active: true, status: "open", drivers: [{qty: 123456789.123}, {qty: 65}, {qty: 50, code: "high"}]}, {score: 0.5, active: null, drivers: [{qty: -1, code: null}]}, {score: 18, active: false, status: "pending", drivers: [{qty: 0.5}, {qty: 0, code: "VIP"}]}, {score: -0.5, active: false, drivers: [{qty: 7.25, code: null}, {qty: 250}]}]}}, {scores: {ok: true}, tenant: {adjusted: true, band: "1", calc: {flag: 0.5, health: "ok"}, channel: "ok", decision: 1, openedAt: "1990-06-15", parcels: [{active: true, drivers: [{qty: 123456789.123}, {qty: 65}, {code: "high", qty: 50}], grade: false, meta: {rank: -0.0202020202020202020202020202}, net: {n: 0, ok: "high"}, score: 7.25, status: "open"}, {active: null, drivers: [{code: null, qty: -1}], grade: false, meta: {rank: -0.1111111111111111111111111111}, net: {n: 0, ok: "high"}, score: 0.5}, {active: false, drivers: [{qty: 0.5}, {code: "VIP", qty: 0}], grade: false, meta: {rank: -0.0087719298245614035087719298}, net: {n: 0, ok: "high"}, score: 18, status: "pending"}, {active: false, drivers: [{code: null, qty: 7.25}, {qty: 250}], grade: false, meta: {rank: -0.1111111111111111111111111111}, net: {n: 0, ok: "high"}, score: -0.5}], plan: "plus", qty: 1, summary: null, urgent: true}}], + [{tenant: {qty: 1, urgent: true, plan: "basic", age: null, channel: "é ü", openedAt: "2030-12-31", parcels: [{score: -0.5, active: false, drivers: [{qty: -0.01}, {qty: 5, code: "a"}]}, {score: 99.99, active: null, status: "open", drivers: [{qty: 0.000001, code: "retail"}]}]}}, {scores: {ok: true}, tenant: {adjusted: false, age: null, band: "1", calc: {flag: 1, health: "1"}, channel: "é ü", decision: 1, openedAt: "2030-12-31", parcels: [{active: false, drivers: [{qty: -0.01}, {code: "a", qty: 5}], grade: false, meta: {rank: -0.1111111111111111111111111111}, net: {n: 0, ok: "high"}, score: -0.5}, {active: null, drivers: [{code: "retail", qty: 0.000001}], grade: false, meta: {rank: -0.0016503284153546555764597155}, net: {n: 0, ok: "high"}, score: 99.99, status: "open"}], plan: "basic", qty: 1, summary: 1, urgent: true}}], + ], +} + +// seed 342600 (attempt 0) +{ + name: "b 27: applicant/companies + contact: 1 assertion, 2 expression, 4 match, 1 table; 3 root, 5 per-member, 0 top-level computed", + policy: { + models: {applicant: {income: "number", limit: "number?", name: "string", kind: "string(retail|corporate)", companies: "company[]", contact: "contactInfo"}, company: {amount: "number", weight: "number?", status: "string(open|closed|pending)?", sku: "string"}, contactInfo: {days: "number?"}}, + blocks: [ + {match: "company.calc.exposure", arms: [["some(applicant.companies, matches(#.sku, 'a'))", "(applicant.limit ?? 0) <= 100"], ["applicant.limit == null", "(company.status ?? '') != 'closed'"], ["", "(company.weight ?? 0) <= 2"]]}, + {match: "company.health", arms: [["matches(company.sku, '^.{2,}$')", "company.sku"], ["", "`${applicant.income}/${company.calc.exposure}`"]]}, + {expression: "applicant.totals.flag", value: "matches((split(applicant.name, '-')[1] ?? 'none'), '^[A-Z]')"}, + {match: "applicant.capped", arms: [["contains(['a', 'ok', ''], applicant.name)", "((applicant.totals.flag ? applicant.name : 'DE') + '-' + (applicant.name + '-' + applicant.name))"], ["(applicant.totals.flag and applicant.totals.flag)", "`${applicant.name}/${((applicant.contact.days ?? 0) - 1000)}`"], ["matches(applicant.name, 'a')", "applicant.name"], ["", "applicant.name"]]}, + {assertion: "applicant.fee", conditions: [["and", "matches(applicant.capped, '[0-9]$')", 2], ["or", "len((applicant.totals.flag ? applicant.capped : applicant.name)) > 0", 1], ["and", "all(applicant.companies, contains(#.health, 'A1'))", 1]]}, + {match: "company.adjusted", arms: [["not (applicant.income > company.amount)", "'retail'"], ["startsWith((applicant.name + '-' + company.health), 'retail')", "(split(company.health, '-')[1] ?? 'none')"], ["(applicant.contact.days ?? 0) in [14..113)", "applicant.name"], ["isNumeric(company.sku)", "applicant.name"], ["", "company.sku"]]}, + {table: "t7", inputs: ["company.calc.exposure", "company.sku"], outputs: ["company.summary[]", "company.penalty"], rules: [ + ["false", "$ != 'US'", "", "(applicant.limit ?? 0)"], + ["true", "startsWith($, 'ok')", "", "0.25"], + ["true", "startsWith($, 'ok')", "(company.weight ?? 0)", "0"], + ["", "'gold'", "1000", "(applicant.contact.days ?? 0)"], + ["", "'high', 'x'", "company.amount", ""], + ["false", "'retail', 'low'", "applicant.income", "applicant.income"], + ]}, + {expression: "contactInfo.flags.segment", value: "(min([abs((avg(map(applicant.companies, trunc((#.penalty ?? 0)))) ?? 0)), 1000]) ^ 1)"}, + ], + }, + cases: [ + [{applicant: {income: 0.5, limit: 2.50, name: "gold", kind: "corporate", companies: [], contact: {days: 0.1}}}, "!error: ExpressionFailed"], + [{applicant: {income: 65, limit: 0, name: "日本", kind: "retail", companies: [{amount: 0.25, weight: 2, status: "open", sku: "Zed"}], contact: {days: 99.99}}}, {applicant: {capped: "日本", companies: [{adjusted: "日本", amount: 0.25, calc: {exposure: true}, health: "Zed", penalty: null, sku: "Zed", status: "open", summary: [], weight: 2}], contact: {days: 99.99, flags: {segment: 0}}, fee: false, income: 65, kind: "retail", limit: 0, name: "日本", totals: {flag: false}}}], + [{applicant: {income: -0, limit: 5, name: "retail", kind: "retail", companies: [{amount: 0.25, weight: 0.000001, status: "open", sku: "A1"}], contact: {days: 1000000}}}, {applicant: {capped: "retail", companies: [{adjusted: "retail", amount: 0.25, calc: {exposure: true}, health: "A1", penalty: null, sku: "A1", status: "open", summary: [], weight: 0.000001}], contact: {days: 1000000, flags: {segment: 0}}, fee: true, income: 0, kind: "retail", limit: 5, name: "retail", totals: {flag: false}}}], + [{applicant: {income: 0.1, limit: 123456789.123, name: "x", kind: "retail", companies: [{amount: -0.01, weight: 10, status: "open", sku: "US"}, {amount: 1000, weight: 2, status: "closed", sku: "3.5"}], contact: {days: 0.1}}}, {applicant: {capped: "x", companies: [{adjusted: "US", amount: -0.01, calc: {exposure: false}, health: "US", penalty: null, sku: "US", status: "open", summary: [], weight: 10}, {adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "3.5", penalty: null, sku: "3.5", status: "closed", summary: [], weight: 2}], contact: {days: 0.1, flags: {segment: 0}}, fee: false, income: 0.1, kind: "retail", limit: 123456789.123, name: "x", totals: {flag: false}}}], + [{applicant: {income: 1000, limit: 0.5, name: "retail", kind: "retail", companies: [{amount: -500, status: null, sku: "NL"}, {amount: 2, weight: -0.5, sku: "VIP"}, {amount: 2, weight: 99999999999999999999, status: "pending", sku: "ok"}, {amount: 2.50, weight: 1000, status: "closed", sku: "low"}], contact: {days: null}}}, {applicant: {capped: "retail", companies: [{adjusted: "none", amount: -500, calc: {exposure: true}, health: "NL", penalty: null, sku: "NL", status: null, summary: []}, {adjusted: "none", amount: 2, calc: {exposure: true}, health: "VIP", penalty: null, sku: "VIP", summary: [], weight: -0.5}, {adjusted: "none", amount: 2, calc: {exposure: false}, health: "ok", penalty: 0.5, sku: "ok", status: "pending", summary: [], weight: 99999999999999999999}, {adjusted: "none", amount: 2.50, calc: {exposure: false}, health: "low", penalty: 0.5, sku: "low", status: "closed", summary: [1000], weight: 1000}], contact: {days: null, flags: {segment: 0}}, fee: false, income: 1000, kind: "retail", limit: 0.5, name: "retail", totals: {flag: false}}}], + [{applicant: {income: 250, limit: 71, name: "VIP", kind: "retail", companies: [{amount: 1, weight: 0.1, status: "open", sku: "12"}], contact: {}}}, {applicant: {capped: "VIP", companies: [{adjusted: "VIP", amount: 1, calc: {exposure: true}, health: "12", penalty: null, sku: "12", status: "open", summary: [], weight: 0.1}], contact: {flags: {segment: 0}}, fee: false, income: 250, kind: "retail", limit: 71, name: "VIP", totals: {flag: false}}}], + [{applicant: {income: 99999999999999999999, limit: 5, name: "a", kind: "corporate", companies: [{amount: 2, weight: 100, status: "open", sku: "VIP"}, {amount: 99999999999999999999, weight: 1000, status: "open", sku: "a-b-c"}, {amount: -0.5, weight: 10, status: "closed", sku: "x-y"}, {amount: 100, weight: -0.5, status: "open", sku: "DE"}, {amount: 2, weight: -500, status: "closed", sku: "Oslo"}, {amount: 99.99, weight: 100, status: "closed", sku: "ok"}, {amount: -0.01, weight: 1000000, status: "pending", sku: "low"}, {amount: 1, weight: 100, status: "open", sku: "Oslo"}], contact: {days: 99999999999999999999}}}, {applicant: {capped: "DE-a-a", companies: [{adjusted: "VIP", amount: 2, calc: {exposure: true}, health: "VIP", penalty: null, sku: "VIP", status: "open", summary: [], weight: 100}, {adjusted: "retail", amount: 99999999999999999999, calc: {exposure: true}, health: "a-b-c", penalty: null, sku: "a-b-c", status: "open", summary: [], weight: 1000}, {adjusted: "x-y", amount: -0.5, calc: {exposure: true}, health: "x-y", penalty: null, sku: "x-y", status: "closed", summary: [], weight: 10}, {adjusted: "DE", amount: 100, calc: {exposure: true}, health: "DE", penalty: null, sku: "DE", status: "open", summary: [], weight: -0.5}, {adjusted: "Oslo", amount: 2, calc: {exposure: true}, health: "Oslo", penalty: null, sku: "Oslo", status: "closed", summary: [], weight: -500}, {adjusted: "ok", amount: 99.99, calc: {exposure: true}, health: "ok", penalty: 0.25, sku: "ok", status: "closed", summary: [100], weight: 100}, {adjusted: "low", amount: -0.01, calc: {exposure: true}, health: "low", penalty: null, sku: "low", status: "pending", summary: [], weight: 1000000}, {adjusted: "Oslo", amount: 1, calc: {exposure: true}, health: "Oslo", penalty: null, sku: "Oslo", status: "open", summary: [], weight: 100}], contact: {days: 99999999999999999999, flags: {segment: 0}}, fee: false, income: 99999999999999999999, kind: "corporate", limit: 5, name: "a", totals: {flag: false}}}], + [{applicant: {income: 2.50, limit: 1000, name: "low", kind: "corporate", companies: [{amount: 0.000001, status: "pending", sku: "ok"}, {amount: -1, weight: 10, status: null, sku: "ok"}, {amount: 1000000, weight: null, status: "open", sku: "ok"}, {amount: 1000, status: "closed", sku: "A1"}, {amount: -500, weight: 10, status: "pending", sku: "gold"}], contact: {days: null}}}, {applicant: {capped: "low", companies: [{adjusted: "ok", amount: 0.000001, calc: {exposure: true}, health: "ok", penalty: 0.25, sku: "ok", status: "pending", summary: [0]}, {adjusted: "ok", amount: -1, calc: {exposure: false}, health: "ok", penalty: 1000, sku: "ok", status: null, summary: [], weight: 10}, {adjusted: "retail", amount: 1000000, calc: {exposure: true}, health: "ok", penalty: 0.25, sku: "ok", status: "open", summary: [0], weight: null}, {adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "A1", penalty: null, sku: "A1", status: "closed", summary: []}, {adjusted: "gold", amount: -500, calc: {exposure: false}, health: "gold", penalty: 1000, sku: "gold", status: "pending", summary: [1000], weight: 10}], contact: {days: null, flags: {segment: 400}}, fee: false, income: 2.50, kind: "corporate", limit: 1000, name: "low", totals: {flag: false}}}], + [{applicant: {income: 0.5, name: "retail", kind: "retail", companies: [{amount: 0.5, status: "open", sku: "VIP"}], contact: {days: 65}}}, {applicant: {capped: "retail", companies: [{adjusted: "retail", amount: 0.5, calc: {exposure: true}, health: "VIP", penalty: null, sku: "VIP", status: "open", summary: []}], contact: {days: 65, flags: {segment: 0}}, fee: false, income: 0.5, kind: "retail", name: "retail", totals: {flag: false}}}], + [{applicant: {income: -1, limit: -1, name: "a", kind: "retail", companies: [{amount: 1, weight: 1, status: "pending", sku: "none"}], contact: {days: 0.000001}}}, {applicant: {capped: "DE-a-a", companies: [{adjusted: "retail", amount: 1, calc: {exposure: true}, health: "none", penalty: null, sku: "none", status: "pending", summary: [], weight: 1}], contact: {days: 0.000001, flags: {segment: 0}}, fee: false, income: -1, kind: "retail", limit: -1, name: "a", totals: {flag: false}}}], + [{applicant: {income: 1000, limit: 2.50, name: "retail", kind: "corporate", companies: [{amount: 5, weight: 99999999999999999999, status: "pending", sku: "gold"}, {amount: 10, weight: 0.25, status: "open", sku: "Oslo"}], contact: {days: 99999999999999999999}}}, {applicant: {capped: "retail", companies: [{adjusted: "none", amount: 5, calc: {exposure: false}, health: "gold", penalty: 2.50, sku: "gold", status: "pending", summary: [1000], weight: 99999999999999999999}, {adjusted: "none", amount: 10, calc: {exposure: true}, health: "Oslo", penalty: null, sku: "Oslo", status: "open", summary: [], weight: 0.25}], contact: {days: 99999999999999999999, flags: {segment: 1}}, fee: false, income: 1000, kind: "corporate", limit: 2.50, name: "retail", totals: {flag: false}}}], + [{applicant: {income: 0.5, limit: null, name: "DE", kind: "retail", companies: [{amount: 5, sku: "x"}, {amount: 99.99, weight: null, status: "open", sku: "abc"}, {amount: 1000, sku: "low"}, {amount: 99999999999999999999, weight: 1000, sku: "Zed"}, {amount: 0, weight: 123456789.123, sku: "a"}, {amount: 0, weight: null, status: null, sku: " pad "}, {amount: 1000, status: null, sku: "DE"}, {amount: -0.5, weight: 5, status: null, sku: "ok"}, {amount: -500, weight: null, sku: "abc"}, {amount: 250, weight: null, status: "open", sku: "ok"}, {amount: 1000, weight: -0.5, sku: "-"}, {amount: -500, weight: -500, status: "closed", sku: "x-y"}, {amount: 2.50, weight: 0.5, status: "open", sku: "A1"}], contact: {days: 0}}}, {applicant: {capped: "DE", companies: [{adjusted: "retail", amount: 5, calc: {exposure: true}, health: "0.5/true", penalty: null, sku: "x", summary: [5]}, {adjusted: "retail", amount: 99.99, calc: {exposure: true}, health: "abc", penalty: null, sku: "abc", status: "open", summary: [], weight: null}, {adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "low", penalty: null, sku: "low", summary: []}, {adjusted: "retail", amount: 99999999999999999999, calc: {exposure: true}, health: "Zed", penalty: null, sku: "Zed", summary: [], weight: 1000}, {adjusted: "a", amount: 0, calc: {exposure: true}, health: "0.5/true", penalty: null, sku: "a", summary: [], weight: 123456789.123}, {adjusted: " pad ", amount: 0, calc: {exposure: true}, health: " pad ", penalty: null, sku: " pad ", status: null, summary: [], weight: null}, {adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "DE", penalty: null, sku: "DE", status: null, summary: []}, {adjusted: "ok", amount: -0.5, calc: {exposure: true}, health: "ok", penalty: 0.25, sku: "ok", status: null, summary: [5], weight: 5}, {adjusted: "abc", amount: -500, calc: {exposure: true}, health: "abc", penalty: null, sku: "abc", summary: [], weight: null}, {adjusted: "retail", amount: 250, calc: {exposure: true}, health: "ok", penalty: 0.25, sku: "ok", status: "open", summary: [0], weight: null}, {adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "0.5/true", penalty: null, sku: "-", summary: [], weight: -0.5}, {adjusted: "x-y", amount: -500, calc: {exposure: true}, health: "x-y", penalty: null, sku: "x-y", status: "closed", summary: [], weight: -500}, {adjusted: "retail", amount: 2.50, calc: {exposure: true}, health: "A1", penalty: null, sku: "A1", status: "open", summary: [], weight: 0.5}], contact: {days: 0, flags: {segment: 0}}, fee: false, income: 0.5, kind: "retail", limit: null, name: "DE", totals: {flag: false}}}], + [{applicant: {income: 18, limit: 1, name: "ok", kind: "retail", companies: [{amount: 0.25, sku: "é ü"}, {amount: 123456789.123, weight: 250, sku: "DE"}, {amount: 54, status: "closed", sku: "low"}, {amount: 99.99, weight: 0.1, status: "pending", sku: "retail"}, {amount: 2, status: "open", sku: "VIP"}], contact: {days: 5}}}, {applicant: {capped: "DE-ok-ok", companies: [{adjusted: "é ü", amount: 0.25, calc: {exposure: true}, health: "é ü", penalty: null, sku: "é ü", summary: []}, {adjusted: "retail", amount: 123456789.123, calc: {exposure: true}, health: "DE", penalty: null, sku: "DE", summary: [], weight: 250}, {adjusted: "retail", amount: 54, calc: {exposure: true}, health: "low", penalty: null, sku: "low", status: "closed", summary: []}, {adjusted: "retail", amount: 99.99, calc: {exposure: true}, health: "retail", penalty: null, sku: "retail", status: "pending", summary: [], weight: 0.1}, {adjusted: "VIP", amount: 2, calc: {exposure: true}, health: "VIP", penalty: null, sku: "VIP", status: "open", summary: []}], contact: {days: 5, flags: {segment: 0}}, fee: false, income: 18, kind: "retail", limit: 1, name: "ok", totals: {flag: false}}}], + [{applicant: {income: -500, limit: 7.25, name: "retail", kind: "retail", companies: [], contact: {days: 65}}}, "!error: ExpressionFailed"], + [{applicant: {income: -0.01, limit: 0, name: "DE", kind: "retail", companies: [{amount: -0, weight: 60, sku: "a"}, {amount: 2.50, status: "open", sku: "DE"}], contact: {days: 1e3}}}, {applicant: {capped: "DE", companies: [{adjusted: "retail", amount: 0, calc: {exposure: true}, health: "-0.01/true", penalty: null, sku: "a", summary: [], weight: 60}, {adjusted: "retail", amount: 2.50, calc: {exposure: true}, health: "DE", penalty: null, sku: "DE", status: "open", summary: []}], contact: {days: 1000, flags: {segment: 0}}, fee: false, income: -0.01, kind: "retail", limit: 0, name: "DE", totals: {flag: false}}}], + [{applicant: {income: 0.000001, limit: 0, name: "O'Neil", kind: "retail", companies: [{amount: 1000000, weight: 18, status: "open", sku: "Zed"}], contact: {days: 0.000001}}}, {applicant: {capped: "O'Neil", companies: [{adjusted: "retail", amount: 1000000, calc: {exposure: false}, health: "Zed", penalty: 0, sku: "Zed", status: "open", summary: [], weight: 18}], contact: {days: 0.000001, flags: {segment: 0}}, fee: false, income: 0.000001, kind: "retail", limit: 0, name: "O'Neil", totals: {flag: false}}}], + [{applicant: {income: 99999999999999999999, limit: 10, name: "VIP", kind: "retail", companies: [{amount: 0, weight: 0, status: "open", sku: "a"}, {amount: 1000, weight: 250, status: "closed", sku: "retail"}, {amount: 0, weight: 1000000, status: "open", sku: "3.5"}, {amount: 250, weight: -500, status: "pending", sku: "日本"}, {amount: 1000, weight: 0, status: "open", sku: "retail"}, {amount: 5, weight: 0, status: "pending", sku: "low"}, {amount: -0, weight: 1000, status: "closed", sku: "high"}, {amount: -0.5, weight: 99999999999999999999, status: "closed", sku: "none"}, {amount: 100, weight: 10, status: "open", sku: "VIP"}, {amount: 2.50, weight: -0.01, status: "open", sku: "low"}, {amount: 2, weight: 100, status: "closed", sku: "ok"}, {amount: 0.1, weight: 2, status: "open", sku: "ok"}, {amount: 2, weight: 99999999999999999999, status: "pending", sku: "x"}], contact: {days: 5}}}, {applicant: {capped: "VIP", companies: [{adjusted: "a", amount: 0, calc: {exposure: true}, health: "99999999999999999999/true", penalty: null, sku: "a", status: "open", summary: [], weight: 0}, {adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "retail", penalty: null, sku: "retail", status: "closed", summary: [], weight: 250}, {adjusted: "VIP", amount: 0, calc: {exposure: true}, health: "3.5", penalty: null, sku: "3.5", status: "open", summary: [], weight: 1000000}, {adjusted: "日本", amount: 250, calc: {exposure: true}, health: "日本", penalty: null, sku: "日本", status: "pending", summary: [], weight: -500}, {adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "retail", penalty: null, sku: "retail", status: "open", summary: [], weight: 0}, {adjusted: "low", amount: 5, calc: {exposure: true}, health: "low", penalty: null, sku: "low", status: "pending", summary: [], weight: 0}, {adjusted: "high", amount: 0, calc: {exposure: true}, health: "high", penalty: null, sku: "high", status: "closed", summary: [0], weight: 1000}, {adjusted: "none", amount: -0.5, calc: {exposure: true}, health: "none", penalty: null, sku: "none", status: "closed", summary: [], weight: 99999999999999999999}, {adjusted: "VIP", amount: 100, calc: {exposure: true}, health: "VIP", penalty: null, sku: "VIP", status: "open", summary: [], weight: 10}, {adjusted: "low", amount: 2.50, calc: {exposure: true}, health: "low", penalty: null, sku: "low", status: "open", summary: [], weight: -0.01}, {adjusted: "ok", amount: 2, calc: {exposure: true}, health: "ok", penalty: 0.25, sku: "ok", status: "closed", summary: [100], weight: 100}, {adjusted: "ok", amount: 0.1, calc: {exposure: true}, health: "ok", penalty: 0.25, sku: "ok", status: "open", summary: [2], weight: 2}, {adjusted: "x", amount: 2, calc: {exposure: true}, health: "99999999999999999999/true", penalty: null, sku: "x", status: "pending", summary: [2], weight: 99999999999999999999}], contact: {days: 5, flags: {segment: 0}}, fee: false, income: 99999999999999999999, kind: "retail", limit: 10, name: "VIP", totals: {flag: false}}}], + [{applicant: {income: 65, name: "ok", kind: "retail", companies: [], contact: {days: 100}}}, "!error: ExpressionFailed"], + [{applicant: {income: 1000, limit: -0.01, name: "x", kind: "corporate", companies: [], contact: {days: 7.25}, extraField: {nested: true}}}, "!error: ExpressionFailed"], + [{applicant: {income: -500, limit: -0, name: "VIP", kind: "retail", companies: [{amount: 1e3, status: "open", sku: "O'Neil"}], contact: {}}}, {applicant: {capped: "VIP", companies: [{adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "O'Neil", penalty: null, sku: "O'Neil", status: "open", summary: []}], contact: {flags: {segment: 0}}, fee: false, income: -500, kind: "retail", limit: 0, name: "VIP", totals: {flag: false}}}], + [{applicant: {income: 100, limit: 0, name: "VIP", kind: "retail", companies: [{amount: -0.5, weight: null, status: "closed", sku: "3.5"}, {amount: -1, weight: 2, status: null, sku: "high"}], contact: {}}}, {applicant: {capped: "VIP", companies: [{adjusted: "VIP", amount: -0.5, calc: {exposure: true}, health: "3.5", penalty: null, sku: "3.5", status: "closed", summary: [], weight: null}, {adjusted: "high", amount: -1, calc: {exposure: true}, health: "high", penalty: null, sku: "high", status: null, summary: [-1], weight: 2}], contact: {flags: {segment: 0}}, fee: false, income: 100, kind: "retail", limit: 0, name: "VIP", totals: {flag: false}}}], + [{applicant: {income: 18, limit: 2.50, name: "x", kind: "retail", companies: [{amount: 2.50, weight: 10, status: "open", sku: "é ü"}, {amount: -0.5, weight: 408, status: "open", sku: "retail"}, {amount: 100, weight: 5, status: "open", sku: "VIP"}, {amount: 122, weight: 2, status: "pending", sku: ""}, {amount: 0.000001, weight: 1e3, status: "pending", sku: "retail"}], contact: {days: 5}, extraField: "x"}}, {applicant: {capped: "x", companies: [{adjusted: "é ü", amount: 2.50, calc: {exposure: true}, health: "é ü", penalty: null, sku: "é ü", status: "open", summary: [], weight: 10}, {adjusted: "retail", amount: -0.5, calc: {exposure: true}, health: "retail", penalty: null, sku: "retail", status: "open", summary: [], weight: 408}, {adjusted: "retail", amount: 100, calc: {exposure: true}, health: "VIP", penalty: null, sku: "VIP", status: "open", summary: [], weight: 5}, {adjusted: "retail", amount: 122, calc: {exposure: true}, health: "18/true", penalty: null, sku: "", status: "pending", summary: [], weight: 2}, {adjusted: "retail", amount: 0.000001, calc: {exposure: true}, health: "retail", penalty: null, sku: "retail", status: "pending", summary: [], weight: 1000}], contact: {days: 5, flags: {segment: 0}}, extraField: "x", fee: false, income: 18, kind: "retail", limit: 2.50, name: "x", totals: {flag: false}}}], + [{applicant: {income: -1, limit: 0.1, name: "NL", kind: "retail", companies: [{amount: 89, weight: 0, status: false, sku: "retail"}, {amount: 10, weight: 400, status: "open", sku: "Oslo"}, {amount: 65, weight: 1000, status: "open", sku: "gold"}, {amount: 100, weight: -0, status: "open", sku: "x"}], contact: {days: 100}}}, "!error: InputValidationFailed"], + [{applicant: {income: 65, limit: 2, name: "VIP", kind: "corporate", companies: [{amount: 7.25, weight: 250, status: "open", sku: " pad "}, {amount: 0, weight: 100, status: "pending", sku: "none"}], contact: {days: 5}, extraField: "x"}}, {applicant: {capped: "VIP", companies: [{adjusted: " pad ", amount: 7.25, calc: {exposure: true}, health: " pad ", penalty: null, sku: " pad ", status: "open", summary: [], weight: 250}, {adjusted: "none", amount: 0, calc: {exposure: true}, health: "none", penalty: null, sku: "none", status: "pending", summary: [], weight: 100}], contact: {days: 5, flags: {segment: 0}}, extraField: "x", fee: false, income: 65, kind: "corporate", limit: 2, name: "VIP", totals: {flag: false}}}], + [{applicant: {income: 1, name: "low", kind: "retail", companies: [{amount: 1e3, sku: "ok"}, {amount: 100, weight: 0.000001, status: "pending", sku: "x"}], contact: {}}}, {applicant: {capped: "low", companies: [{adjusted: "retail", amount: 1000, calc: {exposure: true}, health: "ok", penalty: 0.25, sku: "ok", summary: [0]}, {adjusted: "retail", amount: 100, calc: {exposure: true}, health: "1/true", penalty: null, sku: "x", status: "pending", summary: [100], weight: 0.000001}], contact: {flags: {segment: 0}}, fee: false, income: 1, kind: "retail", name: "low", totals: {flag: false}}}], + [{applicant: {income: 250, limit: 2.50, name: "DE", kind: "retail", companies: [], contact: {}}}, "!error: ExpressionFailed"], + [{applicant: {income: -500, limit: 2.50, name: "US", kind: "retail", companies: [{amount: 2, weight: -1, status: "open", sku: "retail"}], contact: {days: -0}}}, {applicant: {capped: "US", companies: [{adjusted: "retail", amount: 2, calc: {exposure: true}, health: "retail", penalty: null, sku: "retail", status: "open", summary: [], weight: -1}], contact: {days: 0, flags: {segment: 0}}, fee: false, income: -500, kind: "retail", limit: 2.50, name: "US", totals: {flag: false}}}], + [{applicant: {income: 18, limit: 0.1, name: "retail", kind: "corporate", companies: [{amount: 10, weight: 100, status: "pending", sku: null}, {amount: 100, weight: 5, status: "open", sku: "x-y"}], contact: {days: 99.99}}}, "!error: ExpressionFailed"], + [{applicant: {income: 0.5, limit: 65, name: "VIP", kind: "retail", companies: [{amount: 0, weight: 1, status: "open", sku: "US"}], contact: {days: 460}}}, {applicant: {capped: "VIP", companies: [{adjusted: "US", amount: 0, calc: {exposure: true}, health: "US", penalty: null, sku: "US", status: "open", summary: [], weight: 1}], contact: {days: 460, flags: {segment: 0}}, fee: false, income: 0.5, kind: "retail", limit: 65, name: "VIP", totals: {flag: false}}}], + [{applicant: {income: 1e3, limit: 99.99, kind: "retail", companies: [{amount: 1000000, weight: 1000, status: "open", sku: "US"}, {amount: -500, weight: 0, status: "open", sku: ""}, {amount: 7.25, weight: 0.5, status: "pending", sku: "a"}], contact: {days: 1e3}}}, "!error: MissingRequiredInputs"], + ], +} + +// seed 342700 (attempt 0) +{ + name: "b 28: tenant/items: 1 expression, 5 match, 2 table; 4 root, 6 per-member, 0 top-level computed", + policy: { + models: {tenant: {qty: "number", limit: "number?", age: "number", vip: "boolean?", name: "string", kind: "string(retail|corporate)", items: "item[]"}, item: {qty: "number", rate: "number", weight: "number", kind: "string(retail|corporate)"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {match: "item.scores.capped", arms: [["matches(tenant.name, '^[A-Z]')", "tenant.limit != null"], ["", "((tenant.vip ?? false) and (tenant.vip ?? false))"]]}, + {table: "t2", hit: "collect", inputs: ["tenant.kind"], outputs: ["item.segment", "item.decision"], rules: [ + ["'corporate'", "item.scores.capped", "len(tenant.name) > 2"], + ["", "item.scores.capped", "tenant.age in [13..148)"], + ["'corporate'", "item.scores.capped", "item.scores.capped"], + ]}, + {match: "item.surcharge", arms: [["tenant.limit == null", "string(tenant.qty)"], ["item.rate >= 0.25", "tenant.name"], ["", "tenant.name"]]}, + {table: "t4", inputs: ["trunc(factor)", "tenant.kind", null], outputs: ["tenant.discount", "tenant.totals.risk"], rules: [ + ["< 0.25", "'retail'", "tenant.qty in [27..51]", "(tenant.vip ?? false)", "0.5"], + ["", "'corporate', 'retail'", "tenant.kind != 'corporate'", "(tenant.vip ?? false)", "1000"], + ["!= 0.5", "'retail', 'corporate'", "tenant.age in [41..92]", "tenant.qty > (tenant.limit ?? 0)", "(tenant.limit ?? 0)"], + ["0.25, 2", "", "factor != factor", "(tenant.vip ?? false)", "(0.25) / (abs((tenant.limit ?? 0)) + 1)"], + ["", "'corporate', 'retail'", "", "(tenant.vip ?? false)", "(tenant.limit ?? 0)"], + ["[0..395]", "'corporate', 'retail'", "factor == 1.5", "(tenant.vip ?? false)", "(tenant.qty / 3)"], + ["", "", "", "((tenant.vip ?? false) or (tenant.vip ?? false))", "trunc(tenant.qty)"], + ]}, + {match: "item.health", arms: [["item.rate < item.weight", "trim(tenant.name)"], ["contains(tenant.name, 'none')", "string((250 % (abs(item.qty) + 1)))"], ["", "string(item.qty)"]]}, + {match: "item.exposure", arms: [["not ((tenant.totals.risk ?? 0) > item.rate)", "string(tenant.kind in ['corporate', 'retail'])"], ["", "(split(item.health, '-')[0] ?? 'none')"]]}, + {match: "tenant.eligible", arms: [["tenant.limit != null", "contains(`${tenant.qty}/${(tenant.discount ?? false)}`, 'retail')"], ["not ((tenant.discount ?? false))", "contains(['VIP', 'retail', ''], tenant.name)"], ["factor in [8..84]", "tenant.age < 50"], ["((tenant.discount ?? false) or (tenant.vip ?? false))", "100 >= (tenant.totals.risk ?? 0)"], ["", "(tenant.discount ?? false)"]]}, + {expression: "tenant.share", value: "tenant.qty in [16..86]"}, + ], + }, + cases: [ + [{factor: -2, tenant: {qty: 7.25, limit: 0.5, age: 1, vip: null, name: "A1", kind: "corporate", items: [{qty: 250, rate: 0.5, weight: 0.25, kind: "retail"}, {qty: 0.000001, rate: 1, weight: 1000, kind: "corporate"}, {qty: 0.25, rate: 0.5, weight: -0.5, kind: "retail"}, {qty: 1000, rate: 65, weight: -0, kind: "corporate"}, {qty: 1000, rate: 0.25, weight: 10, kind: "corporate"}]}}, {factor: -2, tenant: {age: 1, discount: false, eligible: false, items: [{decision: [false, false, true], exposure: "true", health: "250", kind: "retail", qty: 250, rate: 0.5, scores: {capped: true}, segment: [true, true, true], surcharge: "A1", weight: 0.25}, {decision: [false, false, true], exposure: "true", health: "A1", kind: "corporate", qty: 0.000001, rate: 1, scores: {capped: true}, segment: [true, true, true], surcharge: "A1", weight: 1000}, {decision: [false, false, true], exposure: "true", health: "0.25", kind: "retail", qty: 0.25, rate: 0.5, scores: {capped: true}, segment: [true, true, true], surcharge: "A1", weight: -0.5}, {decision: [false, false, true], exposure: "true", health: "1000", kind: "corporate", qty: 1000, rate: 65, scores: {capped: true}, segment: [true, true, true], surcharge: "A1", weight: 0}, {decision: [false, false, true], exposure: "A1", health: "A1", kind: "corporate", qty: 1000, rate: 0.25, scores: {capped: true}, segment: [true, true, true], surcharge: "A1", weight: 10}], kind: "corporate", limit: 0.5, name: "A1", qty: 7.25, share: false, totals: {risk: 0.5}, vip: null}}], + [{factor: 10, tenant: {qty: 1000, limit: null, age: 0.000001, vip: false, name: "NL", kind: "retail", items: [{qty: 0.5, rate: 0.25, weight: 0, kind: "corporate"}]}}, {factor: 10, tenant: {age: 0.000001, discount: false, eligible: false, items: [{decision: [false], exposure: "0.5", health: "0.5", kind: "corporate", qty: 0.5, rate: 0.25, scores: {capped: false}, segment: [false], surcharge: "1000", weight: 0}], kind: "retail", limit: null, name: "NL", qty: 1000, share: false, totals: {risk: 1000}, vip: false}}], + [{factor: 1, tenant: {qty: 99999999999999999999, limit: null, age: -0, vip: true, name: "a-b-c", kind: "corporate", items: []}}, {factor: 1, tenant: {age: 0, discount: true, eligible: true, items: [], kind: "corporate", limit: null, name: "a-b-c", qty: 99999999999999999999, share: false, totals: {risk: 0}, vip: true}}], + [{factor: -2, tenant: {qty: 100, limit: null, age: 1, vip: null, name: "Zed", kind: "corporate", items: [{qty: 50, rate: -0, weight: 0, kind: "retail"}]}}, {factor: -2, tenant: {age: 1, discount: false, eligible: false, items: [{decision: [true, false, false], exposure: "true", kind: "retail", qty: 50, rate: 0, scores: {capped: false}, segment: [false, false, false], surcharge: "100", weight: 0}], kind: "corporate", limit: null, name: "Zed", qty: 100, share: false, totals: {risk: 0}, vip: null}}], + [{factor: 10, tenant: {qty: 18, limit: 0.5, age: 0, name: "A1", kind: "retail", items: [{qty: 2, rate: 100, weight: 0.5, kind: "retail"}, {qty: 7.25, rate: 1000, weight: 1000, kind: "retail"}, {qty: 1000000, rate: 1, weight: 0, kind: "retail"}]}}, {factor: 10, tenant: {age: 0, discount: false, eligible: false, items: [{decision: [false], exposure: "2", health: "2", kind: "retail", qty: 2, rate: 100, scores: {capped: true}, segment: [true], surcharge: "A1", weight: 0.5}, {decision: [false], exposure: "true", health: "7.25", kind: "retail", qty: 7.25, rate: 1000, scores: {capped: true}, segment: [true], surcharge: "A1", weight: 1000}, {decision: [false], exposure: "1000000", health: "1000000", kind: "retail", qty: 1000000, rate: 1, scores: {capped: true}, segment: [true], surcharge: "A1", weight: 0}], kind: "retail", limit: 0.5, name: "A1", qty: 18, share: true, totals: {risk: 1000}}}], + [{factor: 0, tenant: {qty: 1000000, limit: 443, age: 50, vip: true, name: "abc", kind: "retail", items: [{qty: 100, rate: 250, weight: 1000, kind: "corporate"}, {qty: 18, rate: 65, weight: 100, kind: "corporate"}]}}, {factor: 0, tenant: {age: 50, discount: true, eligible: false, items: [{decision: [true], exposure: "abc", health: "abc", kind: "corporate", qty: 100, rate: 250, scores: {capped: true}, segment: [true], surcharge: "abc", weight: 1000}, {decision: [true], exposure: "abc", health: "abc", kind: "corporate", qty: 18, rate: 65, scores: {capped: true}, segment: [true], surcharge: "abc", weight: 100}], kind: "retail", limit: 443, name: "abc", qty: 1000000, share: false, totals: {risk: 1000}, vip: true}}], + [{factor: 10, tenant: {qty: -0.01, limit: 0.5, age: -500, vip: true, name: "VIP", kind: "retail", items: []}}, {factor: 10, tenant: {age: -500, discount: true, eligible: false, items: [], kind: "retail", limit: 0.5, name: "VIP", qty: -0.01, share: false, totals: {risk: 1000}, vip: true}}], + [{factor: 100, tenant: {qty: 50, limit: null, age: 7.25, name: " pad ", kind: "corporate", items: []}}, {factor: 100, tenant: {age: 7.25, discount: false, eligible: false, items: [], kind: "corporate", limit: null, name: " pad ", qty: 50, share: true, totals: {risk: 0}}}], + [{factor: -2, tenant: {qty: 1000, limit: 0.1, age: 2, vip: false, name: "abc", kind: "retail", items: [{qty: -500, rate: 99999999999999999999, weight: -0.01, kind: "corporate"}, {qty: 0.5, rate: 1, weight: 99999999999999999999, kind: "retail"}]}}, {factor: -2, tenant: {age: 2, discount: false, eligible: false, items: [{decision: [false], exposure: "true", health: "-500", kind: "corporate", qty: -500, rate: 99999999999999999999, scores: {capped: false}, segment: [false], surcharge: "abc", weight: -0.01}, {decision: [false], exposure: "abc", health: "abc", kind: "retail", qty: 0.5, rate: 1, scores: {capped: false}, segment: [false], surcharge: "abc", weight: 99999999999999999999}], kind: "retail", limit: 0.1, name: "abc", qty: 1000, share: false, totals: {risk: 1000}, vip: false}}], + [{factor: 1, tenant: {qty: 5, limit: 0.25, age: 2, vip: false, name: "VIP", kind: "retail", items: [{qty: [1], rate: 0.5, weight: 2, kind: "retail"}, {qty: 1, rate: 50, weight: -0, kind: "corporate"}, {qty: 7.25, rate: 5, weight: 65, kind: "corporate"}]}}, "!error: InputValidationFailed"], + [{factor: 10, tenant: {qty: -1, limit: null, age: 10, vip: true, name: " pad ", kind: "retail", items: [{qty: 5, rate: 18, weight: 1000, kind: "corporate"}]}}, {factor: 10, tenant: {age: 10, discount: true, eligible: true, items: [{decision: [false], exposure: "pad", health: "pad", kind: "corporate", qty: 5, rate: 18, scores: {capped: true}, segment: [true], surcharge: "-1", weight: 1000}], kind: "retail", limit: null, name: " pad ", qty: -1, share: false, totals: {risk: 1000}, vip: true}}], + [{factor: 0, tenant: {qty: 0.000001, limit: 2, age: 1.5, vip: false, name: "A1", kind: "retail", items: [{qty: 125, rate: -0.01, weight: 0, kind: "corporate"}], extraField: {nested: true}}}, {factor: 0, tenant: {age: 1.5, discount: false, eligible: false, extraField: {nested: true}, items: [{decision: [false], exposure: "A1", health: "A1", kind: "corporate", qty: 125, rate: -0.01, scores: {capped: true}, segment: [true], surcharge: "A1", weight: 0}], kind: "retail", limit: 2, name: "A1", qty: 0.000001, share: false, totals: {risk: 1000}, vip: false}}], + [{factor: 0.5, tenant: {qty: 0.5, limit: 250, age: 250, vip: false, name: "abc", kind: "corporate", items: [{qty: 1, rate: 1, weight: 0, kind: "corporate"}, {qty: 1000, rate: 0, weight: 5, kind: "retail"}]}}, {factor: 0.5, tenant: {age: 250, discount: false, eligible: false, items: [{decision: [true, false, false], exposure: "1", health: "1", kind: "corporate", qty: 1, rate: 1, scores: {capped: false}, segment: [false, false, false], surcharge: "abc", weight: 0}, {decision: [true, false, false], exposure: "abc", health: "abc", kind: "retail", qty: 1000, rate: 0, scores: {capped: false}, segment: [false, false, false], surcharge: "abc", weight: 5}], kind: "corporate", limit: 250, name: "abc", qty: 0.5, share: false, totals: {risk: 250}, vip: false}}], + [{factor: 0.5, tenant: {qty: 2, limit: 1000, age: -0.5, vip: false, kind: "retail", items: [{qty: 1000, rate: 99.99, weight: -0.5, kind: "retail"}]}}, "!error: MissingRequiredInputs"], + [{factor: 0.5, tenant: {qty: 50, limit: -500, age: 0.5, vip: true, name: "Zed", kind: "corporate", items: []}}, {factor: 0.5, tenant: {age: 0.5, discount: true, eligible: false, items: [], kind: "corporate", limit: -500, name: "Zed", qty: 50, share: true, totals: {risk: -500}, vip: true}}], + [{factor: 0, tenant: {qty: 0, limit: 65, age: 0, vip: true, name: "-", kind: "corporate", items: []}}, {factor: 0, tenant: {age: 0, discount: true, eligible: false, items: [], kind: "corporate", limit: 65, name: "-", qty: 0, share: false, totals: {risk: 65}, vip: true}}], + [{factor: 100, tenant: {qty: 1000, age: 1000, name: "gold", kind: "corporate", items: [{qty: 100, rate: 0.000001, weight: 18, kind: "retail"}, {qty: 0.000001, rate: 0.25, weight: 7.25, kind: "corporate"}, {qty: 123456789.123, rate: 1000, weight: 1000, kind: "retail"}, {qty: -500, rate: 250, weight: 0.25, kind: "corporate"}, {qty: 0.5, rate: 123456789.123, weight: 100, kind: "retail"}, {qty: -500, rate: 1000, weight: 0.000001, kind: "retail"}, {qty: 1000, rate: 65, weight: 18, kind: "retail"}, {qty: 0.5, rate: 18, weight: 1000, kind: "corporate"}, {qty: 1, rate: -0, weight: 50, kind: "retail"}, {qty: 0, rate: 99.99, weight: 1e3, kind: "retail"}, {qty: 0.25, rate: 0, weight: 65, kind: "corporate"}]}}, {factor: 100, tenant: {age: 1000, discount: false, eligible: false, items: [{decision: [true, false, false], exposure: "true", kind: "retail", qty: 100, rate: 0.000001, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 18}, {decision: [true, false, false], exposure: "true", kind: "corporate", qty: 0.000001, rate: 0.25, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 7.25}, {decision: [true, false, false], exposure: "true", kind: "retail", qty: 123456789.123, rate: 1000, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 1000}, {decision: [true, false, false], exposure: "true", kind: "corporate", qty: -500, rate: 250, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 0.25}, {decision: [true, false, false], exposure: "true", kind: "retail", qty: 0.5, rate: 123456789.123, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 100}, {decision: [true, false, false], exposure: "true", kind: "retail", qty: -500, rate: 1000, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 0.000001}, {decision: [true, false, false], exposure: "true", kind: "retail", qty: 1000, rate: 65, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 18}, {decision: [true, false, false], exposure: "true", kind: "corporate", qty: 0.5, rate: 18, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 1000}, {decision: [true, false, false], exposure: "true", kind: "retail", qty: 1, rate: 0, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 50}, {decision: [true, false, false], exposure: "true", kind: "retail", qty: 0, rate: 99.99, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 1000}, {decision: [true, false, false], exposure: "true", kind: "corporate", qty: 0.25, rate: 0, scores: {capped: false}, segment: [false, false, false], surcharge: "1000", weight: 65}], kind: "corporate", name: "gold", qty: 1000, share: false, totals: {risk: 0}}}], + [{factor: 1, tenant: {qty: 166, limit: 99999999999999999999, age: 0.000001, vip: false, name: "日本", kind: "corporate", items: [{qty: 0.5, rate: 1, weight: 0, kind: "retail"}]}}, {factor: 1, tenant: {age: 0.000001, discount: false, eligible: false, items: [{decision: [true, false, false], exposure: "0.5", health: "0.5", kind: "retail", qty: 0.5, rate: 1, scores: {capped: false}, segment: [false, false, false], surcharge: "日本", weight: 0}], kind: "corporate", limit: 99999999999999999999, name: "日本", qty: 166, share: false, totals: {risk: 99999999999999999999}, vip: false}}], + [{factor: 100, tenant: {qty: 2, limit: -0.01, age: 0.25, vip: true, name: "O'Neil", kind: "retail", items: [{qty: 0.5, rate: 0.25, weight: 250, kind: "retail"}, {qty: 99.99, rate: 123456789.123, weight: 1000, kind: "corporate"}]}}, {factor: 100, tenant: {age: 0.25, discount: true, eligible: false, items: [{decision: [false], exposure: "O'Neil", health: "O'Neil", kind: "retail", qty: 0.5, rate: 0.25, scores: {capped: true}, segment: [true], surcharge: "O'Neil", weight: 250}, {decision: [false], exposure: "true", health: "99.99", kind: "corporate", qty: 99.99, rate: 123456789.123, scores: {capped: true}, segment: [true], surcharge: "O'Neil", weight: 1000}], kind: "retail", limit: -0.01, name: "O'Neil", qty: 2, share: false, totals: {risk: 1000}, vip: true}}], + [{factor: 100, tenant: {qty: 1, limit: 0.5, age: 100, vip: false, name: "Oslo", kind: "retail", items: [{qty: 0, rate: 1e3, weight: 99999999999999999999, kind: "corporate"}, {qty: 0.5, rate: 0.5, weight: 100, kind: "corporate"}, {qty: 99.99, rate: 0.25, weight: 250, kind: "retail"}, {qty: 1000000, rate: 1000000, weight: 1.5, kind: "retail"}]}}, {factor: 100, tenant: {age: 100, discount: false, eligible: false, items: [{decision: [true], exposure: "true", health: "Oslo", kind: "corporate", qty: 0, rate: 1000, scores: {capped: true}, segment: [true], surcharge: "Oslo", weight: 99999999999999999999}, {decision: [true], exposure: "Oslo", health: "Oslo", kind: "corporate", qty: 0.5, rate: 0.5, scores: {capped: true}, segment: [true], surcharge: "Oslo", weight: 100}, {decision: [true], exposure: "Oslo", health: "Oslo", kind: "retail", qty: 99.99, rate: 0.25, scores: {capped: true}, segment: [true], surcharge: "Oslo", weight: 250}, {decision: [true], exposure: "true", health: "1000000", kind: "retail", qty: 1000000, rate: 1000000, scores: {capped: true}, segment: [true], surcharge: "Oslo", weight: 1.5}], kind: "retail", limit: 0.5, name: "Oslo", qty: 1, share: false, totals: {risk: 1000}, vip: false}}], + [{factor: 100, tenant: {qty: 123456789.123, limit: 1000, age: 1000000, vip: false, name: "US", kind: "corporate", items: [{qty: -0, rate: 99.99, weight: 100, kind: "retail"}, {qty: 0.5, rate: 1000, weight: 50, kind: "retail"}, {qty: 0.5, rate: 250, weight: 250, kind: "retail"}, {qty: 1000, rate: -0.01, weight: 1000, kind: "corporate"}, {qty: -0, rate: 2, weight: 1000, kind: "corporate"}]}}, {factor: 100, tenant: {age: 1000000, discount: false, eligible: false, items: [{decision: [false, false, true], exposure: "US", health: "US", kind: "retail", qty: 0, rate: 99.99, scores: {capped: true}, segment: [true, true, true], surcharge: "US", weight: 100}, {decision: [false, false, true], exposure: "true", health: "0.5", kind: "retail", qty: 0.5, rate: 1000, scores: {capped: true}, segment: [true, true, true], surcharge: "US", weight: 50}, {decision: [false, false, true], exposure: "0.5", health: "0.5", kind: "retail", qty: 0.5, rate: 250, scores: {capped: true}, segment: [true, true, true], surcharge: "US", weight: 250}, {decision: [false, false, true], exposure: "US", health: "US", kind: "corporate", qty: 1000, rate: -0.01, scores: {capped: true}, segment: [true, true, true], surcharge: "US", weight: 1000}, {decision: [false, false, true], exposure: "US", health: "US", kind: "corporate", qty: 0, rate: 2, scores: {capped: true}, segment: [true, true, true], surcharge: "US", weight: 1000}], kind: "corporate", limit: 1000, name: "US", qty: 123456789.123, share: false, totals: {risk: 1000}, vip: false}}], + [{factor: 100, tenant: {qty: 1, limit: 65, age: 1000, vip: false, name: "retail", kind: "retail", items: [{qty: 0.5, rate: 100, weight: 0, kind: "retail"}, {qty: 0.25, rate: 0.5, weight: 99999999999999999999, kind: "retail"}, {qty: 0.5, rate: 0.1, weight: 0.5, kind: "retail"}, {qty: 18, rate: 7.25, weight: 100, kind: "retail"}, {qty: 250, rate: 10, weight: 0.25, kind: "retail"}]}}, {factor: 100, tenant: {age: 1000, discount: false, eligible: false, items: [{decision: [false], exposure: "0.5", health: "0.5", kind: "retail", qty: 0.5, rate: 100, scores: {capped: false}, segment: [false], surcharge: "retail", weight: 0}, {decision: [false], exposure: "retail", health: "retail", kind: "retail", qty: 0.25, rate: 0.5, scores: {capped: false}, segment: [false], surcharge: "retail", weight: 99999999999999999999}, {decision: [false], exposure: "retail", health: "retail", kind: "retail", qty: 0.5, rate: 0.1, scores: {capped: false}, segment: [false], surcharge: "retail", weight: 0.5}, {decision: [false], exposure: "retail", health: "retail", kind: "retail", qty: 18, rate: 7.25, scores: {capped: false}, segment: [false], surcharge: "retail", weight: 100}, {decision: [false], exposure: "250", health: "250", kind: "retail", qty: 250, rate: 10, scores: {capped: false}, segment: [false], surcharge: "retail", weight: 0.25}], kind: "retail", limit: 65, name: "retail", qty: 1, share: false, totals: {risk: 1000}, vip: false}}], + [{factor: -2, tenant: {qty: 65, limit: 0.5, age: 100, vip: true, name: "a", kind: "corporate", items: [{qty: 7.25, rate: 0.25, weight: 0.5, kind: "retail"}]}}, {factor: -2, tenant: {age: 100, discount: true, eligible: false, items: [{decision: [false, true, true], exposure: "a", health: "a", kind: "retail", qty: 7.25, rate: 0.25, scores: {capped: true}, segment: [true, true, true], surcharge: "a", weight: 0.5}], kind: "corporate", limit: 0.5, name: "a", qty: 65, share: true, totals: {risk: 0.5}, vip: true}}], + [{factor: 10, tenant: {qty: 0.5, limit: 0.000001, age: 2.50, vip: false, name: "12", kind: "retail", items: []}}, {factor: 10, tenant: {age: 2.50, discount: false, eligible: false, items: [], kind: "retail", limit: 0.000001, name: "12", qty: 0.5, share: false, totals: {risk: 1000}, vip: false}}], + ], +} + +// seed 342800 (attempt 0) +{ + name: "b 29: tenant/loans + report: 2 assertion, 4 expression, 2 match, 1 table; 1 root, 10 per-member, 0 top-level computed", + policy: { + models: {tenant: {years: "number?", status: "string(open|closed|pending)", city: "string?", verified: "boolean", loans: "loan[]", report: "creditReport?"}, loan: {income: "number", kind: "string(retail|corporate)"}, creditReport: {years: "number"}}, + blocks: [ + {expression: "loan.decision", value: "(tenant.verified ? 'x' : loan.margin)"}, + {table: "t1", inputs: ["(tenant.years ?? 0)", "tenant.status", "loan.kind"], outputs: ["loan.level", "loan.flag", "loan.discount"], rules: [ + ["<= 0.5", "", "'retail', 'corporate'", "(tenant.city ?? '')", "(tenant.report.years ?? 0)", "tenant.verified"], + ["[50..324]", "", "", "(tenant.city ?? '')", "((tenant.report.years ?? 0) + (tenant.report.years ?? 0))", "tenant.verified"], + ["> 0", "'open', 'closed'", "'corporate'", "'Oslo'", "(tenant.years ?? 0)", "all(tenant.loans, (#.income > 100 or #.income == 3))"], + ["100", "'open'", "'corporate', 'retail'", "`${(tenant.city ?? '')}/${tenant.verified}`", "", "tenant.verified"], + ["", "", "", "(tenant.city ?? '')", "(tenant.report.years ?? 0)", "tenant.verified"], + ]}, + {assertion: "loan.grade", conditions: [["or", "(loan.flag ?? 0) != (tenant.report.years ?? 0)", 1]]}, + {assertion: "creditReport.exposure", conditions: [["or", "tenant.status == 'open'", 0], ["and", "contains(['high', 'gold', ''], (tenant.city ?? ''))", 0], ["or", "creditReport.years == creditReport.years", 0], ["and", "tenant.totals.weighted != 'low'", 0]]}, + {expression: "loan.flags.fee", value: "((split(upper((tenant.city ?? '')), '-')[1] ?? 'none') + '-' + string(loan.summary.s < 100))"}, + {match: "loan.margin", arms: [["isNumeric(tenant.totals.weighted)", "(tenant.city ?? '')"], ["", "(loan.level ?? '')"]]}, + {expression: "loan.summary", value: "{s: (tenant.years ?? 0)}"}, + {match: "tenant.totals.weighted", arms: [["tenant.status in ['pending', 'closed']", "(tenant.city ?? '')"], ["(tenant.verified or tenant.verified)", "`${(tenant.report.years ?? 0)}/${tenant.verified}`"], ["isNumeric((tenant.verified ? (tenant.city ?? '') : 'Oslo'))", "((tenant.city ?? '') in ['VIP', 'retail'] ? (split((tenant.city ?? ''), '-')[0] ?? 'none') : (tenant.city ?? ''))"], ["tenant.report.years != null", "(tenant.city ?? '')"], ["", "((tenant.city ?? '') + '-' + 'Oslo')"]]}, + {expression: "loan.flags.risk", value: "median([(loan.flag ?? 0), len(filter(tenant.loans, (#.flag ?? 0) >= 10)), count(tenant.loans, (#.grade and #.grade))])"}, + ], + }, + cases: [ + [{tenant: {years: 65, status: "closed", city: "12", verified: false, loans: [{income: 18, kind: "retail"}, {income: 50, kind: "retail"}, {income: 250, kind: "retail"}, {income: 0.1, kind: "corporate"}], report: {years: 5}, extraField: {nested: true}}}, {tenant: {city: "12", extraField: {nested: true}, loans: [{decision: "12", discount: false, flag: 10, flags: {fee: "none-true", risk: 4}, grade: true, income: 18, kind: "retail", level: "12", margin: "12", summary: {s: 65}}, {decision: "12", discount: false, flag: 10, flags: {fee: "none-true", risk: 4}, grade: true, income: 50, kind: "retail", level: "12", margin: "12", summary: {s: 65}}, {decision: "12", discount: false, flag: 10, flags: {fee: "none-true", risk: 4}, grade: true, income: 250, kind: "retail", level: "12", margin: "12", summary: {s: 65}}, {decision: "12", discount: false, flag: 10, flags: {fee: "none-true", risk: 4}, grade: true, income: 0.1, kind: "corporate", level: "12", margin: "12", summary: {s: 65}}], report: {exposure: true, years: 5}, status: "closed", totals: {weighted: "12"}, verified: false, years: 65}}], + [{tenant: {years: -0, status: "pending", city: "VIP", verified: true, loans: [], report: {years: 100}}}, {tenant: {city: "VIP", loans: [], report: {exposure: true, years: 100}, status: "pending", totals: {weighted: "VIP"}, verified: true, years: 0}}], + [{tenant: {years: -500, status: "closed", city: null, verified: false, loans: [{income: 1000, kind: "retail"}], report: {years: 0.25}}}, {tenant: {city: null, loans: [{decision: "", discount: false, flag: 0.25, flags: {fee: "none-true", risk: 0}, grade: false, income: 1000, kind: "retail", level: "", margin: "", summary: {s: -500}}], report: {exposure: true, years: 0.25}, status: "closed", totals: {weighted: ""}, verified: false, years: -500}}], + [{tenant: {years: null, status: "pending", city: "VIP", verified: false, loans: [{income: 2.50, kind: "corporate"}, {income: 2, kind: "corporate"}], report: {years: 65}}}, {tenant: {city: "VIP", loans: [{decision: "VIP", discount: false, flag: 65, flags: {fee: "none-true", risk: 2}, grade: false, income: 2.50, kind: "corporate", level: "VIP", margin: "VIP", summary: {s: 0}}, {decision: "VIP", discount: false, flag: 65, flags: {fee: "none-true", risk: 2}, grade: false, income: 2, kind: "corporate", level: "VIP", margin: "VIP", summary: {s: 0}}], report: {exposure: true, years: 65}, status: "pending", totals: {weighted: "VIP"}, verified: false, years: null}}], + [{tenant: {years: 10, status: "open", city: "a-b-c", verified: false, loans: [{income: 0, kind: "retail"}], report: {years: 1}}}, {tenant: {city: "a-b-c", loans: [{decision: "a-b-c", discount: false, flag: 1, flags: {fee: "B-true", risk: 0}, grade: false, income: 0, kind: "retail", level: "a-b-c", margin: "a-b-c", summary: {s: 10}}], report: {exposure: true, years: 1}, status: "open", totals: {weighted: "a-b-c"}, verified: false, years: 10}}], + [{tenant: {years: 123456789.123, status: "closed", city: "é ü", verified: true, loans: [{income: 1000, kind: "retail"}], report: null}}, {tenant: {city: "é ü", loans: [{decision: "x", discount: true, flag: 0, flags: {fee: "none-false", risk: 0}, grade: false, income: 1000, kind: "retail", level: "é ü", margin: "é ü", summary: {s: 123456789.123}}], report: null, status: "closed", totals: {weighted: "é ü"}, verified: true, years: 123456789.123}}], + [{tenant: {years: null, status: "open", city: "Zed", verified: false, loans: [{income: 1, kind: "corporate"}, {income: 99.99, kind: "retail"}, {income: 3, kind: "retail"}, {income: 5, kind: "corporate"}, {income: 100, kind: "retail"}], report: null}}, {tenant: {city: "Zed", loans: [{decision: "Zed", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 1, kind: "corporate", level: "Zed", margin: "Zed", summary: {s: 0}}, {decision: "Zed", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 99.99, kind: "retail", level: "Zed", margin: "Zed", summary: {s: 0}}, {decision: "Zed", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 3, kind: "retail", level: "Zed", margin: "Zed", summary: {s: 0}}, {decision: "Zed", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 5, kind: "corporate", level: "Zed", margin: "Zed", summary: {s: 0}}, {decision: "Zed", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 100, kind: "retail", level: "Zed", margin: "Zed", summary: {s: 0}}], report: null, status: "open", totals: {weighted: "Zed-Oslo"}, verified: false, years: null}}], + [{tenant: {years: 198, status: "open", city: "VIP", verified: true, loans: [{income: 0, kind: "retail"}, {income: 2, kind: "retail"}, {income: 0.000001, kind: "retail"}, {income: 100, kind: "corporate"}, {income: 100, kind: "retail"}], report: {years: 18}}}, {tenant: {city: "VIP", loans: [{decision: "x", discount: true, flag: 36, flags: {fee: "none-false", risk: 5}, grade: true, income: 0, kind: "retail", level: "VIP", margin: "VIP", summary: {s: 198}}, {decision: "x", discount: true, flag: 36, flags: {fee: "none-false", risk: 5}, grade: true, income: 2, kind: "retail", level: "VIP", margin: "VIP", summary: {s: 198}}, {decision: "x", discount: true, flag: 36, flags: {fee: "none-false", risk: 5}, grade: true, income: 0.000001, kind: "retail", level: "VIP", margin: "VIP", summary: {s: 198}}, {decision: "x", discount: true, flag: 36, flags: {fee: "none-false", risk: 5}, grade: true, income: 100, kind: "corporate", level: "VIP", margin: "VIP", summary: {s: 198}}, {decision: "x", discount: true, flag: 36, flags: {fee: "none-false", risk: 5}, grade: true, income: 100, kind: "retail", level: "VIP", margin: "VIP", summary: {s: 198}}], report: {exposure: true, years: 18}, status: "open", totals: {weighted: "18/true"}, verified: true, years: 198}}], + [{tenant: {years: 1.5, status: "closed", city: "abc", verified: true, loans: [{income: 250, kind: "corporate"}, {income: 100, kind: "retail"}, {income: 10, kind: "retail"}, {income: 0, kind: "retail"}], report: {years: 250}}}, {tenant: {city: "abc", loans: [{decision: "x", discount: false, flag: 1.5, flags: {fee: "none-true", risk: 1.5}, grade: true, income: 250, kind: "corporate", level: "Oslo", margin: "Oslo", summary: {s: 1.5}}, {decision: "x", discount: true, flag: 250, flags: {fee: "none-true", risk: 3}, grade: false, income: 100, kind: "retail", level: "abc", margin: "abc", summary: {s: 1.5}}, {decision: "x", discount: true, flag: 250, flags: {fee: "none-true", risk: 3}, grade: false, income: 10, kind: "retail", level: "abc", margin: "abc", summary: {s: 1.5}}, {decision: "x", discount: true, flag: 250, flags: {fee: "none-true", risk: 3}, grade: false, income: 0, kind: "retail", level: "abc", margin: "abc", summary: {s: 1.5}}], report: {exposure: true, years: 250}, status: "closed", totals: {weighted: "abc"}, verified: true, years: 1.5}}], + [{tenant: {years: -1, status: "open", city: "-", verified: true, loans: [{income: 0.000001, kind: "retail"}, {income: 65, kind: "retail"}, {income: 0.5, kind: "corporate"}, {income: -1, kind: "retail"}, {income: 0.5, kind: "retail"}, {income: -0, kind: "retail"}, {income: 100, kind: "retail"}, {income: 99.99, kind: "retail"}, {income: 65, kind: "retail"}, {income: 1.5, kind: "retail"}, {income: 99.99, kind: "retail"}]}}, {tenant: {city: "-", loans: [{decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 0.000001, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 65, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 0.5, kind: "corporate", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: -1, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 0.5, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 0, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 100, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 99.99, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 65, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 1.5, kind: "retail", level: "-", margin: "-", summary: {s: -1}}, {decision: "x", discount: true, flag: 0, flags: {fee: "-true", risk: 0}, grade: false, income: 99.99, kind: "retail", level: "-", margin: "-", summary: {s: -1}}], status: "open", totals: {weighted: "0/true"}, verified: true, years: -1}}], + [{tenant: {years: null, status: "open", city: null, verified: true, loans: [{income: 2, kind: "retail"}, {income: 1000, kind: "corporate"}], report: {years: 0.5}}}, {tenant: {city: null, loans: [{decision: "x", discount: true, flag: 0.5, flags: {fee: "none-true", risk: 0}, grade: false, income: 2, kind: "retail", level: "", margin: "", summary: {s: 0}}, {decision: "x", discount: true, flag: 0.5, flags: {fee: "none-true", risk: 0}, grade: false, income: 1000, kind: "corporate", level: "", margin: "", summary: {s: 0}}], report: {exposure: true, years: 0.5}, status: "open", totals: {weighted: "0.5/true"}, verified: true, years: null}}], + [{tenant: {years: 0.000001, status: "open", city: "x", verified: false, loans: [{income: 0.25, kind: "corporate"}, {income: 0, kind: "retail"}, {income: -0, kind: "corporate"}], report: {years: 0.1}}}, {tenant: {city: "x", loans: [{decision: "x", discount: false, flag: 0.1, flags: {fee: "none-true", risk: 0}, grade: false, income: 0.25, kind: "corporate", level: "x", margin: "x", summary: {s: 0.000001}}, {decision: "x", discount: false, flag: 0.1, flags: {fee: "none-true", risk: 0}, grade: false, income: 0, kind: "retail", level: "x", margin: "x", summary: {s: 0.000001}}, {decision: "x", discount: false, flag: 0.1, flags: {fee: "none-true", risk: 0}, grade: false, income: 0, kind: "corporate", level: "x", margin: "x", summary: {s: 0.000001}}], report: {exposure: true, years: 0.1}, status: "open", totals: {weighted: "x"}, verified: false, years: 0.000001}}], + [{tenant: {years: 65, city: "é ü", verified: false, loans: [], report: {years: 1}}}, "!error: MissingRequiredInputs"], + [{tenant: {status: "closed", city: "Zed", verified: false, loans: [{income: 0.000001, kind: "retail"}], report: {years: 1.5}}}, {tenant: {city: "Zed", loans: [{decision: "Zed", discount: false, flag: 1.5, flags: {fee: "none-true", risk: 0}, grade: false, income: 0.000001, kind: "retail", level: "Zed", margin: "Zed", summary: {s: 0}}], report: {exposure: true, years: 1.5}, status: "closed", totals: {weighted: "Zed"}, verified: false}}], + [{tenant: {years: 10, status: "closed", city: "Oslo", verified: false, loans: [{income: 0.5, kind: "retail"}, {income: -0, kind: "retail"}, {income: 0.5, kind: "corporate"}, {income: 100, kind: "retail"}, {income: 10, kind: "corporate"}], report: {years: 0.1}}}, {tenant: {city: "Oslo", loans: [{decision: "Oslo", discount: false, flag: 0.1, flags: {fee: "none-true", risk: 2}, grade: false, income: 0.5, kind: "retail", level: "Oslo", margin: "Oslo", summary: {s: 10}}, {decision: "Oslo", discount: false, flag: 0.1, flags: {fee: "none-true", risk: 2}, grade: false, income: 0, kind: "retail", level: "Oslo", margin: "Oslo", summary: {s: 10}}, {decision: "Oslo", discount: false, flag: 10, flags: {fee: "none-true", risk: 2}, grade: true, income: 0.5, kind: "corporate", level: "Oslo", margin: "Oslo", summary: {s: 10}}, {decision: "Oslo", discount: false, flag: 0.1, flags: {fee: "none-true", risk: 2}, grade: false, income: 100, kind: "retail", level: "Oslo", margin: "Oslo", summary: {s: 10}}, {decision: "Oslo", discount: false, flag: 10, flags: {fee: "none-true", risk: 2}, grade: true, income: 10, kind: "corporate", level: "Oslo", margin: "Oslo", summary: {s: 10}}], report: {exposure: true, years: 0.1}, status: "closed", totals: {weighted: "Oslo"}, verified: false, years: 10}}], + [{tenant: {years: 0.000001, status: "open", city: "gold", verified: true, loans: [{income: -1, kind: "retail"}, {income: 123456789.123, kind: "retail"}, {income: 169, kind: "retail"}, {income: 0, kind: "retail"}, {income: 50, kind: "retail"}, {income: 100, kind: "corporate"}, {income: 7.25, kind: "retail"}, {income: -0.01, kind: "corporate"}, {income: 3, kind: "retail"}, {income: -1, kind: "retail"}, {income: 99.99, kind: "corporate"}, {income: 5, kind: "corporate"}, {income: 1.5, kind: "retail"}]}}, {tenant: {city: "gold", loans: [{decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: -1, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 123456789.123, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 169, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 0, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 50, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 100, kind: "corporate", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 7.25, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: -0.01, kind: "corporate", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 3, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: -1, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 99.99, kind: "corporate", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 5, kind: "corporate", level: "gold", margin: "gold", summary: {s: 0.000001}}, {decision: "x", discount: true, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 1.5, kind: "retail", level: "gold", margin: "gold", summary: {s: 0.000001}}], status: "open", totals: {weighted: "0/true"}, verified: true, years: 0.000001}}], + [{tenant: {years: 1.5, status: "open", city: "日本", verified: true, loans: [{income: 250, kind: "corporate"}, {income: 250, kind: "retail"}], report: {years: 7.25}}}, {tenant: {city: "日本", loans: [{decision: "x", discount: true, flag: 1.5, flags: {fee: "none-true", risk: 1}, grade: true, income: 250, kind: "corporate", level: "Oslo", margin: "Oslo", summary: {s: 1.5}}, {decision: "x", discount: true, flag: 7.25, flags: {fee: "none-true", risk: 1}, grade: false, income: 250, kind: "retail", level: "日本", margin: "日本", summary: {s: 1.5}}], report: {exposure: true, years: 7.25}, status: "open", totals: {weighted: "7.25/true"}, verified: true, years: 1.5}}], + [{tenant: {years: 394, status: "closed", city: "Zed", verified: false, loans: [], report: {years: 2}}}, {tenant: {city: "Zed", loans: [], report: {exposure: true, years: 2}, status: "closed", totals: {weighted: "Zed"}, verified: false, years: 394}}], + [{tenant: {years: 2, status: "open", verified: true, loans: [{income: 5, kind: "retail"}, {income: 0.000001, kind: "retail"}, {income: 7.25, kind: "corporate"}, {income: 2, kind: "retail"}, {income: 0.000001, kind: "retail"}, {income: 250, kind: "corporate"}, {income: 99999999999999999999, kind: "retail"}, {income: 0.25, kind: "retail"}, {income: -0.5, kind: "corporate"}], report: {years: 2.50}}}, {tenant: {loans: [{decision: "x", discount: true, flag: 2.50, flags: {fee: "none-true", risk: 2.50}, grade: false, income: 5, kind: "retail", level: "", margin: "", summary: {s: 2}}, {decision: "x", discount: true, flag: 2.50, flags: {fee: "none-true", risk: 2.50}, grade: false, income: 0.000001, kind: "retail", level: "", margin: "", summary: {s: 2}}, {decision: "x", discount: false, flag: 2, flags: {fee: "none-true", risk: 2}, grade: true, income: 7.25, kind: "corporate", level: "Oslo", margin: "Oslo", summary: {s: 2}}, {decision: "x", discount: true, flag: 2.50, flags: {fee: "none-true", risk: 2.50}, grade: false, income: 2, kind: "retail", level: "", margin: "", summary: {s: 2}}, {decision: "x", discount: true, flag: 2.50, flags: {fee: "none-true", risk: 2.50}, grade: false, income: 0.000001, kind: "retail", level: "", margin: "", summary: {s: 2}}, {decision: "x", discount: false, flag: 2, flags: {fee: "none-true", risk: 2}, grade: true, income: 250, kind: "corporate", level: "Oslo", margin: "Oslo", summary: {s: 2}}, {decision: "x", discount: true, flag: 2.50, flags: {fee: "none-true", risk: 2.50}, grade: false, income: 99999999999999999999, kind: "retail", level: "", margin: "", summary: {s: 2}}, {decision: "x", discount: true, flag: 2.50, flags: {fee: "none-true", risk: 2.50}, grade: false, income: 0.25, kind: "retail", level: "", margin: "", summary: {s: 2}}, {decision: "x", discount: false, flag: 2, flags: {fee: "none-true", risk: 2}, grade: true, income: -0.5, kind: "corporate", level: "Oslo", margin: "Oslo", summary: {s: 2}}], report: {exposure: true, years: 2.50}, status: "open", totals: {weighted: "2.50/true"}, verified: true, years: 2}}], + [{tenant: {years: 1, status: "closed", city: "retail", verified: null, loans: [{income: 2, kind: "retail"}, {income: 0.1, kind: "retail"}, {income: 10, kind: "retail"}, {income: 1e3, kind: "retail"}, {income: 0.000001, kind: "retail"}], report: {years: 99.99}}}, "!error: MissingRequiredInputs"], + [{tenant: {years: 1000000, status: "closed", city: " pad ", verified: false, loans: [{income: 10, kind: "retail"}, {income: 0.1, kind: "retail"}], report: {years: 2}}}, {tenant: {city: " pad ", loans: [{decision: " pad ", discount: false, flag: 2, flags: {fee: "none-false", risk: 0}, grade: false, income: 10, kind: "retail", level: " pad ", margin: " pad ", summary: {s: 1000000}}, {decision: " pad ", discount: false, flag: 2, flags: {fee: "none-false", risk: 0}, grade: false, income: 0.1, kind: "retail", level: " pad ", margin: " pad ", summary: {s: 1000000}}], report: {exposure: true, years: 2}, status: "closed", totals: {weighted: " pad "}, verified: false, years: 1000000}}], + [{tenant: {years: 3, status: false, city: " pad ", verified: false, loans: [{income: 3, kind: "retail"}, {income: 0, kind: "retail"}], report: {years: 2.50}}}, "!error: InputValidationFailed"], + [{tenant: {years: 0.5, status: "open", city: "DE", verified: false, loans: [{income: 99999999999999999999, kind: "retail"}, {income: 3, kind: "retail"}, {income: -0, kind: "retail"}, {income: 2, kind: "retail"}], report: {years: 3}}}, {tenant: {city: "DE", loans: [{decision: "DE", discount: false, flag: 3, flags: {fee: "none-true", risk: 0}, grade: false, income: 99999999999999999999, kind: "retail", level: "DE", margin: "DE", summary: {s: 0.5}}, {decision: "DE", discount: false, flag: 3, flags: {fee: "none-true", risk: 0}, grade: false, income: 3, kind: "retail", level: "DE", margin: "DE", summary: {s: 0.5}}, {decision: "DE", discount: false, flag: 3, flags: {fee: "none-true", risk: 0}, grade: false, income: 0, kind: "retail", level: "DE", margin: "DE", summary: {s: 0.5}}, {decision: "DE", discount: false, flag: 3, flags: {fee: "none-true", risk: 0}, grade: false, income: 2, kind: "retail", level: "DE", margin: "DE", summary: {s: 0.5}}], report: {exposure: true, years: 3}, status: "open", totals: {weighted: "DE"}, verified: false, years: 0.5}}], + [{tenant: {years: 1000, status: "pending", city: "x", verified: false, loans: [{income: -0, kind: "corporate"}, {income: 99.99, kind: "retail"}, {income: -0.5, kind: "corporate"}, {income: 3, kind: "retail"}, {income: 0.5, kind: "retail"}, {income: -500, kind: "corporate"}, {income: 0.5, kind: "retail"}, {income: 18, kind: "corporate"}, {income: -500, kind: "retail"}, {income: -0.01, kind: "retail"}], report: {years: -0.5}}}, {tenant: {city: "x", loans: [{decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: 0, kind: "corporate", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: 99.99, kind: "retail", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: -0.5, kind: "corporate", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: 3, kind: "retail", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: 0.5, kind: "retail", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: -500, kind: "corporate", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: 0.5, kind: "retail", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: 18, kind: "corporate", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: -500, kind: "retail", level: "x", margin: "x", summary: {s: 1000}}, {decision: "x", discount: false, flag: -0.5, flags: {fee: "none-false", risk: 0}, grade: false, income: -0.01, kind: "retail", level: "x", margin: "x", summary: {s: 1000}}], report: {exposure: true, years: -0.5}, status: "pending", totals: {weighted: "x"}, verified: false, years: 1000}}], + [{tenant: {years: 0.000001, status: "pending", city: "high", verified: false, loans: [], report: {years: 1000}}}, {tenant: {city: "high", loans: [], report: {exposure: true, years: 1000}, status: "pending", totals: {weighted: "high"}, verified: false, years: 0.000001}}], + [{tenant: {status: "closed", city: "日本", verified: false, loans: [{income: 2, kind: "retail"}, {income: 5, kind: "corporate"}, {income: 2, kind: "corporate"}, {income: 0.5, kind: "corporate"}, {income: 0.000001, kind: "corporate"}, {income: 100, kind: "corporate"}, {income: 0.000001, kind: "corporate"}, {income: -0, kind: "corporate"}, {income: 1000000, kind: "retail"}, {income: 99.99, kind: "retail"}], report: null}}, {tenant: {city: "日本", loans: [{decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 2, kind: "retail", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 5, kind: "corporate", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 2, kind: "corporate", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 0.5, kind: "corporate", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 0.000001, kind: "corporate", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 100, kind: "corporate", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 0.000001, kind: "corporate", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 0, kind: "corporate", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 1000000, kind: "retail", level: "日本", margin: "日本", summary: {s: 0}}, {decision: "日本", discount: false, flag: 0, flags: {fee: "none-true", risk: 0}, grade: false, income: 99.99, kind: "retail", level: "日本", margin: "日本", summary: {s: 0}}], report: null, status: "closed", totals: {weighted: "日本"}, verified: false}}], + [{tenant: {years: 50, status: "closed", city: "x", verified: true, loans: [], report: {years: 0}}}, {tenant: {city: "x", loans: [], report: {exposure: true, years: 0}, status: "closed", totals: {weighted: "x"}, verified: true, years: 50}}], + ], +} + +// seed 342900 (attempt 0) +{ + name: "b 30: shipment/loans/employees + contact: 1 assertion, 5 expression, 1 match, 4 table; 1 root, 8 per-member, 3 top-level computed", + policy: { + models: {shipment: {score: "number?", sku: "string?", birthDate: "date?", since: "date", qty: "number", openedAt: "date", loans: "loan[]", contact: "contactInfo"}, loan: {limit: "number", score: "number?", vip: "boolean", label: "string?", employees: "employee[]"}, employee: {weight: "number?", status: "string(open|closed|pending)"}, contactInfo: {limit: "number?", sku: "string", vip: "boolean"}}, + blocks: [ + {table: "t7", inputs: ["shipment.contact.adjusted", "sum(map(shipment.loans, #.limit))"], outputs: ["scores.exposure", "rank", "net[]"], rules: [ + ["<= 0", "!= 18", "(shipment.contact.limit ?? 0)", "all(shipment.loans, (#.score ?? 0) >= (#.score ?? 0))", "shipment.contact.vip"], + ["", "", "(min([abs(shipment.qty), 1000]) ^ 3)", "contains(['retail', 'DE', ''], shipment.contact.sku)", "shipment.contact.vip"], + ]}, + {expression: "contactInfo.adjusted", value: "(len(filter(shipment.loans, 1 > (#.score ?? 0))) + ((contactInfo.limit ?? 0) - 1))"}, + {table: "t4", hit: "collect", inputs: ["shipment.contact.adjusted", "loan.vip"], outputs: ["loan.points", "loan.discount", "loan.share"], rules: [ + ["18, 0.5", "true", "shipment.contact.vip", "(shipment.score ?? 0)", "(shipment.score ?? 0)"], + ["<= 0.5", "true", "loan.vip", "", "(shipment.calc.margin ?? 0)"], + ["[250..701]", "", "loan.flags.bucket", "(loan.score ?? 0)", "(loan.score ?? 0)"], + ]}, + {expression: "loan.quota", value: "shipment.since"}, + {expression: "loan.capped", value: "(shipment.calc.margin ?? 0) == (shipment.calc.margin ?? 0)"}, + {expression: "shipment.calc.margin", value: "shipment.contact.limit"}, + {table: "t6", hit: "collect", inputs: ["shipment.openedAt", "shipment.since", "shipment.openedAt"], outputs: ["contactInfo.surcharge", "contactInfo.health"], rules: [ + [">= d('2025-01-01')", "> d('2000-06-30')", ">= d('2000-06-30')", "shipment.qty", "(shipment.qty * shipment.qty)"], + [">= d('2025-03-20')", "> d('2025-03-20')", ">= d('2025-01-01')", "sum(map(shipment.loans, -(#.summary)))", "2"], + [">= d('2025-01-01')", "< d('2025-03-20')", "< d('2024-01-01')", "(shipment.score ?? 0)", "(shipment.qty) / (abs((contactInfo.limit ?? 0)) + 1)"], + ["> d('2025-01-01')", "", "> d('2025-01-01')", "median([contactInfo.adjusted, 2, 0.5])", "1"], + [">= d('2000-06-30')", "> d('2024-01-01')", ">= d('2024-01-01')", "50", "(contactInfo.limit ?? 0)"], + ["> d('2000-06-30')", ">= d('2025-03-20')", "> d('2025-01-01')", "(5 + shipment.qty)", "((contactInfo.limit ?? 0) % (abs(1.5) + 1))"], + ["", "", "", "sum(map(shipment.loans, min([#.limit, (#.score ?? 0), 18])))", "shipment.qty"], + ]}, + {assertion: "loan.flags.bucket", conditions: [["or", "((loan.score ?? 0) in [43..97) or all(loan.employees, (1.5 == 0 and (#.weight ?? 0) <= 0.25)))", 2], ["or", "(shipment.sku ?? '') in ['A1', 'x']", 0], ["and", "shipment.contact.adjusted in (47..118)", 1]]}, + {match: "loan.summary", arms: [["(loan.vip or loan.flags.bucket)", "(shipment.calc.margin ?? 0)"], ["((loan.vip or loan.vip) and (loan.flags.bucket and loan.flags.bucket))", "trunc(sum(map(loan.employees, (#.weight ?? 0))))"], ["(matches(shipment.contact.sku, '^.{2,}$') or startsWith(shipment.contact.sku, 'gold'))", "(shipment.contact.adjusted * 0)"], ["", "len((loan.label ?? ''))"]]}, + {expression: "contactInfo.total", value: "((contactInfo.vip or (rank ?? false)) ? shipment.sku : null)"}, + {table: "t10", hit: "collect", inputs: ["round(loan.summary / 7, 2)", "(shipment.contact.limit ?? 0)"], outputs: ["loan.eligible"], rules: [ + ["1000", "!= 0.25", "loan.capped"], + ["[3..171]", "3, 3", "loan.capped"], + ["!= 250", "<= 1000", "(scores.exposure ?? 0) <= (shipment.score ?? 0)"], + ]}, + ], + }, + cases: [ + [{shipment: {score: 3, sku: "", birthDate: "2030-12-31", since: "1990-06-15", qty: 250, openedAt: "2024-01-01", loans: [{limit: 1.5, score: 0.5, vip: false, label: "", employees: [{weight: 1000, status: "pending"}, {weight: 7.25, status: "pending"}]}, {limit: 50, score: 0.000001, vip: true, label: "é ü", employees: [{weight: 18, status: "open"}, {weight: 1.5, status: "pending"}]}], contact: {limit: 0.5, sku: "a-b-c", vip: false}}}, {net: [false], rank: false, scores: {exposure: 15625000}, shipment: {birthDate: "2030-12-31", calc: {margin: 0.5}, contact: {adjusted: 1.5, health: [250], limit: 0.5, sku: "a-b-c", surcharge: [0.500001], total: null, vip: false}, loans: [{discount: [], eligible: [false], employees: [{status: "pending", weight: 1000}, {status: "pending", weight: 7.25}], flags: {bucket: false}, label: "", limit: 1.5, points: [], quota: "1990-06-15", score: 0.5, share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [{status: "open", weight: 18}, {status: "pending", weight: 1.5}], flags: {bucket: false}, label: "é ü", limit: 50, points: [], quota: "1990-06-15", score: 0.000001, share: [], summary: 0.5, vip: true}], openedAt: "2024-01-01", qty: 250, score: 3, since: "1990-06-15", sku: ""}}], + [{shipment: {score: 100, sku: null, birthDate: null, since: "1990-06-15", qty: 3, openedAt: "2030-12-31", loans: [{limit: 0, vip: false, employees: [{weight: 0.5, status: "pending"}, {weight: null, status: "open"}, {weight: null, status: "open"}]}, {limit: 2, score: 0.25, vip: false, employees: []}, {limit: 1.5, score: null, vip: false, label: "none", employees: [{weight: null, status: "closed"}, {weight: 2, status: "pending"}, {weight: 0.1, status: "open"}]}, {limit: 0.25, vip: false, label: null, employees: []}, {limit: 0, vip: true, employees: [{weight: 0.25, status: "pending"}, {weight: 0.25, status: "open"}, {weight: null, status: "open"}]}, {limit: 123456789.123, score: 250, vip: false, employees: [{weight: -0.01, status: "open"}, {weight: null, status: "open"}, {weight: 1000000, status: "open"}]}, {limit: 1000, score: 250, vip: false, label: null, employees: [{weight: null, status: "pending"}, {status: "pending"}, {weight: 0.25, status: "open"}]}, {limit: 250, score: null, vip: true, employees: [{weight: 0.000001, status: "pending"}, {status: "closed"}]}, {limit: 18, score: 5, vip: false, employees: []}, {limit: 1, vip: true, label: "12", employees: [{status: "open"}, {weight: null, status: "open"}]}, {limit: 3, score: null, vip: true, label: "12", employees: [{weight: 0.5, status: "closed"}, {weight: 2, status: "pending"}]}, {limit: 5, score: 5, vip: false, label: null, employees: [{weight: null, status: "open"}, {weight: 0, status: "open"}, {weight: 1e3, status: "open"}]}, {limit: -500, vip: true, employees: []}], contact: {limit: null, sku: "Oslo", vip: false}}}, {net: [false], rank: false, scores: {exposure: 27}, shipment: {birthDate: null, calc: {margin: null}, contact: {adjusted: 8, health: [1, 3], limit: null, sku: "Oslo", surcharge: [2, -453.75], total: null, vip: false}, loans: [{discount: [], eligible: [true], employees: [{status: "pending", weight: 0.5}, {status: "open", weight: null}, {status: "open", weight: null}], flags: {bucket: false}, limit: 0, points: [], quota: "1990-06-15", share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, limit: 2, points: [], quota: "1990-06-15", score: 0.25, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [{status: "closed", weight: null}, {status: "pending", weight: 2}, {status: "open", weight: 0.1}], flags: {bucket: false}, label: "none", limit: 1.5, points: [], quota: "1990-06-15", score: null, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, label: null, limit: 0.25, points: [], quota: "1990-06-15", share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [{status: "pending", weight: 0.25}, {status: "open", weight: 0.25}, {status: "open", weight: null}], flags: {bucket: false}, limit: 0, points: [], quota: "1990-06-15", share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [{status: "open", weight: -0.01}, {status: "open", weight: null}, {status: "open", weight: 1000000}], flags: {bucket: false}, limit: 123456789.123, points: [], quota: "1990-06-15", score: 250, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [{status: "pending", weight: null}, {status: "pending"}, {status: "open", weight: 0.25}], flags: {bucket: false}, label: null, limit: 1000, points: [], quota: "1990-06-15", score: 250, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [{status: "pending", weight: 0.000001}, {status: "closed"}], flags: {bucket: false}, limit: 250, points: [], quota: "1990-06-15", score: null, share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, limit: 18, points: [], quota: "1990-06-15", score: 5, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [{status: "open"}, {status: "open", weight: null}], flags: {bucket: false}, label: "12", limit: 1, points: [], quota: "1990-06-15", share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [{status: "closed", weight: 0.5}, {status: "pending", weight: 2}], flags: {bucket: false}, label: "12", limit: 3, points: [], quota: "1990-06-15", score: null, share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [{status: "open", weight: null}, {status: "open", weight: 0}, {status: "open", weight: 1000}], flags: {bucket: false}, label: null, limit: 5, points: [], quota: "1990-06-15", score: 5, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, limit: -500, points: [], quota: "1990-06-15", share: [], summary: 0, vip: true}], openedAt: "2030-12-31", qty: 3, score: 100, since: "1990-06-15", sku: null}}], + [{shipment: {score: 100, sku: "abc", birthDate: "2025-03-20", since: "2000-01-01", qty: 2, openedAt: "1990-06-15", loans: [], contact: {limit: 1, sku: "Oslo", vip: false}}}, {net: [false, false], rank: true, scores: {exposure: 1}, shipment: {birthDate: "2025-03-20", contact: {adjusted: 0, health: [2], limit: 1, sku: "Oslo", surcharge: [0], total: "abc", vip: false}, loans: [], openedAt: "1990-06-15", qty: 2, score: 100, since: "2000-01-01", sku: "abc"}}], + [{shipment: {score: 250, sku: "DE", birthDate: "2025-03-20", since: "2025-03-20", qty: 250, openedAt: 20250101, loans: [{limit: -0.01, score: 3, vip: true, label: "Zed", employees: [{weight: 7.25, status: "closed"}, {weight: 0, status: "pending"}]}, {limit: 1.5, score: 99.99, vip: false, label: "é ü", employees: [{weight: 65, status: "open"}]}, {limit: 1.5, score: 0.25, vip: false, label: "DE", employees: []}], contact: {limit: 5, sku: "O'Neil", vip: true}}}, "!error: InputValidationFailed"], + [{shipment: {score: -0.01, sku: "A1", birthDate: "2024-01-01", since: "2030-12-31", qty: -500, openedAt: "2024-02-29", loans: [{limit: 0, score: 0.25, vip: false, label: "VIP", employees: [{weight: 100, status: "open"}, {weight: 1, status: "closed"}]}, {limit: 1, score: 18, vip: false, label: "DE", employees: [{weight: 3, status: "open"}, {weight: 0.5, status: "pending"}]}], contact: {limit: 0.5, sku: "retail", vip: true}}}, {net: [true], rank: true, scores: {exposure: 125000000}, shipment: {birthDate: "2024-01-01", calc: {margin: 0.5}, contact: {adjusted: 0.5, health: [0.5, -500], limit: 0.5, sku: "retail", surcharge: [50, 1], total: "A1", vip: true}, loans: [{discount: [], eligible: [false], employees: [{status: "open", weight: 100}, {status: "closed", weight: 1}], flags: {bucket: true}, label: "VIP", limit: 0, points: [], quota: "2030-12-31", score: 0.25, share: [], summary: 0.5, vip: false}, {discount: [], eligible: [false], employees: [{status: "open", weight: 3}, {status: "pending", weight: 0.5}], flags: {bucket: true}, label: "DE", limit: 1, points: [], quota: "2030-12-31", score: 18, share: [], summary: 0.5, vip: false}], openedAt: "2024-02-29", qty: -500, score: -0.01, since: "2030-12-31", sku: "A1"}}], + [{shipment: {score: 1, sku: "abc", birthDate: "not a date", since: "2024-02-29", qty: 123456789.123, openedAt: "1990-06-15", loans: [{limit: 0.5, score: 1000000, vip: false, label: "gold", employees: []}], contact: {limit: 0.5, sku: "VIP", vip: false}}}, "!error: InputValidationFailed"], + [{shipment: {score: 0, sku: "12", birthDate: "1990-06-15", since: "2024-02-29", qty: 99999999999999999999, openedAt: "1990-06-15", loans: [{limit: 193, score: 0, vip: false, label: "VIP", employees: [{weight: 50, status: "open"}]}, {limit: 5, score: 138, vip: true, label: " pad ", employees: [{weight: -500, status: "open"}]}, {limit: 0, score: 0.5, vip: true, label: "x-y", employees: [{weight: -0.5, status: "open"}, {weight: 1e3, status: "open"}]}, {limit: 250, score: 0.5, vip: false, label: "A1", employees: []}], contact: {limit: 2, sku: "a", vip: false}}}, {net: [false], rank: false, scores: {exposure: 1000000000}, shipment: {birthDate: "1990-06-15", calc: {margin: 2}, contact: {adjusted: 4, health: [99999999999999999999], limit: 2, sku: "a", surcharge: [5.5], total: null, vip: false}, loans: [{discount: [], eligible: [false], employees: [{status: "open", weight: 50}], flags: {bucket: false}, label: "VIP", limit: 193, points: [], quota: "2024-02-29", score: 0, share: [], summary: 3, vip: false}, {discount: [], eligible: [false], employees: [{status: "open", weight: -500}], flags: {bucket: false}, label: " pad ", limit: 5, points: [], quota: "2024-02-29", score: 138, share: [], summary: 2, vip: true}, {discount: [], eligible: [false], employees: [{status: "open", weight: -0.5}, {status: "open", weight: 1000}], flags: {bucket: false}, label: "x-y", limit: 0, points: [], quota: "2024-02-29", score: 0.5, share: [], summary: 2, vip: true}, {discount: [], eligible: [false], employees: [], flags: {bucket: true}, label: "A1", limit: 250, points: [], quota: "2024-02-29", score: 0.5, share: [], summary: 2, vip: false}], openedAt: "1990-06-15", qty: 99999999999999999999, score: 0, since: "2024-02-29", sku: "12"}}], + [{shipment: {score: 1, sku: "é ü", birthDate: "2025-03-20", since: "2024-01-01", qty: 0, openedAt: "2000-01-01", loans: [], contact: {limit: 0, sku: "retail", vip: false}, extraField: {nested: true}}}, {net: [false, false], rank: true, scores: {exposure: 0}, shipment: {birthDate: "2025-03-20", contact: {adjusted: -1, health: [0], limit: 0, sku: "retail", surcharge: [0], total: "é ü", vip: false}, extraField: {nested: true}, loans: [], openedAt: "2000-01-01", qty: 0, score: 1, since: "2024-01-01", sku: "é ü"}}], + [{shipment: {score: 100, sku: "Zed", birthDate: "2025-03-20", since: "2030-12-31", qty: 0.25, openedAt: "1990-06-15", loans: [{limit: -0.01, score: 2, vip: true, label: "gold", employees: [{weight: 1, status: "closed"}, {weight: 1, status: "open"}]}, {limit: 10, score: 5, vip: true, label: "VIP", employees: [{weight: 0.1, status: "open"}]}, {limit: 3, score: 0, vip: true, label: "A1", employees: [{weight: 3, status: "closed"}, {weight: 99999999999999999999, status: "open"}]}, {limit: 3, score: 1.5, vip: true, label: "gold", employees: []}], contact: {limit: 1000, sku: "é ü", vip: false}}}, {net: [false], rank: false, scores: {exposure: 0.015625}, shipment: {birthDate: "2025-03-20", calc: {margin: 1000}, contact: {adjusted: 1000, health: [0.25], limit: 1000, sku: "é ü", surcharge: [6.49], total: null, vip: false}, loans: [{discount: [], eligible: [true], employees: [{status: "closed", weight: 1}, {status: "open", weight: 1}], flags: {bucket: false}, label: "gold", limit: -0.01, points: [], quota: "2030-12-31", score: 2, share: [], summary: 1000, vip: true}, {discount: [], eligible: [true], employees: [{status: "open", weight: 0.1}], flags: {bucket: false}, label: "VIP", limit: 10, points: [], quota: "2030-12-31", score: 5, share: [], summary: 1000, vip: true}, {discount: [], eligible: [true], employees: [{status: "closed", weight: 3}, {status: "open", weight: 99999999999999999999}], flags: {bucket: false}, label: "A1", limit: 3, points: [], quota: "2030-12-31", score: 0, share: [], summary: 1000, vip: true}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, label: "gold", limit: 3, points: [], quota: "2030-12-31", score: 1.5, share: [], summary: 1000, vip: true}], openedAt: "1990-06-15", qty: 0.25, score: 100, since: "2030-12-31", sku: "Zed"}}], + [{shipment: {score: 0.5, sku: "x-y", since: "2030-12-31", qty: 1000, openedAt: "2025-03-20", loans: [{limit: 2, vip: true, label: "é ü", employees: [{status: "open"}, {weight: 0, status: "open"}, {weight: null, status: "closed"}]}, {limit: 3, score: null, vip: true, label: "NL", employees: [{weight: null, status: "closed"}, {status: "pending"}, {weight: 1000, status: "pending"}]}], contact: {limit: null, sku: "DE", vip: true}}}, {net: [true], rank: true, scores: {exposure: 1000000000}, shipment: {calc: {margin: null}, contact: {adjusted: 1, health: [1000000, 2, 1, 0, 0, 1000], limit: null, sku: "DE", surcharge: [1000, -0, 1, 50, 1005, 0], total: "x-y", vip: true}, loans: [{discount: [], eligible: [false], employees: [{status: "open"}, {status: "open", weight: 0}, {status: "closed", weight: null}], flags: {bucket: false}, label: "é ü", limit: 2, points: [], quota: "2030-12-31", share: [], summary: 0, vip: true}, {discount: [], eligible: [false], employees: [{status: "closed", weight: null}, {status: "pending"}, {status: "pending", weight: 1000}], flags: {bucket: false}, label: "NL", limit: 3, points: [], quota: "2030-12-31", score: null, share: [], summary: 0, vip: true}], openedAt: "2025-03-20", qty: 1000, score: 0.5, since: "2030-12-31", sku: "x-y"}}], + [{shipment: {score: 3, sku: "none", birthDate: "2025-03-20", since: "2024-02-29", qty: 1000000, openedAt: "2025-03-20T10:15:30Z", loans: [{limit: -1, score: 100, vip: false, label: "", employees: [{weight: 3, status: "closed"}, {weight: 5, status: "open"}]}, {limit: 99.99, score: 0.5, vip: false, label: "a", employees: []}], contact: {limit: 0, sku: "VIP", vip: false}}}, {net: [false, false], rank: true, scores: {exposure: 0}, shipment: {birthDate: "2025-03-20", calc: {margin: 0}, contact: {adjusted: 0, health: [1000000000000, 1, 0, 1000000], limit: 0, sku: "VIP", surcharge: [1000000, 0.5, 50, -0.5], total: "none", vip: false}, loans: [{discount: [], eligible: [true], employees: [{status: "closed", weight: 3}, {status: "open", weight: 5}], flags: {bucket: false}, label: "", limit: -1, points: [], quota: "2024-02-29", score: 100, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, label: "a", limit: 99.99, points: [], quota: "2024-02-29", score: 0.5, share: [], summary: 0, vip: false}], openedAt: "2025-03-20T10:15:30Z", qty: 1000000, score: 3, since: "2024-02-29", sku: "none"}}], + [{shipment: {score: 361, sku: "", birthDate: "1990-06-15", since: "2025-03-20T10:15:30Z", qty: 0.5, openedAt: "2030-12-31", loans: [{limit: 0.5, score: 123456789.123, vip: false, label: "a", employees: [{weight: 0.25, status: "closed"}]}, {limit: 250, score: 1, vip: false, label: "VIP", employees: [{weight: 18, status: "open"}, {weight: 18, status: "open"}, {weight: 50, status: "pending"}]}, {limit: 99999999999999999999, score: 99.99, vip: true, label: "a", employees: []}, {limit: 1, score: 0.000001, vip: true, label: "NL", employees: [{weight: 3, status: "pending"}, {weight: 0.1, status: "open"}]}], contact: {limit: 0.25, sku: "retail", vip: false}, extraField: "x"}}, {net: [false], rank: true, scores: {exposure: 0.125}, shipment: {birthDate: "1990-06-15", calc: {margin: 0.25}, contact: {adjusted: 0.25, health: [0.25, 2, 1, 0.25, 0.25, 0.5], limit: 0.25, sku: "retail", surcharge: [0.5, -0.50, 0.5, 50, 5.5, 19.500001], total: "", vip: false}, extraField: "x", loans: [{discount: [], eligible: [true], employees: [{status: "closed", weight: 0.25}], flags: {bucket: false}, label: "a", limit: 0.5, points: [], quota: "2025-03-20T10:15:30Z", score: 123456789.123, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [{status: "open", weight: 18}, {status: "open", weight: 18}, {status: "pending", weight: 50}], flags: {bucket: false}, label: "VIP", limit: 250, points: [], quota: "2025-03-20T10:15:30Z", score: 1, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, label: "a", limit: 99999999999999999999, points: [true], quota: "2025-03-20T10:15:30Z", score: 99.99, share: [0.25], summary: 0.25, vip: true}, {discount: [], eligible: [true], employees: [{status: "pending", weight: 3}, {status: "open", weight: 0.1}], flags: {bucket: false}, label: "NL", limit: 1, points: [true], quota: "2025-03-20T10:15:30Z", score: 0.000001, share: [0.25], summary: 0.25, vip: true}], openedAt: "2030-12-31", qty: 0.5, score: 361, since: "2025-03-20T10:15:30Z", sku: ""}}], + [{shipment: {score: 1.5, sku: "", birthDate: "2025-03-20T10:15:30Z", since: "2024-01-01", qty: 1.5, openedAt: "2030-12-31", loans: [{limit: 50, score: 0.25, vip: false, label: "NL", employees: [{weight: 340, status: "closed"}, {weight: 10, status: "pending"}]}, {limit: 250, score: 1000, vip: true, label: "Zed", employees: [{weight: 0, status: "open"}, {weight: 1000, status: "pending"}]}], contact: {limit: 0, sku: "x", vip: false}}}, {net: [false, false], rank: true, scores: {exposure: 0}, shipment: {birthDate: "2025-03-20T10:15:30Z", calc: {margin: 0}, contact: {adjusted: 0, health: [2.25, 1, 1.5], limit: 0, sku: "x", surcharge: [1.5, 0.5, 18.25], total: "", vip: false}, loans: [{discount: [], eligible: [true], employees: [{status: "closed", weight: 340}, {status: "pending", weight: 10}], flags: {bucket: false}, label: "NL", limit: 50, points: [], quota: "2024-01-01", score: 0.25, share: [], summary: 2, vip: false}, {discount: [], eligible: [true], employees: [{status: "open", weight: 0}, {status: "pending", weight: 1000}], flags: {bucket: false}, label: "Zed", limit: 250, points: [true], quota: "2024-01-01", score: 1000, share: [0], summary: 0, vip: true}], openedAt: "2030-12-31", qty: 1.5, score: 1.5, since: "2024-01-01", sku: ""}}], + [{shipment: {score: null, sku: null, birthDate: "2024-02-29", since: "2000-01-01", qty: 0, openedAt: "2000-01-01", loans: [{limit: 1e3, score: null, vip: true, label: "gold", employees: [{status: "open"}, {weight: 0.25, status: "closed"}]}, {limit: 1.5, score: 165, vip: false, label: "gold", employees: [{weight: null, status: "open"}, {weight: 2, status: "open"}, {weight: 0.5, status: "closed"}]}, {limit: 99.99, score: 3, vip: true, label: "a", employees: []}, {limit: 5, score: 2, vip: true, label: "a", employees: [{weight: 250, status: "closed"}]}, {limit: 0.000001, score: -0.5, vip: false, label: null, employees: [{status: "pending"}, {status: "open"}, {weight: null, status: "closed"}]}, {limit: 1.5, score: null, vip: false, label: "DE", employees: [{status: "pending"}]}, {limit: 0, score: null, vip: true, label: "US", employees: [{status: "pending"}, {weight: null, status: "closed"}, {status: "closed"}]}, {limit: 2, score: null, vip: false, label: "a-b-c", employees: []}], contact: {limit: null, sku: "日本", vip: true}}}, {net: [true], rank: false, scores: {exposure: 0}, shipment: {birthDate: "2024-02-29", calc: {margin: null}, contact: {adjusted: 4, health: [0], limit: null, sku: "日本", surcharge: [6.0], total: null, vip: true}, loans: [{discount: [], eligible: [true], employees: [{status: "open"}, {status: "closed", weight: 0.25}], flags: {bucket: false}, label: "gold", limit: 1000, points: [], quota: "2000-01-01", score: null, share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [{status: "open", weight: null}, {status: "open", weight: 2}, {status: "closed", weight: 0.5}], flags: {bucket: false}, label: "gold", limit: 1.5, points: [], quota: "2000-01-01", score: 165, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, label: "a", limit: 99.99, points: [], quota: "2000-01-01", score: 3, share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [{status: "closed", weight: 250}], flags: {bucket: false}, label: "a", limit: 5, points: [], quota: "2000-01-01", score: 2, share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [{status: "pending"}, {status: "open"}, {status: "closed", weight: null}], flags: {bucket: false}, label: null, limit: 0.000001, points: [], quota: "2000-01-01", score: -0.5, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [{status: "pending"}], flags: {bucket: false}, label: "DE", limit: 1.5, points: [], quota: "2000-01-01", score: null, share: [], summary: 0, vip: false}, {discount: [], eligible: [true], employees: [{status: "pending"}, {status: "closed", weight: null}, {status: "closed"}], flags: {bucket: false}, label: "US", limit: 0, points: [], quota: "2000-01-01", score: null, share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [], flags: {bucket: true}, label: "a-b-c", limit: 2, points: [], quota: "2000-01-01", score: null, share: [], summary: 0, vip: false}], openedAt: "2000-01-01", qty: 0, score: null, since: "2000-01-01", sku: null}}], + [{shipment: {score: 250, sku: "Oslo", birthDate: "2000-01-01", since: "2000-01-01", qty: 0, openedAt: "2025-03-20", loans: [{limit: 250, score: null, vip: true, employees: []}, {limit: 1.5, vip: true, label: "x", employees: [{status: "closed"}]}, {limit: 1000000, score: null, vip: false, label: "日本", employees: [{weight: null, status: "pending"}, {weight: 250, status: "pending"}]}], contact: {sku: "a", vip: true}}}, {net: [true], rank: false, scores: {exposure: 0}, shipment: {birthDate: "2000-01-01", calc: {margin: null}, contact: {adjusted: 2, health: [1, 0], sku: "a", surcharge: [2, 0], total: "Oslo", vip: true}, loans: [{discount: [], eligible: [true], employees: [], flags: {bucket: true}, limit: 250, points: [], quota: "2000-01-01", score: null, share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [{status: "closed"}], flags: {bucket: false}, label: "x", limit: 1.5, points: [], quota: "2000-01-01", share: [], summary: 0, vip: true}, {discount: [], eligible: [true], employees: [{status: "pending", weight: null}, {status: "pending", weight: 250}], flags: {bucket: false}, label: "日本", limit: 1000000, points: [], quota: "2000-01-01", score: null, share: [], summary: 6, vip: false}], openedAt: "2025-03-20", qty: 0, score: 250, since: "2000-01-01", sku: "Oslo"}}], + [{shipment: {score: null, birthDate: "2024-01-01", since: "2025-03-20T10:15:30Z", qty: 1, openedAt: "2025-03-20T10:15:30Z", loans: [{limit: 250, vip: true, label: "", employees: [{status: "open"}, {weight: 1, status: "open"}]}, {limit: 1000, score: 5, vip: true, label: "a-b-c", employees: [{weight: 18, status: "open"}, {weight: 0.5, status: "open"}]}], contact: {limit: 1.5, sku: "A1", vip: false}}}, {net: [false], rank: false, scores: {exposure: 1}, shipment: {birthDate: "2024-01-01", calc: {margin: 1.5}, contact: {adjusted: 1.5, health: [1, 2, 1, 1.5, 1.5, 1], limit: 1.5, sku: "A1", surcharge: [1, -3.0, 1.5, 50, 6, 5], total: null, vip: false}, loans: [{discount: [], eligible: [false], employees: [{status: "open"}, {status: "open", weight: 1}], flags: {bucket: false}, label: "", limit: 250, points: [], quota: "2025-03-20T10:15:30Z", share: [], summary: 1.5, vip: true}, {discount: [], eligible: [false], employees: [{status: "open", weight: 18}, {status: "open", weight: 0.5}], flags: {bucket: false}, label: "a-b-c", limit: 1000, points: [], quota: "2025-03-20T10:15:30Z", score: 5, share: [], summary: 1.5, vip: true}], openedAt: "2025-03-20T10:15:30Z", qty: 1, score: null, since: "2025-03-20T10:15:30Z"}}], + [{shipment: {score: 0.5, sku: "US", birthDate: "2024-02-29", since: "2025-03-20", qty: 0.000001, openedAt: "2024-01-01", loans: [], contact: {limit: 99.99, sku: "abc", vip: true}}}, {net: [true], rank: false, scores: {exposure: 0.000000000000000001}, shipment: {birthDate: "2024-02-29", contact: {adjusted: 98.99, health: [99.99, 0.000001], limit: 99.99, sku: "abc", surcharge: [50, 0], total: "US", vip: true}, loans: [], openedAt: "2024-01-01", qty: 0.000001, score: 0.5, since: "2025-03-20", sku: "US"}}], + [{shipment: {score: 18, sku: "VIP", birthDate: "2025-03-20", since: "1990-06-15", qty: 3, openedAt: "1990-06-15", loans: [{limit: 0, vip: false, label: "retail", employees: []}, {limit: 1.5, vip: true, label: null, employees: [{weight: null, status: "open"}]}, {limit: 2, score: 250, vip: true, label: null, employees: [{status: "open"}, {weight: 99999999999999999999, status: "open"}]}, {limit: 2, vip: false, employees: [{status: "pending"}]}, {limit: 100, score: null, vip: false, label: null, employees: [{weight: null, status: "pending"}, {weight: -0, status: "open"}]}, {limit: 10, vip: true, label: null, employees: [{weight: 0.25, status: "open"}]}, {limit: 100, vip: true, label: "x-y", employees: [{weight: 2, status: "closed"}, {weight: 100, status: "closed"}]}, {limit: 1000, vip: false, label: "", employees: []}, {limit: 0.25, score: 1, vip: false, label: "A1", employees: [{status: "pending"}, {weight: 2, status: "closed"}]}, {limit: 7.25, score: 3, vip: true, label: null, employees: [{weight: null, status: "open"}, {weight: 1, status: "pending"}]}], contact: {limit: null, sku: "DE", vip: false}}}, {net: [false], rank: true, scores: {exposure: 27}, shipment: {birthDate: "2025-03-20", calc: {margin: null}, contact: {adjusted: 6, health: [3], limit: null, sku: "DE", surcharge: [5.25], total: "VIP", vip: false}, loans: [{discount: [], eligible: [false], employees: [], flags: {bucket: true}, label: "retail", limit: 0, points: [], quota: "1990-06-15", share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [{status: "open", weight: null}], flags: {bucket: false}, label: null, limit: 1.5, points: [], quota: "1990-06-15", share: [], summary: 0, vip: true}, {discount: [], eligible: [false], employees: [{status: "open"}, {status: "open", weight: 99999999999999999999}], flags: {bucket: false}, label: null, limit: 2, points: [], quota: "1990-06-15", score: 250, share: [], summary: 0, vip: true}, {discount: [], eligible: [false], employees: [{status: "pending"}], flags: {bucket: false}, limit: 2, points: [], quota: "1990-06-15", share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [{status: "pending", weight: null}, {status: "open", weight: 0}], flags: {bucket: false}, label: null, limit: 100, points: [], quota: "1990-06-15", score: null, share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [{status: "open", weight: 0.25}], flags: {bucket: false}, label: null, limit: 10, points: [], quota: "1990-06-15", share: [], summary: 0, vip: true}, {discount: [], eligible: [false], employees: [{status: "closed", weight: 2}, {status: "closed", weight: 100}], flags: {bucket: false}, label: "x-y", limit: 100, points: [], quota: "1990-06-15", share: [], summary: 0, vip: true}, {discount: [], eligible: [false], employees: [], flags: {bucket: true}, label: "", limit: 1000, points: [], quota: "1990-06-15", share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [{status: "pending"}, {status: "closed", weight: 2}], flags: {bucket: false}, label: "A1", limit: 0.25, points: [], quota: "1990-06-15", score: 1, share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [{status: "open", weight: null}, {status: "pending", weight: 1}], flags: {bucket: false}, label: null, limit: 7.25, points: [], quota: "1990-06-15", score: 3, share: [], summary: 0, vip: true}], openedAt: "1990-06-15", qty: 3, score: 18, since: "1990-06-15", sku: "VIP"}}], + [{shipment: {score: null, sku: null, birthDate: "2025-03-20T10:15:30Z", since: "2025-03-20", qty: 1000, openedAt: "2030-12-31", loans: [{limit: 2, vip: false, employees: [{weight: 1.5, status: "pending"}]}, {limit: 0.5, score: null, vip: false, employees: []}, {limit: 5, vip: false, label: null, employees: [{weight: 1000, status: "open"}]}, {limit: -0.01, vip: false, employees: [{status: "open"}, {weight: null, status: "closed"}, {weight: null, status: "open"}]}], contact: {limit: null, sku: "a-b-c", vip: false}}}, {net: [false], rank: false, scores: {exposure: 1000000000}, shipment: {birthDate: "2025-03-20T10:15:30Z", calc: {margin: null}, contact: {adjusted: 3, health: [1000000, 1, 0, 0, 1000], limit: null, sku: "a-b-c", surcharge: [1000, 2, 50, 1005, -0.01], total: null, vip: false}, loans: [{discount: [], eligible: [false], employees: [{status: "pending", weight: 1.5}], flags: {bucket: false}, limit: 2, points: [], quota: "2025-03-20", share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [], flags: {bucket: true}, limit: 0.5, points: [], quota: "2025-03-20", score: null, share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [{status: "open", weight: 1000}], flags: {bucket: false}, label: null, limit: 5, points: [], quota: "2025-03-20", share: [], summary: 0, vip: false}, {discount: [], eligible: [false], employees: [{status: "open"}, {status: "closed", weight: null}, {status: "open", weight: null}], flags: {bucket: false}, limit: -0.01, points: [], quota: "2025-03-20", share: [], summary: 0, vip: false}], openedAt: "2030-12-31", qty: 1000, score: null, since: "2025-03-20", sku: null}}], + [{shipment: {score: 0, sku: "VIP", birthDate: null, since: "2025-03-20", qty: 0, openedAt: "1990-06-15", loans: [{limit: 1, score: -0, vip: false, label: "日本", employees: [{weight: -0, status: "open"}, {status: "pending"}]}], contact: {limit: 3, sku: " pad ", vip: true}}}, {net: [true], rank: false, scores: {exposure: 0}, shipment: {birthDate: null, contact: {adjusted: 3, health: [0], limit: 3, sku: " pad ", surcharge: [0], total: "VIP", vip: true}, loans: [{discount: [], eligible: [true], employees: [{status: "open", weight: 0}, {status: "pending"}], flags: {bucket: false}, label: "日本", limit: 1, points: [], quota: "2025-03-20", score: 0, share: [], summary: 0, vip: false}], openedAt: "1990-06-15", qty: 0, score: 0, since: "2025-03-20", sku: "VIP"}}], + [{shipment: {score: 0.5, sku: "a-b-c", birthDate: "1990-06-15", since: "2030-12-31", qty: 0.5, openedAt: "1990-06-15", loans: [], contact: {limit: 100, sku: "gold", vip: false}}}, {net: [false], rank: false, scores: {exposure: 0.125}, shipment: {birthDate: "1990-06-15", contact: {adjusted: 99, health: [0.5], limit: 100, sku: "gold", surcharge: [0], total: null, vip: false}, loans: [], openedAt: "1990-06-15", qty: 0.5, score: 0.5, since: "2030-12-31", sku: "a-b-c"}}], + [{shipment: {score: 3, sku: "US", birthDate: "1990-06-15", since: "2025-03-20", qty: 18, openedAt: "2025-03-20", loans: [{limit: true, score: 1000, vip: false, label: "", employees: [{weight: 100, status: "pending"}, {weight: 2, status: "closed"}, {weight: 5, status: "open"}]}, {limit: 3, score: 1, vip: false, label: "a", employees: [{weight: 2, status: "closed"}, {weight: 250, status: "open"}, {weight: 1, status: "pending"}]}], contact: {limit: 221, sku: "", vip: true}}}, "!error: InputValidationFailed"], + [{shipment: {score: 0.5, sku: "é ü", birthDate: "2024-01-01", since: "1990-06-15", qty: 3, openedAt: "2024-02-29", loans: [], contact: {limit: 100, sku: "é ü", vip: false}}}, {net: [false], rank: false, scores: {exposure: 27}, shipment: {birthDate: "2024-01-01", contact: {adjusted: 99, health: [3], limit: 100, sku: "é ü", surcharge: [0], total: null, vip: false}, loans: [], openedAt: "2024-02-29", qty: 3, score: 0.5, since: "1990-06-15", sku: "é ü"}}], + [{shipment: {score: 1000, sku: "DE", birthDate: "1990-06-15", since: "2024-01-01", qty: 65, openedAt: "2025-03-20T10:15:30Z", loans: [{limit: 1, score: -0.01, vip: true, label: "Oslo", employees: [{weight: 0.5, status: "open"}, {weight: -0.01, status: "pending"}]}, {limit: 1.5, score: 18, vip: false, label: "gold", employees: []}], contact: {limit: 0.5, sku: "gold", vip: true}, extraField: "x"}}, {net: [true], rank: false, scores: {exposure: 274625}, shipment: {birthDate: "1990-06-15", calc: {margin: 0.5}, contact: {adjusted: 0.5, health: [4225, 1, 65], limit: 0.5, sku: "gold", surcharge: [65, 0.5, 1.49], total: "DE", vip: true}, extraField: "x", loans: [{discount: [1000], eligible: [false], employees: [{status: "open", weight: 0.5}, {status: "pending", weight: -0.01}], flags: {bucket: false}, label: "Oslo", limit: 1, points: [true, true], quota: "2024-01-01", score: -0.01, share: [1000, 0.5], summary: 0.5, vip: true}, {discount: [], eligible: [false], employees: [], flags: {bucket: true}, label: "gold", limit: 1.5, points: [], quota: "2024-01-01", score: 18, share: [], summary: 0.5, vip: false}], openedAt: "2025-03-20T10:15:30Z", qty: 65, score: 1000, since: "2024-01-01", sku: "DE"}}], + [{shipment: {score: 5, sku: "retail", birthDate: "2024-02-29", since: "2025-03-20", qty: 99999999999999999999, openedAt: "1990-06-15", loans: [], contact: {limit: 1.5, sku: "DE", vip: true}}}, {net: [true], rank: true, scores: {exposure: 1000000000}, shipment: {birthDate: "2024-02-29", contact: {adjusted: 0.5, health: [99999999999999999999], limit: 1.5, sku: "DE", surcharge: [0], total: "retail", vip: true}, loans: [], openedAt: "1990-06-15", qty: 99999999999999999999, score: 5, since: "2025-03-20", sku: "retail"}}], + [{shipment: {score: 250, sku: "a-b-c", birthDate: "2030-12-31", since: "2030-12-31", qty: 3, openedAt: "2000-01-01", loans: [], contact: {limit: 250, sku: "gold", vip: false}}}, {net: [false], rank: false, scores: {exposure: 27}, shipment: {birthDate: "2030-12-31", contact: {adjusted: 249, health: [3], limit: 250, sku: "gold", surcharge: [0], total: null, vip: false}, loans: [], openedAt: "2000-01-01", qty: 3, score: 250, since: "2030-12-31", sku: "a-b-c"}}], + [{shipment: {score: 2, sku: "a", birthDate: "2000-01-01", since: "2024-01-01", qty: 100, openedAt: "1990-06-15", loans: [], contact: {limit: 2, sku: "NL", vip: false}}}, {net: [false], rank: false, scores: {exposure: 1000000}, shipment: {birthDate: "2000-01-01", contact: {adjusted: 1, health: [100], limit: 2, sku: "NL", surcharge: [0], total: null, vip: false}, loans: [], openedAt: "1990-06-15", qty: 100, score: 2, since: "2024-01-01", sku: "a"}}], + [{shipment: {score: 1, sku: "gold", birthDate: "2000-01-01", since: "2030-12-31", qty: 100, openedAt: "2000-01-01", loans: [], contact: {limit: 1.5, sku: "O'Neil", vip: false}}}, {net: [false], rank: false, scores: {exposure: 1000000}, shipment: {birthDate: "2000-01-01", contact: {adjusted: 0.5, health: [100], limit: 1.5, sku: "O'Neil", surcharge: [0], total: null, vip: false}, loans: [], openedAt: "2000-01-01", qty: 100, score: 1, since: "2030-12-31", sku: "gold"}}], + [{shipment: {score: 3, sku: "", birthDate: "2000-01-01", since: "2030-12-31", qty: 250, openedAt: "2024-02-29", loans: [{limit: 100, score: -1, vip: true, label: "US", employees: [{weight: 250, status: "open"}, {weight: 0, status: "open"}]}, {limit: 250, score: 0.25, vip: true, label: "NL", employees: [{weight: 65, status: "pending"}, {weight: 2, status: "open"}]}], contact: {limit: -1, sku: "none", vip: true}, extraField: {nested: true}}}, {net: [true, true], rank: true, scores: {exposure: -1}, shipment: {birthDate: "2000-01-01", calc: {margin: -1}, contact: {adjusted: 0, health: [-1, 250], limit: -1, sku: "none", surcharge: [50, -0.75], total: "", vip: true}, extraField: {nested: true}, loans: [{discount: [], eligible: [true], employees: [{status: "open", weight: 250}, {status: "open", weight: 0}], flags: {bucket: false}, label: "US", limit: 100, points: [true], quota: "2030-12-31", score: -1, share: [-1], summary: -1, vip: true}, {discount: [], eligible: [true], employees: [{status: "pending", weight: 65}, {status: "open", weight: 2}], flags: {bucket: false}, label: "NL", limit: 250, points: [true], quota: "2030-12-31", score: 0.25, share: [-1], summary: -1, vip: true}], openedAt: "2024-02-29", qty: 250, score: 3, since: "2030-12-31", sku: ""}}], + [{shipment: {sku: "x", birthDate: "2025-03-20", since: "2030-12-31", qty: 0.1, openedAt: "2024-01-01", loans: [], contact: {limit: 0.25, sku: "A1", vip: true}}}, {net: [true, true], rank: true, scores: {exposure: 0.25}, shipment: {birthDate: "2025-03-20", contact: {adjusted: -0.75, health: [0.25, 0.1], limit: 0.25, sku: "A1", surcharge: [50, 0], total: "x", vip: true}, loans: [], openedAt: "2024-01-01", qty: 0.1, since: "2030-12-31", sku: "x"}}], + ], +} + +// seed 343000 (attempt 0) +{ + name: "b 31: applicant/items/payments: 1 assertion, 2 expression, 1 match, 3 table; 1 root, 10 per-member, 1 top-level computed", + policy: { + models: {applicant: {qty: "number", weight: "number", tier: "string(gold|silver|bronze)", items: "item[]"}, item: {age: "number?", birthDate: "date", income: "number?", payments: "payment[]"}, payment: {amount: "number"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {table: "t1", inputs: ["applicant.weight", "applicant.weight", null], outputs: ["item.exposure", "item.meta.health", "item.bonus"], rules: [ + ["[2..5]", "[0..328]", "item.birthDate >= d('2000-06-30')", "", "threshold", ""], + ["50", "[1..305]", "", "50", "applicant.weight", "threshold"], + ]}, + {expression: "item.decision", value: "item.birthDate >= d('2024-01-01')"}, + {expression: "item.penalty", value: "{s: median([threshold, (item.age ?? 0), (item.income ?? 0)])}"}, + {match: "applicant.weighted", arms: [["threshold > applicant.qty", "(min([abs(threshold), 1000]) ^ 3)"], ["threshold in [31..55)", "applicant.qty"], ["", "round(applicant.weight, 2)"]]}, + {assertion: "item.quota", conditions: [["and", "((item.age ?? 0) > 18 or (item.age ?? 0) in (22..199))", 0], ["or", "(item.bonus ?? 0) >= threshold", 0], ["or", "item.birthDate.isSameOrBefore(d('2025-01-01'), 'month')", 0], ["or", "applicant.tier in ['gold', 'bronze']", 0], ["or", "(item.exposure ?? 0) in [-2..123]", 0]]}, + {table: "t6", inputs: ["item.bonus", "item.meta.health"], outputs: ["item.meta.flag", "item.meta.adjusted[]", "item.fee[]"], rules: [ + ["3", "5", "'retail'", "", "applicant.weight"], + ["", "", "", "string(item.quota)", "applicant.qty"], + ]}, + {table: "t7", inputs: ["applicant.tier"], outputs: ["rank"], rules: [ + ["'gold'", "'x'"], + ["'bronze', 'silver'", "`${threshold}/${50 == 0.5}`"], + ["", "'ok'"], + ["'gold', 'silver'", ""], + ["", "'retail'"], + ]}, + ], + }, + cases: [ + [{threshold: 10, applicant: {qty: 0.000001, weight: 0, tier: "silver", items: []}}, {applicant: {items: [], qty: 0.000001, tier: "silver", weight: 0, weighted: 1000}, rank: "10/false", threshold: 10}], + [{threshold: -2, applicant: {qty: 2.50, weight: 10, tier: "bronze", items: [{age: 250, birthDate: "2000-01-01", income: null, payments: [{amount: -0.5}]}]}}, {applicant: {items: [{age: 250, birthDate: "2000-01-01", bonus: null, decision: false, exposure: null, fee: [2.50], income: null, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: -0.5}], penalty: {s: 0}, quota: true}], qty: 2.50, tier: "bronze", weight: 10, weighted: 10}, rank: "-2/false", threshold: -2}], + [{threshold: 10, applicant: {qty: 10, weight: 7.25, tier: "silver", items: []}}, {applicant: {items: [], qty: 10, tier: "silver", weight: 7.25, weighted: 7.25}, rank: "10/false", threshold: 10}], + [{threshold: 100, applicant: {qty: 0.1, weight: 1000, tier: "gold", items: [{age: null, birthDate: "2030-12-31", income: null, payments: []}, {age: -500, birthDate: "2000-01-01", income: -1, payments: [{amount: -1}, {amount: 50}]}, {age: null, birthDate: "2025-03-20T10:15:30Z", income: 123456789.123, payments: [{amount: -1}, {amount: 1}]}]}}, {applicant: {items: [{age: null, birthDate: "2030-12-31", bonus: null, decision: true, exposure: null, fee: [0.1], income: null, meta: {adjusted: ["true"], flag: null, health: null}, payments: [], penalty: {s: 0}, quota: true}, {age: -500, birthDate: "2000-01-01", bonus: null, decision: false, exposure: null, fee: [0.1], income: -1, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: -1}, {amount: 50}], penalty: {s: -1}, quota: true}, {age: null, birthDate: "2025-03-20T10:15:30Z", bonus: null, decision: true, exposure: null, fee: [0.1], income: 123456789.123, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: -1}, {amount: 1}], penalty: {s: 100}, quota: true}], qty: 0.1, tier: "gold", weight: 1000, weighted: 1000000}, rank: "x", threshold: 100}], + [{threshold: 100, applicant: {qty: 100, weight: -0.01, tier: "bronze", items: []}}, {applicant: {items: [], qty: 100, tier: "bronze", weight: -0.01, weighted: -0.01}, rank: "100/false", threshold: 100}], + [{threshold: 0, applicant: {qty: 50, weight: 10, tier: "gold", items: [{age: 0.1, birthDate: "1990-06-15", income: 0.1, payments: [{amount: 0.5}, {amount: 18}, {amount: 0.5}]}, {age: 50, birthDate: "2025-03-20T10:15:30Z", income: 250, payments: [{amount: 1}, {amount: 1e3}, {amount: 50}]}]}}, {applicant: {items: [{age: 0.1, birthDate: "1990-06-15", bonus: null, decision: false, exposure: null, fee: [50], income: 0.1, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: 0.5}, {amount: 18}, {amount: 0.5}], penalty: {s: 0.1}, quota: true}, {age: 50, birthDate: "2025-03-20T10:15:30Z", bonus: null, decision: true, exposure: null, fee: [50], income: 250, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: 1}, {amount: 1000}, {amount: 50}], penalty: {s: 50}, quota: true}], qty: 50, tier: "gold", weight: 10, weighted: 10}, rank: "x", threshold: 0}], + [{threshold: -2, applicant: {qty: 2, weight: 65, tier: "silver", items: [{age: 100, birthDate: "2025-03-20", income: 1.5, payments: [{amount: 100}, {amount: 2}]}]}}, {applicant: {items: [{age: 100, birthDate: "2025-03-20", bonus: null, decision: true, exposure: null, fee: [2], income: 1.5, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: 100}, {amount: 2}], penalty: {s: 1.5}, quota: true}], qty: 2, tier: "silver", weight: 65, weighted: 65}, rank: "-2/false", threshold: -2}], + [{threshold: 0, applicant: {qty: 5, weight: 50, tier: "silver", items: []}}, {applicant: {items: [], qty: 5, tier: "silver", weight: 50, weighted: 50}, rank: "0/false", threshold: 0}], + [{threshold: -2, applicant: {qty: 0.5, weight: 0, tier: "gold", items: [{age: 50, birthDate: "2024-02-29", income: 50, payments: [{amount: 2}, {amount: 1.5}, {amount: 5}]}, {age: 50, birthDate: "2025-03-20", income: 5, payments: []}, {age: 0, birthDate: "2025-03-20T10:15:30Z", income: 0, payments: []}], extraField: {nested: true}}}, {applicant: {extraField: {nested: true}, items: [{age: 50, birthDate: "2024-02-29", bonus: null, decision: true, exposure: null, fee: [0.5], income: 50, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: 2}, {amount: 1.5}, {amount: 5}], penalty: {s: 50}, quota: true}, {age: 50, birthDate: "2025-03-20", bonus: null, decision: true, exposure: null, fee: [0.5], income: 5, meta: {adjusted: ["true"], flag: null, health: null}, payments: [], penalty: {s: 5}, quota: true}, {age: 0, birthDate: "2025-03-20T10:15:30Z", bonus: null, decision: true, exposure: null, fee: [0.5], income: 0, meta: {adjusted: ["true"], flag: null, health: null}, payments: [], penalty: {s: 0}, quota: true}], qty: 0.5, tier: "gold", weight: 0, weighted: 0}, rank: "x", threshold: -2}], + [{threshold: 0.5, applicant: {qty: 0.5, weight: 250, tier: "gold", items: [{age: 1, birthDate: "1990-06-15", income: 2, payments: []}, {age: 7.25, birthDate: "2025-03-20", income: 2, payments: [{amount: -0.01}]}, {age: 7.25, birthDate: "1990-06-15", income: 0.000001, payments: []}]}}, {applicant: {items: [{age: 1, birthDate: "1990-06-15", bonus: null, decision: false, exposure: null, fee: [0.5], income: 2, meta: {adjusted: ["true"], flag: null, health: null}, payments: [], penalty: {s: 1}, quota: true}, {age: 7.25, birthDate: "2025-03-20", bonus: null, decision: true, exposure: null, fee: [0.5], income: 2, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: -0.01}], penalty: {s: 2}, quota: true}, {age: 7.25, birthDate: "1990-06-15", bonus: null, decision: false, exposure: null, fee: [0.5], income: 0.000001, meta: {adjusted: ["true"], flag: null, health: null}, payments: [], penalty: {s: 0.5}, quota: true}], qty: 0.5, tier: "gold", weight: 250, weighted: 250}, rank: "x", threshold: 0.5}], + [{threshold: 100, applicant: {qty: 99.99, weight: 50, tier: "gold", items: [{age: 5, birthDate: "2025-03-20", income: 1e3, payments: [{amount: 10}, {amount: 1000}, {amount: 0.1}]}, {age: 99.99, birthDate: "2000-01-01", income: 3, payments: [{amount: 18}, {amount: 1}]}]}}, {applicant: {items: [{age: 5, birthDate: "2025-03-20", bonus: 100, decision: true, exposure: 50, fee: [99.99], income: 1000, meta: {adjusted: ["true"], flag: null, health: 50}, payments: [{amount: 10}, {amount: 1000}, {amount: 0.1}], penalty: {s: 100}, quota: true}, {age: 99.99, birthDate: "2000-01-01", bonus: 100, decision: false, exposure: 50, fee: [99.99], income: 3, meta: {adjusted: ["true"], flag: null, health: 50}, payments: [{amount: 18}, {amount: 1}], penalty: {s: 99.99}, quota: true}], qty: 99.99, tier: "gold", weight: 50, weighted: 1000000}, rank: "x", threshold: 100}], + [{threshold: 10, applicant: {qty: 0, weight: 5, tier: "gold", items: [{age: 100, birthDate: "2025-03-20", income: 1000, payments: [{amount: 5}, {amount: 1}, {amount: 1000000}]}, {birthDate: "2030-12-31", income: -500, payments: [{amount: 1e3}, {amount: 1e3}, {amount: 7.25}]}, {birthDate: "2024-01-01", payments: [{amount: 10}, {amount: 0}]}]}}, {applicant: {items: [{age: 100, birthDate: "2025-03-20", bonus: null, decision: true, exposure: null, fee: [0], income: 1000, meta: {adjusted: ["true"], flag: null, health: 10}, payments: [{amount: 5}, {amount: 1}, {amount: 1000000}], penalty: {s: 100}, quota: true}, {birthDate: "2030-12-31", bonus: null, decision: true, exposure: null, fee: [0], income: -500, meta: {adjusted: ["true"], flag: null, health: 10}, payments: [{amount: 1000}, {amount: 1000}, {amount: 7.25}], penalty: {s: 0}, quota: true}, {birthDate: "2024-01-01", bonus: null, decision: true, exposure: null, fee: [0], meta: {adjusted: ["true"], flag: null, health: 10}, payments: [{amount: 10}, {amount: 0}], penalty: {s: 0}, quota: true}], qty: 0, tier: "gold", weight: 5, weighted: 1000}, rank: "x", threshold: 10}], + [{threshold: 1, applicant: {qty: 1e3, weight: 0.5, tier: "gold", items: [{age: 1, birthDate: "1990-06-15", income: 0, payments: [{amount: 0}]}]}}, {applicant: {items: [{age: 1, birthDate: "1990-06-15", bonus: null, decision: false, exposure: null, fee: [1000], income: 0, meta: {adjusted: ["true"], flag: null, health: null}, payments: [{amount: 0}], penalty: {s: 1}, quota: true}], qty: 1000, tier: "gold", weight: 0.5, weighted: 0.5}, rank: "x", threshold: 1}], + ], +} + +// seed 343100 (attempt 0) +{ + name: "b 32: account/lines/payments + report: 5 expression, 2 match, 2 table; 4 root, 3 per-member, 3 top-level computed", + policy: { + models: {account: {balance: "number", active: "boolean", insured: "boolean", country: "string", lines: "line[]", report: "creditReport"}, line: {income: "number?", amount: "number", code: "string", payments: "payment[]?"}, payment: {rate: "number", tier: "string(gold|silver|bronze)"}, creditReport: {balance: "number"}}, + blocks: [ + {match: "line.exposure", arms: [["not (isNumeric(account.country))", "count((line.payments ?? []), (#.rate > 0.25 and 100 == 2))"], ["", "len(filter((line.payments ?? []), not (#.rate == 1)))"]]}, + {match: "creditReport.discount", arms: [["matches(account.country, '^.{2,}$')", "`${account.country}/${capped.a}`"], ["", "'Oslo'"]]}, + {table: "t8", inputs: ["account.insured"], outputs: ["account.scores.eligible", "account.points[]"], rules: [ + ["", "account.report.discount", "account.country"], + ["true", "", "`${250}/${account.report.meta.net}`"], + ["", "", "account.report.discount"], + ["", "account.report.discount", "'low'"], + ["true", "account.country", "account.report.discount"], + ["", "(account.active ? account.country : account.report.discount)", ""], + ]}, + {expression: "account.scores.health", value: "(split(account.report.discount, '-')[1] ?? 'none')"}, + {expression: "capped", value: "{s: len(account.lines), a: len(filter(account.lines, contains(['high', 'retail', ''], #.code)))}"}, + {expression: "line.calc.quota", value: "upper(account.country)"}, + {table: "t9", inputs: ["(capped.s + account.report.balance)", "account.active", "account.report.discount"], outputs: ["account.ok"], rules: [ + ["< 3", "true", "$ != 'VIP'", "`${(account.scores.eligible ?? '')}/${account.active}`"], + ["<= 1000", "false", "'A1', 'high'", "account.country"], + ["< 100", "false", "", "account.report.discount"], + ["", "", "", "(account.scores.eligible ?? '')"], + ]}, + {expression: "creditReport.meta.net", value: "(min([abs(len(filter(account.lines, (#.income ?? 0) > #.amount))), 1000]) ^ 1)"}, + {expression: "line.weighted", value: "line.income"}, + ], + }, + cases: [ + [{account: {balance: 100, active: true, insured: true, country: "-", lines: [{income: 250, amount: 0.1, code: "NL", payments: [{rate: 3, tier: "silver"}, {rate: 2, tier: "bronze"}]}], report: {balance: 0}}}, {account: {active: true, balance: 100, country: "-", insured: true, lines: [{amount: 0.1, calc: {quota: "-"}, code: "NL", exposure: 0, income: 250, payments: [{rate: 3, tier: "silver"}, {rate: 2, tier: "bronze"}], weighted: 250}], ok: "Oslo/true", points: ["-", "250/1", "Oslo", "low", "Oslo"], report: {balance: 0, discount: "Oslo", meta: {net: 1}}, scores: {eligible: "Oslo"}}, capped: {a: 0, s: 1}}], + [{account: {balance: 0, active: false, insured: false, country: "x", lines: [{income: 0.5, amount: 3, code: "low", payments: [{rate: 1e3, tier: "silver"}, {rate: 18, tier: "bronze"}]}, {income: -500, amount: 50, code: "US", payments: [{rate: 1000, tier: "gold"}, {rate: 3, tier: "bronze"}, {rate: 1.5, tier: "gold"}]}, {income: -500, amount: 0.000001, code: "Zed", payments: [{rate: 1000, tier: "silver"}, {rate: 250, tier: "silver"}]}, {income: 7.25, amount: 100, code: " pad "}], report: {balance: 0.25}}}, {account: {active: false, balance: 0, country: "x", insured: false, lines: [{amount: 3, calc: {quota: "X"}, code: "low", exposure: 0, income: 0.5, payments: [{rate: 1000, tier: "silver"}, {rate: 18, tier: "bronze"}], weighted: 0.5}, {amount: 50, calc: {quota: "X"}, code: "US", exposure: 0, income: -500, payments: [{rate: 1000, tier: "gold"}, {rate: 3, tier: "bronze"}, {rate: 1.5, tier: "gold"}], weighted: -500}, {amount: 0.000001, calc: {quota: "X"}, code: "Zed", exposure: 0, income: -500, payments: [{rate: 1000, tier: "silver"}, {rate: 250, tier: "silver"}], weighted: -500}, {amount: 100, calc: {quota: "X"}, code: " pad ", exposure: 0, income: 7.25, weighted: 7.25}], ok: "Oslo", points: ["x", "Oslo", "low"], report: {balance: 0.25, discount: "Oslo", meta: {net: 0}}, scores: {eligible: "Oslo"}}, capped: {a: 0, s: 4}}], + [{account: {balance: 0.000001, active: false, insured: true, country: "a-b-c", lines: [], report: {balance: 99999999999999999999}}}, {account: {active: false, balance: 0.000001, country: "a-b-c", insured: true, lines: [], ok: "a-b-c/0", points: ["a-b-c", "250/0", "a-b-c/0", "low", "a-b-c/0"], report: {balance: 99999999999999999999, discount: "a-b-c/0", meta: {net: 0}}, scores: {eligible: "a-b-c/0"}}, capped: {a: 0, s: 0}}], + [{account: {balance: 65, active: false, insured: false, country: "x-y", lines: [], report: {balance: 1e3}}}, {account: {active: false, balance: 65, country: "x-y", insured: false, lines: [], ok: "x-y/0", points: ["x-y", "x-y/0", "low"], report: {balance: 1000, discount: "x-y/0", meta: {net: 0}}, scores: {eligible: "x-y/0"}}, capped: {a: 0, s: 0}}], + [{account: {balance: 99999999999999999999, active: false, insured: true, country: "A1", lines: [{income: 1, amount: 123456789.123, code: "Zed", payments: []}, {income: -500, amount: -500, code: "", payments: null}, {income: 100, amount: 0.5, code: "Zed", payments: [{rate: 99999999999999999999, tier: "silver"}, {rate: 0.1, tier: "silver"}]}], report: {balance: 10}}}, {account: {active: false, balance: 99999999999999999999, country: "A1", insured: true, lines: [{amount: 123456789.123, calc: {quota: "A1"}, code: "Zed", exposure: 0, income: 1, payments: [], weighted: 1}, {amount: -500, calc: {quota: "A1"}, code: "", exposure: 0, income: -500, payments: null, weighted: -500}, {amount: 0.5, calc: {quota: "A1"}, code: "Zed", exposure: 0, income: 100, payments: [{rate: 99999999999999999999, tier: "silver"}, {rate: 0.1, tier: "silver"}], weighted: 100}], ok: "A1/1", points: ["A1", "250/1", "A1/1", "low", "A1/1"], report: {balance: 10, discount: "A1/1", meta: {net: 1}}, scores: {eligible: "A1/1"}}, capped: {a: 1, s: 3}}], + [{account: {balance: -500, active: true, insured: false, country: "abc", lines: [], report: {balance: -0.01}}}, {account: {active: true, balance: -500, country: "abc", insured: false, lines: [], ok: "abc/0/true", points: ["abc", "abc/0", "low"], report: {balance: -0.01, discount: "abc/0", meta: {net: 0}}, scores: {eligible: "abc/0"}}, capped: {a: 0, s: 0}}], + [{account: {balance: 100, active: true, insured: false, country: " pad ", lines: [{income: 100, amount: 10, code: "DE", payments: [{rate: 99999999999999999999, tier: "gold"}, {rate: 100, tier: "gold"}]}], report: {balance: 0.1}}}, {account: {active: true, balance: 100, country: " pad ", insured: false, lines: [{amount: 10, calc: {quota: " PAD "}, code: "DE", exposure: 0, income: 100, payments: [{rate: 99999999999999999999, tier: "gold"}, {rate: 100, tier: "gold"}], weighted: 100}], ok: " pad /0/true", points: [" pad ", " pad /0", "low"], report: {balance: 0.1, discount: " pad /0", meta: {net: 1}}, scores: {eligible: " pad /0"}}, capped: {a: 0, s: 1}}], + [{account: {balance: 7.25, active: true, insured: false, country: "日本", lines: [{income: 250, amount: 0.1, code: "12", payments: [{rate: 5, tier: "silver"}]}, {income: 18, amount: 3, code: "US", payments: []}, {income: 2.50, amount: 100, code: "x", payments: [{rate: 250, tier: "bronze"}, {rate: 1000, tier: "silver"}]}, {income: 99.99, amount: 18, code: "DE", payments: null}], report: {balance: 1}, extraField: {nested: true}}}, {account: {active: true, balance: 7.25, country: "日本", extraField: {nested: true}, insured: false, lines: [{amount: 0.1, calc: {quota: "日本"}, code: "12", exposure: 0, income: 250, payments: [{rate: 5, tier: "silver"}], weighted: 250}, {amount: 3, calc: {quota: "日本"}, code: "US", exposure: 0, income: 18, payments: [], weighted: 18}, {amount: 100, calc: {quota: "日本"}, code: "x", exposure: 0, income: 2.50, payments: [{rate: 250, tier: "bronze"}, {rate: 1000, tier: "silver"}], weighted: 2.50}, {amount: 18, calc: {quota: "日本"}, code: "DE", exposure: 0, income: 99.99, payments: null, weighted: 99.99}], ok: "日本/0", points: ["日本", "日本/0", "low"], report: {balance: 1, discount: "日本/0", meta: {net: 3}}, scores: {eligible: "日本/0"}}, capped: {a: 0, s: 4}}], + [{account: {balance: -0, active: true, insured: true, country: "x-y", lines: [], report: {balance: 1}, extraField: "x"}}, {account: {active: true, balance: 0, country: "x-y", extraField: "x", insured: true, lines: [], ok: "x-y/0/true", points: ["x-y", "250/0", "x-y/0", "low", "x-y/0"], report: {balance: 1, discount: "x-y/0", meta: {net: 0}}, scores: {eligible: "x-y/0"}}, capped: {a: 0, s: 0}}], + [{account: {balance: 3, active: true, insured: false, country: "Oslo", lines: [], report: {balance: 0.25}}}, {account: {active: true, balance: 3, country: "Oslo", insured: false, lines: [], ok: "Oslo/0/true", points: ["Oslo", "Oslo/0", "low"], report: {balance: 0.25, discount: "Oslo/0", meta: {net: 0}}, scores: {eligible: "Oslo/0"}}, capped: {a: 0, s: 0}}], + [{account: {balance: 100, active: false, insured: true, country: "high", lines: [{income: 3, amount: 100, code: "retail", payments: [{rate: 0, tier: "gold"}, {rate: 3, tier: "gold"}]}, {income: 1, amount: 1e3, code: "", payments: []}, {amount: 3, code: "Zed", payments: []}, {income: 1000000, amount: 1000, code: "a", payments: [{rate: -500, tier: "gold"}, {rate: 1, tier: "silver"}]}, {amount: 1.5, code: "O'Neil", payments: [{rate: 250, tier: "gold"}, {rate: 1.5, tier: "gold"}]}, {income: 0, amount: 100, code: "O'Neil", payments: [{rate: 0.1, tier: "gold"}, {rate: 18, tier: "gold"}]}, {amount: 3, code: "VIP", payments: [{rate: 7.25, tier: "gold"}, {rate: 250, tier: "bronze"}, {rate: 18, tier: "gold"}]}, {amount: 2, code: "NL", payments: [{rate: 250, tier: "gold"}]}, {income: -0, amount: 99, code: "", payments: [{rate: 0, tier: "gold"}, {rate: 1000, tier: "silver"}]}, {income: 99999999999999999999, amount: 2.50, code: "x-y", payments: [{rate: 3, tier: "silver"}, {rate: 383, tier: "silver"}]}, {amount: 2, code: "retail", payments: [{rate: 100, tier: "bronze"}]}], report: {balance: 465}}}, {account: {active: false, balance: 100, country: "high", insured: true, lines: [{amount: 100, calc: {quota: "HIGH"}, code: "retail", exposure: 0, income: 3, payments: [{rate: 0, tier: "gold"}, {rate: 3, tier: "gold"}], weighted: 3}, {amount: 1000, calc: {quota: "HIGH"}, code: "", exposure: 0, income: 1, payments: [], weighted: 1}, {amount: 3, calc: {quota: "HIGH"}, code: "Zed", exposure: 0, payments: [], weighted: null}, {amount: 1000, calc: {quota: "HIGH"}, code: "a", exposure: 0, income: 1000000, payments: [{rate: -500, tier: "gold"}, {rate: 1, tier: "silver"}], weighted: 1000000}, {amount: 1.5, calc: {quota: "HIGH"}, code: "O'Neil", exposure: 0, payments: [{rate: 250, tier: "gold"}, {rate: 1.5, tier: "gold"}], weighted: null}, {amount: 100, calc: {quota: "HIGH"}, code: "O'Neil", exposure: 0, income: 0, payments: [{rate: 0.1, tier: "gold"}, {rate: 18, tier: "gold"}], weighted: 0}, {amount: 3, calc: {quota: "HIGH"}, code: "VIP", exposure: 0, payments: [{rate: 7.25, tier: "gold"}, {rate: 250, tier: "bronze"}, {rate: 18, tier: "gold"}], weighted: null}, {amount: 2, calc: {quota: "HIGH"}, code: "NL", exposure: 0, payments: [{rate: 250, tier: "gold"}], weighted: null}, {amount: 99, calc: {quota: "HIGH"}, code: "", exposure: 0, income: 0, payments: [{rate: 0, tier: "gold"}, {rate: 1000, tier: "silver"}], weighted: 0}, {amount: 2.50, calc: {quota: "HIGH"}, code: "x-y", exposure: 0, income: 99999999999999999999, payments: [{rate: 3, tier: "silver"}, {rate: 383, tier: "silver"}], weighted: 99999999999999999999}, {amount: 2, calc: {quota: "HIGH"}, code: "retail", exposure: 0, payments: [{rate: 100, tier: "bronze"}], weighted: null}], ok: "high/4", points: ["high", "250/2", "high/4", "low", "high/4"], report: {balance: 465, discount: "high/4", meta: {net: 2}}, scores: {eligible: "high/4"}}, capped: {a: 4, s: 11}}], + [{account: {balance: -500, active: true, insured: false, country: "3.5", lines: [{income: 65, amount: 1000000, code: "retail"}, {amount: -0.01, code: "VIP", payments: [{rate: 100, tier: "bronze"}, {rate: 1000, tier: "silver"}]}, {amount: 250, code: "US", payments: [{rate: 1000, tier: "silver"}, {rate: 0.5, tier: "silver"}, {rate: 1000, tier: "silver"}]}, {amount: 1000, code: "retail", payments: [{rate: 1000, tier: "silver"}, {rate: 3, tier: "gold"}]}], report: {balance: 2.50}}}, {account: {active: true, balance: -500, country: "3.5", insured: false, lines: [{amount: 1000000, calc: {quota: "3.5"}, code: "retail", exposure: 0, income: 65, weighted: 65}, {amount: -0.01, calc: {quota: "3.5"}, code: "VIP", exposure: 2, payments: [{rate: 100, tier: "bronze"}, {rate: 1000, tier: "silver"}], weighted: null}, {amount: 250, calc: {quota: "3.5"}, code: "US", exposure: 3, payments: [{rate: 1000, tier: "silver"}, {rate: 0.5, tier: "silver"}, {rate: 1000, tier: "silver"}], weighted: null}, {amount: 1000, calc: {quota: "3.5"}, code: "retail", exposure: 2, payments: [{rate: 1000, tier: "silver"}, {rate: 3, tier: "gold"}], weighted: null}], ok: "3.5/2", points: ["3.5", "3.5/2", "low"], report: {balance: 2.50, discount: "3.5/2", meta: {net: 1}}, scores: {eligible: "3.5/2"}}, capped: {a: 2, s: 4}}], + [{account: {balance: 1000, active: false, insured: false, country: "a-b-c", lines: [{income: null, amount: 1.5, code: " pad ", payments: [{rate: 100, tier: "gold"}, {rate: 1, tier: "gold"}]}, {amount: 0.25, code: "a-b-c", payments: [{rate: 447, tier: "silver"}, {rate: 0, tier: "bronze"}]}, {income: 3, amount: 0.5, code: "Oslo", payments: [{rate: 99.99, tier: "silver"}, {rate: 100, tier: "silver"}]}, {income: 1000, amount: 10, code: "US", payments: [{rate: 100, tier: "silver"}, {rate: -0.01, tier: "gold"}]}, {income: null, amount: 317, code: "abc", payments: []}], report: {balance: 0.25}}}, {account: {active: false, balance: 1000, country: "a-b-c", insured: false, lines: [{amount: 1.5, calc: {quota: "A-B-C"}, code: " pad ", exposure: 0, income: null, payments: [{rate: 100, tier: "gold"}, {rate: 1, tier: "gold"}], weighted: null}, {amount: 0.25, calc: {quota: "A-B-C"}, code: "a-b-c", exposure: 0, payments: [{rate: 447, tier: "silver"}, {rate: 0, tier: "bronze"}], weighted: null}, {amount: 0.5, calc: {quota: "A-B-C"}, code: "Oslo", exposure: 0, income: 3, payments: [{rate: 99.99, tier: "silver"}, {rate: 100, tier: "silver"}], weighted: 3}, {amount: 10, calc: {quota: "A-B-C"}, code: "US", exposure: 0, income: 1000, payments: [{rate: 100, tier: "silver"}, {rate: -0.01, tier: "gold"}], weighted: 1000}, {amount: 317, calc: {quota: "A-B-C"}, code: "abc", exposure: 0, income: null, payments: [], weighted: null}], ok: "a-b-c/0", points: ["a-b-c", "a-b-c/0", "low"], report: {balance: 0.25, discount: "a-b-c/0", meta: {net: 2}}, scores: {eligible: "a-b-c/0"}}, capped: {a: 0, s: 5}}], + [{account: {balance: -1, active: true, insured: false, country: "NL", lines: [{income: 0.000001, amount: 65, code: "US", payments: [{rate: 1000000, tier: "silver"}, {rate: 0, tier: "bronze"}]}], report: {balance: 1}}}, {account: {active: true, balance: -1, country: "NL", insured: false, lines: [{amount: 65, calc: {quota: "NL"}, code: "US", exposure: 0, income: 0.000001, payments: [{rate: 1000000, tier: "silver"}, {rate: 0, tier: "bronze"}], weighted: 0.000001}], ok: "NL/0/true", points: ["NL", "NL/0", "low"], report: {balance: 1, discount: "NL/0", meta: {net: 0}}, scores: {eligible: "NL/0"}}, capped: {a: 0, s: 1}}], + [{account: {balance: 2.50, active: false, insured: false, country: " pad ", lines: [{income: 2, amount: 123456789.123, code: "US", payments: [{rate: 3, tier: "silver"}, {rate: 99.99, tier: "gold"}]}, {income: 1000000, amount: 1000000, code: "", payments: null}], report: {balance: 1000}, extraField: 1}}, {account: {active: false, balance: 2.50, country: " pad ", extraField: 1, insured: false, lines: [{amount: 123456789.123, calc: {quota: " PAD "}, code: "US", exposure: 0, income: 2, payments: [{rate: 3, tier: "silver"}, {rate: 99.99, tier: "gold"}], weighted: 2}, {amount: 1000000, calc: {quota: " PAD "}, code: "", exposure: 0, income: 1000000, payments: null, weighted: 1000000}], ok: " pad /1", points: [" pad ", " pad /1", "low"], report: {balance: 1000, discount: " pad /1", meta: {net: 0}}, scores: {eligible: " pad /1"}}, capped: {a: 1, s: 2}}], + [{account: {balance: -1, active: false, insured: true, country: "é ü", lines: [{income: 2, amount: -0.01, code: "retail", payments: [{rate: 250, tier: "gold"}, {rate: -500, tier: "silver"}]}, {income: 2, amount: 65, code: "high", payments: [{rate: 2, tier: "bronze"}, {rate: 2, tier: "gold"}]}], report: {balance: 0.000001}, extraField: {nested: true}}}, {account: {active: false, balance: -1, country: "é ü", extraField: {nested: true}, insured: true, lines: [{amount: -0.01, calc: {quota: "É Ü"}, code: "retail", exposure: 0, income: 2, payments: [{rate: 250, tier: "gold"}, {rate: -500, tier: "silver"}], weighted: 2}, {amount: 65, calc: {quota: "É Ü"}, code: "high", exposure: 0, income: 2, payments: [{rate: 2, tier: "bronze"}, {rate: 2, tier: "gold"}], weighted: 2}], ok: "é ü/2", points: ["é ü", "250/1", "é ü/2", "low", "é ü/2"], report: {balance: 0.000001, discount: "é ü/2", meta: {net: 1}}, scores: {eligible: "é ü/2"}}, capped: {a: 2, s: 2}}], + [{account: {balance: 18, active: true, insured: false, country: "a", lines: [], report: {balance: -1}}}, {account: {active: true, balance: 18, country: "a", insured: false, lines: [], ok: "Oslo/true", points: ["a", "Oslo", "low"], report: {balance: -1, discount: "Oslo", meta: {net: 0}}, scores: {eligible: "Oslo"}}, capped: {a: 0, s: 0}}], + [{account: {balance: -0.5, active: false, insured: true, country: "-", lines: [{amount: -0.5, code: "DE"}, {amount: 1.5, code: "VIP", payments: [{rate: 2.50, tier: "silver"}]}, {income: 50, amount: 0.5, code: "Oslo", payments: [{rate: 1000000, tier: "gold"}, {rate: 100, tier: "gold"}, {rate: 65, tier: "silver"}]}, {amount: 100, code: "gold", payments: [{rate: 3, tier: "gold"}, {rate: 0.5, tier: "bronze"}, {rate: 0.1, tier: "gold"}]}, {income: 50, amount: 1000, code: "retail", payments: []}, {amount: 0.1, code: "retail", payments: [{rate: 2, tier: "gold"}, {rate: 1.5, tier: "bronze"}]}, {amount: 3, code: "x-y", payments: [{rate: 0.5, tier: "silver"}, {rate: 99999999999999999999, tier: "silver"}]}, {income: 0.5, amount: 99999999999999999999, code: "A1", payments: [{rate: 1000, tier: "gold"}, {rate: 1.5, tier: "silver"}]}, {income: 5, amount: 1000000, code: "retail", payments: [{rate: 1000, tier: "silver"}, {rate: 0.5, tier: "gold"}]}, {income: 2, amount: 0.5, code: "US", payments: [{rate: 0, tier: "gold"}, {rate: 5, tier: "silver"}]}], report: {balance: -0.01}}}, {account: {active: false, balance: -0.5, country: "-", insured: true, lines: [{amount: -0.5, calc: {quota: "-"}, code: "DE", exposure: 0, weighted: null}, {amount: 1.5, calc: {quota: "-"}, code: "VIP", exposure: 0, payments: [{rate: 2.50, tier: "silver"}], weighted: null}, {amount: 0.5, calc: {quota: "-"}, code: "Oslo", exposure: 0, income: 50, payments: [{rate: 1000000, tier: "gold"}, {rate: 100, tier: "gold"}, {rate: 65, tier: "silver"}], weighted: 50}, {amount: 100, calc: {quota: "-"}, code: "gold", exposure: 0, payments: [{rate: 3, tier: "gold"}, {rate: 0.5, tier: "bronze"}, {rate: 0.1, tier: "gold"}], weighted: null}, {amount: 1000, calc: {quota: "-"}, code: "retail", exposure: 0, income: 50, payments: [], weighted: 50}, {amount: 0.1, calc: {quota: "-"}, code: "retail", exposure: 0, payments: [{rate: 2, tier: "gold"}, {rate: 1.5, tier: "bronze"}], weighted: null}, {amount: 3, calc: {quota: "-"}, code: "x-y", exposure: 0, payments: [{rate: 0.5, tier: "silver"}, {rate: 99999999999999999999, tier: "silver"}], weighted: null}, {amount: 99999999999999999999, calc: {quota: "-"}, code: "A1", exposure: 0, income: 0.5, payments: [{rate: 1000, tier: "gold"}, {rate: 1.5, tier: "silver"}], weighted: 0.5}, {amount: 1000000, calc: {quota: "-"}, code: "retail", exposure: 0, income: 5, payments: [{rate: 1000, tier: "silver"}, {rate: 0.5, tier: "gold"}], weighted: 5}, {amount: 0.5, calc: {quota: "-"}, code: "US", exposure: 0, income: 2, payments: [{rate: 0, tier: "gold"}, {rate: 5, tier: "silver"}], weighted: 2}], ok: "Oslo", points: ["-", "250/3", "Oslo", "low", "Oslo"], report: {balance: -0.01, discount: "Oslo", meta: {net: 3}}, scores: {eligible: "Oslo"}}, capped: {a: 3, s: 10}}], + [{account: {balance: 100, active: true, insured: true, country: "-", lines: [], report: {balance: 1000}}}, {account: {active: true, balance: 100, country: "-", insured: true, lines: [], ok: "Oslo", points: ["-", "250/0", "Oslo", "low", "Oslo"], report: {balance: 1000, discount: "Oslo", meta: {net: 0}}, scores: {eligible: "Oslo"}}, capped: {a: 0, s: 0}}], + [{account: {balance: 18, active: true, insured: false, country: "gold", lines: [], report: {balance: -0.01}}}, {account: {active: true, balance: 18, country: "gold", insured: false, lines: [], ok: "gold/0/true", points: ["gold", "gold/0", "low"], report: {balance: -0.01, discount: "gold/0", meta: {net: 0}}, scores: {eligible: "gold/0"}}, capped: {a: 0, s: 0}}], + [{account: {balance: -0.01, active: false, insured: false, country: "high", lines: [{income: -0, amount: 3, code: "Oslo", payments: [{rate: 3, tier: "gold"}, {rate: 1000, tier: "gold"}]}], report: {balance: 99.99}}}, {account: {active: false, balance: -0.01, country: "high", insured: false, lines: [{amount: 3, calc: {quota: "HIGH"}, code: "Oslo", exposure: 0, income: 0, payments: [{rate: 3, tier: "gold"}, {rate: 1000, tier: "gold"}], weighted: 0}], ok: "high/0", points: ["high", "high/0", "low"], report: {balance: 99.99, discount: "high/0", meta: {net: 0}}, scores: {eligible: "high/0"}}, capped: {a: 0, s: 1}}], + [{account: {balance: -0.01, active: false, insured: false, country: "low", lines: [{income: 5, amount: 1, code: "low", payments: []}, {amount: -0.01, code: "A1", payments: []}, {income: 2, amount: 3, code: "", payments: []}, {amount: 0.5, code: "low", payments: [{rate: 50, tier: "bronze"}, {rate: -500, tier: "gold"}]}, {income: null, amount: -0.01, code: "US", payments: null}], report: {balance: 1000000}}}, {account: {active: false, balance: -0.01, country: "low", insured: false, lines: [{amount: 1, calc: {quota: "LOW"}, code: "low", exposure: 0, income: 5, payments: [], weighted: 5}, {amount: -0.01, calc: {quota: "LOW"}, code: "A1", exposure: 0, payments: [], weighted: null}, {amount: 3, calc: {quota: "LOW"}, code: "", exposure: 0, income: 2, payments: [], weighted: 2}, {amount: 0.5, calc: {quota: "LOW"}, code: "low", exposure: 0, payments: [{rate: 50, tier: "bronze"}, {rate: -500, tier: "gold"}], weighted: null}, {amount: -0.01, calc: {quota: "LOW"}, code: "US", exposure: 0, income: null, payments: null, weighted: null}], ok: "low/1", points: ["low", "low/1", "low"], report: {balance: 1000000, discount: "low/1", meta: {net: 3}}, scores: {eligible: "low/1"}}, capped: {a: 1, s: 5}}], + [{account: {balance: 2, active: false, insured: true, country: "Zed", lines: [{income: 3, amount: 3, code: "low", payments: []}, {income: 0.5, amount: 1000000, code: "retail", payments: [{rate: 0.5, tier: "gold"}, {rate: 3, tier: "gold"}, {rate: 0.25, tier: "gold"}]}, {income: -0.5, amount: -0.5, code: "retail", payments: []}, {income: 486, amount: 2, code: "x", payments: []}, {income: 0, amount: 0.1, code: "", payments: [{rate: 0.1, tier: "silver"}, {rate: -1, tier: "bronze"}]}], report: {balance: 1000}}}, {account: {active: false, balance: 2, country: "Zed", insured: true, lines: [{amount: 3, calc: {quota: "ZED"}, code: "low", exposure: 0, income: 3, payments: [], weighted: 3}, {amount: 1000000, calc: {quota: "ZED"}, code: "retail", exposure: 0, income: 0.5, payments: [{rate: 0.5, tier: "gold"}, {rate: 3, tier: "gold"}, {rate: 0.25, tier: "gold"}], weighted: 0.5}, {amount: -0.5, calc: {quota: "ZED"}, code: "retail", exposure: 0, income: -0.5, payments: [], weighted: -0.5}, {amount: 2, calc: {quota: "ZED"}, code: "x", exposure: 0, income: 486, payments: [], weighted: 486}, {amount: 0.1, calc: {quota: "ZED"}, code: "", exposure: 0, income: 0, payments: [{rate: 0.1, tier: "silver"}, {rate: -1, tier: "bronze"}], weighted: 0}], ok: "Zed/3", points: ["Zed", "250/1", "Zed/3", "low", "Zed/3"], report: {balance: 1000, discount: "Zed/3", meta: {net: 1}}, scores: {eligible: "Zed/3"}}, capped: {a: 3, s: 5}}], + [{account: {balance: 0.5, active: true, insured: false, country: "Oslo", lines: [{income: 3, amount: 250, payments: [{rate: 1, tier: "bronze"}, {rate: 2, tier: "bronze"}]}], report: {balance: 1}}}, {account: {active: true, balance: 0.5, country: "Oslo", insured: false, lines: [{amount: 250, calc: {quota: "OSLO"}, exposure: 0, income: 3, payments: [{rate: 1, tier: "bronze"}, {rate: 2, tier: "bronze"}], weighted: 3}], ok: "Oslo/0/true", points: ["Oslo", "Oslo/0", "low"], report: {balance: 1, discount: "Oslo/0", meta: {net: 0}}, scores: {eligible: "Oslo/0"}}, capped: {a: 0, s: 1}}], + [{account: {balance: 1000, active: true, insured: true, country: "Oslo", lines: [{income: null, amount: -0, code: "é ü", payments: [{rate: 1000000, tier: "gold"}]}, {income: 0, amount: 250, code: " pad "}, {income: 1e3, amount: 1, code: " pad ", payments: [{rate: 426, tier: "gold"}, {rate: 2, tier: "silver"}]}, {amount: 1000000, code: "日本", payments: [{rate: 100, tier: "bronze"}, {rate: 474, tier: "gold"}]}], report: {balance: 1}}}, {account: {active: true, balance: 1000, country: "Oslo", insured: true, lines: [{amount: 0, calc: {quota: "OSLO"}, code: "é ü", exposure: 0, income: null, payments: [{rate: 1000000, tier: "gold"}], weighted: null}, {amount: 250, calc: {quota: "OSLO"}, code: " pad ", exposure: 0, income: 0, weighted: 0}, {amount: 1, calc: {quota: "OSLO"}, code: " pad ", exposure: 0, income: 1000, payments: [{rate: 426, tier: "gold"}, {rate: 2, tier: "silver"}], weighted: 1000}, {amount: 1000000, calc: {quota: "OSLO"}, code: "日本", exposure: 0, payments: [{rate: 100, tier: "bronze"}, {rate: 474, tier: "gold"}], weighted: null}], ok: "Oslo/0", points: ["Oslo", "250/1", "Oslo/0", "low", "Oslo/0"], report: {balance: 1, discount: "Oslo/0", meta: {net: 1}}, scores: {eligible: "Oslo/0"}}, capped: {a: 0, s: 4}}], + [{account: {balance: 65, active: true, insured: false, country: "retail", lines: [{amount: 2, code: "VIP", payments: [{rate: 1000, tier: "silver"}]}, {income: 65, amount: 100, code: "low", payments: [{rate: 2, tier: "gold"}, {rate: 0.5, tier: "gold"}]}], report: {balance: 100}}}, {account: {active: true, balance: 65, country: "retail", insured: false, lines: [{amount: 2, calc: {quota: "RETAIL"}, code: "VIP", exposure: 0, payments: [{rate: 1000, tier: "silver"}], weighted: null}, {amount: 100, calc: {quota: "RETAIL"}, code: "low", exposure: 0, income: 65, payments: [{rate: 2, tier: "gold"}, {rate: 0.5, tier: "gold"}], weighted: 65}], ok: "retail/0", points: ["retail", "retail/0", "low"], report: {balance: 100, discount: "retail/0", meta: {net: 0}}, scores: {eligible: "retail/0"}}, capped: {a: 0, s: 2}}], + [{account: {balance: 100, active: false, insured: true, country: "VIP", lines: [{amount: 1e3, code: "retail", payments: null}, {income: null, amount: 0, code: "retail", payments: [{rate: 99.99, tier: "gold"}]}, {income: -0.5, amount: -500, code: "abc", payments: null}, {income: 2, amount: 2, code: "VIP", payments: []}, {income: 250, amount: -0.01, code: "retail", payments: [{rate: -0.01, tier: "silver"}]}], report: {balance: -0}}}, {account: {active: false, balance: 100, country: "VIP", insured: true, lines: [{amount: 1000, calc: {quota: "VIP"}, code: "retail", exposure: 0, payments: null, weighted: null}, {amount: 0, calc: {quota: "VIP"}, code: "retail", exposure: 0, income: null, payments: [{rate: 99.99, tier: "gold"}], weighted: null}, {amount: -500, calc: {quota: "VIP"}, code: "abc", exposure: 0, income: -0.5, payments: null, weighted: -0.5}, {amount: 2, calc: {quota: "VIP"}, code: "VIP", exposure: 0, income: 2, payments: [], weighted: 2}, {amount: -0.01, calc: {quota: "VIP"}, code: "retail", exposure: 0, income: 250, payments: [{rate: -0.01, tier: "silver"}], weighted: 250}], ok: "VIP/3", points: ["VIP", "250/2", "VIP/3", "low", "VIP/3"], report: {balance: 0, discount: "VIP/3", meta: {net: 2}}, scores: {eligible: "VIP/3"}}, capped: {a: 3, s: 5}}], + ], +} + +// seed 343200 (attempt 0) +{ + name: "b 33: tenant/loans: 1 assertion, 2 expression, 2 match, 2 table; 3 root, 4 per-member, 2 top-level computed", + policy: { + models: {tenant: {limit: "number?", priority: "boolean", birthDate: "date?", active: "boolean", loans: "loan[]"}, loan: {score: "number", price: "number?", channel: "string", code: "string"}}, + blocks: [ + {assertion: "loan.scores.discount", conditions: [["and", "(tenant.active and tenant.active)", 2], ["or", "(tenant.birthDate ?? d('2025-01-01')) >= d('2025-01-01')", 1]]}, + {expression: "tenant.ok", value: "((tenant.limit ?? 0) * (tenant.limit ?? 0))"}, + {match: "tenant.flag", arms: [["(tenant.priority and tenant.active)", "'ok'"], ["none(tenant.loans, #.score < #.score)", "upper(string(tenant.active))"], ["(all(tenant.loans, (#.scores.discount or #.scores.discount)) or (tenant.birthDate ?? d('2025-01-01')).isAfter(d('2025-03-20'), 'month'))", "(tenant.birthDate ?? d('2025-01-01')).format('%d')"], ["10 == tenant.ok", "'none'"], ["", "'US'"]]}, + {table: "t4", inputs: ["tenant.active", "tenant.limit"], outputs: ["risk", "health"], rules: [ + ["true", "0.5", "tenant.active", ""], + ["true", "", "(tenant.limit ?? 0) in [41..100)", "tenant.ok"], + ["false", "2", "tenant.priority", "(tenant.ok) / (abs(tenant.ok) + 1)"], + ["", "50, 10", "tenant.priority", "(tenant.limit ?? 0)"], + ["false", "0", "tenant.active", "round((tenant.limit ?? 0))"], + ["false", "0.25", "tenant.priority", "10"], + ["true", "5", "tenant.ok >= 0.5", "tenant.ok"], + ]}, + {match: "tenant.totals.bucket", arms: [["some(tenant.loans, (#.scores.discount or #.scores.discount))", "string((health ?? 0))"], ["", "tenant.flag"]]}, + {expression: "loan.tag", value: "not (tenant.priority)"}, + {table: "t7", hit: "collect", inputs: ["loan.tag"], outputs: ["loan.summary", "loan.eligible"], rules: [ + ["false", "tenant.active", "tenant.priority"], + ["false", "tenant.active", "tenant.priority"], + ["true", "loan.tag", ""], + ["", "isNumeric(tenant.flag)", "tenant.active"], + ["true", "tenant.priority", "loan.scores.discount"], + ["false", "(risk ?? false)", "(tenant.birthDate ?? d('2025-01-01')) < d('2000-06-30')"], + ]}, + ], + }, + cases: [ + [{tenant: {limit: 99.99, priority: false, birthDate: "1990-06-15", active: false, loans: [{score: 65, price: 2, code: "é ü"}, {score: -0, price: 10, channel: "12", code: "abc"}]}}, {tenant: {active: false, birthDate: "1990-06-15", flag: "FALSE", limit: 99.99, loans: [{code: "é ü", eligible: [false, false], price: 2, score: 65, scores: {discount: false}, summary: [true, false, false], tag: true}, {channel: "12", code: "abc", eligible: [false, false], price: 10, score: 0, scores: {discount: false}, summary: [true, false, false], tag: true}], ok: 9998.0001, priority: false, totals: {bucket: "FALSE"}}}], + [{tenant: {limit: 1000, priority: true, birthDate: "2024-02-29", active: true, loans: [{score: 1, price: 0.5, channel: "日本", code: "12"}], extraField: "x"}}, {health: 1000000, risk: false, tenant: {active: true, birthDate: "2024-02-29", extraField: "x", flag: "ok", limit: 1000, loans: [{channel: "日本", code: "12", eligible: [true, true, true, false], price: 0.5, score: 1, scores: {discount: false}, summary: [true, true, false, false], tag: false}], ok: 1000000, priority: true, totals: {bucket: "ok"}}}], + [{tenant: {limit: [1], priority: false, birthDate: "2025-03-20", active: true, loans: []}}, "!error: InputValidationFailed"], + [{tenant: {limit: 0.000001, priority: true, birthDate: "2024-01-01", active: true, loans: [{score: 0.25, price: 0.000001, channel: "O'Neil", code: "a"}, {score: 250, price: -0.5, channel: "ok", code: "a-b-c"}, {score: -0.5, price: 10, channel: "", code: "a-b-c"}]}}, {health: 0.000000000001, risk: false, tenant: {active: true, birthDate: "2024-01-01", flag: "ok", limit: 0.000001, loans: [{channel: "O'Neil", code: "a", eligible: [true, true, true, false], price: 0.000001, score: 0.25, scores: {discount: false}, summary: [true, true, false, false], tag: false}, {channel: "ok", code: "a-b-c", eligible: [true, true, true, false], price: -0.5, score: 250, scores: {discount: false}, summary: [true, true, false, false], tag: false}, {channel: "", code: "a-b-c", eligible: [true, true, true, false], price: 10, score: -0.5, scores: {discount: false}, summary: [true, true, false, false], tag: false}], ok: 0.000000000001, priority: true, totals: {bucket: "ok"}}}], + [{tenant: {limit: 0, priority: true, active: false, loans: [{score: 0.25, channel: "é ü", code: "日本"}]}}, {health: 0, risk: false, tenant: {active: false, flag: "FALSE", limit: 0, loans: [{channel: "é ü", code: "日本", eligible: [true, true, false, false], score: 0.25, scores: {discount: false}, summary: [false, false, false, false], tag: false}], ok: 0, priority: true, totals: {bucket: "FALSE"}}}], + [{tenant: {limit: 0.000001, priority: true, birthDate: "2024-01-01", active: true, loans: [{score: 100, price: 10, channel: "-", code: "ok"}, {score: 7.25, price: 18, channel: "gold", code: "Oslo"}]}}, {health: 0.000000000001, risk: false, tenant: {active: true, birthDate: "2024-01-01", flag: "ok", limit: 0.000001, loans: [{channel: "-", code: "ok", eligible: [true, true, true, false], price: 10, score: 100, scores: {discount: false}, summary: [true, true, false, false], tag: false}, {channel: "gold", code: "Oslo", eligible: [true, true, true, false], price: 18, score: 7.25, scores: {discount: false}, summary: [true, true, false, false], tag: false}], ok: 0.000000000001, priority: true, totals: {bucket: "ok"}}}], + [{tenant: {limit: 250, priority: false, birthDate: "2030-12-31", active: false, loans: []}}, {tenant: {active: false, birthDate: "2030-12-31", flag: "FALSE", limit: 250, loans: [], ok: 62500, priority: false, totals: {bucket: "FALSE"}}}], + [{tenant: {limit: 0.25, priority: true, birthDate: "2030-12-31", active: true, loans: [{score: -1, price: 18, channel: "NL", code: "US"}, {score: 1000, price: 99999999999999999999, channel: "Oslo", code: "x-y"}]}}, {health: 0.0625, risk: false, tenant: {active: true, birthDate: "2030-12-31", flag: "ok", limit: 0.25, loans: [{channel: "NL", code: "US", eligible: [true, true, true, false], price: 18, score: -1, scores: {discount: true}, summary: [true, true, false, false], tag: false}, {channel: "Oslo", code: "x-y", eligible: [true, true, true, false], price: 99999999999999999999, score: 1000, scores: {discount: true}, summary: [true, true, false, false], tag: false}], ok: 0.0625, priority: true, totals: {bucket: "0.0625"}}}], + [{tenant: {limit: 10, priority: true, birthDate: "2025-03-20", active: false, loans: []}}, {tenant: {active: false, birthDate: "2025-03-20", flag: "FALSE", limit: 10, loans: [], ok: 100, priority: true, totals: {bucket: "FALSE"}}}], + [{tenant: {limit: 123456789.123, priority: true, birthDate: null, active: false, loans: []}}, {tenant: {active: false, birthDate: null, flag: "FALSE", limit: 123456789.123, loans: [], ok: 15241578780560891.109129, priority: true, totals: {bucket: "FALSE"}}}], + [{tenant: {limit: 65, priority: false, birthDate: "2025-03-20", active: true, loans: [{score: 2, price: 10, channel: "none", code: "é ü"}, {score: 1000, price: 5, channel: "A1", code: " pad "}, {score: 2, price: 10, channel: "", code: "ok"}, {score: 99.99, price: 1000, channel: "gold", code: "none"}]}}, {health: 4225, risk: true, tenant: {active: true, birthDate: "2025-03-20", flag: "TRUE", limit: 65, loans: [{channel: "none", code: "é ü", eligible: [true, true], price: 10, score: 2, scores: {discount: true}, summary: [true, false, false], tag: true}, {channel: "A1", code: " pad ", eligible: [true, true], price: 5, score: 1000, scores: {discount: true}, summary: [true, false, false], tag: true}, {channel: "", code: "ok", eligible: [true, true], price: 10, score: 2, scores: {discount: true}, summary: [true, false, false], tag: true}, {channel: "gold", code: "none", eligible: [true, true], price: 1000, score: 99.99, scores: {discount: true}, summary: [true, false, false], tag: true}], ok: 4225, priority: false, totals: {bucket: "4225"}}}], + [{tenant: {priority: false, birthDate: null, active: false, loans: [{score: 0.5, price: 18, channel: " pad ", code: "x-y"}, {score: 1000, channel: "Zed", code: "A1"}]}}, {tenant: {active: false, birthDate: null, flag: "FALSE", loans: [{channel: " pad ", code: "x-y", eligible: [false, false], price: 18, score: 0.5, scores: {discount: false}, summary: [true, false, false], tag: true}, {channel: "Zed", code: "A1", eligible: [false, false], score: 1000, scores: {discount: false}, summary: [true, false, false], tag: true}], ok: 0, priority: false, totals: {bucket: "FALSE"}}}], + [{tenant: {limit: null, priority: true, birthDate: null, active: false, loans: [{score: 50, price: 2, channel: "none", code: ""}, {score: 0.25, price: 1, channel: "日本", code: "NL"}]}}, {health: null, risk: null, tenant: {active: false, birthDate: null, flag: "FALSE", limit: null, loans: [{channel: "none", code: "", eligible: [true, true, false, false], price: 2, score: 50, scores: {discount: false}, summary: [false, false, false, false], tag: false}, {channel: "日本", code: "NL", eligible: [true, true, false, false], price: 1, score: 0.25, scores: {discount: false}, summary: [false, false, false, false], tag: false}], ok: 0, priority: true, totals: {bucket: "FALSE"}}}], + ], +} + +// seed 343300 (attempt 0) +{ + name: "b 34: tenant/parcels/employees: 1 assertion, 6 expression, 3 match; 2 root, 7 per-member, 3 top-level computed", + policy: { + models: {tenant: {price: "number", dueDate: "date", kind: "string(retail|corporate)?", parcels: "parcel[]"}, parcel: {amount: "number", limit: "number?", dueDate: "date?", price: "number", employees: "employee[]"}, employee: {rate: "number", income: "number"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {match: "parcel.fee", arms: [["matches(`${parcel.amount}/${parcel.price}`, 'a')", "((parcel.limit ?? 0) == 10 ? 'a' : 'Oslo')"], ["", "(parcel.dueDate ?? d('2025-01-01')).format('%Y')"]]}, + {assertion: "parcel.penalty", conditions: [["or", "(tenant.kind ?? '') == 'retail'", 0], ["and", "(tenant.kind ?? '') in ['corporate', 'retail']", 1], ["and", "(10 * parcel.price) >= cap", 1], ["and", "parcel.fee != 'gold'", 1]]}, + {expression: "parcel.bucket", value: "parcel.limit"}, + {expression: "surcharge", value: "cap in [9..149]"}, + {expression: "parcel.review", value: "{n: (split(`${surcharge}/${surcharge}`, '-')[0] ?? 'none'), ok: round((0.25 + parcel.amount) / 7, 2)}"}, + {expression: "tenant.bonus", value: "(cap / 3)"}, + {match: "tenant.grade", arms: [["0.5 == cap", "tenant.price"], ["tenant.bonus == 0.5", "0.5"], ["tenant.kind == null", "cap"], ["not ((tenant.kind ?? '') in ['corporate', 'retail'])", "(sum(map(tenant.parcels, #.price)) - cap)"], ["", "tenant.price"]]}, + {expression: "parcel.band", value: "(none(parcel.employees, #.income <= #.rate) ? len(parcel.employees) : len(parcel.fee))"}, + {expression: "flag", value: "number(string(round(number(string(tenant.grade)), 2)))"}, + {match: "share", arms: [["all(tenant.parcels, contains(['DE', 'US', ''], #.fee))", "`${flag}/${none(tenant.parcels, #.amount >= (#.limit ?? 0))}`"], ["", "'ok'"]]}, + ], + }, + cases: [ + [{cap: 10, tenant: {price: 0.5, dueDate: "2030-12-31", kind: "retail", parcels: [{amount: 1e3, limit: 0.1, dueDate: "2030-12-31", price: 99.99, employees: [{rate: 10, income: 451}, {rate: 10, income: -0.5}]}, {amount: 0.5, limit: 2, dueDate: "2024-01-01", price: 65, employees: [{rate: 1000, income: 2}]}, {amount: 18, limit: -0.5, dueDate: "2025-03-20", price: 1000000, employees: [{rate: -0, income: 0.000001}, {rate: 0.5, income: -0}, {rate: 0.5, income: 0.5}]}]}}, {cap: 10, share: "ok", surcharge: true, tenant: {dueDate: "2030-12-31", kind: "retail", parcels: [{amount: 1000, band: 4, bucket: 0.1, dueDate: "2030-12-31", employees: [{income: 451, rate: 10}, {income: -0.5, rate: 10}], fee: "2030", limit: 0.1, penalty: true, price: 99.99, review: {n: "true/true", ok: 142.89}}, {amount: 0.5, band: 4, bucket: 2, dueDate: "2024-01-01", employees: [{income: 2, rate: 1000}], fee: "2024", limit: 2, penalty: true, price: 65, review: {n: "true/true", ok: 0.11}}, {amount: 18, band: 4, bucket: -0.5, dueDate: "2025-03-20", employees: [{income: 0.000001, rate: 0}, {income: 0, rate: 0.5}, {income: 0.5, rate: 0.5}], fee: "2025", limit: -0.5, penalty: true, price: 1000000, review: {n: "true/true", ok: 2.61}}], price: 0.5}}], + [{cap: -2, tenant: {price: -500, dueDate: "2000-01-01", parcels: [{amount: 250, dueDate: "1990-06-15", price: 409, employees: []}, {amount: 2.50, limit: 1000000, dueDate: "2030-12-31", price: 2.50, employees: [{rate: 0.000001, income: 323}]}, {amount: -500, dueDate: null, price: -0.5, employees: [{rate: 250, income: 2}, {rate: 0.5, income: 5}]}, {amount: 5, limit: null, price: 100, employees: [{rate: -500, income: 1000}, {rate: 1000000, income: 10}]}]}}, {cap: -2, share: "ok", surcharge: false, tenant: {dueDate: "2000-01-01", parcels: [{amount: 250, band: 0, bucket: null, dueDate: "1990-06-15", employees: [], fee: "1990", penalty: false, price: 409, review: {n: "false/false", ok: 35.75}}, {amount: 2.50, band: 1, bucket: 1000000, dueDate: "2030-12-31", employees: [{income: 323, rate: 0.000001}], fee: "2030", limit: 1000000, penalty: false, price: 2.50, review: {n: "false/false", ok: 0.39}}, {amount: -500, band: 4, bucket: null, dueDate: null, employees: [{income: 2, rate: 250}, {income: 5, rate: 0.5}], fee: "2025", penalty: false, price: -0.5, review: {n: "false/false", ok: -71.39}}, {amount: 5, band: 4, bucket: null, employees: [{income: 1000, rate: -500}, {income: 10, rate: 1000000}], fee: "2025", limit: null, penalty: false, price: 100, review: {n: "false/false", ok: 0.75}}], price: -500}}], + [{cap: 10, tenant: {price: 0.5, kind: "retail", parcels: [{amount: 1000, limit: 0.5, dueDate: "2000-01-01", price: 1000, employees: [{rate: 10, income: -500}]}, {amount: 0.5, limit: 2, dueDate: "2030-12-31", price: 10, employees: []}]}}, {cap: 10, share: "ok", surcharge: true, tenant: {kind: "retail", parcels: [{amount: 1000, band: 4, bucket: 0.5, dueDate: "2000-01-01", employees: [{income: -500, rate: 10}], fee: "2000", limit: 0.5, penalty: true, price: 1000, review: {n: "true/true", ok: 142.89}}, {amount: 0.5, band: 0, bucket: 2, dueDate: "2030-12-31", employees: [], fee: "2030", limit: 2, penalty: true, price: 10, review: {n: "true/true", ok: 0.11}}], price: 0.5}}], + [{cap: 0.5, tenant: {price: 10, dueDate: "2024-01-01", kind: "retail", parcels: []}}, {cap: 0.5, flag: 10, share: "10/true", surcharge: false, tenant: {bonus: 0.1666666666666666666666666667, dueDate: "2024-01-01", grade: 10, kind: "retail", parcels: [], price: 10}}], + [{cap: 0.5, tenant: {price: -0.5, dueDate: "1990-06-15", parcels: []}}, {cap: 0.5, flag: -0.5, share: "-0.5/true", surcharge: false, tenant: {bonus: 0.1666666666666666666666666667, dueDate: "1990-06-15", grade: -0.5, parcels: [], price: -0.5}}], + [{cap: 100, tenant: {price: 1e3, dueDate: "2025-03-20", kind: "retail", parcels: [{amount: 0.5, limit: 2.50, dueDate: "2024-01-01", price: -0, employees: [{rate: 1000, income: 0.5}, {rate: 7.25, income: 1000}, {rate: 2, income: 99999999999999999999}]}], extraField: "x"}}, {cap: 100, share: "ok", surcharge: true, tenant: {dueDate: "2025-03-20", extraField: "x", kind: "retail", parcels: [{amount: 0.5, band: 4, bucket: 2.50, dueDate: "2024-01-01", employees: [{income: 0.5, rate: 1000}, {income: 1000, rate: 7.25}, {income: 99999999999999999999, rate: 2}], fee: "2024", limit: 2.50, penalty: true, price: 0, review: {n: "true/true", ok: 0.11}}], price: 1000}}], + [{cap: 100, tenant: {price: 100, dueDate: "2025-03-20", parcels: [{amount: 65, dueDate: null, price: 0.1, employees: [{rate: -0.5, income: -0}, {rate: 5, income: 18}]}, {amount: 2.50, limit: 1e3, dueDate: "2030-12-31", price: 7.25, employees: [{rate: 162, income: 99.99}, {rate: 250, income: 250}]}]}}, {cap: 100, share: "ok", surcharge: true, tenant: {dueDate: "2025-03-20", parcels: [{amount: 65, band: 2, bucket: null, dueDate: null, employees: [{income: 0, rate: -0.5}, {income: 18, rate: 5}], fee: "2025", penalty: false, price: 0.1, review: {n: "true/true", ok: 9.32}}, {amount: 2.50, band: 4, bucket: 1000, dueDate: "2030-12-31", employees: [{income: 99.99, rate: 162}, {income: 250, rate: 250}], fee: "2030", limit: 1000, penalty: false, price: 7.25, review: {n: "true/true", ok: 0.39}}], price: 100}}], + [{cap: 10, tenant: {price: 100, dueDate: "2030-12-31", kind: 5, parcels: [{amount: 0.1, limit: 123456789.123, dueDate: "1990-06-15", price: 2, employees: [{rate: 100, income: -0.01}]}, {amount: 99.99, limit: 65, dueDate: "2024-02-29", price: 0.5, employees: [{rate: -500, income: 10}, {rate: 10, income: 99999999999999999999}]}]}}, "!error: InputValidationFailed"], + [{cap: 10, tenant: {price: 2, dueDate: "2030-12-31", kind: "retail", parcels: [{amount: 99999999999999999999, dueDate: null, price: -1, employees: []}, {amount: 2, dueDate: "2024-02-29", price: 386, employees: [{rate: 5, income: 18}, {rate: 99.99, income: 1000}]}, {amount: 250, dueDate: "2000-01-01", price: 0.5, employees: []}, {amount: 0.5, limit: 1, dueDate: "2030-12-31", price: 123456789.123, employees: []}, {amount: 99.99, limit: 123456789.123, dueDate: null, price: 1, employees: [{rate: -0.01, income: 2}, {rate: 0.000001, income: 0.5}]}, {amount: 1000, limit: 123456789.123, dueDate: null, price: -1, employees: []}, {amount: 99999999999999999999, limit: 1000000, price: 1000000, employees: [{rate: 1000000, income: 10}, {rate: 88, income: 0.000001}]}, {amount: 2, limit: 2.50, price: 2.50, employees: []}, {amount: -0.01, limit: 487, dueDate: null, price: 18, employees: []}, {amount: -1, limit: null, dueDate: "2025-03-20T10:15:30Z", price: 0.5, employees: [{rate: 2, income: 1000000}, {rate: 5, income: 123456789.123}]}, {amount: 1, dueDate: "2030-12-31", price: 1000000, employees: [{rate: -0.5, income: 100}, {rate: 0.5, income: 0}]}, {amount: 0.5, limit: null, dueDate: null, price: 99.99, employees: []}, {amount: 0.5, limit: 2, dueDate: null, price: 2, employees: []}, {amount: 315, limit: 2.50, dueDate: null, price: 10, employees: []}]}}, {cap: 10, share: "ok", surcharge: true, tenant: {dueDate: "2030-12-31", kind: "retail", parcels: [{amount: 99999999999999999999, band: 0, bucket: null, dueDate: null, employees: [], fee: "2025", penalty: true, price: -1, review: {n: "true/true", ok: 14285714285714285714.18}}, {amount: 2, band: 2, bucket: null, dueDate: "2024-02-29", employees: [{income: 18, rate: 5}, {income: 1000, rate: 99.99}], fee: "2024", penalty: true, price: 386, review: {n: "true/true", ok: 0.32}}, {amount: 250, band: 0, bucket: null, dueDate: "2000-01-01", employees: [], fee: "2000", penalty: true, price: 0.5, review: {n: "true/true", ok: 35.75}}, {amount: 0.5, band: 0, bucket: 1, dueDate: "2030-12-31", employees: [], fee: "2030", limit: 1, penalty: true, price: 123456789.123, review: {n: "true/true", ok: 0.11}}, {amount: 99.99, band: 2, bucket: 123456789.123, dueDate: null, employees: [{income: 2, rate: -0.01}, {income: 0.5, rate: 0.000001}], fee: "2025", limit: 123456789.123, penalty: true, price: 1, review: {n: "true/true", ok: 14.32}}, {amount: 1000, band: 0, bucket: 123456789.123, dueDate: null, employees: [], fee: "2025", limit: 123456789.123, penalty: true, price: -1, review: {n: "true/true", ok: 142.89}}, {amount: 99999999999999999999, band: 4, bucket: 1000000, employees: [{income: 10, rate: 1000000}, {income: 0.000001, rate: 88}], fee: "2025", limit: 1000000, penalty: true, price: 1000000, review: {n: "true/true", ok: 14285714285714285714.18}}, {amount: 2, band: 0, bucket: 2.50, employees: [], fee: "2025", limit: 2.50, penalty: true, price: 2.50, review: {n: "true/true", ok: 0.32}}, {amount: -0.01, band: 0, bucket: 487, dueDate: null, employees: [], fee: "2025", limit: 487, penalty: true, price: 18, review: {n: "true/true", ok: 0.03}}, {amount: -1, band: 2, bucket: null, dueDate: "2025-03-20T10:15:30Z", employees: [{income: 1000000, rate: 2}, {income: 123456789.123, rate: 5}], fee: "2025", limit: null, penalty: true, price: 0.5, review: {n: "true/true", ok: -0.11}}, {amount: 1, band: 4, bucket: null, dueDate: "2030-12-31", employees: [{income: 100, rate: -0.5}, {income: 0, rate: 0.5}], fee: "2030", penalty: true, price: 1000000, review: {n: "true/true", ok: 0.18}}, {amount: 0.5, band: 0, bucket: null, dueDate: null, employees: [], fee: "2025", limit: null, penalty: true, price: 99.99, review: {n: "true/true", ok: 0.11}}, {amount: 0.5, band: 0, bucket: 2, dueDate: null, employees: [], fee: "2025", limit: 2, penalty: true, price: 2, review: {n: "true/true", ok: 0.11}}, {amount: 315, band: 0, bucket: 2.50, dueDate: null, employees: [], fee: "2025", limit: 2.50, penalty: true, price: 10, review: {n: "true/true", ok: 45.04}}], price: 2}}], + [{cap: 0, tenant: {price: 65, dueDate: "2030-12-31", parcels: [{amount: 10, limit: null, dueDate: "2000-01-01", price: 7.25, employees: [{rate: 2, income: 10}, {rate: 2, income: 0.5}]}, {amount: 5, dueDate: "2025-03-20T10:15:30Z", price: 250, employees: [{rate: 100, income: 2.50}, {rate: 250, income: 250}, {rate: 0.000001, income: 10}]}, {amount: 18, limit: 18, dueDate: "2024-02-29", price: -500, employees: []}, {amount: 100, limit: null, dueDate: "2024-02-29", price: 123456789.123, employees: [{rate: 10, income: 1}, {rate: 0.5, income: 10}, {rate: 0.000001, income: -1}]}, {amount: 250, limit: 1000000, price: 123456789.123, employees: [{rate: 0.1, income: 0.25}, {rate: 2.50, income: 189}, {rate: 1000000, income: 0.5}]}]}}, {cap: 0, share: "ok", surcharge: false, tenant: {dueDate: "2030-12-31", parcels: [{amount: 10, band: 4, bucket: null, dueDate: "2000-01-01", employees: [{income: 10, rate: 2}, {income: 0.5, rate: 2}], fee: "2000", limit: null, penalty: false, price: 7.25, review: {n: "false/false", ok: 1.46}}, {amount: 5, band: 4, bucket: null, dueDate: "2025-03-20T10:15:30Z", employees: [{income: 2.50, rate: 100}, {income: 250, rate: 250}, {income: 10, rate: 0.000001}], fee: "2025", penalty: false, price: 250, review: {n: "false/false", ok: 0.75}}, {amount: 18, band: 0, bucket: 18, dueDate: "2024-02-29", employees: [], fee: "2024", limit: 18, penalty: false, price: -500, review: {n: "false/false", ok: 2.61}}, {amount: 100, band: 4, bucket: null, dueDate: "2024-02-29", employees: [{income: 1, rate: 10}, {income: 10, rate: 0.5}, {income: -1, rate: 0.000001}], fee: "2024", limit: null, penalty: false, price: 123456789.123, review: {n: "false/false", ok: 14.32}}, {amount: 250, band: 4, bucket: 1000000, employees: [{income: 0.25, rate: 0.1}, {income: 189, rate: 2.50}, {income: 0.5, rate: 1000000}], fee: "2025", limit: 1000000, penalty: false, price: 123456789.123, review: {n: "false/false", ok: 35.75}}], price: 65}}], + [{cap: 0, tenant: {price: 0.5, dueDate: "1990-06-15", kind: "retail", parcels: [{amount: 18, limit: null, price: -1, employees: [{rate: 10, income: 2}, {rate: 1000, income: 99.99}]}, {amount: 0.5, limit: null, dueDate: null, price: 18, employees: []}, {amount: 10, limit: 58, dueDate: "2025-03-20", price: -1, employees: [{rate: 1, income: 0}]}]}}, {cap: 0, share: "ok", surcharge: false, tenant: {dueDate: "1990-06-15", kind: "retail", parcels: [{amount: 18, band: 4, bucket: null, employees: [{income: 2, rate: 10}, {income: 99.99, rate: 1000}], fee: "2025", limit: null, penalty: true, price: -1, review: {n: "false/false", ok: 2.61}}, {amount: 0.5, band: 0, bucket: null, dueDate: null, employees: [], fee: "2025", limit: null, penalty: true, price: 18, review: {n: "false/false", ok: 0.11}}, {amount: 10, band: 4, bucket: 58, dueDate: "2025-03-20", employees: [{income: 0, rate: 1}], fee: "2025", limit: 58, penalty: true, price: -1, review: {n: "false/false", ok: 1.46}}], price: 0.5}}], + [{cap: 1, tenant: {price: 250, dueDate: "2025-03-20", kind: "retail", parcels: [{amount: 10, limit: 100, price: 10, employees: [{rate: 1000000, income: 0.5}, {rate: 0.5, income: 1000}]}, {amount: 10, limit: 65, dueDate: null, price: 380, employees: [{rate: 5, income: -0.01}, {rate: 99999999999999999999, income: 10}]}]}}, {cap: 1, share: "ok", surcharge: false, tenant: {dueDate: "2025-03-20", kind: "retail", parcels: [{amount: 10, band: 4, bucket: 100, employees: [{income: 0.5, rate: 1000000}, {income: 1000, rate: 0.5}], fee: "2025", limit: 100, penalty: true, price: 10, review: {n: "false/false", ok: 1.46}}, {amount: 10, band: 4, bucket: 65, dueDate: null, employees: [{income: -0.01, rate: 5}, {income: 10, rate: 99999999999999999999}], fee: "2025", limit: 65, penalty: true, price: 380, review: {n: "false/false", ok: 1.46}}], price: 250}}], + [{cap: 0, tenant: {price: 0, dueDate: "2024-02-29", kind: "retail", parcels: [{amount: 7.25, limit: -0.01, dueDate: "1990-06-15", price: -0, employees: [{rate: 99.99, income: 18}, {rate: 10, income: 1000}, {rate: 250, income: 250}]}]}}, {cap: 0, share: "ok", surcharge: false, tenant: {dueDate: "2024-02-29", kind: "retail", parcels: [{amount: 7.25, band: 4, bucket: -0.01, dueDate: "1990-06-15", employees: [{income: 18, rate: 99.99}, {income: 1000, rate: 10}, {income: 250, rate: 250}], fee: "1990", limit: -0.01, penalty: true, price: 0, review: {n: "false/false", ok: 1.07}}], price: 0}}], + [{cap: 0, tenant: {price: 65, dueDate: "2025-03-20", parcels: []}}, {cap: 0, flag: 0, share: "0/true", surcharge: false, tenant: {bonus: 0, dueDate: "2025-03-20", grade: 0, parcels: [], price: 65}}], + [{cap: 0, tenant: {price: 0.5, dueDate: "2025-03-20T10:15:30Z", kind: "corporate", parcels: [{amount: 250, limit: 100, dueDate: "2000-01-01", price: 10, employees: [{rate: 18, income: 0.1}, {rate: 1e3, income: 10}, {rate: 2, income: 0.5}]}]}}, {cap: 0, share: "ok", surcharge: false, tenant: {dueDate: "2025-03-20T10:15:30Z", kind: "corporate", parcels: [{amount: 250, band: 4, bucket: 100, dueDate: "2000-01-01", employees: [{income: 0.1, rate: 18}, {income: 10, rate: 1000}, {income: 0.5, rate: 2}], fee: "2000", limit: 100, penalty: true, price: 10, review: {n: "false/false", ok: 35.75}}], price: 0.5}}], + [{cap: -2, tenant: {price: 0.25, dueDate: "2025-03-20", kind: "corporate", parcels: [{amount: 99.99, limit: 0.5, dueDate: "2025-03-20T10:15:30Z", price: 2, employees: [{rate: 10, income: 10}]}]}}, {cap: -2, share: "ok", surcharge: false, tenant: {dueDate: "2025-03-20", kind: "corporate", parcels: [{amount: 99.99, band: 4, bucket: 0.5, dueDate: "2025-03-20T10:15:30Z", employees: [{income: 10, rate: 10}], fee: "2025", limit: 0.5, penalty: true, price: 2, review: {n: "false/false", ok: 14.32}}], price: 0.25}}], + [{cap: -2, tenant: {price: 250, dueDate: "2030-12-31", kind: "retail", parcels: []}}, {cap: -2, flag: 250, share: "250/true", surcharge: false, tenant: {bonus: -0.6666666666666666666666666667, dueDate: "2030-12-31", grade: 250, kind: "retail", parcels: [], price: 250}}], + [{cap: 10, tenant: {price: 1000, dueDate: "2030-12-31", kind: "retail", parcels: [], extraField: "x"}}, {cap: 10, flag: 1000, share: "1000/true", surcharge: true, tenant: {bonus: 3.3333333333333333333333333333, dueDate: "2030-12-31", extraField: "x", grade: 1000, kind: "retail", parcels: [], price: 1000}}], + [{cap: -2, tenant: {price: 1000, dueDate: "1990-06-15", parcels: [{amount: 5, dueDate: "2025-03-20T10:15:30Z", price: 10, employees: [{rate: 100, income: 250}]}, {amount: 1000, dueDate: null, price: 1000, employees: [{rate: 100, income: 99999999999999999999}, {rate: 0.25, income: -500}]}]}}, {cap: -2, share: "ok", surcharge: false, tenant: {dueDate: "1990-06-15", parcels: [{amount: 5, band: 1, bucket: null, dueDate: "2025-03-20T10:15:30Z", employees: [{income: 250, rate: 100}], fee: "2025", penalty: false, price: 10, review: {n: "false/false", ok: 0.75}}, {amount: 1000, band: 4, bucket: null, dueDate: null, employees: [{income: 99999999999999999999, rate: 100}, {income: -500, rate: 0.25}], fee: "2025", penalty: false, price: 1000, review: {n: "false/false", ok: 142.89}}], price: 1000}}], + [{cap: 10, tenant: {price: 0, dueDate: "2025-03-20", parcels: [{amount: 2, limit: -0, dueDate: "2024-02-29", price: 250, employees: [{rate: -0.01, income: 18}]}, {amount: 250, limit: 65, dueDate: "2025-03-20T10:15:30Z", price: 65, employees: [{rate: -0.5, income: 0.1}, {rate: 1000, income: 250}]}, {amount: 2.50, limit: 0.5, dueDate: "2024-02-29", price: 1e3, employees: [{rate: -0.5, income: -500}, {rate: 0.5, income: 0.5}]}, {amount: -0.5, limit: 250, dueDate: "2025-03-20T10:15:30Z", price: 10, employees: [{rate: 0, income: 10}, {rate: 0.000001, income: 2.50}]}, {amount: 1000, limit: 0.5, dueDate: "2025-03-20", price: 1, employees: []}]}}, {cap: 10, share: "ok", surcharge: true, tenant: {dueDate: "2025-03-20", parcels: [{amount: 2, band: 1, bucket: 0, dueDate: "2024-02-29", employees: [{income: 18, rate: -0.01}], fee: "2024", limit: 0, penalty: false, price: 250, review: {n: "true/true", ok: 0.32}}, {amount: 250, band: 4, bucket: 65, dueDate: "2025-03-20T10:15:30Z", employees: [{income: 0.1, rate: -0.5}, {income: 250, rate: 1000}], fee: "2025", limit: 65, penalty: false, price: 65, review: {n: "true/true", ok: 35.75}}, {amount: 2.50, band: 4, bucket: 0.5, dueDate: "2024-02-29", employees: [{income: -500, rate: -0.5}, {income: 0.5, rate: 0.5}], fee: "2024", limit: 0.5, penalty: false, price: 1000, review: {n: "true/true", ok: 0.39}}, {amount: -0.5, band: 2, bucket: 250, dueDate: "2025-03-20T10:15:30Z", employees: [{income: 10, rate: 0}, {income: 2.50, rate: 0.000001}], fee: "2025", limit: 250, penalty: false, price: 10, review: {n: "true/true", ok: -0.04}}, {amount: 1000, band: 0, bucket: 0.5, dueDate: "2025-03-20", employees: [], fee: "2025", limit: 0.5, penalty: false, price: 1, review: {n: "true/true", ok: 142.89}}], price: 0}}], + [{cap: 10, tenant: {price: 250, dueDate: "2025-03-20", kind: "corporate", parcels: [{amount: 0.5, limit: 5, dueDate: "2024-01-01", price: 100, employees: [{rate: 0.1, income: 0.1}, {rate: 7.25, income: 250}, {rate: 1000, income: 0.5}]}], extraField: 1}}, {cap: 10, share: "ok", surcharge: true, tenant: {dueDate: "2025-03-20", extraField: 1, kind: "corporate", parcels: [{amount: 0.5, band: 4, bucket: 5, dueDate: "2024-01-01", employees: [{income: 0.1, rate: 0.1}, {income: 250, rate: 7.25}, {income: 0.5, rate: 1000}], fee: "2024", limit: 5, penalty: true, price: 100, review: {n: "true/true", ok: 0.11}}], price: 250}}], + [{cap: -2, tenant: {price: -500, dueDate: "2025-03-20T10:15:30Z", kind: "retail", parcels: []}}, {cap: -2, flag: -500, share: "-500/true", surcharge: false, tenant: {bonus: -0.6666666666666666666666666667, dueDate: "2025-03-20T10:15:30Z", grade: -500, kind: "retail", parcels: [], price: -500}}], + [{cap: 0, tenant: {price: 0.5, dueDate: null, kind: "corporate", parcels: []}}, {cap: 0, flag: 0.5, share: "0.5/true", surcharge: false, tenant: {bonus: 0, dueDate: null, grade: 0.5, kind: "corporate", parcels: [], price: 0.5}}], + [{cap: 100, tenant: {price: -0, dueDate: "2025-03-20T10:15:30Z", kind: "corporate", parcels: [{amount: 145, limit: -500, dueDate: "2025-03-20", price: 2.50, employees: [{rate: 0, income: -0.01}, {rate: 10, income: 100}, {rate: 65, income: 250}]}, {amount: 1e3, limit: 0, dueDate: "2030-12-31", price: 0.25, employees: [{rate: 0.5, income: 1000}, {rate: 250, income: 2.50}]}]}}, {cap: 100, share: "ok", surcharge: true, tenant: {dueDate: "2025-03-20T10:15:30Z", kind: "corporate", parcels: [{amount: 145, band: 4, bucket: -500, dueDate: "2025-03-20", employees: [{income: -0.01, rate: 0}, {income: 100, rate: 10}, {income: 250, rate: 65}], fee: "2025", limit: -500, penalty: false, price: 2.50, review: {n: "true/true", ok: 20.75}}, {amount: 1000, band: 4, bucket: 0, dueDate: "2030-12-31", employees: [{income: 1000, rate: 0.5}, {income: 2.50, rate: 250}], fee: "2030", limit: 0, penalty: false, price: 0.25, review: {n: "true/true", ok: 142.89}}], price: 0}}], + [{cap: 1, tenant: {price: 100, dueDate: "2024-02-29", parcels: [{amount: 99.99, price: 250, employees: [{rate: 7.25, income: 0.000001}, {rate: -0.5, income: 99.99}]}, {amount: 0.5, price: 1000, employees: [{rate: 0.5, income: 10}, {rate: 18, income: 2}]}]}}, {cap: 1, share: "ok", surcharge: false, tenant: {dueDate: "2024-02-29", parcels: [{amount: 99.99, band: 4, bucket: null, employees: [{income: 0.000001, rate: 7.25}, {income: 99.99, rate: -0.5}], fee: "2025", penalty: false, price: 250, review: {n: "false/false", ok: 14.32}}, {amount: 0.5, band: 4, bucket: null, employees: [{income: 10, rate: 0.5}, {income: 2, rate: 18}], fee: "2025", penalty: false, price: 1000, review: {n: "false/false", ok: 0.11}}], price: 100}}], + ], +} + +// seed 343400 (attempt 0) +{ + name: "b 35: claim/items/parts: 5 expression, 4 match, 3 table; 3 root, 14 per-member, 1 top-level computed", + policy: { + models: {claim: {qty: "number?", insured: "boolean", city: "string", verified: "boolean", urgent: "boolean?", age: "number?", items: "item[]"}, item: {age: "number?", openedAt: "date", flagged: "boolean?", country: "string", parts: "part[]"}, part: {balance: "number"}}, + blocks: [ + {match: "item.totals.grade", arms: [["not (claim.insured)", "(min([abs((item.age ?? 0)), 1000]) ^ 0) == (claim.age ?? 0)"], ["", "((item.flagged ?? false) and (item.flagged ?? false))"]]}, + {table: "t2", inputs: ["(item.flagged ?? false)", "claim.insured"], outputs: ["item.totals.level", "item.segment", "item.review"], rules: [ + ["false", "false", "(claim.qty ?? 0)", "-((item.age ?? 0))", "claim.city"], + ["true", "", "(claim.age ?? 0)", "count(item.parts, (#.balance == 18 and #.balance > 1000))", "claim.city"], + ["", "true", "(item.age ?? 0)", "(claim.qty ?? 0)", "'A1'"], + ["true", "", "((claim.age ?? 0) / 3)", "(item.age ?? 0)", "`${(claim.qty ?? 0)}/${(claim.qty ?? 0)}`"], + ["true", "false", "(max(map(item.parts, #.balance)) ?? 0)", "(claim.age ?? 0)", "item.country"], + ["false", "false", "(avg(map(item.parts, max([#.balance, #.balance]))) ?? 0)", "(max(map(item.parts, 10)) ?? 0)", "`${(claim.age ?? 0)}/${(claim.qty ?? 0)}`"], + ["", "", "(avg(map(item.parts, #.balance)) ?? 0)", "2", "(split(item.country, '-')[0] ?? 'none')"], + ]}, + {match: "item.totals.flag", arms: [["item.openedAt < d('2024-01-01')", "item.country"], ["(item.segment ?? 0) > 18", "string((claim.qty ?? 0))"], ["contains(['none', 'Oslo', ''], (item.review ?? ''))", "(((item.review ?? '') + '-' + claim.city) + '-' + `${'gold'}/${(item.segment ?? 0)}`)"], ["(item.totals.level ?? 0) in [50..148]", "(contains(['DE', 'retail', ''], claim.city) ? (item.country + '-' + item.country) : string((claim.urgent ?? false)))"], ["", "'Oslo'"]]}, + {expression: "item.discount", value: "all(item.parts, not (#.balance > 3))"}, + {expression: "claim.bonus", value: "round((claim.qty ?? 0), 2)"}, + {expression: "band", value: "claim.urgent"}, + {table: "t7", inputs: ["claim.insured"], outputs: ["claim.total", "claim.scores.exposure"], rules: [ + ["true", "string(claim.insured)", "claim.city"], + ["false", "", "'ok'"], + ["true", "claim.city", "'DE'"], + ["false", "claim.city", "'VIP'"], + ["true", "'ok'", "((claim.urgent ?? false) ? claim.city : claim.city)"], + ["", "claim.city", "claim.city"], + ["", "`${(claim.qty ?? 0)}/${(claim.qty ?? 0)}`", "string((claim.age ?? 0))"], + ]}, + {match: "item.adjusted", arms: [["((claim.age ?? 0) + (item.segment ?? 0)) == (item.totals.level ?? 0)", "matches((claim.total ?? ''), '^[A-Z]')"], ["100 > claim.bonus", "claim.bonus in (48..60)"], ["claim.bonus in (30..163]", "some(item.parts, (#.balance > 3 and #.balance <= 0))"], ["", "(claim.urgent ?? false)"]]}, + {expression: "item.risk", value: "(claim.bonus / 3)"}, + {expression: "item.penalty", value: "{s: number(string(len((claim.scores.exposure ?? '')))), a: claim.city}"}, + {table: "t11", inputs: ["(item.penalty.s - (item.age ?? 0))", "item.adjusted", "round((claim.qty ?? 0), 2)"], outputs: ["item.fee", "item.points"], rules: [ + ["5, 0", "", "10", "(band ?? false)", "-((item.segment ?? 0))"], + ["> 1.5", "", "> 1.5", "item.totals.grade", "0.5"], + ]}, + {match: "item.surcharge", arms: [["((item.review ?? '') != 'Oslo' or startsWith(item.country, 'low'))", "`${item.country}/${item.adjusted}`"], ["", "item.country"]]}, + ], + }, + cases: [ + [{claim: {qty: 1.5, insured: false, city: "a", verified: false, urgent: true, age: 0.1, items: [{age: 2, openedAt: "2025-03-20", flagged: true, country: "Zed", parts: [{balance: -1}]}, {age: 99.99, openedAt: "2025-03-20T10:15:30Z", flagged: true, country: "retail", parts: [{balance: 0}, {balance: 99999999999999999999}, {balance: 123456789.123}]}], extraField: 1}}, {claim: {age: 0.1, bonus: 1.5, city: "a", extraField: 1, insured: false, items: [{adjusted: false, age: 2, country: "Zed", discount: true, fee: null, flagged: true, openedAt: "2025-03-20", parts: [{balance: -1}], penalty: {a: "a", s: 2}, points: null, review: "a", risk: 0.5, segment: 0, surcharge: "Zed/false", totals: {level: 0.1}}, {adjusted: false, age: 99.99, country: "retail", discount: false, fee: null, flagged: true, openedAt: "2025-03-20T10:15:30Z", parts: [{balance: 0}, {balance: 99999999999999999999}, {balance: 123456789.123}], penalty: {a: "a", s: 2}, points: null, review: "a", risk: 0.5, segment: 0, surcharge: "retail/false", totals: {level: 0.1}}], qty: 1.5, scores: {exposure: "ok"}, total: "a", urgent: true, verified: false}}], + [{claim: {qty: 0.5, insured: true, city: "none", verified: true, urgent: true, age: 18, items: [{age: 3, openedAt: "1990-06-15", flagged: true, country: "A1", parts: [{balance: 0.1}, {balance: 2}]}, {age: 0.5, openedAt: "2000-01-01", flagged: true, country: "a", parts: [{balance: 18}]}]}}, {claim: {age: 18, bonus: 0.5, city: "none", insured: true, items: [{adjusted: false, age: 3, country: "A1", discount: true, fee: null, flagged: true, openedAt: "1990-06-15", parts: [{balance: 0.1}, {balance: 2}], penalty: {a: "none", s: 4}, points: null, review: "none", risk: 0.1666666666666666666666666667, segment: 0, surcharge: "A1/false", totals: {level: 18}}, {adjusted: false, age: 0.5, country: "a", discount: false, fee: null, flagged: true, openedAt: "2000-01-01", parts: [{balance: 18}], penalty: {a: "none", s: 4}, points: null, review: "none", risk: 0.1666666666666666666666666667, segment: 0, surcharge: "a/false", totals: {level: 18}}], qty: 0.5, scores: {exposure: "none"}, total: "true", urgent: true, verified: true}}], + [{claim: {qty: 2, insured: false, city: "Zed", verified: true, urgent: false, age: 0, items: []}}, {claim: {age: 0, bonus: 2, city: "Zed", insured: false, items: [], qty: 2, scores: {exposure: "ok"}, total: "Zed", urgent: false, verified: true}}], + [{claim: {qty: null, insured: false, city: "Zed", verified: false, urgent: null, age: 100, items: [{openedAt: "2024-01-01", country: "Oslo", parts: [{balance: 10}]}, {age: 2.50, openedAt: "2024-01-01", flagged: null, country: "O'Neil", parts: [{balance: 10}, {balance: 65}]}]}}, {claim: {age: 100, bonus: 0, city: "Zed", insured: false, items: [{adjusted: false, country: "Oslo", discount: false, fee: null, openedAt: "2024-01-01", parts: [{balance: 10}], penalty: {a: "Zed", s: 2}, points: null, review: "Zed", risk: 0, segment: -0, surcharge: "Oslo/false", totals: {level: 0}}, {adjusted: false, age: 2.50, country: "O'Neil", discount: false, fee: null, flagged: null, openedAt: "2024-01-01", parts: [{balance: 10}, {balance: 65}], penalty: {a: "Zed", s: 2}, points: null, review: "Zed", risk: 0, segment: -2.50, surcharge: "O'Neil/false", totals: {level: 0}}], qty: null, scores: {exposure: "ok"}, total: "Zed", urgent: null, verified: false}}], + [{claim: {qty: null, insured: true, city: "Oslo", verified: true, urgent: false, age: 250, items: [{openedAt: "2025-03-20", country: "O'Neil", parts: [{balance: 99999999999999999999}, {balance: 1000000}]}, {openedAt: "2000-01-01", flagged: true, country: "abc", parts: []}]}}, {claim: {age: 250, bonus: 0, city: "Oslo", insured: true, items: [{adjusted: false, country: "O'Neil", discount: false, fee: null, openedAt: "2025-03-20", parts: [{balance: 99999999999999999999}, {balance: 1000000}], penalty: {a: "Oslo", s: 4}, points: null, review: "A1", risk: 0, segment: 0, surcharge: "O'Neil/false", totals: {level: 0}}, {adjusted: false, country: "abc", discount: true, fee: null, flagged: true, openedAt: "2000-01-01", parts: [], penalty: {a: "Oslo", s: 4}, points: null, review: "Oslo", risk: 0, segment: 0, surcharge: "abc", totals: {level: 250}}], qty: null, scores: {exposure: "Oslo"}, total: "true", urgent: false, verified: true}}], + [{claim: {qty: 10, insured: false, city: "Oslo", verified: false, urgent: false, age: 100, items: [{age: 1.5, openedAt: "2000-01-01", flagged: true, country: "low", parts: [{balance: 2}, {balance: 10}]}]}}, {claim: {age: 100, bonus: 10, city: "Oslo", insured: false, items: [{adjusted: true, age: 1.5, country: "low", discount: false, fee: null, flagged: true, openedAt: "2000-01-01", parts: [{balance: 2}, {balance: 10}], penalty: {a: "Oslo", s: 2}, points: null, review: "Oslo", risk: 3.3333333333333333333333333333, segment: 0, surcharge: "low/true", totals: {level: 100}}], qty: 10, scores: {exposure: "ok"}, total: "Oslo", urgent: false, verified: false}}], + [{claim: {qty: 0.5, insured: true, city: "A1", verified: false, urgent: "true", age: 1000, items: [{age: 7.25, openedAt: "2000-01-01", flagged: false, country: "gold", parts: [{balance: 0.1}]}]}}, "!error: InputValidationFailed"], + [{claim: {qty: 0.5, insured: false, city: "low", verified: false, urgent: true, age: 1, items: [{age: 1e3, openedAt: "2030-12-31", flagged: true, country: "Oslo", parts: [{balance: -0}, {balance: 0}]}, {age: 250, openedAt: "2000-01-01", flagged: false, country: "A1", parts: [{balance: 3}, {balance: -0.5}]}, {age: 0, openedAt: "2030-12-31", flagged: false, country: "ok", parts: [{balance: 1.5}]}, {age: 65, openedAt: "2024-01-01", flagged: false, country: "Oslo", parts: [{balance: 1}, {balance: 18}]}]}}, {claim: {age: 1, bonus: 0.5, city: "low", insured: false, items: [{adjusted: false, age: 1000, country: "Oslo", discount: true, fee: null, flagged: true, openedAt: "2030-12-31", parts: [{balance: 0}, {balance: 0}], penalty: {a: "low", s: 2}, points: null, review: "low", risk: 0.1666666666666666666666666667, segment: 0, surcharge: "Oslo/false", totals: {level: 1}}, {adjusted: false, age: 250, country: "A1", discount: true, fee: null, flagged: false, openedAt: "2000-01-01", parts: [{balance: 3}, {balance: -0.5}], penalty: {a: "low", s: 2}, points: null, review: "low", risk: 0.1666666666666666666666666667, segment: -250, surcharge: "A1/false", totals: {level: 0.5}}, {adjusted: false, age: 0, country: "ok", discount: true, fee: null, flagged: false, openedAt: "2030-12-31", parts: [{balance: 1.5}], penalty: {a: "low", s: 2}, points: null, review: "low", risk: 0.1666666666666666666666666667, segment: -0, surcharge: "ok/false", totals: {level: 0.5}}, {adjusted: false, age: 65, country: "Oslo", discount: false, fee: null, flagged: false, openedAt: "2024-01-01", parts: [{balance: 1}, {balance: 18}], penalty: {a: "low", s: 2}, points: null, review: "low", risk: 0.1666666666666666666666666667, segment: -65, surcharge: "Oslo/false", totals: {level: 0.5}}], qty: 0.5, scores: {exposure: "ok"}, total: "low", urgent: true, verified: false}}], + [{claim: {qty: 100, insured: false, city: "", verified: false, urgent: true, age: -0.01, items: []}}, {claim: {age: -0.01, bonus: 100, city: "", insured: false, items: [], qty: 100, scores: {exposure: "ok"}, total: "", urgent: true, verified: false}}], + [{claim: {qty: 0, insured: true, city: "NL", verified: false, urgent: null, age: 1000000, items: [{openedAt: "2024-01-01", flagged: null, country: "A1", parts: [{balance: 0.5}, {balance: 18}, {balance: 71}]}, {age: 18, openedAt: "2025-03-20", flagged: true, country: "3.5", parts: [{balance: 1000000}]}]}}, {claim: {age: 1000000, bonus: 0, city: "NL", insured: true, items: [{adjusted: false, country: "A1", discount: false, fee: null, flagged: null, openedAt: "2024-01-01", parts: [{balance: 0.5}, {balance: 18}, {balance: 71}], penalty: {a: "NL", s: 2}, points: null, review: "A1", risk: 0, segment: 0, surcharge: "A1/false", totals: {level: 0}}, {adjusted: false, age: 18, country: "3.5", discount: false, fee: null, flagged: true, openedAt: "2025-03-20", parts: [{balance: 1000000}], penalty: {a: "NL", s: 2}, points: null, review: "NL", risk: 0, segment: 0, surcharge: "3.5/false", totals: {level: 1000000}}], qty: 0, scores: {exposure: "NL"}, total: "true", urgent: null, verified: false}}], + [{claim: {qty: 99999999999999999999, insured: false, city: "12", verified: false, urgent: true, age: 10, items: [{age: 10, openedAt: "2024-02-29", flagged: false, country: "a-b-c", parts: [{balance: 0}]}, {age: 1000000, openedAt: "2024-01-01", flagged: false, country: "gold", parts: []}]}}, {claim: {age: 10, bonus: 99999999999999999999, city: "12", insured: false, items: [{adjusted: true, age: 10, country: "a-b-c", discount: true, fee: null, flagged: false, openedAt: "2024-02-29", parts: [{balance: 0}], penalty: {a: "12", s: 2}, points: null, review: "12", risk: 33333333333333333333, segment: -10, surcharge: "a-b-c/true", totals: {level: 99999999999999999999}}, {adjusted: true, age: 1000000, country: "gold", discount: true, fee: null, flagged: false, openedAt: "2024-01-01", parts: [], penalty: {a: "12", s: 2}, points: null, review: "12", risk: 33333333333333333333, segment: -1000000, surcharge: "gold/true", totals: {level: 99999999999999999999}}], qty: 99999999999999999999, scores: {exposure: "ok"}, total: "12", urgent: true, verified: false}}], + [{claim: {qty: 0.5, insured: false, city: "low", verified: false, urgent: true, age: 123456789.123, items: [{age: 201, openedAt: 20250101, flagged: false, country: "Oslo", parts: [{balance: 1.5}, {balance: 5}]}]}}, "!error: InputValidationFailed"], + [{claim: {qty: 1000, insured: true, city: "é ü", verified: false, urgent: false, age: 100, items: [{age: 18, openedAt: "2024-01-01", flagged: true, country: "none", parts: [{balance: 0.1}, {balance: 10}]}]}}, {claim: {age: 100, bonus: 1000, city: "é ü", insured: true, items: [{adjusted: false, age: 18, country: "none", discount: false, fee: null, flagged: true, openedAt: "2024-01-01", parts: [{balance: 0.1}, {balance: 10}], penalty: {a: "é ü", s: 5}, points: null, review: "é ü", risk: 333.33333333333333333333333333, segment: 0, surcharge: "none/false", totals: {level: 100}}], qty: 1000, scores: {exposure: "é ü"}, total: "true", urgent: false, verified: false}}], + [{claim: {qty: 1.5, insured: true, city: "none", verified: false, urgent: true, age: 1000, items: [{age: 99.99, openedAt: "1990-06-15", flagged: false, country: "none", parts: [{balance: 0.000001}, {balance: 10}]}, {age: 0, openedAt: "2024-01-01", flagged: false, country: "-", parts: [{balance: 3}]}]}}, {claim: {age: 1000, bonus: 1.5, city: "none", insured: true, items: [{adjusted: false, age: 99.99, country: "none", discount: false, fee: null, flagged: false, openedAt: "1990-06-15", parts: [{balance: 0.000001}, {balance: 10}], penalty: {a: "none", s: 4}, points: null, review: "A1", risk: 0.5, segment: 1.5, surcharge: "none/false", totals: {level: 99.99}}, {adjusted: false, age: 0, country: "-", discount: true, fee: null, flagged: false, openedAt: "2024-01-01", parts: [{balance: 3}], penalty: {a: "none", s: 4}, points: null, review: "A1", risk: 0.5, segment: 1.5, surcharge: "-/false", totals: {level: 0}}], qty: 1.5, scores: {exposure: "none"}, total: "true", urgent: true, verified: false}}], + [{claim: {qty: null, insured: true, city: "retail", verified: true, urgent: true, age: null, items: []}}, {claim: {age: null, bonus: 0, city: "retail", insured: true, items: [], qty: null, scores: {exposure: "retail"}, total: "true", urgent: true, verified: true}}], + [{claim: {qty: 5, insured: false, city: "DE", verified: false, urgent: false, age: 0.1, items: [{age: 99999999999999999999, openedAt: "2025-03-20", flagged: false, country: "gold", parts: [{balance: 111}, {balance: 0}]}, {age: 10, openedAt: "1990-06-15", flagged: false, country: "gold", parts: [{balance: 1000}, {balance: 3}, {balance: 0.000001}]}, {age: 100, openedAt: "2000-01-01", flagged: false, country: "retail", parts: [{balance: 1000000}, {balance: 1}]}, {age: 5, openedAt: "2030-12-31", flagged: false, country: "Oslo", parts: [{balance: 0}]}]}}, {claim: {age: 0.1, bonus: 5, city: "DE", insured: false, items: [{adjusted: false, age: 99999999999999999999, country: "gold", discount: false, fee: null, flagged: false, openedAt: "2025-03-20", parts: [{balance: 111}, {balance: 0}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 1.6666666666666666666666666667, segment: -99999999999999999999, surcharge: "gold/false", totals: {level: 5}}, {adjusted: false, age: 10, country: "gold", discount: false, fee: null, flagged: false, openedAt: "1990-06-15", parts: [{balance: 1000}, {balance: 3}, {balance: 0.000001}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 1.6666666666666666666666666667, segment: -10, surcharge: "gold/false", totals: {level: 5}}, {adjusted: false, age: 100, country: "retail", discount: false, fee: null, flagged: false, openedAt: "2000-01-01", parts: [{balance: 1000000}, {balance: 1}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 1.6666666666666666666666666667, segment: -100, surcharge: "retail/false", totals: {level: 5}}, {adjusted: false, age: 5, country: "Oslo", discount: true, fee: null, flagged: false, openedAt: "2030-12-31", parts: [{balance: 0}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 1.6666666666666666666666666667, segment: -5, surcharge: "Oslo/false", totals: {level: 5}}], qty: 5, scores: {exposure: "ok"}, total: "DE", urgent: false, verified: false}}], + [{claim: {qty: 5, insured: true, city: "gold", verified: true, urgent: null, age: null, items: []}}, {claim: {age: null, bonus: 5, city: "gold", insured: true, items: [], qty: 5, scores: {exposure: "gold"}, total: "true", urgent: null, verified: true}}], + [{claim: {qty: 0.000001, insured: false, city: "VIP", verified: false, urgent: true, age: 18, items: []}}, {claim: {age: 18, bonus: 0.00, city: "VIP", insured: false, items: [], qty: 0.000001, scores: {exposure: "ok"}, total: "VIP", urgent: true, verified: false}}], + [{claim: {qty: 5, insured: true, city: "gold", verified: false, urgent: true, age: -0, items: [{age: 1e3, openedAt: "2025-03-20", flagged: true, country: "a", parts: [{balance: 250}, {balance: 0.5}, {balance: 123456789.123}]}, {age: 0, openedAt: "2030-12-31", flagged: true, country: " pad ", parts: [{balance: 10}, {balance: 65}, {balance: 65}]}]}}, {claim: {age: 0, bonus: 5, city: "gold", insured: true, items: [{adjusted: false, age: 1000, country: "a", discount: false, fee: null, flagged: true, openedAt: "2025-03-20", parts: [{balance: 250}, {balance: 0.5}, {balance: 123456789.123}], penalty: {a: "gold", s: 4}, points: null, review: "gold", risk: 1.6666666666666666666666666667, segment: 0, surcharge: "a/false", totals: {grade: true, level: 0}}, {adjusted: false, age: 0, country: " pad ", discount: false, fee: true, flagged: true, openedAt: "2030-12-31", parts: [{balance: 10}, {balance: 65}, {balance: 65}], penalty: {a: "gold", s: 4}, points: 0.5, review: "gold", risk: 1.6666666666666666666666666667, segment: 0, surcharge: " pad /false", totals: {grade: true, level: 0}}], qty: 5, scores: {exposure: "gold"}, total: "true", urgent: true, verified: false}}], + [{claim: {qty: 1.5, insured: true, city: "a", verified: true, urgent: false, age: 0.1, items: [{age: 10, openedAt: "2030-12-31", flagged: false, country: "VIP", parts: [{balance: -0.5}]}, {age: 0, openedAt: "2025-03-20T10:15:30Z", flagged: true, country: "VIP", parts: []}], extraField: 1}}, {claim: {age: 0.1, bonus: 1.5, city: "a", extraField: 1, insured: true, items: [{adjusted: false, age: 10, country: "VIP", discount: true, fee: null, flagged: false, openedAt: "2030-12-31", parts: [{balance: -0.5}], penalty: {a: "a", s: 1}, points: null, review: "A1", risk: 0.5, segment: 1.5, surcharge: "VIP/false", totals: {level: 10}}, {adjusted: false, age: 0, country: "VIP", discount: true, fee: null, flagged: true, openedAt: "2025-03-20T10:15:30Z", parts: [], penalty: {a: "a", s: 1}, points: null, review: "a", risk: 0.5, segment: 0, surcharge: "VIP/false", totals: {level: 0.1}}], qty: 1.5, scores: {exposure: "a"}, total: "true", urgent: false, verified: true}}], + [{claim: {qty: null, insured: false, city: "DE", verified: true, urgent: false, items: [{age: null, openedAt: "2025-03-20T10:15:30Z", flagged: false, country: "12", parts: [{balance: 65}, {balance: 0.000001}]}, {openedAt: "2000-01-01", country: "Zed", parts: []}]}}, {claim: {bonus: 0, city: "DE", insured: false, items: [{adjusted: true, age: null, country: "12", discount: false, fee: null, flagged: false, openedAt: "2025-03-20T10:15:30Z", parts: [{balance: 65}, {balance: 0.000001}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 0, segment: -0, surcharge: "12/true", totals: {level: 0}}, {adjusted: true, country: "Zed", discount: true, fee: null, openedAt: "2000-01-01", parts: [], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 0, segment: -0, surcharge: "Zed/true", totals: {level: 0}}], qty: null, scores: {exposure: "ok"}, total: "DE", urgent: false, verified: true}}], + [{claim: {qty: -0, insured: true, city: "a-b-c", verified: false, urgent: true, age: 100, items: []}}, {claim: {age: 100, bonus: 0, city: "a-b-c", insured: true, items: [], qty: 0, scores: {exposure: "a-b-c"}, total: "true", urgent: true, verified: false}}], + [{claim: {qty: 2, insured: false, city: "VIP", verified: true, urgent: true, age: 1, items: [{age: 1.5, openedAt: "2000-01-01", flagged: true, country: "a-b-c", parts: [{balance: 0.5}]}, {age: 0.5, openedAt: "2030-12-31", flagged: true, country: "é ü", parts: [{balance: 0.5}, {balance: 99999999999999999999}, {balance: -0.5}]}, {age: 99999999999999999999, openedAt: "2024-01-01", flagged: false, country: "low", parts: [{balance: -1}, {balance: 123456789.123}, {balance: 1.5}]}], extraField: "x"}}, {claim: {age: 1, bonus: 2, city: "VIP", extraField: "x", insured: false, items: [{adjusted: true, age: 1.5, country: "a-b-c", discount: true, fee: null, flagged: true, openedAt: "2000-01-01", parts: [{balance: 0.5}], penalty: {a: "VIP", s: 2}, points: null, review: "VIP", risk: 0.6666666666666666666666666667, segment: 0, surcharge: "a-b-c/true", totals: {level: 1}}, {adjusted: true, age: 0.5, country: "é ü", discount: false, fee: null, flagged: true, openedAt: "2030-12-31", parts: [{balance: 0.5}, {balance: 99999999999999999999}, {balance: -0.5}], penalty: {a: "VIP", s: 2}, points: null, review: "VIP", risk: 0.6666666666666666666666666667, segment: 0, surcharge: "é ü/true", totals: {level: 1}}, {adjusted: false, age: 99999999999999999999, country: "low", discount: false, fee: null, flagged: false, openedAt: "2024-01-01", parts: [{balance: -1}, {balance: 123456789.123}, {balance: 1.5}], penalty: {a: "VIP", s: 2}, points: null, review: "VIP", risk: 0.6666666666666666666666666667, segment: -99999999999999999999, surcharge: "low/false", totals: {level: 2}}], qty: 2, scores: {exposure: "ok"}, total: "VIP", urgent: true, verified: true}}], + [{claim: {qty: true, insured: false, city: "12", verified: true, urgent: false, age: 1, items: [{age: 1, openedAt: "2024-01-01", flagged: false, country: "x-y", parts: [{balance: 10}, {balance: 3}, {balance: 0.25}]}, {age: -1, openedAt: "2025-03-20T10:15:30Z", flagged: true, country: "DE", parts: [{balance: -0}, {balance: 1000000}, {balance: 0.5}]}, {age: 0.1, openedAt: "1990-06-15", flagged: false, country: "ok", parts: [{balance: 99999999999999999999}, {balance: 0.5}, {balance: 5}]}]}}, "!error: InputValidationFailed"], + [{claim: {qty: 2.50, insured: false, city: "retail", verified: true, urgent: true, age: null, items: [{age: 3, openedAt: "2024-02-29", country: "Oslo", parts: []}]}}, {claim: {age: null, bonus: 2.50, city: "retail", insured: false, items: [{adjusted: false, age: 3, country: "Oslo", discount: true, fee: null, openedAt: "2024-02-29", parts: [], penalty: {a: "retail", s: 2}, points: null, review: "retail", risk: 0.8333333333333333333333333333, segment: -3, surcharge: "Oslo/false", totals: {level: 2.50}}], qty: 2.50, scores: {exposure: "ok"}, total: "retail", urgent: true, verified: true}}], + [{claim: {qty: 0, insured: false, city: "DE", verified: true, urgent: true, age: 65, items: [{age: 123456789.123, openedAt: "2024-02-29", flagged: true, country: "A1", parts: [{balance: 1.5}]}, {age: 5, openedAt: "1990-06-15", flagged: false, country: "ok", parts: [{balance: 65}, {balance: 65}]}, {age: 0, openedAt: "2000-01-01", flagged: true, country: "VIP", parts: [{balance: 0.000001}, {balance: 18}, {balance: 2}]}, {age: 1, openedAt: "2025-03-20", flagged: true, country: "DE", parts: [{balance: 2}, {balance: 0}]}]}}, {claim: {age: 65, bonus: 0, city: "DE", insured: false, items: [{adjusted: true, age: 123456789.123, country: "A1", discount: true, fee: null, flagged: true, openedAt: "2024-02-29", parts: [{balance: 1.5}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 0, segment: 0, surcharge: "A1/true", totals: {level: 65}}, {adjusted: false, age: 5, country: "ok", discount: false, fee: null, flagged: false, openedAt: "1990-06-15", parts: [{balance: 65}, {balance: 65}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 0, segment: -5, surcharge: "ok/false", totals: {level: 0}}, {adjusted: true, age: 0, country: "VIP", discount: false, fee: null, flagged: true, openedAt: "2000-01-01", parts: [{balance: 0.000001}, {balance: 18}, {balance: 2}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 0, segment: 0, surcharge: "VIP/true", totals: {level: 65}}, {adjusted: true, age: 1, country: "DE", discount: true, fee: null, flagged: true, openedAt: "2025-03-20", parts: [{balance: 2}, {balance: 0}], penalty: {a: "DE", s: 2}, points: null, review: "DE", risk: 0, segment: 0, surcharge: "DE/true", totals: {level: 65}}], qty: 0, scores: {exposure: "ok"}, total: "DE", urgent: true, verified: true}}], + [{claim: {qty: 3, insured: true, city: "A1", verified: true, urgent: false, age: 65, items: [{age: -0, openedAt: "2025-03-20", flagged: false, country: "", parts: [{balance: 1.5}, {balance: 250}]}]}}, {claim: {age: 65, bonus: 3, city: "A1", insured: true, items: [{adjusted: false, age: 0, country: "", discount: false, fee: false, flagged: false, openedAt: "2025-03-20", parts: [{balance: 1.5}, {balance: 250}], penalty: {a: "A1", s: 2}, points: 0.5, review: "A1", risk: 1, segment: 3, surcharge: "/false", totals: {grade: false, level: 0}}], qty: 3, scores: {exposure: "A1"}, total: "true", urgent: false, verified: true}}], + ], +} + +// seed 343500 (attempt 0) +{ + name: "b 36: tenant/loans/payments: 3 expression, 5 match, 3 table; 7 root, 4 per-member, 2 top-level computed", + policy: { + models: {tenant: {balance: "number", plan: "string(basic|plus|premium|trial)", status: "string(open|closed|pending)", openedAt: "date?", income: "number", score: "number?", loans: "loan[]"}, loan: {price: "number", qty: "number", code: "string", sku: "string", payments: "payment[]"}, payment: {limit: "number?", openedAt: "date"}}, + blocks: [ + {match: "loan.penalty", arms: [["loan.sku in ['retail', 'gold']", "-((avg(map(tenant.loans, #.price)) ?? 0))"], ["contains(['low', 'A1', ''], loan.code)", "(loan.code in ['retail', 'x'] ? (tenant.balance - loan.price) : (avg(map(tenant.loans, #.price)) ?? 0))"], ["(tenant.balance > 1 ? loan.sku : 'x') != 'ok'", "sum(map(tenant.loans, 5))"], ["(tenant.openedAt ?? d('2025-01-01')) < d('2000-06-30')", "((tenant.score ?? 0) * (tenant.score ?? 0))"], ["", "(tenant.score ?? 0)"]]}, + {table: "t6", inputs: ["(tenant.openedAt ?? d('2025-01-01'))"], outputs: ["net", "points"], rules: [ + ["", "5", "(tenant.openedAt ?? d('2025-01-01')).isBefore(d('2024-01-01'), 'month')"], + [">= d('2000-06-30')", "(tenant.score ?? 0)", "(tenant.band ?? 0) <= tenant.income"], + ["> d('2025-03-20')", "tenant.balance", "(tenant.scores.eligible ?? false)"], + ["< d('2025-01-01')", "(tenant.score ?? 0)", "(tenant.scores.eligible ?? false)"], + ["> d('2024-01-01')", "(tenant.band ?? 0)", "len(tenant.ok) > 3"], + ["< d('2000-06-30')", "(tenant.band ?? 0)", "(tenant.scores.eligible ?? false)"], + ["", "tenant.income", "(tenant.scores.eligible ?? false)"], + ]}, + {match: "loan.weighted", arms: [["none(loan.payments, ((#.limit ?? 0) == 0.5 and (#.limit ?? 0) == 0))", "((tenant.scores.eligible ?? false) ? (tenant.score ?? 0) : 1000)"], ["loan.price in (45..137)", "sum([tenant.income, loan.penalty, tenant.income])"], ["matches(loan.sku, '^[A-Z]')", "(len(filter(loan.payments, ((#.limit ?? 0) <= 1 or 50 == 250)))) / (abs(-((tenant.score ?? 0))) + 1)"], ["contains(loan.sku, 'high')", "(tenant.score ?? 0)"], ["", "loan.penalty"]]}, + {table: "t2", inputs: ["tenant.status"], outputs: ["tenant.summary", "tenant.scores.eligible"], rules: [ + ["'closed'", "'ok'", "0 > 0.25"], + ["'closed'", "`${'ok'}/${(tenant.score ?? 0) <= 0}`", ""], + ["'open'", "'x'", "tenant.balance <= 250"], + ["'open', 'closed'", "string((tenant.score ?? 0))", ""], + ["", "'x'", "(tenant.score ?? 0) == 1"], + ]}, + {expression: "tenant.totals.capped", value: "filter(tenant.loans, (#.qty > 18 or #.penalty <= 1))"}, + {match: "tenant.grade", arms: [["(tenant.score ?? 0) != 50", "'A1'"], ["isNumeric((split(tenant.ok, '-')[0] ?? 'none'))", "'retail'"], ["(tenant.summary ?? '') in ['ok', 'gold']", "string(tenant.balance)"], ["tenant.scores.eligible != null", "(tenant.openedAt ?? d('2025-01-01')).format('%Y')"], ["", "tenant.ok"]]}, + {match: "tenant.ok", arms: [["tenant.balance in [33..87]", "((tenant.scores.eligible ?? false) ? (tenant.summary ?? '') : (tenant.summary ?? ''))"], ["(tenant.score ?? 0) in [36..233]", "string((tenant.openedAt ?? d('2025-01-01')).diff(d('2025-01-01'), 'day'))"], ["(tenant.status != 'pending' or tenant.income == 250)", "(`${(tenant.summary ?? '')}/${(tenant.scores.eligible ?? false)}` + '-' + string((tenant.scores.eligible ?? false)))"], ["not (contains((tenant.summary ?? ''), 'VIP'))", "string(tenant.score == null)"], ["", "`${'ok'}/${(tenant.scores.eligible ?? false)}`"]]}, + {expression: "tenant.share", value: "(tenant.summary ?? '') == 'none'"}, + {expression: "loan.flags.level", value: "tenant.balance < loan.qty"}, + {match: "loan.bonus", arms: [["(tenant.openedAt ?? d('2025-01-01')) > d('2025-03-20')", "loan.code"], ["(tenant.openedAt ?? d('2025-01-01')).isSame(d('2025-01-01'), 'year')", "loan.sku"], ["tenant.score == null", "`${tenant.ok}/${len(filter(loan.payments, ((#.limit ?? 0) == 10 and (#.limit ?? 0) == 1)))}`"], ["", "((points ?? false) ? (tenant.summary ?? '') : loan.sku)"]]}, + {table: "t5", inputs: [null], outputs: ["tenant.band"], rules: [ + ["isNumeric(tenant.ok)", "0.5"], + ["(tenant.score ?? 0) < 0", "ceil(tenant.income)"], + ["(tenant.score ?? 0) >= tenant.balance", "tenant.income"], + ["", "3"], + ]}, + ], + }, + cases: [ + [{tenant: {balance: -0, plan: "premium", status: "open", income: -0, score: 0, loans: [{price: 100, qty: 2.50, code: "high", sku: "12", payments: [{limit: 123456789.123, openedAt: "2000-01-01"}, {limit: null, openedAt: "2024-01-01"}]}, {price: 2.50, qty: 99999999999999999999, code: "high", sku: "A1", payments: [{limit: 5, openedAt: "1990-06-15"}, {openedAt: "2024-01-01"}]}]}}, {net: 5, points: false, tenant: {balance: 0, grade: "A1", income: 0, loans: [{bonus: "12", code: "high", flags: {level: true}, payments: [{limit: 123456789.123, openedAt: "2000-01-01"}, {limit: null, openedAt: "2024-01-01"}], penalty: 10, price: 100, qty: 2.50, sku: "12", weighted: 0}, {bonus: "A1", code: "high", flags: {level: true}, payments: [{limit: 5, openedAt: "1990-06-15"}, {openedAt: "2024-01-01"}], penalty: 10, price: 2.50, qty: 99999999999999999999, sku: "A1", weighted: 0}], ok: "x/true-true", plan: "premium", score: 0, scores: {eligible: true}, share: false, status: "open", summary: "x", totals: {capped: [{bonus: "A1", code: "high", flags: {level: true}, payments: [{limit: 5, openedAt: "1990-06-15"}, {openedAt: "2024-01-01"}], penalty: 10, price: 2.50, qty: 99999999999999999999, sku: "A1", weighted: 0}]}}}], + [{tenant: {balance: 5, plan: "plus", status: "open", openedAt: "2024-02-29", income: 1, score: 50, loans: [{price: 3, qty: 250, code: "Oslo", sku: "A1", payments: [{limit: 10, openedAt: "2025-03-20T10:15:30Z"}]}, {price: 1, qty: 50, code: "high", sku: "Oslo", payments: [{limit: 1, openedAt: "2025-03-20"}, {limit: 179, openedAt: "2024-02-29"}]}, {price: -1, qty: 0.1, code: "Zed", sku: "US", payments: []}, {price: 5, qty: 18, code: "O'Neil", sku: "O'Neil", payments: [{limit: -0.5, openedAt: "2030-12-31"}, {limit: 2, openedAt: "1990-06-15"}]}, {price: 50, qty: 50, code: "日本", sku: "ok", payments: [{limit: 1000, openedAt: "2024-01-01"}]}], extraField: "x"}}, {net: 5, points: false, tenant: {balance: 5, extraField: "x", grade: "2024", income: 1, loans: [{bonus: "A1", code: "Oslo", flags: {level: true}, payments: [{limit: 10, openedAt: "2025-03-20T10:15:30Z"}], penalty: 25, price: 3, qty: 250, sku: "A1", weighted: 50}, {bonus: "Oslo", code: "high", flags: {level: true}, payments: [{limit: 1, openedAt: "2025-03-20"}, {limit: 179, openedAt: "2024-02-29"}], penalty: 25, price: 1, qty: 50, sku: "Oslo", weighted: 50}, {bonus: "US", code: "Zed", flags: {level: false}, payments: [], penalty: 25, price: -1, qty: 0.1, sku: "US", weighted: 50}, {bonus: "O'Neil", code: "O'Neil", flags: {level: true}, payments: [{limit: -0.5, openedAt: "2030-12-31"}, {limit: 2, openedAt: "1990-06-15"}], penalty: 25, price: 5, qty: 18, sku: "O'Neil", weighted: 50}, {bonus: "ok", code: "日本", flags: {level: true}, payments: [{limit: 1000, openedAt: "2024-01-01"}], penalty: 50, price: 50, qty: 50, sku: "ok", weighted: 50}], ok: "-307", openedAt: "2024-02-29", plan: "plus", score: 50, scores: {eligible: true}, share: false, status: "open", summary: "x", totals: {capped: [{bonus: "A1", code: "Oslo", flags: {level: true}, payments: [{limit: 10, openedAt: "2025-03-20T10:15:30Z"}], penalty: 25, price: 3, qty: 250, sku: "A1", weighted: 50}, {bonus: "Oslo", code: "high", flags: {level: true}, payments: [{limit: 1, openedAt: "2025-03-20"}, {limit: 179, openedAt: "2024-02-29"}], penalty: 25, price: 1, qty: 50, sku: "Oslo", weighted: 50}, {bonus: "ok", code: "日本", flags: {level: true}, payments: [{limit: 1000, openedAt: "2024-01-01"}], penalty: 50, price: 50, qty: 50, sku: "ok", weighted: 50}]}}}], + [{tenant: {balance: 18, plan: "premium", status: "pending", openedAt: "1990-06-15", income: 1, score: 250, loans: [{price: 99.99, qty: 1000000, code: "ok", sku: "A1", payments: [{limit: 99.99, openedAt: "2024-02-29"}, {limit: 99.99, openedAt: "2024-02-29"}]}]}}, {net: 5, points: true, tenant: {balance: 18, grade: "A1", income: 1, loans: [{bonus: "x", code: "ok", flags: {level: true}, payments: [{limit: 99.99, openedAt: "2024-02-29"}, {limit: 99.99, openedAt: "2024-02-29"}], penalty: 5, price: 99.99, qty: 1000000, sku: "A1", weighted: 1000}], ok: "false", openedAt: "1990-06-15", plan: "premium", score: 250, scores: {eligible: false}, share: false, status: "pending", summary: "x", totals: {capped: [{bonus: "x", code: "ok", flags: {level: true}, payments: [{limit: 99.99, openedAt: "2024-02-29"}, {limit: 99.99, openedAt: "2024-02-29"}], penalty: 5, price: 99.99, qty: 1000000, sku: "A1", weighted: 1000}]}}}], + [{tenant: {balance: 18, plan: "trial", status: "open", openedAt: "2000-01-01", income: 10, score: 65, loans: [{price: 1, qty: 99.99, code: "-", sku: "US", payments: [{limit: 7.25, openedAt: "1990-06-15"}]}, {price: 50, qty: 1, code: "x", sku: "high", payments: []}, {price: 0, qty: 0.5, code: "abc", sku: "Zed", payments: [{limit: 0.000001, openedAt: "1990-06-15"}]}, {price: 123456789.123, qty: 7.25, code: "Zed", sku: "high", payments: [{limit: 18, openedAt: "1990-06-15"}, {limit: 0.5, openedAt: "2025-03-20"}]}, {price: 1, qty: 100, code: "US", sku: "a", payments: [{limit: 18, openedAt: "2024-01-01"}, {limit: 7.25, openedAt: "2030-12-31"}]}, {price: 0.25, qty: 1000000, code: "ok", sku: "high", payments: [{limit: 1000, openedAt: "2024-01-01"}, {limit: 1e3, openedAt: "2025-03-20"}]}, {price: 0, qty: 2, code: "a", sku: "", payments: [{limit: 18, openedAt: "2025-03-20"}, {limit: 250, openedAt: "2025-03-20"}]}, {price: 0.000001, qty: 0.5, code: "ok", sku: "retail", payments: []}, {price: 0.25, qty: 0.25, code: "a-b-c", sku: "high", payments: [{limit: 250, openedAt: "2025-03-20T10:15:30Z"}, {limit: 1000000, openedAt: "2030-12-31"}]}], extraField: {nested: true}}}, {net: 5, points: true, tenant: {balance: 18, extraField: {nested: true}, grade: "A1", income: 10, loans: [{bonus: "x", code: "-", flags: {level: true}, payments: [{limit: 7.25, openedAt: "1990-06-15"}], penalty: 45, price: 1, qty: 99.99, sku: "US", weighted: 65}, {bonus: "x", code: "x", flags: {level: false}, payments: [], penalty: 45, price: 50, qty: 1, sku: "high", weighted: 65}, {bonus: "x", code: "abc", flags: {level: false}, payments: [{limit: 0.000001, openedAt: "1990-06-15"}], penalty: 45, price: 0, qty: 0.5, sku: "Zed", weighted: 65}, {bonus: "x", code: "Zed", flags: {level: false}, payments: [{limit: 18, openedAt: "1990-06-15"}, {limit: 0.5, openedAt: "2025-03-20"}], penalty: 45, price: 123456789.123, qty: 7.25, sku: "high", weighted: 65}, {bonus: "x", code: "US", flags: {level: true}, payments: [{limit: 18, openedAt: "2024-01-01"}, {limit: 7.25, openedAt: "2030-12-31"}], penalty: 45, price: 1, qty: 100, sku: "a", weighted: 65}, {bonus: "x", code: "ok", flags: {level: true}, payments: [{limit: 1000, openedAt: "2024-01-01"}, {limit: 1000, openedAt: "2025-03-20"}], penalty: 45, price: 0.25, qty: 1000000, sku: "high", weighted: 65}, {bonus: "x", code: "a", flags: {level: false}, payments: [{limit: 18, openedAt: "2025-03-20"}, {limit: 250, openedAt: "2025-03-20"}], penalty: 45, price: 0, qty: 2, sku: "", weighted: 65}, {bonus: "x", code: "ok", flags: {level: false}, payments: [], penalty: -13717426.847000111111111111111, price: 0.000001, qty: 0.5, sku: "retail", weighted: 65}, {bonus: "x", code: "a-b-c", flags: {level: false}, payments: [{limit: 250, openedAt: "2025-03-20T10:15:30Z"}, {limit: 1000000, openedAt: "2030-12-31"}], penalty: 45, price: 0.25, qty: 0.25, sku: "high", weighted: 65}], ok: "-9132", openedAt: "2000-01-01", plan: "trial", score: 65, scores: {eligible: true}, share: false, status: "open", summary: "x", totals: {capped: [{bonus: "x", code: "-", flags: {level: true}, payments: [{limit: 7.25, openedAt: "1990-06-15"}], penalty: 45, price: 1, qty: 99.99, sku: "US", weighted: 65}, {bonus: "x", code: "US", flags: {level: true}, payments: [{limit: 18, openedAt: "2024-01-01"}, {limit: 7.25, openedAt: "2030-12-31"}], penalty: 45, price: 1, qty: 100, sku: "a", weighted: 65}, {bonus: "x", code: "ok", flags: {level: true}, payments: [{limit: 1000, openedAt: "2024-01-01"}, {limit: 1000, openedAt: "2025-03-20"}], penalty: 45, price: 0.25, qty: 1000000, sku: "high", weighted: 65}, {bonus: "x", code: "ok", flags: {level: false}, payments: [], penalty: -13717426.847000111111111111111, price: 0.000001, qty: 0.5, sku: "retail", weighted: 65}]}}}], + [{tenant: {balance: 65, plan: "premium", status: "closed", openedAt: "2025-03-20T10:15:30Z", income: 1e3, score: 62, loans: [], extraField: {nested: true}}}, {net: 5, points: false, tenant: {balance: 65, extraField: {nested: true}, grade: "A1", income: 1000, loans: [], ok: "ok", openedAt: "2025-03-20T10:15:30Z", plan: "premium", score: 62, scores: {eligible: false}, share: false, status: "closed", summary: "ok", totals: {capped: []}}}], + [{tenant: {balance: -0, plan: "plus", status: "open", openedAt: "2025-03-20", income: 0, score: 7.25, loans: [{price: 1, qty: 1, code: "VIP", sku: "-", payments: [{limit: 5, openedAt: "2000-01-01"}, {limit: 1, openedAt: "2030-12-31"}]}]}}, {net: 5, points: false, tenant: {balance: 0, grade: "A1", income: 0, loans: [{bonus: "-", code: "VIP", flags: {level: true}, payments: [{limit: 5, openedAt: "2000-01-01"}, {limit: 1, openedAt: "2030-12-31"}], penalty: 5, price: 1, qty: 1, sku: "-", weighted: 7.25}], ok: "x/true-true", openedAt: "2025-03-20", plan: "plus", score: 7.25, scores: {eligible: true}, share: false, status: "open", summary: "x", totals: {capped: []}}}], + [{tenant: {balance: -0, plan: "basic", status: "open", openedAt: "2025-03-20T10:15:30Z", income: 0, score: 5, loans: []}}, {net: 5, points: false, tenant: {balance: 0, grade: "A1", income: 0, loans: [], ok: "x/true-true", openedAt: "2025-03-20T10:15:30Z", plan: "basic", score: 5, scores: {eligible: true}, share: false, status: "open", summary: "x", totals: {capped: []}}}], + [{tenant: {balance: 1, plan: "basic", status: "pending", openedAt: "2024-01-01", income: 50, loans: [{price: 50, qty: -0.5, code: "a", sku: "A1", payments: [{openedAt: "2025-03-20T10:15:30Z"}, {limit: null, openedAt: "2024-02-29"}]}, {price: 0.1, qty: 10, code: "ok", sku: "é ü", payments: [{openedAt: "2024-01-01"}, {limit: -0.5, openedAt: "2024-01-01"}]}]}}, {net: 5, points: false, tenant: {balance: 1, grade: "A1", income: 50, loans: [{bonus: "true/0", code: "a", flags: {level: false}, payments: [{openedAt: "2025-03-20T10:15:30Z"}, {limit: null, openedAt: "2024-02-29"}], penalty: 10, price: 50, qty: -0.5, sku: "A1", weighted: 1000}, {bonus: "true/0", code: "ok", flags: {level: true}, payments: [{openedAt: "2024-01-01"}, {limit: -0.5, openedAt: "2024-01-01"}], penalty: 10, price: 0.1, qty: 10, sku: "é ü", weighted: 1000}], ok: "true", openedAt: "2024-01-01", plan: "basic", scores: {eligible: false}, share: false, status: "pending", summary: "x", totals: {capped: []}}}], + [{tenant: {balance: 18, plan: "basic", status: "closed", openedAt: "2000-01-01", income: 0.5, score: 1000, loans: [{price: 55, qty: 0.1, code: "3.5", sku: "ok", payments: [{limit: -0, openedAt: "1990-06-15"}, {limit: 10, openedAt: "2024-02-29"}]}]}}, {net: 5, points: true, tenant: {balance: 18, grade: "A1", income: 0.5, loans: [{bonus: "ok", code: "3.5", flags: {level: false}, payments: [{limit: 0, openedAt: "1990-06-15"}, {limit: 10, openedAt: "2024-02-29"}], penalty: 1000000, price: 55, qty: 0.1, sku: "ok", weighted: 1000}], ok: "ok/false-false", openedAt: "2000-01-01", plan: "basic", score: 1000, scores: {eligible: false}, share: false, status: "closed", summary: "ok", totals: {capped: []}}}], + [{tenant: {balance: -0.5, plan: "trial", status: "pending", openedAt: "2025-03-20T10:15:30Z", income: [1], score: 2, loans: [{price: -0, qty: -0.01, code: "日本", sku: "VIP", payments: [{limit: 18, openedAt: "2000-01-01"}]}, {price: 1000000, qty: 1, code: "x", sku: "a", payments: [{limit: 1, openedAt: "2024-02-29"}, {limit: 50, openedAt: "1990-06-15"}, {limit: 99999999999999999999, openedAt: "1990-06-15"}]}]}}, "!error: InputValidationFailed"], + [{tenant: {balance: -500, plan: "basic", status: "closed", openedAt: "2024-01-01", income: 99.99, score: 50, loans: [{price: 1, qty: 0.5, code: "x", sku: "none", payments: []}, {price: 99.99, qty: 0.5, code: "gold", sku: "retail", payments: [{limit: 1e3, openedAt: "2024-02-29"}, {limit: 1e3, openedAt: "2000-01-01"}]}, {price: 2.50, qty: 1e3, code: "low", sku: "US", payments: [{limit: 0, openedAt: "1990-06-15"}, {limit: 0.5, openedAt: "2024-02-29"}]}]}}, {net: 5, points: false, tenant: {balance: -500, grade: "-500", income: 99.99, loans: [{bonus: "none", code: "x", flags: {level: true}, payments: [], penalty: 15, price: 1, qty: 0.5, sku: "none", weighted: 1000}, {bonus: "retail", code: "gold", flags: {level: true}, payments: [{limit: 1000, openedAt: "2024-02-29"}, {limit: 1000, openedAt: "2000-01-01"}], penalty: -34.496666666666666666666666667, price: 99.99, qty: 0.5, sku: "retail", weighted: 1000}, {bonus: "US", code: "low", flags: {level: true}, payments: [{limit: 0, openedAt: "1990-06-15"}, {limit: 0.5, openedAt: "2024-02-29"}], penalty: 34.496666666666666666666666667, price: 2.50, qty: 1000, sku: "US", weighted: 1000}], ok: "-366", openedAt: "2024-01-01", plan: "basic", score: 50, scores: {eligible: false}, share: false, status: "closed", summary: "ok", totals: {capped: [{bonus: "retail", code: "gold", flags: {level: true}, payments: [{limit: 1000, openedAt: "2024-02-29"}, {limit: 1000, openedAt: "2000-01-01"}], penalty: -34.496666666666666666666666667, price: 99.99, qty: 0.5, sku: "retail", weighted: 1000}, {bonus: "US", code: "low", flags: {level: true}, payments: [{limit: 0, openedAt: "1990-06-15"}, {limit: 0.5, openedAt: "2024-02-29"}], penalty: 34.496666666666666666666666667, price: 2.50, qty: 1000, sku: "US", weighted: 1000}]}}}], + [{tenant: {balance: 0.5, plan: "trial", status: "closed", income: 5, score: 1, loans: [{price: 18, qty: 18, code: "a", sku: "US", payments: [{openedAt: "2025-03-20T10:15:30Z"}, {limit: null, openedAt: "2025-03-20T10:15:30Z"}]}, {price: 0.1, qty: 1, code: "ok", sku: "-", payments: [{limit: 1, openedAt: "2025-03-20T10:15:30Z"}, {openedAt: "2025-03-20T10:15:30Z"}, {limit: null, openedAt: "2024-01-01"}]}]}}, {net: 5, points: false, tenant: {balance: 0.5, grade: "A1", income: 5, loans: [{bonus: "US", code: "a", flags: {level: true}, payments: [{openedAt: "2025-03-20T10:15:30Z"}, {limit: null, openedAt: "2025-03-20T10:15:30Z"}], penalty: 10, price: 18, qty: 18, sku: "US", weighted: 1000}, {bonus: "-", code: "ok", flags: {level: true}, payments: [{limit: 1, openedAt: "2025-03-20T10:15:30Z"}, {openedAt: "2025-03-20T10:15:30Z"}, {limit: null, openedAt: "2024-01-01"}], penalty: 10, price: 0.1, qty: 1, sku: "-", weighted: 1000}], ok: "ok/false-false", plan: "trial", score: 1, scores: {eligible: false}, share: false, status: "closed", summary: "ok", totals: {capped: []}}}], + [{tenant: {balance: 250, plan: "basic", status: "open", openedAt: "2024-02-29", income: 50, score: 1000, loans: [{price: 1, qty: 65, code: "retail", sku: "VIP", payments: [{limit: 7.25, openedAt: "2024-01-01"}, {limit: -1, openedAt: "1990-06-15"}]}, {price: 99.99, qty: 0, code: "ok", sku: "VIP", payments: [{openedAt: "2025-03-20T10:15:30Z"}, {limit: null, openedAt: "2025-03-20T10:15:30Z"}, {openedAt: "2024-01-01"}]}, {price: 5, qty: 10, code: "gold", sku: "retail", payments: [{limit: 0.25, openedAt: "1990-06-15"}, {limit: -0, openedAt: "1990-06-15"}]}, {price: 5, qty: 0.1, code: "x", sku: "x-y", payments: [{openedAt: "1990-06-15"}, {openedAt: "2024-02-29"}]}, {price: 1, qty: 99999999999999999999, code: "-", sku: "a", payments: [{limit: -1, openedAt: "2024-02-29"}]}, {price: 1e3, qty: 18, code: "日本", sku: "x", payments: [{limit: 50, openedAt: "2030-12-31"}, {openedAt: "1990-06-15"}, {limit: 0, openedAt: "2025-03-20"}]}, {price: 7.25, qty: 0.1, code: "VIP", sku: "gold", payments: [{limit: 1000, openedAt: "2030-12-31"}, {openedAt: "1990-06-15"}]}, {price: 0.5, qty: -0, code: "US", sku: "x", payments: [{limit: 50, openedAt: "2025-03-20T10:15:30Z"}, {limit: 123456789.123, openedAt: "2030-12-31"}]}, {price: 0.25, qty: 65, code: "3.5", sku: "retail", payments: [{openedAt: "2024-02-29"}, {limit: 1, openedAt: "2030-12-31"}]}, {price: 1, qty: 2.50, code: "retail", sku: "VIP", payments: [{openedAt: "2024-01-01"}, {openedAt: "2024-01-01"}, {limit: 1, openedAt: "2000-01-01"}]}, {price: 129, qty: 0, code: "a", sku: "a", payments: [{openedAt: "2000-01-01"}, {limit: null, openedAt: "2000-01-01"}]}, {price: 99.99, qty: 273, code: "low", sku: "3.5", payments: [{openedAt: "2030-12-31"}, {limit: 1, openedAt: "2024-02-29"}]}, {price: 250, qty: 1000, code: "A1", sku: "x", payments: [{limit: -0.5, openedAt: "2000-01-01"}, {limit: 99.99, openedAt: "2025-03-20T10:15:30Z"}, {limit: 50, openedAt: "2024-01-01"}]}]}}, {net: 5, points: false, tenant: {balance: 250, grade: "A1", income: 50, loans: [{bonus: "VIP", code: "retail", flags: {level: false}, payments: [{limit: 7.25, openedAt: "2024-01-01"}, {limit: -1, openedAt: "1990-06-15"}], penalty: 65, price: 1, qty: 65, sku: "VIP", weighted: 1000}, {bonus: "VIP", code: "ok", flags: {level: false}, payments: [{openedAt: "2025-03-20T10:15:30Z"}, {limit: null, openedAt: "2025-03-20T10:15:30Z"}, {openedAt: "2024-01-01"}], penalty: 65, price: 99.99, qty: 0, sku: "VIP", weighted: 1000}, {bonus: "retail", code: "gold", flags: {level: false}, payments: [{limit: 0.25, openedAt: "1990-06-15"}, {limit: 0, openedAt: "1990-06-15"}], penalty: -123.07538461538461538461538462, price: 5, qty: 10, sku: "retail", weighted: 1000}, {bonus: "x-y", code: "x", flags: {level: false}, payments: [{openedAt: "1990-06-15"}, {openedAt: "2024-02-29"}], penalty: 65, price: 5, qty: 0.1, sku: "x-y", weighted: 1000}, {bonus: "a", code: "-", flags: {level: true}, payments: [{limit: -1, openedAt: "2024-02-29"}], penalty: 65, price: 1, qty: 99999999999999999999, sku: "a", weighted: 1000}, {bonus: "x", code: "日本", flags: {level: false}, payments: [{limit: 50, openedAt: "2030-12-31"}, {openedAt: "1990-06-15"}, {limit: 0, openedAt: "2025-03-20"}], penalty: 65, price: 1000, qty: 18, sku: "x", weighted: 1000}, {bonus: "gold", code: "VIP", flags: {level: false}, payments: [{limit: 1000, openedAt: "2030-12-31"}, {openedAt: "1990-06-15"}], penalty: -123.07538461538461538461538462, price: 7.25, qty: 0.1, sku: "gold", weighted: 1000}, {bonus: "x", code: "US", flags: {level: false}, payments: [{limit: 50, openedAt: "2025-03-20T10:15:30Z"}, {limit: 123456789.123, openedAt: "2030-12-31"}], penalty: 65, price: 0.5, qty: 0, sku: "x", weighted: 1000}, {bonus: "retail", code: "3.5", flags: {level: false}, payments: [{openedAt: "2024-02-29"}, {limit: 1, openedAt: "2030-12-31"}], penalty: -123.07538461538461538461538462, price: 0.25, qty: 65, sku: "retail", weighted: 1000}, {bonus: "VIP", code: "retail", flags: {level: false}, payments: [{openedAt: "2024-01-01"}, {openedAt: "2024-01-01"}, {limit: 1, openedAt: "2000-01-01"}], penalty: 65, price: 1, qty: 2.50, sku: "VIP", weighted: 1000}, {bonus: "a", code: "a", flags: {level: false}, payments: [{openedAt: "2000-01-01"}, {limit: null, openedAt: "2000-01-01"}], penalty: 65, price: 129, qty: 0, sku: "a", weighted: 1000}, {bonus: "3.5", code: "low", flags: {level: true}, payments: [{openedAt: "2030-12-31"}, {limit: 1, openedAt: "2024-02-29"}], penalty: 123.07538461538461538461538462, price: 99.99, qty: 273, sku: "3.5", weighted: 1000}, {bonus: "x", code: "A1", flags: {level: true}, payments: [{limit: -0.5, openedAt: "2000-01-01"}, {limit: 99.99, openedAt: "2025-03-20T10:15:30Z"}, {limit: 50, openedAt: "2024-01-01"}], penalty: 123.07538461538461538461538462, price: 250, qty: 1000, sku: "x", weighted: 1000}], ok: "x/true-true", openedAt: "2024-02-29", plan: "basic", score: 1000, scores: {eligible: true}, share: false, status: "open", summary: "x", totals: {capped: [{bonus: "VIP", code: "retail", flags: {level: false}, payments: [{limit: 7.25, openedAt: "2024-01-01"}, {limit: -1, openedAt: "1990-06-15"}], penalty: 65, price: 1, qty: 65, sku: "VIP", weighted: 1000}, {bonus: "retail", code: "gold", flags: {level: false}, payments: [{limit: 0.25, openedAt: "1990-06-15"}, {limit: 0, openedAt: "1990-06-15"}], penalty: -123.07538461538461538461538462, price: 5, qty: 10, sku: "retail", weighted: 1000}, {bonus: "a", code: "-", flags: {level: true}, payments: [{limit: -1, openedAt: "2024-02-29"}], penalty: 65, price: 1, qty: 99999999999999999999, sku: "a", weighted: 1000}, {bonus: "gold", code: "VIP", flags: {level: false}, payments: [{limit: 1000, openedAt: "2030-12-31"}, {openedAt: "1990-06-15"}], penalty: -123.07538461538461538461538462, price: 7.25, qty: 0.1, sku: "gold", weighted: 1000}, {bonus: "retail", code: "3.5", flags: {level: false}, payments: [{openedAt: "2024-02-29"}, {limit: 1, openedAt: "2030-12-31"}], penalty: -123.07538461538461538461538462, price: 0.25, qty: 65, sku: "retail", weighted: 1000}, {bonus: "3.5", code: "low", flags: {level: true}, payments: [{openedAt: "2030-12-31"}, {limit: 1, openedAt: "2024-02-29"}], penalty: 123.07538461538461538461538462, price: 99.99, qty: 273, sku: "3.5", weighted: 1000}, {bonus: "x", code: "A1", flags: {level: true}, payments: [{limit: -0.5, openedAt: "2000-01-01"}, {limit: 99.99, openedAt: "2025-03-20T10:15:30Z"}, {limit: 50, openedAt: "2024-01-01"}], penalty: 123.07538461538461538461538462, price: 250, qty: 1000, sku: "x", weighted: 1000}]}}}], + [{tenant: {balance: 1e3, plan: "basic", status: "closed", openedAt: "2024-01-01", income: 18, loans: [{price: 10, qty: 10, code: "VIP", sku: "high", payments: [{limit: null, openedAt: "1990-06-15"}, {limit: 0.5, openedAt: "2030-12-31"}, {openedAt: "2025-03-20T10:15:30Z"}]}, {price: 100, qty: 50, code: "ok", sku: "high", payments: [{limit: 0, openedAt: "2024-02-29"}, {limit: -500, openedAt: "2024-01-01"}]}, {price: 250, qty: 50, code: "x", sku: "retail", payments: [{openedAt: "2025-03-20T10:15:30Z"}, {openedAt: "2000-01-01"}]}, {price: 1000, qty: 0.5, code: "ok", sku: "A1", payments: [{openedAt: "2025-03-20T10:15:30Z"}, {limit: 10, openedAt: "2024-01-01"}, {openedAt: "2025-03-20T10:15:30Z"}]}, {price: 50, qty: 1e3, code: "x", sku: "3.5", payments: [{openedAt: "2030-12-31"}, {limit: 2.50, openedAt: "2024-02-29"}]}]}}, {net: 5, points: false, tenant: {balance: 1000, grade: "A1", income: 18, loans: [{bonus: "ok/false-false/0", code: "VIP", flags: {level: false}, payments: [{limit: null, openedAt: "1990-06-15"}, {limit: 0.5, openedAt: "2030-12-31"}, {openedAt: "2025-03-20T10:15:30Z"}], penalty: 25, price: 10, qty: 10, sku: "high", weighted: 1000}, {bonus: "ok/false-false/0", code: "ok", flags: {level: false}, payments: [{limit: 0, openedAt: "2024-02-29"}, {limit: -500, openedAt: "2024-01-01"}], penalty: 25, price: 100, qty: 50, sku: "high", weighted: 1000}, {bonus: "ok/false-false/0", code: "x", flags: {level: false}, payments: [{openedAt: "2025-03-20T10:15:30Z"}, {openedAt: "2000-01-01"}], penalty: -282, price: 250, qty: 50, sku: "retail", weighted: 1000}, {bonus: "ok/false-false/0", code: "ok", flags: {level: false}, payments: [{openedAt: "2025-03-20T10:15:30Z"}, {limit: 10, openedAt: "2024-01-01"}, {openedAt: "2025-03-20T10:15:30Z"}], penalty: 25, price: 1000, qty: 0.5, sku: "A1", weighted: 1000}, {bonus: "ok/false-false/0", code: "x", flags: {level: false}, payments: [{openedAt: "2030-12-31"}, {limit: 2.50, openedAt: "2024-02-29"}], penalty: 25, price: 50, qty: 1000, sku: "3.5", weighted: 1000}], ok: "ok/false-false", openedAt: "2024-01-01", plan: "basic", scores: {eligible: false}, share: false, status: "closed", summary: "ok", totals: {capped: [{bonus: "ok/false-false/0", code: "ok", flags: {level: false}, payments: [{limit: 0, openedAt: "2024-02-29"}, {limit: -500, openedAt: "2024-01-01"}], penalty: 25, price: 100, qty: 50, sku: "high", weighted: 1000}, {bonus: "ok/false-false/0", code: "x", flags: {level: false}, payments: [{openedAt: "2025-03-20T10:15:30Z"}, {openedAt: "2000-01-01"}], penalty: -282, price: 250, qty: 50, sku: "retail", weighted: 1000}, {bonus: "ok/false-false/0", code: "x", flags: {level: false}, payments: [{openedAt: "2030-12-31"}, {limit: 2.50, openedAt: "2024-02-29"}], penalty: 25, price: 50, qty: 1000, sku: "3.5", weighted: 1000}]}}}], + [{tenant: {balance: 5, plan: "basic", status: "open", openedAt: "2000-01-01", income: 1000, score: 100, loans: [{price: 0, qty: 0, code: "-", sku: "A1", payments: [{limit: -0.5, openedAt: "2024-01-01"}, {limit: 0, openedAt: "2025-03-20"}]}, {price: 183, qty: 1, code: "gold", sku: "none", payments: [{limit: 0.000001, openedAt: "2000-01-01"}, {limit: -0.5, openedAt: "2025-03-20"}, {limit: -1, openedAt: "1990-06-15"}]}]}}, {net: 5, points: true, tenant: {balance: 5, grade: "A1", income: 1000, loans: [{bonus: "x", code: "-", flags: {level: false}, payments: [{limit: -0.5, openedAt: "2024-01-01"}, {limit: 0, openedAt: "2025-03-20"}], penalty: 10, price: 0, qty: 0, sku: "A1", weighted: 100}, {bonus: "x", code: "gold", flags: {level: false}, payments: [{limit: 0.000001, openedAt: "2000-01-01"}, {limit: -0.5, openedAt: "2025-03-20"}, {limit: -1, openedAt: "1990-06-15"}], penalty: 10, price: 183, qty: 1, sku: "none", weighted: 100}], ok: "-9132", openedAt: "2000-01-01", plan: "basic", score: 100, scores: {eligible: true}, share: false, status: "open", summary: "x", totals: {capped: []}}}], + [{tenant: {balance: 1, plan: "plus", status: "pending", openedAt: "2025-03-20T10:15:30Z", income: 50, score: 0, loans: []}}, {net: 5, points: false, tenant: {balance: 1, grade: "A1", income: 50, loans: [], ok: "false", openedAt: "2025-03-20T10:15:30Z", plan: "plus", score: 0, scores: {eligible: false}, share: false, status: "pending", summary: "x", totals: {capped: []}}}], + ], +} + +// seed 343600 (attempt 0) +{ + name: "b 37: claim/items + report: 1 assertion, 4 expression, 2 match, 2 table; 4 root, 1 per-member, 1 top-level computed", + policy: { + models: {claim: {limit: "number", dueDate: "date", channel: "string", status: "string(open|closed|pending)?", since: "date?", items: "item[]", report: "creditReport"}, item: {balance: "number", status: "string(open|closed|pending)", insured: "boolean"}, creditReport: {age: "number?", urgent: "boolean"}}, + blocks: [ + {expression: "surcharge", value: "claim.report.age"}, + {table: "t3", inputs: ["claim.limit", "claim.report.segment", "(min(map(claim.items, #.balance)) ?? 0)"], outputs: ["claim.flag", "claim.net[]"], rules: [ + [">= 0.5", "$ != 'VIP'", "", "", "claim.status != null"], + ["< 50", "'low', 'gold'", "", "(claim.report.age ?? 0)", "claim.report.weighted"], + ["< 10", "'low'", "< 1.5", "claim.limit", "claim.report.urgent"], + ]}, + {match: "creditReport.segment", arms: [["some(claim.items, #.balance != #.balance)", "claim.channel"], ["(claim.status ?? '') in ['pending', 'open']", "(creditReport.urgent ? claim.channel : claim.channel)"], ["isNumeric(claim.channel)", "(creditReport.urgent ? claim.channel : 'gold')"], ["none(claim.items, #.status == 'closed')", "claim.channel"], ["", "claim.channel"]]}, + {table: "t4", inputs: [null, "creditReport.urgent"], outputs: ["creditReport.exposure[]", "creditReport.scores.review", "creditReport.capped"], rules: [ + ["len(creditReport.segment) > 1", "true", "claim.limit", "(creditReport.age ?? 0)", "claim.channel"], + ["(claim.flag ?? 0) >= claim.limit", "false", "(claim.flag ?? 0)", "(claim.flag ?? 0)", "creditReport.segment"], + ]}, + {expression: "claim.risk", value: "(claim.report.rank * (claim.report.age ?? 0))"}, + {match: "creditReport.rank", arms: [["none(claim.items, (#.insured and #.insured))", "(creditReport.age ?? 0)"], ["", "(claim.limit + (creditReport.age ?? 0))"]]}, + {assertion: "creditReport.weighted", conditions: [["and", "claim.limit >= claim.limit", 1], ["or", "(isNumeric(creditReport.segment) and claim.limit < (creditReport.age ?? 0))", 0], ["and", "claim.channel == 'high'", 1], ["and", "(claim.since != null and (creditReport.age ?? 0) <= (creditReport.age ?? 0))", 0]]}, + {expression: "item.quota", value: "((item.insured and item.insured) ? surcharge : null)"}, + {expression: "claim.flags.penalty", value: "map(claim.items, -((#.quota ?? 0)))"}, + ], + }, + cases: [ + [{claim: {limit: 0, dueDate: "1990-06-15", channel: "x", status: "open", since: "2024-02-29", items: [{balance: 1.5, status: "pending", insured: false}, {balance: 10, status: "pending", insured: false}], report: {urgent: true}}}, {claim: {channel: "x", dueDate: "1990-06-15", flag: null, flags: {penalty: [-0, -0]}, items: [{balance: 1.5, insured: false, quota: null, status: "pending"}, {balance: 10, insured: false, quota: null, status: "pending"}], limit: 0, net: [], report: {capped: null, exposure: [], rank: 0, scores: {review: null}, segment: "x", urgent: true}, risk: 0, since: "2024-02-29", status: "open"}, surcharge: null}], + [{claim: {limit: 0, dueDate: "1990-06-15", channel: "gold", status: "closed", since: "1990-06-15", items: [{balance: 123456789.123, status: "pending", insured: false}, {balance: 18, status: "pending", insured: false}], report: {age: -1, urgent: true}}}, {claim: {channel: "gold", dueDate: "1990-06-15", flag: -1, flags: {penalty: [-0, -0]}, items: [{balance: 123456789.123, insured: false, quota: null, status: "pending"}, {balance: 18, insured: false, quota: null, status: "pending"}], limit: 0, net: [false], report: {age: -1, capped: "gold", exposure: [0], rank: -1, scores: {review: -1}, segment: "gold", urgent: true, weighted: false}, risk: 1, since: "1990-06-15", status: "closed"}, surcharge: -1}], + [{claim: {limit: 0.5, dueDate: "2000-01-01", channel: "a", status: "closed", since: "2025-03-20T10:15:30Z", items: [{balance: 99999999999999999999, status: "open", insured: true}], report: {age: -0.5, urgent: false}, extraField: 1}}, {claim: {channel: "a", dueDate: "2000-01-01", extraField: 1, flag: null, flags: {penalty: [0.5]}, items: [{balance: 99999999999999999999, insured: true, quota: -0.5, status: "open"}], limit: 0.5, net: [true], report: {age: -0.5, capped: null, exposure: [], rank: 0.0, scores: {review: null}, segment: "a", urgent: false}, risk: 0, since: "2025-03-20T10:15:30Z", status: "closed"}, surcharge: -0.5}], + [{claim: {limit: 7.25, dueDate: "2024-01-01", channel: " pad ", status: "closed", since: "2024-02-29", items: [{balance: 10, status: "closed", insured: false}, {balance: 284, status: "open", insured: true}, {balance: 100, status: "open", insured: false}, {balance: 99.99, status: "open", insured: false}, {balance: -0.5, status: "open", insured: false}, {balance: 250, status: "pending", insured: true}, {balance: 405, status: "closed", insured: false}, {balance: 100, status: "pending", insured: true}, {balance: 480, status: "open", insured: true}, {balance: 5, status: "pending", insured: true}, {balance: 50, status: "closed", insured: true}, {balance: 10, status: "open", insured: false}, {balance: 5, status: "open", insured: false}, {balance: -0.5, status: "closed", insured: true}], report: {age: 1, urgent: false}, extraField: 1}}, {claim: {channel: " pad ", dueDate: "2024-01-01", extraField: 1, flag: null, flags: {penalty: [-0, -1, -0, -0, -0, -1, -0, -1, -1, -1, -1, -0, -0, -1]}, items: [{balance: 10, insured: false, quota: null, status: "closed"}, {balance: 284, insured: true, quota: 1, status: "open"}, {balance: 100, insured: false, quota: null, status: "open"}, {balance: 99.99, insured: false, quota: null, status: "open"}, {balance: -0.5, insured: false, quota: null, status: "open"}, {balance: 250, insured: true, quota: 1, status: "pending"}, {balance: 405, insured: false, quota: null, status: "closed"}, {balance: 100, insured: true, quota: 1, status: "pending"}, {balance: 480, insured: true, quota: 1, status: "open"}, {balance: 5, insured: true, quota: 1, status: "pending"}, {balance: 50, insured: true, quota: 1, status: "closed"}, {balance: 10, insured: false, quota: null, status: "open"}, {balance: 5, insured: false, quota: null, status: "open"}, {balance: -0.5, insured: true, quota: 1, status: "closed"}], limit: 7.25, net: [true], report: {age: 1, capped: null, exposure: [], rank: 8.25, scores: {review: null}, segment: " pad ", urgent: false}, risk: 8.25, since: "2024-02-29", status: "closed"}, surcharge: 1}], + [{claim: {limit: 2.50, dueDate: "2030-12-31", channel: "gold", status: "open", since: "2030-12-31", items: [{balance: 1000, status: "open", insured: false}], report: {age: 99999999999999999999, urgent: true}}}, "!error: ExpressionFailed"], + [{claim: {limit: 0.1, dueDate: "2024-01-01", channel: "NL", status: null, since: null, items: [], report: {age: null, urgent: false}}}, {claim: {channel: "NL", dueDate: "2024-01-01", flag: null, flags: {penalty: []}, items: [], limit: 0.1, net: [], report: {age: null, capped: null, exposure: [], rank: 0, scores: {review: null}, segment: "NL", urgent: false}, risk: 0, since: null, status: null}, surcharge: null}], + [{claim: {limit: 5, dueDate: "2025-03-20", channel: "none", status: null, since: "2024-01-01", items: [{balance: 99999999999999999999, status: "open", insured: true}, {balance: 1e3, status: "open", insured: true}, {balance: 1.5, status: "closed", insured: false}, {balance: 2, status: "open", insured: false}], report: {age: 18, urgent: true}}}, {claim: {channel: "none", dueDate: "2025-03-20", flag: null, flags: {penalty: [-18, -18, -0, -0]}, items: [{balance: 99999999999999999999, insured: true, quota: 18, status: "open"}, {balance: 1000, insured: true, quota: 18, status: "open"}, {balance: 1.5, insured: false, quota: null, status: "closed"}, {balance: 2, insured: false, quota: null, status: "open"}], limit: 5, net: [false], report: {age: 18, capped: "none", exposure: [5], rank: 23, scores: {review: 18}, segment: "none", urgent: true}, risk: 414, since: "2024-01-01", status: null}, surcharge: 18}], + [{claim: {limit: 1000, dueDate: "2024-02-29", channel: "Zed", status: "open", since: "2024-01-01", items: [{balance: 0, status: "open", insured: true}], report: {age: 1e3, urgent: false}}}, {claim: {channel: "Zed", dueDate: "2024-02-29", flag: null, flags: {penalty: [-1000]}, items: [{balance: 0, insured: true, quota: 1000, status: "open"}], limit: 1000, net: [true], report: {age: 1000, capped: null, exposure: [], rank: 2000, scores: {review: null}, segment: "Zed", urgent: false}, risk: 2000000, since: "2024-01-01", status: "open"}, surcharge: 1000}], + [{claim: {limit: 100, dueDate: "1990-06-15", channel: "A1", status: "open", since: "2030-12-31", items: [{balance: 2.50, status: "pending", insured: null}], report: {age: 172, urgent: false}}}, "!error: ExpressionFailed"], + [{claim: {limit: 7.25, dueDate: "2024-01-01", channel: "NL", status: "open", since: "2030-12-31", items: [], report: {age: 123456789.123, urgent: true}}}, {claim: {channel: "NL", dueDate: "2024-01-01", flag: null, flags: {penalty: []}, items: [], limit: 7.25, net: [true], report: {age: 123456789.123, capped: "NL", exposure: [7.25], rank: 123456789.123, scores: {review: 123456789.123}, segment: "NL", urgent: true}, risk: 15241578780560891.109129, since: "2030-12-31", status: "open"}, surcharge: 123456789.123}], + [{claim: {limit: 99.99, dueDate: "2025-03-20T10:15:30Z", channel: "O'Neil", status: "open", since: "2024-02-29", items: [{balance: 99.99, status: "open", insured: true}, {balance: 7.25, status: "open", insured: true}, {balance: -0.5, status: "open", insured: false}], report: {age: 1000000, urgent: true}}}, {claim: {channel: "O'Neil", dueDate: "2025-03-20T10:15:30Z", flag: null, flags: {penalty: [-1000000, -1000000, -0]}, items: [{balance: 99.99, insured: true, quota: 1000000, status: "open"}, {balance: 7.25, insured: true, quota: 1000000, status: "open"}, {balance: -0.5, insured: false, quota: null, status: "open"}], limit: 99.99, net: [true], report: {age: 1000000, capped: "O'Neil", exposure: [99.99], rank: 1000099.99, scores: {review: 1000000}, segment: "O'Neil", urgent: true}, risk: 1000099990000.00, since: "2024-02-29", status: "open"}, surcharge: 1000000}], + [{claim: {limit: 99.99, dueDate: "2030-12-31", channel: "x", status: "open", since: "2030-12-31", items: [{balance: 5, status: "pending", insured: false}], report: {age: 1e3, urgent: true}}}, {claim: {channel: "x", dueDate: "2030-12-31", flag: null, flags: {penalty: [-0]}, items: [{balance: 5, insured: false, quota: null, status: "pending"}], limit: 99.99, net: [true], report: {age: 1000, capped: null, exposure: [], rank: 1000, scores: {review: null}, segment: "x", urgent: true}, risk: 1000000, since: "2030-12-31", status: "open"}, surcharge: 1000}], + [{claim: {limit: 0.1, dueDate: "1990-06-15", channel: "-", status: "closed", since: "2030-12-31", items: [{balance: 7.25, status: "pending", insured: true}, {balance: 5, status: "closed", insured: true}, {balance: 5, status: "pending", insured: false}], report: {age: 18, urgent: true}}}, {claim: {channel: "-", dueDate: "1990-06-15", flag: null, flags: {penalty: [-18, -18, -0]}, items: [{balance: 7.25, insured: true, quota: 18, status: "pending"}, {balance: 5, insured: true, quota: 18, status: "closed"}, {balance: 5, insured: false, quota: null, status: "pending"}], limit: 0.1, net: [], report: {age: 18, capped: null, exposure: [], rank: 18.1, scores: {review: null}, segment: "-", urgent: true}, risk: 325.8, since: "2030-12-31", status: "closed"}, surcharge: 18}], + [{claim: {limit: 1000, dueDate: "2000-01-01", channel: "gold", status: "pending", since: "1990-06-15", items: [{balance: 1000000, status: "open", insured: true}, {balance: 277, status: "open", insured: false}], report: {age: -0.01, urgent: true}, extraField: "x"}}, {claim: {channel: "gold", dueDate: "2000-01-01", extraField: "x", flag: null, flags: {penalty: [0.01, -0]}, items: [{balance: 1000000, insured: true, quota: -0.01, status: "open"}, {balance: 277, insured: false, quota: null, status: "open"}], limit: 1000, net: [true], report: {age: -0.01, capped: "gold", exposure: [1000], rank: 999.99, scores: {review: -0.01}, segment: "gold", urgent: true}, risk: -9.9999, since: "1990-06-15", status: "pending"}, surcharge: -0.01}], + [{claim: {limit: 1, dueDate: "2025-03-20T10:15:30Z", channel: "low", status: "pending", since: "2025-03-20T10:15:30Z", items: [{balance: 1000000, status: "closed", insured: false}, {balance: 5, status: "open", insured: false}, {balance: 250, status: "pending", insured: false}, {balance: 1.5, status: "closed", insured: false}, {balance: 10, status: "open", insured: true}], report: {age: 0.1, urgent: true}, extraField: "x"}}, {claim: {channel: "low", dueDate: "2025-03-20T10:15:30Z", extraField: "x", flag: 0.1, flags: {penalty: [-0, -0, -0, -0, -0.1]}, items: [{balance: 1000000, insured: false, quota: null, status: "closed"}, {balance: 5, insured: false, quota: null, status: "open"}, {balance: 250, insured: false, quota: null, status: "pending"}, {balance: 1.5, insured: false, quota: null, status: "closed"}, {balance: 10, insured: true, quota: 0.1, status: "open"}], limit: 1, net: [true, false], report: {age: 0.1, capped: "low", exposure: [1], rank: 1.1, scores: {review: 0.1}, segment: "low", urgent: true, weighted: false}, risk: 0.11, since: "2025-03-20T10:15:30Z", status: "pending"}, surcharge: 0.1}], + [{claim: {limit: 7.25, dueDate: "2024-01-01", channel: "high", status: "closed", since: "2024-01-01", items: [{balance: 7.25, status: "open", insured: true}, {balance: 123456789.123, status: "open", insured: false}, {balance: 2, status: "open", insured: true}, {balance: 1.5, status: "pending", insured: true}, {balance: 99999999999999999999, status: "pending", insured: false}], report: {age: -0, urgent: false}, extraField: 1}}, {claim: {channel: "high", dueDate: "2024-01-01", extraField: 1, flag: null, flags: {penalty: [-0, -0, -0, -0, -0]}, items: [{balance: 7.25, insured: true, quota: 0, status: "open"}, {balance: 123456789.123, insured: false, quota: null, status: "open"}, {balance: 2, insured: true, quota: 0, status: "open"}, {balance: 1.5, insured: true, quota: 0, status: "pending"}, {balance: 99999999999999999999, insured: false, quota: null, status: "pending"}], limit: 7.25, net: [true], report: {age: 0, capped: null, exposure: [], rank: 7.25, scores: {review: null}, segment: "high", urgent: false}, risk: 0, since: "2024-01-01", status: "closed"}, surcharge: 0}], + [{claim: {limit: 1e3, dueDate: "2025-03-20", channel: "x-y", status: "open", since: "2024-02-29", items: [], report: {age: 0.1, urgent: false}}}, {claim: {channel: "x-y", dueDate: "2025-03-20", flag: null, flags: {penalty: []}, items: [], limit: 1000, net: [true], report: {age: 0.1, capped: null, exposure: [], rank: 0.1, scores: {review: null}, segment: "x-y", urgent: false}, risk: 0.01, since: "2024-02-29", status: "open"}, surcharge: 0.1}], + [{claim: {limit: 5, dueDate: "2000-01-01", channel: "x", status: "open", items: [{balance: -0, status: "open", insured: true}], report: {urgent: true}}}, {claim: {channel: "x", dueDate: "2000-01-01", flag: null, flags: {penalty: [-0]}, items: [{balance: 0, insured: true, quota: null, status: "open"}], limit: 5, net: [true], report: {capped: null, exposure: [], rank: 5, scores: {review: null}, segment: "x", urgent: true}, risk: 0, status: "open"}, surcharge: null}], + [{claim: {limit: 65, dueDate: "2024-01-01", channel: "VIP", status: "closed", since: "2024-01-01", items: [{balance: 99999999999999999999, status: "open", insured: false}, {balance: 10, status: "closed", insured: false}], report: {age: 1.5, urgent: true}}}, {claim: {channel: "VIP", dueDate: "2024-01-01", flag: null, flags: {penalty: [-0, -0]}, items: [{balance: 99999999999999999999, insured: false, quota: null, status: "open"}, {balance: 10, insured: false, quota: null, status: "closed"}], limit: 65, net: [], report: {age: 1.5, capped: "VIP", exposure: [65], rank: 1.5, scores: {review: 1.5}, segment: "VIP", urgent: true}, risk: 2.25, since: "2024-01-01", status: "closed"}, surcharge: 1.5}], + [{claim: {limit: 0.5, dueDate: "2024-02-29", channel: "gold", status: "closed", since: "2025-03-20T10:15:30Z", items: [{balance: 123456789.123, status: "pending", insured: true}, {balance: 1000000, status: "open", insured: false}, {balance: 7.25, status: "open", insured: true}], report: {age: 18, urgent: false}}}, {claim: {channel: "gold", dueDate: "2024-02-29", flag: 18, flags: {penalty: [-18, -0, -18]}, items: [{balance: 123456789.123, insured: true, quota: 18, status: "pending"}, {balance: 1000000, insured: false, quota: null, status: "open"}, {balance: 7.25, insured: true, quota: 18, status: "open"}], limit: 0.5, net: [true, false], report: {age: 18, capped: "gold", exposure: [18], rank: 18.5, scores: {review: 18}, segment: "gold", urgent: false, weighted: false}, risk: 333.0, since: "2025-03-20T10:15:30Z", status: "closed"}, surcharge: 18}], + [{claim: {limit: 346, dueDate: "2024-02-29", channel: "é ü", status: "open", since: "2000-01-01", items: [], report: {age: 2, urgent: false}}}, {claim: {channel: "é ü", dueDate: "2024-02-29", flag: null, flags: {penalty: []}, items: [], limit: 346, net: [true], report: {age: 2, capped: null, exposure: [], rank: 2, scores: {review: null}, segment: "é ü", urgent: false}, risk: 4, since: "2000-01-01", status: "open"}, surcharge: 2}], + [{claim: {limit: 7.25, dueDate: "2024-01-01", channel: "3.5", status: "open", since: "2025-03-20T10:15:30Z", items: [{balance: 1000, status: "open", insured: false}], report: {age: 65, urgent: true}, extraField: 1}}, {claim: {channel: "3.5", dueDate: "2024-01-01", extraField: 1, flag: null, flags: {penalty: [-0]}, items: [{balance: 1000, insured: false, quota: null, status: "open"}], limit: 7.25, net: [true], report: {age: 65, capped: "3.5", exposure: [7.25], rank: 65, scores: {review: 65}, segment: "3.5", urgent: true}, risk: 4225, since: "2025-03-20T10:15:30Z", status: "open"}, surcharge: 65}], + [{claim: {limit: 1000000, dueDate: "2025-03-20", channel: "", status: "closed", since: "2024-02-29", items: [{balance: 0.1, status: "pending", insured: true}, {balance: -0.5, status: "closed", insured: false}], report: {age: 2, urgent: true}}}, {claim: {channel: "", dueDate: "2025-03-20", flag: null, flags: {penalty: [-2, -0]}, items: [{balance: 0.1, insured: true, quota: 2, status: "pending"}, {balance: -0.5, insured: false, quota: null, status: "closed"}], limit: 1000000, net: [true], report: {age: 2, capped: null, exposure: [], rank: 1000002, scores: {review: null}, segment: "", urgent: true}, risk: 2000004, since: "2024-02-29", status: "closed"}, surcharge: 2}], + [{claim: {limit: 1, dueDate: "2024-02-29", channel: "low", status: "pending", since: "2025-03-20T10:15:30Z", items: [], report: {age: 18, urgent: true}}}, "!error: ExpressionFailed"], + [{claim: {limit: 2.50, dueDate: "2025-03-20", channel: "gold", status: "open", since: null, items: [{balance: 50, status: "open", insured: false}, {balance: 0.5, status: "open", insured: true}, {balance: 0, status: "pending", insured: true}, {balance: 18, status: "open", insured: true}], report: {age: 1e3, urgent: true}}}, {claim: {channel: "gold", dueDate: "2025-03-20", flag: 1000, flags: {penalty: [-0, -1000, -1000, -1000]}, items: [{balance: 50, insured: false, quota: null, status: "open"}, {balance: 0.5, insured: true, quota: 1000, status: "open"}, {balance: 0, insured: true, quota: 1000, status: "pending"}, {balance: 18, insured: true, quota: 1000, status: "open"}], limit: 2.50, net: [true, false], report: {age: 1000, capped: "gold", exposure: [2.50], rank: 1002.50, scores: {review: 1000}, segment: "gold", urgent: true, weighted: false}, risk: 1002500.00, since: null, status: "open"}, surcharge: 1000}], + [{claim: {limit: 99.99, dueDate: "2000-01-01", channel: "high", status: "open", since: "2000-01-01", items: [], report: {age: -500, urgent: true}}}, {claim: {channel: "high", dueDate: "2000-01-01", flag: null, flags: {penalty: []}, items: [], limit: 99.99, net: [true], report: {age: -500, capped: "high", exposure: [99.99], rank: -500, scores: {review: -500}, segment: "high", urgent: true}, risk: 250000, since: "2000-01-01", status: "open"}, surcharge: -500}], + [{claim: {limit: 2, dueDate: "2000-01-01", channel: "a", status: "open", since: "2024-01-01", items: [], report: {age: -0.5, urgent: true}}}, {claim: {channel: "a", dueDate: "2000-01-01", flag: null, flags: {penalty: []}, items: [], limit: 2, net: [true], report: {age: -0.5, capped: null, exposure: [], rank: -0.5, scores: {review: null}, segment: "a", urgent: true}, risk: 0.25, since: "2024-01-01", status: "open"}, surcharge: -0.5}], + [{claim: {limit: 1.5, dueDate: "2025-03-20T10:15:30Z", channel: "US", status: null, since: null, items: [{balance: 18, status: "open", insured: true}, {balance: 18, status: "pending", insured: false}, {balance: 1e3, status: "open", insured: true}, {balance: 250, status: "open", insured: false}, {balance: 0.000001, status: "open", insured: true}, {balance: 0, status: "open", insured: false}, {balance: 99999999999999999999, status: "pending", insured: true}, {balance: 0.000001, status: "open", insured: false}, {balance: 99999999999999999999, status: "closed", insured: true}, {balance: 18, status: "closed", insured: false}, {balance: 0.5, status: "open", insured: false}, {balance: 1000, status: "open", insured: false}, {balance: 0.5, status: "pending", insured: true}], report: {age: null, urgent: true}}}, {claim: {channel: "US", dueDate: "2025-03-20T10:15:30Z", flag: null, flags: {penalty: [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0]}, items: [{balance: 18, insured: true, quota: null, status: "open"}, {balance: 18, insured: false, quota: null, status: "pending"}, {balance: 1000, insured: true, quota: null, status: "open"}, {balance: 250, insured: false, quota: null, status: "open"}, {balance: 0.000001, insured: true, quota: null, status: "open"}, {balance: 0, insured: false, quota: null, status: "open"}, {balance: 99999999999999999999, insured: true, quota: null, status: "pending"}, {balance: 0.000001, insured: false, quota: null, status: "open"}, {balance: 99999999999999999999, insured: true, quota: null, status: "closed"}, {balance: 18, insured: false, quota: null, status: "closed"}, {balance: 0.5, insured: false, quota: null, status: "open"}, {balance: 1000, insured: false, quota: null, status: "open"}, {balance: 0.5, insured: true, quota: null, status: "pending"}], limit: 1.5, net: [false], report: {age: null, capped: "US", exposure: [1.5], rank: 1.5, scores: {review: 0}, segment: "US", urgent: true}, risk: 0, since: null, status: null}, surcharge: null}], + ], +} + +// seed 343700 (attempt 0) +{ + name: "b 38: customer/loans + address: 4 expression, 1 match, 1 table; 3 root, 2 per-member, 0 top-level computed", + policy: { + models: {customer: {qty: "number", city: "string", name: "string", vip: "boolean?", age: "number", urgent: "boolean?", loans: "loan[]", address: "address"}, loan: {age: "number", kind: "string(retail|corporate)"}, address: {amount: "number"}}, + blocks: [ + {match: "customer.margin", arms: [["some(customer.loans, (#.age == 2 or #.age == 2))", "((customer.vip ?? false) ? customer.name : customer.city)"], ["", "string((customer.vip ?? false))"]]}, + {expression: "customer.quota", value: "(customer.city + '-' + customer.margin)"}, + {expression: "customer.bucket", value: "map(customer.loans, #.age)"}, + {expression: "loan.grade", value: "((round(customer.qty / 7, 2) % (abs((max(customer.bucket) ?? 0)) + 1)) + (min(map(customer.loans, (#.age) / (abs(#.age) + 1))) ?? 0))"}, + {expression: "loan.flags.share", value: "some(customer.loans, (50 == 10 or #.age <= 2))"}, + {table: "t6", inputs: [null, "customer.name", "customer.margin"], outputs: ["address.health"], rules: [ + ["customer.name == 'DE'", "startsWith($, 'none')", "'A1', 'a'", "address.amount"], + ["((customer.urgent ?? false) or (customer.vip ?? false))", "'gold'", "'high'", ""], + ["((customer.vip ?? false) or (customer.vip ?? false))", "'VIP'", "'low'", ""], + ["customer.city != 'a'", "'retail'", "$ != 'a'", ""], + ["contains(['gold', 'a', ''], customer.city)", "$ != 'x'", "$ != 'low'", ""], + ["", "", "", "250"], + ]}, + ], + }, + cases: [ + [{customer: {qty: 250, city: "O'Neil", name: "A1", vip: true, age: 2, urgent: false, loans: [], address: {amount: 65}}}, {customer: {address: {amount: 65, health: 250}, age: 2, bucket: [], city: "O'Neil", loans: [], margin: "true", name: "A1", qty: 250, quota: "O'Neil-true", urgent: false, vip: true}}], + [{customer: {qty: 99999999999999999999, city: "low", name: "low", vip: false, age: 1000000, loans: [{age: 0.1, kind: "retail"}, {age: -1, kind: "corporate"}, {age: 0, kind: "retail"}, {age: 1000, kind: "retail"}], address: {amount: 100}}}, {customer: {address: {amount: 100, health: 250}, age: 1000000, bucket: [0.1, -1, 0, 1000], city: "low", loans: [{age: 0.1, flags: {share: true}, grade: 299.64, kind: "retail"}, {age: -1, flags: {share: true}, grade: 299.64, kind: "corporate"}, {age: 0, flags: {share: true}, grade: 299.64, kind: "retail"}, {age: 1000, flags: {share: true}, grade: 299.64, kind: "retail"}], margin: "false", name: "low", qty: 99999999999999999999, quota: "low-false", vip: false}}], + [{customer: {qty: 18, city: "DE", name: "a", age: 7.25, loans: [{age: 250, kind: "corporate"}, {age: 2.50, kind: "corporate"}], address: {amount: 99.99}}}, {customer: {address: {amount: 99.99, health: 250}, age: 7.25, bucket: [250, 2.50], city: "DE", loans: [{age: 250, flags: {share: false}, grade: 3.2842857142857142857142857143, kind: "corporate"}, {age: 2.50, flags: {share: false}, grade: 3.2842857142857142857142857143, kind: "corporate"}], margin: "false", name: "a", qty: 18, quota: "DE-false"}}], + [{customer: {qty: 5, city: "é ü", name: " pad ", vip: false, age: 250, urgent: false, loans: [{age: 7.25, kind: "retail"}, {age: 100, kind: "retail"}, {age: 2, kind: "retail"}, {age: -0.01, kind: "retail"}, {age: 65, kind: "retail"}, {age: -500, kind: "retail"}, {age: 0.1, kind: "retail"}, {age: 10, kind: "corporate"}, {age: 1, kind: "retail"}, {age: 2, kind: "retail"}], address: {amount: 100}, extraField: 1}}, {customer: {address: {amount: 100, health: 250}, age: 250, bucket: [7.25, 100, 2, -0.01, 65, -500, 0.1, 10, 1, 2], city: "é ü", extraField: 1, loans: [{age: 7.25, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}, {age: 100, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}, {age: 2, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}, {age: -0.01, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}, {age: 65, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}, {age: -500, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}, {age: 0.1, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}, {age: 10, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "corporate"}, {age: 1, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}, {age: 2, flags: {share: true}, grade: -0.288003992015968063872255489, kind: "retail"}], margin: "é ü", name: " pad ", qty: 5, quota: "é ü-é ü", urgent: false, vip: false}}], + [{customer: {qty: 18, city: "gold", name: "O'Neil", age: 1000000, loans: [{age: 2, kind: "retail"}, {age: 123456789.123, kind: "retail"}], address: {amount: 2}}}, {customer: {address: {amount: 2, health: 250}, age: 1000000, bucket: [2, 123456789.123], city: "gold", loans: [{age: 2, flags: {share: true}, grade: 3.2366666666666666666666666667, kind: "retail"}, {age: 123456789.123, flags: {share: true}, grade: 3.2366666666666666666666666667, kind: "retail"}], margin: "gold", name: "O'Neil", qty: 18, quota: "gold-gold"}}], + [{customer: {qty: 10, city: "a", name: "gold", vip: null, age: 2, urgent: null, loans: [{age: 1000000, kind: "corporate"}], address: {amount: 2}}}, {customer: {address: {amount: 2, health: 250}, age: 2, bucket: [1000000], city: "a", loans: [{age: 1000000, flags: {share: false}, grade: 2.429999000000999999000001, kind: "corporate"}], margin: "false", name: "gold", qty: 10, quota: "a-false", urgent: null, vip: null}}], + [{customer: {qty: 1000, city: "DE", name: "US", vip: true, age: 1000, urgent: 1, loans: [{age: 1000, kind: "retail"}], address: {amount: -1}}}, "!error: InputValidationFailed"], + [{customer: {qty: 0.000001, city: "gold", name: "a", vip: true, age: -500, urgent: true, loans: [{age: 0, kind: "retail"}], address: {amount: 1}}}, {customer: {address: {amount: 1, health: 250}, age: -500, bucket: [0], city: "gold", loans: [{age: 0, flags: {share: true}, grade: 0, kind: "retail"}], margin: "true", name: "a", qty: 0.000001, quota: "gold-true", urgent: true, vip: true}}], + [{customer: {qty: 0.5, city: "DE", name: "none", vip: false, age: -0.5, urgent: false, loans: [{age: -1, kind: "corporate"}, {age: 10, kind: "corporate"}, {age: 0.000001, kind: "corporate"}, {age: 1000000, kind: "retail"}, {age: 2, kind: "retail"}], address: {amount: -0.01}}}, {customer: {address: {amount: -0.01, health: 250}, age: -0.5, bucket: [-1, 10, 0.000001, 1000000, 2], city: "DE", loans: [{age: -1, flags: {share: true}, grade: -0.43, kind: "corporate"}, {age: 10, flags: {share: true}, grade: -0.43, kind: "corporate"}, {age: 0.000001, flags: {share: true}, grade: -0.43, kind: "corporate"}, {age: 1000000, flags: {share: true}, grade: -0.43, kind: "retail"}, {age: 2, flags: {share: true}, grade: -0.43, kind: "retail"}], margin: "DE", name: "none", qty: 0.5, quota: "DE-DE", urgent: false, vip: false}}], + [{customer: {qty: 250, city: "Oslo", name: "NL", vip: false, age: 5, urgent: false, loans: [{age: 100, kind: "retail"}, {age: 1e3, kind: "corporate"}, {age: 235, kind: "retail"}], address: {amount: 50}}}, {customer: {address: {amount: 50, health: 250}, age: 5, bucket: [100, 1000, 235], city: "Oslo", loans: [{age: 100, flags: {share: false}, grade: 36.700099009900990099009900990, kind: "retail"}, {age: 1000, flags: {share: false}, grade: 36.700099009900990099009900990, kind: "corporate"}, {age: 235, flags: {share: false}, grade: 36.700099009900990099009900990, kind: "retail"}], margin: "false", name: "NL", qty: 250, quota: "Oslo-false", urgent: false, vip: false}}], + [{customer: {qty: 50, city: "A1", name: "3.5", vip: true, age: 0.1, urgent: false, loans: [], address: {amount: 7.25}}}, {customer: {address: {amount: 7.25, health: 250}, age: 0.1, bucket: [], city: "A1", loans: [], margin: "true", name: "3.5", qty: 50, quota: "A1-true", urgent: false, vip: true}}], + [{customer: {qty: 100, city: "retail", name: "retail", vip: false, age: -0.5, urgent: null, loans: [{age: 50, kind: "retail"}, {age: -500, kind: "retail"}, {age: -0.5, kind: "retail"}, {age: 0.000001, kind: "corporate"}], address: {amount: 18}}}, {customer: {address: {amount: 18, health: 250}, age: -0.5, bucket: [50, -500, -0.5, 0.000001], city: "retail", loans: [{age: 50, flags: {share: true}, grade: 13.291996007984031936127744511, kind: "retail"}, {age: -500, flags: {share: true}, grade: 13.291996007984031936127744511, kind: "retail"}, {age: -0.5, flags: {share: true}, grade: 13.291996007984031936127744511, kind: "retail"}, {age: 0.000001, flags: {share: true}, grade: 13.291996007984031936127744511, kind: "corporate"}], margin: "false", name: "retail", qty: 100, quota: "retail-false", urgent: null, vip: false}}], + [{customer: {qty: 50, city: "high", name: "a", vip: true, age: 10, urgent: false, loans: [{age: 0, kind: "retail"}], address: {amount: 123456789.123}}}, {customer: {address: {amount: 123456789.123, health: 250}, age: 10, bucket: [0], city: "high", loans: [{age: 0, flags: {share: true}, grade: 0.14, kind: "retail"}], margin: "true", name: "a", qty: 50, quota: "high-true", urgent: false, vip: true}}], + [{customer: {qty: 219, city: "none", name: "Zed", vip: true, age: 2.50, urgent: false, loans: [{age: 99999999999999999999, kind: "retail"}, {age: -1, kind: "retail"}], address: {amount: 1000000}, extraField: 1}}, {customer: {address: {amount: 1000000, health: 250}, age: 2.50, bucket: [99999999999999999999, -1], city: "none", extraField: 1, loans: [{age: 99999999999999999999, flags: {share: true}, grade: 30.79, kind: "retail"}, {age: -1, flags: {share: true}, grade: 30.79, kind: "retail"}], margin: "true", name: "Zed", qty: 219, quota: "none-true", urgent: false, vip: true}}], + [{customer: {qty: -0, city: "a", name: "a", vip: true, age: 2, urgent: false, loans: [], address: {amount: 123456789.123}}}, {customer: {address: {amount: 123456789.123, health: 250}, age: 2, bucket: [], city: "a", loans: [], margin: "true", name: "a", qty: 0, quota: "a-true", urgent: false, vip: true}}], + [{customer: {qty: 100, city: "DE", name: "NL", vip: false, age: 7.25, urgent: true, loans: [], address: {amount: 100}}}, {customer: {address: {amount: 100, health: 250}, age: 7.25, bucket: [], city: "DE", loans: [], margin: "false", name: "NL", qty: 100, quota: "DE-false", urgent: true, vip: false}}], + ], +} + +// seed 343800 (attempt 0) +{ + name: "b 39: shipment/accounts: 5 expression, 3 match, 3 table; 6 root, 8 per-member, 0 top-level computed", + policy: { + models: {shipment: {years: "number", region: "string?", amount: "number?", kind: "string(retail|corporate)", plan: "string(basic|plus|premium|trial)", accounts: "acct[]"}, acct: {score: "number", since: "date?"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {match: "acct.discount", arms: [["(shipment.amount ?? 0) in [-2..46]", "shipment.meta.review"], ["(acct.net == 'retail' or (threshold == 3 or shipment.meta.review <= 0))", "(shipment.amount ?? 0)"], ["shipment.region != null", "trunc((shipment.amount ?? 0))"], ["", "(threshold == 18 ? shipment.meta.review : threshold)"]]}, + {expression: "acct.grade", value: "contains(['none', 'retail', ''], acct.net)"}, + {match: "acct.net", arms: [["(acct.since ?? d('2025-01-01')) >= d('2025-01-01')", "lower((shipment.region ?? ''))"], ["", "(shipment.region ?? '')"]]}, + {table: "t8", inputs: ["shipment.penalty", "shipment.penalty", "(acct.since ?? d('2025-01-01'))"], outputs: ["acct.level"], rules: [ + ["", "<= 0.25", "", "50"], + ["[10..35]", "", "< d('2000-06-30')", "acct.score"], + ["< 0", "<= 2", "> d('2000-06-30')", "(shipment.amount ?? 0)"], + ["<= 1", "< 3", ">= d('2000-06-30')", "len(acct.net)"], + ["[100..277]", "50", "< d('2025-03-20')", "shipment.meta.review"], + ]}, + {expression: "shipment.rank", value: "{ok: shipment.penalty, n: (shipment.region ?? '')}"}, + {table: "t1", hit: "collect", inputs: ["(shipment.region ?? '')", "shipment.kind", "shipment.plan"], outputs: ["acct.scores.band"], rules: [ + ["'none', 'retail'", "", "'premium'", "(acct.score <= 250 ? (shipment.amount ?? 0) : (shipment.amount ?? 0))"], + ["", "", "'plus', 'basic'", "(shipment.amount ?? 0)"], + ["$ != 'VIP'", "'retail', 'corporate'", "'basic', 'premium'", "shipment.years"], + ["startsWith($, 'A1')", "'retail'", "'premium', 'plus'", "threshold"], + ]}, + {expression: "shipment.penalty", value: "number(string(sum([(threshold) / (abs(shipment.years) + 1), (shipment.meta.review) / (abs(10) + 1)])))"}, + {match: "shipment.meta.review", arms: [["some(shipment.accounts, #.since == null)", "trunc(threshold)"], ["none(shipment.accounts, #.score > #.score)", "number(string(sum(shipment.total)))"], ["(threshold > 0 or (shipment.amount ?? 0) <= 5)", "1000"], ["", "len(shipment.accounts)"]]}, + {expression: "acct.bucket", value: "map(shipment.accounts, (#.grade ? 0 : (#.level ?? 0)))"}, + {expression: "shipment.total", value: "map(shipment.accounts, #.score)"}, + {table: "t6", hit: "collect", inputs: ["(threshold % (abs(shipment.meta.review) + 1))", "acct.net", "(shipment.region ?? '')"], outputs: ["acct.fee", "acct.ok"], rules: [ + ["", "", "$ != 'high'", "shipment.penalty <= 100", ""], + ["", "'VIP'", "startsWith($, 'high')", "threshold > 1.5", "acct.net"], + ["", "$ != 'x'", "$ != 'a'", "", "'VIP'"], + [">= 100", "", "", "acct.net == 'x'", ""], + ["[0.25..422.25]", "$ != 'VIP'", "'low'", "", "`${shipment.penalty <= 1}/${(shipment.amount ?? 0)}`"], + ["", "", "", "(acct.since ?? d('2025-01-01')) < d('2024-01-01')", ""], + ]}, + ], + }, + cases: [ + [{threshold: 10, shipment: {years: 100, region: "US", amount: 1000, kind: "retail", plan: "trial", accounts: []}}, {shipment: {accounts: [], amount: 1000, kind: "retail", meta: {review: 0}, penalty: 0.099009900990099009900990099, plan: "trial", rank: {n: "US", ok: 0.099009900990099009900990099}, region: "US", total: [], years: 100}, threshold: 10}], + [{threshold: 1, shipment: {years: 18, region: "a", amount: 99.99, kind: "retail", plan: "premium", accounts: []}}, {shipment: {accounts: [], amount: 99.99, kind: "retail", meta: {review: 0}, penalty: 0.0526315789473684210526315789, plan: "premium", rank: {n: "a", ok: 0.0526315789473684210526315789}, region: "a", total: [], years: 18}, threshold: 1}], + [{threshold: 0.5, shipment: {years: 0, amount: null, kind: "corporate", plan: "basic", accounts: [{score: 0.25, since: "2025-03-20T10:15:30Z"}, {score: 250}, {score: 0, since: "2030-12-31"}, {score: 1e3}, {score: 100, since: "2025-03-20T10:15:30Z"}]}}, {shipment: {accounts: [{bucket: [0, 0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 0, net: "", ok: ["VIP"], score: 0.25, scores: {band: [0, 0]}, since: "2025-03-20T10:15:30Z"}, {bucket: [0, 0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 0, net: "", ok: ["VIP"], score: 250, scores: {band: [0, 0]}}, {bucket: [0, 0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 0, net: "", ok: ["VIP"], score: 0, scores: {band: [0, 0]}, since: "2030-12-31"}, {bucket: [0, 0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 0, net: "", ok: ["VIP"], score: 1000, scores: {band: [0, 0]}}, {bucket: [0, 0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 0, net: "", ok: ["VIP"], score: 100, scores: {band: [0, 0]}, since: "2025-03-20T10:15:30Z"}], amount: null, kind: "corporate", meta: {review: 0}, penalty: 0.5, plan: "basic", rank: {n: "", ok: 0.5}, years: 0}, threshold: 0.5}], + [{threshold: 100, shipment: {years: 10, region: "gold", amount: 1, kind: "retail", plan: "premium", accounts: []}}, {shipment: {accounts: [], amount: 1, kind: "retail", meta: {review: 0}, penalty: 9.090909090909090909090909091, plan: "premium", rank: {n: "gold", ok: 9.090909090909090909090909091}, region: "gold", total: [], years: 10}, threshold: 100}], + [{threshold: 10, shipment: {years: 0.25, region: "x-y", amount: 99999999999999999999, kind: "corporate", plan: "premium", accounts: []}}, {shipment: {accounts: [], amount: 99999999999999999999, kind: "corporate", meta: {review: 0}, penalty: 8, plan: "premium", rank: {n: "x-y", ok: 8}, region: "x-y", total: [], years: 0.25}, threshold: 10}], + [{threshold: -2, shipment: {years: 250, region: "VIP", amount: -500, kind: "retail", plan: "basic", accounts: []}}, {shipment: {accounts: [], amount: -500, kind: "retail", meta: {review: 0}, penalty: -0.0079681274900398406374501992, plan: "basic", rank: {n: "VIP", ok: -0.0079681274900398406374501992}, region: "VIP", total: [], years: 250}, threshold: -2}], + [{threshold: 10, shipment: {years: 50, region: "retail", amount: 0, kind: "retail", plan: "basic", accounts: []}}, {shipment: {accounts: [], amount: 0, kind: "retail", meta: {review: 0}, penalty: 0.1960784313725490196078431373, plan: "basic", rank: {n: "retail", ok: 0.1960784313725490196078431373}, region: "retail", total: [], years: 50}, threshold: 10}], + [{threshold: -2, shipment: {years: 18, region: "gold", amount: 1, kind: "retail", plan: "premium", accounts: [{score: 250, since: "2025-03-20"}], extraField: 1}}, {shipment: {accounts: [{bucket: [0], discount: 250, fee: [true, false], grade: false, level: null, net: "gold", ok: ["VIP"], score: 250, scores: {band: [18]}, since: "2025-03-20"}], amount: 1, extraField: 1, kind: "retail", meta: {review: 250}, penalty: 22.622009569377990430622009569, plan: "premium", rank: {n: "gold", ok: 22.622009569377990430622009569}, region: "gold", total: [250], years: 18}, threshold: -2}], + [{threshold: -2, shipment: {years: 100, region: "x", amount: 1000, kind: "retail", plan: "trial", accounts: [{score: 10, since: "2024-01-01"}, {score: 99.99, since: "2000-01-01"}]}}, {shipment: {accounts: [{bucket: [0, 0], discount: 1000, fee: [true, false], grade: false, level: null, net: "x", ok: [], score: 10, scores: {band: []}, since: "2024-01-01"}, {bucket: [0, 0], discount: 1000, fee: [true, true], grade: false, level: null, net: "x", ok: [], score: 99.99, scores: {band: []}, since: "2000-01-01"}], amount: 1000, kind: "retail", meta: {review: 109.99}, penalty: 9.979288928892889288928892889, plan: "trial", rank: {n: "x", ok: 9.979288928892889288928892889}, region: "x", total: [10, 99.99], years: 100}, threshold: -2}], + [{threshold: 0.5, shipment: {years: 308, region: "a", amount: 7.25, kind: "corporate", plan: "basic", accounts: []}}, {shipment: {accounts: [], amount: 7.25, kind: "corporate", meta: {review: 0}, penalty: 0.0016181229773462783171521036, plan: "basic", rank: {n: "a", ok: 0.0016181229773462783171521036}, region: "a", total: [], years: 308}, threshold: 0.5}], + [{threshold: 100, shipment: {years: 0, region: "gold", amount: 99999999999999999999, kind: "retail", plan: "premium", accounts: [{score: 123456789.123, since: "2025-03-20"}]}}, {shipment: {accounts: [{bucket: [0], discount: 99999999999999999999, fee: [false, false, false], grade: false, level: null, net: "gold", ok: ["VIP"], score: 123456789.123, scores: {band: [0]}, since: "2025-03-20"}], amount: 99999999999999999999, kind: "retail", meta: {review: 123456789.123}, penalty: 11223444.465727272727272727273, plan: "premium", rank: {n: "gold", ok: 11223444.465727272727272727273}, region: "gold", total: [123456789.123], years: 0}, threshold: 100}], + [{threshold: -2, shipment: {years: 1.5, region: "none", amount: 3, kind: "retail", plan: "basic", accounts: []}}, {shipment: {accounts: [], amount: 3, kind: "retail", meta: {review: 0}, penalty: -0.8, plan: "basic", rank: {n: "none", ok: -0.8}, region: "none", total: [], years: 1.5}, threshold: -2}], + [{threshold: -2, shipment: {years: 0.1, region: "x", amount: 5, kind: "retail", plan: "basic", accounts: [{score: -0, since: "2025-03-20T10:15:30Z"}]}}, {shipment: {accounts: [{bucket: [50], discount: 0, fee: [true, false], grade: false, level: 50, net: "x", ok: [], score: 0, scores: {band: [5, 0.1]}, since: "2025-03-20T10:15:30Z"}], amount: 5, kind: "retail", meta: {review: 0}, penalty: -1.8181818181818181818181818182, plan: "basic", rank: {n: "x", ok: -1.8181818181818181818181818182}, region: "x", total: [0], years: 0.1}, threshold: -2}], + [{threshold: 1, shipment: {years: 100, region: "VIP", amount: 1, kind: "retail", plan: "basic", accounts: [], extraField: 1}}, {shipment: {accounts: [], amount: 1, extraField: 1, kind: "retail", meta: {review: 0}, penalty: 0.0099009900990099009900990099, plan: "basic", rank: {n: "VIP", ok: 0.0099009900990099009900990099}, region: "VIP", total: [], years: 100}, threshold: 1}], + [{threshold: 10, shipment: {years: 5, region: " pad ", amount: 1.5, kind: "retail", plan: "plus", accounts: []}}, {shipment: {accounts: [], amount: 1.5, kind: "retail", meta: {review: 0}, penalty: 1.6666666666666666666666666667, plan: "plus", rank: {n: " pad ", ok: 1.6666666666666666666666666667}, region: " pad ", total: [], years: 5}, threshold: 10}], + [{threshold: 1, shipment: {years: 99.99, region: "retail", amount: 1, kind: "corporate", plan: "basic", accounts: [{score: null, since: "2030-12-31"}, {score: 0.1, since: "2025-03-20T10:15:30Z"}]}}, "!error: ExpressionFailed"], + [{threshold: 0, shipment: {years: 5, region: null, amount: null, kind: "retail", plan: "basic", accounts: [{score: 250, since: "2025-03-20"}, {score: 250, since: "2024-01-01"}, {score: 10}, {score: 2, since: "2024-02-29"}]}}, {shipment: {accounts: [{bucket: [0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 50, net: "", ok: ["VIP"], score: 250, scores: {band: [0, 5]}, since: "2025-03-20"}, {bucket: [0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 50, net: "", ok: ["VIP"], score: 250, scores: {band: [0, 5]}, since: "2024-01-01"}, {bucket: [0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 50, net: "", ok: ["VIP"], score: 10, scores: {band: [0, 5]}}, {bucket: [0, 0, 0, 0], discount: 0, fee: [true, false], grade: true, level: 50, net: "", ok: ["VIP"], score: 2, scores: {band: [0, 5]}, since: "2024-02-29"}], amount: null, kind: "retail", meta: {review: 0}, penalty: 0, plan: "basic", rank: {n: "", ok: 0}, region: null, years: 5}, threshold: 0}], + [{threshold: 10, shipment: {years: 100, region: null, amount: null, kind: "corporate", plan: "plus", accounts: []}}, {shipment: {accounts: [], amount: null, kind: "corporate", meta: {review: 0}, penalty: 0.099009900990099009900990099, plan: "plus", rank: {n: "", ok: 0.099009900990099009900990099}, region: null, total: [], years: 100}, threshold: 10}], + [{threshold: 10, shipment: {years: 1, region: "high", amount: 3, kind: "retail", plan: "plus", accounts: [{score: 5}, {score: 50, since: "2025-03-20T10:15:30Z"}, {score: 123456789.123, since: "2025-03-20"}, {score: -500, since: "2030-12-31"}]}}, {shipment: {accounts: [{bucket: [0, 0, 0, 0], discount: 10, fee: [false], grade: false, level: null, net: "high", ok: ["VIP"], score: 5, scores: {band: [3]}}, {bucket: [0, 0, 0, 0], discount: 10, fee: [false], grade: false, level: null, net: "high", ok: ["VIP"], score: 50, scores: {band: [3]}, since: "2025-03-20T10:15:30Z"}, {bucket: [0, 0, 0, 0], discount: 10, fee: [false], grade: false, level: null, net: "high", ok: ["VIP"], score: 123456789.123, scores: {band: [3]}, since: "2025-03-20"}, {bucket: [0, 0, 0, 0], discount: 10, fee: [false], grade: false, level: null, net: "high", ok: ["VIP"], score: -500, scores: {band: [3]}, since: "2030-12-31"}], amount: 3, kind: "retail", meta: {review: 10}, penalty: 5.9090909090909090909090909091, plan: "plus", rank: {n: "high", ok: 5.9090909090909090909090909091}, region: "high", years: 1}, threshold: 10}], + [{threshold: 0.5, shipment: {years: 3, region: "-", amount: null, kind: "retail", plan: "basic", accounts: [{score: -500}, {score: 0.000001, since: null}]}}, {shipment: {accounts: [{bucket: [50, 50], discount: 0, fee: [true, false], grade: false, level: 50, net: "-", ok: ["VIP"], score: -500, scores: {band: [0, 3]}}, {bucket: [50, 50], discount: 0, fee: [true, false], grade: false, level: 50, net: "-", ok: ["VIP"], score: 0.000001, scores: {band: [0, 3]}, since: null}], amount: null, kind: "retail", meta: {review: 0}, penalty: 0.125, plan: "basic", rank: {n: "-", ok: 0.125}, region: "-", years: 3}, threshold: 0.5}], + [{threshold: 10, shipment: {years: 2.50, region: "é ü", amount: 7.25, kind: "retail", plan: "plus", accounts: [{score: 99999999999999999999, since: "2030-12-31"}]}}, {shipment: {accounts: [{bucket: [0], discount: 99999999999999999999, fee: [false, false], grade: false, level: null, net: "é ü", ok: ["VIP"], score: 99999999999999999999, scores: {band: [7.25]}, since: "2030-12-31"}], amount: 7.25, kind: "retail", meta: {review: 99999999999999999999}, penalty: 9090909090909090911.857142857, plan: "plus", rank: {n: "é ü", ok: 9090909090909090911.857142857}, region: "é ü", total: [99999999999999999999], years: 2.50}, threshold: 10}], + [{threshold: 10, shipment: {years: 2.50, region: "high", amount: 1000000, kind: "retail", plan: "premium", accounts: [{score: -0.01, since: "2024-02-29"}, {score: 1.5, since: "2000-01-01"}]}}, {shipment: {accounts: [{bucket: [0, 0], discount: 1000000, fee: [false], grade: false, level: null, net: "high", ok: ["VIP"], score: -0.01, scores: {band: [2.50]}, since: "2024-02-29"}, {bucket: [0, 0], discount: 1000000, fee: [true], grade: false, level: null, net: "high", ok: ["VIP"], score: 1.5, scores: {band: [2.50]}, since: "2000-01-01"}], amount: 1000000, kind: "retail", meta: {review: 1.49}, penalty: 2.9925974025974025974025974026, plan: "premium", rank: {n: "high", ok: 2.9925974025974025974025974026}, region: "high", total: [-0.01, 1.5], years: 2.50}, threshold: 10}], + [{threshold: 10, shipment: {years: 18, region: "12", amount: 2, kind: "retail", plan: "plus", accounts: []}}, {shipment: {accounts: [], amount: 2, kind: "retail", meta: {review: 0}, penalty: 0.5263157894736842105263157895, plan: "plus", rank: {n: "12", ok: 0.5263157894736842105263157895}, region: "12", total: [], years: 18}, threshold: 10}], + ], +} + +// seed 343900 (attempt 0) +{ + name: "b 40: customer/members/employees: 6 expression, 4 match; 0 root, 12 per-member, 3 top-level computed", + policy: { + models: {customer: {qty: "number", priority: "boolean", openedAt: "date", days: "number?", flagged: "boolean?", members: "member[]"}, member: {balance: "number?", kind: "string(retail|corporate)", employees: "employee[]"}, employee: {score: "number", years: "number", flagged: "boolean?"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {match: "member.exposure", arms: [["not (not (customer.priority))", "customer.openedAt >= d('2024-01-01')"], ["some(member.employees, #.years == 100)", "customer.priority"], ["some(member.employees, ((#.flagged ?? false) and (#.flagged ?? false)))", "(customer.flagged ?? false)"], ["", "customer.priority"]]}, + {match: "member.rank", arms: [["not (member.balance == null)", "'DE'"], ["", "string(threshold)"]]}, + {expression: "member.share", value: "(contains(['Oslo', 'low', ''], member.rank) or threshold in [4..151])"}, + {expression: "summary", value: "{a: customer.qty == (customer.days ?? 0), ok: customer.qty}"}, + {expression: "member.margin", value: "-(-(threshold))"}, + {match: "member.bucket", arms: [["(summary.ok) / (abs((customer.days ?? 0)) + 1) != threshold", "count(member.employees, not ((#.flagged ?? false)))"], ["", "customer.openedAt.year()"]]}, + {expression: "member.capped", value: "(member.bucket + -(sum(map(member.employees, avg([#.years])))))"}, + {expression: "member.adjusted", value: "string(count(member.employees, not ((#.flagged ?? false))))"}, + {match: "member.calc.bonus", arms: [["some(member.employees, #.flagged == null)", "(member.adjusted + '-' + 'x')"], ["member.balance == null", "member.rank"], ["member.kind in ['retail', 'corporate']", "trim((split(member.adjusted, '-')[1] ?? 'none'))"], ["", "member.adjusted"]]}, + {expression: "member.segment", value: "{ok: threshold, n: ('low' + '-' + member.adjusted), s: (customer.days ?? 0)}"}, + ], + }, + cases: [ + [{threshold: 0, customer: {qty: -500, priority: true, openedAt: "2024-01-01", days: 0, flagged: null, members: [{balance: null, kind: "retail", employees: [{score: 0.5, years: 0.000001, flagged: false}]}]}}, {customer: {days: 0, flagged: null, members: [{adjusted: "1", balance: null, bucket: 1, calc: {bonus: "0"}, capped: 0.999999, employees: [{flagged: false, score: 0.5, years: 0.000001}], exposure: true, kind: "retail", margin: 0, rank: "0", segment: {n: "low-1", ok: 0, s: 0}, share: false}], openedAt: "2024-01-01", priority: true, qty: -500}, summary: {a: false, ok: -500}, threshold: 0}], + [{threshold: 100, customer: {qty: 0, priority: false, openedAt: "2000-01-01", members: [{balance: -0.5, kind: "corporate", employees: []}, {kind: "retail", employees: [{score: 1, years: 123456789.123, flagged: false}, {score: 100, years: 10, flagged: null}, {score: 100, years: 18, flagged: true}]}, {balance: null, kind: "retail", employees: [{score: 99.99, years: 100}, {score: 18, years: 100, flagged: true}]}, {balance: null, kind: "retail", employees: [{score: 65, years: 10, flagged: null}]}, {balance: 123456789.123, kind: "corporate", employees: [{score: 1, years: 1000000, flagged: true}, {score: 1e3, years: 99999999999999999999, flagged: false}]}]}}, {customer: {members: [{adjusted: "0", balance: -0.5, bucket: 0, calc: {bonus: "none"}, capped: -0, employees: [], exposure: false, kind: "corporate", margin: 100, rank: "DE", segment: {n: "low-0", ok: 100, s: 0}, share: true}, {adjusted: "2", bucket: 2, calc: {bonus: "2-x"}, capped: -123456815.123, employees: [{flagged: false, score: 1, years: 123456789.123}, {flagged: null, score: 100, years: 10}, {flagged: true, score: 100, years: 18}], exposure: false, kind: "retail", margin: 100, rank: "100", segment: {n: "low-2", ok: 100, s: 0}, share: true}, {adjusted: "1", balance: null, bucket: 1, calc: {bonus: "1-x"}, capped: -199, employees: [{score: 99.99, years: 100}, {flagged: true, score: 18, years: 100}], exposure: false, kind: "retail", margin: 100, rank: "100", segment: {n: "low-1", ok: 100, s: 0}, share: true}, {adjusted: "1", balance: null, bucket: 1, calc: {bonus: "1-x"}, capped: -9, employees: [{flagged: null, score: 65, years: 10}], exposure: false, kind: "retail", margin: 100, rank: "100", segment: {n: "low-1", ok: 100, s: 0}, share: true}, {adjusted: "1", balance: 123456789.123, bucket: 1, calc: {bonus: "none"}, capped: -100000000000000999998, employees: [{flagged: true, score: 1, years: 1000000}, {flagged: false, score: 1000, years: 99999999999999999999}], exposure: false, kind: "corporate", margin: 100, rank: "DE", segment: {n: "low-1", ok: 100, s: 0}, share: true}], openedAt: "2000-01-01", priority: false, qty: 0}, summary: {a: true, ok: 0}, threshold: 100}], + [{threshold: -2, customer: {qty: 100, priority: true, openedAt: "1990-06-15", days: 0.5, flagged: false, members: [{balance: -0.01, kind: "corporate", employees: [{score: 65, years: 1000, flagged: false}]}, {balance: -500, kind: "retail", employees: [{score: -0.5, years: 18, flagged: false}, {score: 0.000001, years: -0.01, flagged: false}]}, {balance: -500, kind: "corporate", employees: [{score: 100, years: 2, flagged: true}, {score: -1, years: 1, flagged: false}]}, {balance: 1000000, kind: "retail", employees: [{score: 65, years: 133, flagged: true}]}, {balance: 1.5, kind: "corporate", employees: [{score: -1, years: 0, flagged: false}]}], extraField: "x"}}, {customer: {days: 0.5, extraField: "x", flagged: false, members: [{adjusted: "1", balance: -0.01, bucket: 1, calc: {bonus: "none"}, capped: -999, employees: [{flagged: false, score: 65, years: 1000}], exposure: false, kind: "corporate", margin: -2, rank: "DE", segment: {n: "low-1", ok: -2, s: 0.5}, share: false}, {adjusted: "2", balance: -500, bucket: 2, calc: {bonus: "none"}, capped: -15.99, employees: [{flagged: false, score: -0.5, years: 18}, {flagged: false, score: 0.000001, years: -0.01}], exposure: false, kind: "retail", margin: -2, rank: "DE", segment: {n: "low-2", ok: -2, s: 0.5}, share: false}, {adjusted: "1", balance: -500, bucket: 1, calc: {bonus: "none"}, capped: -2, employees: [{flagged: true, score: 100, years: 2}, {flagged: false, score: -1, years: 1}], exposure: false, kind: "corporate", margin: -2, rank: "DE", segment: {n: "low-1", ok: -2, s: 0.5}, share: false}, {adjusted: "0", balance: 1000000, bucket: 0, calc: {bonus: "none"}, capped: -133, employees: [{flagged: true, score: 65, years: 133}], exposure: false, kind: "retail", margin: -2, rank: "DE", segment: {n: "low-0", ok: -2, s: 0.5}, share: false}, {adjusted: "1", balance: 1.5, bucket: 1, calc: {bonus: "none"}, capped: 1, employees: [{flagged: false, score: -1, years: 0}], exposure: false, kind: "corporate", margin: -2, rank: "DE", segment: {n: "low-1", ok: -2, s: 0.5}, share: false}], openedAt: "1990-06-15", priority: true, qty: 100}, summary: {a: false, ok: 100}, threshold: -2}], + [{threshold: 1, customer: {qty: 0.5, priority: true, openedAt: "2025-03-20", days: 99.99, flagged: false, members: [{balance: 5, kind: "corporate", employees: [{score: 0.1, years: 250, flagged: true}]}, {balance: 0.5, kind: "retail", employees: [{score: -0.01, years: 18, flagged: false}]}, {balance: 99.99, kind: "corporate", employees: [{score: 0.5, years: 100, flagged: true}, {score: 100, years: 100, flagged: false}, {score: 0.5, years: 1000000, flagged: true}]}, {balance: 100, kind: "corporate", employees: [{score: 2.50, years: 100, flagged: true}]}, {balance: 0.5, kind: "retail", employees: [{score: 7.25, years: -500, flagged: true}, {score: -0, years: 250, flagged: true}, {score: 96, years: 1.5, flagged: false}]}]}}, {customer: {days: 99.99, flagged: false, members: [{adjusted: "0", balance: 5, bucket: 0, calc: {bonus: "none"}, capped: -250, employees: [{flagged: true, score: 0.1, years: 250}], exposure: true, kind: "corporate", margin: 1, rank: "DE", segment: {n: "low-0", ok: 1, s: 99.99}, share: false}, {adjusted: "1", balance: 0.5, bucket: 1, calc: {bonus: "none"}, capped: -17, employees: [{flagged: false, score: -0.01, years: 18}], exposure: true, kind: "retail", margin: 1, rank: "DE", segment: {n: "low-1", ok: 1, s: 99.99}, share: false}, {adjusted: "1", balance: 99.99, bucket: 1, calc: {bonus: "none"}, capped: -1000199, employees: [{flagged: true, score: 0.5, years: 100}, {flagged: false, score: 100, years: 100}, {flagged: true, score: 0.5, years: 1000000}], exposure: true, kind: "corporate", margin: 1, rank: "DE", segment: {n: "low-1", ok: 1, s: 99.99}, share: false}, {adjusted: "0", balance: 100, bucket: 0, calc: {bonus: "none"}, capped: -100, employees: [{flagged: true, score: 2.50, years: 100}], exposure: true, kind: "corporate", margin: 1, rank: "DE", segment: {n: "low-0", ok: 1, s: 99.99}, share: false}, {adjusted: "1", balance: 0.5, bucket: 1, calc: {bonus: "none"}, capped: 249.5, employees: [{flagged: true, score: 7.25, years: -500}, {flagged: true, score: 0, years: 250}, {flagged: false, score: 96, years: 1.5}], exposure: true, kind: "retail", margin: 1, rank: "DE", segment: {n: "low-1", ok: 1, s: 99.99}, share: false}], openedAt: "2025-03-20", priority: true, qty: 0.5}, summary: {a: false, ok: 0.5}, threshold: 1}], + [{threshold: 0, customer: {qty: 0.1, priority: true, openedAt: "1990-06-15", days: 18, flagged: true, members: [{balance: 1, kind: "retail", employees: [{score: 100, years: 100, flagged: false}, {score: 100, years: 32, flagged: true}]}], extraField: {nested: true}}}, {customer: {days: 18, extraField: {nested: true}, flagged: true, members: [{adjusted: "1", balance: 1, bucket: 1, calc: {bonus: "none"}, capped: -131, employees: [{flagged: false, score: 100, years: 100}, {flagged: true, score: 100, years: 32}], exposure: false, kind: "retail", margin: 0, rank: "DE", segment: {n: "low-1", ok: 0, s: 18}, share: false}], openedAt: "1990-06-15", priority: true, qty: 0.1}, summary: {a: false, ok: 0.1}, threshold: 0}], + [{threshold: 10, customer: {qty: -500, priority: true, openedAt: "2024-02-29", days: 100, flagged: true, members: [{balance: 1, kind: "corporate", employees: []}, {balance: 2, kind: "corporate", employees: [{score: 1.5, years: 5, flagged: false}, {score: 100, years: 2.50, flagged: false}, {score: -0.01, years: 100, flagged: false}]}, {balance: 0.5, kind: "retail", employees: [{score: 1000000, years: 1.5, flagged: true}, {score: -0.5, years: 2, flagged: true}]}]}}, {customer: {days: 100, flagged: true, members: [{adjusted: "0", balance: 1, bucket: 0, calc: {bonus: "none"}, capped: -0, employees: [], exposure: true, kind: "corporate", margin: 10, rank: "DE", segment: {n: "low-0", ok: 10, s: 100}, share: true}, {adjusted: "3", balance: 2, bucket: 3, calc: {bonus: "none"}, capped: -104.50, employees: [{flagged: false, score: 1.5, years: 5}, {flagged: false, score: 100, years: 2.50}, {flagged: false, score: -0.01, years: 100}], exposure: true, kind: "corporate", margin: 10, rank: "DE", segment: {n: "low-3", ok: 10, s: 100}, share: true}, {adjusted: "0", balance: 0.5, bucket: 0, calc: {bonus: "none"}, capped: -3.5, employees: [{flagged: true, score: 1000000, years: 1.5}, {flagged: true, score: -0.5, years: 2}], exposure: true, kind: "retail", margin: 10, rank: "DE", segment: {n: "low-0", ok: 10, s: 100}, share: true}], openedAt: "2024-02-29", priority: true, qty: -500}, summary: {a: false, ok: -500}, threshold: 10}], + [{threshold: 0, customer: {qty: 1.5, priority: true, openedAt: "1990-06-15", days: "12", flagged: true, members: [{balance: 1.5, kind: "retail", employees: [{score: 1000, years: -0.5, flagged: true}, {score: -0, years: 100, flagged: false}, {score: 250, years: 123456789.123, flagged: true}]}, {balance: 0.5, kind: "retail", employees: []}, {balance: 116, kind: "retail", employees: []}, {balance: 2.50, kind: "corporate", employees: []}, {balance: -1, kind: "retail", employees: [{score: 1000, years: 65, flagged: true}, {score: 1.5, years: 2.50, flagged: false}, {score: -0.5, years: 65, flagged: false}]}, {balance: 2, kind: "corporate", employees: [{score: 2, years: 99.99, flagged: true}]}, {balance: 10, kind: "retail", employees: [{score: -0.01, years: 111, flagged: false}, {score: 65, years: 2.50, flagged: false}]}, {balance: 2, kind: "retail", employees: [{score: 10, years: 10, flagged: true}, {score: 1.5, years: 0.5, flagged: true}, {score: 451, years: -0, flagged: true}]}, {balance: 10, kind: "retail", employees: []}]}}, "!error: InputValidationFailed"], + [{threshold: 10, customer: {qty: -0.01, priority: false, openedAt: "2030-12-31", days: 2, flagged: true, members: [{balance: null, kind: "corporate", employees: [{score: 1000000, years: 7.25, flagged: true}, {score: 2, years: 2, flagged: null}, {score: 0.000001, years: 99999999999999999999, flagged: true}]}, {balance: null, kind: "retail", employees: [{score: 7.25, years: 1.5, flagged: false}, {score: 99.99, years: 0.000001}]}, {kind: "corporate", employees: [{score: 100, years: 1000000, flagged: null}, {score: 18, years: -1, flagged: false}]}]}}, {customer: {days: 2, flagged: true, members: [{adjusted: "1", balance: null, bucket: 1, calc: {bonus: "1-x"}, capped: -100000000000000000007.25, employees: [{flagged: true, score: 1000000, years: 7.25}, {flagged: null, score: 2, years: 2}, {flagged: true, score: 0.000001, years: 99999999999999999999}], exposure: true, kind: "corporate", margin: 10, rank: "10", segment: {n: "low-1", ok: 10, s: 2}, share: true}, {adjusted: "2", balance: null, bucket: 2, calc: {bonus: "2-x"}, capped: 0.499999, employees: [{flagged: false, score: 7.25, years: 1.5}, {score: 99.99, years: 0.000001}], exposure: false, kind: "retail", margin: 10, rank: "10", segment: {n: "low-2", ok: 10, s: 2}, share: true}, {adjusted: "2", bucket: 2, calc: {bonus: "2-x"}, capped: -999997, employees: [{flagged: null, score: 100, years: 1000000}, {flagged: false, score: 18, years: -1}], exposure: false, kind: "corporate", margin: 10, rank: "10", segment: {n: "low-2", ok: 10, s: 2}, share: true}], openedAt: "2030-12-31", priority: false, qty: -0.01}, summary: {a: false, ok: -0.01}, threshold: 10}], + [{threshold: 1, customer: {qty: 2, priority: true, openedAt: "2024-01-01", days: null, flagged: false, members: [{balance: -1, kind: "retail", employees: [{score: 2.50, years: 99999999999999999999}, {score: 10, years: 0.5, flagged: false}]}]}}, {customer: {days: null, flagged: false, members: [{adjusted: "2", balance: -1, bucket: 2, calc: {bonus: "2-x"}, capped: -99999999999999999997.5, employees: [{score: 2.50, years: 99999999999999999999}, {flagged: false, score: 10, years: 0.5}], exposure: true, kind: "retail", margin: 1, rank: "DE", segment: {n: "low-2", ok: 1, s: 0}, share: false}], openedAt: "2024-01-01", priority: true, qty: 2}, summary: {a: false, ok: 2}, threshold: 1}], + [{threshold: -2, customer: {qty: 2, priority: true, openedAt: "2000-01-01", days: null, flagged: null, members: [{kind: "corporate", employees: [{score: -0, years: 1, flagged: true}, {score: 1000000, years: 7.25, flagged: false}]}]}}, {customer: {days: null, flagged: null, members: [{adjusted: "1", bucket: 1, calc: {bonus: "-2"}, capped: -7.25, employees: [{flagged: true, score: 0, years: 1}, {flagged: false, score: 1000000, years: 7.25}], exposure: false, kind: "corporate", margin: -2, rank: "-2", segment: {n: "low-1", ok: -2, s: 0}, share: false}], openedAt: "2000-01-01", priority: true, qty: 2}, summary: {a: false, ok: 2}, threshold: -2}], + [{threshold: 0, customer: {qty: 100, priority: true, openedAt: "2024-01-01", flagged: true, members: [{kind: "retail", employees: [{score: 65, years: 100}, {score: 250, years: 0, flagged: null}]}, {kind: "retail", employees: [{score: 1000, years: 99.99, flagged: true}, {score: 100, years: 2.50}]}]}}, {customer: {flagged: true, members: [{adjusted: "2", bucket: 2, calc: {bonus: "2-x"}, capped: -98, employees: [{score: 65, years: 100}, {flagged: null, score: 250, years: 0}], exposure: true, kind: "retail", margin: 0, rank: "0", segment: {n: "low-2", ok: 0, s: 0}, share: false}, {adjusted: "1", bucket: 1, calc: {bonus: "1-x"}, capped: -101.49, employees: [{flagged: true, score: 1000, years: 99.99}, {score: 100, years: 2.50}], exposure: true, kind: "retail", margin: 0, rank: "0", segment: {n: "low-1", ok: 0, s: 0}, share: false}], openedAt: "2024-01-01", priority: true, qty: 100}, summary: {a: false, ok: 100}, threshold: 0}], + [{threshold: 1, customer: {qty: 99.99, priority: false, openedAt: "2024-02-29", days: 0.1, flagged: false, members: [{balance: 1000000, kind: "retail", employees: [{score: 10, years: 100, flagged: true}, {score: 1000000, years: 100, flagged: true}]}, {balance: 2, kind: "corporate", employees: [{score: 18, years: 1e3, flagged: true}, {score: 18, years: 0, flagged: false}]}], extraField: "x"}}, {customer: {days: 0.1, extraField: "x", flagged: false, members: [{adjusted: "0", balance: 1000000, bucket: 0, calc: {bonus: "none"}, capped: -200, employees: [{flagged: true, score: 10, years: 100}, {flagged: true, score: 1000000, years: 100}], exposure: false, kind: "retail", margin: 1, rank: "DE", segment: {n: "low-0", ok: 1, s: 0.1}, share: false}, {adjusted: "1", balance: 2, bucket: 1, calc: {bonus: "none"}, capped: -999, employees: [{flagged: true, score: 18, years: 1000}, {flagged: false, score: 18, years: 0}], exposure: false, kind: "corporate", margin: 1, rank: "DE", segment: {n: "low-1", ok: 1, s: 0.1}, share: false}], openedAt: "2024-02-29", priority: false, qty: 99.99}, summary: {a: false, ok: 99.99}, threshold: 1}], + [{threshold: 0, customer: {qty: 1.5, priority: false, openedAt: "1990-06-15", days: 0.5, flagged: true, members: [{balance: 0, kind: "corporate", employees: [{score: -500, years: 99999999999999999999}]}, {balance: 1000000, kind: "retail", employees: [{score: 0.000001, years: 100, flagged: false}, {score: -0.01, years: 7.25, flagged: true}, {score: -0, years: 0.000001}]}, {kind: "retail", employees: []}, {balance: 0.5, kind: "corporate", employees: [{score: 0, years: -0}]}, {balance: null, kind: "retail", employees: [{score: 7.25, years: 99999999999999999999, flagged: false}, {score: -0.5, years: 1, flagged: true}]}]}}, {customer: {days: 0.5, flagged: true, members: [{adjusted: "1", balance: 0, bucket: 1, calc: {bonus: "1-x"}, capped: -99999999999999999998, employees: [{score: -500, years: 99999999999999999999}], exposure: false, kind: "corporate", margin: 0, rank: "DE", segment: {n: "low-1", ok: 0, s: 0.5}, share: false}, {adjusted: "2", balance: 1000000, bucket: 2, calc: {bonus: "2-x"}, capped: -105.250001, employees: [{flagged: false, score: 0.000001, years: 100}, {flagged: true, score: -0.01, years: 7.25}, {score: 0, years: 0.000001}], exposure: false, kind: "retail", margin: 0, rank: "DE", segment: {n: "low-2", ok: 0, s: 0.5}, share: false}, {adjusted: "0", bucket: 0, calc: {bonus: "0"}, capped: -0, employees: [], exposure: false, kind: "retail", margin: 0, rank: "0", segment: {n: "low-0", ok: 0, s: 0.5}, share: false}, {adjusted: "1", balance: 0.5, bucket: 1, calc: {bonus: "1-x"}, capped: 1, employees: [{score: 0, years: 0}], exposure: false, kind: "corporate", margin: 0, rank: "DE", segment: {n: "low-1", ok: 0, s: 0.5}, share: false}, {adjusted: "1", balance: null, bucket: 1, calc: {bonus: "0"}, capped: -99999999999999999999, employees: [{flagged: false, score: 7.25, years: 99999999999999999999}, {flagged: true, score: -0.5, years: 1}], exposure: true, kind: "retail", margin: 0, rank: "0", segment: {n: "low-1", ok: 0, s: 0.5}, share: false}], openedAt: "1990-06-15", priority: false, qty: 1.5}, summary: {a: false, ok: 1.5}, threshold: 0}], + [{threshold: 100, customer: {qty: 99.99, priority: true, openedAt: "2025-03-20T10:15:30Z", days: 1000000, flagged: true, members: [{balance: 10, kind: "retail", employees: []}, {balance: 1, kind: "retail", employees: []}, {balance: -0.01, kind: "retail", employees: [{score: 100, years: 250, flagged: false}]}]}}, {customer: {days: 1000000, flagged: true, members: [{adjusted: "0", balance: 10, bucket: 0, calc: {bonus: "none"}, capped: -0, employees: [], exposure: true, kind: "retail", margin: 100, rank: "DE", segment: {n: "low-0", ok: 100, s: 1000000}, share: true}, {adjusted: "0", balance: 1, bucket: 0, calc: {bonus: "none"}, capped: -0, employees: [], exposure: true, kind: "retail", margin: 100, rank: "DE", segment: {n: "low-0", ok: 100, s: 1000000}, share: true}, {adjusted: "1", balance: -0.01, bucket: 1, calc: {bonus: "none"}, capped: -249, employees: [{flagged: false, score: 100, years: 250}], exposure: true, kind: "retail", margin: 100, rank: "DE", segment: {n: "low-1", ok: 100, s: 1000000}, share: true}], openedAt: "2025-03-20T10:15:30Z", priority: true, qty: 99.99}, summary: {a: false, ok: 99.99}, threshold: 100}], + [{threshold: -2, customer: {qty: 100, priority: false, openedAt: "2025-03-20", days: 99999999999999999999, flagged: false, members: [{balance: 5, kind: "retail", employees: [{score: 1000, years: 1000000, flagged: false}]}, {balance: 0.1, kind: "retail", employees: [{score: 250, years: 1000, flagged: true}, {score: 1e3, years: 10, flagged: false}, {score: 1, years: -0, flagged: false}]}]}}, {customer: {days: 99999999999999999999, flagged: false, members: [{adjusted: "1", balance: 5, bucket: 1, calc: {bonus: "none"}, capped: -999999, employees: [{flagged: false, score: 1000, years: 1000000}], exposure: false, kind: "retail", margin: -2, rank: "DE", segment: {n: "low-1", ok: -2, s: 99999999999999999999}, share: false}, {adjusted: "2", balance: 0.1, bucket: 2, calc: {bonus: "none"}, capped: -1008, employees: [{flagged: true, score: 250, years: 1000}, {flagged: false, score: 1000, years: 10}, {flagged: false, score: 1, years: 0}], exposure: false, kind: "retail", margin: -2, rank: "DE", segment: {n: "low-2", ok: -2, s: 99999999999999999999}, share: false}], openedAt: "2025-03-20", priority: false, qty: 100}, summary: {a: false, ok: 100}, threshold: -2}], + ], +} + +// seed 344000 (attempt 0) +{ + name: "b 41: applicant/parcels: 4 expression, 2 match, 1 table; 2 root, 7 per-member, 1 top-level computed", + policy: { + models: {applicant: {weight: "number?", vip: "boolean?", limit: "number", dueDate: "date?", active: "boolean?", urgent: "boolean", parcels: "parcel[]"}, parcel: {amount: "number", insured: "boolean"}}, + blocks: [ + {table: "t6", inputs: ["applicant.active", "parcel.review.v", "parcel.exposure"], outputs: ["parcel.margin", "parcel.surcharge"], rules: [ + ["false", "startsWith($, 'none')", "true", "'ok'", "(applicant.active ?? false)"], + ["", "'VIP', 'a'", "false", "parcel.decision", "parcel.amount <= parcel.amount"], + ["", "", "", "(split(parcel.review.a, '-')[1] ?? 'none')", "(applicant.vip ?? false)"], + ]}, + {match: "applicant.scores.bucket", arms: [["(applicant.urgent and (applicant.vip ?? false))", "`${(applicant.weight ?? 0)}/${len(applicant.parcels)}`"], ["(((applicant.vip ?? false) or (applicant.vip ?? false)) or applicant.weight == null)", "`${(total ?? false)}/${number(string(applicant.limit))}`"], ["(applicant.dueDate ?? d('2025-01-01')) >= d('2000-06-30')", "'US'"], ["", "((applicant.vip ?? false) ? 'x' : 'VIP')"]]}, + {expression: "total", value: "((applicant.dueDate ?? d('2025-01-01')) < d('2024-01-01') ? applicant.active : null)"}, + {expression: "parcel.exposure", value: "applicant.dueDate != null"}, + {expression: "applicant.net", value: "applicant.weight != null"}, + {match: "parcel.decision", arms: [["none(applicant.parcels, #.amount != #.amount)", "lower(parcel.review.v)"], ["none(applicant.parcels, (#.insured and #.insured))", "string((applicant.vip ?? false))"], ["len(parcel.review.v) > 2", "`${applicant.limit}/${applicant.urgent}`"], ["", "trim(parcel.review.v)"]]}, + {expression: "parcel.review", value: "{v: (applicant.dueDate ?? d('2025-01-01')).format('%Y-%m'), a: string(parcel.amount)}"}, + ], + }, + cases: [ + [{applicant: {weight: 0.000001, vip: true, limit: 100, active: false, urgent: true, parcels: []}}, {applicant: {active: false, limit: 100, net: true, parcels: [], scores: {bucket: "0.000001/0"}, urgent: true, vip: true, weight: 0.000001}}], + [{applicant: {limit: 0.5, urgent: false, parcels: [{amount: -1, insured: true}]}}, {applicant: {limit: 0.5, net: false, parcels: [{amount: -1, exposure: false, insured: true, margin: "1", review: {a: "-1", v: "2025-01"}, surcharge: false}], scores: {bucket: "false/0.5"}, urgent: false}, total: null}], + [{applicant: {weight: null, vip: true, limit: 2.50, dueDate: null, active: true, urgent: true, parcels: [{amount: 16, insured: false}, {amount: 459, insured: true}]}}, {applicant: {active: true, dueDate: null, limit: 2.50, net: false, parcels: [{amount: 16, exposure: false, insured: false, margin: "none", review: {a: "16", v: "2025-01"}, surcharge: true}, {amount: 459, exposure: false, insured: true, margin: "none", review: {a: "459", v: "2025-01"}, surcharge: true}], scores: {bucket: "0/2"}, urgent: true, vip: true, weight: null}}], + [{applicant: {weight: 0.000001, vip: false, limit: 268, dueDate: "2030-12-31", active: false, urgent: true, parcels: [{amount: -500, insured: false}, {amount: 0.000001, insured: false}]}}, {applicant: {active: false, dueDate: "2030-12-31", limit: 268, net: true, parcels: [{amount: -500, exposure: true, insured: false, margin: "500", review: {a: "-500", v: "2030-12"}, surcharge: false}, {amount: 0.000001, exposure: true, insured: false, margin: "none", review: {a: "0.000001", v: "2030-12"}, surcharge: false}], scores: {bucket: "US"}, urgent: true, vip: false, weight: 0.000001}}], + [{applicant: {vip: false, limit: 10, active: false, urgent: true, parcels: [{amount: -0.5, insured: false}, {amount: 0.5, insured: false}, {amount: 100, insured: true}]}}, {applicant: {active: false, limit: 10, net: false, parcels: [{amount: -0.5, exposure: false, insured: false, margin: "0.5", review: {a: "-0.5", v: "2025-01"}, surcharge: false}, {amount: 0.5, exposure: false, insured: false, margin: "none", review: {a: "0.5", v: "2025-01"}, surcharge: false}, {amount: 100, exposure: false, insured: true, margin: "none", review: {a: "100", v: "2025-01"}, surcharge: false}], scores: {bucket: "false/10"}, urgent: true, vip: false}, total: null}], + [{applicant: {weight: 1, limit: -0.01, dueDate: "2030-12-31", active: null, urgent: true, parcels: [{amount: 167, insured: true}, {amount: -0.5, insured: true}]}}, {applicant: {active: null, dueDate: "2030-12-31", limit: -0.01, net: true, parcels: [{amount: 167, exposure: true, insured: true, margin: "none", review: {a: "167", v: "2030-12"}, surcharge: false}, {amount: -0.5, exposure: true, insured: true, margin: "0.5", review: {a: "-0.5", v: "2030-12"}, surcharge: false}], scores: {bucket: "US"}, urgent: true, weight: 1}}], + [{applicant: {weight: 99999999999999999999, vip: false, limit: 123456789.123, dueDate: "2024-01-01", active: true, urgent: true, parcels: [{amount: 99.99, insured: true}, {amount: -0.01, insured: true}], extraField: 1}}, {applicant: {active: true, dueDate: "2024-01-01", extraField: 1, limit: 123456789.123, net: true, parcels: [{amount: 99.99, exposure: true, insured: true, margin: "none", review: {a: "99.99", v: "2024-01"}, surcharge: false}, {amount: -0.01, exposure: true, insured: true, margin: "0.01", review: {a: "-0.01", v: "2024-01"}, surcharge: false}], scores: {bucket: "US"}, urgent: true, vip: false, weight: 99999999999999999999}}], + [{applicant: {weight: null, vip: null, limit: -1, dueDate: null, urgent: true, parcels: [{amount: 1000000, insured: true}, {amount: 0.1, insured: true}]}}, {applicant: {dueDate: null, limit: -1, net: false, parcels: [{amount: 1000000, exposure: false, insured: true, margin: "none", review: {a: "1000000", v: "2025-01"}, surcharge: false}, {amount: 0.1, exposure: false, insured: true, margin: "none", review: {a: "0.1", v: "2025-01"}, surcharge: false}], scores: {bucket: "false/-1"}, urgent: true, vip: null, weight: null}, total: null}], + [{applicant: {weight: 5, vip: true, limit: -0, dueDate: 20250101, active: false, urgent: true, parcels: [{amount: 37, insured: true}, {amount: 1, insured: false}, {amount: -0.01, insured: false}]}}, "!error: InputValidationFailed"], + [{applicant: {weight: -0.5, vip: null, limit: 467, urgent: false, parcels: [{amount: 2, insured: true}, {amount: 1, insured: true}, {amount: 0.1, insured: false}]}}, {applicant: {limit: 467, net: true, parcels: [{amount: 2, exposure: false, insured: true, margin: "none", review: {a: "2", v: "2025-01"}, surcharge: false}, {amount: 1, exposure: false, insured: true, margin: "none", review: {a: "1", v: "2025-01"}, surcharge: false}, {amount: 0.1, exposure: false, insured: false, margin: "none", review: {a: "0.1", v: "2025-01"}, surcharge: false}], scores: {bucket: "US"}, urgent: false, vip: null, weight: -0.5}}], + [{applicant: {weight: 1, vip: true, limit: -0.01, dueDate: "2000-01-01", active: false, urgent: true, parcels: [{amount: 0.000001, insured: true}, {amount: 1e3, insured: true}, {amount: 18, insured: false}, {amount: 1e3, insured: true}, {amount: -1, insured: false}]}}, {applicant: {active: false, dueDate: "2000-01-01", limit: -0.01, net: true, parcels: [{amount: 0.000001, exposure: true, insured: true, margin: "none", review: {a: "0.000001", v: "2000-01"}, surcharge: true}, {amount: 1000, exposure: true, insured: true, margin: "none", review: {a: "1000", v: "2000-01"}, surcharge: true}, {amount: 18, exposure: true, insured: false, margin: "none", review: {a: "18", v: "2000-01"}, surcharge: true}, {amount: 1000, exposure: true, insured: true, margin: "none", review: {a: "1000", v: "2000-01"}, surcharge: true}, {amount: -1, exposure: true, insured: false, margin: "1", review: {a: "-1", v: "2000-01"}, surcharge: true}], scores: {bucket: "1/5"}, urgent: true, vip: true, weight: 1}}], + [{applicant: {weight: 137, vip: true, limit: 123456789.123, dueDate: "2030-12-31", active: true, urgent: true, parcels: [{amount: -1, insured: false}, {amount: 1e3, insured: true}, {amount: 7.25, insured: true}, {amount: 7.25, insured: true}, {amount: 65, insured: false}, {amount: 1, insured: true}, {amount: -500, insured: true}, {amount: 2, insured: true}, {amount: 1000, insured: false}, {amount: 1e3, insured: true}, {amount: 65, insured: false}, {amount: 99.99, insured: false}, {amount: 18, insured: false}, {amount: 0.000001, insured: false}], extraField: {nested: true}}}, {applicant: {active: true, dueDate: "2030-12-31", extraField: {nested: true}, limit: 123456789.123, net: true, parcels: [{amount: -1, exposure: true, insured: false, margin: "1", review: {a: "-1", v: "2030-12"}, surcharge: true}, {amount: 1000, exposure: true, insured: true, margin: "none", review: {a: "1000", v: "2030-12"}, surcharge: true}, {amount: 7.25, exposure: true, insured: true, margin: "none", review: {a: "7.25", v: "2030-12"}, surcharge: true}, {amount: 7.25, exposure: true, insured: true, margin: "none", review: {a: "7.25", v: "2030-12"}, surcharge: true}, {amount: 65, exposure: true, insured: false, margin: "none", review: {a: "65", v: "2030-12"}, surcharge: true}, {amount: 1, exposure: true, insured: true, margin: "none", review: {a: "1", v: "2030-12"}, surcharge: true}, {amount: -500, exposure: true, insured: true, margin: "500", review: {a: "-500", v: "2030-12"}, surcharge: true}, {amount: 2, exposure: true, insured: true, margin: "none", review: {a: "2", v: "2030-12"}, surcharge: true}, {amount: 1000, exposure: true, insured: false, margin: "none", review: {a: "1000", v: "2030-12"}, surcharge: true}, {amount: 1000, exposure: true, insured: true, margin: "none", review: {a: "1000", v: "2030-12"}, surcharge: true}, {amount: 65, exposure: true, insured: false, margin: "none", review: {a: "65", v: "2030-12"}, surcharge: true}, {amount: 99.99, exposure: true, insured: false, margin: "none", review: {a: "99.99", v: "2030-12"}, surcharge: true}, {amount: 18, exposure: true, insured: false, margin: "none", review: {a: "18", v: "2030-12"}, surcharge: true}, {amount: 0.000001, exposure: true, insured: false, margin: "none", review: {a: "0.000001", v: "2030-12"}, surcharge: true}], scores: {bucket: "137/14"}, urgent: true, vip: true, weight: 137}}], + [{applicant: {weight: 146, vip: true, limit: -0.01, dueDate: "2024-01-01", active: true, urgent: true, parcels: [{amount: -500, insured: false}, {amount: 99.99, insured: true}]}}, {applicant: {active: true, dueDate: "2024-01-01", limit: -0.01, net: true, parcels: [{amount: -500, exposure: true, insured: false, margin: "500", review: {a: "-500", v: "2024-01"}, surcharge: true}, {amount: 99.99, exposure: true, insured: true, margin: "none", review: {a: "99.99", v: "2024-01"}, surcharge: true}], scores: {bucket: "146/2"}, urgent: true, vip: true, weight: 146}}], + [{applicant: {weight: 123456789.123, vip: true, limit: -0, dueDate: "1990-06-15", active: true, urgent: false, parcels: [{amount: 7.25, insured: false}, {amount: 1000, insured: true}]}}, {applicant: {active: true, dueDate: "1990-06-15", limit: 0, net: true, parcels: [{amount: 7.25, exposure: true, insured: false, margin: "none", review: {a: "7.25", v: "1990-06"}, surcharge: true}, {amount: 1000, exposure: true, insured: true, margin: "none", review: {a: "1000", v: "1990-06"}, surcharge: true}], scores: {bucket: "true/0"}, urgent: false, vip: true, weight: 123456789.123}, total: true}], + [{applicant: {weight: null, vip: false, limit: 7.25, dueDate: null, active: null, urgent: true, parcels: [{amount: 0.000001, insured: false}, {amount: 325, insured: true}]}}, {applicant: {active: null, dueDate: null, limit: 7.25, net: false, parcels: [{amount: 0.000001, exposure: false, insured: false, margin: "none", review: {a: "0.000001", v: "2025-01"}, surcharge: false}, {amount: 325, exposure: false, insured: true, margin: "none", review: {a: "325", v: "2025-01"}, surcharge: false}], scores: {bucket: "false/7.25"}, urgent: true, vip: false, weight: null}, total: null}], + [{applicant: {vip: null, limit: 2, urgent: true, parcels: [{amount: -0, insured: true}]}}, {applicant: {limit: 2, net: false, parcels: [{amount: 0, exposure: false, insured: true, margin: "none", review: {a: "0", v: "2025-01"}, surcharge: false}], scores: {bucket: "false/2"}, urgent: true, vip: null}, total: null}], + [{applicant: {weight: 65, vip: false, limit: 2, dueDate: "2030-12-31", active: false, urgent: true, parcels: [{amount: 0.5, insured: false}, {amount: -0, insured: false}, {amount: 99.99, insured: true}, {amount: 1e3, insured: false}, {amount: 0.1, insured: true}, {amount: 5, insured: true}, {amount: 1000, insured: false}, {amount: 123456789.123, insured: true}, {amount: 0.5, insured: false}]}}, {applicant: {active: false, dueDate: "2030-12-31", limit: 2, net: true, parcels: [{amount: 0.5, exposure: true, insured: false, margin: "none", review: {a: "0.5", v: "2030-12"}, surcharge: false}, {amount: 0, exposure: true, insured: false, margin: "none", review: {a: "0", v: "2030-12"}, surcharge: false}, {amount: 99.99, exposure: true, insured: true, margin: "none", review: {a: "99.99", v: "2030-12"}, surcharge: false}, {amount: 1000, exposure: true, insured: false, margin: "none", review: {a: "1000", v: "2030-12"}, surcharge: false}, {amount: 0.1, exposure: true, insured: true, margin: "none", review: {a: "0.1", v: "2030-12"}, surcharge: false}, {amount: 5, exposure: true, insured: true, margin: "none", review: {a: "5", v: "2030-12"}, surcharge: false}, {amount: 1000, exposure: true, insured: false, margin: "none", review: {a: "1000", v: "2030-12"}, surcharge: false}, {amount: 123456789.123, exposure: true, insured: true, margin: "none", review: {a: "123456789.123", v: "2030-12"}, surcharge: false}, {amount: 0.5, exposure: true, insured: false, margin: "none", review: {a: "0.5", v: "2030-12"}, surcharge: false}], scores: {bucket: "US"}, urgent: true, vip: false, weight: 65}}], + [{applicant: {weight: 1000, vip: true, limit: 123456789.123, dueDate: "2025-03-20", active: false, urgent: true, parcels: [{amount: 100, insured: false}, {amount: 250, insured: true}, {amount: 0, insured: false}, {amount: 99.99, insured: true}], extraField: "x"}}, {applicant: {active: false, dueDate: "2025-03-20", extraField: "x", limit: 123456789.123, net: true, parcels: [{amount: 100, exposure: true, insured: false, margin: "none", review: {a: "100", v: "2025-03"}, surcharge: true}, {amount: 250, exposure: true, insured: true, margin: "none", review: {a: "250", v: "2025-03"}, surcharge: true}, {amount: 0, exposure: true, insured: false, margin: "none", review: {a: "0", v: "2025-03"}, surcharge: true}, {amount: 99.99, exposure: true, insured: true, margin: "none", review: {a: "99.99", v: "2025-03"}, surcharge: true}], scores: {bucket: "1000/4"}, urgent: true, vip: true, weight: 1000}}], + [{applicant: {weight: 0.5, vip: true, limit: -1, dueDate: "2030-12-31", urgent: false, parcels: [{amount: 1e3, insured: false}]}}, {applicant: {dueDate: "2030-12-31", limit: -1, net: true, parcels: [{amount: 1000, exposure: true, insured: false, margin: "none", review: {a: "1000", v: "2030-12"}, surcharge: true}], scores: {bucket: "false/-1"}, urgent: false, vip: true, weight: 0.5}, total: null}], + [{applicant: {weight: 5, vip: true, limit: -500, dueDate: "2000-01-01", active: true, urgent: true, parcels: []}}, {applicant: {active: true, dueDate: "2000-01-01", limit: -500, net: true, parcels: [], scores: {bucket: "5/0"}, urgent: true, vip: true, weight: 5}}], + [{applicant: {weight: 100, vip: false, limit: 0.5, dueDate: "2030-12-31", active: true, urgent: false, parcels: [{amount: -0.01, insured: true}, {amount: 99999999999999999999, insured: false}]}}, {applicant: {active: true, dueDate: "2030-12-31", limit: 0.5, net: true, parcels: [{amount: -0.01, exposure: true, insured: true, margin: "0.01", review: {a: "-0.01", v: "2030-12"}, surcharge: false}, {amount: 99999999999999999999, exposure: true, insured: false, margin: "none", review: {a: "99999999999999999999", v: "2030-12"}, surcharge: false}], scores: {bucket: "US"}, urgent: false, vip: false, weight: 100}}], + ], +} + +// seed 344100 (attempt 0) +{ + name: "b 42: account/loans: 4 assertion, 3 expression, 1 match, 2 table; 8 root, 4 per-member, 0 top-level computed", + policy: { + models: {account: {score: "number", channel: "string", label: "string?", vip: "boolean?", urgent: "boolean?", loans: "loan[]"}, loan: {qty: "number?", label: "string"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {assertion: "account.fee", conditions: [["and", "len(account.channel) > 2", 0], ["or", "((account.vip ?? false) or (account.urgent ?? false))", 0], ["or", "(account.label == null or ((account.urgent ?? false) and (account.vip ?? false)))", 0], "50 == factor", "some(account.loans, not ((#.qty ?? 0) <= 18))"]}, + {expression: "account.scores.total", value: "map(account.loans, ((#.qty ?? 0) > 2 ? (#.qty ?? 0) : (#.qty ?? 0)))"}, + {assertion: "loan.margin", conditions: [["and", "isNumeric(((account.label ?? '') + '-' + loan.label))", 1], ["or", "(loan.qty ?? 0) == 1", 0]]}, + {table: "t4", hit: "collect", inputs: ["(min(account.scores.total) ?? 0)", "factor"], outputs: ["account.eligible", "account.band", "account.points"], rules: [ + [">= 5", ">= 0.5", "(account.vip ?? false)", "", "account.score > account.score"], + ["< 3", "", "(account.vip ?? false)", "factor", "(account.vip ?? false)"], + ["", "", "(account.urgent ?? false)", "(min(account.scores.total) ?? 0)", "account.fee"], + ["[5..409]", "", "account.channel in ['Oslo', 'DE']", "factor", "(account.urgent ?? false)"], + ["!= 1", "< 1", "matches(account.channel, '[0-9]$')", "", ""], + ["", "> 1000", "((account.vip ?? false) and (account.vip ?? false))", "(factor + account.score)", ""], + ]}, + {expression: "loan.totals.exposure", value: "(split(((account.vip ?? false) ? 'US' : loan.label), '-')[1] ?? 'none')"}, + {assertion: "loan.decision", conditions: [["and", "all(account.loans, (#.qty ?? 0) <= 50)", 1], "(account.fee and loan.margin)", ["or", "isNumeric((account.label ?? ''))", 0], ["and", "len(filter(account.loans, (#.margin and #.margin))) < factor", 1]]}, + {table: "t7", hit: "collect", inputs: ["(min([abs(factor), 1000]) ^ 2)", "(min(account.band) ?? 0)", "number(string(account.score))"], outputs: ["account.flags.flag"], rules: [ + ["50, 0.5", "!= 10", "< 10", "account.score"], + ["", "", "> 250", "18"], + [">= 0", "", "2", "factor"], + ["10, 50", "!= 100", "< 1000", "account.score"], + ]}, + {assertion: "account.flags.bonus", conditions: ["((account.vip ?? false) and (account.urgent ?? false))", "factor in (14..85]"]}, + {match: "loan.totals.summary", arms: [["matches(string(factor), '^[A-Z]')", "((loan.decision or loan.decision) ? (loan.totals.exposure + '-' + loan.label) : string(loan.decision))"], ["", "string((account.vip ?? false))"]]}, + {expression: "account.flags.surcharge", value: "-(factor) > account.score"}, + ], + }, + cases: [ + [{factor: 100, account: {score: 5, channel: "", label: " pad ", vip: true, urgent: false, loans: [{qty: 10}, {qty: 1000000, label: "3.5"}, {qty: 1.5, label: "Oslo"}, {qty: 1, label: "a"}, {qty: 1.5, label: "3.5"}]}}, {account: {band: [100, 1], channel: "", eligible: [true, false], fee: false, flags: {bonus: false, flag: [], surcharge: false}, label: " pad ", loans: [{qty: 10, totals: {exposure: "none", summary: "true"}}, {label: "3.5", qty: 1000000, totals: {exposure: "none", summary: "true"}}, {label: "Oslo", qty: 1.5, totals: {exposure: "none", summary: "true"}}, {label: "a", qty: 1, totals: {exposure: "none", summary: "true"}}, {label: "3.5", qty: 1.5, totals: {exposure: "none", summary: "true"}}], points: [true, false], score: 5, scores: {total: [10, 1000000, 1.5, 1, 1.5]}, urgent: false, vip: true}, factor: 100}], + [{factor: 100, account: {score: 1, channel: "a-b-c", label: "Zed", vip: 1, urgent: true, loans: []}}, "!error: InputValidationFailed"], + [{factor: 0.5, account: {score: 2, channel: "O'Neil", label: "US", urgent: false, loans: [{label: "DE"}, {qty: 7.25, label: "gold"}, {label: "A1"}, {qty: null, label: "x-y"}, {label: "US"}]}}, {account: {band: [0.5, 0], channel: "O'Neil", eligible: [false, false, false], fee: false, flags: {bonus: false, flag: [0.5], surcharge: false}, label: "US", loans: [{label: "DE", totals: {exposure: "none", summary: "false"}}, {label: "gold", qty: 7.25, totals: {exposure: "none", summary: "false"}}, {label: "A1", totals: {exposure: "none", summary: "false"}}, {label: "x-y", qty: null, totals: {exposure: "y", summary: "false"}}, {label: "US", totals: {exposure: "none", summary: "false"}}], points: [false, false], score: 2, scores: {total: [0, 7.25, 0, 0, 0]}, urgent: false}, factor: 0.5}], + [{factor: 10, account: {score: 0, channel: "retail", label: "gold", vip: false, urgent: true, loans: [], extraField: "x"}}, "!error: ExpressionFailed"], + [{factor: 0, account: {score: 50, channel: "O'Neil", label: "3.5", vip: 1, urgent: false, loans: [{qty: 5, label: "NL"}, {qty: 2, label: "3.5"}]}}, "!error: InputValidationFailed"], + [{factor: 100, account: {score: 5, channel: " pad ", label: "gold", vip: false, urgent: true, loans: [{qty: 10, label: "abc"}, {qty: 18, label: "3.5"}, {qty: 0.5, label: "O'Neil"}, {qty: 100, label: "gold"}], extraField: 1}}, {account: {band: [100, 0.5], channel: " pad ", eligible: [false, true], extraField: 1, fee: true, flags: {bonus: false, flag: [], surcharge: false}, label: "gold", loans: [{label: "abc", qty: 10, totals: {exposure: "none", summary: "false"}}, {label: "3.5", qty: 18, totals: {exposure: "none", summary: "false"}}, {label: "O'Neil", qty: 0.5, totals: {exposure: "none", summary: "false"}}, {label: "gold", qty: 100, totals: {exposure: "none", summary: "false"}}], points: [false, true], score: 5, scores: {total: [10, 18, 0.5, 100]}, urgent: true, vip: false}, factor: 100}], + [{factor: 10, account: {score: 1.5, channel: "NL", vip: true, urgent: false, loans: []}}, "!error: ExpressionFailed"], + [{factor: 100, account: {score: 10, channel: "DE", label: "gold", vip: false, urgent: false, loans: [{qty: 10, label: "A1"}]}}, {account: {band: [10, 100], channel: "DE", eligible: [false, false, true], fee: false, flags: {bonus: false, flag: [], surcharge: false}, label: "gold", loans: [{label: "A1", qty: 10, totals: {exposure: "none", summary: "false"}}], points: [false, false, false], score: 10, scores: {total: [10]}, urgent: false, vip: false}, factor: 100}], + [{factor: -2, account: {score: 457, channel: "retail", label: "a", vip: true, urgent: true, loans: []}}, "!error: ExpressionFailed"], + [{factor: 100, account: {score: 397, channel: "a-b-c", vip: true, loans: [{qty: 10, label: "abc"}]}}, {account: {band: [10, 100], channel: "a-b-c", eligible: [true, false, false], fee: false, flags: {bonus: false, flag: [18], surcharge: false}, loans: [{label: "abc", qty: 10, totals: {exposure: "none", summary: "true"}}], points: [false, false, false], score: 397, scores: {total: [10]}, vip: true}, factor: 100}], + [{factor: -2, account: {score: 1, channel: false, label: "gold", vip: false, urgent: false, loans: [{qty: 50, label: "Zed"}, {qty: 50, label: "a"}]}}, "!error: InputValidationFailed"], + [{factor: 10, account: {score: 18, channel: "US", label: "DE", vip: true, urgent: true, loans: [{qty: 1.5, label: "x-y"}, {qty: 2.50, label: "Oslo"}, {qty: 371, label: "gold"}]}}, {account: {band: [10, 1.5], channel: "US", eligible: [true, true], fee: true, flags: {bonus: false, flag: [], surcharge: false}, label: "DE", loans: [{label: "x-y", qty: 1.5, totals: {exposure: "none", summary: "true"}}, {label: "Oslo", qty: 2.50, totals: {exposure: "none", summary: "true"}}, {label: "gold", qty: 371, totals: {exposure: "none", summary: "true"}}], points: [true, true], score: 18, scores: {total: [1.5, 2.50, 371]}, urgent: true, vip: true}, factor: 10}], + [{factor: 10, account: {score: 250, channel: "12", vip: null, urgent: false, loans: []}}, "!error: ExpressionFailed"], + [{factor: 0.5, account: {score: -0.01, channel: "DE", label: "retail", vip: true, urgent: true, loans: []}}, "!error: ExpressionFailed"], + [{factor: 0.5, account: {score: 2, channel: "US", label: "NL", loans: [{qty: 1000, label: "gold"}]}}, {account: {band: [1000], channel: "US", eligible: [false, false, false], fee: false, flags: {bonus: false, flag: [0.5], surcharge: false}, label: "NL", loans: [{label: "gold", qty: 1000, totals: {exposure: "none", summary: "false"}}], points: [false, false], score: 2, scores: {total: [1000]}}, factor: 0.5}], + [{factor: -2, account: {score: 3, channel: "abc", label: "O'Neil", vip: true, urgent: false, loans: [{qty: 100, label: "12"}, {qty: 2, label: "DE"}, {qty: 250, label: "O'Neil"}]}}, {account: {band: [-2, 2], channel: "abc", eligible: [true, false, false], fee: true, flags: {bonus: false, flag: [], surcharge: false}, label: "O'Neil", loans: [{label: "12", qty: 100, totals: {exposure: "none", summary: "true"}}, {label: "DE", qty: 2, totals: {exposure: "none", summary: "true"}}, {label: "O'Neil", qty: 250, totals: {exposure: "none", summary: "true"}}], points: [true, true], score: 3, scores: {total: [100, 2, 250]}, urgent: false, vip: true}, factor: -2}], + [{factor: 1, account: {score: 50, channel: "retail", label: "retail", vip: true, urgent: "true", loans: [{qty: 250, label: "NL"}, {qty: 65, label: "retail"}, {qty: -1, label: ""}, {qty: -500, label: ""}, {qty: 50, label: ""}]}}, "!error: InputValidationFailed"], + ], +} + +// seed 344201 (attempt 1) +{ + name: "b 43: borrower/parcels/drivers + report: 1 assertion, 4 expression, 3 match, 4 table; 3 root, 4 per-member, 1 top-level computed", + policy: { + models: {borrower: {weight: "number?", verified: "boolean?", tier: "string(gold|silver|bronze)", since: "date", price: "number", parcels: "parcel[]", report: "creditReport"}, parcel: {balance: "number?", flagged: "boolean", region: "string", birthDate: "date", drivers: "driver[]"}, driver: {days: "number", vip: "boolean", dueDate: "date?"}, creditReport: {rate: "number"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {expression: "parcel.capped", value: "filter(parcel.drivers, #.days in [21..169))"}, + {table: "t2", inputs: ["borrower.price", "(baseRate * (borrower.weight ?? 0))", null], outputs: ["borrower.points[]"], rules: [ + ["[3..67]", "", "borrower.since.isAfter(d('2024-01-01'), 'year')", "(borrower.verified ?? false)"], + ["1000", "> 0.5", "borrower.report.rate in [26..212]", "(borrower.verified ?? false)"], + ["> 18", ">= 250", "", "(borrower.verified ?? false)"], + ["[1..15]", "", "borrower.price > (borrower.weight ?? 0)", "(borrower.verified ?? false)"], + ["[100..327]", "> 100", "borrower.report.rate != borrower.report.rate", "(borrower.verified ?? false)"], + ["", "", "", ""], + ]}, + {match: "creditReport.tag", arms: [["(borrower.weight ?? 0) > borrower.price", "(borrower.verified == null ? `${baseRate}/${(borrower.verified ?? false)}` : `${(borrower.verified ?? false)}/${(borrower.verified ?? false)}`)"], ["", "((borrower.verified ?? false) ? 'Oslo' : 'a')"]]}, + {assertion: "creditReport.share", conditions: [["and", "count(borrower.parcels, (#.flagged or #.flagged)) >= borrower.price", 1]]}, + {expression: "creditReport.flags.segment", value: "filter(borrower.parcels, (#.flagged and #.flagged))"}, + {table: "t6", hit: "collect", inputs: ["parcel.birthDate"], outputs: ["parcel.totals.margin"], rules: [ + ["", "(parcel.balance ?? 0)"], + ["", "(parcel.balance ?? 0)"], + ["", "1.5"], + ["< d('2025-01-01')", "(parcel.balance ?? 0)"], + ["> d('2025-01-01')", "baseRate"], + ["", "borrower.report.rate"], + ["", "borrower.price"], + ]}, + {match: "borrower.eligible", arms: [["contains(['DE', 'retail', ''], borrower.report.tag)", "string((borrower.verified ?? false))"], ["baseRate in (41..52)", "(split(borrower.report.tag, '-')[1] ?? 'none')"], ["(borrower.price + 0.5) >= baseRate", "`${(borrower.verified ?? false)}/${(borrower.weight ?? 0) != (borrower.weight ?? 0)}`"], ["1000 != baseRate", "borrower.report.tag"], ["", "borrower.since.format('%Y')"]]}, + {table: "t8", inputs: [null, "(borrower.weight ?? 0)"], outputs: ["creditReport.level[]"], rules: [ + ["not ((borrower.verified ?? false))", "!= 250", "matches(creditReport.tag, '[0-9]$')"], + ["", "< 0.25", "creditReport.share"], + ]}, + {expression: "parcel.net", value: "borrower.weight"}, + {match: "weighted", arms: [["(borrower.weight ?? 0) == (borrower.weight ?? 0)", "2"], ["borrower.report.tag != 'a'", "(borrower.weight ?? 0)"], ["((borrower.verified ?? false) or (borrower.verified ?? false))", "((borrower.weight ?? 0)) / (abs(baseRate) + 1)"], ["", "trunc(baseRate)"]]}, + {table: "t11", hit: "collect", inputs: ["borrower.tier", "borrower.eligible", "borrower.price"], outputs: ["parcel.totals.quota"], rules: [ + ["'gold', 'bronze'", "", "100", "weighted"], + ["'silver', 'bronze'", "'US', 'none'", "!= 1.5", "abs((borrower.weight ?? 0))"], + ["'silver'", "'VIP'", "!= 1", "(parcel.balance ?? 0)"], + ["'gold'", "'ok', 'none'", "", "len(filter(parcel.drivers, (#.vip or #.vip)))"], + ["'silver'", "'low'", "", "(min([abs(baseRate), 1000]) ^ 0)"], + ["", "'VIP'", "3", "baseRate"], + ]}, + {expression: "borrower.penalty", value: "min([100, (borrower.weight ?? 0)])"}, + ], + }, + cases: [ + [{baseRate: 100, borrower: {weight: 250, verified: true, tier: "gold", since: "1990-06-15", price: 250, parcels: [], report: {rate: 0.000001}}}, {baseRate: 100, borrower: {eligible: "true/false", parcels: [], penalty: 100, points: [true], price: 250, report: {flags: {segment: []}, level: [], rate: 0.000001, tag: "Oslo"}, since: "1990-06-15", tier: "gold", verified: true, weight: 250}}], + [{baseRate: 1, borrower: {weight: 18, verified: false, tier: "bronze", since: "2025-03-20", price: 1, parcels: [], report: {rate: 99.99}}}, {baseRate: 1, borrower: {eligible: "false/false", parcels: [], penalty: 18, points: [], price: 1, report: {flags: {segment: []}, level: [false], rate: 99.99, tag: "false/false"}, since: "2025-03-20", tier: "bronze", verified: false, weight: 18}}], + [{baseRate: 100, borrower: {weight: 100, verified: true, tier: "gold", since: "2024-01-01", price: 1.5, parcels: [{balance: 100, flagged: false, region: "O'Neil", birthDate: "2024-01-01", drivers: [{days: 18, vip: false, dueDate: "2025-03-20T10:15:30Z"}, {days: 18, vip: true, dueDate: "2024-01-01"}, {days: 10, vip: false, dueDate: "2000-01-01"}]}], report: {rate: -500}, extraField: {nested: true}}}, {baseRate: 100, borrower: {eligible: "true/true", extraField: {nested: true}, parcels: [{balance: 100, birthDate: "2024-01-01", capped: [], drivers: [{days: 18, dueDate: "2025-03-20T10:15:30Z", vip: false}, {days: 18, dueDate: "2024-01-01", vip: true}, {days: 10, dueDate: "2000-01-01", vip: false}], flagged: false, net: 100, region: "O'Neil", totals: {margin: [100, 100, 1.5, 100, -500, 1.5], quota: []}}], penalty: 100, points: [], price: 1.5, report: {flags: {segment: []}, level: [], rate: -500, tag: "true/true"}, since: "2024-01-01", tier: "gold", verified: true, weight: 100}}], + [{baseRate: -2, borrower: {verified: false, tier: "silver", since: "2030-12-31", price: 0.25, parcels: [{balance: null, flagged: true, region: "retail", birthDate: "2000-01-01", drivers: [{days: 1000, vip: false}, {days: 1, vip: true, dueDate: "2024-02-29"}, {days: 5, vip: false}]}, {balance: 1000000, flagged: true, region: "DE", birthDate: "2024-01-01", drivers: [{days: 10, vip: false}, {days: 1000, vip: false}, {days: 250, vip: true, dueDate: "1990-06-15"}]}], report: {rate: 0}}}, {baseRate: -2, borrower: {eligible: "false/false", parcels: [{balance: null, birthDate: "2000-01-01", capped: [], drivers: [{days: 1000, vip: false}, {days: 1, dueDate: "2024-02-29", vip: true}, {days: 5, vip: false}], flagged: true, net: null, region: "retail", totals: {margin: [0, 0, 1.5, 0, 0, 0.25], quota: []}}, {balance: 1000000, birthDate: "2024-01-01", capped: [], drivers: [{days: 10, vip: false}, {days: 1000, vip: false}, {days: 250, dueDate: "1990-06-15", vip: true}], flagged: true, net: null, region: "DE", totals: {margin: [1000000, 1000000, 1.5, 1000000, 0, 0.25], quota: []}}], penalty: 0, points: [], price: 0.25, report: {flags: {segment: [{balance: null, birthDate: "2000-01-01", capped: [], drivers: [{days: 1000, vip: false}, {days: 1, dueDate: "2024-02-29", vip: true}, {days: 5, vip: false}], flagged: true, net: null, region: "retail", totals: {margin: [0, 0, 1.5, 0, 0, 0.25], quota: []}}, {balance: 1000000, birthDate: "2024-01-01", capped: [], drivers: [{days: 10, vip: false}, {days: 1000, vip: false}, {days: 250, dueDate: "1990-06-15", vip: true}], flagged: true, net: null, region: "DE", totals: {margin: [1000000, 1000000, 1.5, 1000000, 0, 0.25], quota: []}}]}, level: [false, true], rate: 0, share: true, tag: "a"}, since: "2030-12-31", tier: "silver", verified: false}}], + [{baseRate: -2, borrower: {weight: 18, verified: true, tier: "gold", since: "2030-12-31", price: 1000, parcels: [], report: {rate: 0.25}}}, {baseRate: -2, borrower: {eligible: "true/false", parcels: [], penalty: 18, points: [], price: 1000, report: {flags: {segment: []}, level: [], rate: 0.25, tag: "Oslo"}, since: "2030-12-31", tier: "gold", verified: true, weight: 18}}], + [{baseRate: 10, borrower: {weight: 18, tier: "bronze", since: "2030-12-31", price: 7.25, parcels: [{balance: null, flagged: true, region: "none", birthDate: "2030-12-31", drivers: [{days: -500, vip: true}, {days: 18, vip: false, dueDate: "1990-06-15"}]}, {balance: 10, flagged: false, region: "none", birthDate: "2025-03-20T10:15:30Z", drivers: [{days: 0, vip: false, dueDate: "2024-01-01"}, {days: 250, vip: true, dueDate: null}, {days: 10, vip: false, dueDate: null}]}, {flagged: true, region: "3.5", birthDate: "2025-03-20T10:15:30Z", drivers: []}], report: {rate: 1}}}, {baseRate: 10, borrower: {eligible: "10/false", parcels: [{balance: null, birthDate: "2030-12-31", capped: [], drivers: [{days: -500, vip: true}, {days: 18, dueDate: "1990-06-15", vip: false}], flagged: true, net: 18, region: "none", totals: {margin: [0, 0, 1.5, 10, 1, 7.25], quota: []}}, {balance: 10, birthDate: "2025-03-20T10:15:30Z", capped: [], drivers: [{days: 0, dueDate: "2024-01-01", vip: false}, {days: 250, dueDate: null, vip: true}, {days: 10, dueDate: null, vip: false}], flagged: false, net: 18, region: "none", totals: {margin: [10, 10, 1.5, 10, 1, 7.25], quota: []}}, {birthDate: "2025-03-20T10:15:30Z", capped: [], drivers: [], flagged: true, net: 18, region: "3.5", totals: {margin: [0, 0, 1.5, 10, 1, 7.25], quota: []}}], penalty: 18, points: [false], price: 7.25, report: {flags: {segment: [{balance: null, birthDate: "2030-12-31", capped: [], drivers: [{days: -500, vip: true}, {days: 18, dueDate: "1990-06-15", vip: false}], flagged: true, net: 18, region: "none", totals: {margin: [0, 0, 1.5, 10, 1, 7.25], quota: []}}, {birthDate: "2025-03-20T10:15:30Z", capped: [], drivers: [], flagged: true, net: 18, region: "3.5", totals: {margin: [0, 0, 1.5, 10, 1, 7.25], quota: []}}]}, level: [false], rate: 1, tag: "10/false"}, since: "2030-12-31", tier: "bronze", weight: 18}}], + [{baseRate: 0, borrower: {weight: 0, verified: null, tier: "gold", since: "2030-12-31", price: 1000, parcels: [{balance: -0, flagged: true, region: "-", birthDate: "2024-02-29", drivers: [{days: 1000, vip: false, dueDate: null}]}], report: {rate: 1}}}, {baseRate: 0, borrower: {eligible: "false/false", parcels: [{balance: 0, birthDate: "2024-02-29", capped: [], drivers: [{days: 1000, dueDate: null, vip: false}], flagged: true, net: 0, region: "-", totals: {margin: [0, 0, 1.5, 0, 1, 1000], quota: []}}], penalty: 0, points: [], price: 1000, report: {flags: {segment: [{balance: 0, birthDate: "2024-02-29", capped: [], drivers: [{days: 1000, dueDate: null, vip: false}], flagged: true, net: 0, region: "-", totals: {margin: [0, 0, 1.5, 0, 1, 1000], quota: []}}]}, level: [false, false], rate: 1, share: false, tag: "a"}, since: "2030-12-31", tier: "gold", verified: null, weight: 0}}], + [{baseRate: 1, borrower: {weight: 1, verified: false, tier: "silver", since: "2025-03-20T10:15:30Z", price: -0, parcels: [{balance: 18, flagged: true, region: "VIP", birthDate: "2025-03-20T10:15:30Z", drivers: [{days: 99999999999999999999, vip: false, dueDate: "2024-02-29"}, {days: 1, vip: false, dueDate: "1990-06-15"}, {days: 3, vip: true, dueDate: "2024-02-29"}]}, {balance: 2.50, flagged: true, region: "low", birthDate: "2025-03-20T10:15:30Z", drivers: [{days: 0.25, vip: false, dueDate: "2025-03-20T10:15:30Z"}, {days: -0.01, vip: true, dueDate: "2024-01-01"}, {days: -1, vip: false, dueDate: "2000-01-01"}]}], report: {rate: 100}}}, {baseRate: 1, borrower: {eligible: "false/false", parcels: [{balance: 18, birthDate: "2025-03-20T10:15:30Z", capped: [], drivers: [{days: 99999999999999999999, dueDate: "2024-02-29", vip: false}, {days: 1, dueDate: "1990-06-15", vip: false}, {days: 3, dueDate: "2024-02-29", vip: true}], flagged: true, net: 1, region: "VIP", totals: {margin: [18, 18, 1.5, 1, 100, 0], quota: []}}, {balance: 2.50, birthDate: "2025-03-20T10:15:30Z", capped: [], drivers: [{days: 0.25, dueDate: "2025-03-20T10:15:30Z", vip: false}, {days: -0.01, dueDate: "2024-01-01", vip: true}, {days: -1, dueDate: "2000-01-01", vip: false}], flagged: true, net: 1, region: "low", totals: {margin: [2.50, 2.50, 1.5, 1, 100, 0], quota: []}}], penalty: 1, points: [], price: 0, report: {flags: {segment: [{balance: 18, birthDate: "2025-03-20T10:15:30Z", capped: [], drivers: [{days: 99999999999999999999, dueDate: "2024-02-29", vip: false}, {days: 1, dueDate: "1990-06-15", vip: false}, {days: 3, dueDate: "2024-02-29", vip: true}], flagged: true, net: 1, region: "VIP", totals: {margin: [18, 18, 1.5, 1, 100, 0], quota: []}}, {balance: 2.50, birthDate: "2025-03-20T10:15:30Z", capped: [], drivers: [{days: 0.25, dueDate: "2025-03-20T10:15:30Z", vip: false}, {days: -0.01, dueDate: "2024-01-01", vip: true}, {days: -1, dueDate: "2000-01-01", vip: false}], flagged: true, net: 1, region: "low", totals: {margin: [2.50, 2.50, 1.5, 1, 100, 0], quota: []}}]}, level: [false], rate: 100, tag: "false/false"}, since: "2025-03-20T10:15:30Z", tier: "silver", verified: false, weight: 1}}], + [{baseRate: 10, borrower: {weight: 0.5, verified: false, tier: "silver", since: "2024-02-29", price: -1, parcels: [], report: {rate: 18}}}, {baseRate: 10, borrower: {eligible: "false/false", parcels: [], penalty: 0.5, points: [], price: -1, report: {flags: {segment: []}, level: [false], rate: 18, tag: "false/false"}, since: "2024-02-29", tier: "silver", verified: false, weight: 0.5}}], + [{baseRate: 10, borrower: {weight: 18, verified: "true", tier: "gold", since: "1990-06-15", price: 1, parcels: [{balance: 250, flagged: true, region: "3.5", birthDate: "2024-01-01", drivers: []}], report: {rate: 0.5}}}, "!error: InputValidationFailed"], + [{baseRate: 0, borrower: {weight: 1000, verified: true, tier: "gold", since: "2025-03-20", price: 18, parcels: [{balance: 1.5, flagged: false, region: "high", birthDate: "2024-02-29", drivers: [{days: 100, vip: true, dueDate: "2030-12-31"}, {days: 123456789.123, vip: true, dueDate: "2024-01-01"}]}, {balance: 0, flagged: true, region: "DE", birthDate: "2025-03-20", drivers: []}, {balance: 100, flagged: false, region: "none", birthDate: "1990-06-15", drivers: [{days: 250, vip: false, dueDate: "2025-03-20T10:15:30Z"}]}, {balance: 0, flagged: false, region: "high", birthDate: "2025-03-20T10:15:30Z", drivers: [{days: 0, vip: false, dueDate: "2025-03-20"}, {days: 100, vip: true, dueDate: "2000-01-01"}]}, {balance: 1000, flagged: true, region: "abc", birthDate: "2025-03-20", drivers: [{days: 100, vip: false, dueDate: "2000-01-01"}, {days: 7.25, vip: true, dueDate: "2025-03-20"}, {days: 10, vip: true, dueDate: "2024-02-29"}]}, {balance: 1000, flagged: false, region: "US", birthDate: "2030-12-31", drivers: [{days: 1000, vip: true, dueDate: "2025-03-20T10:15:30Z"}, {days: 0.5, vip: true, dueDate: "2000-01-01"}]}, {balance: 1000, flagged: true, region: "12", birthDate: "2030-12-31", drivers: []}, {balance: 7.25, flagged: true, region: "VIP", birthDate: "1990-06-15", drivers: []}, {balance: 5, flagged: false, region: "US", birthDate: "2000-01-01", drivers: [{days: 100, vip: false, dueDate: "2030-12-31"}, {days: 1, vip: true, dueDate: "2025-03-20T10:15:30Z"}, {days: 100, vip: false, dueDate: "2025-03-20T10:15:30Z"}]}, {balance: 100, flagged: true, region: "retail", birthDate: "2025-03-20", drivers: []}], report: {rate: -1}}}, {baseRate: 0, borrower: {eligible: "true/false", parcels: [{balance: 1.5, birthDate: "2024-02-29", capped: [{days: 100, dueDate: "2030-12-31", vip: true}], drivers: [{days: 100, dueDate: "2030-12-31", vip: true}, {days: 123456789.123, dueDate: "2024-01-01", vip: true}], flagged: false, net: 1000, region: "high", totals: {margin: [1.5, 1.5, 1.5, 1.5, -1, 18], quota: []}}, {balance: 0, birthDate: "2025-03-20", capped: [], drivers: [], flagged: true, net: 1000, region: "DE", totals: {margin: [0, 0, 1.5, 0, -1, 18], quota: []}}, {balance: 100, birthDate: "1990-06-15", capped: [], drivers: [{days: 250, dueDate: "2025-03-20T10:15:30Z", vip: false}], flagged: false, net: 1000, region: "none", totals: {margin: [100, 100, 1.5, 100, -1, 18], quota: []}}, {balance: 0, birthDate: "2025-03-20T10:15:30Z", capped: [{days: 100, dueDate: "2000-01-01", vip: true}], drivers: [{days: 0, dueDate: "2025-03-20", vip: false}, {days: 100, dueDate: "2000-01-01", vip: true}], flagged: false, net: 1000, region: "high", totals: {margin: [0, 0, 1.5, 0, -1, 18], quota: []}}, {balance: 1000, birthDate: "2025-03-20", capped: [{days: 100, dueDate: "2000-01-01", vip: false}], drivers: [{days: 100, dueDate: "2000-01-01", vip: false}, {days: 7.25, dueDate: "2025-03-20", vip: true}, {days: 10, dueDate: "2024-02-29", vip: true}], flagged: true, net: 1000, region: "abc", totals: {margin: [1000, 1000, 1.5, 0, -1, 18], quota: []}}, {balance: 1000, birthDate: "2030-12-31", capped: [], drivers: [{days: 1000, dueDate: "2025-03-20T10:15:30Z", vip: true}, {days: 0.5, dueDate: "2000-01-01", vip: true}], flagged: false, net: 1000, region: "US", totals: {margin: [1000, 1000, 1.5, 0, -1, 18], quota: []}}, {balance: 1000, birthDate: "2030-12-31", capped: [], drivers: [], flagged: true, net: 1000, region: "12", totals: {margin: [1000, 1000, 1.5, 0, -1, 18], quota: []}}, {balance: 7.25, birthDate: "1990-06-15", capped: [], drivers: [], flagged: true, net: 1000, region: "VIP", totals: {margin: [7.25, 7.25, 1.5, 7.25, -1, 18], quota: []}}, {balance: 5, birthDate: "2000-01-01", capped: [{days: 100, dueDate: "2030-12-31", vip: false}, {days: 100, dueDate: "2025-03-20T10:15:30Z", vip: false}], drivers: [{days: 100, dueDate: "2030-12-31", vip: false}, {days: 1, dueDate: "2025-03-20T10:15:30Z", vip: true}, {days: 100, dueDate: "2025-03-20T10:15:30Z", vip: false}], flagged: false, net: 1000, region: "US", totals: {margin: [5, 5, 1.5, 5, -1, 18], quota: []}}, {balance: 100, birthDate: "2025-03-20", capped: [], drivers: [], flagged: true, net: 1000, region: "retail", totals: {margin: [100, 100, 1.5, 0, -1, 18], quota: []}}], penalty: 100, points: [true], price: 18, report: {flags: {segment: [{balance: 0, birthDate: "2025-03-20", capped: [], drivers: [], flagged: true, net: 1000, region: "DE", totals: {margin: [0, 0, 1.5, 0, -1, 18], quota: []}}, {balance: 1000, birthDate: "2025-03-20", capped: [{days: 100, dueDate: "2000-01-01", vip: false}], drivers: [{days: 100, dueDate: "2000-01-01", vip: false}, {days: 7.25, dueDate: "2025-03-20", vip: true}, {days: 10, dueDate: "2024-02-29", vip: true}], flagged: true, net: 1000, region: "abc", totals: {margin: [1000, 1000, 1.5, 0, -1, 18], quota: []}}, {balance: 1000, birthDate: "2030-12-31", capped: [], drivers: [], flagged: true, net: 1000, region: "12", totals: {margin: [1000, 1000, 1.5, 0, -1, 18], quota: []}}, {balance: 7.25, birthDate: "1990-06-15", capped: [], drivers: [], flagged: true, net: 1000, region: "VIP", totals: {margin: [7.25, 7.25, 1.5, 7.25, -1, 18], quota: []}}, {balance: 100, birthDate: "2025-03-20", capped: [], drivers: [], flagged: true, net: 1000, region: "retail", totals: {margin: [100, 100, 1.5, 0, -1, 18], quota: []}}]}, level: [], rate: -1, tag: "true/true"}, since: "2025-03-20", tier: "gold", verified: true, weight: 1000}}], + [{baseRate: 0, borrower: {weight: 0.25, verified: true, tier: "bronze", since: "2024-01-01", price: 100, parcels: [], report: {rate: -500}}}, {baseRate: 0, borrower: {eligible: "true/false", parcels: [], penalty: 0.25, points: [], price: 100, report: {flags: {segment: []}, level: [], rate: -500, tag: "Oslo"}, since: "2024-01-01", tier: "bronze", verified: true, weight: 0.25}}], + [{baseRate: 100, borrower: {weight: null, verified: null, tier: "bronze", since: "2024-01-01", price: 1, parcels: [{balance: 100, flagged: false, region: "retail", birthDate: "1990-06-15", drivers: [{days: 0.000001, vip: true, dueDate: "2030-12-31"}, {days: 1000, vip: true, dueDate: null}, {days: 99.99, vip: false, dueDate: "2025-03-20"}]}, {flagged: true, region: "Zed", birthDate: "1990-06-15", drivers: [{days: 0, vip: false, dueDate: "1990-06-15"}]}, {flagged: false, region: "3.5", birthDate: "2024-01-01", drivers: [{days: 1000, vip: false}, {days: 100, vip: false}]}, {balance: 18, flagged: false, region: "-", birthDate: "1990-06-15", drivers: [{days: 1000, vip: false}, {days: 65, vip: false, dueDate: null}, {days: 0.5, vip: false}]}], report: {rate: 123456789.123}}}, {baseRate: 100, borrower: {eligible: "a", parcels: [{balance: 100, birthDate: "1990-06-15", capped: [{days: 99.99, dueDate: "2025-03-20", vip: false}], drivers: [{days: 0.000001, dueDate: "2030-12-31", vip: true}, {days: 1000, dueDate: null, vip: true}, {days: 99.99, dueDate: "2025-03-20", vip: false}], flagged: false, net: null, region: "retail", totals: {margin: [100, 100, 1.5, 100, 123456789.123, 1], quota: []}}, {birthDate: "1990-06-15", capped: [], drivers: [{days: 0, dueDate: "1990-06-15", vip: false}], flagged: true, net: null, region: "Zed", totals: {margin: [0, 0, 1.5, 0, 123456789.123, 1], quota: []}}, {birthDate: "2024-01-01", capped: [{days: 100, vip: false}], drivers: [{days: 1000, vip: false}, {days: 100, vip: false}], flagged: false, net: null, region: "3.5", totals: {margin: [0, 0, 1.5, 0, 123456789.123, 1], quota: []}}, {balance: 18, birthDate: "1990-06-15", capped: [{days: 65, dueDate: null, vip: false}], drivers: [{days: 1000, vip: false}, {days: 65, dueDate: null, vip: false}, {days: 0.5, vip: false}], flagged: false, net: null, region: "-", totals: {margin: [18, 18, 1.5, 18, 123456789.123, 1], quota: []}}], penalty: 0, points: [false], price: 1, report: {flags: {segment: [{birthDate: "1990-06-15", capped: [], drivers: [{days: 0, dueDate: "1990-06-15", vip: false}], flagged: true, net: null, region: "Zed", totals: {margin: [0, 0, 1.5, 0, 123456789.123, 1], quota: []}}]}, level: [false, true], rate: 123456789.123, share: true, tag: "a"}, since: "2024-01-01", tier: "bronze", verified: null, weight: null}}], + [{baseRate: 10, borrower: {weight: 1000000, verified: true, tier: "bronze", since: "2024-01-01", price: 18, parcels: [{balance: 0.5, flagged: true, region: "a", birthDate: "2025-03-20", drivers: []}, {balance: null, flagged: false, region: "DE", birthDate: "1990-06-15", drivers: [{days: 0.5, vip: false, dueDate: null}, {days: 0, vip: false, dueDate: "2024-01-01"}]}], report: {rate: 1}}}, {baseRate: 10, borrower: {eligible: "true/false", parcels: [{balance: 0.5, birthDate: "2025-03-20", capped: [], drivers: [], flagged: true, net: 1000000, region: "a", totals: {margin: [0.5, 0.5, 1.5, 10, 1, 18], quota: []}}, {balance: null, birthDate: "1990-06-15", capped: [], drivers: [{days: 0.5, dueDate: null, vip: false}, {days: 0, dueDate: "2024-01-01", vip: false}], flagged: false, net: 1000000, region: "DE", totals: {margin: [0, 0, 1.5, 0, 1, 18], quota: []}}], penalty: 100, points: [], price: 18, report: {flags: {segment: [{balance: 0.5, birthDate: "2025-03-20", capped: [], drivers: [], flagged: true, net: 1000000, region: "a", totals: {margin: [0.5, 0.5, 1.5, 10, 1, 18], quota: []}}]}, level: [], rate: 1, tag: "true/true"}, since: "2024-01-01", tier: "bronze", verified: true, weight: 1000000}}], + [{baseRate: 10, borrower: {weight: 1000, verified: true, tier: "gold", since: "2025-03-20T10:15:30Z", price: 10, parcels: [], report: {rate: 0}}}, {baseRate: 10, borrower: {eligible: "true/false", parcels: [], penalty: 100, points: [true], price: 10, report: {flags: {segment: []}, level: [], rate: 0, tag: "true/true"}, since: "2025-03-20T10:15:30Z", tier: "gold", verified: true, weight: 1000}}], + [{baseRate: 10, borrower: {weight: null, tier: "bronze", since: "2024-01-01", price: 1, parcels: [{flagged: true, region: "ok", birthDate: "2024-02-29", drivers: [{days: 100, vip: false, dueDate: "2025-03-20T10:15:30Z"}, {days: 0.5, vip: true, dueDate: null}]}, {flagged: true, region: "12", birthDate: "2025-03-20", drivers: [{days: 100, vip: false, dueDate: null}, {days: -0.5, vip: false, dueDate: "2024-01-01"}, {days: 3, vip: true}]}, {flagged: false, region: "-", birthDate: "2025-03-20", drivers: []}], report: {rate: -1}}}, {baseRate: 10, borrower: {eligible: "a", parcels: [{birthDate: "2024-02-29", capped: [{days: 100, dueDate: "2025-03-20T10:15:30Z", vip: false}], drivers: [{days: 100, dueDate: "2025-03-20T10:15:30Z", vip: false}, {days: 0.5, dueDate: null, vip: true}], flagged: true, net: null, region: "ok", totals: {margin: [0, 0, 1.5, 0, -1, 1], quota: []}}, {birthDate: "2025-03-20", capped: [{days: 100, dueDate: null, vip: false}], drivers: [{days: 100, dueDate: null, vip: false}, {days: -0.5, dueDate: "2024-01-01", vip: false}, {days: 3, vip: true}], flagged: true, net: null, region: "12", totals: {margin: [0, 0, 1.5, 10, -1, 1], quota: []}}, {birthDate: "2025-03-20", capped: [], drivers: [], flagged: false, net: null, region: "-", totals: {margin: [0, 0, 1.5, 10, -1, 1], quota: []}}], penalty: 0, points: [false], price: 1, report: {flags: {segment: [{birthDate: "2024-02-29", capped: [{days: 100, dueDate: "2025-03-20T10:15:30Z", vip: false}], drivers: [{days: 100, dueDate: "2025-03-20T10:15:30Z", vip: false}, {days: 0.5, dueDate: null, vip: true}], flagged: true, net: null, region: "ok", totals: {margin: [0, 0, 1.5, 0, -1, 1], quota: []}}, {birthDate: "2025-03-20", capped: [{days: 100, dueDate: null, vip: false}], drivers: [{days: 100, dueDate: null, vip: false}, {days: -0.5, dueDate: "2024-01-01", vip: false}, {days: 3, vip: true}], flagged: true, net: null, region: "12", totals: {margin: [0, 0, 1.5, 10, -1, 1], quota: []}}]}, level: [false, true], rate: -1, share: true, tag: "a"}, since: "2024-01-01", tier: "bronze", weight: null}}], + [{baseRate: -2, borrower: {weight: 1000, verified: false, tier: "bronze", since: "2024-01-01", price: 1, parcels: [{balance: 0.25, flagged: true, region: "US", birthDate: "1990-06-15", drivers: [{days: 2, vip: true, dueDate: "2030-12-31"}, {days: 1000, vip: true, dueDate: "2025-03-20T10:15:30Z"}]}], report: {rate: 5}}}, {baseRate: -2, borrower: {eligible: "false/false", parcels: [{balance: 0.25, birthDate: "1990-06-15", capped: [], drivers: [{days: 2, dueDate: "2030-12-31", vip: true}, {days: 1000, dueDate: "2025-03-20T10:15:30Z", vip: true}], flagged: true, net: 1000, region: "US", totals: {margin: [0.25, 0.25, 1.5, 0.25, 5, 1], quota: []}}], penalty: 100, points: [], price: 1, report: {flags: {segment: [{balance: 0.25, birthDate: "1990-06-15", capped: [], drivers: [{days: 2, dueDate: "2030-12-31", vip: true}, {days: 1000, dueDate: "2025-03-20T10:15:30Z", vip: true}], flagged: true, net: 1000, region: "US", totals: {margin: [0.25, 0.25, 1.5, 0.25, 5, 1], quota: []}}]}, level: [false], rate: 5, tag: "false/false"}, since: "2024-01-01", tier: "bronze", verified: false, weight: 1000}}], + [{baseRate: 0, borrower: {weight: 0, verified: false, tier: "gold", since: "2025-03-20T10:15:30Z", price: 1.5, parcels: [], report: {rate: 0}}}, {baseRate: 0, borrower: {eligible: "false/false", parcels: [], penalty: 0, points: [false], price: 1.5, report: {flags: {segment: []}, level: [false, false], rate: 0, share: false, tag: "a"}, since: "2025-03-20T10:15:30Z", tier: "gold", verified: false, weight: 0}}], + [{baseRate: -2, borrower: {weight: null, verified: true, tier: "gold", since: "2025-03-20T10:15:30Z", price: 99.99, parcels: [{flagged: true, region: "abc", birthDate: "2000-01-01", drivers: [{days: 3, vip: true}, {days: 2, vip: true, dueDate: "2030-12-31"}]}, {flagged: true, region: "US", birthDate: "2000-01-01", drivers: [{days: 65, vip: false, dueDate: null}, {days: 250, vip: true}, {days: 1, vip: true, dueDate: "2000-01-01"}]}, {balance: 0.5, flagged: true, region: "a-b-c", birthDate: "2025-03-20T10:15:30Z", drivers: [{days: 100, vip: false, dueDate: null}]}, {flagged: true, region: " pad ", birthDate: "2000-01-01", drivers: [{days: 100, vip: true, dueDate: null}, {days: 0, vip: false}]}, {balance: 250, flagged: true, region: "none", birthDate: "2000-01-01", drivers: [{days: 250, vip: false, dueDate: "2024-01-01"}]}], report: {rate: 0.1}}}, {baseRate: -2, borrower: {eligible: "true/false", parcels: [{birthDate: "2000-01-01", capped: [], drivers: [{days: 3, vip: true}, {days: 2, dueDate: "2030-12-31", vip: true}], flagged: true, net: null, region: "abc", totals: {margin: [0, 0, 1.5, 0, 0.1, 99.99], quota: []}}, {birthDate: "2000-01-01", capped: [{days: 65, dueDate: null, vip: false}], drivers: [{days: 65, dueDate: null, vip: false}, {days: 250, vip: true}, {days: 1, dueDate: "2000-01-01", vip: true}], flagged: true, net: null, region: "US", totals: {margin: [0, 0, 1.5, 0, 0.1, 99.99], quota: []}}, {balance: 0.5, birthDate: "2025-03-20T10:15:30Z", capped: [{days: 100, dueDate: null, vip: false}], drivers: [{days: 100, dueDate: null, vip: false}], flagged: true, net: null, region: "a-b-c", totals: {margin: [0.5, 0.5, 1.5, -2, 0.1, 99.99], quota: []}}, {birthDate: "2000-01-01", capped: [{days: 100, dueDate: null, vip: true}], drivers: [{days: 100, dueDate: null, vip: true}, {days: 0, vip: false}], flagged: true, net: null, region: " pad ", totals: {margin: [0, 0, 1.5, 0, 0.1, 99.99], quota: []}}, {balance: 250, birthDate: "2000-01-01", capped: [], drivers: [{days: 250, dueDate: "2024-01-01", vip: false}], flagged: true, net: null, region: "none", totals: {margin: [250, 250, 1.5, 250, 0.1, 99.99], quota: []}}], penalty: 0, points: [], price: 99.99, report: {flags: {segment: [{birthDate: "2000-01-01", capped: [], drivers: [{days: 3, vip: true}, {days: 2, dueDate: "2030-12-31", vip: true}], flagged: true, net: null, region: "abc", totals: {margin: [0, 0, 1.5, 0, 0.1, 99.99], quota: []}}, {birthDate: "2000-01-01", capped: [{days: 65, dueDate: null, vip: false}], drivers: [{days: 65, dueDate: null, vip: false}, {days: 250, vip: true}, {days: 1, dueDate: "2000-01-01", vip: true}], flagged: true, net: null, region: "US", totals: {margin: [0, 0, 1.5, 0, 0.1, 99.99], quota: []}}, {balance: 0.5, birthDate: "2025-03-20T10:15:30Z", capped: [{days: 100, dueDate: null, vip: false}], drivers: [{days: 100, dueDate: null, vip: false}], flagged: true, net: null, region: "a-b-c", totals: {margin: [0.5, 0.5, 1.5, -2, 0.1, 99.99], quota: []}}, {birthDate: "2000-01-01", capped: [{days: 100, dueDate: null, vip: true}], drivers: [{days: 100, dueDate: null, vip: true}, {days: 0, vip: false}], flagged: true, net: null, region: " pad ", totals: {margin: [0, 0, 1.5, 0, 0.1, 99.99], quota: []}}, {balance: 250, birthDate: "2000-01-01", capped: [], drivers: [{days: 250, dueDate: "2024-01-01", vip: false}], flagged: true, net: null, region: "none", totals: {margin: [250, 250, 1.5, 250, 0.1, 99.99], quota: []}}]}, level: [false], rate: 0.1, share: false, tag: "Oslo"}, since: "2025-03-20T10:15:30Z", tier: "gold", verified: true, weight: null}}], + [{baseRate: 100, borrower: {weight: 0, verified: true, tier: "bronze", since: "2025-03-20", price: 1000, parcels: [{balance: 0, flagged: true, region: "é ü", birthDate: "1990-06-15", drivers: [{days: 250, vip: true, dueDate: "1990-06-15"}, {days: 10, vip: false, dueDate: "1990-06-15"}]}, {balance: 250, flagged: false, region: "none", birthDate: "2000-01-01", drivers: [{days: 1, vip: false, dueDate: "2000-01-01"}, {days: 250, vip: false, dueDate: "2025-03-20T10:15:30Z"}]}, {balance: 1000, flagged: true, region: "x", birthDate: "2024-02-29", drivers: []}, {balance: -0.01, flagged: true, region: "VIP", birthDate: "1990-06-15", drivers: [{days: 10, vip: false, dueDate: "2024-01-01"}, {days: 0.25, vip: true, dueDate: "2025-03-20"}]}, {balance: 1, flagged: false, region: "low", birthDate: "2024-01-01", drivers: [{days: -0.5, vip: false, dueDate: "2024-02-29"}, {days: 1000, vip: false, dueDate: "1990-06-15"}, {days: 10, vip: true, dueDate: "2025-03-20"}]}], report: {rate: 100}, extraField: "x"}}, {baseRate: 100, borrower: {eligible: "true/false", extraField: "x", parcels: [{balance: 0, birthDate: "1990-06-15", capped: [], drivers: [{days: 250, dueDate: "1990-06-15", vip: true}, {days: 10, dueDate: "1990-06-15", vip: false}], flagged: true, net: 0, region: "é ü", totals: {margin: [0, 0, 1.5, 0, 100, 1000], quota: []}}, {balance: 250, birthDate: "2000-01-01", capped: [], drivers: [{days: 1, dueDate: "2000-01-01", vip: false}, {days: 250, dueDate: "2025-03-20T10:15:30Z", vip: false}], flagged: false, net: 0, region: "none", totals: {margin: [250, 250, 1.5, 250, 100, 1000], quota: []}}, {balance: 1000, birthDate: "2024-02-29", capped: [], drivers: [], flagged: true, net: 0, region: "x", totals: {margin: [1000, 1000, 1.5, 1000, 100, 1000], quota: []}}, {balance: -0.01, birthDate: "1990-06-15", capped: [], drivers: [{days: 10, dueDate: "2024-01-01", vip: false}, {days: 0.25, dueDate: "2025-03-20", vip: true}], flagged: true, net: 0, region: "VIP", totals: {margin: [-0.01, -0.01, 1.5, -0.01, 100, 1000], quota: []}}, {balance: 1, birthDate: "2024-01-01", capped: [], drivers: [{days: -0.5, dueDate: "2024-02-29", vip: false}, {days: 1000, dueDate: "1990-06-15", vip: false}, {days: 10, dueDate: "2025-03-20", vip: true}], flagged: false, net: 0, region: "low", totals: {margin: [1, 1, 1.5, 1, 100, 1000], quota: []}}], penalty: 0, points: [], price: 1000, report: {flags: {segment: [{balance: 0, birthDate: "1990-06-15", capped: [], drivers: [{days: 250, dueDate: "1990-06-15", vip: true}, {days: 10, dueDate: "1990-06-15", vip: false}], flagged: true, net: 0, region: "é ü", totals: {margin: [0, 0, 1.5, 0, 100, 1000], quota: []}}, {balance: 1000, birthDate: "2024-02-29", capped: [], drivers: [], flagged: true, net: 0, region: "x", totals: {margin: [1000, 1000, 1.5, 1000, 100, 1000], quota: []}}, {balance: -0.01, birthDate: "1990-06-15", capped: [], drivers: [{days: 10, dueDate: "2024-01-01", vip: false}, {days: 0.25, dueDate: "2025-03-20", vip: true}], flagged: true, net: 0, region: "VIP", totals: {margin: [-0.01, -0.01, 1.5, -0.01, 100, 1000], quota: []}}]}, level: [false], rate: 100, share: false, tag: "Oslo"}, since: "2025-03-20", tier: "bronze", verified: true, weight: 0}}], + [{baseRate: 100, borrower: {weight: 250, verified: true, tier: "gold", since: "2025-03-20T10:15:30Z", price: 0.25, parcels: [{balance: 1.5, flagged: true, region: "", birthDate: "2024-02-29", drivers: [{days: 99999999999999999999, vip: true, dueDate: "2000-01-01"}, {days: 100, vip: true, dueDate: "2025-03-20"}]}, {balance: 1, flagged: true, region: "a", birthDate: "2025-03-20", drivers: [{days: -0, vip: true, dueDate: "2025-03-20"}, {days: 7.25, vip: true, dueDate: "2025-03-20"}, {days: 99.99, vip: true, dueDate: "2024-01-01"}]}, {balance: 0, flagged: false, region: "high", birthDate: "2000-01-01", drivers: []}], report: {rate: 486}, extraField: 1}}, {baseRate: 100, borrower: {eligible: "true/true", extraField: 1, parcels: [{balance: 1.5, birthDate: "2024-02-29", capped: [{days: 100, dueDate: "2025-03-20", vip: true}], drivers: [{days: 99999999999999999999, dueDate: "2000-01-01", vip: true}, {days: 100, dueDate: "2025-03-20", vip: true}], flagged: true, net: 250, region: "", totals: {margin: [1.5, 1.5, 1.5, 1.5, 486, 0.25], quota: []}}, {balance: 1, birthDate: "2025-03-20", capped: [{days: 99.99, dueDate: "2024-01-01", vip: true}], drivers: [{days: 0, dueDate: "2025-03-20", vip: true}, {days: 7.25, dueDate: "2025-03-20", vip: true}, {days: 99.99, dueDate: "2024-01-01", vip: true}], flagged: true, net: 250, region: "a", totals: {margin: [1, 1, 1.5, 100, 486, 0.25], quota: []}}, {balance: 0, birthDate: "2000-01-01", capped: [], drivers: [], flagged: false, net: 250, region: "high", totals: {margin: [0, 0, 1.5, 0, 486, 0.25], quota: []}}], penalty: 100, points: [], price: 0.25, report: {flags: {segment: [{balance: 1.5, birthDate: "2024-02-29", capped: [{days: 100, dueDate: "2025-03-20", vip: true}], drivers: [{days: 99999999999999999999, dueDate: "2000-01-01", vip: true}, {days: 100, dueDate: "2025-03-20", vip: true}], flagged: true, net: 250, region: "", totals: {margin: [1.5, 1.5, 1.5, 1.5, 486, 0.25], quota: []}}, {balance: 1, birthDate: "2025-03-20", capped: [{days: 99.99, dueDate: "2024-01-01", vip: true}], drivers: [{days: 0, dueDate: "2025-03-20", vip: true}, {days: 7.25, dueDate: "2025-03-20", vip: true}, {days: 99.99, dueDate: "2024-01-01", vip: true}], flagged: true, net: 250, region: "a", totals: {margin: [1, 1, 1.5, 100, 486, 0.25], quota: []}}]}, level: [], rate: 486, tag: "true/true"}, since: "2025-03-20T10:15:30Z", tier: "gold", verified: true, weight: 250}}], + ], +} + +// seed 344300 (attempt 0) +{ + name: "b 44: tenant/accounts + report: 1 assertion, 5 expression, 2 match, 1 table; 2 root, 6 per-member, 1 top-level computed", + policy: { + models: {tenant: {limit: "number?", region: "string?", city: "string", rate: "number", accounts: "acct[]?", report: "creditReport?"}, acct: {weight: "number", country: "string", insured: "boolean"}, creditReport: {years: "number"}}, + blocks: [ + {match: "acct.capped", arms: [["some((tenant.accounts ?? []), (#.insured and #.insured))", "(tenant.report.years ?? 0)"], ["", "(acct.insured ? (tenant.report.years ?? 0) : tenant.rate)"]]}, + {table: "t2", inputs: [null], outputs: ["acct.scores.bucket", "acct.scores.fee", "acct.review"], rules: [ + ["", "acct.country", "(tenant.region ?? '')", ""], + ["(acct.insured and acct.insured)", "tenant.city", "'A1'", "acct.country"], + ["(tenant.report.years ?? 0) in [14..39)", "acct.country", "`${(tenant.limit ?? 0)}/${acct.insured}`", "tenant.city"], + ["isNumeric(acct.country)", "acct.country", "(acct.insured ? tenant.city : (tenant.region ?? ''))", "'VIP'"], + ]}, + {expression: "acct.rank", value: "(matches((acct.review ?? ''), '^.{2,}$') ? acct.scores.fee : null)"}, + {expression: "creditReport.bonus", value: "filter((tenant.accounts ?? []), #.weight <= #.capped)"}, + {assertion: "tenant.calc.share", conditions: ["string((tenant.limit ?? 0) <= 50) != 'retail'", ["or", "tenant.city in ['a', 'x']", 0], ["or", "(tenant.report.years ?? 0) != (tenant.report.years ?? 0)", 0]]}, + {match: "discount", arms: [["contains(['US', 'x', ''], tenant.city)", "(upper(tenant.city) + '-' + `${1.5}/${tenant.calc.share}`)"], ["none((tenant.accounts ?? []), (#.insured and #.insured))", "tenant.city"], ["matches(tenant.city, '^[A-Z]')", "trim(tenant.city)"], ["", "'x'"]]}, + {expression: "tenant.level", value: "len(filter((tenant.accounts ?? []), (#.insured or #.insured)))"}, + {expression: "creditReport.grade", value: "{a: string((tenant.limit ?? 0) == 250)}"}, + {expression: "acct.ok", value: "(acct.capped <= tenant.rate ? acct.country : string(acct.insured))"}, + ], + }, + cases: [ + [{tenant: {region: null, city: "NL", rate: 250, accounts: [], report: null}}, {discount: "NL", tenant: {accounts: [], city: "NL", level: 0, rate: 250, region: null, report: null}}], + [{tenant: {limit: 0, region: "A1", city: "A1", rate: 100, accounts: [{weight: 99999999999999999999, country: "US", insured: null}, {weight: 0.5, country: "abc", insured: false}], report: {years: -0}}}, "!error: ExpressionFailed"], + [{tenant: {limit: -0.5, region: "US", city: "a-b-c", rate: 50, accounts: [{weight: 5, country: "VIP", insured: true}, {weight: 7.25, country: "high", insured: false}], report: {years: 2}}}, {discount: "x", tenant: {accounts: [{capped: 2, country: "VIP", insured: true, ok: "VIP", rank: "US", review: "VIP", scores: {bucket: "VIP", fee: "US"}, weight: 5}, {capped: 2, country: "high", insured: false, ok: "high", rank: null, review: null, scores: {bucket: "high", fee: "US"}, weight: 7.25}], city: "a-b-c", level: 1, limit: -0.5, rate: 50, region: "US", report: {bonus: [], grade: {a: "false"}, years: 2}}}], + [{tenant: {limit: 50, region: "Zed", city: "Zed", rate: 1, accounts: [{weight: 2, country: "-", insured: true}], report: {years: 99999999999999999999}}}, {discount: "Zed", tenant: {accounts: [{capped: 99999999999999999999, country: "-", insured: true, ok: "true", rank: null, review: "-", scores: {bucket: "-", fee: "Zed"}, weight: 2}], city: "Zed", level: 1, limit: 50, rate: 1, region: "Zed", report: {bonus: [{capped: 99999999999999999999, country: "-", insured: true, ok: "true", rank: null, review: "-", scores: {bucket: "-", fee: "Zed"}, weight: 2}], grade: {a: "false"}, years: 99999999999999999999}}}], + [{tenant: {limit: 0, region: "retail", city: "", rate: 315, accounts: [{weight: 100, country: " pad ", insured: true}, {weight: -0.5, country: "US", insured: true}, {weight: 1000000, country: "Oslo", insured: true}], report: {years: 99999999999999999999}}}, {discount: "-1.5/false", tenant: {accounts: [{capped: 99999999999999999999, country: " pad ", insured: true, ok: "true", rank: "retail", review: " pad ", scores: {bucket: " pad ", fee: "retail"}, weight: 100}, {capped: 99999999999999999999, country: "US", insured: true, ok: "true", rank: "retail", review: "US", scores: {bucket: "US", fee: "retail"}, weight: -0.5}, {capped: 99999999999999999999, country: "Oslo", insured: true, ok: "true", rank: "retail", review: "Oslo", scores: {bucket: "Oslo", fee: "retail"}, weight: 1000000}], calc: {share: false}, city: "", level: 3, limit: 0, rate: 315, region: "retail", report: {bonus: [{capped: 99999999999999999999, country: " pad ", insured: true, ok: "true", rank: "retail", review: " pad ", scores: {bucket: " pad ", fee: "retail"}, weight: 100}, {capped: 99999999999999999999, country: "US", insured: true, ok: "true", rank: "retail", review: "US", scores: {bucket: "US", fee: "retail"}, weight: -0.5}, {capped: 99999999999999999999, country: "Oslo", insured: true, ok: "true", rank: "retail", review: "Oslo", scores: {bucket: "Oslo", fee: "retail"}, weight: 1000000}], grade: {a: "false"}, years: 99999999999999999999}}}], + [{tenant: {limit: 100, region: "12", city: "A1", rate: 18, accounts: [{weight: 2, country: "a", insured: false}, {weight: 2.50, country: "日本", insured: false}, {weight: 155, country: "", insured: true}], report: {years: 2.50}, extraField: 1}}, {discount: "A1", tenant: {accounts: [{capped: 2.50, country: "a", insured: false, ok: "a", rank: null, review: null, scores: {bucket: "a", fee: "12"}, weight: 2}, {capped: 2.50, country: "日本", insured: false, ok: "日本", rank: null, review: null, scores: {bucket: "日本", fee: "12"}, weight: 2.50}, {capped: 2.50, country: "", insured: true, ok: "", rank: null, review: "", scores: {bucket: "", fee: "12"}, weight: 155}], city: "A1", extraField: 1, level: 1, limit: 100, rate: 18, region: "12", report: {bonus: [{capped: 2.50, country: "a", insured: false, ok: "a", rank: null, review: null, scores: {bucket: "a", fee: "12"}, weight: 2}, {capped: 2.50, country: "日本", insured: false, ok: "日本", rank: null, review: null, scores: {bucket: "日本", fee: "12"}, weight: 2.50}], grade: {a: "false"}, years: 2.50}}}], + [{tenant: {limit: -0, region: "gold", city: "Oslo", rate: 250, accounts: [{weight: 250, country: "3.5", insured: true}, {weight: 7.25, country: "a", insured: true}], report: {years: 7.25}}}, {discount: "Oslo", tenant: {accounts: [{capped: 7.25, country: "3.5", insured: true, ok: "3.5", rank: "gold", review: "3.5", scores: {bucket: "3.5", fee: "gold"}, weight: 250}, {capped: 7.25, country: "a", insured: true, ok: "a", rank: null, review: "a", scores: {bucket: "a", fee: "gold"}, weight: 7.25}], city: "Oslo", level: 2, limit: 0, rate: 250, region: "gold", report: {bonus: [{capped: 7.25, country: "a", insured: true, ok: "a", rank: null, review: "a", scores: {bucket: "a", fee: "gold"}, weight: 7.25}], grade: {a: "false"}, years: 7.25}}}], + [{tenant: {limit: -0.5, city: "VIP", rate: 5, accounts: [{weight: 0.000001, country: "NL", insured: false}, {weight: 2.50, country: "Zed", insured: false}, {weight: 1000000, country: "VIP", insured: false}, {weight: 0.000001, country: "x", insured: true}], report: {years: 50}}}, {discount: "VIP", tenant: {accounts: [{capped: 50, country: "NL", insured: false, ok: "false", rank: null, review: null, scores: {bucket: "NL", fee: ""}, weight: 0.000001}, {capped: 50, country: "Zed", insured: false, ok: "false", rank: null, review: null, scores: {bucket: "Zed", fee: ""}, weight: 2.50}, {capped: 50, country: "VIP", insured: false, ok: "false", rank: null, review: null, scores: {bucket: "VIP", fee: ""}, weight: 1000000}, {capped: 50, country: "x", insured: true, ok: "true", rank: null, review: "x", scores: {bucket: "x", fee: ""}, weight: 0.000001}], city: "VIP", level: 1, limit: -0.5, rate: 5, report: {bonus: [{capped: 50, country: "NL", insured: false, ok: "false", rank: null, review: null, scores: {bucket: "NL", fee: ""}, weight: 0.000001}, {capped: 50, country: "Zed", insured: false, ok: "false", rank: null, review: null, scores: {bucket: "Zed", fee: ""}, weight: 2.50}, {capped: 50, country: "x", insured: true, ok: "true", rank: null, review: "x", scores: {bucket: "x", fee: ""}, weight: 0.000001}], grade: {a: "false"}, years: 50}}}], + [{tenant: {limit: 1000000, region: "x", city: "VIP", rate: 0, accounts: [{weight: 0.5, country: "high", insured: true}, {weight: 99.99, country: "NL", insured: true}, {weight: 2, country: "VIP", insured: false}, {weight: 1000, country: "VIP", insured: true}, {weight: 250, country: "abc", insured: true}]}}, {discount: "VIP", tenant: {accounts: [{capped: 0, country: "high", insured: true, ok: "high", rank: "x", review: "high", scores: {bucket: "high", fee: "x"}, weight: 0.5}, {capped: 0, country: "NL", insured: true, ok: "NL", rank: "x", review: "NL", scores: {bucket: "NL", fee: "x"}, weight: 99.99}, {capped: 0, country: "VIP", insured: false, ok: "VIP", rank: null, review: null, scores: {bucket: "VIP", fee: "x"}, weight: 2}, {capped: 0, country: "VIP", insured: true, ok: "VIP", rank: "x", review: "VIP", scores: {bucket: "VIP", fee: "x"}, weight: 1000}, {capped: 0, country: "abc", insured: true, ok: "abc", rank: "x", review: "abc", scores: {bucket: "abc", fee: "x"}, weight: 250}], city: "VIP", level: 4, limit: 1000000, rate: 0, region: "x"}}], + [{tenant: {limit: 1, region: "日本", city: "VIP", rate: -500, accounts: [], report: {years: 250}}}, {discount: "VIP", tenant: {accounts: [], city: "VIP", level: 0, limit: 1, rate: -500, region: "日本", report: {bonus: [], grade: {a: "false"}, years: 250}}}], + [{tenant: {limit: 173, region: "3.5", city: "O'Neil", rate: 5, accounts: [{weight: 1e3, country: "x", insured: true}, {weight: 10, country: "A1", insured: true}], report: {years: 99999999999999999999}}}, {discount: "O'Neil", tenant: {accounts: [{capped: 99999999999999999999, country: "x", insured: true, ok: "true", rank: null, review: "x", scores: {bucket: "x", fee: "3.5"}, weight: 1000}, {capped: 99999999999999999999, country: "A1", insured: true, ok: "true", rank: "3.5", review: "A1", scores: {bucket: "A1", fee: "3.5"}, weight: 10}], city: "O'Neil", level: 2, limit: 173, rate: 5, region: "3.5", report: {bonus: [{capped: 99999999999999999999, country: "x", insured: true, ok: "true", rank: null, review: "x", scores: {bucket: "x", fee: "3.5"}, weight: 1000}, {capped: 99999999999999999999, country: "A1", insured: true, ok: "true", rank: "3.5", review: "A1", scores: {bucket: "A1", fee: "3.5"}, weight: 10}], grade: {a: "false"}, years: 99999999999999999999}}}], + [{tenant: {city: "x", rate: 100, accounts: [{weight: 65, country: "x-y", insured: false}, {weight: -500, country: "VIP", insured: true}], report: {years: 0}}}, {discount: "X-1.5/true", tenant: {accounts: [{capped: 0, country: "x-y", insured: false, ok: "x-y", rank: null, review: null, scores: {bucket: "x-y", fee: ""}, weight: 65}, {capped: 0, country: "VIP", insured: true, ok: "VIP", rank: "", review: "VIP", scores: {bucket: "VIP", fee: ""}, weight: -500}], calc: {share: true}, city: "x", level: 1, rate: 100, report: {bonus: [{capped: 0, country: "VIP", insured: true, ok: "VIP", rank: "", review: "VIP", scores: {bucket: "VIP", fee: ""}, weight: -500}], grade: {a: "false"}, years: 0}}}], + [{tenant: {limit: 123456789.123, region: "", city: "x", rate: -500, accounts: [{weight: 99999999999999999999, country: "x-y", insured: true}, {weight: 99999999999999999999, country: " pad ", insured: true}, {weight: -0.5, country: "", insured: true}, {weight: 1e3, country: "12", insured: true}], report: {years: 123456789.123}, extraField: "x"}}, {discount: "X-1.5/true", tenant: {accounts: [{capped: 123456789.123, country: "x-y", insured: true, ok: "true", rank: "", review: "x-y", scores: {bucket: "x-y", fee: ""}, weight: 99999999999999999999}, {capped: 123456789.123, country: " pad ", insured: true, ok: "true", rank: "", review: " pad ", scores: {bucket: " pad ", fee: ""}, weight: 99999999999999999999}, {capped: 123456789.123, country: "", insured: true, ok: "true", rank: null, review: "", scores: {bucket: "", fee: ""}, weight: -0.5}, {capped: 123456789.123, country: "12", insured: true, ok: "true", rank: "", review: "12", scores: {bucket: "12", fee: ""}, weight: 1000}], calc: {share: true}, city: "x", extraField: "x", level: 4, limit: 123456789.123, rate: -500, region: "", report: {bonus: [{capped: 123456789.123, country: "", insured: true, ok: "true", rank: null, review: "", scores: {bucket: "", fee: ""}, weight: -0.5}, {capped: 123456789.123, country: "12", insured: true, ok: "true", rank: "", review: "12", scores: {bucket: "12", fee: ""}, weight: 1000}], grade: {a: "false"}, years: 123456789.123}}}], + [{tenant: {limit: 0.5, region: "high", city: "", rate: 99999999999999999999, accounts: [{weight: 1000000, country: "retail", insured: false}, {weight: 1000, country: " pad ", insured: false}, {weight: 123456789.123, country: "x", insured: true}], report: {years: -0.01}}}, {discount: "-1.5/false", tenant: {accounts: [{capped: -0.01, country: "retail", insured: false, ok: "retail", rank: null, review: null, scores: {bucket: "retail", fee: "high"}, weight: 1000000}, {capped: -0.01, country: " pad ", insured: false, ok: " pad ", rank: null, review: null, scores: {bucket: " pad ", fee: "high"}, weight: 1000}, {capped: -0.01, country: "x", insured: true, ok: "x", rank: null, review: "x", scores: {bucket: "x", fee: "high"}, weight: 123456789.123}], calc: {share: false}, city: "", level: 1, limit: 0.5, rate: 99999999999999999999, region: "high", report: {bonus: [], grade: {a: "false"}, years: -0.01}}}], + ], +} + +// seed 344400 (attempt 0) +{ + name: "b 45: account/items: 5 expression, 2 match, 2 table; 7 root, 6 per-member, 2 top-level computed", + policy: { + models: {account: {amount: "number", sku: "string", urgent: "boolean", score: "number?", insured: "boolean?", vip: "boolean", items: "item[]?"}, item: {price: "number", birthDate: "date", dueDate: "date"}}, + blocks: [ + {table: "t4", inputs: ["item.dueDate"], outputs: ["item.bucket", "item.quota", "item.weighted"], rules: [ + [">= d('2025-01-01')", "item.price", "account.vip", "'ok'"], + ["< d('2025-03-20')", "", "account.vip", ""], + ["< d('2024-01-01')", "(account.discount ?? 0)", "", "`${0.25}/${(account.points ?? 0)}`"], + ["< d('2025-03-20')", "3", "account.decision.a", "account.decision.ok"], + ["> d('2025-01-01')", "(account.discount ?? 0)", "level > 5", "account.sku"], + [">= d('2025-01-01')", "((account.score ?? 0) % (abs(account.amount) + 1))", "account.decision.a", "account.sku"], + ["> d('2024-01-01')", "", "(account.points ?? 0) != (account.fee ?? 0)", "account.sku"], + ]}, + {expression: "item.bonus", value: "(len(item.totals.eligible) + -(number(string(item.price))))"}, + {table: "t3", inputs: [null, "sum([(account.score ?? 0), (account.score ?? 0), (account.score ?? 0), 250])"], outputs: ["account.discount", "account.points", "account.fee"], rules: [ + ["", "<= 0.25", "(18 + (account.score ?? 0))", "account.amount", "round(account.amount)"], + ["account.amount < 0.25", "", "level", "", "level"], + ["", "< 250", "number(string(level))", "1", "100"], + ]}, + {expression: "item.tag", value: "(none((account.items ?? []), not ((#.quota ?? false))) ? account.insured : null)"}, + {expression: "account.decision", value: "{a: account.urgent, ok: account.sku}"}, + {expression: "item.totals.eligible", value: "map((account.items ?? []), (#.bucket ?? 0))"}, + {match: "risk", arms: [["matches(account.sku, '^[A-Z]')", "avg([len(filter((account.items ?? []), #.bonus > 10)), min([(account.discount ?? 0), account.amount, (account.fee ?? 0)]), avg([account.amount])])"], ["(matches(account.decision.ok, 'a') and none((account.items ?? []), ((#.quota ?? false) or (#.quota ?? false))))", "len(filter((account.items ?? []), #.quota != null))"], ["account.amount < (account.score ?? 0)", "min([(account.fee ?? 0), (account.fee ?? 0), (account.discount ?? 0), account.amount])"], ["", "(account.points ?? 0)"]]}, + {expression: "account.segment", value: "account.decision.ok in ['x', 'A1']"}, + {match: "level", arms: [["account.amount < 2", "(account.score ?? 0)"], ["(account.vip and account.urgent)", "18"], ["", "account.amount"]]}, + ], + }, + cases: [ + [{account: {amount: 2.50, sku: "A1", urgent: false, score: 123456789.123, insured: null, vip: false, items: [{price: 0.25, birthDate: "2025-03-20", dueDate: "2030-12-31"}, {price: 250, birthDate: "2000-01-01", dueDate: "2025-03-20"}]}}, {account: {amount: 2.50, decision: {a: false, ok: "A1"}, discount: null, fee: null, insured: null, items: [{birthDate: "2025-03-20", bonus: 1.75, bucket: 0.25, dueDate: "2030-12-31", price: 0.25, quota: false, tag: null, totals: {eligible: [0.25, 250]}, weighted: "ok"}, {birthDate: "2000-01-01", bonus: -248, bucket: 250, dueDate: "2025-03-20", price: 250, quota: false, tag: null, totals: {eligible: [0.25, 250]}, weighted: "ok"}], points: null, score: 123456789.123, segment: true, sku: "A1", urgent: false, vip: false}, risk: 0.8333333333333333333333333333}], + [{account: {amount: 18, sku: "Oslo", urgent: true, score: 1, insured: true, vip: true, items: [{price: 65, birthDate: "2024-02-29", dueDate: "2030-12-31"}, {price: 0.25, birthDate: "2025-03-20", dueDate: "2025-03-20"}, {price: 123456789.123, birthDate: "2024-01-01", dueDate: "2024-02-29"}]}}, {account: {amount: 18, decision: {a: true, ok: "Oslo"}, discount: null, fee: null, insured: true, items: [{birthDate: "2024-02-29", bonus: -62, bucket: 65, dueDate: "2030-12-31", price: 65, quota: true, tag: true, totals: {eligible: [65, 0.25, 3]}, weighted: "ok"}, {birthDate: "2025-03-20", bonus: 2.75, bucket: 0.25, dueDate: "2025-03-20", price: 0.25, quota: true, tag: true, totals: {eligible: [65, 0.25, 3]}, weighted: "ok"}, {birthDate: "2024-01-01", bonus: -123456786.123, bucket: 3, dueDate: "2024-02-29", price: 123456789.123, quota: true, tag: true, totals: {eligible: [65, 0.25, 3]}, weighted: "Oslo"}], points: null, score: 1, segment: false, sku: "Oslo", urgent: true, vip: true}, risk: 6}], + [{account: {amount: 1e3, sku: "-", urgent: true, score: 0, insured: "true", vip: false, items: [{price: 100, birthDate: "2024-02-29", dueDate: "2025-03-20"}]}}, "!error: InputValidationFailed"], + [{account: {amount: 123456789.123, sku: "x", urgent: false, insured: true, vip: false, items: [{price: 123456789.123, birthDate: "1990-06-15", dueDate: "2030-12-31"}]}}, {account: {amount: 123456789.123, decision: {a: false, ok: "x"}, discount: null, fee: null, insured: true, items: [{birthDate: "1990-06-15", bucket: 123456789.123, dueDate: "2030-12-31", price: 123456789.123, quota: false, tag: null, weighted: "ok"}], points: null, segment: true, sku: "x", urgent: false, vip: false}, risk: 0}], + [{account: {amount: 0.25, sku: "Zed", urgent: false, score: 5, insured: true, vip: false, items: [{price: 0.25, birthDate: "2024-01-01", dueDate: "2024-01-01"}, {price: -1, birthDate: "2030-12-31", dueDate: "2030-12-31"}]}}, {account: {amount: 0.25, decision: {a: false, ok: "Zed"}, discount: null, fee: null, insured: true, items: [{birthDate: "2024-01-01", bonus: 1.75, bucket: 3, dueDate: "2024-01-01", price: 0.25, quota: false, tag: null, totals: {eligible: [3, -1]}, weighted: "Zed"}, {birthDate: "2030-12-31", bonus: 3, bucket: -1, dueDate: "2030-12-31", price: -1, quota: false, tag: null, totals: {eligible: [3, -1]}, weighted: "ok"}], points: null, score: 5, segment: false, sku: "Zed", urgent: false, vip: false}, risk: 0.0833333333333333333333333333}], + [{account: {amount: -0.5, sku: "A1", urgent: true, score: 2, insured: false, items: [{price: 18, birthDate: "2024-02-29", dueDate: "2024-01-01"}, {price: 10, birthDate: "2024-01-01", dueDate: "2030-12-31"}, {price: 0, birthDate: "1990-06-15", dueDate: "2024-01-01"}, {price: 250, birthDate: "2025-03-20T10:15:30Z", dueDate: "2024-01-01"}, {price: 0.25, birthDate: "2024-01-01", dueDate: "2024-01-01"}]}}, "!error: MissingRequiredInputs"], + [{account: {amount: 1e3, sku: "日本", urgent: true, score: 0, insured: false, vip: false, items: [{price: 250, birthDate: "2024-01-01", dueDate: "2024-02-29"}, {price: 1e3, birthDate: "2024-01-01", dueDate: "1990-06-15"}, {price: 0, birthDate: "2024-02-29", dueDate: "1990-06-15"}, {price: 1000, birthDate: "2025-03-20", dueDate: "2024-02-29"}, {price: 18, birthDate: "2024-02-29", dueDate: "2030-12-31"}], extraField: "x"}}, {account: {amount: 1000, decision: {a: true, ok: "日本"}, discount: null, extraField: "x", fee: null, insured: false, items: [{birthDate: "2024-01-01", bucket: 3, dueDate: "2024-02-29", price: 250, quota: false, tag: null, weighted: "日本"}, {birthDate: "2024-01-01", bucket: 0, dueDate: "1990-06-15", price: 1000, quota: false, tag: null, weighted: "0.25/0"}, {birthDate: "2024-02-29", bucket: 0, dueDate: "1990-06-15", price: 0, quota: false, tag: null, weighted: "0.25/0"}, {birthDate: "2025-03-20", bucket: 3, dueDate: "2024-02-29", price: 1000, quota: false, tag: null, weighted: "日本"}, {birthDate: "2024-02-29", bucket: 18, dueDate: "2030-12-31", price: 18, quota: false, tag: null, weighted: "ok"}], points: null, score: 0, segment: false, sku: "日本", urgent: true, vip: false}, risk: 0}], + [{account: {amount: 250, sku: "O'Neil", urgent: true, score: 0.1, insured: false, vip: "true", items: [{price: 10, birthDate: "1990-06-15", dueDate: "2024-01-01"}, {price: 10, birthDate: "2030-12-31", dueDate: "2024-02-29"}, {price: 5, birthDate: "2030-12-31", dueDate: "1990-06-15"}]}}, "!error: InputValidationFailed"], + [{account: {amount: 0.25, sku: "a", urgent: true, score: 0, insured: true, vip: false, items: []}}, {account: {amount: 0.25, decision: {a: true, ok: "a"}, insured: true, items: [], score: 0, segment: false, sku: "a", urgent: true, vip: false}, risk: 0}], + [{account: {amount: 0, sku: "x-y", urgent: false, score: [1], insured: true, vip: false, items: [{price: 1, birthDate: "1990-06-15", dueDate: "2000-01-01"}, {price: 123456789.123, birthDate: "2025-03-20", dueDate: "2025-03-20T10:15:30Z"}]}}, "!error: InputValidationFailed"], + [{account: {amount: 1, sku: "é ü", urgent: false, score: 1000000, vip: true}}, {account: {amount: 1, decision: {a: false, ok: "é ü"}, discount: null, fee: null, points: null, score: 1000000, segment: false, sku: "é ü", urgent: false, vip: true}, risk: 0}], + [{account: {amount: 100, sku: " pad ", urgent: true, score: -0.01, insured: null, vip: true, items: [{price: 7.25, birthDate: "2025-03-20T10:15:30Z", dueDate: "2025-03-20T10:15:30Z"}, {price: 35, birthDate: "2024-01-01", dueDate: "2025-03-20T10:15:30Z"}, {price: -1, birthDate: "2030-12-31", dueDate: "2025-03-20"}]}}, {account: {amount: 100, decision: {a: true, ok: " pad "}, discount: 18, fee: 100, insured: null, items: [{birthDate: "2025-03-20T10:15:30Z", bucket: 7.25, dueDate: "2025-03-20T10:15:30Z", price: 7.25, quota: true, tag: null, weighted: "ok"}, {birthDate: "2024-01-01", bucket: 35, dueDate: "2025-03-20T10:15:30Z", price: 35, quota: true, tag: null, weighted: "ok"}, {birthDate: "2030-12-31", bucket: -1, dueDate: "2025-03-20", price: -1, quota: true, tag: null, weighted: "ok"}], points: 1, score: -0.01, segment: false, sku: " pad ", urgent: true, vip: true}, level: 18, risk: 1}], + [{account: {amount: 0.25, sku: "12", urgent: true, score: 3, insured: true, vip: false, items: []}}, {account: {amount: 0.25, decision: {a: true, ok: "12"}, discount: null, fee: null, insured: true, items: [], points: null, score: 3, segment: false, sku: "12", urgent: true, vip: false}, risk: 0}], + [{account: {amount: 99.99, sku: "A1", urgent: false, score: 10, insured: true, vip: false, items: [{price: 99999999999999999999, birthDate: "1990-06-15", dueDate: "2025-03-20T10:15:30Z"}, {price: 0.000001, birthDate: "2030-12-31", dueDate: "2025-03-20T10:15:30Z"}, {price: 100, birthDate: "2030-12-31", dueDate: "1990-06-15"}, {price: 18, birthDate: "2024-02-29", dueDate: "2024-02-29"}, {price: -0.01, birthDate: "2024-01-01", dueDate: "2025-03-20T10:15:30Z"}]}}, {account: {amount: 99.99, decision: {a: false, ok: "A1"}, discount: null, fee: null, insured: true, items: [{birthDate: "1990-06-15", bonus: -99999999999999999994, bucket: 99999999999999999999, dueDate: "2025-03-20T10:15:30Z", price: 99999999999999999999, quota: false, tag: null, totals: {eligible: [99999999999999999999, 0.000001, 0, 3, -0.01]}, weighted: "ok"}, {birthDate: "2030-12-31", bonus: 4.999999, bucket: 0.000001, dueDate: "2025-03-20T10:15:30Z", price: 0.000001, quota: false, tag: null, totals: {eligible: [99999999999999999999, 0.000001, 0, 3, -0.01]}, weighted: "ok"}, {birthDate: "2030-12-31", bonus: -95, bucket: 0, dueDate: "1990-06-15", price: 100, quota: false, tag: null, totals: {eligible: [99999999999999999999, 0.000001, 0, 3, -0.01]}, weighted: "0.25/0"}, {birthDate: "2024-02-29", bonus: -13, bucket: 3, dueDate: "2024-02-29", price: 18, quota: false, tag: null, totals: {eligible: [99999999999999999999, 0.000001, 0, 3, -0.01]}, weighted: "A1"}, {birthDate: "2024-01-01", bonus: 5.01, bucket: -0.01, dueDate: "2025-03-20T10:15:30Z", price: -0.01, quota: false, tag: null, totals: {eligible: [99999999999999999999, 0.000001, 0, 3, -0.01]}, weighted: "ok"}], points: null, score: 10, segment: true, sku: "A1", urgent: false, vip: false}, risk: 33.33}], + [{account: {amount: 0.25, sku: "NL", urgent: true, score: 0.25, insured: true, vip: false, items: [], extraField: "x"}}, {account: {amount: 0.25, decision: {a: true, ok: "NL"}, discount: null, extraField: "x", fee: null, insured: true, items: [], points: null, score: 0.25, segment: false, sku: "NL", urgent: true, vip: false}, risk: 0.0833333333333333333333333333}], + ], +} + +// seed 344500 (attempt 0) +{ + name: "b 46: tenant/parcels: 1 assertion, 4 expression, 3 match, 3 table; 2 root, 6 per-member, 6 top-level computed", + policy: { + models: {tenant: {age: "number?", limit: "number", label: "string", weight: "number?", city: "string", parcels: "parcel[]?"}, parcel: {qty: "number", channel: "string", vip: "boolean"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {expression: "health", value: "{s: tenant.city}"}, + {match: "parcel.rank", arms: [["(parcel.vip and parcel.vip)", "sum(map((tenant.parcels ?? []), #.qty))"], ["isNumeric(tenant.city)", "(tenant.weight ?? 0)"], ["tenant.weight == null", "count((tenant.parcels ?? []), (#.vip and #.vip))"], ["", "(tenant.age ?? 0)"]]}, + {match: "parcel.flags.level", arms: [["matches(tenant.label, '^[A-Z]')", "'US'"], ["", "health.s"]]}, + {match: "calc.weighted", arms: [["cap < (tenant.age ?? 0)", "((0 > 1.5 and (tenant.age ?? 0) > 18) or (cap == 0.5 and 250 > 1000))"], ["contains(tenant.label, 'high')", "not (cap == 1)"], ["", "tenant.limit <= 50"]]}, + {table: "t5", inputs: ["(tenant.weight ?? 0)", "tenant.weight"], outputs: ["bonus"], rules: [ + ["0.5", "", "(tenant.age ?? 0)"], + ["", "18, 0.25", "10"], + ["", "3, 1.5", "((tenant.age ?? 0)) / (abs(cap) + 1)"], + ["> 0", "50", "(tenant.age ?? 0)"], + ["> 250", "3", "cap"], + ["", "", "3"], + ]}, + {expression: "parcel.margin", value: "(min([abs(number(string(trunc((bonus ?? 0))))), 1000]) ^ 1)"}, + {assertion: "tenant.scores.capped", conditions: [["and", "contains(['DE', 'ok', ''], tenant.city)", 0], ["and", "cap in [19..65]", 0], ["or", "string(calc.weighted) != 'retail'", 1], ["or", "(bonus ?? 0) != tenant.limit", 0], ["and", "contains(string((tenant.weight ?? 0)), 'x')", 2]]}, + {expression: "parcel.flags.bucket", value: "(min([abs(parcel.margin), 1000]) ^ 2)"}, + {expression: "tenant.band", value: "(bonus ?? 0) in [49..241]"}, + {table: "t10", inputs: [null, "tenant.label"], outputs: ["parcel.flags.ok[]", "parcel.totals.grade[]"], rules: [ + ["", "'ok'", "", "(tenant.weight ?? 0)"], + ["not (tenant.scores.capped)", "", "parcel.channel", "tenant.limit"], + ["parcel.channel in ['US', 'a']", "'a'", "parcel.channel", "(tenant.band ? 0.5 : cap)"], + ["", "startsWith($, 'ok')", "trim(tenant.city)", "parcel.margin"], + ["tenant.limit > (tenant.weight ?? 0)", "", "parcel.flags.level", "(bonus ?? 0)"], + ["", "", "parcel.channel", "(cap + (tenant.age ?? 0))"], + ["cap in [16..52]", "'US', 'none'", "string(cap)", "(cap + 5)"], + ]}, + {table: "t11", hit: "collect", inputs: ["calc.weighted", "ceil((bonus ?? 0))", "tenant.scores.capped"], outputs: ["review", "total"], rules: [ + ["true", "<= 0", "", "(2) / (abs(tenant.limit) + 1)", "tenant.scores.capped"], + ["false", "> 2", "false", "", "calc.weighted"], + ["false", "1, 100", "", "", ""], + ]}, + ], + }, + cases: [ + [{cap: 0, tenant: {limit: -0, label: "A1", weight: null, city: "NL", parcels: [{qty: 100, channel: "retail", vip: false}]}}, {bonus: 3, calc: {weighted: true}, cap: 0, review: [], tenant: {city: "NL", label: "A1", limit: 0, parcels: [{channel: "retail", flags: {ok: ["retail"]}, qty: 100, rank: 0, totals: {grade: [0]}, vip: false}], scores: {capped: true}, weight: null}, total: []}], + [{cap: -2, tenant: {age: 123456789.123, limit: 0.25, label: "x", weight: 0.5, city: "Oslo", parcels: [{qty: 65, channel: "DE", vip: null}, {qty: 0.25, channel: "DE", vip: false}]}}, "!error: ExpressionFailed"], + [{cap: 0.5, tenant: {age: -1, limit: 0.25, label: "12", weight: 5, city: "high", parcels: [{qty: 0.5, channel: "3.5", vip: true}]}}, {bonus: 3, calc: {weighted: true}, cap: 0.5, review: [], tenant: {age: -1, city: "high", label: "12", limit: 0.25, parcels: [{channel: "3.5", flags: {ok: ["3.5"]}, qty: 0.5, rank: 0.5, totals: {grade: [-0.5]}, vip: true}], scores: {capped: true}, weight: 5}, total: []}], + [{cap: 1, tenant: {age: 2, limit: 0, label: "NL", weight: 0.5, city: "retail", parcels: [{qty: 1.5, channel: "US", vip: true}, {qty: 1, channel: "3.5", vip: false}, {qty: 99999999999999999999, channel: "DE", vip: true}, {qty: 2, channel: "-", vip: false}, {qty: 2, channel: "VIP", vip: true}]}}, {bonus: 2, calc: {weighted: false}, cap: 1, review: [], tenant: {age: 2, city: "retail", label: "NL", limit: 0, parcels: [{channel: "US", flags: {ok: ["US"]}, qty: 1.5, rank: 100000000000000000005.5, totals: {grade: [3]}, vip: true}, {channel: "3.5", flags: {ok: ["3.5"]}, qty: 1, rank: 2, totals: {grade: [3]}, vip: false}, {channel: "DE", flags: {ok: ["DE"]}, qty: 99999999999999999999, rank: 100000000000000000005.5, totals: {grade: [3]}, vip: true}, {channel: "-", flags: {ok: ["-"]}, qty: 2, rank: 2, totals: {grade: [3]}, vip: false}, {channel: "VIP", flags: {ok: ["VIP"]}, qty: 2, rank: 100000000000000000005.5, totals: {grade: [3]}, vip: true}], scores: {capped: true}, weight: 0.5}, total: []}], + [{cap: 0, tenant: {age: -0.01, limit: 1000, label: "é ü", weight: 250, city: "DE", parcels: [{qty: 10, channel: "日本", vip: false}]}}, {bonus: 3, calc: {weighted: false}, cap: 0, health: {s: "DE"}, review: [], tenant: {age: -0.01, city: "DE", label: "é ü", limit: 1000, parcels: [{channel: "日本", flags: {level: "DE", ok: ["DE", "日本"]}, qty: 10, rank: -0.01, totals: {grade: [3, -0.01]}, vip: false}], scores: {capped: true}, weight: 250}, total: []}], + [{cap: 10, tenant: {age: 1.5, limit: 1000, label: "DE", city: "é ü", parcels: [{qty: 1e3, channel: "gold", vip: false}]}}, {bonus: 3, calc: {weighted: false}, cap: 10, review: [], tenant: {age: 1.5, city: "é ü", label: "DE", limit: 1000, parcels: [{channel: "gold", flags: {level: "US", ok: ["US", "gold"]}, qty: 1000, rank: 0, totals: {grade: [3, 11.5]}, vip: false}], scores: {capped: true}}, total: []}], + [{cap: 1, tenant: {age: 250, limit: 2, label: "US", weight: -0.01, city: "ok", parcels: [{qty: 1, channel: "-", vip: false}, {qty: 0.25, channel: "gold", vip: true}, {qty: 1, channel: "3.5", vip: false}, {qty: 3, channel: "US", vip: true}, {qty: -1, channel: "x-y", vip: false}]}}, {bonus: 3, calc: {weighted: false}, cap: 1, review: [], tenant: {age: 250, city: "ok", label: "US", limit: 2, parcels: [{channel: "-", flags: {level: "US", ok: ["US", "-"]}, qty: 1, rank: 250, totals: {grade: [3, 251]}, vip: false}, {channel: "gold", flags: {level: "US", ok: ["US", "gold"]}, qty: 0.25, rank: 4.25, totals: {grade: [3, 251]}, vip: true}, {channel: "3.5", flags: {level: "US", ok: ["US", "3.5"]}, qty: 1, rank: 250, totals: {grade: [3, 251]}, vip: false}, {channel: "US", flags: {level: "US", ok: ["US", "US"]}, qty: 3, rank: 4.25, totals: {grade: [3, 251]}, vip: true}, {channel: "x-y", flags: {level: "US", ok: ["US", "x-y"]}, qty: -1, rank: 250, totals: {grade: [3, 251]}, vip: false}], scores: {capped: true}, weight: -0.01}, total: []}], + [{cap: 1, tenant: {age: 18, limit: 3, label: "gold", weight: 172, city: "a", parcels: [{qty: 5, channel: "VIP", vip: false}, {qty: 1, channel: "x-y", vip: false}], extraField: 1}}, {bonus: 3, calc: {weighted: false}, cap: 1, review: [], tenant: {age: 18, city: "a", extraField: 1, label: "gold", limit: 3, parcels: [{channel: "VIP", flags: {ok: ["VIP", "VIP"]}, qty: 5, rank: 18, totals: {grade: [3, 19]}, vip: false}, {channel: "x-y", flags: {ok: ["x-y", "x-y"]}, qty: 1, rank: 18, totals: {grade: [3, 19]}, vip: false}], scores: {capped: false}, weight: 172}, total: [false]}], + [{cap: 1, tenant: {age: 1.5, limit: 1, label: "O'Neil", weight: 123456789.123, city: "x", parcels: [{qty: 99.99, channel: "x", vip: false}, {qty: 10, channel: "Oslo", vip: false}, {qty: 0.5, channel: "VIP", vip: true}, {qty: 1.5, channel: "ok", vip: true}, {qty: 1000, channel: "3.5", vip: false}]}}, {bonus: 3, calc: {weighted: false}, cap: 1, review: [], tenant: {age: 1.5, city: "x", label: "O'Neil", limit: 1, parcels: [{channel: "x", flags: {ok: ["x"]}, qty: 99.99, rank: 1.5, totals: {grade: [2.5]}, vip: false}, {channel: "Oslo", flags: {ok: ["Oslo"]}, qty: 10, rank: 1.5, totals: {grade: [2.5]}, vip: false}, {channel: "VIP", flags: {ok: ["VIP"]}, qty: 0.5, rank: 1111.99, totals: {grade: [2.5]}, vip: true}, {channel: "ok", flags: {ok: ["ok"]}, qty: 1.5, rank: 1111.99, totals: {grade: [2.5]}, vip: true}, {channel: "3.5", flags: {ok: ["3.5"]}, qty: 1000, rank: 1.5, totals: {grade: [2.5]}, vip: false}], scores: {capped: true}, weight: 123456789.123}, total: []}], + [{cap: 100, tenant: {age: "12", limit: 0.5, label: "retail", weight: 50, city: "US", parcels: [{qty: 18, channel: "DE", vip: false}, {qty: 0.25, channel: "NL", vip: true}, {qty: 50, channel: "US", vip: false}]}}, "!error: InputValidationFailed"], + [{cap: 0.5, tenant: {age: null, limit: 0.25, label: "ok", weight: 50, city: "VIP", parcels: [{qty: 10, channel: "a", vip: false}, {qty: 3, channel: "high", vip: true}, {qty: 1, channel: "x-y", vip: true}, {qty: 100, channel: "US", vip: false}]}}, {bonus: 0, calc: {weighted: true}, cap: 0.5, review: [1.6], tenant: {age: null, city: "VIP", label: "ok", limit: 0.25, parcels: [{channel: "a", flags: {ok: ["VIP", "a"]}, margin: 0, qty: 10, rank: 0, totals: {grade: [50, 0, 0.5]}, vip: false}, {channel: "high", flags: {ok: ["VIP", "high"]}, margin: 0, qty: 3, rank: 114, totals: {grade: [50, 0, 0.5]}, vip: true}, {channel: "x-y", flags: {ok: ["VIP", "x-y"]}, margin: 0, qty: 1, rank: 114, totals: {grade: [50, 0, 0.5]}, vip: true}, {channel: "US", flags: {ok: ["VIP", "US"]}, margin: 0, qty: 100, rank: 0, totals: {grade: [50, 0, 0.5]}, vip: false}], scores: {capped: true}, weight: 50}, total: [true]}], + [{cap: 0.5, tenant: {age: 3, limit: 0, label: "retail", weight: null, city: "O'Neil", parcels: [{qty: 0, channel: "US", vip: false}]}}, {bonus: 3, calc: {weighted: false}, cap: 0.5, review: [], tenant: {age: 3, city: "O'Neil", label: "retail", limit: 0, parcels: [{channel: "US", flags: {ok: ["US"]}, qty: 0, rank: 0, totals: {grade: [3.5]}, vip: false}], scores: {capped: true}, weight: null}, total: []}], + [{cap: 10, tenant: {limit: 0.1, label: "US", weight: 0, city: "ok", parcels: [{qty: -500, channel: "O'Neil", vip: false}, {qty: 321, channel: "US", vip: true}]}}, {bonus: 3, calc: {weighted: true}, cap: 10, review: [], tenant: {city: "ok", label: "US", limit: 0.1, parcels: [{channel: "O'Neil", flags: {level: "US", ok: ["US", "O'Neil"]}, qty: -500, rank: 0, totals: {grade: [3, 10]}, vip: false}, {channel: "US", flags: {level: "US", ok: ["US", "US"]}, qty: 321, rank: -179, totals: {grade: [3, 10]}, vip: true}], scores: {capped: true}, weight: 0}, total: []}], + [{cap: 10, tenant: {age: 10, limit: 3, label: "gold", weight: 0, city: "retail", parcels: []}}, {bonus: 3, calc: {weighted: true}, cap: 10, review: [], tenant: {age: 10, city: "retail", label: "gold", limit: 3, parcels: [], scores: {capped: false}, weight: 0}, total: []}], + [{cap: -2, tenant: {age: null, limit: 3, label: "gold", weight: 5, city: "gold", parcels: [{qty: 100, channel: " pad ", vip: true}]}}, {bonus: 3, calc: {weighted: false}, cap: -2, review: [], tenant: {age: null, city: "gold", label: "gold", limit: 3, parcels: [{channel: " pad ", flags: {ok: [" pad ", " pad "]}, qty: 100, rank: 100, totals: {grade: [3, -2]}, vip: true}], scores: {capped: false}, weight: 5}, total: [false]}], + [{cap: 1, tenant: {age: 0.5, limit: 0, label: "x", weight: 3, city: "é ü", parcels: [{qty: 1, channel: "gold", vip: true}]}}, {bonus: 0.250, calc: {weighted: true}, cap: 1, review: [], tenant: {age: 0.5, city: "é ü", label: "x", limit: 0, parcels: [{channel: "gold", flags: {ok: ["gold"]}, qty: 1, rank: 1, totals: {grade: [1.5]}, vip: true}], scores: {capped: true}, weight: 3}, total: []}], + [{cap: 0, tenant: {age: 0.5, limit: 0.5, label: "retail", weight: 0.5, city: "DE", parcels: [{qty: 123456789.123, channel: "gold", vip: true}, {qty: 3, channel: " pad ", vip: true}]}}, {bonus: 0.5, calc: {weighted: false}, cap: 0, review: [], tenant: {age: 0.5, city: "DE", label: "retail", limit: 0.5, parcels: [{channel: "gold", flags: {ok: ["gold", "gold"]}, qty: 123456789.123, rank: 123456792.123, totals: {grade: [0.5, 0.5]}, vip: true}, {channel: " pad ", flags: {ok: [" pad ", " pad "]}, qty: 3, rank: 123456792.123, totals: {grade: [0.5, 0.5]}, vip: true}], scores: {capped: false}, weight: 0.5}, total: []}], + [{cap: 1, tenant: {age: 10, limit: 2, label: "gold", weight: 123456789.123, city: "a", parcels: [{qty: 1, channel: "Oslo", vip: false}, {qty: -0, channel: "日本", vip: false}]}}, {bonus: 3, calc: {weighted: false}, cap: 1, review: [], tenant: {age: 10, city: "a", label: "gold", limit: 2, parcels: [{channel: "Oslo", flags: {ok: ["Oslo"]}, qty: 1, rank: 10, totals: {grade: [11]}, vip: false}, {channel: "日本", flags: {ok: ["日本"]}, qty: 0, rank: 10, totals: {grade: [11]}, vip: false}], scores: {capped: true}, weight: 123456789.123}, total: []}], + [{cap: -2, tenant: {age: 131, limit: 1, label: "a", weight: 10, city: " pad ", parcels: [{qty: 99999999999999999999, channel: "x", vip: false}, {qty: -0, channel: "gold", vip: true}]}}, {bonus: 3, calc: {weighted: false}, cap: -2, review: [], tenant: {age: 131, city: " pad ", label: "a", limit: 1, parcels: [{channel: "x", flags: {ok: ["x"]}, qty: 99999999999999999999, rank: 131, totals: {grade: [129]}, vip: false}, {channel: "gold", flags: {ok: ["gold"]}, qty: 0, rank: 99999999999999999999, totals: {grade: [129]}, vip: true}], scores: {capped: true}, weight: 10}, total: []}], + [{cap: 100, tenant: {age: 1, limit: 1e3, label: "x", weight: 50, city: "Zed", parcels: [{qty: 0, channel: "-", vip: false}, {qty: 123456789.123, channel: "é ü", vip: true}, {qty: 0, channel: " pad ", vip: true}]}}, {bonus: 1, calc: {weighted: false}, cap: 100, health: {s: "Zed"}, review: [], tenant: {age: 1, city: "Zed", label: "x", limit: 1000, parcels: [{channel: "-", flags: {level: "Zed", ok: ["Zed", "-"]}, qty: 0, rank: 1, totals: {grade: [1, 101]}, vip: false}, {channel: "é ü", flags: {level: "Zed", ok: ["Zed", "é ü"]}, qty: 123456789.123, rank: 123456789.123, totals: {grade: [1, 101]}, vip: true}, {channel: " pad ", flags: {level: "Zed", ok: ["Zed", " pad "]}, qty: 0, rank: 123456789.123, totals: {grade: [1, 101]}, vip: true}], scores: {capped: true}, weight: 50}, total: []}], + [{cap: 100, tenant: {age: 0, limit: 250, label: "gold", weight: 1, city: "VIP", parcels: []}}, {bonus: 3, calc: {weighted: false}, cap: 100, review: [], tenant: {age: 0, city: "VIP", label: "gold", limit: 250, parcels: [], scores: {capped: true}, weight: 1}, total: []}], + [{cap: 10, tenant: {limit: 250, label: "Oslo", weight: 123456789.123, city: "x", parcels: [{qty: 50, channel: "US", vip: true}, {qty: 1, channel: "ok", vip: true}, {qty: 1.5, channel: "US", vip: false}]}}, {bonus: 3, calc: {weighted: false}, cap: 10, review: [], tenant: {city: "x", label: "Oslo", limit: 250, parcels: [{channel: "US", flags: {ok: ["US"]}, qty: 50, rank: 52.5, totals: {grade: [10]}, vip: true}, {channel: "ok", flags: {ok: ["ok"]}, qty: 1, rank: 52.5, totals: {grade: [10]}, vip: true}, {channel: "US", flags: {ok: ["US"]}, qty: 1.5, rank: 0, totals: {grade: [10]}, vip: false}], scores: {capped: true}, weight: 123456789.123}, total: []}], + [{cap: 10, tenant: {limit: 100, label: "abc", weight: 1.5, city: "12", parcels: [{qty: 3, channel: "DE", vip: false}, {qty: 2, channel: "Oslo", vip: true}]}}, {bonus: 0, calc: {weighted: false}, cap: 10, health: {s: "12"}, review: [], tenant: {city: "12", label: "abc", limit: 100, parcels: [{channel: "DE", flags: {level: "12", ok: ["12", "DE"]}, qty: 3, rank: 1.5, totals: {grade: [0, 10]}, vip: false}, {channel: "Oslo", flags: {level: "12", ok: ["12", "Oslo"]}, qty: 2, rank: 5, totals: {grade: [0, 10]}, vip: true}], scores: {capped: true}, weight: 1.5}, total: []}], + ], +} + +// seed 344600 (attempt 0) +{ + name: "b 47: claim/accounts: 1 expression, 1 match, 3 table; 2 root, 3 per-member, 3 top-level computed", + policy: { + models: {claim: {days: "number?", price: "number", dueDate: "date", openedAt: "date?", accounts: "acct[]?"}, acct: {age: "number?", code: "string?"}}, + blocks: [ + {table: "t1", inputs: ["(claim.days ?? 0)", "claim.dueDate"], outputs: ["acct.fee", "acct.share", "acct.flag"], rules: [ + ["< 2", "< d('2024-01-01')", "", "(claim.days ?? 0)", "claim.price"], + ["<= 18", "< d('2025-01-01')", "sum(map((claim.accounts ?? []), ((#.age ?? 0) * (#.age ?? 0))))", "((claim.days ?? 0) - 1)", ""], + ["< 2", ">= d('2025-03-20')", "", "1.5", "(acct.age ?? 0)"], + ["> 0.25", ">= d('2000-06-30')", "((claim.days ?? 0) - (acct.age ?? 0))", "claim.price", ""], + ["", ">= d('2025-03-20')", "min([claim.price, (acct.age ?? 0)])", "(claim.days ?? 0)", "-((acct.age ?? 0))"], + ["", "", "(claim.days ?? 0)", "(claim.days ?? 0)", "(acct.age ?? 0)"], + ]}, + {expression: "claim.bucket", value: "(18 <= 10 and (claim.days ?? 0) <= 1000)"}, + {table: "t3", hit: "collect", inputs: ["(claim.openedAt ?? d('2025-01-01'))"], outputs: ["flags.total", "summary"], rules: [ + ["< d('2025-01-01')", "(claim.days ?? 0)", "(claim.bucket or claim.bucket)"], + [">= d('2025-01-01')", "claim.price", "claim.bucket"], + ["< d('2025-01-01')", "", "claim.price >= 5"], + ]}, + {match: "claim.risk", arms: [["len(summary) <= claim.price", "10"], ["claim.openedAt != null", "((claim.days ?? 0)) / (abs((claim.days ?? 0)) + 1)"], ["none((claim.accounts ?? []), (#.age ?? 0) <= (#.age ?? 0))", "(min(map((claim.accounts ?? []), (#.share ?? 0))) ?? 0)"], ["all((claim.accounts ?? []), isNumeric((#.code ?? '')))", "(claim.price / -6)"], ["", "count((claim.accounts ?? []), #.fee == null)"]]}, + {table: "t5", inputs: [null, "claim.days"], outputs: ["tag"], rules: [ + ["not (claim.bucket)", "5", "claim.price"], + ["(claim.days ?? 0) == (claim.days ?? 0)", "18, 0.5", "-(claim.risk)"], + ["", "3", ""], + ["claim.risk == claim.price", "18, 3", "1000"], + ["", "", "(claim.days ?? 0)"], + ]}, + ], + }, + cases: [ + [{claim: {days: 1000000, price: 18, dueDate: "1990-06-15", openedAt: "2024-02-29", accounts: []}}, {claim: {accounts: [], bucket: false, days: 1000000, dueDate: "1990-06-15", openedAt: "2024-02-29", price: 18, risk: 10}, flags: {total: [1000000]}, summary: [false, true], tag: 1000000}], + [{claim: {days: 100, price: 250, dueDate: "2030-12-31", openedAt: "2024-02-29", accounts: [{age: 18, code: "gold"}]}}, {claim: {accounts: [{age: 18, code: "gold", fee: 82, flag: -18, share: 250}], bucket: false, days: 100, dueDate: "2030-12-31", openedAt: "2024-02-29", price: 250, risk: 10}, flags: {total: [100]}, summary: [false, true], tag: 100}], + [{claim: {days: null, price: 3, dueDate: "2000-01-01", openedAt: null, accounts: [{age: -0.01, code: "NL"}, {age: 1.5}, {code: "a"}, {age: 1000, code: "gold"}]}}, {claim: {accounts: [{age: -0.01, code: "NL", fee: 1000002.2501, flag: 3, share: 0}, {age: 1.5, fee: 1000002.2501, flag: 3, share: 0}, {code: "a", fee: 1000002.2501, flag: 3, share: 0}, {age: 1000, code: "gold", fee: 1000002.2501, flag: 3, share: 0}], bucket: false, days: null, dueDate: "2000-01-01", openedAt: null, price: 3, risk: 10}, flags: {total: [3]}, summary: [false], tag: 0}], + [{claim: {price: 5, dueDate: "1990-06-15", openedAt: "2024-01-01", accounts: [{code: "-"}, {age: null, code: ""}, {age: 7.25, code: "Oslo"}]}}, {claim: {accounts: [{code: "-", fee: 52.5625, flag: 5, share: 0}, {age: null, code: "", fee: 52.5625, flag: 5, share: 0}, {age: 7.25, code: "Oslo", fee: 52.5625, flag: 5, share: 0}], bucket: false, dueDate: "1990-06-15", openedAt: "2024-01-01", price: 5, risk: 10}, flags: {total: [0]}, summary: [false, true], tag: 0}], + [{claim: {days: 0.5, price: 0.5, dueDate: null, openedAt: "2024-01-01", accounts: []}}, "!error: MissingRequiredInputs"], + [{claim: {days: 1000, price: 1000, dueDate: "2000-01-01", openedAt: "2025-03-20", accounts: []}}, {claim: {accounts: [], bucket: false, days: 1000, dueDate: "2000-01-01", openedAt: "2025-03-20", price: 1000, risk: 10}, flags: {total: [1000]}, summary: [false], tag: 1000}], + [{claim: {days: null, price: 99.99, dueDate: "2024-02-29", openedAt: null, accounts: [{code: null}, {age: -0.5, code: "abc"}, {code: " pad "}, {age: 0, code: "gold"}]}}, {claim: {accounts: [{code: null, fee: 0.25, flag: 0, share: -1}, {age: -0.5, code: "abc", fee: 0.25, flag: -0.5, share: -1}, {code: " pad ", fee: 0.25, flag: 0, share: -1}, {age: 0, code: "gold", fee: 0.25, flag: 0, share: -1}], bucket: false, days: null, dueDate: "2024-02-29", openedAt: null, price: 99.99, risk: 10}, flags: {total: [99.99]}, summary: [false], tag: 0}], + [{claim: {days: 0, price: 99.99, dueDate: "2024-01-01", openedAt: "2000-01-01", accounts: [{age: 18, code: "x-y"}, {age: 1.5, code: "gold"}, {age: 18, code: "Oslo"}]}}, {claim: {accounts: [{age: 18, code: "x-y", fee: 650.25, flag: 18, share: -1}, {age: 1.5, code: "gold", fee: 650.25, flag: 1.5, share: -1}, {age: 18, code: "Oslo", fee: 650.25, flag: 18, share: -1}], bucket: false, days: 0, dueDate: "2024-01-01", openedAt: "2000-01-01", price: 99.99, risk: 10}, flags: {total: [0]}, summary: [false, true], tag: 0}], + [{claim: {days: null, price: 1000, dueDate: "2030-12-31", openedAt: "2000-01-01", accounts: [{age: 31, code: null}, {age: 1e3, code: "3.5"}, {age: 18, code: "DE"}, {age: 65, code: "DE"}]}}, {claim: {accounts: [{age: 31, code: null, fee: 31, flag: 31, share: 1.5}, {age: 1000, code: "3.5", fee: 1000, flag: 1000, share: 1.5}, {age: 18, code: "DE", fee: 18, flag: 18, share: 1.5}, {age: 65, code: "DE", fee: 65, flag: 65, share: 1.5}], bucket: false, days: null, dueDate: "2030-12-31", openedAt: "2000-01-01", price: 1000, risk: 10}, flags: {total: [0]}, summary: [false, true], tag: 0}], + [{claim: {days: 3, price: 3, dueDate: "2030-12-31", openedAt: "2025-03-20", accounts: []}}, {claim: {accounts: [], bucket: false, days: 3, dueDate: "2030-12-31", openedAt: "2025-03-20", price: 3, risk: 10}, flags: {total: [3]}, summary: [false], tag: 3}], + [{claim: {days: 2.50, price: 0, dueDate: "2024-02-29", openedAt: 20250101, accounts: [{age: 3, code: "A1"}, {age: -500, code: "a"}]}}, "!error: InputValidationFailed"], + [{claim: {days: 123456789.123, price: 2, dueDate: "2025-03-20T10:15:30Z", openedAt: "2000-01-01", accounts: []}}, {claim: {accounts: [], bucket: false, days: 123456789.123, dueDate: "2025-03-20T10:15:30Z", openedAt: "2000-01-01", price: 2, risk: 10}, flags: {total: [123456789.123]}, summary: [false, false], tag: 123456789.123}], + [{claim: {price: 2, dueDate: "2024-02-29", openedAt: "2025-03-20", accounts: [{age: 3, code: "NL"}, {age: -0.01, code: null}, {}, {age: 99.99, code: "retail"}]}}, {claim: {accounts: [{age: 3, code: "NL", fee: 10007.0002, flag: 3, share: -1}, {age: -0.01, code: null, fee: 10007.0002, flag: -0.01, share: -1}, {fee: 10007.0002, flag: 0, share: -1}, {age: 99.99, code: "retail", fee: 10007.0002, flag: 99.99, share: -1}], bucket: false, dueDate: "2024-02-29", openedAt: "2025-03-20", price: 2, risk: 10}, flags: {total: [2]}, summary: [false], tag: 0}], + [{claim: {days: 5, price: 0.1, dueDate: "2024-02-29", openedAt: "2025-03-20T10:15:30Z", accounts: [{age: 100, code: "gold"}, {age: 0.1, code: " pad "}]}}, {claim: {accounts: [{age: 100, code: "gold", fee: 10000.01, flag: 100, share: 4}, {age: 0.1, code: " pad ", fee: 10000.01, flag: 0.1, share: 4}], bucket: false, days: 5, dueDate: "2024-02-29", openedAt: "2025-03-20T10:15:30Z", price: 0.1, risk: 0.8333333333333333333333333333}, flags: {total: [0.1]}, summary: [false], tag: 0.1}], + [{claim: {days: -500, price: 1, dueDate: "2000-01-01", accounts: []}}, {claim: {accounts: [], bucket: false, days: -500, dueDate: "2000-01-01", price: 1, risk: 10}, flags: {total: [1]}, summary: [false], tag: -500}], + [{claim: {days: 10, price: 3, dueDate: "2000-01-01", openedAt: "2000-01-01", accounts: [{age: 10, code: "gold"}, {age: 3, code: "DE"}]}}, {claim: {accounts: [{age: 10, code: "gold", fee: 109, flag: 10, share: 9}, {age: 3, code: "DE", fee: 109, flag: 3, share: 9}], bucket: false, days: 10, dueDate: "2000-01-01", openedAt: "2000-01-01", price: 3, risk: 10}, flags: {total: [10]}, summary: [false, false], tag: 10}], + ], +} + +// seed 344700 (attempt 0) +{ + name: "b 48: applicant/vehicles + address: 1 assertion, 5 expression, 1 match; 1 root, 1 per-member, 1 top-level computed", + policy: { + models: {applicant: {age: "number?", urgent: "boolean?", days: "number", priority: "boolean", vehicles: "vehicle[]", address: "address?"}, vehicle: {income: "number", qty: "number", active: "boolean?", plan: "string(basic|plus|premium|trial)?"}, address: {rate: "number", plan: "string(basic|plus|premium|trial)"}}, + globals: {settings: {cap: "number"}}, + blocks: [ + {expression: "vehicle.decision", value: "count(applicant.vehicles, #.qty in [43..71])"}, + {expression: "address.quota", value: "(totals.discount) / (abs(totals.discount) + 1)"}, + {match: "address.flags.exposure", arms: [["0.5 >= totals.discount", "'DE'"], ["applicant.urgent != null", "'ok'"], ["address.plan in ['basic', 'plus']", "`${(applicant.points ?? false)}/${(address.rate / -6)}`"], ["", "'Oslo'"]]}, + {assertion: "address.flags.weighted", conditions: [["and", "applicant.age != null", 0]]}, + {expression: "applicant.points", value: "(((applicant.address.total ?? false) and applicant.priority) ? applicant.urgent : null)"}, + {expression: "totals.discount", value: "len(filter(applicant.vehicles, not ((#.active ?? false))))"}, + {expression: "address.total", value: "(applicant.days in (13..169) or some(applicant.vehicles, ((#.active ?? false) or (#.active ?? false))))"}, + ], + }, + cases: [ + [{cap: 1, applicant: {age: null, days: 99.99, priority: true, vehicles: [], address: null}}, {applicant: {address: null, age: null, days: 99.99, priority: true, vehicles: []}, cap: 1, totals: {discount: 0}}], + [{cap: 100, applicant: {urgent: false, days: 0.5, priority: false, vehicles: [{income: 65, qty: 18, active: true, plan: "basic"}, {income: 0, qty: 65, active: null, plan: "premium"}, {income: 2, qty: 438, plan: "basic"}, {income: -0.01, qty: 7.25, active: true, plan: "trial"}, {income: 0, qty: -0.5, active: false, plan: "basic"}, {income: 0.5, qty: 0.5, active: false, plan: "basic"}, {income: 99999999999999999999, qty: -0.5, active: null, plan: null}, {income: 0.000001, qty: -1, plan: "plus"}, {income: 99999999999999999999, qty: -0.5, active: null, plan: "premium"}, {income: 18, qty: 1, plan: null}, {income: 1000, qty: 100, plan: "basic"}], address: null}}, {applicant: {address: null, days: 0.5, priority: false, urgent: false, vehicles: [{active: true, decision: 1, income: 65, plan: "basic", qty: 18}, {active: null, decision: 1, income: 0, plan: "premium", qty: 65}, {decision: 1, income: 2, plan: "basic", qty: 438}, {active: true, decision: 1, income: -0.01, plan: "trial", qty: 7.25}, {active: false, decision: 1, income: 0, plan: "basic", qty: -0.5}, {active: false, decision: 1, income: 0.5, plan: "basic", qty: 0.5}, {active: null, decision: 1, income: 99999999999999999999, plan: null, qty: -0.5}, {decision: 1, income: 0.000001, plan: "plus", qty: -1}, {active: null, decision: 1, income: 99999999999999999999, plan: "premium", qty: -0.5}, {decision: 1, income: 18, plan: null, qty: 1}, {decision: 1, income: 1000, plan: "basic", qty: 100}]}, cap: 100, totals: {discount: 9}}], + [{cap: -2, applicant: {urgent: true, days: 100, priority: true, vehicles: [{income: 7.25, qty: 2, active: true}], address: {rate: 1000000, plan: "trial"}}}, {applicant: {address: {flags: {exposure: "DE", weighted: false}, plan: "trial", quota: 0, rate: 1000000}, days: 100, priority: true, urgent: true, vehicles: [{active: true, decision: 0, income: 7.25, qty: 2}]}, cap: -2, totals: {discount: 0}}], + [{cap: -2, applicant: {age: 2.50, urgent: true, days: 18, priority: false, vehicles: [{income: 100, qty: 0, plan: "basic"}, {income: 0.1, qty: 1, active: null, plan: null}], address: {rate: 123456789.123, plan: "basic"}}}, {applicant: {address: {flags: {exposure: "ok", weighted: true}, plan: "basic", quota: 0.6666666666666666666666666667, rate: 123456789.123}, age: 2.50, days: 18, priority: false, urgent: true, vehicles: [{decision: 0, income: 100, plan: "basic", qty: 0}, {active: null, decision: 0, income: 0.1, plan: null, qty: 1}]}, cap: -2, totals: {discount: 2}}], + [{cap: 0, applicant: {age: 1, urgent: true, days: 100, priority: false, vehicles: [{income: 0.5, qty: 99.99, active: false, plan: "plus"}], address: {rate: 1e3, plan: "trial"}}}, {applicant: {address: {flags: {exposure: "ok", weighted: true}, plan: "trial", quota: 0.50, rate: 1000}, age: 1, days: 100, priority: false, urgent: true, vehicles: [{active: false, decision: 0, income: 0.5, plan: "plus", qty: 99.99}]}, cap: 0, totals: {discount: 1}}], + [{cap: 100, applicant: {age: 123456789.123, urgent: false, days: 7.25, priority: false, vehicles: [{income: 99999999999999999999, qty: 2, active: false, plan: null}, {income: 327, qty: -0.01, plan: "trial"}, {income: -500, qty: 5, active: true, plan: "plus"}], address: {rate: 5, plan: "trial"}}}, {applicant: {address: {flags: {exposure: "ok", weighted: true}, plan: "trial", quota: 0.6666666666666666666666666667, rate: 5}, age: 123456789.123, days: 7.25, priority: false, urgent: false, vehicles: [{active: false, decision: 0, income: 99999999999999999999, plan: null, qty: 2}, {decision: 0, income: 327, plan: "trial", qty: -0.01}, {active: true, decision: 0, income: -500, plan: "plus", qty: 5}]}, cap: 100, totals: {discount: 2}}], + [{cap: 0.5, applicant: {age: 1e3, urgent: true, days: -0, priority: false, vehicles: [{income: -0.01, qty: 1000, active: true, plan: "basic"}, {income: 0, qty: 1, active: true, plan: "basic"}], address: {rate: 5, plan: "trial"}}}, {applicant: {address: {flags: {exposure: "DE", weighted: true}, plan: "trial", quota: 0, rate: 5}, age: 1000, days: 0, priority: false, urgent: true, vehicles: [{active: true, decision: 0, income: -0.01, plan: "basic", qty: 1000}, {active: true, decision: 0, income: 0, plan: "basic", qty: 1}]}, cap: 0.5, totals: {discount: 0}}], + [{cap: -2, applicant: {age: 250, urgent: false, days: 2, priority: false, vehicles: [], address: {rate: 1e3, plan: "basic"}}}, {applicant: {address: {flags: {exposure: "DE", weighted: true}, plan: "basic", quota: 0, rate: 1000}, age: 250, days: 2, priority: false, urgent: false, vehicles: []}, cap: -2, totals: {discount: 0}}], + [{cap: 10, applicant: {age: 99999999999999999999, urgent: false, days: -0, priority: true, vehicles: [{income: 99.99, qty: 18, active: false, plan: "basic"}, {income: 10, qty: 18, active: true, plan: "plus"}, {income: 99999999999999999999, qty: 65, active: false, plan: "basic"}], address: {rate: 1e3, plan: "plus"}, extraField: "x"}}, {applicant: {address: {flags: {exposure: "ok", weighted: true}, plan: "plus", quota: 0.6666666666666666666666666667, rate: 1000}, age: 99999999999999999999, days: 0, extraField: "x", priority: true, urgent: false, vehicles: [{active: false, decision: 1, income: 99.99, plan: "basic", qty: 18}, {active: true, decision: 1, income: 10, plan: "plus", qty: 18}, {active: false, decision: 1, income: 99999999999999999999, plan: "basic", qty: 65}]}, cap: 10, totals: {discount: 2}}], + [{cap: -2, applicant: {age: 7.25, urgent: false, days: 468, priority: false, vehicles: [{income: 0.000001, qty: 0.5, active: true, plan: "basic"}, {income: 1e3, qty: 99.99, active: false, plan: "basic"}, {income: 0.5, qty: 0.1, active: false, plan: "plus"}, {income: -1, qty: -500, active: true, plan: "basic"}, {income: -0.5, qty: 100, active: false, plan: "basic"}], address: {rate: -0, plan: "plus"}}}, {applicant: {address: {flags: {exposure: "ok", weighted: true}, plan: "plus", quota: 0.75, rate: 0}, age: 7.25, days: 468, priority: false, urgent: false, vehicles: [{active: true, decision: 0, income: 0.000001, plan: "basic", qty: 0.5}, {active: false, decision: 0, income: 1000, plan: "basic", qty: 99.99}, {active: false, decision: 0, income: 0.5, plan: "plus", qty: 0.1}, {active: true, decision: 0, income: -1, plan: "basic", qty: -500}, {active: false, decision: 0, income: -0.5, plan: "basic", qty: 100}]}, cap: -2, totals: {discount: 3}}], + [{cap: 10, applicant: {age: null, urgent: null, days: 100, priority: false, vehicles: [{income: 1000000, qty: 18, plan: "trial"}], address: {rate: 99999999999999999999, plan: "plus"}}}, {applicant: {address: {flags: {exposure: "false/-16666666666666666666.50", weighted: false}, plan: "plus", quota: 0.50, rate: 99999999999999999999, total: true}, age: null, days: 100, points: null, priority: false, urgent: null, vehicles: [{decision: 0, income: 1000000, plan: "trial", qty: 18}]}, cap: 10, totals: {discount: 1}}], + [{cap: 1, applicant: {age: null, urgent: null, days: -500, priority: true, vehicles: [{income: 99.99, qty: 0, plan: null}, {income: 0.5, qty: 7.25, plan: null}, {income: 0.5, qty: 0, active: null}, {income: 99.99, qty: 2.50, active: true}], address: null}}, {applicant: {address: null, age: null, days: -500, priority: true, urgent: null, vehicles: [{decision: 0, income: 99.99, plan: null, qty: 0}, {decision: 0, income: 0.5, plan: null, qty: 7.25}, {active: null, decision: 0, income: 0.5, qty: 0}, {active: true, decision: 0, income: 99.99, qty: 2.50}]}, cap: 1, totals: {discount: 3}}], + [{cap: 1, applicant: {age: null, urgent: true, days: 0.1, priority: false, vehicles: [{income: 100, qty: -0.5, active: null, plan: null}, {income: 0, qty: -500, plan: "basic"}], address: {rate: 0, plan: "basic"}}}, {applicant: {address: {flags: {exposure: "ok", weighted: false}, plan: "basic", quota: 0.6666666666666666666666666667, rate: 0}, age: null, days: 0.1, priority: false, urgent: true, vehicles: [{active: null, decision: 0, income: 100, plan: null, qty: -0.5}, {decision: 0, income: 0, plan: "basic", qty: -500}]}, cap: 1, totals: {discount: 2}}], + [{cap: 0, applicant: {age: 0.5, urgent: false, days: -0.01, priority: false, vehicles: [{income: 65, qty: 0.5}, {income: 0, qty: 18, plan: "premium"}, {income: -1, qty: 250, active: true, plan: null}, {income: 65, qty: 1e3, active: false, plan: "basic"}], address: {rate: 0.000001, plan: "premium"}}}, {applicant: {address: {flags: {exposure: "ok", weighted: true}, plan: "premium", quota: 0.75, rate: 0.000001}, age: 0.5, days: -0.01, priority: false, urgent: false, vehicles: [{decision: 0, income: 65, qty: 0.5}, {decision: 0, income: 0, plan: "premium", qty: 18}, {active: true, decision: 0, income: -1, plan: null, qty: 250}, {active: false, decision: 0, income: 65, plan: "basic", qty: 1000}]}, cap: 0, totals: {discount: 3}}], + [{cap: -2, applicant: {age: [1], urgent: false, days: 1, priority: false, vehicles: [{income: 65, qty: 0.1, active: false, plan: "basic"}], address: {rate: 0.000001, plan: "trial"}}}, "!error: InputValidationFailed"], + [{cap: 1, applicant: {age: 1000, urgent: false, days: 250, priority: true, vehicles: [{income: -1, qty: 2.50, active: false, plan: "plus"}], address: {rate: 123456789.123, plan: "basic"}, extraField: {nested: true}}}, {applicant: {address: {flags: {exposure: "ok", weighted: true}, plan: "basic", quota: 0.50, rate: 123456789.123}, age: 1000, days: 250, extraField: {nested: true}, priority: true, urgent: false, vehicles: [{active: false, decision: 0, income: -1, plan: "plus", qty: 2.50}]}, cap: 1, totals: {discount: 1}}], + ], +} + +// seed 344800 (attempt 0) +{ + name: "b 49: shipment/vehicles + profile: 1 assertion, 4 expression, 1 match, 1 table; 6 root, 0 per-member, 1 top-level computed", + policy: { + models: {shipment: {price: "number?", country: "string?", weight: "number", openedAt: "date", vip: "boolean?", vehicles: "vehicle[]", profile: "profile"}, vehicle: {price: "number", kind: "string(retail|corporate)", country: "string", weight: "number?"}, profile: {age: "number", since: "date"}}, + blocks: [ + {expression: "shipment.segment", value: "{v: (shipment.country ?? ''), n: matches(`${(shipment.vip ?? false)}/${(shipment.vip ?? false)}`, '[0-9]$'), s: (shipment.country ?? '')}"}, + {table: "t7", inputs: ["(profile.age) / (abs(shipment.weight) + 1)", "profile.calc.capped"], outputs: ["profile.calc.flag[]"], rules: [ + ["< 250", "", "shipment.segment.n"], + ["<= 1.5", "startsWith($, 'low')", "(shipment.decision ?? false)"], + ["< 2", "'A1', 'US'", "(shipment.vip ?? false)"], + ["[50..346]", "'VIP'", "shipment.segment.v in ['US', 'none']"], + ["< 3", "'a', 'x'", "shipment.segment.n"], + ["", "$ != 'DE'", "scores.total"], + [">= 0.5", "", "(shipment.decision ?? false)"], + ]}, + {expression: "shipment.decision", value: "(contains((shipment.country ?? ''), 'none') ? shipment.vip : null)"}, + {assertion: "scores.total", conditions: ["contains(['low', 'low', ''], (shipment.country ?? ''))", ["and", "shipment.weight in [43..188)", 0], ["or", "shipment.decision == null", 2], ["or", "((shipment.decision ?? false) and (shipment.vip ?? false))", 1], ["and", "(shipment.country ?? '') in ['x', 'none']", 1]]}, + {expression: "profile.margin", value: "profile.since.add(2, 'year')"}, + {match: "profile.calc.capped", arms: [["(((shipment.vip ?? false) or (shipment.decision ?? false)) and (shipment.price ?? 0) in [49..184])", "((shipment.decision ?? false) ? 'gold' : shipment.segment.v)"], ["not ((scores.total or (shipment.vip ?? false)))", "`${profile.age}/${scores.total}`"], ["", "'A1'"]]}, + {expression: "shipment.totals.band", value: "filter(shipment.vehicles, (#.weight ?? 0) < 18)"}, + ], + }, + cases: [ + [{shipment: {price: -0.5, country: "high", weight: 99999999999999999999, openedAt: "2030-12-31", vip: false, vehicles: [{price: 1.5, kind: "corporate", country: "low", weight: 100}], profile: {age: -500, since: "2024-02-29"}, extraField: {nested: true}}}, {scores: {total: false}, shipment: {country: "high", decision: null, extraField: {nested: true}, openedAt: "2030-12-31", price: -0.5, profile: {age: -500, calc: {capped: "-500/false", flag: [false, false]}, margin: "Invalid date", since: "2024-02-29"}, segment: {n: false, s: "high", v: "high"}, totals: {band: []}, vehicles: [{country: "low", kind: "corporate", price: 1.5, weight: 100}], vip: false, weight: 99999999999999999999}}], + [{shipment: {price: 3, country: "Zed", weight: [1], openedAt: "2000-01-01", vip: true, vehicles: [{price: 99.99, kind: "retail", country: "US", weight: 277}], profile: {age: 0.25, since: "2000-01-01"}}}, "!error: InputValidationFailed"], + [{shipment: {price: null, weight: 250, openedAt: "1990-06-15", vip: true, vehicles: [{price: -0.5, kind: "retail", country: "3.5", weight: null}, {price: 0.000001, kind: "corporate", country: "retail", weight: 2}], profile: {age: 5, since: "2030-12-31"}}}, {scores: {total: false}, shipment: {decision: null, openedAt: "1990-06-15", price: null, profile: {age: 5, calc: {capped: "A1", flag: [false, true, false]}, margin: "2032-12-31T00:00:00Z", since: "2030-12-31"}, segment: {n: false, s: "", v: ""}, totals: {band: [{country: "3.5", kind: "retail", price: -0.5, weight: null}, {country: "retail", kind: "corporate", price: 0.000001, weight: 2}]}, vehicles: [{country: "3.5", kind: "retail", price: -0.5, weight: null}, {country: "retail", kind: "corporate", price: 0.000001, weight: 2}], vip: true, weight: 250}}], + [{shipment: {price: 5, country: "A1", weight: 1000000, openedAt: "2024-02-29", vip: null, vehicles: [{price: -0.5, kind: "retail", country: "none", weight: 0}], profile: {age: 100, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: "A1", decision: null, openedAt: "2024-02-29", price: 5, profile: {age: 100, calc: {capped: "100/false", flag: [false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "A1", v: "A1"}, totals: {band: [{country: "none", kind: "retail", price: -0.5, weight: 0}]}, vehicles: [{country: "none", kind: "retail", price: -0.5, weight: 0}], vip: null, weight: 1000000}}], + [{shipment: {price: 100, country: "retail", weight: 1000, openedAt: "2024-01-01", vehicles: [{price: 250, kind: "retail", country: "a", weight: 0.5}, {price: 0.5, kind: "retail", country: "retail", weight: null}, {price: 0.1, kind: "corporate", country: "DE", weight: 0.5}, {price: 18, kind: "corporate", country: "low"}, {price: 0.000001, kind: "retail", country: "none", weight: -0.5}], profile: {age: 250, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: "retail", decision: null, openedAt: "2024-01-01", price: 100, profile: {age: 250, calc: {capped: "250/false", flag: [false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "retail", v: "retail"}, totals: {band: [{country: "a", kind: "retail", price: 250, weight: 0.5}, {country: "retail", kind: "retail", price: 0.5, weight: null}, {country: "DE", kind: "corporate", price: 0.1, weight: 0.5}, {country: "low", kind: "corporate", price: 18}, {country: "none", kind: "retail", price: 0.000001, weight: -0.5}]}, vehicles: [{country: "a", kind: "retail", price: 250, weight: 0.5}, {country: "retail", kind: "retail", price: 0.5, weight: null}, {country: "DE", kind: "corporate", price: 0.1, weight: 0.5}, {country: "low", kind: "corporate", price: 18}, {country: "none", kind: "retail", price: 0.000001, weight: -0.5}], weight: 1000}}], + [{shipment: {price: null, country: "none", weight: -0.01, openedAt: "1990-06-15", vehicles: [{price: 100, kind: "retail", country: "", weight: -0.01}, {price: -1, kind: "retail", country: "DE", weight: 100}, {price: 1.5, kind: "corporate", country: "US", weight: null}], profile: {age: 99.99, since: "1990-06-15"}}}, {scores: {total: false}, shipment: {country: "none", decision: null, openedAt: "1990-06-15", price: null, profile: {age: 99.99, calc: {capped: "99.99/false", flag: [false, false, false]}, margin: "1992-06-15T00:00:00Z", since: "1990-06-15"}, segment: {n: false, s: "none", v: "none"}, totals: {band: [{country: "", kind: "retail", price: 100, weight: -0.01}, {country: "US", kind: "corporate", price: 1.5, weight: null}]}, vehicles: [{country: "", kind: "retail", price: 100, weight: -0.01}, {country: "DE", kind: "retail", price: -1, weight: 100}, {country: "US", kind: "corporate", price: 1.5, weight: null}], weight: -0.01}}], + [{shipment: {price: 5, country: "VIP", weight: 1, openedAt: "2025-03-20", vip: false, vehicles: [], profile: {age: 1000, since: "2025-03-20"}}}, {scores: {total: false}, shipment: {country: "VIP", decision: null, openedAt: "2025-03-20", price: 5, profile: {age: 1000, calc: {capped: "1000/false", flag: [false, false]}, margin: "2027-03-20T00:00:00Z", since: "2025-03-20"}, totals: {band: []}, vehicles: [], vip: false, weight: 1}}], + [{shipment: {price: 2, country: "a-b-c", weight: 250, openedAt: "2030-12-31", vip: false, vehicles: [{price: 100, kind: "retail", country: "O'Neil", weight: 1.5}, {price: 134, kind: "retail", country: "A1", weight: 100}], profile: {age: 0.5, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: "a-b-c", decision: null, openedAt: "2030-12-31", price: 2, profile: {age: 0.5, calc: {capped: "0.5/false", flag: [false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "a-b-c", v: "a-b-c"}, totals: {band: [{country: "O'Neil", kind: "retail", price: 100, weight: 1.5}]}, vehicles: [{country: "O'Neil", kind: "retail", price: 100, weight: 1.5}, {country: "A1", kind: "retail", price: 134, weight: 100}], vip: false, weight: 250}}], + [{shipment: {price: 123456789.123, country: "x", weight: -500, openedAt: "2025-03-20", vip: true, vehicles: [{price: 0.5, kind: "retail", country: "a", weight: null}, {price: 1000, kind: "retail", country: "A1"}, {price: 50, kind: "retail", country: "high", weight: 363}], profile: {age: 1.5, since: "2024-02-29"}}}, {scores: {total: false}, shipment: {country: "x", decision: null, openedAt: "2025-03-20", price: 123456789.123, profile: {age: 1.5, calc: {capped: "A1", flag: [false, true, false]}, margin: "Invalid date", since: "2024-02-29"}, segment: {n: false, s: "x", v: "x"}, totals: {band: [{country: "a", kind: "retail", price: 0.5, weight: null}, {country: "A1", kind: "retail", price: 1000}]}, vehicles: [{country: "a", kind: "retail", price: 0.5, weight: null}, {country: "A1", kind: "retail", price: 1000}, {country: "high", kind: "retail", price: 50, weight: 363}], vip: true, weight: -500}}], + [{shipment: {price: -500, country: "A1", weight: 0, openedAt: "2030-12-31", vip: true, vehicles: [{price: 10, kind: "retail", country: "x", weight: -500}, {price: 100, kind: "corporate", country: "none", weight: 0.5}, {price: 5, kind: "retail", country: "US", weight: 2}, {price: 1.5, kind: "retail", country: "none", weight: 1000}], profile: {age: 0.000001, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: "A1", decision: null, openedAt: "2030-12-31", price: -500, profile: {age: 0.000001, calc: {capped: "A1", flag: [false, true, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "A1", v: "A1"}, totals: {band: [{country: "x", kind: "retail", price: 10, weight: -500}, {country: "none", kind: "corporate", price: 100, weight: 0.5}, {country: "US", kind: "retail", price: 5, weight: 2}]}, vehicles: [{country: "x", kind: "retail", price: 10, weight: -500}, {country: "none", kind: "corporate", price: 100, weight: 0.5}, {country: "US", kind: "retail", price: 5, weight: 2}, {country: "none", kind: "retail", price: 1.5, weight: 1000}], vip: true, weight: 0}}], + [{shipment: {price: -0.5, country: "gold", weight: 18, openedAt: "2025-03-20", vip: false, vehicles: [{price: 0.5, kind: "retail", country: "retail", weight: 250}], profile: {age: 0, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: "gold", decision: null, openedAt: "2025-03-20", price: -0.5, profile: {age: 0, calc: {capped: "0/false", flag: [false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "gold", v: "gold"}, totals: {band: []}, vehicles: [{country: "retail", kind: "retail", price: 0.5, weight: 250}], vip: false, weight: 18}}], + [{shipment: {price: -1, country: "low", weight: 250, openedAt: "1990-06-15", vip: false, vehicles: [{price: 1000, kind: "retail", country: "12", weight: 0.25}, {price: 65, kind: "retail", country: "retail", weight: 99.99}, {price: 3, kind: "corporate", country: "日本", weight: 1000}, {price: 0.25, kind: "corporate", country: "3.5", weight: 0.1}, {price: 0.000001, kind: "corporate", country: "é ü", weight: 123456789.123}], profile: {age: 0, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: "low", decision: null, openedAt: "1990-06-15", price: -1, profile: {age: 0, calc: {capped: "0/false", flag: [false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "low", v: "low"}, totals: {band: [{country: "12", kind: "retail", price: 1000, weight: 0.25}, {country: "3.5", kind: "corporate", price: 0.25, weight: 0.1}]}, vehicles: [{country: "12", kind: "retail", price: 1000, weight: 0.25}, {country: "retail", kind: "retail", price: 65, weight: 99.99}, {country: "日本", kind: "corporate", price: 3, weight: 1000}, {country: "3.5", kind: "corporate", price: 0.25, weight: 0.1}, {country: "é ü", kind: "corporate", price: 0.000001, weight: 123456789.123}], vip: false, weight: 250}}], + [{shipment: {price: 99.99, country: "gold", weight: 1.5, openedAt: "2025-03-20", vip: false, vehicles: [], profile: {age: -1, since: "2024-02-29"}}}, {scores: {total: false}, shipment: {country: "gold", decision: null, openedAt: "2025-03-20", price: 99.99, profile: {age: -1, calc: {capped: "-1/false", flag: [false, false]}, margin: "Invalid date", since: "2024-02-29"}, segment: {n: false, s: "gold", v: "gold"}, totals: {band: []}, vehicles: [], vip: false, weight: 1.5}}], + [{shipment: {price: 0.25, country: "low", weight: 250, openedAt: "1990-06-15", vip: true, vehicles: [{price: 0.1, kind: "corporate", country: "3.5", weight: [1]}], profile: {age: 1000000, since: "2025-03-20T10:15:30Z"}}}, "!error: InputValidationFailed"], + [{shipment: {price: 7.25, country: "3.5", weight: 486, openedAt: "2030-12-31", vip: false, vehicles: [{price: 65, kind: "retail", country: "A1", weight: 5}, {price: 2, kind: "retail", country: "low"}, {price: 100, kind: "retail", country: "US", weight: 5}, {price: 0.5, kind: "retail", country: "gold"}, {price: 65, kind: "retail", country: "12", weight: null}], profile: {age: 1e3, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: "3.5", decision: null, openedAt: "2030-12-31", price: 7.25, profile: {age: 1000, calc: {capped: "1000/false", flag: [false, false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "3.5", v: "3.5"}, totals: {band: [{country: "A1", kind: "retail", price: 65, weight: 5}, {country: "low", kind: "retail", price: 2}, {country: "US", kind: "retail", price: 100, weight: 5}, {country: "gold", kind: "retail", price: 0.5}, {country: "12", kind: "retail", price: 65, weight: null}]}, vehicles: [{country: "A1", kind: "retail", price: 65, weight: 5}, {country: "low", kind: "retail", price: 2}, {country: "US", kind: "retail", price: 100, weight: 5}, {country: "gold", kind: "retail", price: 0.5}, {country: "12", kind: "retail", price: 65, weight: null}], vip: false, weight: 486}}], + [{shipment: {price: 2, country: "x", weight: 7.25, openedAt: "2025-03-20", vip: false, vehicles: [{price: null, kind: "corporate", country: "A1", weight: 250}], profile: {age: 0.5, since: "1990-06-15"}}}, {scores: {total: false}, shipment: {country: "x", decision: null, openedAt: "2025-03-20", price: 2, profile: {age: 0.5, calc: {capped: "0.5/false", flag: [false, false]}, margin: "1992-06-15T00:00:00Z", since: "1990-06-15"}, segment: {n: false, s: "x", v: "x"}, totals: {band: []}, vehicles: [{country: "A1", kind: "corporate", price: null, weight: 250}], vip: false, weight: 7.25}}], + [{shipment: {price: 10, country: "retail", weight: 250, openedAt: "2024-01-01", vip: false, vehicles: [{price: -0.5, kind: "retail", country: "12", weight: -0}, {price: 250, kind: "retail", country: "é ü", weight: null}], profile: {age: 1.5, since: "2000-01-01"}}}, {scores: {total: false}, shipment: {country: "retail", decision: null, openedAt: "2024-01-01", price: 10, profile: {age: 1.5, calc: {capped: "1.5/false", flag: [false, false]}, margin: "2002-01-01T00:00:00Z", since: "2000-01-01"}, segment: {n: false, s: "retail", v: "retail"}, totals: {band: [{country: "12", kind: "retail", price: -0.5, weight: 0}, {country: "é ü", kind: "retail", price: 250, weight: null}]}, vehicles: [{country: "12", kind: "retail", price: -0.5, weight: 0}, {country: "é ü", kind: "retail", price: 250, weight: null}], vip: false, weight: 250}}], + [{shipment: {price: 250, weight: -0, openedAt: "2025-03-20T10:15:30Z", vehicles: [{price: -0, kind: "retail", country: "low", weight: 3}], profile: {age: 3, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {decision: null, openedAt: "2025-03-20T10:15:30Z", price: 250, profile: {age: 3, calc: {capped: "3/false", flag: [false, false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "", v: ""}, totals: {band: [{country: "low", kind: "retail", price: 0, weight: 3}]}, vehicles: [{country: "low", kind: "retail", price: 0, weight: 3}], weight: 0}}], + [{shipment: {price: 1000, country: null, weight: 2.50, openedAt: "2030-12-31", vehicles: [{price: 0, kind: "retail", country: "VIP", weight: 0.5}], profile: {age: -0.5, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: null, decision: null, openedAt: "2030-12-31", price: 1000, profile: {age: -0.5, calc: {capped: "-0.5/false", flag: [false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "", v: ""}, totals: {band: [{country: "VIP", kind: "retail", price: 0, weight: 0.5}]}, vehicles: [{country: "VIP", kind: "retail", price: 0, weight: 0.5}], weight: 2.50}}], + [{shipment: {price: "12", country: "", weight: 10, openedAt: "2030-12-31", vip: false, vehicles: [], profile: {age: 76, since: "2024-01-01"}}}, "!error: InputValidationFailed"], + [{shipment: {price: 1000, country: "retail", weight: 3, openedAt: "2024-01-01", vip: false, vehicles: [{price: 100, kind: "retail", country: "DE"}], profile: {age: 2, since: "2024-01-01"}}}, {scores: {total: false}, shipment: {country: "retail", decision: null, openedAt: "2024-01-01", price: 1000, profile: {age: 2, calc: {capped: "2/false", flag: [false, false, false]}, margin: "2026-01-01T00:00:00Z", since: "2024-01-01"}, segment: {n: false, s: "retail", v: "retail"}, totals: {band: [{country: "DE", kind: "retail", price: 100}]}, vehicles: [{country: "DE", kind: "retail", price: 100}], vip: false, weight: 3}}], + [{shipment: {price: 200, country: null, weight: 18, openedAt: "2024-02-29", vip: null, vehicles: [{price: 0.5, kind: "retail", country: "VIP"}, {price: -1, kind: "corporate", country: "retail", weight: null}, {price: 1, kind: "retail", country: "none", weight: 1000000}], profile: {age: 0.5, since: "2025-03-20T10:15:30Z"}}}, {scores: {total: false}, shipment: {country: null, decision: null, openedAt: "2024-02-29", price: 200, profile: {age: 0.5, calc: {capped: "0.5/false", flag: [false, false]}, margin: "2027-03-20T10:15:30Z", since: "2025-03-20T10:15:30Z"}, segment: {n: false, s: "", v: ""}, totals: {band: [{country: "VIP", kind: "retail", price: 0.5}, {country: "retail", kind: "corporate", price: -1, weight: null}]}, vehicles: [{country: "VIP", kind: "retail", price: 0.5}, {country: "retail", kind: "corporate", price: -1, weight: null}, {country: "none", kind: "retail", price: 1, weight: 1000000}], vip: null, weight: 18}}], + ], +} + +// seed 344900 (attempt 0) +{ + name: "b 50: applicant/companies/parts: 6 expression, 2 match, 3 table; 4 root, 7 per-member, 1 top-level computed", + policy: { + models: {applicant: {score: "number", years: "number", weight: "number?", openedAt: "date", urgent: "boolean", companies: "company[]"}, company: {price: "number?", priority: "boolean?", parts: "part[]"}, part: {weight: "number", label: "string?", rate: "number"}}, + blocks: [ + {table: "t1", inputs: ["company.priority", "(applicant.weight ?? 0)"], outputs: ["company.scores.quota", "company.flags.total"], rules: [ + ["false", "", "applicant.score", "applicant.score"], + ["true", ">= 3", "(applicant.weight ?? 0)", "len(filter(company.parts, #.weight != #.rate))"], + ["false", "> 250", "(company.price ?? 0)", "applicant.score"], + ["", ">= 3", "applicant.years", "applicant.score"], + ["", "", "100", "applicant.years"], + ]}, + {expression: "applicant.calc.summary", value: "applicant.openedAt"}, + {table: "t3", inputs: ["applicant.openedAt", "applicant.years", "applicant.years"], outputs: ["applicant.health"], rules: [ + ["", "[10..43]", "<= 0.25", "applicant.urgent"], + ["", "!= 100", "<= 1", "applicant.urgent"], + ["", "", "", "applicant.urgent"], + ]}, + {match: "company.capped", arms: [["string((company.scores.quota ?? 0)) == 'gold'", "((company.priority ?? false) ? 'ok' : 'x')"], ["matches(`${'Oslo'}/${(applicant.health ?? false)}`, '^.{2,}$')", "string((min([abs(applicant.years), 1000]) ^ 2))"], ["((company.priority ?? false) and (company.priority ?? false))", "string(applicant.urgent)"], ["", "string((company.priority ?? false))"]]}, + {expression: "applicant.band", value: "applicant.weight"}, + {expression: "company.flags.bucket", value: "company.capped"}, + {expression: "meta.flag", value: "filter(applicant.companies, -((#.price ?? 0)) != (#.flags.total ?? 0))"}, + {expression: "company.share", value: "applicant.calc.summary"}, + {match: "company.adjusted", arms: [["company.scores.quota == null", "company.flags.bucket"], ["not ((applicant.health ?? false))", "(applicant.openedAt.isAfter(d('2000-06-30'), 'month') ? trim(company.flags.bucket) : string((applicant.health ?? false)))"], ["", "trim(company.flags.bucket)"]]}, + {table: "t10", inputs: ["applicant.weight"], outputs: ["applicant.risk"], rules: [ + ["", ""], + ["1000, 3", "(applicant.health ?? false)"], + ["3", "applicant.urgent"], + ["100, 3", ""], + ["1000", "(applicant.health ?? false)"], + ]}, + {expression: "company.decision", value: "none(company.parts, #.rate in (10..112))"}, + ], + }, + cases: [ + [{applicant: {score: 458, years: 65, weight: null, openedAt: "1990-06-15", urgent: false, companies: [{price: 0.1, priority: false, parts: [{weight: 0.000001, rate: 100}, {weight: 0, label: "Oslo", rate: 172}, {weight: 2, label: null, rate: 100}]}, {priority: false, parts: []}, {price: 250, priority: false, parts: [{weight: 1, label: " pad ", rate: 0.1}, {weight: 1000, label: "DE", rate: 0}]}, {price: null, priority: null, parts: []}, {price: 7.25, parts: []}]}}, {applicant: {band: null, calc: {summary: "1990-06-15"}, companies: [{adjusted: "false", capped: "4225", decision: false, flags: {bucket: "4225", total: 458}, parts: [{rate: 100, weight: 0.000001}, {label: "Oslo", rate: 172, weight: 0}, {label: null, rate: 100, weight: 2}], price: 0.1, priority: false, scores: {quota: 458}, share: "1990-06-15"}, {adjusted: "false", capped: "4225", decision: true, flags: {bucket: "4225", total: 458}, parts: [], priority: false, scores: {quota: 458}, share: "1990-06-15"}, {adjusted: "false", capped: "4225", decision: true, flags: {bucket: "4225", total: 458}, parts: [{label: " pad ", rate: 0.1, weight: 1}, {label: "DE", rate: 0, weight: 1000}], price: 250, priority: false, scores: {quota: 458}, share: "1990-06-15"}, {adjusted: "false", capped: "4225", decision: true, flags: {bucket: "4225", total: 65}, parts: [], price: null, priority: null, scores: {quota: 100}, share: "1990-06-15"}, {adjusted: "false", capped: "4225", decision: true, flags: {bucket: "4225", total: 65}, parts: [], price: 7.25, scores: {quota: 100}, share: "1990-06-15"}], health: false, openedAt: "1990-06-15", risk: null, score: 458, urgent: false, weight: null, years: 65}, meta: {flag: [{adjusted: "false", capped: "4225", decision: false, flags: {bucket: "4225", total: 458}, parts: [{rate: 100, weight: 0.000001}, {label: "Oslo", rate: 172, weight: 0}, {label: null, rate: 100, weight: 2}], price: 0.1, priority: false, scores: {quota: 458}, share: "1990-06-15"}, {adjusted: "false", capped: "4225", decision: true, flags: {bucket: "4225", total: 458}, parts: [], priority: false, scores: {quota: 458}, share: "1990-06-15"}, {adjusted: "false", capped: "4225", decision: true, flags: {bucket: "4225", total: 458}, parts: [{label: " pad ", rate: 0.1, weight: 1}, {label: "DE", rate: 0, weight: 1000}], price: 250, priority: false, scores: {quota: 458}, share: "1990-06-15"}, {adjusted: "false", capped: "4225", decision: true, flags: {bucket: "4225", total: 65}, parts: [], price: null, priority: null, scores: {quota: 100}, share: "1990-06-15"}, {adjusted: "false", capped: "4225", decision: true, flags: {bucket: "4225", total: 65}, parts: [], price: 7.25, scores: {quota: 100}, share: "1990-06-15"}]}}], + [{applicant: {score: 100, years: -0.5, weight: 3, openedAt: "1990-06-15", urgent: false, companies: [{price: null, parts: [{weight: 1.5, label: "DE", rate: 99999999999999999999}]}]}}, {applicant: {band: 3, calc: {summary: "1990-06-15"}, companies: [{adjusted: "false", capped: "0.25", decision: true, flags: {bucket: "0.25", total: 100}, parts: [{label: "DE", rate: 99999999999999999999, weight: 1.5}], price: null, scores: {quota: -0.5}, share: "1990-06-15"}], health: false, openedAt: "1990-06-15", risk: false, score: 100, urgent: false, weight: 3, years: -0.5}, meta: {flag: [{adjusted: "false", capped: "0.25", decision: true, flags: {bucket: "0.25", total: 100}, parts: [{label: "DE", rate: 99999999999999999999, weight: 1.5}], price: null, scores: {quota: -0.5}, share: "1990-06-15"}]}}], + [{applicant: {score: 1.5, years: 3, weight: 100, openedAt: "2024-01-01", urgent: true, companies: [{price: null, parts: [{weight: 100, rate: 3}, {weight: 18, label: "gold", rate: 100}, {weight: -0.01, label: "DE", rate: 1000}]}, {price: 1e3, priority: true, parts: [{weight: 100, label: "NL", rate: 1}]}, {price: null, priority: true, parts: [{weight: 10, label: "gold", rate: 100}]}, {price: 3, priority: true, parts: [{weight: 100, label: " pad ", rate: 100}, {weight: 1000000, label: "12", rate: 5}, {weight: 250, label: "é ü", rate: 65}]}]}}, {applicant: {band: 100, calc: {summary: "2024-01-01"}, companies: [{adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 1.5}, parts: [{rate: 3, weight: 100}, {label: "gold", rate: 100, weight: 18}, {label: "DE", rate: 1000, weight: -0.01}], price: null, scores: {quota: 3}, share: "2024-01-01"}, {adjusted: "9", capped: "9", decision: true, flags: {bucket: "9", total: 1}, parts: [{label: "NL", rate: 1, weight: 100}], price: 1000, priority: true, scores: {quota: 100}, share: "2024-01-01"}, {adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 1}, parts: [{label: "gold", rate: 100, weight: 10}], price: null, priority: true, scores: {quota: 100}, share: "2024-01-01"}, {adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 2}, parts: [{label: " pad ", rate: 100, weight: 100}, {label: "12", rate: 5, weight: 1000000}, {label: "é ü", rate: 65, weight: 250}], price: 3, priority: true, scores: {quota: 100}, share: "2024-01-01"}], health: true, openedAt: "2024-01-01", risk: null, score: 1.5, urgent: true, weight: 100, years: 3}, meta: {flag: [{adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 1.5}, parts: [{rate: 3, weight: 100}, {label: "gold", rate: 100, weight: 18}, {label: "DE", rate: 1000, weight: -0.01}], price: null, scores: {quota: 3}, share: "2024-01-01"}, {adjusted: "9", capped: "9", decision: true, flags: {bucket: "9", total: 1}, parts: [{label: "NL", rate: 1, weight: 100}], price: 1000, priority: true, scores: {quota: 100}, share: "2024-01-01"}, {adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 1}, parts: [{label: "gold", rate: 100, weight: 10}], price: null, priority: true, scores: {quota: 100}, share: "2024-01-01"}, {adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 2}, parts: [{label: " pad ", rate: 100, weight: 100}, {label: "12", rate: 5, weight: 1000000}, {label: "é ü", rate: 65, weight: 250}], price: 3, priority: true, scores: {quota: 100}, share: "2024-01-01"}]}}], + [{applicant: {score: 65, years: 314, weight: 3, openedAt: "2024-01-01", urgent: true, companies: [{price: null, priority: null, parts: [{weight: 18, label: "A1", rate: 1.5}, {weight: 0.25, rate: 0.25}, {weight: 483, label: "A1", rate: 100}]}]}}, {applicant: {band: 3, calc: {summary: "2024-01-01"}, companies: [{adjusted: "98596", capped: "98596", decision: false, flags: {bucket: "98596", total: 65}, parts: [{label: "A1", rate: 1.5, weight: 18}, {rate: 0.25, weight: 0.25}, {label: "A1", rate: 100, weight: 483}], price: null, priority: null, scores: {quota: 314}, share: "2024-01-01"}], health: true, openedAt: "2024-01-01", risk: true, score: 65, urgent: true, weight: 3, years: 314}, meta: {flag: [{adjusted: "98596", capped: "98596", decision: false, flags: {bucket: "98596", total: 65}, parts: [{label: "A1", rate: 1.5, weight: 18}, {rate: 0.25, weight: 0.25}, {label: "A1", rate: 100, weight: 483}], price: null, priority: null, scores: {quota: 314}, share: "2024-01-01"}]}}], + [{applicant: {score: 1000, years: 1000, weight: 99999999999999999999, openedAt: "2024-01-01", urgent: true, companies: [{price: 0.000001, priority: true, parts: []}, {price: 100, priority: false, parts: [{weight: 99999999999999999999, label: "VIP", rate: 1.5}, {weight: 1.5, label: " pad ", rate: 2}, {weight: 3, label: "NL", rate: 1.5}]}, {price: 0, priority: false, parts: []}]}}, {applicant: {band: 99999999999999999999, calc: {summary: "2024-01-01"}, companies: [{adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 0}, parts: [], price: 0.000001, priority: true, scores: {quota: 99999999999999999999}, share: "2024-01-01"}, {adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 1000}, parts: [{label: "VIP", rate: 1.5, weight: 99999999999999999999}, {label: " pad ", rate: 2, weight: 1.5}, {label: "NL", rate: 1.5, weight: 3}], price: 100, priority: false, scores: {quota: 1000}, share: "2024-01-01"}, {adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 1000}, parts: [], price: 0, priority: false, scores: {quota: 1000}, share: "2024-01-01"}], health: true, openedAt: "2024-01-01", risk: null, score: 1000, urgent: true, weight: 99999999999999999999, years: 1000}, meta: {flag: [{adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 0}, parts: [], price: 0.000001, priority: true, scores: {quota: 99999999999999999999}, share: "2024-01-01"}, {adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 1000}, parts: [{label: "VIP", rate: 1.5, weight: 99999999999999999999}, {label: " pad ", rate: 2, weight: 1.5}, {label: "NL", rate: 1.5, weight: 3}], price: 100, priority: false, scores: {quota: 1000}, share: "2024-01-01"}, {adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 1000}, parts: [], price: 0, priority: false, scores: {quota: 1000}, share: "2024-01-01"}]}}], + [{applicant: {score: 3, years: 100, weight: null, openedAt: "2024-02-29", urgent: true, companies: [{price: null, parts: [{weight: 2, label: null, rate: 1000}]}]}}, {applicant: {band: null, calc: {summary: "2024-02-29"}, companies: [{adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 100}, parts: [{label: null, rate: 1000, weight: 2}], price: null, scores: {quota: 100}, share: "2024-02-29"}], health: true, openedAt: "2024-02-29", risk: null, score: 3, urgent: true, weight: null, years: 100}, meta: {flag: [{adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 100}, parts: [{label: null, rate: 1000, weight: 2}], price: null, scores: {quota: 100}, share: "2024-02-29"}]}}], + [{applicant: {score: 1.5, years: 1.5, weight: 3, openedAt: "2025-03-20", urgent: false, companies: [{price: null, priority: false, parts: [{weight: 10, label: null, rate: 10}]}, {priority: true, parts: [{weight: -0.01, rate: 1}, {weight: 1000, rate: 100}]}, {price: 100, parts: [{weight: 3, label: "3.5", rate: 123456789.123}, {weight: -1, label: "A1", rate: 0.25}]}, {price: 0.5, parts: [{weight: 0.000001, label: "", rate: 1000}, {weight: 3, rate: 100}]}]}}, {applicant: {band: 3, calc: {summary: "2025-03-20"}, companies: [{adjusted: "2.25", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 1.5}, parts: [{label: null, rate: 10, weight: 10}], price: null, priority: false, scores: {quota: 1.5}, share: "2025-03-20"}, {adjusted: "2.25", capped: "2.25", decision: false, flags: {bucket: "2.25", total: 2}, parts: [{rate: 1, weight: -0.01}, {rate: 100, weight: 1000}], priority: true, scores: {quota: 3}, share: "2025-03-20"}, {adjusted: "2.25", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 1.5}, parts: [{label: "3.5", rate: 123456789.123, weight: 3}, {label: "A1", rate: 0.25, weight: -1}], price: 100, scores: {quota: 1.5}, share: "2025-03-20"}, {adjusted: "2.25", capped: "2.25", decision: false, flags: {bucket: "2.25", total: 1.5}, parts: [{label: "", rate: 1000, weight: 0.000001}, {rate: 100, weight: 3}], price: 0.5, scores: {quota: 1.5}, share: "2025-03-20"}], health: false, openedAt: "2025-03-20", risk: false, score: 1.5, urgent: false, weight: 3, years: 1.5}, meta: {flag: [{adjusted: "2.25", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 1.5}, parts: [{label: null, rate: 10, weight: 10}], price: null, priority: false, scores: {quota: 1.5}, share: "2025-03-20"}, {adjusted: "2.25", capped: "2.25", decision: false, flags: {bucket: "2.25", total: 2}, parts: [{rate: 1, weight: -0.01}, {rate: 100, weight: 1000}], priority: true, scores: {quota: 3}, share: "2025-03-20"}, {adjusted: "2.25", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 1.5}, parts: [{label: "3.5", rate: 123456789.123, weight: 3}, {label: "A1", rate: 0.25, weight: -1}], price: 100, scores: {quota: 1.5}, share: "2025-03-20"}, {adjusted: "2.25", capped: "2.25", decision: false, flags: {bucket: "2.25", total: 1.5}, parts: [{label: "", rate: 1000, weight: 0.000001}, {rate: 100, weight: 3}], price: 0.5, scores: {quota: 1.5}, share: "2025-03-20"}]}}], + [{applicant: {score: 3, years: 100, weight: 71, openedAt: "2025-03-20", urgent: true, companies: [{price: 1.5, priority: false, parts: []}, {price: 3, priority: false, parts: [{weight: -500, label: "Zed", rate: 154}, {weight: 3, label: "日本", rate: 5}]}, {price: 250, priority: false, parts: [{weight: 1.5, label: "a", rate: 100}, {weight: 5, label: "Oslo", rate: 100}]}, {price: 1000, priority: false, parts: [{weight: 18, label: "ok", rate: 0.5}]}], extraField: "x"}}, {applicant: {band: 71, calc: {summary: "2025-03-20"}, companies: [{adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 3}, parts: [], price: 1.5, priority: false, scores: {quota: 3}, share: "2025-03-20"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 3}, parts: [{label: "Zed", rate: 154, weight: -500}, {label: "日本", rate: 5, weight: 3}], price: 3, priority: false, scores: {quota: 3}, share: "2025-03-20"}, {adjusted: "10000", capped: "10000", decision: false, flags: {bucket: "10000", total: 3}, parts: [{label: "a", rate: 100, weight: 1.5}, {label: "Oslo", rate: 100, weight: 5}], price: 250, priority: false, scores: {quota: 3}, share: "2025-03-20"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 3}, parts: [{label: "ok", rate: 0.5, weight: 18}], price: 1000, priority: false, scores: {quota: 3}, share: "2025-03-20"}], extraField: "x", health: true, openedAt: "2025-03-20", risk: null, score: 3, urgent: true, weight: 71, years: 100}, meta: {flag: [{adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 3}, parts: [], price: 1.5, priority: false, scores: {quota: 3}, share: "2025-03-20"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 3}, parts: [{label: "Zed", rate: 154, weight: -500}, {label: "日本", rate: 5, weight: 3}], price: 3, priority: false, scores: {quota: 3}, share: "2025-03-20"}, {adjusted: "10000", capped: "10000", decision: false, flags: {bucket: "10000", total: 3}, parts: [{label: "a", rate: 100, weight: 1.5}, {label: "Oslo", rate: 100, weight: 5}], price: 250, priority: false, scores: {quota: 3}, share: "2025-03-20"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 3}, parts: [{label: "ok", rate: 0.5, weight: 18}], price: 1000, priority: false, scores: {quota: 3}, share: "2025-03-20"}]}}], + [{applicant: {score: null, years: 3, weight: 1.5, openedAt: "2025-03-20T10:15:30Z", urgent: false, companies: [{price: 1.5, priority: true, parts: []}, {price: 7.25, priority: false, parts: []}, {price: 0.1, priority: true, parts: [{weight: 3, label: "DE", rate: 0}, {weight: 1000, label: "Zed", rate: 5}, {weight: 1e3, label: "Zed", rate: 0.1}]}, {price: 100, priority: false, parts: [{weight: 18, label: "Oslo", rate: 0.1}, {weight: 100, label: "NL", rate: 250}]}]}}, "!error: MissingRequiredInputs"], + [{applicant: {score: -0.01, years: 100, weight: 1000, openedAt: "1990-06-15", urgent: false, companies: [{parts: [{weight: 100, rate: 100}, {weight: 18, label: "A1", rate: 2.50}]}, {parts: [{weight: 100, rate: 3}, {weight: 250, rate: 99999999999999999999}]}]}}, {applicant: {band: 1000, calc: {summary: "1990-06-15"}, companies: [{adjusted: "false", capped: "10000", decision: false, flags: {bucket: "10000", total: -0.01}, parts: [{rate: 100, weight: 100}, {label: "A1", rate: 2.50, weight: 18}], scores: {quota: 100}, share: "1990-06-15"}, {adjusted: "false", capped: "10000", decision: true, flags: {bucket: "10000", total: -0.01}, parts: [{rate: 3, weight: 100}, {rate: 99999999999999999999, weight: 250}], scores: {quota: 100}, share: "1990-06-15"}], health: false, openedAt: "1990-06-15", risk: false, score: -0.01, urgent: false, weight: 1000, years: 100}, meta: {flag: [{adjusted: "false", capped: "10000", decision: false, flags: {bucket: "10000", total: -0.01}, parts: [{rate: 100, weight: 100}, {label: "A1", rate: 2.50, weight: 18}], scores: {quota: 100}, share: "1990-06-15"}, {adjusted: "false", capped: "10000", decision: true, flags: {bucket: "10000", total: -0.01}, parts: [{rate: 3, weight: 100}, {rate: 99999999999999999999, weight: 250}], scores: {quota: 100}, share: "1990-06-15"}]}}], + [{applicant: {score: 1.5, years: 100, weight: -0.01, openedAt: "2030-12-31", urgent: "true", companies: []}}, "!error: InputValidationFailed"], + [{applicant: {score: 0.1, years: 1.5, weight: 100, openedAt: "1990-06-15", urgent: false, companies: []}}, {applicant: {band: 100, calc: {summary: "1990-06-15"}, companies: [], health: false, openedAt: "1990-06-15", risk: null, score: 0.1, urgent: false, weight: 100, years: 1.5}, meta: {flag: []}}], + [{applicant: {score: 65, years: 99.99, weight: 1.5, openedAt: "2030-12-31", urgent: false, companies: [{price: 3, priority: false, parts: [{weight: 250, label: "DE", rate: 1}, {weight: 1.5, label: "Oslo", rate: 10}, {weight: 7.25, label: "VIP", rate: 0.5}]}]}}, {applicant: {band: 1.5, calc: {summary: "2030-12-31"}, companies: [{adjusted: "9998.0001", capped: "9998.0001", decision: true, flags: {bucket: "9998.0001", total: 65}, parts: [{label: "DE", rate: 1, weight: 250}, {label: "Oslo", rate: 10, weight: 1.5}, {label: "VIP", rate: 0.5, weight: 7.25}], price: 3, priority: false, scores: {quota: 65}, share: "2030-12-31"}], health: false, openedAt: "2030-12-31", risk: null, score: 65, urgent: false, weight: 1.5, years: 99.99}, meta: {flag: [{adjusted: "9998.0001", capped: "9998.0001", decision: true, flags: {bucket: "9998.0001", total: 65}, parts: [{label: "DE", rate: 1, weight: 250}, {label: "Oslo", rate: 10, weight: 1.5}, {label: "VIP", rate: 0.5, weight: 7.25}], price: 3, priority: false, scores: {quota: 65}, share: "2030-12-31"}]}}], + [{applicant: {score: 185, years: 1000, weight: null, openedAt: "2000-01-01", urgent: false, companies: [{parts: [{weight: 100, rate: 1}, {weight: 250, label: "Oslo", rate: 100}]}]}}, {applicant: {band: null, calc: {summary: "2000-01-01"}, companies: [{adjusted: "false", capped: "1000000", decision: false, flags: {bucket: "1000000", total: 1000}, parts: [{rate: 1, weight: 100}, {label: "Oslo", rate: 100, weight: 250}], scores: {quota: 100}, share: "2000-01-01"}], health: false, openedAt: "2000-01-01", risk: null, score: 185, urgent: false, weight: null, years: 1000}, meta: {flag: [{adjusted: "false", capped: "1000000", decision: false, flags: {bucket: "1000000", total: 1000}, parts: [{rate: 1, weight: 100}, {label: "Oslo", rate: 100, weight: 250}], scores: {quota: 100}, share: "2000-01-01"}]}}], + [{applicant: {score: 250, years: 3, weight: -0, openedAt: "2024-02-29", urgent: true, companies: [{price: 1.5, priority: true, parts: []}, {price: 0.5, priority: true, parts: [{weight: 3, label: "Oslo", rate: 18}, {weight: 3, label: "abc", rate: 2}, {weight: 10, label: "ok", rate: 1000}]}, {price: 100, priority: false, parts: [{weight: 3, label: "é ü", rate: 100}, {weight: 3, label: "DE", rate: 2.50}]}]}}, {applicant: {band: 0, calc: {summary: "2024-02-29"}, companies: [{adjusted: "9", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [], price: 1.5, priority: true, scores: {quota: 100}, share: "2024-02-29"}, {adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 3}, parts: [{label: "Oslo", rate: 18, weight: 3}, {label: "abc", rate: 2, weight: 3}, {label: "ok", rate: 1000, weight: 10}], price: 0.5, priority: true, scores: {quota: 100}, share: "2024-02-29"}, {adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 250}, parts: [{label: "é ü", rate: 100, weight: 3}, {label: "DE", rate: 2.50, weight: 3}], price: 100, priority: false, scores: {quota: 250}, share: "2024-02-29"}], health: true, openedAt: "2024-02-29", risk: null, score: 250, urgent: true, weight: 0, years: 3}, meta: {flag: [{adjusted: "9", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [], price: 1.5, priority: true, scores: {quota: 100}, share: "2024-02-29"}, {adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 3}, parts: [{label: "Oslo", rate: 18, weight: 3}, {label: "abc", rate: 2, weight: 3}, {label: "ok", rate: 1000, weight: 10}], price: 0.5, priority: true, scores: {quota: 100}, share: "2024-02-29"}, {adjusted: "9", capped: "9", decision: false, flags: {bucket: "9", total: 250}, parts: [{label: "é ü", rate: 100, weight: 3}, {label: "DE", rate: 2.50, weight: 3}], price: 100, priority: false, scores: {quota: 250}, share: "2024-02-29"}]}}], + [{applicant: {score: 3, years: 1000, weight: null, openedAt: "2025-03-20T10:15:30Z", urgent: true, companies: [{price: 99.99, parts: [{weight: 18, label: "DE", rate: 1.5}]}, {price: 1.5, priority: null, parts: [{weight: 7.25, label: null, rate: 2}]}]}}, {applicant: {band: null, calc: {summary: "2025-03-20T10:15:30Z"}, companies: [{adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 1000}, parts: [{label: "DE", rate: 1.5, weight: 18}], price: 99.99, scores: {quota: 100}, share: "2025-03-20T10:15:30Z"}, {adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 1000}, parts: [{label: null, rate: 2, weight: 7.25}], price: 1.5, priority: null, scores: {quota: 100}, share: "2025-03-20T10:15:30Z"}], health: true, openedAt: "2025-03-20T10:15:30Z", risk: null, score: 3, urgent: true, weight: null, years: 1000}, meta: {flag: [{adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 1000}, parts: [{label: "DE", rate: 1.5, weight: 18}], price: 99.99, scores: {quota: 100}, share: "2025-03-20T10:15:30Z"}, {adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 1000}, parts: [{label: null, rate: 2, weight: 7.25}], price: 1.5, priority: null, scores: {quota: 100}, share: "2025-03-20T10:15:30Z"}]}}], + [{applicant: {score: 7.25, years: 100, weight: 250, openedAt: "2024-01-01", urgent: false, companies: [{price: 0.25, priority: false, parts: [{weight: 3, label: "VIP", rate: 1000}]}, {price: 0.1, priority: true, parts: [{weight: 3, label: " pad ", rate: 1000000}, {weight: 0.25, label: "Oslo", rate: 250}, {weight: 1000, label: "retail", rate: 3}]}, {price: 0.25, priority: false, parts: [{weight: 3, label: "日本", rate: 1000000}, {weight: 0.25, label: "VIP", rate: 250}]}, {price: 1.5, priority: false, parts: [{weight: 99999999999999999999, label: "é ü", rate: 250}, {weight: 1.5, label: "gold", rate: 1}, {weight: 18, label: "Oslo", rate: 10}]}]}}, {applicant: {band: 250, calc: {summary: "2024-01-01"}, companies: [{adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 7.25}, parts: [{label: "VIP", rate: 1000, weight: 3}], price: 0.25, priority: false, scores: {quota: 7.25}, share: "2024-01-01"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 3}, parts: [{label: " pad ", rate: 1000000, weight: 3}, {label: "Oslo", rate: 250, weight: 0.25}, {label: "retail", rate: 3, weight: 1000}], price: 0.1, priority: true, scores: {quota: 250}, share: "2024-01-01"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 7.25}, parts: [{label: "日本", rate: 1000000, weight: 3}, {label: "VIP", rate: 250, weight: 0.25}], price: 0.25, priority: false, scores: {quota: 7.25}, share: "2024-01-01"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 7.25}, parts: [{label: "é ü", rate: 250, weight: 99999999999999999999}, {label: "gold", rate: 1, weight: 1.5}, {label: "Oslo", rate: 10, weight: 18}], price: 1.5, priority: false, scores: {quota: 7.25}, share: "2024-01-01"}], health: false, openedAt: "2024-01-01", risk: null, score: 7.25, urgent: false, weight: 250, years: 100}, meta: {flag: [{adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 7.25}, parts: [{label: "VIP", rate: 1000, weight: 3}], price: 0.25, priority: false, scores: {quota: 7.25}, share: "2024-01-01"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 3}, parts: [{label: " pad ", rate: 1000000, weight: 3}, {label: "Oslo", rate: 250, weight: 0.25}, {label: "retail", rate: 3, weight: 1000}], price: 0.1, priority: true, scores: {quota: 250}, share: "2024-01-01"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 7.25}, parts: [{label: "日本", rate: 1000000, weight: 3}, {label: "VIP", rate: 250, weight: 0.25}], price: 0.25, priority: false, scores: {quota: 7.25}, share: "2024-01-01"}, {adjusted: "10000", capped: "10000", decision: true, flags: {bucket: "10000", total: 7.25}, parts: [{label: "é ü", rate: 250, weight: 99999999999999999999}, {label: "gold", rate: 1, weight: 1.5}, {label: "Oslo", rate: 10, weight: 18}], price: 1.5, priority: false, scores: {quota: 7.25}, share: "2024-01-01"}]}}], + [{applicant: {score: 0.1, years: 1.5, weight: 250, openedAt: "2000-01-01", urgent: false, companies: [{price: 0.1, priority: true, parts: []}, {price: 18, priority: true, parts: [{weight: 100, label: "Oslo", rate: 250}, {weight: 1000, label: "DE", rate: 100}, {weight: 1, label: "gold", rate: 3}]}, {price: 1000, priority: false, parts: [{weight: 0.25, label: "O'Neil", rate: 1.5}, {weight: 99999999999999999999, label: "3.5", rate: 99999999999999999999}]}, {price: 18, priority: true, parts: []}, {price: 10, priority: false, parts: [{weight: 3, label: "US", rate: 1000}, {weight: 3, label: "Oslo", rate: -0.01}]}, {price: 10, priority: false, parts: [{weight: 18, label: "Oslo", rate: 1}]}, {price: 1.5, priority: false, parts: [{weight: -500, label: "", rate: -1}, {weight: 1, label: "A1", rate: 3}]}, {price: 2.50, priority: false, parts: [{weight: 172, label: "DE", rate: 250}]}, {price: -1, priority: false, parts: []}]}}, {applicant: {band: 250, calc: {summary: "2000-01-01"}, companies: [{adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0}, parts: [], price: 0.1, priority: true, scores: {quota: 250}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: false, flags: {bucket: "2.25", total: 3}, parts: [{label: "Oslo", rate: 250, weight: 100}, {label: "DE", rate: 100, weight: 1000}, {label: "gold", rate: 3, weight: 1}], price: 18, priority: true, scores: {quota: 250}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "O'Neil", rate: 1.5, weight: 0.25}, {label: "3.5", rate: 99999999999999999999, weight: 99999999999999999999}], price: 1000, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0}, parts: [], price: 18, priority: true, scores: {quota: 250}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "US", rate: 1000, weight: 3}, {label: "Oslo", rate: -0.01, weight: 3}], price: 10, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "Oslo", rate: 1, weight: 18}], price: 10, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "", rate: -1, weight: -500}, {label: "A1", rate: 3, weight: 1}], price: 1.5, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "DE", rate: 250, weight: 172}], price: 2.50, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [], price: -1, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}], health: false, openedAt: "2000-01-01", risk: null, score: 0.1, urgent: false, weight: 250, years: 1.5}, meta: {flag: [{adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0}, parts: [], price: 0.1, priority: true, scores: {quota: 250}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: false, flags: {bucket: "2.25", total: 3}, parts: [{label: "Oslo", rate: 250, weight: 100}, {label: "DE", rate: 100, weight: 1000}, {label: "gold", rate: 3, weight: 1}], price: 18, priority: true, scores: {quota: 250}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "O'Neil", rate: 1.5, weight: 0.25}, {label: "3.5", rate: 99999999999999999999, weight: 99999999999999999999}], price: 1000, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0}, parts: [], price: 18, priority: true, scores: {quota: 250}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "US", rate: 1000, weight: 3}, {label: "Oslo", rate: -0.01, weight: 3}], price: 10, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "Oslo", rate: 1, weight: 18}], price: 10, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "", rate: -1, weight: -500}, {label: "A1", rate: 3, weight: 1}], price: 1.5, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [{label: "DE", rate: 250, weight: 172}], price: 2.50, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}, {adjusted: "false", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 0.1}, parts: [], price: -1, priority: false, scores: {quota: 0.1}, share: "2000-01-01"}]}}], + [{applicant: {score: 100, years: 0.25, weight: 99.99, openedAt: "2025-03-20T10:15:30Z", urgent: true, companies: [{price: 10, priority: "true", parts: [{weight: 100, label: "gold", rate: 100}, {weight: 0.25, label: "retail", rate: 370}]}]}}, "!error: InputValidationFailed"], + [{applicant: {score: -0.5, years: 3, weight: null, openedAt: "2000-01-01", urgent: false, companies: [{price: 3, priority: false, parts: [{weight: 3, label: null, rate: 100}]}, {price: 1000, parts: []}, {priority: false, parts: [{weight: 1000, rate: 100}, {weight: 3, label: "", rate: 0.5}]}, {priority: null, parts: [{weight: 1000, rate: 10}, {weight: 99999999999999999999, label: "3.5", rate: 100}, {weight: 100, label: "a-b-c", rate: -500}]}, {parts: [{weight: 100, label: "O'Neil", rate: 1.5}, {weight: 1.5, label: "ok", rate: 3}]}, {price: -500, priority: true, parts: []}, {price: 0.25, priority: false, parts: [{weight: 10, label: "abc", rate: 10}, {weight: 1, label: null, rate: 0.25}]}, {price: 100, priority: true, parts: [{weight: 0.1, label: "a", rate: 100}, {weight: 10, label: null, rate: -500}, {weight: 10, rate: 3}]}, {price: 10, priority: null, parts: [{weight: 100, label: null, rate: 250}, {weight: 10, label: "gold", rate: 3}]}, {priority: false, parts: [{weight: 1, label: "a", rate: 250}]}, {price: 100, parts: [{weight: 0, label: null, rate: 1}, {weight: -0.5, rate: 10}]}]}}, {applicant: {band: null, calc: {summary: "2000-01-01"}, companies: [{adjusted: "false", capped: "9", decision: false, flags: {bucket: "9", total: -0.5}, parts: [{label: null, rate: 100, weight: 3}], price: 3, priority: false, scores: {quota: -0.5}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [], price: 1000, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: false, flags: {bucket: "9", total: -0.5}, parts: [{rate: 100, weight: 1000}, {label: "", rate: 0.5, weight: 3}], priority: false, scores: {quota: -0.5}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: false, flags: {bucket: "9", total: 3}, parts: [{rate: 10, weight: 1000}, {label: "3.5", rate: 100, weight: 99999999999999999999}, {label: "a-b-c", rate: -500, weight: 100}], priority: null, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [{label: "O'Neil", rate: 1.5, weight: 100}, {label: "ok", rate: 3, weight: 1.5}], scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [], price: -500, priority: true, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: -0.5}, parts: [{label: "abc", rate: 10, weight: 10}, {label: null, rate: 0.25, weight: 1}], price: 0.25, priority: false, scores: {quota: -0.5}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: false, flags: {bucket: "9", total: 3}, parts: [{label: "a", rate: 100, weight: 0.1}, {label: null, rate: -500, weight: 10}, {rate: 3, weight: 10}], price: 100, priority: true, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [{label: null, rate: 250, weight: 100}, {label: "gold", rate: 3, weight: 10}], price: 10, priority: null, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: -0.5}, parts: [{label: "a", rate: 250, weight: 1}], priority: false, scores: {quota: -0.5}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [{label: null, rate: 1, weight: 0}, {rate: 10, weight: -0.5}], price: 100, scores: {quota: 100}, share: "2000-01-01"}], health: false, openedAt: "2000-01-01", risk: null, score: -0.5, urgent: false, weight: null, years: 3}, meta: {flag: [{adjusted: "false", capped: "9", decision: false, flags: {bucket: "9", total: -0.5}, parts: [{label: null, rate: 100, weight: 3}], price: 3, priority: false, scores: {quota: -0.5}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [], price: 1000, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: false, flags: {bucket: "9", total: -0.5}, parts: [{rate: 100, weight: 1000}, {label: "", rate: 0.5, weight: 3}], priority: false, scores: {quota: -0.5}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: false, flags: {bucket: "9", total: 3}, parts: [{rate: 10, weight: 1000}, {label: "3.5", rate: 100, weight: 99999999999999999999}, {label: "a-b-c", rate: -500, weight: 100}], priority: null, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [{label: "O'Neil", rate: 1.5, weight: 100}, {label: "ok", rate: 3, weight: 1.5}], scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [], price: -500, priority: true, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: -0.5}, parts: [{label: "abc", rate: 10, weight: 10}, {label: null, rate: 0.25, weight: 1}], price: 0.25, priority: false, scores: {quota: -0.5}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: false, flags: {bucket: "9", total: 3}, parts: [{label: "a", rate: 100, weight: 0.1}, {label: null, rate: -500, weight: 10}, {rate: 3, weight: 10}], price: 100, priority: true, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [{label: null, rate: 250, weight: 100}, {label: "gold", rate: 3, weight: 10}], price: 10, priority: null, scores: {quota: 100}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: -0.5}, parts: [{label: "a", rate: 250, weight: 1}], priority: false, scores: {quota: -0.5}, share: "2000-01-01"}, {adjusted: "false", capped: "9", decision: true, flags: {bucket: "9", total: 3}, parts: [{label: null, rate: 1, weight: 0}, {rate: 10, weight: -0.5}], price: 100, scores: {quota: 100}, share: "2000-01-01"}]}}], + [{applicant: {score: 123456789.123, years: 99999999999999999999, weight: 0.5, openedAt: "2000-01-01", urgent: true, companies: [{price: 100, priority: false, parts: [{weight: 7.25, label: "A1", rate: 5}, {weight: 250, rate: 1}]}, {price: 10, priority: null, parts: [{weight: 1e3, label: "Oslo", rate: 2}, {weight: 3, label: "retail", rate: 100}, {weight: 1, label: "gold", rate: 100}]}]}}, {applicant: {band: 0.5, calc: {summary: "2000-01-01"}, companies: [{adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 123456789.123}, parts: [{label: "A1", rate: 5, weight: 7.25}, {rate: 1, weight: 250}], price: 100, priority: false, scores: {quota: 123456789.123}, share: "2000-01-01"}, {adjusted: "1000000", capped: "1000000", decision: false, flags: {bucket: "1000000", total: 99999999999999999999}, parts: [{label: "Oslo", rate: 2, weight: 1000}, {label: "retail", rate: 100, weight: 3}, {label: "gold", rate: 100, weight: 1}], price: 10, priority: null, scores: {quota: 100}, share: "2000-01-01"}], health: true, openedAt: "2000-01-01", risk: null, score: 123456789.123, urgent: true, weight: 0.5, years: 99999999999999999999}, meta: {flag: [{adjusted: "1000000", capped: "1000000", decision: true, flags: {bucket: "1000000", total: 123456789.123}, parts: [{label: "A1", rate: 5, weight: 7.25}, {rate: 1, weight: 250}], price: 100, priority: false, scores: {quota: 123456789.123}, share: "2000-01-01"}, {adjusted: "1000000", capped: "1000000", decision: false, flags: {bucket: "1000000", total: 99999999999999999999}, parts: [{label: "Oslo", rate: 2, weight: 1000}, {label: "retail", rate: 100, weight: 3}, {label: "gold", rate: 100, weight: 1}], price: 10, priority: null, scores: {quota: 100}, share: "2000-01-01"}]}}], + [{applicant: {score: 100, years: 1.5, weight: 1.5, openedAt: "2025-03-20", urgent: false, companies: [{price: 2, priority: false, parts: []}, {price: 5, priority: false, parts: []}]}}, {applicant: {band: 1.5, calc: {summary: "2025-03-20"}, companies: [{adjusted: "2.25", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 100}, parts: [], price: 2, priority: false, scores: {quota: 100}, share: "2025-03-20"}, {adjusted: "2.25", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 100}, parts: [], price: 5, priority: false, scores: {quota: 100}, share: "2025-03-20"}], health: false, openedAt: "2025-03-20", risk: null, score: 100, urgent: false, weight: 1.5, years: 1.5}, meta: {flag: [{adjusted: "2.25", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 100}, parts: [], price: 2, priority: false, scores: {quota: 100}, share: "2025-03-20"}, {adjusted: "2.25", capped: "2.25", decision: true, flags: {bucket: "2.25", total: 100}, parts: [], price: 5, priority: false, scores: {quota: 100}, share: "2025-03-20"}]}}], + ], +} + +// seed 345000 (attempt 0) +{ + name: "b 51: account/vehicles/drivers: 1 assertion, 3 expression, 1 match, 4 table; 4 root, 9 per-member, 0 top-level computed", + policy: { + models: {account: {balance: "number", openedAt: "date", tier: "string(gold|silver|bronze)?", vehicles: "vehicle[]?"}, vehicle: {price: "number", region: "string", country: "string?", drivers: "driver[]"}, driver: {days: "number", openedAt: "date"}}, + blocks: [ + {match: "vehicle.meta.bucket", arms: [["(0.25 > 2 and vehicle.price == 2)", "(isNumeric(vehicle.region) ? `${(vehicle.country ?? '')}/${0 > 10}` : (vehicle.region + '-' + (vehicle.country ?? '')))"], ["account.balance in [40..66]", "'Oslo'"], ["contains(['Oslo', 'retail', ''], vehicle.region)", "account.openedAt.format('%Y-%m')"], ["not (account.balance > 100)", "'DE'"], ["", "vehicle.region"]]}, + {table: "t2", inputs: ["trunc(vehicle.price)", "(account.tier ?? '')", "vehicle.meta.bucket"], outputs: ["vehicle.review"], rules: [ + ["[250..306]", "'silver'", "$ != 'A1'", "vehicle.price"], + ["1, 0.25", "", "startsWith($, 'a')", "(account.balance * 3)"], + ["!= 3", "'bronze', 'silver'", "", "account.balance"], + [">= 100", "", "$ != 'A1'", "100"], + ["", "'bronze'", "'none'", "count(vehicle.drivers, #.days >= #.days)"], + ["", "", "", "(account.balance - account.balance)"], + ]}, + {expression: "vehicle.margin", value: "(vehicle.review ?? 0) == vehicle.price"}, + {assertion: "vehicle.capped", conditions: ["account.openedAt.isSameOrBefore(d('2025-01-01'), 'month')", ["or", "contains(`${vehicle.meta.bucket}/${50}`, 'gold')", 0], ["or", "(vehicle.margin or vehicle.margin)", 0], "contains((vehicle.country ?? ''), 'DE')"]}, + {expression: "vehicle.weighted", value: "map((account.vehicles ?? []), ((#.review ?? 0) * 1.5))"}, + {expression: "account.eligible", value: "((min([abs(account.balance), 1000]) ^ 0) >= 100 ? (min([abs(trunc(account.balance)), 1000]) ^ 2) : account.balance)"}, + {table: "t7", inputs: ["(avg(map(vehicle.drivers, #.days)) ?? 0)", "vehicle.country"], outputs: ["vehicle.total"], rules: [ + ["< 1", "'x'", "account.balance"], + ["> 0", "'retail'", ""], + ["> 1.5", "", "account.balance"], + ["< 2", "'none'", "(min(vehicle.weighted) ?? 0)"], + ["!= 0.25", "'retail'", "(vehicle.review ?? 0)"], + ["", "'A1'", "1"], + ["> 0", "'a'", "1000"], + ]}, + {table: "t8", inputs: ["vehicle.region", "(vehicle.review ?? 0)", "vehicle.country"], outputs: ["vehicle.fee", "vehicle.segment", "vehicle.health"], rules: [ + ["'a', 'high'", "", "", "vehicle.margin", "", "vehicle.meta.bucket"], + ["startsWith($, 'A1')", "", "'low'", "vehicle.capped", "", "vehicle.region"], + ["'Oslo', 'none'", "", "'DE'", "vehicle.margin", "len(filter(vehicle.drivers, not (#.days <= 100)))", "vehicle.meta.bucket"], + ["startsWith($, 'A1')", "<= 1000", "'US'", "vehicle.margin", "vehicle.price", "vehicle.region"], + ["", "<= 3", "'VIP'", "vehicle.capped", "(vehicle.review ?? 0)", "string(vehicle.capped)"], + ["", "", "", "", "account.eligible", "'none'"], + ]}, + {table: "t9", inputs: [null, "account.balance", "account.tier"], outputs: ["account.flags.quota", "account.flags.penalty", "account.points"], rules: [ + ["account.openedAt.isSameOrBefore(d('2024-01-01'), 'month')", "[0..299]", "'silver'", "'A1'", "'x'", "account.eligible"], + ["(account.balance <= 50 and account.balance == 1)", "!= 1", "'silver'", "'low'", "'ok'", "50"], + ["", "0.25, 250", "'bronze'", "string(account.balance)", "'low'", "1000"], + ["(account.tier ?? '') == 'gold'", "", "'silver'", "", "'a'", "18"], + ["account.eligible == account.balance", "", "'silver'", "`${account.balance}/${account.eligible <= 1}`", "account.openedAt.format('%Y')", "account.balance"], + ["", "", "", "'x'", "'retail'", ""], + ]}, + ], + }, + cases: [ + [{account: {balance: 0.25, openedAt: "2024-01-01", tier: "bronze", vehicles: [{price: 18, region: "high", country: "A1", drivers: [{days: 1, openedAt: "2000-01-01"}]}, {price: 50, region: "x", country: "VIP", drivers: [{days: 10, openedAt: "2025-03-20"}]}], extraField: 1}}, {account: {balance: 0.25, eligible: 0.25, extraField: 1, flags: {penalty: "low", quota: "0.25"}, openedAt: "2024-01-01", points: 1000, tier: "bronze", vehicles: [{capped: false, country: "A1", drivers: [{days: 1, openedAt: "2000-01-01"}], fee: false, health: "DE", margin: false, meta: {bucket: "DE"}, price: 18, region: "high", review: 0.25, segment: 0.25, total: 1}, {capped: false, country: "VIP", drivers: [{days: 10, openedAt: "2025-03-20"}], fee: false, health: "false", margin: false, meta: {bucket: "DE"}, price: 50, region: "x", review: 0.25, segment: 0.25, total: 0.25}]}}], + [{account: {balance: 100, openedAt: "1990-06-15", tier: "gold", vehicles: [{price: 100, region: "none", country: "gold", drivers: [{days: 5, openedAt: "2024-02-29"}, {days: 50, openedAt: "2025-03-20"}]}, {price: 1, region: "retail", country: "x", drivers: [{days: -0.01, openedAt: "2025-03-20"}, {days: 0.25, openedAt: "2024-01-01"}]}]}}, {account: {balance: 100, eligible: 100, flags: {penalty: "retail", quota: "x"}, openedAt: "1990-06-15", points: null, tier: "gold", vehicles: [{country: "gold", drivers: [{days: 5, openedAt: "2024-02-29"}, {days: 50, openedAt: "2025-03-20"}], fee: null, health: "none", meta: {bucket: "DE"}, price: 100, region: "none", review: 100, segment: 100, total: 100}, {country: "x", drivers: [{days: -0.01, openedAt: "2025-03-20"}, {days: 0.25, openedAt: "2024-01-01"}], fee: null, health: "none", meta: {bucket: "1990-06"}, price: 1, region: "retail", review: 0, segment: 100, total: 100}]}}], + [{account: {balance: 18, openedAt: "2030-12-31", tier: false, vehicles: []}}, "!error: InputValidationFailed"], + [{account: {balance: 10, openedAt: "2030-12-31", tier: "bronze", vehicles: []}}, {account: {balance: 10, eligible: 10, flags: {penalty: "retail", quota: "x"}, openedAt: "2030-12-31", points: null, tier: "bronze", vehicles: []}}], + [{account: {balance: 0, openedAt: "2024-02-29", vehicles: [{price: 10, region: "high", drivers: [{days: 7.25, openedAt: "2024-02-29"}]}, {price: 1000000, region: "A1", country: null, drivers: [{days: 0.5, openedAt: "2025-03-20T10:15:30Z"}, {days: 100, openedAt: "2025-03-20"}]}, {price: 18, region: "US", country: "none", drivers: [{days: 99999999999999999999, openedAt: "2024-01-01"}, {days: 0, openedAt: "2025-03-20T10:15:30Z"}]}]}}, {account: {balance: 0, eligible: 0, flags: {penalty: "retail", quota: "x"}, openedAt: "2024-02-29", points: null, vehicles: [{drivers: [{days: 7.25, openedAt: "2024-02-29"}], fee: false, health: "DE", margin: false, meta: {bucket: "DE"}, price: 10, region: "high", review: 0, segment: 0, total: 0}, {country: null, drivers: [{days: 0.5, openedAt: "2025-03-20T10:15:30Z"}, {days: 100, openedAt: "2025-03-20"}], fee: null, health: "none", margin: false, meta: {bucket: "DE"}, price: 1000000, region: "A1", review: 100, segment: 0, total: 0}, {country: "none", drivers: [{days: 99999999999999999999, openedAt: "2024-01-01"}, {days: 0, openedAt: "2025-03-20T10:15:30Z"}], fee: null, health: "none", margin: false, meta: {bucket: "DE"}, price: 18, region: "US", review: 0, segment: 0, total: 0}]}}], + [{account: {balance: 2, openedAt: "2025-03-20T10:15:30Z", tier: "silver", vehicles: [], extraField: {nested: true}}}, {account: {balance: 2, eligible: 2, extraField: {nested: true}, flags: {penalty: "2025", quota: "2/false"}, openedAt: "2025-03-20T10:15:30Z", points: 2, tier: "silver", vehicles: []}}], + [{account: {balance: 250, openedAt: "1990-06-15", tier: "gold", vehicles: [{price: 1, region: "retail", country: "A1", drivers: []}], extraField: "x"}}, "!error: ExpressionFailed"], + [{account: {balance: 18, openedAt: "2025-03-20", tier: "gold", vehicles: []}}, {account: {balance: 18, eligible: 18, flags: {penalty: "retail", quota: "x"}, openedAt: "2025-03-20", points: null, tier: "gold", vehicles: []}}], + [{account: {balance: 0.000001, openedAt: "2025-03-20", tier: "gold"}}, {account: {balance: 0.000001, eligible: 0.000001, flags: {penalty: "retail", quota: "x"}, openedAt: "2025-03-20", points: null, tier: "gold"}}], + [{account: {balance: 100, openedAt: "2024-02-29", vehicles: [{price: 0.5, region: "US", country: null, drivers: [{days: -1, openedAt: "2024-01-01"}, {days: 99999999999999999999, openedAt: "2024-02-29"}]}, {price: -0, region: "retail", country: "x", drivers: [{days: -0, openedAt: "2025-03-20"}, {days: 10, openedAt: "2025-03-20"}]}]}}, {account: {balance: 100, eligible: 100, flags: {penalty: "retail", quota: "x"}, openedAt: "2024-02-29", points: null, vehicles: [{country: null, drivers: [{days: -1, openedAt: "2024-01-01"}, {days: 99999999999999999999, openedAt: "2024-02-29"}], fee: null, health: "none", meta: {bucket: "DE"}, price: 0.5, region: "US", review: 0, segment: 100, total: 100}, {country: "x", drivers: [{days: 0, openedAt: "2025-03-20"}, {days: 10, openedAt: "2025-03-20"}], fee: null, health: "none", meta: {bucket: "2024-02"}, price: 0, region: "retail", review: 0, segment: 100, total: 100}]}}], + [{account: {balance: -0, openedAt: "2025-03-20", tier: "silver", vehicles: [{price: 250, region: "VIP", country: "a", drivers: [{days: 3, openedAt: "1990-06-15"}, {days: 2, openedAt: "2025-03-20"}]}, {price: 0.25, region: "high", country: "none", drivers: [{days: 250, openedAt: "1990-06-15"}, {days: 18, openedAt: "2024-02-29"}, {days: 3, openedAt: "2025-03-20T10:15:30Z"}]}]}}, {account: {balance: 0, eligible: 0, flags: {penalty: "2025", quota: "0/true"}, openedAt: "2025-03-20", points: 0, tier: "silver", vehicles: [{country: "a", drivers: [{days: 3, openedAt: "1990-06-15"}, {days: 2, openedAt: "2025-03-20"}], fee: null, health: "none", margin: true, meta: {bucket: "DE"}, price: 250, region: "VIP", review: 250, segment: 0, total: 0}, {country: "none", drivers: [{days: 250, openedAt: "1990-06-15"}, {days: 18, openedAt: "2024-02-29"}, {days: 3, openedAt: "2025-03-20T10:15:30Z"}], fee: false, health: "DE", margin: false, meta: {bucket: "DE"}, price: 0.25, region: "high", review: 0, segment: 0, total: 0}]}}], + [{account: {balance: 445, openedAt: "2024-01-01", vehicles: [{price: 2, region: "a", country: null, drivers: [{days: 5, openedAt: "2025-03-20"}, {days: 0, openedAt: "2025-03-20T10:15:30Z"}, {days: 100, openedAt: "1990-06-15"}]}, {price: 50, region: "A1", country: null, drivers: []}, {price: 99.99, region: "retail", country: null, drivers: [{days: 2, openedAt: "2000-01-01"}, {days: 10, openedAt: "2025-03-20"}, {days: 3, openedAt: "2025-03-20"}]}, {price: 50, region: "x", country: null, drivers: [{days: 10, openedAt: "2024-02-29"}, {days: 1000, openedAt: "2000-01-01"}, {days: 10, openedAt: "2024-01-01"}]}]}}, "!error: ExpressionFailed"], + [{account: {balance: 10, openedAt: "2000-01-01", tier: "gold", vehicles: [{price: 0.25, region: "VIP", country: null, drivers: []}, {price: 5, region: "low", country: "a", drivers: [{days: 1000000, openedAt: "1990-06-15"}, {days: 10, openedAt: "2000-01-01"}, {days: 10, openedAt: "2030-12-31"}]}, {price: 100, region: "A1", country: null, drivers: [{days: 2, openedAt: "2024-02-29"}, {days: 1000, openedAt: "2000-01-01"}]}, {price: 250, region: "none", country: null, drivers: [{days: 10, openedAt: "1990-06-15"}, {days: 7.25, openedAt: "2024-01-01"}, {days: 100, openedAt: "2000-01-01"}]}, {price: 3, region: "VIP", country: "O'Neil", drivers: [{days: 0.000001, openedAt: "2025-03-20"}, {days: 100, openedAt: "2025-03-20"}, {days: 0.25, openedAt: "2030-12-31"}]}]}}, "!error: ExpressionFailed"], + [{account: {balance: 2, openedAt: "2000-01-01", tier: "gold", vehicles: []}}, {account: {balance: 2, eligible: 2, flags: {penalty: "retail", quota: "x"}, openedAt: "2000-01-01", points: null, tier: "gold", vehicles: []}}], + [{account: {balance: 1e3, openedAt: "2025-03-20"}}, {account: {balance: 1000, eligible: 1000, flags: {penalty: "retail", quota: "x"}, openedAt: "2025-03-20", points: null}}], + [{account: {balance: 1000, openedAt: "2024-01-01", tier: null, vehicles: [{price: 100, region: "none", country: null, drivers: [{days: 2, openedAt: "1990-06-15"}, {days: 250, openedAt: "2030-12-31"}]}]}}, {account: {balance: 1000, eligible: 1000, flags: {penalty: "retail", quota: "x"}, openedAt: "2024-01-01", points: null, tier: null, vehicles: [{country: null, drivers: [{days: 2, openedAt: "1990-06-15"}, {days: 250, openedAt: "2030-12-31"}], fee: null, health: "none", meta: {bucket: "none"}, price: 100, region: "none", review: 100, segment: 1000, total: 1000}]}}], + [{account: {balance: 100, openedAt: "2024-01-01", tier: "silver", vehicles: [{price: 18, region: "none", country: "Oslo", drivers: []}, {price: 0, region: "A1", country: "low", drivers: []}, {price: 2.50, region: "low", country: "high", drivers: [{days: 1000, openedAt: "2024-02-29"}, {days: 2, openedAt: "2024-02-29"}, {days: 100, openedAt: "2024-01-01"}]}, {price: 5, region: "low", country: "retail", drivers: [{days: 65, openedAt: "2000-01-01"}, {days: 250, openedAt: "2024-01-01"}]}, {price: 0.25, region: "high", country: "ok", drivers: [{days: 2, openedAt: "2025-03-20T10:15:30Z"}, {days: 1, openedAt: "2030-12-31"}, {days: 3, openedAt: "2024-01-01"}]}]}}, "!error: ExpressionFailed"], + [{account: {balance: 1, openedAt: "2025-03-20T10:15:30Z", tier: "gold", vehicles: [{price: 3, region: "3.5", country: 5, drivers: [{days: 18, openedAt: "2030-12-31"}]}, {price: 0.5, region: "gold", country: "retail", drivers: []}]}}, "!error: InputValidationFailed"], + [{account: {balance: 1, openedAt: "2024-01-01", tier: "silver", vehicles: [{price: 1.5, region: "none", country: null, drivers: [{days: 123456789.123, openedAt: "2030-12-31"}, {days: 250, openedAt: "2025-03-20T10:15:30Z"}]}, {price: 5, region: "A1", drivers: []}]}}, "!error: ExpressionFailed"], + [{account: {balance: 10, openedAt: "2024-01-01", tier: "gold", vehicles: []}}, {account: {balance: 10, eligible: 10, flags: {penalty: "retail", quota: "x"}, openedAt: "2024-01-01", points: null, tier: "gold", vehicles: []}}], + [{account: {balance: 2, openedAt: "2024-01-01", tier: "gold", vehicles: [{price: 5, region: "3.5", country: "retail", drivers: [{days: 1000, openedAt: "2000-01-01"}, {days: 50, openedAt: "2025-03-20T10:15:30Z"}, {days: 3, openedAt: "2030-12-31"}]}, {price: 0, region: "", country: "", drivers: [{days: 1, openedAt: "1990-06-15"}, {days: 1000, openedAt: "2025-03-20"}]}]}}, {account: {balance: 2, eligible: 2, flags: {penalty: "retail", quota: "x"}, openedAt: "2024-01-01", points: null, tier: "gold", vehicles: [{country: "retail", drivers: [{days: 1000, openedAt: "2000-01-01"}, {days: 50, openedAt: "2025-03-20T10:15:30Z"}, {days: 3, openedAt: "2030-12-31"}], fee: null, health: "none", meta: {bucket: "DE"}, price: 5, region: "3.5", review: 0, segment: 2, total: 2}, {country: "", drivers: [{days: 1, openedAt: "1990-06-15"}, {days: 1000, openedAt: "2025-03-20"}], fee: null, health: "none", meta: {bucket: "2024-01"}, price: 0, region: "", review: 0, segment: 2, total: 2}]}}], + [{account: {balance: 50, openedAt: "2025-03-20T10:15:30Z", tier: "silver", vehicles: [{price: 10, region: "A1", country: "Oslo", drivers: [{days: 0.1, openedAt: "2024-01-01"}, {days: 123456789.123, openedAt: "2025-03-20"}, {days: 0.000001, openedAt: "2024-01-01"}]}, {price: 2, region: "x", country: "a", drivers: [{days: 250, openedAt: "2000-01-01"}, {days: 0, openedAt: "2025-03-20"}]}, {price: 250, region: "A1", country: "US", drivers: [{days: -0.5, openedAt: "2030-12-31"}, {days: 5, openedAt: "1990-06-15"}]}, {price: 250, region: "ok", country: "Zed", drivers: [{days: 0, openedAt: "2025-03-20"}, {days: 405, openedAt: "2030-12-31"}]}, {price: 1, region: "DE", country: "DE", drivers: []}, {price: -500, region: "DE", country: "a", drivers: []}, {price: 123456789.123, region: "US", country: "none", drivers: [{days: 1.5, openedAt: "2025-03-20"}, {days: 1, openedAt: "2024-01-01"}, {days: 1000, openedAt: "2025-03-20T10:15:30Z"}]}, {price: 10, region: "A1", country: "é ü", drivers: [{days: -0, openedAt: "2025-03-20"}, {days: 0.25, openedAt: "2025-03-20T10:15:30Z"}, {days: 50, openedAt: "2000-01-01"}]}, {price: 250, region: "a", country: "ok", drivers: [{days: 1000, openedAt: "2025-03-20T10:15:30Z"}, {days: 1, openedAt: "2030-12-31"}]}, {price: 0.5, region: "none", country: "O'Neil", drivers: [{days: 100, openedAt: "2024-02-29"}, {days: 1000, openedAt: "2030-12-31"}]}, {price: 3, region: "x", country: "retail", drivers: [{days: 18, openedAt: "2025-03-20"}]}, {price: 0.25, region: "a", country: "gold", drivers: [{days: 1e3, openedAt: "2025-03-20"}]}]}}, "!error: ExpressionFailed"], + [{account: {balance: 99.99, openedAt: "1990-06-15", tier: "gold", vehicles: [{price: 2, region: "x-y", country: "retail", drivers: [{days: 7.25, openedAt: "2025-03-20"}]}, {price: 0.1, region: "a", country: "DE", drivers: [{days: 100, openedAt: "2024-01-01"}, {days: 5, openedAt: "2025-03-20"}]}, {price: 1000, region: "a-b-c", country: "none", drivers: [{days: 99.99, openedAt: "2025-03-20T10:15:30Z"}]}, {price: -500, region: "US", country: "US", drivers: [{days: 99999999999999999999, openedAt: "2030-12-31"}, {days: -0.5, openedAt: "1990-06-15"}]}], extraField: "x"}}, {account: {balance: 99.99, eligible: 99.99, extraField: "x", flags: {penalty: "retail", quota: "x"}, openedAt: "1990-06-15", points: null, tier: "gold", vehicles: [{country: "retail", drivers: [{days: 7.25, openedAt: "2025-03-20"}], fee: null, health: "none", margin: false, meta: {bucket: "DE"}, price: 2, region: "x-y", review: 0.00, segment: 99.99, total: 99.99}, {country: "DE", drivers: [{days: 100, openedAt: "2024-01-01"}, {days: 5, openedAt: "2025-03-20"}], fee: false, health: "DE", margin: false, meta: {bucket: "DE"}, price: 0.1, region: "a", review: 0.00, segment: 99.99, total: 99.99}, {country: "none", drivers: [{days: 99.99, openedAt: "2025-03-20T10:15:30Z"}], fee: null, health: "none", margin: false, meta: {bucket: "DE"}, price: 1000, region: "a-b-c", review: 100, segment: 99.99, total: 99.99}, {country: "US", drivers: [{days: 99999999999999999999, openedAt: "2030-12-31"}, {days: -0.5, openedAt: "1990-06-15"}], fee: null, health: "none", margin: false, meta: {bucket: "DE"}, price: -500, region: "US", review: 0.00, segment: 99.99, total: 99.99}]}}], + ], +} + +// seed 345100 (attempt 0) +{ + name: "b 52: borrower/accounts/payments: 2 assertion, 4 expression, 2 match, 4 table; 12 root, 5 per-member, 1 top-level computed", + policy: { + models: {borrower: {score: "number", flagged: "boolean", limit: "number", years: "number?", sku: "string", openedAt: "date", accounts: "acct[]"}, acct: {income: "number", plan: "string(basic|plus|premium|trial)?", payments: "payment[]"}, payment: {amount: "number", city: "string?", priority: "boolean"}}, + blocks: [ + {expression: "acct.totals.eligible", value: "(min([abs(sum(map(acct.payments, #.amount))), 1000]) ^ 1)"}, + {assertion: "borrower.tag", conditions: [["and", "len(filter(borrower.accounts, #.income < #.income)) <= (borrower.years ?? 0)", 1], ["and", "round(borrower.limit / 7, 2) <= 0.5", 1]]}, + {expression: "borrower.points", value: "(avg(map(borrower.accounts, #.income)) ?? 0)"}, + {match: "borrower.rank", arms: [["contains(['low', 'gold', ''], borrower.sku)", "borrower.points == 1"], ["", "borrower.flagged"]]}, + {assertion: "acct.totals.exposure", conditions: [["or", "not (some(acct.payments, (#.city ?? '') in ['US', 'A1']))", 0], ["and", "some(acct.payments, matches((#.city ?? ''), 'a'))", 1], ["and", "acct.totals.eligible < (borrower.years ?? 0)", 1]]}, + {table: "t6", inputs: ["(borrower.years ?? 0)", null, "borrower.points"], outputs: ["borrower.penalty", "borrower.total[]", "borrower.discount"], rules: [ + ["", "(borrower.flagged and borrower.rank)", ">= 50", "", "borrower.score", "10"], + ["!= 3", "", "<= 3", "borrower.rank", "(borrower.years ?? 0)", "(1.5) / (abs(borrower.score) + 1)"], + [">= 100", "", "<= 100", "borrower.flagged", "number(string(borrower.limit))", "borrower.points"], + ]}, + {table: "t7", inputs: [null, "borrower.tag", null], outputs: ["acct.capped", "acct.quota[]"], rules: [ + ["", "false", "(acct.plan ?? '') in ['premium', 'plus']", "trunc(borrower.score)", "borrower.tag"], + ["", "false", "(borrower.rank or borrower.tag)", "acct.income", "borrower.tag"], + ["borrower.openedAt.isSameOrBefore(d('2025-03-20'), 'year')", "false", "", "acct.totals.eligible", "(borrower.penalty ?? false)"], + ["(borrower.discount ?? 0) > acct.income", "false", "(borrower.years ?? 0) <= (borrower.years ?? 0)", "borrower.limit", "borrower.flagged"], + ["isNumeric(borrower.sku)", "true", "", "(max(map(acct.payments, #.amount)) ?? 0)", ""], + ["borrower.discount == null", "false", "(borrower.tag and borrower.flagged)", "len(borrower.total)", "contains(['low', 'high', ''], borrower.sku)"], + ["", "true", "borrower.limit in [47..245)", "borrower.limit", "(borrower.penalty ?? false)"], + ]}, + {table: "t8", inputs: ["borrower.sku", "borrower.rank", "borrower.tag"], outputs: ["bonus[]"], rules: [ + ["$ != 'gold'", "true", "false", "(borrower.penalty ?? false)"], + ["", "false", "true", ""], + ]}, + {expression: "borrower.bucket", value: "(borrower.points <= (borrower.years ?? 0) ? borrower.years : null)"}, + {match: "borrower.surcharge", arms: [["(borrower.discount ?? 0) != (borrower.years ?? 0)", "(round(borrower.points / 7, 3) + len(bonus))"], ["", "(borrower.bucket ?? 0)"]]}, + {table: "t11", inputs: ["(acct.capped ?? 0)"], outputs: ["acct.adjusted[]"], rules: [ + ["1000, 18", ""], + ["!= 250", "contains(['none', 'high', ''], borrower.sku)"], + ["> 1.5", "borrower.tag"], + ]}, + {expression: "borrower.scores.net", value: "{s: 'a', n: string(len(borrower.sku) > 2), a: median([avg([borrower.points, borrower.limit, 250, (borrower.discount ?? 0)]), (0.5 + borrower.surcharge), (min(borrower.total) ?? 0), trunc((borrower.discount ?? 0))])}"}, + ], + }, + cases: [ + [{borrower: {score: 2, flagged: true, limit: 0.1, years: -0, openedAt: "2025-03-20", accounts: []}}, "!error: MissingRequiredInputs"], + [{borrower: {score: 10, flagged: false, limit: 250, years: 0.5, sku: "low", openedAt: "2030-12-31", accounts: []}}, "!error: ExpressionFailed"], + [{borrower: {score: 0, flagged: true, limit: 18, years: 5, sku: "NL", openedAt: "2025-03-20T10:15:30Z", accounts: []}}, "!error: ExpressionFailed"], + [{borrower: {score: 1e3, flagged: false, limit: 0.000001, years: 10, sku: "gold", openedAt: "2024-01-01", accounts: [{income: 0.5, plan: "basic", payments: []}]}}, {bonus: [], borrower: {accounts: [{adjusted: [false], capped: null, income: 0.5, payments: [], plan: "basic", quota: []}], discount: 0.0014985014985014985014985015, flagged: false, limit: 0.000001, openedAt: "2024-01-01", penalty: false, points: 0.5, rank: false, score: 1000, scores: {net: {a: 5.28550, n: "true", s: "a"}}, sku: "gold", surcharge: 0.071, tag: true, total: [10], years: 10}}], + [{borrower: {score: 7.25, flagged: false, limit: 250, years: 99.99, sku: "VIP", openedAt: "2025-03-20T10:15:30Z", accounts: []}}, "!error: ExpressionFailed"], + [{borrower: {score: 1000, flagged: true, limit: 5, years: -500, sku: "Oslo", openedAt: "2025-03-20", accounts: [{income: 1000, plan: false, payments: []}]}}, "!error: InputValidationFailed"], + [{borrower: {score: 10, flagged: false, limit: 2.50, years: 2, sku: "a", openedAt: "2025-03-20", accounts: [{income: 1000, plan: "basic", payments: []}, {income: 100, plan: "basic", payments: [{amount: 7.25, city: "Oslo", priority: false}, {amount: 0.000001, city: "A1", priority: false}]}, {income: 1.5, plan: "plus", payments: [{amount: 1000, city: "-", priority: true}, {amount: 2, city: "日本", priority: true}]}, {income: -0.01, plan: "trial", payments: []}, {income: 1, plan: "basic", payments: [{amount: 18, city: "VIP", priority: true}, {amount: 50, city: "none", priority: false}]}, {income: 50, plan: "basic", payments: []}, {income: 100, plan: "premium", payments: [{amount: 250, city: "gold", priority: false}]}, {income: 100, plan: "trial", payments: [{amount: -500, city: "A1", priority: true}, {amount: 100, city: "DE", priority: false}, {amount: 1000, city: "x-y", priority: false}]}, {income: 0.000001, plan: "plus", payments: [{amount: 50, city: "a-b-c", priority: false}, {amount: -1, city: "abc", priority: false}, {amount: 1, city: "日本", priority: true}]}, {income: 10, plan: "basic", payments: [{amount: 100, city: "gold", priority: false}, {amount: 2, city: "-", priority: true}]}, {income: 18, plan: "plus", payments: [{amount: 0.1, city: "-", priority: false}, {amount: 0.000001, city: "Oslo", priority: false}]}, {income: 100, plan: "basic", payments: [{amount: 250, city: "A1", priority: false}]}]}}, "!error: ExpressionFailed"], + [{borrower: {score: 50, flagged: true, limit: 2.50, years: 10, sku: "Zed", openedAt: "2024-02-29", accounts: [{income: 100, plan: "premium", payments: []}, {income: 0, plan: "plus", payments: []}, {income: 2, plan: "basic", payments: [{amount: 100, city: "O'Neil", priority: false}, {amount: 0.5, city: "", priority: true}]}, {income: 50, plan: null, payments: [{amount: 50, city: "a", priority: true}, {amount: 1, city: "gold", priority: false}]}]}}, "!error: ExpressionFailed"], + [{borrower: {score: 1, flagged: false, limit: 65, sku: "low", openedAt: "2024-01-01", accounts: []}}, "!error: ExpressionFailed"], + [{borrower: {score: -500, flagged: true, limit: 250, years: 18, sku: "abc", openedAt: "2030-12-31", accounts: [{income: 0.5, plan: "basic", payments: [{amount: 250, city: "a", priority: true}, {amount: 0, city: "-", priority: true}]}, {income: 18, plan: "trial", payments: [{amount: 10, city: "A1", priority: true}, {amount: 1.5, city: "日本", priority: false}]}]}}, "!error: ExpressionFailed"], + [{borrower: {score: "12", flagged: true, limit: -0, years: 7.25, sku: "DE", openedAt: "2024-01-01", accounts: [{income: 0, plan: "premium", payments: [{amount: 0.5, city: "gold", priority: false}, {amount: -0.01, city: "DE", priority: true}]}, {income: 0.5, plan: "premium", payments: [{amount: -0.5, city: "a", priority: false}, {amount: 99.99, city: "none", priority: false}]}, {income: -500, plan: "plus", payments: []}]}}, "!error: InputValidationFailed"], + [{borrower: {score: 100, flagged: false, limit: 0, years: -0.5, sku: "a", openedAt: "1990-06-15", accounts: [{income: null, plan: "premium", payments: [{amount: 99.99, city: "none", priority: true}, {amount: 99999999999999999999, city: "US", priority: false}]}]}}, "!error: ExpressionFailed"], + ], +} + +// seed 345200 (attempt 0) +{ + name: "b 53: shipment/members: 1 assertion, 7 expression, 2 table; 0 root, 12 per-member, 1 top-level computed", + policy: { + models: {shipment: {years: "number", city: "string", code: "string", members: "member[]"}, member: {amount: "number?", channel: "string", urgent: "boolean"}}, + blocks: [ + {table: "t1", inputs: ["shipment.years", "(min([abs(shipment.years), 1000]) ^ 3)"], outputs: ["member.band"], rules: [ + ["> 10", ">= 50", "(member.amount ?? 0)"], + ["", "0, 0.5", "100"], + ]}, + {expression: "member.total", value: "{n: number(string((member.band ?? 0)))}"}, + {expression: "member.grade", value: "map(shipment.members, ((#.band ?? 0) % (abs((50 - (#.band ?? 0))) + 1)))"}, + {expression: "member.decision", value: "member.amount"}, + {table: "t5", hit: "collect", inputs: ["trunc(shipment.years)", null, null], outputs: ["member.level", "member.rank", "member.meta.segment"], rules: [ + [">= 1.5", "(member.amount ?? 0) < shipment.years", "matches(member.channel, 'a')", "((member.band ?? 0) - (member.decision ?? 0))", "(member.amount ?? 0)", "shipment.years"], + ["< 1", "", "member.total.n != 0", "len(member.grade)", "(member.amount ?? 0)", "(member.band ?? 0)"], + ["> 1.5", "(member.band ?? 0) != (member.amount ?? 0)", "", "250", "", "(member.decision ?? 0)"], + ["50", "member.band != null", "(member.urgent or member.urgent)", "member.total.n", "(member.decision ?? 0)", "(member.amount ?? 0)"], + ["", "shipment.years > shipment.years", "(member.band ?? 0) != 2", "member.total.n", "len(member.channel)", "50"], + ["", "", "", "member.total.n", "5", "(member.decision ?? 0)"], + ]}, + {expression: "totals.surcharge", value: "(shipment.years > 18 ? shipment.years : shipment.years) >= shipment.years"}, + {assertion: "member.meta.exposure", conditions: [["and", "contains(['ok', 'VIP', ''], member.channel)", 0], ["or", "member.amount == null", 1]]}, + {expression: "member.flags.net", value: "(member.decision != null ? member.amount : null)"}, + {expression: "member.review", value: "len(filter(shipment.members, contains(['gold', 'high', ''], #.channel)))"}, + {expression: "member.flags.points", value: "member.decision"}, + ], + }, + cases: [ + [{shipment: {years: 1000, city: "é ü", code: "a", members: [{amount: 123456789.123, channel: "é ü", urgent: false}]}}, {shipment: {city: "é ü", code: "a", members: [{amount: 123456789.123, band: 123456789.123, channel: "é ü", decision: 123456789.123, flags: {net: 123456789.123, points: 123456789.123}, level: [123456789.123], meta: {exposure: false, segment: [123456789.123]}, rank: [5], review: 0, total: {n: 123456789.123}, urgent: false}], years: 1000}, totals: {surcharge: true}}], + [{shipment: {years: 2, city: "Zed", code: "", members: [{amount: 0, channel: "x-y", urgent: false}]}}, {shipment: {city: "Zed", code: "", members: [{amount: 0, band: null, channel: "x-y", decision: 0, flags: {net: 0, points: 0}, level: [0], meta: {exposure: false, segment: [0]}, rank: [5], review: 0, total: {n: 0}, urgent: false}], years: 2}, totals: {surcharge: true}}], + [{shipment: {years: 250, city: "NL", code: "high", members: [], extraField: "x"}}, {shipment: {city: "NL", code: "high", extraField: "x", members: [], years: 250}, totals: {surcharge: true}}], + [{shipment: {years: 50, city: "3.5", code: "Zed", members: [{amount: 50, channel: "abc", urgent: true}], extraField: "x"}}, {shipment: {city: "3.5", code: "Zed", extraField: "x", members: [{amount: 50, band: 50, channel: "abc", decision: 50, flags: {net: 50, points: 50}, level: [50, 50], meta: {exposure: false, segment: [50, 50]}, rank: [50, 5], review: 0, total: {n: 50}, urgent: true}], years: 50}, totals: {surcharge: true}}], + [{shipment: {years: 0, city: "NL", code: "US", members: [{amount: null, channel: "A1", urgent: true}]}}, {shipment: {city: "NL", code: "US", members: [{amount: null, band: 100, channel: "A1", decision: null, flags: {net: null, points: null}, grade: [49], level: [1, 100], meta: {exposure: false, segment: [100, 0]}, rank: [0, 5], review: 0, total: {n: 100}, urgent: true}], years: 0}, totals: {surcharge: true}}], + [{shipment: {years: 1, city: "DE", code: "日本", members: [{amount: 2, channel: "gold", urgent: true}, {amount: 1000000, channel: "Oslo", urgent: true}, {amount: 2.50, channel: "a-b-c", urgent: true}, {amount: 5, channel: "x", urgent: true}, {amount: -0.5, channel: "gold", urgent: false}]}}, {shipment: {city: "DE", code: "日本", members: [{amount: 2, band: null, channel: "gold", decision: 2, flags: {net: 2, points: 2}, level: [0], meta: {exposure: false, segment: [2]}, rank: [5], review: 2, total: {n: 0}, urgent: true}, {amount: 1000000, band: null, channel: "Oslo", decision: 1000000, flags: {net: 1000000, points: 1000000}, level: [0], meta: {exposure: false, segment: [1000000]}, rank: [5], review: 2, total: {n: 0}, urgent: true}, {amount: 2.50, band: null, channel: "a-b-c", decision: 2.50, flags: {net: 2.50, points: 2.50}, level: [0], meta: {exposure: false, segment: [2.50]}, rank: [5], review: 2, total: {n: 0}, urgent: true}, {amount: 5, band: null, channel: "x", decision: 5, flags: {net: 5, points: 5}, level: [0], meta: {exposure: false, segment: [5]}, rank: [5], review: 2, total: {n: 0}, urgent: true}, {amount: -0.5, band: null, channel: "gold", decision: -0.5, flags: {net: -0.5, points: -0.5}, level: [0], meta: {exposure: false, segment: [-0.5]}, rank: [5], review: 2, total: {n: 0}, urgent: false}], years: 1}, totals: {surcharge: true}}], + [{shipment: {years: 2, city: "a-b-c", code: " pad ", members: [{channel: "a", urgent: true}, {amount: 2, channel: "VIP", urgent: false}, {amount: 355, channel: "-", urgent: false}, {amount: null, channel: "A1", urgent: false}]}}, {shipment: {city: "a-b-c", code: " pad ", members: [{band: null, channel: "a", decision: null, flags: {net: null, points: null}, level: [0, 0], meta: {exposure: false, segment: [2, 0]}, rank: [0, 5], review: 0, total: {n: 0}, urgent: true}, {amount: 2, band: null, channel: "VIP", decision: 2, flags: {net: 2, points: 2}, level: [250, 0], meta: {exposure: false, segment: [2, 2]}, rank: [5], review: 0, total: {n: 0}, urgent: false}, {amount: 355, band: null, channel: "-", decision: 355, flags: {net: 355, points: 355}, level: [250, 0], meta: {exposure: false, segment: [355, 355]}, rank: [5], review: 0, total: {n: 0}, urgent: false}, {amount: null, band: null, channel: "A1", decision: null, flags: {net: null, points: null}, level: [0], meta: {exposure: false, segment: [0]}, rank: [5], review: 0, total: {n: 0}, urgent: false}], years: 2}, totals: {surcharge: true}}], + [{shipment: {years: 5, city: "gold", code: "a-b-c", members: [{amount: 2.50, channel: "gold", urgent: false}]}}, {shipment: {city: "gold", code: "a-b-c", members: [{amount: 2.50, band: null, channel: "gold", decision: 2.50, flags: {net: 2.50, points: 2.50}, level: [250, 0], meta: {exposure: false, segment: [2.50, 2.50]}, rank: [5], review: 1, total: {n: 0}, urgent: false}], years: 5}, totals: {surcharge: true}}], + [{shipment: {years: 5, city: "gold", code: "NL", members: [{amount: -500, channel: "abc", urgent: false}]}}, {shipment: {city: "gold", code: "NL", members: [{amount: -500, band: null, channel: "abc", decision: -500, flags: {net: -500, points: -500}, level: [500, 250, 0], meta: {exposure: false, segment: [5, -500, -500]}, rank: [-500, 5], review: 0, total: {n: 0}, urgent: false}], years: 5}, totals: {surcharge: true}}], + [{shipment: {years: 2.50, city: "US", code: "high", members: [{amount: 1000, channel: "x", urgent: true}, {amount: 1000, channel: "VIP", urgent: true}, {amount: 1.5, channel: "A1", urgent: false}]}}, {shipment: {city: "US", code: "high", members: [{amount: 1000, band: null, channel: "x", decision: 1000, flags: {net: 1000, points: 1000}, level: [250, 0], meta: {exposure: false, segment: [1000, 1000]}, rank: [5], review: 0, total: {n: 0}, urgent: true}, {amount: 1000, band: null, channel: "VIP", decision: 1000, flags: {net: 1000, points: 1000}, level: [250, 0], meta: {exposure: false, segment: [1000, 1000]}, rank: [5], review: 0, total: {n: 0}, urgent: true}, {amount: 1.5, band: null, channel: "A1", decision: 1.5, flags: {net: 1.5, points: 1.5}, level: [250, 0], meta: {exposure: false, segment: [1.5, 1.5]}, rank: [5], review: 0, total: {n: 0}, urgent: false}], years: 2.50}, totals: {surcharge: true}}], + [{shipment: {years: 2.50, city: "3.5", code: "a-b-c", members: [{channel: "é ü", urgent: true}, {amount: 1000, channel: "VIP", urgent: false}]}}, {shipment: {city: "3.5", code: "a-b-c", members: [{band: null, channel: "é ü", decision: null, flags: {net: null, points: null}, level: [0], meta: {exposure: false, segment: [0]}, rank: [5], review: 0, total: {n: 0}, urgent: true}, {amount: 1000, band: null, channel: "VIP", decision: 1000, flags: {net: 1000, points: 1000}, level: [250, 0], meta: {exposure: false, segment: [1000, 1000]}, rank: [5], review: 0, total: {n: 0}, urgent: false}], years: 2.50}, totals: {surcharge: true}}], + [{shipment: {years: 250, city: "-", code: "Zed", members: []}}, {shipment: {city: "-", code: "Zed", members: [], years: 250}, totals: {surcharge: true}}], + [{shipment: {years: 0.5, city: "ok", code: "high", members: [{amount: 18, channel: "VIP", urgent: false}, {amount: -1, channel: "日本", urgent: false}, {amount: 250, channel: "US", urgent: false}, {amount: -0.5, channel: "x-y", urgent: true}, {amount: 1, channel: "abc", urgent: true}], extraField: 1}}, {shipment: {city: "ok", code: "high", extraField: 1, members: [{amount: 18, band: null, channel: "VIP", decision: 18, flags: {net: 18, points: 18}, level: [0], meta: {exposure: false, segment: [18]}, rank: [5], review: 0, total: {n: 0}, urgent: false}, {amount: -1, band: null, channel: "日本", decision: -1, flags: {net: -1, points: -1}, level: [0], meta: {exposure: false, segment: [-1]}, rank: [5], review: 0, total: {n: 0}, urgent: false}, {amount: 250, band: null, channel: "US", decision: 250, flags: {net: 250, points: 250}, level: [0], meta: {exposure: false, segment: [250]}, rank: [5], review: 0, total: {n: 0}, urgent: false}, {amount: -0.5, band: null, channel: "x-y", decision: -0.5, flags: {net: -0.5, points: -0.5}, level: [0], meta: {exposure: false, segment: [-0.5]}, rank: [5], review: 0, total: {n: 0}, urgent: true}, {amount: 1, band: null, channel: "abc", decision: 1, flags: {net: 1, points: 1}, level: [0], meta: {exposure: false, segment: [1]}, rank: [5], review: 0, total: {n: 0}, urgent: true}], years: 0.5}, totals: {surcharge: true}}], + [{shipment: {years: 0, city: "Oslo", code: "Zed", members: [{amount: 10, channel: "VIP", urgent: false}]}}, {shipment: {city: "Oslo", code: "Zed", members: [{amount: 10, band: 100, channel: "VIP", decision: 10, flags: {net: 10, points: 10}, grade: [49], level: [1, 100], meta: {exposure: false, segment: [100, 10]}, rank: [10, 5], review: 0, total: {n: 100}, urgent: false}], years: 0}, totals: {surcharge: true}}], + [{shipment: {years: 491, city: "Oslo", code: "日本", members: [{amount: 0.1, channel: "12", urgent: true}, {amount: 50, channel: "VIP", urgent: true}, {amount: 18, channel: "VIP", urgent: true}, {amount: 1000, channel: "Zed", urgent: false}, {amount: 5, channel: "12", urgent: false}]}}, {shipment: {city: "Oslo", code: "日本", members: [{amount: 0.1, band: 0.1, channel: "12", decision: 0.1, flags: {net: 0.1, points: 0.1}, level: [0.1], meta: {exposure: false, segment: [0.1]}, rank: [5], review: 0, total: {n: 0.1}, urgent: true}, {amount: 50, band: 50, channel: "VIP", decision: 50, flags: {net: 50, points: 50}, level: [50], meta: {exposure: false, segment: [50]}, rank: [5], review: 0, total: {n: 50}, urgent: true}, {amount: 18, band: 18, channel: "VIP", decision: 18, flags: {net: 18, points: 18}, level: [18], meta: {exposure: false, segment: [18]}, rank: [5], review: 0, total: {n: 18}, urgent: true}, {amount: 1000, band: 1000, channel: "Zed", decision: 1000, flags: {net: 1000, points: 1000}, level: [1000], meta: {exposure: false, segment: [1000]}, rank: [5], review: 0, total: {n: 1000}, urgent: false}, {amount: 5, band: 5, channel: "12", decision: 5, flags: {net: 5, points: 5}, level: [5], meta: {exposure: false, segment: [5]}, rank: [5], review: 0, total: {n: 5}, urgent: false}], years: 491}, totals: {surcharge: true}}], + ], +} + +// seed 345300 (attempt 0) +{ + name: "b 54: tenant/accounts: 2 assertion, 3 expression, 2 match, 4 table; 11 root, 2 per-member, 2 top-level computed", + policy: { + models: {tenant: {balance: "number", channel: "string", qty: "number?", plan: "string(basic|plus|premium|trial)?", country: "string", accounts: "acct[]"}, acct: {rate: "number", channel: "string"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {match: "acct.net", arms: [["tenant.qty != null", "(tenant.plan ?? '') == 'premium'"], ["not (none(tenant.accounts, #.rate != 10))", "(matches(tenant.channel, '[0-9]$') or some(tenant.accounts, matches(#.channel, '[0-9]$')))"], ["not ((tenant.qty ?? 0) <= 1)", "acct.rate == 100"], ["", "(threshold <= 0 and acct.rate == 1)"]]}, + {match: "tenant.decision", arms: [["not (threshold <= 0.5)", "threshold"], ["matches((split(tenant.country, '-')[0] ?? 'none'), '^.{2,}$')", "len(tenant.country)"], ["(tenant.qty ?? 0) in [11..145)", "(number(string(tenant.balance)) / -6)"], ["contains(['ok', 'none', ''], tenant.channel)", "tenant.balance"], ["", "(min([abs((tenant.qty ?? 0)), 1000]) ^ 2)"]]}, + {table: "t3", inputs: ["tenant.qty"], outputs: ["tenant.meta.summary", "tenant.share", "tenant.penalty"], rules: [ + ["", "(tenant.qty ?? 0)", "tenant.decision <= 100", "tenant.decision"], + ["2, 250", "", "", "tenant.balance"], + ["0.5, 0", "tenant.decision", "(tenant.qty ?? 0) <= 2", "threshold"], + ["5", "tenant.decision", "tenant.decision > 0.5", "number(string(threshold))"], + ["", "threshold", "threshold > 250", "(tenant.qty ?? 0)"], + ]}, + {assertion: "tenant.health", conditions: ["(all(tenant.accounts, not (#.net)) and ((tenant.share ?? false) or (tenant.share ?? false)))", ["and", "(1000 * tenant.decision) <= tenant.balance", 1], ["and", "tenant.balance > (tenant.penalty ?? 0)", 0], ["or", "not ((tenant.share ?? false))", 2]]}, + {expression: "acct.capped", value: "(isNumeric(string(tenant.balance)) ? (acct.rate > acct.rate ? lower(tenant.channel) : (tenant.health ? tenant.country : acct.channel)) : ((tenant.health ? tenant.channel : tenant.channel) + '-' + tenant.country))"}, + {table: "t6", inputs: ["tenant.country", "(tenant.share ?? false)"], outputs: ["tenant.risk", "tenant.segment", "tenant.exposure"], rules: [ + ["'low'", "", "tenant.decision", "tenant.decision >= tenant.decision", "(tenant.share ?? false)"], + ["'ok'", "true", "(tenant.meta.summary ?? 0)", "(tenant.health and tenant.health)", "all(tenant.accounts, isNumeric(#.channel))"], + ["'A1', 'x'", "", "100", "(tenant.share ?? false)", "(tenant.share ?? false)"], + ["'ok', 'low'", "true", "(max(map(tenant.accounts, #.rate)) ?? 0)", "tenant.health", "(tenant.penalty ?? 0) == (tenant.meta.summary ?? 0)"], + ["'high'", "false", "50", "(tenant.share ?? false)", "tenant.health"], + ["'a'", "false", "threshold", "tenant.health", "tenant.health"], + ["", "", "tenant.balance", "tenant.health", "0.5 > (tenant.penalty ?? 0)"], + ]}, + {assertion: "tenant.ok", conditions: [["or", "(tenant.plan ?? '') == 'premium'", 1], ["and", "(tenant.qty ?? 0) in [28..29]", 1], ["or", "number(string(threshold)) < (tenant.risk ?? 0)", 0], ["or", "matches(string(tenant.health), 'a')", 0], ["and", "some(tenant.accounts, #.rate > #.rate)", 2]]}, + {expression: "tenant.rank", value: "(split(tenant.country, '-')[1] ?? 'none')"}, + {expression: "scores.surcharge", value: "filter(tenant.accounts, not (#.net))"}, + {table: "t10", hit: "collect", inputs: ["(min([abs(tenant.balance), 1000]) ^ 2)", "-((tenant.qty ?? 0))"], outputs: ["tenant.quota"], rules: [ + ["<= 250", "", "tenant.country"], + ["", "", "((tenant.segment ?? false) ? tenant.country : tenant.channel)"], + ]}, + {table: "t11", inputs: ["(min(map(tenant.accounts, #.rate)) ?? 0)"], outputs: ["eligible"], rules: [ + ["1.5", "(tenant.exposure ?? false)"], + ["", "(tenant.segment ?? false)"], + ]}, + ], + }, + cases: [ + [{threshold: 100, tenant: {balance: -0.01, channel: "a", qty: 0.5, plan: "basic", country: "ok", accounts: [{rate: 10, channel: "A1"}]}}, {eligible: false, scores: {surcharge: [{capped: "A1", channel: "A1", net: false, rate: 10}]}, tenant: {accounts: [{capped: "A1", channel: "A1", net: false, rate: 10}], balance: -0.01, channel: "a", country: "ok", decision: 100, exposure: false, health: false, meta: {summary: 0.5}, ok: true, penalty: 100, plan: "basic", qty: 0.5, quota: ["ok", "a"], rank: "none", risk: 0.5, segment: false, share: true}, threshold: 100}], + [{threshold: 10, tenant: {balance: 7.25, channel: "ok", qty: 1000, plan: "premium", country: "ok", accounts: []}}, "!error: ExpressionFailed"], + [{threshold: 0, tenant: {balance: 0.5, channel: "low", qty: null, plan: "basic", country: "", accounts: [{rate: 5, channel: "low"}, {rate: 5, channel: "low"}]}}, {eligible: false, scores: {surcharge: [{capped: "low", channel: "low", net: false, rate: 5}, {capped: "low", channel: "low", net: false, rate: 5}]}, tenant: {accounts: [{capped: "low", channel: "low", net: false, rate: 5}, {capped: "low", channel: "low", net: false, rate: 5}], balance: 0.5, channel: "low", country: "", decision: 0, exposure: true, health: false, meta: {summary: 0}, ok: true, penalty: 0, plan: "basic", qty: null, quota: ["", "low"], rank: "none", risk: 0.5, segment: false, share: true}, threshold: 0}], + [{threshold: 10, tenant: {balance: -0.01, channel: "ok", qty: 50, plan: "trial", country: "日本", accounts: [{rate: 123456789.123, channel: "3.5"}, {rate: 438, channel: "a"}], extraField: {nested: true}}}, {eligible: false, scores: {surcharge: [{capped: "3.5", channel: "3.5", net: false, rate: 123456789.123}, {capped: "a", channel: "a", net: false, rate: 438}]}, tenant: {accounts: [{capped: "3.5", channel: "3.5", net: false, rate: 123456789.123}, {capped: "a", channel: "a", net: false, rate: 438}], balance: -0.01, channel: "ok", country: "日本", decision: 10, exposure: false, extraField: {nested: true}, health: false, meta: {summary: 50}, ok: true, penalty: 10, plan: "trial", qty: 50, quota: ["日本", "ok"], rank: "none", risk: -0.01, segment: false, share: true}, threshold: 10}], + [{threshold: 1, tenant: {balance: 0.5, channel: "x", plan: "basic", country: "high", accounts: [{rate: 250, channel: "none"}]}}, {eligible: false, scores: {surcharge: [{capped: "none", channel: "none", net: false, rate: 250}]}, tenant: {accounts: [{capped: "none", channel: "none", net: false, rate: 250}], balance: 0.5, channel: "x", country: "high", decision: 1, exposure: false, health: false, meta: {summary: 0}, ok: true, penalty: 1, plan: "basic", quota: ["high", "x"], rank: "none", risk: 0.5, segment: false, share: true}, threshold: 1}], + [{threshold: 100, tenant: {balance: 99999999999999999999, channel: "x", qty: null, plan: "trial", country: "high", accounts: [{rate: 100, channel: ""}, {rate: 5, channel: "x"}, {rate: 7.25, channel: "日本"}]}}, {eligible: false, scores: {surcharge: [{capped: "", channel: "", net: false, rate: 100}, {capped: "x", channel: "x", net: false, rate: 5}, {capped: "日本", channel: "日本", net: false, rate: 7.25}]}, tenant: {accounts: [{capped: "", channel: "", net: false, rate: 100}, {capped: "x", channel: "x", net: false, rate: 5}, {capped: "日本", channel: "日本", net: false, rate: 7.25}], balance: 99999999999999999999, channel: "x", country: "high", decision: 100, exposure: false, health: false, meta: {summary: 0}, ok: true, penalty: 100, plan: "trial", qty: null, quota: ["x"], rank: "none", risk: 99999999999999999999, segment: false, share: true}, threshold: 100}], + [{threshold: 0.5, tenant: {balance: 0.5, channel: "é ü", qty: 5, plan: "basic", country: "", accounts: [{rate: 1, channel: "a-b-c"}, {rate: 50, channel: "a"}, {rate: 5, channel: "O'Neil"}, {rate: 10, channel: "a"}, {rate: 2, channel: "é ü"}]}}, {eligible: false, scores: {surcharge: [{capped: "a-b-c", channel: "a-b-c", net: false, rate: 1}, {capped: "a", channel: "a", net: false, rate: 50}, {capped: "O'Neil", channel: "O'Neil", net: false, rate: 5}, {capped: "a", channel: "a", net: false, rate: 10}, {capped: "é ü", channel: "é ü", net: false, rate: 2}]}, tenant: {accounts: [{capped: "a-b-c", channel: "a-b-c", net: false, rate: 1}, {capped: "a", channel: "a", net: false, rate: 50}, {capped: "O'Neil", channel: "O'Neil", net: false, rate: 5}, {capped: "a", channel: "a", net: false, rate: 10}, {capped: "é ü", channel: "é ü", net: false, rate: 2}], balance: 0.5, channel: "é ü", country: "", decision: 25, exposure: false, health: false, meta: {summary: 5}, ok: true, penalty: 25, plan: "basic", qty: 5, quota: ["", "é ü"], rank: "none", risk: 0.5, segment: false, share: true}, threshold: 0.5}], + [{threshold: 10, tenant: {balance: 0.5, channel: "x", qty: 0.5, plan: null, country: "O'Neil", accounts: [{rate: 10, channel: "ok"}]}}, {eligible: false, scores: {surcharge: [{capped: "ok", channel: "ok", net: false, rate: 10}]}, tenant: {accounts: [{capped: "ok", channel: "ok", net: false, rate: 10}], balance: 0.5, channel: "x", country: "O'Neil", decision: 10, exposure: false, health: false, meta: {summary: 0.5}, ok: true, penalty: 10, plan: null, qty: 0.5, quota: ["O'Neil", "x"], rank: "none", risk: 0.5, segment: false, share: true}, threshold: 10}], + [{threshold: 100, tenant: {balance: 123456789.123, channel: "é ü", qty: 1, plan: "trial", country: "O'Neil", accounts: []}}, "!error: ExpressionFailed"], + [{threshold: 0.5, tenant: {balance: 0, channel: "abc", qty: 1e3, plan: "trial", country: "a", accounts: [{rate: 0.5, channel: "none"}], extraField: {nested: true}}}, {eligible: false, scores: {surcharge: [{capped: "none", channel: "none", net: false, rate: 0.5}]}, tenant: {accounts: [{capped: "none", channel: "none", net: false, rate: 0.5}], balance: 0, channel: "abc", country: "a", decision: 1000000, exposure: false, extraField: {nested: true}, health: false, meta: {summary: 1000}, ok: true, penalty: 1000000, plan: "trial", qty: 1000, quota: ["a", "abc"], rank: "none", risk: 0.5, segment: false, share: false}, threshold: 0.5}], + [{threshold: 1, tenant: {balance: 0, channel: "A1", qty: 0.1, country: "x", accounts: [{rate: 0.5, channel: "a"}]}}, {eligible: true, scores: {surcharge: [{capped: "a", channel: "a", net: false, rate: 0.5}]}, tenant: {accounts: [{capped: "a", channel: "a", net: false, rate: 0.5}], balance: 0, channel: "A1", country: "x", decision: 1, exposure: true, health: false, meta: {summary: 0.1}, ok: true, penalty: 1, qty: 0.1, quota: ["x", "x"], rank: "none", risk: 100, segment: true, share: true}, threshold: 1}], + [{threshold: 0.5, tenant: {balance: 1000, channel: "gold", qty: -500, plan: "plus", country: "high", accounts: [{rate: 18, channel: "US"}]}}, {eligible: false, scores: {surcharge: [{capped: "US", channel: "US", net: false, rate: 18}]}, tenant: {accounts: [{capped: "US", channel: "US", net: false, rate: 18}], balance: 1000, channel: "gold", country: "high", decision: 4, exposure: false, health: false, meta: {summary: -500}, ok: true, penalty: 4, plan: "plus", qty: -500, quota: ["gold"], rank: "none", risk: 1000, segment: false, share: true}, threshold: 0.5}], + [{threshold: 10, tenant: {balance: 0, channel: "US", qty: 100, plan: "basic", country: "A1", accounts: [{channel: "low"}]}}, "!error: ExpressionFailed"], + [{threshold: 1, tenant: {balance: 99.99, channel: "high", qty: 3, plan: "basic", country: "DE", accounts: []}}, "!error: ExpressionFailed"], + [{threshold: 0, tenant: {balance: 7.25, channel: "high", qty: 18, country: "", accounts: [{rate: 0, channel: "Oslo"}, {rate: 5, channel: "-"}]}}, {eligible: false, scores: {surcharge: [{capped: "Oslo", channel: "Oslo", net: false, rate: 0}, {capped: "-", channel: "-", net: false, rate: 5}]}, tenant: {accounts: [{capped: "Oslo", channel: "Oslo", net: false, rate: 0}, {capped: "-", channel: "-", net: false, rate: 5}], balance: 7.25, channel: "high", country: "", decision: -1.2083333333333333333333333333, exposure: true, health: false, meta: {summary: 18}, ok: true, penalty: -1.2083333333333333333333333333, qty: 18, quota: ["", "high"], rank: "none", risk: 7.25, segment: false, share: true}, threshold: 0}], + [{threshold: 1, tenant: {balance: 426, channel: "none", qty: 1000, plan: "basic", country: "DE", accounts: [{rate: 1000, channel: "none"}, {rate: 0.5, channel: "ok"}], extraField: 1}}, {eligible: false, scores: {surcharge: [{capped: "none", channel: "none", net: false, rate: 1000}, {capped: "ok", channel: "ok", net: false, rate: 0.5}]}, tenant: {accounts: [{capped: "none", channel: "none", net: false, rate: 1000}, {capped: "ok", channel: "ok", net: false, rate: 0.5}], balance: 426, channel: "none", country: "DE", decision: 1, exposure: false, extraField: 1, health: false, meta: {summary: 1000}, ok: true, penalty: 1, plan: "basic", qty: 1000, quota: ["none"], rank: "none", risk: 426, segment: false, share: true}, threshold: 1}], + [{threshold: 0, tenant: {balance: 0, channel: "ok", qty: 2.50, country: "NL", accounts: [{rate: 0, channel: "a"}, {rate: -0.5, channel: "A1"}, {rate: 1e3, channel: "ok"}, {rate: 250, channel: "Oslo"}]}}, {eligible: false, scores: {surcharge: [{capped: "a", channel: "a", net: false, rate: 0}, {capped: "A1", channel: "A1", net: false, rate: -0.5}, {capped: "ok", channel: "ok", net: false, rate: 1000}, {capped: "Oslo", channel: "Oslo", net: false, rate: 250}]}, tenant: {accounts: [{capped: "a", channel: "a", net: false, rate: 0}, {capped: "A1", channel: "A1", net: false, rate: -0.5}, {capped: "ok", channel: "ok", net: false, rate: 1000}, {capped: "Oslo", channel: "Oslo", net: false, rate: 250}], balance: 0, channel: "ok", country: "NL", decision: 2, exposure: false, health: false, meta: {summary: 2.50}, ok: true, penalty: 2, qty: 2.50, quota: ["NL", "ok"], rank: "none", risk: 0, segment: false, share: true}, threshold: 0}], + [{threshold: -2, tenant: {balance: 0.000001, channel: "ok", qty: 18, plan: "plus", country: "O'Neil", accounts: [{rate: 10, channel: "high"}, {rate: 0, channel: "ok"}]}}, {eligible: false, scores: {surcharge: [{capped: "high", channel: "high", net: false, rate: 10}, {capped: "ok", channel: "ok", net: false, rate: 0}]}, tenant: {accounts: [{capped: "high", channel: "high", net: false, rate: 10}, {capped: "ok", channel: "ok", net: false, rate: 0}], balance: 0.000001, channel: "ok", country: "O'Neil", decision: 6, exposure: false, health: false, meta: {summary: 18}, ok: true, penalty: 6, plan: "plus", qty: 18, quota: ["O'Neil", "ok"], rank: "none", risk: 0.000001, segment: false, share: true}, threshold: -2}], + [{threshold: 1, tenant: {balance: 1, channel: "", qty: 250, plan: "basic", country: "none", accounts: [{rate: 2, channel: "US"}, {rate: 0.5, channel: "ok"}]}}, {eligible: false, scores: {surcharge: [{capped: "US", channel: "US", net: false, rate: 2}, {capped: "ok", channel: "ok", net: false, rate: 0.5}]}, tenant: {accounts: [{capped: "US", channel: "US", net: false, rate: 2}, {capped: "ok", channel: "ok", net: false, rate: 0.5}], balance: 1, channel: "", country: "none", decision: 1, exposure: false, health: false, meta: {summary: 250}, ok: true, penalty: 1, plan: "basic", qty: 250, quota: ["none", ""], rank: "none", risk: 1, segment: false, share: true}, threshold: 1}], + [{threshold: -2, tenant: {balance: 123456789.123, channel: "a-b-c", qty: null, plan: "basic", country: "high", accounts: [{rate: -0, channel: "VIP"}, {rate: 0.5, channel: "x"}]}}, {eligible: false, scores: {surcharge: [{capped: "VIP", channel: "VIP", net: false, rate: 0}, {capped: "x", channel: "x", net: false, rate: 0.5}]}, tenant: {accounts: [{capped: "VIP", channel: "VIP", net: false, rate: 0}, {capped: "x", channel: "x", net: false, rate: 0.5}], balance: 123456789.123, channel: "a-b-c", country: "high", decision: 4, exposure: false, health: false, meta: {summary: 0}, ok: true, penalty: 4, plan: "basic", qty: null, quota: ["a-b-c"], rank: "none", risk: 123456789.123, segment: false, share: true}, threshold: -2}], + [{threshold: 10, tenant: {balance: 100, channel: "-", qty: 99999999999999999999, plan: "plus", country: "A1", accounts: [{rate: 2, channel: "US"}, {rate: 99999999999999999999, channel: "Oslo"}], extraField: 1}}, {eligible: true, scores: {surcharge: [{capped: "US", channel: "US", net: false, rate: 2}, {capped: "Oslo", channel: "Oslo", net: false, rate: 99999999999999999999}]}, tenant: {accounts: [{capped: "US", channel: "US", net: false, rate: 2}, {capped: "Oslo", channel: "Oslo", net: false, rate: 99999999999999999999}], balance: 100, channel: "-", country: "A1", decision: 10, exposure: true, extraField: 1, health: false, meta: {summary: 99999999999999999999}, ok: true, penalty: 10, plan: "plus", qty: 99999999999999999999, quota: ["A1"], rank: "none", risk: 100, segment: true, share: true}, threshold: 10}], + [{threshold: 100, tenant: {balance: 100, channel: " pad ", qty: 100, plan: "trial", country: "x", accounts: [{rate: 18, channel: "low"}, {rate: 250, channel: "none"}, {rate: 0.000001, channel: "DE"}, {rate: 1000, channel: "a-b-c"}, {rate: 100, channel: "US"}]}}, {eligible: true, scores: {surcharge: [{capped: "low", channel: "low", net: false, rate: 18}, {capped: "none", channel: "none", net: false, rate: 250}, {capped: "DE", channel: "DE", net: false, rate: 0.000001}, {capped: "a-b-c", channel: "a-b-c", net: false, rate: 1000}, {capped: "US", channel: "US", net: false, rate: 100}]}, tenant: {accounts: [{capped: "low", channel: "low", net: false, rate: 18}, {capped: "none", channel: "none", net: false, rate: 250}, {capped: "DE", channel: "DE", net: false, rate: 0.000001}, {capped: "a-b-c", channel: "a-b-c", net: false, rate: 1000}, {capped: "US", channel: "US", net: false, rate: 100}], balance: 100, channel: " pad ", country: "x", decision: 100, exposure: true, health: false, meta: {summary: 100}, ok: true, penalty: 100, plan: "trial", qty: 100, quota: ["x"], rank: "none", risk: 100, segment: true, share: true}, threshold: 100}], + [{threshold: 100, tenant: {balance: true, channel: "日本", qty: 100, plan: "trial", country: "a", accounts: []}}, "!error: InputValidationFailed"], + [{threshold: 10, tenant: {balance: 123456789.123, channel: "a", qty: 250, plan: "plus", country: "日本", accounts: []}}, "!error: ExpressionFailed"], + [{threshold: 10, tenant: {balance: 5, channel: "日本", qty: 1000, plan: "basic", country: "3.5", accounts: []}}, "!error: ExpressionFailed"], + [{threshold: 1, tenant: {balance: 0.5, channel: "A1", qty: 100, plan: "premium", country: "none", accounts: [{rate: 3, channel: "日本"}, {rate: 100, channel: "none"}, {rate: 0, channel: "Zed"}, {rate: 0.000001, channel: "Oslo"}]}}, {eligible: false, scores: {surcharge: []}, tenant: {accounts: [{capped: "日本", channel: "日本", net: true, rate: 3}, {capped: "none", channel: "none", net: true, rate: 100}, {capped: "Zed", channel: "Zed", net: true, rate: 0}, {capped: "Oslo", channel: "Oslo", net: true, rate: 0.000001}], balance: 0.5, channel: "A1", country: "none", decision: 1, exposure: false, health: false, meta: {summary: 100}, ok: true, penalty: 1, plan: "premium", qty: 100, quota: ["none", "A1"], rank: "none", risk: 0.5, segment: false, share: true}, threshold: 1}], + [{threshold: 100, tenant: {balance: 100, channel: "none", qty: 100, plan: "premium", country: "3.5", accounts: [{rate: 1, channel: "Zed"}]}}, {eligible: false, scores: {surcharge: []}, tenant: {accounts: [{capped: "Zed", channel: "Zed", net: true, rate: 1}], balance: 100, channel: "none", country: "3.5", decision: 100, exposure: false, health: false, meta: {summary: 100}, ok: true, penalty: 100, plan: "premium", qty: 100, quota: ["none"], rank: "none", risk: 100, segment: false, share: true}, threshold: 100}], + [{threshold: 0, tenant: {balance: 0.5, channel: "12", qty: null, plan: null, country: "x-y", accounts: [{rate: 99.99, channel: "日本"}, {rate: 0, channel: "a-b-c"}, {rate: 100, channel: "abc"}]}}, {eligible: false, scores: {surcharge: []}, tenant: {accounts: [{capped: "日本", channel: "日本", net: true, rate: 99.99}, {capped: "a-b-c", channel: "a-b-c", net: true, rate: 0}, {capped: "abc", channel: "abc", net: true, rate: 100}], balance: 0.5, channel: "12", country: "x-y", decision: 0, exposure: true, health: false, meta: {summary: 0}, ok: true, penalty: 0, plan: null, qty: null, quota: ["x-y", "12"], rank: "y", risk: 0.5, segment: false, share: true}, threshold: 0}], + ], +} + +// seed 345400 (attempt 0) +{ + name: "b 55: order/lines: 1 assertion, 1 expression, 5 match, 5 table; 7 root, 6 per-member, 7 top-level computed", + policy: { + models: {order: {rate: "number", limit: "number?", price: "number", city: "string", birthDate: "date", urgent: "boolean?", lines: "line[]"}, line: {price: "number", active: "boolean?", verified: "boolean"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {match: "line.bonus", arms: [["order.rate in [-2..91]", "order.city"], ["isNumeric(order.city)", "order.city"], ["order.city == 'Oslo'", "order.city"], ["isNumeric(order.city)", "`${baseRate}/${line.verified}`"], ["", "order.city"]]}, + {table: "t2", hit: "collect", inputs: ["order.city"], outputs: ["net", "margin", "decision"], rules: [ + ["'DE'", "order.city", "5", "baseRate"], + ["'US', 'Oslo'", "`${(order.urgent ?? false)}/${order.rate}`", "-(order.rate)", "baseRate"], + ["$ != 'DE'", "order.city", "(order.limit ?? 0)", "round(baseRate, 2)"], + ["'a', 'US'", "'a'", "order.rate", "order.birthDate.month()"], + ]}, + {table: "t3", inputs: ["order.rate", null], outputs: ["line.total", "line.ok[]", "line.totals.level"], rules: [ + ["", "contains(['ok', 'none', ''], line.bonus)", "baseRate", "baseRate", "order.rate"], + ["", "", "", "number(string(order.rate))", ""], + ]}, + {table: "t4", inputs: ["order.city"], outputs: ["order.calc.bucket", "order.calc.grade", "order.segment"], rules: [ + ["startsWith($, 'low')", "order.city", "order.price", "order.city"], + ["", "", "order.price", "order.city"], + ["", "order.city", "len(filter(order.lines, (#.total ?? 0) in [-3..128]))", "string(order.rate)"], + ["startsWith($, 'DE')", "order.city", "3", "order.city"], + ["'retail'", "order.city", "order.rate", "`${order.rate}/${order.price}`"], + ]}, + {match: "surcharge", arms: [["none(order.lines, #.total == null)", "len(order.lines)"], ["order.birthDate.isBefore(d('2024-01-01'), 'year')", "-((baseRate * baseRate))"], ["matches(`${(order.urgent ?? false)}/${(order.urgent ?? false)}`, '^[A-Z]')", "baseRate"], ["", "floor((order.limit ?? 0))"]]}, + {assertion: "line.tag", conditions: [["and", "order.birthDate.isSame(d('2025-01-01'), 'month')", 1], ["or", "line.total == null", 0], ["and", "((line.active ?? false) or (line.active ?? false))", 0], "not (line.verified)", ["and", "order.birthDate < d('2025-03-20')", 0]]}, + {match: "flags.eligible", arms: [["((order.urgent ?? false) and (order.urgent ?? false))", "order.city"], ["order.rate in [15..126]", "order.city"], ["", "((order.urgent ?? false) ? order.city : order.city)"]]}, + {match: "points", arms: [["(matches((order.segment ?? ''), '^[A-Z]') and not ((order.urgent ?? false)))", "not ((order.urgent ?? false))"], ["flags.eligible != 'US'", "surcharge < (order.limit ?? 0)"], ["all(order.lines, contains(['retail', 'none', ''], #.bonus))", "(order.urgent ?? false)"], ["", "(order.urgent ?? false)"]]}, + {match: "line.exposure", arms: [["contains(['none', 'low', ''], (order.calc.bucket ?? ''))", "(line.active ?? false)"], ["(line.total ?? 0) in [12..27]", "order.birthDate > d('2024-01-01')"], ["not (order.birthDate.isSameOrBefore(d('2025-01-01'), 'day'))", "all(order.lines, 10 > (#.totals.level ?? 0))"], ["((line.active ?? false) or (line.active ?? false))", "line.verified"], ["", "line.tag"]]}, + {table: "t10", inputs: ["(order.calc.bucket ?? '')", "(0 + (order.limit ?? 0))"], outputs: ["scores.capped"], rules: [ + ["$ != 'A1'", "", "points"], + ["$ != 'ok'", "", ""], + ["$ != 'retail'", "!= 1000", ""], + ["'gold'", ">= 2", "points"], + ]}, + {expression: "order.health", value: "count(order.lines, #.price > (#.total ?? 0))"}, + {table: "t12", inputs: ["(order.health / 3)", null], outputs: ["order.band", "order.weighted[]", "order.risk"], rules: [ + ["> 50", "((order.urgent ?? false) and points)", "order.health", "'VIP'", "order.rate"], + ["", "", "(order.calc.grade ?? 0)", "order.city", "(order.calc.grade ?? 0)"], + ]}, + ], + }, + cases: [ + [{baseRate: -2, order: {rate: 0.5, limit: null, price: 1000, city: "retail", birthDate: "2030-12-31", urgent: null, lines: []}}, {baseRate: -2, decision: [-2], flags: {eligible: "retail"}, margin: [0], net: ["retail"], order: {band: 1000, birthDate: "2030-12-31", calc: {bucket: "retail", grade: 1000}, city: "retail", health: 0, limit: null, lines: [], price: 1000, rate: 0.5, risk: 1000, segment: "retail", urgent: null, weighted: ["retail"]}, points: false, scores: {capped: false}, surcharge: 0}], + [{baseRate: 1, order: {rate: 10, limit: 100, price: -500, city: "none", birthDate: "2030-12-31", urgent: true, lines: [{price: -1, active: true, verified: false}, {price: 2, active: false, verified: false}, {price: 5, active: true, verified: false}, {price: 1.5, active: false, verified: false}]}}, {baseRate: 1, decision: [1], flags: {eligible: "none"}, margin: [100], net: ["none"], order: {band: -500, birthDate: "2030-12-31", calc: {bucket: "none", grade: -500}, city: "none", health: 3, limit: 100, lines: [{active: true, bonus: "none", exposure: true, ok: [1, 10], price: -1, total: 1, totals: {level: 10}, verified: false}, {active: false, bonus: "none", exposure: false, ok: [1, 10], price: 2, total: 1, totals: {level: 10}, verified: false}, {active: true, bonus: "none", exposure: true, ok: [1, 10], price: 5, total: 1, totals: {level: 10}, verified: false}, {active: false, bonus: "none", exposure: false, ok: [1, 10], price: 1.5, total: 1, totals: {level: 10}, verified: false}], price: -500, rate: 10, risk: -500, segment: "none", urgent: true, weighted: ["none"]}, points: true, scores: {capped: true}, surcharge: 4}], + [{baseRate: 10, order: {rate: 250, price: 0.000001, city: "US", birthDate: "2030-12-31", urgent: false, lines: [{price: 100, active: true, verified: true}, {price: 65, active: true, verified: true}, {price: 2.50, active: true, verified: false}, {price: 0.000001, active: true, verified: true}]}}, {baseRate: 10, decision: [10, 10, 12], flags: {eligible: "US"}, margin: [-250, 0, 250], net: ["false/250", "US", "a"], order: {band: 0.000001, birthDate: "2030-12-31", calc: {bucket: "US", grade: 0.000001}, city: "US", health: 4, lines: [{active: true, bonus: "US", exposure: true, ok: [250], price: 100, total: null, totals: {level: null}, verified: true}, {active: true, bonus: "US", exposure: true, ok: [250], price: 65, total: null, totals: {level: null}, verified: true}, {active: true, bonus: "US", exposure: true, ok: [250], price: 2.50, total: null, totals: {level: null}, verified: false}, {active: true, bonus: "US", exposure: true, ok: [250], price: 0.000001, total: null, totals: {level: null}, verified: true}], price: 0.000001, rate: 250, risk: 0.000001, segment: "US", urgent: false, weighted: ["US"]}, points: true, scores: {capped: true}}], + [{baseRate: -2, order: {rate: 5, price: 2, city: "-", birthDate: "1990-06-15", lines: [{price: -0.5, active: null, verified: true}, {price: 0, active: false, verified: true}, {price: 1000, verified: false}, {price: -500, active: false, verified: true}]}}, {baseRate: -2, decision: [-2], flags: {eligible: "-"}, margin: [0], net: ["-"], order: {band: 2, birthDate: "1990-06-15", calc: {bucket: "-", grade: 2}, city: "-", health: 1, lines: [{active: null, bonus: "-", exposure: false, ok: [5], price: -0.5, tag: false, total: null, totals: {level: null}, verified: true}, {active: false, bonus: "-", exposure: false, ok: [5], price: 0, tag: false, total: null, totals: {level: null}, verified: true}, {bonus: "-", exposure: false, ok: [5], price: 1000, tag: false, total: null, totals: {level: null}, verified: false}, {active: false, bonus: "-", exposure: false, ok: [5], price: -500, tag: false, total: null, totals: {level: null}, verified: true}], price: 2, rate: 5, risk: 2, segment: "-", weighted: ["-"]}, points: true, scores: {capped: true}, surcharge: -4}], + [{baseRate: 10, order: {rate: 1000000, limit: 50, price: 65, city: "é ü", birthDate: "2000-01-01", lines: [{price: 5, verified: true}, {price: 1e3, active: true, verified: true}, {price: -1, verified: false}, {price: 18, active: false, verified: false}]}}, {baseRate: 10, decision: [10], flags: {eligible: "é ü"}, margin: [50], net: ["é ü"], order: {band: 65, birthDate: "2000-01-01", calc: {bucket: "é ü", grade: 65}, city: "é ü", health: 3, limit: 50, lines: [{bonus: "é ü", exposure: false, ok: [1000000], price: 5, tag: false, total: null, totals: {level: null}, verified: true}, {active: true, bonus: "é ü", exposure: true, ok: [1000000], price: 1000, tag: false, total: null, totals: {level: null}, verified: true}, {bonus: "é ü", exposure: false, ok: [1000000], price: -1, tag: false, total: null, totals: {level: null}, verified: false}, {active: false, bonus: "é ü", exposure: false, ok: [1000000], price: 18, tag: false, total: null, totals: {level: null}, verified: false}], price: 65, rate: 1000000, risk: 65, segment: "é ü", weighted: ["é ü"]}, points: true, scores: {capped: true}, surcharge: -100}], + [{baseRate: 0.5, order: {rate: 2, limit: 1, price: 1000, city: "A1", birthDate: "2024-01-01", urgent: true, lines: [{price: 0, verified: true}, {price: 0, verified: false}]}}, {baseRate: 0.5, decision: [0.5], flags: {eligible: "A1"}, margin: [1], net: ["A1"], order: {band: 1000, birthDate: "2024-01-01", calc: {bucket: "A1", grade: 1000}, city: "A1", health: 0, limit: 1, lines: [{bonus: "A1", exposure: false, ok: [2], price: 0, tag: false, total: null, totals: {level: null}, verified: true}, {bonus: "A1", exposure: false, ok: [2], price: 0, tag: false, total: null, totals: {level: null}, verified: false}], price: 1000, rate: 2, risk: 1000, segment: "A1", urgent: true, weighted: ["A1"]}, points: false, scores: {capped: null}, surcharge: 1}], + [{baseRate: 0.5, order: {rate: 250, limit: 0, price: 2.50, city: "x", birthDate: "2024-01-01", urgent: true, lines: [{price: 3, active: true, verified: true}, {price: -0.01, active: false, verified: true}]}}, {baseRate: 0.5, decision: [0.5], flags: {eligible: "x"}, margin: [0], net: ["x"], order: {band: 2.50, birthDate: "2024-01-01", calc: {bucket: "x", grade: 2.50}, city: "x", health: 1, limit: 0, lines: [{active: true, bonus: "x", exposure: true, ok: [250], price: 3, tag: false, total: null, totals: {level: null}, verified: true}, {active: false, bonus: "x", exposure: false, ok: [250], price: -0.01, tag: false, total: null, totals: {level: null}, verified: true}], price: 2.50, rate: 250, risk: 2.50, segment: "x", urgent: true, weighted: ["x"]}, points: false, scores: {capped: false}, surcharge: 0}], + [{baseRate: 1, order: {rate: 50, limit: 1.5, price: 0, city: "DE", birthDate: "1990-06-15", urgent: true, lines: [{price: 50, active: true, verified: true}, {price: 1000, active: false, verified: true}, {price: 250, active: false, verified: false}, {price: 3, active: true, verified: true}], extraField: "x"}}, {baseRate: 1, decision: [1], flags: {eligible: "DE"}, margin: [5], net: ["DE"], order: {band: 0, birthDate: "1990-06-15", calc: {bucket: "DE", grade: 0}, city: "DE", extraField: "x", health: 4, limit: 1.5, lines: [{active: true, bonus: "DE", exposure: true, ok: [50], price: 50, tag: false, total: null, totals: {level: null}, verified: true}, {active: false, bonus: "DE", exposure: false, ok: [50], price: 1000, tag: false, total: null, totals: {level: null}, verified: true}, {active: false, bonus: "DE", exposure: false, ok: [50], price: 250, tag: false, total: null, totals: {level: null}, verified: false}, {active: true, bonus: "DE", exposure: true, ok: [50], price: 3, tag: false, total: null, totals: {level: null}, verified: true}], price: 0, rate: 50, risk: 0, segment: "DE", urgent: true, weighted: ["DE"]}, points: true, scores: {capped: true}, surcharge: -1}], + [{baseRate: 0.5, order: {rate: 0.5, limit: null, price: 50, city: "DE", birthDate: "2030-12-31", urgent: false, lines: [{price: 0, active: true, verified: true}]}}, {baseRate: 0.5, decision: [0.5], flags: {eligible: "DE"}, margin: [5], net: ["DE"], order: {band: 50, birthDate: "2030-12-31", calc: {bucket: "DE", grade: 50}, city: "DE", health: 0, limit: null, lines: [{active: true, bonus: "DE", exposure: true, ok: [0.5], price: 0, total: null, totals: {level: null}, verified: true}], price: 50, rate: 0.5, risk: 50, segment: "DE", urgent: false, weighted: ["DE"]}, points: true, scores: {capped: true}}], + [{baseRate: 100, order: {rate: 99999999999999999999, limit: 0, price: 10, city: "a", birthDate: "2000-01-01", urgent: false, lines: [{price: 2, active: false, verified: true}, {price: 1000, active: false, verified: false}]}}, {baseRate: 100, decision: [100, 1], flags: {eligible: "a"}, margin: [0, 99999999999999999999], net: ["a", "a"], order: {band: 10, birthDate: "2000-01-01", calc: {bucket: "a", grade: 10}, city: "a", health: 2, limit: 0, lines: [{active: false, bonus: "a", exposure: false, ok: [99999999999999999999], price: 2, tag: false, total: null, totals: {level: null}, verified: true}, {active: false, bonus: "a", exposure: false, ok: [99999999999999999999], price: 1000, tag: false, total: null, totals: {level: null}, verified: false}], price: 10, rate: 99999999999999999999, risk: 10, segment: "a", urgent: false, weighted: ["a"]}, points: true, scores: {capped: true}, surcharge: -10000}], + [{baseRate: -2, order: {rate: 0.5, limit: 0.5, price: 0.5, city: "low", birthDate: "2000-01-01", urgent: null, lines: [{price: 99999999999999999999, active: false, verified: true}, {price: 18, verified: true}]}}, {baseRate: -2, decision: [-2], flags: {eligible: "low"}, margin: [0.5], net: ["low"], order: {band: 0.5, birthDate: "2000-01-01", calc: {bucket: "low", grade: 0.5}, city: "low", health: 2, limit: 0.5, lines: [{active: false, bonus: "low", exposure: false, ok: [0.5], price: 99999999999999999999, total: null, totals: {level: null}, verified: true}, {bonus: "low", exposure: false, ok: [0.5], price: 18, total: null, totals: {level: null}, verified: true}], price: 0.5, rate: 0.5, risk: 0.5, segment: "low", urgent: null, weighted: ["low"]}, points: true, scores: {capped: true}, surcharge: -4}], + [{baseRate: -2, order: {rate: 50, limit: 1, price: 5, city: "US", birthDate: "2024-02-29", urgent: false, lines: [{price: 250, active: true, verified: false}, {price: -1, active: true, verified: true}, {price: 50, active: false, verified: false}, {price: 1000, active: true, verified: false}], extraField: {nested: true}}}, {baseRate: -2, decision: [-2, -2, 2], flags: {eligible: "US"}, margin: [-50, 1, 50], net: ["false/50", "US", "a"], order: {band: 5, birthDate: "2024-02-29", calc: {bucket: "US", grade: 5}, city: "US", extraField: {nested: true}, health: 3, limit: 1, lines: [{active: true, bonus: "US", exposure: false, ok: [50], price: 250, tag: true, total: null, totals: {level: null}, verified: false}, {active: true, bonus: "US", exposure: true, ok: [50], price: -1, tag: false, total: null, totals: {level: null}, verified: true}, {active: false, bonus: "US", exposure: false, ok: [50], price: 50, tag: false, total: null, totals: {level: null}, verified: false}, {active: true, bonus: "US", exposure: false, ok: [50], price: 1000, tag: true, total: null, totals: {level: null}, verified: false}], price: 5, rate: 50, risk: 5, segment: "US", urgent: false, weighted: ["US"]}, points: true, scores: {capped: true}}], + [{baseRate: 0.5, order: {rate: -500, limit: 0, price: 5, city: "VIP", birthDate: "1990-06-15", urgent: false, lines: [{price: 1000000, active: true, verified: true}], extraField: {nested: true}}}, {baseRate: 0.5, decision: [0.5], flags: {eligible: "VIP"}, margin: [0], net: ["VIP"], order: {band: 5, birthDate: "1990-06-15", calc: {bucket: "VIP", grade: 5}, city: "VIP", extraField: {nested: true}, health: 1, limit: 0, lines: [{active: true, bonus: "VIP", exposure: true, ok: [-500], price: 1000000, total: null, totals: {level: null}, verified: true}], price: 5, rate: -500, risk: 5, segment: "VIP", urgent: false, weighted: ["VIP"]}, points: true, scores: {capped: true}}], + [{baseRate: 1, order: {rate: 50, price: 7.25, city: "abc", birthDate: "2024-02-29", urgent: true, lines: [{price: 100, active: false, verified: true}, {price: 5, active: null, verified: true}, {price: -500, active: false, verified: false}, {price: 1000000, verified: true}]}}, {baseRate: 1, decision: [1], flags: {eligible: "abc"}, margin: [0], net: ["abc"], order: {band: 7.25, birthDate: "2024-02-29", calc: {bucket: "abc", grade: 7.25}, city: "abc", health: 3, lines: [{active: false, bonus: "abc", exposure: false, ok: [50], price: 100, tag: false, total: null, totals: {level: null}, verified: true}, {active: null, bonus: "abc", exposure: false, ok: [50], price: 5, tag: false, total: null, totals: {level: null}, verified: true}, {active: false, bonus: "abc", exposure: false, ok: [50], price: -500, tag: false, total: null, totals: {level: null}, verified: false}, {bonus: "abc", exposure: false, ok: [50], price: 1000000, tag: false, total: null, totals: {level: null}, verified: true}], price: 7.25, rate: 50, risk: 7.25, segment: "abc", urgent: true, weighted: ["abc"]}, points: false, scores: {capped: false}, surcharge: 0}], + [{baseRate: 0, order: {rate: 1000000, limit: 18, price: 68, city: "12", birthDate: "2024-02-29", urgent: false, lines: [{price: 0.5, active: false, verified: false}]}}, {baseRate: 0, decision: [0], flags: {eligible: "12"}, margin: [18], net: ["12"], order: {band: 68, birthDate: "2024-02-29", calc: {bucket: "12", grade: 68}, city: "12", health: 1, limit: 18, lines: [{active: false, bonus: "12", exposure: false, ok: [1000000], price: 0.5, tag: false, total: null, totals: {level: null}, verified: false}], price: 68, rate: 1000000, risk: 68, segment: "12", urgent: false, weighted: ["12"]}, points: false, scores: {capped: false}, surcharge: 18}], + ], +} + +// seed 345500 (attempt 0) +{ + name: "b 56: claim/loans/drivers: 4 expression, 5 match, 3 table; 5 root, 9 per-member, 2 top-level computed", + policy: { + models: {claim: {income: "number", kind: "string(retail|corporate)?", verified: "boolean", dueDate: "date", loans: "loan[]"}, loan: {balance: "number", sku: "string", drivers: "driver[]"}, driver: {limit: "number", status: "string(open|closed|pending)?", country: "string"}}, + blocks: [ + {match: "loan.fee", arms: [["contains(['A1', 'a', ''], loan.sku)", "string(claim.verified)"], ["loan.balance <= (loan.share ?? 0)", "loan.adjusted"], ["", "claim.dueDate.format('%d')"]]}, + {expression: "decision", value: "map(claim.loans, (#.balance % (abs(#.balance) + 1)))"}, + {expression: "claim.points", value: "{v: claim.verified, ok: claim.income in [39..116]}"}, + {match: "loan.adjusted", arms: [["claim.dueDate.isSameOrBefore(d('2025-03-20'), 'month')", "loan.flags.bucket"], ["(claim.kind ?? '') == 'retail'", "loan.sku"], ["all(loan.drivers, isNumeric(#.country))", "(net + '-' + net)"], ["none(loan.drivers, (#.limit == 2 and #.limit == 18))", "net"], ["", "net"]]}, + {expression: "claim.penalty", value: "claim.dueDate.isSame(d('2025-03-20'), 'year')"}, + {table: "t8", inputs: ["max([(loan.surcharge ?? 0), claim.income, (loan.surcharge ?? 0)])", "loan.sku"], outputs: ["loan.rank", "loan.segment"], rules: [ + ["!= 250", "startsWith($, 'gold')", "(loan.surcharge ?? 0)", "loan.flags.quota"], + ["1, 1.5", "$ != 'VIP'", "claim.income", "claim.points.v"], + ]}, + {table: "t3", inputs: [null, "count(loan.drivers, isNumeric(#.country))"], outputs: ["loan.surcharge"], rules: [ + ["isNumeric(loan.sku)", "!= 250", "(claim.verified ? loan.balance : loan.balance)"], + ["", "", "len(loan.sku)"], + ]}, + {expression: "claim.review", value: "net in ['Oslo', 'a']"}, + {match: "net", arms: [["(claim.kind ?? '') != 'corporate'", "string(claim.income)"], ["claim.verified", "'US'"], ["(claim.income <= claim.income and some(claim.loans, matches(#.sku, 'a')))", "claim.dueDate.format('%d')"], ["claim.income < 0.5", "'A1'"], ["", "string(claim.income)"]]}, + {table: "t10", inputs: ["loan.balance", "loan.flags.bucket"], outputs: ["loan.share", "loan.bonus"], rules: [ + ["!= 50", "'low', 'low'", "sum(decision)", "3"], + ["[5..133]", "", "18", "loan.balance"], + [">= 10", "'A1', 'gold'", "loan.balance", "(loan.surcharge ?? 0)"], + ["", "", "", "claim.income"], + ]}, + {match: "loan.flags.quota", arms: [["not (claim.verified)", "matches(loan.sku, '^.{2,}$')"], ["loan.surcharge == null", "claim.kind == null"], ["", "claim.dueDate.isAfter(d('2025-03-20'), 'month')"]]}, + {match: "loan.flags.bucket", arms: [["((loan.surcharge ?? 0) / -6) == claim.income", "(claim.dueDate < d('2024-01-01') ? (split(loan.sku, '-')[0] ?? 'none') : string(loan.flags.quota))"], ["(claim.penalty and loan.flags.quota)", "string(claim.penalty)"], ["none(loan.drivers, isNumeric(#.country))", "(loan.sku + '-' + net)"], ["", "'US'"]]}, + ], + }, + cases: [ + [{claim: {income: 99.99, kind: "retail", verified: false, dueDate: "2000-01-01", loans: []}}, {claim: {dueDate: "2000-01-01", income: 99.99, kind: "retail", loans: [], penalty: false, review: false, verified: false}, net: "99.99"}], + [{claim: {income: 65, kind: "retail", verified: true, dueDate: "2025-03-20", loans: [{balance: 7.25, sku: "ok", drivers: [{limit: 0.5, status: "open", country: "US"}, {limit: 1.5, status: "open", country: "US"}, {limit: 1.5, status: "open", country: "gold"}]}, {balance: 18, sku: "VIP", drivers: []}, {balance: 50, sku: "VIP", drivers: [{limit: 1000, status: "open", country: "3.5"}, {limit: -1, status: "open", country: "-"}]}]}}, {claim: {dueDate: "2025-03-20", income: 65, kind: "retail", loans: [{adjusted: "ok-65", balance: 7.25, bonus: 7.25, drivers: [{country: "US", limit: 0.5, status: "open"}, {country: "US", limit: 1.5, status: "open"}, {country: "gold", limit: 1.5, status: "open"}], fee: "ok-65", flags: {bucket: "ok-65", quota: false}, rank: null, segment: null, share: 18, sku: "ok", surcharge: 2}, {adjusted: "VIP-65", balance: 18, bonus: 18, drivers: [], fee: "VIP-65", flags: {bucket: "VIP-65", quota: false}, rank: null, segment: null, share: 18, sku: "VIP", surcharge: 3}, {adjusted: "US", balance: 50, bonus: 50, drivers: [{country: "3.5", limit: 1000, status: "open"}, {country: "-", limit: -1, status: "open"}], fee: "20", flags: {bucket: "US", quota: false}, rank: null, segment: null, share: 18, sku: "VIP", surcharge: 3}], penalty: true, review: false, verified: true}, net: "65"}], + [{claim: {income: 0, kind: "retail", verified: true, dueDate: "2030-12-31", loans: [{balance: 0.1, sku: "none", drivers: [{limit: 1.5, status: "closed", country: "gold"}, {limit: 18, status: "open", country: "a"}]}, {balance: 262, sku: "gold", drivers: [{limit: 2, status: "closed", country: "ok"}, {limit: 1000, status: "pending", country: "3.5"}]}, {balance: -1, sku: "", drivers: [{limit: 250, status: "open", country: "gold"}, {limit: 99.99, status: "closed", country: "a"}]}, {balance: 1000000, sku: "Oslo", drivers: [{limit: -0.01, status: "pending", country: "12"}, {limit: 1.5, status: "pending", country: "ok"}, {limit: 1, status: "pending", country: "gold"}]}, {balance: 50, sku: " pad ", drivers: [{limit: -0.5, status: "open", country: "日本"}, {limit: -500, status: "closed", country: "ok"}]}]}}, {claim: {dueDate: "2030-12-31", income: 0, kind: "retail", loans: [{balance: 0.1, bonus: 0, drivers: [{country: "gold", limit: 1.5, status: "closed"}, {country: "a", limit: 18, status: "open"}], fee: "31", flags: {bucket: "none-0", quota: true}, rank: null, segment: null, share: null, sku: "none", surcharge: 4}, {balance: 262, bonus: 0, drivers: [{country: "ok", limit: 2, status: "closed"}, {country: "3.5", limit: 1000, status: "pending"}], fee: "31", flags: {bucket: "US", quota: true}, rank: 4, segment: true, share: null, sku: "gold", surcharge: 4}, {balance: -1, bonus: 0, drivers: [{country: "gold", limit: 250, status: "open"}, {country: "a", limit: 99.99, status: "closed"}], fee: "true", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "", surcharge: 0}, {balance: 1000000, bonus: 0, drivers: [{country: "12", limit: -0.01, status: "pending"}, {country: "ok", limit: 1.5, status: "pending"}, {country: "gold", limit: 1, status: "pending"}], fee: "31", flags: {bucket: "US", quota: true}, rank: null, segment: null, share: null, sku: "Oslo", surcharge: 4}, {balance: 50, bonus: 50, drivers: [{country: "日本", limit: -0.5, status: "open"}, {country: "ok", limit: -500, status: "closed"}], fee: "31", flags: {bucket: " pad -0", quota: true}, rank: null, segment: null, share: 18, sku: " pad ", surcharge: 6}], penalty: false, review: false, verified: true}, net: "0"}], + [{claim: {income: 1, kind: "corporate", verified: true, dueDate: "2000-01-01", loans: [{balance: 2.50, sku: "a", drivers: [{limit: 250, status: "pending", country: "low"}, {limit: 50, country: "none"}, {limit: 0.5, country: "Zed"}]}, {balance: -0, sku: "gold", drivers: [{limit: 250, status: "closed", country: "é ü"}]}, {balance: 2, sku: "Oslo", drivers: [{limit: 2, country: "Oslo"}, {limit: 0.5, country: "DE"}]}]}}, {claim: {dueDate: "2000-01-01", income: 1, kind: "corporate", loans: [{adjusted: "a-US", balance: 2.50, bonus: 1, drivers: [{country: "low", limit: 250, status: "pending"}, {country: "none", limit: 50}, {country: "Zed", limit: 0.5}], fee: "true", flags: {bucket: "a-US", quota: false}, rank: 1, segment: true, share: null, sku: "a", surcharge: 1}, {adjusted: "gold-US", balance: 0, bonus: 1, drivers: [{country: "é ü", limit: 250, status: "closed"}], fee: "gold-US", flags: {bucket: "gold-US", quota: false}, rank: 4, segment: false, share: null, sku: "gold", surcharge: 4}, {adjusted: "Oslo-US", balance: 2, bonus: 1, drivers: [{country: "Oslo", limit: 2}, {country: "DE", limit: 0.5}], fee: "01", flags: {bucket: "Oslo-US", quota: false}, rank: null, segment: null, share: null, sku: "Oslo", surcharge: 4}], penalty: false, points: {ok: false, v: true}, review: false, verified: true}, net: "US"}], + [{claim: {income: 250, kind: null, verified: false, dueDate: "2025-03-20", loans: [{balance: 1000000, sku: "", drivers: [{limit: 207, status: "open", country: "gold"}, {limit: 1e3, status: "open", country: "low"}]}, {balance: 1000, sku: "VIP", drivers: [{limit: 1000, status: "pending", country: "A1"}, {limit: 50, status: "closed", country: "gold"}]}, {balance: 476, sku: "none", drivers: [{limit: 2, status: "open", country: "low"}, {limit: 250, country: "gold"}, {limit: 50, status: "open", country: "ok"}]}, {balance: 1.5, sku: "VIP", drivers: [{limit: 2, country: "ok"}, {limit: -0.01, status: null, country: "Zed"}]}, {balance: 0, sku: "gold", drivers: []}, {balance: 1000, sku: "A1", drivers: [{limit: 2, status: null, country: "gold"}, {limit: 18, status: null, country: "DE"}]}, {balance: 0.5, sku: "US", drivers: [{limit: 0.000001, status: null, country: "12"}, {limit: 1.5, status: "open", country: "Zed"}]}, {balance: 2.50, sku: "A1", drivers: [{limit: 125, status: null, country: "gold"}, {limit: 2, status: "open", country: "-"}, {limit: 100, country: "A1"}]}, {balance: 0.1, sku: "gold", drivers: [{limit: 100, country: "low"}, {limit: 1000, country: "x"}]}, {balance: -1, sku: "low", drivers: [{limit: 2.50, country: "low"}, {limit: 1, status: null, country: "A1"}]}, {balance: 18, sku: "a", drivers: [{limit: 1.5, country: "3.5"}, {limit: 1, status: "open", country: "none"}, {limit: 2, country: "none"}]}]}}, {claim: {dueDate: "2025-03-20", income: 250, kind: null, loans: [{adjusted: "-250", balance: 1000000, bonus: 250, drivers: [{country: "gold", limit: 207, status: "open"}, {country: "low", limit: 1000, status: "open"}], fee: "false", flags: {bucket: "-250", quota: false}, rank: null, segment: null, share: null, sku: "", surcharge: 0}, {adjusted: "true", balance: 1000, bonus: 250, drivers: [{country: "A1", limit: 1000, status: "pending"}, {country: "gold", limit: 50, status: "closed"}], fee: "20", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "VIP", surcharge: 3}, {adjusted: "true", balance: 476, bonus: 250, drivers: [{country: "low", limit: 2, status: "open"}, {country: "gold", limit: 250}, {country: "ok", limit: 50, status: "open"}], fee: "20", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "none", surcharge: 4}, {adjusted: "true", balance: 1.5, bonus: 250, drivers: [{country: "ok", limit: 2}, {country: "Zed", limit: -0.01, status: null}], fee: "20", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "VIP", surcharge: 3}, {adjusted: "true", balance: 0, bonus: 250, drivers: [], fee: "true", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "gold", surcharge: 4}, {adjusted: "true", balance: 1000, bonus: 250, drivers: [{country: "gold", limit: 2, status: null}, {country: "DE", limit: 18, status: null}], fee: "false", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "A1", surcharge: 2}, {adjusted: "true", balance: 0.5, bonus: 250, drivers: [{country: "12", limit: 0.000001, status: null}, {country: "Zed", limit: 1.5, status: "open"}], fee: "20", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "US", surcharge: 2}, {adjusted: "true", balance: 2.50, bonus: 250, drivers: [{country: "gold", limit: 125, status: null}, {country: "-", limit: 2, status: "open"}, {country: "A1", limit: 100}], fee: "false", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "A1", surcharge: 2}, {adjusted: "true", balance: 0.1, bonus: 250, drivers: [{country: "low", limit: 100}, {country: "x", limit: 1000}], fee: "20", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "gold", surcharge: 4}, {adjusted: "true", balance: -1, bonus: 250, drivers: [{country: "low", limit: 2.50}, {country: "A1", limit: 1, status: null}], fee: "true", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "low", surcharge: 3}, {adjusted: "US", balance: 18, bonus: 18, drivers: [{country: "3.5", limit: 1.5}, {country: "none", limit: 1, status: "open"}, {country: "none", limit: 2}], fee: "false", flags: {bucket: "US", quota: false}, rank: null, segment: null, share: 18, sku: "a", surcharge: 1}], penalty: true, review: false, verified: false}, net: "250"}], + [{claim: {income: 1, kind: "retail", verified: true, dueDate: "2025-03-20T10:15:30Z", loans: [{balance: 2, sku: "high", drivers: []}, {balance: 2, sku: "gold", drivers: [{limit: 250, status: "open", country: "ok"}, {limit: 50, status: "pending", country: "gold"}]}]}}, {claim: {dueDate: "2025-03-20T10:15:30Z", income: 1, kind: "retail", loans: [{balance: 2, bonus: 1, drivers: [], fee: "20", flags: {bucket: "high-1", quota: false}, rank: null, segment: null, share: null, sku: "high", surcharge: 4}, {balance: 2, bonus: 1, drivers: [{country: "ok", limit: 250, status: "open"}, {country: "gold", limit: 50, status: "pending"}], fee: "20", flags: {bucket: "gold-1", quota: false}, rank: 4, segment: false, share: null, sku: "gold", surcharge: 4}], penalty: true, review: false, verified: true}, net: "1"}], + [{claim: {income: 1000, kind: "retail", verified: true, dueDate: "2024-02-29", loans: [{balance: 0, sku: "日本", drivers: [{limit: 99999999999999999999, status: "pending", country: "VIP"}, {limit: 2, status: "open", country: "gold"}, {limit: 50, status: "open", country: "ok"}]}, {balance: 0, sku: "x-y", drivers: []}, {balance: -0.5, sku: "Zed", drivers: [{limit: 3, status: "pending", country: "a"}, {limit: 99999999999999999999, status: "open", country: "Oslo"}]}, {balance: 99.99, sku: "abc", drivers: [{limit: 1.5, status: "closed", country: "A1"}, {limit: 0.000001, status: "open", country: "12"}]}]}}, {claim: {dueDate: "2024-02-29", income: 1000, kind: "retail", loans: [{adjusted: "日本-1000", balance: 0, bonus: 1000, drivers: [{country: "VIP", limit: 99999999999999999999, status: "pending"}, {country: "gold", limit: 2, status: "open"}, {country: "ok", limit: 50, status: "open"}], fee: "日本-1000", flags: {bucket: "日本-1000", quota: false}, rank: null, segment: null, share: null, sku: "日本", surcharge: 6}, {adjusted: "x-y-1000", balance: 0, bonus: 1000, drivers: [], fee: "x-y-1000", flags: {bucket: "x-y-1000", quota: false}, rank: null, segment: null, share: null, sku: "x-y", surcharge: 3}, {adjusted: "Zed-1000", balance: -0.5, bonus: 1000, drivers: [{country: "a", limit: 3, status: "pending"}, {country: "Oslo", limit: 99999999999999999999, status: "open"}], fee: "Zed-1000", flags: {bucket: "Zed-1000", quota: false}, rank: null, segment: null, share: null, sku: "Zed", surcharge: 3}, {adjusted: "US", balance: 99.99, bonus: 99.99, drivers: [{country: "A1", limit: 1.5, status: "closed"}, {country: "12", limit: 0.000001, status: "open"}], fee: "29", flags: {bucket: "US", quota: false}, rank: null, segment: null, share: 18, sku: "abc", surcharge: 3}], penalty: false, review: false, verified: true}, net: "1000"}], + [{claim: {income: 1, kind: "corporate", verified: false, dueDate: "2025-03-20", loans: [{balance: 1000, sku: "", drivers: [{limit: 3, status: "closed", country: "VIP"}, {limit: 99999999999999999999, status: "closed", country: "é ü"}]}]}}, {claim: {dueDate: "2025-03-20", income: 1, kind: "corporate", loans: [{balance: 1000, bonus: 1, drivers: [{country: "VIP", limit: 3, status: "closed"}, {country: "é ü", limit: 99999999999999999999, status: "closed"}], fee: "false", flags: {bucket: "-1", quota: false}, rank: 1, segment: false, share: null, sku: "", surcharge: 0}], penalty: true, points: {ok: false, v: false}, review: false, verified: false}, net: "1"}], + [{claim: {income: 18, kind: "corporate", verified: false, dueDate: "2000-01-01", loans: [{balance: -0, sku: "US", drivers: [{limit: 250, status: "pending", country: "O'Neil"}, {limit: 50, status: "pending", country: "a"}, {limit: 50, status: null, country: "gold"}]}, {balance: 50, sku: "A1", drivers: [{limit: -0.5, country: "ok"}, {limit: 1e3, status: null, country: "high"}, {limit: 10, status: null, country: "none"}]}]}}, {claim: {dueDate: "2000-01-01", income: 18, kind: "corporate", loans: [{adjusted: "US-18", balance: 0, bonus: 18, drivers: [{country: "O'Neil", limit: 250, status: "pending"}, {country: "a", limit: 50, status: "pending"}, {country: "gold", limit: 50, status: null}], fee: "US-18", flags: {bucket: "US-18", quota: true}, rank: null, segment: null, share: null, sku: "US", surcharge: 2}, {adjusted: "A1-18", balance: 50, bonus: 50, drivers: [{country: "ok", limit: -0.5}, {country: "high", limit: 1000, status: null}, {country: "none", limit: 10, status: null}], fee: "false", flags: {bucket: "A1-18", quota: true}, rank: null, segment: null, share: 18, sku: "A1", surcharge: 2}], penalty: false, review: false, verified: false}, net: "18"}], + [{claim: {income: 1, kind: "retail", verified: false, dueDate: "2025-03-20", loans: [{balance: -0.01, sku: "ok", drivers: [{limit: 18, country: "low"}, {limit: 1, country: "a"}, {limit: 100, status: "open", country: "none"}]}, {balance: 0.5, sku: "gold", drivers: [{limit: 1, status: "pending", country: "a-b-c"}, {limit: 3, country: "a"}, {limit: 0.5, status: null, country: "ok"}]}, {balance: 5, sku: "A1", drivers: [{limit: 250, country: "US"}, {limit: -0.01, status: null, country: "none"}]}, {balance: 0, sku: "VIP", drivers: [{limit: 1, country: "A1"}]}]}}, {claim: {dueDate: "2025-03-20", income: 1, kind: "retail", loans: [{adjusted: "true", balance: -0.01, bonus: 1, drivers: [{country: "low", limit: 18}, {country: "a", limit: 1}, {country: "none", limit: 100, status: "open"}], fee: "true", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "ok", surcharge: 2}, {adjusted: "true", balance: 0.5, bonus: 1, drivers: [{country: "a-b-c", limit: 1, status: "pending"}, {country: "a", limit: 3}, {country: "ok", limit: 0.5, status: null}], fee: "20", flags: {bucket: "true", quota: true}, rank: 4, segment: true, share: null, sku: "gold", surcharge: 4}, {adjusted: "true", balance: 5, bonus: 5, drivers: [{country: "US", limit: 250}, {country: "none", limit: -0.01, status: null}], fee: "false", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: 18, sku: "A1", surcharge: 2}, {adjusted: "true", balance: 0, bonus: 1, drivers: [{country: "A1", limit: 1}], fee: "true", flags: {bucket: "true", quota: true}, rank: null, segment: null, share: null, sku: "VIP", surcharge: 3}], penalty: true, review: false, verified: false}, net: "1"}], + [{claim: {income: 250, kind: "corporate", verified: true, dueDate: "2030-12-31", loans: []}}, {claim: {dueDate: "2030-12-31", income: 250, kind: "corporate", loans: [], penalty: false, review: false, verified: true}, net: "US"}], + [{claim: {income: -0, kind: "corporate", verified: false, dueDate: "1990-06-15", loans: []}}, {claim: {dueDate: "1990-06-15", income: 0, kind: "corporate", loans: [], penalty: false, review: false, verified: false}, net: "A1"}], + [{claim: {income: 3, kind: "retail", verified: true, dueDate: "2025-03-20T10:15:30Z", loans: [{balance: 99.99, sku: "12", drivers: [{limit: 7.25, status: "closed", country: "VIP"}, {limit: 0.5, status: "open", country: "gold"}, {limit: -0, status: "pending", country: "A1"}]}, {balance: 0.5, sku: " pad ", drivers: [{limit: -0.5, status: "open", country: "VIP"}]}]}}, {claim: {dueDate: "2025-03-20T10:15:30Z", income: 3, kind: "retail", loans: [{balance: 99.99, bonus: 99.99, drivers: [{country: "VIP", limit: 7.25, status: "closed"}, {country: "gold", limit: 0.5, status: "open"}, {country: "A1", limit: 0, status: "pending"}], fee: "20", flags: {bucket: "12-3", quota: false}, rank: null, segment: null, share: 18, sku: "12", surcharge: 99.99}, {balance: 0.5, bonus: 3, drivers: [{country: "VIP", limit: -0.5, status: "open"}], fee: "20", flags: {bucket: " pad -3", quota: false}, rank: null, segment: null, share: null, sku: " pad ", surcharge: 6}], penalty: true, review: false, verified: true}, net: "3"}], + [{claim: {income: 1, verified: false, dueDate: "2000-01-01", loans: [{balance: 7.25, sku: "a", drivers: [{limit: 1000, status: "closed", country: "US"}]}, {balance: 2, sku: "gold", drivers: []}, {balance: 1, sku: "ok", drivers: []}, {balance: 1.5, sku: "US", drivers: [{limit: 18, status: null, country: "ok"}, {limit: 2, country: "VIP"}]}]}}, {claim: {dueDate: "2000-01-01", income: 1, loans: [{balance: 7.25, bonus: 7.25, drivers: [{country: "US", limit: 1000, status: "closed"}], fee: "false", flags: {bucket: "a-1", quota: false}, rank: 1, segment: false, share: 18, sku: "a", surcharge: 1}, {balance: 2, bonus: 1, drivers: [], fee: "01", flags: {bucket: "gold-1", quota: true}, rank: 4, segment: true, share: null, sku: "gold", surcharge: 4}, {balance: 1, bonus: 1, drivers: [], fee: "01", flags: {bucket: "ok-1", quota: true}, rank: null, segment: null, share: null, sku: "ok", surcharge: 2}, {balance: 1.5, bonus: 1, drivers: [{country: "ok", limit: 18, status: null}, {country: "VIP", limit: 2}], fee: "01", flags: {bucket: "US-1", quota: true}, rank: null, segment: null, share: null, sku: "US", surcharge: 2}], penalty: false, points: {ok: false, v: false}, review: false, verified: false}, net: "1"}], + [{claim: {income: 18, kind: "retail", verified: true, dueDate: "2025-03-20T10:15:30Z", loans: []}}, {claim: {dueDate: "2025-03-20T10:15:30Z", income: 18, kind: "retail", loans: [], penalty: true, review: false, verified: true}, net: "18"}], + [{claim: {income: 3, kind: "retail", verified: true, dueDate: "2025-03-20", loans: [{balance: 2, sku: "DE", drivers: [{limit: 1, status: "pending", country: "gold"}, {limit: 18, status: "open", country: "a"}, {limit: 0.5, country: "ok"}]}, {balance: 2, sku: "A1", drivers: [{limit: 50, country: "-"}, {limit: 18, status: "open", country: "none"}]}]}}, {claim: {dueDate: "2025-03-20", income: 3, kind: "retail", loans: [{balance: 2, bonus: 3, drivers: [{country: "gold", limit: 1, status: "pending"}, {country: "a", limit: 18, status: "open"}, {country: "ok", limit: 0.5}], fee: "20", flags: {bucket: "DE-3", quota: false}, rank: null, segment: null, share: null, sku: "DE", surcharge: 2}, {balance: 2, bonus: 3, drivers: [{country: "-", limit: 50}, {country: "none", limit: 18, status: "open"}], fee: "true", flags: {bucket: "A1-3", quota: false}, rank: null, segment: null, share: null, sku: "A1", surcharge: 2}], penalty: true, review: false, verified: true}, net: "3"}], + [{claim: {income: 1.5, kind: "retail", verified: false, dueDate: "2030-12-31", loans: [{balance: 18, sku: "low", drivers: [{limit: 0.000001, status: "open", country: "3.5"}, {limit: 1, status: "open", country: "a-b-c"}]}]}}, {claim: {dueDate: "2030-12-31", income: 1.5, kind: "retail", loans: [{adjusted: "low", balance: 18, bonus: 18, drivers: [{country: "3.5", limit: 0.000001, status: "open"}, {country: "a-b-c", limit: 1, status: "open"}], fee: "low", flags: {bucket: "US", quota: true}, rank: null, segment: null, share: 18, sku: "low", surcharge: 3}], penalty: false, review: false, verified: false}, net: "1.5"}], + [{claim: {income: 7.25, kind: "retail", verified: false, dueDate: "1990-06-15", loans: [{balance: 0.5, sku: "A1", drivers: [{limit: 1, status: "open", country: "abc"}, {limit: 18, status: "closed", country: "Oslo"}, {limit: 2, status: "open", country: "a"}]}]}}, {claim: {dueDate: "1990-06-15", income: 7.25, kind: "retail", loans: [{balance: 0.5, bonus: 7.25, drivers: [{country: "abc", limit: 1, status: "open"}, {country: "Oslo", limit: 18, status: "closed"}, {country: "a", limit: 2, status: "open"}], fee: "false", flags: {bucket: "A1-7.25", quota: true}, rank: null, segment: null, share: null, sku: "A1", surcharge: 2}], penalty: false, review: false, verified: false}, net: "7.25"}], + [{claim: {income: 0.5, kind: false, verified: true, dueDate: "2025-03-20T10:15:30Z", loans: [{balance: -1, sku: "a", drivers: [{limit: 2.50, status: "closed", country: "x-y"}]}, {balance: 99999999999999999999, sku: "high", drivers: [{limit: 149, status: "pending", country: "none"}, {limit: 0.000001, status: "open", country: " pad "}]}, {balance: 18, sku: "gold", drivers: [{limit: 2, status: "pending", country: "NL"}, {limit: 279, status: "open", country: "x-y"}]}]}}, "!error: InputValidationFailed"], + [{claim: {income: 2, kind: "corporate", verified: true, dueDate: "2030-12-31", loans: []}}, {claim: {dueDate: "2030-12-31", income: 2, kind: "corporate", loans: [], penalty: false, review: false, verified: true}, net: "US"}], + [{claim: {income: 50, verified: true, dueDate: "2024-01-01", loans: [{balance: 18, sku: "a-b-c", drivers: [{limit: 2, status: "open", country: "high"}]}]}}, {claim: {dueDate: "2024-01-01", income: 50, loans: [{adjusted: "a-b-c-50", balance: 18, bonus: 18, drivers: [{country: "high", limit: 2, status: "open"}], fee: "a-b-c-50", flags: {bucket: "a-b-c-50", quota: false}, rank: null, segment: null, share: 18, sku: "a-b-c", surcharge: 5}], penalty: false, review: false, verified: true}, net: "50"}], + [{claim: {income: 2, kind: "retail", verified: true, dueDate: "2025-03-20T10:15:30Z", loans: [{balance: 250, sku: "VIP", drivers: [{limit: 250, status: "open", country: "Oslo"}, {limit: 10, status: "closed", country: "12"}, {limit: -500, status: "open", country: "x"}]}, {balance: -500, sku: "gold", drivers: []}, {balance: 2, sku: "ok", drivers: [{limit: 2, status: "open", country: "a"}, {limit: 0, status: "pending", country: "none"}, {limit: 50, status: "open", country: "a-b-c"}]}], extraField: "x"}}, {claim: {dueDate: "2025-03-20T10:15:30Z", extraField: "x", income: 2, kind: "retail", loans: [{adjusted: "US", balance: 250, bonus: 2, drivers: [{country: "Oslo", limit: 250, status: "open"}, {country: "12", limit: 10, status: "closed"}, {country: "x", limit: -500, status: "open"}], fee: "20", flags: {bucket: "US", quota: false}, rank: null, segment: null, share: null, sku: "VIP", surcharge: 3}, {adjusted: "gold-2", balance: -500, bonus: 2, drivers: [], fee: "gold-2", flags: {bucket: "gold-2", quota: false}, rank: 4, segment: false, share: null, sku: "gold", surcharge: 4}, {adjusted: "ok-2", balance: 2, bonus: 2, drivers: [{country: "a", limit: 2, status: "open"}, {country: "none", limit: 0, status: "pending"}, {country: "a-b-c", limit: 50, status: "open"}], fee: "20", flags: {bucket: "ok-2", quota: false}, rank: null, segment: null, share: null, sku: "ok", surcharge: 2}], penalty: true, review: false, verified: true}, net: "2"}], + [{claim: {income: 18, kind: null, verified: false, dueDate: "2030-12-31", loans: [{balance: 1.5, sku: "low", drivers: []}]}}, {claim: {dueDate: "2030-12-31", income: 18, kind: null, loans: [{balance: 1.5, bonus: 18, drivers: [], fee: "31", flags: {bucket: "low-18", quota: true}, rank: null, segment: null, share: null, sku: "low", surcharge: 3}], penalty: false, review: false, verified: false}, net: "18"}], + [{claim: {income: 0.000001, verified: false, dueDate: "2030-12-31", loans: [{balance: 2, sku: "US", drivers: [{limit: -0, status: "open", country: "Zed"}, {limit: 1.5, status: "pending", country: "x-y"}]}, {balance: 50, sku: "US", drivers: [{limit: 3, status: "open", country: "gold"}, {limit: 1, status: null, country: "US"}]}, {balance: -1, sku: "A1", drivers: [{limit: 2, country: "a"}, {limit: 18, country: "none"}, {limit: 1000, country: "high"}]}, {balance: 250, sku: "gold", drivers: [{limit: 1.5, country: "-"}, {limit: 2, country: "none"}]}]}}, {claim: {dueDate: "2030-12-31", income: 0.000001, loans: [{balance: 2, bonus: 0.000001, drivers: [{country: "Zed", limit: 0, status: "open"}, {country: "x-y", limit: 1.5, status: "pending"}], fee: "31", flags: {bucket: "US-0.000001", quota: true}, rank: null, segment: null, share: null, sku: "US", surcharge: 2}, {balance: 50, bonus: 50, drivers: [{country: "gold", limit: 3, status: "open"}, {country: "US", limit: 1, status: null}], fee: "31", flags: {bucket: "US-0.000001", quota: true}, rank: null, segment: null, share: 18, sku: "US", surcharge: 2}, {balance: -1, bonus: 0.000001, drivers: [{country: "a", limit: 2}, {country: "none", limit: 18}, {country: "high", limit: 1000}], fee: "false", flags: {bucket: "A1-0.000001", quota: true}, rank: null, segment: null, share: null, sku: "A1", surcharge: 2}, {balance: 250, bonus: 0.000001, drivers: [{country: "-", limit: 1.5}, {country: "none", limit: 2}], fee: "31", flags: {bucket: "gold-0.000001", quota: true}, rank: 4, segment: true, share: null, sku: "gold", surcharge: 4}], penalty: false, review: false, verified: false}, net: "0.000001"}], + [{claim: {income: 7.25, kind: null, verified: true, dueDate: "2030-12-31", loans: [{balance: 1e3, sku: "gold", drivers: [{limit: 2, status: null, country: "A1"}, {limit: 2, country: "DE"}]}, {balance: 1000, sku: "low", drivers: [{limit: 65, status: "open", country: "gold"}, {limit: 99999999999999999999, country: "gold"}, {limit: 65, status: "open", country: ""}]}]}}, {claim: {dueDate: "2030-12-31", income: 7.25, kind: null, loans: [{balance: 1000, bonus: 7.25, drivers: [{country: "A1", limit: 2, status: null}, {country: "DE", limit: 2}], fee: "31", flags: {bucket: "gold-7.25", quota: true}, rank: 4, segment: true, share: null, sku: "gold", surcharge: 4}, {balance: 1000, bonus: 7.25, drivers: [{country: "gold", limit: 65, status: "open"}, {country: "gold", limit: 99999999999999999999}, {country: "", limit: 65, status: "open"}], fee: "31", flags: {bucket: "low-7.25", quota: true}, rank: null, segment: null, share: null, sku: "low", surcharge: 3}], penalty: false, review: false, verified: true}, net: "7.25"}], + [{claim: {income: 250, kind: "retail", verified: true, dueDate: "1990-06-15", loans: [{balance: 1, sku: "NL", drivers: [{limit: 1, status: "open", country: "gold"}, {limit: 1000, status: "open", country: "none"}]}, {balance: 2, sku: "none", drivers: []}, {balance: 1.5, sku: "low", drivers: [{limit: 5, status: "open", country: "x-y"}, {limit: 1, status: "pending", country: "ok"}, {limit: 2, status: "open", country: "Oslo"}]}, {balance: -0, sku: "", drivers: []}, {balance: 3, sku: "gold", drivers: [{limit: 81, status: "open", country: "A1"}]}]}}, {claim: {dueDate: "1990-06-15", income: 250, kind: "retail", loans: [{balance: 1, bonus: 250, drivers: [{country: "gold", limit: 1, status: "open"}, {country: "none", limit: 1000, status: "open"}], fee: "15", flags: {bucket: "NL-250", quota: false}, rank: null, segment: null, share: null, sku: "NL", surcharge: 2}, {balance: 2, bonus: 250, drivers: [], fee: "15", flags: {bucket: "none-250", quota: false}, rank: null, segment: null, share: null, sku: "none", surcharge: 4}, {balance: 1.5, bonus: 250, drivers: [{country: "x-y", limit: 5, status: "open"}, {country: "ok", limit: 1, status: "pending"}, {country: "Oslo", limit: 2, status: "open"}], fee: "15", flags: {bucket: "low-250", quota: false}, rank: null, segment: null, share: null, sku: "low", surcharge: 3}, {balance: 0, bonus: 250, drivers: [], fee: "true", flags: {bucket: "-250", quota: false}, rank: null, segment: null, share: null, sku: "", surcharge: 0}, {balance: 3, bonus: 250, drivers: [{country: "A1", limit: 81, status: "open"}], fee: "15", flags: {bucket: "gold-250", quota: false}, rank: null, segment: null, share: null, sku: "gold", surcharge: 4}], penalty: false, review: false, verified: true}, net: "250"}], + [{claim: {income: 0.1, kind: "retail", verified: false, dueDate: "2025-03-20", loans: []}}, {claim: {dueDate: "2025-03-20", income: 0.1, kind: "retail", loans: [], penalty: true, review: false, verified: false}, net: "0.1"}], + ], +} + +// seed 345600 (attempt 0) +{ + name: "b 57: claim/parcels: 1 assertion, 3 expression, 2 table; 3 root, 4 per-member, 0 top-level computed", + policy: { + models: {claim: {rate: "number?", qty: "number?", birthDate: "date?", parcels: "parcel[]"}, parcel: {years: "number", openedAt: "date", urgent: "boolean", balance: "number"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {expression: "claim.surcharge", value: "none(claim.parcels, (#.urgent and #.urgent))"}, + {expression: "parcel.flag", value: "all(claim.parcels, (#.urgent or #.urgent))"}, + {expression: "claim.fee", value: "max([(number(string((claim.rate ?? 0))) % (abs((claim.birthDate ?? d('2025-01-01')).month()) + 1)), (min([abs(len(claim.parcels)), 1000]) ^ 0)])"}, + {table: "t4", inputs: ["parcel.openedAt", "floor(factor)", "claim.rate"], outputs: ["parcel.totals.weighted"], rules: [ + [">= d('2000-06-30')", "50, 1000", "1000", "250"], + ["", "18", "5, 100", "(claim.qty ?? 0)"], + ["", "", "", "(min([abs((claim.rate ?? 0)), 1000]) ^ 0)"], + ]}, + {table: "t5", hit: "collect", inputs: ["claim.fee", "(claim.qty ?? 0)"], outputs: ["parcel.quota", "parcel.health"], rules: [ + ["!= 0.5", "", "", "len(filter(claim.parcels, not (#.flag)))"], + ["", "<= 250", "", "factor"], + ["", "", "(claim.rate ?? 0)", "parcel.balance"], + ]}, + {assertion: "claim.bucket", conditions: [["or", "0.25 != (claim.rate ?? 0)", 1]]}, + ], + }, + cases: [ + [{factor: 0, claim: {rate: 1000, qty: 1000000, birthDate: "1990-06-15", parcels: [{years: 0, openedAt: "2025-03-20", urgent: true, balance: 0.000001}, {years: 7.25, openedAt: "2000-01-01", urgent: true, balance: 0.1}]}}, {claim: {birthDate: "1990-06-15", bucket: true, fee: 6, parcels: [{balance: 0.000001, flag: true, health: [0, 0.000001], openedAt: "2025-03-20", quota: [1000], totals: {weighted: 1}, urgent: true, years: 0}, {balance: 0.1, flag: true, health: [0, 0.1], openedAt: "2000-01-01", quota: [1000], totals: {weighted: 1}, urgent: true, years: 7.25}], qty: 1000000, rate: 1000, surcharge: false}, factor: 0}], + [{factor: 100, claim: {rate: 18, qty: 0.5, birthDate: "2024-01-01", parcels: [{years: -0.5, openedAt: "2025-03-20T10:15:30Z", urgent: false, balance: 18}, {years: 18, openedAt: "2030-12-31", urgent: true, balance: 1000000}, {years: 1, openedAt: "2024-01-01", urgent: false, balance: -0.5}, {years: 100, openedAt: "2000-01-01", urgent: true, balance: 3}, {years: -1, openedAt: "2025-03-20T10:15:30Z", urgent: false, balance: 0.1}]}}, {claim: {birthDate: "2024-01-01", bucket: true, fee: 1, parcels: [{balance: 18, flag: false, health: [5, 100, 18], openedAt: "2025-03-20T10:15:30Z", quota: [18], totals: {weighted: 1}, urgent: false, years: -0.5}, {balance: 1000000, flag: false, health: [5, 100, 1000000], openedAt: "2030-12-31", quota: [18], totals: {weighted: 1}, urgent: true, years: 18}, {balance: -0.5, flag: false, health: [5, 100, -0.5], openedAt: "2024-01-01", quota: [18], totals: {weighted: 1}, urgent: false, years: 1}, {balance: 3, flag: false, health: [5, 100, 3], openedAt: "2000-01-01", quota: [18], totals: {weighted: 1}, urgent: true, years: 100}, {balance: 0.1, flag: false, health: [5, 100, 0.1], openedAt: "2025-03-20T10:15:30Z", quota: [18], totals: {weighted: 1}, urgent: false, years: -1}], qty: 0.5, rate: 18, surcharge: false}, factor: 100}], + [{factor: -2, claim: {birthDate: "2000-01-01", parcels: [{years: 0.000001, openedAt: "1990-06-15", urgent: false, balance: 50}, {years: 250, openedAt: "2024-01-01", urgent: false, balance: 100}, {years: 123456789.123, openedAt: "2000-01-01", urgent: true, balance: -0.5}, {years: 250, openedAt: "2000-01-01", urgent: false, balance: 10}]}}, {claim: {birthDate: "2000-01-01", bucket: true, fee: 1, parcels: [{balance: 50, flag: false, health: [4, -2, 50], openedAt: "1990-06-15", quota: [0], totals: {weighted: 1}, urgent: false, years: 0.000001}, {balance: 100, flag: false, health: [4, -2, 100], openedAt: "2024-01-01", quota: [0], totals: {weighted: 1}, urgent: false, years: 250}, {balance: -0.5, flag: false, health: [4, -2, -0.5], openedAt: "2000-01-01", quota: [0], totals: {weighted: 1}, urgent: true, years: 123456789.123}, {balance: 10, flag: false, health: [4, -2, 10], openedAt: "2000-01-01", quota: [0], totals: {weighted: 1}, urgent: false, years: 250}], surcharge: false}, factor: -2}], + [{factor: 1, claim: {rate: null, qty: 50, birthDate: "2025-03-20", parcels: [{years: 3, openedAt: "1990-06-15", urgent: false, balance: 1000}, {years: 250, openedAt: "2000-01-01", urgent: false, balance: 123456789.123}, {years: 50, openedAt: "2030-12-31", urgent: true, balance: 1}]}}, {claim: {birthDate: "2025-03-20", bucket: true, fee: 1, parcels: [{balance: 1000, flag: false, health: [3, 1, 1000], openedAt: "1990-06-15", quota: [0], totals: {weighted: 1}, urgent: false, years: 3}, {balance: 123456789.123, flag: false, health: [3, 1, 123456789.123], openedAt: "2000-01-01", quota: [0], totals: {weighted: 1}, urgent: false, years: 250}, {balance: 1, flag: false, health: [3, 1, 1], openedAt: "2030-12-31", quota: [0], totals: {weighted: 1}, urgent: true, years: 50}], qty: 50, rate: null, surcharge: false}, factor: 1}], + [{factor: 1, claim: {rate: 0.000001, qty: 1000, birthDate: "2025-03-20", parcels: [{years: 0.000001, openedAt: "2024-02-29", urgent: false, balance: 250}, {years: -0, openedAt: "2025-03-20", urgent: false, balance: 10}, {years: 1000, openedAt: "1990-06-15", urgent: false, balance: 50}]}}, {claim: {birthDate: "2025-03-20", bucket: true, fee: 1, parcels: [{balance: 250, flag: false, health: [3, 250], openedAt: "2024-02-29", quota: [0.000001], totals: {weighted: 1}, urgent: false, years: 0.000001}, {balance: 10, flag: false, health: [3, 10], openedAt: "2025-03-20", quota: [0.000001], totals: {weighted: 1}, urgent: false, years: 0}, {balance: 50, flag: false, health: [3, 50], openedAt: "1990-06-15", quota: [0.000001], totals: {weighted: 1}, urgent: false, years: 1000}], qty: 1000, rate: 0.000001, surcharge: true}, factor: 1}], + [{factor: 100, claim: {rate: 3, qty: null, birthDate: null, parcels: [{years: -500, openedAt: "2025-03-20", urgent: false, balance: -0}, {years: -0, openedAt: "2024-02-29", urgent: false, balance: 100}]}}, {claim: {birthDate: null, bucket: true, fee: 1, parcels: [{balance: 0, flag: false, health: [2, 100, 0], openedAt: "2025-03-20", quota: [3], totals: {weighted: 1}, urgent: false, years: -500}, {balance: 100, flag: false, health: [2, 100, 100], openedAt: "2024-02-29", quota: [3], totals: {weighted: 1}, urgent: false, years: 0}], qty: null, rate: 3, surcharge: true}, factor: 100}], + [{factor: 10, claim: {rate: null, birthDate: "1990-06-15", parcels: [{years: -0, openedAt: "2024-01-01", urgent: false, balance: 18}, {years: -0.01, openedAt: "2025-03-20", urgent: false, balance: 18}, {years: 100, openedAt: "1990-06-15", urgent: false, balance: -0.01}]}}, {claim: {birthDate: "1990-06-15", bucket: true, fee: 1, parcels: [{balance: 18, flag: false, health: [3, 10, 18], openedAt: "2024-01-01", quota: [0], totals: {weighted: 1}, urgent: false, years: 0}, {balance: 18, flag: false, health: [3, 10, 18], openedAt: "2025-03-20", quota: [0], totals: {weighted: 1}, urgent: false, years: -0.01}, {balance: -0.01, flag: false, health: [3, 10, -0.01], openedAt: "1990-06-15", quota: [0], totals: {weighted: 1}, urgent: false, years: 100}], rate: null, surcharge: true}, factor: 10}], + [{factor: 100, claim: {rate: 99.99, qty: 1e3, birthDate: "2030-12-31", parcels: [{years: -0, openedAt: "2025-03-20", urgent: false, balance: 1}]}}, {claim: {birthDate: "2030-12-31", bucket: true, fee: 8.99, parcels: [{balance: 1, flag: false, health: [1, 1], openedAt: "2025-03-20", quota: [99.99], totals: {weighted: 1}, urgent: false, years: 0}], qty: 1000, rate: 99.99, surcharge: true}, factor: 100}], + [{factor: 10, claim: {rate: 1000000, qty: 50, birthDate: "1990-06-15", parcels: [{years: 123456789.123, openedAt: "2000-01-01", urgent: true, balance: 0.25}]}}, {claim: {birthDate: "1990-06-15", bucket: true, fee: 1, parcels: [{balance: 0.25, flag: true, health: [0, 10, 0.25], openedAt: "2000-01-01", quota: [1000000], totals: {weighted: 1}, urgent: true, years: 123456789.123}], qty: 50, rate: 1000000, surcharge: false}, factor: 10}], + [{factor: 10, claim: {rate: 0.1, qty: 18, birthDate: "2030-12-31", parcels: [{years: 2.50, openedAt: "2024-01-01", urgent: true, balance: 123456789.123}]}}, {claim: {birthDate: "2030-12-31", bucket: true, fee: 1, parcels: [{balance: 123456789.123, flag: true, health: [0, 10, 123456789.123], openedAt: "2024-01-01", quota: [0.1], totals: {weighted: 1}, urgent: true, years: 2.50}], qty: 18, rate: 0.1, surcharge: false}, factor: 10}], + [{factor: 1, claim: {rate: 7.25, qty: 5, birthDate: "2024-01-01", parcels: []}}, {claim: {birthDate: "2024-01-01", bucket: true, fee: 1.25, parcels: [], qty: 5, rate: 7.25, surcharge: true}, factor: 1}], + [{factor: 1, claim: {rate: -500, qty: 0.5, birthDate: "1990-06-15", parcels: [{years: 1e3, openedAt: "1990-06-15", urgent: true, balance: 250}, {years: 250, openedAt: "2025-03-20", urgent: false, balance: 1.5}]}}, {claim: {birthDate: "1990-06-15", bucket: true, fee: 1, parcels: [{balance: 250, flag: false, health: [2, 1, 250], openedAt: "1990-06-15", quota: [-500], totals: {weighted: 1}, urgent: true, years: 1000}, {balance: 1.5, flag: false, health: [2, 1, 1.5], openedAt: "2025-03-20", quota: [-500], totals: {weighted: 1}, urgent: false, years: 250}], qty: 0.5, rate: -500, surcharge: false}, factor: 1}], + [{factor: 10, claim: {rate: 0.5, qty: 50, birthDate: "2025-03-20T10:15:30Z", parcels: [{years: 0.000001, openedAt: "2025-03-20T10:15:30Z", urgent: false, balance: 1000}]}}, {claim: {birthDate: "2025-03-20T10:15:30Z", bucket: true, fee: 1, parcels: [{balance: 1000, flag: false, health: [1, 10, 1000], openedAt: "2025-03-20T10:15:30Z", quota: [0.5], totals: {weighted: 1}, urgent: false, years: 0.000001}], qty: 50, rate: 0.5, surcharge: true}, factor: 10}], + [{factor: 0.5, claim: {rate: null, parcels: [{years: 10, openedAt: "2000-01-01", urgent: true, balance: 0.25}, {years: 199, openedAt: "2025-03-20", urgent: true, balance: 5}]}}, {claim: {bucket: true, fee: 1, parcels: [{balance: 0.25, flag: true, health: [0, 0.5, 0.25], openedAt: "2000-01-01", quota: [0], totals: {weighted: 1}, urgent: true, years: 10}, {balance: 5, flag: true, health: [0, 0.5, 5], openedAt: "2025-03-20", quota: [0], totals: {weighted: 1}, urgent: true, years: 199}], rate: null, surcharge: false}, factor: 0.5}], + [{factor: 10, claim: {rate: 99999999999999999999, parcels: [{years: 5, openedAt: "2025-03-20", urgent: true, balance: 0.1}, {years: 100, openedAt: "2000-01-01", urgent: true, balance: 5}, {years: 1000, openedAt: "2024-01-01", urgent: false, balance: 50}, {years: 5, openedAt: "2025-03-20T10:15:30Z", urgent: false, balance: -0.5}]}}, {claim: {bucket: true, fee: 1, parcels: [{balance: 0.1, flag: false, health: [4, 10, 0.1], openedAt: "2025-03-20", quota: [99999999999999999999], totals: {weighted: 1}, urgent: true, years: 5}, {balance: 5, flag: false, health: [4, 10, 5], openedAt: "2000-01-01", quota: [99999999999999999999], totals: {weighted: 1}, urgent: true, years: 100}, {balance: 50, flag: false, health: [4, 10, 50], openedAt: "2024-01-01", quota: [99999999999999999999], totals: {weighted: 1}, urgent: false, years: 1000}, {balance: -0.5, flag: false, health: [4, 10, -0.5], openedAt: "2025-03-20T10:15:30Z", quota: [99999999999999999999], totals: {weighted: 1}, urgent: false, years: 5}], rate: 99999999999999999999, surcharge: false}, factor: 10}], + [{factor: 0.5, claim: {rate: 123456789.123, qty: 0.1, birthDate: "2024-02-29", parcels: [{years: 18, openedAt: "2000-01-01", urgent: false, balance: 50}]}}, {claim: {birthDate: "2024-02-29", bucket: true, fee: 1, parcels: [{balance: 50, flag: false, health: [1, 0.5, 50], openedAt: "2000-01-01", quota: [123456789.123], totals: {weighted: 1}, urgent: false, years: 18}], qty: 0.1, rate: 123456789.123, surcharge: true}, factor: 0.5}], + [{factor: -2, claim: {rate: 5, qty: 1000, birthDate: "2000-01-01", parcels: [{years: -0.5, openedAt: "2025-03-20T10:15:30Z", urgent: true, balance: 10}]}}, {claim: {birthDate: "2000-01-01", bucket: true, fee: 1, parcels: [{balance: 10, flag: true, health: [0, 10], openedAt: "2025-03-20T10:15:30Z", quota: [5], totals: {weighted: 1}, urgent: true, years: -0.5}], qty: 1000, rate: 5, surcharge: false}, factor: -2}], + [{factor: -2, claim: {rate: 0.5, qty: 0.25, birthDate: "2025-03-20", parcels: [{years: 18, openedAt: "2024-01-01", urgent: false, balance: 5}, {years: 50, openedAt: "2000-01-01", urgent: false, balance: 2}, {years: 1e3, openedAt: "2025-03-20T10:15:30Z", urgent: false, balance: -0.5}, {years: 1e3, openedAt: "2030-12-31", urgent: false, balance: 1000}, {years: 250, openedAt: "2024-01-01", urgent: false, balance: 18}]}}, {claim: {birthDate: "2025-03-20", bucket: true, fee: 1, parcels: [{balance: 5, flag: false, health: [5, -2, 5], openedAt: "2024-01-01", quota: [0.5], totals: {weighted: 1}, urgent: false, years: 18}, {balance: 2, flag: false, health: [5, -2, 2], openedAt: "2000-01-01", quota: [0.5], totals: {weighted: 1}, urgent: false, years: 50}, {balance: -0.5, flag: false, health: [5, -2, -0.5], openedAt: "2025-03-20T10:15:30Z", quota: [0.5], totals: {weighted: 1}, urgent: false, years: 1000}, {balance: 1000, flag: false, health: [5, -2, 1000], openedAt: "2030-12-31", quota: [0.5], totals: {weighted: 1}, urgent: false, years: 1000}, {balance: 18, flag: false, health: [5, -2, 18], openedAt: "2024-01-01", quota: [0.5], totals: {weighted: 1}, urgent: false, years: 250}], qty: 0.25, rate: 0.5, surcharge: true}, factor: -2}], + [{factor: 0.5, claim: {birthDate: "2024-02-29", parcels: [{years: 1000000, openedAt: "2025-03-20", urgent: true, balance: 250}, {years: 100, openedAt: "2024-02-29", urgent: true, balance: 18}]}}, {claim: {birthDate: "2024-02-29", bucket: true, fee: 1, parcels: [{balance: 250, flag: true, health: [0, 0.5, 250], openedAt: "2025-03-20", quota: [0], totals: {weighted: 1}, urgent: true, years: 1000000}, {balance: 18, flag: true, health: [0, 0.5, 18], openedAt: "2024-02-29", quota: [0], totals: {weighted: 1}, urgent: true, years: 100}], surcharge: false}, factor: 0.5}], + [{factor: 1, claim: {rate: -0.5, qty: 50, birthDate: "1990-06-15", parcels: [{years: 100, openedAt: "2030-12-31", urgent: true, balance: 50}]}}, {claim: {birthDate: "1990-06-15", bucket: true, fee: 1, parcels: [{balance: 50, flag: true, health: [0, 1, 50], openedAt: "2030-12-31", quota: [-0.5], totals: {weighted: 1}, urgent: true, years: 100}], qty: 50, rate: -0.5, surcharge: false}, factor: 1}], + [{factor: 10, claim: {rate: 50, qty: 0.25, birthDate: "2025-03-20", parcels: [{years: 65, openedAt: "2025-03-20", urgent: true, balance: -0.5}]}}, {claim: {birthDate: "2025-03-20", bucket: true, fee: 2, parcels: [{balance: -0.5, flag: true, health: [0, 10, -0.5], openedAt: "2025-03-20", quota: [50], totals: {weighted: 1}, urgent: true, years: 65}], qty: 0.25, rate: 50, surcharge: false}, factor: 10}], + [{factor: 10, claim: {rate: 65, qty: null, birthDate: "2000-01-01", parcels: []}}, {claim: {birthDate: "2000-01-01", bucket: true, fee: 1, parcels: [], qty: null, rate: 65, surcharge: true}, factor: 10}], + [{factor: 1, claim: {rate: 1000, qty: 123456789.123, birthDate: "2024-02-29", parcels: [{years: 5, openedAt: "2024-01-01", urgent: false, balance: -500}], extraField: "x"}}, {claim: {birthDate: "2024-02-29", bucket: true, extraField: "x", fee: 1, parcels: [{balance: -500, flag: false, health: [1, -500], openedAt: "2024-01-01", quota: [1000], totals: {weighted: 1}, urgent: false, years: 5}], qty: 123456789.123, rate: 1000, surcharge: true}, factor: 1}], + ], +} + +// seed 345700 (attempt 0) +{ + name: "b 58: claim/items: 3 assertion, 1 expression, 2 match, 3 table; 4 root, 9 per-member, 0 top-level computed", + policy: { + models: {claim: {years: "number", flagged: "boolean?", price: "number?", rate: "number?", items: "item[]"}, item: {qty: "number", country: "string"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {assertion: "claim.bucket", conditions: [["and", "all(claim.items, #.weighted != null)", 1], ["or", "contains(((claim.flag ?? false) ? 'retail' : (claim.margin ?? '')), 'low')", 0], ["or", "matches((claim.margin ?? ''), 'a')", 1], ["and", "isNumeric(((claim.flag ?? false) ? (claim.margin ?? '') : (claim.margin ?? '')))", 0], ["or", "isNumeric((claim.margin ?? ''))", 0]]}, + {match: "item.totals.rank", arms: [["(item.share and (claim.flag ?? false))", "(split(string(item.share), '-')[0] ?? 'none')"], ["len(`${(claim.flag ?? false)}/${(claim.price ?? 0)}`) > 2", "item.country"], ["(claim.rate ?? 0) in [33..158]", "(threshold >= 0 ? `${item.share}/${item.qty}` : item.country)"], ["all(claim.items, (#.share or #.share))", "(claim.margin ?? '')"], ["", "('Oslo' + '-' + (claim.margin ?? ''))"]]}, + {table: "t2", inputs: ["threshold", "claim.price", null], outputs: ["claim.margin", "claim.flag"], rules: [ + [">= 3", "0.25", "((claim.flagged ?? false) and (claim.flagged ?? false))", "'x'", "(claim.flagged ?? false)"], + ["> 100", "", "((claim.flagged ?? false) and (claim.flagged ?? false))", "'gold'", ""], + ["5, 1.5", "2", "claim.flagged == null", "'Oslo'", "(claim.flagged ?? false)"], + ]}, + {table: "t6", inputs: ["item.meta.level"], outputs: ["item.totals.eligible", "item.exposure", "item.penalty[]"], rules: [ + ["'ok'", "len(item.meta.level)", "(avg(map(claim.items, round((#.weighted ?? 0)))) ?? 0)", "threshold"], + ["'low'", "item.qty", "18", "(claim.rate ?? 0)"], + ["$ != 'ok'", "(item.qty / 3)", "claim.years", "item.qty"], + ["'none'", "(claim.rate ?? 0)", "item.qty", "((item.weighted ?? 0) * (claim.price ?? 0))"], + ["'retail'", "claim.years", "item.qty", "(item.meta.bonus ?? 0)"], + ["", "(item.weighted ?? 0)", "((item.meta.bonus ?? 0) / 3)", "0"], + ["", "(claim.rate ?? 0)", "", "claim.years"], + ]}, + {assertion: "item.share", conditions: [["or", "some(claim.items, len(#.country) > 0)", 1]]}, + {table: "t1", inputs: ["(claim.flagged ?? false)", null, null], outputs: ["item.weighted", "item.meta.bonus"], rules: [ + ["", "", "(claim.price ?? 0) > claim.years", "item.qty", "item.qty"], + ["true", "(claim.rate ?? 0) <= threshold", "", "(claim.rate ?? 0)", "claim.years"], + ["", "claim.rate == null", "threshold in [15..196)", "0", "(claim.price ?? 0)"], + ["true", "", "((claim.flagged ?? false) and (claim.flagged ?? false))", "(claim.rate ?? 0)", "claim.years"], + ]}, + {expression: "item.segment", value: "round(sum(item.penalty))"}, + {match: "item.meta.level", arms: [["contains(['Oslo', 'DE', ''], item.country)", "(claim.margin ?? '')"], ["matches(`${item.country}/${(claim.flag ?? false)}`, '^[A-Z]')", "string(threshold)"], ["matches(('high' + '-' + item.country), '^.{2,}$')", "`${item.share}/${sum(map(claim.items, #.qty))}`"], ["claim.years in [29..84]", "(item.meta.bonus != null ? ((claim.flagged ?? false) ? (claim.margin ?? '') : item.country) : string((item.weighted ?? 0)))"], ["", "item.country"]]}, + {assertion: "claim.fee", conditions: [["and", "isNumeric(string(claim.bucket))", 1], ["and", "((claim.flagged ?? false) ? claim.years : 18) <= 3", 0]]}, + ], + }, + cases: [ + [{threshold: 0.5, claim: {years: 0, flagged: false, price: 7.25, rate: 2, items: [{qty: 2, country: "low"}, {qty: 123456789.123, country: "VIP"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [{country: "low", exposure: 0, meta: {bonus: 2, level: "true/123456791.123"}, penalty: [2, 0, 0], qty: 2, segment: 2, share: true, totals: {eligible: 0.6666666666666666666666666667, rank: "low"}, weighted: 2}, {country: "VIP", exposure: 0, meta: {bonus: 123456789.123, level: "0.5"}, penalty: [123456789.123, 0, 0], qty: 123456789.123, segment: 123456789, share: true, totals: {eligible: 41152263.041, rank: "VIP"}, weighted: 123456789.123}], margin: null, price: 7.25, rate: 2, years: 0}, threshold: 0.5}], + [{threshold: 100, claim: {years: 5, flagged: false, price: 0.1, items: [{qty: -500, country: "日本"}, {qty: -0.01, country: "retail"}, {qty: 5, country: "low"}, {qty: -0.5, country: " pad "}, {qty: 100, country: "3.5"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [{country: "日本", exposure: 5, meta: {bonus: 0.1, level: "true/-395.51"}, penalty: [-500, 0, 5], qty: -500, segment: -495, share: true, totals: {eligible: -166.66666666666666666666666667, rank: "日本"}, weighted: 0}, {country: "retail", exposure: 5, meta: {bonus: 0.1, level: "true/-395.51"}, penalty: [-0.01, 0, 5], qty: -0.01, segment: 5, share: true, totals: {eligible: -0.0033333333333333333333333333, rank: "retail"}, weighted: 0}, {country: "low", exposure: 5, meta: {bonus: 0.1, level: "true/-395.51"}, penalty: [5, 0, 5], qty: 5, segment: 10, share: true, totals: {eligible: 1.6666666666666666666666666667, rank: "low"}, weighted: 0}, {country: " pad ", exposure: 5, meta: {bonus: 0.1, level: "true/-395.51"}, penalty: [-0.5, 0, 5], qty: -0.5, segment: 5, share: true, totals: {eligible: -0.1666666666666666666666666667, rank: " pad "}, weighted: 0}, {country: "3.5", exposure: 5, meta: {bonus: 0.1, level: "true/-395.51"}, penalty: [100, 0, 5], qty: 100, segment: 105, share: true, totals: {eligible: 33.333333333333333333333333333, rank: "3.5"}, weighted: 0}], margin: null, price: 0.1, years: 5}, threshold: 100}], + [{threshold: 1, claim: {years: 18, flagged: false, price: 3, rate: 0.5, items: []}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [], margin: null, price: 3, rate: 0.5, years: 18}, threshold: 1}], + [{threshold: 0.5, claim: {years: 2, flagged: true, price: 1.5, rate: 2, items: [{qty: 99.99, country: "Zed"}, {qty: 250, country: "US"}, {qty: 123456789.123, country: "Oslo"}, {qty: 18, country: "US"}, {qty: 1000, country: "low"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: true, items: [{country: "Zed", exposure: 2, meta: {bonus: 2, level: "0.5"}, penalty: [99.99, 0, 2], qty: 99.99, segment: 102, share: true, totals: {eligible: 33.33, rank: "Zed"}, weighted: 2}, {country: "US", exposure: 2, meta: {bonus: 2, level: "0.5"}, penalty: [250, 0, 2], qty: 250, segment: 252, share: true, totals: {eligible: 83.33333333333333333333333333, rank: "US"}, weighted: 2}, {country: "Oslo", exposure: 2, meta: {bonus: 2, level: ""}, penalty: [123456789.123, 0, 2], qty: 123456789.123, segment: 123456791, share: true, totals: {eligible: 41152263.041, rank: "Oslo"}, weighted: 2}, {country: "US", exposure: 2, meta: {bonus: 2, level: "0.5"}, penalty: [18, 0, 2], qty: 18, segment: 20, share: true, totals: {eligible: 6, rank: "US"}, weighted: 2}, {country: "low", exposure: 2, meta: {bonus: 2, level: "true/123458157.113"}, penalty: [1000, 0, 2], qty: 1000, segment: 1002, share: true, totals: {eligible: 333.33333333333333333333333333, rank: "low"}, weighted: 2}], margin: null, price: 1.5, rate: 2, years: 2}, threshold: 0.5}], + [{threshold: 1, claim: {years: 3, flagged: false, price: 0, rate: 65, items: [{qty: 65, country: "low"}, {qty: 3, country: "low"}, {qty: 18, country: "ok"}, {qty: -1, country: "gold"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [{country: "low", exposure: 3, meta: {bonus: null, level: "true/85"}, penalty: [65, 0, 3], qty: 65, segment: 68, share: true, totals: {eligible: 21.666666666666666666666666667, rank: "low"}, weighted: null}, {country: "low", exposure: 3, meta: {bonus: null, level: "true/85"}, penalty: [3, 0, 3], qty: 3, segment: 6, share: true, totals: {eligible: 1, rank: "low"}, weighted: null}, {country: "ok", exposure: 3, meta: {bonus: null, level: "true/85"}, penalty: [18, 0, 3], qty: 18, segment: 21, share: true, totals: {eligible: 6, rank: "ok"}, weighted: null}, {country: "gold", exposure: 3, meta: {bonus: null, level: "true/85"}, penalty: [-1, 0, 3], qty: -1, segment: 2, share: true, totals: {eligible: -0.3333333333333333333333333333, rank: "gold"}, weighted: null}], margin: null, price: 0, rate: 65, years: 3}, threshold: 1}], + [{threshold: -2, claim: {years: 5, flagged: true, price: 0.25, rate: 18, items: []}}, {claim: {bucket: false, fee: false, flag: null, flagged: true, items: [], margin: null, price: 0.25, rate: 18, years: 5}, threshold: -2}], + [{threshold: 0, claim: {years: 1, flagged: false, price: 3, rate: -0.5, items: [{qty: 253, country: "ok"}, {qty: 123456789.123, country: "NL"}, {qty: 250, country: "a"}], extraField: 1}}, {claim: {bucket: false, extraField: 1, fee: false, flag: null, flagged: false, items: [{country: "ok", exposure: 1, meta: {bonus: 253, level: "true/123457292.123"}, penalty: [253, 0, 1], qty: 253, segment: 254, share: true, totals: {eligible: 84.33333333333333333333333333, rank: "ok"}, weighted: 253}, {country: "NL", exposure: 1, meta: {bonus: 123456789.123, level: "0"}, penalty: [123456789.123, 0, 1], qty: 123456789.123, segment: 123456790, share: true, totals: {eligible: 41152263.041, rank: "NL"}, weighted: 123456789.123}, {country: "a", exposure: 1, meta: {bonus: 250, level: "true/123457292.123"}, penalty: [250, 0, 1], qty: 250, segment: 251, share: true, totals: {eligible: 83.33333333333333333333333333, rank: "a"}, weighted: 250}], margin: null, price: 3, rate: -0.5, years: 1}, threshold: 0}], + [{threshold: 1, claim: {years: 5, flagged: false, price: 100, rate: 18, items: [{qty: 100, country: "3.5"}, {qty: 99999999999999999999, country: "none"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [{country: "3.5", exposure: 5, meta: {bonus: 100, level: "true/100000000000000000099"}, penalty: [100, 0, 5], qty: 100, segment: 105, share: true, totals: {eligible: 33.333333333333333333333333333, rank: "3.5"}, weighted: 100}, {country: "none", exposure: 5, meta: {bonus: 99999999999999999999, level: "true/100000000000000000099"}, penalty: [99999999999999999999, 0, 5], qty: 99999999999999999999, segment: 100000000000000000004, share: true, totals: {eligible: 33333333333333333333, rank: "none"}, weighted: 99999999999999999999}], margin: null, price: 100, rate: 18, years: 5}, threshold: 1}], + [{threshold: 0, claim: {years: 250, price: -1, rate: 1, items: [{qty: 100, country: "日本"}, {qty: 3, country: "US"}, {qty: 3, country: "A1"}, {qty: 100, country: "12"}]}}, {claim: {bucket: false, fee: false, flag: null, items: [{country: "日本", exposure: 250, meta: {bonus: null, level: "true/206"}, penalty: [100, 0, 250], qty: 100, segment: 350, share: true, totals: {eligible: 33.333333333333333333333333333, rank: "日本"}, weighted: null}, {country: "US", exposure: 250, meta: {bonus: null, level: "0"}, penalty: [3, 0, 250], qty: 3, segment: 253, share: true, totals: {eligible: 1, rank: "US"}, weighted: null}, {country: "A1", exposure: 250, meta: {bonus: null, level: "0"}, penalty: [3, 0, 250], qty: 3, segment: 253, share: true, totals: {eligible: 1, rank: "A1"}, weighted: null}, {country: "12", exposure: 250, meta: {bonus: null, level: "true/206"}, penalty: [100, 0, 250], qty: 100, segment: 350, share: true, totals: {eligible: 33.333333333333333333333333333, rank: "12"}, weighted: null}], margin: null, price: -1, rate: 1, years: 250}, threshold: 0}], + [{threshold: 100, claim: {years: 5, flagged: null, price: 100, rate: 50, items: [{qty: 0, country: "gold"}, {qty: -1, country: "DE"}, {qty: 7.25, country: "Zed"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: null, items: [{country: "gold", exposure: 5, meta: {bonus: 0, level: "true/6.25"}, penalty: [0, 0, 5], qty: 0, segment: 5, share: true, totals: {eligible: 0, rank: "gold"}, weighted: 0}, {country: "DE", exposure: 5, meta: {bonus: -1, level: ""}, penalty: [-1, 0, 5], qty: -1, segment: 4, share: true, totals: {eligible: -0.3333333333333333333333333333, rank: "DE"}, weighted: -1}, {country: "Zed", exposure: 5, meta: {bonus: 7.25, level: "100"}, penalty: [7.25, 0, 5], qty: 7.25, segment: 12, share: true, totals: {eligible: 2.4166666666666666666666666667, rank: "Zed"}, weighted: 7.25}], margin: null, price: 100, rate: 50, years: 5}, threshold: 100}], + [{threshold: 10, claim: {years: 18, flagged: true, price: 0.1, items: [{qty: 2, country: "Oslo"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: true, items: [{country: "Oslo", exposure: 18, meta: {bonus: 18, level: ""}, penalty: [2, 0, 18], qty: 2, segment: 20, share: true, totals: {eligible: 0.6666666666666666666666666667, rank: "Oslo"}, weighted: 0}], margin: null, price: 0.1, years: 18}, threshold: 10}], + [{threshold: 100, claim: {years: 2, flagged: true, price: 0, rate: -1, items: [{qty: 0, country: "O'Neil"}, {qty: -500, country: "retail"}, {qty: 2, country: "-"}, {qty: 2, country: "US"}, {qty: 1000000, country: "ok"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: true, items: [{country: "O'Neil", exposure: 2, meta: {bonus: 2, level: "100"}, penalty: [0, 0, 2], qty: 0, segment: 2, share: true, totals: {eligible: 0, rank: "O'Neil"}, weighted: -1}, {country: "retail", exposure: 2, meta: {bonus: 2, level: "true/999504"}, penalty: [-500, 0, 2], qty: -500, segment: -498, share: true, totals: {eligible: -166.66666666666666666666666667, rank: "retail"}, weighted: -1}, {country: "-", exposure: 2, meta: {bonus: 2, level: "true/999504"}, penalty: [2, 0, 2], qty: 2, segment: 4, share: true, totals: {eligible: 0.6666666666666666666666666667, rank: "-"}, weighted: -1}, {country: "US", exposure: 2, meta: {bonus: 2, level: "100"}, penalty: [2, 0, 2], qty: 2, segment: 4, share: true, totals: {eligible: 0.6666666666666666666666666667, rank: "US"}, weighted: -1}, {country: "ok", exposure: 2, meta: {bonus: 2, level: "true/999504"}, penalty: [1000000, 0, 2], qty: 1000000, segment: 1000002, share: true, totals: {eligible: 333333.33333333333333333333333, rank: "ok"}, weighted: -1}], margin: null, price: 0, rate: -1, years: 2}, threshold: 100}], + [{threshold: 0.5, claim: {years: 18, flagged: null, price: null, rate: null, items: [{qty: 18, country: "none"}, {qty: 2, country: "retail"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: null, items: [{country: "none", exposure: 18, meta: {bonus: null, level: "true/20"}, penalty: [18, 0, 18], qty: 18, segment: 36, share: true, totals: {eligible: 6, rank: "none"}, weighted: null}, {country: "retail", exposure: 18, meta: {bonus: null, level: "true/20"}, penalty: [2, 0, 18], qty: 2, segment: 20, share: true, totals: {eligible: 0.6666666666666666666666666667, rank: "retail"}, weighted: null}], margin: null, price: null, rate: null, years: 18}, threshold: 0.5}], + [{threshold: 0.5, claim: {years: 5, flagged: false, price: -0.01, rate: null, items: [{qty: 99999999999999999999, country: "é ü"}, {qty: 2, country: "low"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [{country: "é ü", exposure: 5, meta: {bonus: null, level: "true/100000000000000000001"}, penalty: [99999999999999999999, 0, 5], qty: 99999999999999999999, segment: 100000000000000000004, share: true, totals: {eligible: 33333333333333333333, rank: "é ü"}, weighted: null}, {country: "low", exposure: 5, meta: {bonus: null, level: "true/100000000000000000001"}, penalty: [2, 0, 5], qty: 2, segment: 7, share: true, totals: {eligible: 0.6666666666666666666666666667, rank: "low"}, weighted: null}], margin: null, price: -0.01, rate: null, years: 5}, threshold: 0.5}], + [{threshold: 100, claim: {years: 250, price: 0.5, rate: 0, items: [{qty: 5, country: "x-y"}, {qty: 18, country: "gold"}]}}, {claim: {bucket: false, fee: false, flag: null, items: [{country: "x-y", exposure: 250, meta: {bonus: null, level: "true/23"}, penalty: [5, 0, 250], qty: 5, segment: 255, share: true, totals: {eligible: 1.6666666666666666666666666667, rank: "x-y"}, weighted: null}, {country: "gold", exposure: 250, meta: {bonus: null, level: "true/23"}, penalty: [18, 0, 250], qty: 18, segment: 268, share: true, totals: {eligible: 6, rank: "gold"}, weighted: null}], margin: null, price: 0.5, rate: 0, years: 250}, threshold: 100}], + [{threshold: 10, claim: {years: 5, flagged: false, price: 0.1, rate: 1e3, items: [{qty: 250, country: "ok"}, {qty: 3, country: "gold"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [{country: "ok", exposure: 5, meta: {bonus: null, level: "true/253"}, penalty: [250, 0, 5], qty: 250, segment: 255, share: true, totals: {eligible: 83.33333333333333333333333333, rank: "ok"}, weighted: null}, {country: "gold", exposure: 5, meta: {bonus: null, level: "true/253"}, penalty: [3, 0, 5], qty: 3, segment: 8, share: true, totals: {eligible: 1, rank: "gold"}, weighted: null}], margin: null, price: 0.1, rate: 1000, years: 5}, threshold: 10}], + [{threshold: 0, claim: {years: 124, flagged: false, price: 100, rate: 0, items: [{qty: 0, country: " pad "}, {qty: 99.99, country: "a"}, {qty: 250, country: "gold"}, {qty: 1, country: "a"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [{country: " pad ", exposure: 124, meta: {bonus: null, level: "true/350.99"}, penalty: [0, 0, 124], qty: 0, segment: 124, share: true, totals: {eligible: 0, rank: " pad "}, weighted: null}, {country: "a", exposure: 124, meta: {bonus: null, level: "true/350.99"}, penalty: [99.99, 0, 124], qty: 99.99, segment: 224, share: true, totals: {eligible: 33.33, rank: "a"}, weighted: null}, {country: "gold", exposure: 124, meta: {bonus: null, level: "true/350.99"}, penalty: [250, 0, 124], qty: 250, segment: 374, share: true, totals: {eligible: 83.33333333333333333333333333, rank: "gold"}, weighted: null}, {country: "a", exposure: 124, meta: {bonus: null, level: "true/350.99"}, penalty: [1, 0, 124], qty: 1, segment: 125, share: true, totals: {eligible: 0.3333333333333333333333333333, rank: "a"}, weighted: null}], margin: null, price: 100, rate: 0, years: 124}, threshold: 0}], + [{threshold: 10, claim: {years: 2, flagged: false, price: -0.5, rate: 2, items: [{qty: -0, country: "-"}, {qty: 18, country: "none"}, {qty: 2, country: "DE"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: false, items: [{country: "-", exposure: 2, meta: {bonus: null, level: "true/20"}, penalty: [0, 0, 2], qty: 0, segment: 2, share: true, totals: {eligible: 0, rank: "-"}, weighted: null}, {country: "none", exposure: 2, meta: {bonus: null, level: "true/20"}, penalty: [18, 0, 2], qty: 18, segment: 20, share: true, totals: {eligible: 6, rank: "none"}, weighted: null}, {country: "DE", exposure: 2, meta: {bonus: null, level: ""}, penalty: [2, 0, 2], qty: 2, segment: 4, share: true, totals: {eligible: 0.6666666666666666666666666667, rank: "DE"}, weighted: null}], margin: null, price: -0.5, rate: 2, years: 2}, threshold: 10}], + [{threshold: -2, claim: {years: 0.000001, flagged: null, price: 0, rate: 5, items: [{qty: 0.5, country: "é ü"}, {qty: 250, country: "VIP"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: null, items: [{country: "é ü", exposure: 0.000001, meta: {bonus: null, level: "true/250.5"}, penalty: [0.5, 0, 0.000001], qty: 0.5, segment: 1, share: true, totals: {eligible: 0.1666666666666666666666666667, rank: "é ü"}, weighted: null}, {country: "VIP", exposure: 0.000001, meta: {bonus: null, level: "-2"}, penalty: [250, 0, 0.000001], qty: 250, segment: 250, share: true, totals: {eligible: 83.33333333333333333333333333, rank: "VIP"}, weighted: null}], margin: null, price: 0, rate: 5, years: 0.000001}, threshold: -2}], + [{threshold: -2, claim: {years: 0, items: [{qty: 65, country: "a"}]}}, {claim: {bucket: false, fee: false, flag: null, items: [{country: "a", exposure: 0, meta: {bonus: null, level: "true/65"}, penalty: [65, 0, 0], qty: 65, segment: 65, share: true, totals: {eligible: 21.666666666666666666666666667, rank: "a"}, weighted: null}], margin: null, years: 0}, threshold: -2}], + [{threshold: 0.5, claim: {years: 0.25, items: [{qty: 250, country: "Oslo"}]}}, {claim: {bucket: false, fee: false, flag: null, items: [{country: "Oslo", exposure: 0.25, meta: {bonus: null, level: ""}, penalty: [250, 0, 0.25], qty: 250, segment: 250, share: true, totals: {eligible: 83.33333333333333333333333333, rank: "Oslo"}, weighted: null}], margin: null, years: 0.25}, threshold: 0.5}], + [{threshold: 1, claim: {years: 50, flagged: true, rate: 65, items: [{qty: 2, country: "ok"}, {qty: 18, country: "high"}, {qty: 99.99, country: "low"}, {qty: 250, country: "none"}, {qty: 65, country: "US"}]}}, {claim: {bucket: false, fee: false, flag: null, flagged: true, items: [{country: "ok", exposure: 50, meta: {bonus: 50, level: "true/434.99"}, penalty: [2, 0, 50], qty: 2, segment: 52, share: true, totals: {eligible: 0.6666666666666666666666666667, rank: "ok"}, weighted: 65}, {country: "high", exposure: 50, meta: {bonus: 50, level: "true/434.99"}, penalty: [18, 0, 50], qty: 18, segment: 68, share: true, totals: {eligible: 6, rank: "high"}, weighted: 65}, {country: "low", exposure: 50, meta: {bonus: 50, level: "true/434.99"}, penalty: [99.99, 0, 50], qty: 99.99, segment: 150, share: true, totals: {eligible: 33.33, rank: "low"}, weighted: 65}, {country: "none", exposure: 50, meta: {bonus: 50, level: "true/434.99"}, penalty: [250, 0, 50], qty: 250, segment: 300, share: true, totals: {eligible: 83.33333333333333333333333333, rank: "none"}, weighted: 65}, {country: "US", exposure: 50, meta: {bonus: 50, level: "1"}, penalty: [65, 0, 50], qty: 65, segment: 115, share: true, totals: {eligible: 21.666666666666666666666666667, rank: "US"}, weighted: 65}], margin: null, rate: 65, years: 50}, threshold: 1}], + ], +} + +// seed 345800 (attempt 0) +{ + name: "b 59: order/members + address: 2 assertion, 3 expression, 4 table; 3 root, 5 per-member, 0 top-level computed", + policy: { + models: {order: {years: "number?", country: "string?", dueDate: "date", status: "string(open|closed|pending)", members: "member[]", address: "address"}, member: {score: "number?", code: "string?", days: "number?", since: "date"}, address: {amount: "number"}}, + blocks: [ + {expression: "address.health", value: "order.dueDate.year()"}, + {table: "t7", inputs: ["(order.years ?? 0)"], outputs: ["address.scores.ok"], rules: [ + ["< 18", "(order.years ?? 0)"], + ["", "len(order.level)"], + ["", "min([address.health, address.amount])"], + ["", ""], + ["< 250", "sum(map(order.members, (#.days ?? 0)))"], + ]}, + {table: "t8", inputs: ["((order.years ?? 0) / 3)", "address.amount", "address.health"], outputs: ["address.discount", "address.exposure", "address.net[]"], rules: [ + ["250, 0.5", "", "< 50", "(50 % (abs(address.amount) + 1))", "(order.rank ?? 0)", "((order.margin ?? false) ? (order.rank ?? 0) : address.health)"], + ["[100..399]", "", "", "(address.health + (order.rank ?? 0))", "(order.rank ?? 0)", "address.amount"], + ["", "", "", "(order.rank ?? 0)", "(order.rank ?? 0)", "(address.health + address.health)"], + ]}, + {expression: "member.summary", value: "{v: order.address.amount}"}, + {expression: "member.decision", value: "`${(member.code ?? '')}/${(order.country ?? '') in ['Oslo', 'high']}`"}, + {assertion: "address.eligible", conditions: [["or", "len(order.level) == (order.years ?? 0)", 1], ["or", "none(order.members, matches((#.code ?? ''), '[0-9]$'))", 1], ["and", "order.dueDate.isSameOrBefore(d('2025-01-01'), 'day')", 2], ["and", "contains(`${(order.margin ?? false)}/${address.amount}`, 'gold')", 0], ["or", "len(order.level) < (order.rank ?? 0)", 2]]}, + {table: "t3", hit: "collect", inputs: ["order.address.amount", null], outputs: ["member.adjusted"], rules: [ + ["1000, 5", "", "member.segment"], + ["[1..202]", "", "some(order.members, contains(['A1', 'none', ''], (#.code ?? '')))"], + ["< 0.5", "not ((order.margin ?? false))", "(order.margin ?? false)"], + ]}, + {table: "t1", inputs: ["-(order.address.amount)", null], outputs: ["order.level[]", "order.rank", "order.margin"], rules: [ + ["", "matches((order.country ?? ''), 'a')", "(order.country ?? '')", "(order.years ?? 0)", "all(order.members, (#.score ?? 0) in [5..134])"], + ["< 1000", "", "(order.country ?? '')", "2", "order.address.amount == 100"], + ["> 2", "", "(order.country ?? '')", "", "(order.years ?? 0) > 50"], + ["!= 3", "((order.years ?? 0) == 1.5 and (order.years ?? 0) > 250)", "(order.country ?? '')", "order.address.amount", "0.25 <= 5"], + ["", "", "(order.country ?? '')", "(order.address.amount * order.address.amount)", "order.address.amount > 2"], + ["<= 2", "", "(order.country ?? '')", "", "(order.years ?? 0) > 5"], + ]}, + {assertion: "member.segment", conditions: ["((order.margin ?? false) or (order.margin ?? false))", ["and", "some(order.members, #.code != null)", 1], ["or", "member.days != null", 0]]}, + ], + }, + cases: [ + [{order: {years: 0.25, country: "O'Neil", dueDate: "2030-12-31", status: "closed", members: [{score: 5, code: "Zed", days: 5, since: "2000-01-01"}, {score: 1e3, code: "日本", days: 100, since: "2024-01-01"}, {score: 1.5, code: "Zed", days: 5, since: "2024-02-29"}, {score: 1, code: "DE", days: 5, since: "2024-02-29"}], address: {amount: 1.5}}}, {order: {address: {amount: 1.5, discount: 2, eligible: false, exposure: 2, health: 2030, net: [4060], scores: {ok: 0.25}}, country: "O'Neil", dueDate: "2030-12-31", level: ["O'Neil", "O'Neil", "O'Neil"], margin: false, members: [{adjusted: [false], code: "Zed", days: 5, decision: "Zed/false", score: 5, since: "2000-01-01", summary: {v: 1.5}}, {adjusted: [false], code: "日本", days: 100, decision: "日本/false", score: 1000, since: "2024-01-01", summary: {v: 1.5}}, {adjusted: [false], code: "Zed", days: 5, decision: "Zed/false", score: 1.5, since: "2024-02-29", summary: {v: 1.5}}, {adjusted: [false], code: "DE", days: 5, decision: "DE/false", score: 1, since: "2024-02-29", summary: {v: 1.5}}], rank: 2, status: "closed", years: 0.25}}], + [{order: {years: 5, country: "é ü", dueDate: "2000-01-01", status: "pending", members: [{score: 5, code: "O'Neil", days: 250, since: "2025-03-20T10:15:30Z"}, {score: 1000000, code: "12", days: 0, since: "2024-02-29"}, {score: 5, code: "3.5", days: 18, since: "2025-03-20T10:15:30Z"}, {score: 0.5, code: "x-y", days: 2, since: "2025-03-20"}, {score: 2, code: "a-b-c", days: 0.25, since: "2030-12-31"}, {score: 1, code: "3.5", days: 0.000001, since: "1990-06-15"}, {score: 1.5, code: "x-y", days: 2, since: "2030-12-31"}, {score: 0.25, code: "", days: 0.5, since: "2025-03-20"}, {score: 1.5, code: "3.5", days: 100, since: "2025-03-20T10:15:30Z"}, {score: 7.25, code: "high", days: 250, since: "2025-03-20"}], address: {amount: 0.25}}}, {order: {address: {amount: 0.25, discount: 2, eligible: false, exposure: 2, health: 2000, net: [4000], scores: {ok: 5}}, country: "é ü", dueDate: "2000-01-01", level: ["é ü", "é ü", "é ü"], margin: false, members: [{adjusted: [false], code: "O'Neil", days: 250, decision: "O'Neil/false", score: 5, since: "2025-03-20T10:15:30Z", summary: {v: 0.25}}, {adjusted: [false], code: "12", days: 0, decision: "12/false", score: 1000000, since: "2024-02-29", summary: {v: 0.25}}, {adjusted: [false], code: "3.5", days: 18, decision: "3.5/false", score: 5, since: "2025-03-20T10:15:30Z", summary: {v: 0.25}}, {adjusted: [false], code: "x-y", days: 2, decision: "x-y/false", score: 0.5, since: "2025-03-20", summary: {v: 0.25}}, {adjusted: [false], code: "a-b-c", days: 0.25, decision: "a-b-c/false", score: 2, since: "2030-12-31", summary: {v: 0.25}}, {adjusted: [false], code: "3.5", days: 0.000001, decision: "3.5/false", score: 1, since: "1990-06-15", summary: {v: 0.25}}, {adjusted: [false], code: "x-y", days: 2, decision: "x-y/false", score: 1.5, since: "2030-12-31", summary: {v: 0.25}}, {adjusted: [false], code: "", days: 0.5, decision: "/false", score: 0.25, since: "2025-03-20", summary: {v: 0.25}}, {adjusted: [false], code: "3.5", days: 100, decision: "3.5/false", score: 1.5, since: "2025-03-20T10:15:30Z", summary: {v: 0.25}}, {adjusted: [false], code: "high", days: 250, decision: "high/false", score: 7.25, since: "2025-03-20", summary: {v: 0.25}}], rank: 2, status: "pending", years: 5}}], + [{order: {years: 99999999999999999999, country: "NL", dueDate: "2024-01-01", status: "open", members: [{score: 2, code: "Oslo", days: 2, since: "2030-12-31"}, {score: 5, code: "DE", days: -500, since: "2030-12-31"}], address: {amount: 100}}}, {order: {address: {amount: 100, discount: 2, eligible: false, exposure: 2, health: 2024, net: [4048], scores: {ok: 3}}, country: "NL", dueDate: "2024-01-01", level: ["NL", "NL", "NL"], margin: true, members: [{adjusted: [false], code: "Oslo", days: 2, decision: "Oslo/false", score: 2, since: "2030-12-31", summary: {v: 100}}, {adjusted: [false], code: "DE", days: -500, decision: "DE/false", score: 5, since: "2030-12-31", summary: {v: 100}}], rank: 2, status: "open", years: 99999999999999999999}}], + [{order: {years: 100, country: "retail", dueDate: "2025-03-20T10:15:30Z", status: "closed", members: [{score: 2, code: "O'Neil", days: 1000, since: "2024-01-01"}], address: {amount: 250}}}, {order: {address: {amount: 250, discount: 100, eligible: false, exposure: 100, health: 2025, net: [4050], scores: {ok: 4}}, country: "retail", dueDate: "2025-03-20T10:15:30Z", level: ["retail", "retail", "retail", "retail"], margin: false, members: [{adjusted: [], code: "O'Neil", days: 1000, decision: "O'Neil/false", score: 2, since: "2024-01-01", summary: {v: 250}}], rank: 100, status: "closed", years: 100}}], + [{order: {years: -1, dueDate: "2025-03-20", status: "open", members: [{score: null, days: 100, since: "1990-06-15"}, {code: "x-y", days: null, since: "2000-01-01"}, {since: "2024-01-01"}, {code: null, days: 2, since: "2025-03-20"}, {score: -0, since: "2030-12-31"}], address: {amount: 1.5}}}, {order: {address: {amount: 1.5, discount: 2, eligible: false, exposure: 2, health: 2025, net: [4050], scores: {ok: -1}}, dueDate: "2025-03-20", level: ["", "", ""], margin: false, members: [{adjusted: [true], days: 100, decision: "/false", score: null, since: "1990-06-15", summary: {v: 1.5}}, {adjusted: [true], code: "x-y", days: null, decision: "x-y/false", since: "2000-01-01", summary: {v: 1.5}}, {adjusted: [true], decision: "/false", since: "2024-01-01", summary: {v: 1.5}}, {adjusted: [true], code: null, days: 2, decision: "/false", since: "2025-03-20", summary: {v: 1.5}}, {adjusted: [true], decision: "/false", score: 0, since: "2030-12-31", summary: {v: 1.5}}], rank: 2, status: "open", years: -1}}], + [{order: {years: 1.5, country: "gold", dueDate: "2024-02-29", status: "pending", members: [], address: {amount: 5}}}, {order: {address: {amount: 5, discount: 2, eligible: false, exposure: 2, health: 2024, net: [4048], scores: {ok: 1.5}}, country: "gold", dueDate: "2024-02-29", level: ["gold", "gold", "gold"], margin: false, members: [], rank: 2, status: "pending", years: 1.5}}], + [{order: {years: 250, country: "日本", dueDate: "2024-01-01", status: "open", members: [], address: {amount: 250}}}, {order: {address: {amount: 250, discount: 2, eligible: false, exposure: 2, health: 2024, net: [4048], scores: {ok: 3}}, country: "日本", dueDate: "2024-01-01", level: ["日本", "日本", "日本"], margin: false, members: [], rank: 2, status: "open", years: 250}}], + [{order: {years: -0.5, country: "US", dueDate: "2025-03-20", status: "closed", members: [{score: 3, code: "Oslo", days: 250, since: "1990-06-15"}], address: {amount: 1000000}}}, {order: {address: {amount: 1000000, discount: 2, eligible: false, exposure: 2, health: 2025, net: [4050], scores: {ok: -0.5}}, country: "US", dueDate: "2025-03-20", level: ["US", "US", "US"], margin: false, members: [{adjusted: [], code: "Oslo", days: 250, decision: "Oslo/false", score: 3, since: "1990-06-15", summary: {v: 1000000}}], rank: 2, status: "closed", years: -0.5}}], + [{order: {years: 250, country: "VIP", dueDate: "2000-01-01", status: "open", members: [{code: "high", since: "2024-01-01"}, {code: "é ü", days: null, since: "2024-01-01"}], address: {amount: 2}}}, {order: {address: {amount: 2, discount: 2, eligible: false, exposure: 2, health: 2000, net: [4000], scores: {ok: 3}}, country: "VIP", dueDate: "2000-01-01", level: ["VIP", "VIP", "VIP"], margin: false, members: [{adjusted: [false], code: "high", decision: "high/false", since: "2024-01-01", summary: {v: 2}}, {adjusted: [false], code: "é ü", days: null, decision: "é ü/false", since: "2024-01-01", summary: {v: 2}}], rank: 2, status: "open", years: 250}}], + [{order: {years: 3, country: "high", dueDate: "2024-01-01", status: "pending", members: [{score: 1000, code: "none", days: 18, since: "2024-02-29"}, {score: 250, code: "O'Neil", days: 0, since: "1990-06-15"}], address: {amount: 0.5}}}, {order: {address: {amount: 0.5, discount: 2, eligible: false, exposure: 2, health: 2024, net: [4048], scores: {ok: 3}}, country: "high", dueDate: "2024-01-01", level: ["high", "high", "high"], margin: false, members: [{adjusted: [], code: "none", days: 18, decision: "none/true", score: 1000, since: "2024-02-29", summary: {v: 0.5}}, {adjusted: [], code: "O'Neil", days: 0, decision: "O'Neil/true", score: 250, since: "1990-06-15", summary: {v: 0.5}}], rank: 2, status: "pending", years: 3}}], + [{order: {years: 18, country: "Zed", dueDate: "2030-12-31", status: "pending", members: [{score: 0.5, code: "US", days: 50, since: "2025-03-20T10:15:30Z"}, {score: 1, code: "", days: 1000000, since: "2000-01-01"}, {score: 7.25, code: "none", days: 100, since: "2030-12-31"}], address: {amount: 2}, extraField: 1}}, {order: {address: {amount: 2, discount: 2, eligible: false, exposure: 2, health: 2030, net: [4060], scores: {ok: 3}}, country: "Zed", dueDate: "2030-12-31", extraField: 1, level: ["Zed", "Zed", "Zed"], margin: false, members: [{adjusted: [true], code: "US", days: 50, decision: "US/false", score: 0.5, since: "2025-03-20T10:15:30Z", summary: {v: 2}}, {adjusted: [true], code: "", days: 1000000, decision: "/false", score: 1, since: "2000-01-01", summary: {v: 2}}, {adjusted: [true], code: "none", days: 100, decision: "none/false", score: 7.25, since: "2030-12-31", summary: {v: 2}}], rank: 2, status: "pending", years: 18}}], + [{order: {years: 50, country: "A1", dueDate: "2000-01-01", status: "pending", members: [{score: 5, code: "a", days: 5, since: "2030-12-31"}, {score: 99.99, code: "retail", days: 18, since: "1990-06-15"}], address: {amount: 0.5}, extraField: 1}}, {order: {address: {amount: 0.5, discount: 2, eligible: false, exposure: 2, health: 2000, net: [4000], scores: {ok: 3}}, country: "A1", dueDate: "2000-01-01", extraField: 1, level: ["A1", "A1", "A1"], margin: false, members: [{adjusted: [], code: "a", days: 5, decision: "a/false", score: 5, since: "2030-12-31", summary: {v: 0.5}}, {adjusted: [], code: "retail", days: 18, decision: "retail/false", score: 99.99, since: "1990-06-15", summary: {v: 0.5}}], rank: 2, status: "pending", years: 50}}], + [{order: {years: 50, dueDate: "2024-02-29", status: "pending", members: [], address: {amount: 1000}}}, {order: {address: {amount: 1000, discount: 2, eligible: false, exposure: 2, health: 2024, net: [4048], scores: {ok: 3}}, dueDate: "2024-02-29", level: ["", "", ""], margin: false, members: [], rank: 2, status: "pending", years: 50}}], + [{order: {dueDate: "2024-01-01", status: "closed", members: [{score: 1000, code: "NL", days: 50, since: "2030-12-31"}, {score: null, since: "2024-02-29"}], address: {amount: 0.5}}}, {order: {address: {amount: 0.5, discount: 2, eligible: false, exposure: 2, health: 2024, net: [4048], scores: {ok: 0}}, dueDate: "2024-01-01", level: ["", "", ""], margin: false, members: [{adjusted: [], code: "NL", days: 50, decision: "NL/false", score: 1000, since: "2030-12-31", summary: {v: 0.5}}, {adjusted: [], decision: "/false", score: null, since: "2024-02-29", summary: {v: 0.5}}], rank: 2, status: "closed"}}], + [{order: {years: 3, country: "gold", dueDate: "1990-06-15", status: "closed", members: [{score: -0, days: null, since: "2024-02-29"}], address: {amount: 0.1}}}, {order: {address: {amount: 0.1, discount: 2, eligible: false, exposure: 2, health: 1990, net: [3980], scores: {ok: 3}}, country: "gold", dueDate: "1990-06-15", level: ["gold", "gold", "gold"], margin: false, members: [{adjusted: [false], days: null, decision: "/false", score: 0, since: "2024-02-29", summary: {v: 0.1}}], rank: 2, status: "closed", years: 3}}], + [{order: {dueDate: "2024-02-29", status: "closed", members: [{score: 100, code: "x", days: 2, since: "2000-01-01"}, {code: null, days: 0.25, since: "2024-01-01"}, {days: null, since: "2000-01-01"}, {score: 65, code: "abc", days: null, since: "2024-01-01"}, {code: null, since: "2030-12-31"}, {score: 1000, code: null, days: null, since: "1990-06-15"}, {code: null, since: "1990-06-15"}, {score: 0, since: "1990-06-15"}], address: {amount: 99.99}}}, {order: {address: {amount: 99.99, discount: 2, eligible: false, exposure: 2, health: 2024, net: [4048], scores: {ok: 0}}, dueDate: "2024-02-29", level: ["", "", ""], margin: false, members: [{adjusted: [true], code: "x", days: 2, decision: "x/false", score: 100, since: "2000-01-01", summary: {v: 99.99}}, {adjusted: [true], code: null, days: 0.25, decision: "/false", since: "2024-01-01", summary: {v: 99.99}}, {adjusted: [true], days: null, decision: "/false", since: "2000-01-01", summary: {v: 99.99}}, {adjusted: [true], code: "abc", days: null, decision: "abc/false", score: 65, since: "2024-01-01", summary: {v: 99.99}}, {adjusted: [true], code: null, decision: "/false", since: "2030-12-31", summary: {v: 99.99}}, {adjusted: [true], code: null, days: null, decision: "/false", score: 1000, since: "1990-06-15", summary: {v: 99.99}}, {adjusted: [true], code: null, decision: "/false", since: "1990-06-15", summary: {v: 99.99}}, {adjusted: [true], decision: "/false", score: 0, since: "1990-06-15", summary: {v: 99.99}}], rank: 2, status: "closed"}}], + [{order: {years: 5, country: "gold", dueDate: "2025-03-20", status: "open", members: [{score: -0.01, code: "é ü", days: 18, since: "2030-12-31"}, {score: -0.5, code: "Oslo", days: 250, since: "2025-03-20T10:15:30Z"}, {score: 18, code: "gold", days: 2, since: "2025-03-20"}, {score: 5, code: "a-b-c", days: 5, since: "1990-06-15"}], address: {amount: 100}}}, {order: {address: {amount: 100, discount: 2, eligible: false, exposure: 2, health: 2025, net: [4050], scores: {ok: 5}}, country: "gold", dueDate: "2025-03-20", level: ["gold", "gold", "gold"], margin: true, members: [{adjusted: [false], code: "é ü", days: 18, decision: "é ü/false", score: -0.01, since: "2030-12-31", summary: {v: 100}}, {adjusted: [false], code: "Oslo", days: 250, decision: "Oslo/false", score: -0.5, since: "2025-03-20T10:15:30Z", summary: {v: 100}}, {adjusted: [false], code: "gold", days: 2, decision: "gold/false", score: 18, since: "2025-03-20", summary: {v: 100}}, {adjusted: [false], code: "a-b-c", days: 5, decision: "a-b-c/false", score: 5, since: "1990-06-15", summary: {v: 100}}], rank: 2, status: "open", years: 5}}], + [{order: {country: "gold", dueDate: "2025-03-20", status: "closed", members: [{score: 250, code: null, days: null, since: "2024-01-01"}], address: {amount: 1}}}, {order: {address: {amount: 1, discount: 2, eligible: false, exposure: 2, health: 2025, net: [4050], scores: {ok: 0}}, country: "gold", dueDate: "2025-03-20", level: ["gold", "gold", "gold"], margin: false, members: [{adjusted: [true], code: null, days: null, decision: "/false", score: 250, since: "2024-01-01", summary: {v: 1}}], rank: 2, status: "closed"}}], + [{order: {years: 1.5, country: "Zed", dueDate: "1990-06-15", status: "pending", members: [{score: 95, code: "Oslo", days: 50, since: "2025-03-20T10:15:30Z"}, {score: 100, code: "a-b-c", days: 0, since: "2024-01-01"}, {score: 10, code: "A1", days: 0, since: "2000-01-01"}], address: {amount: 123456789.123}}}, {order: {address: {amount: 123456789.123, discount: 2, eligible: false, exposure: 2, health: 1990, net: [3980], scores: {ok: 1.5}}, country: "Zed", dueDate: "1990-06-15", level: ["Zed", "Zed", "Zed"], margin: false, members: [{adjusted: [], code: "Oslo", days: 50, decision: "Oslo/false", score: 95, since: "2025-03-20T10:15:30Z", summary: {v: 123456789.123}}, {adjusted: [], code: "a-b-c", days: 0, decision: "a-b-c/false", score: 100, since: "2024-01-01", summary: {v: 123456789.123}}, {adjusted: [], code: "A1", days: 0, decision: "A1/false", score: 10, since: "2000-01-01", summary: {v: 123456789.123}}], rank: 2, status: "pending", years: 1.5}}], + [{order: {years: null, country: "A1", dueDate: "2030-12-31", status: "pending", members: [], address: {amount: 373}}}, {order: {address: {amount: 373, discount: 2, eligible: false, exposure: 2, health: 2030, net: [4060], scores: {ok: 0}}, country: "A1", dueDate: "2030-12-31", level: ["A1", "A1", "A1"], margin: false, members: [], rank: 2, status: "pending", years: null}}], + [{order: {years: 0.25, country: "US", dueDate: "2000-01-01", status: "pending", members: [], address: {amount: 0.000001}}}, {order: {address: {amount: 0.000001, discount: 2, eligible: false, exposure: 2, health: 2000, net: [4000], scores: {ok: 0.25}}, country: "US", dueDate: "2000-01-01", level: ["US", "US", "US"], margin: false, members: [], rank: 2, status: "pending", years: 0.25}}], + [{order: {years: 2, country: "NL", dueDate: "2030-12-31", status: "open", members: [{score: 1000, code: "VIP", days: 2, since: "2025-03-20"}, {score: 5, code: "US", days: 1, since: "2000-01-01"}, {score: 1.5, code: "DE", days: 0.25, since: "2000-01-01"}, {score: 7.25, code: "US", days: 1, since: "2000-01-01"}], address: {amount: 1}, extraField: "x"}}, {order: {address: {amount: 1, discount: 2, eligible: false, exposure: 2, health: 2030, net: [4060], scores: {ok: 2}}, country: "NL", dueDate: "2030-12-31", extraField: "x", level: ["NL", "NL", "NL"], margin: false, members: [{adjusted: [false], code: "VIP", days: 2, decision: "VIP/false", score: 1000, since: "2025-03-20", summary: {v: 1}}, {adjusted: [false], code: "US", days: 1, decision: "US/false", score: 5, since: "2000-01-01", summary: {v: 1}}, {adjusted: [false], code: "DE", days: 0.25, decision: "DE/false", score: 1.5, since: "2000-01-01", summary: {v: 1}}, {adjusted: [false], code: "US", days: 1, decision: "US/false", score: 7.25, since: "2000-01-01", summary: {v: 1}}], rank: 2, status: "open", years: 2}}], + [{order: {years: 250, country: "x", dueDate: "2000-01-01", status: "open", members: [{score: 250, code: "Zed", days: -0.01, since: "1990-06-15"}, {score: 99.99, code: "A1", days: 1.5, since: "1990-06-15"}, {score: 0.5, code: "3.5", days: 3, since: "1990-06-15"}, {score: 100, code: "gold", days: 50, since: "2024-02-29"}], address: {amount: 1000}}}, {order: {address: {amount: 1000, discount: 2, eligible: false, exposure: 2, health: 2000, net: [4000], scores: {ok: 3}}, country: "x", dueDate: "2000-01-01", level: ["x", "x", "x"], margin: false, members: [{adjusted: [false], code: "Zed", days: -0.01, decision: "Zed/false", score: 250, segment: false, since: "1990-06-15", summary: {v: 1000}}, {adjusted: [false], code: "A1", days: 1.5, decision: "A1/false", score: 99.99, segment: false, since: "1990-06-15", summary: {v: 1000}}, {adjusted: [false], code: "3.5", days: 3, decision: "3.5/false", score: 0.5, segment: false, since: "1990-06-15", summary: {v: 1000}}, {adjusted: [false], code: "gold", days: 50, decision: "gold/false", score: 100, segment: false, since: "2024-02-29", summary: {v: 1000}}], rank: 2, status: "open", years: 250}}], + [{order: {years: 0.000001, country: "O'Neil", dueDate: "2025-03-20T10:15:30Z", status: "pending", members: [{score: 5, code: "-", days: 2, since: "2025-03-20"}, {score: 1e3, code: " pad ", days: 0, since: "2024-02-29"}, {score: 3, code: " pad ", days: 0.000001, since: "2024-01-01"}, {score: 5, code: "Zed", days: 0, since: "2024-01-01"}, {score: 250, code: "Zed", days: -500, since: "2025-03-20"}], address: {amount: 18}}}, {order: {address: {amount: 18, discount: 2, eligible: false, exposure: 2, health: 2025, net: [4050], scores: {ok: 0.000001}}, country: "O'Neil", dueDate: "2025-03-20T10:15:30Z", level: ["O'Neil", "O'Neil", "O'Neil"], margin: false, members: [{adjusted: [false], code: "-", days: 2, decision: "-/false", score: 5, since: "2025-03-20", summary: {v: 18}}, {adjusted: [false], code: " pad ", days: 0, decision: " pad /false", score: 1000, since: "2024-02-29", summary: {v: 18}}, {adjusted: [false], code: " pad ", days: 0.000001, decision: " pad /false", score: 3, since: "2024-01-01", summary: {v: 18}}, {adjusted: [false], code: "Zed", days: 0, decision: "Zed/false", score: 5, since: "2024-01-01", summary: {v: 18}}, {adjusted: [false], code: "Zed", days: -500, decision: "Zed/false", score: 250, since: "2025-03-20", summary: {v: 18}}], rank: 2, status: "pending", years: 0.000001}}], + [{order: {years: 100, country: "DE", dueDate: "2025-03-20", status: "pending", members: [], address: {amount: 250}}}, {order: {address: {amount: 250, discount: 2, eligible: false, exposure: 2, health: 2025, net: [4050], scores: {ok: 3}}, country: "DE", dueDate: "2025-03-20", level: ["DE", "DE", "DE"], margin: false, members: [], rank: 2, status: "pending", years: 100}}], + [{order: {years: 0.000001, country: "DE", dueDate: "2024-01-01", status: "pending", members: [{score: 1, code: false, days: 10, since: "2024-01-01"}, {score: 2.50, code: "abc", days: 3, since: "2024-01-01"}, {score: 0.25, code: "Zed", days: 123456789.123, since: "2025-03-20T10:15:30Z"}, {score: 2, code: "A1", days: 18, since: "2030-12-31"}], address: {amount: 5}}}, "!error: InputValidationFailed"], + ], +} + +// seed 345900 (attempt 0) +{ + name: "b 60: account/companies/payments + address: 2 assertion, 5 expression, 2 match, 1 table; 3 root, 5 per-member, 2 top-level computed", + policy: { + models: {account: {qty: "number", name: "string?", active: "boolean?", companies: "company[]", address: "address"}, company: {score: "number", openedAt: "date", payments: "payment[]"}, payment: {income: "number", verified: "boolean", qty: "number?"}, address: {years: "number"}}, + blocks: [ + {assertion: "account.scores.band", conditions: [["and", "(account.grade and account.grade)", 1], ["and", "not (bonus)", 1], ["and", "isNumeric((split((account.name ?? ''), '-')[0] ?? 'none'))", 1], ["or", "(account.address.years >= 18 or ((account.active ?? false) and bonus))", 1]]}, + {expression: "flags.fee", value: "(account.address.years % (abs(account.address.years) + 1))"}, + {assertion: "account.grade", conditions: [["or", "trunc(account.qty) > account.qty", 1], ["or", "0 <= account.address.years", 1], ["and", "account.qty < 3", 0], ["and", "(account.address.years in (4..129] or account.address.years <= account.qty)", 1], ["or", "((account.active ?? false) and (account.active ?? false))", 2]]}, + {match: "account.scores.bucket", arms: [["startsWith((account.name ?? ''), 'VIP')", "(account.name ?? '')"], ["account.address.years < account.address.years", "'a'"], ["((account.active ?? false) and (account.active ?? false))", "(account.name ?? '')"], ["", "(account.name ?? '')"]]}, + {expression: "bonus", value: "account.qty in [-2..44]"}, + {expression: "address.discount", value: "(isNumeric(account.scores.bucket) ? account.active : null)"}, + {table: "t1", inputs: [null], outputs: ["address.eligible[]", "address.quota[]"], rules: [ + ["account.qty in [-3..157]", "(account.active ?? false)", "all(account.companies, #.score in [22..139])"], + ["", "(account.active ?? false)", ""], + ]}, + {expression: "company.adjusted", value: "{ok: (company.score / -6), n: (account.name ?? '')}"}, + {match: "company.exposure", arms: [["account.address.discount != null", "upper(string(bonus))"], ["account.qty >= account.qty", "company.adjusted.n"], ["", "((account.name ?? '') + '-' + account.scores.bucket)"]]}, + {expression: "company.calc.weighted", value: "company.openedAt"}, + ], + }, + cases: [ + [{account: {qty: -0.5, name: "3.5", active: false, companies: [{score: 0.5, openedAt: "2025-03-20T10:15:30Z", payments: [{income: -500, verified: false, qty: 100}, {income: 1, verified: true, qty: 100}, {income: 5, verified: false, qty: 18}]}], address: {years: 1}}}, {account: {active: false, address: {discount: false, eligible: [false, false], quota: [false], years: 1}, companies: [{calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "TRUE", openedAt: "2025-03-20T10:15:30Z", payments: [{income: -500, qty: 100, verified: false}, {income: 1, qty: 100, verified: true}, {income: 5, qty: 18, verified: false}], score: 0.5}], name: "3.5", qty: -0.5, scores: {bucket: "3.5"}}, bonus: true, flags: {fee: 1}}], + [{account: {qty: 0.5, active: true, companies: [{score: 3, openedAt: "2024-01-01", payments: [{income: 10, verified: true, qty: null}, {income: 1000000, verified: false, qty: null}]}, {score: 1e3, openedAt: "2025-03-20T10:15:30Z", payments: [{income: 0, verified: true}, {income: 1000000, verified: false, qty: 2}]}, {score: 10, openedAt: "2000-01-01", payments: []}, {score: 1000, openedAt: "2030-12-31", payments: []}], address: {years: -0.01}}}, {account: {active: true, address: {discount: null, eligible: [true, true], quota: [false], years: -0.01}, companies: [{adjusted: {n: "", ok: -0.50}, calc: {weighted: "2024-01-01"}, exposure: "", openedAt: "2024-01-01", payments: [{income: 10, qty: null, verified: true}, {income: 1000000, qty: null, verified: false}], score: 3}, {adjusted: {n: "", ok: -166.66666666666666666666666667}, calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "", openedAt: "2025-03-20T10:15:30Z", payments: [{income: 0, verified: true}, {income: 1000000, qty: 2, verified: false}], score: 1000}, {adjusted: {n: "", ok: -1.6666666666666666666666666667}, calc: {weighted: "2000-01-01"}, exposure: "", openedAt: "2000-01-01", payments: [], score: 10}, {adjusted: {n: "", ok: -166.66666666666666666666666667}, calc: {weighted: "2030-12-31"}, exposure: "", openedAt: "2030-12-31", payments: [], score: 1000}], qty: 0.5, scores: {bucket: ""}}, flags: {fee: -0.01}}], + [{account: {qty: -1, name: "VIP", active: true, companies: [], address: {years: 1000000}}}, {account: {active: true, address: {discount: null, eligible: [true, true], quota: [true], years: 1000000}, companies: [], name: "VIP", qty: -1, scores: {bucket: "VIP"}}, flags: {fee: 1000000}}], + [{account: {qty: 18, name: "-", active: true, companies: [{score: 18, openedAt: "1990-06-15", payments: [{income: -0, verified: false, qty: 1}, {income: -0, verified: true, qty: 123456789.123}]}], address: {years: 0.000001}}}, {account: {active: true, address: {discount: null, eligible: [true, true], quota: [false], years: 0.000001}, companies: [{adjusted: {n: "-", ok: -3}, calc: {weighted: "1990-06-15"}, exposure: "-", openedAt: "1990-06-15", payments: [{income: 0, qty: 1, verified: false}, {income: 0, qty: 123456789.123, verified: true}], score: 18}], name: "-", qty: 18, scores: {bucket: "-"}}, flags: {fee: 0.000001}}], + [{account: {qty: 0.5, name: "DE", active: false, companies: [{score: 5, openedAt: "2025-03-20T10:15:30Z", payments: []}, {score: 3, openedAt: "2025-03-20T10:15:30Z", payments: []}, {score: 99999999999999999999, openedAt: "1990-06-15", payments: [{income: 0.1, verified: true, qty: 18}, {income: 99.99, verified: true, qty: 0}]}], address: {years: -0.5}}}, {account: {active: false, address: {discount: null, eligible: [false, false], quota: [false], years: -0.5}, companies: [{adjusted: {n: "DE", ok: -0.8333333333333333333333333333}, calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "DE", openedAt: "2025-03-20T10:15:30Z", payments: [], score: 5}, {adjusted: {n: "DE", ok: -0.50}, calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "DE", openedAt: "2025-03-20T10:15:30Z", payments: [], score: 3}, {adjusted: {n: "DE", ok: -16666666666666666666.50}, calc: {weighted: "1990-06-15"}, exposure: "DE", openedAt: "1990-06-15", payments: [{income: 0.1, qty: 18, verified: true}, {income: 99.99, qty: 0, verified: true}], score: 99999999999999999999}], name: "DE", qty: 0.5, scores: {bucket: "DE"}}, flags: {fee: -0.5}}], + [{account: {qty: -1, active: true, companies: [{score: 1e3, openedAt: "2024-02-29", payments: []}], address: {years: 2.50}}}, {account: {active: true, address: {discount: null, eligible: [true, true], quota: [false], years: 2.50}, companies: [{adjusted: {n: "", ok: -166.66666666666666666666666667}, calc: {weighted: "2024-02-29"}, exposure: "", openedAt: "2024-02-29", payments: [], score: 1000}], qty: -1, scores: {bucket: ""}}, flags: {fee: 2.50}}], + [{account: {qty: 7.25, name: "a", active: false, companies: [], address: {years: 2}}}, {account: {active: false, address: {discount: null, eligible: [false, false], quota: [true], years: 2}, companies: [], name: "a", qty: 7.25, scores: {bucket: "a"}}, flags: {fee: 2}}], + [{account: {qty: 100, name: "retail", active: false, companies: [], address: {years: 100}}}, {account: {active: false, address: {discount: null, eligible: [false, false], quota: [true], years: 100}, companies: [], name: "retail", qty: 100, scores: {bucket: "retail"}}, flags: {fee: 100}}], + [{account: {qty: 2, name: "gold", active: true, companies: [{score: 1, openedAt: "2000-01-01", payments: [{income: 0.000001, verified: false, qty: -0}, {income: 1e3, verified: true, qty: 1e3}, {income: -0.01, verified: true, qty: 65}]}], address: {years: 99.99}}}, {account: {active: true, address: {discount: null, eligible: [true, true], quota: [false], years: 99.99}, companies: [{adjusted: {n: "gold", ok: -0.1666666666666666666666666667}, calc: {weighted: "2000-01-01"}, exposure: "gold", openedAt: "2000-01-01", payments: [{income: 0.000001, qty: 0, verified: false}, {income: 1000, qty: 1000, verified: true}, {income: -0.01, qty: 65, verified: true}], score: 1}], name: "gold", qty: 2, scores: {bucket: "gold"}}, flags: {fee: 99.99}}], + [{account: {qty: 18, name: "DE", active: null, companies: [{score: 1e3, openedAt: "2030-12-31", payments: [{income: -0, verified: true, qty: -0.01}, {income: -1, verified: false, qty: null}]}, {score: 100, openedAt: "2025-03-20T10:15:30Z", payments: [{income: 1e3, verified: false, qty: 65}, {income: 0.5, verified: false, qty: null}]}, {score: 2, openedAt: "2000-01-01", payments: [{income: 250, verified: true, qty: 3}, {income: -0, verified: true, qty: 0.5}]}, {score: 2.50, openedAt: "2024-02-29", payments: [{income: 0, verified: false, qty: 189}, {income: 99.99, verified: true, qty: null}]}, {score: -0, openedAt: "2030-12-31", payments: [{income: 2.50, verified: false, qty: null}, {income: 0.5, verified: true, qty: null}]}, {score: -0.5, openedAt: "2024-01-01", payments: []}, {score: 1, openedAt: "2025-03-20T10:15:30Z", payments: []}, {score: 0.5, openedAt: "2025-03-20", payments: [{income: 1000000, verified: true}, {income: 0, verified: false}, {income: 1000000, verified: false, qty: 5}]}, {score: -500, openedAt: "2025-03-20T10:15:30Z", payments: [{income: 100, verified: false}]}], address: {years: 65}}}, {account: {active: null, address: {discount: null, eligible: [false, false], quota: [false], years: 65}, companies: [{adjusted: {n: "DE", ok: -166.66666666666666666666666667}, calc: {weighted: "2030-12-31"}, exposure: "DE", openedAt: "2030-12-31", payments: [{income: 0, qty: -0.01, verified: true}, {income: -1, qty: null, verified: false}], score: 1000}, {adjusted: {n: "DE", ok: -16.666666666666666666666666667}, calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "DE", openedAt: "2025-03-20T10:15:30Z", payments: [{income: 1000, qty: 65, verified: false}, {income: 0.5, qty: null, verified: false}], score: 100}, {adjusted: {n: "DE", ok: -0.3333333333333333333333333333}, calc: {weighted: "2000-01-01"}, exposure: "DE", openedAt: "2000-01-01", payments: [{income: 250, qty: 3, verified: true}, {income: 0, qty: 0.5, verified: true}], score: 2}, {adjusted: {n: "DE", ok: -0.4166666666666666666666666667}, calc: {weighted: "2024-02-29"}, exposure: "DE", openedAt: "2024-02-29", payments: [{income: 0, qty: 189, verified: false}, {income: 99.99, qty: null, verified: true}], score: 2.50}, {adjusted: {n: "DE", ok: 0}, calc: {weighted: "2030-12-31"}, exposure: "DE", openedAt: "2030-12-31", payments: [{income: 2.50, qty: null, verified: false}, {income: 0.5, qty: null, verified: true}], score: 0}, {adjusted: {n: "DE", ok: 0.0833333333333333333333333333}, calc: {weighted: "2024-01-01"}, exposure: "DE", openedAt: "2024-01-01", payments: [], score: -0.5}, {adjusted: {n: "DE", ok: -0.1666666666666666666666666667}, calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "DE", openedAt: "2025-03-20T10:15:30Z", payments: [], score: 1}, {adjusted: {n: "DE", ok: -0.0833333333333333333333333333}, calc: {weighted: "2025-03-20"}, exposure: "DE", openedAt: "2025-03-20", payments: [{income: 1000000, verified: true}, {income: 0, verified: false}, {income: 1000000, qty: 5, verified: false}], score: 0.5}, {adjusted: {n: "DE", ok: 83.33333333333333333333333333}, calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "DE", openedAt: "2025-03-20T10:15:30Z", payments: [{income: 100, verified: false}], score: -500}], name: "DE", qty: 18, scores: {bucket: "DE"}}, flags: {fee: 65}}], + [{account: {qty: 370, name: "a", companies: [], address: {years: 99.99}}}, {account: {address: {discount: null, eligible: [false], quota: [], years: 99.99}, companies: [], name: "a", qty: 370, scores: {bucket: "a"}}, flags: {fee: 99.99}}], + [{account: {qty: 2, name: "O'Neil", active: 1, companies: [], address: {years: 1000000}}}, "!error: InputValidationFailed"], + [{account: {qty: 100, name: "a", active: false, companies: [{score: 250, openedAt: "2024-02-29", payments: []}, {score: 0.1, openedAt: "2000-01-01", payments: [{income: -0.5, verified: false, qty: 0.000001}]}, {score: -0, openedAt: "2024-02-29", payments: [{income: -1, verified: true, qty: -0.5}]}, {score: 100, openedAt: "2025-03-20T10:15:30Z", payments: []}, {score: 1e3, openedAt: "2024-02-29", payments: [{income: -0.5, verified: false, qty: 99.99}, {income: 18, verified: false, qty: -1}]}], address: {years: 334}, extraField: "x"}}, {account: {active: false, address: {discount: null, eligible: [false, false], quota: [false], years: 334}, companies: [{adjusted: {n: "a", ok: -41.666666666666666666666666667}, calc: {weighted: "2024-02-29"}, exposure: "a", openedAt: "2024-02-29", payments: [], score: 250}, {adjusted: {n: "a", ok: -0.0166666666666666666666666667}, calc: {weighted: "2000-01-01"}, exposure: "a", openedAt: "2000-01-01", payments: [{income: -0.5, qty: 0.000001, verified: false}], score: 0.1}, {adjusted: {n: "a", ok: 0}, calc: {weighted: "2024-02-29"}, exposure: "a", openedAt: "2024-02-29", payments: [{income: -1, qty: -0.5, verified: true}], score: 0}, {adjusted: {n: "a", ok: -16.666666666666666666666666667}, calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "a", openedAt: "2025-03-20T10:15:30Z", payments: [], score: 100}, {adjusted: {n: "a", ok: -166.66666666666666666666666667}, calc: {weighted: "2024-02-29"}, exposure: "a", openedAt: "2024-02-29", payments: [{income: -0.5, qty: 99.99, verified: false}, {income: 18, qty: -1, verified: false}], score: 1000}], extraField: "x", name: "a", qty: 100, scores: {bucket: "a"}}, flags: {fee: 334}}], + [{account: {qty: 18, active: false, companies: [{score: 0.000001, openedAt: "2024-01-01", payments: [{income: 65, verified: true, qty: null}, {income: 1e3, verified: false, qty: 1000}]}, {score: 0.000001, openedAt: "2025-03-20T10:15:30Z", payments: []}, {score: 18, openedAt: "1990-06-15", payments: [{income: 18, verified: true, qty: 99999999999999999999}, {income: 10, verified: true}, {income: 1e3, verified: false, qty: 10}]}], address: {years: 1e3}}}, {account: {active: false, address: {discount: null, eligible: [false, false], quota: [false], years: 1000}, companies: [{adjusted: {n: "", ok: -0.0000001666666666666666666667}, calc: {weighted: "2024-01-01"}, exposure: "", openedAt: "2024-01-01", payments: [{income: 65, qty: null, verified: true}, {income: 1000, qty: 1000, verified: false}], score: 0.000001}, {adjusted: {n: "", ok: -0.0000001666666666666666666667}, calc: {weighted: "2025-03-20T10:15:30Z"}, exposure: "", openedAt: "2025-03-20T10:15:30Z", payments: [], score: 0.000001}, {adjusted: {n: "", ok: -3}, calc: {weighted: "1990-06-15"}, exposure: "", openedAt: "1990-06-15", payments: [{income: 18, qty: 99999999999999999999, verified: true}, {income: 10, verified: true}, {income: 1000, qty: 10, verified: false}], score: 18}], qty: 18, scores: {bucket: ""}}, flags: {fee: 1000}}], + [{account: {qty: 250, name: "ok", active: false, companies: [], address: {years: -0.01}}}, {account: {active: false, address: {discount: null, eligible: [false], quota: [], years: -0.01}, companies: [], name: "ok", qty: 250, scores: {bucket: "ok"}}, flags: {fee: -0.01}}], + ], +} diff --git a/core/engine/tests/spec/policy/35-generated-goals.json5 b/core/engine/tests/spec/policy/35-generated-goals.json5 new file mode 100644 index 00000000..a2d97f28 --- /dev/null +++ b/core/engine/tests/spec/policy/35-generated-goals.json5 @@ -0,0 +1,2507 @@ +// Generated policies with random goal subsets. +// +// Generated by gen33.py + run33.py (`python3 run33.py goals` in the generator directory of the +// round-three spec session), seed 350000. Suite i is built from seed 350000 + 100 * i + +// attempt, where attempt is the first candidate whose policy has no error diagnostics. +// +// Each suite has a random data model: a root entity with 3-6 primitive fields (number, string, +// boolean, date, enum; about 30% optional) and one relationship array to a child entity with +// 2-4 fields, sometimes a number global, a second-level array under the child (read through +// aggregates) and a single relationship on the root. Its blocks (5-12 random expression, match, +// assertion and table blocks, in document order or shuffled) write undeclared computed +// properties on the root, on every member and at the top level; later blocks read earlier ones, +// giving chains, aggregates over member computeds and members reading root computeds. Flavor b +// adds nested write paths (`x.totals.y`), object, filter and map valued computeds, nullable +// computeds, a wider function set (templates, modulo, powers, division, regex, conversions, +// date methods) and occasional 8-14 member arrays. Each suite has 12-30 random inputs: valid, +// missing optional, null optional, boundary values, empty relationships, unknown fields and +// invalid requests (missing or null required, wrong type). Every case requests a random subset +// (1-3) of the computed properties as goals, or none (all terminal writes); the output is the +// input plus the writes of the goals' cones. +// +// Outputs recorded from the driver; this chapter exists to differential-test the engines. + +// seed 350000 (attempt 0) +{ + name: "goals 01: account/vehicles: 1 assertion, 2 expression, 3 match, 2 table; 1 root, 10 per-member, 1 top-level computed", + policy: { + models: {account: {balance: "number", weight: "number?", tier: "string(gold|silver|bronze)?", vehicles: "vehicle[]"}, vehicle: {score: "number?", flagged: "boolean?", years: "number", price: "number"}}, + blocks: [ + {expression: "vehicle.total", value: "map(account.vehicles, trunc(#.price))"}, + {match: "vehicle.net", arms: [["(vehicle.price in (32..201) or not ((vehicle.flagged ?? false)))", "(1.5 * vehicle.years)"], ["(vehicle.score ?? 0) != (account.weight ?? 0)", "((vehicle.flagged ?? false) ? 50 : 1.5)"], ["not ((vehicle.flagged ?? false))", "vehicle.years"], ["", "floor((vehicle.score ?? 0))"]]}, + {expression: "vehicle.calc.weighted", value: "{a: (vehicle.score ?? 0) == (account.weight ?? 0), n: (vehicle.flagged ?? false)}"}, + {match: "vehicle.summary", arms: [["not (vehicle.calc.weighted.n)", "string(vehicle.years != vehicle.years)"], ["not (vehicle.years in [46..66])", "'a'"], ["(account.weight ?? 0) in [45..76]", "'high'"], ["", "`${vehicle.calc.weighted.a}/${(account.weight ?? 0)}`"]]}, + {assertion: "account.points", conditions: [["and", "not (account.balance >= account.balance)", 0], ["and", "(account.balance <= 0.5 or 1.5 > 0.5)", 0], ["and", "account.balance in (6..96]", 1], "none(account.vehicles, #.price in (14..99))"]}, + {match: "totals.band", arms: [["not (account.points)", "(account.points ? (account.weight ?? 0) : account.balance) == account.balance"], ["(account.tier ?? '') in ['bronze', 'silver']", "account.points"], ["", "account.points"]]}, + {table: "t7", hit: "collect", inputs: ["vehicle.calc.weighted.n", "totals.band"], outputs: ["vehicle.decision", "vehicle.flag"], rules: [ + ["", "false", "vehicle.summary", "(avg(map(account.vehicles, len(#.summary))) ?? 0)"], + ["false", "false", "vehicle.summary", "vehicle.net"], + ["", "false", "'DE'", "(account.weight ?? 0)"], + ["true", "true", "vehicle.summary", "account.balance"], + ["", "false", "", "account.balance"], + ["false", "", "'low'", "(account.balance * vehicle.net)"], + ["", "", "vehicle.summary", "(vehicle.score ?? 0)"], + ]}, + {table: "t8", inputs: ["(vehicle.score ?? 0)", "vehicle.summary"], outputs: ["vehicle.penalty", "vehicle.meta.tag[]"], rules: [ + ["5", "", "(vehicle.score ?? 0)", "(account.weight ?? 0)"], + ["!= 0.5", "startsWith($, 'A1')", "", "len(filter(account.vehicles, (#.score ?? 0) >= 2))"], + ["", "$ != 'US'", "(avg(map(account.vehicles, #.price)) ?? 0)", "vehicle.years"], + ["", "'low', 'high'", "account.balance", "vehicle.net"], + ]}, + ], + }, + cases: [ + {input: {account: {balance: 2, weight: 3, tier: "gold", vehicles: []}}, goals: ["vehicle.net"], output: {account: {balance: 2, tier: "gold", vehicles: [], weight: 3}}}, + [{account: {balance: -0.01, weight: 2.50, tier: "bronze", vehicles: [{score: 1000000, flagged: true, years: 1000, price: 0.1}, {score: 0, flagged: false, years: 2, price: 1e3}]}}, {account: {balance: -0.01, points: false, tier: "bronze", vehicles: [{calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [-0.01, 1000000], flagged: true, meta: {tag: [1000]}, net: 50, penalty: 500.050, price: 0.1, score: 1000000, summary: "a", total: [0, 1000], years: 1000}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [-0.030, 0], flagged: false, meta: {tag: [2]}, net: 3.0, penalty: 500.050, price: 1000, score: 0, summary: "false", total: [0, 1000], years: 2}], weight: 2.50}, totals: {band: true}}], + {input: {account: {balance: 50, weight: 3, tier: "silver", vehicles: [{score: 99999999999999999999, flagged: null, years: 99.99, price: 5}]}}, goals: ["vehicle.calc.weighted", "totals.band", "vehicle.total"], output: {account: {balance: 50, points: false, tier: "silver", vehicles: [{calc: {weighted: {a: false, n: false}}, flagged: null, price: 5, score: 99999999999999999999, total: [5], years: 99.99}], weight: 3}, totals: {band: true}}}, + {input: {account: {balance: 7.25, weight: 1e3, tier: "gold", vehicles: [{score: 115, flagged: false, years: 3, price: 99.99}], extraField: "x"}}, goals: ["vehicle.total"], output: {account: {balance: 7.25, extraField: "x", tier: "gold", vehicles: [{flagged: false, price: 99.99, score: 115, total: [99], years: 3}], weight: 1000}}}, + {input: {account: {balance: 1e3, weight: 1.5, tier: "silver", vehicles: [{score: 1000, flagged: true, years: -0.01, price: 0.5}, {score: 0.5, flagged: false, years: 65, price: 3}]}}, goals: ["account.points"], output: {account: {balance: 1000, points: false, tier: "silver", vehicles: [{flagged: true, price: 0.5, score: 1000, years: -0.01}, {flagged: false, price: 3, score: 0.5, years: 65}], weight: 1.5}}}, + {input: {account: {balance: 0.5, weight: 0.000001, tier: "gold", vehicles: [{score: 1.5, flagged: true, years: -0.01, price: 2}, {score: 1000, flagged: false, years: -0, price: 5}]}}, goals: ["vehicle.penalty", "vehicle.total", "vehicle.flag"], output: {account: {balance: 0.5, points: false, tier: "gold", vehicles: [{calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [0.5, 1.5], flagged: true, meta: {tag: [-0.01]}, net: 50, penalty: 3.50, price: 2, score: 1.5, summary: "a", total: [2, 5], years: -0.01}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [0, 1000], flagged: false, meta: {tag: [0]}, net: 0, penalty: 3.50, price: 5, score: 1000, summary: "false", total: [2, 5], years: 0}], weight: 0.000001}, totals: {band: true}}}, + {input: {account: {balance: 0.25, weight: 0.000001, tier: "bronze", vehicles: [{score: 1.5, flagged: true, years: 1.5, price: 18}]}}, goals: ["vehicle.flag", "vehicle.decision", "vehicle.summary"], output: {account: {balance: 0.25, points: false, tier: "bronze", vehicles: [{calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [0.25, 1.5], flagged: true, price: 18, score: 1.5, summary: "a", years: 1.5}], weight: 0.000001}, totals: {band: true}}}, + {input: {account: {balance: 10, weight: 2.50, tier: "silver", vehicles: [{score: 2, flagged: false, years: -0, price: 10}]}}, goals: ["account.points"], output: {account: {balance: 10, points: false, tier: "silver", vehicles: [{flagged: false, price: 10, score: 2, years: 0}], weight: 2.50}}}, + {input: {account: {balance: 99.99, weight: 99999999999999999999, tier: "silver", vehicles: [{score: 1.5, flagged: false, years: -1, price: 65}, {score: 5, flagged: false, years: 1.5, price: 1000000}]}}, goals: ["totals.band", "vehicle.decision", "vehicle.meta.tag"], output: {account: {balance: 99.99, points: false, tier: "silver", vehicles: [{calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [-149.985, 1.5], flagged: false, meta: {tag: [-1]}, net: -1.5, penalty: 500032.50, price: 65, score: 1.5, summary: "false", years: -1}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [224.9775, 5], flagged: false, meta: {tag: [99999999999999999999, 1.5]}, net: 2.25, penalty: 5, price: 1000000, score: 5, summary: "false", years: 1.5}], weight: 99999999999999999999}, totals: {band: true}}}, + {input: {account: {balance: 1000, weight: 0.5, tier: "gold", vehicles: [{score: 1000, flagged: false, years: 65, price: 369}, {score: 99999999999999999999, flagged: false, years: 266, price: 0.1}]}}, goals: ["totals.band", "vehicle.net"], output: {account: {balance: 1000, points: false, tier: "gold", vehicles: [{flagged: false, net: 97.5, price: 369, score: 1000, years: 65}, {flagged: false, net: 399.0, price: 0.1, score: 99999999999999999999, years: 266}], weight: 0.5}, totals: {band: true}}}, + {input: {account: {balance: 50, weight: 50, tier: "bronze", vehicles: [{score: 1e3, flagged: false, years: 1.5, price: 99.99}, {score: 2.50, flagged: true, years: 1.5, price: 1.5}, {score: 10, flagged: false, years: 18, price: 5}, {score: -0, flagged: true, years: 0.5, price: 123456789.123}, {score: 50, flagged: false, years: 0.5, price: 2.50}]}}, goals: ["vehicle.total", "vehicle.summary", "account.points"], output: {account: {balance: 50, points: false, tier: "bronze", vehicles: [{calc: {weighted: {a: false, n: false}}, flagged: false, price: 99.99, score: 1000, summary: "false", total: [99, 1, 5, 123456789, 2], years: 1.5}, {calc: {weighted: {a: false, n: true}}, flagged: true, price: 1.5, score: 2.50, summary: "a", total: [99, 1, 5, 123456789, 2], years: 1.5}, {calc: {weighted: {a: false, n: false}}, flagged: false, price: 5, score: 10, summary: "false", total: [99, 1, 5, 123456789, 2], years: 18}, {calc: {weighted: {a: false, n: true}}, flagged: true, price: 123456789.123, score: 0, summary: "a", total: [99, 1, 5, 123456789, 2], years: 0.5}, {calc: {weighted: {a: true, n: false}}, flagged: false, price: 2.50, score: 50, summary: "false", total: [99, 1, 5, 123456789, 2], years: 0.5}], weight: 50}}}, + [{account: {balance: 2, weight: 2, tier: "gold", vehicles: [{score: 0.5, flagged: true, years: 18, price: 1000}, {score: 0.25, flagged: true, years: 18, price: 100}]}}, {account: {balance: 2, points: false, tier: "gold", vehicles: [{calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [2, 0.5], flagged: true, meta: {tag: [18]}, penalty: 550, price: 1000, score: 0.5, summary: "a", total: [1000, 100], years: 18}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [2, 0.25], flagged: true, meta: {tag: [18]}, penalty: 550, price: 100, score: 0.25, summary: "a", total: [1000, 100], years: 18}], weight: 2}, totals: {band: true}}], + {input: {account: {balance: 0.000001, weight: 1.5, tier: "bronze", vehicles: [{score: 1000, flagged: false, years: 100, price: 7.25}, {score: 99.99, flagged: false, years: 1000, price: 2}, {score: 99.99, flagged: false, years: -0.5, price: 99999999999999999999}, {score: -500, flagged: false, years: 0.1, price: -500}, {score: 1, flagged: true, years: 99999999999999999999, price: 64}]}}, goals: ["vehicle.decision", "vehicle.penalty", "vehicle.net"], output: {account: {balance: 0.000001, points: false, tier: "bronze", vehicles: [{calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [0.0001500, 1000], flagged: false, meta: {tag: [100]}, net: 150.0, penalty: 19999999999999999914.45, price: 7.25, score: 1000, summary: "false", years: 100}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [0.0015000, 99.99], flagged: false, meta: {tag: [1000]}, net: 1500.0, penalty: 19999999999999999914.45, price: 2, score: 99.99, summary: "false", years: 1000}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [-0.00000075, 99.99], flagged: false, meta: {tag: [-0.5]}, net: -0.75, penalty: 19999999999999999914.45, price: 99999999999999999999, score: 99.99, summary: "false", years: -0.5}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [0.00000015, -500], flagged: false, meta: {tag: [0.1]}, net: 0.15, penalty: 19999999999999999914.45, price: -500, score: -500, summary: "false", years: 0.1}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [0.000001, 1], flagged: true, meta: {tag: [99999999999999999999]}, net: 149999999999999999998.5, penalty: 19999999999999999914.45, price: 64, score: 1, summary: "a", years: 99999999999999999999}], weight: 1.5}, totals: {band: true}}}, + {input: {account: {balance: [1], weight: 0.1, tier: "gold", vehicles: [{score: 2.50, flagged: false, years: 0.25, price: 1000000}, {score: 1000, flagged: false, years: -500, price: -0}, {score: 0.5, flagged: true, years: -0, price: 1000}, {score: 1.5, flagged: false, years: 99.99, price: 250}, {score: 1000, flagged: false, years: 250, price: 0.000001}, {score: 100, flagged: true, years: 0.25, price: 1}, {score: 1.5, flagged: false, years: -500, price: 1.5}, {score: 1, flagged: false, years: 50, price: 2}, {score: 1.5, flagged: false, years: -1, price: 18}, {score: 1.5, flagged: true, years: 250, price: 18}, {score: 0.25, flagged: true, years: -0.01, price: 50}, {score: -1, flagged: false, years: 123456789.123, price: 2}, {score: 1000, flagged: false, years: 100, price: 0.5}, {score: 291, flagged: true, years: 291, price: 2}]}}, goals: ["vehicle.penalty"], output: "!error: InputValidationFailed"}, + {input: {account: {balance: 1.5, weight: 0.5, tier: "gold", vehicles: [{score: 1e3, flagged: true, years: 1.5, price: 0.1}, {score: -0.01, flagged: false, years: 123456789.123, price: 1000000}, {score: 50, flagged: false, years: 18, price: 0.25}, {score: 2, flagged: true, years: 0.1, price: 1000}, {score: 1e3, flagged: false, years: 0.5, price: 2}, {score: 65, flagged: false, years: 7.25, price: 65}, {score: 397, flagged: true, years: 2.50, price: -0.01}, {score: 10, flagged: false, years: 1.5, price: -0.5}, {score: 0.5, flagged: true, years: -0.5, price: 7.25}, {score: 18, flagged: true, years: 1000, price: 0.25}, {score: 1.5, flagged: false, years: 1000, price: 1}, {score: 0.5, flagged: true, years: 1, price: 0.000001}]}}, goals: ["vehicle.meta.tag", "vehicle.decision", "account.points"], output: {account: {balance: 1.5, points: false, tier: "gold", vehicles: [{calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [1.5, 1000], flagged: true, meta: {tag: [1.5]}, net: 50, penalty: 83422.94500008333333333333333, price: 0.1, score: 1000, summary: "a", years: 1.5}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [277777775.52675, -0.01], flagged: false, meta: {tag: [123456789.123]}, net: 185185183.6845, penalty: 83422.94500008333333333333333, price: 1000000, score: -0.01, summary: "false", years: 123456789.123}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [40.50, 50], flagged: false, meta: {tag: [18]}, net: 27.0, penalty: 83422.94500008333333333333333, price: 0.25, score: 50, summary: "false", years: 18}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [1.5, 2], flagged: true, meta: {tag: [0.1]}, net: 50, penalty: 83422.94500008333333333333333, price: 1000, score: 2, summary: "a", years: 0.1}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [1.125, 1000], flagged: false, meta: {tag: [0.5]}, net: 0.75, penalty: 83422.94500008333333333333333, price: 2, score: 1000, summary: "false", years: 0.5}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [16.3125, 65], flagged: false, meta: {tag: [7.25]}, net: 10.875, penalty: 83422.94500008333333333333333, price: 65, score: 65, summary: "false", years: 7.25}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [1.5, 397], flagged: true, meta: {tag: [2.50]}, net: 50, penalty: 83422.94500008333333333333333, price: -0.01, score: 397, summary: "a", years: 2.50}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [3.375, 10], flagged: false, meta: {tag: [1.5]}, net: 2.25, penalty: 83422.94500008333333333333333, price: -0.5, score: 10, summary: "false", years: 1.5}, {calc: {weighted: {a: true, n: true}}, decision: ["a", "a"], flag: [1.5, 0.5], flagged: true, meta: {tag: [-0.5]}, net: 0, penalty: 83422.94500008333333333333333, price: 7.25, score: 0.5, summary: "a", years: -0.5}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [1.5, 18], flagged: true, meta: {tag: [1000]}, net: 50, penalty: 83422.94500008333333333333333, price: 0.25, score: 18, summary: "a", years: 1000}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [2250.00, 1.5], flagged: false, meta: {tag: [1000]}, net: 1500.0, penalty: 83422.94500008333333333333333, price: 1, score: 1.5, summary: "false", years: 1000}, {calc: {weighted: {a: true, n: true}}, decision: ["a", "a"], flag: [1.5, 0.5], flagged: true, meta: {tag: [1]}, net: 0, penalty: 83422.94500008333333333333333, price: 0.000001, score: 0.5, summary: "a", years: 1}], weight: 0.5}, totals: {band: true}}}, + [{account: {balance: 1000, weight: 0.000001, tier: "gold", vehicles: [{score: 0.5, flagged: true, years: 1.5}]}}, "!error: ExpressionFailed"], + {input: {account: {balance: 1000, weight: 2.50, tier: "bronze", vehicles: [{score: 99.99, flagged: true, years: 99.99, price: 1}, {score: -0.5, flagged: false, years: 1000, price: 2}, {score: 5, flagged: false, years: 2, price: 1000}]}}, goals: ["vehicle.calc.weighted"], output: {account: {balance: 1000, tier: "bronze", vehicles: [{calc: {weighted: {a: false, n: true}}, flagged: true, price: 1, score: 99.99, years: 99.99}, {calc: {weighted: {a: false, n: false}}, flagged: false, price: 2, score: -0.5, years: 1000}, {calc: {weighted: {a: false, n: false}}, flagged: false, price: 1000, score: 5, years: 2}], weight: 2.50}}}, + {input: {account: {balance: 0.5, weight: 2, tier: "bronze", vehicles: [{score: 0.1, flagged: false, years: 250, price: 1}, {score: 0.000001, flagged: false, years: 5, price: 1.5}, {score: -0, flagged: true, years: -0.01, price: 65}, {score: 1e3, flagged: true, years: 0.5, price: 1.5}]}}, goals: ["vehicle.net"], output: {account: {balance: 0.5, tier: "bronze", vehicles: [{flagged: false, net: 375.0, price: 1, score: 0.1, years: 250}, {flagged: false, net: 7.5, price: 1.5, score: 0.000001, years: 5}, {flagged: true, net: -0.015, price: 65, score: 0, years: -0.01}, {flagged: true, net: 50, price: 1.5, score: 1000, years: 0.5}], weight: 2}}}, + [{account: {balance: 1000000, weight: 99999999999999999999, tier: "gold", vehicles: []}}, {account: {balance: 1000000, points: false, tier: "gold", vehicles: [], weight: 99999999999999999999}, totals: {band: true}}], + {input: {account: {balance: 1.5, weight: 1000, tier: null, vehicles: [{score: null, flagged: false, years: 10, price: 1.5}, {score: null, flagged: true, years: 18, price: 18}]}}, goals: ["vehicle.net", "vehicle.summary"], output: {account: {balance: 1.5, tier: null, vehicles: [{calc: {weighted: {a: false, n: false}}, flagged: false, net: 15.0, price: 1.5, score: null, summary: "false", years: 10}, {calc: {weighted: {a: false, n: true}}, flagged: true, net: 50, price: 18, score: null, summary: "a", years: 18}], weight: 1000}}}, + {input: {account: {balance: 3, vehicles: [{score: null, flagged: false, years: 1.5, price: 18}, {score: 10, years: 5, price: 3}]}}, goals: ["vehicle.total", "totals.band"], output: {account: {balance: 3, points: false, vehicles: [{flagged: false, price: 18, score: null, total: [18, 3], years: 1.5}, {price: 3, score: 10, total: [18, 3], years: 5}]}, totals: {band: true}}}, + {input: {account: {balance: 5, weight: 0.5, tier: false, vehicles: []}}, goals: ["vehicle.decision", "vehicle.net", "vehicle.calc.weighted"], output: "!error: InputValidationFailed"}, + {input: {account: {balance: 123456789.123, weight: null, tier: "gold", vehicles: [{score: 123456789.123, years: 100, price: 2}, {years: 444, price: 2}, {score: 2, flagged: null, years: 0, price: 2}, {years: 99.99, price: 14}, {score: 1, years: -0.01, price: 1000}, {score: 0.25, flagged: false, years: 0.5, price: 1000}, {score: 2.50, flagged: true, years: 1e3, price: -1}, {score: 2, flagged: true, years: 1000, price: -500}, {years: 99.99, price: 65}, {score: 1, flagged: false, years: 1000000, price: -0.5}, {score: 0.1, flagged: true, years: -1, price: 1e3}, {score: 1e3, flagged: false, years: 0.5, price: 1000}, {score: 1.5, flagged: false, years: 92, price: 123456789.123}, {score: 1000, flagged: null, years: 1000, price: 336}]}}, goals: ["totals.band", "vehicle.calc.weighted", "vehicle.flag"], output: {account: {balance: 123456789.123, points: false, tier: "gold", vehicles: [{calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [18518518368.4500, 123456789.123], net: 150.0, price: 2, score: 123456789.123, summary: "false", years: 100}, {calc: {weighted: {a: true, n: false}}, decision: ["low", "false"], flag: [82222221555.9180, 0], net: 666.0, price: 2, summary: "false", years: 444}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [0, 2], flagged: null, net: 0, price: 2, score: 2, summary: "false", years: 0}, {calc: {weighted: {a: true, n: false}}, decision: ["low", "false"], flag: [18516666516.613155, 0], net: 149.985, price: 14, summary: "false", years: 99.99}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [-1851851.836845, 1], net: -0.015, price: 1000, score: 1, summary: "false", years: -0.01}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [92592591.84225, 0.25], flagged: false, net: 0.75, price: 1000, score: 0.25, summary: "false", years: 0.5}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [123456789.123, 2.50], flagged: true, net: 50, price: -1, score: 2.50, summary: "a", years: 1000}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [123456789.123, 2], flagged: true, net: 50, price: -500, score: 2, summary: "a", years: 1000}, {calc: {weighted: {a: true, n: false}}, decision: ["low", "false"], flag: [18516666516.613155, 0], net: 149.985, price: 65, summary: "false", years: 99.99}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [185185183684500.0000, 1], flagged: false, net: 1500000.0, price: -0.5, score: 1, summary: "false", years: 1000000}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [123456789.123, 0.1], flagged: true, net: 50, price: 1000, score: 0.1, summary: "a", years: -1}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [92592591.84225, 1000], flagged: false, net: 0.75, price: 1000, score: 1000, summary: "false", years: 0.5}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [17037036898.9740, 1.5], flagged: false, net: 138.0, price: 123456789.123, score: 1.5, summary: "false", years: 92}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [185185183684.5000, 1000], flagged: null, net: 1500.0, price: 336, score: 1000, summary: "false", years: 1000}], weight: null}, totals: {band: true}}}, + {input: {account: {balance: 1.5, weight: 100, tier: "silver", vehicles: [{score: -1, flagged: true, years: 1000, price: 250}]}}, goals: ["vehicle.flag", "totals.band"], output: {account: {balance: 1.5, points: false, tier: "silver", vehicles: [{calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [1.5, -1], flagged: true, price: 250, score: -1, summary: "a", years: 1000}], weight: 100}, totals: {band: true}}}, + {input: {account: {balance: 18, weight: 123456789.123, tier: "gold", vehicles: [{score: 5, flagged: false, years: 1.5, price: -1}]}}, goals: ["vehicle.net", "vehicle.total", "vehicle.summary"], output: {account: {balance: 18, tier: "gold", vehicles: [{calc: {weighted: {a: false, n: false}}, flagged: false, net: 2.25, price: -1, score: 5, summary: "false", total: [-1], years: 1.5}], weight: 123456789.123}}}, + [{account: {balance: 1000000, weight: 250, tier: "gold", vehicles: [{score: 99999999999999999999, flagged: false, years: 7.25, price: 5}, {score: 1000, flagged: false, years: 0.5, price: 123456789.123}, {score: 1.5, flagged: true, years: 1000000, price: -500}]}}, {account: {balance: 1000000, points: false, tier: "gold", vehicles: [{calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [10875000.000, 99999999999999999999], flagged: false, meta: {tag: [7.25]}, net: 10.875, penalty: 41152098.041, price: 5, score: 99999999999999999999, summary: "false", total: [5, 123456789, -500], years: 7.25}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [750000.00, 1000], flagged: false, meta: {tag: [0.5]}, net: 0.75, penalty: 41152098.041, price: 123456789.123, score: 1000, summary: "false", total: [5, 123456789, -500], years: 0.5}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [1000000, 1.5], flagged: true, meta: {tag: [1000000]}, net: 50, penalty: 41152098.041, price: -500, score: 1.5, summary: "a", total: [5, 123456789, -500], years: 1000000}], weight: 250}, totals: {band: true}}], + {input: {account: {balance: 100, weight: 0.1, tier: "gold", vehicles: [{score: 1000, flagged: true, years: 99.99, price: 2}, {score: 247, flagged: true, years: 1, price: 10}, {score: 123456789.123, flagged: true, years: 10, price: 3}, {score: 3, flagged: false, years: 1.5, price: 1.5}, {score: 100, flagged: false, years: 123456789.123, price: 100}, {score: 123456789.123, flagged: true, years: 1.5, price: 1.5}, {score: 18, flagged: true, years: 3, price: 1.5}, {score: 5, flagged: false, years: 0.5, price: 2}, {score: 0, flagged: true, years: 0.5, price: 123456789.123}, {score: 0.000001, flagged: true, years: 7.25, price: 123456789.123}, {score: 1.5, flagged: true, years: 206, price: -0.01}, {score: 2, flagged: false, years: 0, price: 18}, {score: 0.25, flagged: true, years: 5, price: 250}]}}, goals: ["vehicle.flag"], output: {account: {balance: 100, points: false, tier: "gold", vehicles: [{calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 1000], flagged: true, net: 50, price: 2, score: 1000, summary: "a", years: 99.99}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 247], flagged: true, net: 50, price: 10, score: 247, summary: "a", years: 1}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 123456789.123], flagged: true, net: 50, price: 3, score: 123456789.123, summary: "a", years: 10}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [225.00, 3], flagged: false, net: 2.25, price: 1.5, score: 3, summary: "false", years: 1.5}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [18518518368.4500, 100], flagged: false, net: 185185183.6845, price: 100, score: 100, summary: "false", years: 123456789.123}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 123456789.123], flagged: true, net: 50, price: 1.5, score: 123456789.123, summary: "a", years: 1.5}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 18], flagged: true, net: 50, price: 1.5, score: 18, summary: "a", years: 3}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [75.00, 5], flagged: false, net: 0.75, price: 2, score: 5, summary: "false", years: 0.5}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 0], flagged: true, net: 50, price: 123456789.123, score: 0, summary: "a", years: 0.5}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 0.000001], flagged: true, net: 50, price: 123456789.123, score: 0.000001, summary: "a", years: 7.25}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 1.5], flagged: true, net: 50, price: -0.01, score: 1.5, summary: "a", years: 206}, {calc: {weighted: {a: false, n: false}}, decision: ["low", "false"], flag: [0, 2], flagged: false, net: 0, price: 18, score: 2, summary: "false", years: 0}, {calc: {weighted: {a: false, n: true}}, decision: ["a", "a"], flag: [100, 0.25], flagged: true, net: 50, price: 250, score: 0.25, summary: "a", years: 5}], weight: 0.1}, totals: {band: true}}}, + {input: {account: {balance: 2, weight: 0.1, tier: "gold", vehicles: [{score: 10, flagged: false, years: 100, price: 99.99}, {score: 0.5, flagged: false, years: -0.5, price: 2}, {score: 100, flagged: false, years: 0.1, price: 50}], extraField: {nested: true}}}, goals: ["account.points", "vehicle.net", "totals.band"], output: {account: {balance: 2, extraField: {nested: true}, points: false, tier: "gold", vehicles: [{flagged: false, net: 150.0, price: 99.99, score: 10, years: 100}, {flagged: false, net: -0.75, price: 2, score: 0.5, years: -0.5}, {flagged: false, net: 0.15, price: 50, score: 100, years: 0.1}], weight: 0.1}, totals: {band: true}}}, + ], +} + +// seed 350100 (attempt 0) +{ + name: "goals 02: claim/members + profile: 3 expression, 2 match, 2 table; 4 root, 1 per-member, 3 top-level computed", + policy: { + models: {claim: {limit: "number?", income: "number", active: "boolean", status: "string(open|closed|pending)", members: "member[]?", profile: "profile"}, member: {years: "number", label: "string?", channel: "string", verified: "boolean"}, profile: {age: "number?"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {expression: "member.ok", value: "(member.years) / (abs((claim.limit ?? 0)) + 1)"}, + {match: "claim.level", arms: [["((claim.profile.age ?? 0) in [44..50] or net in ['VIP', 'A1'])", "`${net}/${claim.active}`"], ["(some((claim.members ?? []), (#.verified or #.verified)) and (claim.profile.age ?? 0) in [45..170])", "'x'"], ["not (claim.active)", "'retail'"], ["", "net"]]}, + {expression: "claim.quota", value: "{a: none((claim.members ?? []), contains(['retail', 'high', ''], #.channel)), n: claim.income}"}, + {table: "t4", hit: "collect", inputs: [null, "(claim.limit ?? 0)", "(claim.limit ?? 0)"], outputs: ["eligible"], rules: [ + ["claim.income != (claim.limit ?? 0)", "<= 50", "> 0", "claim.level"], + ["(claim.active and claim.active)", "0.5", "0.25, 5", "'low'"], + ["(claim.profile.age ?? 0) in (0..58)", "[100..579]", "[100..278]", "net"], + ["1.5 == (claim.limit ?? 0)", "1000, 18", "", "'A1'"], + ]}, + {match: "bucket", arms: [["isNumeric(net)", "(claim.active ? claim.level : net)"], ["all((claim.members ?? []), matches(#.channel, '^.{2,}$'))", "(net + '-' + claim.level)"], ["claim.quota.n in (30..88)", "string(round(baseRate / 7, 0))"], ["baseRate > baseRate", "claim.level"], ["", "net"]]}, + {expression: "net", value: "(claim.active ? 'gold' : 'retail')"}, + {table: "t1", hit: "collect", inputs: ["claim.income", "claim.income", "claim.active"], outputs: ["profile.totals.points", "profile.meta.margin", "profile.meta.review"], rules: [ + ["[1..228]", "", "false", "'x'", "", "'low'"], + ["10, 2", "", "", "'a'", "(claim.limit ?? 0)", "`${claim.active}/${claim.active}`"], + ["[0.5..140.5]", "< 0.5", "false", "'none'", "sum(map((claim.members ?? []), #.years))", "`${claim.active}/${claim.income}`"], + ["[0.25..211.25]", ">= 0.25", "", "'A1'", "(claim.limit ?? 0)", "'A1'"], + ["[0.25..163.25]", "!= 2", "", "string(claim.active)", "", "'VIP'"], + ["> 0.25", "<= 100", "false", "'high'", "(profile.age ?? 0)", "'none'"], + ]}, + ], + }, + cases: [ + [{baseRate: 10, claim: {limit: 50, income: 3, active: true, status: "pending", members: [{years: null, label: "a", channel: "low", verified: false}, {years: 100, label: "O'Neil", channel: "12", verified: false}, {years: 0.000001, label: "VIP", channel: "A1", verified: true}, {years: 5, label: "gold", channel: "VIP", verified: false}, {years: 5, label: "x", channel: "12", verified: false}], profile: {age: 10}}}, "!error: ExpressionFailed"], + {input: {baseRate: 10, claim: {limit: 3, income: 18, active: true, status: "closed", profile: {age: 99999999999999999999}}}, goals: ["claim.quota", "claim.level", "profile.meta.margin"], output: {baseRate: 10, claim: {active: true, income: 18, level: "gold", limit: 3, profile: {age: 99999999999999999999, meta: {margin: [3], review: ["A1", "VIP"]}, totals: {points: ["A1", "true"]}}, quota: {a: true, n: 18}, status: "closed"}, net: "gold"}}, + {input: {baseRate: 0, claim: {limit: -500, income: 0, active: false, status: "pending", members: [{years: 0.5, label: "retail", channel: "retail", verified: false}, {years: 3, label: "retail", channel: "none", verified: false}], profile: {age: 0.5}}}, goals: ["claim.quota", "profile.totals.points"], output: {baseRate: 0, claim: {active: false, income: 0, limit: -500, members: [{channel: "retail", label: "retail", verified: false, years: 0.5}, {channel: "none", label: "retail", verified: false, years: 3}], profile: {age: 0.5, meta: {margin: [], review: []}, totals: {points: []}}, quota: {a: false, n: 0}, status: "pending"}}}, + {input: {baseRate: 10, claim: {limit: 5, income: 1000000, active: false, status: "pending", members: [{years: 99999999999999999999, label: "3.5", channel: "abc", verified: true}, {years: 100, label: "US", channel: "-", verified: true}, {years: 1, label: "A1", channel: "a", verified: false}, {years: 100, label: "ok", channel: "low", verified: true}, {years: 250, label: "none", channel: "Zed", verified: false}], profile: {age: 123456789.123}}}, goals: ["profile.totals.points", "eligible", "claim.quota"], output: {baseRate: 10, claim: {active: false, income: 1000000, level: "retail", limit: 5, members: [{channel: "abc", label: "3.5", verified: true, years: 99999999999999999999}, {channel: "-", label: "US", verified: true, years: 100}, {channel: "a", label: "A1", verified: false, years: 1}, {channel: "low", label: "ok", verified: true, years: 100}, {channel: "Zed", label: "none", verified: false, years: 250}], profile: {age: 123456789.123, meta: {margin: [], review: []}, totals: {points: []}}, quota: {a: true, n: 1000000}, status: "pending"}, eligible: ["retail"], net: "retail"}}, + {input: {baseRate: 0.5, claim: {limit: 1, income: 100, active: true, status: "pending", members: [{years: 100, label: "gold", channel: "none", verified: true}, {years: 1e3, label: "none", channel: "Zed", verified: false}], profile: {age: 0.000001}}}, goals: ["member.ok"], output: {baseRate: 0.5, claim: {active: true, income: 100, limit: 1, members: [{channel: "none", label: "gold", ok: 50, verified: true, years: 100}, {channel: "Zed", label: "none", ok: 500, verified: false, years: 1000}], profile: {age: 0.000001}, status: "pending"}}}, + {input: {baseRate: 0.5, claim: {limit: 10, income: 1, active: true, status: "open", members: [{years: 1000000, label: "A1", channel: "low", verified: true}, {years: 0.25, label: "gold", channel: "3.5", verified: false}, {years: 99999999999999999999, label: "US", channel: "high", verified: false}, {years: 0.25, label: "US", channel: "low", verified: true}], profile: {age: 250}}}, goals: ["profile.meta.margin"], output: {baseRate: 0.5, claim: {active: true, income: 1, limit: 10, members: [{channel: "low", label: "A1", verified: true, years: 1000000}, {channel: "3.5", label: "gold", verified: false, years: 0.25}, {channel: "high", label: "US", verified: false, years: 99999999999999999999}, {channel: "low", label: "US", verified: true, years: 0.25}], profile: {age: 250, meta: {margin: [10], review: ["A1", "VIP"]}, totals: {points: ["A1", "true"]}}, status: "open"}}}, + {input: {baseRate: 1, claim: {limit: 100, income: 1, active: true, status: "pending", members: [{years: 0, channel: "a", verified: false}, {years: 99999999999999999999, label: " pad ", channel: "none", verified: true}], profile: {}}}, goals: ["claim.level", "net"], output: {baseRate: 1, claim: {active: true, income: 1, level: "gold", limit: 100, members: [{channel: "a", verified: false, years: 0}, {channel: "none", label: " pad ", verified: true, years: 99999999999999999999}], profile: {}, status: "pending"}, net: "gold"}}, + {input: {baseRate: 0.5, claim: {income: 0.1, active: false, status: "closed", members: [], profile: {}}}, goals: ["claim.quota", "claim.level"], output: {baseRate: 0.5, claim: {active: false, income: 0.1, level: "retail", members: [], profile: {}, quota: {a: true, n: 0.1}, status: "closed"}, net: "retail"}}, + {input: {baseRate: 100, claim: {limit: 0.25, income: 5, active: false, status: "pending", members: [{years: -1, label: "VIP", channel: "none", verified: true}], profile: {age: 0.5}}}, goals: ["profile.totals.points", "member.ok"], output: {baseRate: 100, claim: {active: false, income: 5, limit: 0.25, members: [{channel: "none", label: "VIP", ok: -0.8, verified: true, years: -1}], profile: {age: 0.5, meta: {margin: [0.25, 0.5], review: ["low", "A1", "VIP", "none"]}, totals: {points: ["x", "A1", "false", "high"]}}, status: "pending"}}}, + [{baseRate: 100, claim: {limit: 2, income: 2, active: false, status: "closed", members: [{years: 10, label: "A1", channel: "VIP", verified: false}, {years: 3, label: "high", channel: "x", verified: true}, {years: 0.25, label: "a", channel: "x", verified: false}, {years: -0, label: " pad ", channel: "high", verified: true}, {years: -500, label: "A1", channel: "A1", verified: true}, {years: 99999999999999999999, label: "DE", channel: "Oslo", verified: false}, {years: 0.25, label: "low", channel: "none", verified: false}, {years: 1000000, label: "retail", channel: "VIP", verified: true}], profile: {age: 0.000001}}}, {baseRate: 100, bucket: "retail", claim: {active: false, income: 2, limit: 2, members: [{channel: "VIP", label: "A1", ok: 3.3333333333333333333333333333, verified: false, years: 10}, {channel: "x", label: "high", ok: 1, verified: true, years: 3}, {channel: "x", label: "a", ok: 0.0833333333333333333333333333, verified: false, years: 0.25}, {channel: "high", label: " pad ", ok: 0, verified: true, years: 0}, {channel: "A1", label: "A1", ok: -166.66666666666666666666666667, verified: true, years: -500}, {channel: "Oslo", label: "DE", ok: 33333333333333333333, verified: false, years: 99999999999999999999}, {channel: "none", label: "low", ok: 0.0833333333333333333333333333, verified: false, years: 0.25}, {channel: "VIP", label: "retail", ok: 333333.33333333333333333333333, verified: true, years: 1000000}], profile: {age: 0.000001, meta: {margin: [2, 2, 0.000001], review: ["low", "false/false", "A1", "none"]}, totals: {points: ["x", "a", "A1", "high"]}}, quota: {a: false, n: 2}, status: "closed"}, eligible: [], net: "retail"}], + {input: {baseRate: 0, claim: {limit: 123456789.123, income: 10, active: true, status: "closed", members: [], profile: {age: 0.25}}}, goals: ["profile.totals.points", "eligible"], output: {baseRate: 0, claim: {active: true, income: 10, limit: 123456789.123, members: [], profile: {age: 0.25, meta: {margin: [123456789.123, 123456789.123], review: ["true/true", "A1", "VIP"]}, totals: {points: ["a", "A1", "true"]}}, status: "closed"}, eligible: []}}, + {input: {baseRate: 100, claim: {limit: null, income: 100, active: true, status: "closed", members: [{years: 0.25, label: null, channel: "a", verified: true}], profile: {age: null}}}, goals: ["claim.quota"], output: {baseRate: 100, claim: {active: true, income: 100, limit: null, members: [{channel: "a", label: null, verified: true, years: 0.25}], profile: {age: null}, quota: {a: true, n: 100}, status: "closed"}}}, + {input: {baseRate: 0, claim: {limit: -0.5, income: 2, active: true, status: "closed", members: [{years: 5, label: "gold", channel: "x", verified: false}, {years: 0, channel: "ok", verified: true}], profile: {age: null}}}, goals: ["profile.meta.margin", "profile.meta.review"], output: {baseRate: 0, claim: {active: true, income: 2, limit: -0.5, members: [{channel: "x", label: "gold", verified: false, years: 5}, {channel: "ok", verified: true, years: 0}], profile: {age: null, meta: {margin: [-0.5, -0.5], review: ["true/true", "A1"]}, totals: {points: ["a", "A1"]}}, status: "closed"}}}, + {input: {baseRate: 1, claim: {income: 10, active: false, status: "closed", members: [{years: 2, label: "none", channel: "A1", verified: true}, {years: 1, label: "é ü", channel: "none", verified: false}], profile: {}}}, goals: ["profile.totals.points", "bucket", "profile.meta.margin"], output: {baseRate: 1, bucket: "retail-retail", claim: {active: false, income: 10, level: "retail", members: [{channel: "A1", label: "none", verified: true, years: 2}, {channel: "none", label: "é ü", verified: false, years: 1}], profile: {meta: {margin: [0, 0, 0], review: ["low", "false/false", "A1", "VIP", "none"]}, totals: {points: ["x", "a", "A1", "false", "high"]}}, quota: {a: true, n: 10}, status: "closed"}, net: "retail"}}, + ], +} + +// seed 350200 (attempt 0) +{ + name: "goals 03: claim/lines: 1 assertion, 2 match, 2 table; 6 root, 1 per-member, 1 top-level computed", + policy: { + models: {claim: {rate: "number", verified: "boolean?", weight: "number", age: "number", insured: "boolean?", flagged: "boolean?", lines: "line[]?"}, line: {limit: "number", sku: "string"}}, + blocks: [ + {table: "t5", inputs: ["calc.tag", "(claim.health ?? 0)", "(claim.insured ?? false)"], outputs: ["claim.exposure", "claim.weighted", "claim.margin"], rules: [ + ["true", "", "", "claim.age in [18..174]", "(claim.verified ?? false)", "((claim.verified ?? false) ? claim.weight : claim.rate)"], + ["false", "[2..19]", "false", "claim.age == claim.weight", "calc.tag", "claim.rank"], + ["", "", "", "(claim.insured ?? false)", "claim.rank != 50", "50"], + ]}, + {match: "claim.rank", arms: [["claim.age == 10", "claim.weight"], ["(not ((claim.insured ?? false)) and ((claim.flagged ?? false) and (claim.insured ?? false)))", "(trunc(claim.weight) + len(filter((claim.lines ?? []), not (#.limit == 18))))"], ["not (none((claim.lines ?? []), not (#.limit <= 100)))", "-(claim.rate)"], ["", "claim.weight"]]}, + {assertion: "calc.tag", conditions: ["claim.verified == null", ["or", "isNumeric(`${(claim.discount ?? '')}/${(claim.flagged ?? false)}`)", 1], ["or", "((claim.verified ?? false) or (claim.insured ?? false))", 0], ["or", "(claim.discount ?? '') == 'none'", 0], "(claim.health ?? 0) <= (claim.health ?? 0)"]}, + {table: "t3", inputs: ["claim.weight"], outputs: ["claim.health", "claim.discount"], rules: [ + ["< 0.5", "round(claim.rate / 7, 1)", ""], + ["[5..7]", "claim.rate", "`${2}/${claim.rate}`"], + ["< 1.5", "claim.age", "'Oslo'"], + ["", "claim.rank", "'US'"], + ["[1000..1473]", "250", "'US'"], + ["<= 5", "claim.weight", "'A1'"], + ]}, + {match: "line.decision", arms: [["line.limit < 250", "line.sku"], ["", "line.sku"]]}, + ], + }, + cases: [ + {input: {claim: {rate: 50, verified: null, weight: -500, age: 18, insured: true, flagged: null, lines: [{limit: 50, sku: ""}, {limit: 2, sku: "a"}, {limit: 5, sku: "A1"}, {limit: 100, sku: "US"}, {limit: 65, sku: "12"}]}}, goals: ["claim.discount"], output: {claim: {age: 18, discount: "Oslo", flagged: null, health: 7.1, insured: true, lines: [{limit: 50, sku: ""}, {limit: 2, sku: "a"}, {limit: 5, sku: "A1"}, {limit: 100, sku: "US"}, {limit: 65, sku: "12"}], rate: 50, verified: null, weight: -500}}}, + {input: {claim: {rate: 99999999999999999999, verified: true, weight: 250, age: 250, insured: true, flagged: true, lines: []}}, goals: ["line.decision", "claim.exposure"], output: {calc: {tag: true}, claim: {age: 250, discount: "US", exposure: false, flagged: true, health: 250, insured: true, lines: [], margin: 250, rank: 250, rate: 99999999999999999999, verified: true, weight: 250, weighted: true}}}, + {input: {claim: {rate: 1000, verified: false, weight: -0.5, age: -0, insured: false, flagged: false, lines: []}}, goals: ["claim.health", "claim.margin"], output: {calc: {tag: true}, claim: {age: 0, discount: "Oslo", exposure: false, flagged: false, health: 142.9, insured: false, lines: [], margin: 1000, rate: 1000, verified: false, weight: -0.5, weighted: false}}}, + {input: {claim: {rate: 2, verified: false, weight: 1000, age: 10, insured: true, flagged: false, lines: []}}, goals: ["claim.weighted"], output: {calc: {tag: true}, claim: {age: 10, discount: "US", exposure: false, flagged: false, health: 1000, insured: true, lines: [], margin: 2, rank: 1000, rate: 2, verified: false, weight: 1000, weighted: false}}}, + {input: {claim: {rate: 0, verified: true, weight: -500, age: 123456789.123, insured: false, flagged: true, lines: [{limit: 5, sku: "none"}, {limit: 0.5, sku: "retail"}], extraField: {nested: true}}}, goals: ["claim.health", "claim.exposure"], output: {calc: {tag: true}, claim: {age: 123456789.123, discount: "Oslo", exposure: false, extraField: {nested: true}, flagged: true, health: 0, insured: false, lines: [{limit: 5, sku: "none"}, {limit: 0.5, sku: "retail"}], margin: -500, rate: 0, verified: true, weight: -500, weighted: true}}}, + [{claim: {rate: 18, verified: false, weight: 1000, age: 2, insured: true, flagged: false, lines: [{limit: 1, sku: "a"}]}}, {calc: {tag: true}, claim: {age: 2, discount: "US", exposure: false, flagged: false, health: 1000, insured: true, lines: [{decision: "a", limit: 1, sku: "a"}], margin: 18, rank: 1000, rate: 18, verified: false, weight: 1000, weighted: false}}], + {input: {claim: {rate: 2, verified: false, weight: -1, age: 65, insured: true, lines: [{limit: 250, sku: "VIP"}, {limit: 18, sku: "retail"}, {limit: 99999999999999999999, sku: "A1"}, {limit: -0, sku: "A1"}, {limit: -0.01, sku: " pad "}, {limit: 5, sku: "12"}, {limit: 5, sku: "retail"}, {limit: 100, sku: "DE"}]}}, goals: ["claim.rank"], output: {claim: {age: 65, insured: true, lines: [{limit: 250, sku: "VIP"}, {limit: 18, sku: "retail"}, {limit: 99999999999999999999, sku: "A1"}, {limit: 0, sku: "A1"}, {limit: -0.01, sku: " pad "}, {limit: 5, sku: "12"}, {limit: 5, sku: "retail"}, {limit: 100, sku: "DE"}], rank: -2, rate: 2, verified: false, weight: -1}}}, + {input: {claim: {rate: 100, weight: 18, age: 1, insured: false, flagged: true, lines: [{limit: 0.000001, sku: "O'Neil"}, {limit: 2, sku: "US"}]}}, goals: ["claim.weighted", "claim.margin"], output: {calc: {tag: true}, claim: {age: 1, discount: "US", exposure: false, flagged: true, health: 18, insured: false, lines: [{limit: 0.000001, sku: "O'Neil"}, {limit: 2, sku: "US"}], margin: 100, rank: 18, rate: 100, weight: 18, weighted: false}}}, + {input: {claim: {rate: 100, verified: null, weight: 100, age: 65, insured: false, flagged: null, lines: [{limit: 234, sku: "DE"}, {limit: 2.50, sku: ""}]}}, goals: ["claim.rank", "claim.weighted", "claim.exposure"], output: {calc: {tag: true}, claim: {age: 65, discount: "US", exposure: true, flagged: null, health: -100, insured: false, lines: [{limit: 234, sku: "DE"}, {limit: 2.50, sku: ""}], margin: 100, rank: -100, rate: 100, verified: null, weight: 100, weighted: false}}}, + {input: {claim: {rate: 1, verified: false, weight: 2, age: 18, insured: false, flagged: null, lines: [{limit: 18, sku: "日本"}, {limit: 2, sku: "Zed"}, {limit: 5, sku: "retail"}, {limit: 2, sku: "é ü"}, {limit: 5, sku: "Oslo"}, {limit: 5, sku: "3.5"}, {limit: -0.5, sku: " pad "}, {limit: 5, sku: "O'Neil"}, {limit: 18, sku: "US"}]}}, goals: ["calc.tag", "claim.rank"], output: {calc: {tag: true}, claim: {age: 18, discount: "US", flagged: null, health: 2, insured: false, lines: [{limit: 18, sku: "日本"}, {limit: 2, sku: "Zed"}, {limit: 5, sku: "retail"}, {limit: 2, sku: "é ü"}, {limit: 5, sku: "Oslo"}, {limit: 5, sku: "3.5"}, {limit: -0.5, sku: " pad "}, {limit: 5, sku: "O'Neil"}, {limit: 18, sku: "US"}], rank: 2, rate: 1, verified: false, weight: 2}}}, + {input: {claim: {rate: 0.1, verified: false, weight: 18, age: 2.50, flagged: false, lines: [{limit: -500, sku: "US"}, {limit: 0.1, sku: "gold"}, {limit: 50, sku: "US"}, {limit: 72, sku: "US"}]}}, goals: ["claim.rank", "claim.health"], output: {claim: {age: 2.50, discount: "US", flagged: false, health: 18, lines: [{limit: -500, sku: "US"}, {limit: 0.1, sku: "gold"}, {limit: 50, sku: "US"}, {limit: 72, sku: "US"}], rank: 18, rate: 0.1, verified: false, weight: 18}}}, + {input: {claim: {rate: 250, verified: false, weight: 440, age: -500, insured: false, flagged: true, lines: [{limit: 123456789.123, sku: "O'Neil"}, {limit: 100, sku: "a-b-c"}, {limit: 65, sku: "é ü"}, {limit: 100, sku: "Oslo"}, {limit: 0.5, sku: "DE"}]}}, goals: ["claim.rank", "claim.health"], output: {claim: {age: -500, discount: "US", flagged: true, health: -250, insured: false, lines: [{limit: 123456789.123, sku: "O'Neil"}, {limit: 100, sku: "a-b-c"}, {limit: 65, sku: "é ü"}, {limit: 100, sku: "Oslo"}, {limit: 0.5, sku: "DE"}], rank: -250, rate: 250, verified: false, weight: 440}}}, + {input: {claim: {rate: 123456789.123, verified: true, weight: 18, age: 1, insured: true, flagged: false, lines: []}}, goals: ["claim.weighted"], output: {calc: {tag: true}, claim: {age: 1, discount: "US", exposure: false, flagged: false, health: 18, insured: true, lines: [], margin: 18, rank: 18, rate: 123456789.123, verified: true, weight: 18, weighted: true}}}, + {input: {claim: {rate: 2, verified: false, weight: 0.5, age: 250, insured: true, flagged: false, lines: [{limit: 50, sku: "-"}]}}, goals: ["claim.discount"], output: {claim: {age: 250, discount: "Oslo", flagged: false, health: 250, insured: true, lines: [{limit: 50, sku: "-"}], rate: 2, verified: false, weight: 0.5}}}, + {input: {claim: {rate: 250, weight: 123456789.123, age: 100, insured: null, flagged: false, lines: []}}, goals: ["calc.tag"], output: {calc: {tag: true}, claim: {age: 100, discount: "US", flagged: false, health: 123456789.123, insured: null, lines: [], rank: 123456789.123, rate: 250, weight: 123456789.123}}}, + {input: {claim: {rate: 5, verified: null, weight: 5, age: 250, insured: null, flagged: null, lines: null}}, goals: ["claim.health", "claim.margin", "calc.tag"], output: {calc: {tag: true}, claim: {age: 250, discount: "2/5", exposure: false, flagged: null, health: 5, insured: null, lines: null, margin: 5, rate: 5, verified: null, weight: 5, weighted: false}}}, + {input: {claim: {rate: 0.5, verified: false, weight: 1000000, age: 2, insured: true, flagged: true, lines: []}}, goals: ["claim.health"], output: {claim: {age: 2, discount: "US", flagged: true, health: 1000000, insured: true, lines: [], rank: 1000000, rate: 0.5, verified: false, weight: 1000000}}}, + [{claim: {rate: 0.5, verified: true, weight: -0, age: 0.5, insured: false, flagged: false, lines: [{limit: 5, sku: "A1"}, {limit: -0, sku: " pad "}]}}, {calc: {tag: true}, claim: {age: 0.5, discount: "Oslo", exposure: false, flagged: false, health: 0.1, insured: false, lines: [{decision: "A1", limit: 5, sku: "A1"}, {decision: " pad ", limit: 0, sku: " pad "}], margin: 0, rate: 0.5, verified: true, weight: 0, weighted: true}}], + {input: {claim: {rate: 1e3, verified: null, weight: 99.99, age: 2.50, insured: false, flagged: null, lines: null}}, goals: ["line.decision"], output: {claim: {age: 2.50, flagged: null, insured: false, lines: null, rate: 1000, verified: null, weight: 99.99}}}, + {input: {claim: {rate: 5, verified: true, weight: 7.25, age: 1000, insured: false, flagged: true, lines: []}}, goals: ["claim.margin"], output: {calc: {tag: true}, claim: {age: 1000, discount: "US", exposure: false, flagged: true, health: 7.25, insured: false, lines: [], margin: 7.25, rank: 7.25, rate: 5, verified: true, weight: 7.25, weighted: true}}}, + {input: {claim: {rate: 10, verified: false, weight: 50, age: 5, insured: true, flagged: 1, lines: [{limit: -0.5, sku: "x"}, {limit: 0.5, sku: " pad "}]}}, goals: ["claim.rank", "line.decision"], output: "!error: InputValidationFailed"}, + {input: {claim: {rate: 99.99, verified: false, weight: 18, age: 250, insured: true, flagged: true, lines: [{limit: 250, sku: "Oslo"}]}}, goals: ["claim.weighted", "claim.rank"], output: {calc: {tag: true}, claim: {age: 250, discount: "US", exposure: false, flagged: true, health: -99.99, insured: true, lines: [{limit: 250, sku: "Oslo"}], margin: 99.99, rank: -99.99, rate: 99.99, verified: false, weight: 18, weighted: false}}}, + {input: {claim: {rate: 0.1, verified: false, weight: -0.01, age: -500, insured: true, flagged: false, lines: [{limit: -0.01, sku: "A1"}, {limit: 2.50, sku: "VIP"}]}}, goals: ["calc.tag", "claim.margin"], output: {calc: {tag: true}, claim: {age: -500, discount: "Oslo", exposure: false, flagged: false, health: 0.0, insured: true, lines: [{limit: -0.01, sku: "A1"}, {limit: 2.50, sku: "VIP"}], margin: 0.1, rate: 0.1, verified: false, weight: -0.01, weighted: false}}}, + ], +} + +// seed 350300 (attempt 0) +{ + name: "goals 04: claim/lines: 3 expression, 1 match, 5 table; 3 root, 13 per-member, 1 top-level computed", + policy: { + models: {claim: {amount: "number?", insured: "boolean", label: "string", country: "string", active: "boolean?", lines: "line[]"}, line: {price: "number", days: "number?", vip: "boolean?"}}, + blocks: [ + {table: "t1", inputs: ["claim.amount", "line.price", "claim.insured"], outputs: ["line.meta.review", "line.net", "line.tag"], rules: [ + ["0.5, 5", ">= 18", "", "claim.country", "(line.vip ?? false)", ""], + ["2", "<= 10", "false", "string(line.price)", "claim.insured", "(claim.amount ?? 0) in (18..164)"], + ]}, + {expression: "claim.flags.capped", value: "(split(claim.label, '-')[1] ?? 'none')"}, + {table: "t3", inputs: ["(line.net ?? false)", "claim.insured"], outputs: ["line.meta.eligible", "line.ok"], rules: [ + ["false", "", "(line.days ?? 0)", "(line.days ?? 0)"], + ["false", "true", "50", "line.price"], + ]}, + {table: "t4", inputs: ["claim.flags.capped", "claim.country", "(2 % (abs((claim.amount ?? 0)) + 1))"], outputs: ["line.segment", "line.flag"], rules: [ + ["'retail'", "", "", "10", "(line.days ?? 0)"], + ["", "$ != 'US'", ">= 0", "(min([abs(line.price), 1000]) ^ 2)", ""], + ["", "$ != 'low'", "<= 1", "(line.days ?? 0)", "(line.ok ?? 0)"], + ["'Oslo', 'A1'", "startsWith($, 'x')", "", "line.price", "line.price"], + ]}, + {table: "t5", hit: "collect", inputs: ["(claim.insured ? (claim.amount ?? 0) : 1.5)"], outputs: ["scores.total"], rules: [ + ["> 2", ""], + ["", "claim.insured"], + ["", "claim.insured"], + ["1000, 1", ""], + ]}, + {expression: "claim.rank", value: "{a: (claim.amount ?? 0)}"}, + {expression: "line.margin", value: "{ok: (max(map(claim.lines, (#.meta.eligible ?? 0))) ?? 0), a: count(claim.lines, (#.days ?? 0) > (#.flag ?? 0)), n: (min([abs((line.days ?? 0)), 1000]) ^ 3)}"}, + {match: "line.surcharge", arms: [["claim.rank.a in [34..71]", "line.price"], ["contains(['x', 'ok', ''], claim.country)", "len(claim.country)"], ["", "max([5, (line.ok ?? 0)])"]]}, + {table: "t9", hit: "collect", inputs: [null, null], outputs: ["line.penalty"], rules: [ + ["startsWith(claim.label, 'low')", "", "len(scores.total)"], + ["(line.meta.review ?? '') != 'a'", "", "line.margin.a"], + ["line.price in [38..73]", "", ""], + ["(claim.insured or (line.vip ?? false))", "((line.vip ?? false) or (claim.active ?? false))", "(claim.amount ?? 0)"], + ["", "", "100"], + ]}, + ], + }, + cases: [ + {input: {claim: {amount: 250, insured: true, label: "a-b-c", country: "12", active: false, lines: [{price: 5, days: 1e3, vip: true}]}}, goals: ["line.net", "claim.rank"], output: {claim: {active: false, amount: 250, country: "12", insured: true, label: "a-b-c", lines: [{days: 1000, meta: {review: null}, net: null, price: 5, tag: null, vip: true}], rank: {a: 250}}}}, + {input: {claim: {amount: -0.01, insured: false, label: "a", country: " pad ", active: true, lines: [{price: 1000, days: 0, vip: false}, {price: 1000, days: 123456789.123, vip: false}]}}, goals: ["line.surcharge", "line.meta.review"], output: {claim: {active: true, amount: -0.01, country: " pad ", insured: false, label: "a", lines: [{days: 0, meta: {eligible: 0, review: null}, net: null, ok: 0, price: 1000, surcharge: 5, tag: null, vip: false}, {days: 123456789.123, meta: {eligible: 123456789.123, review: null}, net: null, ok: 123456789.123, price: 1000, surcharge: 123456789.123, tag: null, vip: false}], rank: {a: -0.01}}}}, + [{claim: {amount: 0.5, insured: false, label: "US", country: "x-y", active: true, lines: [{price: 99999999999999999999, days: 1, vip: true}, {price: 2, days: -0, vip: false}, {price: 2, days: 2, vip: false}]}}, {claim: {active: true, amount: 0.5, country: "x-y", flags: {capped: "none"}, insured: false, label: "US", lines: [{days: 1, flag: 0, margin: {a: 1, n: 1, ok: 2}, meta: {eligible: null, review: "x-y"}, net: true, ok: null, penalty: [1, 0.5, 100], price: 99999999999999999999, segment: 1000000, surcharge: 5, tag: null, vip: true}, {days: 0, flag: 0, margin: {a: 1, n: 0, ok: 2}, meta: {eligible: 0, review: null}, net: null, ok: 0, penalty: [1, 100], price: 2, segment: 4, surcharge: 5, tag: null, vip: false}, {days: 2, flag: 2, margin: {a: 1, n: 8, ok: 2}, meta: {eligible: 2, review: null}, net: null, ok: 2, penalty: [1, 100], price: 2, segment: 4, surcharge: 5, tag: null, vip: false}], rank: {a: 0.5}}}], + {input: {claim: {amount: 5, insured: false, label: "12", country: "Zed", active: false, lines: [{price: 0, days: 2, vip: false}, {price: 0, days: 178, vip: true}, {price: 2.50, days: 10, vip: false}], extraField: 1}}, goals: ["claim.flags.capped", "line.ok"], output: {claim: {active: false, amount: 5, country: "Zed", extraField: 1, flags: {capped: "none"}, insured: false, label: "12", lines: [{days: 2, meta: {eligible: 2, review: null}, net: null, ok: 2, price: 0, tag: null, vip: false}, {days: 178, meta: {eligible: 178, review: null}, net: null, ok: 178, price: 0, tag: null, vip: true}, {days: 10, meta: {eligible: 10, review: null}, net: null, ok: 10, price: 2.50, tag: null, vip: false}]}}}, + [{claim: {amount: 2, insured: true, label: "US", country: "retail", active: false, lines: []}}, {claim: {active: false, amount: 2, country: "retail", flags: {capped: "none"}, insured: true, label: "US", lines: [], rank: {a: 2}}}], + {input: {claim: {amount: null, insured: true, label: "x", country: "US", lines: [{price: -0.5, days: 0.5}, {price: 5, days: 2, vip: null}, {price: 7.25, days: 10}]}}, goals: ["line.meta.eligible"], output: {claim: {amount: null, country: "US", insured: true, label: "x", lines: [{days: 0.5, meta: {eligible: 0.5, review: null}, net: null, ok: 0.5, price: -0.5, tag: null}, {days: 2, meta: {eligible: 2, review: null}, net: null, ok: 2, price: 5, tag: null, vip: null}, {days: 10, meta: {eligible: 10, review: null}, net: null, ok: 10, price: 7.25, tag: null}]}}}, + {input: {claim: {amount: 7.25, insured: true, label: "retail", country: "retail", active: false, lines: []}}, goals: ["claim.flags.capped", "line.margin", "line.penalty"], output: {claim: {active: false, amount: 7.25, country: "retail", flags: {capped: "none"}, insured: true, label: "retail", lines: []}}}, + [{claim: {amount: null, insured: true, label: "Zed", country: "12", active: false, lines: [{price: 250, days: 2, vip: true}, {price: 0, days: 1000000, vip: false}, {price: 1000, vip: false}, {price: 2.50, days: null}, {price: 250, days: -1}]}}, {claim: {active: false, amount: null, country: "12", flags: {capped: "none"}, insured: true, label: "Zed", lines: [{days: 2, flag: 2, margin: {a: 0, n: 8, ok: 1000000}, meta: {eligible: 2, review: null}, net: null, ok: 2, penalty: [0, 0, 100], price: 250, segment: 62500, surcharge: 5, tag: null, vip: true}, {days: 1000000, flag: 1000000, margin: {a: 0, n: 1000000000, ok: 1000000}, meta: {eligible: 1000000, review: null}, net: null, ok: 1000000, penalty: [0, 100], price: 0, segment: 0, surcharge: 1000000, tag: null, vip: false}, {flag: 0, margin: {a: 0, n: 0, ok: 1000000}, meta: {eligible: 0, review: null}, net: null, ok: 0, penalty: [0, 100], price: 1000, segment: 1000000, surcharge: 5, tag: null, vip: false}, {days: null, flag: 0, margin: {a: 0, n: 0, ok: 1000000}, meta: {eligible: 0, review: null}, net: null, ok: 0, penalty: [0, 100], price: 2.50, segment: 6.2500, surcharge: 5, tag: null}, {days: -1, flag: -1, margin: {a: 0, n: 1, ok: 1000000}, meta: {eligible: -1, review: null}, net: null, ok: -1, penalty: [0, 100], price: 250, segment: 62500, surcharge: 5, tag: null}], rank: {a: 0}}}], + [{claim: {amount: null, insured: true, label: "VIP", country: "é ü", lines: [{price: 1000, vip: null}, {price: 2.50, days: 100, vip: false}]}}, {claim: {amount: null, country: "é ü", flags: {capped: "none"}, insured: true, label: "VIP", lines: [{flag: 0, margin: {a: 0, n: 0, ok: 100}, meta: {eligible: 0, review: null}, net: null, ok: 0, penalty: [0, 100], price: 1000, segment: 1000000, surcharge: 5, tag: null, vip: null}, {days: 100, flag: 100, margin: {a: 0, n: 1000000, ok: 100}, meta: {eligible: 100, review: null}, net: null, ok: 100, penalty: [0, 100], price: 2.50, segment: 6.2500, surcharge: 100, tag: null, vip: false}], rank: {a: 0}}}], + {input: {claim: {amount: 0, insured: false, label: "gold", country: "日本", active: false, lines: [{price: 18, days: 2, vip: null}, {price: 18, days: null}]}}, goals: ["line.ok"], output: {claim: {active: false, amount: 0, country: "日本", insured: false, label: "gold", lines: [{days: 2, meta: {eligible: 2, review: null}, net: null, ok: 2, price: 18, tag: null, vip: null}, {days: null, meta: {eligible: 0, review: null}, net: null, ok: 0, price: 18, tag: null}]}}}, + {input: {claim: {amount: -0.01, insured: true, label: "x", country: "a-b-c", active: true, lines: [{price: 373, days: 2, vip: true}, {price: 0, days: 100, vip: false}, {price: 100, days: 18, vip: true}, {price: 250, days: 50, vip: true}, {price: 5, days: -0.5, vip: false}, {price: -500, days: 5, vip: true}, {price: 185, days: 1000, vip: false}, {price: 1000, days: 1, vip: false}, {price: 0, days: 2.50, vip: false}, {price: 1, days: 50, vip: true}, {price: 18, days: 5, vip: true}, {price: 1.5, days: 0.5, vip: false}]}}, goals: ["line.flag", "line.ok"], output: {claim: {active: true, amount: -0.01, country: "a-b-c", flags: {capped: "none"}, insured: true, label: "x", lines: [{days: 2, flag: 2, meta: {eligible: 2, review: null}, net: null, ok: 2, price: 373, segment: 139129, tag: null, vip: true}, {days: 100, flag: 100, meta: {eligible: 100, review: null}, net: null, ok: 100, price: 0, segment: 0, tag: null, vip: false}, {days: 18, flag: 18, meta: {eligible: 18, review: null}, net: null, ok: 18, price: 100, segment: 10000, tag: null, vip: true}, {days: 50, flag: 50, meta: {eligible: 50, review: null}, net: null, ok: 50, price: 250, segment: 62500, tag: null, vip: true}, {days: -0.5, flag: -0.5, meta: {eligible: -0.5, review: null}, net: null, ok: -0.5, price: 5, segment: 25, tag: null, vip: false}, {days: 5, flag: 5, meta: {eligible: 5, review: null}, net: null, ok: 5, price: -500, segment: 250000, tag: null, vip: true}, {days: 1000, flag: 1000, meta: {eligible: 1000, review: null}, net: null, ok: 1000, price: 185, segment: 34225, tag: null, vip: false}, {days: 1, flag: 1, meta: {eligible: 1, review: null}, net: null, ok: 1, price: 1000, segment: 1000000, tag: null, vip: false}, {days: 2.50, flag: 2.50, meta: {eligible: 2.50, review: null}, net: null, ok: 2.50, price: 0, segment: 0, tag: null, vip: false}, {days: 50, flag: 50, meta: {eligible: 50, review: null}, net: null, ok: 50, price: 1, segment: 1, tag: null, vip: true}, {days: 5, flag: 5, meta: {eligible: 5, review: null}, net: null, ok: 5, price: 18, segment: 324, tag: null, vip: true}, {days: 0.5, flag: 0.5, meta: {eligible: 0.5, review: null}, net: null, ok: 0.5, price: 1.5, segment: 2.25, tag: null, vip: false}]}}}, + {input: {claim: {amount: [1], insured: false, label: "NL", country: "A1", active: false, lines: []}}, goals: ["line.flag"], output: "!error: InputValidationFailed"}, + {input: {claim: {amount: null, insured: true, label: "-", country: "NL", active: null, lines: [{price: 5, days: null, vip: true}, {price: 2.50, days: null, vip: false}, {price: 2, days: 10, vip: null}, {price: 100, days: 0.5, vip: null}, {price: 1, days: 50, vip: false}]}}, goals: ["scores.total"], output: {claim: {active: null, amount: null, country: "NL", insured: true, label: "-", lines: [{days: null, price: 5, vip: true}, {days: null, price: 2.50, vip: false}, {days: 10, price: 2, vip: null}, {days: 0.5, price: 100, vip: null}, {days: 50, price: 1, vip: false}]}, scores: {total: [true, true]}}}, + {input: {claim: {amount: 0, insured: true, label: "retail", country: "O'Neil", active: true, lines: []}}, goals: ["claim.rank"], output: {claim: {active: true, amount: 0, country: "O'Neil", insured: true, label: "retail", lines: [], rank: {a: 0}}}}, + {input: {claim: {amount: null, insured: false, label: "VIP", country: "", lines: []}}, goals: ["claim.flags.capped", "line.net"], output: {claim: {amount: null, country: "", flags: {capped: "none"}, insured: false, label: "VIP", lines: []}}}, + [{claim: {amount: 99999999999999999999, insured: false, label: "a-b-c", country: "-", active: false, lines: [{price: 1000000, days: 7.25, vip: "true"}]}}, "!error: InputValidationFailed"], + {input: {claim: {amount: 50, insured: false, label: "low", country: "US", active: true, lines: [{price: -0.01, days: 1, vip: false}, {price: 1, days: -500, vip: false}], extraField: {nested: true}}}, goals: ["line.segment", "claim.rank"], output: {claim: {active: true, amount: 50, country: "US", extraField: {nested: true}, flags: {capped: "none"}, insured: false, label: "low", lines: [{days: 1, flag: null, price: -0.01, segment: null, vip: false}, {days: -500, flag: null, price: 1, segment: null, vip: false}], rank: {a: 50}}}}, + {input: {claim: {amount: 1.5, insured: true, label: "é ü", country: "low", active: true, lines: [{price: 0, days: 100, vip: true}, {price: 1000, days: 50, vip: true}, {price: 65, days: 0.5, vip: true}, {price: 2, days: 99.99, vip: true}]}}, goals: ["claim.flags.capped", "line.ok"], output: {claim: {active: true, amount: 1.5, country: "low", flags: {capped: "none"}, insured: true, label: "é ü", lines: [{days: 100, meta: {eligible: 100, review: null}, net: null, ok: 100, price: 0, tag: null, vip: true}, {days: 50, meta: {eligible: 50, review: null}, net: null, ok: 50, price: 1000, tag: null, vip: true}, {days: 0.5, meta: {eligible: 0.5, review: null}, net: null, ok: 0.5, price: 65, tag: null, vip: true}, {days: 99.99, meta: {eligible: 99.99, review: null}, net: null, ok: 99.99, price: 2, tag: null, vip: true}]}}}, + {input: {claim: {amount: 2, insured: false, label: "NL", country: "gold", active: true, lines: []}}, goals: ["line.meta.review", "line.flag"], output: {claim: {active: true, amount: 2, country: "gold", flags: {capped: "none"}, insured: false, label: "NL", lines: []}}}, + {input: {claim: {amount: 0, insured: false, label: "DE", country: "US", active: true, lines: [{price: 5, days: -500, vip: null}]}}, goals: ["line.ok"], output: {claim: {active: true, amount: 0, country: "US", insured: false, label: "DE", lines: [{days: -500, meta: {eligible: -500, review: null}, net: null, ok: -500, price: 5, tag: null, vip: null}]}}}, + {input: {claim: {amount: 50, insured: true, label: "retail", country: "a", active: true, lines: [{price: 99999999999999999999, days: 2, vip: false}, {price: 2, days: 100, vip: true}, {price: 250, days: -0, vip: true}, {price: 1000, days: 123456789.123, vip: true}, {price: 10, days: 2, vip: false}]}}, goals: ["line.surcharge", "claim.rank", "line.penalty"], output: {claim: {active: true, amount: 50, country: "a", flags: {capped: "none"}, insured: true, label: "retail", lines: [{days: 2, flag: null, margin: {a: 4, n: 8, ok: 123456789.123}, meta: {eligible: 2, review: null}, net: null, ok: 2, penalty: [4, 50, 100], price: 99999999999999999999, segment: 1000000, surcharge: 99999999999999999999, tag: null, vip: false}, {days: 100, flag: null, margin: {a: 4, n: 1000000, ok: 123456789.123}, meta: {eligible: 100, review: null}, net: null, ok: 100, penalty: [4, 50, 100], price: 2, segment: 4, surcharge: 2, tag: null, vip: true}, {days: 0, flag: null, margin: {a: 4, n: 0, ok: 123456789.123}, meta: {eligible: 0, review: null}, net: null, ok: 0, penalty: [4, 50, 100], price: 250, segment: 62500, surcharge: 250, tag: null, vip: true}, {days: 123456789.123, flag: null, margin: {a: 4, n: 1000000000, ok: 123456789.123}, meta: {eligible: 123456789.123, review: null}, net: null, ok: 123456789.123, penalty: [4, 50, 100], price: 1000, segment: 1000000, surcharge: 1000, tag: null, vip: true}, {days: 2, flag: null, margin: {a: 4, n: 8, ok: 123456789.123}, meta: {eligible: 2, review: null}, net: null, ok: 2, penalty: [4, 50, 100], price: 10, segment: 100, surcharge: 10, tag: null, vip: false}], rank: {a: 50}}}}, + {input: {claim: {amount: 1e3, insured: false, label: "a", country: "a", active: true, lines: [{price: 0.000001, days: 99.99, vip: false}]}}, goals: ["line.surcharge", "scores.total", "line.flag"], output: {claim: {active: true, amount: 1000, country: "a", flags: {capped: "none"}, insured: false, label: "a", lines: [{days: 99.99, flag: null, meta: {eligible: 99.99, review: null}, net: null, ok: 99.99, price: 0.000001, segment: 0.000000000001, surcharge: 99.99, tag: null, vip: false}], rank: {a: 1000}}, scores: {total: [false, false]}}}, + {input: {claim: {insured: true, label: "low", country: "a-b-c", lines: [{price: -0.01, days: -500, vip: null}, {price: 1, days: null, vip: false}]}}, goals: ["line.penalty", "line.net"], output: {claim: {country: "a-b-c", flags: {capped: "none"}, insured: true, label: "low", lines: [{days: -500, flag: -500, margin: {a: 0, n: 125000000, ok: 0}, meta: {eligible: -500, review: null}, net: null, ok: -500, penalty: [2, 0, 100], price: -0.01, segment: 0.0001, tag: null, vip: null}, {days: null, flag: 0, margin: {a: 0, n: 0, ok: 0}, meta: {eligible: 0, review: null}, net: null, ok: 0, penalty: [2, 0, 100], price: 1, segment: 1, tag: null, vip: false}]}, scores: {total: [true, true]}}}, + ], +} + +// seed 350400 (attempt 0) +{ + name: "goals 05: borrower/companies/parts: 1 assertion, 3 expression, 3 match, 1 table; 6 root, 7 per-member, 1 top-level computed", + policy: { + models: {borrower: {income: "number", code: "string", weight: "number", days: "number?", companies: "company[]"}, company: {income: "number", insured: "boolean", parts: "part[]"}, part: {years: "number", city: "string", code: "string"}}, + blocks: [ + {match: "eligible", arms: [["some(borrower.companies, (#.insured or #.points))", "((borrower.days ?? 0) > 5 ? borrower.bucket : borrower.code)"], ["some(borrower.companies, (#.points or #.insured))", "(`${(borrower.days ?? 0) <= 10}/${borrower.weight}` + '-' + string(borrower.weight > 10))"], ["", "'ok'"]]}, + {assertion: "company.points", conditions: [["or", "(company.income > borrower.weight or (company.insured or company.insured))", 0], ["or", "round(borrower.income) < (borrower.days ?? 0)", 0]]}, + {expression: "company.net", value: "{n: company.calc.surcharge, s: company.calc.surcharge, v: string(len(filter(company.parts, matches(#.code, '^.{2,}$'))))}"}, + {match: "company.calc.surcharge", arms: [["sum(map(company.parts, #.years)) < (borrower.days ?? 0)", "company.income"], ["", "max([company.income, 100])"]]}, + {expression: "borrower.scores.health", value: "{n: string(floor((borrower.days ?? 0)))}"}, + {table: "t7", hit: "collect", inputs: ["borrower.weight", "(borrower.income % (abs(borrower.income) + 1))", null], outputs: ["borrower.summary", "borrower.quota", "borrower.margin"], rules: [ + ["", "", "borrower.days == null", "", "(borrower.days ?? 0)", ""], + ["", "", "", "borrower.code", "", "100"], + ]}, + {expression: "company.calc.ok", value: "company.calc.surcharge"}, + {match: "borrower.bucket", arms: [["(matches(borrower.code, '[0-9]$') and (1 <= 1 and borrower.income <= 0.5))", "(borrower.weight == 1.5 ? borrower.code : borrower.scores.health.n)"], ["", "('retail' + '-' + borrower.code)"]]}, + ], + }, + cases: [ + {input: {borrower: {income: 0.1, code: "3.5", weight: 1.5, companies: [{income: 1, insured: true, parts: [{years: 7.25, city: "A1", code: "Zed"}, {years: 1000000, city: "a", code: "ok"}, {years: 112, city: "US", code: ""}]}, {income: -0.01, insured: true, parts: [{years: 3, city: "é ü", code: "gold"}, {years: 2.50, city: "ok", code: "Zed"}]}]}}, goals: ["company.calc.surcharge", "borrower.quota", "company.net"], output: {borrower: {code: "3.5", companies: [{calc: {surcharge: 100}, income: 1, insured: true, net: {n: 100, s: 100, v: "2"}, parts: [{city: "A1", code: "Zed", years: 7.25}, {city: "a", code: "ok", years: 1000000}, {city: "US", code: "", years: 112}]}, {calc: {surcharge: 100}, income: -0.01, insured: true, net: {n: 100, s: 100, v: "2"}, parts: [{city: "é ü", code: "gold", years: 3}, {city: "ok", code: "Zed", years: 2.50}]}], income: 0.1, margin: [100], quota: [0], summary: ["3.5"], weight: 1.5}}}, + {input: {borrower: {income: 1.5, code: "日本", weight: 1, days: 100, companies: [{income: -500, insured: false, parts: []}], extraField: "x"}}, goals: ["eligible"], output: {borrower: {bucket: "retail-日本", code: "日本", companies: [{income: -500, insured: false, parts: [], points: true}], days: 100, extraField: "x", income: 1.5, weight: 1}, eligible: "retail-日本"}}, + {input: {borrower: {income: 0.5, code: "x-y", weight: 18, days: null, companies: [{income: 250, insured: true, parts: [{years: 3, city: "x-y", code: "3.5"}, {years: 250, city: "日本", code: "é ü"}]}, {income: 0.5, insured: true, parts: [{years: 395, city: "low", code: "a"}, {years: -0.5, city: "a", code: "ok"}]}]}}, goals: ["company.calc.surcharge"], output: {borrower: {code: "x-y", companies: [{calc: {surcharge: 250}, income: 250, insured: true, parts: [{city: "x-y", code: "3.5", years: 3}, {city: "日本", code: "é ü", years: 250}]}, {calc: {surcharge: 100}, income: 0.5, insured: true, parts: [{city: "low", code: "a", years: 395}, {city: "a", code: "ok", years: -0.5}]}], days: null, income: 0.5, weight: 18}}}, + {input: {borrower: {income: 3, code: "DE", weight: 0.5, days: 99.99, companies: [{income: -1, insured: false, parts: [{years: 1000, city: "-", code: "ok"}, {years: 1000000, city: "Oslo", code: " pad "}, {years: 100, city: "ok", code: ""}]}, {income: 100, insured: false, parts: [{years: 123456789.123, city: "retail", code: "12"}, {years: 10, city: "DE", code: "a"}, {years: 0, city: "a", code: "Zed"}]}, {income: 0.000001, insured: true, parts: [{years: 1000, city: "US", code: "x-y"}, {years: 100, city: "A1", code: "Zed"}]}]}}, goals: ["borrower.quota"], output: {borrower: {code: "DE", companies: [{income: -1, insured: false, parts: [{city: "-", code: "ok", years: 1000}, {city: "Oslo", code: " pad ", years: 1000000}, {city: "ok", code: "", years: 100}]}, {income: 100, insured: false, parts: [{city: "retail", code: "12", years: 123456789.123}, {city: "DE", code: "a", years: 10}, {city: "a", code: "Zed", years: 0}]}, {income: 0.000001, insured: true, parts: [{city: "US", code: "x-y", years: 1000}, {city: "A1", code: "Zed", years: 100}]}], days: 99.99, income: 3, margin: [100], quota: [], summary: ["DE"], weight: 0.5}}}, + {input: {borrower: {income: 1, code: "a", weight: 2, days: 1e3, companies: [{income: -500, insured: true, parts: [{years: 10, city: "US", code: "3.5"}, {years: 1, city: "US", code: "retail"}, {years: 100, city: "retail", code: "NL"}]}]}}, goals: ["borrower.summary"], output: {borrower: {code: "a", companies: [{income: -500, insured: true, parts: [{city: "US", code: "3.5", years: 10}, {city: "US", code: "retail", years: 1}, {city: "retail", code: "NL", years: 100}]}], days: 1000, income: 1, margin: [100], quota: [], summary: ["a"], weight: 2}}}, + [{borrower: {income: 99999999999999999999, code: "retail", weight: 3, days: 3, companies: [{income: 100, insured: true, parts: []}]}}, {borrower: {bucket: "retail-retail", code: "retail", companies: [{calc: {surcharge: 100}, income: 100, insured: true, net: {n: 100, s: 100, v: "0"}, parts: [], points: true}], days: 3, income: 99999999999999999999, margin: [100], quota: [], summary: ["retail"], weight: 3}, eligible: "retail"}], + {input: {borrower: {income: -500, code: "retail", weight: 10, days: 0.1, companies: [{income: -0.01, parts: [{years: 250, city: "retail", code: "US"}, {years: 122, city: "abc", code: "Zed"}]}]}}, goals: ["eligible"], output: "!error: ExpressionFailed"}, + {input: {borrower: {income: 1000, code: "retail", weight: 65, days: 2, companies: [{income: 100, insured: true, parts: [{years: 10, city: "US", code: "DE"}, {years: -500, city: "DE", code: "VIP"}]}, {income: 1000000, insured: false, parts: [{years: 65, city: "Oslo", code: "Zed"}, {years: -500, city: "abc", code: "12"}]}, {income: 0.5, insured: false, parts: [{years: -500, city: "-", code: "-"}]}, {income: 100, insured: false, parts: []}]}}, goals: ["borrower.quota", "company.calc.ok"], output: {borrower: {code: "retail", companies: [{calc: {ok: 100, surcharge: 100}, income: 100, insured: true, parts: [{city: "US", code: "DE", years: 10}, {city: "DE", code: "VIP", years: -500}]}, {calc: {ok: 1000000, surcharge: 1000000}, income: 1000000, insured: false, parts: [{city: "Oslo", code: "Zed", years: 65}, {city: "abc", code: "12", years: -500}]}, {calc: {ok: 0.5, surcharge: 0.5}, income: 0.5, insured: false, parts: [{city: "-", code: "-", years: -500}]}, {calc: {ok: 100, surcharge: 100}, income: 100, insured: false, parts: []}], days: 2, income: 1000, margin: [100], quota: [], summary: ["retail"], weight: 65}}}, + {input: {borrower: {income: 99.99, code: "日本", weight: 1000000, days: 10, companies: [{income: 5, insured: true, parts: [{years: 10, city: "retail", code: "DE"}, {years: 65, city: "retail", code: " pad "}]}]}}, goals: ["borrower.summary", "borrower.quota"], output: {borrower: {code: "日本", companies: [{income: 5, insured: true, parts: [{city: "retail", code: "DE", years: 10}, {city: "retail", code: " pad ", years: 65}]}], days: 10, income: 99.99, margin: [100], quota: [], summary: ["日本"], weight: 1000000}}}, + {input: {borrower: {income: 99.99, code: "Zed", weight: 2.50, days: 100, companies: []}}, goals: ["company.calc.surcharge"], output: {borrower: {code: "Zed", companies: [], days: 100, income: 99.99, weight: 2.50}}}, + {input: {borrower: {income: 3, code: "3.5", weight: 1, days: -1, companies: []}}, goals: ["company.points", "eligible", "borrower.bucket"], output: {borrower: {bucket: "retail-3.5", code: "3.5", companies: [], days: -1, income: 3, weight: 1}, eligible: "ok"}}, + [{borrower: {income: 0.5, code: "retail", weight: -500, days: 10, companies: []}}, {borrower: {code: "retail", companies: [], days: 10, income: 0.5, margin: [100], quota: [], summary: ["retail"], weight: -500}, eligible: "ok"}], + ], +} + +// seed 350500 (attempt 0) +{ + name: "goals 06: borrower/loans: 3 expression, 1 match, 1 table; 0 root, 6 per-member, 1 top-level computed", + policy: { + models: {borrower: {balance: "number", verified: "boolean", sku: "string", kind: "string(retail|corporate)?", loans: "loan[]"}, loan: {days: "number", vip: "boolean"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {match: "scores.risk", arms: [["(borrower.kind ?? '') == 'retail'", "matches(borrower.sku, '[0-9]$')"], ["borrower.balance == borrower.balance", "borrower.verified"], ["", "borrower.verified"]]}, + {table: "t2", inputs: ["factor", null, null], outputs: ["loan.summary", "loan.ok", "loan.discount"], rules: [ + ["< 0.25", "not (borrower.verified)", "", "scores.risk", "0.25", ""], + ["<= 3", "borrower.balance != 0.25", "loan.days != factor", "loan.vip", "loan.days", "borrower.sku"], + ["> 50", "", "matches(borrower.sku, '^[A-Z]')", "loan.days in [3..168]", "factor", "borrower.sku"], + ["[0.25..2.25]", "", "borrower.balance in [40..207]", "loan.vip", "borrower.balance", "borrower.sku"], + ]}, + {expression: "loan.rank", value: "ceil((max(map(borrower.loans, (#.ok ?? 0))) ?? 0))"}, + {expression: "loan.penalty", value: "loan.summary"}, + {expression: "loan.margin", value: "trunc(borrower.balance)"}, + ], + }, + cases: [ + {input: {factor: 10, borrower: {balance: 250, verified: true, sku: "", kind: null, loans: []}}, goals: ["scores.risk"], output: {borrower: {balance: 250, kind: null, loans: [], sku: "", verified: true}, factor: 10, scores: {risk: true}}}, + {input: {factor: 100, borrower: {balance: 0.25, verified: true, sku: "NL", kind: "retail", loans: [{days: 50, vip: false}, {days: 0.1, vip: false}, {days: 0.25, vip: false}, {days: 123456789.123, vip: false}]}}, goals: ["loan.ok", "loan.penalty", "loan.margin"], output: {borrower: {balance: 0.25, kind: "retail", loans: [{days: 50, discount: "NL", margin: 0, ok: 100, penalty: true, summary: true, vip: false}, {days: 0.1, discount: "NL", margin: 0, ok: 100, penalty: false, summary: false, vip: false}, {days: 0.25, discount: "NL", margin: 0, ok: 100, penalty: false, summary: false, vip: false}, {days: 123456789.123, discount: "NL", margin: 0, ok: 100, penalty: false, summary: false, vip: false}], sku: "NL", verified: true}, factor: 100}}, + {input: {factor: 0.5, borrower: {balance: 50, verified: false, sku: "Oslo", kind: null, loans: [{days: 123456789.123, vip: true}, {days: 0.25, vip: false}, {days: 0.1, vip: false}]}}, goals: ["loan.summary"], output: {borrower: {balance: 50, kind: null, loans: [{days: 123456789.123, discount: "Oslo", ok: 123456789.123, summary: true, vip: true}, {days: 0.25, discount: "Oslo", ok: 0.25, summary: false, vip: false}, {days: 0.1, discount: "Oslo", ok: 0.1, summary: false, vip: false}], sku: "Oslo", verified: false}, factor: 0.5}}, + {input: {factor: 10, borrower: {balance: 466, verified: true, sku: "DE", kind: null, loans: []}}, goals: ["loan.rank", "loan.margin", "scores.risk"], output: {borrower: {balance: 466, kind: null, loans: [], sku: "DE", verified: true}, factor: 10, scores: {risk: true}}}, + {input: {factor: 10, borrower: {balance: 10, verified: true, sku: " pad ", kind: null, loans: [{days: 50, vip: true}]}}, goals: ["loan.rank", "loan.ok"], output: {borrower: {balance: 10, kind: null, loans: [{days: 50, discount: null, ok: null, rank: 0, summary: null, vip: true}], sku: " pad ", verified: true}, factor: 10}}, + {input: {factor: 100, borrower: {balance: 65, verified: true, sku: "é ü", kind: "retail", loans: [{days: 123456789.123, vip: true}, {days: 5, vip: false}, {days: 0, vip: true}]}}, goals: ["loan.ok"], output: {borrower: {balance: 65, kind: "retail", loans: [{days: 123456789.123, discount: null, ok: null, summary: null, vip: true}, {days: 5, discount: null, ok: null, summary: null, vip: false}, {days: 0, discount: null, ok: null, summary: null, vip: true}], sku: "é ü", verified: true}, factor: 100}}, + {input: {factor: 1, borrower: {balance: 40, verified: true, sku: "Oslo", kind: "retail", loans: [{days: 250, vip: false}, {days: 0.5, vip: true}, {days: 0.25, vip: true}, {days: 10, vip: true}, {days: 1000, vip: false}, {days: 2.50, vip: false}, {days: 5, vip: true}, {days: 250, vip: false}, {days: 99.99, vip: false}, {days: 2.50, vip: false}, {days: 2, vip: false}, {days: -1, vip: false}, {days: 0.000001, vip: false}]}}, goals: ["loan.ok", "loan.summary"], output: {borrower: {balance: 40, kind: "retail", loans: [{days: 250, discount: "Oslo", ok: 250, summary: false, vip: false}, {days: 0.5, discount: "Oslo", ok: 0.5, summary: true, vip: true}, {days: 0.25, discount: "Oslo", ok: 0.25, summary: true, vip: true}, {days: 10, discount: "Oslo", ok: 10, summary: true, vip: true}, {days: 1000, discount: "Oslo", ok: 1000, summary: false, vip: false}, {days: 2.50, discount: "Oslo", ok: 2.50, summary: false, vip: false}, {days: 5, discount: "Oslo", ok: 5, summary: true, vip: true}, {days: 250, discount: "Oslo", ok: 250, summary: false, vip: false}, {days: 99.99, discount: "Oslo", ok: 99.99, summary: false, vip: false}, {days: 2.50, discount: "Oslo", ok: 2.50, summary: false, vip: false}, {days: 2, discount: "Oslo", ok: 2, summary: false, vip: false}, {days: -1, discount: "Oslo", ok: -1, summary: false, vip: false}, {days: 0.000001, discount: "Oslo", ok: 0.000001, summary: false, vip: false}], sku: "Oslo", verified: true}, factor: 1}}, + {input: {factor: 10, borrower: {balance: 5, verified: true, sku: "a-b-c", kind: "retail", loans: [{days: 0.000001, vip: false}]}}, goals: ["loan.ok", "loan.rank"], output: {borrower: {balance: 5, kind: "retail", loans: [{days: 0.000001, discount: null, ok: null, rank: 0, summary: null, vip: false}], sku: "a-b-c", verified: true}, factor: 10}}, + {input: {factor: 10, borrower: {balance: 123456789.123, verified: false, sku: "O'Neil", kind: "corporate", loans: [{days: -0.5, vip: true}, {days: 0.000001, vip: false}]}}, goals: ["loan.rank"], output: {borrower: {balance: 123456789.123, kind: "corporate", loans: [{days: -0.5, discount: null, ok: null, rank: 0, summary: null, vip: true}, {days: 0.000001, discount: null, ok: null, rank: 0, summary: null, vip: false}], sku: "O'Neil", verified: false}, factor: 10}}, + {input: {factor: 0.5, borrower: {balance: 0.25, verified: false, sku: "NL", kind: "retail", loans: [{days: 2, vip: false}, {days: 2.50, vip: false}, {days: -1, vip: true}, {days: 99999999999999999999, vip: true}, {days: 100, vip: false}, {days: 0.25, vip: true}, {days: 0.25, vip: false}, {days: -0, vip: true}, {days: -1, vip: false}, {days: 0.25, vip: false}, {days: 1000000, vip: true}, {days: 0.5, vip: false}, {days: 100, vip: false}]}}, goals: ["loan.summary", "loan.margin"], output: {borrower: {balance: 0.25, kind: "retail", loans: [{days: 2, discount: null, margin: 0, ok: null, summary: null, vip: false}, {days: 2.50, discount: null, margin: 0, ok: null, summary: null, vip: false}, {days: -1, discount: null, margin: 0, ok: null, summary: null, vip: true}, {days: 99999999999999999999, discount: null, margin: 0, ok: null, summary: null, vip: true}, {days: 100, discount: null, margin: 0, ok: null, summary: null, vip: false}, {days: 0.25, discount: null, margin: 0, ok: null, summary: null, vip: true}, {days: 0.25, discount: null, margin: 0, ok: null, summary: null, vip: false}, {days: 0, discount: null, margin: 0, ok: null, summary: null, vip: true}, {days: -1, discount: null, margin: 0, ok: null, summary: null, vip: false}, {days: 0.25, discount: null, margin: 0, ok: null, summary: null, vip: false}, {days: 1000000, discount: null, margin: 0, ok: null, summary: null, vip: true}, {days: 0.5, discount: null, margin: 0, ok: null, summary: null, vip: false}, {days: 100, discount: null, margin: 0, ok: null, summary: null, vip: false}], sku: "NL", verified: false}, factor: 0.5}}, + {input: {factor: -2, borrower: {balance: 0.5, verified: true, sku: "abc", kind: "retail", loans: [{days: 0, vip: true}, {days: 178, vip: false}]}}, goals: ["loan.discount", "loan.rank", "loan.penalty"], output: {borrower: {balance: 0.5, kind: "retail", loans: [{days: 0, discount: "abc", ok: 0, penalty: true, rank: 178, summary: true, vip: true}, {days: 178, discount: "abc", ok: 178, penalty: false, rank: 178, summary: false, vip: false}], sku: "abc", verified: true}, factor: -2}}, + [{factor: 0, borrower: {balance: 10, verified: false, sku: "Oslo", kind: "retail", loans: [{days: 18, vip: false}, {days: 3, vip: false}], extraField: "x"}}, {borrower: {balance: 10, extraField: "x", kind: "retail", loans: [{days: 18, discount: "Oslo", margin: 10, ok: 0.25, penalty: false, rank: 1, summary: false, vip: false}, {days: 3, discount: "Oslo", margin: 10, ok: 0.25, penalty: false, rank: 1, summary: false, vip: false}], sku: "Oslo", verified: false}, factor: 0, scores: {risk: false}}], + [{factor: 10, borrower: {balance: 250, verified: true, sku: "é ü", kind: "retail", loans: []}}, {borrower: {balance: 250, kind: "retail", loans: [], sku: "é ü", verified: true}, factor: 10}], + {input: {factor: 10, borrower: {balance: 1000, verified: true, sku: "O'Neil", kind: "retail", loans: [{days: 0.25, vip: false}, {days: 1e3, vip: true}, {days: 3, vip: false}, {days: 5, vip: false}, {days: 0.1, vip: false}, {days: 250, vip: false}, {days: 1, vip: true}, {days: 10, vip: false}, {days: 10, vip: false}, {days: -0.5, vip: true}]}}, goals: ["loan.penalty", "loan.rank"], output: {borrower: {balance: 1000, kind: "retail", loans: [{days: 0.25, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: false}, {days: 1000, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: true}, {days: 3, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: false}, {days: 5, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: false}, {days: 0.1, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: false}, {days: 250, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: false}, {days: 1, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: true}, {days: 10, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: false}, {days: 10, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: false}, {days: -0.5, discount: null, ok: null, penalty: null, rank: 0, summary: null, vip: true}], sku: "O'Neil", verified: true}, factor: 10}}, + {input: {factor: -2, borrower: {balance: 99999999999999999999, verified: false, sku: "Zed", kind: "retail", loans: [{days: 50, vip: true}]}}, goals: ["loan.discount", "loan.penalty"], output: {borrower: {balance: 99999999999999999999, kind: "retail", loans: [{days: 50, discount: "Zed", ok: 0.25, penalty: false, summary: false, vip: true}], sku: "Zed", verified: false}, factor: -2, scores: {risk: false}}}, + {input: {factor: -2, borrower: {balance: 1, verified: false, sku: "3.5", kind: null, loans: [{days: -0, vip: true}, {days: -0.5, vip: false}]}}, goals: ["loan.discount", "loan.penalty"], output: {borrower: {balance: 1, kind: null, loans: [{days: 0, discount: "3.5", ok: 0.25, penalty: false, summary: false, vip: true}, {days: -0.5, discount: "3.5", ok: 0.25, penalty: false, summary: false, vip: false}], sku: "3.5", verified: false}, factor: -2, scores: {risk: false}}}, + ], +} + +// seed 350600 (attempt 0) +{ + name: "goals 07: shipment/accounts: 1 expression, 1 match, 3 table; 5 root, 4 per-member, 0 top-level computed", + policy: { + models: {shipment: {years: "number", vip: "boolean?", active: "boolean", flagged: "boolean", verified: "boolean", insured: "boolean", accounts: "acct[]"}, acct: {amount: "number", flagged: "boolean", region: "string", city: "string"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {table: "t1", inputs: ["(shipment.years % (abs(threshold) + 1))", "shipment.insured"], outputs: ["shipment.risk", "shipment.discount", "shipment.review"], rules: [ + ["0.5", "false", "threshold", "'a'", "'gold'"], + ["", "", "shipment.years", "(shipment.verified ? 'none' : 'a')", "'Oslo'"], + ]}, + {table: "t2", inputs: ["threshold", "shipment.years"], outputs: ["acct.rank", "acct.band", "acct.flag[]"], rules: [ + ["18", "[100..241]", "acct.amount", "", "acct.city"], + ["< 3", "", "(shipment.years + 10)", "len(shipment.accounts)", "acct.region"], + ["", "", "shipment.years", "threshold", "acct.region"], + ]}, + {table: "t3", hit: "collect", inputs: ["shipment.years"], outputs: ["shipment.share"], rules: [ + ["< 250", "string(shipment.flagged)"], + ["<= 1", "(shipment.discount ?? '')"], + ["50, 10", ""], + ["", "(shipment.review ?? '')"], + ]}, + {match: "acct.adjusted", arms: [["(acct.band ?? 0) in [49..200)", "threshold in [13..43)"], ["", "acct.flagged"]]}, + {expression: "shipment.margin", value: "len((shipment.discount ?? ''))"}, + ], + }, + cases: [ + {input: {threshold: 0.5, shipment: {years: 0.5, vip: false, active: false, flagged: false, verified: false, insured: false, accounts: [{amount: 1.5, flagged: false, region: "US", city: "x-y"}], extraField: "x"}}, goals: ["shipment.share", "acct.rank", "acct.band"], output: {shipment: {accounts: [{amount: 1.5, band: 1, city: "x-y", flag: ["US", "US"], flagged: false, rank: 10.5, region: "US"}], active: false, discount: "a", extraField: "x", flagged: false, insured: false, review: "gold", risk: 0.5, share: ["false", "a", "gold"], verified: false, vip: false, years: 0.5}, threshold: 0.5}}, + {input: {threshold: -2, shipment: {years: 99.99, vip: false, active: false, flagged: false, verified: false, insured: false, accounts: [{amount: -1, flagged: true, region: "O'Neil", city: "Oslo"}, {amount: 10, flagged: true, region: "a", city: "O'Neil"}, {amount: 250, flagged: false, region: " pad ", city: " pad "}, {amount: 250, flagged: false, region: "US", city: "日本"}, {amount: 1, flagged: false, region: "a-b-c", city: "gold"}, {amount: 50, flagged: false, region: "", city: "O'Neil"}, {amount: 99999999999999999999, flagged: true, region: "retail", city: "Oslo"}, {amount: 0.25, flagged: true, region: "gold", city: "Zed"}]}}, goals: ["shipment.discount"], output: {shipment: {accounts: [{amount: -1, city: "Oslo", flagged: true, region: "O'Neil"}, {amount: 10, city: "O'Neil", flagged: true, region: "a"}, {amount: 250, city: " pad ", flagged: false, region: " pad "}, {amount: 250, city: "日本", flagged: false, region: "US"}, {amount: 1, city: "gold", flagged: false, region: "a-b-c"}, {amount: 50, city: "O'Neil", flagged: false, region: ""}, {amount: 99999999999999999999, city: "Oslo", flagged: true, region: "retail"}, {amount: 0.25, city: "Zed", flagged: true, region: "gold"}], active: false, discount: "a", flagged: false, insured: false, review: "Oslo", risk: 99.99, verified: false, vip: false, years: 99.99}, threshold: -2}}, + {input: {threshold: 100, shipment: {years: 10, vip: true, active: true, flagged: true, verified: false, insured: true, accounts: [{amount: 250, flagged: true, region: "Zed", city: "US"}]}}, goals: ["shipment.share"], output: {shipment: {accounts: [{amount: 250, city: "US", flagged: true, region: "Zed"}], active: true, discount: "a", flagged: true, insured: true, review: "Oslo", risk: 10, share: ["true", "Oslo"], verified: false, vip: true, years: 10}, threshold: 100}}, + {input: {threshold: -2, shipment: {years: 65, vip: false, active: false, flagged: true, verified: true, insured: false, accounts: [{amount: 18, flagged: false, region: "retail", city: "gold"}, {amount: 1000000, flagged: true, region: "retail", city: "Oslo"}, {amount: 3, flagged: true, region: " pad ", city: "O'Neil"}, {amount: 50, flagged: false, region: "日本", city: "A1"}]}}, goals: ["acct.band", "acct.adjusted", "shipment.margin"], output: {shipment: {accounts: [{adjusted: false, amount: 18, band: 4, city: "gold", flag: ["retail", "retail"], flagged: false, rank: 75, region: "retail"}, {adjusted: true, amount: 1000000, band: 4, city: "Oslo", flag: ["retail", "retail"], flagged: true, rank: 75, region: "retail"}, {adjusted: true, amount: 3, band: 4, city: "O'Neil", flag: [" pad ", " pad "], flagged: true, rank: 75, region: " pad "}, {adjusted: false, amount: 50, band: 4, city: "A1", flag: ["日本", "日本"], flagged: false, rank: 75, region: "日本"}], active: false, discount: "none", flagged: true, insured: false, margin: 4, review: "Oslo", risk: 65, verified: true, vip: false, years: 65}, threshold: -2}}, + {input: {threshold: 1, shipment: {years: 10, vip: true, active: false, flagged: true, verified: true, insured: false, accounts: [{amount: 2, flagged: true, region: "Zed", city: "retail"}]}}, goals: ["acct.flag", "shipment.risk", "shipment.margin"], output: {shipment: {accounts: [{amount: 2, band: 1, city: "retail", flag: ["Zed", "Zed"], flagged: true, rank: 20, region: "Zed"}], active: false, discount: "none", flagged: true, insured: false, margin: 4, review: "Oslo", risk: 10, verified: true, vip: true, years: 10}, threshold: 1}}, + {input: {threshold: 0, shipment: {years: -500, vip: null, active: true, flagged: false, verified: true, insured: false, accounts: [{amount: -0, flagged: false, region: "VIP", city: "VIP"}, {amount: 250, flagged: false, region: "A1", city: "-"}]}}, goals: ["acct.band", "acct.adjusted"], output: {shipment: {accounts: [{adjusted: false, amount: 0, band: 2, city: "VIP", flag: ["VIP", "VIP"], flagged: false, rank: -490, region: "VIP"}, {adjusted: false, amount: 250, band: 2, city: "-", flag: ["A1", "A1"], flagged: false, rank: -490, region: "A1"}], active: true, flagged: false, insured: false, verified: true, vip: null, years: -500}, threshold: 0}}, + {input: {threshold: 10, shipment: {years: 250, vip: false, active: true, flagged: true, verified: true, insured: true, accounts: [], extraField: 1}}, goals: ["shipment.share"], output: {shipment: {accounts: [], active: true, discount: "none", extraField: 1, flagged: true, insured: true, review: "Oslo", risk: 250, share: ["Oslo"], verified: true, vip: false, years: 250}, threshold: 10}}, + {input: {threshold: 1, shipment: {years: 1000, vip: true, active: true, flagged: true, verified: false, insured: false, accounts: [{amount: -0, flagged: false, region: "a", city: "retail"}, {amount: 0.5, flagged: true, region: "a", city: "-"}, {amount: 50, flagged: false, region: "low", city: "12"}, {amount: 99.99, flagged: false, region: "VIP", city: "Oslo"}]}}, goals: ["shipment.discount", "shipment.margin", "shipment.share"], output: {shipment: {accounts: [{amount: 0, city: "retail", flagged: false, region: "a"}, {amount: 0.5, city: "-", flagged: true, region: "a"}, {amount: 50, city: "12", flagged: false, region: "low"}, {amount: 99.99, city: "Oslo", flagged: false, region: "VIP"}], active: true, discount: "a", flagged: true, insured: false, margin: 1, review: "Oslo", risk: 1000, share: ["Oslo"], verified: false, vip: true, years: 1000}, threshold: 1}}, + {input: {threshold: 0, shipment: {years: 1, active: false, flagged: false, verified: false, insured: false, accounts: [{amount: 0.000001, flagged: false, region: "", city: "12"}]}}, goals: ["shipment.discount"], output: {shipment: {accounts: [{amount: 0.000001, city: "12", flagged: false, region: ""}], active: false, discount: "a", flagged: false, insured: false, review: "Oslo", risk: 1, verified: false, years: 1}, threshold: 0}}, + {input: {threshold: 0.5, shipment: {years: -0.5, vip: null, active: true, flagged: true, verified: true, insured: false, accounts: [{amount: 0.5, flagged: true, region: "日本", city: "a"}, {amount: -0.5, flagged: true, region: "O'Neil", city: "NL"}]}}, goals: ["acct.band"], output: {shipment: {accounts: [{amount: 0.5, band: 2, city: "a", flag: ["日本", "日本"], flagged: true, rank: 9.5, region: "日本"}, {amount: -0.5, band: 2, city: "NL", flag: ["O'Neil", "O'Neil"], flagged: true, rank: 9.5, region: "O'Neil"}], active: true, flagged: true, insured: false, verified: true, vip: null, years: -0.5}, threshold: 0.5}}, + {input: {threshold: -2, shipment: {years: 0.5, vip: true, active: false, flagged: true, verified: false, insured: true, accounts: []}}, goals: ["shipment.share", "acct.band"], output: {shipment: {accounts: [], active: false, discount: "a", flagged: true, insured: true, review: "Oslo", risk: 0.5, share: ["true", "a", "Oslo"], verified: false, vip: true, years: 0.5}, threshold: -2}}, + {input: {threshold: 10, shipment: {years: 100, vip: true, active: false, flagged: true, verified: true, insured: false, accounts: []}}, goals: ["shipment.share", "shipment.discount", "shipment.margin"], output: {shipment: {accounts: [], active: false, discount: "none", flagged: true, insured: false, margin: 4, review: "Oslo", risk: 100, share: ["true", "Oslo"], verified: true, vip: true, years: 100}, threshold: 10}}, + {input: {threshold: 100, shipment: {years: -0.5, active: true, flagged: true, verified: false, insured: true, accounts: [{amount: 100, flagged: true, region: "3.5", city: "日本"}]}}, goals: ["acct.band", "acct.flag"], output: {shipment: {accounts: [{amount: 100, band: 100, city: "日本", flag: ["3.5"], flagged: true, rank: -0.5, region: "3.5"}], active: true, flagged: true, insured: true, verified: false, years: -0.5}, threshold: 100}}, + {input: {threshold: 0, shipment: {years: 1.5, vip: true, active: true, flagged: true, verified: true, insured: true, accounts: [{amount: [1], flagged: false, region: "a-b-c", city: "a"}]}}, goals: ["shipment.share"], output: "!error: InputValidationFailed"}, + {input: {threshold: 0.5, shipment: {years: 1000000, active: false, flagged: true, verified: true, insured: false, accounts: [{amount: 123456789.123, flagged: false, region: "a-b-c", city: "NL"}, {amount: 5, flagged: false, region: "US", city: " pad "}]}}, goals: ["shipment.risk"], output: {shipment: {accounts: [{amount: 123456789.123, city: "NL", flagged: false, region: "a-b-c"}, {amount: 5, city: " pad ", flagged: false, region: "US"}], active: false, discount: "none", flagged: true, insured: false, review: "Oslo", risk: 1000000, verified: true, years: 1000000}, threshold: 0.5}}, + {input: {threshold: 1, shipment: {years: 1.5, vip: false, active: false, flagged: true, verified: false, insured: true, accounts: [{amount: 10, flagged: true, region: "a", city: "Oslo"}, {amount: 0.5, flagged: false, region: "é ü", city: "retail"}], extraField: {nested: true}}}, goals: ["shipment.risk"], output: {shipment: {accounts: [{amount: 10, city: "Oslo", flagged: true, region: "a"}, {amount: 0.5, city: "retail", flagged: false, region: "é ü"}], active: false, discount: "a", extraField: {nested: true}, flagged: true, insured: true, review: "Oslo", risk: 1.5, verified: false, vip: false, years: 1.5}, threshold: 1}}, + ], +} + +// seed 350700 (attempt 0) +{ + name: "goals 08: tenant/members/employees: 1 assertion, 2 expression, 5 match, 1 table; 0 root, 5 per-member, 4 top-level computed", + policy: { + models: {tenant: {limit: "number", region: "string?", urgent: "boolean", channel: "string", birthDate: "date?", members: "member[]"}, member: {days: "number", code: "string", birthDate: "date", priority: "boolean", employees: "employee[]"}, employee: {years: "number", channel: "string", label: "string?"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {match: "member.discount", arms: [["tenant.region != null", "(tenant.birthDate ?? d('2025-01-01')).format('%Y-%m')"], ["member.birthDate.isBefore(d('2000-06-30'), 'day')", "tenant.channel"], ["tenant.region != null", "tenant.channel"], ["(tenant.urgent or member.priority)", "tenant.channel"], ["", "(tenant.region ?? '')"]]}, + {match: "member.penalty", arms: [["member.birthDate < d('2000-06-30')", "len(filter(member.employees, #.years in [4..134)))"], ["matches((tenant.region ?? ''), '^.{2,}$')", "(round(member.days / 7, 2) % (abs(count(member.employees, #.years in [35..62])) + 1))"], ["threshold in [26..97]", "threshold"], ["(member.priority or member.priority)", "tenant.limit"], ["", "threshold"]]}, + {table: "t3", hit: "collect", inputs: ["tenant.limit", "len(filter(tenant.members, contains(#.code, 'Oslo')))", "(tenant.birthDate ?? d('2025-01-01'))"], outputs: ["scores.eligible"], rules: [ + ["!= 3", "[1.5..332.5]", "> d('2000-06-30')", "tenant.urgent"], + ["!= 50", "<= 0", "> d('2000-06-30')", "(tenant.urgent and tenant.urgent)"], + ["", "", "", "tenant.urgent"], + ]}, + {assertion: "member.grade", conditions: [["or", "(member.priority and tenant.urgent)", 1], ["and", "not (member.code in ['DE', 'low'])", 2], ["and", "tenant.birthDate != null", 0]]}, + {match: "margin", arms: [["(tenant.urgent or tenant.urgent)", "tenant.channel"], ["some(tenant.members, #.penalty == #.days)", "`${tenant.limit}/${len(filter(tenant.members, #.code in ['retail', 'high']))}`"], ["", "tenant.channel"]]}, + {expression: "scores.level", value: "(sum([3, 250, tenant.limit]) - (tenant.birthDate ?? d('2025-01-01')).year())"}, + {expression: "member.rank", value: "tenant.region"}, + {match: "share", arms: [["(not (tenant.urgent) and (tenant.birthDate ?? d('2025-01-01')).isAfter(d('2025-03-20'), 'day'))", "tenant.birthDate != null"], ["tenant.birthDate == null", "len(tenant.members) != tenant.limit"], ["(avg(map(tenant.members, #.penalty)) ?? 0) <= scores.level", "not (tenant.urgent)"], ["", "contains(['low', 'x', ''], margin)"]]}, + {match: "member.surcharge", arms: [["some(member.employees, contains((#.label ?? ''), 'low'))", "member.code"], ["member.birthDate.isSameOrBefore(d('2025-03-20'), 'day')", "member.discount"], ["tenant.region != null", "(margin + '-' + 'x')"], ["", "member.discount"]]}, + ], + }, + cases: [ + {input: {threshold: -2, tenant: {limit: 7.25, region: "DE", urgent: true, channel: "ok", birthDate: "2030-12-31", members: [{days: 250, code: "x", birthDate: "2025-03-20T10:15:30Z", priority: true, employees: []}, {days: 0.1, code: "low", birthDate: "2024-02-29", priority: true, employees: [{years: 0, channel: "NL", label: "3.5"}, {years: -0, channel: "x-y", label: "日本"}, {years: 100, channel: "low", label: "a-b-c"}]}]}}, goals: ["share"], output: {margin: "ok", scores: {level: -1769.75}, share: false, tenant: {birthDate: "2030-12-31", channel: "ok", limit: 7.25, members: [{birthDate: "2025-03-20T10:15:30Z", code: "x", days: 250, employees: [], penalty: 0.71, priority: true}, {birthDate: "2024-02-29", code: "low", days: 0.1, employees: [{channel: "NL", label: "3.5", years: 0}, {channel: "x-y", label: "日本", years: 0}, {channel: "low", label: "a-b-c", years: 100}], penalty: 0.01, priority: true}], region: "DE", urgent: true}, threshold: -2}}, + {input: {threshold: 0.5, tenant: {limit: 1, region: "DE", urgent: false, channel: "Oslo", birthDate: "2025-03-20", members: [{days: 2, code: "VIP", birthDate: "2024-01-01", priority: true, employees: [{years: -1, channel: "é ü", label: "3.5"}, {years: 100, channel: "low", label: "retail"}]}]}}, goals: ["scores.level"], output: {scores: {level: -1771}, tenant: {birthDate: "2025-03-20", channel: "Oslo", limit: 1, members: [{birthDate: "2024-01-01", code: "VIP", days: 2, employees: [{channel: "é ü", label: "3.5", years: -1}, {channel: "low", label: "retail", years: 100}], priority: true}], region: "DE", urgent: false}, threshold: 0.5}}, + {input: {threshold: 100, tenant: {limit: -0.01, region: "é ü", urgent: false, channel: "é ü", birthDate: "2024-01-01", members: [{days: 3, code: "gold", birthDate: "2000-01-01", priority: true, employees: [{years: 5, channel: "A1", label: "3.5"}, {years: 99.99, channel: ""}]}]}}, goals: ["scores.eligible"], output: {scores: {eligible: [false, false]}, tenant: {birthDate: "2024-01-01", channel: "é ü", limit: -0.01, members: [{birthDate: "2000-01-01", code: "gold", days: 3, employees: [{channel: "A1", label: "3.5", years: 5}, {channel: "", years: 99.99}], priority: true}], region: "é ü", urgent: false}, threshold: 100}}, + {input: {threshold: 1, tenant: {limit: 5, region: "x", urgent: false, channel: "abc", birthDate: "2024-02-29", members: [{days: 100, code: "high", birthDate: "2030-12-31", priority: false, employees: [{years: 3, channel: "low", label: "US"}, {years: 18, channel: "Zed", label: "retail"}, {years: 0.5, channel: "US", label: "high"}]}, {days: 1.5, code: "Zed", birthDate: "2000-01-01", priority: true, employees: [{years: 99999999999999999999, channel: "low", label: null}]}, {days: 1000000, code: "Oslo", birthDate: "1990-06-15", priority: false, employees: [{years: 0, channel: "A1", label: "日本"}, {years: -0, channel: "US"}]}, {days: 123456789.123, code: "low", birthDate: "1990-06-15", priority: true, employees: [{years: 0.000001, channel: "-", label: null}]}, {days: 3, code: "A1", birthDate: "2000-01-01", priority: false, employees: []}, {days: 99999999999999999999, code: "gold", birthDate: "2025-03-20T10:15:30Z", priority: true, employees: []}, {days: 1000, code: "é ü", birthDate: "2025-03-20T10:15:30Z", priority: false, employees: [{years: 50, channel: "a-b-c", label: null}, {years: -0.01, channel: "é ü", label: "a-b-c"}, {years: 3, channel: "x", label: "NL"}]}, {days: 0.5, code: "DE", birthDate: "2000-01-01", priority: true, employees: [{years: -0.01, channel: "A1", label: null}, {years: 10, channel: "Zed", label: null}]}, {days: 10, code: "retail", birthDate: "2000-01-01", priority: false, employees: [{years: 0.5, channel: "日本", label: null}]}, {days: 99.99, code: "retail", birthDate: "2024-01-01", priority: true, employees: [{years: 0.000001, channel: " pad ", label: "high"}, {years: 0, channel: "x", label: "high"}, {years: 5, channel: "-", label: "ok"}]}, {days: 65, code: "Oslo", birthDate: "2024-01-01", priority: true, employees: [{years: 2, channel: "Oslo", label: ""}, {years: -500, channel: "12", label: "DE"}]}, {days: 1, code: "DE", birthDate: "2024-02-29", priority: false, employees: [{years: 99999999999999999999, channel: "high", label: null}, {years: 0.5, channel: "日本", label: "VIP"}, {years: 2.50, channel: " pad ", label: "DE"}]}, {days: 0.5, code: "low", birthDate: "1990-06-15", priority: true, employees: []}]}}, goals: ["share", "member.rank", "margin"], output: {margin: "5/3", scores: {level: -1766}, share: false, tenant: {birthDate: "2024-02-29", channel: "abc", limit: 5, members: [{birthDate: "2030-12-31", code: "high", days: 100, employees: [{channel: "low", label: "US", years: 3}, {channel: "Zed", label: "retail", years: 18}, {channel: "US", label: "high", years: 0.5}], penalty: 1, priority: false, rank: "x"}, {birthDate: "2000-01-01", code: "Zed", days: 1.5, employees: [{channel: "low", label: null, years: 99999999999999999999}], penalty: 0, priority: true, rank: "x"}, {birthDate: "1990-06-15", code: "Oslo", days: 1000000, employees: [{channel: "A1", label: "日本", years: 0}, {channel: "US", years: 0}], penalty: 0, priority: false, rank: "x"}, {birthDate: "1990-06-15", code: "low", days: 123456789.123, employees: [{channel: "-", label: null, years: 0.000001}], penalty: 0, priority: true, rank: "x"}, {birthDate: "2000-01-01", code: "A1", days: 3, employees: [], penalty: 0, priority: false, rank: "x"}, {birthDate: "2025-03-20T10:15:30Z", code: "gold", days: 99999999999999999999, employees: [], penalty: 5, priority: true, rank: "x"}, {birthDate: "2025-03-20T10:15:30Z", code: "é ü", days: 1000, employees: [{channel: "a-b-c", label: null, years: 50}, {channel: "é ü", label: "a-b-c", years: -0.01}, {channel: "x", label: "NL", years: 3}], penalty: 1, priority: false, rank: "x"}, {birthDate: "2000-01-01", code: "DE", days: 0.5, employees: [{channel: "A1", label: null, years: -0.01}, {channel: "Zed", label: null, years: 10}], penalty: 1, priority: true, rank: "x"}, {birthDate: "2000-01-01", code: "retail", days: 10, employees: [{channel: "日本", label: null, years: 0.5}], penalty: 0, priority: false, rank: "x"}, {birthDate: "2024-01-01", code: "retail", days: 99.99, employees: [{channel: " pad ", label: "high", years: 0.000001}, {channel: "x", label: "high", years: 0}, {channel: "-", label: "ok", years: 5}], penalty: 5, priority: true, rank: "x"}, {birthDate: "2024-01-01", code: "Oslo", days: 65, employees: [{channel: "Oslo", label: "", years: 2}, {channel: "12", label: "DE", years: -500}], penalty: 5, priority: true, rank: "x"}, {birthDate: "2024-02-29", code: "DE", days: 1, employees: [{channel: "high", label: null, years: 99999999999999999999}, {channel: "日本", label: "VIP", years: 0.5}, {channel: " pad ", label: "DE", years: 2.50}], penalty: 1, priority: false, rank: "x"}, {birthDate: "1990-06-15", code: "low", days: 0.5, employees: [], penalty: 0, priority: true, rank: "x"}], region: "x", urgent: false}, threshold: 1}}, + {input: {threshold: 0.5, tenant: {limit: 1000, urgent: true, channel: "retail", birthDate: "2025-03-20T10:15:30Z", members: []}}, goals: ["member.grade", "scores.level"], output: {scores: {level: -772}, tenant: {birthDate: "2025-03-20T10:15:30Z", channel: "retail", limit: 1000, members: [], urgent: true}, threshold: 0.5}}, + {input: {threshold: -2, tenant: {limit: -1, region: "low", urgent: true, channel: "low", birthDate: "2025-03-20T10:15:30Z", members: [{days: 100, code: "3.5", birthDate: "2000-01-01", priority: true, employees: [{years: 0.000001, channel: "high", label: "Zed"}, {years: 1, channel: "low", label: "A1"}, {years: 250, channel: "high", label: "DE"}]}, {days: 10, code: "US", birthDate: "2030-12-31", priority: false, employees: [{years: 1.5, channel: "gold", label: " pad "}, {years: 100, channel: "high", label: ""}, {years: 65, channel: "low", label: "Zed"}]}]}}, goals: ["member.rank", "scores.eligible", "member.penalty"], output: {scores: {eligible: [true, true]}, tenant: {birthDate: "2025-03-20T10:15:30Z", channel: "low", limit: -1, members: [{birthDate: "2000-01-01", code: "3.5", days: 100, employees: [{channel: "high", label: "Zed", years: 0.000001}, {channel: "low", label: "A1", years: 1}, {channel: "high", label: "DE", years: 250}], penalty: 0, priority: true, rank: "low"}, {birthDate: "2030-12-31", code: "US", days: 10, employees: [{channel: "gold", label: " pad ", years: 1.5}, {channel: "high", label: "", years: 100}, {channel: "low", label: "Zed", years: 65}], penalty: 0.43, priority: false, rank: "low"}], region: "low", urgent: true}, threshold: -2}}, + [{threshold: -2, tenant: {limit: 99999999999999999999, region: "12", urgent: false, channel: "DE", birthDate: "2024-01-01", members: [{days: 3, code: "abc", birthDate: "2030-12-31", priority: false, employees: [{years: 100, channel: "日本", label: "é ü"}, {years: 250, channel: "retail", label: "low"}, {years: 0.5, channel: "A1", label: "ok"}]}, {days: 2, code: "Oslo", birthDate: "1990-06-15", priority: true, employees: [{years: 7.25, channel: "abc", label: "retail"}, {years: 1e3, channel: "gold", label: "gold"}, {years: 0.5, channel: "gold", label: "x"}]}, {days: 99999999999999999999, code: "O'Neil", birthDate: "1990-06-15", priority: true, employees: []}]}}, {scores: {level: 99999999999999998228}, share: true, tenant: {birthDate: "2024-01-01", channel: "DE", limit: 99999999999999999999, members: [{birthDate: "2030-12-31", code: "abc", days: 3, discount: "2024-01", employees: [{channel: "日本", label: "é ü", years: 100}, {channel: "retail", label: "low", years: 250}, {channel: "A1", label: "ok", years: 0.5}], grade: true, penalty: 0.43, priority: false, rank: "12", surcharge: "abc"}, {birthDate: "1990-06-15", code: "Oslo", days: 2, discount: "2024-01", employees: [{channel: "abc", label: "retail", years: 7.25}, {channel: "gold", label: "gold", years: 1000}, {channel: "gold", label: "x", years: 0.5}], grade: true, penalty: 1, priority: true, rank: "12", surcharge: "2024-01"}, {birthDate: "1990-06-15", code: "O'Neil", days: 99999999999999999999, discount: "2024-01", employees: [], grade: true, penalty: 0, priority: true, rank: "12", surcharge: "2024-01"}], region: "12", urgent: false}, threshold: -2}], + {input: {threshold: -2, tenant: {limit: 1e3, region: "DE", urgent: true, channel: "A1", birthDate: "2024-01-01", members: [{days: 1000, code: "-", birthDate: "2000-01-01", priority: false, employees: [{years: 100, channel: "A1", label: "A1"}, {years: 0.5, channel: "x", label: "abc"}]}]}}, goals: ["margin", "scores.level", "scores.eligible"], output: {margin: "A1", scores: {eligible: [true, true], level: -771}, tenant: {birthDate: "2024-01-01", channel: "A1", limit: 1000, members: [{birthDate: "2000-01-01", code: "-", days: 1000, employees: [{channel: "A1", label: "A1", years: 100}, {channel: "x", label: "abc", years: 0.5}], penalty: 1, priority: false}], region: "DE", urgent: true}, threshold: -2}}, + {input: {threshold: 100, tenant: {limit: null, region: "3.5", urgent: true, channel: "low", birthDate: "2030-12-31", members: [{days: 123456789.123, code: "US", birthDate: "2024-02-29", priority: false, employees: [{years: 5, channel: "low", label: "Zed"}, {years: 3, channel: "VIP", label: " pad "}]}, {days: 2, code: "ok", birthDate: "2025-03-20T10:15:30Z", priority: false, employees: [{years: 18, channel: "DE", label: "NL"}]}, {days: 250, code: "Oslo", birthDate: "2024-01-01", priority: false, employees: [{years: 2, channel: "a", label: "3.5"}, {years: 0.1, channel: "a", label: "high"}]}, {days: 0.5, code: "high", birthDate: "2030-12-31", priority: true, employees: [{years: 1.5, channel: "", label: "O'Neil"}, {years: 5, channel: "a", label: "a-b-c"}]}, {days: -0.01, code: "-", birthDate: "2024-01-01", priority: true, employees: []}, {days: -0, code: "DE", birthDate: "2024-02-29", priority: false, employees: []}, {days: 100, code: "-", birthDate: "2025-03-20", priority: true, employees: [{years: 7.25, channel: "DE", label: "a-b-c"}, {years: 1, channel: "", label: "US"}]}, {days: 0, code: "A1", birthDate: "1990-06-15", priority: true, employees: [{years: 1, channel: "low", label: "-"}]}, {days: 99999999999999999999, code: "3.5", birthDate: "2024-02-29", priority: true, employees: [{years: -1, channel: "O'Neil", label: "gold"}, {years: 0.000001, channel: "DE", label: "low"}]}, {days: 99999999999999999999, code: "Oslo", birthDate: "2024-01-01", priority: true, employees: [{years: 2, channel: "A1", label: "-"}, {years: 100, channel: "retail", label: "ok"}]}]}}, goals: ["scores.level", "margin"], output: "!error: MissingRequiredInputs"}, + {input: {threshold: 100, tenant: {limit: 2.50, region: "O'Neil", urgent: false, channel: "a-b-c", members: [{days: 2, code: "retail", birthDate: "2000-01-01", priority: true, employees: [{years: 65, channel: "A1", label: "a-b-c"}, {years: -500, channel: "DE", label: "NL"}, {years: 3, channel: "O'Neil", label: "gold"}]}]}}, goals: ["scores.level"], output: {scores: {level: -1769.50}, tenant: {channel: "a-b-c", limit: 2.50, members: [{birthDate: "2000-01-01", code: "retail", days: 2, employees: [{channel: "A1", label: "a-b-c", years: 65}, {channel: "DE", label: "NL", years: -500}, {channel: "O'Neil", label: "gold", years: 3}], priority: true}], region: "O'Neil", urgent: false}, threshold: 100}}, + {input: {threshold: 0, tenant: {limit: 7.25, region: "US", urgent: false, channel: "gold", birthDate: "2030-12-31", members: [{days: 0.5, code: "x-y", birthDate: "2025-03-20", priority: false, employees: [{years: 1e3, channel: "Oslo", label: "O'Neil"}, {years: 3, channel: "low", label: " pad "}, {years: 0.1, channel: "DE", label: "low"}]}, {days: 1.5, code: "x", birthDate: "1990-06-15", priority: true, employees: []}]}}, goals: ["member.grade", "scores.level"], output: {scores: {level: -1769.75}, tenant: {birthDate: "2030-12-31", channel: "gold", limit: 7.25, members: [{birthDate: "2025-03-20", code: "x-y", days: 0.5, employees: [{channel: "Oslo", label: "O'Neil", years: 1000}, {channel: "low", label: " pad ", years: 3}, {channel: "DE", label: "low", years: 0.1}], grade: true, priority: false}, {birthDate: "1990-06-15", code: "x", days: 1.5, employees: [], grade: true, priority: true}], region: "US", urgent: false}, threshold: 0}}, + {input: {threshold: 0.5, tenant: {limit: 7.25, urgent: false, channel: "DE", birthDate: "2025-03-20T10:15:30Z", members: []}}, goals: ["member.grade", "margin"], output: {margin: "DE", tenant: {birthDate: "2025-03-20T10:15:30Z", channel: "DE", limit: 7.25, members: [], urgent: false}, threshold: 0.5}}, + {input: {threshold: 0, tenant: {limit: 0.5, region: null, urgent: true, channel: "x", birthDate: "2030-12-31", members: [{days: 250, code: "a-b-c", birthDate: "2025-03-20", priority: false, employees: [{years: 50, channel: "é ü"}, {years: 65, channel: "high"}, {years: 3, channel: "x", label: "gold"}]}, {days: 1, code: "A1", birthDate: "2025-03-20T10:15:30Z", priority: false, employees: [{years: 100, channel: "Zed", label: "low"}, {years: 1.5, channel: "high", label: "DE"}]}]}}, goals: ["member.surcharge", "member.discount"], output: {tenant: {birthDate: "2030-12-31", channel: "x", limit: 0.5, members: [{birthDate: "2025-03-20", code: "a-b-c", days: 250, discount: "x", employees: [{channel: "é ü", years: 50}, {channel: "high", years: 65}, {channel: "x", label: "gold", years: 3}], priority: false, surcharge: "x"}, {birthDate: "2025-03-20T10:15:30Z", code: "A1", days: 1, discount: "x", employees: [{channel: "Zed", label: "low", years: 100}, {channel: "high", label: "DE", years: 1.5}], priority: false, surcharge: "A1"}], region: null, urgent: true}, threshold: 0}}, + [{threshold: 0, tenant: {limit: 1000, region: "gold", urgent: false, channel: "gold", birthDate: "2025-03-20T10:15:30Z", members: [{days: 100, code: "", birthDate: "2030-12-31", priority: false, employees: [{years: 0.5, channel: " pad ", label: "Oslo"}, {years: 1000000, channel: "12", label: "A1"}]}], extraField: 1}}, {margin: "gold", scores: {level: -772}, share: false, tenant: {birthDate: "2025-03-20T10:15:30Z", channel: "gold", extraField: 1, limit: 1000, members: [{birthDate: "2030-12-31", code: "", days: 100, employees: [{channel: " pad ", label: "Oslo", years: 0.5}, {channel: "12", label: "A1", years: 1000000}], grade: true, penalty: 0.29, priority: false, rank: "gold", surcharge: "gold-x"}], region: "gold", urgent: false}, threshold: 0}], + {input: {threshold: 0, tenant: {limit: 1e3, region: "gold", urgent: true, channel: "Oslo", birthDate: "2025-03-20T10:15:30Z", members: [{days: 1000, code: "A1", birthDate: "2024-01-01", priority: false, employees: [{years: 50, channel: "DE", label: "x-y"}, {years: 100, channel: "NL", label: "US"}, {years: 5, channel: "NL", label: "x"}]}, {days: -0, code: "US", birthDate: "2024-02-29", priority: true, employees: [{years: 1.5, channel: "VIP", label: "-"}, {years: 1000, channel: "gold", label: "DE"}]}, {days: 0.1, code: "retail", birthDate: "2024-01-01", priority: true, employees: [{years: 2, channel: "A1", label: "é ü"}, {years: 5, channel: "Oslo", label: "low"}]}, {days: 5, code: "low", birthDate: "2000-01-01", priority: true, employees: [{years: 3, channel: "low", label: "DE"}, {years: 5, channel: "high", label: "high"}, {years: 0.5, channel: "é ü", label: "abc"}]}]}}, goals: ["member.grade"], output: {tenant: {birthDate: "2025-03-20T10:15:30Z", channel: "Oslo", limit: 1000, members: [{birthDate: "2024-01-01", code: "A1", days: 1000, employees: [{channel: "DE", label: "x-y", years: 50}, {channel: "NL", label: "US", years: 100}, {channel: "NL", label: "x", years: 5}], grade: true, priority: false}, {birthDate: "2024-02-29", code: "US", days: 0, employees: [{channel: "VIP", label: "-", years: 1.5}, {channel: "gold", label: "DE", years: 1000}], grade: true, priority: true}, {birthDate: "2024-01-01", code: "retail", days: 0.1, employees: [{channel: "A1", label: "é ü", years: 2}, {channel: "Oslo", label: "low", years: 5}], grade: true, priority: true}, {birthDate: "2000-01-01", code: "low", days: 5, employees: [{channel: "low", label: "DE", years: 3}, {channel: "high", label: "high", years: 5}, {channel: "é ü", label: "abc", years: 0.5}], grade: true, priority: true}], region: "gold", urgent: true}, threshold: 0}}, + {input: {threshold: 10, tenant: {limit: 1, region: "retail", urgent: false, channel: "Oslo", birthDate: "2024-02-29", members: [{days: 1.5, code: "日本", birthDate: "1990-06-15", priority: true, employees: [{years: 99999999999999999999, channel: "NL", label: ""}]}]}}, goals: ["scores.level", "member.penalty", "share"], output: {margin: "Oslo", scores: {level: -1770}, share: false, tenant: {birthDate: "2024-02-29", channel: "Oslo", limit: 1, members: [{birthDate: "1990-06-15", code: "日本", days: 1.5, employees: [{channel: "NL", label: "", years: 99999999999999999999}], penalty: 0, priority: true}], region: "retail", urgent: false}, threshold: 10}}, + ], +} + +// seed 350800 (attempt 0) +{ + name: "goals 09: account/accounts: 1 assertion, 2 expression, 3 table; 1 root, 7 per-member, 0 top-level computed", + policy: { + models: {account: {amount: "number?", birthDate: "date", income: "number", accounts: "acct[]"}, acct: {days: "number", limit: "number"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {expression: "acct.net", value: "{ok: `${acct.calc.exposure}/${(min(map(account.accounts, (#.flag ?? 0))) ?? 0)}`}"}, + {expression: "acct.flag", value: "(account.amount != null ? account.amount : null)"}, + {table: "t4", inputs: ["acct.limit"], outputs: ["acct.segment[]"], rules: [ + ["<= 250", "'a'"], + ["< 1", "`${acct.calc.exposure}/${acct.days}`"], + ["", "'DE'"], + ]}, + {table: "t6", inputs: ["baseRate"], outputs: ["account.fee[]"], rules: [ + ["", "-(baseRate)"], + ["[0..328]", "max([baseRate])"], + ["!= 1000", "baseRate"], + ["10", "account.income"], + ["", ""], + ["", "(baseRate * 5)"], + ]}, + {assertion: "acct.calc.exposure", conditions: [["or", "account.birthDate.isBefore(d('2024-01-01'), 'year')", 2], ["and", "account.amount == null", 2], ["or", "acct.days in (44..44)", 0]]}, + {table: "t3", hit: "collect", inputs: ["acct.limit", "account.birthDate"], outputs: ["acct.band", "acct.margin"], rules: [ + [">= 0", "", "acct.limit in (38..80]", "3"], + ["", "< d('2024-01-01')", "", "(account.amount ?? 0)"], + ["< 1.5", ">= d('2025-01-01')", "(acct.flag ?? 0) > 1.5", ""], + ["5", "> d('2000-06-30')", "account.income in [35..165]", "100"], + ["<= 1", "< d('2025-01-01')", "account.birthDate < d('2025-01-01')", ""], + ["", "", "not (acct.calc.exposure)", "(acct.calc.exposure ? (account.amount ?? 0) : 0.25)"], + ]}, + ], + }, + cases: [ + {input: {baseRate: -2, account: {amount: null, birthDate: "1990-06-15", income: 1, accounts: [{days: 123456789.123, limit: 1.5}, {days: 0.000001, limit: 0.25}, {days: 3, limit: -1}, {days: 5, limit: 1.5}, {days: 0, limit: 100}]}}, goals: ["acct.margin", "acct.segment"], output: {account: {accounts: [{band: [false, true], calc: {exposure: false}, days: 123456789.123, limit: 1.5, margin: [3, 0, 0.25], segment: ["a", "DE"]}, {band: [false, true, true], calc: {exposure: false}, days: 0.000001, limit: 0.25, margin: [3, 0, 0.25], segment: ["a", "false/0.000001", "DE"]}, {band: [true, true], calc: {exposure: false}, days: 3, limit: -1, margin: [0, 0.25], segment: ["a", "false/3", "DE"]}, {band: [false, true], calc: {exposure: false}, days: 5, limit: 1.5, margin: [3, 0, 0.25], segment: ["a", "DE"]}, {band: [false, true], calc: {exposure: false}, days: 0, limit: 100, margin: [3, 0, 0.25], segment: ["a", "DE"]}], amount: null, birthDate: "1990-06-15", income: 1}, baseRate: -2}}, + {input: {baseRate: 0, account: {amount: 1.5, birthDate: "2000-01-01", income: 1, accounts: [], extraField: 1}}, goals: ["acct.segment"], output: {account: {accounts: [], amount: 1.5, birthDate: "2000-01-01", extraField: 1, income: 1}, baseRate: 0}}, + {input: {baseRate: -2, account: {amount: null, birthDate: "2024-02-29", income: 1000, accounts: [{days: 100, limit: 0.000001}]}}, goals: ["acct.segment", "acct.band", "acct.calc.exposure"], output: {account: {accounts: [{band: [false, true, true], calc: {exposure: false}, days: 100, limit: 0.000001, margin: [3, 0.25], segment: ["a", "false/100", "DE"]}], amount: null, birthDate: "2024-02-29", income: 1000}, baseRate: -2}}, + [{baseRate: 0.5, account: {amount: null, birthDate: "2025-03-20T10:15:30Z", income: 18, accounts: [{days: 250, limit: 0.5}, {days: 99999999999999999999, limit: 99999999999999999999}, {days: 100, limit: 250}, {days: 1000000, limit: 3}, {days: -0, limit: 1000000}]}}, {account: {accounts: [{band: [false, false, true], calc: {exposure: false}, days: 250, flag: null, limit: 0.5, margin: [3, 0.25], net: {ok: "false/0"}, segment: ["a", "false/250", "DE"]}, {band: [false, true], calc: {exposure: false}, days: 99999999999999999999, flag: null, limit: 99999999999999999999, margin: [3, 0.25], net: {ok: "false/0"}, segment: ["DE"]}, {band: [false, true], calc: {exposure: false}, days: 100, flag: null, limit: 250, margin: [3, 0.25], net: {ok: "false/0"}, segment: ["a", "DE"]}, {band: [false, true], calc: {exposure: false}, days: 1000000, flag: null, limit: 3, margin: [3, 0.25], net: {ok: "false/0"}, segment: ["a", "DE"]}, {band: [false, true], calc: {exposure: false}, days: 0, flag: null, limit: 1000000, margin: [3, 0.25], net: {ok: "false/0"}, segment: ["DE"]}], amount: null, birthDate: "2025-03-20T10:15:30Z", fee: [-0.5, 0.5, 0.5, 2.5], income: 18}, baseRate: 0.5}], + {input: {baseRate: 0.5, account: {amount: 3, birthDate: "2024-01-01", income: 0.25, accounts: [{days: 99.99, limit: 1000}, {days: 0, limit: 123456789.123}, {days: -0, limit: 250}, {days: 99.99, limit: 5}]}}, goals: ["acct.margin"], output: {account: {accounts: [{band: [false, true], calc: {exposure: false}, days: 99.99, limit: 1000, margin: [3, 0.25]}, {band: [false, true], calc: {exposure: false}, days: 0, limit: 123456789.123, margin: [3, 0.25]}, {band: [false, true], calc: {exposure: false}, days: 0, limit: 250, margin: [3, 0.25]}, {band: [false, false, true], calc: {exposure: false}, days: 99.99, limit: 5, margin: [3, 100, 0.25]}], amount: 3, birthDate: "2024-01-01", income: 0.25}, baseRate: 0.5}}, + {input: {baseRate: 1, account: {amount: 7.25, birthDate: 20250101, income: 1, accounts: [{days: 1.5, limit: 10}]}}, goals: ["acct.calc.exposure"], output: "!error: InputValidationFailed"}, + [{baseRate: 100, account: {amount: 1e3, birthDate: "2024-01-01", income: 1000, accounts: [{days: 10, limit: -0.01}], extraField: 1}}, {account: {accounts: [{band: [true, true], calc: {exposure: false}, days: 10, flag: 1000, limit: -0.01, margin: [0.25], net: {ok: "false/1000"}, segment: ["a", "false/10", "DE"]}], amount: 1000, birthDate: "2024-01-01", extraField: 1, fee: [-100, 100, 100, 500], income: 1000}, baseRate: 100}], + {input: {baseRate: 1, account: {amount: 18, birthDate: "1990-06-15", income: 5, accounts: [{days: 0.25, limit: 1.5}, {days: 0.5, limit: 1}]}}, goals: ["acct.flag", "acct.calc.exposure"], output: {account: {accounts: [{calc: {exposure: false}, days: 0.25, flag: 18, limit: 1.5}, {calc: {exposure: false}, days: 0.5, flag: 18, limit: 1}], amount: 18, birthDate: "1990-06-15", income: 5}, baseRate: 1}}, + {input: {baseRate: 10, account: {amount: 1.5, birthDate: "2025-03-20", income: 123456789.123, accounts: [{days: 1000, limit: 1}]}}, goals: ["acct.flag", "account.fee", "acct.margin"], output: {account: {accounts: [{band: [false, false, true], calc: {exposure: false}, days: 1000, flag: 1.5, limit: 1, margin: [3, 0.25]}], amount: 1.5, birthDate: "2025-03-20", fee: [-10, 10, 10, 123456789.123, 50], income: 123456789.123}, baseRate: 10}}, + {input: {baseRate: 0, account: {amount: null, birthDate: "2024-01-01", income: 1, accounts: [{days: 100, limit: 0.000001}, {days: -0.5, limit: 1.5}, {days: 5, limit: 1}]}}, goals: ["acct.flag", "acct.net"], output: {account: {accounts: [{calc: {exposure: false}, days: 100, flag: null, limit: 0.000001, net: {ok: "false/0"}}, {calc: {exposure: false}, days: -0.5, flag: null, limit: 1.5, net: {ok: "false/0"}}, {calc: {exposure: false}, days: 5, flag: null, limit: 1, net: {ok: "false/0"}}], amount: null, birthDate: "2024-01-01", income: 1}, baseRate: 0}}, + {input: {baseRate: 0.5, account: {amount: 100, birthDate: "2025-03-20T10:15:30Z", income: 1000, accounts: [{days: 1, limit: 65}, {days: 1.5, limit: 0.000001}, {days: -1, limit: 2.50}, {days: 0, limit: 250}]}}, goals: ["acct.segment"], output: {account: {accounts: [{calc: {exposure: false}, days: 1, limit: 65, segment: ["a", "DE"]}, {calc: {exposure: false}, days: 1.5, limit: 0.000001, segment: ["a", "false/1.5", "DE"]}, {calc: {exposure: false}, days: -1, limit: 2.50, segment: ["a", "DE"]}, {calc: {exposure: false}, days: 0, limit: 250, segment: ["a", "DE"]}], amount: 100, birthDate: "2025-03-20T10:15:30Z", income: 1000}, baseRate: 0.5}}, + {input: {baseRate: 100, account: {amount: null, birthDate: "2000-01-01", income: 5, accounts: [{days: 2.50, limit: 0.25}]}}, goals: ["acct.calc.exposure"], output: {account: {accounts: [{calc: {exposure: false}, days: 2.50, limit: 0.25}], amount: null, birthDate: "2000-01-01", income: 5}, baseRate: 100}}, + ], +} + +// seed 350900 (attempt 0) +{ + name: "goals 10: shipment/parcels: 1 assertion, 3 expression, 1 match, 4 table; 3 root, 6 per-member, 6 top-level computed", + policy: { + models: {shipment: {score: "number", tier: "string(gold|silver|bronze)?", birthDate: "date", rate: "number?", weight: "number", since: "date?", parcels: "parcel[]"}, parcel: {rate: "number?", score: "number", code: "string"}}, + blocks: [ + {table: "t1", inputs: [null, "shipment.rate", "(shipment.rate ?? 0)"], outputs: ["totals.review"], rules: [ + ["", "", ">= 1.5", "shipment.score > 5"], + ["", "10", "[100..377]", "shipment.weight > 5"], + ["shipment.rate != null", "18, 2", "> 10", "250 == 3"], + ]}, + {table: "t2", inputs: ["shipment.weight", null, null], outputs: ["shipment.calc.eligible[]", "shipment.flags.margin[]", "shipment.points"], rules: [ + ["", "not ((totals.review ?? false))", "((totals.review ?? false) or (totals.review ?? false))", "'DE'", "(totals.review ?? false)", "(totals.review ?? false)"], + ["> 1000", "not ((totals.review ?? false))", "1000 != shipment.weight", "'retail'", "((totals.review ?? false) and (totals.review ?? false))", "((totals.review ?? false) and (totals.review ?? false))"], + [">= 0.25", "shipment.score in [1..123)", "shipment.score in [0..121]", "string(shipment.score)", "(totals.review ?? false)", "(totals.review ?? false)"], + ["3", "(shipment.rate ?? 0) == (shipment.rate ?? 0)", "not ((totals.review ?? false))", "`${(shipment.rate ?? 0)}/${(totals.review ?? false)}`", "(totals.review ?? false)", "(totals.review ?? false)"], + ["< 0.25", "", "", "'US'", "", "(totals.review ?? false)"], + ["", "", "", "shipment.birthDate.format('%Y-%m')", "(totals.review ?? false)", "(totals.review ?? false)"], + ]}, + {expression: "parcel.meta.level", value: "(min(map(shipment.parcels, (#.rate ?? 0))) ?? 0)"}, + {match: "parcel.adjusted", arms: [["some(shipment.parcels, isNumeric(#.code))", "ceil((parcel.rate ?? 0))"], ["all(shipment.parcels, #.rate != null)", "((shipment.rate ?? 0) - 0.5)"], ["shipment.birthDate >= d('2024-01-01')", "parcel.score"], ["", "(shipment.rate ?? 0)"]]}, + {assertion: "decision", conditions: [["and", "shipment.birthDate.isSameOrBefore(d('2024-01-01'), 'month')", 1], ["and", "shipment.score > (shipment.rate ?? 0)", 0], ["or", "not ((totals.review ?? false))", 2]]}, + {table: "t6", hit: "collect", inputs: ["decision"], outputs: ["parcel.scores.surcharge", "parcel.meta.tag", "parcel.segment"], rules: [ + ["", "parcel.code", "parcel.meta.level in [-5..59)", "parcel.score"], + ["", "", "(shipment.points ?? false)", "parcel.meta.level"], + ["", "parcel.code", "(shipment.points ?? false)", "0.5"], + ["true", "(decision ? 'retail' : parcel.code)", "(shipment.points ?? false)", "parcel.meta.level"], + ]}, + {expression: "total", value: "filter(shipment.parcels, contains(['ok', 'A1', ''], #.code))"}, + {table: "t8", inputs: ["sum(map(shipment.parcels, trunc(#.score)))", "decision", "totals.review"], outputs: ["health", "weighted", "discount"], rules: [ + ["", "true", "", "(shipment.rate ?? 0)", "string((shipment.points ?? false))", "100"], + ["0, 10", "true", "true", "", "string((shipment.rate ?? 0))", "100"], + ["", "true", "", "shipment.weight", "'Oslo'", "(shipment.rate ?? 0)"], + ["<= 50", "true", "true", "(shipment.rate ?? 0)", "", "((shipment.points ?? false) ? shipment.score : shipment.weight)"], + ["> 10", "true", "false", "shipment.weight", "'gold'", "50"], + ["!= 100", "true", "", "", "string(shipment.score)", "2"], + ["<= 5", "false", "false", "1000", "'none'", "sum([(shipment.rate ?? 0)])"], + ]}, + {expression: "parcel.quota", value: "matches((weighted ?? ''), '[0-9]$')"}, + ], + }, + cases: [ + {input: {shipment: {score: 0, tier: "gold", birthDate: "2025-03-20", rate: 10, weight: 1000000, parcels: [{rate: 0.000001, score: 0.5, code: "retail"}]}}, goals: ["parcel.segment", "shipment.flags.margin"], output: {decision: false, shipment: {birthDate: "2025-03-20", calc: {eligible: ["retail", "2025-03"]}, flags: {margin: [false, false]}, parcels: [{code: "retail", meta: {level: 0.000001, tag: [true, false, false]}, rate: 0.000001, score: 0.5, scores: {surcharge: ["retail", "retail"]}, segment: [0.5, 0.000001, 0.5]}], points: false, rate: 10, score: 0, tier: "gold", weight: 1000000}, totals: {review: false}}}, + {input: {shipment: {score: 0.5, tier: "bronze", birthDate: "2025-03-20T10:15:30Z", rate: 100, weight: [1], since: "2024-02-29", parcels: [{rate: 5, score: 100, code: "a"}, {rate: 0.5, score: 250, code: "retail"}, {rate: 3, score: 5, code: "low"}]}}, goals: ["parcel.adjusted"], output: "!error: InputValidationFailed"}, + {input: {shipment: {score: 1.5, tier: "bronze", birthDate: "2030-12-31", rate: 1000, weight: 1000, since: null, parcels: []}}, goals: ["parcel.quota", "shipment.calc.eligible"], output: {decision: false, discount: 1000, health: 1000, shipment: {birthDate: "2030-12-31", calc: {eligible: ["1.5", "2030-12"]}, flags: {margin: [false, false]}, parcels: [], points: false, rate: 1000, score: 1.5, since: null, tier: "bronze", weight: 1000}, totals: {review: false}, weighted: "none"}}, + {input: {shipment: {score: 5, birthDate: "2024-01-01", rate: null, weight: 100, parcels: [{rate: 10, score: 10, code: "US"}, {score: 10, code: "x"}, {rate: 1.5, score: 2, code: "ok"}, {rate: 18, score: 0, code: "high"}, {rate: 3, score: 100, code: "x"}]}}, goals: ["health", "shipment.calc.eligible"], output: {decision: true, discount: 100, health: 0, shipment: {birthDate: "2024-01-01", calc: {eligible: ["5", "2024-01"]}, flags: {margin: [false, false]}, parcels: [{code: "US", rate: 10, score: 10}, {code: "x", score: 10}, {code: "ok", rate: 1.5, score: 2}, {code: "high", rate: 18, score: 0}, {code: "x", rate: 3, score: 100}], points: false, rate: null, score: 5, weight: 100}, totals: {review: null}, weighted: "false"}}, + [{shipment: {score: 1.5, tier: "bronze", birthDate: "2025-03-20", rate: 1000, weight: 99999999999999999999, since: "2030-12-31", parcels: []}}, {decision: false, discount: 1000, health: 1000, shipment: {birthDate: "2025-03-20", calc: {eligible: ["retail", "1.5", "2025-03"]}, flags: {margin: [false, false, false]}, parcels: [], points: false, rate: 1000, score: 1.5, since: "2030-12-31", tier: "bronze", weight: 99999999999999999999}, total: [], totals: {review: false}, weighted: "none"}], + {input: {shipment: {score: 100, tier: "silver", birthDate: "2025-03-20", rate: 1, weight: 5, since: "2000-01-01", parcels: [{rate: 250, score: 0.5, code: "ok"}, {rate: 2, score: 7.25, code: ""}, {rate: 100, score: 2, code: "a"}]}}, goals: ["parcel.scores.surcharge"], output: {decision: false, shipment: {birthDate: "2025-03-20", calc: {eligible: ["100", "2025-03"]}, flags: {margin: [false, false]}, parcels: [{code: "ok", meta: {level: 2, tag: [true, false, false]}, rate: 250, score: 0.5, scores: {surcharge: ["ok", "ok"]}, segment: [0.5, 2, 0.5]}, {code: "", meta: {level: 2, tag: [true, false, false]}, rate: 2, score: 7.25, scores: {surcharge: ["", ""]}, segment: [7.25, 2, 0.5]}, {code: "a", meta: {level: 2, tag: [true, false, false]}, rate: 100, score: 2, scores: {surcharge: ["a", "a"]}, segment: [2, 2, 0.5]}], points: false, rate: 1, score: 100, since: "2000-01-01", tier: "silver", weight: 5}, totals: {review: null}}}, + {input: {shipment: {score: 317, tier: "gold", birthDate: "1990-06-15", rate: 5, weight: 0.1, since: "2025-03-20T10:15:30Z", parcels: [{rate: 18, score: 2, code: "Oslo"}]}}, goals: ["shipment.flags.margin", "discount"], output: {decision: false, discount: null, health: null, shipment: {birthDate: "1990-06-15", calc: {eligible: ["US", "1990-06"]}, flags: {margin: [true]}, parcels: [{code: "Oslo", rate: 18, score: 2}], points: true, rate: 5, score: 317, since: "2025-03-20T10:15:30Z", tier: "gold", weight: 0.1}, totals: {review: true}, weighted: null}}, + {input: {shipment: {score: 10, birthDate: "2024-02-29", rate: 50, weight: 0.25, parcels: [{rate: 3, score: 2, code: "low"}]}}, goals: ["shipment.points"], output: {shipment: {birthDate: "2024-02-29", calc: {eligible: ["10", "2024-02"]}, flags: {margin: [true, true]}, parcels: [{code: "low", rate: 3, score: 2}], points: true, rate: 50, score: 10, weight: 0.25}, totals: {review: true}}}, + {input: {shipment: {score: 10, tier: "bronze", birthDate: "2025-03-20T10:15:30Z", weight: -0.01, since: "2030-12-31", parcels: [{score: 100, code: "3.5"}, {rate: 1000, score: 250, code: "ok"}, {rate: 10, score: 5, code: "ok"}, {rate: 2, score: 250, code: "ok"}]}}, goals: ["parcel.quota", "total", "totals.review"], output: {decision: false, discount: null, health: null, shipment: {birthDate: "2025-03-20T10:15:30Z", parcels: [{code: "3.5", quota: false, score: 100}, {code: "ok", quota: false, rate: 1000, score: 250}, {code: "ok", quota: false, rate: 10, score: 5}, {code: "ok", quota: false, rate: 2, score: 250}], score: 10, since: "2030-12-31", tier: "bronze", weight: -0.01}, total: [{code: "ok", quota: false, rate: 1000, score: 250}, {code: "ok", quota: false, rate: 10, score: 5}, {code: "ok", quota: false, rate: 2, score: 250}], totals: {review: null}, weighted: null}}, + {input: {shipment: {score: 10, tier: "silver", birthDate: "2024-02-29", weight: 3, parcels: [{score: 1.5, code: "-"}, {score: 1.5, code: "12"}, {rate: null, score: 0.25, code: "retail"}, {score: 50, code: ""}]}}, goals: ["decision", "parcel.quota", "parcel.adjusted"], output: {decision: false, discount: null, health: null, shipment: {birthDate: "2024-02-29", parcels: [{adjusted: 0, code: "-", quota: false, score: 1.5}, {adjusted: 0, code: "12", quota: false, score: 1.5}, {adjusted: 0, code: "retail", quota: false, rate: null, score: 0.25}, {adjusted: 0, code: "", quota: false, score: 50}], score: 10, tier: "silver", weight: 3}, totals: {review: null}, weighted: null}}, + {input: {shipment: {score: 100, birthDate: "2024-02-29", weight: 1000, since: "1990-06-15", parcels: [{rate: null, score: -500, code: "low"}, {rate: 18, score: 2, code: "Oslo"}]}}, goals: ["decision", "weighted"], output: {decision: false, discount: null, health: null, shipment: {birthDate: "2024-02-29", parcels: [{code: "low", rate: null, score: -500}, {code: "Oslo", rate: 18, score: 2}], score: 100, since: "1990-06-15", weight: 1000}, totals: {review: null}, weighted: null}}, + [{shipment: {score: 100, tier: "gold", birthDate: "2030-12-31", rate: 2, weight: 50, since: "2000-01-01", parcels: [{rate: 0.1, score: 10, code: "日本"}, {rate: -0.5, score: 0.5, code: "DE"}]}}, {decision: false, discount: null, health: null, shipment: {birthDate: "2030-12-31", calc: {eligible: ["100", "2030-12"]}, flags: {margin: [true, true]}, parcels: [{adjusted: 1.5, code: "日本", meta: {level: -0.5, tag: [true, true, true]}, quota: false, rate: 0.1, score: 10, scores: {surcharge: ["日本", "日本"]}, segment: [10, -0.5, 0.5]}, {adjusted: 1.5, code: "DE", meta: {level: -0.5, tag: [true, true, true]}, quota: false, rate: -0.5, score: 0.5, scores: {surcharge: ["DE", "DE"]}, segment: [0.5, -0.5, 0.5]}], points: true, rate: 2, score: 100, since: "2000-01-01", tier: "gold", weight: 50}, total: [], totals: {review: true}, weighted: null}], + {input: {shipment: {score: 0.5, tier: "silver", birthDate: "2000-01-01", rate: 5, weight: -500, since: "2000-01-01", parcels: [{rate: 1000, score: 100, code: "-"}, {rate: 1, score: 123456789.123, code: "gold"}, {rate: 7.25, score: 1.5, code: "low"}]}}, goals: ["shipment.flags.margin", "parcel.quota", "total"], output: {decision: false, discount: null, health: null, shipment: {birthDate: "2000-01-01", calc: {eligible: ["US", "2000-01"]}, flags: {margin: [false]}, parcels: [{code: "-", quota: false, rate: 1000, score: 100}, {code: "gold", quota: false, rate: 1, score: 123456789.123}, {code: "low", quota: false, rate: 7.25, score: 1.5}], points: false, rate: 5, score: 0.5, since: "2000-01-01", tier: "silver", weight: -500}, total: [], totals: {review: false}, weighted: null}}, + {input: {shipment: {score: 10, tier: null, birthDate: "2025-03-20T10:15:30Z", rate: null, weight: 2, since: null, parcels: [{rate: 5, score: 18, code: "none"}, {rate: null, score: 10, code: "US"}, {rate: null, score: 0, code: "VIP"}, {rate: 18, score: -500, code: "Oslo"}]}}, goals: ["parcel.segment"], output: {decision: false, shipment: {birthDate: "2025-03-20T10:15:30Z", calc: {eligible: ["10", "2025-03"]}, flags: {margin: [false, false]}, parcels: [{code: "none", meta: {level: 0, tag: [true, false, false]}, rate: 5, score: 18, scores: {surcharge: ["none", "none"]}, segment: [18, 0, 0.5]}, {code: "US", meta: {level: 0, tag: [true, false, false]}, rate: null, score: 10, scores: {surcharge: ["US", "US"]}, segment: [10, 0, 0.5]}, {code: "VIP", meta: {level: 0, tag: [true, false, false]}, rate: null, score: 0, scores: {surcharge: ["VIP", "VIP"]}, segment: [0, 0, 0.5]}, {code: "Oslo", meta: {level: 0, tag: [true, false, false]}, rate: 18, score: -500, scores: {surcharge: ["Oslo", "Oslo"]}, segment: [-500, 0, 0.5]}], points: false, rate: null, score: 10, since: null, tier: null, weight: 2}, totals: {review: null}}}, + {input: {shipment: {score: 2, tier: "silver", birthDate: "1990-06-15", rate: 100, weight: 1000, since: "2025-03-20", parcels: [{rate: 0, score: 2, code: "US"}, {rate: 1000, score: 3, code: "NL"}]}}, goals: ["discount", "totals.review"], output: {decision: false, discount: 100, health: 1000, shipment: {birthDate: "1990-06-15", parcels: [{code: "US", rate: 0, score: 2}, {code: "NL", rate: 1000, score: 3}], rate: 100, score: 2, since: "2025-03-20", tier: "silver", weight: 1000}, totals: {review: false}, weighted: "none"}}, + {input: {shipment: {score: 2.50, tier: "bronze", birthDate: "2030-12-31", weight: 10, parcels: [{rate: null, score: 100, code: "a"}]}}, goals: ["shipment.flags.margin"], output: {shipment: {birthDate: "2030-12-31", calc: {eligible: ["2.50", "2030-12"]}, flags: {margin: [false, false]}, parcels: [{code: "a", rate: null, score: 100}], points: false, score: 2.50, tier: "bronze", weight: 10}, totals: {review: null}}}, + {input: {shipment: {score: 5, birthDate: "2025-03-20", rate: 3, weight: 3, since: "2000-01-01", parcels: [{rate: 2, score: 10, code: " pad "}, {rate: -500, score: 3, code: "retail"}, {rate: 1000, score: 5, code: "VIP"}, {score: 250, code: "high"}, {rate: null, score: 123456789.123, code: "12"}]}}, goals: ["parcel.segment"], output: {decision: false, shipment: {birthDate: "2025-03-20", calc: {eligible: ["5", "3/false", "2025-03"]}, flags: {margin: [false, false, false]}, parcels: [{code: " pad ", meta: {level: -500, tag: [false, false, false]}, rate: 2, score: 10, scores: {surcharge: [" pad ", " pad "]}, segment: [10, -500, 0.5]}, {code: "retail", meta: {level: -500, tag: [false, false, false]}, rate: -500, score: 3, scores: {surcharge: ["retail", "retail"]}, segment: [3, -500, 0.5]}, {code: "VIP", meta: {level: -500, tag: [false, false, false]}, rate: 1000, score: 5, scores: {surcharge: ["VIP", "VIP"]}, segment: [5, -500, 0.5]}, {code: "high", meta: {level: -500, tag: [false, false, false]}, score: 250, scores: {surcharge: ["high", "high"]}, segment: [250, -500, 0.5]}, {code: "12", meta: {level: -500, tag: [false, false, false]}, rate: null, score: 123456789.123, scores: {surcharge: ["12", "12"]}, segment: [123456789.123, -500, 0.5]}], points: false, rate: 3, score: 5, since: "2000-01-01", weight: 3}, totals: {review: false}}}, + {input: {shipment: {score: 18, tier: "gold", birthDate: "2024-01-01", rate: 0, weight: 100, since: "2024-01-01", parcels: [{rate: 3, score: -0.5, code: "low"}, {rate: 2, score: 1000, code: "Zed"}]}}, goals: ["parcel.quota", "parcel.meta.tag", "parcel.adjusted"], output: {decision: true, discount: 100, health: 0, shipment: {birthDate: "2024-01-01", calc: {eligible: ["18", "2024-01"]}, flags: {margin: [false, false]}, parcels: [{adjusted: -0.5, code: "low", meta: {level: 2, tag: [true, false, false, false]}, quota: false, rate: 3, score: -0.5, scores: {surcharge: ["low", "low", "retail"]}, segment: [-0.5, 2, 0.5, 2]}, {adjusted: -0.5, code: "Zed", meta: {level: 2, tag: [true, false, false, false]}, quota: false, rate: 2, score: 1000, scores: {surcharge: ["Zed", "Zed", "retail"]}, segment: [1000, 2, 0.5, 2]}], points: false, rate: 0, score: 18, since: "2024-01-01", tier: "gold", weight: 100}, totals: {review: null}, weighted: "false"}}, + {input: {shipment: {score: 1000, tier: "gold", birthDate: "2025-03-20", rate: 250, weight: 2, since: "1990-06-15", parcels: [{rate: 2.50, score: 2, code: "x"}, {rate: 5, score: 0.000001, code: "ok"}]}}, goals: ["total"], output: {shipment: {birthDate: "2025-03-20", parcels: [{code: "x", rate: 2.50, score: 2}, {code: "ok", rate: 5, score: 0.000001}], rate: 250, score: 1000, since: "1990-06-15", tier: "gold", weight: 2}, total: [{code: "ok", rate: 5, score: 0.000001}]}}, + [{shipment: {score: 5, tier: "silver", birthDate: "2030-12-31", rate: 3, weight: 100, since: "2030-12-31", parcels: [{rate: 100, score: 1.5, code: "a"}, {rate: 1.5, score: 472, code: "x"}, {rate: 3, score: 1000000, code: ""}]}}, {decision: false, discount: null, health: null, shipment: {birthDate: "2030-12-31", calc: {eligible: ["5", "2030-12"]}, flags: {margin: [false, false]}, parcels: [{adjusted: 2.5, code: "a", meta: {level: 1.5, tag: [true, false, false]}, quota: false, rate: 100, score: 1.5, scores: {surcharge: ["a", "a"]}, segment: [1.5, 1.5, 0.5]}, {adjusted: 2.5, code: "x", meta: {level: 1.5, tag: [true, false, false]}, quota: false, rate: 1.5, score: 472, scores: {surcharge: ["x", "x"]}, segment: [472, 1.5, 0.5]}, {adjusted: 2.5, code: "", meta: {level: 1.5, tag: [true, false, false]}, quota: false, rate: 3, score: 1000000, scores: {surcharge: ["", ""]}, segment: [1000000, 1.5, 0.5]}], points: false, rate: 3, score: 5, since: "2030-12-31", tier: "silver", weight: 100}, total: [{adjusted: 2.5, code: "", meta: {level: 1.5, tag: [true, false, false]}, quota: false, rate: 3, score: 1000000, scores: {surcharge: ["", ""]}, segment: [1000000, 1.5, 0.5]}], totals: {review: false}, weighted: null}], + {input: {shipment: {score: 100, tier: "silver", birthDate: "2024-02-29", rate: 0.1, weight: 1000, since: "2025-03-20", parcels: [{rate: 1, score: -0.5, code: "VIP"}]}}, goals: ["shipment.points"], output: {shipment: {birthDate: "2024-02-29", calc: {eligible: ["100", "2024-02"]}, flags: {margin: [false, false]}, parcels: [{code: "VIP", rate: 1, score: -0.5}], points: false, rate: 0.1, score: 100, since: "2025-03-20", tier: "silver", weight: 1000}, totals: {review: null}}}, + [{shipment: {score: 1000, tier: "silver", birthDate: "2024-01-01", rate: 100, weight: 100, since: "2024-02-29", parcels: [{score: 0.5, code: "é ü"}, {rate: 0.25, score: 5, code: "a"}, {score: 1.5, code: "VIP"}, {rate: 1.5, score: 100, code: "DE"}, {score: 100, code: "DE"}, {rate: -0.01, score: 100, code: "日本"}, {rate: 1000, score: 18, code: "x"}, {rate: null, score: 1.5, code: "3.5"}, {score: 100, code: "12"}, {score: 0.25, code: "abc"}, {rate: 3, score: 123456789.123, code: "US"}, {rate: null, score: 1000, code: "3.5"}, {rate: 50, score: 2, code: "VIP"}]}}, {decision: false, discount: null, health: null, shipment: {birthDate: "2024-01-01", calc: {eligible: ["2024-01"]}, flags: {margin: [true]}, parcels: [{adjusted: 0, code: "é ü", meta: {level: -0.01, tag: [true, true, true]}, quota: false, score: 0.5, scores: {surcharge: ["é ü", "é ü"]}, segment: [0.5, -0.01, 0.5]}, {adjusted: 1, code: "a", meta: {level: -0.01, tag: [true, true, true]}, quota: false, rate: 0.25, score: 5, scores: {surcharge: ["a", "a"]}, segment: [5, -0.01, 0.5]}, {adjusted: 0, code: "VIP", meta: {level: -0.01, tag: [true, true, true]}, quota: false, score: 1.5, scores: {surcharge: ["VIP", "VIP"]}, segment: [1.5, -0.01, 0.5]}, {adjusted: 2, code: "DE", meta: {level: -0.01, tag: [true, true, true]}, quota: false, rate: 1.5, score: 100, scores: {surcharge: ["DE", "DE"]}, segment: [100, -0.01, 0.5]}, {adjusted: 0, code: "DE", meta: {level: -0.01, tag: [true, true, true]}, quota: false, score: 100, scores: {surcharge: ["DE", "DE"]}, segment: [100, -0.01, 0.5]}, {adjusted: -0, code: "日本", meta: {level: -0.01, tag: [true, true, true]}, quota: false, rate: -0.01, score: 100, scores: {surcharge: ["日本", "日本"]}, segment: [100, -0.01, 0.5]}, {adjusted: 1000, code: "x", meta: {level: -0.01, tag: [true, true, true]}, quota: false, rate: 1000, score: 18, scores: {surcharge: ["x", "x"]}, segment: [18, -0.01, 0.5]}, {adjusted: 0, code: "3.5", meta: {level: -0.01, tag: [true, true, true]}, quota: false, rate: null, score: 1.5, scores: {surcharge: ["3.5", "3.5"]}, segment: [1.5, -0.01, 0.5]}, {adjusted: 0, code: "12", meta: {level: -0.01, tag: [true, true, true]}, quota: false, score: 100, scores: {surcharge: ["12", "12"]}, segment: [100, -0.01, 0.5]}, {adjusted: 0, code: "abc", meta: {level: -0.01, tag: [true, true, true]}, quota: false, score: 0.25, scores: {surcharge: ["abc", "abc"]}, segment: [0.25, -0.01, 0.5]}, {adjusted: 3, code: "US", meta: {level: -0.01, tag: [true, true, true]}, quota: false, rate: 3, score: 123456789.123, scores: {surcharge: ["US", "US"]}, segment: [123456789.123, -0.01, 0.5]}, {adjusted: 0, code: "3.5", meta: {level: -0.01, tag: [true, true, true]}, quota: false, rate: null, score: 1000, scores: {surcharge: ["3.5", "3.5"]}, segment: [1000, -0.01, 0.5]}, {adjusted: 50, code: "VIP", meta: {level: -0.01, tag: [true, true, true]}, quota: false, rate: 50, score: 2, scores: {surcharge: ["VIP", "VIP"]}, segment: [2, -0.01, 0.5]}], points: true, rate: 100, score: 1000, since: "2024-02-29", tier: "silver", weight: 100}, total: [], totals: {review: true}, weighted: null}], + {input: {shipment: {score: 5, birthDate: "2024-02-29", rate: 1, weight: -1, parcels: [{score: 18, code: "retail"}]}}, goals: ["shipment.flags.margin"], output: {shipment: {birthDate: "2024-02-29", calc: {eligible: ["US", "2024-02"]}, flags: {margin: [false]}, parcels: [{code: "retail", score: 18}], points: false, rate: 1, score: 5, weight: -1}, totals: {review: null}}}, + ], +} + +// seed 351000 (attempt 0) +{ + name: "goals 11: shipment/loans/parts: 3 assertion, 2 expression, 2 match, 5 table; 8 root, 7 per-member, 4 top-level computed", + policy: { + models: {shipment: {years: "number", country: "string?", dueDate: "date?", kind: "string(retail|corporate)", loans: "loan[]"}, loan: {rate: "number?", code: "string?", channel: "string", price: "number", parts: "part[]"}, part: {days: "number", urgent: "boolean"}}, + blocks: [ + {assertion: "loan.flag", conditions: [["and", "shipment.country != null", 2], "(shipment.dueDate ?? d('2025-01-01')) >= d('2025-01-01')", ["and", "all(loan.parts, #.days in (-4..194])", 0]]}, + {assertion: "loan.discount", conditions: [["or", "loan.price == (loan.rate ?? 0)", 1], ["or", "startsWith((loan.code ?? ''), 'US')", 1], ["and", "isNumeric((shipment.country ?? ''))", 1], ["or", "shipment.years in [29..67]", 0]]}, + {table: "t7", inputs: ["shipment.kind", "(shipment.country ?? '')", null], outputs: ["rank", "totals.adjusted", "fee"], rules: [ + ["'corporate'", "$ != 'retail'", "(quota and quota)", "(shipment.country ?? '')", "", "(shipment.country ?? '')"], + ["", "", "", "'US'", "shipment.calc.capped", "'a'"], + ]}, + {table: "t8", inputs: ["shipment.calc.capped"], outputs: ["loan.surcharge", "loan.flags.band[]", "loan.flags.segment[]"], rules: [ + ["false", "100", "loan.channel", "(totals.adjusted ?? false)"], + ["true", "1", "(fee ?? '')", "loan.margin"], + ["true", "loan.price", "(split((shipment.country ?? ''), '-')[0] ?? 'none')", "loan.discount"], + ["true", "", "loan.channel", "loan.flag"], + ["true", "", "(loan.code ?? '')", "contains(['low', 'none', ''], (loan.code ?? ''))"], + ["true", "", "loan.channel", "contains(['a', 'low', ''], loan.channel)"], + ["false", "len(shipment.review)", "(fee ?? '')", "quota"], + ]}, + {table: "t11", inputs: ["shipment.kind", null, "(shipment.dueDate ?? d('2025-01-01'))"], outputs: ["shipment.grade"], rules: [ + ["'retail'", "shipment.years < 2", ">= d('2025-01-01')", "(shipment.calc.capped ? (fee ?? '') : (rank ?? ''))"], + ["'corporate'", "(rank ?? '') in ['high', 'low']", "> d('2025-01-01')", "(split((shipment.country ?? ''), '-')[1] ?? 'none')"], + ["", "", "> d('2024-01-01')", "(fee ?? '')"], + ["", "", "", "(shipment.country ?? '')"], + ]}, + {assertion: "quota", conditions: [["and", "shipment.years > shipment.years", 2], ["and", "trunc(shipment.years) >= shipment.years", 2], ["or", "shipment.years > 10", 1], ["and", "shipment.dueDate != null", 2]]}, + {expression: "shipment.calc.capped", value: "shipment.years < shipment.years"}, + {match: "loan.margin", arms: [["(all(loan.parts, (#.urgent or #.urgent)) and (loan.flag and shipment.calc.capped))", "loan.channel in ['none', 'VIP']"], ["(shipment.calc.capped or loan.flag)", "len(loan.channel) > 2"], ["", "shipment.years in [0..116]"]]}, + {table: "t2", hit: "collect", inputs: ["(shipment.country ?? '')", "shipment.years", "shipment.years"], outputs: ["shipment.level", "shipment.review", "shipment.total"], rules: [ + ["startsWith($, 'x')", "", "> 10", "string(quota)", "shipment.years", "shipment.years"], + ["'DE'", "", "<= 1", "(shipment.country ?? '')", "(0.5 - shipment.years)", "shipment.years"], + ["", "< 1.5", "> 1.5", "(shipment.country ?? '')", "median([shipment.years, shipment.years, shipment.years])", "shipment.years"], + ["", "", "", "(quota ? (shipment.country ?? '') : 'ok')", "", "shipment.years"], + ]}, + {table: "t12", hit: "collect", inputs: ["(fee ?? '')"], outputs: ["shipment.bucket", "shipment.meta.points"], rules: [ + ["", "(min(map(shipment.loans, 3)) ?? 0)", "quota"], + ["", "shipment.years", ""], + ["", "shipment.years", "quota"], + ]}, + {match: "loan.scores.tag", arms: [["contains(['none', 'x', ''], loan.channel)", "`${loan.margin}/${(shipment.dueDate ?? d('2025-01-01')) > d('2025-03-20')}`"], ["", "upper((fee ?? ''))"]]}, + {expression: "shipment.share", value: "((shipment.calc.capped and quota) ? totals.adjusted : null)"}, + ], + }, + cases: [ + {input: {shipment: {years: 65, country: null, dueDate: null, kind: "retail", loans: [{rate: 0, code: "ok", channel: "gold", price: 1, parts: [{days: 123456789.123, urgent: false}, {days: 0.000001, urgent: true}]}, {rate: 50, code: "NL", channel: "ok", price: 2.50, parts: [{days: 100, urgent: false}]}, {code: "abc", channel: "Oslo", price: 10, parts: [{days: 1000000, urgent: true}, {days: 50, urgent: false}, {days: 10, urgent: false}]}, {code: "abc", channel: "gold", price: 10, parts: [{days: 7.25, urgent: true}, {days: 123456789.123, urgent: false}]}, {rate: null, channel: "none", price: -0.01, parts: [{days: 250, urgent: true}]}, {channel: "none", price: 0.5, parts: [{days: 10, urgent: false}, {days: 2.50, urgent: false}, {days: 5, urgent: false}]}, {code: "Zed", channel: "a", price: 10, parts: []}, {code: null, channel: " pad ", price: 99999999999999999999, parts: [{days: 65, urgent: true}, {days: 2.50, urgent: false}, {days: 99.99, urgent: true}]}, {rate: 1000000, channel: "US", price: 50, parts: [{days: 250, urgent: false}]}]}}, goals: ["rank", "loan.flag", "shipment.calc.capped"], output: {fee: "a", quota: false, rank: "US", shipment: {calc: {capped: false}, country: null, dueDate: null, kind: "retail", loans: [{channel: "gold", code: "ok", flag: false, parts: [{days: 123456789.123, urgent: false}, {days: 0.000001, urgent: true}], price: 1, rate: 0}, {channel: "ok", code: "NL", flag: false, parts: [{days: 100, urgent: false}], price: 2.50, rate: 50}, {channel: "Oslo", code: "abc", flag: false, parts: [{days: 1000000, urgent: true}, {days: 50, urgent: false}, {days: 10, urgent: false}], price: 10}, {channel: "gold", code: "abc", flag: false, parts: [{days: 7.25, urgent: true}, {days: 123456789.123, urgent: false}], price: 10}, {channel: "none", flag: false, parts: [{days: 250, urgent: true}], price: -0.01, rate: null}, {channel: "none", flag: false, parts: [{days: 10, urgent: false}, {days: 2.50, urgent: false}, {days: 5, urgent: false}], price: 0.5}, {channel: "a", code: "Zed", flag: false, parts: [], price: 10}, {channel: " pad ", code: null, flag: false, parts: [{days: 65, urgent: true}, {days: 2.50, urgent: false}, {days: 99.99, urgent: true}], price: 99999999999999999999}, {channel: "US", flag: false, parts: [{days: 250, urgent: false}], price: 50, rate: 1000000}], years: 65}, totals: {adjusted: false}}}, + [{shipment: {years: 10, country: "low", dueDate: "2030-12-31", kind: "retail", loans: []}}, "!error: ExpressionFailed"], + {input: {shipment: {years: 2.50, country: "Zed", dueDate: "2025-03-20T10:15:30Z", kind: "retail", loans: [{rate: 2, code: "é ü", channel: "retail", price: 99.99, parts: [{days: 3, urgent: false}]}, {rate: 191, code: "low", channel: "retail", price: 1, parts: [{days: 99.99, urgent: false}, {days: 0.5, urgent: false}]}]}}, goals: ["loan.discount", "loan.margin", "shipment.meta.points"], output: {fee: "a", quota: true, rank: "US", shipment: {bucket: [3, 2.50, 2.50], calc: {capped: false}, country: "Zed", dueDate: "2025-03-20T10:15:30Z", kind: "retail", loans: [{channel: "retail", code: "é ü", discount: false, flag: true, margin: true, parts: [{days: 3, urgent: false}], price: 99.99, rate: 2}, {channel: "retail", code: "low", discount: false, flag: true, margin: true, parts: [{days: 99.99, urgent: false}, {days: 0.5, urgent: false}], price: 1, rate: 191}], meta: {points: [true, true]}, years: 2.50}, totals: {adjusted: false}}}, + {input: {shipment: {years: 2, dueDate: "2024-02-29", kind: "retail", loans: []}}, goals: ["shipment.level", "fee"], output: {fee: "a", quota: true, rank: "US", shipment: {calc: {capped: false}, dueDate: "2024-02-29", kind: "retail", level: [""], loans: [], review: [], total: [2], years: 2}, totals: {adjusted: false}}}, + {input: {shipment: {years: 250, kind: "retail", loans: [{rate: -0.5, code: "high", channel: "-", price: 123456789.123, parts: [{days: 7.25, urgent: true}, {days: 1, urgent: false}]}, {code: "abc", channel: "low", price: 2, parts: []}, {code: "-", channel: "x-y", price: -0.01, parts: [{days: 250, urgent: false}, {days: 1, urgent: false}]}, {rate: null, code: "VIP", channel: "ok", price: 1.5, parts: []}]}}, goals: ["shipment.total"], output: {quota: false, shipment: {kind: "retail", level: ["ok"], loans: [{channel: "-", code: "high", parts: [{days: 7.25, urgent: true}, {days: 1, urgent: false}], price: 123456789.123, rate: -0.5}, {channel: "low", code: "abc", parts: [], price: 2}, {channel: "x-y", code: "-", parts: [{days: 250, urgent: false}, {days: 1, urgent: false}], price: -0.01}, {channel: "ok", code: "VIP", parts: [], price: 1.5, rate: null}], review: [], total: [250], years: 250}}}, + {input: {shipment: {years: 99999999999999999999, country: null, dueDate: null, kind: "retail", loans: [{rate: null, code: "high", channel: "x", price: 1, parts: []}, {rate: null, channel: "DE", price: 99.99, parts: [{days: 50, urgent: false}, {days: 1, urgent: false}]}]}}, goals: ["loan.margin", "shipment.level"], output: {quota: false, shipment: {calc: {capped: false}, country: null, dueDate: null, kind: "retail", level: ["ok"], loans: [{channel: "x", code: "high", flag: false, margin: false, parts: [], price: 1, rate: null}, {channel: "DE", flag: false, margin: false, parts: [{days: 50, urgent: false}, {days: 1, urgent: false}], price: 99.99, rate: null}], review: [], total: [99999999999999999999], years: 99999999999999999999}}}, + {input: {shipment: {years: 10, dueDate: "1990-06-15", kind: "retail", loans: [{rate: null, channel: "x", price: 10, parts: [{days: 50, urgent: true}, {days: 10, urgent: true}]}, {rate: 3, code: null, channel: "abc", price: 1000, parts: [{days: 250, urgent: true}, {days: 1.5, urgent: false}, {days: 1, urgent: false}]}]}}, goals: ["totals.adjusted"], output: {fee: "a", quota: true, rank: "US", shipment: {calc: {capped: false}, dueDate: "1990-06-15", kind: "retail", loans: [{channel: "x", parts: [{days: 50, urgent: true}, {days: 10, urgent: true}], price: 10, rate: null}, {channel: "abc", code: null, parts: [{days: 250, urgent: true}, {days: 1.5, urgent: false}, {days: 1, urgent: false}], price: 1000, rate: 3}], years: 10}, totals: {adjusted: false}}}, + {input: {shipment: {years: 100, country: "a-b-c", dueDate: "2000-01-01", kind: "retail", loans: []}}, goals: ["loan.flags.band", "shipment.bucket"], output: "!error: ExpressionFailed"}, + {input: {shipment: {years: -500, country: null, dueDate: null, kind: "retail", loans: [{rate: null, code: "US", channel: "Zed", price: 250, parts: [{days: 2, urgent: false}, {days: 1, urgent: true}]}]}}, goals: ["totals.adjusted", "shipment.total"], output: {fee: "a", quota: false, rank: "US", shipment: {calc: {capped: false}, country: null, dueDate: null, kind: "retail", level: ["ok"], loans: [{channel: "Zed", code: "US", parts: [{days: 2, urgent: false}, {days: 1, urgent: true}], price: 250, rate: null}], review: [], total: [-500], years: -500}, totals: {adjusted: false}}}, + {input: {shipment: {years: 2, country: 5, dueDate: "2025-03-20", kind: "corporate", loans: [{rate: 99.99, code: "US", channel: "A1", price: 0.5, parts: [{days: 1, urgent: true}, {days: 0.1, urgent: true}]}, {rate: 1000000, code: "ok", channel: "é ü", price: 100, parts: [{days: 65, urgent: true}]}, {rate: 100, code: "DE", channel: "a", price: 250, parts: [{days: 1.5, urgent: true}, {days: 1, urgent: false}, {days: 250, urgent: true}]}, {rate: 0.5, code: "x-y", channel: "VIP", price: 18, parts: [{days: 7.25, urgent: false}, {days: 0.1, urgent: true}, {days: 99.99, urgent: false}]}, {rate: 1, code: "gold", channel: "none", price: -1, parts: [{days: 7.25, urgent: false}, {days: 10, urgent: true}, {days: 0.5, urgent: false}]}, {rate: 1.5, code: "3.5", channel: "none", price: 18, parts: [{days: 123456789.123, urgent: false}, {days: 0, urgent: false}, {days: 2, urgent: true}]}, {rate: 10, code: "gold", channel: "US", price: 250, parts: []}, {rate: 1000, code: "none", channel: "x-y", price: 1, parts: []}, {rate: 99999999999999999999, code: "high", channel: "VIP", price: -500, parts: [{days: 0.5, urgent: true}, {days: 10, urgent: false}]}, {rate: 5, code: "gold", channel: "none", price: -1, parts: [{days: -1, urgent: true}, {days: 18, urgent: false}]}]}}, goals: ["shipment.bucket", "fee", "totals.adjusted"], output: "!error: InputValidationFailed"}, + {input: {shipment: {years: 135, country: "low", dueDate: "2024-01-01", kind: "retail", loans: [{rate: 0.1, code: "retail", channel: "ok", price: 120, parts: [{days: 283, urgent: true}, {days: 2, urgent: true}, {days: 3, urgent: true}]}, {rate: 10, code: "3.5", channel: "ok", price: 2.50, parts: [{days: 0.000001, urgent: false}, {days: -500, urgent: false}]}, {rate: 250, code: "a", channel: "abc", price: 18, parts: [{days: 250, urgent: true}, {days: 250, urgent: true}]}]}}, goals: ["shipment.level"], output: {quota: true, shipment: {country: "low", dueDate: "2024-01-01", kind: "retail", level: ["low"], loans: [{channel: "ok", code: "retail", parts: [{days: 283, urgent: true}, {days: 2, urgent: true}, {days: 3, urgent: true}], price: 120, rate: 0.1}, {channel: "ok", code: "3.5", parts: [{days: 0.000001, urgent: false}, {days: -500, urgent: false}], price: 2.50, rate: 10}, {channel: "abc", code: "a", parts: [{days: 250, urgent: true}, {days: 250, urgent: true}], price: 18, rate: 250}], review: [], total: [135], years: 135}}}, + {input: {shipment: {years: 2, country: "none", dueDate: "1990-06-15", kind: "retail", loans: [{rate: 5, code: "high", channel: false, price: 1000000, parts: [{days: 2, urgent: true}, {days: 18, urgent: true}]}]}}, goals: ["shipment.level", "quota"], output: "!error: InputValidationFailed"}, + {input: {shipment: {years: 1000000, country: "US", dueDate: "2024-02-29", kind: "retail", loans: [{rate: -500, code: "US", channel: "DE", price: 1, parts: [{days: 1000, urgent: true}, {days: 10, urgent: false}]}]}}, goals: ["loan.discount", "loan.flags.band"], output: {fee: "a", quota: true, rank: "US", shipment: {calc: {capped: false}, country: "US", dueDate: "2024-02-29", kind: "retail", loans: [{channel: "DE", code: "US", discount: false, flags: {band: ["DE", "a"], segment: [false, true]}, parts: [{days: 1000, urgent: true}, {days: 10, urgent: false}], price: 1, rate: -500, surcharge: 100}], years: 1000000}, totals: {adjusted: false}}}, + {input: {shipment: {years: 10, kind: "corporate", loans: [{channel: "US", price: 10, parts: [{days: 10, urgent: false}, {days: 10, urgent: true}]}]}}, goals: ["loan.discount", "shipment.calc.capped", "shipment.bucket"], output: {fee: "a", quota: false, rank: "US", shipment: {bucket: [3, 10, 10], calc: {capped: false}, kind: "corporate", loans: [{channel: "US", discount: false, parts: [{days: 10, urgent: false}, {days: 10, urgent: true}], price: 10}], meta: {points: [false, false]}, years: 10}, totals: {adjusted: false}}}, + {input: {shipment: {years: 3, country: "ok", kind: "retail", loans: [{rate: 1000, channel: "none", price: 7.25, parts: [{days: 10, urgent: false}, {days: 2, urgent: false}]}, {rate: 50, channel: "-", price: 10, parts: [{days: 10, urgent: false}, {days: -0.01, urgent: true}]}]}}, goals: ["loan.discount", "loan.flag"], output: {shipment: {country: "ok", kind: "retail", loans: [{channel: "none", discount: false, flag: true, parts: [{days: 10, urgent: false}, {days: 2, urgent: false}], price: 7.25, rate: 1000}, {channel: "-", discount: false, flag: true, parts: [{days: 10, urgent: false}, {days: -0.01, urgent: true}], price: 10, rate: 50}], years: 3}}}, + {input: {shipment: {years: 10, country: "gold", dueDate: "2025-03-20T10:15:30Z", kind: "corporate", loans: []}}, goals: ["quota"], output: {quota: true, shipment: {country: "gold", dueDate: "2025-03-20T10:15:30Z", kind: "corporate", loans: [], years: 10}}}, + {input: {shipment: {years: 0, country: "gold", dueDate: "2000-01-01", kind: "retail", loans: [{rate: -0.5, code: "Oslo", channel: "retail", price: true, parts: [{days: 100, urgent: true}, {days: 1, urgent: false}]}, {rate: 18, code: "retail", channel: "a", price: 2, parts: [{days: 1e3, urgent: true}]}, {rate: 1, code: "none", channel: "ok", price: 10, parts: [{days: 10, urgent: true}]}, {rate: 0.1, code: "none", channel: "a", price: 1, parts: []}, {rate: -1, code: "low", channel: "high", price: 1, parts: [{days: 250, urgent: false}, {days: 0.000001, urgent: true}]}]}}, goals: ["loan.flags.band", "loan.margin"], output: "!error: InputValidationFailed"}, + {input: {shipment: {years: 2.50, country: "x", dueDate: 20250101, kind: "retail", loans: [{rate: 1000, code: "a-b-c", channel: "gold", price: 10, parts: [{days: -0.01, urgent: false}, {days: 10, urgent: false}]}, {rate: 18, code: "3.5", channel: "US", price: 1000, parts: [{days: 100, urgent: false}, {days: -1, urgent: false}, {days: 1, urgent: true}]}]}}, goals: ["shipment.share"], output: "!error: InputValidationFailed"}, + {input: {shipment: {years: 0.1, country: "US", dueDate: "2024-01-01", kind: "corporate", loans: [{code: "none", channel: "gold", price: 2.50, parts: [{days: 0.1, urgent: false}]}, {rate: null, code: "VIP", channel: "a", price: 18, parts: []}, {rate: 2, code: "日本", channel: "low", price: 1, parts: [{days: -0.5, urgent: true}, {days: 10, urgent: true}]}, {channel: "VIP", price: 0.1, parts: [{days: 1e3, urgent: true}, {days: 10, urgent: true}]}, {rate: 1.5, code: null, channel: "A1", price: 0.000001, parts: []}]}}, goals: ["shipment.bucket"], output: {fee: "US", quota: true, rank: "US", shipment: {bucket: [3, 0.1, 0.1], calc: {capped: false}, country: "US", dueDate: "2024-01-01", kind: "corporate", loans: [{channel: "gold", code: "none", parts: [{days: 0.1, urgent: false}], price: 2.50}, {channel: "a", code: "VIP", parts: [], price: 18, rate: null}, {channel: "low", code: "日本", parts: [{days: -0.5, urgent: true}, {days: 10, urgent: true}], price: 1, rate: 2}, {channel: "VIP", parts: [{days: 1000, urgent: true}, {days: 10, urgent: true}], price: 0.1}, {channel: "A1", code: null, parts: [], price: 0.000001, rate: 1.5}], meta: {points: [true, true]}, years: 0.1}, totals: {adjusted: false}}}, + {input: {shipment: {years: 50, dueDate: "2024-01-01", kind: "retail", loans: [{channel: "a", price: 2.50, parts: []}, {code: "US", channel: "low", price: 1.5, parts: [{days: 10, urgent: false}]}, {code: "abc", channel: "ok", price: 100, parts: [{days: 65, urgent: false}, {days: -0, urgent: false}]}]}}, goals: ["loan.flags.band"], output: {fee: "a", quota: true, rank: "US", shipment: {calc: {capped: false}, dueDate: "2024-01-01", kind: "retail", loans: [{channel: "a", flags: {band: ["a", "a"], segment: [false, true]}, parts: [], price: 2.50, surcharge: 100}, {channel: "low", code: "US", flags: {band: ["low", "a"], segment: [false, true]}, parts: [{days: 10, urgent: false}], price: 1.5, surcharge: 100}, {channel: "ok", code: "abc", flags: {band: ["ok", "a"], segment: [false, true]}, parts: [{days: 65, urgent: false}, {days: 0, urgent: false}], price: 100, surcharge: 100}], years: 50}, totals: {adjusted: false}}}, + ], +} + +// seed 351100 (attempt 0) +{ + name: "goals 12: customer/parcels + contact: 1 assertion, 2 expression, 1 match, 3 table; 1 root, 3 per-member, 4 top-level computed", + policy: { + models: {customer: {years: "number?", code: "string?", vip: "boolean", insured: "boolean", parcels: "parcel[]", contact: "contactInfo"}, parcel: {years: "number", price: "number"}, contactInfo: {limit: "number?", rate: "number?", urgent: "boolean?"}}, + blocks: [ + {expression: "parcel.level", value: "((customer.vip or (customer.contact.urgent ?? false)) ? customer.code : null)"}, + {expression: "meta.adjusted", value: "customer.contact.limit"}, + {match: "bucket", arms: [["matches((customer.code ?? ''), '^[A-Z]')", "0.5"], ["", "(customer.years ?? 0)"]]}, + {assertion: "customer.rank", conditions: [["or", "(customer.years ?? 0) in [34..48)", 2], ["and", "round(bucket, 2) == (customer.contact.limit ?? 0)", 2], ["or", "none(customer.parcels, startsWith((#.level ?? ''), 'high'))", 0]]}, + {table: "t5", hit: "collect", inputs: [null], outputs: ["parcel.ok", "parcel.surcharge"], rules: [ + ["not (customer.insured)", "customer.rank", "(customer.contact.rate ?? 0)"], + ["meta.adjusted != null", "all(customer.parcels, (#.price == 100 and #.price == 100))", "5"], + ["(customer.contact.rate ?? 0) in [29..72]", "customer.insured", ""], + ["(customer.contact.rate ?? 0) <= (meta.adjusted ?? 0)", "customer.rank", "(min([abs((meta.adjusted ?? 0)), 1000]) ^ 2)"], + ["(customer.years ?? 0) == (meta.adjusted ?? 0)", "customer.vip", "parcel.years"], + ["(customer.vip or customer.vip)", "customer.rank", "(customer.insured ? 1.5 : (meta.adjusted ?? 0))"], + ["len((customer.code ?? '')) > 1", "(customer.code ?? '') == 'Oslo'", "2"], + ]}, + {table: "t6", inputs: ["customer.rank"], outputs: ["contactInfo.calc.summary"], rules: [ + ["", "(contactInfo.rate ?? 0)"], + ["false", "(contactInfo.limit ?? 0)"], + ["", "(customer.years ?? 0)"], + ]}, + {table: "t7", hit: "collect", inputs: ["customer.contact.urgent", "(customer.contact.rate ?? 0)"], outputs: ["capped", "penalty"], rules: [ + ["false", "5, 5", "isNumeric((customer.code ?? ''))", "(bucket % (abs(50) + 1))"], + ["", "1.5, 100", "customer.vip", "min([(customer.years ?? 0)])"], + ["", "50", "(customer.insured or (customer.contact.urgent ?? false))", "bucket"], + ["true", "[50..84]", "customer.insured", "bucket"], + ["", "", "customer.vip", "(customer.years ?? 0)"], + ]}, + ], + }, + cases: [ + {input: {customer: {years: 99999999999999999999, code: "12", vip: false, insured: false, parcels: [], contact: {limit: 100, rate: 2.50, urgent: false}}}, goals: ["penalty", "contactInfo.calc.summary"], output: {bucket: 99999999999999999999, capped: [false], customer: {code: "12", contact: {calc: {summary: 2.50}, limit: 100, rate: 2.50, urgent: false}, insured: false, parcels: [], rank: false, vip: false, years: 99999999999999999999}, penalty: [99999999999999999999]}}, + {input: {customer: {years: 1000000, code: "é ü", vip: true, insured: true, parcels: [{years: -1, price: 10}, {years: 1000000, price: 50}], contact: {limit: -0, rate: 1.5, urgent: false}}}, goals: ["bucket", "contactInfo.calc.summary"], output: {bucket: 1000000, customer: {code: "é ü", contact: {calc: {summary: 1.5}, limit: 0, rate: 1.5, urgent: false}, insured: true, parcels: [{level: "é ü", price: 10, years: -1}, {level: "é ü", price: 50, years: 1000000}], rank: false, vip: true, years: 1000000}}}, + {input: {customer: {years: 2, code: "low", vip: false, insured: true, parcels: [{years: -500, price: 5}, {years: 50, price: 3}, {years: 7.25, price: -0.01}, {years: 0.5, price: -500}, {years: 3, price: 5}], contact: {limit: 1e3, rate: 1, urgent: false}}}, goals: ["customer.rank", "parcel.ok"], output: {bucket: 2, customer: {code: "low", contact: {limit: 1000, rate: 1, urgent: false}, insured: true, parcels: [{level: null, ok: [false, false, false], price: 5, surcharge: [5, 1000000, 2], years: -500}, {level: null, ok: [false, false, false], price: 3, surcharge: [5, 1000000, 2], years: 50}, {level: null, ok: [false, false, false], price: -0.01, surcharge: [5, 1000000, 2], years: 7.25}, {level: null, ok: [false, false, false], price: -500, surcharge: [5, 1000000, 2], years: 0.5}, {level: null, ok: [false, false, false], price: 5, surcharge: [5, 1000000, 2], years: 3}], rank: false, vip: false, years: 2}, meta: {adjusted: 1000}}}, + [{customer: {years: null, code: " pad ", vip: false, insured: true, parcels: [{years: 0.5, price: 123456789.123}, {years: 269, price: 0.1}, {years: 0.1, price: 1.5}, {years: 18, price: 0.1}, {years: 100, price: 100}, {years: 2, price: 3}, {years: -0.5, price: 2}, {years: 50, price: 99.99}, {years: 50, price: 3}, {years: 5, price: -0}, {years: 5, price: -0.5}, {years: 2, price: 1.5}, {years: 1, price: 0.1}], contact: {limit: 5, rate: 7.25, urgent: null}}}, {bucket: 0, capped: [false], customer: {code: " pad ", contact: {calc: {summary: 7.25}, limit: 5, rate: 7.25, urgent: null}, insured: true, parcels: [{level: null, ok: [false, false], price: 123456789.123, surcharge: [5, 2], years: 0.5}, {level: null, ok: [false, false], price: 0.1, surcharge: [5, 2], years: 269}, {level: null, ok: [false, false], price: 1.5, surcharge: [5, 2], years: 0.1}, {level: null, ok: [false, false], price: 0.1, surcharge: [5, 2], years: 18}, {level: null, ok: [false, false], price: 100, surcharge: [5, 2], years: 100}, {level: null, ok: [false, false], price: 3, surcharge: [5, 2], years: 2}, {level: null, ok: [false, false], price: 2, surcharge: [5, 2], years: -0.5}, {level: null, ok: [false, false], price: 99.99, surcharge: [5, 2], years: 50}, {level: null, ok: [false, false], price: 3, surcharge: [5, 2], years: 50}, {level: null, ok: [false, false], price: 0, surcharge: [5, 2], years: 5}, {level: null, ok: [false, false], price: -0.5, surcharge: [5, 2], years: 5}, {level: null, ok: [false, false], price: 1.5, surcharge: [5, 2], years: 2}, {level: null, ok: [false, false], price: 0.1, surcharge: [5, 2], years: 1}], rank: false, vip: false, years: null}, meta: {adjusted: 5}, penalty: [0]}], + [{customer: {code: "DE", vip: true, insured: true, parcels: [{years: 0.5, price: 65}], contact: {limit: 50, urgent: true}}}, {bucket: 0.5, capped: [true], customer: {code: "DE", contact: {calc: {summary: 0}, limit: 50, urgent: true}, insured: true, parcels: [{level: "DE", ok: [false, false, false, false], price: 65, surcharge: [5, 2500, 1.5, 2], years: 0.5}], rank: false, vip: true}, meta: {adjusted: 50}, penalty: [0]}], + {input: {customer: {years: 99.99, code: "DE", vip: true, parcels: [{years: 7.25, price: 99999999999999999999}, {years: 5, price: -500}, {years: 7.25, price: 1.5}, {years: 18, price: 99999999999999999999}], contact: {limit: 1000000, rate: -1, urgent: false}}}, goals: ["customer.rank", "penalty"], output: "!error: MissingRequiredInputs"}, + {input: {customer: {years: 123456789.123, code: "DE", vip: true, insured: false, parcels: [{years: 2, price: 3}], contact: {limit: 99.99, rate: 0.5, urgent: false}}}, goals: ["capped"], output: {capped: [true], customer: {code: "DE", contact: {limit: 99.99, rate: 0.5, urgent: false}, insured: false, parcels: [{price: 3, years: 2}], vip: true, years: 123456789.123}, penalty: [123456789.123]}}, + {input: {customer: {years: 373, code: "3.5", vip: true, insured: false, parcels: [{years: 50, price: 50}, {years: 0.5, price: 3}], contact: {limit: 123456789.123, rate: 18, urgent: false}}}, goals: ["customer.rank", "parcel.surcharge"], output: {bucket: 373, customer: {code: "3.5", contact: {limit: 123456789.123, rate: 18, urgent: false}, insured: false, parcels: [{level: "3.5", ok: [false, false, false, false, false], price: 50, surcharge: [18, 5, 1000000, 123456789.123, 2], years: 50}, {level: "3.5", ok: [false, false, false, false, false], price: 3, surcharge: [18, 5, 1000000, 123456789.123, 2], years: 0.5}], rank: false, vip: true, years: 373}, meta: {adjusted: 123456789.123}}}, + {input: {customer: {years: 1, code: "A1", vip: false, insured: true, parcels: [{years: 10, price: 50}, {years: 1000, price: 50}, {years: 1, price: 65}, {years: 99.99, price: 160}], contact: {limit: 2, rate: 2, urgent: true}}}, goals: ["bucket"], output: {bucket: 0.5, customer: {code: "A1", contact: {limit: 2, rate: 2, urgent: true}, insured: true, parcels: [{price: 50, years: 10}, {price: 50, years: 1000}, {price: 65, years: 1}, {price: 160, years: 99.99}], vip: false, years: 1}}}, + {input: {customer: {code: "A1", vip: true, insured: true, parcels: [], contact: {limit: 100, rate: 0.1}}}, goals: ["penalty"], output: {capped: [true], customer: {code: "A1", contact: {limit: 100, rate: 0.1}, insured: true, parcels: [], vip: true}, penalty: [0]}}, + {input: {customer: {years: 5, code: "O'Neil", vip: true, insured: true, parcels: [{years: 1, price: 0.5}, {years: 0, price: 100}, {years: 1000, price: 1e3}, {years: 5, price: 250}, {years: 100, price: -500}], contact: {limit: -0, rate: null, urgent: null}}}, goals: ["capped"], output: {capped: [true], customer: {code: "O'Neil", contact: {limit: 0, rate: null, urgent: null}, insured: true, parcels: [{price: 0.5, years: 1}, {price: 100, years: 0}, {price: 1000, years: 1000}, {price: 250, years: 5}, {price: -500, years: 100}], vip: true, years: 5}, penalty: [5]}}, + {input: {customer: {years: true, code: "Oslo", vip: true, insured: true, parcels: [{years: 1.5, price: 1e3}, {years: 250, price: 2}, {years: 50, price: 100}, {years: 2, price: 50}], contact: {limit: 18, rate: 99999999999999999999, urgent: true}}}, goals: ["bucket", "parcel.ok"], output: "!error: InputValidationFailed"}, + {input: {customer: {years: -0.5, code: "é ü", vip: false, insured: true, parcels: [{years: 100, price: 0.5}, {years: 100, price: 5}, {years: 100, price: 123456789.123}, {years: -1, price: 1000}, {years: 100, price: 1000}], contact: {limit: 5, rate: 50, urgent: false}}}, goals: ["contactInfo.calc.summary"], output: {bucket: -0.5, customer: {code: "é ü", contact: {calc: {summary: 50}, limit: 5, rate: 50, urgent: false}, insured: true, parcels: [{level: null, price: 0.5, years: 100}, {level: null, price: 5, years: 100}, {level: null, price: 123456789.123, years: 100}, {level: null, price: 1000, years: -1}, {level: null, price: 1000, years: 100}], rank: false, vip: false, years: -0.5}}}, + {input: {customer: {years: 100, code: "high", vip: false, insured: true, parcels: [{years: 100, price: 100}, {years: 1.5, price: 0.000001}, {years: 18, price: 100}, {years: 100, price: 18}], contact: {limit: 18, rate: 0.5, urgent: true}}}, goals: ["customer.rank"], output: {bucket: 100, customer: {code: "high", contact: {limit: 18, rate: 0.5, urgent: true}, insured: true, parcels: [{level: "high", price: 100, years: 100}, {level: "high", price: 0.000001, years: 1.5}, {level: "high", price: 100, years: 18}, {level: "high", price: 18, years: 100}], rank: false, vip: false, years: 100}}}, + {input: {customer: {years: 100, code: "a-b-c", vip: false, insured: false, parcels: [], contact: {limit: 99.99, rate: 18, urgent: false}}}, goals: ["parcel.level"], output: {customer: {code: "a-b-c", contact: {limit: 99.99, rate: 18, urgent: false}, insured: false, parcels: [], vip: false, years: 100}}}, + {input: {customer: {years: 10, code: "A1", vip: true, insured: true, parcels: [{years: -1, price: 1000000}, {years: -1, price: 2}, {years: 99.99, price: 7.25}], contact: {limit: 50, rate: 5, urgent: true}}}, goals: ["bucket", "penalty", "contactInfo.calc.summary"], output: {bucket: 0.5, capped: [true], customer: {code: "A1", contact: {calc: {summary: 5}, limit: 50, rate: 5, urgent: true}, insured: true, parcels: [{level: "A1", price: 1000000, years: -1}, {level: "A1", price: 2, years: -1}, {level: "A1", price: 7.25, years: 99.99}], rank: false, vip: true, years: 10}, penalty: [10]}}, + {input: {customer: {years: 65, code: "é ü", vip: false, insured: false, parcels: [], contact: {limit: 99999999999999999999, rate: 2, urgent: true}}}, goals: ["parcel.ok", "meta.adjusted"], output: {customer: {code: "é ü", contact: {limit: 99999999999999999999, rate: 2, urgent: true}, insured: false, parcels: [], vip: false, years: 65}, meta: {adjusted: 99999999999999999999}}}, + {input: {customer: {years: null, code: null, vip: true, insured: false, parcels: [{years: 2, price: 0.5}, {years: 1.5, price: -0.5}, {years: 1e3, price: 123456789.123}, {years: 0.5, price: 100}, {years: 10, price: 5}, {years: 0, price: 1.5}, {years: -0.5, price: 50}, {years: 250, price: 50}, {years: 100, price: 274}, {years: -0.01, price: 5}, {years: 7.25, price: 5}], contact: {limit: null, rate: null, urgent: null}}}, goals: ["bucket", "customer.rank", "meta.adjusted"], output: {bucket: 0, customer: {code: null, contact: {limit: null, rate: null, urgent: null}, insured: false, parcels: [{level: null, price: 0.5, years: 2}, {level: null, price: -0.5, years: 1.5}, {level: null, price: 123456789.123, years: 1000}, {level: null, price: 100, years: 0.5}, {level: null, price: 5, years: 10}, {level: null, price: 1.5, years: 0}, {level: null, price: 50, years: -0.5}, {level: null, price: 50, years: 250}, {level: null, price: 274, years: 100}, {level: null, price: 5, years: -0.01}, {level: null, price: 5, years: 7.25}], rank: true, vip: true, years: null}, meta: {adjusted: null}}}, + {input: {customer: {years: 99999999999999999999, code: "US", vip: true, insured: true, parcels: [{years: 2.50, price: 1e3}], contact: {limit: 5, rate: -1, urgent: true}}}, goals: ["bucket", "contactInfo.calc.summary"], output: {bucket: 0.5, customer: {code: "US", contact: {calc: {summary: -1}, limit: 5, rate: -1, urgent: true}, insured: true, parcels: [{level: "US", price: 1000, years: 2.50}], rank: false, vip: true, years: 99999999999999999999}}}, + {input: {customer: {years: 1000, code: "DE", vip: true, insured: true, parcels: [{years: 5, price: 50}, {years: 5, price: 50}, {years: 2.50, price: 100}, {years: 5, price: 50}, {years: -1, price: 2}], contact: {limit: null, rate: 7.25, urgent: null}}}, goals: ["bucket", "customer.rank", "penalty"], output: {bucket: 0.5, capped: [true], customer: {code: "DE", contact: {limit: null, rate: 7.25, urgent: null}, insured: true, parcels: [{level: "DE", price: 50, years: 5}, {level: "DE", price: 50, years: 5}, {level: "DE", price: 100, years: 2.50}, {level: "DE", price: 50, years: 5}, {level: "DE", price: 2, years: -1}], rank: false, vip: true, years: 1000}, penalty: [1000]}}, + {input: {customer: {years: 250, code: "O'Neil", vip: false, insured: false, parcels: [{years: 5, price: 212}, {years: 65, price: 18}, {years: 18, price: 80}, {years: 100, price: 99999999999999999999}], contact: {limit: 99.99, rate: 2, urgent: false}}}, goals: ["customer.rank", "bucket", "parcel.ok"], output: {bucket: 0.5, customer: {code: "O'Neil", contact: {limit: 99.99, rate: 2, urgent: false}, insured: false, parcels: [{level: null, ok: [false, false, false, false], price: 212, surcharge: [2, 5, 9998.0001, 2], years: 5}, {level: null, ok: [false, false, false, false], price: 18, surcharge: [2, 5, 9998.0001, 2], years: 65}, {level: null, ok: [false, false, false, false], price: 80, surcharge: [2, 5, 9998.0001, 2], years: 18}, {level: null, ok: [false, false, false, false], price: 99999999999999999999, surcharge: [2, 5, 9998.0001, 2], years: 100}], rank: false, vip: false, years: 250}, meta: {adjusted: 99.99}}}, + {input: {customer: {years: 2, code: "日本", vip: false, insured: true, parcels: [{years: 0, price: 2.50}], contact: {limit: 5, rate: 100, urgent: true}, extraField: 1}}, goals: ["parcel.surcharge", "parcel.level"], output: {customer: {code: "日本", contact: {limit: 5, rate: 100, urgent: true}, extraField: 1, insured: true, parcels: [{level: "日本", ok: [false, false], price: 2.50, surcharge: [5, 2], years: 0}], vip: false, years: 2}, meta: {adjusted: 5}}}, + {input: {customer: {years: -0.01, code: "x-y", vip: true, insured: true, parcels: [], contact: {rate: 250}}}, goals: ["parcel.ok", "bucket", "meta.adjusted"], output: {bucket: -0.01, customer: {code: "x-y", contact: {rate: 250}, insured: true, parcels: [], vip: true, years: -0.01}, meta: {adjusted: null}}}, + [{customer: {years: -500, code: "Oslo", vip: true, insured: true, parcels: [{years: 50, price: 1000000}], contact: {limit: 0.000001, rate: 2.50, urgent: true}}}, {bucket: 0.5, capped: [true], customer: {code: "Oslo", contact: {calc: {summary: 2.50}, limit: 0.000001, rate: 2.50, urgent: true}, insured: true, parcels: [{level: "Oslo", ok: [false, false, true], price: 1000000, surcharge: [5, 1.5, 2], years: 50}], rank: false, vip: true, years: -500}, meta: {adjusted: 0.000001}, penalty: [-500]}], + {input: {customer: {years: -0.5, code: " pad ", vip: false, insured: false, parcels: [], contact: {limit: 2, rate: -1, urgent: true}}}, goals: ["parcel.level", "customer.rank", "contactInfo.calc.summary"], output: {bucket: -0.5, customer: {code: " pad ", contact: {calc: {summary: -1}, limit: 2, rate: -1, urgent: true}, insured: false, parcels: [], rank: false, vip: false, years: -0.5}}}, + {input: {customer: {years: null, code: "Oslo", vip: false, insured: true, parcels: [{years: 99.99, price: 2}, {years: 0.000001, price: -0}], contact: {urgent: true}}}, goals: ["customer.rank"], output: {bucket: 0.5, customer: {code: "Oslo", contact: {urgent: true}, insured: true, parcels: [{level: "Oslo", price: 2, years: 99.99}, {level: "Oslo", price: 0, years: 0.000001}], rank: false, vip: false, years: null}}}, + {input: {customer: {years: 0.1, code: "Oslo", vip: false, insured: false, parcels: [{years: 5, price: 1e3}, {years: -0.01, price: 65}, {years: 100, price: 2.50}, {years: 5, price: 1}], contact: {limit: 2.50, rate: null, urgent: false}}}, goals: ["contactInfo.calc.summary", "bucket", "customer.rank"], output: {bucket: 0.5, customer: {code: "Oslo", contact: {calc: {summary: 0}, limit: 2.50, rate: null, urgent: false}, insured: false, parcels: [{level: null, price: 1000, years: 5}, {level: null, price: 65, years: -0.01}, {level: null, price: 2.50, years: 100}, {level: null, price: 1, years: 5}], rank: false, vip: false, years: 0.1}}}, + {input: {customer: {years: 7.25, code: "é ü", vip: false, insured: true, parcels: [], contact: {limit: 1000000, rate: 100, urgent: true}}}, goals: ["parcel.level", "parcel.surcharge"], output: {customer: {code: "é ü", contact: {limit: 1000000, rate: 100, urgent: true}, insured: true, parcels: [], vip: false, years: 7.25}, meta: {adjusted: 1000000}}}, + {input: {customer: {years: 167, code: "NL", vip: true, insured: false, parcels: [], contact: {urgent: true}}}, goals: ["contactInfo.calc.summary", "capped", "bucket"], output: {bucket: 0.5, capped: [true], customer: {code: "NL", contact: {calc: {summary: 0}, urgent: true}, insured: false, parcels: [], rank: false, vip: true, years: 167}, penalty: [167]}}, + ], +} + +// seed 351200 (attempt 0) +{ + name: "goals 13: order/vehicles + address: 1 assertion, 5 expression, 4 match, 2 table; 5 root, 10 per-member, 0 top-level computed", + policy: { + models: {order: {amount: "number", qty: "number", days: "number", active: "boolean", income: "number", insured: "boolean", vehicles: "vehicle[]", address: "address"}, vehicle: {rate: "number", priority: "boolean?", dueDate: "date"}, address: {price: "number", openedAt: "date?"}}, + blocks: [ + {expression: "address.meta.adjusted", value: "(min([abs(order.qty), 1000]) ^ 1)"}, + {table: "t5", inputs: ["vehicle.dueDate", null], outputs: ["vehicle.ok", "vehicle.fee"], rules: [ + ["", "(order.active or (vehicle.priority ?? false))", "vehicle.margin", "order.insured"], + ["", "", "'high'", "(vehicle.priority ?? false)"], + ]}, + {match: "order.scores.segment", arms: [["order.income in (4..116]", "len(order.vehicles)"], ["(none(order.vehicles, #.rate > #.rate) or (order.insured or order.active))", "max([order.qty, order.weighted])"], ["order.weighted != order.amount", "avg([sum(map(order.vehicles, 1.5)), len(filter(order.vehicles, len(#.margin) > 1))])"], ["(order.insured and order.insured)", "order.address.price"], ["", "round(order.qty / 7, 4)"]]}, + {expression: "vehicle.calc.share", value: "(order.address.openedAt ?? d('2025-01-01')) > d('2000-06-30')"}, + {match: "vehicle.margin", arms: [["(vehicle.dueDate > d('2025-03-20') or all(order.vehicles, #.rate > #.rate))", "vehicle.dueDate.format('%Y-%m')"], ["", "'DE'"]]}, + {match: "order.discount", arms: [["all(order.vehicles, ((#.fee ?? false) or (#.priority ?? false)))", "order.insured"], ["", "(order.address.openedAt ?? d('2025-01-01')) >= d('2000-06-30')"]]}, + {table: "t4", hit: "collect", inputs: ["order.qty", "order.address.price", "order.insured"], outputs: ["vehicle.flags.penalty", "vehicle.summary", "vehicle.band"], rules: [ + ["!= 18", "<= 1.5", "true", "", "vehicle.margin", "order.active"], + ["0.5, 50", "0.5, 100", "", "", "", "(vehicle.priority ?? false)"], + ["< 18", "<= 50", "true", "(order.amount + order.income)", "vehicle.margin", "order.insured"], + ["100", "1.5", "false", "", "vehicle.margin", "(vehicle.priority ?? false)"], + ["<= 10", "100, 2", "false", "5", "string(order.active)", "(vehicle.priority ?? false)"], + ["[2..67]", "< 18", "", "", "vehicle.margin", ""], + ]}, + {expression: "order.scores.total", value: "{a: some(order.vehicles, isNumeric((#.ok ?? '')))}"}, + {match: "order.weighted", arms: [["(order.address.openedAt ?? d('2025-01-01')).isSameOrBefore(d('2000-06-30'), 'month')", "(min([order.days, order.amount])) / (abs(len(order.vehicles)) + 1)"], ["", "order.amount"]]}, + {expression: "vehicle.grade", value: "isNumeric(string(order.scores.segment))"}, + {expression: "vehicle.flags.net", value: "len(order.vehicles)"}, + {assertion: "vehicle.points", conditions: [["or", "(order.insured or order.insured)", 1], ["and", "contains(['Oslo', 'none', ''], vehicle.margin)", 2], ["or", "not ((order.active or (vehicle.fee ?? false)))", 0]]}, + ], + }, + cases: [ + {input: {order: {amount: 10, qty: 1.5, days: 18, active: true, income: 5, insured: false, vehicles: [{rate: 2, priority: true, dueDate: "2030-12-31"}, {rate: 5, priority: false, dueDate: "2025-03-20T10:15:30Z"}, {rate: 123456789.123, priority: true, dueDate: "2000-01-01"}, {rate: 100, priority: false, dueDate: "2030-12-31"}], address: {price: 0.1, openedAt: "2030-12-31"}}}, goals: ["vehicle.summary"], output: {order: {active: true, address: {openedAt: "2030-12-31", price: 0.1}, amount: 10, days: 18, income: 5, insured: false, qty: 1.5, vehicles: [{band: [], dueDate: "2030-12-31", flags: {penalty: []}, priority: true, rate: 2, summary: []}, {band: [], dueDate: "2025-03-20T10:15:30Z", flags: {penalty: []}, priority: false, rate: 5, summary: []}, {band: [], dueDate: "2000-01-01", flags: {penalty: []}, priority: true, rate: 123456789.123, summary: []}, {band: [], dueDate: "2030-12-31", flags: {penalty: []}, priority: false, rate: 100, summary: []}]}}}, + [{order: {amount: 10, qty: 250, days: -0.5, active: false, income: 1.5, vehicles: [{rate: 1.5, priority: false, dueDate: "2025-03-20"}, {rate: 1.5, priority: true, dueDate: "2000-01-01"}], address: {price: 65, openedAt: "2025-03-20"}}}, "!error: MissingRequiredInputs"], + [{order: {amount: 0.5, qty: 0.25, days: 100, active: false, income: 7.25, insured: false, vehicles: [{rate: 5, priority: true, dueDate: "2000-01-01"}], address: {price: 2.50}}}, {order: {active: false, address: {meta: {adjusted: 0.25}, price: 2.50}, amount: 0.5, days: 100, discount: false, income: 7.25, insured: false, qty: 0.25, scores: {segment: 1}, vehicles: [{band: [], calc: {share: true}, dueDate: "2000-01-01", fee: false, flags: {net: 1, penalty: []}, grade: true, margin: "DE", ok: "DE", points: false, priority: true, rate: 5, summary: []}], weighted: 0.5}}], + {input: {order: {amount: -0, qty: 3, days: 1000, active: true, income: 1.5, insured: false, vehicles: [{rate: 0.5, priority: true, dueDate: "2024-01-01"}, {rate: 10, priority: false, dueDate: "2025-03-20"}], address: {price: 99.99}}}, goals: ["vehicle.ok", "order.discount", "order.weighted"], output: {order: {active: true, address: {price: 99.99}, amount: 0, days: 1000, discount: true, income: 1.5, insured: false, qty: 3, vehicles: [{dueDate: "2024-01-01", fee: false, margin: "DE", ok: "DE", priority: true, rate: 0.5}, {dueDate: "2025-03-20", fee: false, margin: "DE", ok: "DE", priority: false, rate: 10}], weighted: 0}}}, + {input: {order: {amount: 10, qty: 1.5, days: 50, active: false, income: -500, insured: true, vehicles: [{rate: 18, priority: true, dueDate: "2024-02-29"}, {rate: 1000, priority: true, dueDate: "2030-12-31"}, {rate: -0, priority: true, dueDate: "2000-01-01"}, {rate: 1.5, priority: true, dueDate: "2030-12-31"}], address: {price: 18, openedAt: "2024-01-01"}}}, goals: ["vehicle.summary", "order.scores.segment", "vehicle.ok"], output: {order: {active: false, address: {openedAt: "2024-01-01", price: 18}, amount: 10, days: 50, income: -500, insured: true, qty: 1.5, scores: {segment: 10}, vehicles: [{band: [true], dueDate: "2024-02-29", fee: true, flags: {penalty: [-490]}, margin: "DE", ok: "DE", priority: true, rate: 18, summary: ["DE"]}, {band: [true], dueDate: "2030-12-31", fee: true, flags: {penalty: [-490]}, margin: "2030-12", ok: "2030-12", priority: true, rate: 1000, summary: ["2030-12"]}, {band: [true], dueDate: "2000-01-01", fee: true, flags: {penalty: [-490]}, margin: "DE", ok: "DE", priority: true, rate: 0, summary: ["DE"]}, {band: [true], dueDate: "2030-12-31", fee: true, flags: {penalty: [-490]}, margin: "2030-12", ok: "2030-12", priority: true, rate: 1.5, summary: ["2030-12"]}], weighted: 10}}}, + {input: {order: {amount: 5, qty: 250, days: 123456789.123, active: false, income: 1000, insured: false, vehicles: [{rate: 99.99, priority: false, dueDate: "2024-02-29"}, {rate: 100, priority: false, dueDate: "2025-03-20T10:15:30Z"}, {rate: 0.5, priority: false, dueDate: "2025-03-20"}], address: {price: 2, openedAt: "2025-03-20T10:15:30Z"}}}, goals: ["vehicle.margin", "vehicle.points", "vehicle.calc.share"], output: {order: {active: false, address: {openedAt: "2025-03-20T10:15:30Z", price: 2}, amount: 5, days: 123456789.123, income: 1000, insured: false, qty: 250, vehicles: [{calc: {share: true}, dueDate: "2024-02-29", fee: false, margin: "DE", ok: "high", points: false, priority: false, rate: 99.99}, {calc: {share: true}, dueDate: "2025-03-20T10:15:30Z", fee: false, margin: "2025-03", ok: "high", points: false, priority: false, rate: 100}, {calc: {share: true}, dueDate: "2025-03-20", fee: false, margin: "DE", ok: "high", points: false, priority: false, rate: 0.5}]}}}, + [{order: {amount: 65, qty: 90, days: 1.5, active: true, income: 18, insured: true, vehicles: [], address: {price: 123456789.123, openedAt: "2025-03-20T10:15:30Z"}}}, {order: {active: true, address: {meta: {adjusted: 90}, openedAt: "2025-03-20T10:15:30Z", price: 123456789.123}, amount: 65, days: 1.5, discount: true, income: 18, insured: true, qty: 90, scores: {segment: 0}, vehicles: [], weighted: 65}}], + {input: {order: {amount: 250, qty: 1e3, days: 0.1, active: true, income: 5, insured: true, vehicles: [{rate: 1.5, priority: true, dueDate: "2000-01-01"}, {rate: 50, priority: true, dueDate: "2024-02-29"}, {rate: 2, priority: true, dueDate: "2024-02-29"}, {rate: 2, priority: false, dueDate: "2024-02-29"}, {rate: 5, priority: true, dueDate: "2025-03-20T10:15:30Z"}], address: {price: 100, openedAt: "2025-03-20"}}}, goals: ["order.scores.total", "vehicle.summary", "order.weighted"], output: {order: {active: true, address: {openedAt: "2025-03-20", price: 100}, amount: 250, days: 0.1, income: 5, insured: true, qty: 1000, scores: {total: {a: false}}, vehicles: [{band: [], dueDate: "2000-01-01", fee: true, flags: {penalty: []}, margin: "DE", ok: "DE", priority: true, rate: 1.5, summary: []}, {band: [], dueDate: "2024-02-29", fee: true, flags: {penalty: []}, margin: "DE", ok: "DE", priority: true, rate: 50, summary: []}, {band: [], dueDate: "2024-02-29", fee: true, flags: {penalty: []}, margin: "DE", ok: "DE", priority: true, rate: 2, summary: []}, {band: [], dueDate: "2024-02-29", fee: true, flags: {penalty: []}, margin: "DE", ok: "DE", priority: false, rate: 2, summary: []}, {band: [], dueDate: "2025-03-20T10:15:30Z", fee: true, flags: {penalty: []}, margin: "2025-03", ok: "2025-03", priority: true, rate: 5, summary: []}], weighted: 250}}}, + {input: {order: {amount: 31, qty: -0.01, days: 10, active: true, income: 1.5, insured: true, vehicles: [{rate: 65, priority: false, dueDate: "1990-06-15"}, {rate: 18, priority: true, dueDate: "2030-12-31"}], address: {price: 100, openedAt: "2030-12-31"}}}, goals: ["vehicle.ok", "vehicle.points"], output: {order: {active: true, address: {openedAt: "2030-12-31", price: 100}, amount: 31, days: 10, income: 1.5, insured: true, qty: -0.01, vehicles: [{dueDate: "1990-06-15", fee: true, margin: "DE", ok: "DE", points: false, priority: false, rate: 65}, {dueDate: "2030-12-31", fee: true, margin: "2030-12", ok: "2030-12", points: false, priority: true, rate: 18}]}}}, + {input: {order: {amount: 1000000, qty: 10, days: 5, active: false, income: 0.25, insured: true, vehicles: [{rate: 0.000001, priority: false, dueDate: "1990-06-15"}, {rate: 1.5, dueDate: "1990-06-15"}], address: {price: 287, openedAt: "1990-06-15"}}}, goals: ["vehicle.flags.net", "vehicle.band", "address.meta.adjusted"], output: {order: {active: false, address: {meta: {adjusted: 10}, openedAt: "1990-06-15", price: 287}, amount: 1000000, days: 5, income: 0.25, insured: true, qty: 10, vehicles: [{band: [], dueDate: "1990-06-15", flags: {net: 2, penalty: []}, priority: false, rate: 0.000001, summary: []}, {band: [], dueDate: "1990-06-15", flags: {net: 2, penalty: []}, rate: 1.5, summary: []}]}}}, + {input: {order: {amount: 50, qty: 5, days: 1000000, active: true, income: -500, insured: true, vehicles: [], address: {price: 2, openedAt: "2025-03-20"}}}, goals: ["vehicle.band"], output: {order: {active: true, address: {openedAt: "2025-03-20", price: 2}, amount: 50, days: 1000000, income: -500, insured: true, qty: 5, vehicles: []}}}, + {input: {order: {amount: 100, qty: 1.5, days: 357, active: false, income: 0.5, insured: false, vehicles: [{rate: 2, priority: false, dueDate: "2025-03-20"}, {rate: 1.5, priority: true, dueDate: "2025-03-20T10:15:30Z"}, {rate: 0.000001, priority: false, dueDate: "1990-06-15"}, {rate: 0.5, priority: true, dueDate: "2030-12-31"}, {rate: 1000, priority: false, dueDate: "2030-12-31"}], address: {price: 65, openedAt: "2025-03-20"}}}, goals: ["order.scores.total", "vehicle.margin", "vehicle.points"], output: {order: {active: false, address: {openedAt: "2025-03-20", price: 65}, amount: 100, days: 357, income: 0.5, insured: false, qty: 1.5, scores: {total: {a: false}}, vehicles: [{dueDate: "2025-03-20", fee: false, margin: "DE", ok: "high", points: false, priority: false, rate: 2}, {dueDate: "2025-03-20T10:15:30Z", fee: false, margin: "2025-03", ok: "2025-03", points: false, priority: true, rate: 1.5}, {dueDate: "1990-06-15", fee: false, margin: "DE", ok: "high", points: false, priority: false, rate: 0.000001}, {dueDate: "2030-12-31", fee: false, margin: "2030-12", ok: "2030-12", points: false, priority: true, rate: 0.5}, {dueDate: "2030-12-31", fee: false, margin: "2030-12", ok: "high", points: false, priority: false, rate: 1000}]}}}, + {input: {order: {amount: 50, qty: [1], days: 99.99, active: true, income: 2.50, insured: true, vehicles: [{rate: -0.01, priority: false, dueDate: "1990-06-15"}], address: {price: 2, openedAt: "1990-06-15"}}}, goals: ["vehicle.calc.share", "vehicle.band", "address.meta.adjusted"], output: "!error: InputValidationFailed"}, + {input: {order: {amount: 100, qty: 1.5, days: -0.01, active: false, income: 100, insured: false, vehicles: [{rate: 0, priority: false, dueDate: "2024-02-29"}, {rate: 2, priority: false, dueDate: "2024-01-01"}, {rate: 0.5, priority: false, dueDate: "2025-03-20"}, {rate: -0.5, priority: false, dueDate: "1990-06-15"}, {rate: 5, priority: true, dueDate: "2030-12-31"}], address: {price: 18, openedAt: "2025-03-20"}, extraField: 1}}, goals: ["address.meta.adjusted"], output: {order: {active: false, address: {meta: {adjusted: 1.5}, openedAt: "2025-03-20", price: 18}, amount: 100, days: -0.01, extraField: 1, income: 100, insured: false, qty: 1.5, vehicles: [{dueDate: "2024-02-29", priority: false, rate: 0}, {dueDate: "2024-01-01", priority: false, rate: 2}, {dueDate: "2025-03-20", priority: false, rate: 0.5}, {dueDate: "1990-06-15", priority: false, rate: -0.5}, {dueDate: "2030-12-31", priority: true, rate: 5}]}}}, + {input: {order: {amount: 2.50, qty: 2, days: -500, active: false, income: 457, insured: false, vehicles: [{rate: 50, priority: false, dueDate: "2030-12-31"}, {rate: 2, priority: false, dueDate: "2025-03-20"}], address: {price: 0, openedAt: "2030-12-31"}, extraField: 1}}, goals: ["order.discount"], output: {order: {active: false, address: {openedAt: "2030-12-31", price: 0}, amount: 2.50, days: -500, discount: true, extraField: 1, income: 457, insured: false, qty: 2, vehicles: [{dueDate: "2030-12-31", fee: false, ok: "high", priority: false, rate: 50}, {dueDate: "2025-03-20", fee: false, ok: "high", priority: false, rate: 2}]}}}, + {input: {order: {amount: 1.5, qty: 1, days: 5, active: false, income: 0.1, insured: false, vehicles: [{rate: 1.5, priority: false, dueDate: "2025-03-20"}], address: {price: 18, openedAt: "2000-01-01"}}}, goals: ["vehicle.margin"], output: {order: {active: false, address: {openedAt: "2000-01-01", price: 18}, amount: 1.5, days: 5, income: 0.1, insured: false, qty: 1, vehicles: [{dueDate: "2025-03-20", margin: "DE", priority: false, rate: 1.5}]}}}, + ], +} + +// seed 351300 (attempt 0) +{ + name: "goals 14: order/members/drivers: 5 expression, 1 match, 4 table; 2 root, 11 per-member, 0 top-level computed", + policy: { + models: {order: {amount: "number", label: "string", score: "number", insured: "boolean?", members: "member[]"}, member: {limit: "number", urgent: "boolean", plan: "string(basic|plus|premium|trial)", drivers: "driver[]"}, driver: {balance: "number", country: "string"}}, + blocks: [ + {table: "t1", inputs: ["(1.5 * member.limit)", "member.limit", "member.urgent"], outputs: ["member.meta.ok"], rules: [ + ["!= 250", "0.5, 1", "true", "order.amount"], + ["< 0.25", "< 100", "", "(member.urgent ? order.score : order.amount)"], + ["> 50", "0.5, 250", "true", ""], + [">= 5", "", "", "order.amount"], + ["<= 1000", "!= 5", "false", "order.score"], + ["", ">= 1000", "true", "100"], + ["", "", "", "100"], + ]}, + {expression: "member.decision", value: "filter(member.drivers, trunc(#.balance) == #.balance)"}, + {expression: "member.meta.discount", value: "filter(member.drivers, #.balance > #.balance)"}, + {expression: "member.flags.review", value: "((member.meta.ok ?? 0) / 3)"}, + {expression: "member.eligible", value: "len(filter(member.drivers, #.balance in [10..99]))"}, + {table: "t6", inputs: ["order.score", null], outputs: ["member.margin", "member.summary"], rules: [ + ["!= 2", "", "number(string(member.eligible))", "member.flags.review"], + ["", "", "member.limit", "order.amount"], + ["", "", "member.limit", "(member.urgent ? order.amount : order.score)"], + ]}, + {table: "t7", inputs: ["order.amount", "number(string(order.score))"], outputs: ["member.scores.risk", "member.calc.fee[]", "member.capped"], rules: [ + ["", "[0..283]", "", "((member.margin ?? 0) + order.amount)", "(member.margin ?? 0)"], + ["< 1000", "<= 50", "member.urgent", "member.limit", ""], + ["100, 1000", "1", "member.urgent", "", "(member.margin ?? 0)"], + [">= 2", "", "(order.insured ?? false)", "", ""], + ["", "", "member.urgent", "order.amount", "order.score"], + ]}, + {expression: "order.totals.exposure", value: "order.insured"}, + {table: "t9", inputs: [null], outputs: ["member.total"], rules: [ + ["", ""], + ["", "(member.margin ?? 0)"], + ]}, + {match: "order.segment", arms: [["((order.insured ?? false) and (order.insured ?? false))", "string((order.insured ?? false))"], ["(all(order.members, ((#.scores.risk ?? false) or #.urgent)) and none(order.members, (#.summary ?? 0) > (#.total ?? 0)))", "order.label"], ["", "order.label"]]}, + ], + }, + cases: [ + [{order: {amount: 0.25, label: "gold", score: 0.25, insured: true, members: [{limit: 10, urgent: true, plan: "basic", drivers: [{balance: 100, country: ""}, {balance: 0.5, country: "日本"}]}], extraField: {nested: true}}}, {order: {amount: 0.25, extraField: {nested: true}, insured: true, label: "gold", members: [{calc: {fee: [0.25, 10, 0.25]}, capped: 0, decision: [{balance: 100, country: ""}], drivers: [{balance: 100, country: ""}, {balance: 0.5, country: "日本"}], eligible: 0, flags: {review: 0.0833333333333333333333333333}, limit: 10, margin: 0, meta: {ok: 0.25}, plan: "basic", scores: {risk: true}, summary: 0.0833333333333333333333333333, total: 0, urgent: true}], score: 0.25, segment: "true", totals: {exposure: true}}}], + {input: {order: {amount: 99.99, label: "DE", score: 100, insured: true, members: [{limit: 5, urgent: false, plan: "plus", drivers: [{balance: 0.25, country: "O'Neil"}, {balance: 0, country: "a-b-c"}]}, {limit: 10, urgent: false, plan: "premium", drivers: [{balance: 0.5, country: "-"}, {balance: 2.50, country: "é ü"}, {balance: 1000000, country: "US"}]}, {limit: 2, urgent: true, plan: "basic", drivers: []}, {limit: 0.25, urgent: true, plan: "basic", drivers: [{balance: 100, country: "é ü"}]}]}}, goals: ["member.decision", "order.totals.exposure", "order.segment"], output: {order: {amount: 99.99, insured: true, label: "DE", members: [{calc: {fee: [99.99, 99.99]}, capped: 0, decision: [{balance: 0, country: "a-b-c"}], drivers: [{balance: 0.25, country: "O'Neil"}, {balance: 0, country: "a-b-c"}], eligible: 0, flags: {review: 33.33}, limit: 5, margin: 0, meta: {ok: 99.99}, plan: "plus", scores: {risk: true}, summary: 33.33, total: 0, urgent: false}, {calc: {fee: [99.99, 99.99]}, capped: 0, decision: [{balance: 1000000, country: "US"}], drivers: [{balance: 0.5, country: "-"}, {balance: 2.50, country: "é ü"}, {balance: 1000000, country: "US"}], eligible: 0, flags: {review: 33.33}, limit: 10, margin: 0, meta: {ok: 99.99}, plan: "premium", scores: {risk: true}, summary: 33.33, total: 0, urgent: false}, {calc: {fee: [99.99, 99.99]}, capped: 0, decision: [], drivers: [], eligible: 0, flags: {review: 33.333333333333333333333333333}, limit: 2, margin: 0, meta: {ok: 100}, plan: "basic", scores: {risk: true}, summary: 33.333333333333333333333333333, total: 0, urgent: true}, {calc: {fee: [99.99, 99.99]}, capped: 0, decision: [{balance: 100, country: "é ü"}], drivers: [{balance: 100, country: "é ü"}], eligible: 0, flags: {review: 33.333333333333333333333333333}, limit: 0.25, margin: 0, meta: {ok: 100}, plan: "basic", scores: {risk: true}, summary: 33.333333333333333333333333333, total: 0, urgent: true}], score: 100, segment: "true", totals: {exposure: true}}}}, + {input: {order: {amount: -0.5, label: "3.5", score: 2, members: [{limit: 0, urgent: false, plan: "trial", drivers: [{balance: 1.5, country: "Oslo"}, {balance: 123456789.123, country: "x-y"}]}, {limit: 1, urgent: false, plan: "basic", drivers: [{balance: 100, country: "x-y"}, {balance: 0.000001, country: "12"}]}, {limit: 2, urgent: false, plan: "basic", drivers: []}, {limit: 100, urgent: true, plan: "basic", drivers: []}, {limit: 1.5, urgent: false, plan: "trial", drivers: [{balance: 1, country: "x-y"}, {balance: 1000000, country: ""}, {balance: 1, country: "O'Neil"}]}, {limit: 1000, urgent: false, plan: "basic", drivers: [{balance: 0.5, country: "gold"}]}, {limit: 123456789.123, urgent: true, plan: "basic", drivers: []}, {limit: 2, urgent: false, plan: "trial", drivers: []}, {limit: 0.25, urgent: true, plan: "trial", drivers: [{balance: 50, country: "NL"}, {balance: 1000, country: "O'Neil"}]}, {limit: 5, urgent: false, plan: "basic", drivers: [{balance: 0.25, country: "x-y"}, {balance: 0.5, country: "VIP"}, {balance: 10, country: "Oslo"}]}, {limit: 0.25, urgent: false, plan: "premium", drivers: []}, {limit: 1.5, urgent: true, plan: "plus", drivers: [{balance: 100, country: " pad "}, {balance: 1000, country: "US"}, {balance: 10, country: "A1"}]}, {limit: 10, urgent: true, plan: "trial", drivers: []}]}}, goals: ["member.margin"], output: {order: {amount: -0.5, label: "3.5", members: [{drivers: [{balance: 1.5, country: "Oslo"}, {balance: 123456789.123, country: "x-y"}], limit: 0, margin: 0, plan: "trial", summary: -0.5, urgent: false}, {drivers: [{balance: 100, country: "x-y"}, {balance: 0.000001, country: "12"}], limit: 1, margin: 1, plan: "basic", summary: -0.5, urgent: false}, {drivers: [], limit: 2, margin: 2, plan: "basic", summary: -0.5, urgent: false}, {drivers: [], limit: 100, margin: 100, plan: "basic", summary: -0.5, urgent: true}, {drivers: [{balance: 1, country: "x-y"}, {balance: 1000000, country: ""}, {balance: 1, country: "O'Neil"}], limit: 1.5, margin: 1.5, plan: "trial", summary: -0.5, urgent: false}, {drivers: [{balance: 0.5, country: "gold"}], limit: 1000, margin: 1000, plan: "basic", summary: -0.5, urgent: false}, {drivers: [], limit: 123456789.123, margin: 123456789.123, plan: "basic", summary: -0.5, urgent: true}, {drivers: [], limit: 2, margin: 2, plan: "trial", summary: -0.5, urgent: false}, {drivers: [{balance: 50, country: "NL"}, {balance: 1000, country: "O'Neil"}], limit: 0.25, margin: 0.25, plan: "trial", summary: -0.5, urgent: true}, {drivers: [{balance: 0.25, country: "x-y"}, {balance: 0.5, country: "VIP"}, {balance: 10, country: "Oslo"}], limit: 5, margin: 5, plan: "basic", summary: -0.5, urgent: false}, {drivers: [], limit: 0.25, margin: 0.25, plan: "premium", summary: -0.5, urgent: false}, {drivers: [{balance: 100, country: " pad "}, {balance: 1000, country: "US"}, {balance: 10, country: "A1"}], limit: 1.5, margin: 1.5, plan: "plus", summary: -0.5, urgent: true}, {drivers: [], limit: 10, margin: 10, plan: "trial", summary: -0.5, urgent: true}], score: 2}}}, + {input: {order: {amount: -0.5, label: "gold", score: 0.25, insured: null, members: [{limit: 18, urgent: true, plan: "plus", drivers: [{balance: 0.25, country: "O'Neil"}, {balance: 1000, country: "3.5"}]}, {limit: 1000, urgent: true, plan: "trial", drivers: [{balance: -0.5, country: "DE"}]}]}}, goals: ["member.flags.review", "order.segment", "order.totals.exposure"], output: {order: {amount: -0.5, insured: null, label: "gold", members: [{calc: {fee: [-0.5, 18, -0.5]}, capped: 0, drivers: [{balance: 0.25, country: "O'Neil"}, {balance: 1000, country: "3.5"}], eligible: 0, flags: {review: -0.1666666666666666666666666667}, limit: 18, margin: 0, meta: {ok: -0.5}, plan: "plus", scores: {risk: true}, summary: -0.1666666666666666666666666667, total: 0, urgent: true}, {calc: {fee: [-0.5, 1000, -0.5]}, capped: 0, drivers: [{balance: -0.5, country: "DE"}], eligible: 0, flags: {review: -0.1666666666666666666666666667}, limit: 1000, margin: 0, meta: {ok: -0.5}, plan: "trial", scores: {risk: true}, summary: -0.1666666666666666666666666667, total: 0, urgent: true}], score: 0.25, segment: "gold", totals: {exposure: null}}}}, + {input: {order: {amount: 2, label: "a", score: 1000000, insured: null, members: [{limit: 2, urgent: false, plan: "basic", drivers: [{balance: 0, country: "A1"}]}, {limit: 1000, urgent: false, plan: "basic", drivers: [{balance: -0.5, country: "DE"}]}]}}, goals: ["member.scores.risk", "member.summary"], output: {order: {amount: 2, insured: null, label: "a", members: [{calc: {fee: [2]}, capped: 1000000, drivers: [{balance: 0, country: "A1"}], eligible: 0, flags: {review: 333333.33333333333333333333333}, limit: 2, margin: 0, meta: {ok: 1000000}, plan: "basic", scores: {risk: false}, summary: 333333.33333333333333333333333, urgent: false}, {calc: {fee: [2]}, capped: 1000000, drivers: [{balance: -0.5, country: "DE"}], eligible: 0, flags: {review: 0.6666666666666666666666666667}, limit: 1000, margin: 0, meta: {ok: 2}, plan: "basic", scores: {risk: false}, summary: 0.6666666666666666666666666667, urgent: false}], score: 1000000}}}, + {input: {order: {amount: 1000, label: "US", score: 50, insured: true, members: [{limit: 1.5, urgent: false, plan: "basic", drivers: [{balance: 0.5, country: "12"}, {balance: 18, country: "日本"}, {balance: 7.25, country: "gold"}]}, {limit: 250, urgent: false, plan: "plus", drivers: [{balance: 1000000, country: "abc"}, {balance: 0, country: "é ü"}]}, {limit: 100, urgent: false, plan: "premium", drivers: [{balance: 65, country: "US"}]}, {limit: 250, urgent: true, plan: "plus", drivers: [{balance: 7.25, country: "a-b-c"}, {balance: 5, country: "Oslo"}]}, {limit: 1.5, urgent: true, plan: "basic", drivers: [{balance: 50, country: "Oslo"}, {balance: 100, country: "VIP"}]}]}}, goals: ["member.calc.fee", "member.summary"], output: {order: {amount: 1000, insured: true, label: "US", members: [{calc: {fee: [1001, 1000]}, capped: 1, drivers: [{balance: 0.5, country: "12"}, {balance: 18, country: "日本"}, {balance: 7.25, country: "gold"}], eligible: 1, flags: {review: 16.666666666666666666666666667}, limit: 1.5, margin: 1, meta: {ok: 50}, plan: "basic", scores: {risk: true}, summary: 16.666666666666666666666666667, urgent: false}, {calc: {fee: [1000, 1000]}, capped: 0, drivers: [{balance: 1000000, country: "abc"}, {balance: 0, country: "é ü"}], eligible: 0, flags: {review: 333.33333333333333333333333333}, limit: 250, margin: 0, meta: {ok: 1000}, plan: "plus", scores: {risk: true}, summary: 333.33333333333333333333333333, urgent: false}, {calc: {fee: [1001, 1000]}, capped: 1, drivers: [{balance: 65, country: "US"}], eligible: 1, flags: {review: 333.33333333333333333333333333}, limit: 100, margin: 1, meta: {ok: 1000}, plan: "premium", scores: {risk: true}, summary: 333.33333333333333333333333333, urgent: false}, {calc: {fee: [1000, 1000]}, capped: 0, drivers: [{balance: 7.25, country: "a-b-c"}, {balance: 5, country: "Oslo"}], eligible: 0, flags: {review: 333.33333333333333333333333333}, limit: 250, margin: 0, meta: {ok: 1000}, plan: "plus", scores: {risk: true}, summary: 333.33333333333333333333333333, urgent: true}, {calc: {fee: [1001, 1000]}, capped: 1, drivers: [{balance: 50, country: "Oslo"}, {balance: 100, country: "VIP"}], eligible: 1, flags: {review: 33.333333333333333333333333333}, limit: 1.5, margin: 1, meta: {ok: 100}, plan: "basic", scores: {risk: true}, summary: 33.333333333333333333333333333, urgent: true}], score: 50}}}, + {input: {order: {amount: 5, label: "retail", score: 0, insured: false, members: []}}, goals: ["member.meta.ok"], output: {order: {amount: 5, insured: false, label: "retail", members: [], score: 0}}}, + {input: {order: {amount: 0.5, label: "NL", score: 2, members: [{limit: 18, urgent: false, plan: "basic", drivers: [{balance: -0.01, country: "Zed"}, {balance: 0, country: ""}, {balance: 3, country: "DE"}]}, {limit: 1000, urgent: false, plan: "trial", drivers: [{balance: 0.000001, country: "A1"}, {balance: 100, country: "DE"}, {balance: 5, country: "abc"}]}, {limit: 0.5, urgent: false, plan: "plus", drivers: [{balance: 1.5, country: "日本"}, {balance: 10, country: "US"}, {balance: 2, country: "x-y"}]}]}}, goals: ["member.margin"], output: {order: {amount: 0.5, label: "NL", members: [{drivers: [{balance: -0.01, country: "Zed"}, {balance: 0, country: ""}, {balance: 3, country: "DE"}], limit: 18, margin: 18, plan: "basic", summary: 0.5, urgent: false}, {drivers: [{balance: 0.000001, country: "A1"}, {balance: 100, country: "DE"}, {balance: 5, country: "abc"}], limit: 1000, margin: 1000, plan: "trial", summary: 0.5, urgent: false}, {drivers: [{balance: 1.5, country: "日本"}, {balance: 10, country: "US"}, {balance: 2, country: "x-y"}], limit: 0.5, margin: 0.5, plan: "plus", summary: 0.5, urgent: false}], score: 2}}}, + {input: {order: {amount: -1, label: "a-b-c", score: 99999999999999999999, insured: false, members: [{limit: 7.25, urgent: true, plan: "premium", drivers: [{balance: 7.25, country: "Oslo"}, {balance: 0.5, country: "gold"}, {balance: -0.01, country: "Oslo"}]}, {limit: 1.5, urgent: false, plan: "trial", drivers: [{balance: 100, country: "日本"}, {balance: 50, country: "12"}, {balance: 64, country: "é ü"}]}]}}, goals: ["member.decision", "member.flags.review"], output: {order: {amount: -1, insured: false, label: "a-b-c", members: [{decision: [], drivers: [{balance: 7.25, country: "Oslo"}, {balance: 0.5, country: "gold"}, {balance: -0.01, country: "Oslo"}], flags: {review: -0.3333333333333333333333333333}, limit: 7.25, meta: {ok: -1}, plan: "premium", urgent: true}, {decision: [{balance: 100, country: "日本"}, {balance: 50, country: "12"}, {balance: 64, country: "é ü"}], drivers: [{balance: 100, country: "日本"}, {balance: 50, country: "12"}, {balance: 64, country: "é ü"}], flags: {review: 33333333333333333333}, limit: 1.5, meta: {ok: 99999999999999999999}, plan: "trial", urgent: false}], score: 99999999999999999999}}}, + [{order: {amount: 250, label: "Zed", score: 1000, insured: true, members: [{limit: 5, urgent: false, plan: "trial", drivers: [{balance: 0.000001, country: "12"}, {balance: 99.99, country: "retail"}]}, {limit: 1000, urgent: true, plan: "premium", drivers: []}, {limit: 250, urgent: true, plan: "plus", drivers: [{balance: 1, country: "DE"}, {balance: 1.5, country: "abc"}, {balance: 0.25, country: "O'Neil"}]}, {limit: 99.99, urgent: false, plan: "trial", drivers: [{balance: 345, country: " pad "}, {balance: 0.5, country: "a-b-c"}, {balance: 59, country: "US"}]}, {limit: 250, urgent: false, plan: "basic", drivers: [{balance: -500, country: ""}, {balance: 3, country: "Oslo"}]}]}}, {order: {amount: 250, insured: true, label: "Zed", members: [{calc: {fee: [250]}, capped: 1000, decision: [], drivers: [{balance: 0.000001, country: "12"}, {balance: 99.99, country: "retail"}], eligible: 0, flags: {review: 83.33333333333333333333333333}, limit: 5, margin: 0, meta: {ok: 250}, plan: "trial", scores: {risk: true}, summary: 83.33333333333333333333333333, total: 0, urgent: false}, {calc: {fee: [250]}, capped: 1000, decision: [], drivers: [], eligible: 0, flags: {review: 83.33333333333333333333333333}, limit: 1000, margin: 0, meta: {ok: 250}, plan: "premium", scores: {risk: true}, summary: 83.33333333333333333333333333, total: 0, urgent: true}, {calc: {fee: [250]}, capped: 1000, decision: [{balance: 1, country: "DE"}], drivers: [{balance: 1, country: "DE"}, {balance: 1.5, country: "abc"}, {balance: 0.25, country: "O'Neil"}], eligible: 0, flags: {review: 83.33333333333333333333333333}, limit: 250, margin: 0, meta: {ok: 250}, plan: "plus", scores: {risk: true}, summary: 83.33333333333333333333333333, total: 0, urgent: true}, {calc: {fee: [250]}, capped: 1000, decision: [{balance: 345, country: " pad "}, {balance: 59, country: "US"}], drivers: [{balance: 345, country: " pad "}, {balance: 0.5, country: "a-b-c"}, {balance: 59, country: "US"}], eligible: 1, flags: {review: 83.33333333333333333333333333}, limit: 99.99, margin: 1, meta: {ok: 250}, plan: "trial", scores: {risk: true}, summary: 83.33333333333333333333333333, total: 1, urgent: false}, {calc: {fee: [250]}, capped: 1000, decision: [{balance: -500, country: ""}, {balance: 3, country: "Oslo"}], drivers: [{balance: -500, country: ""}, {balance: 3, country: "Oslo"}], eligible: 0, flags: {review: 83.33333333333333333333333333}, limit: 250, margin: 0, meta: {ok: 250}, plan: "basic", scores: {risk: true}, summary: 83.33333333333333333333333333, total: 0, urgent: false}], score: 1000, segment: "true", totals: {exposure: true}}}], + [{order: {amount: 0.25, label: "NL", score: 1e3, insured: null, members: [{limit: 99.99, urgent: false, plan: "plus", drivers: [{balance: 1.5, country: "3.5"}]}, {limit: 1, urgent: false, plan: "basic", drivers: [{balance: 10, country: "a"}, {balance: 1, country: "3.5"}]}, {limit: 0.5, urgent: true, plan: "basic", drivers: [{balance: 250, country: "A1"}, {balance: 10, country: "-"}]}]}}, {order: {amount: 0.25, insured: null, label: "NL", members: [{calc: {fee: [0.25]}, capped: 1000, decision: [], drivers: [{balance: 1.5, country: "3.5"}], eligible: 0, flags: {review: 0.0833333333333333333333333333}, limit: 99.99, margin: 0, meta: {ok: 0.25}, plan: "plus", scores: {risk: false}, summary: 0.0833333333333333333333333333, total: 0, urgent: false}, {calc: {fee: [0.25]}, capped: 1000, decision: [{balance: 10, country: "a"}, {balance: 1, country: "3.5"}], drivers: [{balance: 10, country: "a"}, {balance: 1, country: "3.5"}], eligible: 1, flags: {review: 333.33333333333333333333333333}, limit: 1, margin: 1, meta: {ok: 1000}, plan: "basic", scores: {risk: false}, summary: 333.33333333333333333333333333, total: 1, urgent: false}, {calc: {fee: [0.25]}, capped: 1000, decision: [{balance: 250, country: "A1"}, {balance: 10, country: "-"}], drivers: [{balance: 250, country: "A1"}, {balance: 10, country: "-"}], eligible: 1, flags: {review: 0.0833333333333333333333333333}, limit: 0.5, margin: 1, meta: {ok: 0.25}, plan: "basic", scores: {risk: true}, summary: 0.0833333333333333333333333333, total: 1, urgent: true}], score: 1000, segment: "NL", totals: {exposure: null}}}], + {input: {order: {amount: 99999999999999999999, label: "Oslo", score: 18, insured: null, members: [{limit: 1, urgent: false, plan: "basic", drivers: [{balance: 1.5, country: ""}, {balance: 0.5, country: " pad "}]}, {limit: 1, urgent: false, plan: "plus", drivers: [{balance: 0, country: "x-y"}]}]}}, goals: ["member.meta.ok", "member.meta.discount"], output: {order: {amount: 99999999999999999999, insured: null, label: "Oslo", members: [{drivers: [{balance: 1.5, country: ""}, {balance: 0.5, country: " pad "}], limit: 1, meta: {discount: [], ok: 18}, plan: "basic", urgent: false}, {drivers: [{balance: 0, country: "x-y"}], limit: 1, meta: {discount: [], ok: 18}, plan: "plus", urgent: false}], score: 18}}}, + {input: {order: {amount: 0.25, label: "O'Neil", score: 5, insured: true, members: [{limit: -0, urgent: true, plan: "plus", drivers: [{balance: 18, country: "x-y"}, {balance: 0, country: "a"}, {balance: 99999999999999999999, country: "US"}]}, {limit: 5, urgent: false, plan: "plus", drivers: [{balance: 1.5, country: "12"}]}, {limit: 0.000001, urgent: true, plan: "basic", drivers: [{balance: 7.25, country: "a"}, {balance: 0.5, country: ""}]}, {limit: 18, urgent: true, plan: "trial", drivers: [{balance: 1.5, country: "x-y"}, {balance: 0, country: "3.5"}]}]}}, goals: ["member.decision", "member.flags.review"], output: {order: {amount: 0.25, insured: true, label: "O'Neil", members: [{decision: [{balance: 18, country: "x-y"}, {balance: 0, country: "a"}, {balance: 99999999999999999999, country: "US"}], drivers: [{balance: 18, country: "x-y"}, {balance: 0, country: "a"}, {balance: 99999999999999999999, country: "US"}], flags: {review: 1.6666666666666666666666666667}, limit: 0, meta: {ok: 5}, plan: "plus", urgent: true}, {decision: [], drivers: [{balance: 1.5, country: "12"}], flags: {review: 0.0833333333333333333333333333}, limit: 5, meta: {ok: 0.25}, plan: "plus", urgent: false}, {decision: [], drivers: [{balance: 7.25, country: "a"}, {balance: 0.5, country: ""}], flags: {review: 1.6666666666666666666666666667}, limit: 0.000001, meta: {ok: 5}, plan: "basic", urgent: true}, {decision: [{balance: 0, country: "3.5"}], drivers: [{balance: 1.5, country: "x-y"}, {balance: 0, country: "3.5"}], flags: {review: 0.0833333333333333333333333333}, limit: 18, meta: {ok: 0.25}, plan: "trial", urgent: true}], score: 5}}}, + {input: {order: {amount: 2.50, label: "é ü", score: 18, insured: false, members: [{limit: 5, urgent: false, plan: "plus", drivers: [{balance: 2, country: "Zed"}, {balance: 100, country: "é ü"}]}, {limit: 3, urgent: true, plan: "plus", drivers: [{balance: 0, country: "x-y"}, {balance: 50, country: "Oslo"}]}, {limit: 2, urgent: false, plan: "premium", drivers: []}, {limit: 0.5, urgent: false, plan: "basic", drivers: [{balance: 100, country: "A1"}, {balance: 18, country: "gold"}]}]}}, goals: ["member.margin", "order.segment"], output: {order: {amount: 2.50, insured: false, label: "é ü", members: [{calc: {fee: [2.50, 5, 2.50]}, capped: 0, drivers: [{balance: 2, country: "Zed"}, {balance: 100, country: "é ü"}], eligible: 0, flags: {review: 0.8333333333333333333333333333}, limit: 5, margin: 0, meta: {ok: 2.50}, plan: "plus", scores: {risk: false}, summary: 0.8333333333333333333333333333, total: 0, urgent: false}, {calc: {fee: [3.50, 3, 2.50]}, capped: 1, drivers: [{balance: 0, country: "x-y"}, {balance: 50, country: "Oslo"}], eligible: 1, flags: {review: 33.333333333333333333333333333}, limit: 3, margin: 1, meta: {ok: 100}, plan: "plus", scores: {risk: true}, summary: 33.333333333333333333333333333, total: 1, urgent: true}, {calc: {fee: [2.50, 2, 2.50]}, capped: 0, drivers: [], eligible: 0, flags: {review: 6}, limit: 2, margin: 0, meta: {ok: 18}, plan: "premium", scores: {risk: false}, summary: 6, total: 0, urgent: false}, {calc: {fee: [3.50, 0.5, 2.50]}, capped: 1, drivers: [{balance: 100, country: "A1"}, {balance: 18, country: "gold"}], eligible: 1, flags: {review: 6}, limit: 0.5, margin: 1, meta: {ok: 18}, plan: "basic", scores: {risk: false}, summary: 6, total: 1, urgent: false}], score: 18, segment: "é ü"}}}, + {input: {order: {amount: 0.25, label: "Zed", score: 0.1, insured: false, members: [], extraField: 1}}, goals: ["order.totals.exposure"], output: {order: {amount: 0.25, extraField: 1, insured: false, label: "Zed", members: [], score: 0.1, totals: {exposure: false}}}}, + [{order: {amount: 123456789.123, label: "日本", score: 100, insured: false, members: [{limit: 241, urgent: false, plan: "plus", drivers: [{balance: 7.25, country: "abc"}, {balance: 100, country: "x-y"}, {balance: 5, country: "3.5"}]}, {limit: 5, urgent: true, plan: "trial", drivers: [{balance: 100, country: "-"}, {balance: 1.5, country: "Zed"}, {balance: 99.99, country: "-"}]}]}}, {order: {amount: 123456789.123, insured: false, label: "日本", members: [{calc: {fee: [123456789.123, 123456789.123]}, capped: 0, decision: [{balance: 100, country: "x-y"}, {balance: 5, country: "3.5"}], drivers: [{balance: 7.25, country: "abc"}, {balance: 100, country: "x-y"}, {balance: 5, country: "3.5"}], eligible: 0, flags: {review: 41152263.041}, limit: 241, margin: 0, meta: {ok: 123456789.123}, plan: "plus", scores: {risk: false}, summary: 41152263.041, total: 0, urgent: false}, {calc: {fee: [123456789.123, 123456789.123]}, capped: 0, decision: [{balance: 100, country: "-"}], drivers: [{balance: 100, country: "-"}, {balance: 1.5, country: "Zed"}, {balance: 99.99, country: "-"}], eligible: 0, flags: {review: 41152263.041}, limit: 5, margin: 0, meta: {ok: 123456789.123}, plan: "trial", scores: {risk: false}, summary: 41152263.041, total: 0, urgent: true}], score: 100, segment: "日本", totals: {exposure: false}}}], + [{order: {amount: 2.50, label: "retail", score: 0.5, insured: null, members: [{limit: 0.1, urgent: false, plan: "basic", drivers: [{balance: 50, country: "A1"}]}, {limit: 7.25, urgent: false, plan: "plus", drivers: [{balance: 5, country: "O'Neil"}, {balance: 0.5, country: "x-y"}]}, {limit: 100, urgent: false, plan: "basic", drivers: [{balance: 18, country: "日本"}]}, {limit: 0.25, urgent: false, plan: "premium", drivers: [{balance: 250, country: "A1"}, {balance: 100, country: ""}]}, {limit: 0.25, urgent: true, plan: "basic", drivers: [{balance: 100, country: "US"}, {balance: 3, country: "3.5"}]}, {limit: 1000, urgent: true, plan: "premium", drivers: [{balance: 1000, country: " pad "}, {balance: 5, country: "abc"}]}, {limit: 18, urgent: false, plan: "plus", drivers: []}, {limit: 100, urgent: true, plan: "plus", drivers: [{balance: 2.50, country: "a"}]}, {limit: 50, urgent: false, plan: "basic", drivers: []}, {limit: 369, urgent: true, plan: "plus", drivers: [{balance: 5, country: "DE"}, {balance: 250, country: "12"}]}]}}, {order: {amount: 2.50, insured: null, label: "retail", members: [{calc: {fee: [3.50, 0.1, 2.50]}, capped: 1, decision: [{balance: 50, country: "A1"}], drivers: [{balance: 50, country: "A1"}], eligible: 1, flags: {review: 0.8333333333333333333333333333}, limit: 0.1, margin: 1, meta: {ok: 2.50}, plan: "basic", scores: {risk: false}, summary: 0.8333333333333333333333333333, total: 1, urgent: false}, {calc: {fee: [2.50, 7.25, 2.50]}, capped: 0, decision: [{balance: 5, country: "O'Neil"}], drivers: [{balance: 5, country: "O'Neil"}, {balance: 0.5, country: "x-y"}], eligible: 0, flags: {review: 0.8333333333333333333333333333}, limit: 7.25, margin: 0, meta: {ok: 2.50}, plan: "plus", scores: {risk: false}, summary: 0.8333333333333333333333333333, total: 0, urgent: false}, {calc: {fee: [3.50, 100, 2.50]}, capped: 1, decision: [{balance: 18, country: "日本"}], drivers: [{balance: 18, country: "日本"}], eligible: 1, flags: {review: 0.8333333333333333333333333333}, limit: 100, margin: 1, meta: {ok: 2.50}, plan: "basic", scores: {risk: false}, summary: 0.8333333333333333333333333333, total: 1, urgent: false}, {calc: {fee: [2.50, 0.25, 2.50]}, capped: 0, decision: [{balance: 250, country: "A1"}, {balance: 100, country: ""}], drivers: [{balance: 250, country: "A1"}, {balance: 100, country: ""}], eligible: 0, flags: {review: 0.1666666666666666666666666667}, limit: 0.25, margin: 0, meta: {ok: 0.5}, plan: "premium", scores: {risk: false}, summary: 0.1666666666666666666666666667, total: 0, urgent: false}, {calc: {fee: [2.50, 0.25, 2.50]}, capped: 0, decision: [{balance: 100, country: "US"}, {balance: 3, country: "3.5"}], drivers: [{balance: 100, country: "US"}, {balance: 3, country: "3.5"}], eligible: 0, flags: {review: 33.333333333333333333333333333}, limit: 0.25, margin: 0, meta: {ok: 100}, plan: "basic", scores: {risk: true}, summary: 33.333333333333333333333333333, total: 0, urgent: true}, {calc: {fee: [2.50, 1000, 2.50]}, capped: 0, decision: [{balance: 1000, country: " pad "}, {balance: 5, country: "abc"}], drivers: [{balance: 1000, country: " pad "}, {balance: 5, country: "abc"}], eligible: 0, flags: {review: 0.8333333333333333333333333333}, limit: 1000, margin: 0, meta: {ok: 2.50}, plan: "premium", scores: {risk: true}, summary: 0.8333333333333333333333333333, total: 0, urgent: true}, {calc: {fee: [2.50, 18, 2.50]}, capped: 0, decision: [], drivers: [], eligible: 0, flags: {review: 0.8333333333333333333333333333}, limit: 18, margin: 0, meta: {ok: 2.50}, plan: "plus", scores: {risk: false}, summary: 0.8333333333333333333333333333, total: 0, urgent: false}, {calc: {fee: [2.50, 100, 2.50]}, capped: 0, decision: [], drivers: [{balance: 2.50, country: "a"}], eligible: 0, flags: {review: 0.8333333333333333333333333333}, limit: 100, margin: 0, meta: {ok: 2.50}, plan: "plus", scores: {risk: true}, summary: 0.8333333333333333333333333333, total: 0, urgent: true}, {calc: {fee: [2.50, 50, 2.50]}, capped: 0, decision: [], drivers: [], eligible: 0, flags: {review: 0.8333333333333333333333333333}, limit: 50, margin: 0, meta: {ok: 2.50}, plan: "basic", scores: {risk: false}, summary: 0.8333333333333333333333333333, total: 0, urgent: false}, {calc: {fee: [2.50, 369, 2.50]}, capped: 0, decision: [{balance: 5, country: "DE"}, {balance: 250, country: "12"}], drivers: [{balance: 5, country: "DE"}, {balance: 250, country: "12"}], eligible: 0, flags: {review: 0.8333333333333333333333333333}, limit: 369, margin: 0, meta: {ok: 2.50}, plan: "plus", scores: {risk: true}, summary: 0.8333333333333333333333333333, total: 0, urgent: true}], score: 0.5, segment: "retail", totals: {exposure: null}}}], + ], +} + +// seed 351400 (attempt 0) +{ + name: "goals 15: borrower/lines/employees: 5 expression, 4 match; 5 root, 2 per-member, 2 top-level computed", + policy: { + models: {borrower: {price: "number?", income: "number?", limit: "number", sku: "string", years: "number", active: "boolean?", lines: "line[]?"}, line: {rate: "number", country: "string", plan: "string(basic|plus|premium|trial)?", status: "string(open|closed|pending)", employees: "employee[]"}, employee: {years: "number", code: "string?"}}, + blocks: [ + {expression: "borrower.total", value: "borrower.years"}, + {match: "line.margin", arms: [["matches((split(borrower.sku, '-')[1] ?? 'none'), 'a')", "`${(borrower.active ?? false)}/${none(line.employees, #.years > #.years)}`"], ["borrower.income != null", "string(isNumeric(borrower.sku))"], ["", "`${(borrower.active ?? false)}/${(borrower.active ?? false)}`"]]}, + {expression: "ok", value: "(`${(borrower.active ?? false)}/${(borrower.active ?? false)}` + '-' + `${borrower.sku}/${(borrower.active ?? false)}`)"}, + {expression: "line.meta.eligible", value: "(min([abs(trunc(-(borrower.total))), 1000]) ^ 0)"}, + {expression: "borrower.net", value: "matches(borrower.sku, 'a')"}, + {expression: "borrower.level", value: "round(borrower.years / 7, 1)"}, + {match: "flag", arms: [["all((borrower.lines ?? []), #.country != 'none')", "isNumeric(lower(ok))"], ["1.5 >= borrower.total", "none((borrower.lines ?? []), #.country in ['US', 'DE'])"], ["isNumeric(ok)", "not (startsWith(borrower.sku, 'ok'))"], ["", "(borrower.active ?? false)"]]}, + {match: "borrower.flags.fee", arms: [["10 <= borrower.total", "string((borrower.active ?? false))"], ["not (all((borrower.lines ?? []), #.status in ['open', 'closed']))", "borrower.sku"], ["", "'VIP'"]]}, + {match: "borrower.flags.tag", arms: [["borrower.level < borrower.limit", "trunc(-((borrower.income ?? 0)))"], ["", "borrower.total"]]}, + ], + }, + cases: [ + {input: {borrower: {price: 123456789.123, income: 2, limit: 65, sku: "gold", years: 370, active: true, lines: [{rate: 99.99, country: "NL", plan: "basic", status: "open", employees: [{years: 0.5, code: "none"}, {years: 0.000001, code: "abc"}, {years: 0.000001, code: "abc"}]}, {rate: 0.000001, country: "DE", plan: "plus", status: "pending", employees: [{years: -0, code: "retail"}, {years: 0.5, code: "A1"}]}]}}, goals: ["line.margin", "ok"], output: {borrower: {active: true, income: 2, limit: 65, lines: [{country: "NL", employees: [{code: "none", years: 0.5}, {code: "abc", years: 0.000001}, {code: "abc", years: 0.000001}], margin: "false", plan: "basic", rate: 99.99, status: "open"}, {country: "DE", employees: [{code: "retail", years: 0}, {code: "A1", years: 0.5}], margin: "false", plan: "plus", rate: 0.000001, status: "pending"}], price: 123456789.123, sku: "gold", years: 370}, ok: "true/true-gold/true"}}, + {input: {borrower: {price: 1, income: 1000, limit: 0.000001, sku: "-", years: 5, active: false, lines: [{rate: 0, country: "US", plan: "basic", status: "open", employees: [{years: 10, code: " pad "}]}, {rate: 276, country: "Oslo", plan: "basic", status: "pending", employees: [{years: 0, code: "abc"}, {years: -1, code: "DE"}]}, {rate: 0.5, country: "a", plan: "trial", status: "open", employees: [{years: 123456789.123, code: "DE"}, {years: 5, code: "VIP"}]}]}}, goals: ["borrower.level", "line.meta.eligible", "borrower.flags.tag"], output: {borrower: {active: false, flags: {tag: 5}, income: 1000, level: 0.7, limit: 0.000001, lines: [{country: "US", employees: [{code: " pad ", years: 10}], meta: {eligible: 1}, plan: "basic", rate: 0, status: "open"}, {country: "Oslo", employees: [{code: "abc", years: 0}, {code: "DE", years: -1}], meta: {eligible: 1}, plan: "basic", rate: 276, status: "pending"}, {country: "a", employees: [{code: "DE", years: 123456789.123}, {code: "VIP", years: 5}], meta: {eligible: 1}, plan: "trial", rate: 0.5, status: "open"}], price: 1, sku: "-", total: 5, years: 5}}}, + {input: {borrower: {price: 123456789.123, income: 1000000, limit: 2, sku: "é ü", years: 7.25, active: true, lines: []}}, goals: ["borrower.flags.tag", "ok", "borrower.total"], output: {borrower: {active: true, flags: {tag: -1000000}, income: 1000000, level: 1.0, limit: 2, lines: [], price: 123456789.123, sku: "é ü", total: 7.25, years: 7.25}, ok: "true/true-é ü/true"}}, + {input: {borrower: {price: 1000, income: 1000, limit: 10, sku: "日本", years: 100, active: 1, lines: [{rate: 10, country: "US", plan: "basic", status: "closed", employees: [{years: 5, code: "DE"}, {years: 29, code: "Zed"}]}, {rate: 1000, country: "US", plan: "basic", status: "open", employees: [{years: 2.50, code: "DE"}, {years: 1, code: " pad "}, {years: -500, code: "DE"}]}, {rate: 0.5, country: "12", plan: "basic", status: "pending", employees: [{years: 0, code: "12"}, {years: -1, code: "DE"}]}, {rate: 10, country: "ok", plan: "basic", status: "open", employees: [{years: 65, code: "a"}, {years: 1.5, code: "NL"}, {years: 296, code: "VIP"}]}, {rate: 1.5, country: "é ü", plan: "basic", status: "open", employees: []}, {rate: 100, country: "日本", plan: "basic", status: "open", employees: []}, {rate: 0.5, country: "a", plan: "plus", status: "pending", employees: [{years: 0.1, code: "none"}]}, {rate: 99999999999999999999, country: "日本", plan: "basic", status: "closed", employees: [{years: 123456789.123, code: "12"}, {years: 0.5, code: "ok"}]}, {rate: 65, country: "12", plan: "premium", status: "pending", employees: [{years: 130, code: "O'Neil"}, {years: 0.1, code: "DE"}]}]}}, goals: ["flag", "borrower.total", "borrower.flags.tag"], output: "!error: InputValidationFailed"}, + {input: {borrower: {price: 1, income: 1000000, limit: 0.5, sku: " pad ", years: 10}}, goals: ["borrower.net", "line.margin"], output: {borrower: {income: 1000000, limit: 0.5, net: true, price: 1, sku: " pad ", years: 10}}}, + {input: {borrower: {price: -0.01, income: 18, limit: 250, sku: "a-b-c", years: 99.99, active: false, lines: [{rate: -0.5, country: "DE", plan: "basic", status: "open", employees: [{years: -0.5, code: "A1"}, {years: 1000000, code: "x-y"}]}, {rate: 0.5, country: "NL", plan: "trial", status: "pending", employees: [{years: 1, code: "abc"}, {years: 10, code: "-"}]}, {rate: -0.01, country: "A1", plan: "trial", status: "open", employees: []}, {rate: -500, country: "US", plan: "basic", status: "open", employees: [{years: 0.5, code: "US"}]}, {rate: -500, country: "none", plan: "plus", status: "closed", employees: [{years: 0.000001, code: "-"}, {years: 0.000001, code: "Zed"}]}, {rate: 1.5, country: "DE", plan: "basic", status: "open", employees: []}, {rate: 0.1, country: "Oslo", plan: "premium", status: "open", employees: [{years: 1.5, code: "VIP"}, {years: 1000000, code: "abc"}, {years: 0.5, code: " pad "}]}, {rate: 379, country: "US", plan: "basic", status: "pending", employees: [{years: 250, code: "a-b-c"}]}, {rate: 10, country: "", plan: "premium", status: "pending", employees: []}, {rate: 65, country: "12", plan: "premium", status: "pending", employees: [{years: 10, code: "O'Neil"}]}, {rate: 123456789.123, country: "-", plan: "trial", status: "closed", employees: [{years: 1000, code: "-"}, {years: -1, code: "none"}]}, {rate: 0.1, country: "ok", plan: "basic", status: "open", employees: [{years: -0.5, code: "12"}]}, {rate: 99999999999999999999, country: "a-b-c", plan: "premium", status: "closed", employees: []}], extraField: {nested: true}}}, goals: ["borrower.level", "borrower.total"], output: {borrower: {active: false, extraField: {nested: true}, income: 18, level: 14.3, limit: 250, lines: [{country: "DE", employees: [{code: "A1", years: -0.5}, {code: "x-y", years: 1000000}], plan: "basic", rate: -0.5, status: "open"}, {country: "NL", employees: [{code: "abc", years: 1}, {code: "-", years: 10}], plan: "trial", rate: 0.5, status: "pending"}, {country: "A1", employees: [], plan: "trial", rate: -0.01, status: "open"}, {country: "US", employees: [{code: "US", years: 0.5}], plan: "basic", rate: -500, status: "open"}, {country: "none", employees: [{code: "-", years: 0.000001}, {code: "Zed", years: 0.000001}], plan: "plus", rate: -500, status: "closed"}, {country: "DE", employees: [], plan: "basic", rate: 1.5, status: "open"}, {country: "Oslo", employees: [{code: "VIP", years: 1.5}, {code: "abc", years: 1000000}, {code: " pad ", years: 0.5}], plan: "premium", rate: 0.1, status: "open"}, {country: "US", employees: [{code: "a-b-c", years: 250}], plan: "basic", rate: 379, status: "pending"}, {country: "", employees: [], plan: "premium", rate: 10, status: "pending"}, {country: "12", employees: [{code: "O'Neil", years: 10}], plan: "premium", rate: 65, status: "pending"}, {country: "-", employees: [{code: "-", years: 1000}, {code: "none", years: -1}], plan: "trial", rate: 123456789.123, status: "closed"}, {country: "ok", employees: [{code: "12", years: -0.5}], plan: "basic", rate: 0.1, status: "open"}, {country: "a-b-c", employees: [], plan: "premium", rate: 99999999999999999999, status: "closed"}], price: -0.01, sku: "a-b-c", total: 99.99, years: 99.99}}}, + [{borrower: {price: 1000000, income: -0, limit: 0.5, sku: "12", years: 65, active: false, lines: [{rate: 0.5, country: "A1", plan: "premium", status: "open", employees: []}, {rate: 10, country: "A1", plan: "basic", status: "closed", employees: [{years: 7.25, code: "US"}, {years: 7.25, code: "日本"}]}, {rate: 18, country: "Oslo", plan: "basic", status: "open", employees: [{years: -0.5, code: "x-y"}, {years: 99999999999999999999, code: "DE"}]}, {rate: 2.50, country: "A1", plan: "premium", status: "open", employees: [{years: 0.5, code: "none"}, {years: 5, code: "DE"}]}]}}, {borrower: {active: false, flags: {fee: "false", tag: 65}, income: 0, level: 9.3, limit: 0.5, lines: [{country: "A1", employees: [], margin: "true", meta: {eligible: 1}, plan: "premium", rate: 0.5, status: "open"}, {country: "A1", employees: [{code: "US", years: 7.25}, {code: "日本", years: 7.25}], margin: "true", meta: {eligible: 1}, plan: "basic", rate: 10, status: "closed"}, {country: "Oslo", employees: [{code: "x-y", years: -0.5}, {code: "DE", years: 99999999999999999999}], margin: "true", meta: {eligible: 1}, plan: "basic", rate: 18, status: "open"}, {country: "A1", employees: [{code: "none", years: 0.5}, {code: "DE", years: 5}], margin: "true", meta: {eligible: 1}, plan: "premium", rate: 2.50, status: "open"}], net: false, price: 1000000, sku: "12", total: 65, years: 65}, flag: false, ok: "false/false-12/false"}], + [{borrower: {price: 1e3, income: "12", limit: 0.5, sku: "none", years: 5, active: true, lines: [{rate: 0.5, country: "retail", plan: "premium", status: "open", employees: [{years: 0, code: "NL"}]}, {rate: 65, country: "DE", plan: "premium", status: "open", employees: [{years: -0, code: "US"}, {years: 7.25, code: "DE"}]}, {rate: 100, country: "O'Neil", plan: "premium", status: "closed", employees: [{years: 100, code: "DE"}, {years: 2, code: "none"}]}]}}, "!error: InputValidationFailed"], + {input: {borrower: {price: 2.50, income: 1.5, limit: 18, sku: false, years: -0, active: false, lines: [{rate: 2, country: "", plan: "premium", status: "closed", employees: [{years: 1000000, code: "x-y"}, {years: 10, code: "a-b-c"}]}]}}, goals: ["borrower.level", "flag", "borrower.flags.fee"], output: "!error: InputValidationFailed"}, + {input: {borrower: {income: 2, limit: 5, sku: "O'Neil", years: 1, active: false, lines: [{rate: 0.5, country: "US", plan: null, status: "closed", employees: []}]}}, goals: ["line.margin"], output: {borrower: {active: false, income: 2, limit: 5, lines: [{country: "US", employees: [], margin: "false", plan: null, rate: 0.5, status: "closed"}], sku: "O'Neil", years: 1}}}, + {input: {borrower: {price: 1, income: null, limit: 7.25, sku: "é ü", years: 1e3, active: null, lines: [{rate: 99.99, country: "VIP", plan: "plus", status: "open", employees: [{years: 0}]}, {rate: 250, country: "none", plan: null, status: "open", employees: [{years: -0.5}, {years: -0.01, code: "ok"}]}, {rate: 99.99, country: "a", status: "open", employees: [{years: 0.1, code: "A1"}, {years: 99999999999999999999, code: "VIP"}]}]}}, goals: ["line.margin", "borrower.flags.fee", "ok"], output: {borrower: {active: null, flags: {fee: "false"}, income: null, limit: 7.25, lines: [{country: "VIP", employees: [{years: 0}], margin: "false/false", plan: "plus", rate: 99.99, status: "open"}, {country: "none", employees: [{years: -0.5}, {code: "ok", years: -0.01}], margin: "false/false", plan: null, rate: 250, status: "open"}, {country: "a", employees: [{code: "A1", years: 0.1}, {code: "VIP", years: 99999999999999999999}], margin: "false/false", rate: 99.99, status: "open"}], price: 1, sku: "é ü", total: 1000, years: 1000}, ok: "false/false-é ü/false"}}, + {input: {borrower: {price: 123456789.123, income: 0.000001, limit: 2, sku: "é ü", years: 1, active: true, lines: []}}, goals: ["line.margin", "borrower.flags.fee", "borrower.net"], output: {borrower: {active: true, flags: {fee: "VIP"}, income: 0.000001, limit: 2, lines: [], net: false, price: 123456789.123, sku: "é ü", total: 1, years: 1}}}, + [{borrower: {price: 282, income: -1, limit: -500, sku: "gold", years: 2.50, active: true, lines: []}}, {borrower: {active: true, flags: {fee: "VIP", tag: 2.50}, income: -1, level: 0.4, limit: -500, lines: [], net: false, price: 282, sku: "gold", total: 2.50, years: 2.50}, flag: false, ok: "true/true-gold/true"}], + {input: {borrower: {price: -500, income: 0.000001, limit: 1.5, sku: "Oslo", years: 10, active: true, lines: []}}, goals: ["ok", "borrower.total", "line.meta.eligible"], output: {borrower: {active: true, income: 0.000001, limit: 1.5, lines: [], price: -500, sku: "Oslo", total: 10, years: 10}, ok: "true/true-Oslo/true"}}, + {input: {borrower: {price: -1, income: 123456789.123, limit: 1000000, sku: "é ü", years: 100, active: true, lines: []}}, goals: ["borrower.level"], output: {borrower: {active: true, income: 123456789.123, level: 14.3, limit: 1000000, lines: [], price: -1, sku: "é ü", years: 100}}}, + {input: {borrower: {price: -0.01, income: 1000, limit: 7.25, sku: "VIP", years: 250, active: true, lines: [{rate: 2, country: "3.5", plan: "plus", status: "open", employees: [{years: -500, code: "Oslo"}, {years: -1, code: "x-y"}, {years: -0, code: "US"}]}, {rate: 7.25, country: "VIP", plan: "trial", status: "open", employees: [{years: -500, code: " pad "}]}]}}, goals: ["borrower.flags.tag"], output: {borrower: {active: true, flags: {tag: 250}, income: 1000, level: 35.7, limit: 7.25, lines: [{country: "3.5", employees: [{code: "Oslo", years: -500}, {code: "x-y", years: -1}, {code: "US", years: 0}], plan: "plus", rate: 2, status: "open"}, {country: "VIP", employees: [{code: " pad ", years: -500}], plan: "trial", rate: 7.25, status: "open"}], price: -0.01, sku: "VIP", total: 250, years: 250}}}, + {input: {borrower: {price: 0.000001, income: 99.99, limit: 99.99, sku: "日本", years: 0.000001, active: false, lines: [{rate: 56, country: "a-b-c", plan: "basic", status: "open", employees: []}, {rate: -0.5, country: " pad ", plan: "basic", status: "closed", employees: [{years: 18, code: "A1"}, {years: 10, code: "abc"}]}, {rate: 100, country: "retail", plan: "basic", status: "open", employees: [{years: 10, code: "VIP"}]}, {rate: 7.25, country: "DE", plan: "plus", status: "pending", employees: [{years: 65, code: "O'Neil"}, {years: 2, code: "O'Neil"}]}], extraField: "x"}}, goals: ["borrower.flags.tag"], output: {borrower: {active: false, extraField: "x", flags: {tag: -99}, income: 99.99, level: 0.0, limit: 99.99, lines: [{country: "a-b-c", employees: [], plan: "basic", rate: 56, status: "open"}, {country: " pad ", employees: [{code: "A1", years: 18}, {code: "abc", years: 10}], plan: "basic", rate: -0.5, status: "closed"}, {country: "retail", employees: [{code: "VIP", years: 10}], plan: "basic", rate: 100, status: "open"}, {country: "DE", employees: [{code: "O'Neil", years: 65}, {code: "O'Neil", years: 2}], plan: "plus", rate: 7.25, status: "pending"}], price: 0.000001, sku: "日本", years: 0.000001}}}, + [{borrower: {price: -0, income: 7.25, limit: 2, sku: "Zed", years: 0.5, active: true, lines: []}}, {borrower: {active: true, flags: {fee: "VIP", tag: -7}, income: 7.25, level: 0.1, limit: 2, lines: [], net: false, price: 0, sku: "Zed", total: 0.5, years: 0.5}, flag: false, ok: "true/true-Zed/true"}], + [{borrower: {price: 0.000001, income: 65, limit: 1000000, sku: "NL", years: -1, lines: [{rate: 10, country: "DE", plan: "plus", status: "open", employees: [{years: 2.50, code: null}, {years: -0.5}]}, {rate: 10, country: "US", status: "open", employees: []}, {rate: -0, country: "a", status: "open", employees: [{years: 1.5, code: " pad "}, {years: 0.5, code: "x-y"}]}, {rate: 1, country: "x-y", plan: "premium", status: "pending", employees: [{years: 1.5, code: "abc"}, {years: 18}]}]}}, {borrower: {flags: {fee: "NL", tag: -65}, income: 65, level: -0.1, limit: 1000000, lines: [{country: "DE", employees: [{code: null, years: 2.50}, {years: -0.5}], margin: "false", meta: {eligible: 1}, plan: "plus", rate: 10, status: "open"}, {country: "US", employees: [], margin: "false", meta: {eligible: 1}, rate: 10, status: "open"}, {country: "a", employees: [{code: " pad ", years: 1.5}, {code: "x-y", years: 0.5}], margin: "false", meta: {eligible: 1}, rate: 0, status: "open"}, {country: "x-y", employees: [{code: "abc", years: 1.5}, {years: 18}], margin: "false", meta: {eligible: 1}, plan: "premium", rate: 1, status: "pending"}], net: false, price: 0.000001, sku: "NL", total: -1, years: -1}, flag: false, ok: "false/false-NL/false"}], + {input: {borrower: {price: null, income: null, limit: 7.25, sku: "none", years: 10, active: null, lines: [{rate: 123456789.123, country: "-", plan: "premium", status: "open", employees: [{years: 0.1, code: "x-y"}, {years: -500}]}, {rate: -0, country: "a-b-c", plan: "basic", status: "open", employees: [{years: 1e3}, {years: -1}, {years: 24, code: null}]}, {rate: 10, country: "", plan: "premium", status: "open", employees: [{years: 250, code: "DE"}, {years: -1, code: "a"}]}]}}, goals: ["ok", "borrower.net", "borrower.total"], output: {borrower: {active: null, income: null, limit: 7.25, lines: [{country: "-", employees: [{code: "x-y", years: 0.1}, {years: -500}], plan: "premium", rate: 123456789.123, status: "open"}, {country: "a-b-c", employees: [{years: 1000}, {years: -1}, {code: null, years: 24}], plan: "basic", rate: 0, status: "open"}, {country: "", employees: [{code: "DE", years: 250}, {code: "a", years: -1}], plan: "premium", rate: 10, status: "open"}], net: false, price: null, sku: "none", total: 10, years: 10}, ok: "false/false-none/false"}}, + {input: {borrower: {price: 123456789.123, income: 1.5, limit: -0.01, sku: "", years: 0, active: true, lines: [{rate: 7.25, country: "none", plan: null, status: "pending", employees: []}]}}, goals: ["borrower.level"], output: {borrower: {active: true, income: 1.5, level: 0, limit: -0.01, lines: [{country: "none", employees: [], plan: null, rate: 7.25, status: "pending"}], price: 123456789.123, sku: "", years: 0}}}, + {input: {borrower: {price: -1, income: -1, limit: -500, sku: "3.5", years: 123456789.123, active: true, lines: [{rate: 123456789.123, country: "retail", plan: "trial", status: "closed", employees: [{years: 65, code: "DE"}]}, {rate: 2.50, country: "12", plan: "premium", status: "closed", employees: [{years: 1, code: "é ü"}, {years: 0.5, code: "US"}]}, {rate: 18, country: "NL", plan: "premium", status: "pending", employees: [{years: 7.25, code: "é ü"}, {years: 10, code: "-"}]}, {rate: 2, country: "A1", plan: "premium", status: "open", employees: [{years: 5, code: "a-b-c"}, {years: 99999999999999999999, code: "Zed"}]}, {rate: 7.25, country: "x-y", plan: "plus", status: "closed", employees: [{years: 1000, code: "DE"}]}]}}, goals: ["borrower.net", "borrower.total", "line.meta.eligible"], output: {borrower: {active: true, income: -1, limit: -500, lines: [{country: "retail", employees: [{code: "DE", years: 65}], meta: {eligible: 1}, plan: "trial", rate: 123456789.123, status: "closed"}, {country: "12", employees: [{code: "é ü", years: 1}, {code: "US", years: 0.5}], meta: {eligible: 1}, plan: "premium", rate: 2.50, status: "closed"}, {country: "NL", employees: [{code: "é ü", years: 7.25}, {code: "-", years: 10}], meta: {eligible: 1}, plan: "premium", rate: 18, status: "pending"}, {country: "A1", employees: [{code: "a-b-c", years: 5}, {code: "Zed", years: 99999999999999999999}], meta: {eligible: 1}, plan: "premium", rate: 2, status: "open"}, {country: "x-y", employees: [{code: "DE", years: 1000}], meta: {eligible: 1}, plan: "plus", rate: 7.25, status: "closed"}], net: false, price: -1, sku: "3.5", total: 123456789.123, years: 123456789.123}}}, + [{borrower: {price: -0.01, income: 10, limit: 10, sku: "3.5", years: 5, lines: [{rate: 2.50, country: "US", status: "pending", employees: [{years: 123456789.123, code: "abc"}, {years: 99.99, code: "DE"}, {years: 123456789.123}]}, {rate: 18, country: "é ü", status: "closed", employees: [{years: 0.5, code: null}, {years: 7.25, code: "gold"}, {years: 1000, code: "O'Neil"}]}, {rate: 250, country: "US", status: "open", employees: [{years: 1.5}, {years: 99.99, code: "ok"}]}, {rate: 10, country: "", plan: "trial", status: "open", employees: []}, {rate: -0.5, country: "Zed", status: "closed", employees: []}, {rate: 10, country: "a", status: "open", employees: [{years: 10}, {years: 0.5, code: "-"}]}, {rate: 0.1, country: "VIP", plan: "premium", status: "pending", employees: [{years: 2.50}, {years: 2}, {years: 0.5, code: "3.5"}]}, {rate: 99999999999999999999, country: "O'Neil", plan: null, status: "open", employees: [{years: -0.5, code: "abc"}, {years: 18}]}, {rate: 250, country: "retail", status: "closed", employees: [{years: 18}, {years: 99.99, code: null}]}, {rate: -0.5, country: "3.5", plan: null, status: "open", employees: []}, {rate: 0, country: "Oslo", status: "open", employees: [{years: -500, code: "gold"}, {years: 0, code: "VIP"}]}, {rate: -500, country: "é ü", plan: "basic", status: "open", employees: []}, {rate: 65, country: "VIP", plan: "basic", status: "open", employees: [{years: 1.5, code: "日本"}, {years: 10}]}]}}, {borrower: {flags: {fee: "3.5", tag: -10}, income: 10, level: 0.7, limit: 10, lines: [{country: "US", employees: [{code: "abc", years: 123456789.123}, {code: "DE", years: 99.99}, {years: 123456789.123}], margin: "true", meta: {eligible: 1}, rate: 2.50, status: "pending"}, {country: "é ü", employees: [{code: null, years: 0.5}, {code: "gold", years: 7.25}, {code: "O'Neil", years: 1000}], margin: "true", meta: {eligible: 1}, rate: 18, status: "closed"}, {country: "US", employees: [{years: 1.5}, {code: "ok", years: 99.99}], margin: "true", meta: {eligible: 1}, rate: 250, status: "open"}, {country: "", employees: [], margin: "true", meta: {eligible: 1}, plan: "trial", rate: 10, status: "open"}, {country: "Zed", employees: [], margin: "true", meta: {eligible: 1}, rate: -0.5, status: "closed"}, {country: "a", employees: [{years: 10}, {code: "-", years: 0.5}], margin: "true", meta: {eligible: 1}, rate: 10, status: "open"}, {country: "VIP", employees: [{years: 2.50}, {years: 2}, {code: "3.5", years: 0.5}], margin: "true", meta: {eligible: 1}, plan: "premium", rate: 0.1, status: "pending"}, {country: "O'Neil", employees: [{code: "abc", years: -0.5}, {years: 18}], margin: "true", meta: {eligible: 1}, plan: null, rate: 99999999999999999999, status: "open"}, {country: "retail", employees: [{years: 18}, {code: null, years: 99.99}], margin: "true", meta: {eligible: 1}, rate: 250, status: "closed"}, {country: "3.5", employees: [], margin: "true", meta: {eligible: 1}, plan: null, rate: -0.5, status: "open"}, {country: "Oslo", employees: [{code: "gold", years: -500}, {code: "VIP", years: 0}], margin: "true", meta: {eligible: 1}, rate: 0, status: "open"}, {country: "é ü", employees: [], margin: "true", meta: {eligible: 1}, plan: "basic", rate: -500, status: "open"}, {country: "VIP", employees: [{code: "日本", years: 1.5}, {years: 10}], margin: "true", meta: {eligible: 1}, plan: "basic", rate: 65, status: "open"}], net: false, price: -0.01, sku: "3.5", total: 5, years: 5}, flag: false, ok: "false/false-3.5/false"}], + ], +} + +// seed 351500 (attempt 0) +{ + name: "goals 16: applicant/companies: 1 assertion, 4 expression, 4 match, 2 table; 6 root, 6 per-member, 1 top-level computed", + policy: { + models: {applicant: {years: "number", plan: "string(basic|plus|premium|trial)", days: "number", balance: "number", qty: "number", urgent: "boolean", companies: "company[]"}, company: {years: "number", limit: "number?", birthDate: "date", city: "string"}}, + blocks: [ + {expression: "margin", value: "filter(applicant.companies, #.penalty != null)"}, + {match: "company.totals.tag", arms: [["company.city in ['retail', 'VIP']", "trunc(((company.limit ?? 0) - company.years))"], ["not ((company.totals.review and (applicant.flags.weighted ?? false)))", "(applicant.days + (applicant.surcharge ?? 0))"], ["", "len(filter(applicant.companies, startsWith(#.share, 'VIP')))"]]}, + {table: "t4", inputs: ["applicant.years"], outputs: ["applicant.flags.weighted", "applicant.surcharge", "applicant.summary"], rules: [ + ["", "applicant.urgent", "applicant.qty", "'gold'"], + ["2, 10", "applicant.urgent", "applicant.years", "'high'"], + ["", "applicant.urgent", "applicant.years", "'a'"], + ["< 0", "applicant.urgent", "applicant.balance", ""], + ["[0..480]", "applicant.urgent", "applicant.balance", "'VIP'"], + ["", "applicant.urgent", "applicant.days", "'a'"], + ]}, + {match: "company.totals.review", arms: [["all(applicant.companies, #.birthDate.isAfter(d('2025-03-20'), 'month'))", "applicant.urgent"], ["number(string(applicant.years)) <= 1000", "(company.share + '-' + 'DE') == 'VIP'"], ["(applicant.urgent and applicant.urgent)", "company.birthDate >= d('2025-01-01')"], ["", "company.years != applicant.qty"]]}, + {expression: "applicant.band", value: "filter(applicant.companies, #.city == 'ok')"}, + {expression: "company.adjusted", value: "company.birthDate"}, + {match: "company.share", arms: [["applicant.balance in [34..142]", "(split((split(company.city, '-')[0] ?? 'none'), '-')[0] ?? 'none')"], ["", "`${company.city}/${applicant.urgent}`"]]}, + {table: "t6", inputs: ["(applicant.years + 18)"], outputs: ["company.penalty"], rules: [ + ["18", "0.5"], + ["", "(company.limit ?? 0)"], + ["", ""], + ["", "company.years"], + ]}, + {expression: "company.risk", value: "(applicant.urgent or company.totals.review)"}, + {match: "applicant.exposure", arms: [["applicant.years in [2..30]", "'low'"], ["((applicant.urgent and (applicant.flags.weighted ?? false)) and isNumeric((applicant.summary ?? '')))", "'Oslo'"], ["", "(applicant.summary ?? '')"]]}, + {assertion: "applicant.decision", conditions: [["and", "applicant.summary == null", 0], ["and", "applicant.years in [29..137]", 1]]}, + ], + }, + cases: [ + {input: {applicant: {years: 0, plan: "premium", days: 18, balance: 1e3, qty: 2, urgent: true, companies: [{years: 1, limit: 0.000001, birthDate: "2000-01-01", city: "VIP"}]}}, goals: ["company.totals.review"], output: {applicant: {balance: 1000, companies: [{birthDate: "2000-01-01", city: "VIP", limit: 0.000001, share: "VIP/true", totals: {review: false}, years: 1}], days: 18, plan: "premium", qty: 2, urgent: true, years: 0}}}, + {input: {applicant: {years: 18, plan: "basic", days: 1000000, balance: 100, qty: 0, urgent: true, companies: [{years: 10, limit: 10, birthDate: "2024-02-29", city: "Zed"}, {years: 123456789.123, limit: 100, birthDate: "2000-01-01", city: "VIP"}]}}, goals: ["company.totals.review", "company.risk"], output: {applicant: {balance: 100, companies: [{birthDate: "2024-02-29", city: "Zed", limit: 10, risk: true, share: "Zed", totals: {review: false}, years: 10}, {birthDate: "2000-01-01", city: "VIP", limit: 100, risk: true, share: "VIP", totals: {review: false}, years: 123456789.123}], days: 1000000, plan: "basic", qty: 0, urgent: true, years: 18}}}, + {input: {applicant: {years: 1, plan: "plus", days: 0.1, balance: 0, qty: -1, urgent: true, companies: [{years: 50, birthDate: "2024-02-29", city: ""}, {years: 99999999999999999999, limit: null, birthDate: "2024-02-29", city: "NL"}, {years: 18, limit: null, birthDate: "2024-01-01", city: "a"}, {years: 1000, limit: null, birthDate: "2030-12-31", city: "VIP"}]}}, goals: ["company.totals.tag"], output: {applicant: {balance: 0, companies: [{birthDate: "2024-02-29", city: "", share: "/true", totals: {review: false, tag: -0.9}, years: 50}, {birthDate: "2024-02-29", city: "NL", limit: null, share: "NL/true", totals: {review: false, tag: -0.9}, years: 99999999999999999999}, {birthDate: "2024-01-01", city: "a", limit: null, share: "a/true", totals: {review: false, tag: -0.9}, years: 18}, {birthDate: "2030-12-31", city: "VIP", limit: null, share: "VIP/true", totals: {review: false, tag: -1000}, years: 1000}], days: 0.1, flags: {weighted: true}, plan: "plus", qty: -1, summary: "gold", surcharge: -1, urgent: true, years: 1}}}, + {input: {applicant: {years: 123456789.123, plan: "basic", days: 18, balance: 0, qty: 0, urgent: false, companies: [{years: 250, limit: -0.01, birthDate: "2024-02-29", city: "retail"}], extraField: "x"}}, goals: ["margin", "applicant.flags.weighted"], output: {applicant: {balance: 0, companies: [{birthDate: "2024-02-29", city: "retail", limit: -0.01, penalty: -0.01, years: 250}], days: 18, extraField: "x", flags: {weighted: false}, plan: "basic", qty: 0, summary: "gold", surcharge: 0, urgent: false, years: 123456789.123}, margin: [{birthDate: "2024-02-29", city: "retail", limit: -0.01, penalty: -0.01, years: 250}]}}, + {input: {applicant: {years: 1000000, plan: "premium", days: 65, balance: 100, qty: 18, urgent: false, companies: [{years: 18, limit: null, birthDate: "2025-03-20", city: "O'Neil"}, {years: 1, limit: null, birthDate: "2024-02-29", city: "VIP"}]}}, goals: ["applicant.flags.weighted", "company.totals.review", "applicant.summary"], output: {applicant: {balance: 100, companies: [{birthDate: "2025-03-20", city: "O'Neil", limit: null, totals: {review: false}, years: 18}, {birthDate: "2024-02-29", city: "VIP", limit: null, totals: {review: true}, years: 1}], days: 65, flags: {weighted: false}, plan: "premium", qty: 18, summary: "gold", surcharge: 18, urgent: false, years: 1000000}}}, + {input: {applicant: {years: 0, plan: "plus", days: 0, balance: 1000, qty: 0, urgent: true, companies: [{years: 99.99, limit: 1e3, birthDate: "2025-03-20T10:15:30Z", city: "a"}], extraField: {nested: true}}}, goals: ["applicant.flags.weighted", "margin"], output: {applicant: {balance: 1000, companies: [{birthDate: "2025-03-20T10:15:30Z", city: "a", limit: 1000, penalty: 0.5, years: 99.99}], days: 0, extraField: {nested: true}, flags: {weighted: true}, plan: "plus", qty: 0, summary: "gold", surcharge: 0, urgent: true, years: 0}, margin: [{birthDate: "2025-03-20T10:15:30Z", city: "a", limit: 1000, penalty: 0.5, years: 99.99}]}}, + {input: {applicant: {years: 2, plan: "trial", days: 1000, balance: -0.5, qty: 10, urgent: false, companies: [{years: 99.99, limit: null, birthDate: "2024-01-01", city: " pad "}, {years: 10, birthDate: "2025-03-20T10:15:30Z", city: "é ü"}, {years: -0.5, limit: 0.1, birthDate: "2025-03-20T10:15:30Z", city: "a-b-c"}, {years: 100, limit: 2.50, birthDate: "2024-01-01", city: "retail"}, {years: 18, birthDate: "1990-06-15", city: "x-y"}]}}, goals: ["company.risk", "company.adjusted", "company.penalty"], output: {applicant: {balance: -0.5, companies: [{adjusted: "2024-01-01", birthDate: "2024-01-01", city: " pad ", limit: null, penalty: 0, risk: false, share: " pad /false", totals: {review: false}, years: 99.99}, {adjusted: "2025-03-20T10:15:30Z", birthDate: "2025-03-20T10:15:30Z", city: "é ü", penalty: 0, risk: false, share: "é ü/false", totals: {review: false}, years: 10}, {adjusted: "2025-03-20T10:15:30Z", birthDate: "2025-03-20T10:15:30Z", city: "a-b-c", limit: 0.1, penalty: 0.1, risk: false, share: "a-b-c/false", totals: {review: false}, years: -0.5}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "retail", limit: 2.50, penalty: 2.50, risk: false, share: "retail/false", totals: {review: false}, years: 100}, {adjusted: "1990-06-15", birthDate: "1990-06-15", city: "x-y", penalty: 0, risk: false, share: "x-y/false", totals: {review: false}, years: 18}], days: 1000, plan: "trial", qty: 10, urgent: false, years: 2}}}, + {input: {applicant: {years: 65, plan: "plus", days: 50, balance: 18, qty: -0.5, urgent: true, companies: [{years: 1000000, limit: null, birthDate: "2024-01-01", city: "gold"}, {years: 1, limit: 0.1, birthDate: "2000-01-01", city: "DE"}, {years: 7.25, limit: 10, birthDate: "1990-06-15", city: "a"}, {years: 2, limit: 250, birthDate: "1990-06-15", city: "abc"}, {years: 1, limit: 0.000001, birthDate: "2025-03-20T10:15:30Z", city: "DE"}]}}, goals: ["applicant.band"], output: {applicant: {balance: 18, band: [], companies: [{birthDate: "2024-01-01", city: "gold", limit: null, years: 1000000}, {birthDate: "2000-01-01", city: "DE", limit: 0.1, years: 1}, {birthDate: "1990-06-15", city: "a", limit: 10, years: 7.25}, {birthDate: "1990-06-15", city: "abc", limit: 250, years: 2}, {birthDate: "2025-03-20T10:15:30Z", city: "DE", limit: 0.000001, years: 1}], days: 50, plan: "plus", qty: -0.5, urgent: true, years: 65}}}, + {input: {applicant: {years: -0, plan: "plus", days: 2, balance: 0, qty: 65, urgent: true, companies: []}}, goals: ["applicant.band"], output: {applicant: {balance: 0, band: [], companies: [], days: 2, plan: "plus", qty: 65, urgent: true, years: 0}}}, + {input: {applicant: {years: 1000, plan: "premium", days: 0.1, balance: 0, qty: 0, urgent: true, companies: [{years: 18, birthDate: "1990-06-15", city: "ok"}]}}, goals: ["applicant.exposure"], output: {applicant: {balance: 0, companies: [{birthDate: "1990-06-15", city: "ok", years: 18}], days: 0.1, exposure: "gold", flags: {weighted: true}, plan: "premium", qty: 0, summary: "gold", surcharge: 0, urgent: true, years: 1000}}}, + {input: {applicant: {years: 0.5, plan: "basic", days: 0.1, balance: 18, qty: 81, urgent: false, companies: [{years: 0, birthDate: "1990-06-15", city: "NL"}]}}, goals: ["company.adjusted"], output: {applicant: {balance: 18, companies: [{adjusted: "1990-06-15", birthDate: "1990-06-15", city: "NL", years: 0}], days: 0.1, plan: "basic", qty: 81, urgent: false, years: 0.5}}}, + {input: {applicant: {years: 0, plan: "basic", days: 99.99, balance: 18, qty: 10, urgent: false, companies: [{years: 10, limit: 0, birthDate: "2030-12-31", city: "a"}, {years: -0.5, birthDate: "2030-12-31", city: "VIP"}, {years: 65, birthDate: "2024-01-01", city: ""}]}}, goals: ["company.adjusted", "applicant.exposure"], output: {applicant: {balance: 18, companies: [{adjusted: "2030-12-31", birthDate: "2030-12-31", city: "a", limit: 0, years: 10}, {adjusted: "2030-12-31", birthDate: "2030-12-31", city: "VIP", years: -0.5}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "", years: 65}], days: 99.99, exposure: "gold", flags: {weighted: false}, plan: "basic", qty: 10, summary: "gold", surcharge: 10, urgent: false, years: 0}}}, + {input: {applicant: {years: 1000, plan: "basic", days: 1, balance: 18, qty: 0.5, urgent: false, companies: [{years: 10, limit: 0, birthDate: "2025-03-20", city: "DE"}, {years: 250, limit: null, birthDate: "2025-03-20T10:15:30Z", city: "a"}]}}, goals: ["company.penalty"], output: {applicant: {balance: 18, companies: [{birthDate: "2025-03-20", city: "DE", limit: 0, penalty: 0, years: 10}, {birthDate: "2025-03-20T10:15:30Z", city: "a", limit: null, penalty: 0, years: 250}], days: 1, plan: "basic", qty: 0.5, urgent: false, years: 1000}}}, + {input: {applicant: {years: 1000, plan: "basic", days: 0.5, balance: 18, qty: 1e3, urgent: true, companies: [{years: 65, limit: 2, birthDate: "2030-12-31", city: "VIP"}, {years: 2.50, limit: 1000, birthDate: "2025-03-20", city: "a"}, {years: 1, limit: 5, birthDate: "2025-03-20", city: "VIP"}, {years: 0.5, limit: 1000000, birthDate: "2030-12-31", city: "-"}, {years: 18, limit: 0, birthDate: "2030-12-31", city: "3.5"}]}}, goals: ["company.totals.tag"], output: {applicant: {balance: 18, companies: [{birthDate: "2030-12-31", city: "VIP", limit: 2, share: "VIP/true", totals: {review: false, tag: -63}, years: 65}, {birthDate: "2025-03-20", city: "a", limit: 1000, share: "a/true", totals: {review: false, tag: 1000.5}, years: 2.50}, {birthDate: "2025-03-20", city: "VIP", limit: 5, share: "VIP/true", totals: {review: false, tag: 4}, years: 1}, {birthDate: "2030-12-31", city: "-", limit: 1000000, share: "-/true", totals: {review: false, tag: 1000.5}, years: 0.5}, {birthDate: "2030-12-31", city: "3.5", limit: 0, share: "3.5/true", totals: {review: false, tag: 1000.5}, years: 18}], days: 0.5, flags: {weighted: true}, plan: "basic", qty: 1000, summary: "gold", surcharge: 1000, urgent: true, years: 1000}}}, + {input: {applicant: {years: 18, plan: "trial", days: 2, balance: 18, qty: 1, urgent: false, companies: [{years: 250, limit: -500, birthDate: "2025-03-20T10:15:30Z", city: "VIP"}, {years: -0.5, limit: 7.25, birthDate: "2030-12-31", city: "O'Neil"}, {years: 1000000, limit: 0.1, birthDate: "2024-02-29", city: "US"}]}}, goals: ["company.share"], output: {applicant: {balance: 18, companies: [{birthDate: "2025-03-20T10:15:30Z", city: "VIP", limit: -500, share: "VIP/false", years: 250}, {birthDate: "2030-12-31", city: "O'Neil", limit: 7.25, share: "O'Neil/false", years: -0.5}, {birthDate: "2024-02-29", city: "US", limit: 0.1, share: "US/false", years: 1000000}], days: 2, plan: "trial", qty: 1, urgent: false, years: 18}}}, + {input: {applicant: {years: 1000, plan: "premium", days: 0, balance: 2, qty: -1, urgent: true, companies: [{years: 1, limit: 1, birthDate: "2000-01-01", city: "retail"}, {years: 99999999999999999999, limit: 1e3, birthDate: "1990-06-15", city: "high"}]}}, goals: ["company.totals.review"], output: {applicant: {balance: 2, companies: [{birthDate: "2000-01-01", city: "retail", limit: 1, share: "retail/true", totals: {review: false}, years: 1}, {birthDate: "1990-06-15", city: "high", limit: 1000, share: "high/true", totals: {review: false}, years: 99999999999999999999}], days: 0, plan: "premium", qty: -1, urgent: true, years: 1000}}}, + {input: {applicant: {plan: "trial", days: 250, balance: 18, qty: 1e3, urgent: true, companies: [{years: 18, limit: 99.99, birthDate: "1990-06-15", city: "abc"}]}}, goals: ["applicant.decision", "applicant.flags.weighted"], output: "!error: MissingRequiredInputs"}, + [{applicant: {years: 18, plan: "trial", days: 0, balance: 0, qty: 0.5, urgent: false, companies: [{years: 99.99, limit: 1, birthDate: "2000-01-01", city: "US"}, {years: -0.01, limit: 0, birthDate: "2024-01-01", city: "日本"}, {years: 0.5, limit: 18, birthDate: "2024-01-01", city: "O'Neil"}, {years: 0.000001, limit: 1000, birthDate: "2024-01-01", city: "retail"}, {years: 0, limit: 394, birthDate: "2024-01-01", city: "gold"}]}}, {applicant: {balance: 0, band: [], companies: [{adjusted: "2000-01-01", birthDate: "2000-01-01", city: "US", limit: 1, penalty: 1, risk: false, share: "US/false", totals: {review: false}, years: 99.99}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "日本", limit: 0, penalty: 0, risk: false, share: "日本/false", totals: {review: false}, years: -0.01}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "O'Neil", limit: 18, penalty: 18, risk: false, share: "O'Neil/false", totals: {review: false}, years: 0.5}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "retail", limit: 1000, penalty: 1000, risk: false, share: "retail/false", totals: {review: false}, years: 0.000001}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "gold", limit: 394, penalty: 394, risk: false, share: "gold/false", totals: {review: false}, years: 0}], days: 0, decision: false, exposure: "low", flags: {weighted: false}, plan: "trial", qty: 0.5, summary: "gold", surcharge: 0.5, urgent: false, years: 18}, margin: [{adjusted: "2000-01-01", birthDate: "2000-01-01", city: "US", limit: 1, penalty: 1, risk: false, share: "US/false", totals: {review: false}, years: 99.99}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "日本", limit: 0, penalty: 0, risk: false, share: "日本/false", totals: {review: false}, years: -0.01}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "O'Neil", limit: 18, penalty: 18, risk: false, share: "O'Neil/false", totals: {review: false}, years: 0.5}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "retail", limit: 1000, penalty: 1000, risk: false, share: "retail/false", totals: {review: false}, years: 0.000001}, {adjusted: "2024-01-01", birthDate: "2024-01-01", city: "gold", limit: 394, penalty: 394, risk: false, share: "gold/false", totals: {review: false}, years: 0}]}], + {input: {applicant: {years: -0, plan: "premium", days: 50, balance: 10, qty: 18, companies: [{years: -0, limit: 10, birthDate: "2000-01-01", city: "VIP"}]}}, goals: ["applicant.exposure"], output: "!error: MissingRequiredInputs"}, + {input: {applicant: {years: -0.5, plan: "trial", days: 99999999999999999999, balance: 100, qty: 0.000001, urgent: true, companies: [{years: 0, limit: -0.5, birthDate: "2025-03-20T10:15:30Z", city: "a"}, {years: 7.25, limit: 2.50, birthDate: "2025-03-20", city: "Zed"}, {years: -500, limit: -0.5, birthDate: "2024-02-29", city: "-"}, {years: 18, limit: -0.01, birthDate: "1990-06-15", city: "a"}]}}, goals: ["applicant.surcharge", "margin", "company.totals.tag"], output: {applicant: {balance: 100, companies: [{birthDate: "2025-03-20T10:15:30Z", city: "a", limit: -0.5, penalty: -0.5, share: "a", totals: {review: false, tag: 99999999999999999999.000001}, years: 0}, {birthDate: "2025-03-20", city: "Zed", limit: 2.50, penalty: 2.50, share: "Zed", totals: {review: false, tag: 99999999999999999999.000001}, years: 7.25}, {birthDate: "2024-02-29", city: "-", limit: -0.5, penalty: -0.5, share: "", totals: {review: false, tag: 99999999999999999999.000001}, years: -500}, {birthDate: "1990-06-15", city: "a", limit: -0.01, penalty: -0.01, share: "a", totals: {review: false, tag: 99999999999999999999.000001}, years: 18}], days: 99999999999999999999, flags: {weighted: true}, plan: "trial", qty: 0.000001, summary: "gold", surcharge: 0.000001, urgent: true, years: -0.5}, margin: [{birthDate: "2025-03-20T10:15:30Z", city: "a", limit: -0.5, penalty: -0.5, share: "a", totals: {review: false, tag: 99999999999999999999.000001}, years: 0}, {birthDate: "2025-03-20", city: "Zed", limit: 2.50, penalty: 2.50, share: "Zed", totals: {review: false, tag: 99999999999999999999.000001}, years: 7.25}, {birthDate: "2024-02-29", city: "-", limit: -0.5, penalty: -0.5, share: "", totals: {review: false, tag: 99999999999999999999.000001}, years: -500}, {birthDate: "1990-06-15", city: "a", limit: -0.01, penalty: -0.01, share: "a", totals: {review: false, tag: 99999999999999999999.000001}, years: 18}]}}, + {input: {applicant: {years: 2, plan: "basic", days: 1, balance: 0, qty: 10, urgent: false, companies: []}}, goals: ["applicant.exposure", "company.totals.review", "company.share"], output: {applicant: {balance: 0, companies: [], days: 1, exposure: "low", flags: {weighted: false}, plan: "basic", qty: 10, summary: "gold", surcharge: 10, urgent: false, years: 2}}}, + {input: {applicant: {years: 0.000001, plan: "premium", days: -0.01, balance: 99999999999999999999, qty: 1000, urgent: false, companies: [{years: 50, limit: 1, birthDate: "2025-03-20T10:15:30Z", city: "-"}, {years: 1, limit: 100, birthDate: "2025-03-20", city: "abc"}]}}, goals: ["applicant.exposure"], output: {applicant: {balance: 99999999999999999999, companies: [{birthDate: "2025-03-20T10:15:30Z", city: "-", limit: 1, years: 50}, {birthDate: "2025-03-20", city: "abc", limit: 100, years: 1}], days: -0.01, exposure: "gold", flags: {weighted: false}, plan: "premium", qty: 1000, summary: "gold", surcharge: 1000, urgent: false, years: 0.000001}}}, + [{applicant: {years: 2, plan: "plus", days: 10, balance: 1, qty: 7.25, urgent: false, companies: []}}, {applicant: {balance: 1, band: [], companies: [], days: 10, decision: false, exposure: "low", flags: {weighted: false}, plan: "plus", qty: 7.25, summary: "gold", surcharge: 7.25, urgent: false, years: 2}, margin: []}], + {input: {applicant: {years: 100, plan: "premium", days: 0.5, balance: 0, qty: 2.50, urgent: false, companies: [{years: 2, limit: 0, birthDate: "1990-06-15", city: "VIP"}, {years: 2, limit: 10, birthDate: "2024-01-01", city: ""}, {years: 0, limit: 99999999999999999999, birthDate: "1990-06-15", city: "abc"}]}}, goals: ["applicant.flags.weighted"], output: {applicant: {balance: 0, companies: [{birthDate: "1990-06-15", city: "VIP", limit: 0, years: 2}, {birthDate: "2024-01-01", city: "", limit: 10, years: 2}, {birthDate: "1990-06-15", city: "abc", limit: 99999999999999999999, years: 0}], days: 0.5, flags: {weighted: false}, plan: "premium", qty: 2.50, summary: "gold", surcharge: 2.50, urgent: false, years: 100}}}, + {input: {applicant: {years: 2, plan: "premium", days: 2, balance: 65, qty: -1, urgent: true, companies: [{years: 10, limit: 0, birthDate: "2030-12-31", city: "US"}]}}, goals: ["applicant.flags.weighted", "company.adjusted"], output: {applicant: {balance: 65, companies: [{adjusted: "2030-12-31", birthDate: "2030-12-31", city: "US", limit: 0, years: 10}], days: 2, flags: {weighted: true}, plan: "premium", qty: -1, summary: "gold", surcharge: -1, urgent: true, years: 2}}}, + {input: {applicant: {years: 250, plan: "basic", days: null, balance: 50, qty: 7.25, urgent: false, companies: [{years: 99999999999999999999, limit: 0, birthDate: "2030-12-31", city: "retail"}, {years: 10, limit: 10, birthDate: "2030-12-31", city: "ok"}, {years: 5, limit: 18, birthDate: "1990-06-15", city: "a"}, {years: 2, limit: 99999999999999999999, birthDate: "2024-02-29", city: "Oslo"}, {years: 123456789.123, limit: -500, birthDate: "1990-06-15", city: "Zed"}]}}, goals: ["company.totals.tag", "applicant.summary"], output: "!error: MissingRequiredInputs"}, + {input: {applicant: {years: 2, plan: "basic", balance: 0, qty: 1000, urgent: true, companies: [{years: 0.5, limit: 10, birthDate: "2024-01-01", city: "VIP"}]}}, goals: ["applicant.decision", "company.risk"], output: "!error: MissingRequiredInputs"}, + {input: {applicant: {years: -500, plan: "basic", days: 1000, balance: 0, qty: 65, urgent: true, companies: []}}, goals: ["applicant.flags.weighted", "applicant.band"], output: {applicant: {balance: 0, band: [], companies: [], days: 1000, flags: {weighted: true}, plan: "basic", qty: 65, summary: "gold", surcharge: 65, urgent: true, years: -500}}}, + ], +} + +// seed 351600 (attempt 0) +{ + name: "goals 17: applicant/lines/employees: 1 assertion, 4 expression, 2 match, 4 table; 8 root, 8 per-member, 0 top-level computed", + policy: { + models: {applicant: {rate: "number", since: "date", status: "string(open|closed|pending)", price: "number", dueDate: "date", lines: "line[]"}, line: {days: "number?", status: "string(open|closed|pending)", employees: "employee[]"}, employee: {rate: "number", years: "number?", insured: "boolean?"}}, + blocks: [ + {match: "line.calc.risk", arms: [["applicant.rate in [20..35]", "applicant.price"], ["line.days != null", "applicant.price"], ["", "applicant.rate"]]}, + {expression: "line.calc.review", value: "line.days == null"}, + {expression: "applicant.totals.weighted", value: "filter(applicant.lines, ((#.days ?? 0) - #.calc.risk) < (#.days ?? 0))"}, + {expression: "applicant.decision", value: "(applicant.price in [37..150] ? max([applicant.price, applicant.rate]) : round(applicant.rate / 7, 0))"}, + {table: "t5", hit: "collect", inputs: ["(min([abs(applicant.decision), 1000]) ^ 0)"], outputs: ["applicant.ok", "applicant.totals.total", "applicant.scores.rank"], rules: [ + ["<= 1", "'A1'", "(avg(map(applicant.lines, 1)) ?? 0)", "'low'"], + ["", "'gold'", "(max(map(applicant.lines, (#.days ?? 0))) ?? 0)", "'none'"], + ["> 5", "`${100 <= 3}/${applicant.price}`", "(avg(map(applicant.lines, #.calc.risk)) ?? 0)", "'gold'"], + ]}, + {assertion: "applicant.surcharge", conditions: ["none(applicant.lines, #.status != 'open')", "isNumeric(string(applicant.price > 100))", ["or", "all(applicant.lines, (#.calc.review and #.calc.review))", 0], ["and", "applicant.decision in [6..140]", 1]]}, + {table: "t7", hit: "collect", inputs: [null], outputs: ["line.exposure", "line.discount", "line.health"], rules: [ + ["applicant.decision >= 1.5", "(line.calc.review and applicant.surcharge)", "applicant.rate", "applicant.rate"], + ["50 < (line.days ?? 0)", "applicant.surcharge", "(applicant.decision - applicant.rate)", ""], + ["applicant.price in [35..48]", "line.days != null", "", "applicant.rate"], + ["applicant.dueDate >= d('2025-01-01')", "all(line.employees, #.years != null)", "(line.days ?? 0)", "(min([abs(applicant.decision), 1000]) ^ 1)"], + ["", "line.status == 'closed'", "line.calc.risk", "applicant.price"], + ["line.days != null", "applicant.surcharge", "1000", "(line.days ?? 0)"], + ["", "line.calc.review", "applicant.price", "applicant.decision"], + ]}, + {table: "t8", inputs: ["sum(map(applicant.lines, #.calc.risk))", "applicant.since", "applicant.since"], outputs: ["applicant.bonus", "applicant.level"], rules: [ + ["<= 1000", "", "", "'a'", "0.5"], + ["", "> d('2025-03-20')", ">= d('2000-06-30')", "'Oslo'", "applicant.price"], + ["> 1", "", "", "'DE'", ""], + ["", "", "", "`${applicant.rate}/${applicant.price}`", "(1 * applicant.decision)"], + ]}, + {table: "t9", inputs: ["applicant.since", "line.status", "line.status"], outputs: ["line.eligible"], rules: [ + ["< d('2025-03-20')", "'pending'", "'pending'", "(applicant.level ?? 0)"], + ["", "", "", ""], + ]}, + {match: "line.summary", arms: [["applicant.dueDate.year() <= applicant.decision", "(applicant.bonus ?? '')"], ["", "'retail'"]]}, + {expression: "line.band", value: "(applicant.dueDate < d('2000-06-30') ? line.days : null)"}, + ], + }, + cases: [ + {input: {applicant: {rate: 1.5, since: "2000-01-01", status: "pending", price: 1000, dueDate: "1990-06-15", lines: [{days: 0.25, status: null, employees: [{rate: 0, years: 7.25, insured: true}, {rate: 18, years: -0, insured: true}, {rate: 1000, years: 0.5, insured: false}]}, {days: 1, status: "pending", employees: []}, {days: 5, status: "closed", employees: []}, {days: 99999999999999999999, status: "open", employees: [{rate: 1, years: 0, insured: false}]}, {days: 1, status: "pending", employees: [{rate: 50, years: 3, insured: true}, {rate: 0.5, years: 233, insured: true}]}]}}, goals: ["applicant.decision"], output: {applicant: {decision: 0, dueDate: "1990-06-15", lines: [{days: 0.25, employees: [{insured: true, rate: 0, years: 7.25}, {insured: true, rate: 18, years: 0}, {insured: false, rate: 1000, years: 0.5}], status: null}, {days: 1, employees: [], status: "pending"}, {days: 5, employees: [], status: "closed"}, {days: 99999999999999999999, employees: [{insured: false, rate: 1, years: 0}], status: "open"}, {days: 1, employees: [{insured: true, rate: 50, years: 3}, {insured: true, rate: 0.5, years: 233}], status: "pending"}], price: 1000, rate: 1.5, since: "2000-01-01", status: "pending"}}}, + {input: {applicant: {rate: 1, since: "2025-03-20T10:15:30Z", status: "pending", price: 0, dueDate: "1990-06-15", lines: [{status: "pending", employees: [{rate: 0.25, years: 1}]}]}}, goals: ["line.health"], output: {applicant: {decision: 0, dueDate: "1990-06-15", lines: [{calc: {review: true, risk: 1}, discount: [1, 0], employees: [{rate: 0.25, years: 1}], exposure: [false, true], health: [0, 0], status: "pending"}], price: 0, rate: 1, since: "2025-03-20T10:15:30Z", status: "pending"}}}, + {input: {applicant: {rate: null, since: "2024-02-29", status: "closed", price: 1, dueDate: "2030-12-31", lines: [{days: 3, status: "pending", employees: [{rate: 65, years: 123456789.123, insured: true}, {rate: 3, years: 18, insured: false}, {rate: 0.1, years: 1, insured: true}]}, {days: -0.5, status: "open", employees: []}, {days: 0.1, status: "open", employees: [{rate: 5, years: 1, insured: true}, {rate: 0, years: 10, insured: true}]}, {days: 2, status: "pending", employees: [{rate: 2, years: 1000, insured: false}, {rate: 2.50, years: 408, insured: true}, {rate: 0, years: 99.99, insured: false}]}]}}, goals: ["line.calc.review", "applicant.totals.weighted"], output: "!error: MissingRequiredInputs"}, + {input: {applicant: {rate: 1000, since: "2025-03-20", status: "open", price: 1000, dueDate: "2025-03-20T10:15:30Z", lines: [{days: 18, status: "open", employees: [{rate: 7.25, years: 2, insured: false}, {rate: 7.25, years: null}]}, {days: 3, status: "open", employees: [{rate: 18, years: 7.25}]}]}}, goals: ["applicant.totals.total", "line.health"], output: {applicant: {decision: 143, dueDate: "2025-03-20T10:15:30Z", lines: [{calc: {review: false, risk: 1000}, days: 18, discount: [1000, 18, 1000, 1000, 1000], employees: [{insured: false, rate: 7.25, years: 2}, {rate: 7.25, years: null}], exposure: [false, false, false, false, false], health: [1000, 143, 1000, 18, 143], status: "open"}, {calc: {review: false, risk: 1000}, days: 3, discount: [1000, 3, 1000, 1000, 1000], employees: [{rate: 18, years: 7.25}], exposure: [false, true, false, false, false], health: [1000, 143, 1000, 3, 143], status: "open"}], ok: ["A1", "gold"], price: 1000, rate: 1000, scores: {rank: ["low", "none"]}, since: "2025-03-20", status: "open", surcharge: false, totals: {total: [1, 18]}}}}, + {input: {applicant: {rate: 1000, since: "2000-01-01", status: "closed", price: 5, dueDate: "2000-01-01", lines: []}}, goals: ["line.calc.review", "applicant.scores.rank", "applicant.totals.total"], output: "!error: ExpressionFailed"}, + {input: {applicant: {rate: 50, since: "2030-12-31", status: "closed", price: 18, dueDate: "2025-03-20", lines: [{days: 1000, status: "open", employees: [{rate: 0, years: 0.1, insured: false}]}, {days: 3, status: "open", employees: [{rate: 1000, years: 1000, insured: true}]}, {days: 0.1, status: "open", employees: []}]}}, goals: ["line.discount"], output: {applicant: {decision: 7, dueDate: "2025-03-20", lines: [{calc: {review: false, risk: 18}, days: 1000, discount: [50, -43, 1000, 18, 1000, 18], employees: [{insured: false, rate: 0, years: 0.1}], exposure: [false, true, true, false, true, false], health: [50, 7, 18, 1000, 7], status: "open"}, {calc: {review: false, risk: 18}, days: 3, discount: [50, 3, 18, 1000, 18], employees: [{insured: true, rate: 1000, years: 1000}], exposure: [false, true, false, true, false], health: [50, 7, 18, 3, 7], status: "open"}, {calc: {review: false, risk: 18}, days: 0.1, discount: [50, 0.1, 18, 1000, 18], employees: [], exposure: [false, true, false, true, false], health: [50, 7, 18, 0.1, 7], status: "open"}], price: 18, rate: 50, since: "2030-12-31", status: "closed", surcharge: true}}}, + {input: {applicant: {rate: 5, since: "2025-03-20", status: "pending", price: 0.5, dueDate: "1990-06-15", lines: [{days: 7.25, status: "open", employees: [{rate: 100, insured: false}]}, {days: null, status: "open", employees: [{rate: 123456789.123, years: null, insured: false}, {rate: 1.5, years: 3, insured: true}]}]}}, goals: ["line.calc.risk", "line.health", "applicant.totals.total"], output: {applicant: {decision: 1, dueDate: "1990-06-15", lines: [{calc: {review: false, risk: 0.5}, days: 7.25, discount: [0.5, 1000, 0.5], employees: [{insured: false, rate: 100}], exposure: [false, false, false], health: [0.5, 7.25, 1], status: "open"}, {calc: {review: true, risk: 5}, days: null, discount: [5, 0.5], employees: [{insured: false, rate: 123456789.123, years: null}, {insured: true, rate: 1.5, years: 3}], exposure: [false, true], health: [0.5, 1], status: "open"}], ok: ["A1", "gold"], price: 0.5, rate: 5, scores: {rank: ["low", "none"]}, since: "2025-03-20", status: "pending", surcharge: false, totals: {total: [1, 7.25]}}}}, + [{applicant: {rate: 0.000001, since: "2025-03-20T10:15:30Z", status: "open", price: 100, dueDate: "2025-03-20", lines: [{days: 1e3, status: "closed", employees: [{rate: 5, years: 10, insured: false}, {rate: 0, years: 0.000001, insured: false}, {rate: 3, years: -0, insured: true}]}, {days: 100, status: "open", employees: [{rate: 0.25, years: 0.5, insured: false}]}]}}, {applicant: {decision: 100, dueDate: "2025-03-20", lines: [{band: null, calc: {review: false, risk: 100}, days: 1000, discount: [0.000001, 99.999999, 1000, 100, 1000, 100], eligible: null, employees: [{insured: false, rate: 5, years: 10}, {insured: false, rate: 0, years: 0.000001}, {insured: true, rate: 3, years: 0}], exposure: [false, true, true, true, true, false], health: [0.000001, 100, 100, 1000, 100], status: "closed", summary: "retail"}, {band: null, calc: {review: false, risk: 100}, days: 100, discount: [0.000001, 99.999999, 100, 100, 1000, 100], eligible: null, employees: [{insured: false, rate: 0.25, years: 0.5}], exposure: [false, true, true, false, true, false], health: [0.000001, 100, 100, 100, 100], status: "open", summary: "retail"}], ok: ["A1", "gold"], price: 100, rate: 0.000001, scores: {rank: ["low", "none"]}, since: "2025-03-20T10:15:30Z", status: "open", surcharge: true, totals: {total: [1, 1000], weighted: [{band: null, calc: {review: false, risk: 100}, days: 1000, discount: [0.000001, 99.999999, 1000, 100, 1000, 100], eligible: null, employees: [{insured: false, rate: 5, years: 10}, {insured: false, rate: 0, years: 0.000001}, {insured: true, rate: 3, years: 0}], exposure: [false, true, true, true, true, false], health: [0.000001, 100, 100, 1000, 100], status: "closed", summary: "retail"}, {band: null, calc: {review: false, risk: 100}, days: 100, discount: [0.000001, 99.999999, 100, 100, 1000, 100], eligible: null, employees: [{insured: false, rate: 0.25, years: 0.5}], exposure: [false, true, true, false, true, false], health: [0.000001, 100, 100, 100, 100], status: "open", summary: "retail"}]}}}], + {input: {applicant: {rate: 1, since: "2025-03-20", status: "closed", price: 1, dueDate: "2025-03-20T10:15:30Z", lines: [{days: 0.5, employees: [{rate: 5, years: 50, insured: true}]}]}}, goals: ["applicant.totals.weighted", "applicant.level", "applicant.decision"], output: {applicant: {bonus: "a", decision: 0, dueDate: "2025-03-20T10:15:30Z", level: 0.5, lines: [{calc: {risk: 1}, days: 0.5, employees: [{insured: true, rate: 5, years: 50}]}], price: 1, rate: 1, since: "2025-03-20", status: "closed", totals: {weighted: [{calc: {risk: 1}, days: 0.5, employees: [{insured: true, rate: 5, years: 50}]}]}}}}, + {input: {applicant: {rate: -500, since: "2024-02-29", status: "open", price: 0, dueDate: "2000-01-01", lines: [{days: 18, status: "open", employees: []}, {days: 100, status: "open", employees: []}, {days: 7.25, status: "open", employees: [{rate: -0.5, years: -1, insured: true}]}]}}, goals: ["applicant.bonus"], output: {applicant: {bonus: "a", dueDate: "2000-01-01", level: 0.5, lines: [{calc: {risk: 0}, days: 18, employees: [], status: "open"}, {calc: {risk: 0}, days: 100, employees: [], status: "open"}, {calc: {risk: 0}, days: 7.25, employees: [{insured: true, rate: -0.5, years: -1}], status: "open"}], price: 0, rate: -500, since: "2024-02-29", status: "open"}}}, + {input: {applicant: {rate: 3, since: "2025-03-20T10:15:30Z", status: "closed", price: 0.000001, dueDate: "2025-03-20T10:15:30Z", lines: [{days: 1, status: "pending", employees: [{rate: 1}, {rate: 0.1, insured: null}, {rate: 0.000001, insured: true}]}, {status: "closed", employees: [{rate: 1, years: 1000000, insured: null}, {rate: 50, years: 1000}]}]}}, goals: ["line.calc.review"], output: {applicant: {dueDate: "2025-03-20T10:15:30Z", lines: [{calc: {review: false}, days: 1, employees: [{rate: 1}, {insured: null, rate: 0.1}, {insured: true, rate: 0.000001}], status: "pending"}, {calc: {review: true}, employees: [{insured: null, rate: 1, years: 1000000}, {rate: 50, years: 1000}], status: "closed"}], price: 0.000001, rate: 3, since: "2025-03-20T10:15:30Z", status: "closed"}}}, + {input: {applicant: {rate: 1, since: "1990-06-15", status: "open", price: 5, dueDate: "1990-06-15", lines: [{days: 1e3, status: "pending", employees: [{rate: 2.50, years: 1000000, insured: true}, {rate: 7.25, years: 1, insured: true}]}, {days: 1, status: "open", employees: [{rate: 99.99, years: 50, insured: true}]}]}}, goals: ["applicant.decision"], output: {applicant: {decision: 0, dueDate: "1990-06-15", lines: [{days: 1000, employees: [{insured: true, rate: 2.50, years: 1000000}, {insured: true, rate: 7.25, years: 1}], status: "pending"}, {days: 1, employees: [{insured: true, rate: 99.99, years: 50}], status: "open"}], price: 5, rate: 1, since: "1990-06-15", status: "open"}}}, + ], +} + +// seed 351700 (attempt 0) +{ + name: "goals 18: tenant/members/payments: 2 assertion, 3 expression; 2 root, 5 per-member, 0 top-level computed", + policy: { + models: {tenant: {years: "number", region: "string", flagged: "boolean", status: "string(open|closed|pending)?", code: "string?", tier: "string(gold|silver|bronze)", members: "member[]"}, member: {rate: "number", tier: "string(gold|silver|bronze)?", verified: "boolean", payments: "payment[]?"}, payment: {price: "number", insured: "boolean", days: "number"}}, + blocks: [ + {assertion: "member.calc.eligible", conditions: ["tenant.years != member.rate", ["or", "(member.verified and tenant.flagged)", 0], ["and", "matches(tenant.region, 'a')", 2], ["and", "-(tenant.years) >= tenant.years", 0], ["or", "(member.verified or member.verified)", 2]]}, + {expression: "member.calc.capped", value: "filter((member.payments ?? []), #.price in (23..30])"}, + {expression: "member.health", value: "{a: number(string((tenant.years / -6))), s: (sum(map((member.payments ?? []), #.days)) / 3)}"}, + {expression: "tenant.grade", value: "string(tenant.years)"}, + {assertion: "tenant.meta.bonus", conditions: [["or", "tenant.region in ['VIP', 'DE']", 1]]}, + ], + }, + cases: [ + {input: {tenant: {years: 18, region: "é ü", flagged: false, code: "DE", tier: "bronze", members: [{rate: 0.1, verified: false}]}}, goals: ["member.health"], output: {tenant: {code: "DE", flagged: false, members: [{health: {a: -3, s: 0}, rate: 0.1, verified: false}], region: "é ü", tier: "bronze", years: 18}}}, + {input: {tenant: {years: 1e3, region: "", flagged: null, status: "open", code: "a-b-c", tier: "gold", members: [{rate: 100, tier: "bronze", verified: false, payments: [{price: 0.000001, insured: true, days: 411}]}, {rate: 7.25, tier: "gold", verified: false, payments: [{price: 7.25, insured: false, days: 0}, {price: 0.5, insured: false, days: -0.01}]}, {rate: 2.50, tier: "gold", verified: true, payments: [{price: 2, insured: false, days: 0.5}, {price: 5, insured: false, days: 2.50}, {price: 0.1, insured: true, days: 99.99}]}, {rate: 2.50, tier: "silver", verified: false}]}}, goals: ["tenant.meta.bonus"], output: {tenant: {code: "a-b-c", flagged: null, members: [{payments: [{days: 411, insured: true, price: 0.000001}], rate: 100, tier: "bronze", verified: false}, {payments: [{days: 0, insured: false, price: 7.25}, {days: -0.01, insured: false, price: 0.5}], rate: 7.25, tier: "gold", verified: false}, {payments: [{days: 0.5, insured: false, price: 2}, {days: 2.50, insured: false, price: 5}, {days: 99.99, insured: true, price: 0.1}], rate: 2.50, tier: "gold", verified: true}, {rate: 2.50, tier: "silver", verified: false}], meta: {bonus: false}, region: "", status: "open", tier: "gold", years: 1000}}}, + {input: {tenant: {years: 1000000, region: "DE", flagged: true, status: "closed", code: "日本", tier: "silver", members: [{rate: 171, tier: "gold", verified: false, payments: [{price: 0, insured: true, days: 2.50}, {price: 99999999999999999999, insured: true, days: -0.01}, {price: -0.01, insured: true, days: 18}]}, {rate: 1000, tier: "gold", verified: true, payments: [{price: 1000, insured: true, days: 0}, {price: 10, insured: false, days: 250}]}, {rate: -500, tier: "gold", verified: true, payments: [{price: 7.25, insured: true, days: 123456789.123}, {price: 18, insured: true, days: 10}]}, {rate: 5, tier: "silver", verified: true, payments: [{price: 123456789.123, insured: true, days: 7.25}, {price: 250, insured: true, days: -500}]}, {rate: 1, tier: "gold", verified: true, payments: [{price: 0.000001, insured: true, days: 1000}]}]}}, goals: ["member.health", "member.calc.eligible", "tenant.meta.bonus"], output: {tenant: {code: "日本", flagged: true, members: [{calc: {eligible: false}, health: {a: -166666.66666666666666666666667, s: 6.83}, payments: [{days: 2.50, insured: true, price: 0}, {days: -0.01, insured: true, price: 99999999999999999999}, {days: 18, insured: true, price: -0.01}], rate: 171, tier: "gold", verified: false}, {calc: {eligible: false}, health: {a: -166666.66666666666666666666667, s: 83.33333333333333333333333333}, payments: [{days: 0, insured: true, price: 1000}, {days: 250, insured: false, price: 10}], rate: 1000, tier: "gold", verified: true}, {calc: {eligible: false}, health: {a: -166666.66666666666666666666667, s: 41152266.374333333333333333333}, payments: [{days: 123456789.123, insured: true, price: 7.25}, {days: 10, insured: true, price: 18}], rate: -500, tier: "gold", verified: true}, {calc: {eligible: false}, health: {a: -166666.66666666666666666666667, s: -164.25}, payments: [{days: 7.25, insured: true, price: 123456789.123}, {days: -500, insured: true, price: 250}], rate: 5, tier: "silver", verified: true}, {calc: {eligible: false}, health: {a: -166666.66666666666666666666667, s: 333.33333333333333333333333333}, payments: [{days: 1000, insured: true, price: 0.000001}], rate: 1, tier: "gold", verified: true}], meta: {bonus: true}, region: "DE", status: "closed", tier: "silver", years: 1000000}}}, + {input: {tenant: {years: -1, region: "abc", flagged: false, status: "pending", code: "VIP", tier: "bronze", members: [{rate: 18, tier: "silver", verified: true}]}}, goals: ["tenant.meta.bonus", "member.calc.capped"], output: {tenant: {code: "VIP", flagged: false, members: [{calc: {capped: []}, rate: 18, tier: "silver", verified: true}], meta: {bonus: false}, region: "abc", status: "pending", tier: "bronze", years: -1}}}, + {input: {tenant: {years: 5, region: "NL", flagged: true, status: "closed", code: "-", tier: "silver", members: [{rate: 1e3, tier: "silver", verified: false, payments: [{price: -0.01, insured: false, days: 1000000}, {price: 1000000, insured: true, days: 123456789.123}]}, {rate: 0, tier: "gold", verified: false, payments: null}, {rate: 1, tier: "silver", verified: false, payments: []}, {rate: 123456789.123, tier: "gold", verified: false, payments: null}]}}, goals: ["member.calc.capped", "tenant.meta.bonus"], output: {tenant: {code: "-", flagged: true, members: [{calc: {capped: []}, payments: [{days: 1000000, insured: false, price: -0.01}, {days: 123456789.123, insured: true, price: 1000000}], rate: 1000, tier: "silver", verified: false}, {calc: {capped: []}, payments: null, rate: 0, tier: "gold", verified: false}, {calc: {capped: []}, payments: [], rate: 1, tier: "silver", verified: false}, {calc: {capped: []}, payments: null, rate: 123456789.123, tier: "gold", verified: false}], meta: {bonus: false}, region: "NL", status: "closed", tier: "silver", years: 5}}}, + {input: {tenant: {years: -0.5, region: "12", flagged: true, status: "open", code: "3.5", tier: "gold", members: [{rate: 1, tier: "gold", verified: false, payments: null}, {rate: 1, tier: "silver", verified: false, payments: [{price: -500, insured: false, days: -0.01}, {price: -0, insured: false, days: 2.50}, {price: 123456789.123, insured: false, days: 65}]}, {rate: 10, tier: "gold", verified: false, payments: null}, {rate: 1e3, tier: "bronze", verified: true, payments: []}]}}, goals: ["member.health", "tenant.grade"], output: {tenant: {code: "3.5", flagged: true, grade: "-0.5", members: [{health: {a: 0.0833333333333333333333333333, s: 0}, payments: null, rate: 1, tier: "gold", verified: false}, {health: {a: 0.0833333333333333333333333333, s: 22.496666666666666666666666667}, payments: [{days: -0.01, insured: false, price: -500}, {days: 2.50, insured: false, price: 0}, {days: 65, insured: false, price: 123456789.123}], rate: 1, tier: "silver", verified: false}, {health: {a: 0.0833333333333333333333333333, s: 0}, payments: null, rate: 10, tier: "gold", verified: false}, {health: {a: 0.0833333333333333333333333333, s: 0}, payments: [], rate: 1000, tier: "bronze", verified: true}], region: "12", status: "open", tier: "gold", years: -0.5}}}, + {input: {tenant: {years: 2, region: "é ü", flagged: true, status: "open", code: "VIP", tier: "gold", members: [{rate: 0.1, tier: "bronze", verified: false, payments: [{price: 7.25, insured: false, days: 99.99}, {price: 1e3, insured: true, days: -0}, {price: 65, insured: false, days: 250}]}, {rate: 18, tier: "gold", verified: true, payments: [{price: 0.5, insured: true, days: 1}]}]}}, goals: ["member.calc.eligible", "member.health", "tenant.grade"], output: {tenant: {code: "VIP", flagged: true, grade: "2", members: [{calc: {eligible: false}, health: {a: -0.3333333333333333333333333333, s: 116.66333333333333333333333333}, payments: [{days: 99.99, insured: false, price: 7.25}, {days: 0, insured: true, price: 1000}, {days: 250, insured: false, price: 65}], rate: 0.1, tier: "bronze", verified: false}, {calc: {eligible: false}, health: {a: -0.3333333333333333333333333333, s: 0.3333333333333333333333333333}, payments: [{days: 1, insured: true, price: 0.5}], rate: 18, tier: "gold", verified: true}], region: "é ü", status: "open", tier: "gold", years: 2}}}, + {input: {tenant: {years: -0.01, region: "日本", flagged: true, status: "pending", code: "US", tier: "silver", members: []}}, goals: ["member.calc.capped"], output: {tenant: {code: "US", flagged: true, members: [], region: "日本", status: "pending", tier: "silver", years: -0.01}}}, + {input: {tenant: {years: 250, region: "DE", flagged: true, code: "12", tier: "gold", members: [{rate: 2, tier: "silver", verified: false, payments: [{price: 2.50, insured: false, days: 426}]}, {rate: 10, tier: "silver", verified: false}]}}, goals: ["tenant.grade"], output: {tenant: {code: "12", flagged: true, grade: "250", members: [{payments: [{days: 426, insured: false, price: 2.50}], rate: 2, tier: "silver", verified: false}, {rate: 10, tier: "silver", verified: false}], region: "DE", tier: "gold", years: 250}}}, + {input: {tenant: {years: 2.50, region: "NL", flagged: false, status: "closed", code: "3.5", tier: "bronze", members: [{rate: 123456789.123, tier: "gold", verified: true}]}}, goals: ["member.calc.eligible", "member.calc.capped"], output: {tenant: {code: "3.5", flagged: false, members: [{calc: {capped: [], eligible: false}, rate: 123456789.123, tier: "gold", verified: true}], region: "NL", status: "closed", tier: "bronze", years: 2.50}}}, + {input: {tenant: {years: 248, region: "retail", flagged: false, status: "open", tier: "bronze", members: [{rate: 99.99, tier: "bronze", verified: false, payments: [{price: -0.01, insured: false, days: 1000000}, {price: 5, insured: true, days: 1e3}, {price: 99.99, insured: true, days: -500}]}, {rate: 99999999999999999999, tier: "silver", verified: true, payments: [{price: 10, insured: true, days: 65}, {price: -0.5, insured: false, days: 5}]}, {rate: -0.5, verified: false, payments: [{price: -0, insured: false, days: 0.1}, {price: 1000000, insured: true, days: 5}]}, {rate: 2.50, tier: "gold", verified: true, payments: [{price: 123456789.123, insured: true, days: 1}, {price: 250, insured: true, days: 0.1}]}, {rate: 250, tier: "bronze", verified: false, payments: [{price: 250, insured: true, days: 123456789.123}, {price: 18, insured: false, days: 65}, {price: 0.1, insured: false, days: 250}]}]}}, goals: ["tenant.meta.bonus", "tenant.grade"], output: {tenant: {flagged: false, grade: "248", members: [{payments: [{days: 1000000, insured: false, price: -0.01}, {days: 1000, insured: true, price: 5}, {days: -500, insured: true, price: 99.99}], rate: 99.99, tier: "bronze", verified: false}, {payments: [{days: 65, insured: true, price: 10}, {days: 5, insured: false, price: -0.5}], rate: 99999999999999999999, tier: "silver", verified: true}, {payments: [{days: 0.1, insured: false, price: 0}, {days: 5, insured: true, price: 1000000}], rate: -0.5, verified: false}, {payments: [{days: 1, insured: true, price: 123456789.123}, {days: 0.1, insured: true, price: 250}], rate: 2.50, tier: "gold", verified: true}, {payments: [{days: 123456789.123, insured: true, price: 250}, {days: 65, insured: false, price: 18}, {days: 250, insured: false, price: 0.1}], rate: 250, tier: "bronze", verified: false}], meta: {bonus: false}, region: "retail", status: "open", tier: "bronze", years: 248}}}, + {input: {tenant: {years: 0, region: "3.5", flagged: true, status: "pending", code: "a", tier: "bronze", members: [{rate: 5, tier: "gold", verified: true, payments: null}, {rate: 0.000001, tier: "gold", verified: false}, {rate: -1, tier: "bronze", verified: false, payments: [{price: 99.99, insured: false, days: 7.25}]}, {rate: 0.000001, tier: "gold", verified: false, payments: []}]}}, goals: ["tenant.meta.bonus", "member.health", "member.calc.eligible"], output: {tenant: {code: "a", flagged: true, members: [{calc: {eligible: true}, health: {a: 0, s: 0}, payments: null, rate: 5, tier: "gold", verified: true}, {calc: {eligible: false}, health: {a: 0, s: 0}, rate: 0.000001, tier: "gold", verified: false}, {calc: {eligible: false}, health: {a: 0, s: 2.4166666666666666666666666667}, payments: [{days: 7.25, insured: false, price: 99.99}], rate: -1, tier: "bronze", verified: false}, {calc: {eligible: false}, health: {a: 0, s: 0}, payments: [], rate: 0.000001, tier: "gold", verified: false}], meta: {bonus: false}, region: "3.5", status: "pending", tier: "bronze", years: 0}}}, + {input: {tenant: {years: 0, region: "DE", flagged: true, status: null, code: null, tier: "gold", members: [{rate: 100, tier: "silver", verified: false}, {rate: 123456789.123, tier: "bronze", verified: true, payments: [{price: -0.01, insured: true, days: 1000000}, {price: 1000000, insured: true, days: 250}]}, {rate: 123456789.123, verified: true, payments: [{price: 0.1, insured: true, days: 1}, {price: 100, insured: false, days: 2.50}]}]}}, goals: ["tenant.grade", "member.calc.eligible"], output: {tenant: {code: null, flagged: true, grade: "0", members: [{calc: {eligible: false}, rate: 100, tier: "silver", verified: false}, {calc: {eligible: true}, payments: [{days: 1000000, insured: true, price: -0.01}, {days: 250, insured: true, price: 1000000}], rate: 123456789.123, tier: "bronze", verified: true}, {calc: {eligible: true}, payments: [{days: 1, insured: true, price: 0.1}, {days: 2.50, insured: false, price: 100}], rate: 123456789.123, verified: true}], region: "DE", status: null, tier: "gold", years: 0}}}, + {input: {tenant: {years: 99999999999999999999, region: "12", flagged: false, status: "open", code: "x-y", tier: "gold", members: [{rate: 261, tier: "gold", verified: false, payments: []}, {rate: 99.99, tier: "bronze", verified: false, payments: [{price: -0, insured: false, days: -0.01}, {price: 0.000001, insured: false, days: 1e3}, {price: 123456789.123, insured: false, days: 1e3}]}]}}, goals: ["tenant.meta.bonus"], output: {tenant: {code: "x-y", flagged: false, members: [{payments: [], rate: 261, tier: "gold", verified: false}, {payments: [{days: -0.01, insured: false, price: 0}, {days: 1000, insured: false, price: 0.000001}, {days: 1000, insured: false, price: 123456789.123}], rate: 99.99, tier: "bronze", verified: false}], meta: {bonus: false}, region: "12", status: "open", tier: "gold", years: 99999999999999999999}}}, + {input: {tenant: {years: 171, region: "DE", flagged: true, code: "Oslo", tier: "gold", members: [{rate: 5, verified: false, payments: [{price: 92, insured: true, days: 1e3}, {price: 300, insured: false, days: 100}]}, {rate: 99999999999999999999, tier: null, verified: true}, {rate: -0.01, tier: "gold", verified: false}, {rate: 99.99, verified: false, payments: null}, {rate: 2.50, verified: false, payments: [{price: -500, insured: false, days: 5}]}, {rate: 99.99, verified: false, payments: [{price: 65, insured: false, days: 123456789.123}, {price: 2, insured: false, days: 1e3}]}, {rate: -1, tier: "gold", verified: true, payments: [{price: 0.1, insured: false, days: 1}, {price: 2, insured: true, days: 1}, {price: 0.5, insured: false, days: -0.5}]}, {rate: 5, tier: null, verified: true, payments: [{price: -1, insured: false, days: -0.5}]}, {rate: 7.25, tier: "gold", verified: false}, {rate: -0.01, tier: "gold", verified: false, payments: [{price: 1e3, insured: false, days: 1000}, {price: 0.000001, insured: true, days: 1}, {price: -1, insured: true, days: -1}]}]}}, goals: ["tenant.grade", "member.health", "member.calc.capped"], output: {tenant: {code: "Oslo", flagged: true, grade: "171", members: [{calc: {capped: []}, health: {a: -28.50, s: 366.66666666666666666666666667}, payments: [{days: 1000, insured: true, price: 92}, {days: 100, insured: false, price: 300}], rate: 5, verified: false}, {calc: {capped: []}, health: {a: -28.50, s: 0}, rate: 99999999999999999999, tier: null, verified: true}, {calc: {capped: []}, health: {a: -28.50, s: 0}, rate: -0.01, tier: "gold", verified: false}, {calc: {capped: []}, health: {a: -28.50, s: 0}, payments: null, rate: 99.99, verified: false}, {calc: {capped: []}, health: {a: -28.50, s: 1.6666666666666666666666666667}, payments: [{days: 5, insured: false, price: -500}], rate: 2.50, verified: false}, {calc: {capped: []}, health: {a: -28.50, s: 41152596.374333333333333333333}, payments: [{days: 123456789.123, insured: false, price: 65}, {days: 1000, insured: false, price: 2}], rate: 99.99, verified: false}, {calc: {capped: []}, health: {a: -28.50, s: 0.5}, payments: [{days: 1, insured: false, price: 0.1}, {days: 1, insured: true, price: 2}, {days: -0.5, insured: false, price: 0.5}], rate: -1, tier: "gold", verified: true}, {calc: {capped: []}, health: {a: -28.50, s: -0.1666666666666666666666666667}, payments: [{days: -0.5, insured: false, price: -1}], rate: 5, tier: null, verified: true}, {calc: {capped: []}, health: {a: -28.50, s: 0}, rate: 7.25, tier: "gold", verified: false}, {calc: {capped: []}, health: {a: -28.50, s: 333.33333333333333333333333333}, payments: [{days: 1000, insured: false, price: 1000}, {days: 1, insured: true, price: 0.000001}, {days: -1, insured: true, price: -1}], rate: -0.01, tier: "gold", verified: false}], region: "DE", tier: "gold", years: 171}}}, + {input: {tenant: {years: -1, region: "a", flagged: false, tier: "gold", members: [{rate: 141, tier: "gold", verified: false}, {rate: 65, tier: "gold", verified: true, payments: [{price: 99.99, insured: true, days: -0.01}, {price: 18, insured: true, days: -0.5}]}]}}, goals: ["member.calc.capped", "tenant.meta.bonus", "member.calc.eligible"], output: {tenant: {flagged: false, members: [{calc: {capped: [], eligible: false}, rate: 141, tier: "gold", verified: false}, {calc: {capped: [], eligible: true}, payments: [{days: -0.01, insured: true, price: 99.99}, {days: -0.5, insured: true, price: 18}], rate: 65, tier: "gold", verified: true}], meta: {bonus: false}, region: "a", tier: "gold", years: -1}}}, + {input: {tenant: {years: -0.5, region: "x-y", flagged: true, status: null, code: null, tier: "gold", members: []}}, goals: ["member.calc.capped"], output: {tenant: {code: null, flagged: true, members: [], region: "x-y", status: null, tier: "gold", years: -0.5}}}, + {input: {tenant: {years: 1000000, region: "a", flagged: true, status: "open", code: "a", tier: "bronze", members: [{rate: 1000000, tier: "bronze", verified: true, payments: [{price: -1, insured: false, days: 0.5}, {price: 100, insured: true, days: 99999999999999999999}]}, {rate: 250, tier: "silver", verified: true, payments: [{price: 99999999999999999999, insured: true, days: -0.01}, {price: -0.5, insured: false, days: 99999999999999999999}]}, {rate: 0.5, tier: "silver", verified: false, payments: []}, {rate: 2, tier: "bronze", verified: true, payments: null}, {rate: 250, tier: "gold", verified: true}]}}, goals: ["tenant.grade"], output: {tenant: {code: "a", flagged: true, grade: "1000000", members: [{payments: [{days: 0.5, insured: false, price: -1}, {days: 99999999999999999999, insured: true, price: 100}], rate: 1000000, tier: "bronze", verified: true}, {payments: [{days: -0.01, insured: true, price: 99999999999999999999}, {days: 99999999999999999999, insured: false, price: -0.5}], rate: 250, tier: "silver", verified: true}, {payments: [], rate: 0.5, tier: "silver", verified: false}, {payments: null, rate: 2, tier: "bronze", verified: true}, {rate: 250, tier: "gold", verified: true}], region: "a", status: "open", tier: "bronze", years: 1000000}}}, + [{tenant: {years: -0, region: "12", flagged: false, status: "open", code: "日本", tier: "gold", members: [{rate: 100, tier: "gold", verified: true, payments: [{price: 10, insured: true, days: 65}, {price: 65, insured: false, days: 1e3}]}, {rate: 2.50, tier: "gold", verified: false, payments: [{price: 65, insured: false, days: 18}, {price: 5, insured: true, days: 2.50}, {price: 2.50, insured: false, days: -0.01}]}]}}, {tenant: {code: "日本", flagged: false, grade: "0", members: [{calc: {capped: [], eligible: false}, health: {a: 0, s: 355}, payments: [{days: 65, insured: true, price: 10}, {days: 1000, insured: false, price: 65}], rate: 100, tier: "gold", verified: true}, {calc: {capped: [], eligible: false}, health: {a: 0, s: 6.83}, payments: [{days: 18, insured: false, price: 65}, {days: 2.50, insured: true, price: 5}, {days: -0.01, insured: false, price: 2.50}], rate: 2.50, tier: "gold", verified: false}], meta: {bonus: false}, region: "12", status: "open", tier: "gold", years: 0}}], + {input: {tenant: {years: 18, region: "gold", flagged: false, status: "open", code: "DE", tier: "silver", members: [{rate: 1, tier: "silver", verified: true, payments: [{price: -0.5, insured: false, days: 0}, {price: 1000000, insured: true, days: 250}]}, {rate: -0, tier: "silver", verified: true, payments: [{price: -0.01, insured: false, days: 99.99}]}, {rate: 250, tier: "bronze", verified: true, payments: [{price: 250, insured: true, days: 1000}]}]}}, goals: ["tenant.meta.bonus", "tenant.grade"], output: {tenant: {code: "DE", flagged: false, grade: "18", members: [{payments: [{days: 0, insured: false, price: -0.5}, {days: 250, insured: true, price: 1000000}], rate: 1, tier: "silver", verified: true}, {payments: [{days: 99.99, insured: false, price: -0.01}], rate: 0, tier: "silver", verified: true}, {payments: [{days: 1000, insured: true, price: 250}], rate: 250, tier: "bronze", verified: true}], meta: {bonus: false}, region: "gold", status: "open", tier: "silver", years: 18}}}, + {input: {tenant: {years: -500, region: "VIP", flagged: false, status: "open", code: "12", tier: "gold", members: [{rate: 10, tier: "silver", verified: true, payments: []}, {rate: 2, tier: "gold", verified: false}, {rate: 99999999999999999999, tier: "gold", verified: true, payments: null}]}}, goals: ["member.calc.eligible"], output: {tenant: {code: "12", flagged: false, members: [{calc: {eligible: false}, payments: [], rate: 10, tier: "silver", verified: true}, {calc: {eligible: false}, rate: 2, tier: "gold", verified: false}, {calc: {eligible: false}, payments: null, rate: 99999999999999999999, tier: "gold", verified: true}], region: "VIP", status: "open", tier: "gold", years: -500}}}, + {input: {tenant: {years: 100, region: "", flagged: true, status: "open", code: "a", tier: "silver", members: [{rate: -0, tier: "gold", verified: true, payments: [{price: 10, insured: false, days: 2.50}, {price: 100, insured: false, days: 7.25}, {price: 97, insured: true, days: 2.50}]}, {rate: 1000000, tier: "gold", verified: true, payments: [{price: 1000, insured: false, days: 2.50}, {price: 2, insured: false, days: 0.1}]}], extraField: "x"}}, goals: ["member.health", "member.calc.eligible"], output: {tenant: {code: "a", extraField: "x", flagged: true, members: [{calc: {eligible: false}, health: {a: -16.666666666666666666666666667, s: 4.0833333333333333333333333333}, payments: [{days: 2.50, insured: false, price: 10}, {days: 7.25, insured: false, price: 100}, {days: 2.50, insured: true, price: 97}], rate: 0, tier: "gold", verified: true}, {calc: {eligible: false}, health: {a: -16.666666666666666666666666667, s: 0.8666666666666666666666666667}, payments: [{days: 2.50, insured: false, price: 1000}, {days: 0.1, insured: false, price: 2}], rate: 1000000, tier: "gold", verified: true}], region: "", status: "open", tier: "silver", years: 100}}}, + [{tenant: {years: 0, region: "abc", flagged: true, status: "closed", code: "x-y", tier: "bronze", members: [{rate: 2, tier: "bronze", verified: true, payments: [{price: 0.000001, insured: true, days: 18}, {price: 1e3, insured: true, days: 65}, {price: -1, insured: true, days: 250}]}, {rate: 1e3, tier: "silver", verified: false, payments: [{price: 1, insured: true, days: 5}, {price: 10, insured: false, days: 7.25}, {price: 1000000, insured: true, days: 1}]}, {rate: 100, tier: "gold", verified: false, payments: [{price: 100, insured: true, days: 287}, {price: 1000000, insured: true, days: 10}]}, {rate: 18, verified: true}, {rate: 0, tier: "bronze", verified: false, payments: [{price: 486, insured: true, days: -0.5}, {price: 7.25, insured: true, days: -0}]}, {rate: -0.01, verified: false, payments: [{price: 18, insured: false, days: 1}]}, {rate: 123456789.123, tier: null, verified: false, payments: [{price: 99.99, insured: false, days: 1000}, {price: -0.01, insured: false, days: 1}]}, {rate: 100, tier: "gold", verified: true, payments: [{price: 99999999999999999999, insured: false, days: 100}]}]}}, {tenant: {code: "x-y", flagged: true, grade: "0", members: [{calc: {capped: [], eligible: true}, health: {a: 0, s: 111}, payments: [{days: 18, insured: true, price: 0.000001}, {days: 65, insured: true, price: 1000}, {days: 250, insured: true, price: -1}], rate: 2, tier: "bronze", verified: true}, {calc: {capped: [], eligible: false}, health: {a: 0, s: 4.4166666666666666666666666667}, payments: [{days: 5, insured: true, price: 1}, {days: 7.25, insured: false, price: 10}, {days: 1, insured: true, price: 1000000}], rate: 1000, tier: "silver", verified: false}, {calc: {capped: [], eligible: false}, health: {a: 0, s: 99}, payments: [{days: 287, insured: true, price: 100}, {days: 10, insured: true, price: 1000000}], rate: 100, tier: "gold", verified: false}, {calc: {capped: [], eligible: true}, health: {a: 0, s: 0}, rate: 18, verified: true}, {calc: {capped: [], eligible: false}, health: {a: 0, s: -0.1666666666666666666666666667}, payments: [{days: -0.5, insured: true, price: 486}, {days: 0, insured: true, price: 7.25}], rate: 0, tier: "bronze", verified: false}, {calc: {capped: [], eligible: false}, health: {a: 0, s: 0.3333333333333333333333333333}, payments: [{days: 1, insured: false, price: 18}], rate: -0.01, verified: false}, {calc: {capped: [], eligible: false}, health: {a: 0, s: 333.66666666666666666666666667}, payments: [{days: 1000, insured: false, price: 99.99}, {days: 1, insured: false, price: -0.01}], rate: 123456789.123, tier: null, verified: false}, {calc: {capped: [], eligible: true}, health: {a: 0, s: 33.333333333333333333333333333}, payments: [{days: 100, insured: false, price: 99999999999999999999}], rate: 100, tier: "gold", verified: true}], meta: {bonus: false}, region: "abc", status: "closed", tier: "bronze", years: 0}}], + {input: {tenant: {years: true, region: "abc", flagged: false, status: "open", code: "Oslo", tier: "gold", members: [{rate: -0.01, tier: "silver", verified: true, payments: [{price: 0, insured: false, days: 99999999999999999999}]}, {rate: 10, tier: "gold", verified: true, payments: [{price: 393, insured: false, days: 65}, {price: 99999999999999999999, insured: false, days: 5}]}, {rate: 7.25, tier: "bronze", verified: false, payments: null}]}}, goals: ["member.calc.eligible", "member.health", "tenant.meta.bonus"], output: "!error: InputValidationFailed"}, + {input: {tenant: {years: -0.01, region: "DE", flagged: true, status: "closed", code: "DE", tier: "bronze", members: [{rate: 1e3, tier: "bronze", verified: false, payments: null}, {rate: 250, tier: "gold", verified: true, payments: [{price: 123456789.123, insured: false, days: 1000000}, {price: 65, insured: true, days: -0}]}], extraField: {nested: true}}}, goals: ["member.calc.eligible", "member.calc.capped"], output: {tenant: {code: "DE", extraField: {nested: true}, flagged: true, members: [{calc: {capped: [], eligible: false}, payments: null, rate: 1000, tier: "bronze", verified: false}, {calc: {capped: [], eligible: true}, payments: [{days: 1000000, insured: false, price: 123456789.123}, {days: 0, insured: true, price: 65}], rate: 250, tier: "gold", verified: true}], region: "DE", status: "closed", tier: "bronze", years: -0.01}}}, + ], +} + +// seed 351800 (attempt 0) +{ + name: "goals 19: applicant/loans: 1 assertion, 4 expression, 1 match, 2 table; 0 root, 10 per-member, 0 top-level computed", + policy: { + models: {applicant: {qty: "number?", limit: "number?", plan: "string(basic|plus|premium|trial)?", loans: "loan[]?"}, loan: {balance: "number?", flagged: "boolean"}}, + globals: {settings: {threshold: "number"}}, + blocks: [ + {table: "t6", inputs: ["loan.meta.surcharge", "(min(map((applicant.loans ?? []), trunc(#.review))) ?? 0)", "threshold"], outputs: ["loan.risk", "loan.fee", "loan.share[]"], rules: [ + ["<= 5", "< 5", "2", "(max(map((applicant.loans ?? []), (#.margin ? (#.balance ?? 0) : (#.balance ?? 0)))) ?? 0)", "'retail'", "loan.margin"], + ["", "", "100", "50", "'gold'", "loan.bonus"], + ["0.25, 50", "[50..493]", "", "threshold", "`${(applicant.limit ?? 0)}/${loan.flagged}`", "(loan.bonus and loan.bonus)"], + ["", "0, 1.5", "", "loan.meta.surcharge", "'x'", "(loan.meta.adjusted ?? false)"], + ["", "", "", "(loan.balance ?? 0)", "'none'", ""], + ]}, + {expression: "loan.points", value: "string(-(loan.review))"}, + {expression: "loan.meta.surcharge", value: "((loan.balance ?? 0) + (applicant.qty ?? 0))"}, + {match: "loan.margin", arms: [["(loan.flagged and loan.flagged)", "not ((applicant.limit ?? 0) in (18..75))"], ["", "loan.flagged"]]}, + {expression: "loan.segment", value: "loan.meta.adjusted"}, + {table: "t2", inputs: ["applicant.limit"], outputs: ["loan.meta.adjusted"], rules: [ + ["2, 50", "loan.margin"], + ["0.25, 10", ""], + ["", "loan.flagged"], + ]}, + {assertion: "loan.bonus", conditions: [["or", "(applicant.plan ?? '') in ['premium', 'trial']", 0]]}, + {expression: "loan.review", value: "(number(string((threshold % (abs(threshold) + 1)))) * loan.meta.surcharge)"}, + ], + }, + cases: [ + {input: {threshold: 0.5, applicant: {qty: 0}}, goals: ["loan.risk"], output: {applicant: {qty: 0}, threshold: 0.5}}, + [{threshold: 0.5, applicant: {qty: null, plan: "trial", loans: [{balance: 99.99, flagged: false}, {balance: null, flagged: false}]}}, {applicant: {loans: [{balance: 99.99, fee: "x", flagged: false, meta: {adjusted: false, surcharge: 99.99}, points: "-49.995", review: 49.995, risk: 99.99, segment: false, share: [false]}, {balance: null, fee: "x", flagged: false, meta: {adjusted: false, surcharge: 0}, points: "-0", review: 0, risk: 0, segment: false, share: [false]}], plan: "trial", qty: null}, threshold: 0.5}], + {input: {threshold: 0.5, applicant: {qty: 1000, plan: "trial", loans: [{balance: -0.01, flagged: true}, {flagged: false}, {flagged: true}, {balance: -0, flagged: true}, {balance: 5, flagged: false}, {balance: null, flagged: false}, {flagged: true}, {flagged: true}, {balance: null, flagged: true}, {balance: 1000, flagged: true}, {balance: 10, flagged: false}, {flagged: true}]}}, goals: ["loan.review"], output: {applicant: {loans: [{balance: -0.01, flagged: true, meta: {surcharge: 999.99}, review: 499.995}, {flagged: false, meta: {surcharge: 1000}, review: 500.0}, {flagged: true, meta: {surcharge: 1000}, review: 500.0}, {balance: 0, flagged: true, meta: {surcharge: 1000}, review: 500.0}, {balance: 5, flagged: false, meta: {surcharge: 1005}, review: 502.5}, {balance: null, flagged: false, meta: {surcharge: 1000}, review: 500.0}, {flagged: true, meta: {surcharge: 1000}, review: 500.0}, {flagged: true, meta: {surcharge: 1000}, review: 500.0}, {balance: null, flagged: true, meta: {surcharge: 1000}, review: 500.0}, {balance: 1000, flagged: true, meta: {surcharge: 2000}, review: 1000.0}, {balance: 10, flagged: false, meta: {surcharge: 1010}, review: 505.0}, {flagged: true, meta: {surcharge: 1000}, review: 500.0}], plan: "trial", qty: 1000}, threshold: 0.5}}, + {input: {threshold: 0, applicant: {qty: 0.25, limit: 1000000, plan: null, loans: null}}, goals: ["loan.bonus", "loan.share"], output: {applicant: {limit: 1000000, loans: null, plan: null, qty: 0.25}, threshold: 0}}, + {input: {threshold: -2, applicant: {limit: 1}}, goals: ["loan.segment", "loan.risk", "loan.meta.adjusted"], output: {applicant: {limit: 1}, threshold: -2}}, + {input: {threshold: 0.5, applicant: {qty: 99.99, limit: 0.25, plan: "premium", loans: [{balance: -1, flagged: true}, {balance: 65, flagged: true}, {balance: -0.5, flagged: false}]}}, goals: ["loan.review", "loan.fee"], output: {applicant: {limit: 0.25, loans: [{balance: -1, fee: "none", flagged: true, meta: {surcharge: 98.99}, review: 49.495, risk: -1, share: []}, {balance: 65, fee: "none", flagged: true, meta: {surcharge: 164.99}, review: 82.495, risk: 65, share: []}, {balance: -0.5, fee: "none", flagged: false, meta: {surcharge: 99.49}, review: 49.745, risk: -0.5, share: []}], plan: "premium", qty: 99.99}, threshold: 0.5}}, + {input: {threshold: 0.5, applicant: {qty: 50, limit: 5, plan: "basic", loans: [{balance: 50, flagged: true}, {balance: 250, flagged: false}, {balance: 50, flagged: true}]}}, goals: ["loan.points", "loan.bonus", "loan.review"], output: {applicant: {limit: 5, loans: [{balance: 50, bonus: false, flagged: true, meta: {surcharge: 100}, points: "-50.0", review: 50.0}, {balance: 250, bonus: false, flagged: false, meta: {surcharge: 300}, points: "-150.0", review: 150.0}, {balance: 50, bonus: false, flagged: true, meta: {surcharge: 100}, points: "-50.0", review: 50.0}], plan: "basic", qty: 50}, threshold: 0.5}}, + {input: {threshold: 0, applicant: {qty: 1000, limit: 0.25, plan: "basic", loans: [{balance: 2, flagged: false}]}}, goals: ["loan.review", "loan.points"], output: {applicant: {limit: 0.25, loans: [{balance: 2, flagged: false, meta: {surcharge: 1002}, points: "-0", review: 0}], plan: "basic", qty: 1000}, threshold: 0}}, + {input: {threshold: 10, applicant: {limit: 0.1, plan: "plus", loans: [{balance: null, flagged: false}, {balance: 2, flagged: false}, {balance: 100, flagged: true}]}}, goals: ["loan.bonus"], output: {applicant: {limit: 0.1, loans: [{balance: null, bonus: false, flagged: false}, {balance: 2, bonus: false, flagged: false}, {balance: 100, bonus: false, flagged: true}], plan: "plus"}, threshold: 10}}, + {input: {threshold: 1, applicant: {qty: null, limit: null, plan: "basic", loans: [{balance: 1000, flagged: true}, {balance: null, flagged: false}]}}, goals: ["loan.share"], output: {applicant: {limit: null, loans: [{balance: 1000, fee: "x", flagged: true, meta: {adjusted: true, surcharge: 1000}, review: 1000, risk: 1000, share: [true]}, {balance: null, fee: "x", flagged: false, meta: {adjusted: false, surcharge: 0}, review: 0, risk: 0, share: [false]}], plan: "basic", qty: null}, threshold: 1}}, + {input: {threshold: 1, applicant: {qty: null, plan: "trial", loans: [{balance: 50, flagged: false}, {flagged: false}, {flagged: false}, {balance: 50, flagged: true}, {balance: 1000, flagged: true}]}}, goals: ["loan.meta.adjusted"], output: {applicant: {loans: [{balance: 50, flagged: false, meta: {adjusted: false}}, {flagged: false, meta: {adjusted: false}}, {flagged: false, meta: {adjusted: false}}, {balance: 50, flagged: true, meta: {adjusted: true}}, {balance: 1000, flagged: true, meta: {adjusted: true}}], plan: "trial", qty: null}, threshold: 1}}, + {input: {threshold: 0, applicant: {qty: 1, limit: null, plan: "basic", loans: [{balance: 7.25, flagged: true}]}}, goals: ["loan.meta.adjusted", "loan.risk", "loan.bonus"], output: {applicant: {limit: null, loans: [{balance: 7.25, bonus: false, fee: "x", flagged: true, meta: {adjusted: true, surcharge: 8.25}, review: 0, risk: 8.25, share: [true]}], plan: "basic", qty: 1}, threshold: 0}}, + {input: {threshold: 10, applicant: {qty: 1000000, limit: 50, plan: "plus", loans: [{balance: 10, flagged: false}, {balance: 1000, flagged: true}, {balance: 50, flagged: false}, {balance: 0.25, flagged: true}]}}, goals: ["loan.meta.adjusted", "loan.share"], output: {applicant: {limit: 50, loans: [{balance: 10, fee: "none", flagged: false, margin: false, meta: {adjusted: false, surcharge: 1000010}, review: 10000100, risk: 10, share: []}, {balance: 1000, fee: "none", flagged: true, margin: false, meta: {adjusted: false, surcharge: 1001000}, review: 10010000, risk: 1000, share: []}, {balance: 50, fee: "none", flagged: false, margin: false, meta: {adjusted: false, surcharge: 1000050}, review: 10000500, risk: 50, share: []}, {balance: 0.25, fee: "none", flagged: true, margin: false, meta: {adjusted: false, surcharge: 1000000.25}, review: 10000002.50, risk: 0.25, share: []}], plan: "plus", qty: 1000000}, threshold: 10}}, + {input: {threshold: -2, applicant: {qty: 1000, limit: 250, plan: "trial", loans: [{balance: 99999999999999999999, flagged: false}, {balance: 0.25, flagged: false}, {balance: 0, flagged: false}]}}, goals: ["loan.fee", "loan.risk", "loan.margin"], output: {applicant: {limit: 250, loans: [{balance: 99999999999999999999, fee: "none", flagged: false, margin: false, meta: {surcharge: 100000000000000000999}, review: -200000000000000001998, risk: 99999999999999999999, share: []}, {balance: 0.25, fee: "none", flagged: false, margin: false, meta: {surcharge: 1000.25}, review: -2000.50, risk: 0.25, share: []}, {balance: 0, fee: "none", flagged: false, margin: false, meta: {surcharge: 1000}, review: -2000, risk: 0, share: []}], plan: "trial", qty: 1000}, threshold: -2}}, + {input: {threshold: -2, applicant: {qty: 99999999999999999999, limit: 350, plan: "premium", loans: [{balance: 1.5, flagged: true}]}}, goals: ["loan.margin", "loan.risk"], output: {applicant: {limit: 350, loans: [{balance: 1.5, fee: "none", flagged: true, margin: true, meta: {surcharge: 100000000000000000000.5}, review: -200000000000000000001.0, risk: 1.5, share: []}], plan: "premium", qty: 99999999999999999999}, threshold: -2}}, + {input: {threshold: 100, applicant: {loans: [{flagged: false}, {flagged: false}, {balance: 50, flagged: false}, {flagged: false}, {flagged: false}, {balance: null, flagged: false}, {balance: 100, flagged: false}, {balance: 10, flagged: false}, {balance: null, flagged: false}, {balance: 0.25, flagged: false}]}}, goals: ["loan.fee", "loan.meta.surcharge"], output: {applicant: {loans: [{bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 0}, review: 0, risk: 50, share: [false, false]}, {bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 0}, review: 0, risk: 50, share: [false, false]}, {balance: 50, bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 50}, review: 5000, risk: 50, share: [false, false]}, {bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 0}, review: 0, risk: 50, share: [false, false]}, {bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 0}, review: 0, risk: 50, share: [false, false]}, {balance: null, bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 0}, review: 0, risk: 50, share: [false, false]}, {balance: 100, bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 100}, review: 10000, risk: 50, share: [false, false]}, {balance: 10, bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 10}, review: 1000, risk: 50, share: [false, false]}, {balance: null, bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 0}, review: 0, risk: 50, share: [false, false]}, {balance: 0.25, bonus: false, fee: "gold", flagged: false, meta: {adjusted: false, surcharge: 0.25}, review: 25.00, risk: 50, share: [false, false]}]}, threshold: 100}}, + {input: {threshold: -2, applicant: {qty: 1, limit: 100, plan: "basic", loans: [{balance: null, flagged: true}, {balance: null, flagged: true}, {balance: 1000000, flagged: false}, {balance: 0.5, flagged: false}]}}, goals: ["loan.review"], output: {applicant: {limit: 100, loans: [{balance: null, flagged: true, meta: {surcharge: 1}, review: -2}, {balance: null, flagged: true, meta: {surcharge: 1}, review: -2}, {balance: 1000000, flagged: false, meta: {surcharge: 1000001}, review: -2000002}, {balance: 0.5, flagged: false, meta: {surcharge: 1.5}, review: -3.0}], plan: "basic", qty: 1}, threshold: -2}}, + {input: {threshold: 10, applicant: {qty: 280, limit: 100, plan: "basic", loans: [{balance: 123456789.123, flagged: true}, {balance: 99.99, flagged: true}, {balance: 50, flagged: true}, {balance: 1000000, flagged: true}, {balance: 65, flagged: false}]}}, goals: ["loan.share", "loan.meta.adjusted"], output: {applicant: {limit: 100, loans: [{balance: 123456789.123, fee: "none", flagged: true, meta: {adjusted: true, surcharge: 123457069.123}, review: 1234570691.230, risk: 123456789.123, share: []}, {balance: 99.99, fee: "none", flagged: true, meta: {adjusted: true, surcharge: 379.99}, review: 3799.90, risk: 99.99, share: []}, {balance: 50, fee: "none", flagged: true, meta: {adjusted: true, surcharge: 330}, review: 3300, risk: 50, share: []}, {balance: 1000000, fee: "none", flagged: true, meta: {adjusted: true, surcharge: 1000280}, review: 10002800, risk: 1000000, share: []}, {balance: 65, fee: "none", flagged: false, meta: {adjusted: false, surcharge: 345}, review: 3450, risk: 65, share: []}], plan: "basic", qty: 280}, threshold: 10}}, + {input: {threshold: 10, applicant: {limit: -0.01, loans: [{balance: 99999999999999999999, flagged: true}, {balance: 100, flagged: false}]}}, goals: ["loan.margin"], output: {applicant: {limit: -0.01, loans: [{balance: 99999999999999999999, flagged: true, margin: true}, {balance: 100, flagged: false, margin: false}]}, threshold: 10}}, + {input: {threshold: 0, applicant: {qty: 10, limit: 3, plan: null, loans: [{balance: null, flagged: false}, {balance: 50, flagged: true}, {flagged: true}, {balance: null, flagged: false}]}}, goals: ["loan.meta.adjusted", "loan.points", "loan.meta.surcharge"], output: {applicant: {limit: 3, loans: [{balance: null, flagged: false, meta: {adjusted: false, surcharge: 10}, points: "-0", review: 0}, {balance: 50, flagged: true, meta: {adjusted: true, surcharge: 60}, points: "-0", review: 0}, {flagged: true, meta: {adjusted: true, surcharge: 10}, points: "-0", review: 0}, {balance: null, flagged: false, meta: {adjusted: false, surcharge: 10}, points: "-0", review: 0}], plan: null, qty: 10}, threshold: 0}}, + {input: {threshold: 0, applicant: {qty: 18, limit: 2.50, plan: "basic", loans: [{balance: 50, flagged: true}, {balance: 65, flagged: false}]}}, goals: ["loan.meta.adjusted"], output: {applicant: {limit: 2.50, loans: [{balance: 50, flagged: true, meta: {adjusted: true}}, {balance: 65, flagged: false, meta: {adjusted: false}}], plan: "basic", qty: 18}, threshold: 0}}, + {input: {threshold: -2, applicant: {qty: 1, limit: 10, plan: "trial", loans: [{balance: -0.01, flagged: true}, {balance: 5, flagged: true}, {balance: 5, flagged: false}, {balance: 1e3, flagged: false}, {balance: 5, flagged: false}, {balance: 1, flagged: false}, {balance: 1000000, flagged: false}, {balance: 18, flagged: false}, {balance: 250, flagged: true}], extraField: {nested: true}}}, goals: ["loan.points", "loan.meta.surcharge"], output: {applicant: {extraField: {nested: true}, limit: 10, loans: [{balance: -0.01, flagged: true, meta: {surcharge: 0.99}, points: "1.98", review: -1.98}, {balance: 5, flagged: true, meta: {surcharge: 6}, points: "12", review: -12}, {balance: 5, flagged: false, meta: {surcharge: 6}, points: "12", review: -12}, {balance: 1000, flagged: false, meta: {surcharge: 1001}, points: "2002", review: -2002}, {balance: 5, flagged: false, meta: {surcharge: 6}, points: "12", review: -12}, {balance: 1, flagged: false, meta: {surcharge: 2}, points: "4", review: -4}, {balance: 1000000, flagged: false, meta: {surcharge: 1000001}, points: "2000002", review: -2000002}, {balance: 18, flagged: false, meta: {surcharge: 19}, points: "38", review: -38}, {balance: 250, flagged: true, meta: {surcharge: 251}, points: "502", review: -502}], plan: "trial", qty: 1}, threshold: -2}}, + {input: {threshold: 10, applicant: {limit: 2}}, goals: ["loan.bonus", "loan.margin", "loan.meta.adjusted"], output: {applicant: {limit: 2}, threshold: 10}}, + [{threshold: 0.5, applicant: {qty: null, limit: 3, plan: "basic", loans: [{flagged: false}, {flagged: false}, {flagged: false}]}}, {applicant: {limit: 3, loans: [{fee: "x", flagged: false, meta: {adjusted: false, surcharge: 0}, points: "-0", review: 0, risk: 0, segment: false, share: [false]}, {fee: "x", flagged: false, meta: {adjusted: false, surcharge: 0}, points: "-0", review: 0, risk: 0, segment: false, share: [false]}, {fee: "x", flagged: false, meta: {adjusted: false, surcharge: 0}, points: "-0", review: 0, risk: 0, segment: false, share: [false]}], plan: "basic", qty: null}, threshold: 0.5}], + {input: {threshold: 0, applicant: {qty: -1, limit: 3, plan: "basic", loans: [{balance: 3, flagged: false}, {balance: 100, flagged: false}, {balance: 10, flagged: true}]}}, goals: ["loan.meta.adjusted", "loan.segment"], output: {applicant: {limit: 3, loans: [{balance: 3, flagged: false, meta: {adjusted: false}, segment: false}, {balance: 100, flagged: false, meta: {adjusted: false}, segment: false}, {balance: 10, flagged: true, meta: {adjusted: true}, segment: true}], plan: "basic", qty: -1}, threshold: 0}}, + ], +} + +// seed 351900 (attempt 0) +{ + name: "goals 20: order/parcels + profile: 1 expression, 2 match, 2 table; 5 root, 5 per-member, 0 top-level computed", + policy: { + models: {order: {income: "number", since: "date?", birthDate: "date?", label: "string?", parcels: "parcel[]?", profile: "profile"}, parcel: {income: "number", dueDate: "date"}, profile: {rate: "number?"}}, + blocks: [ + {match: "parcel.fee", arms: [["parcel.dueDate.isAfter(d('2024-01-01'), 'day')", "`${250 <= 0}/${(order.profile.rate ?? 0)}`"], ["", "(order.label ?? '')"]]}, + {expression: "parcel.totals.grade", value: "{n: parcel.income, ok: order.income, a: (order.birthDate ?? d('2025-01-01')).month()}"}, + {match: "profile.tag", arms: [["order.since != null", "(order.label ?? '')"], ["(order.birthDate ?? d('2025-01-01')) > d('2000-06-30')", "(order.label ?? '')"], ["order.birthDate == null", "(order.label ?? '')"], ["", "(order.label ?? '')"]]}, + {table: "t4", hit: "collect", inputs: ["(order.since ?? d('2025-01-01'))", "(order.birthDate ?? d('2025-01-01'))"], outputs: ["order.capped", "order.share", "order.flags.band"], rules: [ + ["< d('2025-01-01')", "> d('2000-06-30')", "order.income <= 0", "(min([abs(order.income), 1000]) ^ 1)", "(order.profile.rate ?? 0)"], + [">= d('2000-06-30')", "< d('2025-03-20')", "(order.profile.rate ?? 0) <= 1.5", "", ""], + ]}, + {table: "t5", inputs: ["avg([250, order.income, order.income])", "order.income"], outputs: ["order.scores.total", "order.flags.review"], rules: [ + [">= 0", "", "(order.profile.rate ?? 0) > 50", ""], + ["[5..489]", "10", "(order.profile.rate ?? 0) == 1.5", "((order.profile.rate ?? 0) * (order.profile.rate ?? 0))"], + ["", "50", "order.profile.tag in ['DE', 'A1']", "order.income"], + [">= 250", "< 100", "(order.profile.rate ?? 0) == 3", "(order.profile.rate ?? 0)"], + ["", "", "((order.profile.rate ?? 0) == 0 or order.income > 50)", "((order.profile.rate ?? 0) % (abs(order.income) + 1))"], + ["> 250", "> 0.25", "(order.birthDate ?? d('2025-01-01')) < d('2025-03-20')", "order.income"], + ]}, + ], + }, + cases: [ + {input: {order: {income: 50, birthDate: "2030-12-31", parcels: [{income: 65, dueDate: "2025-03-20"}, {income: 99.99, dueDate: "2030-12-31"}, {income: 1000, dueDate: "2024-02-29"}], profile: {rate: null}}}, goals: ["profile.tag"], output: {order: {birthDate: "2030-12-31", income: 50, parcels: [{dueDate: "2025-03-20", income: 65}, {dueDate: "2030-12-31", income: 99.99}, {dueDate: "2024-02-29", income: 1000}], profile: {rate: null, tag: ""}}}}, + {input: {order: {income: 250, birthDate: "2024-01-01", parcels: [{income: 0.000001, dueDate: "2030-12-31"}, {income: 50, dueDate: "2000-01-01"}], profile: {}}}, goals: ["order.capped"], output: {order: {birthDate: "2024-01-01", capped: [true], flags: {band: []}, income: 250, parcels: [{dueDate: "2030-12-31", income: 0.000001}, {dueDate: "2000-01-01", income: 50}], profile: {}, share: []}}}, + {input: {order: {income: 1, since: "2024-01-01", birthDate: "2000-01-01", label: "O'Neil", parcels: [{income: 18, dueDate: "2000-01-01"}], profile: {}}}, goals: ["order.share", "parcel.fee", "order.flags.band"], output: {order: {birthDate: "2000-01-01", capped: [true], flags: {band: []}, income: 1, label: "O'Neil", parcels: [{dueDate: "2000-01-01", fee: "O'Neil", income: 18}], profile: {}, share: [], since: "2024-01-01"}}}, + {input: {order: {income: 18, since: "2025-03-20", birthDate: "2024-01-01", label: "A1", parcels: [{income: 0, dueDate: "2025-03-20T10:15:30Z"}, {income: 50, dueDate: "2024-01-01"}, {income: 265, dueDate: "2030-12-31"}, {income: 0, dueDate: "2025-03-20"}, {income: 18, dueDate: "2024-02-29"}, {income: 0.000001, dueDate: "1990-06-15"}, {income: 0, dueDate: "2030-12-31"}, {income: 0.25, dueDate: "2000-01-01"}, {income: 0.000001, dueDate: "2024-02-29"}, {income: 65, dueDate: "2025-03-20T10:15:30Z"}, {income: 2, dueDate: "1990-06-15"}, {income: 0, dueDate: "2024-01-01"}, {income: 0, dueDate: "2024-01-01"}, {income: 0.000001, dueDate: "2025-03-20T10:15:30Z"}], profile: {rate: 18}}}, goals: ["parcel.fee", "order.flags.review"], output: {order: {birthDate: "2024-01-01", flags: {review: 18}, income: 18, label: "A1", parcels: [{dueDate: "2025-03-20T10:15:30Z", fee: "false/18", income: 0}, {dueDate: "2024-01-01", fee: "A1", income: 50}, {dueDate: "2030-12-31", fee: "false/18", income: 265}, {dueDate: "2025-03-20", fee: "false/18", income: 0}, {dueDate: "2024-02-29", fee: "false/18", income: 18}, {dueDate: "1990-06-15", fee: "A1", income: 0.000001}, {dueDate: "2030-12-31", fee: "false/18", income: 0}, {dueDate: "2000-01-01", fee: "A1", income: 0.25}, {dueDate: "2024-02-29", fee: "false/18", income: 0.000001}, {dueDate: "2025-03-20T10:15:30Z", fee: "false/18", income: 65}, {dueDate: "1990-06-15", fee: "A1", income: 2}, {dueDate: "2024-01-01", fee: "A1", income: 0}, {dueDate: "2024-01-01", fee: "A1", income: 0}, {dueDate: "2025-03-20T10:15:30Z", fee: "false/18", income: 0.000001}], profile: {rate: 18}, scores: {total: false}, since: "2025-03-20"}}}, + {input: {order: {income: null, since: "2000-01-01", birthDate: "2025-03-20T10:15:30Z", label: "日本", parcels: [{income: 99999999999999999999, dueDate: "2025-03-20T10:15:30Z"}, {income: 3, dueDate: "2000-01-01"}], profile: {rate: -0.01}}}, goals: ["order.flags.review"], output: "!error: MissingRequiredInputs"}, + {input: {order: {income: 3, since: "1990-06-15", birthDate: "2030-12-31", label: "none", parcels: [], profile: {rate: 7.25}}}, goals: ["profile.tag"], output: {order: {birthDate: "2030-12-31", income: 3, label: "none", parcels: [], profile: {rate: 7.25, tag: "none"}, since: "1990-06-15"}}}, + {input: {order: {income: 1.5, since: "2025-03-20T10:15:30Z", birthDate: "2025-03-20", label: "none", parcels: [{income: 5, dueDate: "2025-03-20"}], profile: {rate: 1000}}}, goals: ["order.scores.total", "parcel.fee", "order.flags.review"], output: {order: {birthDate: "2025-03-20", flags: {review: 0.0}, income: 1.5, label: "none", parcels: [{dueDate: "2025-03-20", fee: "false/1000", income: 5}], profile: {rate: 1000}, scores: {total: true}, since: "2025-03-20T10:15:30Z"}}}, + {input: {order: {income: 2.50, since: null, label: "ok", parcels: [], profile: {}}}, goals: ["parcel.totals.grade", "parcel.fee"], output: {order: {income: 2.50, label: "ok", parcels: [], profile: {}, since: null}}}, + {input: {order: {income: 1e3, since: "1990-06-15", birthDate: "2030-12-31", label: "12", parcels: [{income: 65, dueDate: "1990-06-15"}, {income: 0.5, dueDate: "2000-01-01"}, {income: 10, dueDate: "2030-12-31"}, {income: 0.5, dueDate: "2000-01-01"}, {income: -0.5, dueDate: "2030-12-31"}], profile: {rate: 0.5}}}, goals: ["parcel.totals.grade"], output: {order: {birthDate: "2030-12-31", income: 1000, label: "12", parcels: [{dueDate: "1990-06-15", income: 65, totals: {grade: {a: 12, n: 65, ok: 1000}}}, {dueDate: "2000-01-01", income: 0.5, totals: {grade: {a: 12, n: 0.5, ok: 1000}}}, {dueDate: "2030-12-31", income: 10, totals: {grade: {a: 12, n: 10, ok: 1000}}}, {dueDate: "2000-01-01", income: 0.5, totals: {grade: {a: 12, n: 0.5, ok: 1000}}}, {dueDate: "2030-12-31", income: -0.5, totals: {grade: {a: 12, n: -0.5, ok: 1000}}}], profile: {rate: 0.5}, since: "1990-06-15"}}}, + {input: {order: {income: -0.01, birthDate: "2030-12-31", parcels: [{income: 2.50, dueDate: "1990-06-15"}, {income: 123456789.123, dueDate: "1990-06-15"}, {income: -0, dueDate: "2025-03-20"}, {income: 1.5, dueDate: "2000-01-01"}, {income: 250, dueDate: "2024-02-29"}], profile: {rate: 1000}}}, goals: ["profile.tag", "order.scores.total", "parcel.totals.grade"], output: {order: {birthDate: "2030-12-31", flags: {review: 0.10}, income: -0.01, parcels: [{dueDate: "1990-06-15", income: 2.50, totals: {grade: {a: 12, n: 2.50, ok: -0.01}}}, {dueDate: "1990-06-15", income: 123456789.123, totals: {grade: {a: 12, n: 123456789.123, ok: -0.01}}}, {dueDate: "2025-03-20", income: 0, totals: {grade: {a: 12, n: 0, ok: -0.01}}}, {dueDate: "2000-01-01", income: 1.5, totals: {grade: {a: 12, n: 1.5, ok: -0.01}}}, {dueDate: "2024-02-29", income: 250, totals: {grade: {a: 12, n: 250, ok: -0.01}}}], profile: {rate: 1000, tag: ""}, scores: {total: true}}}}, + {input: {order: {income: 1.5, since: null, birthDate: "2024-02-29", parcels: [{income: 2, dueDate: "2025-03-20T10:15:30Z"}], profile: {rate: 18}}}, goals: ["order.flags.review", "parcel.fee", "order.scores.total"], output: {order: {birthDate: "2024-02-29", flags: {review: 0.5}, income: 1.5, parcels: [{dueDate: "2025-03-20T10:15:30Z", fee: "false/18", income: 2}], profile: {rate: 18}, scores: {total: false}, since: null}}}, + {input: {order: {income: 1, since: "2000-01-01", birthDate: "2025-03-20T10:15:30Z", label: "none", parcels: [{income: 123456789.123, dueDate: "1990-06-15"}, {income: 250, dueDate: "2025-03-20T10:15:30Z"}, {income: 250, dueDate: "2025-03-20"}, {income: 1.5, dueDate: "2025-03-20T10:15:30Z"}, {income: 2.50, dueDate: "2030-12-31"}], profile: {rate: 0.000001}}}, goals: ["profile.tag"], output: {order: {birthDate: "2025-03-20T10:15:30Z", income: 1, label: "none", parcels: [{dueDate: "1990-06-15", income: 123456789.123}, {dueDate: "2025-03-20T10:15:30Z", income: 250}, {dueDate: "2025-03-20", income: 250}, {dueDate: "2025-03-20T10:15:30Z", income: 1.5}, {dueDate: "2030-12-31", income: 2.50}], profile: {rate: 0.000001, tag: "none"}, since: "2000-01-01"}}}, + [{order: {income: 0, since: "1990-06-15", birthDate: "2025-03-20T10:15:30Z", label: "O'Neil", parcels: [{income: 1.5, dueDate: "2025-03-20"}], profile: {rate: 3}}}, {order: {birthDate: "2025-03-20T10:15:30Z", capped: [true], flags: {band: [3], review: 0}, income: 0, label: "O'Neil", parcels: [{dueDate: "2025-03-20", fee: "false/3", income: 1.5, totals: {grade: {a: 3, n: 1.5, ok: 0}}}], profile: {rate: 3}, scores: {total: false}, share: [0], since: "1990-06-15"}}], + {input: {order: {income: 65, since: "2030-12-31", birthDate: "2030-12-31", label: "VIP", parcels: [], profile: {rate: 123456789.123}}}, goals: ["parcel.totals.grade"], output: {order: {birthDate: "2030-12-31", income: 65, label: "VIP", parcels: [], profile: {rate: 123456789.123}, since: "2030-12-31"}}}, + {input: {order: {income: -500, since: "2000-01-01", birthDate: "2030-12-31", label: "NL", parcels: [{income: 50, dueDate: "2000-01-01"}], profile: {rate: 250}}}, goals: ["order.capped"], output: {order: {birthDate: "2030-12-31", capped: [true], flags: {band: [250]}, income: -500, label: "NL", parcels: [{dueDate: "2000-01-01", income: 50}], profile: {rate: 250}, share: [500], since: "2000-01-01"}}}, + {input: {order: {income: 50, since: null, label: "a", parcels: [{income: -500, dueDate: "2030-12-31"}, {income: 250, dueDate: "1990-06-15"}], profile: {rate: 0}}}, goals: ["order.capped"], output: {order: {capped: [true], flags: {band: []}, income: 50, label: "a", parcels: [{dueDate: "2030-12-31", income: -500}, {dueDate: "1990-06-15", income: 250}], profile: {rate: 0}, share: [], since: null}}}, + {input: {order: {income: 392, birthDate: "2024-01-01", label: " pad ", parcels: [{income: 5, dueDate: "2000-01-01"}, {income: 64, dueDate: "2000-01-01"}], profile: {rate: 7.25}}}, goals: ["order.flags.band"], output: {order: {birthDate: "2024-01-01", capped: [false], flags: {band: []}, income: 392, label: " pad ", parcels: [{dueDate: "2000-01-01", income: 5}, {dueDate: "2000-01-01", income: 64}], profile: {rate: 7.25}, share: []}}}, + {input: {order: {income: 1, since: "2030-12-31", birthDate: 20250101, label: "é ü", parcels: [{income: -500, dueDate: "2025-03-20"}, {income: 0, dueDate: "2024-01-01"}], profile: {rate: 99.99}}}, goals: ["parcel.fee"], output: "!error: InputValidationFailed"}, + [{order: {income: 0, since: "2025-03-20T10:15:30Z", birthDate: "2024-02-29", label: "DE", parcels: [{income: 1000, dueDate: "2030-12-31"}, {income: 99.99, dueDate: "1990-06-15"}], profile: {}}}, {order: {birthDate: "2024-02-29", capped: [true], flags: {band: [], review: 0}, income: 0, label: "DE", parcels: [{dueDate: "2030-12-31", fee: "false/0", income: 1000, totals: {grade: {a: 2, n: 1000, ok: 0}}}, {dueDate: "1990-06-15", fee: "DE", income: 99.99, totals: {grade: {a: 2, n: 99.99, ok: 0}}}], profile: {}, scores: {total: false}, share: [], since: "2025-03-20T10:15:30Z"}}], + {input: {order: {income: 100, since: "2030-12-31", birthDate: "1990-06-15", label: "a", parcels: [{income: -0.01, dueDate: "2025-03-20"}, {income: 3, dueDate: "2024-02-29"}], profile: {rate: 2}}}, goals: ["parcel.totals.grade", "profile.tag", "order.capped"], output: {order: {birthDate: "1990-06-15", capped: [false], flags: {band: []}, income: 100, label: "a", parcels: [{dueDate: "2025-03-20", income: -0.01, totals: {grade: {a: 6, n: -0.01, ok: 100}}}, {dueDate: "2024-02-29", income: 3, totals: {grade: {a: 6, n: 3, ok: 100}}}], profile: {rate: 2, tag: "a"}, share: [], since: "2030-12-31"}}}, + {input: {order: {income: 0.25, since: "2024-01-01", birthDate: "2024-01-01", label: 5, parcels: [{income: 1.5, dueDate: "2025-03-20T10:15:30Z"}, {income: -0, dueDate: "2025-03-20"}, {income: 1e3, dueDate: "1990-06-15"}], profile: {rate: 1.5}}}, goals: ["order.flags.review", "profile.tag", "parcel.fee"], output: "!error: InputValidationFailed"}, + {input: {order: {income: -500, since: "2024-01-01", birthDate: "2030-12-31", label: "a-b-c", parcels: [{income: 3, dueDate: "2024-02-29"}, {income: 250, dueDate: "2025-03-20"}, {income: 1, dueDate: "1990-06-15"}, {income: 100, dueDate: "2000-01-01"}], profile: {rate: 1}}}, goals: ["order.capped"], output: {order: {birthDate: "2030-12-31", capped: [true], flags: {band: [1]}, income: -500, label: "a-b-c", parcels: [{dueDate: "2024-02-29", income: 3}, {dueDate: "2025-03-20", income: 250}, {dueDate: "1990-06-15", income: 1}, {dueDate: "2000-01-01", income: 100}], profile: {rate: 1}, share: [500], since: "2024-01-01"}}}, + {input: {order: {income: 1e3, since: "1990-06-15", birthDate: "2024-01-01", label: "A1", parcels: [], profile: {rate: 0}}}, goals: ["order.capped"], output: {order: {birthDate: "2024-01-01", capped: [false], flags: {band: [0]}, income: 1000, label: "A1", parcels: [], profile: {rate: 0}, share: [1000], since: "1990-06-15"}}}, + [{order: {income: 7.25, birthDate: "2024-01-01", label: null, parcels: [{income: 10, dueDate: "2024-02-29"}, {income: 0, dueDate: "2024-02-29"}, {income: 3, dueDate: "2024-02-29"}, {income: 1.5, dueDate: "2025-03-20T10:15:30Z"}, {income: 5, dueDate: "2030-12-31"}], profile: {rate: 0}}}, {order: {birthDate: "2024-01-01", capped: [true], flags: {band: [], review: 0}, income: 7.25, label: null, parcels: [{dueDate: "2024-02-29", fee: "false/0", income: 10, totals: {grade: {a: 1, n: 10, ok: 7.25}}}, {dueDate: "2024-02-29", fee: "false/0", income: 0, totals: {grade: {a: 1, n: 0, ok: 7.25}}}, {dueDate: "2024-02-29", fee: "false/0", income: 3, totals: {grade: {a: 1, n: 3, ok: 7.25}}}, {dueDate: "2025-03-20T10:15:30Z", fee: "false/0", income: 1.5, totals: {grade: {a: 1, n: 1.5, ok: 7.25}}}, {dueDate: "2030-12-31", fee: "false/0", income: 5, totals: {grade: {a: 1, n: 5, ok: 7.25}}}], profile: {rate: 0}, scores: {total: false}, share: []}}], + {input: {order: {income: 1.5, since: "2000-01-01", birthDate: "1990-06-15", label: "high", parcels: [{income: 2.50, dueDate: "2000-01-01"}], profile: {rate: 250}}}, goals: ["order.capped", "parcel.fee"], output: {order: {birthDate: "1990-06-15", capped: [], flags: {band: []}, income: 1.5, label: "high", parcels: [{dueDate: "2000-01-01", fee: "high", income: 2.50}], profile: {rate: 250}, share: [], since: "2000-01-01"}}}, + {input: {order: {income: 240, since: "2030-12-31", birthDate: "2025-03-20T10:15:30Z", label: "-", parcels: [{income: 5, dueDate: "2024-01-01"}, {income: -0, dueDate: "2025-03-20T10:15:30Z"}], profile: {rate: 99999999999999999999}, extraField: 1}}, goals: ["parcel.fee", "parcel.totals.grade", "profile.tag"], output: {order: {birthDate: "2025-03-20T10:15:30Z", extraField: 1, income: 240, label: "-", parcels: [{dueDate: "2024-01-01", fee: "-", income: 5, totals: {grade: {a: 3, n: 5, ok: 240}}}, {dueDate: "2025-03-20T10:15:30Z", fee: "false/99999999999999999999", income: 0, totals: {grade: {a: 3, n: 0, ok: 240}}}], profile: {rate: 99999999999999999999, tag: "-"}, since: "2030-12-31"}}}, + [{order: {income: 250, since: "2024-02-29", birthDate: "2025-03-20", label: "a", parcels: [], profile: {rate: 65}}}, {order: {birthDate: "2025-03-20", capped: [false], flags: {band: [65], review: 65}, income: 250, label: "a", parcels: [], profile: {rate: 65}, scores: {total: true}, share: [250], since: "2024-02-29"}}], + {input: {order: {income: -0.01, since: "1990-06-15", label: "Oslo", parcels: [{income: 100, dueDate: "2000-01-01"}], profile: {rate: 1.5}}}, goals: ["order.flags.band", "order.share"], output: {order: {capped: [true], flags: {band: [1.5]}, income: -0.01, label: "Oslo", parcels: [{dueDate: "2000-01-01", income: 100}], profile: {rate: 1.5}, share: [0.01], since: "1990-06-15"}}}, + ], +} + +// seed 352000 (attempt 0) +{ + name: "goals 21: order/accounts/parts + address: 3 expression, 2 match, 5 table; 1 root, 4 per-member, 0 top-level computed", + policy: { + models: {order: {qty: "number", vip: "boolean", since: "date", accounts: "acct[]", address: "address"}, acct: {weight: "number", verified: "boolean", parts: "part[]"}, part: {days: "number", tier: "string(gold|silver|bronze)"}, address: {amount: "number"}}, + blocks: [ + {table: "t1", hit: "collect", inputs: ["order.vip"], outputs: ["acct.flag"], rules: [ + ["false", "order.vip"], + ["true", "(order.vip or acct.verified)"], + ]}, + {match: "acct.points", arms: [["isNumeric(string(order.vip))", "(order.vip ? 'high' : 'x')"], ["", "'x'"]]}, + {table: "t3", inputs: ["-(address.amount)"], outputs: ["address.rank", "address.total"], rules: [ + ["", "order.qty", "address.amount"], + ["!= 1000", "order.qty", "10"], + ["< 1", "order.qty", "sum(map(order.accounts, #.weight))"], + ["18", "order.qty", "address.amount"], + ["", "order.qty", "order.qty"], + ["< 1000", "3", "50"], + ["", "order.qty", ""], + ]}, + {table: "t4", inputs: ["(avg(map(order.accounts, #.weight)) ?? 0)", "order.vip", "(order.qty % (abs(5) + 1))"], outputs: ["address.bonus"], rules: [ + ["250, 10", "", "5", "order.vip"], + [">= 3", "false", "", "all(order.accounts, contains(['DE', 'DE', ''], #.points))"], + ["!= 1", "false", "", "order.vip"], + ["", "false", "< 2", ""], + ]}, + {expression: "order.meta.segment", value: "string(order.since > d('2025-03-20'))"}, + {expression: "acct.share", value: "filter(acct.parts, #.days > 1)"}, + {expression: "address.review", value: "{s: `${(address.total ?? 0)}/${len(order.meta.segment)}`}"}, + {table: "t8", inputs: ["order.since", "(address.total ?? 0)", "order.since"], outputs: ["address.risk"], rules: [ + ["< d('2025-01-01')", "1.5", "< d('2025-03-20')", "(address.rank ?? 0)"], + ["", ">= 50", "", ""], + ]}, + {match: "acct.tag", arms: [["order.since >= d('2024-01-01')", "order.qty"], ["not ((order.address.bonus ?? false))", "(order.address.total ?? 0)"], ["not (matches(order.address.review.s, '^[A-Z]'))", "50"], ["", "(acct.verified ? (order.address.total ?? 0) : 2)"]]}, + {table: "t10", hit: "collect", inputs: ["address.rank", "address.review.s"], outputs: ["address.band", "address.discount"], rules: [ + ["2", "'gold', 'US'", "", ""], + ["3, 0.5", "", "", "(address.rank ?? 0)"], + ["2", "'a'", "some(order.accounts, matches(#.points, '^[A-Z]'))", "len(address.review.s)"], + ["", "'retail'", "", "order.qty"], + ["1000, 0", "'Oslo'", "", ""], + ["1, 100", "$ != 'x'", "(address.bonus ?? false)", "len(order.meta.segment)"], + ]}, + ], + }, + cases: [ + {input: {order: {qty: 100, vip: true, since: "2025-03-20", accounts: [{weight: 250, verified: true, parts: [{days: 18, tier: "silver"}]}, {weight: 2, verified: false, parts: [{days: 100, tier: "silver"}]}, {weight: 100, verified: false, parts: [{days: 1000, tier: "bronze"}, {days: 0.25, tier: "bronze"}]}, {weight: 3, verified: true, parts: [{days: 100, tier: "silver"}]}], address: {amount: 10}}}, goals: ["address.bonus", "acct.share", "address.rank"], output: {order: {accounts: [{parts: [{days: 18, tier: "silver"}], share: [{days: 18, tier: "silver"}], verified: true, weight: 250}, {parts: [{days: 100, tier: "silver"}], share: [{days: 100, tier: "silver"}], verified: false, weight: 2}, {parts: [{days: 1000, tier: "bronze"}, {days: 0.25, tier: "bronze"}], share: [{days: 1000, tier: "bronze"}], verified: false, weight: 100}, {parts: [{days: 100, tier: "silver"}], share: [{days: 100, tier: "silver"}], verified: true, weight: 3}], address: {amount: 10, bonus: null, rank: 100, total: 10}, qty: 100, since: "2025-03-20", vip: true}}}, + [{order: {qty: 250, vip: true, since: "2025-03-20T10:15:30Z", accounts: [{weight: 3, verified: false, parts: [{days: 123456789.123, tier: "gold"}, {days: 1000, tier: "bronze"}]}, {weight: 50, verified: true, parts: [{days: 1000, tier: "gold"}]}, {weight: 1e3, verified: false, parts: [{days: 1000000, tier: "gold"}, {days: 65, tier: "gold"}, {days: 0.25, tier: "silver"}]}, {weight: 3, verified: false, parts: [{days: 18, tier: "gold"}, {days: 0.25, tier: "bronze"}, {days: 1, tier: "gold"}]}], address: {amount: -0}}}, {order: {accounts: [{flag: [true], parts: [{days: 123456789.123, tier: "gold"}, {days: 1000, tier: "bronze"}], share: [{days: 123456789.123, tier: "gold"}, {days: 1000, tier: "bronze"}], tag: 250, verified: false, weight: 3}, {flag: [true], parts: [{days: 1000, tier: "gold"}], share: [{days: 1000, tier: "gold"}], tag: 250, verified: true, weight: 50}, {flag: [true], parts: [{days: 1000000, tier: "gold"}, {days: 65, tier: "gold"}, {days: 0.25, tier: "silver"}], share: [{days: 1000000, tier: "gold"}, {days: 65, tier: "gold"}], tag: 250, verified: false, weight: 1000}, {flag: [true], parts: [{days: 18, tier: "gold"}, {days: 0.25, tier: "bronze"}, {days: 1, tier: "gold"}], share: [{days: 18, tier: "gold"}], tag: 250, verified: false, weight: 3}], address: {amount: 0, band: [], bonus: null, discount: [], rank: 250, review: {s: "0/4"}, risk: null, total: 0}, meta: {segment: "true"}, qty: 250, since: "2025-03-20T10:15:30Z", vip: true}}], + {input: {order: {qty: 100, vip: true, since: "2030-12-31", accounts: [{weight: 0.25, verified: false, parts: [{days: 0.000001, tier: "gold"}, {days: 2, tier: "silver"}]}, {weight: 100, verified: true, parts: [{days: 65, tier: "gold"}, {days: 250, tier: "silver"}]}, {weight: 10, verified: true, parts: [{days: 0.5, tier: "bronze"}, {days: 0.000001, tier: "bronze"}]}], address: {amount: 123456789.123}}}, goals: ["acct.flag"], output: {order: {accounts: [{flag: [true], parts: [{days: 0.000001, tier: "gold"}, {days: 2, tier: "silver"}], verified: false, weight: 0.25}, {flag: [true], parts: [{days: 65, tier: "gold"}, {days: 250, tier: "silver"}], verified: true, weight: 100}, {flag: [true], parts: [{days: 0.5, tier: "bronze"}, {days: 0.000001, tier: "bronze"}], verified: true, weight: 10}], address: {amount: 123456789.123}, qty: 100, since: "2030-12-31", vip: true}}}, + {input: {order: {qty: 50, vip: true, since: "1990-06-15", accounts: [{weight: 10, verified: false, parts: [{days: 100, tier: "bronze"}, {days: 5, tier: "bronze"}]}, {weight: 0.5, verified: false, parts: [{days: 1000, tier: "bronze"}]}], address: {amount: 1.5}}}, goals: ["acct.tag"], output: {order: {accounts: [{parts: [{days: 100, tier: "bronze"}, {days: 5, tier: "bronze"}], tag: 1.5, verified: false, weight: 10}, {parts: [{days: 1000, tier: "bronze"}], tag: 1.5, verified: false, weight: 0.5}], address: {amount: 1.5, bonus: null, rank: 50, review: {s: "1.5/5"}, total: 1.5}, meta: {segment: "false"}, qty: 50, since: "1990-06-15", vip: true}}}, + {input: {order: {qty: 99.99, vip: true, since: "2024-01-01", accounts: [{weight: 2, verified: true, parts: [{days: 250, tier: "bronze"}, {days: 0.1, tier: "gold"}]}, {weight: 0.25, verified: true, parts: [{days: 1, tier: "silver"}, {days: 2.50, tier: "gold"}, {days: 0.25, tier: "gold"}]}], address: {amount: 5}}}, goals: ["acct.tag", "address.rank", "address.risk"], output: {order: {accounts: [{parts: [{days: 250, tier: "bronze"}, {days: 0.1, tier: "gold"}], tag: 99.99, verified: true, weight: 2}, {parts: [{days: 1, tier: "silver"}, {days: 2.50, tier: "gold"}, {days: 0.25, tier: "gold"}], tag: 99.99, verified: true, weight: 0.25}], address: {amount: 5, bonus: null, rank: 99.99, review: {s: "5/5"}, risk: null, total: 5}, meta: {segment: "false"}, qty: 99.99, since: "2024-01-01", vip: true}}}, + {input: {order: {qty: 1, vip: true, since: "1990-06-15", accounts: [{weight: 5, verified: false, parts: [{days: 1, tier: "gold"}, {days: 1.5, tier: "bronze"}]}], address: {amount: 1}, extraField: {nested: true}}}, goals: ["address.risk", "address.discount"], output: {order: {accounts: [{parts: [{days: 1, tier: "gold"}, {days: 1.5, tier: "bronze"}], verified: false, weight: 5}], address: {amount: 1, band: [false], bonus: null, discount: [5], rank: 1, review: {s: "1/5"}, risk: null, total: 1}, extraField: {nested: true}, meta: {segment: "false"}, qty: 1, since: "1990-06-15", vip: true}}}, + {input: {order: {qty: 0.25, vip: false, since: "2030-12-31", accounts: [{weight: 2, verified: true, parts: [{days: 50, tier: "gold"}, {days: 100, tier: "gold"}]}, {weight: 10, verified: true, parts: [{days: 250, tier: "bronze"}, {days: 50, tier: "silver"}]}], address: {amount: -0.5}}}, goals: ["address.review", "acct.tag", "acct.share"], output: {order: {accounts: [{parts: [{days: 50, tier: "gold"}, {days: 100, tier: "gold"}], points: "x", share: [{days: 50, tier: "gold"}, {days: 100, tier: "gold"}], tag: 0.25, verified: true, weight: 2}, {parts: [{days: 250, tier: "bronze"}, {days: 50, tier: "silver"}], points: "x", share: [{days: 250, tier: "bronze"}, {days: 50, tier: "silver"}], tag: 0.25, verified: true, weight: 10}], address: {amount: -0.5, bonus: false, rank: 0.25, review: {s: "-0.5/4"}, total: -0.5}, meta: {segment: "true"}, qty: 0.25, since: "2030-12-31", vip: false}}}, + {input: {order: {qty: 1.5, vip: false, since: "1990-06-15", accounts: [{weight: 0.5, verified: false, parts: []}, {weight: 50, verified: false, parts: []}, {weight: 0.000001, verified: false, parts: [{days: 7.25, tier: "gold"}, {days: 1, tier: "gold"}, {days: 1.5, tier: "gold"}]}, {weight: 2, verified: false, parts: [{days: 0.5, tier: "bronze"}, {days: 10, tier: "silver"}]}, {weight: 1000000, verified: false, parts: []}, {weight: 250, verified: false, parts: [{days: 1.5, tier: "silver"}]}, {weight: 50, verified: true, parts: []}, {weight: 5, verified: true, parts: [{days: 1000, tier: "gold"}, {days: 250, tier: "silver"}, {days: 99.99, tier: "gold"}]}], address: {amount: 0.000001}}}, goals: ["address.rank", "address.bonus"], output: {order: {accounts: [{parts: [], points: "x", verified: false, weight: 0.5}, {parts: [], points: "x", verified: false, weight: 50}, {parts: [{days: 7.25, tier: "gold"}, {days: 1, tier: "gold"}, {days: 1.5, tier: "gold"}], points: "x", verified: false, weight: 0.000001}, {parts: [{days: 0.5, tier: "bronze"}, {days: 10, tier: "silver"}], points: "x", verified: false, weight: 2}, {parts: [], points: "x", verified: false, weight: 1000000}, {parts: [{days: 1.5, tier: "silver"}], points: "x", verified: false, weight: 250}, {parts: [], points: "x", verified: true, weight: 50}, {parts: [{days: 1000, tier: "gold"}, {days: 250, tier: "silver"}, {days: 99.99, tier: "gold"}], points: "x", verified: true, weight: 5}], address: {amount: 0.000001, bonus: false, rank: 1.5, total: 0.000001}, qty: 1.5, since: "1990-06-15", vip: false}}}, + {input: {order: {qty: 100, vip: true, since: "2024-02-29", accounts: [{weight: -500, verified: false, parts: [{days: 10, tier: "silver"}, {days: 0.5, tier: "gold"}, {days: 100, tier: "gold"}]}], address: {amount: 1000}}}, goals: ["address.rank", "acct.flag"], output: {order: {accounts: [{flag: [true], parts: [{days: 10, tier: "silver"}, {days: 0.5, tier: "gold"}, {days: 100, tier: "gold"}], verified: false, weight: -500}], address: {amount: 1000, rank: 100, total: 1000}, qty: 100, since: "2024-02-29", vip: true}}}, + {input: {order: {qty: 50, vip: false, since: "2000-01-01", accounts: [{weight: 99999999999999999999, verified: true, parts: [{days: 100, tier: "gold"}]}, {weight: 10, verified: true, parts: [{days: 10, tier: "silver"}, {days: 0.5, tier: "gold"}, {days: 1.5, tier: "silver"}]}, {weight: 50, verified: true, parts: [{days: 50, tier: "gold"}, {days: 50, tier: "bronze"}, {days: 7.25, tier: "gold"}]}], address: {amount: 5}}}, goals: ["address.review", "order.meta.segment", "acct.tag"], output: {order: {accounts: [{parts: [{days: 100, tier: "gold"}], points: "x", tag: 5, verified: true, weight: 99999999999999999999}, {parts: [{days: 10, tier: "silver"}, {days: 0.5, tier: "gold"}, {days: 1.5, tier: "silver"}], points: "x", tag: 5, verified: true, weight: 10}, {parts: [{days: 50, tier: "gold"}, {days: 50, tier: "bronze"}, {days: 7.25, tier: "gold"}], points: "x", tag: 5, verified: true, weight: 50}], address: {amount: 5, bonus: false, rank: 50, review: {s: "5/5"}, total: 5}, meta: {segment: "false"}, qty: 50, since: "2000-01-01", vip: false}}}, + {input: {order: {qty: 250, vip: true, since: "2030-12-31", accounts: [{weight: null, verified: true, parts: [{days: 10, tier: "silver"}, {days: 2, tier: "gold"}, {days: 1000000, tier: "bronze"}]}, {weight: 250, verified: false, parts: [{days: 0.25, tier: "gold"}]}], address: {amount: 5}}}, goals: ["acct.tag", "address.rank", "acct.flag"], output: "!error: ExpressionFailed"}, + {input: {order: {qty: 1, vip: false, since: "not a date", accounts: [{weight: 50, verified: true, parts: [{days: 1.5, tier: "bronze"}, {days: 2, tier: "silver"}, {days: 2, tier: "gold"}]}, {weight: 250, verified: false, parts: []}, {weight: 10, verified: false, parts: [{days: 2, tier: "silver"}]}, {weight: 2, verified: true, parts: [{days: 1000, tier: "gold"}, {days: 100, tier: "gold"}, {days: 1000, tier: "gold"}]}, {weight: 1, verified: false, parts: [{days: 1000, tier: "bronze"}, {days: 2, tier: "silver"}]}, {weight: 2, verified: true, parts: [{days: 1000, tier: "silver"}, {days: 1.5, tier: "gold"}, {days: 1, tier: "bronze"}]}, {weight: 3, verified: false, parts: [{days: 99999999999999999999, tier: "gold"}, {days: 50, tier: "gold"}]}, {weight: 100, verified: false, parts: [{days: 0.25, tier: "gold"}]}, {weight: 2, verified: false, parts: [{days: 250, tier: "gold"}, {days: 0.5, tier: "gold"}, {days: 1, tier: "gold"}]}, {weight: 100, verified: true, parts: [{days: 10, tier: "silver"}, {days: 250, tier: "silver"}, {days: 3, tier: "silver"}]}, {weight: 1, verified: true, parts: [{days: 0.25, tier: "gold"}, {days: 3, tier: "gold"}]}, {weight: 2.50, verified: true, parts: []}, {weight: 50, verified: true, parts: [{days: 2, tier: "gold"}, {days: 1e3, tier: "silver"}]}, {weight: 3, verified: false, parts: [{days: 0.5, tier: "gold"}, {days: 0.000001, tier: "gold"}]}], address: {amount: 250}}}, goals: ["acct.share", "address.risk"], output: "!error: InputValidationFailed"}, + {input: {order: {qty: 3, vip: true, since: "1990-06-15", accounts: [{weight: 50, verified: false, parts: []}], address: {amount: 1.5}}}, goals: ["acct.flag", "address.discount", "address.total"], output: {order: {accounts: [{flag: [true], parts: [], verified: false, weight: 50}], address: {amount: 1.5, band: [], discount: [3], rank: 3, review: {s: "1.5/5"}, total: 1.5}, meta: {segment: "false"}, qty: 3, since: "1990-06-15", vip: true}}}, + {input: {order: {qty: 7.25, vip: false, since: "2025-03-20", accounts: [{weight: 1000, verified: false, parts: [{days: 7.25, tier: "gold"}]}, {weight: 1000, verified: false, parts: [{days: 2, tier: "gold"}, {days: 99999999999999999999, tier: "bronze"}]}, {weight: 100, verified: true, parts: [{days: 0.5, tier: "gold"}, {days: 50, tier: "silver"}]}, {weight: 1000, verified: true, parts: []}, {weight: 0.25, verified: false, parts: [{days: 1000, tier: "gold"}, {days: 99999999999999999999, tier: "gold"}]}], address: {amount: 5}}}, goals: ["address.rank", "address.discount"], output: {order: {accounts: [{parts: [{days: 7.25, tier: "gold"}], verified: false, weight: 1000}, {parts: [{days: 2, tier: "gold"}, {days: 99999999999999999999, tier: "bronze"}], verified: false, weight: 1000}, {parts: [{days: 0.5, tier: "gold"}, {days: 50, tier: "silver"}], verified: true, weight: 100}, {parts: [], verified: true, weight: 1000}, {parts: [{days: 1000, tier: "gold"}, {days: 99999999999999999999, tier: "gold"}], verified: false, weight: 0.25}], address: {amount: 5, band: [], discount: [], rank: 7.25, review: {s: "5/5"}, total: 5}, meta: {segment: "false"}, qty: 7.25, since: "2025-03-20", vip: false}}}, + [{order: {qty: 1, vip: true, since: "2030-12-31", accounts: [{weight: 65, verified: true, parts: [{days: -1, tier: "gold"}, {days: 1, tier: "silver"}]}, {weight: 250, verified: false, parts: [{days: 250, tier: "silver"}, {days: 250, tier: "bronze"}, {days: 1000, tier: "gold"}]}, {weight: 50, verified: true, parts: [{days: -0.01, tier: "bronze"}, {days: 18, tier: "gold"}, {days: 116, tier: "gold"}]}, {weight: 2, verified: false, parts: [{days: 1e3, tier: "gold"}, {days: 100, tier: "gold"}]}, {weight: 100, verified: true, parts: [{days: 1000, tier: "gold"}, {days: 99.99, tier: "bronze"}]}], address: {amount: 1.5}, extraField: {nested: true}}}, {order: {accounts: [{flag: [true], parts: [{days: -1, tier: "gold"}, {days: 1, tier: "silver"}], share: [], tag: 1, verified: true, weight: 65}, {flag: [true], parts: [{days: 250, tier: "silver"}, {days: 250, tier: "bronze"}, {days: 1000, tier: "gold"}], share: [{days: 250, tier: "silver"}, {days: 250, tier: "bronze"}, {days: 1000, tier: "gold"}], tag: 1, verified: false, weight: 250}, {flag: [true], parts: [{days: -0.01, tier: "bronze"}, {days: 18, tier: "gold"}, {days: 116, tier: "gold"}], share: [{days: 18, tier: "gold"}, {days: 116, tier: "gold"}], tag: 1, verified: true, weight: 50}, {flag: [true], parts: [{days: 1000, tier: "gold"}, {days: 100, tier: "gold"}], share: [{days: 1000, tier: "gold"}, {days: 100, tier: "gold"}], tag: 1, verified: false, weight: 2}, {flag: [true], parts: [{days: 1000, tier: "gold"}, {days: 99.99, tier: "bronze"}], share: [{days: 1000, tier: "gold"}, {days: 99.99, tier: "bronze"}], tag: 1, verified: true, weight: 100}], address: {amount: 1.5, band: [false], bonus: null, discount: [4], rank: 1, review: {s: "1.5/4"}, risk: null, total: 1.5}, extraField: {nested: true}, meta: {segment: "true"}, qty: 1, since: "2030-12-31", vip: true}}], + ], +} + +// seed 352100 (attempt 0) +{ + name: "goals 22: tenant/loans + address: 3 assertion, 6 expression, 1 match, 2 table; 3 root, 13 per-member, 1 top-level computed", + policy: { + models: {tenant: {income: "number", limit: "number", label: "string", loans: "loan[]", address: "address"}, loan: {qty: "number", score: "number", plan: "string(basic|plus|premium|trial)"}, address: {balance: "number"}}, + blocks: [ + {expression: "tenant.calc.summary", value: "(split(string(tenant.address.balance <= 2), '-')[1] ?? 'none')"}, + {expression: "tenant.segment", value: "filter(tenant.loans, #.qty in [39..64])"}, + {expression: "loan.flag", value: "{a: tenant.label in ['high', 'low']}"}, + {expression: "loan.adjusted", value: "{s: (loan.flag.a and loan.points), v: `${tenant.calc.summary}/${(tenant.income % (abs(18) + 1))}`, n: loan.plan in ['basic', 'trial']}"}, + {assertion: "band", conditions: [["or", "all(tenant.loans, #.score == #.qty)", 1], ["and", "all(tenant.loans, (#.points and #.points))", 0], ["or", "sum(map(tenant.segment, (#.score * #.qty))) <= 5", 0], ["and", "tenant.address.balance < tenant.income", 1], ["or", "tenant.income in [39..163]", 1]]}, + {assertion: "loan.decision", conditions: [["or", "((band or loan.flag.a) and loan.plan != 'plus')", 1], "sum(map(tenant.segment, -(#.score))) >= 18"]}, + {expression: "loan.meta.review", value: "map(tenant.loans, (((#.meta.fee ?? 0) % (abs((#.meta.fee ?? 0)) + 1)) * (#.decision ? (#.meta.fee ?? 0) : (#.meta.fee ?? 0))))"}, + {expression: "address.eligible", value: "address.balance <= tenant.limit"}, + {table: "t8", inputs: ["tenant.label", "loan.adjusted.v"], outputs: ["loan.meta.fee", "loan.margin[]"], rules: [ + ["", "'high', 'x'", "(max(map(tenant.loans, #.score)) ?? 0)", "tenant.limit"], + ["", "", "tenant.limit", "loan.qty"], + ["'ok', 'A1'", "'ok'", "len(tenant.loans)", "-(loan.score)"], + ["$ != 'gold'", "", "", "loan.score"], + ["", "'Oslo', 'VIP'", "(loan.points ? tenant.limit : loan.qty)", "loan.score"], + ["'x'", "startsWith($, 'A1')", "1.5", "tenant.limit"], + ]}, + {assertion: "loan.points", conditions: [["or", "tenant.label in ['none', 'a']", 1]]}, + {table: "t12", inputs: ["loan.adjusted.n", "loan.adjusted.n", "loan.points"], outputs: ["loan.flags.total", "loan.surcharge"], rules: [ + ["false", "false", "false", "", "loan.adjusted.v"], + ["", "false", "true", "tenant.income", ""], + ["", "", "", "tenant.limit", "tenant.risk"], + ]}, + {match: "tenant.risk", arms: [["(band or band)", "(not (band) ? tenant.label : trim(tenant.calc.summary))"], ["tenant.income == 10", "(band ? tenant.label : tenant.calc.summary)"], ["", "upper(tenant.label)"]]}, + ], + }, + cases: [ + {input: {tenant: {income: 7.25, limit: -0.5, label: "a-b-c", loans: [{qty: 18, score: 2, plan: "basic"}, {qty: 2, score: 2, plan: "trial"}], address: {balance: 3}}}, goals: ["loan.flag"], output: {tenant: {address: {balance: 3}, income: 7.25, label: "a-b-c", limit: -0.5, loans: [{flag: {a: false}, plan: "basic", qty: 18, score: 2}, {flag: {a: false}, plan: "trial", qty: 2, score: 2}]}}}, + {input: {tenant: {income: -500, limit: 7.25, label: "O'Neil", loans: [{qty: -500, score: 7.25, plan: "basic"}], address: {balance: 0}}}, goals: ["loan.points"], output: {tenant: {address: {balance: 0}, income: -500, label: "O'Neil", limit: 7.25, loans: [{plan: "basic", points: false, qty: -500, score: 7.25}]}}}, + {input: {tenant: {income: 2, limit: 2.50, label: "a-b-c", loans: [{qty: 18, score: 2, plan: "plus"}, {qty: 1.5, score: -0.01, plan: "basic"}], address: {balance: -0.5}}}, goals: ["tenant.segment", "loan.surcharge", "band"], output: {band: false, tenant: {address: {balance: -0.5}, calc: {summary: "none"}, income: 2, label: "a-b-c", limit: 2.50, loans: [{adjusted: {n: false, s: false, v: "none/2"}, flag: {a: false}, flags: {total: 2.50}, plan: "plus", points: false, qty: 18, score: 2, surcharge: "none/2"}, {adjusted: {n: true, s: false, v: "none/2"}, flag: {a: false}, flags: {total: 2.50}, plan: "basic", points: false, qty: 1.5, score: -0.01, surcharge: "A-B-C"}], risk: "A-B-C", segment: []}}}, + {input: {tenant: {income: 2, limit: -0.01, label: "12", loans: [{qty: 250, score: 1000000, plan: "premium"}, {qty: -0.01, score: 2, plan: "basic"}], address: {balance: -0.01}}}, goals: ["loan.points", "loan.meta.fee", "loan.flags.total"], output: {band: false, tenant: {address: {balance: -0.01}, calc: {summary: "none"}, income: 2, label: "12", limit: -0.01, loans: [{adjusted: {n: false, s: false, v: "none/2"}, flag: {a: false}, flags: {total: -0.01}, margin: [250, 1000000], meta: {fee: -0.01}, plan: "premium", points: false, qty: 250, score: 1000000, surcharge: "none/2"}, {adjusted: {n: true, s: false, v: "none/2"}, flag: {a: false}, flags: {total: -0.01}, margin: [-0.01, 2], meta: {fee: -0.01}, plan: "basic", points: false, qty: -0.01, score: 2, surcharge: "12"}], risk: "12", segment: []}}}, + {input: {tenant: {income: 0, limit: 0.1, label: "retail", loans: [], address: {balance: -0.5}}}, goals: ["loan.flags.total", "loan.margin"], output: {tenant: {address: {balance: -0.5}, calc: {summary: "none"}, income: 0, label: "retail", limit: 0.1, loans: []}}}, + {input: {tenant: {income: 1000000, limit: 250, label: "A1", loans: [], address: {balance: -0.01}}}, goals: ["band", "tenant.segment", "address.eligible"], output: {band: true, tenant: {address: {balance: -0.01, eligible: true}, income: 1000000, label: "A1", limit: 250, loans: [], segment: []}}}, + {input: {tenant: {income: 1.5, limit: -0.01, label: "Oslo", loans: [{qty: 65, score: 1, plan: 5}, {qty: 1000000, score: 2, plan: "trial"}, {qty: 18, score: 2, plan: "basic"}, {qty: 2, score: 18, plan: "basic"}], address: {balance: 100}}}, goals: ["loan.meta.fee", "band"], output: "!error: InputValidationFailed"}, + {input: {tenant: {income: 250, limit: 1000, label: "US", loans: [{qty: 194, score: 2, plan: "trial"}, {qty: -0, score: 1000, plan: "trial"}, {qty: 3, score: 132, plan: "plus"}, {qty: 123456789.123, score: 1e3, plan: "basic"}, {qty: 5, score: 123456789.123, plan: "basic"}, {qty: 100, score: 2, plan: "basic"}, {qty: 100, score: -1, plan: "basic"}, {qty: 18, score: -500, plan: "basic"}, {qty: 99999999999999999999, score: 2, plan: "plus"}, {qty: 18, score: 5, plan: "trial"}], address: {balance: 18}}}, goals: ["loan.adjusted", "loan.flag"], output: {tenant: {address: {balance: 18}, calc: {summary: "none"}, income: 250, label: "US", limit: 1000, loans: [{adjusted: {n: true, s: false, v: "none/3"}, flag: {a: false}, plan: "trial", points: false, qty: 194, score: 2}, {adjusted: {n: true, s: false, v: "none/3"}, flag: {a: false}, plan: "trial", points: false, qty: 0, score: 1000}, {adjusted: {n: false, s: false, v: "none/3"}, flag: {a: false}, plan: "plus", points: false, qty: 3, score: 132}, {adjusted: {n: true, s: false, v: "none/3"}, flag: {a: false}, plan: "basic", points: false, qty: 123456789.123, score: 1000}, {adjusted: {n: true, s: false, v: "none/3"}, flag: {a: false}, plan: "basic", points: false, qty: 5, score: 123456789.123}, {adjusted: {n: true, s: false, v: "none/3"}, flag: {a: false}, plan: "basic", points: false, qty: 100, score: 2}, {adjusted: {n: true, s: false, v: "none/3"}, flag: {a: false}, plan: "basic", points: false, qty: 100, score: -1}, {adjusted: {n: true, s: false, v: "none/3"}, flag: {a: false}, plan: "basic", points: false, qty: 18, score: -500}, {adjusted: {n: false, s: false, v: "none/3"}, flag: {a: false}, plan: "plus", points: false, qty: 99999999999999999999, score: 2}, {adjusted: {n: true, s: false, v: "none/3"}, flag: {a: false}, plan: "trial", points: false, qty: 18, score: 5}]}}}, + {input: {tenant: {income: -1, limit: 1000000, label: "retail", loans: [{qty: 18, score: 1e3, plan: "plus"}], address: {balance: 1.5}}}, goals: ["band", "tenant.calc.summary", "loan.margin"], output: {band: false, tenant: {address: {balance: 1.5}, calc: {summary: "none"}, income: -1, label: "retail", limit: 1000000, loans: [{adjusted: {n: false, s: false, v: "none/-1"}, flag: {a: false}, margin: [18, 1000], meta: {fee: 1000000}, plan: "plus", points: false, qty: 18, score: 1000}], segment: []}}}, + {input: {tenant: {income: 18, limit: null, label: "Oslo", loans: [], address: {balance: -1}}}, goals: ["address.eligible", "loan.adjusted"], output: "!error: MissingRequiredInputs"}, + [{tenant: {income: 0, limit: 0, label: "ok", loans: [{qty: 18, score: 250, plan: "plus"}], address: {balance: 18}}}, {band: false, tenant: {address: {balance: 18, eligible: false}, calc: {summary: "none"}, income: 0, label: "ok", limit: 0, loans: [{adjusted: {n: false, s: false, v: "none/0"}, decision: false, flag: {a: false}, flags: {total: 0}, margin: [18, 250], meta: {fee: 0, review: [0]}, plan: "plus", points: false, qty: 18, score: 250, surcharge: "none/0"}], segment: []}}], + [{tenant: {income: 1000000, limit: 18, label: "DE", loans: [{qty: 10, score: 0.1, plan: "basic"}, {qty: 1.5, score: 99999999999999999999, plan: "plus"}], address: {balance: 2}}}, {band: false, tenant: {address: {balance: 2, eligible: true}, calc: {summary: "none"}, income: 1000000, label: "DE", limit: 18, loans: [{adjusted: {n: true, s: false, v: "none/11"}, decision: false, flag: {a: false}, flags: {total: 18}, margin: [10, 0.1], meta: {fee: 18, review: [324, 324]}, plan: "basic", points: false, qty: 10, score: 0.1, surcharge: "DE"}, {adjusted: {n: false, s: false, v: "none/11"}, decision: false, flag: {a: false}, flags: {total: 18}, margin: [1.5, 99999999999999999999], meta: {fee: 18, review: [324, 324]}, plan: "plus", points: false, qty: 1.5, score: 99999999999999999999, surcharge: "none/11"}], risk: "DE", segment: []}}], + {input: {tenant: {income: 10, limit: 65, label: "DE", loans: [{qty: 1e3, score: 1, plan: "trial"}, {qty: 10, score: 1.5, plan: "trial"}, {qty: 250, score: 381, plan: "plus"}, {qty: 0.25, score: 1, plan: "plus"}], address: {balance: 1000000}}}, goals: ["loan.decision"], output: {band: false, tenant: {address: {balance: 1000000}, income: 10, label: "DE", limit: 65, loans: [{decision: false, flag: {a: false}, plan: "trial", points: false, qty: 1000, score: 1}, {decision: false, flag: {a: false}, plan: "trial", points: false, qty: 10, score: 1.5}, {decision: false, flag: {a: false}, plan: "plus", points: false, qty: 250, score: 381}, {decision: false, flag: {a: false}, plan: "plus", points: false, qty: 0.25, score: 1}], segment: []}}}, + {input: {tenant: {limit: 1, label: "A1", loans: [{qty: 7.25, score: -500, plan: "trial"}, {qty: 10, score: 5, plan: "basic"}, {qty: 10, score: 1, plan: "basic"}, {qty: 0.25, score: 0.1, plan: "plus"}, {qty: 250, score: 65, plan: "premium"}, {qty: 5, score: 5, plan: "basic"}, {qty: 0.25, score: 0.1, plan: "plus"}, {qty: 99.99, score: 100, plan: "trial"}], address: {balance: 498}}}, goals: ["tenant.calc.summary", "loan.decision", "loan.surcharge"], output: "!error: MissingRequiredInputs"}, + {input: {tenant: {income: 2, limit: 2.50, loans: [], address: {balance: 0.5}}}, goals: ["loan.surcharge", "loan.meta.fee"], output: "!error: MissingRequiredInputs"}, + {input: {tenant: {income: 5, limit: 2, label: "abc", loans: [{qty: 250, score: 10, plan: "plus"}, {qty: -0.01, score: 494, plan: "basic"}], address: {balance: 2}}}, goals: ["loan.meta.review", "loan.meta.fee"], output: {band: false, tenant: {address: {balance: 2}, calc: {summary: "none"}, income: 5, label: "abc", limit: 2, loans: [{adjusted: {n: false, s: false, v: "none/5"}, decision: false, flag: {a: false}, margin: [250, 10], meta: {fee: 2, review: [4, 4]}, plan: "plus", points: false, qty: 250, score: 10}, {adjusted: {n: true, s: false, v: "none/5"}, decision: false, flag: {a: false}, margin: [-0.01, 494], meta: {fee: 2, review: [4, 4]}, plan: "basic", points: false, qty: -0.01, score: 494}], segment: []}}}, + {input: {tenant: {income: 1.5, limit: 7.25, label: "DE", loans: [{qty: 25, score: 0.1, plan: "trial"}], address: {balance: 1.5}}}, goals: ["loan.points", "tenant.calc.summary"], output: {tenant: {address: {balance: 1.5}, calc: {summary: "none"}, income: 1.5, label: "DE", limit: 7.25, loans: [{plan: "trial", points: false, qty: 25, score: 0.1}]}}}, + {input: {tenant: {income: 100, limit: 5, label: "Oslo", loans: [{qty: 0.000001, score: 1e3, plan: "trial"}], address: {balance: 0.5}}}, goals: ["loan.flags.total"], output: {band: true, tenant: {address: {balance: 0.5}, calc: {summary: "none"}, income: 100, label: "Oslo", limit: 5, loans: [{adjusted: {n: true, s: false, v: "none/5"}, flag: {a: false}, flags: {total: 5}, plan: "trial", points: false, qty: 0.000001, score: 1000, surcharge: "none"}], risk: "none", segment: []}}}, + {input: {tenant: {income: 0.000001, limit: 0.000001, label: "ok", loans: [{qty: 2, plan: "premium"}, {qty: 99999999999999999999, score: 2, plan: "plus"}, {qty: 1000000, score: 99.99, plan: "trial"}], address: {balance: 18}}}, goals: ["loan.decision"], output: {band: false, tenant: {address: {balance: 18}, income: 0.000001, label: "ok", limit: 0.000001, loans: [{decision: false, flag: {a: false}, plan: "premium", points: false, qty: 2}, {decision: false, flag: {a: false}, plan: "plus", points: false, qty: 99999999999999999999, score: 2}, {decision: false, flag: {a: false}, plan: "trial", points: false, qty: 1000000, score: 99.99}], segment: []}}}, + [{tenant: {income: 99.99, limit: 10, label: "US", loans: [{qty: 0.5, score: 5, plan: "basic"}, {qty: 1.5, score: -500, plan: "trial"}, {qty: 123456789.123, score: 1000, plan: "basic"}, {qty: 2, score: 1, plan: "basic"}], address: {balance: 2}, extraField: 1}}, {band: true, tenant: {address: {balance: 2, eligible: true}, calc: {summary: "none"}, extraField: 1, income: 99.99, label: "US", limit: 10, loans: [{adjusted: {n: true, s: false, v: "none/4.99"}, decision: true, flag: {a: false}, flags: {total: 10}, margin: [0.5, 5], meta: {fee: 10, review: [100, 100, 100, 100]}, plan: "basic", points: false, qty: 0.5, score: 5, surcharge: "none"}, {adjusted: {n: true, s: false, v: "none/4.99"}, decision: true, flag: {a: false}, flags: {total: 10}, margin: [1.5, -500], meta: {fee: 10, review: [100, 100, 100, 100]}, plan: "trial", points: false, qty: 1.5, score: -500, surcharge: "none"}, {adjusted: {n: true, s: false, v: "none/4.99"}, decision: true, flag: {a: false}, flags: {total: 10}, margin: [123456789.123, 1000], meta: {fee: 10, review: [100, 100, 100, 100]}, plan: "basic", points: false, qty: 123456789.123, score: 1000, surcharge: "none"}, {adjusted: {n: true, s: false, v: "none/4.99"}, decision: true, flag: {a: false}, flags: {total: 10}, margin: [2, 1], meta: {fee: 10, review: [100, 100, 100, 100]}, plan: "basic", points: false, qty: 2, score: 1, surcharge: "none"}], risk: "none", segment: []}}], + {input: {tenant: {income: -0, limit: 250, label: "x", loans: [], address: {balance: 18}}}, goals: ["loan.decision", "loan.meta.fee", "loan.surcharge"], output: {band: true, tenant: {address: {balance: 18}, calc: {summary: "none"}, income: 0, label: "x", limit: 250, loans: [], segment: []}}}, + {input: {tenant: {income: 10, limit: 2, label: " pad ", loans: [{qty: 99999999999999999999, score: 250, plan: "plus"}], address: {balance: 7.25}}}, goals: ["loan.flags.total"], output: {tenant: {address: {balance: 7.25}, calc: {summary: "none"}, income: 10, label: " pad ", limit: 2, loans: [{adjusted: {n: false, s: false, v: "none/10"}, flag: {a: false}, flags: {total: 2}, plan: "plus", points: false, qty: 99999999999999999999, score: 250, surcharge: "none/10"}]}}}, + {input: {tenant: {income: 18, limit: 1e3, label: "Oslo", loans: [{qty: -0.5, score: 123456789.123, plan: "basic"}], address: {balance: 1.5}}}, goals: ["loan.margin"], output: {tenant: {address: {balance: 1.5}, calc: {summary: "none"}, income: 18, label: "Oslo", limit: 1000, loans: [{adjusted: {n: true, s: false, v: "none/18"}, flag: {a: false}, margin: [-0.5, 123456789.123], meta: {fee: 1000}, plan: "basic", points: false, qty: -0.5, score: 123456789.123}]}}}, + {input: {tenant: {income: 2, limit: 0.5, label: "Oslo", loans: [], address: {balance: 0.000001}}}, goals: ["loan.points", "loan.flag", "tenant.segment"], output: {tenant: {address: {balance: 0.000001}, income: 2, label: "Oslo", limit: 0.5, loans: [], segment: []}}}, + {input: {tenant: {income: -0.5, limit: 1.5, label: "O'Neil", loans: [{qty: 18, score: 2, plan: "premium"}, {qty: 250, score: 0.5, plan: "premium"}], address: {balance: 7.25}}}, goals: ["loan.flag"], output: {tenant: {address: {balance: 7.25}, income: -0.5, label: "O'Neil", limit: 1.5, loans: [{flag: {a: false}, plan: "premium", qty: 18, score: 2}, {flag: {a: false}, plan: "premium", qty: 250, score: 0.5}]}}}, + {input: {tenant: {income: 100, limit: 7.25, label: "Oslo", loans: [{qty: -500, score: 1e3, plan: "trial"}], address: {balance: 10}}}, goals: ["tenant.risk", "loan.decision", "loan.points"], output: {band: true, tenant: {address: {balance: 10}, calc: {summary: "none"}, income: 100, label: "Oslo", limit: 7.25, loans: [{decision: true, flag: {a: false}, plan: "trial", points: false, qty: -500, score: 1000}], risk: "none", segment: []}}}, + {input: {tenant: {income: 18, limit: 1000, label: "x", loans: [{qty: 0.5, score: 2.50, plan: "basic"}, {qty: 0.000001, score: 250, plan: "basic"}, {qty: 0.5, score: 65, plan: "premium"}, {qty: 0.25, score: 7.25, plan: "premium"}], address: {balance: 3}}}, goals: ["loan.surcharge"], output: {band: false, tenant: {address: {balance: 3}, calc: {summary: "none"}, income: 18, label: "x", limit: 1000, loans: [{adjusted: {n: true, s: false, v: "none/18"}, flag: {a: false}, flags: {total: 1000}, plan: "basic", points: false, qty: 0.5, score: 2.50, surcharge: "X"}, {adjusted: {n: true, s: false, v: "none/18"}, flag: {a: false}, flags: {total: 1000}, plan: "basic", points: false, qty: 0.000001, score: 250, surcharge: "X"}, {adjusted: {n: false, s: false, v: "none/18"}, flag: {a: false}, flags: {total: 1000}, plan: "premium", points: false, qty: 0.5, score: 65, surcharge: "none/18"}, {adjusted: {n: false, s: false, v: "none/18"}, flag: {a: false}, flags: {total: 1000}, plan: "premium", points: false, qty: 0.25, score: 7.25, surcharge: "none/18"}], risk: "X", segment: []}}}, + {input: {tenant: {income: 65, limit: 0.1, label: "abc", loans: [{qty: 1.5, score: -500, plan: "trial"}, {qty: 18, score: 5, plan: "premium"}], address: {balance: 7.25}}}, goals: ["loan.points", "loan.flag", "tenant.risk"], output: {band: true, tenant: {address: {balance: 7.25}, calc: {summary: "none"}, income: 65, label: "abc", limit: 0.1, loans: [{flag: {a: false}, plan: "trial", points: false, qty: 1.5, score: -500}, {flag: {a: false}, plan: "premium", points: false, qty: 18, score: 5}], risk: "none", segment: []}}}, + {input: {tenant: {income: 0.25, limit: 2, label: "US", loans: [{qty: 0.1, score: 18, plan: "basic"}, {qty: 7.25, score: 2.50, plan: "basic"}], address: {balance: 3}, extraField: "x"}}, goals: ["loan.flag"], output: {tenant: {address: {balance: 3}, extraField: "x", income: 0.25, label: "US", limit: 2, loans: [{flag: {a: false}, plan: "basic", qty: 0.1, score: 18}, {flag: {a: false}, plan: "basic", qty: 7.25, score: 2.50}]}}}, + {input: {tenant: {income: 250, limit: 5, label: "", loans: [{qty: 2, score: -0.5, plan: "basic"}], address: {balance: 250}}}, goals: ["tenant.risk"], output: {band: false, tenant: {address: {balance: 250}, income: 250, label: "", limit: 5, loans: [{plan: "basic", points: false, qty: 2, score: -0.5}], risk: "", segment: []}}}, + ], +} + +// seed 352200 (attempt 0) +{ + name: "goals 23: shipment/vehicles/payments: 3 assertion, 7 expression, 2 table; 7 root, 8 per-member, 2 top-level computed", + policy: { + models: {shipment: {qty: "number", dueDate: "date?", active: "boolean", vehicles: "vehicle[]"}, vehicle: {rate: "number", channel: "string", dueDate: "date", payments: "payment[]"}, payment: {price: "number"}}, + blocks: [ + {expression: "shipment.health", value: "{a: string(shipment.qty), ok: (50 % (abs(shipment.qty) + 1))}"}, + {assertion: "shipment.ok", conditions: [["or", "some(shipment.vehicles, #.rate in [25..135))", 1], ["or", "shipment.qty in (40..85)", 1], "shipment.health.a == 'A1'", ["or", "isNumeric(`${shipment.health.ok}/${shipment.active}`)", 0]]}, + {table: "t3", inputs: ["vehicle.rate"], outputs: ["vehicle.totals.risk", "vehicle.share", "vehicle.adjusted"], rules: [ + ["<= 18", "(shipment.active and shipment.ok)", "'retail'", "vehicle.channel"], + ["<= 3", "shipment.ok", "vehicle.channel", "shipment.health.a"], + ]}, + {expression: "vehicle.band", value: "map(vehicle.payments, ((#.price - #.price) % (abs(trunc(#.price)) + 1)))"}, + {table: "t5", inputs: ["(shipment.qty - shipment.health.ok)"], outputs: ["shipment.capped", "shipment.summary[]"], rules: [ + [">= 5", "shipment.active", "shipment.qty"], + ["", "shipment.ok", ""], + ["100, 100", "all(shipment.vehicles, #.rate == #.rate)", ""], + ["[3..105]", "(shipment.dueDate ?? d('2025-01-01')).isAfter(d('2025-03-20'), 'day')", "shipment.health.ok"], + ["!= 3", "shipment.ok", "shipment.health.ok"], + ["< 18", "shipment.health.a in ['none', 'retail']", "(shipment.qty % (abs(shipment.qty) + 1))"], + [">= 0.25", "(shipment.ok and shipment.active)", "100"], + ]}, + {assertion: "vehicle.points", conditions: [["or", "isNumeric(string(shipment.qty))", 0], ["or", "shipment.health.ok in [23..170]", 1], ["and", "matches(string(shipment.health.ok), '^[A-Z]')", 1], ["and", "trunc(shipment.health.ok) < shipment.qty", 1], ["or", "not ((vehicle.totals.risk ?? false))", 1]]}, + {expression: "fee", value: "(shipment.dueDate ?? d('2025-01-01')).isAfter(d('2025-03-20'), 'year')"}, + {expression: "vehicle.scores.net", value: "map(shipment.vehicles, #.rate)"}, + {expression: "vehicle.flag", value: "filter(vehicle.payments, #.price < #.price)"}, + {expression: "vehicle.penalty", value: "-(sum(map(vehicle.flag, #.price)))"}, + {expression: "shipment.bonus", value: "(shipment.dueDate ?? d('2025-01-01')).add(6, 'year')"}, + {assertion: "eligible", conditions: [["or", "(min(map(shipment.vehicles, #.penalty)) ?? 0) != 0.5", 2], ["and", "shipment.bonus < d('2025-03-20')", 0]]}, + ], + }, + cases: [ + {input: {shipment: {qty: 65, dueDate: "1990-06-15", active: false, vehicles: [{rate: null, channel: "a", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 123456789.123}]}, {rate: 5, channel: "é ü", dueDate: "1990-06-15", payments: [{price: 1}, {price: 7.25}]}, {rate: 18, channel: "US", dueDate: "2024-02-29", payments: [{price: 0.000001}]}, {rate: 10, channel: "A1", dueDate: "2024-02-29", payments: [{price: 1e3}, {price: -0.01}, {price: 5}]}]}}, goals: ["shipment.ok"], output: "!error: ExpressionFailed"}, + {input: {shipment: {qty: 100, dueDate: "2024-01-01", active: true, vehicles: [{rate: 1e3, channel: "", dueDate: "2024-01-01", payments: [{price: 50}]}]}}, goals: ["vehicle.flag", "shipment.summary"], output: {shipment: {active: true, capped: true, dueDate: "2024-01-01", health: {a: "100", ok: 50}, qty: 100, summary: [100, 50, 50, 100], vehicles: [{channel: "", dueDate: "2024-01-01", flag: [], payments: [{price: 50}], rate: 1000}]}}}, + {input: {shipment: {qty: 50, dueDate: "2030-12-31", active: false, vehicles: [{rate: 18, channel: "日本", dueDate: "2024-01-01", payments: [{price: 325}, {price: 99.99}]}, {rate: 18, channel: "", dueDate: "2025-03-20T10:15:30Z", payments: []}, {rate: 0, channel: "US", dueDate: "1990-06-15", payments: [{price: 0.25}, {price: -1}, {price: 65}]}]}}, goals: ["vehicle.totals.risk", "vehicle.penalty"], output: {shipment: {active: false, dueDate: "2030-12-31", health: {a: "50", ok: 50}, ok: false, qty: 50, vehicles: [{adjusted: "日本", channel: "日本", dueDate: "2024-01-01", flag: [], payments: [{price: 325}, {price: 99.99}], penalty: -0, rate: 18, share: "retail", totals: {risk: false}}, {adjusted: "", channel: "", dueDate: "2025-03-20T10:15:30Z", flag: [], payments: [], penalty: -0, rate: 18, share: "retail", totals: {risk: false}}, {adjusted: "US", channel: "US", dueDate: "1990-06-15", flag: [], payments: [{price: 0.25}, {price: -1}, {price: 65}], penalty: -0, rate: 0, share: "retail", totals: {risk: false}}]}}}, + {input: {shipment: {qty: 18, dueDate: "2024-02-29", active: true, vehicles: []}}, goals: ["vehicle.adjusted", "vehicle.totals.risk", "vehicle.band"], output: {shipment: {active: true, dueDate: "2024-02-29", qty: 18, vehicles: []}}}, + {input: {shipment: {qty: 0, dueDate: "2000-01-01", active: true, vehicles: []}}, goals: ["shipment.health", "vehicle.band", "shipment.summary"], output: {shipment: {active: true, capped: false, dueDate: "2000-01-01", health: {a: "0", ok: 0}, ok: false, qty: 0, summary: [0, 0], vehicles: []}}}, + {input: {shipment: {qty: 0.000001, active: true, vehicles: [{rate: 5, channel: "Oslo", dueDate: "2030-12-31", payments: [{price: 18}]}, {rate: 18, channel: "a", dueDate: "2024-01-01", payments: [{price: 2.50}, {price: 1000000}]}]}}, goals: ["shipment.ok", "fee", "vehicle.band"], output: {fee: false, shipment: {active: true, health: {a: "0.000001", ok: 0.999951}, ok: false, qty: 0.000001, vehicles: [{band: [0], channel: "Oslo", dueDate: "2030-12-31", payments: [{price: 18}], rate: 5}, {band: [0, 0], channel: "a", dueDate: "2024-01-01", payments: [{price: 2.50}, {price: 1000000}], rate: 18}]}}}, + {input: {shipment: {qty: 5, dueDate: "2024-02-29", active: true, vehicles: []}}, goals: ["vehicle.adjusted", "shipment.ok"], output: {shipment: {active: true, dueDate: "2024-02-29", health: {a: "5", ok: 2}, ok: false, qty: 5, vehicles: []}}}, + {input: {shipment: {qty: 18, dueDate: "2025-03-20", active: true, vehicles: [{rate: 18, channel: "DE", dueDate: "2025-03-20", payments: [{price: 0.5}]}, {rate: 1e3, channel: "", dueDate: "2024-02-29", payments: []}, {rate: 99999999999999999999, channel: "DE", dueDate: "2024-01-01", payments: [{price: -0.01}, {price: 1}, {price: 0.000001}]}, {rate: 0.5, channel: "A1", dueDate: "2030-12-31", payments: [{price: 3}]}, {rate: 0.000001, channel: "retail", dueDate: "1990-06-15", payments: []}]}}, goals: ["shipment.bonus", "shipment.capped"], output: {shipment: {active: true, bonus: "2031-03-20T00:00:00Z", capped: true, dueDate: "2025-03-20", health: {a: "18", ok: 12}, qty: 18, summary: [18, 12, 12, 18, 100], vehicles: [{channel: "DE", dueDate: "2025-03-20", payments: [{price: 0.5}], rate: 18}, {channel: "", dueDate: "2024-02-29", payments: [], rate: 1000}, {channel: "DE", dueDate: "2024-01-01", payments: [{price: -0.01}, {price: 1}, {price: 0.000001}], rate: 99999999999999999999}, {channel: "A1", dueDate: "2030-12-31", payments: [{price: 3}], rate: 0.5}, {channel: "retail", dueDate: "1990-06-15", payments: [], rate: 0.000001}]}}}, + {input: {shipment: {qty: 50, active: true, vehicles: [{rate: 100, channel: "gold", dueDate: "2025-03-20", payments: [{price: 99999999999999999999}, {price: 100}]}]}}, goals: ["vehicle.adjusted", "vehicle.flag", "vehicle.totals.risk"], output: {shipment: {active: true, qty: 50, vehicles: [{adjusted: null, channel: "gold", dueDate: "2025-03-20", flag: [], payments: [{price: 99999999999999999999}, {price: 100}], rate: 100, share: null, totals: {risk: null}}]}}}, + [{shipment: {dueDate: "2024-02-29", active: false, vehicles: [{rate: 1000000, channel: "A1", dueDate: "2024-02-29", payments: [{price: 0.5}, {price: 0.5}]}, {rate: -0, channel: "日本", dueDate: "2000-01-01", payments: [{price: 0.000001}]}]}}, "!error: MissingRequiredInputs"], + {input: {shipment: {qty: 65, dueDate: "2025-03-20T10:15:30Z", active: false, vehicles: [{rate: 50, channel: "a-b-c", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 1}, {price: 0.1}, {price: 0}]}, {rate: 18, channel: "A1", dueDate: "2000-01-01", payments: [{price: 99999999999999999999}, {price: 18}, {price: 18}]}]}}, goals: ["vehicle.flag", "vehicle.penalty", "shipment.bonus"], output: {shipment: {active: false, bonus: "2031-03-20T10:15:30Z", dueDate: "2025-03-20T10:15:30Z", qty: 65, vehicles: [{channel: "a-b-c", dueDate: "2025-03-20T10:15:30Z", flag: [], payments: [{price: 1}, {price: 0.1}, {price: 0}], penalty: -0, rate: 50}, {channel: "A1", dueDate: "2000-01-01", flag: [], payments: [{price: 99999999999999999999}, {price: 18}, {price: 18}], penalty: -0, rate: 18}]}}}, + {input: {shipment: {qty: 0.1, active: true, vehicles: [{rate: 1000, channel: "x-y", dueDate: "2025-03-20", payments: [{price: 7.25}, {price: 100}, {price: 0.000001}]}, {rate: 1, channel: "abc", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 65}, {price: 18}]}, {rate: 100, channel: "Oslo", dueDate: "2025-03-20", payments: [{price: 18}, {price: 1}]}, {rate: 0, channel: "A1", dueDate: "2024-02-29", payments: [{price: 18}]}, {rate: 99999999999999999999, channel: "a", dueDate: "2025-03-20", payments: []}]}}, goals: ["vehicle.totals.risk", "shipment.bonus"], output: {shipment: {active: true, bonus: "2031-01-01T00:00:00Z", health: {a: "0.1", ok: 0.5}, ok: false, qty: 0.1, vehicles: [{adjusted: null, channel: "x-y", dueDate: "2025-03-20", payments: [{price: 7.25}, {price: 100}, {price: 0.000001}], rate: 1000, share: null, totals: {risk: null}}, {adjusted: "abc", channel: "abc", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 65}, {price: 18}], rate: 1, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "Oslo", dueDate: "2025-03-20", payments: [{price: 18}, {price: 1}], rate: 100, share: null, totals: {risk: null}}, {adjusted: "A1", channel: "A1", dueDate: "2024-02-29", payments: [{price: 18}], rate: 0, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "a", dueDate: "2025-03-20", payments: [], rate: 99999999999999999999, share: null, totals: {risk: null}}]}}}, + {input: {shipment: {qty: 1, dueDate: "2000-01-01", active: true, vehicles: [{rate: -0.01, channel: "12", dueDate: "1990-06-15", payments: []}, {rate: 123456789.123, channel: "A1", dueDate: "2030-12-31", payments: [{price: -0}, {price: 0.000001}]}]}}, goals: ["vehicle.points", "vehicle.penalty", "shipment.health"], output: {shipment: {active: true, dueDate: "2000-01-01", health: {a: "1", ok: 0}, ok: false, qty: 1, vehicles: [{adjusted: "12", channel: "12", dueDate: "1990-06-15", flag: [], payments: [], penalty: -0, points: true, rate: -0.01, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "A1", dueDate: "2030-12-31", flag: [], payments: [{price: 0}, {price: 0.000001}], penalty: -0, points: true, rate: 123456789.123, share: null, totals: {risk: null}}]}}}, + {input: {shipment: {qty: 1, dueDate: "2024-01-01", active: false, vehicles: []}}, goals: ["shipment.ok", "vehicle.penalty"], output: {shipment: {active: false, dueDate: "2024-01-01", health: {a: "1", ok: 0}, ok: false, qty: 1, vehicles: []}}}, + [{shipment: {qty: 0.5, dueDate: "2000-01-01", active: true, vehicles: [{rate: 0.000001, channel: " pad ", dueDate: "2030-12-31", payments: [{price: 100}, {price: 1}, {price: 100}]}, {rate: -0.01, channel: "é ü", dueDate: "2024-02-29", payments: [{price: 5}, {price: 353}, {price: 223}]}, {rate: 100, channel: "A1", dueDate: "2024-01-01", payments: []}]}}, {eligible: true, fee: false, shipment: {active: true, bonus: "2006-01-01T00:00:00Z", capped: false, dueDate: "2000-01-01", health: {a: "0.5", ok: 0.5}, ok: false, qty: 0.5, summary: [0.5, 0.5], vehicles: [{adjusted: " pad ", band: [0, 0, 0], channel: " pad ", dueDate: "2030-12-31", flag: [], payments: [{price: 100}, {price: 1}, {price: 100}], penalty: -0, points: true, rate: 0.000001, scores: {net: [0.000001, -0.01, 100]}, share: "retail", totals: {risk: false}}, {adjusted: "é ü", band: [0, 0, 0], channel: "é ü", dueDate: "2024-02-29", flag: [], payments: [{price: 5}, {price: 353}, {price: 223}], penalty: -0, points: true, rate: -0.01, scores: {net: [0.000001, -0.01, 100]}, share: "retail", totals: {risk: false}}, {adjusted: null, band: [], channel: "A1", dueDate: "2024-01-01", flag: [], payments: [], penalty: -0, points: true, rate: 100, scores: {net: [0.000001, -0.01, 100]}, share: null, totals: {risk: null}}]}}], + {input: {shipment: {qty: 100, dueDate: "2024-02-29", active: true, vehicles: [{rate: 0.000001, channel: "gold", dueDate: "2024-02-29", payments: [{price: 0.000001}, {price: 3}]}, {rate: 0.1, channel: "", dueDate: "2000-01-01", payments: [{price: 18}, {price: 1000000}]}, {rate: 18, channel: "DE", dueDate: "2000-01-01", payments: [{price: 100}, {price: 18}, {price: 3}]}, {rate: 0.000001, channel: "DE", dueDate: "1990-06-15", payments: [{price: 0.000001}, {price: 2}, {price: 0.1}]}, {rate: 0.000001, channel: "VIP", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 0}, {price: 18}]}]}}, goals: ["vehicle.scores.net"], output: {shipment: {active: true, dueDate: "2024-02-29", qty: 100, vehicles: [{channel: "gold", dueDate: "2024-02-29", payments: [{price: 0.000001}, {price: 3}], rate: 0.000001, scores: {net: [0.000001, 0.1, 18, 0.000001, 0.000001]}}, {channel: "", dueDate: "2000-01-01", payments: [{price: 18}, {price: 1000000}], rate: 0.1, scores: {net: [0.000001, 0.1, 18, 0.000001, 0.000001]}}, {channel: "DE", dueDate: "2000-01-01", payments: [{price: 100}, {price: 18}, {price: 3}], rate: 18, scores: {net: [0.000001, 0.1, 18, 0.000001, 0.000001]}}, {channel: "DE", dueDate: "1990-06-15", payments: [{price: 0.000001}, {price: 2}, {price: 0.1}], rate: 0.000001, scores: {net: [0.000001, 0.1, 18, 0.000001, 0.000001]}}, {channel: "VIP", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 0}, {price: 18}], rate: 0.000001, scores: {net: [0.000001, 0.1, 18, 0.000001, 0.000001]}}]}}}, + [{shipment: {qty: 0, dueDate: "2000-01-01", active: true, vehicles: [{rate: 100, channel: "x-y", dueDate: "2025-03-20T10:15:30Z", payments: []}, {rate: 18, channel: "é ü", dueDate: "2025-03-20", payments: [{price: 1000}, {price: -0.01}, {price: 1e3}]}], extraField: {nested: true}}}, {eligible: true, fee: false, shipment: {active: true, bonus: "2006-01-01T00:00:00Z", capped: false, dueDate: "2000-01-01", extraField: {nested: true}, health: {a: "0", ok: 0}, ok: false, qty: 0, summary: [0, 0], vehicles: [{adjusted: null, band: [], channel: "x-y", dueDate: "2025-03-20T10:15:30Z", flag: [], payments: [], penalty: -0, points: true, rate: 100, scores: {net: [100, 18]}, share: null, totals: {risk: null}}, {adjusted: "é ü", band: [0, 0, 0], channel: "é ü", dueDate: "2025-03-20", flag: [], payments: [{price: 1000}, {price: -0.01}, {price: 1000}], penalty: -0, points: true, rate: 18, scores: {net: [100, 18]}, share: "retail", totals: {risk: false}}]}}], + {input: {shipment: {qty: 100, dueDate: "2024-02-29", active: false, vehicles: [{rate: 2.50, channel: "é ü", dueDate: "2024-01-01", payments: [{price: 100}, {price: 100}]}], extraField: {nested: true}}}, goals: ["fee", "vehicle.points", "vehicle.adjusted"], output: {fee: false, shipment: {active: false, dueDate: "2024-02-29", extraField: {nested: true}, health: {a: "100", ok: 50}, ok: false, qty: 100, vehicles: [{adjusted: "é ü", channel: "é ü", dueDate: "2024-01-01", payments: [{price: 100}, {price: 100}], points: true, rate: 2.50, share: "retail", totals: {risk: false}}]}}}, + {input: {shipment: {qty: 100, dueDate: null, active: true, vehicles: []}}, goals: ["vehicle.band"], output: {shipment: {active: true, dueDate: null, qty: 100, vehicles: []}}}, + {input: {shipment: {qty: 5, dueDate: "2000-01-01", active: true, vehicles: []}}, goals: ["vehicle.share"], output: {shipment: {active: true, dueDate: "2000-01-01", qty: 5, vehicles: []}}}, + {input: {shipment: {qty: 250, dueDate: "2025-03-20T10:15:30Z", active: false, vehicles: [{rate: 0.25, channel: "a-b-c", dueDate: "2024-02-29", payments: [{price: 1e3}, {price: 1}]}, {rate: 100, channel: "A1", dueDate: "2030-12-31", payments: [{price: 5}, {price: 5}, {price: 18}]}, {rate: 0.5, channel: "é ü", dueDate: "1990-06-15", payments: [{price: 50}]}, {rate: 5, channel: "gold", dueDate: "2025-03-20", payments: [{price: 1000}, {price: -1}]}, {rate: 3, channel: "-", dueDate: "2025-03-20", payments: [{price: 3}]}, {rate: 18, channel: "ok", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 0.25}, {price: 0}]}, {rate: 0.25, channel: "retail", dueDate: "2024-01-01", payments: [{price: 5}, {price: 1e3}, {price: 50}]}, {rate: 0.5, channel: "none", dueDate: "2025-03-20", payments: [{price: 3}]}, {rate: -0.01, channel: "Zed", dueDate: "2030-12-31", payments: [{price: 0.000001}, {price: -0.5}]}, {rate: 0.000001, channel: "DE", dueDate: "2024-01-01", payments: [{price: 50}, {price: 100}]}, {rate: 1e3, channel: "3.5", dueDate: "2024-01-01", payments: [{price: -0}, {price: -0.01}, {price: 0.25}]}, {rate: 65, channel: "a", dueDate: "2000-01-01", payments: [{price: 100}, {price: 3}]}]}}, goals: ["vehicle.flag"], output: {shipment: {active: false, dueDate: "2025-03-20T10:15:30Z", qty: 250, vehicles: [{channel: "a-b-c", dueDate: "2024-02-29", flag: [], payments: [{price: 1000}, {price: 1}], rate: 0.25}, {channel: "A1", dueDate: "2030-12-31", flag: [], payments: [{price: 5}, {price: 5}, {price: 18}], rate: 100}, {channel: "é ü", dueDate: "1990-06-15", flag: [], payments: [{price: 50}], rate: 0.5}, {channel: "gold", dueDate: "2025-03-20", flag: [], payments: [{price: 1000}, {price: -1}], rate: 5}, {channel: "-", dueDate: "2025-03-20", flag: [], payments: [{price: 3}], rate: 3}, {channel: "ok", dueDate: "2025-03-20T10:15:30Z", flag: [], payments: [{price: 0.25}, {price: 0}], rate: 18}, {channel: "retail", dueDate: "2024-01-01", flag: [], payments: [{price: 5}, {price: 1000}, {price: 50}], rate: 0.25}, {channel: "none", dueDate: "2025-03-20", flag: [], payments: [{price: 3}], rate: 0.5}, {channel: "Zed", dueDate: "2030-12-31", flag: [], payments: [{price: 0.000001}, {price: -0.5}], rate: -0.01}, {channel: "DE", dueDate: "2024-01-01", flag: [], payments: [{price: 50}, {price: 100}], rate: 0.000001}, {channel: "3.5", dueDate: "2024-01-01", flag: [], payments: [{price: 0}, {price: -0.01}, {price: 0.25}], rate: 1000}, {channel: "a", dueDate: "2000-01-01", flag: [], payments: [{price: 100}, {price: 3}], rate: 65}]}}}, + {input: {shipment: {qty: 50, active: true, vehicles: [{rate: 18, channel: "é ü", dueDate: "2000-01-01", payments: [{price: -0.5}, {price: 5}]}]}}, goals: ["shipment.summary"], output: {shipment: {active: true, capped: false, health: {a: "50", ok: 50}, ok: false, qty: 50, summary: [50, 50], vehicles: [{channel: "é ü", dueDate: "2000-01-01", payments: [{price: -0.5}, {price: 5}], rate: 18}]}}}, + {input: {shipment: {qty: 99.99, dueDate: "2024-01-01", active: false, vehicles: [{rate: 18, channel: "retail", dueDate: "2024-02-29", payments: [{price: 18}, {price: 100}]}, {rate: 250, channel: "A1", dueDate: "2024-01-01", payments: [{price: 10}]}, {rate: 18, channel: "VIP", dueDate: "1990-06-15", payments: [{price: -0}, {price: 1000}]}]}}, goals: ["fee", "vehicle.totals.risk"], output: {fee: false, shipment: {active: false, dueDate: "2024-01-01", health: {a: "99.99", ok: 50}, ok: false, qty: 99.99, vehicles: [{adjusted: "retail", channel: "retail", dueDate: "2024-02-29", payments: [{price: 18}, {price: 100}], rate: 18, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "A1", dueDate: "2024-01-01", payments: [{price: 10}], rate: 250, share: null, totals: {risk: null}}, {adjusted: "VIP", channel: "VIP", dueDate: "1990-06-15", payments: [{price: 0}, {price: 1000}], rate: 18, share: "retail", totals: {risk: false}}]}}}, + {input: {shipment: {qty: 123456789.123, dueDate: "2024-02-29", active: false, vehicles: [{rate: 451, channel: "retail", dueDate: "2024-01-01", payments: [{price: 100}, {price: 5}, {price: 1e3}]}, {rate: 3, channel: "US", dueDate: "2024-02-29", payments: []}], extraField: "x"}}, goals: ["shipment.bonus"], output: {shipment: {active: false, bonus: "Invalid date", dueDate: "2024-02-29", extraField: "x", qty: 123456789.123, vehicles: [{channel: "retail", dueDate: "2024-01-01", payments: [{price: 100}, {price: 5}, {price: 1000}], rate: 451}, {channel: "US", dueDate: "2024-02-29", payments: [], rate: 3}]}}}, + {input: {shipment: {qty: 10, dueDate: "2000-01-01", active: true, vehicles: [{rate: 2, channel: null, dueDate: "2025-03-20T10:15:30Z", payments: [{price: 50}, {price: 123456789.123}]}, {rate: 99.99, channel: "é ü", dueDate: "2025-03-20", payments: [{price: 3}, {price: 18}]}]}}, goals: ["shipment.ok", "vehicle.share", "vehicle.flag"], output: {shipment: {active: true, dueDate: "2000-01-01", health: {a: "10", ok: 6}, ok: false, qty: 10, vehicles: [{adjusted: null, channel: null, dueDate: "2025-03-20T10:15:30Z", flag: [], payments: [{price: 50}, {price: 123456789.123}], rate: 2, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "é ü", dueDate: "2025-03-20", flag: [], payments: [{price: 3}, {price: 18}], rate: 99.99, share: null, totals: {risk: null}}]}}}, + {input: {shipment: {qty: 123456789.123, dueDate: "2025-03-20T10:15:30Z", active: true, vehicles: [{rate: 99.99, channel: "12", dueDate: "2024-02-29", payments: [{price: 18}, {price: 1000000}, {price: -0.5}]}, {rate: 100, channel: "abc", dueDate: "2024-02-29", payments: []}, {rate: 1000, channel: "Oslo", dueDate: "2030-12-31", payments: [{price: 3}, {price: 5}]}, {rate: 100, channel: "日本", dueDate: "2024-02-29", payments: [{price: 100}]}]}}, goals: ["fee", "vehicle.points"], output: {fee: false, shipment: {active: true, dueDate: "2025-03-20T10:15:30Z", health: {a: "123456789.123", ok: 50}, qty: 123456789.123, vehicles: [{adjusted: null, channel: "12", dueDate: "2024-02-29", payments: [{price: 18}, {price: 1000000}, {price: -0.5}], points: true, rate: 99.99, share: null, totals: {risk: null}}, {adjusted: null, channel: "abc", dueDate: "2024-02-29", payments: [], points: true, rate: 100, share: null, totals: {risk: null}}, {adjusted: null, channel: "Oslo", dueDate: "2030-12-31", payments: [{price: 3}, {price: 5}], points: true, rate: 1000, share: null, totals: {risk: null}}, {adjusted: null, channel: "日本", dueDate: "2024-02-29", payments: [{price: 100}], points: true, rate: 100, share: null, totals: {risk: null}}]}}}, + {input: {shipment: {qty: 10, dueDate: "1990-06-15", active: true, vehicles: [{rate: 123456789.123, channel: "Oslo", dueDate: "2030-12-31", payments: [{price: 100}, {price: 3}, {price: -0.01}]}, {rate: 2, channel: "日本", dueDate: "2025-03-20", payments: [{price: 18}, {price: 2.50}]}, {rate: 3, channel: "retail", dueDate: "2025-03-20", payments: [{price: -0.5}]}, {rate: 1, channel: "-", dueDate: "1990-06-15", payments: []}, {rate: 99999999999999999999, channel: "", dueDate: "2030-12-31", payments: [{price: 18}]}, {rate: 1, channel: "", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 3}, {price: 100}, {price: 100}]}, {rate: 99.99, channel: "a-b-c", dueDate: "2025-03-20T10:15:30Z", payments: []}, {rate: 100, channel: "low", dueDate: "1990-06-15", payments: []}, {rate: 3, channel: "A1", dueDate: "2025-03-20T10:15:30Z", payments: []}, {rate: 1e3, channel: "-", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 5}, {price: 50}]}, {rate: 1, channel: "a", dueDate: "1990-06-15", payments: [{price: 100}, {price: 0.5}]}, {rate: 50, channel: "Oslo", dueDate: "2000-01-01", payments: [{price: 65}, {price: 100}, {price: 3}]}, {rate: -0.01, channel: "low", dueDate: "1990-06-15", payments: [{price: 50}, {price: -500}]}]}}, goals: ["vehicle.adjusted", "shipment.ok"], output: {shipment: {active: true, dueDate: "1990-06-15", health: {a: "10", ok: 6}, ok: false, qty: 10, vehicles: [{adjusted: null, channel: "Oslo", dueDate: "2030-12-31", payments: [{price: 100}, {price: 3}, {price: -0.01}], rate: 123456789.123, share: null, totals: {risk: null}}, {adjusted: "日本", channel: "日本", dueDate: "2025-03-20", payments: [{price: 18}, {price: 2.50}], rate: 2, share: "retail", totals: {risk: false}}, {adjusted: "retail", channel: "retail", dueDate: "2025-03-20", payments: [{price: -0.5}], rate: 3, share: "retail", totals: {risk: false}}, {adjusted: "-", channel: "-", dueDate: "1990-06-15", payments: [], rate: 1, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "", dueDate: "2030-12-31", payments: [{price: 18}], rate: 99999999999999999999, share: null, totals: {risk: null}}, {adjusted: "", channel: "", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 3}, {price: 100}, {price: 100}], rate: 1, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "a-b-c", dueDate: "2025-03-20T10:15:30Z", payments: [], rate: 99.99, share: null, totals: {risk: null}}, {adjusted: null, channel: "low", dueDate: "1990-06-15", payments: [], rate: 100, share: null, totals: {risk: null}}, {adjusted: "A1", channel: "A1", dueDate: "2025-03-20T10:15:30Z", payments: [], rate: 3, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "-", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 5}, {price: 50}], rate: 1000, share: null, totals: {risk: null}}, {adjusted: "a", channel: "a", dueDate: "1990-06-15", payments: [{price: 100}, {price: 0.5}], rate: 1, share: "retail", totals: {risk: false}}, {adjusted: null, channel: "Oslo", dueDate: "2000-01-01", payments: [{price: 65}, {price: 100}, {price: 3}], rate: 50, share: null, totals: {risk: null}}, {adjusted: "low", channel: "low", dueDate: "1990-06-15", payments: [{price: 50}, {price: -500}], rate: -0.01, share: "retail", totals: {risk: false}}]}}}, + {input: {shipment: {qty: 18, dueDate: "2025-03-20", active: true, vehicles: [{rate: 0.1, channel: "A1", dueDate: "2025-03-20T10:15:30Z", payments: [{price: 0.5}, {price: 18}, {price: 99999999999999999999}]}, {rate: 100, channel: "Zed", dueDate: "2000-01-01", payments: [{price: 100}, {price: 99999999999999999999}, {price: 18}]}, {rate: 65, channel: "NL", dueDate: "2024-01-01", payments: [{price: 1e3}, {price: 3}]}, {rate: 1, channel: "Oslo", dueDate: "2024-02-29", payments: []}]}}, goals: ["vehicle.flag"], output: {shipment: {active: true, dueDate: "2025-03-20", qty: 18, vehicles: [{channel: "A1", dueDate: "2025-03-20T10:15:30Z", flag: [], payments: [{price: 0.5}, {price: 18}, {price: 99999999999999999999}], rate: 0.1}, {channel: "Zed", dueDate: "2000-01-01", flag: [], payments: [{price: 100}, {price: 99999999999999999999}, {price: 18}], rate: 100}, {channel: "NL", dueDate: "2024-01-01", flag: [], payments: [{price: 1000}, {price: 3}], rate: 65}, {channel: "Oslo", dueDate: "2024-02-29", flag: [], payments: [], rate: 1}]}}}, + ], +} + +// seed 352300 (attempt 0) +{ + name: "goals 24: customer/members/drivers: 1 assertion, 5 expression, 2 match, 1 table; 4 root, 3 per-member, 2 top-level computed", + policy: { + models: {customer: {rate: "number", insured: "boolean?", label: "string", code: "string", channel: "string", members: "member[]"}, member: {balance: "number?", rate: "number", drivers: "driver[]"}, driver: {days: "number?"}}, + blocks: [ + {expression: "customer.meta.tag", value: "none(customer.members, #.balance == null)"}, + {assertion: "member.flag", conditions: [["and", "10 > customer.rate", 1], ["or", "not ((customer.insured ?? false))", 0], ["or", "some(member.drivers, (#.days ?? 0) <= (#.days ?? 0))", 0], "(customer.rate % (abs((member.balance ?? 0)) + 1)) > member.rate", "matches((customer.channel + '-' + customer.label), '[0-9]$')"]}, + {expression: "customer.penalty", value: "(all(customer.members, (#.flag or #.flag)) or not (customer.meta.tag))"}, + {match: "customer.summary", arms: [["customer.rate == customer.rate", "upper(customer.label)"], ["startsWith((customer.label + '-' + customer.label), 'Oslo')", "`${customer.channel}/${customer.rate}`"], ["customer.rate <= 1.5", "customer.label"], ["customer.rate < customer.rate", "customer.code"], ["", "(customer.label + '-' + customer.channel)"]]}, + {match: "member.exposure", arms: [["(member.balance ?? 0) <= member.rate", "(member.balance ?? 0)"], ["not (member.rate in (10..30])", "customer.rate"], ["(not (customer.penalty) and (member.balance ?? 0) <= customer.rate)", "1"], ["contains(['gold', 'a', ''], customer.label)", "((customer.insured ?? false) ? (member.balance ?? 0) : member.rate)"], ["", "customer.rate"]]}, + {expression: "customer.quota", value: "trunc((customer.penalty ? customer.rate : customer.rate))"}, + {expression: "fee", value: "filter(customer.members, ((#.balance ?? 0) - 0.5) <= (#.balance ?? 0))"}, + {table: "t8", hit: "collect", inputs: ["((member.balance ?? 0) * customer.rate)", null], outputs: ["member.band"], rules: [ + ["", "(member.balance ?? 0) in (26..153]", "customer.label"], + ["", "", "string(customer.rate)"], + ]}, + {expression: "ok", value: "`${customer.rate}/${customer.rate}`"}, + ], + }, + cases: [ + {input: {customer: {rate: 123456789.123, insured: false, label: "a", code: "", channel: "abc", members: [{balance: 7.25, rate: 0.000001, drivers: []}, {rate: 0.000001, drivers: []}]}}, goals: ["member.exposure"], output: {customer: {channel: "abc", code: "", insured: false, label: "a", members: [{balance: 7.25, drivers: [], exposure: 123456789.123, flag: false, rate: 0.000001}, {drivers: [], exposure: 0, flag: false, rate: 0.000001}], meta: {tag: false}, penalty: true, rate: 123456789.123}}}, + [{customer: {rate: 0.5, insured: false, label: "a-b-c", code: null, channel: "x-y", members: [{balance: 2, rate: 1.5, drivers: [{days: 99.99}, {days: 7.25}]}]}}, "!error: MissingRequiredInputs"], + {input: {customer: {rate: 250, insured: false, label: "A1", code: "x-y", channel: "12", members: [{balance: 18, rate: 0.5, drivers: [{days: 0.5}, {}, {}]}, {rate: -1, drivers: [{}, {days: 1.5}]}, {balance: -1, rate: 0, drivers: [{days: null}, {}]}, {balance: 0.5, rate: 1, drivers: [{}, {days: 100}]}, {balance: 18, rate: 100, drivers: [{days: null}, {}, {}]}]}}, goals: ["fee", "customer.quota"], output: {customer: {channel: "12", code: "x-y", insured: false, label: "A1", members: [{balance: 18, drivers: [{days: 0.5}, {}, {}], flag: true, rate: 0.5}, {drivers: [{}, {days: 1.5}], flag: true, rate: -1}, {balance: -1, drivers: [{days: null}, {}], flag: true, rate: 0}, {balance: 0.5, drivers: [{}, {days: 100}], flag: true, rate: 1}, {balance: 18, drivers: [{days: null}, {}, {}], flag: true, rate: 100}], meta: {tag: false}, penalty: true, quota: 250, rate: 250}, fee: [{balance: 18, drivers: [{days: 0.5}, {}, {}], flag: true, rate: 0.5}, {drivers: [{}, {days: 1.5}], flag: true, rate: -1}, {balance: -1, drivers: [{days: null}, {}], flag: true, rate: 0}, {balance: 0.5, drivers: [{}, {days: 100}], flag: true, rate: 1}, {balance: 18, drivers: [{days: null}, {}, {}], flag: true, rate: 100}]}}, + {input: {customer: {rate: 1e3, insured: false, label: "A1", code: "a", channel: "US", members: [{balance: 0.5, rate: 18, drivers: [{days: 99999999999999999999}, {days: 0.5}]}, {balance: 0.5, rate: 1000000, drivers: [{days: 7.25}]}]}}, goals: ["customer.meta.tag", "member.flag", "member.exposure"], output: {customer: {channel: "US", code: "a", insured: false, label: "A1", members: [{balance: 0.5, drivers: [{days: 99999999999999999999}, {days: 0.5}], exposure: 0.5, flag: true, rate: 18}, {balance: 0.5, drivers: [{days: 7.25}], exposure: 0.5, flag: true, rate: 1000000}], meta: {tag: true}, penalty: true, rate: 1000}}}, + {input: {customer: {rate: 1000, insured: false, label: "VIP", code: "Zed", channel: "abc", members: []}}, goals: ["member.flag"], output: {customer: {channel: "abc", code: "Zed", insured: false, label: "VIP", members: [], rate: 1000}}}, + {input: {customer: {rate: 10, insured: "true", label: "DE", code: "gold", channel: "US", members: [{balance: 100, rate: 1e3, drivers: [{days: 2.50}, {days: 0.1}]}]}}, goals: ["fee", "ok", "member.band"], output: "!error: InputValidationFailed"}, + {input: {customer: {rate: -1, insured: false, label: "Oslo", code: "A1", channel: "DE", members: [{balance: 10, rate: 65, drivers: [{days: 1000000}, {days: 0}]}, {balance: 2, rate: 1, drivers: []}, {balance: 18, rate: 486, drivers: [{days: -0}, {days: 2}]}, {balance: 1.5, rate: 18, drivers: [{days: 18}]}, {balance: -1, rate: 10, drivers: [{days: 10}, {days: 1000}]}]}}, goals: ["customer.meta.tag", "member.band", "ok"], output: {customer: {channel: "DE", code: "A1", insured: false, label: "Oslo", members: [{balance: 10, band: ["-1"], drivers: [{days: 1000000}, {days: 0}], rate: 65}, {balance: 2, band: ["-1"], drivers: [], rate: 1}, {balance: 18, band: ["-1"], drivers: [{days: 0}, {days: 2}], rate: 486}, {balance: 1.5, band: ["-1"], drivers: [{days: 18}], rate: 18}, {balance: -1, band: ["-1"], drivers: [{days: 10}, {days: 1000}], rate: 10}], meta: {tag: true}, rate: -1}, ok: "-1/-1"}}, + {input: {customer: {rate: 2.50, insured: true, label: "a-b-c", code: "Oslo", channel: "high", members: [{balance: 2.50, rate: 0, drivers: [{days: 18}, {days: 2.50}]}, {balance: -1, rate: 18, drivers: []}]}}, goals: ["customer.quota", "ok", "fee"], output: {customer: {channel: "high", code: "Oslo", insured: true, label: "a-b-c", members: [{balance: 2.50, drivers: [{days: 18}, {days: 2.50}], flag: false, rate: 0}, {balance: -1, drivers: [], flag: false, rate: 18}], meta: {tag: true}, penalty: false, quota: 2, rate: 2.50}, fee: [{balance: 2.50, drivers: [{days: 18}, {days: 2.50}], flag: false, rate: 0}, {balance: -1, drivers: [], flag: false, rate: 18}], ok: "2.50/2.50"}}, + {input: {customer: {rate: 250, insured: true, label: "VIP", code: "US", channel: "a", members: []}}, goals: ["customer.quota", "ok", "customer.meta.tag"], output: {customer: {channel: "a", code: "US", insured: true, label: "VIP", members: [], meta: {tag: true}, penalty: true, quota: 250, rate: 250}, ok: "250/250"}}, + {input: {customer: {rate: 65, insured: null, label: "é ü", code: "gold", channel: "US", members: [{balance: 1, rate: -0.01, drivers: [{}]}]}}, goals: ["member.band"], output: {customer: {channel: "US", code: "gold", insured: null, label: "é ü", members: [{balance: 1, band: ["65"], drivers: [{}], rate: -0.01}], rate: 65}}}, + {input: {customer: {rate: 1.5, insured: false, label: "gold", code: "日本", channel: "US", members: [{balance: 1000, rate: -1, drivers: [{days: 18}, {days: 10}]}]}}, goals: ["customer.penalty", "member.exposure", "customer.quota"], output: {customer: {channel: "US", code: "日本", insured: false, label: "gold", members: [{balance: 1000, drivers: [{days: 18}, {days: 10}], exposure: 1.5, flag: false, rate: -1}], meta: {tag: true}, penalty: false, quota: 1, rate: 1.5}}}, + {input: {customer: {rate: 99.99, insured: null, label: "A1", code: "a", channel: "é ü", members: [{balance: 99.99, rate: 18, drivers: [{days: null}, {days: 10}]}, {balance: 10, rate: 100, drivers: [{days: -0.01}, {}, {}]}, {rate: 2.50, drivers: []}, {rate: 0.000001, drivers: [{days: 5}, {days: null}, {}]}, {balance: -0.5, rate: -1, drivers: [{days: -0}]}, {balance: 10, rate: 18, drivers: []}, {balance: -1, rate: 1e3, drivers: [{}, {days: null}, {days: 250}]}, {balance: null, rate: 18, drivers: [{days: 65}, {days: 10}, {days: 0.5}]}]}}, goals: ["customer.quota", "member.exposure"], output: {customer: {channel: "é ü", code: "a", insured: null, label: "A1", members: [{balance: 99.99, drivers: [{days: null}, {days: 10}], exposure: 99.99, flag: true, rate: 18}, {balance: 10, drivers: [{days: -0.01}, {}, {}], exposure: 10, flag: true, rate: 100}, {drivers: [], exposure: 0, flag: false, rate: 2.50}, {drivers: [{days: 5}, {days: null}, {}], exposure: 0, flag: true, rate: 0.000001}, {balance: -0.5, drivers: [{days: 0}], exposure: 99.99, flag: true, rate: -1}, {balance: 10, drivers: [], exposure: 10, flag: false, rate: 18}, {balance: -1, drivers: [{}, {days: null}, {days: 250}], exposure: -1, flag: true, rate: 1000}, {balance: null, drivers: [{days: 65}, {days: 10}, {days: 0.5}], exposure: 0, flag: true, rate: 18}], meta: {tag: false}, penalty: true, quota: 99, rate: 99.99}}}, + {input: {customer: {rate: 1000000, insured: null, label: " pad ", code: "A1", channel: "high", members: [{balance: -500, rate: 18, drivers: [{days: -500}, {days: null}]}]}}, goals: ["customer.penalty", "ok", "member.flag"], output: {customer: {channel: "high", code: "A1", insured: null, label: " pad ", members: [{balance: -500, drivers: [{days: -500}, {days: null}], flag: false, rate: 18}], meta: {tag: true}, penalty: false, rate: 1000000}, ok: "1000000/1000000"}}, + [{customer: {rate: 123456789.123, label: "a", code: "US", channel: "US", members: [{balance: 65, rate: 98, drivers: [{days: null}]}]}}, {customer: {channel: "US", code: "US", label: "a", members: [{balance: 65, band: ["a", "123456789.123"], drivers: [{days: null}], exposure: 65, flag: false, rate: 98}], meta: {tag: true}, penalty: false, quota: 123456789, rate: 123456789.123, summary: "A"}, fee: [{balance: 65, band: ["a", "123456789.123"], drivers: [{days: null}], exposure: 65, flag: false, rate: 98}], ok: "123456789.123/123456789.123"}], + [{customer: {rate: 0, insured: true, label: "a", code: "A1", channel: "DE", members: [{rate: 65, drivers: [{}, {days: 1000000}, {days: 10}]}, {rate: 5, drivers: [{days: null}, {days: 123456789.123}]}, {rate: 0, drivers: [{days: null}, {days: null}]}, {balance: 0.5, rate: 0, drivers: [{days: 18}, {days: 123456789.123}]}]}}, {customer: {channel: "DE", code: "A1", insured: true, label: "a", members: [{band: ["0"], drivers: [{}, {days: 1000000}, {days: 10}], exposure: 0, flag: false, rate: 65}, {band: ["0"], drivers: [{days: null}, {days: 123456789.123}], exposure: 0, flag: false, rate: 5}, {band: ["0"], drivers: [{days: null}, {days: null}], exposure: 0, flag: false, rate: 0}, {balance: 0.5, band: ["0"], drivers: [{days: 18}, {days: 123456789.123}], exposure: 0, flag: false, rate: 0}], meta: {tag: false}, penalty: true, quota: 0, rate: 0, summary: "A"}, fee: [{band: ["0"], drivers: [{}, {days: 1000000}, {days: 10}], exposure: 0, flag: false, rate: 65}, {band: ["0"], drivers: [{days: null}, {days: 123456789.123}], exposure: 0, flag: false, rate: 5}, {band: ["0"], drivers: [{days: null}, {days: null}], exposure: 0, flag: false, rate: 0}, {balance: 0.5, band: ["0"], drivers: [{days: 18}, {days: 123456789.123}], exposure: 0, flag: false, rate: 0}], ok: "0/0"}], + [{customer: {rate: 99999999999999999999, insured: true, label: "abc", code: "VIP", channel: "abc", members: [{balance: null, rate: 65, drivers: []}, {balance: null, rate: 99999999999999999999, drivers: [{days: -0.01}, {}]}, {balance: 1, rate: 10, drivers: [{days: 250}, {days: null}]}, {balance: null, rate: 10, drivers: [{}, {days: 0.1}, {days: 250}]}, {balance: 1.5, rate: 18, drivers: [{}, {days: null}]}]}}, {customer: {channel: "abc", code: "VIP", insured: true, label: "abc", members: [{balance: null, band: ["99999999999999999999"], drivers: [], exposure: 0, flag: false, rate: 65}, {balance: null, band: ["99999999999999999999"], drivers: [{days: -0.01}, {}], exposure: 0, flag: false, rate: 99999999999999999999}, {balance: 1, band: ["99999999999999999999"], drivers: [{days: 250}, {days: null}], exposure: 1, flag: false, rate: 10}, {balance: null, band: ["99999999999999999999"], drivers: [{}, {days: 0.1}, {days: 250}], exposure: 0, flag: false, rate: 10}, {balance: 1.5, band: ["99999999999999999999"], drivers: [{}, {days: null}], exposure: 1.5, flag: false, rate: 18}], meta: {tag: false}, penalty: true, quota: 99999999999999999999, rate: 99999999999999999999, summary: "ABC"}, fee: [{balance: null, band: ["99999999999999999999"], drivers: [], exposure: 0, flag: false, rate: 65}, {balance: null, band: ["99999999999999999999"], drivers: [{days: -0.01}, {}], exposure: 0, flag: false, rate: 99999999999999999999}, {balance: 1, band: ["99999999999999999999"], drivers: [{days: 250}, {days: null}], exposure: 1, flag: false, rate: 10}, {balance: null, band: ["99999999999999999999"], drivers: [{}, {days: 0.1}, {days: 250}], exposure: 0, flag: false, rate: 10}, {balance: 1.5, band: ["99999999999999999999"], drivers: [{}, {days: null}], exposure: 1.5, flag: false, rate: 18}], ok: "99999999999999999999/99999999999999999999"}], + [{customer: {rate: 100, insured: true, label: "Oslo", code: "high", channel: "a", members: [{balance: null, rate: 1000000, drivers: [{days: null}]}, {balance: null, rate: -0, drivers: []}]}}, {customer: {channel: "a", code: "high", insured: true, label: "Oslo", members: [{balance: null, band: ["100"], drivers: [{days: null}], exposure: 0, flag: false, rate: 1000000}, {balance: null, band: ["100"], drivers: [], exposure: 0, flag: false, rate: 0}], meta: {tag: false}, penalty: true, quota: 100, rate: 100, summary: "OSLO"}, fee: [{balance: null, band: ["100"], drivers: [{days: null}], exposure: 0, flag: false, rate: 1000000}, {balance: null, band: ["100"], drivers: [], exposure: 0, flag: false, rate: 0}], ok: "100/100"}], + {input: {customer: {rate: 65, insured: true, label: " pad ", code: "", channel: "Zed", members: [{balance: 0, rate: 18, drivers: [{days: 10}, {days: 99999999999999999999}]}, {balance: 2, rate: 10, drivers: [{days: 18}, {days: 2.50}]}]}}, goals: ["customer.summary", "member.exposure", "customer.meta.tag"], output: {customer: {channel: "Zed", code: "", insured: true, label: " pad ", members: [{balance: 0, drivers: [{days: 10}, {days: 99999999999999999999}], exposure: 0, flag: false, rate: 18}, {balance: 2, drivers: [{days: 18}, {days: 2.50}], exposure: 2, flag: false, rate: 10}], meta: {tag: true}, penalty: false, rate: 65, summary: " PAD "}}}, + {input: {customer: {rate: 123456789.123, label: " pad ", code: "gold", channel: "VIP", members: [{balance: null, rate: -0.5, drivers: [{}, {days: null}, {}]}, {balance: 0, rate: 1e3, drivers: [{days: 1}, {days: 1e3}]}]}}, goals: ["member.exposure", "member.flag"], output: {customer: {channel: "VIP", code: "gold", label: " pad ", members: [{balance: null, drivers: [{}, {days: null}, {}], exposure: 123456789.123, flag: false, rate: -0.5}, {balance: 0, drivers: [{days: 1}, {days: 1000}], exposure: 0, flag: false, rate: 1000}], meta: {tag: false}, penalty: true, rate: 123456789.123}}}, + [{customer: {rate: 0, insured: false, label: "abc", code: "gold", channel: "a", members: [{balance: 10, rate: 123456789.123, drivers: [{days: 0.1}, {days: -0}]}]}}, {customer: {channel: "a", code: "gold", insured: false, label: "abc", members: [{balance: 10, band: ["0"], drivers: [{days: 0.1}, {days: 0}], exposure: 10, flag: false, rate: 123456789.123}], meta: {tag: true}, penalty: false, quota: 0, rate: 0, summary: "ABC"}, fee: [{balance: 10, band: ["0"], drivers: [{days: 0.1}, {days: 0}], exposure: 10, flag: false, rate: 123456789.123}], ok: "0/0"}], + [{customer: {rate: 191, insured: false, label: "VIP", code: "retail", channel: "DE", members: []}}, {customer: {channel: "DE", code: "retail", insured: false, label: "VIP", members: [], meta: {tag: true}, penalty: true, quota: 191, rate: 191, summary: "VIP"}, fee: [], ok: "191/191"}], + [{customer: {rate: 99.99, insured: false, label: "", code: "O'Neil", channel: "VIP", members: []}}, {customer: {channel: "VIP", code: "O'Neil", insured: false, label: "", members: [], meta: {tag: true}, penalty: true, quota: 99, rate: 99.99, summary: ""}, fee: [], ok: "99.99/99.99"}], + ], +} + +// seed 352400 (attempt 0) +{ + name: "goals 25: claim/loans + contact: 1 assertion, 4 expression, 3 match, 1 table; 4 root, 1 per-member, 2 top-level computed", + policy: { + models: {claim: {qty: "number", insured: "boolean?", code: "string", loans: "loan[]?", contact: "contactInfo"}, loan: {qty: "number?", verified: "boolean?", active: "boolean?"}, contactInfo: {age: "number"}}, + blocks: [ + {table: "t1", inputs: ["contactInfo.age", "len(filter((claim.loans ?? []), ((#.verified ?? false) and (#.active ?? false))))"], outputs: ["contactInfo.grade"], rules: [ + ["> 0", "[0.5..137.5]", "contactInfo.age"], + ["", "", "claim.qty"], + ["", "", "claim.qty"], + ]}, + {expression: "contactInfo.penalty", value: "sum([(contactInfo.grade ?? 0)])"}, + {match: "eligible", arms: [["contains(['retail', 'a', ''], claim.code)", "claim.code"], ["claim.contact.grade == null", "(claim.code + '-' + claim.code)"], ["len(claim.code) > 3", "claim.code"], ["claim.insured != null", "lower(claim.code)"], ["", "(claim.code + '-' + claim.code)"]]}, + {match: "contactInfo.bucket", arms: [["claim.qty in (49..244)", "(contactInfo.penalty <= contactInfo.age ? (contactInfo.grade ?? 0) : (min(map((claim.loans ?? []), 1000)) ?? 0))"], ["claim.qty != claim.qty", "contactInfo.penalty"], ["contactInfo.penalty == contactInfo.penalty", "claim.qty"], ["", "contactInfo.age"]]}, + {expression: "claim.ok", value: "-((((claim.insured ?? false) and (claim.insured ?? false)) ? len(filter((claim.loans ?? []), ((#.active ?? false) and (#.active ?? false)))) : (claim.qty + 1)))"}, + {expression: "claim.fee", value: "matches((split(eligible, '-')[1] ?? 'none'), '[0-9]$')"}, + {match: "share", arms: [["all((claim.loans ?? []), ((#.verified ?? false) or (#.active ?? false)))", "(none((claim.loans ?? []), (#.qty ?? 0) == (#.qty ?? 0)) ? `${eligible}/${claim.contact.penalty}` : ((claim.insured ?? false) ? eligible : eligible))"], ["(claim.contact.grade ?? 0) in [15..102]", "string((claim.contact.grade ?? 0))"], ["(claim.contact.bucket / 3) == claim.ok", "eligible"], ["", "claim.code"]]}, + {expression: "claim.total", value: "{n: count((claim.loans ?? []), ((#.verified ?? false) and (#.active ?? false)))}"}, + {assertion: "loan.rank", conditions: [["or", "claim.insured != null", 2], ["or", "claim.contact.grade == null", 2], ["and", "claim.contact.bucket in [43..90]", 1], ["and", "contains(['retail', 'a', ''], share)", 1], ["or", "claim.contact.bucket >= claim.contact.penalty", 0]]}, + ], + }, + cases: [ + {input: {claim: {qty: 100, code: "A1", loans: [{qty: 10, verified: true}, {active: null}, {qty: 0.5, verified: null}], contact: {age: 94}}}, goals: ["contactInfo.penalty", "claim.total", "claim.ok"], output: {claim: {code: "A1", contact: {age: 94, grade: 100, penalty: 100}, loans: [{qty: 10, verified: true}, {active: null}, {qty: 0.5, verified: null}], ok: -101, qty: 100, total: {n: 0}}}}, + {input: {claim: {qty: 0.25, insured: null, code: "a", loans: [{verified: true, active: null}, {qty: 0.1, verified: false, active: false}, {qty: null, verified: null}, {verified: true, active: false}, {qty: null}, {qty: 1e3, verified: true}, {active: true}, {qty: 0.25, verified: true, active: false}], contact: {age: 0.5}}}, goals: ["eligible", "contactInfo.grade", "contactInfo.bucket"], output: {claim: {code: "a", contact: {age: 0.5, bucket: 0.25, grade: 0.25, penalty: 0.25}, insured: null, loans: [{active: null, verified: true}, {active: false, qty: 0.1, verified: false}, {qty: null, verified: null}, {active: false, verified: true}, {qty: null}, {qty: 1000, verified: true}, {active: true}, {active: false, qty: 0.25, verified: true}], qty: 0.25}, eligible: "a"}}, + {input: {claim: {qty: 50, insured: false, code: "abc", loans: [{qty: -0.5, verified: false, active: false}, {qty: 0, verified: true, active: false}, {qty: 0.1, verified: true, active: false}, {qty: 99.99, verified: true, active: false}], contact: {age: 5}}}, goals: ["contactInfo.penalty", "claim.fee"], output: {claim: {code: "abc", contact: {age: 5, grade: 50, penalty: 50}, fee: false, insured: false, loans: [{active: false, qty: -0.5, verified: false}, {active: false, qty: 0, verified: true}, {active: false, qty: 0.1, verified: true}, {active: false, qty: 99.99, verified: true}], qty: 50}, eligible: "abc"}}, + {input: {claim: {qty: 0, insured: true, code: "retail", loans: [], contact: {age: 250}}}, goals: ["loan.rank"], output: {claim: {code: "retail", contact: {age: 250, bucket: 0, grade: 0, penalty: 0}, insured: true, loans: [], ok: -0, qty: 0}, eligible: "retail", share: "retail/0"}}, + {input: {claim: {qty: 10, insured: true, code: "low", loans: [{qty: 1, verified: false, active: true}, {qty: -1, verified: false, active: false}], contact: {age: 50}}}, goals: ["contactInfo.grade"], output: {claim: {code: "low", contact: {age: 50, grade: 10}, insured: true, loans: [{active: true, qty: 1, verified: false}, {active: false, qty: -1, verified: false}], qty: 10}}}, + {input: {claim: {qty: 0, insured: true, code: "a", loans: [{qty: 73, verified: true, active: false}, {qty: 18, verified: true, active: true}, {qty: 2.50, verified: false, active: true}, {qty: 1, verified: false, active: true}, {qty: 65, verified: true, active: true}], contact: {age: 18}}}, goals: ["share", "contactInfo.bucket"], output: {claim: {code: "a", contact: {age: 18, bucket: 0, grade: 18, penalty: 18}, insured: true, loans: [{active: false, qty: 73, verified: true}, {active: true, qty: 18, verified: true}, {active: true, qty: 2.50, verified: false}, {active: true, qty: 1, verified: false}, {active: true, qty: 65, verified: true}], ok: -4, qty: 0}, eligible: "a", share: "a"}}, + [{claim: {qty: 10, insured: true, code: "Oslo", loans: [], contact: {age: 0.5}}}, {claim: {code: "Oslo", contact: {age: 0.5, bucket: 10, grade: 10, penalty: 10}, fee: false, insured: true, loans: [], ok: -0, qty: 10, total: {n: 0}}, eligible: "Oslo", share: "Oslo/10"}], + {input: {claim: {qty: 10, insured: false, code: "x", loans: [], contact: {age: 18}}}, goals: ["share", "claim.total", "contactInfo.penalty"], output: {claim: {code: "x", contact: {age: 18, bucket: 10, grade: 10, penalty: 10}, insured: false, loans: [], ok: -11, qty: 10, total: {n: 0}}, eligible: "x", share: "x/10"}}, + {input: {claim: {qty: null, insured: true, code: "retail", loans: [{qty: 5, verified: true, active: true}], contact: {age: -500}}}, goals: ["contactInfo.grade"], output: "!error: MissingRequiredInputs"}, + {input: {claim: {qty: 1, code: "a", loans: [{verified: true}, {verified: false, active: null}], contact: {age: -1}}}, goals: ["eligible"], output: {claim: {code: "a", contact: {age: -1, grade: 1}, loans: [{verified: true}, {active: null, verified: false}], qty: 1}, eligible: "a"}}, + {input: {claim: {qty: 10, insured: false, code: "-", loans: [], contact: {age: 99999999999999999999}}}, goals: ["claim.fee"], output: {claim: {code: "-", contact: {age: 99999999999999999999, grade: 10}, fee: false, insured: false, loans: [], qty: 10}, eligible: "-"}}, + {input: {claim: {qty: 1000, insured: true, code: "-", loans: [{qty: 0.5, verified: true, active: false}], contact: {age: 10}}}, goals: ["contactInfo.grade"], output: {claim: {code: "-", contact: {age: 10, grade: 1000}, insured: true, loans: [{active: false, qty: 0.5, verified: true}], qty: 1000}}}, + {input: {claim: {qty: 7.25, insured: true, code: "12", loans: [{qty: 250, verified: true, active: true}, {qty: 0.000001, verified: true, active: false}], contact: {age: -0.01}}}, goals: ["loan.rank", "claim.ok", "eligible"], output: {claim: {code: "12", contact: {age: -0.01, bucket: 7.25, grade: 7.25, penalty: 7.25}, insured: true, loans: [{active: true, qty: 250, rank: false, verified: true}, {active: false, qty: 0.000001, rank: false, verified: true}], ok: -1, qty: 7.25}, eligible: "12", share: "12"}}, + [{claim: {qty: 10, code: "retail", loans: [{verified: true, active: false}, {qty: null, verified: true, active: null}, {verified: null, active: true}], contact: {age: 10}}}, {claim: {code: "retail", contact: {age: 10, bucket: 10, grade: 10, penalty: 10}, fee: false, loans: [{active: false, rank: false, verified: true}, {active: null, qty: null, rank: false, verified: true}, {active: true, rank: false, verified: null}], ok: -11, qty: 10, total: {n: 0}}, eligible: "retail", share: "retail"}], + {input: {claim: {qty: 10, insured: false, code: "NL", loans: [], contact: {age: -1}}}, goals: ["loan.rank", "contactInfo.penalty", "claim.ok"], output: {claim: {code: "NL", contact: {age: -1, bucket: 10, grade: 10, penalty: 10}, insured: false, loans: [], ok: -11, qty: 10}, eligible: "nl", share: "nl/10"}}, + {input: {claim: {qty: 99999999999999999999, insured: true, code: "é ü", loans: [{qty: 3, verified: false, active: true}, {qty: 0.25, verified: true, active: true}, {qty: 1, verified: true, active: false}, {qty: 0.5, verified: false, active: true}, {qty: 10, verified: true, active: true}], contact: {age: 50}}}, goals: ["contactInfo.penalty"], output: {claim: {code: "é ü", contact: {age: 50, grade: 50, penalty: 50}, insured: true, loans: [{active: true, qty: 3, verified: false}, {active: true, qty: 0.25, verified: true}, {active: false, qty: 1, verified: true}, {active: true, qty: 0.5, verified: false}, {active: true, qty: 10, verified: true}], qty: 99999999999999999999}}}, + {input: {claim: {qty: 0.5, insured: null, code: "Oslo", loans: [{qty: 1e3, verified: false, active: false}, {qty: null, verified: null, active: null}, {qty: -0.5, active: null}, {qty: 65, verified: null, active: null}], contact: {age: 0.1}}}, goals: ["loan.rank"], output: {claim: {code: "Oslo", contact: {age: 0.1, bucket: 0.5, grade: 0.5, penalty: 0.5}, insured: null, loans: [{active: false, qty: 1000, rank: false, verified: false}, {active: null, qty: null, rank: false, verified: null}, {active: null, qty: -0.5, rank: false}, {active: null, qty: 65, rank: false, verified: null}], ok: -1.5, qty: 0.5}, share: "Oslo"}}, + [{claim: {qty: -1, insured: false, code: "x", loans: [{qty: 1000, verified: false, active: false}, {qty: 1, verified: true, active: true}], contact: {age: 2}}}, {claim: {code: "x", contact: {age: 2, bucket: -1, grade: 2, penalty: 2}, fee: false, insured: false, loans: [{active: false, qty: 1000, rank: false, verified: false}, {active: true, qty: 1, rank: false, verified: true}], ok: -0, qty: -1, total: {n: 1}}, eligible: "x", share: "x"}], + {input: {claim: {qty: 0.1, insured: true, code: "retail", loans: [{qty: 7.25, verified: false, active: false}, {qty: 1, verified: true, active: false}, {qty: 1000000, verified: true, active: false}, {qty: 100, verified: false, active: false}], contact: {age: 50}}}, goals: ["contactInfo.penalty"], output: {claim: {code: "retail", contact: {age: 50, grade: 0.1, penalty: 0.1}, insured: true, loans: [{active: false, qty: 7.25, verified: false}, {active: false, qty: 1, verified: true}, {active: false, qty: 1000000, verified: true}, {active: false, qty: 100, verified: false}], qty: 0.1}}}, + {input: {claim: {qty: 99999999999999999999, insured: true, code: "retail", loans: [{qty: 159, verified: false, active: false}, {qty: -0, verified: true, active: false}], contact: {age: 0.000001}}}, goals: ["eligible", "claim.total"], output: {claim: {code: "retail", contact: {age: 0.000001, grade: 99999999999999999999}, insured: true, loans: [{active: false, qty: 159, verified: false}, {active: false, qty: 0, verified: true}], qty: 99999999999999999999, total: {n: 0}}, eligible: "retail"}}, + {input: {claim: {qty: 1000, insured: 1, code: "-", loans: [{qty: 1000, verified: false, active: false}], contact: {age: 2}}}, goals: ["contactInfo.penalty"], output: "!error: InputValidationFailed"}, + {input: {claim: {qty: 2, insured: true, code: "a", contact: {age: 10}}}, goals: ["claim.ok"], output: {claim: {code: "a", contact: {age: 10}, insured: true, ok: -0, qty: 2}}}, + {input: {claim: {qty: -0, code: "é ü", loans: [{verified: false, active: null}, {qty: -0.5, verified: false, active: true}, {qty: 0, verified: true}, {qty: 50, active: false}, {verified: null, active: null}], contact: {age: 1e3}}}, goals: ["loan.rank", "share"], output: {claim: {code: "é ü", contact: {age: 1000, bucket: 0, grade: 0, penalty: 0}, loans: [{active: null, rank: false, verified: false}, {active: true, qty: -0.5, rank: false, verified: false}, {qty: 0, rank: false, verified: true}, {active: false, qty: 50, rank: false}, {active: null, rank: false, verified: null}], ok: -1, qty: 0}, share: "é ü"}}, + ], +} + +// seed 352500 (attempt 0) +{ + name: "goals 26: claim/companies/employees: 1 assertion, 3 expression, 4 table; 3 root, 11 per-member, 2 top-level computed", + policy: { + models: {claim: {balance: "number?", rate: "number", weight: "number", tier: "string(gold|silver|bronze)", companies: "company[]"}, company: {amount: "number", balance: "number?", plan: "string(basic|plus|premium|trial)", kind: "string(retail|corporate)", employees: "employee[]"}, employee: {qty: "number", kind: "string(retail|corporate)", vip: "boolean"}}, + blocks: [ + {expression: "company.calc.grade", value: "(some(company.employees, (#.vip or #.vip)) ? claim.balance : null)"}, + {assertion: "company.band", conditions: [["and", "startsWith((claim.rate == 18 ? 'a' : 'Oslo'), 'ok')", 2], ["and", "company.plan == 'basic'", 2]]}, + {table: "t3", inputs: ["claim.rate", "(claim.balance ?? 0)", null], outputs: ["claim.points", "claim.exposure"], rules: [ + ["[1..321]", "<= 100", "(claim.balance ?? 0) < claim.rate", "claim.rate", "claim.rate <= 0"], + [">= 1.5", "> 0.25", "", "len(filter(claim.companies, #.kind == 'corporate'))", "0 > 10"], + ["", "[3..49]", "claim.weight in [14..144]", "", "claim.weight <= 18"], + [">= 0.5", "", "claim.rate != claim.weight", "", "claim.rate == 1.5"], + ["", "3", "claim.balance == null", "claim.weight", "100 == 0"], + ["10, 50", "<= 50", "claim.tier in ['gold', 'silver']", "claim.rate", "1 == 5"], + ["1.5", "", "(claim.rate == 10 and (claim.balance ?? 0) > 5)", "claim.rate", "(claim.balance ?? 0) <= 3"], + ]}, + {table: "t4", inputs: ["len(filter(company.employees, (#.vip or #.vip)))", "round(claim.rate)"], outputs: ["company.scores.discount[]", "company.fee[]", "company.surcharge[]"], rules: [ + ["[1.5..456.5]", "> 100", "company.amount", "'A1'", "18"], + ["", "> 0.25", "claim.rate", "'none'", ""], + ["", "", "company.amount", "'gold'", "100"], + ]}, + {table: "t5", hit: "collect", inputs: [null, "company.kind", "company.calc.grade"], outputs: ["company.quota", "company.risk", "company.total"], rules: [ + ["company.plan in ['trial', 'basic']", "", "0.5, 0", "claim.rate", "(claim.exposure ?? false)", "company.kind != 'retail'"], + ["(company.band or company.band)", "'retail'", "1000, 0", "company.amount", "(claim.exposure ?? false)", "company.band"], + ["claim.rate != claim.weight", "'retail'", "0.25, 0", "", "", "(claim.exposure ?? false)"], + ["", "'retail'", "2, 2", "(claim.points ?? 0)", "", "all(company.employees, #.kind == 'retail')"], + ["", "", "", "1", "company.band", "(claim.exposure ?? false)"], + ]}, + {table: "t6", hit: "collect", inputs: ["claim.tier", "claim.weight", "(claim.exposure ?? false)"], outputs: ["meta.health", "bonus"], rules: [ + ["'gold', 'silver'", "", "true", "(claim.exposure ?? false)", ""], + ["'bronze', 'silver'", "<= 18", "false", "(claim.exposure ?? false)", "(claim.exposure ?? false)"], + ["", "", "", "(claim.exposure ?? false)", ""], + ]}, + {expression: "company.tag", value: "{ok: company.amount in (16..115], v: claim.tier in ['gold', 'silver']}"}, + {expression: "claim.share", value: "(avg(map(claim.companies, #.amount)) ?? 0)"}, + ], + }, + cases: [ + {input: {claim: {balance: 0, rate: 1000, weight: -0, tier: "silver", companies: [{amount: 65, balance: 1.5, plan: "trial", kind: "retail", employees: [{qty: 0.25, kind: "retail", vip: true}, {qty: -0, kind: "corporate", vip: true}]}], extraField: 1}}, goals: ["company.fee", "company.tag", "company.band"], output: {claim: {balance: 0, companies: [{amount: 65, balance: 1.5, band: false, employees: [{kind: "retail", qty: 0.25, vip: true}, {kind: "corporate", qty: 0, vip: true}], fee: ["A1", "none", "gold"], kind: "retail", plan: "trial", scores: {discount: [65, 1000, 65]}, surcharge: [18, 100], tag: {ok: true, v: true}}], extraField: 1, rate: 1000, tier: "silver", weight: 0}}}, + [{claim: {balance: 3, rate: 18, weight: 10, tier: "gold", companies: [{amount: 0.5, plan: "plus", kind: "corporate", employees: [{qty: 0.1, kind: "retail", vip: false}, {qty: 50, kind: "retail", vip: false}]}]}}, {bonus: [], claim: {balance: 3, companies: [{amount: 0.5, band: false, calc: {grade: null}, employees: [{kind: "retail", qty: 0.1, vip: false}, {kind: "retail", qty: 50, vip: false}], fee: ["none", "gold"], kind: "corporate", plan: "plus", quota: [1], risk: [false], scores: {discount: [18, 0.5]}, surcharge: [100], tag: {ok: false, v: true}, total: [false]}], exposure: false, points: 18, rate: 18, share: 0.5, tier: "gold", weight: 10}, meta: {health: [false]}}], + {input: {claim: {balance: 3, rate: 100, weight: 1.5, tier: "bronze", companies: [{amount: 10, balance: 1, plan: "basic", kind: "retail", employees: [{qty: 50, kind: "retail", vip: true}, {qty: 5, kind: "retail", vip: true}]}, {amount: 250, balance: 10, plan: "trial", kind: "corporate", employees: []}]}}, goals: ["company.surcharge", "company.band", "company.scores.discount"], output: {claim: {balance: 3, companies: [{amount: 10, balance: 1, band: false, employees: [{kind: "retail", qty: 50, vip: true}, {kind: "retail", qty: 5, vip: true}], fee: ["none", "gold"], kind: "retail", plan: "basic", scores: {discount: [100, 10]}, surcharge: [100]}, {amount: 250, balance: 10, band: false, employees: [], fee: ["none", "gold"], kind: "corporate", plan: "trial", scores: {discount: [100, 250]}, surcharge: [100]}], rate: 100, tier: "bronze", weight: 1.5}}}, + {input: {claim: {balance: 0, rate: 100, weight: 18, tier: "gold", companies: [{amount: 1000, plan: "premium", kind: "retail", employees: [{qty: -1, kind: "retail", vip: true}, {qty: 1.5, kind: "retail", vip: true}]}, {amount: 5, balance: null, plan: "basic", kind: "corporate", employees: []}, {amount: 250, balance: 0, plan: "plus", kind: "retail", employees: [{qty: 1.5, kind: "corporate", vip: false}]}]}}, goals: ["company.quota", "company.calc.grade"], output: {claim: {balance: 0, companies: [{amount: 1000, band: false, calc: {grade: 0}, employees: [{kind: "retail", qty: -1, vip: true}, {kind: "retail", qty: 1.5, vip: true}], kind: "retail", plan: "premium", quota: [1], risk: [false], total: [false, false]}, {amount: 5, balance: null, band: false, calc: {grade: null}, employees: [], kind: "corporate", plan: "basic", quota: [1], risk: [false], total: [false]}, {amount: 250, balance: 0, band: false, calc: {grade: null}, employees: [{kind: "corporate", qty: 1.5, vip: false}], kind: "retail", plan: "plus", quota: [1], risk: [false], total: [false]}], exposure: false, points: 100, rate: 100, tier: "gold", weight: 18}}}, + {input: {claim: {balance: 0, rate: 1, weight: 1000, tier: "gold", companies: [{amount: 2, plan: "plus", kind: "corporate", employees: [{qty: 2.50, kind: "corporate", vip: true}]}]}}, goals: ["claim.points", "company.fee"], output: {claim: {balance: 0, companies: [{amount: 2, employees: [{kind: "corporate", qty: 2.50, vip: true}], fee: ["none", "gold"], kind: "corporate", plan: "plus", scores: {discount: [1, 2]}, surcharge: [100]}], exposure: false, points: 1, rate: 1, tier: "gold", weight: 1000}}}, + {input: {claim: {balance: 18, rate: 5, weight: -1, tier: "gold", companies: []}}, goals: ["claim.share", "company.band"], output: "!error: ExpressionFailed"}, + {input: {claim: {balance: 2, rate: 250, weight: 250, tier: "gold", companies: [{amount: 100, balance: 1.5, plan: "basic", kind: "retail", employees: []}, {amount: 0.000001, balance: 0.25, plan: "trial", kind: "retail", employees: [{qty: 18, kind: "corporate", vip: false}]}]}}, goals: ["claim.points", "company.fee"], output: {claim: {balance: 2, companies: [{amount: 100, balance: 1.5, employees: [], fee: ["none", "gold"], kind: "retail", plan: "basic", scores: {discount: [250, 100]}, surcharge: [100]}, {amount: 0.000001, balance: 0.25, employees: [{kind: "corporate", qty: 18, vip: false}], fee: ["none", "gold"], kind: "retail", plan: "trial", scores: {discount: [250, 0.000001]}, surcharge: [100]}], exposure: false, points: 250, rate: 250, tier: "gold", weight: 250}}}, + {input: {claim: {balance: 2, rate: 1.5, weight: 18, tier: "bronze", companies: [{amount: 1000, balance: -0, plan: "basic", kind: "retail", employees: [{qty: 1.5, kind: "retail", vip: true}, {qty: 2, kind: "retail", vip: true}]}, {amount: 18, balance: 65, plan: "basic", kind: "corporate", employees: [{qty: 3, kind: "retail", vip: false}, {qty: 0.000001, kind: "retail", vip: false}]}]}}, goals: ["claim.points", "company.calc.grade"], output: {claim: {balance: 2, companies: [{amount: 1000, balance: 0, calc: {grade: 2}, employees: [{kind: "retail", qty: 1.5, vip: true}, {kind: "retail", qty: 2, vip: true}], kind: "retail", plan: "basic"}, {amount: 18, balance: 65, calc: {grade: null}, employees: [{kind: "retail", qty: 3, vip: false}, {kind: "retail", qty: 0.000001, vip: false}], kind: "corporate", plan: "basic"}], exposure: false, points: 1, rate: 1.5, tier: "bronze", weight: 18}}}, + {input: {claim: {balance: 10, rate: 1, weight: 10, tier: "gold", companies: [{amount: 65, balance: 0.000001, plan: "premium", kind: "retail", employees: [{qty: 10, kind: "retail", vip: false}, {qty: 18, kind: "retail", vip: true}]}, {amount: 5, balance: 1000, plan: "plus", kind: "retail", employees: []}, {amount: 1000, balance: 123456789.123, plan: "premium", kind: "retail", employees: [{qty: 18, kind: "corporate", vip: true}, {qty: 50, kind: "corporate", vip: true}]}, {amount: 1, balance: 18, plan: "plus", kind: "retail", employees: [{qty: 2, kind: "corporate", vip: false}, {qty: 1000, kind: "retail", vip: false}]}, {amount: 0, balance: 5, plan: "premium", kind: "corporate", employees: [{qty: -1, kind: "corporate", vip: false}, {qty: 5, kind: "retail", vip: true}, {qty: 1, kind: "corporate", vip: false}]}], extraField: 1}}, goals: ["company.scores.discount"], output: {claim: {balance: 10, companies: [{amount: 65, balance: 0.000001, employees: [{kind: "retail", qty: 10, vip: false}, {kind: "retail", qty: 18, vip: true}], fee: ["none", "gold"], kind: "retail", plan: "premium", scores: {discount: [1, 65]}, surcharge: [100]}, {amount: 5, balance: 1000, employees: [], fee: ["none", "gold"], kind: "retail", plan: "plus", scores: {discount: [1, 5]}, surcharge: [100]}, {amount: 1000, balance: 123456789.123, employees: [{kind: "corporate", qty: 18, vip: true}, {kind: "corporate", qty: 50, vip: true}], fee: ["none", "gold"], kind: "retail", plan: "premium", scores: {discount: [1, 1000]}, surcharge: [100]}, {amount: 1, balance: 18, employees: [{kind: "corporate", qty: 2, vip: false}, {kind: "retail", qty: 1000, vip: false}], fee: ["none", "gold"], kind: "retail", plan: "plus", scores: {discount: [1, 1]}, surcharge: [100]}, {amount: 0, balance: 5, employees: [{kind: "corporate", qty: -1, vip: false}, {kind: "retail", qty: 5, vip: true}, {kind: "corporate", qty: 1, vip: false}], fee: ["none", "gold"], kind: "corporate", plan: "premium", scores: {discount: [1, 0]}, surcharge: [100]}], extraField: 1, rate: 1, tier: "gold", weight: 10}}}, + {input: {claim: {balance: 100, rate: 0, weight: 10, tier: "silver", companies: [{amount: 2, plan: "premium", kind: "retail", employees: [{qty: 10, kind: "retail", vip: false}]}]}}, goals: ["meta.health", "company.quota", "bonus"], output: {bonus: [false], claim: {balance: 100, companies: [{amount: 2, band: false, calc: {grade: null}, employees: [{kind: "retail", qty: 10, vip: false}], kind: "retail", plan: "premium", quota: [1], risk: [false], total: [false]}], exposure: null, points: null, rate: 0, tier: "silver", weight: 10}, meta: {health: [false, false]}}}, + [{claim: {balance: 2, rate: 10, weight: 1000, tier: null, companies: [{amount: 5, balance: 0.25, plan: "basic", kind: "retail", employees: [{qty: 1.5, kind: "retail", vip: false}]}, {amount: 1.5, balance: 100, plan: "trial", kind: "corporate", employees: [{qty: 18, kind: "corporate", vip: false}, {qty: -0.5, kind: "retail", vip: false}]}, {amount: 2.50, balance: 18, plan: "trial", kind: "retail", employees: [{qty: 18, kind: "corporate", vip: false}]}]}}, "!error: MissingRequiredInputs"], + [{claim: {balance: 18, rate: 2.50, weight: 18, tier: "gold", companies: [{amount: 3, balance: [1], plan: "basic", kind: "corporate", employees: [{qty: 0, kind: "retail", vip: false}, {qty: 10, kind: "retail", vip: false}]}, {amount: 99999999999999999999, balance: 1.5, plan: "basic", kind: "corporate", employees: []}]}}, "!error: InputValidationFailed"], + {input: {claim: {balance: 1000, rate: 1.5, weight: 2, tier: "silver", companies: [{amount: 5, balance: 1.5, plan: "trial", kind: "retail", employees: []}, {amount: 0, balance: 100, plan: "premium", kind: "retail", employees: []}]}}, goals: ["meta.health", "company.total"], output: {bonus: [false], claim: {balance: 1000, companies: [{amount: 5, balance: 1.5, band: false, calc: {grade: null}, employees: [], kind: "retail", plan: "trial", quota: [1], risk: [false], total: [false]}, {amount: 0, balance: 100, band: false, calc: {grade: null}, employees: [], kind: "retail", plan: "premium", quota: [1], risk: [false], total: [false]}], exposure: false, points: 0, rate: 1.5, tier: "silver", weight: 2}, meta: {health: [false, false]}}}, + [{claim: {balance: 0.25, rate: -0.5, weight: 2, tier: "silver", companies: [{amount: 50, balance: 50, plan: "basic", kind: "retail", employees: []}, {amount: 10, balance: 18, plan: "basic", kind: "retail", employees: [{qty: 1000, kind: "retail", vip: true}, {qty: 3, kind: "retail", vip: false}]}, {amount: 18, balance: 250, plan: "plus", kind: "corporate", employees: [{qty: 250, kind: "corporate", vip: true}]}, {amount: 0, balance: 7.25, plan: "basic", kind: "corporate", employees: [{qty: 2, kind: "retail", vip: false}, {qty: 18, kind: "retail", vip: true}, {qty: 123456789.123, kind: "retail", vip: false}]}]}}, {bonus: [false], claim: {balance: 0.25, companies: [{amount: 50, balance: 50, band: false, calc: {grade: null}, employees: [], fee: ["gold"], kind: "retail", plan: "basic", quota: [1], risk: [false], scores: {discount: [50]}, surcharge: [100], tag: {ok: true, v: true}, total: [false]}, {amount: 10, balance: 18, band: false, calc: {grade: 0.25}, employees: [{kind: "retail", qty: 1000, vip: true}, {kind: "retail", qty: 3, vip: false}], fee: ["gold"], kind: "retail", plan: "basic", quota: [1], risk: [false], scores: {discount: [10]}, surcharge: [100], tag: {ok: false, v: true}, total: [false, false]}, {amount: 18, balance: 250, band: false, calc: {grade: 0.25}, employees: [{kind: "corporate", qty: 250, vip: true}], fee: ["gold"], kind: "corporate", plan: "plus", quota: [1], risk: [false], scores: {discount: [18]}, surcharge: [100], tag: {ok: true, v: true}, total: [false]}, {amount: 0, balance: 7.25, band: false, calc: {grade: 0.25}, employees: [{kind: "retail", qty: 2, vip: false}, {kind: "retail", qty: 18, vip: true}, {kind: "retail", qty: 123456789.123, vip: false}], fee: ["gold"], kind: "corporate", plan: "basic", quota: [1], risk: [false], scores: {discount: [0]}, surcharge: [100], tag: {ok: false, v: true}, total: [false]}], exposure: null, points: null, rate: -0.5, share: 19.50, tier: "silver", weight: 2}, meta: {health: [false, false]}}], + {input: {claim: {rate: 100, weight: 1, tier: "gold", companies: [{amount: 0, plan: "basic", kind: "corporate", employees: []}]}}, goals: ["claim.exposure", "company.total"], output: {claim: {companies: [{amount: 0, band: false, calc: {grade: null}, employees: [], kind: "corporate", plan: "basic", quota: [1], risk: [false], total: [false]}], exposure: false, points: 100, rate: 100, tier: "gold", weight: 1}}}, + {input: {claim: {balance: 1.5, rate: 5, weight: 1.5, tier: "gold", companies: [{amount: 50, balance: 100, plan: "basic", kind: "retail", employees: [{qty: 18, kind: "retail", vip: false}, {qty: 100, kind: "retail", vip: false}]}, {amount: 2.50, balance: 100, plan: "basic", kind: "retail", employees: [{qty: 0, kind: "retail", vip: true}, {qty: 0.25, kind: "corporate", vip: true}, {qty: 65, kind: "corporate", vip: true}]}, {amount: 0.25, balance: 0.000001, plan: "basic", kind: "retail", employees: []}]}}, goals: ["company.surcharge"], output: {claim: {balance: 1.5, companies: [{amount: 50, balance: 100, employees: [{kind: "retail", qty: 18, vip: false}, {kind: "retail", qty: 100, vip: false}], fee: ["none", "gold"], kind: "retail", plan: "basic", scores: {discount: [5, 50]}, surcharge: [100]}, {amount: 2.50, balance: 100, employees: [{kind: "retail", qty: 0, vip: true}, {kind: "corporate", qty: 0.25, vip: true}, {kind: "corporate", qty: 65, vip: true}], fee: ["none", "gold"], kind: "retail", plan: "basic", scores: {discount: [5, 2.50]}, surcharge: [100]}, {amount: 0.25, balance: 0.000001, employees: [], fee: ["none", "gold"], kind: "retail", plan: "basic", scores: {discount: [5, 0.25]}, surcharge: [100]}], rate: 5, tier: "gold", weight: 1.5}}}, + {input: {claim: {balance: 2.50, rate: 1, weight: 18, tier: "gold", companies: []}}, goals: ["company.calc.grade", "company.fee"], output: {claim: {balance: 2.50, companies: [], rate: 1, tier: "gold", weight: 18}}}, + {input: {claim: {balance: 1e3, rate: 18, weight: 18, tier: "gold", companies: [{amount: 52, balance: 1.5, plan: "trial", kind: "retail", employees: [{qty: 0.000001, kind: "retail", vip: true}, {qty: 1, kind: "retail", vip: false}]}, {amount: -500, balance: 10, plan: "premium", kind: "retail", employees: []}]}}, goals: ["company.calc.grade", "company.quota", "company.risk"], output: {claim: {balance: 1000, companies: [{amount: 52, balance: 1.5, band: false, calc: {grade: 1000}, employees: [{kind: "retail", qty: 0.000001, vip: true}, {kind: "retail", qty: 1, vip: false}], kind: "retail", plan: "trial", quota: [1], risk: [false], total: [false]}, {amount: -500, balance: 10, band: false, calc: {grade: null}, employees: [], kind: "retail", plan: "premium", quota: [1], risk: [false], total: [false]}], exposure: false, points: 0, rate: 18, tier: "gold", weight: 18}}}, + [{claim: {balance: 18, rate: 0, weight: 0.5, tier: "bronze", companies: [{amount: 100, balance: 18, plan: "basic", kind: "retail", employees: [{qty: 1.5, kind: "corporate", vip: true}, {qty: 1.5, kind: "retail", vip: true}]}]}}, {bonus: [false], claim: {balance: 18, companies: [{amount: 100, balance: 18, band: false, calc: {grade: 18}, employees: [{kind: "corporate", qty: 1.5, vip: true}, {kind: "retail", qty: 1.5, vip: true}], fee: ["gold"], kind: "retail", plan: "basic", quota: [1], risk: [false], scores: {discount: [100]}, surcharge: [100], tag: {ok: true, v: false}, total: [false]}], exposure: null, points: null, rate: 0, share: 100, tier: "bronze", weight: 0.5}, meta: {health: [false, false]}}], + {input: {claim: {balance: -500, rate: 0.5, weight: 2, tier: "gold", companies: [{amount: 1000, balance: 2, plan: "plus", kind: "corporate", employees: [{qty: 123456789.123, kind: "retail", vip: true}, {qty: 1.5, kind: "retail", vip: false}]}, {amount: 50, balance: 5, plan: "trial", kind: "retail", employees: [{qty: 100, kind: "retail", vip: true}, {qty: 1.5, kind: "retail", vip: true}, {qty: 100, kind: "corporate", vip: true}]}, {amount: 0, balance: 5, plan: "basic", kind: "retail", employees: []}, {amount: 18, balance: 100, plan: "basic", kind: "retail", employees: [{qty: 10, kind: "retail", vip: true}]}, {amount: 3, balance: 3, plan: "plus", kind: "corporate", employees: []}, {amount: 0.25, balance: 250, plan: "basic", kind: "corporate", employees: [{qty: 1000, kind: "corporate", vip: false}, {qty: 0, kind: "retail", vip: false}]}, {amount: 0.25, balance: 250, plan: "trial", kind: "retail", employees: [{qty: 10, kind: "corporate", vip: true}, {qty: 0.25, kind: "corporate", vip: true}, {qty: 18, kind: "retail", vip: true}]}, {amount: 0, balance: 250, plan: "plus", kind: "retail", employees: [{qty: 1.5, kind: "retail", vip: false}, {qty: 1000, kind: "retail", vip: true}]}, {amount: 232, balance: 10, plan: "basic", kind: "retail", employees: [{qty: 5, kind: "retail", vip: false}, {qty: 487, kind: "corporate", vip: false}, {qty: 1000, kind: "retail", vip: false}]}]}}, goals: ["meta.health", "claim.exposure", "bonus"], output: {bonus: [], claim: {balance: -500, companies: [{amount: 1000, balance: 2, employees: [{kind: "retail", qty: 123456789.123, vip: true}, {kind: "retail", qty: 1.5, vip: false}], kind: "corporate", plan: "plus"}, {amount: 50, balance: 5, employees: [{kind: "retail", qty: 100, vip: true}, {kind: "retail", qty: 1.5, vip: true}, {kind: "corporate", qty: 100, vip: true}], kind: "retail", plan: "trial"}, {amount: 0, balance: 5, employees: [], kind: "retail", plan: "basic"}, {amount: 18, balance: 100, employees: [{kind: "retail", qty: 10, vip: true}], kind: "retail", plan: "basic"}, {amount: 3, balance: 3, employees: [], kind: "corporate", plan: "plus"}, {amount: 0.25, balance: 250, employees: [{kind: "corporate", qty: 1000, vip: false}, {kind: "retail", qty: 0, vip: false}], kind: "corporate", plan: "basic"}, {amount: 0.25, balance: 250, employees: [{kind: "corporate", qty: 10, vip: true}, {kind: "corporate", qty: 0.25, vip: true}, {kind: "retail", qty: 18, vip: true}], kind: "retail", plan: "trial"}, {amount: 0, balance: 250, employees: [{kind: "retail", qty: 1.5, vip: false}, {kind: "retail", qty: 1000, vip: true}], kind: "retail", plan: "plus"}, {amount: 232, balance: 10, employees: [{kind: "retail", qty: 5, vip: false}, {kind: "corporate", qty: 487, vip: false}, {kind: "retail", qty: 1000, vip: false}], kind: "retail", plan: "basic"}], exposure: false, points: null, rate: 0.5, tier: "gold", weight: 2}, meta: {health: [false]}}}, + {input: {claim: {balance: 10, rate: 0, weight: -0.01, tier: "silver", companies: [{amount: 10, balance: null, plan: "basic", kind: "corporate", employees: [{qty: 100, kind: "retail", vip: false}, {qty: 99999999999999999999, kind: "corporate", vip: true}]}, {amount: 1000000, plan: "trial", kind: "corporate", employees: [{qty: 18, kind: "corporate", vip: false}, {qty: 1e3, kind: "retail", vip: true}, {qty: 5, kind: "retail", vip: false}]}, {amount: 5, balance: null, plan: "trial", kind: "retail", employees: [{qty: 100, kind: "retail", vip: true}]}, {amount: 100, balance: null, plan: "basic", kind: "retail", employees: [{qty: 1.5, kind: "retail", vip: false}]}]}}, goals: ["company.calc.grade", "claim.share"], output: {claim: {balance: 10, companies: [{amount: 10, balance: null, calc: {grade: 10}, employees: [{kind: "retail", qty: 100, vip: false}, {kind: "corporate", qty: 99999999999999999999, vip: true}], kind: "corporate", plan: "basic"}, {amount: 1000000, calc: {grade: 10}, employees: [{kind: "corporate", qty: 18, vip: false}, {kind: "retail", qty: 1000, vip: true}, {kind: "retail", qty: 5, vip: false}], kind: "corporate", plan: "trial"}, {amount: 5, balance: null, calc: {grade: 10}, employees: [{kind: "retail", qty: 100, vip: true}], kind: "retail", plan: "trial"}, {amount: 100, balance: null, calc: {grade: null}, employees: [{kind: "retail", qty: 1.5, vip: false}], kind: "retail", plan: "basic"}], rate: 0, share: 250028.75, tier: "silver", weight: -0.01}}}, + {input: {claim: {balance: 0.25, rate: 0.25, weight: 10, tier: "gold", companies: [{amount: 18, plan: "plus", kind: "corporate", employees: [{qty: 1000000, kind: "retail", vip: true}, {qty: 18, kind: "retail", vip: false}]}, {amount: 1.5, balance: 100, plan: "plus", kind: "retail", employees: [{qty: 0.5, kind: "retail", vip: false}, {qty: 3, kind: "retail", vip: true}, {qty: 99999999999999999999, kind: "retail", vip: false}]}, {amount: 1, balance: 0, plan: "premium", kind: "retail", employees: [{qty: 250, kind: "retail", vip: true}]}, {amount: 2, balance: -0.5, plan: "basic", kind: "retail", employees: [{qty: 10, kind: "retail", vip: false}, {qty: 2, kind: "corporate", vip: false}]}]}}, goals: ["claim.exposure"], output: {claim: {balance: 0.25, companies: [{amount: 18, employees: [{kind: "retail", qty: 1000000, vip: true}, {kind: "retail", qty: 18, vip: false}], kind: "corporate", plan: "plus"}, {amount: 1.5, balance: 100, employees: [{kind: "retail", qty: 0.5, vip: false}, {kind: "retail", qty: 3, vip: true}, {kind: "retail", qty: 99999999999999999999, vip: false}], kind: "retail", plan: "plus"}, {amount: 1, balance: 0, employees: [{kind: "retail", qty: 250, vip: true}], kind: "retail", plan: "premium"}, {amount: 2, balance: -0.5, employees: [{kind: "retail", qty: 10, vip: false}, {kind: "corporate", qty: 2, vip: false}], kind: "retail", plan: "basic"}], exposure: null, points: null, rate: 0.25, tier: "gold", weight: 10}}}, + ], +} + +// seed 352600 (attempt 0) +{ + name: "goals 27: borrower/vehicles: 1 assertion, 4 expression, 2 match, 3 table; 3 root, 5 per-member, 4 top-level computed", + policy: { + models: {borrower: {price: "number", age: "number", urgent: "boolean", limit: "number?", vehicles: "vehicle[]"}, vehicle: {income: "number?", insured: "boolean", active: "boolean?"}}, + globals: {settings: {baseRate: "number"}}, + blocks: [ + {table: "t1", inputs: ["baseRate", "borrower.urgent"], outputs: ["vehicle.ok", "vehicle.weighted"], rules: [ + ["", "", "'US'", "(vehicle.insured ? 'none' : 'x')"], + ["[100..101]", "true", "'VIP'", ""], + ["<= 18", "", "'A1'", "'retail'"], + ["[50..544]", "true", "'A1'", "string(borrower.price)"], + ["", "false", "'low'", "'ok'"], + ["<= 0.5", "true", "'gold'", "`${'a'}/${borrower.price}`"], + ["", "false", "`${250}/${borrower.urgent}`", "((vehicle.active ?? false) ? 'retail' : 'gold')"], + ]}, + {expression: "summary", value: "0.5 == borrower.age"}, + {table: "t3", hit: "collect", inputs: ["borrower.urgent", "baseRate"], outputs: ["borrower.total"], rules: [ + ["false", ">= 0.5", "trunc(borrower.price)"], + ["true", "", "baseRate"], + ["true", "< 5", "baseRate"], + ["false", ">= 0.25", "borrower.age"], + ["true", "< 18", "(borrower.price % (abs(0) + 1))"], + ]}, + {expression: "borrower.health", value: "(min(borrower.total) ?? 0)"}, + {match: "vehicle.discount", arms: [["sum(borrower.total) >= 18", "baseRate"], ["vehicle.active == null", "(min([abs(len(borrower.vehicles)), 1000]) ^ 3)"], ["borrower.health in (35..120]", "baseRate"], ["", "(baseRate / 3)"]]}, + {expression: "vehicle.tag", value: "map(borrower.vehicles, (min([abs(#.discount), 1000]) ^ 0))"}, + {assertion: "borrower.adjusted", conditions: [["or", "not (borrower.age >= baseRate)", 1]]}, + {expression: "vehicle.margin", value: "(borrower.price <= 250 ? borrower.limit : null)"}, + {table: "t9", inputs: ["borrower.price"], outputs: ["meta.bonus", "meta.capped"], rules: [ + [">= 18", "borrower.age", "'x'"], + [">= 2", "borrower.age", ""], + ["!= 10", "-(borrower.age)", "'x'"], + ["<= 18", "borrower.age", "'none'"], + ["<= 3", "borrower.health", "'gold'"], + ["> 1", "", "'high'"], + ]}, + {match: "meta.exposure", arms: [["borrower.health in [47..122]", "borrower.price <= (meta.bonus ?? 0)"], ["(borrower.adjusted and borrower.urgent)", "summary"], ["", "borrower.urgent"]]}, + ], + }, + cases: [ + {input: {baseRate: 0, borrower: {price: 0.5, age: 0.5, urgent: true, limit: 1000, vehicles: [{income: 1e3, insured: true, active: null}]}}, goals: ["vehicle.weighted", "borrower.adjusted"], output: {baseRate: 0, borrower: {adjusted: false, age: 0.5, limit: 1000, price: 0.5, urgent: true, vehicles: [{active: null, income: 1000, insured: true, ok: "US", weighted: "none"}]}}}, + {input: {baseRate: 10, borrower: {price: 18, age: -1, urgent: false, limit: 18, vehicles: [{income: 1000, insured: true, active: false}, {income: 250, insured: true, active: true}, {income: 5, insured: false, active: true}, {income: 2, insured: true, active: true}, {income: 1e3, insured: true, active: false}]}}, goals: ["vehicle.margin", "borrower.total", "summary"], output: {baseRate: 10, borrower: {age: -1, limit: 18, price: 18, total: [18, -1], urgent: false, vehicles: [{active: false, income: 1000, insured: true, margin: 18}, {active: true, income: 250, insured: true, margin: 18}, {active: true, income: 5, insured: false, margin: 18}, {active: true, income: 2, insured: true, margin: 18}, {active: false, income: 1000, insured: true, margin: 18}]}, summary: false}}, + [{baseRate: 10, borrower: {price: -500, age: -500, urgent: false, limit: 10, vehicles: [{income: null, insured: false, active: false}, {income: 10, insured: true, active: true}, {income: 2, insured: false}, {income: null, insured: false, active: false}]}}, {baseRate: 10, borrower: {adjusted: true, age: -500, health: -500, limit: 10, price: -500, total: [-500, -500], urgent: false, vehicles: [{active: false, discount: 3.3333333333333333333333333333, income: null, insured: false, margin: 10, ok: "US", tag: [1, 1, 1, 1], weighted: "x"}, {active: true, discount: 3.3333333333333333333333333333, income: 10, insured: true, margin: 10, ok: "US", tag: [1, 1, 1, 1], weighted: "none"}, {discount: 64, income: 2, insured: false, margin: 10, ok: "US", tag: [1, 1, 1, 1], weighted: "x"}, {active: false, discount: 3.3333333333333333333333333333, income: null, insured: false, margin: 10, ok: "US", tag: [1, 1, 1, 1], weighted: "x"}]}, meta: {bonus: 500, capped: "x", exposure: false}}], + {input: {baseRate: 0.5, borrower: {price: 100, age: 18, urgent: true, limit: true, vehicles: [{income: 250, insured: true, active: true}]}}, goals: ["meta.bonus", "vehicle.margin", "vehicle.tag"], output: "!error: InputValidationFailed"}, + {input: {baseRate: 100, borrower: {price: 0.000001, age: 250, urgent: false, limit: 100, vehicles: [{income: 100, insured: true, active: false}]}}, goals: ["borrower.adjusted", "borrower.total", "summary"], output: {baseRate: 100, borrower: {adjusted: false, age: 250, limit: 100, price: 0.000001, total: [0, 250], urgent: false, vehicles: [{active: false, income: 100, insured: true}]}, summary: false}}, + {input: {baseRate: 10, borrower: {price: 0.000001, age: 250, urgent: false, limit: 0.000001, vehicles: [{income: 99999999999999999999, insured: true, active: false}]}}, goals: ["meta.exposure"], output: {baseRate: 10, borrower: {adjusted: false, age: 250, health: 0, limit: 0.000001, price: 0.000001, total: [0, 250], urgent: false, vehicles: [{active: false, income: 99999999999999999999, insured: true}]}, meta: {exposure: false}}}, + {input: {baseRate: 0, borrower: {price: 50, age: 1000, urgent: true, limit: 0.5, vehicles: [], extraField: 1}}, goals: ["borrower.adjusted", "vehicle.discount"], output: {baseRate: 0, borrower: {adjusted: false, age: 1000, extraField: 1, health: 0, limit: 0.5, price: 50, total: [0, 0, 0], urgent: true, vehicles: []}}}, + {input: {baseRate: 0.5, borrower: {price: 18, age: 100, urgent: true, limit: 10, vehicles: [{income: 10, insured: true, active: false}, {income: 0, insured: true, active: false}, {income: 65, insured: true, active: true}]}}, goals: ["meta.bonus", "borrower.health"], output: {baseRate: 0.5, borrower: {age: 100, health: 0, limit: 10, price: 18, total: [0.5, 0.5, 0], urgent: true, vehicles: [{active: false, income: 10, insured: true}, {active: false, income: 0, insured: true}, {active: true, income: 65, insured: true}]}, meta: {bonus: 100, capped: "x"}}}, + {input: {baseRate: -2, borrower: {price: 0.5, age: 2, urgent: true, vehicles: [{income: 0.1, insured: true}, {income: 0.1, insured: true, active: true}]}}, goals: ["meta.bonus", "vehicle.weighted"], output: {baseRate: -2, borrower: {age: 2, price: 0.5, urgent: true, vehicles: [{income: 0.1, insured: true, ok: "US", weighted: "none"}, {active: true, income: 0.1, insured: true, ok: "US", weighted: "none"}]}, meta: {bonus: -2, capped: "x"}}}, + {input: {baseRate: 100, borrower: {price: 2, age: -500, urgent: false, limit: 18, vehicles: [{income: 18, insured: false, active: false}]}}, goals: ["vehicle.discount"], output: {baseRate: 100, borrower: {age: -500, health: -500, limit: 18, price: 2, total: [2, -500], urgent: false, vehicles: [{active: false, discount: 33.333333333333333333333333333, income: 18, insured: false}]}}}, + {input: {baseRate: 1, borrower: {price: 99999999999999999999, age: 0.000001, urgent: true, limit: 18, vehicles: [{income: 0.25, insured: false, active: false}, {income: 18, insured: true, active: true}]}}, goals: ["borrower.total", "meta.exposure", "summary"], output: {baseRate: 1, borrower: {adjusted: true, age: 0.000001, health: 0, limit: 18, price: 99999999999999999999, total: [1, 1, 0], urgent: true, vehicles: [{active: false, income: 0.25, insured: false}, {active: true, income: 18, insured: true}]}, meta: {exposure: false}, summary: false}}, + {input: {baseRate: 100, borrower: {price: 0, age: 0.000001, urgent: true, limit: null, vehicles: [{insured: false}, {insured: true, active: null}, {insured: false, active: false}, {income: null, insured: true, active: null}]}}, goals: ["meta.exposure", "borrower.health"], output: {baseRate: 100, borrower: {adjusted: true, age: 0.000001, health: 100, limit: null, price: 0, total: [100], urgent: true, vehicles: [{insured: false}, {active: null, insured: true}, {active: false, insured: false}, {active: null, income: null, insured: true}]}, meta: {bonus: -0.000001, capped: "x", exposure: false}}}, + {input: {baseRate: 100, borrower: {price: 2, age: 0.5, urgent: false, vehicles: [{income: -0, insured: true, active: true}, {insured: true, active: true}]}}, goals: ["vehicle.tag", "meta.bonus", "borrower.health"], output: {baseRate: 100, borrower: {age: 0.5, health: 0.5, price: 2, total: [2, 0.5], urgent: false, vehicles: [{active: true, discount: 33.333333333333333333333333333, income: 0, insured: true, tag: [1, 1]}, {active: true, discount: 33.333333333333333333333333333, insured: true, tag: [1, 1]}]}, meta: {bonus: 0.5, capped: "x"}}}, + {input: {baseRate: 10, borrower: {price: 50, age: 250, urgent: false, limit: 1000, vehicles: [{insured: true, active: true}, {income: 10, insured: true, active: true}, {income: null, insured: false, active: false}]}}, goals: ["borrower.health"], output: {baseRate: 10, borrower: {age: 250, health: 50, limit: 1000, price: 50, total: [50, 250], urgent: false, vehicles: [{active: true, insured: true}, {active: true, income: 10, insured: true}, {active: false, income: null, insured: false}]}}}, + {input: {baseRate: 100, borrower: {price: 1000000, age: 250, urgent: true, limit: 100, vehicles: [{income: 18, insured: false, active: true}, {income: 0.5, insured: true, active: false}, {income: 250, insured: false, active: true}, {income: -0.5, insured: false, active: false}]}}, goals: ["vehicle.weighted", "vehicle.margin", "meta.capped"], output: {baseRate: 100, borrower: {age: 250, limit: 100, price: 1000000, urgent: true, vehicles: [{active: true, income: 18, insured: false, margin: null, ok: "US", weighted: "x"}, {active: false, income: 0.5, insured: true, margin: null, ok: "US", weighted: "none"}, {active: true, income: 250, insured: false, margin: null, ok: "US", weighted: "x"}, {active: false, income: -0.5, insured: false, margin: null, ok: "US", weighted: "x"}]}, meta: {bonus: 250, capped: "x"}}}, + {input: {baseRate: 1, borrower: {price: 99.99, age: 250, urgent: true, limit: 0.25, vehicles: []}}, goals: ["vehicle.ok", "borrower.health", "borrower.total"], output: {baseRate: 1, borrower: {age: 250, health: 0.99, limit: 0.25, price: 99.99, total: [1, 1, 0.99], urgent: true, vehicles: []}}}, + {input: {baseRate: -2, borrower: {price: 228, age: 5, urgent: false, limit: 99999999999999999999, vehicles: [{insured: false, active: null}, {income: null, insured: true}]}}, goals: ["vehicle.weighted", "borrower.adjusted", "vehicle.margin"], output: {baseRate: -2, borrower: {adjusted: false, age: 5, limit: 99999999999999999999, price: 228, urgent: false, vehicles: [{active: null, insured: false, margin: 99999999999999999999, ok: "US", weighted: "x"}, {income: null, insured: true, margin: 99999999999999999999, ok: "US", weighted: "none"}]}}}, + {input: {baseRate: -2, borrower: {price: 1000, age: 1000000, urgent: false, limit: 10, vehicles: [{income: 7.25, insured: true, active: false}, {income: 123456789.123, insured: false, active: false}]}}, goals: ["meta.bonus", "vehicle.margin"], output: {baseRate: -2, borrower: {age: 1000000, limit: 10, price: 1000, urgent: false, vehicles: [{active: false, income: 7.25, insured: true, margin: null}, {active: false, income: 123456789.123, insured: false, margin: null}]}, meta: {bonus: 1000000, capped: "x"}}}, + [{baseRate: 0, borrower: {price: 99999999999999999999, age: 18, urgent: false, limit: 10, vehicles: [{income: 100, insured: true, active: true}, {income: 250, insured: true, active: true}, {income: 3, insured: true, active: true}, {income: 0.5, insured: false, active: true}]}}, "!error: ExpressionFailed"], + ], +} + +// seed 352700 (attempt 0) +{ + name: "goals 28: tenant/companies + contact: 2 assertion, 2 expression, 1 match; 1 root, 3 per-member, 0 top-level computed", + policy: { + models: {tenant: {income: "number", insured: "boolean", balance: "number", plan: "string(basic|plus|premium|trial)", years: "number", companies: "company[]", contact: "contactInfo"}, company: {weight: "number", vip: "boolean?", city: "string"}, contactInfo: {rate: "number?"}}, + blocks: [ + {expression: "contactInfo.scores.band", value: "string(tenant.income)"}, + {match: "company.level", arms: [["(not (tenant.insured) and tenant.income != 100)", "tenant.years in (45..167)"], ["not (tenant.insured)", "(none(tenant.companies, 250 == #.weight) or not (tenant.insured))"], ["", "matches(company.city, '^[A-Z]')"]]}, + {assertion: "tenant.total", conditions: [["and", "250 == (tenant.contact.rate ?? 0)", 2], ["or", "contains(['none', 'none', ''], tenant.contact.scores.band)", 1], ["or", "matches(`${tenant.income}/${tenant.insured}`, '^.{2,}$')", 0]]}, + {assertion: "company.calc.segment", conditions: [["or", "tenant.contact.scores.band in ['Oslo', 'none']", 1], ["or", "matches(tenant.contact.scores.band, '^[A-Z]')", 2]]}, + {expression: "company.exposure", value: "len(filter(tenant.companies, #.vip == null))"}, + ], + }, + cases: [ + {input: {tenant: {income: -0.5, insured: false, balance: 250, plan: "premium", years: 1, companies: [], contact: {rate: -500}, extraField: 1}}, goals: ["company.level"], output: {tenant: {balance: 250, companies: [], contact: {rate: -500}, extraField: 1, income: -0.5, insured: false, plan: "premium", years: 1}}}, + {input: {tenant: {income: 1e3, insured: true, balance: 123456789.123, plan: "basic", years: 123456789.123, companies: [{weight: -0.5, vip: false, city: "US"}, {weight: 7.25, city: "US"}, {weight: 99.99, vip: null, city: "VIP"}], contact: {rate: null}}}, goals: ["company.level"], output: {tenant: {balance: 123456789.123, companies: [{city: "US", level: true, vip: false, weight: -0.5}, {city: "US", level: true, weight: 7.25}, {city: "VIP", level: true, vip: null, weight: 99.99}], contact: {rate: null}, income: 1000, insured: true, plan: "basic", years: 123456789.123}}}, + {input: {tenant: {income: -500, insured: true, balance: 99999999999999999999, plan: "premium", years: 1000000, companies: [{weight: 1000, vip: true, city: ""}, {weight: 250, vip: false, city: "日本"}], contact: {rate: 0.1}}}, goals: ["company.calc.segment"], output: {tenant: {balance: 99999999999999999999, companies: [{calc: {segment: false}, city: "", vip: true, weight: 1000}, {calc: {segment: false}, city: "日本", vip: false, weight: 250}], contact: {rate: 0.1, scores: {band: "-500"}}, income: -500, insured: true, plan: "premium", years: 1000000}}}, + {input: {tenant: {income: 250, insured: true, balance: 100, plan: "basic", years: 18, companies: [{weight: 250, vip: true, city: "abc"}, {weight: 2, vip: true, city: ""}, {weight: -0.01, city: "O'Neil"}, {weight: 5, vip: false, city: "US"}, {weight: -1, vip: false, city: "none"}], contact: {rate: 2}}}, goals: ["company.level"], output: {tenant: {balance: 100, companies: [{city: "abc", level: false, vip: true, weight: 250}, {city: "", level: false, vip: true, weight: 2}, {city: "O'Neil", level: true, weight: -0.01}, {city: "US", level: true, vip: false, weight: 5}, {city: "none", level: false, vip: false, weight: -1}], contact: {rate: 2}, income: 250, insured: true, plan: "basic", years: 18}}}, + {input: {tenant: {income: 1, insured: false, balance: 100, plan: "premium", years: 100, companies: [{weight: 1000000, vip: true, city: "none"}, {weight: 2, vip: true, city: "12"}], contact: {rate: 250}}}, goals: ["company.exposure", "tenant.total"], output: {tenant: {balance: 100, companies: [{city: "none", exposure: 0, vip: true, weight: 1000000}, {city: "12", exposure: 0, vip: true, weight: 2}], contact: {rate: 250, scores: {band: "1"}}, income: 1, insured: false, plan: "premium", total: true, years: 100}}}, + {input: {tenant: {income: -1, insured: false, balance: 0.5, plan: "basic", years: 250, companies: [{weight: -500, vip: false, city: "none"}], contact: {rate: 250}}}, goals: ["contactInfo.scores.band"], output: {tenant: {balance: 0.5, companies: [{city: "none", vip: false, weight: -500}], contact: {rate: 250, scores: {band: "-1"}}, income: -1, insured: false, plan: "basic", years: 250}}}, + [{tenant: {income: 65, insured: false, balance: -0.01, plan: "trial", years: 250, companies: [{weight: -0.5, vip: true, city: "DE"}, {weight: 99.99, vip: false, city: "3.5"}, {weight: 0.000001, vip: true, city: "none"}, {weight: 10, vip: false, city: "a"}, {weight: 123456789.123, vip: false, city: "Zed"}], contact: {rate: 10}}}, {tenant: {balance: -0.01, companies: [{calc: {segment: false}, city: "DE", exposure: 0, level: false, vip: true, weight: -0.5}, {calc: {segment: false}, city: "3.5", exposure: 0, level: false, vip: false, weight: 99.99}, {calc: {segment: false}, city: "none", exposure: 0, level: false, vip: true, weight: 0.000001}, {calc: {segment: false}, city: "a", exposure: 0, level: false, vip: false, weight: 10}, {calc: {segment: false}, city: "Zed", exposure: 0, level: false, vip: false, weight: 123456789.123}], contact: {rate: 10, scores: {band: "65"}}, income: 65, insured: false, plan: "trial", total: true, years: 250}}], + {input: {tenant: {income: 1e3, insured: true, balance: 10, plan: "premium", years: 1000000, companies: [{weight: -0.01, vip: true, city: "VIP"}, {weight: 99999999999999999999, vip: false, city: "x-y"}], contact: {rate: -0.5}, extraField: 1}}, goals: ["company.calc.segment", "company.exposure", "company.level"], output: {tenant: {balance: 10, companies: [{calc: {segment: false}, city: "VIP", exposure: 0, level: true, vip: true, weight: -0.01}, {calc: {segment: false}, city: "x-y", exposure: 0, level: false, vip: false, weight: 99999999999999999999}], contact: {rate: -0.5, scores: {band: "1000"}}, extraField: 1, income: 1000, insured: true, plan: "premium", years: 1000000}}}, + {input: {tenant: {income: 0.5, insured: false, balance: -0.5, plan: "plus", years: 1000000, companies: [{weight: -0, vip: false, city: "none"}], contact: {rate: 18}}}, goals: ["company.calc.segment", "company.level"], output: {tenant: {balance: -0.5, companies: [{calc: {segment: false}, city: "none", level: false, vip: false, weight: 0}], contact: {rate: 18, scores: {band: "0.5"}}, income: 0.5, insured: false, plan: "plus", years: 1000000}}}, + {input: {tenant: {income: -0, insured: false, balance: 100, plan: "premium", years: 5, companies: [{weight: 0.5, vip: true, city: "O'Neil"}], contact: {rate: 250}}}, goals: ["company.exposure", "tenant.total"], output: {tenant: {balance: 100, companies: [{city: "O'Neil", exposure: 0, vip: true, weight: 0.5}], contact: {rate: 250, scores: {band: "0"}}, income: 0, insured: false, plan: "premium", total: true, years: 5}}}, + {input: {tenant: {income: 18, insured: true, balance: 250, plan: "basic", years: 250, companies: [], contact: {rate: 0.000001}}}, goals: ["company.level", "contactInfo.scores.band", "company.calc.segment"], output: {tenant: {balance: 250, companies: [], contact: {rate: 0.000001, scores: {band: "18"}}, income: 18, insured: true, plan: "basic", years: 250}}}, + {input: {tenant: {income: 123456789.123, insured: true, balance: -0, plan: "trial", years: -0.5, companies: [{weight: -0.01, vip: true, city: "-"}, {weight: 100, vip: true, city: "US"}], contact: {rate: 250}}}, goals: ["tenant.total", "company.exposure", "company.calc.segment"], output: {tenant: {balance: 0, companies: [{calc: {segment: false}, city: "-", exposure: 0, vip: true, weight: -0.01}, {calc: {segment: false}, city: "US", exposure: 0, vip: true, weight: 100}], contact: {rate: 250, scores: {band: "123456789.123"}}, income: 123456789.123, insured: true, plan: "trial", total: true, years: -0.5}}}, + {input: {tenant: {income: 100, insured: 1, balance: 250, plan: "trial", years: 250, companies: [], contact: {rate: -1}}}, goals: ["company.calc.segment"], output: "!error: InputValidationFailed"}, + {input: {tenant: {income: 65, insured: false, balance: 123456789.123, plan: "premium", years: -1, companies: [{weight: 2, vip: false, city: "abc"}], contact: {rate: 118}}}, goals: ["company.calc.segment"], output: {tenant: {balance: 123456789.123, companies: [{calc: {segment: false}, city: "abc", vip: false, weight: 2}], contact: {rate: 118, scores: {band: "65"}}, income: 65, insured: false, plan: "premium", years: -1}}}, + {input: {tenant: {income: 7.25, insured: false, balance: 1e3, plan: "plus", years: 2.50, companies: [], contact: {rate: 99999999999999999999}}}, goals: ["tenant.total", "company.calc.segment"], output: {tenant: {balance: 1000, companies: [], contact: {rate: 99999999999999999999, scores: {band: "7.25"}}, income: 7.25, insured: false, plan: "plus", total: true, years: 2.50}}}, + {input: {tenant: {income: 250, insured: false, balance: -0, plan: "trial", years: -500, companies: [{weight: 2, city: "日本"}], contact: {rate: 0.5}}}, goals: ["company.exposure"], output: {tenant: {balance: 0, companies: [{city: "日本", exposure: 1, weight: 2}], contact: {rate: 0.5}, income: 250, insured: false, plan: "trial", years: -500}}}, + {input: {tenant: {income: 1e3, insured: false, balance: 99.99, plan: "trial", years: 0.000001, companies: [{weight: 0.1, vip: true, city: "a"}, {weight: 99999999999999999999, vip: false, city: "-"}, {weight: 99.99, vip: true, city: "Oslo"}, {weight: 1, vip: false, city: "Oslo"}, {weight: 0.000001, vip: false, city: ""}], contact: {rate: 5}}}, goals: ["contactInfo.scores.band"], output: {tenant: {balance: 99.99, companies: [{city: "a", vip: true, weight: 0.1}, {city: "-", vip: false, weight: 99999999999999999999}, {city: "Oslo", vip: true, weight: 99.99}, {city: "Oslo", vip: false, weight: 1}, {city: "", vip: false, weight: 0.000001}], contact: {rate: 5, scores: {band: "1000"}}, income: 1000, insured: false, plan: "trial", years: 0.000001}}}, + {input: {tenant: {income: 1000, insured: false, balance: -0, plan: "plus", years: -0.5, companies: [{weight: 100, vip: true, city: "none"}, {weight: 65, vip: true, city: "high"}, {weight: 1000, vip: null, city: "O'Neil"}, {weight: 0, vip: null, city: "日本"}, {weight: -0.01, vip: false, city: "none"}, {weight: 1000000, vip: false, city: " pad "}, {weight: 65, vip: true, city: "O'Neil"}, {weight: 250, vip: null, city: "O'Neil"}, {weight: 10, city: "abc"}, {weight: -0, vip: null, city: "é ü"}, {weight: 18, vip: null, city: "Oslo"}], contact: {rate: null}}}, goals: ["tenant.total"], output: {tenant: {balance: 0, companies: [{city: "none", vip: true, weight: 100}, {city: "high", vip: true, weight: 65}, {city: "O'Neil", vip: null, weight: 1000}, {city: "日本", vip: null, weight: 0}, {city: "none", vip: false, weight: -0.01}, {city: " pad ", vip: false, weight: 1000000}, {city: "O'Neil", vip: true, weight: 65}, {city: "O'Neil", vip: null, weight: 250}, {city: "abc", weight: 10}, {city: "é ü", vip: null, weight: 0}, {city: "Oslo", vip: null, weight: 18}], contact: {rate: null, scores: {band: "1000"}}, income: 1000, insured: false, plan: "plus", total: true, years: -0.5}}}, + {input: {tenant: {income: 2.50, insured: false, balance: 0.1, plan: "trial", years: 100, companies: [{weight: -1, vip: false, city: " pad "}], contact: {rate: 2.50}}}, goals: ["company.calc.segment"], output: {tenant: {balance: 0.1, companies: [{calc: {segment: false}, city: " pad ", vip: false, weight: -1}], contact: {rate: 2.50, scores: {band: "2.50"}}, income: 2.50, insured: false, plan: "trial", years: 100}}}, + {input: {tenant: {income: -0.5, insured: true, balance: -0, plan: "basic", years: -0.5, companies: [{weight: 99999999999999999999, vip: true, city: "NL"}, {weight: 5, vip: false, city: "a-b-c"}], contact: {rate: -1}}}, goals: ["contactInfo.scores.band", "tenant.total", "company.calc.segment"], output: {tenant: {balance: 0, companies: [{calc: {segment: false}, city: "NL", vip: true, weight: 99999999999999999999}, {calc: {segment: false}, city: "a-b-c", vip: false, weight: 5}], contact: {rate: -1, scores: {band: "-0.5"}}, income: -0.5, insured: true, plan: "basic", total: true, years: -0.5}}}, + [{tenant: {income: 0, insured: true, balance: 0.000001, plan: "trial", years: 2, companies: [{weight: 7.25, city: "Zed"}], contact: {rate: -0}}}, {tenant: {balance: 0.000001, companies: [{calc: {segment: false}, city: "Zed", exposure: 1, level: true, weight: 7.25}], contact: {rate: 0, scores: {band: "0"}}, income: 0, insured: true, plan: "trial", total: true, years: 2}}], + {input: {tenant: {income: 0.1, insured: false, balance: 250, plan: "trial", years: -0.5, companies: [], contact: {}}}, goals: ["company.calc.segment", "contactInfo.scores.band"], output: {tenant: {balance: 250, companies: [], contact: {scores: {band: "0.1"}}, income: 0.1, insured: false, plan: "trial", years: -0.5}}}, + {input: {tenant: {income: 18, insured: false, balance: 2, plan: "plus", years: 0.000001, companies: [{weight: 0, city: " pad "}], contact: {rate: null}}}, goals: ["tenant.total"], output: {tenant: {balance: 2, companies: [{city: " pad ", weight: 0}], contact: {rate: null, scores: {band: "18"}}, income: 18, insured: false, plan: "plus", total: true, years: 0.000001}}}, + {input: {tenant: {income: 65, insured: false, balance: 1000000, plan: "premium", years: 10, companies: [{weight: -500, vip: null, city: "a-b-c"}, {weight: 0.1, vip: true, city: "abc"}, {weight: -1, vip: true, city: "gold"}, {weight: -0.01, city: "US"}], contact: {rate: null}}}, goals: ["tenant.total", "company.level", "company.calc.segment"], output: {tenant: {balance: 1000000, companies: [{calc: {segment: false}, city: "a-b-c", level: false, vip: null, weight: -500}, {calc: {segment: false}, city: "abc", level: false, vip: true, weight: 0.1}, {calc: {segment: false}, city: "gold", level: false, vip: true, weight: -1}, {calc: {segment: false}, city: "US", level: false, weight: -0.01}], contact: {rate: null, scores: {band: "65"}}, income: 65, insured: false, plan: "premium", total: true, years: 10}}}, + {input: {tenant: {income: 18, insured: true, balance: 2.50, plan: "basic", years: 250, companies: [{weight: 2.50, vip: false, city: "Oslo"}, {weight: 250, vip: false, city: "é ü"}], contact: {rate: 0.000001}}}, goals: ["company.exposure"], output: {tenant: {balance: 2.50, companies: [{city: "Oslo", exposure: 0, vip: false, weight: 2.50}, {city: "é ü", exposure: 0, vip: false, weight: 250}], contact: {rate: 0.000001}, income: 18, insured: true, plan: "basic", years: 250}}}, + {input: {tenant: {income: 250, insured: false, balance: -0, plan: "trial", years: 1000000, companies: [], contact: {rate: 0.5}}}, goals: ["company.level", "tenant.total", "contactInfo.scores.band"], output: {tenant: {balance: 0, companies: [], contact: {rate: 0.5, scores: {band: "250"}}, income: 250, insured: false, plan: "trial", total: true, years: 1000000}}}, + [{tenant: {income: 99.99, insured: false, balance: 99999999999999999999, plan: "basic", years: 250, companies: [{weight: -0, vip: false, city: "none"}, {weight: 0.5, city: "Oslo"}], contact: {rate: 0.1}}}, {tenant: {balance: 99999999999999999999, companies: [{calc: {segment: false}, city: "none", exposure: 1, level: false, vip: false, weight: 0}, {calc: {segment: false}, city: "Oslo", exposure: 1, level: false, weight: 0.5}], contact: {rate: 0.1, scores: {band: "99.99"}}, income: 99.99, insured: false, plan: "basic", total: true, years: 250}}], + ], +} + +// seed 352800 (attempt 0) +{ + name: "goals 29: borrower/parcels: 1 assertion, 5 expression, 3 match, 1 table; 3 root, 11 per-member, 1 top-level computed", + policy: { + models: {borrower: {score: "number", priority: "boolean?", birthDate: "date", parcels: "parcel[]"}, parcel: {days: "number", city: "string", rate: "number", insured: "boolean"}}, + blocks: [ + {expression: "borrower.capped", value: "map(borrower.parcels, #.days)"}, + {match: "parcel.discount", arms: [["parcel.rate in (39..218)", "(split(borrower.birthDate.format('%Y-%m'), '-')[1] ?? 'none')"], ["(borrower.birthDate > d('2025-03-20') or borrower.priority == null)", "parcel.city"], ["all(borrower.parcels, #.days > #.rate)", "((borrower.priority ?? false) ? parcel.city : parcel.city)"], ["", "parcel.city"]]}, + {expression: "parcel.calc.exposure", value: "{ok: len(filter(borrower.parcels, not (#.insured))) == parcel.rate, a: ((borrower.priority ?? false) ? parcel.rate : 5)}"}, + {match: "margin", arms: [["borrower.priority == null", "`${'x'}/${borrower.score}`"], ["borrower.birthDate.isSame(d('2000-06-30'), 'month')", "string((borrower.priority ?? false))"], ["not ((borrower.priority ?? false))", "string(borrower.score)"], ["borrower.score < borrower.score", "'VIP'"], ["", "'gold'"]]}, + {expression: "parcel.flags.health", value: "(borrower.birthDate < d('2000-06-30') ? borrower.priority : null)"}, + {expression: "parcel.risk", value: "{a: parcel.calc.exposure.a, s: string(parcel.days) != 'a', ok: string(parcel.calc.exposure.ok)}"}, + {expression: "parcel.meta.penalty", value: "((borrower.birthDate.year() / 3) % (abs(len(borrower.capped)) + 1))"}, + {assertion: "borrower.segment", conditions: [["or", "not ((borrower.priority ?? false))", 0], ["or", "((borrower.priority ?? false) or (borrower.priority ?? false))", 1], ["and", "some(borrower.parcels, contains(['DE', 'ok', ''], #.city))", 0]]}, + {match: "parcel.review", arms: [["(min(borrower.capped) ?? 0) != parcel.days", "parcel.calc.exposure.a > parcel.rate"], ["isNumeric(string(parcel.calc.exposure.ok))", "borrower.birthDate < d('2024-01-01')"], ["contains(['VIP', 'low', ''], parcel.discount)", "(parcel.flags.health ?? false)"], ["", "borrower.segment"]]}, + {table: "t10", inputs: ["(borrower.score * 3)", "margin"], outputs: ["borrower.bonus"], rules: [ + ["", "startsWith($, 'VIP')", "borrower.birthDate.format('%Y-%m')"], + ["<= 1.5", "", ""], + ["", "", "margin"], + ["0.25", "'low'", "margin"], + ["5, 2", "startsWith($, 'DE')", "(split(margin, '-')[0] ?? 'none')"], + ["", "", "'DE'"], + ]}, + ], + }, + cases: [ + {input: {borrower: {score: 5, priority: false, birthDate: "1990-06-15", parcels: [{days: 216, city: "VIP", rate: 5, insured: true}, {days: 2, city: "NL", rate: 2, insured: false}, {days: -0, city: "a-b-c", rate: 3, insured: true}, {days: 100, city: "x-y", rate: 1.5, insured: true}], extraField: {nested: true}}}, goals: ["borrower.bonus", "borrower.segment"], output: {borrower: {birthDate: "1990-06-15", bonus: "5", extraField: {nested: true}, parcels: [{city: "VIP", days: 216, insured: true, rate: 5}, {city: "NL", days: 2, insured: false, rate: 2}, {city: "a-b-c", days: 0, insured: true, rate: 3}, {city: "x-y", days: 100, insured: true, rate: 1.5}], priority: false, score: 5, segment: true}, margin: "5"}}, + [{borrower: {score: 0.5, priority: false, birthDate: "2024-01-01", parcels: [{days: 3, city: "US", rate: 2, insured: false}, {days: -0.01, city: "Oslo", rate: 99999999999999999999, insured: true}, {days: 0.5, city: "gold", rate: 2, insured: true}], extraField: "x"}}, {borrower: {birthDate: "2024-01-01", bonus: "0.5", capped: [3, -0.01, 0.5], extraField: "x", parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "US", days: 3, discount: "US", insured: false, meta: {penalty: 2.66666666666666666666666667}, rate: 2, review: true, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "Oslo", days: -0.01, discount: "Oslo", insured: true, meta: {penalty: 2.66666666666666666666666667}, rate: 99999999999999999999, review: true, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "gold", days: 0.5, discount: "gold", insured: true, meta: {penalty: 2.66666666666666666666666667}, rate: 2, review: true, risk: {a: 5, ok: "false", s: true}}], priority: false, score: 0.5, segment: true}, margin: "0.5"}], + [{borrower: {score: 5, priority: true, birthDate: "1990-06-15", parcels: [{days: -500, city: "none", rate: 0, insured: true}, {days: 99999999999999999999, city: "NL", rate: 50, insured: false}]}}, {borrower: {birthDate: "1990-06-15", bonus: "gold", capped: [-500, 99999999999999999999], parcels: [{calc: {exposure: {a: 0, ok: false}}, city: "none", days: -500, discount: "none", insured: true, meta: {penalty: 0.33333333333333333333333333}, rate: 0, review: true, risk: {a: 0, ok: "false", s: true}}, {calc: {exposure: {a: 50, ok: false}}, city: "NL", days: 99999999999999999999, discount: "06", insured: false, meta: {penalty: 0.33333333333333333333333333}, rate: 50, review: false, risk: {a: 50, ok: "false", s: true}}], priority: true, score: 5, segment: true}, margin: "gold"}], + {input: {borrower: {score: 3, birthDate: "2024-02-29", parcels: [{days: 18, city: "ok", rate: 100, insured: false}, {days: 2.50, city: "DE", rate: 0.25, insured: false}, {days: 2, city: "x-y", rate: -0, insured: true}, {days: 250, city: "low", rate: 2, insured: false}, {days: 2, city: "", rate: 5, insured: false}]}}, goals: ["margin"], output: {borrower: {birthDate: "2024-02-29", parcels: [{city: "ok", days: 18, insured: false, rate: 100}, {city: "DE", days: 2.50, insured: false, rate: 0.25}, {city: "x-y", days: 2, insured: true, rate: 0}, {city: "low", days: 250, insured: false, rate: 2}, {city: "", days: 2, insured: false, rate: 5}], score: 3}, margin: "x/3"}}, + {input: {borrower: {score: 99999999999999999999, priority: false, birthDate: "2024-01-01", parcels: [{days: 1.5, city: "O'Neil", rate: 2, insured: true}, {days: -0.01, city: "-", rate: 2, insured: true}]}}, goals: ["parcel.calc.exposure"], output: {borrower: {birthDate: "2024-01-01", parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "O'Neil", days: 1.5, insured: true, rate: 2}, {calc: {exposure: {a: 5, ok: false}}, city: "-", days: -0.01, insured: true, rate: 2}], priority: false, score: 99999999999999999999}}}, + {input: {borrower: {score: 3, priority: false, birthDate: "2025-03-20", parcels: [{days: 1000000, city: "gold", rate: 95, insured: false}, {days: 65, city: "a", rate: 18, insured: false}, {days: -0.01, city: "A1", rate: 123456789.123, insured: false}]}}, goals: ["parcel.risk"], output: {borrower: {birthDate: "2025-03-20", parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "gold", days: 1000000, insured: false, rate: 95, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "a", days: 65, insured: false, rate: 18, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "A1", days: -0.01, insured: false, rate: 123456789.123, risk: {a: 5, ok: "false", s: true}}], priority: false, score: 3}}}, + {input: {borrower: {score: 0.1, priority: null, birthDate: "2024-01-01", parcels: []}}, goals: ["parcel.risk", "margin", "parcel.meta.penalty"], output: {borrower: {birthDate: "2024-01-01", capped: [], parcels: [], priority: null, score: 0.1}, margin: "x/0.1"}}, + [{borrower: {score: 3, priority: true, parcels: [{days: 100, city: "a", rate: 0.25, insured: true}, {days: 50, city: "x", rate: 10, insured: false}, {days: 10, city: "A1", rate: 10, insured: false}, {days: 5, city: "A1", rate: 7.25, insured: false}, {days: 2.50, city: "low", rate: 1000000, insured: true}]}}, "!error: MissingRequiredInputs"], + {input: {borrower: {score: 10, birthDate: "2000-01-01", parcels: [{days: 1.5, city: "3.5", rate: 0.5, insured: false}, {days: -0, city: "Zed", rate: 0.1, insured: false}, {days: 250, city: "Oslo", rate: 5, insured: true}, {days: 65, city: "retail", rate: 99999999999999999999, insured: true}, {days: 65, city: "日本", rate: -0, insured: false}]}}, goals: ["parcel.risk", "margin"], output: {borrower: {birthDate: "2000-01-01", parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "3.5", days: 1.5, insured: false, rate: 0.5, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "Zed", days: 0, insured: false, rate: 0.1, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "Oslo", days: 250, insured: true, rate: 5, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "retail", days: 65, insured: true, rate: 99999999999999999999, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "日本", days: 65, insured: false, rate: 0, risk: {a: 5, ok: "false", s: true}}], score: 10}, margin: "x/10"}}, + {input: {borrower: {score: 0.5, priority: false, birthDate: "2030-12-31", parcels: []}}, goals: ["borrower.segment", "parcel.review", "parcel.calc.exposure"], output: {borrower: {birthDate: "2030-12-31", capped: [], parcels: [], priority: false, score: 0.5, segment: true}}}, + {input: {borrower: {score: 1000000, priority: true, birthDate: "2025-03-20T10:15:30Z", parcels: []}}, goals: ["parcel.flags.health", "parcel.risk", "borrower.bonus"], output: {borrower: {birthDate: "2025-03-20T10:15:30Z", bonus: "gold", parcels: [], priority: true, score: 1000000}, margin: "gold"}}, + [{borrower: {score: 5, priority: true, birthDate: "2024-01-01", parcels: [{days: 5, city: "12", rate: 157, insured: true}, {days: 65, city: "A1", rate: 1.5, insured: true}, {days: -0.5, city: "3.5", rate: 1000, insured: true}, {days: 7.25, city: "x", rate: 5, insured: false}, {days: 5, city: "DE", rate: 1.5, insured: true}]}}, {borrower: {birthDate: "2024-01-01", bonus: "gold", capped: [5, 65, -0.5, 7.25, 5], parcels: [{calc: {exposure: {a: 157, ok: false}}, city: "12", days: 5, discount: "01", insured: true, meta: {penalty: 2.66666666666666666666666667}, rate: 157, review: false, risk: {a: 157, ok: "false", s: true}}, {calc: {exposure: {a: 1.5, ok: false}}, city: "A1", days: 65, discount: "A1", insured: true, meta: {penalty: 2.66666666666666666666666667}, rate: 1.5, review: false, risk: {a: 1.5, ok: "false", s: true}}, {calc: {exposure: {a: 1000, ok: false}}, city: "3.5", days: -0.5, discount: "3.5", insured: true, meta: {penalty: 2.66666666666666666666666667}, rate: 1000, review: true, risk: {a: 1000, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "x", days: 7.25, discount: "x", insured: false, meta: {penalty: 2.66666666666666666666666667}, rate: 5, review: false, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 1.5, ok: false}}, city: "DE", days: 5, discount: "DE", insured: true, meta: {penalty: 2.66666666666666666666666667}, rate: 1.5, review: false, risk: {a: 1.5, ok: "false", s: true}}], priority: true, score: 5, segment: true}, margin: "gold"}], + {input: {borrower: {score: 1e3, priority: false, birthDate: "1990-06-15", parcels: [{days: 10, city: "ok", rate: 7.25, insured: false}, {days: 23, city: "", rate: 99.99, insured: true}, {days: 1000000, city: "a", rate: 5, insured: true}, {days: 5, city: "none", rate: -0, insured: false}]}}, goals: ["parcel.calc.exposure", "borrower.capped"], output: {borrower: {birthDate: "1990-06-15", capped: [10, 23, 1000000, 5], parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "ok", days: 10, insured: false, rate: 7.25}, {calc: {exposure: {a: 5, ok: false}}, city: "", days: 23, insured: true, rate: 99.99}, {calc: {exposure: {a: 5, ok: false}}, city: "a", days: 1000000, insured: true, rate: 5}, {calc: {exposure: {a: 5, ok: false}}, city: "none", days: 5, insured: false, rate: 0}], priority: false, score: 1000}}}, + {input: {borrower: {score: 10, priority: false, birthDate: "2030-12-31", parcels: [{days: 50, city: "A1", rate: 84, insured: false}, {days: 1.5, city: "abc", rate: 2.50, insured: true}, {days: 2, city: "gold", rate: 10, insured: false}, {days: 250, city: "12", rate: 2, insured: false}]}}, goals: ["margin"], output: {borrower: {birthDate: "2030-12-31", parcels: [{city: "A1", days: 50, insured: false, rate: 84}, {city: "abc", days: 1.5, insured: true, rate: 2.50}, {city: "gold", days: 2, insured: false, rate: 10}, {city: "12", days: 250, insured: false, rate: 2}], priority: false, score: 10}, margin: "10"}}, + {input: {borrower: {score: 65, birthDate: "2030-12-31", parcels: []}}, goals: ["parcel.meta.penalty"], output: {borrower: {birthDate: "2030-12-31", capped: [], parcels: [], score: 65}}}, + {input: {borrower: {score: 2, priority: false, birthDate: "2030-12-31", parcels: [{days: 123456789.123, city: "DE", rate: 2, insured: true}, {days: 123456789.123, city: "DE", rate: 5, insured: false}], extraField: "x"}}, goals: ["parcel.meta.penalty", "parcel.review", "borrower.capped"], output: {borrower: {birthDate: "2030-12-31", capped: [123456789.123, 123456789.123], extraField: "x", parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "DE", days: 123456789.123, discount: "DE", insured: true, meta: {penalty: 1.66666666666666666666666667}, rate: 2, review: true}, {calc: {exposure: {a: 5, ok: false}}, city: "DE", days: 123456789.123, discount: "DE", insured: false, meta: {penalty: 1.66666666666666666666666667}, rate: 5, review: true}], priority: false, score: 2, segment: true}}}, + {input: {borrower: {score: 1000000, priority: true, birthDate: "2024-01-01", parcels: [{days: 0.000001, city: "VIP", rate: 250, insured: true}, {days: -0.01, city: "abc", rate: 18, insured: false}, {days: -0, city: "a", rate: 99.99, insured: true}, {days: -0.01, city: "é ü", rate: 3, insured: false}]}}, goals: ["parcel.flags.health"], output: {borrower: {birthDate: "2024-01-01", parcels: [{city: "VIP", days: 0.000001, flags: {health: null}, insured: true, rate: 250}, {city: "abc", days: -0.01, flags: {health: null}, insured: false, rate: 18}, {city: "a", days: 0, flags: {health: null}, insured: true, rate: 99.99}, {city: "é ü", days: -0.01, flags: {health: null}, insured: false, rate: 3}], priority: true, score: 1000000}}}, + [{borrower: {score: 1.5, priority: false, birthDate: "2025-03-20", parcels: [{days: 10, city: null, rate: 0.25, insured: true}, {days: 1000, city: "low", rate: 250, insured: false}, {days: 7.25, city: "A1", rate: 5, insured: false}]}}, {borrower: {birthDate: "2025-03-20", bonus: "1.5", capped: [10, 1000, 7.25], parcels: [{calc: {exposure: {a: 5, ok: false}}, city: null, days: 10, discount: null, insured: true, meta: {penalty: 3}, rate: 0.25, review: true, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "low", days: 1000, discount: "low", insured: false, meta: {penalty: 3}, rate: 250, review: false, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "A1", days: 7.25, discount: "A1", insured: false, meta: {penalty: 3}, rate: 5, review: true, risk: {a: 5, ok: "false", s: true}}], priority: false, score: 1.5, segment: true}, margin: "1.5"}], + {input: {borrower: {score: 1.5, priority: false, birthDate: "2025-03-20T10:15:30Z", parcels: [{days: 2, city: "VIP", rate: -0, insured: true}]}}, goals: ["parcel.discount", "parcel.calc.exposure", "borrower.capped"], output: {borrower: {birthDate: "2025-03-20T10:15:30Z", capped: [2], parcels: [{calc: {exposure: {a: 5, ok: true}}, city: "VIP", days: 2, discount: "VIP", insured: true, rate: 0}], priority: false, score: 1.5}}}, + {input: {borrower: {score: 0.5, priority: false, birthDate: "2000-01-01", parcels: [{days: -0, city: "VIP", rate: -1, insured: true}, {days: 0.25, city: "DE", rate: 5, insured: true}]}}, goals: ["borrower.segment", "parcel.review", "parcel.discount"], output: {borrower: {birthDate: "2000-01-01", capped: [0, 0.25], parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "VIP", days: 0, discount: "VIP", flags: {health: false}, insured: true, rate: -1, review: false}, {calc: {exposure: {a: 5, ok: false}}, city: "DE", days: 0.25, discount: "DE", flags: {health: false}, insured: true, rate: 5, review: false}], priority: false, score: 0.5, segment: true}}}, + {input: {borrower: {score: 1e3, priority: true, birthDate: "1990-06-15", parcels: [{days: 1, city: "VIP", rate: 5, insured: true}, {days: 5, city: "ok", rate: -1, insured: false}, {days: 250, city: "Zed", rate: 1.5, insured: false}], extraField: 1}}, goals: ["parcel.meta.penalty"], output: {borrower: {birthDate: "1990-06-15", capped: [1, 5, 250], extraField: 1, parcels: [{city: "VIP", days: 1, insured: true, meta: {penalty: 3.33333333333333333333333333}, rate: 5}, {city: "ok", days: 5, insured: false, meta: {penalty: 3.33333333333333333333333333}, rate: -1}, {city: "Zed", days: 250, insured: false, meta: {penalty: 3.33333333333333333333333333}, rate: 1.5}], priority: true, score: 1000}}}, + {input: {borrower: {score: 0.1, priority: true, birthDate: "2025-03-20", parcels: [{days: 0.25, city: "A1", rate: 0.5, insured: false}, {days: 0.25, city: "x", rate: -500, insured: false}], extraField: {nested: true}}}, goals: ["borrower.bonus"], output: {borrower: {birthDate: "2025-03-20", bonus: "gold", extraField: {nested: true}, parcels: [{city: "A1", days: 0.25, insured: false, rate: 0.5}, {city: "x", days: 0.25, insured: false, rate: -500}], priority: true, score: 0.1}, margin: "gold"}}, + {input: {borrower: {score: 0, priority: false, birthDate: "2025-03-20", parcels: [{days: 0.1, city: "A1", rate: 99999999999999999999, insured: false}, {days: 0.25, city: "VIP", rate: 7.25, insured: false}, {days: 99999999999999999999, city: "NL", rate: -0.01, insured: true}, {days: -0.5, city: "abc", rate: -0.01, insured: false}, {days: 10, city: "A1", rate: -0, insured: false}]}}, goals: ["borrower.segment", "parcel.review"], output: {borrower: {birthDate: "2025-03-20", capped: [0.1, 0.25, 99999999999999999999, -0.5, 10], parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "A1", days: 0.1, discount: "A1", insured: false, rate: 99999999999999999999, review: false}, {calc: {exposure: {a: 5, ok: false}}, city: "VIP", days: 0.25, discount: "VIP", insured: false, rate: 7.25, review: false}, {calc: {exposure: {a: 5, ok: false}}, city: "NL", days: 99999999999999999999, discount: "NL", insured: true, rate: -0.01, review: true}, {calc: {exposure: {a: 5, ok: false}}, city: "abc", days: -0.5, discount: "abc", insured: false, rate: -0.01, review: true}, {calc: {exposure: {a: 5, ok: false}}, city: "A1", days: 10, discount: "A1", insured: false, rate: 0, review: true}], priority: false, score: 0, segment: true}}}, + {input: {borrower: {score: 1.5, priority: null, birthDate: "1990-06-15", parcels: [{days: 18, city: "DE", rate: 1000, insured: true}, {days: 219, city: "low", rate: 1e3, insured: false}]}}, goals: ["parcel.calc.exposure", "parcel.discount"], output: {borrower: {birthDate: "1990-06-15", parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "DE", days: 18, discount: "DE", insured: true, rate: 1000}, {calc: {exposure: {a: 5, ok: false}}, city: "low", days: 219, discount: "low", insured: false, rate: 1000}], priority: null, score: 1.5}}}, + {input: {borrower: {score: 250, priority: null, birthDate: "2025-03-20", parcels: [{days: 0, city: "none", rate: -1, insured: false}]}}, goals: ["borrower.bonus", "parcel.flags.health", "borrower.capped"], output: {borrower: {birthDate: "2025-03-20", bonus: "x/250", capped: [0], parcels: [{city: "none", days: 0, flags: {health: null}, insured: false, rate: -1}], priority: null, score: 250}, margin: "x/250"}}, + [{borrower: {score: 206, priority: false, birthDate: "2024-02-29", parcels: [{days: 10, city: "gold", rate: 1, insured: true}, {days: 250, city: "DE", rate: 10, insured: false}, {days: 0.000001, city: "Oslo", rate: 0, insured: false}]}}, {borrower: {birthDate: "2024-02-29", bonus: "206", capped: [10, 250, 0.000001], parcels: [{calc: {exposure: {a: 5, ok: false}}, city: "gold", days: 10, discount: "gold", insured: true, meta: {penalty: 2.66666666666666666666666667}, rate: 1, review: true, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "DE", days: 250, discount: "DE", insured: false, meta: {penalty: 2.66666666666666666666666667}, rate: 10, review: false, risk: {a: 5, ok: "false", s: true}}, {calc: {exposure: {a: 5, ok: false}}, city: "Oslo", days: 0.000001, discount: "Oslo", insured: false, meta: {penalty: 2.66666666666666666666666667}, rate: 0, review: true, risk: {a: 5, ok: "false", s: true}}], priority: false, score: 206, segment: true}, margin: "206"}], + {input: {borrower: {score: 2, priority: false, birthDate: "2025-03-20", parcels: [{days: 2, city: "DE", rate: 7.25, insured: null}, {days: 65, city: "A1", rate: 5, insured: false}, {days: 5, city: "DE", rate: 2, insured: true}, {days: 1, city: "high", rate: 0.000001, insured: true}]}}, goals: ["borrower.bonus", "parcel.calc.exposure", "parcel.flags.health"], output: "!error: ExpressionFailed"}, + [{borrower: {score: 100, priority: true, birthDate: "2024-02-29", parcels: [{days: 99.99, city: "é ü", rate: 99999999999999999999, insured: false}]}}, {borrower: {birthDate: "2024-02-29", bonus: "gold", capped: [99.99], parcels: [{calc: {exposure: {a: 99999999999999999999, ok: false}}, city: "é ü", days: 99.99, discount: "é ü", insured: false, meta: {penalty: 0.66666666666666666666666667}, rate: 99999999999999999999, review: true, risk: {a: 99999999999999999999, ok: "false", s: true}}], priority: true, score: 100, segment: true}, margin: "gold"}], + ], +} + +// seed 352900 (attempt 0) +{ + name: "goals 30: tenant/parcels: 2 assertion, 4 expression, 2 match, 3 table; 6 root, 10 per-member, 1 top-level computed", + policy: { + models: {tenant: {price: "number?", openedAt: "date", urgent: "boolean", vip: "boolean", city: "string", parcels: "parcel[]"}, parcel: {years: "number?", channel: "string"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {match: "tenant.scores.net", arms: [["(tenant.vip or tenant.urgent)", "factor"], ["(tenant.vip or tenant.vip)", "18"], ["", "factor"]]}, + {table: "t2", inputs: ["tenant.vip", "tenant.vip"], outputs: ["parcel.totals.surcharge", "parcel.totals.band", "parcel.bonus[]"], rules: [ + ["false", "true", "(tenant.price ?? 0)", "tenant.urgent", "factor"], + ["true", "false", "1.5", "", "(parcel.years ?? 0)"], + ["", "true", "(parcel.years ?? 0)", "tenant.vip", "trunc(tenant.scores.net)"], + ["", "", "tenant.scores.net", "tenant.urgent", "min([factor, (parcel.years ?? 0), (parcel.years ?? 0)])"], + ]}, + {match: "tenant.quota", arms: [["not (tenant.urgent)", "`${factor}/${tenant.vip}`"], ["(tenant.price ?? 0) in [8..67)", "tenant.city"], ["not (tenant.urgent)", "tenant.city"], ["", "tenant.city"]]}, + {assertion: "tenant.grade", conditions: [["or", "(tenant.urgent or tenant.urgent)", 1], ["or", "all(tenant.parcels, not ((#.totals.band ?? false)))", 0], ["or", "(tenant.price ?? 0) in [7..127]", 1]]}, + {table: "t5", inputs: ["tenant.openedAt"], outputs: ["parcel.level", "parcel.meta.eligible", "parcel.meta.discount"], rules: [ + ["> d('2025-03-20')", "tenant.grade", "len(tenant.parcels)", "(parcel.totals.surcharge ?? 0)"], + [">= d('2025-01-01')", "", "(parcel.totals.surcharge ?? 0)", "(tenant.price ?? 0)"], + ["", "", "factor", "factor"], + ]}, + {assertion: "penalty", conditions: [["and", "factor in [13..123]", 1]]}, + {expression: "parcel.meta.decision", value: "string((tenant.urgent ? (parcel.years ?? 0) : (tenant.price ?? 0)))"}, + {expression: "parcel.total", value: "parcel.years"}, + {expression: "parcel.margin", value: "map(tenant.parcels, abs((min(#.bonus) ?? 0)))"}, + {expression: "parcel.flag", value: "(some(tenant.parcels, matches(#.channel, 'a')) or some(tenant.parcels, matches(#.channel, 'a')))"}, + {table: "t11", inputs: ["tenant.scores.net", "trunc(factor)"], outputs: ["tenant.points", "tenant.bucket", "tenant.exposure"], rules: [ + ["", "10, 50", "(max(map(tenant.parcels, (#.meta.discount ?? 0))) ?? 0)", "some(tenant.parcels, ((#.totals.band ?? false) or #.flag))", "string(tenant.grade)"], + ["", "!= 50", "1000", "penalty", "tenant.quota"], + ["[1.5..51.5]", "18, 10", "((tenant.price ?? 0) * factor)", "", "`${tenant.quota}/${tenant.urgent}`"], + [">= 1", "<= 1", "(tenant.price ?? 0)", "tenant.city in ['a', 'a']", "'retail'"], + ["", "", "", "", "tenant.quota"], + ]}, + ], + }, + cases: [ + {input: {factor: 10, tenant: {price: 0.25, openedAt: "2030-12-31", urgent: false, vip: true, city: "12", parcels: []}}, goals: ["parcel.level", "tenant.points", "parcel.meta.eligible"], output: "!error: ExpressionFailed"}, + {input: {factor: 0, tenant: {price: 0, openedAt: "2025-03-20", urgent: false, vip: false, city: "a", parcels: []}}, goals: ["tenant.scores.net", "tenant.quota", "parcel.meta.eligible"], output: {factor: 0, tenant: {city: "a", openedAt: "2025-03-20", parcels: [], price: 0, quota: "0/false", scores: {net: 0}, urgent: false, vip: false}}}, + {input: {factor: -2, tenant: {price: -1, openedAt: "2024-01-01", urgent: false, vip: false, city: "a-b-c", parcels: [{years: 1.5, channel: "x-y"}, {years: 0, channel: "A1"}]}}, goals: ["tenant.scores.net", "tenant.grade"], output: {factor: -2, tenant: {city: "a-b-c", grade: true, openedAt: "2024-01-01", parcels: [{bonus: [-2], channel: "x-y", totals: {band: false, surcharge: -2}, years: 1.5}, {bonus: [-2], channel: "A1", totals: {band: false, surcharge: -2}, years: 0}], price: -1, scores: {net: -2}, urgent: false, vip: false}}}, + {input: {factor: 10, tenant: {price: 65, openedAt: "2000-01-01", urgent: true, vip: false, city: "retail", parcels: []}}, goals: ["tenant.exposure"], output: "!error: ExpressionFailed"}, + {input: {factor: -2, tenant: {price: 10, openedAt: "2030-12-31", urgent: true, vip: true, city: "O'Neil", parcels: []}}, goals: ["parcel.totals.band", "tenant.points", "parcel.margin"], output: {factor: -2, penalty: false, tenant: {bucket: false, city: "O'Neil", exposure: "O'Neil", openedAt: "2030-12-31", parcels: [], points: 1000, price: 10, quota: "O'Neil", scores: {net: -2}, urgent: true, vip: true}}}, + {input: {factor: -2, tenant: {price: 50, openedAt: "2000-01-01", urgent: false, vip: false, city: "a", parcels: [{years: -1, channel: "12"}, {years: 100, channel: "Oslo"}]}}, goals: ["parcel.totals.surcharge"], output: {factor: -2, tenant: {city: "a", openedAt: "2000-01-01", parcels: [{bonus: [-2], channel: "12", totals: {band: false, surcharge: -2}, years: -1}, {bonus: [-2], channel: "Oslo", totals: {band: false, surcharge: -2}, years: 100}], price: 50, scores: {net: -2}, urgent: false, vip: false}}}, + {input: {factor: -2, tenant: {price: 1000000, openedAt: "1990-06-15", urgent: false, vip: true, city: "VIP", parcels: [{years: null, channel: "O'Neil"}, {years: 0, channel: "retail"}]}}, goals: ["parcel.totals.band", "parcel.flag", "parcel.margin"], output: {factor: -2, tenant: {city: "VIP", openedAt: "1990-06-15", parcels: [{bonus: [-2, -2], channel: "O'Neil", flag: true, margin: [2, 2], totals: {band: true, surcharge: 0}, years: null}, {bonus: [-2, -2], channel: "retail", flag: true, margin: [2, 2], totals: {band: true, surcharge: 0}, years: 0}], price: 1000000, scores: {net: -2}, urgent: false, vip: true}}}, + {input: {factor: 1, tenant: {openedAt: "2024-02-29", urgent: false, vip: false, city: "VIP", parcels: [{channel: "a"}]}}, goals: ["parcel.meta.decision", "tenant.points", "parcel.bonus"], output: {factor: 1, penalty: false, tenant: {bucket: false, city: "VIP", exposure: "1/false", openedAt: "2024-02-29", parcels: [{bonus: [0], channel: "a", meta: {decision: "0"}, totals: {band: false, surcharge: 1}}], points: 1000, quota: "1/false", scores: {net: 1}, urgent: false, vip: false}}}, + [{factor: 0.5, tenant: {price: 18, openedAt: "1990-06-15", urgent: true, vip: false, city: "NL", parcels: [{years: 1, channel: "a"}, {years: 1.5, channel: "Oslo"}]}}, {factor: 0.5, penalty: false, tenant: {bucket: false, city: "NL", exposure: "NL", openedAt: "1990-06-15", parcels: [{bonus: [0.5], channel: "a", level: null, margin: [0.5, 0.5], meta: {decision: "1", discount: 0.5, eligible: 0.5}, total: 1, totals: {band: true, surcharge: 0.5}, years: 1}, {bonus: [0.5], channel: "Oslo", level: null, margin: [0.5, 0.5], meta: {decision: "1.5", discount: 0.5, eligible: 0.5}, total: 1.5, totals: {band: true, surcharge: 0.5}, years: 1.5}], points: 1000, price: 18, quota: "NL", scores: {net: 0.5}, urgent: true, vip: false}}], + [{factor: 10, tenant: {price: 250, openedAt: "2025-03-20", urgent: true, vip: true, city: "Oslo", parcels: [{years: null, channel: "x-y"}, {channel: "retail"}, {years: -1, channel: "US"}]}}, {factor: 10, tenant: {bucket: true, city: "Oslo", exposure: "true", grade: true, openedAt: "2025-03-20", parcels: [{bonus: [10, 0], channel: "x-y", flag: true, level: null, margin: [0, 0, 1], meta: {decision: "0", discount: 250, eligible: 0}, total: null, totals: {band: true, surcharge: 0}, years: null}, {bonus: [10, 0], channel: "retail", flag: true, level: null, margin: [0, 0, 1], meta: {decision: "0", discount: 250, eligible: 0}, total: null, totals: {band: true, surcharge: 0}}, {bonus: [10, -1], channel: "US", flag: true, level: null, margin: [0, 0, 1], meta: {decision: "-1", discount: 250, eligible: -1}, total: -1, totals: {band: true, surcharge: -1}, years: -1}], points: 250, price: 250, scores: {net: 10}, urgent: true, vip: true}}], + {input: {factor: -2, tenant: {price: 250, openedAt: "2024-01-01", urgent: false, vip: false, city: "é ü", parcels: [{channel: "NL"}]}}, goals: ["parcel.totals.surcharge", "tenant.bucket"], output: {factor: -2, penalty: false, tenant: {bucket: false, city: "é ü", exposure: "-2/false", openedAt: "2024-01-01", parcels: [{bonus: [-2], channel: "NL", totals: {band: false, surcharge: -2}}], points: 1000, price: 250, quota: "-2/false", scores: {net: -2}, urgent: false, vip: false}}}, + {input: {factor: -2, tenant: {price: 50, openedAt: "2000-01-01", urgent: true, vip: true, city: "-", parcels: [{years: 99999999999999999999, channel: "é ü"}]}}, goals: ["tenant.exposure", "parcel.flag"], output: {factor: -2, penalty: false, tenant: {bucket: false, city: "-", exposure: "-", openedAt: "2000-01-01", parcels: [{channel: "é ü", flag: false, years: 99999999999999999999}], points: 1000, price: 50, quota: "-", scores: {net: -2}, urgent: true, vip: true}}}, + {input: {factor: 10, tenant: {price: 7.25, openedAt: "2025-03-20", urgent: true, vip: true, city: "Oslo", parcels: [{years: 1000, channel: "Oslo"}, {channel: "a-b-c"}]}}, goals: ["parcel.total", "parcel.meta.decision", "parcel.margin"], output: {factor: 10, tenant: {city: "Oslo", openedAt: "2025-03-20", parcels: [{bonus: [10, 10], channel: "Oslo", margin: [10, 0], meta: {decision: "1000"}, total: 1000, totals: {band: true, surcharge: 1000}, years: 1000}, {bonus: [10, 0], channel: "a-b-c", margin: [10, 0], meta: {decision: "0"}, total: null, totals: {band: true, surcharge: 0}}], price: 7.25, scores: {net: 10}, urgent: true, vip: true}}}, + [{factor: 100, tenant: {price: null, openedAt: "2030-12-31", urgent: true, vip: false, city: "a", parcels: [{channel: "gold"}, {years: 1000, channel: "a"}]}}, {factor: 100, penalty: true, tenant: {bucket: true, city: "a", exposure: "a", grade: true, openedAt: "2030-12-31", parcels: [{bonus: [0], channel: "gold", level: true, margin: [0, 100], meta: {decision: "0", discount: 100, eligible: 2}, total: null, totals: {band: true, surcharge: 100}}, {bonus: [100], channel: "a", level: true, margin: [0, 100], meta: {decision: "1000", discount: 100, eligible: 2}, total: 1000, totals: {band: true, surcharge: 100}, years: 1000}], points: 1000, price: null, quota: "a", scores: {net: 100}, urgent: true, vip: false}}], + {input: {factor: -2, tenant: {price: 50, openedAt: "2024-02-29", urgent: false, vip: false, city: "O'Neil", parcels: [{years: -0, channel: "é ü"}, {years: 1.5, channel: ""}]}}, goals: ["parcel.bonus", "tenant.exposure"], output: {factor: -2, penalty: false, tenant: {bucket: false, city: "O'Neil", exposure: "-2/false", openedAt: "2024-02-29", parcels: [{bonus: [-2], channel: "é ü", totals: {band: false, surcharge: -2}, years: 0}, {bonus: [-2], channel: "", totals: {band: false, surcharge: -2}, years: 1.5}], points: 1000, price: 50, quota: "-2/false", scores: {net: -2}, urgent: false, vip: false}}}, + {input: {factor: 0.5, tenant: {price: 99999999999999999999, openedAt: "2030-12-31", urgent: false, vip: true, city: "a", parcels: [{years: 0.1, channel: "é ü"}, {years: 2, channel: "A1"}, {years: -0, channel: "retail"}, {years: 99.99, channel: "A1"}, {years: 2.50, channel: "NL"}, {years: 0.000001, channel: "US"}, {years: 250, channel: "retail"}, {years: 5, channel: " pad "}, {years: 50, channel: ""}, {years: 10, channel: "a"}, {years: 99.99, channel: "retail"}, {years: 100, channel: "Oslo"}]}}, goals: ["parcel.meta.decision", "parcel.totals.surcharge", "tenant.grade"], output: {factor: 0.5, tenant: {city: "a", grade: false, openedAt: "2030-12-31", parcels: [{bonus: [0, 0.1], channel: "é ü", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 0.1}, years: 0.1}, {bonus: [0, 0.5], channel: "A1", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 2}, years: 2}, {bonus: [0, 0], channel: "retail", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 0}, years: 0}, {bonus: [0, 0.5], channel: "A1", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 99.99}, years: 99.99}, {bonus: [0, 0.5], channel: "NL", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 2.50}, years: 2.50}, {bonus: [0, 0.000001], channel: "US", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 0.000001}, years: 0.000001}, {bonus: [0, 0.5], channel: "retail", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 250}, years: 250}, {bonus: [0, 0.5], channel: " pad ", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 5}, years: 5}, {bonus: [0, 0.5], channel: "", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 50}, years: 50}, {bonus: [0, 0.5], channel: "a", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 10}, years: 10}, {bonus: [0, 0.5], channel: "retail", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 99.99}, years: 99.99}, {bonus: [0, 0.5], channel: "Oslo", meta: {decision: "99999999999999999999"}, totals: {band: true, surcharge: 100}, years: 100}], price: 99999999999999999999, scores: {net: 0.5}, urgent: false, vip: true}}}, + {input: {factor: 10, tenant: {price: 1000, openedAt: "2030-12-31", urgent: true, vip: true, city: "3.5", parcels: [{years: 50, channel: "a"}, {years: 5, channel: "A1"}, {years: 324, channel: "é ü"}]}}, goals: ["tenant.scores.net", "tenant.bucket", "parcel.total"], output: {factor: 10, tenant: {bucket: true, city: "3.5", exposure: "true", grade: true, openedAt: "2030-12-31", parcels: [{bonus: [10, 10], channel: "a", flag: true, level: true, meta: {discount: 50, eligible: 3}, total: 50, totals: {band: true, surcharge: 50}, years: 50}, {bonus: [10, 5], channel: "A1", flag: true, level: true, meta: {discount: 5, eligible: 3}, total: 5, totals: {band: true, surcharge: 5}, years: 5}, {bonus: [10, 10], channel: "é ü", flag: true, level: true, meta: {discount: 324, eligible: 3}, total: 324, totals: {band: true, surcharge: 324}, years: 324}], points: 324, price: 1000, scores: {net: 10}, urgent: true, vip: true}}}, + {input: {factor: -2, tenant: {price: 10, openedAt: "2024-02-29", urgent: true, vip: true, parcels: [{years: 100, channel: "A1"}, {years: 0.1, channel: "a"}, {years: 403, channel: "abc"}, {years: 250, channel: "a-b-c"}, {years: 2.50, channel: "a"}]}}, goals: ["parcel.meta.discount", "tenant.grade", "parcel.meta.eligible"], output: {factor: -2, tenant: {grade: true, openedAt: "2024-02-29", parcels: [{bonus: [-2, -2], channel: "A1", level: null, meta: {discount: -2, eligible: -2}, totals: {band: true, surcharge: 100}, years: 100}, {bonus: [-2, -2], channel: "a", level: null, meta: {discount: -2, eligible: -2}, totals: {band: true, surcharge: 0.1}, years: 0.1}, {bonus: [-2, -2], channel: "abc", level: null, meta: {discount: -2, eligible: -2}, totals: {band: true, surcharge: 403}, years: 403}, {bonus: [-2, -2], channel: "a-b-c", level: null, meta: {discount: -2, eligible: -2}, totals: {band: true, surcharge: 250}, years: 250}, {bonus: [-2, -2], channel: "a", level: null, meta: {discount: -2, eligible: -2}, totals: {band: true, surcharge: 2.50}, years: 2.50}], price: 10, scores: {net: -2}, urgent: true, vip: true}}}, + {input: {factor: 0, tenant: {price: 10, openedAt: "2030-12-31", urgent: true, vip: true, city: "a", parcels: []}}, goals: ["parcel.total"], output: {factor: 0, tenant: {city: "a", openedAt: "2030-12-31", parcels: [], price: 10, urgent: true, vip: true}}}, + {input: {factor: -2, tenant: {price: null, openedAt: "2024-01-01", urgent: false, vip: true, city: "gold", parcels: [{years: 0.5, channel: "3.5"}, {years: 18, channel: "DE"}, {years: 5, channel: "3.5"}]}}, goals: ["tenant.bucket"], output: {factor: -2, penalty: false, tenant: {bucket: false, city: "gold", exposure: "-2/true", openedAt: "2024-01-01", parcels: [{channel: "3.5", years: 0.5}, {channel: "DE", years: 18}, {channel: "3.5", years: 5}], points: 1000, price: null, quota: "-2/true", scores: {net: -2}, urgent: false, vip: true}}}, + ], +} + +// seed 353000 (attempt 0) +{ + name: "goals 31: shipment/companies: 5 expression, 1 match, 2 table; 8 root, 3 per-member, 0 top-level computed", + policy: { + models: {shipment: {limit: "number", insured: "boolean", rate: "number", price: "number", companies: "company[]"}, company: {amount: "number", tier: "string(gold|silver|bronze)", openedAt: "date"}}, + blocks: [ + {expression: "company.flags.review", value: "company.openedAt"}, + {expression: "company.flags.summary", value: "shipment.rate"}, + {expression: "shipment.scores.penalty", value: "{s: (shipment.rate - shipment.rate)}"}, + {table: "t4", hit: "collect", inputs: ["shipment.insured"], outputs: ["shipment.adjusted", "shipment.decision", "shipment.share"], rules: [ + ["false", "shipment.limit", "shipment.scores.penalty.s", ""], + ["false", "shipment.rate", "", "'DE'"], + ["true", "0.5", "shipment.scores.penalty.s", "string(shipment.insured)"], + ["true", "len(filter(shipment.companies, (#.flags.summary <= 10 and #.amount == 3)))", "shipment.limit", ""], + ["", "shipment.scores.penalty.s", "shipment.rate", "'Oslo'"], + ]}, + {expression: "company.segment", value: "map(shipment.companies, (#.openedAt > d('2025-01-01') ? -(#.amount) : (#.amount > 1 ? #.flags.summary : #.flags.summary)))"}, + {match: "shipment.surcharge", arms: [["all(shipment.companies, #.flags.summary == 10)", "18"], ["shipment.rate in (35..126)", "shipment.limit"], ["matches(string(shipment.insured), 'a')", "1.5"], ["startsWith((shipment.insured ? 'DE' : 'gold'), 'DE')", "(len(filter(shipment.companies, #.tier in ['silver', 'bronze']))) / (abs(sum(shipment.decision)) + 1)"], ["", "shipment.price"]]}, + {expression: "shipment.capped", value: "filter(shipment.companies, #.flags.review.isSameOrBefore(d('2000-06-30'), 'month'))"}, + {table: "t8", inputs: ["(max(shipment.adjusted) ?? 0)", "shipment.rate"], outputs: ["shipment.tag"], rules: [ + ["", "<= 0", "shipment.rate"], + [">= 5", "!= 1", "len(shipment.adjusted)"], + ["> 5", "> 5", "shipment.price"], + ["", "", "shipment.scores.penalty.s"], + [">= 1000", "[50..496]", "shipment.price"], + ["1, 3", "<= 5", "shipment.rate"], + ]}, + ], + }, + cases: [ + [{shipment: {limit: 99.99, insured: false, rate: 123456789.123, price: 5, companies: [{amount: 1, tier: "gold", openedAt: "1990-06-15"}]}}, {shipment: {adjusted: [99.99, 123456789.123, 0.000], capped: [{amount: 1, flags: {review: "1990-06-15", summary: 123456789.123}, openedAt: "1990-06-15", segment: [123456789.123], tier: "gold"}], companies: [{amount: 1, flags: {review: "1990-06-15", summary: 123456789.123}, openedAt: "1990-06-15", segment: [123456789.123], tier: "gold"}], decision: [0.000, 123456789.123], insured: false, limit: 99.99, price: 5, rate: 123456789.123, scores: {penalty: {s: 0.000}}, share: ["DE", "Oslo"], surcharge: 1.5, tag: 3}}], + {input: {shipment: {limit: -1, insured: false, rate: 18, price: 1000, companies: [{amount: 0, tier: "gold", openedAt: "2024-02-29"}], extraField: {nested: true}}}, goals: ["shipment.scores.penalty", "shipment.share", "shipment.decision"], output: {shipment: {adjusted: [-1, 18, 0], companies: [{amount: 0, openedAt: "2024-02-29", tier: "gold"}], decision: [0, 18], extraField: {nested: true}, insured: false, limit: -1, price: 1000, rate: 18, scores: {penalty: {s: 0}}, share: ["DE", "Oslo"]}}}, + {input: {shipment: {limit: 1e3, insured: false, rate: 3, price: 99.99, companies: [{amount: 65, tier: "bronze", openedAt: "2030-12-31"}, {amount: -1, tier: "bronze", openedAt: "2024-02-29"}]}}, goals: ["shipment.scores.penalty"], output: {shipment: {companies: [{amount: 65, openedAt: "2030-12-31", tier: "bronze"}, {amount: -1, openedAt: "2024-02-29", tier: "bronze"}], insured: false, limit: 1000, price: 99.99, rate: 3, scores: {penalty: {s: 0}}}}}, + {input: {shipment: {limit: 123456789.123, insured: false, rate: 0, price: 1000, companies: [{amount: 1e3, tier: "bronze", openedAt: "2000-01-01"}, {amount: 1, tier: "gold", openedAt: "2030-12-31"}, {amount: 3, tier: "silver", openedAt: "2024-02-29"}, {amount: 250, tier: "silver", openedAt: "2030-12-31"}, {amount: 1, tier: "bronze", openedAt: "2025-03-20"}, {amount: 0, tier: "gold", openedAt: "2025-03-20"}, {amount: 0, tier: "silver", openedAt: "1990-06-15"}, {amount: 0.5, tier: "silver", openedAt: "2025-03-20T10:15:30Z"}, {amount: 184, tier: "silver", openedAt: "2024-02-29"}, {amount: 10, tier: "silver", openedAt: "2030-12-31"}, {amount: 1, tier: "silver", openedAt: "2024-01-01"}, {amount: 1e3, tier: "gold", openedAt: "2024-01-01"}, {amount: 250, tier: "gold", openedAt: "1990-06-15"}]}}, goals: ["shipment.capped", "shipment.decision"], output: {shipment: {adjusted: [123456789.123, 0, 0], capped: [{amount: 1000, flags: {review: "2000-01-01"}, openedAt: "2000-01-01", tier: "bronze"}, {amount: 0, flags: {review: "1990-06-15"}, openedAt: "1990-06-15", tier: "silver"}, {amount: 250, flags: {review: "1990-06-15"}, openedAt: "1990-06-15", tier: "gold"}], companies: [{amount: 1000, flags: {review: "2000-01-01"}, openedAt: "2000-01-01", tier: "bronze"}, {amount: 1, flags: {review: "2030-12-31"}, openedAt: "2030-12-31", tier: "gold"}, {amount: 3, flags: {review: "2024-02-29"}, openedAt: "2024-02-29", tier: "silver"}, {amount: 250, flags: {review: "2030-12-31"}, openedAt: "2030-12-31", tier: "silver"}, {amount: 1, flags: {review: "2025-03-20"}, openedAt: "2025-03-20", tier: "bronze"}, {amount: 0, flags: {review: "2025-03-20"}, openedAt: "2025-03-20", tier: "gold"}, {amount: 0, flags: {review: "1990-06-15"}, openedAt: "1990-06-15", tier: "silver"}, {amount: 0.5, flags: {review: "2025-03-20T10:15:30Z"}, openedAt: "2025-03-20T10:15:30Z", tier: "silver"}, {amount: 184, flags: {review: "2024-02-29"}, openedAt: "2024-02-29", tier: "silver"}, {amount: 10, flags: {review: "2030-12-31"}, openedAt: "2030-12-31", tier: "silver"}, {amount: 1, flags: {review: "2024-01-01"}, openedAt: "2024-01-01", tier: "silver"}, {amount: 1000, flags: {review: "2024-01-01"}, openedAt: "2024-01-01", tier: "gold"}, {amount: 250, flags: {review: "1990-06-15"}, openedAt: "1990-06-15", tier: "gold"}], decision: [0, 0], insured: false, limit: 123456789.123, price: 1000, rate: 0, scores: {penalty: {s: 0}}, share: ["DE", "Oslo"]}}}, + [{shipment: {limit: 1, insured: true, rate: 0.000001, price: 5, companies: []}}, {shipment: {adjusted: [0.5, 0, 0.000000], capped: [], companies: [], decision: [0.000000, 1, 0.000001], insured: true, limit: 1, price: 5, rate: 0.000001, scores: {penalty: {s: 0.000000}}, share: ["true", "Oslo"], surcharge: 18, tag: 0.000000}}], + {input: {shipment: {limit: 2.50, insured: false, rate: 1000, price: 5, companies: [{amount: 123456789.123, tier: "bronze", openedAt: "2024-02-29"}, {amount: 0, tier: "gold", openedAt: "1990-06-15"}, {amount: 0, tier: "bronze", openedAt: "2024-01-01"}]}}, goals: ["shipment.scores.penalty", "shipment.capped", "company.segment"], output: {shipment: {capped: [{amount: 0, flags: {review: "1990-06-15", summary: 1000}, openedAt: "1990-06-15", segment: [1000, 1000, 1000], tier: "gold"}], companies: [{amount: 123456789.123, flags: {review: "2024-02-29", summary: 1000}, openedAt: "2024-02-29", segment: [1000, 1000, 1000], tier: "bronze"}, {amount: 0, flags: {review: "1990-06-15", summary: 1000}, openedAt: "1990-06-15", segment: [1000, 1000, 1000], tier: "gold"}, {amount: 0, flags: {review: "2024-01-01", summary: 1000}, openedAt: "2024-01-01", segment: [1000, 1000, 1000], tier: "bronze"}], insured: false, limit: 2.50, price: 5, rate: 1000, scores: {penalty: {s: 0}}}}}, + {input: {shipment: {limit: 5, insured: false, rate: 1, price: 2, companies: []}}, goals: ["company.segment", "shipment.capped", "shipment.surcharge"], output: {shipment: {capped: [], companies: [], insured: false, limit: 5, price: 2, rate: 1, surcharge: 18}}}, + {input: {shipment: {limit: 3, insured: true, rate: 1000000, price: 0.1, companies: [{amount: 1, tier: "gold", openedAt: "2000-01-01"}, {amount: -0, tier: "gold", openedAt: "2025-03-20"}]}}, goals: ["shipment.capped", "shipment.share"], output: {shipment: {adjusted: [0.5, 0, 0], capped: [{amount: 1, flags: {review: "2000-01-01", summary: 1000000}, openedAt: "2000-01-01", tier: "gold"}], companies: [{amount: 1, flags: {review: "2000-01-01", summary: 1000000}, openedAt: "2000-01-01", tier: "gold"}, {amount: 0, flags: {review: "2025-03-20", summary: 1000000}, openedAt: "2025-03-20", tier: "gold"}], decision: [0, 3, 1000000], insured: true, limit: 3, price: 0.1, rate: 1000000, scores: {penalty: {s: 0}}, share: ["true", "Oslo"]}}}, + {input: {shipment: {limit: 250, insured: true, rate: -1, price: 335, companies: [{amount: 3, tier: "bronze", openedAt: "2030-12-31"}]}}, goals: ["shipment.adjusted"], output: {shipment: {adjusted: [0.5, 1, 0], companies: [{amount: 3, flags: {summary: -1}, openedAt: "2030-12-31", tier: "bronze"}], decision: [0, 250, -1], insured: true, limit: 250, price: 335, rate: -1, scores: {penalty: {s: 0}}, share: ["true", "Oslo"]}}}, + {input: {shipment: {limit: 1, insured: true, rate: 1000, price: 10, companies: [{amount: 1000, tier: "gold", openedAt: "2024-01-01"}]}}, goals: ["shipment.surcharge"], output: {shipment: {adjusted: [0.5, 0, 0], companies: [{amount: 1000, flags: {summary: 1000}, openedAt: "2024-01-01", tier: "gold"}], decision: [0, 1, 1000], insured: true, limit: 1, price: 10, rate: 1000, scores: {penalty: {s: 0}}, share: ["true", "Oslo"], surcharge: 0}}}, + {input: {shipment: {limit: 1, insured: false, rate: 1000, price: 0.5, companies: [{amount: true, tier: "bronze", openedAt: "2030-12-31"}, {amount: 0.1, tier: "gold", openedAt: "2024-02-29"}, {amount: -500, tier: "gold", openedAt: "2024-01-01"}, {amount: -500, tier: "gold", openedAt: "2024-02-29"}, {amount: 10, tier: "silver", openedAt: "1990-06-15"}]}}, goals: ["shipment.surcharge", "shipment.capped"], output: "!error: InputValidationFailed"}, + {input: {shipment: {limit: 10, insured: true, rate: 1, price: 1, companies: [{amount: 0.5, tier: "gold", openedAt: "1990-06-15"}, {amount: 18, tier: "gold", openedAt: "2000-01-01"}, {amount: 5, tier: "bronze", openedAt: "2024-02-29"}, {amount: 18, tier: "gold", openedAt: "2024-02-29"}, {amount: 1, tier: "silver", openedAt: "2025-03-20"}]}}, goals: ["shipment.tag"], output: {shipment: {adjusted: [0.5, 0, 0], companies: [{amount: 0.5, flags: {summary: 1}, openedAt: "1990-06-15", tier: "gold"}, {amount: 18, flags: {summary: 1}, openedAt: "2000-01-01", tier: "gold"}, {amount: 5, flags: {summary: 1}, openedAt: "2024-02-29", tier: "bronze"}, {amount: 18, flags: {summary: 1}, openedAt: "2024-02-29", tier: "gold"}, {amount: 1, flags: {summary: 1}, openedAt: "2025-03-20", tier: "silver"}], decision: [0, 10, 1], insured: true, limit: 10, price: 1, rate: 1, scores: {penalty: {s: 0}}, share: ["true", "Oslo"], tag: 0}}}, + {input: {shipment: {limit: 1, insured: false, rate: 100, price: 1000, companies: [{amount: 1000000, tier: "gold", openedAt: "2024-01-01"}]}}, goals: ["shipment.surcharge", "shipment.capped", "company.flags.summary"], output: {shipment: {capped: [], companies: [{amount: 1000000, flags: {review: "2024-01-01", summary: 100}, openedAt: "2024-01-01", tier: "gold"}], insured: false, limit: 1, price: 1000, rate: 100, surcharge: 1}}}, + {input: {shipment: {limit: 1, insured: true, rate: 1.5, price: 1.5, companies: [{amount: 100, tier: "silver", openedAt: "2024-01-01"}, {amount: 0.1, tier: "gold", openedAt: "2024-02-29"}]}}, goals: ["company.flags.review", "company.flags.summary", "shipment.adjusted"], output: {shipment: {adjusted: [0.5, 0, 0.0], companies: [{amount: 100, flags: {review: "2024-01-01", summary: 1.5}, openedAt: "2024-01-01", tier: "silver"}, {amount: 0.1, flags: {review: "2024-02-29", summary: 1.5}, openedAt: "2024-02-29", tier: "gold"}], decision: [0.0, 1, 1.5], insured: true, limit: 1, price: 1.5, rate: 1.5, scores: {penalty: {s: 0.0}}, share: ["true", "Oslo"]}}}, + {input: {shipment: {limit: 0.1, insured: false, rate: -0.01, price: 18, companies: [{amount: 3, tier: "silver", openedAt: "2024-01-01"}, {amount: 5, tier: "gold", openedAt: "2025-03-20"}]}}, goals: ["shipment.surcharge"], output: {shipment: {companies: [{amount: 3, flags: {summary: -0.01}, openedAt: "2024-01-01", tier: "silver"}, {amount: 5, flags: {summary: -0.01}, openedAt: "2025-03-20", tier: "gold"}], insured: false, limit: 0.1, price: 18, rate: -0.01, surcharge: 1.5}}}, + [{shipment: {insured: false, rate: 2, price: 5, companies: [{amount: 10, tier: "bronze", openedAt: "2024-02-29"}, {amount: 5, tier: "gold", openedAt: "2030-12-31"}]}}, "!error: MissingRequiredInputs"], + {input: {shipment: {limit: 1000000, insured: false, rate: -0.01, price: 10, companies: [{amount: 10, tier: "bronze", openedAt: "2024-02-29"}]}}, goals: ["shipment.share", "shipment.tag", "shipment.capped"], output: {shipment: {adjusted: [1000000, -0.01, 0.00], capped: [], companies: [{amount: 10, flags: {review: "2024-02-29"}, openedAt: "2024-02-29", tier: "bronze"}], decision: [0.00, -0.01], insured: false, limit: 1000000, price: 10, rate: -0.01, scores: {penalty: {s: 0.00}}, share: ["DE", "Oslo"], tag: -0.01}}}, + {input: {shipment: {limit: 0.5, insured: false, rate: 2, price: 3, companies: [{amount: -1, tier: "gold", openedAt: "2000-01-01"}]}}, goals: ["shipment.surcharge", "company.flags.review"], output: {shipment: {companies: [{amount: -1, flags: {review: "2000-01-01", summary: 2}, openedAt: "2000-01-01", tier: "gold"}], insured: false, limit: 0.5, price: 3, rate: 2, surcharge: 1.5}}}, + {input: {shipment: {limit: 0, insured: true, rate: 10, price: 100, companies: [{amount: 1, tier: "silver", openedAt: "2000-01-01"}, {amount: 1.5, tier: "gold", openedAt: "2000-01-01"}], extraField: 1}}, goals: ["company.flags.summary", "company.flags.review", "shipment.scores.penalty"], output: {shipment: {companies: [{amount: 1, flags: {review: "2000-01-01", summary: 10}, openedAt: "2000-01-01", tier: "silver"}, {amount: 1.5, flags: {review: "2000-01-01", summary: 10}, openedAt: "2000-01-01", tier: "gold"}], extraField: 1, insured: true, limit: 0, price: 100, rate: 10, scores: {penalty: {s: 0}}}}}, + {input: {shipment: {limit: 5, insured: true, rate: 1000, price: 10, companies: [{amount: 0.1, tier: "silver", openedAt: "2024-02-29"}, {amount: 18, tier: "bronze", openedAt: "2025-03-20T10:15:30Z"}]}}, goals: ["company.segment", "shipment.tag"], output: {shipment: {adjusted: [0.5, 0, 0], companies: [{amount: 0.1, flags: {summary: 1000}, openedAt: "2024-02-29", segment: [1000, -18], tier: "silver"}, {amount: 18, flags: {summary: 1000}, openedAt: "2025-03-20T10:15:30Z", segment: [1000, -18], tier: "bronze"}], decision: [0, 5, 1000], insured: true, limit: 5, price: 10, rate: 1000, scores: {penalty: {s: 0}}, share: ["true", "Oslo"], tag: 0}}}, + [{shipment: {limit: 0.1, insured: false, rate: 0.5, companies: [{amount: 50, tier: "gold", openedAt: "2000-01-01"}]}}, "!error: MissingRequiredInputs"], + {input: {shipment: {limit: 100, insured: false, rate: 10, price: 3, companies: [{amount: 1, tier: "gold", openedAt: "2025-03-20T10:15:30Z"}, {amount: 2, tier: "gold", openedAt: "2024-02-29"}]}}, goals: ["company.segment", "shipment.scores.penalty"], output: {shipment: {companies: [{amount: 1, flags: {summary: 10}, openedAt: "2025-03-20T10:15:30Z", segment: [-1, 10], tier: "gold"}, {amount: 2, flags: {summary: 10}, openedAt: "2024-02-29", segment: [-1, 10], tier: "gold"}], insured: false, limit: 100, price: 3, rate: 10, scores: {penalty: {s: 0}}}}}, + {input: {shipment: {limit: 1, insured: false, rate: 10, price: 2.50, companies: [{amount: 123456789.123, tier: "gold", openedAt: "2000-01-01"}, {amount: 1000, tier: "gold", openedAt: "1990-06-15"}, {amount: 3, tier: "gold", openedAt: "2025-03-20T10:15:30Z"}, {amount: 5, tier: "gold", openedAt: "2025-03-20"}]}}, goals: ["shipment.adjusted", "company.flags.summary"], output: {shipment: {adjusted: [1, 10, 0], companies: [{amount: 123456789.123, flags: {summary: 10}, openedAt: "2000-01-01", tier: "gold"}, {amount: 1000, flags: {summary: 10}, openedAt: "1990-06-15", tier: "gold"}, {amount: 3, flags: {summary: 10}, openedAt: "2025-03-20T10:15:30Z", tier: "gold"}, {amount: 5, flags: {summary: 10}, openedAt: "2025-03-20", tier: "gold"}], decision: [0, 10], insured: false, limit: 1, price: 2.50, rate: 10, scores: {penalty: {s: 0}}, share: ["DE", "Oslo"]}}}, + {input: {shipment: {limit: -1, insured: false, rate: 18, price: 1, companies: []}}, goals: ["shipment.adjusted", "company.flags.review"], output: {shipment: {adjusted: [-1, 18, 0], companies: [], decision: [0, 18], insured: false, limit: -1, price: 1, rate: 18, scores: {penalty: {s: 0}}, share: ["DE", "Oslo"]}}}, + {input: {shipment: {limit: 18, insured: true, rate: 1.5, price: 1, companies: []}}, goals: ["company.segment", "shipment.surcharge", "shipment.share"], output: {shipment: {adjusted: [0.5, 0, 0.0], companies: [], decision: [0.0, 18, 1.5], insured: true, limit: 18, price: 1, rate: 1.5, scores: {penalty: {s: 0.0}}, share: ["true", "Oslo"], surcharge: 18}}}, + {input: {shipment: {limit: 0.5, insured: false, rate: 1, price: 3, companies: []}}, goals: ["shipment.tag"], output: {shipment: {adjusted: [0.5, 1, 0], companies: [], decision: [0, 1], insured: false, limit: 0.5, price: 3, rate: 1, scores: {penalty: {s: 0}}, share: ["DE", "Oslo"], tag: 0}}}, + {input: {shipment: {limit: 18, insured: true, rate: 5, price: 2, companies: []}}, goals: ["company.flags.summary", "company.flags.review", "shipment.tag"], output: {shipment: {adjusted: [0.5, 0, 0], companies: [], decision: [0, 18, 5], insured: true, limit: 18, price: 2, rate: 5, scores: {penalty: {s: 0}}, share: ["true", "Oslo"], tag: 0}}}, + [{shipment: {limit: 1000, insured: true, rate: 50, price: -500, companies: []}}, {shipment: {adjusted: [0.5, 0, 0], capped: [], companies: [], decision: [0, 1000, 50], insured: true, limit: 1000, price: -500, rate: 50, scores: {penalty: {s: 0}}, share: ["true", "Oslo"], surcharge: 18, tag: 0}}], + ], +} + +// seed 353100 (attempt 0) +{ + name: "goals 32: borrower/accounts + address: 1 assertion, 3 expression, 3 table; 5 root, 3 per-member, 0 top-level computed", + policy: { + models: {borrower: {score: "number?", income: "number", status: "string(open|closed|pending)?", label: "string?", accounts: "acct[]", address: "address"}, acct: {years: "number", dueDate: "date"}, address: {balance: "number", verified: "boolean", openedAt: "date"}}, + blocks: [ + {assertion: "acct.total", conditions: [["and", "acct.dueDate.isSameOrBefore(d('2000-06-30'), 'month')", 1], "not (borrower.address.verified)", ["or", "(borrower.status ?? '') in ['pending', 'closed']", 2], ["or", "((borrower.meta.fee ?? false) and (borrower.meta.fee ?? false))", 0], ["or", "acct.dueDate >= d('2025-03-20')", 1]]}, + {expression: "acct.totals.eligible", value: "len(borrower.address.health)"}, + {table: "t2", hit: "collect", inputs: ["address.openedAt"], outputs: ["address.penalty", "address.calc.review", "address.health"], rules: [ + ["", "'gold'", "", "address.verified"], + ["", "lower((borrower.label ?? ''))", "", "(borrower.meta.fee ?? false)"], + ]}, + {expression: "acct.grade", value: "((borrower.label ?? '') + '-' + (borrower.label ?? ''))"}, + {table: "t5", inputs: ["(min([abs((borrower.score ?? 0)), 1000]) ^ 1)"], outputs: ["borrower.exposure[]", "borrower.surcharge"], rules: [ + ["0, 1000", "(borrower.score ?? 0)", "(borrower.ok ?? false)"], + ["", "10", "(borrower.meta.fee ?? false)"], + ]}, + {table: "t1", inputs: ["(borrower.status ?? '')", "borrower.address.balance"], outputs: ["borrower.meta.fee", "borrower.ok"], rules: [ + ["'pending'", "10, 0.25", "borrower.address.verified", "borrower.address.verified"], + ["'pending'", ">= 0", "borrower.address.verified", "borrower.address.verified"], + ["'pending'", "", "", "borrower.address.verified"], + ["'open', 'closed'", "3", "borrower.address.openedAt.isBefore(d('2000-06-30'), 'day')", "borrower.address.verified"], + ["'pending', 'open'", "!= 1", "borrower.address.openedAt.isSame(d('2025-03-20'), 'year')", ""], + ]}, + {expression: "borrower.scores.segment", value: "filter(borrower.accounts, contains(['low', 'high', ''], #.grade))"}, + ], + }, + cases: [ + {input: {borrower: {score: 0, income: 0.5, status: "open", label: "-", accounts: [{years: 1.5, dueDate: "1990-06-15"}, {years: 1, dueDate: "2024-01-01"}], address: {balance: 0, verified: false, openedAt: "2030-12-31"}}}, goals: ["address.penalty", "borrower.meta.fee", "borrower.ok"], output: {borrower: {accounts: [{dueDate: "1990-06-15", years: 1.5}, {dueDate: "2024-01-01", years: 1}], address: {balance: 0, calc: {review: []}, health: [false, false], openedAt: "2030-12-31", penalty: ["gold", "-"], verified: false}, income: 0.5, label: "-", meta: {fee: false}, ok: null, score: 0, status: "open"}}}, + {input: {borrower: {income: 331, status: null, label: "US", accounts: [{years: 7.25, dueDate: "2024-01-01"}, {years: 2, dueDate: "2030-12-31"}, {years: 10, dueDate: "2025-03-20"}, {years: 2, dueDate: "2024-01-01"}, {years: 1, dueDate: "2030-12-31"}], address: {balance: 0.1, verified: false, openedAt: "2025-03-20T10:15:30Z"}}}, goals: ["acct.total", "borrower.meta.fee"], output: {borrower: {accounts: [{dueDate: "2024-01-01", total: false, years: 7.25}, {dueDate: "2030-12-31", total: true, years: 2}, {dueDate: "2025-03-20", total: true, years: 10}, {dueDate: "2024-01-01", total: false, years: 2}, {dueDate: "2030-12-31", total: true, years: 1}], address: {balance: 0.1, openedAt: "2025-03-20T10:15:30Z", verified: false}, income: 331, label: "US", meta: {fee: null}, ok: null, status: null}}}, + {input: {borrower: {score: 123456789.123, income: 10, status: "closed", label: "VIP", accounts: [{years: 0.5, dueDate: "2025-03-20"}, {years: 50, dueDate: "2024-02-29"}, {years: -500, dueDate: "2024-02-29"}, {years: 3, dueDate: "2025-03-20T10:15:30Z"}, {years: -0, dueDate: "2030-12-31"}], address: {balance: 1000000, verified: false, openedAt: "2000-01-01"}, extraField: "x"}}, goals: ["borrower.surcharge", "acct.total", "borrower.exposure"], output: {borrower: {accounts: [{dueDate: "2025-03-20", total: true, years: 0.5}, {dueDate: "2024-02-29", total: false, years: 50}, {dueDate: "2024-02-29", total: false, years: -500}, {dueDate: "2025-03-20T10:15:30Z", total: true, years: 3}, {dueDate: "2030-12-31", total: true, years: 0}], address: {balance: 1000000, openedAt: "2000-01-01", verified: false}, exposure: [123456789.123, 10], extraField: "x", income: 10, label: "VIP", meta: {fee: null}, ok: null, score: 123456789.123, status: "closed", surcharge: false}}}, + {input: {borrower: {score: 65, income: 99.99, status: "closed", label: "high", accounts: [{years: -0.01, dueDate: "2024-02-29"}, {years: 5, dueDate: "2025-03-20T10:15:30Z"}, {years: 10, dueDate: "2024-02-29"}, {years: 0, dueDate: "2024-01-01"}], address: {balance: -500, verified: false, openedAt: "2024-02-29"}}}, goals: ["borrower.meta.fee"], output: {borrower: {accounts: [{dueDate: "2024-02-29", years: -0.01}, {dueDate: "2025-03-20T10:15:30Z", years: 5}, {dueDate: "2024-02-29", years: 10}, {dueDate: "2024-01-01", years: 0}], address: {balance: -500, openedAt: "2024-02-29", verified: false}, income: 99.99, label: "high", meta: {fee: null}, ok: null, score: 65, status: "closed"}}}, + {input: {borrower: {score: 65, income: 0, status: "open", label: "A1", accounts: [], address: {balance: 250, verified: true, openedAt: "1990-06-15"}}}, goals: ["address.calc.review", "borrower.scores.segment"], output: {borrower: {accounts: [], address: {balance: 250, calc: {review: []}, health: [true, false], openedAt: "1990-06-15", penalty: ["gold", "a1"], verified: true}, income: 0, label: "A1", meta: {fee: false}, ok: null, score: 65, scores: {segment: []}, status: "open"}}}, + {input: {borrower: {score: 1e3, income: 1000000, status: "open", label: "A1", accounts: [{years: 1000, dueDate: "2024-02-29"}, {years: 144, dueDate: "2024-02-29"}, {years: -500, dueDate: "2025-03-20"}], address: {balance: -0.5, verified: true, openedAt: "2025-03-20"}}}, goals: ["address.calc.review", "acct.total", "borrower.scores.segment"], output: {borrower: {accounts: [{dueDate: "2024-02-29", grade: "A1-A1", total: true, years: 1000}, {dueDate: "2024-02-29", grade: "A1-A1", total: true, years: 144}, {dueDate: "2025-03-20", grade: "A1-A1", total: true, years: -500}], address: {balance: -0.5, calc: {review: []}, health: [true, true], openedAt: "2025-03-20", penalty: ["gold", "a1"], verified: true}, income: 1000000, label: "A1", meta: {fee: true}, ok: null, score: 1000, scores: {segment: []}, status: "open"}}}, + [{borrower: {income: -0.5, status: "open", accounts: [{years: 2.50, dueDate: "1990-06-15"}, {years: -1, dueDate: "2030-12-31"}, {years: 1000, dueDate: "2024-01-01"}], address: {balance: 1000000, verified: true, openedAt: "2025-03-20T10:15:30Z"}}}, {borrower: {accounts: [{dueDate: "1990-06-15", grade: "-", total: true, totals: {eligible: 2}, years: 2.50}, {dueDate: "2030-12-31", grade: "-", total: true, totals: {eligible: 2}, years: -1}, {dueDate: "2024-01-01", grade: "-", total: true, totals: {eligible: 2}, years: 1000}], address: {balance: 1000000, calc: {review: []}, health: [true, true], openedAt: "2025-03-20T10:15:30Z", penalty: ["gold", ""], verified: true}, exposure: [0, 10], income: -0.5, meta: {fee: true}, ok: null, scores: {segment: []}, status: "open", surcharge: false}}], + [{borrower: {income: 0.5, status: "open", accounts: [{years: -0.5, dueDate: "2025-03-20T10:15:30Z"}], address: {balance: 0.25, verified: true, openedAt: "2025-03-20T10:15:30Z"}}}, {borrower: {accounts: [{dueDate: "2025-03-20T10:15:30Z", grade: "-", total: true, totals: {eligible: 2}, years: -0.5}], address: {balance: 0.25, calc: {review: []}, health: [true, true], openedAt: "2025-03-20T10:15:30Z", penalty: ["gold", ""], verified: true}, exposure: [0, 10], income: 0.5, meta: {fee: true}, ok: null, scores: {segment: []}, status: "open", surcharge: false}}], + {input: {borrower: {score: 50, income: 250, status: "open", label: "gold", accounts: [{years: 1.5, dueDate: "2000-01-01"}, {years: 7.25, dueDate: "2025-03-20"}, {years: 0, dueDate: "2025-03-20T10:15:30Z"}, {years: 99.99, dueDate: "1990-06-15"}, {years: -500, dueDate: "1990-06-15"}], address: {balance: 123456789.123, verified: true, openedAt: "1990-06-15"}}}, goals: ["borrower.surcharge"], output: {borrower: {accounts: [{dueDate: "2000-01-01", years: 1.5}, {dueDate: "2025-03-20", years: 7.25}, {dueDate: "2025-03-20T10:15:30Z", years: 0}, {dueDate: "1990-06-15", years: 99.99}, {dueDate: "1990-06-15", years: -500}], address: {balance: 123456789.123, openedAt: "1990-06-15", verified: true}, exposure: [10], income: 250, label: "gold", meta: {fee: false}, ok: null, score: 50, status: "open", surcharge: false}}}, + {input: {borrower: {score: [1], income: 123456789.123, status: "closed", label: "", accounts: [{years: 0, dueDate: "2025-03-20"}, {years: 99.99, dueDate: "2000-01-01"}], address: {balance: 3, verified: true, openedAt: "2024-02-29"}}}, goals: ["address.health", "acct.totals.eligible"], output: "!error: InputValidationFailed"}, + {input: {borrower: {score: 1000, income: 99999999999999999999, status: "closed", label: "Zed", accounts: [], address: {balance: 2, verified: false, openedAt: "2024-01-01"}}}, goals: ["borrower.meta.fee", "acct.totals.eligible"], output: {borrower: {accounts: [], address: {balance: 2, calc: {review: []}, health: [false, false], openedAt: "2024-01-01", penalty: ["gold", "zed"], verified: false}, income: 99999999999999999999, label: "Zed", meta: {fee: null}, ok: null, score: 1000, status: "closed"}}}, + {input: {borrower: {score: 50, income: 10, status: 5, label: "O'Neil", accounts: [{years: 1000, dueDate: "1990-06-15"}, {years: 65, dueDate: "2024-01-01"}], address: {balance: 100, verified: true, openedAt: "1990-06-15"}}}, goals: ["acct.total"], output: "!error: InputValidationFailed"}, + {input: {borrower: {score: 0.000001, income: 50, status: "open", label: "high", accounts: [], address: {balance: 10, verified: false, openedAt: "1990-06-15"}}}, goals: ["borrower.exposure", "address.penalty"], output: {borrower: {accounts: [], address: {balance: 10, calc: {review: []}, health: [false, false], openedAt: "1990-06-15", penalty: ["gold", "high"], verified: false}, exposure: [10], income: 50, label: "high", meta: {fee: false}, ok: null, score: 0.000001, status: "open", surcharge: false}}}, + {input: {borrower: {score: null, income: 0.000001, status: "pending", label: null, accounts: [{years: 1.5, dueDate: "2030-12-31"}], address: {balance: 1.5, verified: true, openedAt: "2024-01-01"}}}, goals: ["borrower.meta.fee"], output: {borrower: {accounts: [{dueDate: "2030-12-31", years: 1.5}], address: {balance: 1.5, openedAt: "2024-01-01", verified: true}, income: 0.000001, label: null, meta: {fee: true}, ok: true, score: null, status: "pending"}}}, + ], +} + +// seed 353200 (attempt 0) +{ + name: "goals 33: borrower/vehicles/payments: 2 assertion, 3 expression, 3 match, 4 table; 5 root, 9 per-member, 2 top-level computed", + policy: { + models: {borrower: {days: "number?", balance: "number", active: "boolean?", priority: "boolean?", vehicles: "vehicle[]"}, vehicle: {limit: "number?", verified: "boolean?", birthDate: "date", since: "date", payments: "payment[]"}, payment: {rate: "number", balance: "number", country: "string"}}, + blocks: [ + {expression: "surcharge", value: "matches((borrower.calc.net ?? ''), '^.{2,}$')"}, + {expression: "grade", value: "((borrower.balance / 3) > borrower.balance and not ((borrower.days ?? 0) < (borrower.days ?? 0)))"}, + {match: "borrower.level", arms: [["borrower.flag == null", "`${(borrower.calc.net ?? '')}/${2}`"], ["((borrower.days ?? 0) % (abs(50) + 1)) == borrower.balance", "(borrower.calc.net ?? '')"], ["((borrower.priority ?? false) and (borrower.priority ?? false))", "(split((borrower.calc.net ?? ''), '-')[0] ?? 'none')"], ["", "(borrower.calc.net ?? '')"]]}, + {table: "t8", inputs: ["(borrower.days ?? 0)"], outputs: ["vehicle.ok", "vehicle.segment", "vehicle.quota"], rules: [ + ["", "(borrower.days ?? 0)", "(vehicle.limit ?? 0)", "(vehicle.limit ?? 0)"], + ["<= 2", "(borrower.balance) / (abs(1.5) + 1)", "(vehicle.weighted ?? 0)", "(vehicle.penalty ?? 0)"], + ["1.5", "(borrower.points ? borrower.review : (vehicle.limit ?? 0))", "(vehicle.penalty ?? 0)", "(vehicle.weighted ?? 0)"], + ["0.5, 0.5", "vehicle.margin", "borrower.balance", "(min([abs((vehicle.penalty ?? 0)), 1000]) ^ 2)"], + ["", "vehicle.margin", "1", "borrower.review"], + ["> 1.5", "(vehicle.weighted ?? 0)", "(max(map(vehicle.payments, #.balance)) ?? 0)", "len(filter(vehicle.payments, #.rate in [25..67]))"], + ]}, + {match: "vehicle.margin", arms: [["all(borrower.vehicles, #.birthDate.isBefore(d('2025-03-20'), 'year'))", "count(borrower.vehicles, (#.limit ?? 0) in (23..151))"], ["not ((vehicle.verified ?? false))", "(borrower.balance / 3)"], ["borrower.priority != null", "(borrower.days ?? 0)"], ["some(borrower.vehicles, not ((#.verified ?? false)))", "2"], ["", "(vehicle.limit ?? 0)"]]}, + {table: "t2", inputs: ["(borrower.priority ?? false)", "borrower.days", "borrower.priority"], outputs: ["borrower.flag", "borrower.calc.net"], rules: [ + ["false", "5, 10", "true", "(borrower.priority ?? false)", "'a'"], + ["true", "", "false", "not ((borrower.priority ?? false))", "'x'"], + ["false", "0", "false", "(borrower.active ?? false)", ""], + ["true", "0.5, 0", "true", "", "'ok'"], + ["true", "100", "", "(borrower.active ?? false)", "string((borrower.active ?? false))"], + ["", "", "", "(borrower.active ?? false)", ""], + ]}, + {assertion: "vehicle.scores.share", conditions: [["and", "(contains(['gold', 'gold', ''], (borrower.calc.net ?? '')) and (vehicle.weighted ?? 0) < 50)", 2], ["and", "(borrower.calc.net ?? '') != 'A1'", 1], ["or", "((vehicle.segment ?? 0) / 3) <= 0.25", 1], ["and", "matches((vehicle.capped + '-' + borrower.level), 'a')", 0], ["or", "(startsWith((borrower.calc.net ?? ''), 'x') or vehicle.since.isBefore(d('2025-03-20'), 'month'))", 2]]}, + {match: "vehicle.capped", arms: [["not ((borrower.priority ?? false))", "(split((borrower.calc.net ?? ''), '-')[1] ?? 'none')"], ["none(vehicle.payments, matches(#.country, '^[A-Z]'))", "(borrower.calc.net ?? '')"], ["", "(borrower.calc.net ?? '')"]]}, + {table: "t11", inputs: ["(borrower.calc.net ?? '')"], outputs: ["vehicle.band"], rules: [ + ["startsWith($, 'DE')", "matches(vehicle.capped, 'a')"], + ["'VIP'", "(borrower.priority ?? false)"], + ["'VIP', 'a'", "(borrower.priority ?? false)"], + ["", "grade"], + ["$ != 'A1'", "(borrower.priority ?? false)"], + ]}, + {assertion: "borrower.points", conditions: ["contains(['gold', 'x', ''], (borrower.calc.net ?? ''))"]}, + {table: "t3", inputs: ["-((borrower.days ?? 0))", "(borrower.flag ?? false)", "(vehicle.verified ?? false)"], outputs: ["vehicle.weighted", "vehicle.penalty"], rules: [ + ["0.5", "", "true", "", "vehicle.margin"], + ["3, 1.5", "", "false", "count(vehicle.payments, #.balance > #.balance)", "18"], + ["[0.5..467.5]", "", "false", "(vehicle.limit ?? 0)", "(borrower.days ?? 0)"], + ["< 3", "", "false", "100", "(1 + (vehicle.limit ?? 0))"], + ["> 1", "", "true", "(borrower.days ?? 0)", "borrower.balance"], + ["", "true", "true", "borrower.balance", "(vehicle.limit ?? 0)"], + ["", "", "", "(borrower.balance) / (abs(vehicle.margin) + 1)", ""], + ]}, + {expression: "borrower.review", value: "max([(borrower.days ?? 0), borrower.balance, borrower.balance])"}, + ], + }, + cases: [ + {input: {borrower: {balance: 10, active: false, priority: true, vehicles: [{limit: null, verified: false, birthDate: "2030-12-31", since: "2030-12-31", payments: [{rate: 1.5, balance: 100, country: "ok"}, {rate: 65, balance: 1, country: "gold"}, {rate: 0.5, balance: 5, country: "ok"}]}, {limit: 0.5, verified: false, birthDate: "1990-06-15", since: "1990-06-15", payments: [{rate: -1, balance: -1, country: "-"}]}]}}, goals: ["vehicle.segment"], output: {borrower: {active: false, balance: 10, priority: true, vehicles: [{birthDate: "2030-12-31", limit: null, ok: 0, payments: [{balance: 100, country: "ok", rate: 1.5}, {balance: 1, country: "gold", rate: 65}, {balance: 5, country: "ok", rate: 0.5}], quota: 0, segment: 0, since: "2030-12-31", verified: false}, {birthDate: "1990-06-15", limit: 0.5, ok: 0, payments: [{balance: -1, country: "-", rate: -1}], quota: 0.5, segment: 0.5, since: "1990-06-15", verified: false}]}}}, + {input: {borrower: {days: 3, balance: 2.50, active: false, priority: true, vehicles: [{limit: true, verified: false, birthDate: "1990-06-15", since: "2030-12-31", payments: [{rate: 0.5, balance: 0.000001, country: "x"}]}, {limit: 50, verified: true, birthDate: "2024-01-01", since: "2024-02-29", payments: [{rate: 100, balance: 7.25, country: "ok"}, {rate: 1000, balance: 18, country: "VIP"}, {rate: 0.5, balance: 1.5, country: "12"}]}, {limit: 1000, verified: false, birthDate: "2000-01-01", since: "2024-01-01", payments: [{rate: 0, balance: 0, country: "retail"}, {rate: 123456789.123, balance: 0, country: "ok"}, {rate: 0, balance: 99.99, country: "a"}]}]}}, goals: ["surcharge"], output: "!error: InputValidationFailed"}, + {input: {borrower: {days: 1e3, balance: 0, active: false, priority: false, vehicles: [{limit: 1.5, verified: false, birthDate: "2024-02-29", since: "2024-02-29", payments: [{rate: 0.5, balance: 100, country: "Oslo"}, {rate: -0.5, balance: 0.25, country: "12"}]}, {limit: 2, verified: true, birthDate: "2000-01-01", since: "2024-01-01", payments: [{rate: -1, balance: 10, country: "NL"}]}]}}, goals: ["vehicle.scores.share", "borrower.level", "borrower.points"], output: {borrower: {active: false, balance: 0, calc: {net: null}, days: 1000, flag: false, level: "", points: true, priority: false, vehicles: [{birthDate: "2024-02-29", capped: "none", limit: 1.5, margin: 0, ok: 1000, payments: [{balance: 100, country: "Oslo", rate: 0.5}, {balance: 0.25, country: "12", rate: -0.5}], penalty: 2.5, quota: 1.5, scores: {share: false}, segment: 1.5, since: "2024-02-29", verified: false, weighted: 100}, {birthDate: "2000-01-01", capped: "none", limit: 2, margin: 0, ok: 1000, payments: [{balance: 10, country: "NL", rate: -1}], penalty: null, quota: 2, scores: {share: false}, segment: 2, since: "2024-01-01", verified: true, weighted: 0}]}}}, + {input: {borrower: {days: 0.5, balance: 10, active: true, priority: false, vehicles: [{limit: 0.25, verified: false, birthDate: "2024-02-29", payments: [{rate: 0, balance: 123456789.123, country: "VIP"}, {rate: 100, balance: 1, country: "3.5"}]}, {limit: 65, verified: false, birthDate: "2025-03-20T10:15:30Z", since: "2025-03-20", payments: [{rate: 65, balance: 5, country: "DE"}, {rate: 0.25, balance: 2.50, country: "x"}, {rate: 5, balance: 0.5, country: "Oslo"}]}, {limit: 50, verified: true, birthDate: "2025-03-20", since: "2024-01-01", payments: [{rate: 0.5, balance: 5, country: "12"}, {rate: 50, balance: 123456789.123, country: "gold"}]}, {limit: 0.5, verified: false, birthDate: "2030-12-31", since: "1990-06-15", payments: [{rate: 0.5, balance: 100, country: "A1"}]}, {limit: -0, verified: true, birthDate: "2000-01-01", since: "2030-12-31", payments: [{rate: 1.5, balance: 5, country: "a"}, {rate: 2, balance: 100, country: "NL"}]}]}}, goals: ["borrower.review"], output: {borrower: {active: true, balance: 10, days: 0.5, priority: false, review: 10, vehicles: [{birthDate: "2024-02-29", limit: 0.25, payments: [{balance: 123456789.123, country: "VIP", rate: 0}, {balance: 1, country: "3.5", rate: 100}], verified: false}, {birthDate: "2025-03-20T10:15:30Z", limit: 65, payments: [{balance: 5, country: "DE", rate: 65}, {balance: 2.50, country: "x", rate: 0.25}, {balance: 0.5, country: "Oslo", rate: 5}], since: "2025-03-20", verified: false}, {birthDate: "2025-03-20", limit: 50, payments: [{balance: 5, country: "12", rate: 0.5}, {balance: 123456789.123, country: "gold", rate: 50}], since: "2024-01-01", verified: true}, {birthDate: "2030-12-31", limit: 0.5, payments: [{balance: 100, country: "A1", rate: 0.5}], since: "1990-06-15", verified: false}, {birthDate: "2000-01-01", limit: 0, payments: [{balance: 5, country: "a", rate: 1.5}, {balance: 100, country: "NL", rate: 2}], since: "2030-12-31", verified: true}]}}}, + {input: {borrower: {days: 0.25, balance: 0.5, active: true, priority: true, vehicles: [{limit: 50, verified: false, birthDate: "2030-12-31", since: "2030-12-31", payments: [{rate: 0, balance: 0.000001, country: "A1"}, {rate: 100, balance: 2, country: "12"}]}, {limit: 0.25, verified: false, birthDate: "2000-01-01", since: "2025-03-20T10:15:30Z", payments: []}, {limit: 5, verified: false, birthDate: "2025-03-20", since: "2000-01-01", payments: [{rate: 0.000001, balance: 1.5, country: "O'Neil"}, {rate: 50, balance: 1.5, country: "12"}, {rate: 10, balance: 50, country: "VIP"}]}, {limit: 0.5, verified: false, birthDate: "2000-01-01", since: "2025-03-20T10:15:30Z", payments: [{rate: 50, balance: 1000, country: "retail"}]}, {limit: 50, verified: false, birthDate: "2025-03-20", since: "2024-01-01", payments: [{rate: 3, balance: 0, country: "日本"}]}]}}, goals: ["vehicle.band"], output: {borrower: {active: true, balance: 0.5, calc: {net: null}, days: 0.25, flag: true, priority: true, vehicles: [{band: false, birthDate: "2030-12-31", limit: 50, payments: [{balance: 0.000001, country: "A1", rate: 0}, {balance: 2, country: "12", rate: 100}], since: "2030-12-31", verified: false}, {band: false, birthDate: "2000-01-01", limit: 0.25, payments: [], since: "2025-03-20T10:15:30Z", verified: false}, {band: false, birthDate: "2025-03-20", limit: 5, payments: [{balance: 1.5, country: "O'Neil", rate: 0.000001}, {balance: 1.5, country: "12", rate: 50}, {balance: 50, country: "VIP", rate: 10}], since: "2000-01-01", verified: false}, {band: false, birthDate: "2000-01-01", limit: 0.5, payments: [{balance: 1000, country: "retail", rate: 50}], since: "2025-03-20T10:15:30Z", verified: false}, {band: false, birthDate: "2025-03-20", limit: 50, payments: [{balance: 0, country: "日本", rate: 3}], since: "2024-01-01", verified: false}]}, grade: false}}, + {input: {borrower: {days: 3, balance: 0.1, active: false, priority: false, vehicles: [{limit: 100, verified: false, birthDate: "2000-01-01", since: "2025-03-20T10:15:30Z", payments: [{rate: 2.50, balance: 0.5, country: "VIP"}, {rate: 0, balance: 5, country: "日本"}]}, {limit: 123456789.123, verified: true, birthDate: "2024-02-29", since: "2025-03-20", payments: [{rate: 1000, balance: 10, country: "gold"}, {rate: 1.5, balance: 0, country: "retail"}]}, {limit: 50, verified: true, birthDate: "2030-12-31", since: "1990-06-15", payments: []}, {limit: 0.1, verified: true, birthDate: "2025-03-20", since: "2024-01-01", payments: [{rate: 1.5, balance: 2.50, country: "VIP"}]}, {limit: 10, verified: false, birthDate: "2000-01-01", since: "2024-02-29", payments: [{rate: 123456789.123, balance: 5, country: "DE"}]}]}}, goals: ["borrower.flag", "vehicle.capped", "vehicle.band"], output: {borrower: {active: false, balance: 0.1, calc: {net: null}, days: 3, flag: false, priority: false, vehicles: [{band: false, birthDate: "2000-01-01", capped: "none", limit: 100, payments: [{balance: 0.5, country: "VIP", rate: 2.50}, {balance: 5, country: "日本", rate: 0}], since: "2025-03-20T10:15:30Z", verified: false}, {band: false, birthDate: "2024-02-29", capped: "none", limit: 123456789.123, payments: [{balance: 10, country: "gold", rate: 1000}, {balance: 0, country: "retail", rate: 1.5}], since: "2025-03-20", verified: true}, {band: false, birthDate: "2030-12-31", capped: "none", limit: 50, payments: [], since: "1990-06-15", verified: true}, {band: false, birthDate: "2025-03-20", capped: "none", limit: 0.1, payments: [{balance: 2.50, country: "VIP", rate: 1.5}], since: "2024-01-01", verified: true}, {band: false, birthDate: "2000-01-01", capped: "none", limit: 10, payments: [{balance: 5, country: "DE", rate: 123456789.123}], since: "2024-02-29", verified: false}]}, grade: false}}, + {input: {borrower: {days: 0.5, balance: 250, active: true, priority: false, vehicles: [{limit: null, verified: true, birthDate: "2025-03-20T10:15:30Z", since: "2025-03-20T10:15:30Z", payments: [{rate: 0, balance: 250, country: "retail"}, {rate: 0.1, balance: 1.5, country: "A1"}]}, {limit: 1000, verified: false, birthDate: "2024-01-01", since: "2024-02-29", payments: [{rate: 100, balance: 50, country: "x-y"}]}, {limit: null, birthDate: "2030-12-31", since: "2025-03-20", payments: [{rate: 1.5, balance: 0.5, country: "VIP"}, {rate: 2, balance: 1, country: "VIP"}]}, {verified: false, birthDate: "1990-06-15", since: "2000-01-01", payments: [{rate: -0.01, balance: -0, country: "NL"}, {rate: 0.5, balance: 0, country: "A1"}, {rate: 0, balance: 1.5, country: "DE"}]}, {verified: null, birthDate: "2000-01-01", since: "2025-03-20", payments: [{rate: 0.5, balance: 100, country: "Oslo"}, {rate: 0.5, balance: 5, country: "O'Neil"}, {rate: 0.5, balance: -0.01, country: "a"}]}]}}, goals: ["borrower.calc.net", "grade"], output: {borrower: {active: true, balance: 250, calc: {net: null}, days: 0.5, flag: true, priority: false, vehicles: [{birthDate: "2025-03-20T10:15:30Z", limit: null, payments: [{balance: 250, country: "retail", rate: 0}, {balance: 1.5, country: "A1", rate: 0.1}], since: "2025-03-20T10:15:30Z", verified: true}, {birthDate: "2024-01-01", limit: 1000, payments: [{balance: 50, country: "x-y", rate: 100}], since: "2024-02-29", verified: false}, {birthDate: "2030-12-31", limit: null, payments: [{balance: 0.5, country: "VIP", rate: 1.5}, {balance: 1, country: "VIP", rate: 2}], since: "2025-03-20"}, {birthDate: "1990-06-15", payments: [{balance: 0, country: "NL", rate: -0.01}, {balance: 0, country: "A1", rate: 0.5}, {balance: 1.5, country: "DE", rate: 0}], since: "2000-01-01", verified: false}, {birthDate: "2000-01-01", payments: [{balance: 100, country: "Oslo", rate: 0.5}, {balance: 5, country: "O'Neil", rate: 0.5}, {balance: -0.01, country: "a", rate: 0.5}], since: "2025-03-20", verified: null}]}, grade: false}}, + {input: {borrower: {days: null, balance: 1000, vehicles: [{birthDate: "2000-01-01", since: "2024-01-01", payments: [{rate: 50, balance: 1.5, country: "gold"}, {rate: -500, balance: 1, country: " pad "}]}]}}, goals: ["borrower.level", "vehicle.weighted"], output: {borrower: {balance: 1000, calc: {net: null}, days: null, flag: false, level: "", vehicles: [{birthDate: "2000-01-01", payments: [{balance: 1.5, country: "gold", rate: 50}, {balance: 1, country: " pad ", rate: -500}], penalty: 1, since: "2024-01-01", weighted: 100}]}}}, + [{borrower: {days: -0.5, balance: 50, active: true, priority: true, vehicles: [{limit: 5, verified: false, birthDate: "1990-06-15", since: "2030-12-31", payments: [{rate: -0.5, balance: 1000, country: "12"}]}, {limit: -0, verified: false, birthDate: "1990-06-15", since: "2024-02-29", payments: [{rate: 0.25, balance: 0.25, country: "gold"}, {rate: 7.25, balance: 1.5, country: "abc"}, {rate: 1000, balance: 99.99, country: "none"}]}]}}, {borrower: {active: true, balance: 50, calc: {net: null}, days: -0.5, flag: true, level: "", priority: true, vehicles: [{band: false, birthDate: "1990-06-15", capped: "", limit: 5, ok: -0.5, payments: [{balance: 1000, country: "12", rate: -0.5}], penalty: -0.5, quota: 5, scores: {share: false}, segment: 5, since: "2030-12-31", verified: false, weighted: 5}, {band: false, birthDate: "1990-06-15", capped: "", limit: 0, ok: -0.5, payments: [{balance: 0.25, country: "gold", rate: 0.25}, {balance: 1.5, country: "abc", rate: 7.25}, {balance: 99.99, country: "none", rate: 1000}], penalty: -0.5, quota: 0, scores: {share: true}, segment: 0, since: "2024-02-29", verified: false, weighted: 0}]}, grade: false, surcharge: false}], + {input: {borrower: {days: 18, balance: 100, active: false, priority: true, vehicles: [{limit: 65, verified: false, birthDate: "2024-01-01", since: "2025-03-20", payments: [{rate: 0.5, balance: 1e3, country: "ok"}]}, {limit: 2.50, verified: true, birthDate: "2025-03-20T10:15:30Z", since: "2025-03-20", payments: []}]}}, goals: ["vehicle.ok", "vehicle.weighted"], output: {borrower: {active: false, balance: 100, calc: {net: null}, days: 18, flag: false, priority: true, vehicles: [{birthDate: "2024-01-01", limit: 65, margin: 33.333333333333333333333333333, ok: 18, payments: [{balance: 1000, country: "ok", rate: 0.5}], penalty: 66, quota: 65, segment: 65, since: "2025-03-20", verified: false, weighted: 100}, {birthDate: "2025-03-20T10:15:30Z", limit: 2.50, margin: 18, ok: 18, payments: [], penalty: null, quota: 2.50, segment: 2.50, since: "2025-03-20", verified: true, weighted: 5.2631578947368421052631578947}]}}}, + {input: {borrower: {balance: 5, active: null, vehicles: [{limit: 1.5, verified: true, birthDate: "2000-01-01", since: "2024-01-01", payments: []}, {limit: null, verified: null, birthDate: "2025-03-20T10:15:30Z", since: "2030-12-31", payments: []}, {verified: false, birthDate: "2000-01-01", since: "2025-03-20T10:15:30Z", payments: [{rate: 5, balance: 0.5, country: "a"}, {rate: 18, balance: 10, country: "x"}, {rate: 0.1, balance: 2, country: "é ü"}]}, {limit: null, verified: true, birthDate: "2030-12-31", since: "1990-06-15", payments: [{rate: 3, balance: 50, country: "Zed"}, {rate: 2, balance: 0, country: "ok"}]}]}}, goals: ["vehicle.band"], output: {borrower: {active: null, balance: 5, calc: {net: null}, flag: false, vehicles: [{band: false, birthDate: "2000-01-01", limit: 1.5, payments: [], since: "2024-01-01", verified: true}, {band: false, birthDate: "2025-03-20T10:15:30Z", limit: null, payments: [], since: "2030-12-31", verified: null}, {band: false, birthDate: "2000-01-01", payments: [{balance: 0.5, country: "a", rate: 5}, {balance: 10, country: "x", rate: 18}, {balance: 2, country: "é ü", rate: 0.1}], since: "2025-03-20T10:15:30Z", verified: false}, {band: false, birthDate: "2030-12-31", limit: null, payments: [{balance: 50, country: "Zed", rate: 3}, {balance: 0, country: "ok", rate: 2}], since: "1990-06-15", verified: true}]}, grade: false}}, + {input: {borrower: {days: 100, balance: 18, active: false, priority: true, vehicles: []}}, goals: ["borrower.flag", "borrower.points", "vehicle.quota"], output: {borrower: {active: false, balance: 18, calc: {net: "false"}, days: 100, flag: false, points: false, priority: true, vehicles: []}}}, + {input: {borrower: {days: -0.5, balance: 65, active: true, vehicles: [{limit: null, verified: true, birthDate: "1990-06-15", since: "2025-03-20T10:15:30Z", payments: [{rate: 0.5, balance: 50, country: "VIP"}, {rate: 2, balance: 0.5, country: "a-b-c"}]}, {limit: 18, verified: true, birthDate: "2024-02-29", since: "2024-02-29", payments: [{rate: 2, balance: 50, country: "VIP"}, {rate: 0.5, balance: 1.5, country: "A1"}]}]}}, goals: ["vehicle.scores.share"], output: {borrower: {active: true, balance: 65, calc: {net: null}, days: -0.5, flag: true, level: "", vehicles: [{birthDate: "1990-06-15", capped: "none", limit: null, margin: 0, ok: -0.5, payments: [{balance: 50, country: "VIP", rate: 0.5}, {balance: 0.5, country: "a-b-c", rate: 2}], penalty: 0, quota: 0, scores: {share: false}, segment: 0, since: "2025-03-20T10:15:30Z", verified: true, weighted: 65}, {birthDate: "2024-02-29", capped: "none", limit: 18, margin: 0, ok: -0.5, payments: [{balance: 50, country: "VIP", rate: 2}, {balance: 1.5, country: "A1", rate: 0.5}], penalty: 0, quota: 18, scores: {share: false}, segment: 18, since: "2024-02-29", verified: true, weighted: 65}]}}}, + {input: {borrower: {days: 10, balance: 1, active: true, priority: false, vehicles: [{limit: 3, verified: false, birthDate: "2000-01-01", since: "2030-12-31", payments: [{rate: 65, balance: 1, country: "gold"}, {rate: 402, balance: 50, country: "DE"}, {rate: 250, balance: 2, country: "DE"}]}]}}, goals: ["vehicle.penalty", "grade"], output: {borrower: {active: true, balance: 1, calc: {net: null}, days: 10, flag: true, priority: false, vehicles: [{birthDate: "2000-01-01", limit: 3, payments: [{balance: 1, country: "gold", rate: 65}, {balance: 50, country: "DE", rate: 402}, {balance: 2, country: "DE", rate: 250}], penalty: 4, since: "2030-12-31", verified: false, weighted: 100}]}, grade: false}}, + {input: {borrower: {days: 100, balance: 10, active: false, priority: false, vehicles: [{limit: 50, verified: true, birthDate: "2000-01-01", since: "2025-03-20T10:15:30Z", payments: [{rate: 10, balance: 1.5, country: "DE"}, {rate: -500, balance: 2, country: "gold"}]}, {limit: 5, verified: true, birthDate: "2025-03-20", since: "1990-06-15", payments: [{rate: 0.25, balance: 250, country: "retail"}]}, {limit: 1.5, verified: false, birthDate: "2025-03-20", since: "2000-01-01", payments: [{rate: 100, balance: 1000, country: "a"}, {rate: 3, balance: 250, country: "Zed"}, {rate: 3, balance: 0.5, country: "a"}]}, {limit: 0, verified: true, birthDate: "2025-03-20", since: "2025-03-20", payments: []}, {limit: 1.5, verified: false, birthDate: "2030-12-31", since: "2000-01-01", payments: [{rate: -0.01, balance: 5, country: "DE"}]}]}}, goals: ["vehicle.scores.share", "borrower.flag", "surcharge"], output: {borrower: {active: false, balance: 10, calc: {net: null}, days: 100, flag: false, level: "", priority: false, vehicles: [{birthDate: "2000-01-01", capped: "none", limit: 50, margin: 100, ok: 100, payments: [{balance: 1.5, country: "DE", rate: 10}, {balance: 2, country: "gold", rate: -500}], penalty: null, quota: 50, scores: {share: false}, segment: 50, since: "2025-03-20T10:15:30Z", verified: true, weighted: 0.099009900990099009900990099}, {birthDate: "2025-03-20", capped: "none", limit: 5, margin: 100, ok: 100, payments: [{balance: 250, country: "retail", rate: 0.25}], penalty: null, quota: 5, scores: {share: false}, segment: 5, since: "1990-06-15", verified: true, weighted: 0.099009900990099009900990099}, {birthDate: "2025-03-20", capped: "none", limit: 1.5, margin: 3.3333333333333333333333333333, ok: 100, payments: [{balance: 1000, country: "a", rate: 100}, {balance: 250, country: "Zed", rate: 3}, {balance: 0.5, country: "a", rate: 3}], penalty: 2.5, quota: 1.5, scores: {share: false}, segment: 1.5, since: "2000-01-01", verified: false, weighted: 100}, {birthDate: "2025-03-20", capped: "none", limit: 0, margin: 100, ok: 100, payments: [], penalty: null, quota: 0, scores: {share: false}, segment: 0, since: "2025-03-20", verified: true, weighted: 0.099009900990099009900990099}, {birthDate: "2030-12-31", capped: "none", limit: 1.5, margin: 3.3333333333333333333333333333, ok: 100, payments: [{balance: 5, country: "DE", rate: -0.01}], penalty: 2.5, quota: 1.5, scores: {share: false}, segment: 1.5, since: "2000-01-01", verified: false, weighted: 100}]}, surcharge: false}}, + {input: {borrower: {days: 1e3, balance: 0, active: true, priority: false, vehicles: [{verified: true, birthDate: "2030-12-31", since: "2025-03-20", payments: []}, {verified: false, birthDate: "2024-02-29", since: "2025-03-20", payments: [{rate: 1, balance: 50, country: "3.5"}, {rate: 0, balance: 0.5, country: "VIP"}, {rate: 0, balance: 0, country: "12"}]}, {limit: 0.5, verified: null, birthDate: "2024-01-01", since: "2025-03-20", payments: [{rate: 3, balance: 5, country: "x-y"}, {rate: 1.5, balance: 2, country: "A1"}]}]}}, goals: ["borrower.calc.net", "vehicle.quota"], output: {borrower: {active: true, balance: 0, calc: {net: null}, days: 1000, flag: true, priority: false, vehicles: [{birthDate: "2030-12-31", ok: 1000, payments: [], quota: 0, segment: 0, since: "2025-03-20", verified: true}, {birthDate: "2024-02-29", ok: 1000, payments: [{balance: 50, country: "3.5", rate: 1}, {balance: 0.5, country: "VIP", rate: 0}, {balance: 0, country: "12", rate: 0}], quota: 0, segment: 0, since: "2025-03-20", verified: false}, {birthDate: "2024-01-01", limit: 0.5, ok: 1000, payments: [{balance: 5, country: "x-y", rate: 3}, {balance: 2, country: "A1", rate: 1.5}], quota: 0.5, segment: 0.5, since: "2025-03-20", verified: null}]}}}, + {input: {borrower: {days: 1000, balance: 1, active: false, priority: false, vehicles: []}}, goals: ["grade"], output: {borrower: {active: false, balance: 1, days: 1000, priority: false, vehicles: []}, grade: false}}, + ], +} + +// seed 353300 (attempt 0) +{ + name: "goals 34: borrower/companies: 1 assertion, 1 expression, 2 match, 2 table; 1 root, 5 per-member, 0 top-level computed", + policy: { + models: {borrower: {limit: "number", since: "date?", flagged: "boolean?", price: "number?", dueDate: "date?", rate: "number", companies: "company[]"}, company: {years: "number", score: "number?", income: "number?"}}, + blocks: [ + {table: "t1", inputs: ["borrower.flagged"], outputs: ["company.meta.bonus"], rules: [ + ["false", ""], + ["false", ""], + ["true", "(company.income ?? 0)"], + ["", "(company.score ?? 0)"], + ["false", "borrower.rate"], + ["", "round(company.years)"], + ]}, + {match: "company.surcharge", arms: [["(100 <= borrower.rate and borrower.since == null)", "not ((borrower.flagged ?? false))"], ["all(borrower.companies, (#.income ?? 0) <= 50)", "(company.meta.bonus ?? 0) > borrower.rate"], ["", "(company.income ?? 0) in [45..194]"]]}, + {match: "company.exposure", arms: [["((borrower.price ?? 0) % (abs(250) + 1)) < (company.income ?? 0)", "contains(`${'VIP'}/${(borrower.flagged ?? false)}`, 'A1')"], ["none(borrower.companies, not (#.surcharge))", "((borrower.flagged ?? false) and (borrower.flagged ?? false))"], ["", "company.surcharge"]]}, + {table: "t3", inputs: ["(borrower.dueDate ?? d('2025-01-01'))", "(company.meta.bonus ?? 0)"], outputs: ["company.level"], rules: [ + [">= d('2000-06-30')", "< 1", "number(string((borrower.price ?? 0)))"], + ["", "", "(company.score ?? 0)"], + ]}, + {expression: "company.tag", value: "(split((1000 == (company.level ?? 0) ? `${'A1'}/${(borrower.price ?? 0)}` : `${(company.income ?? 0)}/${company.surcharge}`), '-')[0] ?? 'none')"}, + {assertion: "borrower.review", conditions: [["and", "borrower.rate in [27..148]", 0], ["and", "borrower.dueDate != null", 0], "matches(`${borrower.rate}/${(borrower.flagged ?? false)}`, '^.{2,}$')"]}, + ], + }, + cases: [ + {input: {borrower: {limit: 10, since: null, flagged: true, price: null, dueDate: "2030-12-31", rate: 7.25, companies: []}}, goals: ["company.exposure", "company.level", "company.tag"], output: {borrower: {companies: [], dueDate: "2030-12-31", flagged: true, limit: 10, price: null, rate: 7.25, since: null}}}, + {input: {borrower: {limit: -1, flagged: null, price: 10, dueDate: "2000-01-01", rate: 7.25, companies: [{years: -500, score: 386}, {years: 1}]}}, goals: ["company.level", "company.tag"], output: {borrower: {companies: [{level: 386, meta: {bonus: 386}, score: 386, surcharge: true, tag: "0/true", years: -500}, {level: 0, meta: {bonus: 0}, surcharge: false, tag: "0/false", years: 1}], dueDate: "2000-01-01", flagged: null, limit: -1, price: 10, rate: 7.25}}}, + {input: {borrower: {limit: 123456789.123, since: "2025-03-20", flagged: true, price: 10, dueDate: "2025-03-20", rate: 18, companies: []}}, goals: ["company.meta.bonus"], output: {borrower: {companies: [], dueDate: "2025-03-20", flagged: true, limit: 123456789.123, price: 10, rate: 18, since: "2025-03-20"}}}, + {input: {borrower: {limit: 1, since: "2024-02-29", flagged: false, price: 3, dueDate: "2025-03-20", rate: 10, companies: [{years: -500, score: 1000, income: null}, {years: 0, score: null, income: null}, {years: 250, income: -0.01}, {years: 100, income: 99.99}, {years: 123456789.123}]}}, goals: ["company.meta.bonus"], output: {borrower: {companies: [{income: null, meta: {bonus: 1000}, score: 1000, years: -500}, {income: null, meta: {bonus: 0}, score: null, years: 0}, {income: -0.01, meta: {bonus: 0}, years: 250}, {income: 99.99, meta: {bonus: 0}, years: 100}, {meta: {bonus: 0}, years: 123456789.123}], dueDate: "2025-03-20", flagged: false, limit: 1, price: 3, rate: 10, since: "2024-02-29"}}}, + {input: {borrower: {limit: 100, flagged: false, rate: 1e3, companies: [{years: 250, score: 10}, {years: 1000, income: null}]}}, goals: ["company.meta.bonus", "borrower.review"], output: {borrower: {companies: [{meta: {bonus: 10}, score: 10, years: 250}, {income: null, meta: {bonus: 0}, years: 1000}], flagged: false, limit: 100, rate: 1000, review: false}}}, + {input: {borrower: {limit: -500, rate: 50, companies: [{years: -0.5, income: 50}, {years: 99.99, score: null, income: 50}]}}, goals: ["borrower.review", "company.surcharge"], output: {borrower: {companies: [{income: 50, meta: {bonus: 0}, surcharge: false, years: -0.5}, {income: 50, meta: {bonus: 0}, score: null, surcharge: false, years: 99.99}], limit: -500, rate: 50, review: false}}}, + {input: {borrower: {limit: 100, since: "2024-02-29", flagged: false, price: 367, dueDate: "2024-01-01", rate: 50, companies: [{years: 10, score: 1000000, income: 250}, {years: -0.01, score: 2.50, income: 100}, {years: 50, score: 2, income: 65}, {years: 5, score: 1, income: 18}, {years: 123456789.123, score: -500, income: 50}], extraField: 1}}, goals: ["company.surcharge", "company.exposure"], output: {borrower: {companies: [{exposure: false, income: 250, score: 1000000, surcharge: false, years: 10}, {exposure: true, income: 100, score: 2.50, surcharge: true, years: -0.01}, {exposure: true, income: 65, score: 2, surcharge: true, years: 50}, {exposure: false, income: 18, score: 1, surcharge: false, years: 5}, {exposure: true, income: 50, score: -500, surcharge: true, years: 123456789.123}], dueDate: "2024-01-01", extraField: 1, flagged: false, limit: 100, price: 367, rate: 50, since: "2024-02-29"}}}, + {input: {borrower: {limit: 65, since: null, price: null, dueDate: "1990-06-15", rate: 99999999999999999999, companies: [{years: -0.01}]}}, goals: ["company.surcharge", "company.meta.bonus", "company.exposure"], output: {borrower: {companies: [{exposure: false, meta: {bonus: 0}, surcharge: true, years: -0.01}], dueDate: "1990-06-15", limit: 65, price: null, rate: 99999999999999999999, since: null}}}, + {input: {borrower: {limit: 250, since: "2000-01-01", flagged: false, dueDate: null, rate: 99.99, companies: [{years: 1e3, score: null, income: null}, {years: 1000, score: 1e3}, {years: 100}]}}, goals: ["company.tag", "borrower.review"], output: {borrower: {companies: [{income: null, level: 0, meta: {bonus: 0}, score: null, surcharge: false, tag: "0/false", years: 1000}, {level: 1000, meta: {bonus: 1000}, score: 1000, surcharge: true, tag: "A1/0", years: 1000}, {level: 0, meta: {bonus: 0}, surcharge: false, tag: "0/false", years: 100}], dueDate: null, flagged: false, limit: 250, rate: 99.99, review: false, since: "2000-01-01"}}}, + {input: {borrower: {limit: -0, since: "2025-03-20", flagged: false, price: 100, dueDate: "2025-03-20T10:15:30Z", rate: 99999999999999999999, companies: []}}, goals: ["company.meta.bonus", "company.exposure", "company.tag"], output: {borrower: {companies: [], dueDate: "2025-03-20T10:15:30Z", flagged: false, limit: 0, price: 100, rate: 99999999999999999999, since: "2025-03-20"}}}, + {input: {borrower: {limit: 0.000001, since: "2025-03-20T10:15:30Z", flagged: false, price: 1000000, dueDate: "2024-02-29", rate: 250, companies: [{years: 18, score: 2, income: 1}, {years: 250, score: 99999999999999999999, income: -0}, {years: 100, score: 250, income: 3}, {years: 65, score: 50, income: 353}]}}, goals: ["company.surcharge"], output: {borrower: {companies: [{income: 1, score: 2, surcharge: false, years: 18}, {income: 0, score: 99999999999999999999, surcharge: false, years: 250}, {income: 3, score: 250, surcharge: false, years: 100}, {income: 353, score: 50, surcharge: false, years: 65}], dueDate: "2024-02-29", flagged: false, limit: 0.000001, price: 1000000, rate: 250, since: "2025-03-20T10:15:30Z"}}}, + {input: {borrower: {limit: 1000, since: null, price: null, rate: 1000, companies: [{years: 99999999999999999999, score: null, income: 100}, {years: 1, score: 18, income: null}, {years: 3, income: -500}, {years: -0, score: 50}]}}, goals: ["company.meta.bonus", "company.exposure", "company.level"], output: {borrower: {companies: [{exposure: false, income: 100, level: 0, meta: {bonus: 0}, score: null, surcharge: true, years: 99999999999999999999}, {exposure: false, income: null, level: 18, meta: {bonus: 18}, score: 18, surcharge: true, years: 1}, {exposure: false, income: -500, level: 0, meta: {bonus: 0}, surcharge: true, years: 3}, {exposure: false, level: 50, meta: {bonus: 50}, score: 50, surcharge: true, years: 0}], limit: 1000, price: null, rate: 1000, since: null}}}, + {input: {borrower: {limit: 250, since: "2024-01-01", flagged: false, price: 50, dueDate: "2030-12-31", rate: 65, companies: [{years: 5, score: 5, income: 50}, {years: 2, score: 1000, income: 250}, {years: 100, score: -1, income: 10}, {years: 1e3, score: 0, income: 0.1}, {years: 10, score: 65, income: 123456789.123}], extraField: 1}}, goals: ["company.surcharge"], output: {borrower: {companies: [{income: 50, score: 5, surcharge: true, years: 5}, {income: 250, score: 1000, surcharge: false, years: 2}, {income: 10, score: -1, surcharge: false, years: 100}, {income: 0.1, score: 0, surcharge: false, years: 1000}, {income: 123456789.123, score: 65, surcharge: false, years: 10}], dueDate: "2030-12-31", extraField: 1, flagged: false, limit: 250, price: 50, rate: 65, since: "2024-01-01"}}}, + {input: {borrower: {limit: 0.1, since: "2025-03-20T10:15:30Z", flagged: false, price: null, dueDate: null, rate: 50, companies: [{years: 1000000, score: null}, {years: 250, score: null}]}}, goals: ["company.surcharge", "company.level"], output: {borrower: {companies: [{level: 0, meta: {bonus: 0}, score: null, surcharge: false, years: 1000000}, {level: 0, meta: {bonus: 0}, score: null, surcharge: false, years: 250}], dueDate: null, flagged: false, limit: 0.1, price: null, rate: 50, since: "2025-03-20T10:15:30Z"}}}, + {input: {borrower: {limit: 65, since: "2025-03-20", flagged: null, price: 2, dueDate: null, rate: 123456789.123, companies: [{years: -0.5, score: 0.1}, {years: 65, income: 50}]}}, goals: ["borrower.review", "company.meta.bonus", "company.exposure"], output: {borrower: {companies: [{exposure: false, meta: {bonus: 0.1}, score: 0.1, surcharge: false, years: -0.5}, {exposure: false, income: 50, meta: {bonus: 0}, surcharge: false, years: 65}], dueDate: null, flagged: null, limit: 65, price: 2, rate: 123456789.123, review: false, since: "2025-03-20"}}}, + {input: {borrower: {limit: 7.25, since: "2024-01-01", flagged: true, price: 1e3, dueDate: "2000-01-01", rate: 0.1, companies: []}}, goals: ["company.tag"], output: {borrower: {companies: [], dueDate: "2000-01-01", flagged: true, limit: 7.25, price: 1000, rate: 0.1, since: "2024-01-01"}}}, + {input: {borrower: {limit: 0.5, since: "2025-03-20T10:15:30Z", flagged: false, price: 5, dueDate: "2030-12-31", rate: 100, companies: [{years: 0.000001, score: 1, income: 0}]}}, goals: ["company.surcharge", "company.meta.bonus", "company.tag"], output: {borrower: {companies: [{income: 0, level: 1, meta: {bonus: 1}, score: 1, surcharge: false, tag: "0/false", years: 0.000001}], dueDate: "2030-12-31", flagged: false, limit: 0.5, price: 5, rate: 100, since: "2025-03-20T10:15:30Z"}}}, + [{borrower: {limit: 50, since: "2024-01-01", flagged: false, price: 18, dueDate: "2024-02-29", rate: 0.1, companies: [{years: 0.000001, score: 234, income: 1000}]}}, {borrower: {companies: [{exposure: false, income: 1000, level: 234, meta: {bonus: 234}, score: 234, surcharge: false, tag: "1000/false", years: 0.000001}], dueDate: "2024-02-29", flagged: false, limit: 50, price: 18, rate: 0.1, review: false, since: "2024-01-01"}}], + {input: {borrower: {limit: 250, since: "2024-02-29", flagged: false, price: 100, dueDate: "1990-06-15", rate: 10, companies: []}}, goals: ["company.exposure"], output: {borrower: {companies: [], dueDate: "1990-06-15", flagged: false, limit: 250, price: 100, rate: 10, since: "2024-02-29"}}}, + [{borrower: {limit: 0.1, since: "2030-12-31", flagged: null, price: null, dueDate: "2030-12-31", rate: 100, companies: []}}, {borrower: {companies: [], dueDate: "2030-12-31", flagged: null, limit: 0.1, price: null, rate: 100, review: true, since: "2030-12-31"}}], + ], +} + +// seed 353400 (attempt 0) +{ + name: "goals 35: customer/accounts/employees: 3 expression, 2 match, 3 table; 2 root, 6 per-member, 3 top-level computed", + policy: { + models: {customer: {amount: "number?", flagged: "boolean", weight: "number", label: "string", plan: "string(basic|plus|premium|trial)", sku: "string", accounts: "acct[]"}, acct: {age: "number?", vip: "boolean", label: "string?", employees: "employee[]"}, employee: {rate: "number", insured: "boolean"}}, + blocks: [ + {expression: "acct.penalty", value: "map(acct.employees, #.rate)"}, + {match: "acct.calc.weighted", arms: [["customer.weight >= customer.weight", "customer.sku"], ["(acct.age ?? 0) != customer.weight", "`${(acct.label ?? '')}/${len(filter(acct.employees, (#.insured and #.insured)))}`"], ["", "customer.label"]]}, + {match: "customer.ok", arms: [["customer.weight >= (customer.amount ?? 0)", "customer.plan in ['trial', 'premium']"], ["", "customer.flagged"]]}, + {table: "t4", inputs: ["customer.weight"], outputs: ["acct.decision", "acct.net"], rules: [ + ["[1.5..391.5]", "not (customer.flagged)", "acct.calc.weighted"], + ["> 0.25", "customer.ok", "'none'"], + ]}, + {table: "t5", inputs: ["len(filter(acct.employees, (#.insured or #.insured)))", "(acct.decision ?? false)", null], outputs: ["acct.level", "acct.eligible"], rules: [ + ["[50..182]", "false", "customer.plan in ['plus', 'premium']", "matches((acct.net ?? ''), '^[A-Z]')", "(acct.age ?? 0)"], + ["", "true", "(customer.ok and (acct.decision ?? false))", "(acct.decision ?? false)", "(acct.age ?? 0)"], + [">= 2", "false", "100 < (acct.age ?? 0)", "customer.plan in ['plus', 'trial']", "customer.weight"], + ["!= 1", "true", "(customer.amount ?? 0) > (customer.amount ?? 0)", "customer.flagged", "(acct.age ?? 0)"], + ["< 2", "true", "customer.label == 'DE'", "not (customer.ok)", "len(acct.penalty)"], + ]}, + {table: "t6", inputs: ["customer.weight", "customer.plan"], outputs: ["grade", "adjusted"], rules: [ + ["5, 0.5", "'premium'", "customer.weight", "ceil((customer.amount ?? 0))"], + ["2, 0.25", "'trial'", "(customer.amount ?? 0)", ""], + ["[100..412]", "'plus', 'basic'", "customer.weight", "(customer.amount ?? 0)"], + ["> 5", "'premium'", "customer.weight", "50"], + [">= 2", "", "avg([customer.weight, (customer.amount ?? 0), (customer.amount ?? 0), 18])", "(min([abs((customer.amount ?? 0)), 1000]) ^ 3)"], + ["", "", "-(customer.weight)", ""], + ]}, + {expression: "customer.band", value: "((customer.ok or customer.flagged) ? grade : null)"}, + {expression: "share", value: "filter(customer.accounts, matches((#.net ?? ''), '[0-9]$'))"}, + ], + }, + cases: [ + [{customer: {amount: 50, flagged: false, weight: 1.5, label: "DE", plan: "premium", sku: "3.5", accounts: [{age: 99.99, vip: true, label: "日本", employees: [{rate: 0, insured: false}, {rate: 5, insured: true}]}, {age: -500, vip: false, label: "VIP", employees: [{rate: 18, insured: false}, {rate: 1, insured: true}]}], extraField: {nested: true}}}, {adjusted: null, customer: {accounts: [{age: 99.99, calc: {weighted: "3.5"}, decision: true, eligible: 2, employees: [{insured: false, rate: 0}, {insured: true, rate: 5}], label: "日本", level: true, net: "3.5", penalty: [0, 5], vip: true}, {age: -500, calc: {weighted: "3.5"}, decision: true, eligible: 2, employees: [{insured: false, rate: 18}, {insured: true, rate: 1}], label: "VIP", level: true, net: "3.5", penalty: [18, 1], vip: false}], amount: 50, band: null, extraField: {nested: true}, flagged: false, label: "DE", ok: false, plan: "premium", sku: "3.5", weight: 1.5}, grade: -1.5, share: [{age: 99.99, calc: {weighted: "3.5"}, decision: true, eligible: 2, employees: [{insured: false, rate: 0}, {insured: true, rate: 5}], label: "日本", level: true, net: "3.5", penalty: [0, 5], vip: true}, {age: -500, calc: {weighted: "3.5"}, decision: true, eligible: 2, employees: [{insured: false, rate: 18}, {insured: true, rate: 1}], label: "VIP", level: true, net: "3.5", penalty: [18, 1], vip: false}]}], + [{customer: {amount: 2.50, flagged: true, weight: 0.25, label: "Oslo", plan: "premium", sku: "-", accounts: [{age: 2, vip: true, label: "3.5", employees: [{rate: 0, insured: false}]}, {age: 2, vip: true, label: "abc", employees: [{rate: 5, insured: true}, {rate: 0.25, insured: false}, {rate: 1000, insured: true}]}, {age: 2, vip: false, label: null, employees: [{rate: 0.25, insured: false}]}, {age: 99.99, vip: true, label: "O'Neil", employees: [{rate: 0.000001, insured: true}, {rate: 1.5, insured: false}, {rate: 2.50, insured: true}]}]}}, {adjusted: null, customer: {accounts: [{age: 2, decision: null, eligible: null, employees: [{insured: false, rate: 0}], label: "3.5", level: null, net: null, vip: true}, {age: 2, decision: null, eligible: null, employees: [{insured: true, rate: 5}, {insured: false, rate: 0.25}, {insured: true, rate: 1000}], label: "abc", level: null, net: null, vip: true}, {age: 2, decision: null, eligible: null, employees: [{insured: false, rate: 0.25}], label: null, level: null, net: null, vip: false}, {age: 99.99, decision: null, eligible: null, employees: [{insured: true, rate: 0.000001}, {insured: false, rate: 1.5}, {insured: true, rate: 2.50}], label: "O'Neil", level: null, net: null, vip: true}], amount: 2.50, band: -0.25, flagged: true, label: "Oslo", ok: true, plan: "premium", sku: "-", weight: 0.25}, grade: -0.25, share: []}], + {input: {customer: {amount: 0, flagged: true, weight: 65, label: "x-y", plan: "premium", sku: "NL", accounts: [{age: null, vip: false, label: "", employees: [{rate: -0, insured: false}, {rate: 50, insured: true}]}, {age: null, vip: false, label: " pad ", employees: [{rate: 1, insured: true}, {rate: -500, insured: true}]}]}}, goals: ["acct.level"], output: {customer: {accounts: [{age: null, calc: {weighted: "NL"}, decision: false, eligible: null, employees: [{insured: false, rate: 0}, {insured: true, rate: 50}], label: "", level: null, net: "NL", vip: false}, {age: null, calc: {weighted: "NL"}, decision: false, eligible: null, employees: [{insured: true, rate: 1}, {insured: true, rate: -500}], label: " pad ", level: null, net: "NL", vip: false}], amount: 0, flagged: true, label: "x-y", ok: true, plan: "premium", sku: "NL", weight: 65}}}, + {input: {customer: {flagged: false, weight: 2, label: "12", plan: "premium", sku: "DE", accounts: [{vip: false, employees: []}, {age: 2.50, vip: true, label: "abc", employees: []}, {age: 0.25, vip: false, label: null, employees: [{rate: 1000, insured: true}, {rate: 18, insured: false}]}]}}, goals: ["acct.net", "acct.calc.weighted", "acct.level"], output: {customer: {accounts: [{calc: {weighted: "DE"}, decision: true, eligible: 0, employees: [], level: true, net: "DE", vip: false}, {age: 2.50, calc: {weighted: "DE"}, decision: true, eligible: 2.50, employees: [], label: "abc", level: true, net: "DE", vip: true}, {age: 0.25, calc: {weighted: "DE"}, decision: true, eligible: 0.25, employees: [{insured: true, rate: 1000}, {insured: false, rate: 18}], label: null, level: true, net: "DE", vip: false}], flagged: false, label: "12", ok: true, plan: "premium", sku: "DE", weight: 2}}}, + {input: {customer: {amount: 1000, flagged: false, weight: 0.1, label: "DE", plan: "premium", sku: "3.5", accounts: [{vip: true, label: "high", employees: [{rate: 250, insured: true}]}, {vip: true, employees: [{rate: 2, insured: false}, {rate: 0.1, insured: true}, {rate: 1000, insured: false}]}, {age: null, vip: false, label: null, employees: [{rate: 1, insured: false}, {rate: 2, insured: false}, {rate: 100, insured: true}]}, {age: null, vip: true, label: "a", employees: []}]}}, goals: ["customer.ok", "customer.band", "grade"], output: {adjusted: null, customer: {accounts: [{employees: [{insured: true, rate: 250}], label: "high", vip: true}, {employees: [{insured: false, rate: 2}, {insured: true, rate: 0.1}, {insured: false, rate: 1000}], vip: true}, {age: null, employees: [{insured: false, rate: 1}, {insured: false, rate: 2}, {insured: true, rate: 100}], label: null, vip: false}, {age: null, employees: [], label: "a", vip: true}], amount: 1000, band: null, flagged: false, label: "DE", ok: false, plan: "premium", sku: "3.5", weight: 0.1}, grade: -0.1}}, + {input: {customer: {amount: null, flagged: false, weight: -0.5, label: "a", plan: "basic", sku: "3.5", accounts: []}}, goals: ["acct.level"], output: {customer: {accounts: [], amount: null, flagged: false, label: "a", ok: false, plan: "basic", sku: "3.5", weight: -0.5}}}, + {input: {customer: {amount: null, flagged: false, weight: -0.01, label: "é ü", plan: "basic", sku: "12", accounts: [{vip: false, label: "3.5", employees: [{rate: 1000, insured: false}, {rate: 99999999999999999999, insured: false}, {rate: 18, insured: false}]}]}}, goals: ["customer.ok", "acct.net"], output: {customer: {accounts: [{decision: null, employees: [{insured: false, rate: 1000}, {insured: false, rate: 99999999999999999999}, {insured: false, rate: 18}], label: "3.5", net: null, vip: false}], amount: null, flagged: false, label: "é ü", ok: false, plan: "basic", sku: "12", weight: -0.01}}}, + {input: {customer: {amount: 2.50, flagged: true, weight: 5, label: "a", plan: "trial", sku: "a-b-c", accounts: []}}, goals: ["grade", "adjusted"], output: {adjusted: 15.625, customer: {accounts: [], amount: 2.50, flagged: true, label: "a", plan: "trial", sku: "a-b-c", weight: 5}, grade: 7.00}}, + {input: {customer: {amount: 18, flagged: false, weight: 5, label: "", plan: "premium", sku: "abc", accounts: []}}, goals: ["customer.ok"], output: {customer: {accounts: [], amount: 18, flagged: false, label: "", ok: false, plan: "premium", sku: "abc", weight: 5}}}, + {input: {customer: {amount: -0, flagged: true, weight: 0.5, label: "Zed", plan: "trial", sku: "é ü", accounts: [{age: null, vip: false, employees: [{rate: 0.25, insured: true}]}, {vip: false, label: "Oslo", employees: [{rate: 50, insured: false}, {rate: 100, insured: true}]}, {age: 1000, vip: false, employees: [{rate: -0, insured: true}, {rate: 18, insured: false}, {rate: 0.1, insured: false}]}, {vip: true, label: "日本", employees: [{rate: 2, insured: true}, {rate: 5, insured: true}]}, {age: 1.5, vip: false, label: null, employees: [{rate: 1000, insured: false}, {rate: 0, insured: true}]}]}}, goals: ["share", "acct.level"], output: {customer: {accounts: [{age: null, decision: true, eligible: 0, employees: [{insured: true, rate: 0.25}], level: true, net: "none", vip: false}, {decision: true, eligible: 0, employees: [{insured: false, rate: 50}, {insured: true, rate: 100}], label: "Oslo", level: true, net: "none", vip: false}, {age: 1000, decision: true, eligible: 1000, employees: [{insured: true, rate: 0}, {insured: false, rate: 18}, {insured: false, rate: 0.1}], level: true, net: "none", vip: false}, {decision: true, eligible: 0, employees: [{insured: true, rate: 2}, {insured: true, rate: 5}], label: "日本", level: true, net: "none", vip: true}, {age: 1.5, decision: true, eligible: 1.5, employees: [{insured: false, rate: 1000}, {insured: true, rate: 0}], label: null, level: true, net: "none", vip: false}], amount: 0, flagged: true, label: "Zed", ok: true, plan: "trial", sku: "é ü", weight: 0.5}, share: []}}, + {input: {customer: {amount: null, flagged: true, weight: -0, label: "12", plan: "plus", sku: "none", accounts: [{age: 1.5, vip: true, employees: []}]}}, goals: ["acct.penalty", "customer.band"], output: {adjusted: null, customer: {accounts: [{age: 1.5, employees: [], penalty: [], vip: true}], amount: null, band: -0, flagged: true, label: "12", ok: false, plan: "plus", sku: "none", weight: 0}, grade: -0}}, + {input: {customer: {amount: 2, flagged: false, weight: 0.25, label: "abc", plan: "premium", sku: "abc", accounts: [{age: 1000000, vip: false, label: "Oslo", employees: []}, {age: 1000, vip: true, label: "gold", employees: [{rate: 2, insured: true}]}, {age: 65, vip: true, label: "日本", employees: [{rate: 0, insured: false}]}, {age: 1, vip: true, label: "Oslo", employees: [{rate: -0.5, insured: false}, {rate: 0.1, insured: true}]}, {age: 2, vip: false, label: "A1", employees: []}], extraField: "x"}}, goals: ["acct.calc.weighted", "adjusted", "acct.eligible"], output: {adjusted: null, customer: {accounts: [{age: 1000000, calc: {weighted: "abc"}, decision: null, eligible: null, employees: [], label: "Oslo", level: null, net: null, vip: false}, {age: 1000, calc: {weighted: "abc"}, decision: null, eligible: null, employees: [{insured: true, rate: 2}], label: "gold", level: null, net: null, vip: true}, {age: 65, calc: {weighted: "abc"}, decision: null, eligible: null, employees: [{insured: false, rate: 0}], label: "日本", level: null, net: null, vip: true}, {age: 1, calc: {weighted: "abc"}, decision: null, eligible: null, employees: [{insured: false, rate: -0.5}, {insured: true, rate: 0.1}], label: "Oslo", level: null, net: null, vip: true}, {age: 2, calc: {weighted: "abc"}, decision: null, eligible: null, employees: [], label: "A1", level: null, net: null, vip: false}], amount: 2, extraField: "x", flagged: false, label: "abc", ok: false, plan: "premium", sku: "abc", weight: 0.25}, grade: -0.25}}, + {input: {customer: {amount: 123456789.123, flagged: false, weight: 0.25, label: "x-y", plan: "basic", sku: "none", accounts: []}}, goals: ["acct.decision", "customer.band"], output: {adjusted: null, customer: {accounts: [], amount: 123456789.123, band: null, flagged: false, label: "x-y", ok: false, plan: "basic", sku: "none", weight: 0.25}, grade: -0.25}}, + {input: {customer: {amount: 0.5, flagged: true, weight: 1.5, label: "12", plan: "premium", sku: "日本", accounts: [{age: 0, vip: false, label: "12", employees: []}, {age: 100, vip: false, label: "Oslo", employees: [{rate: 0, insured: true}, {rate: 0, insured: false}, {rate: -0, insured: true}]}, {age: 100, vip: false, label: "3.5", employees: [{rate: 99999999999999999999, insured: false}, {rate: 50, insured: false}]}, {age: 2, vip: true, label: "12", employees: []}], extraField: "x"}}, goals: ["acct.eligible", "acct.decision"], output: {customer: {accounts: [{age: 0, calc: {weighted: "日本"}, decision: false, eligible: null, employees: [], label: "12", level: null, net: "日本", vip: false}, {age: 100, calc: {weighted: "日本"}, decision: false, eligible: null, employees: [{insured: true, rate: 0}, {insured: false, rate: 0}, {insured: true, rate: 0}], label: "Oslo", level: null, net: "日本", vip: false}, {age: 100, calc: {weighted: "日本"}, decision: false, eligible: null, employees: [{insured: false, rate: 99999999999999999999}, {insured: false, rate: 50}], label: "3.5", level: null, net: "日本", vip: false}, {age: 2, calc: {weighted: "日本"}, decision: false, eligible: null, employees: [], label: "12", level: null, net: "日本", vip: true}], amount: 0.5, extraField: "x", flagged: true, label: "12", ok: true, plan: "premium", sku: "日本", weight: 1.5}}}, + [{customer: {amount: 1e3, flagged: true, weight: 100, label: "Oslo", plan: "basic", sku: "-", accounts: [{age: 1.5, vip: true, label: "é ü", employees: []}]}}, {adjusted: 1000, customer: {accounts: [{age: 1.5, calc: {weighted: "-"}, decision: false, eligible: null, employees: [], label: "é ü", level: null, net: "-", vip: true}], amount: 1000, band: 100, flagged: true, label: "Oslo", ok: true, plan: "basic", sku: "-", weight: 100}, grade: 100, share: []}], + {input: {customer: {flagged: true, weight: 100, label: "DE", plan: "plus", sku: "none", accounts: [{vip: false, label: "Oslo", employees: []}, {age: 99999999999999999999, vip: false, label: null, employees: [{rate: 3, insured: false}]}]}}, goals: ["customer.ok", "adjusted", "customer.band"], output: {adjusted: 0, customer: {accounts: [{employees: [], label: "Oslo", vip: false}, {age: 99999999999999999999, employees: [{insured: false, rate: 3}], label: null, vip: false}], band: 100, flagged: true, label: "DE", ok: false, plan: "plus", sku: "none", weight: 100}, grade: 100}}, + {input: {customer: {amount: -0.5, flagged: false, weight: -500, label: "retail", plan: "premium", sku: "high", accounts: [{age: -0.5, vip: false, label: "3.5", employees: [{rate: 2, insured: true}]}]}}, goals: ["customer.band"], output: {adjusted: null, customer: {accounts: [{age: -0.5, employees: [{insured: true, rate: 2}], label: "3.5", vip: false}], amount: -0.5, band: null, flagged: false, label: "retail", ok: false, plan: "premium", sku: "high", weight: -500}, grade: 500}}, + {input: {customer: {amount: 1.5, flagged: true, weight: 250, label: "", plan: "basic", sku: "Zed", accounts: [{age: 0, vip: true, label: "é ü", employees: []}, {age: 0, vip: false, label: "Oslo", employees: [{rate: 18, insured: false}, {rate: 2.50, insured: false}]}]}}, goals: ["acct.decision"], output: {customer: {accounts: [{age: 0, calc: {weighted: "Zed"}, decision: false, employees: [], label: "é ü", net: "Zed", vip: true}, {age: 0, calc: {weighted: "Zed"}, decision: false, employees: [{insured: false, rate: 18}, {insured: false, rate: 2.50}], label: "Oslo", net: "Zed", vip: false}], amount: 1.5, flagged: true, label: "", plan: "basic", sku: "Zed", weight: 250}}}, + {input: {customer: {amount: 1, flagged: true, weight: -0.5, label: "O'Neil", plan: "trial", sku: " pad ", accounts: [{age: 100, vip: null, label: "NL", employees: [{rate: 0, insured: true}]}, {age: 250, vip: false, label: "Oslo", employees: [{rate: -0.01, insured: true}, {rate: 99999999999999999999, insured: true}, {rate: 18, insured: false}]}, {age: 0, vip: true, label: "abc", employees: [{rate: 0, insured: false}]}, {age: 5, vip: true, label: "x-y", employees: [{rate: 2, insured: true}]}, {age: 0.25, vip: false, label: "US", employees: [{rate: -0, insured: false}]}]}}, goals: ["customer.band", "grade"], output: {adjusted: null, customer: {accounts: [{age: 100, employees: [{insured: true, rate: 0}], label: "NL", vip: null}, {age: 250, employees: [{insured: true, rate: -0.01}, {insured: true, rate: 99999999999999999999}, {insured: false, rate: 18}], label: "Oslo", vip: false}, {age: 0, employees: [{insured: false, rate: 0}], label: "abc", vip: true}, {age: 5, employees: [{insured: true, rate: 2}], label: "x-y", vip: true}, {age: 0.25, employees: [{insured: false, rate: 0}], label: "US", vip: false}], amount: 1, band: 0.5, flagged: true, label: "O'Neil", ok: true, plan: "trial", sku: " pad ", weight: -0.5}, grade: 0.5}}, + [{customer: {amount: 1, weight: 1.5, label: "12", plan: "premium", sku: "retail", accounts: [{age: 100, vip: true, label: "x-y", employees: [{rate: 2, insured: true}, {rate: 0.25, insured: false}]}, {age: 144, vip: true, label: "12", employees: [{rate: -0.01, insured: false}, {rate: 1, insured: false}]}, {age: 5, vip: true, label: "", employees: [{rate: 18, insured: false}, {rate: 18, insured: false}]}, {age: 7.25, vip: true, label: "-", employees: [{rate: 18, insured: true}]}]}}, "!error: MissingRequiredInputs"], + {input: {customer: {amount: null, flagged: false, weight: 3, label: "DE", plan: "basic", sku: "-", accounts: [{age: 5, vip: false, label: null, employees: [{rate: 1.5, insured: false}, {rate: 0.5, insured: true}]}, {age: null, vip: false, label: "low", employees: [{rate: 5, insured: true}, {rate: 2, insured: false}, {rate: -0, insured: true}]}]}}, goals: ["grade", "share"], output: {adjusted: 0, customer: {accounts: [{age: 5, calc: {weighted: "-"}, decision: true, employees: [{insured: false, rate: 1.5}, {insured: true, rate: 0.5}], label: null, net: "-", vip: false}, {age: null, calc: {weighted: "-"}, decision: true, employees: [{insured: true, rate: 5}, {insured: false, rate: 2}, {insured: true, rate: 0}], label: "low", net: "-", vip: false}], amount: null, flagged: false, label: "DE", plan: "basic", sku: "-", weight: 3}, grade: 5.25, share: []}}, + {input: {customer: {amount: 100, flagged: true, weight: 3, label: "A1", plan: "basic", sku: "low", accounts: []}}, goals: ["share", "acct.penalty"], output: {customer: {accounts: [], amount: 100, flagged: true, label: "A1", plan: "basic", sku: "low", weight: 3}, share: []}}, + {input: {customer: {amount: 2, flagged: false, weight: 1000, label: "abc", plan: "basic", sku: "-", accounts: []}}, goals: ["grade", "acct.decision", "acct.eligible"], output: {adjusted: 8, customer: {accounts: [], amount: 2, flagged: false, label: "abc", ok: false, plan: "basic", sku: "-", weight: 1000}, grade: 255.50}}, + {input: {customer: {amount: null, flagged: true, weight: 1.5, label: "Zed", plan: "premium", sku: "VIP", accounts: [{vip: true, employees: []}, {vip: true, label: "Oslo", employees: []}, {age: 99999999999999999999, vip: false, employees: []}, {vip: true, label: " pad ", employees: [{rate: 2, insured: true}, {rate: 2.50, insured: true}]}, {age: null, vip: true, label: "日本", employees: [{rate: 18, insured: false}, {rate: 1.5, insured: true}, {rate: 50, insured: false}]}, {age: null, vip: false, employees: [{rate: 0.1, insured: true}, {rate: 250, insured: false}, {rate: 1000, insured: false}]}, {vip: true, label: "abc", employees: [{rate: 0.1, insured: true}, {rate: 1e3, insured: false}]}, {age: 5, vip: true, label: null, employees: []}, {age: 0.25, vip: true, employees: []}, {age: 0.25, vip: false, label: null, employees: [{rate: 99999999999999999999, insured: true}, {rate: 0, insured: true}]}, {vip: true, label: "x-y", employees: [{rate: 50, insured: true}, {rate: 5, insured: true}]}]}}, goals: ["acct.eligible"], output: {customer: {accounts: [{calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [], level: null, net: "VIP", vip: true}, {calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [], label: "Oslo", level: null, net: "VIP", vip: true}, {age: 99999999999999999999, calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [], level: null, net: "VIP", vip: false}, {calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [{insured: true, rate: 2}, {insured: true, rate: 2.50}], label: " pad ", level: null, net: "VIP", vip: true}, {age: null, calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [{insured: false, rate: 18}, {insured: true, rate: 1.5}, {insured: false, rate: 50}], label: "日本", level: null, net: "VIP", vip: true}, {age: null, calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [{insured: true, rate: 0.1}, {insured: false, rate: 250}, {insured: false, rate: 1000}], level: null, net: "VIP", vip: false}, {calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [{insured: true, rate: 0.1}, {insured: false, rate: 1000}], label: "abc", level: null, net: "VIP", vip: true}, {age: 5, calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [], label: null, level: null, net: "VIP", vip: true}, {age: 0.25, calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [], level: null, net: "VIP", vip: true}, {age: 0.25, calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [{insured: true, rate: 99999999999999999999}, {insured: true, rate: 0}], label: null, level: null, net: "VIP", vip: false}, {calc: {weighted: "VIP"}, decision: false, eligible: null, employees: [{insured: true, rate: 50}, {insured: true, rate: 5}], label: "x-y", level: null, net: "VIP", vip: true}], amount: null, flagged: true, label: "Zed", ok: true, plan: "premium", sku: "VIP", weight: 1.5}}}, + {input: {customer: {flagged: true, weight: 223, label: "high", plan: "plus", sku: "a-b-c", accounts: [{vip: true, label: null, employees: []}, {age: 2, vip: false, employees: [{rate: 50, insured: true}]}]}}, goals: ["acct.net", "acct.decision"], output: {customer: {accounts: [{calc: {weighted: "a-b-c"}, decision: false, employees: [], label: null, net: "a-b-c", vip: true}, {age: 2, calc: {weighted: "a-b-c"}, decision: false, employees: [{insured: true, rate: 50}], net: "a-b-c", vip: false}], flagged: true, label: "high", plan: "plus", sku: "a-b-c", weight: 223}}}, + [{customer: {amount: 0.5, flagged: true, weight: 0.000001, label: " pad ", plan: "basic", sku: "3.5", accounts: []}}, {adjusted: null, customer: {accounts: [], amount: 0.5, band: -0.000001, flagged: true, label: " pad ", ok: true, plan: "basic", sku: "3.5", weight: 0.000001}, grade: -0.000001, share: []}], + {input: {customer: {amount: 50, flagged: false, weight: -1, label: "12", plan: "premium", sku: "Oslo", accounts: [{age: 3, vip: true, employees: [{rate: 2, insured: false}, {rate: 2, insured: false}]}, {age: 50, vip: false, label: "O'Neil", employees: []}, {vip: false, employees: [{rate: 0.25, insured: false}, {rate: -0.5, insured: true}]}, {age: 0, vip: false, label: null, employees: [{rate: 99999999999999999999, insured: false}]}, {age: 100, vip: true, label: null, employees: [{rate: -1, insured: false}, {rate: 0, insured: false}, {rate: -500, insured: false}]}]}}, goals: ["share"], output: {customer: {accounts: [{age: 3, decision: null, employees: [{insured: false, rate: 2}, {insured: false, rate: 2}], net: null, vip: true}, {age: 50, decision: null, employees: [], label: "O'Neil", net: null, vip: false}, {decision: null, employees: [{insured: false, rate: 0.25}, {insured: true, rate: -0.5}], net: null, vip: false}, {age: 0, decision: null, employees: [{insured: false, rate: 99999999999999999999}], label: null, net: null, vip: false}, {age: 100, decision: null, employees: [{insured: false, rate: -1}, {insured: false, rate: 0}, {insured: false, rate: -500}], label: null, net: null, vip: true}], amount: 50, flagged: false, label: "12", plan: "premium", sku: "Oslo", weight: -1}, share: []}}, + [{customer: {amount: 0, flagged: false, weight: 1.5, label: "日本", plan: "plus", sku: "3.5", accounts: [{age: 5, vip: false, label: "abc", employees: [{rate: 18, insured: false}]}, {age: 2, vip: true, label: "gold", employees: [{rate: 100, insured: false}]}]}}, {adjusted: null, customer: {accounts: [{age: 5, calc: {weighted: "3.5"}, decision: true, eligible: null, employees: [{insured: false, rate: 18}], label: "abc", level: null, net: "3.5", vip: false}, {age: 2, calc: {weighted: "3.5"}, decision: true, eligible: null, employees: [{insured: false, rate: 100}], label: "gold", level: null, net: "3.5", vip: true}], amount: 0, band: null, flagged: false, label: "日本", ok: false, plan: "plus", sku: "3.5", weight: 1.5}, grade: -1.5, share: [{age: 5, calc: {weighted: "3.5"}, decision: true, eligible: null, employees: [{insured: false, rate: 18}], label: "abc", level: null, net: "3.5", vip: false}, {age: 2, calc: {weighted: "3.5"}, decision: true, eligible: null, employees: [{insured: false, rate: 100}], label: "gold", level: null, net: "3.5", vip: true}]}], + [{customer: {amount: 5, flagged: true, weight: -0.5, label: "", plan: "trial", sku: "Oslo", accounts: [{age: 18, vip: false, label: "é ü", employees: [{rate: 0.25, insured: true}, {rate: 1000000, insured: true}]}, {age: 65, vip: true, label: "Oslo", employees: [{rate: 18, insured: false}, {rate: 2, insured: false}]}]}}, {adjusted: null, customer: {accounts: [{age: 18, decision: null, eligible: null, employees: [{insured: true, rate: 0.25}, {insured: true, rate: 1000000}], label: "é ü", level: null, net: null, vip: false}, {age: 65, decision: null, eligible: null, employees: [{insured: false, rate: 18}, {insured: false, rate: 2}], label: "Oslo", level: null, net: null, vip: true}], amount: 5, band: 0.5, flagged: true, label: "", ok: true, plan: "trial", sku: "Oslo", weight: -0.5}, grade: 0.5, share: []}], + ], +} + +// seed 353500 (attempt 0) +{ + name: "goals 36: shipment/vehicles + profile: 3 expression, 3 match, 3 table; 1 root, 7 per-member, 0 top-level computed", + policy: { + models: {shipment: {days: "number", label: "string", priority: "boolean", plan: "string(basic|plus|premium|trial)?", country: "string", vehicles: "vehicle[]", profile: "profile?"}, vehicle: {price: "number?", dueDate: "date", since: "date", score: "number"}, profile: {amount: "number"}}, + blocks: [ + {expression: "profile.rank", value: "filter(shipment.vehicles, ((1.5 <= 1.5 or #.score <= 3) or ((#.price ?? 0) > 100 or #.score <= 2)))"}, + {match: "shipment.exposure", arms: [["not (matches(shipment.country, '[0-9]$'))", "shipment.days"], ["shipment.plan != null", "(shipment.profile.amount ?? 0)"], ["", "(250 + shipment.days)"]]}, + {table: "t3", hit: "collect", inputs: ["shipment.days", "(vehicle.score - shipment.exposure)", null], outputs: ["vehicle.grade", "vehicle.tag"], rules: [ + ["> 1000", "0.5, 0", "shipment.days != (vehicle.price ?? 0)", "shipment.label", ""], + ["0", ">= 0", "vehicle.dueDate >= d('2025-01-01')", "shipment.country", "matches(shipment.country, '^.{2,}$')"], + ["", "!= 5", "(shipment.plan ?? '') in ['premium', 'basic']", "shipment.label", ""], + ["", "", "", "string(shipment.priority)", "shipment.priority"], + ]}, + {table: "t4", inputs: [null, "vehicle.price"], outputs: ["vehicle.bonus"], rules: [ + ["not (shipment.priority)", "18", "shipment.country"], + ["(shipment.priority and shipment.priority)", "50", "shipment.country"], + ]}, + {table: "t5", inputs: ["profile.amount"], outputs: ["profile.scores.quota", "profile.health"], rules: [ + ["> 1.5", "shipment.exposure", "avg([shipment.exposure, profile.amount])"], + ["5", "profile.amount", "shipment.days"], + [">= 1000", "", ""], + ]}, + {match: "vehicle.meta.points", arms: [["none(shipment.vehicles, #.score < (#.price ?? 0))", "string(not (shipment.priority))"], ["contains(['none', 'retail', ''], shipment.label)", "'VIP'"], ["shipment.profile.scores.quota != null", "(vehicle.bonus ?? '')"], ["", "shipment.label"]]}, + {expression: "vehicle.meta.decision", value: "{v: shipment.priority, a: (shipment.exposure - (shipment.profile.amount ?? 0))}"}, + {expression: "profile.capped", value: "sum(map(profile.rank, (#.price ?? 0)))"}, + {match: "profile.segment", arms: [["(shipment.country != 'retail' or matches(shipment.label, '^[A-Z]'))", "shipment.label"], ["((shipment.priority or shipment.priority) or matches(shipment.label, '^.{2,}$'))", "(shipment.priority ? shipment.country : shipment.label)"], ["contains(['Oslo', 'none', ''], shipment.country)", "shipment.label"], ["", "`${10}/${shipment.priority}`"]]}, + ], + }, + cases: [ + {input: {shipment: {days: 5, label: "é ü", priority: false, plan: "premium", country: "3.5", vehicles: [{price: 123456789.123, dueDate: "2025-03-20T10:15:30Z", since: "not a date", score: 7.25}, {price: 1000, dueDate: "1990-06-15", since: "2025-03-20", score: 0.5}, {price: 5, dueDate: "1990-06-15", since: "2024-01-01", score: 50}], profile: {amount: 0.000001}}}, goals: ["vehicle.bonus"], output: "!error: InputValidationFailed"}, + {input: {shipment: {days: 1, label: "Oslo", priority: false, plan: null, country: "a-b-c", vehicles: [{price: null, dueDate: "2000-01-01", since: "1990-06-15", score: 100}, {price: 10, dueDate: "2024-02-29", since: "2025-03-20", score: 18}, {price: 1e3, dueDate: "2000-01-01", since: "2025-03-20T10:15:30Z", score: -0.01}, {price: 2.50, dueDate: "1990-06-15", since: "2000-01-01", score: 50}, {price: 0, dueDate: "1990-06-15", since: "2024-02-29", score: 18}], profile: null}}, goals: ["profile.scores.quota"], output: {shipment: {country: "a-b-c", days: 1, label: "Oslo", plan: null, priority: false, profile: null, vehicles: [{dueDate: "2000-01-01", price: null, score: 100, since: "1990-06-15"}, {dueDate: "2024-02-29", price: 10, score: 18, since: "2025-03-20"}, {dueDate: "2000-01-01", price: 1000, score: -0.01, since: "2025-03-20T10:15:30Z"}, {dueDate: "1990-06-15", price: 2.50, score: 50, since: "2000-01-01"}, {dueDate: "1990-06-15", price: 0, score: 18, since: "2024-02-29"}]}}}, + {input: {shipment: {days: 1000, label: "NL", priority: true, country: "Oslo", vehicles: [{price: 18, dueDate: "2030-12-31", since: "2025-03-20T10:15:30Z", score: 123456789.123}], profile: {amount: 0}}}, goals: ["vehicle.meta.decision", "vehicle.tag"], output: {shipment: {country: "Oslo", days: 1000, exposure: 1000, label: "NL", priority: true, profile: {amount: 0}, vehicles: [{dueDate: "2030-12-31", grade: ["true"], meta: {decision: {a: 1000, v: true}}, price: 18, score: 123456789.123, since: "2025-03-20T10:15:30Z", tag: [true]}]}}}, + [{shipment: {days: 1000, label: "retail", priority: true, plan: "plus", vehicles: [{price: 5, dueDate: "2024-02-29", since: "2000-01-01", score: 5}], profile: {amount: 5}}}, "!error: MissingRequiredInputs"], + {input: {shipment: {days: 5, label: "retail", priority: false, plan: null, country: "Oslo", vehicles: [{dueDate: "2025-03-20", since: "2030-12-31", score: 250}], profile: null}}, goals: ["profile.capped", "vehicle.meta.decision", "vehicle.meta.points"], output: {shipment: {country: "Oslo", days: 5, exposure: 5, label: "retail", plan: null, priority: false, profile: null, vehicles: [{dueDate: "2025-03-20", meta: {decision: {a: 5, v: false}, points: "true"}, score: 250, since: "2030-12-31"}]}}}, + {input: {shipment: {days: 1.5, label: "DE", priority: true, plan: "basic", country: "12", vehicles: [{price: 0, dueDate: "2025-03-20", since: "1990-06-15", score: 18}, {price: 0.1, dueDate: "2024-01-01", since: "2025-03-20", score: 10}, {price: -0.01, dueDate: "1990-06-15", since: "2024-01-01", score: 1.5}, {price: 1, dueDate: "2025-03-20T10:15:30Z", since: "2024-01-01", score: 1.5}, {price: 123456789.123, dueDate: "1990-06-15", since: "2000-01-01", score: 0}], profile: {amount: 5}}}, goals: ["vehicle.tag", "profile.rank"], output: {shipment: {country: "12", days: 1.5, exposure: 5, label: "DE", plan: "basic", priority: true, profile: {amount: 5, rank: [{dueDate: "2025-03-20", grade: ["DE", "true"], price: 0, score: 18, since: "1990-06-15", tag: [true]}, {dueDate: "2024-01-01", grade: ["true"], price: 0.1, score: 10, since: "2025-03-20", tag: [true]}, {dueDate: "1990-06-15", grade: ["DE", "true"], price: -0.01, score: 1.5, since: "2024-01-01", tag: [true]}, {dueDate: "2025-03-20T10:15:30Z", grade: ["DE", "true"], price: 1, score: 1.5, since: "2024-01-01", tag: [true]}, {dueDate: "1990-06-15", grade: ["DE", "true"], price: 123456789.123, score: 0, since: "2000-01-01", tag: [true]}]}, vehicles: [{dueDate: "2025-03-20", grade: ["DE", "true"], price: 0, score: 18, since: "1990-06-15", tag: [true]}, {dueDate: "2024-01-01", grade: ["true"], price: 0.1, score: 10, since: "2025-03-20", tag: [true]}, {dueDate: "1990-06-15", grade: ["DE", "true"], price: -0.01, score: 1.5, since: "2024-01-01", tag: [true]}, {dueDate: "2025-03-20T10:15:30Z", grade: ["DE", "true"], price: 1, score: 1.5, since: "2024-01-01", tag: [true]}, {dueDate: "1990-06-15", grade: ["DE", "true"], price: 123456789.123, score: 0, since: "2000-01-01", tag: [true]}]}}}, + {input: {shipment: {days: -0.5, label: "retail", priority: false, country: "VIP", vehicles: [{price: 2, dueDate: "2030-12-31", since: "2030-12-31", score: 1.5}, {dueDate: "2024-01-01", since: "2025-03-20", score: 3}], profile: {amount: 10}}}, goals: ["vehicle.grade"], output: {shipment: {country: "VIP", days: -0.5, exposure: -0.5, label: "retail", priority: false, profile: {amount: 10}, vehicles: [{dueDate: "2030-12-31", grade: ["false"], price: 2, score: 1.5, since: "2030-12-31", tag: [false]}, {dueDate: "2024-01-01", grade: ["false"], score: 3, since: "2025-03-20", tag: [false]}]}}}, + {input: {shipment: {days: 7.25, label: "3.5", priority: false, plan: "basic", country: "gold", vehicles: [{price: 250, dueDate: "2024-01-01", since: "2024-01-01", score: 100}, {price: 1.5, dueDate: "1990-06-15", since: "2024-02-29", score: 2.50}, {price: 18, dueDate: "2024-02-29", since: "2024-01-01", score: 5}, {price: 2, dueDate: "2024-01-01", since: "2000-01-01", score: 5}, {price: 1.5, dueDate: "2030-12-31", since: "2025-03-20", score: 5}], profile: {amount: 18}}}, goals: ["profile.health", "profile.rank"], output: {shipment: {country: "gold", days: 7.25, exposure: 7.25, label: "3.5", plan: "basic", priority: false, profile: {amount: 18, health: 12.6250, rank: [{dueDate: "2024-01-01", price: 250, score: 100, since: "2024-01-01"}, {dueDate: "1990-06-15", price: 1.5, score: 2.50, since: "2024-02-29"}, {dueDate: "2024-02-29", price: 18, score: 5, since: "2024-01-01"}, {dueDate: "2024-01-01", price: 2, score: 5, since: "2000-01-01"}, {dueDate: "2030-12-31", price: 1.5, score: 5, since: "2025-03-20"}], scores: {quota: 7.25}}, vehicles: [{dueDate: "2024-01-01", price: 250, score: 100, since: "2024-01-01"}, {dueDate: "1990-06-15", price: 1.5, score: 2.50, since: "2024-02-29"}, {dueDate: "2024-02-29", price: 18, score: 5, since: "2024-01-01"}, {dueDate: "2024-01-01", price: 2, score: 5, since: "2000-01-01"}, {dueDate: "2030-12-31", price: 1.5, score: 5, since: "2025-03-20"}]}}}, + [{shipment: {days: 100, label: "VIP", priority: true, plan: "basic", country: "DE", vehicles: [{price: -0.01, dueDate: "2024-01-01", since: "2024-01-01", score: 1000}, {dueDate: "2025-03-20T10:15:30Z", since: "2024-02-29", score: 0}], profile: {amount: 1.5}}}, {shipment: {country: "DE", days: 100, exposure: 100, label: "VIP", plan: "basic", priority: true, profile: {amount: 1.5, capped: -0.01, health: null, rank: [{dueDate: "2024-01-01", grade: ["VIP", "true"], meta: {decision: {a: 98.5, v: true}, points: "false"}, price: -0.01, score: 1000, since: "2024-01-01", tag: [true]}, {dueDate: "2025-03-20T10:15:30Z", grade: ["VIP", "true"], meta: {decision: {a: 98.5, v: true}, points: "false"}, score: 0, since: "2024-02-29", tag: [true]}], scores: {quota: null}, segment: "VIP"}, vehicles: [{dueDate: "2024-01-01", grade: ["VIP", "true"], meta: {decision: {a: 98.5, v: true}, points: "false"}, price: -0.01, score: 1000, since: "2024-01-01", tag: [true]}, {dueDate: "2025-03-20T10:15:30Z", grade: ["VIP", "true"], meta: {decision: {a: 98.5, v: true}, points: "false"}, score: 0, since: "2024-02-29", tag: [true]}]}}], + [{shipment: {days: 250, label: " pad ", priority: false, plan: "premium", country: "Oslo", vehicles: [{price: -500, dueDate: "2030-12-31", since: "2030-12-31", score: 0.5}, {price: 18, dueDate: "1990-06-15", since: "2025-03-20", score: 0}, {price: 0.000001, dueDate: "2024-01-01", since: "2000-01-01", score: 1}, {price: 1000000, dueDate: "2000-01-01", since: "2024-02-29", score: 100}], profile: {amount: 5}}}, {shipment: {country: "Oslo", days: 250, exposure: 250, label: " pad ", plan: "premium", priority: false, profile: {amount: 5, capped: 999518.000001, health: 127.50, rank: [{bonus: null, dueDate: "2030-12-31", grade: [" pad ", "false"], meta: {decision: {a: 245, v: false}, points: ""}, price: -500, score: 0.5, since: "2030-12-31", tag: [false]}, {bonus: "Oslo", dueDate: "1990-06-15", grade: [" pad ", "false"], meta: {decision: {a: 245, v: false}, points: "Oslo"}, price: 18, score: 0, since: "2025-03-20", tag: [false]}, {bonus: null, dueDate: "2024-01-01", grade: [" pad ", "false"], meta: {decision: {a: 245, v: false}, points: ""}, price: 0.000001, score: 1, since: "2000-01-01", tag: [false]}, {bonus: null, dueDate: "2000-01-01", grade: [" pad ", "false"], meta: {decision: {a: 245, v: false}, points: ""}, price: 1000000, score: 100, since: "2024-02-29", tag: [false]}], scores: {quota: 250}, segment: " pad "}, vehicles: [{bonus: null, dueDate: "2030-12-31", grade: [" pad ", "false"], meta: {decision: {a: 245, v: false}, points: ""}, price: -500, score: 0.5, since: "2030-12-31", tag: [false]}, {bonus: "Oslo", dueDate: "1990-06-15", grade: [" pad ", "false"], meta: {decision: {a: 245, v: false}, points: "Oslo"}, price: 18, score: 0, since: "2025-03-20", tag: [false]}, {bonus: null, dueDate: "2024-01-01", grade: [" pad ", "false"], meta: {decision: {a: 245, v: false}, points: ""}, price: 0.000001, score: 1, since: "2000-01-01", tag: [false]}, {bonus: null, dueDate: "2000-01-01", grade: [" pad ", "false"], meta: {decision: {a: 245, v: false}, points: ""}, price: 1000000, score: 100, since: "2024-02-29", tag: [false]}]}}], + {input: {shipment: {days: 5, label: "A1", priority: true, country: "abc", vehicles: [{price: -0.01, dueDate: "2025-03-20T10:15:30Z", since: "2025-03-20", score: 1.5}]}}, goals: ["vehicle.grade"], output: {shipment: {country: "abc", days: 5, exposure: 5, label: "A1", priority: true, vehicles: [{dueDate: "2025-03-20T10:15:30Z", grade: ["true"], price: -0.01, score: 1.5, since: "2025-03-20", tag: [true]}]}}}, + {input: {shipment: {days: -0.5, label: "Oslo", priority: false, plan: "premium", country: "none", vehicles: [{price: 0, dueDate: "2025-03-20T10:15:30Z", since: "2025-03-20T10:15:30Z", score: 5}], profile: {amount: 250}}}, goals: ["profile.rank", "profile.scores.quota"], output: {shipment: {country: "none", days: -0.5, exposure: -0.5, label: "Oslo", plan: "premium", priority: false, profile: {amount: 250, health: 124.750, rank: [{dueDate: "2025-03-20T10:15:30Z", price: 0, score: 5, since: "2025-03-20T10:15:30Z"}], scores: {quota: -0.5}}, vehicles: [{dueDate: "2025-03-20T10:15:30Z", price: 0, score: 5, since: "2025-03-20T10:15:30Z"}]}}}, + {input: {shipment: {days: 5, label: "VIP", priority: true, plan: "plus", country: "a", vehicles: [{price: 18, dueDate: "2025-03-20T10:15:30Z", since: "2025-03-20T10:15:30Z", score: [1]}, {price: 1000000, dueDate: "1990-06-15", since: "2000-01-01", score: 50}, {price: 1000000, dueDate: "2024-01-01", since: "1990-06-15", score: 5}], profile: {amount: 5}}}, goals: ["profile.scores.quota", "shipment.exposure"], output: "!error: InputValidationFailed"}, + {input: {shipment: {days: 99999999999999999999, label: "x-y", priority: false, plan: "trial", country: "retail", vehicles: [{price: null, dueDate: "2025-03-20", since: "2025-03-20", score: 10}, {price: 1000, dueDate: "2024-01-01", since: "2025-03-20T10:15:30Z", score: 1000000}, {price: 3, dueDate: "2000-01-01", since: "2025-03-20", score: 65}, {price: 1.5, dueDate: "2024-02-29", since: "2000-01-01", score: 99999999999999999999}], profile: {amount: -0.01}}}, goals: ["shipment.exposure", "profile.scores.quota", "vehicle.tag"], output: {shipment: {country: "retail", days: 99999999999999999999, exposure: 99999999999999999999, label: "x-y", plan: "trial", priority: false, profile: {amount: -0.01, health: null, scores: {quota: null}}, vehicles: [{dueDate: "2025-03-20", grade: ["false"], price: null, score: 10, since: "2025-03-20", tag: [false]}, {dueDate: "2024-01-01", grade: ["false"], price: 1000, score: 1000000, since: "2025-03-20T10:15:30Z", tag: [false]}, {dueDate: "2000-01-01", grade: ["false"], price: 3, score: 65, since: "2025-03-20", tag: [false]}, {dueDate: "2024-02-29", grade: ["x-y", "false"], price: 1.5, score: 99999999999999999999, since: "2000-01-01", tag: [false]}]}}}, + {input: {shipment: {days: 2, label: "Oslo", priority: false, plan: "basic", country: "A1", vehicles: [], profile: {amount: 0.5}}}, goals: ["shipment.exposure", "profile.capped"], output: {shipment: {country: "A1", days: 2, exposure: 0.5, label: "Oslo", plan: "basic", priority: false, profile: {amount: 0.5, capped: 0, rank: []}, vehicles: []}}}, + [{shipment: {days: 2, label: "US", priority: false, plan: "plus", country: "a-b-c", vehicles: [{price: 0.5, dueDate: "2000-01-01", since: "1990-06-15", score: -1}, {price: 0.000001, dueDate: "2024-02-29", since: "1990-06-15", score: 1000}, {price: 99.99, dueDate: "2025-03-20", since: "2000-01-01", score: 10}, {price: 100, dueDate: "1990-06-15", since: "1990-06-15", score: 250}, {price: 5, dueDate: "2030-12-31", since: "2024-01-01", score: 100}, {price: 1, dueDate: "2024-02-29", since: "2025-03-20T10:15:30Z", score: 1}, {price: 5, dueDate: "2030-12-31", since: "2024-02-29", score: 0}, {price: 5, dueDate: "2024-01-01", since: "2000-01-01", score: -0.01}, {price: -0.01, dueDate: "2024-01-01", since: "2030-12-31", score: 1000}, {price: 1, dueDate: "2030-12-31", since: "2000-01-01", score: 18}, {price: 1000, dueDate: "2025-03-20", since: "2030-12-31", score: 0.1}, {price: 50, dueDate: "1990-06-15", since: "2030-12-31", score: 0.1}, {price: 250, dueDate: "1990-06-15", since: "2000-01-01", score: 10}], profile: {amount: 5}, extraField: "x"}}, {shipment: {country: "a-b-c", days: 2, exposure: 2, extraField: "x", label: "US", plan: "plus", priority: false, profile: {amount: 5, capped: 1517.480001, health: 3.50, rank: [{bonus: null, dueDate: "2000-01-01", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 0.5, score: -1, since: "1990-06-15", tag: [false]}, {bonus: null, dueDate: "2024-02-29", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 0.000001, score: 1000, since: "1990-06-15", tag: [false]}, {bonus: null, dueDate: "2025-03-20", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 99.99, score: 10, since: "2000-01-01", tag: [false]}, {bonus: null, dueDate: "1990-06-15", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 100, score: 250, since: "1990-06-15", tag: [false]}, {bonus: null, dueDate: "2030-12-31", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 5, score: 100, since: "2024-01-01", tag: [false]}, {bonus: null, dueDate: "2024-02-29", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 1, score: 1, since: "2025-03-20T10:15:30Z", tag: [false]}, {bonus: null, dueDate: "2030-12-31", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 5, score: 0, since: "2024-02-29", tag: [false]}, {bonus: null, dueDate: "2024-01-01", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 5, score: -0.01, since: "2000-01-01", tag: [false]}, {bonus: null, dueDate: "2024-01-01", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: -0.01, score: 1000, since: "2030-12-31", tag: [false]}, {bonus: null, dueDate: "2030-12-31", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 1, score: 18, since: "2000-01-01", tag: [false]}, {bonus: null, dueDate: "2025-03-20", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 1000, score: 0.1, since: "2030-12-31", tag: [false]}, {bonus: null, dueDate: "1990-06-15", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 50, score: 0.1, since: "2030-12-31", tag: [false]}, {bonus: null, dueDate: "1990-06-15", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 250, score: 10, since: "2000-01-01", tag: [false]}], scores: {quota: 2}, segment: "US"}, vehicles: [{bonus: null, dueDate: "2000-01-01", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 0.5, score: -1, since: "1990-06-15", tag: [false]}, {bonus: null, dueDate: "2024-02-29", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 0.000001, score: 1000, since: "1990-06-15", tag: [false]}, {bonus: null, dueDate: "2025-03-20", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 99.99, score: 10, since: "2000-01-01", tag: [false]}, {bonus: null, dueDate: "1990-06-15", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 100, score: 250, since: "1990-06-15", tag: [false]}, {bonus: null, dueDate: "2030-12-31", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 5, score: 100, since: "2024-01-01", tag: [false]}, {bonus: null, dueDate: "2024-02-29", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 1, score: 1, since: "2025-03-20T10:15:30Z", tag: [false]}, {bonus: null, dueDate: "2030-12-31", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 5, score: 0, since: "2024-02-29", tag: [false]}, {bonus: null, dueDate: "2024-01-01", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 5, score: -0.01, since: "2000-01-01", tag: [false]}, {bonus: null, dueDate: "2024-01-01", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: -0.01, score: 1000, since: "2030-12-31", tag: [false]}, {bonus: null, dueDate: "2030-12-31", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 1, score: 18, since: "2000-01-01", tag: [false]}, {bonus: null, dueDate: "2025-03-20", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 1000, score: 0.1, since: "2030-12-31", tag: [false]}, {bonus: null, dueDate: "1990-06-15", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 50, score: 0.1, since: "2030-12-31", tag: [false]}, {bonus: null, dueDate: "1990-06-15", grade: ["false"], meta: {decision: {a: -3, v: false}, points: ""}, price: 250, score: 10, since: "2000-01-01", tag: [false]}]}}], + [{shipment: {days: 1000000, label: "abc", priority: false, plan: "trial", country: "日本", vehicles: [{price: 1e3, dueDate: "2025-03-20T10:15:30Z", since: "2025-03-20", score: 7.25}, {price: 0.5, dueDate: "2000-01-01", since: "1990-06-15", score: 100}], profile: {amount: 0.000001}}}, {shipment: {country: "日本", days: 1000000, exposure: 1000000, label: "abc", plan: "trial", priority: false, profile: {amount: 0.000001, capped: 1000.5, health: null, rank: [{dueDate: "2025-03-20T10:15:30Z", grade: ["false"], meta: {decision: {a: 999999.999999, v: false}, points: "abc"}, price: 1000, score: 7.25, since: "2025-03-20", tag: [false]}, {dueDate: "2000-01-01", grade: ["false"], meta: {decision: {a: 999999.999999, v: false}, points: "abc"}, price: 0.5, score: 100, since: "1990-06-15", tag: [false]}], scores: {quota: null}, segment: "abc"}, vehicles: [{dueDate: "2025-03-20T10:15:30Z", grade: ["false"], meta: {decision: {a: 999999.999999, v: false}, points: "abc"}, price: 1000, score: 7.25, since: "2025-03-20", tag: [false]}, {dueDate: "2000-01-01", grade: ["false"], meta: {decision: {a: 999999.999999, v: false}, points: "abc"}, price: 0.5, score: 100, since: "1990-06-15", tag: [false]}]}}], + ], +} + +// seed 353600 (attempt 0) +{ + name: "goals 37: borrower/vehicles: 2 expression, 1 match, 2 table; 4 root, 6 per-member, 0 top-level computed", + policy: { + models: {borrower: {limit: "number", since: "date?", score: "number?", vehicles: "vehicle[]?"}, vehicle: {days: "number", flagged: "boolean", dueDate: "date"}}, + globals: {settings: {factor: "number"}}, + blocks: [ + {expression: "vehicle.discount", value: "{a: (min([abs((borrower.limit / -6)), 1000]) ^ 1), ok: vehicle.days, v: 'a'}"}, + {table: "t2", inputs: ["sum([borrower.limit])", "(borrower.score ?? 0)"], outputs: ["vehicle.share", "vehicle.weighted"], rules: [ + ["[10..498]", "[1..13]", "some((borrower.vehicles ?? []), not (#.flagged))", "all((borrower.vehicles ?? []), #.days <= 10)"], + ["2, 0.25", "", "vehicle.flagged", "vehicle.flagged"], + ["> 1000", "<= 0.25", "vehicle.flagged", "vehicle.flagged"], + ["", "< 10", "vehicle.flagged", "vehicle.flagged"], + ["", "", "startsWith(vehicle.discount.v, 'DE')", "3 != (borrower.score ?? 0)"], + ]}, + {expression: "borrower.level", value: "(borrower.since ?? d('2025-01-01')).add(31, 'month')"}, + {table: "t4", inputs: ["borrower.limit", "(min([abs(factor), 1000]) ^ 0)", null], outputs: ["borrower.flags.quota", "borrower.tag[]"], rules: [ + ["< 0.25", "", "borrower.level < d('2024-01-01')", "factor", ""], + [">= 18", "<= 50", "0 < factor", "3", ""], + ["", "", "", "0.5", "`${'gold'}/${borrower.limit <= 18}`"], + ]}, + {match: "borrower.flag", arms: [["borrower.level < d('2025-03-20')", "(borrower.score ?? 0) == 1000"], ["borrower.limit in [44..138]", "borrower.flags.quota == null"], ["(all((borrower.vehicles ?? []), #.dueDate.isAfter(d('2024-01-01'), 'month')) and borrower.level.isBefore(d('2000-06-30'), 'month'))", "none((borrower.vehicles ?? []), #.days > 18)"], ["((borrower.flags.quota ?? 0) > 0.25 or factor > 18)", "((borrower.flags.quota ?? 0) * (borrower.score ?? 0)) >= (borrower.score ?? 0)"], ["", "(borrower.flags.quota ?? 0) <= 250"]]}, + ], + }, + cases: [ + {input: {factor: 10, borrower: {limit: 1.5, since: "2024-01-01", score: 100, vehicles: [{days: 250, flagged: false, dueDate: "2024-01-01"}, {days: 250, flagged: false, dueDate: "2024-01-01"}, {days: 3, flagged: false, dueDate: "2025-03-20"}]}}, goals: ["borrower.flags.quota", "borrower.tag", "borrower.level"], output: {borrower: {flags: {quota: 0.5}, level: "2026-08-01T00:00:00Z", limit: 1.5, score: 100, since: "2024-01-01", tag: ["gold/true"], vehicles: [{days: 250, dueDate: "2024-01-01", flagged: false}, {days: 250, dueDate: "2024-01-01", flagged: false}, {days: 3, dueDate: "2025-03-20", flagged: false}]}, factor: 10}}, + [{factor: 0.5, borrower: {limit: 50, since: "2000-01-01", score: 2, vehicles: []}}, {borrower: {flag: false, flags: {quota: 3}, level: "2002-08-01T00:00:00Z", limit: 50, score: 2, since: "2000-01-01", tag: ["gold/false"], vehicles: []}, factor: 0.5}], + [{factor: 1, borrower: {limit: 10, since: null, score: 0.25, vehicles: null}}, {borrower: {flag: false, flags: {quota: 0.5}, level: "2027-08-01T00:00:00Z", limit: 10, score: 0.25, since: null, tag: ["gold/true"], vehicles: null}, factor: 1}], + {input: {factor: 100, borrower: {limit: 1, since: "2024-02-29", score: 5, vehicles: [{days: 5, flagged: true, dueDate: "2025-03-20T10:15:30Z"}]}}, goals: ["borrower.flag", "borrower.flags.quota", "vehicle.share"], output: {borrower: {flag: false, flags: {quota: 0.5}, level: "2026-09-29T00:00:00Z", limit: 1, score: 5, since: "2024-02-29", tag: ["gold/true"], vehicles: [{days: 5, dueDate: "2025-03-20T10:15:30Z", flagged: true, share: true, weighted: true}]}, factor: 100}}, + {input: {factor: 1, borrower: {limit: 18, score: -500}}, goals: ["borrower.flags.quota", "vehicle.discount"], output: {borrower: {flags: {quota: 3}, level: "2027-08-01T00:00:00Z", limit: 18, score: -500, tag: ["gold/true"]}, factor: 1}}, + {input: {factor: -2, borrower: {limit: 5, since: "2025-03-20", score: 2, vehicles: [{days: 99.99, flagged: true, dueDate: "2030-12-31"}, {days: 1e3, flagged: true, dueDate: "2025-03-20T10:15:30Z"}, {days: 1000, flagged: false, dueDate: "2025-03-20"}]}}, goals: ["borrower.flag", "vehicle.weighted", "borrower.level"], output: {borrower: {flag: false, flags: {quota: 0.5}, level: "2027-10-20T00:00:00Z", limit: 5, score: 2, since: "2025-03-20", tag: ["gold/true"], vehicles: [{days: 99.99, dueDate: "2030-12-31", flagged: true, share: true, weighted: true}, {days: 1000, dueDate: "2025-03-20T10:15:30Z", flagged: true, share: true, weighted: true}, {days: 1000, dueDate: "2025-03-20", flagged: false, share: false, weighted: false}]}, factor: -2}}, + [{factor: 10, borrower: {limit: 411, since: "2025-03-20T10:15:30Z", score: 1, vehicles: [{days: 65, flagged: true, dueDate: "2024-01-01"}]}}, {borrower: {flag: true, flags: {quota: 3}, level: "2027-10-20T10:15:30Z", limit: 411, score: 1, since: "2025-03-20T10:15:30Z", tag: ["gold/false"], vehicles: [{days: 65, dueDate: "2024-01-01", flagged: true, share: false, weighted: false}]}, factor: 10}], + {input: {factor: 0.5, borrower: {limit: -500, since: "2000-01-01", score: -500, vehicles: [{days: 1e3, flagged: false, dueDate: "2025-03-20"}], extraField: {nested: true}}}, goals: ["vehicle.weighted", "vehicle.share"], output: {borrower: {extraField: {nested: true}, limit: -500, score: -500, since: "2000-01-01", vehicles: [{days: 1000, dueDate: "2025-03-20", flagged: false, share: false, weighted: false}]}, factor: 0.5}}, + {input: {factor: 100, borrower: {limit: 250, since: "2025-03-20", score: 1000, vehicles: []}}, goals: ["vehicle.weighted", "borrower.tag", "vehicle.share"], output: {borrower: {flags: {quota: 3}, level: "2027-10-20T00:00:00Z", limit: 250, score: 1000, since: "2025-03-20", tag: ["gold/false"], vehicles: []}, factor: 100}}, + {input: {factor: 100, borrower: {limit: 5, since: "2024-01-01", score: 0.25, vehicles: [{days: 100, flagged: true, dueDate: "2025-03-20T10:15:30Z"}, {days: -1, flagged: false, dueDate: "1990-06-15"}, {days: 0, flagged: true, dueDate: "2024-01-01"}, {days: 0, flagged: false, dueDate: "2025-03-20"}, {days: 100, flagged: false, dueDate: "2025-03-20"}, {days: 0.1, flagged: true, dueDate: "2025-03-20T10:15:30Z"}, {days: 10, flagged: false, dueDate: "2000-01-01"}, {days: 123456789.123, flagged: false, dueDate: "2000-01-01"}, {days: 2.50, flagged: true, dueDate: "2024-02-29"}]}}, goals: ["borrower.tag", "borrower.flag", "vehicle.weighted"], output: {borrower: {flag: false, flags: {quota: 0.5}, level: "2026-08-01T00:00:00Z", limit: 5, score: 0.25, since: "2024-01-01", tag: ["gold/true"], vehicles: [{days: 100, dueDate: "2025-03-20T10:15:30Z", flagged: true, share: true, weighted: true}, {days: -1, dueDate: "1990-06-15", flagged: false, share: false, weighted: false}, {days: 0, dueDate: "2024-01-01", flagged: true, share: true, weighted: true}, {days: 0, dueDate: "2025-03-20", flagged: false, share: false, weighted: false}, {days: 100, dueDate: "2025-03-20", flagged: false, share: false, weighted: false}, {days: 0.1, dueDate: "2025-03-20T10:15:30Z", flagged: true, share: true, weighted: true}, {days: 10, dueDate: "2000-01-01", flagged: false, share: false, weighted: false}, {days: 123456789.123, dueDate: "2000-01-01", flagged: false, share: false, weighted: false}, {days: 2.50, dueDate: "2024-02-29", flagged: true, share: true, weighted: true}]}, factor: 100}}, + {input: {factor: 0.5, borrower: {limit: 10, since: "2024-02-29", score: 100, vehicles: []}}, goals: ["vehicle.share", "borrower.tag", "borrower.flag"], output: {borrower: {flag: false, flags: {quota: 0.5}, level: "2026-09-29T00:00:00Z", limit: 10, score: 100, since: "2024-02-29", tag: ["gold/true"], vehicles: []}, factor: 0.5}}, + {input: {factor: -2, borrower: {limit: -1, since: "2024-02-29", score: 0.000001, vehicles: [{days: 10, flagged: true, dueDate: "2030-12-31"}, {days: 2, flagged: false, dueDate: "2025-03-20"}], extraField: "x"}}, goals: ["borrower.flag", "vehicle.share", "borrower.level"], output: {borrower: {extraField: "x", flag: false, flags: {quota: 0.5}, level: "2026-09-29T00:00:00Z", limit: -1, score: 0.000001, since: "2024-02-29", tag: ["gold/true"], vehicles: [{days: 10, dueDate: "2030-12-31", flagged: true, share: true, weighted: true}, {days: 2, dueDate: "2025-03-20", flagged: false, share: false, weighted: false}]}, factor: -2}}, + {input: {factor: 0, borrower: {limit: 5, since: "2025-03-20", score: 1000, vehicles: [{days: 2, flagged: true, dueDate: "2000-01-01"}, {days: 0.5, flagged: true, dueDate: "2030-12-31"}]}}, goals: ["vehicle.discount", "vehicle.weighted"], output: {borrower: {limit: 5, score: 1000, since: "2025-03-20", vehicles: [{days: 2, discount: {a: 0.8333333333333333333333333333, ok: 2, v: "a"}, dueDate: "2000-01-01", flagged: true, share: false, weighted: true}, {days: 0.5, discount: {a: 0.8333333333333333333333333333, ok: 0.5, v: "a"}, dueDate: "2030-12-31", flagged: true, share: false, weighted: true}]}, factor: 0}}, + {input: {factor: 0, borrower: {limit: 1.5, since: "2000-01-01", score: 18, vehicles: []}}, goals: ["vehicle.share", "vehicle.discount", "borrower.tag"], output: {borrower: {flags: {quota: 0.5}, level: "2002-08-01T00:00:00Z", limit: 1.5, score: 18, since: "2000-01-01", tag: ["gold/true"], vehicles: []}, factor: 0}}, + {input: {factor: -2, borrower: {limit: -0.5, since: "2024-02-29", score: 1.5, vehicles: [{days: 5, flagged: false, dueDate: "2000-01-01"}, {days: 2, flagged: false, dueDate: "2024-02-29"}]}}, goals: ["borrower.flags.quota"], output: {borrower: {flags: {quota: 0.5}, level: "2026-09-29T00:00:00Z", limit: -0.5, score: 1.5, since: "2024-02-29", tag: ["gold/true"], vehicles: [{days: 5, dueDate: "2000-01-01", flagged: false}, {days: 2, dueDate: "2024-02-29", flagged: false}]}, factor: -2}}, + [{factor: 1, borrower: {limit: 123456789.123, since: "2025-03-20T10:15:30Z", score: 0, vehicles: [{days: 65, flagged: true, dueDate: "2024-01-01"}]}}, {borrower: {flag: true, flags: {quota: 3}, level: "2027-10-20T10:15:30Z", limit: 123456789.123, score: 0, since: "2025-03-20T10:15:30Z", tag: ["gold/false"], vehicles: [{days: 65, dueDate: "2024-01-01", flagged: true, share: true, weighted: true}]}, factor: 1}], + {input: {factor: -2, borrower: {limit: 0.25, since: "2000-01-01", score: 250, vehicles: [{days: 3, flagged: true, dueDate: "2025-03-20"}, {days: 65, flagged: true, dueDate: "2024-02-29"}]}}, goals: ["borrower.tag", "borrower.flag", "vehicle.weighted"], output: {borrower: {flag: false, flags: {quota: 0.5}, level: "2002-08-01T00:00:00Z", limit: 0.25, score: 250, since: "2000-01-01", tag: ["gold/true"], vehicles: [{days: 3, dueDate: "2025-03-20", flagged: true, share: true, weighted: true}, {days: 65, dueDate: "2024-02-29", flagged: true, share: true, weighted: true}]}, factor: -2}}, + ], +} + +// seed 353700 (attempt 0) +{ + name: "goals 38: shipment/companies/parts + address: 1 assertion, 3 expression, 5 match, 2 table; 5 root, 5 per-member, 2 top-level computed", + policy: { + models: {shipment: {score: "number?", dueDate: "date", flagged: "boolean", birthDate: "date", since: "date?", companies: "company[]?", address: "address?"}, company: {amount: "number", country: "string", price: "number?", parts: "part[]"}, part: {years: "number"}, address: {weight: "number"}}, + blocks: [ + {match: "share", arms: [["(shipment.since ?? d('2025-01-01')).isAfter(d('2000-06-30'), 'month')", "'VIP'"], ["some((shipment.companies ?? []), contains(['high', 'gold', ''], #.country))", "(shipment.flagged ? 'Oslo' : 'low')"], ["none((shipment.companies ?? []), #.price != null)", "`${0.5}/${(shipment.flagged and shipment.flagged)}`"], ["all((shipment.companies ?? []), isNumeric(#.country))", "'retail'"], ["", "`${shipment.flagged}/${(shipment.address.weight ?? 0)}`"]]}, + {match: "company.penalty", arms: [["(shipment.flagged and shipment.flagged)", "('A1' + '-' + company.country)"], ["", "`${shipment.flagged}/${(shipment.score ?? 0)}`"]]}, + {table: "t3", inputs: ["(min([abs((shipment.score ?? 0)), 1000]) ^ 0)", "share"], outputs: ["shipment.calc.band", "shipment.rank", "shipment.calc.review"], rules: [ + ["5, 2", "'retail', 'US'", "shipment.flagged", "shipment.flagged", "(shipment.score ?? 0)"], + ["<= 1.5", "", "shipment.flagged", "(shipment.flagged or shipment.flagged)", "(shipment.score ?? 0)"], + ["", "'low'", "shipment.flagged", "shipment.flagged", "(shipment.score ?? 0)"], + ["3", "$ != 'Oslo'", "(shipment.flagged or shipment.flagged)", "shipment.flagged", ""], + ["[0..366]", "$ != 'US'", "(shipment.score ?? 0) != (shipment.address.weight ?? 0)", "shipment.flagged", "(shipment.score ?? 0)"], + ["[1..120]", "'ok'", "none((shipment.companies ?? []), not ((#.price ?? 0) > 0.5))", "shipment.flagged", "(shipment.score ?? 0)"], + ]}, + {match: "shipment.calc.points", arms: [["startsWith(((shipment.calc.band ?? false) ? share : share), 'US')", "len(filter((shipment.companies ?? []), #.amount > #.amount))"], ["(shipment.address.weight ?? 0) in [32..45)", "(number(string((shipment.score ?? 0)))) / (abs((min([abs((shipment.address.weight ?? 0)), 1000]) ^ 1)) + 1)"], ["", "-((shipment.address.weight ?? 0))"]]}, + {table: "t5", hit: "collect", inputs: ["shipment.flagged", "shipment.calc.review"], outputs: ["company.meta.total"], rules: [ + ["", "0.5", "shipment.calc.points"], + ["false", "50", "(shipment.address.weight ?? 0)"], + ["true", "", "(company.price ?? 0)"], + ["", "2", "(shipment.score ?? 0)"], + ["false", "10, 0.25", ""], + ["", "", "(shipment.address.weight ?? 0)"], + ]}, + {expression: "shipment.eligible", value: "((shipment.score ?? 0) == shipment.calc.points ? shipment.address.weight : null)"}, + {expression: "margin", value: "(shipment.since ?? d('2025-01-01'))"}, + {assertion: "company.capped", conditions: [["or", "(matches(company.penalty, 'a') and not ((shipment.calc.band ?? false)))", 2], "contains(['low', 'none', ''], company.country)"]}, + {expression: "company.surcharge", value: "company.penalty"}, + {match: "company.flag", arms: [["some(company.parts, #.years > #.years)", "`${company.country}/${count(company.parts, #.years == #.years)}`"], ["number(string((shipment.address.weight ?? 0))) >= (shipment.calc.review ?? 0)", "upper(company.surcharge)"], ["", "'low'"]]}, + {match: "address.summary", arms: [["(shipment.eligible ?? 0) != 0", "share"], ["", "share"]]}, + ], + }, + cases: [ + {input: {shipment: {score: 3, dueDate: "1990-06-15", flagged: false, birthDate: "2024-01-01", address: {weight: 10}}}, goals: ["company.meta.total", "shipment.calc.band"], output: {share: "VIP", shipment: {address: {weight: 10}, birthDate: "2024-01-01", calc: {band: false, review: 3}, dueDate: "1990-06-15", flagged: false, rank: false, score: 3}}}, + [{shipment: {score: 18, dueDate: "2025-03-20T10:15:30Z", flagged: true, birthDate: "2000-01-01", since: "2025-03-20", companies: [], address: {weight: 10}}}, {margin: "2025-03-20", share: "VIP", shipment: {address: {summary: "VIP", weight: 10}, birthDate: "2000-01-01", calc: {band: true, points: -10, review: 18}, companies: [], dueDate: "2025-03-20T10:15:30Z", eligible: null, flagged: true, rank: true, score: 18, since: "2025-03-20"}}], + [{shipment: {score: 10, dueDate: "2025-03-20T10:15:30Z", flagged: true, birthDate: "2024-01-01", since: "2024-01-01", companies: [{amount: 1.5, country: "A1", price: 123456789.123, parts: [{years: -0.01}, {years: 3}]}, {amount: 10, country: "DE", price: -0.01, parts: [{years: 2}]}, {amount: 178, country: "Oslo", price: 0.25, parts: [{years: 99.99}]}, {amount: 3, country: "VIP", price: 2, parts: [{years: -0.01}, {years: 1.5}, {years: -0.01}]}, {amount: 250, country: "a", price: 250, parts: [{years: 100}, {years: 0.25}]}, {amount: 0.25, country: "ok", price: 0.5, parts: [{years: 1000}, {years: 7.25}]}, {amount: -0.01, country: "Oslo", price: 10, parts: [{years: 1000000}, {years: 0}]}, {amount: 50, country: "low", price: -0.01, parts: [{years: -0.5}]}, {amount: 10, country: "retail", price: 0, parts: [{years: 50}, {years: -0.01}]}, {amount: 2.50, country: "3.5", price: 50, parts: []}, {amount: 1, country: "Oslo", price: 50, parts: [{years: 1000}, {years: 5}, {years: 10}]}, {amount: 1000000, country: "gold", price: -1, parts: [{years: 0.1}, {years: 1.5}, {years: 1}]}, {amount: 0.5, country: "é ü", price: 0.5, parts: []}, {amount: 0, country: "-", price: 65, parts: [{years: 0.5}, {years: 0.5}]}], address: {weight: 0.5}}}, {margin: "2024-01-01", share: "VIP", shipment: {address: {summary: "VIP", weight: 0.5}, birthDate: "2024-01-01", calc: {band: true, points: -0.5, review: 10}, companies: [{amount: 1.5, capped: false, country: "A1", flag: "low", meta: {total: [123456789.123, 0.5]}, parts: [{years: -0.01}, {years: 3}], penalty: "A1-A1", price: 123456789.123}, {amount: 10, capped: false, country: "DE", flag: "low", meta: {total: [-0.01, 0.5]}, parts: [{years: 2}], penalty: "A1-DE", price: -0.01}, {amount: 178, capped: false, country: "Oslo", flag: "low", meta: {total: [0.25, 0.5]}, parts: [{years: 99.99}], penalty: "A1-Oslo", price: 0.25}, {amount: 3, capped: false, country: "VIP", flag: "low", meta: {total: [2, 0.5]}, parts: [{years: -0.01}, {years: 1.5}, {years: -0.01}], penalty: "A1-VIP", price: 2}, {amount: 250, capped: false, country: "a", flag: "low", meta: {total: [250, 0.5]}, parts: [{years: 100}, {years: 0.25}], penalty: "A1-a", price: 250}, {amount: 0.25, capped: false, country: "ok", flag: "low", meta: {total: [0.5, 0.5]}, parts: [{years: 1000}, {years: 7.25}], penalty: "A1-ok", price: 0.5}, {amount: -0.01, capped: false, country: "Oslo", flag: "low", meta: {total: [10, 0.5]}, parts: [{years: 1000000}, {years: 0}], penalty: "A1-Oslo", price: 10}, {amount: 50, capped: true, country: "low", flag: "low", meta: {total: [-0.01, 0.5]}, parts: [{years: -0.5}], penalty: "A1-low", price: -0.01}, {amount: 10, capped: false, country: "retail", flag: "low", meta: {total: [0, 0.5]}, parts: [{years: 50}, {years: -0.01}], penalty: "A1-retail", price: 0}, {amount: 2.50, capped: false, country: "3.5", flag: "low", meta: {total: [50, 0.5]}, parts: [], penalty: "A1-3.5", price: 50}, {amount: 1, capped: false, country: "Oslo", flag: "low", meta: {total: [50, 0.5]}, parts: [{years: 1000}, {years: 5}, {years: 10}], penalty: "A1-Oslo", price: 50}, {amount: 1000000, capped: false, country: "gold", flag: "low", meta: {total: [-1, 0.5]}, parts: [{years: 0.1}, {years: 1.5}, {years: 1}], penalty: "A1-gold", price: -1}, {amount: 0.5, capped: false, country: "é ü", flag: "low", meta: {total: [0.5, 0.5]}, parts: [], penalty: "A1-é ü", price: 0.5}, {amount: 0, capped: false, country: "-", flag: "low", meta: {total: [65, 0.5]}, parts: [{years: 0.5}, {years: 0.5}], penalty: "A1--", price: 65}], dueDate: "2025-03-20T10:15:30Z", eligible: null, flagged: true, rank: true, score: 10, since: "2024-01-01"}}], + [{shipment: {score: 18, dueDate: "1990-06-15", flagged: false, birthDate: "2030-12-31", since: "2025-03-20", companies: [{amount: 50, country: " pad ", price: 50, parts: []}, {amount: 10, country: "none", price: 1e3, parts: [{years: 1}, {years: 100}]}, {amount: -0.5, country: "US", price: 10, parts: []}, {amount: 2, country: "none", price: 1000000, parts: [{years: 50}]}], address: {weight: 0}}}, {margin: "2025-03-20", share: "VIP", shipment: {address: {summary: "VIP", weight: 0}, birthDate: "2030-12-31", calc: {band: false, points: -0, review: 18}, companies: [{amount: 50, capped: true, country: " pad ", flag: "low", meta: {total: [0]}, parts: [], penalty: "false/18", price: 50}, {amount: 10, capped: true, country: "none", flag: "low", meta: {total: [0]}, parts: [{years: 1}, {years: 100}], penalty: "false/18", price: 1000}, {amount: -0.5, capped: true, country: "US", flag: "low", meta: {total: [0]}, parts: [], penalty: "false/18", price: 10}, {amount: 2, capped: true, country: "none", flag: "low", meta: {total: [0]}, parts: [{years: 50}], penalty: "false/18", price: 1000000}], dueDate: "1990-06-15", eligible: null, flagged: false, rank: false, score: 18, since: "2025-03-20"}}], + {input: {shipment: {score: true, dueDate: "2024-02-29", flagged: false, birthDate: "2030-12-31", since: "2024-01-01", companies: [{amount: 3, country: "3.5", price: 2.50, parts: [{years: 123456789.123}, {years: 1000}]}, {amount: 0.25, country: "DE", price: 0.000001, parts: [{years: 1000}, {years: 10}, {years: 1e3}]}, {amount: 7.25, country: "a", price: 1, parts: [{years: 65}, {years: 100}]}, {amount: 10, country: " pad ", price: 0.25, parts: [{years: 2.50}, {years: 0.25}, {years: 0}]}, {amount: 10, country: "gold", price: 0, parts: [{years: 3}, {years: 50}]}], address: {weight: 10}}}, goals: ["company.surcharge", "company.meta.total", "shipment.calc.band"], output: "!error: InputValidationFailed"}, + {input: {shipment: {score: 99.99, dueDate: "2024-02-29", flagged: true, birthDate: "1990-06-15", since: "2025-03-20T10:15:30Z", companies: [], address: {weight: 2}}}, goals: ["shipment.rank", "company.penalty", "margin"], output: {margin: "2025-03-20T10:15:30Z", share: "VIP", shipment: {address: {weight: 2}, birthDate: "1990-06-15", calc: {band: true, review: 99.99}, companies: [], dueDate: "2024-02-29", flagged: true, rank: true, score: 99.99, since: "2025-03-20T10:15:30Z"}}}, + {input: {shipment: {score: null, dueDate: "2030-12-31", flagged: true, birthDate: "1990-06-15", since: "2024-01-01", companies: [{amount: 10, country: "DE", price: 0, parts: [{years: 1000}, {years: 10}, {years: 0.5}]}, {amount: 1, country: "low", parts: [{years: 1}, {years: 0.5}]}, {amount: 50, country: "VIP", parts: []}, {amount: -500, country: "日本", parts: []}], address: null}}, goals: ["address.summary"], output: {share: "VIP", shipment: {address: null, birthDate: "1990-06-15", calc: {band: true, points: -0, review: 0}, companies: [{amount: 10, country: "DE", parts: [{years: 1000}, {years: 10}, {years: 0.5}], price: 0}, {amount: 1, country: "low", parts: [{years: 1}, {years: 0.5}]}, {amount: 50, country: "VIP", parts: []}, {amount: -500, country: "日本", parts: []}], dueDate: "2030-12-31", eligible: null, flagged: true, rank: true, score: null, since: "2024-01-01"}}}, + {input: {shipment: {score: 1.5, dueDate: "1990-06-15", flagged: false, birthDate: "2000-01-01", since: "2024-02-29", companies: [{amount: 0, country: "high", price: 1, parts: [{years: 100}, {years: 2}]}, {amount: 50, country: "A1", price: 7.25, parts: [{years: 250}, {years: 442}, {years: 0.25}]}, {amount: 50, country: "DE", price: 100, parts: [{years: 0.5}, {years: 10}]}, {amount: 2, country: "VIP", price: 50, parts: [{years: -500}, {years: 0.000001}, {years: 50}]}, {amount: 99999999999999999999, country: "ok", price: 1, parts: [{years: 0.5}, {years: 7.25}, {years: 0.5}]}, {amount: 2, country: "日本", price: 10, parts: [{years: 0}, {years: 2}]}, {amount: 0.5, country: "US", price: -500, parts: [{years: -1}, {years: 10}]}, {amount: 0, country: "US", price: 10, parts: [{years: 0.5}, {years: 2}]}], address: {weight: 50}}}, goals: ["company.surcharge"], output: {shipment: {address: {weight: 50}, birthDate: "2000-01-01", companies: [{amount: 0, country: "high", parts: [{years: 100}, {years: 2}], penalty: "false/1.5", price: 1, surcharge: "false/1.5"}, {amount: 50, country: "A1", parts: [{years: 250}, {years: 442}, {years: 0.25}], penalty: "false/1.5", price: 7.25, surcharge: "false/1.5"}, {amount: 50, country: "DE", parts: [{years: 0.5}, {years: 10}], penalty: "false/1.5", price: 100, surcharge: "false/1.5"}, {amount: 2, country: "VIP", parts: [{years: -500}, {years: 0.000001}, {years: 50}], penalty: "false/1.5", price: 50, surcharge: "false/1.5"}, {amount: 99999999999999999999, country: "ok", parts: [{years: 0.5}, {years: 7.25}, {years: 0.5}], penalty: "false/1.5", price: 1, surcharge: "false/1.5"}, {amount: 2, country: "日本", parts: [{years: 0}, {years: 2}], penalty: "false/1.5", price: 10, surcharge: "false/1.5"}, {amount: 0.5, country: "US", parts: [{years: -1}, {years: 10}], penalty: "false/1.5", price: -500, surcharge: "false/1.5"}, {amount: 0, country: "US", parts: [{years: 0.5}, {years: 2}], penalty: "false/1.5", price: 10, surcharge: "false/1.5"}], dueDate: "1990-06-15", flagged: false, score: 1.5, since: "2024-02-29"}}}, + [{shipment: {score: 99.99, dueDate: "2025-03-20T10:15:30Z", flagged: false, birthDate: "2025-03-20T10:15:30Z", since: "2025-03-20", companies: [{amount: 0.1, country: "retail", price: 0.5, parts: [{years: 0}, {years: 3}, {years: 250}]}, {amount: 0, country: " pad ", price: 3, parts: [{years: 1}]}, {amount: 10, country: "-", price: 50, parts: [{years: 0.5}, {years: 10}]}, {amount: 0.000001, country: "a", price: 0.5, parts: [{years: 5}, {years: 18}, {years: 0}]}], address: {weight: 18}, extraField: "x"}}, {margin: "2025-03-20", share: "VIP", shipment: {address: {summary: "VIP", weight: 18}, birthDate: "2025-03-20T10:15:30Z", calc: {band: false, points: -18, review: 99.99}, companies: [{amount: 0.1, capped: true, country: "retail", flag: "low", meta: {total: [18]}, parts: [{years: 0}, {years: 3}, {years: 250}], penalty: "false/99.99", price: 0.5}, {amount: 0, capped: true, country: " pad ", flag: "low", meta: {total: [18]}, parts: [{years: 1}], penalty: "false/99.99", price: 3}, {amount: 10, capped: true, country: "-", flag: "low", meta: {total: [18]}, parts: [{years: 0.5}, {years: 10}], penalty: "false/99.99", price: 50}, {amount: 0.000001, capped: true, country: "a", flag: "low", meta: {total: [18]}, parts: [{years: 5}, {years: 18}, {years: 0}], penalty: "false/99.99", price: 0.5}], dueDate: "2025-03-20T10:15:30Z", eligible: null, extraField: "x", flagged: false, rank: false, score: 99.99, since: "2025-03-20"}}], + {input: {shipment: {score: 123456789.123, dueDate: "2000-01-01", flagged: false, birthDate: "2024-02-29", companies: [{amount: 100, country: "VIP", price: 0.25, parts: []}], address: {weight: 0.1}}}, goals: ["address.summary"], output: {share: "VIP", shipment: {address: {summary: "VIP", weight: 0.1}, birthDate: "2024-02-29", calc: {band: false, points: -0.1, review: 123456789.123}, companies: [{amount: 100, country: "VIP", parts: [], price: 0.25}], dueDate: "2000-01-01", eligible: null, flagged: false, rank: false, score: 123456789.123}}}, + {input: {shipment: {score: 10, dueDate: "2024-02-29", flagged: true, birthDate: "2024-01-01", companies: [{amount: 250, country: "a", price: 99.99, parts: [{years: 10}, {years: 0.5}, {years: 2}]}, {amount: 2, country: "none", price: 250, parts: [{years: 0.5}]}], address: null}}, goals: ["company.surcharge", "margin", "company.penalty"], output: {margin: "2025-01-01T00:00:00Z", shipment: {address: null, birthDate: "2024-01-01", companies: [{amount: 250, country: "a", parts: [{years: 10}, {years: 0.5}, {years: 2}], penalty: "A1-a", price: 99.99, surcharge: "A1-a"}, {amount: 2, country: "none", parts: [{years: 0.5}], penalty: "A1-none", price: 250, surcharge: "A1-none"}], dueDate: "2024-02-29", flagged: true, score: 10}}}, + {input: {shipment: {score: [1], dueDate: "1990-06-15", flagged: true, birthDate: "2000-01-01", since: "2024-01-01", companies: [{amount: 0.1, country: "DE", price: 100, parts: [{years: 65}, {years: -0}]}, {amount: 0.5, country: " pad ", price: 1e3, parts: [{years: 0.5}, {years: 50}]}], address: {weight: 0.1}}}, goals: ["company.flag", "shipment.eligible"], output: "!error: InputValidationFailed"}, + [{shipment: {score: 2, dueDate: "2025-03-20", flagged: true, birthDate: "2025-03-20T10:15:30Z", since: "1990-06-15", companies: [{amount: 65, country: "US", price: null, parts: [{years: 0.1}, {years: 7.25}]}], address: null}}, {margin: "1990-06-15", share: "0.5/true", shipment: {address: null, birthDate: "2025-03-20T10:15:30Z", calc: {band: true, points: -0, review: 2}, companies: [{amount: 65, capped: false, country: "US", flag: "low", meta: {total: [0, 2, 0]}, parts: [{years: 0.1}, {years: 7.25}], penalty: "A1-US", price: null}], dueDate: "2025-03-20", eligible: null, flagged: true, rank: true, score: 2, since: "1990-06-15"}}], + {input: {shipment: {score: 0.5, dueDate: "2025-03-20T10:15:30Z", flagged: true, birthDate: "1990-06-15", since: "2024-01-01", companies: [], address: {weight: 250}}}, goals: ["company.meta.total"], output: {share: "VIP", shipment: {address: {weight: 250}, birthDate: "1990-06-15", calc: {band: true, review: 0.5}, companies: [], dueDate: "2025-03-20T10:15:30Z", flagged: true, rank: true, score: 0.5, since: "2024-01-01"}}}, + {input: {shipment: {score: 1.5, dueDate: "2025-03-20T10:15:30Z", flagged: false, birthDate: "2000-01-01", since: "2024-02-29", companies: [{amount: 1, country: "US", price: -0.5, parts: [{years: 0.5}, {years: -0.01}, {years: 50}]}, {amount: 100, country: "US", price: 50, parts: [{years: 50}]}, {amount: -0, country: "low", price: 123456789.123, parts: [{years: 0.5}, {years: 0}, {years: 10}]}], address: {weight: 5}}}, goals: ["company.meta.total"], output: {share: "VIP", shipment: {address: {weight: 5}, birthDate: "2000-01-01", calc: {band: false, review: 1.5}, companies: [{amount: 1, country: "US", meta: {total: [5]}, parts: [{years: 0.5}, {years: -0.01}, {years: 50}], price: -0.5}, {amount: 100, country: "US", meta: {total: [5]}, parts: [{years: 50}], price: 50}, {amount: 0, country: "low", meta: {total: [5]}, parts: [{years: 0.5}, {years: 0}, {years: 10}], price: 123456789.123}], dueDate: "2025-03-20T10:15:30Z", flagged: false, rank: false, score: 1.5, since: "2024-02-29"}}}, + [{shipment: {score: 1.5, dueDate: "2025-03-20", flagged: true, birthDate: "2024-01-01", since: "2024-01-01", companies: [{amount: 3, country: "retail", price: 10, parts: []}, {amount: 2, country: "12", price: 5, parts: [{years: 0.25}, {years: 2}, {years: 3}]}], address: {weight: 5}}}, {margin: "2024-01-01", share: "VIP", shipment: {address: {summary: "VIP", weight: 5}, birthDate: "2024-01-01", calc: {band: true, points: -5, review: 1.5}, companies: [{amount: 3, capped: false, country: "retail", flag: "A1-RETAIL", meta: {total: [10, 5]}, parts: [], penalty: "A1-retail", price: 10, surcharge: "A1-retail"}, {amount: 2, capped: false, country: "12", flag: "A1-12", meta: {total: [5, 5]}, parts: [{years: 0.25}, {years: 2}, {years: 3}], penalty: "A1-12", price: 5, surcharge: "A1-12"}], dueDate: "2025-03-20", eligible: null, flagged: true, rank: true, score: 1.5, since: "2024-01-01"}}], + {input: {shipment: {score: 0, dueDate: "2000-01-01", flagged: false, birthDate: "2025-03-20T10:15:30Z", companies: [], address: null}}, goals: ["company.flag", "margin"], output: {margin: "2025-01-01T00:00:00Z", share: "VIP", shipment: {address: null, birthDate: "2025-03-20T10:15:30Z", calc: {band: false, review: 0}, companies: [], dueDate: "2000-01-01", flagged: false, rank: false, score: 0}}}, + [{shipment: {score: 2, dueDate: "2030-12-31", flagged: false, birthDate: "2025-03-20", since: "2000-01-01", companies: [], address: {weight: 100}}}, {margin: "2000-01-01", share: "0.5/false", shipment: {address: {summary: "0.5/false", weight: 100}, birthDate: "2025-03-20", calc: {band: false, points: -100, review: 2}, companies: [], dueDate: "2030-12-31", eligible: null, flagged: false, rank: false, score: 2, since: "2000-01-01"}}], + ], +} + +// seed 353800 (attempt 0) +{ + name: "goals 39: account/companies/parts: 2 assertion, 3 expression, 1 match, 1 table; 1 root, 7 per-member, 1 top-level computed", + policy: { + models: {account: {age: "number", amount: "number", rate: "number", code: "string", label: "string?", companies: "company[]"}, company: {weight: "number", birthDate: "date", kind: "string(retail|corporate)", insured: "boolean", parts: "part[]"}, part: {qty: "number"}}, + blocks: [ + {table: "t7", inputs: ["account.rate", "(company.margin.s ? company.weight : account.rate)", "company.adjusted"], outputs: ["company.total"], rules: [ + ["[50..466]", "< 0.25", "< 3", "company.weight"], + ["> 2", "0.5", "", "company.adjusted"], + ["1.5, 250", "< 1", "[0.5..128.5]", "company.adjusted"], + ["!= 2", "< 50", "[100..445]", "account.amount"], + ["", "", "", "decision"], + ]}, + {assertion: "account.meta.penalty", conditions: [["or", "not ((account.rate == 2 or account.rate > 250))", 0], ["or", "(account.amount == 250 and account.rate == 1000)", 1], "(account.amount in (38..158) and all(account.companies, #.weight >= #.weight))", "(account.amount in [6..121] and (account.age == 10 or account.amount <= 100))"]}, + {expression: "company.margin", value: "{s: some(account.companies, #.weight != #.weight), ok: company.weight in [-1..112]}"}, + {assertion: "company.grade", conditions: [["and", "some(account.companies, #.weight > 2)", 0], ["or", "account.amount in [41..66)", 0], ["and", "account.amount != company.adjusted", 2], ["and", "none(account.companies, #.weight != #.weight)", 0]]}, + {match: "decision", arms: [["account.label == null", "0.5"], ["account.code != 'Oslo'", "(account.meta.penalty ? account.amount : account.age)"], ["matches(`${account.rate}/${account.meta.penalty}`, '^[A-Z]')", "len(filter(account.companies, #.birthDate.isSameOrBefore(d('2025-01-01'), 'year')))"], ["matches(account.code, 'a')", "(count(account.companies, #.kind == 'corporate') * sum(map(account.companies, max([#.adjusted, #.adjusted]))))"], ["", "account.amount"]]}, + {expression: "company.flag", value: "filter(company.parts, not (#.qty == 1.5))"}, + {expression: "company.adjusted", value: "account.amount"}, + ], + }, + cases: [ + {input: {account: {age: 250, amount: -0, rate: 250, code: "", companies: [{weight: 3, birthDate: "2024-02-29", kind: "retail", insured: true, parts: [{qty: 1}, {qty: 10}]}]}}, goals: ["company.adjusted", "company.grade"], output: {account: {age: 250, amount: 0, code: "", companies: [{adjusted: 0, birthDate: "2024-02-29", grade: false, insured: true, kind: "retail", parts: [{qty: 1}, {qty: 10}], weight: 3}], rate: 250}}}, + {input: {account: {age: 250, amount: 2, rate: 2, code: "Oslo", label: null, companies: [{weight: 7.25, birthDate: "2024-01-01", kind: "retail", insured: false, parts: [{qty: 0.5}, {qty: 100}]}, {weight: 223, birthDate: "2024-02-29", kind: "retail", insured: true, parts: [{qty: -0}, {qty: 2}]}]}}, goals: ["company.grade"], output: {account: {age: 250, amount: 2, code: "Oslo", companies: [{adjusted: 2, birthDate: "2024-01-01", grade: false, insured: false, kind: "retail", parts: [{qty: 0.5}, {qty: 100}], weight: 7.25}, {adjusted: 2, birthDate: "2024-02-29", grade: false, insured: true, kind: "retail", parts: [{qty: 0}, {qty: 2}], weight: 223}], label: null, rate: 2}}}, + {input: {account: {age: 393, amount: 1.5, rate: 65, code: "é ü", label: null, companies: [{weight: 100, birthDate: "2024-01-01", kind: "retail", insured: true, parts: [{qty: 50}]}]}}, goals: ["company.flag", "company.grade", "company.adjusted"], output: {account: {age: 393, amount: 1.5, code: "é ü", companies: [{adjusted: 1.5, birthDate: "2024-01-01", flag: [{qty: 50}], grade: false, insured: true, kind: "retail", parts: [{qty: 50}], weight: 100}], label: null, rate: 65}}}, + [{account: {age: 2, amount: 65, rate: 250, code: "a-b-c", label: "US", companies: []}}, {account: {age: 2, amount: 65, code: "a-b-c", companies: [], label: "US", rate: 250}}], + [{account: {age: 50, amount: 250, rate: 250, code: "VIP", label: "DE", companies: []}}, {account: {age: 50, amount: 250, code: "VIP", companies: [], label: "DE", rate: 250}}], + {input: {account: {age: 123456789.123, amount: 1000, rate: -1, code: "Oslo", companies: [{weight: -0.01, birthDate: "2025-03-20", kind: "corporate", insured: false, parts: [{qty: 100}, {qty: 0.000001}]}, {weight: 0, birthDate: "2030-12-31", kind: "corporate", insured: false, parts: [{qty: 100}, {qty: 250}, {qty: 123456789.123}]}, {weight: 5, birthDate: "2024-02-29", kind: "retail", insured: true, parts: [{qty: 5}, {qty: 250}, {qty: 123456789.123}]}, {weight: 3, birthDate: "2025-03-20T10:15:30Z", kind: "retail", insured: true, parts: []}, {weight: 18, birthDate: "2025-03-20", kind: "corporate", insured: true, parts: [{qty: 0.5}, {qty: 2}, {qty: 123456789.123}]}, {weight: 1.5, birthDate: "2000-01-01", kind: "corporate", insured: true, parts: [{qty: 0.5}, {qty: 0}, {qty: 99999999999999999999}]}, {weight: -500, birthDate: "2025-03-20T10:15:30Z", kind: "retail", insured: true, parts: [{qty: 1e3}]}, {weight: 2, birthDate: "2025-03-20", kind: "retail", insured: false, parts: [{qty: 100}, {qty: 100}, {qty: 2.50}]}]}}, goals: ["company.adjusted", "company.flag"], output: {account: {age: 123456789.123, amount: 1000, code: "Oslo", companies: [{adjusted: 1000, birthDate: "2025-03-20", flag: [{qty: 100}, {qty: 0.000001}], insured: false, kind: "corporate", parts: [{qty: 100}, {qty: 0.000001}], weight: -0.01}, {adjusted: 1000, birthDate: "2030-12-31", flag: [{qty: 100}, {qty: 250}, {qty: 123456789.123}], insured: false, kind: "corporate", parts: [{qty: 100}, {qty: 250}, {qty: 123456789.123}], weight: 0}, {adjusted: 1000, birthDate: "2024-02-29", flag: [{qty: 5}, {qty: 250}, {qty: 123456789.123}], insured: true, kind: "retail", parts: [{qty: 5}, {qty: 250}, {qty: 123456789.123}], weight: 5}, {adjusted: 1000, birthDate: "2025-03-20T10:15:30Z", flag: [], insured: true, kind: "retail", parts: [], weight: 3}, {adjusted: 1000, birthDate: "2025-03-20", flag: [{qty: 0.5}, {qty: 2}, {qty: 123456789.123}], insured: true, kind: "corporate", parts: [{qty: 0.5}, {qty: 2}, {qty: 123456789.123}], weight: 18}, {adjusted: 1000, birthDate: "2000-01-01", flag: [{qty: 0.5}, {qty: 0}, {qty: 99999999999999999999}], insured: true, kind: "corporate", parts: [{qty: 0.5}, {qty: 0}, {qty: 99999999999999999999}], weight: 1.5}, {adjusted: 1000, birthDate: "2025-03-20T10:15:30Z", flag: [{qty: 1000}], insured: true, kind: "retail", parts: [{qty: 1000}], weight: -500}, {adjusted: 1000, birthDate: "2025-03-20", flag: [{qty: 100}, {qty: 100}, {qty: 2.50}], insured: false, kind: "retail", parts: [{qty: 100}, {qty: 100}, {qty: 2.50}], weight: 2}], rate: -1}}}, + {input: {account: {age: 0, amount: 0.000001, rate: 0.25, code: "Oslo", label: null, companies: [{weight: 250, birthDate: "2000-01-01", kind: "retail", insured: false, parts: [{qty: 123456789.123}, {qty: 250}, {qty: 10}]}, {weight: 99999999999999999999, birthDate: "2000-01-01", kind: "retail", insured: false, parts: []}, {weight: 50, birthDate: "2024-02-29", kind: "retail", insured: true, parts: [{qty: 250}, {qty: 2.50}]}, {weight: 250, birthDate: "2025-03-20T10:15:30Z", kind: "retail", insured: false, parts: [{qty: 10}]}, {weight: 10, birthDate: "2024-01-01", kind: "corporate", insured: false, parts: [{qty: 250}, {qty: 250}, {qty: 18}]}, {weight: 5, birthDate: "1990-06-15", kind: "retail", insured: false, parts: [{qty: 0}, {qty: 0.5}]}, {weight: 100, birthDate: "2025-03-20", kind: "retail", insured: true, parts: [{qty: 2}, {qty: 250}, {qty: 2}]}, {weight: 250, birthDate: "1990-06-15", kind: "corporate", insured: true, parts: [{qty: 50}, {qty: 250}]}]}}, goals: ["company.grade"], output: {account: {age: 0, amount: 0.000001, code: "Oslo", companies: [{adjusted: 0.000001, birthDate: "2000-01-01", grade: false, insured: false, kind: "retail", parts: [{qty: 123456789.123}, {qty: 250}, {qty: 10}], weight: 250}, {adjusted: 0.000001, birthDate: "2000-01-01", grade: false, insured: false, kind: "retail", parts: [], weight: 99999999999999999999}, {adjusted: 0.000001, birthDate: "2024-02-29", grade: false, insured: true, kind: "retail", parts: [{qty: 250}, {qty: 2.50}], weight: 50}, {adjusted: 0.000001, birthDate: "2025-03-20T10:15:30Z", grade: false, insured: false, kind: "retail", parts: [{qty: 10}], weight: 250}, {adjusted: 0.000001, birthDate: "2024-01-01", grade: false, insured: false, kind: "corporate", parts: [{qty: 250}, {qty: 250}, {qty: 18}], weight: 10}, {adjusted: 0.000001, birthDate: "1990-06-15", grade: false, insured: false, kind: "retail", parts: [{qty: 0}, {qty: 0.5}], weight: 5}, {adjusted: 0.000001, birthDate: "2025-03-20", grade: false, insured: true, kind: "retail", parts: [{qty: 2}, {qty: 250}, {qty: 2}], weight: 100}, {adjusted: 0.000001, birthDate: "1990-06-15", grade: false, insured: true, kind: "corporate", parts: [{qty: 50}, {qty: 250}], weight: 250}], label: null, rate: 0.25}}}, + {input: {account: {age: 250, amount: 18, rate: 2.50, code: "A1", label: null, companies: [{weight: -0.01, birthDate: "2030-12-31", kind: "retail", insured: true, parts: [{qty: 1000000}, {qty: 100}]}, {weight: 250, birthDate: "2000-01-01", kind: "retail", insured: false, parts: [{qty: 7.25}, {qty: 1.5}, {qty: 123456789.123}]}]}}, goals: ["company.grade", "account.meta.penalty", "company.flag"], output: {account: {age: 250, amount: 18, code: "A1", companies: [{adjusted: 18, birthDate: "2030-12-31", flag: [{qty: 1000000}, {qty: 100}], grade: false, insured: true, kind: "retail", parts: [{qty: 1000000}, {qty: 100}], weight: -0.01}, {adjusted: 18, birthDate: "2000-01-01", flag: [{qty: 7.25}, {qty: 123456789.123}], grade: false, insured: false, kind: "retail", parts: [{qty: 7.25}, {qty: 1.5}, {qty: 123456789.123}], weight: 250}], label: null, meta: {penalty: true}, rate: 2.50}}}, + {input: {account: {age: 5, amount: 7.25, rate: 7.25, code: "Oslo", label: "Oslo", companies: [{weight: 1, birthDate: "2024-01-01", kind: "corporate", insured: true, parts: [{qty: 2}, {qty: 0.5}, {qty: 250}]}, {weight: 2, birthDate: "2024-01-01", kind: "corporate", insured: false, parts: [{qty: 0.25}, {qty: 99999999999999999999}]}]}}, goals: ["company.flag", "company.grade", "company.margin"], output: {account: {age: 5, amount: 7.25, code: "Oslo", companies: [{adjusted: 7.25, birthDate: "2024-01-01", flag: [{qty: 2}, {qty: 0.5}, {qty: 250}], grade: false, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [{qty: 2}, {qty: 0.5}, {qty: 250}], weight: 1}, {adjusted: 7.25, birthDate: "2024-01-01", flag: [{qty: 0.25}, {qty: 99999999999999999999}], grade: false, insured: false, kind: "corporate", margin: {ok: true, s: false}, parts: [{qty: 0.25}, {qty: 99999999999999999999}], weight: 2}], label: "Oslo", rate: 7.25}}}, + [{account: {age: -0.01, amount: 50, rate: 50, code: "gold", label: "VIP", companies: [{weight: 250, birthDate: "2024-01-01", kind: "retail", insured: true, parts: []}, {weight: 1, birthDate: "2025-03-20T10:15:30Z", kind: "corporate", insured: false, parts: [{qty: 1000}, {qty: 123456789.123}]}]}}, {account: {age: -0.01, amount: 50, code: "gold", companies: [{adjusted: 50, birthDate: "2024-01-01", flag: [], grade: true, insured: true, kind: "retail", margin: {ok: false, s: false}, parts: [], total: 50, weight: 250}, {adjusted: 50, birthDate: "2025-03-20T10:15:30Z", flag: [{qty: 1000}, {qty: 123456789.123}], grade: true, insured: false, kind: "corporate", margin: {ok: true, s: false}, parts: [{qty: 1000}, {qty: 123456789.123}], total: 50, weight: 1}], label: "VIP", meta: {penalty: true}, rate: 50}, decision: 50}], + [{account: {age: 0.5, amount: 0.000001, rate: 10, code: "Oslo", label: "A1", companies: [{weight: 0.5, birthDate: "2030-12-31", kind: "corporate", insured: true, parts: []}, {weight: 5, birthDate: "2024-02-29", kind: "retail", insured: true, parts: [{qty: 1}, {qty: 0.5}]}]}}, {account: {age: 0.5, amount: 0.000001, code: "Oslo", companies: [{adjusted: 0.000001, birthDate: "2030-12-31", flag: [], grade: false, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [], total: 0.000001, weight: 0.5}, {adjusted: 0.000001, birthDate: "2024-02-29", flag: [{qty: 1}, {qty: 0.5}], grade: false, insured: true, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 1}, {qty: 0.5}], total: 0.000001, weight: 5}], label: "A1", meta: {penalty: false}, rate: 10}, decision: 0.000001}], + {input: {account: {age: 0.25, amount: 5, rate: 3, code: "Oslo", label: "US", companies: []}}, goals: ["company.total", "company.margin"], output: {account: {age: 0.25, amount: 5, code: "Oslo", companies: [], label: "US", rate: 3}}}, + [{account: {age: 1000, amount: 161, rate: -500, code: "DE", companies: [{weight: -0, birthDate: "2030-12-31", kind: "corporate", insured: true, parts: []}, {weight: -1, birthDate: "2030-12-31", kind: "corporate", insured: false, parts: [{qty: 1e3}, {qty: 250}]}]}}, {account: {age: 1000, amount: 161, code: "DE", companies: [{adjusted: 161, birthDate: "2030-12-31", flag: [], grade: false, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [], total: 161, weight: 0}, {adjusted: 161, birthDate: "2030-12-31", flag: [{qty: 1000}, {qty: 250}], grade: false, insured: false, kind: "corporate", margin: {ok: true, s: false}, parts: [{qty: 1000}, {qty: 250}], total: 161, weight: -1}], rate: -500}}], + {input: {account: {age: 100, amount: 250, rate: 250, code: "NL", companies: [{weight: 100, birthDate: "2030-12-31", kind: "retail", insured: false, parts: [{qty: 0.1}, {qty: 250}, {qty: -0.01}]}, {weight: -500, birthDate: "1990-06-15", kind: "corporate", insured: true, parts: [{qty: 1000}, {qty: 7.25}, {qty: 100}]}]}}, goals: ["company.grade", "company.total"], output: {account: {age: 100, amount: 250, code: "NL", companies: [{adjusted: 250, birthDate: "2030-12-31", grade: false, insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 0.1}, {qty: 250}, {qty: -0.01}], total: 0.5, weight: 100}, {adjusted: 250, birthDate: "1990-06-15", grade: false, insured: true, kind: "corporate", margin: {ok: false, s: false}, parts: [{qty: 1000}, {qty: 7.25}, {qty: 100}], total: 0.5, weight: -500}], meta: {penalty: false}, rate: 250}, decision: 0.5}}, + {input: {account: {age: 50, amount: 50, rate: 5, code: "VIP", label: "A1", companies: [{weight: 1000, kind: "retail", insured: false, parts: []}]}}, goals: ["decision"], output: {account: {age: 50, amount: 50, code: "VIP", companies: [{insured: false, kind: "retail", parts: [], weight: 1000}], label: "A1", meta: {penalty: true}, rate: 5}, decision: 50}}, + {input: {account: {age: 0.25, amount: 250, rate: 100, code: "VIP", label: "a", companies: [{weight: 1, birthDate: "2000-01-01", kind: "corporate", insured: false, parts: [{qty: 1000}, {qty: 18}]}]}}, goals: ["decision"], output: {account: {age: 0.25, amount: 250, code: "VIP", companies: [{birthDate: "2000-01-01", insured: false, kind: "corporate", parts: [{qty: 1000}, {qty: 18}], weight: 1}], label: "a", meta: {penalty: false}, rate: 100}, decision: 0.25}}, + {input: {account: {age: 0.25, amount: 1e3, rate: 0.5, code: "US", label: null, companies: [{weight: 10, birthDate: "2024-01-01", kind: "retail", insured: false, parts: [{qty: 5}, {qty: 123456789.123}]}, {weight: 0.5, birthDate: "2025-03-20T10:15:30Z", kind: "retail", insured: false, parts: [{qty: 1.5}, {qty: 18}]}, {weight: -1, birthDate: "2030-12-31", kind: "corporate", insured: false, parts: []}, {weight: 1000, birthDate: "2025-03-20T10:15:30Z", kind: "retail", insured: true, parts: [{qty: 1000}, {qty: 1}]}]}}, goals: ["company.grade", "decision"], output: {account: {age: 0.25, amount: 1000, code: "US", companies: [{adjusted: 1000, birthDate: "2024-01-01", grade: false, insured: false, kind: "retail", parts: [{qty: 5}, {qty: 123456789.123}], weight: 10}, {adjusted: 1000, birthDate: "2025-03-20T10:15:30Z", grade: false, insured: false, kind: "retail", parts: [{qty: 1.5}, {qty: 18}], weight: 0.5}, {adjusted: 1000, birthDate: "2030-12-31", grade: false, insured: false, kind: "corporate", parts: [], weight: -1}, {adjusted: 1000, birthDate: "2025-03-20T10:15:30Z", grade: false, insured: true, kind: "retail", parts: [{qty: 1000}, {qty: 1}], weight: 1000}], label: null, meta: {penalty: false}, rate: 0.5}, decision: 0.5}}, + [{account: {age: 2, amount: 50, rate: 250, code: "abc", label: " pad ", companies: [{weight: 0.5, birthDate: "2000-01-01", kind: "retail", insured: true, parts: [{qty: 352}, {qty: 2.50}, {qty: 1.5}]}, {weight: 100, birthDate: "2025-03-20T10:15:30Z", kind: "corporate", insured: true, parts: [{qty: -0}]}, {weight: 2, birthDate: "2030-12-31", kind: "retail", insured: false, parts: [{qty: 10}, {qty: -0.01}]}, {weight: 10, birthDate: "2025-03-20", kind: "retail", insured: false, parts: [{qty: 2.50}]}, {weight: 65, birthDate: "2025-03-20", kind: "corporate", insured: true, parts: []}, {weight: 1000, birthDate: "2024-01-01", kind: "retail", insured: true, parts: []}, {weight: 5, birthDate: "2024-02-29", kind: "retail", insured: false, parts: [{qty: 1.5}, {qty: 0.5}]}, {weight: 0, birthDate: "2025-03-20T10:15:30Z", kind: "retail", insured: false, parts: []}, {weight: 100, birthDate: "2024-02-29", kind: "corporate", insured: true, parts: [{qty: -1}, {qty: 99999999999999999999}, {qty: -0.01}]}, {weight: 0.000001, birthDate: "2030-12-31", kind: "corporate", insured: true, parts: [{qty: 50}, {qty: 1}, {qty: 0.5}]}]}}, {account: {age: 2, amount: 50, code: "abc", companies: [{adjusted: 50, birthDate: "2000-01-01", flag: [{qty: 352}, {qty: 2.50}], grade: true, insured: true, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 352}, {qty: 2.50}, {qty: 1.5}], total: 50, weight: 0.5}, {adjusted: 50, birthDate: "2025-03-20T10:15:30Z", flag: [{qty: 0}], grade: true, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [{qty: 0}], total: 50, weight: 100}, {adjusted: 50, birthDate: "2030-12-31", flag: [{qty: 10}, {qty: -0.01}], grade: true, insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 10}, {qty: -0.01}], total: 50, weight: 2}, {adjusted: 50, birthDate: "2025-03-20", flag: [{qty: 2.50}], grade: true, insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 2.50}], total: 50, weight: 10}, {adjusted: 50, birthDate: "2025-03-20", flag: [], grade: true, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [], total: 50, weight: 65}, {adjusted: 50, birthDate: "2024-01-01", flag: [], grade: true, insured: true, kind: "retail", margin: {ok: false, s: false}, parts: [], total: 50, weight: 1000}, {adjusted: 50, birthDate: "2024-02-29", flag: [{qty: 0.5}], grade: true, insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 1.5}, {qty: 0.5}], total: 50, weight: 5}, {adjusted: 50, birthDate: "2025-03-20T10:15:30Z", flag: [], grade: true, insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [], total: 50, weight: 0}, {adjusted: 50, birthDate: "2024-02-29", flag: [{qty: -1}, {qty: 99999999999999999999}, {qty: -0.01}], grade: true, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [{qty: -1}, {qty: 99999999999999999999}, {qty: -0.01}], total: 50, weight: 100}, {adjusted: 50, birthDate: "2030-12-31", flag: [{qty: 50}, {qty: 1}, {qty: 0.5}], grade: true, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [{qty: 50}, {qty: 1}, {qty: 0.5}], total: 50, weight: 0.000001}], label: " pad ", meta: {penalty: true}, rate: 250}, decision: 50}], + {input: {account: {age: 1000, amount: 2.50, rate: -500, code: "Oslo", label: "Zed", companies: []}}, goals: ["decision", "company.flag"], output: {account: {age: 1000, amount: 2.50, code: "Oslo", companies: [], label: "Zed", meta: {penalty: false}, rate: -500}, decision: 2.50}}, + {input: {account: {age: 3, amount: 50, rate: 0.25, code: "a", companies: []}}, goals: ["company.adjusted"], output: {account: {age: 3, amount: 50, code: "a", companies: [], rate: 0.25}}}, + {input: {account: {age: 0.5, amount: 18, rate: 0.000001, code: "-", label: "a", companies: [{weight: 7.25, birthDate: "2025-03-20", kind: "retail", insured: false, parts: [{qty: 10}]}, {weight: 99.99, birthDate: "2025-03-20", kind: "retail", insured: true, parts: [{qty: 0.5}]}]}}, goals: ["company.margin", "decision", "company.adjusted"], output: {account: {age: 0.5, amount: 18, code: "-", companies: [{adjusted: 18, birthDate: "2025-03-20", insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 10}], weight: 7.25}, {adjusted: 18, birthDate: "2025-03-20", insured: true, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 0.5}], weight: 99.99}], label: "a", meta: {penalty: true}, rate: 0.000001}, decision: 18}}, + {input: {account: {age: 250, amount: 250, rate: 1000, code: "日本", label: "VIP", companies: []}}, goals: ["company.grade", "company.total"], output: {account: {age: 250, amount: 250, code: "日本", companies: [], label: "VIP", rate: 1000}}}, + {input: {account: {age: 7.25, amount: 123456789.123, rate: -0, code: "abc", label: "US", companies: [{weight: 1000, birthDate: "2024-01-01", kind: "retail", insured: true, parts: [{qty: 7.25}, {qty: -0.5}]}, {weight: 250, birthDate: "2000-01-01", kind: "retail", insured: false, parts: [{qty: 3}, {qty: 0.000001}]}, {weight: 1000, birthDate: "2025-03-20", kind: "retail", insured: false, parts: [{qty: 2}, {qty: -0.5}]}, {weight: 5, birthDate: "2025-03-20", kind: "retail", insured: true, parts: [{qty: 158}, {qty: 10}, {qty: 1e3}]}]}}, goals: ["company.adjusted"], output: {account: {age: 7.25, amount: 123456789.123, code: "abc", companies: [{adjusted: 123456789.123, birthDate: "2024-01-01", insured: true, kind: "retail", parts: [{qty: 7.25}, {qty: -0.5}], weight: 1000}, {adjusted: 123456789.123, birthDate: "2000-01-01", insured: false, kind: "retail", parts: [{qty: 3}, {qty: 0.000001}], weight: 250}, {adjusted: 123456789.123, birthDate: "2025-03-20", insured: false, kind: "retail", parts: [{qty: 2}, {qty: -0.5}], weight: 1000}, {adjusted: 123456789.123, birthDate: "2025-03-20", insured: true, kind: "retail", parts: [{qty: 158}, {qty: 10}, {qty: 1000}], weight: 5}], label: "US", rate: 0}}}, + [{account: {age: -0.01, amount: "12", rate: 499, code: "DE", label: "none", companies: [{weight: 250, birthDate: "2024-01-01", kind: "retail", insured: false, parts: []}, {weight: 0, birthDate: "2024-02-29", kind: "retail", insured: false, parts: [{qty: -1}, {qty: 1000000}]}, {weight: -1, birthDate: "2030-12-31", kind: "corporate", insured: true, parts: [{qty: 250}, {qty: 5}]}, {weight: 250, birthDate: "2025-03-20", kind: "corporate", insured: false, parts: [{qty: 2}]}, {weight: 10, birthDate: "1990-06-15", kind: "corporate", insured: false, parts: []}]}}, "!error: InputValidationFailed"], + {input: {account: {amount: 1.5, rate: 0.1, code: "VIP", label: "US", companies: [{weight: 1000, birthDate: "2025-03-20T10:15:30Z", kind: "corporate", insured: false, parts: [{qty: 250}, {qty: 1}]}]}}, goals: ["company.flag", "account.meta.penalty", "company.adjusted"], output: "!error: MissingRequiredInputs"}, + {input: {account: {age: 7.25, amount: 250, rate: 3, code: "3.5", label: "Oslo", companies: [{weight: 0.000001, birthDate: "2024-01-01", kind: "corporate", insured: true, parts: []}, {weight: 5, birthDate: "2024-01-01", kind: "retail", insured: false, parts: [{qty: 1.5}, {qty: 18}, {qty: 1}]}, {weight: -0.5, birthDate: "2024-02-29", kind: "corporate", insured: true, parts: []}]}}, goals: ["company.grade", "company.total"], output: {account: {age: 7.25, amount: 250, code: "3.5", companies: [{adjusted: 250, birthDate: "2024-01-01", grade: false, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [], total: 250, weight: 0.000001}, {adjusted: 250, birthDate: "2024-01-01", grade: false, insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 1.5}, {qty: 18}, {qty: 1}], total: 250, weight: 5}, {adjusted: 250, birthDate: "2024-02-29", grade: false, insured: true, kind: "corporate", margin: {ok: true, s: false}, parts: [], total: 250, weight: -0.5}], label: "Oslo", rate: 3}}}, + {input: {account: {age: 5, amount: 1.5, rate: 123456789.123, code: "US", companies: [{weight: 2, birthDate: "2000-01-01", kind: "retail", insured: false, parts: [{qty: 250}, {qty: 0.1}, {qty: 18}]}, {weight: 100, birthDate: "2024-02-29", kind: "retail", insured: false, parts: [{qty: 250}]}, {weight: 50, birthDate: "2024-02-29", kind: "retail", insured: true, parts: [{qty: 1}, {qty: -0.5}]}]}}, goals: ["account.meta.penalty", "company.margin", "decision"], output: {account: {age: 5, amount: 1.5, code: "US", companies: [{birthDate: "2000-01-01", insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 250}, {qty: 0.1}, {qty: 18}], weight: 2}, {birthDate: "2024-02-29", insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 250}], weight: 100}, {birthDate: "2024-02-29", insured: true, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 1}, {qty: -0.5}], weight: 50}], meta: {penalty: false}, rate: 123456789.123}, decision: 0.5}}, + {input: {account: {age: 0.5, amount: 65, rate: 5, code: "retail", label: "VIP", companies: [{weight: 250, birthDate: "2025-03-20", kind: "retail", insured: false, parts: [{qty: 1.5}, {qty: 250}, {qty: 250}]}, {weight: 1.5, birthDate: "2024-02-29", kind: "retail", insured: false, parts: [{qty: 250}, {qty: 250}]}, {weight: 250, birthDate: "2024-01-01", kind: "retail", insured: true, parts: [{qty: 0.25}, {qty: 3}]}, {weight: 0.5, birthDate: "2030-12-31", kind: "corporate", insured: true, parts: []}, {weight: -500, birthDate: "2025-03-20", kind: "retail", insured: true, parts: [{qty: 2.50}]}, {weight: 18, birthDate: "2000-01-01", kind: "corporate", insured: false, parts: [{qty: 1000}]}, {weight: 2.50, birthDate: "2030-12-31", kind: "corporate", insured: false, parts: [{qty: 250}]}, {weight: 50, birthDate: "2024-02-29", kind: "retail", insured: true, parts: [{qty: 50}, {qty: 0.5}]}, {weight: 2, birthDate: "2025-03-20", kind: "retail", insured: true, parts: [{qty: 10}, {qty: 50}, {qty: 18}]}, {weight: 250, birthDate: "2000-01-01", kind: "retail", insured: true, parts: [{qty: 1}, {qty: 5}]}, {weight: 250, birthDate: "1990-06-15", kind: "retail", insured: false, parts: [{qty: 2}]}, {weight: 100, birthDate: "2025-03-20T10:15:30Z", kind: "retail", insured: true, parts: [{qty: 10}, {qty: 50}, {qty: 327}]}, {weight: 100, birthDate: "2024-01-01", kind: "retail", insured: false, parts: [{qty: 1}, {qty: 50}]}], extraField: 1}}, goals: ["decision"], output: {account: {age: 0.5, amount: 65, code: "retail", companies: [{birthDate: "2025-03-20", insured: false, kind: "retail", parts: [{qty: 1.5}, {qty: 250}, {qty: 250}], weight: 250}, {birthDate: "2024-02-29", insured: false, kind: "retail", parts: [{qty: 250}, {qty: 250}], weight: 1.5}, {birthDate: "2024-01-01", insured: true, kind: "retail", parts: [{qty: 0.25}, {qty: 3}], weight: 250}, {birthDate: "2030-12-31", insured: true, kind: "corporate", parts: [], weight: 0.5}, {birthDate: "2025-03-20", insured: true, kind: "retail", parts: [{qty: 2.50}], weight: -500}, {birthDate: "2000-01-01", insured: false, kind: "corporate", parts: [{qty: 1000}], weight: 18}, {birthDate: "2030-12-31", insured: false, kind: "corporate", parts: [{qty: 250}], weight: 2.50}, {birthDate: "2024-02-29", insured: true, kind: "retail", parts: [{qty: 50}, {qty: 0.5}], weight: 50}, {birthDate: "2025-03-20", insured: true, kind: "retail", parts: [{qty: 10}, {qty: 50}, {qty: 18}], weight: 2}, {birthDate: "2000-01-01", insured: true, kind: "retail", parts: [{qty: 1}, {qty: 5}], weight: 250}, {birthDate: "1990-06-15", insured: false, kind: "retail", parts: [{qty: 2}], weight: 250}, {birthDate: "2025-03-20T10:15:30Z", insured: true, kind: "retail", parts: [{qty: 10}, {qty: 50}, {qty: 327}], weight: 100}, {birthDate: "2024-01-01", insured: false, kind: "retail", parts: [{qty: 1}, {qty: 50}], weight: 100}], extraField: 1, label: "VIP", meta: {penalty: true}, rate: 5}, decision: 65}}, + {input: {account: {age: 435, amount: 2, rate: 18, code: " pad ", label: "a-b-c", companies: [{weight: 0, birthDate: "2000-01-01", kind: "retail", insured: false, parts: [{qty: 2}]}]}}, goals: ["company.flag", "company.adjusted", "company.margin"], output: {account: {age: 435, amount: 2, code: " pad ", companies: [{adjusted: 2, birthDate: "2000-01-01", flag: [{qty: 2}], insured: false, kind: "retail", margin: {ok: true, s: false}, parts: [{qty: 2}], weight: 0}], label: "a-b-c", rate: 18}}}, + {input: {account: {age: 10, amount: 1000, rate: 250, code: "a-b-c", label: "Oslo", companies: [{weight: 1000, birthDate: "2024-02-29", kind: false, insured: false, parts: []}, {weight: 50, birthDate: "2024-02-29", kind: "corporate", insured: false, parts: []}, {weight: 0.000001, birthDate: "2024-02-29", kind: "corporate", insured: true, parts: [{qty: 0.5}]}, {weight: 3, birthDate: "2024-01-01", kind: "retail", insured: true, parts: [{qty: 18}]}]}}, goals: ["company.flag", "account.meta.penalty"], output: "!error: InputValidationFailed"}, + ], +} + +// seed 353901 (attempt 1) +{ + name: "goals 40: claim/vehicles: 3 expression, 2 match; 1 root, 6 per-member, 1 top-level computed", + policy: { + models: {claim: {age: "number?", years: "number", amount: "number?", priority: "boolean?", vip: "boolean?", active: "boolean?", vehicles: "vehicle[]?"}, vehicle: {balance: "number?", qty: "number", label: "string"}}, + blocks: [ + {expression: "claim.meta.fee", value: "claim.vip"}, + {match: "vehicle.risk", arms: [["(claim.amount ?? 0) in (2..114]", "contains((vehicle.label + '-' + vehicle.label), 'high')"], ["", "(claim.meta.fee ?? false)"]]}, + {expression: "net", value: "min([(claim.amount ?? 0), (((claim.amount ?? 0) + claim.years) / -6)])"}, + {expression: "vehicle.tag", value: "{s: contains(['A1', 'none', ''], vehicle.label), a: sum([((claim.age ?? 0) + vehicle.qty), ((claim.age ?? 0) * (claim.age ?? 0))]), ok: (claim.age ?? 0)}"}, + {match: "vehicle.flag", arms: [["(claim.age ?? 0) >= (claim.age ?? 0)", "(avg(map((claim.vehicles ?? []), (#.balance ?? 0))) ?? 0)"], ["some((claim.vehicles ?? []), not (#.risk))", "vehicle.tag.a"], ["matches((split(vehicle.label, '-')[0] ?? 'none'), '[0-9]$')", "(min([abs(sum([net])), 1000]) ^ 2)"], ["", "(claim.amount ?? 0)"]]}, + ], + }, + cases: [ + {input: {claim: {age: 7.25, years: 0, amount: 268, priority: false, vip: false, active: null, vehicles: [{balance: null, qty: 2, label: "a-b-c"}, {balance: null, qty: 18, label: "abc"}, {balance: 65, qty: -0.01, label: "none"}]}}, goals: ["vehicle.flag", "vehicle.tag"], output: {claim: {active: null, age: 7.25, amount: 268, meta: {fee: false}, priority: false, vehicles: [{balance: null, flag: 21.666666666666666666666666667, label: "a-b-c", qty: 2, risk: false, tag: {a: 61.8125, ok: 7.25, s: false}}, {balance: null, flag: 21.666666666666666666666666667, label: "abc", qty: 18, risk: false, tag: {a: 77.8125, ok: 7.25, s: false}}, {balance: 65, flag: 21.666666666666666666666666667, label: "none", qty: -0.01, risk: false, tag: {a: 59.8025, ok: 7.25, s: true}}], vip: false, years: 0}}}, + {input: {claim: {age: 65, years: 250, priority: false, vip: true, active: true, vehicles: [{balance: null, qty: -500, label: "-"}, {balance: null, qty: 1, label: ""}, {qty: 250, label: "abc"}, {qty: 65, label: "3.5"}, {balance: null, qty: 1, label: "A1"}]}}, goals: ["vehicle.risk", "vehicle.tag", "vehicle.flag"], output: {claim: {active: true, age: 65, meta: {fee: true}, priority: false, vehicles: [{balance: null, flag: 0, label: "-", qty: -500, risk: true, tag: {a: 3790, ok: 65, s: false}}, {balance: null, flag: 0, label: "", qty: 1, risk: true, tag: {a: 4291, ok: 65, s: true}}, {flag: 0, label: "abc", qty: 250, risk: true, tag: {a: 4540, ok: 65, s: false}}, {flag: 0, label: "3.5", qty: 65, risk: true, tag: {a: 4355, ok: 65, s: false}}, {balance: null, flag: 0, label: "A1", qty: 1, risk: true, tag: {a: 4291, ok: 65, s: true}}], vip: true, years: 250}}}, + {input: {claim: {years: 0.000001, priority: false, vip: true, active: true, vehicles: [{qty: 100, label: "é ü"}, {qty: 123456789.123, label: "a-b-c"}, {balance: null, qty: 1000000, label: "-"}]}}, goals: ["vehicle.flag"], output: {claim: {active: true, meta: {fee: true}, priority: false, vehicles: [{flag: 0, label: "é ü", qty: 100, risk: true}, {flag: 0, label: "a-b-c", qty: 123456789.123, risk: true}, {balance: null, flag: 0, label: "-", qty: 1000000, risk: true}], vip: true, years: 0.000001}}}, + {input: {claim: {age: -500, years: -0.01, amount: 1000, priority: false, vip: false, active: true, vehicles: [{balance: 1e3, qty: 100, label: "-"}, {balance: -500, qty: 99.99, label: "A1"}, {balance: 1e3, qty: 18, label: "O'Neil"}, {balance: 123456789.123, qty: -0, label: ""}]}}, goals: ["net", "vehicle.risk", "claim.meta.fee"], output: {claim: {active: true, age: -500, amount: 1000, meta: {fee: false}, priority: false, vehicles: [{balance: 1000, label: "-", qty: 100, risk: false}, {balance: -500, label: "A1", qty: 99.99, risk: false}, {balance: 1000, label: "O'Neil", qty: 18, risk: false}, {balance: 123456789.123, label: "", qty: 0, risk: false}], vip: false, years: -0.01}, net: -166.6650}}, + {input: {claim: {age: 0.1, years: 1, amount: -0, priority: true, vip: false, active: false, vehicles: [{balance: -0, qty: -0, label: "A1"}]}}, goals: ["vehicle.tag", "vehicle.risk", "net"], output: {claim: {active: false, age: 0.1, amount: 0, meta: {fee: false}, priority: true, vehicles: [{balance: 0, label: "A1", qty: 0, risk: false, tag: {a: 0.11, ok: 0.1, s: true}}], vip: false, years: 1}, net: -0.1666666666666666666666666667}}, + {input: {claim: {age: 1000, years: -0, amount: 100, priority: false, vip: false, active: true, vehicles: []}}, goals: ["vehicle.flag"], output: {claim: {active: true, age: 1000, amount: 100, priority: false, vehicles: [], vip: false, years: 0}}}, + {input: {claim: {years: 250, amount: 2.50, priority: true, active: false, vehicles: []}}, goals: ["vehicle.risk"], output: {claim: {active: false, amount: 2.50, priority: true, vehicles: [], years: 250}}}, + {input: {claim: {age: 1000000, years: -500, amount: 65, priority: true, vip: false, active: true, vehicles: [{balance: 99999999999999999999, qty: 1000000, label: "a-b-c"}, {balance: -0.01, qty: 0.1, label: "NL"}, {balance: 65, qty: -0.01, label: "Oslo"}, {balance: 99.99, qty: 7.25, label: "é ü"}, {balance: 18, qty: 2, label: ""}]}}, goals: ["net"], output: {claim: {active: true, age: 1000000, amount: 65, priority: true, vehicles: [{balance: 99999999999999999999, label: "a-b-c", qty: 1000000}, {balance: -0.01, label: "NL", qty: 0.1}, {balance: 65, label: "Oslo", qty: -0.01}, {balance: 99.99, label: "é ü", qty: 7.25}, {balance: 18, label: "", qty: 2}], vip: false, years: -500}, net: 65}}, + {input: {claim: {age: 55, years: 0.000001, amount: 0.000001, priority: false, vip: false, active: false, vehicles: [{balance: 250, qty: 10, label: "Oslo"}, {balance: -0.01, qty: 2.50, label: "gold"}]}}, goals: ["net"], output: {claim: {active: false, age: 55, amount: 0.000001, priority: false, vehicles: [{balance: 250, label: "Oslo", qty: 10}, {balance: -0.01, label: "gold", qty: 2.50}], vip: false, years: 0.000001}, net: -0.0000003333333333333333333333}}, + {input: {claim: {age: 0.000001, years: 5, amount: 1, priority: false, vip: true, active: true, vehicles: []}}, goals: ["vehicle.risk", "claim.meta.fee"], output: {claim: {active: true, age: 0.000001, amount: 1, meta: {fee: true}, priority: false, vehicles: [], vip: true, years: 5}}}, + {input: {claim: {age: 123456789.123, years: 0.000001, amount: 2.50, priority: true, vip: true, active: true, vehicles: [{balance: 1e3, qty: null, label: " pad "}, {balance: 1e3, qty: 0.1, label: " pad "}]}}, goals: ["vehicle.flag"], output: {claim: {active: true, age: 123456789.123, amount: 2.50, priority: true, vehicles: [{balance: 1000, flag: 1000, label: " pad ", qty: null, risk: false}, {balance: 1000, flag: 1000, label: " pad ", qty: 0.1, risk: false}], vip: true, years: 0.000001}}}, + {input: {claim: {age: null, years: 1000000, amount: -0.5, priority: null, vip: true, active: null, vehicles: [{balance: null, qty: 239, label: "A1"}]}}, goals: ["net", "vehicle.risk", "vehicle.flag"], output: {claim: {active: null, age: null, amount: -0.5, meta: {fee: true}, priority: null, vehicles: [{balance: null, flag: 0, label: "A1", qty: 239, risk: true}], vip: true, years: 1000000}, net: -166666.58333333333333333333333}}, + {input: {claim: {age: 1e3, years: 2, amount: 99999999999999999999, priority: true, vip: false, active: true, vehicles: [{balance: 100, qty: 100, label: "O'Neil"}, {balance: 0, qty: 1, label: "VIP"}, {balance: 7.25, qty: 250, label: " pad "}]}}, goals: ["net", "vehicle.risk", "claim.meta.fee"], output: {claim: {active: true, age: 1000, amount: 99999999999999999999, meta: {fee: false}, priority: true, vehicles: [{balance: 100, label: "O'Neil", qty: 100, risk: false}, {balance: 0, label: "VIP", qty: 1, risk: false}, {balance: 7.25, label: " pad ", qty: 250, risk: false}], vip: false, years: 2}, net: -16666666666666666666.833333333}}, + {input: {claim: {age: 0, years: 18, amount: 100, priority: true, vip: null, active: true, vehicles: [{qty: 1e3, label: "A1"}, {balance: 100, qty: 250, label: "abc"}, {balance: null, qty: 123456789.123, label: "none"}]}}, goals: ["vehicle.flag", "net", "claim.meta.fee"], output: {claim: {active: true, age: 0, amount: 100, meta: {fee: null}, priority: true, vehicles: [{flag: 33.333333333333333333333333333, label: "A1", qty: 1000, risk: false}, {balance: 100, flag: 33.333333333333333333333333333, label: "abc", qty: 250, risk: false}, {balance: null, flag: 33.333333333333333333333333333, label: "none", qty: 123456789.123, risk: false}], vip: null, years: 18}, net: -19.666666666666666666666666667}}, + {input: {claim: {age: 0, years: 18, amount: 65, priority: false, vip: false, active: false, vehicles: [{balance: 28, qty: 0, label: " pad "}, {balance: 100, qty: 0.1, label: "high"}, {balance: 1, qty: 99999999999999999999, label: "US"}, {balance: 123456789.123, qty: 99999999999999999999, label: "high"}, {balance: -1, qty: 1000000, label: "x-y"}], extraField: 1}}, goals: ["vehicle.flag", "vehicle.tag"], output: {claim: {active: false, age: 0, amount: 65, extraField: 1, priority: false, vehicles: [{balance: 28, flag: 24691383.42460, label: " pad ", qty: 0, risk: false, tag: {a: 0, ok: 0, s: false}}, {balance: 100, flag: 24691383.42460, label: "high", qty: 0.1, risk: true, tag: {a: 0.1, ok: 0, s: false}}, {balance: 1, flag: 24691383.42460, label: "US", qty: 99999999999999999999, risk: false, tag: {a: 99999999999999999999, ok: 0, s: false}}, {balance: 123456789.123, flag: 24691383.42460, label: "high", qty: 99999999999999999999, risk: true, tag: {a: 99999999999999999999, ok: 0, s: false}}, {balance: -1, flag: 24691383.42460, label: "x-y", qty: 1000000, risk: false, tag: {a: 1000000, ok: 0, s: false}}], vip: false, years: 18}}}, + [{claim: {age: 0, years: -0.5, amount: 1, priority: false, vip: true, active: null, vehicles: [{qty: -0.01, label: "high"}, {qty: 1000000, label: "3.5"}]}}, {claim: {active: null, age: 0, amount: 1, meta: {fee: true}, priority: false, vehicles: [{flag: 0, label: "high", qty: -0.01, risk: true}, {flag: 0, label: "3.5", qty: 1000000, risk: true}], vip: true, years: -0.5}}], + {input: {claim: {age: 1, years: 2, amount: -500, priority: false, vip: false, active: false, vehicles: []}}, goals: ["vehicle.tag"], output: {claim: {active: false, age: 1, amount: -500, priority: false, vehicles: [], vip: false, years: 2}}}, + {input: {claim: {age: 0.1, years: 18, amount: null, priority: true, vip: false, active: null, vehicles: null}}, goals: ["vehicle.flag"], output: {claim: {active: null, age: 0.1, amount: null, priority: true, vehicles: null, vip: false, years: 18}}}, + {input: {claim: {age: -500, years: -500, amount: 1000, priority: false, vip: false, active: true, vehicles: [{balance: -0.5, qty: 99999999999999999999, label: "日本"}]}}, goals: ["vehicle.risk", "vehicle.tag", "claim.meta.fee"], output: {claim: {active: true, age: -500, amount: 1000, meta: {fee: false}, priority: false, vehicles: [{balance: -0.5, label: "日本", qty: 99999999999999999999, risk: false, tag: {a: 100000000000000249499, ok: -500, s: false}}], vip: false, years: -500}}}, + {input: {claim: {age: 1000000, years: -0.5, amount: -500, priority: false, vip: false, active: false, vehicles: [{balance: 50, qty: 1e3, label: "US"}]}}, goals: ["vehicle.flag", "claim.meta.fee"], output: {claim: {active: false, age: 1000000, amount: -500, meta: {fee: false}, priority: false, vehicles: [{balance: 50, flag: 50, label: "US", qty: 1000, risk: false}], vip: false, years: -0.5}}}, + {input: {claim: {age: 1e3, years: 2, amount: 0.1, priority: true, vip: false, active: true, vehicles: [{balance: 5, qty: 250, label: "3.5"}, {balance: 7.25, qty: 60, label: "VIP"}]}}, goals: ["vehicle.tag", "net"], output: {claim: {active: true, age: 1000, amount: 0.1, priority: true, vehicles: [{balance: 5, label: "3.5", qty: 250, tag: {a: 1001250, ok: 1000, s: false}}, {balance: 7.25, label: "VIP", qty: 60, tag: {a: 1001060, ok: 1000, s: false}}], vip: false, years: 2}, net: -0.350}}, + {input: {claim: {age: 65, years: -0.01, amount: -1, priority: false, vip: true, active: true, vehicles: [{balance: 1e3, qty: -500, label: "Oslo"}, {balance: 0, qty: 0.1, label: "12"}]}}, goals: ["claim.meta.fee"], output: {claim: {active: true, age: 65, amount: -1, meta: {fee: true}, priority: false, vehicles: [{balance: 1000, label: "Oslo", qty: -500}, {balance: 0, label: "12", qty: 0.1}], vip: true, years: -0.01}}}, + {input: {claim: {age: 100, years: 0.1, active: true, vehicles: [{qty: -0.01, label: "retail"}, {balance: null, qty: 5, label: "é ü"}]}}, goals: ["vehicle.risk", "vehicle.tag"], output: {claim: {active: true, age: 100, meta: {fee: null}, vehicles: [{label: "retail", qty: -0.01, risk: false, tag: {a: 10099.99, ok: 100, s: false}}, {balance: null, label: "é ü", qty: 5, risk: false, tag: {a: 10105, ok: 100, s: false}}], years: 0.1}}}, + [{claim: {years: 99999999999999999999, priority: null, vip: true, vehicles: [{balance: null, qty: 250, label: "3.5"}, {balance: null, qty: 10, label: "3.5"}, {balance: 0, qty: 10, label: "VIP"}, {balance: null, qty: -0, label: "none"}, {balance: 1000, qty: 5, label: "Zed"}, {balance: null, qty: 5, label: "high"}, {qty: 1, label: "VIP"}, {balance: 50, qty: 5, label: "none"}, {qty: 18, label: "3.5"}, {balance: -1, qty: 0, label: "high"}, {balance: null, qty: -0, label: "high"}]}}, {claim: {meta: {fee: true}, priority: null, vehicles: [{balance: null, flag: 95.36363636363636363636363636, label: "3.5", qty: 250, risk: true}, {balance: null, flag: 95.36363636363636363636363636, label: "3.5", qty: 10, risk: true}, {balance: 0, flag: 95.36363636363636363636363636, label: "VIP", qty: 10, risk: true}, {balance: null, flag: 95.36363636363636363636363636, label: "none", qty: 0, risk: true}, {balance: 1000, flag: 95.36363636363636363636363636, label: "Zed", qty: 5, risk: true}, {balance: null, flag: 95.36363636363636363636363636, label: "high", qty: 5, risk: true}, {flag: 95.36363636363636363636363636, label: "VIP", qty: 1, risk: true}, {balance: 50, flag: 95.36363636363636363636363636, label: "none", qty: 5, risk: true}, {flag: 95.36363636363636363636363636, label: "3.5", qty: 18, risk: true}, {balance: -1, flag: 95.36363636363636363636363636, label: "high", qty: 0, risk: true}, {balance: null, flag: 95.36363636363636363636363636, label: "high", qty: 0, risk: true}], vip: true, years: 99999999999999999999}}], + {input: {claim: {age: 10, years: 10, amount: 7.25, priority: false, vip: false, active: true, vehicles: [{balance: 392, qty: -0.01, label: "é ü"}, {balance: 123456789.123, qty: 7.25, label: "3.5"}, {balance: 1000, qty: 1000000, label: "US"}], extraField: "x"}}, goals: ["claim.meta.fee", "vehicle.tag", "vehicle.flag"], output: {claim: {active: true, age: 10, amount: 7.25, extraField: "x", meta: {fee: false}, priority: false, vehicles: [{balance: 392, flag: 41152727.041, label: "é ü", qty: -0.01, risk: false, tag: {a: 109.99, ok: 10, s: false}}, {balance: 123456789.123, flag: 41152727.041, label: "3.5", qty: 7.25, risk: false, tag: {a: 117.25, ok: 10, s: false}}, {balance: 1000, flag: 41152727.041, label: "US", qty: 1000000, risk: false, tag: {a: 1000110, ok: 10, s: false}}], vip: false, years: 10}}}, + {input: {claim: {age: 250, years: 1, amount: -0.5, priority: false, vip: false, active: false, vehicles: [{balance: "12", qty: 50, label: "a"}]}}, goals: ["vehicle.flag", "vehicle.tag"], output: "!error: InputValidationFailed"}, + {input: {claim: {age: 0, years: 0.000001, amount: 50, priority: false, vip: false, active: true, vehicles: [{balance: 1, qty: 369, label: "3.5"}, {balance: -1, qty: -0.5, label: "none"}, {balance: 0.5, qty: 65, label: "日本"}, {balance: 10, qty: 2.50, label: "abc"}]}}, goals: ["vehicle.tag"], output: {claim: {active: true, age: 0, amount: 50, priority: false, vehicles: [{balance: 1, label: "3.5", qty: 369, tag: {a: 369, ok: 0, s: false}}, {balance: -1, label: "none", qty: -0.5, tag: {a: -0.5, ok: 0, s: true}}, {balance: 0.5, label: "日本", qty: 65, tag: {a: 65, ok: 0, s: false}}, {balance: 10, label: "abc", qty: 2.50, tag: {a: 2.50, ok: 0, s: false}}], vip: false, years: 0.000001}}}, + [{claim: {age: 0.000001, years: 1e3, amount: 65, priority: null, vip: null, active: null, vehicles: null}}, {claim: {active: null, age: 0.000001, amount: 65, priority: null, vehicles: null, vip: null, years: 1000}}], + ], +} + +// seed 354001 (attempt 1) +{ + name: "goals 41: applicant/items/parts + profile: 4 expression, 3 match, 4 table; 4 root, 7 per-member, 4 top-level computed", + policy: { + models: {applicant: {weight: "number", tier: "string(gold|silver|bronze)", amount: "number", insured: "boolean?", country: "string?", code: "string", items: "item[]", profile: "profile"}, item: {years: "number", since: "date", name: "string", weight: "number", parts: "part[]"}, part: {days: "number", label: "string?"}, profile: {qty: "number", urgent: "boolean?", flagged: "boolean?"}}, + blocks: [ + {match: "item.health", arms: [["(applicant.country ?? '') in ['a', 'retail']", "number(string(applicant.amount))"], ["applicant.weight in [31..219]", "18"], ["", "len(item.parts)"]]}, + {expression: "applicant.ok", value: "(isNumeric(`${applicant.weight}/${(applicant.profile.urgent ?? false)}`) or applicant.tier == 'silver')"}, + {match: "item.weighted", arms: [["applicant.tier != 'bronze'", "((applicant.country ?? '') in ['A1', 'ok'] and isNumeric(item.name))"], ["item.health == 2", "(applicant.profile.urgent ?? false)"], ["", "all(item.parts, matches((#.label ?? ''), '[0-9]$'))"]]}, + {table: "t4", inputs: ["applicant.profile.qty"], outputs: ["penalty", "calc.bucket", "level[]"], rules: [ + ["> 0.25", "applicant.profile.qty", "len((applicant.country ?? ''))", "applicant.weight"], + ["", "applicant.weight", "(avg(map(applicant.items, 1000)) ?? 0)", "2"], + ["", "1.5", "applicant.weight", "applicant.amount"], + ["", "applicant.profile.qty", "applicant.weight", "(applicant.weight + applicant.profile.qty)"], + ["< 50", "(applicant.profile.qty + applicant.profile.qty)", "applicant.amount", "2"], + ["2, 50", "sum(map(applicant.items, #.years))", "applicant.amount", "5"], + ["!= 18", "applicant.profile.qty", "applicant.amount", "10"], + ]}, + {match: "applicant.segment", arms: [["contains((applicant.country ?? ''), 'ok')", "applicant.code"], ["applicant.profile.qty <= applicant.amount", "(applicant.country ?? '')"], ["isNumeric((applicant.country ?? ''))", "string(applicant.amount)"], ["", "string((calc.bucket ?? 0))"]]}, + {expression: "band", value: "(all(applicant.items, (#.weighted and #.weighted)) ? penalty : null)"}, + {expression: "item.fee", value: "{s: 2}"}, + {table: "t8", inputs: ["applicant.profile.qty", "applicant.ok", "applicant.amount"], outputs: ["applicant.total", "applicant.share"], rules: [ + ["0.25", "true", "< 3", "applicant.segment", "(applicant.insured ?? false)"], + ["10, 2", "false", "10, 10", "(applicant.country ?? '')", "applicant.ok"], + ["1.5, 10", "false", "100, 0.25", "(applicant.country ?? '')", "applicant.ok"], + ["", "", "", "(applicant.country ?? '')", "(applicant.profile.flagged ?? false)"], + ]}, + {table: "t9", inputs: ["profile.qty"], outputs: ["profile.exposure", "profile.decision"], rules: [ + ["", "(calc.bucket ?? 0)", "applicant.weight in [-5..17]"], + ["[5..90]", "", "(applicant.share ?? false)"], + ["", "(applicant.amount + profile.qty)", "(profile.urgent ?? false)"], + ["1", "", "(applicant.share ?? false)"], + ["", "applicant.amount", "applicant.tier in ['gold', 'bronze']"], + ]}, + {table: "t10", inputs: ["applicant.tier"], outputs: ["item.totals.risk", "item.totals.bonus[]"], rules: [ + ["", "(applicant.profile.flagged ?? false)", "(applicant.profile.urgent ?? false)"], + ["'bronze', 'silver'", "(applicant.insured ?? false)", ""], + ["'silver', 'gold'", "(applicant.profile.decision ?? false)", ""], + ["'gold'", "applicant.ok", "(applicant.profile.urgent ?? false)"], + ]}, + {expression: "item.totals.margin", value: "map(applicant.items, (#.health * 3))"}, + ], + }, + cases: [ + {input: {applicant: {weight: 3, tier: "bronze", amount: 1, insured: false, country: "日本", code: "3.5", items: [{years: 176, since: "2025-03-20", name: "Oslo", weight: 10, parts: [{days: 0.25, label: "A1"}]}, {years: 1.5, since: "2024-02-29", name: "US", weight: 1, parts: [{days: 134, label: "A1"}]}], profile: {qty: 0.25, urgent: true, flagged: true}}}, goals: ["applicant.share", "calc.bucket", "penalty"], output: {applicant: {amount: 1, code: "3.5", country: "日本", insured: false, items: [{name: "Oslo", parts: [{days: 0.25, label: "A1"}], since: "2025-03-20", weight: 10, years: 176}, {name: "US", parts: [{days: 134, label: "A1"}], since: "2024-02-29", weight: 1, years: 1.5}], ok: false, profile: {flagged: true, qty: 0.25, urgent: true}, share: true, tier: "bronze", total: "日本", weight: 3}, calc: {bucket: 1000}, level: [2, 1, 3.25, 2, 10], penalty: 3}}, + {input: {applicant: {weight: 2, tier: "bronze", amount: 2, insured: true, country: null, code: "é ü", items: [{years: -1, since: "2030-12-31", name: "-", weight: 250, parts: [{days: 1}, {days: 0.25, label: null}]}, {years: 18, since: "2030-12-31", name: "ok", weight: 0.000001, parts: []}, {years: 123456789.123, since: "2024-02-29", name: "gold", weight: 7.25, parts: []}], profile: {qty: 250, urgent: true, flagged: null}}}, goals: ["profile.exposure"], output: {applicant: {amount: 2, code: "é ü", country: null, insured: true, items: [{name: "-", parts: [{days: 1}, {days: 0.25, label: null}], since: "2030-12-31", weight: 250, years: -1}, {name: "ok", parts: [], since: "2030-12-31", weight: 0.000001, years: 18}, {name: "gold", parts: [], since: "2024-02-29", weight: 7.25, years: 123456789.123}], profile: {decision: true, exposure: 0, flagged: null, qty: 250, urgent: true}, tier: "bronze", weight: 2}, calc: {bucket: 0}, level: [2, 2, 2, 252, 10], penalty: 250}}, + {input: {applicant: {weight: 250, tier: "bronze", amount: 18, insured: true, country: "-", code: "3.5", items: [{years: 250, since: "2030-12-31", name: " pad ", weight: 100, parts: [{days: 18, label: "Zed"}]}, {years: 10, since: "2000-01-01", name: "", weight: 7.25, parts: [{days: 5, label: "x-y"}]}, {years: 1000, since: "2000-01-01", name: "A1", weight: 5, parts: [{days: -0.01, label: "ok"}, {days: 2, label: "retail"}, {days: 2, label: null}]}, {years: 1000, since: "2024-01-01", name: "a", weight: 2, parts: [{days: 10}]}], profile: {qty: 1, urgent: null, flagged: null}}}, goals: ["profile.decision", "item.health"], output: {applicant: {amount: 18, code: "3.5", country: "-", insured: true, items: [{health: 1, name: " pad ", parts: [{days: 18, label: "Zed"}], since: "2030-12-31", weight: 100, years: 250}, {health: 1, name: "", parts: [{days: 5, label: "x-y"}], since: "2000-01-01", weight: 7.25, years: 10}, {health: 3, name: "A1", parts: [{days: -0.01, label: "ok"}, {days: 2, label: "retail"}, {days: 2, label: null}], since: "2000-01-01", weight: 5, years: 1000}, {health: 1, name: "a", parts: [{days: 10}], since: "2024-01-01", weight: 2, years: 1000}], profile: {decision: false, exposure: 1, flagged: null, qty: 1, urgent: null}, tier: "bronze", weight: 250}, calc: {bucket: 1}, level: [250, 2, 18, 251, 2, 10], penalty: 1}}, + [{applicant: {weight: 1e3, tier: "bronze", amount: 2, insured: false, country: "A1", code: "a", items: [], profile: {qty: 2, urgent: true, flagged: false}}}, {applicant: {amount: 2, code: "a", country: "A1", insured: false, items: [], ok: false, profile: {decision: false, exposure: 2, flagged: false, qty: 2, urgent: true}, share: false, tier: "bronze", total: "A1", weight: 1000}, band: 2, calc: {bucket: 2}, level: [1000, 2, 2, 1002, 2, 5, 10], penalty: 2}], + {input: {applicant: {weight: 2.50, tier: "bronze", amount: 18, insured: null, country: null, code: "x-y", items: [{years: 1, since: "2025-03-20", name: "retail", weight: -1, parts: [{days: 0, label: "ok"}]}, {years: 250, since: "2025-03-20", name: "VIP", weight: 2, parts: [{days: -1, label: "A1"}, {days: 1}, {days: 100}]}], profile: {qty: 18, urgent: null, flagged: true}}}, goals: ["penalty"], output: {applicant: {amount: 18, code: "x-y", country: null, insured: null, items: [{name: "retail", parts: [{days: 0, label: "ok"}], since: "2025-03-20", weight: -1, years: 1}, {name: "VIP", parts: [{days: -1, label: "A1"}, {days: 1}, {days: 100}], since: "2025-03-20", weight: 2, years: 250}], profile: {flagged: true, qty: 18, urgent: null}, tier: "bronze", weight: 2.50}, calc: {bucket: 0}, level: [2.50, 2, 18, 20.50, 2], penalty: 18}}, + {input: {applicant: {weight: 7.25, tier: "gold", amount: 2, code: "O'Neil", items: [{years: 1000, since: "2025-03-20T10:15:30Z", name: "A1", weight: 2, parts: [{days: 10, label: "gold"}, {days: 250}]}], profile: {qty: 5}}}, goals: ["applicant.segment", "profile.exposure"], output: {applicant: {amount: 2, code: "O'Neil", items: [{name: "A1", parts: [{days: 10, label: "gold"}, {days: 250}], since: "2025-03-20T10:15:30Z", weight: 2, years: 1000}], profile: {decision: true, exposure: 0, qty: 5}, segment: "0", tier: "gold", weight: 7.25}, calc: {bucket: 0}, level: [7.25, 2, 2, 12.25, 2, 10], penalty: 5}}, + {input: {applicant: {weight: 0.1, tier: "gold", amount: 1, insured: null, country: "Oslo", code: "VIP", items: [{years: 250, since: "1990-06-15", name: "-", weight: 0.5, parts: [{days: 5, label: "retail"}]}], profile: {qty: -1, flagged: true}}}, goals: ["applicant.share"], output: {applicant: {amount: 1, code: "VIP", country: "Oslo", insured: null, items: [{name: "-", parts: [{days: 5, label: "retail"}], since: "1990-06-15", weight: 0.5, years: 250}], ok: false, profile: {flagged: true, qty: -1}, share: true, tier: "gold", total: "Oslo", weight: 0.1}}}, + {input: {applicant: {weight: 0.25, tier: "silver", amount: 2, insured: true, country: "retail", code: "12", items: [{years: 2, since: "2024-01-01", name: "ok", weight: 50, parts: [{days: -0, label: "A1"}, {days: 3, label: "abc"}]}], profile: {qty: -0.01, urgent: false}}}, goals: ["level", "item.totals.risk"], output: {applicant: {amount: 2, code: "12", country: "retail", insured: true, items: [{name: "ok", parts: [{days: 0, label: "A1"}, {days: 3, label: "abc"}], since: "2024-01-01", totals: {bonus: [false], risk: false}, weight: 50, years: 2}], profile: {qty: -0.01, urgent: false}, tier: "silver", weight: 0.25}, calc: {bucket: 1000}, level: [2, 2, 0.24, 2, 10], penalty: 0.25}}, + {input: {applicant: {weight: 1e3, tier: "silver", amount: 0.1, insured: null, country: "retail", code: "日本", items: [{years: 0.5, since: "2030-12-31", name: "é ü", weight: 250, parts: []}], profile: {qty: 2, urgent: null, flagged: false}}}, goals: ["level", "applicant.share"], output: {applicant: {amount: 0.1, code: "日本", country: "retail", insured: null, items: [{name: "é ü", parts: [], since: "2030-12-31", weight: 250, years: 0.5}], ok: true, profile: {flagged: false, qty: 2, urgent: null}, share: false, tier: "silver", total: "retail", weight: 1000}, calc: {bucket: 6}, level: [1000, 2, 0.1, 1002, 2, 5, 10], penalty: 2}}, + {input: {applicant: {weight: 3, tier: "silver", amount: 18, insured: null, country: "A1", code: "abc", items: [{years: 99999999999999999999, since: "2024-02-29", name: "DE", weight: 250, parts: [{days: 10, label: "abc"}, {days: 0}, {days: 250, label: "NL"}]}, {years: -0.5, since: "2030-12-31", name: "NL", weight: 2, parts: [{days: 99999999999999999999, label: "3.5"}, {days: 2}]}, {years: 0.000001, since: "1990-06-15", name: "", weight: 10, parts: []}], profile: {qty: 10, urgent: true, flagged: false}}}, goals: ["profile.exposure", "applicant.ok"], output: {applicant: {amount: 18, code: "abc", country: "A1", insured: null, items: [{name: "DE", parts: [{days: 10, label: "abc"}, {days: 0}, {days: 250, label: "NL"}], since: "2024-02-29", weight: 250, years: 99999999999999999999}, {name: "NL", parts: [{days: 99999999999999999999, label: "3.5"}, {days: 2}], since: "2030-12-31", weight: 2, years: -0.5}, {name: "", parts: [], since: "1990-06-15", weight: 10, years: 0.000001}], ok: true, profile: {decision: true, exposure: 2, flagged: false, qty: 10, urgent: true}, tier: "silver", weight: 3}, calc: {bucket: 2}, level: [3, 2, 18, 13, 2, 10], penalty: 10}}, + {input: {applicant: {weight: -500, tier: "gold", amount: 0.000001, insured: true, country: "O'Neil", code: "12", items: [{years: 5, since: "2025-03-20T10:15:30Z", name: "Zed", weight: 1e3, parts: [{days: 250, label: "é ü"}, {days: 3, label: ""}]}, {years: 2, since: "2030-12-31", name: "DE", weight: 0.1, parts: [{days: 50, label: "retail"}]}, {years: 2, since: "2024-01-01", name: "A1", weight: 1000, parts: [{days: 10, label: "12"}]}, {years: 0.5, since: "2025-03-20", name: "-", weight: 2, parts: [{days: 1.5, label: "O'Neil"}, {days: 99.99, label: "gold"}, {days: 7.25, label: "Oslo"}]}], profile: {qty: -0, urgent: true, flagged: false}}}, goals: ["calc.bucket", "item.health", "applicant.segment"], output: {applicant: {amount: 0.000001, code: "12", country: "O'Neil", insured: true, items: [{health: 2, name: "Zed", parts: [{days: 250, label: "é ü"}, {days: 3, label: ""}], since: "2025-03-20T10:15:30Z", weight: 1000, years: 5}, {health: 1, name: "DE", parts: [{days: 50, label: "retail"}], since: "2030-12-31", weight: 0.1, years: 2}, {health: 1, name: "A1", parts: [{days: 10, label: "12"}], since: "2024-01-01", weight: 1000, years: 2}, {health: 3, name: "-", parts: [{days: 1.5, label: "O'Neil"}, {days: 99.99, label: "gold"}, {days: 7.25, label: "Oslo"}], since: "2025-03-20", weight: 2, years: 0.5}], profile: {flagged: false, qty: 0, urgent: true}, segment: "O'Neil", tier: "gold", weight: -500}, calc: {bucket: 1000}, level: [2, 0.000001, -500, 2, 10], penalty: -500}}, + {input: {applicant: {weight: 2, tier: "gold", amount: 18, code: "retail", items: [{years: 343, since: "1990-06-15", name: "é ü", weight: 1e3, parts: [{days: 10}, {days: 65}]}, {years: 395, since: "2024-02-29", name: " pad ", weight: 2, parts: [{days: 123456789.123}, {days: 50, label: "A1"}]}, {years: 5, since: "1990-06-15", name: "retail", weight: 18, parts: [{days: 0}]}, {years: 0.25, since: "2030-12-31", name: "DE", weight: 0.25, parts: [{days: 18}]}, {years: 18, since: "2030-12-31", name: " pad ", weight: 0.25, parts: [{days: 0.5, label: "ok"}, {days: 18, label: "ok"}, {days: 0, label: "O'Neil"}]}, {years: 2, since: "2024-02-29", name: "a", weight: 10, parts: [{days: 50}]}, {years: 1, since: "2025-03-20T10:15:30Z", name: "-", weight: 250, parts: [{days: 50, label: null}]}, {years: 1.5, since: "2030-12-31", name: "A1", weight: 0.5, parts: [{days: 2, label: "A1"}, {days: 0, label: "Oslo"}]}, {years: 1.5, since: "2030-12-31", name: "a-b-c", weight: 7.25, parts: []}], profile: {qty: 1000000, urgent: true}}}, goals: ["applicant.segment", "level", "calc.bucket"], output: {applicant: {amount: 18, code: "retail", items: [{name: "é ü", parts: [{days: 10}, {days: 65}], since: "1990-06-15", weight: 1000, years: 343}, {name: " pad ", parts: [{days: 123456789.123}, {days: 50, label: "A1"}], since: "2024-02-29", weight: 2, years: 395}, {name: "retail", parts: [{days: 0}], since: "1990-06-15", weight: 18, years: 5}, {name: "DE", parts: [{days: 18}], since: "2030-12-31", weight: 0.25, years: 0.25}, {name: " pad ", parts: [{days: 0.5, label: "ok"}, {days: 18, label: "ok"}, {days: 0, label: "O'Neil"}], since: "2030-12-31", weight: 0.25, years: 18}, {name: "a", parts: [{days: 50}], since: "2024-02-29", weight: 10, years: 2}, {name: "-", parts: [{days: 50, label: null}], since: "2025-03-20T10:15:30Z", weight: 250, years: 1}, {name: "A1", parts: [{days: 2, label: "A1"}, {days: 0, label: "Oslo"}], since: "2030-12-31", weight: 0.5, years: 1.5}, {name: "a-b-c", parts: [], since: "2030-12-31", weight: 7.25, years: 1.5}], profile: {qty: 1000000, urgent: true}, segment: "0", tier: "gold", weight: 2}, calc: {bucket: 0}, level: [2, 2, 18, 1000002, 10], penalty: 1000000}}, + {input: {applicant: {weight: 18, tier: "silver", amount: 18, insured: true, country: null, code: "VIP", items: [{years: 0.5, since: "2024-02-29", name: "retail", weight: 18, parts: [{days: 2}, {days: 0.5, label: "retail"}, {days: 10}]}, {years: 10, since: "2030-12-31", name: "DE", weight: 0, parts: [{days: 250, label: null}]}, {years: 0, since: "1990-06-15", name: "O'Neil", weight: 0.000001, parts: [{days: 18}]}], profile: {qty: 7.25, urgent: true, flagged: true}}}, goals: ["applicant.total"], output: {applicant: {amount: 18, code: "VIP", country: null, insured: true, items: [{name: "retail", parts: [{days: 2}, {days: 0.5, label: "retail"}, {days: 10}], since: "2024-02-29", weight: 18, years: 0.5}, {name: "DE", parts: [{days: 250, label: null}], since: "2030-12-31", weight: 0, years: 10}, {name: "O'Neil", parts: [{days: 18}], since: "1990-06-15", weight: 0.000001, years: 0}], ok: true, profile: {flagged: true, qty: 7.25, urgent: true}, share: true, tier: "silver", total: "", weight: 18}}}, + {input: {applicant: {weight: 10, tier: "gold", amount: 250, insured: false, country: "abc", code: "a", items: [{years: 10, since: "2025-03-20", name: "A1", weight: 250, parts: [{days: 2, label: "Zed"}, {days: 18, label: "abc"}]}, {years: 250, since: "2024-02-29", name: "retail", weight: 2, parts: [{days: 250, label: "VIP"}]}, {years: 10, since: "2025-03-20T10:15:30Z", name: "VIP", weight: 0.25, parts: [{days: 0.000001, label: "VIP"}, {days: 99999999999999999999, label: "a"}]}, {years: 7.25, since: "1990-06-15", name: "A1", weight: 250, parts: [{days: 10, label: "A1"}, {days: 1, label: "ok"}]}], profile: {qty: 0.1, urgent: true, flagged: true}}}, goals: ["calc.bucket"], output: {applicant: {amount: 250, code: "a", country: "abc", insured: false, items: [{name: "A1", parts: [{days: 2, label: "Zed"}, {days: 18, label: "abc"}], since: "2025-03-20", weight: 250, years: 10}, {name: "retail", parts: [{days: 250, label: "VIP"}], since: "2024-02-29", weight: 2, years: 250}, {name: "VIP", parts: [{days: 0.000001, label: "VIP"}, {days: 99999999999999999999, label: "a"}], since: "2025-03-20T10:15:30Z", weight: 0.25, years: 10}, {name: "A1", parts: [{days: 10, label: "A1"}, {days: 1, label: "ok"}], since: "1990-06-15", weight: 250, years: 7.25}], profile: {flagged: true, qty: 0.1, urgent: true}, tier: "gold", weight: 10}, calc: {bucket: 1000}, level: [2, 250, 10.1, 2, 10], penalty: 10}}, + {input: {applicant: {weight: 2, tier: "gold", amount: 2, insured: false, country: "NL", code: "-", items: [{years: 3, since: "2000-01-01", name: "A1", weight: 250, parts: [{days: 2, label: "retail"}, {days: 1, label: "-"}]}, {years: 250, since: "1990-06-15", name: "abc", weight: 5, parts: [{days: 18, label: "a"}, {days: 10, label: ""}, {days: 2, label: "-"}]}, {years: 2, since: "2024-02-29", name: "abc", weight: 123456789.123, parts: [{days: 1e3, label: "A1"}]}, {years: 2, since: "2024-02-29", name: "A1", weight: 65, parts: [{days: 2, label: "US"}]}], profile: {qty: 99999999999999999999, urgent: true, flagged: true}}}, goals: ["band", "level"], output: {applicant: {amount: 2, code: "-", country: "NL", insured: false, items: [{health: 2, name: "A1", parts: [{days: 2, label: "retail"}, {days: 1, label: "-"}], since: "2000-01-01", weight: 250, weighted: false, years: 3}, {health: 3, name: "abc", parts: [{days: 18, label: "a"}, {days: 10, label: ""}, {days: 2, label: "-"}], since: "1990-06-15", weight: 5, weighted: false, years: 250}, {health: 1, name: "abc", parts: [{days: 1000, label: "A1"}], since: "2024-02-29", weight: 123456789.123, weighted: false, years: 2}, {health: 1, name: "A1", parts: [{days: 2, label: "US"}], since: "2024-02-29", weight: 65, weighted: false, years: 2}], profile: {flagged: true, qty: 99999999999999999999, urgent: true}, tier: "gold", weight: 2}, band: null, calc: {bucket: 2}, level: [2, 2, 2, 100000000000000000001, 10], penalty: 99999999999999999999}}, + {input: {applicant: {weight: 250, tier: null, amount: 50, insured: false, country: "retail", code: "A1", items: [], profile: {qty: 18, urgent: false, flagged: true}}}, goals: ["profile.exposure"], output: "!error: MissingRequiredInputs"}, + {input: {applicant: {weight: 2, tier: "silver", amount: 0.25, insured: true, country: "-", code: "é ü", items: [{years: 0.5, since: "2000-01-01", name: "é ü", weight: 1e3, parts: [{days: 100, label: "A1"}, {days: 257, label: "é ü"}]}], profile: {qty: -500, urgent: true, flagged: true}}}, goals: ["calc.bucket"], output: {applicant: {amount: 0.25, code: "é ü", country: "-", insured: true, items: [{name: "é ü", parts: [{days: 100, label: "A1"}, {days: 257, label: "é ü"}], since: "2000-01-01", weight: 1000, years: 0.5}], profile: {flagged: true, qty: -500, urgent: true}, tier: "silver", weight: 2}, calc: {bucket: 1000}, level: [2, 0.25, -498, 2, 10], penalty: 2}}, + {input: {applicant: {weight: 1, tier: "gold", amount: 0, insured: false, country: "retail", code: " pad ", items: [{years: 1e3, since: "2024-01-01", name: "x-y", weight: 0, parts: []}, {years: 1.5, since: "2000-01-01", name: "a-b-c", weight: 1.5, parts: []}, {years: 1.5, since: "2025-03-20T10:15:30Z", name: "retail", weight: 50, parts: [{days: 10, label: "é ü"}, {days: 3, label: ""}]}], profile: {qty: 2, urgent: false, flagged: false}}}, goals: ["item.totals.margin"], output: {applicant: {amount: 0, code: " pad ", country: "retail", insured: false, items: [{health: 0, name: "x-y", parts: [], since: "2024-01-01", totals: {margin: [0, 0, 0]}, weight: 0, years: 1000}, {health: 0, name: "a-b-c", parts: [], since: "2000-01-01", totals: {margin: [0, 0, 0]}, weight: 1.5, years: 1.5}, {health: 0, name: "retail", parts: [{days: 10, label: "é ü"}, {days: 3, label: ""}], since: "2025-03-20T10:15:30Z", totals: {margin: [0, 0, 0]}, weight: 50, years: 1.5}], profile: {flagged: false, qty: 2, urgent: false}, tier: "gold", weight: 1}}}, + {input: {applicant: {weight: 10, tier: "silver", amount: 18, country: "A1", code: "a", items: [{years: 250, since: "2024-02-29", name: "Zed", weight: 2, parts: [{days: 18, label: ""}]}, {years: 2, since: "2024-02-29", name: " pad ", weight: 1000, parts: [{days: 0}, {days: 1}, {days: 5}]}, {years: 50, since: "2025-03-20T10:15:30Z", name: "US", weight: -1, parts: [{days: 0, label: null}, {days: 3}]}], profile: {qty: 2}}}, goals: ["applicant.ok", "penalty"], output: {applicant: {amount: 18, code: "a", country: "A1", items: [{name: "Zed", parts: [{days: 18, label: ""}], since: "2024-02-29", weight: 2, years: 250}, {name: " pad ", parts: [{days: 0}, {days: 1}, {days: 5}], since: "2024-02-29", weight: 1000, years: 2}, {name: "US", parts: [{days: 0, label: null}, {days: 3}], since: "2025-03-20T10:15:30Z", weight: -1, years: 50}], ok: true, profile: {qty: 2}, tier: "silver", weight: 10}, calc: {bucket: 2}, level: [10, 2, 18, 12, 2, 5, 10], penalty: 2}}, + {input: {applicant: {weight: 0.000001, tier: "gold", amount: 0.5, insured: null, code: "gold", items: [{years: 0.000001, since: "2025-03-20T10:15:30Z", name: "DE", weight: 99.99, parts: [{days: 250, label: "gold"}, {days: 2, label: "3.5"}, {days: 18, label: null}]}, {years: 50, since: "1990-06-15", name: "gold", weight: 10, parts: []}, {years: 250, since: "2024-01-01", name: "3.5", weight: 2, parts: [{days: 1.5}, {days: 10, label: null}, {days: 18, label: "a"}]}, {years: 5, since: "2025-03-20T10:15:30Z", name: "ok", weight: 2, parts: [{days: 3}, {days: 10, label: "ok"}, {days: 18, label: null}]}, {years: 1000, since: "2030-12-31", name: "A1", weight: 0, parts: [{days: 10, label: "日本"}, {days: 0.25, label: "12"}]}], profile: {qty: 0, urgent: null}}}, goals: ["item.fee", "applicant.segment"], output: {applicant: {amount: 0.5, code: "gold", insured: null, items: [{fee: {s: 2}, name: "DE", parts: [{days: 250, label: "gold"}, {days: 2, label: "3.5"}, {days: 18, label: null}], since: "2025-03-20T10:15:30Z", weight: 99.99, years: 0.000001}, {fee: {s: 2}, name: "gold", parts: [], since: "1990-06-15", weight: 10, years: 50}, {fee: {s: 2}, name: "3.5", parts: [{days: 1.5}, {days: 10, label: null}, {days: 18, label: "a"}], since: "2024-01-01", weight: 2, years: 250}, {fee: {s: 2}, name: "ok", parts: [{days: 3}, {days: 10, label: "ok"}, {days: 18, label: null}], since: "2025-03-20T10:15:30Z", weight: 2, years: 5}, {fee: {s: 2}, name: "A1", parts: [{days: 10, label: "日本"}, {days: 0.25, label: "12"}], since: "2030-12-31", weight: 0, years: 1000}], profile: {qty: 0, urgent: null}, segment: "", tier: "gold", weight: 0.000001}}}, + {input: {applicant: {weight: 0, tier: "silver", amount: 1.5, insured: true, country: "a-b-c", code: "abc", items: [{years: 10, since: "1990-06-15", name: "a", weight: 123456789.123, parts: []}, {years: 0.1, since: "2025-03-20", name: "retail", weight: 250, parts: [{days: 3, label: " pad "}]}], profile: {qty: 100, urgent: true, flagged: false}}}, goals: ["profile.exposure", "penalty", "item.health"], output: {applicant: {amount: 1.5, code: "abc", country: "a-b-c", insured: true, items: [{health: 0, name: "a", parts: [], since: "1990-06-15", weight: 123456789.123, years: 10}, {health: 1, name: "retail", parts: [{days: 3, label: " pad "}], since: "2025-03-20", weight: 250, years: 0.1}], profile: {decision: true, exposure: 5, flagged: false, qty: 100, urgent: true}, tier: "silver", weight: 0}, calc: {bucket: 5}, level: [0, 2, 1.5, 100, 10], penalty: 100}}, + {input: {applicant: {weight: 18, tier: "gold", amount: 5, code: "3.5", items: [{years: 18, since: "2024-02-29", name: "retail", weight: 18, parts: [{days: 10, label: ""}, {days: 10, label: "US"}]}, {years: 1000, since: "2030-12-31", name: "A1", weight: -0.01, parts: []}], profile: {qty: 10, flagged: false}}}, goals: ["calc.bucket", "item.totals.risk", "penalty"], output: {applicant: {amount: 5, code: "3.5", items: [{name: "retail", parts: [{days: 10, label: ""}, {days: 10, label: "US"}], since: "2024-02-29", totals: {bonus: [false, false], risk: false}, weight: 18, years: 18}, {name: "A1", parts: [], since: "2030-12-31", totals: {bonus: [false, false], risk: false}, weight: -0.01, years: 1000}], profile: {flagged: false, qty: 10}, tier: "gold", weight: 18}, calc: {bucket: 0}, level: [18, 2, 5, 28, 2, 10], penalty: 10}}, + {input: {applicant: {weight: 1, tier: "bronze", amount: 10, insured: false, country: "a", code: "DE", items: [{years: 5, since: "2025-03-20", name: "", weight: 50, parts: [{days: 1, label: "-"}, {days: 10, label: "a-b-c"}]}, {years: 18, since: "2025-03-20T10:15:30Z", name: "ok", weight: 50, parts: [{days: 1.5, label: "é ü"}, {days: 1000, label: "DE"}]}, {years: 0, since: "2030-12-31", name: "gold", weight: 1000, parts: [{days: 50, label: "a-b-c"}]}], profile: {qty: 99.99, urgent: false, flagged: false}}}, goals: ["calc.bucket", "item.weighted", "applicant.total"], output: {applicant: {amount: 10, code: "DE", country: "a", insured: false, items: [{health: 10, name: "", parts: [{days: 1, label: "-"}, {days: 10, label: "a-b-c"}], since: "2025-03-20", weight: 50, weighted: false, years: 5}, {health: 10, name: "ok", parts: [{days: 1.5, label: "é ü"}, {days: 1000, label: "DE"}], since: "2025-03-20T10:15:30Z", weight: 50, weighted: false, years: 18}, {health: 10, name: "gold", parts: [{days: 50, label: "a-b-c"}], since: "2030-12-31", weight: 1000, weighted: false, years: 0}], ok: false, profile: {flagged: false, qty: 99.99, urgent: false}, share: false, tier: "bronze", total: "a", weight: 1}, calc: {bucket: 1}, level: [1, 2, 10, 100.99, 10], penalty: 99.99}}, + {input: {applicant: {weight: -0.01, tier: "gold", amount: 5, insured: "true", country: "A1", code: "O'Neil", items: [{years: 1, since: "2024-01-01", name: "A1", weight: 250, parts: []}, {years: 1e3, since: "2030-12-31", name: "A1", weight: 2, parts: [{days: 1.5, label: "A1"}, {days: 18, label: "NL"}]}, {years: 2, since: "2024-01-01", name: "ok", weight: 1.5, parts: [{days: 7.25, label: " pad "}, {days: -0.5, label: " pad "}]}, {years: 50, since: "2024-01-01", name: "DE", weight: 1, parts: [{days: 50, label: " pad "}, {days: 2.50, label: "a"}, {days: 0, label: "a"}]}, {years: 1000000, since: "1990-06-15", name: "ok", weight: 0.5, parts: []}], profile: {qty: 10, urgent: false, flagged: true}}}, goals: ["profile.decision"], output: "!error: InputValidationFailed"}, + {input: {applicant: {weight: 5, tier: "bronze", amount: 0, insured: false, country: "12", code: "DE", items: [{years: 2, since: "2024-01-01", name: "ok", weight: 5, parts: [{days: 65, label: "日本"}, {days: -0.01, label: "A1"}]}], profile: {qty: 18, urgent: true, flagged: true}}}, goals: ["applicant.total"], output: {applicant: {amount: 0, code: "DE", country: "12", insured: false, items: [{name: "ok", parts: [{days: 65, label: "日本"}, {days: -0.01, label: "A1"}], since: "2024-01-01", weight: 5, years: 2}], ok: false, profile: {flagged: true, qty: 18, urgent: true}, share: true, tier: "bronze", total: "12", weight: 5}}}, + {input: {applicant: {weight: 250, tier: "gold", amount: 1000, insured: false, country: "a-b-c", code: "VIP", items: [{years: 1, since: "2025-03-20", name: "a", weight: 1000, parts: [{days: 0, label: "A1"}, {days: 50, label: "VIP"}]}], profile: {qty: 10, urgent: true, flagged: false}}}, goals: ["item.weighted", "penalty"], output: {applicant: {amount: 1000, code: "VIP", country: "a-b-c", insured: false, items: [{health: 2, name: "a", parts: [{days: 0, label: "A1"}, {days: 50, label: "VIP"}], since: "2025-03-20", weight: 1000, weighted: false, years: 1}], profile: {flagged: false, qty: 10, urgent: true}, tier: "gold", weight: 250}, calc: {bucket: 5}, level: [250, 2, 1000, 260, 2, 10], penalty: 10}}, + [{applicant: {weight: 250, tier: "silver", amount: -1, insured: false, country: "DE", code: "é ü", items: [{years: -500, since: "2030-12-31", name: "DE", weight: 2, parts: []}, {years: 3, since: "2025-03-20T10:15:30Z", name: "O'Neil", weight: 1000000, parts: [{days: 0.25}, {days: 10, label: "a-b-c"}]}, {years: 1, since: "2030-12-31", name: "x-y", weight: 1, parts: [{days: 47, label: null}]}, {years: 18, since: "2000-01-01", name: "A1", weight: 2.50, parts: []}, {years: 0.25, since: "2024-01-01", name: "a", weight: 10, parts: [{days: 396}, {days: 2, label: " pad "}, {days: 5, label: " pad "}]}], profile: {qty: -0, urgent: true}}}, {applicant: {amount: -1, code: "é ü", country: "DE", insured: false, items: [{fee: {s: 2}, health: 0, name: "DE", parts: [], since: "2030-12-31", totals: {bonus: [true], margin: [0, 6, 3, 0, 9], risk: false}, weight: 2, weighted: false, years: -500}, {fee: {s: 2}, health: 2, name: "O'Neil", parts: [{days: 0.25}, {days: 10, label: "a-b-c"}], since: "2025-03-20T10:15:30Z", totals: {bonus: [true], margin: [0, 6, 3, 0, 9], risk: false}, weight: 1000000, weighted: false, years: 3}, {fee: {s: 2}, health: 1, name: "x-y", parts: [{days: 47, label: null}], since: "2030-12-31", totals: {bonus: [true], margin: [0, 6, 3, 0, 9], risk: false}, weight: 1, weighted: false, years: 1}, {fee: {s: 2}, health: 0, name: "A1", parts: [], since: "2000-01-01", totals: {bonus: [true], margin: [0, 6, 3, 0, 9], risk: false}, weight: 2.50, weighted: false, years: 18}, {fee: {s: 2}, health: 3, name: "a", parts: [{days: 396}, {days: 2, label: " pad "}, {days: 5, label: " pad "}], since: "2024-01-01", totals: {bonus: [true], margin: [0, 6, 3, 0, 9], risk: false}, weight: 10, weighted: false, years: 0.25}], ok: true, profile: {decision: false, exposure: 1000, qty: 0, urgent: true}, share: false, tier: "silver", total: "DE", weight: 250}, band: null, calc: {bucket: 1000}, level: [2, -1, 250, 2, 10], penalty: 250}], + ], +} + +// seed 354100 (attempt 0) +{ + name: "goals 42: claim/lines/employees + contact: 2 assertion, 2 expression, 3 match, 3 table; 6 root, 4 per-member, 1 top-level computed", + policy: { + models: {claim: {weight: "number", income: "number", price: "number", balance: "number?", lines: "line[]", contact: "contactInfo"}, line: {score: "number?", balance: "number?", rate: "number?", age: "number?", employees: "employee[]"}, employee: {years: "number", priority: "boolean", active: "boolean"}, contactInfo: {age: "number", active: "boolean?", verified: "boolean"}}, + blocks: [ + {match: "line.flags.decision", arms: [["50 > (line.rate ?? 0)", "`${(claim.balance ?? 0)}/${(line.age ?? 0)}`"], ["matches((split(claim.scores.band, '-')[1] ?? 'none'), 'a')", "`${claim.scores.band}/${matches(claim.scores.band, '^[A-Z]')}`"], ["", "`${(claim.quota ?? 0)}/${claim.price}`"]]}, + {expression: "contactInfo.margin", value: "len((contactInfo.verified ? 'high' : 'none')) > 2"}, + {assertion: "penalty", conditions: [["and", "matches(claim.scores.band, 'a')", 0], ["or", "none(claim.lines, #.flags.decision == 'low')", 1]]}, + {match: "claim.scores.band", arms: [["isNumeric(string(claim.exposure))", "string((claim.contact.active ?? false))"], ["claim.balance != null", "'retail'"], ["", "string(claim.contact.age)"]]}, + {expression: "claim.surcharge", value: "map(claim.lines, ((#.balance ?? 0) / 3))"}, + {assertion: "claim.exposure", conditions: [["and", "(claim.contact.margin or (claim.contact.active ?? false))", 1], ["and", "(claim.contact.verified or (claim.contact.active ?? false))", 2], ["and", "some(claim.lines, not ((#.balance ?? 0) > 5))", 1], "claim.weight in [-1..113]", ["and", "(claim.contact.margin and claim.contact.margin)", 2]]}, + {table: "t10", hit: "collect", inputs: ["claim.balance", "penalty"], outputs: ["contactInfo.net"], rules: [ + ["2", "true", "claim.scores.band"], + ["", "", "`${(claim.discount ?? 0)}/${claim.income}`"], + ]}, + {match: "line.risk", arms: [["isNumeric(line.flags.decision)", "claim.contact.margin"], ["all(line.employees, #.years > #.years)", "none(line.employees, #.years in [17..109])"], ["", "some(line.employees, not (#.priority))"]]}, + {table: "t8", inputs: ["line.flags.decision", "claim.weight", "claim.contact.verified"], outputs: ["line.adjusted[]", "line.ok"], rules: [ + ["'gold'", "> 1.5", "false", "", "claim.contact.margin"], + ["$ != 'high'", "> 100", "", "(claim.discount ?? 0)", "line.risk"], + ]}, + {table: "t5", inputs: [null, "claim.exposure"], outputs: ["claim.discount", "claim.quota", "claim.grade"], rules: [ + ["", "true", "claim.weight", "claim.weight", ""], + ["(claim.exposure or (claim.contact.active ?? false))", "", "5", "claim.contact.age", ""], + ["", "", "(claim.balance ?? 0)", "claim.price", "claim.exposure"], + ]}, + ], + }, + cases: [ + [{claim: {weight: 1000000, income: 10, price: 1e3, balance: 1000, lines: [{score: 1000000, balance: 250, rate: 100, age: 0.000001, employees: [{years: 0.1, priority: true, active: false}, {years: 18, priority: false, active: false}, {years: 3, priority: false, active: true}]}, {score: 1.5, balance: 3, rate: 1000, age: 1000, employees: [{years: -500, priority: true, active: false}]}, {score: 100, balance: 2, rate: 121, age: 1, employees: [{years: 100, priority: true, active: true}, {years: -0.01, priority: true, active: true}]}, {score: 0, balance: 2.50, rate: 99999999999999999999, age: 100, employees: [{years: 0.1, priority: false, active: false}, {years: 1e3, priority: false, active: true}]}], contact: {age: 0.5, active: false, verified: true}, extraField: "x"}}, {claim: {balance: 1000, contact: {active: false, age: 0.5, margin: true, net: ["1000/10"], verified: true}, discount: 1000, exposure: false, extraField: "x", grade: false, income: 10, lines: [{adjusted: [1000], age: 0.000001, balance: 250, employees: [{active: false, priority: true, years: 0.1}, {active: false, priority: false, years: 18}, {active: true, priority: false, years: 3}], flags: {decision: "1000/1000"}, ok: true, rate: 100, risk: true, score: 1000000}, {adjusted: [1000], age: 1000, balance: 3, employees: [{active: false, priority: true, years: -500}], flags: {decision: "1000/1000"}, ok: false, rate: 1000, risk: false, score: 1.5}, {adjusted: [1000], age: 1, balance: 2, employees: [{active: true, priority: true, years: 100}, {active: true, priority: true, years: -0.01}], flags: {decision: "1000/1000"}, ok: false, rate: 121, risk: false, score: 100}, {adjusted: [1000], age: 100, balance: 2.50, employees: [{active: false, priority: false, years: 0.1}, {active: true, priority: false, years: 1000}], flags: {decision: "1000/1000"}, ok: true, rate: 99999999999999999999, risk: true, score: 0}], price: 1000, quota: 1000, scores: {band: "retail"}, surcharge: [83.33333333333333333333333333, 1, 0.6666666666666666666666666667, 0.8333333333333333333333333333], weight: 1000000}, penalty: true}], + {input: {claim: {weight: -500, income: 10, price: 1, lines: [], contact: {age: 100, verified: false}}}, goals: ["claim.scores.band", "line.flags.decision"], output: {claim: {contact: {age: 100, margin: true, verified: false}, exposure: false, income: 10, lines: [], price: 1, scores: {band: "100"}, weight: -500}}}, + {input: {claim: {weight: -0.01, income: 0.5, price: 2.50, balance: 0.000001, lines: [{score: 0.25, balance: 1000000, age: 65, employees: [{years: 0.5, priority: false, active: false}, {years: 5, priority: true, active: false}]}], contact: {age: 1, active: false, verified: true}}}, goals: ["line.ok", "line.flags.decision"], output: {claim: {balance: 0.000001, contact: {active: false, age: 1, margin: true, verified: true}, exposure: false, income: 0.5, lines: [{adjusted: [], age: 65, balance: 1000000, employees: [{active: false, priority: false, years: 0.5}, {active: false, priority: true, years: 5}], flags: {decision: "0.000001/65"}, ok: null, score: 0.25}], price: 2.50, scores: {band: "retail"}, weight: -0.01}}}, + {input: {claim: {weight: 0.25, income: -500, price: 1000000, balance: 2, lines: [{score: -0.01, balance: 50, rate: 10, age: -0, employees: [{years: 0.25, priority: true, active: false}, {years: 10, priority: true, active: true}]}, {score: 0.25, balance: 99.99, rate: 65, age: -0.01, employees: []}, {score: 1e3, balance: 5, rate: 1000, age: 2, employees: [{years: 3, priority: true, active: true}, {years: 1, priority: false, active: false}]}, {score: 1000000, balance: 2.50, rate: 100, age: 65, employees: []}, {score: 0.5, balance: 0.5, rate: 233, age: 0, employees: [{years: 123456789.123, priority: false, active: true}, {years: 0.25, priority: false, active: false}]}], contact: {age: 3, active: false, verified: true}}}, goals: ["claim.discount", "line.flags.decision", "claim.grade"], output: {claim: {balance: 2, contact: {active: false, age: 3, margin: true, verified: true}, discount: 0.25, exposure: true, grade: true, income: -500, lines: [{age: 0, balance: 50, employees: [{active: false, priority: true, years: 0.25}, {active: true, priority: true, years: 10}], flags: {decision: "2/0"}, rate: 10, score: -0.01}, {age: -0.01, balance: 99.99, employees: [], flags: {decision: "0.25/1000000"}, rate: 65, score: 0.25}, {age: 2, balance: 5, employees: [{active: true, priority: true, years: 3}, {active: false, priority: false, years: 1}], flags: {decision: "0.25/1000000"}, rate: 1000, score: 1000}, {age: 65, balance: 2.50, employees: [], flags: {decision: "0.25/1000000"}, rate: 100, score: 1000000}, {age: 0, balance: 0.5, employees: [{active: true, priority: false, years: 123456789.123}, {active: false, priority: false, years: 0.25}], flags: {decision: "0.25/1000000"}, rate: 233, score: 0.5}], price: 1000000, quota: 0.25, scores: {band: "retail"}, weight: 0.25}}}, + {input: {claim: {weight: 1e3, income: 50, price: 0.1, balance: 0.5, lines: [{score: 2, balance: null, age: 2, employees: [{years: 7.25, priority: false, active: false}, {years: 1000, priority: false, active: true}, {years: 10, priority: false, active: true}]}, {score: 0.25, balance: 0.000001, rate: 1.5, age: 3, employees: [{years: 250, priority: true, active: true}]}], contact: {age: 1.5, verified: false}}}, goals: ["line.flags.decision", "penalty", "claim.discount"], output: {claim: {balance: 0.5, contact: {age: 1.5, margin: true, verified: false}, discount: 0.5, exposure: false, grade: false, income: 50, lines: [{age: 2, balance: null, employees: [{active: false, priority: false, years: 7.25}, {active: true, priority: false, years: 1000}, {active: true, priority: false, years: 10}], flags: {decision: "0.5/2"}, score: 2}, {age: 3, balance: 0.000001, employees: [{active: true, priority: true, years: 250}], flags: {decision: "0.5/3"}, rate: 1.5, score: 0.25}], price: 0.1, quota: 0.1, scores: {band: "retail"}, weight: 1000}, penalty: true}}, + {input: {claim: {weight: 100, income: 7.25, price: 1, balance: null, lines: [{score: 100, balance: 100, rate: -0, age: null, employees: [{years: 2, priority: false, active: false}, {years: 0, priority: true, active: false}]}], contact: {age: 465, active: null, verified: true}}}, goals: ["claim.scores.band", "claim.exposure"], output: {claim: {balance: null, contact: {active: null, age: 465, margin: true, verified: true}, exposure: false, income: 7.25, lines: [{age: null, balance: 100, employees: [{active: false, priority: false, years: 2}, {active: false, priority: true, years: 0}], rate: 0, score: 100}], price: 1, scores: {band: "465"}, weight: 100}}}, + {input: {claim: {weight: -0.5, income: 0, price: 2, balance: 5, lines: [], contact: {age: 1, active: false, verified: true}, extraField: 1}}, goals: ["claim.discount", "line.flags.decision", "contactInfo.margin"], output: {claim: {balance: 5, contact: {active: false, age: 1, margin: true, verified: true}, discount: 5, exposure: false, extraField: 1, grade: false, income: 0, lines: [], price: 2, quota: 2, scores: {band: "retail"}, weight: -0.5}}}, + {input: {claim: {weight: 99999999999999999999, income: 100, price: 5, balance: 1.5, lines: [{score: 10, balance: 1, age: null, employees: [{years: 3, priority: true, active: false}, {years: 2, priority: true, active: false}]}], contact: {age: 2, active: false, verified: false}}}, goals: ["contactInfo.margin"], output: {claim: {balance: 1.5, contact: {active: false, age: 2, margin: true, verified: false}, income: 100, lines: [{age: null, balance: 1, employees: [{active: false, priority: true, years: 3}, {active: false, priority: true, years: 2}], score: 10}], price: 5, weight: 99999999999999999999}}}, + {input: {claim: {weight: 1, income: 10, price: 51, lines: [{score: null, balance: null, rate: 5, employees: [{years: 0.5, priority: true, active: false}, {years: 5, priority: false, active: true}]}, {balance: null, rate: 50, age: null, employees: [{years: 0.25, priority: false, active: false}, {years: 7.25, priority: true, active: true}, {years: 2, priority: false, active: false}]}, {balance: 100, rate: 123456789.123, age: 100, employees: [{years: -0, priority: true, active: true}, {years: 1000, priority: false, active: true}]}, {score: null, balance: 99.99, rate: null, age: 100, employees: [{years: 99.99, priority: false, active: false}]}, {balance: 3, age: 2, employees: [{years: 2, priority: true, active: true}, {years: 3, priority: false, active: false}, {years: 123456789.123, priority: false, active: true}]}], contact: {age: 3, verified: false}}}, goals: ["claim.quota", "contactInfo.net"], output: {claim: {contact: {age: 3, margin: true, net: ["0/10"], verified: false}, discount: 0, exposure: false, grade: false, income: 10, lines: [{balance: null, employees: [{active: false, priority: true, years: 0.5}, {active: true, priority: false, years: 5}], flags: {decision: "0/0"}, rate: 5, score: null}, {age: null, balance: null, employees: [{active: false, priority: false, years: 0.25}, {active: true, priority: true, years: 7.25}, {active: false, priority: false, years: 2}], flags: {decision: "51/51"}, rate: 50}, {age: 100, balance: 100, employees: [{active: true, priority: true, years: 0}, {active: true, priority: false, years: 1000}], flags: {decision: "51/51"}, rate: 123456789.123}, {age: 100, balance: 99.99, employees: [{active: false, priority: false, years: 99.99}], flags: {decision: "0/100"}, rate: null, score: null}, {age: 2, balance: 3, employees: [{active: true, priority: true, years: 2}, {active: false, priority: false, years: 3}, {active: true, priority: false, years: 123456789.123}], flags: {decision: "0/2"}}], price: 51, quota: 51, scores: {band: "3"}, weight: 1}, penalty: false}}, + {input: {claim: {weight: 0.5, income: 0.25, price: 99999999999999999999, balance: -500, lines: [{score: 100, balance: 0.1, rate: 346, age: 1, employees: [{years: 123456789.123, priority: false, active: false}, {years: 3, priority: false, active: true}]}, {score: 1e3, balance: 123456789.123, rate: 99999999999999999999, age: 99.99, employees: [{years: 2.50, priority: false, active: false}, {years: 0.5, priority: true, active: false}]}, {score: 0.5, balance: 0.5, rate: 7.25, age: 1, employees: [{years: 123456789.123, priority: true, active: false}]}], contact: {age: 18, active: false, verified: true}, extraField: "x"}}, goals: ["claim.exposure"], output: {claim: {balance: -500, contact: {active: false, age: 18, margin: true, verified: true}, exposure: true, extraField: "x", income: 0.25, lines: [{age: 1, balance: 0.1, employees: [{active: false, priority: false, years: 123456789.123}, {active: true, priority: false, years: 3}], rate: 346, score: 100}, {age: 99.99, balance: 123456789.123, employees: [{active: false, priority: false, years: 2.50}, {active: false, priority: true, years: 0.5}], rate: 99999999999999999999, score: 1000}, {age: 1, balance: 0.5, employees: [{active: false, priority: true, years: 123456789.123}], rate: 7.25, score: 0.5}], price: 99999999999999999999, weight: 0.5}}}, + {input: {claim: {weight: -0, income: 398, price: -0.5, balance: 1, lines: [{score: 1e3, balance: 3, rate: 1, age: 5, employees: [{years: 7.25, priority: true, active: false}, {years: 0.5, priority: false, active: false}]}, {score: 18, balance: 0.25, rate: 488, age: 10, employees: [{years: 1e3, priority: true, active: false}]}], contact: {age: 10, active: true, verified: false}}}, goals: ["contactInfo.margin"], output: {claim: {balance: 1, contact: {active: true, age: 10, margin: true, verified: false}, income: 398, lines: [{age: 5, balance: 3, employees: [{active: false, priority: true, years: 7.25}, {active: false, priority: false, years: 0.5}], rate: 1, score: 1000}, {age: 10, balance: 0.25, employees: [{active: false, priority: true, years: 1000}], rate: 488, score: 18}], price: -0.5, weight: 0}}}, + {input: {claim: {weight: -0.5, income: 99.99, price: 0.25, balance: 3, lines: [{balance: 1.5, rate: null, age: 99.99, employees: [{years: 250, priority: false, active: true}, {years: -0.01, priority: false, active: true}, {years: 123456789.123, priority: false, active: false}]}, {balance: 5, rate: null, age: null, employees: [{years: 99.99, priority: false, active: false}, {years: 10, priority: false, active: false}]}, {score: -1, balance: 99999999999999999999, rate: 1.5, age: -0.5, employees: [{years: 99.99, priority: true, active: true}, {years: 65, priority: true, active: false}]}, {balance: 1, rate: 0.25, employees: [{years: 99.99, priority: false, active: false}, {years: 123456789.123, priority: true, active: false}]}], contact: {age: 0.25, verified: false}}}, goals: ["line.adjusted", "contactInfo.margin", "line.risk"], output: {claim: {balance: 3, contact: {age: 0.25, margin: true, verified: false}, exposure: false, income: 99.99, lines: [{adjusted: [], age: 99.99, balance: 1.5, employees: [{active: true, priority: false, years: 250}, {active: true, priority: false, years: -0.01}, {active: false, priority: false, years: 123456789.123}], flags: {decision: "3/99.99"}, ok: null, rate: null, risk: true}, {adjusted: [], age: null, balance: 5, employees: [{active: false, priority: false, years: 99.99}, {active: false, priority: false, years: 10}], flags: {decision: "3/0"}, ok: null, rate: null, risk: true}, {adjusted: [], age: -0.5, balance: 99999999999999999999, employees: [{active: true, priority: true, years: 99.99}, {active: false, priority: true, years: 65}], flags: {decision: "3/-0.5"}, ok: null, rate: 1.5, risk: false, score: -1}, {adjusted: [], balance: 1, employees: [{active: false, priority: false, years: 99.99}, {active: false, priority: true, years: 123456789.123}], flags: {decision: "3/0"}, ok: null, rate: 0.25, risk: true}], price: 0.25, scores: {band: "retail"}, weight: -0.5}}}, + {input: {claim: {weight: -0, income: 99999999999999999999, price: 0.1, balance: 7.25, lines: [{score: 65, rate: null, age: 0.25, employees: [{years: 250, priority: false, active: true}, {years: 0, priority: false, active: false}]}, {score: null, rate: 7.25, age: -0.01, employees: [{years: 5, priority: false, active: false}]}, {score: 1, balance: 123456789.123, age: null, employees: [{years: 65, priority: false, active: true}, {years: 1.5, priority: false, active: false}]}, {score: null, balance: null, rate: 1000, employees: [{years: 1e3, priority: false, active: false}, {years: 3, priority: true, active: false}]}, {score: null, balance: 0.5, rate: null, employees: [{years: 0, priority: false, active: true}, {years: 2, priority: false, active: true}]}, {score: 1000000, balance: null, age: 7.25, employees: [{years: 2.50, priority: true, active: false}, {years: -0, priority: false, active: false}, {years: 100, priority: false, active: true}]}, {score: null, balance: 99999999999999999999, rate: 65, age: 18, employees: [{years: 2.50, priority: true, active: true}, {years: 250, priority: true, active: true}]}, {score: 50, rate: 10, age: 123456789.123, employees: [{years: 0.25, priority: true, active: false}]}, {balance: null, age: -1, employees: []}, {score: 5, balance: null, rate: 1000, age: 100, employees: [{years: 0.5, priority: true, active: false}, {years: 0.25, priority: true, active: true}]}, {balance: null, rate: null, age: -0.5, employees: []}], contact: {age: 123456789.123, active: false, verified: false}}}, goals: ["claim.exposure", "contactInfo.net"], output: {claim: {balance: 7.25, contact: {active: false, age: 123456789.123, margin: true, net: ["7.25/99999999999999999999"], verified: false}, discount: 7.25, exposure: false, grade: false, income: 99999999999999999999, lines: [{age: 0.25, employees: [{active: true, priority: false, years: 250}, {active: false, priority: false, years: 0}], flags: {decision: "7.25/0.25"}, rate: null, score: 65}, {age: -0.01, employees: [{active: false, priority: false, years: 5}], flags: {decision: "7.25/-0.01"}, rate: 7.25, score: null}, {age: null, balance: 123456789.123, employees: [{active: true, priority: false, years: 65}, {active: false, priority: false, years: 1.5}], flags: {decision: "7.25/0"}, score: 1}, {balance: null, employees: [{active: false, priority: false, years: 1000}, {active: false, priority: true, years: 3}], flags: {decision: "0.1/0.1"}, rate: 1000, score: null}, {balance: 0.5, employees: [{active: true, priority: false, years: 0}, {active: true, priority: false, years: 2}], flags: {decision: "7.25/0"}, rate: null, score: null}, {age: 7.25, balance: null, employees: [{active: false, priority: true, years: 2.50}, {active: false, priority: false, years: 0}, {active: true, priority: false, years: 100}], flags: {decision: "7.25/7.25"}, score: 1000000}, {age: 18, balance: 99999999999999999999, employees: [{active: true, priority: true, years: 2.50}, {active: true, priority: true, years: 250}], flags: {decision: "0.1/0.1"}, rate: 65, score: null}, {age: 123456789.123, employees: [{active: false, priority: true, years: 0.25}], flags: {decision: "7.25/123456789.123"}, rate: 10, score: 50}, {age: -1, balance: null, employees: [], flags: {decision: "7.25/-1"}}, {age: 100, balance: null, employees: [{active: false, priority: true, years: 0.5}, {active: true, priority: true, years: 0.25}], flags: {decision: "0.1/0.1"}, rate: 1000, score: 5}, {age: -0.5, balance: null, employees: [], flags: {decision: "7.25/-0.5"}, rate: null}], price: 0.1, quota: 0.1, scores: {band: "retail"}, weight: 0}, penalty: true}}, + {input: {claim: {weight: 10, income: 18, price: 0.1, balance: 1, lines: [{score: 65, balance: 1, rate: 100, age: 123456789.123, employees: [{years: 0.25, priority: false, active: true}, {years: 100, priority: true, active: false}, {years: 0, priority: true, active: true}]}], contact: {age: 1000000, active: false, verified: true}, extraField: 1}}, goals: ["contactInfo.margin", "claim.grade"], output: {claim: {balance: 1, contact: {active: false, age: 1000000, margin: true, verified: true}, discount: 10, exposure: true, extraField: 1, grade: true, income: 18, lines: [{age: 123456789.123, balance: 1, employees: [{active: true, priority: false, years: 0.25}, {active: false, priority: true, years: 100}, {active: true, priority: true, years: 0}], rate: 100, score: 65}], price: 0.1, quota: 10, weight: 10}}}, + {input: {claim: {weight: 0.25, income: 0.25, price: 5, balance: 18, lines: [], contact: {age: 5, active: false, verified: false}}}, goals: ["claim.surcharge", "claim.quota", "line.adjusted"], output: {claim: {balance: 18, contact: {active: false, age: 5, margin: true, verified: false}, discount: 18, exposure: false, grade: false, income: 0.25, lines: [], price: 5, quota: 5, scores: {band: "retail"}, surcharge: [], weight: 0.25}}}, + {input: {claim: {weight: 10, income: 0.5, price: 65, balance: null, lines: [{score: 437, balance: 431, rate: 3, age: 18, employees: [{years: 18, priority: true, active: false}, {years: 3, priority: false, active: false}]}, {score: 100, balance: 123456789.123, rate: 5, age: 99999999999999999999, employees: [{years: -0, priority: true, active: true}, {years: 0, priority: true, active: true}]}, {score: 2, balance: null, age: 0, employees: [{years: 0, priority: false, active: true}]}], contact: {age: 18, active: null, verified: false}}}, goals: ["claim.surcharge", "claim.exposure"], output: {claim: {balance: null, contact: {active: null, age: 18, margin: true, verified: false}, exposure: false, income: 0.5, lines: [{age: 18, balance: 431, employees: [{active: false, priority: true, years: 18}, {active: false, priority: false, years: 3}], rate: 3, score: 437}, {age: 99999999999999999999, balance: 123456789.123, employees: [{active: true, priority: true, years: 0}, {active: true, priority: true, years: 0}], rate: 5, score: 100}, {age: 0, balance: null, employees: [{active: true, priority: false, years: 0}], score: 2}], price: 65, surcharge: [143.66666666666666666666666667, 41152263.041, 0], weight: 10}}}, + {input: {claim: {weight: 5, income: -1, price: 250, balance: 2, lines: [{score: 18, balance: 123456789.123, rate: null, age: 5, employees: [{years: 2, priority: false, active: false}, {years: 0.5, priority: true, active: false}]}], contact: {age: 2, active: null, verified: true}}}, goals: ["penalty", "claim.discount", "contactInfo.net"], output: {claim: {balance: 2, contact: {active: null, age: 2, margin: true, net: ["retail", "2/-1"], verified: true}, discount: 2, exposure: false, grade: false, income: -1, lines: [{age: 5, balance: 123456789.123, employees: [{active: false, priority: false, years: 2}, {active: false, priority: true, years: 0.5}], flags: {decision: "2/5"}, rate: null, score: 18}], price: 250, quota: 250, scores: {band: "retail"}, weight: 5}, penalty: true}}, + [{claim: {weight: 1000000, income: 65, price: 5, balance: 0.000001, lines: [{rate: -500, age: 10, employees: [{years: -500, priority: true, active: false}]}, {rate: 100, employees: [{years: 100, priority: false, active: false}]}], contact: {age: 50, verified: true}}}, {claim: {balance: 0.000001, contact: {age: 50, margin: true, net: ["0.000001/65"], verified: true}, discount: 0.000001, exposure: false, grade: false, income: 65, lines: [{adjusted: [0.000001], age: 10, employees: [{active: false, priority: true, years: -500}], flags: {decision: "0.000001/10"}, ok: false, rate: -500, risk: false}, {adjusted: [0.000001], employees: [{active: false, priority: false, years: 100}], flags: {decision: "5/5"}, ok: true, rate: 100, risk: true}], price: 5, quota: 5, scores: {band: "retail"}, surcharge: [0, 0], weight: 1000000}, penalty: true}], + {input: {claim: {weight: 5, income: 0, price: 0.000001, lines: [{score: 50, balance: -0.01, rate: 1.5, age: -500, employees: []}], contact: {age: 3, active: false, verified: true}}}, goals: ["claim.discount"], output: {claim: {contact: {active: false, age: 3, margin: true, verified: true}, discount: 5, exposure: true, grade: true, income: 0, lines: [{age: -500, balance: -0.01, employees: [], rate: 1.5, score: 50}], price: 0.000001, quota: 5, weight: 5}}}, + {input: {claim: {weight: 1, income: 1000, price: -500, balance: 250, lines: [{score: 65, balance: 5, rate: 5, age: 7.25, employees: [{years: -0.5, priority: false, active: true}, {years: 0.1, priority: true, active: true}]}, {score: 7.25, balance: 2, rate: 3, age: 1.5, employees: [{years: 1.5, priority: true, active: false}, {years: 50, priority: false, active: true}, {years: -0.5, priority: false, active: true}]}, {score: 2.50, balance: 0.000001, rate: 0.25, age: -0.5, employees: [{years: 5, priority: true, active: false}]}], contact: {age: 0.25, active: false, verified: true}}}, goals: ["contactInfo.margin", "line.ok"], output: {claim: {balance: 250, contact: {active: false, age: 0.25, margin: true, verified: true}, exposure: true, income: 1000, lines: [{adjusted: [], age: 7.25, balance: 5, employees: [{active: true, priority: false, years: -0.5}, {active: true, priority: true, years: 0.1}], flags: {decision: "250/7.25"}, ok: null, rate: 5, score: 65}, {adjusted: [], age: 1.5, balance: 2, employees: [{active: false, priority: true, years: 1.5}, {active: true, priority: false, years: 50}, {active: true, priority: false, years: -0.5}], flags: {decision: "250/1.5"}, ok: null, rate: 3, score: 7.25}, {adjusted: [], age: -0.5, balance: 0.000001, employees: [{active: false, priority: true, years: 5}], flags: {decision: "250/-0.5"}, ok: null, rate: 0.25, score: 2.50}], price: -500, scores: {band: "retail"}, weight: 1}}}, + {input: {claim: {weight: 0.25, income: 3, price: 100, balance: null, lines: [], contact: {age: 10, active: null, verified: true}}}, goals: ["line.flags.decision"], output: {claim: {balance: null, contact: {active: null, age: 10, margin: true, verified: true}, exposure: false, income: 3, lines: [], price: 100, scores: {band: "10"}, weight: 0.25}}}, + ], +} + +// seed 354200 (attempt 0) +{ + name: "goals 43: order/loans/drivers: 1 assertion, 2 expression, 1 match, 4 table; 5 root, 6 per-member, 3 top-level computed", + policy: { + models: {order: {balance: "number", country: "string?", dueDate: "date", weight: "number", kind: "string(retail|corporate)?", loans: "loan[]"}, loan: {qty: "number?", flagged: "boolean", weight: "number?", drivers: "driver[]"}, driver: {years: "number"}}, + blocks: [ + {table: "t1", inputs: ["loan.qty", "len((order.country ?? ''))", "round(order.balance / 7, 4)"], outputs: ["loan.summary"], rules: [ + ["1", "<= 100", "[0..409]", ""], + ["2", ">= 100", "0.25", "loan.flagged"], + ["0.5, 0.25", "[1..23]", "< 5", "loan.flagged"], + ["1.5, 0", "[50..489]", "0.25", "loan.flagged"], + ["3", "> 250", "", "loan.flagged"], + ["3, 0", "", ">= 2", ""], + ["", "", "", "loan.flagged"], + ]}, + {expression: "order.risk", value: "{a: (order.country ?? ''), n: order.weight}"}, + {table: "t3", hit: "collect", inputs: ["loan.summary", "loan.weight", null], outputs: ["loan.grade"], rules: [ + ["true", "0.5", "order.balance in [30..175]", "string((loan.weight ?? 0))"], + ["", "", "len((order.country ?? '')) > 3", "(order.country ?? '')"], + ["true", "1.5, 1", "0.5 <= order.weight", "string(order.risk.n)"], + ["false", "3", "((loan.summary ?? false) and (loan.summary ?? false))", "order.risk.a"], + ["true", "50", "(loan.weight ?? 0) >= (loan.weight ?? 0)", "order.risk.a"], + ["true", "", "((loan.summary ?? false) or loan.flagged)", "(order.country ?? '')"], + ]}, + {expression: "loan.fee", value: "{ok: 0.25, v: abs((loan.flagged ? order.weight : 0.25))}"}, + {match: "order.capped", arms: [["order.dueDate.year() == order.weight", "upper((order.country ?? ''))"], ["startsWith((order.country ?? ''), 'a')", "`${'US'}/${(order.risk.n * order.risk.n)}`"], ["isNumeric(((order.country ?? '') + '-' + (order.country ?? '')))", "('A1' + '-' + order.risk.a)"], ["", "(order.weight > 250 ? (order.country ?? '') : 'DE')"]]}, + {table: "t6", inputs: ["order.dueDate", "(order.kind ?? '')"], outputs: ["exposure", "net", "decision"], rules: [ + ["", "", "trunc(order.risk.n)", "order.risk.n", ""], + ["> d('2000-06-30')", "'retail', 'corporate'", "order.risk.n", "(avg(map(order.loans, 100)) ?? 0)", "`${order.weight}/${order.balance}`"], + ]}, + {table: "t7", hit: "collect", inputs: ["order.country", "order.risk.n", "order.dueDate"], outputs: ["loan.scores.segment"], rules: [ + ["'DE'", "< 3", "< d('2024-01-01')", "'US'"], + ["'high'", "<= 10", "", "order.risk.a"], + ["'ok'", "> 5", "> d('2024-01-01')", "(decision ?? '')"], + ["'low'", "", "", "((loan.summary ?? false) ? order.capped : order.capped)"], + ["'high'", "", "> d('2025-01-01')", "'VIP'"], + ["'gold'", "0.5, 1000", ">= d('2025-03-20')", "'Oslo'"], + ["'a'", "1000", "> d('2024-01-01')", "(order.country ?? '')"], + ]}, + {assertion: "order.ok", conditions: [["or", "some(order.loans, (#.weight ?? 0) != 0.5)", 1], ["and", "((exposure ?? 0) > 100 or 0.5 > 0.25)", 1], ["and", "(none(order.loans, (#.flagged and #.flagged)) or order.balance in [38..39))", 0], ["or", "((net ?? 0) != order.risk.n and isNumeric(order.risk.a))", 2]]}, + ], + }, + cases: [ + {input: {order: {balance: 5, country: null, dueDate: "2025-03-20T10:15:30Z", weight: 100, kind: "retail", loans: [{flagged: true, drivers: [{years: 1.5}]}, {qty: null, flagged: true, weight: 0, drivers: []}]}}, goals: ["net", "loan.summary", "order.ok"], output: {decision: "100/5", exposure: 100, net: 100, order: {balance: 5, country: null, dueDate: "2025-03-20T10:15:30Z", kind: "retail", loans: [{drivers: [{years: 1.5}], flagged: true, summary: true}, {drivers: [], flagged: true, qty: null, summary: true, weight: 0}], ok: false, risk: {a: "", n: 100}, weight: 100}}}, + {input: {order: {balance: 10, country: "12", dueDate: "2025-03-20", weight: 18, kind: "retail", loans: []}}, goals: ["loan.scores.segment", "loan.summary", "net"], output: {decision: "18/10", exposure: 18, net: 18, order: {balance: 10, country: "12", dueDate: "2025-03-20", kind: "retail", loans: [], risk: {a: "12", n: 18}, weight: 18}}}, + {input: {order: {balance: 0.25, dueDate: "1990-06-15", weight: 0.5, kind: "retail", loans: [{flagged: true, weight: 1.5, drivers: [{years: 1e3}, {years: 0.5}]}, {qty: 18, flagged: false, weight: 0.000001, drivers: [{years: 1.5}, {years: 0.1}]}, {flagged: true, weight: null, drivers: [{years: 3}, {years: 1000}]}, {flagged: false, drivers: [{years: 5}, {years: 0.25}]}, {qty: 100, flagged: false, weight: null, drivers: [{years: 0.5}, {years: 123456789.123}]}]}}, goals: ["loan.summary", "order.capped"], output: {order: {balance: 0.25, capped: "DE", dueDate: "1990-06-15", kind: "retail", loans: [{drivers: [{years: 1000}, {years: 0.5}], flagged: true, summary: true, weight: 1.5}, {drivers: [{years: 1.5}, {years: 0.1}], flagged: false, qty: 18, summary: false, weight: 0.000001}, {drivers: [{years: 3}, {years: 1000}], flagged: true, summary: true, weight: null}, {drivers: [{years: 5}, {years: 0.25}], flagged: false, summary: false}, {drivers: [{years: 0.5}, {years: 123456789.123}], flagged: false, qty: 100, summary: false, weight: null}], weight: 0.5}}}, + {input: {order: {balance: 10, dueDate: "1990-06-15", weight: 2, loans: [{flagged: true, weight: 100, drivers: []}, {qty: 0.5, flagged: true, weight: 99999999999999999999, drivers: [{years: 0}]}, {flagged: false, weight: 1000, drivers: [{years: 99999999999999999999}]}, {flagged: true, weight: 3, drivers: [{years: 50}, {years: 0.000001}]}]}}, goals: ["order.capped"], output: {order: {balance: 10, capped: "DE", dueDate: "1990-06-15", loans: [{drivers: [], flagged: true, weight: 100}, {drivers: [{years: 0}], flagged: true, qty: 0.5, weight: 99999999999999999999}, {drivers: [{years: 99999999999999999999}], flagged: false, weight: 1000}, {drivers: [{years: 50}, {years: 0.000001}], flagged: true, weight: 3}], weight: 2}}}, + [{order: {balance: 0.25, country: "abc", dueDate: "1990-06-15", weight: 0.25, loans: []}}, {decision: null, exposure: 0, net: 0.25, order: {balance: 0.25, country: "abc", dueDate: "1990-06-15", loans: [], ok: false, risk: {a: "abc", n: 0.25}, weight: 0.25}}], + [{order: {balance: 3, country: "DE", dueDate: "1990-06-15", weight: 0.25, kind: "corporate", loans: [{qty: 3, flagged: true, weight: 100, drivers: []}]}}, {decision: null, exposure: 0, net: 0.25, order: {balance: 3, country: "DE", dueDate: "1990-06-15", kind: "corporate", loans: [{drivers: [], fee: {ok: 0.25, v: 0.25}, flagged: true, grade: ["DE"], qty: 3, scores: {segment: ["US"]}, summary: true, weight: 100}], ok: false, risk: {a: "DE", n: 0.25}, weight: 0.25}}], + {input: {order: {balance: 0.5, country: "Oslo", dueDate: "2025-03-20", weight: 1.5, kind: "corporate", loans: []}}, goals: ["decision", "order.capped", "loan.summary"], output: {decision: "1.5/0.5", exposure: 1, net: 1.5, order: {balance: 0.5, capped: "DE", country: "Oslo", dueDate: "2025-03-20", kind: "corporate", loans: [], risk: {a: "Oslo", n: 1.5}, weight: 1.5}}}, + {input: {order: {balance: 123456789.123, country: "12", dueDate: "2000-01-01", weight: -500, kind: "corporate", loans: []}}, goals: ["loan.fee", "loan.summary"], output: {order: {balance: 123456789.123, country: "12", dueDate: "2000-01-01", kind: "corporate", loans: [], weight: -500}}}, + {input: {order: {balance: 0.5, country: "none", dueDate: "2000-01-01", weight: 1000, kind: null, loans: [{qty: null, flagged: true, weight: 250, drivers: []}]}}, goals: ["exposure"], output: {decision: null, exposure: 1000, net: 1000, order: {balance: 0.5, country: "none", dueDate: "2000-01-01", kind: null, loans: [{drivers: [], flagged: true, qty: null, weight: 250}], risk: {a: "none", n: 1000}, weight: 1000}}}, + {input: {order: {balance: 1e3, country: null, dueDate: "2025-03-20", weight: 0.5, kind: "retail", loans: [{flagged: false, weight: 3, drivers: []}, {qty: -1, flagged: false, weight: null, drivers: []}, {qty: 0.25, flagged: false, drivers: [{years: 0.5}]}, {flagged: true, weight: null, drivers: [{years: 10}, {years: 0.25}]}, {qty: 2, flagged: false, weight: null, drivers: [{years: 0.1}, {years: 2.50}]}]}}, goals: ["loan.fee"], output: {order: {balance: 1000, country: null, dueDate: "2025-03-20", kind: "retail", loans: [{drivers: [], fee: {ok: 0.25, v: 0.25}, flagged: false, weight: 3}, {drivers: [], fee: {ok: 0.25, v: 0.25}, flagged: false, qty: -1, weight: null}, {drivers: [{years: 0.5}], fee: {ok: 0.25, v: 0.25}, flagged: false, qty: 0.25}, {drivers: [{years: 10}, {years: 0.25}], fee: {ok: 0.25, v: 0.5}, flagged: true, weight: null}, {drivers: [{years: 0.1}, {years: 2.50}], fee: {ok: 0.25, v: 0.25}, flagged: false, qty: 2, weight: null}], weight: 0.5}}}, + {input: {order: {balance: 18, country: "VIP", dueDate: "2024-02-29", weight: 2, kind: "retail", loans: [{qty: 1, flagged: false, weight: 10, drivers: []}, {qty: 18, flagged: false, weight: 0.5, drivers: [{years: 100}, {years: 0.25}]}], extraField: 1}}, goals: ["loan.summary", "order.ok"], output: {decision: "2/18", exposure: 2, net: 2, order: {balance: 18, country: "VIP", dueDate: "2024-02-29", extraField: 1, kind: "retail", loans: [{drivers: [], flagged: false, qty: 1, summary: false, weight: 10}, {drivers: [{years: 100}, {years: 0.25}], flagged: false, qty: 18, summary: false, weight: 0.5}], ok: false, risk: {a: "VIP", n: 2}, weight: 2}}}, + {input: {order: {balance: 5, country: null, dueDate: "1990-06-15", weight: 1.5, kind: null, loans: []}}, goals: ["order.risk"], output: {order: {balance: 5, country: null, dueDate: "1990-06-15", kind: null, loans: [], risk: {a: "", n: 1.5}, weight: 1.5}}}, + [{order: {balance: 1.5, country: "DE", dueDate: "1990-06-15", weight: 0.5, kind: "retail", loans: [{qty: 10, flagged: true, weight: 0.5, drivers: [{years: 2.50}]}]}}, {decision: null, exposure: 0, net: 0.5, order: {balance: 1.5, country: "DE", dueDate: "1990-06-15", kind: "retail", loans: [{drivers: [{years: 2.50}], fee: {ok: 0.25, v: 0.5}, flagged: true, grade: ["DE"], qty: 10, scores: {segment: ["US"]}, summary: true, weight: 0.5}], ok: false, risk: {a: "DE", n: 0.5}, weight: 0.5}}], + {input: {order: {balance: 1000, country: null, dueDate: "2024-01-01", weight: 0.1, kind: "corporate", loans: [{qty: 250, flagged: false, weight: 250, drivers: [{years: 1.5}, {years: 2}]}, {flagged: false, weight: 0.5, drivers: [{years: -0}, {years: -0.01}]}, {qty: null, flagged: true, weight: null, drivers: [{years: 0.25}, {years: 0}]}, {flagged: false, drivers: [{years: 1000}, {years: 0.5}, {years: 99.99}]}, {flagged: true, drivers: []}]}}, goals: ["loan.scores.segment", "loan.fee", "loan.grade"], output: {order: {balance: 1000, country: null, dueDate: "2024-01-01", kind: "corporate", loans: [{drivers: [{years: 1.5}, {years: 2}], fee: {ok: 0.25, v: 0.25}, flagged: false, grade: [], qty: 250, scores: {segment: []}, summary: false, weight: 250}, {drivers: [{years: 0}, {years: -0.01}], fee: {ok: 0.25, v: 0.25}, flagged: false, grade: [], scores: {segment: []}, summary: false, weight: 0.5}, {drivers: [{years: 0.25}, {years: 0}], fee: {ok: 0.25, v: 0.1}, flagged: true, grade: [""], qty: null, scores: {segment: []}, summary: true, weight: null}, {drivers: [{years: 1000}, {years: 0.5}, {years: 99.99}], fee: {ok: 0.25, v: 0.25}, flagged: false, grade: [], scores: {segment: []}, summary: false}, {drivers: [], fee: {ok: 0.25, v: 0.1}, flagged: true, grade: [""], scores: {segment: []}, summary: true}], risk: {a: "", n: 0.1}, weight: 0.1}}}, + {input: {order: {balance: 1, country: null, dueDate: "2025-03-20", weight: 0.25, kind: null, loans: [{flagged: true, weight: 99999999999999999999, drivers: [{years: 250}]}, {flagged: false, weight: 341, drivers: []}, {flagged: true, drivers: [{years: 1}, {years: 0.5}]}, {flagged: true, drivers: [{years: 0.5}, {years: 0.5}, {years: 0.5}]}, {qty: 0.5, flagged: false, weight: -500, drivers: [{years: 1.5}, {years: 100}, {years: 250}]}]}}, goals: ["order.risk", "order.capped"], output: {order: {balance: 1, capped: "DE", country: null, dueDate: "2025-03-20", kind: null, loans: [{drivers: [{years: 250}], flagged: true, weight: 99999999999999999999}, {drivers: [], flagged: false, weight: 341}, {drivers: [{years: 1}, {years: 0.5}], flagged: true}, {drivers: [{years: 0.5}, {years: 0.5}, {years: 0.5}], flagged: true}, {drivers: [{years: 1.5}, {years: 100}, {years: 250}], flagged: false, qty: 0.5, weight: -500}], risk: {a: "", n: 0.25}, weight: 0.25}}}, + {input: {order: {balance: 0, country: "ok", dueDate: "2025-03-20", weight: 0, loans: [{flagged: false, weight: null, drivers: [{years: 0}, {years: 3}]}, {qty: null, flagged: false, weight: null, drivers: [{years: 65}, {years: 1}]}]}}, goals: ["exposure"], output: {decision: null, exposure: 0, net: 0, order: {balance: 0, country: "ok", dueDate: "2025-03-20", loans: [{drivers: [{years: 0}, {years: 3}], flagged: false, weight: null}, {drivers: [{years: 65}, {years: 1}], flagged: false, qty: null, weight: null}], risk: {a: "ok", n: 0}, weight: 0}}}, + {input: {order: {balance: 1000000, country: "none", dueDate: "2000-01-01", weight: 1, kind: "retail", loans: [{qty: 2, flagged: true, weight: 0.5, drivers: [{years: 10}, {years: 3}]}, {qty: 0.25, flagged: false, weight: 1, drivers: [{years: 0.5}, {years: 0.5}]}]}}, goals: ["loan.scores.segment", "decision", "loan.fee"], output: {decision: null, exposure: 1, net: 1, order: {balance: 1000000, country: "none", dueDate: "2000-01-01", kind: "retail", loans: [{drivers: [{years: 10}, {years: 3}], fee: {ok: 0.25, v: 1}, flagged: true, qty: 2, scores: {segment: []}, weight: 0.5}, {drivers: [{years: 0.5}, {years: 0.5}], fee: {ok: 0.25, v: 0.25}, flagged: false, qty: 0.25, scores: {segment: []}, weight: 1}], risk: {a: "none", n: 1}, weight: 1}}}, + {input: {order: {balance: 250, country: null, dueDate: "2030-12-31", weight: 50, kind: "corporate", loans: [{flagged: true, drivers: [{years: 1.5}, {years: 1.5}, {years: 1000}]}, {flagged: true, weight: 5, drivers: [{years: 0.25}, {years: 0.5}]}, {qty: 3, flagged: false, weight: 1, drivers: [{years: 5}, {years: 0.5}]}, {flagged: true, weight: 18, drivers: []}, {flagged: true, weight: null, drivers: [{years: 1}, {years: 0.5}]}, {qty: null, flagged: true, drivers: []}, {qty: 10, flagged: true, weight: 3, drivers: [{years: 250}, {years: 5}, {years: 5}]}, {qty: 3, flagged: true, weight: 3, drivers: [{years: 123456789.123}, {years: 250}]}, {qty: 2, flagged: false, weight: 0.5, drivers: []}, {qty: 3, flagged: false, weight: null, drivers: [{years: 1.5}, {years: -0}]}]}}, goals: ["loan.scores.segment"], output: {order: {balance: 250, country: null, dueDate: "2030-12-31", kind: "corporate", loans: [{drivers: [{years: 1.5}, {years: 1.5}, {years: 1000}], flagged: true, scores: {segment: []}}, {drivers: [{years: 0.25}, {years: 0.5}], flagged: true, scores: {segment: []}, weight: 5}, {drivers: [{years: 5}, {years: 0.5}], flagged: false, qty: 3, scores: {segment: []}, weight: 1}, {drivers: [], flagged: true, scores: {segment: []}, weight: 18}, {drivers: [{years: 1}, {years: 0.5}], flagged: true, scores: {segment: []}, weight: null}, {drivers: [], flagged: true, qty: null, scores: {segment: []}}, {drivers: [{years: 250}, {years: 5}, {years: 5}], flagged: true, qty: 10, scores: {segment: []}, weight: 3}, {drivers: [{years: 123456789.123}, {years: 250}], flagged: true, qty: 3, scores: {segment: []}, weight: 3}, {drivers: [], flagged: false, qty: 2, scores: {segment: []}, weight: 0.5}, {drivers: [{years: 1.5}, {years: 0}], flagged: false, qty: 3, scores: {segment: []}, weight: null}], risk: {a: "", n: 50}, weight: 50}}}, + {input: {order: {balance: 1000, country: "VIP", dueDate: "2025-03-20", weight: 1, kind: null, loans: [{qty: 2, flagged: true, drivers: [{years: 0.25}]}, {qty: 135, flagged: true, weight: 1e3, drivers: [{years: 100}, {years: 250}]}, {flagged: false, weight: 17, drivers: [{years: 18}, {years: 3}]}, {qty: null, flagged: false, weight: null, drivers: [{years: 1.5}, {years: 18}, {years: 100}]}]}}, goals: ["loan.summary", "order.ok", "loan.scores.segment"], output: {decision: null, exposure: 1, net: 1, order: {balance: 1000, country: "VIP", dueDate: "2025-03-20", kind: null, loans: [{drivers: [{years: 0.25}], flagged: true, qty: 2, scores: {segment: []}, summary: true}, {drivers: [{years: 100}, {years: 250}], flagged: true, qty: 135, scores: {segment: []}, summary: true, weight: 1000}, {drivers: [{years: 18}, {years: 3}], flagged: false, scores: {segment: []}, summary: false, weight: 17}, {drivers: [{years: 1.5}, {years: 18}, {years: 100}], flagged: false, qty: null, scores: {segment: []}, summary: false, weight: null}], ok: false, risk: {a: "VIP", n: 1}, weight: 1}}}, + {input: {order: {balance: 5, country: "a", dueDate: "2000-01-01", weight: 50, kind: "retail", loans: []}}, goals: ["order.risk", "net", "loan.fee"], output: {decision: null, exposure: 50, net: 50, order: {balance: 5, country: "a", dueDate: "2000-01-01", kind: "retail", loans: [], risk: {a: "a", n: 50}, weight: 50}}}, + ], +} + +// seed 354300 (attempt 0) +{ + name: "goals 44: tenant/accounts: 1 assertion, 2 expression, 5 match, 1 table; 4 root, 5 per-member, 1 top-level computed", + policy: { + models: {tenant: {weight: "number?", qty: "number?", age: "number", status: "string(open|closed|pending)?", since: "date", accounts: "acct[]"}, acct: {limit: "number", kind: "string(retail|corporate)", active: "boolean", flagged: "boolean"}}, + blocks: [ + {table: "t8", inputs: ["tenant.age"], outputs: ["tenant.scores.bucket"], rules: [ + ["[2..97]", "0.5"], + ["<= 0.5", "(tenant.weight ?? 0)"], + ["10", "(tenant.weight ?? 0)"], + ["", "(tenant.qty ?? 0)"], + ]}, + {match: "acct.review", arms: [["tenant.since < d('2025-01-01')", "len(tenant.accounts)"], ["", "tenant.age"]]}, + {expression: "acct.summary", value: "{n: 'a'}"}, + {match: "tenant.points", arms: [["(tenant.weight ?? 0) < (tenant.qty ?? 0)", "(tenant.weight ?? 0) == (tenant.qty ?? 0)"], ["", "(tenant.weight ?? 0) > 1.5"]]}, + {expression: "acct.calc.health", value: "len(acct.summary.n)"}, + {match: "capped", arms: [["tenant.since >= d('2000-06-30')", "string(tenant.age <= tenant.age)"], ["tenant.age in [17..30)", "(tenant.points ? 'US' : 'a')"], ["", "`${tenant.points}/${tenant.age}`"]]}, + {match: "tenant.margin", arms: [["some(tenant.accounts, (#.penalty or #.flagged))", "capped"], ["(all(tenant.accounts, not (#.active)) or 2 == tenant.age)", "string((tenant.age + (tenant.weight ?? 0)))"], ["matches(lower(capped), '^.{2,}$')", "(split(`${1000}/${(tenant.weight ?? 0)}`, '-')[0] ?? 'none')"], ["", "capped"]]}, + {match: "tenant.bonus", arms: [["tenant.since < d('2024-01-01')", "(tenant.qty ?? 0)"], ["capped in ['low', 'a']", "tenant.age"], ["capped in ['A1', 'gold']", "(tenant.weight ?? 0)"], ["tenant.status == null", "(tenant.age) / (abs((tenant.qty ?? 0)) + 1)"], ["", "10"]]}, + {assertion: "acct.penalty", conditions: [["and", "tenant.qty != null", 0], ["or", "tenant.since > d('2025-01-01')", 2], "all(tenant.accounts, #.limit < 0)", ["and", "(acct.flagged and acct.flagged)", 2], ["or", "all(tenant.accounts, (#.flagged and #.active))", 1]]}, + ], + }, + cases: [ + {input: {tenant: {weight: null, qty: 1, age: 10, status: "open", since: "2025-03-20T10:15:30Z", accounts: [{limit: 0.5, kind: "retail", active: true, flagged: false}, {limit: 2, kind: "retail", active: false, flagged: false}, {limit: 2, kind: "retail", active: true, flagged: false}, {limit: 498, kind: "retail", active: false, flagged: false}, {limit: 7.25, kind: "corporate", active: false, flagged: true}]}}, goals: ["acct.calc.health", "acct.summary", "acct.review"], output: {tenant: {accounts: [{active: true, calc: {health: 1}, flagged: false, kind: "retail", limit: 0.5, review: 10, summary: {n: "a"}}, {active: false, calc: {health: 1}, flagged: false, kind: "retail", limit: 2, review: 10, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: false, kind: "retail", limit: 2, review: 10, summary: {n: "a"}}, {active: false, calc: {health: 1}, flagged: false, kind: "retail", limit: 498, review: 10, summary: {n: "a"}}, {active: false, calc: {health: 1}, flagged: true, kind: "corporate", limit: 7.25, review: 10, summary: {n: "a"}}], age: 10, qty: 1, since: "2025-03-20T10:15:30Z", status: "open", weight: null}}}, + {input: {tenant: {weight: 0.5, qty: null, age: -0.01, status: null, since: "2024-02-29", accounts: []}}, goals: ["capped"], output: {capped: "true", tenant: {accounts: [], age: -0.01, qty: null, since: "2024-02-29", status: null, weight: 0.5}}}, + {input: {tenant: {weight: 250, qty: null, age: 1.5, status: null, since: "2025-03-20", accounts: [{limit: 1000000, kind: "corporate", active: true, flagged: false}, {limit: 2, kind: "corporate", active: true, flagged: false}, {limit: 1000, kind: "retail", active: true, flagged: true}, {limit: 1000, kind: "retail", active: true, flagged: true}, {limit: 100, kind: "retail", active: true, flagged: false}, {limit: 313, kind: "retail", active: false, flagged: false}, {limit: 100, kind: "corporate", active: false, flagged: true}, {limit: 1, kind: "corporate", active: true, flagged: false}, {limit: 99999999999999999999, kind: "retail", active: true, flagged: false}, {limit: 1000, kind: "corporate", active: false, flagged: true}, {limit: 0, kind: "corporate", active: true, flagged: false}, {limit: 65, kind: "corporate", active: true, flagged: true}]}}, goals: ["tenant.margin"], output: {capped: "true", tenant: {accounts: [{active: true, flagged: false, kind: "corporate", limit: 1000000, penalty: false}, {active: true, flagged: false, kind: "corporate", limit: 2, penalty: false}, {active: true, flagged: true, kind: "retail", limit: 1000, penalty: false}, {active: true, flagged: true, kind: "retail", limit: 1000, penalty: false}, {active: true, flagged: false, kind: "retail", limit: 100, penalty: false}, {active: false, flagged: false, kind: "retail", limit: 313, penalty: false}, {active: false, flagged: true, kind: "corporate", limit: 100, penalty: false}, {active: true, flagged: false, kind: "corporate", limit: 1, penalty: false}, {active: true, flagged: false, kind: "retail", limit: 99999999999999999999, penalty: false}, {active: false, flagged: true, kind: "corporate", limit: 1000, penalty: false}, {active: true, flagged: false, kind: "corporate", limit: 0, penalty: false}, {active: true, flagged: true, kind: "corporate", limit: 65, penalty: false}], age: 1.5, margin: "true", qty: null, since: "2025-03-20", status: null, weight: 250}}}, + {input: {tenant: {weight: 250, qty: 0, age: 1000, status: "open", since: "1990-06-15", accounts: []}}, goals: ["acct.review", "acct.calc.health"], output: {tenant: {accounts: [], age: 1000, qty: 0, since: "1990-06-15", status: "open", weight: 250}}}, + {input: {tenant: {weight: 0.5, qty: -0, age: 10, status: "closed", since: "2025-03-20T10:15:30Z", accounts: []}}, goals: ["tenant.margin"], output: {capped: "true", tenant: {accounts: [], age: 10, margin: "10.5", qty: 0, since: "2025-03-20T10:15:30Z", status: "closed", weight: 0.5}}}, + {input: {tenant: {weight: 2, age: 1e3, since: "2024-02-29", accounts: [{limit: 0, kind: "corporate", active: false, flagged: true}, {limit: 1, kind: "corporate", active: false, flagged: true}]}}, goals: ["tenant.scores.bucket", "acct.review"], output: {tenant: {accounts: [{active: false, flagged: true, kind: "corporate", limit: 0, review: 2}, {active: false, flagged: true, kind: "corporate", limit: 1, review: 2}], age: 1000, scores: {bucket: 0}, since: "2024-02-29", weight: 2}}}, + [{tenant: {weight: 0, qty: 10, age: -1, status: "open", since: "2030-12-31", accounts: [{limit: 18, kind: "retail", active: false, flagged: false}]}}, {capped: "true", tenant: {accounts: [{active: false, calc: {health: 1}, flagged: false, kind: "retail", limit: 18, penalty: false, review: -1, summary: {n: "a"}}], age: -1, bonus: 10, margin: "-1", qty: 10, scores: {bucket: 0}, since: "2030-12-31", status: "open", weight: 0}}], + {input: {tenant: {weight: null, qty: 5, age: 10, since: "1990-06-15", accounts: [{limit: 18, kind: "retail", active: false, flagged: true}]}}, goals: ["tenant.bonus"], output: {capped: "false/10", tenant: {accounts: [{active: false, flagged: true, kind: "retail", limit: 18}], age: 10, bonus: 5, points: false, qty: 5, since: "1990-06-15", weight: null}}}, + {input: {tenant: {weight: -0, age: -500, status: "open", since: "2030-12-31", accounts: [{limit: 10, kind: "retail", active: false, flagged: false}]}}, goals: ["tenant.margin"], output: {capped: "true", tenant: {accounts: [{active: false, flagged: false, kind: "retail", limit: 10, penalty: false}], age: -500, margin: "-500", since: "2030-12-31", status: "open", weight: 0}}}, + {input: {tenant: {qty: null, age: -0.01, since: "2030-12-31", accounts: [{limit: 40, kind: "retail", active: true, flagged: true}, {limit: 250, kind: "retail", active: true, flagged: false}, {limit: 3, kind: "retail", active: false, flagged: true}, {limit: 0, kind: "retail", active: true, flagged: true}]}}, goals: ["acct.calc.health", "acct.summary", "tenant.bonus"], output: {capped: "true", tenant: {accounts: [{active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 40, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: false, kind: "retail", limit: 250, summary: {n: "a"}}, {active: false, calc: {health: 1}, flagged: true, kind: "retail", limit: 3, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 0, summary: {n: "a"}}], age: -0.01, bonus: -0.01, qty: null, since: "2030-12-31"}}}, + [{tenant: {weight: 0.1, qty: 0, age: -500, status: "closed", since: "2024-02-29", accounts: [{limit: 1000, kind: "corporate", active: false, flagged: true}, {limit: 99999999999999999999, kind: "retail", active: true, flagged: false}, {limit: 18, kind: "retail", active: true, flagged: true}, {limit: 7.25, kind: "retail", active: true, flagged: true}, {limit: 0, kind: "retail", active: true, flagged: true}]}}, {capped: "true", tenant: {accounts: [{active: false, calc: {health: 1}, flagged: true, kind: "corporate", limit: 1000, penalty: false, review: 5, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: false, kind: "retail", limit: 99999999999999999999, penalty: false, review: 5, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 18, penalty: false, review: 5, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 7.25, penalty: false, review: 5, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 0, penalty: false, review: 5, summary: {n: "a"}}], age: -500, bonus: 10, margin: "true", qty: 0, scores: {bucket: 0.1}, since: "2024-02-29", status: "closed", weight: 0.1}}], + {input: {tenant: {weight: -500, qty: 7.25, age: 2, status: "open", since: "2024-02-29", accounts: []}}, goals: ["acct.review", "tenant.margin", "capped"], output: {capped: "true", tenant: {accounts: [], age: 2, margin: "-498", qty: 7.25, since: "2024-02-29", status: "open", weight: -500}}}, + {input: {tenant: {weight: 1e3, qty: 0.000001, age: 250, status: "open", since: "2000-01-01", accounts: []}}, goals: ["acct.penalty"], output: {tenant: {accounts: [], age: 250, qty: 0.000001, since: "2000-01-01", status: "open", weight: 1000}}}, + {input: {tenant: {weight: 1e3, qty: 10, age: 2, since: "1990-06-15", accounts: [{limit: 0.5, kind: "corporate", active: false, flagged: true}, {limit: 100, kind: "corporate", active: false, flagged: false}]}}, goals: ["acct.calc.health", "tenant.points"], output: {tenant: {accounts: [{active: false, calc: {health: 1}, flagged: true, kind: "corporate", limit: 0.5, summary: {n: "a"}}, {active: false, calc: {health: 1}, flagged: false, kind: "corporate", limit: 100, summary: {n: "a"}}], age: 2, points: true, qty: 10, since: "1990-06-15", weight: 1000}}}, + {input: {tenant: {weight: 5, qty: 1000, age: 10, status: "closed", since: "2030-12-31", accounts: [{limit: 1, kind: "corporate", active: true, flagged: false}, {limit: 99.99, kind: "retail", active: false, flagged: true}, {limit: 2, kind: "retail", active: false, flagged: false}, {limit: 259, kind: "retail", active: true, flagged: true}, {limit: 99999999999999999999, kind: "retail", active: false, flagged: false}]}}, goals: ["capped"], output: {capped: "true", tenant: {accounts: [{active: true, flagged: false, kind: "corporate", limit: 1}, {active: false, flagged: true, kind: "retail", limit: 99.99}, {active: false, flagged: false, kind: "retail", limit: 2}, {active: true, flagged: true, kind: "retail", limit: 259}, {active: false, flagged: false, kind: "retail", limit: 99999999999999999999}], age: 10, qty: 1000, since: "2030-12-31", status: "closed", weight: 5}}}, + {input: {tenant: {age: 18, status: "open", since: "2000-01-01", accounts: [{limit: 100, kind: "retail", active: false, flagged: true}]}}, goals: ["tenant.bonus", "acct.summary"], output: {capped: "a", tenant: {accounts: [{active: false, flagged: true, kind: "retail", limit: 100, summary: {n: "a"}}], age: 18, bonus: 0, points: false, since: "2000-01-01", status: "open"}}}, + {input: {tenant: {weight: 0.5, qty: 1, age: 18, status: "open", since: "2025-03-20T10:15:30Z", accounts: []}}, goals: ["acct.review", "acct.summary"], output: {tenant: {accounts: [], age: 18, qty: 1, since: "2025-03-20T10:15:30Z", status: "open", weight: 0.5}}}, + {input: {tenant: {weight: -0.5, age: 1000000, status: "open", since: "1990-06-15", accounts: [{limit: 65, kind: "retail", active: false, flagged: true}, {limit: 2, kind: "retail", active: true, flagged: true}, {limit: 1.5, kind: "retail", active: true, flagged: true}, {limit: 18, kind: "retail", active: false, flagged: true}]}}, goals: ["tenant.scores.bucket", "acct.calc.health"], output: {tenant: {accounts: [{active: false, calc: {health: 1}, flagged: true, kind: "retail", limit: 65, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 2, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 1.5, summary: {n: "a"}}, {active: false, calc: {health: 1}, flagged: true, kind: "retail", limit: 18, summary: {n: "a"}}], age: 1000000, scores: {bucket: 0}, since: "1990-06-15", status: "open", weight: -0.5}}}, + {input: {tenant: {weight: null, qty: null, age: 2, status: "open", since: "2030-12-31", accounts: [{limit: 3, kind: "corporate", active: true, flagged: false}, {limit: 1, kind: "corporate", active: false, flagged: true}, {limit: 2.50, kind: "retail", active: true, flagged: false}, {limit: 65, kind: "retail", active: true, flagged: false}, {limit: 0.5, kind: "retail", active: true, flagged: true}, {limit: 1e3, kind: "corporate", active: true, flagged: false}, {limit: 7.25, kind: "retail", active: false, flagged: true}, {limit: 0, kind: "corporate", active: false, flagged: false}, {limit: 2, kind: "corporate", active: true, flagged: false}, {limit: 2, kind: "corporate", active: false, flagged: false}]}}, goals: ["acct.penalty"], output: {tenant: {accounts: [{active: true, flagged: false, kind: "corporate", limit: 3, penalty: false}, {active: false, flagged: true, kind: "corporate", limit: 1, penalty: false}, {active: true, flagged: false, kind: "retail", limit: 2.50, penalty: false}, {active: true, flagged: false, kind: "retail", limit: 65, penalty: false}, {active: true, flagged: true, kind: "retail", limit: 0.5, penalty: false}, {active: true, flagged: false, kind: "corporate", limit: 1000, penalty: false}, {active: false, flagged: true, kind: "retail", limit: 7.25, penalty: false}, {active: false, flagged: false, kind: "corporate", limit: 0, penalty: false}, {active: true, flagged: false, kind: "corporate", limit: 2, penalty: false}, {active: false, flagged: false, kind: "corporate", limit: 2, penalty: false}], age: 2, qty: null, since: "2030-12-31", status: "open", weight: null}}}, + {input: {tenant: {age: 0.5, status: "closed", since: "2024-02-29", accounts: [{limit: 0.000001, kind: "corporate", active: true, flagged: false}, {limit: 18, kind: "corporate", active: false, flagged: false}, {limit: 99.99, kind: "retail", active: false, flagged: true}]}}, goals: ["tenant.margin", "tenant.points"], output: {capped: "true", tenant: {accounts: [{active: true, flagged: false, kind: "corporate", limit: 0.000001, penalty: false}, {active: false, flagged: false, kind: "corporate", limit: 18, penalty: false}, {active: false, flagged: true, kind: "retail", limit: 99.99, penalty: false}], age: 0.5, margin: "true", points: false, since: "2024-02-29", status: "closed"}}}, + {input: {tenant: {age: 0.5, since: "2000-01-01", accounts: [{limit: 2, kind: "retail", active: false, flagged: true}, {limit: -1, kind: "retail", active: false, flagged: true}, {limit: 237, kind: "corporate", active: true, flagged: true}, {limit: 18, kind: "retail", active: false, flagged: false}]}}, goals: ["tenant.scores.bucket"], output: {tenant: {accounts: [{active: false, flagged: true, kind: "retail", limit: 2}, {active: false, flagged: true, kind: "retail", limit: -1}, {active: true, flagged: true, kind: "corporate", limit: 237}, {active: false, flagged: false, kind: "retail", limit: 18}], age: 0.5, scores: {bucket: 0}, since: "2000-01-01"}}}, + {input: {tenant: {weight: 100, qty: 1000, age: -0.01, status: "closed", since: "1990-06-15", accounts: [{limit: 10, kind: "retail", active: true, flagged: true}, {limit: 10, kind: "retail", active: false, flagged: true}, {limit: 18, kind: "corporate", active: true, flagged: true}, {limit: 0, kind: "corporate", active: true, flagged: false}, {limit: 10, kind: "corporate", active: true, flagged: false}, {limit: -0, kind: "retail", active: false, flagged: false}, {limit: 18, kind: "retail", active: true, flagged: true}, {limit: 41, kind: "corporate", active: false, flagged: true}, {limit: 1000000, kind: "corporate", active: true, flagged: false}, {limit: 99.99, kind: "retail", active: false, flagged: false}, {limit: 1000, kind: "corporate", active: true, flagged: true}, {limit: 400, kind: "retail", active: false, flagged: true}, {limit: -500, kind: "retail", active: true, flagged: false}, {limit: 0, kind: "retail", active: true, flagged: false}]}}, goals: ["tenant.points", "tenant.bonus", "tenant.scores.bucket"], output: {capped: "false/-0.01", tenant: {accounts: [{active: true, flagged: true, kind: "retail", limit: 10}, {active: false, flagged: true, kind: "retail", limit: 10}, {active: true, flagged: true, kind: "corporate", limit: 18}, {active: true, flagged: false, kind: "corporate", limit: 0}, {active: true, flagged: false, kind: "corporate", limit: 10}, {active: false, flagged: false, kind: "retail", limit: 0}, {active: true, flagged: true, kind: "retail", limit: 18}, {active: false, flagged: true, kind: "corporate", limit: 41}, {active: true, flagged: false, kind: "corporate", limit: 1000000}, {active: false, flagged: false, kind: "retail", limit: 99.99}, {active: true, flagged: true, kind: "corporate", limit: 1000}, {active: false, flagged: true, kind: "retail", limit: 400}, {active: true, flagged: false, kind: "retail", limit: -500}, {active: true, flagged: false, kind: "retail", limit: 0}], age: -0.01, bonus: 1000, points: false, qty: 1000, scores: {bucket: 100}, since: "1990-06-15", status: "closed", weight: 100}}}, + {input: {tenant: {age: 1, status: "closed", since: "2030-12-31", accounts: [{limit: 99999999999999999999, kind: "corporate", active: false, flagged: true}, {limit: 7.25, kind: "corporate", active: false, flagged: false}]}}, goals: ["tenant.points", "acct.penalty"], output: {tenant: {accounts: [{active: false, flagged: true, kind: "corporate", limit: 99999999999999999999, penalty: false}, {active: false, flagged: false, kind: "corporate", limit: 7.25, penalty: false}], age: 1, points: false, since: "2030-12-31", status: "closed"}}}, + {input: {tenant: {weight: 18, qty: 99.99, age: 99999999999999999999, status: "pending", since: "2024-01-01", accounts: [{limit: 2, kind: "corporate", active: false, flagged: false}, {limit: -0.5, kind: "retail", active: false, flagged: true}, {limit: 1, kind: "corporate", active: true, flagged: true}]}}, goals: ["acct.summary", "tenant.margin", "acct.penalty"], output: {capped: "true", tenant: {accounts: [{active: false, flagged: false, kind: "corporate", limit: 2, penalty: false, summary: {n: "a"}}, {active: false, flagged: true, kind: "retail", limit: -0.5, penalty: false, summary: {n: "a"}}, {active: true, flagged: true, kind: "corporate", limit: 1, penalty: false, summary: {n: "a"}}], age: 99999999999999999999, margin: "true", qty: 99.99, since: "2024-01-01", status: "pending", weight: 18}}}, + [{tenant: {weight: -500, qty: 1.5, age: 3, status: "pending", since: "2025-03-20", accounts: [{limit: 2, kind: "retail", active: false, flagged: true}, {limit: 0.5, kind: "retail", active: false, flagged: true}]}}, {capped: "true", tenant: {accounts: [{active: false, calc: {health: 1}, flagged: true, kind: "retail", limit: 2, penalty: false, review: 3, summary: {n: "a"}}, {active: false, calc: {health: 1}, flagged: true, kind: "retail", limit: 0.5, penalty: false, review: 3, summary: {n: "a"}}], age: 3, bonus: 10, margin: "true", qty: 1.5, scores: {bucket: 0.5}, since: "2025-03-20", status: "pending", weight: -500}}], + {input: {tenant: {weight: 99.99, qty: [1], age: 1000, status: "closed", since: "2024-01-01", accounts: [{limit: 5, kind: "corporate", active: false, flagged: true}]}}, goals: ["acct.review"], output: "!error: InputValidationFailed"}, + {input: {tenant: {weight: -0, age: -0.5, status: "open", since: "2024-01-01", accounts: [{limit: 65, kind: "corporate", active: true, flagged: false}, {limit: 0.5, kind: "retail", active: true, flagged: true}, {limit: 0.5, kind: "retail", active: true, flagged: false}, {limit: 123456789.123, kind: "retail", active: true, flagged: true}]}}, goals: ["acct.calc.health", "acct.summary"], output: {tenant: {accounts: [{active: true, calc: {health: 1}, flagged: false, kind: "corporate", limit: 65, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 0.5, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: false, kind: "retail", limit: 0.5, summary: {n: "a"}}, {active: true, calc: {health: 1}, flagged: true, kind: "retail", limit: 123456789.123, summary: {n: "a"}}], age: -0.5, since: "2024-01-01", status: "open", weight: 0}}}, + [{tenant: {weight: -0, qty: 0.5, age: 1, status: "closed", since: "1990-06-15", accounts: [{limit: 1e3, kind: "retail", active: false, flagged: false}], extraField: {nested: true}}}, {capped: "false/1", tenant: {accounts: [{active: false, calc: {health: 1}, flagged: false, kind: "retail", limit: 1000, penalty: false, review: 1, summary: {n: "a"}}], age: 1, bonus: 0.5, extraField: {nested: true}, margin: "1", points: false, qty: 0.5, scores: {bucket: 0.5}, since: "1990-06-15", status: "closed", weight: 0}}], + ], +} + +// seed 354400 (attempt 0) +{ + name: "goals 45: account/vehicles/parts: 3 expression, 4 match, 4 table; 0 root, 12 per-member, 1 top-level computed", + policy: { + models: {account: {income: "number", status: "string(open|closed|pending)?", birthDate: "date", vehicles: "vehicle[]"}, vehicle: {qty: "number?", label: "string", parts: "part[]"}, part: {days: "number"}}, + blocks: [ + {match: "vehicle.decision", arms: [["contains(['A1', 'a', ''], vehicle.label)", "`${(vehicle.qty ?? 0)}/${(vehicle.qty ?? 0) <= 250}`"], ["account.birthDate >= d('2025-01-01')", "vehicle.label"], ["250 > account.income", "vehicle.label"], ["", "((vehicle.qty ?? 0) > 0.25 ? vehicle.label : vehicle.label)"]]}, + {match: "vehicle.surcharge", arms: [["vehicle.decision in ['ok', 'DE']", "vehicle.label"], ["account.status == null", "vehicle.decision"], ["contains(['low', 'high', ''], vehicle.decision)", "account.birthDate.format('%Y')"], ["", "vehicle.label"]]}, + {table: "t3", hit: "collect", inputs: ["account.birthDate", "vehicle.decision", "account.income"], outputs: ["vehicle.total", "vehicle.fee"], rules: [ + [">= d('2000-06-30')", "startsWith($, 'low')", "", "'VIP'", "3 == 10"], + ["", "'DE', 'retail'", "1000", "'A1'", "account.income in (21..182]"], + ["> d('2025-03-20')", "", "", "vehicle.label", ""], + ]}, + {expression: "vehicle.segment", value: "map(account.vehicles, len(#.total))"}, + {expression: "vehicle.calc.bonus", value: "(((vehicle.qty ?? 0) * (vehicle.qty ?? 0)) / -6)"}, + {table: "t6", inputs: ["account.income", "vehicle.decision"], outputs: ["vehicle.health"], rules: [ + ["", "", "account.income > 18"], + ["", "", "vehicle.calc.bonus <= 2"], + ["<= 100", "", "(vehicle.qty ?? 0) > 3"], + ["", "", "vehicle.calc.bonus <= 250"], + ]}, + {match: "vehicle.points", arms: [["account.birthDate < d('2024-01-01')", "`${vehicle.label}/${(vehicle.health ?? false)}`"], ["vehicle.calc.bonus in [38..196)", "(split(string(vehicle.calc.bonus), '-')[0] ?? 'none')"], ["contains(['ok', 'ok', ''], vehicle.label)", "vehicle.decision"], ["", "'Oslo'"]]}, + {table: "t8", inputs: ["account.status", null, "vehicle.surcharge"], outputs: ["vehicle.level", "vehicle.tag"], rules: [ + ["'closed'", "(account.status ?? '') == 'pending'", "$ != 'none'", "account.income", "vehicle.calc.bonus"], + ["", "", "'US', 'A1'", "(vehicle.qty ?? 0)", "account.income"], + ["'open'", "0 > (vehicle.qty ?? 0)", "'low', 'low'", "account.income", "((vehicle.qty ?? 0) * (vehicle.qty ?? 0))"], + ["", "account.birthDate.isSameOrBefore(d('2024-01-01'), 'year')", "", "(vehicle.calc.bonus) / (abs(vehicle.calc.bonus) + 1)", "10"], + ["'closed'", "not ((vehicle.health ?? false))", "", "round((vehicle.qty ?? 0))", "vehicle.calc.bonus"], + ["", "", "", "account.income", ""], + ]}, + {match: "vehicle.weighted", arms: [["(vehicle.level ?? 0) != vehicle.calc.bonus", "(vehicle.health ?? false)"], ["some(vehicle.parts, #.days != #.days)", "account.income == (vehicle.tag ?? 0)"], ["account.income in [19..110)", "vehicle.health != null"], ["vehicle.tag == null", "(vehicle.health ?? false)"], ["", "(vehicle.health ?? false)"]]}, + {table: "t10", hit: "collect", inputs: ["(vehicle.level ?? 0)", "vehicle.decision"], outputs: ["vehicle.summary"], rules: [ + ["", "", "'high'"], + ["[100..412]", "$ != 'x'", "vehicle.points"], + ]}, + {expression: "rank", value: "(sum(map(account.vehicles, round(#.calc.bonus / 7, 1))) + max([len(filter(account.vehicles, contains(['x', 'VIP', ''], #.decision))), (0 % (abs(account.income) + 1))]))"}, + ], + }, + cases: [ + {input: {account: {income: 10, status: null, birthDate: "1990-06-15", vehicles: [{qty: null, label: "DE", parts: [{days: 10}, {days: 1e3}]}]}}, goals: ["rank"], output: {account: {birthDate: "1990-06-15", income: 10, status: null, vehicles: [{calc: {bonus: 0}, decision: "DE", label: "DE", parts: [{days: 10}, {days: 1000}], qty: null}]}, rank: 0}}, + {input: {account: {income: 2.50, status: null, birthDate: "1990-06-15", vehicles: [{qty: null, label: "a", parts: [{days: 0.1}, {days: 0}]}, {qty: 3, label: "none", parts: [{days: 1e3}]}, {qty: 250, label: "a-b-c", parts: [{days: -1}, {days: 250}, {days: 18}]}, {qty: null, label: "US", parts: [{days: 250}, {days: 0.1}]}, {qty: null, label: "O'Neil", parts: [{days: 0.1}, {days: -500}]}, {label: "x", parts: [{days: 0}, {days: 1000000}]}, {label: "Oslo", parts: [{days: 100}]}, {label: "retail", parts: [{days: 99.99}, {days: 1.5}]}, {qty: 1.5, label: "A1", parts: [{days: 100}, {days: 99999999999999999999}]}, {label: "US", parts: [{days: 65}, {days: 0.1}]}, {label: "low", parts: [{days: 18}, {days: 99.99}, {days: 10}]}, {qty: null, label: "ok", parts: []}]}}, goals: ["vehicle.level"], output: {account: {birthDate: "1990-06-15", income: 2.50, status: null, vehicles: [{calc: {bonus: 0}, decision: "0/true", health: false, label: "a", level: 0, parts: [{days: 0.1}, {days: 0}], qty: null, surcharge: "0/true", tag: 10}, {calc: {bonus: -1.50}, decision: "none", health: false, label: "none", level: -0.60, parts: [{days: 1000}], qty: 3, surcharge: "none", tag: 10}, {calc: {bonus: -10416.666666666666666666666667}, decision: "a-b-c", health: false, label: "a-b-c", level: -0.9999040092151153489265030557, parts: [{days: -1}, {days: 250}, {days: 18}], qty: 250, surcharge: "a-b-c", tag: 10}, {calc: {bonus: 0}, decision: "US", health: false, label: "US", level: 0, parts: [{days: 250}, {days: 0.1}], qty: null, surcharge: "US", tag: 2.50}, {calc: {bonus: 0}, decision: "O'Neil", health: false, label: "O'Neil", level: 0, parts: [{days: 0.1}, {days: -500}], qty: null, surcharge: "O'Neil", tag: 10}, {calc: {bonus: 0}, decision: "x", health: false, label: "x", level: 0, parts: [{days: 0}, {days: 1000000}], surcharge: "x", tag: 10}, {calc: {bonus: 0}, decision: "Oslo", health: false, label: "Oslo", level: 0, parts: [{days: 100}], surcharge: "Oslo", tag: 10}, {calc: {bonus: 0}, decision: "retail", health: false, label: "retail", level: 0, parts: [{days: 99.99}, {days: 1.5}], surcharge: "retail", tag: 10}, {calc: {bonus: -0.3750}, decision: "1.5/true", health: false, label: "A1", level: -0.2727272727272727272727272727, parts: [{days: 100}, {days: 99999999999999999999}], qty: 1.5, surcharge: "1.5/true", tag: 10}, {calc: {bonus: 0}, decision: "US", health: false, label: "US", level: 0, parts: [{days: 65}, {days: 0.1}], surcharge: "US", tag: 2.50}, {calc: {bonus: 0}, decision: "low", health: false, label: "low", level: 0, parts: [{days: 18}, {days: 99.99}, {days: 10}], surcharge: "low", tag: 10}, {calc: {bonus: 0}, decision: "ok", health: false, label: "ok", level: 0, parts: [], qty: null, surcharge: "ok", tag: 10}]}}}, + [{account: {income: 1000, status: "open", birthDate: "2025-03-20", vehicles: [{qty: 3, label: "VIP", parts: [{days: 5}]}]}}, {account: {birthDate: "2025-03-20", income: 1000, status: "open", vehicles: [{calc: {bonus: -1.50}, decision: "VIP", fee: [], health: true, label: "VIP", level: 1000, parts: [{days: 5}], qty: 3, segment: [0], summary: ["high"], surcharge: "VIP", tag: null, total: [], weighted: true}]}, rank: 0.8}], + {input: {account: {income: 10, status: "open", birthDate: "2000-01-01", vehicles: [{label: "x-y", parts: []}, {label: "low", parts: []}]}}, goals: ["vehicle.tag"], output: {account: {birthDate: "2000-01-01", income: 10, status: "open", vehicles: [{calc: {bonus: 0}, decision: "x-y", health: false, label: "x-y", level: 0, parts: [], surcharge: "x-y", tag: 10}, {calc: {bonus: 0}, decision: "low", health: false, label: "low", level: 0, parts: [], surcharge: "2000", tag: 10}]}}}, + {input: {account: {income: 0.1, status: null, birthDate: "2024-01-01", vehicles: [{label: "retail", parts: [{days: 99.99}, {days: 0.1}]}, {qty: null, label: "ok", parts: [{days: 3}]}, {label: "retail", parts: [{days: 5}, {days: 250}, {days: -0}]}]}}, goals: ["vehicle.level", "rank"], output: {account: {birthDate: "2024-01-01", income: 0.1, status: null, vehicles: [{calc: {bonus: 0}, decision: "retail", health: false, label: "retail", level: 0, parts: [{days: 99.99}, {days: 0.1}], surcharge: "retail", tag: 10}, {calc: {bonus: 0}, decision: "ok", health: false, label: "ok", level: 0, parts: [{days: 3}], qty: null, surcharge: "ok", tag: 10}, {calc: {bonus: 0}, decision: "retail", health: false, label: "retail", level: 0, parts: [{days: 5}, {days: 250}, {days: 0}], surcharge: "retail", tag: 10}]}, rank: 0}}, + {input: {account: {income: 1, status: null, birthDate: "2024-02-29", vehicles: [{label: "VIP", parts: [{days: 123456789.123}, {days: 250}]}, {label: "A1", parts: [{days: 468}]}]}}, goals: ["vehicle.points", "rank", "vehicle.calc.bonus"], output: {account: {birthDate: "2024-02-29", income: 1, status: null, vehicles: [{calc: {bonus: 0}, decision: "VIP", label: "VIP", parts: [{days: 123456789.123}, {days: 250}], points: "Oslo"}, {calc: {bonus: 0}, decision: "0/true", label: "A1", parts: [{days: 468}], points: "Oslo"}]}, rank: 1}}, + [{account: {income: 1000, status: "open", birthDate: "2024-01-01", vehicles: []}}, {account: {birthDate: "2024-01-01", income: 1000, status: "open", vehicles: []}, rank: 0}], + {input: {account: {income: 250, status: "open", birthDate: "1990-06-15", vehicles: [{qty: 250, label: "low", parts: [{days: -500}, {days: 10}]}, {qty: 7.25, label: "A1", parts: [{days: -500}, {days: 0}]}]}}, goals: ["rank", "vehicle.health", "vehicle.surcharge"], output: {account: {birthDate: "1990-06-15", income: 250, status: "open", vehicles: [{calc: {bonus: -10416.666666666666666666666667}, decision: "low", health: true, label: "low", parts: [{days: -500}, {days: 10}], qty: 250, surcharge: "1990"}, {calc: {bonus: -8.760416666666666666666666667}, decision: "7.25/true", health: true, label: "A1", parts: [{days: -500}, {days: 0}], qty: 7.25, surcharge: "A1"}]}, rank: -1489.4}}, + {input: {account: {income: 0, status: "closed", birthDate: "2024-01-01", vehicles: [{qty: 2.50, label: "NL", parts: [{days: 1000000}, {days: 18}]}, {qty: 0, label: "é ü", parts: [{days: 1000}, {days: 0.5}]}, {qty: null, label: "-", parts: [{days: 0}, {days: 0}]}, {label: "low", parts: []}]}}, goals: ["vehicle.summary"], output: {account: {birthDate: "2024-01-01", income: 0, status: "closed", vehicles: [{calc: {bonus: -1.0416666666666666666666666667}, decision: "NL", health: false, label: "NL", level: -0.5102040816326530612244897959, parts: [{days: 1000000}, {days: 18}], qty: 2.50, summary: ["high"], surcharge: "NL", tag: 10}, {calc: {bonus: 0}, decision: "é ü", health: false, label: "é ü", level: 0, parts: [{days: 1000}, {days: 0.5}], qty: 0, summary: ["high"], surcharge: "é ü", tag: 10}, {calc: {bonus: 0}, decision: "-", health: false, label: "-", level: 0, parts: [{days: 0}, {days: 0}], qty: null, summary: ["high"], surcharge: "-", tag: 10}, {calc: {bonus: 0}, decision: "low", health: false, label: "low", level: 0, parts: [], summary: ["high"], surcharge: "2024", tag: 10}]}}}, + [{account: {income: 250, status: "open", birthDate: "2024-01-01", vehicles: [{qty: 100, label: "A1", parts: [{days: 1}, {days: 99.99}]}]}}, {account: {birthDate: "2024-01-01", income: 250, status: "open", vehicles: [{calc: {bonus: -1666.6666666666666666666666667}, decision: "100/true", fee: [], health: true, label: "A1", level: 100, parts: [{days: 1}, {days: 99.99}], points: "Oslo", qty: 100, segment: [0], summary: ["high", "Oslo"], surcharge: "A1", tag: 250, total: [], weighted: true}]}, rank: -238.1}], + {input: {account: {income: 100, birthDate: "2025-03-20T10:15:30Z", vehicles: [{label: "retail", parts: [{days: 250}, {days: 10}]}, {qty: 0, label: "none", parts: []}]}}, goals: ["vehicle.decision"], output: {account: {birthDate: "2025-03-20T10:15:30Z", income: 100, vehicles: [{decision: "retail", label: "retail", parts: [{days: 250}, {days: 10}]}, {decision: "none", label: "none", parts: [], qty: 0}]}}}, + {input: {account: {income: 250, status: "closed", birthDate: "2025-03-20", vehicles: [{label: "US", parts: []}, {qty: 1000000, label: "retail", parts: [{days: 1000}, {days: 18}, {days: 100}]}, {qty: -0.01, label: "low", parts: [{days: -0}, {days: -500}, {days: 5}]}, {qty: 0, label: "ok", parts: []}]}}, goals: ["vehicle.total", "vehicle.decision", "vehicle.level"], output: {account: {birthDate: "2025-03-20", income: 250, status: "closed", vehicles: [{decision: "US", fee: [], health: true, label: "US", level: 0, parts: [], surcharge: "US", tag: 250, total: []}, {decision: "retail", fee: [], health: true, label: "retail", level: 250, parts: [{days: 1000}, {days: 18}, {days: 100}], qty: 1000000, surcharge: "retail", tag: null, total: []}, {decision: "low", fee: [false], health: true, label: "low", level: 250, parts: [{days: 0}, {days: -500}, {days: 5}], qty: -0.01, surcharge: "2025", tag: null, total: ["VIP"]}, {decision: "ok", fee: [], health: true, label: "ok", level: 250, parts: [], qty: 0, surcharge: "ok", tag: null, total: []}]}}}, + {input: {account: {income: 5, status: "open", birthDate: "2030-12-31", vehicles: [{qty: 100, parts: [{days: 250}, {days: 1000}]}, {qty: 100, label: "ok", parts: [{days: 7.25}, {days: 1}]}, {qty: 3, label: "x", parts: []}, {qty: -500, label: "ok", parts: [{days: 10}]}]}}, goals: ["vehicle.level", "vehicle.total"], output: "!error: ExpressionFailed"}, + {input: {account: {income: 10, birthDate: "2024-01-01", vehicles: [{label: "NL", parts: [{days: 3}, {days: -1}, {days: 5}]}, {qty: 2.50, label: "retail", parts: [{days: 65}]}, {qty: 10, label: "x", parts: [{days: 0.1}, {days: 10}, {days: 1}]}, {qty: 0, label: "ok", parts: [{days: 1000000}, {days: -500}]}, {label: "", parts: []}]}}, goals: ["vehicle.level", "vehicle.weighted"], output: {account: {birthDate: "2024-01-01", income: 10, vehicles: [{calc: {bonus: 0}, decision: "NL", health: false, label: "NL", level: 0, parts: [{days: 3}, {days: -1}, {days: 5}], surcharge: "NL", tag: 10, weighted: false}, {calc: {bonus: -1.0416666666666666666666666667}, decision: "retail", health: false, label: "retail", level: -0.5102040816326530612244897959, parts: [{days: 65}], qty: 2.50, surcharge: "retail", tag: 10, weighted: false}, {calc: {bonus: -16.666666666666666666666666667}, decision: "x", health: false, label: "x", level: -0.9433962264150943396226415094, parts: [{days: 0.1}, {days: 10}, {days: 1}], qty: 10, surcharge: "x", tag: 10, weighted: false}, {calc: {bonus: 0}, decision: "ok", health: false, label: "ok", level: 0, parts: [{days: 1000000}, {days: -500}], qty: 0, surcharge: "ok", tag: 10, weighted: false}, {calc: {bonus: 0}, decision: "0/true", health: false, label: "", level: 0, parts: [], surcharge: "0/true", tag: 10, weighted: false}]}}}, + {input: {account: {income: 0.25, status: "pending", birthDate: "2024-02-29", vehicles: [{qty: 0, label: "ok", parts: [{days: 65}]}, {label: "日本", parts: []}, {qty: null, label: "US", parts: []}]}}, goals: ["vehicle.decision"], output: {account: {birthDate: "2024-02-29", income: 0.25, status: "pending", vehicles: [{decision: "ok", label: "ok", parts: [{days: 65}], qty: 0}, {decision: "日本", label: "日本", parts: []}, {decision: "US", label: "US", parts: [], qty: null}]}}}, + {input: {account: {income: 99.99, status: "open", birthDate: "2024-02-29", vehicles: [{qty: 123456789.123, label: "retail", parts: [{days: 100}, {days: 0}]}, {qty: 0, label: "A1", parts: [{days: 1000}, {days: 18}]}]}}, goals: ["vehicle.decision"], output: {account: {birthDate: "2024-02-29", income: 99.99, status: "open", vehicles: [{decision: "retail", label: "retail", parts: [{days: 100}, {days: 0}], qty: 123456789.123}, {decision: "0/true", label: "A1", parts: [{days: 1000}, {days: 18}], qty: 0}]}}}, + {input: {account: {income: 250, status: "closed", birthDate: "2025-03-20T10:15:30Z", vehicles: []}}, goals: ["vehicle.calc.bonus"], output: {account: {birthDate: "2025-03-20T10:15:30Z", income: 250, status: "closed", vehicles: []}}}, + {input: {account: {income: 250, status: "open", birthDate: "2000-01-01", vehicles: [{qty: 0, label: "A1", parts: []}, {qty: 1000, label: "US", parts: [{days: 0}, {days: 0}]}, {qty: 18, label: "ok", parts: []}, {label: "ok", parts: []}, {qty: 0, label: "ok", parts: [{days: 250}, {days: 0}]}]}}, goals: ["vehicle.surcharge", "vehicle.decision", "vehicle.points"], output: {account: {birthDate: "2000-01-01", income: 250, status: "open", vehicles: [{calc: {bonus: 0}, decision: "0/true", health: true, label: "A1", parts: [], points: "A1/true", qty: 0, surcharge: "A1"}, {calc: {bonus: -166666.66666666666666666666667}, decision: "US", health: true, label: "US", parts: [{days: 0}, {days: 0}], points: "US/true", qty: 1000, surcharge: "US"}, {calc: {bonus: -54}, decision: "ok", health: true, label: "ok", parts: [], points: "ok/true", qty: 18, surcharge: "ok"}, {calc: {bonus: 0}, decision: "ok", health: true, label: "ok", parts: [], points: "ok/true", surcharge: "ok"}, {calc: {bonus: 0}, decision: "ok", health: true, label: "ok", parts: [{days: 250}, {days: 0}], points: "ok/true", qty: 0, surcharge: "ok"}]}}}, + {input: {account: {income: 10, status: "open", birthDate: "2025-03-20", vehicles: [{qty: 0, label: "x", parts: [{days: 250}, {days: -0.5}]}, {qty: 1, label: "VIP", parts: []}, {qty: 250, label: "none", parts: [{days: 0}]}, {qty: 1000, label: "US", parts: [{days: 1}]}, {qty: 0.000001, label: "Oslo", parts: [{days: 18}, {days: 1000}]}, {qty: 0, label: "Oslo", parts: []}, {qty: 1, label: "a", parts: [{days: 3}, {days: 250}]}, {qty: 0.25, label: "x", parts: [{days: 3}, {days: 250}]}, {qty: 0, label: "日本", parts: [{days: 1000000}]}, {qty: 250, label: "VIP", parts: [{days: 250}, {days: 0}]}], extraField: {nested: true}}}, goals: ["vehicle.fee", "vehicle.segment", "vehicle.decision"], output: {account: {birthDate: "2025-03-20", extraField: {nested: true}, income: 10, status: "open", vehicles: [{decision: "x", fee: [], label: "x", parts: [{days: 250}, {days: -0.5}], qty: 0, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "VIP", fee: [], label: "VIP", parts: [], qty: 1, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "none", fee: [], label: "none", parts: [{days: 0}], qty: 250, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "US", fee: [], label: "US", parts: [{days: 1}], qty: 1000, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "Oslo", fee: [], label: "Oslo", parts: [{days: 18}, {days: 1000}], qty: 0.000001, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "Oslo", fee: [], label: "Oslo", parts: [], qty: 0, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "1/true", fee: [], label: "a", parts: [{days: 3}, {days: 250}], qty: 1, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "x", fee: [], label: "x", parts: [{days: 3}, {days: 250}], qty: 0.25, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "日本", fee: [], label: "日本", parts: [{days: 1000000}], qty: 0, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}, {decision: "VIP", fee: [], label: "VIP", parts: [{days: 250}, {days: 0}], qty: 250, segment: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], total: []}]}}}, + {input: {account: {income: -0.5, status: "closed", birthDate: "2000-01-01", vehicles: [{qty: 100, label: "x-y", parts: [{days: 18}]}]}}, goals: ["rank", "vehicle.tag"], output: {account: {birthDate: "2000-01-01", income: -0.5, status: "closed", vehicles: [{calc: {bonus: -1666.6666666666666666666666667}, decision: "x-y", health: false, label: "x-y", level: -0.9994003597841295222866280232, parts: [{days: 18}], qty: 100, surcharge: "x-y", tag: 10}]}, rank: -238.1}}, + {input: {account: {income: 18, status: "open", birthDate: "2000-01-01", vehicles: [{label: "a", parts: [{days: 0.1}, {days: 99.99}, {days: 99.99}]}, {qty: 1e3, label: "ok", parts: [{days: 100}, {days: 2}]}, {qty: null, label: "DE", parts: [{days: 10}, {days: 250}, {days: 1000}]}, {qty: null, label: "low", parts: [{days: 420}, {days: 0}, {days: 7.25}]}, {qty: -0.01, label: "ok", parts: [{days: 10}, {days: -500}, {days: -0.01}]}]}}, goals: ["vehicle.fee"], output: {account: {birthDate: "2000-01-01", income: 18, status: "open", vehicles: [{decision: "0/true", fee: [], label: "a", parts: [{days: 0.1}, {days: 99.99}, {days: 99.99}], total: []}, {decision: "ok", fee: [], label: "ok", parts: [{days: 100}, {days: 2}], qty: 1000, total: []}, {decision: "DE", fee: [], label: "DE", parts: [{days: 10}, {days: 250}, {days: 1000}], qty: null, total: []}, {decision: "low", fee: [], label: "low", parts: [{days: 420}, {days: 0}, {days: 7.25}], qty: null, total: []}, {decision: "ok", fee: [], label: "ok", parts: [{days: 10}, {days: -500}, {days: -0.01}], qty: -0.01, total: []}]}}}, + {input: {account: {income: -0.5, status: "closed", birthDate: "2025-03-20T10:15:30Z", vehicles: [{qty: null, label: "US", parts: []}, {qty: 0.1, label: "日本", parts: []}]}}, goals: ["vehicle.level", "vehicle.surcharge"], output: {account: {birthDate: "2025-03-20T10:15:30Z", income: -0.5, status: "closed", vehicles: [{calc: {bonus: 0}, decision: "US", health: false, label: "US", level: 0, parts: [], qty: null, surcharge: "US", tag: -0.5}, {calc: {bonus: -0.0016666666666666666666666667}, decision: "日本", health: false, label: "日本", level: 0, parts: [], qty: 0.1, surcharge: "日本", tag: -0.0016666666666666666666666667}]}}}, + {input: {account: {income: 1, status: "open", birthDate: "2000-01-01", vehicles: [{qty: 10, label: "VIP", parts: []}, {qty: 65, label: "Oslo", parts: []}]}}, goals: ["vehicle.surcharge", "vehicle.weighted"], output: {account: {birthDate: "2000-01-01", income: 1, status: "open", vehicles: [{calc: {bonus: -16.666666666666666666666666667}, decision: "VIP", health: false, label: "VIP", level: -0.9433962264150943396226415094, parts: [], qty: 10, surcharge: "VIP", tag: 10, weighted: false}, {calc: {bonus: -704.16666666666666666666666667}, decision: "Oslo", health: false, label: "Oslo", level: -0.998581895532970928858425904, parts: [], qty: 65, surcharge: "Oslo", tag: 10, weighted: false}]}}}, + ], +} diff --git a/core/engine/tests/spec/policy/36-generated-minimal.json5 b/core/engine/tests/spec/policy/36-generated-minimal.json5 new file mode 100644 index 00000000..7359523f --- /dev/null +++ b/core/engine/tests/spec/policy/36-generated-minimal.json5 @@ -0,0 +1,255 @@ +// Minimal reproductions for the generated chapters 33-35. +// +// The generated chapters differential-test the compiled policy engine (single, batch and +// DecisionEngine) against the driver. Over chapters 33-35 (3,496 cases) and three further +// scans of 150 suites each (seeds 910000, 920000 and 930000, about 9,500 cases, not kept) the +// compiled engine produced no mismatch, so there is no compiled root cause to shrink here. +// +// What the generator did hit are policies that are refused before evaluation: candidates with +// error diagnostics are regenerated, and the suites below are those refusals shrunk to their +// root cause, with the output the policy is meant to produce. Not representable here: a +// per-member block writing a filter over its own relationship (`item.peers = filter(o.items, +// #.n > 0)` with a matching member) makes every member contain itself; the driver's result is +// cyclic and the process aborts with a stack overflow, which the runner cannot survive. + +// --- An object-valued member computed read through `#` ---------------------------------------- +// A per-member expression writes an object; reading one of its fields directly on the member +// type-checks, but reading it on `#` inside a closure over the relationship is reported as +// UNDEFINED_VARIABLE and refuses the policy. The workspace path (diagnostics pinned) evaluates +// it to the intended result, so only the type checker is wrong. + +{ + name: "object member computed summed over the members", + policy: { + models: {o: {items: "item[]"}, item: {n: "number"}}, + blocks: [ + {expression: "item.info", value: "{a: item.n * 2}"}, + {expression: "o.sum", value: "sum(map(o.items, #.info.a))"}, + ], + }, + cases: [ + [{o: {items: [{n: 1}, {n: 2}]}}, {o: {items: [{n: 1, info: {a: 2}}, {n: 2, info: {a: 4}}], sum: 6}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE]: the type checker does not see `info.a` on `#` although `item.info` is a member computed"], + [{o: {items: []}}, {o: {items: [], sum: 0}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for `#.info.a`"], + [{o: {items: [{n: -1.5}]}}, {o: {items: [{n: -1.5, info: {a: -3}}], sum: -3}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for `#.info.a`"], + ], +} + +{ + name: "object member computed field in a quantifier", + policy: { + models: {o: {items: "item[]"}, item: {n: "number"}}, + blocks: [ + {expression: "item.info", value: "{big: item.n > 10, n: item.n}"}, + {expression: "o.anyBig", value: "some(o.items, #.info.big)"}, + {expression: "o.bigCount", value: "count(o.items, #.info.big)"}, + ], + }, + cases: [ + [{o: {items: [{n: 20}, {n: 5}]}}, {o: {items: [{n: 20, info: {big: true, n: 20}}, {n: 5, info: {big: false, n: 5}}], anyBig: true, bigCount: 1}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for `#.info.big`"], + [{o: {items: [{n: 1}]}}, {o: {items: [{n: 1, info: {big: false, n: 1}}], anyBig: false, bigCount: 0}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for `#.info.big`"], + [{o: {items: []}}, {o: {items: [], anyBig: false, bigCount: 0}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for `#.info.big`"], + ], +} + +// The same object read on the member itself is accepted. +{ + name: "object member computed read on the member", + policy: { + models: {o: {items: "item[]"}, item: {n: "number"}}, + blocks: [ + {expression: "item.info", value: "{a: item.n * 2}"}, + {expression: "item.b", value: "item.info.a + 1"}, + ], + }, + cases: [ + [{o: {items: [{n: 1}, {n: 2}]}}, {o: {items: [{n: 1, info: {a: 2}, b: 3}, {n: 2, info: {a: 4}, b: 5}]}}], + [{o: {items: []}}, {o: {items: []}}], + ], +} + +// A nested write path (`item.g.x`) read on `#` is accepted; only object values are lost. +{ + name: "nested member write path read through # in a closure", + policy: { + models: {o: {items: "item[]"}, item: {n: "number"}}, + blocks: [ + {expression: "item.g.x", value: "item.n * 2"}, + {expression: "o.sum", value: "sum(map(o.items, #.g.x))"}, + ], + }, + cases: [ + [{o: {items: [{n: 1}, {n: 2}]}}, {o: {items: [{n: 1, g: {x: 2}}, {n: 2, g: {x: 4}}], sum: 6}}], + [{o: {items: []}}, {o: {items: [], sum: 0}}], + ], +} + +// --- False cycles through a nested write group ------------------------------------------------ +// Two properties written under one group (`o.g.a`, `o.g.c`) where the second depends on the first +// through a property outside the group (`o.g.a -> o.b -> o.g.c`) are reported as +// CYCLIC_DEPENDENCY: the dependency analysis treats the group as one node. There is no cycle at +// property level, and a direct chain inside the group (`o.g.c = o.g.a * 2`) is accepted. + +{ + name: "nested group written before and after an outside property", + policy: { + models: {o: {n: "number"}}, + blocks: [ + {expression: "o.g.a", value: "o.n + 1"}, + {expression: "o.b", value: "o.g.a + 1"}, + {expression: "o.g.c", value: "o.b * 2"}, + ], + }, + cases: [ + [{o: {n: 1}}, {o: {n: 1, g: {a: 2, c: 6}, b: 3}}, "bug: refused with CompilationErrors [CYCLIC_DEPENDENCY]: o.g.a -> o.b -> o.g.c has no cycle; the group o.g is treated as one node"], + [{o: {n: -1}}, {o: {n: -1, g: {a: 0, c: 2}, b: 1}}, "bug: false CYCLIC_DEPENDENCY through the group o.g"], + [{o: {n: 0.5}}, {o: {n: 0.5, g: {a: 1.5, c: 5}, b: 2.5}}, "bug: false CYCLIC_DEPENDENCY through the group o.g"], + ], +} + +{ + name: "nested top-level group written before and after an outside property", + policy: { + models: {o: {n: "number"}}, + blocks: [ + {expression: "g.a", value: "o.n + 1"}, + {expression: "b", value: "g.a + 1"}, + {expression: "g.c", value: "b * 2"}, + ], + }, + cases: [ + [{o: {n: 1}}, {o: {n: 1}, g: {a: 2, c: 6}, b: 3}, "bug: refused with CompilationErrors [CYCLIC_DEPENDENCY]: g.a -> b -> g.c has no cycle"], + [{o: {n: 10}}, {o: {n: 10}, g: {a: 11, c: 24}, b: 12}, "bug: false CYCLIC_DEPENDENCY through the group g"], + ], +} + +{ + name: "nested member group written before and after an outside member property", + policy: { + models: {o: {items: "item[]"}, item: {n: "number"}}, + blocks: [ + {expression: "item.g.a", value: "item.n + 1"}, + {expression: "item.b", value: "item.g.a + 1"}, + {expression: "item.g.c", value: "item.b * 2"}, + ], + }, + cases: [ + [{o: {items: [{n: 1}, {n: 2}]}}, {o: {items: [{n: 1, g: {a: 2, c: 6}, b: 3}, {n: 2, g: {a: 3, c: 8}, b: 4}]}}, "bug: refused with CompilationErrors [CYCLIC_DEPENDENCY]: item.g.a -> item.b -> item.g.c has no cycle"], + [{o: {items: []}}, {o: {items: []}}, "bug: false CYCLIC_DEPENDENCY through the member group item.g"], + ], +} + +{ + name: "nested group written by a table, then by an expression downstream", + policy: { + models: {o: {n: "number"}}, + blocks: [ + {table: "t", inputs: ["o.n"], outputs: ["o.g.a"], rules: [["> 0", "o.n + 1"], ["", "0"]]}, + {expression: "o.b", value: "o.g.a + 1"}, + {expression: "o.g.c", value: "o.b * 2"}, + ], + }, + cases: [ + [{o: {n: 1}}, {o: {n: 1, g: {a: 2, c: 6}, b: 3}}, "bug: refused with CompilationErrors [CYCLIC_DEPENDENCY]: o.g.a -> o.b -> o.g.c has no cycle"], + [{o: {n: -4}}, {o: {n: -4, g: {a: 0, c: 2}, b: 1}}, "bug: false CYCLIC_DEPENDENCY through the group o.g"], + ], +} + +// Accepted neighbours: a direct chain inside one group, and the same chain over two groups. +{ + name: "nested group chained directly is accepted", + policy: { + models: {o: {n: "number"}}, + blocks: [ + {expression: "o.g.a", value: "o.n + 1"}, + {expression: "o.g.c", value: "o.g.a * 2"}, + ], + }, + cases: [ + [{o: {n: 1}}, {o: {n: 1, g: {a: 2, c: 4}}}], + [{o: {n: -1}}, {o: {n: -1, g: {a: 0, c: 0}}}], + ], +} + +{ + name: "the same chain over two groups is accepted", + policy: { + models: {o: {n: "number"}}, + blocks: [ + {expression: "o.g.a", value: "o.n + 1"}, + {expression: "o.b", value: "o.g.a + 1"}, + {expression: "o.h.c", value: "o.b * 2"}, + ], + }, + cases: [ + [{o: {n: 1}}, {o: {n: 1, g: {a: 2}, b: 3, h: {c: 6}}}], + [{o: {n: 0}}, {o: {n: 0, g: {a: 1}, b: 2, h: {c: 4}}}], + ], +} + +// --- Comparing a literal union with a literal outside it --------------------------------------- +// A string computed from literals only (`o.f ? 'a' : 'b'`) is typed as the union of those +// literals; comparing it with any other literal is reported as UNDEFINED_VARIABLE and refuses the +// policy. The comparison is ordinary code (always false here, but the value is data-dependent in +// real policies where an arm is added later), and the error code names no variable. + +{ + name: "computed literal union compared with an outside literal", + policy: { + models: {o: {f: "boolean"}}, + blocks: [ + {expression: "o.k", value: "o.f ? 'a' : 'b'"}, + {expression: "o.x", value: "o.k == 'c'"}, + {expression: "o.y", value: "o.k != 'c'"}, + ], + }, + cases: [ + [{o: {f: true}}, {o: {f: true, k: "a", x: false, y: true}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for comparing the literal union 'a'|'b' with 'c'"], + [{o: {f: false}}, {o: {f: false, k: "b", x: false, y: true}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for comparing the literal union 'a'|'b' with 'c'"], + ], +} + +{ + name: "inline literal union compared with an outside literal", + policy: { + models: {o: {f: "boolean", n: "number"}}, + blocks: [ + {expression: "o.x", value: "(o.f ? 'a' : 'b') == 'c' or o.n > 1"}, + ], + }, + cases: [ + [{o: {f: true, n: 2}}, {o: {f: true, n: 2, x: true}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for comparing the literal union 'a'|'b' with 'c'"], + [{o: {f: false, n: 0}}, {o: {f: false, n: 0, x: false}}, "bug: refused with CompilationErrors [UNDEFINED_VARIABLE] for comparing the literal union 'a'|'b' with 'c'"], + ], +} + +// Comparing with a member of the union is accepted. +{ + name: "literal union compared with one of its members", + policy: { + models: {o: {f: "boolean"}}, + blocks: [ + {expression: "o.k", value: "o.f ? 'a' : 'b'"}, + {expression: "o.x", value: "o.k == 'a'"}, + ], + }, + cases: [ + [{o: {f: true}}, {o: {f: true, k: "a", x: true}}], + [{o: {f: false}}, {o: {f: false, k: "b", x: false}}], + ], +} + +// A declared enum compared with a value outside it is refused the same way. Flagging a typo +// against a declared enum may be intended, but the code is UNDEFINED_VARIABLE. +{ + name: "declared enum compared with a value outside it", + policy: { + models: {o: {kind: "string(retail|corporate)"}}, + blocks: [ + {expression: "o.x", value: "o.kind != 'high'"}, + ], + }, + cases: [ + [{o: {kind: "retail"}}, "!error: CompilationErrors [\"UNDEFINED_VARIABLE\"]", "question: an enum compared with a non-member literal is refused as UNDEFINED_VARIABLE; is an error meant here (likely typo), and with which code?"], + [{o: {kind: "corporate"}}, "!error: CompilationErrors [\"UNDEFINED_VARIABLE\"]", "question: enum vs non-member literal refused as UNDEFINED_VARIABLE"], + ], +} diff --git a/core/engine/tests/spec/policy/37-input-validation.json5 b/core/engine/tests/spec/policy/37-input-validation.json5 new file mode 100644 index 00000000..90376593 --- /dev/null +++ b/core/engine/tests/spec/policy/37-input-validation.json5 @@ -0,0 +1,778 @@ +// Input validation in depth. Chapter 01 pins the basic per-type rules at the entity root, chapters +// 09/10/11/21/27 the relationship, reference, global and date rules. This chapter pins the +// validator as a whole: which input keys it visits (root entities, reference pools, globals) and +// which it ignores, the rendered error path for every nesting kind (members, nested +// relationships, primitive arrays, pools, globals), the expected/got wording, how several errors +// are collected into one `InputValidationFailed`, and the order between the request errors: +// `GoalNotFound` first, then `InputValidationFailed` (whole input, every error), then +// `MissingRequiredInputs` (only reads the requested cone needs), then runtime errors. + +// --------------------------------------------------------------------------------------------- +// Which error wins. Validation runs over the whole input before the required-input check, so a +// wrong type wins over a missing input even when the wrongly typed property is never read. + +{ + name: "a wrong type wins over a missing required input", + policy: { + models: {customer: {age: "number", name: "string"}}, + blocks: [{expression: "customer.next", value: "customer.age + 1"}], + }, + cases: [ + [{customer: {name: 5}}, "!error: InputValidationFailed"], + [{customer: {name: 5}}, "!error: customer.name"], + [{customer: {name: "Ann"}}, "!error: MissingRequiredInputs"], + [{customer: {age: null, name: true}}, "!error: InputValidationFailed"], + [{customer: {age: 1, name: "Ann"}}, {customer: {age: 1, name: "Ann", next: 2}}], + ], +} + +{ + name: "an unknown goal wins over a validation error", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.next", value: "customer.age + 1"}], + }, + cases: [ + {input: {customer: {age: "1"}}, goals: ["customer.nope"], output: "!error: GoalNotFound"}, + {input: {customer: {}}, goals: ["customer.nope"], output: "!error: GoalNotFound"}, + {input: {customer: {age: "1"}}, goals: ["customer.next"], output: "!error: InputValidationFailed"}, + {input: {customer: {}}, goals: ["customer.next"], output: "!error: MissingRequiredInputs"}, + {input: {customer: {age: 4}}, goals: ["customer.next"], output: {customer: {age: 4, next: 5}}}, + ], +} + +{ + name: "validation covers properties outside the goal cone", + policy: { + models: {customer: {age: "number", income: "number"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.rich", value: "customer.income > 1000"}, + ], + }, + cases: [ + {input: {customer: {age: 20, income: "lots"}}, goals: ["customer.adult"], output: "!error: customer.income"}, + {input: {customer: {age: 20}}, goals: ["customer.adult"], output: {customer: {age: 20, adult: true}}}, + {input: {customer: {age: 20, income: null}}, goals: ["customer.adult"], output: {customer: {age: 20, income: null, adult: true}}}, + {input: {customer: {income: 5}}, goals: ["customer.adult"], output: "!error: MissingRequiredInputs"}, + ], +} + +{ + name: "a validation error wins over a runtime error the input would cause", + policy: { + models: {customer: {code: "string", age: "number"}}, + blocks: [{expression: "customer.n", value: "number(customer.code)"}], + }, + cases: [ + [{customer: {code: "abc", age: "x"}}, "!error: InputValidationFailed"], + [{customer: {code: "abc", age: 1}}, "!error: ExpressionFailed"], + [{customer: {code: "12", age: 1}}, {customer: {code: "12", age: 1, n: 12}}], + [{customer: {age: 1}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a missing required input wins over a runtime error in another block", + policy: { + models: {customer: {code: "string", age: "number"}}, + blocks: [ + {expression: "customer.n", value: "number(customer.code)"}, + {expression: "customer.next", value: "customer.age + 1"}, + ], + }, + cases: [ + [{customer: {code: "abc"}}, "!error: MissingRequiredInputs"], + [{customer: {code: "abc"}}, "!error: customer.age"], + [{customer: {code: "abc", age: 1}}, "!error: ExpressionFailed"], + [{customer: {code: "7", age: 1}}, {customer: {code: "7", age: 1, n: 7, next: 2}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Every error is collected: one InputValidationFailed lists each failing path, across +// properties, entities, members and globals. + +{ + name: "every invalid property of an entity is reported", + policy: { + models: {customer: {age: "number", name: "string", active: "boolean"}}, + blocks: [{expression: "customer.ok", value: "customer.active"}], + }, + cases: [ + [{customer: {age: "1", name: 2, active: "y"}}, "!error: customer.age"], + [{customer: {age: "1", name: 2, active: "y"}}, "!error: customer.name"], + [{customer: {age: "1", name: 2, active: "y"}}, "!error: customer.active"], + [{customer: {age: 1, name: "a", active: "y"}}, "!error: customer.active"], + [{customer: {age: 1, name: "a", active: false}}, {customer: {age: 1, name: "a", active: false, ok: false}}], + ], +} + +{ + name: "errors from several entities and globals are reported together", + policy: { + globals: {settings: {rate: "number"}}, + models: {customer: {age: "number"}, order: {total: "number"}}, + blocks: [{expression: "order.due", value: "order.total * rate"}], + }, + cases: [ + [{rate: "x", customer: {age: "y"}, order: {total: "z"}}, "!error: rate"], + [{rate: "x", customer: {age: "y"}, order: {total: "z"}}, "!error: customer.age"], + [{rate: "x", customer: {age: "y"}, order: {total: "z"}}, "!error: order.total"], + [{rate: 2, customer: {age: 1}, order: {total: 3}}, {rate: 2, customer: {age: 1}, order: {total: 3, due: 6}}], + ], +} + +{ + name: "every failing member and item is reported", + policy: { + models: {customer: {companies: "company[]", tags: "string[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.n", value: "len(customer.companies)"}], + }, + cases: [ + [{customer: {companies: [{revenue: "a"}, {revenue: 1}, {revenue: "c"}], tags: []}}, "!error: customer.companies[0].revenue"], + [{customer: {companies: [{revenue: "a"}, {revenue: 1}, {revenue: "c"}], tags: []}}, "!error: customer.companies[2].revenue"], + [{customer: {companies: [], tags: ["a", 1, "b", false]}}, "!error: customer.tags[1]"], + [{customer: {companies: [], tags: ["a", 1, "b", false]}}, "!error: customer.tags[3]"], + [{customer: {companies: [{revenue: 1}], tags: ["a"]}}, {customer: {companies: [{revenue: 1}], tags: ["a"], n: 1}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Error paths and wording. The path starts at the input key, follows declared property names with +// `.` and array positions with `[i]`. Expected/got name the declared type and the JSON kind of the +// value (`number`, `string`, `bool`, `array`, `object`), or the quoted value for enums and ids. + +{ + name: "the error path of a member property", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number", report: "report?"}, report: {score: "number"}}, + blocks: [{expression: "customer.n", value: "len(customer.companies)"}], + }, + cases: [ + [{customer: {companies: [{revenue: 1}, {revenue: "x"}]}}, "!error: customer.companies[1].revenue"], + [{customer: {companies: [{revenue: 1, report: {score: "s"}}]}}, "!error: customer.companies[0].report.score"], + [{customer: {companies: [{revenue: 1}, 5]}}, "!error: customer.companies[1]"], + [{customer: {companies: [{revenue: 1, report: 7}]}}, "!error: customer.companies[0].report"], + [{customer: {companies: [{revenue: 1, report: {score: 2}}]}}, {customer: {companies: [{revenue: 1, report: {score: 2}}], n: 1}}], + ], +} + +{ + name: "expected and got name the declared type and the value kind", + policy: { + models: {customer: {age: "number", name: "string", active: "boolean", tags: "string[]?", report: "report?"}, report: {score: "number"}}, + blocks: [{expression: "customer.next", value: "customer.age + 1"}], + }, + cases: [ + [{customer: {age: true, name: "a", active: true}}, "!error: got: \"bool\""], + [{customer: {age: "1", name: "a", active: true}}, "!error: expected: \"number\", got: \"string\""], + [{customer: {age: 1, name: [], active: true}}, "!error: got: \"array\""], + [{customer: {age: 1, name: "a", active: {}}}, "!error: got: \"object\""], + [{customer: {age: 1, name: "a", active: true, tags: "a"}}, "!error: array of string"], + [{customer: {age: 1, name: "a", active: true, report: "r"}}, "!error: object (report)"], + ], +} + +{ + name: "enum and reference errors quote the offending value", + policy: { + models: {customer: {tier: "string(gold|silver)", product: "&product?"}, product: {id: "string"}}, + blocks: [{expression: "customer.gold", value: "customer.tier == 'gold'"}], + }, + cases: [ + [{customer: {tier: "bronze"}}, "!error: one of 'gold', 'silver'"], + [{customer: {tier: "bronze"}}, "!error: 'bronze'"], + [{customer: {tier: 3}}, "!error: one of 'gold', 'silver'"], + [{customer: {tier: "gold", product: "p9"}, product: [{id: "p1"}]}, "!error: 'p9' (not found)"], + [{customer: {tier: "gold", product: 9}, product: [{id: "p1"}]}, "!error: reference id (string"], + [{customer: {tier: "gold", product: "p1"}, product: [{id: "p1"}]}, {customer: {tier: "gold", product: {id: "p1"}, gold: true}, product: [{id: "p1"}]}], + ], +} + +{ + name: "a global error path is the bare property name", + policy: { + globals: {env: {region: "string(eu|us)", limits: "number[]?"}}, + blocks: [{expression: "isEu", value: "region == 'eu'"}], + }, + cases: [ + [{region: "apac"}, "!error: region"], + [{region: "eu", limits: [1, "2"]}, "!error: limits[1]"], + [{region: "eu", limits: 3}, "!error: array of number"], + [{region: "us", limits: [1, null, 3]}, {region: "us", limits: [1, null, 3], isEu: false}], + ], +} + +{ + name: "a pool error path starts at the pool key", + policy: { + models: {customer: {product: "&product?"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.has", value: "customer.product != null"}], + }, + cases: [ + [{customer: {}, product: [{id: "p1", price: 1}, {id: "p2", price: "x"}]}, "!error: product[1].price"], + [{customer: {}, product: [{id: 5, price: 1}]}, "!error: product[0].id"], + [{customer: {}, product: "p1"}, "!error: array of product"], + [{customer: {}, product: [{id: "p1", price: 1}]}, {customer: {has: false}, product: [{id: "p1", price: 1}]}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Which keys the validator visits. Root entities (models no relationship or reference targets), +// reference pools (keys named after a reference target) and global properties. Everything else +// passes through unvalidated: undeclared keys, undeclared entity properties, and a top-level key +// named after an entity that is only reachable through a relationship. + +{ + name: "a relationship target entity supplied at the top level is not validated", + policy: { + models: {customer: {companies: "company[]?"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.n", value: "len(customer.companies ?? [])"}], + }, + cases: [ + [{customer: {}, company: {revenue: "x"}}, {customer: {n: 0}, company: {revenue: "x"}}], + [{customer: {}, company: 5}, {customer: {n: 0}, company: 5}], + [{customer: {}, company: [{revenue: "x"}]}, {customer: {n: 0}, company: [{revenue: "x"}]}], + [{customer: {companies: [{revenue: "x"}]}}, "!error: customer.companies[0].revenue"], + ], +} + +{ + name: "an undeclared property of an entity is not validated at any depth", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.n", value: "len(customer.companies)"}], + }, + cases: [ + [{customer: {companies: [], misc: 5}}, {customer: {companies: [], misc: 5, n: 0}}], + [{customer: {companies: [{revenue: 1, revenueText: 1}]}}, {customer: {companies: [{revenue: 1, revenueText: 1}], n: 1}}], + [{customer: {companies: [{revenue: 1, Revenue: "x"}]}}, {customer: {companies: [{revenue: 1, Revenue: "x"}], n: 1}}], + [{customer: {companies: [{revenue: 1, nested: {revenue: "x"}}]}}, {customer: {companies: [{revenue: 1, nested: {revenue: "x"}}], n: 1}}], + ], +} + +{ + name: "a required member property may be missing as far as validation goes", + policy: { + models: {customer: {companies: "company[]"}, company: {name: "string", revenue: "number"}}, + blocks: [{expression: "customer.n", value: "len(customer.companies)"}], + }, + cases: [ + [{customer: {companies: [{}]}}, {customer: {companies: [{}], n: 1}}], + [{customer: {companies: [{name: null, revenue: null}]}}, {customer: {companies: [{name: null, revenue: null}], n: 1}}], + [{customer: {companies: [{name: "a"}, {revenue: 2}]}}, {customer: {companies: [{name: "a"}, {revenue: 2}], n: 2}}], + ], +} + +{ + name: "a null at any level skips its validation", + policy: { + globals: {env: {limit: "number?"}}, + models: {customer: {age: "number?", report: "report?", companies: "company[]?"}, report: {score: "number"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.known", value: "customer.age != null"}], + }, + cases: [ + [{customer: null, limit: null}, {customer: {known: false}, limit: null}, "bug: a null entity root swallows the computed write customer.known (as a null spine does in chapter 04); null should behave like a missing entity"], + [{customer: {report: null, companies: null}}, {customer: {report: null, companies: null, known: false}}], + [{customer: {report: {score: null}, companies: [null, {revenue: null}]}}, {customer: {report: {score: null}, companies: [null, {revenue: null}], known: false}}], + [{customer: {age: 3, companies: [null, {revenue: "x"}]}}, "!error: customer.companies[1].revenue"], + ], +} + +// --------------------------------------------------------------------------------------------- +// The request itself. A non-object input is rejected (chapter 01), except null, which the +// validator lets through. + +{ + name: "a null input with a required read", + policy: { + models: {customer: {age: "number"}}, + blocks: [{expression: "customer.next", value: "customer.age + 1"}], + }, + cases: [ + [null, "!error: MissingRequiredInputs", "bug: a null request passes validation and the required-input check (the check only walks objects), so the block runs and fails with ExpressionFailed on `null + 1`"], + [{}, "!error: MissingRequiredInputs"], + [{customer: {age: 1}}, {customer: {age: 1, next: 2}}], + ], +} + +{ + name: "a null input with only optional reads", + policy: { + models: {customer: {age: "number?"}}, + blocks: [{expression: "result", value: "customer.age ?? 0"}], + }, + cases: [ + [null, null, "question: a null request is accepted, the block runs, but nothing can be written into a null store, so the output is null instead of {result: 0}"], + [{}, {result: 0}], + [{customer: {}}, {customer: {}, result: 0}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Root entity validation. Scalars of each type, arrays of each type, enum arrays, optional +// modifiers on every kind. + +{ + name: "every scalar kind at the root, valid values", + policy: { + models: {p: {n: "number", s: "string", b: "boolean", d: "date", e: "string(x|y)"}}, + blocks: [{expression: "p.ok", value: "true"}], + }, + cases: [ + [{p: {n: 0, s: "", b: false, d: "2025-01-01", e: "x"}}, {p: {n: 0, s: "", b: false, d: date("2025-01-01"), e: "x", ok: true}}], + [{p: {n: -1.5, s: "1", b: true, d: "2025-01-01T10:00:00Z", e: "y"}}, {p: {n: -1.5, s: "1", b: true, d: date("2025-01-01T10:00:00Z"), e: "y", ok: true}}], + [{p: {}}, {p: {ok: true}}], + [{p: {n: 12345678901234567890123456}}, {p: {n: 12345678901234567890123456, ok: true}}], + ], +} + +{ + name: "every scalar kind at the root, wrong values", + policy: { + models: {p: {n: "number", s: "string", b: "boolean", d: "date", e: "string(x|y)"}}, + blocks: [{expression: "p.ok", value: "true"}], + }, + cases: [ + [{p: {n: "0"}}, "!error: p.n"], + [{p: {s: 0}}, "!error: p.s"], + [{p: {b: "false"}}, "!error: p.b"], + [{p: {d: true}}, "!error: p.d"], + [{p: {e: "X"}}, "!error: p.e"], + [{p: {e: ["x"]}}, "!error: p.e"], + [{p: {n: {}}}, "!error: p.n"], + [{p: {s: {}}}, "!error: p.s"], + ], +} + +{ + name: "every array kind at the root", + policy: { + models: {p: {ns: "number[]?", ss: "string[]?", bs: "boolean[]?", ds: "date[]?", es: "string(x|y)[]?"}}, + blocks: [{expression: "p.ok", value: "true"}], + }, + cases: [ + [{p: {ns: [1, 2], ss: ["a"], bs: [true], ds: ["2025-01-01"], es: ["x", "y", "x"]}}, {p: {ns: [1, 2], ss: ["a"], bs: [true], ds: [date("2025-01-01")], es: ["x", "y", "x"], ok: true}}], + [{p: {ns: [], ss: [], bs: [], ds: [], es: []}}, {p: {ns: [], ss: [], bs: [], ds: [], es: [], ok: true}}], + [{p: {ns: [null], ss: [null], bs: [null], ds: [null], es: [null]}}, {p: {ns: [null], ss: [null], bs: [null], ds: [null], es: [null], ok: true}}], + [{p: {ns: ["1"]}}, "!error: p.ns[0]"], + [{p: {ss: [1]}}, "!error: p.ss[0]"], + [{p: {bs: [1]}}, "!error: p.bs[0]"], + [{p: {ds: ["2025-02-30"]}}, "!error: p.ds[0]"], + [{p: {es: ["x", "z"]}}, "!error: p.es[1]"], + [{p: {es: "x"}}, "!error: p.es"], + [{p: {ns: {a: 1}}}, "!error: p.ns"], + ], +} + +{ + name: "a non-optional array is checked for presence only when read", + policy: { + models: {p: {ns: "number[]", ss: "string[]"}}, + blocks: [{expression: "p.total", value: "sum(p.ns)"}], + }, + cases: [ + [{p: {ns: [1]}}, {p: {ns: [1], total: 1}}], + [{p: {ns: [1], ss: null}}, {p: {ns: [1], ss: null, total: 1}}], + [{p: {ss: ["a"]}}, "!error: MissingRequiredInputs"], + [{p: {ns: [1], ss: "a"}}, "!error: p.ss"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Member validation: every kind inside array members and inside a single relationship. + +{ + name: "every kind inside array members", + policy: { + models: { + order: {lines: "line[]"}, + line: {qty: "number", sku: "string", gift: "boolean?", shipped: "date?", kind: "string(goods|service)", tags: "string[]?"}, + }, + blocks: [{expression: "order.count", value: "len(order.lines)"}], + }, + cases: [ + [ + {order: {lines: [{qty: 1, sku: "a", kind: "goods"}, {qty: 2, sku: "b", gift: true, shipped: "2025-03-01", kind: "service", tags: ["t"]}]}}, + {order: {lines: [{qty: 1, sku: "a", kind: "goods"}, {qty: 2, sku: "b", gift: true, shipped: date("2025-03-01"), kind: "service", tags: ["t"]}], count: 2}}, + ], + [{order: {lines: [{qty: "1", sku: "a", kind: "goods"}]}}, "!error: order.lines[0].qty"], + [{order: {lines: [{qty: 1, sku: 1, kind: "goods"}]}}, "!error: order.lines[0].sku"], + [{order: {lines: [{qty: 1, sku: "a", kind: "goods", gift: "yes"}]}}, "!error: order.lines[0].gift"], + [{order: {lines: [{qty: 1, sku: "a", kind: "goods", shipped: "soon"}]}}, "!error: order.lines[0].shipped"], + [{order: {lines: [{qty: 1, sku: "a", kind: "goods"}, {qty: 1, sku: "a", kind: "rental"}]}}, "!error: order.lines[1].kind"], + [{order: {lines: [{qty: 1, sku: "a", kind: "goods", tags: [1]}]}}, "!error: order.lines[0].tags[0]"], + [{order: {lines: [{qty: 1, sku: "a", kind: "goods", tags: "t"}]}}, "!error: order.lines[0].tags"], + ], +} + +{ + name: "every kind inside a single relationship", + policy: { + models: { + customer: {profile: "profile"}, + profile: {score: "number", email: "string?", verified: "boolean?", since: "date?", band: "string(a|b)?", scores: "number[]?"}, + }, + blocks: [{expression: "customer.score", value: "customer.profile.score"}], + }, + cases: [ + [ + {customer: {profile: {score: 1, email: "e", verified: false, since: "2020-01-01", band: "a", scores: [1, 2]}}}, + {customer: {profile: {score: 1, email: "e", verified: false, since: date("2020-01-01"), band: "a", scores: [1, 2]}, score: 1}}, + ], + [{customer: {profile: {score: "1"}}}, "!error: customer.profile.score"], + [{customer: {profile: {score: 1, email: 2}}}, "!error: customer.profile.email"], + [{customer: {profile: {score: 1, verified: 0}}}, "!error: customer.profile.verified"], + [{customer: {profile: {score: 1, since: 2020}}}, "!error: customer.profile.since"], + [{customer: {profile: {score: 1, band: "c"}}}, "!error: customer.profile.band"], + [{customer: {profile: {score: 1, scores: [1, "2"]}}}, "!error: customer.profile.scores[1]"], + [{customer: {profile: [{score: 1}]}}, "!error: customer.profile"], + ], +} + +{ + name: "members three levels deep are validated with the full path", + policy: { + models: { + customer: {accounts: "account[]"}, + account: {owner: "owner"}, + owner: {cards: "card[]"}, + card: {limit: "number"}, + }, + blocks: [{expression: "customer.n", value: "len(customer.accounts)"}], + }, + cases: [ + [{customer: {accounts: [{owner: {cards: [{limit: 1}, {limit: 2}]}}]}}, {customer: {accounts: [{owner: {cards: [{limit: 1}, {limit: 2}]}}], n: 1}}], + [{customer: {accounts: [{owner: {cards: []}}, {owner: {cards: [{limit: 1}, {limit: "2"}]}}]}}, "!error: customer.accounts[1].owner.cards[1].limit"], + [{customer: {accounts: [{owner: {cards: {limit: 1}}}]}}, "!error: customer.accounts[0].owner.cards"], + [{customer: {accounts: [{owner: [{cards: []}]}]}}, "!error: customer.accounts[0].owner"], + ], +} + +// A self-referencing entity (a tree) is validated recursively until the nesting limit of 32 +// entity levels. + +{ + name: "a recursive entity is validated at every level", + policy: { + models: {tree: {root: "node"}, node: {v: "number", kids: "node[]?"}}, + blocks: [{expression: "tree.top", value: "tree.root.v"}], + }, + cases: [ + [{tree: {root: {v: 1, kids: [{v: 2, kids: [{v: 3}]}]}}}, {tree: {root: {v: 1, kids: [{v: 2, kids: [{v: 3}]}]}, top: 1}}], + [{tree: {root: {v: 1, kids: [{v: "x"}]}}}, "!error: tree.root.kids[0].v"], + [{tree: {root: {v: 1, kids: [{v: 2, kids: [{v: 3, kids: [{v: true}]}]}]}}}, "!error: tree.root.kids[0].kids[0].kids[0].v"], + [{tree: {root: {v: 1, kids: [null, {v: 2}]}}}, {tree: {root: {v: 1, kids: [null, {v: 2}]}, top: 1}}], + ], +} + +{ + name: "entity nesting beyond the recursion limit is rejected", + policy: { + models: {tree: {root: "node"}, node: {v: "number?", next: "node?"}}, + blocks: [{expression: "tree.has", value: "tree.root != null"}], + }, + cases: [ + [ + {tree: {root: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {}}}}}}}}}}}}}, + {tree: {root: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {}}}}}}}}}}}, has: true}}, + ], + [ + {tree: {root: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {next: {}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}, + "!error: entity nesting within 32 levels", + ], + ], +} + +// --------------------------------------------------------------------------------------------- +// Relationships to a dictionary validate like an enum of the dictionary's values. + +{ + name: "a dictionary-typed property validates against the dictionary values", + policy: { + dictionaries: {tier: ["gold", ["silver", "Silver tier"]]}, + models: {customer: {tier: "tier", history: "tier[]?"}}, + blocks: [{expression: "customer.gold", value: "customer.tier == 'gold'"}], + }, + cases: [ + [{customer: {tier: "gold"}}, {customer: {tier: "gold", gold: true}}], + [{customer: {tier: "silver", history: ["gold", "silver"]}}, {customer: {tier: "silver", history: ["gold", "silver"], gold: false}}], + [{customer: {tier: "Silver tier"}}, "!error: customer.tier"], + [{customer: {tier: "bronze"}}, "!error: one of 'gold', 'silver'"], + [{customer: {tier: 1}}, "!error: InputValidationFailed"], + [{customer: {tier: "gold", history: ["gold", "x"]}}, "!error: customer.history[1]"], + [{customer: {}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a dictionary-typed member property", + policy: { + dictionaries: {currency: ["EUR", "USD"]}, + models: {invoice: {lines: "line[]"}, line: {amount: "number", currency: "currency"}}, + blocks: [{expression: "invoice.n", value: "len(invoice.lines)"}], + }, + cases: [ + [{invoice: {lines: [{amount: 1, currency: "EUR"}, {amount: 2, currency: "USD"}]}}, {invoice: {lines: [{amount: 1, currency: "EUR"}, {amount: 2, currency: "USD"}], n: 2}}], + [{invoice: {lines: [{amount: 1, currency: "eur"}]}}, "!error: invoice.lines[0].currency"], + [{invoice: {lines: [{amount: 1}]}}, {invoice: {lines: [{amount: 1}], n: 1}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// References: ids are validated wherever the reference sits (root property, array, member, +// global), always against the top-level pool. The pool items are validated as entities. + +{ + name: "reference arrays validate each id", + policy: { + models: {cart: {items: "&product[]"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "cart.n", value: "len(cart.items)"}], + }, + cases: [ + [{cart: {items: ["a", "b", "a"]}, product: [{id: "a", price: 1}, {id: "b", price: 2}]}, {cart: {items: [{id: "a", price: 1}, {id: "b", price: 2}, {id: "a", price: 1}], n: 3}, product: [{id: "a", price: 1}, {id: "b", price: 2}]}], + [{cart: {items: ["a", "c"]}, product: [{id: "a", price: 1}]}, "!error: cart.items[1]"], + [{cart: {items: ["a", 1]}, product: [{id: "a", price: 1}]}, "!error: cart.items[1]"], + [{cart: {items: "a"}, product: [{id: "a", price: 1}]}, "!error: cart.items"], + [{cart: {items: []}}, {cart: {items: [], n: 0}}], + ], +} + +{ + name: "a reference inside members is validated against the root pool", + policy: { + models: {order: {lines: "line[]"}, line: {sku: "&product", qty: "number"}, product: {id: "string"}}, + blocks: [{expression: "order.n", value: "len(order.lines)"}], + }, + cases: [ + [{order: {lines: [{sku: "p1", qty: 1}, {sku: "p9", qty: 1}]}, product: [{id: "p1"}]}, "!error: order.lines[1].sku"], + [{order: {lines: [{sku: 1, qty: 1}]}, product: [{id: "p1"}]}, "!error: order.lines[0].sku"], + [{order: {lines: [{sku: "p1", qty: 1}]}}, "!error: 'p1' (not found)"], + [{order: {lines: [{qty: 1}]}}, {order: {lines: [{qty: 1}], n: 1}}], + ], +} + +{ + name: "pool items are validated as entities, including their relationships", + policy: { + models: {customer: {product: "&product?"}, product: {id: "string", vendor: "vendor?"}, vendor: {name: "string"}}, + blocks: [{expression: "customer.has", value: "customer.product != null"}], + }, + cases: [ + [{customer: {}, product: [{id: "p1", vendor: {name: "v"}}]}, {customer: {has: false}, product: [{id: "p1", vendor: {name: "v"}}]}], + [{customer: {}, product: [{id: "p1", vendor: {name: 1}}]}, "!error: product[0].vendor.name"], + [{customer: {}, product: [{id: "p1", vendor: "v"}]}, "!error: product[0].vendor"], + [{customer: {}, product: [{id: "p1", other: 1}]}, {customer: {has: false}, product: [{id: "p1", other: 1}]}], + ], +} + +{ + name: "an unused pool is still validated", + policy: { + models: {customer: {product: "&product?", age: "number"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.adult", value: "customer.age >= 18"}], + }, + cases: [ + [{customer: {age: 20}, product: [{id: "p1", price: "free"}]}, "!error: product[0].price"], + [{customer: {age: 20}, product: {}}, "!error: array of product"], + [{customer: {age: 20}, product: null}, {customer: {age: 20, adult: true}, product: null}], + [{customer: {age: 20}, product: []}, {customer: {age: 20, adult: true}, product: []}], + ], +} + +{ + name: "an invalid id and an invalid pool item are reported together", + policy: { + models: {customer: {product: "&product"}, product: {id: "string", price: "number"}}, + blocks: [{expression: "customer.price", value: "customer.product.price"}], + }, + cases: [ + [{customer: {product: "zz"}, product: [{id: "p1", price: "x"}]}, "!error: customer.product"], + [{customer: {product: "zz"}, product: [{id: "p1", price: "x"}]}, "!error: product[0].price"], + [{customer: {product: "p1"}, product: [{id: "p1", price: "x"}]}, "!error: product[0].price"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Globals: relationship, array relationship and reference globals validate like entity +// properties. + +{ + name: "a global single relationship validates the related entity", + policy: { + globals: {env: {settings: "config?"}}, + models: {config: {rate: "number", mode: "string(fast|slow)"}}, + blocks: [{expression: "rate", value: "settings.rate ?? 1"}], + }, + cases: [ + [{settings: {rate: 2, mode: "fast"}}, {settings: {rate: 2, mode: "fast"}, rate: 2}], + [{}, {rate: 1}], + [{settings: {rate: "2"}}, "!error: settings.rate"], + [{settings: {rate: 2, mode: "medium"}}, "!error: settings.mode"], + [{settings: [{rate: 2}]}, "!error: settings"], + ], +} + +{ + name: "a global array relationship validates each member", + policy: { + globals: {env: {brackets: "bracket[]"}}, + models: {bracket: {from: "number", rate: "number"}}, + blocks: [{expression: "top", value: "max(map(brackets, #.rate))"}], + }, + cases: [ + [{brackets: [{from: 0, rate: 0.1}, {from: 100, rate: 0.2}]}, {brackets: [{from: 0, rate: 0.1}, {from: 100, rate: 0.2}], top: 0.2}], + [{brackets: [{from: 0, rate: 0.1}, {from: "100", rate: 0.2}]}, "!error: brackets[1].from"], + [{brackets: {from: 0, rate: 0.1}}, "!error: brackets"], + [{}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a global reference array validates every id", + policy: { + globals: {env: {allowed: "&product[]?"}}, + models: {product: {id: "string", price: "number"}}, + blocks: [{expression: "n", value: "len(allowed ?? [])"}], + }, + cases: [ + [{allowed: ["p1"], product: [{id: "p1", price: 1}]}, {allowed: [{id: "p1", price: 1}], n: 1, product: [{id: "p1", price: 1}]}], + [{allowed: ["p1", "p2"], product: [{id: "p1", price: 1}]}, "!error: allowed[1]"], + [{allowed: [true], product: [{id: "p1", price: 1}]}, "!error: allowed[0]"], + [{product: [{id: "p1", price: 1}]}, {n: 0, product: [{id: "p1", price: 1}]}], + ], +} + +{ + name: "globals and entities share the top level without cross validation", + policy: { + globals: {env: {code: "string"}}, + models: {customer: {code: "number"}}, + blocks: [{expression: "both", value: "code + string(customer.code)"}], + }, + cases: [ + [{code: "A", customer: {code: 1}}, {code: "A", customer: {code: 1}, both: "A1"}], + [{code: 1, customer: {code: 1}}, "!error: InputValidationFailed"], + [{code: "A", customer: {code: "1"}}, "!error: customer.code"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Missing required inputs in depth: which paths the check sees and how it reports them. + +{ + name: "missing inputs are reported with every missing path", + policy: { + globals: {env: {rate: "number"}}, + models: {customer: {age: "number", report: "report"}, report: {score: "number"}}, + blocks: [{expression: "customer.x", value: "customer.age * rate + customer.report.score"}], + }, + cases: [ + [{}, "!error: MissingRequiredInputs"], + [{customer: {report: {}}}, "!error: rate"], + [{customer: {report: {}}}, "!error: customer.age"], + [{customer: {age: 1, report: {}}, rate: 1}, "!error: customer.report.score"], + [{customer: {age: 1, report: {score: 2}}, rate: 3}, {customer: {age: 1, report: {score: 2}, x: 5}, rate: 3}], + ], +} + +{ + name: "a required member property is not checked before evaluation", + policy: { + models: {customer: {companies: "company[]"}, company: {revenue: "number"}}, + blocks: [{expression: "customer.total", value: "sum(map(customer.companies, #.revenue ?? 0))"}], + }, + cases: [ + [{customer: {companies: [{revenue: 1}, {}]}}, {customer: {companies: [{revenue: 1}, {}], total: 1}}], + [{customer: {companies: [{}]}}, {customer: {companies: [{}], total: 0}}], + [{customer: {}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a required property below a present optional hop is checked", + policy: { + models: {customer: {report: "report?"}, report: {score: "number"}}, + blocks: [{expression: "customer.score", value: "customer.report.score ?? -1"}], + }, + cases: [ + [{customer: {}}, {customer: {score: -1}}], + [{customer: {report: null}}, {customer: {report: null, score: -1}}], + [{customer: {report: {score: 5}}}, {customer: {report: {score: 5}, score: 5}}], + [{customer: {report: {}}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "goals narrow the required-input check but not validation", + policy: { + models: {customer: {age: "number", tier: "string(a|b)"}}, + blocks: [ + {expression: "customer.adult", value: "customer.age >= 18"}, + {expression: "customer.isA", value: "customer.tier == 'a'"}, + ], + }, + cases: [ + {input: {customer: {age: 20}}, goals: ["customer.adult"], output: {customer: {age: 20, adult: true}}}, + {input: {customer: {tier: "a"}}, goals: ["customer.isA"], output: {customer: {tier: "a", isA: true}}}, + {input: {customer: {age: 20, tier: "z"}}, goals: ["customer.adult"], output: "!error: customer.tier"}, + {input: {customer: {age: 20}}, output: "!error: customer.tier"}, + {input: {customer: {tier: "b"}}, goals: ["customer.adult"], output: "!error: customer.age"}, + ], +} + +// --------------------------------------------------------------------------------------------- +// Validation happens after date conversion and before reference hydration: the output keeps the +// converted dates and the resolved references, an error output keeps nothing. + +{ + name: "dates are converted in members, pools and globals", + policy: { + globals: {env: {asOf: "date"}}, + models: {customer: {events: "event[]", fav: "&shop?"}, event: {at: "date"}, shop: {id: "string", opened: "date"}}, + blocks: [{expression: "customer.n", value: "len(customer.events)"}], + }, + cases: [ + [ + {asOf: "2025-03-20", customer: {events: [{at: "2025-01-01"}], fav: "s1"}, shop: [{id: "s1", opened: "2020-05-05"}]}, + {asOf: date("2025-03-20"), customer: {events: [{at: date("2025-01-01")}], fav: {id: "s1", opened: date("2020-05-05")}, n: 1}, shop: [{id: "s1", opened: date("2020-05-05")}]}, + ], + [{asOf: "2025-03-20", customer: {events: [{at: "2025-01-32"}]}}, "!error: customer.events[0].at"], + [{asOf: "2025-03-20", customer: {events: []}, shop: [{id: "s1", opened: "x"}]}, "!error: shop[0].opened"], + [{asOf: "x", customer: {events: []}}, "!error: asOf"], + ], +} + +// --------------------------------------------------------------------------------------------- +// A realistic request: a loan application with several error sources at once. + +{ + name: "a loan application request validated as a whole", + policy: { + globals: {env: {baseRate: "number", region: "string(eu|us)"}}, + models: { + application: {amount: "number", term: "number", purpose: "string(home|car|other)", applicants: "applicant[]"}, + applicant: {income: "number", born: "date", employment: "string(employed|self|none)", employer: "&employer?"}, + employer: {id: "string", rating: "number"}, + }, + blocks: [ + {expression: "application.income", value: "sum(map(application.applicants, #.income))"}, + {expression: "application.rate", value: "baseRate + (application.purpose == 'home' ? 0 : 1)"}, + {expression: "application.ratio", value: "application.amount / application.income"}, + ], + }, + cases: [ + [ + {baseRate: 3, region: "eu", application: {amount: 1000, term: 12, purpose: "car", applicants: [{income: 400, born: "1990-01-01", employment: "employed", employer: "e1"}, {income: 600, born: "1992-02-02", employment: "self"}]}, employer: [{id: "e1", rating: 5}]}, + {baseRate: 3, region: "eu", application: {amount: 1000, term: 12, purpose: "car", applicants: [{income: 400, born: date("1990-01-01"), employment: "employed", employer: {id: "e1", rating: 5}}, {income: 600, born: date("1992-02-02"), employment: "self"}], income: 1000, rate: 4, ratio: 1}, employer: [{id: "e1", rating: 5}]}, + "bug: a reference inside a relationship member is validated but not hydrated (chapter 10), so applicants[0].employer stays the id \"e1\"", + ], + [{baseRate: 3, region: "eu", application: {amount: 1000, term: 12, purpose: "boat", applicants: []}}, "!error: application.purpose"], + [{baseRate: 3, region: "eu", application: {amount: 1000, term: 12, purpose: "home", applicants: [{income: 1, born: "1990-01-01", employment: "retired"}]}}, "!error: application.applicants[0].employment"], + [{baseRate: 3, region: "eu", application: {amount: 1000, term: 12, purpose: "home", applicants: [{income: 1, born: "1990-01-01", employment: "none", employer: "e9"}]}, employer: []}, "!error: application.applicants[0].employer"], + [{baseRate: "3", region: "mars", application: {amount: 1000, term: 12, purpose: "home", applicants: []}}, "!error: region"], + [{region: "eu", application: {term: 12, purpose: "home", applicants: []}}, "!error: MissingRequiredInputs"], + [{baseRate: 2, region: "us", application: {amount: 500, term: 6, purpose: "home", applicants: [{income: 250, born: "2000-12-31", employment: "none"}]}}, {baseRate: 2, region: "us", application: {amount: 500, term: 6, purpose: "home", applicants: [{income: 250, born: date("2000-12-31"), employment: "none"}], income: 250, rate: 2, ratio: 2}}], + ], +} diff --git a/core/engine/tests/spec/policy/38-laziness-and-terminals.json5 b/core/engine/tests/spec/policy/38-laziness-and-terminals.json5 new file mode 100644 index 00000000..7684b79b --- /dev/null +++ b/core/engine/tests/spec/policy/38-laziness-and-terminals.json5 @@ -0,0 +1,971 @@ +// Laziness and terminal writes: which computed properties appear in the output. +// +// Without goals the evaluation demands every terminal write (a computed property no other block +// reads); with goals it demands the goals. A demanded block first demands everything its +// expressions read, so intermediates read by a demanded block appear in the output. Only two reads +// are demanded on selection: match arm values (only the taken arm's value) and table output cells +// (only the matched rows' outputs). Arm conditions, table input cells, assertion conditions and +// the operands of `and`, `?:` and `??` are demanded eagerly. +// +// Known defect pinned here in depth: a read of one nested computed leaf (`a.t.x`) hides every +// other computed write under the same computed object (`a.t.y`, `a.t.u.z`, ...): they are no +// longer terminal and nothing demands them, so they vanish from the output (also seen in +// 26-realistic-billing and 31-goals-advanced). Its boundaries: flat siblings are fine, a read of the +// whole object is fine, a reader under the same object is fine, a read through a member closure +// is fine; everything else that names a leaf below a computed object hides that object's other +// leaves, whatever block kind writes them and wherever the reader sits. + +// --------------------------------------------------------------------------------------------- +// Terminal writes without goals: every block whose property nobody reads runs. + +{ + name: "every flat terminal write appears", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.x", value: "a.v + 1"}, + {expression: "a.y", value: "a.v + 2"}, + {expression: "a.n", value: "a.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, x: 1, y: 2, n: 11}}], + [{a: {v: -1}}, {a: {v: -1, x: 0, y: 1, n: 10}}], + [{a: {v: 0.5}}, {a: {v: 0.5, x: 1.5, y: 2.5, n: 11.5}}], + ], +} + +{ + name: "terminal writes of every block kind appear", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.e", value: "a.v * 2"}, + {match: "a.m", arms: [["a.v > 0", "'pos'"], ["", "'non'"]]}, + {table: "dt", inputs: ["a.v"], outputs: ["a.t1", "a.t2"], rules: [["> 0", "1", "2"], ["", "3", "4"]]}, + {table: "ct", hit: "collect", inputs: ["a.v"], outputs: ["a.c"], rules: [[">= 0", "'a'"], ["> 1", "'b'"]]}, + {assertion: "a.ok", conditions: ["a.v >= 0"]}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, e: 0, m: "non", t1: 3, t2: 4, c: ["a"], ok: true}}], + [{a: {v: 2}}, {a: {v: 2, e: 4, m: "pos", t1: 1, t2: 2, c: ["a", "b"], ok: true}}], + [{a: {v: -1}}, {a: {v: -1, e: -2, m: "non", t1: 3, t2: 4, c: [], ok: false}}], + ], +} + +{ + name: "intermediates read by a terminal write appear with it", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.s1", value: "a.v + 1"}, + {expression: "a.s2", value: "a.s1 * 2"}, + {expression: "a.s3", value: "a.s2 - a.s1"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, s1: 1, s2: 2, s3: 1}}], + [{a: {v: 4}}, {a: {v: 4, s1: 5, s2: 10, s3: 5}}], + ], +} + +{ + name: "a terminal write with a literal value needs no input", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "version", value: "'v1'"}, + {expression: "a.next", value: "a.v + 1"}, + ], + }, + cases: [ + [{a: {v: 1}}, {a: {v: 1, next: 2}, version: "v1"}], + [{a: {}}, "!error: MissingRequiredInputs"], + {input: {}, goals: ["version"], output: {version: "v1"}}, + ], +} + +// --------------------------------------------------------------------------------------------- +// Demand on selection: match arm values and table output cells. An intermediate read only by an +// untaken arm or an unmatched row is never demanded and is absent from the output. + +{ + name: "an intermediate read only by an untaken arm is absent", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.hi", value: "a.v * 10"}, + {expression: "a.lo", value: "a.v - 1"}, + {match: "a.out", arms: [["a.v > 5", "a.hi"], ["", "a.lo"]]}, + ], + }, + cases: [ + [{a: {v: 1}}, {a: {v: 1, lo: 0, out: 0}}], + [{a: {v: 9}}, {a: {v: 9, hi: 90, out: 90}}], + [{a: {v: 5}}, {a: {v: 5, lo: 4, out: 4}}], + {input: {a: {v: 1}}, goals: ["a.out"], output: {a: {v: 1, lo: 0, out: 0}}}, + ], +} + +{ + name: "a chain behind an untaken arm is absent as a whole", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.base", value: "a.v * 2"}, + {expression: "a.hi", value: "a.base + 1"}, + {match: "a.out", arms: [["a.v > 5", "a.hi"], ["", "0"]]}, + ], + }, + cases: [ + [{a: {v: 1}}, {a: {v: 1, out: 0}}], + [{a: {v: 6}}, {a: {v: 6, base: 12, hi: 13, out: 13}}], + ], +} + +{ + name: "an intermediate read by an untaken arm and by a terminal write appears", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.hi", value: "a.v * 10"}, + {match: "a.out", arms: [["a.v > 5", "a.hi"], ["", "0"]]}, + {expression: "a.copy", value: "a.hi"}, + ], + }, + cases: [ + [{a: {v: 1}}, {a: {v: 1, hi: 10, out: 0, copy: 10}}], + [{a: {v: 7}}, {a: {v: 7, hi: 70, out: 70, copy: 70}}], + ], +} + +{ + name: "a goal on an intermediate read only by an arm demands it directly", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.hi", value: "a.v * 10"}, + {match: "a.out", arms: [["a.v > 5", "a.hi"], ["", "0"]]}, + ], + }, + cases: [ + {input: {a: {v: 1}}, goals: ["a.hi"], output: {a: {v: 1, hi: 10}}}, + {input: {a: {v: 1}}, goals: ["a.hi", "a.out"], output: {a: {v: 1, hi: 10, out: 0}}}, + {input: {a: {v: 1}}, goals: ["a.out"], output: {a: {v: 1, out: 0}}}, + {input: {a: {v: 1}}, output: {a: {v: 1, out: 0}}}, + ], +} + +{ + name: "a failing intermediate behind an untaken arm does not fail the evaluation", + policy: { + models: {a: {v: "number", s: "string"}}, + blocks: [ + {expression: "a.parsed", value: "string(number(a.s))"}, + {match: "a.out", arms: [["a.v > 5", "a.parsed"], ["", "'ok'"]]}, + ], + }, + cases: [ + [{a: {v: 1, s: "x"}}, {a: {v: 1, s: "x", out: "ok"}}], + [{a: {v: 9, s: "x"}}, "!error: ExpressionFailed"], + [{a: {v: 9, s: "4"}}, {a: {v: 9, s: "4", parsed: "4", out: "4"}}], + [{a: {v: 1}}, "!error: MissingRequiredInputs", "question: the required-input check is static over every arm (as in chapter 14), so a.s is required although the arm reading it is not taken"], + ], +} + +{ + name: "an intermediate read only by an unmatched first-hit row is absent", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.hiMsg", value: "'high ' + string(a.v)"}, + {expression: "a.loMsg", value: "'low ' + string(a.v)"}, + {table: "dt", inputs: ["a.v"], outputs: ["a.msg"], rules: [["> 10", "a.hiMsg"], ["", "a.loMsg"]]}, + ], + }, + cases: [ + [{a: {v: 1}}, {a: {v: 1, loMsg: "low 1", msg: "low 1"}}], + [{a: {v: 11}}, {a: {v: 11, hiMsg: "high 11", msg: "high 11"}}], + [{a: {v: 10}}, {a: {v: 10, loMsg: "low 10", msg: "low 10"}}], + ], +} + +{ + name: "a collect table demands the outputs of every matched row", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.x", value: "'x'"}, + {expression: "a.y", value: "'y'"}, + {table: "dt", hit: "collect", inputs: ["a.v"], outputs: ["a.out"], rules: [["> 0", "a.x"], ["> 5", "a.y"]]}, + ], + }, + cases: [ + [{a: {v: 1}}, {a: {v: 1, x: "x", out: ["x"]}}], + [{a: {v: 6}}, {a: {v: 6, x: "x", y: "y", out: ["x", "y"]}}], + [{a: {v: 0}}, {a: {v: 0, out: []}}], + ], +} + +{ + name: "a root arm reading member computed values demands them only when taken", + policy: { + models: {o: {items: "item[]", v: "number"}, item: {w: "number"}}, + blocks: [ + {expression: "item.d", value: "item.w * 2"}, + {match: "o.out", arms: [["o.v > 5", "sum(map(o.items, #.d))"], ["", "0"]]}, + ], + }, + cases: [ + [{o: {v: 1, items: [{w: 1}, {w: 2}]}}, {o: {v: 1, items: [{w: 1}, {w: 2}], out: 0}}], + [{o: {v: 9, items: [{w: 1}, {w: 2}]}}, {o: {v: 9, items: [{w: 1, d: 2}, {w: 2, d: 4}], out: 6}}], + [{o: {v: 9, items: []}}, {o: {v: 9, items: [], out: 0}}], + ], +} + +// Per-member arms: the intermediate is one block for all members, so it runs for every member as +// soon as one member takes the arm that reads it. + +{ + name: "per-member arm intermediates run for all members once any member needs them", + policy: { + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "item.hi", value: "item.v * 10"}, + {expression: "item.lo", value: "item.v - 1"}, + {match: "item.out", arms: [["item.v > 5", "item.hi"], ["", "item.lo"]]}, + ], + }, + cases: [ + [{o: {items: [{v: 1}, {v: 2}]}}, {o: {items: [{v: 1, lo: 0, out: 0}, {v: 2, lo: 1, out: 1}]}}], + [{o: {items: [{v: 7}]}}, {o: {items: [{v: 7, hi: 70, out: 70}]}}], + [ + {o: {items: [{v: 1}, {v: 9}]}}, + {o: {items: [{v: 1, hi: 10, lo: 0, out: 0}, {v: 9, hi: 90, lo: 8, out: 90}]}}, + "question: member 0 takes the lo arm yet carries hi (and member 1 carries lo); per-member arm laziness is decided for the whole block, unlike the root-level case where the unread intermediate is absent", + ], + [{o: {items: []}}, {o: {items: []}}], + ], +} + +{ + name: "per-member table rows demand outputs for all members once any member matches", + policy: { + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "item.hi", value: "item.v * 10"}, + {expression: "item.lo", value: "item.v - 1"}, + {table: "dt", inputs: ["item.v"], outputs: ["item.out"], rules: [["> 5", "item.hi"], ["", "item.lo"]]}, + ], + }, + cases: [ + [{o: {items: [{v: 1}, {v: 2}]}}, {o: {items: [{v: 1, lo: 0, out: 0}, {v: 2, lo: 1, out: 1}]}}], + [ + {o: {items: [{v: 1}, {v: 9}]}}, + {o: {items: [{v: 1, hi: 10, lo: 0, out: 0}, {v: 9, hi: 90, lo: 8, out: 90}]}}, + "question: as with per-member arms, the unmatched row's intermediate runs for every member once one member matches that row", + ], + ], +} + +// --------------------------------------------------------------------------------------------- +// Eager reads: conditions, table inputs, assertion conditions and expression operands. Every +// computed property they read is demanded before the block runs, even when evaluation would +// short-circuit past it. + +{ + name: "later arm conditions are demanded after an earlier arm matched", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.p", value: "a.v > 0"}, + {expression: "a.q", value: "a.v > 5"}, + {match: "a.n", arms: [["a.p", "'p'"], ["a.q", "'q'"], ["", "'none'"]]}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, p: false, q: false, n: "none"}}], + [{a: {v: 3}}, {a: {v: 3, p: true, q: false, n: "p"}}], + [{a: {v: 9}}, {a: {v: 9, p: true, q: true, n: "p"}}], + ], +} + +{ + name: "every table input and condition cell is demanded", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.lim", value: "10"}, + {expression: "a.w", value: "a.v * 2"}, + {table: "dt", inputs: ["a.v", "a.w"], outputs: ["a.n"], rules: [["> a.lim", "", "'hi'"], ["", "> 0", "'pos'"], ["", "", "'none'"]]}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, lim: 10, w: 0, n: "none"}}], + [{a: {v: 30}}, {a: {v: 30, lim: 10, w: 60, n: "hi"}}], + [{a: {v: 1}}, {a: {v: 1, lim: 10, w: 2, n: "pos"}}], + ], +} + +{ + name: "every assertion condition is demanded", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.p", value: "a.v > 0"}, + {expression: "a.q", value: "a.v > 5"}, + {assertion: "a.ok", conditions: ["a.p", "a.q"]}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, p: false, q: false, ok: false}}], + [{a: {v: 3}}, {a: {v: 3, p: true, q: false, ok: false}}], + [{a: {v: 6}}, {a: {v: 6, p: true, q: true, ok: true}}], + ], +} + +{ + name: "operands of and, ternary and ?? are demanded", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.p", value: "a.v > 0"}, + {expression: "a.q", value: "a.v > 5"}, + {expression: "a.r", value: "a.v + 1"}, + {expression: "a.s", value: "a.v + 2"}, + {expression: "a.both", value: "a.p and a.q"}, + {expression: "a.pick", value: "a.v > 0 ? a.r : a.s"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, p: false, q: false, r: 1, s: 2, both: false, pick: 2}}], + [{a: {v: 3}}, {a: {v: 3, p: true, q: false, r: 4, s: 5, both: false, pick: 4}}], + ], +} + +{ + name: "a failing eager read fails the evaluation even when short-circuited", + policy: { + models: {a: {v: "number", s: "string"}}, + blocks: [ + {expression: "a.parsed", value: "number(a.s)"}, + {expression: "a.out", value: "a.v < 5 ? 0 : a.parsed"}, + ], + }, + cases: [ + [{a: {v: 1, s: "x"}}, "!error: ExpressionFailed", "question: the ternary never evaluates a.parsed for v < 5, but the block's reads are demanded first, so the failing intermediate fails the evaluation; arm values are lazy, expression branches are not"], + [{a: {v: 1, s: "3"}}, {a: {v: 1, s: "3", parsed: 3, out: 0}}], + [{a: {v: 9, s: "3"}}, {a: {v: 9, s: "3", parsed: 3, out: 3}}], + [{a: {v: 9, s: "x"}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "the right operand of ?? is demanded even when the left is present", + policy: { + models: {a: {v: "number?", s: "string"}}, + blocks: [ + {expression: "a.fallback", value: "number(a.s)"}, + {expression: "a.out", value: "a.v ?? a.fallback"}, + ], + }, + cases: [ + [{a: {v: 1, s: "x"}}, "!error: ExpressionFailed", "question: a.v is present so the fallback is never used, but its block is demanded first and fails"], + [{a: {v: 1, s: "2"}}, {a: {v: 1, s: "2", fallback: 2, out: 1}}], + [{a: {s: "2"}}, {a: {s: "2", fallback: 2, out: 2}}], + ], +} + +{ + name: "a failing later arm condition fails the evaluation after an earlier arm matched", + policy: { + models: {a: {v: "number", s: "string"}}, + blocks: [ + {expression: "a.big", value: "number(a.s) > 0"}, + {match: "a.out", arms: [["a.v < 5", "'small'"], ["a.big", "'big'"], ["", "'d'"]]}, + ], + }, + cases: [ + [{a: {v: 1, s: "x"}}, "!error: ExpressionFailed", "question: the first arm matches, yet the read of the second arm's condition is demanded and fails (chapter 31 notes the same eager demand of later conditions)"], + [{a: {v: 1, s: "1"}}, {a: {v: 1, s: "1", big: true, out: "small"}}], + [{a: {v: 9, s: "0"}}, {a: {v: 9, s: "0", big: false, out: "d"}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Goals: only the goal cones run; the output is the input plus those writes. + +{ + name: "goals select nested leaves and their parents", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + {input: {a: {v: 0}}, goals: ["a.n"], output: {a: {v: 0, t: {x: 1}, n: 11}}}, + {input: {a: {v: 0}}, goals: ["a.t.y"], output: {a: {v: 0, t: {y: 2}}}}, + {input: {a: {v: 0}}, goals: ["a.t"], output: {a: {v: 0, t: {x: 1, y: 2}}}}, + {input: {a: {v: 0}}, goals: ["a.n", "a.t"], output: {a: {v: 0, t: {x: 1, y: 2}, n: 11}}}, + {input: {a: {v: 0}}, goals: ["a.n", "a.t.y"], output: {a: {v: 0, t: {x: 1, y: 2}, n: 11}}}, + ], +} + +// --------------------------------------------------------------------------------------------- +// The nested-sibling defect. In each suite the expected output holds every terminal write. + +{ + name: "nested siblings under an entity: one leaf read hides the other", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: 11}}, "bug: a.n reads a.t.x, which hides the terminal write a.t.y; it never runs"], + [{a: {v: 5}}, {a: {v: 5, t: {x: 6, y: 7}, n: 16}}, "bug: a.n reads a.t.x, which hides the terminal write a.t.y; it never runs"], + [{a: {v: -1.5}}, {a: {v: -1.5, t: {x: -0.5, y: 0.5}, n: 9.5}}, "bug: a.n reads a.t.x, which hides the terminal write a.t.y; it never runs"], + ], +} + +{ + name: "nested siblings at the top level", + policy: { + globals: {env: {v: "number"}}, + blocks: [ + {expression: "t.x", value: "v + 1"}, + {expression: "t.y", value: "v + 2"}, + {expression: "n", value: "t.x + 10"}, + ], + }, + cases: [ + [{v: 0}, {v: 0, t: {x: 1, y: 2}, n: 11}, "bug: n reads t.x, which hides the top-level terminal write t.y"], + [{v: 3}, {v: 3, t: {x: 4, y: 5}, n: 14}, "bug: n reads t.x, which hides the top-level terminal write t.y"], + ], +} + +{ + name: "every write under the read object is hidden, at any depth", + policy: { + blocks: [ + {expression: "r.a.b.c.x", value: "1"}, + {expression: "r.a.b.c.y", value: "2"}, + {expression: "r.a.b.z", value: "3"}, + {expression: "r.a.w", value: "4"}, + {expression: "r.k", value: "5"}, + {expression: "s.m", value: "6"}, + {expression: "n", value: "r.a.b.c.x"}, + ], + }, + cases: [ + [{}, {r: {a: {b: {c: {x: 1, y: 2}, z: 3}, w: 4}, k: 5}, s: {m: 6}, n: 1}, "bug: n reads r.a.b.c.x, which hides every other write under r (c.y, b.z, a.w, r.k); s.m under another object survives"], + [{other: 1}, {other: 1, r: {a: {b: {c: {x: 1, y: 2}, z: 3}, w: 4}, k: 5}, s: {m: 6}, n: 1}, "bug: n reads r.a.b.c.x, which hides every other write under r (c.y, b.z, a.w, r.k); s.m under another object survives"], + ], +} + +{ + name: "a deep read hides cousins under the shared computed ancestor", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.u.x", value: "a.v + 1"}, + {expression: "a.t.u.y", value: "a.v + 2"}, + {expression: "a.t.z", value: "a.v + 3"}, + {expression: "a.s.q", value: "a.v + 4"}, + {expression: "a.n", value: "a.t.u.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {u: {x: 1, y: 2}, z: 3}, s: {q: 4}, n: 11}}, "bug: a.n reads a.t.u.x, which hides a.t.u.y and the cousin a.t.z; a.s.q under another object survives"], + [{a: {v: 10}}, {a: {v: 10, t: {u: {x: 11, y: 12}, z: 13}, s: {q: 14}, n: 21}}, "bug: a.n reads a.t.u.x, which hides a.t.u.y and the cousin a.t.z; a.s.q under another object survives"], + ], +} + +{ + name: "the hidden sibling may itself read the leaf that is read", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.t.x + 2"}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 3}, n: 11}}, "bug: a.t.y reads a.t.x and is terminal, but a.n's read of a.t.x hides it"], + [{a: {v: 2}}, {a: {v: 2, t: {x: 3, y: 5}, n: 13}}, "bug: a.t.y reads a.t.x and is terminal, but a.n's read of a.t.x hides it"], + ], +} + +{ + name: "the hidden sibling is written by a match block", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {match: "a.t.y", arms: [["a.v > 0", "'pos'"], ["", "'non'"]]}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: "non"}, n: 11}}, "bug: the match write a.t.y is hidden by the read of a.t.x"], + [{a: {v: 1}}, {a: {v: 1, t: {x: 2, y: "pos"}, n: 12}}, "bug: the match write a.t.y is hidden by the read of a.t.x"], + ], +} + +{ + name: "the hidden sibling is written by a collect table", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {table: "dt", hit: "collect", inputs: ["a.v"], outputs: ["a.t.list"], rules: [["> -1", "'a'"], ["", "'b'"]]}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, list: ["a", "b"]}, n: 11}}, "bug: the collect table write a.t.list is hidden by the read of a.t.x"], + [{a: {v: -5}}, {a: {v: -5, t: {x: -4, list: ["b"]}, n: 6}}, "bug: the collect table write a.t.list is hidden by the read of a.t.x"], + ], +} + +{ + name: "hidden assertion and table siblings", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {assertion: "a.t.ok", conditions: ["a.v >= 0"]}, + {table: "dt", inputs: ["a.v"], outputs: ["a.t.band"], rules: [["> 0", "'p'"], ["", "'z'"]]}, + {expression: "a.n", value: "a.t.x"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, ok: true, band: "z"}, n: 1}}, "bug: the assertion a.t.ok and the table write a.t.band are hidden by the read of a.t.x"], + [{a: {v: 3}}, {a: {v: 3, t: {x: 4, ok: true, band: "p"}, n: 4}}, "bug: the assertion a.t.ok and the table write a.t.band are hidden by the read of a.t.x"], + ], +} + +{ + name: "a table writing both leaves is not affected", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {table: "dt", inputs: ["a.v"], outputs: ["a.t.x", "a.t.y"], rules: [["> 0", "1", "2"], ["", "3", "4"]]}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 3, y: 4}, n: 13}}], + [{a: {v: 1}}, {a: {v: 1, t: {x: 1, y: 2}, n: 11}}], + ], +} + +// The reader's block kind and expression shape do not matter. + +{ + name: "the reader is a table input", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {table: "dt", inputs: ["a.t.x"], outputs: ["a.n"], rules: [["> 1", "'big'"], ["", "'small'"]]}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: "small"}}, "bug: the table input a.t.x hides the terminal write a.t.y"], + [{a: {v: 3}}, {a: {v: 3, t: {x: 4, y: 5}, n: "big"}}, "bug: the table input a.t.x hides the terminal write a.t.y"], + ], +} + +{ + name: "the reader is an assertion condition", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {assertion: "a.ok", conditions: ["a.t.x > 0"]}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, ok: true}}, "bug: the assertion's read of a.t.x hides the terminal write a.t.y"], + [{a: {v: -3}}, {a: {v: -3, t: {x: -2, y: -1}, ok: false}}, "bug: the assertion's read of a.t.x hides the terminal write a.t.y"], + ], +} + +{ + name: "the reader is a closure, a template or an index access", + policy: { + models: {a: {v: "number"}, b: {v: "number"}, c: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.n", value: "map([1, 2], # + a.t.x)"}, + {expression: "b.t.x", value: "b.v + 1"}, + {expression: "b.t.y", value: "b.v + 2"}, + {expression: "b.n", value: "`x=${b.t.x}`"}, + {expression: "c.t.x", value: "c.v + 1"}, + {expression: "c.t.y", value: "c.v + 2"}, + {expression: "c.n", value: "c.t['x']"}, + ], + }, + cases: [ + [ + {a: {v: 0}, b: {v: 0}, c: {v: 0}}, + {a: {v: 0, t: {x: 1, y: 2}, n: [2, 3]}, b: {v: 0, t: {x: 1, y: 2}, n: "x=1"}, c: {v: 0, t: {x: 1, y: 2}, n: 1}}, + "bug: a closure, a template string and an index access each hide the unread sibling t.y", + ], + ], +} + +{ + name: "both leaves read by arm values: only the taken one runs, which is not the defect", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {match: "a.n", arms: [["a.v > 5", "a.t.y"], ["", "a.t.x"]]}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1}, n: 1}}], + [{a: {v: 9}}, {a: {v: 9, t: {y: 11}, n: 11}}], + ], +} + +{ + name: "the reader is on another entity", + policy: { + models: {a: {v: "number"}, b: {w: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "b.n", value: "a.t.x + b.w"}, + ], + }, + cases: [ + [{a: {v: 0}, b: {w: 1}}, {a: {v: 0, t: {x: 1, y: 2}}, b: {w: 1, n: 2}}, "bug: b.n reads a.t.x, which hides a.t.y"], + [{a: {v: 1}, b: {w: 1}}, {a: {v: 1, t: {x: 2, y: 3}}, b: {w: 1, n: 3}}, "bug: b.n reads a.t.x, which hides a.t.y"], + ], +} + +{ + name: "the reader sits in an importing policy", + policies: { + lib: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + ], + }, + }, + policy: { + imports: ["lib"], + models: {a: {v: "number"}}, + blocks: [{expression: "a.n", value: "a.t.x + 10"}], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: 11}}, "bug: the importer's read of a.t.x hides the imported terminal write a.t.y"], + [{a: {v: 2}}, {a: {v: 2, t: {x: 3, y: 4}, n: 13}}, "bug: the importer's read of a.t.x hides the imported terminal write a.t.y"], + ], +} + +{ + name: "the reader sits in an imported policy", + policies: { + lib: { + models: {a: {v: "number"}}, + blocks: [{expression: "a.n", value: "a.t.x + 10"}], + }, + }, + policy: { + imports: ["lib"], + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: 11}}, "bug: the imported block's read of a.t.x hides the importer's terminal write a.t.y"], + ], +} + +{ + name: "per-member nested siblings with a per-member reader", + policy: { + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "item.t.x", value: "item.v + 1"}, + {expression: "item.t.y", value: "item.v + 2"}, + {expression: "item.n", value: "item.t.x + 10"}, + ], + }, + cases: [ + [{o: {items: [{v: 0}, {v: 1}]}}, {o: {items: [{v: 0, t: {x: 1, y: 2}, n: 11}, {v: 1, t: {x: 2, y: 3}, n: 12}]}}, "bug: item.n reads item.t.x, which hides item.t.y on every member"], + [{o: {items: []}}, {o: {items: []}}], + ], +} + +{ + name: "root nested siblings read from a member block", + policy: { + models: {o: {items: "item[]", v: "number"}, item: {w: "number"}}, + blocks: [ + {expression: "o.t.x", value: "o.v + 1"}, + {expression: "o.t.y", value: "o.v + 2"}, + {expression: "item.n", value: "item.w + o.t.x"}, + ], + }, + cases: [ + [{o: {v: 0, items: [{w: 1}]}}, {o: {v: 0, items: [{w: 1, n: 2}], t: {x: 1, y: 2}}}, "bug: the member block's read of o.t.x hides o.t.y"], + [{o: {v: 0, items: []}}, {o: {v: 0, items: [], t: {x: 1, y: 2}}}, "bug: the member block's read of o.t.x hides o.t.y even with no members"], + ], +} + +{ + name: "a chain of readers keeps its own path and drops the hidden ones", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.n", value: "a.t.x + 10"}, + {expression: "a.m", value: "a.n + 1"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: 11, m: 12}}, "bug: a.t.y is hidden by a.n's read of a.t.x; the chain a.n -> a.m itself runs"], + ], +} + +{ + name: "a reader nested under a second object hides siblings in both objects", + policy: { + blocks: [ + {expression: "r.x", value: "1"}, + {expression: "r.y", value: "2"}, + {expression: "s.n", value: "r.x"}, + {expression: "s.m", value: "3"}, + {expression: "q", value: "s.n"}, + ], + }, + cases: [ + [{}, {r: {x: 1, y: 2}, s: {n: 1, m: 3}, q: 1}, "bug: q reads s.n, hiding s.m; s.n reads r.x, hiding r.y"], + ], +} + +{ + name: "two readers hide everything they do not read", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.t.z", value: "a.v + 3"}, + {expression: "a.n", value: "a.t.x + 10"}, + {expression: "a.m", value: "a.t.y + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2, z: 3}, n: 11, m: 12}}, "bug: a.t.x and a.t.y are read, so they run; the unread a.t.z is hidden"], + ], +} + +// The defect has consequences beyond the missing keys: a hidden sibling's runtime error never +// surfaces, while its required inputs are still checked. + +{ + name: "a hidden sibling's error does not surface, its inputs are still required", + policy: { + models: {a: {v: "number"}, b: {s: "string"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "number(b.s)"}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}, b: {s: "zz"}}, "!error: ExpressionFailed", "bug: a.t.y is a terminal write and number('zz') fails; because a.t.y is hidden by the read of a.t.x it never runs and the evaluation succeeds"], + [{a: {v: 0}, b: {s: "5"}}, {a: {v: 0, t: {x: 1, y: 5}, n: 11}, b: {s: "5"}}, "bug: a.t.y is hidden by the read of a.t.x"], + [{a: {v: 0}}, "!error: MissingRequiredInputs"], + ], +} + +// Where the defect does not reach: flat siblings, whole-object reads, readers under the same +// object, member reads through a closure or an index from the root, and goals naming the leaf. + +{ + name: "a read of the whole computed object demands every leaf", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.n", value: "a.t"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: {x: 1, y: 2}}}], + [{a: {v: 7}}, {a: {v: 7, t: {x: 8, y: 9}, n: {x: 8, y: 9}}}], + ], +} + +{ + name: "a read of an intermediate object demands its leaves but hides its cousins", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.u.x", value: "a.v + 1"}, + {expression: "a.t.u.y", value: "a.v + 2"}, + {expression: "a.t.z", value: "a.v + 3"}, + {expression: "a.n", value: "a.t.u"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {u: {x: 1, y: 2}, z: 3}, n: {x: 1, y: 2}}}, "bug: a.n reads a.t.u, which hides the cousin a.t.z"], + ], +} + +{ + name: "a reader under the same computed object does not hide its siblings", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.t.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2, n: 11}}}], + [{a: {v: 4}}, {a: {v: 4, t: {x: 5, y: 6, n: 15}}}], + ], +} + +{ + name: "siblings under an entity of a different name are not hidden", + policy: { + models: {a: {v: "number"}, b: {w: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "b.t.y", value: "b.w + 2"}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + [{a: {v: 0}, b: {w: 1}}, {a: {v: 0, t: {x: 1}, n: 11}, b: {w: 1, t: {y: 3}}}], + ], +} + +{ + name: "a root read of member leaves through a closure or index does not hide", + policy: { + models: {o: {items: "item[]"}, item: {w: "number"}}, + blocks: [ + {expression: "item.t.x", value: "item.w * 2"}, + {expression: "item.t.y", value: "item.w * 3"}, + {expression: "o.sum", value: "sum(map(o.items, #.t.x))"}, + {expression: "o.first", value: "o.items[0].t.x ?? 0"}, + ], + }, + cases: [ + [{o: {items: [{w: 1}, {w: 2}]}}, {o: {items: [{w: 1, t: {x: 2, y: 3}}, {w: 2, t: {x: 4, y: 6}}], sum: 6, first: 2}}], + [{o: {items: []}}, {o: {items: [], sum: 0, first: 0}}], + ], +} + +{ + name: "a reader of every leaf leaves nothing to hide but an unread third", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.n", value: "a.t.x + a.t.y"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: 3}}], + [{a: {v: 1}}, {a: {v: 1, t: {x: 2, y: 3}, n: 5}}], + ], +} + +{ + name: "a hidden sibling read elsewhere is demanded through that reader", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.n", value: "a.t.x + 10"}, + {expression: "a.u.k", value: "a.t.y"}, + ], + }, + cases: [ + [{a: {v: 0}}, {a: {v: 0, t: {x: 1, y: 2}, n: 11, u: {k: 2}}}], + ], +} + +{ + name: "goals naming the hidden leaf bring it back", + policy: { + models: {a: {v: "number"}}, + blocks: [ + {expression: "a.t.x", value: "a.v + 1"}, + {expression: "a.t.y", value: "a.v + 2"}, + {expression: "a.n", value: "a.t.x + 10"}, + ], + }, + cases: [ + {input: {a: {v: 1}}, goals: ["a.n", "a.t.y"], output: {a: {v: 1, t: {x: 2, y: 3}, n: 12}}}, + {input: {a: {v: 1}}, goals: ["a.n", "a.t"], output: {a: {v: 1, t: {x: 2, y: 3}, n: 12}}}, + {input: {a: {v: 1}}, output: {a: {v: 1, t: {x: 2, y: 3}, n: 12}}, note: "bug: without goals a.t.y is hidden by the read of a.t.x"}, + ], +} + +// --------------------------------------------------------------------------------------------- +// A realistic shape: a pricing summary object read by one consumer, with sibling figures that +// only the caller reads. + +{ + name: "a quote summary whose figures only the caller reads", + policy: { + models: {quote: {lines: "qline[]", country: "string(DE|FR)"}, qline: {qty: "number", price: "number"}}, + blocks: [ + {expression: "qline.total", value: "qline.qty * qline.price"}, + {expression: "quote.summary.net", value: "sum(map(quote.lines, #.total))"}, + {expression: "quote.summary.count", value: "len(quote.lines)"}, + {match: "quote.summary.vatRate", arms: [["quote.country == 'DE'", "0.19"], ["", "0.2"]]}, + {expression: "quote.approval", value: "quote.summary.net > 1000 ? 'manager' : 'auto'"}, + ], + }, + cases: [ + [ + {quote: {country: "DE", lines: [{qty: 2, price: 100}]}}, + {quote: {country: "DE", lines: [{qty: 2, price: 100, total: 200}], summary: {net: 200, count: 1, vatRate: 0.19}, approval: "auto"}}, + "bug: quote.approval reads quote.summary.net, which hides the terminal writes quote.summary.count and quote.summary.vatRate", + ], + [ + {quote: {country: "FR", lines: [{qty: 3, price: 500}, {qty: 1, price: 1}]}}, + {quote: {country: "FR", lines: [{qty: 3, price: 500, total: 1500}, {qty: 1, price: 1, total: 1}], summary: {net: 1501, count: 2, vatRate: 0.2}, approval: "manager"}}, + "bug: quote.approval reads quote.summary.net, which hides the terminal writes quote.summary.count and quote.summary.vatRate", + ], + { + input: {quote: {country: "FR", lines: []}}, + goals: ["quote.approval", "quote.summary"], + output: {quote: {country: "FR", lines: [], summary: {net: 0, count: 0, vatRate: 0.2}, approval: "auto"}}, + }, + ], +} diff --git a/core/engine/tests/spec/policy/39-numbers-in-policies.json5 b/core/engine/tests/spec/policy/39-numbers-in-policies.json5 new file mode 100644 index 00000000..68609968 --- /dev/null +++ b/core/engine/tests/spec/policy/39-numbers-in-policies.json5 @@ -0,0 +1,773 @@ +// Numbers in policies. Every number is an exact decimal (28 significant digits, max magnitude +// 79228162514264337593543950335) from the input, through every block, to the output. The +// arithmetic itself is specified by the expression suite (01/02-numbers, 06-rounding, +// 08-arithmetic); this chapter pins what the policy engine adds: decimals carried between +// blocks, through members and aggregates, into table cells and match conditions, division by +// zero producing a null that later blocks must cope with, and overflow failing the evaluation. +// Outputs compare by value, so `1.50` and `1.5` are the same expected number. + +// --------------------------------------------------------------------------------------------- +// Exactness across blocks: no binary floating point anywhere along a chain of computed values. + +{ + name: "decimal sums carried between blocks stay exact", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.sum", value: "a.x + a.y"}, + {expression: "a.isPoint3", value: "a.sum == 0.3"}, + {expression: "a.back", value: "a.sum - a.y"}, + {expression: "a.same", value: "a.back == a.x"}, + ], + }, + cases: [ + [{a: {x: 0.1, y: 0.2}}, {a: {x: 0.1, y: 0.2, sum: 0.3, isPoint3: true, back: 0.1, same: true}}], + [{a: {x: 0.7, y: -0.4}}, {a: {x: 0.7, y: -0.4, sum: 0.3, isPoint3: true, back: 0.7, same: true}}], + [{a: {x: 1.1, y: 2.2}}, {a: {x: 1.1, y: 2.2, sum: 3.3, isPoint3: false, back: 1.1, same: true}}], + [{a: {x: 0.0000000001, y: 0.2999999999}}, {a: {x: 0.0000000001, y: 0.2999999999, sum: 0.3, isPoint3: true, back: 0.0000000001, same: true}}], + ], +} + +{ + name: "trailing zeros do not change equality", + policy: { + models: {a: {x: "number"}}, + blocks: [ + {expression: "a.isOne", value: "a.x == 1"}, + {expression: "a.inList", value: "a.x in [1, 2.5]"}, + {expression: "a.twice", value: "a.x * 2"}, + ], + }, + cases: [ + [{a: {x: 1}}, {a: {x: 1, isOne: true, inList: true, twice: 2}}], + [{a: {x: 1.0}}, {a: {x: 1.0, isOne: true, inList: true, twice: 2.0}}], + [{a: {x: 1.000}}, {a: {x: 1.000, isOne: true, inList: true, twice: 2}}], + [{a: {x: 2.50}}, {a: {x: 2.50, isOne: false, inList: true, twice: 5}}], + [{a: {x: 1.0000000001}}, {a: {x: 1.0000000001, isOne: false, inList: false, twice: 2.0000000002}}], + ], +} + +{ + name: "money multiplication keeps every digit", + policy: { + models: {line: {qty: "number", price: "number", rate: "number"}}, + blocks: [ + {expression: "line.net", value: "line.qty * line.price"}, + {expression: "line.tax", value: "line.net * line.rate"}, + {expression: "line.gross", value: "line.net + line.tax"}, + ], + }, + cases: [ + [{line: {qty: 3, price: 19.99, rate: 0.19}}, {line: {qty: 3, price: 19.99, rate: 0.19, net: 59.97, tax: 11.3943, gross: 71.3643}}], + [{line: {qty: 0.5, price: 0.01, rate: 0.2}}, {line: {qty: 0.5, price: 0.01, rate: 0.2, net: 0.005, tax: 0.001, gross: 0.006}}], + [{line: {qty: 1000000, price: 1234.5678, rate: 0.075}}, {line: {qty: 1000000, price: 1234.5678, rate: 0.075, net: 1234567800, tax: 92592585, gross: 1327160385}}], + [{line: {qty: -2, price: 10.10, rate: 0.1}}, {line: {qty: -2, price: 10.10, rate: 0.1, net: -20.2, tax: -2.02, gross: -22.22}}], + ], +} + +{ + name: "large and tiny inputs pass through and compute exactly", + policy: { + models: {a: {x: "number"}}, + blocks: [ + {expression: "a.plusOne", value: "a.x + 1"}, + {expression: "a.half", value: "a.x / 2"}, + ], + }, + cases: [ + [{a: {x: 12345678901234567890123456}}, {a: {x: 12345678901234567890123456, plusOne: 12345678901234567890123457, half: 6172839450617283945061728}}], + [{a: {x: 0.0000000000000000000000000002}}, {a: {x: 0.0000000000000000000000000002, plusOne: 1.0000000000000000000000000002, half: 0.0000000000000000000000000001}}], + [{a: {x: -9999999999999999999999999999}}, {a: {x: -9999999999999999999999999999, plusOne: -9999999999999999999999999998, half: -4999999999999999999999999999.5}}], + [{a: {x: 1e3}}, {a: {x: 1000, plusOne: 1001, half: 500}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Division: 28 significant digits; a repeating fraction is cut, not rounded to binary. + +{ + name: "division keeps 28 significant digits", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.q", value: "a.x / a.y"}, + {expression: "a.back", value: "a.q * a.y"}, + ], + }, + cases: [ + [{a: {x: 1, y: 3}}, {a: {x: 1, y: 3, q: 0.3333333333333333333333333333, back: 0.9999999999999999999999999999}}], + [{a: {x: 2, y: 3}}, {a: {x: 2, y: 3, q: 0.6666666666666666666666666667, back: 2.0000000000000000000000000001}}], + [{a: {x: 10, y: 4}}, {a: {x: 10, y: 4, q: 2.5, back: 10}}], + [{a: {x: -7, y: 2}}, {a: {x: -7, y: 2, q: -3.5, back: -7}}], + [{a: {x: 1, y: 8}}, {a: {x: 1, y: 8, q: 0.125, back: 1}}], + ], +} + +{ + name: "modulo follows the sign of the dividend", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [{expression: "a.r", value: "a.x % a.y"}], + }, + cases: [ + [{a: {x: 7, y: 2}}, {a: {x: 7, y: 2, r: 1}}], + [{a: {x: -7, y: 2}}, {a: {x: -7, y: 2, r: -1}}], + [{a: {x: 7, y: -2}}, {a: {x: 7, y: -2, r: 1}}], + [{a: {x: 5.5, y: 2}}, {a: {x: 5.5, y: 2, r: 1.5}}], + [{a: {x: 0.3, y: 0.1}}, {a: {x: 0.3, y: 0.1, r: 0}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Division and modulo by zero give null (chapter 02). The null is a computed value like any +// other: it is written to the output and every later block that reads it sees null. + +{ + name: "division and modulo by zero write null", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.q", value: "a.x / a.y"}, + {expression: "a.r", value: "a.x % a.y"}, + ], + }, + cases: [ + [{a: {x: 4, y: 0}}, {a: {x: 4, y: 0, q: null, r: null}}], + [{a: {x: 0, y: 0}}, {a: {x: 0, y: 0, q: null, r: null}}], + [{a: {x: -1, y: 0.0}}, {a: {x: -1, y: 0.0, q: null, r: null}}], + [{a: {x: 4, y: 0.5}}, {a: {x: 4, y: 0.5, q: 8, r: 0}}], + ], +} + +{ + name: "a null quotient defaulted with ??", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.q", value: "a.x / a.y"}, + {expression: "a.safe", value: "a.q ?? 0"}, + {expression: "a.pct", value: "(a.q ?? 0) * 100"}, + ], + }, + cases: [ + [{a: {x: 1, y: 4}}, {a: {x: 1, y: 4, q: 0.25, safe: 0.25, pct: 25}}], + [{a: {x: 1, y: 0}}, {a: {x: 1, y: 0, q: null, safe: 0, pct: 0}}], + [{a: {x: 0, y: 5}}, {a: {x: 0, y: 5, q: 0, safe: 0, pct: 0}}], + ], +} + +{ + name: "arithmetic on a null quotient fails the evaluation", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.q", value: "a.x / a.y"}, + {expression: "a.next", value: "a.q + 1"}, + ], + }, + cases: [ + [{a: {x: 1, y: 2}}, {a: {x: 1, y: 2, q: 0.5, next: 1.5}}], + [{a: {x: 1, y: 0}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a null quotient in a match ordering condition fails the evaluation", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.q", value: "a.x / a.y"}, + {match: "a.band", arms: [["a.q > 1", "'big'"], ["", "'small'"]]}, + ], + }, + cases: [ + [{a: {x: 4, y: 2}}, {a: {x: 4, y: 2, q: 2, band: "big"}}], + [{a: {x: 1, y: 2}}, {a: {x: 1, y: 2, q: 0.5, band: "small"}}], + [{a: {x: 4, y: 0}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a null quotient guarded in the match", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.q", value: "a.x / a.y"}, + {match: "a.band", arms: [["a.q == null", "'undefined'"], ["(a.q ?? 0) > 1", "'big'"], ["", "'small'"]]}, + ], + }, + cases: [ + [{a: {x: 4, y: 2}}, {a: {x: 4, y: 2, q: 2, band: "big"}}], + [{a: {x: 4, y: 0}}, {a: {x: 4, y: 0, q: null, band: "undefined"}}], + [{a: {x: 1, y: 4}}, {a: {x: 1, y: 4, q: 0.25, band: "small"}}], + ], +} + +{ + name: "a null quotient in a table ordering cell fails the evaluation", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.q", value: "a.x / a.y"}, + {table: "dt", inputs: ["a.q"], outputs: ["a.band"], rules: [["> 1", "'big'"], ["", "'small'"]]}, + ], + }, + cases: [ + [{a: {x: 4, y: 2}}, {a: {x: 4, y: 2, q: 2, band: "big"}}], + [{a: {x: 4, y: 0}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "a null quotient matches an explicit null row", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [ + {expression: "a.q", value: "a.x / a.y"}, + {table: "dt", inputs: ["a.q"], outputs: ["a.band"], rules: [["null", "'none'"], ["2", "'two'"], ["", "'other'"]]}, + ], + }, + cases: [ + [{a: {x: 4, y: 0}}, {a: {x: 4, y: 0, q: null, band: "none"}}], + [{a: {x: 4, y: 2}}, {a: {x: 4, y: 2, q: 2, band: "two"}}], + [{a: {x: 4, y: 1}}, {a: {x: 4, y: 1, q: 4, band: "other"}}], + ], +} + +{ + name: "per-member division by zero nulls only that member", + policy: { + models: {o: {items: "item[]"}, item: {num: "number", den: "number"}}, + blocks: [ + {expression: "item.ratio", value: "item.num / item.den"}, + {expression: "o.defined", value: "count(o.items, #.ratio != null)"}, + {expression: "o.total", value: "sum(map(o.items, #.ratio ?? 0))"}, + ], + }, + cases: [ + [ + {o: {items: [{num: 1, den: 2}, {num: 1, den: 0}, {num: 3, den: 4}]}}, + {o: {items: [{num: 1, den: 2, ratio: 0.5}, {num: 1, den: 0, ratio: null}, {num: 3, den: 4, ratio: 0.75}], defined: 2, total: 1.25}}, + ], + [{o: {items: [{num: 0, den: 0}]}}, {o: {items: [{num: 0, den: 0, ratio: null}], defined: 0, total: 0}}], + [{o: {items: []}}, {o: {items: [], defined: 0, total: 0}}], + ], +} + +{ + name: "summing per-member quotients without a default fails on a zero divisor", + policy: { + models: {o: {items: "item[]"}, item: {num: "number", den: "number"}}, + blocks: [ + {expression: "item.ratio", value: "item.num / item.den"}, + {expression: "o.total", value: "sum(map(o.items, #.ratio))"}, + ], + }, + cases: [ + [{o: {items: [{num: 1, den: 2}, {num: 1, den: 4}]}}, {o: {items: [{num: 1, den: 2, ratio: 0.5}, {num: 1, den: 4, ratio: 0.25}], total: 0.75}}], + [{o: {items: [{num: 1, den: 2}, {num: 1, den: 0}]}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "an average over an empty relationship divided by its count", + policy: { + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "o.mean", value: "sum(map(o.items, #.v)) / len(o.items)"}, + ], + }, + cases: [ + [{o: {items: [{v: 1}, {v: 2}]}}, {o: {items: [{v: 1}, {v: 2}], mean: 1.5}}], + [{o: {items: []}}, {o: {items: [], mean: null}}], + [{o: {items: [{v: 0.1}, {v: 0.2}, {v: 0.3}]}}, {o: {items: [{v: 0.1}, {v: 0.2}, {v: 0.3}], mean: 0.2}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Overflow fails the evaluation (ExpressionFailed); it never wraps or turns into a float. + +{ + name: "addition and multiplication overflow fail the evaluation", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [{expression: "a.sum", value: "a.x + a.y"}], + }, + cases: [ + [{a: {x: 79228162514264337593543950335, y: 0}}, {a: {x: 79228162514264337593543950335, y: 0, sum: 79228162514264337593543950335}}], + [{a: {x: 79228162514264337593543950335, y: 1}}, "!error: ExpressionFailed"], + [{a: {x: -79228162514264337593543950335, y: -1}}, "!error: ExpressionFailed"], + [{a: {x: 79228162514264337593543950335, y: -1}}, {a: {x: 79228162514264337593543950335, y: -1, sum: 79228162514264337593543950334}}], + ], +} + +{ + name: "multiplication overflow", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [{expression: "a.p", value: "a.x * a.y"}], + }, + cases: [ + [{a: {x: 10000000000000000000000000000, y: 7}}, {a: {x: 10000000000000000000000000000, y: 7, p: 70000000000000000000000000000}}], + [{a: {x: 10000000000000000000000000000, y: 8}}, "!error: ExpressionFailed"], + [{a: {x: 0.0000000000000001, y: 0.0000000000000001}}, {a: {x: 0.0000000000000001, y: 0.0000000000000001, p: 0}}], + ], +} + +{ + name: "exponent overflow fails the evaluation", + policy: { + models: {a: {x: "number", y: "number"}}, + blocks: [{expression: "a.p", value: "a.x ^ a.y"}], + }, + cases: [ + [{a: {x: 10, y: 28}}, {a: {x: 10, y: 28, p: 10000000000000000000000000000}}], + [{a: {x: 10, y: 30}}, "!error: ExpressionFailed"], + [{a: {x: 2, y: 10}}, {a: {x: 2, y: 10, p: 1024}}], + [{a: {x: 4, y: 0.5}}, {a: {x: 4, y: 0.5, p: 2.0000000000000000000000000003}}, "question: a fractional exponent is computed approximately, so 4 ^ 0.5 is off by 3e-28 instead of the exact 2"], + [{a: {x: 2, y: -1}}, {a: {x: 2, y: -1, p: 0.5}}], + ], +} + +{ + name: "an overflowing aggregate fails the evaluation", + policy: { + models: {a: {xs: "number[]"}}, + blocks: [ + {expression: "a.total", value: "sum(a.xs)"}, + ], + }, + cases: [ + [{a: {xs: [79228162514264337593543950335, 0]}}, {a: {xs: [79228162514264337593543950335, 0], total: 79228162514264337593543950335}}], + [{a: {xs: [79228162514264337593543950335, 1]}}, "!error: ExpressionFailed"], + [{a: {xs: [50000000000000000000000000000, 50000000000000000000000000000]}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "an overflow in one block fails the evaluation even when other blocks succeed", + policy: { + models: {a: {x: "number"}}, + blocks: [ + {expression: "a.ok", value: "a.x - 1"}, + {expression: "a.big", value: "a.x * 2"}, + ], + }, + cases: [ + [{a: {x: 5}}, {a: {x: 5, ok: 4, big: 10}}], + [{a: {x: 50000000000000000000000000000}}, "!error: ExpressionFailed"], + {input: {a: {x: 50000000000000000000000000000}}, goals: ["a.ok"], output: {a: {x: 50000000000000000000000000000, ok: 49999999999999999999999999999}}}, + ], +} + +{ + name: "an overflowing member fails the evaluation", + policy: { + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [{expression: "item.sq", value: "item.v * item.v"}], + }, + cases: [ + [{o: {items: [{v: 3}, {v: -4}]}}, {o: {items: [{v: 3, sq: 9}, {v: -4, sq: 16}]}}], + [{o: {items: [{v: 3}, {v: 100000000000000000}]}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Rounding in blocks: round half away from zero, on exact decimals (1.005 is exactly 1.005, so +// it rounds up to 1.01). + +{ + name: "rounding functions on exact decimals", + policy: { + models: {a: {x: "number"}}, + blocks: [ + {expression: "a.r", value: "round(a.x)"}, + {expression: "a.r2", value: "round(a.x, 2)"}, + {expression: "a.f", value: "floor(a.x)"}, + {expression: "a.c", value: "ceil(a.x)"}, + {expression: "a.t", value: "trunc(a.x)"}, + ], + }, + cases: [ + [{a: {x: 2.5}}, {a: {x: 2.5, r: 3, r2: 2.5, f: 2, c: 3, t: 2}}], + [{a: {x: -2.5}}, {a: {x: -2.5, r: -3, r2: -2.5, f: -3, c: -2, t: -2}}], + [{a: {x: 1.005}}, {a: {x: 1.005, r: 1, r2: 1.01, f: 1, c: 2, t: 1}}], + [{a: {x: 0.125}}, {a: {x: 0.125, r: 0, r2: 0.13, f: 0, c: 1, t: 0}}], + [{a: {x: -0.125}}, {a: {x: -0.125, r: 0, r2: -0.13, f: -1, c: 0, t: 0}}], + [{a: {x: 7}}, {a: {x: 7, r: 7, r2: 7, f: 7, c: 7, t: 7}}], + ], +} + +{ + name: "round per line vs round the total", + policy: { + models: {invoice: {lines: "invLine[]", rate: "number"}, invLine: {net: "number"}}, + blocks: [ + {expression: "invLine.tax", value: "round(invLine.net * invoice.rate, 2)"}, + {expression: "invoice.taxOfLines", value: "sum(map(invoice.lines, #.tax))"}, + {expression: "invoice.taxOfTotal", value: "round(sum(map(invoice.lines, #.net)) * invoice.rate, 2)"}, + {expression: "invoice.diff", value: "invoice.taxOfLines - invoice.taxOfTotal"}, + ], + }, + cases: [ + [ + {invoice: {rate: 0.19, lines: [{net: 0.05}, {net: 0.05}, {net: 0.05}]}}, + {invoice: {rate: 0.19, lines: [{net: 0.05, tax: 0.01}, {net: 0.05, tax: 0.01}, {net: 0.05, tax: 0.01}], taxOfLines: 0.03, taxOfTotal: 0.03, diff: 0}}, + ], + [ + {invoice: {rate: 0.2, lines: [{net: 0.025}, {net: 0.025}, {net: 0.025}, {net: 0.025}]}}, + {invoice: {rate: 0.2, lines: [{net: 0.025, tax: 0.01}, {net: 0.025, tax: 0.01}, {net: 0.025, tax: 0.01}, {net: 0.025, tax: 0.01}], taxOfLines: 0.04, taxOfTotal: 0.02, diff: 0.02}}, + ], + [ + {invoice: {rate: 0.07, lines: [{net: 9.99}, {net: 0.01}]}}, + {invoice: {rate: 0.07, lines: [{net: 9.99, tax: 0.70}, {net: 0.01, tax: 0}], taxOfLines: 0.7, taxOfTotal: 0.7, diff: 0}}, + ], + ], +} + +{ + name: "a rounded value read by a table and a match", + policy: { + models: {a: {score: "number"}}, + blocks: [ + {expression: "a.rounded", value: "round(a.score)"}, + {table: "dt", inputs: ["a.rounded"], outputs: ["a.grade"], rules: [[">= 90", "'A'"], [">= 80", "'B'"], ["", "'C'"]]}, + {match: "a.passed", arms: [["a.rounded >= 50", "true"], ["", "false"]]}, + ], + }, + cases: [ + [{a: {score: 89.5}}, {a: {score: 89.5, rounded: 90, grade: "A", passed: true}}], + [{a: {score: 89.49}}, {a: {score: 89.49, rounded: 89, grade: "B", passed: true}}], + [{a: {score: 49.5}}, {a: {score: 49.5, rounded: 50, grade: "C", passed: true}}], + [{a: {score: 49.4999}}, {a: {score: 49.4999, rounded: 49, grade: "C", passed: false}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Aggregates over decimals: members, primitive arrays, computed member values. + +{ + name: "sum, avg, min, max and median over decimal members", + policy: { + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "o.sum", value: "sum(map(o.items, #.v))"}, + {expression: "o.avg", value: "avg(map(o.items, #.v))"}, + {expression: "o.min", value: "min(map(o.items, #.v))"}, + {expression: "o.max", value: "max(map(o.items, #.v))"}, + {expression: "o.median", value: "median(map(o.items, #.v))"}, + ], + }, + cases: [ + [{o: {items: [{v: 0.1}, {v: 0.2}, {v: 0.3}]}}, {o: {items: [{v: 0.1}, {v: 0.2}, {v: 0.3}], sum: 0.6, avg: 0.2, min: 0.1, max: 0.3, median: 0.2}}], + [{o: {items: [{v: -1.5}, {v: 1.5}]}}, {o: {items: [{v: -1.5}, {v: 1.5}], sum: 0, avg: 0, min: -1.5, max: 1.5, median: 0}}], + [{o: {items: [{v: 1}, {v: 2}]}}, {o: {items: [{v: 1}, {v: 2}], sum: 3, avg: 1.5, min: 1, max: 2, median: 1.5}}], + [{o: {items: [{v: 1}, {v: 1}, {v: 2}]}}, {o: {items: [{v: 1}, {v: 1}, {v: 2}], sum: 4, avg: 1.3333333333333333333333333333, min: 1, max: 2, median: 1}}], + [{o: {items: [{v: 0.01}]}}, {o: {items: [{v: 0.01}], sum: 0.01, avg: 0.01, min: 0.01, max: 0.01, median: 0.01}}], + ], +} + +{ + name: "ten tenths make exactly one", + policy: { + models: {a: {xs: "number[]"}}, + blocks: [ + {expression: "a.total", value: "sum(a.xs)"}, + {expression: "a.isOne", value: "a.total == 1"}, + {expression: "a.mean", value: "avg(a.xs)"}, + ], + }, + cases: [ + [{a: {xs: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]}}, {a: {xs: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1], total: 1, isOne: true, mean: 0.1}}], + [{a: {xs: [0.3333333333333333333333333333, 0.3333333333333333333333333333, 0.3333333333333333333333333333]}}, {a: {xs: [0.3333333333333333333333333333, 0.3333333333333333333333333333, 0.3333333333333333333333333333], total: 0.9999999999999999999999999999, isOne: false, mean: 0.3333333333333333333333333333}}], + ], +} + +{ + name: "aggregates over computed decimal member values", + policy: { + models: {cart: {lines: "cartLine[]"}, cartLine: {qty: "number", unit: "number"}}, + blocks: [ + {expression: "cartLine.amount", value: "cartLine.qty * cartLine.unit"}, + {expression: "cart.total", value: "sum(map(cart.lines, #.amount))"}, + {expression: "cart.largest", value: "max(map(cart.lines, #.amount))"}, + {expression: "cart.share", value: "map(cart.lines, round(#.amount / cart.total * 100, 1))"}, + ], + }, + cases: [ + [ + {cart: {lines: [{qty: 1, unit: 0.1}, {qty: 2, unit: 0.1}, {qty: 7, unit: 0.1}]}}, + {cart: {lines: [{qty: 1, unit: 0.1, amount: 0.1}, {qty: 2, unit: 0.1, amount: 0.2}, {qty: 7, unit: 0.1, amount: 0.7}], total: 1, largest: 0.7, share: [10, 20, 70]}}, + ], + [ + {cart: {lines: [{qty: 1, unit: 1}, {qty: 1, unit: 2}]}}, + {cart: {lines: [{qty: 1, unit: 1, amount: 1}, {qty: 1, unit: 2, amount: 2}], total: 3, largest: 2, share: [33.3, 66.7]}}, + ], + ], +} + +{ + name: "a member's share of a computed total with a zero total", + policy: { + models: {pool: {parts: "part[]"}, part: {w: "number"}}, + blocks: [ + {expression: "pool.total", value: "sum(map(pool.parts, #.w))"}, + {expression: "part.share", value: "part.w / pool.total"}, + ], + }, + cases: [ + [{pool: {parts: [{w: 1}, {w: 3}]}}, {pool: {parts: [{w: 1, share: 0.25}, {w: 3, share: 0.75}], total: 4}}], + [{pool: {parts: [{w: 0}, {w: 0}]}}, {pool: {parts: [{w: 0, share: null}, {w: 0, share: null}], total: 0}}], + [{pool: {parts: [{w: 1}, {w: -1}]}}, {pool: {parts: [{w: 1, share: null}, {w: -1, share: null}], total: 0}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Numbers in tables: equality cells compare by value, ranges, comparison cells and comma lists +// (the numeric "enum" of a table), with decimals and negatives. + +{ + name: "numeric table cells: equality, ranges, lists and comparisons", + policy: { + models: {a: {x: "number"}}, + blocks: [ + {table: "dt", inputs: ["a.x"], outputs: ["a.band"], rules: [ + ["1", "'one'"], + ["[2..5]", "'2-5'"], + ["(5..10)", "'5-10 open'"], + ["10, 20, 30", "'tens'"], + ["< 0", "'negative'"], + ["0.5", "'half'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{a: {x: 1.0}}, {a: {x: 1.0, band: "one"}}], + [{a: {x: 1.00}}, {a: {x: 1.00, band: "one"}}], + [{a: {x: 2}}, {a: {x: 2, band: "2-5"}}], + [{a: {x: 5}}, {a: {x: 5, band: "2-5"}}], + [{a: {x: 5.0001}}, {a: {x: 5.0001, band: "5-10 open"}}], + [{a: {x: 9.99999}}, {a: {x: 9.99999, band: "5-10 open"}}], + [{a: {x: 10}}, {a: {x: 10, band: "tens"}}], + [{a: {x: 20.0}}, {a: {x: 20.0, band: "tens"}}], + [{a: {x: -0.0001}}, {a: {x: -0.0001, band: "negative"}}], + [{a: {x: 0.50}}, {a: {x: 0.50, band: "half"}}], + [{a: {x: 0}}, {a: {x: 0, band: "other"}}], + [{a: {x: 1.5}}, {a: {x: 1.5, band: "other"}}], + ], +} + +{ + name: "decimal boundaries between table rows", + policy: { + models: {loan: {ltv: "number"}}, + blocks: [ + {table: "dt", inputs: ["loan.ltv"], outputs: ["loan.rate"], rules: [ + ["<= 0.6", "0.031"], + ["(0.6..0.8]", "0.0345"], + ["(0.8..0.95]", "0.042"], + ["", "0.055"], + ]}, + {expression: "loan.ratePct", value: "loan.rate * 100"}, + ], + }, + cases: [ + [{loan: {ltv: 0.6}}, {loan: {ltv: 0.6, rate: 0.031, ratePct: 3.1}}], + [{loan: {ltv: 0.6000000001}}, {loan: {ltv: 0.6000000001, rate: 0.0345, ratePct: 3.45}}], + [{loan: {ltv: 0.8}}, {loan: {ltv: 0.8, rate: 0.0345, ratePct: 3.45}}], + [{loan: {ltv: 0.95}}, {loan: {ltv: 0.95, rate: 0.042, ratePct: 4.2}}], + [{loan: {ltv: 0.9500001}}, {loan: {ltv: 0.9500001, rate: 0.055, ratePct: 5.5}}], + [{loan: {ltv: 0}}, {loan: {ltv: 0, rate: 0.031, ratePct: 3.1}}], + ], +} + +{ + name: "numeric output cells are exact decimals", + policy: { + models: {a: {tier: "string(a|b|c)"}}, + blocks: [ + {table: "dt", inputs: ["a.tier"], outputs: ["a.factor", "a.fee"], rules: [ + ["'a'", "1.10", "0.333"], + ["'b'", "0.9", "-0.01"], + ["", "1 / 3", "0.1 * 3"], + ]}, + {expression: "a.check", value: "a.factor * 3"}, + ], + }, + cases: [ + [{a: {tier: "a"}}, {a: {tier: "a", factor: 1.1, fee: 0.333, check: 3.3}}], + [{a: {tier: "b"}}, {a: {tier: "b", factor: 0.9, fee: -0.01, check: 2.7}}], + [{a: {tier: "c"}}, {a: {tier: "c", factor: 0.3333333333333333333333333333, fee: 0.3, check: 0.9999999999999999999999999999}}], + ], +} + +{ + name: "a table over a computed decimal column", + policy: { + models: {a: {income: "number", debt: "number"}}, + blocks: [ + {expression: "a.dti", value: "a.debt / a.income"}, + {table: "dt", inputs: ["a.dti"], outputs: ["a.decision"], rules: [ + ["null", "'no income'"], + ["<= 0.36", "'approve'"], + ["(0.36..0.43]", "'review'"], + ["", "'decline'"], + ]}, + ], + }, + cases: [ + [{a: {income: 1000, debt: 360}}, {a: {income: 1000, debt: 360, dti: 0.36, decision: "approve"}}], + [{a: {income: 3, debt: 1.08}}, {a: {income: 3, debt: 1.08, dti: 0.36, decision: "approve"}}], + [{a: {income: 1000, debt: 430}}, {a: {income: 1000, debt: 430, dti: 0.43, decision: "review"}}], + [{a: {income: 1000, debt: 430.01}}, {a: {income: 1000, debt: 430.01, dti: 0.43001, decision: "decline"}}], + [{a: {income: 0, debt: 10}}, {a: {income: 0, debt: 10, dti: null, decision: "no income"}}], + ], +} + +{ + name: "a collect table over numeric thresholds", + policy: { + models: {a: {amount: "number"}}, + blocks: [ + {table: "dt", hit: "collect", inputs: ["a.amount"], outputs: ["a.flags"], rules: [ + [">= 1000", "'large'"], + [">= 9999.99", "'report'"], + ["< 0", "'refund'"], + ["0.01, 0.02", "'micro'"], + ]}, + ], + }, + cases: [ + [{a: {amount: 9999.99}}, {a: {amount: 9999.99, flags: ["large", "report"]}}], + [{a: {amount: 9999.98}}, {a: {amount: 9999.98, flags: ["large"]}}], + [{a: {amount: -5}}, {a: {amount: -5, flags: ["refund"]}}], + [{a: {amount: 0.020}}, {a: {amount: 0.020, flags: ["micro"]}}], + [{a: {amount: 0}}, {a: {amount: 0, flags: []}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// Numeric codes in matches: equality, membership lists and intervals. Enum types are strings +// only, so a numeric code set is written as a list or an interval in the condition. + +{ + name: "numeric codes in match conditions", + policy: { + models: {a: {code: "number"}}, + blocks: [ + {match: "a.kind", arms: [ + ["a.code in [1, 2, 3]", "'low'"], + ["a.code in [10..20]", "'mid'"], + ["a.code == 99.0", "'special'"], + ["", "'other'"], + ]}, + ], + }, + cases: [ + [{a: {code: 1}}, {a: {code: 1, kind: "low"}}], + [{a: {code: 3.0}}, {a: {code: 3.0, kind: "low"}}], + [{a: {code: 15.5}}, {a: {code: 15.5, kind: "mid"}}], + [{a: {code: 20}}, {a: {code: 20, kind: "mid"}}], + [{a: {code: 99}}, {a: {code: 99, kind: "special"}}], + [{a: {code: 4}}, {a: {code: 4, kind: "other"}}], + [{a: {code: 2.5}}, {a: {code: 2.5, kind: "other"}}], + ], +} + +{ + name: "a numeric-looking enum is matched as a string", + policy: { + models: {a: {level: "string(1|2|3)"}}, + blocks: [ + {match: "a.n", arms: [["a.level == '1'", "1"], ["a.level == '2'", "2"], ["", "3"]]}, + {expression: "a.asNumber", value: "number(a.level) * 10"}, + ], + }, + cases: [ + [{a: {level: "1"}}, {a: {level: "1", n: 1, asNumber: 10}}], + [{a: {level: "3"}}, {a: {level: "3", n: 3, asNumber: 30}}], + [{a: {level: 1}}, "!error: InputValidationFailed"], + [{a: {level: "1.0"}}, "!error: InputValidationFailed"], + ], +} + +{ + name: "per-member numeric codes in a table", + policy: { + models: {claim: {items: "claimItem[]"}, claimItem: {code: "number", amount: "number"}}, + blocks: [ + {table: "dt", inputs: ["claimItem.code"], outputs: ["claimItem.covered"], rules: [ + ["100, 101, 102", "1"], + ["[200..299]", "0.8"], + ["", "0"], + ]}, + {expression: "claimItem.paid", value: "claimItem.amount * claimItem.covered"}, + {expression: "claim.paid", value: "sum(map(claim.items, #.paid))"}, + ], + }, + cases: [ + [ + {claim: {items: [{code: 100, amount: 50.5}, {code: 250, amount: 100.05}, {code: 300, amount: 10}]}}, + {claim: {items: [{code: 100, amount: 50.5, covered: 1, paid: 50.5}, {code: 250, amount: 100.05, covered: 0.8, paid: 80.04}, {code: 300, amount: 10, covered: 0, paid: 0}], paid: 130.54}}, + ], + [{claim: {items: []}}, {claim: {items: [], paid: 0}}], + [ + {claim: {items: [{code: 299.5, amount: 1}, {code: 200.0, amount: 2}]}}, + {claim: {items: [{code: 299.5, amount: 1, covered: 0, paid: 0}, {code: 200.0, amount: 2, covered: 0.8, paid: 1.6}], paid: 1.6}}, + ], + ], +} + +// --------------------------------------------------------------------------------------------- +// Numbers and strings: conversion keeps the decimal scale; parsing failures fail the evaluation. + +{ + name: "number to string keeps the scale, string to number parses exactly", + policy: { + models: {a: {x: "number", s: "string"}}, + blocks: [ + {expression: "a.text", value: "string(a.x)"}, + {expression: "a.parsed", value: "number(a.s)"}, + {expression: "a.sum", value: "a.x + a.parsed"}, + ], + }, + cases: [ + [{a: {x: 1.50, s: "0.25"}}, {a: {x: 1.50, s: "0.25", text: "1.50", parsed: 0.25, sum: 1.75}}], + [{a: {x: 0.000, s: "-3"}}, {a: {x: 0.000, s: "-3", text: "0.000", parsed: -3, sum: -3}}], + [{a: {x: 10, s: "0.1000"}}, {a: {x: 10, s: "0.1000", text: "10", parsed: 0.1, sum: 10.1}}], + [{a: {x: 1, s: "1,5"}}, "!error: ExpressionFailed"], + [{a: {x: 1, s: ""}}, "!error: ExpressionFailed"], + ], +} + +// --------------------------------------------------------------------------------------------- +// A realistic chain: progressive tax brackets over a decimal income. + +{ + name: "progressive tax with decimal brackets", + policy: { + globals: {env: {brackets: "taxBracket[]"}}, + models: {person: {income: "number"}, taxBracket: {from: "number", to: "number?", rate: "number"}}, + blocks: [ + {expression: "taxBracket.taxable", value: "max([0, min([person.income, taxBracket.to ?? person.income]) - taxBracket.from])"}, + {expression: "taxBracket.tax", value: "taxBracket.taxable * taxBracket.rate"}, + {expression: "person.tax", value: "round(sum(map(brackets, #.tax)), 2)"}, + {expression: "person.effective", value: "person.income > 0 ? round(person.tax / person.income, 4) : 0"}, + ], + }, + cases: [ + [ + {person: {income: 50000}, brackets: [{from: 0, to: 10000, rate: 0}, {from: 10000, to: 40000, rate: 0.2}, {from: 40000, rate: 0.4}]}, + {person: {income: 50000, tax: 10000, effective: 0.2}, brackets: [{from: 0, to: 10000, rate: 0, taxable: 10000, tax: 0}, {from: 10000, to: 40000, rate: 0.2, taxable: 30000, tax: 6000}, {from: 40000, rate: 0.4, taxable: 10000, tax: 4000}]}, + ], + [ + {person: {income: 12345.67}, brackets: [{from: 0, to: 10000, rate: 0}, {from: 10000, to: 40000, rate: 0.2}, {from: 40000, rate: 0.4}]}, + {person: {income: 12345.67, tax: 469.13, effective: 0.038}, brackets: [{from: 0, to: 10000, rate: 0, taxable: 10000, tax: 0}, {from: 10000, to: 40000, rate: 0.2, taxable: 2345.67, tax: 469.134}, {from: 40000, rate: 0.4, taxable: 0, tax: 0}]}, + ], + [ + {person: {income: 0}, brackets: [{from: 0, to: 10000, rate: 0.1}]}, + {person: {income: 0, tax: 0, effective: 0}, brackets: [{from: 0, to: 10000, rate: 0.1, taxable: 0, tax: 0}]}, + ], + ], +} diff --git a/core/engine/tests/spec/policy/40-references-and-globals-advanced.json5 b/core/engine/tests/spec/policy/40-references-and-globals-advanced.json5 new file mode 100644 index 00000000..57d20f73 --- /dev/null +++ b/core/engine/tests/spec/policy/40-references-and-globals-advanced.json5 @@ -0,0 +1,674 @@ +// References and globals, advanced. Chapter 10 pins reference resolution and validation, +// chapter 11 globals, chapter 23 member blocks reading globals. This chapter combines them: +// computed properties on reference pools (every pool item is a member, referenced or not), pools +// read by blocks that also read globals, references inside members and inside globals, global +// relationships whose entities carry computed properties, and member blocks that read computed +// globals and global relationships, in both directions. + +// --------------------------------------------------------------------------------------------- +// Computed properties on a pool. A block keyed on a referenced entity runs once per pool item; +// resolved references are copies of the pool items, so they carry the computed values too. + +{ + name: "a pool computed reading a global runs for every pool item", + policy: { + globals: {env: {markup: "number"}}, + models: {cart: {item: "&product"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "product.gross", value: "product.price * markup"}, + {expression: "cart.price", value: "cart.item.price * 2"}, + ], + }, + cases: [ + [ + {markup: 2, cart: {item: "p1"}, product: [{id: "p1", price: 5}, {id: "p2", price: 1}]}, + {markup: 2, cart: {item: {id: "p1", price: 5, gross: 10}, price: 10}, product: [{id: "p1", price: 5, gross: 10}, {id: "p2", price: 1, gross: 2}]}, + ], + [ + {markup: 1.5, cart: {item: "p2"}, product: [{id: "p1", price: 5}, {id: "p2", price: 1}]}, + {markup: 1.5, cart: {item: {id: "p2", price: 1, gross: 1.5}, price: 2}, product: [{id: "p1", price: 5, gross: 7.5}, {id: "p2", price: 1, gross: 1.5}]}, + ], + [{cart: {item: "p1"}, product: [{id: "p1", price: 5}]}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "a pool table runs for every pool item, and resolved arrays carry its output", + policy: { + models: {cart: {items: "&product[]"}, product: {id: "string", price: "number"}}, + blocks: [ + {table: "dt", inputs: ["product.price"], outputs: ["product.band"], rules: [["> 3", "'hi'"], ["", "'lo'"]]}, + {expression: "cart.ids", value: "map(cart.items, #.id)"}, + ], + }, + cases: [ + [ + {cart: {items: ["p2"]}, product: [{id: "p1", price: 5}, {id: "p2", price: 1}]}, + {cart: {items: [{id: "p2", price: 1, band: "lo"}], ids: ["p2"]}, product: [{id: "p1", price: 5, band: "hi"}, {id: "p2", price: 1, band: "lo"}]}, + ], + [ + {cart: {items: ["p1", "p2", "p1"]}, product: [{id: "p1", price: 5}, {id: "p2", price: 1}]}, + {cart: {items: [{id: "p1", price: 5, band: "hi"}, {id: "p2", price: 1, band: "lo"}, {id: "p1", price: 5, band: "hi"}], ids: ["p1", "p2", "p1"]}, product: [{id: "p1", price: 5, band: "hi"}, {id: "p2", price: 1, band: "lo"}]}, + ], + [{cart: {items: []}, product: []}, {cart: {items: [], ids: []}, product: []}], + ], +} + +{ + name: "a pool match reading a global", + policy: { + globals: {env: {cap: "number"}}, + models: {cart: {items: "&product[]"}, product: {id: "string", price: "number"}}, + blocks: [ + {match: "product.capped", arms: [["product.price > cap", "cap"], ["", "product.price"]]}, + {expression: "cart.n", value: "len(cart.items)"}, + ], + }, + cases: [ + [ + {cap: 3, cart: {items: ["p1"]}, product: [{id: "p1", price: 5}, {id: "p2", price: 1}]}, + {cap: 3, cart: {items: [{id: "p1", price: 5, capped: 3}], n: 1}, product: [{id: "p1", price: 5, capped: 3}, {id: "p2", price: 1, capped: 1}]}, + ], + [{cap: 3, cart: {items: []}, product: [{id: "p1", price: 3}]}, {cap: 3, cart: {items: [], n: 0}, product: [{id: "p1", price: 3, capped: 3}]}], + [{cart: {items: []}, product: [{id: "p1", price: 5}]}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "nested computed paths on pool items", + policy: { + models: {cart: {items: "&product[]"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "product.calc.gross", value: "product.price * 2"}, + {expression: "product.calc.net", value: "product.price"}, + ], + }, + cases: [ + [ + {cart: {items: ["p1"]}, product: [{id: "p1", price: 5}]}, + {cart: {items: [{id: "p1", price: 5, calc: {gross: 10, net: 5}}]}, product: [{id: "p1", price: 5, calc: {gross: 10, net: 5}}]}, + ], + [ + {cart: {items: []}, product: [{id: "p1", price: 0.5}, {id: "p2", price: 0}]}, + {cart: {items: []}, product: [{id: "p1", price: 0.5, calc: {gross: 1, net: 0.5}}, {id: "p2", price: 0, calc: {gross: 0, net: 0}}]}, + ], + ], +} + +{ + name: "a pool computed and a root computed read the same global computed", + policy: { + globals: {env: {base: "number"}}, + models: {shop: {lines: "shopLine[]", fav: "&product?"}, shopLine: {q: "number"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "unit", value: "base * 10"}, + {expression: "shopLine.cost", value: "shopLine.q * unit"}, + {expression: "product.units", value: "product.price / unit"}, + ], + }, + cases: [ + [ + {base: 1, shop: {lines: [{q: 2}], fav: "p1"}, product: [{id: "p1", price: 50}]}, + {base: 1, unit: 10, shop: {lines: [{q: 2, cost: 20}], fav: {id: "p1", price: 50, units: 5}}, product: [{id: "p1", price: 50, units: 5}]}, + ], + [ + {base: 0.5, shop: {lines: [{q: 1}, {q: 3}]}, product: [{id: "p1", price: 50}]}, + {base: 0.5, unit: 5, shop: {lines: [{q: 1, cost: 5}, {q: 3, cost: 15}]}, product: [{id: "p1", price: 50, units: 10}]}, + ], + [ + {base: 0, shop: {lines: []}, product: [{id: "p1", price: 50}]}, + {base: 0, unit: 0, shop: {lines: []}, product: [{id: "p1", price: 50, units: null}]}, + ], + ], +} + +// An absent pool when blocks are keyed on its entity: the pool members' reads become required +// inputs. An empty pool is fine; a null item in the pool is evaluated like a member (chapter 09). + +{ + name: "an absent pool with per-item blocks", + policy: { + models: {cart: {items: "&product[]"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "product.gross", value: "product.price * 2"}, + {expression: "cart.n", value: "len(cart.items)"}, + ], + }, + cases: [ + [{cart: {items: []}}, {cart: {items: [], n: 0}}, "bug: no pool means no pool items, yet product.price is required (MissingRequiredInputs); the pool is not a declared input, and an empty pool runs fine"], + [{cart: {items: []}, product: []}, {cart: {items: [], n: 0}, product: []}], + [{cart: {items: []}, product: null}, {cart: {items: [], n: 0}, product: null}, "bug: a null pool is treated as missing and product.price is required"], + [{cart: {items: []}, product: [null]}, "!error: ExpressionFailed", "question: the null pool item passes validation but the per-item block still runs on it and fails on null * 2, as with null relationship members (chapter 09)"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Reading pool computed values back through references. + +{ + name: "a global reference reading a pool computed value", + diagnostics: ["UNDEFINED_VARIABLE"], + policy: { + globals: {env: {plan: "&product"}}, + models: {product: {id: "string", price: "number"}}, + blocks: [ + {expression: "product.gross", value: "product.price * 2"}, + {expression: "planGross", value: "plan.gross"}, + ], + }, + cases: [ + [ + {plan: "p1", product: [{id: "p1", price: 5}]}, + {plan: {id: "p1", price: 5, gross: 10}, planGross: 10, product: [{id: "p1", price: 5, gross: 10}]}, + "bug: plan.gross is a computed property of the referenced entity, but the type checker reports UNDEFINED_VARIABLE for the read through a global reference (through a root reference it type-checks, chapter 10)", + ], + ], +} + +{ + name: "a global reference's computed target without reading it back", + policy: { + globals: {env: {plan: "&product"}}, + models: {product: {id: "string", price: "number"}}, + blocks: [ + {expression: "product.gross", value: "product.price * 2"}, + {expression: "planPrice", value: "plan.price"}, + ], + }, + cases: [ + [ + {plan: "p1", product: [{id: "p1", price: 5}]}, + {plan: {id: "p1", price: 5, gross: 10}, planPrice: 5, product: [{id: "p1", price: 5, gross: 10}]}, + ], + [ + {plan: "p2", product: [{id: "p1", price: 5}, {id: "p2", price: 0.1}]}, + {plan: {id: "p2", price: 0.1, gross: 0.2}, planPrice: 0.1, product: [{id: "p1", price: 5, gross: 10}, {id: "p2", price: 0.1, gross: 0.2}]}, + ], + ], +} + +{ + name: "a reference whose target has a relationship", + policy: { + models: {cart: {item: "&product"}, product: {id: "string", vendor: "vendor"}, vendor: {name: "string", rating: "number?"}}, + blocks: [ + {expression: "cart.vendor", value: "cart.item.vendor.name"}, + {expression: "cart.rating", value: "cart.item.vendor.rating ?? 0"}, + ], + }, + cases: [ + [ + {cart: {item: "p1"}, product: [{id: "p1", vendor: {name: "V", rating: 4}}]}, + {cart: {item: {id: "p1", vendor: {name: "V", rating: 4}}, vendor: "V", rating: 4}, product: [{id: "p1", vendor: {name: "V", rating: 4}}]}, + ], + [ + {cart: {item: "p2"}, product: [{id: "p1", vendor: {name: "V"}}, {id: "p2", vendor: {name: "W"}}]}, + {cart: {item: {id: "p2", vendor: {name: "W"}}, vendor: "W", rating: 0}, product: [{id: "p1", vendor: {name: "V"}}, {id: "p2", vendor: {name: "W"}}]}, + ], + [{cart: {item: "p1"}, product: [{id: "p1", vendor: {name: 5}}]}, "!error: product[0].vendor.name"], + ], +} + +{ + name: "two pools resolved side by side", + policy: { + models: {order: {product: "&product", shop: "&shop"}, product: {id: "string", price: "number"}, shop: {id: "string", fee: "number"}}, + blocks: [{expression: "order.total", value: "order.product.price + order.shop.fee"}], + }, + cases: [ + [ + {order: {product: "p", shop: "s"}, product: [{id: "p", price: 5}], shop: [{id: "s", fee: 1}]}, + {order: {product: {id: "p", price: 5}, shop: {id: "s", fee: 1}, total: 6}, product: [{id: "p", price: 5}], shop: [{id: "s", fee: 1}]}, + ], + [ + {order: {product: "x", shop: "x"}, product: [{id: "x", price: 5}], shop: [{id: "x", fee: 0.5}]}, + {order: {product: {id: "x", price: 5}, shop: {id: "x", fee: 0.5}, total: 5.5}, product: [{id: "x", price: 5}], shop: [{id: "x", fee: 0.5}]}, + ], + [{order: {product: "s", shop: "p"}, product: [{id: "p", price: 5}], shop: [{id: "s", fee: 1}]}, "!error: order.product"], + [{order: {product: "s", shop: "p"}, product: [{id: "p", price: 5}], shop: [{id: "s", fee: 1}]}, "!error: order.shop"], + ], +} + +// --------------------------------------------------------------------------------------------- +// References inside members: validated against the root pool but not resolved (chapter 10), so a +// member sees the id string. + +{ + name: "an optional member reference checked for presence", + policy: { + models: {order: {lines: "orderLine[]"}, orderLine: {sku: "&product?"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "orderLine.has", value: "orderLine.sku != null"}, + {expression: "order.linked", value: "count(order.lines, #.has)"}, + ], + }, + cases: [ + [ + {order: {lines: [{sku: "p1"}, {}]}, product: [{id: "p1", price: 5}]}, + {order: {lines: [{sku: {id: "p1", price: 5}, has: true}, {has: false}], linked: 1}, product: [{id: "p1", price: 5}]}, + "bug: member references are not hydrated, so lines[0].sku stays \"p1\"", + ], + [{order: {lines: [{sku: null}]}}, {order: {lines: [{sku: null, has: false}], linked: 0}}], + [{order: {lines: [{sku: "p9"}]}, product: [{id: "p1", price: 5}]}, "!error: order.lines[0].sku"], + ], +} + +{ + name: "a member reference read for a price", + policy: { + models: {order: {lines: "orderLine[]"}, orderLine: {qty: "number", sku: "&product"}, product: {id: "string", price: "number"}}, + blocks: [ + {expression: "orderLine.amount", value: "orderLine.qty * (orderLine.sku.price ?? 0)"}, + {expression: "order.total", value: "sum(map(order.lines, #.amount))"}, + ], + }, + cases: [ + [ + {order: {lines: [{qty: 2, sku: "p1"}]}, product: [{id: "p1", price: 5}]}, + {order: {lines: [{qty: 2, sku: {id: "p1", price: 5}, amount: 10}], total: 10}, product: [{id: "p1", price: 5}]}, + "bug: member references are not hydrated; sku.price reads null, so amount is 0", + ], + [{order: {lines: []}}, {order: {lines: [], total: 0}}], + ], +} + +{ + name: "a member reference array is validated item by item", + policy: { + models: {order: {lines: "orderLine[]"}, orderLine: {skus: "&product[]?"}, product: {id: "string"}}, + blocks: [{expression: "orderLine.n", value: "len(orderLine.skus ?? [])"}], + }, + cases: [ + [{order: {lines: [{skus: ["a", "b"]}, {}]}, product: [{id: "a"}, {id: "b"}]}, {order: {lines: [{skus: [{id: "a"}, {id: "b"}], n: 2}, {n: 0}]}, product: [{id: "a"}, {id: "b"}]}, "bug: member reference arrays are not hydrated and stay id lists"], + [{order: {lines: [{skus: ["a", "z"]}]}, product: [{id: "a"}]}, "!error: order.lines[0].skus[1]"], + [{order: {lines: [{skus: []}]}}, {order: {lines: [{skus: [], n: 0}]}}], + ], +} + +// --------------------------------------------------------------------------------------------- +// References in globals. + +{ + name: "a global reference array", + policy: { + globals: {env: {picks: "&product[]"}}, + models: {product: {id: "string", price: "number"}}, + blocks: [ + {expression: "total", value: "sum(map(picks, #.price))"}, + {expression: "cheapest", value: "min(map(picks, #.price))"}, + ], + }, + cases: [ + [ + {picks: ["a", "b", "a"], product: [{id: "a", price: 1}, {id: "b", price: 2}]}, + {picks: [{id: "a", price: 1}, {id: "b", price: 2}, {id: "a", price: 1}], total: 4, cheapest: 1, product: [{id: "a", price: 1}, {id: "b", price: 2}]}, + ], + [{picks: ["b"], product: [{id: "a", price: 1}, {id: "b", price: 2}]}, {picks: [{id: "b", price: 2}], total: 2, cheapest: 2, product: [{id: "a", price: 1}, {id: "b", price: 2}]}], + [{picks: [], product: []}, "!error: ExpressionFailed"], + [{picks: ["c"], product: [{id: "a", price: 1}]}, "!error: picks[0]"], + ], +} + +{ + name: "an optional global reference with goals", + policy: { + globals: {env: {plan: "&product?"}}, + models: {product: {id: "string", price: "number"}}, + blocks: [ + {expression: "price", value: "plan.price ?? 0"}, + {expression: "version", value: "1"}, + ], + }, + cases: [ + {input: {}, goals: ["price"], output: {price: 0}}, + {input: {plan: "p1", product: [{id: "p1", price: 5}]}, goals: ["price"], output: {plan: {id: "p1", price: 5}, price: 5, product: [{id: "p1", price: 5}]}}, + {input: {plan: "zz", product: [{id: "p1", price: 5}]}, goals: ["version"], output: "!error: InputValidationFailed"}, + {input: {plan: null}, output: {plan: null, price: 0, version: 1}}, + ], +} + +{ + name: "a global reference and a root reference to the same pool", + policy: { + globals: {env: {defaultPlan: "&plan"}}, + models: {customer: {plan: "&plan?"}, plan: {id: "string", fee: "number"}}, + blocks: [ + {expression: "customer.fee", value: "customer.plan.fee ?? defaultPlan.fee"}, + ], + }, + cases: [ + [ + {defaultPlan: "basic", customer: {}, plan: [{id: "basic", fee: 5}, {id: "pro", fee: 20}]}, + {defaultPlan: {id: "basic", fee: 5}, customer: {fee: 5}, plan: [{id: "basic", fee: 5}, {id: "pro", fee: 20}]}, + ], + [ + {defaultPlan: "basic", customer: {plan: "pro"}, plan: [{id: "basic", fee: 5}, {id: "pro", fee: 20}]}, + {defaultPlan: {id: "basic", fee: 5}, customer: {plan: {id: "pro", fee: 20}, fee: 20}, plan: [{id: "basic", fee: 5}, {id: "pro", fee: 20}]}, + ], + [{defaultPlan: "gold", customer: {}, plan: [{id: "basic", fee: 5}]}, "!error: defaultPlan"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Global relationships with computed properties. + +{ + name: "a global single relationship with a computed property read at the top level", + policy: { + globals: {env: {cfg: "config"}}, + models: {config: {base: "number", mode: "string(lin|sq)"}}, + blocks: [ + {match: "config.factor", arms: [["config.mode == 'sq'", "config.base * config.base"], ["", "config.base"]]}, + {expression: "factor", value: "cfg.factor + 1"}, + ], + }, + cases: [ + [{cfg: {base: 3, mode: "lin"}}, {cfg: {base: 3, mode: "lin", factor: 3}, factor: 4}], + [{cfg: {base: 3, mode: "sq"}}, {cfg: {base: 3, mode: "sq", factor: 9}, factor: 10}], + [{cfg: {base: 3}}, "!error: MissingRequiredInputs"], + [{}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "an optional global relationship absent or null", + policy: { + globals: {env: {cfg: "config?"}}, + models: {config: {base: "number"}}, + blocks: [ + {expression: "config.double", value: "config.base * 2"}, + {expression: "d", value: "cfg.double ?? 0"}, + ], + }, + cases: [ + [{}, {d: 0}], + [{cfg: null}, {cfg: null, d: 0}], + [{cfg: {base: 3}}, {cfg: {base: 3, double: 6}, d: 6}], + [{cfg: {base: "3"}}, "!error: cfg.base"], + ], +} + +{ + name: "a global array relationship with per-member table and match", + policy: { + globals: {env: {bands: "band[]"}}, + models: {band: {from: "number", rate: "number"}, person: {income: "number"}}, + blocks: [ + {table: "dt", inputs: ["band.rate"], outputs: ["band.kind"], rules: [["0", "'free'"], ["< 0.3", "'low'"], ["", "'high'"]]}, + {match: "band.applies", arms: [["person.income >= band.from", "true"], ["", "false"]]}, + {expression: "person.kinds", value: "map(filter(bands, #.applies), #.kind)"}, + ], + }, + cases: [ + [ + {bands: [{from: 0, rate: 0}, {from: 100, rate: 0.2}, {from: 1000, rate: 0.4}], person: {income: 500}}, + {bands: [{from: 0, rate: 0, kind: "free", applies: true}, {from: 100, rate: 0.2, kind: "low", applies: true}, {from: 1000, rate: 0.4, kind: "high", applies: false}], person: {income: 500, kinds: ["free", "low"]}}, + ], + [ + {bands: [], person: {income: 500}}, + {bands: [], person: {income: 500, kinds: []}}, + ], + [ + {bands: [{from: 0, rate: 0.5}], person: {income: 0}}, + {bands: [{from: 0, rate: 0.5, kind: "high", applies: true}], person: {income: 0, kinds: ["high"]}}, + ], + ], +} + +{ + name: "global array members read a root computed value", + policy: { + globals: {env: {checks: "check[]"}}, + models: {check: {min: "number"}, app: {score: "number"}}, + blocks: [ + {expression: "app.adjusted", value: "app.score + 10"}, + {expression: "check.passes", value: "app.adjusted >= check.min"}, + {expression: "app.passed", value: "all(checks, #.passes)"}, + ], + }, + cases: [ + [{checks: [{min: 5}, {min: 50}], app: {score: 45}}, {checks: [{min: 5, passes: true}, {min: 50, passes: true}], app: {score: 45, adjusted: 55, passed: true}}], + [{checks: [{min: 5}, {min: 60}], app: {score: 45}}, {checks: [{min: 5, passes: true}, {min: 60, passes: false}], app: {score: 45, adjusted: 55, passed: false}}], + [{checks: [], app: {score: 1}}, {checks: [], app: {score: 1, adjusted: 11, passed: true}}], + ], +} + +{ + name: "a global relationship read by a root block and vice versa", + policy: { + globals: {env: {caps: "limits"}}, + models: {limits: {max: "number"}, order: {total: "number"}}, + blocks: [ + {expression: "limits.headroom", value: "limits.max - order.total"}, + {expression: "order.allowed", value: "caps.headroom >= 0"}, + ], + }, + cases: [ + [{caps: {max: 100}, order: {total: 40}}, {caps: {max: 100, headroom: 60}, order: {total: 40, allowed: true}}], + [{caps: {max: 100}, order: {total: 140}}, {caps: {max: 100, headroom: -40}, order: {total: 140, allowed: false}}], + [{caps: {max: 100}, order: {total: 100}}, {caps: {max: 100, headroom: 0}, order: {total: 100, allowed: true}}], + ], +} + +{ + name: "goals on a global relationship's computed property", + policy: { + globals: {env: {cfg: "config"}}, + models: {config: {base: "number"}, order: {net: "number"}}, + blocks: [ + {expression: "config.rate", value: "config.base / 100"}, + {expression: "order.gross", value: "order.net * (1 + cfg.rate)"}, + {expression: "order.label", value: "'order'"}, + ], + }, + cases: [ + {input: {cfg: {base: 20}, order: {net: 10}}, goals: ["config.rate"], output: {cfg: {base: 20, rate: 0.2}, order: {net: 10}}}, + {input: {cfg: {base: 20}, order: {net: 10}}, goals: ["order.gross"], output: {cfg: {base: 20, rate: 0.2}, order: {net: 10, gross: 12}}}, + {input: {order: {net: 10}}, goals: ["order.label"], output: {order: {net: 10, label: "order"}}}, + {input: {order: {net: 10}}, goals: ["order.gross"], output: "!error: MissingRequiredInputs"}, + ], +} + +{ + name: "a global relationship writing below a nested relationship is refused", + diagnostics: ["UNSUPPORTED_NESTED_ITERATION"], + policy: { + globals: {env: {firms: "firm[]"}}, + models: {firm: {staff: "worker[]"}, worker: {salary: "number"}}, + blocks: [{expression: "worker.annual", value: "worker.salary * 12"}], + }, + cases: [ + [ + {firms: [{staff: [{salary: 1}]}]}, + "!error: MissingRequiredInputs", + "question: per-member writes two relationships deep are refused (UNSUPPORTED_NESTED_ITERATION, chapter 21) for globals too; through the workspace the second level is not a source, so worker.salary is reported missing although every worker has it", + ], + ], +} + +{ + name: "aggregating a global relationship's nested members without writing them", + policy: { + globals: {env: {company: "firm"}}, + models: {firm: {staff: "worker[]"}, worker: {salary: "number"}}, + blocks: [ + {expression: "firm.payroll", value: "sum(map(firm.staff, #.salary))"}, + {expression: "payroll", value: "company.payroll * 12"}, + ], + }, + cases: [ + [{company: {staff: [{salary: 1}, {salary: 2}]}}, {company: {staff: [{salary: 1}, {salary: 2}], payroll: 3}, payroll: 36}], + [{company: {staff: []}}, {company: {staff: [], payroll: 0}, payroll: 0}], + [{company: {staff: [{salary: "1"}]}}, "!error: company.staff[0].salary"], + ], +} + +// --------------------------------------------------------------------------------------------- +// Globals read by member blocks. + +{ + name: "member blocks read a computed global in an expression, a table input and a match", + policy: { + globals: {env: {rate: "number"}}, + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "factor", value: "rate * 2"}, + {expression: "item.w", value: "item.v * factor"}, + {table: "dt", inputs: ["item.v * factor"], outputs: ["item.big"], rules: [["> 10", "true"], ["", "false"]]}, + {match: "item.tier", arms: [["item.v >= factor", "'up'"], ["", "'down'"]]}, + ], + }, + cases: [ + [ + {rate: 1, o: {items: [{v: 1}, {v: 6}]}}, + {rate: 1, factor: 2, o: {items: [{v: 1, w: 2, big: false, tier: "down"}, {v: 6, w: 12, big: true, tier: "up"}]}}, + ], + [{rate: 0.5, o: {items: [{v: 1}]}}, {rate: 0.5, factor: 1, o: {items: [{v: 1, w: 1, big: false, tier: "up"}]}}], + [{rate: 1, o: {items: []}}, {rate: 1, factor: 2, o: {items: []}}], + ], +} + +{ + name: "member blocks read a global relationship's computed property", + policy: { + globals: {env: {cfg: "config"}}, + models: {config: {base: "number"}, o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "config.double", value: "config.base * 2"}, + {match: "item.tier", arms: [["item.v > cfg.double", "'hi'"], ["", "'lo'"]]}, + ], + }, + cases: [ + [{cfg: {base: 2}, o: {items: [{v: 1}, {v: 6}]}}, {cfg: {base: 2, double: 4}, o: {items: [{v: 1, tier: "lo"}, {v: 6, tier: "hi"}]}}], + [{cfg: {base: 0}, o: {items: [{v: 0}]}}, {cfg: {base: 0, double: 0}, o: {items: [{v: 0, tier: "lo"}]}}], + ], +} + +{ + name: "member blocks read another global array", + policy: { + globals: {env: {blocked: "string[]"}}, + models: {o: {items: "item[]"}, item: {country: "string"}}, + blocks: [ + {expression: "item.blocked", value: "item.country in blocked"}, + {expression: "o.clean", value: "none(o.items, #.blocked)"}, + ], + }, + cases: [ + [{blocked: ["RU", "KP"], o: {items: [{country: "US"}, {country: "KP"}]}}, {blocked: ["RU", "KP"], o: {items: [{country: "US", blocked: false}, {country: "KP", blocked: true}], clean: false}}], + [{blocked: [], o: {items: [{country: "US"}]}}, {blocked: [], o: {items: [{country: "US", blocked: false}], clean: true}}], + [{o: {items: [{country: "US"}]}}, "!error: MissingRequiredInputs"], + ], +} + +{ + name: "member values aggregated into a global, read back by the members", + policy: { + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "grandTotal", value: "sum(map(o.items, #.v))"}, + {expression: "item.share", value: "grandTotal > 0 ? item.v / grandTotal : 0"}, + {expression: "maxShare", value: "max(map(o.items, #.share))"}, + ], + }, + cases: [ + [{o: {items: [{v: 1}, {v: 3}]}}, {o: {items: [{v: 1, share: 0.25}, {v: 3, share: 0.75}]}, grandTotal: 4, maxShare: 0.75}], + [{o: {items: [{v: 0}]}}, {o: {items: [{v: 0, share: 0}]}, grandTotal: 0, maxShare: 0}], + [{o: {items: []}}, "!error: ExpressionFailed"], + ], +} + +{ + name: "members of a global array and of a root relationship read each other's aggregates", + policy: { + globals: {env: {quotas: "quota[]"}}, + models: {quota: {region: "string", limit: "number"}, team: {sales: "sale[]"}, sale: {region: "string", amount: "number"}}, + blocks: [ + {expression: "quota.used", value: "sum(map(filter(team.sales, #.region == quota.region), #.amount))"}, + {expression: "quota.over", value: "quota.used > quota.limit"}, + {expression: "sale.flagged", value: "some(quotas, #.region == sale.region and #.over)"}, + ], + }, + cases: [ + [ + {quotas: [{region: "eu", limit: 10}, {region: "us", limit: 100}], team: {sales: [{region: "eu", amount: 6}, {region: "eu", amount: 5}, {region: "us", amount: 50}]}}, + { + quotas: [{region: "eu", limit: 10, used: 11, over: true}, {region: "us", limit: 100, used: 50, over: false}], + team: {sales: [{region: "eu", amount: 6, flagged: true}, {region: "eu", amount: 5, flagged: true}, {region: "us", amount: 50, flagged: false}]}, + }, + ], + [ + {quotas: [{region: "eu", limit: 10}], team: {sales: [{region: "apac", amount: 99}]}}, + {quotas: [{region: "eu", limit: 10, used: 0, over: false}], team: {sales: [{region: "apac", amount: 99, flagged: false}]}}, + ], + ], +} + +{ + name: "a member block reading a global that a member-fed root block computes", + policy: { + globals: {env: {threshold: "number"}}, + models: {o: {items: "item[]"}, item: {v: "number"}}, + blocks: [ + {expression: "item.doubled", value: "item.v * 2"}, + {expression: "o.avg", value: "avg(map(o.items, #.doubled))"}, + {expression: "cutoff", value: "max([threshold, o.avg])"}, + {expression: "item.above", value: "item.doubled > cutoff"}, + ], + }, + cases: [ + [ + {threshold: 1, o: {items: [{v: 1}, {v: 2}, {v: 6}]}}, + {threshold: 1, cutoff: 6, o: {items: [{v: 1, doubled: 2, above: false}, {v: 2, doubled: 4, above: false}, {v: 6, doubled: 12, above: true}], avg: 6}}, + ], + [ + {threshold: 100, o: {items: [{v: 1}]}}, + {threshold: 100, cutoff: 100, o: {items: [{v: 1, doubled: 2, above: false}], avg: 2}}, + ], + ], +} + +// --------------------------------------------------------------------------------------------- +// A realistic combination: a marketplace order with a product pool, a shipping-zone pool, a +// global fee schedule and per-line computations. + +{ + name: "marketplace order with pools and global fees", + policy: { + globals: {env: {fees: "feeSchedule", vatRate: "number"}}, + models: { + feeSchedule: {platformPct: "number", minFee: "number"}, + mpOrder: {lines: "mpLine[]", zone: "&zone"}, + mpLine: {qty: "number", unitPrice: "number"}, + zone: {id: "string", shipping: "number"}, + }, + blocks: [ + {expression: "mpLine.net", value: "mpLine.qty * mpLine.unitPrice"}, + {expression: "feeSchedule.rate", value: "feeSchedule.platformPct / 100"}, + {expression: "mpOrder.net", value: "sum(map(mpOrder.lines, #.net))"}, + {expression: "mpOrder.platformFee", value: "max([fees.minFee, round(mpOrder.net * fees.rate, 2)])"}, + {expression: "mpOrder.vat", value: "round((mpOrder.net + mpOrder.zone.shipping) * vatRate, 2)"}, + {expression: "mpOrder.total", value: "mpOrder.net + mpOrder.zone.shipping + mpOrder.vat"}, + ], + }, + cases: [ + [ + {fees: {platformPct: 5, minFee: 1}, vatRate: 0.2, mpOrder: {zone: "eu", lines: [{qty: 2, unitPrice: 10}, {qty: 1, unitPrice: 5.5}]}, zone: [{id: "eu", shipping: 4.5}, {id: "us", shipping: 12}]}, + { + fees: {platformPct: 5, minFee: 1, rate: 0.05}, vatRate: 0.2, + mpOrder: {zone: {id: "eu", shipping: 4.5}, lines: [{qty: 2, unitPrice: 10, net: 20}, {qty: 1, unitPrice: 5.5, net: 5.5}], net: 25.5, platformFee: 1.28, vat: 6, total: 36}, + zone: [{id: "eu", shipping: 4.5}, {id: "us", shipping: 12}], + }, + ], + [ + {fees: {platformPct: 5, minFee: 1}, vatRate: 0, mpOrder: {zone: "us", lines: [{qty: 1, unitPrice: 3}]}, zone: [{id: "eu", shipping: 4.5}, {id: "us", shipping: 12}]}, + { + fees: {platformPct: 5, minFee: 1, rate: 0.05}, vatRate: 0, + mpOrder: {zone: {id: "us", shipping: 12}, lines: [{qty: 1, unitPrice: 3, net: 3}], net: 3, platformFee: 1, vat: 0, total: 15}, + zone: [{id: "eu", shipping: 4.5}, {id: "us", shipping: 12}], + }, + ], + [{fees: {platformPct: 5, minFee: 1}, vatRate: 0.2, mpOrder: {zone: "apac", lines: []}, zone: [{id: "eu", shipping: 4.5}]}, "!error: mpOrder.zone"], + [{fees: {platformPct: "5", minFee: 1}, vatRate: 0.2, mpOrder: {zone: "eu", lines: []}, zone: [{id: "eu", shipping: 4.5}]}, "!error: fees.platformPct"], + ], +} diff --git a/core/engine/tests/spec/policy/41-realistic-insurance.json5 b/core/engine/tests/spec/policy/41-realistic-insurance.json5 new file mode 100644 index 00000000..84042dfc --- /dev/null +++ b/core/engine/tests/spec/policy/41-realistic-insurance.json5 @@ -0,0 +1,755 @@ +// Realistic insurance policies: motor households with vehicles and claims as members, home cover +// over properties with peril loadings, claims triage with fraud indicators and document checks, +// renewal pricing against referenced products and a market global, group life census, travel +// quotes with referenced regions and global activity lists, and telematics fleet scoring. Each +// suite combines several block kinds over related entities and runs valid, boundary, missing and +// invalid data. Evaluation time is fixed at 2025-03-20T10:15:30Z. + +// --- Motor household --------------------------------------------------------------------------- +// Vehicles and claims are members of one policyholder. A driver factor match on the root feeds +// every per-vehicle premium; a usage table runs per vehicle; claims within five years load the +// household total, and a multi-car discount applies from two vehicles. A missing optional +// `garaged` defaults to false through `??`. + +{ + name: "motor household with vehicles and claims", + policy: { + models: { + holder: {dob: "date", licensed: "date", vehicles: "vehicle[]", claims: "claim[]"}, + vehicle: {plate: "string", value: "number", year: "number", use: "string(private|commute|business)", garaged: "boolean?"}, + claim: {date: "date", amount: "number", atFault: "boolean"}, + }, + blocks: [ + {expression: "holder.age", value: "d().diff(holder.dob, 'year')"}, + {expression: "holder.experience", value: "d().diff(holder.licensed, 'year')"}, + {expression: "claim.recent", value: "d().diff(claim.date, 'year') < 5"}, + {expression: "holder.faultClaims", value: "count(holder.claims, #.recent and #.atFault)"}, + {expression: "holder.claimsPaid", value: "sum(map(filter(holder.claims, #.recent), #.amount))"}, + {match: "holder.driverFactor", arms: [ + ["holder.age < 25", "1.6"], + ["holder.experience < 3", "1.3"], + ["holder.age >= 75", "1.2"], + ["", "1"], + ]}, + {expression: "vehicle.ageYears", value: "d().year() - vehicle.year"}, + {table: "usage", inputs: ["vehicle.use"], outputs: ["vehicle.useFactor"], rules: [ + ["'private'", "1"], + ["'commute'", "1.1"], + ["'business'", "1.35"], + ]}, + {expression: "vehicle.premium", value: "round(vehicle.value * (vehicle.ageYears > 10 ? 0.02 : 0.03) * vehicle.useFactor * holder.driverFactor * ((vehicle.garaged ?? false) ? 0.9 : 1), 2)"}, + {match: "holder.claimLoad", arms: [ + ["holder.faultClaims == 0", "0.85"], + ["holder.faultClaims == 1", "1.15"], + ["", "1.5"], + ]}, + {expression: "holder.gross", value: "sum(map(holder.vehicles, #.premium))"}, + {expression: "holder.total", value: "round(holder.gross * holder.claimLoad * (len(holder.vehicles) >= 2 ? 0.95 : 1), 2)"}, + {match: "holder.decision", arms: [ + ["holder.faultClaims >= 3", "'decline'"], + ["holder.claimsPaid > 50000", "'refer'"], + ["len(holder.vehicles) == 0", "'no-cover'"], + ["", "'quote'"], + ]}, + ], + }, + cases: [ + [ + {holder: {dob: "1980-01-01", licensed: "2000-01-01", vehicles: [{plate: "A", value: 20000, year: 2020, use: "private"}], claims: []}}, + {holder: {dob: "1980-01-01", licensed: "2000-01-01", claims: [], vehicles: [ + {plate: "A", value: 20000, year: 2020, use: "private", ageYears: 5, useFactor: 1, premium: 600}, + ], age: 45, experience: 25, faultClaims: 0, claimsPaid: 0, driverFactor: 1, claimLoad: 0.85, gross: 600, total: 510, decision: "quote"}}, + ], + // A young driver with two vehicles: an old garaged commuter and a business van; one recent + // at-fault claim and the multi-car discount. + [ + {holder: {dob: "2002-06-01", licensed: "2020-01-01", vehicles: [ + {plate: "B", value: 15000, year: 2012, use: "commute", garaged: true}, + {plate: "C", value: 8000, year: 2016, use: "business"}, + ], claims: [{date: "2023-05-01", amount: 4000, atFault: true}]}}, + {holder: {dob: "2002-06-01", licensed: "2020-01-01", vehicles: [ + {plate: "B", value: 15000, year: 2012, use: "commute", garaged: true, ageYears: 13, useFactor: 1.1, premium: 475.2}, + {plate: "C", value: 8000, year: 2016, use: "business", ageYears: 9, useFactor: 1.35, premium: 518.4}, + ], claims: [{date: "2023-05-01", amount: 4000, atFault: true, recent: true}], + age: 22, experience: 5, faultClaims: 1, claimsPaid: 4000, driverFactor: 1.6, claimLoad: 1.15, gross: 993.6, total: 1085.51, decision: "quote"}}, + ], + // A novice of 35: licensed one day short of two years. + [ + {holder: {dob: "1990-03-20", licensed: "2023-03-21", vehicles: [{plate: "D", value: 30000, year: 2025, use: "private", garaged: false}], claims: []}}, + {holder: {dob: "1990-03-20", licensed: "2023-03-21", claims: [], vehicles: [ + {plate: "D", value: 30000, year: 2025, use: "private", garaged: false, ageYears: 0, useFactor: 1, premium: 1170}, + ], age: 35, experience: 1, faultClaims: 0, claimsPaid: 0, driverFactor: 1.3, claimLoad: 0.85, gross: 1170, total: 994.5, decision: "quote"}}, + ], + // An elderly driver; a six-year-old claim no longer counts, a null `garaged` is not garaged. + [ + {holder: {dob: "1945-01-01", licensed: "1965-01-01", vehicles: [{plate: "E", value: 10000, year: 2014, use: "private", garaged: null}], claims: [{date: "2019-01-01", amount: 60000, atFault: true}]}}, + {holder: {dob: "1945-01-01", licensed: "1965-01-01", vehicles: [ + {plate: "E", value: 10000, year: 2014, use: "private", garaged: null, ageYears: 11, useFactor: 1, premium: 240}, + ], claims: [{date: "2019-01-01", amount: 60000, atFault: true, recent: false}], + age: 80, experience: 60, faultClaims: 0, claimsPaid: 0, driverFactor: 1.2, claimLoad: 0.85, gross: 240, total: 204, decision: "quote"}}, + ], + // Boundaries: exactly 25 years old and 3 years licensed is the standard factor, a 10-year-old + // vehicle keeps the 3% rate, a claim exactly five years old has dropped out. + [ + {holder: {dob: "2000-03-20", licensed: "2022-03-20", vehicles: [{plate: "F", value: 10000, year: 2015, use: "commute"}], claims: [ + {date: "2020-03-20", amount: 100, atFault: false}, + {date: "2020-03-21", amount: 200, atFault: true}, + ]}}, + {holder: {dob: "2000-03-20", licensed: "2022-03-20", vehicles: [ + {plate: "F", value: 10000, year: 2015, use: "commute", ageYears: 10, useFactor: 1.1, premium: 330}, + ], claims: [ + {date: "2020-03-20", amount: 100, atFault: false, recent: false}, + {date: "2020-03-21", amount: 200, atFault: true, recent: true}, + ], age: 25, experience: 3, faultClaims: 1, claimsPaid: 200, driverFactor: 1, claimLoad: 1.15, gross: 330, total: 379.5, decision: "quote"}}, + ], + [ + {holder: {dob: "1985-01-01", licensed: "2005-01-01", vehicles: [{plate: "G", value: 5000, year: 2010, use: "private"}], claims: [ + {date: "2024-01-01", amount: 1000, atFault: true}, + {date: "2024-02-01", amount: 1000, atFault: true}, + {date: "2024-03-01", amount: 1000, atFault: true}, + ]}}, + {holder: {dob: "1985-01-01", licensed: "2005-01-01", vehicles: [ + {plate: "G", value: 5000, year: 2010, use: "private", ageYears: 15, useFactor: 1, premium: 100}, + ], claims: [ + {date: "2024-01-01", amount: 1000, atFault: true, recent: true}, + {date: "2024-02-01", amount: 1000, atFault: true, recent: true}, + {date: "2024-03-01", amount: 1000, atFault: true, recent: true}, + ], age: 40, experience: 20, faultClaims: 3, claimsPaid: 3000, driverFactor: 1, claimLoad: 1.5, gross: 100, total: 150, decision: "decline"}}, + ], + // Large non-fault claims keep the no-claims discount but refer the case. + [ + {holder: {dob: "1975-01-01", licensed: "1995-01-01", vehicles: [{plate: "H", value: 40000, year: 2022, use: "business"}], claims: [ + {date: "2024-06-01", amount: 30000, atFault: false}, + {date: "2023-06-01", amount: 25000, atFault: false}, + ]}}, + {holder: {dob: "1975-01-01", licensed: "1995-01-01", vehicles: [ + {plate: "H", value: 40000, year: 2022, use: "business", ageYears: 3, useFactor: 1.35, premium: 1620}, + ], claims: [ + {date: "2024-06-01", amount: 30000, atFault: false, recent: true}, + {date: "2023-06-01", amount: 25000, atFault: false, recent: true}, + ], age: 50, experience: 30, faultClaims: 0, claimsPaid: 55000, driverFactor: 1, claimLoad: 0.85, gross: 1620, total: 1377, decision: "refer"}}, + ], + [ + {holder: {dob: "1990-01-01", licensed: "2010-01-01", vehicles: [], claims: []}}, + {holder: {dob: "1990-01-01", licensed: "2010-01-01", vehicles: [], claims: [], age: 35, experience: 15, faultClaims: 0, claimsPaid: 0, driverFactor: 1, claimLoad: 0.85, gross: 0, total: 0, decision: "no-cover"}}, + ], + [{holder: {dob: "1990-01-01", licensed: "2010-01-01", vehicles: [{plate: "X", value: 1, year: 2020, use: "racing"}], claims: []}}, "!error: InputValidationFailed"], + [{holder: {dob: "1990-01-01", licensed: "2010-01-01", vehicles: [{plate: "X", year: 2020, use: "private"}], claims: []}}, "!error: ExpressionFailed"], + [{holder: {dob: "1990-01-01", licensed: "2010-01-01", vehicles: [], claims: [{date: "2024-02-30", amount: 1, atFault: false}]}}, "!error: InputValidationFailed"], + [{holder: {dob: "1990-01-01", licensed: "2010-01-01", vehicles: [], claims: [{date: "2024-02-01", amount: 1, atFault: "no"}]}}, "!error: InputValidationFailed"], + [{holder: {dob: "1990-01-01", licensed: "2010-01-01", vehicles: []}}, "!error: MissingRequiredInputs"], + [{holder: {dob: null, licensed: "2010-01-01", vehicles: [], claims: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Home cover over properties ---------------------------------------------------------------- +// Per-property rate from a two-input first-hit table (kind and age), peril loadings from a +// per-property hit-policy `collect` table, a deductible credit match, a bundle discount from two +// properties, and an insurability assertion over all properties. + +{ + name: "home cover with peril loadings per property", + policy: { + models: { + household: {bundle: "boolean", deductible: "string(low|standard|high)", properties: "property[]"}, + property: {kind: "string(house|apartment|cabin)", rebuildCost: "number", contents: "number", built: "number", floodZone: "string(none|low|high)", alarm: "boolean", occupied: "boolean"}, + }, + blocks: [ + {expression: "property.age", value: "d().year() - property.built"}, + {table: "rate", inputs: ["property.kind", "property.age"], outputs: ["property.rate"], rules: [ + ["'house'", "< 30", "0.0012"], + ["'house'", "", "0.0015"], + ["'apartment'", "", "0.0009"], + ["'cabin'", "", "0.002"], + ]}, + {table: "perils", hit: "collect", inputs: ["property.floodZone", "property.occupied", "property.alarm"], outputs: ["property.loadings"], rules: [ + ["'high'", "", "", "0.5"], + ["'low'", "", "", "0.1"], + ["", "false", "", "0.25"], + ["", "", "true", "-0.1"], + ]}, + {expression: "property.premium", value: "round((property.rebuildCost + property.contents) * property.rate * (1 + sum(property.loadings)), 2)"}, + {match: "household.deductibleCredit", arms: [ + ["household.deductible == 'high'", "0.15"], + ["household.deductible == 'low'", "-0.1"], + ["", "0"], + ]}, + {expression: "household.sumInsured", value: "sum(map(household.properties, #.rebuildCost + #.contents))"}, + {expression: "household.base", value: "sum(map(household.properties, #.premium))"}, + {expression: "household.premium", value: "round(household.base * (1 - household.deductibleCredit) * (household.bundle and len(household.properties) > 1 ? 0.9 : 1), 2)"}, + {assertion: "household.insurable", conditions: [ + "none(household.properties, #.floodZone == 'high' and not #.occupied)", + "household.sumInsured <= 5000000", + ]}, + ], + }, + cases: [ + [ + {household: {bundle: false, deductible: "standard", properties: [{kind: "house", rebuildCost: 300000, contents: 50000, built: 2000, floodZone: "none", alarm: true, occupied: true}]}}, + {household: {bundle: false, deductible: "standard", properties: [ + {kind: "house", rebuildCost: 300000, contents: 50000, built: 2000, floodZone: "none", alarm: true, occupied: true, age: 25, rate: 0.0012, loadings: [-0.1], premium: 378}, + ], deductibleCredit: 0, sumInsured: 350000, base: 378, premium: 378, insurable: true}}, + ], + // An old house in a low flood zone and an empty cabin in a high one: two loadings on the + // cabin, the high deductible and the bundle discount; the empty cabin is not insurable. + [ + {household: {bundle: true, deductible: "high", properties: [ + {kind: "house", rebuildCost: 400000, contents: 100000, built: 1980, floodZone: "low", alarm: false, occupied: true}, + {kind: "cabin", rebuildCost: 150000, contents: 20000, built: 1990, floodZone: "high", alarm: false, occupied: false}, + ]}}, + {household: {bundle: true, deductible: "high", properties: [ + {kind: "house", rebuildCost: 400000, contents: 100000, built: 1980, floodZone: "low", alarm: false, occupied: true, age: 45, rate: 0.0015, loadings: [0.1], premium: 825}, + {kind: "cabin", rebuildCost: 150000, contents: 20000, built: 1990, floodZone: "high", alarm: false, occupied: false, age: 35, rate: 0.002, loadings: [0.5, 0.25], premium: 595}, + ], deductibleCredit: 0.15, sumInsured: 670000, base: 1420, premium: 1086.3, insurable: false}}, + ], + // A bundle with a single property gets no bundle discount; a low deductible costs 10% more. + [ + {household: {bundle: true, deductible: "low", properties: [{kind: "apartment", rebuildCost: 200000, contents: 0, built: 2020, floodZone: "none", alarm: true, occupied: true}]}}, + {household: {bundle: true, deductible: "low", properties: [ + {kind: "apartment", rebuildCost: 200000, contents: 0, built: 2020, floodZone: "none", alarm: true, occupied: true, age: 5, rate: 0.0009, loadings: [-0.1], premium: 162}, + ], deductibleCredit: -0.1, sumInsured: 200000, base: 162, premium: 178.2, insurable: true}}, + ], + [ + {household: {bundle: false, deductible: "standard", properties: []}}, + {household: {bundle: false, deductible: "standard", properties: [], deductibleCredit: 0, sumInsured: 0, base: 0, premium: 0, insurable: true}}, + ], + // A house of exactly 30 years takes the older rate and has no loadings at all; the sum + // insured is one over the limit. + [ + {household: {bundle: true, deductible: "standard", properties: [ + {kind: "house", rebuildCost: 1000000, contents: 0, built: 1995, floodZone: "none", alarm: false, occupied: true}, + {kind: "house", rebuildCost: 4000000, contents: 500001, built: 2024, floodZone: "none", alarm: true, occupied: true}, + ]}}, + {household: {bundle: true, deductible: "standard", properties: [ + {kind: "house", rebuildCost: 1000000, contents: 0, built: 1995, floodZone: "none", alarm: false, occupied: true, age: 30, rate: 0.0015, loadings: [], premium: 1500}, + {kind: "house", rebuildCost: 4000000, contents: 500001, built: 2024, floodZone: "none", alarm: true, occupied: true, age: 1, rate: 0.0012, loadings: [-0.1], premium: 4860}, + ], deductibleCredit: 0, sumInsured: 5500001, base: 6360, premium: 5724, insurable: false}}, + ], + [ + {household: {bundle: false, deductible: "high", properties: [{kind: "house", rebuildCost: 250000, contents: 25000, built: 2010, floodZone: "high", alarm: true, occupied: true}]}}, + {household: {bundle: false, deductible: "high", properties: [ + {kind: "house", rebuildCost: 250000, contents: 25000, built: 2010, floodZone: "high", alarm: true, occupied: true, age: 15, rate: 0.0012, loadings: [0.5, -0.1], premium: 462}, + ], deductibleCredit: 0.15, sumInsured: 275000, base: 462, premium: 392.7, insurable: true}}, + ], + // A property without `alarm` reads null: neither the `true` cell nor any other matches it. + [ + {household: {bundle: false, deductible: "standard", properties: [{kind: "house", rebuildCost: 100000, contents: 0, built: 2000, floodZone: "none", occupied: true}]}}, + {household: {bundle: false, deductible: "standard", properties: [ + {kind: "house", rebuildCost: 100000, contents: 0, built: 2000, floodZone: "none", occupied: true, age: 25, rate: 0.0012, loadings: [], premium: 120}, + ], deductibleCredit: 0, sumInsured: 100000, base: 120, premium: 120, insurable: true}}, + ], + [{household: {bundle: false, deductible: "standard", properties: [{kind: "castle", rebuildCost: 1, contents: 0, built: 2000, floodZone: "none", alarm: true, occupied: true}]}}, "!error: InputValidationFailed"], + [{household: {bundle: false, deductible: "zero", properties: []}}, "!error: InputValidationFailed"], + [{household: {bundle: false, deductible: "standard", properties: [{kind: "house", rebuildCost: "100000", contents: 0, built: 2000, floodZone: "none", alarm: true, occupied: true}]}}, "!error: InputValidationFailed"], + [{household: {deductible: "standard", properties: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Claims triage ----------------------------------------------------------------------------- +// Fraud indicators collected by a first-hit table with a `[]` column over date differences and an +// unwitnessed-theft flag; required documents per claim type from a match producing a list, +// missing documents through a received-kinds list; cover from an and-assertion on the policy +// period; the payable amount net of the excess; a routing match. + +{ + name: "claims triage with fraud indicators and documents", + policy: { + models: { + claim: {type: "string(theft|collision|water|fire)", incident: "date", reported: "date", policyStart: "date", policyEnd: "date", amount: "number", excess: "number", witnesses: "number?", documents: "document[]"}, + document: {kind: "string", received: "boolean"}, + }, + blocks: [ + {expression: "claim.reportDelay", value: "claim.reported.diff(claim.incident, 'day')"}, + {expression: "claim.policyAgeDays", value: "claim.incident.diff(claim.policyStart, 'day')"}, + {expression: "claim.unwitnessedTheft", value: "claim.type == 'theft' and (claim.witnesses ?? 0) == 0"}, + {table: "indicators", inputs: ["claim.policyAgeDays", "claim.reportDelay", "claim.amount", "claim.unwitnessedTheft"], outputs: ["claim.indicators[]"], rules: [ + ["< 30", "", "", "", "'early-claim'"], + ["", "> 30", "", "", "'late-report'"], + ["", "", "> 20000", "", "'high-value'"], + ["", "", "", "true", "'no-witness'"], + ]}, + {expression: "claim.fraudScore", value: "len(claim.indicators)"}, + {match: "claim.requiredDocs", arms: [ + ["claim.type == 'theft'", "['police', 'invoice']"], + ["claim.type == 'collision'", "['photos', 'estimate']"], + ["claim.type == 'water'", "['photos']"], + ["", "[]"], + ]}, + {expression: "claim.receivedKinds", value: "map(filter(claim.documents, #.received), #.kind)"}, + {expression: "claim.missingDocs", value: "filter(claim.requiredDocs, not (# in claim.receivedKinds))"}, + {assertion: "claim.covered", conditions: ["claim.incident >= claim.policyStart", "claim.incident < claim.policyEnd"]}, + {expression: "claim.payable", value: "claim.covered ? max([claim.amount - claim.excess, 0]) : 0"}, + {match: "claim.route", arms: [ + ["claim.fraudScore >= 2", "'siu'"], + ["len(claim.missingDocs) > 0", "'pending-docs'"], + ["claim.amount <= 1000", "'fast-track'"], + ["", "'adjuster'"], + ]}, + ], + }, + cases: [ + [ + {claim: {type: "collision", incident: "2025-03-10", reported: "2025-03-11", policyStart: "2024-06-01", policyEnd: "2025-06-01", amount: 3000, excess: 500, witnesses: 1, documents: [{kind: "photos", received: true}, {kind: "estimate", received: true}]}}, + {claim: {type: "collision", incident: "2025-03-10", reported: "2025-03-11", policyStart: "2024-06-01", policyEnd: "2025-06-01", amount: 3000, excess: 500, witnesses: 1, documents: [{kind: "photos", received: true}, {kind: "estimate", received: true}], + reportDelay: 1, policyAgeDays: 282, unwitnessedTheft: false, indicators: [], fraudScore: 0, requiredDocs: ["photos", "estimate"], receivedKinds: ["photos", "estimate"], missingDocs: [], covered: true, payable: 2500, route: "adjuster"}}, + ], + // An early, large, unwitnessed theft goes to the special investigations unit. + [ + {claim: {type: "theft", incident: "2025-03-01", reported: "2025-03-15", policyStart: "2025-02-15", policyEnd: "2026-02-15", amount: 25000, excess: 1000, documents: [{kind: "police", received: true}, {kind: "invoice", received: false}]}}, + {claim: {type: "theft", incident: "2025-03-01", reported: "2025-03-15", policyStart: "2025-02-15", policyEnd: "2026-02-15", amount: 25000, excess: 1000, documents: [{kind: "police", received: true}, {kind: "invoice", received: false}], + reportDelay: 14, policyAgeDays: 14, unwitnessedTheft: true, indicators: ["early-claim", "high-value", "no-witness"], fraudScore: 3, requiredDocs: ["police", "invoice"], receivedKinds: ["police"], missingDocs: ["invoice"], covered: true, payable: 24000, route: "siu"}}, + ], + // The policy end is exclusive: an incident on the end date is not covered. + [ + {claim: {type: "water", incident: "2025-01-01", reported: "2025-03-01", policyStart: "2024-01-01", policyEnd: "2025-01-01", amount: 800, excess: 200, documents: []}}, + {claim: {type: "water", incident: "2025-01-01", reported: "2025-03-01", policyStart: "2024-01-01", policyEnd: "2025-01-01", amount: 800, excess: 200, documents: [], + reportDelay: 59, policyAgeDays: 366, unwitnessedTheft: false, indicators: ["late-report"], fraudScore: 1, requiredDocs: ["photos"], receivedKinds: [], missingDocs: ["photos"], covered: false, payable: 0, route: "pending-docs"}}, + ], + // The excess exceeds the loss: nothing is payable, but a small claim is still fast-tracked. + [ + {claim: {type: "fire", incident: "2025-03-19", reported: "2025-03-19", policyStart: "2020-01-01", policyEnd: "2030-01-01", amount: 1000, excess: 1500, documents: []}}, + {claim: {type: "fire", incident: "2025-03-19", reported: "2025-03-19", policyStart: "2020-01-01", policyEnd: "2030-01-01", amount: 1000, excess: 1500, documents: [], + reportDelay: 0, policyAgeDays: 1904, unwitnessedTheft: false, indicators: [], fraudScore: 0, requiredDocs: [], receivedKinds: [], missingDocs: [], covered: true, payable: 0, route: "fast-track"}}, + ], + // Every indicator threshold is strict: 30 days into the policy, reported 30 days later and a + // loss of exactly 20000 raise nothing. A witnessed theft with an extra unreceived document. + [ + {claim: {type: "theft", incident: "2025-01-31", reported: "2025-03-02", policyStart: "2025-01-01", policyEnd: "2026-01-01", amount: 20000, excess: 0, witnesses: 2, documents: [{kind: "police", received: true}, {kind: "invoice", received: true}, {kind: "photos", received: false}]}}, + {claim: {type: "theft", incident: "2025-01-31", reported: "2025-03-02", policyStart: "2025-01-01", policyEnd: "2026-01-01", amount: 20000, excess: 0, witnesses: 2, documents: [{kind: "police", received: true}, {kind: "invoice", received: true}, {kind: "photos", received: false}], + reportDelay: 30, policyAgeDays: 30, unwitnessedTheft: false, indicators: [], fraudScore: 0, requiredDocs: ["police", "invoice"], receivedKinds: ["police", "invoice"], missingDocs: [], covered: true, payable: 20000, route: "adjuster"}}, + ], + // A null witness count is no witness: one indicator alone does not reach the unit. + [ + {claim: {type: "theft", incident: "2024-12-01", reported: "2024-12-02", policyStart: "2024-01-01", policyEnd: "2025-01-01", amount: 500, excess: 100, witnesses: null, documents: [{kind: "police", received: true}, {kind: "invoice", received: true}]}}, + {claim: {type: "theft", incident: "2024-12-01", reported: "2024-12-02", policyStart: "2024-01-01", policyEnd: "2025-01-01", amount: 500, excess: 100, witnesses: null, documents: [{kind: "police", received: true}, {kind: "invoice", received: true}], + reportDelay: 1, policyAgeDays: 335, unwitnessedTheft: true, indicators: ["no-witness"], fraudScore: 1, requiredDocs: ["police", "invoice"], receivedKinds: ["police", "invoice"], missingDocs: [], covered: true, payable: 400, route: "fast-track"}}, + ], + // An incident the day before the policy started: negative policy age, not covered. + [ + {claim: {type: "collision", incident: "2023-12-31", reported: "2024-01-05", policyStart: "2024-01-01", policyEnd: "2025-01-01", amount: 5000, excess: 500, documents: [{kind: "photos", received: true}, {kind: "estimate", received: true}]}}, + {claim: {type: "collision", incident: "2023-12-31", reported: "2024-01-05", policyStart: "2024-01-01", policyEnd: "2025-01-01", amount: 5000, excess: 500, documents: [{kind: "photos", received: true}, {kind: "estimate", received: true}], + reportDelay: 5, policyAgeDays: -1, unwitnessedTheft: false, indicators: ["early-claim"], fraudScore: 1, requiredDocs: ["photos", "estimate"], receivedKinds: ["photos", "estimate"], missingDocs: [], covered: false, payable: 0, route: "adjuster"}}, + ], + // A document without `received` reads null, and a null filter predicate is an error (as in + // the expression language), unlike an assertion condition which counts null as false. + [{claim: {type: "collision", incident: "2025-03-01", reported: "2025-03-02", policyStart: "2024-01-01", policyEnd: "2026-01-01", amount: 900, excess: 100, documents: [{kind: "photos"}, {kind: "estimate", received: true}]}}, "!error: ExpressionFailed"], + [{claim: {type: "hail", incident: "2025-03-01", reported: "2025-03-02", policyStart: "2024-01-01", policyEnd: "2026-01-01", amount: 1, excess: 0, documents: []}}, "!error: InputValidationFailed"], + [{claim: {type: "fire", incident: "yesterday", reported: "2025-03-02", policyStart: "2024-01-01", policyEnd: "2026-01-01", amount: 1, excess: 0, documents: []}}, "!error: InputValidationFailed"], + [{claim: {type: "fire", incident: "2025-03-01", reported: "2025-03-02", policyStart: "2024-01-01", policyEnd: "2026-01-01", amount: "1", excess: 0, documents: []}}, "!error: InputValidationFailed"], + [{claim: {type: "fire", incident: "2025-03-01", reported: "2025-03-02", policyStart: "2024-01-01", policyEnd: "2026-01-01", amount: 1, documents: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Renewal pricing --------------------------------------------------------------------------- +// The renewal references a product from a pool; a market global moderates the action. Loyalty +// comes from a two-input first-hit table and is capped by the product; claim and payment +// adjustments are matches; the quote is floored at the product minimum. Goals evaluate only the +// requested cone, so unrelated inputs (and the product pool) may be absent. + +{ + name: "renewal pricing against referenced products", + policy: { + globals: {market: {competitorIndex: "number"}}, + models: { + renewal: {product: "&product", previousPremium: "number", tenure: "number", claimsLastYear: "number", autoRenew: "boolean", paymentMethod: "string(card|invoice|directDebit)"}, + product: {id: "string", indexation: "number", maxLoyalty: "number", minPremium: "number"}, + }, + blocks: [ + {expression: "renewal.indexed", value: "round(renewal.previousPremium * (1 + renewal.product.indexation), 2)"}, + {table: "loyalty", inputs: ["renewal.tenure", "renewal.claimsLastYear"], outputs: ["renewal.loyaltyPct"], rules: [ + [">= 10", "0", "0.15"], + [">= 5", "0", "0.1"], + [">= 2", "0", "0.05"], + ["", "", "0"], + ]}, + {expression: "renewal.loyalty", value: "min([renewal.loyaltyPct, renewal.product.maxLoyalty])"}, + {match: "renewal.claimLoad", arms: [ + ["renewal.claimsLastYear >= 2", "0.3"], + ["renewal.claimsLastYear == 1", "0.1"], + ["", "0"], + ]}, + {match: "renewal.paymentAdj", arms: [ + ["renewal.paymentMethod == 'directDebit'", "-0.02"], + ["renewal.paymentMethod == 'invoice'", "0.03"], + ["", "0"], + ]}, + {expression: "renewal.quoted", value: "max([round(renewal.indexed * (1 - renewal.loyalty + renewal.claimLoad + renewal.paymentAdj), 2), renewal.product.minPremium])"}, + {expression: "renewal.change", value: "renewal.previousPremium > 0 ? round((renewal.quoted - renewal.previousPremium) / renewal.previousPremium * 100, 1) : 0"}, + {match: "renewal.action", arms: [ + ["renewal.change > 20", "'retention-call'"], + ["competitorIndex < 1 and renewal.change > 0", "'review-price'"], + ["renewal.autoRenew", "'auto'"], + ["", "'send-offer'"], + ]}, + ], + }, + cases: [ + [ + {competitorIndex: 1, renewal: {product: "basic", previousPremium: 1000, tenure: 12, claimsLastYear: 0, autoRenew: true, paymentMethod: "card"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}, {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + {competitorIndex: 1, renewal: {product: {id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}, previousPremium: 1000, tenure: 12, claimsLastYear: 0, autoRenew: true, paymentMethod: "card", + indexed: 1050, loyaltyPct: 0.15, loyalty: 0.1, claimLoad: 0, paymentAdj: 0, quoted: 945, change: -5.5, action: "auto"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}, {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + ], + [ + {competitorIndex: 1, renewal: {product: "plus", previousPremium: 1000, tenure: 6, claimsLastYear: 0, autoRenew: false, paymentMethod: "directDebit"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}, {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + {competitorIndex: 1, renewal: {product: {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}, previousPremium: 1000, tenure: 6, claimsLastYear: 0, autoRenew: false, paymentMethod: "directDebit", + indexed: 1030, loyaltyPct: 0.1, loyalty: 0.1, claimLoad: 0, paymentAdj: -0.02, quoted: 906.4, change: -9.4, action: "send-offer"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}, {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + ], + // Two claims cancel loyalty and load the premium: a 37% increase calls for retention. + [ + {competitorIndex: 1, renewal: {product: "plus", previousPremium: 500, tenure: 3, claimsLastYear: 2, autoRenew: true, paymentMethod: "invoice"}, product: [{id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + {competitorIndex: 1, renewal: {product: {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}, previousPremium: 500, tenure: 3, claimsLastYear: 2, autoRenew: true, paymentMethod: "invoice", + indexed: 515, loyaltyPct: 0, loyalty: 0, claimLoad: 0.3, paymentAdj: 0.03, quoted: 684.95, change: 37, action: "retention-call"}, product: [{id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + ], + // The product minimum lifts a heavily discounted quote. + [ + {competitorIndex: 1, renewal: {product: "plus", previousPremium: 300, tenure: 20, claimsLastYear: 0, autoRenew: true, paymentMethod: "directDebit"}, product: [{id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + {competitorIndex: 1, renewal: {product: {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}, previousPremium: 300, tenure: 20, claimsLastYear: 0, autoRenew: true, paymentMethod: "directDebit", + indexed: 309, loyaltyPct: 0.15, loyalty: 0.15, claimLoad: 0, paymentAdj: -0.02, quoted: 400, change: 33.3, action: "retention-call"}, product: [{id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + ], + // A soft market (index below 1) reviews any increase before auto-renewal. + [ + {competitorIndex: 0.95, renewal: {product: "basic", previousPremium: 1000, tenure: 1, claimsLastYear: 1, autoRenew: true, paymentMethod: "card"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, + {competitorIndex: 0.95, renewal: {product: {id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}, previousPremium: 1000, tenure: 1, claimsLastYear: 1, autoRenew: true, paymentMethod: "card", + indexed: 1050, loyaltyPct: 0, loyalty: 0, claimLoad: 0.1, paymentAdj: 0, quoted: 1155, change: 15.5, action: "review-price"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, + ], + [ + {competitorIndex: 0.95, renewal: {product: "basic", previousPremium: 1000, tenure: 6, claimsLastYear: 0, autoRenew: true, paymentMethod: "card"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, + {competitorIndex: 0.95, renewal: {product: {id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}, previousPremium: 1000, tenure: 6, claimsLastYear: 0, autoRenew: true, paymentMethod: "card", + indexed: 1050, loyaltyPct: 0.1, loyalty: 0.1, claimLoad: 0, paymentAdj: 0, quoted: 945, change: -5.5, action: "auto"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, + ], + // Tenure of exactly 2 earns 5%; the quote lands just under the minimum and is lifted to it. + [ + {competitorIndex: 1, renewal: {product: "basic", previousPremium: 200, tenure: 2, claimsLastYear: 0, autoRenew: false, paymentMethod: "card"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, + {competitorIndex: 1, renewal: {product: {id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}, previousPremium: 200, tenure: 2, claimsLastYear: 0, autoRenew: false, paymentMethod: "card", + indexed: 210, loyaltyPct: 0.05, loyalty: 0.05, claimLoad: 0, paymentAdj: 0, quoted: 200, change: 0, action: "send-offer"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, + ], + // One claim removes loyalty even after ten years. + [ + {competitorIndex: 0.9, renewal: {product: "plus", previousPremium: 800, tenure: 10, claimsLastYear: 1, autoRenew: false, paymentMethod: "invoice"}, product: [{id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + {competitorIndex: 0.9, renewal: {product: {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}, previousPremium: 800, tenure: 10, claimsLastYear: 1, autoRenew: false, paymentMethod: "invoice", + indexed: 824, loyaltyPct: 0, loyalty: 0, claimLoad: 0.1, paymentAdj: 0.03, quoted: 931.12, change: 16.4, action: "review-price"}, product: [{id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + ], + // A zero previous premium (a reinstated policy) reports no change. + [ + {competitorIndex: 1, renewal: {product: "plus", previousPremium: 0, tenure: 0, claimsLastYear: 0, autoRenew: true, paymentMethod: "card"}, product: [{id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + {competitorIndex: 1, renewal: {product: {id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}, previousPremium: 0, tenure: 0, claimsLastYear: 0, autoRenew: true, paymentMethod: "card", + indexed: 0, loyaltyPct: 0, loyalty: 0, claimLoad: 0, paymentAdj: 0, quoted: 400, change: 0, action: "auto"}, product: [{id: "plus", indexation: 0.03, maxLoyalty: 0.15, minPremium: 400}]}, + ], + { + input: {renewal: {product: "basic", tenure: 7, claimsLastYear: 0}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.08, minPremium: 200}]}, + goals: ["renewal.loyalty"], + output: {renewal: {product: {id: "basic", indexation: 0.05, maxLoyalty: 0.08, minPremium: 200}, tenure: 7, claimsLastYear: 0, loyaltyPct: 0.1, loyalty: 0.08}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.08, minPremium: 200}]}, + }, + { + input: {renewal: {claimsLastYear: 3}}, + goals: ["renewal.claimLoad"], + output: {renewal: {claimsLastYear: 3, claimLoad: 0.3}}, + }, + [{competitorIndex: 1, renewal: {product: "gold", previousPremium: 1, tenure: 1, claimsLastYear: 0, autoRenew: true, paymentMethod: "card"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, "!error: InputValidationFailed"], + [{renewal: {product: "basic", previousPremium: 1, tenure: 1, claimsLastYear: 0, autoRenew: true, paymentMethod: "card"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, "!error: MissingRequiredInputs"], + [{competitorIndex: 1, renewal: {product: "basic", previousPremium: 1, tenure: 1, claimsLastYear: 0, autoRenew: true, paymentMethod: "cash"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: 0.1, minPremium: 200}]}, "!error: InputValidationFailed"], + [{competitorIndex: 1, renewal: {product: "basic", previousPremium: 1, tenure: 1, claimsLastYear: 0, autoRenew: true, paymentMethod: "card"}, product: [{id: "basic", indexation: 0.05, maxLoyalty: "10%", minPremium: 200}]}, "!error: InputValidationFailed"], + ], +} + +// --- Group life census ------------------------------------------------------------------------- +// An employer with employees as members, each with dependents read through closures (a block +// cannot write the dependents themselves: they hang off a member). Age band rates from a table +// with interval cells, cover capped at 500000, smoker loading through `??`, an industry load +// match, and a quotability assertion over participation. + +{ + name: "group life census with dependents", + policy: { + models: { + employer: {industry: "string(office|construction|healthcare)", contribution: "number", employees: "employee[]"}, + employee: {dob: "date", salary: "number", enrolled: "boolean", smoker: "boolean?", dependents: "dependent[]"}, + dependent: {relation: "string(spouse|child)", dob: "date"}, + }, + blocks: [ + {expression: "employee.age", value: "d().diff(employee.dob, 'year')"}, + {table: "band", inputs: ["employee.age"], outputs: ["employee.monthlyRate"], rules: [ + ["< 30", "18"], + ["[30..44]", "25"], + ["[45..59]", "42"], + ["", "70"], + ]}, + {expression: "employee.cover", value: "min([employee.salary * 3, 500000])"}, + {expression: "employee.eligibleDeps", value: "count(employee.dependents, #.relation == 'spouse' or (#.relation == 'child' and d().diff(#.dob, 'year') < 26))"}, + {expression: "employee.monthly", value: "employee.enrolled ? round(employee.monthlyRate * ((employee.smoker ?? false) ? 1.5 : 1) * employee.cover / 100000 + employee.eligibleDeps * 12, 2) : 0"}, + {match: "employer.industryLoad", arms: [ + ["employer.industry == 'construction'", "1.25"], + ["employer.industry == 'healthcare'", "1.1"], + ["", "1"], + ]}, + {expression: "employer.enrolledCount", value: "count(employer.employees, #.enrolled)"}, + {expression: "employer.participation", value: "len(employer.employees) == 0 ? 0 : round(employer.enrolledCount / len(employer.employees), 4)"}, + {expression: "employer.monthlyPremium", value: "round(sum(map(employer.employees, #.monthly)) * employer.industryLoad, 2)"}, + {expression: "employer.employerShare", value: "round(employer.monthlyPremium * employer.contribution, 2)"}, + {assertion: "employer.quotable", conditions: ["employer.participation >= 0.75", "employer.enrolledCount >= 2", "employer.contribution >= 0.5"]}, + ], + }, + cases: [ + [ + {employer: {industry: "office", contribution: 0.5, employees: [ + {dob: "1990-01-01", salary: 60000, enrolled: true, smoker: false, dependents: [{relation: "spouse", dob: "1990-05-05"}, {relation: "child", dob: "2015-01-01"}]}, + {dob: "2000-01-01", salary: 40000, enrolled: true, dependents: []}, + ]}}, + {employer: {industry: "office", contribution: 0.5, employees: [ + {dob: "1990-01-01", salary: 60000, enrolled: true, smoker: false, dependents: [{relation: "spouse", dob: "1990-05-05"}, {relation: "child", dob: "2015-01-01"}], age: 35, monthlyRate: 25, cover: 180000, eligibleDeps: 2, monthly: 69}, + {dob: "2000-01-01", salary: 40000, enrolled: true, dependents: [], age: 25, monthlyRate: 18, cover: 120000, eligibleDeps: 0, monthly: 21.6}, + ], industryLoad: 1, enrolledCount: 2, participation: 1, monthlyPremium: 90.6, employerShare: 45.3, quotable: true}}, + ], + // Construction load, a capped smoker cover, a 27-year-old child no longer counted (a + // 24-year-old one is), one employee not enrolled: exactly 75% participation still quotes. + [ + {employer: {industry: "construction", contribution: 0.6, employees: [ + {dob: "1970-03-20", salary: 200000, enrolled: true, smoker: true, dependents: [{relation: "child", dob: "1998-01-01"}, {relation: "child", dob: "2000-03-21"}]}, + {dob: "1960-01-01", salary: 50000, enrolled: false, dependents: []}, + {dob: "1985-06-01", salary: 30000, enrolled: true, smoker: null, dependents: [{relation: "spouse", dob: "1986-01-01"}]}, + {dob: "1995-01-01", salary: 55000, enrolled: true, smoker: false, dependents: []}, + ]}}, + {employer: {industry: "construction", contribution: 0.6, employees: [ + {dob: "1970-03-20", salary: 200000, enrolled: true, smoker: true, dependents: [{relation: "child", dob: "1998-01-01"}, {relation: "child", dob: "2000-03-21"}], age: 55, monthlyRate: 42, cover: 500000, eligibleDeps: 1, monthly: 327}, + {dob: "1960-01-01", salary: 50000, enrolled: false, dependents: [], age: 65, monthlyRate: 70, cover: 150000, eligibleDeps: 0, monthly: 0}, + {dob: "1985-06-01", salary: 30000, enrolled: true, smoker: null, dependents: [{relation: "spouse", dob: "1986-01-01"}], age: 39, monthlyRate: 25, cover: 90000, eligibleDeps: 1, monthly: 34.5}, + {dob: "1995-01-01", salary: 55000, enrolled: true, smoker: false, dependents: [], age: 30, monthlyRate: 25, cover: 165000, eligibleDeps: 0, monthly: 41.25}, + ], industryLoad: 1.25, enrolledCount: 3, participation: 0.75, monthlyPremium: 503.44, employerShare: 302.06, quotable: true}}, + ], + // Two of three enrolled and a low employer contribution: not quotable. + [ + {employer: {industry: "healthcare", contribution: 0.4, employees: [ + {dob: "1999-03-21", salary: 35000, enrolled: true, dependents: []}, + {dob: "1999-03-20", salary: 35000, enrolled: true, smoker: true, dependents: []}, + {dob: "1950-01-01", salary: 10000, enrolled: false, dependents: [{relation: "spouse", dob: "1950-01-01"}]}, + ]}}, + {employer: {industry: "healthcare", contribution: 0.4, employees: [ + {dob: "1999-03-21", salary: 35000, enrolled: true, dependents: [], age: 25, monthlyRate: 18, cover: 105000, eligibleDeps: 0, monthly: 18.9}, + {dob: "1999-03-20", salary: 35000, enrolled: true, smoker: true, dependents: [], age: 26, monthlyRate: 18, cover: 105000, eligibleDeps: 0, monthly: 28.35}, + {dob: "1950-01-01", salary: 10000, enrolled: false, dependents: [{relation: "spouse", dob: "1950-01-01"}], age: 75, monthlyRate: 70, cover: 30000, eligibleDeps: 1, monthly: 0}, + ], industryLoad: 1.1, enrolledCount: 2, participation: 0.6667, monthlyPremium: 51.98, employerShare: 20.79, quotable: false}}, + ], + [ + {employer: {industry: "office", contribution: 1, employees: []}}, + {employer: {industry: "office", contribution: 1, employees: [], industryLoad: 1, enrolledCount: 0, participation: 0, monthlyPremium: 0, employerShare: 0, quotable: false}}, + ], + [ + {employer: {industry: "office", contribution: 0.5, employees: [ + {dob: "1980-01-01", salary: 100000, enrolled: true, smoker: false, dependents: [{relation: "child", dob: "2010-01-01"}, {relation: "child", dob: "2012-01-01"}, {relation: "spouse", dob: "1981-01-01"}]}, + ]}}, + {employer: {industry: "office", contribution: 0.5, employees: [ + {dob: "1980-01-01", salary: 100000, enrolled: true, smoker: false, dependents: [{relation: "child", dob: "2010-01-01"}, {relation: "child", dob: "2012-01-01"}, {relation: "spouse", dob: "1981-01-01"}], age: 45, monthlyRate: 42, cover: 300000, eligibleDeps: 3, monthly: 162}, + ], industryLoad: 1, enrolledCount: 1, participation: 1, monthlyPremium: 162, employerShare: 81, quotable: false}}, + ], + // An employee without `enrolled` reads null; the ternary on it is an error. + [{employer: {industry: "office", contribution: 0.5, employees: [{dob: "1990-01-01", salary: 60000, dependents: []}, {dob: "2000-01-01", salary: 40000, enrolled: true, dependents: []}]}}, "!error: ExpressionFailed"], + [{employer: {industry: "office", contribution: 0.5, employees: [{dob: "1990-01-01", salary: 1, enrolled: true, dependents: [{relation: "parent", dob: "1960-01-01"}]}]}}, "!error: InputValidationFailed"], + [{employer: {industry: "mining", contribution: 0.5, employees: []}}, "!error: InputValidationFailed"], + [{employer: {industry: "office", contribution: 0.5, employees: [{dob: "1990-01-01", enrolled: true, dependents: []}]}}, "!error: ExpressionFailed"], + [{employer: {industry: "office", contribution: 0.5, employees: [{dob: "1990-01-01", salary: 1, enrolled: true, dependents: [{relation: "child", dob: "2010-13-01"}]}]}}, "!error: InputValidationFailed"], + [{employer: {industry: "office", employees: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Travel quote ------------------------------------------------------------------------------ +// Trip days inclusive of both ends, traveller age at departure (a member reading a root input), a +// hazardous-activity flag against a global list, a destination region by reference, an +// acceptability assertion over all travellers and a status match. + +{ + name: "travel quote with travellers and regions", + policy: { + globals: {rules: {hazardous: "string[]", maxAge: "number"}}, + models: { + trip: {start: "date", end: "date", destination: "®ion", cancelCover: "number", travellers: "traveller[]"}, + region: {id: "string", dailyRate: "number", medicalLoad: "number"}, + traveller: {dob: "date", activities: "string[]", preexisting: "boolean"}, + }, + blocks: [ + {expression: "trip.days", value: "trip.end.diff(trip.start, 'day') + 1"}, + {expression: "traveller.age", value: "trip.start.diff(traveller.dob, 'year')"}, + {match: "traveller.ageFactor", arms: [ + ["traveller.age < 18", "0.5"], + ["traveller.age >= 65", "2"], + ["", "1"], + ]}, + {expression: "traveller.hazard", value: "some(traveller.activities, # in hazardous)"}, + {expression: "traveller.premium", value: "round(trip.days * trip.destination.dailyRate * traveller.ageFactor * (traveller.preexisting ? trip.destination.medicalLoad : 1) * (traveller.hazard ? 1.5 : 1), 2)"}, + {expression: "trip.cancellation", value: "round(trip.cancelCover * 0.04, 2)"}, + {expression: "trip.total", value: "sum(map(trip.travellers, #.premium)) + trip.cancellation"}, + {assertion: "trip.acceptable", conditions: ["trip.days >= 1", "trip.days <= 90", "len(trip.travellers) > 0", "all(trip.travellers, #.age <= maxAge)"]}, + {match: "trip.status", arms: [ + ["not trip.acceptable", "'decline'"], + ["some(trip.travellers, #.hazard)", "'refer-activities'"], + ["", "'issue'"], + ]}, + ], + }, + cases: [ + [ + {hazardous: ["skiing", "diving", "climbing"], maxAge: 80, trip: {start: "2025-04-01", end: "2025-04-10", destination: "EU", cancelCover: 2000, travellers: [ + {dob: "1985-01-01", activities: ["hiking"], preexisting: false}, + {dob: "2015-06-01", activities: [], preexisting: false}, + ]}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, {id: "WW", dailyRate: 5, medicalLoad: 2}]}, + {hazardous: ["skiing", "diving", "climbing"], maxAge: 80, trip: {start: "2025-04-01", end: "2025-04-10", destination: {id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, cancelCover: 2000, travellers: [ + {dob: "1985-01-01", activities: ["hiking"], preexisting: false, age: 40, ageFactor: 1, hazard: false, premium: 25}, + {dob: "2015-06-01", activities: [], preexisting: false, age: 9, ageFactor: 0.5, hazard: false, premium: 12.5}, + ], days: 10, cancellation: 80, total: 117.5, acceptable: true, status: "issue"}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, {id: "WW", dailyRate: 5, medicalLoad: 2}]}, + ], + // A senior diver with a pre-existing condition worldwide: every factor multiplies. + [ + {hazardous: ["skiing", "diving", "climbing"], maxAge: 80, trip: {start: "2025-05-01", end: "2025-05-21", destination: "WW", cancelCover: 0, travellers: [ + {dob: "1955-05-02", activities: ["diving", "museum"], preexisting: true}, + ]}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, {id: "WW", dailyRate: 5, medicalLoad: 2}]}, + {hazardous: ["skiing", "diving", "climbing"], maxAge: 80, trip: {start: "2025-05-01", end: "2025-05-21", destination: {id: "WW", dailyRate: 5, medicalLoad: 2}, cancelCover: 0, travellers: [ + {dob: "1955-05-02", activities: ["diving", "museum"], preexisting: true, age: 69, ageFactor: 2, hazard: true, premium: 630}, + ], days: 21, cancellation: 0, total: 630, acceptable: true, status: "refer-activities"}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, {id: "WW", dailyRate: 5, medicalLoad: 2}]}, + ], + // 91 days is one too many. + [ + {hazardous: [], maxAge: 80, trip: {start: "2025-01-01", end: "2025-04-01", destination: "EU", cancelCover: 1000, travellers: [{dob: "1990-01-01", activities: [], preexisting: false}]}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + {hazardous: [], maxAge: 80, trip: {start: "2025-01-01", end: "2025-04-01", destination: {id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, cancelCover: 1000, travellers: [ + {dob: "1990-01-01", activities: [], preexisting: false, age: 35, ageFactor: 1, hazard: false, premium: 227.5}, + ], days: 91, cancellation: 40, total: 267.5, acceptable: false, status: "decline"}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + ], + // 90 days and a traveller of exactly the maximum age are accepted. + [ + {hazardous: [], maxAge: 80, trip: {start: "2025-01-01", end: "2025-03-31", destination: "EU", cancelCover: 0, travellers: [{dob: "1945-01-01", activities: [], preexisting: true}]}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + {hazardous: [], maxAge: 80, trip: {start: "2025-01-01", end: "2025-03-31", destination: {id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, cancelCover: 0, travellers: [ + {dob: "1945-01-01", activities: [], preexisting: true, age: 80, ageFactor: 2, hazard: false, premium: 630}, + ], days: 90, cancellation: 0, total: 630, acceptable: true, status: "issue"}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + ], + // One traveller over the maximum age declines the whole trip; the child is priced at half. + [ + {hazardous: ["skiing"], maxAge: 80, trip: {start: "2025-06-01", end: "2025-06-07", destination: "WW", cancelCover: 500, travellers: [ + {dob: "1944-06-01", activities: [], preexisting: false}, + {dob: "2010-06-02", activities: ["skiing"], preexisting: false}, + ]}, region: [{id: "WW", dailyRate: 5, medicalLoad: 2}]}, + {hazardous: ["skiing"], maxAge: 80, trip: {start: "2025-06-01", end: "2025-06-07", destination: {id: "WW", dailyRate: 5, medicalLoad: 2}, cancelCover: 500, travellers: [ + {dob: "1944-06-01", activities: [], preexisting: false, age: 81, ageFactor: 2, hazard: false, premium: 70}, + {dob: "2010-06-02", activities: ["skiing"], preexisting: false, age: 14, ageFactor: 0.5, hazard: true, premium: 26.25}, + ], days: 7, cancellation: 20, total: 116.25, acceptable: false, status: "decline"}, region: [{id: "WW", dailyRate: 5, medicalLoad: 2}]}, + ], + [ + {hazardous: [], maxAge: 80, trip: {start: "2025-04-01", end: "2025-04-01", destination: "EU", cancelCover: 0, travellers: []}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + {hazardous: [], maxAge: 80, trip: {start: "2025-04-01", end: "2025-04-01", destination: {id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, cancelCover: 0, travellers: [], days: 1, cancellation: 0, total: 0, acceptable: false, status: "decline"}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + ], + // With an empty hazardous list no activity is hazardous. + [ + {hazardous: [], maxAge: 99, trip: {start: "2025-04-01", end: "2025-04-02", destination: "EU", cancelCover: 12.5, travellers: [{dob: "2000-04-01", activities: ["skiing"], preexisting: false}]}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + {hazardous: [], maxAge: 99, trip: {start: "2025-04-01", end: "2025-04-02", destination: {id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, cancelCover: 12.5, travellers: [ + {dob: "2000-04-01", activities: ["skiing"], preexisting: false, age: 25, ageFactor: 1, hazard: false, premium: 5}, + ], days: 2, cancellation: 0.5, total: 5.5, acceptable: true, status: "issue"}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + ], + // An end date before the start: negative days, declined. + [ + {hazardous: [], maxAge: 80, trip: {start: "2025-04-10", end: "2025-04-01", destination: "EU", cancelCover: 0, travellers: [{dob: "1995-01-01", activities: [], preexisting: false}]}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + {hazardous: [], maxAge: 80, trip: {start: "2025-04-10", end: "2025-04-01", destination: {id: "EU", dailyRate: 2.5, medicalLoad: 1.4}, cancelCover: 0, travellers: [ + {dob: "1995-01-01", activities: [], preexisting: false, age: 30, ageFactor: 1, hazard: false, premium: -20}, + ], days: -8, cancellation: 0, total: -20, acceptable: false, status: "decline"}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, + ], + [{hazardous: [], maxAge: 80, trip: {start: "2025-04-01", end: "2025-04-02", destination: "ASIA", cancelCover: 0, travellers: []}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, "!error: InputValidationFailed"], + [{hazardous: [], maxAge: 80, trip: {start: "2025-04-01", end: "2025-04-02", destination: "EU", cancelCover: 0, travellers: [{dob: "1990-01-01", activities: "skiing", preexisting: false}]}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, "!error: InputValidationFailed"], + [{hazardous: [], trip: {start: "2025-04-01", end: "2025-04-02", destination: "EU", cancelCover: 0, travellers: []}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, "!error: MissingRequiredInputs"], + [{hazardous: [1, 2], maxAge: 80, trip: {start: "2025-04-01", end: "2025-04-02", destination: "EU", cancelCover: 0, travellers: []}, region: [{id: "EU", dailyRate: 2.5, medicalLoad: 1.4}]}, "!error: InputValidationFailed"], + ], +} + +// --- Telematics fleet scoring ------------------------------------------------------------------ +// Vehicles are members with trips read through closures. Per-vehicle rates per 100 km and night +// share guard against zero distance, flags come from a per-vehicle first-hit table with a `[]` +// column, the score is clamped at zero, the band match separates vehicles without data, and the +// fleet discount uses the average over vehicles that drove. + +{ + name: "telematics fleet scoring", + policy: { + models: { + fleet: {basePremium: "number", vehicles: "vehicle[]"}, + vehicle: {plate: "string", trips: "trip[]"}, + trip: {km: "number", harshBrakes: "number", nightKm: "number?", maxSpeed: "number"}, + }, + blocks: [ + {expression: "vehicle.km", value: "sum(map(vehicle.trips, #.km))"}, + {expression: "vehicle.brakesPer100", value: "vehicle.km > 0 ? round(sum(map(vehicle.trips, #.harshBrakes)) / vehicle.km * 100, 2) : 0"}, + {expression: "vehicle.nightShare", value: "vehicle.km > 0 ? round(sum(map(vehicle.trips, #.nightKm ?? 0)) / vehicle.km, 2) : 0"}, + {expression: "vehicle.speedingTrips", value: "count(vehicle.trips, #.maxSpeed > 130)"}, + {table: "flags", inputs: ["vehicle.brakesPer100", "vehicle.nightShare"], outputs: ["vehicle.flags[]"], rules: [ + ["> 5", "", "'harsh-braking'"], + ["", "> 0.3", "'night-driving'"], + ]}, + {expression: "vehicle.score", value: "max([100 - vehicle.brakesPer100 * 4 - vehicle.nightShare * 50 - vehicle.speedingTrips * 10, 0])"}, + {match: "vehicle.band", arms: [ + ["vehicle.km == 0", "'no-data'"], + ["vehicle.score >= 80", "'A'"], + ["vehicle.score >= 60", "'B'"], + ["", "'C'"], + ]}, + {expression: "fleet.avgScore", value: "count(fleet.vehicles, #.km > 0) == 0 ? 0 : avg(map(filter(fleet.vehicles, #.km > 0), #.score))"}, + {match: "fleet.discount", arms: [ + ["fleet.avgScore >= 85", "0.2"], + ["fleet.avgScore >= 70", "0.1"], + ["", "0"], + ]}, + {expression: "fleet.premium", value: "round(fleet.basePremium * len(fleet.vehicles) * (1 - fleet.discount), 2)"}, + ], + }, + cases: [ + [ + {fleet: {basePremium: 1000, vehicles: [{plate: "A", trips: [{km: 100, harshBrakes: 2, nightKm: 20, maxSpeed: 120}, {km: 300, harshBrakes: 4, maxSpeed: 135}]}]}}, + {fleet: {basePremium: 1000, vehicles: [ + {plate: "A", trips: [{km: 100, harshBrakes: 2, nightKm: 20, maxSpeed: 120}, {km: 300, harshBrakes: 4, maxSpeed: 135}], km: 400, brakesPer100: 1.5, nightShare: 0.05, speedingTrips: 1, flags: [], score: 81.5, band: "A"}, + ], avgScore: 81.5, discount: 0.1, premium: 900}}, + ], + // A vehicle without trips has no data and is left out of the average. + [ + {fleet: {basePremium: 1000, vehicles: [{plate: "A", trips: [{km: 50, harshBrakes: 5, nightKm: 30, maxSpeed: 100}]}, {plate: "B", trips: []}]}}, + {fleet: {basePremium: 1000, vehicles: [ + {plate: "A", trips: [{km: 50, harshBrakes: 5, nightKm: 30, maxSpeed: 100}], km: 50, brakesPer100: 10, nightShare: 0.6, speedingTrips: 0, flags: ["harsh-braking", "night-driving"], score: 30, band: "C"}, + {plate: "B", trips: [], km: 0, brakesPer100: 0, nightShare: 0, speedingTrips: 0, flags: [], score: 100, band: "no-data"}, + ], avgScore: 30, discount: 0, premium: 2000}}, + ], + [ + {fleet: {basePremium: 500, vehicles: [ + {plate: "A", trips: [{km: 1000, harshBrakes: 0, nightKm: 0, maxSpeed: 110}]}, + {plate: "B", trips: [{km: 500, harshBrakes: 5, nightKm: null, maxSpeed: 131}]}, + ]}}, + {fleet: {basePremium: 500, vehicles: [ + {plate: "A", trips: [{km: 1000, harshBrakes: 0, nightKm: 0, maxSpeed: 110}], km: 1000, brakesPer100: 0, nightShare: 0, speedingTrips: 0, flags: [], score: 100, band: "A"}, + {plate: "B", trips: [{km: 500, harshBrakes: 5, nightKm: null, maxSpeed: 131}], km: 500, brakesPer100: 1, nightShare: 0, speedingTrips: 1, flags: [], score: 86, band: "A"}, + ], avgScore: 93, discount: 0.2, premium: 800}}, + ], + [ + {fleet: {basePremium: 750, vehicles: []}}, + {fleet: {basePremium: 750, vehicles: [], avgScore: 0, discount: 0, premium: 0}}, + ], + // Thresholds are strict: 5 brakes per 100 km, a night share of 0.3 and 130 km/h raise nothing. + [ + {fleet: {basePremium: 1200, vehicles: [{plate: "A", trips: [{km: 100, harshBrakes: 5, nightKm: 30, maxSpeed: 130}]}]}}, + {fleet: {basePremium: 1200, vehicles: [ + {plate: "A", trips: [{km: 100, harshBrakes: 5, nightKm: 30, maxSpeed: 130}], km: 100, brakesPer100: 5, nightShare: 0.3, speedingTrips: 0, flags: [], score: 65, band: "B"}, + ], avgScore: 65, discount: 0, premium: 1200}}, + ], + [ + {fleet: {basePremium: 100, vehicles: [{plate: "A", trips: [{km: 10, harshBrakes: 10, nightKm: 10, maxSpeed: 200}]}]}}, + {fleet: {basePremium: 100, vehicles: [ + {plate: "A", trips: [{km: 10, harshBrakes: 10, nightKm: 10, maxSpeed: 200}], km: 10, brakesPer100: 100, nightShare: 1, speedingTrips: 1, flags: ["harsh-braking", "night-driving"], score: 0, band: "C"}, + ], avgScore: 0, discount: 0, premium: 100}}, + ], + // An average of exactly 70 earns the lower discount. + [ + {fleet: {basePremium: 1000, vehicles: [ + {plate: "A", trips: [{km: 100, harshBrakes: 10, nightKm: 0, maxSpeed: 100}]}, + {plate: "B", trips: [{km: 60, harshBrakes: 1, maxSpeed: 90}, {km: 40, harshBrakes: 4, maxSpeed: 95}]}, + ]}}, + {fleet: {basePremium: 1000, vehicles: [ + {plate: "A", trips: [{km: 100, harshBrakes: 10, nightKm: 0, maxSpeed: 100}], km: 100, brakesPer100: 10, nightShare: 0, speedingTrips: 0, flags: ["harsh-braking"], score: 60, band: "B"}, + {plate: "B", trips: [{km: 60, harshBrakes: 1, maxSpeed: 90}, {km: 40, harshBrakes: 4, maxSpeed: 95}], km: 100, brakesPer100: 5, nightShare: 0, speedingTrips: 0, flags: [], score: 80, band: "A"}, + ], avgScore: 70, discount: 0.1, premium: 1800}}, + ], + [{fleet: {basePremium: 1, vehicles: [{plate: "A", trips: [{harshBrakes: 1, maxSpeed: 100}]}]}}, "!error: ExpressionFailed"], + [{fleet: {basePremium: 1, vehicles: [{plate: "A", trips: "none"}]}}, "!error: InputValidationFailed"], + [{fleet: {vehicles: []}}, "!error: MissingRequiredInputs"], + [{fleet: {basePremium: 1, vehicles: [{plate: "A", trips: [{km: 1, harshBrakes: "many", maxSpeed: 100}]}]}}, "!error: InputValidationFailed"], + ], +} diff --git a/core/engine/tests/spec/policy/42-realistic-payroll-hr.json5 b/core/engine/tests/spec/policy/42-realistic-payroll-hr.json5 new file mode 100644 index 00000000..51c3ed65 --- /dev/null +++ b/core/engine/tests/spec/policy/42-realistic-payroll-hr.json5 @@ -0,0 +1,664 @@ +// Realistic payroll and HR policies: timesheets with overtime and weekend premiums, net pay with +// pension, benefits, progressive tax and garnishments, leave balances with request states, +// approval routing by referenced staff, a department payroll run against globals, and bonuses +// by referenced grades with goals. Each suite combines several block kinds over related +// entities and runs valid, boundary, missing and invalid data. Evaluation time is fixed at +// 2025-03-20T10:15:30Z (a Thursday); 2025-03-01 is a Saturday. + +// --- Timesheets and overtime ------------------------------------------------------------------- +// Per-entry weekend and long-shift flags (weekday 6 and 7 are the weekend), per-kind hour sums +// on the employee, overtime above the contract, an overtime multiplier table where managers are +// first-hit exempt, and pay components rounded separately. + +{ + name: "timesheets with overtime and weekend premiums", + policy: { + models: { + employee: {grade: "string(staff|senior|manager)", hourlyRate: "number", contractHours: "number", entries: "entry[]"}, + entry: {date: "date", hours: "number", kind: "string(work|sick|vacation|holiday)"}, + }, + blocks: [ + {expression: "entry.weekend", value: "entry.date.weekday() >= 6"}, + {expression: "entry.long", value: "entry.hours > 10"}, + {expression: "employee.worked", value: "sum(map(filter(employee.entries, #.kind == 'work'), #.hours))"}, + {expression: "employee.weekendHours", value: "sum(map(filter(employee.entries, #.kind == 'work' and #.weekend), #.hours))"}, + {expression: "employee.paidLeave", value: "sum(map(filter(employee.entries, #.kind in ['vacation', 'holiday']), #.hours))"}, + {expression: "employee.sickHours", value: "sum(map(filter(employee.entries, #.kind == 'sick'), #.hours))"}, + {expression: "employee.overtime", value: "max([employee.worked - employee.contractHours, 0])"}, + {table: "otRate", inputs: ["employee.grade", "employee.overtime"], outputs: ["employee.otRate"], rules: [ + ["'manager'", "", "1"], + ["", "> 20", "2"], + ["", "", "1.5"], + ]}, + {expression: "employee.basePay", value: "round((min([employee.worked, employee.contractHours]) + employee.paidLeave) * employee.hourlyRate, 2)"}, + {expression: "employee.otPay", value: "round(employee.overtime * employee.hourlyRate * employee.otRate, 2)"}, + {expression: "employee.weekendPremium", value: "round(employee.weekendHours * employee.hourlyRate * 0.25, 2)"}, + {expression: "employee.sickPay", value: "round(employee.sickHours * employee.hourlyRate * 0.8, 2)"}, + {expression: "employee.gross", value: "employee.basePay + employee.otPay + employee.weekendPremium + employee.sickPay"}, + {match: "employee.flag", arms: [ + ["employee.overtime > 40", "'overtime-breach'"], + ["some(employee.entries, #.long)", "'long-shift'"], + ["", "'ok'"], + ]}, + ], + }, + cases: [ + [ + {employee: {grade: "staff", hourlyRate: 20, contractHours: 16, entries: [{date: "2025-03-03", hours: 8, kind: "work"}, {date: "2025-03-04", hours: 8, kind: "work"}]}}, + {employee: {grade: "staff", hourlyRate: 20, contractHours: 16, entries: [ + {date: "2025-03-03", hours: 8, kind: "work", weekend: false, long: false}, + {date: "2025-03-04", hours: 8, kind: "work", weekend: false, long: false}, + ], worked: 16, weekendHours: 0, paidLeave: 0, sickHours: 0, overtime: 0, otRate: 1.5, basePay: 320, otPay: 0, weekendPremium: 0, sickPay: 0, gross: 320, flag: "ok"}}, + ], + [ + {employee: {grade: "senior", hourlyRate: 30, contractHours: 16, entries: [ + {date: "2025-03-03", hours: 10, kind: "work"}, + {date: "2025-03-04", hours: 11, kind: "work"}, + {date: "2025-03-08", hours: 6, kind: "work"}, + ]}}, + {employee: {grade: "senior", hourlyRate: 30, contractHours: 16, entries: [ + {date: "2025-03-03", hours: 10, kind: "work", weekend: false, long: false}, + {date: "2025-03-04", hours: 11, kind: "work", weekend: false, long: true}, + {date: "2025-03-08", hours: 6, kind: "work", weekend: true, long: false}, + ], worked: 27, weekendHours: 6, paidLeave: 0, sickHours: 0, overtime: 11, otRate: 1.5, basePay: 480, otPay: 495, weekendPremium: 45, sickPay: 0, gross: 1020, flag: "long-shift"}}, + ], + // Managers get straight time for overtime, even above 20 hours. + [ + {employee: {grade: "manager", hourlyRate: 50, contractHours: 8, entries: [ + {date: "2025-03-03", hours: 10, kind: "work"}, + {date: "2025-03-04", hours: 10, kind: "work"}, + {date: "2025-03-05", hours: 10, kind: "work"}, + ]}}, + {employee: {grade: "manager", hourlyRate: 50, contractHours: 8, entries: [ + {date: "2025-03-03", hours: 10, kind: "work", weekend: false, long: false}, + {date: "2025-03-04", hours: 10, kind: "work", weekend: false, long: false}, + {date: "2025-03-05", hours: 10, kind: "work", weekend: false, long: false}, + ], worked: 30, weekendHours: 0, paidLeave: 0, sickHours: 0, overtime: 22, otRate: 1, basePay: 400, otPay: 1100, weekendPremium: 0, sickPay: 0, gross: 1500, flag: "ok"}}, + ], + // A casual worker with no contract hours: every hour is overtime, above 20 at double rate. + [ + {employee: {grade: "staff", hourlyRate: 15, contractHours: 0, entries: [ + {date: "2025-03-01", hours: 9, kind: "work"}, + {date: "2025-03-02", hours: 9, kind: "work"}, + {date: "2025-03-03", hours: 5, kind: "work"}, + ]}}, + {employee: {grade: "staff", hourlyRate: 15, contractHours: 0, entries: [ + {date: "2025-03-01", hours: 9, kind: "work", weekend: true, long: false}, + {date: "2025-03-02", hours: 9, kind: "work", weekend: true, long: false}, + {date: "2025-03-03", hours: 5, kind: "work", weekend: false, long: false}, + ], worked: 23, weekendHours: 18, paidLeave: 0, sickHours: 0, overtime: 23, otRate: 2, basePay: 0, otPay: 690, weekendPremium: 67.5, sickPay: 0, gross: 757.5, flag: "ok"}}, + ], + [ + {employee: {grade: "staff", hourlyRate: 22.5, contractHours: 24, entries: [ + {date: "2025-03-10", hours: 8, kind: "vacation"}, + {date: "2025-03-11", hours: 8, kind: "holiday"}, + {date: "2025-03-12", hours: 7.5, kind: "sick"}, + {date: "2025-03-13", hours: 8, kind: "work"}, + ]}}, + {employee: {grade: "staff", hourlyRate: 22.5, contractHours: 24, entries: [ + {date: "2025-03-10", hours: 8, kind: "vacation", weekend: false, long: false}, + {date: "2025-03-11", hours: 8, kind: "holiday", weekend: false, long: false}, + {date: "2025-03-12", hours: 7.5, kind: "sick", weekend: false, long: false}, + {date: "2025-03-13", hours: 8, kind: "work", weekend: false, long: false}, + ], worked: 8, weekendHours: 0, paidLeave: 16, sickHours: 7.5, overtime: 0, otRate: 1.5, basePay: 540, otPay: 0, weekendPremium: 0, sickPay: 135, gross: 675, flag: "ok"}}, + ], + [ + {employee: {grade: "senior", hourlyRate: 10, contractHours: 0, entries: [ + {date: "2025-03-03", hours: 9, kind: "work"}, + {date: "2025-03-04", hours: 9, kind: "work"}, + {date: "2025-03-05", hours: 9, kind: "work"}, + {date: "2025-03-06", hours: 9, kind: "work"}, + {date: "2025-03-07", hours: 9, kind: "work"}, + ]}}, + {employee: {grade: "senior", hourlyRate: 10, contractHours: 0, entries: [ + {date: "2025-03-03", hours: 9, kind: "work", weekend: false, long: false}, + {date: "2025-03-04", hours: 9, kind: "work", weekend: false, long: false}, + {date: "2025-03-05", hours: 9, kind: "work", weekend: false, long: false}, + {date: "2025-03-06", hours: 9, kind: "work", weekend: false, long: false}, + {date: "2025-03-07", hours: 9, kind: "work", weekend: false, long: false}, + ], worked: 45, weekendHours: 0, paidLeave: 0, sickHours: 0, overtime: 45, otRate: 2, basePay: 0, otPay: 900, weekendPremium: 0, sickPay: 0, gross: 900, flag: "overtime-breach"}}, + ], + // Exactly 20 overtime hours stay at time and a half; 10 hours is not a long shift. + [ + {employee: {grade: "staff", hourlyRate: 10, contractHours: 10, entries: [ + {date: "2025-03-03", hours: 10, kind: "work"}, + {date: "2025-03-04", hours: 10, kind: "work"}, + {date: "2025-03-05", hours: 10, kind: "work"}, + ]}}, + {employee: {grade: "staff", hourlyRate: 10, contractHours: 10, entries: [ + {date: "2025-03-03", hours: 10, kind: "work", weekend: false, long: false}, + {date: "2025-03-04", hours: 10, kind: "work", weekend: false, long: false}, + {date: "2025-03-05", hours: 10, kind: "work", weekend: false, long: false}, + ], worked: 30, weekendHours: 0, paidLeave: 0, sickHours: 0, overtime: 20, otRate: 1.5, basePay: 100, otPay: 300, weekendPremium: 0, sickPay: 0, gross: 400, flag: "ok"}}, + ], + [ + {employee: {grade: "staff", hourlyRate: 20, contractHours: 40, entries: []}}, + {employee: {grade: "staff", hourlyRate: 20, contractHours: 40, entries: [], worked: 0, weekendHours: 0, paidLeave: 0, sickHours: 0, overtime: 0, otRate: 1.5, basePay: 0, otPay: 0, weekendPremium: 0, sickPay: 0, gross: 0, flag: "ok"}}, + ], + // Weekend vacation earns no weekend premium; weekend work does. + [ + {employee: {grade: "staff", hourlyRate: 20, contractHours: 8, entries: [{date: "2025-03-15", hours: 8, kind: "vacation"}, {date: "2025-03-16", hours: 12, kind: "work"}]}}, + {employee: {grade: "staff", hourlyRate: 20, contractHours: 8, entries: [ + {date: "2025-03-15", hours: 8, kind: "vacation", weekend: true, long: false}, + {date: "2025-03-16", hours: 12, kind: "work", weekend: true, long: true}, + ], worked: 12, weekendHours: 12, paidLeave: 8, sickHours: 0, overtime: 4, otRate: 1.5, basePay: 320, otPay: 120, weekendPremium: 60, sickPay: 0, gross: 500, flag: "long-shift"}}, + ], + [{employee: {grade: "staff", hourlyRate: 20, contractHours: 8, entries: [{date: "2025-03-03", hours: 8, kind: "training"}]}}, "!error: InputValidationFailed"], + [{employee: {grade: "staff", hourlyRate: 20, contractHours: 8, entries: [{date: "2025-03-03", kind: "work"}]}}, "!error: ExpressionFailed"], + [{employee: {grade: "intern", hourlyRate: 20, contractHours: 8, entries: []}}, "!error: InputValidationFailed"], + [{employee: {grade: "staff", hourlyRate: 20, entries: []}}, "!error: MissingRequiredInputs"], + [{employee: {grade: "staff", hourlyRate: 20, contractHours: 8, entries: [{date: "03/03/2025", hours: 8, kind: "work"}]}}, "!error: InputValidationFailed"], + ], +} + +// --- Net pay ----------------------------------------------------------------------------------- +// Pre-tax and post-tax benefits split by a member flag, pension as a percentage, a progressive +// tax table with two outputs (rate and relief) and a reduced table that wins first, capped union +// dues, an optional garnishment, a payability assertion and a release match. Goals compute only +// the requested deduction. + +{ + name: "net pay with deductions and progressive tax", + policy: { + models: { + employee: {gross: "number", pensionPct: "number", unionMember: "boolean", taxTable: "string(standard|reduced)", garnishment: "number?", benefits: "benefit[]"}, + benefit: {kind: "string(health|dental|gym|transit)", monthlyCost: "number", pretax: "boolean"}, + }, + blocks: [ + {expression: "employee.pretaxBenefits", value: "sum(map(filter(employee.benefits, #.pretax), #.monthlyCost))"}, + {expression: "employee.postTaxBenefits", value: "sum(map(filter(employee.benefits, not #.pretax), #.monthlyCost))"}, + {expression: "employee.pension", value: "round(employee.gross * employee.pensionPct / 100, 2)"}, + {expression: "employee.taxable", value: "max([employee.gross - employee.pension - employee.pretaxBenefits, 0])"}, + {table: "tax", inputs: ["employee.taxTable", "employee.taxable"], outputs: ["employee.taxRate", "employee.relief"], rules: [ + ["'reduced'", "", "0.15", "0"], + ["", "<= 3000", "0.2", "0"], + ["", "<= 6000", "0.3", "300"], + ["", "", "0.4", "900"], + ]}, + {expression: "employee.tax", value: "max([round(employee.taxable * employee.taxRate - employee.relief, 2), 0])"}, + {expression: "employee.unionDues", value: "employee.unionMember ? min([round(employee.gross * 0.01, 2), 40]) : 0"}, + {expression: "employee.net", value: "round(employee.gross - employee.pension - employee.pretaxBenefits - employee.tax - employee.unionDues - employee.postTaxBenefits - (employee.garnishment ?? 0), 2)"}, + {assertion: "employee.payable", conditions: ["employee.net >= 0", "employee.pensionPct <= 15"]}, + {match: "employee.status", arms: [ + ["not employee.payable", "'hold'"], + ["employee.net < employee.gross * 0.5", "'review'"], + ["", "'release'"], + ]}, + ], + }, + cases: [ + [ + {employee: {gross: 2500, pensionPct: 5, unionMember: false, taxTable: "standard", benefits: []}}, + {employee: {gross: 2500, pensionPct: 5, unionMember: false, taxTable: "standard", benefits: [], pretaxBenefits: 0, postTaxBenefits: 0, pension: 125, taxable: 2375, taxRate: 0.2, relief: 0, tax: 475, unionDues: 0, net: 1900, payable: true, status: "release"}}, + ], + [ + {employee: {gross: 5000, pensionPct: 6, unionMember: true, taxTable: "standard", benefits: [{kind: "health", monthlyCost: 200, pretax: true}, {kind: "gym", monthlyCost: 50, pretax: false}]}}, + {employee: {gross: 5000, pensionPct: 6, unionMember: true, taxTable: "standard", benefits: [{kind: "health", monthlyCost: 200, pretax: true}, {kind: "gym", monthlyCost: 50, pretax: false}], + pretaxBenefits: 200, postTaxBenefits: 50, pension: 300, taxable: 4500, taxRate: 0.3, relief: 300, tax: 1050, unionDues: 40, net: 3360, payable: true, status: "release"}}, + ], + // Top bracket and a garnishment push net pay under half of gross. + [ + {employee: {gross: 10000, pensionPct: 10, unionMember: true, taxTable: "standard", garnishment: 1500, benefits: [ + {kind: "health", monthlyCost: 300, pretax: true}, + {kind: "dental", monthlyCost: 100, pretax: true}, + {kind: "transit", monthlyCost: 80, pretax: false}, + ]}}, + {employee: {gross: 10000, pensionPct: 10, unionMember: true, taxTable: "standard", garnishment: 1500, benefits: [ + {kind: "health", monthlyCost: 300, pretax: true}, + {kind: "dental", monthlyCost: 100, pretax: true}, + {kind: "transit", monthlyCost: 80, pretax: false}, + ], pretaxBenefits: 400, postTaxBenefits: 80, pension: 1000, taxable: 8600, taxRate: 0.4, relief: 900, tax: 2540, unionDues: 40, net: 4440, payable: true, status: "review"}}, + ], + [ + {employee: {gross: 3000, pensionPct: 0, unionMember: true, taxTable: "reduced", benefits: []}}, + {employee: {gross: 3000, pensionPct: 0, unionMember: true, taxTable: "reduced", benefits: [], pretaxBenefits: 0, postTaxBenefits: 0, pension: 0, taxable: 3000, taxRate: 0.15, relief: 0, tax: 450, unionDues: 30, net: 2520, payable: true, status: "release"}}, + ], + // Bracket edges are inclusive. + [ + {employee: {gross: 3000, pensionPct: 0, unionMember: false, taxTable: "standard", benefits: []}}, + {employee: {gross: 3000, pensionPct: 0, unionMember: false, taxTable: "standard", benefits: [], pretaxBenefits: 0, postTaxBenefits: 0, pension: 0, taxable: 3000, taxRate: 0.2, relief: 0, tax: 600, unionDues: 0, net: 2400, payable: true, status: "release"}}, + ], + [ + {employee: {gross: 6000, pensionPct: 0, unionMember: false, taxTable: "standard", benefits: []}}, + {employee: {gross: 6000, pensionPct: 0, unionMember: false, taxTable: "standard", benefits: [], pretaxBenefits: 0, postTaxBenefits: 0, pension: 0, taxable: 6000, taxRate: 0.3, relief: 300, tax: 1500, unionDues: 0, net: 4500, payable: true, status: "release"}}, + ], + [ + {employee: {gross: 1000, pensionPct: 0, unionMember: false, taxTable: "standard", garnishment: 900, benefits: []}}, + {employee: {gross: 1000, pensionPct: 0, unionMember: false, taxTable: "standard", garnishment: 900, benefits: [], pretaxBenefits: 0, postTaxBenefits: 0, pension: 0, taxable: 1000, taxRate: 0.2, relief: 0, tax: 200, unionDues: 0, net: -100, payable: false, status: "hold"}}, + ], + [ + {employee: {gross: 2000, pensionPct: 20, unionMember: false, taxTable: "standard", benefits: []}}, + {employee: {gross: 2000, pensionPct: 20, unionMember: false, taxTable: "standard", benefits: [], pretaxBenefits: 0, postTaxBenefits: 0, pension: 400, taxable: 1600, taxRate: 0.2, relief: 0, tax: 320, unionDues: 0, net: 1280, payable: false, status: "hold"}}, + ], + // Pre-tax benefits above gross: taxable income is floored at zero, net pay is negative. + [ + {employee: {gross: 100, pensionPct: 0, unionMember: false, taxTable: "standard", benefits: [{kind: "health", monthlyCost: 150, pretax: true}]}}, + {employee: {gross: 100, pensionPct: 0, unionMember: false, taxTable: "standard", benefits: [{kind: "health", monthlyCost: 150, pretax: true}], pretaxBenefits: 150, postTaxBenefits: 0, pension: 0, taxable: 0, taxRate: 0.2, relief: 0, tax: 0, unionDues: 0, net: -50, payable: false, status: "hold"}}, + ], + [ + {employee: {gross: 1234.56, pensionPct: 3.5, unionMember: true, taxTable: "standard", garnishment: null, benefits: []}}, + {employee: {gross: 1234.56, pensionPct: 3.5, unionMember: true, taxTable: "standard", garnishment: null, benefits: [], pretaxBenefits: 0, postTaxBenefits: 0, pension: 43.21, taxable: 1191.35, taxRate: 0.2, relief: 0, tax: 238.27, unionDues: 12.35, net: 940.73, payable: true, status: "release"}}, + ], + {input: {employee: {gross: 4000, pensionPct: 7.5}}, goals: ["employee.pension"], output: {employee: {gross: 4000, pensionPct: 7.5, pension: 300}}}, + {input: {employee: {gross: 6000, unionMember: true}}, goals: ["employee.unionDues"], output: {employee: {gross: 6000, unionMember: true, unionDues: 40}}}, + {input: {employee: {gross: 6000}}, goals: ["employee.unionDues"], output: "!error: MissingRequiredInputs"}, + [{employee: {gross: 1, pensionPct: 0, unionMember: false, taxTable: "standard", benefits: [{kind: "pet", monthlyCost: 1, pretax: true}]}}, "!error: InputValidationFailed"], + [{employee: {gross: 1, pensionPct: 0, unionMember: false, taxTable: "standard", benefits: [{kind: "gym", monthlyCost: 1}]}}, "!error: ExpressionFailed"], + [{employee: {gross: 1, pensionPct: 0, unionMember: false, benefits: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Leave balances ---------------------------------------------------------------------------- +// Entitlement from a tenure and full-time table, per-request day counts (inclusive) and a +// three-state match over an optional approval flag, balances with a carry-over cap, a booking +// assertion with a probation period, and an alert match. + +{ + name: "leave balances and request states", + policy: { + models: { + employee: {hired: "date", fullTime: "boolean", carryOver: "number", requests: "request[]"}, + request: {kind: "string(vacation|sick|parental|unpaid)", start: "date", end: "date", approved: "boolean?"}, + }, + blocks: [ + {expression: "employee.tenureYears", value: "d().diff(employee.hired, 'year')"}, + {expression: "employee.onProbation", value: "d().diff(employee.hired, 'month') < 6"}, + {table: "entitlement", inputs: ["employee.tenureYears", "employee.fullTime"], outputs: ["employee.annualDays"], rules: [ + [">= 10", "true", "30"], + [">= 5", "true", "27"], + ["", "true", "25"], + ["", "false", "15"], + ]}, + {expression: "request.days", value: "request.end.diff(request.start, 'day') + 1"}, + {match: "request.state", arms: [ + ["request.approved == true", "'approved'"], + ["request.approved == false", "'rejected'"], + ["", "'pending'"], + ]}, + {expression: "employee.vacationTaken", value: "sum(map(filter(employee.requests, #.kind == 'vacation' and #.state == 'approved'), #.days))"}, + {expression: "employee.vacationPending", value: "sum(map(filter(employee.requests, #.kind == 'vacation' and #.state == 'pending'), #.days))"}, + {expression: "employee.sickDays", value: "sum(map(filter(employee.requests, #.kind == 'sick' and #.state != 'rejected'), #.days))"}, + {expression: "employee.balance", value: "employee.annualDays + min([employee.carryOver, 5]) - employee.vacationTaken"}, + {assertion: "employee.canBookMore", conditions: ["employee.balance - employee.vacationPending > 0", "not employee.onProbation"]}, + {match: "employee.alert", arms: [ + ["employee.balance - employee.vacationPending < 0", "'overbooked'"], + ["employee.sickDays > 10", "'sick-review'"], + ["employee.balance >= 25", "'encourage-leave'"], + ["", "'none'"], + ]}, + ], + }, + cases: [ + [ + {employee: {hired: "2015-01-01", fullTime: true, carryOver: 3, requests: [{kind: "vacation", start: "2025-02-03", end: "2025-02-07", approved: true}]}}, + {employee: {hired: "2015-01-01", fullTime: true, carryOver: 3, requests: [ + {kind: "vacation", start: "2025-02-03", end: "2025-02-07", approved: true, days: 5, state: "approved"}, + ], tenureYears: 10, onProbation: false, annualDays: 30, vacationTaken: 5, vacationPending: 0, sickDays: 0, balance: 28, canBookMore: true, alert: "encourage-leave"}}, + ], + // Five years exactly; carry-over capped at 5; a null approval is pending. + [ + {employee: {hired: "2020-03-20", fullTime: true, carryOver: 10, requests: [ + {kind: "vacation", start: "2025-01-06", end: "2025-01-17", approved: true}, + {kind: "vacation", start: "2025-06-01", end: "2025-06-14", approved: null}, + {kind: "sick", start: "2025-02-10", end: "2025-02-11", approved: true}, + ]}}, + {employee: {hired: "2020-03-20", fullTime: true, carryOver: 10, requests: [ + {kind: "vacation", start: "2025-01-06", end: "2025-01-17", approved: true, days: 12, state: "approved"}, + {kind: "vacation", start: "2025-06-01", end: "2025-06-14", approved: null, days: 14, state: "pending"}, + {kind: "sick", start: "2025-02-10", end: "2025-02-11", approved: true, days: 2, state: "approved"}, + ], tenureYears: 5, onProbation: false, annualDays: 27, vacationTaken: 12, vacationPending: 14, sickDays: 2, balance: 20, canBookMore: true, alert: "none"}}, + ], + [ + {employee: {hired: "2024-12-01", fullTime: false, carryOver: 0, requests: []}}, + {employee: {hired: "2024-12-01", fullTime: false, carryOver: 0, requests: [], tenureYears: 0, onProbation: true, annualDays: 15, vacationTaken: 0, vacationPending: 0, sickDays: 0, balance: 15, canBookMore: false, alert: "none"}}, + ], + // A request without `approved` is pending and overbooks the balance. + [ + {employee: {hired: "2018-01-01", fullTime: true, carryOver: 0, requests: [ + {kind: "vacation", start: "2025-03-03", end: "2025-03-21", approved: true}, + {kind: "vacation", start: "2025-07-01", end: "2025-07-14"}, + ]}}, + {employee: {hired: "2018-01-01", fullTime: true, carryOver: 0, requests: [ + {kind: "vacation", start: "2025-03-03", end: "2025-03-21", approved: true, days: 19, state: "approved"}, + {kind: "vacation", start: "2025-07-01", end: "2025-07-14", days: 14, state: "pending"}, + ], tenureYears: 7, onProbation: false, annualDays: 27, vacationTaken: 19, vacationPending: 14, sickDays: 0, balance: 8, canBookMore: false, alert: "overbooked"}}, + ], + // Part-time with long tenure; rejected requests do not count, pending sick days do. + [ + {employee: {hired: "2010-01-01", fullTime: false, carryOver: 2, requests: [ + {kind: "vacation", start: "2025-04-01", end: "2025-04-10", approved: false}, + {kind: "sick", start: "2025-01-01", end: "2025-01-15", approved: false}, + {kind: "sick", start: "2025-02-01", end: "2025-02-11", approved: null}, + ]}}, + {employee: {hired: "2010-01-01", fullTime: false, carryOver: 2, requests: [ + {kind: "vacation", start: "2025-04-01", end: "2025-04-10", approved: false, days: 10, state: "rejected"}, + {kind: "sick", start: "2025-01-01", end: "2025-01-15", approved: false, days: 15, state: "rejected"}, + {kind: "sick", start: "2025-02-01", end: "2025-02-11", approved: null, days: 11, state: "pending"}, + ], tenureYears: 15, onProbation: false, annualDays: 15, vacationTaken: 0, vacationPending: 0, sickDays: 11, balance: 17, canBookMore: true, alert: "sick-review"}}, + ], + // Probation ends at six full months; parental and unpaid leave do not touch the balance. + [ + {employee: {hired: "2024-09-20", fullTime: true, carryOver: 5, requests: [ + {kind: "parental", start: "2025-01-01", end: "2025-03-31", approved: true}, + {kind: "unpaid", start: "2025-04-01", end: "2025-04-01"}, + ]}}, + {employee: {hired: "2024-09-20", fullTime: true, carryOver: 5, requests: [ + {kind: "parental", start: "2025-01-01", end: "2025-03-31", approved: true, days: 90, state: "approved"}, + {kind: "unpaid", start: "2025-04-01", end: "2025-04-01", days: 1, state: "pending"}, + ], tenureYears: 0, onProbation: false, annualDays: 25, vacationTaken: 0, vacationPending: 0, sickDays: 0, balance: 30, canBookMore: true, alert: "encourage-leave"}}, + ], + [ + {employee: {hired: "2024-09-21", fullTime: true, carryOver: 0, requests: []}}, + {employee: {hired: "2024-09-21", fullTime: true, carryOver: 0, requests: [], tenureYears: 0, onProbation: true, annualDays: 25, vacationTaken: 0, vacationPending: 0, sickDays: 0, balance: 25, canBookMore: false, alert: "encourage-leave"}}, + ], + // A negative carry-over is a debt from last year; a zero balance books nothing more. + [ + {employee: {hired: "2016-01-01", fullTime: true, carryOver: -2, requests: [{kind: "vacation", start: "2025-01-01", end: "2025-01-25", approved: true}]}}, + {employee: {hired: "2016-01-01", fullTime: true, carryOver: -2, requests: [ + {kind: "vacation", start: "2025-01-01", end: "2025-01-25", approved: true, days: 25, state: "approved"}, + ], tenureYears: 9, onProbation: false, annualDays: 27, vacationTaken: 25, vacationPending: 0, sickDays: 0, balance: 0, canBookMore: false, alert: "none"}}, + ], + // An end before the start is not rejected by the model: the request counts negative days. + [ + {employee: {hired: "2015-01-01", fullTime: true, carryOver: 0, requests: [{kind: "vacation", start: "2025-05-10", end: "2025-05-01", approved: null}]}}, + {employee: {hired: "2015-01-01", fullTime: true, carryOver: 0, requests: [ + {kind: "vacation", start: "2025-05-10", end: "2025-05-01", approved: null, days: -8, state: "pending"}, + ], tenureYears: 10, onProbation: false, annualDays: 30, vacationTaken: 0, vacationPending: -8, sickDays: 0, balance: 30, canBookMore: true, alert: "encourage-leave"}}, + ], + [{employee: {hired: "2015-01-01", fullTime: true, carryOver: 0, requests: [{kind: "sabbatical", start: "2025-05-01", end: "2025-05-10"}]}}, "!error: InputValidationFailed"], + [{employee: {hired: "2015-01-01", fullTime: true, carryOver: 0, requests: [{kind: "vacation", start: "2025-05-01", end: "2025-05-10", approved: "yes"}]}}, "!error: InputValidationFailed"], + [{employee: {hired: "2015-01-01", fullTime: true, requests: []}}, "!error: MissingRequiredInputs"], + [{employee: {hired: "2015-01-01", fullTime: true, carryOver: 0, requests: [{kind: "vacation", start: "2025-05-01"}]}}, "!error: ExpressionFailed"], + ], +} + +// --- Approval routing -------------------------------------------------------------------------- +// The requester is a reference into a staff pool. Required approvals come from an amount and +// category table; approvals are members read through closures that compare against the +// referenced requester; a six-arm routing match covers rejection, self-approval, auto-approval +// within the requester's limit, completion and escalation after 14 days. + +{ + name: "expense approval routing by referenced staff", + policy: { + models: { + request: {amount: "number", category: "string(travel|training|equipment|software)", submitted: "date", requester: "&staff", approvals: "approval[]"}, + staff: {id: "string", level: "number", approvalLimit: "number"}, + approval: {by: "string", decision: "string(approve|reject)"}, + }, + blocks: [ + {expression: "request.ageDays", value: "d().diff(request.submitted, 'day')"}, + {table: "required", inputs: ["request.amount", "request.category"], outputs: ["request.requiredApprovals"], rules: [ + ["> 10000", "", "3"], + ["> 1000", "", "2"], + ["", "'equipment', 'software'", "2"], + ["", "", "1"], + ]}, + {expression: "request.approvalCount", value: "count(request.approvals, #.decision == 'approve' and #.by != request.requester.id)"}, + {expression: "request.rejected", value: "some(request.approvals, #.decision == 'reject')"}, + {expression: "request.selfApproved", value: "some(request.approvals, #.by == request.requester.id and #.decision == 'approve')"}, + {expression: "request.withinLimit", value: "request.amount <= request.requester.approvalLimit"}, + {expression: "request.missingApprovals", value: "max([request.requiredApprovals - request.approvalCount, 0])"}, + {match: "request.status", arms: [ + ["request.rejected", "'rejected'"], + ["request.selfApproved", "'invalid'"], + ["request.withinLimit and request.requiredApprovals <= 1", "'auto-approved'"], + ["request.approvalCount >= request.requiredApprovals", "'approved'"], + ["request.ageDays > 14", "'escalate'"], + ["", "'pending'"], + ]}, + ], + }, + cases: [ + [ + {request: {amount: 300, category: "travel", submitted: "2025-03-19", requester: "ann", approvals: []}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}, {id: "cy", level: 3, approvalLimit: 50000}]}, + {request: {amount: 300, category: "travel", submitted: "2025-03-19", requester: {id: "ann", level: 1, approvalLimit: 500}, approvals: [], + ageDays: 1, requiredApprovals: 1, approvalCount: 0, rejected: false, selfApproved: false, withinLimit: true, missingApprovals: 1, status: "auto-approved"}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}, {id: "cy", level: 3, approvalLimit: 50000}]}, + ], + [ + {request: {amount: 2500, category: "training", submitted: "2025-03-10", requester: "ann", approvals: [{by: "bob", decision: "approve"}]}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}]}, + {request: {amount: 2500, category: "training", submitted: "2025-03-10", requester: {id: "ann", level: 1, approvalLimit: 500}, approvals: [{by: "bob", decision: "approve"}], + ageDays: 10, requiredApprovals: 2, approvalCount: 1, rejected: false, selfApproved: false, withinLimit: false, missingApprovals: 1, status: "pending"}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}]}, + ], + [ + {request: {amount: 2500, category: "training", submitted: "2025-03-01", requester: "ann", approvals: [{by: "bob", decision: "approve"}, {by: "cy", decision: "approve"}]}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}, {id: "cy", level: 3, approvalLimit: 50000}]}, + {request: {amount: 2500, category: "training", submitted: "2025-03-01", requester: {id: "ann", level: 1, approvalLimit: 500}, approvals: [{by: "bob", decision: "approve"}, {by: "cy", decision: "approve"}], + ageDays: 19, requiredApprovals: 2, approvalCount: 2, rejected: false, selfApproved: false, withinLimit: false, missingApprovals: 0, status: "approved"}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}, {id: "cy", level: 3, approvalLimit: 50000}]}, + ], + [ + {request: {amount: 2500, category: "training", submitted: "2025-03-05", requester: "ann", approvals: [{by: "bob", decision: "approve"}]}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}]}, + {request: {amount: 2500, category: "training", submitted: "2025-03-05", requester: {id: "ann", level: 1, approvalLimit: 500}, approvals: [{by: "bob", decision: "approve"}], + ageDays: 15, requiredApprovals: 2, approvalCount: 1, rejected: false, selfApproved: false, withinLimit: false, missingApprovals: 1, status: "escalate"}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}]}, + ], + // Equipment always needs two approvals, even within the requester's limit. + [ + {request: {amount: 800, category: "equipment", submitted: "2025-03-20", requester: "bob", approvals: []}, staff: [{id: "bob", level: 2, approvalLimit: 5000}]}, + {request: {amount: 800, category: "equipment", submitted: "2025-03-20", requester: {id: "bob", level: 2, approvalLimit: 5000}, approvals: [], + ageDays: 0, requiredApprovals: 2, approvalCount: 0, rejected: false, selfApproved: false, withinLimit: true, missingApprovals: 2, status: "pending"}, staff: [{id: "bob", level: 2, approvalLimit: 5000}]}, + ], + // A requester approving their own request invalidates it and is not counted. + [ + {request: {amount: 4000, category: "software", submitted: "2025-03-18", requester: "bob", approvals: [{by: "bob", decision: "approve"}, {by: "cy", decision: "approve"}]}, staff: [{id: "bob", level: 2, approvalLimit: 5000}, {id: "cy", level: 3, approvalLimit: 50000}]}, + {request: {amount: 4000, category: "software", submitted: "2025-03-18", requester: {id: "bob", level: 2, approvalLimit: 5000}, approvals: [{by: "bob", decision: "approve"}, {by: "cy", decision: "approve"}], + ageDays: 2, requiredApprovals: 2, approvalCount: 1, rejected: false, selfApproved: true, withinLimit: true, missingApprovals: 1, status: "invalid"}, staff: [{id: "bob", level: 2, approvalLimit: 5000}, {id: "cy", level: 3, approvalLimit: 50000}]}, + ], + [ + {request: {amount: 20000, category: "travel", submitted: "2025-02-01", requester: "cy", approvals: [{by: "ann", decision: "approve"}, {by: "bob", decision: "reject"}]}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}, {id: "cy", level: 3, approvalLimit: 50000}]}, + {request: {amount: 20000, category: "travel", submitted: "2025-02-01", requester: {id: "cy", level: 3, approvalLimit: 50000}, approvals: [{by: "ann", decision: "approve"}, {by: "bob", decision: "reject"}], + ageDays: 47, requiredApprovals: 3, approvalCount: 1, rejected: true, selfApproved: false, withinLimit: true, missingApprovals: 2, status: "rejected"}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}, {id: "cy", level: 3, approvalLimit: 50000}]}, + ], + // Amount thresholds are strict: 1000 needs one approval, 10000 two. + [ + {request: {amount: 1000, category: "travel", submitted: "2025-03-06", requester: "ann", approvals: [{by: "bob", decision: "approve"}]}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}]}, + {request: {amount: 1000, category: "travel", submitted: "2025-03-06", requester: {id: "ann", level: 1, approvalLimit: 500}, approvals: [{by: "bob", decision: "approve"}], + ageDays: 14, requiredApprovals: 1, approvalCount: 1, rejected: false, selfApproved: false, withinLimit: false, missingApprovals: 0, status: "approved"}, staff: [{id: "ann", level: 1, approvalLimit: 500}, {id: "bob", level: 2, approvalLimit: 5000}]}, + ], + [ + {request: {amount: 10000, category: "travel", submitted: "2025-03-06", requester: "bob", approvals: []}, staff: [{id: "bob", level: 2, approvalLimit: 5000}]}, + {request: {amount: 10000, category: "travel", submitted: "2025-03-06", requester: {id: "bob", level: 2, approvalLimit: 5000}, approvals: [], + ageDays: 14, requiredApprovals: 2, approvalCount: 0, rejected: false, selfApproved: false, withinLimit: false, missingApprovals: 2, status: "pending"}, staff: [{id: "bob", level: 2, approvalLimit: 5000}]}, + ], + // An approval without `by` reads null: it differs from the requester and counts. + [ + {request: {amount: 3000, category: "training", submitted: "2025-03-20", requester: "ann", approvals: [{decision: "approve"}]}, staff: [{id: "ann", level: 1, approvalLimit: 500}]}, + {request: {amount: 3000, category: "training", submitted: "2025-03-20", requester: {id: "ann", level: 1, approvalLimit: 500}, approvals: [{decision: "approve"}], + ageDays: 0, requiredApprovals: 2, approvalCount: 1, rejected: false, selfApproved: false, withinLimit: false, missingApprovals: 1, status: "pending"}, staff: [{id: "ann", level: 1, approvalLimit: 500}]}, + ], + [{request: {amount: 1, category: "travel", submitted: "2025-03-20", requester: "zed", approvals: []}, staff: [{id: "ann", level: 1, approvalLimit: 500}]}, "!error: InputValidationFailed"], + [{request: {amount: 1, category: "travel", submitted: "2025-03-20", requester: "ann", approvals: [{by: "bob", decision: "maybe"}]}, staff: [{id: "ann", level: 1, approvalLimit: 500}]}, "!error: InputValidationFailed"], + [{request: {category: "travel", submitted: "2025-03-20", requester: "ann", approvals: []}, staff: [{id: "ann", level: 1, approvalLimit: 500}]}, "!error: MissingRequiredInputs"], + [{request: {amount: 1, category: "meals", submitted: "2025-03-20", requester: "ann", approvals: []}, staff: [{id: "ann", level: 1, approvalLimit: 500}]}, "!error: InputValidationFailed"], + ], +} + +// --- Department payroll run -------------------------------------------------------------------- +// Globals hold the employer tax rate and the minimum wage. Employees are salaried or hourly with +// optional rates; a per-employee `[]` table collects issues only for active employees; the +// department totals active pay, adds employer tax, lists blocking employees, asserts the budget +// and decides the run status. + +{ + name: "department payroll run against globals", + policy: { + globals: {payroll: {employerTaxRate: "number", minimumWage: "number"}}, + models: { + department: {name: "string", budget: "number", employees: "employee[]"}, + employee: {name: "string", payType: "string(salary|hourly)", salary: "number?", hourlyRate: "number?", hours: "number?", active: "boolean"}, + }, + blocks: [ + {expression: "employee.gross", value: "employee.payType == 'salary' ? round((employee.salary ?? 0) / 12, 2) : round((employee.hourlyRate ?? 0) * (employee.hours ?? 0), 2)"}, + {expression: "employee.effectiveRate", value: "employee.payType == 'hourly' ? (employee.hourlyRate ?? 0) : round((employee.salary ?? 0) / 1950, 2)"}, + {expression: "employee.missingRate", value: "employee.payType == 'salary' ? employee.salary == null : employee.hourlyRate == null"}, + {expression: "employee.belowMinimum", value: "not employee.missingRate and employee.effectiveRate < minimumWage"}, + {table: "issues", inputs: ["employee.missingRate", "employee.belowMinimum", "employee.active"], outputs: ["employee.issues[]"], rules: [ + ["true", "", "true", "'missing-rate'"], + ["", "true", "true", "'below-minimum'"], + ]}, + {expression: "department.headcount", value: "count(department.employees, #.active)"}, + {expression: "department.payroll", value: "sum(map(filter(department.employees, #.active), #.gross))"}, + {expression: "department.employerTax", value: "round(department.payroll * employerTaxRate, 2)"}, + {expression: "department.cost", value: "department.payroll + department.employerTax"}, + {expression: "department.blockedBy", value: "map(filter(department.employees, len(#.issues) > 0), #.name)"}, + {assertion: "department.withinBudget", conditions: ["department.cost <= department.budget"]}, + {match: "department.runStatus", arms: [ + ["len(department.blockedBy) > 0", "'blocked'"], + ["department.headcount == 0", "'empty'"], + ["not department.withinBudget", "'over-budget'"], + ["", "'ready'"], + ]}, + ], + }, + cases: [ + [ + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "ops", budget: 20000, employees: [ + {name: "ann", payType: "salary", salary: 60000, active: true}, + {name: "bob", payType: "hourly", hourlyRate: 20, hours: 160, active: true}, + ]}}, + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "ops", budget: 20000, employees: [ + {name: "ann", payType: "salary", salary: 60000, active: true, gross: 5000, effectiveRate: 30.77, missingRate: false, belowMinimum: false, issues: []}, + {name: "bob", payType: "hourly", hourlyRate: 20, hours: 160, active: true, gross: 3200, effectiveRate: 20, missingRate: false, belowMinimum: false, issues: []}, + ], headcount: 2, payroll: 8200, employerTax: 1148, cost: 9348, blockedBy: [], withinBudget: true, runStatus: "ready"}}, + ], + [ + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "ops", budget: 5000, employees: [ + {name: "ann", payType: "salary", salary: 30000, active: true}, + {name: "bob", payType: "hourly", hours: 100, active: true}, + ]}}, + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "ops", budget: 5000, employees: [ + {name: "ann", payType: "salary", salary: 30000, active: true, gross: 2500, effectiveRate: 15.38, missingRate: false, belowMinimum: false, issues: []}, + {name: "bob", payType: "hourly", hours: 100, active: true, gross: 0, effectiveRate: 0, missingRate: true, belowMinimum: false, issues: ["missing-rate"]}, + ], headcount: 2, payroll: 2500, employerTax: 350, cost: 2850, blockedBy: ["bob"], withinBudget: true, runStatus: "blocked"}}, + ], + // An inactive employee with a missing rate raises no issue; blocking wins over the budget. + [ + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "shop", budget: 1000, employees: [ + {name: "cy", payType: "hourly", hourlyRate: 12, hours: 80, active: true}, + {name: "dee", payType: "hourly", active: false}, + ]}}, + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "shop", budget: 1000, employees: [ + {name: "cy", payType: "hourly", hourlyRate: 12, hours: 80, active: true, gross: 960, effectiveRate: 12, missingRate: false, belowMinimum: true, issues: ["below-minimum"]}, + {name: "dee", payType: "hourly", active: false, gross: 0, effectiveRate: 0, missingRate: true, belowMinimum: false, issues: []}, + ], headcount: 1, payroll: 960, employerTax: 134.4, cost: 1094.4, blockedBy: ["cy"], withinBudget: false, runStatus: "blocked"}}, + ], + [ + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "hq", budget: 5000, employees: [{name: "ann", payType: "salary", salary: 60000, active: true}]}}, + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "hq", budget: 5000, employees: [ + {name: "ann", payType: "salary", salary: 60000, active: true, gross: 5000, effectiveRate: 30.77, missingRate: false, belowMinimum: false, issues: []}, + ], headcount: 1, payroll: 5000, employerTax: 700, cost: 5700, blockedBy: [], withinBudget: false, runStatus: "over-budget"}}, + ], + [ + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "hq", budget: 5700, employees: [{name: "ann", payType: "salary", salary: 60000, active: true}]}}, + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "hq", budget: 5700, employees: [ + {name: "ann", payType: "salary", salary: 60000, active: true, gross: 5000, effectiveRate: 30.77, missingRate: false, belowMinimum: false, issues: []}, + ], headcount: 1, payroll: 5000, employerTax: 700, cost: 5700, blockedBy: [], withinBudget: true, runStatus: "ready"}}, + ], + [ + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "new", budget: 0, employees: []}}, + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "new", budget: 0, employees: [], headcount: 0, payroll: 0, employerTax: 0, cost: 0, blockedBy: [], withinBudget: true, runStatus: "empty"}}, + ], + [ + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "old", budget: 0, employees: [{name: "ann", payType: "salary", salary: 50000, active: false}]}}, + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "old", budget: 0, employees: [ + {name: "ann", payType: "salary", salary: 50000, active: false, gross: 4166.67, effectiveRate: 25.64, missingRate: false, belowMinimum: false, issues: []}, + ], headcount: 0, payroll: 0, employerTax: 0, cost: 0, blockedBy: [], withinBudget: true, runStatus: "empty"}}, + ], + // A salary of exactly the minimum wage times 1950 hours is not below it. + [ + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "ops", budget: 10000, employees: [{name: "eve", payType: "salary", salary: 29250, active: true}]}}, + {employerTaxRate: 0.14, minimumWage: 15, department: {name: "ops", budget: 10000, employees: [ + {name: "eve", payType: "salary", salary: 29250, active: true, gross: 2437.5, effectiveRate: 15, missingRate: false, belowMinimum: false, issues: []}, + ], headcount: 1, payroll: 2437.5, employerTax: 341.25, cost: 2778.75, blockedBy: [], withinBudget: true, runStatus: "ready"}}, + ], + [ + {employerTaxRate: 0.1, minimumWage: 15, department: {name: "ops", budget: 100, employees: [{name: "fay", payType: "hourly", hourlyRate: 18, hours: null, active: true}]}}, + {employerTaxRate: 0.1, minimumWage: 15, department: {name: "ops", budget: 100, employees: [ + {name: "fay", payType: "hourly", hourlyRate: 18, hours: null, active: true, gross: 0, effectiveRate: 18, missingRate: false, belowMinimum: false, issues: []}, + ], headcount: 1, payroll: 0, employerTax: 0, cost: 0, blockedBy: [], withinBudget: true, runStatus: "ready"}}, + ], + [{employerTaxRate: 0.14, minimumWage: 15, department: {name: "x", budget: 1, employees: [{name: "a", payType: "commission", active: true}]}}, "!error: InputValidationFailed"], + [{employerTaxRate: 0.14, department: {name: "x", budget: 1, employees: []}}, "!error: MissingRequiredInputs"], + [{employerTaxRate: 0.14, minimumWage: 15, department: {name: "x", budget: 1, employees: [{name: "a", payType: "salary", salary: 1000}]}}, "!error: ExpressionFailed"], + [{employerTaxRate: 0.14, minimumWage: 15, department: {name: "x", budget: 1, employees: [{name: "a", payType: "salary", salary: "50k", active: true}]}}, "!error: InputValidationFailed"], + ], +} + +// --- Bonus by referenced grade ----------------------------------------------------------------- +// A weighted target score with each achievement capped at 150%, months served capped at 12 for +// proration, a rating factor match, the bonus capped by the referenced grade and scaled by a +// company payout global, and an eligibility assertion. Goals evaluate single cones. + +{ + name: "bonus by referenced grade with targets", + policy: { + globals: {company: {payoutFactor: "number"}}, + models: { + employee: {grade: "&grade", salary: "number", rating: "string(exceeds|meets|below)", startDate: "date", targets: "target[]"}, + grade: {id: "string", bonusPct: "number", cap: "number"}, + target: {weight: "number", achieved: "number"}, + }, + blocks: [ + {expression: "employee.score", value: "sum(map(employee.targets, #.weight * min([#.achieved, 1.5]))) / max([sum(map(employee.targets, #.weight)), 1])"}, + {expression: "employee.monthsServed", value: "min([d().diff(employee.startDate, 'month'), 12])"}, + {match: "employee.ratingFactor", arms: [ + ["employee.rating == 'exceeds'", "1.25"], + ["employee.rating == 'meets'", "1"], + ["", "0"], + ]}, + {expression: "employee.bonus", value: "round(min([employee.salary * employee.grade.bonusPct * employee.score * employee.ratingFactor * payoutFactor * employee.monthsServed / 12, employee.grade.cap]), 2)"}, + {assertion: "employee.eligible", conditions: ["employee.rating != 'below'", "employee.monthsServed >= 3"]}, + {expression: "employee.payout", value: "employee.eligible ? employee.bonus : 0"}, + ], + }, + cases: [ + [ + {payoutFactor: 1, employee: {grade: "G1", salary: 50000, rating: "meets", startDate: "2020-01-01", targets: [{weight: 1, achieved: 1}]}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}, {id: "G2", bonusPct: 0.1, cap: 10000}]}, + {payoutFactor: 1, employee: {grade: {id: "G1", bonusPct: 0.05, cap: 3000}, salary: 50000, rating: "meets", startDate: "2020-01-01", targets: [{weight: 1, achieved: 1}], + score: 1, monthsServed: 12, ratingFactor: 1, bonus: 2500, eligible: true, payout: 2500}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}, {id: "G2", bonusPct: 0.1, cap: 10000}]}, + ], + [ + {payoutFactor: 1, employee: {grade: "G2", salary: 120000, rating: "exceeds", startDate: "2019-06-01", targets: [{weight: 2, achieved: 1.2}, {weight: 1, achieved: 0.6}]}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}, {id: "G2", bonusPct: 0.1, cap: 10000}]}, + {payoutFactor: 1, employee: {grade: {id: "G2", bonusPct: 0.1, cap: 10000}, salary: 120000, rating: "exceeds", startDate: "2019-06-01", targets: [{weight: 2, achieved: 1.2}, {weight: 1, achieved: 0.6}], + score: 1, monthsServed: 12, ratingFactor: 1.25, bonus: 10000, eligible: true, payout: 10000}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}, {id: "G2", bonusPct: 0.1, cap: 10000}]}, + ], + // Achievement above 150% is capped; three months served is just eligible. + [ + {payoutFactor: 1, employee: {grade: "G1", salary: 60000, rating: "meets", startDate: "2024-12-01", targets: [{weight: 1, achieved: 2}]}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, + {payoutFactor: 1, employee: {grade: {id: "G1", bonusPct: 0.05, cap: 3000}, salary: 60000, rating: "meets", startDate: "2024-12-01", targets: [{weight: 1, achieved: 2}], + score: 1.5, monthsServed: 3, ratingFactor: 1, bonus: 1125, eligible: true, payout: 1125}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, + ], + [ + {payoutFactor: 1, employee: {grade: "G1", salary: 60000, rating: "meets", startDate: "2025-01-01", targets: [{weight: 1, achieved: 1}]}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, + {payoutFactor: 1, employee: {grade: {id: "G1", bonusPct: 0.05, cap: 3000}, salary: 60000, rating: "meets", startDate: "2025-01-01", targets: [{weight: 1, achieved: 1}], + score: 1, monthsServed: 2, ratingFactor: 1, bonus: 500, eligible: false, payout: 0}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, + ], + [ + {payoutFactor: 1, employee: {grade: "G1", salary: 60000, rating: "below", startDate: "2015-01-01", targets: [{weight: 1, achieved: 1}]}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, + {payoutFactor: 1, employee: {grade: {id: "G1", bonusPct: 0.05, cap: 3000}, salary: 60000, rating: "below", startDate: "2015-01-01", targets: [{weight: 1, achieved: 1}], + score: 1, monthsServed: 12, ratingFactor: 0, bonus: 0, eligible: false, payout: 0}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, + ], + [ + {payoutFactor: 1, employee: {grade: "G1", salary: 60000, rating: "exceeds", startDate: "2015-01-01", targets: []}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, + {payoutFactor: 1, employee: {grade: {id: "G1", bonusPct: 0.05, cap: 3000}, salary: 60000, rating: "exceeds", startDate: "2015-01-01", targets: [], + score: 0, monthsServed: 12, ratingFactor: 1.25, bonus: 0, eligible: true, payout: 0}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, + ], + [ + {payoutFactor: 0.8, employee: {grade: "G2", salary: 80000, rating: "meets", startDate: "2010-01-01", targets: [{weight: 3, achieved: 0.9}, {weight: 1, achieved: 1.1}]}, grade: [{id: "G2", bonusPct: 0.1, cap: 10000}]}, + {payoutFactor: 0.8, employee: {grade: {id: "G2", bonusPct: 0.1, cap: 10000}, salary: 80000, rating: "meets", startDate: "2010-01-01", targets: [{weight: 3, achieved: 0.9}, {weight: 1, achieved: 1.1}], + score: 0.95, monthsServed: 12, ratingFactor: 1, bonus: 6080, eligible: true, payout: 6080}, grade: [{id: "G2", bonusPct: 0.1, cap: 10000}]}, + ], + { + input: {employee: {targets: [{weight: 1, achieved: 0.5}, {weight: 1, achieved: 1.5}]}}, + goals: ["employee.score"], + output: {employee: {targets: [{weight: 1, achieved: 0.5}, {weight: 1, achieved: 1.5}], score: 1}}, + }, + { + input: {employee: {rating: "meets", startDate: "2025-01-15"}}, + goals: ["employee.eligible"], + output: {employee: {rating: "meets", startDate: "2025-01-15", monthsServed: 2, eligible: false}}, + }, + [{payoutFactor: 1, employee: {grade: "G9", salary: 1, rating: "meets", startDate: "2020-01-01", targets: []}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, "!error: InputValidationFailed"], + [{payoutFactor: 1, employee: {grade: "G1", salary: 1, rating: "great", startDate: "2020-01-01", targets: []}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, "!error: InputValidationFailed"], + [{employee: {grade: "G1", salary: 1, rating: "meets", startDate: "2020-01-01", targets: []}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, "!error: MissingRequiredInputs"], + [{payoutFactor: 1, employee: {grade: "G1", salary: 1, rating: "meets", startDate: "2020-01-01", targets: [{weight: 1}]}, grade: [{id: "G1", bonusPct: 0.05, cap: 3000}]}, "!error: ExpressionFailed"], + ], +} diff --git a/core/engine/tests/spec/policy/43-realistic-eligibility.json5 b/core/engine/tests/spec/policy/43-realistic-eligibility.json5 new file mode 100644 index 00000000..ef5779b6 --- /dev/null +++ b/core/engine/tests/spec/policy/43-realistic-eligibility.json5 @@ -0,0 +1,712 @@ +// Realistic eligibility policies: a household means test with members and a referenced region, +// a student grant with dictionary-typed documents, small business loans with grouped +// assertions, a childcare subsidy with a referenced provider read from members, residency and +// identity document checks, and an old-age supplement against globals. Each suite combines +// several block kinds over related entities and runs valid, boundary, missing and invalid data. +// Evaluation time is fixed at 2025-03-20T10:15:30Z. + +// --- Household means test ---------------------------------------------------------------------- +// Per-member age, dependency (children under 18, or under 25 while studying) and an income +// weight match (disabled members count half, minors nothing). The household threshold uses an +// equivalence scale on the referenced region's poverty line, housing is capped by the region, +// an asset assertion requires an adult, and a benefit table with expression output cells. + +{ + name: "household means test with members and a referenced region", + policy: { + models: { + household: {region: "®ion", rent: "number", assets: "number", members: "member[]"}, + region: {id: "string", povertyLine: "number", rentCap: "number"}, + member: {dob: "date", role: "string(head|partner|child|other)", income: "number", disabled: "boolean", student: "boolean?"}, + }, + blocks: [ + {expression: "member.age", value: "d().diff(member.dob, 'year')"}, + {expression: "member.dependent", value: "member.role == 'child' and (member.age < 18 or (member.age < 25 and (member.student ?? false)))"}, + {match: "member.incomeWeight", arms: [ + ["member.disabled", "0.5"], + ["member.age < 18", "0"], + ["", "1"], + ]}, + {expression: "member.countedIncome", value: "member.income * member.incomeWeight"}, + {expression: "household.adults", value: "count(household.members, not #.dependent)"}, + {expression: "household.dependents", value: "count(household.members, #.dependent)"}, + {expression: "household.income", value: "sum(map(household.members, #.countedIncome))"}, + {expression: "household.threshold", value: "household.region.povertyLine * (1 + (household.adults - 1) * 0.5 + household.dependents * 0.3)"}, + {expression: "household.housing", value: "min([household.rent, household.region.rentCap])"}, + {expression: "household.gap", value: "max([household.threshold + household.housing - household.income, 0])"}, + {assertion: "household.assetTest", conditions: ["household.adults > 0", "household.assets <= 10000 * household.adults + 2000 * household.dependents"]}, + {table: "benefit", inputs: ["household.assetTest", "household.gap"], outputs: ["household.benefit", "household.tier"], rules: [ + ["false", "", "0", "'ineligible'"], + ["", "0", "0", "'not-needed'"], + ["", "< 200", "200", "'minimum'"], + ["", "", "round(household.gap, 0)", "'top-up'"], + ]}, + ], + }, + cases: [ + [ + {household: {region: "A", rent: 700, assets: 3000, members: [ + {dob: "1985-01-01", role: "head", income: 900, disabled: false}, + {dob: "2015-05-01", role: "child", income: 0, disabled: false}, + ]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}, {id: "B", povertyLine: 1000, rentCap: 600}]}, + {household: {region: {id: "A", povertyLine: 1200, rentCap: 800}, rent: 700, assets: 3000, members: [ + {dob: "1985-01-01", role: "head", income: 900, disabled: false, age: 40, dependent: false, incomeWeight: 1, countedIncome: 900}, + {dob: "2015-05-01", role: "child", income: 0, disabled: false, age: 9, dependent: true, incomeWeight: 0, countedIncome: 0}, + ], adults: 1, dependents: 1, income: 900, threshold: 1560, housing: 700, gap: 1360, assetTest: true, benefit: 1360, tier: "top-up"}, region: [{id: "A", povertyLine: 1200, rentCap: 800}, {id: "B", povertyLine: 1000, rentCap: 600}]}, + ], + // A couple with a disabled partner and a studying 20-year-old: the gap is exactly 200, but + // assets exceed the limit of 22000. + [ + {household: {region: "B", rent: 900, assets: 25000, members: [ + {dob: "1970-01-01", role: "head", income: 1500, disabled: false}, + {dob: "1972-01-01", role: "partner", income: 800, disabled: true}, + {dob: "2004-06-01", role: "child", income: 300, disabled: false, student: true}, + ]}, region: [{id: "B", povertyLine: 1000, rentCap: 600}]}, + {household: {region: {id: "B", povertyLine: 1000, rentCap: 600}, rent: 900, assets: 25000, members: [ + {dob: "1970-01-01", role: "head", income: 1500, disabled: false, age: 55, dependent: false, incomeWeight: 1, countedIncome: 1500}, + {dob: "1972-01-01", role: "partner", income: 800, disabled: true, age: 53, dependent: false, incomeWeight: 0.5, countedIncome: 400}, + {dob: "2004-06-01", role: "child", income: 300, disabled: false, student: true, age: 20, dependent: true, incomeWeight: 1, countedIncome: 300}, + ], adults: 2, dependents: 1, income: 2200, threshold: 1800, housing: 600, gap: 200, assetTest: false, benefit: 0, tier: "ineligible"}, region: [{id: "B", povertyLine: 1000, rentCap: 600}]}, + ], + // The same household at the asset limit; a gap of 200 is a regular top-up. + [ + {household: {region: "B", rent: 900, assets: 22000, members: [ + {dob: "1970-01-01", role: "head", income: 1500, disabled: false}, + {dob: "1972-01-01", role: "partner", income: 800, disabled: true}, + {dob: "2004-06-01", role: "child", income: 300, disabled: false, student: true}, + ]}, region: [{id: "B", povertyLine: 1000, rentCap: 600}]}, + {household: {region: {id: "B", povertyLine: 1000, rentCap: 600}, rent: 900, assets: 22000, members: [ + {dob: "1970-01-01", role: "head", income: 1500, disabled: false, age: 55, dependent: false, incomeWeight: 1, countedIncome: 1500}, + {dob: "1972-01-01", role: "partner", income: 800, disabled: true, age: 53, dependent: false, incomeWeight: 0.5, countedIncome: 400}, + {dob: "2004-06-01", role: "child", income: 300, disabled: false, student: true, age: 20, dependent: true, incomeWeight: 1, countedIncome: 300}, + ], adults: 2, dependents: 1, income: 2200, threshold: 1800, housing: 600, gap: 200, assetTest: true, benefit: 200, tier: "top-up"}, region: [{id: "B", povertyLine: 1000, rentCap: 600}]}, + ], + [ + {household: {region: "A", rent: 300, assets: 0, members: [{dob: "1990-01-01", role: "head", income: 1350, disabled: false}]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + {household: {region: {id: "A", povertyLine: 1200, rentCap: 800}, rent: 300, assets: 0, members: [ + {dob: "1990-01-01", role: "head", income: 1350, disabled: false, age: 35, dependent: false, incomeWeight: 1, countedIncome: 1350}, + ], adults: 1, dependents: 0, income: 1350, threshold: 1200, housing: 300, gap: 150, assetTest: true, benefit: 200, tier: "minimum"}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + ], + [ + {household: {region: "A", rent: 300, assets: 0, members: [{dob: "1990-01-01", role: "head", income: 5000, disabled: false}]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + {household: {region: {id: "A", povertyLine: 1200, rentCap: 800}, rent: 300, assets: 0, members: [ + {dob: "1990-01-01", role: "head", income: 5000, disabled: false, age: 35, dependent: false, incomeWeight: 1, countedIncome: 5000}, + ], adults: 1, dependents: 0, income: 5000, threshold: 1200, housing: 300, gap: 0, assetTest: true, benefit: 0, tier: "not-needed"}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + ], + // A 25-year-old student is an adult; a working 17-year-old is a dependent whose income is not + // counted; rent above the cap is capped. + [ + {household: {region: "A", rent: 1000, assets: 21999, members: [ + {dob: "1980-01-01", role: "head", income: 0, disabled: true}, + {dob: "1999-06-01", role: "child", income: 1000, disabled: false, student: true}, + {dob: "2008-01-01", role: "child", income: 500, disabled: false}, + ]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + {household: {region: {id: "A", povertyLine: 1200, rentCap: 800}, rent: 1000, assets: 21999, members: [ + {dob: "1980-01-01", role: "head", income: 0, disabled: true, age: 45, dependent: false, incomeWeight: 0.5, countedIncome: 0}, + {dob: "1999-06-01", role: "child", income: 1000, disabled: false, student: true, age: 25, dependent: false, incomeWeight: 1, countedIncome: 1000}, + {dob: "2008-01-01", role: "child", income: 500, disabled: false, age: 17, dependent: true, incomeWeight: 0, countedIncome: 0}, + ], adults: 2, dependents: 1, income: 1000, threshold: 2160, housing: 800, gap: 1960, assetTest: true, benefit: 1960, tier: "top-up"}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + ], + // A 21-year-old child without a `student` flag is not a dependent. + [ + {household: {region: "B", rent: 500, assets: 0, members: [ + {dob: "1990-01-01", role: "head", income: 600, disabled: false}, + {dob: "2004-01-01", role: "child", income: 0, disabled: false}, + ]}, region: [{id: "B", povertyLine: 1000, rentCap: 600}]}, + {household: {region: {id: "B", povertyLine: 1000, rentCap: 600}, rent: 500, assets: 0, members: [ + {dob: "1990-01-01", role: "head", income: 600, disabled: false, age: 35, dependent: false, incomeWeight: 1, countedIncome: 600}, + {dob: "2004-01-01", role: "child", income: 0, disabled: false, age: 21, dependent: false, incomeWeight: 1, countedIncome: 0}, + ], adults: 2, dependents: 0, income: 600, threshold: 1500, housing: 500, gap: 1400, assetTest: true, benefit: 1400, tier: "top-up"}, region: [{id: "B", povertyLine: 1000, rentCap: 600}]}, + ], + // The output cell rounds a fractional gap to whole units. + [ + {household: {region: "C", rent: 0, assets: 0, members: [{dob: "1960-01-01", role: "head", income: 0, disabled: false}]}, region: [{id: "C", povertyLine: 1033.33, rentCap: 500}]}, + {household: {region: {id: "C", povertyLine: 1033.33, rentCap: 500}, rent: 0, assets: 0, members: [ + {dob: "1960-01-01", role: "head", income: 0, disabled: false, age: 65, dependent: false, incomeWeight: 1, countedIncome: 0}, + ], adults: 1, dependents: 0, income: 0, threshold: 1033.33, housing: 0, gap: 1033.33, assetTest: true, benefit: 1033, tier: "top-up"}, region: [{id: "C", povertyLine: 1033.33, rentCap: 500}]}, + ], + // A household of children only has no adult and fails the asset test. + [ + {household: {region: "A", rent: 0, assets: 0, members: [{dob: "2010-01-01", role: "child", income: 0, disabled: false}]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + {household: {region: {id: "A", povertyLine: 1200, rentCap: 800}, rent: 0, assets: 0, members: [ + {dob: "2010-01-01", role: "child", income: 0, disabled: false, age: 15, dependent: true, incomeWeight: 0, countedIncome: 0}, + ], adults: 0, dependents: 1, income: 0, threshold: 960, housing: 0, gap: 960, assetTest: false, benefit: 0, tier: "ineligible"}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + ], + [ + {household: {region: "A", rent: 0, assets: 0, members: []}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + {household: {region: {id: "A", povertyLine: 1200, rentCap: 800}, rent: 0, assets: 0, members: [], adults: 0, dependents: 0, income: 0, threshold: 600, housing: 0, gap: 600, assetTest: false, benefit: 0, tier: "ineligible"}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + ], + // A member without `disabled` reads null; a null match condition does not match (like a null + // assertion condition), so the arm falls through to the next one. + [ + {household: {region: "A", rent: 0, assets: 0, members: [{dob: "1990-01-01", role: "head", income: 100}]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + {household: {region: {id: "A", povertyLine: 1200, rentCap: 800}, rent: 0, assets: 0, members: [ + {dob: "1990-01-01", role: "head", income: 100, age: 35, dependent: false, incomeWeight: 1, countedIncome: 100}, + ], adults: 1, dependents: 0, income: 100, threshold: 1200, housing: 0, gap: 1100, assetTest: true, benefit: 1100, tier: "top-up"}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, + ], + [{household: {region: "A", rent: 0, assets: 0, members: [{dob: "1990-01-01", role: "lodger", income: 0, disabled: false}]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, "!error: InputValidationFailed"], + [{household: {region: "Z", rent: 0, assets: 0, members: []}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, "!error: InputValidationFailed"], + [{household: {region: "A", rent: 0, assets: 0, members: [{dob: "1990-01-01", role: "head", disabled: false}]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, "!error: ExpressionFailed"], + [{household: {region: "A", assets: 0, members: []}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, "!error: MissingRequiredInputs"], + [{household: {region: "A", rent: 0, assets: 0, members: [{dob: "1990-01-01", role: "head", income: 1, disabled: "no"}]}, region: [{id: "A", povertyLine: 1200, rentCap: 800}]}, "!error: InputValidationFailed"], + ], +} + +// --- Student grant ----------------------------------------------------------------------------- +// Dictionary-typed document kinds; documents must be valid and uploaded within twelve months. +// Required documents depend on independence and age; missing ones come from list filtering. A +// base grant table over program and study load, a parental contribution above an income floor, +// pro-rating by load, and a decision match. A goal on the missing documents skips the money. + +{ + name: "student grant with documents and parental income", + policy: { + dictionaries: {docType: [["ID", "Identity"], ["ENR", "Enrolment"], ["TAX", "Parental tax return"], ["IND", "Proof of independence"]]}, + models: { + applicant: {dob: "date", independent: "boolean", program: "string(bachelor|master|vocational)", studyLoad: "number", parentalIncome: "number?", documents: "document[]"}, + document: {type: "docType", status: "string(valid|expired|pending)", uploaded: "date"}, + }, + blocks: [ + {expression: "applicant.age", value: "d().diff(applicant.dob, 'year')"}, + {expression: "applicant.selfSupporting", value: "applicant.independent or applicant.age >= 25"}, + {expression: "applicant.validDocs", value: "map(filter(applicant.documents, #.status == 'valid' and d().diff(#.uploaded, 'month') < 12), #.type)"}, + {expression: "applicant.requiredDocs", value: "applicant.independent ? ['ID', 'ENR', 'IND'] : applicant.age >= 25 ? ['ID', 'ENR'] : ['ID', 'ENR', 'TAX']"}, + {expression: "applicant.missingDocs", value: "filter(applicant.requiredDocs, not (# in applicant.validDocs))"}, + {table: "base", inputs: ["applicant.program", "applicant.studyLoad"], outputs: ["applicant.baseGrant"], rules: [ + ["", "< 50", "0"], + ["'master'", "", "1100"], + ["'bachelor'", "", "1000"], + ["'vocational'", "", "800"], + ]}, + {expression: "applicant.parentalContribution", value: "applicant.selfSupporting ? 0 : round(max([(applicant.parentalIncome ?? 0) - 40000, 0]) * 0.05 / 12, 2)"}, + {expression: "applicant.grant", value: "max([round(applicant.baseGrant * (applicant.studyLoad >= 100 ? 1 : applicant.studyLoad / 100) - applicant.parentalContribution, 2), 0])"}, + {match: "applicant.decision", arms: [ + ["len(applicant.missingDocs) > 0", "'incomplete'"], + ["applicant.baseGrant == 0", "'load-too-low'"], + ["applicant.grant == 0", "'means-tested-out'"], + ["", "'award'"], + ]}, + ], + }, + cases: [ + [ + {applicant: {dob: "2004-09-01", independent: false, program: "bachelor", studyLoad: 100, parentalIncome: 60000, documents: [ + {type: "ID", status: "valid", uploaded: "2024-09-01"}, + {type: "ENR", status: "valid", uploaded: "2025-01-10"}, + {type: "TAX", status: "valid", uploaded: "2024-05-01"}, + ]}}, + {applicant: {dob: "2004-09-01", independent: false, program: "bachelor", studyLoad: 100, parentalIncome: 60000, documents: [ + {type: "ID", status: "valid", uploaded: "2024-09-01"}, + {type: "ENR", status: "valid", uploaded: "2025-01-10"}, + {type: "TAX", status: "valid", uploaded: "2024-05-01"}, + ], age: 20, selfSupporting: false, validDocs: ["ID", "ENR", "TAX"], requiredDocs: ["ID", "ENR", "TAX"], missingDocs: [], baseGrant: 1000, parentalContribution: 83.33, grant: 916.67, decision: "award"}}, + ], + [ + {applicant: {dob: "2003-01-01", independent: true, program: "master", studyLoad: 60, parentalIncome: null, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "valid", uploaded: "2025-02-01"}, + {type: "IND", status: "valid", uploaded: "2025-02-01"}, + ]}}, + {applicant: {dob: "2003-01-01", independent: true, program: "master", studyLoad: 60, parentalIncome: null, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "valid", uploaded: "2025-02-01"}, + {type: "IND", status: "valid", uploaded: "2025-02-01"}, + ], age: 22, selfSupporting: true, validDocs: ["ID", "ENR", "IND"], requiredDocs: ["ID", "ENR", "IND"], missingDocs: [], baseGrant: 1100, parentalContribution: 0, grant: 660, decision: "award"}}, + ], + // Turning 25 today makes an applicant self-supporting without the independence proof. + [ + {applicant: {dob: "2000-03-20", independent: false, program: "vocational", studyLoad: 100, parentalIncome: 200000, documents: [ + {type: "ID", status: "valid", uploaded: "2024-04-01"}, + {type: "ENR", status: "valid", uploaded: "2025-03-01"}, + ]}}, + {applicant: {dob: "2000-03-20", independent: false, program: "vocational", studyLoad: 100, parentalIncome: 200000, documents: [ + {type: "ID", status: "valid", uploaded: "2024-04-01"}, + {type: "ENR", status: "valid", uploaded: "2025-03-01"}, + ], age: 25, selfSupporting: true, validDocs: ["ID", "ENR"], requiredDocs: ["ID", "ENR"], missingDocs: [], baseGrant: 800, parentalContribution: 0, grant: 800, decision: "award"}}, + ], + [ + {applicant: {dob: "2006-01-01", independent: false, program: "bachelor", studyLoad: 100, parentalIncome: 30000, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "pending", uploaded: "2025-03-01"}, + {type: "TAX", status: "expired", uploaded: "2025-01-01"}, + ]}}, + {applicant: {dob: "2006-01-01", independent: false, program: "bachelor", studyLoad: 100, parentalIncome: 30000, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "pending", uploaded: "2025-03-01"}, + {type: "TAX", status: "expired", uploaded: "2025-01-01"}, + ], age: 19, selfSupporting: false, validDocs: ["ID"], requiredDocs: ["ID", "ENR", "TAX"], missingDocs: ["ENR", "TAX"], baseGrant: 1000, parentalContribution: 0, grant: 1000, decision: "incomplete"}}, + ], + // An upload exactly twelve months old is stale. + [ + {applicant: {dob: "2005-01-01", independent: false, program: "bachelor", studyLoad: 100, parentalIncome: 40000, documents: [ + {type: "ID", status: "valid", uploaded: "2024-03-20"}, + {type: "ENR", status: "valid", uploaded: "2024-03-21"}, + {type: "TAX", status: "valid", uploaded: "2025-01-01"}, + ]}}, + {applicant: {dob: "2005-01-01", independent: false, program: "bachelor", studyLoad: 100, parentalIncome: 40000, documents: [ + {type: "ID", status: "valid", uploaded: "2024-03-20"}, + {type: "ENR", status: "valid", uploaded: "2024-03-21"}, + {type: "TAX", status: "valid", uploaded: "2025-01-01"}, + ], age: 20, selfSupporting: false, validDocs: ["ENR", "TAX"], requiredDocs: ["ID", "ENR", "TAX"], missingDocs: ["ID"], baseGrant: 1000, parentalContribution: 0, grant: 1000, decision: "incomplete"}}, + ], + [ + {applicant: {dob: "2005-01-01", independent: false, program: "master", studyLoad: 49, parentalIncome: 0, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "valid", uploaded: "2025-01-01"}, + {type: "TAX", status: "valid", uploaded: "2025-01-01"}, + ]}}, + {applicant: {dob: "2005-01-01", independent: false, program: "master", studyLoad: 49, parentalIncome: 0, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "valid", uploaded: "2025-01-01"}, + {type: "TAX", status: "valid", uploaded: "2025-01-01"}, + ], age: 20, selfSupporting: false, validDocs: ["ID", "ENR", "TAX"], requiredDocs: ["ID", "ENR", "TAX"], missingDocs: [], baseGrant: 0, parentalContribution: 0, grant: 0, decision: "load-too-low"}}, + ], + [ + {applicant: {dob: "2005-01-01", independent: false, program: "bachelor", studyLoad: 100, parentalIncome: 300000, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "valid", uploaded: "2025-01-01"}, + {type: "TAX", status: "valid", uploaded: "2025-01-01"}, + ]}}, + {applicant: {dob: "2005-01-01", independent: false, program: "bachelor", studyLoad: 100, parentalIncome: 300000, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "valid", uploaded: "2025-01-01"}, + {type: "TAX", status: "valid", uploaded: "2025-01-01"}, + ], age: 20, selfSupporting: false, validDocs: ["ID", "ENR", "TAX"], requiredDocs: ["ID", "ENR", "TAX"], missingDocs: [], baseGrant: 1000, parentalContribution: 1083.33, grant: 0, decision: "means-tested-out"}}, + ], + // A load of exactly 50 is half a grant. + [ + {applicant: {dob: "2004-01-01", independent: false, program: "vocational", studyLoad: 50, parentalIncome: 52000, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "valid", uploaded: "2025-01-01"}, + {type: "TAX", status: "valid", uploaded: "2025-01-01"}, + ]}}, + {applicant: {dob: "2004-01-01", independent: false, program: "vocational", studyLoad: 50, parentalIncome: 52000, documents: [ + {type: "ID", status: "valid", uploaded: "2025-01-01"}, + {type: "ENR", status: "valid", uploaded: "2025-01-01"}, + {type: "TAX", status: "valid", uploaded: "2025-01-01"}, + ], age: 21, selfSupporting: false, validDocs: ["ID", "ENR", "TAX"], requiredDocs: ["ID", "ENR", "TAX"], missingDocs: [], baseGrant: 800, parentalContribution: 50, grant: 350, decision: "award"}}, + ], + { + input: {applicant: {dob: "2006-01-01", independent: false, documents: [{type: "ID", status: "valid", uploaded: "2025-01-01"}]}}, + goals: ["applicant.missingDocs"], + output: {applicant: {dob: "2006-01-01", independent: false, documents: [{type: "ID", status: "valid", uploaded: "2025-01-01"}], age: 19, validDocs: ["ID"], requiredDocs: ["ID", "ENR", "TAX"], missingDocs: ["ENR", "TAX"]}}, + }, + [{applicant: {dob: "2005-01-01", program: "bachelor", studyLoad: 100, documents: []}}, "!error: MissingRequiredInputs"], + [{applicant: {dob: "2005-01-01", independent: false, program: "bachelor", studyLoad: 100, documents: [{type: "PASS", status: "valid", uploaded: "2025-01-01"}]}}, "!error: InputValidationFailed"], + [{applicant: {dob: "2005-01-01", independent: false, program: "bachelor", studyLoad: 100, documents: [{type: "Identity", status: "valid", uploaded: "2025-01-01"}]}}, "!error: InputValidationFailed"], + [{applicant: {dob: "2005-01-01", independent: false, program: "bachelor", studyLoad: 100, documents: [{type: "ID", status: "revoked", uploaded: "2025-01-01"}]}}, "!error: InputValidationFailed"], + [{applicant: {dob: "2005-01-01", independent: false, program: "bachelor", documents: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Small business loan ----------------------------------------------------------------------- +// A share-weighted owner credit score, debt service over existing loans plus the new payment, a +// debt service coverage ratio guarded against zero, exclusions collected by a first-hit `[]` +// table (sectors match case-sensitively), and the grouped assertion +// `no exclusions and within max and (dscr >= 1.25 or guaranteed)`. + +{ + name: "small business loan with owners and existing loans", + policy: { + globals: {program: {maxLoan: "number", minScore: "number"}}, + models: { + business: {founded: "date", sector: "string", revenue: "number", requested: "number", owners: "owner[]", loans: "loan[]"}, + owner: {creditScore: "number", share: "number", guarantor: "boolean"}, + loan: {monthly: "number", inArrears: "boolean"}, + }, + blocks: [ + {expression: "business.ageYears", value: "d().diff(business.founded, 'year')"}, + {expression: "business.score", value: "round(sum(map(business.owners, #.creditScore * #.share)) / max([sum(map(business.owners, #.share)), 1]), 0)"}, + {expression: "business.lowScore", value: "business.score < minScore"}, + {expression: "business.debtService", value: "sum(map(business.loans, #.monthly))"}, + {expression: "business.newPayment", value: "round(business.requested / 60, 2)"}, + {expression: "business.dscr", value: "business.debtService + business.newPayment > 0 ? round(business.revenue / 12 * 0.2 / (business.debtService + business.newPayment), 2) : 99"}, + {expression: "business.arrears", value: "some(business.loans, #.inArrears)"}, + {expression: "business.guaranteed", value: "some(business.owners, #.guarantor and #.share >= 20)"}, + {table: "exclusions", inputs: ["business.ageYears", "business.lowScore", "business.arrears", "business.sector"], outputs: ["business.exclusions[]"], rules: [ + ["< 2", "", "", "", "'too-young'"], + ["", "true", "", "", "'low-score'"], + ["", "", "true", "", "'arrears'"], + ["", "", "", "'gambling', 'weapons'", "'excluded-sector'"], + ]}, + {expression: "business.maxEligible", value: "min([maxLoan, business.revenue * 0.25])"}, + {assertion: "business.eligible", conditions: [ + ["and", "len(business.exclusions) == 0", 0], + ["and", "business.requested <= business.maxEligible", 0], + ["or", "business.dscr >= 1.25", 1], + ["and", "business.guaranteed", 1], + ]}, + {match: "business.decision", arms: [ + ["business.eligible and business.dscr >= 1.25", "'approve'"], + ["business.eligible", "'approve-guaranteed'"], + ["len(business.exclusions) > 0", "'decline'"], + ["", "'counter-offer'"], + ]}, + ], + }, + cases: [ + [ + {maxLoan: 250000, minScore: 650, business: {founded: "2015-01-01", sector: "retail", revenue: 1200000, requested: 100000, owners: [{creditScore: 720, share: 60, guarantor: false}, {creditScore: 680, share: 40, guarantor: true}], loans: [{monthly: 2000, inArrears: false}]}}, + {maxLoan: 250000, minScore: 650, business: {founded: "2015-01-01", sector: "retail", revenue: 1200000, requested: 100000, owners: [{creditScore: 720, share: 60, guarantor: false}, {creditScore: 680, share: 40, guarantor: true}], loans: [{monthly: 2000, inArrears: false}], + ageYears: 10, score: 704, lowScore: false, debtService: 2000, newPayment: 1666.67, dscr: 5.45, arrears: false, guaranteed: true, exclusions: [], maxEligible: 250000, eligible: true, decision: "approve"}}, + ], + [ + {maxLoan: 250000, minScore: 650, business: {founded: "2024-01-01", sector: "tech", revenue: 200000, requested: 30000, owners: [{creditScore: 780, share: 100, guarantor: true}], loans: []}}, + {maxLoan: 250000, minScore: 650, business: {founded: "2024-01-01", sector: "tech", revenue: 200000, requested: 30000, owners: [{creditScore: 780, share: 100, guarantor: true}], loans: [], + ageYears: 1, score: 780, lowScore: false, debtService: 0, newPayment: 500, dscr: 6.67, arrears: false, guaranteed: true, exclusions: ["too-young"], maxEligible: 50000, eligible: false, decision: "decline"}}, + ], + // Coverage below 1.25 is rescued by a guarantor holding at least 20%. + [ + {maxLoan: 250000, minScore: 650, business: {founded: "2018-06-01", sector: "retail", revenue: 240000, requested: 60000, owners: [{creditScore: 700, share: 50, guarantor: true}, {creditScore: 660, share: 50, guarantor: false}], loans: [{monthly: 2500, inArrears: false}]}}, + {maxLoan: 250000, minScore: 650, business: {founded: "2018-06-01", sector: "retail", revenue: 240000, requested: 60000, owners: [{creditScore: 700, share: 50, guarantor: true}, {creditScore: 660, share: 50, guarantor: false}], loans: [{monthly: 2500, inArrears: false}], + ageYears: 6, score: 680, lowScore: false, debtService: 2500, newPayment: 1000, dscr: 1.14, arrears: false, guaranteed: true, exclusions: [], maxEligible: 60000, eligible: true, decision: "approve-guaranteed"}}, + ], + [ + {maxLoan: 250000, minScore: 650, business: {founded: "2018-06-01", sector: "retail", revenue: 240000, requested: 60000, owners: [{creditScore: 700, share: 85, guarantor: false}, {creditScore: 660, share: 15, guarantor: true}], loans: [{monthly: 2500, inArrears: false}]}}, + {maxLoan: 250000, minScore: 650, business: {founded: "2018-06-01", sector: "retail", revenue: 240000, requested: 60000, owners: [{creditScore: 700, share: 85, guarantor: false}, {creditScore: 660, share: 15, guarantor: true}], loans: [{monthly: 2500, inArrears: false}], + ageYears: 6, score: 694, lowScore: false, debtService: 2500, newPayment: 1000, dscr: 1.14, arrears: false, guaranteed: false, exclusions: [], maxEligible: 60000, eligible: false, decision: "counter-offer"}}, + ], + [ + {maxLoan: 250000, minScore: 650, business: {founded: "2024-06-01", sector: "gambling", revenue: 100000, requested: 10000, owners: [{creditScore: 600, share: 100, guarantor: false}], loans: [{monthly: 500, inArrears: true}]}}, + {maxLoan: 250000, minScore: 650, business: {founded: "2024-06-01", sector: "gambling", revenue: 100000, requested: 10000, owners: [{creditScore: 600, share: 100, guarantor: false}], loans: [{monthly: 500, inArrears: true}], + ageYears: 0, score: 600, lowScore: true, debtService: 500, newPayment: 166.67, dscr: 2.5, arrears: true, guaranteed: false, exclusions: ["too-young", "low-score", "arrears", "excluded-sector"], maxEligible: 25000, eligible: false, decision: "decline"}}, + ], + // Every boundary at once: two years old, a score of exactly 650, coverage of exactly 1.25 + // and the request equal to the maximum. + [ + {maxLoan: 250000, minScore: 650, business: {founded: "2023-03-20", sector: "retail", revenue: 300000, requested: 75000, owners: [{creditScore: 650, share: 100, guarantor: false}], loans: [{monthly: 2750, inArrears: false}]}}, + {maxLoan: 250000, minScore: 650, business: {founded: "2023-03-20", sector: "retail", revenue: 300000, requested: 75000, owners: [{creditScore: 650, share: 100, guarantor: false}], loans: [{monthly: 2750, inArrears: false}], + ageYears: 2, score: 650, lowScore: false, debtService: 2750, newPayment: 1250, dscr: 1.25, arrears: false, guaranteed: false, exclusions: [], maxEligible: 75000, eligible: true, decision: "approve"}}, + ], + // No owners: the score divides by the floor of 1 and is 0. Nothing requested, nothing owed. + [ + {maxLoan: 250000, minScore: 650, business: {founded: "2010-01-01", sector: "retail", revenue: 100000, requested: 0, owners: [], loans: []}}, + {maxLoan: 250000, minScore: 650, business: {founded: "2010-01-01", sector: "retail", revenue: 100000, requested: 0, owners: [], loans: [], + ageYears: 15, score: 0, lowScore: true, debtService: 0, newPayment: 0, dscr: 99, arrears: false, guaranteed: false, exclusions: ["low-score"], maxEligible: 25000, eligible: false, decision: "decline"}}, + ], + // Above the program maximum; `Gambling` does not match the lower-case sector cell. + [ + {maxLoan: 250000, minScore: 650, business: {founded: "2000-01-01", sector: "Gambling", revenue: 2000000, requested: 300000, owners: [{creditScore: 800, share: 100, guarantor: true}], loans: []}}, + {maxLoan: 250000, minScore: 650, business: {founded: "2000-01-01", sector: "Gambling", revenue: 2000000, requested: 300000, owners: [{creditScore: 800, share: 100, guarantor: true}], loans: [], + ageYears: 25, score: 800, lowScore: false, debtService: 0, newPayment: 5000, dscr: 6.67, arrears: false, guaranteed: true, exclusions: [], maxEligible: 250000, eligible: false, decision: "counter-offer"}}, + ], + { + input: {business: {revenue: 120000, requested: 60000, loans: [{monthly: 1000, inArrears: false}]}}, + goals: ["business.dscr"], + output: {business: {revenue: 120000, requested: 60000, loans: [{monthly: 1000, inArrears: false}], debtService: 1000, newPayment: 1000, dscr: 1}}, + }, + [{maxLoan: 250000, business: {founded: "2000-01-01", sector: "retail", revenue: 1, requested: 1, owners: [], loans: []}}, "!error: MissingRequiredInputs"], + [{maxLoan: 250000, minScore: 650, business: {founded: "2000-01-01", sector: "retail", revenue: 1, requested: 1, owners: [{share: 100, guarantor: false}], loans: []}}, "!error: ExpressionFailed"], + [{maxLoan: 250000, minScore: 650, business: {founded: "2000-01-01", sector: "retail", revenue: 1, requested: 1, owners: [], loans: [{monthly: 1}]}}, "!error: ExpressionFailed"], + [{maxLoan: 250000, minScore: 650, business: {founded: "2000-01-01", sector: "retail", revenue: "1M", requested: 1, owners: [], loans: []}}, "!error: InputValidationFailed"], + ], +} + +// --- Childcare subsidy ------------------------------------------------------------------------- +// The family references one provider; per-child blocks read the root reference, the root +// income and globals. A per-child rate match puts special needs first, subsidised hours depend +// on the number of working parents, and the fee is capped by a global hourly cap. + +{ + name: "childcare subsidy with a referenced provider", + policy: { + globals: {scheme: {incomeCeiling: "number", hourlyCap: "number"}}, + models: { + family: {income: "number", workingParents: "number", provider: "&provider", children: "child[]"}, + provider: {id: "string", hourlyFee: "number", accredited: "boolean"}, + child: {dob: "date", hoursPerWeek: "number", specialNeeds: "boolean?"}, + }, + blocks: [ + {expression: "child.age", value: "d().diff(child.dob, 'year')"}, + {expression: "child.eligible", value: "child.age < 13 and family.provider.accredited"}, + {match: "child.rate", arms: [ + ["child.specialNeeds ?? false", "0.95"], + ["family.income <= 40000", "0.85"], + ["family.income <= 80000", "0.6"], + ["family.income <= incomeCeiling", "0.3"], + ["", "0"], + ]}, + {expression: "child.subsidisedHours", value: "min([child.hoursPerWeek, family.workingParents >= 2 ? 50 : 24])"}, + {expression: "child.weekly", value: "child.eligible ? round(child.subsidisedHours * min([family.provider.hourlyFee, hourlyCap]) * child.rate, 2) : 0"}, + {expression: "family.weeklySubsidy", value: "sum(map(family.children, #.weekly))"}, + {expression: "family.eligibleChildren", value: "count(family.children, #.eligible)"}, + {expression: "family.gapFee", value: "round(sum(map(family.children, #.hoursPerWeek)) * family.provider.hourlyFee - family.weeklySubsidy, 2)"}, + {match: "family.status", arms: [ + ["family.eligibleChildren == 0", "'no-entitlement'"], + ["family.weeklySubsidy == 0", "'income-too-high'"], + ["", "'entitled'"], + ]}, + ], + }, + cases: [ + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 35000, workingParents: 2, provider: "P1", children: [{dob: "2021-05-01", hoursPerWeek: 40}]}, provider: [{id: "P1", hourlyFee: 10, accredited: true}, {id: "P2", hourlyFee: 15, accredited: true}, {id: "P3", hourlyFee: 8, accredited: false}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 35000, workingParents: 2, provider: {id: "P1", hourlyFee: 10, accredited: true}, children: [ + {dob: "2021-05-01", hoursPerWeek: 40, age: 3, eligible: true, rate: 0.85, subsidisedHours: 40, weekly: 340}, + ], weeklySubsidy: 340, eligibleChildren: 1, gapFee: 60, status: "entitled"}, provider: [{id: "P1", hourlyFee: 10, accredited: true}, {id: "P2", hourlyFee: 15, accredited: true}, {id: "P3", hourlyFee: 8, accredited: false}]}, + ], + // A provider fee above the cap, one working parent (24 hours), a special-needs child first. + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 60000, workingParents: 1, provider: "P2", children: [ + {dob: "2020-01-01", hoursPerWeek: 30, specialNeeds: true}, + {dob: "2012-03-21", hoursPerWeek: 10}, + ]}, provider: [{id: "P2", hourlyFee: 15, accredited: true}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 60000, workingParents: 1, provider: {id: "P2", hourlyFee: 15, accredited: true}, children: [ + {dob: "2020-01-01", hoursPerWeek: 30, specialNeeds: true, age: 5, eligible: true, rate: 0.95, subsidisedHours: 24, weekly: 273.6}, + {dob: "2012-03-21", hoursPerWeek: 10, age: 12, eligible: true, rate: 0.6, subsidisedHours: 10, weekly: 72}, + ], weeklySubsidy: 345.6, eligibleChildren: 2, gapFee: 254.4, status: "entitled"}, provider: [{id: "P2", hourlyFee: 15, accredited: true}]}, + ], + // An unaccredited provider: nobody is eligible. + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 50000, workingParents: 2, provider: "P3", children: [{dob: "2022-01-01", hoursPerWeek: 20}]}, provider: [{id: "P3", hourlyFee: 8, accredited: false}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 50000, workingParents: 2, provider: {id: "P3", hourlyFee: 8, accredited: false}, children: [ + {dob: "2022-01-01", hoursPerWeek: 20, age: 3, eligible: false, rate: 0.6, subsidisedHours: 20, weekly: 0}, + ], weeklySubsidy: 0, eligibleChildren: 0, gapFee: 160, status: "no-entitlement"}, provider: [{id: "P3", hourlyFee: 8, accredited: false}]}, + ], + // A child turning 13 today is no longer eligible. + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 50000, workingParents: 2, provider: "P1", children: [{dob: "2012-03-20", hoursPerWeek: 15}]}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 50000, workingParents: 2, provider: {id: "P1", hourlyFee: 10, accredited: true}, children: [ + {dob: "2012-03-20", hoursPerWeek: 15, age: 13, eligible: false, rate: 0.6, subsidisedHours: 15, weekly: 0}, + ], weeklySubsidy: 0, eligibleChildren: 0, gapFee: 150, status: "no-entitlement"}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, + ], + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 150000, workingParents: 2, provider: "P1", children: [{dob: "2021-01-01", hoursPerWeek: 45}]}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 150000, workingParents: 2, provider: {id: "P1", hourlyFee: 10, accredited: true}, children: [ + {dob: "2021-01-01", hoursPerWeek: 45, age: 4, eligible: true, rate: 0, subsidisedHours: 45, weekly: 0}, + ], weeklySubsidy: 0, eligibleChildren: 1, gapFee: 450, status: "income-too-high"}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, + ], + // Income bands are inclusive at the ceiling; hours above 50 are not subsidised. + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 120000, workingParents: 2, provider: "P2", children: [{dob: "2019-06-01", hoursPerWeek: 55}]}, provider: [{id: "P2", hourlyFee: 15, accredited: true}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 120000, workingParents: 2, provider: {id: "P2", hourlyFee: 15, accredited: true}, children: [ + {dob: "2019-06-01", hoursPerWeek: 55, age: 5, eligible: true, rate: 0.3, subsidisedHours: 50, weekly: 180}, + ], weeklySubsidy: 180, eligibleChildren: 1, gapFee: 645, status: "entitled"}, provider: [{id: "P2", hourlyFee: 15, accredited: true}]}, + ], + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 200000, workingParents: 1, provider: "P1", children: [{dob: "2023-01-01", hoursPerWeek: 10, specialNeeds: true}]}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 200000, workingParents: 1, provider: {id: "P1", hourlyFee: 10, accredited: true}, children: [ + {dob: "2023-01-01", hoursPerWeek: 10, specialNeeds: true, age: 2, eligible: true, rate: 0.95, subsidisedHours: 10, weekly: 95}, + ], weeklySubsidy: 95, eligibleChildren: 1, gapFee: 5, status: "entitled"}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, + ], + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 40000, workingParents: 1, provider: "P2", children: [{dob: "2018-01-01", hoursPerWeek: 24, specialNeeds: null}]}, provider: [{id: "P2", hourlyFee: 15, accredited: true}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 40000, workingParents: 1, provider: {id: "P2", hourlyFee: 15, accredited: true}, children: [ + {dob: "2018-01-01", hoursPerWeek: 24, specialNeeds: null, age: 7, eligible: true, rate: 0.85, subsidisedHours: 24, weekly: 244.8}, + ], weeklySubsidy: 244.8, eligibleChildren: 1, gapFee: 115.2, status: "entitled"}, provider: [{id: "P2", hourlyFee: 15, accredited: true}]}, + ], + [ + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 10000, workingParents: 0, provider: "P1", children: []}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, + {incomeCeiling: 120000, hourlyCap: 12, family: {income: 10000, workingParents: 0, provider: {id: "P1", hourlyFee: 10, accredited: true}, children: [], weeklySubsidy: 0, eligibleChildren: 0, gapFee: 0, status: "no-entitlement"}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, + ], + { + input: {family: {provider: "P3", children: [{dob: "2020-01-01"}, {dob: "2010-01-01"}]}, provider: [{id: "P3", hourlyFee: 8, accredited: true}]}, + goals: ["family.eligibleChildren"], + output: {family: {provider: {id: "P3", hourlyFee: 8, accredited: true}, children: [{dob: "2020-01-01", age: 5, eligible: true}, {dob: "2010-01-01", age: 15, eligible: false}], eligibleChildren: 1}, provider: [{id: "P3", hourlyFee: 8, accredited: true}]}, + }, + [{incomeCeiling: 120000, hourlyCap: 12, family: {income: 1, workingParents: 1, provider: "P9", children: []}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, "!error: InputValidationFailed"], + [{incomeCeiling: 120000, family: {income: 1, workingParents: 1, provider: "P1", children: []}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, "!error: MissingRequiredInputs"], + [{incomeCeiling: 120000, hourlyCap: 12, family: {income: 1, workingParents: 1, provider: "P1", children: [{dob: "2020-01-01"}]}, provider: [{id: "P1", hourlyFee: 10, accredited: true}]}, "!error: ExpressionFailed"], + [{incomeCeiling: 120000, hourlyCap: 12, family: {income: 1, workingParents: 1, provider: "P1", children: []}, provider: [{id: "P1", hourlyFee: 10, accredited: "yes"}]}, "!error: InputValidationFailed"], + ], +} + +// --- Residency and identity documents ---------------------------------------------------------- +// Dictionary-typed document kinds and issuing countries; per-document currency and usability; +// lawful residence as the grouped assertion `nordic or (permit and resident one year)`; a +// first-hit `[]` table collecting outstanding items and a verification match. + +{ + name: "residency and identity document checks", + policy: { + dictionaries: { + docKind: [["PASS", "Passport"], ["NID", "National id card"], ["RP", "Residence permit"], ["BANK", "Bank statement"], ["UTIL", "Utility bill"]], + country: ["NO", "SE", "DK", "PL", "UA"], + }, + models: { + applicant: {citizenship: "country", residentSince: "date", documents: "doc[]"}, + doc: {kind: "docKind", expires: "date?", issuedBy: "country", verified: "boolean"}, + }, + blocks: [ + {expression: "doc.current", value: "(doc.expires ?? d('9999-12-31')) > d()"}, + {expression: "doc.usable", value: "doc.verified and doc.current"}, + {expression: "applicant.nordic", value: "applicant.citizenship in ['NO', 'SE', 'DK']"}, + {expression: "applicant.residenceYears", value: "d().diff(applicant.residentSince, 'year')"}, + {expression: "applicant.hasIdentity", value: "some(applicant.documents, #.usable and #.kind in ['PASS', 'NID'])"}, + {expression: "applicant.hasPermit", value: "some(applicant.documents, #.usable and #.kind == 'RP')"}, + {expression: "applicant.hasAddressProof", value: "some(applicant.documents, #.usable and #.kind in ['BANK', 'UTIL'])"}, + {assertion: "applicant.lawfulResidence", conditions: [ + ["or", "applicant.nordic", 0], + ["and", "applicant.hasPermit", 1], + ["and", "applicant.residenceYears >= 1", 1], + ]}, + {table: "outstanding", inputs: ["applicant.hasIdentity", "applicant.lawfulResidence", "applicant.hasAddressProof"], outputs: ["applicant.outstanding[]"], rules: [ + ["false", "", "", "'identity'"], + ["", "false", "", "'residence'"], + ["", "", "false", "'address'"], + ]}, + {match: "applicant.verification", arms: [ + ["len(applicant.outstanding) == 0", "'verified'"], + ["'identity' in applicant.outstanding", "'blocked'"], + ["", "'partial'"], + ]}, + ], + }, + cases: [ + [ + {applicant: {citizenship: "NO", residentSince: "2000-01-01", documents: [{kind: "PASS", expires: "2030-01-01", issuedBy: "NO", verified: true}, {kind: "UTIL", expires: null, issuedBy: "NO", verified: true}]}}, + {applicant: {citizenship: "NO", residentSince: "2000-01-01", documents: [ + {kind: "PASS", expires: "2030-01-01", issuedBy: "NO", verified: true, current: true, usable: true}, + {kind: "UTIL", expires: null, issuedBy: "NO", verified: true, current: true, usable: true}, + ], nordic: true, residenceYears: 25, hasIdentity: true, hasPermit: false, hasAddressProof: true, lawfulResidence: true, outstanding: [], verification: "verified"}}, + ], + [ + {applicant: {citizenship: "PL", residentSince: "2023-01-01", documents: [ + {kind: "PASS", expires: "2028-01-01", issuedBy: "PL", verified: true}, + {kind: "RP", expires: "2026-01-01", issuedBy: "NO", verified: true}, + {kind: "BANK", issuedBy: "NO", verified: true}, + ]}}, + {applicant: {citizenship: "PL", residentSince: "2023-01-01", documents: [ + {kind: "PASS", expires: "2028-01-01", issuedBy: "PL", verified: true, current: true, usable: true}, + {kind: "RP", expires: "2026-01-01", issuedBy: "NO", verified: true, current: true, usable: true}, + {kind: "BANK", issuedBy: "NO", verified: true, current: true, usable: true}, + ], nordic: false, residenceYears: 2, hasIdentity: true, hasPermit: true, hasAddressProof: true, lawfulResidence: true, outstanding: [], verification: "verified"}}, + ], + // A permit but under a year of residence. + [ + {applicant: {citizenship: "UA", residentSince: "2024-06-01", documents: [ + {kind: "PASS", expires: "2027-01-01", issuedBy: "UA", verified: true}, + {kind: "RP", expires: "2026-01-01", issuedBy: "NO", verified: true}, + ]}}, + {applicant: {citizenship: "UA", residentSince: "2024-06-01", documents: [ + {kind: "PASS", expires: "2027-01-01", issuedBy: "UA", verified: true, current: true, usable: true}, + {kind: "RP", expires: "2026-01-01", issuedBy: "NO", verified: true, current: true, usable: true}, + ], nordic: false, residenceYears: 0, hasIdentity: true, hasPermit: true, hasAddressProof: false, lawfulResidence: false, outstanding: ["residence", "address"], verification: "partial"}}, + ], + // An id card expiring today (midnight) is no longer current; an unverified statement is unusable. + [ + {applicant: {citizenship: "SE", residentSince: "2010-01-01", documents: [ + {kind: "NID", expires: "2025-03-20", issuedBy: "SE", verified: true}, + {kind: "BANK", issuedBy: "SE", verified: false}, + ]}}, + {applicant: {citizenship: "SE", residentSince: "2010-01-01", documents: [ + {kind: "NID", expires: "2025-03-20", issuedBy: "SE", verified: true, current: false, usable: false}, + {kind: "BANK", issuedBy: "SE", verified: false, current: true, usable: false}, + ], nordic: true, residenceYears: 15, hasIdentity: false, hasPermit: false, hasAddressProof: false, lawfulResidence: true, outstanding: ["identity", "address"], verification: "blocked"}}, + ], + [ + {applicant: {citizenship: "UA", residentSince: "2020-01-01", documents: [ + {kind: "PASS", expires: "2030-01-01", issuedBy: "UA", verified: true}, + {kind: "RP", expires: "2025-01-01", issuedBy: "NO", verified: true}, + {kind: "UTIL", issuedBy: "NO", verified: true}, + ]}}, + {applicant: {citizenship: "UA", residentSince: "2020-01-01", documents: [ + {kind: "PASS", expires: "2030-01-01", issuedBy: "UA", verified: true, current: true, usable: true}, + {kind: "RP", expires: "2025-01-01", issuedBy: "NO", verified: true, current: false, usable: false}, + {kind: "UTIL", issuedBy: "NO", verified: true, current: true, usable: true}, + ], nordic: false, residenceYears: 5, hasIdentity: true, hasPermit: false, hasAddressProof: true, lawfulResidence: false, outstanding: ["residence"], verification: "partial"}}, + ], + [ + {applicant: {citizenship: "DK", residentSince: "2025-01-01", documents: []}}, + {applicant: {citizenship: "DK", residentSince: "2025-01-01", documents: [], nordic: true, residenceYears: 0, hasIdentity: false, hasPermit: false, hasAddressProof: false, lawfulResidence: true, outstanding: ["identity", "address"], verification: "blocked"}}, + ], + // Exactly one year of residence with a permit. + [ + {applicant: {citizenship: "PL", residentSince: "2024-03-20", documents: [ + {kind: "NID", expires: "2029-01-01", issuedBy: "PL", verified: true}, + {kind: "RP", expires: "2026-01-01", issuedBy: "NO", verified: true}, + {kind: "BANK", issuedBy: "NO", verified: true}, + ]}}, + {applicant: {citizenship: "PL", residentSince: "2024-03-20", documents: [ + {kind: "NID", expires: "2029-01-01", issuedBy: "PL", verified: true, current: true, usable: true}, + {kind: "RP", expires: "2026-01-01", issuedBy: "NO", verified: true, current: true, usable: true}, + {kind: "BANK", issuedBy: "NO", verified: true, current: true, usable: true}, + ], nordic: false, residenceYears: 1, hasIdentity: true, hasPermit: true, hasAddressProof: true, lawfulResidence: true, outstanding: [], verification: "verified"}}, + ], + { + input: {applicant: {documents: [{kind: "PASS", expires: "2030-01-01", issuedBy: "NO", verified: true}, {kind: "NID", expires: "2020-01-01", issuedBy: "NO", verified: true}]}}, + goals: ["applicant.hasIdentity"], + output: {applicant: {documents: [ + {kind: "PASS", expires: "2030-01-01", issuedBy: "NO", verified: true, current: true, usable: true}, + {kind: "NID", expires: "2020-01-01", issuedBy: "NO", verified: true, current: false, usable: false}, + ], hasIdentity: true}}, + }, + // A document without `verified` reads null; `null and ...` is an error. + [{applicant: {citizenship: "NO", residentSince: "2000-01-01", documents: [{kind: "PASS", issuedBy: "NO"}]}}, "!error: ExpressionFailed"], + [{applicant: {citizenship: "NO", residentSince: "2000-01-01", documents: [{kind: "DL", issuedBy: "NO", verified: true}]}}, "!error: InputValidationFailed"], + [{applicant: {citizenship: "Norway", residentSince: "2000-01-01", documents: []}}, "!error: InputValidationFailed"], + [{applicant: {citizenship: "NO", residentSince: "2000-01-01", documents: [{kind: "PASS", issuedBy: "DE", verified: true}]}}, "!error: InputValidationFailed"], + [{applicant: {citizenship: "NO", documents: []}}, "!error: MissingRequiredInputs"], + ], +} + +// --- Old-age supplement ------------------------------------------------------------------------ +// The supplement tops up pensions to a residence-prorated full amount (married rate 85%), half +// of a partner's income counts, and a three-condition assertion gates the payment, chosen by a +// match whose arm value is an expression. + +{ + name: "old-age supplement with pensions and globals", + policy: { + globals: {supplement: {fullAmount: "number", minAge: "number"}}, + models: { + person: {dob: "date", residenceYears: "number", married: "boolean", partnerIncome: "number?", pensions: "pension[]"}, + pension: {kind: "string(state|occupational|private)", monthly: "number"}, + }, + blocks: [ + {expression: "person.age", value: "d().diff(person.dob, 'year')"}, + {expression: "person.ownIncome", value: "sum(map(person.pensions, #.monthly))"}, + {expression: "person.residenceRatio", value: "min([person.residenceYears / 40, 1])"}, + {expression: "person.maxSupplement", value: "round(fullAmount * person.residenceRatio * (person.married ? 0.85 : 1), 2)"}, + {expression: "person.countedIncome", value: "person.ownIncome + (person.married ? (person.partnerIncome ?? 0) * 0.5 : 0)"}, + {expression: "person.supplement", value: "max([round(person.maxSupplement - person.countedIncome, 2), 0])"}, + {assertion: "person.qualifies", conditions: ["person.age >= minAge", "person.residenceYears >= 10", "person.supplement > 0"]}, + {match: "person.payment", arms: [ + ["person.qualifies", "person.supplement"], + ["", "0"], + ]}, + ], + }, + cases: [ + [ + {fullAmount: 2000, minAge: 67, person: {dob: "1950-01-01", residenceYears: 40, married: false, pensions: [{kind: "state", monthly: 800}]}}, + {fullAmount: 2000, minAge: 67, person: {dob: "1950-01-01", residenceYears: 40, married: false, pensions: [{kind: "state", monthly: 800}], age: 75, ownIncome: 800, residenceRatio: 1, maxSupplement: 2000, countedIncome: 800, supplement: 1200, qualifies: true, payment: 1200}}, + ], + [ + {fullAmount: 2000, minAge: 67, person: {dob: "1955-05-01", residenceYears: 20, married: true, partnerIncome: 1000, pensions: [{kind: "state", monthly: 300}, {kind: "private", monthly: 100}]}}, + {fullAmount: 2000, minAge: 67, person: {dob: "1955-05-01", residenceYears: 20, married: true, partnerIncome: 1000, pensions: [{kind: "state", monthly: 300}, {kind: "private", monthly: 100}], age: 69, ownIncome: 400, residenceRatio: 0.5, maxSupplement: 850, countedIncome: 900, supplement: 0, qualifies: false, payment: 0}}, + ], + // Exactly the minimum age and ten years of residence. + [ + {fullAmount: 2000, minAge: 67, person: {dob: "1958-03-20", residenceYears: 10, married: false, pensions: []}}, + {fullAmount: 2000, minAge: 67, person: {dob: "1958-03-20", residenceYears: 10, married: false, pensions: [], age: 67, ownIncome: 0, residenceRatio: 0.25, maxSupplement: 500, countedIncome: 0, supplement: 500, qualifies: true, payment: 500}}, + ], + [ + {fullAmount: 2000, minAge: 67, person: {dob: "1958-03-21", residenceYears: 50, married: false, pensions: [{kind: "occupational", monthly: 1500}]}}, + {fullAmount: 2000, minAge: 67, person: {dob: "1958-03-21", residenceYears: 50, married: false, pensions: [{kind: "occupational", monthly: 1500}], age: 66, ownIncome: 1500, residenceRatio: 1, maxSupplement: 2000, countedIncome: 1500, supplement: 500, qualifies: false, payment: 0}}, + ], + [ + {fullAmount: 2000, minAge: 67, person: {dob: "1940-01-01", residenceYears: 9, married: false, pensions: [{kind: "state", monthly: 100}]}}, + {fullAmount: 2000, minAge: 67, person: {dob: "1940-01-01", residenceYears: 9, married: false, pensions: [{kind: "state", monthly: 100}], age: 85, ownIncome: 100, residenceRatio: 0.225, maxSupplement: 450, countedIncome: 100, supplement: 350, qualifies: false, payment: 0}}, + ], + // A null partner income counts as zero; a supplement of one cent still qualifies. + [ + {fullAmount: 2000, minAge: 67, person: {dob: "1950-01-01", residenceYears: 32, married: true, partnerIncome: null, pensions: [{kind: "state", monthly: 1000}, {kind: "occupational", monthly: 359.99}]}}, + {fullAmount: 2000, minAge: 67, person: {dob: "1950-01-01", residenceYears: 32, married: true, partnerIncome: null, pensions: [{kind: "state", monthly: 1000}, {kind: "occupational", monthly: 359.99}], age: 75, ownIncome: 1359.99, residenceRatio: 0.8, maxSupplement: 1360, countedIncome: 1359.99, supplement: 0.01, qualifies: true, payment: 0.01}}, + ], + // A partner's income is ignored for a single person. + [ + {fullAmount: 1800, minAge: 65, person: {dob: "1959-01-01", residenceYears: 45, married: false, partnerIncome: 5000, pensions: [{kind: "state", monthly: 900}]}}, + {fullAmount: 1800, minAge: 65, person: {dob: "1959-01-01", residenceYears: 45, married: false, partnerIncome: 5000, pensions: [{kind: "state", monthly: 900}], age: 66, ownIncome: 900, residenceRatio: 1, maxSupplement: 1800, countedIncome: 900, supplement: 900, qualifies: true, payment: 900}}, + ], + { + input: {fullAmount: 2000, person: {residenceYears: 44, married: true}}, + goals: ["person.maxSupplement"], + output: {fullAmount: 2000, person: {residenceYears: 44, married: true, residenceRatio: 1, maxSupplement: 1700}}, + }, + [{fullAmount: 2000, minAge: 67, person: {dob: "1950-01-01", residenceYears: 40, married: false, pensions: [{kind: "annuity", monthly: 1}]}}, "!error: InputValidationFailed"], + [{fullAmount: 2000, minAge: 67, person: {dob: "1950-01-01", residenceYears: 40, pensions: []}}, "!error: MissingRequiredInputs"], + [{minAge: 67, person: {dob: "1950-01-01", residenceYears: 40, married: false, pensions: []}}, "!error: MissingRequiredInputs"], + [{fullAmount: 2000, minAge: 67, person: {dob: "1950-01-01", residenceYears: 40, married: true, partnerIncome: "none", pensions: []}}, "!error: InputValidationFailed"], + ], +} diff --git a/core/engine/tests/spec/policy/44-realistic-commerce.json5 b/core/engine/tests/spec/policy/44-realistic-commerce.json5 new file mode 100644 index 00000000..d02c5b86 --- /dev/null +++ b/core/engine/tests/spec/policy/44-realistic-commerce.json5 @@ -0,0 +1,672 @@ +// Realistic commerce policies: cart promotions with per-item two-output tables and coupons, +// shipping by billable weight with surcharges collected in two `[]` columns and a referenced +// zone, sales tax by referenced jurisdiction and product tax codes, loyalty points and tier +// progression against globals, and checkout fraud scoring with collected signals and points. +// Each suite combines several block kinds over related entities and runs valid, boundary, +// missing and invalid data. Evaluation time is fixed at 2025-03-20T10:15:30Z. + +// --- Cart promotions --------------------------------------------------------------------------- +// A per-item first-hit table with two outputs (sale items take no promotion first, apparel +// three-for, books 5%), a coupon match whose arm values are expressions over the non-sale +// remainder, a tier discount on what is left, and totals. + +{ + name: "cart promotions, coupons and member tiers", + policy: { + models: { + cart: {memberTier: "string(none|silver|gold)", couponCode: "string?", items: "item[]"}, + item: {sku: "string", category: "string(electronics|apparel|grocery|books)", unitPrice: "number", qty: "number", onSale: "boolean"}, + }, + blocks: [ + {expression: "item.lineTotal", value: "item.unitPrice * item.qty"}, + {table: "promo", inputs: ["item.onSale", "item.category", "item.qty"], outputs: ["item.promoPct", "item.promoLabel"], rules: [ + ["true", "", "", "0", "'sale-item'"], + ["", "'apparel'", ">= 3", "0.2", "'3-for-apparel'"], + ["", "'books'", "", "0.05", "'books'"], + ["", "", "", "0", "'none'"], + ]}, + {expression: "item.promoAmount", value: "round(item.lineTotal * item.promoPct, 2)"}, + {expression: "cart.subtotal", value: "sum(map(cart.items, #.lineTotal))"}, + {expression: "cart.promoTotal", value: "sum(map(cart.items, #.promoAmount))"}, + {expression: "cart.couponBase", value: "sum(map(filter(cart.items, not #.onSale), #.lineTotal - #.promoAmount))"}, + {match: "cart.couponDiscount", arms: [ + ["cart.couponCode == 'SAVE10' and cart.couponBase >= 50", "round(cart.couponBase * 0.1, 2)"], + ["cart.couponCode == 'FLAT5'", "min([5, cart.couponBase])"], + ["", "0"], + ]}, + {match: "cart.tierPct", arms: [ + ["cart.memberTier == 'gold'", "0.05"], + ["cart.memberTier == 'silver'", "0.02"], + ["", "0"], + ]}, + {expression: "cart.tierDiscount", value: "round((cart.subtotal - cart.promoTotal - cart.couponDiscount) * cart.tierPct, 2)"}, + {expression: "cart.total", value: "cart.subtotal - cart.promoTotal - cart.couponDiscount - cart.tierDiscount"}, + {expression: "cart.savings", value: "cart.promoTotal + cart.couponDiscount + cart.tierDiscount"}, + ], + }, + cases: [ + [ + {cart: {memberTier: "none", items: [{sku: "A", category: "electronics", unitPrice: 100, qty: 1, onSale: false}]}}, + {cart: {memberTier: "none", items: [ + {sku: "A", category: "electronics", unitPrice: 100, qty: 1, onSale: false, lineTotal: 100, promoPct: 0, promoLabel: "none", promoAmount: 0}, + ], subtotal: 100, promoTotal: 0, couponBase: 100, couponDiscount: 0, tierPct: 0, tierDiscount: 0, total: 100, savings: 0}}, + ], + // Every discount stacks: apparel three-for, books, SAVE10 on the remainder, then gold. + [ + {cart: {memberTier: "gold", couponCode: "SAVE10", items: [ + {sku: "T", category: "apparel", unitPrice: 20, qty: 3, onSale: false}, + {sku: "B", category: "books", unitPrice: 15, qty: 2, onSale: false}, + ]}}, + {cart: {memberTier: "gold", couponCode: "SAVE10", items: [ + {sku: "T", category: "apparel", unitPrice: 20, qty: 3, onSale: false, lineTotal: 60, promoPct: 0.2, promoLabel: "3-for-apparel", promoAmount: 12}, + {sku: "B", category: "books", unitPrice: 15, qty: 2, onSale: false, lineTotal: 30, promoPct: 0.05, promoLabel: "books", promoAmount: 1.5}, + ], subtotal: 90, promoTotal: 13.5, couponBase: 76.5, couponDiscount: 7.65, tierPct: 0.05, tierDiscount: 3.44, total: 65.41, savings: 24.59}}, + ], + // SAVE10 needs a coupon base of 50: 49.90 earns nothing. + [ + {cart: {memberTier: "silver", couponCode: "SAVE10", items: [{sku: "G", category: "grocery", unitPrice: 4.99, qty: 10, onSale: false}]}}, + {cart: {memberTier: "silver", couponCode: "SAVE10", items: [ + {sku: "G", category: "grocery", unitPrice: 4.99, qty: 10, onSale: false, lineTotal: 49.9, promoPct: 0, promoLabel: "none", promoAmount: 0}, + ], subtotal: 49.9, promoTotal: 0, couponBase: 49.9, couponDiscount: 0, tierPct: 0.02, tierDiscount: 1, total: 48.9, savings: 1}}, + ], + // Sale items are excluded from the coupon base. + [ + {cart: {memberTier: "none", couponCode: "FLAT5", items: [ + {sku: "TV", category: "electronics", unitPrice: 200, qty: 1, onSale: true}, + {sku: "G", category: "grocery", unitPrice: 10, qty: 2, onSale: false}, + ]}}, + {cart: {memberTier: "none", couponCode: "FLAT5", items: [ + {sku: "TV", category: "electronics", unitPrice: 200, qty: 1, onSale: true, lineTotal: 200, promoPct: 0, promoLabel: "sale-item", promoAmount: 0}, + {sku: "G", category: "grocery", unitPrice: 10, qty: 2, onSale: false, lineTotal: 20, promoPct: 0, promoLabel: "none", promoAmount: 0}, + ], subtotal: 220, promoTotal: 0, couponBase: 20, couponDiscount: 5, tierPct: 0, tierDiscount: 0, total: 215, savings: 5}}, + ], + // FLAT5 never exceeds the coupon base: the cart drops to zero. + [ + {cart: {memberTier: "gold", couponCode: "FLAT5", items: [{sku: "B", category: "books", unitPrice: 3, qty: 1, onSale: false}]}}, + {cart: {memberTier: "gold", couponCode: "FLAT5", items: [ + {sku: "B", category: "books", unitPrice: 3, qty: 1, onSale: false, lineTotal: 3, promoPct: 0.05, promoLabel: "books", promoAmount: 0.15}, + ], subtotal: 3, promoTotal: 0.15, couponBase: 2.85, couponDiscount: 2.85, tierPct: 0.05, tierDiscount: 0, total: 0, savings: 3}}, + ], + // Two apparel items are no three-for; three on sale take the sale row first. A coupon base + // of exactly 50 qualifies. + [ + {cart: {memberTier: "silver", couponCode: "SAVE10", items: [ + {sku: "J", category: "apparel", unitPrice: 25, qty: 2, onSale: false}, + {sku: "S", category: "apparel", unitPrice: 10, qty: 3, onSale: true}, + ]}}, + {cart: {memberTier: "silver", couponCode: "SAVE10", items: [ + {sku: "J", category: "apparel", unitPrice: 25, qty: 2, onSale: false, lineTotal: 50, promoPct: 0, promoLabel: "none", promoAmount: 0}, + {sku: "S", category: "apparel", unitPrice: 10, qty: 3, onSale: true, lineTotal: 30, promoPct: 0, promoLabel: "sale-item", promoAmount: 0}, + ], subtotal: 80, promoTotal: 0, couponBase: 50, couponDiscount: 5, tierPct: 0.02, tierDiscount: 1.5, total: 73.5, savings: 6.5}}, + ], + [ + {cart: {memberTier: "gold", couponCode: "SAVE10", items: []}}, + {cart: {memberTier: "gold", couponCode: "SAVE10", items: [], subtotal: 0, promoTotal: 0, couponBase: 0, couponDiscount: 0, tierPct: 0.05, tierDiscount: 0, total: 0, savings: 0}}, + ], + // Coupon codes are case-sensitive. + [ + {cart: {memberTier: "none", couponCode: "save10", items: [{sku: "A", category: "electronics", unitPrice: 50, qty: 1, onSale: false}]}}, + {cart: {memberTier: "none", couponCode: "save10", items: [ + {sku: "A", category: "electronics", unitPrice: 50, qty: 1, onSale: false, lineTotal: 50, promoPct: 0, promoLabel: "none", promoAmount: 0}, + ], subtotal: 50, promoTotal: 0, couponBase: 50, couponDiscount: 0, tierPct: 0, tierDiscount: 0, total: 50, savings: 0}}, + ], + [ + {cart: {memberTier: "none", couponCode: null, items: [{sku: "A", category: "apparel", unitPrice: 9.99, qty: 4, onSale: false}]}}, + {cart: {memberTier: "none", couponCode: null, items: [ + {sku: "A", category: "apparel", unitPrice: 9.99, qty: 4, onSale: false, lineTotal: 39.96, promoPct: 0.2, promoLabel: "3-for-apparel", promoAmount: 7.99}, + ], subtotal: 39.96, promoTotal: 7.99, couponBase: 31.97, couponDiscount: 0, tierPct: 0, tierDiscount: 0, total: 31.97, savings: 7.99}}, + ], + { + input: {cart: {items: [{sku: "A", category: "books", unitPrice: 10, qty: 1, onSale: false}]}}, + goals: ["cart.couponBase"], + output: {cart: {items: [{sku: "A", category: "books", unitPrice: 10, qty: 1, onSale: false, lineTotal: 10, promoPct: 0.05, promoLabel: "books", promoAmount: 0.5}], couponBase: 9.5}}, + }, + [{cart: {memberTier: "none", items: [{sku: "A", category: "toys", unitPrice: 1, qty: 1, onSale: false}]}}, "!error: InputValidationFailed"], + [{cart: {memberTier: "platinum", items: []}}, "!error: InputValidationFailed"], + [{cart: {memberTier: "none", items: [{sku: "A", category: "books", unitPrice: 1, onSale: false}]}}, "!error: ExpressionFailed"], + [{cart: {items: []}}, "!error: MissingRequiredInputs"], + // An item without `onSale` reads null: the sale row does not match it, but `not null` in the + // coupon base filter is an error. + [{cart: {memberTier: "none", items: [{sku: "A", category: "books", unitPrice: 10, qty: 1}]}}, "!error: ExpressionFailed"], + ], +} + +// --- Shipping ---------------------------------------------------------------------------------- +// Per-item billable weight is the larger of actual and volumetric weight (cm³ / 5000) times the +// quantity. Surcharges and their fees are collected in two `[]` columns of one first-hit table +// whose third input reads the referenced zone; express multiplies the cost; free shipping is a +// match; the shippability assertion is `not hazmat or (not remote and not express)`. + +{ + name: "shipping by billable weight with surcharges", + policy: { + models: { + shipment: {destination: "&zone", express: "boolean", cartTotal: "number", items: "parcel[]"}, + zone: {id: "string", baseRate: "number", perKg: "number", remote: "boolean"}, + parcel: {weightKg: "number", lengthCm: "number", widthCm: "number", heightCm: "number", qty: "number", hazmat: "boolean"}, + }, + blocks: [ + {expression: "parcel.volumetric", value: "round(parcel.lengthCm * parcel.widthCm * parcel.heightCm / 5000, 2)"}, + {expression: "parcel.billable", value: "max([parcel.weightKg, parcel.volumetric]) * parcel.qty"}, + {expression: "shipment.weight", value: "sum(map(shipment.items, #.billable))"}, + {expression: "shipment.hazmat", value: "some(shipment.items, #.hazmat)"}, + {expression: "shipment.oversize", value: "some(shipment.items, max([#.lengthCm, #.widthCm, #.heightCm]) > 120)"}, + {table: "surcharges", inputs: ["shipment.hazmat", "shipment.oversize", "shipment.destination.remote"], outputs: ["shipment.surcharges[]", "shipment.fees[]"], rules: [ + ["true", "", "", "'hazmat'", "25"], + ["", "true", "", "'oversize'", "15"], + ["", "", "true", "'remote'", "10"], + ]}, + {expression: "shipment.base", value: "round(shipment.destination.baseRate + shipment.destination.perKg * shipment.weight, 2)"}, + {expression: "shipment.cost", value: "round((shipment.base + sum(shipment.fees)) * (shipment.express ? 1.5 : 1), 2)"}, + {match: "shipment.freeShipping", arms: [ + ["shipment.hazmat or shipment.oversize", "false"], + ["shipment.cartTotal >= 100 and not shipment.express", "true"], + ["", "false"], + ]}, + {expression: "shipment.charge", value: "shipment.freeShipping ? 0 : shipment.cost"}, + {assertion: "shipment.shippable", conditions: [ + ["or", "not shipment.hazmat", 0], + ["and", "not shipment.destination.remote", 1], + ["and", "not shipment.express", 1], + ]}, + ], + }, + cases: [ + [ + {shipment: {destination: "DOM", express: false, cartTotal: 50, items: [{weightKg: 2, lengthCm: 30, widthCm: 20, heightCm: 10, qty: 1, hazmat: false}]}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}, {id: "ISL", baseRate: 12, perKg: 2.5, remote: true}]}, + {shipment: {destination: {id: "DOM", baseRate: 5, perKg: 1, remote: false}, express: false, cartTotal: 50, items: [ + {weightKg: 2, lengthCm: 30, widthCm: 20, heightCm: 10, qty: 1, hazmat: false, volumetric: 1.2, billable: 2}, + ], weight: 2, hazmat: false, oversize: false, surcharges: [], fees: [], base: 7, cost: 7, freeShipping: false, charge: 7, shippable: true}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}, {id: "ISL", baseRate: 12, perKg: 2.5, remote: true}]}, + ], + // A light but bulky box bills by volume; the cart total earns free shipping. + [ + {shipment: {destination: "DOM", express: false, cartTotal: 150, items: [{weightKg: 1, lengthCm: 50, widthCm: 40, heightCm: 30, qty: 2, hazmat: false}]}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + {shipment: {destination: {id: "DOM", baseRate: 5, perKg: 1, remote: false}, express: false, cartTotal: 150, items: [ + {weightKg: 1, lengthCm: 50, widthCm: 40, heightCm: 30, qty: 2, hazmat: false, volumetric: 12, billable: 24}, + ], weight: 24, hazmat: false, oversize: false, surcharges: [], fees: [], base: 29, cost: 29, freeShipping: true, charge: 0, shippable: true}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + ], + [ + {shipment: {destination: "DOM", express: true, cartTotal: 200, items: [{weightKg: 3, lengthCm: 10, widthCm: 10, heightCm: 10, qty: 1, hazmat: false}]}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + {shipment: {destination: {id: "DOM", baseRate: 5, perKg: 1, remote: false}, express: true, cartTotal: 200, items: [ + {weightKg: 3, lengthCm: 10, widthCm: 10, heightCm: 10, qty: 1, hazmat: false, volumetric: 0.2, billable: 3}, + ], weight: 3, hazmat: false, oversize: false, surcharges: [], fees: [], base: 8, cost: 12, freeShipping: false, charge: 12, shippable: true}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + ], + // Hazardous goods to an island: two surcharges and not shippable. + [ + {shipment: {destination: "ISL", express: false, cartTotal: 500, items: [{weightKg: 4, lengthCm: 20, widthCm: 20, heightCm: 20, qty: 1, hazmat: true}]}, zone: [{id: "ISL", baseRate: 12, perKg: 2.5, remote: true}]}, + {shipment: {destination: {id: "ISL", baseRate: 12, perKg: 2.5, remote: true}, express: false, cartTotal: 500, items: [ + {weightKg: 4, lengthCm: 20, widthCm: 20, heightCm: 20, qty: 1, hazmat: true, volumetric: 1.6, billable: 4}, + ], weight: 4, hazmat: true, oversize: false, surcharges: ["hazmat", "remote"], fees: [25, 10], base: 22, cost: 57, freeShipping: false, charge: 57, shippable: false}, zone: [{id: "ISL", baseRate: 12, perKg: 2.5, remote: true}]}, + ], + [ + {shipment: {destination: "DOM", express: false, cartTotal: 300, items: [{weightKg: 10, lengthCm: 121, widthCm: 10, heightCm: 10, qty: 1, hazmat: false}]}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + {shipment: {destination: {id: "DOM", baseRate: 5, perKg: 1, remote: false}, express: false, cartTotal: 300, items: [ + {weightKg: 10, lengthCm: 121, widthCm: 10, heightCm: 10, qty: 1, hazmat: false, volumetric: 2.42, billable: 10}, + ], weight: 10, hazmat: false, oversize: true, surcharges: ["oversize"], fees: [15], base: 15, cost: 30, freeShipping: false, charge: 30, shippable: true}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + ], + // 120 cm is not oversize; a cart total of exactly 100 ships free. + [ + {shipment: {destination: "DOM", express: false, cartTotal: 100, items: [{weightKg: 1, lengthCm: 120, widthCm: 10, heightCm: 10, qty: 1, hazmat: false}]}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + {shipment: {destination: {id: "DOM", baseRate: 5, perKg: 1, remote: false}, express: false, cartTotal: 100, items: [ + {weightKg: 1, lengthCm: 120, widthCm: 10, heightCm: 10, qty: 1, hazmat: false, volumetric: 2.4, billable: 2.4}, + ], weight: 2.4, hazmat: false, oversize: false, surcharges: [], fees: [], base: 7.4, cost: 7.4, freeShipping: true, charge: 0, shippable: true}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + ], + [ + {shipment: {destination: "ISL", express: true, cartTotal: 20, items: [{weightKg: 1, lengthCm: 10, widthCm: 10, heightCm: 10, qty: 3, hazmat: false}]}, zone: [{id: "ISL", baseRate: 12, perKg: 2.5, remote: true}]}, + {shipment: {destination: {id: "ISL", baseRate: 12, perKg: 2.5, remote: true}, express: true, cartTotal: 20, items: [ + {weightKg: 1, lengthCm: 10, widthCm: 10, heightCm: 10, qty: 3, hazmat: false, volumetric: 0.2, billable: 3}, + ], weight: 3, hazmat: false, oversize: false, surcharges: ["remote"], fees: [10], base: 19.5, cost: 44.25, freeShipping: false, charge: 44.25, shippable: true}, zone: [{id: "ISL", baseRate: 12, perKg: 2.5, remote: true}]}, + ], + // Hazardous goods ship domestically, but not by express. + [ + {shipment: {destination: "DOM", express: true, cartTotal: 10, items: [{weightKg: 1, lengthCm: 10, widthCm: 10, heightCm: 10, qty: 1, hazmat: true}]}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + {shipment: {destination: {id: "DOM", baseRate: 5, perKg: 1, remote: false}, express: true, cartTotal: 10, items: [ + {weightKg: 1, lengthCm: 10, widthCm: 10, heightCm: 10, qty: 1, hazmat: true, volumetric: 0.2, billable: 1}, + ], weight: 1, hazmat: true, oversize: false, surcharges: ["hazmat"], fees: [25], base: 6, cost: 46.5, freeShipping: false, charge: 46.5, shippable: false}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + ], + [ + {shipment: {destination: "DOM", express: false, cartTotal: 0, items: []}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + {shipment: {destination: {id: "DOM", baseRate: 5, perKg: 1, remote: false}, express: false, cartTotal: 0, items: [], weight: 0, hazmat: false, oversize: false, surcharges: [], fees: [], base: 5, cost: 5, freeShipping: false, charge: 5, shippable: true}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, + ], + { + input: {shipment: {items: [{weightKg: 1, lengthCm: 50, widthCm: 40, heightCm: 30, qty: 1, hazmat: false}]}}, + goals: ["shipment.weight"], + output: {shipment: {items: [{weightKg: 1, lengthCm: 50, widthCm: 40, heightCm: 30, qty: 1, hazmat: false, volumetric: 12, billable: 12}], weight: 12}}, + }, + [{shipment: {destination: "MARS", express: false, cartTotal: 0, items: []}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, "!error: InputValidationFailed"], + [{shipment: {destination: "DOM", cartTotal: 0, items: []}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, "!error: MissingRequiredInputs"], + [{shipment: {destination: "DOM", express: false, cartTotal: 0, items: [{lengthCm: 10, widthCm: 10, heightCm: 10, qty: 1, hazmat: false}]}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, "!error: ExpressionFailed"], + [{shipment: {destination: "DOM", express: false, cartTotal: 0, items: [{weightKg: 1, lengthCm: 10, widthCm: 10, heightCm: 10, qty: 1, hazmat: "no"}]}, zone: [{id: "DOM", baseRate: 5, perKg: 1, remote: false}]}, "!error: InputValidationFailed"], + ], +} + +// --- Sales tax --------------------------------------------------------------------------------- +// The ship-to jurisdiction is a reference; per-line blocks read it through the root. Clothing +// under an optional per-jurisdiction threshold is exempt; a per-line table maps tax codes to a +// taxable share; tax rounds per line; shipping is taxed only where the jurisdiction says so; +// an exemption certificate zeroes everything. + +{ + name: "sales tax by referenced jurisdiction", + policy: { + models: { + order: {shipTo: "&jurisdiction", shippingFee: "number", exemptCertificate: "boolean", lines: "line[]"}, + jurisdiction: {id: "string", stateRate: "number", localRate: "number", taxesShipping: "boolean", clothingExemptUnder: "number?"}, + line: {taxCode: "string(general|clothing|food|digital|service)", amount: "number"}, + }, + blocks: [ + {expression: "line.clothingExempt", value: "line.taxCode == 'clothing' and line.amount < (order.shipTo.clothingExemptUnder ?? 0)"}, + {table: "taxable", inputs: ["line.taxCode", "line.clothingExempt"], outputs: ["line.taxablePct"], rules: [ + ["'food', 'service'", "", "0"], + ["", "true", "0"], + ["'digital'", "", "0.5"], + ["", "", "1"], + ]}, + {expression: "line.tax", value: "order.exemptCertificate ? 0 : round(line.amount * line.taxablePct * (order.shipTo.stateRate + order.shipTo.localRate), 2)"}, + {expression: "order.itemsTotal", value: "sum(map(order.lines, #.amount))"}, + {expression: "order.shippingTax", value: "(order.exemptCertificate or not order.shipTo.taxesShipping) ? 0 : round(order.shippingFee * (order.shipTo.stateRate + order.shipTo.localRate), 2)"}, + {expression: "order.taxTotal", value: "sum(map(order.lines, #.tax)) + order.shippingTax"}, + {expression: "order.grandTotal", value: "order.itemsTotal + order.shippingFee + order.taxTotal"}, + {expression: "order.effectiveRate", value: "order.itemsTotal > 0 ? round(order.taxTotal / order.itemsTotal, 4) : 0"}, + ], + }, + cases: [ + [ + {order: {shipTo: "NY", shippingFee: 10, exemptCertificate: false, lines: [{taxCode: "general", amount: 100}, {taxCode: "clothing", amount: 50}, {taxCode: "clothing", amount: 200}, {taxCode: "food", amount: 30}]}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}, {id: "CA", stateRate: 0.0725, localRate: 0.0125, taxesShipping: false}]}, + {order: {shipTo: {id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}, shippingFee: 10, exemptCertificate: false, lines: [ + {taxCode: "general", amount: 100, clothingExempt: false, taxablePct: 1, tax: 8.5}, + {taxCode: "clothing", amount: 50, clothingExempt: true, taxablePct: 0, tax: 0}, + {taxCode: "clothing", amount: 200, clothingExempt: false, taxablePct: 1, tax: 17}, + {taxCode: "food", amount: 30, clothingExempt: false, taxablePct: 0, tax: 0}, + ], itemsTotal: 380, shippingTax: 0.85, taxTotal: 26.35, grandTotal: 416.35, effectiveRate: 0.0693}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}, {id: "CA", stateRate: 0.0725, localRate: 0.0125, taxesShipping: false}]}, + ], + // No clothing threshold: clothing is always taxed; digital goods are half taxable; shipping + // is untaxed. + [ + {order: {shipTo: "CA", shippingFee: 10, exemptCertificate: false, lines: [{taxCode: "clothing", amount: 50}, {taxCode: "digital", amount: 20}, {taxCode: "service", amount: 100}]}, jurisdiction: [{id: "CA", stateRate: 0.0725, localRate: 0.0125, taxesShipping: false}]}, + {order: {shipTo: {id: "CA", stateRate: 0.0725, localRate: 0.0125, taxesShipping: false}, shippingFee: 10, exemptCertificate: false, lines: [ + {taxCode: "clothing", amount: 50, clothingExempt: false, taxablePct: 1, tax: 4.25}, + {taxCode: "digital", amount: 20, clothingExempt: false, taxablePct: 0.5, tax: 0.85}, + {taxCode: "service", amount: 100, clothingExempt: false, taxablePct: 0, tax: 0}, + ], itemsTotal: 170, shippingTax: 0, taxTotal: 5.1, grandTotal: 185.1, effectiveRate: 0.03}, jurisdiction: [{id: "CA", stateRate: 0.0725, localRate: 0.0125, taxesShipping: false}]}, + ], + [ + {order: {shipTo: "NY", shippingFee: 20, exemptCertificate: true, lines: [{taxCode: "general", amount: 1000}]}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}]}, + {order: {shipTo: {id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}, shippingFee: 20, exemptCertificate: true, lines: [ + {taxCode: "general", amount: 1000, clothingExempt: false, taxablePct: 1, tax: 0}, + ], itemsTotal: 1000, shippingTax: 0, taxTotal: 0, grandTotal: 1020, effectiveRate: 0}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}]}, + ], + [ + {order: {shipTo: "OR", shippingFee: 5, exemptCertificate: false, lines: [{taxCode: "general", amount: 99.99}]}, jurisdiction: [{id: "OR", stateRate: 0, localRate: 0, taxesShipping: true, clothingExemptUnder: null}]}, + {order: {shipTo: {id: "OR", stateRate: 0, localRate: 0, taxesShipping: true, clothingExemptUnder: null}, shippingFee: 5, exemptCertificate: false, lines: [ + {taxCode: "general", amount: 99.99, clothingExempt: false, taxablePct: 1, tax: 0}, + ], itemsTotal: 99.99, shippingTax: 0, taxTotal: 0, grandTotal: 104.99, effectiveRate: 0}, jurisdiction: [{id: "OR", stateRate: 0, localRate: 0, taxesShipping: true, clothingExemptUnder: null}]}, + ], + // The clothing threshold is exclusive. + [ + {order: {shipTo: "NY", shippingFee: 0, exemptCertificate: false, lines: [{taxCode: "clothing", amount: 110}, {taxCode: "clothing", amount: 109.99}]}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}]}, + {order: {shipTo: {id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}, shippingFee: 0, exemptCertificate: false, lines: [ + {taxCode: "clothing", amount: 110, clothingExempt: false, taxablePct: 1, tax: 9.35}, + {taxCode: "clothing", amount: 109.99, clothingExempt: true, taxablePct: 0, tax: 0}, + ], itemsTotal: 219.99, shippingTax: 0, taxTotal: 9.35, grandTotal: 229.34, effectiveRate: 0.0425}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}]}, + ], + [ + {order: {shipTo: "NY", shippingFee: 7.5, exemptCertificate: false, lines: []}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}]}, + {order: {shipTo: {id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}, shippingFee: 7.5, exemptCertificate: false, lines: [], itemsTotal: 0, shippingTax: 0.64, taxTotal: 0.64, grandTotal: 8.14, effectiveRate: 0}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}]}, + ], + // Rounding per line loses a cent against rounding the total. + [ + {order: {shipTo: "NY", shippingFee: 0, exemptCertificate: false, lines: [{taxCode: "general", amount: 0.99}, {taxCode: "general", amount: 0.99}, {taxCode: "general", amount: 0.99}]}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}]}, + {order: {shipTo: {id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}, shippingFee: 0, exemptCertificate: false, lines: [ + {taxCode: "general", amount: 0.99, clothingExempt: false, taxablePct: 1, tax: 0.08}, + {taxCode: "general", amount: 0.99, clothingExempt: false, taxablePct: 1, tax: 0.08}, + {taxCode: "general", amount: 0.99, clothingExempt: false, taxablePct: 1, tax: 0.08}, + ], itemsTotal: 2.97, shippingTax: 0, taxTotal: 0.24, grandTotal: 3.21, effectiveRate: 0.0808}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true, clothingExemptUnder: 110}]}, + ], + // A refund line (negative amount) reduces tax. + [ + {order: {shipTo: "CA", shippingFee: 0, exemptCertificate: false, lines: [{taxCode: "general", amount: 100}, {taxCode: "general", amount: -40}]}, jurisdiction: [{id: "CA", stateRate: 0.0725, localRate: 0.0125, taxesShipping: false}]}, + {order: {shipTo: {id: "CA", stateRate: 0.0725, localRate: 0.0125, taxesShipping: false}, shippingFee: 0, exemptCertificate: false, lines: [ + {taxCode: "general", amount: 100, clothingExempt: false, taxablePct: 1, tax: 8.5}, + {taxCode: "general", amount: -40, clothingExempt: false, taxablePct: 1, tax: -3.4}, + ], itemsTotal: 60, shippingTax: 0, taxTotal: 5.1, grandTotal: 65.1, effectiveRate: 0.085}, jurisdiction: [{id: "CA", stateRate: 0.0725, localRate: 0.0125, taxesShipping: false}]}, + ], + { + input: {order: {lines: [{taxCode: "general", amount: 5}, {taxCode: "food", amount: 7}]}}, + goals: ["order.itemsTotal"], + output: {order: {lines: [{taxCode: "general", amount: 5}, {taxCode: "food", amount: 7}], itemsTotal: 12}}, + }, + [{order: {shipTo: "TX", shippingFee: 0, exemptCertificate: false, lines: []}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true}]}, "!error: InputValidationFailed"], + [{order: {shipTo: "NY", shippingFee: 0, exemptCertificate: false, lines: [{taxCode: "alcohol", amount: 1}]}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true}]}, "!error: InputValidationFailed"], + [{order: {shipTo: "NY", exemptCertificate: false, lines: []}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true}]}, "!error: MissingRequiredInputs"], + [{order: {shipTo: "NY", shippingFee: 0, exemptCertificate: false, lines: [{taxCode: "general"}]}, jurisdiction: [{id: "NY", stateRate: 0.04, localRate: 0.045, taxesShipping: true}]}, "!error: ExpressionFailed"], + ], +} + +// --- Loyalty ----------------------------------------------------------------------------------- +// Orders within twelve months count. Per-order points use a multiplier match (returns earn +// nothing, app orders double) and `floor`; yearly spend sets the next tier through a table; +// the tier change match lets long-standing members keep their tier for a grace year. + +{ + name: "loyalty points and tier progression", + policy: { + globals: {loyalty: {pointsPerUnit: "number"}}, + models: { + customer: {tier: "string(bronze|silver|gold)", pointsBalance: "number", joined: "date", orders: "order[]"}, + order: {placed: "date", amount: "number", returned: "boolean", channel: "string(web|app|store)"}, + }, + blocks: [ + {expression: "order.recent", value: "d().diff(order.placed, 'month') < 12"}, + {match: "order.multiplier", arms: [ + ["order.returned", "0"], + ["order.channel == 'app'", "2"], + ["", "1"], + ]}, + {expression: "order.points", value: "floor(order.amount * pointsPerUnit * order.multiplier)"}, + {expression: "customer.yearSpend", value: "sum(map(filter(customer.orders, #.recent and not #.returned), #.amount))"}, + {expression: "customer.earned", value: "sum(map(filter(customer.orders, #.recent), #.points))"}, + {expression: "customer.newBalance", value: "customer.pointsBalance + customer.earned"}, + {table: "nextTier", inputs: ["customer.yearSpend"], outputs: ["customer.nextTier"], rules: [ + [">= 5000", "'gold'"], + [">= 1000", "'silver'"], + ["", "'bronze'"], + ]}, + {expression: "customer.tenureYears", value: "d().diff(customer.joined, 'year')"}, + {match: "customer.tierChange", arms: [ + ["customer.nextTier == customer.tier", "'keep'"], + ["customer.nextTier == 'gold' or (customer.nextTier == 'silver' and customer.tier == 'bronze')", "'upgrade'"], + ["customer.tenureYears >= 5", "'grace'"], + ["", "'downgrade'"], + ]}, + {expression: "customer.vouchers", value: "floor(customer.newBalance / 1000)"}, + ], + }, + cases: [ + [ + {pointsPerUnit: 1, customer: {tier: "bronze", pointsBalance: 200, joined: "2022-01-01", orders: [ + {placed: "2025-01-10", amount: 300, returned: false, channel: "web"}, + {placed: "2024-12-01", amount: 800, returned: false, channel: "app"}, + ]}}, + {pointsPerUnit: 1, customer: {tier: "bronze", pointsBalance: 200, joined: "2022-01-01", orders: [ + {placed: "2025-01-10", amount: 300, returned: false, channel: "web", recent: true, multiplier: 1, points: 300}, + {placed: "2024-12-01", amount: 800, returned: false, channel: "app", recent: true, multiplier: 2, points: 1600}, + ], yearSpend: 1100, earned: 1900, newBalance: 2100, nextTier: "silver", tenureYears: 3, tierChange: "upgrade", vouchers: 2}}, + ], + // Gold falling to silver keeps gold for a grace year after five years of membership... + [ + {pointsPerUnit: 1, customer: {tier: "gold", pointsBalance: 0, joined: "2010-01-01", orders: [{placed: "2024-06-01", amount: 2000, returned: false, channel: "store"}]}}, + {pointsPerUnit: 1, customer: {tier: "gold", pointsBalance: 0, joined: "2010-01-01", orders: [ + {placed: "2024-06-01", amount: 2000, returned: false, channel: "store", recent: true, multiplier: 1, points: 2000}, + ], yearSpend: 2000, earned: 2000, newBalance: 2000, nextTier: "silver", tenureYears: 15, tierChange: "grace", vouchers: 2}}, + ], + // ...but is downgraded with less tenure. + [ + {pointsPerUnit: 1, customer: {tier: "gold", pointsBalance: 0, joined: "2023-01-01", orders: [{placed: "2024-06-01", amount: 2000, returned: false, channel: "store"}]}}, + {pointsPerUnit: 1, customer: {tier: "gold", pointsBalance: 0, joined: "2023-01-01", orders: [ + {placed: "2024-06-01", amount: 2000, returned: false, channel: "store", recent: true, multiplier: 1, points: 2000}, + ], yearSpend: 2000, earned: 2000, newBalance: 2000, nextTier: "silver", tenureYears: 2, tierChange: "downgrade", vouchers: 2}}, + ], + // A returned app order earns nothing and does not count as spend; points are floored. + [ + {pointsPerUnit: 1, customer: {tier: "silver", pointsBalance: 50, joined: "2020-06-01", orders: [ + {placed: "2025-02-01", amount: 1500, returned: true, channel: "app"}, + {placed: "2025-03-01", amount: 999.99, returned: false, channel: "web"}, + ]}}, + {pointsPerUnit: 1, customer: {tier: "silver", pointsBalance: 50, joined: "2020-06-01", orders: [ + {placed: "2025-02-01", amount: 1500, returned: true, channel: "app", recent: true, multiplier: 0, points: 0}, + {placed: "2025-03-01", amount: 999.99, returned: false, channel: "web", recent: true, multiplier: 1, points: 999}, + ], yearSpend: 999.99, earned: 999, newBalance: 1049, nextTier: "bronze", tenureYears: 4, tierChange: "downgrade", vouchers: 1}}, + ], + // An order exactly twelve months old no longer counts. + [ + {pointsPerUnit: 1, customer: {tier: "silver", pointsBalance: 0, joined: "2015-01-01", orders: [ + {placed: "2024-03-20", amount: 5000, returned: false, channel: "web"}, + {placed: "2024-03-21", amount: 1000, returned: false, channel: "web"}, + ]}}, + {pointsPerUnit: 1, customer: {tier: "silver", pointsBalance: 0, joined: "2015-01-01", orders: [ + {placed: "2024-03-20", amount: 5000, returned: false, channel: "web", recent: false, multiplier: 1, points: 5000}, + {placed: "2024-03-21", amount: 1000, returned: false, channel: "web", recent: true, multiplier: 1, points: 1000}, + ], yearSpend: 1000, earned: 1000, newBalance: 1000, nextTier: "silver", tenureYears: 10, tierChange: "keep", vouchers: 1}}, + ], + [ + {pointsPerUnit: 1, customer: {tier: "bronze", pointsBalance: 10, joined: "2024-01-01", orders: [ + {placed: "2025-03-19", amount: 2500, returned: false, channel: "app"}, + {placed: "2025-01-01", amount: 2500, returned: false, channel: "store"}, + ]}}, + {pointsPerUnit: 1, customer: {tier: "bronze", pointsBalance: 10, joined: "2024-01-01", orders: [ + {placed: "2025-03-19", amount: 2500, returned: false, channel: "app", recent: true, multiplier: 2, points: 5000}, + {placed: "2025-01-01", amount: 2500, returned: false, channel: "store", recent: true, multiplier: 1, points: 2500}, + ], yearSpend: 5000, earned: 7500, newBalance: 7510, nextTier: "gold", tenureYears: 1, tierChange: "upgrade", vouchers: 7}}, + ], + [ + {pointsPerUnit: 1, customer: {tier: "bronze", pointsBalance: 999, joined: "2024-01-01", orders: []}}, + {pointsPerUnit: 1, customer: {tier: "bronze", pointsBalance: 999, joined: "2024-01-01", orders: [], yearSpend: 0, earned: 0, newBalance: 999, nextTier: "bronze", tenureYears: 1, tierChange: "keep", vouchers: 0}}, + ], + [ + {pointsPerUnit: 1.5, customer: {tier: "silver", pointsBalance: 0, joined: "2019-01-01", orders: [{placed: "2025-01-01", amount: 33.33, returned: false, channel: "web"}]}}, + {pointsPerUnit: 1.5, customer: {tier: "silver", pointsBalance: 0, joined: "2019-01-01", orders: [ + {placed: "2025-01-01", amount: 33.33, returned: false, channel: "web", recent: true, multiplier: 1, points: 49}, + ], yearSpend: 33.33, earned: 49, newBalance: 49, nextTier: "bronze", tenureYears: 6, tierChange: "grace", vouchers: 0}}, + ], + { + input: {customer: {orders: [{placed: "2025-01-01", amount: 6000, returned: false}]}}, + goals: ["customer.nextTier"], + output: {customer: {orders: [{placed: "2025-01-01", amount: 6000, returned: false, recent: true}], yearSpend: 6000, nextTier: "gold"}}, + }, + [{pointsPerUnit: 1, customer: {tier: "bronze", pointsBalance: 0, joined: "2024-01-01", orders: [{placed: "2025-01-01", amount: 1, returned: false, channel: "phone"}]}}, "!error: InputValidationFailed"], + [{customer: {tier: "bronze", pointsBalance: 0, joined: "2024-01-01", orders: []}}, "!error: MissingRequiredInputs"], + [{pointsPerUnit: 1, customer: {tier: "diamond", pointsBalance: 0, joined: "2024-01-01", orders: []}}, "!error: InputValidationFailed"], + // An order without `returned`: the multiplier match falls through on null, but the spend + // filter's `not null` is an error. + [{pointsPerUnit: 1, customer: {tier: "bronze", pointsBalance: 0, joined: "2024-01-01", orders: [{placed: "2025-01-01", amount: 10, channel: "web"}]}}, "!error: ExpressionFailed"], + ], +} + +// --- Checkout fraud scoring -------------------------------------------------------------------- +// Root signals from the checkout, a disposable email suffix test, recent declined attempts +// (strictly within 24 hours) and prepaid cards from members, high-risk geography from a global +// list. One first-hit table collects signal names and their points in two `[]` columns; the +// score adds a large-amount bump; a decision match reads a global review threshold. + +{ + name: "checkout fraud signals and scoring", + policy: { + globals: {risk: {highRiskCountries: "string[]", reviewThreshold: "number"}}, + models: { + checkout: {amount: "number", accountAgeDays: "number", email: "string", billingCountry: "string", shippingCountry: "string", ipCountry: "string", cards: "card[]", attempts: "attempt[]"}, + card: {bin: "string", country: "string", prepaid: "boolean"}, + attempt: {at: "date", declined: "boolean"}, + }, + blocks: [ + {expression: "checkout.countryMismatch", value: "checkout.billingCountry != checkout.shippingCountry or checkout.billingCountry != checkout.ipCountry"}, + {expression: "checkout.disposableEmail", value: "endsWith(checkout.email, '@mailinator.com') or endsWith(checkout.email, '@tempmail.io')"}, + {expression: "attempt.recent", value: "attempt.at > d().add(-24, 'hour')"}, + {expression: "checkout.recentDeclines", value: "count(checkout.attempts, #.recent and #.declined)"}, + {expression: "checkout.prepaidCards", value: "count(checkout.cards, #.prepaid)"}, + {expression: "checkout.highRiskGeo", value: "checkout.ipCountry in highRiskCountries or checkout.shippingCountry in highRiskCountries"}, + {table: "signals", inputs: ["checkout.countryMismatch", "checkout.disposableEmail", "checkout.recentDeclines", "checkout.prepaidCards", "checkout.highRiskGeo", "checkout.accountAgeDays"], outputs: ["checkout.signals[]", "checkout.points[]"], rules: [ + ["true", "", "", "", "", "", "'country-mismatch'", "15"], + ["", "true", "", "", "", "", "'disposable-email'", "20"], + ["", "", ">= 3", "", "", "", "'velocity'", "30"], + ["", "", "", "> 0", "", "", "'prepaid'", "10"], + ["", "", "", "", "true", "", "'high-risk-geo'", "40"], + ["", "", "", "", "", "< 7", "'new-account'", "15"], + ]}, + {expression: "checkout.score", value: "sum(checkout.points) + (checkout.amount > 1000 ? 10 : 0)"}, + {match: "checkout.decision", arms: [ + ["checkout.score >= 70", "'decline'"], + ["checkout.score >= reviewThreshold", "'review'"], + ["checkout.score > 0 and checkout.amount > 500", "'step-up'"], + ["", "'accept'"], + ]}, + ], + }, + cases: [ + [ + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 120, accountAgeDays: 400, email: "kari@example.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [{bin: "411111", country: "NO", prepaid: false}], attempts: []}}, + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 120, accountAgeDays: 400, email: "kari@example.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [{bin: "411111", country: "NO", prepaid: false}], attempts: [], + countryMismatch: false, disposableEmail: false, recentDeclines: 0, prepaidCards: 0, highRiskGeo: false, signals: [], points: [], score: 0, decision: "accept"}}, + ], + [ + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 600, accountAgeDays: 3, email: "a@example.no", billingCountry: "NO", shippingCountry: "SE", ipCountry: "NO", cards: [{bin: "411111", country: "NO", prepaid: false}], attempts: [{at: "2025-03-20T09:00:00Z", declined: true}]}}, + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 600, accountAgeDays: 3, email: "a@example.no", billingCountry: "NO", shippingCountry: "SE", ipCountry: "NO", cards: [{bin: "411111", country: "NO", prepaid: false}], attempts: [{at: "2025-03-20T09:00:00Z", declined: true, recent: true}], + countryMismatch: true, disposableEmail: false, recentDeclines: 1, prepaidCards: 0, highRiskGeo: false, signals: ["country-mismatch", "new-account"], points: [15, 15], score: 30, decision: "review"}}, + ], + [ + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 50, accountAgeDays: 100, email: "b@example.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: [ + {at: "2025-03-20T08:00:00Z", declined: true}, + {at: "2025-03-19T12:00:00Z", declined: true}, + {at: "2025-03-19T10:15:31Z", declined: true}, + ]}}, + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 50, accountAgeDays: 100, email: "b@example.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: [ + {at: "2025-03-20T08:00:00Z", declined: true, recent: true}, + {at: "2025-03-19T12:00:00Z", declined: true, recent: true}, + {at: "2025-03-19T10:15:31Z", declined: true, recent: true}, + ], countryMismatch: false, disposableEmail: false, recentDeclines: 3, prepaidCards: 0, highRiskGeo: false, signals: ["velocity"], points: [30], score: 30, decision: "review"}}, + ], + // A decline exactly 24 hours ago is not recent; a clean large order is stepped up only + // through the amount bump. + [ + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 2000, accountAgeDays: 30, email: "c@example.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: [ + {at: "2025-03-19T10:15:30Z", declined: true}, + {at: "2025-03-20T10:00:00Z", declined: true}, + {at: "2025-03-20T10:10:00Z", declined: false}, + ]}}, + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 2000, accountAgeDays: 30, email: "c@example.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: [ + {at: "2025-03-19T10:15:30Z", declined: true, recent: false}, + {at: "2025-03-20T10:00:00Z", declined: true, recent: true}, + {at: "2025-03-20T10:10:00Z", declined: false, recent: true}, + ], countryMismatch: false, disposableEmail: false, recentDeclines: 1, prepaidCards: 0, highRiskGeo: false, signals: [], points: [], score: 10, decision: "step-up"}}, + ], + [ + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 80, accountAgeDays: 10, email: "x@mailinator.com", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NG", cards: [{bin: "522222", country: "NO", prepaid: true}], attempts: []}}, + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 80, accountAgeDays: 10, email: "x@mailinator.com", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NG", cards: [{bin: "522222", country: "NO", prepaid: true}], attempts: [], + countryMismatch: true, disposableEmail: true, recentDeclines: 0, prepaidCards: 1, highRiskGeo: true, signals: ["country-mismatch", "disposable-email", "prepaid", "high-risk-geo"], points: [15, 20, 10, 40], score: 85, decision: "decline"}}, + ], + // An amount of exactly 1000 adds nothing and seven days is no longer a new account. + [ + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 1000, accountAgeDays: 7, email: "", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: []}}, + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 1000, accountAgeDays: 7, email: "", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: [], + countryMismatch: false, disposableEmail: false, recentDeclines: 0, prepaidCards: 0, highRiskGeo: false, signals: [], points: [], score: 0, decision: "accept"}}, + ], + // A lower global threshold sends a single signal to review. + [ + {highRiskCountries: [], reviewThreshold: 15, checkout: {amount: 100, accountAgeDays: 50, email: "d@tempmail.io.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "SE", cards: [], attempts: []}}, + {highRiskCountries: [], reviewThreshold: 15, checkout: {amount: 100, accountAgeDays: 50, email: "d@tempmail.io.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "SE", cards: [], attempts: [], + countryMismatch: true, disposableEmail: false, recentDeclines: 0, prepaidCards: 0, highRiskGeo: false, signals: ["country-mismatch"], points: [15], score: 15, decision: "review"}}, + ], + [ + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 700, accountAgeDays: 365, email: "e@example.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [{bin: "1", country: "NO", prepaid: true}, {bin: "2", country: "SE", prepaid: true}], attempts: []}}, + {highRiskCountries: ["NG", "KP"], reviewThreshold: 30, checkout: {amount: 700, accountAgeDays: 365, email: "e@example.no", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [{bin: "1", country: "NO", prepaid: true}, {bin: "2", country: "SE", prepaid: true}], attempts: [], + countryMismatch: false, disposableEmail: false, recentDeclines: 0, prepaidCards: 2, highRiskGeo: false, signals: ["prepaid"], points: [10], score: 10, decision: "step-up"}}, + ], + { + input: {checkout: {attempts: [{at: "2025-03-20T10:00:00Z", declined: true}, {at: "2025-03-01", declined: true}]}}, + goals: ["checkout.recentDeclines"], + output: {checkout: {attempts: [{at: "2025-03-20T10:00:00Z", declined: true, recent: true}, {at: "2025-03-01", declined: true, recent: false}], recentDeclines: 1}}, + }, + [{highRiskCountries: ["NG"], checkout: {amount: 1, accountAgeDays: 1, email: "", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: []}}, "!error: MissingRequiredInputs"], + [{highRiskCountries: ["NG"], reviewThreshold: 30, checkout: {amount: 1, accountAgeDays: 1, email: "", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: [{at: "now", declined: true}]}}, "!error: InputValidationFailed"], + [{highRiskCountries: "NG", reviewThreshold: 30, checkout: {amount: 1, accountAgeDays: 1, email: "", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [], attempts: []}}, "!error: InputValidationFailed"], + [{highRiskCountries: ["NG"], reviewThreshold: 30, checkout: {amount: 1, accountAgeDays: 1, email: "", billingCountry: "NO", shippingCountry: "NO", ipCountry: "NO", cards: [{bin: "1", country: "NO"}], attempts: []}}, "!error: ExpressionFailed"], + ], +} + +// --- Marketplace settlement -------------------------------------------------------------------- +// Sellers are members that select their own lines from the order's line list by id. A +// per-seller commission table reads globals in its output cells (luxury adds three points), a +// cross-border fee applies only to sellers with lines, a hold match flags low ratings and large +// payouts, lines whose seller is not on the order are orphans, and settlement is an assertion. + +{ + name: "marketplace settlement by seller", + policy: { + globals: {market: {commissionBasic: "number", commissionPro: "number"}}, + models: { + order: {buyerCountry: "string", lines: "line[]", sellers: "seller[]"}, + line: {seller: "string", price: "number", qty: "number", category: "string(standard|luxury)"}, + seller: {id: "string", country: "string", plan: "string(basic|pro)", rating: "number"}, + }, + blocks: [ + {expression: "seller.lines", value: "count(order.lines, #.seller == seller.id)"}, + {expression: "seller.gross", value: "sum(map(filter(order.lines, #.seller == seller.id), #.price * #.qty))"}, + {expression: "seller.luxury", value: "some(order.lines, #.seller == seller.id and #.category == 'luxury')"}, + {table: "commission", inputs: ["seller.plan", "seller.luxury"], outputs: ["seller.commissionRate"], rules: [ + ["'pro'", "true", "commissionPro + 0.03"], + ["'pro'", "", "commissionPro"], + ["", "true", "commissionBasic + 0.03"], + ["", "", "commissionBasic"], + ]}, + {expression: "seller.commission", value: "round(seller.gross * seller.commissionRate, 2)"}, + {expression: "seller.crossBorder", value: "seller.country != order.buyerCountry"}, + {expression: "seller.payout", value: "seller.gross - seller.commission - (seller.crossBorder and seller.lines > 0 ? 2 : 0)"}, + {match: "seller.hold", arms: [ + ["seller.rating < 3", "true"], + ["seller.payout > 5000 and seller.rating < 4", "true"], + ["", "false"], + ]}, + {expression: "order.total", value: "sum(map(order.lines, #.price * #.qty))"}, + {expression: "order.platformRevenue", value: "sum(map(order.sellers, #.commission))"}, + {expression: "order.sellerIds", value: "map(order.sellers, #.id)"}, + {expression: "order.orphanLines", value: "count(order.lines, not (#.seller in order.sellerIds))"}, + {assertion: "order.settleable", conditions: ["order.orphanLines == 0", "none(order.sellers, #.hold)"]}, + ], + }, + cases: [ + [ + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 100, qty: 2, category: "standard"}, {seller: "s2", price: 50, qty: 1, category: "luxury"}], sellers: [{id: "s1", country: "NO", plan: "pro", rating: 4.5}, {id: "s2", country: "SE", plan: "basic", rating: 4}]}}, + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 100, qty: 2, category: "standard"}, {seller: "s2", price: 50, qty: 1, category: "luxury"}], sellers: [ + {id: "s1", country: "NO", plan: "pro", rating: 4.5, lines: 1, gross: 200, luxury: false, commissionRate: 0.07, commission: 14, crossBorder: false, payout: 186, hold: false}, + {id: "s2", country: "SE", plan: "basic", rating: 4, lines: 1, gross: 50, luxury: true, commissionRate: 0.13, commission: 6.5, crossBorder: true, payout: 41.5, hold: false}, + ], total: 250, platformRevenue: 20.5, sellerIds: ["s1", "s2"], orphanLines: 0, settleable: true}}, + ], + // A line for a seller missing from the order, and a low-rated seller on hold. + [ + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 10, qty: 1, category: "standard"}, {seller: "s9", price: 5, qty: 1, category: "standard"}], sellers: [{id: "s1", country: "NO", plan: "basic", rating: 2.5}]}}, + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 10, qty: 1, category: "standard"}, {seller: "s9", price: 5, qty: 1, category: "standard"}], sellers: [ + {id: "s1", country: "NO", plan: "basic", rating: 2.5, lines: 1, gross: 10, luxury: false, commissionRate: 0.1, commission: 1, crossBorder: false, payout: 9, hold: true}, + ], total: 15, platformRevenue: 1, sellerIds: ["s1"], orphanLines: 1, settleable: false}}, + ], + [ + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 6000, qty: 1, category: "luxury"}], sellers: [{id: "s1", country: "DE", plan: "pro", rating: 3.9}]}}, + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 6000, qty: 1, category: "luxury"}], sellers: [ + {id: "s1", country: "DE", plan: "pro", rating: 3.9, lines: 1, gross: 6000, luxury: true, commissionRate: 0.1, commission: 600, crossBorder: true, payout: 5398, hold: true}, + ], total: 6000, platformRevenue: 600, sellerIds: ["s1"], orphanLines: 0, settleable: false}}, + ], + // A foreign seller without lines pays no cross-border fee. + [ + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 20, qty: 3, category: "standard"}], sellers: [{id: "s1", country: "NO", plan: "basic", rating: 5}, {id: "s2", country: "SE", plan: "pro", rating: 5}]}}, + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 20, qty: 3, category: "standard"}], sellers: [ + {id: "s1", country: "NO", plan: "basic", rating: 5, lines: 1, gross: 60, luxury: false, commissionRate: 0.1, commission: 6, crossBorder: false, payout: 54, hold: false}, + {id: "s2", country: "SE", plan: "pro", rating: 5, lines: 0, gross: 0, luxury: false, commissionRate: 0.07, commission: 0, crossBorder: true, payout: 0, hold: false}, + ], total: 60, platformRevenue: 6, sellerIds: ["s1", "s2"], orphanLines: 0, settleable: true}}, + ], + // A rating of exactly 3 is not held. + [ + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 5000, qty: 1, category: "standard"}], sellers: [{id: "s1", country: "NO", plan: "basic", rating: 3}]}}, + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 5000, qty: 1, category: "standard"}], sellers: [ + {id: "s1", country: "NO", plan: "basic", rating: 3, lines: 1, gross: 5000, luxury: false, commissionRate: 0.1, commission: 500, crossBorder: false, payout: 4500, hold: false}, + ], total: 5000, platformRevenue: 500, sellerIds: ["s1"], orphanLines: 0, settleable: true}}, + ], + [ + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 10, qty: 1, category: "standard"}, {seller: "s1", price: 20, qty: 2, category: "luxury"}], sellers: [{id: "s1", country: "NO", plan: "pro", rating: 4.2}]}}, + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 10, qty: 1, category: "standard"}, {seller: "s1", price: 20, qty: 2, category: "luxury"}], sellers: [ + {id: "s1", country: "NO", plan: "pro", rating: 4.2, lines: 2, gross: 50, luxury: true, commissionRate: 0.1, commission: 5, crossBorder: false, payout: 45, hold: false}, + ], total: 50, platformRevenue: 5, sellerIds: ["s1"], orphanLines: 0, settleable: true}}, + ], + [ + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [], sellers: []}}, + {commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [], sellers: [], total: 0, platformRevenue: 0, sellerIds: [], orphanLines: 0, settleable: true}}, + ], + { + input: {order: {lines: [{seller: "a"}, {seller: "b"}, {seller: "a"}], sellers: [{id: "a"}]}}, + goals: ["order.orphanLines"], + output: {order: {lines: [{seller: "a"}, {seller: "b"}, {seller: "a"}], sellers: [{id: "a"}], sellerIds: ["a"], orphanLines: 1}}, + }, + [{commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [], sellers: [{id: "s1", country: "NO", plan: "enterprise", rating: 5}]}}, "!error: InputValidationFailed"], + [{commissionBasic: 0.1, order: {buyerCountry: "NO", lines: [], sellers: []}}, "!error: MissingRequiredInputs"], + [{commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", qty: 1, category: "standard"}], sellers: [{id: "s1", country: "NO", plan: "basic", rating: 5}]}}, "!error: ExpressionFailed"], + [{commissionBasic: 0.1, commissionPro: 0.07, order: {buyerCountry: "NO", lines: [{seller: "s1", price: 1, qty: 1, category: "used"}], sellers: []}}, "!error: InputValidationFailed"], + ], +} diff --git a/core/engine/tests/support/columns.rs b/core/engine/tests/support/columns.rs new file mode 100644 index 00000000..dce70c8b --- /dev/null +++ b/core/engine/tests/support/columns.rs @@ -0,0 +1,467 @@ +#![allow(dead_code)] + +use serde_json::Value; +use zen_expression::Variable; + +pub enum Buf { + Dec(Vec), + Text(Vec, Vec), + Bool(Vec), + Any(Vec), + List(Vec, Child), +} + +pub enum Child { + Text(Vec, String), + Scaled(Vec, Vec), + Bool(Vec), + Struct(Vec<(String, Buf, Vec)>, usize, Vec), +} + +impl Child { + pub fn structs(column: &[Option], items: &[&Value]) -> Option { + let mut names: Vec = Vec::new(); + for item in items { + for key in item.as_object()?.keys() { + if !names.contains(key) { + names.push(key.clone()); + } + } + } + let words = items.len().div_ceil(64).max(1); + let fields = names + .into_iter() + .map(|name| { + let cells: Vec> = items + .iter() + .map(|item| item.get(&name).filter(|v| !v.is_null()).cloned()) + .collect(); + let mut valid = vec![0u64; words]; + cells + .iter() + .enumerate() + .filter(|(_, c)| c.is_some()) + .for_each(|(i, _)| valid[i / 64] |= 1 << (i % 64)); + let buf = Buf::scalar(&cells, words)?; + Some((name, buf, valid)) + }) + .collect::>>()?; + let fallback = column + .iter() + .map(|c| { + c.as_ref() + .map_or(Variable::Null, |v| Variable::from(v.clone())) + }) + .collect(); + Some(Child::Struct(fields, items.len(), fallback)) + } + + pub fn of(column: &[Option]) -> Option<(Vec, Child)> { + Self::shape(column, false) + } + + pub fn shape(column: &[Option], nested: bool) -> Option<(Vec, Child)> { + let items: Vec<&Value> = column + .iter() + .flatten() + .map(|v| v.as_array().map(|a| a.iter())) + .collect::>>()? + .into_iter() + .flatten() + .collect(); + let mut offsets = vec![0i32]; + let mut count = 0i32; + for cell in column { + count += cell + .as_ref() + .and_then(Value::as_array) + .map_or(0, |a| a.len() as i32); + offsets.push(count); + } + let child = match items.first() { + None => Child::Text(vec![0], String::new()), + Some(Value::String(_)) if items.iter().all(|v| v.is_string()) => { + let mut child_offsets = vec![0i32]; + let mut data = String::new(); + for item in &items { + data.push_str(item.as_str().unwrap_or_default()); + child_offsets.push(data.len() as i32); + } + Child::Text(child_offsets, data) + } + Some(Value::Number(_)) if items.iter().all(|v| v.is_number()) => { + let parts: Option> = items + .iter() + .map(|v| { + let d = Built::decimal(&v.to_string())?; + Some(( + i64::try_from(d.mantissa()).ok()?, + u8::try_from(d.scale()).ok()?, + )) + }) + .collect(); + let parts = parts?; + Child::Scaled( + parts.iter().map(|p| p.0).collect(), + parts.iter().map(|p| p.1).collect(), + ) + } + Some(Value::Bool(_)) if items.iter().all(|v| v.is_boolean()) => { + let mut bits = vec![0u64; items.len().div_ceil(64).max(1)]; + for (i, item) in items.iter().enumerate() { + if item.as_bool() == Some(true) { + bits[i / 64] |= 1 << (i % 64); + } + } + Child::Bool(bits) + } + Some(Value::Object(_)) if nested && items.iter().all(|v| v.is_object()) => { + Self::structs(column, &items)? + } + _ => return None, + }; + Some((offsets, child)) + } +} + +pub struct Built { + pub rows: usize, + pub paths: Vec, + pub bufs: Vec<(Buf, Vec)>, +} + +impl Buf { + pub fn scalar(column: &[Option], words: usize) -> Option { + let present: Vec<&Value> = column.iter().flatten().collect(); + if present.is_empty() { + return Some(Buf::Bool(vec![0u64; words])); + } + if present.iter().all(|v| { + v.as_number() + .is_some_and(|n| Built::decimal(&n.to_string()).is_some()) + }) { + return Some(Buf::Dec( + column + .iter() + .map(|c| match c { + Some(Value::Number(n)) => { + Built::decimal(&n.to_string()).unwrap_or_default() + } + _ => rust_decimal::Decimal::ZERO, + }) + .collect(), + )); + } + if present.iter().all(|v| v.is_string()) { + let mut offsets = vec![0i32]; + let mut data = Vec::new(); + for cell in column { + if let Some(Value::String(s)) = cell { + data.extend_from_slice(s.as_bytes()); + } + offsets.push(data.len() as i32); + } + return Some(Buf::Text(offsets, data)); + } + if present.iter().all(|v| v.is_boolean()) { + let mut bits = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if let Some(Value::Bool(true)) = cell { + bits[row / 64] |= 1 << (row % 64); + } + } + return Some(Buf::Bool(bits)); + } + None + } + + fn values(&self) -> zen_expression::lane::Values<'_> { + use zen_expression::lane::Values; + match self { + Buf::Dec(v) => Values::Dec(v), + Buf::Text(offsets, data) => Values::Utf8 { offsets, data }, + Buf::Bool(bits) => Values::Bool { bits, offset: 0 }, + Buf::Any(v) => Values::Any(v), + Buf::List(..) => Values::Any(&[]), + } + } +} + +pub type Fields<'b> = Vec)>>; + +impl Built { + pub fn decimal(text: &str) -> Option { + text.parse() + .ok() + .or_else(|| rust_decimal::Decimal::from_scientific(text).ok()) + } + + pub fn flatten(value: &Value, prefix: &str, out: &mut Vec<(String, Value)>) -> bool { + match value { + Value::Object(map) => map.iter().all(|(key, child)| { + !key.contains('.') + && Self::flatten( + child, + &match prefix.is_empty() { + true => key.clone(), + false => format!("{prefix}.{key}"), + }, + out, + ) + }), + Value::Null => true, + other if !prefix.is_empty() => { + out.push((prefix.to_string(), other.clone())); + true + } + _ => false, + } + } + + pub fn new(rows: &[Value]) -> Option { + Self::shaped(rows, false) + } + + pub fn lists(rows: &[Value]) -> Option { + Self::shaped(rows, true) + .filter(|built| built.bufs.iter().any(|(b, _)| matches!(b, Buf::List(..)))) + } + + pub fn nested(rows: &[Value]) -> Option { + Self::build(rows, true, true).filter(|built| { + built + .bufs + .iter() + .any(|(b, _)| matches!(b, Buf::List(_, Child::Struct(..)))) + }) + } + + pub fn shaped(rows: &[Value], lists: bool) -> Option { + Self::build(rows, lists, false) + } + + pub fn fields(&self) -> Fields<'_> { + use zen_expression::lane::Column; + self.bufs + .iter() + .filter_map(|(buf, _)| match buf { + Buf::List(_, Child::Struct(fields, _, _)) => Some( + fields + .iter() + .map(|(name, buf, valid)| { + (name.as_str(), Column::with_validity(buf.values(), valid, 0)) + }) + .collect(), + ), + _ => None, + }) + .collect() + } + + pub fn structs<'b>(&self, fields: &'b Fields<'b>) -> Vec> { + use zen_expression::lane::{Column, Values}; + let lens = self.bufs.iter().filter_map(|(buf, _)| match buf { + Buf::List(_, Child::Struct(_, len, _)) => Some(*len), + _ => None, + }); + fields + .iter() + .zip(lens) + .map(|(f, len)| Column::new(Values::Struct { fields: f, len })) + .collect() + } + + pub fn columns_with<'c>( + &'c self, + structs: &'c [zen_expression::lane::Column<'c>], + ) -> zen_expression::lane::Columns<'c> { + use zen_expression::lane::{Column, Columns, Dictionary, Values}; + let mut columns = Columns::new(self.rows); + let mut next = structs.iter(); + for (path, (buf, valid)) in self.paths.iter().zip(&self.bufs) { + let values = match buf { + Buf::List(offsets, Child::Struct(_, len, fallback)) => match next.next() { + Some(child) if child.len() == *len || *len == 0 => Values::List { + offsets, + child: Dictionary::Column(child), + }, + _ => Values::Any(fallback), + }, + other => match Self::plain(other) { + Some(values) => values, + None => continue, + }, + }; + columns = columns.column(path, Column::with_validity(values, valid, 0)); + } + columns + } + + fn build(rows: &[Value], lists: bool, nested: bool) -> Option { + let conflicts = |a: &str, b: &str| { + a.strip_prefix(b).is_some_and(|r| r.starts_with('.')) + || b.strip_prefix(a).is_some_and(|r| r.starts_with('.')) + }; + let mut kept: Vec> = Vec::new(); + let mut seen: Vec = Vec::new(); + for value in rows { + let mut entries = Vec::new(); + if !Self::flatten(value, "", &mut entries) { + continue; + } + if entries + .iter() + .any(|(p, _)| seen.iter().any(|s| conflicts(p, s))) + { + continue; + } + for (p, _) in &entries { + if !seen.contains(p) { + seen.push(p.clone()); + } + } + kept.push(entries); + } + if kept.is_empty() { + return None; + } + let rows: Vec<()> = vec![(); kept.len()]; + let mut paths: Vec = Vec::new(); + let mut cells: Vec>> = Vec::new(); + for (row, entries) in kept.into_iter().enumerate() { + for (path, leaf) in entries { + let at = match paths.iter().position(|p| *p == path) { + Some(at) => at, + None => { + paths.push(path); + cells.push(vec![None; rows.len()]); + cells.len() - 1 + } + }; + cells[at][row] = Some(leaf); + } + } + for (i, a) in paths.iter().enumerate() { + if paths + .iter() + .enumerate() + .any(|(j, b)| i != j && b.starts_with(&format!("{a}."))) + { + return None; + } + } + let words = rows.len().div_ceil(64); + let bufs = cells + .into_iter() + .map(|column| { + let mut valid = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if cell.is_some() { + valid[row / 64] |= 1 << (row % 64); + } + } + let present: Vec<&Value> = column.iter().flatten().collect(); + let buf = if !present.is_empty() + && present.iter().all(|v| { + v.as_number() + .is_some_and(|n| Self::decimal(&n.to_string()).is_some()) + }) { + Buf::Dec( + column + .iter() + .map(|c| match c { + Some(Value::Number(n)) => { + Self::decimal(&n.to_string()).unwrap_or_default() + } + _ => rust_decimal::Decimal::ZERO, + }) + .collect(), + ) + } else if !present.is_empty() && present.iter().all(|v| v.is_string()) { + let mut offsets = vec![0i32]; + let mut data = Vec::new(); + for cell in &column { + if let Some(Value::String(s)) = cell { + data.extend_from_slice(s.as_bytes()); + } + offsets.push(data.len() as i32); + } + Buf::Text(offsets, data) + } else if !present.is_empty() && present.iter().all(|v| v.is_boolean()) { + let mut bits = vec![0u64; words]; + for (row, cell) in column.iter().enumerate() { + if let Some(Value::Bool(true)) = cell { + bits[row / 64] |= 1 << (row % 64); + } + } + Buf::Bool(bits) + } else if let Some((offsets, child)) = + lists.then(|| Child::shape(&column, nested)).flatten() + { + Buf::List(offsets, child) + } else { + Buf::Any( + column + .iter() + .map(|c| { + c.as_ref() + .map_or(Variable::Null, |v| Variable::from(v.clone())) + }) + .collect(), + ) + }; + (buf, valid) + }) + .collect(); + Some(Built { + rows: rows.len(), + paths, + bufs, + }) + } + + fn plain(buf: &Buf) -> Option> { + use zen_expression::lane::{Dictionary, Values}; + Some(match buf { + Buf::List(offsets, child) => Values::List { + offsets, + child: match child { + Child::Text(o, d) => Dictionary::Text { + offsets: o, + data: d, + }, + Child::Scaled(m, sc) => Dictionary::Scaled { mant: m, scale: sc }, + Child::Bool(bits) => Dictionary::Bool { bits }, + Child::Struct(_, _, fallback) => return Some(Values::Any(fallback)), + }, + }, + other => other.values(), + }) + } + + pub fn columns(&self) -> zen_expression::lane::Columns<'_> { + use zen_expression::lane::{Column, Columns}; + let mut columns = Columns::new(self.rows); + for (path, (buf, valid)) in self.paths.iter().zip(&self.bufs) { + if let Some(values) = Self::plain(buf) { + columns = columns.column(path, Column::with_validity(values, valid, 0)); + } + } + columns + } + + pub fn normalized(value: Value) -> Value { + match value { + Value::Object(map) => { + let cleaned: serde_json::Map = map + .into_iter() + .filter(|(_, v)| !v.is_null()) + .map(|(k, v)| (k, Self::normalized(v))) + .filter(|(_, v)| !matches!(v, Value::Object(m) if m.is_empty())) + .collect(); + Value::Object(cleaned) + } + other => other, + } + } +} diff --git a/core/engine/tests/support/fixture.rs b/core/engine/tests/support/fixture.rs new file mode 100644 index 00000000..73e9ef80 --- /dev/null +++ b/core/engine/tests/support/fixture.rs @@ -0,0 +1,168 @@ +use crate::support::test_data_root; +use serde_json::{json, Value}; +use std::fs; +use std::path::{Path, PathBuf}; +use zen_engine::model::{DecisionContent, GraphContent}; + +pub struct Fixture { + pub name: String, + pub content: GraphContent, + pub inputs: Vec, +} + +impl Fixture { + pub fn load_all() -> Vec { + let root = PathBuf::from(test_data_root()); + let mut paths: Vec = fs::read_dir(root.join("graphs")) + .into_iter() + .flatten() + .chain(fs::read_dir(&root).into_iter().flatten()) + .chain( + fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/compiled")) + .into_iter() + .flatten(), + ) + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + paths.sort(); + paths.iter().filter_map(|p| Self::load(p)).collect() + } + + pub fn load(path: &Path) -> Option { + let text = fs::read_to_string(path).ok()?; + let raw: Value = serde_json::from_str(&text).ok()?; + let content: DecisionContent = serde_json::from_value(raw.clone()).ok()?; + let DecisionContent::Graph(graph) = content else { + return None; + }; + let mut inputs: Vec = raw + .get("tests") + .and_then(Value::as_array) + .map(|tests| { + tests + .iter() + .filter_map(|t| t.get("input").cloned()) + .collect() + }) + .unwrap_or_default(); + if inputs.is_empty() { + inputs.push(json!({})); + } + Some(Fixture { + name: path.file_name()?.to_string_lossy().to_string(), + content: (*graph).clone(), + inputs, + }) + } + + pub fn typed_variants(&self) -> Vec { + let mut out: Vec = Vec::new(); + for base in &self.inputs { + out.push(base.clone()); + let Some(object) = base.as_object() else { + continue; + }; + for (key, value) in object { + let mut with = |replacement: Option| { + let mut copy = object.clone(); + match replacement { + Some(v) => copy.insert(key.clone(), v), + None => copy.remove(key), + }; + out.push(Value::Object(copy)); + }; + with(None); + match value { + Value::Number(n) => { + for delta in ["1", "-1", "0", "1000000", "0.5"] { + let shifted: Option = n + .to_string() + .parse::() + .ok() + .zip(delta.parse::().ok()) + .and_then(|(a, b)| a.checked_add(b)); + if let Some(v) = + shifted.and_then(|d| serde_json::from_str(&d.to_string()).ok()) + { + with(Some(v)); + } + } + } + Value::String(s) => { + with(Some(json!(""))); + with(Some(json!(format!("{s}x")))); + } + Value::Bool(b) => with(Some(json!(!b))), + _ => {} + } + } + } + out.truncate(400); + out + } + + pub fn variants(&self) -> Vec { + let mut out: Vec = Vec::new(); + for base in &self.inputs { + out.push(base.clone()); + let Some(object) = base.as_object() else { + continue; + }; + for (key, value) in object { + let mut with = |replacement: Option| { + let mut copy = object.clone(); + match replacement { + Some(v) => { + copy.insert(key.clone(), v); + } + None => { + copy.remove(key); + } + } + out.push(Value::Object(copy)); + }; + with(None); + with(Some(Value::Null)); + match value { + Value::Number(n) => { + let text = n.to_string(); + for delta in ["1", "-1", "0", "1000000", "0.5"] { + let shifted: Option = text + .parse::() + .ok() + .zip(delta.parse::().ok()) + .and_then(|(a, b)| a.checked_add(b)); + if let Some(v) = + shifted.and_then(|d| serde_json::from_str(&d.to_string()).ok()) + { + with(Some(v)); + } + } + with(Some(json!("text"))); + } + Value::String(s) => { + with(Some(json!(""))); + with(Some(json!(format!("{s}x")))); + with(Some(json!(42))); + } + Value::Bool(b) => with(Some(json!(!b))), + Value::Array(items) => { + with(Some(json!([]))); + let mut doubled = items.clone(); + doubled.extend(items.iter().cloned()); + with(Some(Value::Array(doubled))); + } + Value::Object(_) => with(Some(json!({}))), + Value::Null => with(Some(json!(1))), + } + } + } + out.truncate(400); + out + } +} + +pub const NETWORK_BOUND: &[&str] = &["http-function.json"]; +pub const TIME_BOUND: &[&str] = &["infinite-function.json", "sleep-function.json"]; diff --git a/core/engine/tests/support/golden.rs b/core/engine/tests/support/golden.rs new file mode 100644 index 00000000..31752099 --- /dev/null +++ b/core/engine/tests/support/golden.rs @@ -0,0 +1,1020 @@ +use flate2::read::GzDecoder; +use flate2::write::GzEncoder; +use flate2::Compression; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::future::Future; +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use zen_engine::policy::{ + EvaluateRequest, EvaluationError as PolicyError, EvaluationResult, PolicyWorkspace, +}; +use zen_engine::{Decision, DecisionGraphResponse, EvaluationError, EvaluationTraceKind}; +use zen_expression::variable::{RcValue, VariableMap}; +use zen_expression::Variable; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Outcome { + Ok(Value), + Err { debug: String, value: Value }, +} + +impl Outcome { + pub fn missing(key: &str) -> Outcome { + Outcome::Err { + debug: format!("missing golden entry {key}"), + value: Value::Null, + } + } + + pub fn graph(result: &Result>) -> Outcome { + match result { + Ok(response) => Outcome::Ok(Canon::variable(&response.result)), + Err(error) => Outcome::Err { + debug: error.to_string(), + value: Canon::value(serde_json::to_value(&**error).unwrap_or(Value::Null)), + }, + } + } + + pub fn graph_traced( + result: &Result>, + mode: EvaluationTraceKind, + ) -> Outcome { + match result { + Ok(response) => Outcome::Ok(Canon::redacted( + response + .serialize_with_mode(serde_json::value::Serializer, mode) + .unwrap_or(Value::Null), + )), + Err(error) => Outcome::Err { + debug: error.to_string(), + value: Canon::redacted( + error + .serialize_with_mode(serde_json::value::Serializer, mode) + .unwrap_or(Value::Null), + ), + }, + } + } + + pub fn serialized(result: Result) -> Outcome { + match result { + Ok(value) => Outcome::Ok(Canon::redacted(value)), + Err(value) => Outcome::Err { + debug: String::new(), + value: Canon::redacted(value), + }, + } + } + + pub fn policy(result: Result) -> Outcome { + match result { + Ok(result) => Outcome::Ok(Canon::variable(&result.output)), + Err(error) => { + let error = Self::ordered(error); + Outcome::Err { + debug: format!("{error:?}"), + value: Canon::unordered( + serde_json::to_value(&EvaluationError::Policy(error)) + .unwrap_or(Value::Null), + false, + ), + } + } + } + } + + pub fn policy_traced(result: Result) -> Outcome { + match result { + Ok(result) => Outcome::Ok(Canon::unordered( + serde_json::to_value(&result).unwrap_or(Value::Null), + true, + )), + Err(error) => { + let error = Self::ordered(error); + Outcome::Err { + debug: error.to_string(), + value: Canon::unordered( + serde_json::to_value(&EvaluationError::Policy(error)) + .unwrap_or(Value::Null), + true, + ), + } + } + } + } + + pub fn debug(error: &PolicyError) -> String { + match error { + PolicyError::InputValidationFailed { errors } => format!( + "{:?}", + Self::ordered(PolicyError::InputValidationFailed { + errors: errors.clone() + }) + ), + other => format!("{other:?}"), + } + } + + pub fn ordered(error: PolicyError) -> PolicyError { + match error { + PolicyError::InputValidationFailed { mut errors } => { + errors.sort_by(|a, b| { + (&a.path, &a.expected, &a.got).cmp(&(&b.path, &b.expected, &b.got)) + }); + PolicyError::InputValidationFailed { errors } + } + other => other, + } + } + + pub fn value(&self) -> &Value { + match self { + Outcome::Ok(value) => value, + Outcome::Err { value, .. } => value, + } + } + + pub fn normalized(&self, normalize: impl Fn(Value) -> Value) -> Outcome { + match self { + Outcome::Ok(value) => Outcome::Ok(Canon::value(normalize(value.clone()))), + other => other.clone(), + } + } + + pub fn without_trace(&self) -> Outcome { + match self { + Outcome::Err { debug, value } => Outcome::Err { + debug: debug.clone(), + value: match value { + Value::Object(map) => Value::Object( + map.iter() + .filter(|(k, _)| k.as_str() != "trace") + .map(|(k, v)| (k.clone(), v.clone())) + .collect(), + ), + other => other.clone(), + }, + }, + other => other.clone(), + } + } + + pub fn show(&self) -> String { + match self { + Outcome::Ok(value) => value.to_string(), + Outcome::Err { debug, value } => format!("!error {debug} {value}"), + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Entry { + pub key: String, + pub suite: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub goals: Vec, + pub input: Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fingerprint: Option, + pub plain: Outcome, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub traced: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enhanced: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reference: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub ordered: bool, +} + +impl Entry { + pub fn new(suite: &str, goals: &[String], input: &Variable, plain: Outcome) -> Entry { + Entry { + key: Canon::key(suite, goals, input), + suite: suite.to_string(), + goals: goals.to_vec(), + input: Canon::variable(input), + fingerprint: None, + plain, + traced: None, + enhanced: None, + reference: None, + ordered: false, + } + } + + pub fn fingerprint(mut self, fingerprint: Option) -> Entry { + self.fingerprint = fingerprint; + self + } + + pub fn traced(mut self, traced: Outcome, reference: Option) -> Entry { + self.traced = Some(traced); + self.reference = reference; + self + } + + pub fn enhanced(mut self, enhanced: Outcome) -> Entry { + self.enhanced = Some(enhanced); + self + } + + pub fn outcome(&self, mode: Mode) -> Option<&Outcome> { + match mode { + Mode::Plain => Some(&self.plain), + Mode::Traced => self.traced.as_ref(), + Mode::Enhanced => self.enhanced.as_ref(), + } + } + + pub fn merge(&mut self, other: Entry) -> Result<(), String> { + let (traced, enhanced, reference) = ( + self.traced.take().or(other.traced.clone()), + self.enhanced.take().or(other.enhanced.clone()), + self.reference.take().or(other.reference.clone()), + ); + self.traced = traced; + self.enhanced = enhanced; + self.reference = reference; + let consistent = self.plain == other.plain + && other + .traced + .as_ref() + .is_none_or(|t| self.traced.as_ref() == Some(t)) + && other + .enhanced + .as_ref() + .is_none_or(|t| self.enhanced.as_ref() == Some(t)) + && other + .reference + .as_ref() + .is_none_or(|t| self.reference.as_ref() == Some(t)); + self.ordered |= !consistent || other.ordered; + match self.fingerprint == other.fingerprint { + true => Ok(()), + false => Err(format!( + "{}: fingerprints differ between duplicates", + self.key + )), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Mode { + Plain, + Traced, + Enhanced, +} + +pub struct Canon; + +impl Canon { + pub const REDACTED: [&'static str; 4] = + ["performance", "msSinceRun", "engineVersion", "duration"]; + + pub fn value(value: Value) -> Value { + Self::sorted(value, false) + } + + pub fn redacted(value: Value) -> Value { + Self::sorted(value, true) + } + + pub fn variable(variable: &Variable) -> Value { + Self::value(Self::typed(variable)) + } + + fn typed(variable: &Variable) -> Value { + match variable { + Variable::Dynamic(d) => { + serde_json::json!({ "$type": d.type_name(), "$value": d.to_value() }) + } + Variable::Array(items) => { + Value::Array(items.borrow().iter().map(Self::typed).collect()) + } + Variable::Object(map) => Value::Object( + map.borrow() + .iter() + .map(|(k, v)| (k.to_string(), Self::typed(v))) + .collect(), + ), + other => serde_json::to_value(other).unwrap_or(Value::Null), + } + } + + pub fn restore(value: &Value) -> Variable { + match value { + Value::Object(map) + if map.len() == 2 && map.get("$type").and_then(Value::as_str) == Some("date") => + { + let text = map + .get("$value") + .and_then(Value::as_str) + .unwrap_or_default(); + zen_expression::DateValue::from_text(text) + .unwrap_or_else(|| Variable::String(text.into())) + } + Value::Object(map) if map.len() == 2 && map.contains_key("$type") => map + .get("$value") + .map(Self::restore) + .unwrap_or(Variable::Null), + Value::Array(items) => Variable::from_array(items.iter().map(Self::restore).collect()), + Value::Object(map) => { + let mut object = VariableMap::new(); + for (key, item) in map { + object.insert(Variable::key(key), Self::restore(item)); + } + Variable::from_object(object) + } + other => Variable::from(other.clone()), + } + } + + pub fn unordered(value: Value, redact: bool) -> Value { + Self::sorted(Self::sets(value), redact) + } + + fn sets(value: Value) -> Value { + match value { + Value::Object(map) => Value::Object( + map.into_iter() + .map(|(k, v)| match (k.as_str(), v) { + ("writes", Value::Array(mut items)) => { + items.sort_by_key(|item| { + item.get("path").map(Value::to_string).unwrap_or_default() + }); + let items = items.into_iter().map(Self::sets).collect(); + (k, Value::Array(items)) + } + (_, v) => (k, Self::sets(v)), + }) + .collect(), + ), + Value::Array(items) => Value::Array(items.into_iter().map(Self::sets).collect()), + other => other, + } + } + + pub const DEPTH: usize = 96; + + fn sorted(value: Value, redact: bool) -> Value { + Self::bounded(value, redact, 0) + } + + fn bounded(value: Value, redact: bool, depth: usize) -> Value { + if depth >= Self::DEPTH && (value.is_object() || value.is_array()) { + let flat = Self::bounded(value, redact, 0); + return serde_json::json!({ "$digest": Self::hash(&serde_json::to_string(&flat).unwrap_or_default()) }); + } + match value { + Value::Object(map) => { + let ordered: BTreeMap = map + .into_iter() + .map( + |(k, v)| match redact && Self::REDACTED.contains(&k.as_str()) { + true => (k, Value::String("~".to_string())), + false => (k, Self::bounded(v, redact, depth + 1)), + }, + ) + .collect(); + Value::Object(ordered.into_iter().collect::>()) + } + Value::Array(items) => Value::Array( + items + .into_iter() + .map(|v| Self::bounded(v, redact, depth + 1)) + .collect(), + ), + other => other, + } + } + + pub fn tagged(variable: &Variable, out: &mut String) { + match variable { + Variable::Null => out.push('z'), + Variable::Bool(true) => out.push('t'), + Variable::Bool(false) => out.push('f'), + Variable::Number(n) => { + out.push('n'); + out.push_str(&n.to_string()); + } + Variable::String(s) => { + out.push('s'); + out.push_str(&serde_json::to_string(s.as_str()).unwrap_or_default()); + } + Variable::Dynamic(d) => { + out.push('d'); + out.push_str(d.type_name()); + out.push_str(&serde_json::to_string(&d.to_string()).unwrap_or_default()); + } + Variable::Array(items) => { + out.push('['); + for (at, item) in items.borrow().iter().enumerate() { + if at > 0 { + out.push(','); + } + Self::tagged(item, out); + } + out.push(']'); + } + Variable::Object(map) => { + let map = map.borrow(); + let mut entries: Vec<(&str, &Variable)> = + map.iter().map(|(k, v)| (k.as_str(), v)).collect(); + entries.sort_by(|a, b| a.0.cmp(b.0)); + out.push('{'); + for (at, (key, value)) in entries.into_iter().enumerate() { + if at > 0 { + out.push(','); + } + out.push_str(&serde_json::to_string(key).unwrap_or_default()); + out.push(':'); + Self::tagged(value, out); + } + out.push('}'); + } + } + } + + pub fn hash(text: &str) -> String { + let hash = text + .bytes() + .fold(0x6c62_272e_07bb_0142_62b8_2175_6295_c58du128, |h, b| { + (h ^ b as u128).wrapping_mul(0x0000_0000_0100_0000_0000_0000_0000_013b) + }); + format!("{hash:032x}") + } + + pub fn key(suite: &str, goals: &[String], input: &Variable) -> String { + let mut text = String::new(); + Self::tagged(input, &mut text); + format!("{suite} | {} | {}", goals.join(","), Self::hash(&text)) + } + + pub fn sharing(value: &Value) -> (usize, usize) { + let refs = value + .get("$refs") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let shared: BTreeSet = refs + .iter() + .enumerate() + .filter(|(_, v)| v.is_object() || v.is_array()) + .map(|(at, _)| at) + .collect(); + (shared.len(), Self::sites(value, &shared)) + } + + fn sites(value: &Value, shared: &BTreeSet) -> usize { + let site = |s: &str| { + s.strip_prefix('@') + .and_then(|id| id.parse::().ok()) + .is_some_and(|id| shared.contains(&id)) + }; + match value { + Value::String(s) => usize::from(site(s)), + Value::Array(items) => items.iter().map(|v| Self::sites(v, shared)).sum(), + Value::Object(map) => map.values().map(|v| Self::sites(v, shared)).sum(), + _ => 0, + } + } + + pub fn reference(traced: &Outcome, serialized: Result) -> Value { + let (ok, raw) = match serialized { + Ok(value) => (true, value), + Err(value) => (false, value), + }; + let Value::Object(mut map) = raw else { + return serde_json::json!({"malformed": true}); + }; + let trace = map.remove("trace"); + let (refs, sites) = trace.as_ref().map_or((0, 0), Self::sharing); + if let Some(trace) = trace { + let dereferenced = Variable::deserialize_ref(RcValue::from(&trace)) + .map(|v| serde_json::to_value(&v).unwrap_or(Value::Null)) + .unwrap_or(Value::String("undecodable".to_string())); + map.insert("trace".to_string(), dereferenced); + } + let response = Canon::redacted(Value::Object(map)); + let same = match traced { + Outcome::Ok(value) => ok && value == &response, + Outcome::Err { value, .. } => !ok && value == &response, + }; + let mut summary = serde_json::json!({"refs": refs, "sites": sites}); + if !same { + summary["response"] = response; + } + summary + } +} + +impl Canon { + pub fn mode(result: Result, reference: bool) -> Outcome { + let (ok, raw) = match result { + Ok(value) => (true, value), + Err(value) => (false, value), + }; + let value = match raw { + Value::Object(mut map) => { + if let Some(trace) = map.remove("trace") { + let trace = match trace { + Value::String(text) => { + serde_json::from_str(&text).unwrap_or_else(|_| Self::opaque(&text)) + } + other => other, + }; + match reference { + true => { + map.insert("$shared".to_string(), Self::shared(&trace)); + let dereferenced = Variable::deserialize_ref(RcValue::from(&trace)) + .map(|v| serde_json::to_value(&v).unwrap_or(Value::Null)) + .unwrap_or(Value::String("undecodable".to_string())); + map.insert("trace".to_string(), dereferenced); + } + false => { + map.insert("trace".to_string(), trace); + } + } + } + Self::redacted(Value::Object(map)) + } + other => Self::redacted(other), + }; + match ok { + true => Outcome::Ok(value), + false => Outcome::Err { + debug: String::new(), + value, + }, + } + } + + fn opaque(text: &str) -> Value { + let marker = "\"performance\":\""; + let mut rest = text; + let mut kept = String::with_capacity(text.len()); + while let Some(at) = rest.find(marker) { + kept.push_str(&rest[..at]); + let tail = &rest[at + marker.len()..]; + rest = tail.find('"').map_or("", |end| &tail[end + 1..]); + } + kept.push_str(rest); + let mut chars: Vec = kept.chars().collect(); + chars.sort_unstable(); + serde_json::json!({ "$unparsed": Self::hash(&chars.into_iter().collect::()) }) + } + + pub fn shared(value: &Value) -> Value { + let refs = value + .get("$refs") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + let mut sites = vec![0usize; refs.len()]; + Self::count(value, &mut sites); + let mut shared: Vec<(String, usize)> = refs + .iter() + .enumerate() + .filter(|(_, v)| v.is_object() || v.is_array()) + .map(|(at, v)| { + ( + serde_json::to_string(&Self::redacted(Self::deref(v, &refs))) + .unwrap_or_default(), + sites[at], + ) + }) + .collect(); + shared.sort(); + serde_json::json!(shared) + } + + fn ref_id(text: &str) -> Option { + text.strip_prefix('@') + .and_then(|id| id.parse::().ok()) + } + + fn count(value: &Value, sites: &mut [usize]) { + match value { + Value::String(text) => { + if let Some(site) = Self::ref_id(text).and_then(|id| sites.get_mut(id)) { + *site += 1; + } + } + Value::Array(items) => items.iter().for_each(|v| Self::count(v, sites)), + Value::Object(map) => map.values().for_each(|v| Self::count(v, sites)), + _ => {} + } + } + + fn deref(value: &Value, refs: &[Value]) -> Value { + match value { + Value::String(text) => match Self::ref_id(text).and_then(|id| refs.get(id)) { + Some(target) => Self::deref(target, refs), + None => value.clone(), + }, + Value::Array(items) => { + Value::Array(items.iter().map(|v| Self::deref(v, refs)).collect()) + } + Value::Object(map) => Value::Object( + map.iter() + .map(|(k, v)| { + let key = match Self::ref_id(k).and_then(|id| refs.get(id)) { + Some(Value::String(text)) => text.clone(), + _ => k.clone(), + }; + (key, Self::deref(v, refs)) + }) + .collect(), + ), + other => other.clone(), + } + } +} + +pub struct Written { + pub path: PathBuf, + pub entries: usize, + pub raw: u64, + pub stored: u64, +} + +pub struct Golden { + pub name: String, + entries: BTreeMap, + seen: Mutex>, + missing: Mutex>, + pub conflicts: Vec, +} + +impl Golden { + pub const LIMIT: u64 = 15 * 1024 * 1024; + pub const CLOCK: &'static str = "2025-03-20T10:15:30Z"; + + pub fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("golden") + } + + pub fn prepare() { + std::env::set_var("TZ", "UTC"); + std::env::set_var("__ZEN_MOCK_UTC_TIME", Self::CLOCK); + } + + pub fn new(name: &str) -> Golden { + Golden { + name: name.to_string(), + entries: BTreeMap::new(), + seen: Mutex::new(BTreeSet::new()), + missing: Mutex::new(BTreeSet::new()), + conflicts: Vec::new(), + } + } + + pub fn insert(&mut self, entry: Entry) { + match self.entries.get_mut(&entry.key) { + Some(existing) => { + if let Err(conflict) = existing.merge(entry) { + self.conflicts.push(conflict); + } + } + None => { + self.entries.insert(entry.key.clone(), entry); + } + } + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn entries(&self) -> impl Iterator { + self.entries.values() + } + + fn files(&self) -> Vec { + let base = Self::root().join(&self.name); + let mut files: Vec = match base.is_dir() { + true => std::fs::read_dir(&base) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .collect(), + false => ["jsonl", "jsonl.gz"] + .iter() + .map(|ext| Self::root().join(format!("{}.{ext}", self.name))) + .collect(), + }; + files.retain(|p| p.is_file() && p.to_string_lossy().contains(".jsonl")); + files.sort(); + files + } + + pub fn open(name: &str) -> Golden { + let mut golden = Golden::new(name); + let files = golden.files(); + assert!( + !files.is_empty(), + "no golden files for {name} under {}", + Self::root().display() + ); + for path in files { + let file = std::fs::File::open(&path).expect("golden file"); + let reader: Box = match path.extension().is_some_and(|e| e == "gz") { + true => Box::new(GzDecoder::new(file)), + false => Box::new(file), + }; + for line in BufReader::new(reader).lines() { + let line = line.expect("golden line"); + let entry: Entry = serde_json::from_str(&line) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())); + golden.insert(entry); + } + } + golden + } + + pub fn get(&self, key: &str) -> Option<&Entry> { + match self.entries.get(key) { + Some(entry) => { + self.seen.lock().expect("seen").insert(key.to_string()); + Some(entry) + } + None => { + self.missing + .lock() + .expect("missing") + .insert(key.to_string()); + None + } + } + } + + pub fn outcome(&self, key: &str, mode: Mode) -> Outcome { + match self.get(key).and_then(|e| e.outcome(mode)) { + Some(outcome) => outcome.clone(), + None => Outcome::missing(key), + } + } + + pub fn missing(&self) -> Vec { + self.missing + .lock() + .expect("missing") + .iter() + .cloned() + .collect() + } + + pub fn unvisited(&self) -> Vec { + let seen = self.seen.lock().expect("seen"); + self.entries + .keys() + .filter(|k| !seen.contains(*k)) + .cloned() + .collect() + } + + pub fn compare(&self, recorded: &Golden) -> Vec { + let mut out = Vec::new(); + for (key, entry) in &self.entries { + match recorded.entries.get(key) { + None => out.push(format!("{key}: not in recorded goldens")), + Some(want) if want != entry => out.push(format!( + "{key}: differs\n recorded {}\n live {}", + serde_json::to_string(want).unwrap_or_default(), + serde_json::to_string(entry).unwrap_or_default() + )), + Some(_) => {} + } + } + out.extend( + recorded + .entries + .keys() + .filter(|k| !self.entries.contains_key(*k)) + .map(|k| format!("{k}: recorded but no longer produced")), + ); + out + } + + pub fn write(&self, shard: impl Fn(&Entry) -> Option) -> Vec { + let mut shards: BTreeMap, Vec> = BTreeMap::new(); + for entry in self.entries.values() { + shards + .entry(shard(entry)) + .or_default() + .push(serde_json::to_string(entry).expect("entry json")); + } + let raw: u64 = shards.values().flatten().map(|l| l.len() as u64 + 1).sum(); + let gzip = raw > Self::LIMIT || std::env::var("GOLDEN_GZIP").is_ok_and(|v| v == "1"); + for stale in self.files() { + std::fs::remove_file(stale).expect("remove stale golden"); + } + let extension = match gzip { + true => "jsonl.gz", + false => "jsonl", + }; + let mut written = Vec::new(); + for (shard, lines) in shards { + let path = match shard { + Some(name) => Self::root() + .join(&self.name) + .join(format!("{name}.{extension}")), + None => Self::root().join(format!("{}.{extension}", self.name)), + }; + std::fs::create_dir_all(path.parent().expect("parent")).expect("golden dir"); + let mut text = lines.join("\n"); + text.push('\n'); + let bytes = match gzip { + true => { + let mut encoder = GzEncoder::new(Vec::new(), Compression::new(9)); + encoder.write_all(text.as_bytes()).expect("gzip"); + encoder.finish().expect("gzip") + } + false => text.clone().into_bytes(), + }; + std::fs::write(&path, &bytes).expect("write golden"); + written.push(Written { + path, + entries: lines.len(), + raw: text.len() as u64, + stored: bytes.len() as u64, + }); + } + written + } +} + +pub struct Live; + +impl Live { + pub const GRAPH: &'static str = "live graph references need the driver feature"; + + #[cfg(feature = "driver")] + pub fn walker(decision: &Decision) -> Decision { + decision.interpreted() + } + + #[cfg(not(feature = "driver"))] + pub fn walker(decision: &Decision) -> Decision { + decision.clone() + } + + pub fn require_walker() { + assert!(cfg!(feature = "driver"), "{}", Self::GRAPH); + } + + #[cfg(feature = "driver")] + pub fn policy( + ws: &PolicyWorkspace, + req: &EvaluateRequest, + ) -> Result { + ws.evaluate_with_driver(req) + } + + #[cfg(feature = "driver")] + pub fn enhanced( + ws: &PolicyWorkspace, + req: &EvaluateRequest, + ) -> Result { + ws.enhance_trace_with_driver(req) + } + + #[cfg(not(feature = "driver"))] + pub fn policy( + _: &PolicyWorkspace, + _: &EvaluateRequest, + ) -> Result { + panic!("live policy references need the driver feature") + } + + #[cfg(not(feature = "driver"))] + pub fn enhanced( + _: &PolicyWorkspace, + _: &EvaluateRequest, + ) -> Result { + panic!("live policy references need the driver feature") + } +} + +pub enum Reference { + Live, + Recorded(Golden), +} + +impl Reference { + const DEFAULT: &'static str = + if cfg!(feature = "driver") || !cfg!(feature = "arbitrary_precision") { + "live" + } else { + "recorded" + }; + pub fn unavailable(corpus: &str) -> bool { + let unavailable = !cfg!(feature = "driver") && !Self::recorded(); + if unavailable { + eprintln!("{corpus}: skipped, references need the driver feature (live) or arbitrary_precision (recorded goldens)"); + } + unavailable + } + + pub fn recorded() -> bool { + std::env::var("GOLDEN_REFERENCE").unwrap_or_else(|_| Self::DEFAULT.to_string()) + == "recorded" + } + + pub fn open(corpus: &str) -> Reference { + match Self::recorded() { + true => { + assert!( + std::env::var("SPEC_TZ").map_or(true, |tz| tz == "UTC"), + "recorded goldens are UTC only" + ); + Golden::prepare(); + Reference::Recorded(Golden::open(corpus)) + } + false => Reference::Live, + } + } + + pub fn prepare(live: &str) { + match Self::recorded() { + true => Golden::prepare(), + false => std::env::set_var("__ZEN_MOCK_UTC_TIME", live), + } + } + + pub fn debug(error: &PolicyError) -> String { + match Self::recorded() { + true => Outcome::debug(error), + false => format!("{error:?}"), + } + } + + pub fn ordered(&self, key: impl FnOnce() -> String) -> bool { + match self { + Reference::Live => false, + Reference::Recorded(golden) => golden.get(&key()).is_some_and(|e| e.ordered), + } + } + + pub fn is_live(&self) -> bool { + matches!(self, Reference::Live) + } + + pub async fn graph( + &self, + key: impl FnOnce() -> String, + live: impl FnOnce() -> F, + recorded: impl FnOnce(&Outcome) -> T, + ) -> T + where + F: Future, + { + match self { + Reference::Live => live().await, + Reference::Recorded(golden) => recorded(&golden.outcome(&key(), Mode::Plain)), + } + } + + pub fn policy( + &self, + key: impl FnOnce() -> String, + live: impl FnOnce() -> T, + recorded: impl FnOnce(&Outcome) -> T, + ) -> T { + match self { + Reference::Live => live(), + Reference::Recorded(golden) => recorded(&golden.outcome(&key(), Mode::Plain)), + } + } + + pub fn stale(&self, key: impl FnOnce() -> String, fingerprint: &str) -> bool { + match self { + Reference::Live => false, + Reference::Recorded(golden) => golden + .get(&key()) + .is_some_and(|e| e.fingerprint.as_deref() != Some(fingerprint)), + } + } + + pub fn missing(&self) -> Vec { + match self { + Reference::Live => Vec::new(), + Reference::Recorded(golden) => golden + .missing() + .into_iter() + .map(|k| format!("missing golden entry {k}")) + .collect(), + } + } +} diff --git a/core/engine/tests/support/mod.rs b/core/engine/tests/support/mod.rs index ec652b7c..5b2890b7 100644 --- a/core/engine/tests/support/mod.rs +++ b/core/engine/tests/support/mod.rs @@ -1,9 +1,30 @@ +pub mod columns; +#[allow(dead_code)] +pub mod golden; + use std::fs::File; use std::io::BufReader; use std::path::Path; use zen_engine::loader::{FilesystemLoader, FilesystemLoaderOptions}; use zen_engine::model::{DecisionContent, GraphContent}; +#[allow(dead_code)] +pub struct Switches { + pub typed: bool, + pub census: bool, +} + +#[allow(dead_code)] +pub fn switches() -> Switches { + let switches = Switches { + typed: std::env::var("ZEN_TYPED").map_or(true, |v| v.trim() != "0"), + census: std::env::var("ZEN_CENSUS").is_ok(), + }; + zen_engine::diagnostics::set_typed(switches.typed); + zen_engine::diagnostics::set_census(switches.census); + switches +} + #[allow(dead_code)] pub fn test_data_root() -> String { let cargo_root = Path::new(env!("CARGO_MANIFEST_DIR")); diff --git a/core/engine/tests/support/policies.rs b/core/engine/tests/support/policies.rs new file mode 100644 index 00000000..54b553db --- /dev/null +++ b/core/engine/tests/support/policies.rs @@ -0,0 +1,606 @@ +use crate::conformance; +use crate::policy_gen::{Gen, Rng}; +use crate::support::columns::Built; +use crate::support::golden::Canon; +use serde::Deserialize; +use serde_json::{json, Value}; +use zen_engine::policy::PolicyWorkspace; +use zen_expression::Variable; + +pub struct Batch { + pub suite: &'static str, + pub policy: String, + pub values: Vec, +} + +impl Batch { + pub fn new(suite: &'static str, policy: &str, values: Vec) -> Batch { + Batch { + suite, + policy: policy.to_string(), + values, + } + } + + pub fn workspace(&self) -> PolicyWorkspace { + Anchor::workspace_with(&self.policy) + } + + pub fn column_rows(&self) -> Vec { + let mut out = Vec::new(); + if let Some(built) = Built::new(&self.values) { + let columns = built.columns(); + out.extend((0..columns.rows).map(|row| columns.row(row))); + } + if let Some(built) = Built::nested(&self.values) { + let fields = built.fields(); + let structs = built.structs(&fields); + let columns = built.columns_with(&structs); + out.extend((0..columns.rows).map(|row| columns.row(row))); + } + out + } +} + +pub struct Anchor; + +impl Anchor { + pub const PATH: &'static str = "anchor"; + + pub const POLICY: &'static str = r#"{ + models: { + customer: {age: "number", income: "number", tier: "string", rate: "number", accounts: "account[]"}, + account: {balance: "number", kind: "string", active: "boolean"}, + }, + blocks: [ + {expression: "account.fee", value: "account.balance * customer.rate / 100 * (account.kind == 'loan' ? 2 : 1)"}, + {match: "account.label", arms: [["account.kind == 'savings'", "'S'"], ["account.kind == 'checking'", "'C'"], ["", "'L'"]]}, + {expression: "customer.total", value: "sum(map(filter(customer.accounts, #.active), #.balance))"}, + {expression: "customer.fees", value: "sum(map(customer.accounts, #.fee))"}, + {match: "customer.risk", arms: [["customer.total > customer.income * 2", "'high'"], ["customer.total > customer.income", "'mid'"], ["", "'low'"]]}, + {table: "discount", inputs: ["customer.tier", "customer.risk"], outputs: ["customer.discount"], rules: [ + ["'gold'", "'low'", "0.15"], + ["'gold'", "'mid'", "0.1"], + ["'silver'", "'low'", "0.1"], + ["'silver'", "'mid'", "0.05"], + ["", "'low'", "0.02"], + ["", "", "0"], + ]}, + {expression: "customer.net", value: "customer.total - customer.fees - customer.discount"}, + {assertion: "customer.eligible", conditions: ["customer.age >= 18", "customer.risk != 'high'"]}, + ], +}"#; + + pub fn rows(count: usize, seed: u64) -> Vec { + let mut state = seed | 1; + let mut pick = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + (0..count) + .map(|_| { + let accounts: Vec = (0..pick(8)) + .map(|_| { + let (balance, kind, active) = (pick(5000), ["savings", "checking", "loan"][pick(3) as usize], pick(4) != 0); + json!({"balance": balance, "kind": kind, "active": active}) + }) + .collect(); + let (age, income, tier, rate) = (16 + pick(64), 1000 + pick(9000), ["gold", "silver", "bronze"][pick(3) as usize], 1 + pick(5)); + json!({"customer": {"age": age, "income": income, "tier": tier, "rate": rate, "accounts": accounts}}) + }) + .collect() + } + + pub fn workspace() -> PolicyWorkspace { + Self::workspace_with(Self::POLICY) + } + + pub fn workspace_with(policy: &str) -> PolicyWorkspace { + crate::support::switches(); + let literal = conformance::literal::Parser::document(policy).expect("policy literal"); + let document = conformance::policy::Policy::expand(&literal[0]).expect("policy expand"); + let mut ws = PolicyWorkspace::new(); + ws.set_policy( + "anchor", + serde_json::from_value(document).expect("policy json"), + ); + ws + } + + pub fn typed() -> bool { + crate::support::switches().typed + } + + pub fn base() -> Batch { + Batch::new("anchor", Self::POLICY, Self::rows(1024, 7)) + } + + pub fn fallback_policy() -> String { + Self::POLICY.replace( + " {match: \"customer.risk\"", + " {expression: \"customer.label\", value: \"split(customer.tier, 'l')\"},\n {match: \"customer.risk\"", + ) + } + + pub fn fallback() -> Batch { + Batch::new( + "anchor-fallback", + &Self::fallback_policy(), + Self::rows(256, 5), + ) + } + + pub fn fused_policy() -> String { + Self::POLICY.replace( + " {match: \"customer.risk\"", + " {expression: \"customer.label\", value: \"split(customer.tier, 'l')\"},\n {expression: \"customer.tag\", value: \"split(customer.tier, 'o')\"},\n {match: \"customer.risk\"", + ) + } + + pub fn fusion(seed: u64) -> Batch { + Batch::new("anchor-fused", &Self::fused_policy(), Self::rows(256, seed)) + } + + pub fn members_policy() -> String { + Self::POLICY + .replace( + " {expression: \"customer.total\"", + " {table: \"band\", inputs: [\"account.balance\", \"customer.tier\"], outputs: [\"account.band\", \"account.boost\"], rules: [\n [\"> 4000\", \"'gold'\", \"'A'\", \"1.5\"],\n [\"> 2000\", \"\", \"'B'\", \"2\"],\n [\"\", \"\", \"'C'\", \"0\"],\n ]},\n {expression: \"customer.total\"", + ) + .replace( + " {assertion: \"customer.eligible\"", + " {expression: \"customer.rich\", value: \"some(customer.accounts, #.balance > 4000)\"},\n {expression: \"customer.active\", value: \"all(customer.accounts, #.active)\"},\n {expression: \"customer.loans\", value: \"count(customer.accounts, #.kind == 'loan')\"},\n {expression: \"customer.third\", value: \"round(customer.total / 3, 2) + customer.total % 7\"},\n {expression: \"customer.gap\", value: \"abs(customer.total - customer.income) + min([customer.total, customer.income, 100])\"},\n {expression: \"customer.square\", value: \"floor(customer.income / 7) ^ 2\"},\n {assertion: \"customer.eligible\"", + ) + } + + pub fn members(seed: u64) -> Batch { + Batch::new( + "anchor-members", + &Self::members_policy(), + Self::rows(300, seed), + ) + } + + pub fn lists() -> Batch { + let policy = r#"{ + models: { + customer: {limit: "number", rate: "number", tags: "string[]", scores: "number[]", companies: "company[]", holdings: "holding[]"}, + company: {revenue: "number", active: "boolean", depts: "dept[]"}, + holding: {value: "number", lots: "lot[]"}, + dept: {size: "number", cost: "number"}, + lot: {qty: "number"}, + }, + blocks: [ + {expression: "company.cost", value: "sum(map(company.depts, #.cost))"}, + {expression: "company.wide", value: "count(company.depts, #.size > customer.limit)"}, + {expression: "company.sizes", value: "map(company.depts, #.size * 2)"}, + {expression: "customer.total", value: "sum(map(customer.companies, #.revenue))"}, + {expression: "customer.lots", value: "sum(map(customer.holdings, sum(map(#.lots, #.qty))))"}, + {expression: "customer.big", value: "map(filter(customer.holdings, #.value > customer.limit), #.value)"}, + {expression: "customer.score", value: "sum(customer.scores)"}, + {expression: "customer.vip", value: "'vip' in customer.tags"}, + {expression: "customer.hit", value: "contains(customer.scores, 3)"}, + {expression: "customer.scaled", value: "map(customer.scores, # * customer.rate)"}, + {expression: "customer.kept", value: "count(filter(customer.holdings, #.value > 10), len(#.lots) > 1)"}, + {expression: "customer.top", value: "max(map(customer.holdings, #.value))"}, + ], +}"#; + let mut state = 23u64; + let mut pick = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + let mut values: Vec = (0..300) + .map(|_| { + let companies: Vec = (0..pick(4)) + .map(|_| { + let depts: Vec = (0..pick(4)).map(|_| json!({"size": pick(30), "cost": pick(900) as f64 / 4.0})).collect(); + json!({"revenue": pick(10_000), "active": pick(3) != 0, "depts": depts}) + }) + .collect(); + let holdings: Vec = (0..pick(4)) + .map(|_| { + let lots: Vec = (0..pick(4)).map(|_| json!({"qty": pick(100)})).collect(); + json!({"value": pick(50), "lots": lots}) + }) + .collect(); + let scores: Vec = (0..pick(5)).map(|_| json!(pick(8))).collect(); + let tags: Vec = (0..pick(3)).map(|_| json!(["a", "vip", "b"][pick(3) as usize])).collect(); + json!({"customer": {"limit": pick(20), "rate": pick(4) as f64 / 2.0, "tags": tags, "scores": scores, "companies": companies, "holdings": holdings}}) + }) + .collect(); + let odd = [ + json!({"customer": {"limit": 1, "rate": 1, "tags": [], "scores": [], "companies": [], "holdings": []}}), + json!({"customer": {"limit": null, "rate": null, "tags": null, "scores": null, "companies": null, "holdings": null}}), + json!({"customer": {"limit": 2, "rate": 0.5, "tags": ["vip"], "scores": [9223372036854775807i64, 9223372036854775807i64], "companies": [{"revenue": 9223372036854775807i64, "active": true, "depts": [{"size": 1, "cost": 9223372036854775807i64}, {"size": 2, "cost": 9223372036854775807i64}]}], "holdings": [{"value": 1, "lots": [{"qty": 9223372036854775807i64}, {"qty": 9223372036854775807i64}]}]}}), + json!({"customer": {"limit": 3, "rate": 2, "tags": ["a"], "scores": [1.50, 0.00, 3], "companies": [{"revenue": 1, "active": null, "depts": null}], "holdings": [{"value": null, "lots": null}]}}), + json!({"customer": {"limit": 3, "rate": 2, "tags": ["a", 1], "scores": ["x"], "companies": [{"revenue": "lots", "depts": []}], "holdings": [{"value": 4}]}}), + json!({"customer": {"limit": 0, "rate": 0.25, "tags": [null], "scores": [null, 3], "companies": [{"revenue": 5, "active": false, "depts": [{"size": null, "cost": 0.000000001}]}], "holdings": [{"value": 30, "lots": [{"qty": 1}, {"qty": 2}]}]}}), + json!({"customer": {"limit": 5}}), + ]; + for (at, row) in odd.into_iter().enumerate() { + values.insert(at * 37 + 4, row); + } + Batch::new("typed-lists", policy, values) + } + + pub fn strings() -> [Batch; 2] { + let policy = r#"{ + models: { + customer: {name: "string", city: "string", tier: "string", amount: "number", qty: "number", flag: "boolean", tags: "string[]", items: "item[]"}, + item: {name: "string", qty: "number"}, + }, + blocks: [ + {expression: "item.label", value: "upper(item.name) + '-' + customer.tier"}, + {expression: "item.same", value: "item.name == customer.name"}, + {expression: "item.s", value: "string(item.qty * customer.amount)"}, + {expression: "customer.s", value: "string(customer.amount)"}, + {expression: "customer.tpl", value: "`${customer.name}:${customer.qty}:${customer.flag}`"}, + {expression: "customer.cat", value: "customer.name + '/' + customer.city"}, + {expression: "customer.up", value: "upper(customer.name)"}, + {expression: "customer.tr", value: "trim(customer.city)"}, + {expression: "customer.has", value: "contains(lower(customer.name), 'an')"}, + {expression: "customer.tz", value: "customer.tier ?? 'none'"}, + {expression: "customer.pick", value: "customer.qty > 4 ? customer.name : 'nobody'"}, + {expression: "customer.same", value: "customer.name == customer.city"}, + {expression: "customer.gold", value: "customer.tz in ['gold', 'none']"}, + {expression: "customer.names", value: "map(customer.items, #.name)"}, + {expression: "customer.cnt", value: "count(customer.items, #.name == customer.tier)"}, + {expression: "customer.intag", value: "customer.city in customer.tags"}, + {expression: "customer.rx", value: "matches(customer.name, '^[A-Z]')"}, + {expression: "customer.big", value: "string(customer.amount * 1000000000000)"}, + {expression: "customer.again", value: "upper(customer.tz) + '!'"}, + {table: "lvl", inputs: ["customer.qty"], outputs: ["customer.lvl"], rules: [ + ["> 7", "customer.name"], + ["> 3", "customer.city"], + ["", "'small'"], + ]}, + {expression: "customer.lv", value: "customer.lvl + ':' + customer.tz"}, + ], +}"#; + let mut state = 41u64; + let mut pick = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + let names = [ + "Anna", + "bob", + " Cara ", + "Émile", + "straße", + "", + "İstanbul", + "日本", + "Bart", + ]; + let cities = ["Berlin", "bonn", "Anna", " x ", ""]; + let tiers = ["gold", "silver", "Gold"]; + let mut values: Vec = (0..300) + .map(|_| { + let items: Vec = (0..pick(4)).map(|_| json!({"name": names[pick(9) as usize], "qty": pick(9)})).collect(); + let tags: Vec = (0..pick(3)).map(|_| json!(cities[pick(5) as usize])).collect(); + json!({"customer": {"name": names[pick(9) as usize], "city": cities[pick(5) as usize], "tier": tiers[pick(3) as usize], "amount": pick(40_000) as f64 / 8.0 - 2000.0, "qty": pick(10), "flag": pick(2) == 0, "tags": tags, "items": items}}) + }) + .collect(); + let long = "ab".repeat(600); + let odd = [ + json!({"customer": {"name": null, "city": "Berlin", "tier": null, "amount": null, "qty": 3, "flag": null, "tags": null, "items": null}}), + json!({"customer": {"name": long, "city": long, "tier": "gold", "amount": 9223372036854775807i64, "qty": 9, "flag": false, "tags": [], "items": []}}), + json!({"customer": {"name": "ß", "city": "Dž", "tier": "", "amount": -0.0, "qty": 0, "flag": true, "tags": ["Dž"], "items": [{"name": "ß", "qty": 1}]}}), + json!({"customer": {"name": "\u{1F600} x", "city": "\u{2003}a\u{2003}", "tier": "silver", "amount": 0.000000001, "qty": 6, "flag": false, "tags": ["\u{2003}a\u{2003}"], "items": [{"qty": 2}]}}), + json!({"customer": {"qty": 5}}), + json!({"customer": {"name": "Anna", "city": "Anna", "tier": "gold", "amount": 1.50, "qty": 8, "flag": true, "tags": ["Anna"], "items": [{"name": "gold", "qty": 9223372036854775807i64}]}}), + ]; + for (at, row) in odd.into_iter().enumerate() { + values.insert(at * 37 + 4, row); + } + let first = Batch::new("typed-strings", policy, values.clone()); + values.insert(12, json!({"customer": {"name": "q", "city": "q", "tier": "gold", "amount": 1, "qty": 2, "flag": true, "tags": [null], "items": [{"name": null, "qty": 2}]}})); + values.insert(9, json!({"customer": {"name": 7, "city": true, "tier": 1.5, "amount": "x", "qty": 1, "flag": true, "tags": [1], "items": [{"name": 3, "qty": "a"}]}})); + [first, Batch::new("typed-strings", policy, values)] + } + + pub fn dates() -> [Batch; 2] { + let policy = r#"{ + models: { + customer: {start: "string", other: "string", days: "number", events: "event[]"}, + event: {on: "string", amt: "number"}, + }, + blocks: [ + {expression: "event.due", value: "d(event.on).add(customer.days, 'day')"}, + {expression: "event.late", value: "d(event.on) > d(customer.start)"}, + {expression: "event.s", value: "string(d(event.on).startOf('month'))"}, + {expression: "customer.f", value: "d(customer.start).format('%d.%m.%Y')"}, + {expression: "customer.y", value: "d(customer.start).year()"}, + {expression: "customer.ok", value: "d(customer.start).isValid()"}, + {expression: "customer.past", value: "d(customer.start) < d()"}, + {expression: "customer.same", value: "d(customer.start) == customer.other"}, + {expression: "customer.dts", value: "map(customer.events, d(#.on).endOf('day'))"}, + {expression: "customer.any", value: "some(customer.events, d(#.on).isBefore(d(customer.other)))"}, + {expression: "customer.first", value: "min(map(customer.events, d(#.on)))"}, + {expression: "customer.cnt", value: "count(customer.events, #.on > d(customer.start))"}, + {table: "era", inputs: ["customer.start"], outputs: ["customer.era"], rules: [ + ["< d('2000-01-01')", "'old'"], + ["", "'new'"], + ]}, + ], +}"#; + let mut state = 43u64; + let mut pick = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + let days = [ + "2024-01-15", + "2024-02-29", + "2023-12-31 23:59:59", + "2024-03-31T01:30:00Z", + "1999-06-30", + "2025-03-30 02:30:00", + "9999-12-31", + "2024/01/15", + "2024-07", + ]; + let bad = ["nope", "", "2024-02-30"]; + let day = |pick: &mut dyn FnMut(u64) -> u64| match pick(15) { + 0 => json!(bad[pick(3) as usize]), + _ => json!(days[pick(9) as usize]), + }; + let mut values: Vec = (0..300) + .map(|_| { + let events: Vec = (0..1 + pick(4)).map(|_| json!({"on": day(&mut pick), "amt": pick(100)})).collect(); + json!({"customer": {"start": day(&mut pick), "other": day(&mut pick), "days": pick(400) as i64 - 200, "events": events}}) + }) + .collect(); + let odd = [ + json!({"customer": {"start": null, "other": null, "days": 0, "events": []}}), + json!({"customer": {"start": "0001-01-01", "other": "9999-12-31", "days": 1000000000, "events": [{"on": "9999-12-31", "amt": 1}]}}), + json!({"customer": {"start": "2024-02-29", "other": "2024-02-29T00:00:00Z", "days": -366, "events": [{"amt": 1}]}}), + ]; + for (at, row) in odd.into_iter().enumerate() { + values.insert(at * 37 + 4, row); + } + let first = Batch::new("typed-dates", policy, values.clone()); + values.insert(9, json!({"customer": {"start": 7, "other": true, "days": "x", "events": [{"on": 3, "amt": "a"}]}})); + values.insert(15, json!({"customer": {"start": "2024-02-29", "other": null, "days": 1, "events": [{"on": null, "amt": 1}]}})); + [first, Batch::new("typed-dates", policy, values)] + } + + pub fn extremes() -> [Batch; 2] { + let customer = |accounts: Value| json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": accounts}}); + let overflow = [ + customer(json!([{"balance": 9223372036854775807i64, "kind": "loan", "active": true}])), + customer( + json!([{"balance": 4611686018427387904i64, "kind": "savings", "active": true}, {"balance": 4611686018427387904i64, "kind": "savings", "active": true}]), + ), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 9223372036854775807i64, "accounts": [{"balance": 3, "kind": "loan", "active": true}]}}), + ]; + let odd = [ + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": -0.0, "accounts": [{"balance": 3, "kind": "loan", "active": true}]}}), + customer(json!([])), + customer( + json!([{"balance": 0, "kind": "loan", "active": true}, {"balance": 0, "kind": "savings", "active": false}]), + ), + customer( + json!([{"balance": 12.5, "kind": "checking", "active": true}, {"balance": 0.000000001, "kind": "savings", "active": true}]), + ), + customer( + json!([{"balance": 0.00, "kind": "savings", "active": true}, {"balance": 1.50, "kind": "loan", "active": true}]), + ), + customer( + json!([{"balance": -250, "kind": "other", "active": true}, {"balance": 7, "kind": "", "active": false}]), + ), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 0.25, "accounts": [{"balance": 100, "kind": "savings", "active": true}]}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2}}), + json!({"customer": {"age": 30, "income": 4000, "tier": "gold", "rate": 2, "accounts": null}}), + json!({"customer": {"age": null, "income": 4000, "tier": "gold", "rate": 2, "accounts": []}}), + json!({"customer": {"age": 30, "income": null, "tier": null, "rate": null, "accounts": []}}), + json!({"customer": {"age": 17, "income": 0, "tier": "platinum", "rate": 0, "accounts": [{"balance": 5000, "kind": "loan", "active": true}]}}), + json!({"customer": {"age": 18, "income": 0.01, "tier": "silver", "rate": 1.000, "accounts": [{"balance": 1, "kind": "checking", "active": false}]}}), + json!({"customer": {"age": 64, "income": 1.10, "tier": "bronze", "rate": 0.00, "accounts": [{"balance": 0.10, "kind": "loan", "active": true}, {"balance": 3.333, "kind": "checking", "active": true}]}}), + ]; + let nulls = [ + customer(json!([{"balance": -0.0, "kind": "loan", "active": true}])), + customer(json!([{"balance": null, "kind": null, "active": null}])), + customer(json!([{"balance": 5, "kind": "loan"}, {"kind": "savings", "active": true}])), + customer(json!([null])), + ]; + let policy = Self::POLICY; + let mut values = Self::rows(128, 13); + for (at, row) in odd.into_iter().enumerate() { + values.insert(at * 7 + 2, row); + } + for (at, row) in overflow.iter().enumerate() { + values.insert(at * 31 + 5, row.clone()); + } + let first = Batch::new("anchor", policy, values.clone()); + for (at, row) in nulls.into_iter().enumerate() { + values.insert(at * 11 + 3, row); + } + [first, Batch::new("anchor", policy, values)] + } + + pub fn batches() -> Vec { + let mut out = vec![Self::base(), Self::fallback()]; + out.extend([5, 6, 7].map(Self::fusion)); + out.extend([5, 9].map(Self::members)); + out.push(Self::lists()); + out.extend(Self::strings()); + out.extend(Self::dates()); + out.extend(Self::extremes()); + out + } +} + +#[derive(Deserialize)] +struct EvaluationFile { + test: Vec, +} + +#[derive(Deserialize)] +struct EvaluationCase { + name: String, + policies: Vec, + input: toml::Value, +} + +pub struct PolicyCase { + pub name: String, + pub path: String, + pub workspace: PolicyWorkspace, + pub inputs: Vec, +} + +impl PolicyCase { + const FIXTURES_DIR: &'static str = + concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/policy/fixtures/"); + const EVALUATION: &'static str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/data/policy/evaluation.toml" + ); + + pub fn load_all() -> Vec { + let raw = std::fs::read_to_string(Self::EVALUATION).expect("evaluation.toml"); + let file: EvaluationFile = toml::from_str(&raw).expect("evaluation cases"); + file.test + .into_iter() + .map(|case| { + let mut workspace = PolicyWorkspace::new(); + for path in &case.policies { + let text = std::fs::read_to_string(format!("{}{path}", Self::FIXTURES_DIR)) + .expect("fixture"); + workspace.set_policy( + path.as_str(), + serde_json::from_str(&text).expect("policy document"), + ); + } + let input: Value = serde_json::to_value(&case.input).expect("input"); + PolicyCase { + name: case.name, + path: case.policies[0].clone(), + workspace, + inputs: Self::variants(&input), + } + }) + .collect() + } + + pub fn variants(base: &Value) -> Vec { + let mut out = vec![base.clone()]; + let Some(object) = base.as_object() else { + return out; + }; + for (key, value) in object { + let mut with = |replacement: Option| { + let mut copy = object.clone(); + match replacement { + Some(v) => copy.insert(key.clone(), v), + None => copy.remove(key), + }; + out.push(Value::Object(copy)); + }; + with(None); + with(Some(Value::Null)); + if let Value::Object(inner) = value { + for (field, v) in inner { + let mut nested = inner.clone(); + nested.insert( + field.clone(), + match v { + Value::Number(_) => json!("text"), + Value::String(_) => json!(7), + Value::Bool(b) => json!(!b), + Value::Array(_) => json!([]), + _ => Value::Null, + }, + ); + with(Some(Value::Object(nested))); + } + } + } + out + } + + pub fn leaves(value: &Value, prefix: &str, out: &mut Vec) { + let Value::Object(map) = value else { + out.push(prefix.to_string()); + return; + }; + for (key, child) in map { + let path = match prefix.is_empty() { + true => key.clone(), + false => format!("{prefix}.{key}"), + }; + Self::leaves(child, &path, out); + } + } + + pub fn computed(output: &Value, input: &Value) -> Vec { + let (mut produced, mut given) = (Vec::new(), Vec::new()); + Self::leaves(output, "", &mut produced); + Self::leaves(input, "", &mut given); + produced + .into_iter() + .filter(|p| !given.contains(p)) + .collect() + } + + pub fn goals(computed: &[String], i: usize) -> Vec { + let choices: Vec> = std::iter::once(Vec::new()) + .chain(computed.iter().map(|c| vec![c.clone()])) + .chain( + computed + .windows(2) + .map(|w| vec![w[0].clone(), w[1].clone()]), + ) + .collect(); + choices[(i * 7) % choices.len()].clone() + } +} + +pub struct Generated; + +impl Generated { + pub const PATH: &'static str = "generated.json"; + + pub fn seeds() -> u64 { + std::env::var("POLICY_SEEDS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(300) + } + + pub fn workspace(seed: u64) -> Option { + let parsed = serde_json::from_value(Gen::document(seed)).ok()?; + let mut ws = PolicyWorkspace::new(); + ws.set_policy(Self::PATH, parsed); + Some(ws) + } + + pub fn inputs(seed: u64) -> Vec { + let mut rng = Rng(seed.wrapping_mul(7919) | 1); + (0..24) + .map(|i| match i % 3 { + 0 => Gen::input(&mut rng), + _ => Gen::valid_input(&mut rng), + }) + .collect() + } + + pub fn fingerprint(seed: u64) -> String { + Canon::hash(&serde_json::to_string(&Canon::value(Gen::document(seed))).unwrap_or_default()) + } + + pub fn label(seed: u64) -> String { + format!("seed {seed}") + } +} diff --git a/core/engine/tests/support/policy_gen.rs b/core/engine/tests/support/policy_gen.rs new file mode 100644 index 00000000..b05c67fa --- /dev/null +++ b/core/engine/tests/support/policy_gen.rs @@ -0,0 +1,679 @@ +use serde_json::{json, Value}; + +pub struct Rng(pub u64); + +impl Rng { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + + pub fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T { + &items[self.below(items.len())] + } + + pub fn chance(&mut self, pct: u64) -> bool { + self.next() % 100 < pct + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Num, + Bool, + Str, +} + +const NUM_KEYS: &[&str] = &["doubled", "fee", "score", "bonus"]; +const BOOL_KEYS: &[&str] = &["rich", "flag", "eligible"]; +const STR_KEYS: &[&str] = &["label", "bucket"]; + +const NUM_VALUES: &[&str] = &[ + "customer.income * 2", + "(customer.age ?? 0) + 1", + "(customer.income + 1) / 2", + "customer.income > 100 ? 1 : 2", + "len(customer.tags ?? [])", + "customer.income - 3", + "1.5", + "customer.income", +]; +const BOOL_VALUES: &[&str] = &[ + "customer.income > 1000", + "customer.vip == true", + "customer.vip != true", + "customer.tier == 'gold'", + "customer.tier in ['gold', 'silver']", + "customer.tier not in ['gold']", + "customer.region != 'eu'", + "(customer.age ?? 0) > 30", + "customer.income in [1..500]", + "customer.tier != 'silver'", + "customer.region == 'us'", +]; +const STR_VALUES: &[&str] = &[ + "customer.tier ?? 'none'", + "customer.income > 5 ? 'hi' : 'lo'", + "customer.region ?? 'zz'", + "'x'", +]; +const DT_NUM_CELLS: &[&str] = &["> 100", "<= 50", "[1..200]", "!= 2", "", ""]; +const DT_TIER_CELLS: &[&str] = &["'gold'", "'gold', 'silver'", "", "'bronze'"]; +const DT_BOOL_CELLS: &[&str] = &["true", "false", ""]; +const DT_TAG_CELLS: &[&str] = &[ + "contains($ ?? [], 'gold')", + "some($ ?? [], # == 'silver')", + "all($ ?? [], # != 'x')", + "len($ ?? []) > 0", + "", + "", +]; +const DT_EXPR_CELLS: &[&str] = &[ + "some(customer.tags ?? [], # == 'vip')", + "contains(customer.region ?? '', 'u')", + "(customer.tier ?? 'none') == 'gold'", + "len(customer.region ?? '') > 1", + "", +]; +const DT_FEE_CELLS: &[&str] = &["10", "25", "customer.income * 0.1", "", "0"]; +const DT_PERK_CELLS: &[&str] = &["'lounge'", "'priority'", "", "'starter'"]; +const DT_KIND_CELLS: &[&str] = &["'savings'", "'savings', 'checking'", "", "'other'"]; + +const ACC_NUM_KEYS: &[&str] = &["doubled", "fee", "weight"]; +const ACC_BOOL_KEYS: &[&str] = &["ok", "flagged"]; +const ACC_STR_KEYS: &[&str] = &["label"]; +const ACC_NUM_VALUES: &[&str] = &[ + "account.balance * 2", + "(account.balance ?? 0) + customer.income", + "account.customer.income + 1", + "len(customer.accounts ?? [])", + "account.balance - customer.age", + "1.5", +]; +const ACC_BOOL_VALUES: &[&str] = &[ + "account.active == true", + "account.balance > 100", + "account.kind == 'savings'", + "account.kind in ['savings', 'checking']", + "(account.balance ?? 0) > customer.income", + "account.customer.vip == true", + "account.active != true", +]; +const ACC_STR_VALUES: &[&str] = &[ + "account.kind ?? 'none'", + "account.balance > 5 ? 'hi' : 'lo'", + "'x'", +]; +const COLLECTION_VALUES: &[&str] = &[ + "sum(map(customer.accounts ?? [], #.balance ?? 0))", + "len(customer.accounts ?? [])", + "sum(map(customer.picks ?? [], #.price))", + "len(customer.picks ?? [])", +]; + +pub struct Gen { + rng: Rng, + blocks: Vec, + written: Vec<(String, Kind)>, + written_acc: Vec<(String, Kind)>, + product_block: bool, + counter: usize, +} + +impl Gen { + fn id(&mut self, prefix: &str) -> String { + self.counter += 1; + format!("{prefix}{}", self.counter) + } + + fn free_key(&mut self, kind: Kind) -> Option { + let pool: &[&str] = match kind { + Kind::Num => NUM_KEYS, + Kind::Bool => BOOL_KEYS, + Kind::Str => STR_KEYS, + }; + let candidates: Vec<&str> = pool + .iter() + .copied() + .filter(|key| !self.written.iter().any(|(seen, _)| seen == key)) + .collect(); + if candidates.is_empty() { + return None; + } + Some((*self.rng.pick(&candidates)).to_string()) + } + + fn free_acc_key(&mut self, kind: Kind) -> Option { + let pool: &[&str] = match kind { + Kind::Num => ACC_NUM_KEYS, + Kind::Bool => ACC_BOOL_KEYS, + Kind::Str => ACC_STR_KEYS, + }; + let candidates: Vec<&str> = pool + .iter() + .copied() + .filter(|key| !self.written_acc.iter().any(|(seen, _)| seen == key)) + .collect(); + if candidates.is_empty() { + return None; + } + Some((*self.rng.pick(&candidates)).to_string()) + } + + fn acc_value(&mut self, kind: Kind) -> String { + let prior: Vec = self + .written_acc + .iter() + .filter(|(_, k)| *k == kind) + .map(|(key, _)| format!("account.{key}")) + .collect(); + if !prior.is_empty() && self.rng.chance(35) { + let key = self.rng.pick(&prior).clone(); + return match kind { + Kind::Num => format!("{key} + 1"), + Kind::Bool => format!("not {key}"), + Kind::Str => key, + }; + } + let pool: &[&str] = match kind { + Kind::Num => ACC_NUM_VALUES, + Kind::Bool => ACC_BOOL_VALUES, + Kind::Str => ACC_STR_VALUES, + }; + (*self.rng.pick(pool)).to_string() + } + + fn account_expression_block(&mut self) { + let kind = *self.rng.pick(&[Kind::Num, Kind::Bool, Kind::Str]); + let Some(key) = self.free_acc_key(kind) else { + return; + }; + let value = self.acc_value(kind); + self.block( + "expression", + json!({ "key": format!("account.{key}"), "value": value }), + ); + self.written_acc.push((key, kind)); + } + + fn account_match_block(&mut self) { + let kind = *self.rng.pick(&[Kind::Num, Kind::Str]); + let Some(key) = self.free_acc_key(kind) else { + return; + }; + let arms = 1 + self.rng.below(3); + let mut list: Vec = (0..arms) + .map(|i| { + let condition = self.acc_value(Kind::Bool); + let value = self.acc_value(kind); + json!({ "id": format!("a{i}"), "condition": condition, "value": value }) + }) + .collect(); + let default = self.acc_value(kind); + list.push(json!({ "id": "default", "condition": "", "value": default })); + self.block( + "match", + json!({ "key": format!("account.{key}"), "arms": list }), + ); + self.written_acc.push((key, kind)); + } + + fn account_assertion_block(&mut self) { + let Some(key) = self.free_acc_key(Kind::Bool) else { + return; + }; + let count = 1 + self.rng.below(3); + let conditions: Vec = (0..count) + .map(|i| { + let expression = self.acc_value(Kind::Bool); + let operator = if self.rng.chance(50) { "and" } else { "or" }; + json!({ "id": format!("c{i}"), "expression": expression, "operator": operator, "depth": 0 }) + }) + .collect(); + self.block( + "assertion", + json!({ "output": format!("account.{key}"), "conditions": conditions }), + ); + self.written_acc.push((key, Kind::Bool)); + } + + fn account_table_block(&mut self) { + let Some(key) = self.free_acc_key(Kind::Num) else { + return; + }; + let columns: Vec<(&str, &[&str])> = vec![ + ("account.balance", DT_NUM_CELLS), + ("account.kind", DT_KIND_CELLS), + ("customer.income", DT_NUM_CELLS), + ]; + let n_in = 1 + self.rng.below(2); + let chosen: Vec<(&str, &[&str])> = (0..n_in).map(|_| *self.rng.pick(&columns)).collect(); + let inputs: Vec = chosen + .iter() + .enumerate() + .map(|(i, (field, _))| json!({ "id": format!("i{i}"), "field": field, "name": format!("i{i}") })) + .collect(); + let outputs = vec![json!({ "id": "o1", "field": format!("account.{key}"), "name": "fee" })]; + let n_rules = 1 + self.rng.below(4); + let rules: Vec = (0..n_rules) + .map(|r| { + let mut rule = json!({ "_id": format!("r{r}") }); + for (i, (_, cells)) in chosen.iter().enumerate() { + rule[format!("i{i}")] = json!(*self.rng.pick(cells)); + } + rule["o1"] = json!(*self + .rng + .pick(&["10", "25", "account.balance * 0.1", "", "0"])); + rule + }) + .collect(); + self.block( + "decisionTable", + json!({ "hitPolicy": "first", "inputs": inputs, "outputs": outputs, "rules": rules }), + ); + self.written_acc.push((key, Kind::Num)); + } + + fn collection_block(&mut self) { + let Some(key) = self.free_key(Kind::Num) else { + return; + }; + let value = if self + .written_acc + .iter() + .any(|(k, kind)| k == "doubled" && *kind == Kind::Num) + && self.rng.chance(50) + { + "sum(map(customer.accounts ?? [], #.doubled ?? 0))".to_string() + } else { + (*self.rng.pick(COLLECTION_VALUES)).to_string() + }; + self.block( + "expression", + json!({ "key": format!("customer.{key}"), "value": value }), + ); + self.written.push((key, Kind::Num)); + } + + fn product_block(&mut self) { + if self.product_block { + return; + } + self.product_block = true; + self.block( + "expression", + json!({ "key": "product.discounted", "value": "product.price * 0.9" }), + ); + } + + fn written_of(&self, kind: Kind) -> Vec { + self.written + .iter() + .filter(|(_, k)| *k == kind) + .map(|(key, _)| format!("customer.{key}")) + .collect() + } + + fn value(&mut self, kind: Kind) -> String { + let prior = self.written_of(kind); + if !prior.is_empty() && self.rng.chance(35) { + let key = self.rng.pick(&prior).clone(); + return match kind { + Kind::Num => match self.rng.below(6) { + 0 => format!("{key} + 1"), + 1 => format!("{key} * 2"), + 2 => format!("round({key} / 3, 2)"), + 3 => format!("max([{key}, 10])"), + 4 => format!("min([{key} * 0.5, 100, customer.income])"), + _ => format!("abs({key} - 5) + floor({key})"), + }, + Kind::Bool => { + if self.rng.chance(50) { + key + } else { + format!("not {key}") + } + } + Kind::Str => key, + }; + } + let nums = self.written_of(Kind::Num); + if kind == Kind::Bool && !nums.is_empty() && self.rng.chance(25) { + let key = self.rng.pick(&nums).clone(); + return format!("{key} > 10"); + } + let pool: &[&str] = match kind { + Kind::Num => NUM_VALUES, + Kind::Bool => BOOL_VALUES, + Kind::Str => STR_VALUES, + }; + (*self.rng.pick(pool)).to_string() + } + + fn block(&mut self, kind: &str, data: Value) { + let id = self.id(kind); + self.blocks + .push(json!({ "id": id, "type": kind, "props": { "data": data } })); + } + + fn expression_block(&mut self) { + let kind = *self.rng.pick(&[Kind::Num, Kind::Bool, Kind::Str]); + let Some(key) = self.free_key(kind) else { + return; + }; + let value = self.value(kind); + self.block( + "expression", + json!({ "key": format!("customer.{key}"), "value": value }), + ); + self.written.push((key, kind)); + } + + fn assertion_block(&mut self) { + let Some(key) = self.free_key(Kind::Bool) else { + return; + }; + let count = 1 + self.rng.below(3); + let conditions: Vec = (0..count) + .map(|i| { + let expression = self.value(Kind::Bool); + let operator = if self.rng.chance(50) { "and" } else { "or" }; + let depth = if i == 1 && count == 3 && self.rng.chance(50) { 1 } else { 0 }; + json!({ "id": format!("c{i}"), "expression": expression, "operator": operator, "depth": depth }) + }) + .collect(); + self.block( + "assertion", + json!({ "output": format!("customer.{key}"), "conditions": conditions }), + ); + self.written.push((key, Kind::Bool)); + } + + fn match_block(&mut self) { + let kind = *self.rng.pick(&[Kind::Num, Kind::Str]); + let Some(key) = self.free_key(kind) else { + return; + }; + let arms = 1 + self.rng.below(3); + let mut list: Vec = (0..arms) + .map(|i| { + let condition = self.value(Kind::Bool); + let value = self.value(kind); + json!({ "id": format!("a{i}"), "condition": condition, "value": value }) + }) + .collect(); + let default = self.value(kind); + list.push(json!({ "id": "default", "condition": "", "value": default })); + self.block( + "match", + json!({ "key": format!("customer.{key}"), "arms": list }), + ); + self.written.push((key, kind)); + } + + fn table_block(&mut self) { + let Some(key) = self.free_key(Kind::Num) else { + return; + }; + let with_perks = + self.rng.chance(50) && !self.written.iter().any(|(seen, _)| seen == "perks"); + let columns: Vec<(&str, &[&str])> = vec![ + ("customer.income", DT_NUM_CELLS), + ("customer.tier", DT_TIER_CELLS), + ("customer.vip", DT_BOOL_CELLS), + ("customer.tags", DT_TAG_CELLS), + ("", DT_EXPR_CELLS), + ]; + let n_in = 1 + self.rng.below(2); + let chosen: Vec<(&str, &[&str])> = (0..n_in).map(|_| *self.rng.pick(&columns)).collect(); + let inputs: Vec = chosen + .iter() + .enumerate() + .map(|(i, (field, _))| json!({ "id": format!("i{i}"), "field": field, "name": format!("i{i}") })) + .collect(); + let mut outputs = + vec![json!({ "id": "o1", "field": format!("customer.{key}"), "name": "fee" })]; + if with_perks { + outputs.push(json!({ "id": "o2", "field": "customer.perks[]", "name": "perks" })); + } + let n_rules = 1 + self.rng.below(4); + let rules: Vec = (0..n_rules) + .map(|r| { + let mut rule = json!({ "_id": format!("r{r}") }); + for (i, (_, cells)) in chosen.iter().enumerate() { + rule[format!("i{i}")] = json!(*self.rng.pick(cells)); + } + rule["o1"] = json!(*self.rng.pick(DT_FEE_CELLS)); + if with_perks { + rule["o2"] = json!(*self.rng.pick(DT_PERK_CELLS)); + } + rule + }) + .collect(); + self.block( + "decisionTable", + json!({ "hitPolicy": "first", "inputs": inputs, "outputs": outputs, "rules": rules }), + ); + self.written.push((key, Kind::Num)); + if with_perks { + self.written.push(("perks".to_string(), Kind::Str)); + } + } + + pub fn document(seed: u64) -> Value { + let mut builder = Gen { + rng: Rng(seed | 1), + blocks: Vec::new(), + written: Vec::new(), + written_acc: Vec::new(), + product_block: false, + counter: 0, + }; + builder.block( + "dataModel", + json!({ + "name": "customer", + "properties": [ + { "id": "p1", "name": "income", "type": "number", "array": false, "optional": false }, + { "id": "p2", "name": "vip", "type": "boolean", "array": false, "optional": true }, + { "id": "p3", "name": "region", "type": "string", "array": false, "optional": true }, + { "id": "p4", "name": "tier", "type": "string", "enum": ["gold", "silver", "bronze"], "array": false, "optional": true }, + { "id": "p5", "name": "age", "type": "number", "array": false, "optional": true }, + { "id": "p6", "name": "tags", "type": "string", "array": true, "optional": true }, + { "id": "p7", "name": "accounts", "type": "relationship", "target": "account", "array": true, "optional": true }, + { "id": "p8", "name": "picks", "type": "reference", "target": "product", "array": true, "optional": true } + ] + }), + ); + builder.block( + "dataModel", + json!({ + "name": "account", + "properties": [ + { "id": "a1", "name": "balance", "type": "number", "array": false, "optional": true }, + { "id": "a2", "name": "kind", "type": "string", "enum": ["savings", "checking", "other"], "array": false, "optional": true }, + { "id": "a3", "name": "active", "type": "boolean", "array": false, "optional": true } + ] + }), + ); + builder.block( + "dataModel", + json!({ + "name": "product", + "properties": [ + { "id": "d1", "name": "id", "type": "string", "array": false, "optional": false }, + { "id": "d2", "name": "price", "type": "number", "array": false, "optional": false } + ] + }), + ); + let count = 2 + builder.rng.below(6); + for _ in 0..count { + match builder.rng.below(10) { + 0 => builder.expression_block(), + 1 => builder.assertion_block(), + 2 => builder.match_block(), + 3 => builder.table_block(), + 4 => builder.account_expression_block(), + 5 => builder.account_match_block(), + 6 => builder.account_assertion_block(), + 7 => builder.account_table_block(), + 8 => builder.collection_block(), + _ => builder.product_block(), + } + } + json!({ "blocks": builder.blocks }) + } + + pub fn input(rng: &mut Rng) -> Value { + let mut customer = serde_json::Map::new(); + if rng.chance(90) { + let income = match rng.below(6) { + 0 => json!(null), + 1 => json!("oops"), + 2 => json!(2.5), + _ => json!(rng.below(2000) as i64), + }; + customer.insert("income".into(), income); + } + if rng.chance(60) { + let vip = match rng.below(3) { + 0 => json!(null), + _ => json!(rng.chance(50)), + }; + customer.insert("vip".into(), vip); + } + if rng.chance(60) { + customer.insert("region".into(), json!(*rng.pick(&["eu", "us", "apac"]))); + } + if rng.chance(70) { + customer.insert( + "tier".into(), + json!(*rng.pick(&["gold", "silver", "bronze", "platinum"])), + ); + } + if rng.chance(50) { + customer.insert("age".into(), json!(rng.below(80) as i64)); + } + if rng.chance(40) { + customer.insert("tags".into(), json!(["a", "b"])); + } + if rng.chance(20) { + customer.insert("extra".into(), json!(null)); + } + if rng.chance(75) { + let accounts = match rng.below(10) { + 0 => json!("x"), + 1 => json!(null), + _ => { + let n = rng.below(4); + Value::Array((0..n).map(|_| Self::account(rng)).collect()) + } + }; + customer.insert("accounts".into(), accounts); + } + let mut root = serde_json::Map::new(); + if rng.chance(35) { + let picks = match rng.below(5) { + 0 => json!(["p1", "p9"]), + 1 => json!([]), + 2 => json!(["p2"]), + _ => json!(["p1", "p2"]), + }; + customer.insert("picks".into(), picks); + if rng.chance(85) { + root.insert( + "product".into(), + json!([{ "id": "p1", "price": 3 }, { "id": "p2", "price": 5 }]), + ); + } + } + if rng.chance(15) { + root.insert("account".into(), json!({ "balance": 1, "kind": "savings" })); + } + root.insert("customer".into(), Value::Object(customer)); + Value::Object(root) + } + + pub fn valid_input(rng: &mut Rng) -> Value { + let accounts: Vec = (0..rng.below(5)) + .map(|_| { + let mut account = serde_json::Map::new(); + account.insert("balance".into(), json!(rng.below(500) as i64)); + account.insert( + "kind".into(), + json!(*rng.pick(&["savings", "checking", "other"])), + ); + if rng.chance(50) { + account.insert("active".into(), json!(rng.chance(50))); + } + Value::Object(account) + }) + .collect(); + let mut customer = serde_json::Map::new(); + customer.insert("income".into(), json!(rng.below(3000) as i64)); + customer.insert("vip".into(), json!(rng.chance(50))); + customer.insert("region".into(), json!(*rng.pick(&["eu", "us", "apac"]))); + customer.insert( + "tier".into(), + json!(*rng.pick(&["gold", "silver", "bronze"])), + ); + customer.insert("age".into(), json!(rng.below(90) as i64)); + if rng.chance(50) { + customer.insert("tags".into(), json!(["a", "b"])); + } + customer.insert("accounts".into(), Value::Array(accounts)); + customer.insert( + "picks".into(), + json!(*rng.pick(&[&["p1", "p2"][..], &["p2"][..], &[][..]])), + ); + let mut root = serde_json::Map::new(); + root.insert("customer".into(), Value::Object(customer)); + root.insert( + "product".into(), + json!([{ "id": "p1", "price": 3 }, { "id": "p2", "price": 5 }]), + ); + Value::Object(root) + } + + fn account(rng: &mut Rng) -> Value { + match rng.below(12) { + 0 => json!("str"), + 1 => json!(null), + _ => { + let mut account = serde_json::Map::new(); + if rng.chance(85) { + let balance = match rng.below(8) { + 0 => json!(null), + 1 => json!("oops"), + _ => json!(rng.below(500) as i64), + }; + account.insert("balance".into(), balance); + } + if rng.chance(70) { + account.insert( + "kind".into(), + json!(*rng.pick(&["savings", "checking", "other"])), + ); + } + if rng.chance(50) { + account.insert("active".into(), json!(rng.chance(50))); + } + if rng.chance(15) { + account.insert("customer".into(), json!({ "income": 1, "vip": true })); + } + if rng.chance(10) { + account.insert("doubled".into(), json!(7)); + } + Value::Object(account) + } + } + } +} diff --git a/core/engine/tests/table_dialects.rs b/core/engine/tests/table_dialects.rs new file mode 100644 index 00000000..94466c11 --- /dev/null +++ b/core/engine/tests/table_dialects.rs @@ -0,0 +1,883 @@ +mod support; + +use serde_json::{json, Value}; +use std::sync::Arc; +use support::columns::Built; +use zen_engine::model::DecisionContent; +use zen_engine::policy::{EvaluateRequest, PolicyWorkspace}; +use zen_engine::{Decision, EvaluationOptions}; +use zen_expression::Variable; + +struct Table { + hit: &'static str, + inputs: Vec>, + outputs: Vec<&'static str>, + rules: Vec>, + attributes: Value, + models: Value, + policy: Option<(Value, Value)>, +} + +#[derive(Debug)] +struct Seen { + graph: Vec<(&'static str, String)>, + policy: Vec<(&'static str, String)>, + graph_trace: String, + policy_trace: String, + columns: Option<(String, usize)>, +} + +impl Seen { + fn graph(&self) -> &str { + &self.graph[0].1 + } + + fn policy(&self) -> &str { + &self.policy[0].1 + } + + fn agreed(&self) -> &Self { + for (mode, value) in &self.graph { + assert_eq!( + value, + self.graph(), + "graph mode {mode} disagrees: {self:#?}" + ); + } + for (mode, value) in &self.policy { + assert_eq!( + value, + self.policy(), + "policy mode {mode} disagrees: {self:#?}" + ); + } + self + } + + fn expect(&self, graph: &str, policy: &str) { + println!( + "graph {}\npolicy {}\ngraph trace {}\npolicy trace {}\ncolumns {:?}\n", + self.graph(), + self.policy(), + self.graph_trace, + self.policy_trace, + self.columns + ); + self.agreed(); + if let Some((columns, _)) = &self.columns { + let parsed = |text: &str| { + serde_json::from_str::(text) + .map_or_else(|_| Value::String(text.to_string()), Built::normalized) + }; + assert_eq!( + parsed(columns), + parsed(self.policy()), + "policy columns disagree: {self:#?}" + ); + } + assert_eq!((self.graph(), self.policy()), (graph, policy), "{self:#?}"); + } + + fn columnar(&self) -> &Self { + assert_eq!( + self.columns.as_ref().map(|(_, hosted)| *hosted), + Some(0), + "policy table was hosted: {self:#?}" + ); + self + } +} + +impl Table { + fn new( + hit: &'static str, + inputs: &[Option<&'static str>], + outputs: &[&'static str], + rules: &[&[&'static str]], + ) -> Self { + Self { + hit, + inputs: inputs.to_vec(), + outputs: outputs.to_vec(), + rules: rules.iter().map(|r| r.to_vec()).collect(), + attributes: json!({}), + models: json!({"n": ["number", true]}), + policy: None, + } + } + + fn with_attributes(mut self, attributes: Value) -> Self { + self.attributes = attributes; + self + } + + fn with_models(mut self, models: Value) -> Self { + self.models = models; + self + } + + fn with_policy(mut self, doc: Value, input: Value) -> Self { + self.policy = Some((doc, input)); + self + } + + fn prefixed(text: &str, prefix: &str) -> String { + text.replace("{p}", prefix) + } + + fn data(&self, prefix: &str, out_prefix: &str) -> Value { + let inputs: Vec = self + .inputs + .iter() + .enumerate() + .map(|(i, field)| match field { + Some(field) => { + json!({"id": format!("i{i}"), "name": "", "field": format!("{prefix}{field}")}) + } + None => json!({"id": format!("i{i}"), "name": ""}), + }) + .collect(); + let outputs: Vec = self + .outputs + .iter() + .enumerate() + .map(|(i, field)| json!({"id": format!("o{i}"), "name": "", "field": format!("{out_prefix}{field}")})) + .collect(); + let rules: Vec = self + .rules + .iter() + .enumerate() + .map(|(r, row)| { + let mut rule = serde_json::Map::new(); + rule.insert("_id".into(), json!(format!("r{r}"))); + rule.insert("_description".into(), json!(format!("rule {r}"))); + let ids = (0..self.inputs.len()) + .map(|i| format!("i{i}")) + .chain((0..self.outputs.len()).map(|o| format!("o{o}"))); + for (id, cell) in ids.zip(row) { + rule.insert(id, json!(Self::prefixed(cell, prefix))); + } + Value::Object(rule) + }) + .collect(); + json!({"hitPolicy": self.hit, "inputs": inputs, "outputs": outputs, "rules": rules}) + } + + fn decision(&self) -> Decision { + let mut content = self.data("", ""); + if let (Some(content), Some(attributes)) = + (content.as_object_mut(), self.attributes.as_object()) + { + content.extend(attributes.clone()); + } + let graph = json!({ + "nodes": [ + {"id": "in", "name": "in", "type": "inputNode", "content": {}}, + {"id": "t", "name": "t", "type": "decisionTableNode", "content": content}, + {"id": "out", "name": "out", "type": "outputNode", "content": {}} + ], + "edges": [ + {"id": "e1", "sourceId": "in", "targetId": "t"}, + {"id": "e2", "sourceId": "t", "targetId": "out"} + ] + }); + let DecisionContent::Graph(graph) = + serde_json::from_value::(graph).expect("graph") + else { + panic!("not a graph"); + }; + let mut decision = Decision::from(graph); + decision.compile(); + decision + } + + fn workspace(&self) -> PolicyWorkspace { + let properties: Vec = self + .models + .as_object() + .expect("models") + .iter() + .map(|(name, spec)| { + let ty = spec[0].as_str().unwrap_or("number"); + let (ty, array) = match ty.strip_suffix("[]") { + Some(base) => (base, true), + None => (ty, false), + }; + json!({"id": format!("x.{name}"), "name": name, "type": ty, "array": array, "optional": spec[1].as_bool().unwrap_or(true)}) + }) + .collect(); + let doc = match &self.policy { + Some((doc, _)) => doc.clone(), + None => json!({"blocks": [ + {"id": "dm", "type": "dataModel", "props": {"data": {"name": "x", "properties": properties}}}, + {"id": "t", "type": "decisionTable", "props": {"data": self.data("x.", "x.")}} + ]}), + }; + let mut ws = PolicyWorkspace::new(); + ws.set_policy("p", serde_json::from_value(doc).expect("policy")); + ws + } + + fn block(future: F) -> F::Output { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime") + .block_on(future) + } + + fn graph_result( + result: Result>, + ) -> String { + match result { + Ok(response) => response.result.to_string(), + Err(error) => format!( + "ERROR {}", + Self::error_kind(&serde_json::to_value(&*error).unwrap_or(Value::Null)) + ), + } + } + + fn error_kind(value: &Value) -> String { + value + .get("type") + .and_then(Value::as_str) + .unwrap_or("?") + .to_string() + } + + fn policy_result( + result: Result, + ) -> (String, String) { + match result { + Ok(result) => { + let trace = result + .trace + .as_ref() + .and_then(|t| t.executions.iter().find(|e| e.block_id.as_ref() == "t")) + .map(|e| { + serde_json::to_value(&e.trace) + .unwrap_or(Value::Null) + .to_string() + }) + .unwrap_or_default(); + let output = result.output.dot("x").unwrap_or(result.output); + (output.to_string(), trace) + } + Err(error) => { + let debug = format!("{error:?}"); + let kind = debug + .split(|c: char| !c.is_alphanumeric()) + .find(|s| !s.is_empty()) + .unwrap_or("?") + .to_string(); + let inner = debug + .split("source: ") + .nth(1) + .map(|s| { + s.split(|c: char| !c.is_alphanumeric()) + .find(|s| !s.is_empty()) + .unwrap_or("") + }) + .unwrap_or(""); + ( + format!( + "ERROR {kind}{}", + if inner.is_empty() { + String::new() + } else { + format!("/{inner}") + } + ), + String::new(), + ) + } + } + } + + fn run(&self, input: Value) -> Seen { + let decision = self.decision(); + let context = Variable::from(input.clone()); + let single = Self::graph_result(Self::block(decision.evaluate(context.depth_clone(64)))); + let batch = Self::block( + decision.evaluate_batch(&[context.depth_clone(64)], EvaluationOptions::default()), + ) + .into_iter() + .map(Self::graph_result) + .next() + .unwrap_or_default(); + let traced = Self::block(decision.evaluate_with_opts( + context.depth_clone(64), + EvaluationOptions { + trace: true, + max_depth: 10, + }, + )); + let graph_trace = match &traced { + Ok(response) => response + .trace + .as_ref() + .and_then(|t| t.as_graph()) + .and_then(|t| t.get("t")) + .map(|t| { + format!( + "output={} data={}", + t.output, + t.trace_data.clone().unwrap_or(Variable::Null) + ) + }) + .unwrap_or_default(), + Err(_) => String::new(), + }; + let mut graph = vec![ + ("single", single), + ("batch", batch), + ("traced", Self::graph_result(traced)), + ]; + #[cfg(feature = "driver")] + graph.push(( + "walker", + Self::graph_result(Self::block( + decision.interpreted().evaluate(context.depth_clone(64)), + )), + )); + + let ws = self.workspace(); + let policy_input = match &self.policy { + Some((_, input)) => input.clone(), + None => json!({"x": input}), + }; + let request = |trace: bool| EvaluateRequest { + policy_path: Arc::from("p"), + input: Variable::from(policy_input.clone()), + goals: Vec::new(), + trace, + }; + let (compiled, _) = Self::policy_result(ws.evaluate(&request(false))); + let (traced, policy_trace) = Self::policy_result(ws.evaluate(&request(true))); + let batch = Self::policy_result(ws.evaluate_batch(&[request(false)]).remove(0)).0; + let mut policy = vec![("compiled", compiled), ("batch", batch), ("traced", traced)]; + #[cfg(feature = "driver")] + policy.push(( + "driver", + Self::policy_result(ws.evaluate_with_driver(&request(false))).0, + )); + let rows = vec![policy_input.clone(); 2]; + let built = Built::new(&rows); + let columns = built.as_ref().map(|built| built.columns()); + let columns = columns + .as_ref() + .and_then(|columns| ws.evaluate_columns(&Arc::from("p"), &[], columns).ok()) + .map(|mut output| { + let text = match output.errors[0].take().map(std::rc::Rc::try_unwrap) { + Some(Ok(zen_engine::EvaluationError::Policy(error))) => { + Self::policy_result(Err(error)).0 + } + Some(other) => format!("{other:?}"), + None => output.row(0).dot("x").unwrap_or(output.row(0)).to_string(), + }; + (text, output.paths().hosted) + }); + Seen { + graph, + policy, + graph_trace, + policy_trace, + columns, + } + } +} + +#[test] +fn d01_first_hit_empty_output_cell_is_not_filled_by_later_rules_in_graph() { + let table = Table::new( + "first", + &[Some("n")], + &["a", "b"], + &[&["> 5", "'a0'", ""], &["> 0", "'a1'", "'b1'"]], + ); + table + .run(json!({"n": 6})) + .columnar() + .expect(r#"{"a":"a0"}"#, r#"{"n":6,"a":"a0","b":"b1"}"#); +} + +#[test] +fn d02_first_hit_no_match() { + let table = Table::new("first", &[Some("n")], &["a"], &[&["> 5", "1"]]); + table + .run(json!({"n": 1})) + .expect(r#"{}"#, r#"{"n":1,"a":null}"#); +} + +#[test] +fn d02b_first_hit_no_match_with_output_path() { + let table = Table::new("first", &[Some("n")], &["a"], &[&["> 5", "1"]]) + .with_attributes(json!({"outputPath": "res"})); + table + .run(json!({"n": 1})) + .expect(r#"{}"#, r#"{"n":1,"a":null}"#); +} + +#[test] +fn d03_collect_hit_policy_shape() { + let table = Table::new( + "collect", + &[Some("n")], + &["a", "b"], + &[ + &["> 5", "1", "'x'"], + &["> 0", "2", ""], + &["< 0", "3", "'z'"], + ], + ); + table.run(json!({"n": 6})).columnar().expect( + r#"[{"a":1,"b":"x"},{"a":2}]"#, + r#"{"n":6,"a":[1,2],"b":["x"]}"#, + ); +} + +#[test] +fn d04_collect_hit_policy_no_match() { + let table = Table::new("collect", &[Some("n")], &["a"], &[&["> 5", "1"]]); + table + .run(json!({"n": 1})) + .columnar() + .expect(r#"[]"#, r#"{"n":1,"a":[]}"#); +} + +#[test] +fn d05_column_collect_in_first_table() { + let table = Table::new( + "first", + &[Some("n")], + &["a", "b", "tags[]"], + &[ + &["> 5", "'a0'", "", "'t0'"], + &["> 0", "'a1'", "'b1'", "'t1'"], + ], + ); + table.run(json!({"n": 6})).columnar().expect( + r#"{"a":"a0","tags":["t0","t1"]}"#, + r#"{"n":6,"a":"a0","b":"b1","tags":["t0","t1"]}"#, + ); +} + +#[test] +fn d06_column_collect_no_match() { + let table = Table::new( + "first", + &[Some("n")], + &["a", "tags[]"], + &[&["> 5", "'a0'", "'t0'"]], + ); + table + .run(json!({"n": 1})) + .columnar() + .expect(r#"{"tags":[]}"#, r#"{"n":1,"a":null,"tags":[]}"#); +} + +#[test] +fn d07_column_suffix_under_collect_hit_policy() { + let table = Table::new( + "collect", + &[Some("n")], + &["a", "tags[]"], + &[&["> 5", "1", "'t0'"], &["> 0", "2", "'t1'"]], + ); + table.run(json!({"n": 6})).columnar().expect( + r#"[{"a":1,"tags":"t0"},{"a":2,"tags":"t1"}]"#, + r#"{"n":6,"a":[1,2],"tags":["t0","t1"]}"#, + ); +} + +#[test] +fn d08_input_cell_error() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["$ + 1 > 'x'", "1"], &["", "2"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":2}"#, "ERROR ExpressionFailed/VMError"); +} + +#[test] +fn d09_output_cell_error() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["> 5", "{p}n + 'x' > 1"], &["", "2"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":2}"#, "ERROR ExpressionFailed/VMError"); +} + +#[test] +fn d10_unary_cell_without_comparison_is_equality() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["$ + 1", "1"], &["", "2"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":2}"#, r#"{"n":6,"a":2}"#); +} + +#[test] +fn d11_fieldless_cell_non_boolean() { + let table = Table::new("first", &[None], &["a"], &[&["{p}n + 1", "1"], &["", "2"]]); + table + .run(json!({"n": 6})) + .expect(r#"{"a":2}"#, r#"{"n":6,"a":2}"#); +} + +#[test] +fn d12_dollar_in_output_cell() { + let table = Table::new("first", &[Some("n")], &["a"], &[&["> 0", "$"]]); + table + .run(json!({"n": 6})) + .expect(r#"{"a":6}"#, "ERROR MissingRequiredInputs"); +} + +#[test] +fn d13_null_and_absent_input() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["null", "'null'"], &["", "'any'"]], + ); + table + .run(json!({"n": null})) + .expect(r#"{"a":"null"}"#, r#"{"n":null,"a":"null"}"#); + table + .run(json!({})) + .expect(r#"{"a":"null"}"#, r#"{"a":"null"}"#); +} + +#[test] +fn d14_required_absent_input() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["null", "'null'"], &["", "'any'"]], + ) + .with_models(json!({"n": ["number", false]})); + table + .run(json!({})) + .expect(r#"{"a":"null"}"#, "ERROR MissingRequiredInputs"); +} + +#[test] +fn d15_nested_output_paths_and_order() { + let table = Table::new( + "first", + &[Some("n")], + &["r.b", "r.a", "s"], + &[&["> 5", "", "1", "2"], &["> 0", "3", "4", "5"]], + ); + table.run(json!({"n": 6})).expect( + r#"{"r":{"a":1},"s":2}"#, + r#"{"n":6,"r":{"a":1,"b":3},"s":2}"#, + ); +} + +#[test] +fn d16_scalar_parent_then_nested_child() { + let table = Table::new("first", &[Some("n")], &["r", "r.a"], &[&["> 0", "1", "2"]]); + table + .run(json!({"n": 6})) + .expect(r#"{"r":1}"#, r#"{"n":6,"r":1}"#); +} + +#[test] +fn d17_two_collect_columns_one_field() { + let table = Table::new( + "first", + &[Some("n")], + &["v[]", "v[]"], + &[&["> 0", "1", "'a'"], &["> 0", "2", "'b'"]], + ); + table + .run(json!({"n": 6})) + .columnar() + .expect(r#"{"v":[1,"a",2,"b"]}"#, r#"{"n":6,"v":[1,"a",2,"b"]}"#); +} + +#[test] +fn d18_duplicate_scalar_columns() { + let table = Table::new( + "first", + &[Some("n")], + &["v", "v"], + &[&["> 5", "", "1"], &["> 0", "2", "3"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"v":1}"#, r#"{"n":6,"v":2}"#); +} + +#[test] +fn d19_whitespace_cell() { + let table = Table::new("first", &[Some("n")], &["a"], &[&[" ", "1"], &["", "2"]]); + table + .run(json!({"n": 6})) + .expect(r#"{"a":1}"#, r#"{"n":6,"a":1}"#); +} + +#[test] +fn d20_unparsable_cell() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["> > 1", "1"], &["", "2"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":2}"#, "ERROR ExpressionFailed/ParserError"); +} + +#[test] +fn d21_number_scale() { + let table = Table::new( + "first", + &[Some("n")], + &["a", "b"], + &[&["1.0", "1.10", "{p}n * 1.00"]], + ); + table + .run(json!({"n": 1})) + .expect(r#"{"a":1.10,"b":1.00}"#, r#"{"n":1,"a":1.10,"b":1.00}"#); +} + +#[test] +fn d22_list_valued_input() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[ + &["'a'", "'eq'"], + &["contains($, 'b')", "'has b'"], + &["", "'other'"], + ], + ) + .with_models(json!({"n": ["string[]", true]})); + table + .run(json!({"n": ["a", "b"]})) + .expect(r#"{"a":"has b"}"#, r#"{"n":["a","b"],"a":"has b"}"#); +} + +#[test] +fn d23_date_input_coercion() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["> d('2024-01-01')", "'after'"], &["", "'other'"]], + ) + .with_models(json!({"n": ["date", true]})); + table + .run(json!({"n": "2025-01-01"})) + .expect(r#"{"a":"after"}"#, r#"{"n":2025-01-01,"a":"after"}"#); +} + +#[test] +fn d24_rule_with_no_outputs() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["> 5", ""], &["> 0", "1"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{}"#, r#"{"n":6,"a":1}"#); +} + +#[test] +fn d25_pass_through_no_match() { + let table = Table::new("first", &[Some("n")], &["a"], &[&["> 5", "1"]]) + .with_attributes(json!({"passThrough": true})); + table + .run(json!({"n": 1, "a": 9})) + .expect(r#"{"a":9,"n":1}"#, r#"{"a":null,"n":1}"#); +} + +#[test] +fn d26_loop_mode_vs_member_table() { + let doc = json!({"blocks": [ + {"id": "dm", "type": "dataModel", "props": {"data": {"name": "c", "properties": [ + {"id": "c.items", "name": "items", "type": "relationship", "target": "item", "array": true, "optional": false} + ]}}}, + {"id": "di", "type": "dataModel", "props": {"data": {"name": "item", "properties": [ + {"id": "item.n", "name": "n", "type": "number", "array": false, "optional": false} + ]}}}, + {"id": "t", "type": "decisionTable", "props": {"data": Table::new("first", &[Some("item.n")], &["item.a"], &[&["> 5", "1"]]).data("", "")}} + ]}); + let table = Table::new("first", &[Some("n")], &["a"], &[&["> 5", "1"]]) + .with_attributes(json!({"executionMode": "loop", "inputField": "items", "outputPath": "items", "passThrough": true})) + .with_policy(doc, json!({"c": {"items": [{"n": 6}, {"n": 1}]}})); + table.run(json!({"items": [{"n": 6}, {"n": 1}]})).expect( + r#"{"items":[{"n":6,"a":1},{"n":1}]}"#, + r#"{"c":{"items":[{"n":6,"a":1},{"n":1,"a":null}]}}"#, + ); +} + +#[test] +fn d27_input_field_expression_error() { + let table = Table::new( + "first", + &[Some("n + 'x' > 1")], + &["a"], + &[&["true", "1"], &["", "2"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":2}"#, "ERROR ExpressionFailed/VMError"); +} + +#[test] +fn d28_collect_output_error() { + let table = Table::new( + "first", + &[Some("n")], + &["a", "v[]"], + &[&["> 0", "1", "{p}n + 'x' > 1"], &["> 0", "2", "'ok'"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":2,"v":["ok"]}"#, "ERROR ExpressionFailed/VMError"); +} + +#[test] +fn d29_no_rules() { + let table = Table::new("first", &[Some("n")], &["a", "v[]"], &[]); + table + .run(json!({"n": 6})) + .expect(r#"{"v":[]}"#, r#"{"n":6,"a":null,"v":[]}"#); +} + +#[test] +fn d30_existing_input_value_at_output_path() { + let table = Table::new("first", &[Some("n")], &["a"], &[&["> 5", "1"]]); + table + .run(json!({"n": 1, "a": 9})) + .expect(r#"{}"#, r#"{"a":null,"n":1}"#); +} + +#[test] +fn d31_write_order_of_outputs_filled_by_different_rules() { + let table = Table::new( + "first", + &[Some("n")], + &["a", "b"], + &[&["> 5", "", "'b0'"], &["> 0", "'a1'", "'b1'"]], + ); + table + .run(json!({"n": 6})) + .columnar() + .expect(r#"{"b":"b0"}"#, r#"{"n":6,"b":"b0","a":"a1"}"#); +} + +#[test] +fn d32_policy_keeps_scanning_rows_after_the_first_match() { + let table = Table::new( + "first", + &[Some("n")], + &["a", "b"], + &[ + &["> 5", "'a0'", ""], + &["$ + 'x' > 1", "'a1'", "'b1'"], + &["", "", "'b2'"], + ], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":"a0"}"#, "ERROR ExpressionFailed/VMError"); +} + +#[test] +fn d33_policy_stops_once_every_scalar_is_resolved() { + let table = Table::new( + "first", + &[Some("n")], + &["a"], + &[&["> 5", "'a0'"], &["$ + 'x' > 1", "'a1'"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":"a0"}"#, r#"{"n":6,"a":"a0"}"#); +} + +#[test] +fn d34_collect_values_with_empty_cells_and_nulls() { + let table = Table::new( + "collect", + &[Some("n")], + &["a", "b"], + &[&["> 0", "null", ""], &["> 0", "", "1"]], + ); + table + .run(json!({"n": 6})) + .columnar() + .expect(r#"[{"a":null},{"b":1}]"#, r#"{"n":6,"a":[null],"b":[1]}"#); +} + +#[test] +fn d35_first_collect_first_rule_scalar_error_drops_the_rule() { + let table = Table::new( + "first", + &[Some("n")], + &["a", "v[]"], + &[&["> 0", "{p}n + 'x' > 1", "1"], &["> 0", "'a1'", "2"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a":"a1","v":[2]}"#, "ERROR ExpressionFailed/VMError"); +} + +#[test] +fn d36_first_collect_only_collect_columns_and_no_match() { + let table = Table::new("first", &[Some("n")], &["v[]"], &[&["> 5", "1"]]) + .with_attributes(json!({"outputPath": "res"})); + table + .run(json!({"n": 1})) + .expect(r#"{"res":{"v":[]}}"#, r#"{"n":1,"v":[]}"#); +} + +#[test] +fn d37_collect_marker_inside_a_path() { + let table = Table::new( + "first", + &[Some("n")], + &["a[].b", "c"], + &[&["> 0", "1", "2"]], + ); + table + .run(json!({"n": 6})) + .expect(r#"{"a[]":{"b":1},"c":2}"#, r#"{"n":6,"c":2}"#); +} + +#[test] +fn d38_dotted_collect_path_and_scalar_sibling() { + let table = Table::new( + "first", + &[Some("n")], + &["r.s", "r.v[]"], + &[&["> 5", "'big'", "1"], &["> 0", "'small'", "2"]], + ); + table.run(json!({"n": 6})).columnar().expect( + r#"{"r":{"s":"big","v":[1,2]}}"#, + r#"{"n":6,"r":{"s":"big","v":[1,2]}}"#, + ); +} diff --git a/core/engine/tests/verify.rs b/core/engine/tests/verify.rs new file mode 100644 index 00000000..3c2cef1c --- /dev/null +++ b/core/engine/tests/verify.rs @@ -0,0 +1,425 @@ +#![cfg(feature = "driver")] +#[allow(dead_code)] +mod support; + +use serde_json::{json, Value}; +use std::sync::Arc; +use support::columns::Built; +use zen_engine::model::GraphContent; +use zen_engine::policy::{EvaluateRequest, EvaluationResult, PolicyWorkspace}; +use zen_engine::{Decision, DecisionGraphResponse, EvaluationError, EvaluationOptions}; +use zen_expression::Variable; + +struct Graphs; + +impl Graphs { + fn chain(nodes: Vec) -> Value { + let mut all = vec![json!({ "id": "in", "name": "in", "type": "inputNode" })]; + all.extend(nodes); + all.push(json!({ "id": "out", "name": "out", "type": "outputNode" })); + let edges: Vec = all + .windows(2) + .enumerate() + .map(|(i, w)| json!({ "id": format!("e{i}"), "type": "edge", "sourceId": w[0]["id"], "targetId": w[1]["id"] })) + .collect(); + json!({ "nodes": all, "edges": edges }) + } + + fn expression(id: &str, pairs: &[(&str, &str)]) -> Value { + let expressions: Vec = pairs + .iter() + .enumerate() + .map(|(i, (key, value))| json!({ "id": format!("{id}-{i}"), "key": key, "value": value })) + .collect(); + json!({ "id": id, "name": id, "type": "expressionNode", "content": { "expressions": expressions, "passThrough": true } }) + } + + fn table(id: &str, outputs: &[(&str, &str)]) -> Value { + let columns: Vec = outputs + .iter() + .enumerate() + .map(|(i, (field, _))| json!({ "id": format!("o{i}"), "name": field, "field": field, "type": "expression" })) + .collect(); + let mut rule = serde_json::Map::new(); + rule.insert("_id".into(), json!("r1")); + rule.insert("i1".into(), json!("")); + for (i, (_, cell)) in outputs.iter().enumerate() { + rule.insert(format!("o{i}"), json!(cell)); + } + json!({ "id": id, "name": id, "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": [ { "id": "i1", "name": "x", "field": "x", "type": "expression" } ], + "outputs": columns, + "rules": [ Value::Object(rule) ], + "passThrough": true + } }) + } + + fn content(graph: &Value) -> GraphContent { + serde_json::from_value(graph.clone()).unwrap() + } + + fn decision(graph: &Value) -> Decision { + Decision::from(Arc::new(Self::content(graph))) + } + + fn text(result: Result>) -> String { + match result { + Ok(response) => serde_json::to_string(&response.result).unwrap(), + Err(error) => format!("ERR {error}"), + } + } + + fn unchanged(first: &str, second: &str) -> Vec { + let fields = |text: &str| match serde_json::from_str::(text) { + Ok(Value::Object(map)) => map.into_iter().filter(|(key, _)| key != "x").collect(), + _ => serde_json::Map::from_iter([("?".to_string(), Value::from(text))]), + }; + let second = fields(second); + fields(first) + .into_iter() + .filter(|(key, value)| second.get(key) == Some(value)) + .map(|(key, _)| key) + .collect() + } +} + +struct Stripped; + +impl Stripped { + const SOURCE: &'static str = + "export const handler = (input: { x: number }) => ({ via: 'strip' });"; + const CACHED: &'static str = "export const handler = (input) => ({ via: 'cache' });"; + + fn graph() -> Value { + Graphs::chain(vec![ + json!({ "id": "f", "name": "f", "type": "functionNode", "content": { "source": Self::SOURCE } }), + ]) + } + + fn primed() -> GraphContent { + let mut content = Graphs::content(&Self::graph()); + content.compile(); + let stripped: ahash::HashMap, Arc> = + [(Arc::from(Self::SOURCE), Arc::from(Self::CACHED))] + .into_iter() + .collect(); + content.stripped_functions = Some(Arc::new(stripped)); + content + } +} + +struct Policies; + +impl Policies { + fn workspace(doc: Value) -> PolicyWorkspace { + let mut ws = PolicyWorkspace::new(); + ws.set_policy("p", serde_json::from_value(doc).unwrap()); + ws + } + + fn request(input: &Value, trace: bool) -> EvaluateRequest { + EvaluateRequest { + policy_path: Arc::from("p"), + input: Variable::from(input.clone()), + goals: Vec::new(), + trace, + } + } + + fn text(result: Result) -> String { + match result { + Ok(result) => serde_json::to_string(&result.output).unwrap(), + Err(error) => format!("ERR {error:?}"), + } + } + + fn columnar( + ws: &PolicyWorkspace, + columns: &zen_expression::lane::Columns, + rows: usize, + ) -> Vec { + let output = ws.evaluate_columns(&Arc::from("p"), &[], columns).unwrap(); + (0..rows) + .map(|row| match &output.errors[row] { + Some(error) => format!("ERR {error:?}"), + None => serde_json::to_string(&output.row(row)).unwrap(), + }) + .collect() + } + + fn mismatches(label: &str, doc: Value, inputs: &[Value]) -> Vec { + let ws = Self::workspace(doc); + let driver: Vec = inputs + .iter() + .map(|input| Self::text(ws.evaluate_with_driver(&Self::request(input, false)))) + .collect(); + let single = inputs + .iter() + .map(|input| Self::text(ws.evaluate(&Self::request(input, false)))) + .collect(); + let requests: Vec = inputs + .iter() + .map(|input| Self::request(input, false)) + .collect(); + let batch = ws + .evaluate_batch(&requests) + .into_iter() + .map(Self::text) + .collect(); + let columns = match Built::nested(inputs) { + Some(built) => { + let fields = built.fields(); + let structs = built.structs(&fields); + Self::columnar(&ws, &built.columns_with(&structs), inputs.len()) + } + None => Self::columnar(&ws, &Built::new(inputs).unwrap().columns(), inputs.len()), + }; + [("single", single), ("batch", batch), ("columns", columns)] + .into_iter() + .flat_map(|(path, got): (&str, Vec)| { + driver + .iter() + .zip(got) + .enumerate() + .filter(|(_, (want, got))| *want != got) + .map(move |(row, (want, got))| { + format!("{label} {path} row {row}:\n driver {want}\n {path} {got}") + }) + .collect::>() + }) + .collect() + } +} + +#[tokio::test] +async fn compiled_table_cells_reread_the_clock() { + assert!(std::env::var("__ZEN_MOCK_UTC_TIME").is_err()); + let graph = Graphs::chain(vec![ + Graphs::expression( + "ex", + &[ + ("second", "startOf('now', 'second')"), + ("end", "endOf('now', 'second')"), + ], + ), + Graphs::table( + "dt", + &[ + ("cell", "startOf('now', 'second')"), + ("cellEnd", "endOf('now', 'second')"), + ], + ), + ]); + let input = json!({ "x": 1 }); + let walker = Graphs::decision(&graph).interpreted(); + let single = Graphs::decision(&graph); + let batch = Graphs::decision(&graph); + let mut compiled = Graphs::decision(&graph); + compiled.compile(); + let contexts = [Variable::from(input.clone()), Variable::from(input.clone())]; + let built = Built::new(&[input.clone(), input.clone()]).unwrap(); + let columns = built.columns(); + let first = |results: Vec>>| { + results.into_iter().map(Graphs::text).next().unwrap() + }; + let run = || async { + let columnar = compiled + .evaluate_columns(&columns, EvaluationOptions::default()) + .await; + [ + ( + "walker", + Graphs::text(walker.evaluate(Variable::from(input.clone())).await), + ), + ( + "single", + Graphs::text(single.evaluate(Variable::from(input.clone())).await), + ), + ( + "batch", + first( + batch + .evaluate_batch(&contexts, EvaluationOptions::default()) + .await, + ), + ), + ( + "compiled-single", + Graphs::text(compiled.evaluate(Variable::from(input.clone())).await), + ), + ( + "compiled-batch", + first( + compiled + .evaluate_batch(&contexts, EvaluationOptions::default()) + .await, + ), + ), + ("columnar", serde_json::to_string(&columnar.row(0)).unwrap()), + ] + }; + let before = run().await; + std::thread::sleep(std::time::Duration::from_millis(1100)); + let after = run().await; + let stale: Vec = before + .iter() + .zip(&after) + .filter_map(|((path, a), (_, b))| { + let unchanged = Graphs::unchanged(a, b); + (!unchanged.is_empty()).then(|| format!("{path}: {unchanged:?}")) + }) + .collect(); + assert!(stale.is_empty(), "values frozen at compile time: {stale:?}"); +} + +#[test] +fn policy_columnar_keeps_negative_zero() { + let doc = json!({ "blocks": [ + { "id": "dm", "type": "dataModel", "props": { "data": { + "name": "order", + "properties": [ + { "id": "p1", "name": "amount", "type": "number", "array": false, "optional": false }, + { "id": "p2", "name": "items", "type": "number", "array": true, "optional": false } + ] + } } }, + { "id": "e1", "type": "expression", "props": { "data": { "key": "order.neg", "value": "-order.amount" } } }, + { "id": "e2", "type": "expression", "props": { "data": { "key": "order.list", "value": "map(order.items, -#)" } } }, + { "id": "m", "type": "match", "props": { "data": { "key": "order.matched", "arms": [ + { "id": "a1", "condition": "order.amount > 5", "value": "1" }, + { "id": "a2", "condition": "", "value": "-0" } + ] } } }, + { "id": "dt", "type": "decisionTable", "props": { "data": { + "inputs": [ { "id": "i1", "name": "", "field": "order.amount" } ], + "outputs": [ { "id": "o1", "name": "", "field": "order.tneg" }, { "id": "o2", "name": "", "field": "order.tags[]" } ], + "rules": [ { "i1": "", "o1": "-order.amount", "o2": "-order.amount" } ] + } } }, + { "id": "s1", "type": "expression", "props": { "data": { "key": "order.sneg", "value": "string(order.neg)" } } }, + { "id": "s2", "type": "expression", "props": { "data": { "key": "order.slist", "value": "map(order.list, string(#))" } } }, + { "id": "s3", "type": "expression", "props": { "data": { "key": "order.smatched", "value": "string(order.matched)" } } }, + { "id": "s4", "type": "expression", "props": { "data": { "key": "order.stneg", "value": "string(order.tneg)" } } }, + { "id": "s5", "type": "expression", "props": { "data": { "key": "order.stags", "value": "map(order.tags, string(#))" } } } + ] }); + let inputs = [ + json!({ "order": { "amount": 0, "items": [0, 2] } }), + json!({ "order": { "amount": 0, "items": [0] } }), + json!({ "order": { "amount": 7, "items": [1] } }), + ]; + let mismatches = Policies::mismatches("negative zero", doc, &inputs); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[test] +fn policy_columnar_entities_keep_field_order() { + let inputs = [ + json!({ "customer": { "companies": [ { "revenue": 5 }, { "revenue": 50 } ] } }), + json!({ "customer": { "companies": [ { "revenue": 20 } ] } }), + ]; + let mismatches: Vec = [false, true] + .into_iter() + .flat_map(|nested| { + let mut blocks = vec![ + json!({ "id": "dm-customer", "type": "dataModel", "props": { "data": { + "name": "customer", + "properties": [ { "id": "p1", "name": "companies", "type": "relationship", "target": "company", "array": true, "optional": false } ] + } } }), + json!({ "id": "dm-company", "type": "dataModel", "props": { "data": { + "name": "company", + "properties": [ { "id": "p2", "name": "revenue", "type": "number", "array": false, "optional": false } ] + } } }), + json!({ "id": "e1", "type": "expression", "props": { "data": { "key": "company.meta.big", "value": "company.revenue > 10" } } }), + json!({ "id": "e2", "type": "expression", "props": { "data": { "key": "company.flag", "value": "company.meta.big ? 'y' : 'n'" } } }), + json!({ "id": "k1", "type": "expression", "props": { "data": { "key": "customer.keys", "value": "map(customer.companies, keys(#))" } } }), + ]; + if nested { + blocks.push(json!({ "id": "e3", "type": "expression", "props": { "data": { "key": "customer.info.count", "value": "len(customer.companies)" } } })); + blocks.push(json!({ "id": "e4", "type": "expression", "props": { "data": { "key": "customer.info.first", "value": "customer.info.count > 0" } } })); + } + Policies::mismatches(&format!("key order nested={nested}"), json!({ "blocks": blocks }), &inputs) + }) + .collect(); + assert!(mismatches.is_empty(), "{}", mismatches.join("\n")); +} + +#[test] +fn policy_driver_collects_in_output_order() { + let ws = Policies::workspace(json!({ "blocks": [ + { "id": "dm", "type": "dataModel", "props": { "data": { + "name": "order", + "properties": [ { "id": "p1", "name": "amount", "type": "number", "array": false, "optional": false } ] + } } }, + { "id": "dt", "type": "decisionTable", "props": { "data": { + "inputs": [ { "id": "i1", "name": "", "field": "order.amount" } ], + "outputs": [ + { "id": "o1", "name": "", "field": "order.a[]" }, + { "id": "o2", "name": "", "field": "order.b[]" }, + { "id": "o3", "name": "", "field": "order.c[]" }, + { "id": "o4", "name": "", "field": "order.d[]" }, + { "id": "o5", "name": "", "field": "order.e[]" } + ], + "rules": [ { "i1": "", "o1": "1", "o2": "2", "o3": "3", "o4": "4", "o5": "5" } ] + } } } + ] })); + let request = Policies::request(&json!({ "order": { "amount": 1 } }), true); + let writes = |result: EvaluationResult| -> Vec { + result + .trace + .map(|trace| { + trace + .executions + .iter() + .flat_map(|execution| { + execution.writes.iter().map(|write| write.path.to_string()) + }) + .collect() + }) + .unwrap_or_default() + }; + let output = Policies::text(ws.evaluate(&request)); + let log = writes(ws.enhance_trace(&request).unwrap()); + assert_eq!(log, ["order.a", "order.b", "order.c", "order.d", "order.e"]); + for run in 0..32 { + assert_eq!( + Policies::text(ws.evaluate_with_driver(&request)), + output, + "run {run}: driver output order" + ); + assert_eq!( + writes(ws.enhance_trace_with_driver(&request).unwrap()), + log, + "run {run}: driver write log order" + ); + } +} + +#[tokio::test] +async fn sub_decisions_reuse_stripped_functions() { + let loader = Arc::new(zen_engine::loader::MemoryLoader::default()); + loader.add("child", Stripped::primed()); + let graph = Graphs::chain(vec![ + json!({ "id": "d", "name": "d", "type": "decisionNode", "content": { "key": "child" } }), + ]); + let mut parent = Graphs::decision(&graph).with_loader(loader); + parent.compile(); + let input = Variable::from(json!({ "x": 1 })); + let top = Graphs::text( + Decision::from(Arc::new(Stripped::primed())) + .evaluate(input.clone()) + .await, + ); + assert!( + top.contains("cache"), + "top-level function must use the stripped cache: {top}" + ); + let single = Graphs::text(parent.evaluate(input.clone()).await); + let batch: Vec = parent + .evaluate_batch(&[input.clone(), input], EvaluationOptions::default()) + .await + .into_iter() + .map(Graphs::text) + .collect(); + assert!( + single.contains("cache") && batch.iter().all(|row| row.contains("cache")), + "sub-decision re-stripped the source: single {single} batch {batch:?}" + ); +} diff --git a/core/engine/tests/workspace_graph.rs b/core/engine/tests/workspace_graph.rs index 926d6791..cdaf5525 100644 --- a/core/engine/tests/workspace_graph.rs +++ b/core/engine/tests/workspace_graph.rs @@ -485,6 +485,43 @@ fn decision_table_invalid_collect_marker_is_reported() { ); } +#[test] +fn decision_table_collect_marker_under_collect_hit_policy_is_reported() { + let mut ws = Workspace::new(); + let table = node( + "dt", + "decisionTableNode", + json!({ + "hitPolicy": "collect", + "inputs": [ + { "id": "c1", "name": "Age", "field": "age" } + ], + "outputs": [ + { "id": "o1", "name": "Tags", "field": "tags[]" }, + { "id": "o2", "name": "Plain", "field": "plain" } + ], + "rules": [ + { "_id": "r1", "c1": "", "o1": "1", "o2": "2" } + ] + }), + ); + ws.set_document( + "g", + document(linear_graph(Some(person_schema()), vec![table])), + ); + let warnings: Vec<_> = ws + .diagnostics("g") + .into_iter() + .filter(|d| d.severity == Severity::Warning && d.code == DiagnosticCode::InvalidWritePath) + .collect(); + assert_eq!( + warnings.len(), + 1, + "expected one collect marker warning, got {warnings:?}" + ); + assert!(error_codes(&ws, "g").is_empty()); +} + #[test] fn transform_loop_iterates_elements() { let mut ws = Workspace::new(); diff --git a/core/engine/tests/workspace_graph_dictionary.rs b/core/engine/tests/workspace_graph_dictionary.rs index ea2c49d8..2629f0ac 100644 --- a/core/engine/tests/workspace_graph_dictionary.rs +++ b/core/engine/tests/workspace_graph_dictionary.rs @@ -377,11 +377,8 @@ async fn runtime_validates_dictionary_membership() { assert!(ok.is_ok(), "{ok:?}"); let bad = engine.evaluate("g", json!({ "tier": "GOLD" }).into()).await; - let message = format!("{:?}", bad.expect_err("must fail validation")); - assert!( - message.contains("Validation") || message.to_lowercase().contains("enum"), - "{message}" - ); + let message = bad.expect_err("must fail validation").to_string(); + assert!(message.contains("is not one of"), "{message}"); } #[tokio::test] @@ -407,3 +404,65 @@ async fn runtime_errors_on_unknown_schema_dictionary() { "{message}" ); } + +#[cfg(feature = "driver")] +#[tokio::test] +async fn unresolved_dictionaries_resolve_per_evaluation_like_the_walker() { + use zen_engine::loader::MemoryLoader; + use zen_engine::{Decision, EvaluationOptions}; + + let loader = Arc::new(MemoryLoader::default()); + loader.add( + "dicts", + document(dictionary_policy( + &[], + "customerTier", + &[("VIP", "Very important"), ("STD", "Standard")], + )), + ); + let tier = json!({ "$dictionary": "customerTier" }); + let unknown = + json!({ "type": "object", "properties": { "tier": { "$dictionary": "missingTier" } } }); + let graphs = [ + schema_graph( + &["dicts"], + tier.clone(), + Some(json!({ "type": "object", "properties": { "tier": tier.clone() } })), + ), + schema_graph(&[], tier.clone(), None), + schema_graph(&["dicts"], tier.clone(), Some(unknown.clone())), + schema_graph(&["absent"], tier.clone(), None), + schema_graph(&["dicts"], json!({ "type": "string" }), Some(unknown)), + ]; + let inputs = [ + json!({ "tier": "VIP" }), + json!({ "tier": "GOLD" }), + json!({}), + json!({ "tier": 1 }), + ]; + for graph in graphs { + let DecisionContent::Graph(content) = document(graph) else { + panic!("graph content"); + }; + let decision = Decision::from(content).with_loader(loader.clone()); + let walker = decision.interpreted(); + let contexts: Vec = + inputs.iter().map(|i| i.clone().into()).collect(); + let batch = decision + .evaluate_batch(&contexts, EvaluationOptions::default()) + .await; + for (input, batched) in contexts.iter().zip(batch) { + let want = walker.evaluate(input.clone()).await; + let got = decision.evaluate(input.clone()).await; + let describe = |r: &Result< + zen_engine::DecisionGraphResponse, + Box, + >| match r { + Ok(response) => format!("ok {}", response.result.to_value()), + Err(error) => format!("err {error} {}", serde_json::to_value(&**error).unwrap()), + }; + assert_eq!(describe(&want), describe(&got), "{input:?}"); + assert_eq!(describe(&want), describe(&batched), "{input:?}"); + } + } +} diff --git a/core/engine/tests/workspace_graph_enhance.rs b/core/engine/tests/workspace_graph_enhance.rs index 24981ab2..1b2d2499 100644 --- a/core/engine/tests/workspace_graph_enhance.rs +++ b/core/engine/tests/workspace_graph_enhance.rs @@ -77,14 +77,57 @@ async fn graph_trace(documents: &[(&str, Value)], entry: &str, input: Value) -> .expect("graph trace") } +#[cfg(feature = "driver")] +async fn walker_trace(documents: &[(&str, Value)], entry: &str, input: Value) -> GraphTraceMap { + let loader = Arc::new(MemoryLoader::default()); + for (key, value) in documents { + loader.add(*key, document(value.clone())); + } + let content = documents + .iter() + .find(|(key, _)| *key == entry) + .and_then(|(_, value)| document(value.clone()).as_graph().cloned()) + .expect("entry graph"); + let walker = zen_engine::Decision::from(content) + .with_loader(loader) + .interpreted(); + walker + .evaluate_with_opts( + input.into(), + EvaluationOptions { + trace: true, + max_depth: 10, + }, + ) + .await + .expect("walker evaluation succeeds") + .trace + .and_then(|trace| trace.into_graph()) + .expect("walker graph trace") +} + async fn enhance(documents: &[(&str, Value)], entry: &str, input: Value) -> Trace { let trace = graph_trace(documents, entry, input.clone()).await; let mut ws = Workspace::new(); for (key, value) in documents { ws.set_document(*key, document(value.clone())); } - ws.enhance_graph_trace(&Arc::from(entry), &trace) - .expect("enhance succeeds") + let enhanced = ws + .enhance_graph_trace(&Arc::from(entry), &trace) + .expect("enhance succeeds"); + #[cfg(feature = "driver")] + { + let walker = walker_trace(documents, entry, input).await; + let reference = ws + .enhance_graph_trace(&Arc::from(entry), &walker) + .expect("walker enhance succeeds"); + assert_eq!( + serde_json::to_value(&reference).expect("walker trace json"), + serde_json::to_value(&enhanced).expect("trace json"), + "enhanced trace differs from the walker's" + ); + } + enhanced } fn execution<'a>(trace: &'a Trace, block_id: &str) -> &'a BlockExecution {